Change the signatures of the destroyFile and destroyDirectory methods to
[oota-llvm.git] / lib / System / Win32 / Path.cpp
1 //===- llvm/System/Linux/Path.cpp - Linux Path Implementation ---*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Reid Spencer and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 // Modified by Henrik Bach to comply with at least MinGW.
9 // Ported to Win32 by Jeff Cohen.
10 //
11 //===----------------------------------------------------------------------===//
12 //
13 // This file provides the Win32 specific implementation of the Path class.
14 //
15 //===----------------------------------------------------------------------===//
16
17 //===----------------------------------------------------------------------===//
18 //=== WARNING: Implementation here must contain only generic Win32 code that
19 //===          is guaranteed to work on *all* Win32 variants.
20 //===----------------------------------------------------------------------===//
21
22 #include "Win32.h"
23 #include <fstream>
24 #include <malloc.h>
25
26 static void FlipBackSlashes(std::string& s) {
27   for (size_t i = 0; i < s.size(); i++)
28     if (s[i] == '\\')
29       s[i] = '/';
30 }
31
32 namespace llvm {
33 namespace sys {
34
35 bool
36 Path::isValid() const {
37   if (path.empty())
38     return false;
39
40   // If there is a colon, it must be the second character, preceded by a letter
41   // and followed by something.
42   size_t len = path.size();
43   size_t pos = path.rfind(':',len);
44   if (pos != std::string::npos) {
45     if (pos != 1 || !isalpha(path[0]) || len < 3)
46       return false;
47   }
48
49   // Check for illegal characters.
50   if (path.find_first_of("\\<>\"|\001\002\003\004\005\006\007\010\011\012"
51                          "\013\014\015\016\017\020\021\022\023\024\025\026"
52                          "\027\030\031\032\033\034\035\036\037")
53       != std::string::npos)
54     return false;
55
56   // A file or directory name may not end in a period.
57   if (path[len-1] == '.')
58     return false;
59   if (len >= 2 && path[len-2] == '.' && path[len-1] == '/')
60     return false;
61
62   // A file or directory name may not end in a space.
63   if (path[len-1] == ' ')
64     return false;
65   if (len >= 2 && path[len-2] == ' ' && path[len-1] == '/')
66     return false;
67
68   return true;
69 }
70
71 static Path *TempDirectory = NULL;
72
73 Path
74 Path::GetTemporaryDirectory() {
75   if (TempDirectory)
76     return *TempDirectory;
77
78   char pathname[MAX_PATH];
79   if (!GetTempPath(MAX_PATH, pathname))
80     throw std::string("Can't determine temporary directory");
81
82   Path result;
83   result.setDirectory(pathname);
84
85   // Append a subdirectory passed on our process id so multiple LLVMs don't
86   // step on each other's toes.
87   sprintf(pathname, "LLVM_%u", GetCurrentProcessId());
88   result.appendDirectory(pathname);
89
90   // If there's a directory left over from a previous LLVM execution that
91   // happened to have the same process id, get rid of it.
92   result.destroyDirectory(true);
93
94   // And finally (re-)create the empty directory.
95   result.createDirectory(false);
96   TempDirectory = new Path(result);
97   return *TempDirectory;
98 }
99
100 Path::Path(const std::string& unverified_path)
101   : path(unverified_path)
102 {
103   FlipBackSlashes(path);
104   if (unverified_path.empty())
105     return;
106   if (this->isValid())
107     return;
108   // oops, not valid.
109   path.clear();
110   throw std::string(unverified_path + ": path is not valid");
111 }
112
113 // FIXME: the following set of functions don't map to Windows very well.
114 Path
115 Path::GetRootDirectory() {
116   Path result;
117   result.setDirectory("/");
118   return result;
119 }
120
121 static void getPathList(const char*path, std::vector<sys::Path>& Paths) {
122   const char* at = path;
123   const char* delim = strchr(at, ';');
124   Path tmpPath;
125   while( delim != 0 ) {
126     std::string tmp(at, size_t(delim-at));
127     if (tmpPath.setDirectory(tmp))
128       if (tmpPath.readable())
129         Paths.push_back(tmpPath);
130     at = delim + 1;
131     delim = strchr(at, ';');
132   }
133   if (*at != 0)
134     if (tmpPath.setDirectory(std::string(at)))
135       if (tmpPath.readable())
136         Paths.push_back(tmpPath);
137
138 }
139
140 void 
141 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
142 #ifdef LTDL_SHLIBPATH_VAR
143   char* env_var = getenv(LTDL_SHLIBPATH_VAR);
144   if (env_var != 0) {
145     getPathList(env_var,Paths);
146   }
147 #endif
148   // FIXME: Should this look at LD_LIBRARY_PATH too?
149   Paths.push_back(sys::Path("C:\\WINDOWS\\SYSTEM32\\"));
150   Paths.push_back(sys::Path("C:\\WINDOWS\\"));
151 }
152
153 void
154 Path::GetBytecodeLibraryPaths(std::vector<sys::Path>& Paths) {
155   char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
156   if (env_var != 0) {
157     getPathList(env_var,Paths);
158   }
159 #ifdef LLVM_LIBDIR
160   {
161     Path tmpPath;
162     if (tmpPath.setDirectory(LLVM_LIBDIR))
163       if (tmpPath.readable())
164         Paths.push_back(tmpPath);
165   }
166 #endif
167   GetSystemLibraryPaths(Paths);
168 }
169
170 Path
171 Path::GetLLVMDefaultConfigDir() {
172   return Path("/etc/llvm/");
173 }
174
175 Path
176 Path::GetUserHomeDirectory() {
177   const char* home = getenv("HOME");
178   if (home) {
179     Path result;
180     if (result.setDirectory(home))
181       return result;
182   }
183   return GetRootDirectory();
184 }
185 // FIXME: the above set of functions don't map to Windows very well.
186
187 bool
188 Path::isFile() const {
189   return (isValid() && path[path.length()-1] != '/');
190 }
191
192 bool
193 Path::isDirectory() const {
194   return (isValid() && path[path.length()-1] == '/');
195 }
196
197 std::string
198 Path::getBasename() const {
199   // Find the last slash
200   size_t slash = path.rfind('/');
201   if (slash == std::string::npos)
202     slash = 0;
203   else
204     slash++;
205
206   return path.substr(slash, path.rfind('.'));
207 }
208
209 bool Path::hasMagicNumber(const std::string &Magic) const {
210   size_t len = Magic.size();
211   char *buf = reinterpret_cast<char *>(_alloca(len+1));
212   std::ifstream f(path.c_str());
213   f.read(buf, len);
214   buf[len] = '\0';
215   return Magic == buf;
216 }
217
218 bool 
219 Path::isBytecodeFile() const {
220   char buffer[ 4];
221   buffer[0] = 0;
222   std::ifstream f(path.c_str());
223   f.read(buffer, 4);
224   if (f.bad())
225     ThrowErrno("can't read file signature");
226   return 0 == memcmp(buffer,"llvc",4) || 0 == memcmp(buffer,"llvm",4);
227 }
228
229 bool
230 Path::exists() const {
231   DWORD attr = GetFileAttributes(path.c_str());
232   return attr != INVALID_FILE_ATTRIBUTES;
233 }
234
235 bool
236 Path::readable() const {
237   // FIXME: take security attributes into account.
238   DWORD attr = GetFileAttributes(path.c_str());
239   return attr != INVALID_FILE_ATTRIBUTES;
240 }
241
242 bool
243 Path::writable() const {
244   // FIXME: take security attributes into account.
245   DWORD attr = GetFileAttributes(path.c_str());
246   return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
247 }
248
249 bool
250 Path::executable() const {
251   // FIXME: take security attributes into account.
252   DWORD attr = GetFileAttributes(path.c_str());
253   return attr != INVALID_FILE_ATTRIBUTES;
254 }
255
256 std::string
257 Path::getLast() const {
258   // Find the last slash
259   size_t pos = path.rfind('/');
260
261   // Handle the corner cases
262   if (pos == std::string::npos)
263     return path;
264
265   // If the last character is a slash
266   if (pos == path.length()-1) {
267     // Find the second to last slash
268     size_t pos2 = path.rfind('/', pos-1);
269     if (pos2 == std::string::npos)
270       return path.substr(0,pos);
271     else
272       return path.substr(pos2+1,pos-pos2-1);
273   }
274   // Return everything after the last slash
275   return path.substr(pos+1);
276 }
277
278 void
279 Path::getStatusInfo(StatusInfo& info) const {
280   WIN32_FILE_ATTRIBUTE_DATA fi;
281   if (!GetFileAttributesEx(path.c_str(), GetFileExInfoStandard, &fi))
282     ThrowError(std::string(path) + ": Can't get status: ");
283
284   info.fileSize = fi.nFileSizeHigh;
285   info.fileSize <<= 32;
286   info.fileSize += fi.nFileSizeLow;
287
288   info.mode = 0777;    // Not applicable to Windows, so...
289   info.user = 9999;    // Not applicable to Windows, so...
290   info.group = 9999;   // Not applicable to Windows, so...
291
292   __int64 ft = *reinterpret_cast<__int64*>(&fi.ftLastWriteTime);
293   info.modTime.fromWin32Time(ft);
294
295   info.isDir = fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
296   if (info.isDir && path[path.length() - 1] != '/')
297     path += '/';
298   else if (!info.isDir && path[path.length() - 1] == '/')
299     path.erase(path.length() - 1);
300 }
301
302 void Path::makeReadable() {
303   // All files are readable on Windows (ignoring security attributes).
304 }
305
306 void Path::makeWriteable() {
307   DWORD attr = GetFileAttributes(path.c_str());
308
309   // If it doesn't exist, we're done.
310   if (attr == INVALID_FILE_ATTRIBUTES)
311     return;
312
313   if (attr & FILE_ATTRIBUTE_READONLY) {
314     if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY))
315       ThrowError(std::string(path) + ": Can't make file writable: ");
316   }
317 }
318
319 void Path::makeExecutable() {
320   // All files are executable on Windows (ignoring security attributes).
321 }
322
323 bool
324 Path::setDirectory(const std::string& a_path) {
325   if (a_path.size() == 0)
326     return false;
327   Path save(*this);
328   path = a_path;
329   FlipBackSlashes(path);
330   size_t last = a_path.size() -1;
331   if (a_path[last] != '/')
332     path += '/';
333   if (!isValid()) {
334     path = save.path;
335     return false;
336   }
337   return true;
338 }
339
340 bool
341 Path::setFile(const std::string& a_path) {
342   if (a_path.size() == 0)
343     return false;
344   Path save(*this);
345   path = a_path;
346   FlipBackSlashes(path);
347   size_t last = a_path.size() - 1;
348   while (last > 0 && a_path[last] == '/')
349     last--;
350   path.erase(last+1);
351   if (!isValid()) {
352     path = save.path;
353     return false;
354   }
355   return true;
356 }
357
358 bool
359 Path::appendDirectory(const std::string& dir) {
360   if (isFile())
361     return false;
362   Path save(*this);
363   path += dir;
364   path += "/";
365   if (!isValid()) {
366     path = save.path;
367     return false;
368   }
369   return true;
370 }
371
372 bool
373 Path::elideDirectory() {
374   if (isFile())
375     return false;
376   size_t slashpos = path.rfind('/',path.size());
377   if (slashpos == 0 || slashpos == std::string::npos)
378     return false;
379   if (slashpos == path.size() - 1)
380     slashpos = path.rfind('/',slashpos-1);
381   if (slashpos == std::string::npos)
382     return false;
383   path.erase(slashpos);
384   return true;
385 }
386
387 bool
388 Path::appendFile(const std::string& file) {
389   if (!isDirectory())
390     return false;
391   Path save(*this);
392   path += file;
393   if (!isValid()) {
394     path = save.path;
395     return false;
396   }
397   return true;
398 }
399
400 bool
401 Path::elideFile() {
402   if (isDirectory())
403     return false;
404   size_t slashpos = path.rfind('/',path.size());
405   if (slashpos == std::string::npos)
406     return false;
407   path.erase(slashpos+1);
408   return true;
409 }
410
411 bool
412 Path::appendSuffix(const std::string& suffix) {
413   if (isDirectory())
414     return false;
415   Path save(*this);
416   path.append(".");
417   path.append(suffix);
418   if (!isValid()) {
419     path = save.path;
420     return false;
421   }
422   return true;
423 }
424
425 bool
426 Path::elideSuffix() {
427   if (isDirectory()) return false;
428   size_t dotpos = path.rfind('.',path.size());
429   size_t slashpos = path.rfind('/',path.size());
430   if (slashpos != std::string::npos && dotpos != std::string::npos &&
431       dotpos > slashpos) {
432     path.erase(dotpos, path.size()-dotpos);
433     return true;
434   }
435   return false;
436 }
437
438
439 bool
440 Path::createDirectory( bool create_parents) {
441   // Make sure we're dealing with a directory
442   if (!isDirectory()) return false;
443
444   // Get a writeable copy of the path name
445   char *pathname = reinterpret_cast<char *>(_alloca(path.length()+1));
446   path.copy(pathname,path.length());
447   pathname[path.length()] = 0;
448
449   // Determine starting point for initial / search.
450   char *next = pathname;
451   if (pathname[0] == '/' && pathname[1] == '/') {
452     // Skip host name.
453     next = strchr(pathname+2, '/');
454     if (next == NULL)
455       throw std::string(pathname) + ": badly formed remote directory";
456     // Skip share name.
457     next = strchr(next+1, '/');
458     if (next == NULL)
459       throw std::string(pathname) + ": badly formed remote directory";
460     next++;
461     if (*next == 0)
462       throw std::string(pathname) + ": badly formed remote directory";
463   } else {
464     if (pathname[1] == ':')
465       next += 2;    // skip drive letter
466     if (*next == '/')
467       next++;       // skip root directory
468   }
469
470   // If we're supposed to create intermediate directories
471   if (create_parents) {
472     // Loop through the directory components until we're done
473     while (*next) {
474       next = strchr(next, '/');
475       *next = 0;
476       if (!CreateDirectory(pathname, NULL))
477           ThrowError(std::string(pathname) + ": Can't create directory: ");
478       *next++ = '/';
479     }
480   } else {
481     // Drop trailing slash.
482     pathname[path.size()-1] = 0;
483     if (!CreateDirectory(pathname, NULL)) {
484       ThrowError(std::string(pathname) + ": Can't create directory: ");
485     }
486   }
487   return true;
488 }
489
490 bool
491 Path::createFile() {
492   // Make sure we're dealing with a file
493   if (!isFile()) return false;
494
495   // Create the file
496   HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
497                         FILE_ATTRIBUTE_NORMAL, NULL);
498   if (h == INVALID_HANDLE_VALUE)
499     ThrowError(std::string(path.c_str()) + ": Can't create file: ");
500
501   CloseHandle(h);
502   return true;
503 }
504
505 bool
506 Path::destroyDirectory(bool remove_contents) const {
507   // Make sure we're dealing with a directory
508   if (!isDirectory()) return false;
509
510   // If it doesn't exist, we're done.
511   if (!exists()) return true;
512
513   char *pathname = reinterpret_cast<char *>(_alloca(path.length()+1));
514   path.copy(pathname,path.length()+1);
515   int lastchar = path.length() - 1 ;
516   if (pathname[lastchar] == '/')
517     pathname[lastchar] = 0;
518
519   if (remove_contents) {
520     // Recursively descend the directory to remove its content
521     // FIXME: The correct way of doing this on Windows isn't pretty...
522     // but this may work if unix-like utils are present.
523     std::string cmd("rm -rf ");
524     cmd += path;
525     system(cmd.c_str());
526   } else {
527     // Otherwise, try to just remove the one directory
528     if (!RemoveDirectory(pathname))
529       ThrowError(std::string(pathname) + ": Can't destroy directory: ");
530   }
531   return true;
532 }
533
534 bool
535 Path::destroyFile() const {
536   if (!isFile()) return false;
537
538   DWORD attr = GetFileAttributes(path.c_str());
539
540   // If it doesn't exist, we're done.
541   if (attr == INVALID_FILE_ATTRIBUTES)
542     return true;
543
544   // Read-only files cannot be deleted on Windows.  Must remove the read-only
545   // attribute first.
546   if (attr & FILE_ATTRIBUTE_READONLY) {
547     if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY))
548       ThrowError(std::string(path.c_str()) + ": Can't destroy file: ");
549   }
550
551   if (!DeleteFile(path.c_str()))
552     ThrowError(std::string(path.c_str()) + ": Can't destroy file: ");
553   return true;
554 }
555
556 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
557   if (!isFile())
558     return false;
559   assert(len < 1024 && "Request for magic string too long");
560   char* buf = (char*) alloca(1 + len);
561   std::ofstream ofs(path.c_str(),std::ofstream::in);
562   if (!ofs.is_open())
563     return false;
564   std::ifstream ifs(path.c_str());
565   if (!ifs.is_open())
566     return false;
567   ifs.read(buf, len);
568   ofs.close();
569   ifs.close();
570   buf[len] = '\0';
571   Magic = buf;
572   return true;
573 }
574
575 void 
576 CopyFile(const sys::Path &Dest, const sys::Path &Src) {
577   if (!::CopyFile(Src.c_str(), Dest.c_str(), false))
578     ThrowError("Can't copy '" + Src.toString() + 
579                "' to '" + Dest.toString() + "'");
580 }
581
582 void 
583 Path::makeUnique( bool reuse_current ) {
584   if (reuse_current && !exists())
585     return; // File doesn't exist already, just use it!
586
587   Path dir (*this);
588   dir.elideFile();
589   std::string fname = this->getLast();
590
591   char newName[MAX_PATH + 1];
592   if (!GetTempFileName(dir.c_str(), fname.c_str(), 0, newName))
593     ThrowError("Cannot make unique filename for '" + path + "'");
594
595   path = newName;
596 }
597
598 bool
599 Path::createTemporaryFile(bool reuse_current) {
600   // Make sure we're dealing with a file
601   if (!isFile()) 
602     return false;
603
604   // Make this into a unique file name
605   makeUnique( reuse_current );
606 }
607
608 }
609 }
610
611 // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab
612