Check .rela instead of ELF64 for the compensation vaue resetting
[oota-llvm.git] / lib / Support / PathV2.cpp
index edb3accbb5fc1faabe88851eb167e81f58475b88..46571c049f12d3be1e48026c85dbd872ba95e9ff 100644 (file)
 
 #include "llvm/Support/PathV2.h"
 #include "llvm/Support/FileSystem.h"
+#include "llvm/Support/Endian.h"
 #include "llvm/Support/ErrorHandling.h"
 #include <cctype>
+#include <cstdio>
+#include <cstring>
 
 namespace {
   using llvm::StringRef;
+  using llvm::sys::path::is_separator;
 
-  bool is_separator(const char value) {
-    switch(value) {
 #ifdef LLVM_ON_WIN32
-    case '\\': // fall through
-#endif
-    case '/': return true;
-    default: return false;
-    }
-  }
-
-#ifdef LLVM_ON_WIN32
-  const StringRef separators = "\\/";
-  const char       prefered_separator = '\\';
+  const char *separators = "\\/";
+  const char  prefered_separator = '\\';
 #else
-  const StringRef separators = "/";
-  const char      prefered_separator = '/';
+  const char  separators = '/';
+  const char  prefered_separator = '/';
 #endif
 
-  const llvm::error_code success;
-
-  StringRef find_first_component(const StringRef  &path) {
+  StringRef find_first_component(StringRef path) {
     // Look for this first component in the following order.
     // * empty (in this case we return an empty string)
     // * either C: or {//,\\}net.
@@ -50,46 +42,41 @@ namespace {
     if (path.empty())
       return path;
 
+#ifdef LLVM_ON_WIN32
     // C:
     if (path.size() >= 2 && std::isalpha(path[0]) && path[1] == ':')
-      return StringRef(path.begin(), 2);
+      return path.substr(0, 2);
+#endif
 
     // //net
     if ((path.size() > 2) &&
-        (path.startswith("\\\\") || path.startswith("//")) &&
-        (path[2] != '\\' && path[2] != '/')) {
+        is_separator(path[0]) &&
+        path[0] == path[1] &&
+        !is_separator(path[2])) {
       // Find the next directory separator.
-      size_t end = path.find_first_of("\\/", 2);
-      if (end == StringRef::npos)
-        return path;
-      else
-        return StringRef(path.begin(), end);
+      size_t end = path.find_first_of(separators, 2);
+      return path.substr(0, end);
     }
 
     // {/,\}
-    if (path[0] == '\\' || path[0] == '/')
-      return StringRef(path.begin(), 1);
+    if (is_separator(path[0]))
+      return path.substr(0, 1);
 
     if (path.startswith(".."))
-      return StringRef(path.begin(), 2);
+      return path.substr(0, 2);
 
     if (path[0] == '.')
-      return StringRef(path.begin(), 1);
+      return path.substr(0, 1);
 
     // * {file,directory}name
-    size_t end = path.find_first_of("\\/", 2);
-    if (end == StringRef::npos)
-      return path;
-    else
-      return StringRef(path.begin(), end);
-
-    return StringRef();
+    size_t end = path.find_first_of(separators, 2);
+    return path.substr(0, end);
   }
 
-  size_t filename_pos(const StringRef &str) {
+  size_t filename_pos(StringRef str) {
     if (str.size() == 2 &&
         is_separator(str[0]) &&
-        is_separator(str[1]))
+        str[0] == str[1])
       return 0;
 
     if (str.size() > 0 && is_separator(str[str.size() - 1]))
@@ -109,7 +96,7 @@ namespace {
     return pos + 1;
   }
 
-  size_t root_dir_start(const StringRef &str) {
+  size_t root_dir_start(StringRef str) {
     // case "c:/"
 #ifdef LLVM_ON_WIN32
     if (str.size() > 2 &&
@@ -139,13 +126,13 @@ namespace {
     return StringRef::npos;
   }
 
-  size_t parent_path_end(const StringRef &path) {
+  size_t parent_path_end(StringRef path) {
     size_t end_pos = filename_pos(path);
 
     bool filename_was_sep = path.size() > 0 && is_separator(path[end_pos]);
 
     // Skip separators except for root dir.
-    size_t root_dir_pos = root_dir_start(StringRef(path.begin(), end_pos));
+    size_t root_dir_pos = root_dir_start(path.substr(0, end_pos));
 
     while(end_pos > 0 &&
           (end_pos - 1) != root_dir_pos &&
@@ -157,13 +144,13 @@ namespace {
 
     return end_pos;
   }
-}
+} // end unnamed namespace
 
 namespace llvm {
 namespace sys  {
 namespace path {
 
-const_iterator begin(const StringRef &path) {
+const_iterator begin(StringRef path) {
   const_iterator i;
   i.Path      = path;
   i.Component = find_first_component(path);
@@ -171,7 +158,7 @@ const_iterator begin(const StringRef &path) {
   return i;
 }
 
-const_iterator end(const StringRef &path) {
+const_iterator end(StringRef path) {
   const_iterator i;
   i.Path      = path;
   i.Position  = path.size();
@@ -206,7 +193,7 @@ const_iterator &const_iterator::operator++() {
         || Component.endswith(":")
 #endif
         ) {
-      Component = StringRef(Path.begin() + Position, 1);
+      Component = Path.substr(Position, 1);
       return *this;
     }
 
@@ -226,9 +213,7 @@ const_iterator &const_iterator::operator++() {
 
   // Find next component.
   size_t end_pos = Path.find_first_of(separators, Position);
-  if (end_pos == StringRef::npos)
-    end_pos = Path.size();
-  Component = StringRef(Path.begin() + Position, end_pos - Position);
+  Component = Path.slice(Position, end_pos);
 
   return *this;
 }
@@ -257,8 +242,8 @@ const_iterator &const_iterator::operator--() {
     --end_pos;
 
   // Find next separator.
-  size_t start_pos = filename_pos(StringRef(Path.begin(), end_pos));
-  Component = StringRef(Path.begin() + start_pos, end_pos - start_pos);
+  size_t start_pos = filename_pos(Path.substr(0, end_pos));
+  Component = Path.slice(start_pos, end_pos);
   Position = start_pos;
   return *this;
 }
@@ -276,7 +261,7 @@ ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
   return Position - RHS.Position;
 }
 
-error_code root_path(const StringRef &path, StringRef &result) {
+const StringRef root_path(StringRef path) {
   const_iterator b = begin(path),
                  pos = b,
                  e = end(path);
@@ -292,32 +277,23 @@ error_code root_path(const StringRef &path, StringRef &result) {
     if (has_net || has_drive) {
       if ((++pos != e) && is_separator((*pos)[0])) {
         // {C:/,//net/}, so get the first two components.
-        result = StringRef(path.begin(), b->size() + pos->size());
-        return success;
+        return path.substr(0, b->size() + pos->size());
       } else {
         // just {C:,//net}, return the first component.
-        result = *b;
-        return success;
+        return *b;
       }
     }
 
     // POSIX style root directory.
     if (is_separator((*b)[0])) {
-      result = *b;
-      return success;
+      return *b;
     }
-
-    // No root_path.
-    result = StringRef();
-    return success;
   }
 
-  // No path :(.
-  result = StringRef();
-  return success;
+  return StringRef();
 }
 
-error_code root_name(const StringRef &path, StringRef &result) {
+const StringRef root_name(StringRef path) {
   const_iterator b = begin(path),
                  e = end(path);
   if (b != e) {
@@ -331,17 +307,15 @@ error_code root_name(const StringRef &path, StringRef &result) {
 
     if (has_net || has_drive) {
       // just {C:,//net}, return the first component.
-      result = *b;
-      return success;
+      return *b;
     }
   }
 
   // No path or no name.
-  result = StringRef();
-  return success;
+  return StringRef();
 }
 
-error_code root_directory(const StringRef &path, StringRef &result) {
+const StringRef root_directory(StringRef path) {
   const_iterator b = begin(path),
                  pos = b,
                  e = end(path);
@@ -357,33 +331,28 @@ error_code root_directory(const StringRef &path, StringRef &result) {
     if ((has_net || has_drive) &&
         // {C:,//net}, skip to the next component.
         (++pos != e) && is_separator((*pos)[0])) {
-      result = *pos;
-      return success;
+      return *pos;
     }
 
     // POSIX style root directory.
     if (!has_net && is_separator((*b)[0])) {
-      result = *b;
-      return success;
+      return *b;
     }
   }
 
   // No path or no root.
-  result = StringRef();
-  return success;
+  return StringRef();
 }
 
-error_code relative_path(const StringRef &path, StringRef &result) {
-  StringRef root;
-  if (error_code ec = root_path(path, root)) return ec;
-  result = StringRef(path.begin() + root.size(), path.size() - root.size());
-  return success;
+const StringRef relative_path(StringRef path) {
+  StringRef root = root_path(path);
+  return path.substr(root.size());
 }
 
-error_code append(SmallVectorImpl<char> &path, const Twine &a,
-                                               const Twine &b,
-                                               const Twine &c,
-                                               const Twine &d) {
+void append(SmallVectorImpl<char> &path, const Twine &a,
+                                         const Twine &b,
+                                         const Twine &c,
+                                         const Twine &d) {
   SmallString<32> a_storage;
   SmallString<32> b_storage;
   SmallString<32> c_storage;
@@ -400,104 +369,48 @@ error_code append(SmallVectorImpl<char> &path, const Twine &a,
                                                   i != e; ++i) {
     bool path_has_sep = !path.empty() && is_separator(path[path.size() - 1]);
     bool component_has_sep = !i->empty() && is_separator((*i)[0]);
-    bool is_root_name;
-    if (error_code ec = has_root_name(*i, is_root_name)) return ec;
+    bool is_root_name = has_root_name(*i);
 
     if (path_has_sep) {
       // Strip separators from beginning of component.
       size_t loc = i->find_first_not_of(separators);
-      StringRef c = StringRef(i->begin() + loc, i->size() - loc);
+      StringRef c = i->substr(loc);
 
       // Append it.
       path.append(c.begin(), c.end());
       continue;
     }
 
-    if (!component_has_sep && !(path.empty() && is_root_name)) {
+    if (!component_has_sep && !(path.empty() || is_root_name)) {
       // Add a separator.
       path.push_back(prefered_separator);
     }
 
     path.append(i->begin(), i->end());
   }
-
-  return success;
 }
 
-error_code make_absolute(SmallVectorImpl<char> &path) {
-  StringRef p(path.data(), path.size());
-
-  bool rootName, rootDirectory;
-  if (error_code ec = has_root_name(p, rootName)) return ec;
-  if (error_code ec = has_root_directory(p, rootDirectory)) return ec;
-
-  // Already absolute.
-  if (rootName && rootDirectory)
-    return success;
-
-  // All of the following conditions will need the current directory.
-  SmallString<128> current_dir;
-  if (error_code ec = current_path(current_dir)) return ec;
-
-  // Relative path. Prepend the current directory.
-  if (!rootName && !rootDirectory) {
-    // Append path to the current directory.
-    if (error_code ec = append(current_dir, p)) return ec;
-    // Set path to the result.
-    path.swap(current_dir);
-    return success;
-  }
-
-  if (!rootName && rootDirectory) {
-    StringRef cdrn;
-    if (error_code ec = root_name(current_dir, cdrn)) return ec;
-    SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
-    if (error_code ec = append(curDirRootName, p)) return ec;
-    // Set path to the result.
-    path.swap(curDirRootName);
-    return success;
-  }
-
-  if (rootName && !rootDirectory) {
-    StringRef pRootName;
-    StringRef bRootDirectory;
-    StringRef bRelativePath;
-    StringRef pRelativePath;
-    if (error_code ec = root_name(p, pRootName)) return ec;
-    if (error_code ec = root_directory(current_dir, bRootDirectory)) return ec;
-    if (error_code ec = relative_path(current_dir, bRelativePath)) return ec;
-    if (error_code ec = relative_path(p, pRelativePath)) return ec;
-
-    SmallString<128> res;
-    if (error_code ec = append(res, pRootName, bRootDirectory,
-                                    bRelativePath, pRelativePath)) return ec;
-    path.swap(res);
-    return success;
-  }
-
-  llvm_unreachable("All rootName and rootDirectory combinations should have "
-                   "occurred above!");
+void append(SmallVectorImpl<char> &path,
+            const_iterator begin, const_iterator end) {
+  for (; begin != end; ++begin)
+    path::append(path, *begin);
 }
 
-error_code parent_path(const StringRef &path, StringRef &result) {
+const StringRef parent_path(StringRef path) {
   size_t end_pos = parent_path_end(path);
   if (end_pos == StringRef::npos)
-    result = StringRef();
+    return StringRef();
   else
-    result = StringRef(path.data(), end_pos);
-  return success;
+    return path.substr(0, end_pos);
 }
 
-error_code remove_filename(SmallVectorImpl<char> &path) {
+void remove_filename(SmallVectorImpl<char> &path) {
   size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()));
-  if (end_pos == StringRef::npos)
-    return success;
-  path.set_size(end_pos);
-  return success;
+  if (end_pos != StringRef::npos)
+    path.set_size(end_pos);
 }
 
-error_code replace_extension(SmallVectorImpl<char> &path,
-                             const Twine &extension) {
+void replace_extension(SmallVectorImpl<char> &path, const Twine &extension) {
   StringRef p(path.begin(), path.size());
   SmallString<32> ext_storage;
   StringRef ext = extension.toStringRef(ext_storage);
@@ -513,12 +426,11 @@ error_code replace_extension(SmallVectorImpl<char> &path,
 
   // Append extension.
   path.append(ext.begin(), ext.end());
-  return success;
 }
 
-error_code native(const Twine &path, SmallVectorImpl<char> &result) {
+void native(const Twine &path, SmallVectorImpl<char> &result) {
   // Clear result.
-  result.set_size(0);
+  result.clear();
 #ifdef LLVM_ON_WIN32
   SmallString<128> path_storage;
   StringRef p = path.toStringRef(path_storage);
@@ -535,159 +447,467 @@ error_code native(const Twine &path, SmallVectorImpl<char> &result) {
 #else
   path.toVector(result);
 #endif
-  return success;
 }
 
-error_code filename(const StringRef &path, StringRef &result) {
-  result = *(--end(path));
-  return success;
+const StringRef filename(StringRef path) {
+  return *(--end(path));
 }
 
-error_code stem(const StringRef &path, StringRef &result) {
-  StringRef fname;
-  if (error_code ec = filename(path, fname)) return ec;
+const StringRef stem(StringRef path) {
+  StringRef fname = filename(path);
   size_t pos = fname.find_last_of('.');
   if (pos == StringRef::npos)
-    result = fname;
+    return fname;
   else
     if ((fname.size() == 1 && fname == ".") ||
         (fname.size() == 2 && fname == ".."))
-      result = fname;
+      return fname;
     else
-      result = StringRef(fname.begin(), pos);
-
-  return success;
+      return fname.substr(0, pos);
 }
 
-error_code extension(const StringRef &path, StringRef &result) {
-  StringRef fname;
-  if (error_code ec = filename(path, fname)) return ec;
+const StringRef extension(StringRef path) {
+  StringRef fname = filename(path);
   size_t pos = fname.find_last_of('.');
   if (pos == StringRef::npos)
-    result = StringRef();
+    return StringRef();
   else
     if ((fname.size() == 1 && fname == ".") ||
         (fname.size() == 2 && fname == ".."))
-      result = StringRef();
+      return StringRef();
     else
-      result = StringRef(fname.begin() + pos, fname.size() - pos);
+      return fname.substr(pos);
+}
 
-  return success;
+bool is_separator(char value) {
+  switch(value) {
+#ifdef LLVM_ON_WIN32
+    case '\\': // fall through
+#endif
+    case '/': return true;
+    default: return false;
+  }
 }
 
-error_code has_root_name(const Twine &path, bool &result) {
-  SmallString<128> path_storage;
-  StringRef p = path.toStringRef(path_storage);
+void system_temp_directory(bool erasedOnReboot, SmallVectorImpl<char> &result) {
+  result.clear();
 
-  if (error_code ec = root_name(p, p)) return ec;
+  // Check whether the temporary directory is specified by an environment
+  // variable.
+  const char *EnvironmentVariable;
+#ifdef LLVM_ON_WIN32
+  EnvironmentVariable = "TEMP";
+#else
+  EnvironmentVariable = "TMPDIR";
+#endif
+  if (char *RequestedDir = getenv(EnvironmentVariable)) {
+    result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
+    return;
+  }
 
-  result = !p.empty();
-  return success;
+  // Fall back to a system default.
+  const char *DefaultResult;
+#ifdef LLVM_ON_WIN32
+  (void)erasedOnReboot;
+  DefaultResult = "C:\\TEMP";
+#else
+  if (erasedOnReboot)
+    DefaultResult = "/tmp";
+  else
+    DefaultResult = "/var/tmp";
+#endif
+  result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
 }
 
-error_code has_root_directory(const Twine &path, bool &result) {
+bool has_root_name(const Twine &path) {
   SmallString<128> path_storage;
   StringRef p = path.toStringRef(path_storage);
 
-  if (error_code ec = root_directory(p, p)) return ec;
-
-  result = !p.empty();
-  return success;
+  return !root_name(p).empty();
 }
 
-error_code has_root_path(const Twine &path, bool &result) {
+bool has_root_directory(const Twine &path) {
   SmallString<128> path_storage;
   StringRef p = path.toStringRef(path_storage);
 
-  if (error_code ec = root_path(p, p)) return ec;
-
-  result = !p.empty();
-  return success;
+  return !root_directory(p).empty();
 }
 
-error_code has_filename(const Twine &path, bool &result) {
+bool has_root_path(const Twine &path) {
   SmallString<128> path_storage;
   StringRef p = path.toStringRef(path_storage);
 
-  if (error_code ec = filename(p, p)) return ec;
-
-  result = !p.empty();
-  return success;
+  return !root_path(p).empty();
 }
 
-error_code has_parent_path(const Twine &path, bool &result) {
+bool has_relative_path(const Twine &path) {
   SmallString<128> path_storage;
   StringRef p = path.toStringRef(path_storage);
 
-  if (error_code ec = parent_path(p, p)) return ec;
-
-  result = !p.empty();
-  return success;
+  return !relative_path(p).empty();
 }
 
-error_code has_stem(const Twine &path, bool &result) {
+bool has_filename(const Twine &path) {
   SmallString<128> path_storage;
   StringRef p = path.toStringRef(path_storage);
 
-  if (error_code ec = stem(p, p)) return ec;
+  return !filename(p).empty();
+}
+
+bool has_parent_path(const Twine &path) {
+  SmallString<128> path_storage;
+  StringRef p = path.toStringRef(path_storage);
 
-  result = !p.empty();
-  return success;
+  return !parent_path(p).empty();
 }
 
-error_code has_extension(const Twine &path, bool &result) {
+bool has_stem(const Twine &path) {
   SmallString<128> path_storage;
   StringRef p = path.toStringRef(path_storage);
 
-  if (error_code ec = extension(p, p)) return ec;
+  return !stem(p).empty();
+}
 
-  result = !p.empty();
-  return success;
+bool has_extension(const Twine &path) {
+  SmallString<128> path_storage;
+  StringRef p = path.toStringRef(path_storage);
+
+  return !extension(p).empty();
 }
 
-error_code is_absolute(const Twine &path, bool &result) {
+bool is_absolute(const Twine &path) {
   SmallString<128> path_storage;
   StringRef p = path.toStringRef(path_storage);
 
-  bool rootDir = false,
-       rootName = false;
-  if (error_code ec = has_root_directory(p, rootDir)) return ec;
+  bool rootDir = has_root_directory(p),
 #ifdef LLVM_ON_WIN32
-  if (error_code ec = has_root_name(p, rootName)) return ec;
+       rootName = has_root_name(p);
 #else
-  rootName = true;
+       rootName = true;
 #endif
 
-  result = rootDir && rootName;
-  return success;
+  return rootDir && rootName;
 }
 
-error_code is_relative(const Twine &path, bool &result) {
-  bool res;
-  error_code ec = is_absolute(path, res);
-  result = !res;
-  return ec;
+bool is_relative(const Twine &path) {
+  return !is_absolute(path);
 }
 
 } // end namespace path
 
 namespace fs {
 
+error_code make_absolute(SmallVectorImpl<char> &path) {
+  StringRef p(path.data(), path.size());
+
+  bool rootDirectory = path::has_root_directory(p),
+#ifdef LLVM_ON_WIN32
+       rootName = path::has_root_name(p);
+#else
+       rootName = true;
+#endif
+
+  // Already absolute.
+  if (rootName && rootDirectory)
+    return error_code::success();
+
+  // All of the following conditions will need the current directory.
+  SmallString<128> current_dir;
+  if (error_code ec = current_path(current_dir)) return ec;
+
+  // Relative path. Prepend the current directory.
+  if (!rootName && !rootDirectory) {
+    // Append path to the current directory.
+    path::append(current_dir, p);
+    // Set path to the result.
+    path.swap(current_dir);
+    return error_code::success();
+  }
+
+  if (!rootName && rootDirectory) {
+    StringRef cdrn = path::root_name(current_dir);
+    SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
+    path::append(curDirRootName, p);
+    // Set path to the result.
+    path.swap(curDirRootName);
+    return error_code::success();
+  }
+
+  if (rootName && !rootDirectory) {
+    StringRef pRootName      = path::root_name(p);
+    StringRef bRootDirectory = path::root_directory(current_dir);
+    StringRef bRelativePath  = path::relative_path(current_dir);
+    StringRef pRelativePath  = path::relative_path(p);
+
+    SmallString<128> res;
+    path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
+    path.swap(res);
+    return error_code::success();
+  }
+
+  llvm_unreachable("All rootName and rootDirectory combinations should have "
+                   "occurred above!");
+}
+
 error_code create_directories(const Twine &path, bool &existed) {
   SmallString<128> path_storage;
   StringRef p = path.toStringRef(path_storage);
 
-  StringRef parent;
-  bool parent_exists;
-  if (error_code ec = path::parent_path(p, parent)) return ec;
-  if (error_code ec = fs::exists(parent, parent_exists)) return ec;
+  StringRef parent = path::parent_path(p);
+  if (!parent.empty()) {
+    bool parent_exists;
+    if (error_code ec = fs::exists(parent, parent_exists)) return ec;
 
-  if (!parent_exists)
-    return create_directories(parent, existed);
+    if (!parent_exists)
+      if (error_code ec = create_directories(parent, existed)) return ec;
+  }
 
   return create_directory(p, existed);
 }
 
+bool exists(file_status status) {
+  return status_known(status) && status.type() != file_type::file_not_found;
+}
+
+bool status_known(file_status s) {
+  return s.type() != file_type::status_error;
+}
+
+bool is_directory(file_status status) {
+  return status.type() == file_type::directory_file;
+}
+
+error_code is_directory(const Twine &path, bool &result) {
+  file_status st;
+  if (error_code ec = status(path, st))
+    return ec;
+  result = is_directory(st);
+  return error_code::success();
+}
+
+bool is_regular_file(file_status status) {
+  return status.type() == file_type::regular_file;
+}
+
+error_code is_regular_file(const Twine &path, bool &result) {
+  file_status st;
+  if (error_code ec = status(path, st))
+    return ec;
+  result = is_regular_file(st);
+  return error_code::success();
+}
+
+bool is_symlink(file_status status) {
+  return status.type() == file_type::symlink_file;
+}
+
+error_code is_symlink(const Twine &path, bool &result) {
+  file_status st;
+  if (error_code ec = status(path, st))
+    return ec;
+  result = is_symlink(st);
+  return error_code::success();
+}
+
+bool is_other(file_status status) {
+  return exists(status) &&
+         !is_regular_file(status) &&
+         !is_directory(status) &&
+         !is_symlink(status);
+}
+
+void directory_entry::replace_filename(const Twine &filename, file_status st) {
+  SmallString<128> path(Path.begin(), Path.end());
+  path::remove_filename(path);
+  path::append(path, filename);
+  Path = path.str();
+  Status = st;
+}
+
+error_code has_magic(const Twine &path, const Twine &magic, bool &result) {
+  SmallString<32>  MagicStorage;
+  StringRef Magic = magic.toStringRef(MagicStorage);
+  SmallString<32> Buffer;
+
+  if (error_code ec = get_magic(path, Magic.size(), Buffer)) {
+    if (ec == errc::value_too_large) {
+      // Magic.size() > file_size(Path).
+      result = false;
+      return error_code::success();
+    }
+    return ec;
+  }
+
+  result = Magic == Buffer;
+  return error_code::success();
+}
+
+/// @brief Identify the magic in magic.
+file_magic identify_magic(StringRef magic) {
+  if (magic.size() < 4)
+    return file_magic::unknown;
+  switch ((unsigned char)magic[0]) {
+    case 0xDE:  // 0x0B17C0DE = BC wraper
+      if (magic[1] == (char)0xC0 && magic[2] == (char)0x17 &&
+          magic[3] == (char)0x0B)
+        return file_magic::bitcode;
+      break;
+    case 'B':
+      if (magic[1] == 'C' && magic[2] == (char)0xC0 && magic[3] == (char)0xDE)
+        return file_magic::bitcode;
+      break;
+    case '!':
+      if (magic.size() >= 8)
+        if (memcmp(magic.data(),"!<arch>\n",8) == 0)
+          return file_magic::archive;
+      break;
+
+    case '\177':
+      if (magic[1] == 'E' && magic[2] == 'L' && magic[3] == 'F') {
+        if (magic.size() >= 18 && magic[17] == 0)
+          switch (magic[16]) {
+            default: break;
+            case 1: return file_magic::elf_relocatable;
+            case 2: return file_magic::elf_executable;
+            case 3: return file_magic::elf_shared_object;
+            case 4: return file_magic::elf_core;
+          }
+      }
+      break;
+
+    case 0xCA:
+      if (magic[1] == char(0xFE) && magic[2] == char(0xBA) &&
+          magic[3] == char(0xBE)) {
+        // This is complicated by an overlap with Java class files.
+        // See the Mach-O section in /usr/share/file/magic for details.
+        if (magic.size() >= 8 && magic[7] < 43)
+          // FIXME: Universal Binary of any type.
+          return file_magic::macho_dynamically_linked_shared_lib;
+      }
+      break;
+
+      // The two magic numbers for mach-o are:
+      // 0xfeedface - 32-bit mach-o
+      // 0xfeedfacf - 64-bit mach-o
+    case 0xFE:
+    case 0xCE:
+    case 0xCF: {
+      uint16_t type = 0;
+      if (magic[0] == char(0xFE) && magic[1] == char(0xED) &&
+          magic[2] == char(0xFA) &&
+          (magic[3] == char(0xCE) || magic[3] == char(0xCF))) {
+        /* Native endian */
+        if (magic.size() >= 16) type = magic[14] << 8 | magic[15];
+      } else if ((magic[0] == char(0xCE) || magic[0] == char(0xCF)) &&
+                 magic[1] == char(0xFA) && magic[2] == char(0xED) &&
+                 magic[3] == char(0xFE)) {
+        /* Reverse endian */
+        if (magic.size() >= 14) type = magic[13] << 8 | magic[12];
+      }
+      switch (type) {
+        default: break;
+        case 1: return file_magic::macho_object;
+        case 2: return file_magic::macho_executable;
+        case 3: return file_magic::macho_fixed_virtual_memory_shared_lib;
+        case 4: return file_magic::macho_core;
+        case 5: return file_magic::macho_preload_executabl;
+        case 6: return file_magic::macho_dynamically_linked_shared_lib;
+        case 7: return file_magic::macho_dynamic_linker;
+        case 8: return file_magic::macho_bundle;
+        case 9: return file_magic::macho_dynamic_linker;
+        case 10: return file_magic::macho_dsym_companion;
+      }
+      break;
+    }
+    case 0xF0: // PowerPC Windows
+    case 0x83: // Alpha 32-bit
+    case 0x84: // Alpha 64-bit
+    case 0x66: // MPS R4000 Windows
+    case 0x50: // mc68K
+    case 0x4c: // 80386 Windows
+      if (magic[1] == 0x01)
+        return file_magic::coff_object;
+
+    case 0x90: // PA-RISC Windows
+    case 0x68: // mc68K Windows
+      if (magic[1] == 0x02)
+        return file_magic::coff_object;
+      break;
+
+    case 0x4d: // Possible MS-DOS stub on Windows PE file
+      if (magic[1] == 0x5a) {
+        uint32_t off =
+          *reinterpret_cast<const support::ulittle32_t*>(magic.data() + 0x3c);
+        // PE/COFF file, either EXE or DLL.
+        if (off < magic.size() && memcmp(magic.data() + off, "PE\0\0",4) == 0)
+          return file_magic::pecoff_executable;
+      }
+      break;
+
+    case 0x64: // x86-64 Windows.
+      if (magic[1] == char(0x86))
+        return file_magic::coff_object;
+      break;
+
+    default:
+      break;
+  }
+  return file_magic::unknown;
+}
+
+error_code identify_magic(const Twine &path, file_magic &result) {
+  SmallString<32> Magic;
+  error_code ec = get_magic(path, Magic.capacity(), Magic);
+  if (ec && ec != errc::value_too_large)
+    return ec;
+
+  result = identify_magic(Magic);
+  return error_code::success();
+}
+
+namespace {
+error_code remove_all_r(StringRef path, file_type ft, uint32_t &count) {
+  if (ft == file_type::directory_file) {
+    // This code would be a lot better with exceptions ;/.
+    error_code ec;
+    directory_iterator i(path, ec);
+    if (ec) return ec;
+    for (directory_iterator e; i != e; i.increment(ec)) {
+      if (ec) return ec;
+      file_status st;
+      if (error_code ec = i->status(st)) return ec;
+      if (error_code ec = remove_all_r(i->path(), st.type(), count)) return ec;
+    }
+    bool obviously_this_exists;
+    if (error_code ec = remove(path, obviously_this_exists)) return ec;
+    assert(obviously_this_exists);
+    ++count; // Include the directory itself in the items removed.
+  } else {
+    bool obviously_this_exists;
+    if (error_code ec = remove(path, obviously_this_exists)) return ec;
+    assert(obviously_this_exists);
+    ++count;
+  }
+
+  return error_code::success();
+}
+} // end unnamed namespace
+
+error_code remove_all(const Twine &path, uint32_t &num_removed) {
+  SmallString<128> path_storage;
+  StringRef p = path.toStringRef(path_storage);
+
+  file_status fs;
+  if (error_code ec = status(path, fs))
+    return ec;
+  num_removed = 0;
+  return remove_all_r(p, fs.type(), num_removed);
+}
+
+error_code directory_entry::status(file_status &result) const {
+  return fs::status(Path, result);
+}
+
 } // end namespace fs
 } // end namespace sys
 } // end namespace llvm