1 //===- llvm/Support/Unix/PathV2.cpp - Unix Path Implementation --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Unix specific implementation of the PathV2 API.
12 //===----------------------------------------------------------------------===//
14 //===----------------------------------------------------------------------===//
15 //=== WARNING: Implementation here must contain only generic UNIX code that
16 //=== is guaranteed to work on *all* UNIX variants.
17 //===----------------------------------------------------------------------===//
28 # define NAMLEN(dirent) strlen((dirent)->d_name)
30 # define dirent direct
31 # define NAMLEN(dirent) (dirent)->d_namlen
33 # include <sys/ndir.h>
50 #if defined(__GNU__) && !defined(PATH_MAX)
51 # define PATH_MAX 4096
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.
65 AutoFD(int fd) : FileDescriptor(fd) {}
67 if (FileDescriptor >= 0)
68 ::close(FileDescriptor);
72 int ret = FileDescriptor;
77 operator int() const {return FileDescriptor;}
80 error_code TempDir(SmallVectorImpl<char> &result) {
81 // FIXME: Don't use TMPDIR if program is SUID or SGID enabled.
83 (dir = std::getenv("TMPDIR" )) ||
84 (dir = std::getenv("TMP" )) ||
85 (dir = std::getenv("TEMP" )) ||
86 (dir = std::getenv("TEMPDIR")) ||
94 result.append(d.begin(), d.end());
95 return error_code::success();
103 error_code current_path(SmallVectorImpl<char> &result) {
105 result.reserve(MAXPATHLEN);
108 result.reserve(1024);
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);
122 result.set_size(strlen(result.data()));
123 return error_code::success();
126 error_code copy_file(const Twine &from, const Twine &to, copy_option copt) {
128 SmallString<128> from_storage;
129 SmallString<128> to_storage;
130 StringRef f = from.toNullTerminatedStringRef(from_storage);
131 StringRef t = to.toNullTerminatedStringRef(to_storage);
133 const size_t buf_sz = 32768;
135 int from_file = -1, to_file = -1;
138 if ((from_file = ::open(f.begin(), O_RDONLY)) < 0)
139 return error_code(errno, system_category());
140 AutoFD from_fd(from_file);
143 struct stat from_stat;
144 if (::stat(f.begin(), &from_stat) != 0)
145 return error_code(errno, system_category());
148 int to_flags = O_CREAT | O_WRONLY;
149 if (copt == copy_option::fail_if_exists)
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);
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
165 if ((sz = ::write(to_fd, buffer + sz_write, sz_read - sz_write)) < 0) {
166 sz_read = sz; // cause read loop termination.
170 } while (sz_write < sz_read);
173 // After all the file operations above the return value of close actually
175 if (::close(from_fd.take()) < 0) sz_read = -1;
176 if (::close(to_fd.take()) < 0) sz_read = -1;
180 return error_code(errno, system_category());
182 return error_code::success();
185 error_code create_directory(const Twine &path, bool &existed) {
186 SmallString<128> path_storage;
187 StringRef p = path.toNullTerminatedStringRef(path_storage);
189 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
190 if (errno != errc::file_exists)
191 return error_code(errno, system_category());
196 return error_code::success();
199 error_code create_hard_link(const Twine &to, const Twine &from) {
201 SmallString<128> from_storage;
202 SmallString<128> to_storage;
203 StringRef f = from.toNullTerminatedStringRef(from_storage);
204 StringRef t = to.toNullTerminatedStringRef(to_storage);
206 if (::link(t.begin(), f.begin()) == -1)
207 return error_code(errno, system_category());
209 return error_code::success();
212 error_code create_symlink(const Twine &to, const Twine &from) {
214 SmallString<128> from_storage;
215 SmallString<128> to_storage;
216 StringRef f = from.toNullTerminatedStringRef(from_storage);
217 StringRef t = to.toNullTerminatedStringRef(to_storage);
219 if (::symlink(t.begin(), f.begin()) == -1)
220 return error_code(errno, system_category());
222 return error_code::success();
225 error_code remove(const Twine &path, bool &existed) {
226 SmallString<128> path_storage;
227 StringRef p = path.toNullTerminatedStringRef(path_storage);
229 if (::remove(p.begin()) == -1) {
230 if (errno != errc::no_such_file_or_directory)
231 return error_code(errno, system_category());
236 return error_code::success();
239 error_code rename(const Twine &from, const Twine &to) {
241 SmallString<128> from_storage;
242 SmallString<128> to_storage;
243 StringRef f = from.toNullTerminatedStringRef(from_storage);
244 StringRef t = to.toNullTerminatedStringRef(to_storage);
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))
252 if (error_code ec = remove(from, Existed))
255 return error_code(errno, system_category());
258 return error_code::success();
261 error_code resize_file(const Twine &path, uint64_t size) {
262 SmallString<128> path_storage;
263 StringRef p = path.toNullTerminatedStringRef(path_storage);
265 if (::truncate(p.begin(), size) == -1)
266 return error_code(errno, system_category());
268 return error_code::success();
271 error_code exists(const Twine &path, bool &result) {
272 SmallString<128> path_storage;
273 StringRef p = path.toNullTerminatedStringRef(path_storage);
276 if (::stat(p.begin(), &status) == -1) {
277 if (errno != errc::no_such_file_or_directory)
278 return error_code(errno, system_category());
283 return error_code::success();
286 bool equivalent(file_status A, file_status B) {
287 assert(status_known(A) && status_known(B));
288 return A.fs_st_dev == B.fs_st_dev &&
289 A.fs_st_ino == B.fs_st_ino;
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();
300 error_code file_size(const Twine &path, uint64_t &result) {
301 SmallString<128> path_storage;
302 StringRef p = path.toNullTerminatedStringRef(path_storage);
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);
310 result = status.st_size;
311 return error_code::success();
314 error_code status(const Twine &path, file_status &result) {
315 SmallString<128> path_storage;
316 StringRef p = path.toNullTerminatedStringRef(path_storage);
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);
324 result = file_status(file_type::status_error);
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);
341 result = file_status(file_type::type_unknown);
343 result.fs_st_dev = status.st_dev;
344 result.fs_st_ino = status.st_ino;
346 return error_code::success();
349 error_code unique_file(const Twine &model, int &result_fd,
350 SmallVectorImpl<char> &result_path,
352 SmallString<128> Model;
353 model.toVector(Model);
358 // Make model absolute by prepending a temp directory if it's not already.
359 bool absolute = path::is_absolute(Twine(Model));
361 SmallString<128> TDir;
362 if (error_code ec = TempDir(TDir)) return ec;
363 path::append(TDir, Twine(Model));
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));
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
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) {
385 val = fgetc(RandomSource);
388 RandomPath.push_back("0123456789abcdef"[val & 15]);
390 RandomPath.push_back(*i);
394 ::fclose(RandomSource);
396 // Try to open + create the file.
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);
411 if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
413 // Don't try to create network paths.
414 if (i->size() > 2 && (*i)[0] == '/' &&
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());
422 goto rety_open_create;
424 return error_code(errno, system_category());
427 // Make the path absolute.
428 char real_path_buff[PATH_MAX + 1];
429 if (realpath(RandomPath.c_str(), real_path_buff) == NULL) {
432 ::unlink(RandomPath.c_str());
433 return error_code(error, system_category());
437 StringRef d(real_path_buff);
438 result_path.append(d.begin(), d.end());
440 result_fd = RandomFD;
441 return error_code::success();
444 error_code detail::directory_iterator_construct(detail::DirIterState &it,
446 SmallString<128> path_null(path);
447 DIR *directory = ::opendir(path_null.c_str());
449 return error_code(errno, system_category());
451 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
452 // Add something for replace_filename to replace.
453 path::append(path_null, ".");
454 it.CurrentEntry = directory_entry(path_null.str());
455 return directory_iterator_increment(it);
458 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
459 if (it.IterationHandle)
460 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
461 it.IterationHandle = 0;
462 it.CurrentEntry = directory_entry();
463 return error_code::success();
466 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
468 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
469 if (cur_dir == 0 && errno != 0) {
470 return error_code(errno, system_category());
471 } else if (cur_dir != 0) {
472 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
473 if ((name.size() == 1 && name[0] == '.') ||
474 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
475 return directory_iterator_increment(it);
476 it.CurrentEntry.replace_filename(name);
478 return directory_iterator_destruct(it);
480 return error_code::success();
483 error_code get_magic(const Twine &path, uint32_t len,
484 SmallVectorImpl<char> &result) {
485 SmallString<128> PathStorage;
486 StringRef Path = path.toNullTerminatedStringRef(PathStorage);
490 std::FILE *file = std::fopen(Path.data(), "rb");
492 return error_code(errno, system_category());
498 size_t size = std::fread(result.data(), 1, len, file);
499 if (std::ferror(file) != 0) {
501 return error_code(errno, system_category());
502 } else if (size != result.size()) {
503 if (std::feof(file) != 0) {
505 result.set_size(size);
506 return make_error_code(errc::value_too_large);
510 result.set_size(len);
511 return error_code::success();
514 } // end namespace fs
515 } // end namespace sys
516 } // end namespace llvm