1 //===- llvm/Support/FileSystem.h - File System OS Concept -------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file declares the llvm::sys::fs namespace. It is designed after
11 // TR2/boost filesystem (v3), but modified to remove exception handling and the
12 // path class.
13 //
14 // All functions return an error_code and their actual work via the last out
15 // argument. The out argument is defined if and only if errc::success is
16 // returned. A function may return any error code in the generic or system
17 // category. However, they shall be equivalent to any error conditions listed
18 // in each functions respective documentation if the condition applies. [ note:
19 // this does not guarantee that error_code will be in the set of explicitly
20 // listed codes, but it does guarantee that if any of the explicitly listed
21 // errors occur, the correct error_code will be used ]. All functions may
22 // return errc::not_enough_memory if there is not enough memory to complete the
23 // operation.
24 //
25 //===----------------------------------------------------------------------===//
26
27 #ifndef LLVM_SUPPORT_FILESYSTEM_H
28 #define LLVM_SUPPORT_FILESYSTEM_H
29
30 #include "llvm/ADT/IntrusiveRefCntPtr.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Support/DataTypes.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include <ctime>
36 #include <iterator>
37 #include <stack>
38 #include <string>
39 #include <system_error>
40 #include <tuple>
41 #include <vector>
42
43 #ifdef HAVE_SYS_STAT_H
44 #include <sys/stat.h>
45 #endif
46
47 namespace llvm {
48 namespace sys {
49 namespace fs {
50
51 /// An enumeration for the file system's view of the type.
52 enum class file_type {
53 status_error,
54 file_not_found,
55 regular_file,
56 directory_file,
57 symlink_file,
58 block_file,
59 character_file,
60 fifo_file,
61 socket_file,
62 type_unknown
63 };
64
65 /// space_info - Self explanatory.
66 struct space_info {
67 uint64_t capacity;
68 uint64_t free;
69 uint64_t available;
70 };
71
72 enum perms {
73 no_perms = 0,
74 owner_read = 0400,
75 owner_write = 0200,
76 owner_exe = 0100,
77 owner_all = owner_read | owner_write | owner_exe,
78 group_read = 040,
79 group_write = 020,
80 group_exe = 010,
81 group_all = group_read | group_write | group_exe,
82 others_read = 04,
83 others_write = 02,
84 others_exe = 01,
85 others_all = others_read | others_write | others_exe,
86 all_read = owner_read | group_read | others_read,
87 all_write = owner_write | group_write | others_write,
88 all_exe = owner_exe | group_exe | others_exe,
89 all_all = owner_all | group_all | others_all,
90 set_uid_on_exe = 04000,
91 set_gid_on_exe = 02000,
92 sticky_bit = 01000,
93 perms_not_known = 0xFFFF
94 };
95
96 // Helper functions so that you can use & and | to manipulate perms bits:
97 inline perms operator|(perms l, perms r) {
98 return static_cast<perms>(static_cast<unsigned short>(l) |
99 static_cast<unsigned short>(r));
100 }
101 inline perms operator&(perms l, perms r) {
102 return static_cast<perms>(static_cast<unsigned short>(l) &
103 static_cast<unsigned short>(r));
104 }
105 inline perms &operator|=(perms &l, perms r) {
106 l = l | r;
107 return l;
108 }
109 inline perms &operator&=(perms &l, perms r) {
110 l = l & r;
111 return l;
112 }
113 inline perms operator~(perms x) {
114 return static_cast<perms>(~static_cast<unsigned short>(x));
115 }
116
117 class UniqueID {
118 uint64_t Device;
119 uint64_t File;
120
121 public:
122 UniqueID() = default;
UniqueID(uint64_t Device,uint64_t File)123 UniqueID(uint64_t Device, uint64_t File) : Device(Device), File(File) {}
124 bool operator==(const UniqueID &Other) const {
125 return Device == Other.Device && File == Other.File;
126 }
127 bool operator!=(const UniqueID &Other) const { return !(*this == Other); }
128 bool operator<(const UniqueID &Other) const {
129 return std::tie(Device, File) < std::tie(Other.Device, Other.File);
130 }
getDevice()131 uint64_t getDevice() const { return Device; }
getFile()132 uint64_t getFile() const { return File; }
133 };
134
135 /// file_status - Represents the result of a call to stat and friends. It has
136 /// a platform-specific member to store the result.
137 class file_status
138 {
139 #if defined(LLVM_ON_UNIX)
140 dev_t fs_st_dev;
141 ino_t fs_st_ino;
142 time_t fs_st_mtime;
143 uid_t fs_st_uid;
144 gid_t fs_st_gid;
145 off_t fs_st_size;
146 #elif defined (LLVM_ON_WIN32)
147 uint32_t LastWriteTimeHigh;
148 uint32_t LastWriteTimeLow;
149 uint32_t VolumeSerialNumber;
150 uint32_t FileSizeHigh;
151 uint32_t FileSizeLow;
152 uint32_t FileIndexHigh;
153 uint32_t FileIndexLow;
154 #endif
155 friend bool equivalent(file_status A, file_status B);
156 file_type Type;
157 perms Perms;
158
159 public:
160 #if defined(LLVM_ON_UNIX)
file_status()161 file_status() : fs_st_dev(0), fs_st_ino(0), fs_st_mtime(0),
162 fs_st_uid(0), fs_st_gid(0), fs_st_size(0),
163 Type(file_type::status_error), Perms(perms_not_known) {}
164
file_status(file_type Type)165 file_status(file_type Type) : fs_st_dev(0), fs_st_ino(0), fs_st_mtime(0),
166 fs_st_uid(0), fs_st_gid(0), fs_st_size(0), Type(Type),
167 Perms(perms_not_known) {}
168
file_status(file_type Type,perms Perms,dev_t Dev,ino_t Ino,time_t MTime,uid_t UID,gid_t GID,off_t Size)169 file_status(file_type Type, perms Perms, dev_t Dev, ino_t Ino, time_t MTime,
170 uid_t UID, gid_t GID, off_t Size)
171 : fs_st_dev(Dev), fs_st_ino(Ino), fs_st_mtime(MTime), fs_st_uid(UID),
172 fs_st_gid(GID), fs_st_size(Size), Type(Type), Perms(Perms) {}
173 #elif defined(LLVM_ON_WIN32)
174 file_status() : LastWriteTimeHigh(0), LastWriteTimeLow(0),
175 VolumeSerialNumber(0), FileSizeHigh(0), FileSizeLow(0),
176 FileIndexHigh(0), FileIndexLow(0), Type(file_type::status_error),
177 Perms(perms_not_known) {}
178
179 file_status(file_type Type) : LastWriteTimeHigh(0), LastWriteTimeLow(0),
180 VolumeSerialNumber(0), FileSizeHigh(0), FileSizeLow(0),
181 FileIndexHigh(0), FileIndexLow(0), Type(Type),
182 Perms(perms_not_known) {}
183
184 file_status(file_type Type, uint32_t LastWriteTimeHigh,
185 uint32_t LastWriteTimeLow, uint32_t VolumeSerialNumber,
186 uint32_t FileSizeHigh, uint32_t FileSizeLow,
187 uint32_t FileIndexHigh, uint32_t FileIndexLow)
188 : LastWriteTimeHigh(LastWriteTimeHigh),
189 LastWriteTimeLow(LastWriteTimeLow),
190 VolumeSerialNumber(VolumeSerialNumber), FileSizeHigh(FileSizeHigh),
191 FileSizeLow(FileSizeLow), FileIndexHigh(FileIndexHigh),
192 FileIndexLow(FileIndexLow), Type(Type), Perms(perms_not_known) {}
193 #endif
194
195 // getters
type()196 file_type type() const { return Type; }
permissions()197 perms permissions() const { return Perms; }
198 UniqueID getUniqueID() const;
199
200 #if defined(LLVM_ON_UNIX)
getUser()201 uint32_t getUser() const { return fs_st_uid; }
getGroup()202 uint32_t getGroup() const { return fs_st_gid; }
getSize()203 uint64_t getSize() const { return fs_st_size; }
204 #elif defined (LLVM_ON_WIN32)
getUser()205 uint32_t getUser() const {
206 return 9999; // Not applicable to Windows, so...
207 }
getGroup()208 uint32_t getGroup() const {
209 return 9999; // Not applicable to Windows, so...
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 /// file_magic - An "enum class" enumeration of file types based on magic (the first
222 /// N bytes of the file).
223 struct file_magic {
224 enum Impl {
225 unknown = 0, ///< Unrecognized file
226 bitcode, ///< Bitcode file
227 archive, ///< ar style archive file
228 elf, ///< ELF Unknown type
229 elf_relocatable, ///< ELF Relocatable object file
230 elf_executable, ///< ELF Executable image
231 elf_shared_object, ///< ELF dynamically linked shared lib
232 elf_core, ///< ELF core image
233 macho_object, ///< Mach-O Object file
234 macho_executable, ///< Mach-O Executable
235 macho_fixed_virtual_memory_shared_lib, ///< Mach-O Shared Lib, FVM
236 macho_core, ///< Mach-O Core File
237 macho_preload_executable, ///< Mach-O Preloaded Executable
238 macho_dynamically_linked_shared_lib, ///< Mach-O dynlinked shared lib
239 macho_dynamic_linker, ///< The Mach-O dynamic linker
240 macho_bundle, ///< Mach-O Bundle file
241 macho_dynamically_linked_shared_lib_stub, ///< Mach-O Shared lib stub
242 macho_dsym_companion, ///< Mach-O dSYM companion file
243 macho_kext_bundle, ///< Mach-O kext bundle file
244 macho_universal_binary, ///< Mach-O universal binary
245 coff_object, ///< COFF object file
246 coff_import_library, ///< COFF import library
247 pecoff_executable, ///< PECOFF executable file
248 windows_resource ///< Windows compiled resource file (.rc)
249 };
250
is_objectfile_magic251 bool is_object() const {
252 return V == unknown ? false : true;
253 }
254
file_magicfile_magic255 file_magic() : V(unknown) {}
file_magicfile_magic256 file_magic(Impl V) : V(V) {}
Implfile_magic257 operator Impl() const { return V; }
258
259 private:
260 Impl V;
261 };
262
263 /// @}
264 /// @name Physical Operators
265 /// @{
266
267 /// @brief Make \a path an absolute path.
268 ///
269 /// Makes \a path absolute using the \a current_directory if it is not already.
270 /// An empty \a path will result in the \a current_directory.
271 ///
272 /// /absolute/path => /absolute/path
273 /// relative/../path => <current-directory>/relative/../path
274 ///
275 /// @param path A path that is modified to be an absolute path.
276 /// @returns errc::success if \a path has been made absolute, otherwise a
277 /// platform-specific error_code.
278 std::error_code make_absolute(const Twine ¤t_directory,
279 SmallVectorImpl<char> &path);
280
281 /// @brief 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 std::error_code make_absolute(SmallVectorImpl<char> &path);
293
294 /// @brief 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 std::error_code create_directories(const Twine &path,
301 bool IgnoreExisting = true,
302 perms Perms = owner_all | group_all);
303
304 /// @brief 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 std::error_code create_directory(const Twine &path, bool IgnoreExisting = true,
311 perms Perms = owner_all | group_all);
312
313 /// @brief Create a link from \a from to \a to.
314 ///
315 /// The link may be a soft or a hard link, depending on the platform. The caller
316 /// may not assume which one. Currently on windows it creates a hard link since
317 /// soft links require extra privileges. On unix, it creates a soft link since
318 /// hard links don't work on SMB file systems.
319 ///
320 /// @param to The path to hard link to.
321 /// @param from The path to hard link from. This is created.
322 /// @returns errc::success if the link was created, otherwise a platform
323 /// specific error_code.
324 std::error_code create_link(const Twine &to, const Twine &from);
325
326 /// @brief Get the current path.
327 ///
328 /// @param result Holds the current path on return.
329 /// @returns errc::success if the current path has been stored in result,
330 /// otherwise a platform-specific error_code.
331 std::error_code current_path(SmallVectorImpl<char> &result);
332
333 /// @brief Remove path. Equivalent to POSIX remove().
334 ///
335 /// @param path Input path.
336 /// @returns errc::success if path has been removed or didn't exist, otherwise a
337 /// platform-specific error code. If IgnoreNonExisting is false, also
338 /// returns error if the file didn't exist.
339 std::error_code remove(const Twine &path, bool IgnoreNonExisting = true);
340
341 /// @brief Rename \a from to \a to. Files are renamed as if by POSIX rename().
342 ///
343 /// @param from The path to rename from.
344 /// @param to The path to rename to. This is created.
345 std::error_code rename(const Twine &from, const Twine &to);
346
347 /// @brief Copy the contents of \a From to \a To.
348 ///
349 /// @param From The path to copy from.
350 /// @param To The path to copy to. This is created.
351 std::error_code copy_file(const Twine &From, const Twine &To);
352
353 /// @brief Resize path to size. File is resized as if by POSIX truncate().
354 ///
355 /// @param FD Input file descriptor.
356 /// @param Size Size to resize to.
357 /// @returns errc::success if \a path has been resized to \a size, otherwise a
358 /// platform-specific error_code.
359 std::error_code resize_file(int FD, uint64_t Size);
360
361 /// @}
362 /// @name Physical Observers
363 /// @{
364
365 /// @brief Does file exist?
366 ///
367 /// @param status A file_status previously returned from stat.
368 /// @returns True if the file represented by status exists, false if it does
369 /// not.
370 bool exists(file_status status);
371
372 enum class AccessMode { Exist, Write, Execute };
373
374 /// @brief Can the file be accessed?
375 ///
376 /// @param Path Input path.
377 /// @returns errc::success if the path can be accessed, otherwise a
378 /// platform-specific error_code.
379 std::error_code access(const Twine &Path, AccessMode Mode);
380
381 /// @brief Does file exist?
382 ///
383 /// @param Path Input path.
384 /// @returns True if it exists, false otherwise.
exists(const Twine & Path)385 inline bool exists(const Twine &Path) {
386 return !access(Path, AccessMode::Exist);
387 }
388
389 /// @brief Can we execute this file?
390 ///
391 /// @param Path Input path.
392 /// @returns True if we can execute it, false otherwise.
393 bool can_execute(const Twine &Path);
394
395 /// @brief Can we write this file?
396 ///
397 /// @param Path Input path.
398 /// @returns True if we can write to it, false otherwise.
can_write(const Twine & Path)399 inline bool can_write(const Twine &Path) {
400 return !access(Path, AccessMode::Write);
401 }
402
403 /// @brief Do file_status's represent the same thing?
404 ///
405 /// @param A Input file_status.
406 /// @param B Input file_status.
407 ///
408 /// assert(status_known(A) || status_known(B));
409 ///
410 /// @returns True if A and B both represent the same file system entity, false
411 /// otherwise.
412 bool equivalent(file_status A, file_status B);
413
414 /// @brief Do paths represent the same thing?
415 ///
416 /// assert(status_known(A) || status_known(B));
417 ///
418 /// @param A Input path A.
419 /// @param B Input path B.
420 /// @param result Set to true if stat(A) and stat(B) have the same device and
421 /// inode (or equivalent).
422 /// @returns errc::success if result has been successfully set, otherwise a
423 /// platform-specific error_code.
424 std::error_code equivalent(const Twine &A, const Twine &B, bool &result);
425
426 /// @brief Simpler version of equivalent for clients that don't need to
427 /// differentiate between an error and false.
equivalent(const Twine & A,const Twine & B)428 inline bool equivalent(const Twine &A, const Twine &B) {
429 bool result;
430 return !equivalent(A, B, result) && result;
431 }
432
433 /// @brief Does status represent a directory?
434 ///
435 /// @param status A file_status previously returned from status.
436 /// @returns status.type() == file_type::directory_file.
437 bool is_directory(file_status status);
438
439 /// @brief Is path a directory?
440 ///
441 /// @param path Input path.
442 /// @param result Set to true if \a path is a directory, false if it is not.
443 /// Undefined otherwise.
444 /// @returns errc::success if result has been successfully set, otherwise a
445 /// platform-specific error_code.
446 std::error_code is_directory(const Twine &path, bool &result);
447
448 /// @brief Simpler version of is_directory for clients that don't need to
449 /// differentiate between an error and false.
is_directory(const Twine & Path)450 inline bool is_directory(const Twine &Path) {
451 bool Result;
452 return !is_directory(Path, Result) && Result;
453 }
454
455 /// @brief Does status represent a regular file?
456 ///
457 /// @param status A file_status previously returned from status.
458 /// @returns status_known(status) && status.type() == file_type::regular_file.
459 bool is_regular_file(file_status status);
460
461 /// @brief Is path a regular file?
462 ///
463 /// @param path Input path.
464 /// @param result Set to true if \a path is a regular file, false if it is not.
465 /// Undefined otherwise.
466 /// @returns errc::success if result has been successfully set, otherwise a
467 /// platform-specific error_code.
468 std::error_code is_regular_file(const Twine &path, bool &result);
469
470 /// @brief Simpler version of is_regular_file for clients that don't need to
471 /// differentiate between an error and false.
is_regular_file(const Twine & Path)472 inline bool is_regular_file(const Twine &Path) {
473 bool Result;
474 if (is_regular_file(Path, Result))
475 return false;
476 return Result;
477 }
478
479 /// @brief Does this status represent something that exists but is not a
480 /// directory, regular file, or symlink?
481 ///
482 /// @param status A file_status previously returned from status.
483 /// @returns exists(s) && !is_regular_file(s) && !is_directory(s)
484 bool is_other(file_status status);
485
486 /// @brief Is path something that exists but is not a directory,
487 /// regular file, or symlink?
488 ///
489 /// @param path Input path.
490 /// @param result Set to true if \a path exists, but is not a directory, regular
491 /// file, or a symlink, false if it does not. Undefined otherwise.
492 /// @returns errc::success if result has been successfully set, otherwise a
493 /// platform-specific error_code.
494 std::error_code is_other(const Twine &path, bool &result);
495
496 /// @brief Get file status as if by POSIX stat().
497 ///
498 /// @param path Input path.
499 /// @param result Set to the file status.
500 /// @returns errc::success if result has been successfully set, otherwise a
501 /// platform-specific error_code.
502 std::error_code status(const Twine &path, file_status &result);
503
504 /// @brief A version for when a file descriptor is already available.
505 std::error_code status(int FD, file_status &Result);
506
507 /// @brief Get file size.
508 ///
509 /// @param Path Input path.
510 /// @param Result Set to the size of the file in \a Path.
511 /// @returns errc::success if result has been successfully set, otherwise a
512 /// platform-specific error_code.
file_size(const Twine & Path,uint64_t & Result)513 inline std::error_code file_size(const Twine &Path, uint64_t &Result) {
514 file_status Status;
515 std::error_code EC = status(Path, Status);
516 if (EC)
517 return EC;
518 Result = Status.getSize();
519 return std::error_code();
520 }
521
522 /// @brief Is status available?
523 ///
524 /// @param s Input file status.
525 /// @returns True if status() != status_error.
526 bool status_known(file_status s);
527
528 /// @brief Is status available?
529 ///
530 /// @param path Input path.
531 /// @param result Set to true if status() != status_error.
532 /// @returns errc::success if result has been successfully set, otherwise a
533 /// platform-specific error_code.
534 std::error_code status_known(const Twine &path, bool &result);
535
536 /// @brief Create a uniquely named file.
537 ///
538 /// Generates a unique path suitable for a temporary file and then opens it as a
539 /// file. The name is based on \a model with '%' replaced by a random char in
540 /// [0-9a-f]. If \a model is not an absolute path, the temporary file will be
541 /// created in the current directory.
542 ///
543 /// Example: clang-%%-%%-%%-%%-%%.s => clang-a0-b1-c2-d3-e4.s
544 ///
545 /// This is an atomic operation. Either the file is created and opened, or the
546 /// file system is left untouched.
547 ///
548 /// The intended use is for files that are to be kept, possibly after
549 /// renaming them. For example, when running 'clang -c foo.o', the file can
550 /// be first created as foo-abc123.o and then renamed.
551 ///
552 /// @param Model Name to base unique path off of.
553 /// @param ResultFD Set to the opened file's file descriptor.
554 /// @param ResultPath Set to the opened file's absolute path.
555 /// @returns errc::success if Result{FD,Path} have been successfully set,
556 /// otherwise a platform-specific error_code.
557 std::error_code createUniqueFile(const Twine &Model, int &ResultFD,
558 SmallVectorImpl<char> &ResultPath,
559 unsigned Mode = all_read | all_write);
560
561 /// @brief Simpler version for clients that don't want an open file.
562 std::error_code createUniqueFile(const Twine &Model,
563 SmallVectorImpl<char> &ResultPath);
564
565 /// @brief Create a file in the system temporary directory.
566 ///
567 /// The filename is of the form prefix-random_chars.suffix. Since the directory
568 /// is not know to the caller, Prefix and Suffix cannot have path separators.
569 /// The files are created with mode 0600.
570 ///
571 /// This should be used for things like a temporary .s that is removed after
572 /// running the assembler.
573 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
574 int &ResultFD,
575 SmallVectorImpl<char> &ResultPath);
576
577 /// @brief Simpler version for clients that don't want an open file.
578 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
579 SmallVectorImpl<char> &ResultPath);
580
581 std::error_code createUniqueDirectory(const Twine &Prefix,
582 SmallVectorImpl<char> &ResultPath);
583
584 enum OpenFlags : unsigned {
585 F_None = 0,
586
587 /// F_Excl - When opening a file, this flag makes raw_fd_ostream
588 /// report an error if the file already exists.
589 F_Excl = 1,
590
591 /// F_Append - When opening a file, if it already exists append to the
592 /// existing file instead of returning an error. This may not be specified
593 /// with F_Excl.
594 F_Append = 2,
595
596 /// The file should be opened in text mode on platforms that make this
597 /// distinction.
598 F_Text = 4,
599
600 /// Open the file for read and write.
601 F_RW = 8
602 };
603
604 inline OpenFlags operator|(OpenFlags A, OpenFlags B) {
605 return OpenFlags(unsigned(A) | unsigned(B));
606 }
607
608 inline OpenFlags &operator|=(OpenFlags &A, OpenFlags B) {
609 A = A | B;
610 return A;
611 }
612
613 std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
614 OpenFlags Flags, unsigned Mode = 0666);
615
616 std::error_code openFileForRead(const Twine &Name, int &ResultFD);
617
618 /// @brief Identify the type of a binary file based on how magical it is.
619 file_magic identify_magic(StringRef magic);
620
621 /// @brief Get and identify \a path's type based on its content.
622 ///
623 /// @param path Input path.
624 /// @param result Set to the type of file, or file_magic::unknown.
625 /// @returns errc::success if result has been successfully set, otherwise a
626 /// platform-specific error_code.
627 std::error_code identify_magic(const Twine &path, file_magic &result);
628
629 std::error_code getUniqueID(const Twine Path, UniqueID &Result);
630
631 /// This class represents a memory mapped file. It is based on
632 /// boost::iostreams::mapped_file.
633 class mapped_file_region {
634 mapped_file_region() = delete;
635 mapped_file_region(mapped_file_region&) = delete;
636 mapped_file_region &operator =(mapped_file_region&) = delete;
637
638 public:
639 enum mapmode {
640 readonly, ///< May only access map via const_data as read only.
641 readwrite, ///< May access map via data and modify it. Written to path.
642 priv ///< May modify via data, but changes are lost on destruction.
643 };
644
645 private:
646 /// Platform-specific mapping state.
647 uint64_t Size;
648 void *Mapping;
649
650 std::error_code init(int FD, uint64_t Offset, mapmode Mode);
651
652 public:
653 /// \param fd An open file descriptor to map. mapped_file_region takes
654 /// ownership if closefd is true. It must have been opended in the correct
655 /// mode.
656 mapped_file_region(int fd, mapmode mode, uint64_t length, uint64_t offset,
657 std::error_code &ec);
658
659 ~mapped_file_region();
660
661 uint64_t size() const;
662 char *data() const;
663
664 /// Get a const view of the data. Modifying this memory has undefined
665 /// behavior.
666 const char *const_data() const;
667
668 /// \returns The minimum alignment offset must be.
669 static int alignment();
670 };
671
672 /// Return the path to the main executable, given the value of argv[0] from
673 /// program startup and the address of main itself. In extremis, this function
674 /// may fail and return an empty path.
675 std::string getMainExecutable(const char *argv0, void *MainExecAddr);
676
677 /// @}
678 /// @name Iterators
679 /// @{
680
681 /// directory_entry - A single entry in a directory. Caches the status either
682 /// from the result of the iteration syscall, or the first time status is
683 /// called.
684 class directory_entry {
685 std::string Path;
686 mutable file_status Status;
687
688 public:
689 explicit directory_entry(const Twine &path, file_status st = file_status())
690 : Path(path.str())
691 , Status(st) {}
692
directory_entry()693 directory_entry() {}
694
695 void assign(const Twine &path, file_status st = file_status()) {
696 Path = path.str();
697 Status = st;
698 }
699
700 void replace_filename(const Twine &filename, file_status st = file_status());
701
path()702 const std::string &path() const { return Path; }
703 std::error_code status(file_status &result) const;
704
705 bool operator==(const directory_entry& rhs) const { return Path == rhs.Path; }
706 bool operator!=(const directory_entry& rhs) const { return !(*this == rhs); }
707 bool operator< (const directory_entry& rhs) const;
708 bool operator<=(const directory_entry& rhs) const;
709 bool operator> (const directory_entry& rhs) const;
710 bool operator>=(const directory_entry& rhs) const;
711 };
712
713 namespace detail {
714 struct DirIterState;
715
716 std::error_code directory_iterator_construct(DirIterState &, StringRef);
717 std::error_code directory_iterator_increment(DirIterState &);
718 std::error_code directory_iterator_destruct(DirIterState &);
719
720 /// DirIterState - Keeps state for the directory_iterator. It is reference
721 /// counted in order to preserve InputIterator semantics on copy.
722 struct DirIterState : public RefCountedBase<DirIterState> {
DirIterStateDirIterState723 DirIterState()
724 : IterationHandle(0) {}
725
~DirIterStateDirIterState726 ~DirIterState() {
727 directory_iterator_destruct(*this);
728 }
729
730 intptr_t IterationHandle;
731 directory_entry CurrentEntry;
732 };
733 }
734
735 /// directory_iterator - Iterates through the entries in path. There is no
736 /// operator++ because we need an error_code. If it's really needed we can make
737 /// it call report_fatal_error on error.
738 class directory_iterator {
739 IntrusiveRefCntPtr<detail::DirIterState> State;
740
741 public:
directory_iterator(const Twine & path,std::error_code & ec)742 explicit directory_iterator(const Twine &path, std::error_code &ec) {
743 State = new detail::DirIterState;
744 SmallString<128> path_storage;
745 ec = detail::directory_iterator_construct(*State,
746 path.toStringRef(path_storage));
747 }
748
directory_iterator(const directory_entry & de,std::error_code & ec)749 explicit directory_iterator(const directory_entry &de, std::error_code &ec) {
750 State = new detail::DirIterState;
751 ec = detail::directory_iterator_construct(*State, de.path());
752 }
753
754 /// Construct end iterator.
directory_iterator()755 directory_iterator() : State(nullptr) {}
756
757 // No operator++ because we need error_code.
increment(std::error_code & ec)758 directory_iterator &increment(std::error_code &ec) {
759 ec = directory_iterator_increment(*State);
760 return *this;
761 }
762
763 const directory_entry &operator*() const { return State->CurrentEntry; }
764 const directory_entry *operator->() const { return &State->CurrentEntry; }
765
766 bool operator==(const directory_iterator &RHS) const {
767 if (State == RHS.State)
768 return true;
769 if (!RHS.State)
770 return State->CurrentEntry == directory_entry();
771 if (!State)
772 return RHS.State->CurrentEntry == directory_entry();
773 return State->CurrentEntry == RHS.State->CurrentEntry;
774 }
775
776 bool operator!=(const directory_iterator &RHS) const {
777 return !(*this == RHS);
778 }
779 // Other members as required by
780 // C++ Std, 24.1.1 Input iterators [input.iterators]
781 };
782
783 namespace detail {
784 /// RecDirIterState - Keeps state for the recursive_directory_iterator. It is
785 /// reference counted in order to preserve InputIterator semantics on copy.
786 struct RecDirIterState : public RefCountedBase<RecDirIterState> {
RecDirIterStateRecDirIterState787 RecDirIterState()
788 : Level(0)
789 , HasNoPushRequest(false) {}
790
791 std::stack<directory_iterator, std::vector<directory_iterator> > Stack;
792 uint16_t Level;
793 bool HasNoPushRequest;
794 };
795 }
796
797 /// recursive_directory_iterator - Same as directory_iterator except for it
798 /// recurses down into child directories.
799 class recursive_directory_iterator {
800 IntrusiveRefCntPtr<detail::RecDirIterState> State;
801
802 public:
recursive_directory_iterator()803 recursive_directory_iterator() {}
recursive_directory_iterator(const Twine & path,std::error_code & ec)804 explicit recursive_directory_iterator(const Twine &path, std::error_code &ec)
805 : State(new detail::RecDirIterState) {
806 State->Stack.push(directory_iterator(path, ec));
807 if (State->Stack.top() == directory_iterator())
808 State.reset();
809 }
810 // No operator++ because we need error_code.
increment(std::error_code & ec)811 recursive_directory_iterator &increment(std::error_code &ec) {
812 const directory_iterator end_itr;
813
814 if (State->HasNoPushRequest)
815 State->HasNoPushRequest = false;
816 else {
817 file_status st;
818 if ((ec = State->Stack.top()->status(st))) return *this;
819 if (is_directory(st)) {
820 State->Stack.push(directory_iterator(*State->Stack.top(), ec));
821 if (ec) return *this;
822 if (State->Stack.top() != end_itr) {
823 ++State->Level;
824 return *this;
825 }
826 State->Stack.pop();
827 }
828 }
829
830 while (!State->Stack.empty()
831 && State->Stack.top().increment(ec) == end_itr) {
832 State->Stack.pop();
833 --State->Level;
834 }
835
836 // Check if we are done. If so, create an end iterator.
837 if (State->Stack.empty())
838 State.reset();
839
840 return *this;
841 }
842
843 const directory_entry &operator*() const { return *State->Stack.top(); }
844 const directory_entry *operator->() const { return &*State->Stack.top(); }
845
846 // observers
847 /// Gets the current level. Starting path is at level 0.
level()848 int level() const { return State->Level; }
849
850 /// Returns true if no_push has been called for this directory_entry.
no_push_request()851 bool no_push_request() const { return State->HasNoPushRequest; }
852
853 // modifiers
854 /// Goes up one level if Level > 0.
pop()855 void pop() {
856 assert(State && "Cannot pop an end iterator!");
857 assert(State->Level > 0 && "Cannot pop an iterator with level < 1");
858
859 const directory_iterator end_itr;
860 std::error_code ec;
861 do {
862 if (ec)
863 report_fatal_error("Error incrementing directory iterator.");
864 State->Stack.pop();
865 --State->Level;
866 } while (!State->Stack.empty()
867 && State->Stack.top().increment(ec) == end_itr);
868
869 // Check if we are done. If so, create an end iterator.
870 if (State->Stack.empty())
871 State.reset();
872 }
873
874 /// Does not go down into the current directory_entry.
no_push()875 void no_push() { State->HasNoPushRequest = true; }
876
877 bool operator==(const recursive_directory_iterator &RHS) const {
878 return State == RHS.State;
879 }
880
881 bool operator!=(const recursive_directory_iterator &RHS) const {
882 return !(*this == RHS);
883 }
884 // Other members as required by
885 // C++ Std, 24.1.1 Input iterators [input.iterators]
886 };
887
888 /// @}
889
890 } // end namespace fs
891 } // end namespace sys
892 } // end namespace llvm
893
894 #endif
895