1 //===- llvm/unittest/Support/Path.cpp - Path tests ------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Support/Path.h"
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/ScopeExit.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/BinaryFormat/Magic.h"
14 #include "llvm/Config/llvm-config.h"
15 #include "llvm/Support/Compiler.h"
16 #include "llvm/Support/ConvertUTF.h"
17 #include "llvm/Support/Duration.h"
18 #include "llvm/Support/Errc.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/FileUtilities.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/TargetParser/Host.h"
25 #include "llvm/TargetParser/Triple.h"
26 #include "llvm/Testing/Support/Error.h"
27 #include "llvm/Testing/Support/SupportHelpers.h"
28 #include "gmock/gmock.h"
29 #include "gtest/gtest.h"
32 #include "llvm/ADT/ArrayRef.h"
33 #include "llvm/Support/Chrono.h"
34 #include "llvm/Support/Windows/WindowsSupport.h"
45 using namespace llvm::sys
;
47 #define ASSERT_NO_ERROR(x) \
48 if (std::error_code ASSERT_NO_ERROR_ec = x) { \
49 SmallString<128> MessageStorage; \
50 raw_svector_ostream Message(MessageStorage); \
51 Message << #x ": did not return errc::success.\n" \
52 << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \
53 << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \
54 GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \
58 #define ASSERT_ERROR(x) \
60 SmallString<128> MessageStorage; \
61 raw_svector_ostream Message(MessageStorage); \
62 Message << #x ": did not return a failure error code.\n"; \
63 GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \
68 void checkSeparators(StringRef Path
) {
70 char UndesiredSeparator
= sys::path::get_separator()[0] == '/' ? '\\' : '/';
71 ASSERT_EQ(Path
.find(UndesiredSeparator
), StringRef::npos
);
75 struct FileDescriptorCloser
{
76 explicit FileDescriptorCloser(int FD
) : FD(FD
) {}
77 ~FileDescriptorCloser() { ::close(FD
); }
81 TEST(is_style_Style
, Works
) {
82 using namespace llvm::sys::path
;
83 // Check platform-independent results.
84 EXPECT_TRUE(is_style_posix(Style::posix
));
85 EXPECT_TRUE(is_style_windows(Style::windows
));
86 EXPECT_TRUE(is_style_windows(Style::windows_slash
));
87 EXPECT_FALSE(is_style_posix(Style::windows
));
88 EXPECT_FALSE(is_style_posix(Style::windows_slash
));
89 EXPECT_FALSE(is_style_windows(Style::posix
));
91 // Check platform-dependent results.
93 EXPECT_FALSE(is_style_posix(Style::native
));
94 EXPECT_TRUE(is_style_windows(Style::native
));
96 EXPECT_TRUE(is_style_posix(Style::native
));
97 EXPECT_FALSE(is_style_windows(Style::native
));
101 TEST(is_separator
, Works
) {
102 EXPECT_TRUE(path::is_separator('/'));
103 EXPECT_FALSE(path::is_separator('\0'));
104 EXPECT_FALSE(path::is_separator('-'));
105 EXPECT_FALSE(path::is_separator(' '));
107 EXPECT_TRUE(path::is_separator('\\', path::Style::windows
));
108 EXPECT_TRUE(path::is_separator('\\', path::Style::windows_slash
));
109 EXPECT_FALSE(path::is_separator('\\', path::Style::posix
));
111 EXPECT_EQ(path::is_style_windows(path::Style::native
),
112 path::is_separator('\\'));
115 TEST(get_separator
, Works
) {
116 EXPECT_EQ(path::get_separator(path::Style::posix
), "/");
117 EXPECT_EQ(path::get_separator(path::Style::windows_backslash
), "\\");
118 EXPECT_EQ(path::get_separator(path::Style::windows_slash
), "/");
121 TEST(is_absolute_gnu
, Works
) {
122 // Test tuple <Path, ExpectedPosixValue, ExpectedWindowsValue>.
123 const std::tuple
<StringRef
, bool, bool> Paths
[] = {
124 std::make_tuple("", false, false),
125 std::make_tuple("/", true, true),
126 std::make_tuple("/foo", true, true),
127 std::make_tuple("\\", false, true),
128 std::make_tuple("\\foo", false, true),
129 std::make_tuple("foo", false, false),
130 std::make_tuple("c", false, false),
131 std::make_tuple("c:", false, true),
132 std::make_tuple("c:\\", false, true),
133 std::make_tuple("!:", false, true),
134 std::make_tuple("xx:", false, false),
135 std::make_tuple("c:abc\\", false, true),
136 std::make_tuple(":", false, false)};
138 for (const auto &Path
: Paths
) {
139 EXPECT_EQ(path::is_absolute_gnu(std::get
<0>(Path
), path::Style::posix
),
141 EXPECT_EQ(path::is_absolute_gnu(std::get
<0>(Path
), path::Style::windows
),
144 constexpr int Native
= is_style_posix(path::Style::native
) ? 1 : 2;
145 EXPECT_EQ(path::is_absolute_gnu(std::get
<0>(Path
), path::Style::native
),
146 std::get
<Native
>(Path
));
150 TEST(Support
, Path
) {
151 SmallVector
<StringRef
, 40> paths
;
153 paths
.push_back(".");
154 paths
.push_back("..");
155 paths
.push_back("foo");
156 paths
.push_back("/");
157 paths
.push_back("/foo");
158 paths
.push_back("foo/");
159 paths
.push_back("/foo/");
160 paths
.push_back("foo/bar");
161 paths
.push_back("/foo/bar");
162 paths
.push_back("//net");
163 paths
.push_back("//net/");
164 paths
.push_back("//net/foo");
165 paths
.push_back("///foo///");
166 paths
.push_back("///foo///bar");
167 paths
.push_back("/.");
168 paths
.push_back("./");
169 paths
.push_back("/..");
170 paths
.push_back("../");
171 paths
.push_back("foo/.");
172 paths
.push_back("foo/..");
173 paths
.push_back("foo/./");
174 paths
.push_back("foo/./bar");
175 paths
.push_back("foo/..");
176 paths
.push_back("foo/../");
177 paths
.push_back("foo/../bar");
178 paths
.push_back("c:");
179 paths
.push_back("c:/");
180 paths
.push_back("c:foo");
181 paths
.push_back("c:/foo");
182 paths
.push_back("c:foo/");
183 paths
.push_back("c:/foo/");
184 paths
.push_back("c:/foo/bar");
185 paths
.push_back("prn:");
186 paths
.push_back("c:\\");
187 paths
.push_back("c:foo");
188 paths
.push_back("c:\\foo");
189 paths
.push_back("c:foo\\");
190 paths
.push_back("c:\\foo\\");
191 paths
.push_back("c:\\foo/");
192 paths
.push_back("c:/foo\\bar");
193 paths
.push_back(":");
195 for (SmallVector
<StringRef
, 40>::const_iterator i
= paths
.begin(),
200 SmallVector
<StringRef
, 5> ComponentStack
;
201 for (sys::path::const_iterator ci
= sys::path::begin(*i
),
202 ce
= sys::path::end(*i
);
205 EXPECT_FALSE(ci
->empty());
206 ComponentStack
.push_back(*ci
);
209 SmallVector
<StringRef
, 5> ReverseComponentStack
;
210 for (sys::path::reverse_iterator ci
= sys::path::rbegin(*i
),
211 ce
= sys::path::rend(*i
);
214 EXPECT_FALSE(ci
->empty());
215 ReverseComponentStack
.push_back(*ci
);
217 std::reverse(ReverseComponentStack
.begin(), ReverseComponentStack
.end());
218 EXPECT_THAT(ComponentStack
, testing::ContainerEq(ReverseComponentStack
));
220 // Crash test most of the API - since we're iterating over all of our paths
221 // here there isn't really anything reasonable to assert on in the results.
222 (void)path::has_root_path(*i
);
223 (void)path::root_path(*i
);
224 (void)path::has_root_name(*i
);
225 (void)path::root_name(*i
);
226 (void)path::has_root_directory(*i
);
227 (void)path::root_directory(*i
);
228 (void)path::has_parent_path(*i
);
229 (void)path::parent_path(*i
);
230 (void)path::has_filename(*i
);
231 (void)path::filename(*i
);
232 (void)path::has_stem(*i
);
233 (void)path::stem(*i
);
234 (void)path::has_extension(*i
);
235 (void)path::extension(*i
);
236 (void)path::is_absolute(*i
);
237 (void)path::is_absolute_gnu(*i
);
238 (void)path::is_relative(*i
);
240 SmallString
<128> temp_store
;
242 ASSERT_NO_ERROR(fs::make_absolute(temp_store
));
244 path::remove_filename(temp_store
);
247 path::replace_extension(temp_store
, "ext");
248 StringRef
filename(temp_store
.begin(), temp_store
.size()), stem
, ext
;
249 stem
= path::stem(filename
);
250 ext
= path::extension(filename
);
251 EXPECT_EQ(*sys::path::rbegin(filename
), (stem
+ ext
).str());
253 path::native(*i
, temp_store
);
257 SmallString
<32> Relative("foo.cpp");
258 sys::fs::make_absolute("/root", Relative
);
259 Relative
[5] = '/'; // Fix up windows paths.
260 ASSERT_EQ("/root/foo.cpp", Relative
);
264 SmallString
<32> Relative("foo.cpp");
265 sys::fs::make_absolute("//root", Relative
);
266 Relative
[6] = '/'; // Fix up windows paths.
267 ASSERT_EQ("//root/foo.cpp", Relative
);
271 TEST(Support
, PathRoot
) {
272 ASSERT_EQ(path::root_name("//net/hello", path::Style::posix
).str(), "//net");
273 ASSERT_EQ(path::root_name("c:/hello", path::Style::posix
).str(), "");
274 ASSERT_EQ(path::root_name("c:/hello", path::Style::windows
).str(), "c:");
275 ASSERT_EQ(path::root_name("/hello", path::Style::posix
).str(), "");
277 ASSERT_EQ(path::root_directory("/goo/hello", path::Style::posix
).str(), "/");
278 ASSERT_EQ(path::root_directory("c:/hello", path::Style::windows
).str(), "/");
279 ASSERT_EQ(path::root_directory("d/file.txt", path::Style::posix
).str(), "");
280 ASSERT_EQ(path::root_directory("d/file.txt", path::Style::windows
).str(), "");
282 SmallVector
<StringRef
, 40> paths
;
284 paths
.push_back(".");
285 paths
.push_back("..");
286 paths
.push_back("foo");
287 paths
.push_back("/");
288 paths
.push_back("/foo");
289 paths
.push_back("foo/");
290 paths
.push_back("/foo/");
291 paths
.push_back("foo/bar");
292 paths
.push_back("/foo/bar");
293 paths
.push_back("//net");
294 paths
.push_back("//net/");
295 paths
.push_back("//net/foo");
296 paths
.push_back("///foo///");
297 paths
.push_back("///foo///bar");
298 paths
.push_back("/.");
299 paths
.push_back("./");
300 paths
.push_back("/..");
301 paths
.push_back("../");
302 paths
.push_back("foo/.");
303 paths
.push_back("foo/..");
304 paths
.push_back("foo/./");
305 paths
.push_back("foo/./bar");
306 paths
.push_back("foo/..");
307 paths
.push_back("foo/../");
308 paths
.push_back("foo/../bar");
309 paths
.push_back("c:");
310 paths
.push_back("c:/");
311 paths
.push_back("c:foo");
312 paths
.push_back("c:/foo");
313 paths
.push_back("c:foo/");
314 paths
.push_back("c:/foo/");
315 paths
.push_back("c:/foo/bar");
316 paths
.push_back("prn:");
317 paths
.push_back("c:\\");
318 paths
.push_back("c:foo");
319 paths
.push_back("c:\\foo");
320 paths
.push_back("c:foo\\");
321 paths
.push_back("c:\\foo\\");
322 paths
.push_back("c:\\foo/");
323 paths
.push_back("c:/foo\\bar");
325 for (StringRef p
: paths
) {
327 path::root_name(p
, path::Style::posix
).str() + path::root_directory(p
, path::Style::posix
).str(),
328 path::root_path(p
, path::Style::posix
).str());
331 path::root_name(p
, path::Style::windows
).str() + path::root_directory(p
, path::Style::windows
).str(),
332 path::root_path(p
, path::Style::windows
).str());
336 TEST(Support
, FilenameParent
) {
337 EXPECT_EQ("/", path::filename("/"));
338 EXPECT_EQ("", path::parent_path("/"));
340 EXPECT_EQ("\\", path::filename("c:\\", path::Style::windows
));
341 EXPECT_EQ("c:", path::parent_path("c:\\", path::Style::windows
));
343 EXPECT_EQ("/", path::filename("///"));
344 EXPECT_EQ("", path::parent_path("///"));
346 EXPECT_EQ("\\", path::filename("c:\\\\", path::Style::windows
));
347 EXPECT_EQ("c:", path::parent_path("c:\\\\", path::Style::windows
));
349 EXPECT_EQ("bar", path::filename("/foo/bar"));
350 EXPECT_EQ("/foo", path::parent_path("/foo/bar"));
352 EXPECT_EQ("foo", path::filename("/foo"));
353 EXPECT_EQ("/", path::parent_path("/foo"));
355 EXPECT_EQ("foo", path::filename("foo"));
356 EXPECT_EQ("", path::parent_path("foo"));
358 EXPECT_EQ(".", path::filename("foo/"));
359 EXPECT_EQ("foo", path::parent_path("foo/"));
361 EXPECT_EQ("//net", path::filename("//net"));
362 EXPECT_EQ("", path::parent_path("//net"));
364 EXPECT_EQ("/", path::filename("//net/"));
365 EXPECT_EQ("//net", path::parent_path("//net/"));
367 EXPECT_EQ("foo", path::filename("//net/foo"));
368 EXPECT_EQ("//net/", path::parent_path("//net/foo"));
370 // These checks are just to make sure we do something reasonable with the
371 // paths below. They are not meant to prescribe the one true interpretation of
372 // these paths. Other decompositions (e.g. "//" -> "" + "//") are also
374 EXPECT_EQ("/", path::filename("//"));
375 EXPECT_EQ("", path::parent_path("//"));
377 EXPECT_EQ("\\", path::filename("\\\\", path::Style::windows
));
378 EXPECT_EQ("", path::parent_path("\\\\", path::Style::windows
));
380 EXPECT_EQ("\\", path::filename("\\\\\\", path::Style::windows
));
381 EXPECT_EQ("", path::parent_path("\\\\\\", path::Style::windows
));
384 static std::vector
<StringRef
>
385 GetComponents(StringRef Path
, path::Style S
= path::Style::native
) {
386 return {path::begin(Path
, S
), path::end(Path
)};
389 TEST(Support
, PathIterator
) {
390 EXPECT_THAT(GetComponents("/foo"), testing::ElementsAre("/", "foo"));
391 EXPECT_THAT(GetComponents("/"), testing::ElementsAre("/"));
392 EXPECT_THAT(GetComponents("//"), testing::ElementsAre("/"));
393 EXPECT_THAT(GetComponents("///"), testing::ElementsAre("/"));
394 EXPECT_THAT(GetComponents("c/d/e/foo.txt"),
395 testing::ElementsAre("c", "d", "e", "foo.txt"));
396 EXPECT_THAT(GetComponents(".c/.d/../."),
397 testing::ElementsAre(".c", ".d", "..", "."));
398 EXPECT_THAT(GetComponents("/c/d/e/foo.txt"),
399 testing::ElementsAre("/", "c", "d", "e", "foo.txt"));
400 EXPECT_THAT(GetComponents("/.c/.d/../."),
401 testing::ElementsAre("/", ".c", ".d", "..", "."));
402 EXPECT_THAT(GetComponents("c:\\c\\e\\foo.txt", path::Style::windows
),
403 testing::ElementsAre("c:", "\\", "c", "e", "foo.txt"));
404 EXPECT_THAT(GetComponents("c:\\c\\e\\foo.txt", path::Style::windows_slash
),
405 testing::ElementsAre("c:", "\\", "c", "e", "foo.txt"));
406 EXPECT_THAT(GetComponents("//net/"), testing::ElementsAre("//net", "/"));
407 EXPECT_THAT(GetComponents("//net/c/foo.txt"),
408 testing::ElementsAre("//net", "/", "c", "foo.txt"));
411 TEST(Support
, AbsolutePathIteratorEnd
) {
412 // Trailing slashes are converted to '.' unless they are part of the root path.
413 SmallVector
<std::pair
<StringRef
, path::Style
>, 4> Paths
;
414 Paths
.emplace_back("/foo/", path::Style::native
);
415 Paths
.emplace_back("/foo//", path::Style::native
);
416 Paths
.emplace_back("//net/foo/", path::Style::native
);
417 Paths
.emplace_back("c:\\foo\\", path::Style::windows
);
419 for (auto &Path
: Paths
) {
420 SCOPED_TRACE(Path
.first
);
421 StringRef LastComponent
= *path::rbegin(Path
.first
, Path
.second
);
422 EXPECT_EQ(".", LastComponent
);
425 SmallVector
<std::pair
<StringRef
, path::Style
>, 3> RootPaths
;
426 RootPaths
.emplace_back("/", path::Style::native
);
427 RootPaths
.emplace_back("//net/", path::Style::native
);
428 RootPaths
.emplace_back("c:\\", path::Style::windows
);
429 RootPaths
.emplace_back("//net//", path::Style::native
);
430 RootPaths
.emplace_back("c:\\\\", path::Style::windows
);
432 for (auto &Path
: RootPaths
) {
433 SCOPED_TRACE(Path
.first
);
434 StringRef LastComponent
= *path::rbegin(Path
.first
, Path
.second
);
435 EXPECT_EQ(1u, LastComponent
.size());
436 EXPECT_TRUE(path::is_separator(LastComponent
[0], Path
.second
));
441 std::string
getEnvWin(const wchar_t *Var
) {
442 std::string expected
;
443 if (wchar_t const *path
= ::_wgetenv(Var
)) {
444 auto pathLen
= ::wcslen(path
);
445 ArrayRef
<char> ref
{reinterpret_cast<char const *>(path
),
446 pathLen
* sizeof(wchar_t)};
447 convertUTF16ToUTF8String(ref
, expected
);
448 SmallString
<32> Buf(expected
);
449 path::make_preferred(Buf
);
450 expected
.assign(Buf
.begin(), Buf
.end());
455 // RAII helper to set and restore an environment variable.
458 std::optional
<std::string
> OriginalValue
;
461 WithEnv(const char *Var
, const char *Value
) : Var(Var
) {
462 if (const char *V
= ::getenv(Var
))
463 OriginalValue
.emplace(V
);
465 ::setenv(Var
, Value
, 1);
471 ::setenv(Var
, OriginalValue
->c_str(), 1);
478 TEST(Support
, HomeDirectory
) {
479 std::string expected
;
481 expected
= getEnvWin(L
"USERPROFILE");
483 if (char const *path
= ::getenv("HOME"))
486 // Do not try to test it if we don't know what to expect.
487 // On Windows we use something better than env vars.
488 if (expected
.empty())
490 SmallString
<128> HomeDir
;
491 auto status
= path::home_directory(HomeDir
);
493 EXPECT_EQ(expected
, HomeDir
);
496 // Apple has their own solution for this.
497 #if defined(LLVM_ON_UNIX) && !defined(__APPLE__)
498 TEST(Support
, HomeDirectoryWithNoEnv
) {
499 WithEnv
Env("HOME", nullptr);
501 // Don't run the test if we have nothing to compare against.
502 struct passwd
*pw
= getpwuid(getuid());
503 if (!pw
|| !pw
->pw_dir
)
505 std::string PwDir
= pw
->pw_dir
;
507 SmallString
<128> HomeDir
;
508 EXPECT_TRUE(path::home_directory(HomeDir
));
509 EXPECT_EQ(PwDir
, HomeDir
);
512 TEST(Support
, ConfigDirectoryWithEnv
) {
513 WithEnv
Env("XDG_CONFIG_HOME", "/xdg/config");
515 SmallString
<128> ConfigDir
;
516 EXPECT_TRUE(path::user_config_directory(ConfigDir
));
517 EXPECT_EQ("/xdg/config", ConfigDir
);
520 TEST(Support
, ConfigDirectoryNoEnv
) {
521 WithEnv
Env("XDG_CONFIG_HOME", nullptr);
523 SmallString
<128> Fallback
;
524 ASSERT_TRUE(path::home_directory(Fallback
));
525 path::append(Fallback
, ".config");
527 SmallString
<128> CacheDir
;
528 EXPECT_TRUE(path::user_config_directory(CacheDir
));
529 EXPECT_EQ(Fallback
, CacheDir
);
532 TEST(Support
, CacheDirectoryWithEnv
) {
533 WithEnv
Env("XDG_CACHE_HOME", "/xdg/cache");
535 SmallString
<128> CacheDir
;
536 EXPECT_TRUE(path::cache_directory(CacheDir
));
537 EXPECT_EQ("/xdg/cache", CacheDir
);
540 TEST(Support
, CacheDirectoryNoEnv
) {
541 WithEnv
Env("XDG_CACHE_HOME", nullptr);
543 SmallString
<128> Fallback
;
544 ASSERT_TRUE(path::home_directory(Fallback
));
545 path::append(Fallback
, ".cache");
547 SmallString
<128> CacheDir
;
548 EXPECT_TRUE(path::cache_directory(CacheDir
));
549 EXPECT_EQ(Fallback
, CacheDir
);
554 TEST(Support
, ConfigDirectory
) {
555 SmallString
<128> Fallback
;
556 ASSERT_TRUE(path::home_directory(Fallback
));
557 path::append(Fallback
, "Library/Preferences");
559 SmallString
<128> ConfigDir
;
560 EXPECT_TRUE(path::user_config_directory(ConfigDir
));
561 EXPECT_EQ(Fallback
, ConfigDir
);
566 TEST(Support
, ConfigDirectory
) {
567 std::string Expected
= getEnvWin(L
"LOCALAPPDATA");
568 // Do not try to test it if we don't know what to expect.
569 if (Expected
.empty())
571 SmallString
<128> CacheDir
;
572 EXPECT_TRUE(path::user_config_directory(CacheDir
));
573 EXPECT_EQ(Expected
, CacheDir
);
576 TEST(Support
, CacheDirectory
) {
577 std::string Expected
= getEnvWin(L
"LOCALAPPDATA");
578 // Do not try to test it if we don't know what to expect.
579 if (Expected
.empty())
581 SmallString
<128> CacheDir
;
582 EXPECT_TRUE(path::cache_directory(CacheDir
));
583 EXPECT_EQ(Expected
, CacheDir
);
587 TEST(Support
, TempDirectory
) {
588 SmallString
<32> TempDir
;
589 path::system_temp_directory(false, TempDir
);
590 EXPECT_TRUE(!TempDir
.empty());
592 path::system_temp_directory(true, TempDir
);
593 EXPECT_TRUE(!TempDir
.empty());
597 static std::string
path2regex(std::string Path
) {
599 bool Forward
= path::get_separator()[0] == '/';
600 while ((Pos
= Path
.find('\\', Pos
)) != std::string::npos
) {
602 Path
.replace(Pos
, 1, "/");
605 Path
.replace(Pos
, 1, "\\\\");
612 /// Helper for running temp dir test in separated process. See below.
613 #define EXPECT_TEMP_DIR(prepare, expected) \
617 SmallString<300> TempDir; \
618 path::system_temp_directory(true, TempDir); \
619 raw_os_ostream(std::cerr) << TempDir; \
622 ::testing::ExitedWithCode(0), path2regex(expected))
624 TEST(SupportDeathTest
, TempDirectoryOnWindows
) {
625 // In this test we want to check how system_temp_directory responds to
626 // different values of specific env vars. To prevent corrupting env vars of
627 // the current process all checks are done in separated processes.
628 EXPECT_TEMP_DIR(_wputenv_s(L
"TMP", L
"C:\\OtherFolder"), "C:\\OtherFolder");
629 EXPECT_TEMP_DIR(_wputenv_s(L
"TMP", L
"C:/Unix/Path/Separators"),
630 "C:\\Unix\\Path\\Separators");
631 EXPECT_TEMP_DIR(_wputenv_s(L
"TMP", L
"Local Path"), ".+\\Local Path$");
632 EXPECT_TEMP_DIR(_wputenv_s(L
"TMP", L
"F:\\TrailingSep\\"), "F:\\TrailingSep");
634 _wputenv_s(L
"TMP", L
"C:\\2\x03C0r-\x00B5\x00B3\\\x2135\x2080"),
635 "C:\\2\xCF\x80r-\xC2\xB5\xC2\xB3\\\xE2\x84\xB5\xE2\x82\x80");
637 // Test $TMP empty, $TEMP set.
640 _wputenv_s(L
"TMP", L
"");
641 _wputenv_s(L
"TEMP", L
"C:\\Valid\\Path");
645 // All related env vars empty
648 _wputenv_s(L
"TMP", L
"");
649 _wputenv_s(L
"TEMP", L
"");
650 _wputenv_s(L
"USERPROFILE", L
"");
654 // Test evn var / path with 260 chars.
655 SmallString
<270> Expected
{"C:\\Temp\\AB\\123456789"};
656 while (Expected
.size() < 260)
657 Expected
.append("\\DirNameWith19Charss");
658 ASSERT_EQ(260U, Expected
.size());
659 EXPECT_TEMP_DIR(_putenv_s("TMP", Expected
.c_str()), Expected
.c_str());
663 class FileSystemTest
: public testing::Test
{
665 /// Unique temporary directory in which all created filesystem entities must
666 /// be placed. It is removed at the end of each test (must be empty).
667 SmallString
<128> TestDirectory
;
668 SmallString
<128> NonExistantFile
;
670 void SetUp() override
{
672 fs::createUniqueDirectory("file-system-test", TestDirectory
));
673 // We don't care about this specific file.
674 errs() << "Test Directory: " << TestDirectory
<< '\n';
676 NonExistantFile
= TestDirectory
;
678 // Even though this value is hardcoded, is a 128-bit GUID, so we should be
679 // guaranteed that this file will never exist.
680 sys::path::append(NonExistantFile
, "1B28B495C16344CB9822E588CD4C3EF0");
683 void TearDown() override
{ ASSERT_NO_ERROR(fs::remove(TestDirectory
.str())); }
686 TEST_F(FileSystemTest
, Unique
) {
687 // Create a temp file.
689 SmallString
<64> TempPath
;
691 fs::createTemporaryFile("prefix", "temp", FileDescriptor
, TempPath
));
693 // The same file should return an identical unique id.
695 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath
), F1
));
696 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath
), F2
));
699 // Different files should return different unique ids.
701 SmallString
<64> TempPath2
;
703 fs::createTemporaryFile("prefix", "temp", FileDescriptor2
, TempPath2
));
706 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2
), D
));
708 ::close(FileDescriptor2
);
710 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2
)));
713 // Two paths representing the same file on disk should still provide the
714 // same unique id. We can test this by making a hard link.
715 // FIXME: Our implementation of getUniqueID on Windows doesn't consider hard
716 // links to be the same file.
717 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath
), Twine(TempPath2
)));
719 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2
), D2
));
723 ::close(FileDescriptor
);
725 SmallString
<128> Dir1
;
727 fs::createUniqueDirectory("dir1", Dir1
));
728 ASSERT_NO_ERROR(fs::getUniqueID(Dir1
.c_str(), F1
));
729 ASSERT_NO_ERROR(fs::getUniqueID(Dir1
.c_str(), F2
));
732 SmallString
<128> Dir2
;
734 fs::createUniqueDirectory("dir2", Dir2
));
735 ASSERT_NO_ERROR(fs::getUniqueID(Dir2
.c_str(), F2
));
737 ASSERT_NO_ERROR(fs::remove(Dir1
));
738 ASSERT_NO_ERROR(fs::remove(Dir2
));
739 ASSERT_NO_ERROR(fs::remove(TempPath2
));
740 ASSERT_NO_ERROR(fs::remove(TempPath
));
743 TEST_F(FileSystemTest
, RealPath
) {
745 fs::create_directories(Twine(TestDirectory
) + "/test1/test2/test3"));
746 ASSERT_TRUE(fs::exists(Twine(TestDirectory
) + "/test1/test2/test3"));
748 SmallString
<64> RealBase
;
749 SmallString
<64> Expected
;
750 SmallString
<64> Actual
;
752 // TestDirectory itself might be under a symlink or have been specified with
753 // a different case than the existing temp directory. In such cases real_path
754 // on the concatenated path will differ in the TestDirectory portion from
755 // how we specified it. Make sure to compare against the real_path of the
756 // TestDirectory, and not just the value of TestDirectory.
757 ASSERT_NO_ERROR(fs::real_path(TestDirectory
, RealBase
));
758 checkSeparators(RealBase
);
759 path::native(Twine(RealBase
) + "/test1/test2", Expected
);
761 ASSERT_NO_ERROR(fs::real_path(
762 Twine(TestDirectory
) + "/././test1/../test1/test2/./test3/..", Actual
));
763 checkSeparators(Actual
);
765 EXPECT_EQ(Expected
, Actual
);
767 SmallString
<64> HomeDir
;
769 // This can fail if $HOME is not set and getpwuid fails.
770 bool Result
= llvm::sys::path::home_directory(HomeDir
);
772 checkSeparators(HomeDir
);
773 ASSERT_NO_ERROR(fs::real_path(HomeDir
, Expected
));
774 checkSeparators(Expected
);
775 ASSERT_NO_ERROR(fs::real_path("~", Actual
, true));
776 EXPECT_EQ(Expected
, Actual
);
777 ASSERT_NO_ERROR(fs::real_path("~/", Actual
, true));
778 EXPECT_EQ(Expected
, Actual
);
781 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory
) + "/test1"));
784 TEST_F(FileSystemTest
, ExpandTilde
) {
785 SmallString
<64> Expected
;
786 SmallString
<64> Actual
;
787 SmallString
<64> HomeDir
;
789 // This can fail if $HOME is not set and getpwuid fails.
790 bool Result
= llvm::sys::path::home_directory(HomeDir
);
792 fs::expand_tilde(HomeDir
, Expected
);
794 fs::expand_tilde("~", Actual
);
795 EXPECT_EQ(Expected
, Actual
);
799 fs::expand_tilde("~\\foo", Actual
);
802 fs::expand_tilde("~/foo", Actual
);
805 EXPECT_EQ(Expected
, Actual
);
810 TEST_F(FileSystemTest
, RealPathNoReadPerm
) {
811 SmallString
<64> Expanded
;
814 fs::create_directories(Twine(TestDirectory
) + "/noreadperm"));
815 ASSERT_TRUE(fs::exists(Twine(TestDirectory
) + "/noreadperm"));
817 fs::setPermissions(Twine(TestDirectory
) + "/noreadperm", fs::no_perms
);
818 fs::setPermissions(Twine(TestDirectory
) + "/noreadperm", fs::all_exe
);
820 ASSERT_NO_ERROR(fs::real_path(Twine(TestDirectory
) + "/noreadperm", Expanded
,
823 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory
) + "/noreadperm"));
825 TEST_F(FileSystemTest
, RemoveDirectoriesNoExePerm
) {
826 SmallString
<64> Expanded
;
829 fs::create_directories(Twine(TestDirectory
) + "/noexeperm/foo"));
830 ASSERT_TRUE(fs::exists(Twine(TestDirectory
) + "/noexeperm/foo"));
832 fs::setPermissions(Twine(TestDirectory
) + "/noexeperm",
833 fs::all_read
| fs::all_write
);
835 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory
) + "/noexeperm",
836 /*IgnoreErrors=*/true));
838 // It's expected that the directory exists, but some environments appear to
839 // allow the removal despite missing the 'x' permission, so be flexible.
840 if (fs::exists(Twine(TestDirectory
) + "/noexeperm")) {
841 fs::setPermissions(Twine(TestDirectory
) + "/noexeperm", fs::all_perms
);
842 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory
) + "/noexeperm",
843 /*IgnoreErrors=*/false));
849 TEST_F(FileSystemTest
, TempFileKeepDiscard
) {
850 // We can keep then discard.
851 auto TempFileOrError
= fs::TempFile::create(TestDirectory
+ "/test-%%%%");
852 ASSERT_TRUE((bool)TempFileOrError
);
853 fs::TempFile File
= std::move(*TempFileOrError
);
854 ASSERT_EQ(-1, TempFileOrError
->FD
);
855 ASSERT_FALSE((bool)File
.keep(TestDirectory
+ "/keep"));
856 ASSERT_FALSE((bool)File
.discard());
857 ASSERT_TRUE(fs::exists(TestDirectory
+ "/keep"));
858 ASSERT_NO_ERROR(fs::remove(TestDirectory
+ "/keep"));
861 TEST_F(FileSystemTest
, TempFileDiscardDiscard
) {
862 // We can discard twice.
863 auto TempFileOrError
= fs::TempFile::create(TestDirectory
+ "/test-%%%%");
864 ASSERT_TRUE((bool)TempFileOrError
);
865 fs::TempFile File
= std::move(*TempFileOrError
);
866 ASSERT_EQ(-1, TempFileOrError
->FD
);
867 ASSERT_FALSE((bool)File
.discard());
868 ASSERT_FALSE((bool)File
.discard());
869 ASSERT_FALSE(fs::exists(TestDirectory
+ "/keep"));
872 TEST_F(FileSystemTest
, TempFiles
) {
873 // Create a temp file.
875 SmallString
<64> TempPath
;
877 fs::createTemporaryFile("prefix", "temp", FileDescriptor
, TempPath
));
879 // Make sure it exists.
880 ASSERT_TRUE(sys::fs::exists(Twine(TempPath
)));
882 // Create another temp tile.
884 SmallString
<64> TempPath2
;
885 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD2
, TempPath2
));
886 ASSERT_TRUE(TempPath2
.ends_with(".temp"));
887 ASSERT_NE(TempPath
.str(), TempPath2
.str());
889 fs::file_status A
, B
;
890 ASSERT_NO_ERROR(fs::status(Twine(TempPath
), A
));
891 ASSERT_NO_ERROR(fs::status(Twine(TempPath2
), B
));
892 EXPECT_FALSE(fs::equivalent(A
, B
));
897 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2
)));
898 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2
)));
899 ASSERT_EQ(fs::remove(Twine(TempPath2
), false),
900 errc::no_such_file_or_directory
);
902 std::error_code EC
= fs::status(TempPath2
.c_str(), B
);
903 EXPECT_EQ(EC
, errc::no_such_file_or_directory
);
904 EXPECT_EQ(B
.type(), fs::file_type::file_not_found
);
906 // Make sure Temp2 doesn't exist.
907 ASSERT_EQ(fs::access(Twine(TempPath2
), sys::fs::AccessMode::Exist
),
908 errc::no_such_file_or_directory
);
910 SmallString
<64> TempPath3
;
911 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "", TempPath3
));
912 ASSERT_FALSE(TempPath3
.ends_with("."));
913 FileRemover
Cleanup3(TempPath3
);
915 // Create a hard link to Temp1.
916 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath
), Twine(TempPath2
)));
918 // FIXME: Our implementation of equivalent() on Windows doesn't consider hard
919 // links to be the same file.
921 ASSERT_NO_ERROR(fs::equivalent(Twine(TempPath
), Twine(TempPath2
), equal
));
923 ASSERT_NO_ERROR(fs::status(Twine(TempPath
), A
));
924 ASSERT_NO_ERROR(fs::status(Twine(TempPath2
), B
));
925 EXPECT_TRUE(fs::equivalent(A
, B
));
929 ::close(FileDescriptor
);
930 ASSERT_NO_ERROR(fs::remove(Twine(TempPath
)));
932 // Remove the hard link.
933 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2
)));
935 // Make sure Temp1 doesn't exist.
936 ASSERT_EQ(fs::access(Twine(TempPath
), sys::fs::AccessMode::Exist
),
937 errc::no_such_file_or_directory
);
940 // Path name > 260 chars should get an error.
941 const char *Path270
=
942 "abcdefghijklmnopqrstuvwxyz9abcdefghijklmnopqrstuvwxyz8"
943 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
944 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
945 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
946 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
947 EXPECT_EQ(fs::createUniqueFile(Path270
, FileDescriptor
, TempPath
),
948 errc::invalid_argument
);
949 // Relative path < 247 chars, no problem.
950 const char *Path216
=
951 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
952 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
953 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
954 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
955 ASSERT_NO_ERROR(fs::createTemporaryFile(Path216
, "", TempPath
));
956 ASSERT_NO_ERROR(fs::remove(Twine(TempPath
)));
960 TEST_F(FileSystemTest
, TempFileCollisions
) {
961 SmallString
<128> TestDirectory
;
963 fs::createUniqueDirectory("CreateUniqueFileTest", TestDirectory
));
964 FileRemover
Cleanup(TestDirectory
);
965 SmallString
<128> Model
= TestDirectory
;
966 path::append(Model
, "%.tmp");
967 SmallString
<128> Path
;
968 std::vector
<fs::TempFile
> TempFiles
;
970 auto TryCreateTempFile
= [&]() {
971 Expected
<fs::TempFile
> T
= fs::TempFile::create(Model
);
973 TempFiles
.push_back(std::move(*T
));
976 logAllUnhandledErrors(T
.takeError(), errs(),
977 "Failed to create temporary file: ");
982 // Our single-character template allows for 16 unique names. Check that
983 // calling TryCreateTempFile repeatedly results in 16 successes.
984 // Because the test depends on random numbers, it could theoretically fail.
985 // However, the probability of this happening is tiny: with 32 calls, each
986 // of which will retry up to 128 times, to not get a given digit we would
987 // have to fail at least 15 + 17 * 128 = 2191 attempts. The probability of
988 // 2191 attempts not producing a given hexadecimal digit is
989 // (1 - 1/16) ** 2191 or 3.88e-62.
991 for (int i
= 0; i
< 32; ++i
)
992 if (TryCreateTempFile()) ++Successes
;
993 EXPECT_EQ(Successes
, 16);
995 for (fs::TempFile
&T
: TempFiles
)
996 cantFail(T
.discard());
999 TEST_F(FileSystemTest
, CreateDir
) {
1000 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory
) + "foo"));
1001 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory
) + "foo"));
1002 ASSERT_EQ(fs::create_directory(Twine(TestDirectory
) + "foo", false),
1004 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "foo"));
1007 // Set a 0000 umask so that we can test our directory permissions.
1008 mode_t OldUmask
= ::umask(0000);
1010 fs::file_status Status
;
1012 fs::create_directory(Twine(TestDirectory
) + "baz500", false,
1013 fs::perms::owner_read
| fs::perms::owner_exe
));
1014 ASSERT_NO_ERROR(fs::status(Twine(TestDirectory
) + "baz500", Status
));
1015 ASSERT_EQ(Status
.permissions() & fs::perms::all_all
,
1016 fs::perms::owner_read
| fs::perms::owner_exe
);
1017 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory
) + "baz777", false,
1018 fs::perms::all_all
));
1019 ASSERT_NO_ERROR(fs::status(Twine(TestDirectory
) + "baz777", Status
));
1020 ASSERT_EQ(Status
.permissions() & fs::perms::all_all
, fs::perms::all_all
);
1022 // Restore umask to be safe.
1027 // Prove that create_directories() can handle a pathname > 248 characters,
1028 // which is the documented limit for CreateDirectory().
1029 // (248 is MAX_PATH subtracting room for an 8.3 filename.)
1030 // Generate a directory path guaranteed to fall into that range.
1031 size_t TmpLen
= TestDirectory
.size();
1032 const char *OneDir
= "\\123456789";
1033 size_t OneDirLen
= strlen(OneDir
);
1034 ASSERT_LT(OneDirLen
, 12U);
1035 size_t NLevels
= ((248 - TmpLen
) / OneDirLen
) + 1;
1036 SmallString
<260> LongDir(TestDirectory
);
1037 for (size_t I
= 0; I
< NLevels
; ++I
)
1038 LongDir
.append(OneDir
);
1039 ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir
)));
1040 ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir
)));
1041 ASSERT_EQ(fs::create_directories(Twine(LongDir
), false),
1043 // Tidy up, "recursively" removing the directories.
1044 StringRef
ThisDir(LongDir
);
1045 for (size_t J
= 0; J
< NLevels
; ++J
) {
1046 ASSERT_NO_ERROR(fs::remove(ThisDir
));
1047 ThisDir
= path::parent_path(ThisDir
);
1050 // Also verify that paths with Unix separators are handled correctly.
1051 std::string
LongPathWithUnixSeparators(TestDirectory
.str());
1052 // Add at least one subdirectory to TestDirectory, and replace slashes with
1055 LongPathWithUnixSeparators
.append("/DirNameWith19Charss");
1056 } while (LongPathWithUnixSeparators
.size() < 260);
1057 std::replace(LongPathWithUnixSeparators
.begin(),
1058 LongPathWithUnixSeparators
.end(),
1060 ASSERT_NO_ERROR(fs::create_directories(Twine(LongPathWithUnixSeparators
)));
1062 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory
) +
1063 "/DirNameWith19Charss"));
1065 // Similarly for a relative pathname. Need to set the current directory to
1066 // TestDirectory so that the one we create ends up in the right place.
1067 char PreviousDir
[260];
1068 size_t PreviousDirLen
= ::GetCurrentDirectoryA(260, PreviousDir
);
1069 ASSERT_GT(PreviousDirLen
, 0U);
1070 ASSERT_LT(PreviousDirLen
, 260U);
1071 ASSERT_NE(::SetCurrentDirectoryA(TestDirectory
.c_str()), 0);
1073 // Generate a relative directory name with absolute length > 248.
1074 size_t LongDirLen
= 249 - TestDirectory
.size();
1075 LongDir
.assign(LongDirLen
, 'a');
1076 ASSERT_NO_ERROR(fs::create_directory(Twine(LongDir
)));
1077 // While we're here, prove that .. and . handling works in these long paths.
1078 const char *DotDotDirs
= "\\..\\.\\b";
1079 LongDir
.append(DotDotDirs
);
1080 ASSERT_NO_ERROR(fs::create_directory("b"));
1081 ASSERT_EQ(fs::create_directory(Twine(LongDir
), false), errc::file_exists
);
1083 ASSERT_NO_ERROR(fs::remove("b"));
1084 ASSERT_NO_ERROR(fs::remove(
1085 Twine(LongDir
.substr(0, LongDir
.size() - strlen(DotDotDirs
)))));
1086 ASSERT_NE(::SetCurrentDirectoryA(PreviousDir
), 0);
1090 TEST_F(FileSystemTest
, DirectoryIteration
) {
1092 for (fs::directory_iterator
i(".", ec
), e
; i
!= e
; i
.increment(ec
))
1093 ASSERT_NO_ERROR(ec
);
1095 // Create a known hierarchy to recurse over.
1097 fs::create_directories(Twine(TestDirectory
) + "/recursive/a0/aa1"));
1099 fs::create_directories(Twine(TestDirectory
) + "/recursive/a0/ab1"));
1100 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory
) +
1101 "/recursive/dontlookhere/da1"));
1103 fs::create_directories(Twine(TestDirectory
) + "/recursive/z0/za1"));
1105 fs::create_directories(Twine(TestDirectory
) + "/recursive/pop/p1"));
1106 typedef std::vector
<std::string
> v_t
;
1108 for (fs::recursive_directory_iterator
i(Twine(TestDirectory
)
1109 + "/recursive", ec
), e
; i
!= e
; i
.increment(ec
)){
1110 ASSERT_NO_ERROR(ec
);
1111 if (path::filename(i
->path()) == "p1") {
1113 // FIXME: recursive_directory_iterator should be more robust.
1116 if (path::filename(i
->path()) == "dontlookhere")
1118 visited
.push_back(std::string(path::filename(i
->path())));
1120 v_t::const_iterator a0
= find(visited
, "a0");
1121 v_t::const_iterator aa1
= find(visited
, "aa1");
1122 v_t::const_iterator ab1
= find(visited
, "ab1");
1123 v_t::const_iterator dontlookhere
= find(visited
, "dontlookhere");
1124 v_t::const_iterator da1
= find(visited
, "da1");
1125 v_t::const_iterator z0
= find(visited
, "z0");
1126 v_t::const_iterator za1
= find(visited
, "za1");
1127 v_t::const_iterator pop
= find(visited
, "pop");
1128 v_t::const_iterator p1
= find(visited
, "p1");
1130 // Make sure that each path was visited correctly.
1131 ASSERT_NE(a0
, visited
.end());
1132 ASSERT_NE(aa1
, visited
.end());
1133 ASSERT_NE(ab1
, visited
.end());
1134 ASSERT_NE(dontlookhere
, visited
.end());
1135 ASSERT_EQ(da1
, visited
.end()); // Not visited.
1136 ASSERT_NE(z0
, visited
.end());
1137 ASSERT_NE(za1
, visited
.end());
1138 ASSERT_NE(pop
, visited
.end());
1139 ASSERT_EQ(p1
, visited
.end()); // Not visited.
1141 // Make sure that parents were visited before children. No other ordering
1142 // guarantees can be made across siblings.
1147 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/a0/aa1"));
1148 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/a0/ab1"));
1149 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/a0"));
1151 fs::remove(Twine(TestDirectory
) + "/recursive/dontlookhere/da1"));
1152 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/dontlookhere"));
1153 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/pop/p1"));
1154 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/pop"));
1155 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/z0/za1"));
1156 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/z0"));
1157 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive"));
1159 // Test recursive_directory_iterator level()
1161 fs::create_directories(Twine(TestDirectory
) + "/reclevel/a/b/c"));
1162 fs::recursive_directory_iterator
I(Twine(TestDirectory
) + "/reclevel", ec
), E
;
1163 for (int l
= 0; I
!= E
; I
.increment(ec
), ++l
) {
1164 ASSERT_NO_ERROR(ec
);
1165 EXPECT_EQ(I
.level(), l
);
1168 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/reclevel/a/b/c"));
1169 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/reclevel/a/b"));
1170 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/reclevel/a"));
1171 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/reclevel"));
1174 TEST_F(FileSystemTest
, DirectoryNotExecutable
) {
1175 ASSERT_EQ(fs::access(TestDirectory
, sys::fs::AccessMode::Execute
),
1176 errc::permission_denied
);
1180 TEST_F(FileSystemTest
, BrokenSymlinkDirectoryIteration
) {
1181 // Create a known hierarchy to recurse over.
1182 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory
) + "/symlink"));
1184 fs::create_link("no_such_file", Twine(TestDirectory
) + "/symlink/a"));
1186 fs::create_directories(Twine(TestDirectory
) + "/symlink/b/bb"));
1188 fs::create_link("no_such_file", Twine(TestDirectory
) + "/symlink/b/ba"));
1190 fs::create_link("no_such_file", Twine(TestDirectory
) + "/symlink/b/bc"));
1192 fs::create_link("no_such_file", Twine(TestDirectory
) + "/symlink/c"));
1194 fs::create_directories(Twine(TestDirectory
) + "/symlink/d/dd/ddd"));
1195 ASSERT_NO_ERROR(fs::create_link(Twine(TestDirectory
) + "/symlink/d/dd",
1196 Twine(TestDirectory
) + "/symlink/d/da"));
1198 fs::create_link("no_such_file", Twine(TestDirectory
) + "/symlink/e"));
1200 typedef std::vector
<std::string
> v_t
;
1201 v_t VisitedNonBrokenSymlinks
;
1202 v_t VisitedBrokenSymlinks
;
1204 using testing::UnorderedElementsAre
;
1205 using testing::UnorderedElementsAreArray
;
1207 // Broken symbol links are expected to throw an error.
1208 for (fs::directory_iterator
i(Twine(TestDirectory
) + "/symlink", ec
), e
;
1209 i
!= e
; i
.increment(ec
)) {
1210 ASSERT_NO_ERROR(ec
);
1211 if (i
->status().getError() ==
1212 std::make_error_code(std::errc::no_such_file_or_directory
)) {
1213 VisitedBrokenSymlinks
.push_back(std::string(path::filename(i
->path())));
1216 VisitedNonBrokenSymlinks
.push_back(std::string(path::filename(i
->path())));
1218 EXPECT_THAT(VisitedNonBrokenSymlinks
, UnorderedElementsAre("b", "d"));
1219 VisitedNonBrokenSymlinks
.clear();
1221 EXPECT_THAT(VisitedBrokenSymlinks
, UnorderedElementsAre("a", "c", "e"));
1222 VisitedBrokenSymlinks
.clear();
1224 // Broken symbol links are expected to throw an error.
1225 for (fs::recursive_directory_iterator
i(
1226 Twine(TestDirectory
) + "/symlink", ec
), e
; i
!= e
; i
.increment(ec
)) {
1227 ASSERT_NO_ERROR(ec
);
1228 if (i
->status().getError() ==
1229 std::make_error_code(std::errc::no_such_file_or_directory
)) {
1230 VisitedBrokenSymlinks
.push_back(std::string(path::filename(i
->path())));
1233 VisitedNonBrokenSymlinks
.push_back(std::string(path::filename(i
->path())));
1235 EXPECT_THAT(VisitedNonBrokenSymlinks
,
1236 UnorderedElementsAre("b", "bb", "d", "da", "dd", "ddd", "ddd"));
1237 VisitedNonBrokenSymlinks
.clear();
1239 EXPECT_THAT(VisitedBrokenSymlinks
,
1240 UnorderedElementsAre("a", "ba", "bc", "c", "e"));
1241 VisitedBrokenSymlinks
.clear();
1243 for (fs::recursive_directory_iterator
i(
1244 Twine(TestDirectory
) + "/symlink", ec
, /*follow_symlinks=*/false), e
;
1245 i
!= e
; i
.increment(ec
)) {
1246 ASSERT_NO_ERROR(ec
);
1247 if (i
->status().getError() ==
1248 std::make_error_code(std::errc::no_such_file_or_directory
)) {
1249 VisitedBrokenSymlinks
.push_back(std::string(path::filename(i
->path())));
1252 VisitedNonBrokenSymlinks
.push_back(std::string(path::filename(i
->path())));
1254 EXPECT_THAT(VisitedNonBrokenSymlinks
,
1255 UnorderedElementsAreArray({"a", "b", "ba", "bb", "bc", "c", "d",
1256 "da", "dd", "ddd", "e"}));
1257 VisitedNonBrokenSymlinks
.clear();
1259 EXPECT_THAT(VisitedBrokenSymlinks
, UnorderedElementsAre());
1260 VisitedBrokenSymlinks
.clear();
1262 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory
) + "/symlink"));
1267 TEST_F(FileSystemTest
, UTF8ToUTF16DirectoryIteration
) {
1268 // The Windows filesystem support uses UTF-16 and converts paths from the
1269 // input UTF-8. The UTF-16 equivalent of the input path can be shorter in
1272 // This test relies on TestDirectory not being so long such that MAX_PATH
1273 // would be exceeded (see widenPath). If that were the case, the UTF-16
1274 // path is likely to be longer than the input.
1275 const char *Pi
= "\xcf\x80"; // UTF-8 lower case pi.
1276 std::string RootDir
= (TestDirectory
+ "/" + Pi
).str();
1278 // Create test directories.
1279 ASSERT_NO_ERROR(fs::create_directories(Twine(RootDir
) + "/a"));
1280 ASSERT_NO_ERROR(fs::create_directories(Twine(RootDir
) + "/b"));
1284 for (fs::directory_iterator
I(Twine(RootDir
), EC
), E
; I
!= E
;
1286 ASSERT_NO_ERROR(EC
);
1287 StringRef DirName
= path::filename(I
->path());
1288 EXPECT_TRUE(DirName
== "a" || DirName
== "b");
1291 EXPECT_EQ(Count
, 2U);
1293 ASSERT_NO_ERROR(fs::remove(Twine(RootDir
) + "/a"));
1294 ASSERT_NO_ERROR(fs::remove(Twine(RootDir
) + "/b"));
1295 ASSERT_NO_ERROR(fs::remove(Twine(RootDir
)));
1299 TEST_F(FileSystemTest
, Remove
) {
1300 SmallString
<64> BaseDir
;
1301 SmallString
<64> Paths
[4];
1303 ASSERT_NO_ERROR(fs::createUniqueDirectory("fs_remove", BaseDir
));
1305 ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir
) + "/foo/bar/baz"));
1306 ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir
) + "/foo/bar/buzz"));
1307 ASSERT_NO_ERROR(fs::createUniqueFile(
1308 Twine(BaseDir
) + "/foo/bar/baz/%%%%%%.tmp", fds
[0], Paths
[0]));
1309 ASSERT_NO_ERROR(fs::createUniqueFile(
1310 Twine(BaseDir
) + "/foo/bar/baz/%%%%%%.tmp", fds
[1], Paths
[1]));
1311 ASSERT_NO_ERROR(fs::createUniqueFile(
1312 Twine(BaseDir
) + "/foo/bar/buzz/%%%%%%.tmp", fds
[2], Paths
[2]));
1313 ASSERT_NO_ERROR(fs::createUniqueFile(
1314 Twine(BaseDir
) + "/foo/bar/buzz/%%%%%%.tmp", fds
[3], Paths
[3]));
1319 EXPECT_TRUE(fs::exists(Twine(BaseDir
) + "/foo/bar/baz"));
1320 EXPECT_TRUE(fs::exists(Twine(BaseDir
) + "/foo/bar/buzz"));
1321 EXPECT_TRUE(fs::exists(Paths
[0]));
1322 EXPECT_TRUE(fs::exists(Paths
[1]));
1323 EXPECT_TRUE(fs::exists(Paths
[2]));
1324 EXPECT_TRUE(fs::exists(Paths
[3]));
1326 ASSERT_NO_ERROR(fs::remove_directories("D:/footest"));
1328 ASSERT_NO_ERROR(fs::remove_directories(BaseDir
));
1329 ASSERT_FALSE(fs::exists(BaseDir
));
1333 TEST_F(FileSystemTest
, CarriageReturn
) {
1334 SmallString
<128> FilePathname(TestDirectory
);
1336 path::append(FilePathname
, "test");
1339 raw_fd_ostream
File(FilePathname
, EC
, sys::fs::OF_TextWithCRLF
);
1340 ASSERT_NO_ERROR(EC
);
1344 auto Buf
= MemoryBuffer::getFile(FilePathname
.str());
1345 EXPECT_TRUE((bool)Buf
);
1346 EXPECT_EQ(Buf
.get()->getBuffer(), "\r\n");
1350 raw_fd_ostream
File(FilePathname
, EC
, sys::fs::OF_None
);
1351 ASSERT_NO_ERROR(EC
);
1355 auto Buf
= MemoryBuffer::getFile(FilePathname
.str());
1356 EXPECT_TRUE((bool)Buf
);
1357 EXPECT_EQ(Buf
.get()->getBuffer(), "\n");
1359 ASSERT_NO_ERROR(fs::remove(Twine(FilePathname
)));
1363 TEST_F(FileSystemTest
, Resize
) {
1365 SmallString
<64> TempPath
;
1366 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD
, TempPath
));
1367 ASSERT_NO_ERROR(fs::resize_file(FD
, 123));
1368 fs::file_status Status
;
1369 ASSERT_NO_ERROR(fs::status(FD
, Status
));
1370 ASSERT_EQ(Status
.getSize(), 123U);
1372 ASSERT_NO_ERROR(fs::remove(TempPath
));
1375 TEST_F(FileSystemTest
, ResizeBeforeMapping
) {
1376 // Create a temp file.
1378 SmallString
<64> TempPath
;
1379 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD
, TempPath
));
1380 ASSERT_NO_ERROR(fs::resize_file_before_mapping_readwrite(FD
, 123));
1382 // Map in temp file. On Windows, fs::resize_file_before_mapping_readwrite is
1383 // a no-op and the mapping itself will resize the file.
1386 fs::mapped_file_region
mfr(fs::convertFDToNativeFile(FD
),
1387 fs::mapped_file_region::readwrite
, 123, 0, EC
);
1388 ASSERT_NO_ERROR(EC
);
1393 fs::file_status Status
;
1394 ASSERT_NO_ERROR(fs::status(FD
, Status
));
1395 ASSERT_EQ(Status
.getSize(), 123U);
1397 ASSERT_NO_ERROR(fs::remove(TempPath
));
1400 TEST_F(FileSystemTest
, MD5
) {
1402 SmallString
<64> TempPath
;
1403 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD
, TempPath
));
1404 StringRef
Data("abcdefghijklmnopqrstuvwxyz");
1405 ASSERT_EQ(write(FD
, Data
.data(), Data
.size()), static_cast<ssize_t
>(Data
.size()));
1406 lseek(FD
, 0, SEEK_SET
);
1407 auto Hash
= fs::md5_contents(FD
);
1409 ASSERT_NO_ERROR(Hash
.getError());
1411 EXPECT_STREQ("c3fcd3d76192e4007dfb496cca67e13b", Hash
->digest().c_str());
1414 TEST_F(FileSystemTest
, FileMapping
) {
1415 // Create a temp file.
1417 SmallString
<64> TempPath
;
1419 fs::createTemporaryFile("prefix", "temp", FileDescriptor
, TempPath
));
1420 unsigned Size
= 4096;
1422 fs::resize_file_before_mapping_readwrite(FileDescriptor
, Size
));
1424 // Map in temp file and add some content
1426 StringRef
Val("hello there");
1427 fs::mapped_file_region MaybeMFR
;
1428 EXPECT_FALSE(MaybeMFR
);
1430 fs::mapped_file_region
mfr(fs::convertFDToNativeFile(FileDescriptor
),
1431 fs::mapped_file_region::readwrite
, Size
, 0, EC
);
1432 ASSERT_NO_ERROR(EC
);
1433 std::copy(Val
.begin(), Val
.end(), mfr
.data());
1434 // Explicitly add a 0.
1435 mfr
.data()[Val
.size()] = 0;
1437 // Move it out of the scope and confirm mfr is reset.
1438 MaybeMFR
= std::move(mfr
);
1440 #if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST
1441 EXPECT_DEATH(mfr
.data(), "Mapping failed but used anyway!");
1442 EXPECT_DEATH(mfr
.size(), "Mapping failed but used anyway!");
1446 // Check that the moved-to region is still valid.
1447 EXPECT_EQ(Val
, StringRef(MaybeMFR
.data()));
1448 EXPECT_EQ(Size
, MaybeMFR
.size());
1453 ASSERT_EQ(close(FileDescriptor
), 0);
1455 // Map it back in read-only
1458 EC
= fs::openFileForRead(Twine(TempPath
), FD
);
1459 ASSERT_NO_ERROR(EC
);
1460 fs::mapped_file_region
mfr(fs::convertFDToNativeFile(FD
),
1461 fs::mapped_file_region::readonly
, Size
, 0, EC
);
1462 ASSERT_NO_ERROR(EC
);
1465 EXPECT_EQ(StringRef(mfr
.const_data()), Val
);
1468 fs::mapped_file_region
m(fs::convertFDToNativeFile(FD
),
1469 fs::mapped_file_region::readonly
, Size
, 0, EC
);
1470 ASSERT_NO_ERROR(EC
);
1471 ASSERT_EQ(close(FD
), 0);
1473 ASSERT_NO_ERROR(fs::remove(TempPath
));
1476 TEST(Support
, NormalizePath
) {
1477 // Input, Expected Win, Expected Posix
1478 using TestTuple
= std::tuple
<const char *, const char *, const char *>;
1479 std::vector
<TestTuple
> Tests
;
1480 Tests
.emplace_back("a", "a", "a");
1481 Tests
.emplace_back("a/b", "a\\b", "a/b");
1482 Tests
.emplace_back("a\\b", "a\\b", "a/b");
1483 Tests
.emplace_back("a\\\\b", "a\\\\b", "a//b");
1484 Tests
.emplace_back("\\a", "\\a", "/a");
1485 Tests
.emplace_back("a\\", "a\\", "a/");
1486 Tests
.emplace_back("a\\t", "a\\t", "a/t");
1488 for (auto &T
: Tests
) {
1489 SmallString
<64> Win(std::get
<0>(T
));
1490 SmallString
<64> Posix(Win
);
1491 SmallString
<64> WinSlash(Win
);
1492 path::native(Win
, path::Style::windows
);
1493 path::native(Posix
, path::Style::posix
);
1494 path::native(WinSlash
, path::Style::windows_slash
);
1495 EXPECT_EQ(std::get
<1>(T
), Win
);
1496 EXPECT_EQ(std::get
<2>(T
), Posix
);
1497 EXPECT_EQ(std::get
<2>(T
), WinSlash
);
1500 for (auto &T
: Tests
) {
1501 SmallString
<64> WinBackslash(std::get
<0>(T
));
1502 SmallString
<64> Posix(WinBackslash
);
1503 SmallString
<64> WinSlash(WinBackslash
);
1504 path::make_preferred(WinBackslash
, path::Style::windows_backslash
);
1505 path::make_preferred(Posix
, path::Style::posix
);
1506 path::make_preferred(WinSlash
, path::Style::windows_slash
);
1507 EXPECT_EQ(std::get
<1>(T
), WinBackslash
);
1508 EXPECT_EQ(std::get
<0>(T
), Posix
); // Posix remains unchanged here
1509 EXPECT_EQ(std::get
<2>(T
), WinSlash
);
1513 SmallString
<64> PathHome
;
1514 path::home_directory(PathHome
);
1516 const char *Path7a
= "~/aaa";
1517 SmallString
<64> Path7(Path7a
);
1518 path::native(Path7
, path::Style::windows_backslash
);
1519 EXPECT_TRUE(Path7
.ends_with("\\aaa"));
1520 EXPECT_TRUE(Path7
.starts_with(PathHome
));
1521 EXPECT_EQ(Path7
.size(), PathHome
.size() + strlen(Path7a
+ 1));
1523 path::native(Path7
, path::Style::windows_slash
);
1524 EXPECT_TRUE(Path7
.ends_with("/aaa"));
1525 EXPECT_TRUE(Path7
.starts_with(PathHome
));
1526 EXPECT_EQ(Path7
.size(), PathHome
.size() + strlen(Path7a
+ 1));
1528 const char *Path8a
= "~";
1529 SmallString
<64> Path8(Path8a
);
1530 path::native(Path8
);
1531 EXPECT_EQ(Path8
, PathHome
);
1533 const char *Path9a
= "~aaa";
1534 SmallString
<64> Path9(Path9a
);
1535 path::native(Path9
);
1536 EXPECT_EQ(Path9
, "~aaa");
1538 const char *Path10a
= "aaa/~/b";
1539 SmallString
<64> Path10(Path10a
);
1540 path::native(Path10
, path::Style::windows_backslash
);
1541 EXPECT_EQ(Path10
, "aaa\\~\\b");
1545 TEST(Support
, RemoveLeadingDotSlash
) {
1546 StringRef
Path1("././/foolz/wat");
1547 StringRef
Path2("./////");
1549 Path1
= path::remove_leading_dotslash(Path1
);
1550 EXPECT_EQ(Path1
, "foolz/wat");
1551 Path2
= path::remove_leading_dotslash(Path2
);
1552 EXPECT_EQ(Path2
, "");
1555 static std::string
remove_dots(StringRef path
, bool remove_dot_dot
,
1556 path::Style style
) {
1557 SmallString
<256> buffer(path
);
1558 path::remove_dots(buffer
, remove_dot_dot
, style
);
1559 return std::string(buffer
.str());
1562 TEST(Support
, RemoveDots
) {
1563 EXPECT_EQ("foolz\\wat",
1564 remove_dots(".\\.\\\\foolz\\wat", false, path::Style::windows
));
1565 EXPECT_EQ("", remove_dots(".\\\\\\\\\\", false, path::Style::windows
));
1567 EXPECT_EQ("a\\..\\b\\c",
1568 remove_dots(".\\a\\..\\b\\c", false, path::Style::windows
));
1569 EXPECT_EQ("b\\c", remove_dots(".\\a\\..\\b\\c", true, path::Style::windows
));
1570 EXPECT_EQ("c", remove_dots(".\\.\\c", true, path::Style::windows
));
1571 EXPECT_EQ("..\\a\\c",
1572 remove_dots("..\\a\\b\\..\\c", true, path::Style::windows
));
1573 EXPECT_EQ("..\\..\\a\\c",
1574 remove_dots("..\\..\\a\\b\\..\\c", true, path::Style::windows
));
1575 EXPECT_EQ("C:\\a\\c", remove_dots("C:\\foo\\bar//..\\..\\a\\c", true,
1576 path::Style::windows
));
1578 EXPECT_EQ("C:\\bar",
1579 remove_dots("C:/foo/../bar", true, path::Style::windows
));
1580 EXPECT_EQ("C:\\foo\\bar",
1581 remove_dots("C:/foo/bar", true, path::Style::windows
));
1582 EXPECT_EQ("C:\\foo\\bar",
1583 remove_dots("C:/foo\\bar", true, path::Style::windows
));
1584 EXPECT_EQ("\\", remove_dots("/", true, path::Style::windows
));
1585 EXPECT_EQ("C:\\", remove_dots("C:/", true, path::Style::windows
));
1587 // Some clients of remove_dots expect it to remove trailing slashes. Again,
1588 // this is emergent behavior that VFS relies on, and not inherently part of
1589 // the specification.
1590 EXPECT_EQ("C:\\foo\\bar",
1591 remove_dots("C:\\foo\\bar\\", true, path::Style::windows
));
1592 EXPECT_EQ("/foo/bar",
1593 remove_dots("/foo/bar/", true, path::Style::posix
));
1595 // A double separator is rewritten.
1596 EXPECT_EQ("C:\\foo\\bar",
1597 remove_dots("C:/foo//bar", true, path::Style::windows
));
1599 SmallString
<64> Path1(".\\.\\c");
1600 EXPECT_TRUE(path::remove_dots(Path1
, true, path::Style::windows
));
1601 EXPECT_EQ("c", Path1
);
1603 EXPECT_EQ("foolz/wat",
1604 remove_dots("././/foolz/wat", false, path::Style::posix
));
1605 EXPECT_EQ("", remove_dots("./////", false, path::Style::posix
));
1607 EXPECT_EQ("a/../b/c", remove_dots("./a/../b/c", false, path::Style::posix
));
1608 EXPECT_EQ("b/c", remove_dots("./a/../b/c", true, path::Style::posix
));
1609 EXPECT_EQ("c", remove_dots("././c", true, path::Style::posix
));
1610 EXPECT_EQ("../a/c", remove_dots("../a/b/../c", true, path::Style::posix
));
1611 EXPECT_EQ("../../a/c",
1612 remove_dots("../../a/b/../c", true, path::Style::posix
));
1613 EXPECT_EQ("/a/c", remove_dots("/../../a/c", true, path::Style::posix
));
1615 remove_dots("/../a/b//../././/c", true, path::Style::posix
));
1616 EXPECT_EQ("/", remove_dots("/", true, path::Style::posix
));
1618 // FIXME: Leaving behind this double leading slash seems like a bug.
1619 EXPECT_EQ("//foo/bar",
1620 remove_dots("//foo/bar/", true, path::Style::posix
));
1622 SmallString
<64> Path2("././c");
1623 EXPECT_TRUE(path::remove_dots(Path2
, true, path::Style::posix
));
1624 EXPECT_EQ("c", Path2
);
1627 TEST(Support
, ReplacePathPrefix
) {
1628 SmallString
<64> Path1("/foo");
1629 SmallString
<64> Path2("/old/foo");
1630 SmallString
<64> Path3("/oldnew/foo");
1631 SmallString
<64> Path4("C:\\old/foo\\bar");
1632 SmallString
<64> OldPrefix("/old");
1633 SmallString
<64> OldPrefixSep("/old/");
1634 SmallString
<64> OldPrefixWin("c:/oLD/F");
1635 SmallString
<64> NewPrefix("/new");
1636 SmallString
<64> NewPrefix2("/longernew");
1637 SmallString
<64> EmptyPrefix("");
1640 SmallString
<64> Path
= Path1
;
1641 Found
= path::replace_path_prefix(Path
, OldPrefix
, NewPrefix
);
1642 EXPECT_FALSE(Found
);
1643 EXPECT_EQ(Path
, "/foo");
1645 Found
= path::replace_path_prefix(Path
, OldPrefix
, NewPrefix
);
1647 EXPECT_EQ(Path
, "/new/foo");
1649 Found
= path::replace_path_prefix(Path
, OldPrefix
, NewPrefix2
);
1651 EXPECT_EQ(Path
, "/longernew/foo");
1653 Found
= path::replace_path_prefix(Path
, EmptyPrefix
, NewPrefix
);
1655 EXPECT_EQ(Path
, "/new/foo");
1657 Found
= path::replace_path_prefix(Path
, OldPrefix
, EmptyPrefix
);
1659 EXPECT_EQ(Path
, "/foo");
1661 Found
= path::replace_path_prefix(Path
, OldPrefixSep
, EmptyPrefix
);
1663 EXPECT_EQ(Path
, "foo");
1665 Found
= path::replace_path_prefix(Path
, OldPrefix
, NewPrefix
);
1667 EXPECT_EQ(Path
, "/newnew/foo");
1669 Found
= path::replace_path_prefix(Path
, OldPrefix
, NewPrefix2
);
1671 EXPECT_EQ(Path
, "/longernewnew/foo");
1673 Found
= path::replace_path_prefix(Path
, EmptyPrefix
, NewPrefix
);
1675 EXPECT_EQ(Path
, "/new/foo");
1677 Found
= path::replace_path_prefix(Path
, OldPrefix
, NewPrefix
);
1679 EXPECT_EQ(Path
, "/new");
1680 Path
= OldPrefixSep
;
1681 Found
= path::replace_path_prefix(Path
, OldPrefix
, NewPrefix
);
1683 EXPECT_EQ(Path
, "/new/");
1685 Found
= path::replace_path_prefix(Path
, OldPrefixSep
, NewPrefix
);
1686 EXPECT_FALSE(Found
);
1687 EXPECT_EQ(Path
, "/old");
1689 Found
= path::replace_path_prefix(Path
, OldPrefixWin
, NewPrefix
,
1690 path::Style::windows
);
1692 EXPECT_EQ(Path
, "/newoo\\bar");
1694 Found
= path::replace_path_prefix(Path
, OldPrefixWin
, NewPrefix
,
1695 path::Style::posix
);
1696 EXPECT_FALSE(Found
);
1697 EXPECT_EQ(Path
, "C:\\old/foo\\bar");
1700 TEST_F(FileSystemTest
, OpenFileForRead
) {
1701 // Create a temp file.
1703 SmallString
<64> TempPath
;
1705 fs::createTemporaryFile("prefix", "temp", FileDescriptor
, TempPath
));
1706 FileRemover
Cleanup(TempPath
);
1708 // Make sure it exists.
1709 ASSERT_TRUE(sys::fs::exists(Twine(TempPath
)));
1711 // Open the file for read
1712 int FileDescriptor2
;
1713 SmallString
<64> ResultPath
;
1714 ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath
), FileDescriptor2
,
1715 fs::OF_None
, &ResultPath
))
1717 // If we succeeded, check that the paths are the same (modulo case):
1718 if (!ResultPath
.empty()) {
1719 // The paths returned by createTemporaryFile and getPathFromOpenFD
1720 // should reference the same file on disk.
1721 fs::UniqueID D1
, D2
;
1722 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath
), D1
));
1723 ASSERT_NO_ERROR(fs::getUniqueID(Twine(ResultPath
), D2
));
1726 ::close(FileDescriptor
);
1727 ::close(FileDescriptor2
);
1730 // Since Windows Vista, file access time is not updated by default.
1731 // This is instead updated manually by openFileForRead.
1732 // https://blogs.technet.microsoft.com/filecab/2006/11/07/disabling-last-access-time-in-windows-vista-to-improve-ntfs-performance/
1733 // This part of the unit test is Windows specific as the updating of
1734 // access times can be disabled on Linux using /etc/fstab.
1736 // Set access time to UNIX epoch.
1737 ASSERT_NO_ERROR(sys::fs::openFileForWrite(Twine(TempPath
), FileDescriptor
,
1738 fs::CD_OpenExisting
));
1739 TimePoint
<> Epoch(std::chrono::milliseconds(0));
1740 ASSERT_NO_ERROR(fs::setLastAccessAndModificationTime(FileDescriptor
, Epoch
));
1741 ::close(FileDescriptor
);
1743 // Open the file and ensure access time is updated, when forced.
1744 ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath
), FileDescriptor
,
1745 fs::OF_UpdateAtime
, &ResultPath
));
1747 sys::fs::file_status Status
;
1748 ASSERT_NO_ERROR(sys::fs::status(FileDescriptor
, Status
));
1749 auto FileAccessTime
= Status
.getLastAccessedTime();
1751 ASSERT_NE(Epoch
, FileAccessTime
);
1752 ::close(FileDescriptor
);
1754 // Ideally this test would include a case when ATime is not forced to update,
1755 // however the expected behaviour will differ depending on the configuration
1756 // of the Windows file system.
1760 TEST_F(FileSystemTest
, OpenDirectoryAsFileForRead
) {
1761 std::string
Buf(5, '?');
1762 Expected
<fs::file_t
> FD
= fs::openNativeFileForRead(TestDirectory
);
1764 EXPECT_EQ(errorToErrorCode(FD
.takeError()), errc::is_a_directory
);
1766 ASSERT_THAT_EXPECTED(FD
, Succeeded());
1767 auto Close
= make_scope_exit([&] { fs::closeFile(*FD
); });
1768 Expected
<size_t> BytesRead
=
1769 fs::readNativeFile(*FD
, MutableArrayRef(&*Buf
.begin(), Buf
.size()));
1770 EXPECT_EQ(errorToErrorCode(BytesRead
.takeError()), errc::is_a_directory
);
1774 TEST_F(FileSystemTest
, OpenDirectoryAsFileForWrite
) {
1776 std::error_code EC
= fs::openFileForWrite(Twine(TestDirectory
), FD
);
1779 EXPECT_EQ(EC
, errc::is_a_directory
);
1782 static void createFileWithData(const Twine
&Path
, bool ShouldExistBefore
,
1783 fs::CreationDisposition Disp
, StringRef Data
) {
1785 ASSERT_EQ(ShouldExistBefore
, fs::exists(Path
));
1786 ASSERT_NO_ERROR(fs::openFileForWrite(Path
, FD
, Disp
));
1787 FileDescriptorCloser
Closer(FD
);
1788 ASSERT_TRUE(fs::exists(Path
));
1790 ASSERT_EQ(Data
.size(), (size_t)write(FD
, Data
.data(), Data
.size()));
1793 static void verifyFileContents(const Twine
&Path
, StringRef Contents
) {
1794 auto Buffer
= MemoryBuffer::getFile(Path
);
1795 ASSERT_TRUE((bool)Buffer
);
1796 StringRef Data
= Buffer
.get()->getBuffer();
1797 ASSERT_EQ(Data
, Contents
);
1800 TEST_F(FileSystemTest
, CreateNew
) {
1802 std::optional
<FileDescriptorCloser
> Closer
;
1804 // Succeeds if the file does not exist.
1805 ASSERT_FALSE(fs::exists(NonExistantFile
));
1806 ASSERT_NO_ERROR(fs::openFileForWrite(NonExistantFile
, FD
, fs::CD_CreateNew
));
1807 ASSERT_TRUE(fs::exists(NonExistantFile
));
1809 FileRemover
Cleanup(NonExistantFile
);
1812 // And creates a file of size 0.
1813 sys::fs::file_status Status
;
1814 ASSERT_NO_ERROR(sys::fs::status(FD
, Status
));
1815 EXPECT_EQ(0ULL, Status
.getSize());
1817 // Close this first, before trying to re-open the file.
1820 // But fails if the file does exist.
1821 ASSERT_ERROR(fs::openFileForWrite(NonExistantFile
, FD
, fs::CD_CreateNew
));
1824 TEST_F(FileSystemTest
, CreateAlways
) {
1826 std::optional
<FileDescriptorCloser
> Closer
;
1828 // Succeeds if the file does not exist.
1829 ASSERT_FALSE(fs::exists(NonExistantFile
));
1831 fs::openFileForWrite(NonExistantFile
, FD
, fs::CD_CreateAlways
));
1835 ASSERT_TRUE(fs::exists(NonExistantFile
));
1837 FileRemover
Cleanup(NonExistantFile
);
1839 // And creates a file of size 0.
1841 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1842 ASSERT_EQ(0ULL, FileSize
);
1844 // If we write some data to it re-create it with CreateAlways, it succeeds and
1845 // truncates to 0 bytes.
1846 ASSERT_EQ(4, write(FD
, "Test", 4));
1850 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1851 ASSERT_EQ(4ULL, FileSize
);
1854 fs::openFileForWrite(NonExistantFile
, FD
, fs::CD_CreateAlways
));
1856 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1857 ASSERT_EQ(0ULL, FileSize
);
1860 TEST_F(FileSystemTest
, OpenExisting
) {
1863 // Fails if the file does not exist.
1864 ASSERT_FALSE(fs::exists(NonExistantFile
));
1865 ASSERT_ERROR(fs::openFileForWrite(NonExistantFile
, FD
, fs::CD_OpenExisting
));
1866 ASSERT_FALSE(fs::exists(NonExistantFile
));
1868 // Make a dummy file now so that we can try again when the file does exist.
1869 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "Fizz");
1870 FileRemover
Cleanup(NonExistantFile
);
1872 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1873 ASSERT_EQ(4ULL, FileSize
);
1875 // If we re-create it with different data, it overwrites rather than
1877 createFileWithData(NonExistantFile
, true, fs::CD_OpenExisting
, "Buzz");
1878 verifyFileContents(NonExistantFile
, "Buzz");
1881 TEST_F(FileSystemTest
, OpenAlways
) {
1882 // Succeeds if the file does not exist.
1883 createFileWithData(NonExistantFile
, false, fs::CD_OpenAlways
, "Fizz");
1884 FileRemover
Cleanup(NonExistantFile
);
1886 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1887 ASSERT_EQ(4ULL, FileSize
);
1889 // Now re-open it and write again, verifying the contents get over-written.
1890 createFileWithData(NonExistantFile
, true, fs::CD_OpenAlways
, "Bu");
1891 verifyFileContents(NonExistantFile
, "Buzz");
1894 TEST_F(FileSystemTest
, AppendSetsCorrectFileOffset
) {
1895 fs::CreationDisposition Disps
[] = {fs::CD_CreateAlways
, fs::CD_OpenAlways
,
1896 fs::CD_OpenExisting
};
1898 // Write some data and re-open it with every possible disposition (this is a
1899 // hack that shouldn't work, but is left for compatibility. OF_Append
1901 // the specified disposition.
1902 for (fs::CreationDisposition Disp
: Disps
) {
1904 std::optional
<FileDescriptorCloser
> Closer
;
1906 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "Fizz");
1908 FileRemover
Cleanup(NonExistantFile
);
1911 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1912 ASSERT_EQ(4ULL, FileSize
);
1914 fs::openFileForWrite(NonExistantFile
, FD
, Disp
, fs::OF_Append
));
1916 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1917 ASSERT_EQ(4ULL, FileSize
);
1919 ASSERT_EQ(4, write(FD
, "Buzz", 4));
1922 verifyFileContents(NonExistantFile
, "FizzBuzz");
1926 static void verifyRead(int FD
, StringRef Data
, bool ShouldSucceed
) {
1927 std::vector
<char> Buffer
;
1928 Buffer
.resize(Data
.size());
1929 int Result
= ::read(FD
, Buffer
.data(), Buffer
.size());
1930 if (ShouldSucceed
) {
1931 ASSERT_EQ((size_t)Result
, Data
.size());
1932 ASSERT_EQ(Data
, StringRef(Buffer
.data(), Buffer
.size()));
1934 ASSERT_EQ(-1, Result
);
1935 ASSERT_EQ(EBADF
, errno
);
1939 static void verifyWrite(int FD
, StringRef Data
, bool ShouldSucceed
) {
1940 int Result
= ::write(FD
, Data
.data(), Data
.size());
1942 ASSERT_EQ((size_t)Result
, Data
.size());
1944 ASSERT_EQ(-1, Result
);
1945 ASSERT_EQ(EBADF
, errno
);
1949 TEST_F(FileSystemTest
, ReadOnlyFileCantWrite
) {
1950 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "Fizz");
1951 FileRemover
Cleanup(NonExistantFile
);
1954 ASSERT_NO_ERROR(fs::openFileForRead(NonExistantFile
, FD
));
1955 FileDescriptorCloser
Closer(FD
);
1957 verifyWrite(FD
, "Buzz", false);
1958 verifyRead(FD
, "Fizz", true);
1961 TEST_F(FileSystemTest
, WriteOnlyFileCantRead
) {
1962 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "Fizz");
1963 FileRemover
Cleanup(NonExistantFile
);
1967 fs::openFileForWrite(NonExistantFile
, FD
, fs::CD_OpenExisting
));
1968 FileDescriptorCloser
Closer(FD
);
1969 verifyRead(FD
, "Fizz", false);
1970 verifyWrite(FD
, "Buzz", true);
1973 TEST_F(FileSystemTest
, ReadWriteFileCanReadOrWrite
) {
1974 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "Fizz");
1975 FileRemover
Cleanup(NonExistantFile
);
1978 ASSERT_NO_ERROR(fs::openFileForReadWrite(NonExistantFile
, FD
,
1979 fs::CD_OpenExisting
, fs::OF_None
));
1980 FileDescriptorCloser
Closer(FD
);
1981 verifyRead(FD
, "Fizz", true);
1982 verifyWrite(FD
, "Buzz", true);
1985 TEST_F(FileSystemTest
, readNativeFile
) {
1986 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "01234");
1987 FileRemover
Cleanup(NonExistantFile
);
1988 const auto &Read
= [&](size_t ToRead
) -> Expected
<std::string
> {
1989 std::string
Buf(ToRead
, '?');
1990 Expected
<fs::file_t
> FD
= fs::openNativeFileForRead(NonExistantFile
);
1992 return FD
.takeError();
1993 auto Close
= make_scope_exit([&] { fs::closeFile(*FD
); });
1994 if (Expected
<size_t> BytesRead
= fs::readNativeFile(
1995 *FD
, MutableArrayRef(&*Buf
.begin(), Buf
.size())))
1996 return Buf
.substr(0, *BytesRead
);
1998 return BytesRead
.takeError();
2000 EXPECT_THAT_EXPECTED(Read(5), HasValue("01234"));
2001 EXPECT_THAT_EXPECTED(Read(3), HasValue("012"));
2002 EXPECT_THAT_EXPECTED(Read(6), HasValue("01234"));
2005 TEST_F(FileSystemTest
, readNativeFileToEOF
) {
2006 constexpr StringLiteral Content
= "0123456789";
2007 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, Content
);
2008 FileRemover
Cleanup(NonExistantFile
);
2009 const auto &Read
= [&](SmallVectorImpl
<char> &V
,
2010 std::optional
<ssize_t
> ChunkSize
) {
2011 Expected
<fs::file_t
> FD
= fs::openNativeFileForRead(NonExistantFile
);
2013 return FD
.takeError();
2014 auto Close
= make_scope_exit([&] { fs::closeFile(*FD
); });
2016 return fs::readNativeFileToEOF(*FD
, V
, *ChunkSize
);
2017 return fs::readNativeFileToEOF(*FD
, V
);
2020 // Check basic operation.
2022 SmallString
<0> NoSmall
;
2023 SmallString
<fs::DefaultReadChunkSize
+ Content
.size()> StaysSmall
;
2024 SmallVectorImpl
<char> *Vectors
[] = {
2025 static_cast<SmallVectorImpl
<char> *>(&NoSmall
),
2026 static_cast<SmallVectorImpl
<char> *>(&StaysSmall
),
2028 for (SmallVectorImpl
<char> *V
: Vectors
) {
2029 ASSERT_THAT_ERROR(Read(*V
, std::nullopt
), Succeeded());
2030 ASSERT_EQ(Content
, StringRef(V
->begin(), V
->size()));
2032 ASSERT_EQ(fs::DefaultReadChunkSize
+ Content
.size(), StaysSmall
.capacity());
2036 constexpr StringLiteral Prefix
= "prefix-";
2037 for (SmallVectorImpl
<char> *V
: Vectors
) {
2038 V
->assign(Prefix
.begin(), Prefix
.end());
2039 ASSERT_THAT_ERROR(Read(*V
, std::nullopt
), Succeeded());
2040 ASSERT_EQ((Prefix
+ Content
).str(), StringRef(V
->begin(), V
->size()));
2045 // Check that the chunk size (if specified) is respected.
2046 SmallString
<Content
.size() + 5> SmallChunks
;
2047 ASSERT_THAT_ERROR(Read(SmallChunks
, 5), Succeeded());
2048 ASSERT_EQ(SmallChunks
, Content
);
2049 ASSERT_EQ(Content
.size() + 5, SmallChunks
.capacity());
2052 TEST_F(FileSystemTest
, readNativeFileSlice
) {
2053 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "01234");
2054 FileRemover
Cleanup(NonExistantFile
);
2055 Expected
<fs::file_t
> FD
= fs::openNativeFileForRead(NonExistantFile
);
2056 ASSERT_THAT_EXPECTED(FD
, Succeeded());
2057 auto Close
= make_scope_exit([&] { fs::closeFile(*FD
); });
2058 const auto &Read
= [&](size_t Offset
,
2059 size_t ToRead
) -> Expected
<std::string
> {
2060 std::string
Buf(ToRead
, '?');
2061 if (Expected
<size_t> BytesRead
= fs::readNativeFileSlice(
2062 *FD
, MutableArrayRef(&*Buf
.begin(), Buf
.size()), Offset
))
2063 return Buf
.substr(0, *BytesRead
);
2065 return BytesRead
.takeError();
2067 EXPECT_THAT_EXPECTED(Read(0, 5), HasValue("01234"));
2068 EXPECT_THAT_EXPECTED(Read(0, 3), HasValue("012"));
2069 EXPECT_THAT_EXPECTED(Read(2, 3), HasValue("234"));
2070 EXPECT_THAT_EXPECTED(Read(0, 6), HasValue("01234"));
2071 EXPECT_THAT_EXPECTED(Read(2, 6), HasValue("234"));
2072 EXPECT_THAT_EXPECTED(Read(5, 5), HasValue(""));
2075 TEST_F(FileSystemTest
, is_local
) {
2076 bool TestDirectoryIsLocal
;
2077 ASSERT_NO_ERROR(fs::is_local(TestDirectory
, TestDirectoryIsLocal
));
2078 EXPECT_EQ(TestDirectoryIsLocal
, fs::is_local(TestDirectory
));
2081 SmallString
<128> TempPath
;
2083 fs::createUniqueFile(Twine(TestDirectory
) + "/temp", FD
, TempPath
));
2084 FileRemover
Cleanup(TempPath
);
2086 // Make sure it exists.
2087 ASSERT_TRUE(sys::fs::exists(Twine(TempPath
)));
2089 bool TempFileIsLocal
;
2090 ASSERT_NO_ERROR(fs::is_local(FD
, TempFileIsLocal
));
2091 EXPECT_EQ(TempFileIsLocal
, fs::is_local(FD
));
2094 // Expect that the file and its parent directory are equally local or equally
2096 EXPECT_EQ(TestDirectoryIsLocal
, TempFileIsLocal
);
2099 TEST_F(FileSystemTest
, getUmask
) {
2101 EXPECT_EQ(fs::getUmask(), 0U) << "Should always be 0 on Windows.";
2103 unsigned OldMask
= ::umask(0022);
2104 unsigned CurrentMask
= fs::getUmask();
2105 EXPECT_EQ(CurrentMask
, 0022U)
2106 << "getUmask() didn't return previously set umask()";
2107 EXPECT_EQ(::umask(OldMask
), mode_t(0022U))
2108 << "getUmask() may have changed umask()";
2112 TEST_F(FileSystemTest
, RespectUmask
) {
2114 unsigned OldMask
= ::umask(0022);
2117 SmallString
<128> TempPath
;
2118 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD
, TempPath
));
2120 fs::perms AllRWE
= static_cast<fs::perms
>(0777);
2122 ASSERT_NO_ERROR(fs::setPermissions(TempPath
, AllRWE
));
2124 ErrorOr
<fs::perms
> Perms
= fs::getPermissions(TempPath
);
2125 ASSERT_TRUE(!!Perms
);
2126 EXPECT_EQ(Perms
.get(), AllRWE
) << "Should have ignored umask by default";
2128 ASSERT_NO_ERROR(fs::setPermissions(TempPath
, AllRWE
));
2130 Perms
= fs::getPermissions(TempPath
);
2131 ASSERT_TRUE(!!Perms
);
2132 EXPECT_EQ(Perms
.get(), AllRWE
) << "Should have ignored umask";
2135 fs::setPermissions(FD
, static_cast<fs::perms
>(AllRWE
& ~fs::getUmask())));
2136 Perms
= fs::getPermissions(TempPath
);
2137 ASSERT_TRUE(!!Perms
);
2138 EXPECT_EQ(Perms
.get(), static_cast<fs::perms
>(0755))
2139 << "Did not respect umask";
2141 (void)::umask(0057);
2144 fs::setPermissions(FD
, static_cast<fs::perms
>(AllRWE
& ~fs::getUmask())));
2145 Perms
= fs::getPermissions(TempPath
);
2146 ASSERT_TRUE(!!Perms
);
2147 EXPECT_EQ(Perms
.get(), static_cast<fs::perms
>(0720))
2148 << "Did not respect umask";
2150 (void)::umask(OldMask
);
2155 TEST_F(FileSystemTest
, set_current_path
) {
2156 SmallString
<128> path
;
2158 ASSERT_NO_ERROR(fs::current_path(path
));
2159 ASSERT_NE(TestDirectory
, path
);
2161 struct RestorePath
{
2162 SmallString
<128> path
;
2163 RestorePath(const SmallString
<128> &path
) : path(path
) {}
2164 ~RestorePath() { fs::set_current_path(path
); }
2165 } restore_path(path
);
2167 ASSERT_NO_ERROR(fs::set_current_path(TestDirectory
));
2169 ASSERT_NO_ERROR(fs::current_path(path
));
2171 fs::UniqueID D1
, D2
;
2172 ASSERT_NO_ERROR(fs::getUniqueID(TestDirectory
, D1
));
2173 ASSERT_NO_ERROR(fs::getUniqueID(path
, D2
));
2174 ASSERT_EQ(D1
, D2
) << "D1: " << TestDirectory
<< "\nD2: " << path
;
2177 TEST_F(FileSystemTest
, permissions
) {
2179 SmallString
<64> TempPath
;
2180 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD
, TempPath
));
2181 FileRemover
Cleanup(TempPath
);
2183 // Make sure it exists.
2184 ASSERT_TRUE(fs::exists(Twine(TempPath
)));
2186 auto CheckPermissions
= [&](fs::perms Expected
) {
2187 ErrorOr
<fs::perms
> Actual
= fs::getPermissions(TempPath
);
2188 return Actual
&& *Actual
== Expected
;
2191 std::error_code NoError
;
2192 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_all
), NoError
);
2193 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2195 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_read
| fs::all_exe
), NoError
);
2196 EXPECT_TRUE(CheckPermissions(fs::all_read
| fs::all_exe
));
2199 fs::perms ReadOnly
= fs::all_read
| fs::all_exe
;
2200 EXPECT_EQ(fs::setPermissions(TempPath
, fs::no_perms
), NoError
);
2201 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2203 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_read
), NoError
);
2204 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2206 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_write
), NoError
);
2207 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2209 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_exe
), NoError
);
2210 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2212 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_all
), NoError
);
2213 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2215 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_read
), NoError
);
2216 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2218 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_write
), NoError
);
2219 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2221 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_exe
), NoError
);
2222 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2224 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_all
), NoError
);
2225 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2227 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_read
), NoError
);
2228 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2230 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_write
), NoError
);
2231 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2233 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_exe
), NoError
);
2234 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2236 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_all
), NoError
);
2237 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2239 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_read
), NoError
);
2240 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2242 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_write
), NoError
);
2243 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2245 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_exe
), NoError
);
2246 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2248 EXPECT_EQ(fs::setPermissions(TempPath
, fs::set_uid_on_exe
), NoError
);
2249 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2251 EXPECT_EQ(fs::setPermissions(TempPath
, fs::set_gid_on_exe
), NoError
);
2252 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2254 EXPECT_EQ(fs::setPermissions(TempPath
, fs::sticky_bit
), NoError
);
2255 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2257 EXPECT_EQ(fs::setPermissions(TempPath
, fs::set_uid_on_exe
|
2258 fs::set_gid_on_exe
|
2261 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2263 EXPECT_EQ(fs::setPermissions(TempPath
, ReadOnly
| fs::set_uid_on_exe
|
2264 fs::set_gid_on_exe
|
2267 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2269 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_perms
), NoError
);
2270 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2272 EXPECT_EQ(fs::setPermissions(TempPath
, fs::no_perms
), NoError
);
2273 EXPECT_TRUE(CheckPermissions(fs::no_perms
));
2275 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_read
), NoError
);
2276 EXPECT_TRUE(CheckPermissions(fs::owner_read
));
2278 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_write
), NoError
);
2279 EXPECT_TRUE(CheckPermissions(fs::owner_write
));
2281 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_exe
), NoError
);
2282 EXPECT_TRUE(CheckPermissions(fs::owner_exe
));
2284 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_all
), NoError
);
2285 EXPECT_TRUE(CheckPermissions(fs::owner_all
));
2287 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_read
), NoError
);
2288 EXPECT_TRUE(CheckPermissions(fs::group_read
));
2290 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_write
), NoError
);
2291 EXPECT_TRUE(CheckPermissions(fs::group_write
));
2293 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_exe
), NoError
);
2294 EXPECT_TRUE(CheckPermissions(fs::group_exe
));
2296 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_all
), NoError
);
2297 EXPECT_TRUE(CheckPermissions(fs::group_all
));
2299 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_read
), NoError
);
2300 EXPECT_TRUE(CheckPermissions(fs::others_read
));
2302 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_write
), NoError
);
2303 EXPECT_TRUE(CheckPermissions(fs::others_write
));
2305 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_exe
), NoError
);
2306 EXPECT_TRUE(CheckPermissions(fs::others_exe
));
2308 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_all
), NoError
);
2309 EXPECT_TRUE(CheckPermissions(fs::others_all
));
2311 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_read
), NoError
);
2312 EXPECT_TRUE(CheckPermissions(fs::all_read
));
2314 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_write
), NoError
);
2315 EXPECT_TRUE(CheckPermissions(fs::all_write
));
2317 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_exe
), NoError
);
2318 EXPECT_TRUE(CheckPermissions(fs::all_exe
));
2320 EXPECT_EQ(fs::setPermissions(TempPath
, fs::set_uid_on_exe
), NoError
);
2321 EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe
));
2323 EXPECT_EQ(fs::setPermissions(TempPath
, fs::set_gid_on_exe
), NoError
);
2324 EXPECT_TRUE(CheckPermissions(fs::set_gid_on_exe
));
2326 // Modern BSDs require root to set the sticky bit on files.
2327 // AIX and Solaris without root will mask off (i.e., lose) the sticky bit
2329 #if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
2330 !defined(_AIX) && !(defined(__sun__) && defined(__svr4__))
2331 EXPECT_EQ(fs::setPermissions(TempPath
, fs::sticky_bit
), NoError
);
2332 EXPECT_TRUE(CheckPermissions(fs::sticky_bit
));
2334 EXPECT_EQ(fs::setPermissions(TempPath
, fs::set_uid_on_exe
|
2335 fs::set_gid_on_exe
|
2338 EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe
| fs::set_gid_on_exe
|
2341 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_read
| fs::set_uid_on_exe
|
2342 fs::set_gid_on_exe
|
2345 EXPECT_TRUE(CheckPermissions(fs::all_read
| fs::set_uid_on_exe
|
2346 fs::set_gid_on_exe
| fs::sticky_bit
));
2348 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_perms
), NoError
);
2349 EXPECT_TRUE(CheckPermissions(fs::all_perms
));
2350 #endif // !FreeBSD && !NetBSD && !OpenBSD && !AIX
2352 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_perms
& ~fs::sticky_bit
),
2354 EXPECT_TRUE(CheckPermissions(fs::all_perms
& ~fs::sticky_bit
));
2359 TEST_F(FileSystemTest
, widenPath
) {
2360 const std::wstring
LongPathPrefix(L
"\\\\?\\");
2362 // Test that the length limit is checked against the UTF-16 length and not the
2364 std::string
Input("C:\\foldername\\");
2365 const std::string
Pi("\xcf\x80"); // UTF-8 lower case pi.
2366 // Add Pi up to the MAX_PATH limit.
2367 const size_t NumChars
= MAX_PATH
- Input
.size() - 1;
2368 for (size_t i
= 0; i
< NumChars
; ++i
)
2370 // Check that UTF-8 length already exceeds MAX_PATH.
2371 EXPECT_GT(Input
.size(), (size_t)MAX_PATH
);
2372 SmallVector
<wchar_t, MAX_PATH
+ 16> Result
;
2373 ASSERT_NO_ERROR(windows::widenPath(Input
, Result
));
2374 // Result should not start with the long path prefix.
2375 EXPECT_TRUE(std::wmemcmp(Result
.data(), LongPathPrefix
.c_str(),
2376 LongPathPrefix
.size()) != 0);
2377 EXPECT_EQ(Result
.size(), (size_t)MAX_PATH
- 1);
2379 // Add another Pi to exceed the MAX_PATH limit.
2381 // Construct the expected result.
2382 SmallVector
<wchar_t, MAX_PATH
+ 16> Expected
;
2383 ASSERT_NO_ERROR(windows::UTF8ToUTF16(Input
, Expected
));
2384 Expected
.insert(Expected
.begin(), LongPathPrefix
.begin(),
2385 LongPathPrefix
.end());
2387 ASSERT_NO_ERROR(windows::widenPath(Input
, Result
));
2388 EXPECT_EQ(Result
, Expected
);
2389 // Pass a path with forward slashes, check that it ends up with
2390 // backslashes when widened with the long path prefix.
2391 SmallString
<MAX_PATH
+ 16> InputForward(Input
);
2392 path::make_preferred(InputForward
, path::Style::windows_slash
);
2393 ASSERT_NO_ERROR(windows::widenPath(InputForward
, Result
));
2394 EXPECT_EQ(Result
, Expected
);
2396 // Pass a path which has the long path prefix prepended originally, but
2397 // which is short enough to not require the long path prefix. If such a
2398 // path is passed with forward slashes, make sure it gets normalized to
2400 SmallString
<MAX_PATH
+ 16> PrefixedPath("\\\\?\\C:\\foldername");
2401 ASSERT_NO_ERROR(windows::UTF8ToUTF16(PrefixedPath
, Expected
));
2402 // Mangle the input to forward slashes.
2403 path::make_preferred(PrefixedPath
, path::Style::windows_slash
);
2404 ASSERT_NO_ERROR(windows::widenPath(PrefixedPath
, Result
));
2405 EXPECT_EQ(Result
, Expected
);
2407 // A short path with an inconsistent prefix is passed through as-is; this
2408 // is a degenerate case that we currently don't care about handling.
2409 PrefixedPath
.assign("/\\?/C:/foldername");
2410 ASSERT_NO_ERROR(windows::UTF8ToUTF16(PrefixedPath
, Expected
));
2411 ASSERT_NO_ERROR(windows::widenPath(PrefixedPath
, Result
));
2412 EXPECT_EQ(Result
, Expected
);
2414 // Test that UNC paths are handled correctly.
2415 const std::string
ShareName("\\\\sharename\\");
2416 const std::string
FileName("\\filename");
2417 // Initialize directory name so that the input is within the MAX_PATH limit.
2418 const char DirChar
= 'x';
2419 std::string
DirName(MAX_PATH
- ShareName
.size() - FileName
.size() - 1,
2422 Input
= ShareName
+ DirName
+ FileName
;
2423 ASSERT_NO_ERROR(windows::widenPath(Input
, Result
));
2424 // Result should not start with the long path prefix.
2425 EXPECT_TRUE(std::wmemcmp(Result
.data(), LongPathPrefix
.c_str(),
2426 LongPathPrefix
.size()) != 0);
2427 EXPECT_EQ(Result
.size(), (size_t)MAX_PATH
- 1);
2429 // Extend the directory name so the input exceeds the MAX_PATH limit.
2431 Input
= ShareName
+ DirName
+ FileName
;
2432 // Construct the expected result.
2433 ASSERT_NO_ERROR(windows::UTF8ToUTF16(StringRef(Input
).substr(2), Expected
));
2434 const std::wstring
UNCPrefix(LongPathPrefix
+ L
"UNC\\");
2435 Expected
.insert(Expected
.begin(), UNCPrefix
.begin(), UNCPrefix
.end());
2437 ASSERT_NO_ERROR(windows::widenPath(Input
, Result
));
2438 EXPECT_EQ(Result
, Expected
);
2440 // Check that Unix separators are handled correctly.
2441 std::replace(Input
.begin(), Input
.end(), '\\', '/');
2442 ASSERT_NO_ERROR(windows::widenPath(Input
, Result
));
2443 EXPECT_EQ(Result
, Expected
);
2445 // Check the removal of "dots".
2446 Input
= ShareName
+ DirName
+ "\\.\\foo\\.\\.." + FileName
;
2447 ASSERT_NO_ERROR(windows::widenPath(Input
, Result
));
2448 EXPECT_EQ(Result
, Expected
);
2453 // Windows refuses lock request if file region is already locked by the same
2454 // process. POSIX system in this case updates the existing lock.
2455 TEST_F(FileSystemTest
, FileLocker
) {
2456 using namespace std::chrono
;
2459 SmallString
<64> TempPath
;
2460 EC
= fs::createTemporaryFile("test", "temp", FD
, TempPath
);
2461 ASSERT_NO_ERROR(EC
);
2462 FileRemover
Cleanup(TempPath
);
2463 raw_fd_ostream
Stream(TempPath
, EC
);
2465 EC
= fs::tryLockFile(FD
);
2466 ASSERT_NO_ERROR(EC
);
2467 EC
= fs::unlockFile(FD
);
2468 ASSERT_NO_ERROR(EC
);
2470 if (auto L
= Stream
.lock()) {
2471 ASSERT_ERROR(fs::tryLockFile(FD
));
2472 ASSERT_NO_ERROR(L
->unlock());
2473 ASSERT_NO_ERROR(fs::tryLockFile(FD
));
2474 ASSERT_NO_ERROR(fs::unlockFile(FD
));
2477 handleAllErrors(L
.takeError(), [&](ErrorInfoBase
&EIB
) {});
2480 ASSERT_NO_ERROR(fs::tryLockFile(FD
));
2481 ASSERT_NO_ERROR(fs::unlockFile(FD
));
2484 Expected
<fs::FileLocker
> L1
= Stream
.lock();
2485 ASSERT_THAT_EXPECTED(L1
, Succeeded());
2486 raw_fd_ostream
Stream2(FD
, false);
2487 Expected
<fs::FileLocker
> L2
= Stream2
.tryLockFor(250ms
);
2488 ASSERT_THAT_EXPECTED(L2
, Failed());
2489 ASSERT_NO_ERROR(L1
->unlock());
2490 Expected
<fs::FileLocker
> L3
= Stream
.tryLockFor(0ms
);
2491 ASSERT_THAT_EXPECTED(L3
, Succeeded());
2494 ASSERT_NO_ERROR(fs::tryLockFile(FD
));
2495 ASSERT_NO_ERROR(fs::unlockFile(FD
));
2499 TEST_F(FileSystemTest
, CopyFile
) {
2500 unittest::TempDir
RootTestDirectory("CopyFileTest", /*Unique=*/true);
2502 SmallVector
<std::string
> Data
;
2503 SmallVector
<SmallString
<128>> Sources
;
2504 for (int I
= 0, E
= 3; I
!= E
; ++I
) {
2505 Data
.push_back(Twine(I
).str());
2506 Sources
.emplace_back(RootTestDirectory
.path());
2507 path::append(Sources
.back(), "source" + Data
.back() + ".txt");
2508 createFileWithData(Sources
.back(), /*ShouldExistBefore=*/false,
2509 fs::CD_CreateNew
, Data
.back());
2512 // Copy the first file to a non-existing file.
2513 SmallString
<128> Destination(RootTestDirectory
.path());
2514 path::append(Destination
, "destination");
2515 ASSERT_FALSE(fs::exists(Destination
));
2516 fs::copy_file(Sources
[0], Destination
);
2517 verifyFileContents(Destination
, Data
[0]);
2519 // Copy the second file to an existing file.
2520 fs::copy_file(Sources
[1], Destination
);
2521 verifyFileContents(Destination
, Data
[1]);
2523 // Note: The remaining logic is targeted at a potential failure case related
2524 // to file cloning and symlinks on Darwin. On Windows, fs::create_link() does
2525 // not return success here so the test is skipped.
2526 #if !defined(_WIN32)
2527 // Set up a symlink to the third file.
2528 SmallString
<128> Symlink(RootTestDirectory
.path());
2529 path::append(Symlink
, "symlink");
2530 ASSERT_NO_ERROR(fs::create_link(path::filename(Sources
[2]), Symlink
));
2531 verifyFileContents(Symlink
, Data
[2]);
2533 // fs::getUniqueID() should follow symlinks. Otherwise, this isn't good test
2535 fs::UniqueID SymlinkID
;
2536 fs::UniqueID Data2ID
;
2537 ASSERT_NO_ERROR(fs::getUniqueID(Symlink
, SymlinkID
));
2538 ASSERT_NO_ERROR(fs::getUniqueID(Sources
[2], Data2ID
));
2539 ASSERT_EQ(SymlinkID
, Data2ID
);
2541 // Copy the third file through the symlink.
2542 fs::copy_file(Symlink
, Destination
);
2543 verifyFileContents(Destination
, Data
[2]);
2545 // Confirm the destination is not a link to the original file, and not a
2547 bool IsDestinationSymlink
;
2548 ASSERT_NO_ERROR(fs::is_symlink_file(Destination
, IsDestinationSymlink
));
2549 ASSERT_FALSE(IsDestinationSymlink
);
2550 fs::UniqueID DestinationID
;
2551 ASSERT_NO_ERROR(fs::getUniqueID(Destination
, DestinationID
));
2552 ASSERT_NE(SymlinkID
, DestinationID
);
2556 } // anonymous namespace