blob: 2483aae046f5679aef7de09b1532ea9dc24b70e7 [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- llvm/Support/FileSystem.h - File System OS Concept -------*- C++ -*-===//
2//
Andrew Walbran16937d02019-10-22 13:54:20 +01003// 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
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01006//
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
29#include "llvm/ADT/SmallString.h"
30#include "llvm/ADT/StringRef.h"
31#include "llvm/ADT/Twine.h"
Andrew Scullcdfcccc2018-10-05 20:58:37 +010032#include "llvm/Config/llvm-config.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010033#include "llvm/Support/Chrono.h"
34#include "llvm/Support/Error.h"
35#include "llvm/Support/ErrorHandling.h"
36#include "llvm/Support/ErrorOr.h"
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020037#include "llvm/Support/FileSystem/UniqueID.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010038#include "llvm/Support/MD5.h"
39#include <cassert>
40#include <cstdint>
41#include <ctime>
42#include <memory>
43#include <stack>
44#include <string>
45#include <system_error>
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010046#include <vector>
47
48#ifdef HAVE_SYS_STAT_H
49#include <sys/stat.h>
50#endif
51
52namespace llvm {
53namespace sys {
54namespace fs {
55
Andrew Scullcdfcccc2018-10-05 20:58:37 +010056#if defined(_WIN32)
57// A Win32 HANDLE is a typedef of void*
58using file_t = void *;
59#else
60using file_t = int;
61#endif
62
63extern const file_t kInvalidFile;
64
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010065/// An enumeration for the file system's view of the type.
66enum class file_type {
67 status_error,
68 file_not_found,
69 regular_file,
70 directory_file,
71 symlink_file,
72 block_file,
73 character_file,
74 fifo_file,
75 socket_file,
76 type_unknown
77};
78
79/// space_info - Self explanatory.
80struct space_info {
81 uint64_t capacity;
82 uint64_t free;
83 uint64_t available;
84};
85
86enum perms {
87 no_perms = 0,
88 owner_read = 0400,
89 owner_write = 0200,
90 owner_exe = 0100,
91 owner_all = owner_read | owner_write | owner_exe,
92 group_read = 040,
93 group_write = 020,
94 group_exe = 010,
95 group_all = group_read | group_write | group_exe,
96 others_read = 04,
97 others_write = 02,
98 others_exe = 01,
99 others_all = others_read | others_write | others_exe,
100 all_read = owner_read | group_read | others_read,
101 all_write = owner_write | group_write | others_write,
102 all_exe = owner_exe | group_exe | others_exe,
103 all_all = owner_all | group_all | others_all,
104 set_uid_on_exe = 04000,
105 set_gid_on_exe = 02000,
106 sticky_bit = 01000,
107 all_perms = all_all | set_uid_on_exe | set_gid_on_exe | sticky_bit,
108 perms_not_known = 0xFFFF
109};
110
111// Helper functions so that you can use & and | to manipulate perms bits:
112inline perms operator|(perms l, perms r) {
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 return static_cast<perms>(static_cast<unsigned short>(l) &
118 static_cast<unsigned short>(r));
119}
120inline perms &operator|=(perms &l, perms r) {
121 l = l | r;
122 return l;
123}
124inline perms &operator&=(perms &l, perms r) {
125 l = l & r;
126 return l;
127}
128inline perms operator~(perms x) {
129 // Avoid UB by explicitly truncating the (unsigned) ~ result.
130 return static_cast<perms>(
131 static_cast<unsigned short>(~static_cast<unsigned short>(x)));
132}
133
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100134/// Represents the result of a call to directory_iterator::status(). This is a
135/// subset of the information returned by a regular sys::fs::status() call, and
136/// represents the information provided by Windows FileFirstFile/FindNextFile.
137class basic_file_status {
138protected:
139 #if defined(LLVM_ON_UNIX)
140 time_t fs_st_atime = 0;
141 time_t fs_st_mtime = 0;
Andrew Walbran16937d02019-10-22 13:54:20 +0100142 uint32_t fs_st_atime_nsec = 0;
143 uint32_t fs_st_mtime_nsec = 0;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100144 uid_t fs_st_uid = 0;
145 gid_t fs_st_gid = 0;
146 off_t fs_st_size = 0;
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100147 #elif defined (_WIN32)
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100148 uint32_t LastAccessedTimeHigh = 0;
149 uint32_t LastAccessedTimeLow = 0;
150 uint32_t LastWriteTimeHigh = 0;
151 uint32_t LastWriteTimeLow = 0;
152 uint32_t FileSizeHigh = 0;
153 uint32_t FileSizeLow = 0;
154 #endif
155 file_type Type = file_type::status_error;
156 perms Perms = perms_not_known;
157
158public:
159 basic_file_status() = default;
160
161 explicit basic_file_status(file_type Type) : Type(Type) {}
162
163 #if defined(LLVM_ON_UNIX)
Andrew Walbran16937d02019-10-22 13:54:20 +0100164 basic_file_status(file_type Type, perms Perms, time_t ATime,
165 uint32_t ATimeNSec, time_t MTime, uint32_t MTimeNSec,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100166 uid_t UID, gid_t GID, off_t Size)
Andrew Walbran16937d02019-10-22 13:54:20 +0100167 : fs_st_atime(ATime), fs_st_mtime(MTime),
168 fs_st_atime_nsec(ATimeNSec), fs_st_mtime_nsec(MTimeNSec),
169 fs_st_uid(UID), fs_st_gid(GID),
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100170 fs_st_size(Size), Type(Type), Perms(Perms) {}
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100171#elif defined(_WIN32)
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100172 basic_file_status(file_type Type, perms Perms, uint32_t LastAccessTimeHigh,
173 uint32_t LastAccessTimeLow, uint32_t LastWriteTimeHigh,
174 uint32_t LastWriteTimeLow, uint32_t FileSizeHigh,
175 uint32_t FileSizeLow)
176 : LastAccessedTimeHigh(LastAccessTimeHigh),
177 LastAccessedTimeLow(LastAccessTimeLow),
178 LastWriteTimeHigh(LastWriteTimeHigh),
179 LastWriteTimeLow(LastWriteTimeLow), FileSizeHigh(FileSizeHigh),
180 FileSizeLow(FileSizeLow), Type(Type), Perms(Perms) {}
181 #endif
182
183 // getters
184 file_type type() const { return Type; }
185 perms permissions() const { return Perms; }
Andrew Walbran16937d02019-10-22 13:54:20 +0100186
187 /// The file access time as reported from the underlying file system.
188 ///
189 /// Also see comments on \c getLastModificationTime() related to the precision
190 /// of the returned value.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100191 TimePoint<> getLastAccessedTime() const;
Andrew Walbran16937d02019-10-22 13:54:20 +0100192
193 /// The file modification time as reported from the underlying file system.
194 ///
195 /// The returned value allows for nanosecond precision but the actual
196 /// resolution is an implementation detail of the underlying file system.
197 /// There is no guarantee for what kind of resolution you can expect, the
198 /// resolution can differ across platforms and even across mountpoints on the
199 /// same machine.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100200 TimePoint<> getLastModificationTime() const;
201
202 #if defined(LLVM_ON_UNIX)
203 uint32_t getUser() const { return fs_st_uid; }
204 uint32_t getGroup() const { return fs_st_gid; }
205 uint64_t getSize() const { return fs_st_size; }
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100206 #elif defined (_WIN32)
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100207 uint32_t getUser() const {
208 return 9999; // Not applicable to Windows, so...
209 }
210
211 uint32_t getGroup() const {
212 return 9999; // Not applicable to Windows, so...
213 }
214
215 uint64_t getSize() const {
216 return (uint64_t(FileSizeHigh) << 32) + FileSizeLow;
217 }
218 #endif
219
220 // setters
221 void type(file_type v) { Type = v; }
222 void permissions(perms p) { Perms = p; }
223};
224
225/// Represents the result of a call to sys::fs::status().
226class file_status : public basic_file_status {
227 friend bool equivalent(file_status A, file_status B);
228
229 #if defined(LLVM_ON_UNIX)
230 dev_t fs_st_dev = 0;
231 nlink_t fs_st_nlinks = 0;
232 ino_t fs_st_ino = 0;
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100233 #elif defined (_WIN32)
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100234 uint32_t NumLinks = 0;
235 uint32_t VolumeSerialNumber = 0;
236 uint32_t FileIndexHigh = 0;
237 uint32_t FileIndexLow = 0;
238 #endif
239
240public:
241 file_status() = default;
242
243 explicit file_status(file_type Type) : basic_file_status(Type) {}
244
245 #if defined(LLVM_ON_UNIX)
246 file_status(file_type Type, perms Perms, dev_t Dev, nlink_t Links, ino_t Ino,
Andrew Walbran16937d02019-10-22 13:54:20 +0100247 time_t ATime, uint32_t ATimeNSec,
248 time_t MTime, uint32_t MTimeNSec,
249 uid_t UID, gid_t GID, off_t Size)
250 : basic_file_status(Type, Perms, ATime, ATimeNSec, MTime, MTimeNSec,
251 UID, GID, Size),
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100252 fs_st_dev(Dev), fs_st_nlinks(Links), fs_st_ino(Ino) {}
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100253 #elif defined(_WIN32)
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100254 file_status(file_type Type, perms Perms, uint32_t LinkCount,
255 uint32_t LastAccessTimeHigh, uint32_t LastAccessTimeLow,
256 uint32_t LastWriteTimeHigh, uint32_t LastWriteTimeLow,
257 uint32_t VolumeSerialNumber, uint32_t FileSizeHigh,
258 uint32_t FileSizeLow, uint32_t FileIndexHigh,
259 uint32_t FileIndexLow)
260 : basic_file_status(Type, Perms, LastAccessTimeHigh, LastAccessTimeLow,
261 LastWriteTimeHigh, LastWriteTimeLow, FileSizeHigh,
262 FileSizeLow),
263 NumLinks(LinkCount), VolumeSerialNumber(VolumeSerialNumber),
264 FileIndexHigh(FileIndexHigh), FileIndexLow(FileIndexLow) {}
265 #endif
266
267 UniqueID getUniqueID() const;
268 uint32_t getLinkCount() const;
269};
270
271/// @}
272/// @name Physical Operators
273/// @{
274
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100275/// Make \a path an absolute path.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100276///
277/// Makes \a path absolute using the \a current_directory if it is not already.
278/// An empty \a path will result in the \a current_directory.
279///
280/// /absolute/path => /absolute/path
281/// relative/../path => <current-directory>/relative/../path
282///
283/// @param path A path that is modified to be an absolute path.
Andrew Walbran16937d02019-10-22 13:54:20 +0100284void make_absolute(const Twine &current_directory, SmallVectorImpl<char> &path);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100285
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100286/// Make \a path an absolute path.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100287///
288/// Makes \a path absolute using the current directory if it is not already. An
289/// empty \a path will result in the current directory.
290///
291/// /absolute/path => /absolute/path
292/// relative/../path => <current-directory>/relative/../path
293///
294/// @param path A path that is modified to be an absolute path.
295/// @returns errc::success if \a path has been made absolute, otherwise a
296/// platform-specific error_code.
297std::error_code make_absolute(SmallVectorImpl<char> &path);
298
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100299/// Create all the non-existent directories in path.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100300///
301/// @param path Directories to create.
302/// @returns errc::success if is_directory(path), otherwise a platform
303/// specific error_code. If IgnoreExisting is false, also returns
304/// error if the directory already existed.
305std::error_code create_directories(const Twine &path,
306 bool IgnoreExisting = true,
307 perms Perms = owner_all | group_all);
308
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100309/// Create the directory in path.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100310///
311/// @param path Directory to create.
312/// @returns errc::success if is_directory(path), otherwise a platform
313/// specific error_code. If IgnoreExisting is false, also returns
314/// error if the directory already existed.
315std::error_code create_directory(const Twine &path, bool IgnoreExisting = true,
316 perms Perms = owner_all | group_all);
317
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100318/// Create a link from \a from to \a to.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100319///
320/// The link may be a soft or a hard link, depending on the platform. The caller
321/// may not assume which one. Currently on windows it creates a hard link since
322/// soft links require extra privileges. On unix, it creates a soft link since
323/// hard links don't work on SMB file systems.
324///
325/// @param to The path to hard link to.
326/// @param from The path to hard link from. This is created.
327/// @returns errc::success if the link was created, otherwise a platform
328/// specific error_code.
329std::error_code create_link(const Twine &to, const Twine &from);
330
331/// Create a hard link from \a from to \a to, or return an error.
332///
333/// @param to The path to hard link to.
334/// @param from The path to hard link from. This is created.
335/// @returns errc::success if the link was created, otherwise a platform
336/// specific error_code.
337std::error_code create_hard_link(const Twine &to, const Twine &from);
338
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100339/// Collapse all . and .. patterns, resolve all symlinks, and optionally
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100340/// expand ~ expressions to the user's home directory.
341///
342/// @param path The path to resolve.
343/// @param output The location to store the resolved path.
344/// @param expand_tilde If true, resolves ~ expressions to the user's home
345/// directory.
346std::error_code real_path(const Twine &path, SmallVectorImpl<char> &output,
347 bool expand_tilde = false);
348
Andrew Walbran16937d02019-10-22 13:54:20 +0100349/// Expands ~ expressions to the user's home directory. On Unix ~user
350/// directories are resolved as well.
351///
352/// @param path The path to resolve.
353void expand_tilde(const Twine &path, SmallVectorImpl<char> &output);
354
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100355/// Get the current path.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100356///
357/// @param result Holds the current path on return.
358/// @returns errc::success if the current path has been stored in result,
359/// otherwise a platform-specific error_code.
360std::error_code current_path(SmallVectorImpl<char> &result);
361
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100362/// Set the current path.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100363///
364/// @param path The path to set.
365/// @returns errc::success if the current path was successfully set,
366/// otherwise a platform-specific error_code.
367std::error_code set_current_path(const Twine &path);
368
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100369/// Remove path. Equivalent to POSIX remove().
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100370///
371/// @param path Input path.
372/// @returns errc::success if path has been removed or didn't exist, otherwise a
373/// platform-specific error code. If IgnoreNonExisting is false, also
374/// returns error if the file didn't exist.
375std::error_code remove(const Twine &path, bool IgnoreNonExisting = true);
376
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100377/// Recursively delete a directory.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100378///
379/// @param path Input path.
380/// @returns errc::success if path has been removed or didn't exist, otherwise a
381/// platform-specific error code.
382std::error_code remove_directories(const Twine &path, bool IgnoreErrors = true);
383
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100384/// Rename \a from to \a to.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100385///
386/// Files are renamed as if by POSIX rename(), except that on Windows there may
387/// be a short interval of time during which the destination file does not
388/// exist.
389///
390/// @param from The path to rename from.
391/// @param to The path to rename to. This is created.
392std::error_code rename(const Twine &from, const Twine &to);
393
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100394/// Copy the contents of \a From to \a To.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100395///
396/// @param From The path to copy from.
397/// @param To The path to copy to. This is created.
398std::error_code copy_file(const Twine &From, const Twine &To);
399
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100400/// Copy the contents of \a From to \a To.
401///
402/// @param From The path to copy from.
403/// @param ToFD The open file descriptor of the destination file.
404std::error_code copy_file(const Twine &From, int ToFD);
405
406/// Resize path to size. File is resized as if by POSIX truncate().
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100407///
408/// @param FD Input file descriptor.
409/// @param Size Size to resize to.
410/// @returns errc::success if \a path has been resized to \a size, otherwise a
411/// platform-specific error_code.
412std::error_code resize_file(int FD, uint64_t Size);
413
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100414/// Compute an MD5 hash of a file's contents.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100415///
416/// @param FD Input file descriptor.
417/// @returns An MD5Result with the hash computed, if successful, otherwise a
418/// std::error_code.
419ErrorOr<MD5::MD5Result> md5_contents(int FD);
420
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100421/// Version of compute_md5 that doesn't require an open file descriptor.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100422ErrorOr<MD5::MD5Result> md5_contents(const Twine &Path);
423
424/// @}
425/// @name Physical Observers
426/// @{
427
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100428/// Does file exist?
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100429///
430/// @param status A basic_file_status previously returned from stat.
431/// @returns True if the file represented by status exists, false if it does
432/// not.
433bool exists(const basic_file_status &status);
434
435enum class AccessMode { Exist, Write, Execute };
436
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100437/// Can the file be accessed?
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100438///
439/// @param Path Input path.
440/// @returns errc::success if the path can be accessed, otherwise a
441/// platform-specific error_code.
442std::error_code access(const Twine &Path, AccessMode Mode);
443
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100444/// Does file exist?
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100445///
446/// @param Path Input path.
447/// @returns True if it exists, false otherwise.
448inline bool exists(const Twine &Path) {
449 return !access(Path, AccessMode::Exist);
450}
451
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100452/// Can we execute this file?
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100453///
454/// @param Path Input path.
455/// @returns True if we can execute it, false otherwise.
456bool can_execute(const Twine &Path);
457
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100458/// Can we write this file?
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100459///
460/// @param Path Input path.
461/// @returns True if we can write to it, false otherwise.
462inline bool can_write(const Twine &Path) {
463 return !access(Path, AccessMode::Write);
464}
465
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100466/// Do file_status's represent the same thing?
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100467///
468/// @param A Input file_status.
469/// @param B Input file_status.
470///
471/// assert(status_known(A) || status_known(B));
472///
473/// @returns True if A and B both represent the same file system entity, false
474/// otherwise.
475bool equivalent(file_status A, file_status B);
476
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100477/// Do paths represent the same thing?
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100478///
479/// assert(status_known(A) || status_known(B));
480///
481/// @param A Input path A.
482/// @param B Input path B.
483/// @param result Set to true if stat(A) and stat(B) have the same device and
484/// inode (or equivalent).
485/// @returns errc::success if result has been successfully set, otherwise a
486/// platform-specific error_code.
487std::error_code equivalent(const Twine &A, const Twine &B, bool &result);
488
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100489/// Simpler version of equivalent for clients that don't need to
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100490/// differentiate between an error and false.
491inline bool equivalent(const Twine &A, const Twine &B) {
492 bool result;
493 return !equivalent(A, B, result) && result;
494}
495
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100496/// Is the file mounted on a local filesystem?
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100497///
498/// @param path Input path.
499/// @param result Set to true if \a path is on fixed media such as a hard disk,
500/// false if it is not.
501/// @returns errc::success if result has been successfully set, otherwise a
502/// platform specific error_code.
503std::error_code is_local(const Twine &path, bool &result);
504
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100505/// Version of is_local accepting an open file descriptor.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100506std::error_code is_local(int FD, bool &result);
507
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100508/// Simpler version of is_local for clients that don't need to
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100509/// differentiate between an error and false.
510inline bool is_local(const Twine &Path) {
511 bool Result;
512 return !is_local(Path, Result) && Result;
513}
514
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100515/// Simpler version of is_local accepting an open file descriptor for
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100516/// clients that don't need to differentiate between an error and false.
517inline bool is_local(int FD) {
518 bool Result;
519 return !is_local(FD, Result) && Result;
520}
521
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100522/// Does status represent a directory?
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100523///
524/// @param Path The path to get the type of.
525/// @param Follow For symbolic links, indicates whether to return the file type
526/// of the link itself, or of the target.
527/// @returns A value from the file_type enumeration indicating the type of file.
528file_type get_file_type(const Twine &Path, bool Follow = true);
529
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100530/// Does status represent a directory?
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100531///
532/// @param status A basic_file_status previously returned from status.
533/// @returns status.type() == file_type::directory_file.
534bool is_directory(const basic_file_status &status);
535
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100536/// Is path a directory?
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100537///
538/// @param path Input path.
539/// @param result Set to true if \a path is a directory (after following
540/// symlinks, false if it is not. Undefined otherwise.
541/// @returns errc::success if result has been successfully set, otherwise a
542/// platform-specific error_code.
543std::error_code is_directory(const Twine &path, bool &result);
544
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100545/// Simpler version of is_directory for clients that don't need to
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100546/// differentiate between an error and false.
547inline bool is_directory(const Twine &Path) {
548 bool Result;
549 return !is_directory(Path, Result) && Result;
550}
551
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100552/// Does status represent a regular file?
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100553///
554/// @param status A basic_file_status previously returned from status.
555/// @returns status_known(status) && status.type() == file_type::regular_file.
556bool is_regular_file(const basic_file_status &status);
557
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100558/// Is path a regular file?
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100559///
560/// @param path Input path.
561/// @param result Set to true if \a path is a regular file (after following
562/// symlinks), false if it is not. Undefined otherwise.
563/// @returns errc::success if result has been successfully set, otherwise a
564/// platform-specific error_code.
565std::error_code is_regular_file(const Twine &path, bool &result);
566
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100567/// Simpler version of is_regular_file for clients that don't need to
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100568/// differentiate between an error and false.
569inline bool is_regular_file(const Twine &Path) {
570 bool Result;
571 if (is_regular_file(Path, Result))
572 return false;
573 return Result;
574}
575
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100576/// Does status represent a symlink file?
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100577///
578/// @param status A basic_file_status previously returned from status.
579/// @returns status_known(status) && status.type() == file_type::symlink_file.
580bool is_symlink_file(const basic_file_status &status);
581
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100582/// Is path a symlink file?
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100583///
584/// @param path Input path.
585/// @param result Set to true if \a path is a symlink file, false if it is not.
586/// Undefined otherwise.
587/// @returns errc::success if result has been successfully set, otherwise a
588/// platform-specific error_code.
589std::error_code is_symlink_file(const Twine &path, bool &result);
590
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100591/// Simpler version of is_symlink_file for clients that don't need to
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100592/// differentiate between an error and false.
593inline bool is_symlink_file(const Twine &Path) {
594 bool Result;
595 if (is_symlink_file(Path, Result))
596 return false;
597 return Result;
598}
599
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100600/// Does this status represent something that exists but is not a
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100601/// directory or regular file?
602///
603/// @param status A basic_file_status previously returned from status.
604/// @returns exists(s) && !is_regular_file(s) && !is_directory(s)
605bool is_other(const basic_file_status &status);
606
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100607/// Is path something that exists but is not a directory,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100608/// regular file, or symlink?
609///
610/// @param path Input path.
611/// @param result Set to true if \a path exists, but is not a directory, regular
612/// file, or a symlink, false if it does not. Undefined otherwise.
613/// @returns errc::success if result has been successfully set, otherwise a
614/// platform-specific error_code.
615std::error_code is_other(const Twine &path, bool &result);
616
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100617/// Get file status as if by POSIX stat().
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100618///
619/// @param path Input path.
620/// @param result Set to the file status.
621/// @param follow When true, follows symlinks. Otherwise, the symlink itself is
622/// statted.
623/// @returns errc::success if result has been successfully set, otherwise a
624/// platform-specific error_code.
625std::error_code status(const Twine &path, file_status &result,
626 bool follow = true);
627
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100628/// A version for when a file descriptor is already available.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100629std::error_code status(int FD, file_status &Result);
630
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100631#ifdef _WIN32
632/// A version for when a file descriptor is already available.
633std::error_code status(file_t FD, file_status &Result);
634#endif
635
636/// Get file creation mode mask of the process.
637///
638/// @returns Mask reported by umask(2)
639/// @note There is no umask on Windows. This function returns 0 always
640/// on Windows. This function does not return an error_code because
641/// umask(2) never fails. It is not thread safe.
642unsigned getUmask();
643
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100644/// Set file permissions.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100645///
646/// @param Path File to set permissions on.
647/// @param Permissions New file permissions.
648/// @returns errc::success if the permissions were successfully set, otherwise
649/// a platform-specific error_code.
650/// @note On Windows, all permissions except *_write are ignored. Using any of
651/// owner_write, group_write, or all_write will make the file writable.
652/// Otherwise, the file will be marked as read-only.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200653std::error_code setPermissions(const Twine &Path, perms Permissions);
654
655/// Vesion of setPermissions accepting a file descriptor.
656/// TODO Delete the path based overload once we implement the FD based overload
657/// on Windows.
658std::error_code setPermissions(int FD, perms Permissions);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100659
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100660/// Get file permissions.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100661///
662/// @param Path File to get permissions from.
663/// @returns the permissions if they were successfully retrieved, otherwise a
664/// platform-specific error_code.
665/// @note On Windows, if the file does not have the FILE_ATTRIBUTE_READONLY
666/// attribute, all_all will be returned. Otherwise, all_read | all_exe
667/// will be returned.
668ErrorOr<perms> getPermissions(const Twine &Path);
669
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100670/// Get file size.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100671///
672/// @param Path Input path.
673/// @param Result Set to the size of the file in \a Path.
674/// @returns errc::success if result has been successfully set, otherwise a
675/// platform-specific error_code.
676inline std::error_code file_size(const Twine &Path, uint64_t &Result) {
677 file_status Status;
678 std::error_code EC = status(Path, Status);
679 if (EC)
680 return EC;
681 Result = Status.getSize();
682 return std::error_code();
683}
684
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100685/// Set the file modification and access time.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100686///
687/// @returns errc::success if the file times were successfully set, otherwise a
688/// platform-specific error_code or errc::function_not_supported on
689/// platforms where the functionality isn't available.
Andrew Scull0372a572018-11-16 15:47:06 +0000690std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
691 TimePoint<> ModificationTime);
692
693/// Simpler version that sets both file modification and access time to the same
694/// time.
695inline std::error_code setLastAccessAndModificationTime(int FD,
696 TimePoint<> Time) {
697 return setLastAccessAndModificationTime(FD, Time, Time);
698}
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100699
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100700/// Is status available?
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100701///
702/// @param s Input file status.
703/// @returns True if status() != status_error.
704bool status_known(const basic_file_status &s);
705
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100706/// Is status available?
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100707///
708/// @param path Input path.
709/// @param result Set to true if status() != status_error.
710/// @returns errc::success if result has been successfully set, otherwise a
711/// platform-specific error_code.
712std::error_code status_known(const Twine &path, bool &result);
713
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100714enum CreationDisposition : unsigned {
715 /// CD_CreateAlways - When opening a file:
716 /// * If it already exists, truncate it.
717 /// * If it does not already exist, create a new file.
718 CD_CreateAlways = 0,
719
720 /// CD_CreateNew - When opening a file:
721 /// * If it already exists, fail.
722 /// * If it does not already exist, create a new file.
723 CD_CreateNew = 1,
724
Andrew Scull0372a572018-11-16 15:47:06 +0000725 /// CD_OpenExisting - When opening a file:
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100726 /// * If it already exists, open the file with the offset set to 0.
727 /// * If it does not already exist, fail.
728 CD_OpenExisting = 2,
729
730 /// CD_OpenAlways - When opening a file:
731 /// * If it already exists, open the file with the offset set to 0.
732 /// * If it does not already exist, create a new file.
733 CD_OpenAlways = 3,
734};
735
736enum FileAccess : unsigned {
737 FA_Read = 1,
738 FA_Write = 2,
739};
740
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100741enum OpenFlags : unsigned {
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100742 OF_None = 0,
743 F_None = 0, // For compatibility
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100744
745 /// The file should be opened in text mode on platforms that make this
746 /// distinction.
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100747 OF_Text = 1,
748 F_Text = 1, // For compatibility
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100749
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100750 /// The file should be opened in append mode.
751 OF_Append = 2,
752 F_Append = 2, // For compatibility
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100753
754 /// Delete the file on close. Only makes a difference on windows.
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100755 OF_Delete = 4,
756
757 /// When a child process is launched, this file should remain open in the
758 /// child process.
759 OF_ChildInherit = 8,
760
761 /// Force files Atime to be updated on access. Only makes a difference on windows.
762 OF_UpdateAtime = 16,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100763};
764
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100765/// Create a potentially unique file name but does not create it.
766///
767/// Generates a unique path suitable for a temporary file but does not
768/// open or create the file. The name is based on \a Model with '%'
769/// replaced by a random char in [0-9a-f]. If \a MakeAbsolute is true
770/// then the system's temp directory is prepended first. If \a MakeAbsolute
771/// is false the current directory will be used instead.
772///
773/// This function does not check if the file exists. If you want to be sure
774/// that the file does not yet exist, you should use use enough '%' characters
775/// in your model to ensure this. Each '%' gives 4-bits of entropy so you can
776/// use 32 of them to get 128 bits of entropy.
777///
778/// Example: clang-%%-%%-%%-%%-%%.s => clang-a0-b1-c2-d3-e4.s
779///
780/// @param Model Name to base unique path off of.
781/// @param ResultPath Set to the file's path.
782/// @param MakeAbsolute Whether to use the system temp directory.
783void createUniquePath(const Twine &Model, SmallVectorImpl<char> &ResultPath,
784 bool MakeAbsolute);
785
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100786/// Create a uniquely named file.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100787///
788/// Generates a unique path suitable for a temporary file and then opens it as a
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100789/// file. The name is based on \a Model with '%' replaced by a random char in
790/// [0-9a-f]. If \a Model is not an absolute path, the temporary file will be
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100791/// created in the current directory.
792///
793/// Example: clang-%%-%%-%%-%%-%%.s => clang-a0-b1-c2-d3-e4.s
794///
795/// This is an atomic operation. Either the file is created and opened, or the
796/// file system is left untouched.
797///
798/// The intended use is for files that are to be kept, possibly after
799/// renaming them. For example, when running 'clang -c foo.o', the file can
800/// be first created as foo-abc123.o and then renamed.
801///
802/// @param Model Name to base unique path off of.
803/// @param ResultFD Set to the opened file's file descriptor.
804/// @param ResultPath Set to the opened file's absolute path.
805/// @returns errc::success if Result{FD,Path} have been successfully set,
806/// otherwise a platform-specific error_code.
807std::error_code createUniqueFile(const Twine &Model, int &ResultFD,
808 SmallVectorImpl<char> &ResultPath,
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100809 unsigned Mode = all_read | all_write);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100810
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100811/// Simpler version for clients that don't want an open file. An empty
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100812/// file will still be created.
813std::error_code createUniqueFile(const Twine &Model,
814 SmallVectorImpl<char> &ResultPath,
815 unsigned Mode = all_read | all_write);
816
817/// Represents a temporary file.
818///
819/// The temporary file must be eventually discarded or given a final name and
820/// kept.
821///
822/// The destructor doesn't implicitly discard because there is no way to
823/// properly handle errors in a destructor.
824class TempFile {
825 bool Done = false;
826 TempFile(StringRef Name, int FD);
827
828public:
829 /// This creates a temporary file with createUniqueFile and schedules it for
830 /// deletion with sys::RemoveFileOnSignal.
831 static Expected<TempFile> create(const Twine &Model,
832 unsigned Mode = all_read | all_write);
833 TempFile(TempFile &&Other);
834 TempFile &operator=(TempFile &&Other);
835
836 // Name of the temporary file.
837 std::string TmpName;
838
839 // The open file descriptor.
840 int FD = -1;
841
842 // Keep this with the given name.
843 Error keep(const Twine &Name);
844
845 // Keep this with the temporary name.
846 Error keep();
847
848 // Delete the file.
849 Error discard();
850
851 // This checks that keep or delete was called.
852 ~TempFile();
853};
854
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100855/// Create a file in the system temporary directory.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100856///
857/// The filename is of the form prefix-random_chars.suffix. Since the directory
858/// is not know to the caller, Prefix and Suffix cannot have path separators.
859/// The files are created with mode 0600.
860///
861/// This should be used for things like a temporary .s that is removed after
862/// running the assembler.
863std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
864 int &ResultFD,
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100865 SmallVectorImpl<char> &ResultPath);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100866
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100867/// Simpler version for clients that don't want an open file. An empty
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100868/// file will still be created.
869std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
870 SmallVectorImpl<char> &ResultPath);
871
872std::error_code createUniqueDirectory(const Twine &Prefix,
873 SmallVectorImpl<char> &ResultPath);
874
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100875/// Get a unique name, not currently exisiting in the filesystem. Subject
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100876/// to race conditions, prefer to use createUniqueFile instead.
877///
878/// Similar to createUniqueFile, but instead of creating a file only
879/// checks if it exists. This function is subject to race conditions, if you
880/// want to use the returned name to actually create a file, use
881/// createUniqueFile instead.
882std::error_code getPotentiallyUniqueFileName(const Twine &Model,
883 SmallVectorImpl<char> &ResultPath);
884
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100885/// Get a unique temporary file name, not currently exisiting in the
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100886/// filesystem. Subject to race conditions, prefer to use createTemporaryFile
887/// instead.
888///
889/// Similar to createTemporaryFile, but instead of creating a file only
890/// checks if it exists. This function is subject to race conditions, if you
891/// want to use the returned name to actually create a file, use
892/// createTemporaryFile instead.
893std::error_code
894getPotentiallyUniqueTempFileName(const Twine &Prefix, StringRef Suffix,
895 SmallVectorImpl<char> &ResultPath);
896
897inline OpenFlags operator|(OpenFlags A, OpenFlags B) {
898 return OpenFlags(unsigned(A) | unsigned(B));
899}
900
901inline OpenFlags &operator|=(OpenFlags &A, OpenFlags B) {
902 A = A | B;
903 return A;
904}
905
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100906inline FileAccess operator|(FileAccess A, FileAccess B) {
907 return FileAccess(unsigned(A) | unsigned(B));
908}
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100909
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100910inline FileAccess &operator|=(FileAccess &A, FileAccess B) {
911 A = A | B;
912 return A;
913}
914
915/// @brief Opens a file with the specified creation disposition, access mode,
916/// and flags and returns a file descriptor.
917///
918/// The caller is responsible for closing the file descriptor once they are
919/// finished with it.
920///
921/// @param Name The path of the file to open, relative or absolute.
922/// @param ResultFD If the file could be opened successfully, its descriptor
923/// is stored in this location. Otherwise, this is set to -1.
924/// @param Disp Value specifying the existing-file behavior.
925/// @param Access Value specifying whether to open the file in read, write, or
926/// read-write mode.
927/// @param Flags Additional flags.
928/// @param Mode The access permissions of the file, represented in octal.
929/// @returns errc::success if \a Name has been opened, otherwise a
930/// platform-specific error_code.
931std::error_code openFile(const Twine &Name, int &ResultFD,
932 CreationDisposition Disp, FileAccess Access,
933 OpenFlags Flags, unsigned Mode = 0666);
934
935/// @brief Opens a file with the specified creation disposition, access mode,
936/// and flags and returns a platform-specific file object.
937///
938/// The caller is responsible for closing the file object once they are
939/// finished with it.
940///
941/// @param Name The path of the file to open, relative or absolute.
942/// @param Disp Value specifying the existing-file behavior.
943/// @param Access Value specifying whether to open the file in read, write, or
944/// read-write mode.
945/// @param Flags Additional flags.
946/// @param Mode The access permissions of the file, represented in octal.
947/// @returns errc::success if \a Name has been opened, otherwise a
948/// platform-specific error_code.
949Expected<file_t> openNativeFile(const Twine &Name, CreationDisposition Disp,
950 FileAccess Access, OpenFlags Flags,
951 unsigned Mode = 0666);
952
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100953/// Converts from a Posix file descriptor number to a native file handle.
954/// On Windows, this retreives the underlying handle. On non-Windows, this is a
955/// no-op.
956file_t convertFDToNativeFile(int FD);
957
958#ifndef _WIN32
959inline file_t convertFDToNativeFile(int FD) { return FD; }
960#endif
961
962/// Return an open handle to standard in. On Unix, this is typically FD 0.
963/// Returns kInvalidFile when the stream is closed.
964file_t getStdinHandle();
965
966/// Return an open handle to standard out. On Unix, this is typically FD 1.
967/// Returns kInvalidFile when the stream is closed.
968file_t getStdoutHandle();
969
970/// Return an open handle to standard error. On Unix, this is typically FD 2.
971/// Returns kInvalidFile when the stream is closed.
972file_t getStderrHandle();
973
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200974/// Reads \p Buf.size() bytes from \p FileHandle into \p Buf. Returns the number
975/// of bytes actually read. On Unix, this is equivalent to `return ::read(FD,
976/// Buf.data(), Buf.size())`, with error reporting. Returns 0 when reaching EOF.
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100977///
978/// @param FileHandle File to read from.
979/// @param Buf Buffer to read into.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200980/// @returns The number of bytes read, or error.
981Expected<size_t> readNativeFile(file_t FileHandle, MutableArrayRef<char> Buf);
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100982
983/// Reads \p Buf.size() bytes from \p FileHandle at offset \p Offset into \p
984/// Buf. If 'pread' is available, this will use that, otherwise it will use
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200985/// 'lseek'. Returns the number of bytes actually read. Returns 0 when reaching
986/// EOF.
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100987///
988/// @param FileHandle File to read from.
989/// @param Buf Buffer to read into.
990/// @param Offset Offset into the file at which the read should occur.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200991/// @returns The number of bytes read, or error.
992Expected<size_t> readNativeFileSlice(file_t FileHandle,
993 MutableArrayRef<char> Buf,
994 uint64_t Offset);
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100995
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100996/// @brief Opens the file with the given name in a write-only or read-write
997/// mode, returning its open file descriptor. If the file does not exist, it
998/// is created.
999///
1000/// The caller is responsible for closing the file descriptor once they are
1001/// finished with it.
1002///
1003/// @param Name The path of the file to open, relative or absolute.
1004/// @param ResultFD If the file could be opened successfully, its descriptor
1005/// is stored in this location. Otherwise, this is set to -1.
1006/// @param Flags Additional flags used to determine whether the file should be
1007/// opened in, for example, read-write or in write-only mode.
1008/// @param Mode The access permissions of the file, represented in octal.
1009/// @returns errc::success if \a Name has been opened, otherwise a
1010/// platform-specific error_code.
1011inline std::error_code
1012openFileForWrite(const Twine &Name, int &ResultFD,
1013 CreationDisposition Disp = CD_CreateAlways,
1014 OpenFlags Flags = OF_None, unsigned Mode = 0666) {
1015 return openFile(Name, ResultFD, Disp, FA_Write, Flags, Mode);
1016}
1017
1018/// @brief Opens the file with the given name in a write-only or read-write
1019/// mode, returning its open file descriptor. If the file does not exist, it
1020/// is created.
1021///
1022/// The caller is responsible for closing the freeing the file once they are
1023/// finished with it.
1024///
1025/// @param Name The path of the file to open, relative or absolute.
1026/// @param Flags Additional flags used to determine whether the file should be
1027/// opened in, for example, read-write or in write-only mode.
1028/// @param Mode The access permissions of the file, represented in octal.
1029/// @returns a platform-specific file descriptor if \a Name has been opened,
1030/// otherwise an error object.
1031inline Expected<file_t> openNativeFileForWrite(const Twine &Name,
1032 CreationDisposition Disp,
1033 OpenFlags Flags,
1034 unsigned Mode = 0666) {
1035 return openNativeFile(Name, Disp, FA_Write, Flags, Mode);
1036}
1037
1038/// @brief Opens the file with the given name in a write-only or read-write
1039/// mode, returning its open file descriptor. If the file does not exist, it
1040/// is created.
1041///
1042/// The caller is responsible for closing the file descriptor once they are
1043/// finished with it.
1044///
1045/// @param Name The path of the file to open, relative or absolute.
1046/// @param ResultFD If the file could be opened successfully, its descriptor
1047/// is stored in this location. Otherwise, this is set to -1.
1048/// @param Flags Additional flags used to determine whether the file should be
1049/// opened in, for example, read-write or in write-only mode.
1050/// @param Mode The access permissions of the file, represented in octal.
1051/// @returns errc::success if \a Name has been opened, otherwise a
1052/// platform-specific error_code.
1053inline std::error_code openFileForReadWrite(const Twine &Name, int &ResultFD,
1054 CreationDisposition Disp,
1055 OpenFlags Flags,
1056 unsigned Mode = 0666) {
1057 return openFile(Name, ResultFD, Disp, FA_Write | FA_Read, Flags, Mode);
1058}
1059
1060/// @brief Opens the file with the given name in a write-only or read-write
1061/// mode, returning its open file descriptor. If the file does not exist, it
1062/// is created.
1063///
1064/// The caller is responsible for closing the freeing the file once they are
1065/// finished with it.
1066///
1067/// @param Name The path of the file to open, relative or absolute.
1068/// @param Flags Additional flags used to determine whether the file should be
1069/// opened in, for example, read-write or in write-only mode.
1070/// @param Mode The access permissions of the file, represented in octal.
1071/// @returns a platform-specific file descriptor if \a Name has been opened,
1072/// otherwise an error object.
1073inline Expected<file_t> openNativeFileForReadWrite(const Twine &Name,
1074 CreationDisposition Disp,
1075 OpenFlags Flags,
1076 unsigned Mode = 0666) {
1077 return openNativeFile(Name, Disp, FA_Write | FA_Read, Flags, Mode);
1078}
1079
1080/// @brief Opens the file with the given name in a read-only mode, returning
1081/// its open file descriptor.
1082///
1083/// The caller is responsible for closing the file descriptor once they are
1084/// finished with it.
1085///
1086/// @param Name The path of the file to open, relative or absolute.
1087/// @param ResultFD If the file could be opened successfully, its descriptor
1088/// is stored in this location. Otherwise, this is set to -1.
1089/// @param RealPath If nonnull, extra work is done to determine the real path
1090/// of the opened file, and that path is stored in this
1091/// location.
1092/// @returns errc::success if \a Name has been opened, otherwise a
1093/// platform-specific error_code.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001094std::error_code openFileForRead(const Twine &Name, int &ResultFD,
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001095 OpenFlags Flags = OF_None,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001096 SmallVectorImpl<char> *RealPath = nullptr);
1097
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001098/// @brief Opens the file with the given name in a read-only mode, returning
1099/// its open file descriptor.
1100///
1101/// The caller is responsible for closing the freeing the file once they are
1102/// finished with it.
1103///
1104/// @param Name The path of the file to open, relative or absolute.
1105/// @param RealPath If nonnull, extra work is done to determine the real path
1106/// of the opened file, and that path is stored in this
1107/// location.
1108/// @returns a platform-specific file descriptor if \a Name has been opened,
1109/// otherwise an error object.
1110Expected<file_t>
1111openNativeFileForRead(const Twine &Name, OpenFlags Flags = OF_None,
1112 SmallVectorImpl<char> *RealPath = nullptr);
1113
Olivier Deprezf4ef2d02021-04-20 13:36:24 +02001114/// Try to locks the file during the specified time.
1115///
1116/// This function implements advisory locking on entire file. If it returns
1117/// <em>errc::success</em>, the file is locked by the calling process. Until the
1118/// process unlocks the file by calling \a unlockFile, all attempts to lock the
1119/// same file will fail/block. The process that locked the file may assume that
1120/// none of other processes read or write this file, provided that all processes
1121/// lock the file prior to accessing its content.
1122///
1123/// @param FD The descriptor representing the file to lock.
1124/// @param Timeout Time in milliseconds that the process should wait before
1125/// reporting lock failure. Zero value means try to get lock only
1126/// once.
1127/// @returns errc::success if lock is successfully obtained,
1128/// errc::no_lock_available if the file cannot be locked, or platform-specific
1129/// error_code otherwise.
1130///
1131/// @note Care should be taken when using this function in a multithreaded
1132/// context, as it may not prevent other threads in the same process from
1133/// obtaining a lock on the same file, even if they are using a different file
1134/// descriptor.
1135std::error_code
1136tryLockFile(int FD,
1137 std::chrono::milliseconds Timeout = std::chrono::milliseconds(0));
1138
1139/// Lock the file.
1140///
1141/// This function acts as @ref tryLockFile but it waits infinitely.
1142std::error_code lockFile(int FD);
1143
1144/// Unlock the file.
1145///
1146/// @param FD The descriptor representing the file to unlock.
1147/// @returns errc::success if lock is successfully released or platform-specific
1148/// error_code otherwise.
1149std::error_code unlockFile(int FD);
1150
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001151/// @brief Close the file object. This should be used instead of ::close for
Andrew Walbran3d2c1972020-04-07 12:24:26 +01001152/// portability. On error, the caller should assume the file is closed, as is
1153/// the case for Process::SafelyCloseFileDescriptor
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001154///
1155/// @param F On input, this is the file to close. On output, the file is
1156/// set to kInvalidFile.
Andrew Walbran3d2c1972020-04-07 12:24:26 +01001157///
1158/// @returns An error code if closing the file failed. Typically, an error here
1159/// means that the filesystem may have failed to perform some buffered writes.
1160std::error_code closeFile(file_t &F);
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001161
Olivier Deprezf4ef2d02021-04-20 13:36:24 +02001162/// RAII class that facilitates file locking.
1163class FileLocker {
1164 int FD; ///< Locked file handle.
1165 FileLocker(int FD) : FD(FD) {}
1166 friend class llvm::raw_fd_ostream;
1167
1168public:
1169 FileLocker(const FileLocker &L) = delete;
1170 FileLocker(FileLocker &&L) : FD(L.FD) { L.FD = -1; }
1171 ~FileLocker() {
1172 if (FD != -1)
1173 unlockFile(FD);
1174 }
1175 FileLocker &operator=(FileLocker &&L) {
1176 FD = L.FD;
1177 L.FD = -1;
1178 return *this;
1179 }
1180 FileLocker &operator=(const FileLocker &L) = delete;
1181 std::error_code unlock() {
1182 if (FD != -1) {
1183 std::error_code Result = unlockFile(FD);
1184 FD = -1;
1185 return Result;
1186 }
1187 return std::error_code();
1188 }
1189};
1190
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001191std::error_code getUniqueID(const Twine Path, UniqueID &Result);
1192
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001193/// Get disk space usage information.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001194///
1195/// Note: Users must be careful about "Time Of Check, Time Of Use" kind of bug.
1196/// Note: Windows reports results according to the quota allocated to the user.
1197///
1198/// @param Path Input path.
1199/// @returns a space_info structure filled with the capacity, free, and
1200/// available space on the device \a Path is on. A platform specific error_code
1201/// is returned on error.
1202ErrorOr<space_info> disk_space(const Twine &Path);
1203
1204/// This class represents a memory mapped file. It is based on
1205/// boost::iostreams::mapped_file.
1206class mapped_file_region {
1207public:
1208 enum mapmode {
1209 readonly, ///< May only access map via const_data as read only.
1210 readwrite, ///< May access map via data and modify it. Written to path.
1211 priv ///< May modify via data, but changes are lost on destruction.
1212 };
1213
1214private:
1215 /// Platform-specific mapping state.
1216 size_t Size;
1217 void *Mapping;
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001218#ifdef _WIN32
Andrew Walbran3d2c1972020-04-07 12:24:26 +01001219 sys::fs::file_t FileHandle;
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001220#endif
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001221 mapmode Mode;
1222
Andrew Walbran3d2c1972020-04-07 12:24:26 +01001223 std::error_code init(sys::fs::file_t FD, uint64_t Offset, mapmode Mode);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001224
1225public:
1226 mapped_file_region() = delete;
1227 mapped_file_region(mapped_file_region&) = delete;
1228 mapped_file_region &operator =(mapped_file_region&) = delete;
1229
Andrew Walbran3d2c1972020-04-07 12:24:26 +01001230 /// \param fd An open file descriptor to map. Does not take ownership of fd.
1231 mapped_file_region(sys::fs::file_t fd, mapmode mode, size_t length, uint64_t offset,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001232 std::error_code &ec);
1233
1234 ~mapped_file_region();
1235
1236 size_t size() const;
1237 char *data() const;
1238
1239 /// Get a const view of the data. Modifying this memory has undefined
1240 /// behavior.
1241 const char *const_data() const;
1242
1243 /// \returns The minimum alignment offset must be.
1244 static int alignment();
1245};
1246
1247/// Return the path to the main executable, given the value of argv[0] from
1248/// program startup and the address of main itself. In extremis, this function
1249/// may fail and return an empty path.
1250std::string getMainExecutable(const char *argv0, void *MainExecAddr);
1251
1252/// @}
1253/// @name Iterators
1254/// @{
1255
Andrew Scull0372a572018-11-16 15:47:06 +00001256/// directory_entry - A single entry in a directory.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001257class directory_entry {
Andrew Scull0372a572018-11-16 15:47:06 +00001258 // FIXME: different platforms make different information available "for free"
1259 // when traversing a directory. The design of this class wraps most of the
1260 // information in basic_file_status, so on platforms where we can't populate
1261 // that whole structure, callers end up paying for a stat().
1262 // std::filesystem::directory_entry may be a better model.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001263 std::string Path;
Olivier Deprezf4ef2d02021-04-20 13:36:24 +02001264 file_type Type = file_type::type_unknown; // Most platforms can provide this.
1265 bool FollowSymlinks = true; // Affects the behavior of status().
1266 basic_file_status Status; // If available.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001267
1268public:
Andrew Scull0372a572018-11-16 15:47:06 +00001269 explicit directory_entry(const Twine &Path, bool FollowSymlinks = true,
1270 file_type Type = file_type::type_unknown,
1271 basic_file_status Status = basic_file_status())
1272 : Path(Path.str()), Type(Type), FollowSymlinks(FollowSymlinks),
1273 Status(Status) {}
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001274
1275 directory_entry() = default;
1276
Andrew Scull0372a572018-11-16 15:47:06 +00001277 void replace_filename(const Twine &Filename, file_type Type,
1278 basic_file_status Status = basic_file_status());
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001279
1280 const std::string &path() const { return Path; }
Andrew Scull0372a572018-11-16 15:47:06 +00001281 // Get basic information about entry file (a subset of fs::status()).
1282 // On most platforms this is a stat() call.
1283 // On windows the information was already retrieved from the directory.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001284 ErrorOr<basic_file_status> status() const;
Andrew Scull0372a572018-11-16 15:47:06 +00001285 // Get the type of this file.
1286 // On most platforms (Linux/Mac/Windows/BSD), this was already retrieved.
1287 // On some platforms (e.g. Solaris) this is a stat() call.
1288 file_type type() const {
1289 if (Type != file_type::type_unknown)
1290 return Type;
1291 auto S = status();
1292 return S ? S->type() : file_type::type_unknown;
1293 }
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001294
Andrew Scull0372a572018-11-16 15:47:06 +00001295 bool operator==(const directory_entry& RHS) const { return Path == RHS.Path; }
1296 bool operator!=(const directory_entry& RHS) const { return !(*this == RHS); }
1297 bool operator< (const directory_entry& RHS) const;
1298 bool operator<=(const directory_entry& RHS) const;
1299 bool operator> (const directory_entry& RHS) const;
1300 bool operator>=(const directory_entry& RHS) const;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001301};
1302
1303namespace detail {
1304
1305 struct DirIterState;
1306
1307 std::error_code directory_iterator_construct(DirIterState &, StringRef, bool);
1308 std::error_code directory_iterator_increment(DirIterState &);
1309 std::error_code directory_iterator_destruct(DirIterState &);
1310
1311 /// Keeps state for the directory_iterator.
1312 struct DirIterState {
1313 ~DirIterState() {
1314 directory_iterator_destruct(*this);
1315 }
1316
1317 intptr_t IterationHandle = 0;
1318 directory_entry CurrentEntry;
1319 };
1320
1321} // end namespace detail
1322
1323/// directory_iterator - Iterates through the entries in path. There is no
1324/// operator++ because we need an error_code. If it's really needed we can make
1325/// it call report_fatal_error on error.
1326class directory_iterator {
1327 std::shared_ptr<detail::DirIterState> State;
1328 bool FollowSymlinks = true;
1329
1330public:
1331 explicit directory_iterator(const Twine &path, std::error_code &ec,
1332 bool follow_symlinks = true)
1333 : FollowSymlinks(follow_symlinks) {
1334 State = std::make_shared<detail::DirIterState>();
1335 SmallString<128> path_storage;
1336 ec = detail::directory_iterator_construct(
1337 *State, path.toStringRef(path_storage), FollowSymlinks);
1338 }
1339
1340 explicit directory_iterator(const directory_entry &de, std::error_code &ec,
1341 bool follow_symlinks = true)
1342 : FollowSymlinks(follow_symlinks) {
1343 State = std::make_shared<detail::DirIterState>();
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001344 ec = detail::directory_iterator_construct(
1345 *State, de.path(), FollowSymlinks);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001346 }
1347
1348 /// Construct end iterator.
1349 directory_iterator() = default;
1350
1351 // No operator++ because we need error_code.
1352 directory_iterator &increment(std::error_code &ec) {
1353 ec = directory_iterator_increment(*State);
1354 return *this;
1355 }
1356
1357 const directory_entry &operator*() const { return State->CurrentEntry; }
1358 const directory_entry *operator->() const { return &State->CurrentEntry; }
1359
1360 bool operator==(const directory_iterator &RHS) const {
1361 if (State == RHS.State)
1362 return true;
1363 if (!RHS.State)
1364 return State->CurrentEntry == directory_entry();
1365 if (!State)
1366 return RHS.State->CurrentEntry == directory_entry();
1367 return State->CurrentEntry == RHS.State->CurrentEntry;
1368 }
1369
1370 bool operator!=(const directory_iterator &RHS) const {
1371 return !(*this == RHS);
1372 }
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001373};
1374
1375namespace detail {
1376
1377 /// Keeps state for the recursive_directory_iterator.
1378 struct RecDirIterState {
1379 std::stack<directory_iterator, std::vector<directory_iterator>> Stack;
1380 uint16_t Level = 0;
1381 bool HasNoPushRequest = false;
1382 };
1383
1384} // end namespace detail
1385
1386/// recursive_directory_iterator - Same as directory_iterator except for it
1387/// recurses down into child directories.
1388class recursive_directory_iterator {
1389 std::shared_ptr<detail::RecDirIterState> State;
1390 bool Follow;
1391
1392public:
1393 recursive_directory_iterator() = default;
1394 explicit recursive_directory_iterator(const Twine &path, std::error_code &ec,
1395 bool follow_symlinks = true)
1396 : State(std::make_shared<detail::RecDirIterState>()),
1397 Follow(follow_symlinks) {
1398 State->Stack.push(directory_iterator(path, ec, Follow));
1399 if (State->Stack.top() == directory_iterator())
1400 State.reset();
1401 }
1402
1403 // No operator++ because we need error_code.
1404 recursive_directory_iterator &increment(std::error_code &ec) {
1405 const directory_iterator end_itr = {};
1406
1407 if (State->HasNoPushRequest)
1408 State->HasNoPushRequest = false;
1409 else {
Andrew Scull0372a572018-11-16 15:47:06 +00001410 file_type type = State->Stack.top()->type();
1411 if (type == file_type::symlink_file && Follow) {
1412 // Resolve the symlink: is it a directory to recurse into?
1413 ErrorOr<basic_file_status> status = State->Stack.top()->status();
1414 if (status)
1415 type = status->type();
1416 // Otherwise broken symlink, and we'll continue.
1417 }
1418 if (type == file_type::directory_file) {
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001419 State->Stack.push(directory_iterator(*State->Stack.top(), ec, Follow));
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001420 if (State->Stack.top() != end_itr) {
1421 ++State->Level;
1422 return *this;
1423 }
1424 State->Stack.pop();
1425 }
1426 }
1427
1428 while (!State->Stack.empty()
1429 && State->Stack.top().increment(ec) == end_itr) {
1430 State->Stack.pop();
1431 --State->Level;
1432 }
1433
1434 // Check if we are done. If so, create an end iterator.
1435 if (State->Stack.empty())
1436 State.reset();
1437
1438 return *this;
1439 }
1440
1441 const directory_entry &operator*() const { return *State->Stack.top(); }
1442 const directory_entry *operator->() const { return &*State->Stack.top(); }
1443
1444 // observers
1445 /// Gets the current level. Starting path is at level 0.
1446 int level() const { return State->Level; }
1447
1448 /// Returns true if no_push has been called for this directory_entry.
1449 bool no_push_request() const { return State->HasNoPushRequest; }
1450
1451 // modifiers
1452 /// Goes up one level if Level > 0.
1453 void pop() {
1454 assert(State && "Cannot pop an end iterator!");
1455 assert(State->Level > 0 && "Cannot pop an iterator with level < 1");
1456
1457 const directory_iterator end_itr = {};
1458 std::error_code ec;
1459 do {
1460 if (ec)
1461 report_fatal_error("Error incrementing directory iterator.");
1462 State->Stack.pop();
1463 --State->Level;
1464 } while (!State->Stack.empty()
1465 && State->Stack.top().increment(ec) == end_itr);
1466
1467 // Check if we are done. If so, create an end iterator.
1468 if (State->Stack.empty())
1469 State.reset();
1470 }
1471
1472 /// Does not go down into the current directory_entry.
1473 void no_push() { State->HasNoPushRequest = true; }
1474
1475 bool operator==(const recursive_directory_iterator &RHS) const {
1476 return State == RHS.State;
1477 }
1478
1479 bool operator!=(const recursive_directory_iterator &RHS) const {
1480 return !(*this == RHS);
1481 }
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001482};
1483
1484/// @}
1485
1486} // end namespace fs
1487} // end namespace sys
1488} // end namespace llvm
1489
1490#endif // LLVM_SUPPORT_FILESYSTEM_H