blob: b036c74ad1657d004a132221f2fdf24616a2d3d8 [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
Rafael Espindolabe3ede72013-06-20 21:51:49 +0000113TimeValue file_status::getLastModificationTime() const {
Rafael Espindoladb5d8fe2013-06-20 18:42:04 +0000114 TimeValue Ret;
115 Ret.fromEpochTime(fs_st_mtime);
116 return Ret;
117}
118
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000119error_code current_path(SmallVectorImpl<char> &result) {
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000120#ifdef MAXPATHLEN
Andrew Tricka4ec5b22011-03-24 16:43:37 +0000121 result.reserve(MAXPATHLEN);
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000122#else
123// For GNU Hurd
124 result.reserve(1024);
125#endif
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000126
Michael J. Spencer20daa282010-12-07 01:22:31 +0000127 while (true) {
128 if (::getcwd(result.data(), result.capacity()) == 0) {
129 // See if there was a real error.
130 if (errno != errc::not_enough_memory)
131 return error_code(errno, system_category());
132 // Otherwise there just wasn't enough space.
133 result.reserve(result.capacity() * 2);
134 } else
135 break;
136 }
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000137
138 result.set_size(strlen(result.data()));
David Blaikie18544b92012-02-09 19:24:12 +0000139 return error_code::success();
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000140}
141
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000142error_code copy_file(const Twine &from, const Twine &to, copy_option copt) {
143 // Get arguments.
144 SmallString<128> from_storage;
145 SmallString<128> to_storage;
Michael J. Spencer795adf52010-12-01 20:37:42 +0000146 StringRef f = from.toNullTerminatedStringRef(from_storage);
147 StringRef t = to.toNullTerminatedStringRef(to_storage);
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000148
149 const size_t buf_sz = 32768;
150 char buffer[buf_sz];
151 int from_file = -1, to_file = -1;
152
153 // Open from.
154 if ((from_file = ::open(f.begin(), O_RDONLY)) < 0)
155 return error_code(errno, system_category());
156 AutoFD from_fd(from_file);
157
158 // Stat from.
159 struct stat from_stat;
160 if (::stat(f.begin(), &from_stat) != 0)
161 return error_code(errno, system_category());
162
163 // Setup to flags.
164 int to_flags = O_CREAT | O_WRONLY;
165 if (copt == copy_option::fail_if_exists)
166 to_flags |= O_EXCL;
167
168 // Open to.
169 if ((to_file = ::open(t.begin(), to_flags, from_stat.st_mode)) < 0)
170 return error_code(errno, system_category());
171 AutoFD to_fd(to_file);
172
173 // Copy!
174 ssize_t sz, sz_read = 1, sz_write;
175 while (sz_read > 0 &&
176 (sz_read = ::read(from_fd, buffer, buf_sz)) > 0) {
177 // Allow for partial writes - see Advanced Unix Programming (2nd Ed.),
178 // Marc Rochkind, Addison-Wesley, 2004, page 94
179 sz_write = 0;
180 do {
181 if ((sz = ::write(to_fd, buffer + sz_write, sz_read - sz_write)) < 0) {
182 sz_read = sz; // cause read loop termination.
183 break; // error.
184 }
185 sz_write += sz;
186 } while (sz_write < sz_read);
187 }
188
189 // After all the file operations above the return value of close actually
190 // matters.
191 if (::close(from_fd.take()) < 0) sz_read = -1;
192 if (::close(to_fd.take()) < 0) sz_read = -1;
193
194 // Check for errors.
195 if (sz_read < 0)
196 return error_code(errno, system_category());
197
David Blaikie18544b92012-02-09 19:24:12 +0000198 return error_code::success();
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000199}
200
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000201error_code create_directory(const Twine &path, bool &existed) {
202 SmallString<128> path_storage;
203 StringRef p = path.toNullTerminatedStringRef(path_storage);
204
Michael J. Spencere5755be2010-12-07 01:23:29 +0000205 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
Michael J. Spencer66a1f862010-12-04 18:45:32 +0000206 if (errno != errc::file_exists)
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000207 return error_code(errno, system_category());
208 existed = true;
209 } else
210 existed = false;
211
David Blaikie18544b92012-02-09 19:24:12 +0000212 return error_code::success();
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000213}
214
Michael J. Spencere0c45602010-12-03 05:58:41 +0000215error_code create_hard_link(const Twine &to, const Twine &from) {
216 // Get arguments.
217 SmallString<128> from_storage;
218 SmallString<128> to_storage;
219 StringRef f = from.toNullTerminatedStringRef(from_storage);
220 StringRef t = to.toNullTerminatedStringRef(to_storage);
221
222 if (::link(t.begin(), f.begin()) == -1)
223 return error_code(errno, system_category());
224
David Blaikie18544b92012-02-09 19:24:12 +0000225 return error_code::success();
Michael J. Spencere0c45602010-12-03 05:58:41 +0000226}
227
Michael J. Spencer7ee6d5d2010-12-03 07:41:25 +0000228error_code create_symlink(const Twine &to, const Twine &from) {
229 // Get arguments.
230 SmallString<128> from_storage;
231 SmallString<128> to_storage;
232 StringRef f = from.toNullTerminatedStringRef(from_storage);
233 StringRef t = to.toNullTerminatedStringRef(to_storage);
234
235 if (::symlink(t.begin(), f.begin()) == -1)
236 return error_code(errno, system_category());
237
David Blaikie18544b92012-02-09 19:24:12 +0000238 return error_code::success();
Michael J. Spencer7ee6d5d2010-12-03 07:41:25 +0000239}
240
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000241error_code remove(const Twine &path, bool &existed) {
242 SmallString<128> path_storage;
243 StringRef p = path.toNullTerminatedStringRef(path_storage);
244
Rafael Espindola8cd62b02013-06-17 20:35:51 +0000245 struct stat buf;
246 if (stat(p.begin(), &buf) != 0) {
247 if (errno != errc::no_such_file_or_directory)
248 return error_code(errno, system_category());
249 existed = false;
250 return error_code::success();
251 }
252
253 // Note: this check catches strange situations. In all cases, LLVM should
254 // only be involved in the creation and deletion of regular files. This
255 // check ensures that what we're trying to erase is a regular file. It
256 // effectively prevents LLVM from erasing things like /dev/null, any block
257 // special file, or other things that aren't "regular" files.
258 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode))
259 return make_error_code(errc::operation_not_permitted);
260
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000261 if (::remove(p.begin()) == -1) {
Michael J. Spencer66a1f862010-12-04 18:45:32 +0000262 if (errno != errc::no_such_file_or_directory)
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000263 return error_code(errno, system_category());
264 existed = false;
265 } else
266 existed = true;
267
David Blaikie18544b92012-02-09 19:24:12 +0000268 return error_code::success();
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000269}
270
Michael J. Spencer409f5562010-12-03 17:53:55 +0000271error_code rename(const Twine &from, const Twine &to) {
272 // Get arguments.
273 SmallString<128> from_storage;
274 SmallString<128> to_storage;
275 StringRef f = from.toNullTerminatedStringRef(from_storage);
276 StringRef t = to.toNullTerminatedStringRef(to_storage);
277
Michael J. Spencerec202ee2011-01-16 22:18:41 +0000278 if (::rename(f.begin(), t.begin()) == -1) {
279 // If it's a cross device link, copy then delete, otherwise return the error
280 if (errno == EXDEV) {
281 if (error_code ec = copy_file(from, to, copy_option::overwrite_if_exists))
282 return ec;
283 bool Existed;
284 if (error_code ec = remove(from, Existed))
285 return ec;
286 } else
287 return error_code(errno, system_category());
288 }
Michael J. Spencer409f5562010-12-03 17:53:55 +0000289
David Blaikie18544b92012-02-09 19:24:12 +0000290 return error_code::success();
Michael J. Spencer409f5562010-12-03 17:53:55 +0000291}
292
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000293error_code resize_file(const Twine &path, uint64_t size) {
294 SmallString<128> path_storage;
295 StringRef p = path.toNullTerminatedStringRef(path_storage);
296
297 if (::truncate(p.begin(), size) == -1)
298 return error_code(errno, system_category());
299
David Blaikie18544b92012-02-09 19:24:12 +0000300 return error_code::success();
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000301}
302
Michael J. Spencer45710402010-12-03 01:21:28 +0000303error_code exists(const Twine &path, bool &result) {
304 SmallString<128> path_storage;
305 StringRef p = path.toNullTerminatedStringRef(path_storage);
306
Benjamin Kramer172f8082012-06-02 16:28:09 +0000307 if (::access(p.begin(), F_OK) == -1) {
Michael J. Spencer66a1f862010-12-04 18:45:32 +0000308 if (errno != errc::no_such_file_or_directory)
Michael J. Spencer45710402010-12-03 01:21:28 +0000309 return error_code(errno, system_category());
310 result = false;
311 } else
312 result = true;
313
David Blaikie18544b92012-02-09 19:24:12 +0000314 return error_code::success();
Michael J. Spencer45710402010-12-03 01:21:28 +0000315}
316
Rafael Espindolaa1280c12013-06-18 20:56:38 +0000317bool can_write(const Twine &Path) {
318 SmallString<128> PathStorage;
319 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
320 return 0 == access(P.begin(), W_OK);
321}
322
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000323bool can_execute(const Twine &Path) {
324 SmallString<128> PathStorage;
325 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
326
Manuel Klimek52772bf2013-06-17 10:48:34 +0000327 if (0 != access(P.begin(), R_OK | X_OK))
328 return false;
329 struct stat buf;
330 if (0 != stat(P.begin(), &buf))
331 return false;
332 if (!S_ISREG(buf.st_mode))
333 return false;
334 return true;
Rafael Espindolab0a5c962013-06-14 19:38:45 +0000335}
336
Michael J. Spencer203d7802011-12-12 06:04:28 +0000337bool equivalent(file_status A, file_status B) {
338 assert(status_known(A) && status_known(B));
Sylvestre Ledru3099f4bd2012-04-23 16:37:23 +0000339 return A.fs_st_dev == B.fs_st_dev &&
340 A.fs_st_ino == B.fs_st_ino;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000341}
342
Michael J. Spencer376d3872010-12-03 18:49:13 +0000343error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000344 file_status fsA, fsB;
345 if (error_code ec = status(A, fsA)) return ec;
346 if (error_code ec = status(B, fsB)) return ec;
347 result = equivalent(fsA, fsB);
David Blaikie18544b92012-02-09 19:24:12 +0000348 return error_code::success();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000349}
350
Michael J. Spencer818ab4a2010-12-04 00:31:48 +0000351error_code file_size(const Twine &path, uint64_t &result) {
352 SmallString<128> path_storage;
353 StringRef p = path.toNullTerminatedStringRef(path_storage);
354
355 struct stat status;
356 if (::stat(p.begin(), &status) == -1)
357 return error_code(errno, system_category());
358 if (!S_ISREG(status.st_mode))
Michael J. Spencer66a1f862010-12-04 18:45:32 +0000359 return make_error_code(errc::operation_not_permitted);
Michael J. Spencer818ab4a2010-12-04 00:31:48 +0000360
361 result = status.st_size;
David Blaikie18544b92012-02-09 19:24:12 +0000362 return error_code::success();
Michael J. Spencer818ab4a2010-12-04 00:31:48 +0000363}
364
Rafael Espindola7cf7c512013-06-20 15:06:35 +0000365error_code getUniqueID(const Twine Path, uint64_t &Result) {
Rafael Espindola45e6c242013-06-18 19:34:49 +0000366 SmallString<128> Storage;
367 StringRef P = Path.toNullTerminatedStringRef(Storage);
368
369 struct stat Status;
370 if (::stat(P.begin(), &Status) != 0)
371 return error_code(errno, system_category());
372
373 Result = Status.st_ino;
374 return error_code::success();
375}
376
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000377error_code status(const Twine &path, file_status &result) {
378 SmallString<128> path_storage;
379 StringRef p = path.toNullTerminatedStringRef(path_storage);
380
381 struct stat status;
382 if (::stat(p.begin(), &status) != 0) {
383 error_code ec(errno, system_category());
384 if (ec == errc::no_such_file_or_directory)
385 result = file_status(file_type::file_not_found);
386 else
387 result = file_status(file_type::status_error);
388 return ec;
389 }
390
Nick Kledzik18497e92012-06-20 00:28:54 +0000391 perms prms = static_cast<perms>(status.st_mode & perms_mask);
392
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000393 if (S_ISDIR(status.st_mode))
Nick Kledzik18497e92012-06-20 00:28:54 +0000394 result = file_status(file_type::directory_file, prms);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000395 else if (S_ISREG(status.st_mode))
Nick Kledzik18497e92012-06-20 00:28:54 +0000396 result = file_status(file_type::regular_file, prms);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000397 else if (S_ISBLK(status.st_mode))
Nick Kledzik18497e92012-06-20 00:28:54 +0000398 result = file_status(file_type::block_file, prms);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000399 else if (S_ISCHR(status.st_mode))
Nick Kledzik18497e92012-06-20 00:28:54 +0000400 result = file_status(file_type::character_file, prms);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000401 else if (S_ISFIFO(status.st_mode))
Nick Kledzik18497e92012-06-20 00:28:54 +0000402 result = file_status(file_type::fifo_file, prms);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000403 else if (S_ISSOCK(status.st_mode))
Nick Kledzik18497e92012-06-20 00:28:54 +0000404 result = file_status(file_type::socket_file, prms);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000405 else
Nick Kledzik18497e92012-06-20 00:28:54 +0000406 result = file_status(file_type::type_unknown, prms);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000407
Sylvestre Ledru3099f4bd2012-04-23 16:37:23 +0000408 result.fs_st_dev = status.st_dev;
409 result.fs_st_ino = status.st_ino;
Rafael Espindoladb5d8fe2013-06-20 18:42:04 +0000410 result.fs_st_mtime = status.st_mtime;
Rafael Espindolae34d6a52013-06-20 22:02:10 +0000411 result.fs_st_uid = status.st_uid;
412 result.fs_st_gid = status.st_gid;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000413
David Blaikie18544b92012-02-09 19:24:12 +0000414 return error_code::success();
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000415}
416
Nick Kledzik18497e92012-06-20 00:28:54 +0000417// Modifies permissions on a file.
418error_code permissions(const Twine &path, perms prms) {
419 if ((prms & add_perms) && (prms & remove_perms))
420 llvm_unreachable("add_perms and remove_perms are mutually exclusive");
421
422 // Get current permissions
423 file_status info;
424 if (error_code ec = status(path, info)) {
425 return ec;
426 }
427
428 // Set updated permissions.
429 SmallString<128> path_storage;
430 StringRef p = path.toNullTerminatedStringRef(path_storage);
431 perms permsToSet;
432 if (prms & add_perms) {
433 permsToSet = (info.permissions() | prms) & perms_mask;
434 } else if (prms & remove_perms) {
435 permsToSet = (info.permissions() & ~prms) & perms_mask;
436 } else {
437 permsToSet = prms & perms_mask;
438 }
439 if (::chmod(p.begin(), static_cast<mode_t>(permsToSet))) {
440 return error_code(errno, system_category());
441 }
442
443 return error_code::success();
444}
445
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000446error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
447 timeval Times[2];
448 Times[0].tv_sec = Time.toPosixTime();
449 Times[0].tv_usec = 0;
450 Times[1] = Times[0];
451 if (::futimes(FD, Times))
452 return error_code(errno, system_category());
453 return error_code::success();
454}
455
Eric Christopherb6148ed2012-05-11 00:07:44 +0000456// Since this is most often used for temporary files, mode defaults to 0600.
Michael J. Spencer45710402010-12-03 01:21:28 +0000457error_code unique_file(const Twine &model, int &result_fd,
Eric Christopherb6148ed2012-05-11 00:07:44 +0000458 SmallVectorImpl<char> &result_path,
459 bool makeAbsolute, unsigned mode) {
Michael J. Spencer45710402010-12-03 01:21:28 +0000460 SmallString<128> Model;
461 model.toVector(Model);
462 // Null terminate.
463 Model.c_str();
464
Argyrios Kyrtzidis348937d2011-07-28 00:29:20 +0000465 if (makeAbsolute) {
466 // Make model absolute by prepending a temp directory if it's not already.
467 bool absolute = path::is_absolute(Twine(Model));
468 if (!absolute) {
469 SmallString<128> TDir;
470 if (error_code ec = TempDir(TDir)) return ec;
471 path::append(TDir, Twine(Model));
472 Model.swap(TDir);
473 }
Michael J. Spencer45710402010-12-03 01:21:28 +0000474 }
475
Daniel Dunbar58ed0c62012-05-05 16:39:22 +0000476 // From here on, DO NOT modify model. It may be needed if the randomly chosen
477 // path already exists.
Daniel Dunbar3f0fa192012-05-05 16:36:24 +0000478 SmallString<128> RandomPath = Model;
Michael J. Spencer45710402010-12-03 01:21:28 +0000479
480retry_random_path:
Daniel Dunbar58ed0c62012-05-05 16:39:22 +0000481 // Replace '%' with random chars.
Daniel Dunbar3f0fa192012-05-05 16:36:24 +0000482 for (unsigned i = 0, e = Model.size(); i != e; ++i) {
483 if (Model[i] == '%')
484 RandomPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
Michael J. Spencer45710402010-12-03 01:21:28 +0000485 }
486
Argyrios Kyrtzidiseed2dc52013-02-28 00:38:19 +0000487 // Make sure we don't fall into an infinite loop by constantly trying
488 // to create the parent path.
489 bool TriedToCreateParent = false;
490
Michael J. Spencer45710402010-12-03 01:21:28 +0000491 // Try to open + create the file.
492rety_open_create:
Eric Christopherb6148ed2012-05-11 00:07:44 +0000493 int RandomFD = ::open(RandomPath.c_str(), O_RDWR | O_CREAT | O_EXCL, mode);
Michael J. Spencer45710402010-12-03 01:21:28 +0000494 if (RandomFD == -1) {
Douglas Gregor95585ab2013-01-10 01:58:46 +0000495 int SavedErrno = errno;
Michael J. Spencer45710402010-12-03 01:21:28 +0000496 // If the file existed, try again, otherwise, error.
Douglas Gregor95585ab2013-01-10 01:58:46 +0000497 if (SavedErrno == errc::file_exists)
Michael J. Spencer45710402010-12-03 01:21:28 +0000498 goto retry_random_path;
Daniel Dunbar61d59f22012-11-15 20:24:52 +0000499 // If path prefix doesn't exist, try to create it.
Douglas Gregor6bd4d8c2013-04-05 20:48:36 +0000500 if (SavedErrno == errc::no_such_file_or_directory && !TriedToCreateParent) {
Argyrios Kyrtzidiseed2dc52013-02-28 00:38:19 +0000501 TriedToCreateParent = true;
Daniel Dunbar61d59f22012-11-15 20:24:52 +0000502 StringRef p(RandomPath);
Michael J. Spencer45710402010-12-03 01:21:28 +0000503 SmallString<64> dir_to_create;
504 for (path::const_iterator i = path::begin(p),
505 e = --path::end(p); i != e; ++i) {
Michael J. Spencer1e090f02010-12-07 03:57:37 +0000506 path::append(dir_to_create, *i);
Michael J. Spencer45710402010-12-03 01:21:28 +0000507 bool Exists;
508 if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
509 if (!Exists) {
510 // Don't try to create network paths.
511 if (i->size() > 2 && (*i)[0] == '/' &&
512 (*i)[1] == '/' &&
513 (*i)[2] != '/')
Michael J. Spencer66a1f862010-12-04 18:45:32 +0000514 return make_error_code(errc::no_such_file_or_directory);
Douglas Gregor95585ab2013-01-10 01:58:46 +0000515 if (::mkdir(dir_to_create.c_str(), 0700) == -1 &&
516 errno != errc::file_exists)
Michael J. Spencer45710402010-12-03 01:21:28 +0000517 return error_code(errno, system_category());
518 }
519 }
520 goto rety_open_create;
521 }
Douglas Gregor95585ab2013-01-10 01:58:46 +0000522
523 return error_code(SavedErrno, system_category());
Michael J. Spencer45710402010-12-03 01:21:28 +0000524 }
525
Michael J. Spencer66a1f862010-12-04 18:45:32 +0000526 // Make the path absolute.
Andrew Tricka4ec5b22011-03-24 16:43:37 +0000527 char real_path_buff[PATH_MAX + 1];
528 if (realpath(RandomPath.c_str(), real_path_buff) == NULL) {
529 int error = errno;
Michael J. Spencer45710402010-12-03 01:21:28 +0000530 ::close(RandomFD);
531 ::unlink(RandomPath.c_str());
Andrew Tricka4ec5b22011-03-24 16:43:37 +0000532 return error_code(error, system_category());
Michael J. Spencer45710402010-12-03 01:21:28 +0000533 }
534
Andrew Tricka4ec5b22011-03-24 16:43:37 +0000535 result_path.clear();
536 StringRef d(real_path_buff);
537 result_path.append(d.begin(), d.end());
538
Michael J. Spencer45710402010-12-03 01:21:28 +0000539 result_fd = RandomFD;
David Blaikie18544b92012-02-09 19:24:12 +0000540 return error_code::success();
Michael J. Spencer45710402010-12-03 01:21:28 +0000541}
542
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000543error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
544 AutoFD ScopedFD(FD);
545 if (!CloseFD)
546 ScopedFD.take();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000547
548 // Figure out how large the file is.
549 struct stat FileInfo;
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000550 if (fstat(FD, &FileInfo) == -1)
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000551 return error_code(errno, system_category());
552 uint64_t FileSize = FileInfo.st_size;
553
554 if (Size == 0)
555 Size = FileSize;
556 else if (FileSize < Size) {
557 // We need to grow the file.
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000558 if (ftruncate(FD, Size) == -1)
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000559 return error_code(errno, system_category());
560 }
561
562 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
563 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
564#ifdef MAP_FILE
565 flags |= MAP_FILE;
566#endif
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000567 Mapping = ::mmap(0, Size, prot, flags, FD, Offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000568 if (Mapping == MAP_FAILED)
569 return error_code(errno, system_category());
570 return error_code::success();
571}
572
573mapped_file_region::mapped_file_region(const Twine &path,
574 mapmode mode,
575 uint64_t length,
576 uint64_t offset,
577 error_code &ec)
578 : Mode(mode)
579 , Size(length)
580 , Mapping() {
581 // Make sure that the requested size fits within SIZE_T.
582 if (length > std::numeric_limits<size_t>::max()) {
583 ec = make_error_code(errc::invalid_argument);
584 return;
585 }
586
587 SmallString<128> path_storage;
588 StringRef name = path.toNullTerminatedStringRef(path_storage);
589 int oflags = (mode == readonly) ? O_RDONLY : O_RDWR;
590 int ofd = ::open(name.begin(), oflags);
591 if (ofd == -1) {
592 ec = error_code(errno, system_category());
593 return;
594 }
595
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000596 ec = init(ofd, true, offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000597 if (ec)
598 Mapping = 0;
599}
600
601mapped_file_region::mapped_file_region(int fd,
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000602 bool closefd,
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000603 mapmode mode,
604 uint64_t length,
605 uint64_t offset,
606 error_code &ec)
607 : Mode(mode)
608 , Size(length)
609 , Mapping() {
610 // Make sure that the requested size fits within SIZE_T.
611 if (length > std::numeric_limits<size_t>::max()) {
612 ec = make_error_code(errc::invalid_argument);
613 return;
614 }
615
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000616 ec = init(fd, closefd, offset);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000617 if (ec)
618 Mapping = 0;
619}
620
621mapped_file_region::~mapped_file_region() {
622 if (Mapping)
623 ::munmap(Mapping, Size);
624}
625
Chandler Carruthf12e3a62012-11-30 11:45:22 +0000626#if LLVM_HAS_RVALUE_REFERENCES
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000627mapped_file_region::mapped_file_region(mapped_file_region &&other)
628 : Mode(other.Mode), Size(other.Size), Mapping(other.Mapping) {
629 other.Mapping = 0;
630}
631#endif
632
633mapped_file_region::mapmode mapped_file_region::flags() const {
634 assert(Mapping && "Mapping failed but used anyway!");
635 return Mode;
636}
637
638uint64_t mapped_file_region::size() const {
639 assert(Mapping && "Mapping failed but used anyway!");
640 return Size;
641}
642
643char *mapped_file_region::data() const {
644 assert(Mapping && "Mapping failed but used anyway!");
645 assert(Mode != readonly && "Cannot get non const data for readonly mapping!");
646 return reinterpret_cast<char*>(Mapping);
647}
648
649const char *mapped_file_region::const_data() const {
650 assert(Mapping && "Mapping failed but used anyway!");
651 return reinterpret_cast<const char*>(Mapping);
652}
653
654int mapped_file_region::alignment() {
Chandler Carruthacd64be2012-12-31 23:31:56 +0000655 return process::get_self()->page_size();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000656}
657
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000658error_code detail::directory_iterator_construct(detail::DirIterState &it,
659 StringRef path){
Michael J. Spencer52714862011-01-05 16:38:57 +0000660 SmallString<128> path_null(path);
661 DIR *directory = ::opendir(path_null.c_str());
662 if (directory == 0)
663 return error_code(errno, system_category());
664
665 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
666 // Add something for replace_filename to replace.
667 path::append(path_null, ".");
668 it.CurrentEntry = directory_entry(path_null.str());
669 return directory_iterator_increment(it);
670}
671
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000672error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000673 if (it.IterationHandle)
674 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
675 it.IterationHandle = 0;
676 it.CurrentEntry = directory_entry();
David Blaikie18544b92012-02-09 19:24:12 +0000677 return error_code::success();
Michael J. Spencer52714862011-01-05 16:38:57 +0000678}
679
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000680error_code detail::directory_iterator_increment(detail::DirIterState &it) {
Michael J. Spencer52714862011-01-05 16:38:57 +0000681 errno = 0;
682 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
683 if (cur_dir == 0 && errno != 0) {
684 return error_code(errno, system_category());
685 } else if (cur_dir != 0) {
686 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
687 if ((name.size() == 1 && name[0] == '.') ||
688 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
689 return directory_iterator_increment(it);
690 it.CurrentEntry.replace_filename(name);
691 } else
692 return directory_iterator_destruct(it);
693
David Blaikie18544b92012-02-09 19:24:12 +0000694 return error_code::success();
Michael J. Spencer52714862011-01-05 16:38:57 +0000695}
696
Michael J. Spenceree1699c2011-01-15 18:52:33 +0000697error_code get_magic(const Twine &path, uint32_t len,
698 SmallVectorImpl<char> &result) {
699 SmallString<128> PathStorage;
700 StringRef Path = path.toNullTerminatedStringRef(PathStorage);
701 result.set_size(0);
702
703 // Open path.
704 std::FILE *file = std::fopen(Path.data(), "rb");
705 if (file == 0)
706 return error_code(errno, system_category());
707
708 // Reserve storage.
709 result.reserve(len);
710
711 // Read magic!
712 size_t size = std::fread(result.data(), 1, len, file);
713 if (std::ferror(file) != 0) {
714 std::fclose(file);
715 return error_code(errno, system_category());
Evgeniy Stepanov6eb44842013-06-20 15:56:05 +0000716 } else if (size != len) {
Michael J. Spenceree1699c2011-01-15 18:52:33 +0000717 if (std::feof(file) != 0) {
718 std::fclose(file);
719 result.set_size(size);
720 return make_error_code(errc::value_too_large);
721 }
722 }
723 std::fclose(file);
Evgeniy Stepanov6eb44842013-06-20 15:56:05 +0000724 result.set_size(size);
David Blaikie18544b92012-02-09 19:24:12 +0000725 return error_code::success();
Michael J. Spenceree1699c2011-01-15 18:52:33 +0000726}
727
Nick Kledzik18497e92012-06-20 00:28:54 +0000728error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
729 bool map_writable, void *&result) {
730 SmallString<128> path_storage;
731 StringRef name = path.toNullTerminatedStringRef(path_storage);
732 int oflags = map_writable ? O_RDWR : O_RDONLY;
733 int ofd = ::open(name.begin(), oflags);
734 if ( ofd == -1 )
735 return error_code(errno, system_category());
736 AutoFD fd(ofd);
737 int flags = map_writable ? MAP_SHARED : MAP_PRIVATE;
738 int prot = map_writable ? (PROT_READ|PROT_WRITE) : PROT_READ;
739#ifdef MAP_FILE
740 flags |= MAP_FILE;
741#endif
742 result = ::mmap(0, size, prot, flags, fd, file_offset);
743 if (result == MAP_FAILED) {
744 return error_code(errno, system_category());
745 }
746
747 return error_code::success();
748}
749
750error_code unmap_file_pages(void *base, size_t size) {
751 if ( ::munmap(base, size) == -1 )
752 return error_code(errno, system_category());
753
754 return error_code::success();
755}
756
757
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000758} // end namespace fs
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000759} // end namespace sys
760} // end namespace llvm