Support/FileSystem: Add create_symlink implementation.
authorMichael J. Spencer <bigcheesegs@gmail.com>
Fri, 3 Dec 2010 07:41:25 +0000 (07:41 +0000)
committerMichael J. Spencer <bigcheesegs@gmail.com>
Fri, 3 Dec 2010 07:41:25 +0000 (07:41 +0000)
git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@120800 91177308-0d34-0410-b5e6-96231b3b80d8

lib/Support/Unix/PathV2.inc
lib/Support/Windows/PathV2.inc

index 2bde7805f0985a1da2f4b8aed18206835a47f5a2..985dde7426a9fefba910e316b96147636c6d6a2d 100644 (file)
@@ -173,6 +173,19 @@ error_code create_hard_link(const Twine &to, const Twine &from) {
   return make_error_code(errc::success);
 }
 
+error_code create_symlink(const Twine &to, const Twine &from) {
+  // Get arguments.
+  SmallString<128> from_storage;
+  SmallString<128> to_storage;
+  StringRef f = from.toNullTerminatedStringRef(from_storage);
+  StringRef t = to.toNullTerminatedStringRef(to_storage);
+
+  if (::symlink(t.begin(), f.begin()) == -1)
+    return error_code(errno, system_category());
+
+  return make_error_code(errc::success);
+}
+
 error_code exists(const Twine &path, bool &result) {
   SmallString<128> path_storage;
   StringRef p = path.toNullTerminatedStringRef(path_storage);
index d374dccdeb6ebf8aadc184d51fa6f67d8fc85a31..b15f47777df1ac33f4d820d6d64290513069797d 100644 (file)
 using namespace llvm;
 
 namespace {
+  typedef BOOLEAN (WINAPI *PtrCreateSymbolicLinkW)(\r
+    /*__in*/ LPCWSTR lpSymlinkFileName,\r
+    /*__in*/ LPCWSTR lpTargetFileName,\r
+    /*__in*/ DWORD dwFlags);\r
+\r
+  PtrCreateSymbolicLinkW create_symbolic_link_api = PtrCreateSymbolicLinkW(\r
+    ::GetProcAddress(::GetModuleHandleA("kernel32.dll"),
+                     "CreateSymbolicLinkW"));
+
   error_code UTF8ToUTF16(const StringRef &utf8,
                                SmallVectorImpl<wchar_t> &utf16) {
     int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
@@ -220,6 +229,29 @@ error_code create_hard_link(const Twine &to, const Twine &from) {
   return make_error_code(errc::success);
 }
 
+error_code create_symlink(const Twine &to, const Twine &from) {
+  // Only do it if the function is available at runtime.
+  if (!create_symbolic_link_api)
+    return make_error_code(errc::function_not_supported);
+
+  // Get arguments.
+  SmallString<128> from_storage;
+  SmallString<128> to_storage;
+  StringRef f = from.toStringRef(from_storage);
+  StringRef t = to.toStringRef(to_storage);
+
+  // Convert to utf-16.
+  SmallVector<wchar_t, 128> wide_from;
+  SmallVector<wchar_t, 128> wide_to;
+  if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
+  if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
+
+  if (!create_symbolic_link_api(wide_from.begin(), wide_to.begin(), NULL))
+    return make_error_code(windows_error(::GetLastError()));
+
+  return make_error_code(errc::success);
+}
+
 error_code exists(const Twine &path, bool &result) {
   SmallString<128> path_storage;
   SmallVector<wchar_t, 128> path_utf16;