Add a version of unique_file that return just the file name.
[oota-llvm.git] / include / llvm / Support / FileSystem.h
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/OwningPtr.h"
32 #include "llvm/ADT/SmallString.h"
33 #include "llvm/ADT/Twine.h"
34 #include "llvm/Support/DataTypes.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/system_error.h"
37 #include <ctime>
38 #include <iterator>
39 #include <stack>
40 #include <string>
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 /// file_type - An "enum class" enumeration for the file system's view of the
52 ///             type.
53 struct file_type {
54   enum _ {
55     status_error,
56     file_not_found,
57     regular_file,
58     directory_file,
59     symlink_file,
60     block_file,
61     character_file,
62     fifo_file,
63     socket_file,
64     type_unknown
65   };
66
67   file_type(_ v) : v_(v) {}
68   explicit file_type(int v) : v_(_(v)) {}
69   operator int() const {return v_;}
70
71 private:
72   int v_;
73 };
74
75 /// copy_option - An "enum class" enumeration of copy semantics for copy
76 ///               operations.
77 struct copy_option {
78   enum _ {
79     fail_if_exists,
80     overwrite_if_exists
81   };
82
83   copy_option(_ v) : v_(v) {}
84   explicit copy_option(int v) : v_(_(v)) {}
85   operator int() const {return v_;}
86
87 private:
88   int v_;
89 };
90
91 /// space_info - Self explanatory.
92 struct space_info {
93   uint64_t capacity;
94   uint64_t free;
95   uint64_t available;
96 };
97
98
99 enum perms {
100   no_perms     = 0,
101   owner_read   = 0400, 
102   owner_write  = 0200, 
103   owner_exe    = 0100, 
104   owner_all    = owner_read | owner_write | owner_exe,
105   group_read   =  040, 
106   group_write  =  020, 
107   group_exe    =  010, 
108   group_all    = group_read | group_write | group_exe,
109   others_read  =   04, 
110   others_write =   02, 
111   others_exe   =   01, 
112   others_all   = others_read | others_write | others_exe, 
113   all_all      = owner_all | group_all | others_all,
114   set_uid_on_exe  = 04000, 
115   set_gid_on_exe  = 02000, 
116   sticky_bit      = 01000,
117   perms_mask      = all_all | set_uid_on_exe | set_gid_on_exe | sticky_bit, 
118   perms_not_known = 0xFFFF,
119   add_perms       = 0x1000,
120   remove_perms    = 0x2000, 
121   symlink_perms   = 0x4000
122 };
123
124 // Helper functions so that you can use & and | to manipulate perms bits:
125 inline perms operator|(perms l , perms r) {
126   return static_cast<perms>(
127              static_cast<unsigned short>(l) | static_cast<unsigned short>(r)); 
128 }
129 inline perms operator&(perms l , perms r) {
130   return static_cast<perms>(
131              static_cast<unsigned short>(l) & static_cast<unsigned short>(r)); 
132 }
133 inline perms &operator|=(perms &l, perms r) {
134   l = l | r; 
135   return l; 
136 }
137 inline perms &operator&=(perms &l, perms r) {
138   l = l & r; 
139   return l; 
140 }
141 inline perms operator~(perms x) {
142   return static_cast<perms>(~static_cast<unsigned short>(x));
143 }
144
145
146  
147 /// file_status - Represents the result of a call to stat and friends. It has
148 ///               a platform specific member to store the result.
149 class file_status
150 {
151   #if defined(LLVM_ON_UNIX)
152   dev_t fs_st_dev;
153   ino_t fs_st_ino;
154   #elif defined (LLVM_ON_WIN32)
155   uint32_t LastWriteTimeHigh;
156   uint32_t LastWriteTimeLow;
157   uint32_t VolumeSerialNumber;
158   uint32_t FileSizeHigh;
159   uint32_t FileSizeLow;
160   uint32_t FileIndexHigh;
161   uint32_t FileIndexLow;
162   #endif
163   friend bool equivalent(file_status A, file_status B);
164   friend error_code status(const Twine &path, file_status &result);
165   file_type Type;
166   perms Perms;
167 public:
168   explicit file_status(file_type v=file_type::status_error, 
169                       perms prms=perms_not_known)
170     : Type(v), Perms(prms) {}
171
172   // getters
173   file_type type() const { return Type; }
174   perms permissions() const { return Perms; }
175   
176   // setters
177   void type(file_type v) { Type = v; }
178   void permissions(perms p) { Perms = p; }
179 };
180
181 /// file_magic - An "enum class" enumeration of file types based on magic (the first
182 ///         N bytes of the file).
183 struct file_magic {
184   enum Impl {
185     unknown = 0,              ///< Unrecognized file
186     bitcode,                  ///< Bitcode file
187     archive,                  ///< ar style archive file
188     elf_relocatable,          ///< ELF Relocatable object file
189     elf_executable,           ///< ELF Executable image
190     elf_shared_object,        ///< ELF dynamically linked shared lib
191     elf_core,                 ///< ELF core image
192     macho_object,             ///< Mach-O Object file
193     macho_executable,         ///< Mach-O Executable
194     macho_fixed_virtual_memory_shared_lib, ///< Mach-O Shared Lib, FVM
195     macho_core,               ///< Mach-O Core File
196     macho_preload_executable, ///< Mach-O Preloaded Executable
197     macho_dynamically_linked_shared_lib, ///< Mach-O dynlinked shared lib
198     macho_dynamic_linker,     ///< The Mach-O dynamic linker
199     macho_bundle,             ///< Mach-O Bundle file
200     macho_dynamically_linked_shared_lib_stub, ///< Mach-O Shared lib stub
201     macho_dsym_companion,     ///< Mach-O dSYM companion file
202     macho_universal_binary,   ///< Mach-O universal binary
203     coff_object,              ///< COFF object file
204     pecoff_executable         ///< PECOFF executable file
205   };
206
207   bool is_object() const {
208     return V == unknown ? false : true;
209   }
210
211   file_magic() : V(unknown) {}
212   file_magic(Impl V) : V(V) {}
213   operator Impl() const { return V; }
214
215 private:
216   Impl V;
217 };
218
219 /// @}
220 /// @name Physical Operators
221 /// @{
222
223 /// @brief Make \a path an absolute path.
224 ///
225 /// Makes \a path absolute using the current directory if it is not already. An
226 /// empty \a path will result in the current directory.
227 ///
228 /// /absolute/path   => /absolute/path
229 /// relative/../path => <current-directory>/relative/../path
230 ///
231 /// @param path A path that is modified to be an absolute path.
232 /// @returns errc::success if \a path has been made absolute, otherwise a
233 ///          platform specific error_code.
234 error_code make_absolute(SmallVectorImpl<char> &path);
235
236 /// @brief Copy the file at \a from to the path \a to.
237 ///
238 /// @param from The path to copy the file from.
239 /// @param to The path to copy the file to.
240 /// @param copt Behavior if \a to already exists.
241 /// @returns errc::success if the file has been successfully copied.
242 ///          errc::file_exists if \a to already exists and \a copt ==
243 ///          copy_option::fail_if_exists. Otherwise a platform specific
244 ///          error_code.
245 error_code copy_file(const Twine &from, const Twine &to,
246                      copy_option copt = copy_option::fail_if_exists);
247
248 /// @brief Create all the non-existent directories in path.
249 ///
250 /// @param path Directories to create.
251 /// @param existed Set to true if \a path already existed, false otherwise.
252 /// @returns errc::success if is_directory(path) and existed have been set,
253 ///          otherwise a platform specific error_code.
254 error_code create_directories(const Twine &path, bool &existed);
255
256 /// @brief Create the directory in path.
257 ///
258 /// @param path Directory to create.
259 /// @param existed Set to true if \a path already existed, false otherwise.
260 /// @returns errc::success if is_directory(path) and existed have been set,
261 ///          otherwise a platform specific error_code.
262 error_code create_directory(const Twine &path, bool &existed);
263
264 /// @brief Create a hard link from \a from to \a to.
265 ///
266 /// @param to The path to hard link to.
267 /// @param from The path to hard link from. This is created.
268 /// @returns errc::success if exists(to) && exists(from) && equivalent(to, from)
269 ///          , otherwise a platform specific error_code.
270 error_code create_hard_link(const Twine &to, const Twine &from);
271
272 /// @brief Create a symbolic link from \a from to \a to.
273 ///
274 /// @param to The path to symbolically link to.
275 /// @param from The path to symbolically link from. This is created.
276 /// @returns errc::success if exists(to) && exists(from) && is_symlink(from),
277 ///          otherwise a platform specific error_code.
278 error_code create_symlink(const Twine &to, const Twine &from);
279
280 /// @brief Get the current path.
281 ///
282 /// @param result Holds the current path on return.
283 /// @returns errc::success if the current path has been stored in result,
284 ///          otherwise a platform specific error_code.
285 error_code current_path(SmallVectorImpl<char> &result);
286
287 /// @brief Remove path. Equivalent to POSIX remove().
288 ///
289 /// @param path Input path.
290 /// @param existed Set to true if \a path existed, false if it did not.
291 ///                undefined otherwise.
292 /// @returns errc::success if path has been removed and existed has been
293 ///          successfully set, otherwise a platform specific error_code.
294 error_code remove(const Twine &path, bool &existed);
295
296 /// @brief Convenience function for clients that don't need to know if the file
297 ///        existed or not.
298 inline error_code remove(const Twine &Path) {
299   bool Existed;
300   return remove(Path, Existed);
301 }
302
303 /// @brief Recursively remove all files below \a path, then \a path. Files are
304 ///        removed as if by POSIX remove().
305 ///
306 /// @param path Input path.
307 /// @param num_removed Number of files removed.
308 /// @returns errc::success if path has been removed and num_removed has been
309 ///          successfully set, otherwise a platform specific error_code.
310 error_code remove_all(const Twine &path, uint32_t &num_removed);
311
312 /// @brief Rename \a from to \a to. Files are renamed as if by POSIX rename().
313 ///
314 /// @param from The path to rename from.
315 /// @param to The path to rename to. This is created.
316 error_code rename(const Twine &from, const Twine &to);
317
318 /// @brief Resize path to size. File is resized as if by POSIX truncate().
319 ///
320 /// @param path Input path.
321 /// @param size Size to resize to.
322 /// @returns errc::success if \a path has been resized to \a size, otherwise a
323 ///          platform specific error_code.
324 error_code resize_file(const Twine &path, uint64_t size);
325
326 /// @}
327 /// @name Physical Observers
328 /// @{
329
330 /// @brief Does file exist?
331 ///
332 /// @param status A file_status previously returned from stat.
333 /// @returns True if the file represented by status exists, false if it does
334 ///          not.
335 bool exists(file_status status);
336
337 /// @brief Does file exist?
338 ///
339 /// @param path Input path.
340 /// @param result Set to true if the file represented by status exists, false if
341 ///               it does not. Undefined otherwise.
342 /// @returns errc::success if result has been successfully set, otherwise a
343 ///          platform specific error_code.
344 error_code exists(const Twine &path, bool &result);
345
346 /// @brief Simpler version of exists for clients that don't need to
347 ///        differentiate between an error and false.
348 inline bool exists(const Twine &path) {
349   bool result;
350   return !exists(path, result) && result;
351 }
352
353 /// @brief Can we execute this file?
354 ///
355 /// @param Path Input path.
356 /// @returns True if we can execute it, false otherwise.
357 bool can_execute(const Twine &Path);
358
359 /// @brief Do file_status's represent the same thing?
360 ///
361 /// @param A Input file_status.
362 /// @param B Input file_status.
363 ///
364 /// assert(status_known(A) || status_known(B));
365 ///
366 /// @returns True if A and B both represent the same file system entity, false
367 ///          otherwise.
368 bool equivalent(file_status A, file_status B);
369
370 /// @brief Do paths represent the same thing?
371 ///
372 /// assert(status_known(A) || status_known(B));
373 ///
374 /// @param A Input path A.
375 /// @param B Input path B.
376 /// @param result Set to true if stat(A) and stat(B) have the same device and
377 ///               inode (or equivalent).
378 /// @returns errc::success if result has been successfully set, otherwise a
379 ///          platform specific error_code.
380 error_code equivalent(const Twine &A, const Twine &B, bool &result);
381
382 /// @brief Simpler version of equivalent for clients that don't need to
383 ///        differentiate between an error and false.
384 inline bool equivalent(const Twine &A, const Twine &B) {
385   bool result;
386   return !equivalent(A, B, result) && result;
387 }
388
389 /// @brief Get file size.
390 ///
391 /// @param path Input path.
392 /// @param result Set to the size of the file in \a path.
393 /// @returns errc::success if result has been successfully set, otherwise a
394 ///          platform specific error_code.
395 error_code file_size(const Twine &path, uint64_t &result);
396
397 /// @brief Does status represent a directory?
398 ///
399 /// @param status A file_status previously returned from status.
400 /// @returns status.type() == file_type::directory_file.
401 bool is_directory(file_status status);
402
403 /// @brief Is path a directory?
404 ///
405 /// @param path Input path.
406 /// @param result Set to true if \a path is a directory, false if it is not.
407 ///               Undefined otherwise.
408 /// @returns errc::success if result has been successfully set, otherwise a
409 ///          platform specific error_code.
410 error_code is_directory(const Twine &path, bool &result);
411
412 /// @brief Does status represent a regular file?
413 ///
414 /// @param status A file_status previously returned from status.
415 /// @returns status_known(status) && status.type() == file_type::regular_file.
416 bool is_regular_file(file_status status);
417
418 /// @brief Is path a regular file?
419 ///
420 /// @param path Input path.
421 /// @param result Set to true if \a path is a regular file, false if it is not.
422 ///               Undefined otherwise.
423 /// @returns errc::success if result has been successfully set, otherwise a
424 ///          platform specific error_code.
425 error_code is_regular_file(const Twine &path, bool &result);
426
427 /// @brief Does this status represent something that exists but is not a
428 ///        directory, regular file, or symlink?
429 ///
430 /// @param status A file_status previously returned from status.
431 /// @returns exists(s) && !is_regular_file(s) && !is_directory(s) &&
432 ///          !is_symlink(s)
433 bool is_other(file_status status);
434
435 /// @brief Is path something that exists but is not a directory,
436 ///        regular file, or symlink?
437 ///
438 /// @param path Input path.
439 /// @param result Set to true if \a path exists, but is not a directory, regular
440 ///               file, or a symlink, false if it does not. Undefined otherwise.
441 /// @returns errc::success if result has been successfully set, otherwise a
442 ///          platform specific error_code.
443 error_code is_other(const Twine &path, bool &result);
444
445 /// @brief Does status represent a symlink?
446 ///
447 /// @param status A file_status previously returned from stat.
448 /// @returns status.type() == symlink_file.
449 bool is_symlink(file_status status);
450
451 /// @brief Is path a symlink?
452 ///
453 /// @param path Input path.
454 /// @param result Set to true if \a path is a symlink, false if it is not.
455 ///               Undefined otherwise.
456 /// @returns errc::success if result has been successfully set, otherwise a
457 ///          platform specific error_code.
458 error_code is_symlink(const Twine &path, bool &result);
459
460 /// @brief Get file status as if by POSIX stat().
461 ///
462 /// @param path Input path.
463 /// @param result Set to the file status.
464 /// @returns errc::success if result has been successfully set, otherwise a
465 ///          platform specific error_code.
466 error_code status(const Twine &path, file_status &result);
467
468 /// @brief Modifies permission bits on a file
469 ///
470 /// @param path Input path.
471 /// @returns errc::success if permissions have been changed, otherwise a
472 ///          platform specific error_code.
473 error_code permissions(const Twine &path, perms prms);
474
475 /// @brief Is status available?
476 ///
477 /// @param s Input file status.
478 /// @returns True if status() != status_error.
479 bool status_known(file_status s);
480
481 /// @brief Is status available?
482 ///
483 /// @param path Input path.
484 /// @param result Set to true if status() != status_error.
485 /// @returns errc::success if result has been successfully set, otherwise a
486 ///          platform specific error_code.
487 error_code status_known(const Twine &path, bool &result);
488
489 /// @brief Generate a unique path and open it as a file.
490 ///
491 /// Generates a unique path suitable for a temporary file and then opens it as a
492 /// file. The name is based on \a model with '%' replaced by a random char in
493 /// [0-9a-f]. If \a model is not an absolute path, a suitable temporary
494 /// directory will be prepended.
495 ///
496 /// This is an atomic operation. Either the file is created and opened, or the
497 /// file system is left untouched.
498 ///
499 /// clang-%%-%%-%%-%%-%%.s => /tmp/clang-a0-b1-c2-d3-e4.s
500 ///
501 /// @param model Name to base unique path off of.
502 /// @param result_fd Set to the opened file's file descriptor.
503 /// @param result_path Set to the opened file's absolute path.
504 /// @param makeAbsolute If true and \a model is not an absolute path, a temp
505 ///        directory will be prepended.
506 /// @returns errc::success if result_{fd,path} have been successfully set,
507 ///          otherwise a platform specific error_code.
508 error_code unique_file(const Twine &model, int &result_fd,
509                        SmallVectorImpl<char> &result_path,
510                        bool makeAbsolute = true, unsigned mode = 0600);
511
512 /// @brief Simpler version for clients that don't want an open file.
513 error_code unique_file(const Twine &Model, SmallVectorImpl<char> &ResultPath,
514                        bool MakeAbsolute = true, unsigned Mode = 0600);
515
516 /// @brief Canonicalize path.
517 ///
518 /// Sets result to the file system's idea of what path is. The result is always
519 /// absolute and has the same capitalization as the file system.
520 ///
521 /// @param path Input path.
522 /// @param result Set to the canonicalized version of \a path.
523 /// @returns errc::success if result has been successfully set, otherwise a
524 ///          platform specific error_code.
525 error_code canonicalize(const Twine &path, SmallVectorImpl<char> &result);
526
527 /// @brief Are \a path's first bytes \a magic?
528 ///
529 /// @param path Input path.
530 /// @param magic Byte sequence to compare \a path's first len(magic) bytes to.
531 /// @returns errc::success if result has been successfully set, otherwise a
532 ///          platform specific error_code.
533 error_code has_magic(const Twine &path, const Twine &magic, bool &result);
534
535 /// @brief Get \a path's first \a len bytes.
536 ///
537 /// @param path Input path.
538 /// @param len Number of magic bytes to get.
539 /// @param result Set to the first \a len bytes in the file pointed to by
540 ///               \a path. Or the entire file if file_size(path) < len, in which
541 ///               case result.size() returns the size of the file.
542 /// @returns errc::success if result has been successfully set,
543 ///          errc::value_too_large if len is larger then the file pointed to by
544 ///          \a path, otherwise a platform specific error_code.
545 error_code get_magic(const Twine &path, uint32_t len,
546                      SmallVectorImpl<char> &result);
547
548 /// @brief Identify the type of a binary file based on how magical it is.
549 file_magic identify_magic(StringRef magic);
550
551 /// @brief Get and identify \a path's type based on its content.
552 ///
553 /// @param path Input path.
554 /// @param result Set to the type of file, or file_magic::unknown.
555 /// @returns errc::success if result has been successfully set, otherwise a
556 ///          platform specific error_code.
557 error_code identify_magic(const Twine &path, file_magic &result);
558
559 /// This class represents a memory mapped file. It is based on
560 /// boost::iostreams::mapped_file.
561 class mapped_file_region {
562   mapped_file_region() LLVM_DELETED_FUNCTION;
563   mapped_file_region(mapped_file_region&) LLVM_DELETED_FUNCTION;
564   mapped_file_region &operator =(mapped_file_region&) LLVM_DELETED_FUNCTION;
565
566 public:
567   enum mapmode {
568     readonly, ///< May only access map via const_data as read only.
569     readwrite, ///< May access map via data and modify it. Written to path.
570     priv ///< May modify via data, but changes are lost on destruction.
571   };
572
573 private:
574   /// Platform specific mapping state.
575   mapmode Mode;
576   uint64_t Size;
577   void *Mapping;
578 #ifdef LLVM_ON_WIN32
579   int FileDescriptor;
580   void *FileHandle;
581   void *FileMappingHandle;
582 #endif
583
584   error_code init(int FD, bool CloseFD, uint64_t Offset);
585
586 public:
587   typedef char char_type;
588
589 #if LLVM_HAS_RVALUE_REFERENCES
590   mapped_file_region(mapped_file_region&&);
591   mapped_file_region &operator =(mapped_file_region&&);
592 #endif
593
594   /// Construct a mapped_file_region at \a path starting at \a offset of length
595   /// \a length and with access \a mode.
596   ///
597   /// \param path Path to the file to map. If it does not exist it will be
598   ///             created.
599   /// \param mode How to map the memory.
600   /// \param length Number of bytes to map in starting at \a offset. If the file
601   ///               is shorter than this, it will be extended. If \a length is
602   ///               0, the entire file will be mapped.
603   /// \param offset Byte offset from the beginning of the file where the map
604   ///               should begin. Must be a multiple of
605   ///               mapped_file_region::alignment().
606   /// \param ec This is set to errc::success if the map was constructed
607   ///           sucessfully. Otherwise it is set to a platform dependent error.
608   mapped_file_region(const Twine &path,
609                      mapmode mode,
610                      uint64_t length,
611                      uint64_t offset,
612                      error_code &ec);
613
614   /// \param fd An open file descriptor to map. mapped_file_region takes
615   ///   ownership if closefd is true. It must have been opended in the correct
616   ///   mode.
617   mapped_file_region(int fd,
618                      bool closefd,
619                      mapmode mode,
620                      uint64_t length,
621                      uint64_t offset,
622                      error_code &ec);
623
624   ~mapped_file_region();
625
626   mapmode flags() const;
627   uint64_t size() const;
628   char *data() const;
629
630   /// Get a const view of the data. Modifying this memory has undefined
631   /// behaivor.
632   const char *const_data() const;
633
634   /// \returns The minimum alignment offset must be.
635   static int alignment();
636 };
637
638 /// @brief Memory maps the contents of a file
639 ///
640 /// @param path Path to file to map.
641 /// @param file_offset Byte offset in file where mapping should begin.
642 /// @param size Byte length of range of the file to map.
643 /// @param map_writable If true, the file will be mapped in r/w such
644 ///        that changes to the mapped buffer will be flushed back
645 ///        to the file.  If false, the file will be mapped read-only
646 ///        and the buffer will be read-only.
647 /// @param result Set to the start address of the mapped buffer.
648 /// @returns errc::success if result has been successfully set, otherwise a
649 ///          platform specific error_code.
650 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,  
651                           bool map_writable, void *&result);
652
653
654 /// @brief Memory unmaps the contents of a file
655 ///
656 /// @param base Pointer to the start of the buffer.
657 /// @param size Byte length of the range to unmmap.
658 /// @returns errc::success if result has been successfully set, otherwise a
659 ///          platform specific error_code.
660 error_code unmap_file_pages(void *base, size_t size);
661
662
663
664 /// @}
665 /// @name Iterators
666 /// @{
667
668 /// directory_entry - A single entry in a directory. Caches the status either
669 /// from the result of the iteration syscall, or the first time status is
670 /// called.
671 class directory_entry {
672   std::string Path;
673   mutable file_status Status;
674
675 public:
676   explicit directory_entry(const Twine &path, file_status st = file_status())
677     : Path(path.str())
678     , Status(st) {}
679
680   directory_entry() {}
681
682   void assign(const Twine &path, file_status st = file_status()) {
683     Path = path.str();
684     Status = st;
685   }
686
687   void replace_filename(const Twine &filename, file_status st = file_status());
688
689   const std::string &path() const { return Path; }
690   error_code status(file_status &result) const;
691
692   bool operator==(const directory_entry& rhs) const { return Path == rhs.Path; }
693   bool operator!=(const directory_entry& rhs) const { return !(*this == rhs); }
694   bool operator< (const directory_entry& rhs) const;
695   bool operator<=(const directory_entry& rhs) const;
696   bool operator> (const directory_entry& rhs) const;
697   bool operator>=(const directory_entry& rhs) const;
698 };
699
700 namespace detail {
701   struct DirIterState;
702
703   error_code directory_iterator_construct(DirIterState&, StringRef);
704   error_code directory_iterator_increment(DirIterState&);
705   error_code directory_iterator_destruct(DirIterState&);
706
707   /// DirIterState - Keeps state for the directory_iterator. It is reference
708   /// counted in order to preserve InputIterator semantics on copy.
709   struct DirIterState : public RefCountedBase<DirIterState> {
710     DirIterState()
711       : IterationHandle(0) {}
712
713     ~DirIterState() {
714       directory_iterator_destruct(*this);
715     }
716
717     intptr_t IterationHandle;
718     directory_entry CurrentEntry;
719   };
720 }
721
722 /// directory_iterator - Iterates through the entries in path. There is no
723 /// operator++ because we need an error_code. If it's really needed we can make
724 /// it call report_fatal_error on error.
725 class directory_iterator {
726   IntrusiveRefCntPtr<detail::DirIterState> State;
727
728 public:
729   explicit directory_iterator(const Twine &path, error_code &ec) {
730     State = new detail::DirIterState;
731     SmallString<128> path_storage;
732     ec = detail::directory_iterator_construct(*State,
733             path.toStringRef(path_storage));
734   }
735
736   explicit directory_iterator(const directory_entry &de, error_code &ec) {
737     State = new detail::DirIterState;
738     ec = detail::directory_iterator_construct(*State, de.path());
739   }
740
741   /// Construct end iterator.
742   directory_iterator() : State(new detail::DirIterState) {}
743
744   // No operator++ because we need error_code.
745   directory_iterator &increment(error_code &ec) {
746     ec = directory_iterator_increment(*State);
747     return *this;
748   }
749
750   const directory_entry &operator*() const { return State->CurrentEntry; }
751   const directory_entry *operator->() const { return &State->CurrentEntry; }
752
753   bool operator==(const directory_iterator &RHS) const {
754     return State->CurrentEntry == RHS.State->CurrentEntry;
755   }
756
757   bool operator!=(const directory_iterator &RHS) const {
758     return !(*this == RHS);
759   }
760   // Other members as required by
761   // C++ Std, 24.1.1 Input iterators [input.iterators]
762 };
763
764 namespace detail {
765   /// RecDirIterState - Keeps state for the recursive_directory_iterator. It is
766   /// reference counted in order to preserve InputIterator semantics on copy.
767   struct RecDirIterState : public RefCountedBase<RecDirIterState> {
768     RecDirIterState()
769       : Level(0)
770       , HasNoPushRequest(false) {}
771
772     std::stack<directory_iterator, std::vector<directory_iterator> > Stack;
773     uint16_t Level;
774     bool HasNoPushRequest;
775   };
776 }
777
778 /// recursive_directory_iterator - Same as directory_iterator except for it
779 /// recurses down into child directories.
780 class recursive_directory_iterator {
781   IntrusiveRefCntPtr<detail::RecDirIterState> State;
782
783 public:
784   recursive_directory_iterator() {}
785   explicit recursive_directory_iterator(const Twine &path, error_code &ec)
786     : State(new detail::RecDirIterState) {
787     State->Stack.push(directory_iterator(path, ec));
788     if (State->Stack.top() == directory_iterator())
789       State.reset();
790   }
791   // No operator++ because we need error_code.
792   recursive_directory_iterator &increment(error_code &ec) {
793     static const directory_iterator end_itr;
794
795     if (State->HasNoPushRequest)
796       State->HasNoPushRequest = false;
797     else {
798       file_status st;
799       if ((ec = State->Stack.top()->status(st))) return *this;
800       if (is_directory(st)) {
801         State->Stack.push(directory_iterator(*State->Stack.top(), ec));
802         if (ec) return *this;
803         if (State->Stack.top() != end_itr) {
804           ++State->Level;
805           return *this;
806         }
807         State->Stack.pop();
808       }
809     }
810
811     while (!State->Stack.empty()
812            && State->Stack.top().increment(ec) == end_itr) {
813       State->Stack.pop();
814       --State->Level;
815     }
816
817     // Check if we are done. If so, create an end iterator.
818     if (State->Stack.empty())
819       State.reset();
820
821     return *this;
822   }
823
824   const directory_entry &operator*() const { return *State->Stack.top(); }
825   const directory_entry *operator->() const { return &*State->Stack.top(); }
826
827   // observers
828   /// Gets the current level. Starting path is at level 0.
829   int level() const { return State->Level; }
830
831   /// Returns true if no_push has been called for this directory_entry.
832   bool no_push_request() const { return State->HasNoPushRequest; }
833
834   // modifiers
835   /// Goes up one level if Level > 0.
836   void pop() {
837     assert(State && "Cannot pop and end itertor!");
838     assert(State->Level > 0 && "Cannot pop an iterator with level < 1");
839
840     static const directory_iterator end_itr;
841     error_code ec;
842     do {
843       if (ec)
844         report_fatal_error("Error incrementing directory iterator.");
845       State->Stack.pop();
846       --State->Level;
847     } while (!State->Stack.empty()
848              && State->Stack.top().increment(ec) == end_itr);
849
850     // Check if we are done. If so, create an end iterator.
851     if (State->Stack.empty())
852       State.reset();
853   }
854
855   /// Does not go down into the current directory_entry.
856   void no_push() { State->HasNoPushRequest = true; }
857
858   bool operator==(const recursive_directory_iterator &RHS) const {
859     return State == RHS.State;
860   }
861
862   bool operator!=(const recursive_directory_iterator &RHS) const {
863     return !(*this == RHS);
864   }
865   // Other members as required by
866   // C++ Std, 24.1.1 Input iterators [input.iterators]
867 };
868
869 /// @}
870
871 } // end namespace fs
872 } // end namespace sys
873 } // end namespace llvm
874
875 #endif