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