FileSystem.h 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/Support/FileSystem.h - File System OS Concept -------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file declares the llvm::sys::fs namespace. It is designed after
  15. // TR2/boost filesystem (v3), but modified to remove exception handling and the
  16. // path class.
  17. //
  18. // All functions return an error_code and their actual work via the last out
  19. // argument. The out argument is defined if and only if errc::success is
  20. // returned. A function may return any error code in the generic or system
  21. // category. However, they shall be equivalent to any error conditions listed
  22. // in each functions respective documentation if the condition applies. [ note:
  23. // this does not guarantee that error_code will be in the set of explicitly
  24. // listed codes, but it does guarantee that if any of the explicitly listed
  25. // errors occur, the correct error_code will be used ]. All functions may
  26. // return errc::not_enough_memory if there is not enough memory to complete the
  27. // operation.
  28. //
  29. //===----------------------------------------------------------------------===//
  30. #ifndef LLVM_SUPPORT_FILESYSTEM_H
  31. #define LLVM_SUPPORT_FILESYSTEM_H
  32. #include "llvm/ADT/SmallString.h"
  33. #include "llvm/ADT/StringRef.h"
  34. #include "llvm/ADT/Twine.h"
  35. #include "llvm/Config/llvm-config.h"
  36. #include "llvm/Support/Chrono.h"
  37. #include "llvm/Support/Error.h"
  38. #include "llvm/Support/ErrorHandling.h"
  39. #include "llvm/Support/ErrorOr.h"
  40. #include "llvm/Support/FileSystem/UniqueID.h"
  41. #include "llvm/Support/MD5.h"
  42. #include <cassert>
  43. #include <cstdint>
  44. #include <ctime>
  45. #include <memory>
  46. #include <stack>
  47. #include <string>
  48. #include <system_error>
  49. #include <vector>
  50. #ifdef HAVE_SYS_STAT_H
  51. #include <sys/stat.h>
  52. #endif
  53. namespace llvm {
  54. namespace sys {
  55. namespace fs {
  56. #if defined(_WIN32)
  57. // A Win32 HANDLE is a typedef of void*
  58. using file_t = void *;
  59. #else
  60. using file_t = int;
  61. #endif
  62. extern const file_t kInvalidFile;
  63. /// An enumeration for the file system's view of the type.
  64. enum class file_type {
  65. status_error,
  66. file_not_found,
  67. regular_file,
  68. directory_file,
  69. symlink_file,
  70. block_file,
  71. character_file,
  72. fifo_file,
  73. socket_file,
  74. type_unknown
  75. };
  76. /// space_info - Self explanatory.
  77. struct space_info {
  78. uint64_t capacity;
  79. uint64_t free;
  80. uint64_t available;
  81. };
  82. enum perms {
  83. no_perms = 0,
  84. owner_read = 0400,
  85. owner_write = 0200,
  86. owner_exe = 0100,
  87. owner_all = owner_read | owner_write | owner_exe,
  88. group_read = 040,
  89. group_write = 020,
  90. group_exe = 010,
  91. group_all = group_read | group_write | group_exe,
  92. others_read = 04,
  93. others_write = 02,
  94. others_exe = 01,
  95. others_all = others_read | others_write | others_exe,
  96. all_read = owner_read | group_read | others_read,
  97. all_write = owner_write | group_write | others_write,
  98. all_exe = owner_exe | group_exe | others_exe,
  99. all_all = owner_all | group_all | others_all,
  100. set_uid_on_exe = 04000,
  101. set_gid_on_exe = 02000,
  102. sticky_bit = 01000,
  103. all_perms = all_all | set_uid_on_exe | set_gid_on_exe | sticky_bit,
  104. perms_not_known = 0xFFFF
  105. };
  106. // Helper functions so that you can use & and | to manipulate perms bits:
  107. inline perms operator|(perms l, perms r) {
  108. return static_cast<perms>(static_cast<unsigned short>(l) |
  109. static_cast<unsigned short>(r));
  110. }
  111. inline perms operator&(perms l, perms r) {
  112. return static_cast<perms>(static_cast<unsigned short>(l) &
  113. static_cast<unsigned short>(r));
  114. }
  115. inline perms &operator|=(perms &l, perms r) {
  116. l = l | r;
  117. return l;
  118. }
  119. inline perms &operator&=(perms &l, perms r) {
  120. l = l & r;
  121. return l;
  122. }
  123. inline perms operator~(perms x) {
  124. // Avoid UB by explicitly truncating the (unsigned) ~ result.
  125. return static_cast<perms>(
  126. static_cast<unsigned short>(~static_cast<unsigned short>(x)));
  127. }
  128. /// Represents the result of a call to directory_iterator::status(). This is a
  129. /// subset of the information returned by a regular sys::fs::status() call, and
  130. /// represents the information provided by Windows FileFirstFile/FindNextFile.
  131. class basic_file_status {
  132. protected:
  133. #if defined(LLVM_ON_UNIX)
  134. time_t fs_st_atime = 0;
  135. time_t fs_st_mtime = 0;
  136. uint32_t fs_st_atime_nsec = 0;
  137. uint32_t fs_st_mtime_nsec = 0;
  138. uid_t fs_st_uid = 0;
  139. gid_t fs_st_gid = 0;
  140. off_t fs_st_size = 0;
  141. #elif defined (_WIN32)
  142. uint32_t LastAccessedTimeHigh = 0;
  143. uint32_t LastAccessedTimeLow = 0;
  144. uint32_t LastWriteTimeHigh = 0;
  145. uint32_t LastWriteTimeLow = 0;
  146. uint32_t FileSizeHigh = 0;
  147. uint32_t FileSizeLow = 0;
  148. #endif
  149. file_type Type = file_type::status_error;
  150. perms Perms = perms_not_known;
  151. public:
  152. basic_file_status() = default;
  153. explicit basic_file_status(file_type Type) : Type(Type) {}
  154. #if defined(LLVM_ON_UNIX)
  155. basic_file_status(file_type Type, perms Perms, time_t ATime,
  156. uint32_t ATimeNSec, time_t MTime, uint32_t MTimeNSec,
  157. uid_t UID, gid_t GID, off_t Size)
  158. : fs_st_atime(ATime), fs_st_mtime(MTime),
  159. fs_st_atime_nsec(ATimeNSec), fs_st_mtime_nsec(MTimeNSec),
  160. fs_st_uid(UID), fs_st_gid(GID),
  161. fs_st_size(Size), Type(Type), Perms(Perms) {}
  162. #elif defined(_WIN32)
  163. basic_file_status(file_type Type, perms Perms, uint32_t LastAccessTimeHigh,
  164. uint32_t LastAccessTimeLow, uint32_t LastWriteTimeHigh,
  165. uint32_t LastWriteTimeLow, uint32_t FileSizeHigh,
  166. uint32_t FileSizeLow)
  167. : LastAccessedTimeHigh(LastAccessTimeHigh),
  168. LastAccessedTimeLow(LastAccessTimeLow),
  169. LastWriteTimeHigh(LastWriteTimeHigh),
  170. LastWriteTimeLow(LastWriteTimeLow), FileSizeHigh(FileSizeHigh),
  171. FileSizeLow(FileSizeLow), Type(Type), Perms(Perms) {}
  172. #endif
  173. // getters
  174. file_type type() const { return Type; }
  175. perms permissions() const { return Perms; }
  176. /// The file access time as reported from the underlying file system.
  177. ///
  178. /// Also see comments on \c getLastModificationTime() related to the precision
  179. /// of the returned value.
  180. TimePoint<> getLastAccessedTime() const;
  181. /// The file modification time as reported from the underlying file system.
  182. ///
  183. /// The returned value allows for nanosecond precision but the actual
  184. /// resolution is an implementation detail of the underlying file system.
  185. /// There is no guarantee for what kind of resolution you can expect, the
  186. /// resolution can differ across platforms and even across mountpoints on the
  187. /// same machine.
  188. TimePoint<> getLastModificationTime() const;
  189. #if defined(LLVM_ON_UNIX)
  190. uint32_t getUser() const { return fs_st_uid; }
  191. uint32_t getGroup() const { return fs_st_gid; }
  192. uint64_t getSize() const { return fs_st_size; }
  193. #elif defined (_WIN32)
  194. uint32_t getUser() const {
  195. return 9999; // Not applicable to Windows, so...
  196. }
  197. uint32_t getGroup() const {
  198. return 9999; // Not applicable to Windows, so...
  199. }
  200. uint64_t getSize() const {
  201. return (uint64_t(FileSizeHigh) << 32) + FileSizeLow;
  202. }
  203. #endif
  204. // setters
  205. void type(file_type v) { Type = v; }
  206. void permissions(perms p) { Perms = p; }
  207. };
  208. /// Represents the result of a call to sys::fs::status().
  209. class file_status : public basic_file_status {
  210. friend bool equivalent(file_status A, file_status B);
  211. #if defined(LLVM_ON_UNIX)
  212. dev_t fs_st_dev = 0;
  213. nlink_t fs_st_nlinks = 0;
  214. ino_t fs_st_ino = 0;
  215. #elif defined (_WIN32)
  216. uint32_t NumLinks = 0;
  217. uint32_t VolumeSerialNumber = 0;
  218. uint32_t FileIndexHigh = 0;
  219. uint32_t FileIndexLow = 0;
  220. #endif
  221. public:
  222. file_status() = default;
  223. explicit file_status(file_type Type) : basic_file_status(Type) {}
  224. #if defined(LLVM_ON_UNIX)
  225. file_status(file_type Type, perms Perms, dev_t Dev, nlink_t Links, ino_t Ino,
  226. time_t ATime, uint32_t ATimeNSec,
  227. time_t MTime, uint32_t MTimeNSec,
  228. uid_t UID, gid_t GID, off_t Size)
  229. : basic_file_status(Type, Perms, ATime, ATimeNSec, MTime, MTimeNSec,
  230. UID, GID, Size),
  231. fs_st_dev(Dev), fs_st_nlinks(Links), fs_st_ino(Ino) {}
  232. #elif defined(_WIN32)
  233. file_status(file_type Type, perms Perms, uint32_t LinkCount,
  234. uint32_t LastAccessTimeHigh, uint32_t LastAccessTimeLow,
  235. uint32_t LastWriteTimeHigh, uint32_t LastWriteTimeLow,
  236. uint32_t VolumeSerialNumber, uint32_t FileSizeHigh,
  237. uint32_t FileSizeLow, uint32_t FileIndexHigh,
  238. uint32_t FileIndexLow)
  239. : basic_file_status(Type, Perms, LastAccessTimeHigh, LastAccessTimeLow,
  240. LastWriteTimeHigh, LastWriteTimeLow, FileSizeHigh,
  241. FileSizeLow),
  242. NumLinks(LinkCount), VolumeSerialNumber(VolumeSerialNumber),
  243. FileIndexHigh(FileIndexHigh), FileIndexLow(FileIndexLow) {}
  244. #endif
  245. UniqueID getUniqueID() const;
  246. uint32_t getLinkCount() const;
  247. };
  248. /// @}
  249. /// @name Physical Operators
  250. /// @{
  251. /// Make \a path an absolute path.
  252. ///
  253. /// Makes \a path absolute using the \a current_directory if it is not already.
  254. /// An empty \a path will result in the \a current_directory.
  255. ///
  256. /// /absolute/path => /absolute/path
  257. /// relative/../path => <current-directory>/relative/../path
  258. ///
  259. /// @param path A path that is modified to be an absolute path.
  260. void make_absolute(const Twine &current_directory, SmallVectorImpl<char> &path);
  261. /// Make \a path an absolute path.
  262. ///
  263. /// Makes \a path absolute using the current directory if it is not already. An
  264. /// empty \a path will result in the current directory.
  265. ///
  266. /// /absolute/path => /absolute/path
  267. /// relative/../path => <current-directory>/relative/../path
  268. ///
  269. /// @param path A path that is modified to be an absolute path.
  270. /// @returns errc::success if \a path has been made absolute, otherwise a
  271. /// platform-specific error_code.
  272. std::error_code make_absolute(SmallVectorImpl<char> &path);
  273. /// Create all the non-existent directories in path.
  274. ///
  275. /// @param path Directories to create.
  276. /// @returns errc::success if is_directory(path), otherwise a platform
  277. /// specific error_code. If IgnoreExisting is false, also returns
  278. /// error if the directory already existed.
  279. std::error_code create_directories(const Twine &path,
  280. bool IgnoreExisting = true,
  281. perms Perms = owner_all | group_all);
  282. /// Create the directory in path.
  283. ///
  284. /// @param path Directory to create.
  285. /// @returns errc::success if is_directory(path), otherwise a platform
  286. /// specific error_code. If IgnoreExisting is false, also returns
  287. /// error if the directory already existed.
  288. std::error_code create_directory(const Twine &path, bool IgnoreExisting = true,
  289. perms Perms = owner_all | group_all);
  290. /// Create a link from \a from to \a to.
  291. ///
  292. /// The link may be a soft or a hard link, depending on the platform. The caller
  293. /// may not assume which one. Currently on windows it creates a hard link since
  294. /// soft links require extra privileges. On unix, it creates a soft link since
  295. /// hard links don't work on SMB file systems.
  296. ///
  297. /// @param to The path to hard link to.
  298. /// @param from The path to hard link from. This is created.
  299. /// @returns errc::success if the link was created, otherwise a platform
  300. /// specific error_code.
  301. std::error_code create_link(const Twine &to, const Twine &from);
  302. /// Create a hard link from \a from to \a to, or return an error.
  303. ///
  304. /// @param to The path to hard link to.
  305. /// @param from The path to hard link from. This is created.
  306. /// @returns errc::success if the link was created, otherwise a platform
  307. /// specific error_code.
  308. std::error_code create_hard_link(const Twine &to, const Twine &from);
  309. /// Collapse all . and .. patterns, resolve all symlinks, and optionally
  310. /// expand ~ expressions to the user's home directory.
  311. ///
  312. /// @param path The path to resolve.
  313. /// @param output The location to store the resolved path.
  314. /// @param expand_tilde If true, resolves ~ expressions to the user's home
  315. /// directory.
  316. std::error_code real_path(const Twine &path, SmallVectorImpl<char> &output,
  317. bool expand_tilde = false);
  318. /// Expands ~ expressions to the user's home directory. On Unix ~user
  319. /// directories are resolved as well.
  320. ///
  321. /// @param path The path to resolve.
  322. void expand_tilde(const Twine &path, SmallVectorImpl<char> &output);
  323. /// Get the current path.
  324. ///
  325. /// @param result Holds the current path on return.
  326. /// @returns errc::success if the current path has been stored in result,
  327. /// otherwise a platform-specific error_code.
  328. std::error_code current_path(SmallVectorImpl<char> &result);
  329. /// Set the current path.
  330. ///
  331. /// @param path The path to set.
  332. /// @returns errc::success if the current path was successfully set,
  333. /// otherwise a platform-specific error_code.
  334. std::error_code set_current_path(const Twine &path);
  335. /// Remove path. Equivalent to POSIX remove().
  336. ///
  337. /// @param path Input path.
  338. /// @returns errc::success if path has been removed or didn't exist, otherwise a
  339. /// platform-specific error code. If IgnoreNonExisting is false, also
  340. /// returns error if the file didn't exist.
  341. std::error_code remove(const Twine &path, bool IgnoreNonExisting = true);
  342. /// Recursively delete a directory.
  343. ///
  344. /// @param path Input path.
  345. /// @returns errc::success if path has been removed or didn't exist, otherwise a
  346. /// platform-specific error code.
  347. std::error_code remove_directories(const Twine &path, bool IgnoreErrors = true);
  348. /// Rename \a from to \a to.
  349. ///
  350. /// Files are renamed as if by POSIX rename(), except that on Windows there may
  351. /// be a short interval of time during which the destination file does not
  352. /// exist.
  353. ///
  354. /// @param from The path to rename from.
  355. /// @param to The path to rename to. This is created.
  356. std::error_code rename(const Twine &from, const Twine &to);
  357. /// Copy the contents of \a From to \a To.
  358. ///
  359. /// @param From The path to copy from.
  360. /// @param To The path to copy to. This is created.
  361. std::error_code copy_file(const Twine &From, const Twine &To);
  362. /// Copy the contents of \a From to \a To.
  363. ///
  364. /// @param From The path to copy from.
  365. /// @param ToFD The open file descriptor of the destination file.
  366. std::error_code copy_file(const Twine &From, int ToFD);
  367. /// Resize path to size. File is resized as if by POSIX truncate().
  368. ///
  369. /// @param FD Input file descriptor.
  370. /// @param Size Size to resize to.
  371. /// @returns errc::success if \a path has been resized to \a size, otherwise a
  372. /// platform-specific error_code.
  373. std::error_code resize_file(int FD, uint64_t Size);
  374. /// Resize \p FD to \p Size before mapping \a mapped_file_region::readwrite. On
  375. /// non-Windows, this calls \a resize_file(). On Windows, this is a no-op,
  376. /// since the subsequent mapping (via \c CreateFileMapping) automatically
  377. /// extends the file.
  378. inline std::error_code resize_file_before_mapping_readwrite(int FD,
  379. uint64_t Size) {
  380. #ifdef _WIN32
  381. (void)FD;
  382. (void)Size;
  383. return std::error_code();
  384. #else
  385. return resize_file(FD, Size);
  386. #endif
  387. }
  388. /// Compute an MD5 hash of a file's contents.
  389. ///
  390. /// @param FD Input file descriptor.
  391. /// @returns An MD5Result with the hash computed, if successful, otherwise a
  392. /// std::error_code.
  393. ErrorOr<MD5::MD5Result> md5_contents(int FD);
  394. /// Version of compute_md5 that doesn't require an open file descriptor.
  395. ErrorOr<MD5::MD5Result> md5_contents(const Twine &Path);
  396. /// @}
  397. /// @name Physical Observers
  398. /// @{
  399. /// Does file exist?
  400. ///
  401. /// @param status A basic_file_status previously returned from stat.
  402. /// @returns True if the file represented by status exists, false if it does
  403. /// not.
  404. bool exists(const basic_file_status &status);
  405. enum class AccessMode { Exist, Write, Execute };
  406. /// Can the file be accessed?
  407. ///
  408. /// @param Path Input path.
  409. /// @returns errc::success if the path can be accessed, otherwise a
  410. /// platform-specific error_code.
  411. std::error_code access(const Twine &Path, AccessMode Mode);
  412. /// Does file exist?
  413. ///
  414. /// @param Path Input path.
  415. /// @returns True if it exists, false otherwise.
  416. inline bool exists(const Twine &Path) {
  417. return !access(Path, AccessMode::Exist);
  418. }
  419. /// Can we execute this file?
  420. ///
  421. /// @param Path Input path.
  422. /// @returns True if we can execute it, false otherwise.
  423. bool can_execute(const Twine &Path);
  424. /// Can we write this file?
  425. ///
  426. /// @param Path Input path.
  427. /// @returns True if we can write to it, false otherwise.
  428. inline bool can_write(const Twine &Path) {
  429. return !access(Path, AccessMode::Write);
  430. }
  431. /// Do file_status's represent the same thing?
  432. ///
  433. /// @param A Input file_status.
  434. /// @param B Input file_status.
  435. ///
  436. /// assert(status_known(A) || status_known(B));
  437. ///
  438. /// @returns True if A and B both represent the same file system entity, false
  439. /// otherwise.
  440. bool equivalent(file_status A, file_status B);
  441. /// Do paths represent the same thing?
  442. ///
  443. /// assert(status_known(A) || status_known(B));
  444. ///
  445. /// @param A Input path A.
  446. /// @param B Input path B.
  447. /// @param result Set to true if stat(A) and stat(B) have the same device and
  448. /// inode (or equivalent).
  449. /// @returns errc::success if result has been successfully set, otherwise a
  450. /// platform-specific error_code.
  451. std::error_code equivalent(const Twine &A, const Twine &B, bool &result);
  452. /// Simpler version of equivalent for clients that don't need to
  453. /// differentiate between an error and false.
  454. inline bool equivalent(const Twine &A, const Twine &B) {
  455. bool result;
  456. return !equivalent(A, B, result) && result;
  457. }
  458. /// Is the file mounted on a local filesystem?
  459. ///
  460. /// @param path Input path.
  461. /// @param result Set to true if \a path is on fixed media such as a hard disk,
  462. /// false if it is not.
  463. /// @returns errc::success if result has been successfully set, otherwise a
  464. /// platform specific error_code.
  465. std::error_code is_local(const Twine &path, bool &result);
  466. /// Version of is_local accepting an open file descriptor.
  467. std::error_code is_local(int FD, bool &result);
  468. /// Simpler version of is_local for clients that don't need to
  469. /// differentiate between an error and false.
  470. inline bool is_local(const Twine &Path) {
  471. bool Result;
  472. return !is_local(Path, Result) && Result;
  473. }
  474. /// Simpler version of is_local accepting an open file descriptor for
  475. /// clients that don't need to differentiate between an error and false.
  476. inline bool is_local(int FD) {
  477. bool Result;
  478. return !is_local(FD, Result) && Result;
  479. }
  480. /// Does status represent a directory?
  481. ///
  482. /// @param Path The path to get the type of.
  483. /// @param Follow For symbolic links, indicates whether to return the file type
  484. /// of the link itself, or of the target.
  485. /// @returns A value from the file_type enumeration indicating the type of file.
  486. file_type get_file_type(const Twine &Path, bool Follow = true);
  487. /// Does status represent a directory?
  488. ///
  489. /// @param status A basic_file_status previously returned from status.
  490. /// @returns status.type() == file_type::directory_file.
  491. bool is_directory(const basic_file_status &status);
  492. /// Is path a directory?
  493. ///
  494. /// @param path Input path.
  495. /// @param result Set to true if \a path is a directory (after following
  496. /// symlinks, false if it is not. Undefined otherwise.
  497. /// @returns errc::success if result has been successfully set, otherwise a
  498. /// platform-specific error_code.
  499. std::error_code is_directory(const Twine &path, bool &result);
  500. /// Simpler version of is_directory for clients that don't need to
  501. /// differentiate between an error and false.
  502. inline bool is_directory(const Twine &Path) {
  503. bool Result;
  504. return !is_directory(Path, Result) && Result;
  505. }
  506. /// Does status represent a regular file?
  507. ///
  508. /// @param status A basic_file_status previously returned from status.
  509. /// @returns status_known(status) && status.type() == file_type::regular_file.
  510. bool is_regular_file(const basic_file_status &status);
  511. /// Is path a regular file?
  512. ///
  513. /// @param path Input path.
  514. /// @param result Set to true if \a path is a regular file (after following
  515. /// symlinks), false if it is not. Undefined otherwise.
  516. /// @returns errc::success if result has been successfully set, otherwise a
  517. /// platform-specific error_code.
  518. std::error_code is_regular_file(const Twine &path, bool &result);
  519. /// Simpler version of is_regular_file for clients that don't need to
  520. /// differentiate between an error and false.
  521. inline bool is_regular_file(const Twine &Path) {
  522. bool Result;
  523. if (is_regular_file(Path, Result))
  524. return false;
  525. return Result;
  526. }
  527. /// Does status represent a symlink file?
  528. ///
  529. /// @param status A basic_file_status previously returned from status.
  530. /// @returns status_known(status) && status.type() == file_type::symlink_file.
  531. bool is_symlink_file(const basic_file_status &status);
  532. /// Is path a symlink file?
  533. ///
  534. /// @param path Input path.
  535. /// @param result Set to true if \a path is a symlink file, false if it is not.
  536. /// Undefined otherwise.
  537. /// @returns errc::success if result has been successfully set, otherwise a
  538. /// platform-specific error_code.
  539. std::error_code is_symlink_file(const Twine &path, bool &result);
  540. /// Simpler version of is_symlink_file for clients that don't need to
  541. /// differentiate between an error and false.
  542. inline bool is_symlink_file(const Twine &Path) {
  543. bool Result;
  544. if (is_symlink_file(Path, Result))
  545. return false;
  546. return Result;
  547. }
  548. /// Does this status represent something that exists but is not a
  549. /// directory or regular file?
  550. ///
  551. /// @param status A basic_file_status previously returned from status.
  552. /// @returns exists(s) && !is_regular_file(s) && !is_directory(s)
  553. bool is_other(const basic_file_status &status);
  554. /// Is path something that exists but is not a directory,
  555. /// regular file, or symlink?
  556. ///
  557. /// @param path Input path.
  558. /// @param result Set to true if \a path exists, but is not a directory, regular
  559. /// file, or a symlink, false if it does not. Undefined otherwise.
  560. /// @returns errc::success if result has been successfully set, otherwise a
  561. /// platform-specific error_code.
  562. std::error_code is_other(const Twine &path, bool &result);
  563. /// Get file status as if by POSIX stat().
  564. ///
  565. /// @param path Input path.
  566. /// @param result Set to the file status.
  567. /// @param follow When true, follows symlinks. Otherwise, the symlink itself is
  568. /// statted.
  569. /// @returns errc::success if result has been successfully set, otherwise a
  570. /// platform-specific error_code.
  571. std::error_code status(const Twine &path, file_status &result,
  572. bool follow = true);
  573. /// A version for when a file descriptor is already available.
  574. std::error_code status(int FD, file_status &Result);
  575. #ifdef _WIN32
  576. /// A version for when a file descriptor is already available.
  577. std::error_code status(file_t FD, file_status &Result);
  578. #endif
  579. /// Get file creation mode mask of the process.
  580. ///
  581. /// @returns Mask reported by umask(2)
  582. /// @note There is no umask on Windows. This function returns 0 always
  583. /// on Windows. This function does not return an error_code because
  584. /// umask(2) never fails. It is not thread safe.
  585. unsigned getUmask();
  586. /// Set file permissions.
  587. ///
  588. /// @param Path File to set permissions on.
  589. /// @param Permissions New file permissions.
  590. /// @returns errc::success if the permissions were successfully set, otherwise
  591. /// a platform-specific error_code.
  592. /// @note On Windows, all permissions except *_write are ignored. Using any of
  593. /// owner_write, group_write, or all_write will make the file writable.
  594. /// Otherwise, the file will be marked as read-only.
  595. std::error_code setPermissions(const Twine &Path, perms Permissions);
  596. /// Vesion of setPermissions accepting a file descriptor.
  597. /// TODO Delete the path based overload once we implement the FD based overload
  598. /// on Windows.
  599. std::error_code setPermissions(int FD, perms Permissions);
  600. /// Get file permissions.
  601. ///
  602. /// @param Path File to get permissions from.
  603. /// @returns the permissions if they were successfully retrieved, otherwise a
  604. /// platform-specific error_code.
  605. /// @note On Windows, if the file does not have the FILE_ATTRIBUTE_READONLY
  606. /// attribute, all_all will be returned. Otherwise, all_read | all_exe
  607. /// will be returned.
  608. ErrorOr<perms> getPermissions(const Twine &Path);
  609. /// Get file size.
  610. ///
  611. /// @param Path Input path.
  612. /// @param Result Set to the size of the file in \a Path.
  613. /// @returns errc::success if result has been successfully set, otherwise a
  614. /// platform-specific error_code.
  615. inline std::error_code file_size(const Twine &Path, uint64_t &Result) {
  616. file_status Status;
  617. std::error_code EC = status(Path, Status);
  618. if (EC)
  619. return EC;
  620. Result = Status.getSize();
  621. return std::error_code();
  622. }
  623. /// Set the file modification and access time.
  624. ///
  625. /// @returns errc::success if the file times were successfully set, otherwise a
  626. /// platform-specific error_code or errc::function_not_supported on
  627. /// platforms where the functionality isn't available.
  628. std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
  629. TimePoint<> ModificationTime);
  630. /// Simpler version that sets both file modification and access time to the same
  631. /// time.
  632. inline std::error_code setLastAccessAndModificationTime(int FD,
  633. TimePoint<> Time) {
  634. return setLastAccessAndModificationTime(FD, Time, Time);
  635. }
  636. /// Is status available?
  637. ///
  638. /// @param s Input file status.
  639. /// @returns True if status() != status_error.
  640. bool status_known(const basic_file_status &s);
  641. /// Is status available?
  642. ///
  643. /// @param path Input path.
  644. /// @param result Set to true if status() != status_error.
  645. /// @returns errc::success if result has been successfully set, otherwise a
  646. /// platform-specific error_code.
  647. std::error_code status_known(const Twine &path, bool &result);
  648. enum CreationDisposition : unsigned {
  649. /// CD_CreateAlways - When opening a file:
  650. /// * If it already exists, truncate it.
  651. /// * If it does not already exist, create a new file.
  652. CD_CreateAlways = 0,
  653. /// CD_CreateNew - When opening a file:
  654. /// * If it already exists, fail.
  655. /// * If it does not already exist, create a new file.
  656. CD_CreateNew = 1,
  657. /// CD_OpenExisting - When opening a file:
  658. /// * If it already exists, open the file with the offset set to 0.
  659. /// * If it does not already exist, fail.
  660. CD_OpenExisting = 2,
  661. /// CD_OpenAlways - When opening a file:
  662. /// * If it already exists, open the file with the offset set to 0.
  663. /// * If it does not already exist, create a new file.
  664. CD_OpenAlways = 3,
  665. };
  666. enum FileAccess : unsigned {
  667. FA_Read = 1,
  668. FA_Write = 2,
  669. };
  670. enum OpenFlags : unsigned {
  671. OF_None = 0,
  672. /// The file should be opened in text mode on platforms like z/OS that make
  673. /// this distinction.
  674. OF_Text = 1,
  675. /// The file should use a carriage linefeed '\r\n'. This flag should only be
  676. /// used with OF_Text. Only makes a difference on Windows.
  677. OF_CRLF = 2,
  678. /// The file should be opened in text mode and use a carriage linefeed '\r\n'.
  679. /// This flag has the same functionality as OF_Text on z/OS but adds a
  680. /// carriage linefeed on Windows.
  681. OF_TextWithCRLF = OF_Text | OF_CRLF,
  682. /// The file should be opened in append mode.
  683. OF_Append = 4,
  684. /// The returned handle can be used for deleting the file. Only makes a
  685. /// difference on windows.
  686. OF_Delete = 8,
  687. /// When a child process is launched, this file should remain open in the
  688. /// child process.
  689. OF_ChildInherit = 16,
  690. /// Force files Atime to be updated on access. Only makes a difference on
  691. /// Windows.
  692. OF_UpdateAtime = 32,
  693. };
  694. /// Create a potentially unique file name but does not create it.
  695. ///
  696. /// Generates a unique path suitable for a temporary file but does not
  697. /// open or create the file. The name is based on \a Model with '%'
  698. /// replaced by a random char in [0-9a-f]. If \a MakeAbsolute is true
  699. /// then the system's temp directory is prepended first. If \a MakeAbsolute
  700. /// is false the current directory will be used instead.
  701. ///
  702. /// This function does not check if the file exists. If you want to be sure
  703. /// that the file does not yet exist, you should use use enough '%' characters
  704. /// in your model to ensure this. Each '%' gives 4-bits of entropy so you can
  705. /// use 32 of them to get 128 bits of entropy.
  706. ///
  707. /// Example: clang-%%-%%-%%-%%-%%.s => clang-a0-b1-c2-d3-e4.s
  708. ///
  709. /// @param Model Name to base unique path off of.
  710. /// @param ResultPath Set to the file's path.
  711. /// @param MakeAbsolute Whether to use the system temp directory.
  712. void createUniquePath(const Twine &Model, SmallVectorImpl<char> &ResultPath,
  713. bool MakeAbsolute);
  714. /// Create a uniquely named file.
  715. ///
  716. /// Generates a unique path suitable for a temporary file and then opens it as a
  717. /// file. The name is based on \a Model with '%' replaced by a random char in
  718. /// [0-9a-f]. If \a Model is not an absolute path, the temporary file will be
  719. /// created in the current directory.
  720. ///
  721. /// Example: clang-%%-%%-%%-%%-%%.s => clang-a0-b1-c2-d3-e4.s
  722. ///
  723. /// This is an atomic operation. Either the file is created and opened, or the
  724. /// file system is left untouched.
  725. ///
  726. /// The intended use is for files that are to be kept, possibly after
  727. /// renaming them. For example, when running 'clang -c foo.o', the file can
  728. /// be first created as foo-abc123.o and then renamed.
  729. ///
  730. /// @param Model Name to base unique path off of.
  731. /// @param ResultFD Set to the opened file's file descriptor.
  732. /// @param ResultPath Set to the opened file's absolute path.
  733. /// @param Flags Set to the opened file's flags.
  734. /// @param Mode Set to the opened file's permissions.
  735. /// @returns errc::success if Result{FD,Path} have been successfully set,
  736. /// otherwise a platform-specific error_code.
  737. std::error_code createUniqueFile(const Twine &Model, int &ResultFD,
  738. SmallVectorImpl<char> &ResultPath,
  739. OpenFlags Flags = OF_None,
  740. unsigned Mode = all_read | all_write);
  741. /// Simpler version for clients that don't want an open file. An empty
  742. /// file will still be created.
  743. std::error_code createUniqueFile(const Twine &Model,
  744. SmallVectorImpl<char> &ResultPath,
  745. unsigned Mode = all_read | all_write);
  746. /// Represents a temporary file.
  747. ///
  748. /// The temporary file must be eventually discarded or given a final name and
  749. /// kept.
  750. ///
  751. /// The destructor doesn't implicitly discard because there is no way to
  752. /// properly handle errors in a destructor.
  753. class TempFile {
  754. bool Done = false;
  755. TempFile(StringRef Name, int FD);
  756. public:
  757. /// This creates a temporary file with createUniqueFile and schedules it for
  758. /// deletion with sys::RemoveFileOnSignal.
  759. static Expected<TempFile> create(const Twine &Model,
  760. unsigned Mode = all_read | all_write,
  761. OpenFlags ExtraFlags = OF_None);
  762. TempFile(TempFile &&Other);
  763. TempFile &operator=(TempFile &&Other);
  764. // Name of the temporary file.
  765. std::string TmpName;
  766. // The open file descriptor.
  767. int FD = -1;
  768. #ifdef _WIN32
  769. // Whether we need to manually remove the file on close.
  770. bool RemoveOnClose = false;
  771. #endif
  772. // Keep this with the given name.
  773. Error keep(const Twine &Name);
  774. // Keep this with the temporary name.
  775. Error keep();
  776. // Delete the file.
  777. Error discard();
  778. // This checks that keep or delete was called.
  779. ~TempFile();
  780. };
  781. /// Create a file in the system temporary directory.
  782. ///
  783. /// The filename is of the form prefix-random_chars.suffix. Since the directory
  784. /// is not know to the caller, Prefix and Suffix cannot have path separators.
  785. /// The files are created with mode 0600.
  786. ///
  787. /// This should be used for things like a temporary .s that is removed after
  788. /// running the assembler.
  789. std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
  790. int &ResultFD,
  791. SmallVectorImpl<char> &ResultPath,
  792. OpenFlags Flags = OF_None);
  793. /// Simpler version for clients that don't want an open file. An empty
  794. /// file will still be created.
  795. std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
  796. SmallVectorImpl<char> &ResultPath,
  797. OpenFlags Flags = OF_None);
  798. std::error_code createUniqueDirectory(const Twine &Prefix,
  799. SmallVectorImpl<char> &ResultPath);
  800. /// Get a unique name, not currently exisiting in the filesystem. Subject
  801. /// to race conditions, prefer to use createUniqueFile instead.
  802. ///
  803. /// Similar to createUniqueFile, but instead of creating a file only
  804. /// checks if it exists. This function is subject to race conditions, if you
  805. /// want to use the returned name to actually create a file, use
  806. /// createUniqueFile instead.
  807. std::error_code getPotentiallyUniqueFileName(const Twine &Model,
  808. SmallVectorImpl<char> &ResultPath);
  809. /// Get a unique temporary file name, not currently exisiting in the
  810. /// filesystem. Subject to race conditions, prefer to use createTemporaryFile
  811. /// instead.
  812. ///
  813. /// Similar to createTemporaryFile, but instead of creating a file only
  814. /// checks if it exists. This function is subject to race conditions, if you
  815. /// want to use the returned name to actually create a file, use
  816. /// createTemporaryFile instead.
  817. std::error_code
  818. getPotentiallyUniqueTempFileName(const Twine &Prefix, StringRef Suffix,
  819. SmallVectorImpl<char> &ResultPath);
  820. inline OpenFlags operator|(OpenFlags A, OpenFlags B) {
  821. return OpenFlags(unsigned(A) | unsigned(B));
  822. }
  823. inline OpenFlags &operator|=(OpenFlags &A, OpenFlags B) {
  824. A = A | B;
  825. return A;
  826. }
  827. inline FileAccess operator|(FileAccess A, FileAccess B) {
  828. return FileAccess(unsigned(A) | unsigned(B));
  829. }
  830. inline FileAccess &operator|=(FileAccess &A, FileAccess B) {
  831. A = A | B;
  832. return A;
  833. }
  834. /// @brief Opens a file with the specified creation disposition, access mode,
  835. /// and flags and returns a file descriptor.
  836. ///
  837. /// The caller is responsible for closing the file descriptor once they are
  838. /// finished with it.
  839. ///
  840. /// @param Name The path of the file to open, relative or absolute.
  841. /// @param ResultFD If the file could be opened successfully, its descriptor
  842. /// is stored in this location. Otherwise, this is set to -1.
  843. /// @param Disp Value specifying the existing-file behavior.
  844. /// @param Access Value specifying whether to open the file in read, write, or
  845. /// read-write mode.
  846. /// @param Flags Additional flags.
  847. /// @param Mode The access permissions of the file, represented in octal.
  848. /// @returns errc::success if \a Name has been opened, otherwise a
  849. /// platform-specific error_code.
  850. std::error_code openFile(const Twine &Name, int &ResultFD,
  851. CreationDisposition Disp, FileAccess Access,
  852. OpenFlags Flags, unsigned Mode = 0666);
  853. /// @brief Opens a file with the specified creation disposition, access mode,
  854. /// and flags and returns a platform-specific file object.
  855. ///
  856. /// The caller is responsible for closing the file object once they are
  857. /// finished with it.
  858. ///
  859. /// @param Name The path of the file to open, relative or absolute.
  860. /// @param Disp Value specifying the existing-file behavior.
  861. /// @param Access Value specifying whether to open the file in read, write, or
  862. /// read-write mode.
  863. /// @param Flags Additional flags.
  864. /// @param Mode The access permissions of the file, represented in octal.
  865. /// @returns errc::success if \a Name has been opened, otherwise a
  866. /// platform-specific error_code.
  867. Expected<file_t> openNativeFile(const Twine &Name, CreationDisposition Disp,
  868. FileAccess Access, OpenFlags Flags,
  869. unsigned Mode = 0666);
  870. /// Converts from a Posix file descriptor number to a native file handle.
  871. /// On Windows, this retreives the underlying handle. On non-Windows, this is a
  872. /// no-op.
  873. file_t convertFDToNativeFile(int FD);
  874. #ifndef _WIN32
  875. inline file_t convertFDToNativeFile(int FD) { return FD; }
  876. #endif
  877. /// Return an open handle to standard in. On Unix, this is typically FD 0.
  878. /// Returns kInvalidFile when the stream is closed.
  879. file_t getStdinHandle();
  880. /// Return an open handle to standard out. On Unix, this is typically FD 1.
  881. /// Returns kInvalidFile when the stream is closed.
  882. file_t getStdoutHandle();
  883. /// Return an open handle to standard error. On Unix, this is typically FD 2.
  884. /// Returns kInvalidFile when the stream is closed.
  885. file_t getStderrHandle();
  886. /// Reads \p Buf.size() bytes from \p FileHandle into \p Buf. Returns the number
  887. /// of bytes actually read. On Unix, this is equivalent to `return ::read(FD,
  888. /// Buf.data(), Buf.size())`, with error reporting. Returns 0 when reaching EOF.
  889. ///
  890. /// @param FileHandle File to read from.
  891. /// @param Buf Buffer to read into.
  892. /// @returns The number of bytes read, or error.
  893. Expected<size_t> readNativeFile(file_t FileHandle, MutableArrayRef<char> Buf);
  894. /// Default chunk size for \a readNativeFileToEOF().
  895. enum : size_t { DefaultReadChunkSize = 4 * 4096 };
  896. /// Reads from \p FileHandle until EOF, appending to \p Buffer in chunks of
  897. /// size \p ChunkSize.
  898. ///
  899. /// This calls \a readNativeFile() in a loop. On Error, previous chunks that
  900. /// were read successfully are left in \p Buffer and returned.
  901. ///
  902. /// Note: For reading the final chunk at EOF, \p Buffer's capacity needs extra
  903. /// storage of \p ChunkSize.
  904. ///
  905. /// \param FileHandle File to read from.
  906. /// \param Buffer Where to put the file content.
  907. /// \param ChunkSize Size of chunks.
  908. /// \returns The error if EOF was not found.
  909. Error readNativeFileToEOF(file_t FileHandle, SmallVectorImpl<char> &Buffer,
  910. ssize_t ChunkSize = DefaultReadChunkSize);
  911. /// Reads \p Buf.size() bytes from \p FileHandle at offset \p Offset into \p
  912. /// Buf. If 'pread' is available, this will use that, otherwise it will use
  913. /// 'lseek'. Returns the number of bytes actually read. Returns 0 when reaching
  914. /// EOF.
  915. ///
  916. /// @param FileHandle File to read from.
  917. /// @param Buf Buffer to read into.
  918. /// @param Offset Offset into the file at which the read should occur.
  919. /// @returns The number of bytes read, or error.
  920. Expected<size_t> readNativeFileSlice(file_t FileHandle,
  921. MutableArrayRef<char> Buf,
  922. uint64_t Offset);
  923. /// @brief Opens the file with the given name in a write-only or read-write
  924. /// mode, returning its open file descriptor. If the file does not exist, it
  925. /// is created.
  926. ///
  927. /// The caller is responsible for closing the file descriptor once they are
  928. /// finished with it.
  929. ///
  930. /// @param Name The path of the file to open, relative or absolute.
  931. /// @param ResultFD If the file could be opened successfully, its descriptor
  932. /// is stored in this location. Otherwise, this is set to -1.
  933. /// @param Flags Additional flags used to determine whether the file should be
  934. /// opened in, for example, read-write or in write-only mode.
  935. /// @param Mode The access permissions of the file, represented in octal.
  936. /// @returns errc::success if \a Name has been opened, otherwise a
  937. /// platform-specific error_code.
  938. inline std::error_code
  939. openFileForWrite(const Twine &Name, int &ResultFD,
  940. CreationDisposition Disp = CD_CreateAlways,
  941. OpenFlags Flags = OF_None, unsigned Mode = 0666) {
  942. return openFile(Name, ResultFD, Disp, FA_Write, Flags, Mode);
  943. }
  944. /// @brief Opens the file with the given name in a write-only or read-write
  945. /// mode, returning its open file descriptor. If the file does not exist, it
  946. /// is created.
  947. ///
  948. /// The caller is responsible for closing the freeing the file once they are
  949. /// finished with it.
  950. ///
  951. /// @param Name The path of the file to open, relative or absolute.
  952. /// @param Flags Additional flags used to determine whether the file should be
  953. /// opened in, for example, read-write or in write-only mode.
  954. /// @param Mode The access permissions of the file, represented in octal.
  955. /// @returns a platform-specific file descriptor if \a Name has been opened,
  956. /// otherwise an error object.
  957. inline Expected<file_t> openNativeFileForWrite(const Twine &Name,
  958. CreationDisposition Disp,
  959. OpenFlags Flags,
  960. unsigned Mode = 0666) {
  961. return openNativeFile(Name, Disp, FA_Write, Flags, Mode);
  962. }
  963. /// @brief Opens the file with the given name in a write-only or read-write
  964. /// mode, returning its open file descriptor. If the file does not exist, it
  965. /// is created.
  966. ///
  967. /// The caller is responsible for closing the file descriptor once they are
  968. /// finished with it.
  969. ///
  970. /// @param Name The path of the file to open, relative or absolute.
  971. /// @param ResultFD If the file could be opened successfully, its descriptor
  972. /// is stored in this location. Otherwise, this is set to -1.
  973. /// @param Flags Additional flags used to determine whether the file should be
  974. /// opened in, for example, read-write or in write-only mode.
  975. /// @param Mode The access permissions of the file, represented in octal.
  976. /// @returns errc::success if \a Name has been opened, otherwise a
  977. /// platform-specific error_code.
  978. inline std::error_code openFileForReadWrite(const Twine &Name, int &ResultFD,
  979. CreationDisposition Disp,
  980. OpenFlags Flags,
  981. unsigned Mode = 0666) {
  982. return openFile(Name, ResultFD, Disp, FA_Write | FA_Read, Flags, Mode);
  983. }
  984. /// @brief Opens the file with the given name in a write-only or read-write
  985. /// mode, returning its open file descriptor. If the file does not exist, it
  986. /// is created.
  987. ///
  988. /// The caller is responsible for closing the freeing the file once they are
  989. /// finished with it.
  990. ///
  991. /// @param Name The path of the file to open, relative or absolute.
  992. /// @param Flags Additional flags used to determine whether the file should be
  993. /// opened in, for example, read-write or in write-only mode.
  994. /// @param Mode The access permissions of the file, represented in octal.
  995. /// @returns a platform-specific file descriptor if \a Name has been opened,
  996. /// otherwise an error object.
  997. inline Expected<file_t> openNativeFileForReadWrite(const Twine &Name,
  998. CreationDisposition Disp,
  999. OpenFlags Flags,
  1000. unsigned Mode = 0666) {
  1001. return openNativeFile(Name, Disp, FA_Write | FA_Read, Flags, Mode);
  1002. }
  1003. /// @brief Opens the file with the given name in a read-only mode, returning
  1004. /// its open file descriptor.
  1005. ///
  1006. /// The caller is responsible for closing the file descriptor once they are
  1007. /// finished with it.
  1008. ///
  1009. /// @param Name The path of the file to open, relative or absolute.
  1010. /// @param ResultFD If the file could be opened successfully, its descriptor
  1011. /// is stored in this location. Otherwise, this is set to -1.
  1012. /// @param RealPath If nonnull, extra work is done to determine the real path
  1013. /// of the opened file, and that path is stored in this
  1014. /// location.
  1015. /// @returns errc::success if \a Name has been opened, otherwise a
  1016. /// platform-specific error_code.
  1017. std::error_code openFileForRead(const Twine &Name, int &ResultFD,
  1018. OpenFlags Flags = OF_None,
  1019. SmallVectorImpl<char> *RealPath = nullptr);
  1020. /// @brief Opens the file with the given name in a read-only mode, returning
  1021. /// its open file descriptor.
  1022. ///
  1023. /// The caller is responsible for closing the freeing the file once they are
  1024. /// finished with it.
  1025. ///
  1026. /// @param Name The path of the file to open, relative or absolute.
  1027. /// @param RealPath If nonnull, extra work is done to determine the real path
  1028. /// of the opened file, and that path is stored in this
  1029. /// location.
  1030. /// @returns a platform-specific file descriptor if \a Name has been opened,
  1031. /// otherwise an error object.
  1032. Expected<file_t>
  1033. openNativeFileForRead(const Twine &Name, OpenFlags Flags = OF_None,
  1034. SmallVectorImpl<char> *RealPath = nullptr);
  1035. /// Try to locks the file during the specified time.
  1036. ///
  1037. /// This function implements advisory locking on entire file. If it returns
  1038. /// <em>errc::success</em>, the file is locked by the calling process. Until the
  1039. /// process unlocks the file by calling \a unlockFile, all attempts to lock the
  1040. /// same file will fail/block. The process that locked the file may assume that
  1041. /// none of other processes read or write this file, provided that all processes
  1042. /// lock the file prior to accessing its content.
  1043. ///
  1044. /// @param FD The descriptor representing the file to lock.
  1045. /// @param Timeout Time in milliseconds that the process should wait before
  1046. /// reporting lock failure. Zero value means try to get lock only
  1047. /// once.
  1048. /// @returns errc::success if lock is successfully obtained,
  1049. /// errc::no_lock_available if the file cannot be locked, or platform-specific
  1050. /// error_code otherwise.
  1051. ///
  1052. /// @note Care should be taken when using this function in a multithreaded
  1053. /// context, as it may not prevent other threads in the same process from
  1054. /// obtaining a lock on the same file, even if they are using a different file
  1055. /// descriptor.
  1056. std::error_code
  1057. tryLockFile(int FD,
  1058. std::chrono::milliseconds Timeout = std::chrono::milliseconds(0));
  1059. /// Lock the file.
  1060. ///
  1061. /// This function acts as @ref tryLockFile but it waits infinitely.
  1062. std::error_code lockFile(int FD);
  1063. /// Unlock the file.
  1064. ///
  1065. /// @param FD The descriptor representing the file to unlock.
  1066. /// @returns errc::success if lock is successfully released or platform-specific
  1067. /// error_code otherwise.
  1068. std::error_code unlockFile(int FD);
  1069. /// @brief Close the file object. This should be used instead of ::close for
  1070. /// portability. On error, the caller should assume the file is closed, as is
  1071. /// the case for Process::SafelyCloseFileDescriptor
  1072. ///
  1073. /// @param F On input, this is the file to close. On output, the file is
  1074. /// set to kInvalidFile.
  1075. ///
  1076. /// @returns An error code if closing the file failed. Typically, an error here
  1077. /// means that the filesystem may have failed to perform some buffered writes.
  1078. std::error_code closeFile(file_t &F);
  1079. #ifdef LLVM_ON_UNIX
  1080. /// @brief Change ownership of a file.
  1081. ///
  1082. /// @param Owner The owner of the file to change to.
  1083. /// @param Group The group of the file to change to.
  1084. /// @returns errc::success if successfully updated file ownership, otherwise an
  1085. /// error code is returned.
  1086. std::error_code changeFileOwnership(int FD, uint32_t Owner, uint32_t Group);
  1087. #endif
  1088. /// RAII class that facilitates file locking.
  1089. class FileLocker {
  1090. int FD; ///< Locked file handle.
  1091. FileLocker(int FD) : FD(FD) {}
  1092. friend class llvm::raw_fd_ostream;
  1093. public:
  1094. FileLocker(const FileLocker &L) = delete;
  1095. FileLocker(FileLocker &&L) : FD(L.FD) { L.FD = -1; }
  1096. ~FileLocker() {
  1097. if (FD != -1)
  1098. unlockFile(FD);
  1099. }
  1100. FileLocker &operator=(FileLocker &&L) {
  1101. FD = L.FD;
  1102. L.FD = -1;
  1103. return *this;
  1104. }
  1105. FileLocker &operator=(const FileLocker &L) = delete;
  1106. std::error_code unlock() {
  1107. if (FD != -1) {
  1108. std::error_code Result = unlockFile(FD);
  1109. FD = -1;
  1110. return Result;
  1111. }
  1112. return std::error_code();
  1113. }
  1114. };
  1115. std::error_code getUniqueID(const Twine Path, UniqueID &Result);
  1116. /// Get disk space usage information.
  1117. ///
  1118. /// Note: Users must be careful about "Time Of Check, Time Of Use" kind of bug.
  1119. /// Note: Windows reports results according to the quota allocated to the user.
  1120. ///
  1121. /// @param Path Input path.
  1122. /// @returns a space_info structure filled with the capacity, free, and
  1123. /// available space on the device \a Path is on. A platform specific error_code
  1124. /// is returned on error.
  1125. ErrorOr<space_info> disk_space(const Twine &Path);
  1126. /// This class represents a memory mapped file. It is based on
  1127. /// boost::iostreams::mapped_file.
  1128. class mapped_file_region {
  1129. public:
  1130. enum mapmode {
  1131. readonly, ///< May only access map via const_data as read only.
  1132. readwrite, ///< May access map via data and modify it. Written to path.
  1133. priv ///< May modify via data, but changes are lost on destruction.
  1134. };
  1135. private:
  1136. /// Platform-specific mapping state.
  1137. size_t Size = 0;
  1138. void *Mapping = nullptr;
  1139. #ifdef _WIN32
  1140. sys::fs::file_t FileHandle = nullptr;
  1141. #endif
  1142. mapmode Mode = readonly;
  1143. void copyFrom(const mapped_file_region &Copied) {
  1144. Size = Copied.Size;
  1145. Mapping = Copied.Mapping;
  1146. #ifdef _WIN32
  1147. FileHandle = Copied.FileHandle;
  1148. #endif
  1149. Mode = Copied.Mode;
  1150. }
  1151. void moveFromImpl(mapped_file_region &Moved) {
  1152. copyFrom(Moved);
  1153. Moved.copyFrom(mapped_file_region());
  1154. }
  1155. void unmapImpl();
  1156. void dontNeedImpl();
  1157. std::error_code init(sys::fs::file_t FD, uint64_t Offset, mapmode Mode);
  1158. public:
  1159. mapped_file_region() = default;
  1160. mapped_file_region(mapped_file_region &&Moved) { moveFromImpl(Moved); }
  1161. mapped_file_region &operator=(mapped_file_region &&Moved) {
  1162. unmap();
  1163. moveFromImpl(Moved);
  1164. return *this;
  1165. }
  1166. mapped_file_region(const mapped_file_region &) = delete;
  1167. mapped_file_region &operator=(const mapped_file_region &) = delete;
  1168. /// \param fd An open file descriptor to map. Does not take ownership of fd.
  1169. mapped_file_region(sys::fs::file_t fd, mapmode mode, size_t length, uint64_t offset,
  1170. std::error_code &ec);
  1171. ~mapped_file_region() { unmapImpl(); }
  1172. /// Check if this is a valid mapping.
  1173. explicit operator bool() const { return Mapping; }
  1174. /// Unmap.
  1175. void unmap() {
  1176. unmapImpl();
  1177. copyFrom(mapped_file_region());
  1178. }
  1179. void dontNeed() { dontNeedImpl(); }
  1180. size_t size() const;
  1181. char *data() const;
  1182. /// Get a const view of the data. Modifying this memory has undefined
  1183. /// behavior.
  1184. const char *const_data() const;
  1185. /// \returns The minimum alignment offset must be.
  1186. static int alignment();
  1187. };
  1188. /// Return the path to the main executable, given the value of argv[0] from
  1189. /// program startup and the address of main itself. In extremis, this function
  1190. /// may fail and return an empty path.
  1191. std::string getMainExecutable(const char *argv0, void *MainExecAddr);
  1192. /// @}
  1193. /// @name Iterators
  1194. /// @{
  1195. /// directory_entry - A single entry in a directory.
  1196. class directory_entry {
  1197. // FIXME: different platforms make different information available "for free"
  1198. // when traversing a directory. The design of this class wraps most of the
  1199. // information in basic_file_status, so on platforms where we can't populate
  1200. // that whole structure, callers end up paying for a stat().
  1201. // std::filesystem::directory_entry may be a better model.
  1202. std::string Path;
  1203. file_type Type = file_type::type_unknown; // Most platforms can provide this.
  1204. bool FollowSymlinks = true; // Affects the behavior of status().
  1205. basic_file_status Status; // If available.
  1206. public:
  1207. explicit directory_entry(const Twine &Path, bool FollowSymlinks = true,
  1208. file_type Type = file_type::type_unknown,
  1209. basic_file_status Status = basic_file_status())
  1210. : Path(Path.str()), Type(Type), FollowSymlinks(FollowSymlinks),
  1211. Status(Status) {}
  1212. directory_entry() = default;
  1213. void replace_filename(const Twine &Filename, file_type Type,
  1214. basic_file_status Status = basic_file_status());
  1215. const std::string &path() const { return Path; }
  1216. // Get basic information about entry file (a subset of fs::status()).
  1217. // On most platforms this is a stat() call.
  1218. // On windows the information was already retrieved from the directory.
  1219. ErrorOr<basic_file_status> status() const;
  1220. // Get the type of this file.
  1221. // On most platforms (Linux/Mac/Windows/BSD), this was already retrieved.
  1222. // On some platforms (e.g. Solaris) this is a stat() call.
  1223. file_type type() const {
  1224. if (Type != file_type::type_unknown)
  1225. return Type;
  1226. auto S = status();
  1227. return S ? S->type() : file_type::type_unknown;
  1228. }
  1229. bool operator==(const directory_entry& RHS) const { return Path == RHS.Path; }
  1230. bool operator!=(const directory_entry& RHS) const { return !(*this == RHS); }
  1231. bool operator< (const directory_entry& RHS) const;
  1232. bool operator<=(const directory_entry& RHS) const;
  1233. bool operator> (const directory_entry& RHS) const;
  1234. bool operator>=(const directory_entry& RHS) const;
  1235. };
  1236. namespace detail {
  1237. struct DirIterState;
  1238. std::error_code directory_iterator_construct(DirIterState &, StringRef, bool);
  1239. std::error_code directory_iterator_increment(DirIterState &);
  1240. std::error_code directory_iterator_destruct(DirIterState &);
  1241. /// Keeps state for the directory_iterator.
  1242. struct DirIterState {
  1243. ~DirIterState() {
  1244. directory_iterator_destruct(*this);
  1245. }
  1246. intptr_t IterationHandle = 0;
  1247. directory_entry CurrentEntry;
  1248. };
  1249. } // end namespace detail
  1250. /// directory_iterator - Iterates through the entries in path. There is no
  1251. /// operator++ because we need an error_code. If it's really needed we can make
  1252. /// it call report_fatal_error on error.
  1253. class directory_iterator {
  1254. std::shared_ptr<detail::DirIterState> State;
  1255. bool FollowSymlinks = true;
  1256. public:
  1257. explicit directory_iterator(const Twine &path, std::error_code &ec,
  1258. bool follow_symlinks = true)
  1259. : FollowSymlinks(follow_symlinks) {
  1260. State = std::make_shared<detail::DirIterState>();
  1261. SmallString<128> path_storage;
  1262. ec = detail::directory_iterator_construct(
  1263. *State, path.toStringRef(path_storage), FollowSymlinks);
  1264. }
  1265. explicit directory_iterator(const directory_entry &de, std::error_code &ec,
  1266. bool follow_symlinks = true)
  1267. : FollowSymlinks(follow_symlinks) {
  1268. State = std::make_shared<detail::DirIterState>();
  1269. ec = detail::directory_iterator_construct(
  1270. *State, de.path(), FollowSymlinks);
  1271. }
  1272. /// Construct end iterator.
  1273. directory_iterator() = default;
  1274. // No operator++ because we need error_code.
  1275. directory_iterator &increment(std::error_code &ec) {
  1276. ec = directory_iterator_increment(*State);
  1277. return *this;
  1278. }
  1279. const directory_entry &operator*() const { return State->CurrentEntry; }
  1280. const directory_entry *operator->() const { return &State->CurrentEntry; }
  1281. bool operator==(const directory_iterator &RHS) const {
  1282. if (State == RHS.State)
  1283. return true;
  1284. if (!RHS.State)
  1285. return State->CurrentEntry == directory_entry();
  1286. if (!State)
  1287. return RHS.State->CurrentEntry == directory_entry();
  1288. return State->CurrentEntry == RHS.State->CurrentEntry;
  1289. }
  1290. bool operator!=(const directory_iterator &RHS) const {
  1291. return !(*this == RHS);
  1292. }
  1293. };
  1294. namespace detail {
  1295. /// Keeps state for the recursive_directory_iterator.
  1296. struct RecDirIterState {
  1297. std::stack<directory_iterator, std::vector<directory_iterator>> Stack;
  1298. uint16_t Level = 0;
  1299. bool HasNoPushRequest = false;
  1300. };
  1301. } // end namespace detail
  1302. /// recursive_directory_iterator - Same as directory_iterator except for it
  1303. /// recurses down into child directories.
  1304. class recursive_directory_iterator {
  1305. std::shared_ptr<detail::RecDirIterState> State;
  1306. bool Follow;
  1307. public:
  1308. recursive_directory_iterator() = default;
  1309. explicit recursive_directory_iterator(const Twine &path, std::error_code &ec,
  1310. bool follow_symlinks = true)
  1311. : State(std::make_shared<detail::RecDirIterState>()),
  1312. Follow(follow_symlinks) {
  1313. State->Stack.push(directory_iterator(path, ec, Follow));
  1314. if (State->Stack.top() == directory_iterator())
  1315. State.reset();
  1316. }
  1317. // No operator++ because we need error_code.
  1318. recursive_directory_iterator &increment(std::error_code &ec) {
  1319. const directory_iterator end_itr = {};
  1320. if (State->HasNoPushRequest)
  1321. State->HasNoPushRequest = false;
  1322. else {
  1323. file_type type = State->Stack.top()->type();
  1324. if (type == file_type::symlink_file && Follow) {
  1325. // Resolve the symlink: is it a directory to recurse into?
  1326. ErrorOr<basic_file_status> status = State->Stack.top()->status();
  1327. if (status)
  1328. type = status->type();
  1329. // Otherwise broken symlink, and we'll continue.
  1330. }
  1331. if (type == file_type::directory_file) {
  1332. State->Stack.push(directory_iterator(*State->Stack.top(), ec, Follow));
  1333. if (State->Stack.top() != end_itr) {
  1334. ++State->Level;
  1335. return *this;
  1336. }
  1337. State->Stack.pop();
  1338. }
  1339. }
  1340. while (!State->Stack.empty()
  1341. && State->Stack.top().increment(ec) == end_itr) {
  1342. State->Stack.pop();
  1343. --State->Level;
  1344. }
  1345. // Check if we are done. If so, create an end iterator.
  1346. if (State->Stack.empty())
  1347. State.reset();
  1348. return *this;
  1349. }
  1350. const directory_entry &operator*() const { return *State->Stack.top(); }
  1351. const directory_entry *operator->() const { return &*State->Stack.top(); }
  1352. // observers
  1353. /// Gets the current level. Starting path is at level 0.
  1354. int level() const { return State->Level; }
  1355. /// Returns true if no_push has been called for this directory_entry.
  1356. bool no_push_request() const { return State->HasNoPushRequest; }
  1357. // modifiers
  1358. /// Goes up one level if Level > 0.
  1359. void pop() {
  1360. assert(State && "Cannot pop an end iterator!");
  1361. assert(State->Level > 0 && "Cannot pop an iterator with level < 1");
  1362. const directory_iterator end_itr = {};
  1363. std::error_code ec;
  1364. do {
  1365. if (ec)
  1366. report_fatal_error("Error incrementing directory iterator.");
  1367. State->Stack.pop();
  1368. --State->Level;
  1369. } while (!State->Stack.empty()
  1370. && State->Stack.top().increment(ec) == end_itr);
  1371. // Check if we are done. If so, create an end iterator.
  1372. if (State->Stack.empty())
  1373. State.reset();
  1374. }
  1375. /// Does not go down into the current directory_entry.
  1376. void no_push() { State->HasNoPushRequest = true; }
  1377. bool operator==(const recursive_directory_iterator &RHS) const {
  1378. return State == RHS.State;
  1379. }
  1380. bool operator!=(const recursive_directory_iterator &RHS) const {
  1381. return !(*this == RHS);
  1382. }
  1383. };
  1384. /// @}
  1385. } // end namespace fs
  1386. } // end namespace sys
  1387. } // end namespace llvm
  1388. #endif // LLVM_SUPPORT_FILESYSTEM_H
  1389. #ifdef __GNUC__
  1390. #pragma GCC diagnostic pop
  1391. #endif