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