LLVM  8.0.1
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/Config/llvm-config.h"
34 #include "llvm/Support/Chrono.h"
35 #include "llvm/Support/Error.h"
37 #include "llvm/Support/ErrorOr.h"
38 #include "llvm/Support/MD5.h"
39 #include <cassert>
40 #include <cstdint>
41 #include <ctime>
42 #include <memory>
43 #include <stack>
44 #include <string>
45 #include <system_error>
46 #include <tuple>
47 #include <vector>
48 
49 #ifdef HAVE_SYS_STAT_H
50 #include <sys/stat.h>
51 #endif
52 
53 namespace llvm {
54 namespace sys {
55 namespace fs {
56 
57 #if defined(_WIN32)
58 // A Win32 HANDLE is a typedef of void*
59 using file_t = void *;
60 #else
61 using file_t = int;
62 #endif
63 
64 extern const file_t kInvalidFile;
65 
66 /// An enumeration for the file system's view of the type.
67 enum class file_type {
73  block_file,
75  fifo_file,
78 };
79 
80 /// space_info - Self explanatory.
81 struct space_info {
82  uint64_t capacity;
83  uint64_t free;
84  uint64_t available;
85 };
86 
87 enum perms {
88  no_perms = 0,
89  owner_read = 0400,
90  owner_write = 0200,
91  owner_exe = 0100,
93  group_read = 040,
94  group_write = 020,
95  group_exe = 010,
99  others_exe = 01,
105  set_uid_on_exe = 04000,
106  set_gid_on_exe = 02000,
107  sticky_bit = 01000,
110 };
111 
112 // Helper functions so that you can use & and | to manipulate perms bits:
113 inline perms operator|(perms l, perms r) {
114  return static_cast<perms>(static_cast<unsigned short>(l) |
115  static_cast<unsigned short>(r));
116 }
117 inline perms operator&(perms l, perms r) {
118  return static_cast<perms>(static_cast<unsigned short>(l) &
119  static_cast<unsigned short>(r));
120 }
121 inline perms &operator|=(perms &l, perms r) {
122  l = l | r;
123  return l;
124 }
125 inline perms &operator&=(perms &l, perms r) {
126  l = l & r;
127  return l;
128 }
129 inline perms operator~(perms x) {
130  // Avoid UB by explicitly truncating the (unsigned) ~ result.
131  return static_cast<perms>(
132  static_cast<unsigned short>(~static_cast<unsigned short>(x)));
133 }
134 
135 class UniqueID {
136  uint64_t Device;
137  uint64_t File;
138 
139 public:
140  UniqueID() = default;
141  UniqueID(uint64_t Device, uint64_t File) : Device(Device), File(File) {}
142 
143  bool operator==(const UniqueID &Other) const {
144  return Device == Other.Device && File == Other.File;
145  }
146  bool operator!=(const UniqueID &Other) const { return !(*this == Other); }
147  bool operator<(const UniqueID &Other) const {
148  return std::tie(Device, File) < std::tie(Other.Device, Other.File);
149  }
150 
151  uint64_t getDevice() const { return Device; }
152  uint64_t getFile() const { return File; }
153 };
154 
155 /// Represents the result of a call to directory_iterator::status(). This is a
156 /// subset of the information returned by a regular sys::fs::status() call, and
157 /// represents the information provided by Windows FileFirstFile/FindNextFile.
159 protected:
160  #if defined(LLVM_ON_UNIX)
161  time_t fs_st_atime = 0;
162  time_t fs_st_mtime = 0;
163  uint32_t fs_st_atime_nsec = 0;
164  uint32_t fs_st_mtime_nsec = 0;
165  uid_t fs_st_uid = 0;
166  gid_t fs_st_gid = 0;
167  off_t fs_st_size = 0;
168  #elif defined (_WIN32)
169  uint32_t LastAccessedTimeHigh = 0;
170  uint32_t LastAccessedTimeLow = 0;
171  uint32_t LastWriteTimeHigh = 0;
172  uint32_t LastWriteTimeLow = 0;
173  uint32_t FileSizeHigh = 0;
174  uint32_t FileSizeLow = 0;
175  #endif
178 
179 public:
180  basic_file_status() = default;
181 
182  explicit basic_file_status(file_type Type) : Type(Type) {}
183 
184  #if defined(LLVM_ON_UNIX)
185  basic_file_status(file_type Type, perms Perms, time_t ATime,
186  uint32_t ATimeNSec, time_t MTime, uint32_t MTimeNSec,
187  uid_t UID, gid_t GID, off_t Size)
188  : fs_st_atime(ATime), fs_st_mtime(MTime),
189  fs_st_atime_nsec(ATimeNSec), fs_st_mtime_nsec(MTimeNSec),
190  fs_st_uid(UID), fs_st_gid(GID),
191  fs_st_size(Size), Type(Type), Perms(Perms) {}
192 #elif defined(_WIN32)
193  basic_file_status(file_type Type, perms Perms, uint32_t LastAccessTimeHigh,
194  uint32_t LastAccessTimeLow, uint32_t LastWriteTimeHigh,
195  uint32_t LastWriteTimeLow, uint32_t FileSizeHigh,
196  uint32_t FileSizeLow)
197  : LastAccessedTimeHigh(LastAccessTimeHigh),
198  LastAccessedTimeLow(LastAccessTimeLow),
199  LastWriteTimeHigh(LastWriteTimeHigh),
200  LastWriteTimeLow(LastWriteTimeLow), FileSizeHigh(FileSizeHigh),
201  FileSizeLow(FileSizeLow), Type(Type), Perms(Perms) {}
202  #endif
203 
204  // getters
205  file_type type() const { return Type; }
206  perms permissions() const { return Perms; }
207 
208  /// The file access time as reported from the underlying file system.
209  ///
210  /// Also see comments on \c getLastModificationTime() related to the precision
211  /// of the returned value.
212  TimePoint<> getLastAccessedTime() const;
213 
214  /// The file modification time as reported from the underlying file system.
215  ///
216  /// The returned value allows for nanosecond precision but the actual
217  /// resolution is an implementation detail of the underlying file system.
218  /// There is no guarantee for what kind of resolution you can expect, the
219  /// resolution can differ across platforms and even across mountpoints on the
220  /// same machine.
221  TimePoint<> getLastModificationTime() const;
222 
223  #if defined(LLVM_ON_UNIX)
224  uint32_t getUser() const { return fs_st_uid; }
225  uint32_t getGroup() const { return fs_st_gid; }
226  uint64_t getSize() const { return fs_st_size; }
227  #elif defined (_WIN32)
228  uint32_t getUser() const {
229  return 9999; // Not applicable to Windows, so...
230  }
231 
232  uint32_t getGroup() const {
233  return 9999; // Not applicable to Windows, so...
234  }
235 
236  uint64_t getSize() const {
237  return (uint64_t(FileSizeHigh) << 32) + FileSizeLow;
238  }
239  #endif
240 
241  // setters
242  void type(file_type v) { Type = v; }
243  void permissions(perms p) { Perms = p; }
244 };
245 
246 /// Represents the result of a call to sys::fs::status().
248  friend bool equivalent(file_status A, file_status B);
249 
250  #if defined(LLVM_ON_UNIX)
251  dev_t fs_st_dev = 0;
252  nlink_t fs_st_nlinks = 0;
253  ino_t fs_st_ino = 0;
254  #elif defined (_WIN32)
255  uint32_t NumLinks = 0;
256  uint32_t VolumeSerialNumber = 0;
257  uint32_t FileIndexHigh = 0;
258  uint32_t FileIndexLow = 0;
259  #endif
260 
261 public:
262  file_status() = default;
263 
265 
266  #if defined(LLVM_ON_UNIX)
267  file_status(file_type Type, perms Perms, dev_t Dev, nlink_t Links, ino_t Ino,
268  time_t ATime, uint32_t ATimeNSec,
269  time_t MTime, uint32_t MTimeNSec,
270  uid_t UID, gid_t GID, off_t Size)
271  : basic_file_status(Type, Perms, ATime, ATimeNSec, MTime, MTimeNSec,
272  UID, GID, Size),
273  fs_st_dev(Dev), fs_st_nlinks(Links), fs_st_ino(Ino) {}
274  #elif defined(_WIN32)
275  file_status(file_type Type, perms Perms, uint32_t LinkCount,
276  uint32_t LastAccessTimeHigh, uint32_t LastAccessTimeLow,
277  uint32_t LastWriteTimeHigh, uint32_t LastWriteTimeLow,
278  uint32_t VolumeSerialNumber, uint32_t FileSizeHigh,
279  uint32_t FileSizeLow, uint32_t FileIndexHigh,
280  uint32_t FileIndexLow)
281  : basic_file_status(Type, Perms, LastAccessTimeHigh, LastAccessTimeLow,
282  LastWriteTimeHigh, LastWriteTimeLow, FileSizeHigh,
283  FileSizeLow),
284  NumLinks(LinkCount), VolumeSerialNumber(VolumeSerialNumber),
285  FileIndexHigh(FileIndexHigh), FileIndexLow(FileIndexLow) {}
286  #endif
287 
288  UniqueID getUniqueID() const;
289  uint32_t getLinkCount() const;
290 };
291 
292 /// @}
293 /// @name Physical Operators
294 /// @{
295 
296 /// Make \a path an absolute path.
297 ///
298 /// Makes \a path absolute using the \a current_directory if it is not already.
299 /// An empty \a path will result in the \a current_directory.
300 ///
301 /// /absolute/path => /absolute/path
302 /// relative/../path => <current-directory>/relative/../path
303 ///
304 /// @param path A path that is modified to be an absolute path.
305 void make_absolute(const Twine &current_directory, SmallVectorImpl<char> &path);
306 
307 /// Make \a path an absolute path.
308 ///
309 /// Makes \a path absolute using the current directory if it is not already. An
310 /// empty \a path will result in the current directory.
311 ///
312 /// /absolute/path => /absolute/path
313 /// relative/../path => <current-directory>/relative/../path
314 ///
315 /// @param path A path that is modified to be an absolute path.
316 /// @returns errc::success if \a path has been made absolute, otherwise a
317 /// platform-specific error_code.
318 std::error_code make_absolute(SmallVectorImpl<char> &path);
319 
320 /// Create all the non-existent directories in path.
321 ///
322 /// @param path Directories to create.
323 /// @returns errc::success if is_directory(path), otherwise a platform
324 /// specific error_code. If IgnoreExisting is false, also returns
325 /// error if the directory already existed.
326 std::error_code create_directories(const Twine &path,
327  bool IgnoreExisting = true,
328  perms Perms = owner_all | group_all);
329 
330 /// Create the directory in path.
331 ///
332 /// @param path Directory to create.
333 /// @returns errc::success if is_directory(path), otherwise a platform
334 /// specific error_code. If IgnoreExisting is false, also returns
335 /// error if the directory already existed.
336 std::error_code create_directory(const Twine &path, bool IgnoreExisting = true,
337  perms Perms = owner_all | group_all);
338 
339 /// Create a link from \a from to \a to.
340 ///
341 /// The link may be a soft or a hard link, depending on the platform. The caller
342 /// may not assume which one. Currently on windows it creates a hard link since
343 /// soft links require extra privileges. On unix, it creates a soft link since
344 /// hard links don't work on SMB file systems.
345 ///
346 /// @param to The path to hard link to.
347 /// @param from The path to hard link from. This is created.
348 /// @returns errc::success if the link was created, otherwise a platform
349 /// specific error_code.
350 std::error_code create_link(const Twine &to, const Twine &from);
351 
352 /// Create a hard link from \a from to \a to, or return an error.
353 ///
354 /// @param to The path to hard link to.
355 /// @param from The path to hard link from. This is created.
356 /// @returns errc::success if the link was created, otherwise a platform
357 /// specific error_code.
358 std::error_code create_hard_link(const Twine &to, const Twine &from);
359 
360 /// Collapse all . and .. patterns, resolve all symlinks, and optionally
361 /// expand ~ expressions to the user's home directory.
362 ///
363 /// @param path The path to resolve.
364 /// @param output The location to store the resolved path.
365 /// @param expand_tilde If true, resolves ~ expressions to the user's home
366 /// directory.
367 std::error_code real_path(const Twine &path, SmallVectorImpl<char> &output,
368  bool expand_tilde = false);
369 
370 /// Expands ~ expressions to the user's home directory. On Unix ~user
371 /// directories are resolved as well.
372 ///
373 /// @param path The path to resolve.
374 void expand_tilde(const Twine &path, SmallVectorImpl<char> &output);
375 
376 /// Get the current path.
377 ///
378 /// @param result Holds the current path on return.
379 /// @returns errc::success if the current path has been stored in result,
380 /// otherwise a platform-specific error_code.
381 std::error_code current_path(SmallVectorImpl<char> &result);
382 
383 /// Set the current path.
384 ///
385 /// @param path The path to set.
386 /// @returns errc::success if the current path was successfully set,
387 /// otherwise a platform-specific error_code.
388 std::error_code set_current_path(const Twine &path);
389 
390 /// Remove path. Equivalent to POSIX remove().
391 ///
392 /// @param path Input path.
393 /// @returns errc::success if path has been removed or didn't exist, otherwise a
394 /// platform-specific error code. If IgnoreNonExisting is false, also
395 /// returns error if the file didn't exist.
396 std::error_code remove(const Twine &path, bool IgnoreNonExisting = true);
397 
398 /// Recursively delete a directory.
399 ///
400 /// @param path Input path.
401 /// @returns errc::success if path has been removed or didn't exist, otherwise a
402 /// platform-specific error code.
403 std::error_code remove_directories(const Twine &path, bool IgnoreErrors = true);
404 
405 /// Rename \a from to \a to.
406 ///
407 /// Files are renamed as if by POSIX rename(), except that on Windows there may
408 /// be a short interval of time during which the destination file does not
409 /// exist.
410 ///
411 /// @param from The path to rename from.
412 /// @param to The path to rename to. This is created.
413 std::error_code rename(const Twine &from, const Twine &to);
414 
415 /// Copy the contents of \a From to \a To.
416 ///
417 /// @param From The path to copy from.
418 /// @param To The path to copy to. This is created.
419 std::error_code copy_file(const Twine &From, const Twine &To);
420 
421 /// Copy the contents of \a From to \a To.
422 ///
423 /// @param From The path to copy from.
424 /// @param ToFD The open file descriptor of the destination file.
425 std::error_code copy_file(const Twine &From, int ToFD);
426 
427 /// Resize path to size. File is resized as if by POSIX truncate().
428 ///
429 /// @param FD Input file descriptor.
430 /// @param Size Size to resize to.
431 /// @returns errc::success if \a path has been resized to \a size, otherwise a
432 /// platform-specific error_code.
433 std::error_code resize_file(int FD, uint64_t Size);
434 
435 /// Compute an MD5 hash of a file's contents.
436 ///
437 /// @param FD Input file descriptor.
438 /// @returns An MD5Result with the hash computed, if successful, otherwise a
439 /// std::error_code.
441 
442 /// Version of compute_md5 that doesn't require an open file descriptor.
444 
445 /// @}
446 /// @name Physical Observers
447 /// @{
448 
449 /// Does file exist?
450 ///
451 /// @param status A basic_file_status previously returned from stat.
452 /// @returns True if the file represented by status exists, false if it does
453 /// not.
454 bool exists(const basic_file_status &status);
455 
456 enum class AccessMode { Exist, Write, Execute };
457 
458 /// Can the file be accessed?
459 ///
460 /// @param Path Input path.
461 /// @returns errc::success if the path can be accessed, otherwise a
462 /// platform-specific error_code.
463 std::error_code access(const Twine &Path, AccessMode Mode);
464 
465 /// Does file exist?
466 ///
467 /// @param Path Input path.
468 /// @returns True if it exists, false otherwise.
469 inline bool exists(const Twine &Path) {
470  return !access(Path, AccessMode::Exist);
471 }
472 
473 /// Can we execute this file?
474 ///
475 /// @param Path Input path.
476 /// @returns True if we can execute it, false otherwise.
477 bool can_execute(const Twine &Path);
478 
479 /// Can we write this file?
480 ///
481 /// @param Path Input path.
482 /// @returns True if we can write to it, false otherwise.
483 inline bool can_write(const Twine &Path) {
484  return !access(Path, AccessMode::Write);
485 }
486 
487 /// Do file_status's represent the same thing?
488 ///
489 /// @param A Input file_status.
490 /// @param B Input file_status.
491 ///
492 /// assert(status_known(A) || status_known(B));
493 ///
494 /// @returns True if A and B both represent the same file system entity, false
495 /// otherwise.
497 
498 /// Do paths represent the same thing?
499 ///
500 /// assert(status_known(A) || status_known(B));
501 ///
502 /// @param A Input path A.
503 /// @param B Input path B.
504 /// @param result Set to true if stat(A) and stat(B) have the same device and
505 /// inode (or equivalent).
506 /// @returns errc::success if result has been successfully set, otherwise a
507 /// platform-specific error_code.
508 std::error_code equivalent(const Twine &A, const Twine &B, bool &result);
509 
510 /// Simpler version of equivalent for clients that don't need to
511 /// differentiate between an error and false.
512 inline bool equivalent(const Twine &A, const Twine &B) {
513  bool result;
514  return !equivalent(A, B, result) && result;
515 }
516 
517 /// Is the file mounted on a local filesystem?
518 ///
519 /// @param path Input path.
520 /// @param result Set to true if \a path is on fixed media such as a hard disk,
521 /// false if it is not.
522 /// @returns errc::success if result has been successfully set, otherwise a
523 /// platform specific error_code.
524 std::error_code is_local(const Twine &path, bool &result);
525 
526 /// Version of is_local accepting an open file descriptor.
527 std::error_code is_local(int FD, bool &result);
528 
529 /// Simpler version of is_local for clients that don't need to
530 /// differentiate between an error and false.
531 inline bool is_local(const Twine &Path) {
532  bool Result;
533  return !is_local(Path, Result) && Result;
534 }
535 
536 /// Simpler version of is_local accepting an open file descriptor for
537 /// clients that don't need to differentiate between an error and false.
538 inline bool is_local(int FD) {
539  bool Result;
540  return !is_local(FD, Result) && Result;
541 }
542 
543 /// Does status represent a directory?
544 ///
545 /// @param Path The path to get the type of.
546 /// @param Follow For symbolic links, indicates whether to return the file type
547 /// of the link itself, or of the target.
548 /// @returns A value from the file_type enumeration indicating the type of file.
549 file_type get_file_type(const Twine &Path, bool Follow = true);
550 
551 /// Does status represent a directory?
552 ///
553 /// @param status A basic_file_status previously returned from status.
554 /// @returns status.type() == file_type::directory_file.
555 bool is_directory(const basic_file_status &status);
556 
557 /// Is path a directory?
558 ///
559 /// @param path Input path.
560 /// @param result Set to true if \a path is a directory (after following
561 /// symlinks, false if it is not. Undefined otherwise.
562 /// @returns errc::success if result has been successfully set, otherwise a
563 /// platform-specific error_code.
564 std::error_code is_directory(const Twine &path, bool &result);
565 
566 /// Simpler version of is_directory for clients that don't need to
567 /// differentiate between an error and false.
568 inline bool is_directory(const Twine &Path) {
569  bool Result;
570  return !is_directory(Path, Result) && Result;
571 }
572 
573 /// Does status represent a regular file?
574 ///
575 /// @param status A basic_file_status previously returned from status.
576 /// @returns status_known(status) && status.type() == file_type::regular_file.
577 bool is_regular_file(const basic_file_status &status);
578 
579 /// Is path a regular file?
580 ///
581 /// @param path Input path.
582 /// @param result Set to true if \a path is a regular file (after following
583 /// symlinks), false if it is not. Undefined otherwise.
584 /// @returns errc::success if result has been successfully set, otherwise a
585 /// platform-specific error_code.
586 std::error_code is_regular_file(const Twine &path, bool &result);
587 
588 /// Simpler version of is_regular_file for clients that don't need to
589 /// differentiate between an error and false.
590 inline bool is_regular_file(const Twine &Path) {
591  bool Result;
592  if (is_regular_file(Path, Result))
593  return false;
594  return Result;
595 }
596 
597 /// Does status represent a symlink file?
598 ///
599 /// @param status A basic_file_status previously returned from status.
600 /// @returns status_known(status) && status.type() == file_type::symlink_file.
601 bool is_symlink_file(const basic_file_status &status);
602 
603 /// Is path a symlink file?
604 ///
605 /// @param path Input path.
606 /// @param result Set to true if \a path is a symlink file, false if it is not.
607 /// Undefined otherwise.
608 /// @returns errc::success if result has been successfully set, otherwise a
609 /// platform-specific error_code.
610 std::error_code is_symlink_file(const Twine &path, bool &result);
611 
612 /// Simpler version of is_symlink_file for clients that don't need to
613 /// differentiate between an error and false.
614 inline bool is_symlink_file(const Twine &Path) {
615  bool Result;
616  if (is_symlink_file(Path, Result))
617  return false;
618  return Result;
619 }
620 
621 /// Does this status represent something that exists but is not a
622 /// directory or regular file?
623 ///
624 /// @param status A basic_file_status previously returned from status.
625 /// @returns exists(s) && !is_regular_file(s) && !is_directory(s)
626 bool is_other(const basic_file_status &status);
627 
628 /// Is path something that exists but is not a directory,
629 /// regular file, or symlink?
630 ///
631 /// @param path Input path.
632 /// @param result Set to true if \a path exists, but is not a directory, regular
633 /// file, or a symlink, false if it does not. Undefined otherwise.
634 /// @returns errc::success if result has been successfully set, otherwise a
635 /// platform-specific error_code.
636 std::error_code is_other(const Twine &path, bool &result);
637 
638 /// Get file status as if by POSIX stat().
639 ///
640 /// @param path Input path.
641 /// @param result Set to the file status.
642 /// @param follow When true, follows symlinks. Otherwise, the symlink itself is
643 /// statted.
644 /// @returns errc::success if result has been successfully set, otherwise a
645 /// platform-specific error_code.
646 std::error_code status(const Twine &path, file_status &result,
647  bool follow = true);
648 
649 /// A version for when a file descriptor is already available.
650 std::error_code status(int FD, file_status &Result);
651 
652 /// Set file permissions.
653 ///
654 /// @param Path File to set permissions on.
655 /// @param Permissions New file permissions.
656 /// @returns errc::success if the permissions were successfully set, otherwise
657 /// a platform-specific error_code.
658 /// @note On Windows, all permissions except *_write are ignored. Using any of
659 /// owner_write, group_write, or all_write will make the file writable.
660 /// Otherwise, the file will be marked as read-only.
661 std::error_code setPermissions(const Twine &Path, perms Permissions);
662 
663 /// Get file permissions.
664 ///
665 /// @param Path File to get permissions from.
666 /// @returns the permissions if they were successfully retrieved, otherwise a
667 /// platform-specific error_code.
668 /// @note On Windows, if the file does not have the FILE_ATTRIBUTE_READONLY
669 /// attribute, all_all will be returned. Otherwise, all_read | all_exe
670 /// will be returned.
671 ErrorOr<perms> getPermissions(const Twine &Path);
672 
673 /// Get file size.
674 ///
675 /// @param Path Input path.
676 /// @param Result Set to the size of the file in \a Path.
677 /// @returns errc::success if result has been successfully set, otherwise a
678 /// platform-specific error_code.
679 inline std::error_code file_size(const Twine &Path, uint64_t &Result) {
681  std::error_code EC = status(Path, Status);
682  if (EC)
683  return EC;
684  Result = Status.getSize();
685  return std::error_code();
686 }
687 
688 /// Set the file modification and access time.
689 ///
690 /// @returns errc::success if the file times were successfully set, otherwise a
691 /// platform-specific error_code or errc::function_not_supported on
692 /// platforms where the functionality isn't available.
693 std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
694  TimePoint<> ModificationTime);
695 
696 /// Simpler version that sets both file modification and access time to the same
697 /// time.
698 inline std::error_code setLastAccessAndModificationTime(int FD,
699  TimePoint<> Time) {
700  return setLastAccessAndModificationTime(FD, Time, Time);
701 }
702 
703 /// Is status available?
704 ///
705 /// @param s Input file status.
706 /// @returns True if status() != status_error.
707 bool status_known(const basic_file_status &s);
708 
709 /// Is status available?
710 ///
711 /// @param path Input path.
712 /// @param result Set to true if status() != status_error.
713 /// @returns errc::success if result has been successfully set, otherwise a
714 /// platform-specific error_code.
715 std::error_code status_known(const Twine &path, bool &result);
716 
717 enum CreationDisposition : unsigned {
718  /// CD_CreateAlways - When opening a file:
719  /// * If it already exists, truncate it.
720  /// * If it does not already exist, create a new file.
722 
723  /// CD_CreateNew - When opening a file:
724  /// * If it already exists, fail.
725  /// * If it does not already exist, create a new file.
727 
728  /// CD_OpenExisting - When opening a file:
729  /// * If it already exists, open the file with the offset set to 0.
730  /// * If it does not already exist, fail.
732 
733  /// CD_OpenAlways - When opening a file:
734  /// * If it already exists, open the file with the offset set to 0.
735  /// * If it does not already exist, create a new file.
737 };
738 
739 enum FileAccess : unsigned {
740  FA_Read = 1,
741  FA_Write = 2,
742 };
743 
744 enum OpenFlags : unsigned {
745  OF_None = 0,
746  F_None = 0, // For compatibility
747 
748  /// The file should be opened in text mode on platforms that make this
749  /// distinction.
750  OF_Text = 1,
751  F_Text = 1, // For compatibility
752 
753  /// The file should be opened in append mode.
755  F_Append = 2, // For compatibility
756 
757  /// Delete the file on close. Only makes a difference on windows.
759 
760  /// When a child process is launched, this file should remain open in the
761  /// child process.
763 
764  /// Force files Atime to be updated on access. Only makes a difference on windows.
766 };
767 
768 /// Create a uniquely named file.
769 ///
770 /// Generates a unique path suitable for a temporary file and then opens it as a
771 /// file. The name is based on \a model with '%' replaced by a random char in
772 /// [0-9a-f]. If \a model is not an absolute path, the temporary file will be
773 /// created in the current directory.
774 ///
775 /// Example: clang-%%-%%-%%-%%-%%.s => clang-a0-b1-c2-d3-e4.s
776 ///
777 /// This is an atomic operation. Either the file is created and opened, or the
778 /// file system is left untouched.
779 ///
780 /// The intended use is for files that are to be kept, possibly after
781 /// renaming them. For example, when running 'clang -c foo.o', the file can
782 /// be first created as foo-abc123.o and then renamed.
783 ///
784 /// @param Model Name to base unique path off of.
785 /// @param ResultFD Set to the opened file's file descriptor.
786 /// @param ResultPath Set to the opened file's absolute path.
787 /// @returns errc::success if Result{FD,Path} have been successfully set,
788 /// otherwise a platform-specific error_code.
789 std::error_code createUniqueFile(const Twine &Model, int &ResultFD,
790  SmallVectorImpl<char> &ResultPath,
791  unsigned Mode = all_read | all_write);
792 
793 /// Simpler version for clients that don't want an open file. An empty
794 /// file will still be created.
795 std::error_code createUniqueFile(const Twine &Model,
796  SmallVectorImpl<char> &ResultPath,
797  unsigned Mode = all_read | all_write);
798 
799 /// Represents a temporary file.
800 ///
801 /// The temporary file must be eventually discarded or given a final name and
802 /// kept.
803 ///
804 /// The destructor doesn't implicitly discard because there is no way to
805 /// properly handle errors in a destructor.
806 class TempFile {
807  bool Done = false;
808  TempFile(StringRef Name, int FD);
809 
810 public:
811  /// This creates a temporary file with createUniqueFile and schedules it for
812  /// deletion with sys::RemoveFileOnSignal.
813  static Expected<TempFile> create(const Twine &Model,
814  unsigned Mode = all_read | all_write);
816  TempFile &operator=(TempFile &&Other);
817 
818  // Name of the temporary file.
819  std::string TmpName;
820 
821  // The open file descriptor.
822  int FD = -1;
823 
824  // Keep this with the given name.
825  Error keep(const Twine &Name);
826 
827  // Keep this with the temporary name.
828  Error keep();
829 
830  // Delete the file.
831  Error discard();
832 
833  // This checks that keep or delete was called.
834  ~TempFile();
835 };
836 
837 /// Create a file in the system temporary directory.
838 ///
839 /// The filename is of the form prefix-random_chars.suffix. Since the directory
840 /// is not know to the caller, Prefix and Suffix cannot have path separators.
841 /// The files are created with mode 0600.
842 ///
843 /// This should be used for things like a temporary .s that is removed after
844 /// running the assembler.
845 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
846  int &ResultFD,
847  SmallVectorImpl<char> &ResultPath);
848 
849 /// Simpler version for clients that don't want an open file. An empty
850 /// file will still be created.
851 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
852  SmallVectorImpl<char> &ResultPath);
853 
854 std::error_code createUniqueDirectory(const Twine &Prefix,
855  SmallVectorImpl<char> &ResultPath);
856 
857 /// Get a unique name, not currently exisiting in the filesystem. Subject
858 /// to race conditions, prefer to use createUniqueFile instead.
859 ///
860 /// Similar to createUniqueFile, but instead of creating a file only
861 /// checks if it exists. This function is subject to race conditions, if you
862 /// want to use the returned name to actually create a file, use
863 /// createUniqueFile instead.
864 std::error_code getPotentiallyUniqueFileName(const Twine &Model,
865  SmallVectorImpl<char> &ResultPath);
866 
867 /// Get a unique temporary file name, not currently exisiting in the
868 /// filesystem. Subject to race conditions, prefer to use createTemporaryFile
869 /// instead.
870 ///
871 /// Similar to createTemporaryFile, but instead of creating a file only
872 /// checks if it exists. This function is subject to race conditions, if you
873 /// want to use the returned name to actually create a file, use
874 /// createTemporaryFile instead.
875 std::error_code
877  SmallVectorImpl<char> &ResultPath);
878 
880  return OpenFlags(unsigned(A) | unsigned(B));
881 }
882 
884  A = A | B;
885  return A;
886 }
887 
889  return FileAccess(unsigned(A) | unsigned(B));
890 }
891 
893  A = A | B;
894  return A;
895 }
896 
897 /// @brief Opens a file with the specified creation disposition, access mode,
898 /// and flags and returns a file descriptor.
899 ///
900 /// The caller is responsible for closing the file descriptor once they are
901 /// finished with it.
902 ///
903 /// @param Name The path of the file to open, relative or absolute.
904 /// @param ResultFD If the file could be opened successfully, its descriptor
905 /// is stored in this location. Otherwise, this is set to -1.
906 /// @param Disp Value specifying the existing-file behavior.
907 /// @param Access Value specifying whether to open the file in read, write, or
908 /// read-write mode.
909 /// @param Flags Additional flags.
910 /// @param Mode The access permissions of the file, represented in octal.
911 /// @returns errc::success if \a Name has been opened, otherwise a
912 /// platform-specific error_code.
913 std::error_code openFile(const Twine &Name, int &ResultFD,
914  CreationDisposition Disp, FileAccess Access,
915  OpenFlags Flags, unsigned Mode = 0666);
916 
917 /// @brief Opens a file with the specified creation disposition, access mode,
918 /// and flags and returns a platform-specific file object.
919 ///
920 /// The caller is responsible for closing the file object once they are
921 /// finished with it.
922 ///
923 /// @param Name The path of the file to open, relative or absolute.
924 /// @param Disp Value specifying the existing-file behavior.
925 /// @param Access Value specifying whether to open the file in read, write, or
926 /// read-write mode.
927 /// @param Flags Additional flags.
928 /// @param Mode The access permissions of the file, represented in octal.
929 /// @returns errc::success if \a Name has been opened, otherwise a
930 /// platform-specific error_code.
932  FileAccess Access, OpenFlags Flags,
933  unsigned Mode = 0666);
934 
935 /// @brief Opens the file with the given name in a write-only or read-write
936 /// mode, returning its open file descriptor. If the file does not exist, it
937 /// is created.
938 ///
939 /// The caller is responsible for closing the file descriptor once they are
940 /// finished with it.
941 ///
942 /// @param Name The path of the file to open, relative or absolute.
943 /// @param ResultFD If the file could be opened successfully, its descriptor
944 /// is stored in this location. Otherwise, this is set to -1.
945 /// @param Flags Additional flags used to determine whether the file should be
946 /// opened in, for example, read-write or in write-only mode.
947 /// @param Mode The access permissions of the file, represented in octal.
948 /// @returns errc::success if \a Name has been opened, otherwise a
949 /// platform-specific error_code.
950 inline std::error_code
951 openFileForWrite(const Twine &Name, int &ResultFD,
953  OpenFlags Flags = OF_None, unsigned Mode = 0666) {
954  return openFile(Name, ResultFD, Disp, FA_Write, Flags, Mode);
955 }
956 
957 /// @brief Opens the file with the given name in a write-only or read-write
958 /// mode, returning its open file descriptor. If the file does not exist, it
959 /// is created.
960 ///
961 /// The caller is responsible for closing the freeing the file once they are
962 /// finished with it.
963 ///
964 /// @param Name The path of the file to open, relative or absolute.
965 /// @param Flags Additional flags used to determine whether the file should be
966 /// opened in, for example, read-write or in write-only mode.
967 /// @param Mode The access permissions of the file, represented in octal.
968 /// @returns a platform-specific file descriptor if \a Name has been opened,
969 /// otherwise an error object.
971  CreationDisposition Disp,
972  OpenFlags Flags,
973  unsigned Mode = 0666) {
974  return openNativeFile(Name, Disp, FA_Write, Flags, Mode);
975 }
976 
977 /// @brief Opens the file with the given name in a write-only or read-write
978 /// mode, returning its open file descriptor. If the file does not exist, it
979 /// is created.
980 ///
981 /// The caller is responsible for closing the file descriptor once they are
982 /// finished with it.
983 ///
984 /// @param Name The path of the file to open, relative or absolute.
985 /// @param ResultFD If the file could be opened successfully, its descriptor
986 /// is stored in this location. Otherwise, this is set to -1.
987 /// @param Flags Additional flags used to determine whether the file should be
988 /// opened in, for example, read-write or in write-only mode.
989 /// @param Mode The access permissions of the file, represented in octal.
990 /// @returns errc::success if \a Name has been opened, otherwise a
991 /// platform-specific error_code.
992 inline std::error_code openFileForReadWrite(const Twine &Name, int &ResultFD,
993  CreationDisposition Disp,
994  OpenFlags Flags,
995  unsigned Mode = 0666) {
996  return openFile(Name, ResultFD, Disp, FA_Write | FA_Read, Flags, Mode);
997 }
998 
999 /// @brief Opens the file with the given name in a write-only or read-write
1000 /// mode, returning its open file descriptor. If the file does not exist, it
1001 /// is created.
1002 ///
1003 /// The caller is responsible for closing the freeing the file once they are
1004 /// finished with it.
1005 ///
1006 /// @param Name The path of the file to open, relative or absolute.
1007 /// @param Flags Additional flags used to determine whether the file should be
1008 /// opened in, for example, read-write or in write-only mode.
1009 /// @param Mode The access permissions of the file, represented in octal.
1010 /// @returns a platform-specific file descriptor if \a Name has been opened,
1011 /// otherwise an error object.
1013  CreationDisposition Disp,
1014  OpenFlags Flags,
1015  unsigned Mode = 0666) {
1016  return openNativeFile(Name, Disp, FA_Write | FA_Read, Flags, Mode);
1017 }
1018 
1019 /// @brief Opens the file with the given name in a read-only mode, returning
1020 /// its open file descriptor.
1021 ///
1022 /// The caller is responsible for closing the file descriptor once they are
1023 /// finished with it.
1024 ///
1025 /// @param Name The path of the file to open, relative or absolute.
1026 /// @param ResultFD If the file could be opened successfully, its descriptor
1027 /// is stored in this location. Otherwise, this is set to -1.
1028 /// @param RealPath If nonnull, extra work is done to determine the real path
1029 /// of the opened file, and that path is stored in this
1030 /// location.
1031 /// @returns errc::success if \a Name has been opened, otherwise a
1032 /// platform-specific error_code.
1033 std::error_code openFileForRead(const Twine &Name, int &ResultFD,
1034  OpenFlags Flags = OF_None,
1035  SmallVectorImpl<char> *RealPath = nullptr);
1036 
1037 /// @brief Opens the file with the given name in a read-only mode, returning
1038 /// its open file descriptor.
1039 ///
1040 /// The caller is responsible for closing the freeing the file once they are
1041 /// finished with it.
1042 ///
1043 /// @param Name The path of the file to open, relative or absolute.
1044 /// @param RealPath If nonnull, extra work is done to determine the real path
1045 /// of the opened file, and that path is stored in this
1046 /// location.
1047 /// @returns a platform-specific file descriptor if \a Name has been opened,
1048 /// otherwise an error object.
1050 openNativeFileForRead(const Twine &Name, OpenFlags Flags = OF_None,
1051  SmallVectorImpl<char> *RealPath = nullptr);
1052 
1053 /// @brief Close the file object. This should be used instead of ::close for
1054 /// portability.
1055 ///
1056 /// @param F On input, this is the file to close. On output, the file is
1057 /// set to kInvalidFile.
1058 void closeFile(file_t &F);
1059 
1060 std::error_code getUniqueID(const Twine Path, UniqueID &Result);
1061 
1062 /// Get disk space usage information.
1063 ///
1064 /// Note: Users must be careful about "Time Of Check, Time Of Use" kind of bug.
1065 /// Note: Windows reports results according to the quota allocated to the user.
1066 ///
1067 /// @param Path Input path.
1068 /// @returns a space_info structure filled with the capacity, free, and
1069 /// available space on the device \a Path is on. A platform specific error_code
1070 /// is returned on error.
1071 ErrorOr<space_info> disk_space(const Twine &Path);
1072 
1073 /// This class represents a memory mapped file. It is based on
1074 /// boost::iostreams::mapped_file.
1076 public:
1077  enum mapmode {
1078  readonly, ///< May only access map via const_data as read only.
1079  readwrite, ///< May access map via data and modify it. Written to path.
1080  priv ///< May modify via data, but changes are lost on destruction.
1081  };
1082 
1083 private:
1084  /// Platform-specific mapping state.
1085  size_t Size;
1086  void *Mapping;
1087 #ifdef _WIN32
1088  void *FileHandle;
1089 #endif
1090  mapmode Mode;
1091 
1092  std::error_code init(int FD, uint64_t Offset, mapmode Mode);
1093 
1094 public:
1095  mapped_file_region() = delete;
1097  mapped_file_region &operator =(mapped_file_region&) = delete;
1098 
1099  /// \param fd An open file descriptor to map. mapped_file_region takes
1100  /// ownership if closefd is true. It must have been opended in the correct
1101  /// mode.
1102  mapped_file_region(int fd, mapmode mode, size_t length, uint64_t offset,
1103  std::error_code &ec);
1104 
1105  ~mapped_file_region();
1106 
1107  size_t size() const;
1108  char *data() const;
1109 
1110  /// Get a const view of the data. Modifying this memory has undefined
1111  /// behavior.
1112  const char *const_data() const;
1113 
1114  /// \returns The minimum alignment offset must be.
1115  static int alignment();
1116 };
1117 
1118 /// Return the path to the main executable, given the value of argv[0] from
1119 /// program startup and the address of main itself. In extremis, this function
1120 /// may fail and return an empty path.
1121 std::string getMainExecutable(const char *argv0, void *MainExecAddr);
1122 
1123 /// @}
1124 /// @name Iterators
1125 /// @{
1126 
1127 /// directory_entry - A single entry in a directory.
1129  // FIXME: different platforms make different information available "for free"
1130  // when traversing a directory. The design of this class wraps most of the
1131  // information in basic_file_status, so on platforms where we can't populate
1132  // that whole structure, callers end up paying for a stat().
1133  // std::filesystem::directory_entry may be a better model.
1134  std::string Path;
1135  file_type Type; // Most platforms can provide this.
1136  bool FollowSymlinks; // Affects the behavior of status().
1137  basic_file_status Status; // If available.
1138 
1139 public:
1140  explicit directory_entry(const Twine &Path, bool FollowSymlinks = true,
1143  : Path(Path.str()), Type(Type), FollowSymlinks(FollowSymlinks),
1144  Status(Status) {}
1145 
1146  directory_entry() = default;
1147 
1148  void replace_filename(const Twine &Filename, file_type Type,
1150 
1151  const std::string &path() const { return Path; }
1152  // Get basic information about entry file (a subset of fs::status()).
1153  // On most platforms this is a stat() call.
1154  // On windows the information was already retrieved from the directory.
1156  // Get the type of this file.
1157  // On most platforms (Linux/Mac/Windows/BSD), this was already retrieved.
1158  // On some platforms (e.g. Solaris) this is a stat() call.
1159  file_type type() const {
1160  if (Type != file_type::type_unknown)
1161  return Type;
1162  auto S = status();
1163  return S ? S->type() : file_type::type_unknown;
1164  }
1165 
1166  bool operator==(const directory_entry& RHS) const { return Path == RHS.Path; }
1167  bool operator!=(const directory_entry& RHS) const { return !(*this == RHS); }
1168  bool operator< (const directory_entry& RHS) const;
1169  bool operator<=(const directory_entry& RHS) const;
1170  bool operator> (const directory_entry& RHS) const;
1171  bool operator>=(const directory_entry& RHS) const;
1172 };
1173 
1174 namespace detail {
1175 
1176  struct DirIterState;
1177 
1178  std::error_code directory_iterator_construct(DirIterState &, StringRef, bool);
1179  std::error_code directory_iterator_increment(DirIterState &);
1180  std::error_code directory_iterator_destruct(DirIterState &);
1181 
1182  /// Keeps state for the directory_iterator.
1183  struct DirIterState {
1186  }
1187 
1188  intptr_t IterationHandle = 0;
1190  };
1191 
1192 } // end namespace detail
1193 
1194 /// directory_iterator - Iterates through the entries in path. There is no
1195 /// operator++ because we need an error_code. If it's really needed we can make
1196 /// it call report_fatal_error on error.
1198  std::shared_ptr<detail::DirIterState> State;
1199  bool FollowSymlinks = true;
1200 
1201 public:
1202  explicit directory_iterator(const Twine &path, std::error_code &ec,
1203  bool follow_symlinks = true)
1204  : FollowSymlinks(follow_symlinks) {
1205  State = std::make_shared<detail::DirIterState>();
1206  SmallString<128> path_storage;
1208  *State, path.toStringRef(path_storage), FollowSymlinks);
1209  }
1210 
1211  explicit directory_iterator(const directory_entry &de, std::error_code &ec,
1212  bool follow_symlinks = true)
1213  : FollowSymlinks(follow_symlinks) {
1214  State = std::make_shared<detail::DirIterState>();
1216  *State, de.path(), FollowSymlinks);
1217  }
1218 
1219  /// Construct end iterator.
1220  directory_iterator() = default;
1221 
1222  // No operator++ because we need error_code.
1223  directory_iterator &increment(std::error_code &ec) {
1224  ec = directory_iterator_increment(*State);
1225  return *this;
1226  }
1227 
1228  const directory_entry &operator*() const { return State->CurrentEntry; }
1229  const directory_entry *operator->() const { return &State->CurrentEntry; }
1230 
1231  bool operator==(const directory_iterator &RHS) const {
1232  if (State == RHS.State)
1233  return true;
1234  if (!RHS.State)
1235  return State->CurrentEntry == directory_entry();
1236  if (!State)
1237  return RHS.State->CurrentEntry == directory_entry();
1238  return State->CurrentEntry == RHS.State->CurrentEntry;
1239  }
1240 
1241  bool operator!=(const directory_iterator &RHS) const {
1242  return !(*this == RHS);
1243  }
1244 };
1245 
1246 namespace detail {
1247 
1248  /// Keeps state for the recursive_directory_iterator.
1250  std::stack<directory_iterator, std::vector<directory_iterator>> Stack;
1251  uint16_t Level = 0;
1252  bool HasNoPushRequest = false;
1253  };
1254 
1255 } // end namespace detail
1256 
1257 /// recursive_directory_iterator - Same as directory_iterator except for it
1258 /// recurses down into child directories.
1260  std::shared_ptr<detail::RecDirIterState> State;
1261  bool Follow;
1262 
1263 public:
1264  recursive_directory_iterator() = default;
1265  explicit recursive_directory_iterator(const Twine &path, std::error_code &ec,
1266  bool follow_symlinks = true)
1267  : State(std::make_shared<detail::RecDirIterState>()),
1268  Follow(follow_symlinks) {
1269  State->Stack.push(directory_iterator(path, ec, Follow));
1270  if (State->Stack.top() == directory_iterator())
1271  State.reset();
1272  }
1273 
1274  // No operator++ because we need error_code.
1275  recursive_directory_iterator &increment(std::error_code &ec) {
1276  const directory_iterator end_itr = {};
1277 
1278  if (State->HasNoPushRequest)
1279  State->HasNoPushRequest = false;
1280  else {
1281  file_type type = State->Stack.top()->type();
1282  if (type == file_type::symlink_file && Follow) {
1283  // Resolve the symlink: is it a directory to recurse into?
1284  ErrorOr<basic_file_status> status = State->Stack.top()->status();
1285  if (status)
1286  type = status->type();
1287  // Otherwise broken symlink, and we'll continue.
1288  }
1289  if (type == file_type::directory_file) {
1290  State->Stack.push(directory_iterator(*State->Stack.top(), ec, Follow));
1291  if (State->Stack.top() != end_itr) {
1292  ++State->Level;
1293  return *this;
1294  }
1295  State->Stack.pop();
1296  }
1297  }
1298 
1299  while (!State->Stack.empty()
1300  && State->Stack.top().increment(ec) == end_itr) {
1301  State->Stack.pop();
1302  --State->Level;
1303  }
1304 
1305  // Check if we are done. If so, create an end iterator.
1306  if (State->Stack.empty())
1307  State.reset();
1308 
1309  return *this;
1310  }
1311 
1312  const directory_entry &operator*() const { return *State->Stack.top(); }
1313  const directory_entry *operator->() const { return &*State->Stack.top(); }
1314 
1315  // observers
1316  /// Gets the current level. Starting path is at level 0.
1317  int level() const { return State->Level; }
1318 
1319  /// Returns true if no_push has been called for this directory_entry.
1320  bool no_push_request() const { return State->HasNoPushRequest; }
1321 
1322  // modifiers
1323  /// Goes up one level if Level > 0.
1324  void pop() {
1325  assert(State && "Cannot pop an end iterator!");
1326  assert(State->Level > 0 && "Cannot pop an iterator with level < 1");
1327 
1328  const directory_iterator end_itr = {};
1329  std::error_code ec;
1330  do {
1331  if (ec)
1332  report_fatal_error("Error incrementing directory iterator.");
1333  State->Stack.pop();
1334  --State->Level;
1335  } while (!State->Stack.empty()
1336  && State->Stack.top().increment(ec) == end_itr);
1337 
1338  // Check if we are done. If so, create an end iterator.
1339  if (State->Stack.empty())
1340  State.reset();
1341  }
1342 
1343  /// Does not go down into the current directory_entry.
1344  void no_push() { State->HasNoPushRequest = true; }
1345 
1346  bool operator==(const recursive_directory_iterator &RHS) const {
1347  return State == RHS.State;
1348  }
1349 
1350  bool operator!=(const recursive_directory_iterator &RHS) const {
1351  return !(*this == RHS);
1352  }
1353 };
1354 
1355 /// @}
1356 
1357 } // end namespace fs
1358 } // end namespace sys
1359 } // end namespace llvm
1360 
1361 #endif // LLVM_SUPPORT_FILESYSTEM_H
const file_t kInvalidFile
const directory_entry & operator*() const
Definition: FileSystem.h:1228
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:914
bool can_execute(const Twine &Path)
Can we execute this file?
std::error_code openFileForReadWrite(const Twine &Name, int &ResultFD, CreationDisposition Disp, OpenFlags Flags, unsigned Mode=0666)
Opens the file with the given name in a write-only or read-write mode, returning its open file descri...
Definition: FileSystem.h:992
Represents either an error or a value T.
Definition: ErrorOr.h:57
space_info - Self explanatory.
Definition: FileSystem.h:81
Expected< file_t > openNativeFileForWrite(const Twine &Name, CreationDisposition Disp, OpenFlags Flags, unsigned Mode=0666)
Opens the file with the given name in a write-only or read-write mode, returning its open file descri...
Definition: FileSystem.h:970
SI Whole Quad Mode
bool status_known(const basic_file_status &s)
Is status available?
Definition: Path.cpp:1026
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:140
This class represents lattice values for constants.
Definition: AllocatorList.h:24
bool operator<(const UniqueID &Other) const
Definition: FileSystem.h:147
std::error_code openFileForRead(const Twine &Name, int &ResultFD, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
void closeFile(file_t &F)
Close the file object.
file_type type() const
Definition: FileSystem.h:1159
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:766
std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime, TimePoint<> ModificationTime)
Set the file modification and access time.
bool operator>(int64_t V1, const APSInt &V2)
Definition: APSInt.h:327
file_status(file_type Type, perms Perms, dev_t Dev, nlink_t Links, ino_t Ino, time_t ATime, uint32_t ATimeNSec, time_t MTime, uint32_t MTimeNSec, uid_t UID, gid_t GID, off_t Size)
Definition: FileSystem.h:267
recursive_directory_iterator(const Twine &path, std::error_code &ec, bool follow_symlinks=true)
Definition: FileSystem.h:1265
StringRef toStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single StringRef if it can be represented as such.
Definition: Twine.h:453
void pop()
Goes up one level if Level > 0.
Definition: FileSystem.h:1324
This class represents a memory mapped file.
Definition: FileSystem.h:1075
std::error_code current_path(SmallVectorImpl< char > &result)
Get the current path.
bool is_directory(const basic_file_status &status)
Does status represent a directory?
Definition: Path.cpp:1037
Expected< file_t > openNativeFile(const Twine &Name, CreationDisposition Disp, FileAccess Access, OpenFlags Flags, unsigned Mode=0666)
Opens a file with the specified creation disposition, access mode, and flags and returns a platform-s...
F(f)
bool is_regular_file(const basic_file_status &status)
Does status represent a regular file?
Definition: Path.cpp:1049
perms operator~(perms x)
Definition: FileSystem.h:129
directory_iterator & increment(std::error_code &ec)
Definition: FileSystem.h:1223
recursive_directory_iterator - Same as directory_iterator except for it recurses down into child dire...
Definition: FileSystem.h:1259
std::error_code remove_directories(const Twine &path, bool IgnoreErrors=true)
Recursively delete a directory.
Represents the result of a call to sys::fs::status().
Definition: FileSystem.h:247
CD_OpenExisting - When opening a file:
Definition: FileSystem.h:731
ErrorOr< MD5::MD5Result > md5_contents(int FD)
Compute an MD5 hash of a file&#39;s contents.
Definition: Path.cpp:992
bool operator<=(int64_t V1, const APSInt &V2)
Definition: APSInt.h:324
amode Optimize addressing mode
ErrorOr< perms > getPermissions(const Twine &Path)
Get file permissions.
Definition: Path.cpp:1096
std::error_code directory_iterator_increment(DirIterState &)
amdgpu Simplify well known AMD library false Value Value const Twine & Name
Definition: BitVector.h:938
perms operator &(perms l, perms r)
Definition: FileSystem.h:117
perms & operator &=(perms &l, perms r)
Definition: FileSystem.h:125
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
bool operator>=(int64_t V1, const APSInt &V2)
Definition: APSInt.h:325
Keeps state for the directory_iterator.
Definition: FileSystem.h:1183
directory_iterator(const Twine &path, std::error_code &ec, bool follow_symlinks=true)
Definition: FileSystem.h:1202
bool operator<(uint32_t Value, UnicodeCharRange Range)
Represents a temporary file.
Definition: FileSystem.h:806
void make_absolute(const Twine &current_directory, SmallVectorImpl< char > &path)
Make path an absolute path.
Definition: Path.cpp:852
std::error_code file_size(const Twine &Path, uint64_t &Result)
Get file size.
Definition: FileSystem.h:679
const directory_entry & operator*() const
Definition: FileSystem.h:1312
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
May access map via data and modify it. Written to path.
Definition: FileSystem.h:1079
ELFYAML::ELF_STO Other
Definition: ELFYAML.cpp:784
bool can_write(const Twine &Path)
Can we write this file?
Definition: FileSystem.h:483
When a child process is launched, this file should remain open in the child process.
Definition: FileSystem.h:762
May only access map via const_data as read only.
Definition: FileSystem.h:1078
CD_CreateNew - When opening a file:
Definition: FileSystem.h:726
uint64_t getFile() const
Definition: FileSystem.h:152
std::error_code is_local(const Twine &path, bool &result)
Is the file mounted on a local filesystem?
std::error_code create_link(const Twine &to, const Twine &from)
Create a link from from to to.
std::stack< directory_iterator, std::vector< directory_iterator > > Stack
Definition: FileSystem.h:1250
directory_iterator(const directory_entry &de, std::error_code &ec, bool follow_symlinks=true)
Definition: FileSystem.h:1211
Delete the file on close. Only makes a difference on windows.
Definition: FileSystem.h:758
The file should be opened in text mode on platforms that make this distinction.
Definition: FileSystem.h:750
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...
bool operator!=(const directory_iterator &RHS) const
Definition: FileSystem.h:1241
Represents the result of a call to directory_iterator::status().
Definition: FileSystem.h:158
std::error_code copy_file(const Twine &From, const Twine &To)
Copy the contents of From to To.
Definition: Path.cpp:962
bool operator!=(const directory_entry &RHS) const
Definition: FileSystem.h:1167
const directory_entry * operator->() const
Definition: FileSystem.h:1313
std::error_code real_path(const Twine &path, SmallVectorImpl< char > &output, bool expand_tilde=false)
Collapse all .
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:423
UniqueID(uint64_t Device, uint64_t File)
Definition: FileSystem.h:141
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
void no_push()
Does not go down into the current directory_entry.
Definition: FileSystem.h:1344
file_status(file_type Type)
Definition: FileSystem.h:264
void expand_tilde(const Twine &path, SmallVectorImpl< char > &output)
Expands ~ expressions to the user&#39;s home directory.
std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
recursive_directory_iterator & increment(std::error_code &ec)
Definition: FileSystem.h:1275
Expected< file_t > openNativeFileForReadWrite(const Twine &Name, CreationDisposition Disp, OpenFlags Flags, unsigned Mode=0666)
Opens the file with the given name in a write-only or read-write mode, returning its open file descri...
Definition: FileSystem.h:1012
bool operator!=(const UniqueID &Other) const
Definition: FileSystem.h:146
std::error_code getUniqueID(const Twine Path, UniqueID &Result)
Definition: Path.cpp:757
std::error_code resize_file(int FD, uint64_t Size)
Resize path to size.
const directory_entry * operator->() const
Definition: FileSystem.h:1229
file_type get_file_type(const Twine &Path, bool Follow=true)
Does status represent a directory?
Definition: Path.cpp:1030
basic_file_status(file_type Type, perms Perms, time_t ATime, uint32_t ATimeNSec, time_t MTime, uint32_t MTimeNSec, uid_t UID, gid_t GID, off_t Size)
Definition: FileSystem.h:185
std::error_code create_hard_link(const Twine &to, const Twine &from)
Create a hard link from from to to, or return an error.
basic_file_status(file_type Type)
Definition: FileSystem.h:182
std::error_code openFileForWrite(const Twine &Name, int &ResultFD, CreationDisposition Disp=CD_CreateAlways, OpenFlags Flags=OF_None, unsigned Mode=0666)
Opens the file with the given name in a write-only or read-write mode, returning its open file descri...
Definition: FileSystem.h:951
perms operator|(perms l, perms r)
Definition: FileSystem.h:113
Force files Atime to be updated on access. Only makes a difference on windows.
Definition: FileSystem.h:765
const std::string & path() const
Definition: FileSystem.h:1151
std::error_code rename(const Twine &from, const Twine &to)
Rename from to to.
Keeps state for the recursive_directory_iterator.
Definition: FileSystem.h:1249
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Definition: STLExtras.h:1167
std::error_code directory_iterator_construct(DirIterState &, StringRef, bool)
BlockVerifier::State From
bool operator==(const recursive_directory_iterator &RHS) const
Definition: FileSystem.h:1346
The file should be opened in append mode.
Definition: FileSystem.h:754
std::error_code createUniqueDirectory(const Twine &Prefix, SmallVectorImpl< char > &ResultPath)
Definition: Path.cpp:831
Expected< file_t > openNativeFileForRead(const Twine &Name, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
directory_entry(const Twine &Path, bool FollowSymlinks=true, file_type Type=file_type::type_unknown, basic_file_status Status=basic_file_status())
Definition: FileSystem.h:1140
std::error_code setPermissions(const Twine &Path, perms Permissions)
Set file permissions.
bool is_other(const basic_file_status &status)
Does this status represent something that exists but is not a directory or regular file...
Definition: Path.cpp:1073
std::error_code set_current_path(const Twine &path)
Set the current path.
ErrorOr< space_info > disk_space(const Twine &Path)
Get disk space usage information.
std::error_code directory_iterator_destruct(DirIterState &)
directory_iterator - Iterates through the entries in path.
Definition: FileSystem.h:1197
bool operator!=(const recursive_directory_iterator &RHS) const
Definition: FileSystem.h:1350
file_type
An enumeration for the file system&#39;s view of the type.
Definition: FileSystem.h:67
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:811
bool operator==(const directory_iterator &RHS) const
Definition: FileSystem.h:1231
std::error_code getPotentiallyUniqueTempFileName(const Twine &Prefix, StringRef Suffix, SmallVectorImpl< char > &ResultPath)
Get a unique temporary file name, not currently exisiting in the filesystem.
Definition: Path.cpp:846
uint64_t getDevice() const
Definition: FileSystem.h:151
std::error_code create_directory(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create the directory in path.
bool operator==(const UniqueID &Other) const
Definition: FileSystem.h:143
uint32_t Size
Definition: Profile.cpp:47
std::error_code getPotentiallyUniqueFileName(const Twine &Model, SmallVectorImpl< char > &ResultPath)
Get a unique name, not currently exisiting in the filesystem.
Definition: Path.cpp:839
Provides ErrorOr<T> smart pointer.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool equivalent(file_status A, file_status B)
Do file_status&#39;s represent the same thing?
CD_CreateAlways - When opening a file:
Definition: FileSystem.h:721
perms & operator|=(perms &l, perms r)
Definition: FileSystem.h:121
std::error_code openFile(const Twine &Name, int &ResultFD, CreationDisposition Disp, FileAccess Access, OpenFlags Flags, unsigned Mode=0666)
Opens a file with the specified creation disposition, access mode, and flags and returns a file descr...
int level() const
Gets the current level. Starting path is at level 0.
Definition: FileSystem.h:1317
Lightweight error class with error context and mandatory checking.
Definition: Error.h:158
bool no_push_request() const
Returns true if no_push has been called for this directory_entry.
Definition: FileSystem.h:1320
directory_entry - A single entry in a directory.
Definition: FileSystem.h:1128
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:49
CD_OpenAlways - When opening a file:
Definition: FileSystem.h:736
bool operator==(const directory_entry &RHS) const
Definition: FileSystem.h:1166
bool is_symlink_file(const basic_file_status &status)
Does status represent a symlink file?
Definition: Path.cpp:1061
bool exists(const basic_file_status &status)
Does file exist?
Definition: Path.cpp:1022
std::chrono::time_point< std::chrono::system_clock, D > TimePoint
A time point on the system clock.
Definition: Chrono.h:34