OSDN Git Service

[llvm-objcopy] Make .build-id linking atomic
[android-x86/external-llvm.git] / lib / Support / Path.cpp
1 //===-- Path.cpp - Implement OS Path Concept ------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements the operating system Path API.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/Support/Path.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/Config/llvm-config.h"
16 #include "llvm/Support/Endian.h"
17 #include "llvm/Support/Errc.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/Process.h"
21 #include "llvm/Support/Signals.h"
22 #include <cctype>
23 #include <cstring>
24
25 #if !defined(_MSC_VER) && !defined(__MINGW32__)
26 #include <unistd.h>
27 #else
28 #include <io.h>
29 #endif
30
31 using namespace llvm;
32 using namespace llvm::support::endian;
33
34 namespace {
35   using llvm::StringRef;
36   using llvm::sys::path::is_separator;
37   using llvm::sys::path::Style;
38
39   inline Style real_style(Style style) {
40 #ifdef _WIN32
41     return (style == Style::posix) ? Style::posix : Style::windows;
42 #else
43     return (style == Style::windows) ? Style::windows : Style::posix;
44 #endif
45   }
46
47   inline const char *separators(Style style) {
48     if (real_style(style) == Style::windows)
49       return "\\/";
50     return "/";
51   }
52
53   inline char preferred_separator(Style style) {
54     if (real_style(style) == Style::windows)
55       return '\\';
56     return '/';
57   }
58
59   StringRef find_first_component(StringRef path, Style style) {
60     // Look for this first component in the following order.
61     // * empty (in this case we return an empty string)
62     // * either C: or {//,\\}net.
63     // * {/,\}
64     // * {file,directory}name
65
66     if (path.empty())
67       return path;
68
69     if (real_style(style) == Style::windows) {
70       // C:
71       if (path.size() >= 2 &&
72           std::isalpha(static_cast<unsigned char>(path[0])) && path[1] == ':')
73         return path.substr(0, 2);
74     }
75
76     // //net
77     if ((path.size() > 2) && is_separator(path[0], style) &&
78         path[0] == path[1] && !is_separator(path[2], style)) {
79       // Find the next directory separator.
80       size_t end = path.find_first_of(separators(style), 2);
81       return path.substr(0, end);
82     }
83
84     // {/,\}
85     if (is_separator(path[0], style))
86       return path.substr(0, 1);
87
88     // * {file,directory}name
89     size_t end = path.find_first_of(separators(style));
90     return path.substr(0, end);
91   }
92
93   // Returns the first character of the filename in str. For paths ending in
94   // '/', it returns the position of the '/'.
95   size_t filename_pos(StringRef str, Style style) {
96     if (str.size() > 0 && is_separator(str[str.size() - 1], style))
97       return str.size() - 1;
98
99     size_t pos = str.find_last_of(separators(style), str.size() - 1);
100
101     if (real_style(style) == Style::windows) {
102       if (pos == StringRef::npos)
103         pos = str.find_last_of(':', str.size() - 2);
104     }
105
106     if (pos == StringRef::npos || (pos == 1 && is_separator(str[0], style)))
107       return 0;
108
109     return pos + 1;
110   }
111
112   // Returns the position of the root directory in str. If there is no root
113   // directory in str, it returns StringRef::npos.
114   size_t root_dir_start(StringRef str, Style style) {
115     // case "c:/"
116     if (real_style(style) == Style::windows) {
117       if (str.size() > 2 && str[1] == ':' && is_separator(str[2], style))
118         return 2;
119     }
120
121     // case "//net"
122     if (str.size() > 3 && is_separator(str[0], style) && str[0] == str[1] &&
123         !is_separator(str[2], style)) {
124       return str.find_first_of(separators(style), 2);
125     }
126
127     // case "/"
128     if (str.size() > 0 && is_separator(str[0], style))
129       return 0;
130
131     return StringRef::npos;
132   }
133
134   // Returns the position past the end of the "parent path" of path. The parent
135   // path will not end in '/', unless the parent is the root directory. If the
136   // path has no parent, 0 is returned.
137   size_t parent_path_end(StringRef path, Style style) {
138     size_t end_pos = filename_pos(path, style);
139
140     bool filename_was_sep =
141         path.size() > 0 && is_separator(path[end_pos], style);
142
143     // Skip separators until we reach root dir (or the start of the string).
144     size_t root_dir_pos = root_dir_start(path, style);
145     while (end_pos > 0 &&
146            (root_dir_pos == StringRef::npos || end_pos > root_dir_pos) &&
147            is_separator(path[end_pos - 1], style))
148       --end_pos;
149
150     if (end_pos == root_dir_pos && !filename_was_sep) {
151       // We've reached the root dir and the input path was *not* ending in a
152       // sequence of slashes. Include the root dir in the parent path.
153       return root_dir_pos + 1;
154     }
155
156     // Otherwise, just include before the last slash.
157     return end_pos;
158   }
159 } // end unnamed namespace
160
161 enum FSEntity {
162   FS_Dir,
163   FS_File,
164   FS_Name
165 };
166
167 static std::error_code
168 createUniqueEntity(const Twine &Model, int &ResultFD,
169                    SmallVectorImpl<char> &ResultPath, bool MakeAbsolute,
170                    unsigned Mode, FSEntity Type,
171                    sys::fs::OpenFlags Flags = sys::fs::OF_None) {
172
173   // Limit the number of attempts we make, so that we don't infinite loop. E.g.
174   // "permission denied" could be for a specific file (so we retry with a
175   // different name) or for the whole directory (retry would always fail).
176   // Checking which is racy, so we try a number of times, then give up.
177   std::error_code EC;
178   for (int Retries = 128; Retries > 0; --Retries) {
179     sys::fs::createUniquePath(Model, ResultPath, MakeAbsolute);
180     // Try to open + create the file.
181     switch (Type) {
182     case FS_File: {
183       EC = sys::fs::openFileForReadWrite(Twine(ResultPath.begin()), ResultFD,
184                                          sys::fs::CD_CreateNew, Flags, Mode);
185       if (EC) {
186         // errc::permission_denied happens on Windows when we try to open a file
187         // that has been marked for deletion.
188         if (EC == errc::file_exists || EC == errc::permission_denied)
189           continue;
190         return EC;
191       }
192
193       return std::error_code();
194     }
195
196     case FS_Name: {
197       EC = sys::fs::access(ResultPath.begin(), sys::fs::AccessMode::Exist);
198       if (EC == errc::no_such_file_or_directory)
199         return std::error_code();
200       if (EC)
201         return EC;
202       continue;
203     }
204
205     case FS_Dir: {
206       EC = sys::fs::create_directory(ResultPath.begin(), false);
207       if (EC) {
208         if (EC == errc::file_exists)
209           continue;
210         return EC;
211       }
212       return std::error_code();
213     }
214     }
215     llvm_unreachable("Invalid Type");
216   }
217   return EC;
218 }
219
220 namespace llvm {
221 namespace sys  {
222 namespace path {
223
224 const_iterator begin(StringRef path, Style style) {
225   const_iterator i;
226   i.Path      = path;
227   i.Component = find_first_component(path, style);
228   i.Position  = 0;
229   i.S = style;
230   return i;
231 }
232
233 const_iterator end(StringRef path) {
234   const_iterator i;
235   i.Path      = path;
236   i.Position  = path.size();
237   return i;
238 }
239
240 const_iterator &const_iterator::operator++() {
241   assert(Position < Path.size() && "Tried to increment past end!");
242
243   // Increment Position to past the current component
244   Position += Component.size();
245
246   // Check for end.
247   if (Position == Path.size()) {
248     Component = StringRef();
249     return *this;
250   }
251
252   // Both POSIX and Windows treat paths that begin with exactly two separators
253   // specially.
254   bool was_net = Component.size() > 2 && is_separator(Component[0], S) &&
255                  Component[1] == Component[0] && !is_separator(Component[2], S);
256
257   // Handle separators.
258   if (is_separator(Path[Position], S)) {
259     // Root dir.
260     if (was_net ||
261         // c:/
262         (real_style(S) == Style::windows && Component.endswith(":"))) {
263       Component = Path.substr(Position, 1);
264       return *this;
265     }
266
267     // Skip extra separators.
268     while (Position != Path.size() && is_separator(Path[Position], S)) {
269       ++Position;
270     }
271
272     // Treat trailing '/' as a '.', unless it is the root dir.
273     if (Position == Path.size() && Component != "/") {
274       --Position;
275       Component = ".";
276       return *this;
277     }
278   }
279
280   // Find next component.
281   size_t end_pos = Path.find_first_of(separators(S), Position);
282   Component = Path.slice(Position, end_pos);
283
284   return *this;
285 }
286
287 bool const_iterator::operator==(const const_iterator &RHS) const {
288   return Path.begin() == RHS.Path.begin() && Position == RHS.Position;
289 }
290
291 ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
292   return Position - RHS.Position;
293 }
294
295 reverse_iterator rbegin(StringRef Path, Style style) {
296   reverse_iterator I;
297   I.Path = Path;
298   I.Position = Path.size();
299   I.S = style;
300   return ++I;
301 }
302
303 reverse_iterator rend(StringRef Path) {
304   reverse_iterator I;
305   I.Path = Path;
306   I.Component = Path.substr(0, 0);
307   I.Position = 0;
308   return I;
309 }
310
311 reverse_iterator &reverse_iterator::operator++() {
312   size_t root_dir_pos = root_dir_start(Path, S);
313
314   // Skip separators unless it's the root directory.
315   size_t end_pos = Position;
316   while (end_pos > 0 && (end_pos - 1) != root_dir_pos &&
317          is_separator(Path[end_pos - 1], S))
318     --end_pos;
319
320   // Treat trailing '/' as a '.', unless it is the root dir.
321   if (Position == Path.size() && !Path.empty() &&
322       is_separator(Path.back(), S) &&
323       (root_dir_pos == StringRef::npos || end_pos - 1 > root_dir_pos)) {
324     --Position;
325     Component = ".";
326     return *this;
327   }
328
329   // Find next separator.
330   size_t start_pos = filename_pos(Path.substr(0, end_pos), S);
331   Component = Path.slice(start_pos, end_pos);
332   Position = start_pos;
333   return *this;
334 }
335
336 bool reverse_iterator::operator==(const reverse_iterator &RHS) const {
337   return Path.begin() == RHS.Path.begin() && Component == RHS.Component &&
338          Position == RHS.Position;
339 }
340
341 ptrdiff_t reverse_iterator::operator-(const reverse_iterator &RHS) const {
342   return Position - RHS.Position;
343 }
344
345 StringRef root_path(StringRef path, Style style) {
346   const_iterator b = begin(path, style), pos = b, e = end(path);
347   if (b != e) {
348     bool has_net =
349         b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
350     bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
351
352     if (has_net || has_drive) {
353       if ((++pos != e) && is_separator((*pos)[0], style)) {
354         // {C:/,//net/}, so get the first two components.
355         return path.substr(0, b->size() + pos->size());
356       } else {
357         // just {C:,//net}, return the first component.
358         return *b;
359       }
360     }
361
362     // POSIX style root directory.
363     if (is_separator((*b)[0], style)) {
364       return *b;
365     }
366   }
367
368   return StringRef();
369 }
370
371 StringRef root_name(StringRef path, Style style) {
372   const_iterator b = begin(path, style), e = end(path);
373   if (b != e) {
374     bool has_net =
375         b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
376     bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
377
378     if (has_net || has_drive) {
379       // just {C:,//net}, return the first component.
380       return *b;
381     }
382   }
383
384   // No path or no name.
385   return StringRef();
386 }
387
388 StringRef root_directory(StringRef path, Style style) {
389   const_iterator b = begin(path, style), pos = b, e = end(path);
390   if (b != e) {
391     bool has_net =
392         b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
393     bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
394
395     if ((has_net || has_drive) &&
396         // {C:,//net}, skip to the next component.
397         (++pos != e) && is_separator((*pos)[0], style)) {
398       return *pos;
399     }
400
401     // POSIX style root directory.
402     if (!has_net && is_separator((*b)[0], style)) {
403       return *b;
404     }
405   }
406
407   // No path or no root.
408   return StringRef();
409 }
410
411 StringRef relative_path(StringRef path, Style style) {
412   StringRef root = root_path(path, style);
413   return path.substr(root.size());
414 }
415
416 void append(SmallVectorImpl<char> &path, Style style, const Twine &a,
417             const Twine &b, const Twine &c, const Twine &d) {
418   SmallString<32> a_storage;
419   SmallString<32> b_storage;
420   SmallString<32> c_storage;
421   SmallString<32> d_storage;
422
423   SmallVector<StringRef, 4> components;
424   if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage));
425   if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage));
426   if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage));
427   if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage));
428
429   for (auto &component : components) {
430     bool path_has_sep =
431         !path.empty() && is_separator(path[path.size() - 1], style);
432     if (path_has_sep) {
433       // Strip separators from beginning of component.
434       size_t loc = component.find_first_not_of(separators(style));
435       StringRef c = component.substr(loc);
436
437       // Append it.
438       path.append(c.begin(), c.end());
439       continue;
440     }
441
442     bool component_has_sep =
443         !component.empty() && is_separator(component[0], style);
444     if (!component_has_sep &&
445         !(path.empty() || has_root_name(component, style))) {
446       // Add a separator.
447       path.push_back(preferred_separator(style));
448     }
449
450     path.append(component.begin(), component.end());
451   }
452 }
453
454 void append(SmallVectorImpl<char> &path, const Twine &a, const Twine &b,
455             const Twine &c, const Twine &d) {
456   append(path, Style::native, a, b, c, d);
457 }
458
459 void append(SmallVectorImpl<char> &path, const_iterator begin,
460             const_iterator end, Style style) {
461   for (; begin != end; ++begin)
462     path::append(path, style, *begin);
463 }
464
465 StringRef parent_path(StringRef path, Style style) {
466   size_t end_pos = parent_path_end(path, style);
467   if (end_pos == StringRef::npos)
468     return StringRef();
469   else
470     return path.substr(0, end_pos);
471 }
472
473 void remove_filename(SmallVectorImpl<char> &path, Style style) {
474   size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()), style);
475   if (end_pos != StringRef::npos)
476     path.set_size(end_pos);
477 }
478
479 void replace_extension(SmallVectorImpl<char> &path, const Twine &extension,
480                        Style style) {
481   StringRef p(path.begin(), path.size());
482   SmallString<32> ext_storage;
483   StringRef ext = extension.toStringRef(ext_storage);
484
485   // Erase existing extension.
486   size_t pos = p.find_last_of('.');
487   if (pos != StringRef::npos && pos >= filename_pos(p, style))
488     path.set_size(pos);
489
490   // Append '.' if needed.
491   if (ext.size() > 0 && ext[0] != '.')
492     path.push_back('.');
493
494   // Append extension.
495   path.append(ext.begin(), ext.end());
496 }
497
498 void replace_path_prefix(SmallVectorImpl<char> &Path,
499                          const StringRef &OldPrefix, const StringRef &NewPrefix,
500                          Style style) {
501   if (OldPrefix.empty() && NewPrefix.empty())
502     return;
503
504   StringRef OrigPath(Path.begin(), Path.size());
505   if (!OrigPath.startswith(OldPrefix))
506     return;
507
508   // If prefixes have the same size we can simply copy the new one over.
509   if (OldPrefix.size() == NewPrefix.size()) {
510     llvm::copy(NewPrefix, Path.begin());
511     return;
512   }
513
514   StringRef RelPath = OrigPath.substr(OldPrefix.size());
515   SmallString<256> NewPath;
516   path::append(NewPath, style, NewPrefix);
517   path::append(NewPath, style, RelPath);
518   Path.swap(NewPath);
519 }
520
521 void native(const Twine &path, SmallVectorImpl<char> &result, Style style) {
522   assert((!path.isSingleStringRef() ||
523           path.getSingleStringRef().data() != result.data()) &&
524          "path and result are not allowed to overlap!");
525   // Clear result.
526   result.clear();
527   path.toVector(result);
528   native(result, style);
529 }
530
531 void native(SmallVectorImpl<char> &Path, Style style) {
532   if (Path.empty())
533     return;
534   if (real_style(style) == Style::windows) {
535     std::replace(Path.begin(), Path.end(), '/', '\\');
536     if (Path[0] == '~' && (Path.size() == 1 || is_separator(Path[1], style))) {
537       SmallString<128> PathHome;
538       home_directory(PathHome);
539       PathHome.append(Path.begin() + 1, Path.end());
540       Path = PathHome;
541     }
542   } else {
543     for (auto PI = Path.begin(), PE = Path.end(); PI < PE; ++PI) {
544       if (*PI == '\\') {
545         auto PN = PI + 1;
546         if (PN < PE && *PN == '\\')
547           ++PI; // increment once, the for loop will move over the escaped slash
548         else
549           *PI = '/';
550       }
551     }
552   }
553 }
554
555 std::string convert_to_slash(StringRef path, Style style) {
556   if (real_style(style) != Style::windows)
557     return path;
558
559   std::string s = path.str();
560   std::replace(s.begin(), s.end(), '\\', '/');
561   return s;
562 }
563
564 StringRef filename(StringRef path, Style style) { return *rbegin(path, style); }
565
566 StringRef stem(StringRef path, Style style) {
567   StringRef fname = filename(path, style);
568   size_t pos = fname.find_last_of('.');
569   if (pos == StringRef::npos)
570     return fname;
571   else
572     if ((fname.size() == 1 && fname == ".") ||
573         (fname.size() == 2 && fname == ".."))
574       return fname;
575     else
576       return fname.substr(0, pos);
577 }
578
579 StringRef extension(StringRef path, Style style) {
580   StringRef fname = filename(path, style);
581   size_t pos = fname.find_last_of('.');
582   if (pos == StringRef::npos)
583     return StringRef();
584   else
585     if ((fname.size() == 1 && fname == ".") ||
586         (fname.size() == 2 && fname == ".."))
587       return StringRef();
588     else
589       return fname.substr(pos);
590 }
591
592 bool is_separator(char value, Style style) {
593   if (value == '/')
594     return true;
595   if (real_style(style) == Style::windows)
596     return value == '\\';
597   return false;
598 }
599
600 StringRef get_separator(Style style) {
601   if (real_style(style) == Style::windows)
602     return "\\";
603   return "/";
604 }
605
606 bool has_root_name(const Twine &path, Style style) {
607   SmallString<128> path_storage;
608   StringRef p = path.toStringRef(path_storage);
609
610   return !root_name(p, style).empty();
611 }
612
613 bool has_root_directory(const Twine &path, Style style) {
614   SmallString<128> path_storage;
615   StringRef p = path.toStringRef(path_storage);
616
617   return !root_directory(p, style).empty();
618 }
619
620 bool has_root_path(const Twine &path, Style style) {
621   SmallString<128> path_storage;
622   StringRef p = path.toStringRef(path_storage);
623
624   return !root_path(p, style).empty();
625 }
626
627 bool has_relative_path(const Twine &path, Style style) {
628   SmallString<128> path_storage;
629   StringRef p = path.toStringRef(path_storage);
630
631   return !relative_path(p, style).empty();
632 }
633
634 bool has_filename(const Twine &path, Style style) {
635   SmallString<128> path_storage;
636   StringRef p = path.toStringRef(path_storage);
637
638   return !filename(p, style).empty();
639 }
640
641 bool has_parent_path(const Twine &path, Style style) {
642   SmallString<128> path_storage;
643   StringRef p = path.toStringRef(path_storage);
644
645   return !parent_path(p, style).empty();
646 }
647
648 bool has_stem(const Twine &path, Style style) {
649   SmallString<128> path_storage;
650   StringRef p = path.toStringRef(path_storage);
651
652   return !stem(p, style).empty();
653 }
654
655 bool has_extension(const Twine &path, Style style) {
656   SmallString<128> path_storage;
657   StringRef p = path.toStringRef(path_storage);
658
659   return !extension(p, style).empty();
660 }
661
662 bool is_absolute(const Twine &path, Style style) {
663   SmallString<128> path_storage;
664   StringRef p = path.toStringRef(path_storage);
665
666   bool rootDir = has_root_directory(p, style);
667   bool rootName =
668       (real_style(style) != Style::windows) || has_root_name(p, style);
669
670   return rootDir && rootName;
671 }
672
673 bool is_relative(const Twine &path, Style style) {
674   return !is_absolute(path, style);
675 }
676
677 StringRef remove_leading_dotslash(StringRef Path, Style style) {
678   // Remove leading "./" (or ".//" or "././" etc.)
679   while (Path.size() > 2 && Path[0] == '.' && is_separator(Path[1], style)) {
680     Path = Path.substr(2);
681     while (Path.size() > 0 && is_separator(Path[0], style))
682       Path = Path.substr(1);
683   }
684   return Path;
685 }
686
687 static SmallString<256> remove_dots(StringRef path, bool remove_dot_dot,
688                                     Style style) {
689   SmallVector<StringRef, 16> components;
690
691   // Skip the root path, then look for traversal in the components.
692   StringRef rel = path::relative_path(path, style);
693   for (StringRef C :
694        llvm::make_range(path::begin(rel, style), path::end(rel))) {
695     if (C == ".")
696       continue;
697     // Leading ".." will remain in the path unless it's at the root.
698     if (remove_dot_dot && C == "..") {
699       if (!components.empty() && components.back() != "..") {
700         components.pop_back();
701         continue;
702       }
703       if (path::is_absolute(path, style))
704         continue;
705     }
706     components.push_back(C);
707   }
708
709   SmallString<256> buffer = path::root_path(path, style);
710   for (StringRef C : components)
711     path::append(buffer, style, C);
712   return buffer;
713 }
714
715 bool remove_dots(SmallVectorImpl<char> &path, bool remove_dot_dot,
716                  Style style) {
717   StringRef p(path.data(), path.size());
718
719   SmallString<256> result = remove_dots(p, remove_dot_dot, style);
720   if (result == path)
721     return false;
722
723   path.swap(result);
724   return true;
725 }
726
727 } // end namespace path
728
729 namespace fs {
730
731 std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
732   file_status Status;
733   std::error_code EC = status(Path, Status);
734   if (EC)
735     return EC;
736   Result = Status.getUniqueID();
737   return std::error_code();
738 }
739
740 void createUniquePath(const Twine &Model, SmallVectorImpl<char> &ResultPath,
741                       bool MakeAbsolute) {
742   SmallString<128> ModelStorage;
743   Model.toVector(ModelStorage);
744
745   if (MakeAbsolute) {
746     // Make model absolute by prepending a temp directory if it's not already.
747     if (!sys::path::is_absolute(Twine(ModelStorage))) {
748       SmallString<128> TDir;
749       sys::path::system_temp_directory(true, TDir);
750       sys::path::append(TDir, Twine(ModelStorage));
751       ModelStorage.swap(TDir);
752     }
753   }
754
755   ResultPath = ModelStorage;
756   ResultPath.push_back(0);
757   ResultPath.pop_back();
758
759   // Replace '%' with random chars.
760   for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
761     if (ModelStorage[i] == '%')
762       ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
763   }
764 }
765
766 std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
767                                  SmallVectorImpl<char> &ResultPath,
768                                  unsigned Mode) {
769   return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File);
770 }
771
772 static std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
773                                         SmallVectorImpl<char> &ResultPath,
774                                         unsigned Mode, OpenFlags Flags) {
775   return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File,
776                             Flags);
777 }
778
779 std::error_code createUniqueFile(const Twine &Model,
780                                  SmallVectorImpl<char> &ResultPath,
781                                  unsigned Mode) {
782   int FD;
783   auto EC = createUniqueFile(Model, FD, ResultPath, Mode);
784   if (EC)
785     return EC;
786   // FD is only needed to avoid race conditions. Close it right away.
787   close(FD);
788   return EC;
789 }
790
791 static std::error_code
792 createTemporaryFile(const Twine &Model, int &ResultFD,
793                     llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
794   SmallString<128> Storage;
795   StringRef P = Model.toNullTerminatedStringRef(Storage);
796   assert(P.find_first_of(separators(Style::native)) == StringRef::npos &&
797          "Model must be a simple filename.");
798   // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
799   return createUniqueEntity(P.begin(), ResultFD, ResultPath, true,
800                             owner_read | owner_write, Type);
801 }
802
803 static std::error_code
804 createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
805                     llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
806   const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
807   return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
808                              Type);
809 }
810
811 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
812                                     int &ResultFD,
813                                     SmallVectorImpl<char> &ResultPath) {
814   return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File);
815 }
816
817 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
818                                     SmallVectorImpl<char> &ResultPath) {
819   int FD;
820   auto EC = createTemporaryFile(Prefix, Suffix, FD, ResultPath);
821   if (EC)
822     return EC;
823   // FD is only needed to avoid race conditions. Close it right away.
824   close(FD);
825   return EC;
826 }
827
828
829 // This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
830 // for consistency. We should try using mkdtemp.
831 std::error_code createUniqueDirectory(const Twine &Prefix,
832                                       SmallVectorImpl<char> &ResultPath) {
833   int Dummy;
834   return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath, true, 0,
835                             FS_Dir);
836 }
837
838 std::error_code
839 getPotentiallyUniqueFileName(const Twine &Model,
840                              SmallVectorImpl<char> &ResultPath) {
841   int Dummy;
842   return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
843 }
844
845 std::error_code
846 getPotentiallyUniqueTempFileName(const Twine &Prefix, StringRef Suffix,
847                                  SmallVectorImpl<char> &ResultPath) {
848   int Dummy;
849   return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
850 }
851
852 void make_absolute(const Twine &current_directory,
853                    SmallVectorImpl<char> &path) {
854   StringRef p(path.data(), path.size());
855
856   bool rootDirectory = path::has_root_directory(p);
857   bool rootName =
858       (real_style(Style::native) != Style::windows) || path::has_root_name(p);
859
860   // Already absolute.
861   if (rootName && rootDirectory)
862     return;
863
864   // All of the following conditions will need the current directory.
865   SmallString<128> current_dir;
866   current_directory.toVector(current_dir);
867
868   // Relative path. Prepend the current directory.
869   if (!rootName && !rootDirectory) {
870     // Append path to the current directory.
871     path::append(current_dir, p);
872     // Set path to the result.
873     path.swap(current_dir);
874     return;
875   }
876
877   if (!rootName && rootDirectory) {
878     StringRef cdrn = path::root_name(current_dir);
879     SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
880     path::append(curDirRootName, p);
881     // Set path to the result.
882     path.swap(curDirRootName);
883     return;
884   }
885
886   if (rootName && !rootDirectory) {
887     StringRef pRootName      = path::root_name(p);
888     StringRef bRootDirectory = path::root_directory(current_dir);
889     StringRef bRelativePath  = path::relative_path(current_dir);
890     StringRef pRelativePath  = path::relative_path(p);
891
892     SmallString<128> res;
893     path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
894     path.swap(res);
895     return;
896   }
897
898   llvm_unreachable("All rootName and rootDirectory combinations should have "
899                    "occurred above!");
900 }
901
902 std::error_code make_absolute(SmallVectorImpl<char> &path) {
903   if (path::is_absolute(path))
904     return {};
905
906   SmallString<128> current_dir;
907   if (std::error_code ec = current_path(current_dir))
908     return ec;
909
910   make_absolute(current_dir, path);
911   return {};
912 }
913
914 std::error_code create_directories(const Twine &Path, bool IgnoreExisting,
915                                    perms Perms) {
916   SmallString<128> PathStorage;
917   StringRef P = Path.toStringRef(PathStorage);
918
919   // Be optimistic and try to create the directory
920   std::error_code EC = create_directory(P, IgnoreExisting, Perms);
921   // If we succeeded, or had any error other than the parent not existing, just
922   // return it.
923   if (EC != errc::no_such_file_or_directory)
924     return EC;
925
926   // We failed because of a no_such_file_or_directory, try to create the
927   // parent.
928   StringRef Parent = path::parent_path(P);
929   if (Parent.empty())
930     return EC;
931
932   if ((EC = create_directories(Parent, IgnoreExisting, Perms)))
933       return EC;
934
935   return create_directory(P, IgnoreExisting, Perms);
936 }
937
938 static std::error_code copy_file_internal(int ReadFD, int WriteFD) {
939   const size_t BufSize = 4096;
940   char *Buf = new char[BufSize];
941   int BytesRead = 0, BytesWritten = 0;
942   for (;;) {
943     BytesRead = read(ReadFD, Buf, BufSize);
944     if (BytesRead <= 0)
945       break;
946     while (BytesRead) {
947       BytesWritten = write(WriteFD, Buf, BytesRead);
948       if (BytesWritten < 0)
949         break;
950       BytesRead -= BytesWritten;
951     }
952     if (BytesWritten < 0)
953       break;
954   }
955   delete[] Buf;
956
957   if (BytesRead < 0 || BytesWritten < 0)
958     return std::error_code(errno, std::generic_category());
959   return std::error_code();
960 }
961
962 std::error_code copy_file(const Twine &From, const Twine &To) {
963   int ReadFD, WriteFD;
964   if (std::error_code EC = openFileForRead(From, ReadFD, OF_None))
965     return EC;
966   if (std::error_code EC =
967           openFileForWrite(To, WriteFD, CD_CreateAlways, OF_None)) {
968     close(ReadFD);
969     return EC;
970   }
971
972   std::error_code EC = copy_file_internal(ReadFD, WriteFD);
973
974   close(ReadFD);
975   close(WriteFD);
976
977   return EC;
978 }
979
980 std::error_code copy_file(const Twine &From, int ToFD) {
981   int ReadFD;
982   if (std::error_code EC = openFileForRead(From, ReadFD, OF_None))
983     return EC;
984
985   std::error_code EC = copy_file_internal(ReadFD, ToFD);
986
987   close(ReadFD);
988
989   return EC;
990 }
991
992 ErrorOr<MD5::MD5Result> md5_contents(int FD) {
993   MD5 Hash;
994
995   constexpr size_t BufSize = 4096;
996   std::vector<uint8_t> Buf(BufSize);
997   int BytesRead = 0;
998   for (;;) {
999     BytesRead = read(FD, Buf.data(), BufSize);
1000     if (BytesRead <= 0)
1001       break;
1002     Hash.update(makeArrayRef(Buf.data(), BytesRead));
1003   }
1004
1005   if (BytesRead < 0)
1006     return std::error_code(errno, std::generic_category());
1007   MD5::MD5Result Result;
1008   Hash.final(Result);
1009   return Result;
1010 }
1011
1012 ErrorOr<MD5::MD5Result> md5_contents(const Twine &Path) {
1013   int FD;
1014   if (auto EC = openFileForRead(Path, FD, OF_None))
1015     return EC;
1016
1017   auto Result = md5_contents(FD);
1018   close(FD);
1019   return Result;
1020 }
1021
1022 bool exists(const basic_file_status &status) {
1023   return status_known(status) && status.type() != file_type::file_not_found;
1024 }
1025
1026 bool status_known(const basic_file_status &s) {
1027   return s.type() != file_type::status_error;
1028 }
1029
1030 file_type get_file_type(const Twine &Path, bool Follow) {
1031   file_status st;
1032   if (status(Path, st, Follow))
1033     return file_type::status_error;
1034   return st.type();
1035 }
1036
1037 bool is_directory(const basic_file_status &status) {
1038   return status.type() == file_type::directory_file;
1039 }
1040
1041 std::error_code is_directory(const Twine &path, bool &result) {
1042   file_status st;
1043   if (std::error_code ec = status(path, st))
1044     return ec;
1045   result = is_directory(st);
1046   return std::error_code();
1047 }
1048
1049 bool is_regular_file(const basic_file_status &status) {
1050   return status.type() == file_type::regular_file;
1051 }
1052
1053 std::error_code is_regular_file(const Twine &path, bool &result) {
1054   file_status st;
1055   if (std::error_code ec = status(path, st))
1056     return ec;
1057   result = is_regular_file(st);
1058   return std::error_code();
1059 }
1060
1061 bool is_symlink_file(const basic_file_status &status) {
1062   return status.type() == file_type::symlink_file;
1063 }
1064
1065 std::error_code is_symlink_file(const Twine &path, bool &result) {
1066   file_status st;
1067   if (std::error_code ec = status(path, st, false))
1068     return ec;
1069   result = is_symlink_file(st);
1070   return std::error_code();
1071 }
1072
1073 bool is_other(const basic_file_status &status) {
1074   return exists(status) &&
1075          !is_regular_file(status) &&
1076          !is_directory(status);
1077 }
1078
1079 std::error_code is_other(const Twine &Path, bool &Result) {
1080   file_status FileStatus;
1081   if (std::error_code EC = status(Path, FileStatus))
1082     return EC;
1083   Result = is_other(FileStatus);
1084   return std::error_code();
1085 }
1086
1087 void directory_entry::replace_filename(const Twine &Filename, file_type Type,
1088                                        basic_file_status Status) {
1089   SmallString<128> PathStr = path::parent_path(Path);
1090   path::append(PathStr, Filename);
1091   this->Path = PathStr.str();
1092   this->Type = Type;
1093   this->Status = Status;
1094 }
1095
1096 ErrorOr<perms> getPermissions(const Twine &Path) {
1097   file_status Status;
1098   if (std::error_code EC = status(Path, Status))
1099     return EC;
1100
1101   return Status.permissions();
1102 }
1103
1104 } // end namespace fs
1105 } // end namespace sys
1106 } // end namespace llvm
1107
1108 // Include the truly platform-specific parts.
1109 #if defined(LLVM_ON_UNIX)
1110 #include "Unix/Path.inc"
1111 #endif
1112 #if defined(_WIN32)
1113 #include "Windows/Path.inc"
1114 #endif
1115
1116 namespace llvm {
1117 namespace sys {
1118 namespace fs {
1119 TempFile::TempFile(StringRef Name, int FD) : TmpName(Name), FD(FD) {}
1120 TempFile::TempFile(TempFile &&Other) { *this = std::move(Other); }
1121 TempFile &TempFile::operator=(TempFile &&Other) {
1122   TmpName = std::move(Other.TmpName);
1123   FD = Other.FD;
1124   Other.Done = true;
1125   return *this;
1126 }
1127
1128 TempFile::~TempFile() { assert(Done); }
1129
1130 Error TempFile::discard() {
1131   Done = true;
1132   if (FD != -1 && close(FD) == -1) {
1133     std::error_code EC = std::error_code(errno, std::generic_category());
1134     return errorCodeToError(EC);
1135   }
1136   FD = -1;
1137
1138 #ifdef _WIN32
1139   // On windows closing will remove the file.
1140   TmpName = "";
1141   return Error::success();
1142 #else
1143   // Always try to close and remove.
1144   std::error_code RemoveEC;
1145   if (!TmpName.empty()) {
1146     RemoveEC = fs::remove(TmpName);
1147     sys::DontRemoveFileOnSignal(TmpName);
1148     if (!RemoveEC)
1149       TmpName = "";
1150   }
1151   return errorCodeToError(RemoveEC);
1152 #endif
1153 }
1154
1155 Error TempFile::keep(const Twine &Name) {
1156   assert(!Done);
1157   Done = true;
1158   // Always try to close and rename.
1159 #ifdef _WIN32
1160   // If we can't cancel the delete don't rename.
1161   auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
1162   std::error_code RenameEC = setDeleteDisposition(H, false);
1163   if (!RenameEC) {
1164     RenameEC = rename_fd(FD, Name);
1165     // If rename failed because it's cross-device, copy instead
1166     if (RenameEC ==
1167       std::error_code(ERROR_NOT_SAME_DEVICE, std::system_category())) {
1168       RenameEC = copy_file(TmpName, Name);
1169       setDeleteDisposition(H, true);
1170     }
1171   }
1172
1173   // If we can't rename, discard the temporary file.
1174   if (RenameEC)
1175     setDeleteDisposition(H, true);
1176 #else
1177   std::error_code RenameEC = fs::rename(TmpName, Name);
1178   if (RenameEC) {
1179     // If we can't rename, try to copy to work around cross-device link issues.
1180     RenameEC = sys::fs::copy_file(TmpName, Name);
1181     // If we can't rename or copy, discard the temporary file.
1182     if (RenameEC)
1183       remove(TmpName);
1184   }
1185   sys::DontRemoveFileOnSignal(TmpName);
1186 #endif
1187
1188   if (!RenameEC)
1189     TmpName = "";
1190
1191   if (close(FD) == -1) {
1192     std::error_code EC(errno, std::generic_category());
1193     return errorCodeToError(EC);
1194   }
1195   FD = -1;
1196
1197   return errorCodeToError(RenameEC);
1198 }
1199
1200 Error TempFile::keep() {
1201   assert(!Done);
1202   Done = true;
1203
1204 #ifdef _WIN32
1205   auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
1206   if (std::error_code EC = setDeleteDisposition(H, false))
1207     return errorCodeToError(EC);
1208 #else
1209   sys::DontRemoveFileOnSignal(TmpName);
1210 #endif
1211
1212   TmpName = "";
1213
1214   if (close(FD) == -1) {
1215     std::error_code EC(errno, std::generic_category());
1216     return errorCodeToError(EC);
1217   }
1218   FD = -1;
1219
1220   return Error::success();
1221 }
1222
1223 Expected<TempFile> TempFile::create(const Twine &Model, unsigned Mode) {
1224   int FD;
1225   SmallString<128> ResultPath;
1226   if (std::error_code EC =
1227           createUniqueFile(Model, FD, ResultPath, Mode, OF_Delete))
1228     return errorCodeToError(EC);
1229
1230   TempFile Ret(ResultPath, FD);
1231 #ifndef _WIN32
1232   if (sys::RemoveFileOnSignal(ResultPath)) {
1233     // Make sure we delete the file when RemoveFileOnSignal fails.
1234     consumeError(Ret.discard());
1235     std::error_code EC(errc::operation_not_permitted);
1236     return errorCodeToError(EC);
1237   }
1238 #endif
1239   return std::move(Ret);
1240 }
1241 }
1242
1243 } // end namsspace sys
1244 } // end namespace llvm