[llvm] [Support][Windows][DTLTO] Expand system temp path to avoid 8.3 short paths (PR #175196)

via llvm-commits llvm-commits at lists.llvm.org
Fri Jan 9 10:54:17 PST 2026


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-llvm-support

Author: Ben Dunbobbin (bd1976bris)

<details>
<summary>Changes</summary>

On Windows, the system temporary directory is commonly derived from the `TMP` environment variable. For historical compatibility reasons, this variable is often set to an 8.3-form short path. This is especially common on systems where user names exceed eight characters; for example, a user name of `dunbobbin` may result in `C:\Users\DUNBOB~1\AppData\Local\Temp`.

8.3 short paths are undesirable for distributed compilation scenarios, as they are a local mapping tied to a specific folder on a specific machine, and they can break or defeat sandboxing/path-based isolation used by distributed build systems. Such failures have been observed for DTLTO (https://llvm.org/docs/DTLTO.html), which is the primary motivation for this change. For example, on my machine, running:
```
clang.exe hello.c -flto=thin -fthinlto-distributor=fastbuild.exe -fuse-ld=lld -nostdlib -###
```
results in 8.3 short-form paths being passed to LLD (output paraphrased):
```
ld.lld -o a.out -plugin-opt=thinlto \
  --thinlto-distributor=fastbuild.exe \
  --thinlto-remote-compiler=clang.exe \
  C:\Users\DUNBOB~1\AppData\Local\Temp\hello-380d65.o
```
For DTLTO, distribution-specific logic is kept out of LLVM where possible, but path normalization is required for ThinLTO ModuleIDs. The `TMP` environment variable is the main source of 8.3 paths, and normalizing here avoids intrusive changes elsewhere.

In addition to distribution, 8.3 short paths are also confusing and inconvenient to work with; for example, tab completion in the Windows Command Prompt does not work reliably with 8.3 paths.

Note that, in practice, especially in automated and CI environments, users often have limited control over their environment variables. Normalizing the system temporary directory to its long-path form therefore improves usability and robustness.

SIE internal tracker: TOOLCHAIN-19185

---
Full diff: https://github.com/llvm/llvm-project/pull/175196.diff


3 Files Affected:

- (modified) llvm/include/llvm/Support/Windows/WindowsSupport.h (+4) 
- (modified) llvm/lib/Support/Windows/Path.inc (+59-11) 
- (modified) llvm/unittests/Support/Path.cpp (+203) 


``````````diff
diff --git a/llvm/include/llvm/Support/Windows/WindowsSupport.h b/llvm/include/llvm/Support/Windows/WindowsSupport.h
index f35e7b55cb8d3..f2d9d700402ae 100644
--- a/llvm/include/llvm/Support/Windows/WindowsSupport.h
+++ b/llvm/include/llvm/Support/Windows/WindowsSupport.h
@@ -249,6 +249,10 @@ LLVM_ABI std::error_code widenPath(const Twine &Path8,
 /// ensuring we're not retrieving a malicious injected module but a module
 /// loaded from the system path.
 LLVM_ABI HMODULE loadSystemModuleSecure(LPCWSTR lpModuleName);
+
+/// Convert UTF-8 path into a long form UTF-8 path.
+LLVM_ABI std::error_code makeLongPath(const Twine &Path8,
+                                      llvm::SmallVectorImpl<char> &Result8);
 } // end namespace windows
 } // end namespace sys
 } // end namespace llvm.
diff --git a/llvm/lib/Support/Windows/Path.inc b/llvm/lib/Support/Windows/Path.inc
index 3a9af4352b3bf..0fa6b2aa4a825 100644
--- a/llvm/lib/Support/Windows/Path.inc
+++ b/llvm/lib/Support/Windows/Path.inc
@@ -60,6 +60,19 @@ static bool is_separator(const wchar_t value) {
   }
 }
 
