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>
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.
60 AutoFD(int fd) : FileDescriptor(fd) {}
62 if (FileDescriptor >= 0)
63 ::close(FileDescriptor);
67 int ret = FileDescriptor;
72 operator int() const {return FileDescriptor;}
75 error_code TempDir(SmallVectorImpl<char> &result) {
76 // FIXME: Don't use TMPDIR if program is SUID or SGID enabled.
78 (dir = std::getenv("TMPDIR" )) ||
79 (dir = std::getenv("TMP" )) ||
80 (dir = std::getenv("TEMP" )) ||
81 (dir = std::getenv("TEMPDIR")) ||
89 result.append(d.begin(), d.end());
98 error_code current_path(SmallVectorImpl<char> &result) {
99 result.reserve(MAXPATHLEN);
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);
112 result.set_size(strlen(result.data()));
116 error_code copy_file(const Twine &from, const Twine &to, copy_option copt) {
118 SmallString<128> from_storage;
119 SmallString<128> to_storage;
120 StringRef f = from.toNullTerminatedStringRef(from_storage);
121 StringRef t = to.toNullTerminatedStringRef(to_storage);
123 const size_t buf_sz = 32768;
125 int from_file = -1, to_file = -1;
128 if ((from_file = ::open(f.begin(), O_RDONLY)) < 0)
129 return error_code(errno, system_category());
130 AutoFD from_fd(from_file);
133 struct stat from_stat;
134 if (::stat(f.begin(), &from_stat) != 0)
135 return error_code(errno, system_category());
138 int to_flags = O_CREAT | O_WRONLY;
139 if (copt == copy_option::fail_if_exists)
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);
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
155 if ((sz = ::write(to_fd, buffer + sz_write, sz_read - sz_write)) < 0) {
156 sz_read = sz; // cause read loop termination.
160 } while (sz_write < sz_read);
163 // After all the file operations above the return value of close actually
165 if (::close(from_fd.take()) < 0) sz_read = -1;
166 if (::close(to_fd.take()) < 0) sz_read = -1;
170 return error_code(errno, system_category());
175 error_code create_directory(const Twine &path, bool &existed) {
176 SmallString<128> path_storage;
177 StringRef p = path.toNullTerminatedStringRef(path_storage);
179 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
180 if (errno != errc::file_exists)
181 return error_code(errno, system_category());
189 error_code create_hard_link(const Twine &to, const Twine &from) {
191 SmallString<128> from_storage;
192 SmallString<128> to_storage;
193 StringRef f = from.toNullTerminatedStringRef(from_storage);
194 StringRef t = to.toNullTerminatedStringRef(to_storage);
196 if (::link(t.begin(), f.begin()) == -1)
197 return error_code(errno, system_category());
202 error_code create_symlink(const Twine &to, const Twine &from) {
204 SmallString<128> from_storage;
205 SmallString<128> to_storage;
206 StringRef f = from.toNullTerminatedStringRef(from_storage);
207 StringRef t = to.toNullTerminatedStringRef(to_storage);
209 if (::symlink(t.begin(), f.begin()) == -1)
210 return error_code(errno, system_category());
215 error_code remove(const Twine &path, bool &existed) {
216 SmallString<128> path_storage;
217 StringRef p = path.toNullTerminatedStringRef(path_storage);
219 if (::remove(p.begin()) == -1) {
220 if (errno != errc::no_such_file_or_directory)
221 return error_code(errno, system_category());
229 error_code rename(const Twine &from, const Twine &to) {
231 SmallString<128> from_storage;
232 SmallString<128> to_storage;
233 StringRef f = from.toNullTerminatedStringRef(from_storage);
234 StringRef t = to.toNullTerminatedStringRef(to_storage);
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))
242 if (error_code ec = remove(from, Existed))
245 return error_code(errno, system_category());
251 error_code resize_file(const Twine &path, uint64_t size) {
252 SmallString<128> path_storage;
253 StringRef p = path.toNullTerminatedStringRef(path_storage);
255 if (::truncate(p.begin(), size) == -1)
256 return error_code(errno, system_category());
261 error_code exists(const Twine &path, bool &result) {
262 SmallString<128> path_storage;
263 StringRef p = path.toNullTerminatedStringRef(path_storage);
266 if (::stat(p.begin(), &status) == -1) {
267 if (errno != errc::no_such_file_or_directory)
268 return error_code(errno, system_category());
276 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
278 SmallString<128> a_storage;
279 SmallString<128> b_storage;
280 StringRef a = A.toNullTerminatedStringRef(a_storage);
281 StringRef b = B.toNullTerminatedStringRef(b_storage);
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);
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());
294 stat_a.st_dev == stat_b.st_dev &&
295 stat_a.st_ino == stat_b.st_ino;
301 error_code file_size(const Twine &path, uint64_t &result) {
302 SmallString<128> path_storage;
303 StringRef p = path.toNullTerminatedStringRef(path_storage);
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);
311 result = status.st_size;
315 error_code status(const Twine &path, file_status &result) {
316 SmallString<128> path_storage;
317 StringRef p = path.toNullTerminatedStringRef(path_storage);
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);
325 result = file_status(file_type::status_error);
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);
342 result = file_status(file_type::type_unknown);
347 error_code unique_file(const Twine &model, int &result_fd,
348 SmallVectorImpl<char> &result_path,
350 SmallString<128> Model;
351 model.toVector(Model);
356 // Make model absolute by prepending a temp directory if it's not already.
357 bool absolute = path::is_absolute(Twine(Model));
359 SmallString<128> TDir;
360 if (error_code ec = TempDir(TDir)) return ec;
361 path::append(TDir, Twine(Model));
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));
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
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) {
383 val = fgetc(RandomSource);
386 RandomPath.push_back("0123456789abcdef"[val & 15]);
388 RandomPath.push_back(*i);
392 ::fclose(RandomSource);
394 // Try to open + create the file.
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);
409 if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
411 // Don't try to create network paths.
412 if (i->size() > 2 && (*i)[0] == '/' &&
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());
420 goto rety_open_create;
422 return error_code(errno, system_category());
425 // Make the path absolute.
426 char real_path_buff[PATH_MAX + 1];
427 if (realpath(RandomPath.c_str(), real_path_buff) == NULL) {
430 ::unlink(RandomPath.c_str());
431 return error_code(error, system_category());
435 StringRef d(real_path_buff);
436 result_path.append(d.begin(), d.end());
438 result_fd = RandomFD;
442 error_code directory_iterator_construct(directory_iterator &it, StringRef path){
443 SmallString<128> path_null(path);
444 DIR *directory = ::opendir(path_null.c_str());
446 return error_code(errno, system_category());
448 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
449 // Add something for replace_filename to replace.
450 path::append(path_null, ".");
451 it.CurrentEntry = directory_entry(path_null.str());
452 return directory_iterator_increment(it);
455 error_code directory_iterator_destruct(directory_iterator& it) {
456 if (it.IterationHandle)
457 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
458 it.IterationHandle = 0;
459 it.CurrentEntry = directory_entry();
463 error_code directory_iterator_increment(directory_iterator& it) {
465 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
466 if (cur_dir == 0 && errno != 0) {
467 return error_code(errno, system_category());
468 } else if (cur_dir != 0) {
469 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
470 if ((name.size() == 1 && name[0] == '.') ||
471 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
472 return directory_iterator_increment(it);
473 it.CurrentEntry.replace_filename(name);
475 return directory_iterator_destruct(it);
480 error_code get_magic(const Twine &path, uint32_t len,
481 SmallVectorImpl<char> &result) {
482 SmallString<128> PathStorage;
483 StringRef Path = path.toNullTerminatedStringRef(PathStorage);
487 std::FILE *file = std::fopen(Path.data(), "rb");
489 return error_code(errno, system_category());
495 size_t size = std::fread(result.data(), 1, len, file);
496 if (std::ferror(file) != 0) {
498 return error_code(errno, system_category());
499 } else if (size != result.size()) {
500 if (std::feof(file) != 0) {
502 result.set_size(size);
503 return make_error_code(errc::value_too_large);
507 result.set_size(len);
511 } // end namespace fs
512 } // end namespace sys
513 } // end namespace llvm