Path.cpp 30 KB

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