Path.cpp 35 KB

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