+static void stripExtendedPrefix(wchar_t *&Data, DWORD &CountChars) {
+  if (CountChars >= 8 && ::memcmp(Data, L"\\\\?\\UNC\\", 16) == 0) {
+    // Convert \\?\UNC\foo\bar to \\foo\bar
+    CountChars -= 6;
+    Data += 6;
+    Data[0] = '\\';
+  } else if (CountChars >= 4 && ::memcmp(Data, L"\\\\?\\", 8) == 0) {
+    // Convert \\?\C:\foo to C:\foo
+    CountChars -= 4;
+    Data += 4;
+  }
+}
+
 namespace llvm {
 namespace sys {
 namespace windows {
@@ -127,6 +140,46 @@ std::error_code widenPath(const Twine &Path8, SmallVectorImpl<wchar_t> &Path16,
   return UTF8ToUTF16(FullPath, Path16);
 }
 
+std::error_code makeLongPath(const Twine &Path8,
+                             llvm::SmallVectorImpl<char> &Result8) {
+  constexpr StringLiteral LongPathPrefix = R"(\\?\)";
+
+  SmallString<128> PathStorage;
+  StringRef PathStr = Path8.toStringRef(PathStorage);
+  bool HadPrefix = PathStr.starts_with(LongPathPrefix);
+
+  SmallVector<wchar_t, 128> Path16;
+  if (std::error_code EC = widenPath(PathStr, Path16))
+    return EC;
+
+  // Start with a buffer equal to input.
+  llvm::SmallVector<wchar_t, 128> Long16;
+  DWORD Len = static_cast<DWORD>(Path16.size());
+
+  do {
+    Long16.resize_for_overwrite(Len);
+
+    Len = ::GetLongPathNameW(Path16.data(), Long16.data(), Len);
+
+    // A zero return value indicates a failure other than insufficient space.
+    if (Len == 0)
+      return mapWindowsError(::GetLastError());
+
+    // If there's insufficient space, the len returned is larger than the len
+    // given - in this case len includes the null-terminator.
+  } while (Len >= Long16.size());
+
+  // On success, GetLongPathNameW returns the number of characters not
+  // including the null-terminator.
+  Long16.truncate(Len);
+  // Strip \\?\ or \\?\UNC\ prefix if it wasn't part of the original path
+  wchar_t *Data = Long16.data();
+  if (!HadPrefix)
+    stripExtendedPrefix(Data, Len);
+
+  return sys::windows::UTF16ToUTF8(Data, Len, Result8);
+}
+
 } // end namespace windows
 
 namespace fs {
@@ -405,16 +458,7 @@ static std::error_code realPathFromHandle(HANDLE H,
   // paths don't get canonicalized by file APIs.
   wchar_t *Data = Buffer.data();
   DWORD CountChars = Buffer.size();
-  if (CountChars >= 8 && ::memcmp(Data, L"\\\\?\\UNC\\", 16) == 0) {
-    // Convert \\?\UNC\foo\bar to \\foo\bar
-    CountChars -= 6;
-    Data += 6;
-    Data[0] = '\\';
-  } else if (CountChars >= 4 && ::memcmp(Data, L"\\\\?\\", 8) == 0) {
-    // Convert \\?\c:\foo to c:\foo
-    CountChars -= 4;
-    Data += 4;
-  }
+  stripExtendedPrefix(Data, CountChars);
 
   // Convert the result from UTF-16 to UTF-8.
   if (std::error_code EC = UTF16ToUTF8(Data, CountChars, RealPath))
@@ -1619,12 +1663,16 @@ void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
 
   // Check whether the temporary directory is specified by an environment var.
   // This matches GetTempPath logic to some degree. GetTempPath is not used
-  // directly as it cannot handle evn var longer than 130 chars on Windows 7
+  // directly as it cannot handle env var longer than 130 chars on Windows 7
   // (fixed on Windows 8).
   if (getTempDirEnvVar(Result)) {
     assert(!Result.empty() && "Unexpected empty path");
     native(Result); // Some Unix-like shells use Unix path separator in $TMP.
     fs::make_absolute(Result); // Make it absolute if not already.
+    // Expand to long-form. Best-effort; ignore failure.
+    SmallString<260> LongPath;
+    if (!llvm::sys::windows::makeLongPath(Result, LongPath))
+      Result.assign(LongPath.begin(), LongPath.end());
     return;
   }
 
diff --git a/llvm/unittests/Support/Path.cpp b/llvm/unittests/Support/Path.cpp
index 7f22b7c2edb4b..97ebcd76ca0ca 100644
--- a/llvm/unittests/Support/Path.cpp
+++ b/llvm/unittests/Support/Path.cpp
@@ -32,6 +32,7 @@
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/Support/Chrono.h"
 #include "llvm/Support/Windows/WindowsSupport.h"
+#include <fileapi.h>
 #include <windows.h>
 #include <winerror.h>
 #endif
@@ -658,6 +659,137 @@ TEST(SupportDeathTest, TempDirectoryOnWindows) {
   ASSERT_EQ(260U, Expected.size());
   EXPECT_TEMP_DIR(_putenv_s("TMP", Expected.c_str()), Expected.c_str());
 }
+
+/// Checks whether short (8.3) names are enabled in the given UTF-8 path. This
+/// is the best way I have found of checking this. Note that 8.3 names can be
+/// enabled and disabled on a per-folder, per-volume, and per-system basis.
+static bool areShortNamesEnabled(llvm::StringRef Path8) {
+  // Create a directory under Path8 with a name long enough that Windows will
+  // provide a shortened 8.3 form name, if 8.3 names are enabled.
+  SmallString<256> Dir(Path8);
+  path::append(Dir, "verylongdir");
+  if (std::error_code EC = fs::create_directories(Dir))
+    return false;
+
+  // Check if the expected 8.3 form name was created.
+  SmallString<256> Short(Path8);
+  path::append(Short, "verylo~1");
+  bool Result = fs::is_directory(Short);
+
+  fs::remove_directories(Dir);
+  return Result;
+}
+
+/// Returns the 8.3 path for the given UTF-8 path, or an empty string on
+/// failure. Uses Win32 GetShortPathNameW.
+static std::string getShortPathName(llvm::StringRef Path8) {
+  // Convert UTF-8 to UTF-16.
+  SmallVector<wchar_t, MAX_PATH> Path16;
+  if (std::error_code EC = sys::windows::widenPath(Path8, Path16))
+    return {};
+
+  // Get required buffer size for short path (includes null terminator).
+  DWORD Required = ::GetShortPathNameW(Path16.data(), nullptr, 0);
+  if (Required == 0)
+    return {};
+
+  SmallVector<wchar_t, MAX_PATH> ShortPath;
+  ShortPath.resize_for_overwrite(Required);
+
+  DWORD Written =
+      ::GetShortPathNameW(Path16.data(), ShortPath.data(), Required);
+  if (Written == 0 || Written >= Required)
+    return {};
+
+  ShortPath.truncate(Written);
+
+  SmallString<128> Utf8Result;
+  if (std::error_code EC = sys::windows::UTF16ToUTF8(
+          ShortPath.data(), ShortPath.size(), Utf8Result))
+    return {};
+
+  return std::string(Utf8Result);
+}
+
+/// Returns true if the two paths refer to the same file or directory by
+/// comparing their UniqueIDs.
+static bool sameEntity(llvm::StringRef P1, llvm::StringRef P2) {
+  fs::UniqueID ID1, ID2;
+  return !fs::getUniqueID(P1, ID1) && !fs::getUniqueID(P2, ID2) && ID1 == ID2;
+}
+
+TEST(SupportDeathTest, ShortFormTempDir) {
+  SmallString<128> TestDir;
+  ASSERT_NO_ERROR(
+      fs::createUniqueDirectory("short-form-temp-dir-test", TestDir));
+
+  if (!areShortNamesEnabled(TestDir))
+    GTEST_SKIP() << "Short names not enabled in: " << TestDir;
+
+  // Create a test directory longer than 8 characters for which a distinct
+  // short form alias will be created on Windows. Typically, 123456~1.
+  constexpr const char *ShortenableDir = "\\123456789"; // >8 chars
+
+  // Capture the 8.3-form short alias.
+  SmallString<256> ShortenablePath(TestDir);
+  path::append(ShortenablePath, ShortenableDir);
+  ASSERT_NO_ERROR(fs::create_directories(ShortenablePath));
+  std::string ShortPath = getShortPathName(ShortenablePath);
+  ASSERT_FALSE(ShortPath.empty())
+      << "Expected 8.3 short path form for test directory.";
+
+  // Case 1: 8.3-form short paths are expanded (use a seperate process to avoid
+  // env var pollution).
+  EXPECT_EXIT(
+      {
+        auto Fail = [] { std::exit(1); };
+
+        if (_putenv_s("TMP", ShortPath.c_str()) != 0)
+          Fail();
+
+        SmallString<128> TempPath;
+        path::system_temp_directory(true, TempPath);
+
+        // Ensure TMP refers to the same directory as the short path.
+        if (!sameEntity(ShortPath, TempPath))
+          Fail();
+
+        // Check that TMP was expanded as expected.
+        SmallString<128> LongPath;
+        if (windows::makeLongPath(ShortPath, LongPath))
+          Fail();
+        if (LongPath != TempPath)
+          Fail();
+
+        std::exit(0);
+      },
+      ::testing::ExitedWithCode(0), ".*" /*Match anything*/);
+
+  // Case 2: Paths that can't be expanded (e.g. a non-existent short path) do
+  // not result in an error.
+  SmallString<256> UnshortenablePath(TestDir);
+  path::append(UnshortenablePath, "NotEre~1");
+  ASSERT_FALSE(fs::exists(UnshortenablePath));
+
+  // Test env var is not expanded in a seperate process (avoids env var
+  // pollution).
+  EXPECT_EXIT(
+      {
+        auto Fail = [] { std::exit(1); };
+
+        if (_putenv_s("TMP", UnshortenablePath.c_str()) != 0)
+          Fail();
+
+        SmallString<128> TempPath;
+        path::system_temp_directory(true, TempPath);
+
+        if (TempPath != UnshortenablePath)
+          Fail();
+
+        std::exit(0);
+      },
+      ::testing::ExitedWithCode(0), ".*" /*Match anything*/);
+}
 #endif
 
 class FileSystemTest : public testing::Test {
@@ -2485,6 +2617,77 @@ TEST_F(FileSystemTest, widenPath) {
 #endif
 
 #ifdef _WIN32
+/// Removes the Windows extended path prefix (\\?\ or \\?\UNC\) from the given
+/// UTF-8 path, if present.
+static std::string stripPrefix(llvm::StringRef P) {
+  if (P.starts_with(R"(\\?\UNC\)"))
+    return "\\" + P.drop_front(7).str();
+  if (P.starts_with(R"(\\?\)"))
+    return P.drop_front(4).str();
+  return P.str();
+}
+
+TEST_F(FileSystemTest, makeLongPath) {
+  if (!areShortNamesEnabled(TestDirectory.str()))
+    GTEST_SKIP() << "Short names not enabled in: " << TestDirectory;
+
+  // Setup: A test directory longer than 8 characters for which a distinct
+  // short form will be created on Windows. Typically, 123456~1.
+  constexpr const char *OneDir = "\\123456789"; // >8 chars
+
+  // Setup: Create a path where even if all components were reduced to short
+  // form, the total length would exceed MAX_PATH.
+  SmallString<MAX_PATH * 2> Deep(TestDirectory);
+  const size_t NLevels = (MAX_PATH / 8) + 1;
+  for (size_t I = 0; I < NLevels; ++I)
+    Deep.append(OneDir);
+
+  ASSERT_NO_ERROR(fs::create_directories(Deep));
+
+  // Setup: Create prefixed and non-prefixed 8.3 forms of the deep test path we
+  // just created.
+  std::string DeepShortWithPrefix = getShortPathName(Deep);
+  ASSERT_TRUE(StringRef(DeepShortWithPrefix).starts_with(R"(\\?\)"))
+      << "Expected prefixed short path, got: " << DeepShortWithPrefix;
+  std::string DeepShort = stripPrefix(DeepShortWithPrefix);
+
+  // Setup: Create an 8.3-form short path for the first-level directory.
+  SmallString<256> FirstLevel(TestDirectory);
+  FirstLevel.append(OneDir);
+  std::string Short = getShortPathName(FirstLevel);
+  ASSERT_FALSE(Short.empty())
+      << "Expected 8.3 short path form for test directory.";
+
+  // Case 1: Non-existent short path.
+  SmallString<128> NoExist("NotEre~1");
+  ASSERT_FALSE(fs::exists(NoExist));
+  SmallString<128> NoExistResult;
+  EXPECT_TRUE(windows::makeLongPath(NoExist, NoExistResult));
+  EXPECT_TRUE(NoExistResult.empty());
+
+  // Case 2: Valid short path.
+  SmallString<128> ShortResult;
+  ASSERT_FALSE(windows::makeLongPath(Short, ShortResult));
+  EXPECT_TRUE(sameEntity(Short, ShortResult));
+
+  // Case 3: Deep short path without \\?\ prefix.
+  SmallString<128> DeepResult;
+  ASSERT_FALSE(windows::makeLongPath(DeepShort, DeepResult));
+  EXPECT_TRUE(sameEntity(DeepShort, DeepResult));
+  EXPECT_FALSE(StringRef(DeepResult).starts_with(R"(\\?\)"))
+      << "Expected unprefixed result, got: " << DeepResult;
+
+  // Case 4: Deep short path with \\?\ prefix.
+  SmallString<128> DeepPrefixedResult;
+  ASSERT_FALSE(windows::makeLongPath(DeepShortWithPrefix, DeepPrefixedResult));
+  EXPECT_TRUE(sameEntity(DeepShortWithPrefix, DeepPrefixedResult));
+  EXPECT_TRUE(StringRef(DeepPrefixedResult).starts_with(R"(\\?\)"))
+      << "Expected prefixed result, got: " << DeepPrefixedResult;
+
+  // Cleanup.
+  ASSERT_NO_ERROR(fs::remove_directories(TestDirectory.str()));
+}
+
 // Windows refuses lock request if file region is already locked by the same
 // process. POSIX system in this case updates the existing lock.
 TEST_F(FileSystemTest, FileLocker) {

``````````

</details>


https://github.com/llvm/llvm-project/pull/175196


More information about the llvm-commits mailing list