2abbc48b2e759201e76ad3d89cfd41e6bce05601
[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_FILE_SYSTEM_H
28 #define LLVM_SUPPORT_FILE_SYSTEM_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 "llvm/Support/PathV1.h"
36 #include "llvm/Support/system_error.h"
37 #include <ctime>
38 #include <iterator>
39 #include <stack>
40 #include <string>
41
42 #if HAVE_SYS_STAT_H
43 #include <sys/stat.h>
44 #endif
45
46 namespace llvm {
47 namespace sys {
48 namespace fs {
49
50 /// file_type - An "enum class" enumeration for the file system's view of the
51 ///             type.
52 struct file_type {
53   enum _ {
54     status_error,
55     file_not_found,
56     regular_file,
57     directory_file,
58     symlink_file,
59     block_file,
60     character_file,
61     fifo_file,
62     socket_file,
63     type_unknown
64   };
65
66   file_type(_ v) : v_(v) {}
67   explicit file_type(int v) : v_(_(v)) {}
68   operator int() const {return v_;}
69
70 private:
71   int v_;
72 };
73
74 /// copy_option - An "enum class" enumeration of copy semantics for copy
75 ///               operations.
76 struct copy_option {
77   enum _ {
78     fail_if_exists,
79     overwrite_if_exists
80   };
81
82   copy_option(_ v) : v_(v) {}
83   explicit copy_option(int v) : v_(_(v)) {}
84   operator int() const {return v_;}
85
86 private:
87   int v_;
88 };
89
90 /// space_info - Self explanatory.
91 struct space_info {
92   uint64_t capacity;
93   uint64_t free;
94   uint64_t available;
95 };
96
97 /// file_status - Represents the result of a call to stat and friends. It has
98 ///               a platform specific member to store the result.
99 class file_status
100 {
101   #if defined(LLVM_ON_UNIX)
102   dev_t st_dev;
103   ino_t st_ino;
104   #elif defined (LLVM_ON_WIN32)
105   uint32_t LastWriteTimeHigh;
106   uint32_t LastWriteTimeLow;
107   uint32_t VolumeSerialNumber;
108   uint32_t FileSizeHigh;
109   uint32_t FileSizeLow;
110   uint32_t FileIndexHigh;
111   uint32_t FileIndexLow;
112   #endif
113   friend bool equivalent(file_status A, file_status B);
114   friend error_code status(const Twine &path, file_status &result);
115   file_type Type;
116 public:
117   explicit file_status(file_type v=file_type::status_error)
118     : Type(v) {}
119
120   file_type type() const { return Type; }
121   void type(file_type v) { Type = v; }
122 };
123
124 /// @}
125 /// @name Physical Operators
126 /// @{
127
128 /// @brief Make \a path an absolute path.
129 ///
130 /// Makes \a path absolute using the current directory if it is not already. An
131 /// empty \a path will result in the current directory.
132 ///
133 /// /absolute/path   => /absolute/path
134 /// relative/../path => <current-directory>/relative/../path
135 ///
136 /// @param path A path that is modified to be an absolute path.
137 /// @returns errc::success if \a path has been made absolute, otherwise a
138 ///          platform specific error_code.
139 error_code make_absolute(SmallVectorImpl<char> &path);
140
141 /// @brief Copy the file at \a from to the path \a to.
142 ///
143 /// @param from The path to copy the file from.
144 /// @param to The path to copy the file to.
145 /// @param copt Behavior if \a to already exists.
146 /// @returns errc::success if the file has been successfully copied.
147 ///          errc::file_exists if \a to already exists and \a copt ==
148 ///          copy_option::fail_if_exists. Otherwise a platform specific
149 ///          error_code.
150 error_code copy_file(const Twine &from, const Twine &to,
151                      copy_option copt = copy_option::fail_if_exists);
152
153 /// @brief Create all the non-existent directories in path.
154 ///
155 /// @param path Directories to create.
156 /// @param existed Set to true if \a path already existed, false otherwise.
157 /// @returns errc::success if is_directory(path) and existed have been set,
158 ///          otherwise a platform specific error_code.
159 error_code create_directories(const Twine &path, bool &existed);
160
161 /// @brief Create the directory in path.
162 ///
163 /// @param path Directory to create.
164 /// @param existed Set to true if \a path already existed, false otherwise.
165 /// @returns errc::success if is_directory(path) and existed have been set,
166 ///          otherwise a platform specific error_code.
167 error_code create_directory(const Twine &path, bool &existed);
168
169 /// @brief Create a hard link from \a from to \a to.
170 ///
171 /// @param to The path to hard link to.
172 /// @param from The path to hard link from. This is created.
173 /// @returns errc::success if exists(to) && exists(from) && equivalent(to, from)
174 ///          , otherwise a platform specific error_code.
175 error_code create_hard_link(const Twine &to, const Twine &from);
176
177 /// @brief Create a symbolic link from \a from to \a to.
178 ///
179 /// @param to The path to symbolically link to.
180 /// @param from The path to symbolically link from. This is created.
181 /// @returns errc::success if exists(to) && exists(from) && is_symlink(from),
182 ///          otherwise a platform specific error_code.
183 error_code create_symlink(const Twine &to, const Twine &from);
184
185 /// @brief Get the current path.
186 ///
187 /// @param result Holds the current path on return.
188 /// @results errc::success if the current path has been stored in result,
189 ///          otherwise a platform specific error_code.
190 error_code current_path(SmallVectorImpl<char> &result);
191
192 /// @brief Remove path. Equivalent to POSIX remove().
193 ///
194 /// @param path Input path.
195 /// @param existed Set to true if \a path existed, false if it did not.
196 ///                undefined otherwise.
197 /// @results errc::success if path has been removed and existed has been
198 ///          successfully set, otherwise a platform specific error_code.
199 error_code remove(const Twine &path, bool &existed);
200
201 /// @brief Recursively remove all files below \a path, then \a path. Files are
202 ///        removed as if by POSIX remove().
203 ///
204 /// @param path Input path.
205 /// @param num_removed Number of files removed.
206 /// @results errc::success if path has been removed and num_removed has been
207 ///          successfully set, otherwise a platform specific error_code.
208 error_code remove_all(const Twine &path, uint32_t &num_removed);
209
210 /// @brief Rename \a from to \a to. Files are renamed as if by POSIX rename().
211 ///
212 /// @param from The path to rename from.
213 /// @param to The path to rename to. This is created.
214 error_code rename(const Twine &from, const Twine &to);
215
216 /// @brief Resize path to size. File is resized as if by POSIX truncate().
217 ///
218 /// @param path Input path.
219 /// @param size Size to resize to.
220 /// @returns errc::success if \a path has been resized to \a size, otherwise a
221 ///          platform specific error_code.
222 error_code resize_file(const Twine &path, uint64_t size);
223
224 /// @}
225 /// @name Physical Observers
226 /// @{
227
228 /// @brief Does file exist?
229 ///
230 /// @param status A file_status previously returned from stat.
231 /// @results True if the file represented by status exists, false if it does
232 ///          not.
233 bool exists(file_status status);
234
235 /// @brief Does file exist?
236 ///
237 /// @param path Input path.
238 /// @param result Set to true if the file represented by status exists, false if
239 ///               it does not. Undefined otherwise.
240 /// @results errc::success if result has been successfully set, otherwise a
241 ///          platform specific error_code.
242 error_code exists(const Twine &path, bool &result);
243
244 /// @brief Simpler version of exists for clients that don't need to
245 ///        differentiate between an error and false.
246 inline bool exists(const Twine &path) {
247   bool result;
248   return !exists(path, result) && result;
249 }
250
251 /// @brief Do file_status's represent the same thing?
252 ///
253 /// @param A Input file_status.
254 /// @param B Input file_status.
255 ///
256 /// assert(status_known(A) || status_known(B));
257 ///
258 /// @results True if A and B both represent the same file system entity, false
259 ///          otherwise.
260 bool equivalent(file_status A, file_status B);
261
262 /// @brief Do paths represent the same thing?
263 ///
264 /// assert(status_known(A) || status_known(B));
265 ///
266 /// @param A Input path A.
267 /// @param B Input path B.
268 /// @param result Set to true if stat(A) and stat(B) have the same device and
269 ///               inode (or equivalent).
270 /// @results errc::success if result has been successfully set, otherwise a
271 ///          platform specific error_code.
272 error_code equivalent(const Twine &A, const Twine &B, bool &result);
273
274 /// @brief Get file size.
275 ///
276 /// @param path Input path.
277 /// @param result Set to the size of the file in \a path.
278 /// @returns errc::success if result has been successfully set, otherwise a
279 ///          platform specific error_code.
280 error_code file_size(const Twine &path, uint64_t &result);
281
282 /// @brief Does status represent a directory?
283 ///
284 /// @param status A file_status previously returned from status.
285 /// @results status.type() == file_type::directory_file.
286 bool is_directory(file_status status);
287
288 /// @brief Is path a directory?
289 ///
290 /// @param path Input path.
291 /// @param result Set to true if \a path is a directory, false if it is not.
292 ///               Undefined otherwise.
293 /// @results errc::success if result has been successfully set, otherwise a
294 ///          platform specific error_code.
295 error_code is_directory(const Twine &path, bool &result);
296
297 /// @brief Does status represent a regular file?
298 ///
299 /// @param status A file_status previously returned from status.
300 /// @results status_known(status) && status.type() == file_type::regular_file.
301 bool is_regular_file(file_status status);
302
303 /// @brief Is path a regular file?
304 ///
305 /// @param path Input path.
306 /// @param result Set to true if \a path is a regular file, false if it is not.
307 ///               Undefined otherwise.
308 /// @results errc::success if result has been successfully set, otherwise a
309 ///          platform specific error_code.
310 error_code is_regular_file(const Twine &path, bool &result);
311
312 /// @brief Does this status represent something that exists but is not a
313 ///        directory, regular file, or symlink?
314 ///
315 /// @param status A file_status previously returned from status.
316 /// @results exists(s) && !is_regular_file(s) && !is_directory(s) &&
317 ///          !is_symlink(s)
318 bool is_other(file_status status);
319
320 /// @brief Is path something that exists but is not a directory,
321 ///        regular file, or symlink?
322 ///
323 /// @param path Input path.
324 /// @param result Set to true if \a path exists, but is not a directory, regular
325 ///               file, or a symlink, false if it does not. Undefined otherwise.
326 /// @results errc::success if result has been successfully set, otherwise a
327 ///          platform specific error_code.
328 error_code is_other(const Twine &path, bool &result);
329
330 /// @brief Does status represent a symlink?
331 ///
332 /// @param status A file_status previously returned from stat.
333 /// @param result status.type() == symlink_file.
334 bool is_symlink(file_status status);
335
336 /// @brief Is path a symlink?
337 ///
338 /// @param path Input path.
339 /// @param result Set to true if \a path is a symlink, false if it is not.
340 ///               Undefined otherwise.
341 /// @results errc::success if result has been successfully set, otherwise a
342 ///          platform specific error_code.
343 error_code is_symlink(const Twine &path, bool &result);
344
345 /// @brief Get file status as if by POSIX stat().
346 ///
347 /// @param path Input path.
348 /// @param result Set to the file status.
349 /// @results errc::success if result has been successfully set, otherwise a
350 ///          platform specific error_code.
351 error_code status(const Twine &path, file_status &result);
352
353 /// @brief Is status available?
354 ///
355 /// @param path Input path.
356 /// @results True if status() != status_error.
357 bool status_known(file_status s);
358
359 /// @brief Is status available?
360 ///
361 /// @param path Input path.
362 /// @param result Set to true if status() != status_error.
363 /// @results errc::success if result has been successfully set, otherwise a
364 ///          platform specific error_code.
365 error_code status_known(const Twine &path, bool &result);
366
367 /// @brief Generate a unique path and open it as a file.
368 ///
369 /// Generates a unique path suitable for a temporary file and then opens it as a
370 /// file. The name is based on \a model with '%' replaced by a random char in
371 /// [0-9a-f]. If \a model is not an absolute path, a suitable temporary
372 /// directory will be prepended.
373 ///
374 /// This is an atomic operation. Either the file is created and opened, or the
375 /// file system is left untouched.
376 ///
377 /// clang-%%-%%-%%-%%-%%.s => /tmp/clang-a0-b1-c2-d3-e4.s
378 ///
379 /// @param model Name to base unique path off of.
380 /// @param result_fs Set to the opened file's file descriptor.
381 /// @param result_path Set to the opened file's absolute path.
382 /// @param makeAbsolute If true and @model is not an absolute path, a temp
383 ///        directory will be prepended.
384 /// @results errc::success if result_{fd,path} have been successfully set,
385 ///          otherwise a platform specific error_code.
386 error_code unique_file(const Twine &model, int &result_fd,
387                              SmallVectorImpl<char> &result_path,
388                              bool makeAbsolute = true);
389
390 /// @brief Canonicalize path.
391 ///
392 /// Sets result to the file system's idea of what path is. Path must be
393 /// absolute. The result has the same case as the file system.
394 ///
395 /// Example: Give a file system with "C:\a\b\c\file.txt".
396 ///
397 /// C:\A\b\C\fIlE.TxT => C:\a\b\c\file.txt
398 ///
399 /// @param path Input path.
400 /// @param result Set to the canonicalized version of \a path.
401 /// @results errc::success if result has been successfully set, otherwise a
402 ///          platform specific error_code.
403 error_code canonicalize(const Twine &path, SmallVectorImpl<char> &result);
404
405 /// @brief Are \a path's first bytes \a magic?
406 ///
407 /// @param path Input path.
408 /// @param magic Byte sequence to compare \a path's first len(magic) bytes to.
409 /// @results errc::success if result has been successfully set, otherwise a
410 ///          platform specific error_code.
411 error_code has_magic(const Twine &path, const Twine &magic, bool &result);
412
413 /// @brief Get \a path's first \a len bytes.
414 ///
415 /// @param path Input path.
416 /// @param len Number of magic bytes to get.
417 /// @param result Set to the first \a len bytes in the file pointed to by
418 ///               \a path. Or the entire file if file_size(path) < len, in which
419 ///               case result.size() returns the size of the file.
420 /// @results errc::success if result has been successfully set,
421 ///          errc::value_too_large if len is larger then the file pointed to by
422 ///          \a path, otherwise a platform specific error_code.
423 error_code get_magic(const Twine &path, uint32_t len,
424                      SmallVectorImpl<char> &result);
425
426 /// @brief Get and identify \a path's type based on its content.
427 ///
428 /// @param path Input path.
429 /// @param result Set to the type of file, or LLVMFileType::Unknown_FileType.
430 /// @results errc::success if result has been successfully set, otherwise a
431 ///          platform specific error_code.
432 error_code identify_magic(const Twine &path, LLVMFileType &result);
433
434 /// @brief Get library paths the system linker uses.
435 ///
436 /// @param result Set to the list of system library paths.
437 /// @results errc::success if result has been successfully set, otherwise a
438 ///          platform specific error_code.
439 error_code GetSystemLibraryPaths(SmallVectorImpl<std::string> &result);
440
441 /// @brief Get bitcode library paths the system linker uses
442 ///        + LLVM_LIB_SEARCH_PATH + LLVM_LIBDIR.
443 ///
444 /// @param result Set to the list of bitcode library paths.
445 /// @results errc::success if result has been successfully set, otherwise a
446 ///          platform specific error_code.
447 error_code GetBitcodeLibraryPaths(SmallVectorImpl<std::string> &result);
448
449 /// @brief Find a library.
450 ///
451 /// Find the path to a library using its short name. Use the system
452 /// dependent library paths to locate the library.
453 ///
454 /// c => /usr/lib/libc.so
455 ///
456 /// @param short_name Library name one would give to the system linker.
457 /// @param result Set to the absolute path \a short_name represents.
458 /// @results errc::success if result has been successfully set, otherwise a
459 ///          platform specific error_code.
460 error_code FindLibrary(const Twine &short_name, SmallVectorImpl<char> &result);
461
462 /// @brief Get absolute path of main executable.
463 ///
464 /// @param argv0 The program name as it was spelled on the command line.
465 /// @param MainAddr Address of some symbol in the executable (not in a library).
466 /// @param result Set to the absolute path of the current executable.
467 /// @results errc::success if result has been successfully set, otherwise a
468 ///          platform specific error_code.
469 error_code GetMainExecutable(const char *argv0, void *MainAddr,
470                              SmallVectorImpl<char> &result);
471
472 /// @}
473 /// @name Iterators
474 /// @{
475
476 /// directory_entry - A single entry in a directory. Caches the status either
477 /// from the result of the iteration syscall, or the first time status is
478 /// called.
479 class directory_entry {
480   std::string Path;
481   mutable file_status Status;
482
483 public:
484   explicit directory_entry(const Twine &path, file_status st = file_status())
485     : Path(path.str())
486     , Status(st) {}
487
488   directory_entry() {}
489
490   void assign(const Twine &path, file_status st = file_status()) {
491     Path = path.str();
492     Status = st;
493   }
494
495   void replace_filename(const Twine &filename, file_status st = file_status());
496
497   const std::string &path() const { return Path; }
498   error_code status(file_status &result) const;
499
500   bool operator==(const directory_entry& rhs) const { return Path == rhs.Path; }
501   bool operator!=(const directory_entry& rhs) const { return !(*this == rhs); }
502   bool operator< (const directory_entry& rhs) const;
503   bool operator<=(const directory_entry& rhs) const;
504   bool operator> (const directory_entry& rhs) const;
505   bool operator>=(const directory_entry& rhs) const;
506 };
507
508 namespace detail {
509   struct DirIterState;
510
511   error_code directory_iterator_construct(DirIterState&, StringRef);
512   error_code directory_iterator_increment(DirIterState&);
513   error_code directory_iterator_destruct(DirIterState&);
514
515   /// DirIterState - Keeps state for the directory_iterator. It is reference
516   /// counted in order to preserve InputIterator semantics on copy.
517   struct DirIterState : public RefCountedBase<DirIterState> {
518     DirIterState()
519       : IterationHandle(0) {}
520
521     ~DirIterState() {
522       directory_iterator_destruct(*this);
523     }
524
525     intptr_t IterationHandle;
526     directory_entry CurrentEntry;
527   };
528 }
529
530 /// directory_iterator - Iterates through the entries in path. There is no
531 /// operator++ because we need an error_code. If it's really needed we can make
532 /// it call report_fatal_error on error.
533 class directory_iterator {
534   IntrusiveRefCntPtr<detail::DirIterState> State;
535
536 public:
537   explicit directory_iterator(const Twine &path, error_code &ec) {
538     State = new detail::DirIterState;
539     SmallString<128> path_storage;
540     ec = detail::directory_iterator_construct(*State,
541             path.toStringRef(path_storage));
542   }
543
544   explicit directory_iterator(const directory_entry &de, error_code &ec) {
545     State = new detail::DirIterState;
546     ec = detail::directory_iterator_construct(*State, de.path());
547   }
548
549   /// Construct end iterator.
550   directory_iterator() : State(new detail::DirIterState) {}
551
552   // No operator++ because we need error_code.
553   directory_iterator &increment(error_code &ec) {
554     ec = directory_iterator_increment(*State);
555     return *this;
556   }
557
558   const directory_entry &operator*() const { return State->CurrentEntry; }
559   const directory_entry *operator->() const { return &State->CurrentEntry; }
560
561   bool operator==(const directory_iterator &RHS) const {
562     return State->CurrentEntry == RHS.State->CurrentEntry;
563   }
564
565   bool operator!=(const directory_iterator &RHS) const {
566     return !(*this == RHS);
567   }
568   // Other members as required by
569   // C++ Std, 24.1.1 Input iterators [input.iterators]
570 };
571
572 namespace detail {
573   /// RecDirIterState - Keeps state for the recursive_directory_iterator. It is
574   /// reference counted in order to preserve InputIterator semantics on copy.
575   struct RecDirIterState : public RefCountedBase<RecDirIterState> {
576     RecDirIterState()
577       : Level(0)
578       , HasNoPushRequest(false) {}
579
580     std::stack<directory_iterator, std::vector<directory_iterator> > Stack;
581     uint16_t Level;
582     bool HasNoPushRequest;
583   };
584 }
585
586 /// recursive_directory_iterator - Same as directory_iterator except for it
587 /// recurses down into child directories.
588 class recursive_directory_iterator {
589   IntrusiveRefCntPtr<detail::RecDirIterState> State;
590
591 public:
592   recursive_directory_iterator() {}
593   explicit recursive_directory_iterator(const Twine &path, error_code &ec)
594     : State(new detail::RecDirIterState) {
595     State->Stack.push(directory_iterator(path, ec));
596     if (State->Stack.top() == directory_iterator())
597       State.reset();
598   }
599   // No operator++ because we need error_code.
600   recursive_directory_iterator &increment(error_code &ec) {
601     static const directory_iterator end_itr;
602
603     if (State->HasNoPushRequest)
604       State->HasNoPushRequest = false;
605     else {
606       file_status st;
607       if ((ec = State->Stack.top()->status(st))) return *this;
608       if (is_directory(st)) {
609         State->Stack.push(directory_iterator(*State->Stack.top(), ec));
610         if (ec) return *this;
611         if (State->Stack.top() != end_itr) {
612           ++State->Level;
613           return *this;
614         }
615         State->Stack.pop();
616       }
617     }
618
619     while (!State->Stack.empty()
620            && State->Stack.top().increment(ec) == end_itr) {
621       State->Stack.pop();
622       --State->Level;
623     }
624
625     // Check if we are done. If so, create an end iterator.
626     if (State->Stack.empty())
627       State.reset();
628
629     return *this;
630   }
631
632   const directory_entry &operator*() const { return *State->Stack.top(); };
633   const directory_entry *operator->() const { return &*State->Stack.top(); };
634
635   // observers
636   /// Gets the current level. Starting path is at level 0.
637   int level() const { return State->Level; }
638
639   /// Returns true if no_push has been called for this directory_entry.
640   bool no_push_request() const { return State->HasNoPushRequest; }
641
642   // modifiers
643   /// Goes up one level if Level > 0.
644   void pop() {
645     assert(State && "Cannot pop and end itertor!");
646     assert(State->Level > 0 && "Cannot pop an iterator with level < 1");
647
648     static const directory_iterator end_itr;
649     error_code ec;
650     do {
651       if (ec)
652         report_fatal_error("Error incrementing directory iterator.");
653       State->Stack.pop();
654       --State->Level;
655     } while (!State->Stack.empty()
656              && State->Stack.top().increment(ec) == end_itr);
657
658     // Check if we are done. If so, create an end iterator.
659     if (State->Stack.empty())
660       State.reset();
661   }
662
663   /// Does not go down into the current directory_entry.
664   void no_push() { State->HasNoPushRequest = true; }
665
666   bool operator==(const recursive_directory_iterator &RHS) const {
667     return State == RHS.State;
668   }
669
670   bool operator!=(const recursive_directory_iterator &RHS) const {
671     return !(*this == RHS);
672   }
673   // Other members as required by
674   // C++ Std, 24.1.1 Input iterators [input.iterators]
675 };
676
677 /// @}
678
679 } // end namespace fs
680 } // end namespace sys
681 } // end namespace llvm
682
683 #endif