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