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