Remove a convoluted way of calling close by moving the call to the only caller.
[oota-llvm.git] / lib / Support / Unix / Path.inc
1 //===- llvm/Support/Unix/Path.inc - Unix Path Implementation ----*- 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 implements the Unix specific implementation of the Path API.
11 //
12 //===----------------------------------------------------------------------===//
13
14 //===----------------------------------------------------------------------===//
15 //=== WARNING: Implementation here must contain only generic UNIX code that
16 //===          is guaranteed to work on *all* UNIX variants.
17 //===----------------------------------------------------------------------===//
18
19 #include "Unix.h"
20 #include <limits.h>
21 #include <stdio.h>
22 #if HAVE_SYS_STAT_H
23 #include <sys/stat.h>
24 #endif
25 #if HAVE_FCNTL_H
26 #include <fcntl.h>
27 #endif
28 #ifdef HAVE_SYS_MMAN_H
29 #include <sys/mman.h>
30 #endif
31 #if HAVE_DIRENT_H
32 # include <dirent.h>
33 # define NAMLEN(dirent) strlen((dirent)->d_name)
34 #else
35 # define dirent direct
36 # define NAMLEN(dirent) (dirent)->d_namlen
37 # if HAVE_SYS_NDIR_H
38 #  include <sys/ndir.h>
39 # endif
40 # if HAVE_SYS_DIR_H
41 #  include <sys/dir.h>
42 # endif
43 # if HAVE_NDIR_H
44 #  include <ndir.h>
45 # endif
46 #endif
47
48 #ifdef __APPLE__
49 #include <mach-o/dyld.h>
50 #endif
51
52 // Both stdio.h and cstdio are included via different pathes and
53 // stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
54 // either.
55 #undef ferror
56 #undef feof
57
58 // For GNU Hurd
59 #if defined(__GNU__) && !defined(PATH_MAX)
60 # define PATH_MAX 4096
61 #endif
62
63 using namespace llvm;
64
65 namespace llvm {
66 namespace sys  {
67 namespace fs {
68 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
69     defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
70     defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__)
71 static int
72 test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
73 {  
74   struct stat sb;
75   char fullpath[PATH_MAX];
76
77   snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
78   if (realpath(fullpath, ret) == NULL)
79     return (1);
80   if (stat(fullpath, &sb) != 0)
81     return (1);
82
83   return (0);
84 }
85
86 static char *
87 getprogpath(char ret[PATH_MAX], const char *bin)
88 {
89   char *pv, *s, *t;
90
91   /* First approach: absolute path. */
92   if (bin[0] == '/') {
93     if (test_dir(ret, "/", bin) == 0)
94       return (ret);
95     return (NULL);
96   }
97
98   /* Second approach: relative path. */
99   if (strchr(bin, '/') != NULL) {
100     char cwd[PATH_MAX];
101     if (getcwd(cwd, PATH_MAX) == NULL)
102       return (NULL);
103     if (test_dir(ret, cwd, bin) == 0)
104       return (ret);
105     return (NULL);
106   }
107
108   /* Third approach: $PATH */
109   if ((pv = getenv("PATH")) == NULL)
110     return (NULL);
111   s = pv = strdup(pv);
112   if (pv == NULL)
113     return (NULL);
114   while ((t = strsep(&s, ":")) != NULL) {
115     if (test_dir(ret, t, bin) == 0) {
116       free(pv);
117       return (ret);
118     }
119   }
120   free(pv);
121   return (NULL);
122 }
123 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
124
125 /// GetMainExecutable - Return the path to the main executable, given the
126 /// value of argv[0] from program startup.
127 std::string getMainExecutable(const char *argv0, void *MainAddr) {
128 #if defined(__APPLE__)
129   // On OS X the executable path is saved to the stack by dyld. Reading it
130   // from there is much faster than calling dladdr, especially for large
131   // binaries with symbols.
132   char exe_path[MAXPATHLEN];
133   uint32_t size = sizeof(exe_path);
134   if (_NSGetExecutablePath(exe_path, &size) == 0) {
135     char link_path[MAXPATHLEN];
136     if (realpath(exe_path, link_path))
137       return link_path;
138   }
139 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
140       defined(__OpenBSD__) || defined(__minix) || defined(__DragonFly__) || \
141       defined(__FreeBSD_kernel__)
142   char exe_path[PATH_MAX];
143
144   if (getprogpath(exe_path, argv0) != NULL)
145     return exe_path;
146 #elif defined(__linux__) || defined(__CYGWIN__)
147   char exe_path[MAXPATHLEN];
148   StringRef aPath("/proc/self/exe");
149   if (sys::fs::exists(aPath)) {
150       // /proc is not always mounted under Linux (chroot for example).
151       ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
152       if (len >= 0)
153           return StringRef(exe_path, len);
154   } else {
155       // Fall back to the classical detection.
156       if (getprogpath(exe_path, argv0) != NULL)
157           return exe_path;
158   }
159 #elif defined(HAVE_DLFCN_H)
160   // Use dladdr to get executable path if available.
161   Dl_info DLInfo;
162   int err = dladdr(MainAddr, &DLInfo);
163   if (err == 0)
164     return "";
165
166   // If the filename is a symlink, we need to resolve and return the location of
167   // the actual executable.
168   char link_path[MAXPATHLEN];
169   if (realpath(DLInfo.dli_fname, link_path))
170     return link_path;
171 #else
172 #error GetMainExecutable is not implemented on this host yet.
173 #endif
174   return "";
175 }
176
177 TimeValue file_status::getLastModificationTime() const {
178   TimeValue Ret;
179   Ret.fromEpochTime(fs_st_mtime);
180   return Ret;
181 }
182
183 UniqueID file_status::getUniqueID() const {
184   return UniqueID(fs_st_dev, fs_st_ino);
185 }
186
187 std::error_code current_path(SmallVectorImpl<char> &result) {
188   result.clear();
189
190   const char *pwd = ::getenv("PWD");
191   llvm::sys::fs::file_status PWDStatus, DotStatus;
192   if (pwd && llvm::sys::path::is_absolute(pwd) &&
193       !llvm::sys::fs::status(pwd, PWDStatus) &&
194       !llvm::sys::fs::status(".", DotStatus) &&
195       PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
196     result.append(pwd, pwd + strlen(pwd));
197     return std::error_code();
198   }
199
200 #ifdef MAXPATHLEN
201   result.reserve(MAXPATHLEN);
202 #else
203 // For GNU Hurd
204   result.reserve(1024);
205 #endif
206
207   while (true) {
208     if (::getcwd(result.data(), result.capacity()) == nullptr) {
209       // See if there was a real error.
210       if (errno != ENOMEM)
211         return std::error_code(errno, std::generic_category());
212       // Otherwise there just wasn't enough space.
213       result.reserve(result.capacity() * 2);
214     } else
215       break;
216   }
217
218   result.set_size(strlen(result.data()));
219   return std::error_code();
220 }
221
222 std::error_code create_directory(const Twine &path, bool IgnoreExisting) {
223   SmallString<128> path_storage;
224   StringRef p = path.toNullTerminatedStringRef(path_storage);
225
226   if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
227     if (errno != EEXIST || !IgnoreExisting)
228       return std::error_code(errno, std::generic_category());
229   }
230
231   return std::error_code();
232 }
233
234 // Note that we are using symbolic link because hard links are not supported by
235 // all filesystems (SMB doesn't).
236 std::error_code create_link(const Twine &to, const Twine &from) {
237   // Get arguments.
238   SmallString<128> from_storage;
239   SmallString<128> to_storage;
240   StringRef f = from.toNullTerminatedStringRef(from_storage);
241   StringRef t = to.toNullTerminatedStringRef(to_storage);
242
243   if (::symlink(t.begin(), f.begin()) == -1)
244     return std::error_code(errno, std::generic_category());
245
246   return std::error_code();
247 }
248
249 std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
250   SmallString<128> path_storage;
251   StringRef p = path.toNullTerminatedStringRef(path_storage);
252
253   struct stat buf;
254   if (lstat(p.begin(), &buf) != 0) {
255     if (errno != ENOENT || !IgnoreNonExisting)
256       return std::error_code(errno, std::generic_category());
257     return std::error_code();
258   }
259
260   // Note: this check catches strange situations. In all cases, LLVM should
261   // only be involved in the creation and deletion of regular files.  This
262   // check ensures that what we're trying to erase is a regular file. It
263   // effectively prevents LLVM from erasing things like /dev/null, any block
264   // special file, or other things that aren't "regular" files.
265   if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
266     return make_error_code(errc::operation_not_permitted);
267
268   if (::remove(p.begin()) == -1) {
269     if (errno != ENOENT || !IgnoreNonExisting)
270       return std::error_code(errno, std::generic_category());
271   }
272
273   return std::error_code();
274 }
275
276 std::error_code rename(const Twine &from, const Twine &to) {
277   // Get arguments.
278   SmallString<128> from_storage;
279   SmallString<128> to_storage;
280   StringRef f = from.toNullTerminatedStringRef(from_storage);
281   StringRef t = to.toNullTerminatedStringRef(to_storage);
282
283   if (::rename(f.begin(), t.begin()) == -1)
284     return std::error_code(errno, std::generic_category());
285
286   return std::error_code();
287 }
288
289 std::error_code resize_file(const Twine &path, uint64_t size) {
290   SmallString<128> path_storage;
291   StringRef p = path.toNullTerminatedStringRef(path_storage);
292
293   if (::truncate(p.begin(), size) == -1)
294     return std::error_code(errno, std::generic_category());
295
296   return std::error_code();
297 }
298
299 static int convertAccessMode(AccessMode Mode) {
300   switch (Mode) {
301   case AccessMode::Exist:
302     return F_OK;
303   case AccessMode::Write:
304     return W_OK;
305   case AccessMode::Execute:
306     return R_OK | X_OK; // scripts also need R_OK.
307   }
308   llvm_unreachable("invalid enum");
309 }
310
311 std::error_code access(const Twine &Path, AccessMode Mode) {
312   SmallString<128> PathStorage;
313   StringRef P = Path.toNullTerminatedStringRef(PathStorage);
314
315   if (::access(P.begin(), convertAccessMode(Mode)) == -1)
316     return std::error_code(errno, std::generic_category());
317
318   if (Mode == AccessMode::Execute) {
319     // Don't say that directories are executable.
320     struct stat buf;
321     if (0 != stat(P.begin(), &buf))
322       return errc::permission_denied;
323     if (!S_ISREG(buf.st_mode))
324       return errc::permission_denied;
325   }
326
327   return std::error_code();
328 }
329
330 bool equivalent(file_status A, file_status B) {
331   assert(status_known(A) && status_known(B));
332   return A.fs_st_dev == B.fs_st_dev &&
333          A.fs_st_ino == B.fs_st_ino;
334 }
335
336 std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
337   file_status fsA, fsB;
338   if (std::error_code ec = status(A, fsA))
339     return ec;
340   if (std::error_code ec = status(B, fsB))
341     return ec;
342   result = equivalent(fsA, fsB);
343   return std::error_code();
344 }
345
346 static std::error_code fillStatus(int StatRet, const struct stat &Status,
347                              file_status &Result) {
348   if (StatRet != 0) {
349     std::error_code ec(errno, std::generic_category());
350     if (ec == errc::no_such_file_or_directory)
351       Result = file_status(file_type::file_not_found);
352     else
353       Result = file_status(file_type::status_error);
354     return ec;
355   }
356
357   file_type Type = file_type::type_unknown;
358
359   if (S_ISDIR(Status.st_mode))
360     Type = file_type::directory_file;
361   else if (S_ISREG(Status.st_mode))
362     Type = file_type::regular_file;
363   else if (S_ISBLK(Status.st_mode))
364     Type = file_type::block_file;
365   else if (S_ISCHR(Status.st_mode))
366     Type = file_type::character_file;
367   else if (S_ISFIFO(Status.st_mode))
368     Type = file_type::fifo_file;
369   else if (S_ISSOCK(Status.st_mode))
370     Type = file_type::socket_file;
371
372   perms Perms = static_cast<perms>(Status.st_mode);
373   Result =
374       file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
375                   Status.st_uid, Status.st_gid, Status.st_size);
376
377   return std::error_code();
378 }
379
380 std::error_code status(const Twine &Path, file_status &Result) {
381   SmallString<128> PathStorage;
382   StringRef P = Path.toNullTerminatedStringRef(PathStorage);
383
384   struct stat Status;
385   int StatRet = ::stat(P.begin(), &Status);
386   return fillStatus(StatRet, Status, Result);
387 }
388
389 std::error_code status(int FD, file_status &Result) {
390   struct stat Status;
391   int StatRet = ::fstat(FD, &Status);
392   return fillStatus(StatRet, Status, Result);
393 }
394
395 std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
396 #if defined(HAVE_FUTIMENS)
397   timespec Times[2];
398   Times[0].tv_sec = Time.toEpochTime();
399   Times[0].tv_nsec = 0;
400   Times[1] = Times[0];
401   if (::futimens(FD, Times))
402     return std::error_code(errno, std::generic_category());
403   return std::error_code();
404 #elif defined(HAVE_FUTIMES)
405   timeval Times[2];
406   Times[0].tv_sec = Time.toEpochTime();
407   Times[0].tv_usec = 0;
408   Times[1] = Times[0];
409   if (::futimes(FD, Times))
410     return std::error_code(errno, std::generic_category());
411   return std::error_code();
412 #else
413 #warning Missing futimes() and futimens()
414   return make_error_code(errc::function_not_supported);
415 #endif
416 }
417
418 std::error_code mapped_file_region::init(int FD, uint64_t Offset,
419                                          mapmode Mode) {
420   // Figure out how large the file is.
421   struct stat FileInfo;
422   if (fstat(FD, &FileInfo) == -1)
423     return std::error_code(errno, std::generic_category());
424   uint64_t FileSize = FileInfo.st_size;
425
426   if (Size == 0)
427     Size = FileSize;
428   else if (FileSize < Size) {
429     // We need to grow the file.
430     if (ftruncate(FD, Size) == -1)
431       return std::error_code(errno, std::generic_category());
432   }
433
434   int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
435   int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
436 #ifdef MAP_FILE
437   flags |= MAP_FILE;
438 #endif
439   Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
440   if (Mapping == MAP_FAILED)
441     return std::error_code(errno, std::generic_category());
442   return std::error_code();
443 }
444
445 mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
446                                        uint64_t offset, std::error_code &ec)
447     : Size(length), Mapping() {
448   // Make sure that the requested size fits within SIZE_T.
449   if (length > std::numeric_limits<size_t>::max()) {
450     ec = make_error_code(errc::invalid_argument);
451     return;
452   }
453
454   ec = init(fd, offset, mode);
455   if (ec)
456     Mapping = nullptr;
457 }
458
459 mapped_file_region::~mapped_file_region() {
460   if (Mapping)
461     ::munmap(Mapping, Size);
462 }
463
464 uint64_t mapped_file_region::size() const {
465   assert(Mapping && "Mapping failed but used anyway!");
466   return Size;
467 }
468
469 char *mapped_file_region::data() const {
470   assert(Mapping && "Mapping failed but used anyway!");
471   return reinterpret_cast<char*>(Mapping);
472 }
473
474 const char *mapped_file_region::const_data() const {
475   assert(Mapping && "Mapping failed but used anyway!");
476   return reinterpret_cast<const char*>(Mapping);
477 }
478
479 int mapped_file_region::alignment() {
480   return Process::getPageSize();
481 }
482
483 std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
484                                                 StringRef path){
485   SmallString<128> path_null(path);
486   DIR *directory = ::opendir(path_null.c_str());
487   if (!directory)
488     return std::error_code(errno, std::generic_category());
489
490   it.IterationHandle = reinterpret_cast<intptr_t>(directory);
491   // Add something for replace_filename to replace.
492   path::append(path_null, ".");
493   it.CurrentEntry = directory_entry(path_null.str());
494   return directory_iterator_increment(it);
495 }
496
497 std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
498   if (it.IterationHandle)
499     ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
500   it.IterationHandle = 0;
501   it.CurrentEntry = directory_entry();
502   return std::error_code();
503 }
504
505 std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
506   errno = 0;
507   dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
508   if (cur_dir == nullptr && errno != 0) {
509     return std::error_code(errno, std::generic_category());
510   } else if (cur_dir != nullptr) {
511     StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
512     if ((name.size() == 1 && name[0] == '.') ||
513         (name.size() == 2 && name[0] == '.' && name[1] == '.'))
514       return directory_iterator_increment(it);
515     it.CurrentEntry.replace_filename(name);
516   } else
517     return directory_iterator_destruct(it);
518
519   return std::error_code();
520 }
521
522 std::error_code openFileForRead(const Twine &Name, int &ResultFD) {
523   SmallString<128> Storage;
524   StringRef P = Name.toNullTerminatedStringRef(Storage);
525   while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
526     if (errno != EINTR)
527       return std::error_code(errno, std::generic_category());
528   }
529   return std::error_code();
530 }
531
532 std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
533                             sys::fs::OpenFlags Flags, unsigned Mode) {
534   // Verify that we don't have both "append" and "excl".
535   assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
536          "Cannot specify both 'excl' and 'append' file creation flags!");
537
538   int OpenFlags = O_CREAT;
539
540   if (Flags & F_RW)
541     OpenFlags |= O_RDWR;
542   else
543     OpenFlags |= O_WRONLY;
544
545   if (Flags & F_Append)
546     OpenFlags |= O_APPEND;
547   else
548     OpenFlags |= O_TRUNC;
549
550   if (Flags & F_Excl)
551     OpenFlags |= O_EXCL;
552
553   SmallString<128> Storage;
554   StringRef P = Name.toNullTerminatedStringRef(Storage);
555   while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
556     if (errno != EINTR)
557       return std::error_code(errno, std::generic_category());
558   }
559   return std::error_code();
560 }
561
562 } // end namespace fs
563
564 namespace path {
565
566 bool home_directory(SmallVectorImpl<char> &result) {
567   if (char *RequestedDir = getenv("HOME")) {
568     result.clear();
569     result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
570     return true;
571   }
572
573   return false;
574 }
575
576 static const char *getEnvTempDir() {
577   // Check whether the temporary directory is specified by an environment
578   // variable.
579   const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
580   for (const char *Env : EnvironmentVariables) {
581     if (const char *Dir = std::getenv(Env))
582       return Dir;
583   }
584
585   return nullptr;
586 }
587
588 static const char *getDefaultTempDir(bool ErasedOnReboot) {
589 #ifdef P_tmpdir
590   if ((bool)P_tmpdir)
591     return P_tmpdir;
592 #endif
593
594   if (ErasedOnReboot)
595     return "/tmp";
596   return "/var/tmp";
597 }
598
599 void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
600   Result.clear();
601
602   if (ErasedOnReboot) {
603     // There is no env variable for the cache directory.
604     if (const char *RequestedDir = getEnvTempDir()) {
605       Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
606       return;
607     }
608   }
609
610 #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
611   // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
612   // macros defined in <unistd.h> on darwin >= 9
613   int ConfName = ErasedOnReboot? _CS_DARWIN_USER_TEMP_DIR
614                                : _CS_DARWIN_USER_CACHE_DIR;
615   size_t ConfLen = confstr(ConfName, nullptr, 0);
616   if (ConfLen > 0) {
617     do {
618       Result.resize(ConfLen);
619       ConfLen = confstr(ConfName, Result.data(), Result.size());
620     } while (ConfLen > 0 && ConfLen != Result.size());
621
622     if (ConfLen > 0) {
623       assert(Result.back() == 0);
624       Result.pop_back();
625       return;
626     }
627
628     Result.clear();
629   }
630 #endif
631
632   const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
633   Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
634 }
635
636 } // end namespace path
637
638 } // end namespace sys
639 } // end namespace llvm