Path.cpp 60 KB

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