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 bool equivalent(file_status A, file_status B) {
277 assert(status_known(A) && status_known(B));
278 return A.st_dev == B.st_dev &&
279 A.st_ino == B.st_ino;
282 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
283 file_status fsA, fsB;
284 if (error_code ec = status(A, fsA)) return ec;
285 if (error_code ec = status(B, fsB)) return ec;
286 result = equivalent(fsA, fsB);
290 error_code file_size(const Twine &path, uint64_t &result) {
291 SmallString<128> path_storage;
292 StringRef p = path.toNullTerminatedStringRef(path_storage);
295 if (::stat(p.begin(), &status) == -1)
296 return error_code(errno, system_category());
297 if (!S_ISREG(status.st_mode))
298 return make_error_code(errc::operation_not_permitted);
300 result = status.st_size;
304 error_code status(const Twine &path, file_status &result) {
305 SmallString<128> path_storage;
306 StringRef p = path.toNullTerminatedStringRef(path_storage);
309 if (::stat(p.begin(), &status) != 0) {
310 error_code ec(errno, system_category());
311 if (ec == errc::no_such_file_or_directory)
312 result = file_status(file_type::file_not_found);
314 result = file_status(file_type::status_error);
318 if (S_ISDIR(status.st_mode))
319 result = file_status(file_type::directory_file);
320 else if (S_ISREG(status.st_mode))
321 result = file_status(file_type::regular_file);
322 else if (S_ISBLK(status.st_mode))
323 result = file_status(file_type::block_file);
324 else if (S_ISCHR(status.st_mode))
325 result = file_status(file_type::character_file);
326 else if (S_ISFIFO(status.st_mode))
327 result = file_status(file_type::fifo_file);
328 else if (S_ISSOCK(status.st_mode))
329 result = file_status(file_type::socket_file);
331 result = file_status(file_type::type_unknown);
333 result.st_dev = status.st_dev;
334 result.st_ino = status.st_ino;
339 error_code unique_file(const Twine &model, int &result_fd,
340 SmallVectorImpl<char> &result_path,
342 SmallString<128> Model;
343 model.toVector(Model);
348 // Make model absolute by prepending a temp directory if it's not already.
349 bool absolute = path::is_absolute(Twine(Model));
351 SmallString<128> TDir;
352 if (error_code ec = TempDir(TDir)) return ec;
353 path::append(TDir, Twine(Model));
358 // Replace '%' with random chars. From here on, DO NOT modify model. It may be
359 // needed if the randomly chosen path already exists.
360 SmallString<128> RandomPath;
361 RandomPath.reserve(Model.size() + 1);
362 ::srand(::time(NULL));
365 // This is opened here instead of above to make it easier to track when to
366 // close it. Collisions should be rare enough for the possible extra syscalls
368 FILE *RandomSource = ::fopen("/dev/urandom", "r");
369 RandomPath.set_size(0);
370 for (SmallVectorImpl<char>::const_iterator i = Model.begin(),
371 e = Model.end(); i != e; ++i) {
375 val = fgetc(RandomSource);
378 RandomPath.push_back("0123456789abcdef"[val & 15]);
380 RandomPath.push_back(*i);
384 ::fclose(RandomSource);
386 // Try to open + create the file.
388 int RandomFD = ::open(RandomPath.c_str(), O_RDWR | O_CREAT | O_EXCL, 0600);
389 if (RandomFD == -1) {
390 // If the file existed, try again, otherwise, error.
391 if (errno == errc::file_exists)
392 goto retry_random_path;
393 // The path prefix doesn't exist.
394 if (errno == errc::no_such_file_or_directory) {
395 StringRef p(RandomPath.begin(), RandomPath.size());
396 SmallString<64> dir_to_create;
397 for (path::const_iterator i = path::begin(p),
398 e = --path::end(p); i != e; ++i) {
399 path::append(dir_to_create, *i);
401 if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
403 // Don't try to create network paths.
404 if (i->size() > 2 && (*i)[0] == '/' &&
407 return make_error_code(errc::no_such_file_or_directory);
408 if (::mkdir(dir_to_create.c_str(), 0700) == -1)
409 return error_code(errno, system_category());
412 goto rety_open_create;
414 return error_code(errno, system_category());
417 // Make the path absolute.
418 char real_path_buff[PATH_MAX + 1];
419 if (realpath(RandomPath.c_str(), real_path_buff) == NULL) {
422 ::unlink(RandomPath.c_str());
423 return error_code(error, system_category());
427 StringRef d(real_path_buff);
428 result_path.append(d.begin(), d.end());
430 result_fd = RandomFD;
434 error_code detail::directory_iterator_construct(detail::DirIterState &it,
436 SmallString<128> path_null(path);
437 DIR *directory = ::opendir(path_null.c_str());
439 return error_code(errno, system_category());
441 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
442 // Add something for replace_filename to replace.
443 path::append(path_null, ".");
444 it.CurrentEntry = directory_entry(path_null.str());
445 return directory_iterator_increment(it);
448 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
449 if (it.IterationHandle)
450 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
451 it.IterationHandle = 0;
452 it.CurrentEntry = directory_entry();
456 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
458 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
459 if (cur_dir == 0 && errno != 0) {
460 return error_code(errno, system_category());
461 } else if (cur_dir != 0) {
462 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
463 if ((name.size() == 1 && name[0] == '.') ||
464 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
465 return directory_iterator_increment(it);
466 it.CurrentEntry.replace_filename(name);
468 return directory_iterator_destruct(it);
473 error_code get_magic(const Twine &path, uint32_t len,
474 SmallVectorImpl<char> &result) {
475 SmallString<128> PathStorage;
476 StringRef Path = path.toNullTerminatedStringRef(PathStorage);
480 std::FILE *file = std::fopen(Path.data(), "rb");
482 return error_code(errno, system_category());
488 size_t size = std::fread(result.data(), 1, len, file);
489 if (std::ferror(file) != 0) {
491 return error_code(errno, system_category());
492 } else if (size != result.size()) {
493 if (std::feof(file) != 0) {
495 result.set_size(size);
496 return make_error_code(errc::value_too_large);
500 result.set_size(len);
504 } // end namespace fs
505 } // end namespace sys
506 } // end namespace llvm