Stop propagating method names that violate the coding standard
[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 <llvm/System/Path.h>
24 #include <fstream>
25 #include <malloc.h>
26
27 static void FlipBackSlashes(std::string& s) {
28   for (size_t i = 0; i < s.size(); i++)
29     if (s[i] == '\\')
30       s[i] = '/';
31 }
32
33 namespace llvm {
34 namespace sys {
35
36 bool
37 Path::isValid() const {
38   if (path.empty())
39     return false;
40
41   // If there is a colon, it must be the second character, preceded by a letter
42   // and followed by something.
43   size_t len = path.size();
44   size_t pos = path.rfind(':',len);
45   if (pos != std::string::npos) {
46     if (pos != 1 || !isalpha(path[0]) || len < 3)
47       return false;
48   }
49
50   // Check for illegal characters.
51   if (path.find_first_of("\\<>\"|\001\002\003\004\005\006\007\010\011\012"
52                          "\013\014\015\016\017\020\021\022\023\024\025\026"
53                          "\027\030\031\032\033\034\035\036\037")
54       != std::string::npos)
55     return false;
56
57   // A file or directory name may not end in a period.
58   if (path[len-1] == '.')
59     return false;
60   if (len >= 2 && path[len-2] == '.' && path[len-1] == '/')
61     return false;
62
63   // A file or directory name may not end in a space.
64   if (path[len-1] == ' ')
65     return false;
66   if (len >= 2 && path[len-2] == ' ' && path[len-1] == '/')
67     return false;
68
69   return true;
70 }
71
72 static Path *TempDirectory = NULL;
73
74 Path
75 Path::GetTemporaryDirectory() {
76   if (TempDirectory)
77     return *TempDirectory;
78
79   char pathname[MAX_PATH];
80   if (!GetTempPath(MAX_PATH, pathname))
81     throw std::string("Can't determine temporary directory");
82
83   Path result;
84   result.setDirectory(pathname);
85
86   // Append a subdirectory passed on our process id so multiple LLVMs don't
87   // step on each other's toes.
88   sprintf(pathname, "LLVM_%u", GetCurrentProcessId());
89   result.appendDirectory(pathname);
90
91   // If there's a directory left over from a previous LLVM execution that
92   // happened to have the same process id, get rid of it.
93   result.destroyDirectory(true);
94
95   // And finally (re-)create the empty directory.
96   result.createDirectory(false);
97   TempDirectory = new Path(result);
98   return *TempDirectory;
99 }
100
101 Path::Path(std::string unverified_path)
102   : path(unverified_path)
103 {
104   FlipBackSlashes(path);
105   if (unverified_path.empty())
106     return;
107   if (this->isValid())
108     return;
109   // oops, not valid.
110   path.clear();
111   throw std::string(unverified_path + ": path is not valid");
112 }
113
114 // FIXME: the following set of functions don't map to Windows very well.
115 Path
116 Path::GetRootDirectory() {
117   Path result;
118   result.setDirectory("/");
119   return result;
120 }
121
122 std::string
123 Path::GetDLLSuffix() {
124   return "dll";
125 }
126
127 static inline bool IsLibrary(Path& path, const std::string& basename) {
128   if (path.appendFile(std::string("lib") + basename)) {
129     if (path.appendSuffix(Path::GetDLLSuffix()) && path.readable())
130       return true;
131     else if (path.elideSuffix() && path.appendSuffix("a") && path.readable())
132       return true;
133     else if (path.elideSuffix() && path.appendSuffix("o") && path.readable())
134       return true;
135     else if (path.elideSuffix() && path.appendSuffix("bc") && path.readable())
136       return true;
137   } else if (path.elideFile() && path.appendFile(basename)) {
138     if (path.appendSuffix(Path::GetDLLSuffix()) && path.readable())
139       return true;
140     else if (path.elideSuffix() && path.appendSuffix("a") && path.readable())
141       return true;
142     else if (path.elideSuffix() && path.appendSuffix("o") && path.readable())
143       return true;
144     else if (path.elideSuffix() && path.appendSuffix("bc") && path.readable())
145       return true;
146   }
147   path.clear();
148   return false;
149 }
150
151 Path 
152 Path::GetLibraryPath(const std::string& basename, 
153                      const std::vector<std::string>& LibPaths) {
154   Path result;
155
156   // Try the paths provided
157   for (std::vector<std::string>::const_iterator I = LibPaths.begin(),
158        E = LibPaths.end(); I != E; ++I ) {
159     if (result.setDirectory(*I) && IsLibrary(result,basename))
160       return result;
161   }
162
163   // Try the LLVM lib directory in the LLVM install area
164   //if (result.setDirectory(LLVM_LIBDIR) && IsLibrary(result,basename))
165   //  return result;
166
167   // Try /usr/lib
168   if (result.setDirectory("/usr/lib/") && IsLibrary(result,basename))
169     return result;
170
171   // Try /lib
172   if (result.setDirectory("/lib/") && IsLibrary(result,basename))
173     return result;
174
175   // Can't find it, give up and return invalid path.
176   result.clear();
177   return result;
178 }
179
180 Path
181 Path::GetSystemLibraryPath1() {
182   return Path("/lib/");
183 }
184
185 Path
186 Path::GetSystemLibraryPath2() {
187   return Path("/usr/lib/");
188 }
189
190 Path
191 Path::GetLLVMDefaultConfigDir() {
192   return Path("/etc/llvm/");
193 }
194
195 Path
196 Path::GetLLVMConfigDir() {
197   return GetLLVMDefaultConfigDir();
198 }
199
200 Path
201 Path::GetUserHomeDirectory() {
202   const char* home = getenv("HOME");
203   if (home) {
204     Path result;
205     if (result.setDirectory(home))
206       return result;
207   }
208   return GetRootDirectory();
209 }
210 // FIXME: the above set of functions don't map to Windows very well.
211
212 bool
213 Path::isFile() const {
214   return (isValid() && path[path.length()-1] != '/');
215 }
216
217 bool
218 Path::isDirectory() const {
219   return (isValid() && path[path.length()-1] == '/');
220 }
221
222 std::string
223 Path::getBasename() const {
224   // Find the last slash
225   size_t slash = path.rfind('/');
226   if (slash == std::string::npos)
227     slash = 0;
228   else
229     slash++;
230
231   return path.substr(slash, path.rfind('.'));
232 }
233
234 bool Path::hasMagicNumber(const std::string &Magic) const {
235   size_t len = Magic.size();
236   char *buf = reinterpret_cast<char *>(_alloca(len+1));
237   std::ifstream f(path.c_str());
238   f.read(buf, len);
239   buf[len] = '\0';
240   return Magic == buf;
241 }
242
243 bool 
244 Path::isBytecodeFile() const {
245   if (readable()) {
246     return hasMagicNumber("llvm");
247   }
248   return false;
249 }
250
251 bool
252 Path::isArchive() const {
253   if (readable()) {
254     return hasMagicNumber("!<arch>\012");
255   }
256   return false;
257 }
258
259 bool
260 Path::exists() const {
261   DWORD attr = GetFileAttributes(path.c_str());
262   return attr != INVALID_FILE_ATTRIBUTES;
263 }
264
265 bool
266 Path::readable() const {
267   // FIXME: take security attributes into account.
268   DWORD attr = GetFileAttributes(path.c_str());
269   return attr != INVALID_FILE_ATTRIBUTES;
270 }
271
272 bool
273 Path::writable() const {
274   // FIXME: take security attributes into account.
275   DWORD attr = GetFileAttributes(path.c_str());
276   return (attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_READONLY);
277 }
278
279 bool
280 Path::executable() const {
281   // FIXME: take security attributes into account.
282   DWORD attr = GetFileAttributes(path.c_str());
283   return attr != INVALID_FILE_ATTRIBUTES;
284 }
285
286 std::string
287 Path::getLast() const {
288   // Find the last slash
289   size_t pos = path.rfind('/');
290
291   // Handle the corner cases
292   if (pos == std::string::npos)
293     return path;
294
295   // If the last character is a slash
296   if (pos == path.length()-1) {
297     // Find the second to last slash
298     size_t pos2 = path.rfind('/', pos-1);
299     if (pos2 == std::string::npos)
300       return path.substr(0,pos);
301     else
302       return path.substr(pos2+1,pos-pos2-1);
303   }
304   // Return everything after the last slash
305   return path.substr(pos+1);
306 }
307
308 bool
309 Path::setDirectory(const std::string& a_path) {
310   if (a_path.size() == 0)
311     return false;
312   Path save(*this);
313   path = a_path;
314   FlipBackSlashes(path);
315   size_t last = a_path.size() -1;
316   if (last != 0 && a_path[last] != '/')
317     path += '/';
318   if (!isValid()) {
319     path = save.path;
320     return false;
321   }
322   return true;
323 }
324
325 bool
326 Path::setFile(const std::string& a_path) {
327   if (a_path.size() == 0)
328     return false;
329   Path save(*this);
330   path = a_path;
331   FlipBackSlashes(path);
332   size_t last = a_path.size() - 1;
333   while (last > 0 && a_path[last] == '/')
334     last--;
335   path.erase(last+1);
336   if (!isValid()) {
337     path = save.path;
338     return false;
339   }
340   return true;
341 }
342
343 bool
344 Path::appendDirectory(const std::string& dir) {
345   if (isFile())
346     return false;
347   Path save(*this);
348   path += dir;
349   path += "/";
350   if (!isValid()) {
351     path = save.path;
352     return false;
353   }
354   return true;
355 }
356
357 bool
358 Path::elideDirectory() {
359   if (isFile())
360     return false;
361   size_t slashpos = path.rfind('/',path.size());
362   if (slashpos == 0 || slashpos == std::string::npos)
363     return false;
364   if (slashpos == path.size() - 1)
365     slashpos = path.rfind('/',slashpos-1);
366   if (slashpos == std::string::npos)
367     return false;
368   path.erase(slashpos);
369   return true;
370 }
371
372 bool
373 Path::appendFile(const std::string& file) {
374   if (!isDirectory())
375     return false;
376   Path save(*this);
377   path += file;
378   if (!isValid()) {
379     path = save.path;
380     return false;
381   }
382   return true;
383 }
384
385 bool
386 Path::elideFile() {
387   if (isDirectory())
388     return false;
389   size_t slashpos = path.rfind('/',path.size());
390   if (slashpos == std::string::npos)
391     return false;
392   path.erase(slashpos+1);
393   return true;
394 }
395
396 bool
397 Path::appendSuffix(const std::string& suffix) {
398   if (isDirectory())
399     return false;
400   Path save(*this);
401   path.append(".");
402   path.append(suffix);
403   if (!isValid()) {
404     path = save.path;
405     return false;
406   }
407   return true;
408 }
409
410 bool
411 Path::elideSuffix() {
412   if (isDirectory()) return false;
413   size_t dotpos = path.rfind('.',path.size());
414   size_t slashpos = path.rfind('/',path.size());
415   if (slashpos != std::string::npos && dotpos != std::string::npos &&
416       dotpos > slashpos) {
417     path.erase(dotpos, path.size()-dotpos);
418     return true;
419   }
420   return false;
421 }
422
423
424 bool
425 Path::createDirectory( bool create_parents) {
426   // Make sure we're dealing with a directory
427   if (!isDirectory()) return false;
428
429   // Get a writeable copy of the path name
430   char *pathname = reinterpret_cast<char *>(_alloca(path.length()+1));
431   path.copy(pathname,path.length());
432   pathname[path.length()] = 0;
433
434   // Determine starting point for initial / search.
435   char *next = pathname;
436   if (pathname[0] == '/' && pathname[1] == '/') {
437     // Skip host name.
438     next = strchr(pathname+2, '/');
439     if (next == NULL)
440       throw std::string(pathname) + ": badly formed remote directory";
441     // Skip share name.
442     next = strchr(next+1, '/');
443     if (next == NULL)
444       throw std::string(pathname) + ": badly formed remote directory";
445     next++;
446     if (*next == 0)
447       throw std::string(pathname) + ": badly formed remote directory";
448   } else {
449     if (pathname[1] == ':')
450       next += 2;    // skip drive letter
451     if (*next == '/')
452       next++;       // skip root directory
453   }
454
455   // If we're supposed to create intermediate directories
456   if (create_parents) {
457     // Loop through the directory components until we're done
458     while (*next) {
459       next = strchr(next, '/');
460       *next = 0;
461       if (!CreateDirectory(pathname, NULL))
462           ThrowError(std::string(pathname) + ": Can't create directory: ");
463       *next++ = '/';
464     }
465   } else {
466     // Drop trailing slash.
467     pathname[path.size()-1] = 0;
468     if (!CreateDirectory(pathname, NULL)) {
469       ThrowError(std::string(pathname) + ": Can't create directory: ");
470     }
471   }
472   return true;
473 }
474
475 bool
476 Path::createFile() {
477   // Make sure we're dealing with a file
478   if (!isFile()) return false;
479
480   // Create the file
481   HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_NEW,
482                         FILE_ATTRIBUTE_NORMAL, NULL);
483   if (h == INVALID_HANDLE_VALUE)
484     ThrowError(std::string(path.c_str()) + ": Can't create file: ");
485
486   CloseHandle(h);
487   return true;
488 }
489
490 bool
491 Path::destroyDirectory(bool remove_contents) {
492   // Make sure we're dealing with a directory
493   if (!isDirectory()) return false;
494
495   // If it doesn't exist, we're done.
496   if (!exists()) return true;
497
498   char *pathname = reinterpret_cast<char *>(_alloca(path.length()+1));
499   path.copy(pathname,path.length()+1);
500   int lastchar = path.length() - 1 ;
501   if (pathname[lastchar] == '/')
502     pathname[lastchar] = 0;
503
504   if (remove_contents) {
505     // Recursively descend the directory to remove its content
506     // FIXME: The correct way of doing this on Windows isn't pretty...
507     // but this may work if unix-like utils are present.
508     std::string cmd("rm -rf ");
509     cmd += path;
510     system(cmd.c_str());
511   } else {
512     // Otherwise, try to just remove the one directory
513     if (!RemoveDirectory(pathname))
514       ThrowError(std::string(pathname) + ": Can't destroy directory: ");
515   }
516   return true;
517 }
518
519 bool
520 Path::destroyFile() {
521   if (!isFile()) return false;
522
523   DWORD attr = GetFileAttributes(path.c_str());
524
525   // If it doesn't exist, we're done.
526   if (attr == INVALID_FILE_ATTRIBUTES)
527     return true;
528
529   // Read-only files cannot be deleted on Windows.  Must remove the read-only
530   // attribute first.
531   if (attr & FILE_ATTRIBUTE_READONLY) {
532     if (!SetFileAttributes(path.c_str(), attr & ~FILE_ATTRIBUTE_READONLY))
533       ThrowError(std::string(path.c_str()) + ": Can't destroy file: ");
534   }
535
536   if (!DeleteFile(path.c_str()))
537     ThrowError(std::string(path.c_str()) + ": Can't destroy file: ");
538   return true;
539 }
540
541 }
542 }
543
544 // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab
545