Path.cpp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  1. //===-- Path.cpp - Implement OS Path Concept ------------------------------===//
  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. //
  10. // This file implements the operating system Path API.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Support/Path.h"
  14. #include "llvm/ADT/ArrayRef.h"
  15. #include "llvm/Config/llvm-config.h"
  16. #include "llvm/Support/Endian.h"
  17. #include "llvm/Support/Errc.h"
  18. #include "llvm/Support/ErrorHandling.h"
  19. #include "llvm/Support/FileSystem.h"
  20. #include "llvm/Support/Process.h"
  21. #include "llvm/Support/Signals.h"
  22. #include <cctype>
  23. #include <cstring>
  24. #if !defined(_MSC_VER) && !defined(__MINGW32__)
  25. #include <unistd.h>
  26. #else
  27. #include <io.h>
  28. #endif
  29. using namespace llvm;
  30. using namespace llvm::support::endian;
  31. namespace {
  32. using llvm::StringRef;
  33. using llvm::sys::path::is_separator;
  34. using llvm::sys::path::Style;
  35. inline Style real_style(Style style) {
  36. #ifdef _WIN32
  37. return (style == Style::posix) ? Style::posix : Style::windows;
  38. #else
  39. return (style == Style::windows) ? Style::windows : Style::posix;
  40. #endif
  41. }
  42. inline const char *separators(Style style) {
  43. if (real_style(style) == Style::windows)
  44. return "\\/";
  45. return "/";
  46. }
  47. inline char preferred_separator(Style style) {
  48. if (real_style(style) == Style::windows)
  49. return '\\';
  50. return '/';
  51. }
  52. StringRef find_first_component(StringRef path, Style style) {
  53. // Look for this first component in the following order.
  54. // * empty (in this case we return an empty string)
  55. // * either C: or {//,\\}net.
  56. // * {/,\}
  57. // * {file,directory}name
  58. if (path.empty())
  59. return path;
  60. if (real_style(style) == Style::windows) {
  61. // C:
  62. if (path.size() >= 2 &&
  63. std::isalpha(static_cast<unsigned char>(path[0])) && path[1] == ':')
  64. return path.substr(0, 2);
  65. }
  66. // //net
  67. if ((path.size() > 2) && is_separator(path[0], style) &&
  68. path[0] == path[1] && !is_separator(path[2], style)) {
  69. // Find the next directory separator.
  70. size_t end = path.find_first_of(separators(style), 2);
  71. return path.substr(0, end);
  72. }
  73. // {/,\}
  74. if (is_separator(path[0], style))
  75. return path.substr(0, 1);
  76. // * {file,directory}name
  77. size_t end = path.find_first_of(separators(style));
  78. return path.substr(0, end);
  79. }
  80. // Returns the first character of the filename in str. For paths ending in
  81. // '/', it returns the position of the '/'.
  82. size_t filename_pos(StringRef str, Style style) {
  83. if (str.size() > 0 && is_separator(str[str.size() - 1], style))
  84. return str.size() - 1;
  85. size_t pos = str.find_last_of(separators(style), str.size() - 1);
  86. if (real_style(style) == Style::windows) {
  87. if (pos == StringRef::npos)
  88. pos = str.find_last_of(':', str.size() - 2);
  89. }
  90. if (pos == StringRef::npos || (pos == 1 && is_separator(str[0], style)))
  91. return 0;
  92. return pos + 1;
  93. }
  94. // Returns the position of the root directory in str. If there is no root
  95. // directory in str, it returns StringRef::npos.
  96. size_t root_dir_start(StringRef str, Style style) {
  97. // case "c:/"
  98. if (real_style(style) == Style::windows) {
  99. if (str.size() > 2 && str[1] == ':' && is_separator(str[2], style))
  100. return 2;
  101. }
  102. // case "//net"
  103. if (str.size() > 3 && is_separator(str[0], style) && str[0] == str[1] &&
  104. !is_separator(str[2], style)) {
  105. return str.find_first_of(separators(style), 2);
  106. }
  107. // case "/"
  108. if (str.size() > 0 && is_separator(str[0], style))
  109. return 0;
  110. return StringRef::npos;
  111. }
  112. // Returns the position past the end of the "parent path" of path. The parent
  113. // path will not end in '/', unless the parent is the root directory. If the
  114. // path has no parent, 0 is returned.
  115. size_t parent_path_end(StringRef path, Style style) {
  116. size_t end_pos = filename_pos(path, style);
  117. bool filename_was_sep =
  118. path.size() > 0 && is_separator(path[end_pos], style);
  119. // Skip separators until we reach root dir (or the start of the string).
  120. size_t root_dir_pos = root_dir_start(path, style);
  121. while (end_pos > 0 &&
  122. (root_dir_pos == StringRef::npos || end_pos > root_dir_pos) &&
  123. is_separator(path[end_pos - 1], style))
  124. --end_pos;
  125. if (end_pos == root_dir_pos && !filename_was_sep) {
  126. // We've reached the root dir and the input path was *not* ending in a
  127. // sequence of slashes. Include the root dir in the parent path.
  128. return root_dir_pos + 1;
  129. }
  130. // Otherwise, just include before the last slash.
  131. return end_pos;
  132. }
  133. } // end unnamed namespace
  134. enum FSEntity {
  135. FS_Dir,
  136. FS_File,
  137. FS_Name
  138. };
  139. static std::error_code
  140. createUniqueEntity(const Twine &Model, int &ResultFD,
  141. SmallVectorImpl<char> &ResultPath, bool MakeAbsolute,
  142. unsigned Mode, FSEntity Type,
  143. sys::fs::OpenFlags Flags = sys::fs::OF_None) {
  144. SmallString<128> ModelStorage;
  145. Model.toVector(ModelStorage);
  146. if (MakeAbsolute) {
  147. // Make model absolute by prepending a temp directory if it's not already.
  148. if (!sys::path::is_absolute(Twine(ModelStorage))) {
  149. SmallString<128> TDir;
  150. sys::path::system_temp_directory(true, TDir);
  151. sys::path::append(TDir, Twine(ModelStorage));
  152. ModelStorage.swap(TDir);
  153. }
  154. }
  155. // From here on, DO NOT modify model. It may be needed if the randomly chosen
  156. // path already exists.
  157. ResultPath = ModelStorage;
  158. // Null terminate.
  159. ResultPath.push_back(0);
  160. ResultPath.pop_back();
  161. // Limit the number of attempts we make, so that we don't infinite loop. E.g.
  162. // "permission denied" could be for a specific file (so we retry with a
  163. // different name) or for the whole directory (retry would always fail).
  164. // Checking which is racy, so we try a number of times, then give up.
  165. std::error_code EC;
  166. for (int Retries = 128; Retries > 0; --Retries) {
  167. // Replace '%' with random chars.
  168. for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
  169. if (ModelStorage[i] == '%')
  170. ResultPath[i] =
  171. "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
  172. }
  173. // Try to open + create the file.
  174. switch (Type) {
  175. case FS_File: {
  176. EC = sys::fs::openFileForReadWrite(Twine(ResultPath.begin()), ResultFD,
  177. sys::fs::CD_CreateNew, Flags, Mode);
  178. if (EC) {
  179. // errc::permission_denied happens on Windows when we try to open a file
  180. // that has been marked for deletion.
  181. if (EC == errc::file_exists || EC == errc::permission_denied)
  182. continue;
  183. return EC;
  184. }
  185. return std::error_code();
  186. }
  187. case FS_Name: {
  188. EC = sys::fs::access(ResultPath.begin(), sys::fs::AccessMode::Exist);
  189. if (EC == errc::no_such_file_or_directory)
  190. return std::error_code();
  191. if (EC)
  192. return EC;
  193. continue;
  194. }
  195. case FS_Dir: {
  196. EC = sys::fs::create_directory(ResultPath.begin(), false);
  197. if (EC) {
  198. if (EC == errc::file_exists)
  199. continue;
  200. return EC;
  201. }
  202. return std::error_code();
  203. }
  204. }
  205. llvm_unreachable("Invalid Type");
  206. }
  207. return EC;
  208. }
  209. namespace llvm {
  210. namespace sys {
  211. namespace path {
  212. const_iterator begin(StringRef path, Style style) {
  213. const_iterator i;
  214. i.Path = path;
  215. i.Component = find_first_component(path, style);
  216. i.Position = 0;
  217. i.S = style;
  218. return i;
  219. }
  220. const_iterator end(StringRef path) {
  221. const_iterator i;
  222. i.Path = path;
  223. i.Position = path.size();
  224. return i;
  225. }
  226. const_iterator &const_iterator::operator++() {
  227. assert(Position < Path.size() && "Tried to increment past end!");
  228. // Increment Position to past the current component
  229. Position += Component.size();
  230. // Check for end.
  231. if (Position == Path.size()) {
  232. Component = StringRef();
  233. return *this;
  234. }
  235. // Both POSIX and Windows treat paths that begin with exactly two separators
  236. // specially.
  237. bool was_net = Component.size() > 2 && is_separator(Component[0], S) &&
  238. Component[1] == Component[0] && !is_separator(Component[2], S);
  239. // Handle separators.
  240. if (is_separator(Path[Position], S)) {
  241. // Root dir.
  242. if (was_net ||
  243. // c:/
  244. (real_style(S) == Style::windows && Component.endswith(":"))) {
  245. Component = Path.substr(Position, 1);
  246. return *this;
  247. }
  248. // Skip extra separators.
  249. while (Position != Path.size() && is_separator(Path[Position], S)) {
  250. ++Position;
  251. }
  252. // Treat trailing '/' as a '.', unless it is the root dir.
  253. if (Position == Path.size() && Component != "/") {
  254. --Position;
  255. Component = ".";
  256. return *this;
  257. }
  258. }
  259. // Find next component.
  260. size_t end_pos = Path.find_first_of(separators(S), Position);
  261. Component = Path.slice(Position, end_pos);
  262. return *this;
  263. }
  264. bool const_iterator::operator==(const const_iterator &RHS) const {
  265. return Path.begin() == RHS.Path.begin() && Position == RHS.Position;
  266. }
  267. ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
  268. return Position - RHS.Position;
  269. }
  270. reverse_iterator rbegin(StringRef Path, Style style) {
  271. reverse_iterator I;
  272. I.Path = Path;
  273. I.Position = Path.size();
  274. I.S = style;
  275. return ++I;
  276. }
  277. reverse_iterator rend(StringRef Path) {
  278. reverse_iterator I;
  279. I.Path = Path;
  280. I.Component = Path.substr(0, 0);
  281. I.Position = 0;
  282. return I;
  283. }
  284. reverse_iterator &reverse_iterator::operator++() {
  285. size_t root_dir_pos = root_dir_start(Path, S);
  286. // Skip separators unless it's the root directory.
  287. size_t end_pos = Position;
  288. while (end_pos > 0 && (end_pos - 1) != root_dir_pos &&
  289. is_separator(Path[end_pos - 1], S))
  290. --end_pos;
  291. // Treat trailing '/' as a '.', unless it is the root dir.
  292. if (Position == Path.size() && !Path.empty() &&
  293. is_separator(Path.back(), S) &&
  294. (root_dir_pos == StringRef::npos || end_pos - 1 > root_dir_pos)) {
  295. --Position;
  296. Component = ".";
  297. return *this;
  298. }
  299. // Find next separator.
  300. size_t start_pos = filename_pos(Path.substr(0, end_pos), S);
  301. Component = Path.slice(start_pos, end_pos);
  302. Position = start_pos;
  303. return *this;
  304. }
  305. bool reverse_iterator::operator==(const reverse_iterator &RHS) const {
  306. return Path.begin() == RHS.Path.begin() && Component == RHS.Component &&
  307. Position == RHS.Position;
  308. }
  309. ptrdiff_t reverse_iterator::operator-(const reverse_iterator &RHS) const {
  310. return Position - RHS.Position;
  311. }
  312. StringRef root_path(StringRef path, Style style) {
  313. const_iterator b = begin(path, style), pos = b, e = end(path);
  314. if (b != e) {
  315. bool has_net =
  316. b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
  317. bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
  318. if (has_net || has_drive) {
  319. if ((++pos != e) && is_separator((*pos)[0], style)) {
  320. // {C:/,//net/}, so get the first two components.
  321. return path.substr(0, b->size() + pos->size());
  322. } else {
  323. // just {C:,//net}, return the first component.
  324. return *b;
  325. }
  326. }
  327. // POSIX style root directory.
  328. if (is_separator((*b)[0], style)) {
  329. return *b;
  330. }
  331. }
  332. return StringRef();
  333. }
  334. StringRef root_name(StringRef path, Style style) {
  335. const_iterator b = begin(path, style), e = end(path);
  336. if (b != e) {
  337. bool has_net =
  338. b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
  339. bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
  340. if (has_net || has_drive) {
  341. // just {C:,//net}, return the first component.
  342. return *b;
  343. }
  344. }
  345. // No path or no name.
  346. return StringRef();
  347. }
  348. StringRef root_directory(StringRef path, Style style) {
  349. const_iterator b = begin(path, style), pos = b, e = end(path);
  350. if (b != e) {
  351. bool has_net =
  352. b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
  353. bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
  354. if ((has_net || has_drive) &&
  355. // {C:,//net}, skip to the next component.
  356. (++pos != e) && is_separator((*pos)[0], style)) {
  357. return *pos;
  358. }
  359. // POSIX style root directory.
  360. if (!has_net && is_separator((*b)[0], style)) {
  361. return *b;
  362. }
  363. }
  364. // No path or no root.
  365. return StringRef();
  366. }
  367. StringRef relative_path(StringRef path, Style style) {
  368. StringRef root = root_path(path, style);
  369. return path.substr(root.size());
  370. }
  371. void append(SmallVectorImpl<char> &path, Style style, const Twine &a,
  372. const Twine &b, const Twine &c, const Twine &d) {
  373. SmallString<32> a_storage;
  374. SmallString<32> b_storage;
  375. SmallString<32> c_storage;
  376. SmallString<32> d_storage;
  377. SmallVector<StringRef, 4> components;
  378. if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage));
  379. if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage));
  380. if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage));
  381. if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage));
  382. for (auto &component : components) {
  383. bool path_has_sep =
  384. !path.empty() && is_separator(path[path.size() - 1], style);
  385. if (path_has_sep) {
  386. // Strip separators from beginning of component.
  387. size_t loc = component.find_first_not_of(separators(style));
  388. StringRef c = component.substr(loc);
  389. // Append it.
  390. path.append(c.begin(), c.end());
  391. continue;
  392. }
  393. bool component_has_sep =
  394. !component.empty() && is_separator(component[0], style);
  395. if (!component_has_sep &&
  396. !(path.empty() || has_root_name(component, style))) {
  397. // Add a separator.
  398. path.push_back(preferred_separator(style));
  399. }
  400. path.append(component.begin(), component.end());
  401. }
  402. }
  403. void append(SmallVectorImpl<char> &path, const Twine &a, const Twine &b,
  404. const Twine &c, const Twine &d) {
  405. append(path, Style::native, a, b, c, d);
  406. }
  407. void append(SmallVectorImpl<char> &path, const_iterator begin,
  408. const_iterator end, Style style) {
  409. for (; begin != end; ++begin)
  410. path::append(path, style, *begin);
  411. }
  412. StringRef parent_path(StringRef path, Style style) {
  413. size_t end_pos = parent_path_end(path, style);
  414. if (end_pos == StringRef::npos)
  415. return StringRef();
  416. else
  417. return path.substr(0, end_pos);
  418. }
  419. void remove_filename(SmallVectorImpl<char> &path, Style style) {
  420. size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()), style);
  421. if (end_pos != StringRef::npos)
  422. path.set_size(end_pos);
  423. }
  424. void replace_extension(SmallVectorImpl<char> &path, const Twine &extension,
  425. Style style) {
  426. StringRef p(path.begin(), path.size());
  427. SmallString<32> ext_storage;
  428. StringRef ext = extension.toStringRef(ext_storage);
  429. // Erase existing extension.
  430. size_t pos = p.find_last_of('.');
  431. if (pos != StringRef::npos && pos >= filename_pos(p, style))
  432. path.set_size(pos);
  433. // Append '.' if needed.
  434. if (ext.size() > 0 && ext[0] != '.')
  435. path.push_back('.');
  436. // Append extension.
  437. path.append(ext.begin(), ext.end());
  438. }
  439. void replace_path_prefix(SmallVectorImpl<char> &Path,
  440. const StringRef &OldPrefix, const StringRef &NewPrefix,
  441. Style style) {
  442. if (OldPrefix.empty() && NewPrefix.empty())
  443. return;
  444. StringRef OrigPath(Path.begin(), Path.size());
  445. if (!OrigPath.startswith(OldPrefix))
  446. return;
  447. // If prefixes have the same size we can simply copy the new one over.
  448. if (OldPrefix.size() == NewPrefix.size()) {
  449. std::copy(NewPrefix.begin(), NewPrefix.end(), Path.begin());
  450. return;
  451. }
  452. StringRef RelPath = OrigPath.substr(OldPrefix.size());
  453. SmallString<256> NewPath;
  454. path::append(NewPath, style, NewPrefix);
  455. path::append(NewPath, style, RelPath);
  456. Path.swap(NewPath);
  457. }
  458. void native(const Twine &path, SmallVectorImpl<char> &result, Style style) {
  459. assert((!path.isSingleStringRef() ||
  460. path.getSingleStringRef().data() != result.data()) &&
  461. "path and result are not allowed to overlap!");
  462. // Clear result.
  463. result.clear();
  464. path.toVector(result);
  465. native(result, style);
  466. }
  467. void native(SmallVectorImpl<char> &Path, Style style) {
  468. if (Path.empty())
  469. return;
  470. if (real_style(style) == Style::windows) {
  471. std::replace(Path.begin(), Path.end(), '/', '\\');
  472. if (Path[0] == '~' && (Path.size() == 1 || is_separator(Path[1], style))) {
  473. SmallString<128> PathHome;
  474. home_directory(PathHome);
  475. PathHome.append(Path.begin() + 1, Path.end());
  476. Path = PathHome;
  477. }
  478. } else {
  479. for (auto PI = Path.begin(), PE = Path.end(); PI < PE; ++PI) {
  480. if (*PI == '\\') {
  481. auto PN = PI + 1;
  482. if (PN < PE && *PN == '\\')
  483. ++PI; // increment once, the for loop will move over the escaped slash
  484. else
  485. *PI = '/';
  486. }
  487. }
  488. }
  489. }
  490. std::string convert_to_slash(StringRef path, Style style) {
  491. if (real_style(style) != Style::windows)
  492. return path;
  493. std::string s = path.str();
  494. std::replace(s.begin(), s.end(), '\\', '/');
  495. return s;
  496. }
  497. StringRef filename(StringRef path, Style style) { return *rbegin(path, style); }
  498. StringRef stem(StringRef path, Style style) {
  499. StringRef fname = filename(path, style);
  500. size_t pos = fname.find_last_of('.');
  501. if (pos == StringRef::npos)
  502. return fname;
  503. else
  504. if ((fname.size() == 1 && fname == ".") ||
  505. (fname.size() == 2 && fname == ".."))
  506. return fname;
  507. else
  508. return fname.substr(0, pos);
  509. }
  510. StringRef extension(StringRef path, Style style) {
  511. StringRef fname = filename(path, style);
  512. size_t pos = fname.find_last_of('.');
  513. if (pos == StringRef::npos)
  514. return StringRef();
  515. else
  516. if ((fname.size() == 1 && fname == ".") ||
  517. (fname.size() == 2 && fname == ".."))
  518. return StringRef();
  519. else
  520. return fname.substr(pos);
  521. }
  522. bool is_separator(char value, Style style) {
  523. if (value == '/')
  524. return true;
  525. if (real_style(style) == Style::windows)
  526. return value == '\\';
  527. return false;
  528. }
  529. StringRef get_separator(Style style) {
  530. if (real_style(style) == Style::windows)
  531. return "\\";
  532. return "/";
  533. }
  534. bool has_root_name(const Twine &path, Style style) {
  535. SmallString<128> path_storage;
  536. StringRef p = path.toStringRef(path_storage);
  537. return !root_name(p, style).empty();
  538. }
  539. bool has_root_directory(const Twine &path, Style style) {
  540. SmallString<128> path_storage;
  541. StringRef p = path.toStringRef(path_storage);
  542. return !root_directory(p, style).empty();
  543. }
  544. bool has_root_path(const Twine &path, Style style) {
  545. SmallString<128> path_storage;
  546. StringRef p = path.toStringRef(path_storage);
  547. return !root_path(p, style).empty();
  548. }
  549. bool has_relative_path(const Twine &path, Style style) {
  550. SmallString<128> path_storage;
  551. StringRef p = path.toStringRef(path_storage);
  552. return !relative_path(p, style).empty();
  553. }
  554. bool has_filename(const Twine &path, Style style) {
  555. SmallString<128> path_storage;
  556. StringRef p = path.toStringRef(path_storage);
  557. return !filename(p, style).empty();
  558. }
  559. bool has_parent_path(const Twine &path, Style style) {
  560. SmallString<128> path_storage;
  561. StringRef p = path.toStringRef(path_storage);
  562. return !parent_path(p, style).empty();
  563. }
  564. bool has_stem(const Twine &path, Style style) {
  565. SmallString<128> path_storage;
  566. StringRef p = path.toStringRef(path_storage);
  567. return !stem(p, style).empty();
  568. }
  569. bool has_extension(const Twine &path, Style style) {
  570. SmallString<128> path_storage;
  571. StringRef p = path.toStringRef(path_storage);
  572. return !extension(p, style).empty();
  573. }
  574. bool is_absolute(const Twine &path, Style style) {
  575. SmallString<128> path_storage;
  576. StringRef p = path.toStringRef(path_storage);
  577. bool rootDir = has_root_directory(p, style);
  578. bool rootName =
  579. (real_style(style) != Style::windows) || has_root_name(p, style);
  580. return rootDir && rootName;
  581. }
  582. bool is_relative(const Twine &path, Style style) {
  583. return !is_absolute(path, style);
  584. }
  585. StringRef remove_leading_dotslash(StringRef Path, Style style) {
  586. // Remove leading "./" (or ".//" or "././" etc.)
  587. while (Path.size() > 2 && Path[0] == '.' && is_separator(Path[1], style)) {
  588. Path = Path.substr(2);
  589. while (Path.size() > 0 && is_separator(Path[0], style))
  590. Path = Path.substr(1);
  591. }
  592. return Path;
  593. }
  594. static SmallString<256> remove_dots(StringRef path, bool remove_dot_dot,
  595. Style style) {
  596. SmallVector<StringRef, 16> components;
  597. // Skip the root path, then look for traversal in the components.
  598. StringRef rel = path::relative_path(path, style);
  599. for (StringRef C :
  600. llvm::make_range(path::begin(rel, style), path::end(rel))) {
  601. if (C == ".")
  602. continue;
  603. // Leading ".." will remain in the path unless it's at the root.
  604. if (remove_dot_dot && C == "..") {
  605. if (!components.empty() && components.back() != "..") {
  606. components.pop_back();
  607. continue;
  608. }
  609. if (path::is_absolute(path, style))
  610. continue;
  611. }
  612. components.push_back(C);
  613. }
  614. SmallString<256> buffer = path::root_path(path, style);
  615. for (StringRef C : components)
  616. path::append(buffer, style, C);
  617. return buffer;
  618. }
  619. bool remove_dots(SmallVectorImpl<char> &path, bool remove_dot_dot,
  620. Style style) {
  621. StringRef p(path.data(), path.size());
  622. SmallString<256> result = remove_dots(p, remove_dot_dot, style);
  623. if (result == path)
  624. return false;
  625. path.swap(result);
  626. return true;
  627. }
  628. } // end namespace path
  629. namespace fs {
  630. std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
  631. file_status Status;
  632. std::error_code EC = status(Path, Status);
  633. if (EC)
  634. return EC;
  635. Result = Status.getUniqueID();
  636. return std::error_code();
  637. }
  638. std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
  639. SmallVectorImpl<char> &ResultPath,
  640. unsigned Mode) {
  641. return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File);
  642. }
  643. static std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
  644. SmallVectorImpl<char> &ResultPath,
  645. unsigned Mode, OpenFlags Flags) {
  646. return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File,
  647. Flags);
  648. }
  649. std::error_code createUniqueFile(const Twine &Model,
  650. SmallVectorImpl<char> &ResultPath,
  651. unsigned Mode) {
  652. int FD;
  653. auto EC = createUniqueFile(Model, FD, ResultPath, Mode);
  654. if (EC)
  655. return EC;
  656. // FD is only needed to avoid race conditions. Close it right away.
  657. close(FD);
  658. return EC;
  659. }
  660. static std::error_code
  661. createTemporaryFile(const Twine &Model, int &ResultFD,
  662. llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
  663. SmallString<128> Storage;
  664. StringRef P = Model.toNullTerminatedStringRef(Storage);
  665. assert(P.find_first_of(separators(Style::native)) == StringRef::npos &&
  666. "Model must be a simple filename.");
  667. // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
  668. return createUniqueEntity(P.begin(), ResultFD, ResultPath, true,
  669. owner_read | owner_write, Type);
  670. }
  671. static std::error_code
  672. createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
  673. llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
  674. const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
  675. return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
  676. Type);
  677. }
  678. std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
  679. int &ResultFD,
  680. SmallVectorImpl<char> &ResultPath) {
  681. return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File);
  682. }
  683. std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
  684. SmallVectorImpl<char> &ResultPath) {
  685. int FD;
  686. auto EC = createTemporaryFile(Prefix, Suffix, FD, ResultPath);
  687. if (EC)
  688. return EC;
  689. // FD is only needed to avoid race conditions. Close it right away.
  690. close(FD);
  691. return EC;
  692. }
  693. // This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
  694. // for consistency. We should try using mkdtemp.
  695. std::error_code createUniqueDirectory(const Twine &Prefix,
  696. SmallVectorImpl<char> &ResultPath) {
  697. int Dummy;
  698. return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath, true, 0,
  699. FS_Dir);
  700. }
  701. std::error_code
  702. getPotentiallyUniqueFileName(const Twine &Model,
  703. SmallVectorImpl<char> &ResultPath) {
  704. int Dummy;
  705. return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
  706. }
  707. std::error_code
  708. getPotentiallyUniqueTempFileName(const Twine &Prefix, StringRef Suffix,
  709. SmallVectorImpl<char> &ResultPath) {
  710. int Dummy;
  711. return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
  712. }
  713. static std::error_code make_absolute(const Twine &current_directory,
  714. SmallVectorImpl<char> &path,
  715. bool use_current_directory) {
  716. StringRef p(path.data(), path.size());
  717. bool rootDirectory = path::has_root_directory(p);
  718. bool rootName =
  719. (real_style(Style::native) != Style::windows) || path::has_root_name(p);
  720. // Already absolute.
  721. if (rootName && rootDirectory)
  722. return std::error_code();
  723. // All of the following conditions will need the current directory.
  724. SmallString<128> current_dir;
  725. if (use_current_directory)
  726. current_directory.toVector(current_dir);
  727. else if (std::error_code ec = current_path(current_dir))
  728. return ec;
  729. // Relative path. Prepend the current directory.
  730. if (!rootName && !rootDirectory) {
  731. // Append path to the current directory.
  732. path::append(current_dir, p);
  733. // Set path to the result.
  734. path.swap(current_dir);
  735. return std::error_code();
  736. }
  737. if (!rootName && rootDirectory) {
  738. StringRef cdrn = path::root_name(current_dir);
  739. SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
  740. path::append(curDirRootName, p);
  741. // Set path to the result.
  742. path.swap(curDirRootName);
  743. return std::error_code();
  744. }
  745. if (rootName && !rootDirectory) {
  746. StringRef pRootName = path::root_name(p);
  747. StringRef bRootDirectory = path::root_directory(current_dir);
  748. StringRef bRelativePath = path::relative_path(current_dir);
  749. StringRef pRelativePath = path::relative_path(p);
  750. SmallString<128> res;
  751. path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
  752. path.swap(res);
  753. return std::error_code();
  754. }
  755. llvm_unreachable("All rootName and rootDirectory combinations should have "
  756. "occurred above!");
  757. }
  758. std::error_code make_absolute(const Twine &current_directory,
  759. SmallVectorImpl<char> &path) {
  760. return make_absolute(current_directory, path, true);
  761. }
  762. std::error_code make_absolute(SmallVectorImpl<char> &path) {
  763. return make_absolute(Twine(), path, false);
  764. }
  765. std::error_code create_directories(const Twine &Path, bool IgnoreExisting,
  766. perms Perms) {
  767. SmallString<128> PathStorage;
  768. StringRef P = Path.toStringRef(PathStorage);
  769. // Be optimistic and try to create the directory
  770. std::error_code EC = create_directory(P, IgnoreExisting, Perms);
  771. // If we succeeded, or had any error other than the parent not existing, just
  772. // return it.
  773. if (EC != errc::no_such_file_or_directory)
  774. return EC;
  775. // We failed because of a no_such_file_or_directory, try to create the
  776. // parent.
  777. StringRef Parent = path::parent_path(P);
  778. if (Parent.empty())
  779. return EC;
  780. if ((EC = create_directories(Parent, IgnoreExisting, Perms)))
  781. return EC;
  782. return create_directory(P, IgnoreExisting, Perms);
  783. }
  784. static std::error_code copy_file_internal(int ReadFD, int WriteFD) {
  785. const size_t BufSize = 4096;
  786. char *Buf = new char[BufSize];
  787. int BytesRead = 0, BytesWritten = 0;
  788. for (;;) {
  789. BytesRead = read(ReadFD, Buf, BufSize);
  790. if (BytesRead <= 0)
  791. break;
  792. while (BytesRead) {
  793. BytesWritten = write(WriteFD, Buf, BytesRead);
  794. if (BytesWritten < 0)
  795. break;
  796. BytesRead -= BytesWritten;
  797. }
  798. if (BytesWritten < 0)
  799. break;
  800. }
  801. delete[] Buf;
  802. if (BytesRead < 0 || BytesWritten < 0)
  803. return std::error_code(errno, std::generic_category());
  804. return std::error_code();
  805. }
  806. std::error_code copy_file(const Twine &From, const Twine &To) {
  807. int ReadFD, WriteFD;
  808. if (std::error_code EC = openFileForRead(From, ReadFD, OF_None))
  809. return EC;
  810. if (std::error_code EC =
  811. openFileForWrite(To, WriteFD, CD_CreateAlways, OF_None)) {
  812. close(ReadFD);
  813. return EC;
  814. }
  815. std::error_code EC = copy_file_internal(ReadFD, WriteFD);
  816. close(ReadFD);
  817. close(WriteFD);
  818. return EC;
  819. }
  820. std::error_code copy_file(const Twine &From, int ToFD) {
  821. int ReadFD;
  822. if (std::error_code EC = openFileForRead(From, ReadFD, OF_None))
  823. return EC;
  824. std::error_code EC = copy_file_internal(ReadFD, ToFD);
  825. close(ReadFD);
  826. return EC;
  827. }
  828. ErrorOr<MD5::MD5Result> md5_contents(int FD) {
  829. MD5 Hash;
  830. constexpr size_t BufSize = 4096;
  831. std::vector<uint8_t> Buf(BufSize);
  832. int BytesRead = 0;
  833. for (;;) {
  834. BytesRead = read(FD, Buf.data(), BufSize);
  835. if (BytesRead <= 0)
  836. break;
  837. Hash.update(makeArrayRef(Buf.data(), BytesRead));
  838. }
  839. if (BytesRead < 0)
  840. return std::error_code(errno, std::generic_category());
  841. MD5::MD5Result Result;
  842. Hash.final(Result);
  843. return Result;
  844. }
  845. ErrorOr<MD5::MD5Result> md5_contents(const Twine &Path) {
  846. int FD;
  847. if (auto EC = openFileForRead(Path, FD, OF_None))
  848. return EC;
  849. auto Result = md5_contents(FD);
  850. close(FD);
  851. return Result;
  852. }
  853. bool exists(const basic_file_status &status) {
  854. return status_known(status) && status.type() != file_type::file_not_found;
  855. }
  856. bool status_known(const basic_file_status &s) {
  857. return s.type() != file_type::status_error;
  858. }
  859. file_type get_file_type(const Twine &Path, bool Follow) {
  860. file_status st;
  861. if (status(Path, st, Follow))
  862. return file_type::status_error;
  863. return st.type();
  864. }
  865. bool is_directory(const basic_file_status &status) {
  866. return status.type() == file_type::directory_file;
  867. }
  868. std::error_code is_directory(const Twine &path, bool &result) {
  869. file_status st;
  870. if (std::error_code ec = status(path, st))
  871. return ec;
  872. result = is_directory(st);
  873. return std::error_code();
  874. }
  875. bool is_regular_file(const basic_file_status &status) {
  876. return status.type() == file_type::regular_file;
  877. }
  878. std::error_code is_regular_file(const Twine &path, bool &result) {
  879. file_status st;
  880. if (std::error_code ec = status(path, st))
  881. return ec;
  882. result = is_regular_file(st);
  883. return std::error_code();
  884. }
  885. bool is_symlink_file(const basic_file_status &status) {
  886. return status.type() == file_type::symlink_file;
  887. }
  888. std::error_code is_symlink_file(const Twine &path, bool &result) {
  889. file_status st;
  890. if (std::error_code ec = status(path, st, false))
  891. return ec;
  892. result = is_symlink_file(st);
  893. return std::error_code();
  894. }
  895. bool is_other(const basic_file_status &status) {
  896. return exists(status) &&
  897. !is_regular_file(status) &&
  898. !is_directory(status);
  899. }
  900. std::error_code is_other(const Twine &Path, bool &Result) {
  901. file_status FileStatus;
  902. if (std::error_code EC = status(Path, FileStatus))
  903. return EC;
  904. Result = is_other(FileStatus);
  905. return std::error_code();
  906. }
  907. void directory_entry::replace_filename(const Twine &Filename, file_type Type,
  908. basic_file_status Status) {
  909. SmallString<128> PathStr = path::parent_path(Path);
  910. path::append(PathStr, Filename);
  911. this->Path = PathStr.str();
  912. this->Type = Type;
  913. this->Status = Status;
  914. }
  915. ErrorOr<perms> getPermissions(const Twine &Path) {
  916. file_status Status;
  917. if (std::error_code EC = status(Path, Status))
  918. return EC;
  919. return Status.permissions();
  920. }
  921. } // end namespace fs
  922. } // end namespace sys
  923. } // end namespace llvm
  924. // Include the truly platform-specific parts.
  925. #if defined(LLVM_ON_UNIX)
  926. #include "Unix/Path.inc"
  927. #endif
  928. #if defined(_WIN32)
  929. #include "Windows/Path.inc"
  930. #endif
  931. namespace llvm {
  932. namespace sys {
  933. namespace fs {
  934. TempFile::TempFile(StringRef Name, int FD) : TmpName(Name), FD(FD) {}
  935. TempFile::TempFile(TempFile &&Other) { *this = std::move(Other); }
  936. TempFile &TempFile::operator=(TempFile &&Other) {
  937. TmpName = std::move(Other.TmpName);
  938. FD = Other.FD;
  939. Other.Done = true;
  940. return *this;
  941. }
  942. TempFile::~TempFile() { assert(Done); }
  943. Error TempFile::discard() {
  944. Done = true;
  945. std::error_code RemoveEC;
  946. // On windows closing will remove the file.
  947. #ifndef _WIN32
  948. // Always try to close and remove.
  949. if (!TmpName.empty()) {
  950. RemoveEC = fs::remove(TmpName);
  951. sys::DontRemoveFileOnSignal(TmpName);
  952. }
  953. #endif
  954. if (!RemoveEC)
  955. TmpName = "";
  956. if (FD != -1 && close(FD) == -1) {
  957. std::error_code EC = std::error_code(errno, std::generic_category());
  958. return errorCodeToError(EC);
  959. }
  960. FD = -1;
  961. return errorCodeToError(RemoveEC);
  962. }
  963. Error TempFile::keep(const Twine &Name) {
  964. assert(!Done);
  965. Done = true;
  966. // Always try to close and rename.
  967. #ifdef _WIN32
  968. // If we can't cancel the delete don't rename.
  969. auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
  970. std::error_code RenameEC = setDeleteDisposition(H, false);
  971. if (!RenameEC) {
  972. RenameEC = rename_fd(FD, Name);
  973. // If rename failed because it's cross-device, copy instead
  974. if (RenameEC ==
  975. std::error_code(ERROR_NOT_SAME_DEVICE, std::system_category())) {
  976. RenameEC = copy_file(TmpName, Name);
  977. setDeleteDisposition(H, true);
  978. }
  979. }
  980. // If we can't rename, discard the temporary file.
  981. if (RenameEC)
  982. setDeleteDisposition(H, true);
  983. #else
  984. std::error_code RenameEC = fs::rename(TmpName, Name);
  985. if (RenameEC) {
  986. // If we can't rename, try to copy to work around cross-device link issues.
  987. RenameEC = sys::fs::copy_file(TmpName, Name);
  988. // If we can't rename or copy, discard the temporary file.
  989. if (RenameEC)
  990. remove(TmpName);
  991. }
  992. sys::DontRemoveFileOnSignal(TmpName);
  993. #endif
  994. if (!RenameEC)
  995. TmpName = "";
  996. if (close(FD) == -1) {
  997. std::error_code EC(errno, std::generic_category());
  998. return errorCodeToError(EC);
  999. }
  1000. FD = -1;
  1001. return errorCodeToError(RenameEC);
  1002. }
  1003. Error TempFile::keep() {
  1004. assert(!Done);
  1005. Done = true;
  1006. #ifdef _WIN32
  1007. auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
  1008. if (std::error_code EC = setDeleteDisposition(H, false))
  1009. return errorCodeToError(EC);
  1010. #else
  1011. sys::DontRemoveFileOnSignal(TmpName);
  1012. #endif
  1013. TmpName = "";
  1014. if (close(FD) == -1) {
  1015. std::error_code EC(errno, std::generic_category());
  1016. return errorCodeToError(EC);
  1017. }
  1018. FD = -1;
  1019. return Error::success();
  1020. }
  1021. Expected<TempFile> TempFile::create(const Twine &Model, unsigned Mode) {
  1022. int FD;
  1023. SmallString<128> ResultPath;
  1024. if (std::error_code EC =
  1025. createUniqueFile(Model, FD, ResultPath, Mode, OF_Delete))
  1026. return errorCodeToError(EC);
  1027. TempFile Ret(ResultPath, FD);
  1028. #ifndef _WIN32
  1029. if (sys::RemoveFileOnSignal(ResultPath)) {
  1030. // Make sure we delete the file when RemoveFileOnSignal fails.
  1031. consumeError(Ret.discard());
  1032. std::error_code EC(errc::operation_not_permitted);
  1033. return errorCodeToError(EC);
  1034. }
  1035. #endif
  1036. return std::move(Ret);
  1037. }
  1038. }
  1039. } // end namsspace sys
  1040. } // end namespace llvm