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__anon29112f600111::FileDescriptorCloser67 explicit FileDescriptorCloser(int FD) : FD(FD) {}
~FileDescriptorCloser__anon29112f600111::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
TEST_F(FileSystemTest,DirectoryNotExecutable)1091 TEST_F(FileSystemTest, DirectoryNotExecutable) {
1092 ASSERT_EQ(fs::access(TestDirectory, sys::fs::AccessMode::Execute),
1093 errc::permission_denied);
1094 }
1095
1096 #ifdef LLVM_ON_UNIX
TEST_F(FileSystemTest,BrokenSymlinkDirectoryIteration)1097 TEST_F(FileSystemTest, BrokenSymlinkDirectoryIteration) {
1098 // Create a known hierarchy to recurse over.
1099 ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) + "/symlink"));
1100 ASSERT_NO_ERROR(
1101 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/a"));
1102 ASSERT_NO_ERROR(
1103 fs::create_directories(Twine(TestDirectory) + "/symlink/b/bb"));
1104 ASSERT_NO_ERROR(
1105 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/b/ba"));
1106 ASSERT_NO_ERROR(
1107 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/b/bc"));
1108 ASSERT_NO_ERROR(
1109 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/c"));
1110 ASSERT_NO_ERROR(
1111 fs::create_directories(Twine(TestDirectory) + "/symlink/d/dd/ddd"));
1112 ASSERT_NO_ERROR(fs::create_link(Twine(TestDirectory) + "/symlink/d/dd",
1113 Twine(TestDirectory) + "/symlink/d/da"));
1114 ASSERT_NO_ERROR(
1115 fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/e"));
1116
1117 typedef std::vector<std::string> v_t;
1118 v_t VisitedNonBrokenSymlinks;
1119 v_t VisitedBrokenSymlinks;
1120 std::error_code ec;
1121 using testing::UnorderedElementsAre;
1122 using testing::UnorderedElementsAreArray;
1123
1124 // Broken symbol links are expected to throw an error.
1125 for (fs::directory_iterator i(Twine(TestDirectory) + "/symlink", ec), e;
1126 i != e; i.increment(ec)) {
1127 ASSERT_NO_ERROR(ec);
1128 if (i->status().getError() ==
1129 std::make_error_code(std::errc::no_such_file_or_directory)) {
1130 VisitedBrokenSymlinks.push_back(std::string(path::filename(i->path())));
1131 continue;
1132 }
1133 VisitedNonBrokenSymlinks.push_back(std::string(path::filename(i->path())));
1134 }
1135 EXPECT_THAT(VisitedNonBrokenSymlinks, UnorderedElementsAre("b", "d"));
1136 VisitedNonBrokenSymlinks.clear();
1137
1138 EXPECT_THAT(VisitedBrokenSymlinks, UnorderedElementsAre("a", "c", "e"));
1139 VisitedBrokenSymlinks.clear();
1140
1141 // Broken symbol links are expected to throw an error.
1142 for (fs::recursive_directory_iterator i(
1143 Twine(TestDirectory) + "/symlink", ec), e; i != e; i.increment(ec)) {
1144 ASSERT_NO_ERROR(ec);
1145 if (i->status().getError() ==
1146 std::make_error_code(std::errc::no_such_file_or_directory)) {
1147 VisitedBrokenSymlinks.push_back(std::string(path::filename(i->path())));
1148 continue;
1149 }
1150 VisitedNonBrokenSymlinks.push_back(std::string(path::filename(i->path())));
1151 }
1152 EXPECT_THAT(VisitedNonBrokenSymlinks,
1153 UnorderedElementsAre("b", "bb", "d", "da", "dd", "ddd", "ddd"));
1154 VisitedNonBrokenSymlinks.clear();
1155
1156 EXPECT_THAT(VisitedBrokenSymlinks,
1157 UnorderedElementsAre("a", "ba", "bc", "c", "e"));
1158 VisitedBrokenSymlinks.clear();
1159
1160 for (fs::recursive_directory_iterator i(
1161 Twine(TestDirectory) + "/symlink", ec, /*follow_symlinks=*/false), e;
1162 i != e; i.increment(ec)) {
1163 ASSERT_NO_ERROR(ec);
1164 if (i->status().getError() ==
1165 std::make_error_code(std::errc::no_such_file_or_directory)) {
1166 VisitedBrokenSymlinks.push_back(std::string(path::filename(i->path())));
1167 continue;
1168 }
1169 VisitedNonBrokenSymlinks.push_back(std::string(path::filename(i->path())));
1170 }
1171 EXPECT_THAT(VisitedNonBrokenSymlinks,
1172 UnorderedElementsAreArray({"a", "b", "ba", "bb", "bc", "c", "d",
1173 "da", "dd", "ddd", "e"}));
1174 VisitedNonBrokenSymlinks.clear();
1175
1176 EXPECT_THAT(VisitedBrokenSymlinks, UnorderedElementsAre());
1177 VisitedBrokenSymlinks.clear();
1178
1179 ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/symlink"));
1180 }
1181 #endif
1182
1183 #ifdef _WIN32
TEST_F(FileSystemTest,UTF8ToUTF16DirectoryIteration)1184 TEST_F(FileSystemTest, UTF8ToUTF16DirectoryIteration) {
1185 // The Windows filesystem support uses UTF-16 and converts paths from the
1186 // input UTF-8. The UTF-16 equivalent of the input path can be shorter in
1187 // length.
1188
1189 // This test relies on TestDirectory not being so long such that MAX_PATH
1190 // would be exceeded (see widenPath). If that were the case, the UTF-16
1191 // path is likely to be longer than the input.
1192 const char *Pi = "\xcf\x80"; // UTF-8 lower case pi.
1193 std::string RootDir = (TestDirectory + "/" + Pi).str();
1194
1195 // Create test directories.
1196 ASSERT_NO_ERROR(fs::create_directories(Twine(RootDir) + "/a"));
1197 ASSERT_NO_ERROR(fs::create_directories(Twine(RootDir) + "/b"));
1198
1199 std::error_code EC;
1200 unsigned Count = 0;
1201 for (fs::directory_iterator I(Twine(RootDir), EC), E; I != E;
1202 I.increment(EC)) {
1203 ASSERT_NO_ERROR(EC);
1204 StringRef DirName = path::filename(I->path());
1205 EXPECT_TRUE(DirName == "a" || DirName == "b");
1206 ++Count;
1207 }
1208 EXPECT_EQ(Count, 2U);
1209
1210 ASSERT_NO_ERROR(fs::remove(Twine(RootDir) + "/a"));
1211 ASSERT_NO_ERROR(fs::remove(Twine(RootDir) + "/b"));
1212 ASSERT_NO_ERROR(fs::remove(Twine(RootDir)));
1213 }
1214 #endif
1215
TEST_F(FileSystemTest,Remove)1216 TEST_F(FileSystemTest, Remove) {
1217 SmallString<64> BaseDir;
1218 SmallString<64> Paths[4];
1219 int fds[4];
1220 ASSERT_NO_ERROR(fs::createUniqueDirectory("fs_remove", BaseDir));
1221
1222 ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir) + "/foo/bar/baz"));
1223 ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir) + "/foo/bar/buzz"));
1224 ASSERT_NO_ERROR(fs::createUniqueFile(
1225 Twine(BaseDir) + "/foo/bar/baz/%%%%%%.tmp", fds[0], Paths[0]));
1226 ASSERT_NO_ERROR(fs::createUniqueFile(
1227 Twine(BaseDir) + "/foo/bar/baz/%%%%%%.tmp", fds[1], Paths[1]));
1228 ASSERT_NO_ERROR(fs::createUniqueFile(
1229 Twine(BaseDir) + "/foo/bar/buzz/%%%%%%.tmp", fds[2], Paths[2]));
1230 ASSERT_NO_ERROR(fs::createUniqueFile(
1231 Twine(BaseDir) + "/foo/bar/buzz/%%%%%%.tmp", fds[3], Paths[3]));
1232
1233 for (int fd : fds)
1234 ::close(fd);
1235
1236 EXPECT_TRUE(fs::exists(Twine(BaseDir) + "/foo/bar/baz"));
1237 EXPECT_TRUE(fs::exists(Twine(BaseDir) + "/foo/bar/buzz"));
1238 EXPECT_TRUE(fs::exists(Paths[0]));
1239 EXPECT_TRUE(fs::exists(Paths[1]));
1240 EXPECT_TRUE(fs::exists(Paths[2]));
1241 EXPECT_TRUE(fs::exists(Paths[3]));
1242
1243 ASSERT_NO_ERROR(fs::remove_directories("D:/footest"));
1244
1245 ASSERT_NO_ERROR(fs::remove_directories(BaseDir));
1246 ASSERT_FALSE(fs::exists(BaseDir));
1247 }
1248
1249 #ifdef _WIN32
TEST_F(FileSystemTest,CarriageReturn)1250 TEST_F(FileSystemTest, CarriageReturn) {
1251 SmallString<128> FilePathname(TestDirectory);
1252 std::error_code EC;
1253 path::append(FilePathname, "test");
1254
1255 {
1256 raw_fd_ostream File(FilePathname, EC, sys::fs::OF_TextWithCRLF);
1257 ASSERT_NO_ERROR(EC);
1258 File << '\n';
1259 }
1260 {
1261 auto Buf = MemoryBuffer::getFile(FilePathname.str());
1262 EXPECT_TRUE((bool)Buf);
1263 EXPECT_EQ(Buf.get()->getBuffer(), "\r\n");
1264 }
1265
1266 {
1267 raw_fd_ostream File(FilePathname, EC, sys::fs::OF_None);
1268 ASSERT_NO_ERROR(EC);
1269 File << '\n';
1270 }
1271 {
1272 auto Buf = MemoryBuffer::getFile(FilePathname.str());
1273 EXPECT_TRUE((bool)Buf);
1274 EXPECT_EQ(Buf.get()->getBuffer(), "\n");
1275 }
1276 ASSERT_NO_ERROR(fs::remove(Twine(FilePathname)));
1277 }
1278 #endif
1279
TEST_F(FileSystemTest,Resize)1280 TEST_F(FileSystemTest, Resize) {
1281 int FD;
1282 SmallString<64> TempPath;
1283 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1284 ASSERT_NO_ERROR(fs::resize_file(FD, 123));
1285 fs::file_status Status;
1286 ASSERT_NO_ERROR(fs::status(FD, Status));
1287 ASSERT_EQ(Status.getSize(), 123U);
1288 ::close(FD);
1289 ASSERT_NO_ERROR(fs::remove(TempPath));
1290 }
1291
TEST_F(FileSystemTest,ResizeBeforeMapping)1292 TEST_F(FileSystemTest, ResizeBeforeMapping) {
1293 // Create a temp file.
1294 int FD;
1295 SmallString<64> TempPath;
1296 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1297 ASSERT_NO_ERROR(fs::resize_file_before_mapping_readwrite(FD, 123));
1298
1299 // Map in temp file. On Windows, fs::resize_file_before_mapping_readwrite is
1300 // a no-op and the mapping itself will resize the file.
1301 std::error_code EC;
1302 {
1303 fs::mapped_file_region mfr(fs::convertFDToNativeFile(FD),
1304 fs::mapped_file_region::readwrite, 123, 0, EC);
1305 ASSERT_NO_ERROR(EC);
1306 // Unmap temp file
1307 }
1308
1309 // Check the size.
1310 fs::file_status Status;
1311 ASSERT_NO_ERROR(fs::status(FD, Status));
1312 ASSERT_EQ(Status.getSize(), 123U);
1313 ::close(FD);
1314 ASSERT_NO_ERROR(fs::remove(TempPath));
1315 }
1316
TEST_F(FileSystemTest,MD5)1317 TEST_F(FileSystemTest, MD5) {
1318 int FD;
1319 SmallString<64> TempPath;
1320 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1321 StringRef Data("abcdefghijklmnopqrstuvwxyz");
1322 ASSERT_EQ(write(FD, Data.data(), Data.size()), static_cast<ssize_t>(Data.size()));
1323 lseek(FD, 0, SEEK_SET);
1324 auto Hash = fs::md5_contents(FD);
1325 ::close(FD);
1326 ASSERT_NO_ERROR(Hash.getError());
1327
1328 EXPECT_STREQ("c3fcd3d76192e4007dfb496cca67e13b", Hash->digest().c_str());
1329 }
1330
TEST_F(FileSystemTest,FileMapping)1331 TEST_F(FileSystemTest, FileMapping) {
1332 // Create a temp file.
1333 int FileDescriptor;
1334 SmallString<64> TempPath;
1335 ASSERT_NO_ERROR(
1336 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
1337 unsigned Size = 4096;
1338 ASSERT_NO_ERROR(
1339 fs::resize_file_before_mapping_readwrite(FileDescriptor, Size));
1340
1341 // Map in temp file and add some content
1342 std::error_code EC;
1343 StringRef Val("hello there");
1344 fs::mapped_file_region MaybeMFR;
1345 EXPECT_FALSE(MaybeMFR);
1346 {
1347 fs::mapped_file_region mfr(fs::convertFDToNativeFile(FileDescriptor),
1348 fs::mapped_file_region::readwrite, Size, 0, EC);
1349 ASSERT_NO_ERROR(EC);
1350 std::copy(Val.begin(), Val.end(), mfr.data());
1351 // Explicitly add a 0.
1352 mfr.data()[Val.size()] = 0;
1353
1354 // Move it out of the scope and confirm mfr is reset.
1355 MaybeMFR = std::move(mfr);
1356 EXPECT_FALSE(mfr);
1357 #if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST
1358 EXPECT_DEATH(mfr.data(), "Mapping failed but used anyway!");
1359 EXPECT_DEATH(mfr.size(), "Mapping failed but used anyway!");
1360 #endif
1361 }
1362
1363 // Check that the moved-to region is still valid.
1364 EXPECT_EQ(Val, StringRef(MaybeMFR.data()));
1365 EXPECT_EQ(Size, MaybeMFR.size());
1366
1367 // Unmap temp file.
1368 MaybeMFR.unmap();
1369
1370 ASSERT_EQ(close(FileDescriptor), 0);
1371
1372 // Map it back in read-only
1373 {
1374 int FD;
1375 EC = fs::openFileForRead(Twine(TempPath), FD);
1376 ASSERT_NO_ERROR(EC);
1377 fs::mapped_file_region mfr(fs::convertFDToNativeFile(FD),
1378 fs::mapped_file_region::readonly, Size, 0, EC);
1379 ASSERT_NO_ERROR(EC);
1380
1381 // Verify content
1382 EXPECT_EQ(StringRef(mfr.const_data()), Val);
1383
1384 // Unmap temp file
1385 fs::mapped_file_region m(fs::convertFDToNativeFile(FD),
1386 fs::mapped_file_region::readonly, Size, 0, EC);
1387 ASSERT_NO_ERROR(EC);
1388 ASSERT_EQ(close(FD), 0);
1389 }
1390 ASSERT_NO_ERROR(fs::remove(TempPath));
1391 }
1392
TEST(Support,NormalizePath)1393 TEST(Support, NormalizePath) {
1394 // Input, Expected Win, Expected Posix
1395 using TestTuple = std::tuple<const char *, const char *, const char *>;
1396 std::vector<TestTuple> Tests;
1397 Tests.emplace_back("a", "a", "a");
1398 Tests.emplace_back("a/b", "a\\b", "a/b");
1399 Tests.emplace_back("a\\b", "a\\b", "a/b");
1400 Tests.emplace_back("a\\\\b", "a\\\\b", "a//b");
1401 Tests.emplace_back("\\a", "\\a", "/a");
1402 Tests.emplace_back("a\\", "a\\", "a/");
1403 Tests.emplace_back("a\\t", "a\\t", "a/t");
1404
1405 for (auto &T : Tests) {
1406 SmallString<64> Win(std::get<0>(T));
1407 SmallString<64> Posix(Win);
1408 path::native(Win, path::Style::windows);
1409 path::native(Posix, path::Style::posix);
1410 EXPECT_EQ(std::get<1>(T), Win);
1411 EXPECT_EQ(std::get<2>(T), Posix);
1412 }
1413
1414 #if defined(_WIN32)
1415 SmallString<64> PathHome;
1416 path::home_directory(PathHome);
1417
1418 const char *Path7a = "~/aaa";
1419 SmallString<64> Path7(Path7a);
1420 path::native(Path7);
1421 EXPECT_TRUE(Path7.endswith("\\aaa"));
1422 EXPECT_TRUE(Path7.startswith(PathHome));
1423 EXPECT_EQ(Path7.size(), PathHome.size() + strlen(Path7a + 1));
1424
1425 const char *Path8a = "~";
1426 SmallString<64> Path8(Path8a);
1427 path::native(Path8);
1428 EXPECT_EQ(Path8, PathHome);
1429
1430 const char *Path9a = "~aaa";
1431 SmallString<64> Path9(Path9a);
1432 path::native(Path9);
1433 EXPECT_EQ(Path9, "~aaa");
1434
1435 const char *Path10a = "aaa/~/b";
1436 SmallString<64> Path10(Path10a);
1437 path::native(Path10);
1438 EXPECT_EQ(Path10, "aaa\\~\\b");
1439 #endif
1440 }
1441
TEST(Support,RemoveLeadingDotSlash)1442 TEST(Support, RemoveLeadingDotSlash) {
1443 StringRef Path1("././/foolz/wat");
1444 StringRef Path2("./////");
1445
1446 Path1 = path::remove_leading_dotslash(Path1);
1447 EXPECT_EQ(Path1, "foolz/wat");
1448 Path2 = path::remove_leading_dotslash(Path2);
1449 EXPECT_EQ(Path2, "");
1450 }
1451
remove_dots(StringRef path,bool remove_dot_dot,path::Style style)1452 static std::string remove_dots(StringRef path, bool remove_dot_dot,
1453 path::Style style) {
1454 SmallString<256> buffer(path);
1455 path::remove_dots(buffer, remove_dot_dot, style);
1456 return std::string(buffer.str());
1457 }
1458
TEST(Support,RemoveDots)1459 TEST(Support, RemoveDots) {
1460 EXPECT_EQ("foolz\\wat",
1461 remove_dots(".\\.\\\\foolz\\wat", false, path::Style::windows));
1462 EXPECT_EQ("", remove_dots(".\\\\\\\\\\", false, path::Style::windows));
1463
1464 EXPECT_EQ("a\\..\\b\\c",
1465 remove_dots(".\\a\\..\\b\\c", false, path::Style::windows));
1466 EXPECT_EQ("b\\c", remove_dots(".\\a\\..\\b\\c", true, path::Style::windows));
1467 EXPECT_EQ("c", remove_dots(".\\.\\c", true, path::Style::windows));
1468 EXPECT_EQ("..\\a\\c",
1469 remove_dots("..\\a\\b\\..\\c", true, path::Style::windows));
1470 EXPECT_EQ("..\\..\\a\\c",
1471 remove_dots("..\\..\\a\\b\\..\\c", true, path::Style::windows));
1472 EXPECT_EQ("C:\\a\\c", remove_dots("C:\\foo\\bar//..\\..\\a\\c", true,
1473 path::Style::windows));
1474
1475 // FIXME: These leading forward slashes are emergent behavior. VFS depends on
1476 // this behavior now.
1477 EXPECT_EQ("C:/bar",
1478 remove_dots("C:/foo/../bar", true, path::Style::windows));
1479 EXPECT_EQ("C:/foo\\bar",
1480 remove_dots("C:/foo/bar", true, path::Style::windows));
1481 EXPECT_EQ("C:/foo\\bar",
1482 remove_dots("C:/foo\\bar", true, path::Style::windows));
1483 EXPECT_EQ("/", remove_dots("/", true, path::Style::windows));
1484 EXPECT_EQ("C:/", remove_dots("C:/", true, path::Style::windows));
1485
1486 // Some clients of remove_dots expect it to remove trailing slashes. Again,
1487 // this is emergent behavior that VFS relies on, and not inherently part of
1488 // the specification.
1489 EXPECT_EQ("C:\\foo\\bar",
1490 remove_dots("C:\\foo\\bar\\", true, path::Style::windows));
1491 EXPECT_EQ("/foo/bar",
1492 remove_dots("/foo/bar/", true, path::Style::posix));
1493
1494 // A double separator is rewritten.
1495 EXPECT_EQ("C:/foo\\bar", remove_dots("C:/foo//bar", true, path::Style::windows));
1496
1497 SmallString<64> Path1(".\\.\\c");
1498 EXPECT_TRUE(path::remove_dots(Path1, true, path::Style::windows));
1499 EXPECT_EQ("c", Path1);
1500
1501 EXPECT_EQ("foolz/wat",
1502 remove_dots("././/foolz/wat", false, path::Style::posix));
1503 EXPECT_EQ("", remove_dots("./////", false, path::Style::posix));
1504
1505 EXPECT_EQ("a/../b/c", remove_dots("./a/../b/c", false, path::Style::posix));
1506 EXPECT_EQ("b/c", remove_dots("./a/../b/c", true, path::Style::posix));
1507 EXPECT_EQ("c", remove_dots("././c", true, path::Style::posix));
1508 EXPECT_EQ("../a/c", remove_dots("../a/b/../c", true, path::Style::posix));
1509 EXPECT_EQ("../../a/c",
1510 remove_dots("../../a/b/../c", true, path::Style::posix));
1511 EXPECT_EQ("/a/c", remove_dots("/../../a/c", true, path::Style::posix));
1512 EXPECT_EQ("/a/c",
1513 remove_dots("/../a/b//../././/c", true, path::Style::posix));
1514 EXPECT_EQ("/", remove_dots("/", true, path::Style::posix));
1515
1516 // FIXME: Leaving behind this double leading slash seems like a bug.
1517 EXPECT_EQ("//foo/bar",
1518 remove_dots("//foo/bar/", true, path::Style::posix));
1519
1520 SmallString<64> Path2("././c");
1521 EXPECT_TRUE(path::remove_dots(Path2, true, path::Style::posix));
1522 EXPECT_EQ("c", Path2);
1523 }
1524
TEST(Support,ReplacePathPrefix)1525 TEST(Support, ReplacePathPrefix) {
1526 SmallString<64> Path1("/foo");
1527 SmallString<64> Path2("/old/foo");
1528 SmallString<64> Path3("/oldnew/foo");
1529 SmallString<64> Path4("C:\\old/foo\\bar");
1530 SmallString<64> OldPrefix("/old");
1531 SmallString<64> OldPrefixSep("/old/");
1532 SmallString<64> OldPrefixWin("c:/oLD/F");
1533 SmallString<64> NewPrefix("/new");
1534 SmallString<64> NewPrefix2("/longernew");
1535 SmallString<64> EmptyPrefix("");
1536 bool Found;
1537
1538 SmallString<64> Path = Path1;
1539 Found = path::replace_path_prefix(Path, OldPrefix, NewPrefix);
1540 EXPECT_FALSE(Found);
1541 EXPECT_EQ(Path, "/foo");
1542 Path = Path2;
1543 Found = path::replace_path_prefix(Path, OldPrefix, NewPrefix);
1544 EXPECT_TRUE(Found);
1545 EXPECT_EQ(Path, "/new/foo");
1546 Path = Path2;
1547 Found = path::replace_path_prefix(Path, OldPrefix, NewPrefix2);
1548 EXPECT_TRUE(Found);
1549 EXPECT_EQ(Path, "/longernew/foo");
1550 Path = Path1;
1551 Found = path::replace_path_prefix(Path, EmptyPrefix, NewPrefix);
1552 EXPECT_TRUE(Found);
1553 EXPECT_EQ(Path, "/new/foo");
1554 Path = Path2;
1555 Found = path::replace_path_prefix(Path, OldPrefix, EmptyPrefix);
1556 EXPECT_TRUE(Found);
1557 EXPECT_EQ(Path, "/foo");
1558 Path = Path2;
1559 Found = path::replace_path_prefix(Path, OldPrefixSep, EmptyPrefix);
1560 EXPECT_TRUE(Found);
1561 EXPECT_EQ(Path, "foo");
1562 Path = Path3;
1563 Found = path::replace_path_prefix(Path, OldPrefix, NewPrefix);
1564 EXPECT_TRUE(Found);
1565 EXPECT_EQ(Path, "/newnew/foo");
1566 Path = Path3;
1567 Found = path::replace_path_prefix(Path, OldPrefix, NewPrefix2);
1568 EXPECT_TRUE(Found);
1569 EXPECT_EQ(Path, "/longernewnew/foo");
1570 Path = Path1;
1571 Found = path::replace_path_prefix(Path, EmptyPrefix, NewPrefix);
1572 EXPECT_TRUE(Found);
1573 EXPECT_EQ(Path, "/new/foo");
1574 Path = OldPrefix;
1575 Found = path::replace_path_prefix(Path, OldPrefix, NewPrefix);
1576 EXPECT_TRUE(Found);
1577 EXPECT_EQ(Path, "/new");
1578 Path = OldPrefixSep;
1579 Found = path::replace_path_prefix(Path, OldPrefix, NewPrefix);
1580 EXPECT_TRUE(Found);
1581 EXPECT_EQ(Path, "/new/");
1582 Path = OldPrefix;
1583 Found = path::replace_path_prefix(Path, OldPrefixSep, NewPrefix);
1584 EXPECT_FALSE(Found);
1585 EXPECT_EQ(Path, "/old");
1586 Path = Path4;
1587 Found = path::replace_path_prefix(Path, OldPrefixWin, NewPrefix,
1588 path::Style::windows);
1589 EXPECT_TRUE(Found);
1590 EXPECT_EQ(Path, "/newoo\\bar");
1591 Path = Path4;
1592 Found = path::replace_path_prefix(Path, OldPrefixWin, NewPrefix,
1593 path::Style::posix);
1594 EXPECT_FALSE(Found);
1595 EXPECT_EQ(Path, "C:\\old/foo\\bar");
1596 }
1597
TEST_F(FileSystemTest,OpenFileForRead)1598 TEST_F(FileSystemTest, OpenFileForRead) {
1599 // Create a temp file.
1600 int FileDescriptor;
1601 SmallString<64> TempPath;
1602 ASSERT_NO_ERROR(
1603 fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
1604 FileRemover Cleanup(TempPath);
1605
1606 // Make sure it exists.
1607 ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
1608
1609 // Open the file for read
1610 int FileDescriptor2;
1611 SmallString<64> ResultPath;
1612 ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath), FileDescriptor2,
1613 fs::OF_None, &ResultPath))
1614
1615 // If we succeeded, check that the paths are the same (modulo case):
1616 if (!ResultPath.empty()) {
1617 // The paths returned by createTemporaryFile and getPathFromOpenFD
1618 // should reference the same file on disk.
1619 fs::UniqueID D1, D2;
1620 ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), D1));
1621 ASSERT_NO_ERROR(fs::getUniqueID(Twine(ResultPath), D2));
1622 ASSERT_EQ(D1, D2);
1623 }
1624 ::close(FileDescriptor);
1625 ::close(FileDescriptor2);
1626
1627 #ifdef _WIN32
1628 // Since Windows Vista, file access time is not updated by default.
1629 // This is instead updated manually by openFileForRead.
1630 // https://blogs.technet.microsoft.com/filecab/2006/11/07/disabling-last-access-time-in-windows-vista-to-improve-ntfs-performance/
1631 // This part of the unit test is Windows specific as the updating of
1632 // access times can be disabled on Linux using /etc/fstab.
1633
1634 // Set access time to UNIX epoch.
1635 ASSERT_NO_ERROR(sys::fs::openFileForWrite(Twine(TempPath), FileDescriptor,
1636 fs::CD_OpenExisting));
1637 TimePoint<> Epoch(std::chrono::milliseconds(0));
1638 ASSERT_NO_ERROR(fs::setLastAccessAndModificationTime(FileDescriptor, Epoch));
1639 ::close(FileDescriptor);
1640
1641 // Open the file and ensure access time is updated, when forced.
1642 ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath), FileDescriptor,
1643 fs::OF_UpdateAtime, &ResultPath));
1644
1645 sys::fs::file_status Status;
1646 ASSERT_NO_ERROR(sys::fs::status(FileDescriptor, Status));
1647 auto FileAccessTime = Status.getLastAccessedTime();
1648
1649 ASSERT_NE(Epoch, FileAccessTime);
1650 ::close(FileDescriptor);
1651
1652 // Ideally this test would include a case when ATime is not forced to update,
1653 // however the expected behaviour will differ depending on the configuration
1654 // of the Windows file system.
1655 #endif
1656 }
1657
createFileWithData(const Twine & Path,bool ShouldExistBefore,fs::CreationDisposition Disp,StringRef Data)1658 static void createFileWithData(const Twine &Path, bool ShouldExistBefore,
1659 fs::CreationDisposition Disp, StringRef Data) {
1660 int FD;
1661 ASSERT_EQ(ShouldExistBefore, fs::exists(Path));
1662 ASSERT_NO_ERROR(fs::openFileForWrite(Path, FD, Disp));
1663 FileDescriptorCloser Closer(FD);
1664 ASSERT_TRUE(fs::exists(Path));
1665
1666 ASSERT_EQ(Data.size(), (size_t)write(FD, Data.data(), Data.size()));
1667 }
1668
verifyFileContents(const Twine & Path,StringRef Contents)1669 static void verifyFileContents(const Twine &Path, StringRef Contents) {
1670 auto Buffer = MemoryBuffer::getFile(Path);
1671 ASSERT_TRUE((bool)Buffer);
1672 StringRef Data = Buffer.get()->getBuffer();
1673 ASSERT_EQ(Data, Contents);
1674 }
1675
TEST_F(FileSystemTest,CreateNew)1676 TEST_F(FileSystemTest, CreateNew) {
1677 int FD;
1678 Optional<FileDescriptorCloser> Closer;
1679
1680 // Succeeds if the file does not exist.
1681 ASSERT_FALSE(fs::exists(NonExistantFile));
1682 ASSERT_NO_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateNew));
1683 ASSERT_TRUE(fs::exists(NonExistantFile));
1684
1685 FileRemover Cleanup(NonExistantFile);
1686 Closer.emplace(FD);
1687
1688 // And creates a file of size 0.
1689 sys::fs::file_status Status;
1690 ASSERT_NO_ERROR(sys::fs::status(FD, Status));
1691 EXPECT_EQ(0ULL, Status.getSize());
1692
1693 // Close this first, before trying to re-open the file.
1694 Closer.reset();
1695
1696 // But fails if the file does exist.
1697 ASSERT_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateNew));
1698 }
1699
TEST_F(FileSystemTest,CreateAlways)1700 TEST_F(FileSystemTest, CreateAlways) {
1701 int FD;
1702 Optional<FileDescriptorCloser> Closer;
1703
1704 // Succeeds if the file does not exist.
1705 ASSERT_FALSE(fs::exists(NonExistantFile));
1706 ASSERT_NO_ERROR(
1707 fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateAlways));
1708
1709 Closer.emplace(FD);
1710
1711 ASSERT_TRUE(fs::exists(NonExistantFile));
1712
1713 FileRemover Cleanup(NonExistantFile);
1714
1715 // And creates a file of size 0.
1716 uint64_t FileSize;
1717 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1718 ASSERT_EQ(0ULL, FileSize);
1719
1720 // If we write some data to it re-create it with CreateAlways, it succeeds and
1721 // truncates to 0 bytes.
1722 ASSERT_EQ(4, write(FD, "Test", 4));
1723
1724 Closer.reset();
1725
1726 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1727 ASSERT_EQ(4ULL, FileSize);
1728
1729 ASSERT_NO_ERROR(
1730 fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateAlways));
1731 Closer.emplace(FD);
1732 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1733 ASSERT_EQ(0ULL, FileSize);
1734 }
1735
TEST_F(FileSystemTest,OpenExisting)1736 TEST_F(FileSystemTest, OpenExisting) {
1737 int FD;
1738
1739 // Fails if the file does not exist.
1740 ASSERT_FALSE(fs::exists(NonExistantFile));
1741 ASSERT_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_OpenExisting));
1742 ASSERT_FALSE(fs::exists(NonExistantFile));
1743
1744 // Make a dummy file now so that we can try again when the file does exist.
1745 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1746 FileRemover Cleanup(NonExistantFile);
1747 uint64_t FileSize;
1748 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1749 ASSERT_EQ(4ULL, FileSize);
1750
1751 // If we re-create it with different data, it overwrites rather than
1752 // appending.
1753 createFileWithData(NonExistantFile, true, fs::CD_OpenExisting, "Buzz");
1754 verifyFileContents(NonExistantFile, "Buzz");
1755 }
1756
TEST_F(FileSystemTest,OpenAlways)1757 TEST_F(FileSystemTest, OpenAlways) {
1758 // Succeeds if the file does not exist.
1759 createFileWithData(NonExistantFile, false, fs::CD_OpenAlways, "Fizz");
1760 FileRemover Cleanup(NonExistantFile);
1761 uint64_t FileSize;
1762 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1763 ASSERT_EQ(4ULL, FileSize);
1764
1765 // Now re-open it and write again, verifying the contents get over-written.
1766 createFileWithData(NonExistantFile, true, fs::CD_OpenAlways, "Bu");
1767 verifyFileContents(NonExistantFile, "Buzz");
1768 }
1769
TEST_F(FileSystemTest,AppendSetsCorrectFileOffset)1770 TEST_F(FileSystemTest, AppendSetsCorrectFileOffset) {
1771 fs::CreationDisposition Disps[] = {fs::CD_CreateAlways, fs::CD_OpenAlways,
1772 fs::CD_OpenExisting};
1773
1774 // Write some data and re-open it with every possible disposition (this is a
1775 // hack that shouldn't work, but is left for compatibility. OF_Append
1776 // overrides
1777 // the specified disposition.
1778 for (fs::CreationDisposition Disp : Disps) {
1779 int FD;
1780 Optional<FileDescriptorCloser> Closer;
1781
1782 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1783
1784 FileRemover Cleanup(NonExistantFile);
1785
1786 uint64_t FileSize;
1787 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1788 ASSERT_EQ(4ULL, FileSize);
1789 ASSERT_NO_ERROR(
1790 fs::openFileForWrite(NonExistantFile, FD, Disp, fs::OF_Append));
1791 Closer.emplace(FD);
1792 ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
1793 ASSERT_EQ(4ULL, FileSize);
1794
1795 ASSERT_EQ(4, write(FD, "Buzz", 4));
1796 Closer.reset();
1797
1798 verifyFileContents(NonExistantFile, "FizzBuzz");
1799 }
1800 }
1801
verifyRead(int FD,StringRef Data,bool ShouldSucceed)1802 static void verifyRead(int FD, StringRef Data, bool ShouldSucceed) {
1803 std::vector<char> Buffer;
1804 Buffer.resize(Data.size());
1805 int Result = ::read(FD, Buffer.data(), Buffer.size());
1806 if (ShouldSucceed) {
1807 ASSERT_EQ((size_t)Result, Data.size());
1808 ASSERT_EQ(Data, StringRef(Buffer.data(), Buffer.size()));
1809 } else {
1810 ASSERT_EQ(-1, Result);
1811 ASSERT_EQ(EBADF, errno);
1812 }
1813 }
1814
verifyWrite(int FD,StringRef Data,bool ShouldSucceed)1815 static void verifyWrite(int FD, StringRef Data, bool ShouldSucceed) {
1816 int Result = ::write(FD, Data.data(), Data.size());
1817 if (ShouldSucceed)
1818 ASSERT_EQ((size_t)Result, Data.size());
1819 else {
1820 ASSERT_EQ(-1, Result);
1821 ASSERT_EQ(EBADF, errno);
1822 }
1823 }
1824
TEST_F(FileSystemTest,ReadOnlyFileCantWrite)1825 TEST_F(FileSystemTest, ReadOnlyFileCantWrite) {
1826 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1827 FileRemover Cleanup(NonExistantFile);
1828
1829 int FD;
1830 ASSERT_NO_ERROR(fs::openFileForRead(NonExistantFile, FD));
1831 FileDescriptorCloser Closer(FD);
1832
1833 verifyWrite(FD, "Buzz", false);
1834 verifyRead(FD, "Fizz", true);
1835 }
1836
TEST_F(FileSystemTest,WriteOnlyFileCantRead)1837 TEST_F(FileSystemTest, WriteOnlyFileCantRead) {
1838 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1839 FileRemover Cleanup(NonExistantFile);
1840
1841 int FD;
1842 ASSERT_NO_ERROR(
1843 fs::openFileForWrite(NonExistantFile, FD, fs::CD_OpenExisting));
1844 FileDescriptorCloser Closer(FD);
1845 verifyRead(FD, "Fizz", false);
1846 verifyWrite(FD, "Buzz", true);
1847 }
1848
TEST_F(FileSystemTest,ReadWriteFileCanReadOrWrite)1849 TEST_F(FileSystemTest, ReadWriteFileCanReadOrWrite) {
1850 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
1851 FileRemover Cleanup(NonExistantFile);
1852
1853 int FD;
1854 ASSERT_NO_ERROR(fs::openFileForReadWrite(NonExistantFile, FD,
1855 fs::CD_OpenExisting, fs::OF_None));
1856 FileDescriptorCloser Closer(FD);
1857 verifyRead(FD, "Fizz", true);
1858 verifyWrite(FD, "Buzz", true);
1859 }
1860
TEST_F(FileSystemTest,readNativeFile)1861 TEST_F(FileSystemTest, readNativeFile) {
1862 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "01234");
1863 FileRemover Cleanup(NonExistantFile);
1864 const auto &Read = [&](size_t ToRead) -> Expected<std::string> {
1865 std::string Buf(ToRead, '?');
1866 Expected<fs::file_t> FD = fs::openNativeFileForRead(NonExistantFile);
1867 if (!FD)
1868 return FD.takeError();
1869 auto Close = make_scope_exit([&] { fs::closeFile(*FD); });
1870 if (Expected<size_t> BytesRead = fs::readNativeFile(
1871 *FD, makeMutableArrayRef(&*Buf.begin(), Buf.size())))
1872 return Buf.substr(0, *BytesRead);
1873 else
1874 return BytesRead.takeError();
1875 };
1876 EXPECT_THAT_EXPECTED(Read(5), HasValue("01234"));
1877 EXPECT_THAT_EXPECTED(Read(3), HasValue("012"));
1878 EXPECT_THAT_EXPECTED(Read(6), HasValue("01234"));
1879 }
1880
TEST_F(FileSystemTest,readNativeFileSlice)1881 TEST_F(FileSystemTest, readNativeFileSlice) {
1882 createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "01234");
1883 FileRemover Cleanup(NonExistantFile);
1884 Expected<fs::file_t> FD = fs::openNativeFileForRead(NonExistantFile);
1885 ASSERT_THAT_EXPECTED(FD, Succeeded());
1886 auto Close = make_scope_exit([&] { fs::closeFile(*FD); });
1887 const auto &Read = [&](size_t Offset,
1888 size_t ToRead) -> Expected<std::string> {
1889 std::string Buf(ToRead, '?');
1890 if (Expected<size_t> BytesRead = fs::readNativeFileSlice(
1891 *FD, makeMutableArrayRef(&*Buf.begin(), Buf.size()), Offset))
1892 return Buf.substr(0, *BytesRead);
1893 else
1894 return BytesRead.takeError();
1895 };
1896 EXPECT_THAT_EXPECTED(Read(0, 5), HasValue("01234"));
1897 EXPECT_THAT_EXPECTED(Read(0, 3), HasValue("012"));
1898 EXPECT_THAT_EXPECTED(Read(2, 3), HasValue("234"));
1899 EXPECT_THAT_EXPECTED(Read(0, 6), HasValue("01234"));
1900 EXPECT_THAT_EXPECTED(Read(2, 6), HasValue("234"));
1901 EXPECT_THAT_EXPECTED(Read(5, 5), HasValue(""));
1902 }
1903
TEST_F(FileSystemTest,is_local)1904 TEST_F(FileSystemTest, is_local) {
1905 bool TestDirectoryIsLocal;
1906 ASSERT_NO_ERROR(fs::is_local(TestDirectory, TestDirectoryIsLocal));
1907 EXPECT_EQ(TestDirectoryIsLocal, fs::is_local(TestDirectory));
1908
1909 int FD;
1910 SmallString<128> TempPath;
1911 ASSERT_NO_ERROR(
1912 fs::createUniqueFile(Twine(TestDirectory) + "/temp", FD, TempPath));
1913 FileRemover Cleanup(TempPath);
1914
1915 // Make sure it exists.
1916 ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
1917
1918 bool TempFileIsLocal;
1919 ASSERT_NO_ERROR(fs::is_local(FD, TempFileIsLocal));
1920 EXPECT_EQ(TempFileIsLocal, fs::is_local(FD));
1921 ::close(FD);
1922
1923 // Expect that the file and its parent directory are equally local or equally
1924 // remote.
1925 EXPECT_EQ(TestDirectoryIsLocal, TempFileIsLocal);
1926 }
1927
TEST_F(FileSystemTest,getUmask)1928 TEST_F(FileSystemTest, getUmask) {
1929 #ifdef _WIN32
1930 EXPECT_EQ(fs::getUmask(), 0U) << "Should always be 0 on Windows.";
1931 #else
1932 unsigned OldMask = ::umask(0022);
1933 unsigned CurrentMask = fs::getUmask();
1934 EXPECT_EQ(CurrentMask, 0022U)
1935 << "getUmask() didn't return previously set umask()";
1936 EXPECT_EQ(::umask(OldMask), mode_t(0022U))
1937 << "getUmask() may have changed umask()";
1938 #endif
1939 }
1940
TEST_F(FileSystemTest,RespectUmask)1941 TEST_F(FileSystemTest, RespectUmask) {
1942 #ifndef _WIN32
1943 unsigned OldMask = ::umask(0022);
1944
1945 int FD;
1946 SmallString<128> TempPath;
1947 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
1948
1949 fs::perms AllRWE = static_cast<fs::perms>(0777);
1950
1951 ASSERT_NO_ERROR(fs::setPermissions(TempPath, AllRWE));
1952
1953 ErrorOr<fs::perms> Perms = fs::getPermissions(TempPath);
1954 ASSERT_TRUE(!!Perms);
1955 EXPECT_EQ(Perms.get(), AllRWE) << "Should have ignored umask by default";
1956
1957 ASSERT_NO_ERROR(fs::setPermissions(TempPath, AllRWE));
1958
1959 Perms = fs::getPermissions(TempPath);
1960 ASSERT_TRUE(!!Perms);
1961 EXPECT_EQ(Perms.get(), AllRWE) << "Should have ignored umask";
1962
1963 ASSERT_NO_ERROR(
1964 fs::setPermissions(FD, static_cast<fs::perms>(AllRWE & ~fs::getUmask())));
1965 Perms = fs::getPermissions(TempPath);
1966 ASSERT_TRUE(!!Perms);
1967 EXPECT_EQ(Perms.get(), static_cast<fs::perms>(0755))
1968 << "Did not respect umask";
1969
1970 (void)::umask(0057);
1971
1972 ASSERT_NO_ERROR(
1973 fs::setPermissions(FD, static_cast<fs::perms>(AllRWE & ~fs::getUmask())));
1974 Perms = fs::getPermissions(TempPath);
1975 ASSERT_TRUE(!!Perms);
1976 EXPECT_EQ(Perms.get(), static_cast<fs::perms>(0720))
1977 << "Did not respect umask";
1978
1979 (void)::umask(OldMask);
1980 (void)::close(FD);
1981 #endif
1982 }
1983
TEST_F(FileSystemTest,set_current_path)1984 TEST_F(FileSystemTest, set_current_path) {
1985 SmallString<128> path;
1986
1987 ASSERT_NO_ERROR(fs::current_path(path));
1988 ASSERT_NE(TestDirectory, path);
1989
1990 struct RestorePath {
1991 SmallString<128> path;
1992 RestorePath(const SmallString<128> &path) : path(path) {}
1993 ~RestorePath() { fs::set_current_path(path); }
1994 } restore_path(path);
1995
1996 ASSERT_NO_ERROR(fs::set_current_path(TestDirectory));
1997
1998 ASSERT_NO_ERROR(fs::current_path(path));
1999
2000 fs::UniqueID D1, D2;
2001 ASSERT_NO_ERROR(fs::getUniqueID(TestDirectory, D1));
2002 ASSERT_NO_ERROR(fs::getUniqueID(path, D2));
2003 ASSERT_EQ(D1, D2) << "D1: " << TestDirectory << "\nD2: " << path;
2004 }
2005
TEST_F(FileSystemTest,permissions)2006 TEST_F(FileSystemTest, permissions) {
2007 int FD;
2008 SmallString<64> TempPath;
2009 ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
2010 FileRemover Cleanup(TempPath);
2011
2012 // Make sure it exists.
2013 ASSERT_TRUE(fs::exists(Twine(TempPath)));
2014
2015 auto CheckPermissions = [&](fs::perms Expected) {
2016 ErrorOr<fs::perms> Actual = fs::getPermissions(TempPath);
2017 return Actual && *Actual == Expected;
2018 };
2019
2020 std::error_code NoError;
2021 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_all), NoError);
2022 EXPECT_TRUE(CheckPermissions(fs::all_all));
2023
2024 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read | fs::all_exe), NoError);
2025 EXPECT_TRUE(CheckPermissions(fs::all_read | fs::all_exe));
2026
2027 #if defined(_WIN32)
2028 fs::perms ReadOnly = fs::all_read | fs::all_exe;
2029 EXPECT_EQ(fs::setPermissions(TempPath, fs::no_perms), NoError);
2030 EXPECT_TRUE(CheckPermissions(ReadOnly));
2031
2032 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_read), NoError);
2033 EXPECT_TRUE(CheckPermissions(ReadOnly));
2034
2035 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_write), NoError);
2036 EXPECT_TRUE(CheckPermissions(fs::all_all));
2037
2038 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_exe), NoError);
2039 EXPECT_TRUE(CheckPermissions(ReadOnly));
2040
2041 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_all), NoError);
2042 EXPECT_TRUE(CheckPermissions(fs::all_all));
2043
2044 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_read), NoError);
2045 EXPECT_TRUE(CheckPermissions(ReadOnly));
2046
2047 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_write), NoError);
2048 EXPECT_TRUE(CheckPermissions(fs::all_all));
2049
2050 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_exe), NoError);
2051 EXPECT_TRUE(CheckPermissions(ReadOnly));
2052
2053 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_all), NoError);
2054 EXPECT_TRUE(CheckPermissions(fs::all_all));
2055
2056 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_read), NoError);
2057 EXPECT_TRUE(CheckPermissions(ReadOnly));
2058
2059 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_write), NoError);
2060 EXPECT_TRUE(CheckPermissions(fs::all_all));
2061
2062 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_exe), NoError);
2063 EXPECT_TRUE(CheckPermissions(ReadOnly));
2064
2065 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_all), NoError);
2066 EXPECT_TRUE(CheckPermissions(fs::all_all));
2067
2068 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read), NoError);
2069 EXPECT_TRUE(CheckPermissions(ReadOnly));
2070
2071 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_write), NoError);
2072 EXPECT_TRUE(CheckPermissions(fs::all_all));
2073
2074 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_exe), NoError);
2075 EXPECT_TRUE(CheckPermissions(ReadOnly));
2076
2077 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe), NoError);
2078 EXPECT_TRUE(CheckPermissions(ReadOnly));
2079
2080 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_gid_on_exe), NoError);
2081 EXPECT_TRUE(CheckPermissions(ReadOnly));
2082
2083 EXPECT_EQ(fs::setPermissions(TempPath, fs::sticky_bit), NoError);
2084 EXPECT_TRUE(CheckPermissions(ReadOnly));
2085
2086 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe |
2087 fs::set_gid_on_exe |
2088 fs::sticky_bit),
2089 NoError);
2090 EXPECT_TRUE(CheckPermissions(ReadOnly));
2091
2092 EXPECT_EQ(fs::setPermissions(TempPath, ReadOnly | fs::set_uid_on_exe |
2093 fs::set_gid_on_exe |
2094 fs::sticky_bit),
2095 NoError);
2096 EXPECT_TRUE(CheckPermissions(ReadOnly));
2097
2098 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms), NoError);
2099 EXPECT_TRUE(CheckPermissions(fs::all_all));
2100 #else
2101 EXPECT_EQ(fs::setPermissions(TempPath, fs::no_perms), NoError);
2102 EXPECT_TRUE(CheckPermissions(fs::no_perms));
2103
2104 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_read), NoError);
2105 EXPECT_TRUE(CheckPermissions(fs::owner_read));
2106
2107 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_write), NoError);
2108 EXPECT_TRUE(CheckPermissions(fs::owner_write));
2109
2110 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_exe), NoError);
2111 EXPECT_TRUE(CheckPermissions(fs::owner_exe));
2112
2113 EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_all), NoError);
2114 EXPECT_TRUE(CheckPermissions(fs::owner_all));
2115
2116 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_read), NoError);
2117 EXPECT_TRUE(CheckPermissions(fs::group_read));
2118
2119 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_write), NoError);
2120 EXPECT_TRUE(CheckPermissions(fs::group_write));
2121
2122 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_exe), NoError);
2123 EXPECT_TRUE(CheckPermissions(fs::group_exe));
2124
2125 EXPECT_EQ(fs::setPermissions(TempPath, fs::group_all), NoError);
2126 EXPECT_TRUE(CheckPermissions(fs::group_all));
2127
2128 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_read), NoError);
2129 EXPECT_TRUE(CheckPermissions(fs::others_read));
2130
2131 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_write), NoError);
2132 EXPECT_TRUE(CheckPermissions(fs::others_write));
2133
2134 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_exe), NoError);
2135 EXPECT_TRUE(CheckPermissions(fs::others_exe));
2136
2137 EXPECT_EQ(fs::setPermissions(TempPath, fs::others_all), NoError);
2138 EXPECT_TRUE(CheckPermissions(fs::others_all));
2139
2140 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read), NoError);
2141 EXPECT_TRUE(CheckPermissions(fs::all_read));
2142
2143 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_write), NoError);
2144 EXPECT_TRUE(CheckPermissions(fs::all_write));
2145
2146 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_exe), NoError);
2147 EXPECT_TRUE(CheckPermissions(fs::all_exe));
2148
2149 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe), NoError);
2150 EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe));
2151
2152 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_gid_on_exe), NoError);
2153 EXPECT_TRUE(CheckPermissions(fs::set_gid_on_exe));
2154
2155 // Modern BSDs require root to set the sticky bit on files.
2156 // AIX and Solaris without root will mask off (i.e., lose) the sticky bit
2157 // on files.
2158 #if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
2159 !defined(_AIX) && !(defined(__sun__) && defined(__svr4__))
2160 EXPECT_EQ(fs::setPermissions(TempPath, fs::sticky_bit), NoError);
2161 EXPECT_TRUE(CheckPermissions(fs::sticky_bit));
2162
2163 EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe |
2164 fs::set_gid_on_exe |
2165 fs::sticky_bit),
2166 NoError);
2167 EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe | fs::set_gid_on_exe |
2168 fs::sticky_bit));
2169
2170 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read | fs::set_uid_on_exe |
2171 fs::set_gid_on_exe |
2172 fs::sticky_bit),
2173 NoError);
2174 EXPECT_TRUE(CheckPermissions(fs::all_read | fs::set_uid_on_exe |
2175 fs::set_gid_on_exe | fs::sticky_bit));
2176
2177 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms), NoError);
2178 EXPECT_TRUE(CheckPermissions(fs::all_perms));
2179 #endif // !FreeBSD && !NetBSD && !OpenBSD && !AIX
2180
2181 EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms & ~fs::sticky_bit),
2182 NoError);
2183 EXPECT_TRUE(CheckPermissions(fs::all_perms & ~fs::sticky_bit));
2184 #endif
2185 }
2186
2187 #ifdef _WIN32
TEST_F(FileSystemTest,widenPath)2188 TEST_F(FileSystemTest, widenPath) {
2189 const std::wstring LongPathPrefix(L"\\\\?\\");
2190
2191 // Test that the length limit is checked against the UTF-16 length and not the
2192 // UTF-8 length.
2193 std::string Input("C:\\foldername\\");
2194 const std::string Pi("\xcf\x80"); // UTF-8 lower case pi.
2195 // Add Pi up to the MAX_PATH limit.
2196 const size_t NumChars = MAX_PATH - Input.size() - 1;
2197 for (size_t i = 0; i < NumChars; ++i)
2198 Input += Pi;
2199 // Check that UTF-8 length already exceeds MAX_PATH.
2200 EXPECT_TRUE(Input.size() > MAX_PATH);
2201 SmallVector<wchar_t, MAX_PATH + 16> Result;
2202 ASSERT_NO_ERROR(windows::widenPath(Input, Result));
2203 // Result should not start with the long path prefix.
2204 EXPECT_TRUE(std::wmemcmp(Result.data(), LongPathPrefix.c_str(),
2205 LongPathPrefix.size()) != 0);
2206 EXPECT_EQ(Result.size(), (size_t)MAX_PATH - 1);
2207
2208 // Add another Pi to exceed the MAX_PATH limit.
2209 Input += Pi;
2210 // Construct the expected result.
2211 SmallVector<wchar_t, MAX_PATH + 16> Expected;
2212 ASSERT_NO_ERROR(windows::UTF8ToUTF16(Input, Expected));
2213 Expected.insert(Expected.begin(), LongPathPrefix.begin(),
2214 LongPathPrefix.end());
2215
2216 ASSERT_NO_ERROR(windows::widenPath(Input, Result));
2217 EXPECT_EQ(Result, Expected);
2218
2219 // Test that UNC paths are handled correctly.
2220 const std::string ShareName("\\\\sharename\\");
2221 const std::string FileName("\\filename");
2222 // Initialize directory name so that the input is within the MAX_PATH limit.
2223 const char DirChar = 'x';
2224 std::string DirName(MAX_PATH - ShareName.size() - FileName.size() - 1,
2225 DirChar);
2226
2227 Input = ShareName + DirName + FileName;
2228 ASSERT_NO_ERROR(windows::widenPath(Input, Result));
2229 // Result should not start with the long path prefix.
2230 EXPECT_TRUE(std::wmemcmp(Result.data(), LongPathPrefix.c_str(),
2231 LongPathPrefix.size()) != 0);
2232 EXPECT_EQ(Result.size(), (size_t)MAX_PATH - 1);
2233
2234 // Extend the directory name so the input exceeds the MAX_PATH limit.
2235 DirName += DirChar;
2236 Input = ShareName + DirName + FileName;
2237 // Construct the expected result.
2238 ASSERT_NO_ERROR(windows::UTF8ToUTF16(StringRef(Input).substr(2), Expected));
2239 const std::wstring UNCPrefix(LongPathPrefix + L"UNC\\");
2240 Expected.insert(Expected.begin(), UNCPrefix.begin(), UNCPrefix.end());
2241
2242 ASSERT_NO_ERROR(windows::widenPath(Input, Result));
2243 EXPECT_EQ(Result, Expected);
2244
2245 // Check that Unix separators are handled correctly.
2246 std::replace(Input.begin(), Input.end(), '\\', '/');
2247 ASSERT_NO_ERROR(windows::widenPath(Input, Result));
2248 EXPECT_EQ(Result, Expected);
2249
2250 // Check the removal of "dots".
2251 Input = ShareName + DirName + "\\.\\foo\\.\\.." + FileName;
2252 ASSERT_NO_ERROR(windows::widenPath(Input, Result));
2253 EXPECT_EQ(Result, Expected);
2254 }
2255 #endif
2256
2257 #ifdef _WIN32
2258 // Windows refuses lock request if file region is already locked by the same
2259 // process. POSIX system in this case updates the existing lock.
TEST_F(FileSystemTest,FileLocker)2260 TEST_F(FileSystemTest, FileLocker) {
2261 using namespace std::chrono;
2262 int FD;
2263 std::error_code EC;
2264 SmallString<64> TempPath;
2265 EC = fs::createTemporaryFile("test", "temp", FD, TempPath);
2266 ASSERT_NO_ERROR(EC);
2267 FileRemover Cleanup(TempPath);
2268 raw_fd_ostream Stream(TempPath, EC);
2269
2270 EC = fs::tryLockFile(FD);
2271 ASSERT_NO_ERROR(EC);
2272 EC = fs::unlockFile(FD);
2273 ASSERT_NO_ERROR(EC);
2274
2275 if (auto L = Stream.lock()) {
2276 ASSERT_ERROR(fs::tryLockFile(FD));
2277 ASSERT_NO_ERROR(L->unlock());
2278 ASSERT_NO_ERROR(fs::tryLockFile(FD));
2279 ASSERT_NO_ERROR(fs::unlockFile(FD));
2280 } else {
2281 ADD_FAILURE();
2282 handleAllErrors(L.takeError(), [&](ErrorInfoBase &EIB) {});
2283 }
2284
2285 ASSERT_NO_ERROR(fs::tryLockFile(FD));
2286 ASSERT_NO_ERROR(fs::unlockFile(FD));
2287
2288 {
2289 Expected<fs::FileLocker> L1 = Stream.lock();
2290 ASSERT_THAT_EXPECTED(L1, Succeeded());
2291 raw_fd_ostream Stream2(FD, false);
2292 Expected<fs::FileLocker> L2 = Stream2.tryLockFor(250ms);
2293 ASSERT_THAT_EXPECTED(L2, Failed());
2294 ASSERT_NO_ERROR(L1->unlock());
2295 Expected<fs::FileLocker> L3 = Stream.tryLockFor(0ms);
2296 ASSERT_THAT_EXPECTED(L3, Succeeded());
2297 }
2298
2299 ASSERT_NO_ERROR(fs::tryLockFile(FD));
2300 ASSERT_NO_ERROR(fs::unlockFile(FD));
2301 }
2302 #endif
2303
2304 } // anonymous namespace
2305