Path.cpp 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723
  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, UserCacheDirectory) {
  305. SmallString<13> CacheDir;
  306. SmallString<20> CacheDir2;
  307. auto Status = path::user_cache_directory(CacheDir, "");
  308. EXPECT_TRUE(Status ^ CacheDir.empty());
  309. if (Status) {
  310. EXPECT_TRUE(path::user_cache_directory(CacheDir2, "")); // should succeed
  311. EXPECT_EQ(CacheDir, CacheDir2); // and return same paths
  312. EXPECT_TRUE(path::user_cache_directory(CacheDir, "A", "B", "file.c"));
  313. auto It = path::rbegin(CacheDir);
  314. EXPECT_EQ("file.c", *It);
  315. EXPECT_EQ("B", *++It);
  316. EXPECT_EQ("A", *++It);
  317. auto ParentDir = *++It;
  318. // Test Unicode: "<user_cache_dir>/(pi)r^2/aleth.0"
  319. EXPECT_TRUE(path::user_cache_directory(CacheDir2, "\xCF\x80r\xC2\xB2",
  320. "\xE2\x84\xB5.0"));
  321. auto It2 = path::rbegin(CacheDir2);
  322. EXPECT_EQ("\xE2\x84\xB5.0", *It2);
  323. EXPECT_EQ("\xCF\x80r\xC2\xB2", *++It2);
  324. auto ParentDir2 = *++It2;
  325. EXPECT_EQ(ParentDir, ParentDir2);
  326. }
  327. }
  328. TEST(Support, TempDirectory) {
  329. SmallString<32> TempDir;
  330. path::system_temp_directory(false, TempDir);
  331. EXPECT_TRUE(!TempDir.empty());
  332. TempDir.clear();
  333. path::system_temp_directory(true, TempDir);
  334. EXPECT_TRUE(!TempDir.empty());
  335. }
  336. #ifdef _WIN32
  337. static std::string path2regex(std::string Path) {
  338. size_t Pos = 0;
  339. while ((Pos = Path.find('\\', Pos)) != std::string::npos) {
  340. Path.replace(Pos, 1, "\\\\");
  341. Pos += 2;
  342. }
  343. return Path;
  344. }
  345. /// Helper for running temp dir test in separated process. See below.
  346. #define EXPECT_TEMP_DIR(prepare, expected) \
  347. EXPECT_EXIT( \
  348. { \
  349. prepare; \
  350. SmallString<300> TempDir; \
  351. path::system_temp_directory(true, TempDir); \
  352. raw_os_ostream(std::cerr) << TempDir; \
  353. std::exit(0); \
  354. }, \
  355. ::testing::ExitedWithCode(0), path2regex(expected))
  356. TEST(SupportDeathTest, TempDirectoryOnWindows) {
  357. // In this test we want to check how system_temp_directory responds to
  358. // different values of specific env vars. To prevent corrupting env vars of
  359. // the current process all checks are done in separated processes.
  360. EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"C:\\OtherFolder"), "C:\\OtherFolder");
  361. EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"C:/Unix/Path/Seperators"),
  362. "C:\\Unix\\Path\\Seperators");
  363. EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"Local Path"), ".+\\Local Path$");
  364. EXPECT_TEMP_DIR(_wputenv_s(L"TMP", L"F:\\TrailingSep\\"), "F:\\TrailingSep");
  365. EXPECT_TEMP_DIR(
  366. _wputenv_s(L"TMP", L"C:\\2\x03C0r-\x00B5\x00B3\\\x2135\x2080"),
  367. "C:\\2\xCF\x80r-\xC2\xB5\xC2\xB3\\\xE2\x84\xB5\xE2\x82\x80");
  368. // Test $TMP empty, $TEMP set.
  369. EXPECT_TEMP_DIR(
  370. {
  371. _wputenv_s(L"TMP", L"");
  372. _wputenv_s(L"TEMP", L"C:\\Valid\\Path");
  373. },
  374. "C:\\Valid\\Path");
  375. // All related env vars empty
  376. EXPECT_TEMP_DIR(
  377. {
  378. _wputenv_s(L"TMP", L"");
  379. _wputenv_s(L"TEMP", L"");
  380. _wputenv_s(L"USERPROFILE", L"");
  381. },
  382. "C:\\Temp");
  383. // Test evn var / path with 260 chars.
  384. SmallString<270> Expected{"C:\\Temp\\AB\\123456789"};
  385. while (Expected.size() < 260)
  386. Expected.append("\\DirNameWith19Charss");
  387. ASSERT_EQ(260U, Expected.size());
  388. EXPECT_TEMP_DIR(_putenv_s("TMP", Expected.c_str()), Expected.c_str());
  389. }
  390. #endif
  391. class FileSystemTest : public testing::Test {
  392. protected:
  393. /// Unique temporary directory in which all created filesystem entities must
  394. /// be placed. It is removed at the end of each test (must be empty).
  395. SmallString<128> TestDirectory;
  396. SmallString<128> NonExistantFile;
  397. void SetUp() override {
  398. ASSERT_NO_ERROR(
  399. fs::createUniqueDirectory("file-system-test", TestDirectory));
  400. // We don't care about this specific file.
  401. errs() << "Test Directory: " << TestDirectory << '\n';
  402. errs().flush();
  403. NonExistantFile = TestDirectory;
  404. // Even though this value is hardcoded, is a 128-bit GUID, so we should be
  405. // guaranteed that this file will never exist.
  406. sys::path::append(NonExistantFile, "1B28B495C16344CB9822E588CD4C3EF0");
  407. }
  408. void TearDown() override { ASSERT_NO_ERROR(fs::remove(TestDirectory.str())); }
  409. };
  410. TEST_F(FileSystemTest, Unique) {
  411. // Create a temp file.
  412. int FileDescriptor;
  413. SmallString<64> TempPath;
  414. ASSERT_NO_ERROR(
  415. fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
  416. // The same file should return an identical unique id.
  417. fs::UniqueID F1, F2;
  418. ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F1));
  419. ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), F2));
  420. ASSERT_EQ(F1, F2);
  421. // Different files should return different unique ids.
  422. int FileDescriptor2;
  423. SmallString<64> TempPath2;
  424. ASSERT_NO_ERROR(
  425. fs::createTemporaryFile("prefix", "temp", FileDescriptor2, TempPath2));
  426. fs::UniqueID D;
  427. ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D));
  428. ASSERT_NE(D, F1);
  429. ::close(FileDescriptor2);
  430. ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
  431. // Two paths representing the same file on disk should still provide the
  432. // same unique id. We can test this by making a hard link.
  433. ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
  434. fs::UniqueID D2;
  435. ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath2), D2));
  436. ASSERT_EQ(D2, F1);
  437. ::close(FileDescriptor);
  438. SmallString<128> Dir1;
  439. ASSERT_NO_ERROR(
  440. fs::createUniqueDirectory("dir1", Dir1));
  441. ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F1));
  442. ASSERT_NO_ERROR(fs::getUniqueID(Dir1.c_str(), F2));
  443. ASSERT_EQ(F1, F2);
  444. SmallString<128> Dir2;
  445. ASSERT_NO_ERROR(
  446. fs::createUniqueDirectory("dir2", Dir2));
  447. ASSERT_NO_ERROR(fs::getUniqueID(Dir2.c_str(), F2));
  448. ASSERT_NE(F1, F2);
  449. ASSERT_NO_ERROR(fs::remove(Dir1));
  450. ASSERT_NO_ERROR(fs::remove(Dir2));
  451. ASSERT_NO_ERROR(fs::remove(TempPath2));
  452. ASSERT_NO_ERROR(fs::remove(TempPath));
  453. }
  454. TEST_F(FileSystemTest, RealPath) {
  455. ASSERT_NO_ERROR(
  456. fs::create_directories(Twine(TestDirectory) + "/test1/test2/test3"));
  457. ASSERT_TRUE(fs::exists(Twine(TestDirectory) + "/test1/test2/test3"));
  458. SmallString<64> RealBase;
  459. SmallString<64> Expected;
  460. SmallString<64> Actual;
  461. // TestDirectory itself might be under a symlink or have been specified with
  462. // a different case than the existing temp directory. In such cases real_path
  463. // on the concatenated path will differ in the TestDirectory portion from
  464. // how we specified it. Make sure to compare against the real_path of the
  465. // TestDirectory, and not just the value of TestDirectory.
  466. ASSERT_NO_ERROR(fs::real_path(TestDirectory, RealBase));
  467. path::native(Twine(RealBase) + "/test1/test2", Expected);
  468. ASSERT_NO_ERROR(fs::real_path(
  469. Twine(TestDirectory) + "/././test1/../test1/test2/./test3/..", Actual));
  470. EXPECT_EQ(Expected, Actual);
  471. SmallString<64> HomeDir;
  472. bool Result = llvm::sys::path::home_directory(HomeDir);
  473. if (Result) {
  474. ASSERT_NO_ERROR(fs::real_path(HomeDir, Expected));
  475. ASSERT_NO_ERROR(fs::real_path("~", Actual, true));
  476. EXPECT_EQ(Expected, Actual);
  477. ASSERT_NO_ERROR(fs::real_path("~/", Actual, true));
  478. EXPECT_EQ(Expected, Actual);
  479. }
  480. ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/test1"));
  481. }
  482. #ifdef LLVM_ON_UNIX
  483. TEST_F(FileSystemTest, RealPathNoReadPerm) {
  484. SmallString<64> Expanded;
  485. ASSERT_NO_ERROR(
  486. fs::create_directories(Twine(TestDirectory) + "/noreadperm"));
  487. ASSERT_TRUE(fs::exists(Twine(TestDirectory) + "/noreadperm"));
  488. fs::setPermissions(Twine(TestDirectory) + "/noreadperm", fs::no_perms);
  489. fs::setPermissions(Twine(TestDirectory) + "/noreadperm", fs::all_exe);
  490. ASSERT_NO_ERROR(fs::real_path(Twine(TestDirectory) + "/noreadperm", Expanded,
  491. false));
  492. ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/noreadperm"));
  493. }
  494. #endif
  495. TEST_F(FileSystemTest, TempFileKeepDiscard) {
  496. // We can keep then discard.
  497. auto TempFileOrError = fs::TempFile::create(TestDirectory + "/test-%%%%");
  498. ASSERT_TRUE((bool)TempFileOrError);
  499. fs::TempFile File = std::move(*TempFileOrError);
  500. ASSERT_FALSE((bool)File.keep(TestDirectory + "/keep"));
  501. ASSERT_FALSE((bool)File.discard());
  502. ASSERT_TRUE(fs::exists(TestDirectory + "/keep"));
  503. ASSERT_NO_ERROR(fs::remove(TestDirectory + "/keep"));
  504. }
  505. TEST_F(FileSystemTest, TempFileDiscardDiscard) {
  506. // We can discard twice.
  507. auto TempFileOrError = fs::TempFile::create(TestDirectory + "/test-%%%%");
  508. ASSERT_TRUE((bool)TempFileOrError);
  509. fs::TempFile File = std::move(*TempFileOrError);
  510. ASSERT_FALSE((bool)File.discard());
  511. ASSERT_FALSE((bool)File.discard());
  512. ASSERT_FALSE(fs::exists(TestDirectory + "/keep"));
  513. }
  514. TEST_F(FileSystemTest, TempFiles) {
  515. // Create a temp file.
  516. int FileDescriptor;
  517. SmallString<64> TempPath;
  518. ASSERT_NO_ERROR(
  519. fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
  520. // Make sure it exists.
  521. ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
  522. // Create another temp tile.
  523. int FD2;
  524. SmallString<64> TempPath2;
  525. ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD2, TempPath2));
  526. ASSERT_TRUE(TempPath2.endswith(".temp"));
  527. ASSERT_NE(TempPath.str(), TempPath2.str());
  528. fs::file_status A, B;
  529. ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
  530. ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
  531. EXPECT_FALSE(fs::equivalent(A, B));
  532. ::close(FD2);
  533. // Remove Temp2.
  534. ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
  535. ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
  536. ASSERT_EQ(fs::remove(Twine(TempPath2), false),
  537. errc::no_such_file_or_directory);
  538. std::error_code EC = fs::status(TempPath2.c_str(), B);
  539. EXPECT_EQ(EC, errc::no_such_file_or_directory);
  540. EXPECT_EQ(B.type(), fs::file_type::file_not_found);
  541. // Make sure Temp2 doesn't exist.
  542. ASSERT_EQ(fs::access(Twine(TempPath2), sys::fs::AccessMode::Exist),
  543. errc::no_such_file_or_directory);
  544. SmallString<64> TempPath3;
  545. ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "", TempPath3));
  546. ASSERT_FALSE(TempPath3.endswith("."));
  547. FileRemover Cleanup3(TempPath3);
  548. // Create a hard link to Temp1.
  549. ASSERT_NO_ERROR(fs::create_link(Twine(TempPath), Twine(TempPath2)));
  550. bool equal;
  551. ASSERT_NO_ERROR(fs::equivalent(Twine(TempPath), Twine(TempPath2), equal));
  552. EXPECT_TRUE(equal);
  553. ASSERT_NO_ERROR(fs::status(Twine(TempPath), A));
  554. ASSERT_NO_ERROR(fs::status(Twine(TempPath2), B));
  555. EXPECT_TRUE(fs::equivalent(A, B));
  556. // Remove Temp1.
  557. ::close(FileDescriptor);
  558. ASSERT_NO_ERROR(fs::remove(Twine(TempPath)));
  559. // Remove the hard link.
  560. ASSERT_NO_ERROR(fs::remove(Twine(TempPath2)));
  561. // Make sure Temp1 doesn't exist.
  562. ASSERT_EQ(fs::access(Twine(TempPath), sys::fs::AccessMode::Exist),
  563. errc::no_such_file_or_directory);
  564. #ifdef _WIN32
  565. // Path name > 260 chars should get an error.
  566. const char *Path270 =
  567. "abcdefghijklmnopqrstuvwxyz9abcdefghijklmnopqrstuvwxyz8"
  568. "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
  569. "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
  570. "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
  571. "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
  572. EXPECT_EQ(fs::createUniqueFile(Path270, FileDescriptor, TempPath),
  573. errc::invalid_argument);
  574. // Relative path < 247 chars, no problem.
  575. const char *Path216 =
  576. "abcdefghijklmnopqrstuvwxyz7abcdefghijklmnopqrstuvwxyz6"
  577. "abcdefghijklmnopqrstuvwxyz5abcdefghijklmnopqrstuvwxyz4"
  578. "abcdefghijklmnopqrstuvwxyz3abcdefghijklmnopqrstuvwxyz2"
  579. "abcdefghijklmnopqrstuvwxyz1abcdefghijklmnopqrstuvwxyz0";
  580. ASSERT_NO_ERROR(fs::createTemporaryFile(Path216, "", TempPath));
  581. ASSERT_NO_ERROR(fs::remove(Twine(TempPath)));
  582. #endif
  583. }
  584. TEST_F(FileSystemTest, TempFileCollisions) {
  585. SmallString<128> TestDirectory;
  586. ASSERT_NO_ERROR(
  587. fs::createUniqueDirectory("CreateUniqueFileTest", TestDirectory));
  588. FileRemover Cleanup(TestDirectory);
  589. SmallString<128> Model = TestDirectory;
  590. path::append(Model, "%.tmp");
  591. SmallString<128> Path;
  592. std::vector<fs::TempFile> TempFiles;
  593. auto TryCreateTempFile = [&]() {
  594. Expected<fs::TempFile> T = fs::TempFile::create(Model);
  595. if (T) {
  596. TempFiles.push_back(std::move(*T));
  597. return true;
  598. } else {
  599. logAllUnhandledErrors(T.takeError(), errs(),
  600. "Failed to create temporary file: ");
  601. return false;
  602. }
  603. };
  604. // We should be able to create exactly 16 temporary files.
  605. for (int i = 0; i < 16; ++i)
  606. EXPECT_TRUE(TryCreateTempFile());
  607. EXPECT_FALSE(TryCreateTempFile());
  608. for (fs::TempFile &T : TempFiles)
  609. cantFail(T.discard());
  610. }
  611. TEST_F(FileSystemTest, CreateDir) {
  612. ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
  613. ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "foo"));
  614. ASSERT_EQ(fs::create_directory(Twine(TestDirectory) + "foo", false),
  615. errc::file_exists);
  616. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "foo"));
  617. #ifdef LLVM_ON_UNIX
  618. // Set a 0000 umask so that we can test our directory permissions.
  619. mode_t OldUmask = ::umask(0000);
  620. fs::file_status Status;
  621. ASSERT_NO_ERROR(
  622. fs::create_directory(Twine(TestDirectory) + "baz500", false,
  623. fs::perms::owner_read | fs::perms::owner_exe));
  624. ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz500", Status));
  625. ASSERT_EQ(Status.permissions() & fs::perms::all_all,
  626. fs::perms::owner_read | fs::perms::owner_exe);
  627. ASSERT_NO_ERROR(fs::create_directory(Twine(TestDirectory) + "baz777", false,
  628. fs::perms::all_all));
  629. ASSERT_NO_ERROR(fs::status(Twine(TestDirectory) + "baz777", Status));
  630. ASSERT_EQ(Status.permissions() & fs::perms::all_all, fs::perms::all_all);
  631. // Restore umask to be safe.
  632. ::umask(OldUmask);
  633. #endif
  634. #ifdef _WIN32
  635. // Prove that create_directories() can handle a pathname > 248 characters,
  636. // which is the documented limit for CreateDirectory().
  637. // (248 is MAX_PATH subtracting room for an 8.3 filename.)
  638. // Generate a directory path guaranteed to fall into that range.
  639. size_t TmpLen = TestDirectory.size();
  640. const char *OneDir = "\\123456789";
  641. size_t OneDirLen = strlen(OneDir);
  642. ASSERT_LT(OneDirLen, 12U);
  643. size_t NLevels = ((248 - TmpLen) / OneDirLen) + 1;
  644. SmallString<260> LongDir(TestDirectory);
  645. for (size_t I = 0; I < NLevels; ++I)
  646. LongDir.append(OneDir);
  647. ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir)));
  648. ASSERT_NO_ERROR(fs::create_directories(Twine(LongDir)));
  649. ASSERT_EQ(fs::create_directories(Twine(LongDir), false),
  650. errc::file_exists);
  651. // Tidy up, "recursively" removing the directories.
  652. StringRef ThisDir(LongDir);
  653. for (size_t J = 0; J < NLevels; ++J) {
  654. ASSERT_NO_ERROR(fs::remove(ThisDir));
  655. ThisDir = path::parent_path(ThisDir);
  656. }
  657. // Also verify that paths with Unix separators are handled correctly.
  658. std::string LongPathWithUnixSeparators(TestDirectory.str());
  659. // Add at least one subdirectory to TestDirectory, and replace slashes with
  660. // backslashes
  661. do {
  662. LongPathWithUnixSeparators.append("/DirNameWith19Charss");
  663. } while (LongPathWithUnixSeparators.size() < 260);
  664. std::replace(LongPathWithUnixSeparators.begin(),
  665. LongPathWithUnixSeparators.end(),
  666. '\\', '/');
  667. ASSERT_NO_ERROR(fs::create_directories(Twine(LongPathWithUnixSeparators)));
  668. // cleanup
  669. ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) +
  670. "/DirNameWith19Charss"));
  671. // Similarly for a relative pathname. Need to set the current directory to
  672. // TestDirectory so that the one we create ends up in the right place.
  673. char PreviousDir[260];
  674. size_t PreviousDirLen = ::GetCurrentDirectoryA(260, PreviousDir);
  675. ASSERT_GT(PreviousDirLen, 0U);
  676. ASSERT_LT(PreviousDirLen, 260U);
  677. ASSERT_NE(::SetCurrentDirectoryA(TestDirectory.c_str()), 0);
  678. LongDir.clear();
  679. // Generate a relative directory name with absolute length > 248.
  680. size_t LongDirLen = 249 - TestDirectory.size();
  681. LongDir.assign(LongDirLen, 'a');
  682. ASSERT_NO_ERROR(fs::create_directory(Twine(LongDir)));
  683. // While we're here, prove that .. and . handling works in these long paths.
  684. const char *DotDotDirs = "\\..\\.\\b";
  685. LongDir.append(DotDotDirs);
  686. ASSERT_NO_ERROR(fs::create_directory("b"));
  687. ASSERT_EQ(fs::create_directory(Twine(LongDir), false), errc::file_exists);
  688. // And clean up.
  689. ASSERT_NO_ERROR(fs::remove("b"));
  690. ASSERT_NO_ERROR(fs::remove(
  691. Twine(LongDir.substr(0, LongDir.size() - strlen(DotDotDirs)))));
  692. ASSERT_NE(::SetCurrentDirectoryA(PreviousDir), 0);
  693. #endif
  694. }
  695. TEST_F(FileSystemTest, DirectoryIteration) {
  696. std::error_code ec;
  697. for (fs::directory_iterator i(".", ec), e; i != e; i.increment(ec))
  698. ASSERT_NO_ERROR(ec);
  699. // Create a known hierarchy to recurse over.
  700. ASSERT_NO_ERROR(
  701. fs::create_directories(Twine(TestDirectory) + "/recursive/a0/aa1"));
  702. ASSERT_NO_ERROR(
  703. fs::create_directories(Twine(TestDirectory) + "/recursive/a0/ab1"));
  704. ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) +
  705. "/recursive/dontlookhere/da1"));
  706. ASSERT_NO_ERROR(
  707. fs::create_directories(Twine(TestDirectory) + "/recursive/z0/za1"));
  708. ASSERT_NO_ERROR(
  709. fs::create_directories(Twine(TestDirectory) + "/recursive/pop/p1"));
  710. typedef std::vector<std::string> v_t;
  711. v_t visited;
  712. for (fs::recursive_directory_iterator i(Twine(TestDirectory)
  713. + "/recursive", ec), e; i != e; i.increment(ec)){
  714. ASSERT_NO_ERROR(ec);
  715. if (path::filename(i->path()) == "p1") {
  716. i.pop();
  717. // FIXME: recursive_directory_iterator should be more robust.
  718. if (i == e) break;
  719. }
  720. if (path::filename(i->path()) == "dontlookhere")
  721. i.no_push();
  722. visited.push_back(path::filename(i->path()));
  723. }
  724. v_t::const_iterator a0 = find(visited, "a0");
  725. v_t::const_iterator aa1 = find(visited, "aa1");
  726. v_t::const_iterator ab1 = find(visited, "ab1");
  727. v_t::const_iterator dontlookhere = find(visited, "dontlookhere");
  728. v_t::const_iterator da1 = find(visited, "da1");
  729. v_t::const_iterator z0 = find(visited, "z0");
  730. v_t::const_iterator za1 = find(visited, "za1");
  731. v_t::const_iterator pop = find(visited, "pop");
  732. v_t::const_iterator p1 = find(visited, "p1");
  733. // Make sure that each path was visited correctly.
  734. ASSERT_NE(a0, visited.end());
  735. ASSERT_NE(aa1, visited.end());
  736. ASSERT_NE(ab1, visited.end());
  737. ASSERT_NE(dontlookhere, visited.end());
  738. ASSERT_EQ(da1, visited.end()); // Not visited.
  739. ASSERT_NE(z0, visited.end());
  740. ASSERT_NE(za1, visited.end());
  741. ASSERT_NE(pop, visited.end());
  742. ASSERT_EQ(p1, visited.end()); // Not visited.
  743. // Make sure that parents were visited before children. No other ordering
  744. // guarantees can be made across siblings.
  745. ASSERT_LT(a0, aa1);
  746. ASSERT_LT(a0, ab1);
  747. ASSERT_LT(z0, za1);
  748. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/aa1"));
  749. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0/ab1"));
  750. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/a0"));
  751. ASSERT_NO_ERROR(
  752. fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere/da1"));
  753. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/dontlookhere"));
  754. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop/p1"));
  755. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/pop"));
  756. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0/za1"));
  757. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive/z0"));
  758. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/recursive"));
  759. // Test recursive_directory_iterator level()
  760. ASSERT_NO_ERROR(
  761. fs::create_directories(Twine(TestDirectory) + "/reclevel/a/b/c"));
  762. fs::recursive_directory_iterator I(Twine(TestDirectory) + "/reclevel", ec), E;
  763. for (int l = 0; I != E; I.increment(ec), ++l) {
  764. ASSERT_NO_ERROR(ec);
  765. EXPECT_EQ(I.level(), l);
  766. }
  767. EXPECT_EQ(I, E);
  768. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a/b/c"));
  769. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a/b"));
  770. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel/a"));
  771. ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory) + "/reclevel"));
  772. }
  773. #ifdef LLVM_ON_UNIX
  774. TEST_F(FileSystemTest, BrokenSymlinkDirectoryIteration) {
  775. // Create a known hierarchy to recurse over.
  776. ASSERT_NO_ERROR(fs::create_directories(Twine(TestDirectory) + "/symlink"));
  777. ASSERT_NO_ERROR(
  778. fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/a"));
  779. ASSERT_NO_ERROR(
  780. fs::create_directories(Twine(TestDirectory) + "/symlink/b/bb"));
  781. ASSERT_NO_ERROR(
  782. fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/b/ba"));
  783. ASSERT_NO_ERROR(
  784. fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/b/bc"));
  785. ASSERT_NO_ERROR(
  786. fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/c"));
  787. ASSERT_NO_ERROR(
  788. fs::create_directories(Twine(TestDirectory) + "/symlink/d/dd/ddd"));
  789. ASSERT_NO_ERROR(fs::create_link(Twine(TestDirectory) + "/symlink/d/dd",
  790. Twine(TestDirectory) + "/symlink/d/da"));
  791. ASSERT_NO_ERROR(
  792. fs::create_link("no_such_file", Twine(TestDirectory) + "/symlink/e"));
  793. typedef std::vector<std::string> v_t;
  794. v_t VisitedNonBrokenSymlinks;
  795. v_t VisitedBrokenSymlinks;
  796. std::error_code ec;
  797. // Broken symbol links are expected to throw an error.
  798. for (fs::directory_iterator i(Twine(TestDirectory) + "/symlink", ec), e;
  799. i != e; i.increment(ec)) {
  800. if (ec == std::make_error_code(std::errc::no_such_file_or_directory)) {
  801. VisitedBrokenSymlinks.push_back(path::filename(i->path()));
  802. continue;
  803. }
  804. ASSERT_NO_ERROR(ec);
  805. VisitedNonBrokenSymlinks.push_back(path::filename(i->path()));
  806. }
  807. llvm::sort(VisitedNonBrokenSymlinks.begin(), VisitedNonBrokenSymlinks.end());
  808. llvm::sort(VisitedBrokenSymlinks.begin(), VisitedBrokenSymlinks.end());
  809. v_t ExpectedNonBrokenSymlinks = {"b", "d"};
  810. ASSERT_EQ(ExpectedNonBrokenSymlinks.size(), VisitedNonBrokenSymlinks.size());
  811. ASSERT_TRUE(std::equal(VisitedNonBrokenSymlinks.begin(),
  812. VisitedNonBrokenSymlinks.end(),
  813. ExpectedNonBrokenSymlinks.begin()));
  814. VisitedNonBrokenSymlinks.clear();
  815. v_t ExpectedBrokenSymlinks = {"a", "c", "e"};
  816. ASSERT_EQ(ExpectedBrokenSymlinks.size(), VisitedBrokenSymlinks.size());
  817. ASSERT_TRUE(std::equal(VisitedBrokenSymlinks.begin(),
  818. VisitedBrokenSymlinks.end(),
  819. ExpectedBrokenSymlinks.begin()));
  820. VisitedBrokenSymlinks.clear();
  821. // Broken symbol links are expected to throw an error.
  822. for (fs::recursive_directory_iterator i(
  823. Twine(TestDirectory) + "/symlink", ec), e; i != e; i.increment(ec)) {
  824. if (ec == std::make_error_code(std::errc::no_such_file_or_directory)) {
  825. VisitedBrokenSymlinks.push_back(path::filename(i->path()));
  826. continue;
  827. }
  828. ASSERT_NO_ERROR(ec);
  829. VisitedNonBrokenSymlinks.push_back(path::filename(i->path()));
  830. }
  831. llvm::sort(VisitedNonBrokenSymlinks.begin(), VisitedNonBrokenSymlinks.end());
  832. llvm::sort(VisitedBrokenSymlinks.begin(), VisitedBrokenSymlinks.end());
  833. ExpectedNonBrokenSymlinks = {"b", "bb", "d", "da", "dd", "ddd", "ddd"};
  834. ASSERT_EQ(ExpectedNonBrokenSymlinks.size(), VisitedNonBrokenSymlinks.size());
  835. ASSERT_TRUE(std::equal(VisitedNonBrokenSymlinks.begin(),
  836. VisitedNonBrokenSymlinks.end(),
  837. ExpectedNonBrokenSymlinks.begin()));
  838. VisitedNonBrokenSymlinks.clear();
  839. ExpectedBrokenSymlinks = {"a", "ba", "bc", "c", "e"};
  840. ASSERT_EQ(ExpectedBrokenSymlinks.size(), VisitedBrokenSymlinks.size());
  841. ASSERT_TRUE(std::equal(VisitedBrokenSymlinks.begin(),
  842. VisitedBrokenSymlinks.end(),
  843. ExpectedBrokenSymlinks.begin()));
  844. VisitedBrokenSymlinks.clear();
  845. for (fs::recursive_directory_iterator i(
  846. Twine(TestDirectory) + "/symlink", ec, /*follow_symlinks=*/false), e;
  847. i != e; i.increment(ec)) {
  848. if (ec == std::make_error_code(std::errc::no_such_file_or_directory)) {
  849. VisitedBrokenSymlinks.push_back(path::filename(i->path()));
  850. continue;
  851. }
  852. ASSERT_NO_ERROR(ec);
  853. VisitedNonBrokenSymlinks.push_back(path::filename(i->path()));
  854. }
  855. llvm::sort(VisitedNonBrokenSymlinks.begin(), VisitedNonBrokenSymlinks.end());
  856. llvm::sort(VisitedBrokenSymlinks.begin(), VisitedBrokenSymlinks.end());
  857. ExpectedNonBrokenSymlinks = {"a", "b", "ba", "bb", "bc", "c", "d", "da", "dd",
  858. "ddd", "e"};
  859. ASSERT_EQ(ExpectedNonBrokenSymlinks.size(), VisitedNonBrokenSymlinks.size());
  860. ASSERT_TRUE(std::equal(VisitedNonBrokenSymlinks.begin(),
  861. VisitedNonBrokenSymlinks.end(),
  862. ExpectedNonBrokenSymlinks.begin()));
  863. VisitedNonBrokenSymlinks.clear();
  864. ExpectedBrokenSymlinks = {};
  865. ASSERT_EQ(ExpectedBrokenSymlinks.size(), VisitedBrokenSymlinks.size());
  866. ASSERT_TRUE(std::equal(VisitedBrokenSymlinks.begin(),
  867. VisitedBrokenSymlinks.end(),
  868. ExpectedBrokenSymlinks.begin()));
  869. VisitedBrokenSymlinks.clear();
  870. ASSERT_NO_ERROR(fs::remove_directories(Twine(TestDirectory) + "/symlink"));
  871. }
  872. #endif
  873. TEST_F(FileSystemTest, Remove) {
  874. SmallString<64> BaseDir;
  875. SmallString<64> Paths[4];
  876. int fds[4];
  877. ASSERT_NO_ERROR(fs::createUniqueDirectory("fs_remove", BaseDir));
  878. ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir) + "/foo/bar/baz"));
  879. ASSERT_NO_ERROR(fs::create_directories(Twine(BaseDir) + "/foo/bar/buzz"));
  880. ASSERT_NO_ERROR(fs::createUniqueFile(
  881. Twine(BaseDir) + "/foo/bar/baz/%%%%%%.tmp", fds[0], Paths[0]));
  882. ASSERT_NO_ERROR(fs::createUniqueFile(
  883. Twine(BaseDir) + "/foo/bar/baz/%%%%%%.tmp", fds[1], Paths[1]));
  884. ASSERT_NO_ERROR(fs::createUniqueFile(
  885. Twine(BaseDir) + "/foo/bar/buzz/%%%%%%.tmp", fds[2], Paths[2]));
  886. ASSERT_NO_ERROR(fs::createUniqueFile(
  887. Twine(BaseDir) + "/foo/bar/buzz/%%%%%%.tmp", fds[3], Paths[3]));
  888. for (int fd : fds)
  889. ::close(fd);
  890. EXPECT_TRUE(fs::exists(Twine(BaseDir) + "/foo/bar/baz"));
  891. EXPECT_TRUE(fs::exists(Twine(BaseDir) + "/foo/bar/buzz"));
  892. EXPECT_TRUE(fs::exists(Paths[0]));
  893. EXPECT_TRUE(fs::exists(Paths[1]));
  894. EXPECT_TRUE(fs::exists(Paths[2]));
  895. EXPECT_TRUE(fs::exists(Paths[3]));
  896. ASSERT_NO_ERROR(fs::remove_directories("D:/footest"));
  897. ASSERT_NO_ERROR(fs::remove_directories(BaseDir));
  898. ASSERT_FALSE(fs::exists(BaseDir));
  899. }
  900. #ifdef _WIN32
  901. TEST_F(FileSystemTest, CarriageReturn) {
  902. SmallString<128> FilePathname(TestDirectory);
  903. std::error_code EC;
  904. path::append(FilePathname, "test");
  905. {
  906. raw_fd_ostream File(FilePathname, EC, sys::fs::F_Text);
  907. ASSERT_NO_ERROR(EC);
  908. File << '\n';
  909. }
  910. {
  911. auto Buf = MemoryBuffer::getFile(FilePathname.str());
  912. EXPECT_TRUE((bool)Buf);
  913. EXPECT_EQ(Buf.get()->getBuffer(), "\r\n");
  914. }
  915. {
  916. raw_fd_ostream File(FilePathname, EC, sys::fs::F_None);
  917. ASSERT_NO_ERROR(EC);
  918. File << '\n';
  919. }
  920. {
  921. auto Buf = MemoryBuffer::getFile(FilePathname.str());
  922. EXPECT_TRUE((bool)Buf);
  923. EXPECT_EQ(Buf.get()->getBuffer(), "\n");
  924. }
  925. ASSERT_NO_ERROR(fs::remove(Twine(FilePathname)));
  926. }
  927. #endif
  928. TEST_F(FileSystemTest, Resize) {
  929. int FD;
  930. SmallString<64> TempPath;
  931. ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
  932. ASSERT_NO_ERROR(fs::resize_file(FD, 123));
  933. fs::file_status Status;
  934. ASSERT_NO_ERROR(fs::status(FD, Status));
  935. ASSERT_EQ(Status.getSize(), 123U);
  936. ::close(FD);
  937. ASSERT_NO_ERROR(fs::remove(TempPath));
  938. }
  939. TEST_F(FileSystemTest, MD5) {
  940. int FD;
  941. SmallString<64> TempPath;
  942. ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
  943. StringRef Data("abcdefghijklmnopqrstuvwxyz");
  944. ASSERT_EQ(write(FD, Data.data(), Data.size()), static_cast<ssize_t>(Data.size()));
  945. lseek(FD, 0, SEEK_SET);
  946. auto Hash = fs::md5_contents(FD);
  947. ::close(FD);
  948. ASSERT_NO_ERROR(Hash.getError());
  949. EXPECT_STREQ("c3fcd3d76192e4007dfb496cca67e13b", Hash->digest().c_str());
  950. }
  951. TEST_F(FileSystemTest, FileMapping) {
  952. // Create a temp file.
  953. int FileDescriptor;
  954. SmallString<64> TempPath;
  955. ASSERT_NO_ERROR(
  956. fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
  957. unsigned Size = 4096;
  958. ASSERT_NO_ERROR(fs::resize_file(FileDescriptor, Size));
  959. // Map in temp file and add some content
  960. std::error_code EC;
  961. StringRef Val("hello there");
  962. {
  963. fs::mapped_file_region mfr(FileDescriptor,
  964. fs::mapped_file_region::readwrite, Size, 0, EC);
  965. ASSERT_NO_ERROR(EC);
  966. std::copy(Val.begin(), Val.end(), mfr.data());
  967. // Explicitly add a 0.
  968. mfr.data()[Val.size()] = 0;
  969. // Unmap temp file
  970. }
  971. ASSERT_EQ(close(FileDescriptor), 0);
  972. // Map it back in read-only
  973. {
  974. int FD;
  975. EC = fs::openFileForRead(Twine(TempPath), FD);
  976. ASSERT_NO_ERROR(EC);
  977. fs::mapped_file_region mfr(FD, fs::mapped_file_region::readonly, Size, 0, EC);
  978. ASSERT_NO_ERROR(EC);
  979. // Verify content
  980. EXPECT_EQ(StringRef(mfr.const_data()), Val);
  981. // Unmap temp file
  982. fs::mapped_file_region m(FD, fs::mapped_file_region::readonly, Size, 0, EC);
  983. ASSERT_NO_ERROR(EC);
  984. ASSERT_EQ(close(FD), 0);
  985. }
  986. ASSERT_NO_ERROR(fs::remove(TempPath));
  987. }
  988. TEST(Support, NormalizePath) {
  989. using TestTuple = std::tuple<const char *, const char *, const char *>;
  990. std::vector<TestTuple> Tests;
  991. Tests.emplace_back("a", "a", "a");
  992. Tests.emplace_back("a/b", "a\\b", "a/b");
  993. Tests.emplace_back("a\\b", "a\\b", "a/b");
  994. Tests.emplace_back("a\\\\b", "a\\\\b", "a\\\\b");
  995. Tests.emplace_back("\\a", "\\a", "/a");
  996. Tests.emplace_back("a\\", "a\\", "a/");
  997. for (auto &T : Tests) {
  998. SmallString<64> Win(std::get<0>(T));
  999. SmallString<64> Posix(Win);
  1000. path::native(Win, path::Style::windows);
  1001. path::native(Posix, path::Style::posix);
  1002. EXPECT_EQ(std::get<1>(T), Win);
  1003. EXPECT_EQ(std::get<2>(T), Posix);
  1004. }
  1005. #if defined(_WIN32)
  1006. SmallString<64> PathHome;
  1007. path::home_directory(PathHome);
  1008. const char *Path7a = "~/aaa";
  1009. SmallString<64> Path7(Path7a);
  1010. path::native(Path7);
  1011. EXPECT_TRUE(Path7.endswith("\\aaa"));
  1012. EXPECT_TRUE(Path7.startswith(PathHome));
  1013. EXPECT_EQ(Path7.size(), PathHome.size() + strlen(Path7a + 1));
  1014. const char *Path8a = "~";
  1015. SmallString<64> Path8(Path8a);
  1016. path::native(Path8);
  1017. EXPECT_EQ(Path8, PathHome);
  1018. const char *Path9a = "~aaa";
  1019. SmallString<64> Path9(Path9a);
  1020. path::native(Path9);
  1021. EXPECT_EQ(Path9, "~aaa");
  1022. const char *Path10a = "aaa/~/b";
  1023. SmallString<64> Path10(Path10a);
  1024. path::native(Path10);
  1025. EXPECT_EQ(Path10, "aaa\\~\\b");
  1026. #endif
  1027. }
  1028. TEST(Support, RemoveLeadingDotSlash) {
  1029. StringRef Path1("././/foolz/wat");
  1030. StringRef Path2("./////");
  1031. Path1 = path::remove_leading_dotslash(Path1);
  1032. EXPECT_EQ(Path1, "foolz/wat");
  1033. Path2 = path::remove_leading_dotslash(Path2);
  1034. EXPECT_EQ(Path2, "");
  1035. }
  1036. static std::string remove_dots(StringRef path, bool remove_dot_dot,
  1037. path::Style style) {
  1038. SmallString<256> buffer(path);
  1039. path::remove_dots(buffer, remove_dot_dot, style);
  1040. return buffer.str();
  1041. }
  1042. TEST(Support, RemoveDots) {
  1043. EXPECT_EQ("foolz\\wat",
  1044. remove_dots(".\\.\\\\foolz\\wat", false, path::Style::windows));
  1045. EXPECT_EQ("", remove_dots(".\\\\\\\\\\", false, path::Style::windows));
  1046. EXPECT_EQ("a\\..\\b\\c",
  1047. remove_dots(".\\a\\..\\b\\c", false, path::Style::windows));
  1048. EXPECT_EQ("b\\c", remove_dots(".\\a\\..\\b\\c", true, path::Style::windows));
  1049. EXPECT_EQ("c", remove_dots(".\\.\\c", true, path::Style::windows));
  1050. EXPECT_EQ("..\\a\\c",
  1051. remove_dots("..\\a\\b\\..\\c", true, path::Style::windows));
  1052. EXPECT_EQ("..\\..\\a\\c",
  1053. remove_dots("..\\..\\a\\b\\..\\c", true, path::Style::windows));
  1054. SmallString<64> Path1(".\\.\\c");
  1055. EXPECT_TRUE(path::remove_dots(Path1, true, path::Style::windows));
  1056. EXPECT_EQ("c", Path1);
  1057. EXPECT_EQ("foolz/wat",
  1058. remove_dots("././/foolz/wat", false, path::Style::posix));
  1059. EXPECT_EQ("", remove_dots("./////", false, path::Style::posix));
  1060. EXPECT_EQ("a/../b/c", remove_dots("./a/../b/c", false, path::Style::posix));
  1061. EXPECT_EQ("b/c", remove_dots("./a/../b/c", true, path::Style::posix));
  1062. EXPECT_EQ("c", remove_dots("././c", true, path::Style::posix));
  1063. EXPECT_EQ("../a/c", remove_dots("../a/b/../c", true, path::Style::posix));
  1064. EXPECT_EQ("../../a/c",
  1065. remove_dots("../../a/b/../c", true, path::Style::posix));
  1066. EXPECT_EQ("/a/c", remove_dots("/../../a/c", true, path::Style::posix));
  1067. EXPECT_EQ("/a/c",
  1068. remove_dots("/../a/b//../././/c", true, path::Style::posix));
  1069. SmallString<64> Path2("././c");
  1070. EXPECT_TRUE(path::remove_dots(Path2, true, path::Style::posix));
  1071. EXPECT_EQ("c", Path2);
  1072. }
  1073. TEST(Support, ReplacePathPrefix) {
  1074. SmallString<64> Path1("/foo");
  1075. SmallString<64> Path2("/old/foo");
  1076. SmallString<64> OldPrefix("/old");
  1077. SmallString<64> NewPrefix("/new");
  1078. SmallString<64> NewPrefix2("/longernew");
  1079. SmallString<64> EmptyPrefix("");
  1080. SmallString<64> Path = Path1;
  1081. path::replace_path_prefix(Path, OldPrefix, NewPrefix);
  1082. EXPECT_EQ(Path, "/foo");
  1083. Path = Path2;
  1084. path::replace_path_prefix(Path, OldPrefix, NewPrefix);
  1085. EXPECT_EQ(Path, "/new/foo");
  1086. Path = Path2;
  1087. path::replace_path_prefix(Path, OldPrefix, NewPrefix2);
  1088. EXPECT_EQ(Path, "/longernew/foo");
  1089. Path = Path1;
  1090. path::replace_path_prefix(Path, EmptyPrefix, NewPrefix);
  1091. EXPECT_EQ(Path, "/new/foo");
  1092. Path = Path2;
  1093. path::replace_path_prefix(Path, OldPrefix, EmptyPrefix);
  1094. EXPECT_EQ(Path, "/foo");
  1095. }
  1096. TEST_F(FileSystemTest, OpenFileForRead) {
  1097. // Create a temp file.
  1098. int FileDescriptor;
  1099. SmallString<64> TempPath;
  1100. ASSERT_NO_ERROR(
  1101. fs::createTemporaryFile("prefix", "temp", FileDescriptor, TempPath));
  1102. FileRemover Cleanup(TempPath);
  1103. // Make sure it exists.
  1104. ASSERT_TRUE(sys::fs::exists(Twine(TempPath)));
  1105. // Open the file for read
  1106. int FileDescriptor2;
  1107. SmallString<64> ResultPath;
  1108. ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath), FileDescriptor2,
  1109. fs::OF_None, &ResultPath))
  1110. // If we succeeded, check that the paths are the same (modulo case):
  1111. if (!ResultPath.empty()) {
  1112. // The paths returned by createTemporaryFile and getPathFromOpenFD
  1113. // should reference the same file on disk.
  1114. fs::UniqueID D1, D2;
  1115. ASSERT_NO_ERROR(fs::getUniqueID(Twine(TempPath), D1));
  1116. ASSERT_NO_ERROR(fs::getUniqueID(Twine(ResultPath), D2));
  1117. ASSERT_EQ(D1, D2);
  1118. }
  1119. ::close(FileDescriptor);
  1120. ::close(FileDescriptor2);
  1121. #ifdef _WIN32
  1122. // Since Windows Vista, file access time is not updated by default.
  1123. // This is instead updated manually by openFileForRead.
  1124. // https://blogs.technet.microsoft.com/filecab/2006/11/07/disabling-last-access-time-in-windows-vista-to-improve-ntfs-performance/
  1125. // This part of the unit test is Windows specific as the updating of
  1126. // access times can be disabled on Linux using /etc/fstab.
  1127. // Set access time to UNIX epoch.
  1128. ASSERT_NO_ERROR(sys::fs::openFileForWrite(Twine(TempPath), FileDescriptor,
  1129. fs::CD_OpenExisting));
  1130. TimePoint<> Epoch(std::chrono::milliseconds(0));
  1131. ASSERT_NO_ERROR(fs::setLastAccessAndModificationTime(FileDescriptor, Epoch));
  1132. ::close(FileDescriptor);
  1133. // Open the file and ensure access time is updated, when forced.
  1134. ASSERT_NO_ERROR(fs::openFileForRead(Twine(TempPath), FileDescriptor,
  1135. fs::OF_UpdateAtime, &ResultPath));
  1136. sys::fs::file_status Status;
  1137. ASSERT_NO_ERROR(sys::fs::status(FileDescriptor, Status));
  1138. auto FileAccessTime = Status.getLastAccessedTime();
  1139. ASSERT_NE(Epoch, FileAccessTime);
  1140. ::close(FileDescriptor);
  1141. // Ideally this test would include a case when ATime is not forced to update,
  1142. // however the expected behaviour will differ depending on the configuration
  1143. // of the Windows file system.
  1144. #endif
  1145. }
  1146. static void createFileWithData(const Twine &Path, bool ShouldExistBefore,
  1147. fs::CreationDisposition Disp, StringRef Data) {
  1148. int FD;
  1149. ASSERT_EQ(ShouldExistBefore, fs::exists(Path));
  1150. ASSERT_NO_ERROR(fs::openFileForWrite(Path, FD, Disp));
  1151. FileDescriptorCloser Closer(FD);
  1152. ASSERT_TRUE(fs::exists(Path));
  1153. ASSERT_EQ(Data.size(), (size_t)write(FD, Data.data(), Data.size()));
  1154. }
  1155. static void verifyFileContents(const Twine &Path, StringRef Contents) {
  1156. auto Buffer = MemoryBuffer::getFile(Path);
  1157. ASSERT_TRUE((bool)Buffer);
  1158. StringRef Data = Buffer.get()->getBuffer();
  1159. ASSERT_EQ(Data, Contents);
  1160. }
  1161. TEST_F(FileSystemTest, CreateNew) {
  1162. int FD;
  1163. Optional<FileDescriptorCloser> Closer;
  1164. // Succeeds if the file does not exist.
  1165. ASSERT_FALSE(fs::exists(NonExistantFile));
  1166. ASSERT_NO_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateNew));
  1167. ASSERT_TRUE(fs::exists(NonExistantFile));
  1168. FileRemover Cleanup(NonExistantFile);
  1169. Closer.emplace(FD);
  1170. // And creates a file of size 0.
  1171. sys::fs::file_status Status;
  1172. ASSERT_NO_ERROR(sys::fs::status(FD, Status));
  1173. EXPECT_EQ(0ULL, Status.getSize());
  1174. // Close this first, before trying to re-open the file.
  1175. Closer.reset();
  1176. // But fails if the file does exist.
  1177. ASSERT_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateNew));
  1178. }
  1179. TEST_F(FileSystemTest, CreateAlways) {
  1180. int FD;
  1181. Optional<FileDescriptorCloser> Closer;
  1182. // Succeeds if the file does not exist.
  1183. ASSERT_FALSE(fs::exists(NonExistantFile));
  1184. ASSERT_NO_ERROR(
  1185. fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateAlways));
  1186. Closer.emplace(FD);
  1187. ASSERT_TRUE(fs::exists(NonExistantFile));
  1188. FileRemover Cleanup(NonExistantFile);
  1189. // And creates a file of size 0.
  1190. uint64_t FileSize;
  1191. ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
  1192. ASSERT_EQ(0ULL, FileSize);
  1193. // If we write some data to it re-create it with CreateAlways, it succeeds and
  1194. // truncates to 0 bytes.
  1195. ASSERT_EQ(4, write(FD, "Test", 4));
  1196. Closer.reset();
  1197. ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
  1198. ASSERT_EQ(4ULL, FileSize);
  1199. ASSERT_NO_ERROR(
  1200. fs::openFileForWrite(NonExistantFile, FD, fs::CD_CreateAlways));
  1201. Closer.emplace(FD);
  1202. ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
  1203. ASSERT_EQ(0ULL, FileSize);
  1204. }
  1205. TEST_F(FileSystemTest, OpenExisting) {
  1206. int FD;
  1207. // Fails if the file does not exist.
  1208. ASSERT_FALSE(fs::exists(NonExistantFile));
  1209. ASSERT_ERROR(fs::openFileForWrite(NonExistantFile, FD, fs::CD_OpenExisting));
  1210. ASSERT_FALSE(fs::exists(NonExistantFile));
  1211. // Make a dummy file now so that we can try again when the file does exist.
  1212. createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
  1213. FileRemover Cleanup(NonExistantFile);
  1214. uint64_t FileSize;
  1215. ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
  1216. ASSERT_EQ(4ULL, FileSize);
  1217. // If we re-create it with different data, it overwrites rather than
  1218. // appending.
  1219. createFileWithData(NonExistantFile, true, fs::CD_OpenExisting, "Buzz");
  1220. verifyFileContents(NonExistantFile, "Buzz");
  1221. }
  1222. TEST_F(FileSystemTest, OpenAlways) {
  1223. // Succeeds if the file does not exist.
  1224. createFileWithData(NonExistantFile, false, fs::CD_OpenAlways, "Fizz");
  1225. FileRemover Cleanup(NonExistantFile);
  1226. uint64_t FileSize;
  1227. ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
  1228. ASSERT_EQ(4ULL, FileSize);
  1229. // Now re-open it and write again, verifying the contents get over-written.
  1230. createFileWithData(NonExistantFile, true, fs::CD_OpenAlways, "Bu");
  1231. verifyFileContents(NonExistantFile, "Buzz");
  1232. }
  1233. TEST_F(FileSystemTest, AppendSetsCorrectFileOffset) {
  1234. fs::CreationDisposition Disps[] = {fs::CD_CreateAlways, fs::CD_OpenAlways,
  1235. fs::CD_OpenExisting};
  1236. // Write some data and re-open it with every possible disposition (this is a
  1237. // hack that shouldn't work, but is left for compatibility. F_Append
  1238. // overrides
  1239. // the specified disposition.
  1240. for (fs::CreationDisposition Disp : Disps) {
  1241. int FD;
  1242. Optional<FileDescriptorCloser> Closer;
  1243. createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
  1244. FileRemover Cleanup(NonExistantFile);
  1245. uint64_t FileSize;
  1246. ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
  1247. ASSERT_EQ(4ULL, FileSize);
  1248. ASSERT_NO_ERROR(
  1249. fs::openFileForWrite(NonExistantFile, FD, Disp, fs::OF_Append));
  1250. Closer.emplace(FD);
  1251. ASSERT_NO_ERROR(sys::fs::file_size(NonExistantFile, FileSize));
  1252. ASSERT_EQ(4ULL, FileSize);
  1253. ASSERT_EQ(4, write(FD, "Buzz", 4));
  1254. Closer.reset();
  1255. verifyFileContents(NonExistantFile, "FizzBuzz");
  1256. }
  1257. }
  1258. static void verifyRead(int FD, StringRef Data, bool ShouldSucceed) {
  1259. std::vector<char> Buffer;
  1260. Buffer.resize(Data.size());
  1261. int Result = ::read(FD, Buffer.data(), Buffer.size());
  1262. if (ShouldSucceed) {
  1263. ASSERT_EQ((size_t)Result, Data.size());
  1264. ASSERT_EQ(Data, StringRef(Buffer.data(), Buffer.size()));
  1265. } else {
  1266. ASSERT_EQ(-1, Result);
  1267. ASSERT_EQ(EBADF, errno);
  1268. }
  1269. }
  1270. static void verifyWrite(int FD, StringRef Data, bool ShouldSucceed) {
  1271. int Result = ::write(FD, Data.data(), Data.size());
  1272. if (ShouldSucceed)
  1273. ASSERT_EQ((size_t)Result, Data.size());
  1274. else {
  1275. ASSERT_EQ(-1, Result);
  1276. ASSERT_EQ(EBADF, errno);
  1277. }
  1278. }
  1279. TEST_F(FileSystemTest, ReadOnlyFileCantWrite) {
  1280. createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
  1281. FileRemover Cleanup(NonExistantFile);
  1282. int FD;
  1283. ASSERT_NO_ERROR(fs::openFileForRead(NonExistantFile, FD));
  1284. FileDescriptorCloser Closer(FD);
  1285. verifyWrite(FD, "Buzz", false);
  1286. verifyRead(FD, "Fizz", true);
  1287. }
  1288. TEST_F(FileSystemTest, WriteOnlyFileCantRead) {
  1289. createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
  1290. FileRemover Cleanup(NonExistantFile);
  1291. int FD;
  1292. ASSERT_NO_ERROR(
  1293. fs::openFileForWrite(NonExistantFile, FD, fs::CD_OpenExisting));
  1294. FileDescriptorCloser Closer(FD);
  1295. verifyRead(FD, "Fizz", false);
  1296. verifyWrite(FD, "Buzz", true);
  1297. }
  1298. TEST_F(FileSystemTest, ReadWriteFileCanReadOrWrite) {
  1299. createFileWithData(NonExistantFile, false, fs::CD_CreateNew, "Fizz");
  1300. FileRemover Cleanup(NonExistantFile);
  1301. int FD;
  1302. ASSERT_NO_ERROR(fs::openFileForReadWrite(NonExistantFile, FD,
  1303. fs::CD_OpenExisting, fs::OF_None));
  1304. FileDescriptorCloser Closer(FD);
  1305. verifyRead(FD, "Fizz", true);
  1306. verifyWrite(FD, "Buzz", true);
  1307. }
  1308. TEST_F(FileSystemTest, set_current_path) {
  1309. SmallString<128> path;
  1310. ASSERT_NO_ERROR(fs::current_path(path));
  1311. ASSERT_NE(TestDirectory, path);
  1312. struct RestorePath {
  1313. SmallString<128> path;
  1314. RestorePath(const SmallString<128> &path) : path(path) {}
  1315. ~RestorePath() { fs::set_current_path(path); }
  1316. } restore_path(path);
  1317. ASSERT_NO_ERROR(fs::set_current_path(TestDirectory));
  1318. ASSERT_NO_ERROR(fs::current_path(path));
  1319. fs::UniqueID D1, D2;
  1320. ASSERT_NO_ERROR(fs::getUniqueID(TestDirectory, D1));
  1321. ASSERT_NO_ERROR(fs::getUniqueID(path, D2));
  1322. ASSERT_EQ(D1, D2) << "D1: " << TestDirectory << "\nD2: " << path;
  1323. }
  1324. TEST_F(FileSystemTest, permissions) {
  1325. int FD;
  1326. SmallString<64> TempPath;
  1327. ASSERT_NO_ERROR(fs::createTemporaryFile("prefix", "temp", FD, TempPath));
  1328. FileRemover Cleanup(TempPath);
  1329. // Make sure it exists.
  1330. ASSERT_TRUE(fs::exists(Twine(TempPath)));
  1331. auto CheckPermissions = [&](fs::perms Expected) {
  1332. ErrorOr<fs::perms> Actual = fs::getPermissions(TempPath);
  1333. return Actual && *Actual == Expected;
  1334. };
  1335. std::error_code NoError;
  1336. EXPECT_EQ(fs::setPermissions(TempPath, fs::all_all), NoError);
  1337. EXPECT_TRUE(CheckPermissions(fs::all_all));
  1338. EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read | fs::all_exe), NoError);
  1339. EXPECT_TRUE(CheckPermissions(fs::all_read | fs::all_exe));
  1340. #if defined(_WIN32)
  1341. fs::perms ReadOnly = fs::all_read | fs::all_exe;
  1342. EXPECT_EQ(fs::setPermissions(TempPath, fs::no_perms), NoError);
  1343. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1344. EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_read), NoError);
  1345. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1346. EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_write), NoError);
  1347. EXPECT_TRUE(CheckPermissions(fs::all_all));
  1348. EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_exe), NoError);
  1349. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1350. EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_all), NoError);
  1351. EXPECT_TRUE(CheckPermissions(fs::all_all));
  1352. EXPECT_EQ(fs::setPermissions(TempPath, fs::group_read), NoError);
  1353. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1354. EXPECT_EQ(fs::setPermissions(TempPath, fs::group_write), NoError);
  1355. EXPECT_TRUE(CheckPermissions(fs::all_all));
  1356. EXPECT_EQ(fs::setPermissions(TempPath, fs::group_exe), NoError);
  1357. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1358. EXPECT_EQ(fs::setPermissions(TempPath, fs::group_all), NoError);
  1359. EXPECT_TRUE(CheckPermissions(fs::all_all));
  1360. EXPECT_EQ(fs::setPermissions(TempPath, fs::others_read), NoError);
  1361. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1362. EXPECT_EQ(fs::setPermissions(TempPath, fs::others_write), NoError);
  1363. EXPECT_TRUE(CheckPermissions(fs::all_all));
  1364. EXPECT_EQ(fs::setPermissions(TempPath, fs::others_exe), NoError);
  1365. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1366. EXPECT_EQ(fs::setPermissions(TempPath, fs::others_all), NoError);
  1367. EXPECT_TRUE(CheckPermissions(fs::all_all));
  1368. EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read), NoError);
  1369. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1370. EXPECT_EQ(fs::setPermissions(TempPath, fs::all_write), NoError);
  1371. EXPECT_TRUE(CheckPermissions(fs::all_all));
  1372. EXPECT_EQ(fs::setPermissions(TempPath, fs::all_exe), NoError);
  1373. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1374. EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe), NoError);
  1375. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1376. EXPECT_EQ(fs::setPermissions(TempPath, fs::set_gid_on_exe), NoError);
  1377. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1378. EXPECT_EQ(fs::setPermissions(TempPath, fs::sticky_bit), NoError);
  1379. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1380. EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe |
  1381. fs::set_gid_on_exe |
  1382. fs::sticky_bit),
  1383. NoError);
  1384. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1385. EXPECT_EQ(fs::setPermissions(TempPath, ReadOnly | fs::set_uid_on_exe |
  1386. fs::set_gid_on_exe |
  1387. fs::sticky_bit),
  1388. NoError);
  1389. EXPECT_TRUE(CheckPermissions(ReadOnly));
  1390. EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms), NoError);
  1391. EXPECT_TRUE(CheckPermissions(fs::all_all));
  1392. #else
  1393. EXPECT_EQ(fs::setPermissions(TempPath, fs::no_perms), NoError);
  1394. EXPECT_TRUE(CheckPermissions(fs::no_perms));
  1395. EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_read), NoError);
  1396. EXPECT_TRUE(CheckPermissions(fs::owner_read));
  1397. EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_write), NoError);
  1398. EXPECT_TRUE(CheckPermissions(fs::owner_write));
  1399. EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_exe), NoError);
  1400. EXPECT_TRUE(CheckPermissions(fs::owner_exe));
  1401. EXPECT_EQ(fs::setPermissions(TempPath, fs::owner_all), NoError);
  1402. EXPECT_TRUE(CheckPermissions(fs::owner_all));
  1403. EXPECT_EQ(fs::setPermissions(TempPath, fs::group_read), NoError);
  1404. EXPECT_TRUE(CheckPermissions(fs::group_read));
  1405. EXPECT_EQ(fs::setPermissions(TempPath, fs::group_write), NoError);
  1406. EXPECT_TRUE(CheckPermissions(fs::group_write));
  1407. EXPECT_EQ(fs::setPermissions(TempPath, fs::group_exe), NoError);
  1408. EXPECT_TRUE(CheckPermissions(fs::group_exe));
  1409. EXPECT_EQ(fs::setPermissions(TempPath, fs::group_all), NoError);
  1410. EXPECT_TRUE(CheckPermissions(fs::group_all));
  1411. EXPECT_EQ(fs::setPermissions(TempPath, fs::others_read), NoError);
  1412. EXPECT_TRUE(CheckPermissions(fs::others_read));
  1413. EXPECT_EQ(fs::setPermissions(TempPath, fs::others_write), NoError);
  1414. EXPECT_TRUE(CheckPermissions(fs::others_write));
  1415. EXPECT_EQ(fs::setPermissions(TempPath, fs::others_exe), NoError);
  1416. EXPECT_TRUE(CheckPermissions(fs::others_exe));
  1417. EXPECT_EQ(fs::setPermissions(TempPath, fs::others_all), NoError);
  1418. EXPECT_TRUE(CheckPermissions(fs::others_all));
  1419. EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read), NoError);
  1420. EXPECT_TRUE(CheckPermissions(fs::all_read));
  1421. EXPECT_EQ(fs::setPermissions(TempPath, fs::all_write), NoError);
  1422. EXPECT_TRUE(CheckPermissions(fs::all_write));
  1423. EXPECT_EQ(fs::setPermissions(TempPath, fs::all_exe), NoError);
  1424. EXPECT_TRUE(CheckPermissions(fs::all_exe));
  1425. EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe), NoError);
  1426. EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe));
  1427. EXPECT_EQ(fs::setPermissions(TempPath, fs::set_gid_on_exe), NoError);
  1428. EXPECT_TRUE(CheckPermissions(fs::set_gid_on_exe));
  1429. // Modern BSDs require root to set the sticky bit on files.
  1430. #if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__)
  1431. EXPECT_EQ(fs::setPermissions(TempPath, fs::sticky_bit), NoError);
  1432. EXPECT_TRUE(CheckPermissions(fs::sticky_bit));
  1433. EXPECT_EQ(fs::setPermissions(TempPath, fs::set_uid_on_exe |
  1434. fs::set_gid_on_exe |
  1435. fs::sticky_bit),
  1436. NoError);
  1437. EXPECT_TRUE(CheckPermissions(fs::set_uid_on_exe | fs::set_gid_on_exe |
  1438. fs::sticky_bit));
  1439. EXPECT_EQ(fs::setPermissions(TempPath, fs::all_read | fs::set_uid_on_exe |
  1440. fs::set_gid_on_exe |
  1441. fs::sticky_bit),
  1442. NoError);
  1443. EXPECT_TRUE(CheckPermissions(fs::all_read | fs::set_uid_on_exe |
  1444. fs::set_gid_on_exe | fs::sticky_bit));
  1445. EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms), NoError);
  1446. EXPECT_TRUE(CheckPermissions(fs::all_perms));
  1447. #endif // !FreeBSD && !NetBSD && !OpenBSD
  1448. EXPECT_EQ(fs::setPermissions(TempPath, fs::all_perms & ~fs::sticky_bit),
  1449. NoError);
  1450. EXPECT_TRUE(CheckPermissions(fs::all_perms & ~fs::sticky_bit));
  1451. #endif
  1452. }
  1453. } // anonymous namespace