FileSystem.h 32 KB

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