1 //===- llvm/Support/FileSystem.h - File System OS Concept -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
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
25 //===----------------------------------------------------------------------===//
27 #ifndef LLVM_SUPPORT_FILESYSTEM_H
28 #define LLVM_SUPPORT_FILESYSTEM_H
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/ADT/StringRef.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Support/Chrono.h"
34 #include "llvm/Support/Error.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/ErrorOr.h"
37 #include "llvm/Support/MD5.h"
44 #include <system_error>
48 #ifdef HAVE_SYS_STAT_H
56 /// An enumeration for the file system's view of the type.
57 enum class file_type {
70 /// space_info - Self explanatory.
82 owner_all = owner_read | owner_write | owner_exe,
86 group_all = group_read | group_write | group_exe,
90 others_all = others_read | others_write | others_exe,
91 all_read = owner_read | group_read | others_read,
92 all_write = owner_write | group_write | others_write,
93 all_exe = owner_exe | group_exe | others_exe,
94 all_all = owner_all | group_all | others_all,
95 set_uid_on_exe = 04000,
96 set_gid_on_exe = 02000,
98 all_perms = all_all | set_uid_on_exe | set_gid_on_exe | sticky_bit,
99 perms_not_known = 0xFFFF
102 // Helper functions so that you can use & and | to manipulate perms bits:
103 inline perms operator|(perms l, perms r) {
104 return static_cast<perms>(static_cast<unsigned short>(l) |
105 static_cast<unsigned short>(r));
107 inline perms operator&(perms l, perms r) {
108 return static_cast<perms>(static_cast<unsigned short>(l) &
109 static_cast<unsigned short>(r));
111 inline perms &operator|=(perms &l, perms r) {
115 inline perms &operator&=(perms &l, perms r) {
119 inline perms operator~(perms x) {
120 // Avoid UB by explicitly truncating the (unsigned) ~ result.
121 return static_cast<perms>(
122 static_cast<unsigned short>(~static_cast<unsigned short>(x)));
130 UniqueID() = default;
131 UniqueID(uint64_t Device, uint64_t File) : Device(Device), File(File) {}
133 bool operator==(const UniqueID &Other) const {
134 return Device == Other.Device && File == Other.File;
136 bool operator!=(const UniqueID &Other) const { return !(*this == Other); }
137 bool operator<(const UniqueID &Other) const {
138 return std::tie(Device, File) < std::tie(Other.Device, Other.File);
141 uint64_t getDevice() const { return Device; }
142 uint64_t getFile() const { return File; }
145 /// Represents the result of a call to directory_iterator::status(). This is a
146 /// subset of the information returned by a regular sys::fs::status() call, and
147 /// represents the information provided by Windows FileFirstFile/FindNextFile.
148 class basic_file_status {
150 #if defined(LLVM_ON_UNIX)
151 time_t fs_st_atime = 0;
152 time_t fs_st_mtime = 0;
155 off_t fs_st_size = 0;
156 #elif defined (LLVM_ON_WIN32)
157 uint32_t LastAccessedTimeHigh = 0;
158 uint32_t LastAccessedTimeLow = 0;
159 uint32_t LastWriteTimeHigh = 0;
160 uint32_t LastWriteTimeLow = 0;
161 uint32_t FileSizeHigh = 0;
162 uint32_t FileSizeLow = 0;
164 file_type Type = file_type::status_error;
165 perms Perms = perms_not_known;
168 basic_file_status() = default;
170 explicit basic_file_status(file_type Type) : Type(Type) {}
172 #if defined(LLVM_ON_UNIX)
173 basic_file_status(file_type Type, perms Perms, time_t ATime, time_t MTime,
174 uid_t UID, gid_t GID, off_t Size)
175 : fs_st_atime(ATime), fs_st_mtime(MTime), fs_st_uid(UID), fs_st_gid(GID),
176 fs_st_size(Size), Type(Type), Perms(Perms) {}
177 #elif defined(LLVM_ON_WIN32)
178 basic_file_status(file_type Type, perms Perms, uint32_t LastAccessTimeHigh,
179 uint32_t LastAccessTimeLow, uint32_t LastWriteTimeHigh,
180 uint32_t LastWriteTimeLow, uint32_t FileSizeHigh,
181 uint32_t FileSizeLow)
182 : LastAccessedTimeHigh(LastAccessTimeHigh),
183 LastAccessedTimeLow(LastAccessTimeLow),
184 LastWriteTimeHigh(LastWriteTimeHigh),
185 LastWriteTimeLow(LastWriteTimeLow), FileSizeHigh(FileSizeHigh),
186 FileSizeLow(FileSizeLow), Type(Type), Perms(Perms) {}
190 file_type type() const { return Type; }
191 perms permissions() const { return Perms; }
192 TimePoint<> getLastAccessedTime() const;
193 TimePoint<> getLastModificationTime() const;
195 #if defined(LLVM_ON_UNIX)
196 uint32_t getUser() const { return fs_st_uid; }
197 uint32_t getGroup() const { return fs_st_gid; }
198 uint64_t getSize() const { return fs_st_size; }
199 #elif defined (LLVM_ON_WIN32)
200 uint32_t getUser() const {
201 return 9999; // Not applicable to Windows, so...
204 uint32_t getGroup() const {
205 return 9999; // Not applicable to Windows, so...
208 uint64_t getSize() const {
209 return (uint64_t(FileSizeHigh) << 32) + FileSizeLow;
214 void type(file_type v) { Type = v; }
215 void permissions(perms p) { Perms = p; }
218 /// Represents the result of a call to sys::fs::status().
219 class file_status : public basic_file_status {
220 friend bool equivalent(file_status A, file_status B);
222 #if defined(LLVM_ON_UNIX)
224 nlink_t fs_st_nlinks = 0;
226 #elif defined (LLVM_ON_WIN32)
227 uint32_t NumLinks = 0;
228 uint32_t VolumeSerialNumber = 0;
229 uint32_t FileIndexHigh = 0;
230 uint32_t FileIndexLow = 0;
234 file_status() = default;
236 explicit file_status(file_type Type) : basic_file_status(Type) {}
238 #if defined(LLVM_ON_UNIX)
239 file_status(file_type Type, perms Perms, dev_t Dev, nlink_t Links, ino_t Ino,
240 time_t ATime, time_t MTime, uid_t UID, gid_t GID, off_t Size)
241 : basic_file_status(Type, Perms, ATime, MTime, UID, GID, Size),
242 fs_st_dev(Dev), fs_st_nlinks(Links), fs_st_ino(Ino) {}
243 #elif defined(LLVM_ON_WIN32)
244 file_status(file_type Type, perms Perms, uint32_t LinkCount,
245 uint32_t LastAccessTimeHigh, uint32_t LastAccessTimeLow,
246 uint32_t LastWriteTimeHigh, uint32_t LastWriteTimeLow,
247 uint32_t VolumeSerialNumber, uint32_t FileSizeHigh,
248 uint32_t FileSizeLow, uint32_t FileIndexHigh,
249 uint32_t FileIndexLow)
250 : basic_file_status(Type, Perms, LastAccessTimeHigh, LastAccessTimeLow,
251 LastWriteTimeHigh, LastWriteTimeLow, FileSizeHigh,
253 NumLinks(LinkCount), VolumeSerialNumber(VolumeSerialNumber),
254 FileIndexHigh(FileIndexHigh), FileIndexLow(FileIndexLow) {}
257 UniqueID getUniqueID() const;
258 uint32_t getLinkCount() const;
262 /// @name Physical Operators
265 /// @brief Make \a path an absolute path.
267 /// Makes \a path absolute using the \a current_directory if it is not already.
268 /// An empty \a path will result in the \a current_directory.
270 /// /absolute/path => /absolute/path
271 /// relative/../path => <current-directory>/relative/../path
273 /// @param path A path that is modified to be an absolute path.
274 /// @returns errc::success if \a path has been made absolute, otherwise a
275 /// platform-specific error_code.
276 std::error_code make_absolute(const Twine ¤t_directory,
277 SmallVectorImpl<char> &path);
279 /// @brief Make \a path an absolute path.
281 /// Makes \a path absolute using the current directory if it is not already. An
282 /// empty \a path will result in the current directory.
284 /// /absolute/path => /absolute/path
285 /// relative/../path => <current-directory>/relative/../path
287 /// @param path A path that is modified to be an absolute path.
288 /// @returns errc::success if \a path has been made absolute, otherwise a
289 /// platform-specific error_code.
290 std::error_code make_absolute(SmallVectorImpl<char> &path);
292 /// @brief Create all the non-existent directories in path.
294 /// @param path Directories to create.
295 /// @returns errc::success if is_directory(path), otherwise a platform
296 /// specific error_code. If IgnoreExisting is false, also returns
297 /// error if the directory already existed.
298 std::error_code create_directories(const Twine &path,
299 bool IgnoreExisting = true,
300 perms Perms = owner_all | group_all);
302 /// @brief Create the directory in path.
304 /// @param path Directory to create.
305 /// @returns errc::success if is_directory(path), otherwise a platform
306 /// specific error_code. If IgnoreExisting is false, also returns
307 /// error if the directory already existed.
308 std::error_code create_directory(const Twine &path, bool IgnoreExisting = true,
309 perms Perms = owner_all | group_all);
311 /// @brief Create a link from \a from to \a to.
313 /// The link may be a soft or a hard link, depending on the platform. The caller
314 /// may not assume which one. Currently on windows it creates a hard link since
315 /// soft links require extra privileges. On unix, it creates a soft link since
316 /// hard links don't work on SMB file systems.
318 /// @param to The path to hard link to.
319 /// @param from The path to hard link from. This is created.
320 /// @returns errc::success if the link was created, otherwise a platform
321 /// specific error_code.
322 std::error_code create_link(const Twine &to, const Twine &from);
324 /// Create a hard link from \a from to \a to, or return an error.
326 /// @param to The path to hard link to.
327 /// @param from The path to hard link from. This is created.
328 /// @returns errc::success if the link was created, otherwise a platform
329 /// specific error_code.
330 std::error_code create_hard_link(const Twine &to, const Twine &from);
332 /// @brief Collapse all . and .. patterns, resolve all symlinks, and optionally
333 /// expand ~ expressions to the user's home directory.
335 /// @param path The path to resolve.
336 /// @param output The location to store the resolved path.
337 /// @param expand_tilde If true, resolves ~ expressions to the user's home
339 std::error_code real_path(const Twine &path, SmallVectorImpl<char> &output,
340 bool expand_tilde = false);
342 /// @brief Get the current path.
344 /// @param result Holds the current path on return.
345 /// @returns errc::success if the current path has been stored in result,
346 /// otherwise a platform-specific error_code.
347 std::error_code current_path(SmallVectorImpl<char> &result);
349 /// @brief Set the current path.
351 /// @param path The path to set.
352 /// @returns errc::success if the current path was successfully set,
353 /// otherwise a platform-specific error_code.
354 std::error_code set_current_path(const Twine &path);
356 /// @brief Remove path. Equivalent to POSIX remove().
358 /// @param path Input path.
359 /// @returns errc::success if path has been removed or didn't exist, otherwise a
360 /// platform-specific error code. If IgnoreNonExisting is false, also
361 /// returns error if the file didn't exist.
362 std::error_code remove(const Twine &path, bool IgnoreNonExisting = true);
364 /// @brief Recursively delete a directory.
366 /// @param path Input path.
367 /// @returns errc::success if path has been removed or didn't exist, otherwise a
368 /// platform-specific error code.
369 std::error_code remove_directories(const Twine &path, bool IgnoreErrors = true);
371 /// @brief Rename \a from to \a to.
373 /// Files are renamed as if by POSIX rename(), except that on Windows there may
374 /// be a short interval of time during which the destination file does not
377 /// @param from The path to rename from.
378 /// @param to The path to rename to. This is created.
379 std::error_code rename(const Twine &from, const Twine &to);
381 /// @brief Copy the contents of \a From to \a To.
383 /// @param From The path to copy from.
384 /// @param To The path to copy to. This is created.
385 std::error_code copy_file(const Twine &From, const Twine &To);
387 /// @brief Resize path to size. File is resized as if by POSIX truncate().
389 /// @param FD Input file descriptor.
390 /// @param Size Size to resize to.
391 /// @returns errc::success if \a path has been resized to \a size, otherwise a
392 /// platform-specific error_code.
393 std::error_code resize_file(int FD, uint64_t Size);
395 /// @brief Compute an MD5 hash of a file's contents.
397 /// @param FD Input file descriptor.
398 /// @returns An MD5Result with the hash computed, if successful, otherwise a
400 ErrorOr<MD5::MD5Result> md5_contents(int FD);
402 /// @brief Version of compute_md5 that doesn't require an open file descriptor.
403 ErrorOr<MD5::MD5Result> md5_contents(const Twine &Path);
406 /// @name Physical Observers
409 /// @brief Does file exist?
411 /// @param status A basic_file_status previously returned from stat.
412 /// @returns True if the file represented by status exists, false if it does
414 bool exists(const basic_file_status &status);
416 enum class AccessMode { Exist, Write, Execute };
418 /// @brief Can the file be accessed?
420 /// @param Path Input path.
421 /// @returns errc::success if the path can be accessed, otherwise a
422 /// platform-specific error_code.
423 std::error_code access(const Twine &Path, AccessMode Mode);
425 /// @brief Does file exist?
427 /// @param Path Input path.
428 /// @returns True if it exists, false otherwise.
429 inline bool exists(const Twine &Path) {
430 return !access(Path, AccessMode::Exist);
433 /// @brief Can we execute this file?
435 /// @param Path Input path.
436 /// @returns True if we can execute it, false otherwise.
437 bool can_execute(const Twine &Path);
439 /// @brief Can we write this file?
441 /// @param Path Input path.
442 /// @returns True if we can write to it, false otherwise.
443 inline bool can_write(const Twine &Path) {
444 return !access(Path, AccessMode::Write);
447 /// @brief Do file_status's represent the same thing?
449 /// @param A Input file_status.
450 /// @param B Input file_status.
452 /// assert(status_known(A) || status_known(B));
454 /// @returns True if A and B both represent the same file system entity, false
456 bool equivalent(file_status A, file_status B);
458 /// @brief Do paths represent the same thing?
460 /// assert(status_known(A) || status_known(B));
462 /// @param A Input path A.
463 /// @param B Input path B.
464 /// @param result Set to true if stat(A) and stat(B) have the same device and
465 /// inode (or equivalent).
466 /// @returns errc::success if result has been successfully set, otherwise a
467 /// platform-specific error_code.
468 std::error_code equivalent(const Twine &A, const Twine &B, bool &result);
470 /// @brief Simpler version of equivalent for clients that don't need to
471 /// differentiate between an error and false.
472 inline bool equivalent(const Twine &A, const Twine &B) {
474 return !equivalent(A, B, result) && result;
477 /// @brief Is the file mounted on a local filesystem?
479 /// @param path Input path.
480 /// @param result Set to true if \a path is on fixed media such as a hard disk,
481 /// false if it is not.
482 /// @returns errc::success if result has been successfully set, otherwise a
483 /// platform specific error_code.
484 std::error_code is_local(const Twine &path, bool &result);
486 /// @brief Version of is_local accepting an open file descriptor.
487 std::error_code is_local(int FD, bool &result);
489 /// @brief Simpler version of is_local for clients that don't need to
490 /// differentiate between an error and false.
491 inline bool is_local(const Twine &Path) {
493 return !is_local(Path, Result) && Result;
496 /// @brief Simpler version of is_local accepting an open file descriptor for
497 /// clients that don't need to differentiate between an error and false.
498 inline bool is_local(int FD) {
500 return !is_local(FD, Result) && Result;
503 /// @brief Does status represent a directory?
505 /// @param Path The path to get the type of.
506 /// @param Follow For symbolic links, indicates whether to return the file type
507 /// of the link itself, or of the target.
508 /// @returns A value from the file_type enumeration indicating the type of file.
509 file_type get_file_type(const Twine &Path, bool Follow = true);
511 /// @brief Does status represent a directory?
513 /// @param status A basic_file_status previously returned from status.
514 /// @returns status.type() == file_type::directory_file.
515 bool is_directory(const basic_file_status &status);
517 /// @brief Is path a directory?
519 /// @param path Input path.
520 /// @param result Set to true if \a path is a directory (after following
521 /// symlinks, false if it is not. Undefined otherwise.
522 /// @returns errc::success if result has been successfully set, otherwise a
523 /// platform-specific error_code.
524 std::error_code is_directory(const Twine &path, bool &result);
526 /// @brief Simpler version of is_directory for clients that don't need to
527 /// differentiate between an error and false.
528 inline bool is_directory(const Twine &Path) {
530 return !is_directory(Path, Result) && Result;
533 /// @brief Does status represent a regular file?
535 /// @param status A basic_file_status previously returned from status.
536 /// @returns status_known(status) && status.type() == file_type::regular_file.
537 bool is_regular_file(const basic_file_status &status);
539 /// @brief Is path a regular file?
541 /// @param path Input path.
542 /// @param result Set to true if \a path is a regular file (after following
543 /// symlinks), false if it is not. Undefined otherwise.
544 /// @returns errc::success if result has been successfully set, otherwise a
545 /// platform-specific error_code.
546 std::error_code is_regular_file(const Twine &path, bool &result);
548 /// @brief Simpler version of is_regular_file for clients that don't need to
549 /// differentiate between an error and false.
550 inline bool is_regular_file(const Twine &Path) {
552 if (is_regular_file(Path, Result))
557 /// @brief Does status represent a symlink file?
559 /// @param status A basic_file_status previously returned from status.
560 /// @returns status_known(status) && status.type() == file_type::symlink_file.
561 bool is_symlink_file(const basic_file_status &status);
563 /// @brief Is path a symlink file?
565 /// @param path Input path.
566 /// @param result Set to true if \a path is a symlink file, false if it is not.
567 /// Undefined otherwise.
568 /// @returns errc::success if result has been successfully set, otherwise a
569 /// platform-specific error_code.
570 std::error_code is_symlink_file(const Twine &path, bool &result);
572 /// @brief Simpler version of is_symlink_file for clients that don't need to
573 /// differentiate between an error and false.
574 inline bool is_symlink_file(const Twine &Path) {
576 if (is_symlink_file(Path, Result))
581 /// @brief Does this status represent something that exists but is not a
582 /// directory or regular file?
584 /// @param status A basic_file_status previously returned from status.
585 /// @returns exists(s) && !is_regular_file(s) && !is_directory(s)
586 bool is_other(const basic_file_status &status);
588 /// @brief Is path something that exists but is not a directory,
589 /// regular file, or symlink?
591 /// @param path Input path.
592 /// @param result Set to true if \a path exists, but is not a directory, regular
593 /// file, or a symlink, false if it does not. Undefined otherwise.
594 /// @returns errc::success if result has been successfully set, otherwise a
595 /// platform-specific error_code.
596 std::error_code is_other(const Twine &path, bool &result);
598 /// @brief Get file status as if by POSIX stat().
600 /// @param path Input path.
601 /// @param result Set to the file status.
602 /// @param follow When true, follows symlinks. Otherwise, the symlink itself is
604 /// @returns errc::success if result has been successfully set, otherwise a
605 /// platform-specific error_code.
606 std::error_code status(const Twine &path, file_status &result,
609 /// @brief A version for when a file descriptor is already available.
610 std::error_code status(int FD, file_status &Result);
612 /// @brief Set file permissions.
614 /// @param Path File to set permissions on.
615 /// @param Permissions New file permissions.
616 /// @returns errc::success if the permissions were successfully set, otherwise
617 /// a platform-specific error_code.
618 /// @note On Windows, all permissions except *_write are ignored. Using any of
619 /// owner_write, group_write, or all_write will make the file writable.
620 /// Otherwise, the file will be marked as read-only.
621 std::error_code setPermissions(const Twine &Path, perms Permissions);
623 /// @brief Get file permissions.
625 /// @param Path File to get permissions from.
626 /// @returns the permissions if they were successfully retrieved, otherwise a
627 /// platform-specific error_code.
628 /// @note On Windows, if the file does not have the FILE_ATTRIBUTE_READONLY
629 /// attribute, all_all will be returned. Otherwise, all_read | all_exe
630 /// will be returned.
631 ErrorOr<perms> getPermissions(const Twine &Path);
633 /// @brief Get file size.
635 /// @param Path Input path.
636 /// @param Result Set to the size of the file in \a Path.
637 /// @returns errc::success if result has been successfully set, otherwise a
638 /// platform-specific error_code.
639 inline std::error_code file_size(const Twine &Path, uint64_t &Result) {
641 std::error_code EC = status(Path, Status);
644 Result = Status.getSize();
645 return std::error_code();
648 /// @brief Set the file modification and access time.
650 /// @returns errc::success if the file times were successfully set, otherwise a
651 /// platform-specific error_code or errc::function_not_supported on
652 /// platforms where the functionality isn't available.
653 std::error_code setLastModificationAndAccessTime(int FD, TimePoint<> Time);
655 /// @brief Is status available?
657 /// @param s Input file status.
658 /// @returns True if status() != status_error.
659 bool status_known(const basic_file_status &s);
661 /// @brief Is status available?
663 /// @param path Input path.
664 /// @param result Set to true if status() != status_error.
665 /// @returns errc::success if result has been successfully set, otherwise a
666 /// platform-specific error_code.
667 std::error_code status_known(const Twine &path, bool &result);
669 enum OpenFlags : unsigned {
672 /// F_Excl - When opening a file, this flag makes raw_fd_ostream
673 /// report an error if the file already exists.
676 /// F_Append - When opening a file, if it already exists append to the
677 /// existing file instead of returning an error. This may not be specified
681 /// The file should be opened in text mode on platforms that make this
685 /// Open the file for read and write.
688 /// Delete the file on close. Only makes a difference on windows.
692 /// @brief Create a uniquely named file.
694 /// Generates a unique path suitable for a temporary file and then opens it as a
695 /// file. The name is based on \a model with '%' replaced by a random char in
696 /// [0-9a-f]. If \a model is not an absolute path, the temporary file will be
697 /// created in the current directory.
699 /// Example: clang-%%-%%-%%-%%-%%.s => clang-a0-b1-c2-d3-e4.s
701 /// This is an atomic operation. Either the file is created and opened, or the
702 /// file system is left untouched.
704 /// The intended use is for files that are to be kept, possibly after
705 /// renaming them. For example, when running 'clang -c foo.o', the file can
706 /// be first created as foo-abc123.o and then renamed.
708 /// @param Model Name to base unique path off of.
709 /// @param ResultFD Set to the opened file's file descriptor.
710 /// @param ResultPath Set to the opened file's absolute path.
711 /// @returns errc::success if Result{FD,Path} have been successfully set,
712 /// otherwise a platform-specific error_code.
713 std::error_code createUniqueFile(const Twine &Model, int &ResultFD,
714 SmallVectorImpl<char> &ResultPath,
715 unsigned Mode = all_read | all_write,
716 sys::fs::OpenFlags Flags = sys::fs::F_RW);
718 /// @brief Simpler version for clients that don't want an open file.
719 std::error_code createUniqueFile(const Twine &Model,
720 SmallVectorImpl<char> &ResultPath);
722 /// Represents a temporary file.
724 /// The temporary file must be eventually discarded or given a final name and
727 /// The destructor doesn't implicitly discard because there is no way to
728 /// properly handle errors in a destructor.
731 TempFile(StringRef Name, int FD);
734 /// This creates a temporary file with createUniqueFile and schedules it for
735 /// deletion with sys::RemoveFileOnSignal.
736 static Expected<TempFile> create(const Twine &Model,
737 unsigned Mode = all_read | all_write);
738 TempFile(TempFile &&Other);
739 TempFile &operator=(TempFile &&Other);
741 // Name of the temporary file.
744 // The open file descriptor.
747 // Keep this with the given name.
748 Error keep(const Twine &Name);
750 // Keep this with the temporary name.
756 // This checks that keep or delete was called.
760 /// @brief Create a file in the system temporary directory.
762 /// The filename is of the form prefix-random_chars.suffix. Since the directory
763 /// is not know to the caller, Prefix and Suffix cannot have path separators.
764 /// The files are created with mode 0600.
766 /// This should be used for things like a temporary .s that is removed after
767 /// running the assembler.
768 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
770 SmallVectorImpl<char> &ResultPath,
771 sys::fs::OpenFlags Flags = sys::fs::F_RW);
773 /// @brief Simpler version for clients that don't want an open file.
774 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
775 SmallVectorImpl<char> &ResultPath);
777 std::error_code createUniqueDirectory(const Twine &Prefix,
778 SmallVectorImpl<char> &ResultPath);
780 inline OpenFlags operator|(OpenFlags A, OpenFlags B) {
781 return OpenFlags(unsigned(A) | unsigned(B));
784 inline OpenFlags &operator|=(OpenFlags &A, OpenFlags B) {
789 std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
790 OpenFlags Flags, unsigned Mode = 0666);
792 std::error_code openFileForRead(const Twine &Name, int &ResultFD,
793 SmallVectorImpl<char> *RealPath = nullptr);
795 std::error_code getUniqueID(const Twine Path, UniqueID &Result);
797 /// @brief Get disk space usage information.
799 /// Note: Users must be careful about "Time Of Check, Time Of Use" kind of bug.
800 /// Note: Windows reports results according to the quota allocated to the user.
802 /// @param Path Input path.
803 /// @returns a space_info structure filled with the capacity, free, and
804 /// available space on the device \a Path is on. A platform specific error_code
805 /// is returned on error.
806 ErrorOr<space_info> disk_space(const Twine &Path);
808 /// This class represents a memory mapped file. It is based on
809 /// boost::iostreams::mapped_file.
810 class mapped_file_region {
813 readonly, ///< May only access map via const_data as read only.
814 readwrite, ///< May access map via data and modify it. Written to path.
815 priv ///< May modify via data, but changes are lost on destruction.
819 /// Platform-specific mapping state.
823 std::error_code init(int FD, uint64_t Offset, mapmode Mode);
826 mapped_file_region() = delete;
827 mapped_file_region(mapped_file_region&) = delete;
828 mapped_file_region &operator =(mapped_file_region&) = delete;
830 /// \param fd An open file descriptor to map. mapped_file_region takes
831 /// ownership if closefd is true. It must have been opended in the correct
833 mapped_file_region(int fd, mapmode mode, size_t length, uint64_t offset,
834 std::error_code &ec);
836 ~mapped_file_region();
841 /// Get a const view of the data. Modifying this memory has undefined
843 const char *const_data() const;
845 /// \returns The minimum alignment offset must be.
846 static int alignment();
849 /// Return the path to the main executable, given the value of argv[0] from
850 /// program startup and the address of main itself. In extremis, this function
851 /// may fail and return an empty path.
852 std::string getMainExecutable(const char *argv0, void *MainExecAddr);
858 /// directory_entry - A single entry in a directory. Caches the status either
859 /// from the result of the iteration syscall, or the first time status is
861 class directory_entry {
864 basic_file_status Status;
867 explicit directory_entry(const Twine &path, bool follow_symlinks = true,
868 basic_file_status st = basic_file_status())
869 : Path(path.str()), FollowSymlinks(follow_symlinks), Status(st) {}
871 directory_entry() = default;
873 void assign(const Twine &path, basic_file_status st = basic_file_status()) {
878 void replace_filename(const Twine &filename,
879 basic_file_status st = basic_file_status());
881 const std::string &path() const { return Path; }
882 ErrorOr<basic_file_status> status() const;
884 bool operator==(const directory_entry& rhs) const { return Path == rhs.Path; }
885 bool operator!=(const directory_entry& rhs) const { return !(*this == rhs); }
886 bool operator< (const directory_entry& rhs) const;
887 bool operator<=(const directory_entry& rhs) const;
888 bool operator> (const directory_entry& rhs) const;
889 bool operator>=(const directory_entry& rhs) const;
896 std::error_code directory_iterator_construct(DirIterState &, StringRef, bool);
897 std::error_code directory_iterator_increment(DirIterState &);
898 std::error_code directory_iterator_destruct(DirIterState &);
900 /// Keeps state for the directory_iterator.
901 struct DirIterState {
903 directory_iterator_destruct(*this);
906 intptr_t IterationHandle = 0;
907 directory_entry CurrentEntry;
910 } // end namespace detail
912 /// directory_iterator - Iterates through the entries in path. There is no
913 /// operator++ because we need an error_code. If it's really needed we can make
914 /// it call report_fatal_error on error.
915 class directory_iterator {
916 std::shared_ptr<detail::DirIterState> State;
917 bool FollowSymlinks = true;
920 explicit directory_iterator(const Twine &path, std::error_code &ec,
921 bool follow_symlinks = true)
922 : FollowSymlinks(follow_symlinks) {
923 State = std::make_shared<detail::DirIterState>();
924 SmallString<128> path_storage;
925 ec = detail::directory_iterator_construct(
926 *State, path.toStringRef(path_storage), FollowSymlinks);
929 explicit directory_iterator(const directory_entry &de, std::error_code &ec,
930 bool follow_symlinks = true)
931 : FollowSymlinks(follow_symlinks) {
932 State = std::make_shared<detail::DirIterState>();
934 detail::directory_iterator_construct(*State, de.path(), FollowSymlinks);
937 /// Construct end iterator.
938 directory_iterator() = default;
940 // No operator++ because we need error_code.
941 directory_iterator &increment(std::error_code &ec) {
942 ec = directory_iterator_increment(*State);
946 const directory_entry &operator*() const { return State->CurrentEntry; }
947 const directory_entry *operator->() const { return &State->CurrentEntry; }
949 bool operator==(const directory_iterator &RHS) const {
950 if (State == RHS.State)
953 return State->CurrentEntry == directory_entry();
955 return RHS.State->CurrentEntry == directory_entry();
956 return State->CurrentEntry == RHS.State->CurrentEntry;
959 bool operator!=(const directory_iterator &RHS) const {
960 return !(*this == RHS);
962 // Other members as required by
963 // C++ Std, 24.1.1 Input iterators [input.iterators]
968 /// Keeps state for the recursive_directory_iterator.
969 struct RecDirIterState {
970 std::stack<directory_iterator, std::vector<directory_iterator>> Stack;
972 bool HasNoPushRequest = false;
975 } // end namespace detail
977 /// recursive_directory_iterator - Same as directory_iterator except for it
978 /// recurses down into child directories.
979 class recursive_directory_iterator {
980 std::shared_ptr<detail::RecDirIterState> State;
984 recursive_directory_iterator() = default;
985 explicit recursive_directory_iterator(const Twine &path, std::error_code &ec,
986 bool follow_symlinks = true)
987 : State(std::make_shared<detail::RecDirIterState>()),
988 Follow(follow_symlinks) {
989 State->Stack.push(directory_iterator(path, ec, Follow));
990 if (State->Stack.top() == directory_iterator())
994 // No operator++ because we need error_code.
995 recursive_directory_iterator &increment(std::error_code &ec) {
996 const directory_iterator end_itr = {};
998 if (State->HasNoPushRequest)
999 State->HasNoPushRequest = false;
1001 ErrorOr<basic_file_status> st = State->Stack.top()->status();
1002 if (!st) return *this;
1003 if (is_directory(*st)) {
1004 State->Stack.push(directory_iterator(*State->Stack.top(), ec, Follow));
1005 if (ec) return *this;
1006 if (State->Stack.top() != end_itr) {
1014 while (!State->Stack.empty()
1015 && State->Stack.top().increment(ec) == end_itr) {
1020 // Check if we are done. If so, create an end iterator.
1021 if (State->Stack.empty())
1027 const directory_entry &operator*() const { return *State->Stack.top(); }
1028 const directory_entry *operator->() const { return &*State->Stack.top(); }
1031 /// Gets the current level. Starting path is at level 0.
1032 int level() const { return State->Level; }
1034 /// Returns true if no_push has been called for this directory_entry.
1035 bool no_push_request() const { return State->HasNoPushRequest; }
1038 /// Goes up one level if Level > 0.
1040 assert(State && "Cannot pop an end iterator!");
1041 assert(State->Level > 0 && "Cannot pop an iterator with level < 1");
1043 const directory_iterator end_itr = {};
1047 report_fatal_error("Error incrementing directory iterator.");
1050 } while (!State->Stack.empty()
1051 && State->Stack.top().increment(ec) == end_itr);
1053 // Check if we are done. If so, create an end iterator.
1054 if (State->Stack.empty())
1058 /// Does not go down into the current directory_entry.
1059 void no_push() { State->HasNoPushRequest = true; }
1061 bool operator==(const recursive_directory_iterator &RHS) const {
1062 return State == RHS.State;
1065 bool operator!=(const recursive_directory_iterator &RHS) const {
1066 return !(*this == RHS);
1068 // Other members as required by
1069 // C++ Std, 24.1.1 Input iterators [input.iterators]
1074 } // end namespace fs
1075 } // end namespace sys
1076 } // end namespace llvm
1078 #endif // LLVM_SUPPORT_FILESYSTEM_H