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