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

source code of llvm/unittests/Support/Path.cpp