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