7477b4f2a08bf37fde8dad7bfe1e31326cdaf5b5
[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 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
277   // Get arguments.
278   SmallString<128> a_storage;
279   SmallString<128> b_storage;
280   StringRef a = A.toNullTerminatedStringRef(a_storage);
281   StringRef b = B.toNullTerminatedStringRef(b_storage);
282
283   struct stat stat_a, stat_b;
284   int error_b = ::stat(b.begin(), &stat_b);
285   int error_a = ::stat(a.begin(), &stat_a);
286
287   // If both are invalid, it's an error. If only one is, the result is false.
288   if (error_a != 0 || error_b != 0) {
289     if (error_a == error_b)
290       return error_code(errno, system_category());
291     result = false;
292   } else {
293     result =
294       stat_a.st_dev == stat_b.st_dev &&
295       stat_a.st_ino == stat_b.st_ino;
296   }
297
298   return success;
299 }
300
301 error_code file_size(const Twine &path, uint64_t &result) {
302   SmallString<128> path_storage;
303   StringRef p = path.toNullTerminatedStringRef(path_storage);
304
305   struct stat status;
306   if (::stat(p.begin(), &status) == -1)
307     return error_code(errno, system_category());
308   if (!S_ISREG(status.st_mode))
309     return make_error_code(errc::operation_not_permitted);
310
311   result = status.st_size;
312   return success;
313 }
314
315 error_code status(const Twine &path, file_status &result) {
316   SmallString<128> path_storage;
317   StringRef p = path.toNullTerminatedStringRef(path_storage);
318
319   struct stat status;
320   if (::stat(p.begin(), &status) != 0) {
321     error_code ec(errno, system_category());
322     if (ec == errc::no_such_file_or_directory)
323       result = file_status(file_type::file_not_found);
324     else
325       result = file_status(file_type::status_error);
326     return ec;
327   }
328
329   if (S_ISDIR(status.st_mode))
330     result = file_status(file_type::directory_file);
331   else if (S_ISREG(status.st_mode))
332     result = file_status(file_type::regular_file);
333   else if (S_ISBLK(status.st_mode))
334     result = file_status(file_type::block_file);
335   else if (S_ISCHR(status.st_mode))
336     result = file_status(file_type::character_file);
337   else if (S_ISFIFO(status.st_mode))
338     result = file_status(file_type::fifo_file);
339   else if (S_ISSOCK(status.st_mode))
340     result = file_status(file_type::socket_file);
341   else
342     result = file_status(file_type::type_unknown);
343
344   return success;
345 }
346
347 error_code unique_file(const Twine &model, int &result_fd,
348                              SmallVectorImpl<char> &result_path,
349                              bool makeAbsolute) {
350   SmallString<128> Model;
351   model.toVector(Model);
352   // Null terminate.
353   Model.c_str();
354
355   if (makeAbsolute) {
356     // Make model absolute by prepending a temp directory if it's not already.
357     bool absolute = path::is_absolute(Twine(Model));
358     if (!absolute) {
359       SmallString<128> TDir;
360       if (error_code ec = TempDir(TDir)) return ec;
361       path::append(TDir, Twine(Model));
362       Model.swap(TDir);
363     }
364   }
365
366   // Replace '%' with random chars. From here on, DO NOT modify model. It may be
367   // needed if the randomly chosen path already exists.
368   SmallString<128> RandomPath;
369   RandomPath.reserve(Model.size() + 1);
370   ::srand(::time(NULL));
371
372 retry_random_path:
373   // This is opened here instead of above to make it easier to track when to
374   // close it. Collisions should be rare enough for the possible extra syscalls
375   // not to matter.
376   FILE *RandomSource = ::fopen("/dev/urandom", "r");
377   RandomPath.set_size(0);
378   for (SmallVectorImpl<char>::const_iterator i = Model.begin(),
379                                              e = Model.end(); i != e; ++i) {
380     if (*i == '%') {
381       char val = 0;
382       if (RandomSource)
383         val = fgetc(RandomSource);
384       else
385         val = ::rand();
386       RandomPath.push_back("0123456789abcdef"[val & 15]);
387     } else
388       RandomPath.push_back(*i);
389   }
390
391   if (RandomSource)
392     ::fclose(RandomSource);
393
394   // Try to open + create the file.
395 rety_open_create:
396   int RandomFD = ::open(RandomPath.c_str(), O_RDWR | O_CREAT | O_EXCL, 0600);
397   if (RandomFD == -1) {
398     // If the file existed, try again, otherwise, error.
399     if (errno == errc::file_exists)
400       goto retry_random_path;
401     // The path prefix doesn't exist.
402     if (errno == errc::no_such_file_or_directory) {
403       StringRef p(RandomPath.begin(), RandomPath.size());
404       SmallString<64> dir_to_create;
405       for (path::const_iterator i = path::begin(p),
406                                 e = --path::end(p); i != e; ++i) {
407         path::append(dir_to_create, *i);
408         bool Exists;
409         if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
410         if (!Exists) {
411           // Don't try to create network paths.
412           if (i->size() > 2 && (*i)[0] == '/' &&
413                                (*i)[1] == '/' &&
414                                (*i)[2] != '/')
415             return make_error_code(errc::no_such_file_or_directory);
416           if (::mkdir(dir_to_create.c_str(), 0700) == -1)
417             return error_code(errno, system_category());
418         }
419       }
420       goto rety_open_create;
421     }
422     return error_code(errno, system_category());
423   }
424
425    // Make the path absolute.
426   char real_path_buff[PATH_MAX + 1];
427   if (realpath(RandomPath.c_str(), real_path_buff) == NULL) {
428     int error = errno;
429     ::close(RandomFD);
430     ::unlink(RandomPath.c_str());
431     return error_code(error, system_category());
432   }
433
434   result_path.clear();
435   StringRef d(real_path_buff);
436   result_path.append(d.begin(), d.end());
437
438   result_fd = RandomFD;
439   return success;
440 }
441
442 error_code detail::directory_iterator_construct(detail::DirIterState &it,
443                                                 StringRef path){
444   SmallString<128> path_null(path);
445   DIR *directory = ::opendir(path_null.c_str());
446   if (directory == 0)
447     return error_code(errno, system_category());
448
449   it.IterationHandle = reinterpret_cast<intptr_t>(directory);
450   // Add something for replace_filename to replace.
451   path::append(path_null, ".");
452   it.CurrentEntry = directory_entry(path_null.str());
453   return directory_iterator_increment(it);
454 }
455
456 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
457   if (it.IterationHandle)
458     ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
459   it.IterationHandle = 0;
460   it.CurrentEntry = directory_entry();
461   return success;
462 }
463
464 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
465   errno = 0;
466   dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
467   if (cur_dir == 0 && errno != 0) {
468     return error_code(errno, system_category());
469   } else if (cur_dir != 0) {
470     StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
471     if ((name.size() == 1 && name[0] == '.') ||
472         (name.size() == 2 && name[0] == '.' && name[1] == '.'))
473       return directory_iterator_increment(it);
474     it.CurrentEntry.replace_filename(name);
475   } else
476     return directory_iterator_destruct(it);
477
478   return success;
479 }
480
481 error_code get_magic(const Twine &path, uint32_t len,
482                      SmallVectorImpl<char> &result) {
483   SmallString<128> PathStorage;
484   StringRef Path = path.toNullTerminatedStringRef(PathStorage);
485   result.set_size(0);
486
487   // Open path.
488   std::FILE *file = std::fopen(Path.data(), "rb");
489   if (file == 0)
490     return error_code(errno, system_category());
491
492   // Reserve storage.
493   result.reserve(len);
494
495   // Read magic!
496   size_t size = std::fread(result.data(), 1, len, file);
497   if (std::ferror(file) != 0) {
498     std::fclose(file);
499     return error_code(errno, system_category());
500   } else if (size != result.size()) {
501     if (std::feof(file) != 0) {
502       std::fclose(file);
503       result.set_size(size);
504       return make_error_code(errc::value_too_large);
505     }
506   }
507   std::fclose(file);
508   result.set_size(len);
509   return success;
510 }
511
512 } // end namespace fs
513 } // end namespace sys
514 } // end namespace llvm