blob: c9267c06b39d147211f856de0ae42114a0d4ccd5 [file] [log] [blame]
Michael J. Spencerdffde992010-11-29 22:28:51 +00001//===- llvm/Support/Unix/PathV2.cpp - Unix Path Implementation --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Unix specific implementation of the PathV2 API.
11//
12//===----------------------------------------------------------------------===//
13
14//===----------------------------------------------------------------------===//
15//=== WARNING: Implementation here must contain only generic UNIX code that
16//=== is guaranteed to work on *all* UNIX variants.
17//===----------------------------------------------------------------------===//
18
19#include "Unix.h"
Michael J. Spencerbee0c382010-12-01 19:32:01 +000020#if HAVE_SYS_STAT_H
21#include <sys/stat.h>
22#endif
23#if HAVE_FCNTL_H
24#include <fcntl.h>
25#endif
Michael J. Spencerda7c1ca2011-01-05 16:38:57 +000026#if HAVE_DIRENT_H
27# include <dirent.h>
28# define NAMLEN(dirent) strlen((dirent)->d_name)
29#else
30# define dirent direct
31# define NAMLEN(dirent) (dirent)->d_namlen
32# if HAVE_SYS_NDIR_H
33# include <sys/ndir.h>
34# endif
35# if HAVE_SYS_DIR_H
36# include <sys/dir.h>
37# endif
38# if HAVE_NDIR_H
39# include <ndir.h>
40# endif
41#endif
Michael J. Spencer3cb84ef2010-12-03 01:21:28 +000042#if HAVE_STDIO_H
43#include <stdio.h>
Michael J. Spencerbee0c382010-12-01 19:32:01 +000044#endif
45
Michael J. Spencer3cb84ef2010-12-03 01:21:28 +000046using namespace llvm;
47
Michael J. Spencerbee0c382010-12-01 19:32:01 +000048namespace {
Michael J. Spencerad8a14f2010-12-07 01:23:08 +000049 /// 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.
Michael J. Spencerbee0c382010-12-01 19:32:01 +000054 struct AutoFD {
55 int FileDescriptor;
56
57 AutoFD(int fd) : FileDescriptor(fd) {}
58 ~AutoFD() {
59 if (FileDescriptor >= 0)
60 ::close(FileDescriptor);
61 }
62
63 int take() {
64 int ret = FileDescriptor;
65 FileDescriptor = -1;
66 return ret;
67 }
68
69 operator int() const {return FileDescriptor;}
70 };
Michael J. Spencer3cb84ef2010-12-03 01:21:28 +000071
72 error_code TempDir(SmallVectorImpl<char> &result) {
73 // FIXME: Don't use TMPDIR if program is SUID or SGID enabled.
74 const char *dir = 0;
75 (dir = std::getenv("TMPDIR" )) ||
76 (dir = std::getenv("TMP" )) ||
77 (dir = std::getenv("TEMP" )) ||
78 (dir = std::getenv("TEMPDIR")) ||
79#ifdef P_tmpdir
80 (dir = P_tmpdir) ||
81#endif
82 (dir = "/tmp");
83
Michael J. Spencerfbd1bbd2010-12-07 01:23:19 +000084 result.clear();
Michael J. Spencer3cb84ef2010-12-03 01:21:28 +000085 StringRef d(dir);
86 result.append(d.begin(), d.end());
Michael J. Spencer9d425e72010-12-04 18:45:32 +000087 return success;
Michael J. Spencer3cb84ef2010-12-03 01:21:28 +000088 }
Michael J. Spencerbee0c382010-12-01 19:32:01 +000089}
Michael J. Spencerdffde992010-11-29 22:28:51 +000090
91namespace llvm {
92namespace sys {
Michael J. Spencer1522fce2010-12-07 01:22:31 +000093namespace fs {
Michael J. Spencerdffde992010-11-29 22:28:51 +000094
95error_code current_path(SmallVectorImpl<char> &result) {
Michael J. Spencere1db1b82011-03-24 05:23:40 +000096 // Reserve an arbitrary amount of space.
97 result.reserve(128);
Michael J. Spencerdffde992010-11-29 22:28:51 +000098
Michael J. Spencer1522fce2010-12-07 01:22:31 +000099 while (true) {
100 if (::getcwd(result.data(), result.capacity()) == 0) {
101 // See if there was a real error.
102 if (errno != errc::not_enough_memory)
103 return error_code(errno, system_category());
104 // Otherwise there just wasn't enough space.
105 result.reserve(result.capacity() * 2);
106 } else
107 break;
108 }
Michael J. Spencerdffde992010-11-29 22:28:51 +0000109
110 result.set_size(strlen(result.data()));
Michael J. Spencer9d425e72010-12-04 18:45:32 +0000111 return success;
Michael J. Spencerdffde992010-11-29 22:28:51 +0000112}
113
Michael J. Spencerbee0c382010-12-01 19:32:01 +0000114error_code copy_file(const Twine &from, const Twine &to, copy_option copt) {
115 // Get arguments.
116 SmallString<128> from_storage;
117 SmallString<128> to_storage;
Michael J. Spencer871498e2010-12-01 20:37:42 +0000118 StringRef f = from.toNullTerminatedStringRef(from_storage);
119 StringRef t = to.toNullTerminatedStringRef(to_storage);
Michael J. Spencerbee0c382010-12-01 19:32:01 +0000120
121 const size_t buf_sz = 32768;
122 char buffer[buf_sz];
123 int from_file = -1, to_file = -1;
124
125 // Open from.
126 if ((from_file = ::open(f.begin(), O_RDONLY)) < 0)
127 return error_code(errno, system_category());
128 AutoFD from_fd(from_file);
129
130 // Stat from.
131 struct stat from_stat;
132 if (::stat(f.begin(), &from_stat) != 0)
133 return error_code(errno, system_category());
134
135 // Setup to flags.
136 int to_flags = O_CREAT | O_WRONLY;
137 if (copt == copy_option::fail_if_exists)
138 to_flags |= O_EXCL;
139
140 // Open to.
141 if ((to_file = ::open(t.begin(), to_flags, from_stat.st_mode)) < 0)
142 return error_code(errno, system_category());
143 AutoFD to_fd(to_file);
144
145 // Copy!
146 ssize_t sz, sz_read = 1, sz_write;
147 while (sz_read > 0 &&
148 (sz_read = ::read(from_fd, buffer, buf_sz)) > 0) {
149 // Allow for partial writes - see Advanced Unix Programming (2nd Ed.),
150 // Marc Rochkind, Addison-Wesley, 2004, page 94
151 sz_write = 0;
152 do {
153 if ((sz = ::write(to_fd, buffer + sz_write, sz_read - sz_write)) < 0) {
154 sz_read = sz; // cause read loop termination.
155 break; // error.
156 }
157 sz_write += sz;
158 } while (sz_write < sz_read);
159 }
160
161 // After all the file operations above the return value of close actually
162 // matters.
163 if (::close(from_fd.take()) < 0) sz_read = -1;
164 if (::close(to_fd.take()) < 0) sz_read = -1;
165
166 // Check for errors.
167 if (sz_read < 0)
168 return error_code(errno, system_category());
169
Michael J. Spencer9d425e72010-12-04 18:45:32 +0000170 return success;
Michael J. Spencerbee0c382010-12-01 19:32:01 +0000171}
172
Michael J. Spencerb83769f2010-12-03 05:42:11 +0000173error_code create_directory(const Twine &path, bool &existed) {
174 SmallString<128> path_storage;
175 StringRef p = path.toNullTerminatedStringRef(path_storage);
176
Michael J. Spencer79c3c3a2010-12-07 01:23:29 +0000177 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
Michael J. Spencer9d425e72010-12-04 18:45:32 +0000178 if (errno != errc::file_exists)
Michael J. Spencerb83769f2010-12-03 05:42:11 +0000179 return error_code(errno, system_category());
180 existed = true;
181 } else
182 existed = false;
183
Michael J. Spencer9d425e72010-12-04 18:45:32 +0000184 return success;
Michael J. Spencerb83769f2010-12-03 05:42:11 +0000185}
186
Michael J. Spencerd7b305f2010-12-03 05:58:41 +0000187error_code create_hard_link(const Twine &to, const Twine &from) {
188 // Get arguments.
189 SmallString<128> from_storage;
190 SmallString<128> to_storage;
191 StringRef f = from.toNullTerminatedStringRef(from_storage);
192 StringRef t = to.toNullTerminatedStringRef(to_storage);
193
194 if (::link(t.begin(), f.begin()) == -1)
195 return error_code(errno, system_category());
196
Michael J. Spencer9d425e72010-12-04 18:45:32 +0000197 return success;
Michael J. Spencerd7b305f2010-12-03 05:58:41 +0000198}
199
Michael J. Spencer9b391c52010-12-03 07:41:25 +0000200error_code create_symlink(const Twine &to, const Twine &from) {
201 // Get arguments.
202 SmallString<128> from_storage;
203 SmallString<128> to_storage;
204 StringRef f = from.toNullTerminatedStringRef(from_storage);
205 StringRef t = to.toNullTerminatedStringRef(to_storage);
206
207 if (::symlink(t.begin(), f.begin()) == -1)
208 return error_code(errno, system_category());
209
Michael J. Spencer9d425e72010-12-04 18:45:32 +0000210 return success;
Michael J. Spencer9b391c52010-12-03 07:41:25 +0000211}
212
Michael J. Spencer106aa732010-12-03 17:53:43 +0000213error_code remove(const Twine &path, bool &existed) {
214 SmallString<128> path_storage;
215 StringRef p = path.toNullTerminatedStringRef(path_storage);
216
217 if (::remove(p.begin()) == -1) {
Michael J. Spencer9d425e72010-12-04 18:45:32 +0000218 if (errno != errc::no_such_file_or_directory)
Michael J. Spencer106aa732010-12-03 17:53:43 +0000219 return error_code(errno, system_category());
220 existed = false;
221 } else
222 existed = true;
223
Michael J. Spencer9d425e72010-12-04 18:45:32 +0000224 return success;
Michael J. Spencer106aa732010-12-03 17:53:43 +0000225}
226
Michael J. Spencera50b98c2010-12-03 17:53:55 +0000227error_code rename(const Twine &from, const Twine &to) {
228 // Get arguments.
229 SmallString<128> from_storage;
230 SmallString<128> to_storage;
231 StringRef f = from.toNullTerminatedStringRef(from_storage);
232 StringRef t = to.toNullTerminatedStringRef(to_storage);
233
Michael J. Spencer283d49c2011-01-16 22:18:41 +0000234 if (::rename(f.begin(), t.begin()) == -1) {
235 // If it's a cross device link, copy then delete, otherwise return the error
236 if (errno == EXDEV) {
237 if (error_code ec = copy_file(from, to, copy_option::overwrite_if_exists))
238 return ec;
239 bool Existed;
240 if (error_code ec = remove(from, Existed))
241 return ec;
242 } else
243 return error_code(errno, system_category());
244 }
Michael J. Spencera50b98c2010-12-03 17:53:55 +0000245
Michael J. Spencer9d425e72010-12-04 18:45:32 +0000246 return success;
Michael J. Spencera50b98c2010-12-03 17:53:55 +0000247}
248
Michael J. Spencer3920d3b2010-12-03 17:54:07 +0000249error_code resize_file(const Twine &path, uint64_t size) {
250 SmallString<128> path_storage;
251 StringRef p = path.toNullTerminatedStringRef(path_storage);
252
253 if (::truncate(p.begin(), size) == -1)
254 return error_code(errno, system_category());
255
Michael J. Spencer9d425e72010-12-04 18:45:32 +0000256 return success;
Michael J. Spencer3920d3b2010-12-03 17:54:07 +0000257}
258
Michael J. Spencer3cb84ef2010-12-03 01:21:28 +0000259error_code exists(const Twine &path, bool &result) {
260 SmallString<128> path_storage;
261 StringRef p = path.toNullTerminatedStringRef(path_storage);
262
263 struct stat status;
264 if (::stat(p.begin(), &status) == -1) {
Michael J. Spencer9d425e72010-12-04 18:45:32 +0000265 if (errno != errc::no_such_file_or_directory)
Michael J. Spencer3cb84ef2010-12-03 01:21:28 +0000266 return error_code(errno, system_category());
267 result = false;
268 } else
269 result = true;
270
Michael J. Spencer9d425e72010-12-04 18:45:32 +0000271 return success;
Michael J. Spencer3cb84ef2010-12-03 01:21:28 +0000272}
273
Michael J. Spencerb531f452010-12-03 18:49:13 +0000274error_code equivalent(const Twine &A, const Twine &B, bool &result) {
275 // Get arguments.
276 SmallString<128> a_storage;
277 SmallString<128> b_storage;
278 StringRef a = A.toNullTerminatedStringRef(a_storage);
279 StringRef b = B.toNullTerminatedStringRef(b_storage);
280
281 struct stat stat_a, stat_b;
282 int error_b = ::stat(b.begin(), &stat_b);
283 int error_a = ::stat(a.begin(), &stat_a);
284
285 // If both are invalid, it's an error. If only one is, the result is false.
286 if (error_a != 0 || error_b != 0) {
287 if (error_a == error_b)
288 return error_code(errno, system_category());
289 result = false;
290 } else {
291 result =
292 stat_a.st_dev == stat_b.st_dev &&
293 stat_a.st_ino == stat_b.st_ino;
294 }
295
Michael J. Spencer9d425e72010-12-04 18:45:32 +0000296 return success;
Michael J. Spencerb531f452010-12-03 18:49:13 +0000297}
298
Michael J. Spencer01a87c42010-12-04 00:31:48 +0000299error_code file_size(const Twine &path, uint64_t &result) {
300 SmallString<128> path_storage;
301 StringRef p = path.toNullTerminatedStringRef(path_storage);
302
303 struct stat status;
304 if (::stat(p.begin(), &status) == -1)
305 return error_code(errno, system_category());
306 if (!S_ISREG(status.st_mode))
Michael J. Spencer9d425e72010-12-04 18:45:32 +0000307 return make_error_code(errc::operation_not_permitted);
Michael J. Spencer01a87c42010-12-04 00:31:48 +0000308
309 result = status.st_size;
Michael J. Spencer9d425e72010-12-04 18:45:32 +0000310 return success;
Michael J. Spencer01a87c42010-12-04 00:31:48 +0000311}
312
Michael J. Spencer470ae132010-12-04 00:32:40 +0000313error_code status(const Twine &path, file_status &result) {
314 SmallString<128> path_storage;
315 StringRef p = path.toNullTerminatedStringRef(path_storage);
316
317 struct stat status;
318 if (::stat(p.begin(), &status) != 0) {
319 error_code ec(errno, system_category());
320 if (ec == errc::no_such_file_or_directory)
321 result = file_status(file_type::file_not_found);
322 else
323 result = file_status(file_type::status_error);
324 return ec;
325 }
326
327 if (S_ISDIR(status.st_mode))
328 result = file_status(file_type::directory_file);
329 else if (S_ISREG(status.st_mode))
330 result = file_status(file_type::regular_file);
331 else if (S_ISBLK(status.st_mode))
332 result = file_status(file_type::block_file);
333 else if (S_ISCHR(status.st_mode))
334 result = file_status(file_type::character_file);
335 else if (S_ISFIFO(status.st_mode))
336 result = file_status(file_type::fifo_file);
337 else if (S_ISSOCK(status.st_mode))
338 result = file_status(file_type::socket_file);
339 else
340 result = file_status(file_type::type_unknown);
341
342 return success;
343}
344
Michael J. Spencer3cb84ef2010-12-03 01:21:28 +0000345error_code unique_file(const Twine &model, int &result_fd,
346 SmallVectorImpl<char> &result_path) {
347 SmallString<128> Model;
348 model.toVector(Model);
349 // Null terminate.
350 Model.c_str();
351
352 // Make model absolute by prepending a temp directory if it's not already.
Michael J. Spencer50291592010-12-07 17:04:04 +0000353 bool absolute = path::is_absolute(Twine(Model));
Michael J. Spencer3cb84ef2010-12-03 01:21:28 +0000354 if (!absolute) {
355 SmallString<128> TDir;
356 if (error_code ec = TempDir(TDir)) return ec;
Michael J. Spencer936671b2010-12-07 03:57:37 +0000357 path::append(TDir, Twine(Model));
Michael J. Spencer3cb84ef2010-12-03 01:21:28 +0000358 Model.swap(TDir);
359 }
360
361 // Replace '%' with random chars. From here on, DO NOT modify model. It may be
362 // needed if the randomly chosen path already exists.
363 SmallString<128> RandomPath;
364 RandomPath.reserve(Model.size() + 1);
365 ::srand(::time(NULL));
366
367retry_random_path:
368 // This is opened here instead of above to make it easier to track when to
369 // close it. Collisions should be rare enough for the possible extra syscalls
370 // not to matter.
371 FILE *RandomSource = ::fopen("/dev/urandom", "r");
372 RandomPath.set_size(0);
373 for (SmallVectorImpl<char>::const_iterator i = Model.begin(),
374 e = Model.end(); i != e; ++i) {
375 if (*i == '%') {
376 char val = 0;
377 if (RandomSource)
378 val = fgetc(RandomSource);
379 else
380 val = ::rand();
381 RandomPath.push_back("0123456789abcdef"[val & 15]);
382 } else
383 RandomPath.push_back(*i);
384 }
385
386 if (RandomSource)
387 ::fclose(RandomSource);
388
389 // Try to open + create the file.
390rety_open_create:
391 int RandomFD = ::open(RandomPath.c_str(), O_RDWR | O_CREAT | O_EXCL, 0600);
392 if (RandomFD == -1) {
393 // If the file existed, try again, otherwise, error.
Michael J. Spencer9d425e72010-12-04 18:45:32 +0000394 if (errno == errc::file_exists)
Michael J. Spencer3cb84ef2010-12-03 01:21:28 +0000395 goto retry_random_path;
396 // The path prefix doesn't exist.
Michael J. Spencer9d425e72010-12-04 18:45:32 +0000397 if (errno == errc::no_such_file_or_directory) {
Michael J. Spencer3cb84ef2010-12-03 01:21:28 +0000398 StringRef p(RandomPath.begin(), RandomPath.size());
399 SmallString<64> dir_to_create;
400 for (path::const_iterator i = path::begin(p),
401 e = --path::end(p); i != e; ++i) {
Michael J. Spencer936671b2010-12-07 03:57:37 +0000402 path::append(dir_to_create, *i);
Michael J. Spencer3cb84ef2010-12-03 01:21:28 +0000403 bool Exists;
404 if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
405 if (!Exists) {
406 // Don't try to create network paths.
407 if (i->size() > 2 && (*i)[0] == '/' &&
408 (*i)[1] == '/' &&
409 (*i)[2] != '/')
Michael J. Spencer9d425e72010-12-04 18:45:32 +0000410 return make_error_code(errc::no_such_file_or_directory);
Michael J. Spencer3cb84ef2010-12-03 01:21:28 +0000411 if (::mkdir(dir_to_create.c_str(), 0700) == -1)
412 return error_code(errno, system_category());
413 }
414 }
415 goto rety_open_create;
416 }
417 return error_code(errno, system_category());
418 }
419
Michael J. Spencer9d425e72010-12-04 18:45:32 +0000420 // Make the path absolute.
Michael J. Spencere1db1b82011-03-24 05:23:40 +0000421 if (error_code ec = make_absolute(RandomPath)) {
Michael J. Spencer3cb84ef2010-12-03 01:21:28 +0000422 ::close(RandomFD);
423 ::unlink(RandomPath.c_str());
Michael J. Spencere1db1b82011-03-24 05:23:40 +0000424 return ec;
Michael J. Spencer3cb84ef2010-12-03 01:21:28 +0000425 }
426
Michael J. Spencere1db1b82011-03-24 05:23:40 +0000427 result_path = RandomPath;
Michael J. Spencer3cb84ef2010-12-03 01:21:28 +0000428 result_fd = RandomFD;
Michael J. Spencer9d425e72010-12-04 18:45:32 +0000429 return success;
Michael J. Spencer3cb84ef2010-12-03 01:21:28 +0000430}
431
Michael J. Spencerda7c1ca2011-01-05 16:38:57 +0000432error_code directory_iterator_construct(directory_iterator &it, StringRef path){
433 SmallString<128> path_null(path);
434 DIR *directory = ::opendir(path_null.c_str());
435 if (directory == 0)
436 return error_code(errno, system_category());
437
438 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
439 // Add something for replace_filename to replace.
440 path::append(path_null, ".");
441 it.CurrentEntry = directory_entry(path_null.str());
442 return directory_iterator_increment(it);
443}
444
445error_code directory_iterator_destruct(directory_iterator& it) {
446 if (it.IterationHandle)
447 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
448 it.IterationHandle = 0;
449 it.CurrentEntry = directory_entry();
450 return success;
451}
452
453error_code directory_iterator_increment(directory_iterator& it) {
454 errno = 0;
455 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
456 if (cur_dir == 0 && errno != 0) {
457 return error_code(errno, system_category());
458 } else if (cur_dir != 0) {
459 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
460 if ((name.size() == 1 && name[0] == '.') ||
461 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
462 return directory_iterator_increment(it);
463 it.CurrentEntry.replace_filename(name);
464 } else
465 return directory_iterator_destruct(it);
466
467 return success;
468}
469
Michael J. Spencerd6cdf1d2011-01-15 18:52:33 +0000470error_code get_magic(const Twine &path, uint32_t len,
471 SmallVectorImpl<char> &result) {
472 SmallString<128> PathStorage;
473 StringRef Path = path.toNullTerminatedStringRef(PathStorage);
474 result.set_size(0);
475
476 // Open path.
477 std::FILE *file = std::fopen(Path.data(), "rb");
478 if (file == 0)
479 return error_code(errno, system_category());
480
481 // Reserve storage.
482 result.reserve(len);
483
484 // Read magic!
485 size_t size = std::fread(result.data(), 1, len, file);
486 if (std::ferror(file) != 0) {
487 std::fclose(file);
488 return error_code(errno, system_category());
489 } else if (size != result.size()) {
490 if (std::feof(file) != 0) {
491 std::fclose(file);
492 result.set_size(size);
493 return make_error_code(errc::value_too_large);
494 }
495 }
496 std::fclose(file);
497 result.set_size(len);
498 return success;
499}
500
Michael J. Spencerbee0c382010-12-01 19:32:01 +0000501} // end namespace fs
Michael J. Spencerdffde992010-11-29 22:28:51 +0000502} // end namespace sys
503} // end namespace llvm