FileSystem.h 31 KB

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