Path.cpp 39 KB

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