blob: 39b33123de8a983a8051bbaac040dffe97434021 [file] [log] [blame]
Michael J. Spencerebad2f92010-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"
Daniel Dunbar3f0fa192012-05-05 16:36:24 +000020#include "llvm/Support/Process.h"
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000021#if HAVE_SYS_STAT_H
22#include <sys/stat.h>
23#endif
24#if HAVE_FCNTL_H
25#include <fcntl.h>
26#endif
Nick Kledzik18497e92012-06-20 00:28:54 +000027#ifdef HAVE_SYS_MMAN_H
28#include <sys/mman.h>
29#endif
Michael J. Spencer52714862011-01-05 16:38:57 +000030#if HAVE_DIRENT_H
31# include <dirent.h>
32# define NAMLEN(dirent) strlen((dirent)->d_name)
33#else
34# define dirent direct
35# define NAMLEN(dirent) (dirent)->d_namlen
36# if HAVE_SYS_NDIR_H
37# include <sys/ndir.h>
38# endif
39# if HAVE_SYS_DIR_H
40# include <sys/dir.h>
41# endif
42# if HAVE_NDIR_H
43# include <ndir.h>
44# endif
45#endif
Michael J. Spencer45710402010-12-03 01:21:28 +000046#if HAVE_STDIO_H
47#include <stdio.h>
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000048#endif
Bill Wendlingbdaa57f2011-09-14 21:49:42 +000049#if HAVE_LIMITS_H
50#include <limits.h>
51#endif
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000052
Joerg Sonnenbergerc0697302012-08-10 10:56:09 +000053// Both stdio.h and cstdio are included via different pathes and
54// stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
55// either.
56#undef ferror
57#undef feof
58
Sylvestre Ledru14ada942012-04-11 15:35:36 +000059// For GNU Hurd
60#if defined(__GNU__) && !defined(PATH_MAX)
61# define PATH_MAX 4096
62#endif
63
Michael J. Spencer45710402010-12-03 01:21:28 +000064using namespace llvm;
65
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000066namespace {
Michael J. Spencer5529c572010-12-07 01:23:08 +000067 /// This class automatically closes the given file descriptor when it goes out
68 /// of scope. You can take back explicit ownership of the file descriptor by
69 /// calling take(). The destructor does not verify that close was successful.
70 /// Therefore, never allow this class to call close on a file descriptor that
71 /// has been read from or written to.
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000072 struct AutoFD {
73 int FileDescriptor;
74
75 AutoFD(int fd) : FileDescriptor(fd) {}
76 ~AutoFD() {
77 if (FileDescriptor >= 0)
78 ::close(FileDescriptor);
79 }
80
81 int take() {
82 int ret = FileDescriptor;
83 FileDescriptor = -1;
84 return ret;
85 }
86
87 operator int() const {return FileDescriptor;}
88 };
Michael J. Spencer45710402010-12-03 01:21:28 +000089
90 error_code TempDir(SmallVectorImpl<char> &result) {
91 // FIXME: Don't use TMPDIR if program is SUID or SGID enabled.
92 const char *dir = 0;
93 (dir = std::getenv("TMPDIR" )) ||
94 (dir = std::getenv("TMP" )) ||
95 (dir = std::getenv("TEMP" )) ||
96 (dir = std::getenv("TEMPDIR")) ||
97#ifdef P_tmpdir
98 (dir = P_tmpdir) ||
99#endif
100 (dir = "/tmp");
101
Michael J. Spencer98c7a112010-12-07 01:23:19 +0000102 result.clear();
Michael J. Spencer45710402010-12-03 01:21:28 +0000103 StringRef d(dir);
104 result.append(d.begin(), d.end());
David Blaikie18544b92012-02-09 19:24:12 +0000105 return error_code::success();
Michael J. Spencer45710402010-12-03 01:21:28 +0000106 }
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000107}
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000108
109namespace llvm {
110namespace sys {
Michael J. Spencer20daa282010-12-07 01:22:31 +0000111namespace fs {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000112
113error_code current_path(SmallVectorImpl<char> &result) {
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000114#ifdef MAXPATHLEN
Andrew Tricka4ec5b22011-03-24 16:43:37 +0000115 result.reserve(MAXPATHLEN);
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000116#else
117// For GNU Hurd
118 result.reserve(1024);
119#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000120
Michael J. Spencer20daa282010-12-07 01:22:31 +0000121 while (true) {
122 if (::getcwd(result.data(), result.capacity()) == 0) {
123 // See if there was a real error.
124 if (errno != errc::not_enough_memory)
125 return error_code(errno, system_category());
126 // Otherwise there just wasn't enough space.
127 result.reserve(result.capacity() * 2);
128 } else
129 break;
130 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000131
132 result.set_size(strlen(result.data()));
David Blaikie18544b92012-02-09 19:24:12 +0000133 return error_code::success();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000134}
135
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000136error_code copy_file(const Twine &from, const Twine &to, copy_option copt) {
137 // Get arguments.
138 SmallString<128> from_storage;
139 SmallString<128> to_storage;
Michael J. Spencer795adf52010-12-01 20:37:42 +0000140 StringRef f = from.toNullTerminatedStringRef(from_storage);
141 StringRef t = to.toNullTerminatedStringRef(to_storage);
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000142
143 const size_t buf_sz = 32768;
144 char buffer[buf_sz];
145 int from_file = -1, to_file = -1;
146
147 // Open from.
148 if ((from_file = ::open(f.begin(), O_RDONLY)) < 0)
149 return error_code(errno, system_category());
150 AutoFD from_fd(from_file);
151
152 // Stat from.
153 struct stat from_stat;
154 if (::stat(f.begin(), &from_stat) != 0)
155 return error_code(errno, system_category());
156
157 // Setup to flags.
158 int to_flags = O_CREAT | O_WRONLY;
159 if (copt == copy_option::fail_if_exists)
160 to_flags |= O_EXCL;
161
162 // Open to.
163 if ((to_file = ::open(t.begin(), to_flags, from_stat.st_mode)) < 0)
164 return error_code(errno, system_category());
165 AutoFD to_fd(to_file);
166
167 // Copy!
168 ssize_t sz, sz_read = 1, sz_write;
169 while (sz_read > 0 &&
170 (sz_read = ::read(from_fd, buffer, buf_sz)) > 0) {
171 // Allow for partial writes - see Advanced Unix Programming (2nd Ed.),
172 // Marc Rochkind, Addison-Wesley, 2004, page 94
173 sz_write = 0;
174 do {
175 if ((sz = ::write(to_fd, buffer + sz_write, sz_read - sz_write)) < 0) {
176 sz_read = sz; // cause read loop termination.
177 break; // error.
178 }
179 sz_write += sz;
180 } while (sz_write < sz_read);
181 }
182
183 // After all the file operations above the return value of close actually
184 // matters.
185 if (::close(from_fd.take()) < 0) sz_read = -1;
186 if (::close(to_fd.take()) < 0) sz_read = -1;
187
188 // Check for errors.
189 if (sz_read < 0)
190 return error_code(errno, system_category());
191
David Blaikie18544b92012-02-09 19:24:12 +0000192 return error_code::success();
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000193}
194
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000195error_code create_directory(const Twine &path, bool &existed) {
196 SmallString<128> path_storage;
197 StringRef p = path.toNullTerminatedStringRef(path_storage);
198
Michael J. Spencere5755be2010-12-07 01:23:29 +0000199 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
Michael J. Spencer66a1f862010-12-04 18:45:32 +0000200 if (errno != errc::file_exists)
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000201 return error_code(errno, system_category());
202 existed = true;
203 } else
204 existed = false;
205
David Blaikie18544b92012-02-09 19:24:12 +0000206 return error_code::success();
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000207}
208
Michael J. Spencere0c45602010-12-03 05:58:41 +0000209error_code create_hard_link(const Twine &to, const Twine &from) {
210 // Get arguments.
211 SmallString<128> from_storage;
212 SmallString<128> to_storage;
213 StringRef f = from.toNullTerminatedStringRef(from_storage);
214 StringRef t = to.toNullTerminatedStringRef(to_storage);
215
216 if (::link(t.begin(), f.begin()) == -1)
217 return error_code(errno, system_category());
218
David Blaikie18544b92012-02-09 19:24:12 +0000219 return error_code::success();
Michael J. Spencere0c45602010-12-03 05:58:41 +0000220}
221
Michael J. Spencer7ee6d5d2010-12-03 07:41:25 +0000222error_code create_symlink(const Twine &to, const Twine &from) {
223 // Get arguments.
224 SmallString<128> from_storage;
225 SmallString<128> to_storage;
226 StringRef f = from.toNullTerminatedStringRef(from_storage);
227 StringRef t = to.toNullTerminatedStringRef(to_storage);
228
229 if (::symlink(t.begin(), f.begin()) == -1)
230 return error_code(errno, system_category());
231
David Blaikie18544b92012-02-09 19:24:12 +0000232 return error_code::success();
Michael J. Spencer7ee6d5d2010-12-03 07:41:25 +0000233}
234
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000235error_code remove(const Twine &path, bool &existed) {
236 SmallString<128> path_storage;
237 StringRef p = path.toNullTerminatedStringRef(path_storage);
238
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000239 struct stat buf;
240 if (stat(p.begin(), &buf) != 0) {
241 if (errno != errc::no_such_file_or_directory)
242 return error_code(errno, system_category());
243 existed = false;
244 return error_code::success();
245 }
246
247 // Note: this check catches strange situations. In all cases, LLVM should
248 // only be involved in the creation and deletion of regular files. This
249 // check ensures that what we're trying to erase is a regular file. It
250 // effectively prevents LLVM from erasing things like /dev/null, any block
251 // special file, or other things that aren't "regular" files.
252 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode))
253 return make_error_code(errc::operation_not_permitted);
254
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000255 if (::remove(p.begin()) == -1) {
Michael J. Spencer66a1f862010-12-04 18:45:32 +0000256 if (errno != errc::no_such_file_or_directory)
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000257 return error_code(errno, system_category());
258 existed = false;
259 } else
260 existed = true;
261
David Blaikie18544b92012-02-09 19:24:12 +0000262 return error_code::success();
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000263}
264
Michael J. Spencer409f5562010-12-03 17:53:55 +0000265error_code rename(const Twine &from, const Twine &to) {
266 // Get arguments.
267 SmallString<128> from_storage;
268 SmallString<128> to_storage;
269 StringRef f = from.toNullTerminatedStringRef(from_storage);
270 StringRef t = to.toNullTerminatedStringRef(to_storage);
271
Michael J. Spencerec202ee2011-01-16 22:18:41 +0000272 if (::rename(f.begin(), t.begin()) == -1) {
273 // If it's a cross device link, copy then delete, otherwise return the error
274 if (errno == EXDEV) {
275 if (error_code ec = copy_file(from, to, copy_option::overwrite_if_exists))
276 return ec;
277 bool Existed;
278 if (error_code ec = remove(from, Existed))
279 return ec;
280 } else
281 return error_code(errno, system_category());
282 }
Michael J. Spencer409f5562010-12-03 17:53:55 +0000283
David Blaikie18544b92012-02-09 19:24:12 +0000284 return error_code::success();
Michael J. Spencer409f5562010-12-03 17:53:55 +0000285}
286
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000287error_code resize_file(const Twine &path, uint64_t size) {
288 SmallString<128> path_storage;
289 StringRef p = path.toNullTerminatedStringRef(path_storage);
290
291 if (::truncate(p.begin(), size) == -1)
292 return error_code(errno, system_category());
293
David Blaikie18544b92012-02-09 19:24:12 +0000294 return error_code::success();
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000295}
296
Michael J. Spencer45710402010-12-03 01:21:28 +0000297error_code exists(const Twine &path, bool &result) {
298 SmallString<128> path_storage;
299 StringRef p = path.toNullTerminatedStringRef(path_storage);
300
Benjamin Kramer172f8082012-06-02 16:28:09 +0000301 if (::access(p.begin(), F_OK) == -1) {
Michael J. Spencer66a1f862010-12-04 18:45:32 +0000302 if (errno != errc::no_such_file_or_directory)
Michael J. Spencer45710402010-12-03 01:21:28 +0000303 return error_code(errno, system_category());
304 result = false;
305 } else
306 result = true;
307
David Blaikie18544b92012-02-09 19:24:12 +0000308 return error_code::success();
Michael J. Spencer45710402010-12-03 01:21:28 +0000309}
310
Rafael Espindolaa1280c12013-06-18 20:56:38 +0000311bool can_write(const Twine &Path) {
312 SmallString<128> PathStorage;
313 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
314 return 0 == access(P.begin(), W_OK);
315}
316
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000317bool can_execute(const Twine &Path) {
318 SmallString<128> PathStorage;
319 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
320
Manuel Klimek52772bf2013-06-17 10:48:34 +0000321 if (0 != access(P.begin(), R_OK | X_OK))
322 return false;
323 struct stat buf;
324 if (0 != stat(P.begin(), &buf))
325 return false;
326 if (!S_ISREG(buf.st_mode))
327 return false;
328 return true;
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000329}
330
Michael J. Spencer203d7802011-12-12 06:04:28 +0000331bool equivalent(file_status A, file_status B) {
332 assert(status_known(A) && status_known(B));
Sylvestre Ledru3099f4bd2012-04-23 16:37:23 +0000333 return A.fs_st_dev == B.fs_st_dev &&
334 A.fs_st_ino == B.fs_st_ino;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000335}
336
Michael J. Spencer376d3872010-12-03 18:49:13 +0000337error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000338 file_status fsA, fsB;
339 if (error_code ec = status(A, fsA)) return ec;
340 if (error_code ec = status(B, fsB)) return ec;
341 result = equivalent(fsA, fsB);
David Blaikie18544b92012-02-09 19:24:12 +0000342 return error_code::success();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000343}
344
Michael J. Spencer818ab4a2010-12-04 00:31:48 +0000345error_code file_size(const Twine &path, uint64_t &result) {
346 SmallString<128> path_storage;
347 StringRef p = path.toNullTerminatedStringRef(path_storage);
348
349 struct stat status;
350 if (::stat(p.begin(), &status) == -1)
351 return error_code(errno, system_category());
352 if (!S_ISREG(status.st_mode))
Michael J. Spencer66a1f862010-12-04 18:45:32 +0000353 return make_error_code(errc::operation_not_permitted);
Michael J. Spencer818ab4a2010-12-04 00:31:48 +0000354
355 result = status.st_size;
David Blaikie18544b92012-02-09 19:24:12 +0000356 return error_code::success();
Michael J. Spencer818ab4a2010-12-04 00:31:48 +0000357}
358
Rafael Espindola7cf7c512013-06-20 15:06:35 +0000359error_code getUniqueID(const Twine Path, uint64_t &Result) {
Rafael Espindola45e6c242013-06-18 19:34:49 +0000360 SmallString<128> Storage;
361 StringRef P = Path.toNullTerminatedStringRef(Storage);
362
363 struct stat Status;
364 if (::stat(P.begin(), &Status) != 0)
365 return error_code(errno, system_category());
366
367 Result = Status.st_ino;
368 return error_code::success();
369}
370
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000371error_code status(const Twine &path, file_status &result) {
372 SmallString<128> path_storage;
373 StringRef p = path.toNullTerminatedStringRef(path_storage);
374
375 struct stat status;
376 if (::stat(p.begin(), &status) != 0) {
377 error_code ec(errno, system_category());
378 if (ec == errc::no_such_file_or_directory)
379 result = file_status(file_type::file_not_found);
380 else
381 result = file_status(file_type::status_error);
382 return ec;
383 }
384
Nick Kledzik18497e92012-06-20 00:28:54 +0000385 perms prms = static_cast<perms>(status.st_mode & perms_mask);
386
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000387 if (S_ISDIR(status.st_mode))
Nick Kledzik18497e92012-06-20 00:28:54 +0000388 result = file_status(file_type::directory_file, prms);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000389 else if (S_ISREG(status.st_mode))
Nick Kledzik18497e92012-06-20 00:28:54 +0000390 result = file_status(file_type::regular_file, prms);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000391 else if (S_ISBLK(status.st_mode))
Nick Kledzik18497e92012-06-20 00:28:54 +0000392 result = file_status(file_type::block_file, prms);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000393 else if (S_ISCHR(status.st_mode))
Nick Kledzik18497e92012-06-20 00:28:54 +0000394 result = file_status(file_type::character_file, prms);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000395 else if (S_ISFIFO(status.st_mode))
Nick Kledzik18497e92012-06-20 00:28:54 +0000396 result = file_status(file_type::fifo_file, prms);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000397 else if (S_ISSOCK(status.st_mode))
Nick Kledzik18497e92012-06-20 00:28:54 +0000398 result = file_status(file_type::socket_file, prms);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000399 else
Nick Kledzik18497e92012-06-20 00:28:54 +0000400 result = file_status(file_type::type_unknown, prms);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000401
Sylvestre Ledru3099f4bd2012-04-23 16:37:23 +0000402 result.fs_st_dev = status.st_dev;
403 result.fs_st_ino = status.st_ino;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000404
David Blaikie18544b92012-02-09 19:24:12 +0000405 return error_code::success();
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000406}
407
Nick Kledzik18497e92012-06-20 00:28:54 +0000408// Modifies permissions on a file.
409error_code permissions(const Twine &path, perms prms) {
410 if ((prms & add_perms) && (prms & remove_perms))
411 llvm_unreachable("add_perms and remove_perms are mutually exclusive");
412
413 // Get current permissions
414 file_status info;
415 if (error_code ec = status(path, info)) {
416 return ec;
417 }
418
419 // Set updated permissions.
420 SmallString<128> path_storage;
421 StringRef p = path.toNullTerminatedStringRef(path_storage);
422 perms permsToSet;
423 if (prms & add_perms) {
424 permsToSet = (info.permissions() | prms) & perms_mask;
425 } else if (prms & remove_perms) {
426 permsToSet = (info.permissions() & ~prms) & perms_mask;
427 } else {
428 permsToSet = prms & perms_mask;
429 }
430 if (::chmod(p.begin(), static_cast<mode_t>(permsToSet))) {
431 return error_code(errno, system_category());
432 }
433
434 return error_code::success();
435}
436
Eric Christopherb6148ed2012-05-11 00:07:44 +0000437// Since this is most often used for temporary files, mode defaults to 0600.
Michael J. Spencer45710402010-12-03 01:21:28 +0000438error_code unique_file(const Twine &model, int &result_fd,
Eric Christopherb6148ed2012-05-11 00:07:44 +0000439 SmallVectorImpl<char> &result_path,
440 bool makeAbsolute, unsigned mode) {
Michael J. Spencer45710402010-12-03 01:21:28 +0000441 SmallString<128> Model;
442 model.toVector(Model);
443 // Null terminate.
444 Model.c_str();
445
Argyrios Kyrtzidis348937d2011-07-28 00:29:20 +0000446 if (makeAbsolute) {
447 // Make model absolute by prepending a temp directory if it's not already.
448 bool absolute = path::is_absolute(Twine(Model));
449 if (!absolute) {
450 SmallString<128> TDir;
451 if (error_code ec = TempDir(TDir)) return ec;
452 path::append(TDir, Twine(Model));
453 Model.swap(TDir);
454 }
Michael J. Spencer45710402010-12-03 01:21:28 +0000455 }
456
Daniel Dunbar58ed0c62012-05-05 16:39:22 +0000457 // From here on, DO NOT modify model. It may be needed if the randomly chosen
458 // path already exists.
Daniel Dunbar3f0fa192012-05-05 16:36:24 +0000459 SmallString<128> RandomPath = Model;
Michael J. Spencer45710402010-12-03 01:21:28 +0000460
461retry_random_path:
Daniel Dunbar58ed0c62012-05-05 16:39:22 +0000462 // Replace '%' with random chars.
Daniel Dunbar3f0fa192012-05-05 16:36:24 +0000463 for (unsigned i = 0, e = Model.size(); i != e; ++i) {
464 if (Model[i] == '%')
465 RandomPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
Michael J. Spencer45710402010-12-03 01:21:28 +0000466 }
467
Argyrios Kyrtzidiseed2dc52013-02-28 00:38:19 +0000468 // Make sure we don't fall into an infinite loop by constantly trying
469 // to create the parent path.
470 bool TriedToCreateParent = false;
471
Michael J. Spencer45710402010-12-03 01:21:28 +0000472 // Try to open + create the file.
473rety_open_create:
Eric Christopherb6148ed2012-05-11 00:07:44 +0000474 int RandomFD = ::open(RandomPath.c_str(), O_RDWR | O_CREAT | O_EXCL, mode);
Michael J. Spencer45710402010-12-03 01:21:28 +0000475 if (RandomFD == -1) {
Douglas Gregor95585ab2013-01-10 01:58:46 +0000476 int SavedErrno = errno;
Michael J. Spencer45710402010-12-03 01:21:28 +0000477 // If the file existed, try again, otherwise, error.
Douglas Gregor95585ab2013-01-10 01:58:46 +0000478 if (SavedErrno == errc::file_exists)
Michael J. Spencer45710402010-12-03 01:21:28 +0000479 goto retry_random_path;
Daniel Dunbar61d59f22012-11-15 20:24:52 +0000480 // If path prefix doesn't exist, try to create it.
Douglas Gregor6bd4d8c2013-04-05 20:48:36 +0000481 if (SavedErrno == errc::no_such_file_or_directory && !TriedToCreateParent) {
Argyrios Kyrtzidiseed2dc52013-02-28 00:38:19 +0000482 TriedToCreateParent = true;
Daniel Dunbar61d59f22012-11-15 20:24:52 +0000483 StringRef p(RandomPath);
Michael J. Spencer45710402010-12-03 01:21:28 +0000484 SmallString<64> dir_to_create;
485 for (path::const_iterator i = path::begin(p),
486 e = --path::end(p); i != e; ++i) {
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000487 path::append(dir_to_create, *i);
Michael J. Spencer45710402010-12-03 01:21:28 +0000488 bool Exists;
489 if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
490 if (!Exists) {
491 // Don't try to create network paths.
492 if (i->size() > 2 && (*i)[0] == '/' &&
493 (*i)[1] == '/' &&
494 (*i)[2] != '/')
Michael J. Spencer66a1f862010-12-04 18:45:32 +0000495 return make_error_code(errc::no_such_file_or_directory);
Douglas Gregor95585ab2013-01-10 01:58:46 +0000496 if (::mkdir(dir_to_create.c_str(), 0700) == -1 &&
497 errno != errc::file_exists)
Michael J. Spencer45710402010-12-03 01:21:28 +0000498 return error_code(errno, system_category());
499 }
500 }
501 goto rety_open_create;
502 }
Douglas Gregor95585ab2013-01-10 01:58:46 +0000503
504 return error_code(SavedErrno, system_category());
Michael J. Spencer45710402010-12-03 01:21:28 +0000505 }
506
Michael J. Spencer66a1f862010-12-04 18:45:32 +0000507 // Make the path absolute.
Andrew Tricka4ec5b22011-03-24 16:43:37 +0000508 char real_path_buff[PATH_MAX + 1];
509 if (realpath(RandomPath.c_str(), real_path_buff) == NULL) {
510 int error = errno;
Michael J. Spencer45710402010-12-03 01:21:28 +0000511 ::close(RandomFD);
512 ::unlink(RandomPath.c_str());
Andrew Tricka4ec5b22011-03-24 16:43:37 +0000513 return error_code(error, system_category());
Michael J. Spencer45710402010-12-03 01:21:28 +0000514 }
515
Andrew Tricka4ec5b22011-03-24 16:43:37 +0000516 result_path.clear();
517 StringRef d(real_path_buff);
518 result_path.append(d.begin(), d.end());
519
Michael J. Spencer45710402010-12-03 01:21:28 +0000520 result_fd = RandomFD;
David Blaikie18544b92012-02-09 19:24:12 +0000521 return error_code::success();
Michael J. Spencer45710402010-12-03 01:21:28 +0000522}
523
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000524error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
525 AutoFD ScopedFD(FD);
526 if (!CloseFD)
527 ScopedFD.take();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000528
529 // Figure out how large the file is.
530 struct stat FileInfo;
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000531 if (fstat(FD, &FileInfo) == -1)
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000532 return error_code(errno, system_category());
533 uint64_t FileSize = FileInfo.st_size;
534
535 if (Size == 0)
536 Size = FileSize;
537 else if (FileSize < Size) {
538 // We need to grow the file.
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000539 if (ftruncate(FD, Size) == -1)
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000540 return error_code(errno, system_category());
541 }
542
543 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
544 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
545#ifdef MAP_FILE
546 flags |= MAP_FILE;
547#endif
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000548 Mapping = ::mmap(0, Size, prot, flags, FD, Offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000549 if (Mapping == MAP_FAILED)
550 return error_code(errno, system_category());
551 return error_code::success();
552}
553
554mapped_file_region::mapped_file_region(const Twine &path,
555 mapmode mode,
556 uint64_t length,
557 uint64_t offset,
558 error_code &ec)
559 : Mode(mode)
560 , Size(length)
561 , Mapping() {
562 // Make sure that the requested size fits within SIZE_T.
563 if (length > std::numeric_limits<size_t>::max()) {
564 ec = make_error_code(errc::invalid_argument);
565 return;
566 }
567
568 SmallString<128> path_storage;
569 StringRef name = path.toNullTerminatedStringRef(path_storage);
570 int oflags = (mode == readonly) ? O_RDONLY : O_RDWR;
571 int ofd = ::open(name.begin(), oflags);
572 if (ofd == -1) {
573 ec = error_code(errno, system_category());
574 return;
575 }
576
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000577 ec = init(ofd, true, offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000578 if (ec)
579 Mapping = 0;
580}
581
582mapped_file_region::mapped_file_region(int fd,
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000583 bool closefd,
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000584 mapmode mode,
585 uint64_t length,
586 uint64_t offset,
587 error_code &ec)
588 : Mode(mode)
589 , Size(length)
590 , Mapping() {
591 // Make sure that the requested size fits within SIZE_T.
592 if (length > std::numeric_limits<size_t>::max()) {
593 ec = make_error_code(errc::invalid_argument);
594 return;
595 }
596
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000597 ec = init(fd, closefd, offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000598 if (ec)
599 Mapping = 0;
600}
601
602mapped_file_region::~mapped_file_region() {
603 if (Mapping)
604 ::munmap(Mapping, Size);
605}
606
Chandler Carruthf12e3a62012-11-30 11:45:22 +0000607#if LLVM_HAS_RVALUE_REFERENCES
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000608mapped_file_region::mapped_file_region(mapped_file_region &&other)
609 : Mode(other.Mode), Size(other.Size), Mapping(other.Mapping) {
610 other.Mapping = 0;
611}
612#endif
613
614mapped_file_region::mapmode mapped_file_region::flags() const {
615 assert(Mapping && "Mapping failed but used anyway!");
616 return Mode;
617}
618
619uint64_t mapped_file_region::size() const {
620 assert(Mapping && "Mapping failed but used anyway!");
621 return Size;
622}
623
624char *mapped_file_region::data() const {
625 assert(Mapping && "Mapping failed but used anyway!");
626 assert(Mode != readonly && "Cannot get non const data for readonly mapping!");
627 return reinterpret_cast<char*>(Mapping);
628}
629
630const char *mapped_file_region::const_data() const {
631 assert(Mapping && "Mapping failed but used anyway!");
632 return reinterpret_cast<const char*>(Mapping);
633}
634
635int mapped_file_region::alignment() {
Chandler Carruthacd64be2012-12-31 23:31:56 +0000636 return process::get_self()->page_size();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000637}
638
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000639error_code detail::directory_iterator_construct(detail::DirIterState &it,
640 StringRef path){
Michael J. Spencer52714862011-01-05 16:38:57 +0000641 SmallString<128> path_null(path);
642 DIR *directory = ::opendir(path_null.c_str());
643 if (directory == 0)
644 return error_code(errno, system_category());
645
646 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
647 // Add something for replace_filename to replace.
648 path::append(path_null, ".");
649 it.CurrentEntry = directory_entry(path_null.str());
650 return directory_iterator_increment(it);
651}
652
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000653error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000654 if (it.IterationHandle)
655 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
656 it.IterationHandle = 0;
657 it.CurrentEntry = directory_entry();
David Blaikie18544b92012-02-09 19:24:12 +0000658 return error_code::success();
Michael J. Spencer52714862011-01-05 16:38:57 +0000659}
660
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000661error_code detail::directory_iterator_increment(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000662 errno = 0;
663 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
664 if (cur_dir == 0 && errno != 0) {
665 return error_code(errno, system_category());
666 } else if (cur_dir != 0) {
667 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
668 if ((name.size() == 1 && name[0] == '.') ||
669 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
670 return directory_iterator_increment(it);
671 it.CurrentEntry.replace_filename(name);
672 } else
673 return directory_iterator_destruct(it);
674
David Blaikie18544b92012-02-09 19:24:12 +0000675 return error_code::success();
Michael J. Spencer52714862011-01-05 16:38:57 +0000676}
677
Michael J. Spenceree1699c2011-01-15 18:52:33 +0000678error_code get_magic(const Twine &path, uint32_t len,
679 SmallVectorImpl<char> &result) {
680 SmallString<128> PathStorage;
681 StringRef Path = path.toNullTerminatedStringRef(PathStorage);
682 result.set_size(0);
683
684 // Open path.
685 std::FILE *file = std::fopen(Path.data(), "rb");
686 if (file == 0)
687 return error_code(errno, system_category());
688
689 // Reserve storage.
690 result.reserve(len);
691
692 // Read magic!
693 size_t size = std::fread(result.data(), 1, len, file);
694 if (std::ferror(file) != 0) {
695 std::fclose(file);
696 return error_code(errno, system_category());
Evgeniy Stepanov6eb44842013-06-20 15:56:05 +0000697 } else if (size != len) {
Michael J. Spenceree1699c2011-01-15 18:52:33 +0000698 if (std::feof(file) != 0) {
699 std::fclose(file);
700 result.set_size(size);
701 return make_error_code(errc::value_too_large);
702 }
703 }
704 std::fclose(file);
Evgeniy Stepanov6eb44842013-06-20 15:56:05 +0000705 result.set_size(size);
David Blaikie18544b92012-02-09 19:24:12 +0000706 return error_code::success();
Michael J. Spenceree1699c2011-01-15 18:52:33 +0000707}
708
Nick Kledzik18497e92012-06-20 00:28:54 +0000709error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
710 bool map_writable, void *&result) {
711 SmallString<128> path_storage;
712 StringRef name = path.toNullTerminatedStringRef(path_storage);
713 int oflags = map_writable ? O_RDWR : O_RDONLY;
714 int ofd = ::open(name.begin(), oflags);
715 if ( ofd == -1 )
716 return error_code(errno, system_category());
717 AutoFD fd(ofd);
718 int flags = map_writable ? MAP_SHARED : MAP_PRIVATE;
719 int prot = map_writable ? (PROT_READ|PROT_WRITE) : PROT_READ;
720#ifdef MAP_FILE
721 flags |= MAP_FILE;
722#endif
723 result = ::mmap(0, size, prot, flags, fd, file_offset);
724 if (result == MAP_FAILED) {
725 return error_code(errno, system_category());
726 }
727
728 return error_code::success();
729}
730
731error_code unmap_file_pages(void *base, size_t size) {
732 if ( ::munmap(base, size) == -1 )
733 return error_code(errno, system_category());
734
735 return error_code::success();
736}
737
738
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000739} // end namespace fs
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000740} // end namespace sys
741} // end namespace llvm