Path.cpp 63 KB

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