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");
194 for (SmallVector
<StringRef
, 40>::const_iterator i
= paths
.begin(),
199 SmallVector
<StringRef
, 5> ComponentStack
;
200 for (sys::path::const_iterator ci
= sys::path::begin(*i
),
201 ce
= sys::path::end(*i
);
204 EXPECT_FALSE(ci
->empty());
205 ComponentStack
.push_back(*ci
);
208 SmallVector
<StringRef
, 5> ReverseComponentStack
;
209 for (sys::path::reverse_iterator ci
= sys::path::rbegin(*i
),
210 ce
= sys::path::rend(*i
);
213 EXPECT_FALSE(ci
->empty());
214 ReverseComponentStack
.push_back(*ci
);
216 std::reverse(ReverseComponentStack
.begin(), ReverseComponentStack
.end());
217 EXPECT_THAT(ComponentStack
, testing::ContainerEq(ReverseComponentStack
));
219 // Crash test most of the API - since we're iterating over all of our paths
220 // here there isn't really anything reasonable to assert on in the results.
221 (void)path::has_root_path(*i
);
222 (void)path::root_path(*i
);
223 (void)path::has_root_name(*i
);
224 (void)path::root_name(*i
);
225 (void)path::has_root_directory(*i
);
226 (void)path::root_directory(*i
);
227 (void)path::has_parent_path(*i
);
228 (void)path::parent_path(*i
);
229 (void)path::has_filename(*i
);
230 (void)path::filename(*i
);
231 (void)path::has_stem(*i
);
232 (void)path::stem(*i
);
233 (void)path::has_extension(*i
);
234 (void)path::extension(*i
);
235 (void)path::is_absolute(*i
);
236 (void)path::is_absolute_gnu(*i
);
237 (void)path::is_relative(*i
);
239 SmallString
<128> temp_store
;
241 ASSERT_NO_ERROR(fs::make_absolute(temp_store
));
243 path::remove_filename(temp_store
);
246 path::replace_extension(temp_store
, "ext");
247 StringRef
filename(temp_store
.begin(), temp_store
.size()), stem
, ext
;
248 stem
= path::stem(filename
);
249 ext
= path::extension(filename
);
250 EXPECT_EQ(*sys::path::rbegin(filename
), (stem
+ ext
).str());
252 path::native(*i
, temp_store
);
256 SmallString
<32> Relative("foo.cpp");
257 sys::fs::make_absolute("/root", Relative
);
258 Relative
[5] = '/'; // Fix up windows paths.
259 ASSERT_EQ("/root/foo.cpp", Relative
);
263 SmallString
<32> Relative("foo.cpp");
264 sys::fs::make_absolute("//root", Relative
);
265 Relative
[6] = '/'; // Fix up windows paths.
266 ASSERT_EQ("//root/foo.cpp", Relative
);
270 TEST(Support
, PathRoot
) {
271 ASSERT_EQ(path::root_name("//net/hello", path::Style::posix
).str(), "//net");
272 ASSERT_EQ(path::root_name("c:/hello", path::Style::posix
).str(), "");
273 ASSERT_EQ(path::root_name("c:/hello", path::Style::windows
).str(), "c:");
274 ASSERT_EQ(path::root_name("/hello", path::Style::posix
).str(), "");
276 ASSERT_EQ(path::root_directory("/goo/hello", path::Style::posix
).str(), "/");
277 ASSERT_EQ(path::root_directory("c:/hello", path::Style::windows
).str(), "/");
278 ASSERT_EQ(path::root_directory("d/file.txt", path::Style::posix
).str(), "");
279 ASSERT_EQ(path::root_directory("d/file.txt", path::Style::windows
).str(), "");
281 SmallVector
<StringRef
, 40> paths
;
283 paths
.push_back(".");
284 paths
.push_back("..");
285 paths
.push_back("foo");
286 paths
.push_back("/");
287 paths
.push_back("/foo");
288 paths
.push_back("foo/");
289 paths
.push_back("/foo/");
290 paths
.push_back("foo/bar");
291 paths
.push_back("/foo/bar");
292 paths
.push_back("//net");
293 paths
.push_back("//net/");
294 paths
.push_back("//net/foo");
295 paths
.push_back("///foo///");
296 paths
.push_back("///foo///bar");
297 paths
.push_back("/.");
298 paths
.push_back("./");
299 paths
.push_back("/..");
300 paths
.push_back("../");
301 paths
.push_back("foo/.");
302 paths
.push_back("foo/..");
303 paths
.push_back("foo/./");
304 paths
.push_back("foo/./bar");
305 paths
.push_back("foo/..");
306 paths
.push_back("foo/../");
307 paths
.push_back("foo/../bar");
308 paths
.push_back("c:");
309 paths
.push_back("c:/");
310 paths
.push_back("c:foo");
311 paths
.push_back("c:/foo");
312 paths
.push_back("c:foo/");
313 paths
.push_back("c:/foo/");
314 paths
.push_back("c:/foo/bar");
315 paths
.push_back("prn:");
316 paths
.push_back("c:\\");
317 paths
.push_back("c:foo");
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\\bar");
324 for (StringRef p
: paths
) {
326 path::root_name(p
, path::Style::posix
).str() + path::root_directory(p
, path::Style::posix
).str(),
327 path::root_path(p
, path::Style::posix
).str());
330 path::root_name(p
, path::Style::windows
).str() + path::root_directory(p
, path::Style::windows
).str(),
331 path::root_path(p
, path::Style::windows
).str());
335 TEST(Support
, FilenameParent
) {
336 EXPECT_EQ("/", path::filename("/"));
337 EXPECT_EQ("", path::parent_path("/"));
339 EXPECT_EQ("\\", path::filename("c:\\", path::Style::windows
));
340 EXPECT_EQ("c:", path::parent_path("c:\\", path::Style::windows
));
342 EXPECT_EQ("/", path::filename("///"));
343 EXPECT_EQ("", path::parent_path("///"));
345 EXPECT_EQ("\\", path::filename("c:\\\\", path::Style::windows
));
346 EXPECT_EQ("c:", path::parent_path("c:\\\\", path::Style::windows
));
348 EXPECT_EQ("bar", path::filename("/foo/bar"));
349 EXPECT_EQ("/foo", path::parent_path("/foo/bar"));
351 EXPECT_EQ("foo", path::filename("/foo"));
352 EXPECT_EQ("/", path::parent_path("/foo"));
354 EXPECT_EQ("foo", path::filename("foo"));
355 EXPECT_EQ("", path::parent_path("foo"));
357 EXPECT_EQ(".", path::filename("foo/"));
358 EXPECT_EQ("foo", path::parent_path("foo/"));
360 EXPECT_EQ("//net", path::filename("//net"));
361 EXPECT_EQ("", path::parent_path("//net"));
363 EXPECT_EQ("/", path::filename("//net/"));
364 EXPECT_EQ("//net", path::parent_path("//net/"));
366 EXPECT_EQ("foo", path::filename("//net/foo"));
367 EXPECT_EQ("//net/", path::parent_path("//net/foo"));
369 // These checks are just to make sure we do something reasonable with the
370 // paths below. They are not meant to prescribe the one true interpretation of
371 // these paths. Other decompositions (e.g. "//" -> "" + "//") are also
373 EXPECT_EQ("/", path::filename("//"));
374 EXPECT_EQ("", path::parent_path("//"));
376 EXPECT_EQ("\\", path::filename("\\\\", path::Style::windows
));
377 EXPECT_EQ("", path::parent_path("\\\\", path::Style::windows
));
379 EXPECT_EQ("\\", path::filename("\\\\\\", path::Style::windows
));
380 EXPECT_EQ("", path::parent_path("\\\\\\", path::Style::windows
));
383 static std::vector
<StringRef
>
384 GetComponents(StringRef Path
, path::Style S
= path::Style::native
) {
385 return {path::begin(Path
, S
), path::end(Path
)};
388 TEST(Support
, PathIterator
) {
389 EXPECT_THAT(GetComponents("/foo"), testing::ElementsAre("/", "foo"));
390 EXPECT_THAT(GetComponents("/"), testing::ElementsAre("/"));
391 EXPECT_THAT(GetComponents("//"), testing::ElementsAre("/"));
392 EXPECT_THAT(GetComponents("///"), testing::ElementsAre("/"));
393 EXPECT_THAT(GetComponents("c/d/e/foo.txt"),
394 testing::ElementsAre("c", "d", "e", "foo.txt"));
395 EXPECT_THAT(GetComponents(".c/.d/../."),
396 testing::ElementsAre(".c", ".d", "..", "."));
397 EXPECT_THAT(GetComponents("/c/d/e/foo.txt"),
398 testing::ElementsAre("/", "c", "d", "e", "foo.txt"));
399 EXPECT_THAT(GetComponents("/.c/.d/../."),
400 testing::ElementsAre("/", ".c", ".d", "..", "."));
401 EXPECT_THAT(GetComponents("c:\\c\\e\\foo.txt", path::Style::windows
),
402 testing::ElementsAre("c:", "\\", "c", "e", "foo.txt"));
403 EXPECT_THAT(GetComponents("c:\\c\\e\\foo.txt", path::Style::windows_slash
),
404 testing::ElementsAre("c:", "\\", "c", "e", "foo.txt"));
405 EXPECT_THAT(GetComponents("//net/"), testing::ElementsAre("//net", "/"));
406 EXPECT_THAT(GetComponents("//net/c/foo.txt"),
407 testing::ElementsAre("//net", "/", "c", "foo.txt"));
410 TEST(Support
, AbsolutePathIteratorEnd
) {
411 // Trailing slashes are converted to '.' unless they are part of the root path.
412 SmallVector
<std::pair
<StringRef
, path::Style
>, 4> Paths
;
413 Paths
.emplace_back("/foo/", path::Style::native
);
414 Paths
.emplace_back("/foo//", path::Style::native
);
415 Paths
.emplace_back("//net/foo/", path::Style::native
);
416 Paths
.emplace_back("c:\\foo\\", path::Style::windows
);
418 for (auto &Path
: Paths
) {
419 SCOPED_TRACE(Path
.first
);
420 StringRef LastComponent
= *path::rbegin(Path
.first
, Path
.second
);
421 EXPECT_EQ(".", LastComponent
);
424 SmallVector
<std::pair
<StringRef
, path::Style
>, 3> RootPaths
;
425 RootPaths
.emplace_back("/", path::Style::native
);
426 RootPaths
.emplace_back("//net/", path::Style::native
);
427 RootPaths
.emplace_back("c:\\", path::Style::windows
);
428 RootPaths
.emplace_back("//net//", path::Style::native
);
429 RootPaths
.emplace_back("c:\\\\", path::Style::windows
);
431 for (auto &Path
: RootPaths
) {
432 SCOPED_TRACE(Path
.first
);
433 StringRef LastComponent
= *path::rbegin(Path
.first
, Path
.second
);
434 EXPECT_EQ(1u, LastComponent
.size());
435 EXPECT_TRUE(path::is_separator(LastComponent
[0], Path
.second
));
440 std::string
getEnvWin(const wchar_t *Var
) {
441 std::string expected
;
442 if (wchar_t const *path
= ::_wgetenv(Var
)) {
443 auto pathLen
= ::wcslen(path
);
444 ArrayRef
<char> ref
{reinterpret_cast<char const *>(path
),
445 pathLen
* sizeof(wchar_t)};
446 convertUTF16ToUTF8String(ref
, expected
);
447 SmallString
<32> Buf(expected
);
448 path::make_preferred(Buf
);
449 expected
.assign(Buf
.begin(), Buf
.end());
454 // RAII helper to set and restore an environment variable.
457 std::optional
<std::string
> OriginalValue
;
460 WithEnv(const char *Var
, const char *Value
) : Var(Var
) {
461 if (const char *V
= ::getenv(Var
))
462 OriginalValue
.emplace(V
);
464 ::setenv(Var
, Value
, 1);
470 ::setenv(Var
, OriginalValue
->c_str(), 1);
477 TEST(Support
, HomeDirectory
) {
478 std::string expected
;
480 expected
= getEnvWin(L
"USERPROFILE");
482 if (char const *path
= ::getenv("HOME"))
485 // Do not try to test it if we don't know what to expect.
486 // On Windows we use something better than env vars.
487 if (expected
.empty())
489 SmallString
<128> HomeDir
;
490 auto status
= path::home_directory(HomeDir
);
492 EXPECT_EQ(expected
, HomeDir
);
495 // Apple has their own solution for this.
496 #if defined(LLVM_ON_UNIX) && !defined(__APPLE__)
497 TEST(Support
, HomeDirectoryWithNoEnv
) {
498 WithEnv
Env("HOME", nullptr);
500 // Don't run the test if we have nothing to compare against.
501 struct passwd
*pw
= getpwuid(getuid());
502 if (!pw
|| !pw
->pw_dir
)
504 std::string PwDir
= pw
->pw_dir
;
506 SmallString
<128> HomeDir
;
507 EXPECT_TRUE(path::home_directory(HomeDir
));
508 EXPECT_EQ(PwDir
, HomeDir
);
511 TEST(Support
, ConfigDirectoryWithEnv
) {
512 WithEnv
Env("XDG_CONFIG_HOME", "/xdg/config");
514 SmallString
<128> ConfigDir
;
515 EXPECT_TRUE(path::user_config_directory(ConfigDir
));
516 EXPECT_EQ("/xdg/config", ConfigDir
);
519 TEST(Support
, ConfigDirectoryNoEnv
) {
520 WithEnv
Env("XDG_CONFIG_HOME", nullptr);
522 SmallString
<128> Fallback
;
523 ASSERT_TRUE(path::home_directory(Fallback
));
524 path::append(Fallback
, ".config");
526 SmallString
<128> CacheDir
;
527 EXPECT_TRUE(path::user_config_directory(CacheDir
));
528 EXPECT_EQ(Fallback
, CacheDir
);
531 TEST(Support
, CacheDirectoryWithEnv
) {
532 WithEnv
Env("XDG_CACHE_HOME", "/xdg/cache");
534 SmallString
<128> CacheDir
;
535 EXPECT_TRUE(path::cache_directory(CacheDir
));
536 EXPECT_EQ("/xdg/cache", CacheDir
);
539 TEST(Support
, CacheDirectoryNoEnv
) {
540 WithEnv
Env("XDG_CACHE_HOME", nullptr);
542 SmallString
<128> Fallback
;
543 ASSERT_TRUE(path::home_directory(Fallback
));
544 path::append(Fallback
, ".cache");
546 SmallString
<128> CacheDir
;
547 EXPECT_TRUE(path::cache_directory(CacheDir
));
548 EXPECT_EQ(Fallback
, CacheDir
);
553 TEST(Support
, ConfigDirectory
) {
554 SmallString
<128> Fallback
;
555 ASSERT_TRUE(path::home_directory(Fallback
));
556 path::append(Fallback
, "Library/Preferences");
558 SmallString
<128> ConfigDir
;
559 EXPECT_TRUE(path::user_config_directory(ConfigDir
));
560 EXPECT_EQ(Fallback
, ConfigDir
);
565 TEST(Support
, ConfigDirectory
) {
566 std::string Expected
= getEnvWin(L
"LOCALAPPDATA");
567 // Do not try to test it if we don't know what to expect.
568 if (Expected
.empty())
570 SmallString
<128> CacheDir
;
571 EXPECT_TRUE(path::user_config_directory(CacheDir
));
572 EXPECT_EQ(Expected
, CacheDir
);
575 TEST(Support
, CacheDirectory
) {
576 std::string Expected
= getEnvWin(L
"LOCALAPPDATA");
577 // Do not try to test it if we don't know what to expect.
578 if (Expected
.empty())
580 SmallString
<128> CacheDir
;
581 EXPECT_TRUE(path::cache_directory(CacheDir
));
582 EXPECT_EQ(Expected
, CacheDir
);
586 TEST(Support
, TempDirectory
) {
587 SmallString
<32> TempDir
;
588 path::system_temp_directory(false, TempDir
);
589 EXPECT_TRUE(!TempDir
.empty());
591 path::system_temp_directory(true, TempDir
);
592 EXPECT_TRUE(!TempDir
.empty());
596 static std::string
path2regex(std::string Path
) {
598 bool Forward
= path::get_separator()[0] == '/';
599 while ((Pos
= Path
.find('\\', Pos
)) != std::string::npos
) {
601 Path
.replace(Pos
, 1, "/");
604 Path
.replace(Pos
, 1, "\\\\");
611 /// Helper for running temp dir test in separated process. See below.
612 #define EXPECT_TEMP_DIR(prepare, expected) \
616 SmallString<300> TempDir; \
617 path::system_temp_directory(true, TempDir); \
618 raw_os_ostream(std::cerr) << TempDir; \
621 ::testing::ExitedWithCode(0), path2regex(expected))
623 TEST(SupportDeathTest
, TempDirectoryOnWindows
) {
624 // In this test we want to check how system_temp_directory responds to
625 // different values of specific env vars. To prevent corrupting env vars of
626 // the current process all checks are done in separated processes.
627 EXPECT_TEMP_DIR(_wputenv_s(L
"TMP", L
"C:\\OtherFolder"), "C:\\OtherFolder");
628 EXPECT_TEMP_DIR(_wputenv_s(L
"TMP", L
"C:/Unix/Path/Seperators"),
629 "C:\\Unix\\Path\\Seperators");
630 EXPECT_TEMP_DIR(_wputenv_s(L
"TMP", L
"Local Path"), ".+\\Local Path$");
631 EXPECT_TEMP_DIR(_wputenv_s(L
"TMP", L
"F:\\TrailingSep\\"), "F:\\TrailingSep");
633 _wputenv_s(L
"TMP", L
"C:\\2\x03C0r-\x00B5\x00B3\\\x2135\x2080"),
634 "C:\\2\xCF\x80r-\xC2\xB5\xC2\xB3\\\xE2\x84\xB5\xE2\x82\x80");
636 // Test $TMP empty, $TEMP set.
639 _wputenv_s(L
"TMP", L
"");
640 _wputenv_s(L
"TEMP", L
"C:\\Valid\\Path");
644 // All related env vars empty
647 _wputenv_s(L
"TMP", L
"");
648 _wputenv_s(L
"TEMP", L
"");
649 _wputenv_s(L
"USERPROFILE", L
"");
653 // Test evn var / path with 260 chars.
654 SmallString
<270> Expected
{"C:\\Temp\\AB\\123456789"};
655 while (Expected
.size() < 260)
656 Expected
.append("\\DirNameWith19Charss");
657 ASSERT_EQ(260U, Expected
.size());
658 EXPECT_TEMP_DIR(_putenv_s("TMP", Expected
.c_str()), Expected
.c_str());
662 class FileSystemTest
: public testing::Test
{
664 /// Unique temporary directory in which all created filesystem entities must
665 /// be placed. It is removed at the end of each test (must be empty).
666 SmallString
<128> TestDirectory
;
667 SmallString
<128> NonExistantFile
;
669 void SetUp() override
{
671 fs::createUniqueDirectory("file-system-test", TestDirectory
));
672 // We don't care about this specific file.
673 errs() << "Test Directory: " << TestDirectory
<< '\n';
675 NonExistantFile
= TestDirectory
;
677 // Even though this value is hardcoded, is a 128-bit GUID, so we should be
678 // guaranteed that this file will never exist.
679 sys::path::append(NonExistantFile
, "1B28B495C16344CB9822E588CD4C3EF0");
682 void TearDown() override
{ ASSERT_NO_ERROR(fs::remove(TestDirectory
.str())); }
685 TEST_F(FileSystemTest
, Unique
) {
686 // Create a temp file.
688 SmallString
<64> TempPath
;
690 fs::createTemporaryFile("prefix", "temp", FileDescriptor
, TempPath
));
692 // The same file should return an identical unique id.
694 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath
), F1
));
695 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath
), F2
));
698 // Different files should return different unique ids.
700 SmallString
<64> TempPath2
;
702 fs::createTemporaryFile("prefix", "temp", FileDescriptor2
, TempPath2
));
705 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2
), D
));
707 ::close(FileDescriptor2
);
709 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2
)));
712 // Two paths representing the same file on disk should still provide the
713 // same unique id. We can test this by making a hard link.
714 // FIXME: Our implementation of getUniqueID on Windows doesn't consider hard
715 // links to be the same file.
716 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath
), Twine(TempPath2
)));
718 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2
), D2
));
722 ::close(FileDescriptor
);
724 SmallString
<128> Dir1
;
726 fs::createUniqueDirectory("dir1", Dir1
));
727 ASSERT_NO_ERROR(fs::getUniqueID(Dir1
.c_str(), F1
));
728 ASSERT_NO_ERROR(fs::getUniqueID(Dir1
.c_str(), F2
));
731 SmallString
<128> Dir2
;
733 fs::createUniqueDirectory("dir2", Dir2
));
734 ASSERT_NO_ERROR(fs::getUniqueID(Dir2
.c_str(), F2
));
736 ASSERT_NO_ERROR(fs::remove(Dir1
));
737 ASSERT_NO_ERROR(fs::remove(Dir2
));
738 ASSERT_NO_ERROR(fs::remove(TempPath2
));
739 ASSERT_NO_ERROR(fs::remove(TempPath
));
742 TEST_F(FileSystemTest
, RealPath
) {
744 fs::create_directories(Twine(TestDirectory
) + "/test1/test2/test3"));
745 ASSERT_TRUE(fs::exists(Twine(TestDirectory
) + "/test1/test2/test3"));
747 SmallString
<64> RealBase
;
748 SmallString
<64> Expected
;
749 SmallString
<64> Actual
;
751 // TestDirectory itself might be under a symlink or have been specified with
752 // a different case than the existing temp directory. In such cases real_path
753 // on the concatenated path will differ in the TestDirectory portion from
754 // how we specified it. Make sure to compare against the real_path of the
755 // TestDirectory, and not just the value of TestDirectory.
756 ASSERT_NO_ERROR(fs::real_path(TestDirectory
, RealBase
));
757 checkSeparators(RealBase
);
758 path::native(Twine(RealBase
) + "/test1/test2", Expected
);
760 ASSERT_NO_ERROR(fs::real_path(
761 Twine(TestDirectory
) + "/././test1/../test1/test2/./test3/..", Actual
));
762 checkSeparators(Actual
);
764 EXPECT_EQ(Expected
, Actual
);
766 SmallString
<64> HomeDir
;
768 // This can fail if $HOME is not set and getpwuid fails.
769 bool Result
= llvm::sys::path::home_directory(HomeDir
);
771 checkSeparators(HomeDir
);
772 ASSERT_NO_ERROR(fs::real_path(HomeDir
, Expected
));
773 checkSeparators(Expected
);
774 ASSERT_NO_ERROR(fs::real_path("~", Actual
, true));
775 EXPECT_EQ(Expected
, Actual
);
776 ASSERT_NO_ERROR(fs::real_path("~/", Actual
, true));
777 EXPECT_EQ(Expected
, Actual
);
780 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory
) + "/test1"));
783 TEST_F(FileSystemTest
, ExpandTilde
) {
784 SmallString
<64> Expected
;
785 SmallString
<64> Actual
;
786 SmallString
<64> HomeDir
;
788 // This can fail if $HOME is not set and getpwuid fails.
789 bool Result
= llvm::sys::path::home_directory(HomeDir
);
791 fs::expand_tilde(HomeDir
, Expected
);
793 fs::expand_tilde("~", Actual
);
794 EXPECT_EQ(Expected
, Actual
);
798 fs::expand_tilde("~\\foo", Actual
);
801 fs::expand_tilde("~/foo", Actual
);
804 EXPECT_EQ(Expected
, Actual
);
809 TEST_F(FileSystemTest
, RealPathNoReadPerm
) {
810 SmallString
<64> Expanded
;
813 fs::create_directories(Twine(TestDirectory
) + "/noreadperm"));
814 ASSERT_TRUE(fs::exists(Twine(TestDirectory
) + "/noreadperm"));
816 fs::setPermissions(Twine(TestDirectory
) + "/noreadperm", fs::no_perms
);
817 fs::setPermissions(Twine(TestDirectory
) + "/noreadperm", fs::all_exe
);
819 ASSERT_NO_ERROR(fs::real_path(Twine(TestDirectory
) + "/noreadperm", Expanded
,
822 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory
) + "/noreadperm"));
824 TEST_F(FileSystemTest
, RemoveDirectoriesNoExePerm
) {
825 SmallString
<64> Expanded
;
828 fs::create_directories(Twine(TestDirectory
) + "/noexeperm/foo"));
829 ASSERT_TRUE(fs::exists(Twine(TestDirectory
) + "/noexeperm/foo"));
831 fs::setPermissions(Twine(TestDirectory
) + "/noexeperm",
832 fs::all_read
| fs::all_write
);
834 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory
) + "/noexeperm",
835 /*IgnoreErrors=*/true));
837 // It's expected that the directory exists, but some environments appear to
838 // allow the removal despite missing the 'x' permission, so be flexible.
839 if (fs::exists(Twine(TestDirectory
) + "/noexeperm")) {
840 fs::setPermissions(Twine(TestDirectory
) + "/noexeperm", fs::all_perms
);
841 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory
) + "/noexeperm",
842 /*IgnoreErrors=*/false));
848 TEST_F(FileSystemTest
, TempFileKeepDiscard
) {
849 // We can keep then discard.
850 auto TempFileOrError
= fs::TempFile::create(TestDirectory
+ "/test-%%%%");
851 ASSERT_TRUE((bool)TempFileOrError
);
852 fs::TempFile File
= std::move(*TempFileOrError
);
853 ASSERT_EQ(-1, TempFileOrError
->FD
);
854 ASSERT_FALSE((bool)File
.keep(TestDirectory
+ "/keep"));
855 ASSERT_FALSE((bool)File
.discard());
856 ASSERT_TRUE(fs::exists(TestDirectory
+ "/keep"));
857 ASSERT_NO_ERROR(fs::remove(TestDirectory
+ "/keep"));
860 TEST_F(FileSystemTest
, TempFileDiscardDiscard
) {
861 // We can discard twice.
862 auto TempFileOrError
= fs::TempFile::create(TestDirectory
+ "/test-%%%%");
863 ASSERT_TRUE((bool)TempFileOrError
);
864 fs::TempFile File
= std::move(*TempFileOrError
);
865 ASSERT_EQ(-1, TempFileOrError
->FD
);
866 ASSERT_FALSE((bool)File
.discard());
867 ASSERT_FALSE((bool)File
.discard());
868 ASSERT_FALSE(fs::exists(TestDirectory
+ "/keep"));
871 TEST_F(FileSystemTest
, TempFiles
) {
872 // Create a temp file.
874 SmallString
<64> TempPath
;
876 fs::createTemporaryFile("prefix", "temp", FileDescriptor
, TempPath
));
878 // Make sure it exists.
879 ASSERT_TRUE(sys::fs::exists(Twine(TempPath
)));
881 // Create another temp tile.
883 SmallString
<64> TempPath2
;
884 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD2
, TempPath2
));
885 ASSERT_TRUE(TempPath2
.endswith(".temp"));
886 ASSERT_NE(TempPath
.str(), TempPath2
.str());
888 fs::file_status A
, B
;
889 ASSERT_NO_ERROR(fs::status(Twine(TempPath
), A
));
890 ASSERT_NO_ERROR(fs::status(Twine(TempPath2
), B
));
891 EXPECT_FALSE(fs::equivalent(A
, B
));
896 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2
)));
897 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2
)));
898 ASSERT_EQ(fs::remove(Twine(TempPath2
), false),
899 errc::no_such_file_or_directory
);
901 std::error_code EC
= fs::status(TempPath2
.c_str(), B
);
902 EXPECT_EQ(EC
, errc::no_such_file_or_directory
);
903 EXPECT_EQ(B
.type(), fs::file_type::file_not_found
);
905 // Make sure Temp2 doesn't exist.
906 ASSERT_EQ(fs::access(Twine(TempPath2
), sys::fs::AccessMode::Exist
),
907 errc::no_such_file_or_directory
);
909 SmallString
<64> TempPath3
;
910 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "", TempPath3
));
911 ASSERT_FALSE(TempPath3
.endswith("."));
912 FileRemover
Cleanup3(TempPath3
);
914 // Create a hard link to Temp1.
915 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath
), Twine(TempPath2
)));
917 // FIXME: Our implementation of equivalent() on Windows doesn't consider hard
918 // links to be the same file.
920 ASSERT_NO_ERROR(fs::equivalent(Twine(TempPath
), Twine(TempPath2
), equal
));
922 ASSERT_NO_ERROR(fs::status(Twine(TempPath
), A
));
923 ASSERT_NO_ERROR(fs::status(Twine(TempPath2
), B
));
924 EXPECT_TRUE(fs::equivalent(A
, B
));
928 ::close(FileDescriptor
);
929 ASSERT_NO_ERROR(fs::remove(Twine(TempPath
)));
931 // Remove the hard link.
932 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2
)));
934 // Make sure Temp1 doesn't exist.
935 ASSERT_EQ(fs::access(Twine(TempPath
), sys::fs::AccessMode::Exist
),
936 errc::no_such_file_or_directory
);
939 // Path name > 260 chars should get an error.
940 const char *Path270
=
941 "abcdefghijklmnopqrstuvwxyz9abcdefghijklmnopqrstuvwxyz8"
942 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
943 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
944 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
945 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
946 EXPECT_EQ(fs::createUniqueFile(Path270
, FileDescriptor
, TempPath
),
947 errc::invalid_argument
);
948 // Relative path < 247 chars, no problem.
949 const char *Path216
=
950 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
951 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
952 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
953 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
954 ASSERT_NO_ERROR(fs::createTemporaryFile(Path216
, "", TempPath
));
955 ASSERT_NO_ERROR(fs::remove(Twine(TempPath
)));
959 TEST_F(FileSystemTest
, TempFileCollisions
) {
960 SmallString
<128> TestDirectory
;
962 fs::createUniqueDirectory("CreateUniqueFileTest", TestDirectory
));
963 FileRemover
Cleanup(TestDirectory
);
964 SmallString
<128> Model
= TestDirectory
;
965 path::append(Model
, "%.tmp");
966 SmallString
<128> Path
;
967 std::vector
<fs::TempFile
> TempFiles
;
969 auto TryCreateTempFile
= [&]() {
970 Expected
<fs::TempFile
> T
= fs::TempFile::create(Model
);
972 TempFiles
.push_back(std::move(*T
));
975 logAllUnhandledErrors(T
.takeError(), errs(),
976 "Failed to create temporary file: ");
981 // Our single-character template allows for 16 unique names. Check that
982 // calling TryCreateTempFile repeatedly results in 16 successes.
983 // Because the test depends on random numbers, it could theoretically fail.
984 // However, the probability of this happening is tiny: with 32 calls, each
985 // of which will retry up to 128 times, to not get a given digit we would
986 // have to fail at least 15 + 17 * 128 = 2191 attempts. The probability of
987 // 2191 attempts not producing a given hexadecimal digit is
988 // (1 - 1/16) ** 2191 or 3.88e-62.
990 for (int i
= 0; i
< 32; ++i
)
991 if (TryCreateTempFile()) ++Successes
;
992 EXPECT_EQ(Successes
, 16);
994 for (fs::TempFile
&T
: TempFiles
)
995 cantFail(T
.discard());
998 TEST_F(FileSystemTest
, CreateDir
) {
999 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory
) + "foo"));
1000 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory
) + "foo"));
1001 ASSERT_EQ(fs::create_directory(Twine(TestDirectory
) + "foo", false),
1003 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "foo"));
1006 // Set a 0000 umask so that we can test our directory permissions.
1007 mode_t OldUmask
= ::umask(0000);
1009 fs::file_status Status
;
1011 fs::create_directory(Twine(TestDirectory
) + "baz500", false,
1012 fs::perms::owner_read
| fs::perms::owner_exe
));
1013 ASSERT_NO_ERROR(fs::status(Twine(TestDirectory
) + "baz500", Status
));
1014 ASSERT_EQ(Status
.permissions() & fs::perms::all_all
,
1015 fs::perms::owner_read
| fs::perms::owner_exe
);
1016 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory
) + "baz777", false,
1017 fs::perms::all_all
));
1018 ASSERT_NO_ERROR(fs::status(Twine(TestDirectory
) + "baz777", Status
));
1019 ASSERT_EQ(Status
.permissions() & fs::perms::all_all
, fs::perms::all_all
);
1021 // Restore umask to be safe.
1026 // Prove that create_directories() can handle a pathname > 248 characters,
1027 // which is the documented limit for CreateDirectory().
1028 // (248 is MAX_PATH subtracting room for an 8.3 filename.)
1029 // Generate a directory path guaranteed to fall into that range.
1030 size_t TmpLen
= TestDirectory
.size();
1031 const char *OneDir
= "\\123456789";
1032 size_t OneDirLen
= strlen(OneDir
);
1033 ASSERT_LT(OneDirLen
, 12U);
1034 size_t NLevels
= ((248 - TmpLen
) / OneDirLen
) + 1;
1035 SmallString
<260> LongDir(TestDirectory
);
1036 for (size_t I
= 0; I
< NLevels
; ++I
)
1037 LongDir
.append(OneDir
);
1038 ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir
)));
1039 ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir
)));
1040 ASSERT_EQ(fs::create_directories(Twine(LongDir
), false),
1042 // Tidy up, "recursively" removing the directories.
1043 StringRef
ThisDir(LongDir
);
1044 for (size_t J
= 0; J
< NLevels
; ++J
) {
1045 ASSERT_NO_ERROR(fs::remove(ThisDir
));
1046 ThisDir
= path::parent_path(ThisDir
);
1049 // Also verify that paths with Unix separators are handled correctly.
1050 std::string
LongPathWithUnixSeparators(TestDirectory
.str());
1051 // Add at least one subdirectory to TestDirectory, and replace slashes with
1054 LongPathWithUnixSeparators
.append("/DirNameWith19Charss");
1055 } while (LongPathWithUnixSeparators
.size() < 260);
1056 std::replace(LongPathWithUnixSeparators
.begin(),
1057 LongPathWithUnixSeparators
.end(),
1059 ASSERT_NO_ERROR(fs::create_directories(Twine(LongPathWithUnixSeparators
)));
1061 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory
) +
1062 "/DirNameWith19Charss"));
1064 // Similarly for a relative pathname. Need to set the current directory to
1065 // TestDirectory so that the one we create ends up in the right place.
1066 char PreviousDir
[260];
1067 size_t PreviousDirLen
= ::GetCurrentDirectoryA(260, PreviousDir
);
1068 ASSERT_GT(PreviousDirLen
, 0U);
1069 ASSERT_LT(PreviousDirLen
, 260U);
1070 ASSERT_NE(::SetCurrentDirectoryA(TestDirectory
.c_str()), 0);
1072 // Generate a relative directory name with absolute length > 248.
1073 size_t LongDirLen
= 249 - TestDirectory
.size();
1074 LongDir
.assign(LongDirLen
, 'a');
1075 ASSERT_NO_ERROR(fs::create_directory(Twine(LongDir
)));
1076 // While we're here, prove that .. and . handling works in these long paths.
1077 const char *DotDotDirs
= "\\..\\.\\b";
1078 LongDir
.append(DotDotDirs
);
1079 ASSERT_NO_ERROR(fs::create_directory("b"));
1080 ASSERT_EQ(fs::create_directory(Twine(LongDir
), false), errc::file_exists
);
1082 ASSERT_NO_ERROR(fs::remove("b"));
1083 ASSERT_NO_ERROR(fs::remove(
1084 Twine(LongDir
.substr(0, LongDir
.size() - strlen(DotDotDirs
)))));
1085 ASSERT_NE(::SetCurrentDirectoryA(PreviousDir
), 0);
1089 TEST_F(FileSystemTest
, DirectoryIteration
) {
1091 for (fs::directory_iterator
i(".", ec
), e
; i
!= e
; i
.increment(ec
))
1092 ASSERT_NO_ERROR(ec
);
1094 // Create a known hierarchy to recurse over.
1096 fs::create_directories(Twine(TestDirectory
) + "/recursive/a0/aa1"));
1098 fs::create_directories(Twine(TestDirectory
) + "/recursive/a0/ab1"));
1099 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory
) +
1100 "/recursive/dontlookhere/da1"));
1102 fs::create_directories(Twine(TestDirectory
) + "/recursive/z0/za1"));
1104 fs::create_directories(Twine(TestDirectory
) + "/recursive/pop/p1"));
1105 typedef std::vector
<std::string
> v_t
;
1107 for (fs::recursive_directory_iterator
i(Twine(TestDirectory
)
1108 + "/recursive", ec
), e
; i
!= e
; i
.increment(ec
)){
1109 ASSERT_NO_ERROR(ec
);
1110 if (path::filename(i
->path()) == "p1") {
1112 // FIXME: recursive_directory_iterator should be more robust.
1115 if (path::filename(i
->path()) == "dontlookhere")
1117 visited
.push_back(std::string(path::filename(i
->path())));
1119 v_t::const_iterator a0
= find(visited
, "a0");
1120 v_t::const_iterator aa1
= find(visited
, "aa1");
1121 v_t::const_iterator ab1
= find(visited
, "ab1");
1122 v_t::const_iterator dontlookhere
= find(visited
, "dontlookhere");
1123 v_t::const_iterator da1
= find(visited
, "da1");
1124 v_t::const_iterator z0
= find(visited
, "z0");
1125 v_t::const_iterator za1
= find(visited
, "za1");
1126 v_t::const_iterator pop
= find(visited
, "pop");
1127 v_t::const_iterator p1
= find(visited
, "p1");
1129 // Make sure that each path was visited correctly.
1130 ASSERT_NE(a0
, visited
.end());
1131 ASSERT_NE(aa1
, visited
.end());
1132 ASSERT_NE(ab1
, visited
.end());
1133 ASSERT_NE(dontlookhere
, visited
.end());
1134 ASSERT_EQ(da1
, visited
.end()); // Not visited.
1135 ASSERT_NE(z0
, visited
.end());
1136 ASSERT_NE(za1
, visited
.end());
1137 ASSERT_NE(pop
, visited
.end());
1138 ASSERT_EQ(p1
, visited
.end()); // Not visited.
1140 // Make sure that parents were visited before children. No other ordering
1141 // guarantees can be made across siblings.
1146 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/a0/aa1"));
1147 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/a0/ab1"));
1148 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/a0"));
1150 fs::remove(Twine(TestDirectory
) + "/recursive/dontlookhere/da1"));
1151 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/dontlookhere"));
1152 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/pop/p1"));
1153 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/pop"));
1154 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/z0/za1"));
1155 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/z0"));
1156 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive"));
1158 // Test recursive_directory_iterator level()
1160 fs::create_directories(Twine(TestDirectory
) + "/reclevel/a/b/c"));
1161 fs::recursive_directory_iterator
I(Twine(TestDirectory
) + "/reclevel", ec
), E
;
1162 for (int l
= 0; I
!= E
; I
.increment(ec
), ++l
) {
1163 ASSERT_NO_ERROR(ec
);
1164 EXPECT_EQ(I
.level(), l
);
1167 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/reclevel/a/b/c"));
1168 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/reclevel/a/b"));
1169 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/reclevel/a"));
1170 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/reclevel"));
1173 TEST_F(FileSystemTest
, DirectoryNotExecutable
) {
1174 ASSERT_EQ(fs::access(TestDirectory
, sys::fs::AccessMode::Execute
),
1175 errc::permission_denied
);
1179 TEST_F(FileSystemTest
, BrokenSymlinkDirectoryIteration
) {
1180 // Create a known hierarchy to recurse over.
1181 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory
) + "/symlink"));
1183 fs::create_link("no_such_file", Twine(TestDirectory
) + "/symlink/a"));
1185 fs::create_directories(Twine(TestDirectory
) + "/symlink/b/bb"));
1187 fs::create_link("no_such_file", Twine(TestDirectory
) + "/symlink/b/ba"));
1189 fs::create_link("no_such_file", Twine(TestDirectory
) + "/symlink/b/bc"));
1191 fs::create_link("no_such_file", Twine(TestDirectory
) + "/symlink/c"));
1193 fs::create_directories(Twine(TestDirectory
) + "/symlink/d/dd/ddd"));
1194 ASSERT_NO_ERROR(fs::create_link(Twine(TestDirectory
) + "/symlink/d/dd",
1195 Twine(TestDirectory
) + "/symlink/d/da"));
1197 fs::create_link("no_such_file", Twine(TestDirectory
) + "/symlink/e"));
1199 typedef std::vector
<std::string
> v_t
;
1200 v_t VisitedNonBrokenSymlinks
;
1201 v_t VisitedBrokenSymlinks
;
1203 using testing::UnorderedElementsAre
;
1204 using testing::UnorderedElementsAreArray
;
1206 // Broken symbol links are expected to throw an error.
1207 for (fs::directory_iterator
i(Twine(TestDirectory
) + "/symlink", ec
), e
;
1208 i
!= e
; i
.increment(ec
)) {
1209 ASSERT_NO_ERROR(ec
);
1210 if (i
->status().getError() ==
1211 std::make_error_code(std::errc::no_such_file_or_directory
)) {
1212 VisitedBrokenSymlinks
.push_back(std::string(path::filename(i
->path())));
1215 VisitedNonBrokenSymlinks
.push_back(std::string(path::filename(i
->path())));
1217 EXPECT_THAT(VisitedNonBrokenSymlinks
, UnorderedElementsAre("b", "d"));
1218 VisitedNonBrokenSymlinks
.clear();
1220 EXPECT_THAT(VisitedBrokenSymlinks
, UnorderedElementsAre("a", "c", "e"));
1221 VisitedBrokenSymlinks
.clear();
1223 // Broken symbol links are expected to throw an error.
1224 for (fs::recursive_directory_iterator
i(
1225 Twine(TestDirectory
) + "/symlink", ec
), e
; i
!= e
; i
.increment(ec
)) {
1226 ASSERT_NO_ERROR(ec
);
1227 if (i
->status().getError() ==
1228 std::make_error_code(std::errc::no_such_file_or_directory
)) {
1229 VisitedBrokenSymlinks
.push_back(std::string(path::filename(i
->path())));
1232 VisitedNonBrokenSymlinks
.push_back(std::string(path::filename(i
->path())));
1234 EXPECT_THAT(VisitedNonBrokenSymlinks
,
1235 UnorderedElementsAre("b", "bb", "d", "da", "dd", "ddd", "ddd"));
1236 VisitedNonBrokenSymlinks
.clear();
1238 EXPECT_THAT(VisitedBrokenSymlinks
,
1239 UnorderedElementsAre("a", "ba", "bc", "c", "e"));
1240 VisitedBrokenSymlinks
.clear();
1242 for (fs::recursive_directory_iterator
i(
1243 Twine(TestDirectory
) + "/symlink", ec
, /*follow_symlinks=*/false), e
;
1244 i
!= e
; i
.increment(ec
)) {
1245 ASSERT_NO_ERROR(ec
);
1246 if (i
->status().getError() ==
1247 std::make_error_code(std::errc::no_such_file_or_directory
)) {
1248 VisitedBrokenSymlinks
.push_back(std::string(path::filename(i
->path())));
1251 VisitedNonBrokenSymlinks
.push_back(std::string(path::filename(i
->path())));
1253 EXPECT_THAT(VisitedNonBrokenSymlinks
,
1254 UnorderedElementsAreArray({"a", "b", "ba", "bb", "bc", "c", "d",
1255 "da", "dd", "ddd", "e"}));
1256 VisitedNonBrokenSymlinks
.clear();
1258 EXPECT_THAT(VisitedBrokenSymlinks
, UnorderedElementsAre());
1259 VisitedBrokenSymlinks
.clear();
1261 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory
) + "/symlink"));
1266 TEST_F(FileSystemTest
, UTF8ToUTF16DirectoryIteration
) {
1267 // The Windows filesystem support uses UTF-16 and converts paths from the
1268 // input UTF-8. The UTF-16 equivalent of the input path can be shorter in
1271 // This test relies on TestDirectory not being so long such that MAX_PATH
1272 // would be exceeded (see widenPath). If that were the case, the UTF-16
1273 // path is likely to be longer than the input.
1274 const char *Pi
= "\xcf\x80"; // UTF-8 lower case pi.
1275 std::string RootDir
= (TestDirectory
+ "/" + Pi
).str();
1277 // Create test directories.
1278 ASSERT_NO_ERROR(fs::create_directories(Twine(RootDir
) + "/a"));
1279 ASSERT_NO_ERROR(fs::create_directories(Twine(RootDir
) + "/b"));
1283 for (fs::directory_iterator
I(Twine(RootDir
), EC
), E
; I
!= E
;
1285 ASSERT_NO_ERROR(EC
);
1286 StringRef DirName
= path::filename(I
->path());
1287 EXPECT_TRUE(DirName
== "a" || DirName
== "b");
1290 EXPECT_EQ(Count
, 2U);
1292 ASSERT_NO_ERROR(fs::remove(Twine(RootDir
) + "/a"));
1293 ASSERT_NO_ERROR(fs::remove(Twine(RootDir
) + "/b"));
1294 ASSERT_NO_ERROR(fs::remove(Twine(RootDir
)));
1298 TEST_F(FileSystemTest
, Remove
) {
1299 SmallString
<64> BaseDir
;
1300 SmallString
<64> Paths
[4];
1302 ASSERT_NO_ERROR(fs::createUniqueDirectory("fs_remove", BaseDir
));
1304 ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir
) + "/foo/bar/baz"));
1305 ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir
) + "/foo/bar/buzz"));
1306 ASSERT_NO_ERROR(fs::createUniqueFile(
1307 Twine(BaseDir
) + "/foo/bar/baz/%%%%%%.tmp", fds
[0], Paths
[0]));
1308 ASSERT_NO_ERROR(fs::createUniqueFile(
1309 Twine(BaseDir
) + "/foo/bar/baz/%%%%%%.tmp", fds
[1], Paths
[1]));
1310 ASSERT_NO_ERROR(fs::createUniqueFile(
1311 Twine(BaseDir
) + "/foo/bar/buzz/%%%%%%.tmp", fds
[2], Paths
[2]));
1312 ASSERT_NO_ERROR(fs::createUniqueFile(
1313 Twine(BaseDir
) + "/foo/bar/buzz/%%%%%%.tmp", fds
[3], Paths
[3]));
1318 EXPECT_TRUE(fs::exists(Twine(BaseDir
) + "/foo/bar/baz"));
1319 EXPECT_TRUE(fs::exists(Twine(BaseDir
) + "/foo/bar/buzz"));
1320 EXPECT_TRUE(fs::exists(Paths
[0]));
1321 EXPECT_TRUE(fs::exists(Paths
[1]));
1322 EXPECT_TRUE(fs::exists(Paths
[2]));
1323 EXPECT_TRUE(fs::exists(Paths
[3]));
1325 ASSERT_NO_ERROR(fs::remove_directories("D:/footest"));
1327 ASSERT_NO_ERROR(fs::remove_directories(BaseDir
));
1328 ASSERT_FALSE(fs::exists(BaseDir
));
1332 TEST_F(FileSystemTest
, CarriageReturn
) {
1333 SmallString
<128> FilePathname(TestDirectory
);
1335 path::append(FilePathname
, "test");
1338 raw_fd_ostream
File(FilePathname
, EC
, sys::fs::OF_TextWithCRLF
);
1339 ASSERT_NO_ERROR(EC
);
1343 auto Buf
= MemoryBuffer::getFile(FilePathname
.str());
1344 EXPECT_TRUE((bool)Buf
);
1345 EXPECT_EQ(Buf
.get()->getBuffer(), "\r\n");
1349 raw_fd_ostream
File(FilePathname
, EC
, sys::fs::OF_None
);
1350 ASSERT_NO_ERROR(EC
);
1354 auto Buf
= MemoryBuffer::getFile(FilePathname
.str());
1355 EXPECT_TRUE((bool)Buf
);
1356 EXPECT_EQ(Buf
.get()->getBuffer(), "\n");
1358 ASSERT_NO_ERROR(fs::remove(Twine(FilePathname
)));
1362 TEST_F(FileSystemTest
, Resize
) {
1364 SmallString
<64> TempPath
;
1365 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD
, TempPath
));
1366 ASSERT_NO_ERROR(fs::resize_file(FD
, 123));
1367 fs::file_status Status
;
1368 ASSERT_NO_ERROR(fs::status(FD
, Status
));
1369 ASSERT_EQ(Status
.getSize(), 123U);
1371 ASSERT_NO_ERROR(fs::remove(TempPath
));
1374 TEST_F(FileSystemTest
, ResizeBeforeMapping
) {
1375 // Create a temp file.
1377 SmallString
<64> TempPath
;
1378 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD
, TempPath
));
1379 ASSERT_NO_ERROR(fs::resize_file_before_mapping_readwrite(FD
, 123));
1381 // Map in temp file. On Windows, fs::resize_file_before_mapping_readwrite is
1382 // a no-op and the mapping itself will resize the file.
1385 fs::mapped_file_region
mfr(fs::convertFDToNativeFile(FD
),
1386 fs::mapped_file_region::readwrite
, 123, 0, EC
);
1387 ASSERT_NO_ERROR(EC
);
1392 fs::file_status Status
;
1393 ASSERT_NO_ERROR(fs::status(FD
, Status
));
1394 ASSERT_EQ(Status
.getSize(), 123U);
1396 ASSERT_NO_ERROR(fs::remove(TempPath
));
1399 TEST_F(FileSystemTest
, MD5
) {
1401 SmallString
<64> TempPath
;
1402 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD
, TempPath
));
1403 StringRef
Data("abcdefghijklmnopqrstuvwxyz");
1404 ASSERT_EQ(write(FD
, Data
.data(), Data
.size()), static_cast<ssize_t
>(Data
.size()));
1405 lseek(FD
, 0, SEEK_SET
);
1406 auto Hash
= fs::md5_contents(FD
);
1408 ASSERT_NO_ERROR(Hash
.getError());
1410 EXPECT_STREQ("c3fcd3d76192e4007dfb496cca67e13b", Hash
->digest().c_str());
1413 TEST_F(FileSystemTest
, FileMapping
) {
1414 // Create a temp file.
1416 SmallString
<64> TempPath
;
1418 fs::createTemporaryFile("prefix", "temp", FileDescriptor
, TempPath
));
1419 unsigned Size
= 4096;
1421 fs::resize_file_before_mapping_readwrite(FileDescriptor
, Size
));
1423 // Map in temp file and add some content
1425 StringRef
Val("hello there");
1426 fs::mapped_file_region MaybeMFR
;
1427 EXPECT_FALSE(MaybeMFR
);
1429 fs::mapped_file_region
mfr(fs::convertFDToNativeFile(FileDescriptor
),
1430 fs::mapped_file_region::readwrite
, Size
, 0, EC
);
1431 ASSERT_NO_ERROR(EC
);
1432 std::copy(Val
.begin(), Val
.end(), mfr
.data());
1433 // Explicitly add a 0.
1434 mfr
.data()[Val
.size()] = 0;
1436 // Move it out of the scope and confirm mfr is reset.
1437 MaybeMFR
= std::move(mfr
);
1439 #if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST
1440 EXPECT_DEATH(mfr
.data(), "Mapping failed but used anyway!");
1441 EXPECT_DEATH(mfr
.size(), "Mapping failed but used anyway!");
1445 // Check that the moved-to region is still valid.
1446 EXPECT_EQ(Val
, StringRef(MaybeMFR
.data()));
1447 EXPECT_EQ(Size
, MaybeMFR
.size());
1452 ASSERT_EQ(close(FileDescriptor
), 0);
1454 // Map it back in read-only
1457 EC
= fs::openFileForRead(Twine(TempPath
), FD
);
1458 ASSERT_NO_ERROR(EC
);
1459 fs::mapped_file_region
mfr(fs::convertFDToNativeFile(FD
),
1460 fs::mapped_file_region::readonly
, Size
, 0, EC
);
1461 ASSERT_NO_ERROR(EC
);
1464 EXPECT_EQ(StringRef(mfr
.const_data()), Val
);
1467 fs::mapped_file_region
m(fs::convertFDToNativeFile(FD
),
1468 fs::mapped_file_region::readonly
, Size
, 0, EC
);
1469 ASSERT_NO_ERROR(EC
);
1470 ASSERT_EQ(close(FD
), 0);
1472 ASSERT_NO_ERROR(fs::remove(TempPath
));
1475 TEST(Support
, NormalizePath
) {
1476 // Input, Expected Win, Expected Posix
1477 using TestTuple
= std::tuple
<const char *, const char *, const char *>;
1478 std::vector
<TestTuple
> Tests
;
1479 Tests
.emplace_back("a", "a", "a");
1480 Tests
.emplace_back("a/b", "a\\b", "a/b");
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", "\\a", "/a");
1484 Tests
.emplace_back("a\\", "a\\", "a/");
1485 Tests
.emplace_back("a\\t", "a\\t", "a/t");
1487 for (auto &T
: Tests
) {
1488 SmallString
<64> Win(std::get
<0>(T
));
1489 SmallString
<64> Posix(Win
);
1490 SmallString
<64> WinSlash(Win
);
1491 path::native(Win
, path::Style::windows
);
1492 path::native(Posix
, path::Style::posix
);
1493 path::native(WinSlash
, path::Style::windows_slash
);
1494 EXPECT_EQ(std::get
<1>(T
), Win
);
1495 EXPECT_EQ(std::get
<2>(T
), Posix
);
1496 EXPECT_EQ(std::get
<2>(T
), WinSlash
);
1499 for (auto &T
: Tests
) {
1500 SmallString
<64> WinBackslash(std::get
<0>(T
));
1501 SmallString
<64> Posix(WinBackslash
);
1502 SmallString
<64> WinSlash(WinBackslash
);
1503 path::make_preferred(WinBackslash
, path::Style::windows_backslash
);
1504 path::make_preferred(Posix
, path::Style::posix
);
1505 path::make_preferred(WinSlash
, path::Style::windows_slash
);
1506 EXPECT_EQ(std::get
<1>(T
), WinBackslash
);
1507 EXPECT_EQ(std::get
<0>(T
), Posix
); // Posix remains unchanged here
1508 EXPECT_EQ(std::get
<2>(T
), WinSlash
);
1512 SmallString
<64> PathHome
;
1513 path::home_directory(PathHome
);
1515 const char *Path7a
= "~/aaa";
1516 SmallString
<64> Path7(Path7a
);
1517 path::native(Path7
, path::Style::windows_backslash
);
1518 EXPECT_TRUE(Path7
.endswith("\\aaa"));
1519 EXPECT_TRUE(Path7
.startswith(PathHome
));
1520 EXPECT_EQ(Path7
.size(), PathHome
.size() + strlen(Path7a
+ 1));
1522 path::native(Path7
, path::Style::windows_slash
);
1523 EXPECT_TRUE(Path7
.endswith("/aaa"));
1524 EXPECT_TRUE(Path7
.startswith(PathHome
));
1525 EXPECT_EQ(Path7
.size(), PathHome
.size() + strlen(Path7a
+ 1));
1527 const char *Path8a
= "~";
1528 SmallString
<64> Path8(Path8a
);
1529 path::native(Path8
);
1530 EXPECT_EQ(Path8
, PathHome
);
1532 const char *Path9a
= "~aaa";
1533 SmallString
<64> Path9(Path9a
);
1534 path::native(Path9
);
1535 EXPECT_EQ(Path9
, "~aaa");
1537 const char *Path10a
= "aaa/~/b";
1538 SmallString
<64> Path10(Path10a
);
1539 path::native(Path10
, path::Style::windows_backslash
);
1540 EXPECT_EQ(Path10
, "aaa\\~\\b");
1544 TEST(Support
, RemoveLeadingDotSlash
) {
1545 StringRef
Path1("././/foolz/wat");
1546 StringRef
Path2("./////");
1548 Path1
= path::remove_leading_dotslash(Path1
);
1549 EXPECT_EQ(Path1
, "foolz/wat");
1550 Path2
= path::remove_leading_dotslash(Path2
);
1551 EXPECT_EQ(Path2
, "");
1554 static std::string
remove_dots(StringRef path
, bool remove_dot_dot
,
1555 path::Style style
) {
1556 SmallString
<256> buffer(path
);
1557 path::remove_dots(buffer
, remove_dot_dot
, style
);
1558 return std::string(buffer
.str());
1561 TEST(Support
, RemoveDots
) {
1562 EXPECT_EQ("foolz\\wat",
1563 remove_dots(".\\.\\\\foolz\\wat", false, path::Style::windows
));
1564 EXPECT_EQ("", remove_dots(".\\\\\\\\\\", false, path::Style::windows
));
1566 EXPECT_EQ("a\\..\\b\\c",
1567 remove_dots(".\\a\\..\\b\\c", false, path::Style::windows
));
1568 EXPECT_EQ("b\\c", remove_dots(".\\a\\..\\b\\c", true, path::Style::windows
));
1569 EXPECT_EQ("c", remove_dots(".\\.\\c", true, path::Style::windows
));
1570 EXPECT_EQ("..\\a\\c",
1571 remove_dots("..\\a\\b\\..\\c", true, path::Style::windows
));
1572 EXPECT_EQ("..\\..\\a\\c",
1573 remove_dots("..\\..\\a\\b\\..\\c", true, path::Style::windows
));
1574 EXPECT_EQ("C:\\a\\c", remove_dots("C:\\foo\\bar//..\\..\\a\\c", true,
1575 path::Style::windows
));
1577 EXPECT_EQ("C:\\bar",
1578 remove_dots("C:/foo/../bar", true, path::Style::windows
));
1579 EXPECT_EQ("C:\\foo\\bar",
1580 remove_dots("C:/foo/bar", true, path::Style::windows
));
1581 EXPECT_EQ("C:\\foo\\bar",
1582 remove_dots("C:/foo\\bar", true, path::Style::windows
));
1583 EXPECT_EQ("\\", remove_dots("/", true, path::Style::windows
));
1584 EXPECT_EQ("C:\\", remove_dots("C:/", true, path::Style::windows
));
1586 // Some clients of remove_dots expect it to remove trailing slashes. Again,
1587 // this is emergent behavior that VFS relies on, and not inherently part of
1588 // the specification.
1589 EXPECT_EQ("C:\\foo\\bar",
1590 remove_dots("C:\\foo\\bar\\", true, path::Style::windows
));
1591 EXPECT_EQ("/foo/bar",
1592 remove_dots("/foo/bar/", true, path::Style::posix
));
1594 // A double separator is rewritten.
1595 EXPECT_EQ("C:\\foo\\bar",
1596 remove_dots("C:/foo//bar", true, path::Style::windows
));
1598 SmallString
<64> Path1(".\\.\\c");
1599 EXPECT_TRUE(path::remove_dots(Path1
, true, path::Style::windows
));
1600 EXPECT_EQ("c", Path1
);
1602 EXPECT_EQ("foolz/wat",
1603 remove_dots("././/foolz/wat", false, path::Style::posix
));
1604 EXPECT_EQ("", remove_dots("./////", false, path::Style::posix
));
1606 EXPECT_EQ("a/../b/c", remove_dots("./a/../b/c", false, path::Style::posix
));
1607 EXPECT_EQ("b/c", remove_dots("./a/../b/c", true, path::Style::posix
));
1608 EXPECT_EQ("c", remove_dots("././c", true, path::Style::posix
));
1609 EXPECT_EQ("../a/c", remove_dots("../a/b/../c", true, path::Style::posix
));
1610 EXPECT_EQ("../../a/c",
1611 remove_dots("../../a/b/../c", true, path::Style::posix
));
1612 EXPECT_EQ("/a/c", remove_dots("/../../a/c", true, path::Style::posix
));
1614 remove_dots("/../a/b//../././/c", true, path::Style::posix
));
1615 EXPECT_EQ("/", remove_dots("/", true, path::Style::posix
));
1617 // FIXME: Leaving behind this double leading slash seems like a bug.
1618 EXPECT_EQ("//foo/bar",
1619 remove_dots("//foo/bar/", true, path::Style::posix
));
1621 SmallString
<64> Path2("././c");
1622 EXPECT_TRUE(path::remove_dots(Path2
, true, path::Style::posix
));
1623 EXPECT_EQ("c", Path2
);
1626 TEST(Support
, ReplacePathPrefix
) {
1627 SmallString
<64> Path1("/foo");
1628 SmallString
<64> Path2("/old/foo");
1629 SmallString
<64> Path3("/oldnew/foo");
1630 SmallString
<64> Path4("C:\\old/foo\\bar");
1631 SmallString
<64> OldPrefix("/old");
1632 SmallString
<64> OldPrefixSep("/old/");
1633 SmallString
<64> OldPrefixWin("c:/oLD/F");
1634 SmallString
<64> NewPrefix("/new");
1635 SmallString
<64> NewPrefix2("/longernew");
1636 SmallString
<64> EmptyPrefix("");
1639 SmallString
<64> Path
= Path1
;
1640 Found
= path::replace_path_prefix(Path
, OldPrefix
, NewPrefix
);
1641 EXPECT_FALSE(Found
);
1642 EXPECT_EQ(Path
, "/foo");
1644 Found
= path::replace_path_prefix(Path
, OldPrefix
, NewPrefix
);
1646 EXPECT_EQ(Path
, "/new/foo");
1648 Found
= path::replace_path_prefix(Path
, OldPrefix
, NewPrefix2
);
1650 EXPECT_EQ(Path
, "/longernew/foo");
1652 Found
= path::replace_path_prefix(Path
, EmptyPrefix
, NewPrefix
);
1654 EXPECT_EQ(Path
, "/new/foo");
1656 Found
= path::replace_path_prefix(Path
, OldPrefix
, EmptyPrefix
);
1658 EXPECT_EQ(Path
, "/foo");
1660 Found
= path::replace_path_prefix(Path
, OldPrefixSep
, EmptyPrefix
);
1662 EXPECT_EQ(Path
, "foo");
1664 Found
= path::replace_path_prefix(Path
, OldPrefix
, NewPrefix
);
1666 EXPECT_EQ(Path
, "/newnew/foo");
1668 Found
= path::replace_path_prefix(Path
, OldPrefix
, NewPrefix2
);
1670 EXPECT_EQ(Path
, "/longernewnew/foo");
1672 Found
= path::replace_path_prefix(Path
, EmptyPrefix
, NewPrefix
);
1674 EXPECT_EQ(Path
, "/new/foo");
1676 Found
= path::replace_path_prefix(Path
, OldPrefix
, NewPrefix
);
1678 EXPECT_EQ(Path
, "/new");
1679 Path
= OldPrefixSep
;
1680 Found
= path::replace_path_prefix(Path
, OldPrefix
, NewPrefix
);
1682 EXPECT_EQ(Path
, "/new/");
1684 Found
= path::replace_path_prefix(Path
, OldPrefixSep
, NewPrefix
);
1685 EXPECT_FALSE(Found
);
1686 EXPECT_EQ(Path
, "/old");
1688 Found
= path::replace_path_prefix(Path
, OldPrefixWin
, NewPrefix
,
1689 path::Style::windows
);
1691 EXPECT_EQ(Path
, "/newoo\\bar");
1693 Found
= path::replace_path_prefix(Path
, OldPrefixWin
, NewPrefix
,
1694 path::Style::posix
);
1695 EXPECT_FALSE(Found
);
1696 EXPECT_EQ(Path
, "C:\\old/foo\\bar");
1699 TEST_F(FileSystemTest
, OpenFileForRead
) {
1700 // Create a temp file.
1702 SmallString
<64> TempPath
;
1704 fs::createTemporaryFile("prefix", "temp", FileDescriptor
, TempPath
));
1705 FileRemover
Cleanup(TempPath
);
1707 // Make sure it exists.
1708 ASSERT_TRUE(sys::fs::exists(Twine(TempPath
)));
1710 // Open the file for read
1711 int FileDescriptor2
;
1712 SmallString
<64> ResultPath
;
1713 ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath
), FileDescriptor2
,
1714 fs::OF_None
, &ResultPath
))
1716 // If we succeeded, check that the paths are the same (modulo case):
1717 if (!ResultPath
.empty()) {
1718 // The paths returned by createTemporaryFile and getPathFromOpenFD
1719 // should reference the same file on disk.
1720 fs::UniqueID D1
, D2
;
1721 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath
), D1
));
1722 ASSERT_NO_ERROR(fs::getUniqueID(Twine(ResultPath
), D2
));
1725 ::close(FileDescriptor
);
1726 ::close(FileDescriptor2
);
1729 // Since Windows Vista, file access time is not updated by default.
1730 // This is instead updated manually by openFileForRead.
1731 // https://blogs.technet.microsoft.com/filecab/2006/11/07/disabling-last-access-time-in-windows-vista-to-improve-ntfs-performance/
1732 // This part of the unit test is Windows specific as the updating of
1733 // access times can be disabled on Linux using /etc/fstab.
1735 // Set access time to UNIX epoch.
1736 ASSERT_NO_ERROR(sys::fs::openFileForWrite(Twine(TempPath
), FileDescriptor
,
1737 fs::CD_OpenExisting
));
1738 TimePoint
<> Epoch(std::chrono::milliseconds(0));
1739 ASSERT_NO_ERROR(fs::setLastAccessAndModificationTime(FileDescriptor
, Epoch
));
1740 ::close(FileDescriptor
);
1742 // Open the file and ensure access time is updated, when forced.
1743 ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath
), FileDescriptor
,
1744 fs::OF_UpdateAtime
, &ResultPath
));
1746 sys::fs::file_status Status
;
1747 ASSERT_NO_ERROR(sys::fs::status(FileDescriptor
, Status
));
1748 auto FileAccessTime
= Status
.getLastAccessedTime();
1750 ASSERT_NE(Epoch
, FileAccessTime
);
1751 ::close(FileDescriptor
);
1753 // Ideally this test would include a case when ATime is not forced to update,
1754 // however the expected behaviour will differ depending on the configuration
1755 // of the Windows file system.
1759 static void createFileWithData(const Twine
&Path
, bool ShouldExistBefore
,
1760 fs::CreationDisposition Disp
, StringRef Data
) {
1762 ASSERT_EQ(ShouldExistBefore
, fs::exists(Path
));
1763 ASSERT_NO_ERROR(fs::openFileForWrite(Path
, FD
, Disp
));
1764 FileDescriptorCloser
Closer(FD
);
1765 ASSERT_TRUE(fs::exists(Path
));
1767 ASSERT_EQ(Data
.size(), (size_t)write(FD
, Data
.data(), Data
.size()));
1770 static void verifyFileContents(const Twine
&Path
, StringRef Contents
) {
1771 auto Buffer
= MemoryBuffer::getFile(Path
);
1772 ASSERT_TRUE((bool)Buffer
);
1773 StringRef Data
= Buffer
.get()->getBuffer();
1774 ASSERT_EQ(Data
, Contents
);
1777 TEST_F(FileSystemTest
, CreateNew
) {
1779 std::optional
<FileDescriptorCloser
> Closer
;
1781 // Succeeds if the file does not exist.
1782 ASSERT_FALSE(fs::exists(NonExistantFile
));
1783 ASSERT_NO_ERROR(fs::openFileForWrite(NonExistantFile
, FD
, fs::CD_CreateNew
));
1784 ASSERT_TRUE(fs::exists(NonExistantFile
));
1786 FileRemover
Cleanup(NonExistantFile
);
1789 // And creates a file of size 0.
1790 sys::fs::file_status Status
;
1791 ASSERT_NO_ERROR(sys::fs::status(FD
, Status
));
1792 EXPECT_EQ(0ULL, Status
.getSize());
1794 // Close this first, before trying to re-open the file.
1797 // But fails if the file does exist.
1798 ASSERT_ERROR(fs::openFileForWrite(NonExistantFile
, FD
, fs::CD_CreateNew
));
1801 TEST_F(FileSystemTest
, CreateAlways
) {
1803 std::optional
<FileDescriptorCloser
> Closer
;
1805 // Succeeds if the file does not exist.
1806 ASSERT_FALSE(fs::exists(NonExistantFile
));
1808 fs::openFileForWrite(NonExistantFile
, FD
, fs::CD_CreateAlways
));
1812 ASSERT_TRUE(fs::exists(NonExistantFile
));
1814 FileRemover
Cleanup(NonExistantFile
);
1816 // And creates a file of size 0.
1818 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1819 ASSERT_EQ(0ULL, FileSize
);
1821 // If we write some data to it re-create it with CreateAlways, it succeeds and
1822 // truncates to 0 bytes.
1823 ASSERT_EQ(4, write(FD
, "Test", 4));
1827 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1828 ASSERT_EQ(4ULL, FileSize
);
1831 fs::openFileForWrite(NonExistantFile
, FD
, fs::CD_CreateAlways
));
1833 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1834 ASSERT_EQ(0ULL, FileSize
);
1837 TEST_F(FileSystemTest
, OpenExisting
) {
1840 // Fails if the file does not exist.
1841 ASSERT_FALSE(fs::exists(NonExistantFile
));
1842 ASSERT_ERROR(fs::openFileForWrite(NonExistantFile
, FD
, fs::CD_OpenExisting
));
1843 ASSERT_FALSE(fs::exists(NonExistantFile
));
1845 // Make a dummy file now so that we can try again when the file does exist.
1846 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "Fizz");
1847 FileRemover
Cleanup(NonExistantFile
);
1849 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1850 ASSERT_EQ(4ULL, FileSize
);
1852 // If we re-create it with different data, it overwrites rather than
1854 createFileWithData(NonExistantFile
, true, fs::CD_OpenExisting
, "Buzz");
1855 verifyFileContents(NonExistantFile
, "Buzz");
1858 TEST_F(FileSystemTest
, OpenAlways
) {
1859 // Succeeds if the file does not exist.
1860 createFileWithData(NonExistantFile
, false, fs::CD_OpenAlways
, "Fizz");
1861 FileRemover
Cleanup(NonExistantFile
);
1863 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1864 ASSERT_EQ(4ULL, FileSize
);
1866 // Now re-open it and write again, verifying the contents get over-written.
1867 createFileWithData(NonExistantFile
, true, fs::CD_OpenAlways
, "Bu");
1868 verifyFileContents(NonExistantFile
, "Buzz");
1871 TEST_F(FileSystemTest
, AppendSetsCorrectFileOffset
) {
1872 fs::CreationDisposition Disps
[] = {fs::CD_CreateAlways
, fs::CD_OpenAlways
,
1873 fs::CD_OpenExisting
};
1875 // Write some data and re-open it with every possible disposition (this is a
1876 // hack that shouldn't work, but is left for compatibility. OF_Append
1878 // the specified disposition.
1879 for (fs::CreationDisposition Disp
: Disps
) {
1881 std::optional
<FileDescriptorCloser
> Closer
;
1883 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "Fizz");
1885 FileRemover
Cleanup(NonExistantFile
);
1888 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1889 ASSERT_EQ(4ULL, FileSize
);
1891 fs::openFileForWrite(NonExistantFile
, FD
, Disp
, fs::OF_Append
));
1893 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1894 ASSERT_EQ(4ULL, FileSize
);
1896 ASSERT_EQ(4, write(FD
, "Buzz", 4));
1899 verifyFileContents(NonExistantFile
, "FizzBuzz");
1903 static void verifyRead(int FD
, StringRef Data
, bool ShouldSucceed
) {
1904 std::vector
<char> Buffer
;
1905 Buffer
.resize(Data
.size());
1906 int Result
= ::read(FD
, Buffer
.data(), Buffer
.size());
1907 if (ShouldSucceed
) {
1908 ASSERT_EQ((size_t)Result
, Data
.size());
1909 ASSERT_EQ(Data
, StringRef(Buffer
.data(), Buffer
.size()));
1911 ASSERT_EQ(-1, Result
);
1912 ASSERT_EQ(EBADF
, errno
);
1916 static void verifyWrite(int FD
, StringRef Data
, bool ShouldSucceed
) {
1917 int Result
= ::write(FD
, Data
.data(), Data
.size());
1919 ASSERT_EQ((size_t)Result
, Data
.size());
1921 ASSERT_EQ(-1, Result
);
1922 ASSERT_EQ(EBADF
, errno
);
1926 TEST_F(FileSystemTest
, ReadOnlyFileCantWrite
) {
1927 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "Fizz");
1928 FileRemover
Cleanup(NonExistantFile
);
1931 ASSERT_NO_ERROR(fs::openFileForRead(NonExistantFile
, FD
));
1932 FileDescriptorCloser
Closer(FD
);
1934 verifyWrite(FD
, "Buzz", false);
1935 verifyRead(FD
, "Fizz", true);
1938 TEST_F(FileSystemTest
, WriteOnlyFileCantRead
) {
1939 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "Fizz");
1940 FileRemover
Cleanup(NonExistantFile
);
1944 fs::openFileForWrite(NonExistantFile
, FD
, fs::CD_OpenExisting
));
1945 FileDescriptorCloser
Closer(FD
);
1946 verifyRead(FD
, "Fizz", false);
1947 verifyWrite(FD
, "Buzz", true);
1950 TEST_F(FileSystemTest
, ReadWriteFileCanReadOrWrite
) {
1951 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "Fizz");
1952 FileRemover
Cleanup(NonExistantFile
);
1955 ASSERT_NO_ERROR(fs::openFileForReadWrite(NonExistantFile
, FD
,
1956 fs::CD_OpenExisting
, fs::OF_None
));
1957 FileDescriptorCloser
Closer(FD
);
1958 verifyRead(FD
, "Fizz", true);
1959 verifyWrite(FD
, "Buzz", true);
1962 TEST_F(FileSystemTest
, readNativeFile
) {
1963 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "01234");
1964 FileRemover
Cleanup(NonExistantFile
);
1965 const auto &Read
= [&](size_t ToRead
) -> Expected
<std::string
> {
1966 std::string
Buf(ToRead
, '?');
1967 Expected
<fs::file_t
> FD
= fs::openNativeFileForRead(NonExistantFile
);
1969 return FD
.takeError();
1970 auto Close
= make_scope_exit([&] { fs::closeFile(*FD
); });
1971 if (Expected
<size_t> BytesRead
= fs::readNativeFile(
1972 *FD
, MutableArrayRef(&*Buf
.begin(), Buf
.size())))
1973 return Buf
.substr(0, *BytesRead
);
1975 return BytesRead
.takeError();
1977 EXPECT_THAT_EXPECTED(Read(5), HasValue("01234"));
1978 EXPECT_THAT_EXPECTED(Read(3), HasValue("012"));
1979 EXPECT_THAT_EXPECTED(Read(6), HasValue("01234"));
1982 TEST_F(FileSystemTest
, readNativeFileToEOF
) {
1983 constexpr StringLiteral Content
= "0123456789";
1984 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, Content
);
1985 FileRemover
Cleanup(NonExistantFile
);
1986 const auto &Read
= [&](SmallVectorImpl
<char> &V
,
1987 std::optional
<ssize_t
> ChunkSize
) {
1988 Expected
<fs::file_t
> FD
= fs::openNativeFileForRead(NonExistantFile
);
1990 return FD
.takeError();
1991 auto Close
= make_scope_exit([&] { fs::closeFile(*FD
); });
1993 return fs::readNativeFileToEOF(*FD
, V
, *ChunkSize
);
1994 return fs::readNativeFileToEOF(*FD
, V
);
1997 // Check basic operation.
1999 SmallString
<0> NoSmall
;
2000 SmallString
<fs::DefaultReadChunkSize
+ Content
.size()> StaysSmall
;
2001 SmallVectorImpl
<char> *Vectors
[] = {
2002 static_cast<SmallVectorImpl
<char> *>(&NoSmall
),
2003 static_cast<SmallVectorImpl
<char> *>(&StaysSmall
),
2005 for (SmallVectorImpl
<char> *V
: Vectors
) {
2006 ASSERT_THAT_ERROR(Read(*V
, std::nullopt
), Succeeded());
2007 ASSERT_EQ(Content
, StringRef(V
->begin(), V
->size()));
2009 ASSERT_EQ(fs::DefaultReadChunkSize
+ Content
.size(), StaysSmall
.capacity());
2013 constexpr StringLiteral Prefix
= "prefix-";
2014 for (SmallVectorImpl
<char> *V
: Vectors
) {
2015 V
->assign(Prefix
.begin(), Prefix
.end());
2016 ASSERT_THAT_ERROR(Read(*V
, std::nullopt
), Succeeded());
2017 ASSERT_EQ((Prefix
+ Content
).str(), StringRef(V
->begin(), V
->size()));
2022 // Check that the chunk size (if specified) is respected.
2023 SmallString
<Content
.size() + 5> SmallChunks
;
2024 ASSERT_THAT_ERROR(Read(SmallChunks
, 5), Succeeded());
2025 ASSERT_EQ(SmallChunks
, Content
);
2026 ASSERT_EQ(Content
.size() + 5, SmallChunks
.capacity());
2029 TEST_F(FileSystemTest
, readNativeFileSlice
) {
2030 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "01234");
2031 FileRemover
Cleanup(NonExistantFile
);
2032 Expected
<fs::file_t
> FD
= fs::openNativeFileForRead(NonExistantFile
);
2033 ASSERT_THAT_EXPECTED(FD
, Succeeded());
2034 auto Close
= make_scope_exit([&] { fs::closeFile(*FD
); });
2035 const auto &Read
= [&](size_t Offset
,
2036 size_t ToRead
) -> Expected
<std::string
> {
2037 std::string
Buf(ToRead
, '?');
2038 if (Expected
<size_t> BytesRead
= fs::readNativeFileSlice(
2039 *FD
, MutableArrayRef(&*Buf
.begin(), Buf
.size()), Offset
))
2040 return Buf
.substr(0, *BytesRead
);
2042 return BytesRead
.takeError();
2044 EXPECT_THAT_EXPECTED(Read(0, 5), HasValue("01234"));
2045 EXPECT_THAT_EXPECTED(Read(0, 3), HasValue("012"));
2046 EXPECT_THAT_EXPECTED(Read(2, 3), HasValue("234"));
2047 EXPECT_THAT_EXPECTED(Read(0, 6), HasValue("01234"));
2048 EXPECT_THAT_EXPECTED(Read(2, 6), HasValue("234"));
2049 EXPECT_THAT_EXPECTED(Read(5, 5), HasValue(""));
2052 TEST_F(FileSystemTest
, is_local
) {
2053 bool TestDirectoryIsLocal
;
2054 ASSERT_NO_ERROR(fs::is_local(TestDirectory
, TestDirectoryIsLocal
));
2055 EXPECT_EQ(TestDirectoryIsLocal
, fs::is_local(TestDirectory
));
2058 SmallString
<128> TempPath
;
2060 fs::createUniqueFile(Twine(TestDirectory
) + "/temp", FD
, TempPath
));
2061 FileRemover
Cleanup(TempPath
);
2063 // Make sure it exists.
2064 ASSERT_TRUE(sys::fs::exists(Twine(TempPath
)));
2066 bool TempFileIsLocal
;
2067 ASSERT_NO_ERROR(fs::is_local(FD
, TempFileIsLocal
));
2068 EXPECT_EQ(TempFileIsLocal
, fs::is_local(FD
));
2071 // Expect that the file and its parent directory are equally local or equally
2073 EXPECT_EQ(TestDirectoryIsLocal
, TempFileIsLocal
);
2076 TEST_F(FileSystemTest
, getUmask
) {
2078 EXPECT_EQ(fs::getUmask(), 0U) << "Should always be 0 on Windows.";
2080 unsigned OldMask
= ::umask(0022);
2081 unsigned CurrentMask
= fs::getUmask();
2082 EXPECT_EQ(CurrentMask
, 0022U)
2083 << "getUmask() didn't return previously set umask()";
2084 EXPECT_EQ(::umask(OldMask
), mode_t(0022U))
2085 << "getUmask() may have changed umask()";
2089 TEST_F(FileSystemTest
, RespectUmask
) {
2091 unsigned OldMask
= ::umask(0022);
2094 SmallString
<128> TempPath
;
2095 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD
, TempPath
));
2097 fs::perms AllRWE
= static_cast<fs::perms
>(0777);
2099 ASSERT_NO_ERROR(fs::setPermissions(TempPath
, AllRWE
));
2101 ErrorOr
<fs::perms
> Perms
= fs::getPermissions(TempPath
);
2102 ASSERT_TRUE(!!Perms
);
2103 EXPECT_EQ(Perms
.get(), AllRWE
) << "Should have ignored umask by default";
2105 ASSERT_NO_ERROR(fs::setPermissions(TempPath
, AllRWE
));
2107 Perms
= fs::getPermissions(TempPath
);
2108 ASSERT_TRUE(!!Perms
);
2109 EXPECT_EQ(Perms
.get(), AllRWE
) << "Should have ignored umask";
2112 fs::setPermissions(FD
, static_cast<fs::perms
>(AllRWE
& ~fs::getUmask())));
2113 Perms
= fs::getPermissions(TempPath
);
2114 ASSERT_TRUE(!!Perms
);
2115 EXPECT_EQ(Perms
.get(), static_cast<fs::perms
>(0755))
2116 << "Did not respect umask";
2118 (void)::umask(0057);
2121 fs::setPermissions(FD
, static_cast<fs::perms
>(AllRWE
& ~fs::getUmask())));
2122 Perms
= fs::getPermissions(TempPath
);
2123 ASSERT_TRUE(!!Perms
);
2124 EXPECT_EQ(Perms
.get(), static_cast<fs::perms
>(0720))
2125 << "Did not respect umask";
2127 (void)::umask(OldMask
);
2132 TEST_F(FileSystemTest
, set_current_path
) {
2133 SmallString
<128> path
;
2135 ASSERT_NO_ERROR(fs::current_path(path
));
2136 ASSERT_NE(TestDirectory
, path
);
2138 struct RestorePath
{
2139 SmallString
<128> path
;
2140 RestorePath(const SmallString
<128> &path
) : path(path
) {}
2141 ~RestorePath() { fs::set_current_path(path
); }
2142 } restore_path(path
);
2144 ASSERT_NO_ERROR(fs::set_current_path(TestDirectory
));
2146 ASSERT_NO_ERROR(fs::current_path(path
));
2148 fs::UniqueID D1
, D2
;
2149 ASSERT_NO_ERROR(fs::getUniqueID(TestDirectory
, D1
));
2150 ASSERT_NO_ERROR(fs::getUniqueID(path
, D2
));
2151 ASSERT_EQ(D1
, D2
) << "D1: " << TestDirectory
<< "\nD2: " << path
;
2154 TEST_F(FileSystemTest
, permissions
) {
2156 SmallString
<64> TempPath
;
2157 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD
, TempPath
));
2158 FileRemover
Cleanup(TempPath
);
2160 // Make sure it exists.
2161 ASSERT_TRUE(fs::exists(Twine(TempPath
)));
2163 auto CheckPermissions
= [&](fs::perms Expected
) {
2164 ErrorOr
<fs::perms
> Actual
= fs::getPermissions(TempPath
);
2165 return Actual
&& *Actual
== Expected
;
2168 std::error_code NoError
;
2169 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_all
), NoError
);
2170 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2172 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_read
| fs::all_exe
), NoError
);
2173 EXPECT_TRUE(CheckPermissions(fs::all_read
| fs::all_exe
));
2176 fs::perms ReadOnly
= fs::all_read
| fs::all_exe
;
2177 EXPECT_EQ(fs::setPermissions(TempPath
, fs::no_perms
), NoError
);
2178 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2180 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_read
), NoError
);
2181 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2183 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_write
), NoError
);
2184 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2186 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_exe
), NoError
);
2187 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2189 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_all
), NoError
);
2190 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2192 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_read
), NoError
);
2193 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2195 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_write
), NoError
);
2196 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2198 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_exe
), NoError
);
2199 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2201 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_all
), NoError
);
2202 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2204 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_read
), NoError
);
2205 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2207 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_write
), NoError
);
2208 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2210 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_exe
), NoError
);
2211 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2213 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_all
), NoError
);
2214 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2216 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_read
), NoError
);
2217 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2219 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_write
), NoError
);
2220 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2222 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_exe
), NoError
);
2223 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2225 EXPECT_EQ(fs::setPermissions(TempPath
, fs::set_uid_on_exe
), NoError
);
2226 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2228 EXPECT_EQ(fs::setPermissions(TempPath
, fs::set_gid_on_exe
), NoError
);
2229 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2231 EXPECT_EQ(fs::setPermissions(TempPath
, fs::sticky_bit
), NoError
);
2232 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2234 EXPECT_EQ(fs::setPermissions(TempPath
, fs::set_uid_on_exe
|
2235 fs::set_gid_on_exe
|
2238 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2240 EXPECT_EQ(fs::setPermissions(TempPath
, ReadOnly
| fs::set_uid_on_exe
|
2241 fs::set_gid_on_exe
|
2244 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2246 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_perms
), NoError
);
2247 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2249 EXPECT_EQ(fs::setPermissions(TempPath
, fs::no_perms
), NoError
);
2250 EXPECT_TRUE(CheckPermissions(fs::no_perms
));
2252 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_read
), NoError
);
2253 EXPECT_TRUE(CheckPermissions(fs::owner_read
));
2255 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_write
), NoError
);
2256 EXPECT_TRUE(CheckPermissions(fs::owner_write
));
2258 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_exe
), NoError
);
2259 EXPECT_TRUE(CheckPermissions(fs::owner_exe
));
2261 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_all
), NoError
);
2262 EXPECT_TRUE(CheckPermissions(fs::owner_all
));
2264 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_read
), NoError
);
2265 EXPECT_TRUE(CheckPermissions(fs::group_read
));
2267 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_write
), NoError
);
2268 EXPECT_TRUE(CheckPermissions(fs::group_write
));
2270 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_exe
), NoError
);
2271 EXPECT_TRUE(CheckPermissions(fs::group_exe
));
2273 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_all
), NoError
);
2274 EXPECT_TRUE(CheckPermissions(fs::group_all
));
2276 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_read
), NoError
);
2277 EXPECT_TRUE(CheckPermissions(fs::others_read
));
2279 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_write
), NoError
);
2280 EXPECT_TRUE(CheckPermissions(fs::others_write
));
2282 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_exe
), NoError
);
2283 EXPECT_TRUE(CheckPermissions(fs::others_exe
));
2285 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_all
), NoError
);
2286 EXPECT_TRUE(CheckPermissions(fs::others_all
));
2288 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_read
), NoError
);
2289 EXPECT_TRUE(CheckPermissions(fs::all_read
));
2291 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_write
), NoError
);
2292 EXPECT_TRUE(CheckPermissions(fs::all_write
));
2294 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_exe
), NoError
);
2295 EXPECT_TRUE(CheckPermissions(fs::all_exe
));
2297 EXPECT_EQ(fs::setPermissions(TempPath
, fs::set_uid_on_exe
), NoError
);
2298 EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe
));
2300 EXPECT_EQ(fs::setPermissions(TempPath
, fs::set_gid_on_exe
), NoError
);
2301 EXPECT_TRUE(CheckPermissions(fs::set_gid_on_exe
));
2303 // Modern BSDs require root to set the sticky bit on files.
2304 // AIX and Solaris without root will mask off (i.e., lose) the sticky bit
2306 #if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
2307 !defined(_AIX) && !(defined(__sun__) && defined(__svr4__))
2308 EXPECT_EQ(fs::setPermissions(TempPath
, fs::sticky_bit
), NoError
);
2309 EXPECT_TRUE(CheckPermissions(fs::sticky_bit
));
2311 EXPECT_EQ(fs::setPermissions(TempPath
, fs::set_uid_on_exe
|
2312 fs::set_gid_on_exe
|
2315 EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe
| fs::set_gid_on_exe
|
2318 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_read
| fs::set_uid_on_exe
|
2319 fs::set_gid_on_exe
|
2322 EXPECT_TRUE(CheckPermissions(fs::all_read
| fs::set_uid_on_exe
|
2323 fs::set_gid_on_exe
| fs::sticky_bit
));
2325 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_perms
), NoError
);
2326 EXPECT_TRUE(CheckPermissions(fs::all_perms
));
2327 #endif // !FreeBSD && !NetBSD && !OpenBSD && !AIX
2329 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_perms
& ~fs::sticky_bit
),
2331 EXPECT_TRUE(CheckPermissions(fs::all_perms
& ~fs::sticky_bit
));
2336 TEST_F(FileSystemTest
, widenPath
) {
2337 const std::wstring
LongPathPrefix(L
"\\\\?\\");
2339 // Test that the length limit is checked against the UTF-16 length and not the
2341 std::string
Input("C:\\foldername\\");
2342 const std::string
Pi("\xcf\x80"); // UTF-8 lower case pi.
2343 // Add Pi up to the MAX_PATH limit.
2344 const size_t NumChars
= MAX_PATH
- Input
.size() - 1;
2345 for (size_t i
= 0; i
< NumChars
; ++i
)
2347 // Check that UTF-8 length already exceeds MAX_PATH.
2348 EXPECT_GT(Input
.size(), (size_t)MAX_PATH
);
2349 SmallVector
<wchar_t, MAX_PATH
+ 16> Result
;
2350 ASSERT_NO_ERROR(windows::widenPath(Input
, Result
));
2351 // Result should not start with the long path prefix.
2352 EXPECT_TRUE(std::wmemcmp(Result
.data(), LongPathPrefix
.c_str(),
2353 LongPathPrefix
.size()) != 0);
2354 EXPECT_EQ(Result
.size(), (size_t)MAX_PATH
- 1);
2356 // Add another Pi to exceed the MAX_PATH limit.
2358 // Construct the expected result.
2359 SmallVector
<wchar_t, MAX_PATH
+ 16> Expected
;
2360 ASSERT_NO_ERROR(windows::UTF8ToUTF16(Input
, Expected
));
2361 Expected
.insert(Expected
.begin(), LongPathPrefix
.begin(),
2362 LongPathPrefix
.end());
2364 ASSERT_NO_ERROR(windows::widenPath(Input
, Result
));
2365 EXPECT_EQ(Result
, Expected
);
2366 // Pass a path with forward slashes, check that it ends up with
2367 // backslashes when widened with the long path prefix.
2368 SmallString
<MAX_PATH
+ 16> InputForward(Input
);
2369 path::make_preferred(InputForward
, path::Style::windows_slash
);
2370 ASSERT_NO_ERROR(windows::widenPath(InputForward
, Result
));
2371 EXPECT_EQ(Result
, Expected
);
2373 // Pass a path which has the long path prefix prepended originally, but
2374 // which is short enough to not require the long path prefix. If such a
2375 // path is passed with forward slashes, make sure it gets normalized to
2377 SmallString
<MAX_PATH
+ 16> PrefixedPath("\\\\?\\C:\\foldername");
2378 ASSERT_NO_ERROR(windows::UTF8ToUTF16(PrefixedPath
, Expected
));
2379 // Mangle the input to forward slashes.
2380 path::make_preferred(PrefixedPath
, path::Style::windows_slash
);
2381 ASSERT_NO_ERROR(windows::widenPath(PrefixedPath
, Result
));
2382 EXPECT_EQ(Result
, Expected
);
2384 // A short path with an inconsistent prefix is passed through as-is; this
2385 // is a degenerate case that we currently don't care about handling.
2386 PrefixedPath
.assign("/\\?/C:/foldername");
2387 ASSERT_NO_ERROR(windows::UTF8ToUTF16(PrefixedPath
, Expected
));
2388 ASSERT_NO_ERROR(windows::widenPath(PrefixedPath
, Result
));
2389 EXPECT_EQ(Result
, Expected
);
2391 // Test that UNC paths are handled correctly.
2392 const std::string
ShareName("\\\\sharename\\");
2393 const std::string
FileName("\\filename");
2394 // Initialize directory name so that the input is within the MAX_PATH limit.
2395 const char DirChar
= 'x';
2396 std::string
DirName(MAX_PATH
- ShareName
.size() - FileName
.size() - 1,
2399 Input
= ShareName
+ DirName
+ FileName
;
2400 ASSERT_NO_ERROR(windows::widenPath(Input
, Result
));
2401 // Result should not start with the long path prefix.
2402 EXPECT_TRUE(std::wmemcmp(Result
.data(), LongPathPrefix
.c_str(),
2403 LongPathPrefix
.size()) != 0);
2404 EXPECT_EQ(Result
.size(), (size_t)MAX_PATH
- 1);
2406 // Extend the directory name so the input exceeds the MAX_PATH limit.
2408 Input
= ShareName
+ DirName
+ FileName
;
2409 // Construct the expected result.
2410 ASSERT_NO_ERROR(windows::UTF8ToUTF16(StringRef(Input
).substr(2), Expected
));
2411 const std::wstring
UNCPrefix(LongPathPrefix
+ L
"UNC\\");
2412 Expected
.insert(Expected
.begin(), UNCPrefix
.begin(), UNCPrefix
.end());
2414 ASSERT_NO_ERROR(windows::widenPath(Input
, Result
));
2415 EXPECT_EQ(Result
, Expected
);
2417 // Check that Unix separators are handled correctly.
2418 std::replace(Input
.begin(), Input
.end(), '\\', '/');
2419 ASSERT_NO_ERROR(windows::widenPath(Input
, Result
));
2420 EXPECT_EQ(Result
, Expected
);
2422 // Check the removal of "dots".
2423 Input
= ShareName
+ DirName
+ "\\.\\foo\\.\\.." + FileName
;
2424 ASSERT_NO_ERROR(windows::widenPath(Input
, Result
));
2425 EXPECT_EQ(Result
, Expected
);
2430 // Windows refuses lock request if file region is already locked by the same
2431 // process. POSIX system in this case updates the existing lock.
2432 TEST_F(FileSystemTest
, FileLocker
) {
2433 using namespace std::chrono
;
2436 SmallString
<64> TempPath
;
2437 EC
= fs::createTemporaryFile("test", "temp", FD
, TempPath
);
2438 ASSERT_NO_ERROR(EC
);
2439 FileRemover
Cleanup(TempPath
);
2440 raw_fd_ostream
Stream(TempPath
, EC
);
2442 EC
= fs::tryLockFile(FD
);
2443 ASSERT_NO_ERROR(EC
);
2444 EC
= fs::unlockFile(FD
);
2445 ASSERT_NO_ERROR(EC
);
2447 if (auto L
= Stream
.lock()) {
2448 ASSERT_ERROR(fs::tryLockFile(FD
));
2449 ASSERT_NO_ERROR(L
->unlock());
2450 ASSERT_NO_ERROR(fs::tryLockFile(FD
));
2451 ASSERT_NO_ERROR(fs::unlockFile(FD
));
2454 handleAllErrors(L
.takeError(), [&](ErrorInfoBase
&EIB
) {});
2457 ASSERT_NO_ERROR(fs::tryLockFile(FD
));
2458 ASSERT_NO_ERROR(fs::unlockFile(FD
));
2461 Expected
<fs::FileLocker
> L1
= Stream
.lock();
2462 ASSERT_THAT_EXPECTED(L1
, Succeeded());
2463 raw_fd_ostream
Stream2(FD
, false);
2464 Expected
<fs::FileLocker
> L2
= Stream2
.tryLockFor(250ms
);
2465 ASSERT_THAT_EXPECTED(L2
, Failed());
2466 ASSERT_NO_ERROR(L1
->unlock());
2467 Expected
<fs::FileLocker
> L3
= Stream
.tryLockFor(0ms
);
2468 ASSERT_THAT_EXPECTED(L3
, Succeeded());
2471 ASSERT_NO_ERROR(fs::tryLockFile(FD
));
2472 ASSERT_NO_ERROR(fs::unlockFile(FD
));
2476 TEST_F(FileSystemTest
, CopyFile
) {
2477 unittest::TempDir
RootTestDirectory("CopyFileTest", /*Unique=*/true);
2479 SmallVector
<std::string
> Data
;
2480 SmallVector
<SmallString
<128>> Sources
;
2481 for (int I
= 0, E
= 3; I
!= E
; ++I
) {
2482 Data
.push_back(Twine(I
).str());
2483 Sources
.emplace_back(RootTestDirectory
.path());
2484 path::append(Sources
.back(), "source" + Data
.back() + ".txt");
2485 createFileWithData(Sources
.back(), /*ShouldExistBefore=*/false,
2486 fs::CD_CreateNew
, Data
.back());
2489 // Copy the first file to a non-existing file.
2490 SmallString
<128> Destination(RootTestDirectory
.path());
2491 path::append(Destination
, "destination");
2492 ASSERT_FALSE(fs::exists(Destination
));
2493 fs::copy_file(Sources
[0], Destination
);
2494 verifyFileContents(Destination
, Data
[0]);
2496 // Copy the second file to an existing file.
2497 fs::copy_file(Sources
[1], Destination
);
2498 verifyFileContents(Destination
, Data
[1]);
2500 // Note: The remaining logic is targeted at a potential failure case related
2501 // to file cloning and symlinks on Darwin. On Windows, fs::create_link() does
2502 // not return success here so the test is skipped.
2503 #if !defined(_WIN32)
2504 // Set up a symlink to the third file.
2505 SmallString
<128> Symlink(RootTestDirectory
.path());
2506 path::append(Symlink
, "symlink");
2507 ASSERT_NO_ERROR(fs::create_link(path::filename(Sources
[2]), Symlink
));
2508 verifyFileContents(Symlink
, Data
[2]);
2510 // fs::getUniqueID() should follow symlinks. Otherwise, this isn't good test
2512 fs::UniqueID SymlinkID
;
2513 fs::UniqueID Data2ID
;
2514 ASSERT_NO_ERROR(fs::getUniqueID(Symlink
, SymlinkID
));
2515 ASSERT_NO_ERROR(fs::getUniqueID(Sources
[2], Data2ID
));
2516 ASSERT_EQ(SymlinkID
, Data2ID
);
2518 // Copy the third file through the symlink.
2519 fs::copy_file(Symlink
, Destination
);
2520 verifyFileContents(Destination
, Data
[2]);
2522 // Confirm the destination is not a link to the original file, and not a
2524 bool IsDestinationSymlink
;
2525 ASSERT_NO_ERROR(fs::is_symlink_file(Destination
, IsDestinationSymlink
));
2526 ASSERT_FALSE(IsDestinationSymlink
);
2527 fs::UniqueID DestinationID
;
2528 ASSERT_NO_ERROR(fs::getUniqueID(Destination
, DestinationID
));
2529 ASSERT_NE(SymlinkID
, DestinationID
);
2533 } // anonymous namespace