1 //===- llvm/unittest/Support/Path.cpp - Path tests ------------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8
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/Errc.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/FileUtilities.h"
22 #include "llvm/Support/Host.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Testing/Support/Error.h"
26 #include "gmock/gmock.h"
27 #include "gtest/gtest.h"
28
29 #ifdef _WIN32
30 #include "llvm/ADT/ArrayRef.h"
31 #include "llvm/Support/Chrono.h"
32 #include "llvm/Support/Windows/WindowsSupport.h"
33 #include <windows.h>
34 #include <winerror.h>
35 #endif
36
37 #ifdef LLVM_ON_UNIX
38 #include <pwd.h>
39 #include <sys/stat.h>
40 #endif
41
42 using namespace llvm;
43 using namespace llvm::sys;
44
45 #define ASSERT_NO_ERROR(x) \
46 if (std::error_code ASSERT_NO_ERROR_ec = x) { \
47 SmallString<128> MessageStorage; \
48 raw_svector_ostream Message(MessageStorage); \
49 Message << #x ": did not return errc::success.\n" \
50 << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \
51 << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \
52 GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \
53 } else { \
54 }
55
56 #define ASSERT_ERROR(x) \
57 if (!x) { \
58 SmallString<128> MessageStorage; \
59 raw_svector_ostream Message(MessageStorage); \
60 Message << #x ": did not return a failure error code.\n"; \
61 GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \
62 }
63
64 namespace {
65
66 struct FileDescriptorCloser {
FileDescriptorCloser__anon5521ec1c0111::FileDescriptorCloser67 explicit FileDescriptorCloser(int FD) : FD(FD) {}
~FileDescriptorCloser__anon5521ec1c0111::FileDescriptorCloser68 ~FileDescriptorCloser() { ::close(FD); }
69 int FD;
70 };
71
TEST(is_separator,Works)72 TEST(is_separator, Works) {
73 EXPECT_TRUE(path::is_separator('/'));
74 EXPECT_FALSE(path::is_separator('\0'));
75 EXPECT_FALSE(path::is_separator('-'));
76 EXPECT_FALSE(path::is_separator(' '));
77
78 EXPECT_TRUE(path::is_separator('\\', path::Style::windows));
79 EXPECT_FALSE(path::is_separator('\\', path::Style::posix));
80
81 #ifdef _WIN32
82 EXPECT_TRUE(path::is_separator('\\'));
83 #else
84 EXPECT_FALSE(path::is_separator('\\'));
85 #endif
86 }
87
TEST(is_absolute_gnu,Works)88 TEST(is_absolute_gnu, Works) {
89 // Test tuple <Path, ExpectedPosixValue, ExpectedWindowsValue>.
90 const std::tuple<StringRef, bool, bool> Paths[] = {
91 std::make_tuple("", false, false),
92 std::make_tuple("/", true, true),
93 std::make_tuple("/foo", true, true),
94 std::make_tuple("\\", false, true),
95 std::make_tuple("\\foo", false, true),
96 std::make_tuple("foo", false, false),
97 std::make_tuple("c", false, false),
98 std::make_tuple("c:", false, true),
99 std::make_tuple("c:\\", false, true),
100 std::make_tuple("!:", false, true),
101 std::make_tuple("xx:", false, false),
102 std::make_tuple("c:abc\\", false, true),
103 std::make_tuple(":", false, false)};
104
105 for (const auto &Path : Paths) {
106 EXPECT_EQ(path::is_absolute_gnu(std::get<0>(Path), path::Style::posix),
107 std::get<1>(Path));
108 EXPECT_EQ(path::is_absolute_gnu(std::get<0>(Path), path::Style::windows),
109 std::get<2>(Path));
110 }
111 }
112
TEST(Support,Path)113 TEST(Support, Path) {
114 SmallVector<StringRef, 40> paths;
115 paths.push_back("");
116 paths.push_back(".");
117 paths.push_back("..");
118 paths.push_back("foo");
119 paths.push_back("/");
120 paths.push_back("/foo");
121 paths.push_back("foo/");
122 paths.push_back("/foo/");
123 paths.push_back("foo/bar");
124 paths.push_back("/foo/bar");
125 paths.push_back("//net");
126 paths.push_back("//net/");
127 paths.push_back("//net/foo");
128 paths.push_back("///foo///");
129 paths.push_back("///foo///bar");
130 paths.push_back("/.");
131 paths.push_back("./");
132 paths.push_back("/..");
133 paths.push_back("../");
134 paths.push_back("foo/.");
135 paths.push_back("foo/..");
136 paths.push_back("foo/./");
137 paths.push_back("foo/./bar");
138 paths.push_back("foo/..");
139 paths.push_back("foo/../");
140 paths.push_back("foo/../bar");
141 paths.push_back("c:");
142 paths.push_back("c:/");
143 paths.push_back("c:foo");
144 paths.push_back("c:/foo");
145 paths.push_back("c:foo/");
146 paths.push_back("c:/foo/");
147 paths.push_back("c:/foo/bar");
148 paths.push_back("prn:");
149 paths.push_back("c:\\");
150 paths.push_back("c:foo");
151 paths.push_back("c:\\foo");
152 paths.push_back("c:foo\\");
153 paths.push_back("c:\\foo\\");
154 paths.push_back("c:\\foo/");
155 paths.push_back("c:/foo\\bar");
156
157 for (SmallVector<StringRef, 40>::const_iterator i = paths.begin(),
158 e = paths.end();
159 i != e;
160 ++i) {
161 SCOPED_TRACE(*i);
162 SmallVector<StringRef, 5> ComponentStack;
163 for (sys::path::const_iterator ci = sys::path::begin(*i),
164 ce = sys::path::end(*i);
165 ci != ce;
166 ++ci) {
167 EXPECT_FALSE(ci->empty());
168 ComponentStack.push_back(*ci);
169 }
170
171 SmallVector<StringRef, 5> ReverseComponentStack;
172 for (sys::path::reverse_iterator ci = sys::path::rbegin(*i),
173 ce = sys::path::rend(*i);
174 ci != ce;
175 ++ci) {
176 EXPECT_FALSE(ci->empty());
177 ReverseComponentStack.push_back(*ci);
178 }
179 std::reverse(ReverseComponentStack.begin(), ReverseComponentStack.end());
180 EXPECT_THAT(ComponentStack, testing::ContainerEq(ReverseComponentStack));
181
182 // Crash test most of the API - since we're iterating over all of our paths
183 // here there isn't really anything reasonable to assert on in the results.
184 (void)path::has_root_path(*i);
185 (void)path::root_path(*i);
186 (void)path::has_root_name(*i);
187 (void)path::root_name(*i);
188 (void)path::has_root_directory(*i);
189 (void)path::root_directory(*i);
190 (void)path::has_parent_path(*i);
191 (void)path::parent_path(*i);
192 (void)path::has_filename(*i);
193 (void)path::filename(*i);
194 (void)path::has_stem(*i);
195 (void)path::stem(*i);
196 (void)path::has_extension(*i);
197 (void)path::extension(*i);
198 (void)path::is_absolute(*i);
199 (void)path::is_absolute_gnu(*i);
200 (void)path::is_relative(*i);
201
202 SmallString<128> temp_store;
203 temp_store = *i;
204 ASSERT_NO_ERROR(fs::make_absolute(temp_store));
205 temp_store = *i;
206 path::remove_filename(temp_store);
207
208 temp_store = *i;
209 path::replace_extension(temp_store, "ext");
210 StringRef filename(temp_store.begin(), temp_store.size()), stem, ext;
211 stem = path::stem(filename);
212 ext = path::extension(filename);
213 EXPECT_EQ(*sys::path::rbegin(filename), (stem + ext).str());
214
215 path::native(*i, temp_store);
216 }
217
218 {
219 SmallString<32> Relative("foo.cpp");
220 sys::fs::make_absolute("/root", Relative);
221 Relative[5] = '/'; // Fix up windows paths.
222 ASSERT_EQ("/root/foo.cpp", Relative);
223 }
224
225 {
226 SmallString<32> Relative("foo.cpp");
227 sys::fs::make_absolute("//root", Relative);
228 Relative[6] = '/'; // Fix up windows paths.
229 ASSERT_EQ("//root/foo.cpp", Relative);
230 }
231 }
232
TEST(Support,PathRoot)233 TEST(Support, PathRoot) {
234 ASSERT_EQ(path::root_name("//net/hello", path::Style::posix).str(), "//net");
235 ASSERT_EQ(path::root_name("c:/hello", path::Style::posix).str(), "");
236 ASSERT_EQ(path::root_name("c:/hello", path::Style::windows).str(), "c:");
237 ASSERT_EQ(path::root_name("/hello", path::Style::posix).str(), "");
238
239 ASSERT_EQ(path::root_directory("/goo/hello", path::Style::posix).str(), "/");
240 ASSERT_EQ(path::root_directory("c:/hello", path::Style::windows).str(), "/");
241 ASSERT_EQ(path::root_directory("d/file.txt", path::Style::posix).str(), "");
242 ASSERT_EQ(path::root_directory("d/file.txt", path::Style::windows).str(), "");
243
244 SmallVector<StringRef, 40> paths;
245 paths.push_back("");
246 paths.push_back(".");
247 paths.push_back("..");
248 paths.push_back("foo");
249 paths.push_back("/");
250 paths.push_back("/foo");
251 paths.push_back("foo/");
252 paths.push_back("/foo/");
253 paths.push_back("foo/bar");
254 paths.push_back("/foo/bar");
255 paths.push_back("//net");
256 paths.push_back("//net/");
257 paths.push_back("//net/foo");
258 paths.push_back("///foo///");
259 paths.push_back("///foo///bar");
260 paths.push_back("/.");
261 paths.push_back("./");
262 paths.push_back("/..");
263 paths.push_back("../");
264 paths.push_back("foo/.");
265 paths.push_back("foo/..");
266 paths.push_back("foo/./");
267 paths.push_back("foo/./bar");
268 paths.push_back("foo/..");
269 paths.push_back("foo/../");
270 paths.push_back("foo/../bar");
271 paths.push_back("c:");
272 paths.push_back("c:/");
273 paths.push_back("c:foo");
274 paths.push_back("c:/foo");
275 paths.push_back("c:foo/");
276 paths.push_back("c:/foo/");
277 paths.push_back("c:/foo/bar");
278 paths.push_back("prn:");
279 paths.push_back("c:\\");
280 paths.push_back("c:foo");
281 paths.push_back("c:\\foo");
282 paths.push_back("c:foo\\");
283 paths.push_back("c:\\foo\\");
284 paths.push_back("c:\\foo/");
285 paths.push_back("c:/foo\\bar");
286
287 for (StringRef p : paths) {
288 ASSERT_EQ(
289 path::root_name(p, path::Style::posix).str() + path::root_directory(p, path::Style::posix).str(),
290 path::root_path(p, path::Style::posix).str());
291
292 ASSERT_EQ(
293 path::root_name(p, path::Style::windows).str() + path::root_directory(p, path::Style::windows).str(),
294 path::root_path(p, path::Style::windows).str());
295 }
296 }
297
TEST(Support,FilenameParent)298 TEST(Support, FilenameParent) {
299 EXPECT_EQ("/", path::filename("/"));
300 EXPECT_EQ("", path::parent_path("/"));
301
302 EXPECT_EQ("\\", path::filename("c:\\", path::Style::windows));
303 EXPECT_EQ("c:", path::parent_path("c:\\", path::Style::windows));
304
305 EXPECT_EQ("/", path::filename("///"));
306 EXPECT_EQ("", path::parent_path("///"));
307
308 EXPECT_EQ("\\", path::filename("c:\\\\", path::Style::windows));
309 EXPECT_EQ("c:", path::parent_path("c:\\\\", path::Style::windows));
310
311 EXPECT_EQ("bar", path::filename("/foo/bar"));
312 EXPECT_EQ("/foo", path::parent_path("/foo/bar"));
313
314 EXPECT_EQ("foo", path::filename("/foo"));
315 EXPECT_EQ("/", path::parent_path("/foo"));
316
317 EXPECT_EQ("foo", path::filename("foo"));
318 EXPECT_EQ("", path::parent_path("foo"));
319
320 EXPECT_EQ(".", path::filename("foo/"));
321 EXPECT_EQ("foo", path::parent_path("foo/"));
322
323 EXPECT_EQ("//net", path::filename("//net"));
324 EXPECT_EQ("", path::parent_path("//net"));
325
326 EXPECT_EQ("/", path::filename("//net/"));
327 EXPECT_EQ("//net", path::parent_path("//net/"));
328
329 EXPECT_EQ("foo", path::filename("//net/foo"));
330 EXPECT_EQ("//net/", path::parent_path("//net/foo"));
331
332 // These checks are just to make sure we do something reasonable with the
333 // paths below. They are not meant to prescribe the one true interpretation of
334 // these paths. Other decompositions (e.g. "//" -> "" + "//") are also
335 // possible.
336 EXPECT_EQ("/", path::filename("//"));
337 EXPECT_EQ("", path::parent_path("//"));
338
339 EXPECT_EQ("\\", path::filename("\\\\", path::Style::windows));
340 EXPECT_EQ("", path::parent_path("\\\\", path::Style::windows));
341
342 EXPECT_EQ("\\", path::filename("\\\\\\", path::Style::windows));
343 EXPECT_EQ("", path::parent_path("\\\\\\", path::Style::windows));
344 }
345
346 static std::vector<StringRef>
GetComponents(StringRef Path,path::Style S=path::Style::native)347 GetComponents(StringRef Path, path::Style S = path::Style::native) {
348 return {path::begin(Path, S), path::end(Path)};
349 }
350
TEST(Support,PathIterator)351 TEST(Support, PathIterator) {
352 EXPECT_THAT(GetComponents("/foo"), testing::ElementsAre("/", "foo"));
353 EXPECT_THAT(GetComponents("/"), testing::ElementsAre("/"));
354 EXPECT_THAT(GetComponents("//"), testing::ElementsAre("/"));
355 EXPECT_THAT(GetComponents("///"), testing::ElementsAre("/"));
356 EXPECT_THAT(GetComponents("c/d/e/foo.txt"),
357 testing::ElementsAre("c", "d", "e", "foo.txt"));
358 EXPECT_THAT(GetComponents(".c/.d/../."),
359 testing::ElementsAre(".c", ".d", "..", "."));
360 EXPECT_THAT(GetComponents("/c/d/e/foo.txt"),
361 testing::ElementsAre("/", "c", "d", "e", "foo.txt"));
362 EXPECT_THAT(GetComponents("/.c/.d/../."),
363 testing::ElementsAre("/", ".c", ".d", "..", "."));
364 EXPECT_THAT(GetComponents("c:\\c\\e\\foo.txt", path::Style::windows),
365 testing::ElementsAre("c:", "\\", "c", "e", "foo.txt"));
366 EXPECT_THAT(GetComponents("//net/"), testing::ElementsAre("//net", "/"));
367 EXPECT_THAT(GetComponents("//net/c/foo.txt"),
368 testing::ElementsAre("//net", "/", "c", "foo.txt"));
369 }
370
TEST(Support,AbsolutePathIteratorEnd)371 TEST(Support, AbsolutePathIteratorEnd) {
372 // Trailing slashes are converted to '.' unless they are part of the root path.
373 SmallVector<std::pair<StringRef, path::Style>, 4> Paths;
374 Paths.emplace_back("/foo/", path::Style::native);
375 Paths.emplace_back("/foo//", path::Style::native);
376 Paths.emplace_back("//net/foo/", path::Style::native);
377 Paths.emplace_back("c:\\foo\\", path::Style::windows);
378
379 for (auto &Path : Paths) {
380 SCOPED_TRACE(Path.first);
381 StringRef LastComponent = *path::rbegin(Path.first, Path.second);
382 EXPECT_EQ(".", LastComponent);
383 }
384
385 SmallVector<std::pair<StringRef, path::Style>, 3> RootPaths;
386 RootPaths.emplace_back("/", path::Style::native);
387 RootPaths.emplace_back("//net/", path::Style::native);
388 RootPaths.emplace_back("c:\\", path::Style::windows);
389 RootPaths.emplace_back("//net//", path::Style::native);
390 RootPaths.emplace_back("c:\\\\", path::Style::windows);
391
392 for (auto &Path : RootPaths) {
393 SCOPED_TRACE(Path.first);
394 StringRef LastComponent = *path::rbegin(Path.first, Path.second);
395 EXPECT_EQ(1u, LastComponent.size());
396 EXPECT_TRUE(path::is_separator(LastComponent[0], Path.second));
397 }
398 }
399
400 #ifdef _WIN32
getEnvWin(const wchar_t * Var)401 std::string getEnvWin(const wchar_t *Var) {
402 std::string expected;
403 if (wchar_t const *path = ::_wgetenv(Var)) {
404 auto pathLen = ::wcslen(path);
405 ArrayRef<char> ref{reinterpret_cast<char const *>(path),
406 pathLen * sizeof(wchar_t)};
407 convertUTF16ToUTF8String(ref, expected);
408 }
409 return expected;
410 }
411 #else
412 // RAII helper to set and restore an environment variable.
413 class WithEnv {
414 const char *Var;
415 llvm::Optional<std::string> OriginalValue;
416
417 public:
WithEnv(const char * Var,const char * Value)418 WithEnv(const char *Var, const char *Value) : Var(Var) {
419 if (const char *V = ::getenv(Var))
420 OriginalValue.emplace(V);
421 if (Value)
422 ::setenv(Var, Value, 1);
423 else
424 ::unsetenv(Var);
425 }
~WithEnv()426 ~WithEnv() {
427 if (OriginalValue)
428 ::setenv(Var, OriginalValue->c_str(), 1);
429 else
430 ::unsetenv(Var);
431 }
432 };
433 #endif
434
TEST(Support,HomeDirectory)435 TEST(Support, HomeDirectory) {
436 std::string expected;
437 #ifdef _WIN32
438 expected = getEnvWin(L"USERPROFILE");
439 #else
440 if (char const *path = ::getenv("HOME"))
441 expected = path;
442 #endif
443 // Do not try to test it if we don't know what to expect.
444 // On Windows we use something better than env vars.
445 if (!expected.empty()) {
446 SmallString<128> HomeDir;
447 auto status = path::home_directory(HomeDir);
448 EXPECT_TRUE(status);
449 EXPECT_EQ(expected, HomeDir);
450 }
451 }
452
453 // Apple has their own solution for this.
454 #if defined(LLVM_ON_UNIX) && !defined(__APPLE__)
TEST(Support,HomeDirectoryWithNoEnv)455 TEST(Support, HomeDirectoryWithNoEnv) {
456 WithEnv Env("HOME", nullptr);
457
458 // Don't run the test if we have nothing to compare against.
459 struct passwd *pw = getpwuid(getuid());
460 if (!pw || !pw->pw_dir) return;
461 std::string PwDir = pw->pw_dir;
462
463 SmallString<128> HomeDir;
464 EXPECT_TRUE(path::home_directory(HomeDir));
465 EXPECT_EQ(PwDir, HomeDir);
466 }
467
TEST(Support,ConfigDirectoryWithEnv)468 TEST(Support, ConfigDirectoryWithEnv) {
469 WithEnv Env("XDG_CONFIG_HOME", "/xdg/config");
470
471 SmallString<128> ConfigDir;
472 EXPECT_TRUE(path::user_config_directory(ConfigDir));
473 EXPECT_EQ("/xdg/config", ConfigDir);
474 }
475
TEST(Support,ConfigDirectoryNoEnv)476 TEST(Support, ConfigDirectoryNoEnv) {
477 WithEnv Env("XDG_CONFIG_HOME", nullptr);
478
479 SmallString<128> Fallback;
480 ASSERT_TRUE(path::home_directory(Fallback));
481 path::append(Fallback, ".config");
482
483 SmallString<128> CacheDir;
484 EXPECT_TRUE(path::user_config_directory(CacheDir));
485 EXPECT_EQ(Fallback, CacheDir);
486 }
487
TEST(Support,CacheDirectoryWithEnv)488 TEST(Support, CacheDirectoryWithEnv) {
489 WithEnv Env("XDG_CACHE_HOME", "/xdg/cache");
490
491 SmallString<128> CacheDir;
492 EXPECT_TRUE(path::cache_directory(CacheDir));
493 EXPECT_EQ("/xdg/cache", CacheDir);
494 }
495
TEST(Support,CacheDirectoryNoEnv)496 TEST(Support, CacheDirectoryNoEnv) {
497 WithEnv Env("XDG_CACHE_HOME", nullptr);
498
499 SmallString<128> Fallback;
500 ASSERT_TRUE(path::home_directory(Fallback));
501 path::append(Fallback, ".cache");
502
503 SmallString<128> CacheDir;
504 EXPECT_TRUE(path::cache_directory(CacheDir));
505 EXPECT_EQ(Fallback, CacheDir);
506 }
507 #endif
508
509 #ifdef __APPLE__
TEST(Support,ConfigDirectory)510 TEST(Support, ConfigDirectory) {
511 SmallString<128> Fallback;
512 ASSERT_TRUE(path::home_directory(Fallback));
513 path::append(Fallback, "Library/Preferences");
514
515 SmallString<128> ConfigDir;
516 EXPECT_TRUE(path::user_config_directory(ConfigDir));
517 EXPECT_EQ(Fallback, ConfigDir);
518 }
519 #endif
520
521 #ifdef _WIN32
TEST(Support,ConfigDirectory)522 TEST(Support, ConfigDirectory) {
523 std::string Expected = getEnvWin(L"LOCALAPPDATA");
524 // Do not try to test it if we don't know what to expect.
525 if (!Expected.empty()) {
526 SmallString<128> CacheDir;
527 EXPECT_TRUE(path::user_config_directory(CacheDir));
528 EXPECT_EQ(Expected, CacheDir);
529 }
530 }
531
TEST(Support,CacheDirectory)532 TEST(Support, CacheDirectory) {
533 std::string Expected = getEnvWin(L"LOCALAPPDATA");
534 // Do not try to test it if we don't know what to expect.
535 if (!Expected.empty()) {
536 SmallString<128> CacheDir;
537 EXPECT_TRUE(path::cache_directory(CacheDir));
538 EXPECT_EQ(Expected, CacheDir);
539 }
540 }
541 #endif
542
TEST(Support,TempDirectory)543 TEST(Support, TempDirectory) {
544 SmallString<32> TempDir;
545 path::system_temp_directory(false, TempDir);
546 EXPECT_TRUE(!TempDir.empty());
547 TempDir.clear();
548 path::system_temp_directory(true, TempDir);
549 EXPECT_TRUE(!TempDir.empty());
550 }
551
552 #ifdef _WIN32
path2regex(std::string Path)553 static std::string path2regex(std::string Path) {
554 size_t Pos = 0;
555 while ((Pos = Path.find('\\', Pos)) != std::string::npos) {
556 Path.replace(Pos, 1, "\\\\");
557 Pos += 2;
558 }
559 return Path;
560 }
561
562 /// Helper for running temp dir test in separated process. See below.
563 #define EXPECT_TEMP_DIR(prepare, expected) \
564 EXPECT_EXIT( \
565 { \
566 prepare; \
567 SmallString<300> TempDir; \
568 path::system_temp_directory(true, TempDir); \
569 raw_os_ostream(std::cerr) << TempDir; \
570 std::exit(0); \
571 }, \
572 ::testing::ExitedWithCode(0), path2regex(expected))
573
TEST(SupportDeathTest,TempDirectoryOnWindows)574 TEST(SupportDeathTest, TempDirectoryOnWindows) {
575 // In this test we want to check how system_temp_directory responds to
576 // different values of specific env vars. To prevent corrupting env vars of
577 // the current process all checks are done in separated processes.
578 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"C:\\OtherFolder"), "C:\\OtherFolder");
579 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"C:/Unix/Path/Seperators"),
580 "C:\\Unix\\Path\\Seperators");
581 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"Local Path"), ".+\\Local Path$");
582 EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"F:\\TrailingSep\\"), "F:\\TrailingSep");
583 EXPECT_TEMP_DIR(
584 _wputenv_s(L"TMP", L"C:\\2\x03C0r-\x00B5\x00B3\\\x2135\x2080"),
585 "C:\\2\xCF\x80r-\xC2\xB5\xC2\xB3\\\xE2\x84\xB5\xE2\x82\x80");
586
587 // Test $TMP empty, $TEMP set.
588 EXPECT_TEMP_DIR(
589 {
590 _wputenv_s(L"TMP", L"");
591 _wputenv_s(L"TEMP", L"C:\\Valid\\Path");
592 },
593 "C:\\Valid\\Path");
594
595 // All related env vars empty
596 EXPECT_TEMP_DIR(
597 {
598 _wputenv_s(L"TMP", L"");
599 _wputenv_s(L"TEMP", L"");
600 _wputenv_s(L"USERPROFILE", L"");
601 },
602 "C:\\Temp");
603
604 // Test evn var / path with 260 chars.
605 SmallString<270> Expected{"C:\\Temp\\AB\\123456789"};
606 while (Expected.size() < 260)
607 Expected.append("\\DirNameWith19Charss");
608 ASSERT_EQ(260U, Expected.size());
609 EXPECT_TEMP_DIR(_putenv_s("TMP", Expected.c_str()), Expected.c_str());
610 }
611 #endif
612
613 class FileSystemTest : public testing::Test {
614 protected:
615 /// Unique temporary directory in which all created filesystem entities must
616 /// be placed. It is removed at the end of each test (must be empty).
617 SmallString<128> TestDirectory;
618 SmallString<128> NonExistantFile;
619
SetUp()620 void SetUp() override {
621 ASSERT_NO_ERROR(
622 fs::createUniqueDirectory("file-system-test", TestDirectory));
623 // We don't care about this specific file.
624 errs() << "Test Directory: " << TestDirectory << '\n';
625 errs().flush();
626 NonExistantFile = TestDirectory;
627
628 // Even though this value is hardcoded, is a 128-bit GUID, so we should be
629 // guaranteed that this file will never exist.
630 sys::path::append(NonExistantFile, "1B28B495C16344CB9822E588CD4C3EF0");
631 }
632
TearDown()633 void TearDown() override { ASSERT_NO_ERROR(fs::remove(TestDirectory.str())); }
634 };
635
TEST_F(FileSystemTest,Unique)636 TEST_F(FileSystemTest, Unique) {
637 // Create a temp file.
638 int FileDescriptor;
639 SmallString<64> TempPath;
640 ASSERT_NO_ERROR(
641 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
642
643 // The same file should return an identical unique id.
644 fs::UniqueID F1, F2;
645 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F1));
646 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F2));
647 ASSERT_EQ(F1, F2);
648
649 // Different files should return different unique ids.
650 int FileDescriptor2;
651 SmallString<64> TempPath2;
652 ASSERT_NO_ERROR(
653 fs::createTemporaryFile("prefix", "temp", FileDescriptor2, TempPath2));
654
655 fs::UniqueID D;
656 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D));
657 ASSERT_NE(D, F1);
658 ::close(FileDescriptor2);
659
660 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
661
662 // Two paths representing the same file on disk should still provide the
663 // same unique id. We can test this by making a hard link.
664 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
665 fs::UniqueID D2;
666 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D2));
667 ASSERT_EQ(D2, F1);
668
669 ::close(FileDescriptor);
670
671 SmallString<128> Dir1;
672 ASSERT_NO_ERROR(
673 fs::createUniqueDirectory("dir1", Dir1));
674 ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F1));
675 ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F2));
676 ASSERT_EQ(F1, F2);
677
678 SmallString<128> Dir2;
679 ASSERT_NO_ERROR(
680 fs::createUniqueDirectory("dir2", Dir2));
681 ASSERT_NO_ERROR(fs::getUniqueID(Dir2.c_str(), F2));
682 ASSERT_NE(F1, F2);
683 ASSERT_NO_ERROR(fs::remove(Dir1));
684 ASSERT_NO_ERROR(fs::remove(Dir2));
685 ASSERT_NO_ERROR(fs::remove(TempPath2));
686 ASSERT_NO_ERROR(fs::remove(TempPath));
687 }
688
TEST_F(FileSystemTest,RealPath)689 TEST_F(FileSystemTest, RealPath) {
690 ASSERT_NO_ERROR(
691 fs::create_directories(Twine(TestDirectory) + "/test1/test2/test3"));
692 ASSERT_TRUE(fs::exists(Twine(TestDirectory) + "/test1/test2/test3"));
693
694 SmallString<64> RealBase;
695 SmallString<64> Expected;
696 SmallString<64> Actual;
697
698 // TestDirectory itself might be under a symlink or have been specified with
699 // a different case than the existing temp directory. In such cases real_path
700 // on the concatenated path will differ in the TestDirectory portion from
701 // how we specified it. Make sure to compare against the real_path of the
702 // TestDirectory, and not just the value of TestDirectory.
703 ASSERT_NO_ERROR(fs::real_path(TestDirectory, RealBase));
704 path::native(Twine(RealBase) + "/test1/test2", Expected);
705
706 ASSERT_NO_ERROR(fs::real_path(
707 Twine(TestDirectory) + "/././test1/../test1/test2/./test3/..", Actual));
708
709 EXPECT_EQ(Expected, Actual);
710
711 SmallString<64> HomeDir;
712
713 // This can fail if $HOME is not set and getpwuid fails.
714 bool Result = llvm::sys::path::home_directory(HomeDir);
715 if (Result) {
716 ASSERT_NO_ERROR(fs::real_path(HomeDir, Expected));
717 ASSERT_NO_ERROR(fs::real_path("~", Actual, true));
718 EXPECT_EQ(Expected, Actual);
719 ASSERT_NO_ERROR(fs::real_path("~/", Actual, true));
720 EXPECT_EQ(Expected, Actual);
721 }
722
723 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/test1"));
724 }
725
TEST_F(FileSystemTest,ExpandTilde)726 TEST_F(FileSystemTest, ExpandTilde) {
727 SmallString<64> Expected;
728 SmallString<64> Actual;
729 SmallString<64> HomeDir;
730
731 // This can fail if $HOME is not set and getpwuid fails.
732 bool Result = llvm::sys::path::home_directory(HomeDir);
733 if (Result) {
734 fs::expand_tilde(HomeDir, Expected);
735
736 fs::expand_tilde("~", Actual);
737 EXPECT_EQ(Expected, Actual);
738
739 #ifdef _WIN32
740 Expected += "\\foo";
741 fs::expand_tilde("~\\foo", Actual);
742 #else
743 Expected += "/foo";
744 fs::expand_tilde("~/foo", Actual);
745 #endif
746
747 EXPECT_EQ(Expected, Actual);
748 }
749 }
750
751 #ifdef LLVM_ON_UNIX
TEST_F(FileSystemTest,RealPathNoReadPerm)752 TEST_F(FileSystemTest, RealPathNoReadPerm) {
753 SmallString<64> Expanded;
754
755 ASSERT_NO_ERROR(
756 fs::create_directories(Twine(TestDirectory) + "/noreadperm"));
757 ASSERT_TRUE(fs::exists(Twine(TestDirectory) + "/noreadperm"));
758
759 fs::setPermissions(Twine(TestDirectory) + "/noreadperm", fs::no_perms);
760 fs::setPermissions(Twine(TestDirectory) + "/noreadperm", fs::all_exe);
761
762 ASSERT_NO_ERROR(fs::real_path(Twine(TestDirectory) + "/noreadperm", Expanded,
763 false));
764
765 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/noreadperm"));
766 }
767 #endif
768
769
TEST_F(FileSystemTest,TempFileKeepDiscard)770 TEST_F(FileSystemTest, TempFileKeepDiscard) {
771 // We can keep then discard.
772 auto TempFileOrError = fs::TempFile::create(TestDirectory + "/test-%%%%");
773 ASSERT_TRUE((bool)TempFileOrError);
774 fs::TempFile File = std::move(*TempFileOrError);
775 ASSERT_EQ(-1, TempFileOrError->FD);
776 ASSERT_FALSE((bool)File.keep(TestDirectory + "/keep"));
777 ASSERT_FALSE((bool)File.discard());
778 ASSERT_TRUE(fs::exists(TestDirectory + "/keep"));
779 ASSERT_NO_ERROR(fs::remove(TestDirectory + "/keep"));
780 }
781
TEST_F(FileSystemTest,TempFileDiscardDiscard)782 TEST_F(FileSystemTest, TempFileDiscardDiscard) {
783 // We can discard twice.
784 auto TempFileOrError = fs::TempFile::create(TestDirectory + "/test-%%%%");
785 ASSERT_TRUE((bool)TempFileOrError);
786 fs::TempFile File = std::move(*TempFileOrError);
787 ASSERT_EQ(-1, TempFileOrError->FD);
788 ASSERT_FALSE((bool)File.discard());
789 ASSERT_FALSE((bool)File.discard());
790 ASSERT_FALSE(fs::exists(TestDirectory + "/keep"));
791 }
792
TEST_F(FileSystemTest,TempFiles)793 TEST_F(FileSystemTest, TempFiles) {
794 // Create a temp file.
795 int FileDescriptor;
796 SmallString<64> TempPath;
797 ASSERT_NO_ERROR(
798 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
799
800 // Make sure it exists.
801 ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
802
803 // Create another temp tile.
804 int FD2;
805 SmallString<64> TempPath2;
806 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD2, TempPath2));
807 ASSERT_TRUE(TempPath2.endswith(".temp"));
808 ASSERT_NE(TempPath.str(), TempPath2.str());
809
810 fs::file_status A, B;
811 ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
812 ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
813 EXPECT_FALSE(fs::equivalent(A, B));
814
815 ::close(FD2);
816
817 // Remove Temp2.
818 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
819 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
820 ASSERT_EQ(fs::remove(Twine(TempPath2), false),
821 errc::no_such_file_or_directory);
822
823 std::error_code EC = fs::status(TempPath2.c_str(), B);
824 EXPECT_EQ(EC, errc::no_such_file_or_directory);
825 EXPECT_EQ(B.type(), fs::file_type::file_not_found);
826
827 // Make sure Temp2 doesn't exist.
828 ASSERT_EQ(fs::access(Twine(TempPath2), sys::fs::AccessMode::Exist),
829 errc::no_such_file_or_directory);
830
831 SmallString<64> TempPath3;
832 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "", TempPath3));
833 ASSERT_FALSE(TempPath3.endswith("."));
834 FileRemover Cleanup3(TempPath3);
835
836 // Create a hard link to Temp1.
837 ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
838 bool equal;
839 ASSERT_NO_ERROR(fs::equivalent(Twine(TempPath), Twine(TempPath2), equal));
840 EXPECT_TRUE(equal);
841 ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
842 ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
843 EXPECT_TRUE(fs::equivalent(A, B));
844
845 // Remove Temp1.
846 ::close(FileDescriptor);
847 ASSERT_NO_ERROR(fs::remove(Twine(TempPath)));
848
849 // Remove the hard link.
850 ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
851
852 // Make sure Temp1 doesn't exist.
853 ASSERT_EQ(fs::access(Twine(TempPath), sys::fs::AccessMode::Exist),
854 errc::no_such_file_or_directory);
855
856 #ifdef _WIN32
857 // Path name > 260 chars should get an error.
858 const char *Path270 =
859 "abcdefghijklmnopqrstuvwxyz9abcdefghijklmnopqrstuvwxyz8"
860 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
861 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
862 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
863 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
864 EXPECT_EQ(fs::createUniqueFile(Path270, FileDescriptor, TempPath),
865 errc::invalid_argument);
866 // Relative path < 247 chars, no problem.
867 const char *Path216 =
868 "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
869 "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
870 "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
871 "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
872 ASSERT_NO_ERROR(fs::createTemporaryFile(Path216, "", TempPath));
873 ASSERT_NO_ERROR(fs::remove(Twine(TempPath)));
874 #endif
875 }
876
TEST_F(FileSystemTest,TempFileCollisions)877 TEST_F(FileSystemTest, TempFileCollisions) {
878 SmallString<128> TestDirectory;
879 ASSERT_NO_ERROR(
880 fs::createUniqueDirectory("CreateUniqueFileTest", TestDirectory));
881 FileRemover Cleanup(TestDirectory);
882 SmallString<128> Model = TestDirectory;
883 path::append(Model, "%.tmp");
884 SmallString<128> Path;
885 std::vector<fs::TempFile> TempFiles;
886
887 auto TryCreateTempFile = [&]() {
888 Expected<fs::TempFile> T = fs::TempFile::create(Model);
889 if (T) {
890 TempFiles.push_back(std::move(*T));
891 return true;
892 } else {
893 logAllUnhandledErrors(T.takeError(), errs(),
894 "Failed to create temporary file: ");
895 return false;
896 }
897 };
898
899 // Our single-character template allows for 16 unique names. Check that
900 // calling TryCreateTempFile repeatedly results in 16 successes.
901 // Because the test depends on random numbers, it could theoretically fail.
902 // However, the probability of this happening is tiny: with 32 calls, each
903 // of which will retry up to 128 times, to not get a given digit we would
904 // have to fail at least 15 + 17 * 128 = 2191 attempts. The probability of
905 // 2191 attempts not producing a given hexadecimal digit is
906 // (1 - 1/16) ** 2191 or 3.88e-62.
907 int Successes = 0;
908 for (int i = 0; i < 32; ++i)
909 if (TryCreateTempFile()) ++Successes;
910 EXPECT_EQ(Successes, 16);
911
912 for (fs::TempFile &T : TempFiles)
913 cantFail(T.discard());
914 }
915
TEST_F(FileSystemTest,CreateDir)916 TEST_F(FileSystemTest, CreateDir) {
917 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
918 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
919 ASSERT_EQ(fs::create_directory(Twine(TestDirectory) + "foo", false),
920 errc::file_exists);
921 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "foo"));
922
923 #ifdef LLVM_ON_UNIX
924 // Set a 0000 umask so that we can test our directory permissions.
925 mode_t OldUmask = ::umask(0000);
926
927 fs::file_status Status;
928 ASSERT_NO_ERROR(
929 fs::create_directory(Twine(TestDirectory) + "baz500", false,
930 fs::perms::owner_read | fs::perms::owner_exe));
931 ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz500", Status));
932 ASSERT_EQ(Status.permissions() & fs::perms::all_all,
933 fs::perms::owner_read | fs::perms::owner_exe);
934 ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "baz777", false,
935 fs::perms::all_all));
936 ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz777", Status));
937 ASSERT_EQ(Status.permissions() & fs::perms::all_all, fs::perms::all_all);
938
939 // Restore umask to be safe.
940 ::umask(OldUmask);
941 #endif
942
943 #ifdef _WIN32
944 // Prove that create_directories() can handle a pathname > 248 characters,
945 // which is the documented limit for CreateDirectory().
946 // (248 is MAX_PATH subtracting room for an 8.3 filename.)
947 // Generate a directory path guaranteed to fall into that range.
948 size_t TmpLen = TestDirectory.size();
949 const char *OneDir = "\\123456789";
950 size_t OneDirLen = strlen(OneDir);
951 ASSERT_LT(OneDirLen, 12U);
952 size_t NLevels = ((248 - TmpLen) / OneDirLen) + 1;
953 SmallString<260> LongDir(TestDirectory);
954 for (size_t I = 0; I < NLevels; ++I)
955 LongDir.append(OneDir);
956 ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir)));
957 ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir)));
958 ASSERT_EQ(fs::create_directories(Twine(LongDir), false),
959 errc::file_exists);
960 // Tidy up, "recursively" removing the directories.
961 StringRef ThisDir(LongDir);
962 for (size_t J = 0; J < NLevels; ++J) {
963 ASSERT_NO_ERROR(fs::remove(ThisDir));
964 ThisDir = path::parent_path(ThisDir);
965 }
966
967 // Also verify that paths with Unix separators are handled correctly.
968 std::string LongPathWithUnixSeparators(TestDirectory.str());
969 // Add at least one subdirectory to TestDirectory, and replace slashes with
970 // backslashes
971 do {
972 LongPathWithUnixSeparators.append("/DirNameWith19Charss");
973 } while (LongPathWithUnixSeparators.size() < 260);
974 std::replace(LongPathWithUnixSeparators.begin(),
975 LongPathWithUnixSeparators.end(),
976 '\\', '/');
977 ASSERT_NO_ERROR(fs::create_directories(Twine(LongPathWithUnixSeparators)));
978 // cleanup
979 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) +
980 "/DirNameWith19Charss"));
981
982 // Similarly for a relative pathname. Need to set the current directory to
983 // TestDirectory so that the one we create ends up in the right place.
984 char PreviousDir[260];
985 size_t PreviousDirLen = ::GetCurrentDirectoryA(260, PreviousDir);
986 ASSERT_GT(PreviousDirLen, 0U);
987 ASSERT_LT(PreviousDirLen, 260U);
988 ASSERT_NE(::SetCurrentDirectoryA(TestDirectory.c_str()), 0);
989 LongDir.clear();
990 // Generate a relative directory name with absolute length > 248.
991 size_t LongDirLen = 249 - TestDirectory.size();
992 LongDir.assign(LongDirLen, 'a');
993 ASSERT_NO_ERROR(fs::create_directory(Twine(LongDir)));
994 // While we're here, prove that .. and . handling works in these long paths.
995 const char *DotDotDirs = "\\..\\.\\b";
996 LongDir.append(DotDotDirs);
997 ASSERT_NO_ERROR(fs::create_directory("b"));
998 ASSERT_EQ(fs::create_directory(Twine(LongDir), false), errc::file_exists);
999 // And clean up.
1000 ASSERT_NO_ERROR(fs::remove("b"));
1001 ASSERT_NO_ERROR(fs::remove(
1002 Twine(LongDir.substr(0, LongDir.size() - strlen(DotDotDirs)))));
1003 ASSERT_NE(::SetCurrentDirectoryA(PreviousDir), 0);
1004 #endif
1005 }
1006
TEST_F(FileSystemTest,DirectoryIteration)1007 TEST_F(FileSystemTest, DirectoryIteration) {
1008 std::error_code ec;
1009 for (fs::directory_iterator i(".", ec), e; i != e; i.increment(ec))
1010 ASSERT_NO_ERROR(ec);
1011
1012 // Create a known hierarchy to recurse over.
1013 ASSERT_NO_ERROR(
1014 fs::create_directories(Twine(TestDirectory) + "/recursive/a0/aa1"));
1015 ASSERT_NO_ERROR(
1016 fs::create_directories(Twine(TestDirectory) + "/recursive/a0/ab1"));
1017 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) +
1018 "/recursive/dontlookhere/da1"));
1019 ASSERT_NO_ERROR(
1020 fs::create_directories(Twine(TestDirectory) + "/recursive/z0/za1"));
1021 ASSERT_NO_ERROR(
1022 fs::create_directories(Twine(TestDirectory) + "/recursive/pop/p1"));
1023 typedef std::vector<std::string> v_t;
1024 v_t visited;
1025 for (fs::recursive_directory_iterator i(Twine(TestDirectory)
1026 + "/recursive", ec), e; i != e; i.increment(ec)){
1027 ASSERT_NO_ERROR(ec);
1028 if (path::filename(i->path()) == "p1") {
1029 i.pop();
1030 // FIXME: recursive_directory_iterator should be more robust.
1031 if (i == e) break;
1032 }
1033 if (path::filename(i->path()) == "dontlookhere")
1034 i.no_push();
1035 visited.push_back(std::string(path::filename(i->path())));
1036 }
1037 v_t::const_iterator a0 = find(visited, "a0");
1038 v_t::const_iterator aa1 = find(visited, "aa1");
1039 v_t::const_iterator ab1 = find(visited, "ab1");
1040 v_t::const_iterator dontlookhere = find(visited, "dontlookhere");
1041 v_t::const_iterator da1 = find(visited, "da1");
1042 v_t::const_iterator z0 = find(visited, "z0");
1043 v_t::const_iterator za1 = find(visited, "za1");
1044 v_t::const_iterator pop = find(visited, "pop");
1045 v_t::const_iterator p1 = find(visited, "p1");
1046
1047 // Make sure that each path was visited correctly.
1048 ASSERT_NE(a0, visited.end());
1049 ASSERT_NE(aa1, visited.end());
1050 ASSERT_NE(ab1, visited.end());
1051 ASSERT_NE(dontlookhere, visited.end());
1052 ASSERT_EQ(da1, visited.end()); // Not visited.
1053 ASSERT_NE(z0, visited.end());
1054 ASSERT_NE(za1, visited.end());
1055 ASSERT_NE(pop, visited.end());
1056 ASSERT_EQ(p1, visited.end()); // Not visited.
1057
1058 // Make sure that parents were visited before children. No other ordering
1059 // guarantees can be made across siblings.
1060 ASSERT_LT(a0, aa1);
1061 ASSERT_LT(a0, ab1);
1062 ASSERT_LT(z0, za1);
1063
1064 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/aa1"));
1065 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/ab1"));
1066 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0"));
1067 ASSERT_NO_ERROR(
1068 fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere/da1"));
1069 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere"));
1070 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop/p1"));
1071 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop"));
1072 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0/za1"));
1073 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0"));
1074 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive"));
1075
1076 // Test recursive_directory_iterator level()
1077 ASSERT_NO_ERROR(
1078 fs::create_directories(Twine(TestDirectory) + "/reclevel/a/b/c"));
1079 fs::recursive_directory_iterator I(Twine(TestDirectory) + "/reclevel", ec), E;
1080 for (int l = 0; I != E; I.increment(ec), ++l) {
1081 ASSERT_NO_ERROR(ec);
1082 EXPECT_EQ(I.level(), l);
1083 }
1084 EXPECT_EQ(I, E);
1085 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a/b/c"));
1086 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a/b"));
1087 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a"));
1088 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel"));
1089 }
1090
1091 #ifdef LLVM_ON_UNIX
TEST_F(FileSystemTest,BrokenSymlinkDirectoryIteration)1092 TEST_F(FileSystemTest, BrokenSymlinkDirectoryIteration) {
1093 // Create a known hierarchy to recurse over.
1094 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) + "/symlink"));
1095 ASSERT_NO_ERROR(
1096 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/a"));
1097 ASSERT_NO_ERROR(
1098 fs::create_directories(Twine(TestDirectory) + "/symlink/b/bb"));
1099 ASSERT_NO_ERROR(
1100 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/b/ba"));
1101 ASSERT_NO_ERROR(
1102 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/b/bc"));
1103 ASSERT_NO_ERROR(
1104 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/c"));
1105 ASSERT_NO_ERROR(
1106 fs::create_directories(Twine(TestDirectory) + "/symlink/d/dd/ddd"));
1107 ASSERT_NO_ERROR(fs::create_link(Twine(TestDirectory) + "/symlink/d/dd",
1108 Twine(TestDirectory) + "/symlink/d/da"));
1109 ASSERT_NO_ERROR(
1110 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/e"));
1111
1112 typedef std::vector<std::string> v_t;
1113 v_t VisitedNonBrokenSymlinks;
1114 v_t VisitedBrokenSymlinks;
1115 std::error_code ec;
1116 using testing::UnorderedElementsAre;
1117 using testing::UnorderedElementsAreArray;
1118
1119 // Broken symbol links are expected to throw an error.
1120 for (fs::directory_iterator i(Twine(TestDirectory) + "/symlink", ec), e;
1121 i != e; i.increment(ec)) {
1122 ASSERT_NO_ERROR(ec);
1123 if (i->status().getError() ==
1124 std::make_error_code(std::errc::no_such_file_or_directory)) {
1125 VisitedBrokenSymlinks.push_back(std::string(path::filename(i->path())));
1126 continue;
1127 }
1128 VisitedNonBrokenSymlinks.push_back(std::string(path::filename(i->path())));
1129 }
1130 EXPECT_THAT(VisitedNonBrokenSymlinks, UnorderedElementsAre("b", "d"));
1131 VisitedNonBrokenSymlinks.clear();
1132
1133 EXPECT_THAT(VisitedBrokenSymlinks, UnorderedElementsAre("a", "c", "e"));
1134 VisitedBrokenSymlinks.clear();
1135
1136 // Broken symbol links are expected to throw an error.
1137 for (fs::recursive_directory_iterator i(
1138 Twine(TestDirectory) + "/symlink", ec), e; i != e; i.increment(ec)) {
1139 ASSERT_NO_ERROR(ec);
1140 if (i->status().getError() ==
1141 std::make_error_code(std::errc::no_such_file_or_directory)) {
1142 VisitedBrokenSymlinks.push_back(std::string(path::filename(i->path())));
1143 continue;
1144 }
1145 VisitedNonBrokenSymlinks.push_back(std::string(path::filename(i->path())));
1146 }
1147 EXPECT_THAT(VisitedNonBrokenSymlinks,
1148 UnorderedElementsAre("b", "bb", "d", "da", "dd", "ddd", "ddd"));
1149 VisitedNonBrokenSymlinks.clear();
1150
1151 EXPECT_THAT(VisitedBrokenSymlinks,
1152 UnorderedElementsAre("a", "ba", "bc", "c", "e"));
1153 VisitedBrokenSymlinks.clear();
1154
1155 for (fs::recursive_directory_iterator i(
1156 Twine(TestDirectory) + "/symlink", ec, /*follow_symlinks=*/false), e;
1157 i != e; i.increment(ec)) {
1158 ASSERT_NO_ERROR(ec);
1159 if (i->status().getError() ==
1160 std::make_error_code(std::errc::no_such_file_or_directory)) {
1161 VisitedBrokenSymlinks.push_back(std::string(path::filename(i->path())));
1162 continue;
1163 }
1164 VisitedNonBrokenSymlinks.push_back(std::string(path::filename(i->path())));
1165 }
1166 EXPECT_THAT(VisitedNonBrokenSymlinks,
1167 UnorderedElementsAreArray({"a", "b", "ba", "bb", "bc", "c", "d",
1168 "da", "dd", "ddd", "e"}));
1169 VisitedNonBrokenSymlinks.clear();
1170
1171 EXPECT_THAT(VisitedBrokenSymlinks, UnorderedElementsAre());
1172 VisitedBrokenSymlinks.clear();
1173
1174 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/symlink"));
1175 }
1176 #endif
1177
1178 #ifdef _WIN32
TEST_F(FileSystemTest,UTF8ToUTF16DirectoryIteration)1179 TEST_F(FileSystemTest, UTF8ToUTF16DirectoryIteration) {
1180 // The Windows filesystem support uses UTF-16 and converts paths from the
1181 // input UTF-8. The UTF-16 equivalent of the input path can be shorter in
1182 // length.
1183
1184 // This test relies on TestDirectory not being so long such that MAX_PATH
1185 // would be exceeded (see widenPath). If that were the case, the UTF-16
1186 // path is likely to be longer than the input.
1187 const char *Pi = "\xcf\x80"; // UTF-8 lower case pi.
1188 std::string RootDir = (TestDirectory + "/" + Pi).str();
1189
1190 // Create test directories.
1191 ASSERT_NO_ERROR(fs::create_directories(Twine(RootDir) + "/a"));
1192 ASSERT_NO_ERROR(fs::create_directories(Twine(RootDir) + "/b"));
1193
1194 std::error_code EC;
1195 unsigned Count = 0;
1196 for (fs::directory_iterator I(Twine(RootDir), EC), E; I != E;
1197 I.increment(EC)) {
1198 ASSERT_NO_ERROR(EC);
1199 StringRef DirName = path::filename(I->path());
1200 EXPECT_TRUE(DirName == "a" || DirName == "b");
1201 ++Count;
1202 }
1203 EXPECT_EQ(Count, 2U);
1204
1205 ASSERT_NO_ERROR(fs::remove(Twine(RootDir) + "/a"));
1206 ASSERT_NO_ERROR(fs::remove(Twine(RootDir) + "/b"));
1207 ASSERT_NO_ERROR(fs::remove(Twine(RootDir)));
1208 }
1209 #endif
1210
TEST_F(FileSystemTest,Remove)1211 TEST_F(FileSystemTest, Remove) {
1212 SmallString<64> BaseDir;
1213 SmallString<64> Paths[4];
1214 int fds[4];
1215 ASSERT_NO_ERROR(fs::createUniqueDirectory("fs_remove", BaseDir));
1216
1217 ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir) + "/foo/bar/baz"));
1218 ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir) + "/foo/bar/buzz"));
1219 ASSERT_NO_ERROR(fs::createUniqueFile(
1220 Twine(BaseDir) + "/foo/bar/baz/%%%%%%.tmp", fds[0], Paths[0]));
1221 ASSERT_NO_ERROR(fs::createUniqueFile(
1222 Twine(BaseDir) + "/foo/bar/baz/%%%%%%.tmp", fds[1], Paths[1]));
1223 ASSERT_NO_ERROR(fs::createUniqueFile(
1224 Twine(BaseDir) + "/foo/bar/buzz/%%%%%%.tmp", fds[2], Paths[2]));
1225 ASSERT_NO_ERROR(fs::createUniqueFile(
1226 Twine(BaseDir) + "/foo/bar/buzz/%%%%%%.tmp", fds[3], Paths[3]));
1227
1228 for (int fd : fds)
1229 ::close(fd);
1230
1231 EXPECT_TRUE(fs::exists(Twine(BaseDir) + "/foo/bar/baz"));
1232 EXPECT_TRUE(fs::exists(Twine(BaseDir) + "/foo/bar/buzz"));
1233 EXPECT_TRUE(fs::exists(Paths[0]));
1234 EXPECT_TRUE(fs::exists(Paths[1]));
1235 EXPECT_TRUE(fs::exists(Paths[2]));
1236 EXPECT_TRUE(fs::exists(Paths[3]));
1237
1238 ASSERT_NO_ERROR(fs::remove_directories("D:/footest"));
1239
1240 ASSERT_NO_ERROR(fs::remove_directories(BaseDir));
1241 ASSERT_FALSE(fs::exists(BaseDir));
1242 }
1243
1244 #ifdef _WIN32
TEST_F(FileSystemTest,CarriageReturn)1245 TEST_F(FileSystemTest, CarriageReturn) {
1246 SmallString<128> FilePathname(TestDirectory);
1247 std::error_code EC;
1248 path::append(FilePathname, "test");
1249
1250 {
1251 raw_fd_ostream File(FilePathname, EC, sys::fs::OF_Text);
1252 ASSERT_NO_ERROR(EC);
1253 File << '\n';
1254 }
1255 {
1256 auto Buf = MemoryBuffer::getFile(FilePathname.str());
1257 EXPECT_TRUE((bool)Buf);
1258 EXPECT_EQ(Buf.get()->getBuffer(), "\r\n");
1259 }
1260
1261 {
1262 raw_fd_ostream File(FilePathname, EC, sys::fs::OF_None);
1263 ASSERT_NO_ERROR(EC);
1264 File << '\n';
1265 }
1266 {
1267 auto Buf = MemoryBuffer::getFile(FilePathname.str());
1268 EXPECT_TRUE((bool)Buf);
1269 EXPECT_EQ(Buf.get()->getBuffer(), "\n");
1270 }
1271 ASSERT_NO_ERROR(fs::remove(Twine(FilePathname)));
1272 }
1273 #endif
1274
TEST_F(FileSystemTest,Resize)1275 TEST_F(FileSystemTest, Resize) {
1276 int FD;
1277 SmallString<64> TempPath;
1278 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1279 ASSERT_NO_ERROR(fs::resize_file(FD, 123));
1280 fs::file_status Status;
1281 ASSERT_NO_ERROR(fs::status(FD, Status));
1282 ASSERT_EQ(Status.getSize(), 123U);
1283 ::close(FD);
1284 ASSERT_NO_ERROR(fs::remove(TempPath));
1285 }
1286
TEST_F(FileSystemTest,MD5)1287 TEST_F(FileSystemTest, MD5) {
1288 int FD;
1289 SmallString<64> TempPath;
1290 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1291 StringRef Data("abcdefghijklmnopqrstuvwxyz");
1292 ASSERT_EQ(write(FD, Data.data(), Data.size()), static_cast<ssize_t>(Data.size()));
1293 lseek(FD, 0, SEEK_SET);
1294 auto Hash = fs::md5_contents(FD);
1295 ::close(FD);
1296 ASSERT_NO_ERROR(Hash.getError());
1297
1298 EXPECT_STREQ("c3fcd3d76192e4007dfb496cca67e13b", Hash->digest().c_str());
1299 }
1300
TEST_F(FileSystemTest,FileMapping)1301 TEST_F(FileSystemTest, FileMapping) {
1302 // Create a temp file.
1303 int FileDescriptor;
1304 SmallString<64> TempPath;
1305 ASSERT_NO_ERROR(
1306 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
1307 unsigned Size = 4096;
1308 ASSERT_NO_ERROR(fs::resize_file(FileDescriptor, Size));
1309
1310 // Map in temp file and add some content
1311 std::error_code EC;
1312 StringRef Val("hello there");
1313 {
1314 fs::mapped_file_region mfr(fs::convertFDToNativeFile(FileDescriptor),
1315 fs::mapped_file_region::readwrite, Size, 0, EC);
1316 ASSERT_NO_ERROR(EC);
1317 std::copy(Val.begin(), Val.end(), mfr.data());
1318 // Explicitly add a 0.
1319 mfr.data()[Val.size()] = 0;
1320 // Unmap temp file
1321 }
1322 ASSERT_EQ(close(FileDescriptor), 0);
1323
1324 // Map it back in read-only
1325 {
1326 int FD;
1327 EC = fs::openFileForRead(Twine(TempPath), FD);
1328 ASSERT_NO_ERROR(EC);
1329 fs::mapped_file_region mfr(fs::convertFDToNativeFile(FD),
1330 fs::mapped_file_region::readonly, Size, 0, EC);
1331 ASSERT_NO_ERROR(EC);
1332
1333 // Verify content
1334 EXPECT_EQ(StringRef(mfr.const_data()), Val);
1335
1336 // Unmap temp file
1337 fs::mapped_file_region m(fs::convertFDToNativeFile(FD),
1338 fs::mapped_file_region::readonly, Size, 0, EC);
1339 ASSERT_NO_ERROR(EC);
1340 ASSERT_EQ(close(FD), 0);
1341 }
1342 ASSERT_NO_ERROR(fs::remove(TempPath));
1343 }
1344
TEST(Support,NormalizePath)1345 TEST(Support, NormalizePath) {
1346 // Input, Expected Win, Expected Posix
1347 using TestTuple = std::tuple<const char *, const char *, const char *>;
1348 std::vector<TestTuple> Tests;
1349 Tests.emplace_back("a", "a", "a");
1350 Tests.emplace_back("a/b", "a\\b", "a/b");
1351 Tests.emplace_back("a\\b", "a\\b", "a/b");
1352 Tests.emplace_back("a\\\\b", "a\\\\b", "a//b");
1353 Tests.emplace_back("\\a", "\\a", "/a");
1354 Tests.emplace_back("a\\", "a\\", "a/");
1355 Tests.emplace_back("a\\t", "a\\t", "a/t");
1356
1357 for (auto &T : Tests) {
1358 SmallString<64> Win(std::get<0>(T));
1359 SmallString<64> Posix(Win);
1360 path::native(Win, path::Style::windows);
1361 path::native(Posix, path::Style::posix);
1362 EXPECT_EQ(std::get<1>(T), Win);
1363 EXPECT_EQ(std::get<2>(T), Posix);
1364 }
1365
1366 #if defined(_WIN32)
1367 SmallString<64> PathHome;
1368 path::home_directory(PathHome);
1369
1370 const char *Path7a = "~/aaa";
1371 SmallString<64> Path7(Path7a);
1372 path::native(Path7);
1373 EXPECT_TRUE(Path7.endswith("\\aaa"));
1374 EXPECT_TRUE(Path7.startswith(PathHome));
1375 EXPECT_EQ(Path7.size(), PathHome.size() + strlen(Path7a + 1));
1376
1377 const char *Path8a = "~";
1378 SmallString<64> Path8(Path8a);
1379 path::native(Path8);
1380 EXPECT_EQ(Path8, PathHome);
1381
1382 const char *Path9a = "~aaa";
1383 SmallString<64> Path9(Path9a);
1384 path::native(Path9);
1385 EXPECT_EQ(Path9, "~aaa");
1386
1387 const char *Path10a = "aaa/~/b";
1388 SmallString<64> Path10(Path10a);
1389 path::native(Path10);
1390 EXPECT_EQ(Path10, "aaa\\~\\b");
1391 #endif
1392 }
1393
TEST(Support,RemoveLeadingDotSlash)1394 TEST(Support, RemoveLeadingDotSlash) {
1395 StringRef Path1("././/foolz/wat");
1396 StringRef Path2("./////");
1397
1398 Path1 = path::remove_leading_dotslash(Path1);
1399 EXPECT_EQ(Path1, "foolz/wat");
1400 Path2 = path::remove_leading_dotslash(Path2);
1401 EXPECT_EQ(Path2, "");
1402 }
1403
remove_dots(StringRef path,bool remove_dot_dot,path::Style style)1404 static std::string remove_dots(StringRef path, bool remove_dot_dot,
1405 path::Style style) {
1406 SmallString<256> buffer(path);
1407 path::remove_dots(buffer, remove_dot_dot, style);
1408 return std::string(buffer.str());
1409 }
1410
TEST(Support,RemoveDots)1411 TEST(Support, RemoveDots) {
1412 EXPECT_EQ("foolz\\wat",
1413 remove_dots(".\\.\\\\foolz\\wat", false, path::Style::windows));
1414 EXPECT_EQ("", remove_dots(".\\\\\\\\\\", false, path::Style::windows));
1415
1416 EXPECT_EQ("a\\..\\b\\c",
1417 remove_dots(".\\a\\..\\b\\c", false, path::Style::windows));
1418 EXPECT_EQ("b\\c", remove_dots(".\\a\\..\\b\\c", true, path::Style::windows));
1419 EXPECT_EQ("c", remove_dots(".\\.\\c", true, path::Style::windows));
1420 EXPECT_EQ("..\\a\\c",
1421 remove_dots("..\\a\\b\\..\\c", true, path::Style::windows));
1422 EXPECT_EQ("..\\..\\a\\c",
1423 remove_dots("..\\..\\a\\b\\..\\c", true, path::Style::windows));
1424 EXPECT_EQ("C:\\a\\c", remove_dots("C:\\foo\\bar//..\\..\\a\\c", true,
1425 path::Style::windows));
1426
1427 // FIXME: These leading forward slashes are emergent behavior. VFS depends on
1428 // this behavior now.
1429 EXPECT_EQ("C:/bar",
1430 remove_dots("C:/foo/../bar", true, path::Style::windows));
1431 EXPECT_EQ("C:/foo\\bar",
1432 remove_dots("C:/foo/bar", true, path::Style::windows));
1433 EXPECT_EQ("C:/foo\\bar",
1434 remove_dots("C:/foo\\bar", true, path::Style::windows));
1435 EXPECT_EQ("/", remove_dots("/", true, path::Style::windows));
1436 EXPECT_EQ("C:/", remove_dots("C:/", true, path::Style::windows));
1437
1438 // Some clients of remove_dots expect it to remove trailing slashes. Again,
1439 // this is emergent behavior that VFS relies on, and not inherently part of
1440 // the specification.
1441 EXPECT_EQ("C:\\foo\\bar",
1442 remove_dots("C:\\foo\\bar\\", true, path::Style::windows));
1443 EXPECT_EQ("/foo/bar",
1444 remove_dots("/foo/bar/", true, path::Style::posix));
1445
1446 // A double separator is rewritten.
1447 EXPECT_EQ("C:/foo\\bar", remove_dots("C:/foo//bar", true, path::Style::windows));
1448
1449 SmallString<64> Path1(".\\.\\c");
1450 EXPECT_TRUE(path::remove_dots(Path1, true, path::Style::windows));
1451 EXPECT_EQ("c", Path1);
1452
1453 EXPECT_EQ("foolz/wat",
1454 remove_dots("././/foolz/wat", false, path::Style::posix));
1455 EXPECT_EQ("", remove_dots("./////", false, path::Style::posix));
1456
1457 EXPECT_EQ("a/../b/c", remove_dots("./a/../b/c", false, path::Style::posix));
1458 EXPECT_EQ("b/c", remove_dots("./a/../b/c", true, path::Style::posix));
1459 EXPECT_EQ("c", remove_dots("././c", true, path::Style::posix));
1460 EXPECT_EQ("../a/c", remove_dots("../a/b/../c", true, path::Style::posix));
1461 EXPECT_EQ("../../a/c",
1462 remove_dots("../../a/b/../c", true, path::Style::posix));
1463 EXPECT_EQ("/a/c", remove_dots("/../../a/c", true, path::Style::posix));
1464 EXPECT_EQ("/a/c",
1465 remove_dots("/../a/b//../././/c", true, path::Style::posix));
1466 EXPECT_EQ("/", remove_dots("/", true, path::Style::posix));
1467
1468 // FIXME: Leaving behind this double leading slash seems like a bug.
1469 EXPECT_EQ("//foo/bar",
1470 remove_dots("//foo/bar/", true, path::Style::posix));
1471
1472 SmallString<64> Path2("././c");
1473 EXPECT_TRUE(path::remove_dots(Path2, true, path::Style::posix));
1474 EXPECT_EQ("c", Path2);
1475 }
1476
TEST(Support,ReplacePathPrefix)1477 TEST(Support, ReplacePathPrefix) {
1478 SmallString<64> Path1("/foo");
1479 SmallString<64> Path2("/old/foo");
1480 SmallString<64> Path3("/oldnew/foo");
1481 SmallString<64> Path4("C:\\old/foo\\bar");
1482 SmallString<64> OldPrefix("/old");
1483 SmallString<64> OldPrefixSep("/old/");
1484 SmallString<64> OldPrefixWin("c:/oLD/F");
1485 SmallString<64> NewPrefix("/new");
1486 SmallString<64> NewPrefix2("/longernew");
1487 SmallString<64> EmptyPrefix("");
1488 bool Found;
1489
1490 SmallString<64> Path = Path1;
1491 Found = path::replace_path_prefix(Path, OldPrefix, NewPrefix);
1492 EXPECT_FALSE(Found);
1493 EXPECT_EQ(Path, "/foo");
1494 Path = Path2;
1495 Found = path::replace_path_prefix(Path, OldPrefix, NewPrefix);
1496 EXPECT_TRUE(Found);
1497 EXPECT_EQ(Path, "/new/foo");
1498 Path = Path2;
1499 Found = path::replace_path_prefix(Path, OldPrefix, NewPrefix2);
1500 EXPECT_TRUE(Found);
1501 EXPECT_EQ(Path, "/longernew/foo");
1502 Path = Path1;
1503 Found = path::replace_path_prefix(Path, EmptyPrefix, NewPrefix);
1504 EXPECT_TRUE(Found);
1505 EXPECT_EQ(Path, "/new/foo");
1506 Path = Path2;
1507 Found = path::replace_path_prefix(Path, OldPrefix, EmptyPrefix);
1508 EXPECT_TRUE(Found);
1509 EXPECT_EQ(Path, "/foo");
1510 Path = Path2;
1511 Found = path::replace_path_prefix(Path, OldPrefixSep, EmptyPrefix);
1512 EXPECT_TRUE(Found);
1513 EXPECT_EQ(Path, "foo");
1514 Path = Path3;
1515 Found = path::replace_path_prefix(Path, OldPrefix, NewPrefix);
1516 EXPECT_TRUE(Found);
1517 EXPECT_EQ(Path, "/newnew/foo");
1518 Path = Path3;
1519 Found = path::replace_path_prefix(Path, OldPrefix, NewPrefix2);
1520 EXPECT_TRUE(Found);
1521 EXPECT_EQ(Path, "/longernewnew/foo");
1522 Path = Path1;
1523 Found = path::replace_path_prefix(Path, EmptyPrefix, NewPrefix);
1524 EXPECT_TRUE(Found);
1525 EXPECT_EQ(Path, "/new/foo");
1526 Path = OldPrefix;
1527 Found = path::replace_path_prefix(Path, OldPrefix, NewPrefix);
1528 EXPECT_TRUE(Found);
1529 EXPECT_EQ(Path, "/new");
1530 Path = OldPrefixSep;
1531 Found = path::replace_path_prefix(Path, OldPrefix, NewPrefix);
1532 EXPECT_TRUE(Found);
1533 EXPECT_EQ(Path, "/new/");
1534 Path = OldPrefix;
1535 Found = path::replace_path_prefix(Path, OldPrefixSep, NewPrefix);
1536 EXPECT_FALSE(Found);
1537 EXPECT_EQ(Path, "/old");
1538 Path = Path4;
1539 Found = path::replace_path_prefix(Path, OldPrefixWin, NewPrefix,
1540 path::Style::windows);
1541 EXPECT_TRUE(Found);
1542 EXPECT_EQ(Path, "/newoo\\bar");
1543 Path = Path4;
1544 Found = path::replace_path_prefix(Path, OldPrefixWin, NewPrefix,
1545 path::Style::posix);
1546 EXPECT_FALSE(Found);
1547 EXPECT_EQ(Path, "C:\\old/foo\\bar");
1548 }
1549
TEST_F(FileSystemTest,OpenFileForRead)1550 TEST_F(FileSystemTest, OpenFileForRead) {
1551 // Create a temp file.
1552 int FileDescriptor;
1553 SmallString<64> TempPath;
1554 ASSERT_NO_ERROR(
1555 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
1556 FileRemover Cleanup(TempPath);
1557
1558 // Make sure it exists.
1559 ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
1560
1561 // Open the file for read
1562 int FileDescriptor2;
1563 SmallString<64> ResultPath;
1564 ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath), FileDescriptor2,
1565 fs::OF_None, &ResultPath))
1566
1567 // If we succeeded, check that the paths are the same (modulo case):
1568 if (!ResultPath.empty()) {
1569 // The paths returned by createTemporaryFile and getPathFromOpenFD
1570 // should reference the same file on disk.
1571 fs::UniqueID D1, D2;
1572 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), D1));
1573 ASSERT_NO_ERROR(fs::getUniqueID(Twine(ResultPath), D2));
1574 ASSERT_EQ(D1, D2);
1575 }
1576 ::close(FileDescriptor);
1577 ::close(FileDescriptor2);
1578
1579 #ifdef _WIN32
1580 // Since Windows Vista, file access time is not updated by default.
1581 // This is instead updated manually by openFileForRead.
1582 // https://blogs.technet.microsoft.com/filecab/2006/11/07/disabling-last-access-time-in-windows-vista-to-improve-ntfs-performance/
1583 // This part of the unit test is Windows specific as the updating of
1584 // access times can be disabled on Linux using /etc/fstab.
1585
1586 // Set access time to UNIX epoch.
1587 ASSERT_NO_ERROR(sys::fs::openFileForWrite(Twine(TempPath), FileDescriptor,
1588 fs::CD_OpenExisting));
1589 TimePoint<> Epoch(std::chrono::milliseconds(0));
1590 ASSERT_NO_ERROR(fs::setLastAccessAndModificationTime(FileDescriptor, Epoch));
1591 ::close(FileDescriptor);
1592
1593 // Open the file and ensure access time is updated, when forced.
1594 ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath), FileDescriptor,
1595 fs::OF_UpdateAtime, &ResultPath));
1596
1597 sys::fs::file_status Status;
1598 ASSERT_NO_ERROR(sys::fs::status(FileDescriptor, Status));
1599 auto FileAccessTime = Status.getLastAccessedTime();
1600
1601 ASSERT_NE(Epoch, FileAccessTime);
1602 ::close(FileDescriptor);
1603
1604 // Ideally this test would include a case when ATime is not forced to update,
1605 // however the expected behaviour will differ depending on the configuration
1606 // of the Windows file system.
1607 #endif
1608 }
1609
createFileWithData(const Twine & Path,bool ShouldExistBefore,fs::CreationDisposition Disp,StringRef Data)1610 static void createFileWithData(const Twine &Path, bool ShouldExistBefore,
1611 fs::CreationDisposition Disp, StringRef Data) {
1612 int FD;
1613 ASSERT_EQ(ShouldExistBefore, fs::exists(Path));
1614 ASSERT_NO_ERROR(fs::openFileForWrite(Path, FD, Disp));
1615 FileDescriptorCloser Closer(FD);
1616 ASSERT_TRUE(fs::exists(Path));
1617
1618 ASSERT_EQ(Data.size(), (size_t)write(FD, Data.data(), Data.size()));
1619 }
1620
verifyFileContents(const Twine & Path,StringRef Contents)1621 static void verifyFileContents(const Twine &Path, StringRef Contents) {
1622 auto Buffer = MemoryBuffer::getFile(Path);
1623 ASSERT_TRUE((bool)Buffer);
1624 StringRef Data = Buffer.get()->getBuffer();
1625 ASSERT_EQ(Data, Contents);
1626 }
1627
TEST_F(FileSystemTest,CreateNew)1628 TEST_F(FileSystemTest, CreateNew) {
1629 int FD;
1630 Optional<FileDescriptorCloser> Closer;
1631
1632 // Succeeds if the file does not exist.
1633 ASSERT_FALSE(fs::exists(NonExistantFile));
1634 ASSERT_NO_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateNew));
1635 ASSERT_TRUE(fs::exists(NonExistantFile));
1636
1637 FileRemover Cleanup(NonExistantFile);
1638 Closer.emplace(FD);
1639
1640 // And creates a file of size 0.
1641 sys::fs::file_status Status;
1642 ASSERT_NO_ERROR(sys::fs::status(FD, Status));
1643 EXPECT_EQ(0ULL, Status.getSize());
1644
1645 // Close this first, before trying to re-open the file.
1646 Closer.reset();
1647
1648 // But fails if the file does exist.
1649 ASSERT_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateNew));
1650 }
1651
TEST_F(FileSystemTest,CreateAlways)1652 TEST_F(FileSystemTest, CreateAlways) {
1653 int FD;
1654 Optional<FileDescriptorCloser> Closer;
1655
1656 // Succeeds if the file does not exist.
1657 ASSERT_FALSE(fs::exists(NonExistantFile));
1658 ASSERT_NO_ERROR(
1659 fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateAlways));
1660
1661 Closer.emplace(FD);
1662
1663 ASSERT_TRUE(fs::exists(NonExistantFile));
1664
1665 FileRemover Cleanup(NonExistantFile);
1666
1667 // And creates a file of size 0.
1668 uint64_t FileSize;
1669 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1670 ASSERT_EQ(0ULL, FileSize);
1671
1672 // If we write some data to it re-create it with CreateAlways, it succeeds and
1673 // truncates to 0 bytes.
1674 ASSERT_EQ(4, write(FD, "Test", 4));
1675
1676 Closer.reset();
1677
1678 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1679 ASSERT_EQ(4ULL, FileSize);
1680
1681 ASSERT_NO_ERROR(
1682 fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateAlways));
1683 Closer.emplace(FD);
1684 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1685 ASSERT_EQ(0ULL, FileSize);
1686 }
1687
TEST_F(FileSystemTest,OpenExisting)1688 TEST_F(FileSystemTest, OpenExisting) {
1689 int FD;
1690
1691 // Fails if the file does not exist.
1692 ASSERT_FALSE(fs::exists(NonExistantFile));
1693 ASSERT_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_OpenExisting));
1694 ASSERT_FALSE(fs::exists(NonExistantFile));
1695
1696 // Make a dummy file now so that we can try again when the file does exist.
1697 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1698 FileRemover Cleanup(NonExistantFile);
1699 uint64_t FileSize;
1700 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1701 ASSERT_EQ(4ULL, FileSize);
1702
1703 // If we re-create it with different data, it overwrites rather than
1704 // appending.
1705 createFileWithData(NonExistantFile, true, fs::CD_OpenExisting, "Buzz");
1706 verifyFileContents(NonExistantFile, "Buzz");
1707 }
1708
TEST_F(FileSystemTest,OpenAlways)1709 TEST_F(FileSystemTest, OpenAlways) {
1710 // Succeeds if the file does not exist.
1711 createFileWithData(NonExistantFile, false, fs::CD_OpenAlways, "Fizz");
1712 FileRemover Cleanup(NonExistantFile);
1713 uint64_t FileSize;
1714 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1715 ASSERT_EQ(4ULL, FileSize);
1716
1717 // Now re-open it and write again, verifying the contents get over-written.
1718 createFileWithData(NonExistantFile, true, fs::CD_OpenAlways, "Bu");
1719 verifyFileContents(NonExistantFile, "Buzz");
1720 }
1721
TEST_F(FileSystemTest,AppendSetsCorrectFileOffset)1722 TEST_F(FileSystemTest, AppendSetsCorrectFileOffset) {
1723 fs::CreationDisposition Disps[] = {fs::CD_CreateAlways, fs::CD_OpenAlways,
1724 fs::CD_OpenExisting};
1725
1726 // Write some data and re-open it with every possible disposition (this is a
1727 // hack that shouldn't work, but is left for compatibility. OF_Append
1728 // overrides
1729 // the specified disposition.
1730 for (fs::CreationDisposition Disp : Disps) {
1731 int FD;
1732 Optional<FileDescriptorCloser> Closer;
1733
1734 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1735
1736 FileRemover Cleanup(NonExistantFile);
1737
1738 uint64_t FileSize;
1739 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1740 ASSERT_EQ(4ULL, FileSize);
1741 ASSERT_NO_ERROR(
1742 fs::openFileForWrite(NonExistantFile, FD, Disp, fs::OF_Append));
1743 Closer.emplace(FD);
1744 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1745 ASSERT_EQ(4ULL, FileSize);
1746
1747 ASSERT_EQ(4, write(FD, "Buzz", 4));
1748 Closer.reset();
1749
1750 verifyFileContents(NonExistantFile, "FizzBuzz");
1751 }
1752 }
1753
verifyRead(int FD,StringRef Data,bool ShouldSucceed)1754 static void verifyRead(int FD, StringRef Data, bool ShouldSucceed) {
1755 std::vector<char> Buffer;
1756 Buffer.resize(Data.size());
1757 int Result = ::read(FD, Buffer.data(), Buffer.size());
1758 if (ShouldSucceed) {
1759 ASSERT_EQ((size_t)Result, Data.size());
1760 ASSERT_EQ(Data, StringRef(Buffer.data(), Buffer.size()));
1761 } else {
1762 ASSERT_EQ(-1, Result);
1763 ASSERT_EQ(EBADF, errno);
1764 }
1765 }
1766
verifyWrite(int FD,StringRef Data,bool ShouldSucceed)1767 static void verifyWrite(int FD, StringRef Data, bool ShouldSucceed) {
1768 int Result = ::write(FD, Data.data(), Data.size());
1769 if (ShouldSucceed)
1770 ASSERT_EQ((size_t)Result, Data.size());
1771 else {
1772 ASSERT_EQ(-1, Result);
1773 ASSERT_EQ(EBADF, errno);
1774 }
1775 }
1776
TEST_F(FileSystemTest,ReadOnlyFileCantWrite)1777 TEST_F(FileSystemTest, ReadOnlyFileCantWrite) {
1778 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1779 FileRemover Cleanup(NonExistantFile);
1780
1781 int FD;
1782 ASSERT_NO_ERROR(fs::openFileForRead(NonExistantFile, FD));
1783 FileDescriptorCloser Closer(FD);
1784
1785 verifyWrite(FD, "Buzz", false);
1786 verifyRead(FD, "Fizz", true);
1787 }
1788
TEST_F(FileSystemTest,WriteOnlyFileCantRead)1789 TEST_F(FileSystemTest, WriteOnlyFileCantRead) {
1790 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1791 FileRemover Cleanup(NonExistantFile);
1792
1793 int FD;
1794 ASSERT_NO_ERROR(
1795 fs::openFileForWrite(NonExistantFile, FD, fs::CD_OpenExisting));
1796 FileDescriptorCloser Closer(FD);
1797 verifyRead(FD, "Fizz", false);
1798 verifyWrite(FD, "Buzz", true);
1799 }
1800
TEST_F(FileSystemTest,ReadWriteFileCanReadOrWrite)1801 TEST_F(FileSystemTest, ReadWriteFileCanReadOrWrite) {
1802 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1803 FileRemover Cleanup(NonExistantFile);
1804
1805 int FD;
1806 ASSERT_NO_ERROR(fs::openFileForReadWrite(NonExistantFile, FD,
1807 fs::CD_OpenExisting, fs::OF_None));
1808 FileDescriptorCloser Closer(FD);
1809 verifyRead(FD, "Fizz", true);
1810 verifyWrite(FD, "Buzz", true);
1811 }
1812
TEST_F(FileSystemTest,readNativeFile)1813 TEST_F(FileSystemTest, readNativeFile) {
1814 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "01234");
1815 FileRemover Cleanup(NonExistantFile);
1816 const auto &Read = [&](size_t ToRead) -> Expected<std::string> {
1817 std::string Buf(ToRead, '?');
1818 Expected<fs::file_t> FD = fs::openNativeFileForRead(NonExistantFile);
1819 if (!FD)
1820 return FD.takeError();
1821 auto Close = make_scope_exit([&] { fs::closeFile(*FD); });
1822 if (Expected<size_t> BytesRead = fs::readNativeFile(
1823 *FD, makeMutableArrayRef(&*Buf.begin(), Buf.size())))
1824 return Buf.substr(0, *BytesRead);
1825 else
1826 return BytesRead.takeError();
1827 };
1828 EXPECT_THAT_EXPECTED(Read(5), HasValue("01234"));
1829 EXPECT_THAT_EXPECTED(Read(3), HasValue("012"));
1830 EXPECT_THAT_EXPECTED(Read(6), HasValue("01234"));
1831 }
1832
TEST_F(FileSystemTest,readNativeFileSlice)1833 TEST_F(FileSystemTest, readNativeFileSlice) {
1834 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "01234");
1835 FileRemover Cleanup(NonExistantFile);
1836 Expected<fs::file_t> FD = fs::openNativeFileForRead(NonExistantFile);
1837 ASSERT_THAT_EXPECTED(FD, Succeeded());
1838 auto Close = make_scope_exit([&] { fs::closeFile(*FD); });
1839 const auto &Read = [&](size_t Offset,
1840 size_t ToRead) -> Expected<std::string> {
1841 std::string Buf(ToRead, '?');
1842 if (Expected<size_t> BytesRead = fs::readNativeFileSlice(
1843 *FD, makeMutableArrayRef(&*Buf.begin(), Buf.size()), Offset))
1844 return Buf.substr(0, *BytesRead);
1845 else
1846 return BytesRead.takeError();
1847 };
1848 EXPECT_THAT_EXPECTED(Read(0, 5), HasValue("01234"));
1849 EXPECT_THAT_EXPECTED(Read(0, 3), HasValue("012"));
1850 EXPECT_THAT_EXPECTED(Read(2, 3), HasValue("234"));
1851 EXPECT_THAT_EXPECTED(Read(0, 6), HasValue("01234"));
1852 EXPECT_THAT_EXPECTED(Read(2, 6), HasValue("234"));
1853 EXPECT_THAT_EXPECTED(Read(5, 5), HasValue(""));
1854 }
1855
TEST_F(FileSystemTest,is_local)1856 TEST_F(FileSystemTest, is_local) {
1857 bool TestDirectoryIsLocal;
1858 ASSERT_NO_ERROR(fs::is_local(TestDirectory, TestDirectoryIsLocal));
1859 EXPECT_EQ(TestDirectoryIsLocal, fs::is_local(TestDirectory));
1860
1861 int FD;
1862 SmallString<128> TempPath;
1863 ASSERT_NO_ERROR(
1864 fs::createUniqueFile(Twine(TestDirectory) + "/temp", FD, TempPath));
1865 FileRemover Cleanup(TempPath);
1866
1867 // Make sure it exists.
1868 ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
1869
1870 bool TempFileIsLocal;
1871 ASSERT_NO_ERROR(fs::is_local(FD, TempFileIsLocal));
1872 EXPECT_EQ(TempFileIsLocal, fs::is_local(FD));
1873 ::close(FD);
1874
1875 // Expect that the file and its parent directory are equally local or equally
1876 // remote.
1877 EXPECT_EQ(TestDirectoryIsLocal, TempFileIsLocal);
1878 }
1879
TEST_F(FileSystemTest,getUmask)1880 TEST_F(FileSystemTest, getUmask) {
1881 #ifdef _WIN32
1882 EXPECT_EQ(fs::getUmask(), 0U) << "Should always be 0 on Windows.";
1883 #else
1884 unsigned OldMask = ::umask(0022);
1885 unsigned CurrentMask = fs::getUmask();
1886 EXPECT_EQ(CurrentMask, 0022U)
1887 << "getUmask() didn't return previously set umask()";
1888 EXPECT_EQ(::umask(OldMask), 0022U) << "getUmask() may have changed umask()";
1889 #endif
1890 }
1891
TEST_F(FileSystemTest,RespectUmask)1892 TEST_F(FileSystemTest, RespectUmask) {
1893 #ifndef _WIN32
1894 unsigned OldMask = ::umask(0022);
1895
1896 int FD;
1897 SmallString<128> TempPath;
1898 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1899
1900 fs::perms AllRWE = static_cast<fs::perms>(0777);
1901
1902 ASSERT_NO_ERROR(fs::setPermissions(TempPath, AllRWE));
1903
1904 ErrorOr<fs::perms> Perms = fs::getPermissions(TempPath);
1905 ASSERT_TRUE(!!Perms);
1906 EXPECT_EQ(Perms.get(), AllRWE) << "Should have ignored umask by default";
1907
1908 ASSERT_NO_ERROR(fs::setPermissions(TempPath, AllRWE));
1909
1910 Perms = fs::getPermissions(TempPath);
1911 ASSERT_TRUE(!!Perms);
1912 EXPECT_EQ(Perms.get(), AllRWE) << "Should have ignored umask";
1913
1914 ASSERT_NO_ERROR(
1915 fs::setPermissions(FD, static_cast<fs::perms>(AllRWE & ~fs::getUmask())));
1916 Perms = fs::getPermissions(TempPath);
1917 ASSERT_TRUE(!!Perms);
1918 EXPECT_EQ(Perms.get(), static_cast<fs::perms>(0755))
1919 << "Did not respect umask";
1920
1921 (void)::umask(0057);
1922
1923 ASSERT_NO_ERROR(
1924 fs::setPermissions(FD, static_cast<fs::perms>(AllRWE & ~fs::getUmask())));
1925 Perms = fs::getPermissions(TempPath);
1926 ASSERT_TRUE(!!Perms);
1927 EXPECT_EQ(Perms.get(), static_cast<fs::perms>(0720))
1928 << "Did not respect umask";
1929
1930 (void)::umask(OldMask);
1931 (void)::close(FD);
1932 #endif
1933 }
1934
TEST_F(FileSystemTest,set_current_path)1935 TEST_F(FileSystemTest, set_current_path) {
1936 SmallString<128> path;
1937
1938 ASSERT_NO_ERROR(fs::current_path(path));
1939 ASSERT_NE(TestDirectory, path);
1940
1941 struct RestorePath {
1942 SmallString<128> path;
1943 RestorePath(const SmallString<128> &path) : path(path) {}
1944 ~RestorePath() { fs::set_current_path(path); }
1945 } restore_path(path);
1946
1947 ASSERT_NO_ERROR(fs::set_current_path(TestDirectory));
1948
1949 ASSERT_NO_ERROR(fs::current_path(path));
1950
1951 fs::UniqueID D1, D2;
1952 ASSERT_NO_ERROR(fs::getUniqueID(TestDirectory, D1));
1953 ASSERT_NO_ERROR(fs::getUniqueID(path, D2));
1954 ASSERT_EQ(D1, D2) << "D1: " << TestDirectory << "\nD2: " << path;
1955 }
1956
TEST_F(FileSystemTest,permissions)1957 TEST_F(FileSystemTest, permissions) {
1958 int FD;
1959 SmallString<64> TempPath;
1960 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1961 FileRemover Cleanup(TempPath);
1962
1963 // Make sure it exists.
1964 ASSERT_TRUE(fs::exists(Twine(TempPath)));
1965
1966 auto CheckPermissions = [&](fs::perms Expected) {
1967 ErrorOr<fs::perms> Actual = fs::getPermissions(TempPath);
1968 return Actual && *Actual == Expected;
1969 };
1970
1971 std::error_code NoError;
1972 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_all), NoError);
1973 EXPECT_TRUE(CheckPermissions(fs::all_all));
1974
1975 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read | fs::all_exe), NoError);
1976 EXPECT_TRUE(CheckPermissions(fs::all_read | fs::all_exe));
1977
1978 #if defined(_WIN32)
1979 fs::perms ReadOnly = fs::all_read | fs::all_exe;
1980 EXPECT_EQ(fs::setPermissions(TempPath, fs::no_perms), NoError);
1981 EXPECT_TRUE(CheckPermissions(ReadOnly));
1982
1983 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_read), NoError);
1984 EXPECT_TRUE(CheckPermissions(ReadOnly));
1985
1986 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_write), NoError);
1987 EXPECT_TRUE(CheckPermissions(fs::all_all));
1988
1989 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_exe), NoError);
1990 EXPECT_TRUE(CheckPermissions(ReadOnly));
1991
1992 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_all), NoError);
1993 EXPECT_TRUE(CheckPermissions(fs::all_all));
1994
1995 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_read), NoError);
1996 EXPECT_TRUE(CheckPermissions(ReadOnly));
1997
1998 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_write), NoError);
1999 EXPECT_TRUE(CheckPermissions(fs::all_all));
2000
2001 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_exe), NoError);
2002 EXPECT_TRUE(CheckPermissions(ReadOnly));
2003
2004 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_all), NoError);
2005 EXPECT_TRUE(CheckPermissions(fs::all_all));
2006
2007 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_read), NoError);
2008 EXPECT_TRUE(CheckPermissions(ReadOnly));
2009
2010 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_write), NoError);
2011 EXPECT_TRUE(CheckPermissions(fs::all_all));
2012
2013 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_exe), NoError);
2014 EXPECT_TRUE(CheckPermissions(ReadOnly));
2015
2016 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_all), NoError);
2017 EXPECT_TRUE(CheckPermissions(fs::all_all));
2018
2019 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read), NoError);
2020 EXPECT_TRUE(CheckPermissions(ReadOnly));
2021
2022 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_write), NoError);
2023 EXPECT_TRUE(CheckPermissions(fs::all_all));
2024
2025 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_exe), NoError);
2026 EXPECT_TRUE(CheckPermissions(ReadOnly));
2027
2028 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe), NoError);
2029 EXPECT_TRUE(CheckPermissions(ReadOnly));
2030
2031 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_gid_on_exe), NoError);
2032 EXPECT_TRUE(CheckPermissions(ReadOnly));
2033
2034 EXPECT_EQ(fs::setPermissions(TempPath, fs::sticky_bit), NoError);
2035 EXPECT_TRUE(CheckPermissions(ReadOnly));
2036
2037 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe |
2038 fs::set_gid_on_exe |
2039 fs::sticky_bit),
2040 NoError);
2041 EXPECT_TRUE(CheckPermissions(ReadOnly));
2042
2043 EXPECT_EQ(fs::setPermissions(TempPath, ReadOnly | fs::set_uid_on_exe |
2044 fs::set_gid_on_exe |
2045 fs::sticky_bit),
2046 NoError);
2047 EXPECT_TRUE(CheckPermissions(ReadOnly));
2048
2049 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms), NoError);
2050 EXPECT_TRUE(CheckPermissions(fs::all_all));
2051 #else
2052 EXPECT_EQ(fs::setPermissions(TempPath, fs::no_perms), NoError);
2053 EXPECT_TRUE(CheckPermissions(fs::no_perms));
2054
2055 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_read), NoError);
2056 EXPECT_TRUE(CheckPermissions(fs::owner_read));
2057
2058 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_write), NoError);
2059 EXPECT_TRUE(CheckPermissions(fs::owner_write));
2060
2061 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_exe), NoError);
2062 EXPECT_TRUE(CheckPermissions(fs::owner_exe));
2063
2064 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_all), NoError);
2065 EXPECT_TRUE(CheckPermissions(fs::owner_all));
2066
2067 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_read), NoError);
2068 EXPECT_TRUE(CheckPermissions(fs::group_read));
2069
2070 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_write), NoError);
2071 EXPECT_TRUE(CheckPermissions(fs::group_write));
2072
2073 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_exe), NoError);
2074 EXPECT_TRUE(CheckPermissions(fs::group_exe));
2075
2076 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_all), NoError);
2077 EXPECT_TRUE(CheckPermissions(fs::group_all));
2078
2079 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_read), NoError);
2080 EXPECT_TRUE(CheckPermissions(fs::others_read));
2081
2082 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_write), NoError);
2083 EXPECT_TRUE(CheckPermissions(fs::others_write));
2084
2085 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_exe), NoError);
2086 EXPECT_TRUE(CheckPermissions(fs::others_exe));
2087
2088 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_all), NoError);
2089 EXPECT_TRUE(CheckPermissions(fs::others_all));
2090
2091 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read), NoError);
2092 EXPECT_TRUE(CheckPermissions(fs::all_read));
2093
2094 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_write), NoError);
2095 EXPECT_TRUE(CheckPermissions(fs::all_write));
2096
2097 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_exe), NoError);
2098 EXPECT_TRUE(CheckPermissions(fs::all_exe));
2099
2100 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe), NoError);
2101 EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe));
2102
2103 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_gid_on_exe), NoError);
2104 EXPECT_TRUE(CheckPermissions(fs::set_gid_on_exe));
2105
2106 // Modern BSDs require root to set the sticky bit on files.
2107 // AIX and Solaris without root will mask off (i.e., lose) the sticky bit
2108 // on files.
2109 #if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
2110 !defined(_AIX) && !(defined(__sun__) && defined(__svr4__))
2111 EXPECT_EQ(fs::setPermissions(TempPath, fs::sticky_bit), NoError);
2112 EXPECT_TRUE(CheckPermissions(fs::sticky_bit));
2113
2114 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe |
2115 fs::set_gid_on_exe |
2116 fs::sticky_bit),
2117 NoError);
2118 EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe | fs::set_gid_on_exe |
2119 fs::sticky_bit));
2120
2121 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read | fs::set_uid_on_exe |
2122 fs::set_gid_on_exe |
2123 fs::sticky_bit),
2124 NoError);
2125 EXPECT_TRUE(CheckPermissions(fs::all_read | fs::set_uid_on_exe |
2126 fs::set_gid_on_exe | fs::sticky_bit));
2127
2128 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms), NoError);
2129 EXPECT_TRUE(CheckPermissions(fs::all_perms));
2130 #endif // !FreeBSD && !NetBSD && !OpenBSD && !AIX
2131
2132 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms & ~fs::sticky_bit),
2133 NoError);
2134 EXPECT_TRUE(CheckPermissions(fs::all_perms & ~fs::sticky_bit));
2135 #endif
2136 }
2137
2138 #ifdef _WIN32
TEST_F(FileSystemTest,widenPath)2139 TEST_F(FileSystemTest, widenPath) {
2140 const std::wstring LongPathPrefix(L"\\\\?\\");
2141
2142 // Test that the length limit is checked against the UTF-16 length and not the
2143 // UTF-8 length.
2144 std::string Input("C:\\foldername\\");
2145 const std::string Pi("\xcf\x80"); // UTF-8 lower case pi.
2146 // Add Pi up to the MAX_PATH limit.
2147 const size_t NumChars = MAX_PATH - Input.size() - 1;
2148 for (size_t i = 0; i < NumChars; ++i)
2149 Input += Pi;
2150 // Check that UTF-8 length already exceeds MAX_PATH.
2151 EXPECT_TRUE(Input.size() > MAX_PATH);
2152 SmallVector<wchar_t, MAX_PATH + 16> Result;
2153 ASSERT_NO_ERROR(windows::widenPath(Input, Result));
2154 // Result should not start with the long path prefix.
2155 EXPECT_TRUE(std::wmemcmp(Result.data(), LongPathPrefix.c_str(),
2156 LongPathPrefix.size()) != 0);
2157 EXPECT_EQ(Result.size(), (size_t)MAX_PATH - 1);
2158
2159 // Add another Pi to exceed the MAX_PATH limit.
2160 Input += Pi;
2161 // Construct the expected result.
2162 SmallVector<wchar_t, MAX_PATH + 16> Expected;
2163 ASSERT_NO_ERROR(windows::UTF8ToUTF16(Input, Expected));
2164 Expected.insert(Expected.begin(), LongPathPrefix.begin(),
2165 LongPathPrefix.end());
2166
2167 ASSERT_NO_ERROR(windows::widenPath(Input, Result));
2168 EXPECT_EQ(Result, Expected);
2169
2170 // Test that UNC paths are handled correctly.
2171 const std::string ShareName("\\\\sharename\\");
2172 const std::string FileName("\\filename");
2173 // Initialize directory name so that the input is within the MAX_PATH limit.
2174 const char DirChar = 'x';
2175 std::string DirName(MAX_PATH - ShareName.size() - FileName.size() - 1,
2176 DirChar);
2177
2178 Input = ShareName + DirName + FileName;
2179 ASSERT_NO_ERROR(windows::widenPath(Input, Result));
2180 // Result should not start with the long path prefix.
2181 EXPECT_TRUE(std::wmemcmp(Result.data(), LongPathPrefix.c_str(),
2182 LongPathPrefix.size()) != 0);
2183 EXPECT_EQ(Result.size(), (size_t)MAX_PATH - 1);
2184
2185 // Extend the directory name so the input exceeds the MAX_PATH limit.
2186 DirName += DirChar;
2187 Input = ShareName + DirName + FileName;
2188 // Construct the expected result.
2189 ASSERT_NO_ERROR(windows::UTF8ToUTF16(StringRef(Input).substr(2), Expected));
2190 const std::wstring UNCPrefix(LongPathPrefix + L"UNC\\");
2191 Expected.insert(Expected.begin(), UNCPrefix.begin(), UNCPrefix.end());
2192
2193 ASSERT_NO_ERROR(windows::widenPath(Input, Result));
2194 EXPECT_EQ(Result, Expected);
2195
2196 // Check that Unix separators are handled correctly.
2197 std::replace(Input.begin(), Input.end(), '\\', '/');
2198 ASSERT_NO_ERROR(windows::widenPath(Input, Result));
2199 EXPECT_EQ(Result, Expected);
2200
2201 // Check the removal of "dots".
2202 Input = ShareName + DirName + "\\.\\foo\\.\\.." + FileName;
2203 ASSERT_NO_ERROR(windows::widenPath(Input, Result));
2204 EXPECT_EQ(Result, Expected);
2205 }
2206 #endif
2207
2208 #ifdef _WIN32
2209 // Windows refuses lock request if file region is already locked by the same
2210 // process. POSIX system in this case updates the existing lock.
TEST_F(FileSystemTest,FileLocker)2211 TEST_F(FileSystemTest, FileLocker) {
2212 using namespace std::chrono;
2213 int FD;
2214 std::error_code EC;
2215 SmallString<64> TempPath;
2216 EC = fs::createTemporaryFile("test", "temp", FD, TempPath);
2217 ASSERT_NO_ERROR(EC);
2218 FileRemover Cleanup(TempPath);
2219 raw_fd_ostream Stream(TempPath, EC);
2220
2221 EC = fs::tryLockFile(FD);
2222 ASSERT_NO_ERROR(EC);
2223 EC = fs::unlockFile(FD);
2224 ASSERT_NO_ERROR(EC);
2225
2226 if (auto L = Stream.lock()) {
2227 ASSERT_ERROR(fs::tryLockFile(FD));
2228 ASSERT_NO_ERROR(L->unlock());
2229 ASSERT_NO_ERROR(fs::tryLockFile(FD));
2230 ASSERT_NO_ERROR(fs::unlockFile(FD));
2231 } else {
2232 ADD_FAILURE();
2233 handleAllErrors(L.takeError(), [&](ErrorInfoBase &EIB) {});
2234 }
2235
2236 ASSERT_NO_ERROR(fs::tryLockFile(FD));
2237 ASSERT_NO_ERROR(fs::unlockFile(FD));
2238
2239 {
2240 Expected<fs::FileLocker> L1 = Stream.lock();
2241 ASSERT_THAT_EXPECTED(L1, Succeeded());
2242 raw_fd_ostream Stream2(FD, false);
2243 Expected<fs::FileLocker> L2 = Stream2.tryLockFor(250ms);
2244 ASSERT_THAT_EXPECTED(L2, Failed());
2245 ASSERT_NO_ERROR(L1->unlock());
2246 Expected<fs::FileLocker> L3 = Stream.tryLockFor(0ms);
2247 ASSERT_THAT_EXPECTED(L3, Succeeded());
2248 }
2249
2250 ASSERT_NO_ERROR(fs::tryLockFile(FD));
2251 ASSERT_NO_ERROR(fs::unlockFile(FD));
2252 }
2253 #endif
2254
2255 } // anonymous namespace
2256