LLVM 20.0.0git
FileSystem.h
Go to the documentation of this file.
1//===- llvm/Support/FileSystem.h - File System OS Concept -------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file declares the llvm::sys::fs namespace. It is designed after
10// TR2/boost filesystem (v3), but modified to remove exception handling and the
11// path class.
12//
13// All functions return an error_code and their actual work via the last out
14// argument. The out argument is defined if and only if errc::success is
15// returned. A function may return any error code in the generic or system
16// category. However, they shall be equivalent to any error conditions listed
17// in each functions respective documentation if the condition applies. [ note:
18// this does not guarantee that error_code will be in the set of explicitly
19// listed codes, but it does guarantee that if any of the explicitly listed
20// errors occur, the correct error_code will be used ]. All functions may
21// return errc::not_enough_memory if there is not enough memory to complete the
22// operation.
23//
24//===----------------------------------------------------------------------===//
25
26#ifndef LLVM_SUPPORT_FILESYSTEM_H
27#define LLVM_SUPPORT_FILESYSTEM_H
28
30#include "llvm/ADT/StringRef.h"
31#include "llvm/ADT/Twine.h"
32#include "llvm/Config/llvm-config.h"
33#include "llvm/Support/Chrono.h"
34#include "llvm/Support/Error.h"
38#include "llvm/Support/MD5.h"
39#include <cassert>
40#include <cstdint>
41#include <ctime>
42#include <memory>
43#include <string>
44#include <system_error>
45#include <vector>
46
47#include <sys/stat.h>
48
49namespace llvm {
50namespace sys {
51namespace fs {
52
53#if defined(_WIN32)
54// A Win32 HANDLE is a typedef of void*
55using file_t = void *;
56#else
57using file_t = int;
58#endif
59
60extern const file_t kInvalidFile;
61
62/// An enumeration for the file system's view of the type.
63enum class file_type {
74};
75
76/// space_info - Self explanatory.
77struct space_info {
81};
82
83enum perms {
85 owner_read = 0400,
87 owner_exe = 0100,
91 group_exe = 010,
103 sticky_bit = 01000,
105 perms_not_known = 0xFFFF
107
108// Helper functions so that you can use & and | to manipulate perms bits:
110 return static_cast<perms>(static_cast<unsigned short>(l) |
111 static_cast<unsigned short>(r));
112}
114 return static_cast<perms>(static_cast<unsigned short>(l) &
115 static_cast<unsigned short>(r));
116}
117inline perms &operator|=(perms &l, perms r) {
118 l = l | r;
119 return l;
120}
121inline perms &operator&=(perms &l, perms r) {
122 l = l & r;
123 return l;
124}
126 // Avoid UB by explicitly truncating the (unsigned) ~ result.
127 return static_cast<perms>(
128 static_cast<unsigned short>(~static_cast<unsigned short>(x)));
129}
130
131/// Represents the result of a call to directory_iterator::status(). This is a
132/// subset of the information returned by a regular sys::fs::status() call, and
133/// represents the information provided by Windows FileFirstFile/FindNextFile.
135protected:
136 #if defined(LLVM_ON_UNIX)
137 time_t fs_st_atime = 0;
138 time_t fs_st_mtime = 0;
141 uid_t fs_st_uid = 0;
142 gid_t fs_st_gid = 0;
143 off_t fs_st_size = 0;
144 #elif defined (_WIN32)
145 uint32_t LastAccessedTimeHigh = 0;
146 uint32_t LastAccessedTimeLow = 0;
147 uint32_t LastWriteTimeHigh = 0;
148 uint32_t LastWriteTimeLow = 0;
149 uint32_t FileSizeHigh = 0;
150 uint32_t FileSizeLow = 0;
151 #endif
154
155public:
156 basic_file_status() = default;
157
159
160 #if defined(LLVM_ON_UNIX)
162 uint32_t ATimeNSec, time_t MTime, uint32_t MTimeNSec,
163 uid_t UID, gid_t GID, off_t Size)
164 : fs_st_atime(ATime), fs_st_mtime(MTime),
165 fs_st_atime_nsec(ATimeNSec), fs_st_mtime_nsec(MTimeNSec),
166 fs_st_uid(UID), fs_st_gid(GID),
168#elif defined(_WIN32)
169 basic_file_status(file_type Type, perms Perms, uint32_t LastAccessTimeHigh,
170 uint32_t LastAccessTimeLow, uint32_t LastWriteTimeHigh,
171 uint32_t LastWriteTimeLow, uint32_t FileSizeHigh,
172 uint32_t FileSizeLow)
173 : LastAccessedTimeHigh(LastAccessTimeHigh),
174 LastAccessedTimeLow(LastAccessTimeLow),
175 LastWriteTimeHigh(LastWriteTimeHigh),
176 LastWriteTimeLow(LastWriteTimeLow), FileSizeHigh(FileSizeHigh),
177 FileSizeLow(FileSizeLow), Type(Type), Perms(Perms) {}
178 #endif
179
180 // getters
181 file_type type() const { return Type; }
182 perms permissions() const { return Perms; }
183
184 /// The file access time as reported from the underlying file system.
185 ///
186 /// Also see comments on \c getLastModificationTime() related to the precision
187 /// of the returned value.
189
190 /// The file modification time as reported from the underlying file system.
191 ///
192 /// The returned value allows for nanosecond precision but the actual
193 /// resolution is an implementation detail of the underlying file system.
194 /// There is no guarantee for what kind of resolution you can expect, the
195 /// resolution can differ across platforms and even across mountpoints on the
196 /// same machine.
198
199 #if defined(LLVM_ON_UNIX)
200 uint32_t getUser() const { return fs_st_uid; }
201 uint32_t getGroup() const { return fs_st_gid; }
202 uint64_t getSize() const { return fs_st_size; }
203 #elif defined (_WIN32)
204 uint32_t getUser() const {
205 return 9999; // Not applicable to Windows, so...
206 }
207
208 uint32_t getGroup() const {
209 return 9999; // Not applicable to Windows, so...
210 }
211
212 uint64_t getSize() const {
213 return (uint64_t(FileSizeHigh) << 32) + FileSizeLow;
214 }
215 #endif
216
217 // setters
218 void type(file_type v) { Type = v; }
219 void permissions(perms p) { Perms = p; }
220};
221
222/// Represents the result of a call to sys::fs::status().
225
226 #if defined(LLVM_ON_UNIX)
227 dev_t fs_st_dev = 0;
228 nlink_t fs_st_nlinks = 0;
229 ino_t fs_st_ino = 0;
230 #elif defined (_WIN32)
231 uint32_t NumLinks = 0;
232 uint32_t VolumeSerialNumber = 0;
233 uint64_t PathHash = 0;
234 #endif
235
236public:
237 file_status() = default;
238
240
241 #if defined(LLVM_ON_UNIX)
242 file_status(file_type Type, perms Perms, dev_t Dev, nlink_t Links, ino_t Ino,
243 time_t ATime, uint32_t ATimeNSec,
244 time_t MTime, uint32_t MTimeNSec,
245 uid_t UID, gid_t GID, off_t Size)
246 : basic_file_status(Type, Perms, ATime, ATimeNSec, MTime, MTimeNSec,
247 UID, GID, Size),
248 fs_st_dev(Dev), fs_st_nlinks(Links), fs_st_ino(Ino) {}
249 #elif defined(_WIN32)
251 uint32_t LastAccessTimeHigh, uint32_t LastAccessTimeLow,
252 uint32_t LastWriteTimeHigh, uint32_t LastWriteTimeLow,
253 uint32_t VolumeSerialNumber, uint32_t FileSizeHigh,
254 uint32_t FileSizeLow, uint64_t PathHash)
255 : basic_file_status(Type, Perms, LastAccessTimeHigh, LastAccessTimeLow,
256 LastWriteTimeHigh, LastWriteTimeLow, FileSizeHigh,
257 FileSizeLow),
258 NumLinks(LinkCount), VolumeSerialNumber(VolumeSerialNumber),
259 PathHash(PathHash) {}
260 #endif
261
264};
265
266/// @}
267/// @name Physical Operators
268/// @{
269
270/// Make \a path an absolute path.
271///
272/// Makes \a path absolute using the \a current_directory if it is not already.
273/// An empty \a path will result in the \a current_directory.
274///
275/// /absolute/path => /absolute/path
276/// relative/../path => <current-directory>/relative/../path
277///
278/// @param path A path that is modified to be an absolute path.
279void make_absolute(const Twine &current_directory, SmallVectorImpl<char> &path);
280
281/// Make \a path an absolute path.
282///
283/// Makes \a path absolute using the current directory if it is not already. An
284/// empty \a path will result in the current directory.
285///
286/// /absolute/path => /absolute/path
287/// relative/../path => <current-directory>/relative/../path
288///
289/// @param path A path that is modified to be an absolute path.
290/// @returns errc::success if \a path has been made absolute, otherwise a
291/// platform-specific error_code.
292std::error_code make_absolute(SmallVectorImpl<char> &path);
293
294/// Create all the non-existent directories in path.
295///
296/// @param path Directories to create.
297/// @returns errc::success if is_directory(path), otherwise a platform
298/// specific error_code. If IgnoreExisting is false, also returns
299/// error if the directory already existed.
300std::error_code create_directories(const Twine &path,
301 bool IgnoreExisting = true,
302 perms Perms = owner_all | group_all);
303
304/// Create the directory in path.
305///
306/// @param path Directory to create.
307/// @returns errc::success if is_directory(path), otherwise a platform
308/// specific error_code. If IgnoreExisting is false, also returns
309/// error if the directory already existed.
310std::error_code create_directory(const Twine &path, bool IgnoreExisting = true,
311 perms Perms = owner_all | group_all);
312
313/// Create a link from \a from to \a to.
314///
315/// The link may be a soft or a hard link, depending on the platform. The caller
316/// may not assume which one. Currently on windows it creates a hard link since
317/// soft links require extra privileges. On unix, it creates a soft link since
318/// hard links don't work on SMB file systems.
319///
320/// @param to The path to hard link to.
321/// @param from The path to hard link from. This is created.
322/// @returns errc::success if the link was created, otherwise a platform
323/// specific error_code.
324std::error_code create_link(const Twine &to, const Twine &from);
325
326/// Create a hard link from \a from to \a to, or return an error.
327///
328/// @param to The path to hard link to.
329/// @param from The path to hard link from. This is created.
330/// @returns errc::success if the link was created, otherwise a platform
331/// specific error_code.
332std::error_code create_hard_link(const Twine &to, const Twine &from);
333
334/// Collapse all . and .. patterns, resolve all symlinks, and optionally
335/// expand ~ expressions to the user's home directory.
336///
337/// @param path The path to resolve.
338/// @param output The location to store the resolved path.
339/// @param expand_tilde If true, resolves ~ expressions to the user's home
340/// directory.
341std::error_code real_path(const Twine &path, SmallVectorImpl<char> &output,
342 bool expand_tilde = false);
343
344/// Expands ~ expressions to the user's home directory. On Unix ~user
345/// directories are resolved as well.
346///
347/// @param path The path to resolve.
348void expand_tilde(const Twine &path, SmallVectorImpl<char> &output);
349
350/// Get the current path.
351///
352/// @param result Holds the current path on return.
353/// @returns errc::success if the current path has been stored in result,
354/// otherwise a platform-specific error_code.
355std::error_code current_path(SmallVectorImpl<char> &result);
356
357/// Set the current path.
358///
359/// @param path The path to set.
360/// @returns errc::success if the current path was successfully set,
361/// otherwise a platform-specific error_code.
362std::error_code set_current_path(const Twine &path);
363
364/// Remove path. Equivalent to POSIX remove().
365///
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. If IgnoreNonExisting is false, also
369/// returns error if the file didn't exist.
370std::error_code remove(const Twine &path, bool IgnoreNonExisting = true);
371
372/// Recursively delete a directory.
373///
374/// @param path Input path.
375/// @returns errc::success if path has been removed or didn't exist, otherwise a
376/// platform-specific error code.
377std::error_code remove_directories(const Twine &path, bool IgnoreErrors = true);
378
379/// Rename \a from to \a to.
380///
381/// Files are renamed as if by POSIX rename(), except that on Windows there may
382/// be a short interval of time during which the destination file does not
383/// exist.
384///
385/// @param from The path to rename from.
386/// @param to The path to rename to. This is created.
387std::error_code rename(const Twine &from, const Twine &to);
388
389/// Copy the contents of \a From to \a To.
390///
391/// @param From The path to copy from.
392/// @param To The path to copy to. This is created.
393std::error_code copy_file(const Twine &From, const Twine &To);
394
395/// Copy the contents of \a From to \a To.
396///
397/// @param From The path to copy from.
398/// @param ToFD The open file descriptor of the destination file.
399std::error_code copy_file(const Twine &From, int ToFD);
400
401/// Resize path to size. File is resized as if by POSIX truncate().
402///
403/// @param FD Input file descriptor.
404/// @param Size Size to resize to.
405/// @returns errc::success if \a path has been resized to \a size, otherwise a
406/// platform-specific error_code.
407std::error_code resize_file(int FD, uint64_t Size);
408
409/// Resize \p FD to \p Size before mapping \a mapped_file_region::readwrite. On
410/// non-Windows, this calls \a resize_file(). On Windows, this is a no-op,
411/// since the subsequent mapping (via \c CreateFileMapping) automatically
412/// extends the file.
413inline std::error_code resize_file_before_mapping_readwrite(int FD,
414 uint64_t Size) {
415#ifdef _WIN32
416 (void)FD;
417 (void)Size;
418 return std::error_code();
419#else
420 return resize_file(FD, Size);
421#endif
422}
423
424/// Compute an MD5 hash of a file's contents.
425///
426/// @param FD Input file descriptor.
427/// @returns An MD5Result with the hash computed, if successful, otherwise a
428/// std::error_code.
430
431/// Version of compute_md5 that doesn't require an open file descriptor.
433
434/// @}
435/// @name Physical Observers
436/// @{
437
438/// Does file exist?
439///
440/// @param status A basic_file_status previously returned from stat.
441/// @returns True if the file represented by status exists, false if it does
442/// not.
443bool exists(const basic_file_status &status);
444
445enum class AccessMode { Exist, Write, Execute };
446
447/// Can the file be accessed?
448///
449/// @param Path Input path.
450/// @returns errc::success if the path can be accessed, otherwise a
451/// platform-specific error_code.
452std::error_code access(const Twine &Path, AccessMode Mode);
453
454/// Does file exist?
455///
456/// @param Path Input path.
457/// @returns True if it exists, false otherwise.
458inline bool exists(const Twine &Path) {
459 return !access(Path, AccessMode::Exist);
460}
461
462/// Can we execute this file?
463///
464/// @param Path Input path.
465/// @returns True if we can execute it, false otherwise.
466bool can_execute(const Twine &Path);
467
468/// Can we write this file?
469///
470/// @param Path Input path.
471/// @returns True if we can write to it, false otherwise.
472inline bool can_write(const Twine &Path) {
473 return !access(Path, AccessMode::Write);
474}
475
476/// Do file_status's represent the same thing?
477///
478/// @param A Input file_status.
479/// @param B Input file_status.
480///
481/// assert(status_known(A) || status_known(B));
482///
483/// @returns True if A and B both represent the same file system entity, false
484/// otherwise.
486
487/// Do paths represent the same thing?
488///
489/// assert(status_known(A) || status_known(B));
490///
491/// @param A Input path A.
492/// @param B Input path B.
493/// @param result Set to true if stat(A) and stat(B) have the same device and
494/// inode (or equivalent).
495/// @returns errc::success if result has been successfully set, otherwise a
496/// platform-specific error_code.
497std::error_code equivalent(const Twine &A, const Twine &B, bool &result);
498
499/// Simpler version of equivalent for clients that don't need to
500/// differentiate between an error and false.
501inline bool equivalent(const Twine &A, const Twine &B) {
502 bool result;
503 return !equivalent(A, B, result) && result;
504}
505
506/// Is the file mounted on a local filesystem?
507///
508/// @param path Input path.
509/// @param result Set to true if \a path is on fixed media such as a hard disk,
510/// false if it is not.
511/// @returns errc::success if result has been successfully set, otherwise a
512/// platform specific error_code.
513std::error_code is_local(const Twine &path, bool &result);
514
515/// Version of is_local accepting an open file descriptor.
516std::error_code is_local(int FD, bool &result);
517
518/// Simpler version of is_local for clients that don't need to
519/// differentiate between an error and false.
520inline bool is_local(const Twine &Path) {
521 bool Result;
522 return !is_local(Path, Result) && Result;
523}
524
525/// Simpler version of is_local accepting an open file descriptor for
526/// clients that don't need to differentiate between an error and false.
527inline bool is_local(int FD) {
528 bool Result;
529 return !is_local(FD, Result) && Result;
530}
531
532/// Does status represent a directory?
533///
534/// @param Path The path to get the type of.
535/// @param Follow For symbolic links, indicates whether to return the file type
536/// of the link itself, or of the target.
537/// @returns A value from the file_type enumeration indicating the type of file.
538file_type get_file_type(const Twine &Path, bool Follow = true);
539
540/// Does status represent a directory?
541///
542/// @param status A basic_file_status previously returned from status.
543/// @returns status.type() == file_type::directory_file.
544bool is_directory(const basic_file_status &status);
545
546/// Is path a directory?
547///
548/// @param path Input path.
549/// @param result Set to true if \a path is a directory (after following
550/// symlinks, false if it is not. Undefined otherwise.
551/// @returns errc::success if result has been successfully set, otherwise a
552/// platform-specific error_code.
553std::error_code is_directory(const Twine &path, bool &result);
554
555/// Simpler version of is_directory for clients that don't need to
556/// differentiate between an error and false.
557inline bool is_directory(const Twine &Path) {
558 bool Result;
559 return !is_directory(Path, Result) && Result;
560}
561
562/// Does status represent a regular file?
563///
564/// @param status A basic_file_status previously returned from status.
565/// @returns status_known(status) && status.type() == file_type::regular_file.
566bool is_regular_file(const basic_file_status &status);
567
568/// Is path a regular file?
569///
570/// @param path Input path.
571/// @param result Set to true if \a path is a regular file (after following
572/// symlinks), false if it is not. Undefined otherwise.
573/// @returns errc::success if result has been successfully set, otherwise a
574/// platform-specific error_code.
575std::error_code is_regular_file(const Twine &path, bool &result);
576
577/// Simpler version of is_regular_file for clients that don't need to
578/// differentiate between an error and false.
579inline bool is_regular_file(const Twine &Path) {
580 bool Result;
581 if (is_regular_file(Path, Result))
582 return false;
583 return Result;
584}
585
586/// Does status represent a symlink file?
587///
588/// @param status A basic_file_status previously returned from status.
589/// @returns status_known(status) && status.type() == file_type::symlink_file.
590bool is_symlink_file(const basic_file_status &status);
591
592/// Is path a symlink file?
593///
594/// @param path Input path.
595/// @param result Set to true if \a path is a symlink file, false if it is not.
596/// Undefined otherwise.
597/// @returns errc::success if result has been successfully set, otherwise a
598/// platform-specific error_code.
599std::error_code is_symlink_file(const Twine &path, bool &result);
600
601/// Simpler version of is_symlink_file for clients that don't need to
602/// differentiate between an error and false.
603inline bool is_symlink_file(const Twine &Path) {
604 bool Result;
605 if (is_symlink_file(Path, Result))
606 return false;
607 return Result;
608}
609
610/// Does this status represent something that exists but is not a
611/// directory or regular file?
612///
613/// @param status A basic_file_status previously returned from status.
614/// @returns exists(s) && !is_regular_file(s) && !is_directory(s)
615bool is_other(const basic_file_status &status);
616
617/// Is path something that exists but is not a directory,
618/// regular file, or symlink?
619///
620/// @param path Input path.
621/// @param result Set to true if \a path exists, but is not a directory, regular
622/// file, or a symlink, false if it does not. Undefined otherwise.
623/// @returns errc::success if result has been successfully set, otherwise a
624/// platform-specific error_code.
625std::error_code is_other(const Twine &path, bool &result);
626
627/// Get file status as if by POSIX stat().
628///
629/// @param path Input path.
630/// @param result Set to the file status.
631/// @param follow When true, follows symlinks. Otherwise, the symlink itself is
632/// statted.
633/// @returns errc::success if result has been successfully set, otherwise a
634/// platform-specific error_code.
635std::error_code status(const Twine &path, file_status &result,
636 bool follow = true);
637
638/// A version for when a file descriptor is already available.
639std::error_code status(int FD, file_status &Result);
640
641#ifdef _WIN32
642/// A version for when a file descriptor is already available.
643std::error_code status(file_t FD, file_status &Result);
644#endif
645
646/// Get file creation mode mask of the process.
647///
648/// @returns Mask reported by umask(2)
649/// @note There is no umask on Windows. This function returns 0 always
650/// on Windows. This function does not return an error_code because
651/// umask(2) never fails. It is not thread safe.
652unsigned getUmask();
653
654/// Set file permissions.
655///
656/// @param Path File to set permissions on.
657/// @param Permissions New file permissions.
658/// @returns errc::success if the permissions were successfully set, otherwise
659/// a platform-specific error_code.
660/// @note On Windows, all permissions except *_write are ignored. Using any of
661/// owner_write, group_write, or all_write will make the file writable.
662/// Otherwise, the file will be marked as read-only.
663std::error_code setPermissions(const Twine &Path, perms Permissions);
664
665/// Vesion of setPermissions accepting a file descriptor.
666/// TODO Delete the path based overload once we implement the FD based overload
667/// on Windows.
668std::error_code setPermissions(int FD, perms Permissions);
669
670/// Get file permissions.
671///
672/// @param Path File to get permissions from.
673/// @returns the permissions if they were successfully retrieved, otherwise a
674/// platform-specific error_code.
675/// @note On Windows, if the file does not have the FILE_ATTRIBUTE_READONLY
676/// attribute, all_all will be returned. Otherwise, all_read | all_exe
677/// will be returned.
679
680/// Get file size.
681///
682/// @param Path Input path.
683/// @param Result Set to the size of the file in \a Path.
684/// @returns errc::success if result has been successfully set, otherwise a
685/// platform-specific error_code.
686inline std::error_code file_size(const Twine &Path, uint64_t &Result) {
688 std::error_code EC = status(Path, Status);
689 if (EC)
690 return EC;
691 Result = Status.getSize();
692 return std::error_code();
693}
694
695/// Set the file modification and access time.
696///
697/// @returns errc::success if the file times were successfully set, otherwise a
698/// platform-specific error_code or errc::function_not_supported on
699/// platforms where the functionality isn't available.
700std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
701 TimePoint<> ModificationTime);
702
703/// Simpler version that sets both file modification and access time to the same
704/// time.
705inline std::error_code setLastAccessAndModificationTime(int FD,
706 TimePoint<> Time) {
707 return setLastAccessAndModificationTime(FD, Time, Time);
708}
709
710/// Is status available?
711///
712/// @param s Input file status.
713/// @returns True if status() != status_error.
714bool status_known(const basic_file_status &s);
715
716/// Is status available?
717///
718/// @param path Input path.
719/// @param result Set to true if status() != status_error.
720/// @returns errc::success if result has been successfully set, otherwise a
721/// platform-specific error_code.
722std::error_code status_known(const Twine &path, bool &result);
723
724enum CreationDisposition : unsigned {
725 /// CD_CreateAlways - When opening a file:
726 /// * If it already exists, truncate it.
727 /// * If it does not already exist, create a new file.
729
730 /// CD_CreateNew - When opening a file:
731 /// * If it already exists, fail.
732 /// * If it does not already exist, create a new file.
734
735 /// CD_OpenExisting - When opening a file:
736 /// * If it already exists, open the file with the offset set to 0.
737 /// * If it does not already exist, fail.
739
740 /// CD_OpenAlways - When opening a file:
741 /// * If it already exists, open the file with the offset set to 0.
742 /// * If it does not already exist, create a new file.
744};
745
746enum FileAccess : unsigned {
749};
750
751enum OpenFlags : unsigned {
753
754 /// The file should be opened in text mode on platforms like z/OS that make
755 /// this distinction.
757
758 /// The file should use a carriage linefeed '\r\n'. This flag should only be
759 /// used with OF_Text. Only makes a difference on Windows.
761
762 /// The file should be opened in text mode and use a carriage linefeed '\r\n'.
763 /// This flag has the same functionality as OF_Text on z/OS but adds a
764 /// carriage linefeed on Windows.
766
767 /// The file should be opened in append mode.
769
770 /// The returned handle can be used for deleting the file. Only makes a
771 /// difference on windows.
773
774 /// When a child process is launched, this file should remain open in the
775 /// child process.
777
778 /// Force files Atime to be updated on access. Only makes a difference on
779 /// Windows.
781};
782
783/// Create a potentially unique file name but does not create it.
784///
785/// Generates a unique path suitable for a temporary file but does not
786/// open or create the file. The name is based on \a Model with '%'
787/// replaced by a random char in [0-9a-f]. If \a MakeAbsolute is true
788/// then the system's temp directory is prepended first. If \a MakeAbsolute
789/// is false the current directory will be used instead.
790///
791/// This function does not check if the file exists. If you want to be sure
792/// that the file does not yet exist, you should use enough '%' characters
793/// in your model to ensure this. Each '%' gives 4-bits of entropy so you can
794/// use 32 of them to get 128 bits of entropy.
795///
796/// Example: clang-%%-%%-%%-%%-%%.s => clang-a0-b1-c2-d3-e4.s
797///
798/// @param Model Name to base unique path off of.
799/// @param ResultPath Set to the file's path.
800/// @param MakeAbsolute Whether to use the system temp directory.
801void createUniquePath(const Twine &Model, SmallVectorImpl<char> &ResultPath,
802 bool MakeAbsolute);
803
804/// Create a uniquely named file.
805///
806/// Generates a unique path suitable for a temporary file and then opens it as a
807/// file. The name is based on \a Model with '%' replaced by a random char in
808/// [0-9a-f]. If \a Model is not an absolute path, the temporary file will be
809/// created in the current directory.
810///
811/// Example: clang-%%-%%-%%-%%-%%.s => clang-a0-b1-c2-d3-e4.s
812///
813/// This is an atomic operation. Either the file is created and opened, or the
814/// file system is left untouched.
815///
816/// The intended use is for files that are to be kept, possibly after
817/// renaming them. For example, when running 'clang -c foo.o', the file can
818/// be first created as foo-abc123.o and then renamed.
819///
820/// @param Model Name to base unique path off of.
821/// @param ResultFD Set to the opened file's file descriptor.
822/// @param ResultPath Set to the opened file's absolute path.
823/// @param Flags Set to the opened file's flags.
824/// @param Mode Set to the opened file's permissions.
825/// @returns errc::success if Result{FD,Path} have been successfully set,
826/// otherwise a platform-specific error_code.
827std::error_code createUniqueFile(const Twine &Model, int &ResultFD,
828 SmallVectorImpl<char> &ResultPath,
829 OpenFlags Flags = OF_None,
830 unsigned Mode = all_read | all_write);
831
832/// Simpler version for clients that don't want an open file. An empty
833/// file will still be created.
834std::error_code createUniqueFile(const Twine &Model,
835 SmallVectorImpl<char> &ResultPath,
836 unsigned Mode = all_read | all_write);
837
838/// Represents a temporary file.
839///
840/// The temporary file must be eventually discarded or given a final name and
841/// kept.
842///
843/// The destructor doesn't implicitly discard because there is no way to
844/// properly handle errors in a destructor.
845class TempFile {
846 bool Done = false;
848
849public:
850 /// This creates a temporary file with createUniqueFile and schedules it for
851 /// deletion with sys::RemoveFileOnSignal.
852 static Expected<TempFile> create(const Twine &Model,
853 unsigned Mode = all_read | all_write,
854 OpenFlags ExtraFlags = OF_None);
857
858 // Name of the temporary file.
859 std::string TmpName;
860
861 // The open file descriptor.
862 int FD = -1;
863
864#ifdef _WIN32
865 // Whether we need to manually remove the file on close.
866 bool RemoveOnClose = false;
867#endif
868
869 // Keep this with the given name.
870 Error keep(const Twine &Name);
871
872 // Keep this with the temporary name.
873 Error keep();
874
875 // Delete the file.
876 Error discard();
877
878 // This checks that keep or delete was called.
879 ~TempFile();
880};
881
882/// Create a file in the system temporary directory.
883///
884/// The filename is of the form prefix-random_chars.suffix. Since the directory
885/// is not know to the caller, Prefix and Suffix cannot have path separators.
886/// The files are created with mode 0600.
887///
888/// This should be used for things like a temporary .s that is removed after
889/// running the assembler.
890std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
891 int &ResultFD,
892 SmallVectorImpl<char> &ResultPath,
893 OpenFlags Flags = OF_None);
894
895/// Simpler version for clients that don't want an open file. An empty
896/// file will still be created.
897std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
898 SmallVectorImpl<char> &ResultPath,
899 OpenFlags Flags = OF_None);
900
901std::error_code createUniqueDirectory(const Twine &Prefix,
902 SmallVectorImpl<char> &ResultPath);
903
904/// Get a unique name, not currently exisiting in the filesystem. Subject
905/// to race conditions, prefer to use createUniqueFile instead.
906///
907/// Similar to createUniqueFile, but instead of creating a file only
908/// checks if it exists. This function is subject to race conditions, if you
909/// want to use the returned name to actually create a file, use
910/// createUniqueFile instead.
911std::error_code getPotentiallyUniqueFileName(const Twine &Model,
912 SmallVectorImpl<char> &ResultPath);
913
914/// Get a unique temporary file name, not currently exisiting in the
915/// filesystem. Subject to race conditions, prefer to use createTemporaryFile
916/// instead.
917///
918/// Similar to createTemporaryFile, but instead of creating a file only
919/// checks if it exists. This function is subject to race conditions, if you
920/// want to use the returned name to actually create a file, use
921/// createTemporaryFile instead.
922std::error_code
924 SmallVectorImpl<char> &ResultPath);
925
927 return OpenFlags(unsigned(A) | unsigned(B));
928}
929
931 A = A | B;
932 return A;
933}
934
936 return FileAccess(unsigned(A) | unsigned(B));
937}
938
940 A = A | B;
941 return A;
942}
943
944/// @brief Opens a file with the specified creation disposition, access mode,
945/// and flags and returns a file descriptor.
946///
947/// The caller is responsible for closing the file descriptor once they are
948/// finished with it.
949///
950/// @param Name The path of the file to open, relative or absolute.
951/// @param ResultFD If the file could be opened successfully, its descriptor
952/// is stored in this location. Otherwise, this is set to -1.
953/// @param Disp Value specifying the existing-file behavior.
954/// @param Access Value specifying whether to open the file in read, write, or
955/// read-write mode.
956/// @param Flags Additional flags.
957/// @param Mode The access permissions of the file, represented in octal.
958/// @returns errc::success if \a Name has been opened, otherwise a
959/// platform-specific error_code.
960std::error_code openFile(const Twine &Name, int &ResultFD,
962 OpenFlags Flags, unsigned Mode = 0666);
963
964/// @brief Opens a file with the specified creation disposition, access mode,
965/// and flags and returns a platform-specific file object.
966///
967/// The caller is responsible for closing the file object once they are
968/// finished with it.
969///
970/// @param Name The path of the file to open, relative or absolute.
971/// @param Disp Value specifying the existing-file behavior.
972/// @param Access Value specifying whether to open the file in read, write, or
973/// read-write mode.
974/// @param Flags Additional flags.
975/// @param Mode The access permissions of the file, represented in octal.
976/// @returns errc::success if \a Name has been opened, otherwise a
977/// platform-specific error_code.
980 unsigned Mode = 0666);
981
982/// Converts from a Posix file descriptor number to a native file handle.
983/// On Windows, this retreives the underlying handle. On non-Windows, this is a
984/// no-op.
986
987#ifndef _WIN32
988inline file_t convertFDToNativeFile(int FD) { return FD; }
989#endif
990
991/// Return an open handle to standard in. On Unix, this is typically FD 0.
992/// Returns kInvalidFile when the stream is closed.
994
995/// Return an open handle to standard out. On Unix, this is typically FD 1.
996/// Returns kInvalidFile when the stream is closed.
998
999/// Return an open handle to standard error. On Unix, this is typically FD 2.
1000/// Returns kInvalidFile when the stream is closed.
1002
1003/// Reads \p Buf.size() bytes from \p FileHandle into \p Buf. Returns the number
1004/// of bytes actually read. On Unix, this is equivalent to `return ::read(FD,
1005/// Buf.data(), Buf.size())`, with error reporting. Returns 0 when reaching EOF.
1006///
1007/// @param FileHandle File to read from.
1008/// @param Buf Buffer to read into.
1009/// @returns The number of bytes read, or error.
1011
1012/// Default chunk size for \a readNativeFileToEOF().
1013enum : size_t { DefaultReadChunkSize = 4 * 4096 };
1014
1015/// Reads from \p FileHandle until EOF, appending to \p Buffer in chunks of
1016/// size \p ChunkSize.
1017///
1018/// This calls \a readNativeFile() in a loop. On Error, previous chunks that
1019/// were read successfully are left in \p Buffer and returned.
1020///
1021/// Note: For reading the final chunk at EOF, \p Buffer's capacity needs extra
1022/// storage of \p ChunkSize.
1023///
1024/// \param FileHandle File to read from.
1025/// \param Buffer Where to put the file content.
1026/// \param ChunkSize Size of chunks.
1027/// \returns The error if EOF was not found.
1029 ssize_t ChunkSize = DefaultReadChunkSize);
1030
1031/// Reads \p Buf.size() bytes from \p FileHandle at offset \p Offset into \p
1032/// Buf. If 'pread' is available, this will use that, otherwise it will use
1033/// 'lseek'. Returns the number of bytes actually read. Returns 0 when reaching
1034/// EOF.
1035///
1036/// @param FileHandle File to read from.
1037/// @param Buf Buffer to read into.
1038/// @param Offset Offset into the file at which the read should occur.
1039/// @returns The number of bytes read, or error.
1043
1044/// @brief Opens the file with the given name in a write-only or read-write
1045/// mode, returning its open file descriptor. If the file does not exist, it
1046/// is created.
1047///
1048/// The caller is responsible for closing the file descriptor once they are
1049/// finished with it.
1050///
1051/// @param Name The path of the file to open, relative or absolute.
1052/// @param ResultFD If the file could be opened successfully, its descriptor
1053/// is stored in this location. Otherwise, this is set to -1.
1054/// @param Flags Additional flags used to determine whether the file should be
1055/// opened in, for example, read-write or in write-only mode.
1056/// @param Mode The access permissions of the file, represented in octal.
1057/// @returns errc::success if \a Name has been opened, otherwise a
1058/// platform-specific error_code.
1059inline std::error_code
1060openFileForWrite(const Twine &Name, int &ResultFD,
1062 OpenFlags Flags = OF_None, unsigned Mode = 0666) {
1063 return openFile(Name, ResultFD, Disp, FA_Write, Flags, Mode);
1064}
1065
1066/// @brief Opens the file with the given name in a write-only or read-write
1067/// mode, returning its open file descriptor. If the file does not exist, it
1068/// is created.
1069///
1070/// The caller is responsible for closing the freeing the file once they are
1071/// finished with it.
1072///
1073/// @param Name The path of the file to open, relative or absolute.
1074/// @param Flags Additional flags used to determine whether the file should be
1075/// opened in, for example, read-write or in write-only mode.
1076/// @param Mode The access permissions of the file, represented in octal.
1077/// @returns a platform-specific file descriptor if \a Name has been opened,
1078/// otherwise an error object.
1081 OpenFlags Flags,
1082 unsigned Mode = 0666) {
1083 return openNativeFile(Name, Disp, FA_Write, Flags, Mode);
1084}
1085
1086/// @brief Opens the file with the given name in a write-only or read-write
1087/// mode, returning its open file descriptor. If the file does not exist, it
1088/// is created.
1089///
1090/// The caller is responsible for closing the file descriptor once they are
1091/// finished with it.
1092///
1093/// @param Name The path of the file to open, relative or absolute.
1094/// @param ResultFD If the file could be opened successfully, its descriptor
1095/// is stored in this location. Otherwise, this is set to -1.
1096/// @param Flags Additional flags used to determine whether the file should be
1097/// opened in, for example, read-write or in write-only mode.
1098/// @param Mode The access permissions of the file, represented in octal.
1099/// @returns errc::success if \a Name has been opened, otherwise a
1100/// platform-specific error_code.
1101inline std::error_code openFileForReadWrite(const Twine &Name, int &ResultFD,
1103 OpenFlags Flags,
1104 unsigned Mode = 0666) {
1105 return openFile(Name, ResultFD, Disp, FA_Write | FA_Read, Flags, Mode);
1106}
1107
1108/// @brief Opens the file with the given name in a write-only or read-write
1109/// mode, returning its open file descriptor. If the file does not exist, it
1110/// is created.
1111///
1112/// The caller is responsible for closing the freeing the file once they are
1113/// finished with it.
1114///
1115/// @param Name The path of the file to open, relative or absolute.
1116/// @param Flags Additional flags used to determine whether the file should be
1117/// opened in, for example, read-write or in write-only mode.
1118/// @param Mode The access permissions of the file, represented in octal.
1119/// @returns a platform-specific file descriptor if \a Name has been opened,
1120/// otherwise an error object.
1123 OpenFlags Flags,
1124 unsigned Mode = 0666) {
1125 return openNativeFile(Name, Disp, FA_Write | FA_Read, Flags, Mode);
1126}
1127
1128/// @brief Opens the file with the given name in a read-only mode, returning
1129/// its open file descriptor.
1130///
1131/// The caller is responsible for closing the file descriptor once they are
1132/// finished with it.
1133///
1134/// @param Name The path of the file to open, relative or absolute.
1135/// @param ResultFD If the file could be opened successfully, its descriptor
1136/// is stored in this location. Otherwise, this is set to -1.
1137/// @param RealPath If nonnull, extra work is done to determine the real path
1138/// of the opened file, and that path is stored in this
1139/// location.
1140/// @returns errc::success if \a Name has been opened, otherwise a
1141/// platform-specific error_code.
1142std::error_code openFileForRead(const Twine &Name, int &ResultFD,
1143 OpenFlags Flags = OF_None,
1144 SmallVectorImpl<char> *RealPath = nullptr);
1145
1146/// @brief Opens the file with the given name in a read-only mode, returning
1147/// its open file descriptor.
1148///
1149/// The caller is responsible for closing the freeing the file once they are
1150/// finished with it.
1151///
1152/// @param Name The path of the file to open, relative or absolute.
1153/// @param RealPath If nonnull, extra work is done to determine the real path
1154/// of the opened file, and that path is stored in this
1155/// location.
1156/// @returns a platform-specific file descriptor if \a Name has been opened,
1157/// otherwise an error object.
1160 SmallVectorImpl<char> *RealPath = nullptr);
1161
1162/// Try to locks the file during the specified time.
1163///
1164/// This function implements advisory locking on entire file. If it returns
1165/// <em>errc::success</em>, the file is locked by the calling process. Until the
1166/// process unlocks the file by calling \a unlockFile, all attempts to lock the
1167/// same file will fail/block. The process that locked the file may assume that
1168/// none of other processes read or write this file, provided that all processes
1169/// lock the file prior to accessing its content.
1170///
1171/// @param FD The descriptor representing the file to lock.
1172/// @param Timeout Time in milliseconds that the process should wait before
1173/// reporting lock failure. Zero value means try to get lock only
1174/// once.
1175/// @returns errc::success if lock is successfully obtained,
1176/// errc::no_lock_available if the file cannot be locked, or platform-specific
1177/// error_code otherwise.
1178///
1179/// @note Care should be taken when using this function in a multithreaded
1180/// context, as it may not prevent other threads in the same process from
1181/// obtaining a lock on the same file, even if they are using a different file
1182/// descriptor.
1183std::error_code
1185 std::chrono::milliseconds Timeout = std::chrono::milliseconds(0));
1186
1187/// Lock the file.
1188///
1189/// This function acts as @ref tryLockFile but it waits infinitely.
1190std::error_code lockFile(int FD);
1191
1192/// Unlock the file.
1193///
1194/// @param FD The descriptor representing the file to unlock.
1195/// @returns errc::success if lock is successfully released or platform-specific
1196/// error_code otherwise.
1197std::error_code unlockFile(int FD);
1198
1199/// @brief Close the file object. This should be used instead of ::close for
1200/// portability. On error, the caller should assume the file is closed, as is
1201/// the case for Process::SafelyCloseFileDescriptor
1202///
1203/// @param F On input, this is the file to close. On output, the file is
1204/// set to kInvalidFile.
1205///
1206/// @returns An error code if closing the file failed. Typically, an error here
1207/// means that the filesystem may have failed to perform some buffered writes.
1208std::error_code closeFile(file_t &F);
1209
1210#ifdef LLVM_ON_UNIX
1211/// @brief Change ownership of a file.
1212///
1213/// @param Owner The owner of the file to change to.
1214/// @param Group The group of the file to change to.
1215/// @returns errc::success if successfully updated file ownership, otherwise an
1216/// error code is returned.
1217std::error_code changeFileOwnership(int FD, uint32_t Owner, uint32_t Group);
1218#endif
1219
1220/// RAII class that facilitates file locking.
1222 int FD; ///< Locked file handle.
1223 FileLocker(int FD) : FD(FD) {}
1225
1226public:
1227 FileLocker(const FileLocker &L) = delete;
1228 FileLocker(FileLocker &&L) : FD(L.FD) { L.FD = -1; }
1230 if (FD != -1)
1231 unlockFile(FD);
1232 }
1234 FD = L.FD;
1235 L.FD = -1;
1236 return *this;
1237 }
1238 FileLocker &operator=(const FileLocker &L) = delete;
1239 std::error_code unlock() {
1240 if (FD != -1) {
1241 std::error_code Result = unlockFile(FD);
1242 FD = -1;
1243 return Result;
1244 }
1245 return std::error_code();
1246 }
1247};
1248
1249std::error_code getUniqueID(const Twine Path, UniqueID &Result);
1250
1251/// Get disk space usage information.
1252///
1253/// Note: Users must be careful about "Time Of Check, Time Of Use" kind of bug.
1254/// Note: Windows reports results according to the quota allocated to the user.
1255///
1256/// @param Path Input path.
1257/// @returns a space_info structure filled with the capacity, free, and
1258/// available space on the device \a Path is on. A platform specific error_code
1259/// is returned on error.
1261
1262/// This class represents a memory mapped file. It is based on
1263/// boost::iostreams::mapped_file.
1265public:
1266 enum mapmode {
1267 readonly, ///< May only access map via const_data as read only.
1268 readwrite, ///< May access map via data and modify it. Written to path.
1269 priv ///< May modify via data, but changes are lost on destruction.
1271
1272private:
1273 /// Platform-specific mapping state.
1274 size_t Size = 0;
1275 void *Mapping = nullptr;
1276#ifdef _WIN32
1277 sys::fs::file_t FileHandle = nullptr;
1278#endif
1279 mapmode Mode = readonly;
1280
1281 void copyFrom(const mapped_file_region &Copied) {
1282 Size = Copied.Size;
1283 Mapping = Copied.Mapping;
1284#ifdef _WIN32
1285 FileHandle = Copied.FileHandle;
1286#endif
1287 Mode = Copied.Mode;
1288 }
1289
1290 void moveFromImpl(mapped_file_region &Moved) {
1291 copyFrom(Moved);
1292 Moved.copyFrom(mapped_file_region());
1293 }
1294
1295 void unmapImpl();
1296 void dontNeedImpl();
1297
1298 std::error_code init(sys::fs::file_t FD, uint64_t Offset, mapmode Mode);
1299
1300public:
1302 mapped_file_region(mapped_file_region &&Moved) { moveFromImpl(Moved); }
1304 unmap();
1305 moveFromImpl(Moved);
1306 return *this;
1307 }
1308
1311
1312 /// \param fd An open file descriptor to map. Does not take ownership of fd.
1314 std::error_code &ec);
1315
1316 ~mapped_file_region() { unmapImpl(); }
1317
1318 /// Check if this is a valid mapping.
1319 explicit operator bool() const { return Mapping; }
1320
1321 /// Unmap.
1322 void unmap() {
1323 unmapImpl();
1324 copyFrom(mapped_file_region());
1325 }
1326 void dontNeed() { dontNeedImpl(); }
1327
1328 size_t size() const;
1329 char *data() const;
1330
1331 /// Get a const view of the data. Modifying this memory has undefined
1332 /// behavior.
1333 const char *const_data() const;
1334
1335 /// \returns The minimum alignment offset must be.
1336 static int alignment();
1337};
1338
1339/// Return the path to the main executable, given the value of argv[0] from
1340/// program startup and the address of main itself. In extremis, this function
1341/// may fail and return an empty path.
1342std::string getMainExecutable(const char *argv0, void *MainExecAddr);
1343
1344/// @}
1345/// @name Iterators
1346/// @{
1347
1348/// directory_entry - A single entry in a directory.
1350 // FIXME: different platforms make different information available "for free"
1351 // when traversing a directory. The design of this class wraps most of the
1352 // information in basic_file_status, so on platforms where we can't populate
1353 // that whole structure, callers end up paying for a stat().
1354 // std::filesystem::directory_entry may be a better model.
1355 std::string Path;
1356 file_type Type = file_type::type_unknown; // Most platforms can provide this.
1357 bool FollowSymlinks = true; // Affects the behavior of status().
1358 basic_file_status Status; // If available.
1359
1360public:
1361 explicit directory_entry(const Twine &Path, bool FollowSymlinks = true,
1364 : Path(Path.str()), Type(Type), FollowSymlinks(FollowSymlinks),
1365 Status(Status) {}
1366
1367 directory_entry() = default;
1368
1369 void replace_filename(const Twine &Filename, file_type Type,
1371
1372 const std::string &path() const { return Path; }
1373 // Get basic information about entry file (a subset of fs::status()).
1374 // On most platforms this is a stat() call.
1375 // On windows the information was already retrieved from the directory.
1377 // Get the type of this file.
1378 // On most platforms (Linux/Mac/Windows/BSD), this was already retrieved.
1379 // On some platforms (e.g. Solaris) this is a stat() call.
1380 file_type type() const {
1382 return Type;
1383 auto S = status();
1384 return S ? S->type() : file_type::type_unknown;
1385 }
1386
1387 bool operator==(const directory_entry& RHS) const { return Path == RHS.Path; }
1388 bool operator!=(const directory_entry& RHS) const { return !(*this == RHS); }
1389 bool operator< (const directory_entry& RHS) const;
1390 bool operator<=(const directory_entry& RHS) const;
1391 bool operator> (const directory_entry& RHS) const;
1392 bool operator>=(const directory_entry& RHS) const;
1393};
1394
1395namespace detail {
1396
1397 struct DirIterState;
1398
1402
1403 /// Keeps state for the directory_iterator.
1407 }
1408
1409 intptr_t IterationHandle = 0;
1411 };
1412
1413} // end namespace detail
1414
1415/// directory_iterator - Iterates through the entries in path. There is no
1416/// operator++ because we need an error_code. If it's really needed we can make
1417/// it call report_fatal_error on error.
1419 std::shared_ptr<detail::DirIterState> State;
1420 bool FollowSymlinks = true;
1421
1422public:
1423 explicit directory_iterator(const Twine &path, std::error_code &ec,
1424 bool follow_symlinks = true)
1425 : FollowSymlinks(follow_symlinks) {
1426 State = std::make_shared<detail::DirIterState>();
1427 SmallString<128> path_storage;
1429 *State, path.toStringRef(path_storage), FollowSymlinks);
1430 }
1431
1432 explicit directory_iterator(const directory_entry &de, std::error_code &ec,
1433 bool follow_symlinks = true)
1434 : FollowSymlinks(follow_symlinks) {
1435 State = std::make_shared<detail::DirIterState>();
1437 *State, de.path(), FollowSymlinks);
1438 }
1439
1440 /// Construct end iterator.
1442
1443 // No operator++ because we need error_code.
1444 directory_iterator &increment(std::error_code &ec) {
1445 ec = directory_iterator_increment(*State);
1446 return *this;
1447 }
1448
1449 const directory_entry &operator*() const { return State->CurrentEntry; }
1450 const directory_entry *operator->() const { return &State->CurrentEntry; }
1451
1452 bool operator==(const directory_iterator &RHS) const {
1453 if (State == RHS.State)
1454 return true;
1455 if (!RHS.State)
1456 return State->CurrentEntry == directory_entry();
1457 if (!State)
1458 return RHS.State->CurrentEntry == directory_entry();
1459 return State->CurrentEntry == RHS.State->CurrentEntry;
1460 }
1461
1462 bool operator!=(const directory_iterator &RHS) const {
1463 return !(*this == RHS);
1464 }
1465};
1466
1467namespace detail {
1468
1469 /// Keeps state for the recursive_directory_iterator.
1471 std::vector<directory_iterator> Stack;
1472 uint16_t Level = 0;
1473 bool HasNoPushRequest = false;
1474 };
1475
1476} // end namespace detail
1477
1478/// recursive_directory_iterator - Same as directory_iterator except for it
1479/// recurses down into child directories.
1481 std::shared_ptr<detail::RecDirIterState> State;
1482 bool Follow;
1483
1484public:
1486 explicit recursive_directory_iterator(const Twine &path, std::error_code &ec,
1487 bool follow_symlinks = true)
1488 : State(std::make_shared<detail::RecDirIterState>()),
1489 Follow(follow_symlinks) {
1490 State->Stack.push_back(directory_iterator(path, ec, Follow));
1491 if (State->Stack.back() == directory_iterator())
1492 State.reset();
1493 }
1494
1495 // No operator++ because we need error_code.
1497 const directory_iterator end_itr = {};
1498
1499 if (State->HasNoPushRequest)
1500 State->HasNoPushRequest = false;
1501 else {
1502 file_type type = State->Stack.back()->type();
1503 if (type == file_type::symlink_file && Follow) {
1504 // Resolve the symlink: is it a directory to recurse into?
1505 ErrorOr<basic_file_status> status = State->Stack.back()->status();
1506 if (status)
1507 type = status->type();
1508 // Otherwise broken symlink, and we'll continue.
1509 }
1510 if (type == file_type::directory_file) {
1511 State->Stack.push_back(
1512 directory_iterator(*State->Stack.back(), ec, Follow));
1513 if (State->Stack.back() != end_itr) {
1514 ++State->Level;
1515 return *this;
1516 }
1517 State->Stack.pop_back();
1518 }
1519 }
1520
1521 while (!State->Stack.empty()
1522 && State->Stack.back().increment(ec) == end_itr) {
1523 State->Stack.pop_back();
1524 --State->Level;
1525 }
1526
1527 // Check if we are done. If so, create an end iterator.
1528 if (State->Stack.empty())
1529 State.reset();
1530
1531 return *this;
1532 }
1533
1534 const directory_entry &operator*() const { return *State->Stack.back(); }
1535 const directory_entry *operator->() const { return &*State->Stack.back(); }
1536
1537 // observers
1538 /// Gets the current level. Starting path is at level 0.
1539 int level() const { return State->Level; }
1540
1541 /// Returns true if no_push has been called for this directory_entry.
1542 bool no_push_request() const { return State->HasNoPushRequest; }
1543
1544 // modifiers
1545 /// Goes up one level if Level > 0.
1546 void pop() {
1547 assert(State && "Cannot pop an end iterator!");
1548 assert(State->Level > 0 && "Cannot pop an iterator with level < 1");
1549
1550 const directory_iterator end_itr = {};
1551 std::error_code ec;
1552 do {
1553 if (ec)
1554 report_fatal_error("Error incrementing directory iterator.");
1555 State->Stack.pop_back();
1556 --State->Level;
1557 } while (!State->Stack.empty()
1558 && State->Stack.back().increment(ec) == end_itr);
1559
1560 // Check if we are done. If so, create an end iterator.
1561 if (State->Stack.empty())
1562 State.reset();
1563 }
1564
1565 /// Does not go down into the current directory_entry.
1566 void no_push() { State->HasNoPushRequest = true; }
1567
1569 return State == RHS.State;
1570 }
1571
1573 return !(*this == RHS);
1574 }
1575};
1576
1577/// @}
1578
1579} // end namespace fs
1580} // end namespace sys
1581} // end namespace llvm
1582
1583#endif // LLVM_SUPPORT_FILESYSTEM_H
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
DXIL Resource Access
std::string Name
uint64_t Size
Provides ErrorOr<T> smart pointer.
amode Optimize addressing mode
#define F(x, y, z)
Definition: MD5.cpp:55
static cl::opt< RegAllocEvictionAdvisorAnalysis::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Development, "development", "for training")))
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallString class.
Value * RHS
Represents either an error or a value T.
Definition: ErrorOr.h:56
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
Tagged union holding either a T or a Error.
Definition: Error.h:481
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:310
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:573
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
StringRef toStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single StringRef if it can be represented as such.
Definition: Twine.h:492
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:460
RAII class that facilitates file locking.
Definition: FileSystem.h:1221
FileLocker & operator=(FileLocker &&L)
Definition: FileSystem.h:1233
FileLocker(const FileLocker &L)=delete
FileLocker & operator=(const FileLocker &L)=delete
FileLocker(FileLocker &&L)
Definition: FileSystem.h:1228
std::error_code unlock()
Definition: FileSystem.h:1239
Represents a temporary file.
Definition: FileSystem.h:845
TempFile & operator=(TempFile &&Other)
Definition: Path.cpp:1212
static Expected< TempFile > create(const Twine &Model, unsigned Mode=all_read|all_write, OpenFlags ExtraFlags=OF_None)
This creates a temporary file with createUniqueFile and schedules it for deletion with sys::RemoveFil...
Definition: Path.cpp:1325
Represents the result of a call to directory_iterator::status().
Definition: FileSystem.h:134
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:161
TimePoint getLastAccessedTime() const
The file access time as reported from the underlying file system.
basic_file_status(file_type Type)
Definition: FileSystem.h:158
TimePoint getLastModificationTime() const
The file modification time as reported from the underlying file system.
directory_entry - A single entry in a directory.
Definition: FileSystem.h:1349
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:1361
ErrorOr< basic_file_status > status() const
bool operator>=(const directory_entry &RHS) const
bool operator<(const directory_entry &RHS) const
bool operator<=(const directory_entry &RHS) const
bool operator==(const directory_entry &RHS) const
Definition: FileSystem.h:1387
bool operator!=(const directory_entry &RHS) const
Definition: FileSystem.h:1388
file_type type() const
Definition: FileSystem.h:1380
bool operator>(const directory_entry &RHS) const
const std::string & path() const
Definition: FileSystem.h:1372
directory_entry()=default
void replace_filename(const Twine &Filename, file_type Type, basic_file_status Status=basic_file_status())
Definition: Path.cpp:1142
directory_iterator - Iterates through the entries in path.
Definition: FileSystem.h:1418
bool operator!=(const directory_iterator &RHS) const
Definition: FileSystem.h:1462
directory_iterator(const directory_entry &de, std::error_code &ec, bool follow_symlinks=true)
Definition: FileSystem.h:1432
directory_iterator(const Twine &path, std::error_code &ec, bool follow_symlinks=true)
Definition: FileSystem.h:1423
directory_iterator()=default
Construct end iterator.
const directory_entry & operator*() const
Definition: FileSystem.h:1449
directory_iterator & increment(std::error_code &ec)
Definition: FileSystem.h:1444
bool operator==(const directory_iterator &RHS) const
Definition: FileSystem.h:1452
const directory_entry * operator->() const
Definition: FileSystem.h:1450
Represents the result of a call to sys::fs::status().
Definition: FileSystem.h:223
uint32_t getLinkCount() const
UniqueID getUniqueID() const
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:242
friend bool equivalent(file_status A, file_status B)
Do file_status's represent the same thing?
file_status(file_type Type)
Definition: FileSystem.h:239
This class represents a memory mapped file.
Definition: FileSystem.h:1264
mapped_file_region(mapped_file_region &&Moved)
Definition: FileSystem.h:1302
@ priv
May modify via data, but changes are lost on destruction.
Definition: FileSystem.h:1269
@ readonly
May only access map via const_data as read only.
Definition: FileSystem.h:1267
@ readwrite
May access map via data and modify it. Written to path.
Definition: FileSystem.h:1268
mapped_file_region & operator=(mapped_file_region &&Moved)
Definition: FileSystem.h:1303
mapped_file_region(sys::fs::file_t fd, mapmode mode, size_t length, uint64_t offset, std::error_code &ec)
const char * const_data() const
Get a const view of the data.
Definition: Path.cpp:1169
mapped_file_region(const mapped_file_region &)=delete
mapped_file_region & operator=(const mapped_file_region &)=delete
recursive_directory_iterator - Same as directory_iterator except for it recurses down into child dire...
Definition: FileSystem.h:1480
void pop()
Goes up one level if Level > 0.
Definition: FileSystem.h:1546
bool operator==(const recursive_directory_iterator &RHS) const
Definition: FileSystem.h:1568
void no_push()
Does not go down into the current directory_entry.
Definition: FileSystem.h:1566
int level() const
Gets the current level. Starting path is at level 0.
Definition: FileSystem.h:1539
const directory_entry * operator->() const
Definition: FileSystem.h:1535
recursive_directory_iterator & increment(std::error_code &ec)
Definition: FileSystem.h:1496
recursive_directory_iterator(const Twine &path, std::error_code &ec, bool follow_symlinks=true)
Definition: FileSystem.h:1486
const directory_entry & operator*() const
Definition: FileSystem.h:1534
bool no_push_request() const
Returns true if no_push has been called for this directory_entry.
Definition: FileSystem.h:1542
bool operator!=(const recursive_directory_iterator &RHS) const
Definition: FileSystem.h:1572
std::error_code directory_iterator_construct(DirIterState &, StringRef, bool)
std::error_code directory_iterator_destruct(DirIterState &)
std::error_code directory_iterator_increment(DirIterState &)
std::error_code unlockFile(int FD)
Unlock the file.
std::string getMainExecutable(const char *argv0, void *MainExecAddr)
Return the path to the main executable, given the value of argv[0] from program startup and the addre...
std::error_code remove_directories(const Twine &path, bool IgnoreErrors=true)
Recursively delete a directory.
bool is_regular_file(const basic_file_status &status)
Does status represent a regular file?
Definition: Path.cpp:1104
bool is_symlink_file(const basic_file_status &status)
Does status represent a symlink file?
Definition: Path.cpp:1116
perms operator&(perms l, perms r)
Definition: FileSystem.h:113
std::error_code create_link(const Twine &to, const Twine &from)
Create a link from from to to.
bool equivalent(file_status A, file_status B)
Do file_status's represent the same thing?
void make_absolute(const Twine &current_directory, SmallVectorImpl< char > &path)
Make path an absolute path.
Definition: Path.cpp:906
perms operator|(perms l, perms r)
Definition: FileSystem.h:109
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:1101
const file_t kInvalidFile
std::error_code real_path(const Twine &path, SmallVectorImpl< char > &output, bool expand_tilde=false)
Collapse all .
Error readNativeFileToEOF(file_t FileHandle, SmallVectorImpl< char > &Buffer, ssize_t ChunkSize=DefaultReadChunkSize)
Reads from FileHandle until EOF, appending to Buffer in chunks of size ChunkSize.
Definition: Path.cpp:1174
std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout=std::chrono::milliseconds(0))
Try to locks the file during the specified time.
perms & operator&=(perms &l, perms r)
Definition: FileSystem.h:121
Expected< size_t > readNativeFile(file_t FileHandle, MutableArrayRef< char > Buf)
Reads Buf.size() bytes from FileHandle into Buf.
ErrorOr< perms > getPermissions(const Twine &Path)
Get file permissions.
Definition: Path.cpp:1151
bool can_write(const Twine &Path)
Can we write this file?
Definition: FileSystem.h:472
std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime, TimePoint<> ModificationTime)
Set the file modification and access time.
perms operator~(perms x)
Definition: FileSystem.h:125
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...
std::error_code resize_file_before_mapping_readwrite(int FD, uint64_t Size)
Resize FD to Size before mapping mapped_file_region::readwrite.
Definition: FileSystem.h:413
std::error_code closeFile(file_t &F)
Close the file object.
std::error_code getPotentiallyUniqueFileName(const Twine &Model, SmallVectorImpl< char > &ResultPath)
Get a unique name, not currently exisiting in the filesystem.
Definition: Path.cpp:893
file_t getStdoutHandle()
Return an open handle to standard out.
std::error_code rename(const Twine &from, const Twine &to)
Rename from to to.
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 expand_tilde(const Twine &path, SmallVectorImpl< char > &output)
Expands ~ expressions to the user's home directory.
Expected< size_t > readNativeFileSlice(file_t FileHandle, MutableArrayRef< char > Buf, uint64_t Offset)
Reads Buf.size() bytes from FileHandle at offset Offset into Buf.
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:1128
std::error_code access(const Twine &Path, AccessMode Mode)
Can the file be accessed?
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:900
perms & operator|=(perms &l, perms r)
Definition: FileSystem.h:117
std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
bool exists(const basic_file_status &status)
Does file exist?
Definition: Path.cpp:1077
@ OF_Delete
The returned handle can be used for deleting the file.
Definition: FileSystem.h:772
@ OF_ChildInherit
When a child process is launched, this file should remain open in the child process.
Definition: FileSystem.h:776
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
Definition: FileSystem.h:756
@ OF_CRLF
The file should use a carriage linefeed '\r '.
Definition: FileSystem.h:760
@ OF_UpdateAtime
Force files Atime to be updated on access.
Definition: FileSystem.h:780
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
Definition: FileSystem.h:765
@ OF_Append
The file should be opened in append mode.
Definition: FileSystem.h:768
file_type
An enumeration for the file system's view of the type.
Definition: FileSystem.h:63
std::error_code changeFileOwnership(int FD, uint32_t Owner, uint32_t Group)
Change ownership of a file.
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:1079
std::error_code create_hard_link(const Twine &to, const Twine &from)
Create a hard link from from to to, or return an error.
std::error_code getUniqueID(const Twine Path, UniqueID &Result)
Definition: Path.cpp:787
std::error_code createUniqueFile(const Twine &Model, int &ResultFD, SmallVectorImpl< char > &ResultPath, OpenFlags Flags=OF_None, unsigned Mode=all_read|all_write)
Create a uniquely named file.
Definition: Path.cpp:822
std::error_code resize_file(int FD, uint64_t Size)
Resize path to size.
std::error_code create_directory(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create the directory in path.
std::error_code lockFile(int FD)
Lock the file.
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
@ CD_OpenExisting
CD_OpenExisting - When opening a file:
Definition: FileSystem.h:738
@ CD_OpenAlways
CD_OpenAlways - When opening a file:
Definition: FileSystem.h:743
@ CD_CreateAlways
CD_CreateAlways - When opening a file:
Definition: FileSystem.h:728
@ CD_CreateNew
CD_CreateNew - When opening a file:
Definition: FileSystem.h:733
std::error_code set_current_path(const Twine &path)
Set the current path.
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:1121
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...
void createUniquePath(const Twine &Model, SmallVectorImpl< char > &ResultPath, bool MakeAbsolute)
Create a potentially unique file name but does not create it.
Definition: Path.cpp:796
ErrorOr< space_info > disk_space(const Twine &Path)
Get disk space usage information.
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:1060
file_t getStderrHandle()
Return an open handle to standard error.
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:967
bool status_known(const basic_file_status &s)
Is status available?
Definition: Path.cpp:1081
std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD, SmallVectorImpl< char > &ResultPath, OpenFlags Flags=OF_None)
Create a file in the system temporary directory.
Definition: Path.cpp:863
file_type get_file_type(const Twine &Path, bool Follow=true)
Does status represent a directory?
Definition: Path.cpp:1085
std::error_code is_local(const Twine &path, bool &result)
Is the file mounted on a local filesystem?
std::error_code copy_file(const Twine &From, const Twine &To)
Copy the contents of From to To.
Definition: Path.cpp:1016
std::error_code createUniqueDirectory(const Twine &Prefix, SmallVectorImpl< char > &ResultPath)
Definition: Path.cpp:885
file_t convertFDToNativeFile(int FD)
Converts from a Posix file descriptor number to a native file handle.
Definition: FileSystem.h:988
bool can_execute(const Twine &Path)
Can we execute this file?
unsigned getUmask()
Get file creation mode mask of the process.
ErrorOr< MD5::MD5Result > md5_contents(int FD)
Compute an MD5 hash of a file's contents.
Definition: Path.cpp:1047
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.
std::error_code file_size(const Twine &Path, uint64_t &Result)
Get file size.
Definition: FileSystem.h:686
std::error_code current_path(SmallVectorImpl< char > &result)
Get the current path.
std::error_code setPermissions(const Twine &Path, perms Permissions)
Set file permissions.
bool is_directory(const basic_file_status &status)
Does status represent a directory?
Definition: Path.cpp:1092
file_t getStdinHandle()
Return an open handle to standard in.
std::chrono::time_point< std::chrono::system_clock, D > TimePoint
A time point on the system clock.
Definition: Chrono.h:34
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:480
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
@ Other
Any other memory.
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
Keeps state for the directory_iterator.
Definition: FileSystem.h:1404
Keeps state for the recursive_directory_iterator.
Definition: FileSystem.h:1470
std::vector< directory_iterator > Stack
Definition: FileSystem.h:1471
space_info - Self explanatory.
Definition: FileSystem.h:77