272109d03d7c74499985ff691b2d1980b64e1688
[oota-llvm.git] / lib / Support / Unix / PathV2.inc
1 //===- llvm/Support/Unix/PathV2.cpp - 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 PathV2 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 #if HAVE_SYS_STAT_H
21 #include <sys/stat.h>
22 #endif
23 #if HAVE_FCNTL_H
24 #include <fcntl.h>
25 #endif
26 #if HAVE_DIRENT_H
27 # include <dirent.h>
28 # define NAMLEN(dirent) strlen((dirent)->d_name)
29 #else
30 # define dirent direct
31 # define NAMLEN(dirent) (dirent)->d_namlen
32 # if HAVE_SYS_NDIR_H
33 #  include <sys/ndir.h>
34 # endif
35 # if HAVE_SYS_DIR_H
36 #  include <sys/dir.h>
37 # endif
38 # if HAVE_NDIR_H
39 #  include <ndir.h>
40 # endif
41 #endif
42 #if HAVE_STDIO_H
43 #include <stdio.h>
44 #endif
45 #if HAVE_LIMITS_H
46 #include <limits.h>
47 #endif
48
49 using namespace llvm;
50
51 namespace {
52   /// This class automatically closes the given file descriptor when it goes out
53   /// of scope. You can take back explicit ownership of the file descriptor by
54   /// calling take(). The destructor does not verify that close was successful.
55   /// Therefore, never allow this class to call close on a file descriptor that
56   /// has been read from or written to.
57   struct AutoFD {
58     int FileDescriptor;
59
60     AutoFD(int fd) : FileDescriptor(fd) {}
61     ~AutoFD() {
62       if (FileDescriptor >= 0)
63         ::close(FileDescriptor);
64     }
65
66     int take() {
67       int ret = FileDescriptor;
68       FileDescriptor = -1;
69       return ret;
70     }
71
72     operator int() const {return FileDescriptor;}
73   };
74
75   error_code TempDir(SmallVectorImpl<char> &result) {
76     // FIXME: Don't use TMPDIR if program is SUID or SGID enabled.
77     const char *dir = 0;
78     (dir = std::getenv("TMPDIR" )) ||
79     (dir = std::getenv("TMP"    )) ||
80     (dir = std::getenv("TEMP"   )) ||
81     (dir = std::getenv("TEMPDIR")) ||
82 #ifdef P_tmpdir
83     (dir = P_tmpdir) ||
84 #endif
85     (dir = "/tmp");
86
87     result.clear();
88     StringRef d(dir);
89     result.append(d.begin(), d.end());
90     return success;
91   }
92 }
93
94 namespace llvm {
95 namespace sys  {
96 namespace fs {
97
98 error_code current_path(SmallVectorImpl<char> &result) {
99   result.reserve(MAXPATHLEN);
100
101   while (true) {
102     if (::getcwd(result.data(), result.capacity()) == 0) {
103       // See if there was a real error.
104       if (errno != errc::not_enough_memory)
105         return error_code(errno, system_category());
106       // Otherwise there just wasn't enough space.
107       result.reserve(result.capacity() * 2);
108     } else
109       break;
110   }
111
112   result.set_size(strlen(result.data()));
113   return success;
114 }
115
116 error_code copy_file(const Twine &from, const Twine &to, copy_option copt) {
117  // Get arguments.
118   SmallString<128> from_storage;
119   SmallString<128> to_storage;
120   StringRef f = from.toNullTerminatedStringRef(from_storage);
121   StringRef t = to.toNullTerminatedStringRef(to_storage);
122
123   const size_t buf_sz = 32768;
124   char buffer[buf_sz];
125   int from_file = -1, to_file = -1;
126
127   // Open from.
128   if ((from_file = ::open(f.begin(), O_RDONLY)) < 0)
129     return error_code(errno, system_category());
130   AutoFD from_fd(from_file);
131
132   // Stat from.
133   struct stat from_stat;
134   if (::stat(f.begin(), &from_stat) != 0)
135     return error_code(errno, system_category());
136
137   // Setup to flags.
138   int to_flags = O_CREAT | O_WRONLY;
139   if (copt == copy_option::fail_if_exists)
140     to_flags |= O_EXCL;
141
142   // Open to.
143   if ((to_file = ::open(t.begin(), to_flags, from_stat.st_mode)) < 0)
144     return error_code(errno, system_category());
145   AutoFD to_fd(to_file);
146
147   // Copy!
148   ssize_t sz, sz_read = 1, sz_write;
149   while (sz_read > 0 &&
150          (sz_read = ::read(from_fd, buffer, buf_sz)) > 0) {
151     // Allow for partial writes - see Advanced Unix Programming (2nd Ed.),
152     // Marc Rochkind, Addison-Wesley, 2004, page 94
153     sz_write = 0;
154     do {
155       if ((sz = ::write(to_fd, buffer + sz_write, sz_read - sz_write)) < 0) {
156         sz_read = sz;  // cause read loop termination.
157         break;         // error.
158       }
159       sz_write += sz;
160     } while (sz_write < sz_read);
161   }
162
163   // After all the file operations above the return value of close actually
164   // matters.
165   if (::close(from_fd.take()) < 0) sz_read = -1;
166   if (::close(to_fd.take()) < 0) sz_read = -1;
167
168   // Check for errors.
169   if (sz_read < 0)
170     return error_code(errno, system_category());
171
172   return success;
173 }
174
175 error_code create_directory(const Twine &path, bool &existed) {
176   SmallString<128> path_storage;
177   StringRef p = path.toNullTerminatedStringRef(path_storage);
178
179   if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
180     if (errno != errc::file_exists)
181       return error_code(errno, system_category());
182     existed = true;
183   } else
184     existed = false;
185
186   return success;
187 }
188
189 error_code create_hard_link(const Twine &to, const Twine &from) {
190   // Get arguments.
191   SmallString<128> from_storage;
192   SmallString<128> to_storage;
193   StringRef f = from.toNullTerminatedStringRef(from_storage);
194   StringRef t = to.toNullTerminatedStringRef(to_storage);
195
196   if (::link(t.begin(), f.begin()) == -1)
197     return error_code(errno, system_category());
198
199   return success;
200 }
201
202 error_code create_symlink(const Twine &to, const Twine &from) {
203   // Get arguments.
204   SmallString<128> from_storage;
205   SmallString<128> to_storage;
206   StringRef f = from.toNullTerminatedStringRef(from_storage);
207   StringRef t = to.toNullTerminatedStringRef(to_storage);
208
209   if (::symlink(t.begin(), f.begin()) == -1)
210     return error_code(errno, system_category());
211
212   return success;
213 }
214
215 error_code remove(const Twine &path, bool &existed) {
216   SmallString<128> path_storage;
217   StringRef p = path.toNullTerminatedStringRef(path_storage);
218
219   if (::remove(p.begin()) == -1) {
220     if (errno != errc::no_such_file_or_directory)
221       return error_code(errno, system_category());
222     existed = false;
223   } else
224     existed = true;
225
226   return success;
227 }
228
229 error_code rename(const Twine &from, const Twine &to) {
230   // Get arguments.
231   SmallString<128> from_storage;
232   SmallString<128> to_storage;
233   StringRef f = from.toNullTerminatedStringRef(from_storage);
234   StringRef t = to.toNullTerminatedStringRef(to_storage);
235
236   if (::rename(f.begin(), t.begin()) == -1) {
237     // If it's a cross device link, copy then delete, otherwise return the error
238     if (errno == EXDEV) {
239       if (error_code ec = copy_file(from, to, copy_option::overwrite_if_exists))
240         return ec;
241       bool Existed;
242       if (error_code ec = remove(from, Existed))
243         return ec;
244     } else
245       return error_code(errno, system_category());
246   }
247
248   return success;
249 }
250
251 error_code resize_file(const Twine &path, uint64_t size) {
252   SmallString<128> path_storage;
253   StringRef p = path.toNullTerminatedStringRef(path_storage);
254
255   if (::truncate(p.begin(), size) == -1)
256     return error_code(errno, system_category());
257
258   return success;
259 }
260
261 error_code exists(const Twine &path, bool &result) {
262   SmallString<128> path_storage;
263   StringRef p = path.toNullTerminatedStringRef(path_storage);
264
265   struct stat status;
266   if (::stat(p.begin(), &status) == -1) {
267     if (errno != errc::no_such_file_or_directory)
268       return error_code(errno, system_category());
269     result = false;
270   } else
271     result = true;
272
273   return success;
274 }
275
276 bool equivalent(file_status A, file_status B) {
277   assert(status_known(A) && status_known(B));
278   return A.st_dev == B.st_dev &&
279          A.st_ino == B.st_ino;
280 }
281
282 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
283   file_status fsA, fsB;
284   if (error_code ec = status(A, fsA)) return ec;
285   if (error_code ec = status(B, fsB)) return ec;
286   result = equivalent(fsA, fsB);
287   return success;
288 }
289
290 error_code file_size(const Twine &path, uint64_t &result) {
291   SmallString<128> path_storage;
292   StringRef p = path.toNullTerminatedStringRef(path_storage);
293
294   struct stat status;
295   if (::stat(p.begin(), &status) == -1)
296     return error_code(errno, system_category());
297   if (!S_ISREG(status.st_mode))
298     return make_error_code(errc::operation_not_permitted);
299
300   result = status.st_size;
301   return success;
302 }
303
304 error_code status(const Twine &path, file_status &result) {
305   SmallString<128> path_storage;
306   StringRef p = path.toNullTerminatedStringRef(path_storage);
307
308   struct stat status;
309   if (::stat(p.begin(), &status) != 0) {
310     error_code ec(errno, system_category());
311     if (ec == errc::no_such_file_or_directory)
312       result = file_status(file_type::file_not_found);
313     else
314       result = file_status(file_type::status_error);
315     return ec;
316   }
317
318   if (S_ISDIR(status.st_mode))
319     result = file_status(file_type::directory_file);
320   else if (S_ISREG(status.st_mode))
321     result = file_status(file_type::regular_file);
322   else if (S_ISBLK(status.st_mode))
323     result = file_status(file_type::block_file);
324   else if (S_ISCHR(status.st_mode))
325     result = file_status(file_type::character_file);
326   else if (S_ISFIFO(status.st_mode))
327     result = file_status(file_type::fifo_file);
328   else if (S_ISSOCK(status.st_mode))
329     result = file_status(file_type::socket_file);
330   else
331     result = file_status(file_type::type_unknown);
332
333   result.st_dev = status.st_dev;
334   result.st_ino = status.st_ino;
335
336   return success;
337 }
338
339 error_code unique_file(const Twine &model, int &result_fd,
340                              SmallVectorImpl<char> &result_path,
341                              bool makeAbsolute) {
342   SmallString<128> Model;
343   model.toVector(Model);
344   // Null terminate.
345   Model.c_str();
346
347   if (makeAbsolute) {
348     // Make model absolute by prepending a temp directory if it's not already.
349     bool absolute = path::is_absolute(Twine(Model));
350     if (!absolute) {
351       SmallString<128> TDir;
352       if (error_code ec = TempDir(TDir)) return ec;
353       path::append(TDir, Twine(Model));
354       Model.swap(TDir);
355     }
356   }
357
358   // Replace '%' with random chars. From here on, DO NOT modify model. It may be
359   // needed if the randomly chosen path already exists.
360   SmallString<128> RandomPath;
361   RandomPath.reserve(Model.size() + 1);
362   ::srand(::time(NULL));
363
364 retry_random_path:
365   // This is opened here instead of above to make it easier to track when to
366   // close it. Collisions should be rare enough for the possible extra syscalls
367   // not to matter.
368   FILE *RandomSource = ::fopen("/dev/urandom", "r");
369   RandomPath.set_size(0);
370   for (SmallVectorImpl<char>::const_iterator i = Model.begin(),
371                                              e = Model.end(); i != e; ++i) {
372     if (*i == '%') {
373       char val = 0;
374       if (RandomSource)
375         val = fgetc(RandomSource);
376       else
377         val = ::rand();
378       RandomPath.push_back("0123456789abcdef"[val & 15]);
379     } else
380       RandomPath.push_back(*i);
381   }
382
383   if (RandomSource)
384     ::fclose(RandomSource);
385
386   // Try to open + create the file.
387 rety_open_create:
388   int RandomFD = ::open(RandomPath.c_str(), O_RDWR | O_CREAT | O_EXCL, 0600);
389   if (RandomFD == -1) {
390     // If the file existed, try again, otherwise, error.
391     if (errno == errc::file_exists)
392       goto retry_random_path;
393     // The path prefix doesn't exist.
394     if (errno == errc::no_such_file_or_directory) {
395       StringRef p(RandomPath.begin(), RandomPath.size());
396       SmallString<64> dir_to_create;
397       for (path::const_iterator i = path::begin(p),
398                                 e = --path::end(p); i != e; ++i) {
399         path::append(dir_to_create, *i);
400         bool Exists;
401         if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
402         if (!Exists) {
403           // Don't try to create network paths.
404           if (i->size() > 2 && (*i)[0] == '/' &&
405                                (*i)[1] == '/' &&
406                                (*i)[2] != '/')
407             return make_error_code(errc::no_such_file_or_directory);
408           if (::mkdir(dir_to_create.c_str(), 0700) == -1)
409             return error_code(errno, system_category());
410         }
411       }
412       goto rety_open_create;
413     }
414     return error_code(errno, system_category());
415   }
416
417    // Make the path absolute.
418   char real_path_buff[PATH_MAX + 1];
419   if (realpath(RandomPath.c_str(), real_path_buff) == NULL) {
420     int error = errno;
421     ::close(RandomFD);
422     ::unlink(RandomPath.c_str());
423     return error_code(error, system_category());
424   }
425
426   result_path.clear();
427   StringRef d(real_path_buff);
428   result_path.append(d.begin(), d.end());
429
430   result_fd = RandomFD;
431   return success;
432 }
433
434 error_code detail::directory_iterator_construct(detail::DirIterState &it,
435                                                 StringRef path){
436   SmallString<128> path_null(path);
437   DIR *directory = ::opendir(path_null.c_str());
438   if (directory == 0)
439     return error_code(errno, system_category());
440
441   it.IterationHandle = reinterpret_cast<intptr_t>(directory);
442   // Add something for replace_filename to replace.
443   path::append(path_null, ".");
444   it.CurrentEntry = directory_entry(path_null.str());
445   return directory_iterator_increment(it);
446 }
447
448 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
449   if (it.IterationHandle)
450     ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
451   it.IterationHandle = 0;
452   it.CurrentEntry = directory_entry();
453   return success;
454 }
455
456 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
457   errno = 0;
458   dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
459   if (cur_dir == 0 && errno != 0) {
460     return error_code(errno, system_category());
461   } else if (cur_dir != 0) {
462     StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
463     if ((name.size() == 1 && name[0] == '.') ||
464         (name.size() == 2 && name[0] == '.' && name[1] == '.'))
465       return directory_iterator_increment(it);
466     it.CurrentEntry.replace_filename(name);
467   } else
468     return directory_iterator_destruct(it);
469
470   return success;
471 }
472
473 error_code get_magic(const Twine &path, uint32_t len,
474                      SmallVectorImpl<char> &result) {
475   SmallString<128> PathStorage;
476   StringRef Path = path.toNullTerminatedStringRef(PathStorage);
477   result.set_size(0);
478
479   // Open path.
480   std::FILE *file = std::fopen(Path.data(), "rb");
481   if (file == 0)
482     return error_code(errno, system_category());
483
484   // Reserve storage.
485   result.reserve(len);
486
487   // Read magic!
488   size_t size = std::fread(result.data(), 1, len, file);
489   if (std::ferror(file) != 0) {
490     std::fclose(file);
491     return error_code(errno, system_category());
492   } else if (size != result.size()) {
493     if (std::feof(file) != 0) {
494       std::fclose(file);
495       result.set_size(size);
496       return make_error_code(errc::value_too_large);
497     }
498   }
499   std::fclose(file);
500   result.set_size(len);
501   return success;
502 }
503
504 } // end namespace fs
505 } // end namespace sys
506 } // end namespace llvm