Early exit if we don't have invokes. The 'Unwinds' vector isn't modified unless
[oota-llvm.git] / lib / Support / PathV2.cpp
1 //===-- PathV2.cpp - Implement OS Path Concept ------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the operating system PathV2 API.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Support/PathV2.h"
15 #include "llvm/Support/FileSystem.h"
16 #include "llvm/Support/ErrorHandling.h"
17 #include <cctype>
18 #include <cstdio>
19 #include <cstring>
20
21 namespace {
22   using llvm::StringRef;
23
24   bool is_separator(const char value) {
25     switch(value) {
26 #ifdef LLVM_ON_WIN32
27     case '\\': // fall through
28 #endif
29     case '/': return true;
30     default: return false;
31     }
32   }
33
34 #ifdef LLVM_ON_WIN32
35   const StringRef separators = "\\/";
36   const char      prefered_separator = '\\';
37 #else
38   const StringRef separators = "/";
39   const char      prefered_separator = '/';
40 #endif
41
42   const llvm::error_code success;
43
44   StringRef find_first_component(StringRef path) {
45     // Look for this first component in the following order.
46     // * empty (in this case we return an empty string)
47     // * either C: or {//,\\}net.
48     // * {/,\}
49     // * {.,..}
50     // * {file,directory}name
51
52     if (path.empty())
53       return path;
54
55 #ifdef LLVM_ON_WIN32
56     // C:
57     if (path.size() >= 2 && std::isalpha(path[0]) && path[1] == ':')
58       return path.substr(0, 2);
59 #endif
60
61     // //net
62     if ((path.size() > 2) &&
63         is_separator(path[0]) &&
64         path[0] == path[1] &&
65         !is_separator(path[2])) {
66       // Find the next directory separator.
67       size_t end = path.find_first_of(separators, 2);
68       return path.substr(0, end);
69     }
70
71     // {/,\}
72     if (is_separator(path[0]))
73       return path.substr(0, 1);
74
75     if (path.startswith(".."))
76       return path.substr(0, 2);
77
78     if (path[0] == '.')
79       return path.substr(0, 1);
80
81     // * {file,directory}name
82     size_t end = path.find_first_of(separators, 2);
83     return path.substr(0, end);
84   }
85
86   size_t filename_pos(StringRef str) {
87     if (str.size() == 2 &&
88         is_separator(str[0]) &&
89         str[0] == str[1])
90       return 0;
91
92     if (str.size() > 0 && is_separator(str[str.size() - 1]))
93       return str.size() - 1;
94
95     size_t pos = str.find_last_of(separators, str.size() - 1);
96
97 #ifdef LLVM_ON_WIN32
98     if (pos == StringRef::npos)
99       pos = str.find_last_of(':', str.size() - 2);
100 #endif
101
102     if (pos == StringRef::npos ||
103         (pos == 1 && is_separator(str[0])))
104       return 0;
105
106     return pos + 1;
107   }
108
109   size_t root_dir_start(StringRef str) {
110     // case "c:/"
111 #ifdef LLVM_ON_WIN32
112     if (str.size() > 2 &&
113         str[1] == ':' &&
114         is_separator(str[2]))
115       return 2;
116 #endif
117
118     // case "//"
119     if (str.size() == 2 &&
120         is_separator(str[0]) &&
121         str[0] == str[1])
122       return StringRef::npos;
123
124     // case "//net"
125     if (str.size() > 3 &&
126         is_separator(str[0]) &&
127         str[0] == str[1] &&
128         !is_separator(str[2])) {
129       return str.find_first_of(separators, 2);
130     }
131
132     // case "/"
133     if (str.size() > 0 && is_separator(str[0]))
134       return 0;
135
136     return StringRef::npos;
137   }
138
139   size_t parent_path_end(StringRef path) {
140     size_t end_pos = filename_pos(path);
141
142     bool filename_was_sep = path.size() > 0 && is_separator(path[end_pos]);
143
144     // Skip separators except for root dir.
145     size_t root_dir_pos = root_dir_start(path.substr(0, end_pos));
146
147     while(end_pos > 0 &&
148           (end_pos - 1) != root_dir_pos &&
149           is_separator(path[end_pos - 1]))
150       --end_pos;
151
152     if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep)
153       return StringRef::npos;
154
155     return end_pos;
156   }
157 }
158
159 namespace llvm {
160 namespace sys  {
161 namespace path {
162
163 const_iterator begin(StringRef path) {
164   const_iterator i;
165   i.Path      = path;
166   i.Component = find_first_component(path);
167   i.Position  = 0;
168   return i;
169 }
170
171 const_iterator end(StringRef path) {
172   const_iterator i;
173   i.Path      = path;
174   i.Position  = path.size();
175   return i;
176 }
177
178 const_iterator &const_iterator::operator++() {
179   assert(Position < Path.size() && "Tried to increment past end!");
180
181   // Increment Position to past the current component
182   Position += Component.size();
183
184   // Check for end.
185   if (Position == Path.size()) {
186     Component = StringRef();
187     return *this;
188   }
189
190   // Both POSIX and Windows treat paths that begin with exactly two separators
191   // specially.
192   bool was_net = Component.size() > 2 &&
193     is_separator(Component[0]) &&
194     Component[1] == Component[0] &&
195     !is_separator(Component[2]);
196
197   // Handle separators.
198   if (is_separator(Path[Position])) {
199     // Root dir.
200     if (was_net
201 #ifdef LLVM_ON_WIN32
202         // c:/
203         || Component.endswith(":")
204 #endif
205         ) {
206       Component = Path.substr(Position, 1);
207       return *this;
208     }
209
210     // Skip extra separators.
211     while (Position != Path.size() &&
212            is_separator(Path[Position])) {
213       ++Position;
214     }
215
216     // Treat trailing '/' as a '.'.
217     if (Position == Path.size()) {
218       --Position;
219       Component = ".";
220       return *this;
221     }
222   }
223
224   // Find next component.
225   size_t end_pos = Path.find_first_of(separators, Position);
226   Component = Path.slice(Position, end_pos);
227
228   return *this;
229 }
230
231 const_iterator &const_iterator::operator--() {
232   // If we're at the end and the previous char was a '/', return '.'.
233   if (Position == Path.size() &&
234       Path.size() > 1 &&
235       is_separator(Path[Position - 1])
236 #ifdef LLVM_ON_WIN32
237       && Path[Position - 2] != ':'
238 #endif
239       ) {
240     --Position;
241     Component = ".";
242     return *this;
243   }
244
245   // Skip separators unless it's the root directory.
246   size_t root_dir_pos = root_dir_start(Path);
247   size_t end_pos = Position;
248
249   while(end_pos > 0 &&
250         (end_pos - 1) != root_dir_pos &&
251         is_separator(Path[end_pos - 1]))
252     --end_pos;
253
254   // Find next separator.
255   size_t start_pos = filename_pos(Path.substr(0, end_pos));
256   Component = Path.slice(start_pos, end_pos);
257   Position = start_pos;
258   return *this;
259 }
260
261 bool const_iterator::operator==(const const_iterator &RHS) const {
262   return Path.begin() == RHS.Path.begin() &&
263          Position == RHS.Position;
264 }
265
266 bool const_iterator::operator!=(const const_iterator &RHS) const {
267   return !(*this == RHS);
268 }
269
270 ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
271   return Position - RHS.Position;
272 }
273
274 const StringRef root_path(StringRef path) {
275   const_iterator b = begin(path),
276                  pos = b,
277                  e = end(path);
278   if (b != e) {
279     bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
280     bool has_drive =
281 #ifdef LLVM_ON_WIN32
282       b->endswith(":");
283 #else
284       false;
285 #endif
286
287     if (has_net || has_drive) {
288       if ((++pos != e) && is_separator((*pos)[0])) {
289         // {C:/,//net/}, so get the first two components.
290         return path.substr(0, b->size() + pos->size());
291       } else {
292         // just {C:,//net}, return the first component.
293         return *b;
294       }
295     }
296
297     // POSIX style root directory.
298     if (is_separator((*b)[0])) {
299       return *b;
300     }
301   }
302
303   return StringRef();
304 }
305
306 const StringRef root_name(StringRef path) {
307   const_iterator b = begin(path),
308                  e = end(path);
309   if (b != e) {
310     bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
311     bool has_drive =
312 #ifdef LLVM_ON_WIN32
313       b->endswith(":");
314 #else
315       false;
316 #endif
317
318     if (has_net || has_drive) {
319       // just {C:,//net}, return the first component.
320       return *b;
321     }
322   }
323
324   // No path or no name.
325   return StringRef();
326 }
327
328 const StringRef root_directory(StringRef path) {
329   const_iterator b = begin(path),
330                  pos = b,
331                  e = end(path);
332   if (b != e) {
333     bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
334     bool has_drive =
335 #ifdef LLVM_ON_WIN32
336       b->endswith(":");
337 #else
338       false;
339 #endif
340
341     if ((has_net || has_drive) &&
342         // {C:,//net}, skip to the next component.
343         (++pos != e) && is_separator((*pos)[0])) {
344       return *pos;
345     }
346
347     // POSIX style root directory.
348     if (!has_net && is_separator((*b)[0])) {
349       return *b;
350     }
351   }
352
353   // No path or no root.
354   return StringRef();
355 }
356
357 const StringRef relative_path(StringRef path) {
358   StringRef root = root_path(path);
359   return root.substr(root.size());
360 }
361
362 void append(SmallVectorImpl<char> &path, const Twine &a,
363                                          const Twine &b,
364                                          const Twine &c,
365                                          const Twine &d) {
366   SmallString<32> a_storage;
367   SmallString<32> b_storage;
368   SmallString<32> c_storage;
369   SmallString<32> d_storage;
370
371   SmallVector<StringRef, 4> components;
372   if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage));
373   if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage));
374   if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage));
375   if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage));
376
377   for (SmallVectorImpl<StringRef>::const_iterator i = components.begin(),
378                                                   e = components.end();
379                                                   i != e; ++i) {
380     bool path_has_sep = !path.empty() && is_separator(path[path.size() - 1]);
381     bool component_has_sep = !i->empty() && is_separator((*i)[0]);
382     bool is_root_name = has_root_name(*i);
383
384     if (path_has_sep) {
385       // Strip separators from beginning of component.
386       size_t loc = i->find_first_not_of(separators);
387       StringRef c = i->substr(loc);
388
389       // Append it.
390       path.append(c.begin(), c.end());
391       continue;
392     }
393
394     if (!component_has_sep && !(path.empty() || is_root_name)) {
395       // Add a separator.
396       path.push_back(prefered_separator);
397     }
398
399     path.append(i->begin(), i->end());
400   }
401 }
402
403 const StringRef parent_path(StringRef path) {
404   size_t end_pos = parent_path_end(path);
405   if (end_pos == StringRef::npos)
406     return StringRef();
407   else
408     return path.substr(0, end_pos);
409 }
410
411 void remove_filename(SmallVectorImpl<char> &path) {
412   size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()));
413   if (end_pos != StringRef::npos)
414     path.set_size(end_pos);
415 }
416
417 void replace_extension(SmallVectorImpl<char> &path, const Twine &extension) {
418   StringRef p(path.begin(), path.size());
419   SmallString<32> ext_storage;
420   StringRef ext = extension.toStringRef(ext_storage);
421
422   // Erase existing extension.
423   size_t pos = p.find_last_of('.');
424   if (pos != StringRef::npos && pos >= filename_pos(p))
425     path.set_size(pos);
426
427   // Append '.' if needed.
428   if (ext.size() > 0 && ext[0] != '.')
429     path.push_back('.');
430
431   // Append extension.
432   path.append(ext.begin(), ext.end());
433 }
434
435 void native(const Twine &path, SmallVectorImpl<char> &result) {
436   // Clear result.
437   result.clear();
438 #ifdef LLVM_ON_WIN32
439   SmallString<128> path_storage;
440   StringRef p = path.toStringRef(path_storage);
441   result.reserve(p.size());
442   for (StringRef::const_iterator i = p.begin(),
443                                  e = p.end();
444                                  i != e;
445                                  ++i) {
446     if (*i == '/')
447       result.push_back('\\');
448     else
449       result.push_back(*i);
450   }
451 #else
452   path.toVector(result);
453 #endif
454 }
455
456 const StringRef filename(StringRef path) {
457   return *(--end(path));
458 }
459
460 const StringRef stem(StringRef path) {
461   StringRef fname = filename(path);
462   size_t pos = fname.find_last_of('.');
463   if (pos == StringRef::npos)
464     return fname;
465   else
466     if ((fname.size() == 1 && fname == ".") ||
467         (fname.size() == 2 && fname == ".."))
468       return fname;
469     else
470       return fname.substr(0, pos);
471 }
472
473 const StringRef extension(StringRef path) {
474   StringRef fname = filename(path);
475   size_t pos = fname.find_last_of('.');
476   if (pos == StringRef::npos)
477     return StringRef();
478   else
479     if ((fname.size() == 1 && fname == ".") ||
480         (fname.size() == 2 && fname == ".."))
481       return StringRef();
482     else
483       return fname.substr(pos);
484 }
485
486 bool has_root_name(const Twine &path) {
487   SmallString<128> path_storage;
488   StringRef p = path.toStringRef(path_storage);
489
490   return !root_name(p).empty();
491 }
492
493 bool has_root_directory(const Twine &path) {
494   SmallString<128> path_storage;
495   StringRef p = path.toStringRef(path_storage);
496
497   return !root_directory(p).empty();
498 }
499
500 bool has_root_path(const Twine &path) {
501   SmallString<128> path_storage;
502   StringRef p = path.toStringRef(path_storage);
503
504   return !root_path(p).empty();
505 }
506
507 bool has_relative_path(const Twine &path) {
508   SmallString<128> path_storage;
509   StringRef p = path.toStringRef(path_storage);
510
511   return !relative_path(p).empty();
512 }
513
514 bool has_filename(const Twine &path) {
515   SmallString<128> path_storage;
516   StringRef p = path.toStringRef(path_storage);
517
518   return !filename(p).empty();
519 }
520
521 bool has_parent_path(const Twine &path) {
522   SmallString<128> path_storage;
523   StringRef p = path.toStringRef(path_storage);
524
525   return !parent_path(p).empty();
526 }
527
528 bool has_stem(const Twine &path) {
529   SmallString<128> path_storage;
530   StringRef p = path.toStringRef(path_storage);
531
532   return !stem(p).empty();
533 }
534
535 bool has_extension(const Twine &path) {
536   SmallString<128> path_storage;
537   StringRef p = path.toStringRef(path_storage);
538
539   return !extension(p).empty();
540 }
541
542 bool is_absolute(const Twine &path) {
543   SmallString<128> path_storage;
544   StringRef p = path.toStringRef(path_storage);
545
546   bool rootDir = has_root_directory(p),
547 #ifdef LLVM_ON_WIN32
548        rootName = has_root_name(p);
549 #else
550        rootName = true;
551 #endif
552
553   return rootDir && rootName;
554 }
555
556 bool is_relative(const Twine &path) {
557   return !is_absolute(path);
558 }
559
560 } // end namespace path
561
562 namespace fs {
563
564 error_code make_absolute(SmallVectorImpl<char> &path) {
565   StringRef p(path.data(), path.size());
566
567   bool rootName      = path::has_root_name(p),
568        rootDirectory = path::has_root_directory(p);
569
570   // Already absolute.
571   if (rootName && rootDirectory)
572     return success;
573
574   // All of the following conditions will need the current directory.
575   SmallString<128> current_dir;
576   if (error_code ec = current_path(current_dir)) return ec;
577
578   // Relative path. Prepend the current directory.
579   if (!rootName && !rootDirectory) {
580     // Append path to the current directory.
581     path::append(current_dir, p);
582     // Set path to the result.
583     path.swap(current_dir);
584     return success;
585   }
586
587   if (!rootName && rootDirectory) {
588     StringRef cdrn = path::root_name(current_dir);
589     SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
590     path::append(curDirRootName, p);
591     // Set path to the result.
592     path.swap(curDirRootName);
593     return success;
594   }
595
596   if (rootName && !rootDirectory) {
597     StringRef pRootName      = path::root_name(p);
598     StringRef bRootDirectory = path::root_directory(current_dir);
599     StringRef bRelativePath  = path::relative_path(current_dir);
600     StringRef pRelativePath  = path::relative_path(p);
601
602     SmallString<128> res;
603     path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
604     path.swap(res);
605     return success;
606   }
607
608   llvm_unreachable("All rootName and rootDirectory combinations should have "
609                    "occurred above!");
610 }
611
612 error_code create_directories(const Twine &path, bool &existed) {
613   SmallString<128> path_storage;
614   StringRef p = path.toStringRef(path_storage);
615
616   StringRef parent = path::parent_path(p);
617   bool parent_exists;
618
619   if (error_code ec = fs::exists(parent, parent_exists)) return ec;
620
621   if (!parent_exists)
622     return create_directories(parent, existed);
623
624   return create_directory(p, existed);
625 }
626
627 bool exists(file_status status) {
628   return status_known(status) && status.type() != file_type::file_not_found;
629 }
630
631 bool status_known(file_status s) {
632   return s.type() != file_type::status_error;
633 }
634
635 bool is_directory(file_status status) {
636   return status.type() == file_type::directory_file;
637 }
638
639 bool is_regular_file(file_status status) {
640   return status.type() == file_type::regular_file;
641 }
642
643 bool is_symlink(file_status status) {
644   return status.type() == file_type::symlink_file;
645 }
646
647 bool is_other(file_status status) {
648   return exists(status) &&
649          !is_regular_file(status) &&
650          !is_directory(status) &&
651          !is_symlink(status);
652 }
653
654 void directory_entry::replace_filename(const Twine &filename, file_status st,
655                                        file_status symlink_st) {
656   SmallString<128> path(Path.begin(), Path.end());
657   path::remove_filename(path);
658   path::append(path, filename);
659   Path = path.str();
660   Status = st;
661   SymlinkStatus = symlink_st;
662 }
663
664 error_code has_magic(const Twine &path, const Twine &magic, bool &result) {
665   SmallString<128> PathStorage;
666   SmallString<32>  MagicStorage;
667   StringRef Path  = path.toNullTerminatedStringRef(PathStorage);
668   StringRef Magic = magic.toNullTerminatedStringRef(MagicStorage);
669
670   assert(Magic.size() > 0 && "magic must be non-empty!");
671
672   SmallString<32> BufferStorage;
673   BufferStorage.reserve(Magic.size());
674
675   // Open file.
676   std::FILE *file = std::fopen(Path.data(), "rb");
677   if (file == 0)
678     return error_code(errno, posix_category());
679   size_t size = ::fread(BufferStorage.data(), 1, Magic.size(), file);
680   if (size != Magic.size()) {
681     int error = errno;
682     bool eof = std::feof(file) != 0;
683     std::fclose(file);
684     if (eof) {
685       // EOF, return false.
686       result = false;
687       return success;
688     }
689     return error_code(error, posix_category());
690   }
691   std::fclose(file);
692
693   if (std::memcmp(BufferStorage.data(), Magic.data(), Magic.size()) != 0)
694     result = false;
695   else
696     result = true;
697   return success;
698 }
699
700 namespace {
701 error_code remove_all_r(StringRef path, file_type ft, uint32_t &count) {
702   if (ft == file_type::directory_file) {
703     // This code would be a lot better with exceptions ;/.
704     error_code ec;
705     for (directory_iterator i(path, ec), e; i != e; i.increment(ec)) {
706       if (ec) return ec;
707       file_status st;
708       if (error_code ec = i->status(st)) return ec;
709       if (error_code ec = remove_all_r(i->path(), st.type(), count)) return ec;
710     }
711     bool obviously_this_exists;
712     if (error_code ec = remove(path, obviously_this_exists)) return ec;
713     assert(obviously_this_exists);
714     ++count; // Include the directory itself in the items removed.
715   } else {
716     bool obviously_this_exists;
717     if (error_code ec = remove(path, obviously_this_exists)) return ec;
718     assert(obviously_this_exists);
719     ++count;
720   }
721
722   return success;
723 }
724 }
725
726 error_code remove_all(const Twine &path, uint32_t &num_removed) {
727   SmallString<128> path_storage;
728   StringRef p = path.toStringRef(path_storage);
729
730   file_status fs;
731   if (error_code ec = status(path, fs))
732     return ec;
733   num_removed = 0;
734   return remove_all_r(p, fs.type(), num_removed);
735 }
736
737 error_code directory_entry::status(file_status &result) const {
738   return fs::status(Path, result);
739 }
740
741 } // end namespace fs
742 } // end namespace sys
743 } // end namespace llvm
744
745 // Include the truly platform-specific parts.
746 #if defined(LLVM_ON_UNIX)
747 #include "Unix/PathV2.inc"
748 #endif
749 #if defined(LLVM_ON_WIN32)
750 #include "Windows/PathV2.inc"
751 #endif