LLVM  4.0.0
FileSystem.h
Go to the documentation of this file.
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 
27 #ifndef LLVM_SUPPORT_FILESYSTEM_H
28 #define LLVM_SUPPORT_FILESYSTEM_H
29 
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/ADT/StringRef.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Support/Chrono.h"
35 #include "llvm/Support/ErrorOr.h"
36 #include <cassert>
37 #include <cstdint>
38 #include <ctime>
39 #include <memory>
40 #include <stack>
41 #include <string>
42 #include <system_error>
43 #include <tuple>
44 #include <vector>
45 
46 #ifdef HAVE_SYS_STAT_H
47 #include <sys/stat.h>
48 #endif
49 
50 namespace llvm {
51 namespace sys {
52 namespace fs {
53 
54 /// An enumeration for the file system's view of the type.
55 enum class file_type {
61  block_file,
63  fifo_file,
66 };
67 
68 /// space_info - Self explanatory.
69 struct space_info {
70  uint64_t capacity;
71  uint64_t free;
72  uint64_t available;
73 };
74 
75 enum perms {
76  no_perms = 0,
77  owner_read = 0400,
78  owner_write = 0200,
79  owner_exe = 0100,
81  group_read = 040,
82  group_write = 020,
83  group_exe = 010,
87  others_exe = 01,
93  set_uid_on_exe = 04000,
94  set_gid_on_exe = 02000,
95  sticky_bit = 01000,
96  perms_not_known = 0xFFFF
97 };
98 
99 // Helper functions so that you can use & and | to manipulate perms bits:
100 inline perms operator|(perms l, perms r) {
101  return static_cast<perms>(static_cast<unsigned short>(l) |
102  static_cast<unsigned short>(r));
103 }
104 inline perms operator&(perms l, perms r) {
105  return static_cast<perms>(static_cast<unsigned short>(l) &
106  static_cast<unsigned short>(r));
107 }
108 inline perms &operator|=(perms &l, perms r) {
109  l = l | r;
110  return l;
111 }
112 inline perms &operator&=(perms &l, perms r) {
113  l = l & r;
114  return l;
115 }
116 inline perms operator~(perms x) {
117  return static_cast<perms>(~static_cast<unsigned short>(x));
118 }
119 
120 class UniqueID {
121  uint64_t Device;
122  uint64_t File;
123 
124 public:
125  UniqueID() = default;
126  UniqueID(uint64_t Device, uint64_t File) : Device(Device), File(File) {}
127 
128  bool operator==(const UniqueID &Other) const {
129  return Device == Other.Device && File == Other.File;
130  }
131  bool operator!=(const UniqueID &Other) const { return !(*this == Other); }
132  bool operator<(const UniqueID &Other) const {
133  return std::tie(Device, File) < std::tie(Other.Device, Other.File);
134  }
135 
136  uint64_t getDevice() const { return Device; }
137  uint64_t getFile() const { return File; }
138 };
139 
140 /// file_status - Represents the result of a call to stat and friends. It has
141 /// a platform-specific member to store the result.
143 {
144  #if defined(LLVM_ON_UNIX)
145  dev_t fs_st_dev;
146  ino_t fs_st_ino;
147  time_t fs_st_atime;
148  time_t fs_st_mtime;
149  uid_t fs_st_uid;
150  gid_t fs_st_gid;
151  off_t fs_st_size;
152  #elif defined (LLVM_ON_WIN32)
153  uint32_t LastAccessedTimeHigh;
154  uint32_t LastAccessedTimeLow;
155  uint32_t LastWriteTimeHigh;
156  uint32_t LastWriteTimeLow;
157  uint32_t VolumeSerialNumber;
158  uint32_t FileSizeHigh;
159  uint32_t FileSizeLow;
160  uint32_t FileIndexHigh;
161  uint32_t FileIndexLow;
162  #endif
163  friend bool equivalent(file_status A, file_status B);
164  file_type Type;
165  perms Perms;
166 
167 public:
168  #if defined(LLVM_ON_UNIX)
169  file_status()
170  : fs_st_dev(0), fs_st_ino(0), fs_st_atime(0), fs_st_mtime(0),
171  fs_st_uid(0), fs_st_gid(0), fs_st_size(0),
173 
175  : fs_st_dev(0), fs_st_ino(0), fs_st_atime(0), fs_st_mtime(0),
176  fs_st_uid(0), fs_st_gid(0), fs_st_size(0), Type(Type),
177  Perms(perms_not_known) {}
178 
179  file_status(file_type Type, perms Perms, dev_t Dev, ino_t Ino, time_t ATime,
180  time_t MTime, uid_t UID, gid_t GID, off_t Size)
181  : fs_st_dev(Dev), fs_st_ino(Ino), fs_st_atime(ATime), fs_st_mtime(MTime),
182  fs_st_uid(UID), fs_st_gid(GID), fs_st_size(Size), Type(Type),
183  Perms(Perms) {}
184  #elif defined(LLVM_ON_WIN32)
185  file_status()
186  : LastAccessedTimeHigh(0), LastAccessedTimeLow(0), LastWriteTimeHigh(0),
187  LastWriteTimeLow(0), VolumeSerialNumber(0), FileSizeHigh(0),
188  FileSizeLow(0), FileIndexHigh(0), FileIndexLow(0),
190 
191  file_status(file_type Type)
192  : LastAccessedTimeHigh(0), LastAccessedTimeLow(0), LastWriteTimeHigh(0),
193  LastWriteTimeLow(0), VolumeSerialNumber(0), FileSizeHigh(0),
194  FileSizeLow(0), FileIndexHigh(0), FileIndexLow(0), Type(Type),
195  Perms(perms_not_known) {}
196 
197  file_status(file_type Type, uint32_t LastAccessTimeHigh,
198  uint32_t LastAccessTimeLow, uint32_t LastWriteTimeHigh,
199  uint32_t LastWriteTimeLow, uint32_t VolumeSerialNumber,
200  uint32_t FileSizeHigh, uint32_t FileSizeLow,
201  uint32_t FileIndexHigh, uint32_t FileIndexLow)
202  : LastAccessedTimeHigh(LastAccessTimeHigh), LastAccessedTimeLow(LastAccessTimeLow),
203  LastWriteTimeHigh(LastWriteTimeHigh),
204  LastWriteTimeLow(LastWriteTimeLow),
205  VolumeSerialNumber(VolumeSerialNumber), FileSizeHigh(FileSizeHigh),
206  FileSizeLow(FileSizeLow), FileIndexHigh(FileIndexHigh),
207  FileIndexLow(FileIndexLow), Type(Type), Perms(perms_not_known) {}
208  #endif
209 
210  // getters
211  file_type type() const { return Type; }
212  perms permissions() const { return Perms; }
215  UniqueID getUniqueID() const;
216 
217  #if defined(LLVM_ON_UNIX)
218  uint32_t getUser() const { return fs_st_uid; }
219  uint32_t getGroup() const { return fs_st_gid; }
220  uint64_t getSize() const { return fs_st_size; }
221  #elif defined (LLVM_ON_WIN32)
222  uint32_t getUser() const {
223  return 9999; // Not applicable to Windows, so...
224  }
225  uint32_t getGroup() const {
226  return 9999; // Not applicable to Windows, so...
227  }
228  uint64_t getSize() const {
229  return (uint64_t(FileSizeHigh) << 32) + FileSizeLow;
230  }
231  #endif
232 
233  // setters
234  void type(file_type v) { Type = v; }
235  void permissions(perms p) { Perms = p; }
236 };
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_cl_gl_object, ///< Microsoft cl.exe's intermediate code file
263  coff_object, ///< COFF object file
264  coff_import_library, ///< COFF import library
265  pecoff_executable, ///< PECOFF executable file
266  windows_resource, ///< Windows compiled resource file (.rc)
267  wasm_object ///< WebAssembly Object file
268  };
269 
270  bool is_object() const {
271  return V != unknown;
272  }
273 
274  file_magic() : V(unknown) {}
275  file_magic(Impl V) : V(V) {}
276  operator Impl() const { return V; }
277 
278 private:
279  Impl V;
280 };
281 
282 /// @}
283 /// @name Physical Operators
284 /// @{
285 
286 /// @brief Make \a path an absolute path.
287 ///
288 /// Makes \a path absolute using the \a current_directory if it is not already.
289 /// An empty \a path will result in the \a 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(const Twine &current_directory,
298  SmallVectorImpl<char> &path);
299 
300 /// @brief Make \a path an absolute path.
301 ///
302 /// Makes \a path absolute using the current directory if it is not already. An
303 /// empty \a path will result in the current directory.
304 ///
305 /// /absolute/path => /absolute/path
306 /// relative/../path => <current-directory>/relative/../path
307 ///
308 /// @param path A path that is modified to be an absolute path.
309 /// @returns errc::success if \a path has been made absolute, otherwise a
310 /// platform-specific error_code.
311 std::error_code make_absolute(SmallVectorImpl<char> &path);
312 
313 /// @brief Create all the non-existent directories in path.
314 ///
315 /// @param path Directories to create.
316 /// @returns errc::success if is_directory(path), otherwise a platform
317 /// specific error_code. If IgnoreExisting is false, also returns
318 /// error if the directory already existed.
319 std::error_code create_directories(const Twine &path,
320  bool IgnoreExisting = true,
321  perms Perms = owner_all | group_all);
322 
323 /// @brief Create the directory in path.
324 ///
325 /// @param path Directory to create.
326 /// @returns errc::success if is_directory(path), otherwise a platform
327 /// specific error_code. If IgnoreExisting is false, also returns
328 /// error if the directory already existed.
329 std::error_code create_directory(const Twine &path, bool IgnoreExisting = true,
330  perms Perms = owner_all | group_all);
331 
332 /// @brief Create a link from \a from to \a to.
333 ///
334 /// The link may be a soft or a hard link, depending on the platform. The caller
335 /// may not assume which one. Currently on windows it creates a hard link since
336 /// soft links require extra privileges. On unix, it creates a soft link since
337 /// hard links don't work on SMB file systems.
338 ///
339 /// @param to The path to hard link to.
340 /// @param from The path to hard link from. This is created.
341 /// @returns errc::success if the link was created, otherwise a platform
342 /// specific error_code.
343 std::error_code create_link(const Twine &to, const Twine &from);
344 
345 /// Create a hard link from \a from to \a to, or return an error.
346 ///
347 /// @param to The path to hard link to.
348 /// @param from The path to hard link from. This is created.
349 /// @returns errc::success if the link was created, otherwise a platform
350 /// specific error_code.
351 std::error_code create_hard_link(const Twine &to, const Twine &from);
352 
353 /// @brief Get the current path.
354 ///
355 /// @param result Holds the current path on return.
356 /// @returns errc::success if the current path has been stored in result,
357 /// otherwise a platform-specific error_code.
358 std::error_code current_path(SmallVectorImpl<char> &result);
359 
360 /// @brief Remove path. Equivalent to POSIX remove().
361 ///
362 /// @param path Input path.
363 /// @returns errc::success if path has been removed or didn't exist, otherwise a
364 /// platform-specific error code. If IgnoreNonExisting is false, also
365 /// returns error if the file didn't exist.
366 std::error_code remove(const Twine &path, bool IgnoreNonExisting = true);
367 
368 /// @brief Rename \a from to \a to. Files are renamed as if by POSIX rename().
369 ///
370 /// @param from The path to rename from.
371 /// @param to The path to rename to. This is created.
372 std::error_code rename(const Twine &from, const Twine &to);
373 
374 /// @brief Copy the contents of \a From to \a To.
375 ///
376 /// @param From The path to copy from.
377 /// @param To The path to copy to. This is created.
378 std::error_code copy_file(const Twine &From, const Twine &To);
379 
380 /// @brief Resize path to size. File is resized as if by POSIX truncate().
381 ///
382 /// @param FD Input file descriptor.
383 /// @param Size Size to resize to.
384 /// @returns errc::success if \a path has been resized to \a size, otherwise a
385 /// platform-specific error_code.
386 std::error_code resize_file(int FD, uint64_t Size);
387 
388 /// @}
389 /// @name Physical Observers
390 /// @{
391 
392 /// @brief Does file exist?
393 ///
394 /// @param status A file_status previously returned from stat.
395 /// @returns True if the file represented by status exists, false if it does
396 /// not.
397 bool exists(file_status status);
398 
399 enum class AccessMode { Exist, Write, Execute };
400 
401 /// @brief Can the file be accessed?
402 ///
403 /// @param Path Input path.
404 /// @returns errc::success if the path can be accessed, otherwise a
405 /// platform-specific error_code.
406 std::error_code access(const Twine &Path, AccessMode Mode);
407 
408 /// @brief Does file exist?
409 ///
410 /// @param Path Input path.
411 /// @returns True if it exists, false otherwise.
412 inline bool exists(const Twine &Path) {
413  return !access(Path, AccessMode::Exist);
414 }
415 
416 /// @brief Can we execute this file?
417 ///
418 /// @param Path Input path.
419 /// @returns True if we can execute it, false otherwise.
420 bool can_execute(const Twine &Path);
421 
422 /// @brief Can we write this file?
423 ///
424 /// @param Path Input path.
425 /// @returns True if we can write to it, false otherwise.
426 inline bool can_write(const Twine &Path) {
427  return !access(Path, AccessMode::Write);
428 }
429 
430 /// @brief Do file_status's represent the same thing?
431 ///
432 /// @param A Input file_status.
433 /// @param B Input file_status.
434 ///
435 /// assert(status_known(A) || status_known(B));
436 ///
437 /// @returns True if A and B both represent the same file system entity, false
438 /// otherwise.
439 bool equivalent(file_status A, file_status B);
440 
441 /// @brief Do paths represent the same thing?
442 ///
443 /// assert(status_known(A) || status_known(B));
444 ///
445 /// @param A Input path A.
446 /// @param B Input path B.
447 /// @param result Set to true if stat(A) and stat(B) have the same device and
448 /// inode (or equivalent).
449 /// @returns errc::success if result has been successfully set, otherwise a
450 /// platform-specific error_code.
451 std::error_code equivalent(const Twine &A, const Twine &B, bool &result);
452 
453 /// @brief Simpler version of equivalent for clients that don't need to
454 /// differentiate between an error and false.
455 inline bool equivalent(const Twine &A, const Twine &B) {
456  bool result;
457  return !equivalent(A, B, result) && result;
458 }
459 
460 /// @brief Does status represent a directory?
461 ///
462 /// @param status A file_status previously returned from status.
463 /// @returns status.type() == file_type::directory_file.
464 bool is_directory(file_status status);
465 
466 /// @brief Is path a directory?
467 ///
468 /// @param path Input path.
469 /// @param result Set to true if \a path is a directory, false if it is not.
470 /// Undefined otherwise.
471 /// @returns errc::success if result has been successfully set, otherwise a
472 /// platform-specific error_code.
473 std::error_code is_directory(const Twine &path, bool &result);
474 
475 /// @brief Simpler version of is_directory for clients that don't need to
476 /// differentiate between an error and false.
477 inline bool is_directory(const Twine &Path) {
478  bool Result;
479  return !is_directory(Path, Result) && Result;
480 }
481 
482 /// @brief Does status represent a regular file?
483 ///
484 /// @param status A file_status previously returned from status.
485 /// @returns status_known(status) && status.type() == file_type::regular_file.
486 bool is_regular_file(file_status status);
487 
488 /// @brief Is path a regular file?
489 ///
490 /// @param path Input path.
491 /// @param result Set to true if \a path is a regular file, false if it is not.
492 /// Undefined otherwise.
493 /// @returns errc::success if result has been successfully set, otherwise a
494 /// platform-specific error_code.
495 std::error_code is_regular_file(const Twine &path, bool &result);
496 
497 /// @brief Simpler version of is_regular_file for clients that don't need to
498 /// differentiate between an error and false.
499 inline bool is_regular_file(const Twine &Path) {
500  bool Result;
501  if (is_regular_file(Path, Result))
502  return false;
503  return Result;
504 }
505 
506 /// @brief Does this status represent something that exists but is not a
507 /// directory, regular file, or symlink?
508 ///
509 /// @param status A file_status previously returned from status.
510 /// @returns exists(s) && !is_regular_file(s) && !is_directory(s)
511 bool is_other(file_status status);
512 
513 /// @brief Is path something that exists but is not a directory,
514 /// regular file, or symlink?
515 ///
516 /// @param path Input path.
517 /// @param result Set to true if \a path exists, but is not a directory, regular
518 /// file, or a symlink, false if it does not. Undefined otherwise.
519 /// @returns errc::success if result has been successfully set, otherwise a
520 /// platform-specific error_code.
521 std::error_code is_other(const Twine &path, bool &result);
522 
523 /// @brief Get file status as if by POSIX stat().
524 ///
525 /// @param path Input path.
526 /// @param result Set to the file status.
527 /// @returns errc::success if result has been successfully set, otherwise a
528 /// platform-specific error_code.
529 std::error_code status(const Twine &path, file_status &result);
530 
531 /// @brief A version for when a file descriptor is already available.
532 std::error_code status(int FD, file_status &Result);
533 
534 /// @brief Get file size.
535 ///
536 /// @param Path Input path.
537 /// @param Result Set to the size of the file in \a Path.
538 /// @returns errc::success if result has been successfully set, otherwise a
539 /// platform-specific error_code.
540 inline std::error_code file_size(const Twine &Path, uint64_t &Result) {
542  std::error_code EC = status(Path, Status);
543  if (EC)
544  return EC;
545  Result = Status.getSize();
546  return std::error_code();
547 }
548 
549 /// @brief Set the file modification and access time.
550 ///
551 /// @returns errc::success if the file times were successfully set, otherwise a
552 /// platform-specific error_code or errc::function_not_supported on
553 /// platforms where the functionality isn't available.
554 std::error_code setLastModificationAndAccessTime(int FD, TimePoint<> Time);
555 
556 /// @brief Is status available?
557 ///
558 /// @param s Input file status.
559 /// @returns True if status() != status_error.
560 bool status_known(file_status s);
561 
562 /// @brief Is status available?
563 ///
564 /// @param path Input path.
565 /// @param result Set to true if status() != status_error.
566 /// @returns errc::success if result has been successfully set, otherwise a
567 /// platform-specific error_code.
568 std::error_code status_known(const Twine &path, bool &result);
569 
570 /// @brief Create a uniquely named file.
571 ///
572 /// Generates a unique path suitable for a temporary file and then opens it as a
573 /// file. The name is based on \a model with '%' replaced by a random char in
574 /// [0-9a-f]. If \a model is not an absolute path, the temporary file will be
575 /// created in the current directory.
576 ///
577 /// Example: clang-%%-%%-%%-%%-%%.s => clang-a0-b1-c2-d3-e4.s
578 ///
579 /// This is an atomic operation. Either the file is created and opened, or the
580 /// file system is left untouched.
581 ///
582 /// The intended use is for files that are to be kept, possibly after
583 /// renaming them. For example, when running 'clang -c foo.o', the file can
584 /// be first created as foo-abc123.o and then renamed.
585 ///
586 /// @param Model Name to base unique path off of.
587 /// @param ResultFD Set to the opened file's file descriptor.
588 /// @param ResultPath Set to the opened file's absolute path.
589 /// @returns errc::success if Result{FD,Path} have been successfully set,
590 /// otherwise a platform-specific error_code.
591 std::error_code createUniqueFile(const Twine &Model, int &ResultFD,
592  SmallVectorImpl<char> &ResultPath,
593  unsigned Mode = all_read | all_write);
594 
595 /// @brief Simpler version for clients that don't want an open file.
596 std::error_code createUniqueFile(const Twine &Model,
597  SmallVectorImpl<char> &ResultPath);
598 
599 /// @brief Create a file in the system temporary directory.
600 ///
601 /// The filename is of the form prefix-random_chars.suffix. Since the directory
602 /// is not know to the caller, Prefix and Suffix cannot have path separators.
603 /// The files are created with mode 0600.
604 ///
605 /// This should be used for things like a temporary .s that is removed after
606 /// running the assembler.
607 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
608  int &ResultFD,
609  SmallVectorImpl<char> &ResultPath);
610 
611 /// @brief Simpler version for clients that don't want an open file.
612 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
613  SmallVectorImpl<char> &ResultPath);
614 
615 std::error_code createUniqueDirectory(const Twine &Prefix,
616  SmallVectorImpl<char> &ResultPath);
617 
618 /// @brief Fetch a path to an open file, as specified by a file descriptor
619 ///
620 /// @param FD File descriptor to a currently open file
621 /// @param ResultPath The buffer into which to write the path
622 std::error_code getPathFromOpenFD(int FD, SmallVectorImpl<char> &ResultPath);
623 
624 enum OpenFlags : unsigned {
625  F_None = 0,
626 
627  /// F_Excl - When opening a file, this flag makes raw_fd_ostream
628  /// report an error if the file already exists.
629  F_Excl = 1,
630 
631  /// F_Append - When opening a file, if it already exists append to the
632  /// existing file instead of returning an error. This may not be specified
633  /// with F_Excl.
634  F_Append = 2,
635 
636  /// The file should be opened in text mode on platforms that make this
637  /// distinction.
638  F_Text = 4,
639 
640  /// Open the file for read and write.
641  F_RW = 8
642 };
643 
645  return OpenFlags(unsigned(A) | unsigned(B));
646 }
647 
649  A = A | B;
650  return A;
651 }
652 
653 std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
654  OpenFlags Flags, unsigned Mode = 0666);
655 
656 std::error_code openFileForRead(const Twine &Name, int &ResultFD,
657  SmallVectorImpl<char> *RealPath = nullptr);
658 
659 /// @brief Identify the type of a binary file based on how magical it is.
660 file_magic identify_magic(StringRef magic);
661 
662 /// @brief Get and identify \a path's type based on its content.
663 ///
664 /// @param path Input path.
665 /// @param result Set to the type of file, or file_magic::unknown.
666 /// @returns errc::success if result has been successfully set, otherwise a
667 /// platform-specific error_code.
668 std::error_code identify_magic(const Twine &path, file_magic &result);
669 
670 std::error_code getUniqueID(const Twine Path, UniqueID &Result);
671 
672 /// @brief Get disk space usage information.
673 ///
674 /// Note: Users must be careful about "Time Of Check, Time Of Use" kind of bug.
675 /// Note: Windows reports results according to the quota allocated to the user.
676 ///
677 /// @param Path Input path.
678 /// @returns a space_info structure filled with the capacity, free, and
679 /// available space on the device \a Path is on. A platform specific error_code
680 /// is returned on error.
682 
683 /// This class represents a memory mapped file. It is based on
684 /// boost::iostreams::mapped_file.
686 public:
687  enum mapmode {
688  readonly, ///< May only access map via const_data as read only.
689  readwrite, ///< May access map via data and modify it. Written to path.
690  priv ///< May modify via data, but changes are lost on destruction.
691  };
692 
693 private:
694  /// Platform-specific mapping state.
695  uint64_t Size;
696  void *Mapping;
697 
698  std::error_code init(int FD, uint64_t Offset, mapmode Mode);
699 
700 public:
701  mapped_file_region() = delete;
704 
705  /// \param fd An open file descriptor to map. mapped_file_region takes
706  /// ownership if closefd is true. It must have been opended in the correct
707  /// mode.
708  mapped_file_region(int fd, mapmode mode, uint64_t length, uint64_t offset,
709  std::error_code &ec);
710 
712 
713  uint64_t size() const;
714  char *data() const;
715 
716  /// Get a const view of the data. Modifying this memory has undefined
717  /// behavior.
718  const char *const_data() const;
719 
720  /// \returns The minimum alignment offset must be.
721  static int alignment();
722 };
723 
724 /// Return the path to the main executable, given the value of argv[0] from
725 /// program startup and the address of main itself. In extremis, this function
726 /// may fail and return an empty path.
727 std::string getMainExecutable(const char *argv0, void *MainExecAddr);
728 
729 /// @}
730 /// @name Iterators
731 /// @{
732 
733 /// directory_entry - A single entry in a directory. Caches the status either
734 /// from the result of the iteration syscall, or the first time status is
735 /// called.
737  std::string Path;
738  mutable file_status Status;
739 
740 public:
742  : Path(path.str())
743  , Status(st) {}
744 
745  directory_entry() = default;
746 
747  void assign(const Twine &path, file_status st = file_status()) {
748  Path = path.str();
749  Status = st;
750  }
751 
753 
754  const std::string &path() const { return Path; }
755  std::error_code status(file_status &result) const;
756 
757  bool operator==(const directory_entry& rhs) const { return Path == rhs.Path; }
758  bool operator!=(const directory_entry& rhs) const { return !(*this == rhs); }
759  bool operator< (const directory_entry& rhs) const;
760  bool operator<=(const directory_entry& rhs) const;
761  bool operator> (const directory_entry& rhs) const;
762  bool operator>=(const directory_entry& rhs) const;
763 };
764 
765 namespace detail {
766  struct DirIterState;
767 
769  std::error_code directory_iterator_increment(DirIterState &);
770  std::error_code directory_iterator_destruct(DirIterState &);
771 
772  /// Keeps state for the directory_iterator.
773  struct DirIterState {
776  }
777 
780  };
781 } // end namespace detail
782 
783 /// directory_iterator - Iterates through the entries in path. There is no
784 /// operator++ because we need an error_code. If it's really needed we can make
785 /// it call report_fatal_error on error.
787  std::shared_ptr<detail::DirIterState> State;
788 
789 public:
790  explicit directory_iterator(const Twine &path, std::error_code &ec) {
791  State = std::make_shared<detail::DirIterState>();
792  SmallString<128> path_storage;
794  path.toStringRef(path_storage));
795  }
796 
797  explicit directory_iterator(const directory_entry &de, std::error_code &ec) {
798  State = std::make_shared<detail::DirIterState>();
799  ec = detail::directory_iterator_construct(*State, de.path());
800  }
801 
802  /// Construct end iterator.
803  directory_iterator() = default;
804 
805  // No operator++ because we need error_code.
806  directory_iterator &increment(std::error_code &ec) {
807  ec = directory_iterator_increment(*State);
808  return *this;
809  }
810 
811  const directory_entry &operator*() const { return State->CurrentEntry; }
812  const directory_entry *operator->() const { return &State->CurrentEntry; }
813 
814  bool operator==(const directory_iterator &RHS) const {
815  if (State == RHS.State)
816  return true;
817  if (!RHS.State)
818  return State->CurrentEntry == directory_entry();
819  if (!State)
820  return RHS.State->CurrentEntry == directory_entry();
821  return State->CurrentEntry == RHS.State->CurrentEntry;
822  }
823 
824  bool operator!=(const directory_iterator &RHS) const {
825  return !(*this == RHS);
826  }
827  // Other members as required by
828  // C++ Std, 24.1.1 Input iterators [input.iterators]
829 };
830 
831 namespace detail {
832  /// Keeps state for the recursive_directory_iterator.
834  std::stack<directory_iterator, std::vector<directory_iterator>> Stack;
835  uint16_t Level = 0;
836  bool HasNoPushRequest = false;
837  };
838 } // end namespace detail
839 
840 /// recursive_directory_iterator - Same as directory_iterator except for it
841 /// recurses down into child directories.
843  std::shared_ptr<detail::RecDirIterState> State;
844 
845 public:
846  recursive_directory_iterator() = default;
847  explicit recursive_directory_iterator(const Twine &path, std::error_code &ec)
848  : State(std::make_shared<detail::RecDirIterState>()) {
849  State->Stack.push(directory_iterator(path, ec));
850  if (State->Stack.top() == directory_iterator())
851  State.reset();
852  }
853 
854  // No operator++ because we need error_code.
855  recursive_directory_iterator &increment(std::error_code &ec) {
856  const directory_iterator end_itr = {};
857 
858  if (State->HasNoPushRequest)
859  State->HasNoPushRequest = false;
860  else {
861  file_status st;
862  if ((ec = State->Stack.top()->status(st))) return *this;
863  if (is_directory(st)) {
864  State->Stack.push(directory_iterator(*State->Stack.top(), ec));
865  if (ec) return *this;
866  if (State->Stack.top() != end_itr) {
867  ++State->Level;
868  return *this;
869  }
870  State->Stack.pop();
871  }
872  }
873 
874  while (!State->Stack.empty()
875  && State->Stack.top().increment(ec) == end_itr) {
876  State->Stack.pop();
877  --State->Level;
878  }
879 
880  // Check if we are done. If so, create an end iterator.
881  if (State->Stack.empty())
882  State.reset();
883 
884  return *this;
885  }
886 
887  const directory_entry &operator*() const { return *State->Stack.top(); }
888  const directory_entry *operator->() const { return &*State->Stack.top(); }
889 
890  // observers
891  /// Gets the current level. Starting path is at level 0.
892  int level() const { return State->Level; }
893 
894  /// Returns true if no_push has been called for this directory_entry.
895  bool no_push_request() const { return State->HasNoPushRequest; }
896 
897  // modifiers
898  /// Goes up one level if Level > 0.
899  void pop() {
900  assert(State && "Cannot pop an end iterator!");
901  assert(State->Level > 0 && "Cannot pop an iterator with level < 1");
902 
903  const directory_iterator end_itr = {};
904  std::error_code ec;
905  do {
906  if (ec)
907  report_fatal_error("Error incrementing directory iterator.");
908  State->Stack.pop();
909  --State->Level;
910  } while (!State->Stack.empty()
911  && State->Stack.top().increment(ec) == end_itr);
912 
913  // Check if we are done. If so, create an end iterator.
914  if (State->Stack.empty())
915  State.reset();
916  }
917 
918  /// Does not go down into the current directory_entry.
919  void no_push() { State->HasNoPushRequest = true; }
920 
921  bool operator==(const recursive_directory_iterator &RHS) const {
922  return State == RHS.State;
923  }
924 
925  bool operator!=(const recursive_directory_iterator &RHS) const {
926  return !(*this == RHS);
927  }
928  // Other members as required by
929  // C++ Std, 24.1.1 Input iterators [input.iterators]
930 };
931 
932 /// @}
933 
934 } // end namespace fs
935 } // end namespace sys
936 } // end namespace llvm
937 
938 #endif // LLVM_SUPPORT_FILESYSTEM_H
recursive_directory_iterator(const Twine &path, std::error_code &ec)
Definition: FileSystem.h:847
std::error_code create_directories(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create all the non-existent directories in path.
Definition: Path.cpp:882
F_Append - When opening a file, if it already exists append to the existing file instead of returning...
Definition: FileSystem.h:634
bool can_execute(const Twine &Path)
Can we execute this file?
const directory_entry * operator->() const
Definition: FileSystem.h:812
Represents either an error or a value T.
Definition: ErrorOr.h:68
space_info - Self explanatory.
Definition: FileSystem.h:69
WebAssembly Object file.
Definition: FileSystem.h:267
bool operator<=(const directory_entry &rhs) const
SI Whole Quad Mode
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
std::error_code createUniqueFile(const Twine &Model, int &ResultFD, SmallVectorImpl< char > &ResultPath, unsigned Mode=all_read|all_write)
Create a uniquely named file.
Definition: Path.cpp:762
std::error_code openFileForRead(const Twine &Name, int &ResultFD, SmallVectorImpl< char > *RealPath=nullptr)
F_Excl - When opening a file, this flag makes raw_fd_ostream report an error if the file already exis...
Definition: FileSystem.h:629
bool operator==(const recursive_directory_iterator &RHS) const
Definition: FileSystem.h:921
bool operator!=(const UniqueID &Other) const
Definition: FileSystem.h:131
void replace_filename(const Twine &filename, file_status st=file_status())
Definition: Path.cpp:986
void pop()
Goes up one level if Level > 0.
Definition: FileSystem.h:899
UniqueID getUniqueID() const
mapped_file_region & operator=(mapped_file_region &)=delete
bool operator<(const UniqueID &Other) const
Definition: FileSystem.h:132
This class represents a memory mapped file.
Definition: FileSystem.h:685
std::error_code setLastModificationAndAccessTime(int FD, TimePoint<> Time)
Set the file modification and access time.
opt Optimize addressing mode
std::error_code current_path(SmallVectorImpl< char > &result)
Get the current path.
ELF Relocatable object file.
Definition: FileSystem.h:246
perms operator~(perms x)
Definition: FileSystem.h:116
directory_iterator & increment(std::error_code &ec)
Definition: FileSystem.h:806
recursive_directory_iterator - Same as directory_iterator except for it recurses down into child dire...
Definition: FileSystem.h:842
bool operator!=(const directory_iterator &RHS) const
Definition: FileSystem.h:824
const char * const_data() const
Get a const view of the data.
file_status - Represents the result of a call to stat and friends.
Definition: FileSystem.h:142
bool status_known(file_status s)
Is status available?
Definition: Path.cpp:944
std::error_code directory_iterator_increment(DirIterState &)
void permissions(perms p)
Definition: FileSystem.h:235
bool operator>=(const directory_entry &rhs) const
std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:17
struct fuzzer::@269 Flags
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
Keeps state for the directory_iterator.
Definition: FileSystem.h:773
directory_iterator(const Twine &path, std::error_code &ec)
Definition: FileSystem.h:790
bool operator==(const directory_entry &rhs) const
Definition: FileSystem.h:757
perms operator&(perms l, perms r)
Definition: FileSystem.h:104
bool operator!=(const directory_entry &rhs) const
Definition: FileSystem.h:758
std::error_code file_size(const Twine &Path, uint64_t &Result)
Get file size.
Definition: FileSystem.h:540
May access map via data and modify it. Written to path.
Definition: FileSystem.h:689
bool no_push_request() const
Returns true if no_push has been called for this directory_entry.
Definition: FileSystem.h:895
bool can_write(const Twine &Path)
Can we write this file?
Definition: FileSystem.h:426
const directory_entry * operator->() const
Definition: FileSystem.h:888
ELF dynamically linked shared lib.
Definition: FileSystem.h:248
May only access map via const_data as read only.
Definition: FileSystem.h:688
directory_entry(const Twine &path, file_status st=file_status())
Definition: FileSystem.h:741
Windows compiled resource file (.rc)
Definition: FileSystem.h:266
std::error_code create_link(const Twine &to, const Twine &from)
Create a link from from to to.
Open the file for read and write.
Definition: FileSystem.h:641
void type(file_type v)
Definition: FileSystem.h:234
static GCRegistry::Add< OcamlGC > B("ocaml","ocaml 3.10-compatible GC")
std::stack< directory_iterator, std::vector< directory_iterator > > Stack
Definition: FileSystem.h:834
std::string getMainExecutable(const char *argv0, void *MainExecAddr)
Return the path to the main executable, given the value of argv[0] from program startup and the addre...
std::error_code copy_file(const Twine &From, const Twine &To)
Copy the contents of From to To.
Definition: Path.cpp:906
StringRef filename(StringRef path)
Get filename.
Definition: Path.cpp:584
ar style archive file
Definition: FileSystem.h:244
bool is_object() const
Definition: FileSystem.h:270
UniqueID(uint64_t Device, uint64_t File)
Definition: FileSystem.h:126
bool operator<(const directory_entry &rhs) const
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
void no_push()
Does not go down into the current directory_entry.
Definition: FileSystem.h:919
static char * argv0
Microsoft cl.exe's intermediate code file.
Definition: FileSystem.h:262
void assign(const Twine &path, file_status st=file_status())
Definition: FileSystem.h:747
recursive_directory_iterator & increment(std::error_code &ec)
Definition: FileSystem.h:855
std::error_code directory_iterator_construct(DirIterState &, StringRef)
bool is_other(file_status status)
Does this status represent something that exists but is not a directory, regular file, or symlink?
Definition: Path.cpp:972
TimePoint getLastAccessedTime() const
uint32_t Offset
std::error_code getUniqueID(const Twine Path, UniqueID &Result)
Definition: Path.cpp:753
std::error_code resize_file(int FD, uint64_t Size)
Resize path to size.
const directory_entry & operator*() const
Definition: FileSystem.h:811
friend bool equivalent(file_status A, file_status B)
Do file_status's represent the same thing?
std::error_code getPathFromOpenFD(int FD, SmallVectorImpl< char > &ResultPath)
Fetch a path to an open file, as specified by a file descriptor.
std::error_code make_absolute(const Twine &current_directory, SmallVectorImpl< char > &path)
Make path an absolute path.
Definition: Path.cpp:873
std::error_code create_hard_link(const Twine &to, const Twine &from)
Create a hard link from from to to, or return an error.
const directory_entry & operator*() const
Definition: FileSystem.h:887
perms permissions() const
Definition: FileSystem.h:212
const std::string & path() const
Definition: FileSystem.h:754
perms operator|(perms l, perms r)
Definition: FileSystem.h:100
bool is_directory(file_status status)
Does status represent a directory?
Definition: Path.cpp:948
file_magic identify_magic(StringRef magic)
Identify the type of a binary file based on how magical it is.
Definition: Path.cpp:999
std::error_code rename(const Twine &from, const Twine &to)
Rename from to to.
Keeps state for the recursive_directory_iterator.
Definition: FileSystem.h:833
StringRef toStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single StringRef if it can be represented as such.
Definition: Twine.h:463
std::error_code createUniqueDirectory(const Twine &Prefix, SmallVectorImpl< char > &ResultPath)
Definition: Path.cpp:809
std::error_code status(file_status &result) const
Definition: Path.cpp:1164
uint64_t getDevice() const
Definition: FileSystem.h:136
bool is_regular_file(file_status status)
Does status represent a regular file?
Definition: Path.cpp:960
The file should be opened in text mode on platforms that make this distinction.
Definition: FileSystem.h:638
May modify via data, but changes are lost on destruction.
Definition: FileSystem.h:690
bool operator!=(const recursive_directory_iterator &RHS) const
Definition: FileSystem.h:925
bool operator>(const directory_entry &rhs) const
ErrorOr< space_info > disk_space(const Twine &Path)
Get disk space usage information.
directory_iterator(const directory_entry &de, std::error_code &ec)
Definition: FileSystem.h:797
std::error_code directory_iterator_destruct(DirIterState &)
directory_iterator - Iterates through the entries in path.
Definition: FileSystem.h:786
file_magic - An "enum class" enumeration of file types based on magic (the first N bytes of the file)...
Definition: FileSystem.h:240
file_type
An enumeration for the file system's view of the type.
Definition: FileSystem.h:55
std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD, SmallVectorImpl< char > &ResultPath)
Create a file in the system temporary directory.
Definition: Path.cpp:794
TimePoint getLastModificationTime() const
std::error_code create_directory(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create the directory in path.
int level() const
Gets the current level. Starting path is at level 0.
Definition: FileSystem.h:892
bool operator==(const UniqueID &Other) const
Definition: FileSystem.h:128
Provides ErrorOr<T> smart pointer.
bool operator==(const directory_iterator &RHS) const
Definition: FileSystem.h:814
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
perms & operator&=(perms &l, perms r)
Definition: FileSystem.h:112
bool equivalent(file_status A, file_status B)
Do file_status's represent the same thing?
perms & operator|=(perms &l, perms r)
Definition: FileSystem.h:108
directory_entry()=default
uint64_t getFile() const
Definition: FileSystem.h:137
directory_entry - A single entry in a directory.
Definition: FileSystem.h:736
std::error_code access(const Twine &Path, AccessMode Mode)
Can the file be accessed?
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:47
std::error_code status(const Twine &path, file_status &result)
Get file status as if by POSIX stat().
bool exists(file_status status)
Does file exist?
Definition: Path.cpp:940
file_type type() const
Definition: FileSystem.h:211
directory_iterator()=default
Construct end iterator.
static GCRegistry::Add< ErlangGC > A("erlang","erlang-compatible garbage collector")
std::chrono::time_point< std::chrono::system_clock, D > TimePoint
A time point on the system clock.
Definition: Chrono.h:33
std::error_code openFileForWrite(const Twine &Name, int &ResultFD, OpenFlags Flags, unsigned Mode=0666)