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/ADT/Triple.h"
14 #include "llvm/BinaryFormat/Magic.h"
15 #include "llvm/Config/llvm-config.h"
16 #include "llvm/Support/Compiler.h"
17 #include "llvm/Support/ConvertUTF.h"
18 #include "llvm/Support/Duration.h"
19 #include "llvm/Support/Errc.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/FileSystem.h"
22 #include "llvm/Support/FileUtilities.h"
23 #include "llvm/Support/Host.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/raw_ostream.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 llvm::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
) return;
503 std::string PwDir
= pw
->pw_dir
;
505 SmallString
<128> HomeDir
;
506 EXPECT_TRUE(path::home_directory(HomeDir
));
507 EXPECT_EQ(PwDir
, HomeDir
);
510 TEST(Support
, ConfigDirectoryWithEnv
) {
511 WithEnv
Env("XDG_CONFIG_HOME", "/xdg/config");
513 SmallString
<128> ConfigDir
;
514 EXPECT_TRUE(path::user_config_directory(ConfigDir
));
515 EXPECT_EQ("/xdg/config", ConfigDir
);
518 TEST(Support
, ConfigDirectoryNoEnv
) {
519 WithEnv
Env("XDG_CONFIG_HOME", nullptr);
521 SmallString
<128> Fallback
;
522 ASSERT_TRUE(path::home_directory(Fallback
));
523 path::append(Fallback
, ".config");
525 SmallString
<128> CacheDir
;
526 EXPECT_TRUE(path::user_config_directory(CacheDir
));
527 EXPECT_EQ(Fallback
, CacheDir
);
530 TEST(Support
, CacheDirectoryWithEnv
) {
531 WithEnv
Env("XDG_CACHE_HOME", "/xdg/cache");
533 SmallString
<128> CacheDir
;
534 EXPECT_TRUE(path::cache_directory(CacheDir
));
535 EXPECT_EQ("/xdg/cache", CacheDir
);
538 TEST(Support
, CacheDirectoryNoEnv
) {
539 WithEnv
Env("XDG_CACHE_HOME", nullptr);
541 SmallString
<128> Fallback
;
542 ASSERT_TRUE(path::home_directory(Fallback
));
543 path::append(Fallback
, ".cache");
545 SmallString
<128> CacheDir
;
546 EXPECT_TRUE(path::cache_directory(CacheDir
));
547 EXPECT_EQ(Fallback
, CacheDir
);
552 TEST(Support
, ConfigDirectory
) {
553 SmallString
<128> Fallback
;
554 ASSERT_TRUE(path::home_directory(Fallback
));
555 path::append(Fallback
, "Library/Preferences");
557 SmallString
<128> ConfigDir
;
558 EXPECT_TRUE(path::user_config_directory(ConfigDir
));
559 EXPECT_EQ(Fallback
, ConfigDir
);
564 TEST(Support
, ConfigDirectory
) {
565 std::string Expected
= getEnvWin(L
"LOCALAPPDATA");
566 // Do not try to test it if we don't know what to expect.
567 if (Expected
.empty())
569 SmallString
<128> CacheDir
;
570 EXPECT_TRUE(path::user_config_directory(CacheDir
));
571 EXPECT_EQ(Expected
, CacheDir
);
574 TEST(Support
, CacheDirectory
) {
575 std::string Expected
= getEnvWin(L
"LOCALAPPDATA");
576 // Do not try to test it if we don't know what to expect.
577 if (Expected
.empty())
579 SmallString
<128> CacheDir
;
580 EXPECT_TRUE(path::cache_directory(CacheDir
));
581 EXPECT_EQ(Expected
, CacheDir
);
585 TEST(Support
, TempDirectory
) {
586 SmallString
<32> TempDir
;
587 path::system_temp_directory(false, TempDir
);
588 EXPECT_TRUE(!TempDir
.empty());
590 path::system_temp_directory(true, TempDir
);
591 EXPECT_TRUE(!TempDir
.empty());
595 static std::string
path2regex(std::string Path
) {
597 bool Forward
= path::get_separator()[0] == '/';
598 while ((Pos
= Path
.find('\\', Pos
)) != std::string::npos
) {
600 Path
.replace(Pos
, 1, "/");
603 Path
.replace(Pos
, 1, "\\\\");
610 /// Helper for running temp dir test in separated process. See below.
611 #define EXPECT_TEMP_DIR(prepare, expected) \
615 SmallString<300> TempDir; \
616 path::system_temp_directory(true, TempDir); \
617 raw_os_ostream(std::cerr) << TempDir; \
620 ::testing::ExitedWithCode(0), path2regex(expected))
622 TEST(SupportDeathTest
, TempDirectoryOnWindows
) {
623 // In this test we want to check how system_temp_directory responds to
624 // different values of specific env vars. To prevent corrupting env vars of
625 // the current process all checks are done in separated processes.
626 EXPECT_TEMP_DIR(_wputenv_s(L
"TMP", L
"C:\\OtherFolder"), "C:\\OtherFolder");
627 EXPECT_TEMP_DIR(_wputenv_s(L
"TMP", L
"C:/Unix/Path/Seperators"),
628 "C:\\Unix\\Path\\Seperators");
629 EXPECT_TEMP_DIR(_wputenv_s(L
"TMP", L
"Local Path"), ".+\\Local Path$");
630 EXPECT_TEMP_DIR(_wputenv_s(L
"TMP", L
"F:\\TrailingSep\\"), "F:\\TrailingSep");
632 _wputenv_s(L
"TMP", L
"C:\\2\x03C0r-\x00B5\x00B3\\\x2135\x2080"),
633 "C:\\2\xCF\x80r-\xC2\xB5\xC2\xB3\\\xE2\x84\xB5\xE2\x82\x80");
635 // Test $TMP empty, $TEMP set.
638 _wputenv_s(L
"TMP", L
"");
639 _wputenv_s(L
"TEMP", L
"C:\\Valid\\Path");
643 // All related env vars empty
646 _wputenv_s(L
"TMP", L
"");
647 _wputenv_s(L
"TEMP", L
"");
648 _wputenv_s(L
"USERPROFILE", L
"");
652 // Test evn var / path with 260 chars.
653 SmallString
<270> Expected
{"C:\\Temp\\AB\\123456789"};
654 while (Expected
.size() < 260)
655 Expected
.append("\\DirNameWith19Charss");
656 ASSERT_EQ(260U, Expected
.size());
657 EXPECT_TEMP_DIR(_putenv_s("TMP", Expected
.c_str()), Expected
.c_str());
661 class FileSystemTest
: public testing::Test
{
663 /// Unique temporary directory in which all created filesystem entities must
664 /// be placed. It is removed at the end of each test (must be empty).
665 SmallString
<128> TestDirectory
;
666 SmallString
<128> NonExistantFile
;
668 void SetUp() override
{
670 fs::createUniqueDirectory("file-system-test", TestDirectory
));
671 // We don't care about this specific file.
672 errs() << "Test Directory: " << TestDirectory
<< '\n';
674 NonExistantFile
= TestDirectory
;
676 // Even though this value is hardcoded, is a 128-bit GUID, so we should be
677 // guaranteed that this file will never exist.
678 sys::path::append(NonExistantFile
, "1B28B495C16344CB9822E588CD4C3EF0");
681 void TearDown() override
{ ASSERT_NO_ERROR(fs::remove(TestDirectory
.str())); }
684 TEST_F(FileSystemTest
, Unique
) {
685 // Create a temp file.
687 SmallString
<64> TempPath
;
689 fs::createTemporaryFile("prefix", "temp", FileDescriptor
, TempPath
));
691 // The same file should return an identical unique id.
693 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath
), F1
));
694 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath
), F2
));
697 // Different files should return different unique ids.
699 SmallString
<64> TempPath2
;
701 fs::createTemporaryFile("prefix", "temp", FileDescriptor2
, TempPath2
));
704 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2
), D
));
706 ::close(FileDescriptor2
);
708 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2
)));
710 // Two paths representing the same file on disk should still provide the
711 // same unique id. We can test this by making a hard link.
712 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath
), Twine(TempPath2
)));
714 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2
), D2
));
717 ::close(FileDescriptor
);
719 SmallString
<128> Dir1
;
721 fs::createUniqueDirectory("dir1", Dir1
));
722 ASSERT_NO_ERROR(fs::getUniqueID(Dir1
.c_str(), F1
));
723 ASSERT_NO_ERROR(fs::getUniqueID(Dir1
.c_str(), F2
));
726 SmallString
<128> Dir2
;
728 fs::createUniqueDirectory("dir2", Dir2
));
729 ASSERT_NO_ERROR(fs::getUniqueID(Dir2
.c_str(), F2
));
731 ASSERT_NO_ERROR(fs::remove(Dir1
));
732 ASSERT_NO_ERROR(fs::remove(Dir2
));
733 ASSERT_NO_ERROR(fs::remove(TempPath2
));
734 ASSERT_NO_ERROR(fs::remove(TempPath
));
737 TEST_F(FileSystemTest
, RealPath
) {
739 fs::create_directories(Twine(TestDirectory
) + "/test1/test2/test3"));
740 ASSERT_TRUE(fs::exists(Twine(TestDirectory
) + "/test1/test2/test3"));
742 SmallString
<64> RealBase
;
743 SmallString
<64> Expected
;
744 SmallString
<64> Actual
;
746 // TestDirectory itself might be under a symlink or have been specified with
747 // a different case than the existing temp directory. In such cases real_path
748 // on the concatenated path will differ in the TestDirectory portion from
749 // how we specified it. Make sure to compare against the real_path of the
750 // TestDirectory, and not just the value of TestDirectory.
751 ASSERT_NO_ERROR(fs::real_path(TestDirectory
, RealBase
));
752 checkSeparators(RealBase
);
753 path::native(Twine(RealBase
) + "/test1/test2", Expected
);
755 ASSERT_NO_ERROR(fs::real_path(
756 Twine(TestDirectory
) + "/././test1/../test1/test2/./test3/..", Actual
));
757 checkSeparators(Actual
);
759 EXPECT_EQ(Expected
, Actual
);
761 SmallString
<64> HomeDir
;
763 // This can fail if $HOME is not set and getpwuid fails.
764 bool Result
= llvm::sys::path::home_directory(HomeDir
);
766 checkSeparators(HomeDir
);
767 ASSERT_NO_ERROR(fs::real_path(HomeDir
, Expected
));
768 checkSeparators(Expected
);
769 ASSERT_NO_ERROR(fs::real_path("~", Actual
, true));
770 EXPECT_EQ(Expected
, Actual
);
771 ASSERT_NO_ERROR(fs::real_path("~/", Actual
, true));
772 EXPECT_EQ(Expected
, Actual
);
775 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory
) + "/test1"));
778 TEST_F(FileSystemTest
, ExpandTilde
) {
779 SmallString
<64> Expected
;
780 SmallString
<64> Actual
;
781 SmallString
<64> HomeDir
;
783 // This can fail if $HOME is not set and getpwuid fails.
784 bool Result
= llvm::sys::path::home_directory(HomeDir
);
786 fs::expand_tilde(HomeDir
, Expected
);
788 fs::expand_tilde("~", Actual
);
789 EXPECT_EQ(Expected
, Actual
);
793 fs::expand_tilde("~\\foo", Actual
);
796 fs::expand_tilde("~/foo", Actual
);
799 EXPECT_EQ(Expected
, Actual
);
804 TEST_F(FileSystemTest
, RealPathNoReadPerm
) {
805 SmallString
<64> Expanded
;
808 fs::create_directories(Twine(TestDirectory
) + "/noreadperm"));
809 ASSERT_TRUE(fs::exists(Twine(TestDirectory
) + "/noreadperm"));
811 fs::setPermissions(Twine(TestDirectory
) + "/noreadperm", fs::no_perms
);
812 fs::setPermissions(Twine(TestDirectory
) + "/noreadperm", fs::all_exe
);
814 ASSERT_NO_ERROR(fs::real_path(Twine(TestDirectory
) + "/noreadperm", Expanded
,
817 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory
) + "/noreadperm"));
819 TEST_F(FileSystemTest
, RemoveDirectoriesNoExePerm
) {
820 SmallString
<64> Expanded
;
823 fs::create_directories(Twine(TestDirectory
) + "/noexeperm/foo"));
824 ASSERT_TRUE(fs::exists(Twine(TestDirectory
) + "/noexeperm/foo"));
826 fs::setPermissions(Twine(TestDirectory
) + "/noexeperm",
827 fs::all_read
| fs::all_write
);
829 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory
) + "/noexeperm",
830 /*IgnoreErrors=*/true));
832 // It's expected that the directory exists, but some environments appear to
833 // allow the removal despite missing the 'x' permission, so be flexible.
834 if (fs::exists(Twine(TestDirectory
) + "/noexeperm")) {
835 fs::setPermissions(Twine(TestDirectory
) + "/noexeperm", fs::all_perms
);
836 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory
) + "/noexeperm",
837 /*IgnoreErrors=*/false));
843 TEST_F(FileSystemTest
, TempFileKeepDiscard
) {
844 // We can keep then discard.
845 auto TempFileOrError
= fs::TempFile::create(TestDirectory
+ "/test-%%%%");
846 ASSERT_TRUE((bool)TempFileOrError
);
847 fs::TempFile File
= std::move(*TempFileOrError
);
848 ASSERT_EQ(-1, TempFileOrError
->FD
);
849 ASSERT_FALSE((bool)File
.keep(TestDirectory
+ "/keep"));
850 ASSERT_FALSE((bool)File
.discard());
851 ASSERT_TRUE(fs::exists(TestDirectory
+ "/keep"));
852 ASSERT_NO_ERROR(fs::remove(TestDirectory
+ "/keep"));
855 TEST_F(FileSystemTest
, TempFileDiscardDiscard
) {
856 // We can discard twice.
857 auto TempFileOrError
= fs::TempFile::create(TestDirectory
+ "/test-%%%%");
858 ASSERT_TRUE((bool)TempFileOrError
);
859 fs::TempFile File
= std::move(*TempFileOrError
);
860 ASSERT_EQ(-1, TempFileOrError
->FD
);
861 ASSERT_FALSE((bool)File
.discard());
862 ASSERT_FALSE((bool)File
.discard());
863 ASSERT_FALSE(fs::exists(TestDirectory
+ "/keep"));
866 TEST_F(FileSystemTest
, TempFiles
) {
867 // Create a temp file.
869 SmallString
<64> TempPath
;
871 fs::createTemporaryFile("prefix", "temp", FileDescriptor
, TempPath
));
873 // Make sure it exists.
874 ASSERT_TRUE(sys::fs::exists(Twine(TempPath
)));
876 // Create another temp tile.
878 SmallString
<64> TempPath2
;
879 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD2
, TempPath2
));
880 ASSERT_TRUE(TempPath2
.endswith(".temp"));
881 ASSERT_NE(TempPath
.str(), TempPath2
.str());
883 fs::file_status A
, B
;
884 ASSERT_NO_ERROR(fs::status(Twine(TempPath
), A
));
885 ASSERT_NO_ERROR(fs::status(Twine(TempPath2
), B
));
886 EXPECT_FALSE(fs::equivalent(A
, B
));
891 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2
)));
892 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2
)));
893 ASSERT_EQ(fs::remove(Twine(TempPath2
), false),
894 errc::no_such_file_or_directory
);
896 std::error_code EC
= fs::status(TempPath2
.c_str(), B
);
897 EXPECT_EQ(EC
, errc::no_such_file_or_directory
);
898 EXPECT_EQ(B
.type(), fs::file_type::file_not_found
);
900 // Make sure Temp2 doesn't exist.
901 ASSERT_EQ(fs::access(Twine(TempPath2
), sys::fs::AccessMode::Exist
),
902 errc::no_such_file_or_directory
);
904 SmallString
<64> TempPath3
;
905 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "", TempPath3
));
906 ASSERT_FALSE(TempPath3
.endswith("."));
907 FileRemover
Cleanup3(TempPath3
);
909 // Create a hard link to Temp1.
910 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath
), Twine(TempPath2
)));
912 ASSERT_NO_ERROR(fs::equivalent(Twine(TempPath
), Twine(TempPath2
), equal
));
914 ASSERT_NO_ERROR(fs::status(Twine(TempPath
), A
));
915 ASSERT_NO_ERROR(fs::status(Twine(TempPath2
), B
));
916 EXPECT_TRUE(fs::equivalent(A
, B
));
919 ::close(FileDescriptor
);
920 ASSERT_NO_ERROR(fs::remove(Twine(TempPath
)));
922 // Remove the hard link.
923 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2
)));
925 // Make sure Temp1 doesn't exist.
926 ASSERT_EQ(fs::access(Twine(TempPath
), sys::fs::AccessMode::Exist
),
927 errc::no_such_file_or_directory
);
930 // Path name > 260 chars should get an error.
931 const char *Path270
=
932 "abcdefghijklmnopqrstuvwxyz9abcdefghijklmnopqrstuvwxyz8"
933 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
934 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
935 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
936 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
937 EXPECT_EQ(fs::createUniqueFile(Path270
, FileDescriptor
, TempPath
),
938 errc::invalid_argument
);
939 // Relative path < 247 chars, no problem.
940 const char *Path216
=
941 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
942 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
943 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
944 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
945 ASSERT_NO_ERROR(fs::createTemporaryFile(Path216
, "", TempPath
));
946 ASSERT_NO_ERROR(fs::remove(Twine(TempPath
)));
950 TEST_F(FileSystemTest
, TempFileCollisions
) {
951 SmallString
<128> TestDirectory
;
953 fs::createUniqueDirectory("CreateUniqueFileTest", TestDirectory
));
954 FileRemover
Cleanup(TestDirectory
);
955 SmallString
<128> Model
= TestDirectory
;
956 path::append(Model
, "%.tmp");
957 SmallString
<128> Path
;
958 std::vector
<fs::TempFile
> TempFiles
;
960 auto TryCreateTempFile
= [&]() {
961 Expected
<fs::TempFile
> T
= fs::TempFile::create(Model
);
963 TempFiles
.push_back(std::move(*T
));
966 logAllUnhandledErrors(T
.takeError(), errs(),
967 "Failed to create temporary file: ");
972 // Our single-character template allows for 16 unique names. Check that
973 // calling TryCreateTempFile repeatedly results in 16 successes.
974 // Because the test depends on random numbers, it could theoretically fail.
975 // However, the probability of this happening is tiny: with 32 calls, each
976 // of which will retry up to 128 times, to not get a given digit we would
977 // have to fail at least 15 + 17 * 128 = 2191 attempts. The probability of
978 // 2191 attempts not producing a given hexadecimal digit is
979 // (1 - 1/16) ** 2191 or 3.88e-62.
981 for (int i
= 0; i
< 32; ++i
)
982 if (TryCreateTempFile()) ++Successes
;
983 EXPECT_EQ(Successes
, 16);
985 for (fs::TempFile
&T
: TempFiles
)
986 cantFail(T
.discard());
989 TEST_F(FileSystemTest
, CreateDir
) {
990 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory
) + "foo"));
991 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory
) + "foo"));
992 ASSERT_EQ(fs::create_directory(Twine(TestDirectory
) + "foo", false),
994 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "foo"));
997 // Set a 0000 umask so that we can test our directory permissions.
998 mode_t OldUmask
= ::umask(0000);
1000 fs::file_status Status
;
1002 fs::create_directory(Twine(TestDirectory
) + "baz500", false,
1003 fs::perms::owner_read
| fs::perms::owner_exe
));
1004 ASSERT_NO_ERROR(fs::status(Twine(TestDirectory
) + "baz500", Status
));
1005 ASSERT_EQ(Status
.permissions() & fs::perms::all_all
,
1006 fs::perms::owner_read
| fs::perms::owner_exe
);
1007 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory
) + "baz777", false,
1008 fs::perms::all_all
));
1009 ASSERT_NO_ERROR(fs::status(Twine(TestDirectory
) + "baz777", Status
));
1010 ASSERT_EQ(Status
.permissions() & fs::perms::all_all
, fs::perms::all_all
);
1012 // Restore umask to be safe.
1017 // Prove that create_directories() can handle a pathname > 248 characters,
1018 // which is the documented limit for CreateDirectory().
1019 // (248 is MAX_PATH subtracting room for an 8.3 filename.)
1020 // Generate a directory path guaranteed to fall into that range.
1021 size_t TmpLen
= TestDirectory
.size();
1022 const char *OneDir
= "\\123456789";
1023 size_t OneDirLen
= strlen(OneDir
);
1024 ASSERT_LT(OneDirLen
, 12U);
1025 size_t NLevels
= ((248 - TmpLen
) / OneDirLen
) + 1;
1026 SmallString
<260> LongDir(TestDirectory
);
1027 for (size_t I
= 0; I
< NLevels
; ++I
)
1028 LongDir
.append(OneDir
);
1029 ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir
)));
1030 ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir
)));
1031 ASSERT_EQ(fs::create_directories(Twine(LongDir
), false),
1033 // Tidy up, "recursively" removing the directories.
1034 StringRef
ThisDir(LongDir
);
1035 for (size_t J
= 0; J
< NLevels
; ++J
) {
1036 ASSERT_NO_ERROR(fs::remove(ThisDir
));
1037 ThisDir
= path::parent_path(ThisDir
);
1040 // Also verify that paths with Unix separators are handled correctly.
1041 std::string
LongPathWithUnixSeparators(TestDirectory
.str());
1042 // Add at least one subdirectory to TestDirectory, and replace slashes with
1045 LongPathWithUnixSeparators
.append("/DirNameWith19Charss");
1046 } while (LongPathWithUnixSeparators
.size() < 260);
1047 std::replace(LongPathWithUnixSeparators
.begin(),
1048 LongPathWithUnixSeparators
.end(),
1050 ASSERT_NO_ERROR(fs::create_directories(Twine(LongPathWithUnixSeparators
)));
1052 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory
) +
1053 "/DirNameWith19Charss"));
1055 // Similarly for a relative pathname. Need to set the current directory to
1056 // TestDirectory so that the one we create ends up in the right place.
1057 char PreviousDir
[260];
1058 size_t PreviousDirLen
= ::GetCurrentDirectoryA(260, PreviousDir
);
1059 ASSERT_GT(PreviousDirLen
, 0U);
1060 ASSERT_LT(PreviousDirLen
, 260U);
1061 ASSERT_NE(::SetCurrentDirectoryA(TestDirectory
.c_str()), 0);
1063 // Generate a relative directory name with absolute length > 248.
1064 size_t LongDirLen
= 249 - TestDirectory
.size();
1065 LongDir
.assign(LongDirLen
, 'a');
1066 ASSERT_NO_ERROR(fs::create_directory(Twine(LongDir
)));
1067 // While we're here, prove that .. and . handling works in these long paths.
1068 const char *DotDotDirs
= "\\..\\.\\b";
1069 LongDir
.append(DotDotDirs
);
1070 ASSERT_NO_ERROR(fs::create_directory("b"));
1071 ASSERT_EQ(fs::create_directory(Twine(LongDir
), false), errc::file_exists
);
1073 ASSERT_NO_ERROR(fs::remove("b"));
1074 ASSERT_NO_ERROR(fs::remove(
1075 Twine(LongDir
.substr(0, LongDir
.size() - strlen(DotDotDirs
)))));
1076 ASSERT_NE(::SetCurrentDirectoryA(PreviousDir
), 0);
1080 TEST_F(FileSystemTest
, DirectoryIteration
) {
1082 for (fs::directory_iterator
i(".", ec
), e
; i
!= e
; i
.increment(ec
))
1083 ASSERT_NO_ERROR(ec
);
1085 // Create a known hierarchy to recurse over.
1087 fs::create_directories(Twine(TestDirectory
) + "/recursive/a0/aa1"));
1089 fs::create_directories(Twine(TestDirectory
) + "/recursive/a0/ab1"));
1090 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory
) +
1091 "/recursive/dontlookhere/da1"));
1093 fs::create_directories(Twine(TestDirectory
) + "/recursive/z0/za1"));
1095 fs::create_directories(Twine(TestDirectory
) + "/recursive/pop/p1"));
1096 typedef std::vector
<std::string
> v_t
;
1098 for (fs::recursive_directory_iterator
i(Twine(TestDirectory
)
1099 + "/recursive", ec
), e
; i
!= e
; i
.increment(ec
)){
1100 ASSERT_NO_ERROR(ec
);
1101 if (path::filename(i
->path()) == "p1") {
1103 // FIXME: recursive_directory_iterator should be more robust.
1106 if (path::filename(i
->path()) == "dontlookhere")
1108 visited
.push_back(std::string(path::filename(i
->path())));
1110 v_t::const_iterator a0
= find(visited
, "a0");
1111 v_t::const_iterator aa1
= find(visited
, "aa1");
1112 v_t::const_iterator ab1
= find(visited
, "ab1");
1113 v_t::const_iterator dontlookhere
= find(visited
, "dontlookhere");
1114 v_t::const_iterator da1
= find(visited
, "da1");
1115 v_t::const_iterator z0
= find(visited
, "z0");
1116 v_t::const_iterator za1
= find(visited
, "za1");
1117 v_t::const_iterator pop
= find(visited
, "pop");
1118 v_t::const_iterator p1
= find(visited
, "p1");
1120 // Make sure that each path was visited correctly.
1121 ASSERT_NE(a0
, visited
.end());
1122 ASSERT_NE(aa1
, visited
.end());
1123 ASSERT_NE(ab1
, visited
.end());
1124 ASSERT_NE(dontlookhere
, visited
.end());
1125 ASSERT_EQ(da1
, visited
.end()); // Not visited.
1126 ASSERT_NE(z0
, visited
.end());
1127 ASSERT_NE(za1
, visited
.end());
1128 ASSERT_NE(pop
, visited
.end());
1129 ASSERT_EQ(p1
, visited
.end()); // Not visited.
1131 // Make sure that parents were visited before children. No other ordering
1132 // guarantees can be made across siblings.
1137 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/a0/aa1"));
1138 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/a0/ab1"));
1139 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/a0"));
1141 fs::remove(Twine(TestDirectory
) + "/recursive/dontlookhere/da1"));
1142 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/dontlookhere"));
1143 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/pop/p1"));
1144 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/pop"));
1145 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/z0/za1"));
1146 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive/z0"));
1147 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/recursive"));
1149 // Test recursive_directory_iterator level()
1151 fs::create_directories(Twine(TestDirectory
) + "/reclevel/a/b/c"));
1152 fs::recursive_directory_iterator
I(Twine(TestDirectory
) + "/reclevel", ec
), E
;
1153 for (int l
= 0; I
!= E
; I
.increment(ec
), ++l
) {
1154 ASSERT_NO_ERROR(ec
);
1155 EXPECT_EQ(I
.level(), l
);
1158 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/reclevel/a/b/c"));
1159 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/reclevel/a/b"));
1160 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/reclevel/a"));
1161 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
) + "/reclevel"));
1164 TEST_F(FileSystemTest
, DirectoryNotExecutable
) {
1165 ASSERT_EQ(fs::access(TestDirectory
, sys::fs::AccessMode::Execute
),
1166 errc::permission_denied
);
1170 TEST_F(FileSystemTest
, BrokenSymlinkDirectoryIteration
) {
1171 // Create a known hierarchy to recurse over.
1172 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory
) + "/symlink"));
1174 fs::create_link("no_such_file", Twine(TestDirectory
) + "/symlink/a"));
1176 fs::create_directories(Twine(TestDirectory
) + "/symlink/b/bb"));
1178 fs::create_link("no_such_file", Twine(TestDirectory
) + "/symlink/b/ba"));
1180 fs::create_link("no_such_file", Twine(TestDirectory
) + "/symlink/b/bc"));
1182 fs::create_link("no_such_file", Twine(TestDirectory
) + "/symlink/c"));
1184 fs::create_directories(Twine(TestDirectory
) + "/symlink/d/dd/ddd"));
1185 ASSERT_NO_ERROR(fs::create_link(Twine(TestDirectory
) + "/symlink/d/dd",
1186 Twine(TestDirectory
) + "/symlink/d/da"));
1188 fs::create_link("no_such_file", Twine(TestDirectory
) + "/symlink/e"));
1190 typedef std::vector
<std::string
> v_t
;
1191 v_t VisitedNonBrokenSymlinks
;
1192 v_t VisitedBrokenSymlinks
;
1194 using testing::UnorderedElementsAre
;
1195 using testing::UnorderedElementsAreArray
;
1197 // Broken symbol links are expected to throw an error.
1198 for (fs::directory_iterator
i(Twine(TestDirectory
) + "/symlink", ec
), e
;
1199 i
!= e
; i
.increment(ec
)) {
1200 ASSERT_NO_ERROR(ec
);
1201 if (i
->status().getError() ==
1202 std::make_error_code(std::errc::no_such_file_or_directory
)) {
1203 VisitedBrokenSymlinks
.push_back(std::string(path::filename(i
->path())));
1206 VisitedNonBrokenSymlinks
.push_back(std::string(path::filename(i
->path())));
1208 EXPECT_THAT(VisitedNonBrokenSymlinks
, UnorderedElementsAre("b", "d"));
1209 VisitedNonBrokenSymlinks
.clear();
1211 EXPECT_THAT(VisitedBrokenSymlinks
, UnorderedElementsAre("a", "c", "e"));
1212 VisitedBrokenSymlinks
.clear();
1214 // Broken symbol links are expected to throw an error.
1215 for (fs::recursive_directory_iterator
i(
1216 Twine(TestDirectory
) + "/symlink", ec
), e
; i
!= e
; i
.increment(ec
)) {
1217 ASSERT_NO_ERROR(ec
);
1218 if (i
->status().getError() ==
1219 std::make_error_code(std::errc::no_such_file_or_directory
)) {
1220 VisitedBrokenSymlinks
.push_back(std::string(path::filename(i
->path())));
1223 VisitedNonBrokenSymlinks
.push_back(std::string(path::filename(i
->path())));
1225 EXPECT_THAT(VisitedNonBrokenSymlinks
,
1226 UnorderedElementsAre("b", "bb", "d", "da", "dd", "ddd", "ddd"));
1227 VisitedNonBrokenSymlinks
.clear();
1229 EXPECT_THAT(VisitedBrokenSymlinks
,
1230 UnorderedElementsAre("a", "ba", "bc", "c", "e"));
1231 VisitedBrokenSymlinks
.clear();
1233 for (fs::recursive_directory_iterator
i(
1234 Twine(TestDirectory
) + "/symlink", ec
, /*follow_symlinks=*/false), e
;
1235 i
!= e
; i
.increment(ec
)) {
1236 ASSERT_NO_ERROR(ec
);
1237 if (i
->status().getError() ==
1238 std::make_error_code(std::errc::no_such_file_or_directory
)) {
1239 VisitedBrokenSymlinks
.push_back(std::string(path::filename(i
->path())));
1242 VisitedNonBrokenSymlinks
.push_back(std::string(path::filename(i
->path())));
1244 EXPECT_THAT(VisitedNonBrokenSymlinks
,
1245 UnorderedElementsAreArray({"a", "b", "ba", "bb", "bc", "c", "d",
1246 "da", "dd", "ddd", "e"}));
1247 VisitedNonBrokenSymlinks
.clear();
1249 EXPECT_THAT(VisitedBrokenSymlinks
, UnorderedElementsAre());
1250 VisitedBrokenSymlinks
.clear();
1252 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory
) + "/symlink"));
1257 TEST_F(FileSystemTest
, UTF8ToUTF16DirectoryIteration
) {
1258 // The Windows filesystem support uses UTF-16 and converts paths from the
1259 // input UTF-8. The UTF-16 equivalent of the input path can be shorter in
1262 // This test relies on TestDirectory not being so long such that MAX_PATH
1263 // would be exceeded (see widenPath). If that were the case, the UTF-16
1264 // path is likely to be longer than the input.
1265 const char *Pi
= "\xcf\x80"; // UTF-8 lower case pi.
1266 std::string RootDir
= (TestDirectory
+ "/" + Pi
).str();
1268 // Create test directories.
1269 ASSERT_NO_ERROR(fs::create_directories(Twine(RootDir
) + "/a"));
1270 ASSERT_NO_ERROR(fs::create_directories(Twine(RootDir
) + "/b"));
1274 for (fs::directory_iterator
I(Twine(RootDir
), EC
), E
; I
!= E
;
1276 ASSERT_NO_ERROR(EC
);
1277 StringRef DirName
= path::filename(I
->path());
1278 EXPECT_TRUE(DirName
== "a" || DirName
== "b");
1281 EXPECT_EQ(Count
, 2U);
1283 ASSERT_NO_ERROR(fs::remove(Twine(RootDir
) + "/a"));
1284 ASSERT_NO_ERROR(fs::remove(Twine(RootDir
) + "/b"));
1285 ASSERT_NO_ERROR(fs::remove(Twine(RootDir
)));
1289 TEST_F(FileSystemTest
, Remove
) {
1290 SmallString
<64> BaseDir
;
1291 SmallString
<64> Paths
[4];
1293 ASSERT_NO_ERROR(fs::createUniqueDirectory("fs_remove", BaseDir
));
1295 ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir
) + "/foo/bar/baz"));
1296 ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir
) + "/foo/bar/buzz"));
1297 ASSERT_NO_ERROR(fs::createUniqueFile(
1298 Twine(BaseDir
) + "/foo/bar/baz/%%%%%%.tmp", fds
[0], Paths
[0]));
1299 ASSERT_NO_ERROR(fs::createUniqueFile(
1300 Twine(BaseDir
) + "/foo/bar/baz/%%%%%%.tmp", fds
[1], Paths
[1]));
1301 ASSERT_NO_ERROR(fs::createUniqueFile(
1302 Twine(BaseDir
) + "/foo/bar/buzz/%%%%%%.tmp", fds
[2], Paths
[2]));
1303 ASSERT_NO_ERROR(fs::createUniqueFile(
1304 Twine(BaseDir
) + "/foo/bar/buzz/%%%%%%.tmp", fds
[3], Paths
[3]));
1309 EXPECT_TRUE(fs::exists(Twine(BaseDir
) + "/foo/bar/baz"));
1310 EXPECT_TRUE(fs::exists(Twine(BaseDir
) + "/foo/bar/buzz"));
1311 EXPECT_TRUE(fs::exists(Paths
[0]));
1312 EXPECT_TRUE(fs::exists(Paths
[1]));
1313 EXPECT_TRUE(fs::exists(Paths
[2]));
1314 EXPECT_TRUE(fs::exists(Paths
[3]));
1316 ASSERT_NO_ERROR(fs::remove_directories("D:/footest"));
1318 ASSERT_NO_ERROR(fs::remove_directories(BaseDir
));
1319 ASSERT_FALSE(fs::exists(BaseDir
));
1323 TEST_F(FileSystemTest
, CarriageReturn
) {
1324 SmallString
<128> FilePathname(TestDirectory
);
1326 path::append(FilePathname
, "test");
1329 raw_fd_ostream
File(FilePathname
, EC
, sys::fs::OF_TextWithCRLF
);
1330 ASSERT_NO_ERROR(EC
);
1334 auto Buf
= MemoryBuffer::getFile(FilePathname
.str());
1335 EXPECT_TRUE((bool)Buf
);
1336 EXPECT_EQ(Buf
.get()->getBuffer(), "\r\n");
1340 raw_fd_ostream
File(FilePathname
, EC
, sys::fs::OF_None
);
1341 ASSERT_NO_ERROR(EC
);
1345 auto Buf
= MemoryBuffer::getFile(FilePathname
.str());
1346 EXPECT_TRUE((bool)Buf
);
1347 EXPECT_EQ(Buf
.get()->getBuffer(), "\n");
1349 ASSERT_NO_ERROR(fs::remove(Twine(FilePathname
)));
1353 TEST_F(FileSystemTest
, Resize
) {
1355 SmallString
<64> TempPath
;
1356 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD
, TempPath
));
1357 ASSERT_NO_ERROR(fs::resize_file(FD
, 123));
1358 fs::file_status Status
;
1359 ASSERT_NO_ERROR(fs::status(FD
, Status
));
1360 ASSERT_EQ(Status
.getSize(), 123U);
1362 ASSERT_NO_ERROR(fs::remove(TempPath
));
1365 TEST_F(FileSystemTest
, ResizeBeforeMapping
) {
1366 // Create a temp file.
1368 SmallString
<64> TempPath
;
1369 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD
, TempPath
));
1370 ASSERT_NO_ERROR(fs::resize_file_before_mapping_readwrite(FD
, 123));
1372 // Map in temp file. On Windows, fs::resize_file_before_mapping_readwrite is
1373 // a no-op and the mapping itself will resize the file.
1376 fs::mapped_file_region
mfr(fs::convertFDToNativeFile(FD
),
1377 fs::mapped_file_region::readwrite
, 123, 0, EC
);
1378 ASSERT_NO_ERROR(EC
);
1383 fs::file_status Status
;
1384 ASSERT_NO_ERROR(fs::status(FD
, Status
));
1385 ASSERT_EQ(Status
.getSize(), 123U);
1387 ASSERT_NO_ERROR(fs::remove(TempPath
));
1390 TEST_F(FileSystemTest
, MD5
) {
1392 SmallString
<64> TempPath
;
1393 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD
, TempPath
));
1394 StringRef
Data("abcdefghijklmnopqrstuvwxyz");
1395 ASSERT_EQ(write(FD
, Data
.data(), Data
.size()), static_cast<ssize_t
>(Data
.size()));
1396 lseek(FD
, 0, SEEK_SET
);
1397 auto Hash
= fs::md5_contents(FD
);
1399 ASSERT_NO_ERROR(Hash
.getError());
1401 EXPECT_STREQ("c3fcd3d76192e4007dfb496cca67e13b", Hash
->digest().c_str());
1404 TEST_F(FileSystemTest
, FileMapping
) {
1405 // Create a temp file.
1407 SmallString
<64> TempPath
;
1409 fs::createTemporaryFile("prefix", "temp", FileDescriptor
, TempPath
));
1410 unsigned Size
= 4096;
1412 fs::resize_file_before_mapping_readwrite(FileDescriptor
, Size
));
1414 // Map in temp file and add some content
1416 StringRef
Val("hello there");
1417 fs::mapped_file_region MaybeMFR
;
1418 EXPECT_FALSE(MaybeMFR
);
1420 fs::mapped_file_region
mfr(fs::convertFDToNativeFile(FileDescriptor
),
1421 fs::mapped_file_region::readwrite
, Size
, 0, EC
);
1422 ASSERT_NO_ERROR(EC
);
1423 std::copy(Val
.begin(), Val
.end(), mfr
.data());
1424 // Explicitly add a 0.
1425 mfr
.data()[Val
.size()] = 0;
1427 // Move it out of the scope and confirm mfr is reset.
1428 MaybeMFR
= std::move(mfr
);
1430 #if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST
1431 EXPECT_DEATH(mfr
.data(), "Mapping failed but used anyway!");
1432 EXPECT_DEATH(mfr
.size(), "Mapping failed but used anyway!");
1436 // Check that the moved-to region is still valid.
1437 EXPECT_EQ(Val
, StringRef(MaybeMFR
.data()));
1438 EXPECT_EQ(Size
, MaybeMFR
.size());
1443 ASSERT_EQ(close(FileDescriptor
), 0);
1445 // Map it back in read-only
1448 EC
= fs::openFileForRead(Twine(TempPath
), FD
);
1449 ASSERT_NO_ERROR(EC
);
1450 fs::mapped_file_region
mfr(fs::convertFDToNativeFile(FD
),
1451 fs::mapped_file_region::readonly
, Size
, 0, EC
);
1452 ASSERT_NO_ERROR(EC
);
1455 EXPECT_EQ(StringRef(mfr
.const_data()), Val
);
1458 fs::mapped_file_region
m(fs::convertFDToNativeFile(FD
),
1459 fs::mapped_file_region::readonly
, Size
, 0, EC
);
1460 ASSERT_NO_ERROR(EC
);
1461 ASSERT_EQ(close(FD
), 0);
1463 ASSERT_NO_ERROR(fs::remove(TempPath
));
1466 TEST(Support
, NormalizePath
) {
1467 // Input, Expected Win, Expected Posix
1468 using TestTuple
= std::tuple
<const char *, const char *, const char *>;
1469 std::vector
<TestTuple
> Tests
;
1470 Tests
.emplace_back("a", "a", "a");
1471 Tests
.emplace_back("a/b", "a\\b", "a/b");
1472 Tests
.emplace_back("a\\b", "a\\b", "a/b");
1473 Tests
.emplace_back("a\\\\b", "a\\\\b", "a//b");
1474 Tests
.emplace_back("\\a", "\\a", "/a");
1475 Tests
.emplace_back("a\\", "a\\", "a/");
1476 Tests
.emplace_back("a\\t", "a\\t", "a/t");
1478 for (auto &T
: Tests
) {
1479 SmallString
<64> Win(std::get
<0>(T
));
1480 SmallString
<64> Posix(Win
);
1481 SmallString
<64> WinSlash(Win
);
1482 path::native(Win
, path::Style::windows
);
1483 path::native(Posix
, path::Style::posix
);
1484 path::native(WinSlash
, path::Style::windows_slash
);
1485 EXPECT_EQ(std::get
<1>(T
), Win
);
1486 EXPECT_EQ(std::get
<2>(T
), Posix
);
1487 EXPECT_EQ(std::get
<2>(T
), WinSlash
);
1490 for (auto &T
: Tests
) {
1491 SmallString
<64> WinBackslash(std::get
<0>(T
));
1492 SmallString
<64> Posix(WinBackslash
);
1493 SmallString
<64> WinSlash(WinBackslash
);
1494 path::make_preferred(WinBackslash
, path::Style::windows_backslash
);
1495 path::make_preferred(Posix
, path::Style::posix
);
1496 path::make_preferred(WinSlash
, path::Style::windows_slash
);
1497 EXPECT_EQ(std::get
<1>(T
), WinBackslash
);
1498 EXPECT_EQ(std::get
<0>(T
), Posix
); // Posix remains unchanged here
1499 EXPECT_EQ(std::get
<2>(T
), WinSlash
);
1503 SmallString
<64> PathHome
;
1504 path::home_directory(PathHome
);
1506 const char *Path7a
= "~/aaa";
1507 SmallString
<64> Path7(Path7a
);
1508 path::native(Path7
, path::Style::windows_backslash
);
1509 EXPECT_TRUE(Path7
.endswith("\\aaa"));
1510 EXPECT_TRUE(Path7
.startswith(PathHome
));
1511 EXPECT_EQ(Path7
.size(), PathHome
.size() + strlen(Path7a
+ 1));
1513 path::native(Path7
, path::Style::windows_slash
);
1514 EXPECT_TRUE(Path7
.endswith("/aaa"));
1515 EXPECT_TRUE(Path7
.startswith(PathHome
));
1516 EXPECT_EQ(Path7
.size(), PathHome
.size() + strlen(Path7a
+ 1));
1518 const char *Path8a
= "~";
1519 SmallString
<64> Path8(Path8a
);
1520 path::native(Path8
);
1521 EXPECT_EQ(Path8
, PathHome
);
1523 const char *Path9a
= "~aaa";
1524 SmallString
<64> Path9(Path9a
);
1525 path::native(Path9
);
1526 EXPECT_EQ(Path9
, "~aaa");
1528 const char *Path10a
= "aaa/~/b";
1529 SmallString
<64> Path10(Path10a
);
1530 path::native(Path10
, path::Style::windows_backslash
);
1531 EXPECT_EQ(Path10
, "aaa\\~\\b");
1535 TEST(Support
, RemoveLeadingDotSlash
) {
1536 StringRef
Path1("././/foolz/wat");
1537 StringRef
Path2("./////");
1539 Path1
= path::remove_leading_dotslash(Path1
);
1540 EXPECT_EQ(Path1
, "foolz/wat");
1541 Path2
= path::remove_leading_dotslash(Path2
);
1542 EXPECT_EQ(Path2
, "");
1545 static std::string
remove_dots(StringRef path
, bool remove_dot_dot
,
1546 path::Style style
) {
1547 SmallString
<256> buffer(path
);
1548 path::remove_dots(buffer
, remove_dot_dot
, style
);
1549 return std::string(buffer
.str());
1552 TEST(Support
, RemoveDots
) {
1553 EXPECT_EQ("foolz\\wat",
1554 remove_dots(".\\.\\\\foolz\\wat", false, path::Style::windows
));
1555 EXPECT_EQ("", remove_dots(".\\\\\\\\\\", false, path::Style::windows
));
1557 EXPECT_EQ("a\\..\\b\\c",
1558 remove_dots(".\\a\\..\\b\\c", false, path::Style::windows
));
1559 EXPECT_EQ("b\\c", remove_dots(".\\a\\..\\b\\c", true, path::Style::windows
));
1560 EXPECT_EQ("c", remove_dots(".\\.\\c", true, path::Style::windows
));
1561 EXPECT_EQ("..\\a\\c",
1562 remove_dots("..\\a\\b\\..\\c", true, path::Style::windows
));
1563 EXPECT_EQ("..\\..\\a\\c",
1564 remove_dots("..\\..\\a\\b\\..\\c", true, path::Style::windows
));
1565 EXPECT_EQ("C:\\a\\c", remove_dots("C:\\foo\\bar//..\\..\\a\\c", true,
1566 path::Style::windows
));
1568 EXPECT_EQ("C:\\bar",
1569 remove_dots("C:/foo/../bar", true, path::Style::windows
));
1570 EXPECT_EQ("C:\\foo\\bar",
1571 remove_dots("C:/foo/bar", true, path::Style::windows
));
1572 EXPECT_EQ("C:\\foo\\bar",
1573 remove_dots("C:/foo\\bar", true, path::Style::windows
));
1574 EXPECT_EQ("\\", remove_dots("/", true, path::Style::windows
));
1575 EXPECT_EQ("C:\\", remove_dots("C:/", true, path::Style::windows
));
1577 // Some clients of remove_dots expect it to remove trailing slashes. Again,
1578 // this is emergent behavior that VFS relies on, and not inherently part of
1579 // the specification.
1580 EXPECT_EQ("C:\\foo\\bar",
1581 remove_dots("C:\\foo\\bar\\", true, path::Style::windows
));
1582 EXPECT_EQ("/foo/bar",
1583 remove_dots("/foo/bar/", true, path::Style::posix
));
1585 // A double separator is rewritten.
1586 EXPECT_EQ("C:\\foo\\bar",
1587 remove_dots("C:/foo//bar", true, path::Style::windows
));
1589 SmallString
<64> Path1(".\\.\\c");
1590 EXPECT_TRUE(path::remove_dots(Path1
, true, path::Style::windows
));
1591 EXPECT_EQ("c", Path1
);
1593 EXPECT_EQ("foolz/wat",
1594 remove_dots("././/foolz/wat", false, path::Style::posix
));
1595 EXPECT_EQ("", remove_dots("./////", false, path::Style::posix
));
1597 EXPECT_EQ("a/../b/c", remove_dots("./a/../b/c", false, path::Style::posix
));
1598 EXPECT_EQ("b/c", remove_dots("./a/../b/c", true, path::Style::posix
));
1599 EXPECT_EQ("c", remove_dots("././c", true, path::Style::posix
));
1600 EXPECT_EQ("../a/c", remove_dots("../a/b/../c", true, path::Style::posix
));
1601 EXPECT_EQ("../../a/c",
1602 remove_dots("../../a/b/../c", true, path::Style::posix
));
1603 EXPECT_EQ("/a/c", remove_dots("/../../a/c", true, path::Style::posix
));
1605 remove_dots("/../a/b//../././/c", true, path::Style::posix
));
1606 EXPECT_EQ("/", remove_dots("/", true, path::Style::posix
));
1608 // FIXME: Leaving behind this double leading slash seems like a bug.
1609 EXPECT_EQ("//foo/bar",
1610 remove_dots("//foo/bar/", true, path::Style::posix
));
1612 SmallString
<64> Path2("././c");
1613 EXPECT_TRUE(path::remove_dots(Path2
, true, path::Style::posix
));
1614 EXPECT_EQ("c", Path2
);
1617 TEST(Support
, ReplacePathPrefix
) {
1618 SmallString
<64> Path1("/foo");
1619 SmallString
<64> Path2("/old/foo");
1620 SmallString
<64> Path3("/oldnew/foo");
1621 SmallString
<64> Path4("C:\\old/foo\\bar");
1622 SmallString
<64> OldPrefix("/old");
1623 SmallString
<64> OldPrefixSep("/old/");
1624 SmallString
<64> OldPrefixWin("c:/oLD/F");
1625 SmallString
<64> NewPrefix("/new");
1626 SmallString
<64> NewPrefix2("/longernew");
1627 SmallString
<64> EmptyPrefix("");
1630 SmallString
<64> Path
= Path1
;
1631 Found
= path::replace_path_prefix(Path
, OldPrefix
, NewPrefix
);
1632 EXPECT_FALSE(Found
);
1633 EXPECT_EQ(Path
, "/foo");
1635 Found
= path::replace_path_prefix(Path
, OldPrefix
, NewPrefix
);
1637 EXPECT_EQ(Path
, "/new/foo");
1639 Found
= path::replace_path_prefix(Path
, OldPrefix
, NewPrefix2
);
1641 EXPECT_EQ(Path
, "/longernew/foo");
1643 Found
= path::replace_path_prefix(Path
, EmptyPrefix
, NewPrefix
);
1645 EXPECT_EQ(Path
, "/new/foo");
1647 Found
= path::replace_path_prefix(Path
, OldPrefix
, EmptyPrefix
);
1649 EXPECT_EQ(Path
, "/foo");
1651 Found
= path::replace_path_prefix(Path
, OldPrefixSep
, EmptyPrefix
);
1653 EXPECT_EQ(Path
, "foo");
1655 Found
= path::replace_path_prefix(Path
, OldPrefix
, NewPrefix
);
1657 EXPECT_EQ(Path
, "/newnew/foo");
1659 Found
= path::replace_path_prefix(Path
, OldPrefix
, NewPrefix2
);
1661 EXPECT_EQ(Path
, "/longernewnew/foo");
1663 Found
= path::replace_path_prefix(Path
, EmptyPrefix
, NewPrefix
);
1665 EXPECT_EQ(Path
, "/new/foo");
1667 Found
= path::replace_path_prefix(Path
, OldPrefix
, NewPrefix
);
1669 EXPECT_EQ(Path
, "/new");
1670 Path
= OldPrefixSep
;
1671 Found
= path::replace_path_prefix(Path
, OldPrefix
, NewPrefix
);
1673 EXPECT_EQ(Path
, "/new/");
1675 Found
= path::replace_path_prefix(Path
, OldPrefixSep
, NewPrefix
);
1676 EXPECT_FALSE(Found
);
1677 EXPECT_EQ(Path
, "/old");
1679 Found
= path::replace_path_prefix(Path
, OldPrefixWin
, NewPrefix
,
1680 path::Style::windows
);
1682 EXPECT_EQ(Path
, "/newoo\\bar");
1684 Found
= path::replace_path_prefix(Path
, OldPrefixWin
, NewPrefix
,
1685 path::Style::posix
);
1686 EXPECT_FALSE(Found
);
1687 EXPECT_EQ(Path
, "C:\\old/foo\\bar");
1690 TEST_F(FileSystemTest
, OpenFileForRead
) {
1691 // Create a temp file.
1693 SmallString
<64> TempPath
;
1695 fs::createTemporaryFile("prefix", "temp", FileDescriptor
, TempPath
));
1696 FileRemover
Cleanup(TempPath
);
1698 // Make sure it exists.
1699 ASSERT_TRUE(sys::fs::exists(Twine(TempPath
)));
1701 // Open the file for read
1702 int FileDescriptor2
;
1703 SmallString
<64> ResultPath
;
1704 ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath
), FileDescriptor2
,
1705 fs::OF_None
, &ResultPath
))
1707 // If we succeeded, check that the paths are the same (modulo case):
1708 if (!ResultPath
.empty()) {
1709 // The paths returned by createTemporaryFile and getPathFromOpenFD
1710 // should reference the same file on disk.
1711 fs::UniqueID D1
, D2
;
1712 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath
), D1
));
1713 ASSERT_NO_ERROR(fs::getUniqueID(Twine(ResultPath
), D2
));
1716 ::close(FileDescriptor
);
1717 ::close(FileDescriptor2
);
1720 // Since Windows Vista, file access time is not updated by default.
1721 // This is instead updated manually by openFileForRead.
1722 // https://blogs.technet.microsoft.com/filecab/2006/11/07/disabling-last-access-time-in-windows-vista-to-improve-ntfs-performance/
1723 // This part of the unit test is Windows specific as the updating of
1724 // access times can be disabled on Linux using /etc/fstab.
1726 // Set access time to UNIX epoch.
1727 ASSERT_NO_ERROR(sys::fs::openFileForWrite(Twine(TempPath
), FileDescriptor
,
1728 fs::CD_OpenExisting
));
1729 TimePoint
<> Epoch(std::chrono::milliseconds(0));
1730 ASSERT_NO_ERROR(fs::setLastAccessAndModificationTime(FileDescriptor
, Epoch
));
1731 ::close(FileDescriptor
);
1733 // Open the file and ensure access time is updated, when forced.
1734 ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath
), FileDescriptor
,
1735 fs::OF_UpdateAtime
, &ResultPath
));
1737 sys::fs::file_status Status
;
1738 ASSERT_NO_ERROR(sys::fs::status(FileDescriptor
, Status
));
1739 auto FileAccessTime
= Status
.getLastAccessedTime();
1741 ASSERT_NE(Epoch
, FileAccessTime
);
1742 ::close(FileDescriptor
);
1744 // Ideally this test would include a case when ATime is not forced to update,
1745 // however the expected behaviour will differ depending on the configuration
1746 // of the Windows file system.
1750 static void createFileWithData(const Twine
&Path
, bool ShouldExistBefore
,
1751 fs::CreationDisposition Disp
, StringRef Data
) {
1753 ASSERT_EQ(ShouldExistBefore
, fs::exists(Path
));
1754 ASSERT_NO_ERROR(fs::openFileForWrite(Path
, FD
, Disp
));
1755 FileDescriptorCloser
Closer(FD
);
1756 ASSERT_TRUE(fs::exists(Path
));
1758 ASSERT_EQ(Data
.size(), (size_t)write(FD
, Data
.data(), Data
.size()));
1761 static void verifyFileContents(const Twine
&Path
, StringRef Contents
) {
1762 auto Buffer
= MemoryBuffer::getFile(Path
);
1763 ASSERT_TRUE((bool)Buffer
);
1764 StringRef Data
= Buffer
.get()->getBuffer();
1765 ASSERT_EQ(Data
, Contents
);
1768 TEST_F(FileSystemTest
, CreateNew
) {
1770 Optional
<FileDescriptorCloser
> Closer
;
1772 // Succeeds if the file does not exist.
1773 ASSERT_FALSE(fs::exists(NonExistantFile
));
1774 ASSERT_NO_ERROR(fs::openFileForWrite(NonExistantFile
, FD
, fs::CD_CreateNew
));
1775 ASSERT_TRUE(fs::exists(NonExistantFile
));
1777 FileRemover
Cleanup(NonExistantFile
);
1780 // And creates a file of size 0.
1781 sys::fs::file_status Status
;
1782 ASSERT_NO_ERROR(sys::fs::status(FD
, Status
));
1783 EXPECT_EQ(0ULL, Status
.getSize());
1785 // Close this first, before trying to re-open the file.
1788 // But fails if the file does exist.
1789 ASSERT_ERROR(fs::openFileForWrite(NonExistantFile
, FD
, fs::CD_CreateNew
));
1792 TEST_F(FileSystemTest
, CreateAlways
) {
1794 Optional
<FileDescriptorCloser
> Closer
;
1796 // Succeeds if the file does not exist.
1797 ASSERT_FALSE(fs::exists(NonExistantFile
));
1799 fs::openFileForWrite(NonExistantFile
, FD
, fs::CD_CreateAlways
));
1803 ASSERT_TRUE(fs::exists(NonExistantFile
));
1805 FileRemover
Cleanup(NonExistantFile
);
1807 // And creates a file of size 0.
1809 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1810 ASSERT_EQ(0ULL, FileSize
);
1812 // If we write some data to it re-create it with CreateAlways, it succeeds and
1813 // truncates to 0 bytes.
1814 ASSERT_EQ(4, write(FD
, "Test", 4));
1818 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1819 ASSERT_EQ(4ULL, FileSize
);
1822 fs::openFileForWrite(NonExistantFile
, FD
, fs::CD_CreateAlways
));
1824 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1825 ASSERT_EQ(0ULL, FileSize
);
1828 TEST_F(FileSystemTest
, OpenExisting
) {
1831 // Fails if the file does not exist.
1832 ASSERT_FALSE(fs::exists(NonExistantFile
));
1833 ASSERT_ERROR(fs::openFileForWrite(NonExistantFile
, FD
, fs::CD_OpenExisting
));
1834 ASSERT_FALSE(fs::exists(NonExistantFile
));
1836 // Make a dummy file now so that we can try again when the file does exist.
1837 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "Fizz");
1838 FileRemover
Cleanup(NonExistantFile
);
1840 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1841 ASSERT_EQ(4ULL, FileSize
);
1843 // If we re-create it with different data, it overwrites rather than
1845 createFileWithData(NonExistantFile
, true, fs::CD_OpenExisting
, "Buzz");
1846 verifyFileContents(NonExistantFile
, "Buzz");
1849 TEST_F(FileSystemTest
, OpenAlways
) {
1850 // Succeeds if the file does not exist.
1851 createFileWithData(NonExistantFile
, false, fs::CD_OpenAlways
, "Fizz");
1852 FileRemover
Cleanup(NonExistantFile
);
1854 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1855 ASSERT_EQ(4ULL, FileSize
);
1857 // Now re-open it and write again, verifying the contents get over-written.
1858 createFileWithData(NonExistantFile
, true, fs::CD_OpenAlways
, "Bu");
1859 verifyFileContents(NonExistantFile
, "Buzz");
1862 TEST_F(FileSystemTest
, AppendSetsCorrectFileOffset
) {
1863 fs::CreationDisposition Disps
[] = {fs::CD_CreateAlways
, fs::CD_OpenAlways
,
1864 fs::CD_OpenExisting
};
1866 // Write some data and re-open it with every possible disposition (this is a
1867 // hack that shouldn't work, but is left for compatibility. OF_Append
1869 // the specified disposition.
1870 for (fs::CreationDisposition Disp
: Disps
) {
1872 Optional
<FileDescriptorCloser
> Closer
;
1874 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "Fizz");
1876 FileRemover
Cleanup(NonExistantFile
);
1879 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1880 ASSERT_EQ(4ULL, FileSize
);
1882 fs::openFileForWrite(NonExistantFile
, FD
, Disp
, fs::OF_Append
));
1884 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile
, FileSize
));
1885 ASSERT_EQ(4ULL, FileSize
);
1887 ASSERT_EQ(4, write(FD
, "Buzz", 4));
1890 verifyFileContents(NonExistantFile
, "FizzBuzz");
1894 static void verifyRead(int FD
, StringRef Data
, bool ShouldSucceed
) {
1895 std::vector
<char> Buffer
;
1896 Buffer
.resize(Data
.size());
1897 int Result
= ::read(FD
, Buffer
.data(), Buffer
.size());
1898 if (ShouldSucceed
) {
1899 ASSERT_EQ((size_t)Result
, Data
.size());
1900 ASSERT_EQ(Data
, StringRef(Buffer
.data(), Buffer
.size()));
1902 ASSERT_EQ(-1, Result
);
1903 ASSERT_EQ(EBADF
, errno
);
1907 static void verifyWrite(int FD
, StringRef Data
, bool ShouldSucceed
) {
1908 int Result
= ::write(FD
, Data
.data(), Data
.size());
1910 ASSERT_EQ((size_t)Result
, Data
.size());
1912 ASSERT_EQ(-1, Result
);
1913 ASSERT_EQ(EBADF
, errno
);
1917 TEST_F(FileSystemTest
, ReadOnlyFileCantWrite
) {
1918 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "Fizz");
1919 FileRemover
Cleanup(NonExistantFile
);
1922 ASSERT_NO_ERROR(fs::openFileForRead(NonExistantFile
, FD
));
1923 FileDescriptorCloser
Closer(FD
);
1925 verifyWrite(FD
, "Buzz", false);
1926 verifyRead(FD
, "Fizz", true);
1929 TEST_F(FileSystemTest
, WriteOnlyFileCantRead
) {
1930 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "Fizz");
1931 FileRemover
Cleanup(NonExistantFile
);
1935 fs::openFileForWrite(NonExistantFile
, FD
, fs::CD_OpenExisting
));
1936 FileDescriptorCloser
Closer(FD
);
1937 verifyRead(FD
, "Fizz", false);
1938 verifyWrite(FD
, "Buzz", true);
1941 TEST_F(FileSystemTest
, ReadWriteFileCanReadOrWrite
) {
1942 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "Fizz");
1943 FileRemover
Cleanup(NonExistantFile
);
1946 ASSERT_NO_ERROR(fs::openFileForReadWrite(NonExistantFile
, FD
,
1947 fs::CD_OpenExisting
, fs::OF_None
));
1948 FileDescriptorCloser
Closer(FD
);
1949 verifyRead(FD
, "Fizz", true);
1950 verifyWrite(FD
, "Buzz", true);
1953 TEST_F(FileSystemTest
, readNativeFile
) {
1954 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "01234");
1955 FileRemover
Cleanup(NonExistantFile
);
1956 const auto &Read
= [&](size_t ToRead
) -> Expected
<std::string
> {
1957 std::string
Buf(ToRead
, '?');
1958 Expected
<fs::file_t
> FD
= fs::openNativeFileForRead(NonExistantFile
);
1960 return FD
.takeError();
1961 auto Close
= make_scope_exit([&] { fs::closeFile(*FD
); });
1962 if (Expected
<size_t> BytesRead
= fs::readNativeFile(
1963 *FD
, makeMutableArrayRef(&*Buf
.begin(), Buf
.size())))
1964 return Buf
.substr(0, *BytesRead
);
1966 return BytesRead
.takeError();
1968 EXPECT_THAT_EXPECTED(Read(5), HasValue("01234"));
1969 EXPECT_THAT_EXPECTED(Read(3), HasValue("012"));
1970 EXPECT_THAT_EXPECTED(Read(6), HasValue("01234"));
1973 TEST_F(FileSystemTest
, readNativeFileToEOF
) {
1974 constexpr StringLiteral Content
= "0123456789";
1975 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, Content
);
1976 FileRemover
Cleanup(NonExistantFile
);
1977 const auto &Read
= [&](SmallVectorImpl
<char> &V
,
1978 Optional
<ssize_t
> ChunkSize
) {
1979 Expected
<fs::file_t
> FD
= fs::openNativeFileForRead(NonExistantFile
);
1981 return FD
.takeError();
1982 auto Close
= make_scope_exit([&] { fs::closeFile(*FD
); });
1984 return fs::readNativeFileToEOF(*FD
, V
, *ChunkSize
);
1985 return fs::readNativeFileToEOF(*FD
, V
);
1988 // Check basic operation.
1990 SmallString
<0> NoSmall
;
1991 SmallString
<fs::DefaultReadChunkSize
+ Content
.size()> StaysSmall
;
1992 SmallVectorImpl
<char> *Vectors
[] = {
1993 static_cast<SmallVectorImpl
<char> *>(&NoSmall
),
1994 static_cast<SmallVectorImpl
<char> *>(&StaysSmall
),
1996 for (SmallVectorImpl
<char> *V
: Vectors
) {
1997 ASSERT_THAT_ERROR(Read(*V
, None
), Succeeded());
1998 ASSERT_EQ(Content
, StringRef(V
->begin(), V
->size()));
2000 ASSERT_EQ(fs::DefaultReadChunkSize
+ Content
.size(), StaysSmall
.capacity());
2004 constexpr StringLiteral Prefix
= "prefix-";
2005 for (SmallVectorImpl
<char> *V
: Vectors
) {
2006 V
->assign(Prefix
.begin(), Prefix
.end());
2007 ASSERT_THAT_ERROR(Read(*V
, None
), Succeeded());
2008 ASSERT_EQ((Prefix
+ Content
).str(), StringRef(V
->begin(), V
->size()));
2013 // Check that the chunk size (if specified) is respected.
2014 SmallString
<Content
.size() + 5> SmallChunks
;
2015 ASSERT_THAT_ERROR(Read(SmallChunks
, 5), Succeeded());
2016 ASSERT_EQ(SmallChunks
, Content
);
2017 ASSERT_EQ(Content
.size() + 5, SmallChunks
.capacity());
2020 TEST_F(FileSystemTest
, readNativeFileSlice
) {
2021 createFileWithData(NonExistantFile
, false, fs::CD_CreateNew
, "01234");
2022 FileRemover
Cleanup(NonExistantFile
);
2023 Expected
<fs::file_t
> FD
= fs::openNativeFileForRead(NonExistantFile
);
2024 ASSERT_THAT_EXPECTED(FD
, Succeeded());
2025 auto Close
= make_scope_exit([&] { fs::closeFile(*FD
); });
2026 const auto &Read
= [&](size_t Offset
,
2027 size_t ToRead
) -> Expected
<std::string
> {
2028 std::string
Buf(ToRead
, '?');
2029 if (Expected
<size_t> BytesRead
= fs::readNativeFileSlice(
2030 *FD
, makeMutableArrayRef(&*Buf
.begin(), Buf
.size()), Offset
))
2031 return Buf
.substr(0, *BytesRead
);
2033 return BytesRead
.takeError();
2035 EXPECT_THAT_EXPECTED(Read(0, 5), HasValue("01234"));
2036 EXPECT_THAT_EXPECTED(Read(0, 3), HasValue("012"));
2037 EXPECT_THAT_EXPECTED(Read(2, 3), HasValue("234"));
2038 EXPECT_THAT_EXPECTED(Read(0, 6), HasValue("01234"));
2039 EXPECT_THAT_EXPECTED(Read(2, 6), HasValue("234"));
2040 EXPECT_THAT_EXPECTED(Read(5, 5), HasValue(""));
2043 TEST_F(FileSystemTest
, is_local
) {
2044 bool TestDirectoryIsLocal
;
2045 ASSERT_NO_ERROR(fs::is_local(TestDirectory
, TestDirectoryIsLocal
));
2046 EXPECT_EQ(TestDirectoryIsLocal
, fs::is_local(TestDirectory
));
2049 SmallString
<128> TempPath
;
2051 fs::createUniqueFile(Twine(TestDirectory
) + "/temp", FD
, TempPath
));
2052 FileRemover
Cleanup(TempPath
);
2054 // Make sure it exists.
2055 ASSERT_TRUE(sys::fs::exists(Twine(TempPath
)));
2057 bool TempFileIsLocal
;
2058 ASSERT_NO_ERROR(fs::is_local(FD
, TempFileIsLocal
));
2059 EXPECT_EQ(TempFileIsLocal
, fs::is_local(FD
));
2062 // Expect that the file and its parent directory are equally local or equally
2064 EXPECT_EQ(TestDirectoryIsLocal
, TempFileIsLocal
);
2067 TEST_F(FileSystemTest
, getUmask
) {
2069 EXPECT_EQ(fs::getUmask(), 0U) << "Should always be 0 on Windows.";
2071 unsigned OldMask
= ::umask(0022);
2072 unsigned CurrentMask
= fs::getUmask();
2073 EXPECT_EQ(CurrentMask
, 0022U)
2074 << "getUmask() didn't return previously set umask()";
2075 EXPECT_EQ(::umask(OldMask
), mode_t(0022U))
2076 << "getUmask() may have changed umask()";
2080 TEST_F(FileSystemTest
, RespectUmask
) {
2082 unsigned OldMask
= ::umask(0022);
2085 SmallString
<128> TempPath
;
2086 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD
, TempPath
));
2088 fs::perms AllRWE
= static_cast<fs::perms
>(0777);
2090 ASSERT_NO_ERROR(fs::setPermissions(TempPath
, AllRWE
));
2092 ErrorOr
<fs::perms
> Perms
= fs::getPermissions(TempPath
);
2093 ASSERT_TRUE(!!Perms
);
2094 EXPECT_EQ(Perms
.get(), AllRWE
) << "Should have ignored umask by default";
2096 ASSERT_NO_ERROR(fs::setPermissions(TempPath
, AllRWE
));
2098 Perms
= fs::getPermissions(TempPath
);
2099 ASSERT_TRUE(!!Perms
);
2100 EXPECT_EQ(Perms
.get(), AllRWE
) << "Should have ignored umask";
2103 fs::setPermissions(FD
, static_cast<fs::perms
>(AllRWE
& ~fs::getUmask())));
2104 Perms
= fs::getPermissions(TempPath
);
2105 ASSERT_TRUE(!!Perms
);
2106 EXPECT_EQ(Perms
.get(), static_cast<fs::perms
>(0755))
2107 << "Did not respect umask";
2109 (void)::umask(0057);
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
>(0720))
2116 << "Did not respect umask";
2118 (void)::umask(OldMask
);
2123 TEST_F(FileSystemTest
, set_current_path
) {
2124 SmallString
<128> path
;
2126 ASSERT_NO_ERROR(fs::current_path(path
));
2127 ASSERT_NE(TestDirectory
, path
);
2129 struct RestorePath
{
2130 SmallString
<128> path
;
2131 RestorePath(const SmallString
<128> &path
) : path(path
) {}
2132 ~RestorePath() { fs::set_current_path(path
); }
2133 } restore_path(path
);
2135 ASSERT_NO_ERROR(fs::set_current_path(TestDirectory
));
2137 ASSERT_NO_ERROR(fs::current_path(path
));
2139 fs::UniqueID D1
, D2
;
2140 ASSERT_NO_ERROR(fs::getUniqueID(TestDirectory
, D1
));
2141 ASSERT_NO_ERROR(fs::getUniqueID(path
, D2
));
2142 ASSERT_EQ(D1
, D2
) << "D1: " << TestDirectory
<< "\nD2: " << path
;
2145 TEST_F(FileSystemTest
, permissions
) {
2147 SmallString
<64> TempPath
;
2148 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD
, TempPath
));
2149 FileRemover
Cleanup(TempPath
);
2151 // Make sure it exists.
2152 ASSERT_TRUE(fs::exists(Twine(TempPath
)));
2154 auto CheckPermissions
= [&](fs::perms Expected
) {
2155 ErrorOr
<fs::perms
> Actual
= fs::getPermissions(TempPath
);
2156 return Actual
&& *Actual
== Expected
;
2159 std::error_code NoError
;
2160 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_all
), NoError
);
2161 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2163 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_read
| fs::all_exe
), NoError
);
2164 EXPECT_TRUE(CheckPermissions(fs::all_read
| fs::all_exe
));
2167 fs::perms ReadOnly
= fs::all_read
| fs::all_exe
;
2168 EXPECT_EQ(fs::setPermissions(TempPath
, fs::no_perms
), NoError
);
2169 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2171 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_read
), NoError
);
2172 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2174 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_write
), NoError
);
2175 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2177 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_exe
), NoError
);
2178 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2180 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_all
), NoError
);
2181 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2183 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_read
), NoError
);
2184 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2186 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_write
), NoError
);
2187 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2189 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_exe
), NoError
);
2190 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2192 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_all
), NoError
);
2193 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2195 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_read
), NoError
);
2196 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2198 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_write
), NoError
);
2199 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2201 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_exe
), NoError
);
2202 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2204 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_all
), NoError
);
2205 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2207 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_read
), NoError
);
2208 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2210 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_write
), NoError
);
2211 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2213 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_exe
), NoError
);
2214 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2216 EXPECT_EQ(fs::setPermissions(TempPath
, fs::set_uid_on_exe
), NoError
);
2217 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2219 EXPECT_EQ(fs::setPermissions(TempPath
, fs::set_gid_on_exe
), NoError
);
2220 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2222 EXPECT_EQ(fs::setPermissions(TempPath
, fs::sticky_bit
), NoError
);
2223 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2225 EXPECT_EQ(fs::setPermissions(TempPath
, fs::set_uid_on_exe
|
2226 fs::set_gid_on_exe
|
2229 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2231 EXPECT_EQ(fs::setPermissions(TempPath
, ReadOnly
| fs::set_uid_on_exe
|
2232 fs::set_gid_on_exe
|
2235 EXPECT_TRUE(CheckPermissions(ReadOnly
));
2237 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_perms
), NoError
);
2238 EXPECT_TRUE(CheckPermissions(fs::all_all
));
2240 EXPECT_EQ(fs::setPermissions(TempPath
, fs::no_perms
), NoError
);
2241 EXPECT_TRUE(CheckPermissions(fs::no_perms
));
2243 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_read
), NoError
);
2244 EXPECT_TRUE(CheckPermissions(fs::owner_read
));
2246 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_write
), NoError
);
2247 EXPECT_TRUE(CheckPermissions(fs::owner_write
));
2249 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_exe
), NoError
);
2250 EXPECT_TRUE(CheckPermissions(fs::owner_exe
));
2252 EXPECT_EQ(fs::setPermissions(TempPath
, fs::owner_all
), NoError
);
2253 EXPECT_TRUE(CheckPermissions(fs::owner_all
));
2255 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_read
), NoError
);
2256 EXPECT_TRUE(CheckPermissions(fs::group_read
));
2258 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_write
), NoError
);
2259 EXPECT_TRUE(CheckPermissions(fs::group_write
));
2261 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_exe
), NoError
);
2262 EXPECT_TRUE(CheckPermissions(fs::group_exe
));
2264 EXPECT_EQ(fs::setPermissions(TempPath
, fs::group_all
), NoError
);
2265 EXPECT_TRUE(CheckPermissions(fs::group_all
));
2267 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_read
), NoError
);
2268 EXPECT_TRUE(CheckPermissions(fs::others_read
));
2270 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_write
), NoError
);
2271 EXPECT_TRUE(CheckPermissions(fs::others_write
));
2273 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_exe
), NoError
);
2274 EXPECT_TRUE(CheckPermissions(fs::others_exe
));
2276 EXPECT_EQ(fs::setPermissions(TempPath
, fs::others_all
), NoError
);
2277 EXPECT_TRUE(CheckPermissions(fs::others_all
));
2279 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_read
), NoError
);
2280 EXPECT_TRUE(CheckPermissions(fs::all_read
));
2282 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_write
), NoError
);
2283 EXPECT_TRUE(CheckPermissions(fs::all_write
));
2285 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_exe
), NoError
);
2286 EXPECT_TRUE(CheckPermissions(fs::all_exe
));
2288 EXPECT_EQ(fs::setPermissions(TempPath
, fs::set_uid_on_exe
), NoError
);
2289 EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe
));
2291 EXPECT_EQ(fs::setPermissions(TempPath
, fs::set_gid_on_exe
), NoError
);
2292 EXPECT_TRUE(CheckPermissions(fs::set_gid_on_exe
));
2294 // Modern BSDs require root to set the sticky bit on files.
2295 // AIX and Solaris without root will mask off (i.e., lose) the sticky bit
2297 #if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
2298 !defined(_AIX) && !(defined(__sun__) && defined(__svr4__))
2299 EXPECT_EQ(fs::setPermissions(TempPath
, fs::sticky_bit
), NoError
);
2300 EXPECT_TRUE(CheckPermissions(fs::sticky_bit
));
2302 EXPECT_EQ(fs::setPermissions(TempPath
, fs::set_uid_on_exe
|
2303 fs::set_gid_on_exe
|
2306 EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe
| fs::set_gid_on_exe
|
2309 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_read
| fs::set_uid_on_exe
|
2310 fs::set_gid_on_exe
|
2313 EXPECT_TRUE(CheckPermissions(fs::all_read
| fs::set_uid_on_exe
|
2314 fs::set_gid_on_exe
| fs::sticky_bit
));
2316 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_perms
), NoError
);
2317 EXPECT_TRUE(CheckPermissions(fs::all_perms
));
2318 #endif // !FreeBSD && !NetBSD && !OpenBSD && !AIX
2320 EXPECT_EQ(fs::setPermissions(TempPath
, fs::all_perms
& ~fs::sticky_bit
),
2322 EXPECT_TRUE(CheckPermissions(fs::all_perms
& ~fs::sticky_bit
));
2327 TEST_F(FileSystemTest
, widenPath
) {
2328 const std::wstring
LongPathPrefix(L
"\\\\?\\");
2330 // Test that the length limit is checked against the UTF-16 length and not the
2332 std::string
Input("C:\\foldername\\");
2333 const std::string
Pi("\xcf\x80"); // UTF-8 lower case pi.
2334 // Add Pi up to the MAX_PATH limit.
2335 const size_t NumChars
= MAX_PATH
- Input
.size() - 1;
2336 for (size_t i
= 0; i
< NumChars
; ++i
)
2338 // Check that UTF-8 length already exceeds MAX_PATH.
2339 EXPECT_GT(Input
.size(), (size_t)MAX_PATH
);
2340 SmallVector
<wchar_t, MAX_PATH
+ 16> Result
;
2341 ASSERT_NO_ERROR(windows::widenPath(Input
, Result
));
2342 // Result should not start with the long path prefix.
2343 EXPECT_TRUE(std::wmemcmp(Result
.data(), LongPathPrefix
.c_str(),
2344 LongPathPrefix
.size()) != 0);
2345 EXPECT_EQ(Result
.size(), (size_t)MAX_PATH
- 1);
2347 // Add another Pi to exceed the MAX_PATH limit.
2349 // Construct the expected result.
2350 SmallVector
<wchar_t, MAX_PATH
+ 16> Expected
;
2351 ASSERT_NO_ERROR(windows::UTF8ToUTF16(Input
, Expected
));
2352 Expected
.insert(Expected
.begin(), LongPathPrefix
.begin(),
2353 LongPathPrefix
.end());
2355 ASSERT_NO_ERROR(windows::widenPath(Input
, Result
));
2356 EXPECT_EQ(Result
, Expected
);
2357 // Pass a path with forward slashes, check that it ends up with
2358 // backslashes when widened with the long path prefix.
2359 SmallString
<MAX_PATH
+ 16> InputForward(Input
);
2360 path::make_preferred(InputForward
, path::Style::windows_slash
);
2361 ASSERT_NO_ERROR(windows::widenPath(InputForward
, Result
));
2362 EXPECT_EQ(Result
, Expected
);
2364 // Pass a path which has the long path prefix prepended originally, but
2365 // which is short enough to not require the long path prefix. If such a
2366 // path is passed with forward slashes, make sure it gets normalized to
2368 SmallString
<MAX_PATH
+ 16> PrefixedPath("\\\\?\\C:\\foldername");
2369 ASSERT_NO_ERROR(windows::UTF8ToUTF16(PrefixedPath
, Expected
));
2370 // Mangle the input to forward slashes.
2371 path::make_preferred(PrefixedPath
, path::Style::windows_slash
);
2372 ASSERT_NO_ERROR(windows::widenPath(PrefixedPath
, Result
));
2373 EXPECT_EQ(Result
, Expected
);
2375 // A short path with an inconsistent prefix is passed through as-is; this
2376 // is a degenerate case that we currently don't care about handling.
2377 PrefixedPath
.assign("/\\?/C:/foldername");
2378 ASSERT_NO_ERROR(windows::UTF8ToUTF16(PrefixedPath
, Expected
));
2379 ASSERT_NO_ERROR(windows::widenPath(PrefixedPath
, Result
));
2380 EXPECT_EQ(Result
, Expected
);
2382 // Test that UNC paths are handled correctly.
2383 const std::string
ShareName("\\\\sharename\\");
2384 const std::string
FileName("\\filename");
2385 // Initialize directory name so that the input is within the MAX_PATH limit.
2386 const char DirChar
= 'x';
2387 std::string
DirName(MAX_PATH
- ShareName
.size() - FileName
.size() - 1,
2390 Input
= ShareName
+ DirName
+ FileName
;
2391 ASSERT_NO_ERROR(windows::widenPath(Input
, Result
));
2392 // Result should not start with the long path prefix.
2393 EXPECT_TRUE(std::wmemcmp(Result
.data(), LongPathPrefix
.c_str(),
2394 LongPathPrefix
.size()) != 0);
2395 EXPECT_EQ(Result
.size(), (size_t)MAX_PATH
- 1);
2397 // Extend the directory name so the input exceeds the MAX_PATH limit.
2399 Input
= ShareName
+ DirName
+ FileName
;
2400 // Construct the expected result.
2401 ASSERT_NO_ERROR(windows::UTF8ToUTF16(StringRef(Input
).substr(2), Expected
));
2402 const std::wstring
UNCPrefix(LongPathPrefix
+ L
"UNC\\");
2403 Expected
.insert(Expected
.begin(), UNCPrefix
.begin(), UNCPrefix
.end());
2405 ASSERT_NO_ERROR(windows::widenPath(Input
, Result
));
2406 EXPECT_EQ(Result
, Expected
);
2408 // Check that Unix separators are handled correctly.
2409 std::replace(Input
.begin(), Input
.end(), '\\', '/');
2410 ASSERT_NO_ERROR(windows::widenPath(Input
, Result
));
2411 EXPECT_EQ(Result
, Expected
);
2413 // Check the removal of "dots".
2414 Input
= ShareName
+ DirName
+ "\\.\\foo\\.\\.." + FileName
;
2415 ASSERT_NO_ERROR(windows::widenPath(Input
, Result
));
2416 EXPECT_EQ(Result
, Expected
);
2421 // Windows refuses lock request if file region is already locked by the same
2422 // process. POSIX system in this case updates the existing lock.
2423 TEST_F(FileSystemTest
, FileLocker
) {
2424 using namespace std::chrono
;
2427 SmallString
<64> TempPath
;
2428 EC
= fs::createTemporaryFile("test", "temp", FD
, TempPath
);
2429 ASSERT_NO_ERROR(EC
);
2430 FileRemover
Cleanup(TempPath
);
2431 raw_fd_ostream
Stream(TempPath
, EC
);
2433 EC
= fs::tryLockFile(FD
);
2434 ASSERT_NO_ERROR(EC
);
2435 EC
= fs::unlockFile(FD
);
2436 ASSERT_NO_ERROR(EC
);
2438 if (auto L
= Stream
.lock()) {
2439 ASSERT_ERROR(fs::tryLockFile(FD
));
2440 ASSERT_NO_ERROR(L
->unlock());
2441 ASSERT_NO_ERROR(fs::tryLockFile(FD
));
2442 ASSERT_NO_ERROR(fs::unlockFile(FD
));
2445 handleAllErrors(L
.takeError(), [&](ErrorInfoBase
&EIB
) {});
2448 ASSERT_NO_ERROR(fs::tryLockFile(FD
));
2449 ASSERT_NO_ERROR(fs::unlockFile(FD
));
2452 Expected
<fs::FileLocker
> L1
= Stream
.lock();
2453 ASSERT_THAT_EXPECTED(L1
, Succeeded());
2454 raw_fd_ostream
Stream2(FD
, false);
2455 Expected
<fs::FileLocker
> L2
= Stream2
.tryLockFor(250ms
);
2456 ASSERT_THAT_EXPECTED(L2
, Failed());
2457 ASSERT_NO_ERROR(L1
->unlock());
2458 Expected
<fs::FileLocker
> L3
= Stream
.tryLockFor(0ms
);
2459 ASSERT_THAT_EXPECTED(L3
, Succeeded());
2462 ASSERT_NO_ERROR(fs::tryLockFile(FD
));
2463 ASSERT_NO_ERROR(fs::unlockFile(FD
));
2467 TEST_F(FileSystemTest
, CopyFile
) {
2468 unittest::TempDir
RootTestDirectory("CopyFileTest", /*Unique=*/true);
2470 SmallVector
<std::string
> Data
;
2471 SmallVector
<SmallString
<128>> Sources
;
2472 for (int I
= 0, E
= 3; I
!= E
; ++I
) {
2473 Data
.push_back(Twine(I
).str());
2474 Sources
.emplace_back(RootTestDirectory
.path());
2475 path::append(Sources
.back(), "source" + Data
.back() + ".txt");
2476 createFileWithData(Sources
.back(), /*ShouldExistBefore=*/false,
2477 fs::CD_CreateNew
, Data
.back());
2480 // Copy the first file to a non-existing file.
2481 SmallString
<128> Destination(RootTestDirectory
.path());
2482 path::append(Destination
, "destination");
2483 ASSERT_FALSE(fs::exists(Destination
));
2484 fs::copy_file(Sources
[0], Destination
);
2485 verifyFileContents(Destination
, Data
[0]);
2487 // Copy the second file to an existing file.
2488 fs::copy_file(Sources
[1], Destination
);
2489 verifyFileContents(Destination
, Data
[1]);
2491 // Note: The remaining logic is targeted at a potential failure case related
2492 // to file cloning and symlinks on Darwin. On Windows, fs::create_link() does
2493 // not return success here so the test is skipped.
2494 #if !defined(_WIN32)
2495 // Set up a symlink to the third file.
2496 SmallString
<128> Symlink(RootTestDirectory
.path());
2497 path::append(Symlink
, "symlink");
2498 ASSERT_NO_ERROR(fs::create_link(path::filename(Sources
[2]), Symlink
));
2499 verifyFileContents(Symlink
, Data
[2]);
2501 // fs::getUniqueID() should follow symlinks. Otherwise, this isn't good test
2503 fs::UniqueID SymlinkID
;
2504 fs::UniqueID Data2ID
;
2505 ASSERT_NO_ERROR(fs::getUniqueID(Symlink
, SymlinkID
));
2506 ASSERT_NO_ERROR(fs::getUniqueID(Sources
[2], Data2ID
));
2507 ASSERT_EQ(SymlinkID
, Data2ID
);
2509 // Copy the third file through the symlink.
2510 fs::copy_file(Symlink
, Destination
);
2511 verifyFileContents(Destination
, Data
[2]);
2513 // Confirm the destination is not a link to the original file, and not a
2515 bool IsDestinationSymlink
;
2516 ASSERT_NO_ERROR(fs::is_symlink_file(Destination
, IsDestinationSymlink
));
2517 ASSERT_FALSE(IsDestinationSymlink
);
2518 fs::UniqueID DestinationID
;
2519 ASSERT_NO_ERROR(fs::getUniqueID(Destination
, DestinationID
));
2520 ASSERT_NE(SymlinkID
, DestinationID
);
2524 } // anonymous namespace