Path.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  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. llvm::copy(NewPrefix, 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. void make_absolute(const Twine &current_directory,
  714. SmallVectorImpl<char> &path) {
  715. StringRef p(path.data(), path.size());
  716. bool rootDirectory = path::has_root_directory(p);
  717. bool rootName =
  718. (real_style(Style::native) != Style::windows) || path::has_root_name(p);
  719. // Already absolute.
  720. if (rootName && rootDirectory)
  721. return;
  722. // All of the following conditions will need the current directory.
  723. SmallString<128> current_dir;
  724. current_directory.toVector(current_dir);
  725. // Relative path. Prepend the current directory.
  726. if (!rootName && !rootDirectory) {
  727. // Append path to the current directory.
  728. path::append(current_dir, p);
  729. // Set path to the result.
  730. path.swap(current_dir);
  731. return;
  732. }
  733. if (!rootName && rootDirectory) {
  734. StringRef cdrn = path::root_name(current_dir);
  735. SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
  736. path::append(curDirRootName, p);
  737. // Set path to the result.
  738. path.swap(curDirRootName);
  739. return;
  740. }
  741. if (rootName && !rootDirectory) {
  742. StringRef pRootName = path::root_name(p);
  743. StringRef bRootDirectory = path::root_directory(current_dir);
  744. StringRef bRelativePath = path::relative_path(current_dir);
  745. StringRef pRelativePath = path::relative_path(p);
  746. SmallString<128> res;
  747. path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
  748. path.swap(res);
  749. return;
  750. }
  751. llvm_unreachable("All rootName and rootDirectory combinations should have "
  752. "occurred above!");
  753. }
  754. std::error_code make_absolute(SmallVectorImpl<char> &path) {
  755. if (path::is_absolute(path))
  756. return {};
  757. SmallString<128> current_dir;
  758. if (std::error_code ec = current_path(current_dir))
  759. return ec;
  760. make_absolute(current_dir, path);
  761. return {};
  762. }
  763. std::error_code create_directories(const Twine &Path, bool IgnoreExisting,
  764. perms Perms) {
  765. SmallString<128> PathStorage;
  766. StringRef P = Path.toStringRef(PathStorage);
  767. // Be optimistic and try to create the directory
  768. std::error_code EC = create_directory(P, IgnoreExisting, Perms);
  769. // If we succeeded, or had any error other than the parent not existing, just
  770. // return it.
  771. if (EC != errc::no_such_file_or_directory)
  772. return EC;
  773. // We failed because of a no_such_file_or_directory, try to create the
  774. // parent.
  775. StringRef Parent = path::parent_path(P);
  776. if (Parent.empty())
  777. return EC;
  778. if ((EC = create_directories(Parent, IgnoreExisting, Perms)))
  779. return EC;
  780. return create_directory(P, IgnoreExisting, Perms);
  781. }
  782. static std::error_code copy_file_internal(int ReadFD, int WriteFD) {
  783. const size_t BufSize = 4096;
  784. char *Buf = new char[BufSize];
  785. int BytesRead = 0, BytesWritten = 0;
  786. for (;;) {
  787. BytesRead = read(ReadFD, Buf, BufSize);
  788. if (BytesRead <= 0)
  789. break;
  790. while (BytesRead) {
  791. BytesWritten = write(WriteFD, Buf, BytesRead);
  792. if (BytesWritten < 0)
  793. break;
  794. BytesRead -= BytesWritten;
  795. }
  796. if (BytesWritten < 0)
  797. break;
  798. }
  799. delete[] Buf;
  800. if (BytesRead < 0 || BytesWritten < 0)
  801. return std::error_code(errno, std::generic_category());
  802. return std::error_code();
  803. }
  804. std::error_code copy_file(const Twine &From, const Twine &To) {
  805. int ReadFD, WriteFD;
  806. if (std::error_code EC = openFileForRead(From, ReadFD, OF_None))
  807. return EC;
  808. if (std::error_code EC =
  809. openFileForWrite(To, WriteFD, CD_CreateAlways, OF_None)) {
  810. close(ReadFD);
  811. return EC;
  812. }
  813. std::error_code EC = copy_file_internal(ReadFD, WriteFD);
  814. close(ReadFD);
  815. close(WriteFD);
  816. return EC;
  817. }
  818. std::error_code copy_file(const Twine &From, int ToFD) {
  819. int ReadFD;
  820. if (std::error_code EC = openFileForRead(From, ReadFD, OF_None))
  821. return EC;
  822. std::error_code EC = copy_file_internal(ReadFD, ToFD);
  823. close(ReadFD);
  824. return EC;
  825. }
  826. ErrorOr<MD5::MD5Result> md5_contents(int FD) {
  827. MD5 Hash;
  828. constexpr size_t BufSize = 4096;
  829. std::vector<uint8_t> Buf(BufSize);
  830. int BytesRead = 0;
  831. for (;;) {
  832. BytesRead = read(FD, Buf.data(), BufSize);
  833. if (BytesRead <= 0)
  834. break;
  835. Hash.update(makeArrayRef(Buf.data(), BytesRead));
  836. }
  837. if (BytesRead < 0)
  838. return std::error_code(errno, std::generic_category());
  839. MD5::MD5Result Result;
  840. Hash.final(Result);
  841. return Result;
  842. }
  843. ErrorOr<MD5::MD5Result> md5_contents(const Twine &Path) {
  844. int FD;
  845. if (auto EC = openFileForRead(Path, FD, OF_None))
  846. return EC;
  847. auto Result = md5_contents(FD);
  848. close(FD);
  849. return Result;
  850. }
  851. bool exists(const basic_file_status &status) {
  852. return status_known(status) && status.type() != file_type::file_not_found;
  853. }
  854. bool status_known(const basic_file_status &s) {
  855. return s.type() != file_type::status_error;
  856. }
  857. file_type get_file_type(const Twine &Path, bool Follow) {
  858. file_status st;
  859. if (status(Path, st, Follow))
  860. return file_type::status_error;
  861. return st.type();
  862. }
  863. bool is_directory(const basic_file_status &status) {
  864. return status.type() == file_type::directory_file;
  865. }
  866. std::error_code is_directory(const Twine &path, bool &result) {
  867. file_status st;
  868. if (std::error_code ec = status(path, st))
  869. return ec;
  870. result = is_directory(st);
  871. return std::error_code();
  872. }
  873. bool is_regular_file(const basic_file_status &status) {
  874. return status.type() == file_type::regular_file;
  875. }
  876. std::error_code is_regular_file(const Twine &path, bool &result) {
  877. file_status st;
  878. if (std::error_code ec = status(path, st))
  879. return ec;
  880. result = is_regular_file(st);
  881. return std::error_code();
  882. }
  883. bool is_symlink_file(const basic_file_status &status) {
  884. return status.type() == file_type::symlink_file;
  885. }
  886. std::error_code is_symlink_file(const Twine &path, bool &result) {
  887. file_status st;
  888. if (std::error_code ec = status(path, st, false))
  889. return ec;
  890. result = is_symlink_file(st);
  891. return std::error_code();
  892. }
  893. bool is_other(const basic_file_status &status) {
  894. return exists(status) &&
  895. !is_regular_file(status) &&
  896. !is_directory(status);
  897. }
  898. std::error_code is_other(const Twine &Path, bool &Result) {
  899. file_status FileStatus;
  900. if (std::error_code EC = status(Path, FileStatus))
  901. return EC;
  902. Result = is_other(FileStatus);
  903. return std::error_code();
  904. }
  905. void directory_entry::replace_filename(const Twine &Filename, file_type Type,
  906. basic_file_status Status) {
  907. SmallString<128> PathStr = path::parent_path(Path);
  908. path::append(PathStr, Filename);
  909. this->Path = PathStr.str();
  910. this->Type = Type;
  911. this->Status = Status;
  912. }
  913. ErrorOr<perms> getPermissions(const Twine &Path) {
  914. file_status Status;
  915. if (std::error_code EC = status(Path, Status))
  916. return EC;
  917. return Status.permissions();
  918. }
  919. } // end namespace fs
  920. } // end namespace sys
  921. } // end namespace llvm
  922. // Include the truly platform-specific parts.
  923. #if defined(LLVM_ON_UNIX)
  924. #include "Unix/Path.inc"
  925. #endif
  926. #if defined(_WIN32)
  927. #include "Windows/Path.inc"
  928. #endif
  929. namespace llvm {
  930. namespace sys {
  931. namespace fs {
  932. TempFile::TempFile(StringRef Name, int FD) : TmpName(Name), FD(FD) {}
  933. TempFile::TempFile(TempFile &&Other) { *this = std::move(Other); }
  934. TempFile &TempFile::operator=(TempFile &&Other) {
  935. TmpName = std::move(Other.TmpName);
  936. FD = Other.FD;
  937. Other.Done = true;
  938. return *this;
  939. }
  940. TempFile::~TempFile() { assert(Done); }
  941. Error TempFile::discard() {
  942. Done = true;
  943. std::error_code RemoveEC;
  944. // On windows closing will remove the file.
  945. #ifndef _WIN32
  946. // Always try to close and remove.
  947. if (!TmpName.empty()) {
  948. RemoveEC = fs::remove(TmpName);
  949. sys::DontRemoveFileOnSignal(TmpName);
  950. }
  951. #endif
  952. if (!RemoveEC)
  953. TmpName = "";
  954. if (FD != -1 && close(FD) == -1) {
  955. std::error_code EC = std::error_code(errno, std::generic_category());
  956. return errorCodeToError(EC);
  957. }
  958. FD = -1;
  959. return errorCodeToError(RemoveEC);
  960. }
  961. Error TempFile::keep(const Twine &Name) {
  962. assert(!Done);
  963. Done = true;
  964. // Always try to close and rename.
  965. #ifdef _WIN32
  966. // If we can't cancel the delete don't rename.
  967. auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
  968. std::error_code RenameEC = setDeleteDisposition(H, false);
  969. if (!RenameEC) {
  970. RenameEC = rename_fd(FD, Name);
  971. // If rename failed because it's cross-device, copy instead
  972. if (RenameEC ==
  973. std::error_code(ERROR_NOT_SAME_DEVICE, std::system_category())) {
  974. RenameEC = copy_file(TmpName, Name);
  975. setDeleteDisposition(H, true);
  976. }
  977. }
  978. // If we can't rename, discard the temporary file.
  979. if (RenameEC)
  980. setDeleteDisposition(H, true);
  981. #else
  982. std::error_code RenameEC = fs::rename(TmpName, Name);
  983. if (RenameEC) {
  984. // If we can't rename, try to copy to work around cross-device link issues.
  985. RenameEC = sys::fs::copy_file(TmpName, Name);
  986. // If we can't rename or copy, discard the temporary file.
  987. if (RenameEC)
  988. remove(TmpName);
  989. }
  990. sys::DontRemoveFileOnSignal(TmpName);
  991. #endif
  992. if (!RenameEC)
  993. TmpName = "";
  994. if (close(FD) == -1) {
  995. std::error_code EC(errno, std::generic_category());
  996. return errorCodeToError(EC);
  997. }
  998. FD = -1;
  999. return errorCodeToError(RenameEC);
  1000. }
  1001. Error TempFile::keep() {
  1002. assert(!Done);
  1003. Done = true;
  1004. #ifdef _WIN32
  1005. auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
  1006. if (std::error_code EC = setDeleteDisposition(H, false))
  1007. return errorCodeToError(EC);
  1008. #else
  1009. sys::DontRemoveFileOnSignal(TmpName);
  1010. #endif
  1011. TmpName = "";
  1012. if (close(FD) == -1) {
  1013. std::error_code EC(errno, std::generic_category());
  1014. return errorCodeToError(EC);
  1015. }
  1016. FD = -1;
  1017. return Error::success();
  1018. }
  1019. Expected<TempFile> TempFile::create(const Twine &Model, unsigned Mode) {
  1020. int FD;
  1021. SmallString<128> ResultPath;
  1022. if (std::error_code EC =
  1023. createUniqueFile(Model, FD, ResultPath, Mode, OF_Delete))
  1024. return errorCodeToError(EC);
  1025. TempFile Ret(ResultPath, FD);
  1026. #ifndef _WIN32
  1027. if (sys::RemoveFileOnSignal(ResultPath)) {
  1028. // Make sure we delete the file when RemoveFileOnSignal fails.
  1029. consumeError(Ret.discard());
  1030. std::error_code EC(errc::operation_not_permitted);
  1031. return errorCodeToError(EC);
  1032. }
  1033. #endif
  1034. return std::move(Ret);
  1035. }
  1036. }
  1037. } // end namsspace sys
  1038. } // end namespace llvm