Path.cpp 39 KB

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