FileSystem.h 32 KB

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