xref: /freebsd-src/contrib/llvm-project/llvm/lib/Support/Path.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===-- Path.cpp - Implement OS Path Concept ------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric //  This file implements the operating system Path API.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "llvm/Support/Path.h"
140b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
1504eeddc0SDimitry Andric #include "llvm/ADT/ScopeExit.h"
1606c3fb27SDimitry Andric #include "llvm/ADT/StringExtras.h"
17349cc55cSDimitry Andric #include "llvm/Config/config.h"
180b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
190b57cec5SDimitry Andric #include "llvm/Support/Endian.h"
200b57cec5SDimitry Andric #include "llvm/Support/Errc.h"
210b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
220b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
230b57cec5SDimitry Andric #include "llvm/Support/Process.h"
240b57cec5SDimitry Andric #include "llvm/Support/Signals.h"
250b57cec5SDimitry Andric #include <cctype>
260b57cec5SDimitry Andric 
270b57cec5SDimitry Andric #if !defined(_MSC_VER) && !defined(__MINGW32__)
280b57cec5SDimitry Andric #include <unistd.h>
290b57cec5SDimitry Andric #else
300b57cec5SDimitry Andric #include <io.h>
310b57cec5SDimitry Andric #endif
320b57cec5SDimitry Andric 
330b57cec5SDimitry Andric using namespace llvm;
340b57cec5SDimitry Andric using namespace llvm::support::endian;
350b57cec5SDimitry Andric 
360b57cec5SDimitry Andric namespace {
370b57cec5SDimitry Andric   using llvm::StringRef;
380b57cec5SDimitry Andric   using llvm::sys::path::is_separator;
390b57cec5SDimitry Andric   using llvm::sys::path::Style;
400b57cec5SDimitry Andric 
410b57cec5SDimitry Andric   inline Style real_style(Style style) {
42349cc55cSDimitry Andric     if (style != Style::native)
43349cc55cSDimitry Andric       return style;
44349cc55cSDimitry Andric     if (is_style_posix(style))
45349cc55cSDimitry Andric       return Style::posix;
46349cc55cSDimitry Andric     return LLVM_WINDOWS_PREFER_FORWARD_SLASH ? Style::windows_slash
47349cc55cSDimitry Andric                                              : Style::windows_backslash;
480b57cec5SDimitry Andric   }
490b57cec5SDimitry Andric 
500b57cec5SDimitry Andric   inline const char *separators(Style style) {
51349cc55cSDimitry Andric     if (is_style_windows(style))
520b57cec5SDimitry Andric       return "\\/";
530b57cec5SDimitry Andric     return "/";
540b57cec5SDimitry Andric   }
550b57cec5SDimitry Andric 
560b57cec5SDimitry Andric   inline char preferred_separator(Style style) {
570b57cec5SDimitry Andric     if (real_style(style) == Style::windows)
580b57cec5SDimitry Andric       return '\\';
590b57cec5SDimitry Andric     return '/';
600b57cec5SDimitry Andric   }
610b57cec5SDimitry Andric 
620b57cec5SDimitry Andric   StringRef find_first_component(StringRef path, Style style) {
630b57cec5SDimitry Andric     // Look for this first component in the following order.
640b57cec5SDimitry Andric     // * empty (in this case we return an empty string)
650b57cec5SDimitry Andric     // * either C: or {//,\\}net.
660b57cec5SDimitry Andric     // * {/,\}
670b57cec5SDimitry Andric     // * {file,directory}name
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric     if (path.empty())
700b57cec5SDimitry Andric       return path;
710b57cec5SDimitry Andric 
72349cc55cSDimitry Andric     if (is_style_windows(style)) {
730b57cec5SDimitry Andric       // C:
740b57cec5SDimitry Andric       if (path.size() >= 2 &&
750b57cec5SDimitry Andric           std::isalpha(static_cast<unsigned char>(path[0])) && path[1] == ':')
760b57cec5SDimitry Andric         return path.substr(0, 2);
770b57cec5SDimitry Andric     }
780b57cec5SDimitry Andric 
790b57cec5SDimitry Andric     // //net
800b57cec5SDimitry Andric     if ((path.size() > 2) && is_separator(path[0], style) &&
810b57cec5SDimitry Andric         path[0] == path[1] && !is_separator(path[2], style)) {
820b57cec5SDimitry Andric       // Find the next directory separator.
830b57cec5SDimitry Andric       size_t end = path.find_first_of(separators(style), 2);
840b57cec5SDimitry Andric       return path.substr(0, end);
850b57cec5SDimitry Andric     }
860b57cec5SDimitry Andric 
870b57cec5SDimitry Andric     // {/,\}
880b57cec5SDimitry Andric     if (is_separator(path[0], style))
890b57cec5SDimitry Andric       return path.substr(0, 1);
900b57cec5SDimitry Andric 
910b57cec5SDimitry Andric     // * {file,directory}name
920b57cec5SDimitry Andric     size_t end = path.find_first_of(separators(style));
930b57cec5SDimitry Andric     return path.substr(0, end);
940b57cec5SDimitry Andric   }
950b57cec5SDimitry Andric 
960b57cec5SDimitry Andric   // Returns the first character of the filename in str. For paths ending in
970b57cec5SDimitry Andric   // '/', it returns the position of the '/'.
980b57cec5SDimitry Andric   size_t filename_pos(StringRef str, Style style) {
990b57cec5SDimitry Andric     if (str.size() > 0 && is_separator(str[str.size() - 1], style))
1000b57cec5SDimitry Andric       return str.size() - 1;
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric     size_t pos = str.find_last_of(separators(style), str.size() - 1);
1030b57cec5SDimitry Andric 
104349cc55cSDimitry Andric     if (is_style_windows(style)) {
1050b57cec5SDimitry Andric       if (pos == StringRef::npos)
1067a6dacacSDimitry Andric         pos = str.find_last_of(':', str.size() - 1);
1070b57cec5SDimitry Andric     }
1080b57cec5SDimitry Andric 
1090b57cec5SDimitry Andric     if (pos == StringRef::npos || (pos == 1 && is_separator(str[0], style)))
1100b57cec5SDimitry Andric       return 0;
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric     return pos + 1;
1130b57cec5SDimitry Andric   }
1140b57cec5SDimitry Andric 
1150b57cec5SDimitry Andric   // Returns the position of the root directory in str. If there is no root
1160b57cec5SDimitry Andric   // directory in str, it returns StringRef::npos.
1170b57cec5SDimitry Andric   size_t root_dir_start(StringRef str, Style style) {
1180b57cec5SDimitry Andric     // case "c:/"
119349cc55cSDimitry Andric     if (is_style_windows(style)) {
1200b57cec5SDimitry Andric       if (str.size() > 2 && str[1] == ':' && is_separator(str[2], style))
1210b57cec5SDimitry Andric         return 2;
1220b57cec5SDimitry Andric     }
1230b57cec5SDimitry Andric 
1240b57cec5SDimitry Andric     // case "//net"
1250b57cec5SDimitry Andric     if (str.size() > 3 && is_separator(str[0], style) && str[0] == str[1] &&
1260b57cec5SDimitry Andric         !is_separator(str[2], style)) {
1270b57cec5SDimitry Andric       return str.find_first_of(separators(style), 2);
1280b57cec5SDimitry Andric     }
1290b57cec5SDimitry Andric 
1300b57cec5SDimitry Andric     // case "/"
1310b57cec5SDimitry Andric     if (str.size() > 0 && is_separator(str[0], style))
1320b57cec5SDimitry Andric       return 0;
1330b57cec5SDimitry Andric 
1340b57cec5SDimitry Andric     return StringRef::npos;
1350b57cec5SDimitry Andric   }
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric   // Returns the position past the end of the "parent path" of path. The parent
1380b57cec5SDimitry Andric   // path will not end in '/', unless the parent is the root directory. If the
1390b57cec5SDimitry Andric   // path has no parent, 0 is returned.
1400b57cec5SDimitry Andric   size_t parent_path_end(StringRef path, Style style) {
1410b57cec5SDimitry Andric     size_t end_pos = filename_pos(path, style);
1420b57cec5SDimitry Andric 
1430b57cec5SDimitry Andric     bool filename_was_sep =
1440b57cec5SDimitry Andric         path.size() > 0 && is_separator(path[end_pos], style);
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric     // Skip separators until we reach root dir (or the start of the string).
1470b57cec5SDimitry Andric     size_t root_dir_pos = root_dir_start(path, style);
1480b57cec5SDimitry Andric     while (end_pos > 0 &&
1490b57cec5SDimitry Andric            (root_dir_pos == StringRef::npos || end_pos > root_dir_pos) &&
1500b57cec5SDimitry Andric            is_separator(path[end_pos - 1], style))
1510b57cec5SDimitry Andric       --end_pos;
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric     if (end_pos == root_dir_pos && !filename_was_sep) {
1540b57cec5SDimitry Andric       // We've reached the root dir and the input path was *not* ending in a
1550b57cec5SDimitry Andric       // sequence of slashes. Include the root dir in the parent path.
1560b57cec5SDimitry Andric       return root_dir_pos + 1;
1570b57cec5SDimitry Andric     }
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric     // Otherwise, just include before the last slash.
1600b57cec5SDimitry Andric     return end_pos;
1610b57cec5SDimitry Andric   }
1620b57cec5SDimitry Andric } // end unnamed namespace
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric enum FSEntity {
1650b57cec5SDimitry Andric   FS_Dir,
1660b57cec5SDimitry Andric   FS_File,
1670b57cec5SDimitry Andric   FS_Name
1680b57cec5SDimitry Andric };
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric static std::error_code
1710b57cec5SDimitry Andric createUniqueEntity(const Twine &Model, int &ResultFD,
1720b57cec5SDimitry Andric                    SmallVectorImpl<char> &ResultPath, bool MakeAbsolute,
173fe6060f1SDimitry Andric                    FSEntity Type, sys::fs::OpenFlags Flags = sys::fs::OF_None,
174fe6060f1SDimitry Andric                    unsigned Mode = 0) {
1750b57cec5SDimitry Andric 
1760b57cec5SDimitry Andric   // Limit the number of attempts we make, so that we don't infinite loop. E.g.
1770b57cec5SDimitry Andric   // "permission denied" could be for a specific file (so we retry with a
1780b57cec5SDimitry Andric   // different name) or for the whole directory (retry would always fail).
1790b57cec5SDimitry Andric   // Checking which is racy, so we try a number of times, then give up.
1800b57cec5SDimitry Andric   std::error_code EC;
1810b57cec5SDimitry Andric   for (int Retries = 128; Retries > 0; --Retries) {
1820b57cec5SDimitry Andric     sys::fs::createUniquePath(Model, ResultPath, MakeAbsolute);
1830b57cec5SDimitry Andric     // Try to open + create the file.
1840b57cec5SDimitry Andric     switch (Type) {
1850b57cec5SDimitry Andric     case FS_File: {
1860b57cec5SDimitry Andric       EC = sys::fs::openFileForReadWrite(Twine(ResultPath.begin()), ResultFD,
1870b57cec5SDimitry Andric                                          sys::fs::CD_CreateNew, Flags, Mode);
1880b57cec5SDimitry Andric       if (EC) {
1890b57cec5SDimitry Andric         // errc::permission_denied happens on Windows when we try to open a file
1900b57cec5SDimitry Andric         // that has been marked for deletion.
1910b57cec5SDimitry Andric         if (EC == errc::file_exists || EC == errc::permission_denied)
1920b57cec5SDimitry Andric           continue;
1930b57cec5SDimitry Andric         return EC;
1940b57cec5SDimitry Andric       }
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric       return std::error_code();
1970b57cec5SDimitry Andric     }
1980b57cec5SDimitry Andric 
1990b57cec5SDimitry Andric     case FS_Name: {
2000b57cec5SDimitry Andric       EC = sys::fs::access(ResultPath.begin(), sys::fs::AccessMode::Exist);
2010b57cec5SDimitry Andric       if (EC == errc::no_such_file_or_directory)
2020b57cec5SDimitry Andric         return std::error_code();
2030b57cec5SDimitry Andric       if (EC)
2040b57cec5SDimitry Andric         return EC;
2050b57cec5SDimitry Andric       continue;
2060b57cec5SDimitry Andric     }
2070b57cec5SDimitry Andric 
2080b57cec5SDimitry Andric     case FS_Dir: {
2090b57cec5SDimitry Andric       EC = sys::fs::create_directory(ResultPath.begin(), false);
2100b57cec5SDimitry Andric       if (EC) {
2110b57cec5SDimitry Andric         if (EC == errc::file_exists)
2120b57cec5SDimitry Andric           continue;
2130b57cec5SDimitry Andric         return EC;
2140b57cec5SDimitry Andric       }
2150b57cec5SDimitry Andric       return std::error_code();
2160b57cec5SDimitry Andric     }
2170b57cec5SDimitry Andric     }
2180b57cec5SDimitry Andric     llvm_unreachable("Invalid Type");
2190b57cec5SDimitry Andric   }
2200b57cec5SDimitry Andric   return EC;
2210b57cec5SDimitry Andric }
2220b57cec5SDimitry Andric 
2230b57cec5SDimitry Andric namespace llvm {
2240b57cec5SDimitry Andric namespace sys  {
2250b57cec5SDimitry Andric namespace path {
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric const_iterator begin(StringRef path, Style style) {
2280b57cec5SDimitry Andric   const_iterator i;
2290b57cec5SDimitry Andric   i.Path      = path;
2300b57cec5SDimitry Andric   i.Component = find_first_component(path, style);
2310b57cec5SDimitry Andric   i.Position  = 0;
2320b57cec5SDimitry Andric   i.S = style;
2330b57cec5SDimitry Andric   return i;
2340b57cec5SDimitry Andric }
2350b57cec5SDimitry Andric 
2360b57cec5SDimitry Andric const_iterator end(StringRef path) {
2370b57cec5SDimitry Andric   const_iterator i;
2380b57cec5SDimitry Andric   i.Path      = path;
2390b57cec5SDimitry Andric   i.Position  = path.size();
2400b57cec5SDimitry Andric   return i;
2410b57cec5SDimitry Andric }
2420b57cec5SDimitry Andric 
2430b57cec5SDimitry Andric const_iterator &const_iterator::operator++() {
2440b57cec5SDimitry Andric   assert(Position < Path.size() && "Tried to increment past end!");
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric   // Increment Position to past the current component
2470b57cec5SDimitry Andric   Position += Component.size();
2480b57cec5SDimitry Andric 
2490b57cec5SDimitry Andric   // Check for end.
2500b57cec5SDimitry Andric   if (Position == Path.size()) {
2510b57cec5SDimitry Andric     Component = StringRef();
2520b57cec5SDimitry Andric     return *this;
2530b57cec5SDimitry Andric   }
2540b57cec5SDimitry Andric 
2550b57cec5SDimitry Andric   // Both POSIX and Windows treat paths that begin with exactly two separators
2560b57cec5SDimitry Andric   // specially.
2570b57cec5SDimitry Andric   bool was_net = Component.size() > 2 && is_separator(Component[0], S) &&
2580b57cec5SDimitry Andric                  Component[1] == Component[0] && !is_separator(Component[2], S);
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric   // Handle separators.
2610b57cec5SDimitry Andric   if (is_separator(Path[Position], S)) {
2620b57cec5SDimitry Andric     // Root dir.
2630b57cec5SDimitry Andric     if (was_net ||
2640b57cec5SDimitry Andric         // c:/
2655f757f3fSDimitry Andric         (is_style_windows(S) && Component.ends_with(":"))) {
2660b57cec5SDimitry Andric       Component = Path.substr(Position, 1);
2670b57cec5SDimitry Andric       return *this;
2680b57cec5SDimitry Andric     }
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric     // Skip extra separators.
2710b57cec5SDimitry Andric     while (Position != Path.size() && is_separator(Path[Position], S)) {
2720b57cec5SDimitry Andric       ++Position;
2730b57cec5SDimitry Andric     }
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric     // Treat trailing '/' as a '.', unless it is the root dir.
2760b57cec5SDimitry Andric     if (Position == Path.size() && Component != "/") {
2770b57cec5SDimitry Andric       --Position;
2780b57cec5SDimitry Andric       Component = ".";
2790b57cec5SDimitry Andric       return *this;
2800b57cec5SDimitry Andric     }
2810b57cec5SDimitry Andric   }
2820b57cec5SDimitry Andric 
2830b57cec5SDimitry Andric   // Find next component.
2840b57cec5SDimitry Andric   size_t end_pos = Path.find_first_of(separators(S), Position);
2850b57cec5SDimitry Andric   Component = Path.slice(Position, end_pos);
2860b57cec5SDimitry Andric 
2870b57cec5SDimitry Andric   return *this;
2880b57cec5SDimitry Andric }
2890b57cec5SDimitry Andric 
2900b57cec5SDimitry Andric bool const_iterator::operator==(const const_iterator &RHS) const {
2910b57cec5SDimitry Andric   return Path.begin() == RHS.Path.begin() && Position == RHS.Position;
2920b57cec5SDimitry Andric }
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
2950b57cec5SDimitry Andric   return Position - RHS.Position;
2960b57cec5SDimitry Andric }
2970b57cec5SDimitry Andric 
2980b57cec5SDimitry Andric reverse_iterator rbegin(StringRef Path, Style style) {
2990b57cec5SDimitry Andric   reverse_iterator I;
3000b57cec5SDimitry Andric   I.Path = Path;
3010b57cec5SDimitry Andric   I.Position = Path.size();
3020b57cec5SDimitry Andric   I.S = style;
3030b57cec5SDimitry Andric   ++I;
3040b57cec5SDimitry Andric   return I;
3050b57cec5SDimitry Andric }
3060b57cec5SDimitry Andric 
3070b57cec5SDimitry Andric reverse_iterator rend(StringRef Path) {
3080b57cec5SDimitry Andric   reverse_iterator I;
3090b57cec5SDimitry Andric   I.Path = Path;
3100b57cec5SDimitry Andric   I.Component = Path.substr(0, 0);
3110b57cec5SDimitry Andric   I.Position = 0;
3120b57cec5SDimitry Andric   return I;
3130b57cec5SDimitry Andric }
3140b57cec5SDimitry Andric 
3150b57cec5SDimitry Andric reverse_iterator &reverse_iterator::operator++() {
3160b57cec5SDimitry Andric   size_t root_dir_pos = root_dir_start(Path, S);
3170b57cec5SDimitry Andric 
3180b57cec5SDimitry Andric   // Skip separators unless it's the root directory.
3190b57cec5SDimitry Andric   size_t end_pos = Position;
3200b57cec5SDimitry Andric   while (end_pos > 0 && (end_pos - 1) != root_dir_pos &&
3210b57cec5SDimitry Andric          is_separator(Path[end_pos - 1], S))
3220b57cec5SDimitry Andric     --end_pos;
3230b57cec5SDimitry Andric 
3240b57cec5SDimitry Andric   // Treat trailing '/' as a '.', unless it is the root dir.
3250b57cec5SDimitry Andric   if (Position == Path.size() && !Path.empty() &&
3260b57cec5SDimitry Andric       is_separator(Path.back(), S) &&
3270b57cec5SDimitry Andric       (root_dir_pos == StringRef::npos || end_pos - 1 > root_dir_pos)) {
3280b57cec5SDimitry Andric     --Position;
3290b57cec5SDimitry Andric     Component = ".";
3300b57cec5SDimitry Andric     return *this;
3310b57cec5SDimitry Andric   }
3320b57cec5SDimitry Andric 
3330b57cec5SDimitry Andric   // Find next separator.
3340b57cec5SDimitry Andric   size_t start_pos = filename_pos(Path.substr(0, end_pos), S);
3350b57cec5SDimitry Andric   Component = Path.slice(start_pos, end_pos);
3360b57cec5SDimitry Andric   Position = start_pos;
3370b57cec5SDimitry Andric   return *this;
3380b57cec5SDimitry Andric }
3390b57cec5SDimitry Andric 
3400b57cec5SDimitry Andric bool reverse_iterator::operator==(const reverse_iterator &RHS) const {
3410b57cec5SDimitry Andric   return Path.begin() == RHS.Path.begin() && Component == RHS.Component &&
3420b57cec5SDimitry Andric          Position == RHS.Position;
3430b57cec5SDimitry Andric }
3440b57cec5SDimitry Andric 
3450b57cec5SDimitry Andric ptrdiff_t reverse_iterator::operator-(const reverse_iterator &RHS) const {
3460b57cec5SDimitry Andric   return Position - RHS.Position;
3470b57cec5SDimitry Andric }
3480b57cec5SDimitry Andric 
3490b57cec5SDimitry Andric StringRef root_path(StringRef path, Style style) {
3500b57cec5SDimitry Andric   const_iterator b = begin(path, style), pos = b, e = end(path);
3510b57cec5SDimitry Andric   if (b != e) {
3520b57cec5SDimitry Andric     bool has_net =
3530b57cec5SDimitry Andric         b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
3545f757f3fSDimitry Andric     bool has_drive = is_style_windows(style) && b->ends_with(":");
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric     if (has_net || has_drive) {
3570b57cec5SDimitry Andric       if ((++pos != e) && is_separator((*pos)[0], style)) {
3580b57cec5SDimitry Andric         // {C:/,//net/}, so get the first two components.
3590b57cec5SDimitry Andric         return path.substr(0, b->size() + pos->size());
360e8d8bef9SDimitry Andric       }
3610b57cec5SDimitry Andric       // just {C:,//net}, return the first component.
3620b57cec5SDimitry Andric       return *b;
3630b57cec5SDimitry Andric     }
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric     // POSIX style root directory.
3660b57cec5SDimitry Andric     if (is_separator((*b)[0], style)) {
3670b57cec5SDimitry Andric       return *b;
3680b57cec5SDimitry Andric     }
3690b57cec5SDimitry Andric   }
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric   return StringRef();
3720b57cec5SDimitry Andric }
3730b57cec5SDimitry Andric 
3740b57cec5SDimitry Andric StringRef root_name(StringRef path, Style style) {
3750b57cec5SDimitry Andric   const_iterator b = begin(path, style), e = end(path);
3760b57cec5SDimitry Andric   if (b != e) {
3770b57cec5SDimitry Andric     bool has_net =
3780b57cec5SDimitry Andric         b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
3795f757f3fSDimitry Andric     bool has_drive = is_style_windows(style) && b->ends_with(":");
3800b57cec5SDimitry Andric 
3810b57cec5SDimitry Andric     if (has_net || has_drive) {
3820b57cec5SDimitry Andric       // just {C:,//net}, return the first component.
3830b57cec5SDimitry Andric       return *b;
3840b57cec5SDimitry Andric     }
3850b57cec5SDimitry Andric   }
3860b57cec5SDimitry Andric 
3870b57cec5SDimitry Andric   // No path or no name.
3880b57cec5SDimitry Andric   return StringRef();
3890b57cec5SDimitry Andric }
3900b57cec5SDimitry Andric 
3910b57cec5SDimitry Andric StringRef root_directory(StringRef path, Style style) {
3920b57cec5SDimitry Andric   const_iterator b = begin(path, style), pos = b, e = end(path);
3930b57cec5SDimitry Andric   if (b != e) {
3940b57cec5SDimitry Andric     bool has_net =
3950b57cec5SDimitry Andric         b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
3965f757f3fSDimitry Andric     bool has_drive = is_style_windows(style) && b->ends_with(":");
3970b57cec5SDimitry Andric 
3980b57cec5SDimitry Andric     if ((has_net || has_drive) &&
3990b57cec5SDimitry Andric         // {C:,//net}, skip to the next component.
4000b57cec5SDimitry Andric         (++pos != e) && is_separator((*pos)[0], style)) {
4010b57cec5SDimitry Andric       return *pos;
4020b57cec5SDimitry Andric     }
4030b57cec5SDimitry Andric 
4040b57cec5SDimitry Andric     // POSIX style root directory.
4050b57cec5SDimitry Andric     if (!has_net && is_separator((*b)[0], style)) {
4060b57cec5SDimitry Andric       return *b;
4070b57cec5SDimitry Andric     }
4080b57cec5SDimitry Andric   }
4090b57cec5SDimitry Andric 
4100b57cec5SDimitry Andric   // No path or no root.
4110b57cec5SDimitry Andric   return StringRef();
4120b57cec5SDimitry Andric }
4130b57cec5SDimitry Andric 
4140b57cec5SDimitry Andric StringRef relative_path(StringRef path, Style style) {
4150b57cec5SDimitry Andric   StringRef root = root_path(path, style);
4160b57cec5SDimitry Andric   return path.substr(root.size());
4170b57cec5SDimitry Andric }
4180b57cec5SDimitry Andric 
4190b57cec5SDimitry Andric void append(SmallVectorImpl<char> &path, Style style, const Twine &a,
4200b57cec5SDimitry Andric             const Twine &b, const Twine &c, const Twine &d) {
4210b57cec5SDimitry Andric   SmallString<32> a_storage;
4220b57cec5SDimitry Andric   SmallString<32> b_storage;
4230b57cec5SDimitry Andric   SmallString<32> c_storage;
4240b57cec5SDimitry Andric   SmallString<32> d_storage;
4250b57cec5SDimitry Andric 
4260b57cec5SDimitry Andric   SmallVector<StringRef, 4> components;
4270b57cec5SDimitry Andric   if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage));
4280b57cec5SDimitry Andric   if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage));
4290b57cec5SDimitry Andric   if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage));
4300b57cec5SDimitry Andric   if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage));
4310b57cec5SDimitry Andric 
4320b57cec5SDimitry Andric   for (auto &component : components) {
4330b57cec5SDimitry Andric     bool path_has_sep =
4340b57cec5SDimitry Andric         !path.empty() && is_separator(path[path.size() - 1], style);
4350b57cec5SDimitry Andric     if (path_has_sep) {
4360b57cec5SDimitry Andric       // Strip separators from beginning of component.
4370b57cec5SDimitry Andric       size_t loc = component.find_first_not_of(separators(style));
4380b57cec5SDimitry Andric       StringRef c = component.substr(loc);
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric       // Append it.
4410b57cec5SDimitry Andric       path.append(c.begin(), c.end());
4420b57cec5SDimitry Andric       continue;
4430b57cec5SDimitry Andric     }
4440b57cec5SDimitry Andric 
4450b57cec5SDimitry Andric     bool component_has_sep =
4460b57cec5SDimitry Andric         !component.empty() && is_separator(component[0], style);
4470b57cec5SDimitry Andric     if (!component_has_sep &&
4480b57cec5SDimitry Andric         !(path.empty() || has_root_name(component, style))) {
4490b57cec5SDimitry Andric       // Add a separator.
4500b57cec5SDimitry Andric       path.push_back(preferred_separator(style));
4510b57cec5SDimitry Andric     }
4520b57cec5SDimitry Andric 
4530b57cec5SDimitry Andric     path.append(component.begin(), component.end());
4540b57cec5SDimitry Andric   }
4550b57cec5SDimitry Andric }
4560b57cec5SDimitry Andric 
4570b57cec5SDimitry Andric void append(SmallVectorImpl<char> &path, const Twine &a, const Twine &b,
4580b57cec5SDimitry Andric             const Twine &c, const Twine &d) {
4590b57cec5SDimitry Andric   append(path, Style::native, a, b, c, d);
4600b57cec5SDimitry Andric }
4610b57cec5SDimitry Andric 
4620b57cec5SDimitry Andric void append(SmallVectorImpl<char> &path, const_iterator begin,
4630b57cec5SDimitry Andric             const_iterator end, Style style) {
4640b57cec5SDimitry Andric   for (; begin != end; ++begin)
4650b57cec5SDimitry Andric     path::append(path, style, *begin);
4660b57cec5SDimitry Andric }
4670b57cec5SDimitry Andric 
4680b57cec5SDimitry Andric StringRef parent_path(StringRef path, Style style) {
4690b57cec5SDimitry Andric   size_t end_pos = parent_path_end(path, style);
4700b57cec5SDimitry Andric   if (end_pos == StringRef::npos)
4710b57cec5SDimitry Andric     return StringRef();
4720b57cec5SDimitry Andric   return path.substr(0, end_pos);
4730b57cec5SDimitry Andric }
4740b57cec5SDimitry Andric 
4750b57cec5SDimitry Andric void remove_filename(SmallVectorImpl<char> &path, Style style) {
4760b57cec5SDimitry Andric   size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()), style);
4770b57cec5SDimitry Andric   if (end_pos != StringRef::npos)
4780eae32dcSDimitry Andric     path.truncate(end_pos);
4790b57cec5SDimitry Andric }
4800b57cec5SDimitry Andric 
4810b57cec5SDimitry Andric void replace_extension(SmallVectorImpl<char> &path, const Twine &extension,
4820b57cec5SDimitry Andric                        Style style) {
4830b57cec5SDimitry Andric   StringRef p(path.begin(), path.size());
4840b57cec5SDimitry Andric   SmallString<32> ext_storage;
4850b57cec5SDimitry Andric   StringRef ext = extension.toStringRef(ext_storage);
4860b57cec5SDimitry Andric 
4870b57cec5SDimitry Andric   // Erase existing extension.
4880b57cec5SDimitry Andric   size_t pos = p.find_last_of('.');
4890b57cec5SDimitry Andric   if (pos != StringRef::npos && pos >= filename_pos(p, style))
4900eae32dcSDimitry Andric     path.truncate(pos);
4910b57cec5SDimitry Andric 
4920b57cec5SDimitry Andric   // Append '.' if needed.
4930b57cec5SDimitry Andric   if (ext.size() > 0 && ext[0] != '.')
4940b57cec5SDimitry Andric     path.push_back('.');
4950b57cec5SDimitry Andric 
4960b57cec5SDimitry Andric   // Append extension.
4970b57cec5SDimitry Andric   path.append(ext.begin(), ext.end());
4980b57cec5SDimitry Andric }
4990b57cec5SDimitry Andric 
5005ffd83dbSDimitry Andric static bool starts_with(StringRef Path, StringRef Prefix,
5015ffd83dbSDimitry Andric                         Style style = Style::native) {
5025ffd83dbSDimitry Andric   // Windows prefix matching : case and separator insensitive
503349cc55cSDimitry Andric   if (is_style_windows(style)) {
5045ffd83dbSDimitry Andric     if (Path.size() < Prefix.size())
5055ffd83dbSDimitry Andric       return false;
5065ffd83dbSDimitry Andric     for (size_t I = 0, E = Prefix.size(); I != E; ++I) {
5075ffd83dbSDimitry Andric       bool SepPath = is_separator(Path[I], style);
5085ffd83dbSDimitry Andric       bool SepPrefix = is_separator(Prefix[I], style);
5095ffd83dbSDimitry Andric       if (SepPath != SepPrefix)
5105ffd83dbSDimitry Andric         return false;
5115ffd83dbSDimitry Andric       if (!SepPath && toLower(Path[I]) != toLower(Prefix[I]))
5125ffd83dbSDimitry Andric         return false;
5135ffd83dbSDimitry Andric     }
5145ffd83dbSDimitry Andric     return true;
5155ffd83dbSDimitry Andric   }
5165f757f3fSDimitry Andric   return Path.starts_with(Prefix);
5175ffd83dbSDimitry Andric }
5185ffd83dbSDimitry Andric 
5195ffd83dbSDimitry Andric bool replace_path_prefix(SmallVectorImpl<char> &Path, StringRef OldPrefix,
5205ffd83dbSDimitry Andric                          StringRef NewPrefix, Style style) {
5210b57cec5SDimitry Andric   if (OldPrefix.empty() && NewPrefix.empty())
522480093f4SDimitry Andric     return false;
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric   StringRef OrigPath(Path.begin(), Path.size());
5255ffd83dbSDimitry Andric   if (!starts_with(OrigPath, OldPrefix, style))
526480093f4SDimitry Andric     return false;
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric   // If prefixes have the same size we can simply copy the new one over.
5295ffd83dbSDimitry Andric   if (OldPrefix.size() == NewPrefix.size()) {
5300b57cec5SDimitry Andric     llvm::copy(NewPrefix, Path.begin());
531480093f4SDimitry Andric     return true;
5320b57cec5SDimitry Andric   }
5330b57cec5SDimitry Andric 
5345ffd83dbSDimitry Andric   StringRef RelPath = OrigPath.substr(OldPrefix.size());
5350b57cec5SDimitry Andric   SmallString<256> NewPath;
5365ffd83dbSDimitry Andric   (Twine(NewPrefix) + RelPath).toVector(NewPath);
5370b57cec5SDimitry Andric   Path.swap(NewPath);
538480093f4SDimitry Andric   return true;
5390b57cec5SDimitry Andric }
5400b57cec5SDimitry Andric 
5410b57cec5SDimitry Andric void native(const Twine &path, SmallVectorImpl<char> &result, Style style) {
5420b57cec5SDimitry Andric   assert((!path.isSingleStringRef() ||
5430b57cec5SDimitry Andric           path.getSingleStringRef().data() != result.data()) &&
5440b57cec5SDimitry Andric          "path and result are not allowed to overlap!");
5450b57cec5SDimitry Andric   // Clear result.
5460b57cec5SDimitry Andric   result.clear();
5470b57cec5SDimitry Andric   path.toVector(result);
5480b57cec5SDimitry Andric   native(result, style);
5490b57cec5SDimitry Andric }
5500b57cec5SDimitry Andric 
5510b57cec5SDimitry Andric void native(SmallVectorImpl<char> &Path, Style style) {
5520b57cec5SDimitry Andric   if (Path.empty())
5530b57cec5SDimitry Andric     return;
554349cc55cSDimitry Andric   if (is_style_windows(style)) {
555349cc55cSDimitry Andric     for (char &Ch : Path)
556349cc55cSDimitry Andric       if (is_separator(Ch, style))
557349cc55cSDimitry Andric         Ch = preferred_separator(style);
5580b57cec5SDimitry Andric     if (Path[0] == '~' && (Path.size() == 1 || is_separator(Path[1], style))) {
5590b57cec5SDimitry Andric       SmallString<128> PathHome;
5600b57cec5SDimitry Andric       home_directory(PathHome);
5610b57cec5SDimitry Andric       PathHome.append(Path.begin() + 1, Path.end());
5620b57cec5SDimitry Andric       Path = PathHome;
5630b57cec5SDimitry Andric     }
5640b57cec5SDimitry Andric   } else {
565349cc55cSDimitry Andric     std::replace(Path.begin(), Path.end(), '\\', '/');
5660b57cec5SDimitry Andric   }
5670b57cec5SDimitry Andric }
5680b57cec5SDimitry Andric 
5690b57cec5SDimitry Andric std::string convert_to_slash(StringRef path, Style style) {
570349cc55cSDimitry Andric   if (is_style_posix(style))
5715ffd83dbSDimitry Andric     return std::string(path);
5720b57cec5SDimitry Andric 
5730b57cec5SDimitry Andric   std::string s = path.str();
5740b57cec5SDimitry Andric   std::replace(s.begin(), s.end(), '\\', '/');
5750b57cec5SDimitry Andric   return s;
5760b57cec5SDimitry Andric }
5770b57cec5SDimitry Andric 
5780b57cec5SDimitry Andric StringRef filename(StringRef path, Style style) { return *rbegin(path, style); }
5790b57cec5SDimitry Andric 
5800b57cec5SDimitry Andric StringRef stem(StringRef path, Style style) {
5810b57cec5SDimitry Andric   StringRef fname = filename(path, style);
5820b57cec5SDimitry Andric   size_t pos = fname.find_last_of('.');
5830b57cec5SDimitry Andric   if (pos == StringRef::npos)
5840b57cec5SDimitry Andric     return fname;
5850b57cec5SDimitry Andric   if ((fname.size() == 1 && fname == ".") ||
5860b57cec5SDimitry Andric       (fname.size() == 2 && fname == ".."))
5870b57cec5SDimitry Andric     return fname;
5880b57cec5SDimitry Andric   return fname.substr(0, pos);
5890b57cec5SDimitry Andric }
5900b57cec5SDimitry Andric 
5910b57cec5SDimitry Andric StringRef extension(StringRef path, Style style) {
5920b57cec5SDimitry Andric   StringRef fname = filename(path, style);
5930b57cec5SDimitry Andric   size_t pos = fname.find_last_of('.');
5940b57cec5SDimitry Andric   if (pos == StringRef::npos)
5950b57cec5SDimitry Andric     return StringRef();
5960b57cec5SDimitry Andric   if ((fname.size() == 1 && fname == ".") ||
5970b57cec5SDimitry Andric       (fname.size() == 2 && fname == ".."))
5980b57cec5SDimitry Andric     return StringRef();
5990b57cec5SDimitry Andric   return fname.substr(pos);
6000b57cec5SDimitry Andric }
6010b57cec5SDimitry Andric 
6020b57cec5SDimitry Andric bool is_separator(char value, Style style) {
6030b57cec5SDimitry Andric   if (value == '/')
6040b57cec5SDimitry Andric     return true;
605349cc55cSDimitry Andric   if (is_style_windows(style))
6060b57cec5SDimitry Andric     return value == '\\';
6070b57cec5SDimitry Andric   return false;
6080b57cec5SDimitry Andric }
6090b57cec5SDimitry Andric 
6100b57cec5SDimitry Andric StringRef get_separator(Style style) {
6110b57cec5SDimitry Andric   if (real_style(style) == Style::windows)
6120b57cec5SDimitry Andric     return "\\";
6130b57cec5SDimitry Andric   return "/";
6140b57cec5SDimitry Andric }
6150b57cec5SDimitry Andric 
6160b57cec5SDimitry Andric bool has_root_name(const Twine &path, Style style) {
6170b57cec5SDimitry Andric   SmallString<128> path_storage;
6180b57cec5SDimitry Andric   StringRef p = path.toStringRef(path_storage);
6190b57cec5SDimitry Andric 
6200b57cec5SDimitry Andric   return !root_name(p, style).empty();
6210b57cec5SDimitry Andric }
6220b57cec5SDimitry Andric 
6230b57cec5SDimitry Andric bool has_root_directory(const Twine &path, Style style) {
6240b57cec5SDimitry Andric   SmallString<128> path_storage;
6250b57cec5SDimitry Andric   StringRef p = path.toStringRef(path_storage);
6260b57cec5SDimitry Andric 
6270b57cec5SDimitry Andric   return !root_directory(p, style).empty();
6280b57cec5SDimitry Andric }
6290b57cec5SDimitry Andric 
6300b57cec5SDimitry Andric bool has_root_path(const Twine &path, Style style) {
6310b57cec5SDimitry Andric   SmallString<128> path_storage;
6320b57cec5SDimitry Andric   StringRef p = path.toStringRef(path_storage);
6330b57cec5SDimitry Andric 
6340b57cec5SDimitry Andric   return !root_path(p, style).empty();
6350b57cec5SDimitry Andric }
6360b57cec5SDimitry Andric 
6370b57cec5SDimitry Andric bool has_relative_path(const Twine &path, Style style) {
6380b57cec5SDimitry Andric   SmallString<128> path_storage;
6390b57cec5SDimitry Andric   StringRef p = path.toStringRef(path_storage);
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric   return !relative_path(p, style).empty();
6420b57cec5SDimitry Andric }
6430b57cec5SDimitry Andric 
6440b57cec5SDimitry Andric bool has_filename(const Twine &path, Style style) {
6450b57cec5SDimitry Andric   SmallString<128> path_storage;
6460b57cec5SDimitry Andric   StringRef p = path.toStringRef(path_storage);
6470b57cec5SDimitry Andric 
6480b57cec5SDimitry Andric   return !filename(p, style).empty();
6490b57cec5SDimitry Andric }
6500b57cec5SDimitry Andric 
6510b57cec5SDimitry Andric bool has_parent_path(const Twine &path, Style style) {
6520b57cec5SDimitry Andric   SmallString<128> path_storage;
6530b57cec5SDimitry Andric   StringRef p = path.toStringRef(path_storage);
6540b57cec5SDimitry Andric 
6550b57cec5SDimitry Andric   return !parent_path(p, style).empty();
6560b57cec5SDimitry Andric }
6570b57cec5SDimitry Andric 
6580b57cec5SDimitry Andric bool has_stem(const Twine &path, Style style) {
6590b57cec5SDimitry Andric   SmallString<128> path_storage;
6600b57cec5SDimitry Andric   StringRef p = path.toStringRef(path_storage);
6610b57cec5SDimitry Andric 
6620b57cec5SDimitry Andric   return !stem(p, style).empty();
6630b57cec5SDimitry Andric }
6640b57cec5SDimitry Andric 
6650b57cec5SDimitry Andric bool has_extension(const Twine &path, Style style) {
6660b57cec5SDimitry Andric   SmallString<128> path_storage;
6670b57cec5SDimitry Andric   StringRef p = path.toStringRef(path_storage);
6680b57cec5SDimitry Andric 
6690b57cec5SDimitry Andric   return !extension(p, style).empty();
6700b57cec5SDimitry Andric }
6710b57cec5SDimitry Andric 
6720b57cec5SDimitry Andric bool is_absolute(const Twine &path, Style style) {
6730b57cec5SDimitry Andric   SmallString<128> path_storage;
6740b57cec5SDimitry Andric   StringRef p = path.toStringRef(path_storage);
6750b57cec5SDimitry Andric 
6760b57cec5SDimitry Andric   bool rootDir = has_root_directory(p, style);
677349cc55cSDimitry Andric   bool rootName = is_style_posix(style) || has_root_name(p, style);
6780b57cec5SDimitry Andric 
6790b57cec5SDimitry Andric   return rootDir && rootName;
6800b57cec5SDimitry Andric }
6810b57cec5SDimitry Andric 
682e8d8bef9SDimitry Andric bool is_absolute_gnu(const Twine &path, Style style) {
683e8d8bef9SDimitry Andric   SmallString<128> path_storage;
684e8d8bef9SDimitry Andric   StringRef p = path.toStringRef(path_storage);
685e8d8bef9SDimitry Andric 
686e8d8bef9SDimitry Andric   // Handle '/' which is absolute for both Windows and POSIX systems.
687e8d8bef9SDimitry Andric   // Handle '\\' on Windows.
688e8d8bef9SDimitry Andric   if (!p.empty() && is_separator(p.front(), style))
689e8d8bef9SDimitry Andric     return true;
690e8d8bef9SDimitry Andric 
691349cc55cSDimitry Andric   if (is_style_windows(style)) {
692e8d8bef9SDimitry Andric     // Handle drive letter pattern (a character followed by ':') on Windows.
693e8d8bef9SDimitry Andric     if (p.size() >= 2 && (p[0] && p[1] == ':'))
694e8d8bef9SDimitry Andric       return true;
695e8d8bef9SDimitry Andric   }
696e8d8bef9SDimitry Andric 
697e8d8bef9SDimitry Andric   return false;
698e8d8bef9SDimitry Andric }
699e8d8bef9SDimitry Andric 
7000b57cec5SDimitry Andric bool is_relative(const Twine &path, Style style) {
7010b57cec5SDimitry Andric   return !is_absolute(path, style);
7020b57cec5SDimitry Andric }
7030b57cec5SDimitry Andric 
7040b57cec5SDimitry Andric StringRef remove_leading_dotslash(StringRef Path, Style style) {
7050b57cec5SDimitry Andric   // Remove leading "./" (or ".//" or "././" etc.)
7060b57cec5SDimitry Andric   while (Path.size() > 2 && Path[0] == '.' && is_separator(Path[1], style)) {
7070b57cec5SDimitry Andric     Path = Path.substr(2);
7080b57cec5SDimitry Andric     while (Path.size() > 0 && is_separator(Path[0], style))
7090b57cec5SDimitry Andric       Path = Path.substr(1);
7100b57cec5SDimitry Andric   }
7110b57cec5SDimitry Andric   return Path;
7120b57cec5SDimitry Andric }
7130b57cec5SDimitry Andric 
7145ffd83dbSDimitry Andric // Remove path traversal components ("." and "..") when possible, and
7155ffd83dbSDimitry Andric // canonicalize slashes.
7165ffd83dbSDimitry Andric bool remove_dots(SmallVectorImpl<char> &the_path, bool remove_dot_dot,
7170b57cec5SDimitry Andric                  Style style) {
7185ffd83dbSDimitry Andric   style = real_style(style);
7195ffd83dbSDimitry Andric   StringRef remaining(the_path.data(), the_path.size());
7205ffd83dbSDimitry Andric   bool needs_change = false;
7210b57cec5SDimitry Andric   SmallVector<StringRef, 16> components;
7220b57cec5SDimitry Andric 
7235ffd83dbSDimitry Andric   // Consume the root path, if present.
7245ffd83dbSDimitry Andric   StringRef root = path::root_path(remaining, style);
7255ffd83dbSDimitry Andric   bool absolute = !root.empty();
7265ffd83dbSDimitry Andric   if (absolute)
7275ffd83dbSDimitry Andric     remaining = remaining.drop_front(root.size());
7285ffd83dbSDimitry Andric 
7295ffd83dbSDimitry Andric   // Loop over path components manually. This makes it easier to detect
7305ffd83dbSDimitry Andric   // non-preferred slashes and double separators that must be canonicalized.
7315ffd83dbSDimitry Andric   while (!remaining.empty()) {
7325ffd83dbSDimitry Andric     size_t next_slash = remaining.find_first_of(separators(style));
7335ffd83dbSDimitry Andric     if (next_slash == StringRef::npos)
7345ffd83dbSDimitry Andric       next_slash = remaining.size();
7355ffd83dbSDimitry Andric     StringRef component = remaining.take_front(next_slash);
7365ffd83dbSDimitry Andric     remaining = remaining.drop_front(next_slash);
7375ffd83dbSDimitry Andric 
7385ffd83dbSDimitry Andric     // Eat the slash, and check if it is the preferred separator.
7395ffd83dbSDimitry Andric     if (!remaining.empty()) {
7405ffd83dbSDimitry Andric       needs_change |= remaining.front() != preferred_separator(style);
7415ffd83dbSDimitry Andric       remaining = remaining.drop_front();
7425ffd83dbSDimitry Andric       // The path needs to be rewritten if it has a trailing slash.
7435ffd83dbSDimitry Andric       // FIXME: This is emergent behavior that could be removed.
7445ffd83dbSDimitry Andric       needs_change |= remaining.empty();
7455ffd83dbSDimitry Andric     }
7465ffd83dbSDimitry Andric 
7475ffd83dbSDimitry Andric     // Check for path traversal components or double separators.
7485ffd83dbSDimitry Andric     if (component.empty() || component == ".") {
7495ffd83dbSDimitry Andric       needs_change = true;
7505ffd83dbSDimitry Andric     } else if (remove_dot_dot && component == "..") {
7515ffd83dbSDimitry Andric       needs_change = true;
7525ffd83dbSDimitry Andric       // Do not allow ".." to remove the root component. If this is the
7535ffd83dbSDimitry Andric       // beginning of a relative path, keep the ".." component.
7540b57cec5SDimitry Andric       if (!components.empty() && components.back() != "..") {
7550b57cec5SDimitry Andric         components.pop_back();
7565ffd83dbSDimitry Andric       } else if (!absolute) {
7575ffd83dbSDimitry Andric         components.push_back(component);
7580b57cec5SDimitry Andric       }
7595ffd83dbSDimitry Andric     } else {
7605ffd83dbSDimitry Andric       components.push_back(component);
7610b57cec5SDimitry Andric     }
7620b57cec5SDimitry Andric   }
7630b57cec5SDimitry Andric 
76481ad6265SDimitry Andric   SmallString<256> buffer = root;
76581ad6265SDimitry Andric   // "root" could be "/", which may need to be translated into "\".
76681ad6265SDimitry Andric   make_preferred(buffer, style);
76781ad6265SDimitry Andric   needs_change |= root != buffer;
76881ad6265SDimitry Andric 
7695ffd83dbSDimitry Andric   // Avoid rewriting the path unless we have to.
7705ffd83dbSDimitry Andric   if (!needs_change)
7710b57cec5SDimitry Andric     return false;
7720b57cec5SDimitry Andric 
7735ffd83dbSDimitry Andric   if (!components.empty()) {
7745ffd83dbSDimitry Andric     buffer += components[0];
775bdd1243dSDimitry Andric     for (StringRef C : ArrayRef(components).drop_front()) {
7765ffd83dbSDimitry Andric       buffer += preferred_separator(style);
7775ffd83dbSDimitry Andric       buffer += C;
7785ffd83dbSDimitry Andric     }
7795ffd83dbSDimitry Andric   }
7805ffd83dbSDimitry Andric   the_path.swap(buffer);
7810b57cec5SDimitry Andric   return true;
7820b57cec5SDimitry Andric }
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric } // end namespace path
7850b57cec5SDimitry Andric 
7860b57cec5SDimitry Andric namespace fs {
7870b57cec5SDimitry Andric 
7880b57cec5SDimitry Andric std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
7890b57cec5SDimitry Andric   file_status Status;
7900b57cec5SDimitry Andric   std::error_code EC = status(Path, Status);
7910b57cec5SDimitry Andric   if (EC)
7920b57cec5SDimitry Andric     return EC;
7930b57cec5SDimitry Andric   Result = Status.getUniqueID();
7940b57cec5SDimitry Andric   return std::error_code();
7950b57cec5SDimitry Andric }
7960b57cec5SDimitry Andric 
7970b57cec5SDimitry Andric void createUniquePath(const Twine &Model, SmallVectorImpl<char> &ResultPath,
7980b57cec5SDimitry Andric                       bool MakeAbsolute) {
7990b57cec5SDimitry Andric   SmallString<128> ModelStorage;
8000b57cec5SDimitry Andric   Model.toVector(ModelStorage);
8010b57cec5SDimitry Andric 
8020b57cec5SDimitry Andric   if (MakeAbsolute) {
8030b57cec5SDimitry Andric     // Make model absolute by prepending a temp directory if it's not already.
8040b57cec5SDimitry Andric     if (!sys::path::is_absolute(Twine(ModelStorage))) {
8050b57cec5SDimitry Andric       SmallString<128> TDir;
8060b57cec5SDimitry Andric       sys::path::system_temp_directory(true, TDir);
8070b57cec5SDimitry Andric       sys::path::append(TDir, Twine(ModelStorage));
8080b57cec5SDimitry Andric       ModelStorage.swap(TDir);
8090b57cec5SDimitry Andric     }
8100b57cec5SDimitry Andric   }
8110b57cec5SDimitry Andric 
8120b57cec5SDimitry Andric   ResultPath = ModelStorage;
8130b57cec5SDimitry Andric   ResultPath.push_back(0);
8140b57cec5SDimitry Andric   ResultPath.pop_back();
8150b57cec5SDimitry Andric 
8160b57cec5SDimitry Andric   // Replace '%' with random chars.
8170b57cec5SDimitry Andric   for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
8180b57cec5SDimitry Andric     if (ModelStorage[i] == '%')
8190b57cec5SDimitry Andric       ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
8200b57cec5SDimitry Andric   }
8210b57cec5SDimitry Andric }
8220b57cec5SDimitry Andric 
8230b57cec5SDimitry Andric std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
8240b57cec5SDimitry Andric                                  SmallVectorImpl<char> &ResultPath,
825fe6060f1SDimitry Andric                                  OpenFlags Flags, unsigned Mode) {
826fe6060f1SDimitry Andric   return createUniqueEntity(Model, ResultFd, ResultPath, false, FS_File, Flags,
827fe6060f1SDimitry Andric                             Mode);
8280b57cec5SDimitry Andric }
8290b57cec5SDimitry Andric 
8300b57cec5SDimitry Andric std::error_code createUniqueFile(const Twine &Model,
8310b57cec5SDimitry Andric                                  SmallVectorImpl<char> &ResultPath,
8320b57cec5SDimitry Andric                                  unsigned Mode) {
8330b57cec5SDimitry Andric   int FD;
834fe6060f1SDimitry Andric   auto EC = createUniqueFile(Model, FD, ResultPath, OF_None, Mode);
8350b57cec5SDimitry Andric   if (EC)
8360b57cec5SDimitry Andric     return EC;
8370b57cec5SDimitry Andric   // FD is only needed to avoid race conditions. Close it right away.
8380b57cec5SDimitry Andric   close(FD);
8390b57cec5SDimitry Andric   return EC;
8400b57cec5SDimitry Andric }
8410b57cec5SDimitry Andric 
8420b57cec5SDimitry Andric static std::error_code
8430b57cec5SDimitry Andric createTemporaryFile(const Twine &Model, int &ResultFD,
844fe6060f1SDimitry Andric                     llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type,
845fe6060f1SDimitry Andric                     sys::fs::OpenFlags Flags = sys::fs::OF_None) {
8460b57cec5SDimitry Andric   SmallString<128> Storage;
8470b57cec5SDimitry Andric   StringRef P = Model.toNullTerminatedStringRef(Storage);
8480b57cec5SDimitry Andric   assert(P.find_first_of(separators(Style::native)) == StringRef::npos &&
8490b57cec5SDimitry Andric          "Model must be a simple filename.");
8500b57cec5SDimitry Andric   // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
851fe6060f1SDimitry Andric   return createUniqueEntity(P.begin(), ResultFD, ResultPath, true, Type, Flags,
852*0fca6ea1SDimitry Andric                             all_read | all_write);
8530b57cec5SDimitry Andric }
8540b57cec5SDimitry Andric 
8550b57cec5SDimitry Andric static std::error_code
8560b57cec5SDimitry Andric createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
857fe6060f1SDimitry Andric                     llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type,
858fe6060f1SDimitry Andric                     sys::fs::OpenFlags Flags = sys::fs::OF_None) {
8590b57cec5SDimitry Andric   const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
8600b57cec5SDimitry Andric   return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
861fe6060f1SDimitry Andric                              Type, Flags);
8620b57cec5SDimitry Andric }
8630b57cec5SDimitry Andric 
8640b57cec5SDimitry Andric std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
8650b57cec5SDimitry Andric                                     int &ResultFD,
866fe6060f1SDimitry Andric                                     SmallVectorImpl<char> &ResultPath,
867fe6060f1SDimitry Andric                                     sys::fs::OpenFlags Flags) {
868fe6060f1SDimitry Andric   return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File,
869fe6060f1SDimitry Andric                              Flags);
8700b57cec5SDimitry Andric }
8710b57cec5SDimitry Andric 
8720b57cec5SDimitry Andric std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
873fe6060f1SDimitry Andric                                     SmallVectorImpl<char> &ResultPath,
874fe6060f1SDimitry Andric                                     sys::fs::OpenFlags Flags) {
8750b57cec5SDimitry Andric   int FD;
876fe6060f1SDimitry Andric   auto EC = createTemporaryFile(Prefix, Suffix, FD, ResultPath, Flags);
8770b57cec5SDimitry Andric   if (EC)
8780b57cec5SDimitry Andric     return EC;
8790b57cec5SDimitry Andric   // FD is only needed to avoid race conditions. Close it right away.
8800b57cec5SDimitry Andric   close(FD);
8810b57cec5SDimitry Andric   return EC;
8820b57cec5SDimitry Andric }
8830b57cec5SDimitry Andric 
8840b57cec5SDimitry Andric // This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
8850b57cec5SDimitry Andric // for consistency. We should try using mkdtemp.
8860b57cec5SDimitry Andric std::error_code createUniqueDirectory(const Twine &Prefix,
8870b57cec5SDimitry Andric                                       SmallVectorImpl<char> &ResultPath) {
8880b57cec5SDimitry Andric   int Dummy;
889fe6060f1SDimitry Andric   return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath, true,
8900b57cec5SDimitry Andric                             FS_Dir);
8910b57cec5SDimitry Andric }
8920b57cec5SDimitry Andric 
8930b57cec5SDimitry Andric std::error_code
8940b57cec5SDimitry Andric getPotentiallyUniqueFileName(const Twine &Model,
8950b57cec5SDimitry Andric                              SmallVectorImpl<char> &ResultPath) {
8960b57cec5SDimitry Andric   int Dummy;
897fe6060f1SDimitry Andric   return createUniqueEntity(Model, Dummy, ResultPath, false, FS_Name);
8980b57cec5SDimitry Andric }
8990b57cec5SDimitry Andric 
9000b57cec5SDimitry Andric std::error_code
9010b57cec5SDimitry Andric getPotentiallyUniqueTempFileName(const Twine &Prefix, StringRef Suffix,
9020b57cec5SDimitry Andric                                  SmallVectorImpl<char> &ResultPath) {
9030b57cec5SDimitry Andric   int Dummy;
9040b57cec5SDimitry Andric   return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
9050b57cec5SDimitry Andric }
9060b57cec5SDimitry Andric 
9070b57cec5SDimitry Andric void make_absolute(const Twine &current_directory,
9080b57cec5SDimitry Andric                    SmallVectorImpl<char> &path) {
9090b57cec5SDimitry Andric   StringRef p(path.data(), path.size());
9100b57cec5SDimitry Andric 
9110b57cec5SDimitry Andric   bool rootDirectory = path::has_root_directory(p);
9128bcb0991SDimitry Andric   bool rootName = path::has_root_name(p);
9130b57cec5SDimitry Andric 
9140b57cec5SDimitry Andric   // Already absolute.
915349cc55cSDimitry Andric   if ((rootName || is_style_posix(Style::native)) && rootDirectory)
9160b57cec5SDimitry Andric     return;
9170b57cec5SDimitry Andric 
9180b57cec5SDimitry Andric   // All of the following conditions will need the current directory.
9190b57cec5SDimitry Andric   SmallString<128> current_dir;
9200b57cec5SDimitry Andric   current_directory.toVector(current_dir);
9210b57cec5SDimitry Andric 
9220b57cec5SDimitry Andric   // Relative path. Prepend the current directory.
9230b57cec5SDimitry Andric   if (!rootName && !rootDirectory) {
9240b57cec5SDimitry Andric     // Append path to the current directory.
9250b57cec5SDimitry Andric     path::append(current_dir, p);
9260b57cec5SDimitry Andric     // Set path to the result.
9270b57cec5SDimitry Andric     path.swap(current_dir);
9280b57cec5SDimitry Andric     return;
9290b57cec5SDimitry Andric   }
9300b57cec5SDimitry Andric 
9310b57cec5SDimitry Andric   if (!rootName && rootDirectory) {
9320b57cec5SDimitry Andric     StringRef cdrn = path::root_name(current_dir);
9330b57cec5SDimitry Andric     SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
9340b57cec5SDimitry Andric     path::append(curDirRootName, p);
9350b57cec5SDimitry Andric     // Set path to the result.
9360b57cec5SDimitry Andric     path.swap(curDirRootName);
9370b57cec5SDimitry Andric     return;
9380b57cec5SDimitry Andric   }
9390b57cec5SDimitry Andric 
9400b57cec5SDimitry Andric   if (rootName && !rootDirectory) {
9410b57cec5SDimitry Andric     StringRef pRootName      = path::root_name(p);
9420b57cec5SDimitry Andric     StringRef bRootDirectory = path::root_directory(current_dir);
9430b57cec5SDimitry Andric     StringRef bRelativePath  = path::relative_path(current_dir);
9440b57cec5SDimitry Andric     StringRef pRelativePath  = path::relative_path(p);
9450b57cec5SDimitry Andric 
9460b57cec5SDimitry Andric     SmallString<128> res;
9470b57cec5SDimitry Andric     path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
9480b57cec5SDimitry Andric     path.swap(res);
9490b57cec5SDimitry Andric     return;
9500b57cec5SDimitry Andric   }
9510b57cec5SDimitry Andric 
9520b57cec5SDimitry Andric   llvm_unreachable("All rootName and rootDirectory combinations should have "
9530b57cec5SDimitry Andric                    "occurred above!");
9540b57cec5SDimitry Andric }
9550b57cec5SDimitry Andric 
9560b57cec5SDimitry Andric std::error_code make_absolute(SmallVectorImpl<char> &path) {
9570b57cec5SDimitry Andric   if (path::is_absolute(path))
9580b57cec5SDimitry Andric     return {};
9590b57cec5SDimitry Andric 
9600b57cec5SDimitry Andric   SmallString<128> current_dir;
9610b57cec5SDimitry Andric   if (std::error_code ec = current_path(current_dir))
9620b57cec5SDimitry Andric     return ec;
9630b57cec5SDimitry Andric 
9640b57cec5SDimitry Andric   make_absolute(current_dir, path);
9650b57cec5SDimitry Andric   return {};
9660b57cec5SDimitry Andric }
9670b57cec5SDimitry Andric 
9680b57cec5SDimitry Andric std::error_code create_directories(const Twine &Path, bool IgnoreExisting,
9690b57cec5SDimitry Andric                                    perms Perms) {
9700b57cec5SDimitry Andric   SmallString<128> PathStorage;
9710b57cec5SDimitry Andric   StringRef P = Path.toStringRef(PathStorage);
9720b57cec5SDimitry Andric 
9730b57cec5SDimitry Andric   // Be optimistic and try to create the directory
9740b57cec5SDimitry Andric   std::error_code EC = create_directory(P, IgnoreExisting, Perms);
9750b57cec5SDimitry Andric   // If we succeeded, or had any error other than the parent not existing, just
9760b57cec5SDimitry Andric   // return it.
9770b57cec5SDimitry Andric   if (EC != errc::no_such_file_or_directory)
9780b57cec5SDimitry Andric     return EC;
9790b57cec5SDimitry Andric 
9800b57cec5SDimitry Andric   // We failed because of a no_such_file_or_directory, try to create the
9810b57cec5SDimitry Andric   // parent.
9820b57cec5SDimitry Andric   StringRef Parent = path::parent_path(P);
9830b57cec5SDimitry Andric   if (Parent.empty())
9840b57cec5SDimitry Andric     return EC;
9850b57cec5SDimitry Andric 
9860b57cec5SDimitry Andric   if ((EC = create_directories(Parent, IgnoreExisting, Perms)))
9870b57cec5SDimitry Andric       return EC;
9880b57cec5SDimitry Andric 
9890b57cec5SDimitry Andric   return create_directory(P, IgnoreExisting, Perms);
9900b57cec5SDimitry Andric }
9910b57cec5SDimitry Andric 
9920b57cec5SDimitry Andric static std::error_code copy_file_internal(int ReadFD, int WriteFD) {
9930b57cec5SDimitry Andric   const size_t BufSize = 4096;
9940b57cec5SDimitry Andric   char *Buf = new char[BufSize];
9950b57cec5SDimitry Andric   int BytesRead = 0, BytesWritten = 0;
9960b57cec5SDimitry Andric   for (;;) {
9970b57cec5SDimitry Andric     BytesRead = read(ReadFD, Buf, BufSize);
9980b57cec5SDimitry Andric     if (BytesRead <= 0)
9990b57cec5SDimitry Andric       break;
10000b57cec5SDimitry Andric     while (BytesRead) {
10010b57cec5SDimitry Andric       BytesWritten = write(WriteFD, Buf, BytesRead);
10020b57cec5SDimitry Andric       if (BytesWritten < 0)
10030b57cec5SDimitry Andric         break;
10040b57cec5SDimitry Andric       BytesRead -= BytesWritten;
10050b57cec5SDimitry Andric     }
10060b57cec5SDimitry Andric     if (BytesWritten < 0)
10070b57cec5SDimitry Andric       break;
10080b57cec5SDimitry Andric   }
10090b57cec5SDimitry Andric   delete[] Buf;
10100b57cec5SDimitry Andric 
10110b57cec5SDimitry Andric   if (BytesRead < 0 || BytesWritten < 0)
1012*0fca6ea1SDimitry Andric     return errnoAsErrorCode();
10130b57cec5SDimitry Andric   return std::error_code();
10140b57cec5SDimitry Andric }
10150b57cec5SDimitry Andric 
10160b57cec5SDimitry Andric #ifndef __APPLE__
10170b57cec5SDimitry Andric std::error_code copy_file(const Twine &From, const Twine &To) {
10180b57cec5SDimitry Andric   int ReadFD, WriteFD;
10190b57cec5SDimitry Andric   if (std::error_code EC = openFileForRead(From, ReadFD, OF_None))
10200b57cec5SDimitry Andric     return EC;
10210b57cec5SDimitry Andric   if (std::error_code EC =
10220b57cec5SDimitry Andric           openFileForWrite(To, WriteFD, CD_CreateAlways, OF_None)) {
10230b57cec5SDimitry Andric     close(ReadFD);
10240b57cec5SDimitry Andric     return EC;
10250b57cec5SDimitry Andric   }
10260b57cec5SDimitry Andric 
10270b57cec5SDimitry Andric   std::error_code EC = copy_file_internal(ReadFD, WriteFD);
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric   close(ReadFD);
10300b57cec5SDimitry Andric   close(WriteFD);
10310b57cec5SDimitry Andric 
10320b57cec5SDimitry Andric   return EC;
10330b57cec5SDimitry Andric }
10340b57cec5SDimitry Andric #endif
10350b57cec5SDimitry Andric 
10360b57cec5SDimitry Andric std::error_code copy_file(const Twine &From, int ToFD) {
10370b57cec5SDimitry Andric   int ReadFD;
10380b57cec5SDimitry Andric   if (std::error_code EC = openFileForRead(From, ReadFD, OF_None))
10390b57cec5SDimitry Andric     return EC;
10400b57cec5SDimitry Andric 
10410b57cec5SDimitry Andric   std::error_code EC = copy_file_internal(ReadFD, ToFD);
10420b57cec5SDimitry Andric 
10430b57cec5SDimitry Andric   close(ReadFD);
10440b57cec5SDimitry Andric 
10450b57cec5SDimitry Andric   return EC;
10460b57cec5SDimitry Andric }
10470b57cec5SDimitry Andric 
10480b57cec5SDimitry Andric ErrorOr<MD5::MD5Result> md5_contents(int FD) {
10490b57cec5SDimitry Andric   MD5 Hash;
10500b57cec5SDimitry Andric 
10510b57cec5SDimitry Andric   constexpr size_t BufSize = 4096;
10520b57cec5SDimitry Andric   std::vector<uint8_t> Buf(BufSize);
10530b57cec5SDimitry Andric   int BytesRead = 0;
10540b57cec5SDimitry Andric   for (;;) {
10550b57cec5SDimitry Andric     BytesRead = read(FD, Buf.data(), BufSize);
10560b57cec5SDimitry Andric     if (BytesRead <= 0)
10570b57cec5SDimitry Andric       break;
1058bdd1243dSDimitry Andric     Hash.update(ArrayRef(Buf.data(), BytesRead));
10590b57cec5SDimitry Andric   }
10600b57cec5SDimitry Andric 
10610b57cec5SDimitry Andric   if (BytesRead < 0)
1062*0fca6ea1SDimitry Andric     return errnoAsErrorCode();
10630b57cec5SDimitry Andric   MD5::MD5Result Result;
10640b57cec5SDimitry Andric   Hash.final(Result);
10650b57cec5SDimitry Andric   return Result;
10660b57cec5SDimitry Andric }
10670b57cec5SDimitry Andric 
10680b57cec5SDimitry Andric ErrorOr<MD5::MD5Result> md5_contents(const Twine &Path) {
10690b57cec5SDimitry Andric   int FD;
10700b57cec5SDimitry Andric   if (auto EC = openFileForRead(Path, FD, OF_None))
10710b57cec5SDimitry Andric     return EC;
10720b57cec5SDimitry Andric 
10730b57cec5SDimitry Andric   auto Result = md5_contents(FD);
10740b57cec5SDimitry Andric   close(FD);
10750b57cec5SDimitry Andric   return Result;
10760b57cec5SDimitry Andric }
10770b57cec5SDimitry Andric 
10780b57cec5SDimitry Andric bool exists(const basic_file_status &status) {
10790b57cec5SDimitry Andric   return status_known(status) && status.type() != file_type::file_not_found;
10800b57cec5SDimitry Andric }
10810b57cec5SDimitry Andric 
10820b57cec5SDimitry Andric bool status_known(const basic_file_status &s) {
10830b57cec5SDimitry Andric   return s.type() != file_type::status_error;
10840b57cec5SDimitry Andric }
10850b57cec5SDimitry Andric 
10860b57cec5SDimitry Andric file_type get_file_type(const Twine &Path, bool Follow) {
10870b57cec5SDimitry Andric   file_status st;
10880b57cec5SDimitry Andric   if (status(Path, st, Follow))
10890b57cec5SDimitry Andric     return file_type::status_error;
10900b57cec5SDimitry Andric   return st.type();
10910b57cec5SDimitry Andric }
10920b57cec5SDimitry Andric 
10930b57cec5SDimitry Andric bool is_directory(const basic_file_status &status) {
10940b57cec5SDimitry Andric   return status.type() == file_type::directory_file;
10950b57cec5SDimitry Andric }
10960b57cec5SDimitry Andric 
10970b57cec5SDimitry Andric std::error_code is_directory(const Twine &path, bool &result) {
10980b57cec5SDimitry Andric   file_status st;
10990b57cec5SDimitry Andric   if (std::error_code ec = status(path, st))
11000b57cec5SDimitry Andric     return ec;
11010b57cec5SDimitry Andric   result = is_directory(st);
11020b57cec5SDimitry Andric   return std::error_code();
11030b57cec5SDimitry Andric }
11040b57cec5SDimitry Andric 
11050b57cec5SDimitry Andric bool is_regular_file(const basic_file_status &status) {
11060b57cec5SDimitry Andric   return status.type() == file_type::regular_file;
11070b57cec5SDimitry Andric }
11080b57cec5SDimitry Andric 
11090b57cec5SDimitry Andric std::error_code is_regular_file(const Twine &path, bool &result) {
11100b57cec5SDimitry Andric   file_status st;
11110b57cec5SDimitry Andric   if (std::error_code ec = status(path, st))
11120b57cec5SDimitry Andric     return ec;
11130b57cec5SDimitry Andric   result = is_regular_file(st);
11140b57cec5SDimitry Andric   return std::error_code();
11150b57cec5SDimitry Andric }
11160b57cec5SDimitry Andric 
11170b57cec5SDimitry Andric bool is_symlink_file(const basic_file_status &status) {
11180b57cec5SDimitry Andric   return status.type() == file_type::symlink_file;
11190b57cec5SDimitry Andric }
11200b57cec5SDimitry Andric 
11210b57cec5SDimitry Andric std::error_code is_symlink_file(const Twine &path, bool &result) {
11220b57cec5SDimitry Andric   file_status st;
11230b57cec5SDimitry Andric   if (std::error_code ec = status(path, st, false))
11240b57cec5SDimitry Andric     return ec;
11250b57cec5SDimitry Andric   result = is_symlink_file(st);
11260b57cec5SDimitry Andric   return std::error_code();
11270b57cec5SDimitry Andric }
11280b57cec5SDimitry Andric 
11290b57cec5SDimitry Andric bool is_other(const basic_file_status &status) {
11300b57cec5SDimitry Andric   return exists(status) &&
11310b57cec5SDimitry Andric          !is_regular_file(status) &&
11320b57cec5SDimitry Andric          !is_directory(status);
11330b57cec5SDimitry Andric }
11340b57cec5SDimitry Andric 
11350b57cec5SDimitry Andric std::error_code is_other(const Twine &Path, bool &Result) {
11360b57cec5SDimitry Andric   file_status FileStatus;
11370b57cec5SDimitry Andric   if (std::error_code EC = status(Path, FileStatus))
11380b57cec5SDimitry Andric     return EC;
11390b57cec5SDimitry Andric   Result = is_other(FileStatus);
11400b57cec5SDimitry Andric   return std::error_code();
11410b57cec5SDimitry Andric }
11420b57cec5SDimitry Andric 
11430b57cec5SDimitry Andric void directory_entry::replace_filename(const Twine &Filename, file_type Type,
11440b57cec5SDimitry Andric                                        basic_file_status Status) {
11450b57cec5SDimitry Andric   SmallString<128> PathStr = path::parent_path(Path);
11460b57cec5SDimitry Andric   path::append(PathStr, Filename);
11477a6dacacSDimitry Andric   this->Path = std::string(PathStr);
11480b57cec5SDimitry Andric   this->Type = Type;
11490b57cec5SDimitry Andric   this->Status = Status;
11500b57cec5SDimitry Andric }
11510b57cec5SDimitry Andric 
11520b57cec5SDimitry Andric ErrorOr<perms> getPermissions(const Twine &Path) {
11530b57cec5SDimitry Andric   file_status Status;
11540b57cec5SDimitry Andric   if (std::error_code EC = status(Path, Status))
11550b57cec5SDimitry Andric     return EC;
11560b57cec5SDimitry Andric 
11570b57cec5SDimitry Andric   return Status.permissions();
11580b57cec5SDimitry Andric }
11590b57cec5SDimitry Andric 
1160fe6060f1SDimitry Andric size_t mapped_file_region::size() const {
1161fe6060f1SDimitry Andric   assert(Mapping && "Mapping failed but used anyway!");
1162fe6060f1SDimitry Andric   return Size;
1163fe6060f1SDimitry Andric }
1164fe6060f1SDimitry Andric 
1165fe6060f1SDimitry Andric char *mapped_file_region::data() const {
1166fe6060f1SDimitry Andric   assert(Mapping && "Mapping failed but used anyway!");
1167fe6060f1SDimitry Andric   return reinterpret_cast<char *>(Mapping);
1168fe6060f1SDimitry Andric }
1169fe6060f1SDimitry Andric 
1170fe6060f1SDimitry Andric const char *mapped_file_region::const_data() const {
1171fe6060f1SDimitry Andric   assert(Mapping && "Mapping failed but used anyway!");
1172fe6060f1SDimitry Andric   return reinterpret_cast<const char *>(Mapping);
1173fe6060f1SDimitry Andric }
1174fe6060f1SDimitry Andric 
117504eeddc0SDimitry Andric Error readNativeFileToEOF(file_t FileHandle, SmallVectorImpl<char> &Buffer,
117604eeddc0SDimitry Andric                           ssize_t ChunkSize) {
117704eeddc0SDimitry Andric   // Install a handler to truncate the buffer to the correct size on exit.
117804eeddc0SDimitry Andric   size_t Size = Buffer.size();
117904eeddc0SDimitry Andric   auto TruncateOnExit = make_scope_exit([&]() { Buffer.truncate(Size); });
118004eeddc0SDimitry Andric 
118104eeddc0SDimitry Andric   // Read into Buffer until we hit EOF.
118204eeddc0SDimitry Andric   for (;;) {
118304eeddc0SDimitry Andric     Buffer.resize_for_overwrite(Size + ChunkSize);
118404eeddc0SDimitry Andric     Expected<size_t> ReadBytes = readNativeFile(
1185bdd1243dSDimitry Andric         FileHandle, MutableArrayRef(Buffer.begin() + Size, ChunkSize));
118604eeddc0SDimitry Andric     if (!ReadBytes)
118704eeddc0SDimitry Andric       return ReadBytes.takeError();
118804eeddc0SDimitry Andric     if (*ReadBytes == 0)
118904eeddc0SDimitry Andric       return Error::success();
119004eeddc0SDimitry Andric     Size += *ReadBytes;
119104eeddc0SDimitry Andric   }
119204eeddc0SDimitry Andric }
119304eeddc0SDimitry Andric 
11940b57cec5SDimitry Andric } // end namespace fs
11950b57cec5SDimitry Andric } // end namespace sys
11960b57cec5SDimitry Andric } // end namespace llvm
11970b57cec5SDimitry Andric 
11980b57cec5SDimitry Andric // Include the truly platform-specific parts.
11990b57cec5SDimitry Andric #if defined(LLVM_ON_UNIX)
12000b57cec5SDimitry Andric #include "Unix/Path.inc"
12010b57cec5SDimitry Andric #endif
12020b57cec5SDimitry Andric #if defined(_WIN32)
12030b57cec5SDimitry Andric #include "Windows/Path.inc"
12040b57cec5SDimitry Andric #endif
12050b57cec5SDimitry Andric 
12060b57cec5SDimitry Andric namespace llvm {
12070b57cec5SDimitry Andric namespace sys {
12080b57cec5SDimitry Andric namespace fs {
120981ad6265SDimitry Andric 
12105ffd83dbSDimitry Andric TempFile::TempFile(StringRef Name, int FD)
12115ffd83dbSDimitry Andric     : TmpName(std::string(Name)), FD(FD) {}
12120b57cec5SDimitry Andric TempFile::TempFile(TempFile &&Other) { *this = std::move(Other); }
12130b57cec5SDimitry Andric TempFile &TempFile::operator=(TempFile &&Other) {
12140b57cec5SDimitry Andric   TmpName = std::move(Other.TmpName);
12150b57cec5SDimitry Andric   FD = Other.FD;
12160b57cec5SDimitry Andric   Other.Done = true;
12170b57cec5SDimitry Andric   Other.FD = -1;
1218349cc55cSDimitry Andric #ifdef _WIN32
1219349cc55cSDimitry Andric   RemoveOnClose = Other.RemoveOnClose;
1220349cc55cSDimitry Andric   Other.RemoveOnClose = false;
1221349cc55cSDimitry Andric #endif
12220b57cec5SDimitry Andric   return *this;
12230b57cec5SDimitry Andric }
12240b57cec5SDimitry Andric 
12250b57cec5SDimitry Andric TempFile::~TempFile() { assert(Done); }
12260b57cec5SDimitry Andric 
12270b57cec5SDimitry Andric Error TempFile::discard() {
12280b57cec5SDimitry Andric   Done = true;
12290b57cec5SDimitry Andric   if (FD != -1 && close(FD) == -1) {
1230*0fca6ea1SDimitry Andric     std::error_code EC = errnoAsErrorCode();
12310b57cec5SDimitry Andric     return errorCodeToError(EC);
12320b57cec5SDimitry Andric   }
12330b57cec5SDimitry Andric   FD = -1;
12340b57cec5SDimitry Andric 
12350b57cec5SDimitry Andric #ifdef _WIN32
1236349cc55cSDimitry Andric   // On Windows, closing will remove the file, if we set the delete
1237349cc55cSDimitry Andric   // disposition. If not, remove it manually.
1238349cc55cSDimitry Andric   bool Remove = RemoveOnClose;
12390b57cec5SDimitry Andric #else
1240349cc55cSDimitry Andric   // Always try to remove the file.
1241349cc55cSDimitry Andric   bool Remove = true;
1242349cc55cSDimitry Andric #endif
12430b57cec5SDimitry Andric   std::error_code RemoveEC;
1244349cc55cSDimitry Andric   if (Remove && !TmpName.empty()) {
12450b57cec5SDimitry Andric     RemoveEC = fs::remove(TmpName);
12460b57cec5SDimitry Andric     sys::DontRemoveFileOnSignal(TmpName);
12470b57cec5SDimitry Andric     if (!RemoveEC)
12480b57cec5SDimitry Andric       TmpName = "";
1249349cc55cSDimitry Andric   } else {
1250349cc55cSDimitry Andric     TmpName = "";
12510b57cec5SDimitry Andric   }
12520b57cec5SDimitry Andric   return errorCodeToError(RemoveEC);
12530b57cec5SDimitry Andric }
12540b57cec5SDimitry Andric 
12550b57cec5SDimitry Andric Error TempFile::keep(const Twine &Name) {
12560b57cec5SDimitry Andric   assert(!Done);
12570b57cec5SDimitry Andric   Done = true;
12580b57cec5SDimitry Andric   // Always try to close and rename.
12590b57cec5SDimitry Andric #ifdef _WIN32
12600b57cec5SDimitry Andric   // If we can't cancel the delete don't rename.
12610b57cec5SDimitry Andric   auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
126204eeddc0SDimitry Andric   std::error_code RenameEC =
126304eeddc0SDimitry Andric       RemoveOnClose ? std::error_code() : setDeleteDisposition(H, false);
1264349cc55cSDimitry Andric   bool ShouldDelete = false;
12650b57cec5SDimitry Andric   if (!RenameEC) {
1266fe6060f1SDimitry Andric     RenameEC = rename_handle(H, Name);
12670b57cec5SDimitry Andric     // If rename failed because it's cross-device, copy instead
12680b57cec5SDimitry Andric     if (RenameEC ==
12690b57cec5SDimitry Andric       std::error_code(ERROR_NOT_SAME_DEVICE, std::system_category())) {
12700b57cec5SDimitry Andric       RenameEC = copy_file(TmpName, Name);
1271349cc55cSDimitry Andric       ShouldDelete = true;
12720b57cec5SDimitry Andric     }
12730b57cec5SDimitry Andric   }
12740b57cec5SDimitry Andric 
1275349cc55cSDimitry Andric   // If we can't rename or copy, discard the temporary file.
12760b57cec5SDimitry Andric   if (RenameEC)
1277349cc55cSDimitry Andric     ShouldDelete = true;
1278349cc55cSDimitry Andric   if (ShouldDelete) {
1279349cc55cSDimitry Andric     if (!RemoveOnClose)
12800b57cec5SDimitry Andric       setDeleteDisposition(H, true);
1281349cc55cSDimitry Andric     else
1282349cc55cSDimitry Andric       remove(TmpName);
1283349cc55cSDimitry Andric   }
12840b57cec5SDimitry Andric #else
12850b57cec5SDimitry Andric   std::error_code RenameEC = fs::rename(TmpName, Name);
12860b57cec5SDimitry Andric   if (RenameEC) {
12870b57cec5SDimitry Andric     // If we can't rename, try to copy to work around cross-device link issues.
12880b57cec5SDimitry Andric     RenameEC = sys::fs::copy_file(TmpName, Name);
12890b57cec5SDimitry Andric     // If we can't rename or copy, discard the temporary file.
12900b57cec5SDimitry Andric     if (RenameEC)
12910b57cec5SDimitry Andric       remove(TmpName);
12920b57cec5SDimitry Andric   }
12930b57cec5SDimitry Andric #endif
1294349cc55cSDimitry Andric   sys::DontRemoveFileOnSignal(TmpName);
12950b57cec5SDimitry Andric 
12960b57cec5SDimitry Andric   if (!RenameEC)
12970b57cec5SDimitry Andric     TmpName = "";
12980b57cec5SDimitry Andric 
1299*0fca6ea1SDimitry Andric   if (close(FD) == -1)
1300*0fca6ea1SDimitry Andric     return errorCodeToError(errnoAsErrorCode());
13010b57cec5SDimitry Andric   FD = -1;
13020b57cec5SDimitry Andric 
13030b57cec5SDimitry Andric   return errorCodeToError(RenameEC);
13040b57cec5SDimitry Andric }
13050b57cec5SDimitry Andric 
13060b57cec5SDimitry Andric Error TempFile::keep() {
13070b57cec5SDimitry Andric   assert(!Done);
13080b57cec5SDimitry Andric   Done = true;
13090b57cec5SDimitry Andric 
13100b57cec5SDimitry Andric #ifdef _WIN32
13110b57cec5SDimitry Andric   auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
13120b57cec5SDimitry Andric   if (std::error_code EC = setDeleteDisposition(H, false))
13130b57cec5SDimitry Andric     return errorCodeToError(EC);
13140b57cec5SDimitry Andric #endif
1315349cc55cSDimitry Andric   sys::DontRemoveFileOnSignal(TmpName);
13160b57cec5SDimitry Andric 
13170b57cec5SDimitry Andric   TmpName = "";
13180b57cec5SDimitry Andric 
1319*0fca6ea1SDimitry Andric   if (close(FD) == -1)
1320*0fca6ea1SDimitry Andric     return errorCodeToError(errnoAsErrorCode());
13210b57cec5SDimitry Andric   FD = -1;
13220b57cec5SDimitry Andric 
13230b57cec5SDimitry Andric   return Error::success();
13240b57cec5SDimitry Andric }
13250b57cec5SDimitry Andric 
1326fe6060f1SDimitry Andric Expected<TempFile> TempFile::create(const Twine &Model, unsigned Mode,
1327fe6060f1SDimitry Andric                                     OpenFlags ExtraFlags) {
13280b57cec5SDimitry Andric   int FD;
13290b57cec5SDimitry Andric   SmallString<128> ResultPath;
13300b57cec5SDimitry Andric   if (std::error_code EC =
1331fe6060f1SDimitry Andric           createUniqueFile(Model, FD, ResultPath, OF_Delete | ExtraFlags, Mode))
13320b57cec5SDimitry Andric     return errorCodeToError(EC);
13330b57cec5SDimitry Andric 
13340b57cec5SDimitry Andric   TempFile Ret(ResultPath, FD);
1335349cc55cSDimitry Andric #ifdef _WIN32
1336349cc55cSDimitry Andric   auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
1337349cc55cSDimitry Andric   bool SetSignalHandler = false;
1338349cc55cSDimitry Andric   if (std::error_code EC = setDeleteDisposition(H, true)) {
1339349cc55cSDimitry Andric     Ret.RemoveOnClose = true;
1340349cc55cSDimitry Andric     SetSignalHandler = true;
1341349cc55cSDimitry Andric   }
1342349cc55cSDimitry Andric #else
1343349cc55cSDimitry Andric   bool SetSignalHandler = true;
1344349cc55cSDimitry Andric #endif
1345349cc55cSDimitry Andric   if (SetSignalHandler && sys::RemoveFileOnSignal(ResultPath)) {
13460b57cec5SDimitry Andric     // Make sure we delete the file when RemoveFileOnSignal fails.
13470b57cec5SDimitry Andric     consumeError(Ret.discard());
13480b57cec5SDimitry Andric     std::error_code EC(errc::operation_not_permitted);
13490b57cec5SDimitry Andric     return errorCodeToError(EC);
13500b57cec5SDimitry Andric   }
13510b57cec5SDimitry Andric   return std::move(Ret);
13520b57cec5SDimitry Andric }
1353e8d8bef9SDimitry Andric } // namespace fs
13540b57cec5SDimitry Andric 
1355e8d8bef9SDimitry Andric } // namespace sys
1356e8d8bef9SDimitry Andric } // namespace llvm
1357