Path.cpp 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669
  1. //===- llvm/unittest/Support/Path.cpp - Path tests ------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "llvm/Support/Path.h"
  10. #include "llvm/ADT/STLExtras.h"
  11. #include "llvm/ADT/SmallVector.h"
  12. #include "llvm/ADT/Triple.h"
  13. #include "llvm/BinaryFormat/Magic.h"
  14. #include "llvm/Config/llvm-config.h"
  15. #include "llvm/Support/ConvertUTF.h"
  16. #include "llvm/Support/Errc.h"
  17. #include "llvm/Support/ErrorHandling.h"
  18. #include "llvm/Support/FileSystem.h"
  19. #include "llvm/Support/FileUtilities.h"
  20. #include "llvm/Support/Host.h"
  21. #include "llvm/Support/MemoryBuffer.h"
  22. #include "llvm/Support/raw_ostream.h"
  23. #include "gtest/gtest.h"
  24. #include "gmock/gmock.h"
  25. #ifdef _WIN32
  26. #include "llvm/ADT/ArrayRef.h"
  27. #include "llvm/Support/Chrono.h"
  28. #include <windows.h>
  29. #include <winerror.h>
  30. #endif
  31. #ifdef LLVM_ON_UNIX
  32. #include <pwd.h>
  33. #include <sys/stat.h>
  34. #endif
  35. using namespace llvm;
  36. using namespace llvm::sys;
  37. #define ASSERT_NO_ERROR(x) \
  38. if (std::error_code ASSERT_NO_ERROR_ec = x) { \
  39. SmallString<128> MessageStorage; \
  40. raw_svector_ostream Message(MessageStorage); \
  41. Message << #x ": did not return errc::success.\n" \
  42. << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \
  43. << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \
  44. GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \
  45. } else { \
  46. }
  47. #define ASSERT_ERROR(x) \
  48. if (!x) { \
  49. SmallString<128> MessageStorage; \
  50. raw_svector_ostream Message(MessageStorage); \
  51. Message << #x ": did not return a failure error code.\n"; \
  52. GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \
  53. }
  54. namespace {
  55. struct FileDescriptorCloser {
  56. explicit FileDescriptorCloser(int FD) : FD(FD) {}
  57. ~FileDescriptorCloser() { ::close(FD); }
  58. int FD;
  59. };
  60. TEST(is_separator, Works) {
  61. EXPECT_TRUE(path::is_separator('/'));
  62. EXPECT_FALSE(path::is_separator('\0'));
  63. EXPECT_FALSE(path::is_separator('-'));
  64. EXPECT_FALSE(path::is_separator(' '));
  65. EXPECT_TRUE(path::is_separator('\\', path::Style::windows));
  66. EXPECT_FALSE(path::is_separator('\\', path::Style::posix));
  67. #ifdef _WIN32
  68. EXPECT_TRUE(path::is_separator('\\'));
  69. #else
  70. EXPECT_FALSE(path::is_separator('\\'));
  71. #endif
  72. }
  73. TEST(Support, Path) {
  74. SmallVector<StringRef, 40> paths;
  75. paths.push_back("");
  76. paths.push_back(".");
  77. paths.push_back("..");
  78. paths.push_back("foo");
  79. paths.push_back("/");
  80. paths.push_back("/foo");
  81. paths.push_back("foo/");
  82. paths.push_back("/foo/");
  83. paths.push_back("foo/bar");
  84. paths.push_back("/foo/bar");
  85. paths.push_back("//net");
  86. paths.push_back("//net/");
  87. paths.push_back("//net/foo");
  88. paths.push_back("///foo///");
  89. paths.push_back("///foo///bar");
  90. paths.push_back("/.");
  91. paths.push_back("./");
  92. paths.push_back("/..");
  93. paths.push_back("../");
  94. paths.push_back("foo/.");
  95. paths.push_back("foo/..");
  96. paths.push_back("foo/./");
  97. paths.push_back("foo/./bar");
  98. paths.push_back("foo/..");
  99. paths.push_back("foo/../");
  100. paths.push_back("foo/../bar");
  101. paths.push_back("c:");
  102. paths.push_back("c:/");
  103. paths.push_back("c:foo");
  104. paths.push_back("c:/foo");
  105. paths.push_back("c:foo/");
  106. paths.push_back("c:/foo/");
  107. paths.push_back("c:/foo/bar");
  108. paths.push_back("prn:");
  109. paths.push_back("c:\\");
  110. paths.push_back("c:foo");
  111. paths.push_back("c:\\foo");
  112. paths.push_back("c:foo\\");
  113. paths.push_back("c:\\foo\\");
  114. paths.push_back("c:\\foo/");
  115. paths.push_back("c:/foo\\bar");
  116. for (SmallVector<StringRef, 40>::const_iterator i = paths.begin(),
  117. e = paths.end();
  118. i != e;
  119. ++i) {
  120. SCOPED_TRACE(*i);
  121. SmallVector<StringRef, 5> ComponentStack;
  122. for (sys::path::const_iterator ci = sys::path::begin(*i),
  123. ce = sys::path::end(*i);
  124. ci != ce;
  125. ++ci) {
  126. EXPECT_FALSE(ci->empty());
  127. ComponentStack.push_back(*ci);
  128. }
  129. SmallVector<StringRef, 5> ReverseComponentStack;
  130. for (sys::path::reverse_iterator ci = sys::path::rbegin(*i),
  131. ce = sys::path::rend(*i);
  132. ci != ce;
  133. ++ci) {
  134. EXPECT_FALSE(ci->empty());
  135. ReverseComponentStack.push_back(*ci);
  136. }
  137. std::reverse(ReverseComponentStack.begin(), ReverseComponentStack.end());
  138. EXPECT_THAT(ComponentStack, testing::ContainerEq(ReverseComponentStack));
  139. // Crash test most of the API - since we're iterating over all of our paths
  140. // here there isn't really anything reasonable to assert on in the results.
  141. (void)path::has_root_path(*i);
  142. (void)path::root_path(*i);
  143. (void)path::has_root_name(*i);
  144. (void)path::root_name(*i);
  145. (void)path::has_root_directory(*i);
  146. (void)path::root_directory(*i);
  147. (void)path::has_parent_path(*i);
  148. (void)path::parent_path(*i);
  149. (void)path::has_filename(*i);
  150. (void)path::filename(*i);
  151. (void)path::has_stem(*i);
  152. (void)path::stem(*i);
  153. (void)path::has_extension(*i);
  154. (void)path::extension(*i);
  155. (void)path::is_absolute(*i);
  156. (void)path::is_relative(*i);
  157. SmallString<128> temp_store;
  158. temp_store = *i;
  159. ASSERT_NO_ERROR(fs::make_absolute(temp_store));
  160. temp_store = *i;
  161. path::remove_filename(temp_store);
  162. temp_store = *i;
  163. path::replace_extension(temp_store, "ext");
  164. StringRef filename(temp_store.begin(), temp_store.size()), stem, ext;
  165. stem = path::stem(filename);
  166. ext = path::extension(filename);
  167. EXPECT_EQ(*sys::path::rbegin(filename), (stem + ext).str());
  168. path::native(*i, temp_store);
  169. }
  170. SmallString<32> Relative("foo.cpp");
  171. ASSERT_NO_ERROR(sys::fs::make_absolute("/root", Relative));
  172. Relative[5] = '/'; // Fix up windows paths.
  173. ASSERT_EQ("/root/foo.cpp", Relative);
  174. }
  175. TEST(Support, FilenameParent) {
  176. EXPECT_EQ("/", path::filename("/"));
  177. EXPECT_EQ("", path::parent_path("/"));
  178. EXPECT_EQ("\\", path::filename("c:\\", path::Style::windows));
  179. EXPECT_EQ("c:", path::parent_path("c:\\", path::Style::windows));
  180. EXPECT_EQ("/", path::filename("///"));
  181. EXPECT_EQ("", path::parent_path("///"));
  182. EXPECT_EQ("\\", path::filename("c:\\\\", path::Style::windows));
  183. EXPECT_EQ("c:", path::parent_path("c:\\\\", path::Style::windows));
  184. EXPECT_EQ("bar", path::filename("/foo/bar"));
  185. EXPECT_EQ("/foo", path::parent_path("/foo/bar"));
  186. EXPECT_EQ("foo", path::filename("/foo"));
  187. EXPECT_EQ("/", path::parent_path("/foo"));
  188. EXPECT_EQ("foo", path::filename("foo"));
  189. EXPECT_EQ("", path::parent_path("foo"));
  190. EXPECT_EQ(".", path::filename("foo/"));
  191. EXPECT_EQ("foo", path::parent_path("foo/"));
  192. EXPECT_EQ("//net", path::filename("//net"));
  193. EXPECT_EQ("", path::parent_path("//net"));
  194. EXPECT_EQ("/", path::filename("//net/"));
  195. EXPECT_EQ("//net", path::parent_path("//net/"));
  196. EXPECT_EQ("foo", path::filename("//net/foo"));
  197. EXPECT_EQ("//net/", path::parent_path("//net/foo"));
  198. // These checks are just to make sure we do something reasonable with the
  199. // paths below. They are not meant to prescribe the one true interpretation of
  200. // these paths. Other decompositions (e.g. "//" -> "" + "//") are also
  201. // possible.
  202. EXPECT_EQ("/", path::filename("//"));
  203. EXPECT_EQ("", path::parent_path("//"));
  204. EXPECT_EQ("\\", path::filename("\\\\", path::Style::windows));
  205. EXPECT_EQ("", path::parent_path("\\\\", path::Style::windows));
  206. EXPECT_EQ("\\", path::filename("\\\\\\", path::Style::windows));
  207. EXPECT_EQ("", path::parent_path("\\\\\\", path::Style::windows));
  208. }
  209. static std::vector<StringRef>
  210. GetComponents(StringRef Path, path::Style S = path::Style::native) {
  211. return {path::begin(Path, S), path::end(Path)};
  212. }
  213. TEST(Support, PathIterator) {
  214. EXPECT_THAT(GetComponents("/foo"), testing::ElementsAre("/", "foo"));
  215. EXPECT_THAT(GetComponents("/"), testing::ElementsAre("/"));
  216. EXPECT_THAT(GetComponents("//"), testing::ElementsAre("/"));
  217. EXPECT_THAT(GetComponents("///"), testing::ElementsAre("/"));
  218. EXPECT_THAT(GetComponents("c/d/e/foo.txt"),
  219. testing::ElementsAre("c", "d", "e", "foo.txt"));
  220. EXPECT_THAT(GetComponents(".c/.d/../."),
  221. testing::ElementsAre(".c", ".d", "..", "."));
  222. EXPECT_THAT(GetComponents("/c/d/e/foo.txt"),
  223. testing::ElementsAre("/", "c", "d", "e", "foo.txt"));
  224. EXPECT_THAT(GetComponents("/.c/.d/../."),
  225. testing::ElementsAre("/", ".c", ".d", "..", "."));
  226. EXPECT_THAT(GetComponents("c:\\c\\e\\foo.txt", path::Style::windows),
  227. testing::ElementsAre("c:", "\\", "c", "e", "foo.txt"));
  228. EXPECT_THAT(GetComponents("//net/"), testing::ElementsAre("//net", "/"));
  229. EXPECT_THAT(GetComponents("//net/c/foo.txt"),
  230. testing::ElementsAre("//net", "/", "c", "foo.txt"));
  231. }
  232. TEST(Support, AbsolutePathIteratorEnd) {
  233. // Trailing slashes are converted to '.' unless they are part of the root path.
  234. SmallVector<std::pair<StringRef, path::Style>, 4> Paths;
  235. Paths.emplace_back("/foo/", path::Style::native);
  236. Paths.emplace_back("/foo//", path::Style::native);
  237. Paths.emplace_back("//net/foo/", path::Style::native);
  238. Paths.emplace_back("c:\\foo\\", path::Style::windows);
  239. for (auto &Path : Paths) {
  240. SCOPED_TRACE(Path.first);
  241. StringRef LastComponent = *path::rbegin(Path.first, Path.second);
  242. EXPECT_EQ(".", LastComponent);
  243. }
  244. SmallVector<std::pair<StringRef, path::Style>, 3> RootPaths;
  245. RootPaths.emplace_back("/", path::Style::native);
  246. RootPaths.emplace_back("//net/", path::Style::native);
  247. RootPaths.emplace_back("c:\\", path::Style::windows);
  248. RootPaths.emplace_back("//net//", path::Style::native);
  249. RootPaths.emplace_back("c:\\\\", path::Style::windows);
  250. for (auto &Path : RootPaths) {
  251. SCOPED_TRACE(Path.first);
  252. StringRef LastComponent = *path::rbegin(Path.first, Path.second);
  253. EXPECT_EQ(1u, LastComponent.size());
  254. EXPECT_TRUE(path::is_separator(LastComponent[0], Path.second));
  255. }
  256. }
  257. TEST(Support, HomeDirectory) {
  258. std::string expected;
  259. #ifdef _WIN32
  260. if (wchar_t const *path = ::_wgetenv(L"USERPROFILE")) {
  261. auto pathLen = ::wcslen(path);
  262. ArrayRef<char> ref{reinterpret_cast<char const *>(path),
  263. pathLen * sizeof(wchar_t)};
  264. convertUTF16ToUTF8String(ref, expected);
  265. }
  266. #else
  267. if (char const *path = ::getenv("HOME"))
  268. expected = path;
  269. #endif
  270. // Do not try to test it if we don't know what to expect.
  271. // On Windows we use something better than env vars.
  272. if (!expected.empty()) {
  273. SmallString<128> HomeDir;
  274. auto status = path::home_directory(HomeDir);
  275. EXPECT_TRUE(status);
  276. EXPECT_EQ(expected, HomeDir);
  277. }
  278. }
  279. #ifdef LLVM_ON_UNIX
  280. TEST(Support, HomeDirectoryWithNoEnv) {
  281. std::string OriginalStorage;
  282. char const *OriginalEnv = ::getenv("HOME");
  283. if (OriginalEnv) {
  284. // We're going to unset it, so make a copy and save a pointer to the copy
  285. // so that we can reset it at the end of the test.
  286. OriginalStorage = OriginalEnv;
  287. OriginalEnv = OriginalStorage.c_str();
  288. }
  289. // Don't run the test if we have nothing to compare against.
  290. struct passwd *pw = getpwuid(getuid());
  291. if (!pw || !pw->pw_dir) return;
  292. ::unsetenv("HOME");
  293. EXPECT_EQ(nullptr, ::getenv("HOME"));
  294. std::string PwDir = pw->pw_dir;
  295. SmallString<128> HomeDir;
  296. auto status = path::home_directory(HomeDir);
  297. EXPECT_TRUE(status);
  298. EXPECT_EQ(PwDir, HomeDir);
  299. // Now put the environment back to its original state (meaning that if it was
  300. // unset before, we don't reset it).
  301. if (OriginalEnv) ::setenv("HOME", OriginalEnv, 1);
  302. }
  303. #endif
  304. TEST(Support, TempDirectory) {
  305. SmallString<32> TempDir;
  306. path::system_temp_directory(false, TempDir);
  307. EXPECT_TRUE(!TempDir.empty());
  308. TempDir.clear();
  309. path::system_temp_directory(true, TempDir);
  310. EXPECT_TRUE(!TempDir.empty());
  311. }
  312. #ifdef _WIN32
  313. static std::string path2regex(std::string Path) {
  314. size_t Pos = 0;
  315. while ((Pos = Path.find('\\', Pos)) != std::string::npos) {
  316. Path.replace(Pos, 1, "\\\\");
  317. Pos += 2;
  318. }
  319. return Path;
  320. }
  321. /// Helper for running temp dir test in separated process. See below.
  322. #define EXPECT_TEMP_DIR(prepare, expected) \
  323. EXPECT_EXIT( \
  324. { \
  325. prepare; \
  326. SmallString<300> TempDir; \
  327. path::system_temp_directory(true, TempDir); \
  328. raw_os_ostream(std::cerr) << TempDir; \
  329. std::exit(0); \
  330. }, \
  331. ::testing::ExitedWithCode(0), path2regex(expected))
  332. TEST(SupportDeathTest, TempDirectoryOnWindows) {
  333. // In this test we want to check how system_temp_directory responds to
  334. // different values of specific env vars. To prevent corrupting env vars of
  335. // the current process all checks are done in separated processes.
  336. EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"C:\\OtherFolder"), "C:\\OtherFolder");
  337. EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"C:/Unix/Path/Seperators"),
  338. "C:\\Unix\\Path\\Seperators");
  339. EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"Local Path"), ".+\\Local Path$");
  340. EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"F:\\TrailingSep\\"), "F:\\TrailingSep");
  341. EXPECT_TEMP_DIR(
  342. _wputenv_s(L"TMP", L"C:\\2\x03C0r-\x00B5\x00B3\\\x2135\x2080"),
  343. "C:\\2\xCF\x80r-\xC2\xB5\xC2\xB3\\\xE2\x84\xB5\xE2\x82\x80");
  344. // Test $TMP empty, $TEMP set.
  345. EXPECT_TEMP_DIR(
  346. {
  347. _wputenv_s(L"TMP", L"");
  348. _wputenv_s(L"TEMP", L"C:\\Valid\\Path");
  349. },
  350. "C:\\Valid\\Path");
  351. // All related env vars empty
  352. EXPECT_TEMP_DIR(
  353. {
  354. _wputenv_s(L"TMP", L"");
  355. _wputenv_s(L"TEMP", L"");
  356. _wputenv_s(L"USERPROFILE", L"");
  357. },
  358. "C:\\Temp");
  359. // Test evn var / path with 260 chars.
  360. SmallString<270> Expected{"C:\\Temp\\AB\\123456789"};
  361. while (Expected.size() < 260)
  362. Expected.append("\\DirNameWith19Charss");
  363. ASSERT_EQ(260U, Expected.size());
  364. EXPECT_TEMP_DIR(_putenv_s("TMP", Expected.c_str()), Expected.c_str());
  365. }
  366. #endif
  367. class FileSystemTest : public testing::Test {
  368. protected:
  369. /// Unique temporary directory in which all created filesystem entities must
  370. /// be placed. It is removed at the end of each test (must be empty).
  371. SmallString<128> TestDirectory;
  372. SmallString<128> NonExistantFile;
  373. void SetUp() override {
  374. ASSERT_NO_ERROR(
  375. fs::createUniqueDirectory("file-system-test", TestDirectory));
  376. // We don't care about this specific file.
  377. errs() << "Test Directory: " << TestDirectory << '\n';
  378. errs().flush();
  379. NonExistantFile = TestDirectory;
  380. // Even though this value is hardcoded, is a 128-bit GUID, so we should be
  381. // guaranteed that this file will never exist.
  382. sys::path::append(NonExistantFile, "1B28B495C16344CB9822E588CD4C3EF0");
  383. }
  384. void TearDown() override { ASSERT_NO_ERROR(fs::remove(TestDirectory.str())); }
  385. };
  386. TEST_F(FileSystemTest, Unique) {
  387. // Create a temp file.
  388. int FileDescriptor;
  389. SmallString<64> TempPath;
  390. ASSERT_NO_ERROR(
  391. fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
  392. // The same file should return an identical unique id.
  393. fs::UniqueID F1, F2;
  394. ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F1));
  395. ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F2));
  396. ASSERT_EQ(F1, F2);
  397. // Different files should return different unique ids.
  398. int FileDescriptor2;
  399. SmallString<64> TempPath2;
  400. ASSERT_NO_ERROR(
  401. fs::createTemporaryFile("prefix", "temp", FileDescriptor2, TempPath2));
  402. fs::UniqueID D;
  403. ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D));
  404. ASSERT_NE(D, F1);
  405. ::close(FileDescriptor2);
  406. ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
  407. // Two paths representing the same file on disk should still provide the
  408. // same unique id. We can test this by making a hard link.
  409. ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
  410. fs::UniqueID D2;
  411. ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D2));
  412. ASSERT_EQ(D2, F1);
  413. ::close(FileDescriptor);
  414. SmallString<128> Dir1;
  415. ASSERT_NO_ERROR(
  416. fs::createUniqueDirectory("dir1", Dir1));
  417. ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F1));
  418. ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F2));
  419. ASSERT_EQ(F1, F2);
  420. SmallString<128> Dir2;
  421. ASSERT_NO_ERROR(
  422. fs::createUniqueDirectory("dir2", Dir2));
  423. ASSERT_NO_ERROR(fs::getUniqueID(Dir2.c_str(), F2));
  424. ASSERT_NE(F1, F2);
  425. ASSERT_NO_ERROR(fs::remove(Dir1));
  426. ASSERT_NO_ERROR(fs::remove(Dir2));
  427. ASSERT_NO_ERROR(fs::remove(TempPath2));
  428. ASSERT_NO_ERROR(fs::remove(TempPath));
  429. }
  430. TEST_F(FileSystemTest, RealPath) {
  431. ASSERT_NO_ERROR(
  432. fs::create_directories(Twine(TestDirectory) + "/test1/test2/test3"));
  433. ASSERT_TRUE(fs::exists(Twine(TestDirectory) + "/test1/test2/test3"));
  434. SmallString<64> RealBase;
  435. SmallString<64> Expected;
  436. SmallString<64> Actual;
  437. // TestDirectory itself might be under a symlink or have been specified with
  438. // a different case than the existing temp directory. In such cases real_path
  439. // on the concatenated path will differ in the TestDirectory portion from
  440. // how we specified it. Make sure to compare against the real_path of the
  441. // TestDirectory, and not just the value of TestDirectory.
  442. ASSERT_NO_ERROR(fs::real_path(TestDirectory, RealBase));
  443. path::native(Twine(RealBase) + "/test1/test2", Expected);
  444. ASSERT_NO_ERROR(fs::real_path(
  445. Twine(TestDirectory) + "/././test1/../test1/test2/./test3/..", Actual));
  446. EXPECT_EQ(Expected, Actual);
  447. SmallString<64> HomeDir;
  448. bool Result = llvm::sys::path::home_directory(HomeDir);
  449. if (Result) {
  450. ASSERT_NO_ERROR(fs::real_path(HomeDir, Expected));
  451. ASSERT_NO_ERROR(fs::real_path("~", Actual, true));
  452. EXPECT_EQ(Expected, Actual);
  453. ASSERT_NO_ERROR(fs::real_path("~/", Actual, true));
  454. EXPECT_EQ(Expected, Actual);
  455. }
  456. ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/test1"));
  457. }
  458. #ifdef LLVM_ON_UNIX
  459. TEST_F(FileSystemTest, RealPathNoReadPerm) {
  460. SmallString<64> Expanded;
  461. ASSERT_NO_ERROR(
  462. fs::create_directories(Twine(TestDirectory) + "/noreadperm"));
  463. ASSERT_TRUE(fs::exists(Twine(TestDirectory) + "/noreadperm"));
  464. fs::setPermissions(Twine(TestDirectory) + "/noreadperm", fs::no_perms);
  465. fs::setPermissions(Twine(TestDirectory) + "/noreadperm", fs::all_exe);
  466. ASSERT_NO_ERROR(fs::real_path(Twine(TestDirectory) + "/noreadperm", Expanded,
  467. false));
  468. ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/noreadperm"));
  469. }
  470. #endif
  471. TEST_F(FileSystemTest, TempFileKeepDiscard) {
  472. // We can keep then discard.
  473. auto TempFileOrError = fs::TempFile::create(TestDirectory + "/test-%%%%");
  474. ASSERT_TRUE((bool)TempFileOrError);
  475. fs::TempFile File = std::move(*TempFileOrError);
  476. ASSERT_FALSE((bool)File.keep(TestDirectory + "/keep"));
  477. ASSERT_FALSE((bool)File.discard());
  478. ASSERT_TRUE(fs::exists(TestDirectory + "/keep"));
  479. ASSERT_NO_ERROR(fs::remove(TestDirectory + "/keep"));
  480. }
  481. TEST_F(FileSystemTest, TempFileDiscardDiscard) {
  482. // We can discard twice.
  483. auto TempFileOrError = fs::TempFile::create(TestDirectory + "/test-%%%%");
  484. ASSERT_TRUE((bool)TempFileOrError);
  485. fs::TempFile File = std::move(*TempFileOrError);
  486. ASSERT_FALSE((bool)File.discard());
  487. ASSERT_FALSE((bool)File.discard());
  488. ASSERT_FALSE(fs::exists(TestDirectory + "/keep"));
  489. }
  490. TEST_F(FileSystemTest, TempFiles) {
  491. // Create a temp file.
  492. int FileDescriptor;
  493. SmallString<64> TempPath;
  494. ASSERT_NO_ERROR(
  495. fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
  496. // Make sure it exists.
  497. ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
  498. // Create another temp tile.
  499. int FD2;
  500. SmallString<64> TempPath2;
  501. ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD2, TempPath2));
  502. ASSERT_TRUE(TempPath2.endswith(".temp"));
  503. ASSERT_NE(TempPath.str(), TempPath2.str());
  504. fs::file_status A, B;
  505. ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
  506. ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
  507. EXPECT_FALSE(fs::equivalent(A, B));
  508. ::close(FD2);
  509. // Remove Temp2.
  510. ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
  511. ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
  512. ASSERT_EQ(fs::remove(Twine(TempPath2), false),
  513. errc::no_such_file_or_directory);
  514. std::error_code EC = fs::status(TempPath2.c_str(), B);
  515. EXPECT_EQ(EC, errc::no_such_file_or_directory);
  516. EXPECT_EQ(B.type(), fs::file_type::file_not_found);
  517. // Make sure Temp2 doesn't exist.
  518. ASSERT_EQ(fs::access(Twine(TempPath2), sys::fs::AccessMode::Exist),
  519. errc::no_such_file_or_directory);
  520. SmallString<64> TempPath3;
  521. ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "", TempPath3));
  522. ASSERT_FALSE(TempPath3.endswith("."));
  523. FileRemover Cleanup3(TempPath3);
  524. // Create a hard link to Temp1.
  525. ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
  526. bool equal;
  527. ASSERT_NO_ERROR(fs::equivalent(Twine(TempPath), Twine(TempPath2), equal));
  528. EXPECT_TRUE(equal);
  529. ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
  530. ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
  531. EXPECT_TRUE(fs::equivalent(A, B));
  532. // Remove Temp1.
  533. ::close(FileDescriptor);
  534. ASSERT_NO_ERROR(fs::remove(Twine(TempPath)));
  535. // Remove the hard link.
  536. ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
  537. // Make sure Temp1 doesn't exist.
  538. ASSERT_EQ(fs::access(Twine(TempPath), sys::fs::AccessMode::Exist),
  539. errc::no_such_file_or_directory);
  540. #ifdef _WIN32
  541. // Path name > 260 chars should get an error.
  542. const char *Path270 =
  543. "abcdefghijklmnopqrstuvwxyz9abcdefghijklmnopqrstuvwxyz8"
  544. "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
  545. "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
  546. "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
  547. "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
  548. EXPECT_EQ(fs::createUniqueFile(Path270, FileDescriptor, TempPath),
  549. errc::invalid_argument);
  550. // Relative path < 247 chars, no problem.
  551. const char *Path216 =
  552. "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
  553. "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
  554. "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
  555. "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
  556. ASSERT_NO_ERROR(fs::createTemporaryFile(Path216, "", TempPath));
  557. ASSERT_NO_ERROR(fs::remove(Twine(TempPath)));
  558. #endif
  559. }
  560. TEST_F(FileSystemTest, TempFileCollisions) {
  561. SmallString<128> TestDirectory;
  562. ASSERT_NO_ERROR(
  563. fs::createUniqueDirectory("CreateUniqueFileTest", TestDirectory));
  564. FileRemover Cleanup(TestDirectory);
  565. SmallString<128> Model = TestDirectory;
  566. path::append(Model, "%.tmp");
  567. SmallString<128> Path;
  568. std::vector<fs::TempFile> TempFiles;
  569. auto TryCreateTempFile = [&]() {
  570. Expected<fs::TempFile> T = fs::TempFile::create(Model);
  571. if (T) {
  572. TempFiles.push_back(std::move(*T));
  573. return true;
  574. } else {
  575. logAllUnhandledErrors(T.takeError(), errs(),
  576. "Failed to create temporary file: ");
  577. return false;
  578. }
  579. };
  580. // We should be able to create exactly 16 temporary files.
  581. for (int i = 0; i < 16; ++i)
  582. EXPECT_TRUE(TryCreateTempFile());
  583. EXPECT_FALSE(TryCreateTempFile());
  584. for (fs::TempFile &T : TempFiles)
  585. cantFail(T.discard());
  586. }
  587. TEST_F(FileSystemTest, CreateDir) {
  588. ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
  589. ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
  590. ASSERT_EQ(fs::create_directory(Twine(TestDirectory) + "foo", false),
  591. errc::file_exists);
  592. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "foo"));
  593. #ifdef LLVM_ON_UNIX
  594. // Set a 0000 umask so that we can test our directory permissions.
  595. mode_t OldUmask = ::umask(0000);
  596. fs::file_status Status;
  597. ASSERT_NO_ERROR(
  598. fs::create_directory(Twine(TestDirectory) + "baz500", false,
  599. fs::perms::owner_read | fs::perms::owner_exe));
  600. ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz500", Status));
  601. ASSERT_EQ(Status.permissions() & fs::perms::all_all,
  602. fs::perms::owner_read | fs::perms::owner_exe);
  603. ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "baz777", false,
  604. fs::perms::all_all));
  605. ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz777", Status));
  606. ASSERT_EQ(Status.permissions() & fs::perms::all_all, fs::perms::all_all);
  607. // Restore umask to be safe.
  608. ::umask(OldUmask);
  609. #endif
  610. #ifdef _WIN32
  611. // Prove that create_directories() can handle a pathname > 248 characters,
  612. // which is the documented limit for CreateDirectory().
  613. // (248 is MAX_PATH subtracting room for an 8.3 filename.)
  614. // Generate a directory path guaranteed to fall into that range.
  615. size_t TmpLen = TestDirectory.size();
  616. const char *OneDir = "\\123456789";
  617. size_t OneDirLen = strlen(OneDir);
  618. ASSERT_LT(OneDirLen, 12U);
  619. size_t NLevels = ((248 - TmpLen) / OneDirLen) + 1;
  620. SmallString<260> LongDir(TestDirectory);
  621. for (size_t I = 0; I < NLevels; ++I)
  622. LongDir.append(OneDir);
  623. ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir)));
  624. ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir)));
  625. ASSERT_EQ(fs::create_directories(Twine(LongDir), false),
  626. errc::file_exists);
  627. // Tidy up, "recursively" removing the directories.
  628. StringRef ThisDir(LongDir);
  629. for (size_t J = 0; J < NLevels; ++J) {
  630. ASSERT_NO_ERROR(fs::remove(ThisDir));
  631. ThisDir = path::parent_path(ThisDir);
  632. }
  633. // Also verify that paths with Unix separators are handled correctly.
  634. std::string LongPathWithUnixSeparators(TestDirectory.str());
  635. // Add at least one subdirectory to TestDirectory, and replace slashes with
  636. // backslashes
  637. do {
  638. LongPathWithUnixSeparators.append("/DirNameWith19Charss");
  639. } while (LongPathWithUnixSeparators.size() < 260);
  640. std::replace(LongPathWithUnixSeparators.begin(),
  641. LongPathWithUnixSeparators.end(),
  642. '\\', '/');
  643. ASSERT_NO_ERROR(fs::create_directories(Twine(LongPathWithUnixSeparators)));
  644. // cleanup
  645. ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) +
  646. "/DirNameWith19Charss"));
  647. // Similarly for a relative pathname. Need to set the current directory to
  648. // TestDirectory so that the one we create ends up in the right place.
  649. char PreviousDir[260];
  650. size_t PreviousDirLen = ::GetCurrentDirectoryA(260, PreviousDir);
  651. ASSERT_GT(PreviousDirLen, 0U);
  652. ASSERT_LT(PreviousDirLen, 260U);
  653. ASSERT_NE(::SetCurrentDirectoryA(TestDirectory.c_str()), 0);
  654. LongDir.clear();
  655. // Generate a relative directory name with absolute length > 248.
  656. size_t LongDirLen = 249 - TestDirectory.size();
  657. LongDir.assign(LongDirLen, 'a');
  658. ASSERT_NO_ERROR(fs::create_directory(Twine(LongDir)));
  659. // While we're here, prove that .. and . handling works in these long paths.
  660. const char *DotDotDirs = "\\..\\.\\b";
  661. LongDir.append(DotDotDirs);
  662. ASSERT_NO_ERROR(fs::create_directory("b"));
  663. ASSERT_EQ(fs::create_directory(Twine(LongDir), false), errc::file_exists);
  664. // And clean up.
  665. ASSERT_NO_ERROR(fs::remove("b"));
  666. ASSERT_NO_ERROR(fs::remove(
  667. Twine(LongDir.substr(0, LongDir.size() - strlen(DotDotDirs)))));
  668. ASSERT_NE(::SetCurrentDirectoryA(PreviousDir), 0);
  669. #endif
  670. }
  671. TEST_F(FileSystemTest, DirectoryIteration) {
  672. std::error_code ec;
  673. for (fs::directory_iterator i(".", ec), e; i != e; i.increment(ec))
  674. ASSERT_NO_ERROR(ec);
  675. // Create a known hierarchy to recurse over.
  676. ASSERT_NO_ERROR(
  677. fs::create_directories(Twine(TestDirectory) + "/recursive/a0/aa1"));
  678. ASSERT_NO_ERROR(
  679. fs::create_directories(Twine(TestDirectory) + "/recursive/a0/ab1"));
  680. ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) +
  681. "/recursive/dontlookhere/da1"));
  682. ASSERT_NO_ERROR(
  683. fs::create_directories(Twine(TestDirectory) + "/recursive/z0/za1"));
  684. ASSERT_NO_ERROR(
  685. fs::create_directories(Twine(TestDirectory) + "/recursive/pop/p1"));
  686. typedef std::vector<std::string> v_t;
  687. v_t visited;
  688. for (fs::recursive_directory_iterator i(Twine(TestDirectory)
  689. + "/recursive", ec), e; i != e; i.increment(ec)){
  690. ASSERT_NO_ERROR(ec);
  691. if (path::filename(i->path()) == "p1") {
  692. i.pop();
  693. // FIXME: recursive_directory_iterator should be more robust.
  694. if (i == e) break;
  695. }
  696. if (path::filename(i->path()) == "dontlookhere")
  697. i.no_push();
  698. visited.push_back(path::filename(i->path()));
  699. }
  700. v_t::const_iterator a0 = find(visited, "a0");
  701. v_t::const_iterator aa1 = find(visited, "aa1");
  702. v_t::const_iterator ab1 = find(visited, "ab1");
  703. v_t::const_iterator dontlookhere = find(visited, "dontlookhere");
  704. v_t::const_iterator da1 = find(visited, "da1");
  705. v_t::const_iterator z0 = find(visited, "z0");
  706. v_t::const_iterator za1 = find(visited, "za1");
  707. v_t::const_iterator pop = find(visited, "pop");
  708. v_t::const_iterator p1 = find(visited, "p1");
  709. // Make sure that each path was visited correctly.
  710. ASSERT_NE(a0, visited.end());
  711. ASSERT_NE(aa1, visited.end());
  712. ASSERT_NE(ab1, visited.end());
  713. ASSERT_NE(dontlookhere, visited.end());
  714. ASSERT_EQ(da1, visited.end()); // Not visited.
  715. ASSERT_NE(z0, visited.end());
  716. ASSERT_NE(za1, visited.end());
  717. ASSERT_NE(pop, visited.end());
  718. ASSERT_EQ(p1, visited.end()); // Not visited.
  719. // Make sure that parents were visited before children. No other ordering
  720. // guarantees can be made across siblings.
  721. ASSERT_LT(a0, aa1);
  722. ASSERT_LT(a0, ab1);
  723. ASSERT_LT(z0, za1);
  724. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/aa1"));
  725. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/ab1"));
  726. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0"));
  727. ASSERT_NO_ERROR(
  728. fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere/da1"));
  729. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere"));
  730. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop/p1"));
  731. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop"));
  732. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0/za1"));
  733. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0"));
  734. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive"));
  735. // Test recursive_directory_iterator level()
  736. ASSERT_NO_ERROR(
  737. fs::create_directories(Twine(TestDirectory) + "/reclevel/a/b/c"));
  738. fs::recursive_directory_iterator I(Twine(TestDirectory) + "/reclevel", ec), E;
  739. for (int l = 0; I != E; I.increment(ec), ++l) {
  740. ASSERT_NO_ERROR(ec);
  741. EXPECT_EQ(I.level(), l);
  742. }
  743. EXPECT_EQ(I, E);
  744. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a/b/c"));
  745. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a/b"));
  746. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a"));
  747. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel"));
  748. }
  749. #ifdef LLVM_ON_UNIX
  750. TEST_F(FileSystemTest, BrokenSymlinkDirectoryIteration) {
  751. // Create a known hierarchy to recurse over.
  752. ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) + "/symlink"));
  753. ASSERT_NO_ERROR(
  754. fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/a"));
  755. ASSERT_NO_ERROR(
  756. fs::create_directories(Twine(TestDirectory) + "/symlink/b/bb"));
  757. ASSERT_NO_ERROR(
  758. fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/b/ba"));
  759. ASSERT_NO_ERROR(
  760. fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/b/bc"));
  761. ASSERT_NO_ERROR(
  762. fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/c"));
  763. ASSERT_NO_ERROR(
  764. fs::create_directories(Twine(TestDirectory) + "/symlink/d/dd/ddd"));
  765. ASSERT_NO_ERROR(fs::create_link(Twine(TestDirectory) + "/symlink/d/dd",
  766. Twine(TestDirectory) + "/symlink/d/da"));
  767. ASSERT_NO_ERROR(
  768. fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/e"));
  769. typedef std::vector<std::string> v_t;
  770. v_t VisitedNonBrokenSymlinks;
  771. v_t VisitedBrokenSymlinks;
  772. std::error_code ec;
  773. using testing::UnorderedElementsAre;
  774. using testing::UnorderedElementsAreArray;
  775. // Broken symbol links are expected to throw an error.
  776. for (fs::directory_iterator i(Twine(TestDirectory) + "/symlink", ec), e;
  777. i != e; i.increment(ec)) {
  778. ASSERT_NO_ERROR(ec);
  779. if (i->status().getError() ==
  780. std::make_error_code(std::errc::no_such_file_or_directory)) {
  781. VisitedBrokenSymlinks.push_back(path::filename(i->path()));
  782. continue;
  783. }
  784. VisitedNonBrokenSymlinks.push_back(path::filename(i->path()));
  785. }
  786. EXPECT_THAT(VisitedNonBrokenSymlinks, UnorderedElementsAre("b", "d"));
  787. VisitedNonBrokenSymlinks.clear();
  788. EXPECT_THAT(VisitedBrokenSymlinks, UnorderedElementsAre("a", "c", "e"));
  789. VisitedBrokenSymlinks.clear();
  790. // Broken symbol links are expected to throw an error.
  791. for (fs::recursive_directory_iterator i(
  792. Twine(TestDirectory) + "/symlink", ec), e; i != e; i.increment(ec)) {
  793. ASSERT_NO_ERROR(ec);
  794. if (i->status().getError() ==
  795. std::make_error_code(std::errc::no_such_file_or_directory)) {
  796. VisitedBrokenSymlinks.push_back(path::filename(i->path()));
  797. continue;
  798. }
  799. VisitedNonBrokenSymlinks.push_back(path::filename(i->path()));
  800. }
  801. EXPECT_THAT(VisitedNonBrokenSymlinks,
  802. UnorderedElementsAre("b", "bb", "d", "da", "dd", "ddd", "ddd"));
  803. VisitedNonBrokenSymlinks.clear();
  804. EXPECT_THAT(VisitedBrokenSymlinks,
  805. UnorderedElementsAre("a", "ba", "bc", "c", "e"));
  806. VisitedBrokenSymlinks.clear();
  807. for (fs::recursive_directory_iterator i(
  808. Twine(TestDirectory) + "/symlink", ec, /*follow_symlinks=*/false), e;
  809. i != e; i.increment(ec)) {
  810. ASSERT_NO_ERROR(ec);
  811. if (i->status().getError() ==
  812. std::make_error_code(std::errc::no_such_file_or_directory)) {
  813. VisitedBrokenSymlinks.push_back(path::filename(i->path()));
  814. continue;
  815. }
  816. VisitedNonBrokenSymlinks.push_back(path::filename(i->path()));
  817. }
  818. EXPECT_THAT(VisitedNonBrokenSymlinks,
  819. UnorderedElementsAreArray({"a", "b", "ba", "bb", "bc", "c", "d",
  820. "da", "dd", "ddd", "e"}));
  821. VisitedNonBrokenSymlinks.clear();
  822. EXPECT_THAT(VisitedBrokenSymlinks, UnorderedElementsAre());
  823. VisitedBrokenSymlinks.clear();
  824. ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/symlink"));
  825. }
  826. #endif
  827. TEST_F(FileSystemTest, Remove) {
  828. SmallString<64> BaseDir;
  829. SmallString<64> Paths[4];
  830. int fds[4];
  831. ASSERT_NO_ERROR(fs::createUniqueDirectory("fs_remove", BaseDir));
  832. ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir) + "/foo/bar/baz"));
  833. ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir) + "/foo/bar/buzz"));
  834. ASSERT_NO_ERROR(fs::createUniqueFile(
  835. Twine(BaseDir) + "/foo/bar/baz/%%%%%%.tmp", fds[0], Paths[0]));
  836. ASSERT_NO_ERROR(fs::createUniqueFile(
  837. Twine(BaseDir) + "/foo/bar/baz/%%%%%%.tmp", fds[1], Paths[1]));
  838. ASSERT_NO_ERROR(fs::createUniqueFile(
  839. Twine(BaseDir) + "/foo/bar/buzz/%%%%%%.tmp", fds[2], Paths[2]));
  840. ASSERT_NO_ERROR(fs::createUniqueFile(
  841. Twine(BaseDir) + "/foo/bar/buzz/%%%%%%.tmp", fds[3], Paths[3]));
  842. for (int fd : fds)
  843. ::close(fd);
  844. EXPECT_TRUE(fs::exists(Twine(BaseDir) + "/foo/bar/baz"));
  845. EXPECT_TRUE(fs::exists(Twine(BaseDir) + "/foo/bar/buzz"));
  846. EXPECT_TRUE(fs::exists(Paths[0]));
  847. EXPECT_TRUE(fs::exists(Paths[1]));
  848. EXPECT_TRUE(fs::exists(Paths[2]));
  849. EXPECT_TRUE(fs::exists(Paths[3]));
  850. ASSERT_NO_ERROR(fs::remove_directories("D:/footest"));
  851. ASSERT_NO_ERROR(fs::remove_directories(BaseDir));
  852. ASSERT_FALSE(fs::exists(BaseDir));
  853. }
  854. #ifdef _WIN32
  855. TEST_F(FileSystemTest, CarriageReturn) {
  856. SmallString<128> FilePathname(TestDirectory);
  857. std::error_code EC;
  858. path::append(FilePathname, "test");
  859. {
  860. raw_fd_ostream File(FilePathname, EC, sys::fs::F_Text);
  861. ASSERT_NO_ERROR(EC);
  862. File << '\n';
  863. }
  864. {
  865. auto Buf = MemoryBuffer::getFile(FilePathname.str());
  866. EXPECT_TRUE((bool)Buf);
  867. EXPECT_EQ(Buf.get()->getBuffer(), "\r\n");
  868. }
  869. {
  870. raw_fd_ostream File(FilePathname, EC, sys::fs::F_None);
  871. ASSERT_NO_ERROR(EC);
  872. File << '\n';
  873. }
  874. {
  875. auto Buf = MemoryBuffer::getFile(FilePathname.str());
  876. EXPECT_TRUE((bool)Buf);
  877. EXPECT_EQ(Buf.get()->getBuffer(), "\n");
  878. }
  879. ASSERT_NO_ERROR(fs::remove(Twine(FilePathname)));
  880. }
  881. #endif
  882. TEST_F(FileSystemTest, Resize) {
  883. int FD;
  884. SmallString<64> TempPath;
  885. ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
  886. ASSERT_NO_ERROR(fs::resize_file(FD, 123));
  887. fs::file_status Status;
  888. ASSERT_NO_ERROR(fs::status(FD, Status));
  889. ASSERT_EQ(Status.getSize(), 123U);
  890. ::close(FD);
  891. ASSERT_NO_ERROR(fs::remove(TempPath));
  892. }
  893. TEST_F(FileSystemTest, MD5) {
  894. int FD;
  895. SmallString<64> TempPath;
  896. ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
  897. StringRef Data("abcdefghijklmnopqrstuvwxyz");
  898. ASSERT_EQ(write(FD, Data.data(), Data.size()), static_cast<ssize_t>(Data.size()));
  899. lseek(FD, 0, SEEK_SET);
  900. auto Hash = fs::md5_contents(FD);
  901. ::close(FD);
  902. ASSERT_NO_ERROR(Hash.getError());
  903. EXPECT_STREQ("c3fcd3d76192e4007dfb496cca67e13b", Hash->digest().c_str());
  904. }
  905. TEST_F(FileSystemTest, FileMapping) {
  906. // Create a temp file.
  907. int FileDescriptor;
  908. SmallString<64> TempPath;
  909. ASSERT_NO_ERROR(
  910. fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
  911. unsigned Size = 4096;
  912. ASSERT_NO_ERROR(fs::resize_file(FileDescriptor, Size));
  913. // Map in temp file and add some content
  914. std::error_code EC;
  915. StringRef Val("hello there");
  916. {
  917. fs::mapped_file_region mfr(FileDescriptor,
  918. fs::mapped_file_region::readwrite, Size, 0, EC);
  919. ASSERT_NO_ERROR(EC);
  920. std::copy(Val.begin(), Val.end(), mfr.data());
  921. // Explicitly add a 0.
  922. mfr.data()[Val.size()] = 0;
  923. // Unmap temp file
  924. }
  925. ASSERT_EQ(close(FileDescriptor), 0);
  926. // Map it back in read-only
  927. {
  928. int FD;
  929. EC = fs::openFileForRead(Twine(TempPath), FD);
  930. ASSERT_NO_ERROR(EC);
  931. fs::mapped_file_region mfr(FD, fs::mapped_file_region::readonly, Size, 0, EC);
  932. ASSERT_NO_ERROR(EC);
  933. // Verify content
  934. EXPECT_EQ(StringRef(mfr.const_data()), Val);
  935. // Unmap temp file
  936. fs::mapped_file_region m(FD, fs::mapped_file_region::readonly, Size, 0, EC);
  937. ASSERT_NO_ERROR(EC);
  938. ASSERT_EQ(close(FD), 0);
  939. }
  940. ASSERT_NO_ERROR(fs::remove(TempPath));
  941. }
  942. TEST(Support, NormalizePath) {
  943. using TestTuple = std::tuple<const char *, const char *, const char *>;
  944. std::vector<TestTuple> Tests;
  945. Tests.emplace_back("a", "a", "a");
  946. Tests.emplace_back("a/b", "a\\b", "a/b");
  947. Tests.emplace_back("a\\b", "a\\b", "a/b");
  948. Tests.emplace_back("a\\\\b", "a\\\\b", "a\\\\b");
  949. Tests.emplace_back("\\a", "\\a", "/a");
  950. Tests.emplace_back("a\\", "a\\", "a/");
  951. for (auto &T : Tests) {
  952. SmallString<64> Win(std::get<0>(T));
  953. SmallString<64> Posix(Win);
  954. path::native(Win, path::Style::windows);
  955. path::native(Posix, path::Style::posix);
  956. EXPECT_EQ(std::get<1>(T), Win);
  957. EXPECT_EQ(std::get<2>(T), Posix);
  958. }
  959. #if defined(_WIN32)
  960. SmallString<64> PathHome;
  961. path::home_directory(PathHome);
  962. const char *Path7a = "~/aaa";
  963. SmallString<64> Path7(Path7a);
  964. path::native(Path7);
  965. EXPECT_TRUE(Path7.endswith("\\aaa"));
  966. EXPECT_TRUE(Path7.startswith(PathHome));
  967. EXPECT_EQ(Path7.size(), PathHome.size() + strlen(Path7a + 1));
  968. const char *Path8a = "~";
  969. SmallString<64> Path8(Path8a);
  970. path::native(Path8);
  971. EXPECT_EQ(Path8, PathHome);
  972. const char *Path9a = "~aaa";
  973. SmallString<64> Path9(Path9a);
  974. path::native(Path9);
  975. EXPECT_EQ(Path9, "~aaa");
  976. const char *Path10a = "aaa/~/b";
  977. SmallString<64> Path10(Path10a);
  978. path::native(Path10);
  979. EXPECT_EQ(Path10, "aaa\\~\\b");
  980. #endif
  981. }
  982. TEST(Support, RemoveLeadingDotSlash) {
  983. StringRef Path1("././/foolz/wat");
  984. StringRef Path2("./////");
  985. Path1 = path::remove_leading_dotslash(Path1);
  986. EXPECT_EQ(Path1, "foolz/wat");
  987. Path2 = path::remove_leading_dotslash(Path2);
  988. EXPECT_EQ(Path2, "");
  989. }
  990. static std::string remove_dots(StringRef path, bool remove_dot_dot,
  991. path::Style style) {
  992. SmallString<256> buffer(path);
  993. path::remove_dots(buffer, remove_dot_dot, style);
  994. return buffer.str();
  995. }
  996. TEST(Support, RemoveDots) {
  997. EXPECT_EQ("foolz\\wat",
  998. remove_dots(".\\.\\\\foolz\\wat", false, path::Style::windows));
  999. EXPECT_EQ("", remove_dots(".\\\\\\\\\\", false, path::Style::windows));
  1000. EXPECT_EQ("a\\..\\b\\c",
  1001. remove_dots(".\\a\\..\\b\\c", false, path::Style::windows));
  1002. EXPECT_EQ("b\\c", remove_dots(".\\a\\..\\b\\c", true, path::Style::windows));
  1003. EXPECT_EQ("c", remove_dots(".\\.\\c", true, path::Style::windows));
  1004. EXPECT_EQ("..\\a\\c",
  1005. remove_dots("..\\a\\b\\..\\c", true, path::Style::windows));
  1006. EXPECT_EQ("..\\..\\a\\c",
  1007. remove_dots("..\\..\\a\\b\\..\\c", true, path::Style::windows));
  1008. SmallString<64> Path1(".\\.\\c");
  1009. EXPECT_TRUE(path::remove_dots(Path1, true, path::Style::windows));
  1010. EXPECT_EQ("c", Path1);
  1011. EXPECT_EQ("foolz/wat",
  1012. remove_dots("././/foolz/wat", false, path::Style::posix));
  1013. EXPECT_EQ("", remove_dots("./////", false, path::Style::posix));
  1014. EXPECT_EQ("a/../b/c", remove_dots("./a/../b/c", false, path::Style::posix));
  1015. EXPECT_EQ("b/c", remove_dots("./a/../b/c", true, path::Style::posix));
  1016. EXPECT_EQ("c", remove_dots("././c", true, path::Style::posix));
  1017. EXPECT_EQ("../a/c", remove_dots("../a/b/../c", true, path::Style::posix));
  1018. EXPECT_EQ("../../a/c",
  1019. remove_dots("../../a/b/../c", true, path::Style::posix));
  1020. EXPECT_EQ("/a/c", remove_dots("/../../a/c", true, path::Style::posix));
  1021. EXPECT_EQ("/a/c",
  1022. remove_dots("/../a/b//../././/c", true, path::Style::posix));
  1023. SmallString<64> Path2("././c");
  1024. EXPECT_TRUE(path::remove_dots(Path2, true, path::Style::posix));
  1025. EXPECT_EQ("c", Path2);
  1026. }
  1027. TEST(Support, ReplacePathPrefix) {
  1028. SmallString<64> Path1("/foo");
  1029. SmallString<64> Path2("/old/foo");
  1030. SmallString<64> OldPrefix("/old");
  1031. SmallString<64> NewPrefix("/new");
  1032. SmallString<64> NewPrefix2("/longernew");
  1033. SmallString<64> EmptyPrefix("");
  1034. SmallString<64> Path = Path1;
  1035. path::replace_path_prefix(Path, OldPrefix, NewPrefix);
  1036. EXPECT_EQ(Path, "/foo");
  1037. Path = Path2;
  1038. path::replace_path_prefix(Path, OldPrefix, NewPrefix);
  1039. EXPECT_EQ(Path, "/new/foo");
  1040. Path = Path2;
  1041. path::replace_path_prefix(Path, OldPrefix, NewPrefix2);
  1042. EXPECT_EQ(Path, "/longernew/foo");
  1043. Path = Path1;
  1044. path::replace_path_prefix(Path, EmptyPrefix, NewPrefix);
  1045. EXPECT_EQ(Path, "/new/foo");
  1046. Path = Path2;
  1047. path::replace_path_prefix(Path, OldPrefix, EmptyPrefix);
  1048. EXPECT_EQ(Path, "/foo");
  1049. }
  1050. TEST_F(FileSystemTest, OpenFileForRead) {
  1051. // Create a temp file.
  1052. int FileDescriptor;
  1053. SmallString<64> TempPath;
  1054. ASSERT_NO_ERROR(
  1055. fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
  1056. FileRemover Cleanup(TempPath);
  1057. // Make sure it exists.
  1058. ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
  1059. // Open the file for read
  1060. int FileDescriptor2;
  1061. SmallString<64> ResultPath;
  1062. ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath), FileDescriptor2,
  1063. fs::OF_None, &ResultPath))
  1064. // If we succeeded, check that the paths are the same (modulo case):
  1065. if (!ResultPath.empty()) {
  1066. // The paths returned by createTemporaryFile and getPathFromOpenFD
  1067. // should reference the same file on disk.
  1068. fs::UniqueID D1, D2;
  1069. ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), D1));
  1070. ASSERT_NO_ERROR(fs::getUniqueID(Twine(ResultPath), D2));
  1071. ASSERT_EQ(D1, D2);
  1072. }
  1073. ::close(FileDescriptor);
  1074. ::close(FileDescriptor2);
  1075. #ifdef _WIN32
  1076. // Since Windows Vista, file access time is not updated by default.
  1077. // This is instead updated manually by openFileForRead.
  1078. // https://blogs.technet.microsoft.com/filecab/2006/11/07/disabling-last-access-time-in-windows-vista-to-improve-ntfs-performance/
  1079. // This part of the unit test is Windows specific as the updating of
  1080. // access times can be disabled on Linux using /etc/fstab.
  1081. // Set access time to UNIX epoch.
  1082. ASSERT_NO_ERROR(sys::fs::openFileForWrite(Twine(TempPath), FileDescriptor,
  1083. fs::CD_OpenExisting));
  1084. TimePoint<> Epoch(std::chrono::milliseconds(0));
  1085. ASSERT_NO_ERROR(fs::setLastAccessAndModificationTime(FileDescriptor, Epoch));
  1086. ::close(FileDescriptor);
  1087. // Open the file and ensure access time is updated, when forced.
  1088. ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath), FileDescriptor,
  1089. fs::OF_UpdateAtime, &ResultPath));
  1090. sys::fs::file_status Status;
  1091. ASSERT_NO_ERROR(sys::fs::status(FileDescriptor, Status));
  1092. auto FileAccessTime = Status.getLastAccessedTime();
  1093. ASSERT_NE(Epoch, FileAccessTime);
  1094. ::close(FileDescriptor);
  1095. // Ideally this test would include a case when ATime is not forced to update,
  1096. // however the expected behaviour will differ depending on the configuration
  1097. // of the Windows file system.
  1098. #endif
  1099. }
  1100. static void createFileWithData(const Twine &Path, bool ShouldExistBefore,
  1101. fs::CreationDisposition Disp, StringRef Data) {
  1102. int FD;
  1103. ASSERT_EQ(ShouldExistBefore, fs::exists(Path));
  1104. ASSERT_NO_ERROR(fs::openFileForWrite(Path, FD, Disp));
  1105. FileDescriptorCloser Closer(FD);
  1106. ASSERT_TRUE(fs::exists(Path));
  1107. ASSERT_EQ(Data.size(), (size_t)write(FD, Data.data(), Data.size()));
  1108. }
  1109. static void verifyFileContents(const Twine &Path, StringRef Contents) {
  1110. auto Buffer = MemoryBuffer::getFile(Path);
  1111. ASSERT_TRUE((bool)Buffer);
  1112. StringRef Data = Buffer.get()->getBuffer();
  1113. ASSERT_EQ(Data, Contents);
  1114. }
  1115. TEST_F(FileSystemTest, CreateNew) {
  1116. int FD;
  1117. Optional<FileDescriptorCloser> Closer;
  1118. // Succeeds if the file does not exist.
  1119. ASSERT_FALSE(fs::exists(NonExistantFile));
  1120. ASSERT_NO_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateNew));
  1121. ASSERT_TRUE(fs::exists(NonExistantFile));
  1122. FileRemover Cleanup(NonExistantFile);
  1123. Closer.emplace(FD);
  1124. // And creates a file of size 0.
  1125. sys::fs::file_status Status;
  1126. ASSERT_NO_ERROR(sys::fs::status(FD, Status));
  1127. EXPECT_EQ(0ULL, Status.getSize());
  1128. // Close this first, before trying to re-open the file.
  1129. Closer.reset();
  1130. // But fails if the file does exist.
  1131. ASSERT_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateNew));
  1132. }
  1133. TEST_F(FileSystemTest, CreateAlways) {
  1134. int FD;
  1135. Optional<FileDescriptorCloser> Closer;
  1136. // Succeeds if the file does not exist.
  1137. ASSERT_FALSE(fs::exists(NonExistantFile));
  1138. ASSERT_NO_ERROR(
  1139. fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateAlways));
  1140. Closer.emplace(FD);
  1141. ASSERT_TRUE(fs::exists(NonExistantFile));
  1142. FileRemover Cleanup(NonExistantFile);
  1143. // And creates a file of size 0.
  1144. uint64_t FileSize;
  1145. ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
  1146. ASSERT_EQ(0ULL, FileSize);
  1147. // If we write some data to it re-create it with CreateAlways, it succeeds and
  1148. // truncates to 0 bytes.
  1149. ASSERT_EQ(4, write(FD, "Test", 4));
  1150. Closer.reset();
  1151. ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
  1152. ASSERT_EQ(4ULL, FileSize);
  1153. ASSERT_NO_ERROR(
  1154. fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateAlways));
  1155. Closer.emplace(FD);
  1156. ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
  1157. ASSERT_EQ(0ULL, FileSize);
  1158. }
  1159. TEST_F(FileSystemTest, OpenExisting) {
  1160. int FD;
  1161. // Fails if the file does not exist.
  1162. ASSERT_FALSE(fs::exists(NonExistantFile));
  1163. ASSERT_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_OpenExisting));
  1164. ASSERT_FALSE(fs::exists(NonExistantFile));
  1165. // Make a dummy file now so that we can try again when the file does exist.
  1166. createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
  1167. FileRemover Cleanup(NonExistantFile);
  1168. uint64_t FileSize;
  1169. ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
  1170. ASSERT_EQ(4ULL, FileSize);
  1171. // If we re-create it with different data, it overwrites rather than
  1172. // appending.
  1173. createFileWithData(NonExistantFile, true, fs::CD_OpenExisting, "Buzz");
  1174. verifyFileContents(NonExistantFile, "Buzz");
  1175. }
  1176. TEST_F(FileSystemTest, OpenAlways) {
  1177. // Succeeds if the file does not exist.
  1178. createFileWithData(NonExistantFile, false, fs::CD_OpenAlways, "Fizz");
  1179. FileRemover Cleanup(NonExistantFile);
  1180. uint64_t FileSize;
  1181. ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
  1182. ASSERT_EQ(4ULL, FileSize);
  1183. // Now re-open it and write again, verifying the contents get over-written.
  1184. createFileWithData(NonExistantFile, true, fs::CD_OpenAlways, "Bu");
  1185. verifyFileContents(NonExistantFile, "Buzz");
  1186. }
  1187. TEST_F(FileSystemTest, AppendSetsCorrectFileOffset) {
  1188. fs::CreationDisposition Disps[] = {fs::CD_CreateAlways, fs::CD_OpenAlways,
  1189. fs::CD_OpenExisting};
  1190. // Write some data and re-open it with every possible disposition (this is a
  1191. // hack that shouldn't work, but is left for compatibility. F_Append
  1192. // overrides
  1193. // the specified disposition.
  1194. for (fs::CreationDisposition Disp : Disps) {
  1195. int FD;
  1196. Optional<FileDescriptorCloser> Closer;
  1197. createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
  1198. FileRemover Cleanup(NonExistantFile);
  1199. uint64_t FileSize;
  1200. ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
  1201. ASSERT_EQ(4ULL, FileSize);
  1202. ASSERT_NO_ERROR(
  1203. fs::openFileForWrite(NonExistantFile, FD, Disp, fs::OF_Append));
  1204. Closer.emplace(FD);
  1205. ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
  1206. ASSERT_EQ(4ULL, FileSize);
  1207. ASSERT_EQ(4, write(FD, "Buzz", 4));
  1208. Closer.reset();
  1209. verifyFileContents(NonExistantFile, "FizzBuzz");
  1210. }
  1211. }
  1212. static void verifyRead(int FD, StringRef Data, bool ShouldSucceed) {
  1213. std::vector<char> Buffer;
  1214. Buffer.resize(Data.size());
  1215. int Result = ::read(FD, Buffer.data(), Buffer.size());
  1216. if (ShouldSucceed) {
  1217. ASSERT_EQ((size_t)Result, Data.size());
  1218. ASSERT_EQ(Data, StringRef(Buffer.data(), Buffer.size()));
  1219. } else {
  1220. ASSERT_EQ(-1, Result);
  1221. ASSERT_EQ(EBADF, errno);
  1222. }
  1223. }
  1224. static void verifyWrite(int FD, StringRef Data, bool ShouldSucceed) {
  1225. int Result = ::write(FD, Data.data(), Data.size());
  1226. if (ShouldSucceed)
  1227. ASSERT_EQ((size_t)Result, Data.size());
  1228. else {
  1229. ASSERT_EQ(-1, Result);
  1230. ASSERT_EQ(EBADF, errno);
  1231. }
  1232. }
  1233. TEST_F(FileSystemTest, ReadOnlyFileCantWrite) {
  1234. createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
  1235. FileRemover Cleanup(NonExistantFile);
  1236. int FD;
  1237. ASSERT_NO_ERROR(fs::openFileForRead(NonExistantFile, FD));
  1238. FileDescriptorCloser Closer(FD);
  1239. verifyWrite(FD, "Buzz", false);
  1240. verifyRead(FD, "Fizz", true);
  1241. }
  1242. TEST_F(FileSystemTest, WriteOnlyFileCantRead) {
  1243. createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
  1244. FileRemover Cleanup(NonExistantFile);
  1245. int FD;
  1246. ASSERT_NO_ERROR(
  1247. fs::openFileForWrite(NonExistantFile, FD, fs::CD_OpenExisting));
  1248. FileDescriptorCloser Closer(FD);
  1249. verifyRead(FD, "Fizz", false);
  1250. verifyWrite(FD, "Buzz", true);
  1251. }
  1252. TEST_F(FileSystemTest, ReadWriteFileCanReadOrWrite) {
  1253. createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
  1254. FileRemover Cleanup(NonExistantFile);
  1255. int FD;
  1256. ASSERT_NO_ERROR(fs::openFileForReadWrite(NonExistantFile, FD,
  1257. fs::CD_OpenExisting, fs::OF_None));
  1258. FileDescriptorCloser Closer(FD);
  1259. verifyRead(FD, "Fizz", true);
  1260. verifyWrite(FD, "Buzz", true);
  1261. }
  1262. TEST_F(FileSystemTest, set_current_path) {
  1263. SmallString<128> path;
  1264. ASSERT_NO_ERROR(fs::current_path(path));
  1265. ASSERT_NE(TestDirectory, path);
  1266. struct RestorePath {
  1267. SmallString<128> path;
  1268. RestorePath(const SmallString<128> &path) : path(path) {}
  1269. ~RestorePath() { fs::set_current_path(path); }
  1270. } restore_path(path);
  1271. ASSERT_NO_ERROR(fs::set_current_path(TestDirectory));
  1272. ASSERT_NO_ERROR(fs::current_path(path));
  1273. fs::UniqueID D1, D2;
  1274. ASSERT_NO_ERROR(fs::getUniqueID(TestDirectory, D1));
  1275. ASSERT_NO_ERROR(fs::getUniqueID(path, D2));
  1276. ASSERT_EQ(D1, D2) << "D1: " << TestDirectory << "\nD2: " << path;
  1277. }
  1278. TEST_F(FileSystemTest, permissions) {
  1279. int FD;
  1280. SmallString<64> TempPath;
  1281. ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
  1282. FileRemover Cleanup(TempPath);
  1283. // Make sure it exists.
  1284. ASSERT_TRUE(fs::exists(Twine(TempPath)));
  1285. auto CheckPermissions = [&](fs::perms Expected) {
  1286. ErrorOr<fs::perms> Actual = fs::getPermissions(TempPath);
  1287. return Actual && *Actual == Expected;
  1288. };
  1289. std::error_code NoError;
  1290. EXPECT_EQ(fs::setPermissions(TempPath, fs::all_all), NoError);
  1291. EXPECT_TRUE(CheckPermissions(fs::all_all));
  1292. EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read | fs::all_exe), NoError);
  1293. EXPECT_TRUE(CheckPermissions(fs::all_read | fs::all_exe));
  1294. #if defined(_WIN32)
  1295. fs::perms ReadOnly = fs::all_read | fs::all_exe;
  1296. EXPECT_EQ(fs::setPermissions(TempPath, fs::no_perms), NoError);
  1297. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1298. EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_read), NoError);
  1299. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1300. EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_write), NoError);
  1301. EXPECT_TRUE(CheckPermissions(fs::all_all));
  1302. EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_exe), NoError);
  1303. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1304. EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_all), NoError);
  1305. EXPECT_TRUE(CheckPermissions(fs::all_all));
  1306. EXPECT_EQ(fs::setPermissions(TempPath, fs::group_read), NoError);
  1307. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1308. EXPECT_EQ(fs::setPermissions(TempPath, fs::group_write), NoError);
  1309. EXPECT_TRUE(CheckPermissions(fs::all_all));
  1310. EXPECT_EQ(fs::setPermissions(TempPath, fs::group_exe), NoError);
  1311. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1312. EXPECT_EQ(fs::setPermissions(TempPath, fs::group_all), NoError);
  1313. EXPECT_TRUE(CheckPermissions(fs::all_all));
  1314. EXPECT_EQ(fs::setPermissions(TempPath, fs::others_read), NoError);
  1315. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1316. EXPECT_EQ(fs::setPermissions(TempPath, fs::others_write), NoError);
  1317. EXPECT_TRUE(CheckPermissions(fs::all_all));
  1318. EXPECT_EQ(fs::setPermissions(TempPath, fs::others_exe), NoError);
  1319. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1320. EXPECT_EQ(fs::setPermissions(TempPath, fs::others_all), NoError);
  1321. EXPECT_TRUE(CheckPermissions(fs::all_all));
  1322. EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read), NoError);
  1323. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1324. EXPECT_EQ(fs::setPermissions(TempPath, fs::all_write), NoError);
  1325. EXPECT_TRUE(CheckPermissions(fs::all_all));
  1326. EXPECT_EQ(fs::setPermissions(TempPath, fs::all_exe), NoError);
  1327. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1328. EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe), NoError);
  1329. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1330. EXPECT_EQ(fs::setPermissions(TempPath, fs::set_gid_on_exe), NoError);
  1331. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1332. EXPECT_EQ(fs::setPermissions(TempPath, fs::sticky_bit), NoError);
  1333. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1334. EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe |
  1335. fs::set_gid_on_exe |
  1336. fs::sticky_bit),
  1337. NoError);
  1338. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1339. EXPECT_EQ(fs::setPermissions(TempPath, ReadOnly | fs::set_uid_on_exe |
  1340. fs::set_gid_on_exe |
  1341. fs::sticky_bit),
  1342. NoError);
  1343. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1344. EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms), NoError);
  1345. EXPECT_TRUE(CheckPermissions(fs::all_all));
  1346. #else
  1347. EXPECT_EQ(fs::setPermissions(TempPath, fs::no_perms), NoError);
  1348. EXPECT_TRUE(CheckPermissions(fs::no_perms));
  1349. EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_read), NoError);
  1350. EXPECT_TRUE(CheckPermissions(fs::owner_read));
  1351. EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_write), NoError);
  1352. EXPECT_TRUE(CheckPermissions(fs::owner_write));
  1353. EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_exe), NoError);
  1354. EXPECT_TRUE(CheckPermissions(fs::owner_exe));
  1355. EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_all), NoError);
  1356. EXPECT_TRUE(CheckPermissions(fs::owner_all));
  1357. EXPECT_EQ(fs::setPermissions(TempPath, fs::group_read), NoError);
  1358. EXPECT_TRUE(CheckPermissions(fs::group_read));
  1359. EXPECT_EQ(fs::setPermissions(TempPath, fs::group_write), NoError);
  1360. EXPECT_TRUE(CheckPermissions(fs::group_write));
  1361. EXPECT_EQ(fs::setPermissions(TempPath, fs::group_exe), NoError);
  1362. EXPECT_TRUE(CheckPermissions(fs::group_exe));
  1363. EXPECT_EQ(fs::setPermissions(TempPath, fs::group_all), NoError);
  1364. EXPECT_TRUE(CheckPermissions(fs::group_all));
  1365. EXPECT_EQ(fs::setPermissions(TempPath, fs::others_read), NoError);
  1366. EXPECT_TRUE(CheckPermissions(fs::others_read));
  1367. EXPECT_EQ(fs::setPermissions(TempPath, fs::others_write), NoError);
  1368. EXPECT_TRUE(CheckPermissions(fs::others_write));
  1369. EXPECT_EQ(fs::setPermissions(TempPath, fs::others_exe), NoError);
  1370. EXPECT_TRUE(CheckPermissions(fs::others_exe));
  1371. EXPECT_EQ(fs::setPermissions(TempPath, fs::others_all), NoError);
  1372. EXPECT_TRUE(CheckPermissions(fs::others_all));
  1373. EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read), NoError);
  1374. EXPECT_TRUE(CheckPermissions(fs::all_read));
  1375. EXPECT_EQ(fs::setPermissions(TempPath, fs::all_write), NoError);
  1376. EXPECT_TRUE(CheckPermissions(fs::all_write));
  1377. EXPECT_EQ(fs::setPermissions(TempPath, fs::all_exe), NoError);
  1378. EXPECT_TRUE(CheckPermissions(fs::all_exe));
  1379. EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe), NoError);
  1380. EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe));
  1381. EXPECT_EQ(fs::setPermissions(TempPath, fs::set_gid_on_exe), NoError);
  1382. EXPECT_TRUE(CheckPermissions(fs::set_gid_on_exe));
  1383. // Modern BSDs require root to set the sticky bit on files.
  1384. #if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__)
  1385. EXPECT_EQ(fs::setPermissions(TempPath, fs::sticky_bit), NoError);
  1386. EXPECT_TRUE(CheckPermissions(fs::sticky_bit));
  1387. EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe |
  1388. fs::set_gid_on_exe |
  1389. fs::sticky_bit),
  1390. NoError);
  1391. EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe | fs::set_gid_on_exe |
  1392. fs::sticky_bit));
  1393. EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read | fs::set_uid_on_exe |
  1394. fs::set_gid_on_exe |
  1395. fs::sticky_bit),
  1396. NoError);
  1397. EXPECT_TRUE(CheckPermissions(fs::all_read | fs::set_uid_on_exe |
  1398. fs::set_gid_on_exe | fs::sticky_bit));
  1399. EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms), NoError);
  1400. EXPECT_TRUE(CheckPermissions(fs::all_perms));
  1401. #endif // !FreeBSD && !NetBSD && !OpenBSD
  1402. EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms & ~fs::sticky_bit),
  1403. NoError);
  1404. EXPECT_TRUE(CheckPermissions(fs::all_perms & ~fs::sticky_bit));
  1405. #endif
  1406. }
  1407. } // anonymous namespace