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