FileSystem.h 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  1. //===- llvm/Support/FileSystem.h - File System OS Concept -------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file declares the llvm::sys::fs namespace. It is designed after
  11. // TR2/boost filesystem (v3), but modified to remove exception handling and the
  12. // path class.
  13. //
  14. // All functions return an error_code and their actual work via the last out
  15. // argument. The out argument is defined if and only if errc::success is
  16. // returned. A function may return any error code in the generic or system
  17. // category. However, they shall be equivalent to any error conditions listed
  18. // in each functions respective documentation if the condition applies. [ note:
  19. // this does not guarantee that error_code will be in the set of explicitly
  20. // listed codes, but it does guarantee that if any of the explicitly listed
  21. // errors occur, the correct error_code will be used ]. All functions may
  22. // return errc::not_enough_memory if there is not enough memory to complete the
  23. // operation.
  24. //
  25. //===----------------------------------------------------------------------===//
  26. #ifndef LLVM_SUPPORT_FILESYSTEM_H
  27. #define LLVM_SUPPORT_FILESYSTEM_H
  28. #include "dxc/Support/WinAdapter.h" // HLSL Change
  29. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  30. #include "llvm/ADT/SmallString.h"
  31. #include "llvm/ADT/Twine.h"
  32. #include "llvm/Support/DataTypes.h"
  33. #include "llvm/Support/ErrorHandling.h"
  34. #include "llvm/Support/TimeValue.h"
  35. #include <ctime>
  36. #include <iterator>
  37. #include <stack>
  38. #include <string>
  39. #include <system_error>
  40. #include <tuple>
  41. #include <vector>
  42. #ifdef HAVE_SYS_STAT_H
  43. #include <sys/stat.h>
  44. #endif
  45. namespace llvm {
  46. namespace sys {
  47. namespace fs {
  48. // HLSL Change Start
  49. class MSFileSystem;
  50. typedef _Inout_ MSFileSystem* MSFileSystemRef;
  51. std::error_code GetFileSystemTlsStatus() throw();
  52. std::error_code SetupPerThreadFileSystem() throw();
  53. void CleanupPerThreadFileSystem() throw();
  54. struct AutoCleanupPerThreadFileSystem { ~AutoCleanupPerThreadFileSystem() { CleanupPerThreadFileSystem(); } };
  55. /// <summary>Gets a reference to the file system installed for the current thread (possibly NULL).</summary>
  56. /// <remarks>In practice, consumers of the library should always install a file system.</remarks>
  57. MSFileSystemRef GetCurrentThreadFileSystem() throw();
  58. /// <summary>
  59. /// Sets the specified file system reference for the current thread.
  60. /// </summary>
  61. std::error_code SetCurrentThreadFileSystem(MSFileSystemRef value) throw();
  62. int msf_read(int fd, void* buffer, unsigned int count) throw();
  63. int msf_write(int fd, const void* buffer, unsigned int count) throw();
  64. int msf_close(int fd) throw();
  65. int msf_setmode(int fd, int mode) throw();
  66. long msf_lseek(int fd, long offset, int origin);
  67. class AutoPerThreadSystem
  68. {
  69. private:
  70. ::llvm::sys::fs::MSFileSystem* m_pOrigValue;
  71. std::error_code ec;
  72. public:
  73. AutoPerThreadSystem(_In_ ::llvm::sys::fs::MSFileSystem *value)
  74. : m_pOrigValue(::llvm::sys::fs::GetCurrentThreadFileSystem()) {
  75. SetCurrentThreadFileSystem(nullptr);
  76. ec = ::llvm::sys::fs::SetCurrentThreadFileSystem(value);
  77. }
  78. ~AutoPerThreadSystem()
  79. {
  80. if (m_pOrigValue) {
  81. ::llvm::sys::fs::SetCurrentThreadFileSystem(nullptr);
  82. ::llvm::sys::fs::SetCurrentThreadFileSystem(m_pOrigValue);
  83. } else if (!ec) {
  84. ::llvm::sys::fs::SetCurrentThreadFileSystem(nullptr);
  85. }
  86. }
  87. const std::error_code& error_code() const { return ec; }
  88. };
  89. // HLSL Change Ends
  90. /// An enumeration for the file system's view of the type.
  91. enum class file_type {
  92. status_error,
  93. file_not_found,
  94. regular_file,
  95. directory_file,
  96. symlink_file,
  97. block_file,
  98. character_file,
  99. fifo_file,
  100. socket_file,
  101. type_unknown
  102. };
  103. /// space_info - Self explanatory.
  104. struct space_info {
  105. uint64_t capacity;
  106. uint64_t free;
  107. uint64_t available;
  108. };
  109. enum perms {
  110. no_perms = 0,
  111. owner_read = 0400,
  112. owner_write = 0200,
  113. owner_exe = 0100,
  114. owner_all = owner_read | owner_write | owner_exe,
  115. group_read = 040,
  116. group_write = 020,
  117. group_exe = 010,
  118. group_all = group_read | group_write | group_exe,
  119. others_read = 04,
  120. others_write = 02,
  121. others_exe = 01,
  122. others_all = others_read | others_write | others_exe,
  123. all_read = owner_read | group_read | others_read,
  124. all_write = owner_write | group_write | others_write,
  125. all_exe = owner_exe | group_exe | others_exe,
  126. all_all = owner_all | group_all | others_all,
  127. set_uid_on_exe = 04000,
  128. set_gid_on_exe = 02000,
  129. sticky_bit = 01000,
  130. perms_not_known = 0xFFFF
  131. };
  132. // Helper functions so that you can use & and | to manipulate perms bits:
  133. inline perms operator|(perms l , perms r) {
  134. return static_cast<perms>(
  135. static_cast<unsigned short>(l) | static_cast<unsigned short>(r));
  136. }
  137. inline perms operator&(perms l , perms r) {
  138. return static_cast<perms>(
  139. static_cast<unsigned short>(l) & static_cast<unsigned short>(r));
  140. }
  141. inline perms &operator|=(perms &l, perms r) {
  142. l = l | r;
  143. return l;
  144. }
  145. inline perms &operator&=(perms &l, perms r) {
  146. l = l & r;
  147. return l;
  148. }
  149. inline perms operator~(perms x) {
  150. return static_cast<perms>(~static_cast<unsigned short>(x));
  151. }
  152. class UniqueID {
  153. uint64_t Device;
  154. uint64_t File;
  155. public:
  156. UniqueID() = default;
  157. UniqueID(uint64_t Device, uint64_t File) : Device(Device), File(File) {}
  158. bool operator==(const UniqueID &Other) const {
  159. return Device == Other.Device && File == Other.File;
  160. }
  161. bool operator!=(const UniqueID &Other) const { return !(*this == Other); }
  162. bool operator<(const UniqueID &Other) const {
  163. return std::tie(Device, File) < std::tie(Other.Device, Other.File);
  164. }
  165. uint64_t getDevice() const { return Device; }
  166. uint64_t getFile() const { return File; }
  167. };
  168. /// file_status - Represents the result of a call to stat and friends. It has
  169. /// a platform-specific member to store the result.
  170. class file_status
  171. {
  172. #if defined(LLVM_ON_UNIX)
  173. dev_t fs_st_dev;
  174. ino_t fs_st_ino;
  175. time_t fs_st_mtime;
  176. uid_t fs_st_uid;
  177. gid_t fs_st_gid;
  178. off_t fs_st_size;
  179. #elif defined (LLVM_ON_WIN32)
  180. uint32_t LastWriteTimeHigh;
  181. uint32_t LastWriteTimeLow;
  182. uint32_t VolumeSerialNumber;
  183. uint32_t FileSizeHigh;
  184. uint32_t FileSizeLow;
  185. uint32_t FileIndexHigh;
  186. uint32_t FileIndexLow;
  187. #endif
  188. friend bool equivalent(file_status A, file_status B);
  189. file_type Type;
  190. perms Perms;
  191. public:
  192. #if defined(LLVM_ON_UNIX)
  193. file_status() : fs_st_dev(0), fs_st_ino(0), fs_st_mtime(0),
  194. fs_st_uid(0), fs_st_gid(0), fs_st_size(0),
  195. Type(file_type::status_error), Perms(perms_not_known) {}
  196. file_status(file_type Type) : fs_st_dev(0), fs_st_ino(0), fs_st_mtime(0),
  197. fs_st_uid(0), fs_st_gid(0), fs_st_size(0), Type(Type),
  198. Perms(perms_not_known) {}
  199. file_status(file_type Type, perms Perms, dev_t Dev, ino_t Ino, time_t MTime,
  200. uid_t UID, gid_t GID, off_t Size)
  201. : fs_st_dev(Dev), fs_st_ino(Ino), fs_st_mtime(MTime), fs_st_uid(UID),
  202. fs_st_gid(GID), fs_st_size(Size), Type(Type), Perms(Perms) {}
  203. #elif defined(LLVM_ON_WIN32)
  204. file_status() : LastWriteTimeHigh(0), LastWriteTimeLow(0),
  205. VolumeSerialNumber(0), FileSizeHigh(0), FileSizeLow(0),
  206. FileIndexHigh(0), FileIndexLow(0), Type(file_type::status_error),
  207. Perms(perms_not_known) {}
  208. file_status(file_type Type) : LastWriteTimeHigh(0), LastWriteTimeLow(0),
  209. VolumeSerialNumber(0), FileSizeHigh(0), FileSizeLow(0),
  210. FileIndexHigh(0), FileIndexLow(0), Type(Type),
  211. Perms(perms_not_known) {}
  212. file_status(file_type Type, uint32_t LastWriteTimeHigh,
  213. uint32_t LastWriteTimeLow, uint32_t VolumeSerialNumber,
  214. uint32_t FileSizeHigh, uint32_t FileSizeLow,
  215. uint32_t FileIndexHigh, uint32_t FileIndexLow)
  216. : LastWriteTimeHigh(LastWriteTimeHigh),
  217. LastWriteTimeLow(LastWriteTimeLow),
  218. VolumeSerialNumber(VolumeSerialNumber), FileSizeHigh(FileSizeHigh),
  219. FileSizeLow(FileSizeLow), FileIndexHigh(FileIndexHigh),
  220. FileIndexLow(FileIndexLow), Type(Type), Perms(perms_not_known) {}
  221. #endif
  222. // getters
  223. file_type type() const { return Type; }
  224. perms permissions() const { return Perms; }
  225. TimeValue getLastModificationTime() const;
  226. UniqueID getUniqueID() const;
  227. #if defined(LLVM_ON_UNIX)
  228. uint32_t getUser() const { return fs_st_uid; }
  229. uint32_t getGroup() const { return fs_st_gid; }
  230. uint64_t getSize() const { return fs_st_size; }
  231. #elif defined (LLVM_ON_WIN32)
  232. uint32_t getUser() const {
  233. return 9999; // Not applicable to Windows, so...
  234. }
  235. uint32_t getGroup() const {
  236. return 9999; // Not applicable to Windows, so...
  237. }
  238. uint64_t getSize() const {
  239. return (uint64_t(FileSizeHigh) << 32) + FileSizeLow;
  240. }
  241. #endif
  242. // setters
  243. void type(file_type v) { Type = v; }
  244. void permissions(perms p) { Perms = p; }
  245. };
  246. /// file_magic - An "enum class" enumeration of file types based on magic (the first
  247. /// N bytes of the file).
  248. struct file_magic {
  249. enum Impl {
  250. unknown = 0, ///< Unrecognized file
  251. bitcode, ///< Bitcode file
  252. archive, ///< ar style archive file
  253. elf, ///< ELF Unknown type
  254. elf_relocatable, ///< ELF Relocatable object file
  255. elf_executable, ///< ELF Executable image
  256. elf_shared_object, ///< ELF dynamically linked shared lib
  257. elf_core, ///< ELF core image
  258. macho_object, ///< Mach-O Object file
  259. macho_executable, ///< Mach-O Executable
  260. macho_fixed_virtual_memory_shared_lib, ///< Mach-O Shared Lib, FVM
  261. macho_core, ///< Mach-O Core File
  262. macho_preload_executable, ///< Mach-O Preloaded Executable
  263. macho_dynamically_linked_shared_lib, ///< Mach-O dynlinked shared lib
  264. macho_dynamic_linker, ///< The Mach-O dynamic linker
  265. macho_bundle, ///< Mach-O Bundle file
  266. macho_dynamically_linked_shared_lib_stub, ///< Mach-O Shared lib stub
  267. macho_dsym_companion, ///< Mach-O dSYM companion file
  268. macho_kext_bundle, ///< Mach-O kext bundle file
  269. macho_universal_binary, ///< Mach-O universal binary
  270. coff_object, ///< COFF object file
  271. coff_import_library, ///< COFF import library
  272. pecoff_executable, ///< PECOFF executable file
  273. windows_resource ///< Windows compiled resource file (.rc)
  274. };
  275. bool is_object() const {
  276. return V == unknown ? false : true;
  277. }
  278. file_magic() : V(unknown) {}
  279. file_magic(Impl V) : V(V) {}
  280. operator Impl() const { return V; }
  281. private:
  282. Impl V;
  283. };
  284. /// @}
  285. /// @name Physical Operators
  286. /// @{
  287. /// @brief Make \a path an absolute path.
  288. ///
  289. /// Makes \a path absolute using the current directory if it is not already. An
  290. /// empty \a path will result in the current directory.
  291. ///
  292. /// /absolute/path => /absolute/path
  293. /// relative/../path => <current-directory>/relative/../path
  294. ///
  295. /// @param path A path that is modified to be an absolute path.
  296. /// @returns errc::success if \a path has been made absolute, otherwise a
  297. /// platform-specific error_code.
  298. std::error_code make_absolute(SmallVectorImpl<char> &path);
  299. /// @brief Create all the non-existent directories in path.
  300. ///
  301. /// @param path Directories to create.
  302. /// @returns errc::success if is_directory(path), otherwise a platform
  303. /// specific error_code. If IgnoreExisting is false, also returns
  304. /// error if the directory already existed.
  305. std::error_code create_directories(const Twine &path,
  306. bool IgnoreExisting = true);
  307. /// @brief Create the directory in path.
  308. ///
  309. /// @param path Directory to create.
  310. /// @returns errc::success if is_directory(path), otherwise a platform
  311. /// specific error_code. If IgnoreExisting is false, also returns
  312. /// error if the directory already existed.
  313. std::error_code create_directory(const Twine &path, bool IgnoreExisting = true);
  314. /// @brief Create a link from \a from to \a to.
  315. ///
  316. /// The link may be a soft or a hard link, depending on the platform. The caller
  317. /// may not assume which one. Currently on windows it creates a hard link since
  318. /// soft links require extra privileges. On unix, it creates a soft link since
  319. /// hard links don't work on SMB file systems.
  320. ///
  321. /// @param to The path to hard link to.
  322. /// @param from The path to hard link from. This is created.
  323. /// @returns errc::success if the link was created, otherwise a platform
  324. /// specific error_code.
  325. std::error_code create_link(const Twine &to, const Twine &from);
  326. /// @brief Get the current path.
  327. ///
  328. /// @param result Holds the current path on return.
  329. /// @returns errc::success if the current path has been stored in result,
  330. /// otherwise a platform-specific error_code.
  331. std::error_code current_path(SmallVectorImpl<char> &result);
  332. /// @brief Remove path. Equivalent to POSIX remove().
  333. ///
  334. /// @param path Input path.
  335. /// @returns errc::success if path has been removed or didn't exist, otherwise a
  336. /// platform-specific error code. If IgnoreNonExisting is false, also
  337. /// returns error if the file didn't exist.
  338. std::error_code remove(const Twine &path, bool IgnoreNonExisting = true);
  339. /// @brief Rename \a from to \a to. Files are renamed as if by POSIX rename().
  340. ///
  341. /// @param from The path to rename from.
  342. /// @param to The path to rename to. This is created.
  343. std::error_code rename(const Twine &from, const Twine &to);
  344. /// @brief Copy the contents of \a From to \a To.
  345. ///
  346. /// @param From The path to copy from.
  347. /// @param To The path to copy to. This is created.
  348. std::error_code copy_file(const Twine &From, const Twine &To);
  349. /// @brief Resize path to size. File is resized as if by POSIX truncate().
  350. ///
  351. /// @param FD Input file descriptor.
  352. /// @param Size Size to resize to.
  353. /// @returns errc::success if \a path has been resized to \a size, otherwise a
  354. /// platform-specific error_code.
  355. std::error_code resize_file(int FD, uint64_t Size);
  356. /// @}
  357. /// @name Physical Observers
  358. /// @{
  359. /// @brief Does file exist?
  360. ///
  361. /// @param status A file_status previously returned from stat.
  362. /// @returns True if the file represented by status exists, false if it does
  363. /// not.
  364. bool exists(file_status status);
  365. enum class AccessMode { Exist, Write, Execute };
  366. /// @brief Can the file be accessed?
  367. ///
  368. /// @param Path Input path.
  369. /// @returns errc::success if the path can be accessed, otherwise a
  370. /// platform-specific error_code.
  371. std::error_code access(const Twine &Path, AccessMode Mode);
  372. /// @brief Does file exist?
  373. ///
  374. /// @param Path Input path.
  375. /// @returns True if it exists, false otherwise.
  376. inline bool exists(const Twine &Path) {
  377. return !access(Path, AccessMode::Exist);
  378. }
  379. /// @brief Can we execute this file?
  380. ///
  381. /// @param Path Input path.
  382. /// @returns True if we can execute it, false otherwise.
  383. inline bool can_execute(const Twine &Path) {
  384. return !access(Path, AccessMode::Execute);
  385. }
  386. /// @brief Can we write this file?
  387. ///
  388. /// @param Path Input path.
  389. /// @returns True if we can write to it, false otherwise.
  390. inline bool can_write(const Twine &Path) {
  391. return !access(Path, AccessMode::Write);
  392. }
  393. /// @brief Do file_status's represent the same thing?
  394. ///
  395. /// @param A Input file_status.
  396. /// @param B Input file_status.
  397. ///
  398. /// assert(status_known(A) || status_known(B));
  399. ///
  400. /// @returns True if A and B both represent the same file system entity, false
  401. /// otherwise.
  402. bool equivalent(file_status A, file_status B);
  403. /// @brief Do paths represent the same thing?
  404. ///
  405. /// assert(status_known(A) || status_known(B));
  406. ///
  407. /// @param A Input path A.
  408. /// @param B Input path B.
  409. /// @param result Set to true if stat(A) and stat(B) have the same device and
  410. /// inode (or equivalent).
  411. /// @returns errc::success if result has been successfully set, otherwise a
  412. /// platform-specific error_code.
  413. std::error_code equivalent(const Twine &A, const Twine &B, bool &result);
  414. /// @brief Simpler version of equivalent for clients that don't need to
  415. /// differentiate between an error and false.
  416. inline bool equivalent(const Twine &A, const Twine &B) {
  417. bool result;
  418. return !equivalent(A, B, result) && result;
  419. }
  420. /// @brief Does status represent a directory?
  421. ///
  422. /// @param status A file_status previously returned from status.
  423. /// @returns status.type() == file_type::directory_file.
  424. bool is_directory(file_status status);
  425. /// @brief Is path a directory?
  426. ///
  427. /// @param path Input path.
  428. /// @param result Set to true if \a path is a directory, false if it is not.
  429. /// Undefined otherwise.
  430. /// @returns errc::success if result has been successfully set, otherwise a
  431. /// platform-specific error_code.
  432. std::error_code is_directory(const Twine &path, bool &result);
  433. /// @brief Simpler version of is_directory for clients that don't need to
  434. /// differentiate between an error and false.
  435. inline bool is_directory(const Twine &Path) {
  436. bool Result;
  437. return !is_directory(Path, Result) && Result;
  438. }
  439. /// @brief Does status represent a regular file?
  440. ///
  441. /// @param status A file_status previously returned from status.
  442. /// @returns status_known(status) && status.type() == file_type::regular_file.
  443. bool is_regular_file(file_status status);
  444. /// @brief Is path a regular file?
  445. ///
  446. /// @param path Input path.
  447. /// @param result Set to true if \a path is a regular file, false if it is not.
  448. /// Undefined otherwise.
  449. /// @returns errc::success if result has been successfully set, otherwise a
  450. /// platform-specific error_code.
  451. std::error_code is_regular_file(const Twine &path, bool &result);
  452. /// @brief Simpler version of is_regular_file for clients that don't need to
  453. /// differentiate between an error and false.
  454. inline bool is_regular_file(const Twine &Path) {
  455. bool Result;
  456. if (is_regular_file(Path, Result))
  457. return false;
  458. return Result;
  459. }
  460. /// @brief Does this status represent something that exists but is not a
  461. /// directory, regular file, or symlink?
  462. ///
  463. /// @param status A file_status previously returned from status.
  464. /// @returns exists(s) && !is_regular_file(s) && !is_directory(s)
  465. bool is_other(file_status status);
  466. /// @brief Is path something that exists but is not a directory,
  467. /// regular file, or symlink?
  468. ///
  469. /// @param path Input path.
  470. /// @param result Set to true if \a path exists, but is not a directory, regular
  471. /// file, or a symlink, false if it does not. Undefined otherwise.
  472. /// @returns errc::success if result has been successfully set, otherwise a
  473. /// platform-specific error_code.
  474. std::error_code is_other(const Twine &path, bool &result);
  475. /// @brief Get file status as if by POSIX stat().
  476. ///
  477. /// @param path Input path.
  478. /// @param result Set to the file status.
  479. /// @returns errc::success if result has been successfully set, otherwise a
  480. /// platform-specific error_code.
  481. std::error_code status(const Twine &path, file_status &result);
  482. /// @brief A version for when a file descriptor is already available.
  483. std::error_code status(int FD, file_status &Result);
  484. /// @brief Get file size.
  485. ///
  486. /// @param Path Input path.
  487. /// @param Result Set to the size of the file in \a Path.
  488. /// @returns errc::success if result has been successfully set, otherwise a
  489. /// platform-specific error_code.
  490. inline std::error_code file_size(const Twine &Path, uint64_t &Result) {
  491. file_status Status;
  492. std::error_code EC = status(Path, Status);
  493. if (EC)
  494. return EC;
  495. Result = Status.getSize();
  496. return std::error_code();
  497. }
  498. /// @brief Set the file modification and access time.
  499. ///
  500. /// @returns errc::success if the file times were successfully set, otherwise a
  501. /// platform-specific error_code or errc::function_not_supported on
  502. /// platforms where the functionality isn't available.
  503. std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time);
  504. /// @brief Is status available?
  505. ///
  506. /// @param s Input file status.
  507. /// @returns True if status() != status_error.
  508. bool status_known(file_status s);
  509. /// @brief Is status available?
  510. ///
  511. /// @param path Input path.
  512. /// @param result Set to true if status() != status_error.
  513. /// @returns errc::success if result has been successfully set, otherwise a
  514. /// platform-specific error_code.
  515. std::error_code status_known(const Twine &path, bool &result);
  516. /// @brief Create a uniquely named file.
  517. ///
  518. /// Generates a unique path suitable for a temporary file and then opens it as a
  519. /// file. The name is based on \a model with '%' replaced by a random char in
  520. /// [0-9a-f]. If \a model is not an absolute path, a suitable temporary
  521. /// directory will be prepended.
  522. ///
  523. /// Example: clang-%%-%%-%%-%%-%%.s => clang-a0-b1-c2-d3-e4.s
  524. ///
  525. /// This is an atomic operation. Either the file is created and opened, or the
  526. /// file system is left untouched.
  527. ///
  528. /// The intendend use is for files that are to be kept, possibly after
  529. /// renaming them. For example, when running 'clang -c foo.o', the file can
  530. /// be first created as foo-abc123.o and then renamed.
  531. ///
  532. /// @param Model Name to base unique path off of.
  533. /// @param ResultFD Set to the opened file's file descriptor.
  534. /// @param ResultPath Set to the opened file's absolute path.
  535. /// @returns errc::success if Result{FD,Path} have been successfully set,
  536. /// otherwise a platform-specific error_code.
  537. std::error_code createUniqueFile(const Twine &Model, int &ResultFD,
  538. SmallVectorImpl<char> &ResultPath,
  539. unsigned Mode = all_read | all_write);
  540. /// @brief Simpler version for clients that don't want an open file.
  541. std::error_code createUniqueFile(const Twine &Model,
  542. SmallVectorImpl<char> &ResultPath);
  543. /// @brief Create a file in the system temporary directory.
  544. ///
  545. /// The filename is of the form prefix-random_chars.suffix. Since the directory
  546. /// is not know to the caller, Prefix and Suffix cannot have path separators.
  547. /// The files are created with mode 0600.
  548. ///
  549. /// This should be used for things like a temporary .s that is removed after
  550. /// running the assembler.
  551. std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
  552. int &ResultFD,
  553. SmallVectorImpl<char> &ResultPath);
  554. /// @brief Simpler version for clients that don't want an open file.
  555. std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
  556. SmallVectorImpl<char> &ResultPath);
  557. std::error_code createUniqueDirectory(const Twine &Prefix,
  558. SmallVectorImpl<char> &ResultPath);
  559. enum OpenFlags : unsigned {
  560. F_None = 0,
  561. /// F_Excl - When opening a file, this flag makes raw_fd_ostream
  562. /// report an error if the file already exists.
  563. F_Excl = 1,
  564. /// F_Append - When opening a file, if it already exists append to the
  565. /// existing file instead of returning an error. This may not be specified
  566. /// with F_Excl.
  567. F_Append = 2,
  568. /// The file should be opened in text mode on platforms that make this
  569. /// distinction.
  570. F_Text = 4,
  571. /// Open the file for read and write.
  572. F_RW = 8
  573. };
  574. inline OpenFlags operator|(OpenFlags A, OpenFlags B) {
  575. return OpenFlags(unsigned(A) | unsigned(B));
  576. }
  577. inline OpenFlags &operator|=(OpenFlags &A, OpenFlags B) {
  578. A = A | B;
  579. return A;
  580. }
  581. std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
  582. OpenFlags Flags, unsigned Mode = 0666);
  583. std::error_code openFileForRead(const Twine &Name, int &ResultFD);
  584. /// @brief Identify the type of a binary file based on how magical it is.
  585. file_magic identify_magic(StringRef magic);
  586. /// @brief Get and identify \a path's type based on its content.
  587. ///
  588. /// @param path Input path.
  589. /// @param result Set to the type of file, or file_magic::unknown.
  590. /// @returns errc::success if result has been successfully set, otherwise a
  591. /// platform-specific error_code.
  592. std::error_code identify_magic(const Twine &path, file_magic &result);
  593. std::error_code getUniqueID(const Twine Path, UniqueID &Result);
  594. /// This class represents a memory mapped file. It is based on
  595. /// boost::iostreams::mapped_file.
  596. class mapped_file_region {
  597. mapped_file_region() = delete;
  598. mapped_file_region(mapped_file_region&) = delete;
  599. mapped_file_region &operator =(mapped_file_region&) = delete;
  600. public:
  601. enum mapmode {
  602. readonly, ///< May only access map via const_data as read only.
  603. readwrite, ///< May access map via data and modify it. Written to path.
  604. priv ///< May modify via data, but changes are lost on destruction.
  605. };
  606. private:
  607. /// Platform-specific mapping state.
  608. uint64_t Size;
  609. void *Mapping;
  610. std::error_code init(int FD, uint64_t Offset, mapmode Mode);
  611. public:
  612. /// \param fd An open file descriptor to map. mapped_file_region takes
  613. /// ownership if closefd is true. It must have been opended in the correct
  614. /// mode.
  615. mapped_file_region(int fd, mapmode mode, uint64_t length, uint64_t offset,
  616. std::error_code &ec);
  617. ~mapped_file_region();
  618. uint64_t size() const;
  619. char *data() const;
  620. /// Get a const view of the data. Modifying this memory has undefined
  621. /// behavior.
  622. const char *const_data() const;
  623. /// \returns The minimum alignment offset must be.
  624. static int alignment();
  625. };
  626. /// Return the path to the main executable, given the value of argv[0] from
  627. /// program startup and the address of main itself. In extremis, this function
  628. /// may fail and return an empty path.
  629. std::string getMainExecutable(const char *argv0, void *MainExecAddr);
  630. /// @}
  631. /// @name Iterators
  632. /// @{
  633. /// directory_entry - A single entry in a directory. Caches the status either
  634. /// from the result of the iteration syscall, or the first time status is
  635. /// called.
  636. class directory_entry {
  637. std::string Path;
  638. mutable file_status Status;
  639. public:
  640. explicit directory_entry(const Twine &path, file_status st = file_status())
  641. : Path(path.str())
  642. , Status(st) {}
  643. directory_entry() {}
  644. void assign(const Twine &path, file_status st = file_status()) {
  645. Path = path.str();
  646. Status = st;
  647. }
  648. void replace_filename(const Twine &filename, file_status st = file_status());
  649. const std::string &path() const { return Path; }
  650. std::error_code status(file_status &result) const;
  651. bool operator==(const directory_entry& rhs) const { return Path == rhs.Path; }
  652. bool operator!=(const directory_entry& rhs) const { return !(*this == rhs); }
  653. bool operator< (const directory_entry& rhs) const;
  654. bool operator<=(const directory_entry& rhs) const;
  655. bool operator> (const directory_entry& rhs) const;
  656. bool operator>=(const directory_entry& rhs) const;
  657. };
  658. namespace detail {
  659. struct DirIterState;
  660. std::error_code directory_iterator_construct(DirIterState &, StringRef);
  661. std::error_code directory_iterator_increment(DirIterState &);
  662. std::error_code directory_iterator_destruct(DirIterState &);
  663. /// DirIterState - Keeps state for the directory_iterator. It is reference
  664. /// counted in order to preserve InputIterator semantics on copy.
  665. struct DirIterState : public RefCountedBase<DirIterState> {
  666. DirIterState()
  667. : IterationHandle(0) {}
  668. ~DirIterState() {
  669. directory_iterator_destruct(*this);
  670. }
  671. intptr_t IterationHandle;
  672. directory_entry CurrentEntry;
  673. };
  674. }
  675. /// directory_iterator - Iterates through the entries in path. There is no
  676. /// operator++ because we need an error_code. If it's really needed we can make
  677. /// it call report_fatal_error on error.
  678. class directory_iterator {
  679. IntrusiveRefCntPtr<detail::DirIterState> State;
  680. public:
  681. explicit directory_iterator(const Twine &path, std::error_code &ec) {
  682. State = new detail::DirIterState;
  683. SmallString<128> path_storage;
  684. ec = detail::directory_iterator_construct(*State,
  685. path.toStringRef(path_storage));
  686. }
  687. explicit directory_iterator(const directory_entry &de, std::error_code &ec) {
  688. State = new detail::DirIterState;
  689. ec = detail::directory_iterator_construct(*State, de.path());
  690. }
  691. /// Construct end iterator.
  692. directory_iterator() : State(nullptr) {}
  693. // No operator++ because we need error_code.
  694. directory_iterator &increment(std::error_code &ec) {
  695. ec = directory_iterator_increment(*State);
  696. return *this;
  697. }
  698. const directory_entry &operator*() const { return State->CurrentEntry; }
  699. const directory_entry *operator->() const { return &State->CurrentEntry; }
  700. bool operator==(const directory_iterator &RHS) const {
  701. if (State == RHS.State)
  702. return true;
  703. if (!RHS.State)
  704. return State->CurrentEntry == directory_entry();
  705. if (!State)
  706. return RHS.State->CurrentEntry == directory_entry();
  707. return State->CurrentEntry == RHS.State->CurrentEntry;
  708. }
  709. bool operator!=(const directory_iterator &RHS) const {
  710. return !(*this == RHS);
  711. }
  712. // Other members as required by
  713. // C++ Std, 24.1.1 Input iterators [input.iterators]
  714. };
  715. namespace detail {
  716. /// RecDirIterState - Keeps state for the recursive_directory_iterator. It is
  717. /// reference counted in order to preserve InputIterator semantics on copy.
  718. struct RecDirIterState : public RefCountedBase<RecDirIterState> {
  719. RecDirIterState()
  720. : Level(0)
  721. , HasNoPushRequest(false) {}
  722. std::stack<directory_iterator, std::vector<directory_iterator> > Stack;
  723. uint16_t Level;
  724. bool HasNoPushRequest;
  725. };
  726. }
  727. /// recursive_directory_iterator - Same as directory_iterator except for it
  728. /// recurses down into child directories.
  729. class recursive_directory_iterator {
  730. IntrusiveRefCntPtr<detail::RecDirIterState> State;
  731. public:
  732. recursive_directory_iterator() {}
  733. explicit recursive_directory_iterator(const Twine &path, std::error_code &ec)
  734. : State(new detail::RecDirIterState) {
  735. State->Stack.push(directory_iterator(path, ec));
  736. if (State->Stack.top() == directory_iterator())
  737. State.reset();
  738. }
  739. // No operator++ because we need error_code.
  740. recursive_directory_iterator &increment(std::error_code &ec) {
  741. const directory_iterator end_itr;
  742. if (State->HasNoPushRequest)
  743. State->HasNoPushRequest = false;
  744. else {
  745. file_status st;
  746. if ((ec = State->Stack.top()->status(st))) return *this;
  747. if (is_directory(st)) {
  748. State->Stack.push(directory_iterator(*State->Stack.top(), ec));
  749. if (ec) return *this;
  750. if (State->Stack.top() != end_itr) {
  751. ++State->Level;
  752. return *this;
  753. }
  754. State->Stack.pop();
  755. }
  756. }
  757. while (!State->Stack.empty()
  758. && State->Stack.top().increment(ec) == end_itr) {
  759. State->Stack.pop();
  760. --State->Level;
  761. }
  762. // Check if we are done. If so, create an end iterator.
  763. if (State->Stack.empty())
  764. State.reset();
  765. return *this;
  766. }
  767. const directory_entry &operator*() const { return *State->Stack.top(); }
  768. const directory_entry *operator->() const { return &*State->Stack.top(); }
  769. // observers
  770. /// Gets the current level. Starting path is at level 0.
  771. int level() const { return State->Level; }
  772. /// Returns true if no_push has been called for this directory_entry.
  773. bool no_push_request() const { return State->HasNoPushRequest; }
  774. // modifiers
  775. /// Goes up one level if Level > 0.
  776. void pop() {
  777. assert(State && "Cannot pop an end iterator!");
  778. assert(State->Level > 0 && "Cannot pop an iterator with level < 1");
  779. const directory_iterator end_itr;
  780. std::error_code ec;
  781. do {
  782. if (ec)
  783. report_fatal_error("Error incrementing directory iterator.");
  784. State->Stack.pop();
  785. --State->Level;
  786. } while (!State->Stack.empty()
  787. && State->Stack.top().increment(ec) == end_itr);
  788. // Check if we are done. If so, create an end iterator.
  789. if (State->Stack.empty())
  790. State.reset();
  791. }
  792. /// Does not go down into the current directory_entry.
  793. void no_push() { State->HasNoPushRequest = true; }
  794. bool operator==(const recursive_directory_iterator &RHS) const {
  795. return State == RHS.State;
  796. }
  797. bool operator!=(const recursive_directory_iterator &RHS) const {
  798. return !(*this == RHS);
  799. }
  800. // Other members as required by
  801. // C++ Std, 24.1.1 Input iterators [input.iterators]
  802. };
  803. /// @}
  804. } // end namespace fs
  805. } // end namespace sys
  806. } // end namespace llvm
  807. #endif