Repository navigation
[Support][Windows][DTLTO] Expand short 8.3 form system temp dirs - #175196
bd1976bris wants to merge 2 commits into
Conversation
10dfada to
d40f5f8
Compare
|
@llvm/pr-subscribers-platform-windows @llvm/pr-subscribers-llvm-support Author: Ben Dunbobbin (bd1976bris) ChangesOn Windows, the system temporary directory is commonly derived from the 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: results in 8.3 short-form paths being passed to LLD (output paraphrased): For DTLTO, distribution-specific logic is kept out of LLVM where possible, but path normalization is required for ThinLTO ModuleIDs. The 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 3 Files Affected:
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) {
|
This comment was marked as spam.
This comment was marked as spam.
d40f5f8 to
6dbf380
Compare
6dbf380 to
3b17ed1
Compare
|
Force pushed to simplify the testing, share some constants in |
On Windows, the system temporary directory is commonly derived from the `TMP` environment variable. For historical compatibility reasons, this variable is often set to a short 8.3 form 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`. Short 8.3 form 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 -### results in short 8.3 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 Module IDs. The `TMP` environment variable is the main source of short 8.3 form paths, and normalizing here avoids intrusive changes elsewhere. In addition to distribution, short 8.3 form paths are also confusing and inconvenient to work with; for example, tab completion in the Windows Command Prompt does not work reliably with short 8.3 form 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 path to its long form therefore improves usability and robustness. SIE internal tracker: TOOLCHAIN-19185
3b17ed1 to
571a90d
Compare
|
Force-pushed to add minor improvements to comments, improve the naming of functions and variables, and define wide constants using the same raw string literal constructs as the narrow versions. |
|
Hi reviewers (@aganea, @cachemeifyoucan, @teresajohnson, @efriedma-quic, @tru, @mstorsjo), can I please ask whether you think that adding this normalization to the Windows temp dir path is acceptable? Whilst I personally would like to see short 8.3 form paths removed, and I think that the arguments I presented in this PR’s description are reasonable, I can accept that no one has felt the need to make this change in the years of Windows support. It therefore seems likely that DTLTO is the only substantial justification for this. Given that, I can see the point of view that this patch is at too low a level to be justified (just for DTLTO)? |
|
I don't understand the direct connection between path normalization vs. distributed build system. Are you trying to turn that into a unified location on all machines? But what if user doesn't have write permission to the directory? Or user is expecting to write to a different drive/partition?
|
A distribution system needs to be able to schedule compilation jobs onto remote nodes. To execute on a remote node, some sort of sandboxing/path-virtualization is required so that when a remote compilation loads from a specific path, it gets the same data that it would see on the machine from which the compilation job originated. On Linux (I'm unsure about the Mac side of things - Sorry), this is often provided by a distinct component, e.g. https://github.com/containers/bubblewrap, or a technology layer such as NFS. However, on Windows, both of these functions are typically combined under one system. See for example, Incredibuild™'s description of "Virtualized Distributed Processing™" in their documentation, or Unreal™'s UBA documentation, which talks about "Lightweight Virtualization". Windows supports legacy short 8.3 form names in the filesystem (see: https://en.wikipedia.org/wiki/8.3_filename). You might have seen paths like:
Thanks. It's certainly the case that the user can adjust their build system or environment to prevent this style of paths from causing an issue along the lines that you suggest. However, one of the important features of DTLTO is that the user doesn't need to make such adjustments - the distribution should just work. Hence the requirement for normalization. Having said all that I don't necessarily have to remove short 8.3 form paths by normalization |
|
You didn't really answer my question. I still don't think path canonicalization in LLVM/compiler is a good idea in general but I won't be the one reluctantly blocking it if you insist. Path virtualization and sanitization is all good, but that is not the job of compiler/linker. And of course, you see different system has different ways to approach this so hard coding some implementation inside the compiler is not a good idea. That is why I propose the solution needs to be configurable so the user or the build system can configure where the output should be. If you worried about user making mistake without using the configuration correctly, we should provide good diagnostics when such condition is detected. Just enforcing a certain ways of doing it is not the best approach. |
Thanks for the feedback, and apologies for not addressing your question directly earlier - I was trying to provide some Windows-specific context.
I agree that, in general, path canonicalization and virtualization should be configurable and not hard-coded in the compiler or linker. Your earlier suggestion of a clang driver option to control where intermediate outputs are placed (or something similar) seems like a good long-term direction, particularly for supporting a wider range of distributed build systems, and I agree that this would be valuable for upstream DTLTO. However on Windows today the situation is narrower: the most commonly used distribution systems are already supported by DTLTO, and our main source of observed failures comes from legacy short 8.3 form path components. These paths are generally undesirable and tend to defeat existing sandboxing and path-virtualization mechanisms. Given that, normalizing away 8.3 paths on Windows seems like a pragmatic, targeted improvement, even if path normalization is not something we would normally expect a toolchain to do in the general case. |
|
This PR hasn't gathered any support. Therefore, I'm going to rework this so that only DTLTO code is affected. Thanks for the input here. |
On Windows, the system temporary directory is commonly derived from the
TMPenvironment variable. For historical compatibility reasons, this variable is often set to a short 8.3 form path. This is especially common on systems where user names exceed eight characters; for example, a user name ofdunbobbinmay result inC:\Users\DUNBOB~1\AppData\Local\Temp.Short 8.3 form 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:
results in short 8.3 form paths being passed to LLD (output paraphrased):
For DTLTO, distribution-specific logic is kept out of LLVM where possible, but path normalization is required for ThinLTO ModuleIDs. The
TMPenvironment variable is the main source of short 8.3 form paths, and normalizing here avoids intrusive changes elsewhere.In addition to distribution, short 8.3 form paths are also confusing and inconvenient to work with; for example, tab completion in the Windows Command Prompt does not work reliably with short 8.3 form 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 path to its long form therefore improves usability and robustness.
SIE internal tracker: TOOLCHAIN-19185