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