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