/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Support/Unix/Path.inc
Line | Count | Source (jump to first uncovered line) |
1 | | //===- llvm/Support/Unix/Path.inc - Unix Path Implementation ----*- C++ -*-===// |
2 | | // |
3 | | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | | // See https://llvm.org/LICENSE.txt for license information. |
5 | | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | | // |
7 | | //===----------------------------------------------------------------------===// |
8 | | // |
9 | | // This file implements the Unix specific implementation of the Path API. |
10 | | // |
11 | | //===----------------------------------------------------------------------===// |
12 | | |
13 | | //===----------------------------------------------------------------------===// |
14 | | //=== WARNING: Implementation here must contain only generic UNIX code that |
15 | | //=== is guaranteed to work on *all* UNIX variants. |
16 | | //===----------------------------------------------------------------------===// |
17 | | |
18 | | #include "Unix.h" |
19 | | #include <limits.h> |
20 | | #include <stdio.h> |
21 | | #if HAVE_SYS_STAT_H |
22 | | #include <sys/stat.h> |
23 | | #endif |
24 | | #if HAVE_FCNTL_H |
25 | | #include <fcntl.h> |
26 | | #endif |
27 | | #ifdef HAVE_UNISTD_H |
28 | | #include <unistd.h> |
29 | | #endif |
30 | | #ifdef HAVE_SYS_MMAN_H |
31 | | #include <sys/mman.h> |
32 | | #endif |
33 | | |
34 | | #include <dirent.h> |
35 | | #include <pwd.h> |
36 | | |
37 | | #ifdef __APPLE__ |
38 | | #include <mach-o/dyld.h> |
39 | | #include <sys/attr.h> |
40 | | #include <copyfile.h> |
41 | | #elif defined(__DragonFly__) |
42 | | #include <sys/mount.h> |
43 | | #endif |
44 | | |
45 | | // Both stdio.h and cstdio are included via different paths and |
46 | | // stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros |
47 | | // either. |
48 | | #undef ferror |
49 | | #undef feof |
50 | | |
51 | | // For GNU Hurd |
52 | | #if defined(__GNU__) && !defined(PATH_MAX) |
53 | | # define PATH_MAX 4096 |
54 | | # define MAXPATHLEN 4096 |
55 | | #endif |
56 | | |
57 | | #include <sys/types.h> |
58 | | #if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && \ |
59 | | !defined(__linux__) && !defined(__FreeBSD_kernel__) && !defined(_AIX) |
60 | | #include <sys/statvfs.h> |
61 | | #define STATVFS statvfs |
62 | | #define FSTATVFS fstatvfs |
63 | | #define STATVFS_F_FRSIZE(vfs) vfs.f_frsize |
64 | | #else |
65 | | #if defined(__OpenBSD__) || defined(__FreeBSD__) |
66 | | #include <sys/mount.h> |
67 | | #include <sys/param.h> |
68 | | #elif defined(__linux__) |
69 | | #if defined(HAVE_LINUX_MAGIC_H) |
70 | | #include <linux/magic.h> |
71 | | #else |
72 | | #if defined(HAVE_LINUX_NFS_FS_H) |
73 | | #include <linux/nfs_fs.h> |
74 | | #endif |
75 | | #if defined(HAVE_LINUX_SMB_H) |
76 | | #include <linux/smb.h> |
77 | | #endif |
78 | | #endif |
79 | | #include <sys/vfs.h> |
80 | | #elif defined(_AIX) |
81 | | #include <sys/statfs.h> |
82 | | |
83 | | // <sys/vmount.h> depends on `uint` to be a typedef from <sys/types.h> to |
84 | | // `uint_t`; however, <sys/types.h> does not always declare `uint`. We provide |
85 | | // the typedef prior to including <sys/vmount.h> to work around this issue. |
86 | | typedef uint_t uint; |
87 | | #include <sys/vmount.h> |
88 | | #else |
89 | | #include <sys/mount.h> |
90 | | #endif |
91 | 22 | #define STATVFS statfs |
92 | 2 | #define FSTATVFS fstatfs |
93 | 20 | #define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize) |
94 | | #endif |
95 | | |
96 | | #if defined(__NetBSD__) || defined(__DragonFly__) || defined(__GNU__) |
97 | | #define STATVFS_F_FLAG(vfs) (vfs).f_flag |
98 | | #else |
99 | 4 | #define STATVFS_F_FLAG(vfs) (vfs).f_flags |
100 | | #endif |
101 | | |
102 | | using namespace llvm; |
103 | | |
104 | | namespace llvm { |
105 | | namespace sys { |
106 | | namespace fs { |
107 | | |
108 | | const file_t kInvalidFile = -1; |
109 | | |
110 | | #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \ |
111 | | defined(__minix) || defined(__FreeBSD_kernel__) || defined(__linux__) || \ |
112 | | defined(__CYGWIN__) || defined(__DragonFly__) || defined(_AIX) || defined(__GNU__) |
113 | | static int |
114 | | test_dir(char ret[PATH_MAX], const char *dir, const char *bin) |
115 | | { |
116 | | struct stat sb; |
117 | | char fullpath[PATH_MAX]; |
118 | | |
119 | | int chars = snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin); |
120 | | // We cannot write PATH_MAX characters because the string will be terminated |
121 | | // with a null character. Fail if truncation happened. |
122 | | if (chars >= PATH_MAX) |
123 | | return 1; |
124 | | if (!realpath(fullpath, ret)) |
125 | | return 1; |
126 | | if (stat(fullpath, &sb) != 0) |
127 | | return 1; |
128 | | |
129 | | return 0; |
130 | | } |
131 | | |
132 | | static char * |
133 | | getprogpath(char ret[PATH_MAX], const char *bin) |
134 | | { |
135 | | /* First approach: absolute path. */ |
136 | | if (bin[0] == '/') { |
137 | | if (test_dir(ret, "/", bin) == 0) |
138 | | return ret; |
139 | | return nullptr; |
140 | | } |
141 | | |
142 | | /* Second approach: relative path. */ |
143 | | if (strchr(bin, '/')) { |
144 | | char cwd[PATH_MAX]; |
145 | | if (!getcwd(cwd, PATH_MAX)) |
146 | | return nullptr; |
147 | | if (test_dir(ret, cwd, bin) == 0) |
148 | | return ret; |
149 | | return nullptr; |
150 | | } |
151 | | |
152 | | /* Third approach: $PATH */ |
153 | | char *pv; |
154 | | if ((pv = getenv("PATH")) == nullptr) |
155 | | return nullptr; |
156 | | char *s = strdup(pv); |
157 | | if (!s) |
158 | | return nullptr; |
159 | | char *state; |
160 | | for (char *t = strtok_r(s, ":", &state); t != nullptr; |
161 | | t = strtok_r(nullptr, ":", &state)) { |
162 | | if (test_dir(ret, t, bin) == 0) { |
163 | | free(s); |
164 | | return ret; |
165 | | } |
166 | | } |
167 | | free(s); |
168 | | return nullptr; |
169 | | } |
170 | | #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__ |
171 | | |
172 | | /// GetMainExecutable - Return the path to the main executable, given the |
173 | | /// value of argv[0] from program startup. |
174 | 44.9k | std::string getMainExecutable(const char *argv0, void *MainAddr) { |
175 | 44.9k | #if defined(__APPLE__) |
176 | 44.9k | // On OS X the executable path is saved to the stack by dyld. Reading it |
177 | 44.9k | // from there is much faster than calling dladdr, especially for large |
178 | 44.9k | // binaries with symbols. |
179 | 44.9k | char exe_path[MAXPATHLEN]; |
180 | 44.9k | uint32_t size = sizeof(exe_path); |
181 | 44.9k | if (_NSGetExecutablePath(exe_path, &size) == 0) { |
182 | 44.9k | char link_path[MAXPATHLEN]; |
183 | 44.9k | if (realpath(exe_path, link_path)) |
184 | 44.9k | return link_path; |
185 | 0 | } |
186 | | #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \ |
187 | | defined(__minix) || defined(__DragonFly__) || \ |
188 | | defined(__FreeBSD_kernel__) || defined(_AIX) |
189 | | StringRef curproc("/proc/curproc/file"); |
190 | | char exe_path[PATH_MAX]; |
191 | | // /proc is not mounted by default under FreeBSD, but gives more accurate |
192 | | // information than argv[0] when it is. |
193 | | if (sys::fs::exists(curproc)) { |
194 | | ssize_t len = readlink(curproc.str().c_str(), exe_path, sizeof(exe_path)); |
195 | | if (len > 0) { |
196 | | // Null terminate the string for realpath. readlink never null |
197 | | // terminates its output. |
198 | | len = std::min(len, ssize_t(sizeof(exe_path) - 1)); |
199 | | exe_path[len] = '\0'; |
200 | | return exe_path; |
201 | | } |
202 | | } |
203 | | // If we don't have procfs mounted, fall back to argv[0] |
204 | | if (getprogpath(exe_path, argv0) != NULL) |
205 | | return exe_path; |
206 | | #elif defined(__linux__) || defined(__CYGWIN__) |
207 | | char exe_path[MAXPATHLEN]; |
208 | | StringRef aPath("/proc/self/exe"); |
209 | | if (sys::fs::exists(aPath)) { |
210 | | // /proc is not always mounted under Linux (chroot for example). |
211 | | ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path)); |
212 | | if (len < 0) |
213 | | return ""; |
214 | | |
215 | | // Null terminate the string for realpath. readlink never null |
216 | | // terminates its output. |
217 | | len = std::min(len, ssize_t(sizeof(exe_path) - 1)); |
218 | | exe_path[len] = '\0'; |
219 | | |
220 | | // On Linux, /proc/self/exe always looks through symlinks. However, on |
221 | | // GNU/Hurd, /proc/self/exe is a symlink to the path that was used to start |
222 | | // the program, and not the eventual binary file. Therefore, call realpath |
223 | | // so this behaves the same on all platforms. |
224 | | #if _POSIX_VERSION >= 200112 || defined(__GLIBC__) |
225 | | if (char *real_path = realpath(exe_path, NULL)) { |
226 | | std::string ret = std::string(real_path); |
227 | | free(real_path); |
228 | | return ret; |
229 | | } |
230 | | #else |
231 | | char real_path[MAXPATHLEN]; |
232 | | if (realpath(exe_path, real_path)) |
233 | | return std::string(real_path); |
234 | | #endif |
235 | | } |
236 | | // Fall back to the classical detection. |
237 | | if (getprogpath(exe_path, argv0)) |
238 | | return exe_path; |
239 | | #elif defined(HAVE_DLFCN_H) && defined(HAVE_DLADDR) |
240 | | // Use dladdr to get executable path if available. |
241 | | Dl_info DLInfo; |
242 | | int err = dladdr(MainAddr, &DLInfo); |
243 | | if (err == 0) |
244 | | return ""; |
245 | | |
246 | | // If the filename is a symlink, we need to resolve and return the location of |
247 | | // the actual executable. |
248 | | char link_path[MAXPATHLEN]; |
249 | | if (realpath(DLInfo.dli_fname, link_path)) |
250 | | return link_path; |
251 | | #else |
252 | | #error GetMainExecutable is not implemented on this host yet. |
253 | | #endif |
254 | 0 | return ""; |
255 | 0 | } |
256 | | |
257 | 78 | TimePoint<> basic_file_status::getLastAccessedTime() const { |
258 | 78 | return toTimePoint(fs_st_atime, fs_st_atime_nsec); |
259 | 78 | } |
260 | | |
261 | 834k | TimePoint<> basic_file_status::getLastModificationTime() const { |
262 | 834k | return toTimePoint(fs_st_mtime, fs_st_mtime_nsec); |
263 | 834k | } |
264 | | |
265 | 930k | UniqueID file_status::getUniqueID() const { |
266 | 930k | return UniqueID(fs_st_dev, fs_st_ino); |
267 | 930k | } |
268 | | |
269 | 0 | uint32_t file_status::getLinkCount() const { |
270 | 0 | return fs_st_nlinks; |
271 | 0 | } |
272 | | |
273 | 20 | ErrorOr<space_info> disk_space(const Twine &Path) { |
274 | 20 | struct STATVFS Vfs; |
275 | 20 | if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs)) |
276 | 0 | return std::error_code(errno, std::generic_category()); |
277 | 20 | auto FrSize = STATVFS_F_FRSIZE(Vfs); |
278 | 20 | space_info SpaceInfo; |
279 | 20 | SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize; |
280 | 20 | SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize; |
281 | 20 | SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize; |
282 | 20 | return SpaceInfo; |
283 | 20 | } |
284 | | |
285 | 66.4k | std::error_code current_path(SmallVectorImpl<char> &result) { |
286 | 66.4k | result.clear(); |
287 | 66.4k | |
288 | 66.4k | const char *pwd = ::getenv("PWD"); |
289 | 66.4k | llvm::sys::fs::file_status PWDStatus, DotStatus; |
290 | 66.4k | if (pwd && llvm::sys::path::is_absolute(pwd)43.0k && |
291 | 66.4k | !llvm::sys::fs::status(pwd, PWDStatus)43.0k && |
292 | 66.4k | !llvm::sys::fs::status(".", DotStatus)43.0k && |
293 | 66.4k | PWDStatus.getUniqueID() == DotStatus.getUniqueID()43.0k ) { |
294 | 43.0k | result.append(pwd, pwd + strlen(pwd)); |
295 | 43.0k | return std::error_code(); |
296 | 43.0k | } |
297 | 23.3k | |
298 | 23.3k | #ifdef MAXPATHLEN |
299 | 23.3k | result.reserve(MAXPATHLEN); |
300 | | #else |
301 | | // For GNU Hurd |
302 | | result.reserve(1024); |
303 | | #endif |
304 | | |
305 | 23.3k | while (true) { |
306 | 23.3k | if (::getcwd(result.data(), result.capacity()) == nullptr) { |
307 | 0 | // See if there was a real error. |
308 | 0 | if (errno != ENOMEM) |
309 | 0 | return std::error_code(errno, std::generic_category()); |
310 | 0 | // Otherwise there just wasn't enough space. |
311 | 0 | result.reserve(result.capacity() * 2); |
312 | 0 | } else |
313 | 23.3k | break; |
314 | 23.3k | } |
315 | 23.3k | |
316 | 23.3k | result.set_size(strlen(result.data())); |
317 | 23.3k | return std::error_code(); |
318 | 23.3k | } |
319 | | |
320 | 411 | std::error_code set_current_path(const Twine &path) { |
321 | 411 | SmallString<128> path_storage; |
322 | 411 | StringRef p = path.toNullTerminatedStringRef(path_storage); |
323 | 411 | |
324 | 411 | if (::chdir(p.begin()) == -1) |
325 | 0 | return std::error_code(errno, std::generic_category()); |
326 | 411 | |
327 | 411 | return std::error_code(); |
328 | 411 | } |
329 | | |
330 | | std::error_code create_directory(const Twine &path, bool IgnoreExisting, |
331 | 3.59k | perms Perms) { |
332 | 3.59k | SmallString<128> path_storage; |
333 | 3.59k | StringRef p = path.toNullTerminatedStringRef(path_storage); |
334 | 3.59k | |
335 | 3.59k | if (::mkdir(p.begin(), Perms) == -1) { |
336 | 2.00k | if (errno != EEXIST || !IgnoreExisting1.30k ) |
337 | 694 | return std::error_code(errno, std::generic_category()); |
338 | 2.90k | } |
339 | 2.90k | |
340 | 2.90k | return std::error_code(); |
341 | 2.90k | } |
342 | | |
343 | | // Note that we are using symbolic link because hard links are not supported by |
344 | | // all filesystems (SMB doesn't). |
345 | 1.85k | std::error_code create_link(const Twine &to, const Twine &from) { |
346 | 1.85k | // Get arguments. |
347 | 1.85k | SmallString<128> from_storage; |
348 | 1.85k | SmallString<128> to_storage; |
349 | 1.85k | StringRef f = from.toNullTerminatedStringRef(from_storage); |
350 | 1.85k | StringRef t = to.toNullTerminatedStringRef(to_storage); |
351 | 1.85k | |
352 | 1.85k | if (::symlink(t.begin(), f.begin()) == -1) |
353 | 0 | return std::error_code(errno, std::generic_category()); |
354 | 1.85k | |
355 | 1.85k | return std::error_code(); |
356 | 1.85k | } |
357 | | |
358 | 11 | std::error_code create_hard_link(const Twine &to, const Twine &from) { |
359 | 11 | // Get arguments. |
360 | 11 | SmallString<128> from_storage; |
361 | 11 | SmallString<128> to_storage; |
362 | 11 | StringRef f = from.toNullTerminatedStringRef(from_storage); |
363 | 11 | StringRef t = to.toNullTerminatedStringRef(to_storage); |
364 | 11 | |
365 | 11 | if (::link(t.begin(), f.begin()) == -1) |
366 | 0 | return std::error_code(errno, std::generic_category()); |
367 | 11 | |
368 | 11 | return std::error_code(); |
369 | 11 | } |
370 | | |
371 | 20.2k | std::error_code remove(const Twine &path, bool IgnoreNonExisting) { |
372 | 20.2k | SmallString<128> path_storage; |
373 | 20.2k | StringRef p = path.toNullTerminatedStringRef(path_storage); |
374 | 20.2k | |
375 | 20.2k | struct stat buf; |
376 | 20.2k | if (lstat(p.begin(), &buf) != 0) { |
377 | 2.52k | if (errno != ENOENT || !IgnoreNonExisting) |
378 | 1 | return std::error_code(errno, std::generic_category()); |
379 | 2.52k | return std::error_code(); |
380 | 2.52k | } |
381 | 17.6k | |
382 | 17.6k | // Note: this check catches strange situations. In all cases, LLVM should |
383 | 17.6k | // only be involved in the creation and deletion of regular files. This |
384 | 17.6k | // check ensures that what we're trying to erase is a regular file. It |
385 | 17.6k | // effectively prevents LLVM from erasing things like /dev/null, any block |
386 | 17.6k | // special file, or other things that aren't "regular" files. |
387 | 17.6k | if (!S_ISREG(buf.st_mode) && !S_ISDIR2.33k (buf.st_mode) && !S_ISLNK2.20k (buf.st_mode)) |
388 | 17.6k | return make_error_code(errc::operation_not_permitted)354 ; |
389 | 17.3k | |
390 | 17.3k | if (::remove(p.begin()) == -1) { |
391 | 2 | if (errno != ENOENT || !IgnoreNonExisting0 ) |
392 | 2 | return std::error_code(errno, std::generic_category()); |
393 | 17.3k | } |
394 | 17.3k | |
395 | 17.3k | return std::error_code(); |
396 | 17.3k | } |
397 | | |
398 | 4 | static bool is_local_impl(struct STATVFS &Vfs) { |
399 | | #if defined(__linux__) || defined(__GNU__) |
400 | | #ifndef NFS_SUPER_MAGIC |
401 | | #define NFS_SUPER_MAGIC 0x6969 |
402 | | #endif |
403 | | #ifndef SMB_SUPER_MAGIC |
404 | | #define SMB_SUPER_MAGIC 0x517B |
405 | | #endif |
406 | | #ifndef CIFS_MAGIC_NUMBER |
407 | | #define CIFS_MAGIC_NUMBER 0xFF534D42 |
408 | | #endif |
409 | | #ifdef __GNU__ |
410 | | switch ((uint32_t)Vfs.__f_type) { |
411 | | #else |
412 | | switch ((uint32_t)Vfs.f_type) { |
413 | | #endif |
414 | | case NFS_SUPER_MAGIC: |
415 | | case SMB_SUPER_MAGIC: |
416 | | case CIFS_MAGIC_NUMBER: |
417 | | return false; |
418 | | default: |
419 | | return true; |
420 | | } |
421 | | #elif defined(__CYGWIN__) |
422 | | // Cygwin doesn't expose this information; would need to use Win32 API. |
423 | | return false; |
424 | | #elif defined(__Fuchsia__) |
425 | | // Fuchsia doesn't yet support remote filesystem mounts. |
426 | | return true; |
427 | | #elif defined(__EMSCRIPTEN__) |
428 | | // Emscripten doesn't currently support remote filesystem mounts. |
429 | | return true; |
430 | | #elif defined(__HAIKU__) |
431 | | // Haiku doesn't expose this information. |
432 | | return false; |
433 | | #elif defined(__sun) |
434 | | // statvfs::f_basetype contains a null-terminated FSType name of the mounted target |
435 | | StringRef fstype(Vfs.f_basetype); |
436 | | // NFS is the only non-local fstype?? |
437 | | return !fstype.equals("nfs"); |
438 | | #elif defined(_AIX) |
439 | | // Call mntctl; try more than twice in case of timing issues with a concurrent |
440 | | // mount. |
441 | | int Ret; |
442 | | size_t BufSize = 2048u; |
443 | | std::unique_ptr<char[]> Buf; |
444 | | int Tries = 3; |
445 | | while (Tries--) { |
446 | | Buf = llvm::make_unique<char[]>(BufSize); |
447 | | Ret = mntctl(MCTL_QUERY, BufSize, Buf.get()); |
448 | | if (Ret != 0) |
449 | | break; |
450 | | BufSize = *reinterpret_cast<unsigned int *>(Buf.get()); |
451 | | Buf.reset(); |
452 | | } |
453 | | |
454 | | if (Ret == -1) |
455 | | // There was an error; "remote" is the conservative answer. |
456 | | return false; |
457 | | |
458 | | // Look for the correct vmount entry. |
459 | | char *CurObjPtr = Buf.get(); |
460 | | while (Ret--) { |
461 | | struct vmount *Vp = reinterpret_cast<struct vmount *>(CurObjPtr); |
462 | | static_assert(sizeof(Vfs.f_fsid) == sizeof(Vp->vmt_fsid), |
463 | | "fsid length mismatch"); |
464 | | if (memcmp(&Vfs.f_fsid, &Vp->vmt_fsid, sizeof Vfs.f_fsid) == 0) |
465 | | return (Vp->vmt_flags & MNT_REMOTE) == 0; |
466 | | |
467 | | CurObjPtr += Vp->vmt_length; |
468 | | } |
469 | | |
470 | | // vmount entry not found; "remote" is the conservative answer. |
471 | | return false; |
472 | | #else |
473 | 4 | return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL); |
474 | 4 | #endif |
475 | 4 | } |
476 | | |
477 | 2 | std::error_code is_local(const Twine &Path, bool &Result) { |
478 | 2 | struct STATVFS Vfs; |
479 | 2 | if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs)) |
480 | 0 | return std::error_code(errno, std::generic_category()); |
481 | 2 | |
482 | 2 | Result = is_local_impl(Vfs); |
483 | 2 | return std::error_code(); |
484 | 2 | } |
485 | | |
486 | 2 | std::error_code is_local(int FD, bool &Result) { |
487 | 2 | struct STATVFS Vfs; |
488 | 2 | if (::FSTATVFS(FD, &Vfs)) |
489 | 0 | return std::error_code(errno, std::generic_category()); |
490 | 2 | |
491 | 2 | Result = is_local_impl(Vfs); |
492 | 2 | return std::error_code(); |
493 | 2 | } |
494 | | |
495 | 22.6k | std::error_code rename(const Twine &from, const Twine &to) { |
496 | 22.6k | // Get arguments. |
497 | 22.6k | SmallString<128> from_storage; |
498 | 22.6k | SmallString<128> to_storage; |
499 | 22.6k | StringRef f = from.toNullTerminatedStringRef(from_storage); |
500 | 22.6k | StringRef t = to.toNullTerminatedStringRef(to_storage); |
501 | 22.6k | |
502 | 22.6k | if (::rename(f.begin(), t.begin()) == -1) |
503 | 1 | return std::error_code(errno, std::generic_category()); |
504 | 22.6k | |
505 | 22.6k | return std::error_code(); |
506 | 22.6k | } |
507 | | |
508 | 7.23k | std::error_code resize_file(int FD, uint64_t Size) { |
509 | | #if defined(HAVE_POSIX_FALLOCATE) |
510 | | // If we have posix_fallocate use it. Unlike ftruncate it always allocates |
511 | | // space, so we get an error if the disk is full. |
512 | | if (int Err = ::posix_fallocate(FD, 0, Size)) { |
513 | | #ifdef _AIX |
514 | | constexpr int NotSupportedError = ENOTSUP; |
515 | | #else |
516 | | constexpr int NotSupportedError = EOPNOTSUPP; |
517 | | #endif |
518 | | if (Err != EINVAL && Err != NotSupportedError) |
519 | | return std::error_code(Err, std::generic_category()); |
520 | | } |
521 | | #endif |
522 | | // Use ftruncate as a fallback. It may or may not allocate space. At least on |
523 | 7.23k | // OS X with HFS+ it does. |
524 | 7.23k | if (::ftruncate(FD, Size) == -1) |
525 | 0 | return std::error_code(errno, std::generic_category()); |
526 | 7.23k | |
527 | 7.23k | return std::error_code(); |
528 | 7.23k | } |
529 | | |
530 | 422k | static int convertAccessMode(AccessMode Mode) { |
531 | 422k | switch (Mode) { |
532 | 422k | case AccessMode::Exist: |
533 | 111k | return F_OK; |
534 | 422k | case AccessMode::Write: |
535 | 12.4k | return W_OK; |
536 | 422k | case AccessMode::Execute: |
537 | 298k | return R_OK | X_OK; // scripts also need R_OK. |
538 | 0 | } |
539 | 0 | llvm_unreachable("invalid enum"); |
540 | 0 | } |
541 | | |
542 | 422k | std::error_code access(const Twine &Path, AccessMode Mode) { |
543 | 422k | SmallString<128> PathStorage; |
544 | 422k | StringRef P = Path.toNullTerminatedStringRef(PathStorage); |
545 | 422k | |
546 | 422k | if (::access(P.begin(), convertAccessMode(Mode)) == -1) |
547 | 355k | return std::error_code(errno, std::generic_category()); |
548 | 66.7k | |
549 | 66.7k | if (Mode == AccessMode::Execute) { |
550 | 6.44k | // Don't say that directories are executable. |
551 | 6.44k | struct stat buf; |
552 | 6.44k | if (0 != stat(P.begin(), &buf)) |
553 | 0 | return errc::permission_denied; |
554 | 6.44k | if (!S_ISREG(buf.st_mode)) |
555 | 6.44k | return errc::permission_denied0 ; |
556 | 66.7k | } |
557 | 66.7k | |
558 | 66.7k | return std::error_code(); |
559 | 66.7k | } |
560 | | |
561 | 298k | bool can_execute(const Twine &Path) { |
562 | 298k | return !access(Path, AccessMode::Execute); |
563 | 298k | } |
564 | | |
565 | 262 | bool equivalent(file_status A, file_status B) { |
566 | 262 | assert(status_known(A) && status_known(B)); |
567 | 262 | return A.fs_st_dev == B.fs_st_dev && |
568 | 262 | A.fs_st_ino == B.fs_st_ino; |
569 | 262 | } |
570 | | |
571 | 262 | std::error_code equivalent(const Twine &A, const Twine &B, bool &result) { |
572 | 262 | file_status fsA, fsB; |
573 | 262 | if (std::error_code ec = status(A, fsA)) |
574 | 2 | return ec; |
575 | 260 | if (std::error_code ec = status(B, fsB)) |
576 | 0 | return ec; |
577 | 260 | result = equivalent(fsA, fsB); |
578 | 260 | return std::error_code(); |
579 | 260 | } |
580 | | |
581 | 32 | static void expandTildeExpr(SmallVectorImpl<char> &Path) { |
582 | 32 | StringRef PathStr(Path.begin(), Path.size()); |
583 | 32 | if (PathStr.empty() || !PathStr.startswith("~")) |
584 | 28 | return; |
585 | 4 | |
586 | 4 | PathStr = PathStr.drop_front(); |
587 | 4 | StringRef Expr = |
588 | 4 | PathStr.take_until([](char c) { return path::is_separator(c); }2 ); |
589 | 4 | StringRef Remainder = PathStr.substr(Expr.size() + 1); |
590 | 4 | SmallString<128> Storage; |
591 | 4 | if (Expr.empty()) { |
592 | 4 | // This is just ~/..., resolve it to the current user's home dir. |
593 | 4 | if (!path::home_directory(Storage)) { |
594 | 0 | // For some reason we couldn't get the home directory. Just exit. |
595 | 0 | return; |
596 | 0 | } |
597 | 4 | |
598 | 4 | // Overwrite the first character and insert the rest. |
599 | 4 | Path[0] = Storage[0]; |
600 | 4 | Path.insert(Path.begin() + 1, Storage.begin() + 1, Storage.end()); |
601 | 4 | return; |
602 | 4 | } |
603 | 0 | |
604 | 0 | // This is a string of the form ~username/, look up this user's entry in the |
605 | 0 | // password database. |
606 | 0 | struct passwd *Entry = nullptr; |
607 | 0 | std::string User = Expr.str(); |
608 | 0 | Entry = ::getpwnam(User.c_str()); |
609 | 0 |
|
610 | 0 | if (!Entry) { |
611 | 0 | // Unable to look up the entry, just return back the original path. |
612 | 0 | return; |
613 | 0 | } |
614 | 0 | |
615 | 0 | Storage = Remainder; |
616 | 0 | Path.clear(); |
617 | 0 | Path.append(Entry->pw_dir, Entry->pw_dir + strlen(Entry->pw_dir)); |
618 | 0 | llvm::sys::path::append(Path, Storage); |
619 | 0 | } |
620 | | |
621 | | |
622 | 3 | void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) { |
623 | 3 | dest.clear(); |
624 | 3 | if (path.isTriviallyEmpty()) |
625 | 0 | return; |
626 | 3 | |
627 | 3 | path.toVector(dest); |
628 | 3 | expandTildeExpr(dest); |
629 | 3 | |
630 | 3 | return; |
631 | 3 | } |
632 | | |
633 | 1.02M | static file_type typeForMode(mode_t Mode) { |
634 | 1.02M | if (S_ISDIR(Mode)) |
635 | 1.02M | return file_type::directory_file317k ; |
636 | 704k | else if (S_ISREG(Mode)) |
637 | 704k | return file_type::regular_file702k ; |
638 | 1.82k | else if (S_ISBLK(Mode)) |
639 | 1.82k | return file_type::block_file0 ; |
640 | 1.82k | else if (S_ISCHR(Mode)) |
641 | 1.82k | return file_type::character_file1.02k ; |
642 | 797 | else if (S_ISFIFO(Mode)) |
643 | 797 | return file_type::fifo_file4 ; |
644 | 793 | else if (S_ISSOCK(Mode)) |
645 | 793 | return file_type::socket_file0 ; |
646 | 793 | else if (S_ISLNK(Mode)) |
647 | 793 | return file_type::symlink_file791 ; |
648 | 2 | return file_type::type_unknown; |
649 | 2 | } |
650 | | |
651 | | static std::error_code fillStatus(int StatRet, const struct stat &Status, |
652 | 1.81M | file_status &Result) { |
653 | 1.81M | if (StatRet != 0) { |
654 | 804k | std::error_code EC(errno, std::generic_category()); |
655 | 804k | if (EC == errc::no_such_file_or_directory) |
656 | 804k | Result = file_status(file_type::file_not_found); |
657 | 31 | else |
658 | 31 | Result = file_status(file_type::status_error); |
659 | 804k | return EC; |
660 | 804k | } |
661 | 1.00M | |
662 | 1.00M | uint32_t atime_nsec, mtime_nsec; |
663 | 1.00M | #if defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC) |
664 | 1.00M | atime_nsec = Status.st_atimespec.tv_nsec; |
665 | 1.00M | mtime_nsec = Status.st_mtimespec.tv_nsec; |
666 | | #elif defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC) |
667 | | atime_nsec = Status.st_atim.tv_nsec; |
668 | | mtime_nsec = Status.st_mtim.tv_nsec; |
669 | | #else |
670 | | atime_nsec = mtime_nsec = 0; |
671 | | #endif |
672 | | |
673 | 1.00M | perms Perms = static_cast<perms>(Status.st_mode) & all_perms; |
674 | 1.00M | Result = file_status(typeForMode(Status.st_mode), Perms, Status.st_dev, |
675 | 1.00M | Status.st_nlink, Status.st_ino, |
676 | 1.00M | Status.st_atime, atime_nsec, Status.st_mtime, mtime_nsec, |
677 | 1.00M | Status.st_uid, Status.st_gid, Status.st_size); |
678 | 1.00M | |
679 | 1.00M | return std::error_code(); |
680 | 1.00M | } |
681 | | |
682 | 1.25M | std::error_code status(const Twine &Path, file_status &Result, bool Follow) { |
683 | 1.25M | SmallString<128> PathStorage; |
684 | 1.25M | StringRef P = Path.toNullTerminatedStringRef(PathStorage); |
685 | 1.25M | |
686 | 1.25M | struct stat Status; |
687 | 1.25M | int StatRet = (Follow ? ::stat1.25M : ::lstat578 )(P.begin(), &Status); |
688 | 1.25M | return fillStatus(StatRet, Status, Result); |
689 | 1.25M | } |
690 | | |
691 | 557k | std::error_code status(int FD, file_status &Result) { |
692 | 557k | struct stat Status; |
693 | 557k | int StatRet = ::fstat(FD, &Status); |
694 | 557k | return fillStatus(StatRet, Status, Result); |
695 | 557k | } |
696 | | |
697 | 563 | unsigned getUmask() { |
698 | 563 | // Chose arbitary new mask and reset the umask to the old mask. |
699 | 563 | // umask(2) never fails so ignore the return of the second call. |
700 | 563 | unsigned Mask = ::umask(0); |
701 | 563 | (void) ::umask(Mask); |
702 | 563 | return Mask; |
703 | 563 | } |
704 | | |
705 | 29 | std::error_code setPermissions(const Twine &Path, perms Permissions) { |
706 | 29 | SmallString<128> PathStorage; |
707 | 29 | StringRef P = Path.toNullTerminatedStringRef(PathStorage); |
708 | 29 | |
709 | 29 | if (::chmod(P.begin(), Permissions)) |
710 | 0 | return std::error_code(errno, std::generic_category()); |
711 | 29 | return std::error_code(); |
712 | 29 | } |
713 | | |
714 | 562 | std::error_code setPermissions(int FD, perms Permissions) { |
715 | 562 | if (::fchmod(FD, Permissions)) |
716 | 0 | return std::error_code(errno, std::generic_category()); |
717 | 562 | return std::error_code(); |
718 | 562 | } |
719 | | |
720 | | std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime, |
721 | 13 | TimePoint<> ModificationTime) { |
722 | 13 | #if defined(HAVE_FUTIMENS) |
723 | 13 | timespec Times[2]; |
724 | 13 | Times[0] = sys::toTimeSpec(AccessTime); |
725 | 13 | Times[1] = sys::toTimeSpec(ModificationTime); |
726 | 13 | if (::futimens(FD, Times)) |
727 | 0 | return std::error_code(errno, std::generic_category()); |
728 | 13 | return std::error_code(); |
729 | | #elif defined(HAVE_FUTIMES) |
730 | | timeval Times[2]; |
731 | | Times[0] = sys::toTimeVal( |
732 | | std::chrono::time_point_cast<std::chrono::microseconds>(AccessTime)); |
733 | | Times[1] = |
734 | | sys::toTimeVal(std::chrono::time_point_cast<std::chrono::microseconds>( |
735 | | ModificationTime)); |
736 | | if (::futimes(FD, Times)) |
737 | | return std::error_code(errno, std::generic_category()); |
738 | | return std::error_code(); |
739 | | #else |
740 | | #warning Missing futimes() and futimens() |
741 | | return make_error_code(errc::function_not_supported); |
742 | | #endif |
743 | | } |
744 | | |
745 | | std::error_code mapped_file_region::init(int FD, uint64_t Offset, |
746 | 79.4k | mapmode Mode) { |
747 | 79.4k | assert(Size != 0); |
748 | 79.4k | |
749 | 79.4k | int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE; |
750 | 79.4k | int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE)7.24k ; |
751 | 79.4k | #if defined(__APPLE__) |
752 | 79.4k | //---------------------------------------------------------------------- |
753 | 79.4k | // Newer versions of MacOSX have a flag that will allow us to read from |
754 | 79.4k | // binaries whose code signature is invalid without crashing by using |
755 | 79.4k | // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media |
756 | 79.4k | // is mapped we can avoid crashing and return zeroes to any pages we try |
757 | 79.4k | // to read if the media becomes unavailable by using the |
758 | 79.4k | // MAP_RESILIENT_MEDIA flag. These flags are only usable when mapping |
759 | 79.4k | // with PROT_READ, so take care not to specify them otherwise. |
760 | 79.4k | //---------------------------------------------------------------------- |
761 | 79.4k | if (Mode == readonly) { |
762 | 72.1k | #if defined(MAP_RESILIENT_CODESIGN) |
763 | 72.1k | flags |= MAP_RESILIENT_CODESIGN; |
764 | 72.1k | #endif |
765 | 72.1k | #if defined(MAP_RESILIENT_MEDIA) |
766 | 72.1k | flags |= MAP_RESILIENT_MEDIA; |
767 | 72.1k | #endif |
768 | 72.1k | } |
769 | 79.4k | #endif // #if defined (__APPLE__) |
770 | 79.4k | |
771 | 79.4k | Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset); |
772 | 79.4k | if (Mapping == MAP_FAILED) |
773 | 79.4k | return std::error_code(errno, std::generic_category())0 ; |
774 | 79.4k | return std::error_code(); |
775 | 79.4k | } |
776 | | |
777 | | mapped_file_region::mapped_file_region(int fd, mapmode mode, size_t length, |
778 | | uint64_t offset, std::error_code &ec) |
779 | 79.4k | : Size(length), Mapping(), Mode(mode) { |
780 | 79.4k | (void)Mode; |
781 | 79.4k | ec = init(fd, offset, mode); |
782 | 79.4k | if (ec) |
783 | 0 | Mapping = nullptr; |
784 | 79.4k | } |
785 | | |
786 | 28.6k | mapped_file_region::~mapped_file_region() { |
787 | 28.6k | if (Mapping) |
788 | 28.6k | ::munmap(Mapping, Size); |
789 | 28.6k | } |
790 | | |
791 | 928 | size_t mapped_file_region::size() const { |
792 | 928 | assert(Mapping && "Mapping failed but used anyway!"); |
793 | 928 | return Size; |
794 | 928 | } |
795 | | |
796 | 534k | char *mapped_file_region::data() const { |
797 | 534k | assert(Mapping && "Mapping failed but used anyway!"); |
798 | 534k | return reinterpret_cast<char*>(Mapping); |
799 | 534k | } |
800 | | |
801 | 72.0k | const char *mapped_file_region::const_data() const { |
802 | 72.0k | assert(Mapping && "Mapping failed but used anyway!"); |
803 | 72.0k | return reinterpret_cast<const char*>(Mapping); |
804 | 72.0k | } |
805 | | |
806 | 216k | int mapped_file_region::alignment() { |
807 | 216k | return Process::getPageSizeEstimate(); |
808 | 216k | } |
809 | | |
810 | | std::error_code detail::directory_iterator_construct(detail::DirIterState &it, |
811 | | StringRef path, |
812 | 416k | bool follow_symlinks) { |
813 | 416k | SmallString<128> path_null(path); |
814 | 416k | DIR *directory = ::opendir(path_null.c_str()); |
815 | 416k | if (!directory) |
816 | 413k | return std::error_code(errno, std::generic_category()); |
817 | 2.60k | |
818 | 2.60k | it.IterationHandle = reinterpret_cast<intptr_t>(directory); |
819 | 2.60k | // Add something for replace_filename to replace. |
820 | 2.60k | path::append(path_null, "."); |
821 | 2.60k | it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks); |
822 | 2.60k | return directory_iterator_increment(it); |
823 | 2.60k | } |
824 | | |
825 | 418k | std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) { |
826 | 418k | if (it.IterationHandle) |
827 | 2.60k | ::closedir(reinterpret_cast<DIR *>(it.IterationHandle)); |
828 | 418k | it.IterationHandle = 0; |
829 | 418k | it.CurrentEntry = directory_entry(); |
830 | 418k | return std::error_code(); |
831 | 418k | } |
832 | | |
833 | 12.4k | static file_type direntType(dirent* Entry) { |
834 | 12.4k | // Most platforms provide the file type in the dirent: Linux/BSD/Mac. |
835 | 12.4k | // The DTTOIF macro lets us reuse our status -> type conversion. |
836 | 12.4k | // Note that while glibc provides a macro to see if this is supported, |
837 | 12.4k | // _DIRENT_HAVE_D_TYPE, it's not defined on BSD/Mac, so we test for the |
838 | 12.4k | // d_type-to-mode_t conversion macro instead. |
839 | 12.4k | #if defined(DTTOIF) |
840 | 12.4k | return typeForMode(DTTOIF(Entry->d_type)); |
841 | | #else |
842 | | // Other platforms such as Solaris require a stat() to get the type. |
843 | | return file_type::type_unknown; |
844 | | #endif |
845 | | } |
846 | | |
847 | 20.2k | std::error_code detail::directory_iterator_increment(detail::DirIterState &It) { |
848 | 20.2k | errno = 0; |
849 | 20.2k | dirent *CurDir = ::readdir(reinterpret_cast<DIR *>(It.IterationHandle)); |
850 | 20.2k | if (CurDir == nullptr && errno != 02.59k ) { |
851 | 0 | return std::error_code(errno, std::generic_category()); |
852 | 20.2k | } else if (CurDir != nullptr) { |
853 | 17.7k | StringRef Name(CurDir->d_name); |
854 | 17.7k | if ((Name.size() == 1 && Name[0] == '.'2.69k ) || |
855 | 17.7k | (15.0k Name.size() == 215.0k && Name[0] == '.'2.68k && Name[1] == '.'2.60k )) |
856 | 5.21k | return directory_iterator_increment(It); |
857 | 12.4k | It.CurrentEntry.replace_filename(Name, direntType(CurDir)); |
858 | 12.4k | } else |
859 | 2.59k | return directory_iterator_destruct(It); |
860 | 12.4k | |
861 | 12.4k | return std::error_code(); |
862 | 12.4k | } |
863 | | |
864 | 153 | ErrorOr<basic_file_status> directory_entry::status() const { |
865 | 153 | file_status s; |
866 | 153 | if (auto EC = fs::status(Path, s, FollowSymlinks)) |
867 | 13 | return EC; |
868 | 140 | return s; |
869 | 140 | } |
870 | | |
871 | | #if !defined(F_GETPATH) |
872 | | static bool hasProcSelfFD() { |
873 | | // If we have a /proc filesystem mounted, we can quickly establish the |
874 | | // real name of the file with readlink |
875 | | static const bool Result = (::access("/proc/self/fd", R_OK) == 0); |
876 | | return Result; |
877 | | } |
878 | | #endif |
879 | | |
880 | | static int nativeOpenFlags(CreationDisposition Disp, OpenFlags Flags, |
881 | 1.14M | FileAccess Access) { |
882 | 1.14M | int Result = 0; |
883 | 1.14M | if (Access == FA_Read) |
884 | 1.08M | Result |= O_RDONLY; |
885 | 1.14M | else if (61.3k Access == FA_Write61.3k ) |
886 | 21.5k | Result |= O_WRONLY; |
887 | 61.3k | else if (39.8k Access == (FA_Read | FA_Write)39.8k ) |
888 | 39.8k | Result |= O_RDWR; |
889 | 1.14M | |
890 | 1.14M | // This is for compatibility with old code that assumed F_Append implied |
891 | 1.14M | // would open an existing file. See Windows/Path.inc for a longer comment. |
892 | 1.14M | if (Flags & F_Append) |
893 | 12 | Disp = CD_OpenAlways; |
894 | 1.14M | |
895 | 1.14M | if (Disp == CD_CreateNew) { |
896 | 39.7k | Result |= O_CREAT; // Create if it doesn't exist. |
897 | 39.7k | Result |= O_EXCL; // Fail if it does. |
898 | 1.10M | } else if (Disp == CD_CreateAlways) { |
899 | 21.0k | Result |= O_CREAT; // Create if it doesn't exist. |
900 | 21.0k | Result |= O_TRUNC; // Truncate if it does. |
901 | 1.08M | } else if (Disp == CD_OpenAlways) { |
902 | 14 | Result |= O_CREAT; // Create if it doesn't exist. |
903 | 1.08M | } else if (Disp == CD_OpenExisting) { |
904 | 1.08M | // Nothing special, just don't add O_CREAT and we get these semantics. |
905 | 1.08M | } |
906 | 1.14M | |
907 | 1.14M | if (Flags & F_Append) |
908 | 12 | Result |= O_APPEND; |
909 | 1.14M | |
910 | 1.14M | #ifdef O_CLOEXEC |
911 | 1.14M | if (!(Flags & OF_ChildInherit)) |
912 | 1.14M | Result |= O_CLOEXEC; |
913 | 1.14M | #endif |
914 | 1.14M | |
915 | 1.14M | return Result; |
916 | 1.14M | } |
917 | | |
918 | | std::error_code openFile(const Twine &Name, int &ResultFD, |
919 | | CreationDisposition Disp, FileAccess Access, |
920 | 1.14M | OpenFlags Flags, unsigned Mode) { |
921 | 1.14M | int OpenFlags = nativeOpenFlags(Disp, Flags, Access); |
922 | 1.14M | |
923 | 1.14M | SmallString<128> Storage; |
924 | 1.14M | StringRef P = Name.toNullTerminatedStringRef(Storage); |
925 | 1.14M | // Call ::open in a lambda to avoid overload resolution in RetryAfterSignal |
926 | 1.14M | // when open is overloaded, such as in Bionic. |
927 | 1.14M | auto Open = [&]() { return ::open(P.begin(), OpenFlags, Mode); }1.14M ; |
928 | 1.14M | if ((ResultFD = sys::RetryAfterSignal(-1, Open)) < 0) |
929 | 520k | return std::error_code(errno, std::generic_category()); |
930 | | #ifndef O_CLOEXEC |
931 | | if (!(Flags & OF_ChildInherit)) { |
932 | | int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC); |
933 | | (void)r; |
934 | | assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed"); |
935 | | } |
936 | | #endif |
937 | 624k | return std::error_code(); |
938 | 624k | } |
939 | | |
940 | | Expected<int> openNativeFile(const Twine &Name, CreationDisposition Disp, |
941 | | FileAccess Access, OpenFlags Flags, |
942 | 12 | unsigned Mode) { |
943 | 12 | |
944 | 12 | int FD; |
945 | 12 | std::error_code EC = openFile(Name, FD, Disp, Access, Flags, Mode); |
946 | 12 | if (EC) |
947 | 0 | return errorCodeToError(EC); |
948 | 12 | return FD; |
949 | 12 | } |
950 | | |
951 | | std::error_code openFileForRead(const Twine &Name, int &ResultFD, |
952 | | OpenFlags Flags, |
953 | 1.08M | SmallVectorImpl<char> *RealPath) { |
954 | 1.08M | std::error_code EC = |
955 | 1.08M | openFile(Name, ResultFD, CD_OpenExisting, FA_Read, Flags, 0666); |
956 | 1.08M | if (EC) |
957 | 517k | return EC; |
958 | 565k | |
959 | 565k | // Attempt to get the real name of the file, if the user asked |
960 | 565k | if(!RealPath) |
961 | 47.2k | return std::error_code(); |
962 | 518k | RealPath->clear(); |
963 | 518k | #if defined(F_GETPATH) |
964 | 518k | // When F_GETPATH is availble, it is the quickest way to get |
965 | 518k | // the real path name. |
966 | 518k | char Buffer[MAXPATHLEN]; |
967 | 518k | if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1) |
968 | 518k | RealPath->append(Buffer, Buffer + strlen(Buffer)); |
969 | | #else |
970 | | char Buffer[PATH_MAX]; |
971 | | if (hasProcSelfFD()) { |
972 | | char ProcPath[64]; |
973 | | snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD); |
974 | | ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer)); |
975 | | if (CharCount > 0) |
976 | | RealPath->append(Buffer, Buffer + CharCount); |
977 | | } else { |
978 | | SmallString<128> Storage; |
979 | | StringRef P = Name.toNullTerminatedStringRef(Storage); |
980 | | |
981 | | // Use ::realpath to get the real path name |
982 | | if (::realpath(P.begin(), Buffer) != nullptr) |
983 | | RealPath->append(Buffer, Buffer + strlen(Buffer)); |
984 | | } |
985 | | #endif |
986 | | return std::error_code(); |
987 | 518k | } |
988 | | |
989 | | Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags, |
990 | 1.08M | SmallVectorImpl<char> *RealPath) { |
991 | 1.08M | file_t ResultFD; |
992 | 1.08M | std::error_code EC = openFileForRead(Name, ResultFD, Flags, RealPath); |
993 | 1.08M | if (EC) |
994 | 517k | return errorCodeToError(EC); |
995 | 565k | return ResultFD; |
996 | 565k | } |
997 | | |
998 | 40.3k | file_t getStdinHandle() { return 0; } |
999 | 0 | file_t getStdoutHandle() { return 1; } |
1000 | 0 | file_t getStderrHandle() { return 2; } |
1001 | | |
1002 | | std::error_code readNativeFile(file_t FD, MutableArrayRef<char> Buf, |
1003 | 111k | size_t *BytesRead) { |
1004 | 111k | *BytesRead = sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Buf.size()); |
1005 | 111k | if (ssize_t(*BytesRead) == -1) |
1006 | 0 | return std::error_code(errno, std::generic_category()); |
1007 | 111k | return std::error_code(); |
1008 | 111k | } |
1009 | | |
1010 | | std::error_code readNativeFileSlice(file_t FD, MutableArrayRef<char> Buf, |
1011 | 483k | size_t Offset) { |
1012 | 483k | char *BufPtr = Buf.data(); |
1013 | 483k | size_t BytesLeft = Buf.size(); |
1014 | 483k | |
1015 | | #ifndef HAVE_PREAD |
1016 | | // If we don't have pread, seek to Offset. |
1017 | | if (lseek(FD, Offset, SEEK_SET) == -1) |
1018 | | return std::error_code(errno, std::generic_category()); |
1019 | | #endif |
1020 | | |
1021 | 966k | while (BytesLeft) { |
1022 | 482k | #ifdef HAVE_PREAD |
1023 | 482k | ssize_t NumRead = sys::RetryAfterSignal(-1, ::pread, FD, BufPtr, BytesLeft, |
1024 | 482k | Buf.size() - BytesLeft + Offset); |
1025 | | #else |
1026 | | ssize_t NumRead = sys::RetryAfterSignal(-1, ::read, FD, BufPtr, BytesLeft); |
1027 | | #endif |
1028 | 482k | if (NumRead == -1) { |
1029 | 0 | // Error while reading. |
1030 | 0 | return std::error_code(errno, std::generic_category()); |
1031 | 0 | } |
1032 | 482k | if (NumRead == 0) { |
1033 | 0 | memset(BufPtr, 0, BytesLeft); // zero-initialize rest of the buffer. |
1034 | 0 | break; |
1035 | 0 | } |
1036 | 482k | BytesLeft -= NumRead; |
1037 | 482k | BufPtr += NumRead; |
1038 | 482k | } |
1039 | 483k | return std::error_code(); |
1040 | 483k | } |
1041 | | |
1042 | 558k | std::error_code closeFile(file_t &F) { |
1043 | 558k | file_t TmpF = F; |
1044 | 558k | F = kInvalidFile; |
1045 | 558k | return Process::SafelyCloseFileDescriptor(TmpF); |
1046 | 558k | } |
1047 | | |
1048 | | template <typename T> |
1049 | | static std::error_code remove_directories_impl(const T &Entry, |
1050 | 30 | bool IgnoreErrors) { |
1051 | 30 | std::error_code EC; |
1052 | 30 | directory_iterator Begin(Entry, EC, false); |
1053 | 30 | directory_iterator End; |
1054 | 67 | while (Begin != End) { |
1055 | 37 | auto &Item = *Begin; |
1056 | 37 | ErrorOr<basic_file_status> st = Item.status(); |
1057 | 37 | if (!st && !IgnoreErrors0 ) |
1058 | 0 | return st.getError(); |
1059 | 37 | |
1060 | 37 | if (is_directory(*st)) { |
1061 | 17 | EC = remove_directories_impl(Item, IgnoreErrors); |
1062 | 17 | if (EC && !IgnoreErrors0 ) |
1063 | 0 | return EC; |
1064 | 37 | } |
1065 | 37 | |
1066 | 37 | EC = fs::remove(Item.path(), true); |
1067 | 37 | if (EC && !IgnoreErrors0 ) |
1068 | 0 | return EC; |
1069 | 37 | |
1070 | 37 | Begin.increment(EC); |
1071 | 37 | if (EC && !IgnoreErrors0 ) |
1072 | 0 | return EC; |
1073 | 37 | } |
1074 | 30 | return std::error_code(); |
1075 | 30 | } Path.cpp:std::__1::error_code llvm::sys::fs::remove_directories_impl<llvm::Twine>(llvm::Twine const&, bool) Line | Count | Source | 1050 | 13 | bool IgnoreErrors) { | 1051 | 13 | std::error_code EC; | 1052 | 13 | directory_iterator Begin(Entry, EC, false); | 1053 | 13 | directory_iterator End; | 1054 | 26 | while (Begin != End) { | 1055 | 13 | auto &Item = *Begin; | 1056 | 13 | ErrorOr<basic_file_status> st = Item.status(); | 1057 | 13 | if (!st && !IgnoreErrors0 ) | 1058 | 0 | return st.getError(); | 1059 | 13 | | 1060 | 13 | if (is_directory(*st)) { | 1061 | 10 | EC = remove_directories_impl(Item, IgnoreErrors); | 1062 | 10 | if (EC && !IgnoreErrors0 ) | 1063 | 0 | return EC; | 1064 | 13 | } | 1065 | 13 | | 1066 | 13 | EC = fs::remove(Item.path(), true); | 1067 | 13 | if (EC && !IgnoreErrors0 ) | 1068 | 0 | return EC; | 1069 | 13 | | 1070 | 13 | Begin.increment(EC); | 1071 | 13 | if (EC && !IgnoreErrors0 ) | 1072 | 0 | return EC; | 1073 | 13 | } | 1074 | 13 | return std::error_code(); | 1075 | 13 | } |
Path.cpp:std::__1::error_code llvm::sys::fs::remove_directories_impl<llvm::sys::fs::directory_entry>(llvm::sys::fs::directory_entry const&, bool) Line | Count | Source | 1050 | 17 | bool IgnoreErrors) { | 1051 | 17 | std::error_code EC; | 1052 | 17 | directory_iterator Begin(Entry, EC, false); | 1053 | 17 | directory_iterator End; | 1054 | 41 | while (Begin != End) { | 1055 | 24 | auto &Item = *Begin; | 1056 | 24 | ErrorOr<basic_file_status> st = Item.status(); | 1057 | 24 | if (!st && !IgnoreErrors0 ) | 1058 | 0 | return st.getError(); | 1059 | 24 | | 1060 | 24 | if (is_directory(*st)) { | 1061 | 7 | EC = remove_directories_impl(Item, IgnoreErrors); | 1062 | 7 | if (EC && !IgnoreErrors0 ) | 1063 | 0 | return EC; | 1064 | 24 | } | 1065 | 24 | | 1066 | 24 | EC = fs::remove(Item.path(), true); | 1067 | 24 | if (EC && !IgnoreErrors0 ) | 1068 | 0 | return EC; | 1069 | 24 | | 1070 | 24 | Begin.increment(EC); | 1071 | 24 | if (EC && !IgnoreErrors0 ) | 1072 | 0 | return EC; | 1073 | 24 | } | 1074 | 17 | return std::error_code(); | 1075 | 17 | } |
|
1076 | | |
1077 | 13 | std::error_code remove_directories(const Twine &path, bool IgnoreErrors) { |
1078 | 13 | auto EC = remove_directories_impl(path, IgnoreErrors); |
1079 | 13 | if (EC && !IgnoreErrors0 ) |
1080 | 0 | return EC; |
1081 | 13 | EC = fs::remove(path, true); |
1082 | 13 | if (EC && !IgnoreErrors0 ) |
1083 | 0 | return EC; |
1084 | 13 | return std::error_code(); |
1085 | 13 | } |
1086 | | |
1087 | | std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest, |
1088 | 25.3k | bool expand_tilde) { |
1089 | 25.3k | dest.clear(); |
1090 | 25.3k | if (path.isTriviallyEmpty()) |
1091 | 0 | return std::error_code(); |
1092 | 25.3k | |
1093 | 25.3k | if (expand_tilde) { |
1094 | 29 | SmallString<128> Storage; |
1095 | 29 | path.toVector(Storage); |
1096 | 29 | expandTildeExpr(Storage); |
1097 | 29 | return real_path(Storage, dest, false); |
1098 | 29 | } |
1099 | 25.2k | |
1100 | 25.2k | SmallString<128> Storage; |
1101 | 25.2k | StringRef P = path.toNullTerminatedStringRef(Storage); |
1102 | 25.2k | char Buffer[PATH_MAX]; |
1103 | 25.2k | if (::realpath(P.begin(), Buffer) == nullptr) |
1104 | 41 | return std::error_code(errno, std::generic_category()); |
1105 | 25.2k | dest.append(Buffer, Buffer + strlen(Buffer)); |
1106 | 25.2k | return std::error_code(); |
1107 | 25.2k | } |
1108 | | |
1109 | | } // end namespace fs |
1110 | | |
1111 | | namespace path { |
1112 | | |
1113 | 30 | bool home_directory(SmallVectorImpl<char> &result) { |
1114 | 30 | char *RequestedDir = getenv("HOME"); |
1115 | 30 | if (!RequestedDir) { |
1116 | 23 | struct passwd *pw = getpwuid(getuid()); |
1117 | 23 | if (pw && pw->pw_dir) |
1118 | 23 | RequestedDir = pw->pw_dir; |
1119 | 23 | } |
1120 | 30 | if (!RequestedDir) |
1121 | 0 | return false; |
1122 | 30 | |
1123 | 30 | result.clear(); |
1124 | 30 | result.append(RequestedDir, RequestedDir + strlen(RequestedDir)); |
1125 | 30 | return true; |
1126 | 30 | } |
1127 | | |
1128 | 106 | static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) { |
1129 | 106 | #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR) |
1130 | 106 | // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR. |
1131 | 106 | // macros defined in <unistd.h> on darwin >= 9 |
1132 | 106 | int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR |
1133 | 106 | : _CS_DARWIN_USER_CACHE_DIR; |
1134 | 106 | size_t ConfLen = confstr(ConfName, nullptr, 0); |
1135 | 106 | if (ConfLen > 0) { |
1136 | 106 | do { |
1137 | 106 | Result.resize(ConfLen); |
1138 | 106 | ConfLen = confstr(ConfName, Result.data(), Result.size()); |
1139 | 106 | } while (ConfLen > 0 && ConfLen != Result.size()); |
1140 | 106 | |
1141 | 106 | if (ConfLen > 0) { |
1142 | 106 | assert(Result.back() == 0); |
1143 | 106 | Result.pop_back(); |
1144 | 106 | return true; |
1145 | 106 | } |
1146 | 0 | |
1147 | 0 | Result.clear(); |
1148 | 0 | } |
1149 | 106 | #endif |
1150 | 106 | return false0 ; |
1151 | 106 | } |
1152 | | |
1153 | 9.24k | static const char *getEnvTempDir() { |
1154 | 9.24k | // Check whether the temporary directory is specified by an environment |
1155 | 9.24k | // variable. |
1156 | 9.24k | const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"}; |
1157 | 9.25k | for (const char *Env : EnvironmentVariables) { |
1158 | 9.25k | if (const char *Dir = std::getenv(Env)) |
1159 | 9.24k | return Dir; |
1160 | 9.25k | } |
1161 | 9.24k | |
1162 | 9.24k | return nullptr2 ; |
1163 | 9.24k | } |
1164 | | |
1165 | 0 | static const char *getDefaultTempDir(bool ErasedOnReboot) { |
1166 | 0 | #ifdef P_tmpdir |
1167 | 0 | if ((bool)P_tmpdir) |
1168 | 0 | return P_tmpdir; |
1169 | 0 | #endif |
1170 | 0 | |
1171 | 0 | if (ErasedOnReboot) |
1172 | 0 | return "/tmp"; |
1173 | 0 | return "/var/tmp"; |
1174 | 0 | } |
1175 | | |
1176 | 9.35k | void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) { |
1177 | 9.35k | Result.clear(); |
1178 | 9.35k | |
1179 | 9.35k | if (ErasedOnReboot) { |
1180 | 9.24k | // There is no env variable for the cache directory. |
1181 | 9.24k | if (const char *RequestedDir = getEnvTempDir()) { |
1182 | 9.24k | Result.append(RequestedDir, RequestedDir + strlen(RequestedDir)); |
1183 | 9.24k | return; |
1184 | 9.24k | } |
1185 | 106 | } |
1186 | 106 | |
1187 | 106 | if (getDarwinConfDir(ErasedOnReboot, Result)) |
1188 | 106 | return; |
1189 | 0 | |
1190 | 0 | const char *RequestedDir = getDefaultTempDir(ErasedOnReboot); |
1191 | 0 | Result.append(RequestedDir, RequestedDir + strlen(RequestedDir)); |
1192 | 0 | } |
1193 | | |
1194 | | } // end namespace path |
1195 | | |
1196 | | namespace fs { |
1197 | | |
1198 | | #ifdef __APPLE__ |
1199 | | /// This implementation tries to perform an APFS CoW clone of the file, |
1200 | | /// which can be much faster and uses less space. |
1201 | | /// Unfortunately fcopyfile(3) does not support COPYFILE_CLONE, so the |
1202 | | /// file descriptor variant of this function still uses the default |
1203 | | /// implementation. |
1204 | 530 | std::error_code copy_file(const Twine &From, const Twine &To) { |
1205 | 530 | uint32_t Flag = COPYFILE_DATA; |
1206 | 530 | #if __has_builtin(__builtin_available) |
1207 | 530 | if (__builtin_available(macos 10.12, *)) { |
1208 | 530 | bool IsSymlink; |
1209 | 530 | if (std::error_code Error = is_symlink_file(From, IsSymlink)) |
1210 | 5 | return Error; |
1211 | 525 | // COPYFILE_CLONE clones the symlink instead of following it |
1212 | 525 | // and returns EEXISTS if the target file already exists. |
1213 | 525 | if (!IsSymlink && !exists(To)524 ) |
1214 | 523 | Flag = COPYFILE_CLONE; |
1215 | 525 | } |
1216 | 530 | #endif |
1217 | 530 | int Status = |
1218 | 525 | copyfile(From.str().c_str(), To.str().c_str(), /* State */ NULL, Flag); |
1219 | 525 | |
1220 | 525 | if (Status == 0) |
1221 | 524 | return std::error_code(); |
1222 | 1 | return std::error_code(errno, std::generic_category()); |
1223 | 1 | } |
1224 | | #endif // __APPLE__ |
1225 | | |
1226 | | } // end namespace fs |
1227 | | |
1228 | | } // end namespace sys |
1229 | | } // end namespace llvm |