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>
49 /// This class automatically closes the given file descriptor when it goes out
50 /// of scope. You can take back explicit ownership of the file descriptor by
51 /// calling take(). The destructor does not verify that close was successful.
52 /// Therefore, never allow this class to call close on a file descriptor that
53 /// has been read from or written to.
57 AutoFD(int fd) : FileDescriptor(fd) {}
59 if (FileDescriptor >= 0)
60 ::close(FileDescriptor);
64 int ret = FileDescriptor;
69 operator int() const {return FileDescriptor;}
72 error_code TempDir(SmallVectorImpl<char> &result) {
73 // FIXME: Don't use TMPDIR if program is SUID or SGID enabled.
75 (dir = std::getenv("TMPDIR" )) ||
76 (dir = std::getenv("TMP" )) ||
77 (dir = std::getenv("TEMP" )) ||
78 (dir = std::getenv("TEMPDIR")) ||
86 result.append(d.begin(), d.end());
95 error_code current_path(SmallVectorImpl<char> &result) {
96 result.reserve(MAXPATHLEN);
99 if (::getcwd(result.data(), result.capacity()) == 0) {
100 // See if there was a real error.
101 if (errno != errc::not_enough_memory)
102 return error_code(errno, system_category());
103 // Otherwise there just wasn't enough space.
104 result.reserve(result.capacity() * 2);
109 result.set_size(strlen(result.data()));
113 error_code copy_file(const Twine &from, const Twine &to, copy_option copt) {
115 SmallString<128> from_storage;
116 SmallString<128> to_storage;
117 StringRef f = from.toNullTerminatedStringRef(from_storage);
118 StringRef t = to.toNullTerminatedStringRef(to_storage);
120 const size_t buf_sz = 32768;
122 int from_file = -1, to_file = -1;
125 if ((from_file = ::open(f.begin(), O_RDONLY)) < 0)
126 return error_code(errno, system_category());
127 AutoFD from_fd(from_file);
130 struct stat from_stat;
131 if (::stat(f.begin(), &from_stat) != 0)
132 return error_code(errno, system_category());
135 int to_flags = O_CREAT | O_WRONLY;
136 if (copt == copy_option::fail_if_exists)
140 if ((to_file = ::open(t.begin(), to_flags, from_stat.st_mode)) < 0)
141 return error_code(errno, system_category());
142 AutoFD to_fd(to_file);
145 ssize_t sz, sz_read = 1, sz_write;
146 while (sz_read > 0 &&
147 (sz_read = ::read(from_fd, buffer, buf_sz)) > 0) {
148 // Allow for partial writes - see Advanced Unix Programming (2nd Ed.),
149 // Marc Rochkind, Addison-Wesley, 2004, page 94
152 if ((sz = ::write(to_fd, buffer + sz_write, sz_read - sz_write)) < 0) {
153 sz_read = sz; // cause read loop termination.
157 } while (sz_write < sz_read);
160 // After all the file operations above the return value of close actually
162 if (::close(from_fd.take()) < 0) sz_read = -1;
163 if (::close(to_fd.take()) < 0) sz_read = -1;
167 return error_code(errno, system_category());
172 error_code create_directory(const Twine &path, bool &existed) {
173 SmallString<128> path_storage;
174 StringRef p = path.toNullTerminatedStringRef(path_storage);
176 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
177 if (errno != errc::file_exists)
178 return error_code(errno, system_category());
186 error_code create_hard_link(const Twine &to, const Twine &from) {
188 SmallString<128> from_storage;
189 SmallString<128> to_storage;
190 StringRef f = from.toNullTerminatedStringRef(from_storage);
191 StringRef t = to.toNullTerminatedStringRef(to_storage);
193 if (::link(t.begin(), f.begin()) == -1)
194 return error_code(errno, system_category());
199 error_code create_symlink(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 (::symlink(t.begin(), f.begin()) == -1)
207 return error_code(errno, system_category());
212 error_code remove(const Twine &path, bool &existed) {
213 SmallString<128> path_storage;
214 StringRef p = path.toNullTerminatedStringRef(path_storage);
216 if (::remove(p.begin()) == -1) {
217 if (errno != errc::no_such_file_or_directory)
218 return error_code(errno, system_category());
226 error_code rename(const Twine &from, const Twine &to) {
228 SmallString<128> from_storage;
229 SmallString<128> to_storage;
230 StringRef f = from.toNullTerminatedStringRef(from_storage);
231 StringRef t = to.toNullTerminatedStringRef(to_storage);
233 if (::rename(f.begin(), t.begin()) == -1)
234 return error_code(errno, system_category());
239 error_code resize_file(const Twine &path, uint64_t size) {
240 SmallString<128> path_storage;
241 StringRef p = path.toNullTerminatedStringRef(path_storage);
243 if (::truncate(p.begin(), size) == -1)
244 return error_code(errno, system_category());
249 error_code exists(const Twine &path, bool &result) {
250 SmallString<128> path_storage;
251 StringRef p = path.toNullTerminatedStringRef(path_storage);
254 if (::stat(p.begin(), &status) == -1) {
255 if (errno != errc::no_such_file_or_directory)
256 return error_code(errno, system_category());
264 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
266 SmallString<128> a_storage;
267 SmallString<128> b_storage;
268 StringRef a = A.toNullTerminatedStringRef(a_storage);
269 StringRef b = B.toNullTerminatedStringRef(b_storage);
271 struct stat stat_a, stat_b;
272 int error_b = ::stat(b.begin(), &stat_b);
273 int error_a = ::stat(a.begin(), &stat_a);
275 // If both are invalid, it's an error. If only one is, the result is false.
276 if (error_a != 0 || error_b != 0) {
277 if (error_a == error_b)
278 return error_code(errno, system_category());
282 stat_a.st_dev == stat_b.st_dev &&
283 stat_a.st_ino == stat_b.st_ino;
289 error_code file_size(const Twine &path, uint64_t &result) {
290 SmallString<128> path_storage;
291 StringRef p = path.toNullTerminatedStringRef(path_storage);
294 if (::stat(p.begin(), &status) == -1)
295 return error_code(errno, system_category());
296 if (!S_ISREG(status.st_mode))
297 return make_error_code(errc::operation_not_permitted);
299 result = status.st_size;
303 error_code status(const Twine &path, file_status &result) {
304 SmallString<128> path_storage;
305 StringRef p = path.toNullTerminatedStringRef(path_storage);
308 if (::stat(p.begin(), &status) != 0) {
309 error_code ec(errno, system_category());
310 if (ec == errc::no_such_file_or_directory)
311 result = file_status(file_type::file_not_found);
313 result = file_status(file_type::status_error);
317 if (S_ISDIR(status.st_mode))
318 result = file_status(file_type::directory_file);
319 else if (S_ISREG(status.st_mode))
320 result = file_status(file_type::regular_file);
321 else if (S_ISBLK(status.st_mode))
322 result = file_status(file_type::block_file);
323 else if (S_ISCHR(status.st_mode))
324 result = file_status(file_type::character_file);
325 else if (S_ISFIFO(status.st_mode))
326 result = file_status(file_type::fifo_file);
327 else if (S_ISSOCK(status.st_mode))
328 result = file_status(file_type::socket_file);
330 result = file_status(file_type::type_unknown);
335 error_code unique_file(const Twine &model, int &result_fd,
336 SmallVectorImpl<char> &result_path) {
337 SmallString<128> Model;
338 model.toVector(Model);
342 // Make model absolute by prepending a temp directory if it's not already.
343 bool absolute = path::is_absolute(Twine(Model));
345 SmallString<128> TDir;
346 if (error_code ec = TempDir(TDir)) return ec;
347 path::append(TDir, Twine(Model));
351 // Replace '%' with random chars. From here on, DO NOT modify model. It may be
352 // needed if the randomly chosen path already exists.
353 SmallString<128> RandomPath;
354 RandomPath.reserve(Model.size() + 1);
355 ::srand(::time(NULL));
358 // This is opened here instead of above to make it easier to track when to
359 // close it. Collisions should be rare enough for the possible extra syscalls
361 FILE *RandomSource = ::fopen("/dev/urandom", "r");
362 RandomPath.set_size(0);
363 for (SmallVectorImpl<char>::const_iterator i = Model.begin(),
364 e = Model.end(); i != e; ++i) {
368 val = fgetc(RandomSource);
371 RandomPath.push_back("0123456789abcdef"[val & 15]);
373 RandomPath.push_back(*i);
377 ::fclose(RandomSource);
379 // Try to open + create the file.
381 int RandomFD = ::open(RandomPath.c_str(), O_RDWR | O_CREAT | O_EXCL, 0600);
382 if (RandomFD == -1) {
383 // If the file existed, try again, otherwise, error.
384 if (errno == errc::file_exists)
385 goto retry_random_path;
386 // The path prefix doesn't exist.
387 if (errno == errc::no_such_file_or_directory) {
388 StringRef p(RandomPath.begin(), RandomPath.size());
389 SmallString<64> dir_to_create;
390 for (path::const_iterator i = path::begin(p),
391 e = --path::end(p); i != e; ++i) {
392 path::append(dir_to_create, *i);
394 if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
396 // Don't try to create network paths.
397 if (i->size() > 2 && (*i)[0] == '/' &&
400 return make_error_code(errc::no_such_file_or_directory);
401 if (::mkdir(dir_to_create.c_str(), 0700) == -1)
402 return error_code(errno, system_category());
405 goto rety_open_create;
407 return error_code(errno, system_category());
410 // Make the path absolute.
411 char real_path_buff[PATH_MAX + 1];
412 if (realpath(RandomPath.c_str(), real_path_buff) == NULL) {
415 ::unlink(RandomPath.c_str());
416 return error_code(error, system_category());
420 StringRef d(real_path_buff);
421 result_path.append(d.begin(), d.end());
423 result_fd = RandomFD;
427 error_code directory_iterator_construct(directory_iterator &it, StringRef path){
428 SmallString<128> path_null(path);
429 DIR *directory = ::opendir(path_null.c_str());
431 return error_code(errno, system_category());
433 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
434 // Add something for replace_filename to replace.
435 path::append(path_null, ".");
436 it.CurrentEntry = directory_entry(path_null.str());
437 return directory_iterator_increment(it);
440 error_code directory_iterator_destruct(directory_iterator& it) {
441 if (it.IterationHandle)
442 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
443 it.IterationHandle = 0;
444 it.CurrentEntry = directory_entry();
448 error_code directory_iterator_increment(directory_iterator& it) {
450 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
451 if (cur_dir == 0 && errno != 0) {
452 return error_code(errno, system_category());
453 } else if (cur_dir != 0) {
454 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
455 if ((name.size() == 1 && name[0] == '.') ||
456 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
457 return directory_iterator_increment(it);
458 it.CurrentEntry.replace_filename(name);
460 return directory_iterator_destruct(it);
465 } // end namespace fs
466 } // end namespace sys
467 } // end namespace llvm