Path.cpp 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  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/COFF.h"
  14. #include "llvm/Support/Endian.h"
  15. #include "llvm/Support/Errc.h"
  16. #include "llvm/Support/ErrorHandling.h"
  17. #include "llvm/Support/FileSystem.h"
  18. #include "llvm/Support/Path.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. #ifdef LLVM_ON_WIN32
  33. const char *separators = "\\/";
  34. const char preferred_separator = '\\';
  35. #else
  36. const char separators = '/';
  37. const char preferred_separator = '/';
  38. #endif
  39. StringRef find_first_component(StringRef path) {
  40. // Look for this first component in the following order.
  41. // * empty (in this case we return an empty string)
  42. // * either C: or {//,\\}net.
  43. // * {/,\}
  44. // * {file,directory}name
  45. if (path.empty())
  46. return path;
  47. #ifdef LLVM_ON_WIN32
  48. // C:
  49. if (path.size() >= 2 && std::isalpha(static_cast<unsigned char>(path[0])) &&
  50. path[1] == ':')
  51. return path.substr(0, 2);
  52. #endif
  53. // //net
  54. if ((path.size() > 2) &&
  55. is_separator(path[0]) &&
  56. path[0] == path[1] &&
  57. !is_separator(path[2])) {
  58. // Find the next directory separator.
  59. size_t end = path.find_first_of(separators, 2);
  60. return path.substr(0, end);
  61. }
  62. // {/,\}
  63. if (is_separator(path[0]))
  64. return path.substr(0, 1);
  65. // * {file,directory}name
  66. size_t end = path.find_first_of(separators);
  67. return path.substr(0, end);
  68. }
  69. size_t filename_pos(StringRef str) {
  70. if (str.size() == 2 &&
  71. is_separator(str[0]) &&
  72. str[0] == str[1])
  73. return 0;
  74. if (str.size() > 0 && is_separator(str[str.size() - 1]))
  75. return str.size() - 1;
  76. size_t pos = str.find_last_of(separators, str.size() - 1);
  77. #ifdef LLVM_ON_WIN32
  78. if (pos == StringRef::npos)
  79. pos = str.find_last_of(':', str.size() - 2);
  80. #endif
  81. if (pos == StringRef::npos ||
  82. (pos == 1 && is_separator(str[0])))
  83. return 0;
  84. return pos + 1;
  85. }
  86. size_t root_dir_start(StringRef str) {
  87. // case "c:/"
  88. #ifdef LLVM_ON_WIN32
  89. if (str.size() > 2 &&
  90. str[1] == ':' &&
  91. is_separator(str[2]))
  92. return 2;
  93. #endif
  94. // case "//"
  95. if (str.size() == 2 &&
  96. is_separator(str[0]) &&
  97. str[0] == str[1])
  98. return StringRef::npos;
  99. // case "//net"
  100. if (str.size() > 3 &&
  101. is_separator(str[0]) &&
  102. str[0] == str[1] &&
  103. !is_separator(str[2])) {
  104. return str.find_first_of(separators, 2);
  105. }
  106. // case "/"
  107. if (str.size() > 0 && is_separator(str[0]))
  108. return 0;
  109. return StringRef::npos;
  110. }
  111. size_t parent_path_end(StringRef path) {
  112. size_t end_pos = filename_pos(path);
  113. bool filename_was_sep = path.size() > 0 && is_separator(path[end_pos]);
  114. // Skip separators except for root dir.
  115. size_t root_dir_pos = root_dir_start(path.substr(0, end_pos));
  116. while(end_pos > 0 &&
  117. (end_pos - 1) != root_dir_pos &&
  118. is_separator(path[end_pos - 1]))
  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) {
  194. const_iterator i;
  195. i.Path = path;
  196. i.Component = find_first_component(path);
  197. i.Position = 0;
  198. return i;
  199. }
  200. const_iterator end(StringRef path) {
  201. const_iterator i;
  202. i.Path = path;
  203. i.Position = path.size();
  204. return i;
  205. }
  206. const_iterator &const_iterator::operator++() {
  207. assert(Position < Path.size() && "Tried to increment past end!");
  208. // Increment Position to past the current component
  209. Position += Component.size();
  210. // Check for end.
  211. if (Position == Path.size()) {
  212. Component = StringRef();
  213. return *this;
  214. }
  215. // Both POSIX and Windows treat paths that begin with exactly two separators
  216. // specially.
  217. bool was_net = Component.size() > 2 &&
  218. is_separator(Component[0]) &&
  219. Component[1] == Component[0] &&
  220. !is_separator(Component[2]);
  221. // Handle separators.
  222. if (is_separator(Path[Position])) {
  223. // Root dir.
  224. if (was_net
  225. #ifdef LLVM_ON_WIN32
  226. // c:/
  227. || Component.endswith(":")
  228. #endif
  229. ) {
  230. Component = Path.substr(Position, 1);
  231. return *this;
  232. }
  233. // Skip extra separators.
  234. while (Position != Path.size() &&
  235. is_separator(Path[Position])) {
  236. ++Position;
  237. }
  238. // Treat trailing '/' as a '.'.
  239. if (Position == Path.size()) {
  240. --Position;
  241. Component = ".";
  242. return *this;
  243. }
  244. }
  245. // Find next component.
  246. size_t end_pos = Path.find_first_of(separators, Position);
  247. Component = Path.slice(Position, end_pos);
  248. return *this;
  249. }
  250. bool const_iterator::operator==(const const_iterator &RHS) const {
  251. return Path.begin() == RHS.Path.begin() && Position == RHS.Position;
  252. }
  253. ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
  254. return Position - RHS.Position;
  255. }
  256. reverse_iterator rbegin(StringRef Path) {
  257. reverse_iterator I;
  258. I.Path = Path;
  259. I.Position = Path.size();
  260. return ++I;
  261. }
  262. reverse_iterator rend(StringRef Path) {
  263. reverse_iterator I;
  264. I.Path = Path;
  265. I.Component = Path.substr(0, 0);
  266. I.Position = 0;
  267. return I;
  268. }
  269. reverse_iterator &reverse_iterator::operator++() {
  270. // If we're at the end and the previous char was a '/', return '.' unless
  271. // we are the root path.
  272. size_t root_dir_pos = root_dir_start(Path);
  273. if (Position == Path.size() &&
  274. Path.size() > root_dir_pos + 1 &&
  275. is_separator(Path[Position - 1])) {
  276. --Position;
  277. Component = ".";
  278. return *this;
  279. }
  280. // Skip separators unless it's the root directory.
  281. size_t end_pos = Position;
  282. while(end_pos > 0 &&
  283. (end_pos - 1) != root_dir_pos &&
  284. is_separator(Path[end_pos - 1]))
  285. --end_pos;
  286. // Find next separator.
  287. size_t start_pos = filename_pos(Path.substr(0, end_pos));
  288. Component = Path.slice(start_pos, end_pos);
  289. Position = start_pos;
  290. return *this;
  291. }
  292. bool reverse_iterator::operator==(const reverse_iterator &RHS) const {
  293. return Path.begin() == RHS.Path.begin() && Component == RHS.Component &&
  294. Position == RHS.Position;
  295. }
  296. StringRef root_path(StringRef path) {
  297. const_iterator b = begin(path),
  298. pos = b,
  299. e = end(path);
  300. if (b != e) {
  301. bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
  302. bool has_drive =
  303. #ifdef LLVM_ON_WIN32
  304. b->endswith(":");
  305. #else
  306. false;
  307. #endif
  308. if (has_net || has_drive) {
  309. if ((++pos != e) && is_separator((*pos)[0])) {
  310. // {C:/,//net/}, so get the first two components.
  311. return path.substr(0, b->size() + pos->size());
  312. } else {
  313. // just {C:,//net}, return the first component.
  314. return *b;
  315. }
  316. }
  317. // POSIX style root directory.
  318. if (is_separator((*b)[0])) {
  319. return *b;
  320. }
  321. }
  322. return StringRef();
  323. }
  324. StringRef root_name(StringRef path) {
  325. const_iterator b = begin(path),
  326. e = end(path);
  327. if (b != e) {
  328. bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
  329. bool has_drive =
  330. #ifdef LLVM_ON_WIN32
  331. b->endswith(":");
  332. #else
  333. false;
  334. #endif
  335. if (has_net || has_drive) {
  336. // just {C:,//net}, return the first component.
  337. return *b;
  338. }
  339. }
  340. // No path or no name.
  341. return StringRef();
  342. }
  343. StringRef root_directory(StringRef path) {
  344. const_iterator b = begin(path),
  345. pos = b,
  346. e = end(path);
  347. if (b != e) {
  348. bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
  349. bool has_drive =
  350. #ifdef LLVM_ON_WIN32
  351. b->endswith(":");
  352. #else
  353. false;
  354. #endif
  355. if ((has_net || has_drive) &&
  356. // {C:,//net}, skip to the next component.
  357. (++pos != e) && is_separator((*pos)[0])) {
  358. return *pos;
  359. }
  360. // POSIX style root directory.
  361. if (!has_net && is_separator((*b)[0])) {
  362. return *b;
  363. }
  364. }
  365. // No path or no root.
  366. return StringRef();
  367. }
  368. StringRef relative_path(StringRef path) {
  369. StringRef root = root_path(path);
  370. return path.substr(root.size());
  371. }
  372. void append(SmallVectorImpl<char> &path, const Twine &a,
  373. const Twine &b,
  374. const Twine &c,
  375. const Twine &d) {
  376. SmallString<32> a_storage;
  377. SmallString<32> b_storage;
  378. SmallString<32> c_storage;
  379. SmallString<32> d_storage;
  380. SmallVector<StringRef, 4> components;
  381. if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage));
  382. if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage));
  383. if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage));
  384. if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage));
  385. for (SmallVectorImpl<StringRef>::const_iterator i = components.begin(),
  386. e = components.end();
  387. i != e; ++i) {
  388. bool path_has_sep = !path.empty() && is_separator(path[path.size() - 1]);
  389. bool component_has_sep = !i->empty() && is_separator((*i)[0]);
  390. bool is_root_name = has_root_name(*i);
  391. if (path_has_sep) {
  392. // Strip separators from beginning of component.
  393. size_t loc = i->find_first_not_of(separators);
  394. StringRef c = i->substr(loc);
  395. // Append it.
  396. path.append(c.begin(), c.end());
  397. continue;
  398. }
  399. if (!component_has_sep && !(path.empty() || is_root_name)) {
  400. // Add a separator.
  401. path.push_back(preferred_separator);
  402. }
  403. path.append(i->begin(), i->end());
  404. }
  405. }
  406. void append(SmallVectorImpl<char> &path,
  407. const_iterator begin, const_iterator end) {
  408. for (; begin != end; ++begin)
  409. path::append(path, *begin);
  410. }
  411. StringRef parent_path(StringRef path) {
  412. size_t end_pos = parent_path_end(path);
  413. if (end_pos == StringRef::npos)
  414. return StringRef();
  415. else
  416. return path.substr(0, end_pos);
  417. }
  418. void remove_filename(SmallVectorImpl<char> &path) {
  419. size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()));
  420. if (end_pos != StringRef::npos)
  421. path.set_size(end_pos);
  422. }
  423. void replace_extension(SmallVectorImpl<char> &path, const Twine &extension) {
  424. StringRef p(path.begin(), path.size());
  425. SmallString<32> ext_storage;
  426. StringRef ext = extension.toStringRef(ext_storage);
  427. // Erase existing extension.
  428. size_t pos = p.find_last_of('.');
  429. if (pos != StringRef::npos && pos >= filename_pos(p))
  430. path.set_size(pos);
  431. // Append '.' if needed.
  432. if (ext.size() > 0 && ext[0] != '.')
  433. path.push_back('.');
  434. // Append extension.
  435. path.append(ext.begin(), ext.end());
  436. }
  437. void native(const Twine &path, SmallVectorImpl<char> &result) {
  438. assert((!path.isSingleStringRef() ||
  439. path.getSingleStringRef().data() != result.data()) &&
  440. "path and result are not allowed to overlap!");
  441. // Clear result.
  442. result.clear();
  443. path.toVector(result);
  444. native(result);
  445. }
  446. void native(SmallVectorImpl<char> &Path) {
  447. #ifdef LLVM_ON_WIN32
  448. std::replace(Path.begin(), Path.end(), '/', '\\');
  449. #else
  450. for (auto PI = Path.begin(), PE = Path.end(); PI < PE; ++PI) {
  451. if (*PI == '\\') {
  452. auto PN = PI + 1;
  453. if (PN < PE && *PN == '\\')
  454. ++PI; // increment once, the for loop will move over the escaped slash
  455. else
  456. *PI = '/';
  457. }
  458. }
  459. #endif
  460. }
  461. StringRef filename(StringRef path) {
  462. return *rbegin(path);
  463. }
  464. StringRef stem(StringRef path) {
  465. StringRef fname = filename(path);
  466. size_t pos = fname.find_last_of('.');
  467. if (pos == StringRef::npos)
  468. return fname;
  469. else
  470. if ((fname.size() == 1 && fname == ".") ||
  471. (fname.size() == 2 && fname == ".."))
  472. return fname;
  473. else
  474. return fname.substr(0, pos);
  475. }
  476. StringRef extension(StringRef path) {
  477. StringRef fname = filename(path);
  478. size_t pos = fname.find_last_of('.');
  479. if (pos == StringRef::npos)
  480. return StringRef();
  481. else
  482. if ((fname.size() == 1 && fname == ".") ||
  483. (fname.size() == 2 && fname == ".."))
  484. return StringRef();
  485. else
  486. return fname.substr(pos);
  487. }
  488. bool is_separator(char value) {
  489. switch(value) {
  490. #ifdef LLVM_ON_WIN32
  491. case '\\': // fall through
  492. #endif
  493. case '/': return true;
  494. default: return false;
  495. }
  496. }
  497. static const char preferred_separator_string[] = { preferred_separator, '\0' };
  498. StringRef get_separator() {
  499. return preferred_separator_string;
  500. }
  501. bool has_root_name(const Twine &path) {
  502. SmallString<128> path_storage;
  503. StringRef p = path.toStringRef(path_storage);
  504. return !root_name(p).empty();
  505. }
  506. bool has_root_directory(const Twine &path) {
  507. SmallString<128> path_storage;
  508. StringRef p = path.toStringRef(path_storage);
  509. return !root_directory(p).empty();
  510. }
  511. bool has_root_path(const Twine &path) {
  512. SmallString<128> path_storage;
  513. StringRef p = path.toStringRef(path_storage);
  514. return !root_path(p).empty();
  515. }
  516. bool has_relative_path(const Twine &path) {
  517. SmallString<128> path_storage;
  518. StringRef p = path.toStringRef(path_storage);
  519. return !relative_path(p).empty();
  520. }
  521. bool has_filename(const Twine &path) {
  522. SmallString<128> path_storage;
  523. StringRef p = path.toStringRef(path_storage);
  524. return !filename(p).empty();
  525. }
  526. bool has_parent_path(const Twine &path) {
  527. SmallString<128> path_storage;
  528. StringRef p = path.toStringRef(path_storage);
  529. return !parent_path(p).empty();
  530. }
  531. bool has_stem(const Twine &path) {
  532. SmallString<128> path_storage;
  533. StringRef p = path.toStringRef(path_storage);
  534. return !stem(p).empty();
  535. }
  536. bool has_extension(const Twine &path) {
  537. SmallString<128> path_storage;
  538. StringRef p = path.toStringRef(path_storage);
  539. return !extension(p).empty();
  540. }
  541. bool is_absolute(const Twine &path) {
  542. SmallString<128> path_storage;
  543. StringRef p = path.toStringRef(path_storage);
  544. bool rootDir = has_root_directory(p),
  545. #ifdef LLVM_ON_WIN32
  546. rootName = has_root_name(p);
  547. #else
  548. rootName = true;
  549. #endif
  550. return rootDir && rootName;
  551. }
  552. bool is_relative(const Twine &path) {
  553. return !is_absolute(path);
  554. }
  555. } // end namespace path
  556. namespace fs {
  557. std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
  558. file_status Status;
  559. std::error_code EC = status(Path, Status);
  560. if (EC)
  561. return EC;
  562. Result = Status.getUniqueID();
  563. return std::error_code();
  564. }
  565. std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
  566. SmallVectorImpl<char> &ResultPath,
  567. unsigned Mode) {
  568. return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File);
  569. }
  570. std::error_code createUniqueFile(const Twine &Model,
  571. SmallVectorImpl<char> &ResultPath) {
  572. int Dummy;
  573. return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
  574. }
  575. static std::error_code
  576. createTemporaryFile(const Twine &Model, int &ResultFD,
  577. llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
  578. SmallString<128> Storage;
  579. StringRef P = Model.toNullTerminatedStringRef(Storage);
  580. assert(P.find_first_of(separators) == StringRef::npos &&
  581. "Model must be a simple filename.");
  582. // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
  583. return createUniqueEntity(P.begin(), ResultFD, ResultPath,
  584. true, owner_read | owner_write, Type);
  585. }
  586. static std::error_code
  587. createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
  588. llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
  589. const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
  590. return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
  591. Type);
  592. }
  593. std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
  594. int &ResultFD,
  595. SmallVectorImpl<char> &ResultPath) {
  596. return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File);
  597. }
  598. std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
  599. SmallVectorImpl<char> &ResultPath) {
  600. int Dummy;
  601. return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
  602. }
  603. // This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
  604. // for consistency. We should try using mkdtemp.
  605. std::error_code createUniqueDirectory(const Twine &Prefix,
  606. SmallVectorImpl<char> &ResultPath) {
  607. int Dummy;
  608. return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath,
  609. true, 0, FS_Dir);
  610. }
  611. std::error_code make_absolute(SmallVectorImpl<char> &path) {
  612. StringRef p(path.data(), path.size());
  613. bool rootDirectory = path::has_root_directory(p),
  614. #ifdef LLVM_ON_WIN32
  615. rootName = path::has_root_name(p);
  616. #else
  617. rootName = true;
  618. #endif
  619. // Already absolute.
  620. if (rootName && rootDirectory)
  621. return std::error_code();
  622. // All of the following conditions will need the current directory.
  623. SmallString<128> current_dir;
  624. if (std::error_code ec = current_path(current_dir))
  625. return ec;
  626. // Relative path. Prepend the current directory.
  627. if (!rootName && !rootDirectory) {
  628. // Append path to the current directory.
  629. path::append(current_dir, p);
  630. // Set path to the result.
  631. path.swap(current_dir);
  632. return std::error_code();
  633. }
  634. if (!rootName && rootDirectory) {
  635. StringRef cdrn = path::root_name(current_dir);
  636. SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
  637. path::append(curDirRootName, p);
  638. // Set path to the result.
  639. path.swap(curDirRootName);
  640. return std::error_code();
  641. }
  642. if (rootName && !rootDirectory) {
  643. StringRef pRootName = path::root_name(p);
  644. StringRef bRootDirectory = path::root_directory(current_dir);
  645. StringRef bRelativePath = path::relative_path(current_dir);
  646. StringRef pRelativePath = path::relative_path(p);
  647. SmallString<128> res;
  648. path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
  649. path.swap(res);
  650. return std::error_code();
  651. }
  652. llvm_unreachable("All rootName and rootDirectory combinations should have "
  653. "occurred above!");
  654. }
  655. std::error_code create_directories(const Twine &Path, bool IgnoreExisting) {
  656. SmallString<128> PathStorage;
  657. StringRef P = Path.toStringRef(PathStorage);
  658. // Be optimistic and try to create the directory
  659. std::error_code EC = create_directory(P, IgnoreExisting);
  660. // If we succeeded, or had any error other than the parent not existing, just
  661. // return it.
  662. if (EC != errc::no_such_file_or_directory)
  663. return EC;
  664. // We failed because of a no_such_file_or_directory, try to create the
  665. // parent.
  666. StringRef Parent = path::parent_path(P);
  667. if (Parent.empty())
  668. return EC;
  669. if ((EC = create_directories(Parent)))
  670. return EC;
  671. return create_directory(P, IgnoreExisting);
  672. }
  673. std::error_code copy_file(const Twine &From, const Twine &To) {
  674. int ReadFD, WriteFD;
  675. if (std::error_code EC = openFileForRead(From, ReadFD))
  676. return EC;
  677. if (std::error_code EC = openFileForWrite(To, WriteFD, F_None)) {
  678. msf_close(ReadFD); // HLSL Change
  679. return EC;
  680. }
  681. const size_t BufSize = 4096;
  682. char *Buf = new char[BufSize];
  683. int BytesRead = 0, BytesWritten = 0;
  684. for (;;) {
  685. BytesRead = msf_read(ReadFD, Buf, BufSize); // HLSL Change
  686. if (BytesRead <= 0)
  687. break;
  688. while (BytesRead) {
  689. BytesWritten = msf_write(WriteFD, Buf, BytesRead); // HLSL Change
  690. if (BytesWritten < 0)
  691. break;
  692. BytesRead -= BytesWritten;
  693. }
  694. if (BytesWritten < 0)
  695. break;
  696. }
  697. msf_close(ReadFD); // HLSL Change
  698. msf_close(WriteFD); // HLSL Change
  699. delete[] Buf;
  700. if (BytesRead < 0 || BytesWritten < 0)
  701. return std::error_code(errno, std::generic_category());
  702. return std::error_code();
  703. }
  704. bool exists(file_status status) {
  705. return status_known(status) && status.type() != file_type::file_not_found;
  706. }
  707. bool status_known(file_status s) {
  708. return s.type() != file_type::status_error;
  709. }
  710. bool is_directory(file_status status) {
  711. return status.type() == file_type::directory_file;
  712. }
  713. std::error_code is_directory(const Twine &path, bool &result) {
  714. file_status st;
  715. if (std::error_code ec = status(path, st))
  716. return ec;
  717. result = is_directory(st);
  718. return std::error_code();
  719. }
  720. bool is_regular_file(file_status status) {
  721. return status.type() == file_type::regular_file;
  722. }
  723. std::error_code is_regular_file(const Twine &path, bool &result) {
  724. file_status st;
  725. if (std::error_code ec = status(path, st))
  726. return ec;
  727. result = is_regular_file(st);
  728. return std::error_code();
  729. }
  730. bool is_other(file_status status) {
  731. return exists(status) &&
  732. !is_regular_file(status) &&
  733. !is_directory(status);
  734. }
  735. std::error_code is_other(const Twine &Path, bool &Result) {
  736. file_status FileStatus;
  737. if (std::error_code EC = status(Path, FileStatus))
  738. return EC;
  739. Result = is_other(FileStatus);
  740. return std::error_code();
  741. }
  742. void directory_entry::replace_filename(const Twine &filename, file_status st) {
  743. SmallString<128> path(Path.begin(), Path.end());
  744. path::remove_filename(path);
  745. path::append(path, filename);
  746. Path = path.str();
  747. Status = st;
  748. }
  749. /// @brief Identify the magic in magic.
  750. file_magic identify_magic(StringRef Magic) {
  751. if (Magic.size() < 4)
  752. return file_magic::unknown;
  753. switch ((unsigned char)Magic[0]) {
  754. case 0x00: {
  755. // COFF bigobj or short import library file
  756. if (Magic[1] == (char)0x00 && Magic[2] == (char)0xff &&
  757. Magic[3] == (char)0xff) {
  758. size_t MinSize = offsetof(COFF::BigObjHeader, UUID) + sizeof(COFF::BigObjMagic);
  759. if (Magic.size() < MinSize)
  760. return file_magic::coff_import_library;
  761. int BigObjVersion = read16le(
  762. Magic.data() + offsetof(COFF::BigObjHeader, Version));
  763. if (BigObjVersion < COFF::BigObjHeader::MinBigObjectVersion)
  764. return file_magic::coff_import_library;
  765. const char *Start = Magic.data() + offsetof(COFF::BigObjHeader, UUID);
  766. if (memcmp(Start, COFF::BigObjMagic, sizeof(COFF::BigObjMagic)) != 0)
  767. return file_magic::coff_import_library;
  768. return file_magic::coff_object;
  769. }
  770. // Windows resource file
  771. const char Expected[] = { 0, 0, 0, 0, '\x20', 0, 0, 0, '\xff' };
  772. if (Magic.size() >= sizeof(Expected) &&
  773. memcmp(Magic.data(), Expected, sizeof(Expected)) == 0)
  774. return file_magic::windows_resource;
  775. // 0x0000 = COFF unknown machine type
  776. if (Magic[1] == 0)
  777. return file_magic::coff_object;
  778. break;
  779. }
  780. case 0xDE: // 0x0B17C0DE = BC wraper
  781. if (Magic[1] == (char)0xC0 && Magic[2] == (char)0x17 &&
  782. Magic[3] == (char)0x0B)
  783. return file_magic::bitcode;
  784. break;
  785. case 'B':
  786. if (Magic[1] == 'C' && Magic[2] == (char)0xC0 && Magic[3] == (char)0xDE)
  787. return file_magic::bitcode;
  788. break;
  789. case '!':
  790. if (Magic.size() >= 8)
  791. if (memcmp(Magic.data(),"!<arch>\n",8) == 0)
  792. return file_magic::archive;
  793. break;
  794. case '\177':
  795. if (Magic.size() >= 18 && Magic[1] == 'E' && Magic[2] == 'L' &&
  796. Magic[3] == 'F') {
  797. bool Data2MSB = Magic[5] == 2;
  798. unsigned high = Data2MSB ? 16 : 17;
  799. unsigned low = Data2MSB ? 17 : 16;
  800. if (Magic[high] == 0)
  801. switch (Magic[low]) {
  802. default: return file_magic::elf;
  803. case 1: return file_magic::elf_relocatable;
  804. case 2: return file_magic::elf_executable;
  805. case 3: return file_magic::elf_shared_object;
  806. case 4: return file_magic::elf_core;
  807. }
  808. else
  809. // It's still some type of ELF file.
  810. return file_magic::elf;
  811. }
  812. break;
  813. case 0xCA:
  814. if (Magic[1] == char(0xFE) && Magic[2] == char(0xBA) &&
  815. Magic[3] == char(0xBE)) {
  816. // This is complicated by an overlap with Java class files.
  817. // See the Mach-O section in /usr/share/file/magic for details.
  818. if (Magic.size() >= 8 && Magic[7] < 43)
  819. return file_magic::macho_universal_binary;
  820. }
  821. break;
  822. // The two magic numbers for mach-o are:
  823. // 0xfeedface - 32-bit mach-o
  824. // 0xfeedfacf - 64-bit mach-o
  825. case 0xFE:
  826. case 0xCE:
  827. case 0xCF: {
  828. uint16_t type = 0;
  829. if (Magic[0] == char(0xFE) && Magic[1] == char(0xED) &&
  830. Magic[2] == char(0xFA) &&
  831. (Magic[3] == char(0xCE) || Magic[3] == char(0xCF))) {
  832. /* Native endian */
  833. if (Magic.size() >= 16) type = Magic[14] << 8 | Magic[15];
  834. } else if ((Magic[0] == char(0xCE) || Magic[0] == char(0xCF)) &&
  835. Magic[1] == char(0xFA) && Magic[2] == char(0xED) &&
  836. Magic[3] == char(0xFE)) {
  837. /* Reverse endian */
  838. if (Magic.size() >= 14) type = Magic[13] << 8 | Magic[12];
  839. }
  840. switch (type) {
  841. default: break;
  842. case 1: return file_magic::macho_object;
  843. case 2: return file_magic::macho_executable;
  844. case 3: return file_magic::macho_fixed_virtual_memory_shared_lib;
  845. case 4: return file_magic::macho_core;
  846. case 5: return file_magic::macho_preload_executable;
  847. case 6: return file_magic::macho_dynamically_linked_shared_lib;
  848. case 7: return file_magic::macho_dynamic_linker;
  849. case 8: return file_magic::macho_bundle;
  850. case 9: return file_magic::macho_dynamically_linked_shared_lib_stub;
  851. case 10: return file_magic::macho_dsym_companion;
  852. case 11: return file_magic::macho_kext_bundle;
  853. }
  854. break;
  855. }
  856. case 0xF0: // PowerPC Windows
  857. case 0x83: // Alpha 32-bit
  858. case 0x84: // Alpha 64-bit
  859. case 0x66: // MPS R4000 Windows
  860. case 0x50: // mc68K
  861. case 0x4c: // 80386 Windows
  862. case 0xc4: // ARMNT Windows
  863. if (Magic[1] == 0x01)
  864. return file_magic::coff_object;
  865. case 0x90: // PA-RISC Windows
  866. case 0x68: // mc68K Windows
  867. if (Magic[1] == 0x02)
  868. return file_magic::coff_object;
  869. break;
  870. case 'M': // Possible MS-DOS stub on Windows PE file
  871. if (Magic[1] == 'Z') {
  872. uint32_t off = read32le(Magic.data() + 0x3c);
  873. // PE/COFF file, either EXE or DLL.
  874. if (off < Magic.size() &&
  875. memcmp(Magic.data()+off, COFF::PEMagic, sizeof(COFF::PEMagic)) == 0)
  876. return file_magic::pecoff_executable;
  877. }
  878. break;
  879. case 0x64: // x86-64 Windows.
  880. if (Magic[1] == char(0x86))
  881. return file_magic::coff_object;
  882. break;
  883. default:
  884. break;
  885. }
  886. return file_magic::unknown;
  887. }
  888. std::error_code identify_magic(const Twine &Path, file_magic &Result) {
  889. int FD;
  890. if (std::error_code EC = openFileForRead(Path, FD))
  891. return EC;
  892. char Buffer[32];
  893. int Length = msf_read(FD, Buffer, sizeof(Buffer)); // HLSL Change
  894. if (msf_close(FD) != 0 || Length < 0) // HLSL Change
  895. return std::error_code(errno, std::generic_category());
  896. Result = identify_magic(StringRef(Buffer, Length));
  897. return std::error_code();
  898. }
  899. std::error_code directory_entry::status(file_status &result) const {
  900. return fs::status(Path, result);
  901. }
  902. } // end namespace fs
  903. } // end namespace sys
  904. } // end namespace llvm
  905. // Include the truly platform-specific parts.
  906. #if defined(LLVM_ON_UNIX)
  907. #include "Unix/Path.inc"
  908. #endif
  909. #if defined(LLVM_ON_WIN32)
  910. #include "Windows/MSFileSystem.inc.cpp"
  911. #endif