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 //===----------------------------------------------------------------------===//
20 #include "llvm/Support/Process.h"
29 # define NAMLEN(dirent) strlen((dirent)->d_name)
31 # define dirent direct
32 # define NAMLEN(dirent) (dirent)->d_namlen
34 # include <sys/ndir.h>
51 #if defined(__GNU__) && !defined(PATH_MAX)
52 # define PATH_MAX 4096
58 /// This class automatically closes the given file descriptor when it goes out
59 /// of scope. You can take back explicit ownership of the file descriptor by
60 /// calling take(). The destructor does not verify that close was successful.
61 /// Therefore, never allow this class to call close on a file descriptor that
62 /// has been read from or written to.
66 AutoFD(int fd) : FileDescriptor(fd) {}
68 if (FileDescriptor >= 0)
69 ::close(FileDescriptor);
73 int ret = FileDescriptor;
78 operator int() const {return FileDescriptor;}
81 error_code TempDir(SmallVectorImpl<char> &result) {
82 // FIXME: Don't use TMPDIR if program is SUID or SGID enabled.
84 (dir = std::getenv("TMPDIR" )) ||
85 (dir = std::getenv("TMP" )) ||
86 (dir = std::getenv("TEMP" )) ||
87 (dir = std::getenv("TEMPDIR")) ||
95 result.append(d.begin(), d.end());
96 return error_code::success();
104 error_code current_path(SmallVectorImpl<char> &result) {
106 result.reserve(MAXPATHLEN);
109 result.reserve(1024);
113 if (::getcwd(result.data(), result.capacity()) == 0) {
114 // See if there was a real error.
115 if (errno != errc::not_enough_memory)
116 return error_code(errno, system_category());
117 // Otherwise there just wasn't enough space.
118 result.reserve(result.capacity() * 2);
123 result.set_size(strlen(result.data()));
124 return error_code::success();
127 error_code copy_file(const Twine &from, const Twine &to, copy_option copt) {
129 SmallString<128> from_storage;
130 SmallString<128> to_storage;
131 StringRef f = from.toNullTerminatedStringRef(from_storage);
132 StringRef t = to.toNullTerminatedStringRef(to_storage);
134 const size_t buf_sz = 32768;
136 int from_file = -1, to_file = -1;
139 if ((from_file = ::open(f.begin(), O_RDONLY)) < 0)
140 return error_code(errno, system_category());
141 AutoFD from_fd(from_file);
144 struct stat from_stat;
145 if (::stat(f.begin(), &from_stat) != 0)
146 return error_code(errno, system_category());
149 int to_flags = O_CREAT | O_WRONLY;
150 if (copt == copy_option::fail_if_exists)
154 if ((to_file = ::open(t.begin(), to_flags, from_stat.st_mode)) < 0)
155 return error_code(errno, system_category());
156 AutoFD to_fd(to_file);
159 ssize_t sz, sz_read = 1, sz_write;
160 while (sz_read > 0 &&
161 (sz_read = ::read(from_fd, buffer, buf_sz)) > 0) {
162 // Allow for partial writes - see Advanced Unix Programming (2nd Ed.),
163 // Marc Rochkind, Addison-Wesley, 2004, page 94
166 if ((sz = ::write(to_fd, buffer + sz_write, sz_read - sz_write)) < 0) {
167 sz_read = sz; // cause read loop termination.
171 } while (sz_write < sz_read);
174 // After all the file operations above the return value of close actually
176 if (::close(from_fd.take()) < 0) sz_read = -1;
177 if (::close(to_fd.take()) < 0) sz_read = -1;
181 return error_code(errno, system_category());
183 return error_code::success();
186 error_code create_directory(const Twine &path, bool &existed) {
187 SmallString<128> path_storage;
188 StringRef p = path.toNullTerminatedStringRef(path_storage);
190 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
191 if (errno != errc::file_exists)
192 return error_code(errno, system_category());
197 return error_code::success();
200 error_code create_hard_link(const Twine &to, const Twine &from) {
202 SmallString<128> from_storage;
203 SmallString<128> to_storage;
204 StringRef f = from.toNullTerminatedStringRef(from_storage);
205 StringRef t = to.toNullTerminatedStringRef(to_storage);
207 if (::link(t.begin(), f.begin()) == -1)
208 return error_code(errno, system_category());
210 return error_code::success();
213 error_code create_symlink(const Twine &to, const Twine &from) {
215 SmallString<128> from_storage;
216 SmallString<128> to_storage;
217 StringRef f = from.toNullTerminatedStringRef(from_storage);
218 StringRef t = to.toNullTerminatedStringRef(to_storage);
220 if (::symlink(t.begin(), f.begin()) == -1)
221 return error_code(errno, system_category());
223 return error_code::success();
226 error_code remove(const Twine &path, bool &existed) {
227 SmallString<128> path_storage;
228 StringRef p = path.toNullTerminatedStringRef(path_storage);
230 if (::remove(p.begin()) == -1) {
231 if (errno != errc::no_such_file_or_directory)
232 return error_code(errno, system_category());
237 return error_code::success();
240 error_code rename(const Twine &from, const Twine &to) {
242 SmallString<128> from_storage;
243 SmallString<128> to_storage;
244 StringRef f = from.toNullTerminatedStringRef(from_storage);
245 StringRef t = to.toNullTerminatedStringRef(to_storage);
247 if (::rename(f.begin(), t.begin()) == -1) {
248 // If it's a cross device link, copy then delete, otherwise return the error
249 if (errno == EXDEV) {
250 if (error_code ec = copy_file(from, to, copy_option::overwrite_if_exists))
253 if (error_code ec = remove(from, Existed))
256 return error_code(errno, system_category());
259 return error_code::success();
262 error_code resize_file(const Twine &path, uint64_t size) {
263 SmallString<128> path_storage;
264 StringRef p = path.toNullTerminatedStringRef(path_storage);
266 if (::truncate(p.begin(), size) == -1)
267 return error_code(errno, system_category());
269 return error_code::success();
272 error_code exists(const Twine &path, bool &result) {
273 SmallString<128> path_storage;
274 StringRef p = path.toNullTerminatedStringRef(path_storage);
277 if (::stat(p.begin(), &status) == -1) {
278 if (errno != errc::no_such_file_or_directory)
279 return error_code(errno, system_category());
284 return error_code::success();
287 bool equivalent(file_status A, file_status B) {
288 assert(status_known(A) && status_known(B));
289 return A.fs_st_dev == B.fs_st_dev &&
290 A.fs_st_ino == B.fs_st_ino;
293 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
294 file_status fsA, fsB;
295 if (error_code ec = status(A, fsA)) return ec;
296 if (error_code ec = status(B, fsB)) return ec;
297 result = equivalent(fsA, fsB);
298 return error_code::success();
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;
312 return error_code::success();
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);
344 result.fs_st_dev = status.st_dev;
345 result.fs_st_ino = status.st_ino;
347 return error_code::success();
350 error_code unique_file(const Twine &model, int &result_fd,
351 SmallVectorImpl<char> &result_path,
353 SmallString<128> Model;
354 model.toVector(Model);
359 // Make model absolute by prepending a temp directory if it's not already.
360 bool absolute = path::is_absolute(Twine(Model));
362 SmallString<128> TDir;
363 if (error_code ec = TempDir(TDir)) return ec;
364 path::append(TDir, Twine(Model));
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 = Model;
374 // This is opened here instead of above to make it easier to track when to
375 // close it. Collisions should be rare enough for the possible extra syscalls
377 for (unsigned i = 0, e = Model.size(); i != e; ++i) {
379 RandomPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
382 // Try to open + create the file.
384 int RandomFD = ::open(RandomPath.c_str(), O_RDWR | O_CREAT | O_EXCL, 0600);
385 if (RandomFD == -1) {
386 // If the file existed, try again, otherwise, error.
387 if (errno == errc::file_exists)
388 goto retry_random_path;
389 // The path prefix doesn't exist.
390 if (errno == errc::no_such_file_or_directory) {
391 StringRef p(RandomPath.begin(), RandomPath.size());
392 SmallString<64> dir_to_create;
393 for (path::const_iterator i = path::begin(p),
394 e = --path::end(p); i != e; ++i) {
395 path::append(dir_to_create, *i);
397 if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
399 // Don't try to create network paths.
400 if (i->size() > 2 && (*i)[0] == '/' &&
403 return make_error_code(errc::no_such_file_or_directory);
404 if (::mkdir(dir_to_create.c_str(), 0700) == -1)
405 return error_code(errno, system_category());
408 goto rety_open_create;
410 return error_code(errno, system_category());
413 // Make the path absolute.
414 char real_path_buff[PATH_MAX + 1];
415 if (realpath(RandomPath.c_str(), real_path_buff) == NULL) {
418 ::unlink(RandomPath.c_str());
419 return error_code(error, system_category());
423 StringRef d(real_path_buff);
424 result_path.append(d.begin(), d.end());
426 result_fd = RandomFD;
427 return error_code::success();
430 error_code detail::directory_iterator_construct(detail::DirIterState &it,
432 SmallString<128> path_null(path);
433 DIR *directory = ::opendir(path_null.c_str());
435 return error_code(errno, system_category());
437 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
438 // Add something for replace_filename to replace.
439 path::append(path_null, ".");
440 it.CurrentEntry = directory_entry(path_null.str());
441 return directory_iterator_increment(it);
444 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
445 if (it.IterationHandle)
446 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
447 it.IterationHandle = 0;
448 it.CurrentEntry = directory_entry();
449 return error_code::success();
452 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
454 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
455 if (cur_dir == 0 && errno != 0) {
456 return error_code(errno, system_category());
457 } else if (cur_dir != 0) {
458 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
459 if ((name.size() == 1 && name[0] == '.') ||
460 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
461 return directory_iterator_increment(it);
462 it.CurrentEntry.replace_filename(name);
464 return directory_iterator_destruct(it);
466 return error_code::success();
469 error_code get_magic(const Twine &path, uint32_t len,
470 SmallVectorImpl<char> &result) {
471 SmallString<128> PathStorage;
472 StringRef Path = path.toNullTerminatedStringRef(PathStorage);
476 std::FILE *file = std::fopen(Path.data(), "rb");
478 return error_code(errno, system_category());
484 size_t size = std::fread(result.data(), 1, len, file);
485 if (std::ferror(file) != 0) {
487 return error_code(errno, system_category());
488 } else if (size != result.size()) {
489 if (std::feof(file) != 0) {
491 result.set_size(size);
492 return make_error_code(errc::value_too_large);
496 result.set_size(len);
497 return error_code::success();
500 } // end namespace fs
501 } // end namespace sys
502 } // end namespace llvm