LLVM API Documentation

Path.cpp
Go to the documentation of this file.
00001 //===-- Path.cpp - Implement OS Path Concept ------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements the operating system Path API.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Support/Errc.h"
00015 #include "llvm/Support/Path.h"
00016 #include "llvm/Support/Endian.h"
00017 #include "llvm/Support/ErrorHandling.h"
00018 #include "llvm/Support/FileSystem.h"
00019 #include "llvm/Support/Process.h"
00020 #include <cctype>
00021 #include <cstdio>
00022 #include <cstring>
00023 #include <fcntl.h>
00024 
00025 #if !defined(_MSC_VER) && !defined(__MINGW32__)
00026 #include <unistd.h>
00027 #else
00028 #include <io.h>
00029 #endif
00030 
00031 using namespace llvm;
00032 
00033 namespace {
00034   using llvm::StringRef;
00035   using llvm::sys::path::is_separator;
00036 
00037 #ifdef LLVM_ON_WIN32
00038   const char *separators = "\\/";
00039   const char preferred_separator = '\\';
00040 #else
00041   const char  separators = '/';
00042   const char preferred_separator = '/';
00043 #endif
00044 
00045   StringRef find_first_component(StringRef path) {
00046     // Look for this first component in the following order.
00047     // * empty (in this case we return an empty string)
00048     // * either C: or {//,\\}net.
00049     // * {/,\}
00050     // * {.,..}
00051     // * {file,directory}name
00052 
00053     if (path.empty())
00054       return path;
00055 
00056 #ifdef LLVM_ON_WIN32
00057     // C:
00058     if (path.size() >= 2 && std::isalpha(static_cast<unsigned char>(path[0])) &&
00059         path[1] == ':')
00060       return path.substr(0, 2);
00061 #endif
00062 
00063     // //net
00064     if ((path.size() > 2) &&
00065         is_separator(path[0]) &&
00066         path[0] == path[1] &&
00067         !is_separator(path[2])) {
00068       // Find the next directory separator.
00069       size_t end = path.find_first_of(separators, 2);
00070       return path.substr(0, end);
00071     }
00072 
00073     // {/,\}
00074     if (is_separator(path[0]))
00075       return path.substr(0, 1);
00076 
00077     if (path.startswith(".."))
00078       return path.substr(0, 2);
00079 
00080     if (path[0] == '.')
00081       return path.substr(0, 1);
00082 
00083     // * {file,directory}name
00084     size_t end = path.find_first_of(separators);
00085     return path.substr(0, end);
00086   }
00087 
00088   size_t filename_pos(StringRef str) {
00089     if (str.size() == 2 &&
00090         is_separator(str[0]) &&
00091         str[0] == str[1])
00092       return 0;
00093 
00094     if (str.size() > 0 && is_separator(str[str.size() - 1]))
00095       return str.size() - 1;
00096 
00097     size_t pos = str.find_last_of(separators, str.size() - 1);
00098 
00099 #ifdef LLVM_ON_WIN32
00100     if (pos == StringRef::npos)
00101       pos = str.find_last_of(':', str.size() - 2);
00102 #endif
00103 
00104     if (pos == StringRef::npos ||
00105         (pos == 1 && is_separator(str[0])))
00106       return 0;
00107 
00108     return pos + 1;
00109   }
00110 
00111   size_t root_dir_start(StringRef str) {
00112     // case "c:/"
00113 #ifdef LLVM_ON_WIN32
00114     if (str.size() > 2 &&
00115         str[1] == ':' &&
00116         is_separator(str[2]))
00117       return 2;
00118 #endif
00119 
00120     // case "//"
00121     if (str.size() == 2 &&
00122         is_separator(str[0]) &&
00123         str[0] == str[1])
00124       return StringRef::npos;
00125 
00126     // case "//net"
00127     if (str.size() > 3 &&
00128         is_separator(str[0]) &&
00129         str[0] == str[1] &&
00130         !is_separator(str[2])) {
00131       return str.find_first_of(separators, 2);
00132     }
00133 
00134     // case "/"
00135     if (str.size() > 0 && is_separator(str[0]))
00136       return 0;
00137 
00138     return StringRef::npos;
00139   }
00140 
00141   size_t parent_path_end(StringRef path) {
00142     size_t end_pos = filename_pos(path);
00143 
00144     bool filename_was_sep = path.size() > 0 && is_separator(path[end_pos]);
00145 
00146     // Skip separators except for root dir.
00147     size_t root_dir_pos = root_dir_start(path.substr(0, end_pos));
00148 
00149     while(end_pos > 0 &&
00150           (end_pos - 1) != root_dir_pos &&
00151           is_separator(path[end_pos - 1]))
00152       --end_pos;
00153 
00154     if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep)
00155       return StringRef::npos;
00156 
00157     return end_pos;
00158   }
00159 } // end unnamed namespace
00160 
00161 enum FSEntity {
00162   FS_Dir,
00163   FS_File,
00164   FS_Name
00165 };
00166 
00167 // Implemented in Unix/Path.inc and Windows/Path.inc.
00168 static std::error_code TempDir(SmallVectorImpl<char> &result);
00169 
00170 static std::error_code createUniqueEntity(const Twine &Model, int &ResultFD,
00171                                           SmallVectorImpl<char> &ResultPath,
00172                                           bool MakeAbsolute, unsigned Mode,
00173                                           FSEntity Type) {
00174   SmallString<128> ModelStorage;
00175   Model.toVector(ModelStorage);
00176 
00177   if (MakeAbsolute) {
00178     // Make model absolute by prepending a temp directory if it's not already.
00179     if (!sys::path::is_absolute(Twine(ModelStorage))) {
00180       SmallString<128> TDir;
00181       if (std::error_code EC = TempDir(TDir))
00182         return EC;
00183       sys::path::append(TDir, Twine(ModelStorage));
00184       ModelStorage.swap(TDir);
00185     }
00186   }
00187 
00188   // From here on, DO NOT modify model. It may be needed if the randomly chosen
00189   // path already exists.
00190   ResultPath = ModelStorage;
00191   // Null terminate.
00192   ResultPath.push_back(0);
00193   ResultPath.pop_back();
00194 
00195 retry_random_path:
00196   // Replace '%' with random chars.
00197   for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
00198     if (ModelStorage[i] == '%')
00199       ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
00200   }
00201 
00202   // Try to open + create the file.
00203   switch (Type) {
00204   case FS_File: {
00205     if (std::error_code EC =
00206             sys::fs::openFileForWrite(Twine(ResultPath.begin()), ResultFD,
00207                                       sys::fs::F_RW | sys::fs::F_Excl, Mode)) {
00208       if (EC == errc::file_exists)
00209         goto retry_random_path;
00210       return EC;
00211     }
00212 
00213     return std::error_code();
00214   }
00215 
00216   case FS_Name: {
00217     bool Exists;
00218     std::error_code EC = sys::fs::exists(ResultPath.begin(), Exists);
00219     if (EC)
00220       return EC;
00221     if (Exists)
00222       goto retry_random_path;
00223     return std::error_code();
00224   }
00225 
00226   case FS_Dir: {
00227     if (std::error_code EC =
00228             sys::fs::create_directory(ResultPath.begin(), false)) {
00229       if (EC == errc::file_exists)
00230         goto retry_random_path;
00231       return EC;
00232     }
00233     return std::error_code();
00234   }
00235   }
00236   llvm_unreachable("Invalid Type");
00237 }
00238 
00239 namespace llvm {
00240 namespace sys  {
00241 namespace path {
00242 
00243 const_iterator begin(StringRef path) {
00244   const_iterator i;
00245   i.Path      = path;
00246   i.Component = find_first_component(path);
00247   i.Position  = 0;
00248   return i;
00249 }
00250 
00251 const_iterator end(StringRef path) {
00252   const_iterator i;
00253   i.Path      = path;
00254   i.Position  = path.size();
00255   return i;
00256 }
00257 
00258 const_iterator &const_iterator::operator++() {
00259   assert(Position < Path.size() && "Tried to increment past end!");
00260 
00261   // Increment Position to past the current component
00262   Position += Component.size();
00263 
00264   // Check for end.
00265   if (Position == Path.size()) {
00266     Component = StringRef();
00267     return *this;
00268   }
00269 
00270   // Both POSIX and Windows treat paths that begin with exactly two separators
00271   // specially.
00272   bool was_net = Component.size() > 2 &&
00273     is_separator(Component[0]) &&
00274     Component[1] == Component[0] &&
00275     !is_separator(Component[2]);
00276 
00277   // Handle separators.
00278   if (is_separator(Path[Position])) {
00279     // Root dir.
00280     if (was_net
00281 #ifdef LLVM_ON_WIN32
00282         // c:/
00283         || Component.endswith(":")
00284 #endif
00285         ) {
00286       Component = Path.substr(Position, 1);
00287       return *this;
00288     }
00289 
00290     // Skip extra separators.
00291     while (Position != Path.size() &&
00292            is_separator(Path[Position])) {
00293       ++Position;
00294     }
00295 
00296     // Treat trailing '/' as a '.'.
00297     if (Position == Path.size()) {
00298       --Position;
00299       Component = ".";
00300       return *this;
00301     }
00302   }
00303 
00304   // Find next component.
00305   size_t end_pos = Path.find_first_of(separators, Position);
00306   Component = Path.slice(Position, end_pos);
00307 
00308   return *this;
00309 }
00310 
00311 const_iterator &const_iterator::operator--() {
00312   // If we're at the end and the previous char was a '/', return '.' unless
00313   // we are the root path.
00314   size_t root_dir_pos = root_dir_start(Path);
00315   if (Position == Path.size() &&
00316       Path.size() > root_dir_pos + 1 &&
00317       is_separator(Path[Position - 1])) {
00318     --Position;
00319     Component = ".";
00320     return *this;
00321   }
00322 
00323   // Skip separators unless it's the root directory.
00324   size_t end_pos = Position;
00325 
00326   while(end_pos > 0 &&
00327         (end_pos - 1) != root_dir_pos &&
00328         is_separator(Path[end_pos - 1]))
00329     --end_pos;
00330 
00331   // Find next separator.
00332   size_t start_pos = filename_pos(Path.substr(0, end_pos));
00333   Component = Path.slice(start_pos, end_pos);
00334   Position = start_pos;
00335   return *this;
00336 }
00337 
00338 bool const_iterator::operator==(const const_iterator &RHS) const {
00339   return Path.begin() == RHS.Path.begin() &&
00340          Position == RHS.Position;
00341 }
00342 
00343 bool const_iterator::operator!=(const const_iterator &RHS) const {
00344   return !(*this == RHS);
00345 }
00346 
00347 ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
00348   return Position - RHS.Position;
00349 }
00350 
00351 const StringRef root_path(StringRef path) {
00352   const_iterator b = begin(path),
00353                  pos = b,
00354                  e = end(path);
00355   if (b != e) {
00356     bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
00357     bool has_drive =
00358 #ifdef LLVM_ON_WIN32
00359       b->endswith(":");
00360 #else
00361       false;
00362 #endif
00363 
00364     if (has_net || has_drive) {
00365       if ((++pos != e) && is_separator((*pos)[0])) {
00366         // {C:/,//net/}, so get the first two components.
00367         return path.substr(0, b->size() + pos->size());
00368       } else {
00369         // just {C:,//net}, return the first component.
00370         return *b;
00371       }
00372     }
00373 
00374     // POSIX style root directory.
00375     if (is_separator((*b)[0])) {
00376       return *b;
00377     }
00378   }
00379 
00380   return StringRef();
00381 }
00382 
00383 const StringRef root_name(StringRef path) {
00384   const_iterator b = begin(path),
00385                  e = end(path);
00386   if (b != e) {
00387     bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
00388     bool has_drive =
00389 #ifdef LLVM_ON_WIN32
00390       b->endswith(":");
00391 #else
00392       false;
00393 #endif
00394 
00395     if (has_net || has_drive) {
00396       // just {C:,//net}, return the first component.
00397       return *b;
00398     }
00399   }
00400 
00401   // No path or no name.
00402   return StringRef();
00403 }
00404 
00405 const StringRef root_directory(StringRef path) {
00406   const_iterator b = begin(path),
00407                  pos = b,
00408                  e = end(path);
00409   if (b != e) {
00410     bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
00411     bool has_drive =
00412 #ifdef LLVM_ON_WIN32
00413       b->endswith(":");
00414 #else
00415       false;
00416 #endif
00417 
00418     if ((has_net || has_drive) &&
00419         // {C:,//net}, skip to the next component.
00420         (++pos != e) && is_separator((*pos)[0])) {
00421       return *pos;
00422     }
00423 
00424     // POSIX style root directory.
00425     if (!has_net && is_separator((*b)[0])) {
00426       return *b;
00427     }
00428   }
00429 
00430   // No path or no root.
00431   return StringRef();
00432 }
00433 
00434 const StringRef relative_path(StringRef path) {
00435   StringRef root = root_path(path);
00436   return path.substr(root.size());
00437 }
00438 
00439 void append(SmallVectorImpl<char> &path, const Twine &a,
00440                                          const Twine &b,
00441                                          const Twine &c,
00442                                          const Twine &d) {
00443   SmallString<32> a_storage;
00444   SmallString<32> b_storage;
00445   SmallString<32> c_storage;
00446   SmallString<32> d_storage;
00447 
00448   SmallVector<StringRef, 4> components;
00449   if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage));
00450   if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage));
00451   if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage));
00452   if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage));
00453 
00454   for (SmallVectorImpl<StringRef>::const_iterator i = components.begin(),
00455                                                   e = components.end();
00456                                                   i != e; ++i) {
00457     bool path_has_sep = !path.empty() && is_separator(path[path.size() - 1]);
00458     bool component_has_sep = !i->empty() && is_separator((*i)[0]);
00459     bool is_root_name = has_root_name(*i);
00460 
00461     if (path_has_sep) {
00462       // Strip separators from beginning of component.
00463       size_t loc = i->find_first_not_of(separators);
00464       StringRef c = i->substr(loc);
00465 
00466       // Append it.
00467       path.append(c.begin(), c.end());
00468       continue;
00469     }
00470 
00471     if (!component_has_sep && !(path.empty() || is_root_name)) {
00472       // Add a separator.
00473       path.push_back(preferred_separator);
00474     }
00475 
00476     path.append(i->begin(), i->end());
00477   }
00478 }
00479 
00480 void append(SmallVectorImpl<char> &path,
00481             const_iterator begin, const_iterator end) {
00482   for (; begin != end; ++begin)
00483     path::append(path, *begin);
00484 }
00485 
00486 const StringRef parent_path(StringRef path) {
00487   size_t end_pos = parent_path_end(path);
00488   if (end_pos == StringRef::npos)
00489     return StringRef();
00490   else
00491     return path.substr(0, end_pos);
00492 }
00493 
00494 void remove_filename(SmallVectorImpl<char> &path) {
00495   size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()));
00496   if (end_pos != StringRef::npos)
00497     path.set_size(end_pos);
00498 }
00499 
00500 void replace_extension(SmallVectorImpl<char> &path, const Twine &extension) {
00501   StringRef p(path.begin(), path.size());
00502   SmallString<32> ext_storage;
00503   StringRef ext = extension.toStringRef(ext_storage);
00504 
00505   // Erase existing extension.
00506   size_t pos = p.find_last_of('.');
00507   if (pos != StringRef::npos && pos >= filename_pos(p))
00508     path.set_size(pos);
00509 
00510   // Append '.' if needed.
00511   if (ext.size() > 0 && ext[0] != '.')
00512     path.push_back('.');
00513 
00514   // Append extension.
00515   path.append(ext.begin(), ext.end());
00516 }
00517 
00518 void native(const Twine &path, SmallVectorImpl<char> &result) {
00519   assert((!path.isSingleStringRef() ||
00520           path.getSingleStringRef().data() != result.data()) &&
00521          "path and result are not allowed to overlap!");
00522   // Clear result.
00523   result.clear();
00524   path.toVector(result);
00525   native(result);
00526 }
00527 
00528 void native(SmallVectorImpl<char> &path) {
00529 #ifdef LLVM_ON_WIN32
00530   std::replace(path.begin(), path.end(), '/', '\\');
00531 #endif
00532 }
00533 
00534 const StringRef filename(StringRef path) {
00535   return *(--end(path));
00536 }
00537 
00538 const StringRef stem(StringRef path) {
00539   StringRef fname = filename(path);
00540   size_t pos = fname.find_last_of('.');
00541   if (pos == StringRef::npos)
00542     return fname;
00543   else
00544     if ((fname.size() == 1 && fname == ".") ||
00545         (fname.size() == 2 && fname == ".."))
00546       return fname;
00547     else
00548       return fname.substr(0, pos);
00549 }
00550 
00551 const StringRef extension(StringRef path) {
00552   StringRef fname = filename(path);
00553   size_t pos = fname.find_last_of('.');
00554   if (pos == StringRef::npos)
00555     return StringRef();
00556   else
00557     if ((fname.size() == 1 && fname == ".") ||
00558         (fname.size() == 2 && fname == ".."))
00559       return StringRef();
00560     else
00561       return fname.substr(pos);
00562 }
00563 
00564 bool is_separator(char value) {
00565   switch(value) {
00566 #ifdef LLVM_ON_WIN32
00567     case '\\': // fall through
00568 #endif
00569     case '/': return true;
00570     default: return false;
00571   }
00572 }
00573 
00574 static const char preferred_separator_string[] = { preferred_separator, '\0' };
00575 
00576 const StringRef get_separator() {
00577   return preferred_separator_string;
00578 }
00579 
00580 void system_temp_directory(bool erasedOnReboot, SmallVectorImpl<char> &result) {
00581   result.clear();
00582 
00583 #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
00584   // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
00585   // macros defined in <unistd.h> on darwin >= 9
00586   int ConfName = erasedOnReboot? _CS_DARWIN_USER_TEMP_DIR
00587                                : _CS_DARWIN_USER_CACHE_DIR;
00588   size_t ConfLen = confstr(ConfName, nullptr, 0);
00589   if (ConfLen > 0) {
00590     do {
00591       result.resize(ConfLen);
00592       ConfLen = confstr(ConfName, result.data(), result.size());
00593     } while (ConfLen > 0 && ConfLen != result.size());
00594 
00595     if (ConfLen > 0) {
00596       assert(result.back() == 0);
00597       result.pop_back();
00598       return;
00599     }
00600 
00601     result.clear();
00602   }
00603 #endif
00604 
00605   // Check whether the temporary directory is specified by an environment
00606   // variable.
00607   const char *EnvironmentVariable;
00608 #ifdef LLVM_ON_WIN32
00609   EnvironmentVariable = "TEMP";
00610 #else
00611   EnvironmentVariable = "TMPDIR";
00612 #endif
00613   if (char *RequestedDir = getenv(EnvironmentVariable)) {
00614     result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
00615     return;
00616   }
00617 
00618   // Fall back to a system default.
00619   const char *DefaultResult;
00620 #ifdef LLVM_ON_WIN32
00621   (void)erasedOnReboot;
00622   DefaultResult = "C:\\TEMP";
00623 #else
00624   if (erasedOnReboot)
00625     DefaultResult = "/tmp";
00626   else
00627     DefaultResult = "/var/tmp";
00628 #endif
00629   result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
00630 }
00631 
00632 bool has_root_name(const Twine &path) {
00633   SmallString<128> path_storage;
00634   StringRef p = path.toStringRef(path_storage);
00635 
00636   return !root_name(p).empty();
00637 }
00638 
00639 bool has_root_directory(const Twine &path) {
00640   SmallString<128> path_storage;
00641   StringRef p = path.toStringRef(path_storage);
00642 
00643   return !root_directory(p).empty();
00644 }
00645 
00646 bool has_root_path(const Twine &path) {
00647   SmallString<128> path_storage;
00648   StringRef p = path.toStringRef(path_storage);
00649 
00650   return !root_path(p).empty();
00651 }
00652 
00653 bool has_relative_path(const Twine &path) {
00654   SmallString<128> path_storage;
00655   StringRef p = path.toStringRef(path_storage);
00656 
00657   return !relative_path(p).empty();
00658 }
00659 
00660 bool has_filename(const Twine &path) {
00661   SmallString<128> path_storage;
00662   StringRef p = path.toStringRef(path_storage);
00663 
00664   return !filename(p).empty();
00665 }
00666 
00667 bool has_parent_path(const Twine &path) {
00668   SmallString<128> path_storage;
00669   StringRef p = path.toStringRef(path_storage);
00670 
00671   return !parent_path(p).empty();
00672 }
00673 
00674 bool has_stem(const Twine &path) {
00675   SmallString<128> path_storage;
00676   StringRef p = path.toStringRef(path_storage);
00677 
00678   return !stem(p).empty();
00679 }
00680 
00681 bool has_extension(const Twine &path) {
00682   SmallString<128> path_storage;
00683   StringRef p = path.toStringRef(path_storage);
00684 
00685   return !extension(p).empty();
00686 }
00687 
00688 bool is_absolute(const Twine &path) {
00689   SmallString<128> path_storage;
00690   StringRef p = path.toStringRef(path_storage);
00691 
00692   bool rootDir = has_root_directory(p),
00693 #ifdef LLVM_ON_WIN32
00694        rootName = has_root_name(p);
00695 #else
00696        rootName = true;
00697 #endif
00698 
00699   return rootDir && rootName;
00700 }
00701 
00702 bool is_relative(const Twine &path) {
00703   return !is_absolute(path);
00704 }
00705 
00706 } // end namespace path
00707 
00708 namespace fs {
00709 
00710 std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
00711   file_status Status;
00712   std::error_code EC = status(Path, Status);
00713   if (EC)
00714     return EC;
00715   Result = Status.getUniqueID();
00716   return std::error_code();
00717 }
00718 
00719 std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
00720                                  SmallVectorImpl<char> &ResultPath,
00721                                  unsigned Mode) {
00722   return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File);
00723 }
00724 
00725 std::error_code createUniqueFile(const Twine &Model,
00726                                  SmallVectorImpl<char> &ResultPath) {
00727   int Dummy;
00728   return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
00729 }
00730 
00731 static std::error_code
00732 createTemporaryFile(const Twine &Model, int &ResultFD,
00733                     llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
00734   SmallString<128> Storage;
00735   StringRef P = Model.toNullTerminatedStringRef(Storage);
00736   assert(P.find_first_of(separators) == StringRef::npos &&
00737          "Model must be a simple filename.");
00738   // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
00739   return createUniqueEntity(P.begin(), ResultFD, ResultPath,
00740                             true, owner_read | owner_write, Type);
00741 }
00742 
00743 static std::error_code
00744 createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
00745                     llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
00746   const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
00747   return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
00748                              Type);
00749 }
00750 
00751 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
00752                                     int &ResultFD,
00753                                     SmallVectorImpl<char> &ResultPath) {
00754   return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File);
00755 }
00756 
00757 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
00758                                     SmallVectorImpl<char> &ResultPath) {
00759   int Dummy;
00760   return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
00761 }
00762 
00763 
00764 // This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
00765 // for consistency. We should try using mkdtemp.
00766 std::error_code createUniqueDirectory(const Twine &Prefix,
00767                                       SmallVectorImpl<char> &ResultPath) {
00768   int Dummy;
00769   return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath,
00770                             true, 0, FS_Dir);
00771 }
00772 
00773 std::error_code make_absolute(SmallVectorImpl<char> &path) {
00774   StringRef p(path.data(), path.size());
00775 
00776   bool rootDirectory = path::has_root_directory(p),
00777 #ifdef LLVM_ON_WIN32
00778        rootName = path::has_root_name(p);
00779 #else
00780        rootName = true;
00781 #endif
00782 
00783   // Already absolute.
00784   if (rootName && rootDirectory)
00785     return std::error_code();
00786 
00787   // All of the following conditions will need the current directory.
00788   SmallString<128> current_dir;
00789   if (std::error_code ec = current_path(current_dir))
00790     return ec;
00791 
00792   // Relative path. Prepend the current directory.
00793   if (!rootName && !rootDirectory) {
00794     // Append path to the current directory.
00795     path::append(current_dir, p);
00796     // Set path to the result.
00797     path.swap(current_dir);
00798     return std::error_code();
00799   }
00800 
00801   if (!rootName && rootDirectory) {
00802     StringRef cdrn = path::root_name(current_dir);
00803     SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
00804     path::append(curDirRootName, p);
00805     // Set path to the result.
00806     path.swap(curDirRootName);
00807     return std::error_code();
00808   }
00809 
00810   if (rootName && !rootDirectory) {
00811     StringRef pRootName      = path::root_name(p);
00812     StringRef bRootDirectory = path::root_directory(current_dir);
00813     StringRef bRelativePath  = path::relative_path(current_dir);
00814     StringRef pRelativePath  = path::relative_path(p);
00815 
00816     SmallString<128> res;
00817     path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
00818     path.swap(res);
00819     return std::error_code();
00820   }
00821 
00822   llvm_unreachable("All rootName and rootDirectory combinations should have "
00823                    "occurred above!");
00824 }
00825 
00826 std::error_code create_directories(const Twine &Path, bool IgnoreExisting) {
00827   SmallString<128> PathStorage;
00828   StringRef P = Path.toStringRef(PathStorage);
00829 
00830   // Be optimistic and try to create the directory
00831   std::error_code EC = create_directory(P, IgnoreExisting);
00832   // If we succeeded, or had any error other than the parent not existing, just
00833   // return it.
00834   if (EC != errc::no_such_file_or_directory)
00835     return EC;
00836 
00837   // We failed because of a no_such_file_or_directory, try to create the
00838   // parent.
00839   StringRef Parent = path::parent_path(P);
00840   if (Parent.empty())
00841     return EC;
00842 
00843   if ((EC = create_directories(Parent)))
00844       return EC;
00845 
00846   return create_directory(P, IgnoreExisting);
00847 }
00848 
00849 std::error_code copy_file(const Twine &From, const Twine &To) {
00850   int ReadFD, WriteFD;
00851   if (std::error_code EC = openFileForRead(From, ReadFD))
00852     return EC;
00853   if (std::error_code EC = openFileForWrite(To, WriteFD, F_None)) {
00854     close(ReadFD);
00855     return EC;
00856   }
00857 
00858   const size_t BufSize = 4096;
00859   char *Buf = new char[BufSize];
00860   int BytesRead = 0, BytesWritten = 0;
00861   for (;;) {
00862     BytesRead = read(ReadFD, Buf, BufSize);
00863     if (BytesRead <= 0)
00864       break;
00865     while (BytesRead) {
00866       BytesWritten = write(WriteFD, Buf, BytesRead);
00867       if (BytesWritten < 0)
00868         break;
00869       BytesRead -= BytesWritten;
00870     }
00871     if (BytesWritten < 0)
00872       break;
00873   }
00874   close(ReadFD);
00875   close(WriteFD);
00876   delete[] Buf;
00877 
00878   if (BytesRead < 0 || BytesWritten < 0)
00879     return std::error_code(errno, std::generic_category());
00880   return std::error_code();
00881 }
00882 
00883 bool exists(file_status status) {
00884   return status_known(status) && status.type() != file_type::file_not_found;
00885 }
00886 
00887 bool status_known(file_status s) {
00888   return s.type() != file_type::status_error;
00889 }
00890 
00891 bool is_directory(file_status status) {
00892   return status.type() == file_type::directory_file;
00893 }
00894 
00895 std::error_code is_directory(const Twine &path, bool &result) {
00896   file_status st;
00897   if (std::error_code ec = status(path, st))
00898     return ec;
00899   result = is_directory(st);
00900   return std::error_code();
00901 }
00902 
00903 bool is_regular_file(file_status status) {
00904   return status.type() == file_type::regular_file;
00905 }
00906 
00907 std::error_code is_regular_file(const Twine &path, bool &result) {
00908   file_status st;
00909   if (std::error_code ec = status(path, st))
00910     return ec;
00911   result = is_regular_file(st);
00912   return std::error_code();
00913 }
00914 
00915 bool is_other(file_status status) {
00916   return exists(status) &&
00917          !is_regular_file(status) &&
00918          !is_directory(status);
00919 }
00920 
00921 void directory_entry::replace_filename(const Twine &filename, file_status st) {
00922   SmallString<128> path(Path.begin(), Path.end());
00923   path::remove_filename(path);
00924   path::append(path, filename);
00925   Path = path.str();
00926   Status = st;
00927 }
00928 
00929 /// @brief Identify the magic in magic.
00930 file_magic identify_magic(StringRef Magic) {
00931   if (Magic.size() < 4)
00932     return file_magic::unknown;
00933   switch ((unsigned char)Magic[0]) {
00934     case 0x00: {
00935       // COFF short import library file
00936       if (Magic[1] == (char)0x00 && Magic[2] == (char)0xff &&
00937           Magic[3] == (char)0xff)
00938         return file_magic::coff_import_library;
00939       // Windows resource file
00940       const char Expected[] = { 0, 0, 0, 0, '\x20', 0, 0, 0, '\xff' };
00941       if (Magic.size() >= sizeof(Expected) &&
00942           memcmp(Magic.data(), Expected, sizeof(Expected)) == 0)
00943         return file_magic::windows_resource;
00944       // 0x0000 = COFF unknown machine type
00945       if (Magic[1] == 0)
00946         return file_magic::coff_object;
00947       break;
00948     }
00949     case 0xDE:  // 0x0B17C0DE = BC wraper
00950       if (Magic[1] == (char)0xC0 && Magic[2] == (char)0x17 &&
00951           Magic[3] == (char)0x0B)
00952         return file_magic::bitcode;
00953       break;
00954     case 'B':
00955       if (Magic[1] == 'C' && Magic[2] == (char)0xC0 && Magic[3] == (char)0xDE)
00956         return file_magic::bitcode;
00957       break;
00958     case '!':
00959       if (Magic.size() >= 8)
00960         if (memcmp(Magic.data(),"!<arch>\n",8) == 0)
00961           return file_magic::archive;
00962       break;
00963 
00964     case '\177':
00965       if (Magic.size() >= 18 && Magic[1] == 'E' && Magic[2] == 'L' &&
00966           Magic[3] == 'F') {
00967         bool Data2MSB = Magic[5] == 2;
00968         unsigned high = Data2MSB ? 16 : 17;
00969         unsigned low  = Data2MSB ? 17 : 16;
00970         if (Magic[high] == 0)
00971           switch (Magic[low]) {
00972             default: break;
00973             case 1: return file_magic::elf_relocatable;
00974             case 2: return file_magic::elf_executable;
00975             case 3: return file_magic::elf_shared_object;
00976             case 4: return file_magic::elf_core;
00977           }
00978       }
00979       break;
00980 
00981     case 0xCA:
00982       if (Magic[1] == char(0xFE) && Magic[2] == char(0xBA) &&
00983           Magic[3] == char(0xBE)) {
00984         // This is complicated by an overlap with Java class files.
00985         // See the Mach-O section in /usr/share/file/magic for details.
00986         if (Magic.size() >= 8 && Magic[7] < 43)
00987           return file_magic::macho_universal_binary;
00988       }
00989       break;
00990 
00991       // The two magic numbers for mach-o are:
00992       // 0xfeedface - 32-bit mach-o
00993       // 0xfeedfacf - 64-bit mach-o
00994     case 0xFE:
00995     case 0xCE:
00996     case 0xCF: {
00997       uint16_t type = 0;
00998       if (Magic[0] == char(0xFE) && Magic[1] == char(0xED) &&
00999           Magic[2] == char(0xFA) &&
01000           (Magic[3] == char(0xCE) || Magic[3] == char(0xCF))) {
01001         /* Native endian */
01002         if (Magic.size() >= 16) type = Magic[14] << 8 | Magic[15];
01003       } else if ((Magic[0] == char(0xCE) || Magic[0] == char(0xCF)) &&
01004                  Magic[1] == char(0xFA) && Magic[2] == char(0xED) &&
01005                  Magic[3] == char(0xFE)) {
01006         /* Reverse endian */
01007         if (Magic.size() >= 14) type = Magic[13] << 8 | Magic[12];
01008       }
01009       switch (type) {
01010         default: break;
01011         case 1: return file_magic::macho_object;
01012         case 2: return file_magic::macho_executable;
01013         case 3: return file_magic::macho_fixed_virtual_memory_shared_lib;
01014         case 4: return file_magic::macho_core;
01015         case 5: return file_magic::macho_preload_executable;
01016         case 6: return file_magic::macho_dynamically_linked_shared_lib;
01017         case 7: return file_magic::macho_dynamic_linker;
01018         case 8: return file_magic::macho_bundle;
01019         case 9: return file_magic::macho_dynamic_linker;
01020         case 10: return file_magic::macho_dsym_companion;
01021       }
01022       break;
01023     }
01024     case 0xF0: // PowerPC Windows
01025     case 0x83: // Alpha 32-bit
01026     case 0x84: // Alpha 64-bit
01027     case 0x66: // MPS R4000 Windows
01028     case 0x50: // mc68K
01029     case 0x4c: // 80386 Windows
01030     case 0xc4: // ARMNT Windows
01031       if (Magic[1] == 0x01)
01032         return file_magic::coff_object;
01033 
01034     case 0x90: // PA-RISC Windows
01035     case 0x68: // mc68K Windows
01036       if (Magic[1] == 0x02)
01037         return file_magic::coff_object;
01038       break;
01039 
01040     case 0x4d: // Possible MS-DOS stub on Windows PE file
01041       if (Magic[1] == 0x5a) {
01042         uint32_t off =
01043           *reinterpret_cast<const support::ulittle32_t*>(Magic.data() + 0x3c);
01044         // PE/COFF file, either EXE or DLL.
01045         if (off < Magic.size() && memcmp(Magic.data() + off, "PE\0\0",4) == 0)
01046           return file_magic::pecoff_executable;
01047       }
01048       break;
01049 
01050     case 0x64: // x86-64 Windows.
01051       if (Magic[1] == char(0x86))
01052         return file_magic::coff_object;
01053       break;
01054 
01055     default:
01056       break;
01057   }
01058   return file_magic::unknown;
01059 }
01060 
01061 std::error_code identify_magic(const Twine &Path, file_magic &Result) {
01062   int FD;
01063   if (std::error_code EC = openFileForRead(Path, FD))
01064     return EC;
01065 
01066   char Buffer[32];
01067   int Length = read(FD, Buffer, sizeof(Buffer));
01068   if (close(FD) != 0 || Length < 0)
01069     return std::error_code(errno, std::generic_category());
01070 
01071   Result = identify_magic(StringRef(Buffer, Length));
01072   return std::error_code();
01073 }
01074 
01075 std::error_code directory_entry::status(file_status &result) const {
01076   return fs::status(Path, result);
01077 }
01078 
01079 } // end namespace fs
01080 } // end namespace sys
01081 } // end namespace llvm
01082 
01083 // Include the truly platform-specific parts.
01084 #if defined(LLVM_ON_UNIX)
01085 #include "Unix/Path.inc"
01086 #endif
01087 #if defined(LLVM_ON_WIN32)
01088 #include "Windows/Path.inc"
01089 #endif