Coverage Report

Created: 2025-12-12 07:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/hermes/external/llvh/lib/Support/Unix/Path.inc
Line
Count
Source
1
//===- llvm/Support/Unix/Path.inc - 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 Path 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"
20
#include <limits.h>
21
#include <stdio.h>
22
#if HAVE_SYS_STAT_H
23
#include <sys/stat.h>
24
#endif
25
#if HAVE_FCNTL_H
26
#include <fcntl.h>
27
#endif
28
#ifdef HAVE_UNISTD_H
29
#include <unistd.h>
30
#endif
31
#ifdef HAVE_SYS_MMAN_H
32
#include <sys/mman.h>
33
#endif
34
35
#include <dirent.h>
36
#include <pwd.h>
37
38
#ifdef __APPLE__
39
#include <mach-o/dyld.h>
40
#include <sys/attr.h>
41
#endif
42
43
// Both stdio.h and cstdio are included via different paths and
44
// stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
45
// either.
46
#undef ferror
47
#undef feof
48
49
// For GNU Hurd
50
#if defined(__GNU__) && !defined(PATH_MAX)
51
# define PATH_MAX 4096
52
#endif
53
54
#include <sys/types.h>
55
#if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__FreeBSD__) &&   \
56
    !defined(__linux__)
57
#include <sys/statvfs.h>
58
#define STATVFS statvfs
59
#define FSTATVFS fstatvfs
60
#define STATVFS_F_FRSIZE(vfs) vfs.f_frsize
61
#else
62
#if defined(__OpenBSD__) || defined(__FreeBSD__)
63
#include <sys/mount.h>
64
#include <sys/param.h>
65
#elif defined(__linux__)
66
#if defined(HAVE_LINUX_MAGIC_H)
67
#include <linux/magic.h>
68
#else
69
#if defined(HAVE_LINUX_NFS_FS_H)
70
#include <linux/nfs_fs.h>
71
#endif
72
#if defined(HAVE_LINUX_SMB_H)
73
#include <linux/smb.h>
74
#endif
75
#endif
76
#include <sys/vfs.h>
77
#else
78
#include <sys/mount.h>
79
#endif
80
0
#define STATVFS statfs
81
0
#define FSTATVFS fstatfs
82
0
#define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
83
#endif
84
85
#if defined(__NetBSD__) || defined(__EMSCRIPTEN__)
86
#define STATVFS_F_FLAG(vfs) (vfs).f_flag
87
#else
88
#define STATVFS_F_FLAG(vfs) (vfs).f_flags
89
#endif
90
91
using namespace llvh;
92
93
namespace llvh {
94
namespace sys  {
95
namespace fs {
96
97
const file_t kInvalidFile = -1;
98
99
#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) ||     \
100
    defined(__minix) || defined(__FreeBSD_kernel__) || defined(__linux__) ||   \
101
    defined(__CYGWIN__) || defined(__DragonFly__) || defined(_AIX)
102
static int
103
test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
104
0
{
105
0
  struct stat sb;
106
0
  char fullpath[PATH_MAX];
107
108
0
  snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
109
0
  if (!realpath(fullpath, ret))
110
0
    return 1;
111
0
  if (stat(fullpath, &sb) != 0)
112
0
    return 1;
113
114
0
  return 0;
115
0
}
116
117
static char *
118
getprogpath(char ret[PATH_MAX], const char *bin)
119
0
{
120
0
  char *pv, *s, *t;
121
122
  /* First approach: absolute path. */
123
0
  if (bin[0] == '/') {
124
0
    if (test_dir(ret, "/", bin) == 0)
125
0
      return ret;
126
0
    return nullptr;
127
0
  }
128
129
  /* Second approach: relative path. */
130
0
  if (strchr(bin, '/')) {
131
0
    char cwd[PATH_MAX];
132
0
    if (!getcwd(cwd, PATH_MAX))
133
0
      return nullptr;
134
0
    if (test_dir(ret, cwd, bin) == 0)
135
0
      return ret;
136
0
    return nullptr;
137
0
  }
138
139
  /* Third approach: $PATH */
140
0
  if ((pv = getenv("PATH")) == nullptr)
141
0
    return nullptr;
142
0
  s = pv = strdup(pv);
143
0
  if (!pv)
144
0
    return nullptr;
145
0
  while ((t = strsep(&s, ":")) != nullptr) {
146
0
    if (test_dir(ret, t, bin) == 0) {
147
0
      free(pv);
148
0
      return ret;
149
0
    }
150
0
  }
151
0
  free(pv);
152
0
  return nullptr;
153
0
}
154
#endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
155
156
/// GetMainExecutable - Return the path to the main executable, given the
157
/// value of argv[0] from program startup.
158
0
std::string getMainExecutable(const char *argv0, void *MainAddr) {
159
#if defined(__APPLE__)
160
  // On OS X the executable path is saved to the stack by dyld. Reading it
161
  // from there is much faster than calling dladdr, especially for large
162
  // binaries with symbols.
163
  char exe_path[MAXPATHLEN];
164
  uint32_t size = sizeof(exe_path);
165
  if (_NSGetExecutablePath(exe_path, &size) == 0) {
166
    char link_path[MAXPATHLEN];
167
    if (realpath(exe_path, link_path))
168
      return link_path;
169
  }
170
#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) ||   \
171
    defined(__minix) || defined(__DragonFly__) ||                              \
172
    defined(__FreeBSD_kernel__) || defined(_AIX)
173
  char exe_path[PATH_MAX];
174
175
  if (getprogpath(exe_path, argv0) != NULL)
176
    return exe_path;
177
#elif defined(__linux__) || defined(__CYGWIN__)
178
  char exe_path[MAXPATHLEN];
179
0
  StringRef aPath("/proc/self/exe");
180
0
  if (sys::fs::exists(aPath)) {
181
      // /proc is not always mounted under Linux (chroot for example).
182
0
      ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
183
0
      if (len >= 0)
184
0
          return std::string(exe_path, len);
185
0
  } else {
186
      // Fall back to the classical detection.
187
0
      if (getprogpath(exe_path, argv0))
188
0
        return exe_path;
189
0
  }
190
#elif defined(HAVE_DLFCN_H) && defined(HAVE_DLADDR)
191
  // Use dladdr to get executable path if available.
192
  Dl_info DLInfo;
193
  int err = dladdr(MainAddr, &DLInfo);
194
  if (err == 0)
195
    return "";
196
197
  // If the filename is a symlink, we need to resolve and return the location of
198
  // the actual executable.
199
  char link_path[MAXPATHLEN];
200
  if (realpath(DLInfo.dli_fname, link_path))
201
    return link_path;
202
#else
203
#error GetMainExecutable is not implemented on this host yet.
204
#endif
205
0
  return "";
206
0
}
207
208
0
TimePoint<> basic_file_status::getLastAccessedTime() const {
209
0
  return toTimePoint(fs_st_atime);
210
0
}
211
212
0
TimePoint<> basic_file_status::getLastModificationTime() const {
213
0
  return toTimePoint(fs_st_mtime);
214
0
}
215
216
0
UniqueID file_status::getUniqueID() const {
217
0
  return UniqueID(fs_st_dev, fs_st_ino);
218
0
}
219
220
0
uint32_t file_status::getLinkCount() const {
221
0
  return fs_st_nlinks;
222
0
}
223
224
0
ErrorOr<space_info> disk_space(const Twine &Path) {
225
0
  struct STATVFS Vfs;
226
0
  if (::STATVFS(Path.str().c_str(), &Vfs))
227
0
    return std::error_code(errno, std::generic_category());
228
0
  auto FrSize = STATVFS_F_FRSIZE(Vfs);
229
0
  space_info SpaceInfo;
230
0
  SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;
231
0
  SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize;
232
0
  SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize;
233
0
  return SpaceInfo;
234
0
}
235
236
0
std::error_code current_path(SmallVectorImpl<char> &result) {
237
0
  result.clear();
238
239
0
  const char *pwd = ::getenv("PWD");
240
0
  llvh::sys::fs::file_status PWDStatus, DotStatus;
241
0
  if (pwd && llvh::sys::path::is_absolute(pwd) &&
242
0
      !llvh::sys::fs::status(pwd, PWDStatus) &&
243
0
      !llvh::sys::fs::status(".", DotStatus) &&
244
0
      PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
245
0
    result.append(pwd, pwd + strlen(pwd));
246
0
    return std::error_code();
247
0
  }
248
249
0
#ifdef MAXPATHLEN
250
0
  result.reserve(MAXPATHLEN);
251
#else
252
// For GNU Hurd
253
  result.reserve(1024);
254
#endif
255
256
0
  while (true) {
257
0
    if (::getcwd(result.data(), result.capacity()) == nullptr) {
258
      // See if there was a real error.
259
0
      if (errno != ENOMEM)
260
0
        return std::error_code(errno, std::generic_category());
261
      // Otherwise there just wasn't enough space.
262
0
      result.reserve(result.capacity() * 2);
263
0
    } else
264
0
      break;
265
0
  }
266
267
0
  result.set_size(strlen(result.data()));
268
0
  return std::error_code();
269
0
}
270
271
0
std::error_code set_current_path(const Twine &path) {
272
0
  SmallString<128> path_storage;
273
0
  StringRef p = path.toNullTerminatedStringRef(path_storage);
274
275
0
  if (::chdir(p.begin()) == -1)
276
0
    return std::error_code(errno, std::generic_category());
277
278
0
  return std::error_code();
279
0
}
280
281
std::error_code create_directory(const Twine &path, bool IgnoreExisting,
282
0
                                 perms Perms) {
283
0
  SmallString<128> path_storage;
284
0
  StringRef p = path.toNullTerminatedStringRef(path_storage);
285
286
0
  if (::mkdir(p.begin(), Perms) == -1) {
287
0
    if (errno != EEXIST || !IgnoreExisting)
288
0
      return std::error_code(errno, std::generic_category());
289
0
  }
290
291
0
  return std::error_code();
292
0
}
293
294
// Note that we are using symbolic link because hard links are not supported by
295
// all filesystems (SMB doesn't).
296
0
std::error_code create_link(const Twine &to, const Twine &from) {
297
  // Get arguments.
298
0
  SmallString<128> from_storage;
299
0
  SmallString<128> to_storage;
300
0
  StringRef f = from.toNullTerminatedStringRef(from_storage);
301
0
  StringRef t = to.toNullTerminatedStringRef(to_storage);
302
303
0
  if (::symlink(t.begin(), f.begin()) == -1)
304
0
    return std::error_code(errno, std::generic_category());
305
306
0
  return std::error_code();
307
0
}
308
309
0
std::error_code create_hard_link(const Twine &to, const Twine &from) {
310
  // Get arguments.
311
0
  SmallString<128> from_storage;
312
0
  SmallString<128> to_storage;
313
0
  StringRef f = from.toNullTerminatedStringRef(from_storage);
314
0
  StringRef t = to.toNullTerminatedStringRef(to_storage);
315
316
0
  if (::link(t.begin(), f.begin()) == -1)
317
0
    return std::error_code(errno, std::generic_category());
318
319
0
  return std::error_code();
320
0
}
321
322
0
std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
323
0
  SmallString<128> path_storage;
324
0
  StringRef p = path.toNullTerminatedStringRef(path_storage);
325
326
0
  struct stat buf;
327
0
  if (lstat(p.begin(), &buf) != 0) {
328
0
    if (errno != ENOENT || !IgnoreNonExisting)
329
0
      return std::error_code(errno, std::generic_category());
330
0
    return std::error_code();
331
0
  }
332
333
  // Note: this check catches strange situations. In all cases, LLVM should
334
  // only be involved in the creation and deletion of regular files.  This
335
  // check ensures that what we're trying to erase is a regular file. It
336
  // effectively prevents LLVM from erasing things like /dev/null, any block
337
  // special file, or other things that aren't "regular" files.
338
0
  if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
339
0
    return make_error_code(errc::operation_not_permitted);
340
341
0
  if (::remove(p.begin()) == -1) {
342
0
    if (errno != ENOENT || !IgnoreNonExisting)
343
0
      return std::error_code(errno, std::generic_category());
344
0
  }
345
346
0
  return std::error_code();
347
0
}
348
349
0
static bool is_local_impl(struct STATVFS &Vfs) {
350
0
#if defined(__linux__)
351
0
#ifndef NFS_SUPER_MAGIC
352
0
#define NFS_SUPER_MAGIC 0x6969
353
0
#endif
354
0
#ifndef SMB_SUPER_MAGIC
355
0
#define SMB_SUPER_MAGIC 0x517B
356
0
#endif
357
0
#ifndef CIFS_MAGIC_NUMBER
358
0
#define CIFS_MAGIC_NUMBER 0xFF534D42
359
0
#endif
360
0
  switch ((uint32_t)Vfs.f_type) {
361
0
  case NFS_SUPER_MAGIC:
362
0
  case SMB_SUPER_MAGIC:
363
0
  case CIFS_MAGIC_NUMBER:
364
0
    return false;
365
0
  default:
366
0
    return true;
367
0
  }
368
#elif defined(__CYGWIN__)
369
  // Cygwin doesn't expose this information; would need to use Win32 API.
370
  return false;
371
#elif defined(__Fuchsia__)
372
  // Fuchsia doesn't yet support remote filesystem mounts.
373
  return true;
374
#elif defined(__HAIKU__)
375
  // Haiku doesn't expose this information.
376
  return false;
377
#elif defined(__sun)
378
  // statvfs::f_basetype contains a null-terminated FSType name of the mounted target
379
  StringRef fstype(Vfs.f_basetype);
380
  // NFS is the only non-local fstype??
381
  return !fstype.equals("nfs");
382
#elif defined(__EMSCRIPTEN__)
383
  return false;
384
#else
385
  return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
386
#endif
387
0
}
388
389
0
std::error_code is_local(const Twine &Path, bool &Result) {
390
0
  struct STATVFS Vfs;
391
0
  if (::STATVFS(Path.str().c_str(), &Vfs))
392
0
    return std::error_code(errno, std::generic_category());
393
394
0
  Result = is_local_impl(Vfs);
395
0
  return std::error_code();
396
0
}
397
398
0
std::error_code is_local(int FD, bool &Result) {
399
0
  struct STATVFS Vfs;
400
0
  if (::FSTATVFS(FD, &Vfs))
401
0
    return std::error_code(errno, std::generic_category());
402
403
0
  Result = is_local_impl(Vfs);
404
0
  return std::error_code();
405
0
}
406
407
0
std::error_code rename(const Twine &from, const Twine &to) {
408
  // Get arguments.
409
0
  SmallString<128> from_storage;
410
0
  SmallString<128> to_storage;
411
0
  StringRef f = from.toNullTerminatedStringRef(from_storage);
412
0
  StringRef t = to.toNullTerminatedStringRef(to_storage);
413
414
0
  if (::rename(f.begin(), t.begin()) == -1)
415
0
    return std::error_code(errno, std::generic_category());
416
417
0
  return std::error_code();
418
0
}
419
420
0
std::error_code resize_file(int FD, uint64_t Size) {
421
0
#if defined(HAVE_POSIX_FALLOCATE)
422
  // If we have posix_fallocate use it. Unlike ftruncate it always allocates
423
  // space, so we get an error if the disk is full.
424
0
  if (int Err = ::posix_fallocate(FD, 0, Size)) {
425
0
    if (Err != EINVAL && Err != EOPNOTSUPP)
426
0
      return std::error_code(Err, std::generic_category());
427
0
  }
428
0
#endif
429
  // Use ftruncate as a fallback. It may or may not allocate space. At least on
430
  // OS X with HFS+ it does.
431
0
  if (::ftruncate(FD, Size) == -1)
432
0
    return std::error_code(errno, std::generic_category());
433
434
0
  return std::error_code();
435
0
}
436
437
0
static int convertAccessMode(AccessMode Mode) {
438
0
  switch (Mode) {
439
0
  case AccessMode::Exist:
440
0
    return F_OK;
441
0
  case AccessMode::Write:
442
0
    return W_OK;
443
0
  case AccessMode::Execute:
444
0
    return R_OK | X_OK; // scripts also need R_OK.
445
0
  }
446
0
  llvm_unreachable("invalid enum");
447
0
}
448
449
0
std::error_code access(const Twine &Path, AccessMode Mode) {
450
0
  SmallString<128> PathStorage;
451
0
  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
452
453
0
  if (::access(P.begin(), convertAccessMode(Mode)) == -1)
454
0
    return std::error_code(errno, std::generic_category());
455
456
0
  if (Mode == AccessMode::Execute) {
457
    // Don't say that directories are executable.
458
0
    struct stat buf;
459
0
    if (0 != stat(P.begin(), &buf))
460
0
      return errc::permission_denied;
461
0
    if (!S_ISREG(buf.st_mode))
462
0
      return errc::permission_denied;
463
0
  }
464
465
0
  return std::error_code();
466
0
}
467
468
0
bool can_execute(const Twine &Path) {
469
0
  return !access(Path, AccessMode::Execute);
470
0
}
471
472
0
bool equivalent(file_status A, file_status B) {
473
0
  assert(status_known(A) && status_known(B));
474
0
  return A.fs_st_dev == B.fs_st_dev &&
475
0
         A.fs_st_ino == B.fs_st_ino;
476
0
}
477
478
0
std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
479
0
  file_status fsA, fsB;
480
0
  if (std::error_code ec = status(A, fsA))
481
0
    return ec;
482
0
  if (std::error_code ec = status(B, fsB))
483
0
    return ec;
484
0
  result = equivalent(fsA, fsB);
485
0
  return std::error_code();
486
0
}
487
488
0
static void expandTildeExpr(SmallVectorImpl<char> &Path) {
489
0
  StringRef PathStr(Path.begin(), Path.size());
490
0
  if (PathStr.empty() || !PathStr.startswith("~"))
491
0
    return;
492
493
0
  PathStr = PathStr.drop_front();
494
0
  StringRef Expr =
495
0
      PathStr.take_until([](char c) { return path::is_separator(c); });
496
0
  StringRef Remainder = PathStr.substr(Expr.size() + 1);
497
0
  SmallString<128> Storage;
498
0
  if (Expr.empty()) {
499
    // This is just ~/..., resolve it to the current user's home dir.
500
0
    if (!path::home_directory(Storage)) {
501
      // For some reason we couldn't get the home directory.  Just exit.
502
0
      return;
503
0
    }
504
505
    // Overwrite the first character and insert the rest.
506
0
    Path[0] = Storage[0];
507
0
    Path.insert(Path.begin() + 1, Storage.begin() + 1, Storage.end());
508
0
    return;
509
0
  }
510
511
  // This is a string of the form ~username/, look up this user's entry in the
512
  // password database.
513
0
  struct passwd *Entry = nullptr;
514
0
  std::string User = Expr.str();
515
0
  Entry = ::getpwnam(User.c_str());
516
517
0
  if (!Entry) {
518
    // Unable to look up the entry, just return back the original path.
519
0
    return;
520
0
  }
521
522
0
  Storage = Remainder;
523
0
  Path.clear();
524
0
  Path.append(Entry->pw_dir, Entry->pw_dir + strlen(Entry->pw_dir));
525
0
  llvh::sys::path::append(Path, Storage);
526
0
}
527
528
0
static file_type typeForMode(mode_t Mode) {
529
0
  if (S_ISDIR(Mode))
530
0
    return file_type::directory_file;
531
0
  else if (S_ISREG(Mode))
532
0
    return file_type::regular_file;
533
0
  else if (S_ISBLK(Mode))
534
0
    return file_type::block_file;
535
0
  else if (S_ISCHR(Mode))
536
0
    return file_type::character_file;
537
0
  else if (S_ISFIFO(Mode))
538
0
    return file_type::fifo_file;
539
0
  else if (S_ISSOCK(Mode))
540
0
    return file_type::socket_file;
541
0
  else if (S_ISLNK(Mode))
542
0
    return file_type::symlink_file;
543
0
  return file_type::type_unknown;
544
0
}
545
546
static std::error_code fillStatus(int StatRet, const struct stat &Status,
547
0
                                  file_status &Result) {
548
0
  if (StatRet != 0) {
549
0
    std::error_code EC(errno, std::generic_category());
550
0
    if (EC == errc::no_such_file_or_directory)
551
0
      Result = file_status(file_type::file_not_found);
552
0
    else
553
0
      Result = file_status(file_type::status_error);
554
0
    return EC;
555
0
  }
556
557
0
  perms Perms = static_cast<perms>(Status.st_mode) & all_perms;
558
0
  Result = file_status(typeForMode(Status.st_mode), Perms, Status.st_dev,
559
0
                       Status.st_nlink, Status.st_ino, Status.st_atime,
560
0
                       Status.st_mtime, Status.st_uid, Status.st_gid,
561
0
                       Status.st_size);
562
563
0
  return std::error_code();
564
0
}
565
566
0
std::error_code status(const Twine &Path, file_status &Result, bool Follow) {
567
0
  SmallString<128> PathStorage;
568
0
  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
569
570
0
  struct stat Status;
571
0
  int StatRet = (Follow ? ::stat : ::lstat)(P.begin(), &Status);
572
0
  return fillStatus(StatRet, Status, Result);
573
0
}
574
575
0
std::error_code status(int FD, file_status &Result) {
576
0
  struct stat Status;
577
0
  int StatRet = ::fstat(FD, &Status);
578
0
  return fillStatus(StatRet, Status, Result);
579
0
}
580
581
0
std::error_code setPermissions(const Twine &Path, perms Permissions) {
582
0
  SmallString<128> PathStorage;
583
0
  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
584
585
0
  if (::chmod(P.begin(), Permissions))
586
0
    return std::error_code(errno, std::generic_category());
587
0
  return std::error_code();
588
0
}
589
590
std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
591
0
                                                 TimePoint<> ModificationTime) {
592
0
#if defined(HAVE_FUTIMENS)
593
0
  timespec Times[2];
594
0
  Times[0] = sys::toTimeSpec(AccessTime);
595
0
  Times[1] = sys::toTimeSpec(ModificationTime);
596
0
  if (::futimens(FD, Times))
597
0
    return std::error_code(errno, std::generic_category());
598
0
  return std::error_code();
599
#elif defined(HAVE_FUTIMES)
600
  timeval Times[2];
601
  Times[0] = sys::toTimeVal(
602
      std::chrono::time_point_cast<std::chrono::microseconds>(AccessTime));
603
  Times[1] =
604
      sys::toTimeVal(std::chrono::time_point_cast<std::chrono::microseconds>(
605
          ModificationTime));
606
  if (::futimes(FD, Times))
607
    return std::error_code(errno, std::generic_category());
608
  return std::error_code();
609
#else
610
#warning Missing futimes() and futimens()
611
  return make_error_code(errc::function_not_supported);
612
#endif
613
0
}
614
615
std::error_code mapped_file_region::init(int FD, uint64_t Offset,
616
0
                                         mapmode Mode) {
617
0
  assert(Size != 0);
618
619
0
  int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
620
0
  int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
621
#if defined(__APPLE__)
622
  //----------------------------------------------------------------------
623
  // Newer versions of MacOSX have a flag that will allow us to read from
624
  // binaries whose code signature is invalid without crashing by using
625
  // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media
626
  // is mapped we can avoid crashing and return zeroes to any pages we try
627
  // to read if the media becomes unavailable by using the
628
  // MAP_RESILIENT_MEDIA flag.  These flags are only usable when mapping
629
  // with PROT_READ, so take care not to specify them otherwise.
630
  //----------------------------------------------------------------------
631
  if (Mode == readonly) {
632
#if defined(MAP_RESILIENT_CODESIGN)
633
    flags |= MAP_RESILIENT_CODESIGN;
634
#endif
635
#if defined(MAP_RESILIENT_MEDIA)
636
    flags |= MAP_RESILIENT_MEDIA;
637
#endif
638
  }
639
#endif // #if defined (__APPLE__)
640
641
0
  Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
642
0
  if (Mapping == MAP_FAILED)
643
0
    return std::error_code(errno, std::generic_category());
644
0
  return std::error_code();
645
0
}
646
647
mapped_file_region::mapped_file_region(int fd, mapmode mode, size_t length,
648
                                       uint64_t offset, std::error_code &ec)
649
0
    : Size(length), Mapping(), Mode(mode) {
650
0
  (void)Mode;
651
0
  ec = init(fd, offset, mode);
652
0
  if (ec)
653
0
    Mapping = nullptr;
654
0
}
655
656
0
mapped_file_region::~mapped_file_region() {
657
0
  if (Mapping)
658
0
    ::munmap(Mapping, Size);
659
0
}
660
661
0
size_t mapped_file_region::size() const {
662
0
  assert(Mapping && "Mapping failed but used anyway!");
663
0
  return Size;
664
0
}
665
666
0
char *mapped_file_region::data() const {
667
0
  assert(Mapping && "Mapping failed but used anyway!");
668
0
  return reinterpret_cast<char*>(Mapping);
669
0
}
670
671
0
const char *mapped_file_region::const_data() const {
672
0
  assert(Mapping && "Mapping failed but used anyway!");
673
0
  return reinterpret_cast<const char*>(Mapping);
674
0
}
675
676
0
int mapped_file_region::alignment() {
677
0
  return Process::getPageSize();
678
0
}
679
680
std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
681
                                                     StringRef path,
682
0
                                                     bool follow_symlinks) {
683
0
  SmallString<128> path_null(path);
684
0
  DIR *directory = ::opendir(path_null.c_str());
685
0
  if (!directory)
686
0
    return std::error_code(errno, std::generic_category());
687
688
0
  it.IterationHandle = reinterpret_cast<intptr_t>(directory);
689
  // Add something for replace_filename to replace.
690
0
  path::append(path_null, ".");
691
0
  it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks);
692
0
  return directory_iterator_increment(it);
693
0
}
694
695
0
std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
696
0
  if (it.IterationHandle)
697
0
    ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
698
0
  it.IterationHandle = 0;
699
0
  it.CurrentEntry = directory_entry();
700
0
  return std::error_code();
701
0
}
702
703
0
static file_type direntType(dirent* Entry) {
704
  // Most platforms provide the file type in the dirent: Linux/BSD/Mac.
705
  // The DTTOIF macro lets us reuse our status -> type conversion.
706
0
#if defined(_DIRENT_HAVE_D_TYPE) && defined(DTTOIF)
707
0
  return typeForMode(DTTOIF(Entry->d_type));
708
#else
709
  // Other platforms such as Solaris require a stat() to get the type.
710
  return file_type::type_unknown;
711
#endif
712
0
}
713
714
0
std::error_code detail::directory_iterator_increment(detail::DirIterState &It) {
715
0
  errno = 0;
716
0
  dirent *CurDir = ::readdir(reinterpret_cast<DIR *>(It.IterationHandle));
717
0
  if (CurDir == nullptr && errno != 0) {
718
0
    return std::error_code(errno, std::generic_category());
719
0
  } else if (CurDir != nullptr) {
720
0
    StringRef Name(CurDir->d_name);
721
0
    if ((Name.size() == 1 && Name[0] == '.') ||
722
0
        (Name.size() == 2 && Name[0] == '.' && Name[1] == '.'))
723
0
      return directory_iterator_increment(It);
724
0
    It.CurrentEntry.replace_filename(Name, direntType(CurDir));
725
0
  } else
726
0
    return directory_iterator_destruct(It);
727
728
0
  return std::error_code();
729
0
}
730
731
0
ErrorOr<basic_file_status> directory_entry::status() const {
732
0
  file_status s;
733
0
  if (auto EC = fs::status(Path, s, FollowSymlinks))
734
0
    return EC;
735
0
  return s;
736
0
}
737
738
#if !defined(F_GETPATH)
739
0
static bool hasProcSelfFD() {
740
  // If we have a /proc filesystem mounted, we can quickly establish the
741
  // real name of the file with readlink
742
0
  static const bool Result = (::access("/proc/self/fd", R_OK) == 0);
743
0
  return Result;
744
0
}
745
#endif
746
747
static int nativeOpenFlags(CreationDisposition Disp, OpenFlags Flags,
748
0
                           FileAccess Access) {
749
0
  int Result = 0;
750
0
  if (Access == FA_Read)
751
0
    Result |= O_RDONLY;
752
0
  else if (Access == FA_Write)
753
0
    Result |= O_WRONLY;
754
0
  else if (Access == (FA_Read | FA_Write))
755
0
    Result |= O_RDWR;
756
757
  // This is for compatibility with old code that assumed F_Append implied
758
  // would open an existing file.  See Windows/Path.inc for a longer comment.
759
0
  if (Flags & F_Append)
760
0
    Disp = CD_OpenAlways;
761
762
0
  if (Disp == CD_CreateNew) {
763
0
    Result |= O_CREAT; // Create if it doesn't exist.
764
0
    Result |= O_EXCL;  // Fail if it does.
765
0
  } else if (Disp == CD_CreateAlways) {
766
0
    Result |= O_CREAT; // Create if it doesn't exist.
767
0
    Result |= O_TRUNC; // Truncate if it does.
768
0
  } else if (Disp == CD_OpenAlways) {
769
0
    Result |= O_CREAT; // Create if it doesn't exist.
770
0
  } else if (Disp == CD_OpenExisting) {
771
    // Nothing special, just don't add O_CREAT and we get these semantics.
772
0
  }
773
774
0
  if (Flags & F_Append)
775
0
    Result |= O_APPEND;
776
777
0
#ifdef O_CLOEXEC
778
0
  if (!(Flags & OF_ChildInherit))
779
0
    Result |= O_CLOEXEC;
780
0
#endif
781
782
0
  return Result;
783
0
}
784
785
std::error_code openFile(const Twine &Name, int &ResultFD,
786
                         CreationDisposition Disp, FileAccess Access,
787
0
                         OpenFlags Flags, unsigned Mode) {
788
0
  int OpenFlags = nativeOpenFlags(Disp, Flags, Access);
789
790
0
  SmallString<128> Storage;
791
0
  StringRef P = Name.toNullTerminatedStringRef(Storage);
792
  // Call ::open in a lambda to avoid overload resolution in RetryAfterSignal
793
  // when open is overloaded, such as in Bionic.
794
0
  auto Open = [&]() { return ::open(P.begin(), OpenFlags, Mode); };
795
0
  if ((ResultFD = sys::RetryAfterSignal(-1, Open)) < 0)
796
0
    return std::error_code(errno, std::generic_category());
797
#ifndef O_CLOEXEC
798
  if (!(Flags & OF_ChildInherit)) {
799
    int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
800
    (void)r;
801
    assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
802
  }
803
#endif
804
0
  return std::error_code();
805
0
}
806
807
Expected<int> openNativeFile(const Twine &Name, CreationDisposition Disp,
808
                             FileAccess Access, OpenFlags Flags,
809
0
                             unsigned Mode) {
810
811
0
  int FD;
812
0
  std::error_code EC = openFile(Name, FD, Disp, Access, Flags, Mode);
813
0
  if (EC)
814
0
    return errorCodeToError(EC);
815
0
  return FD;
816
0
}
817
818
std::error_code openFileForRead(const Twine &Name, int &ResultFD,
819
                                OpenFlags Flags,
820
0
                                SmallVectorImpl<char> *RealPath) {
821
0
  std::error_code EC =
822
0
      openFile(Name, ResultFD, CD_OpenExisting, FA_Read, Flags, 0666);
823
0
  if (EC)
824
0
    return EC;
825
826
  // Attempt to get the real name of the file, if the user asked
827
0
  if(!RealPath)
828
0
    return std::error_code();
829
0
  RealPath->clear();
830
#if defined(F_GETPATH)
831
  // When F_GETPATH is availble, it is the quickest way to get
832
  // the real path name.
833
  char Buffer[MAXPATHLEN];
834
  if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
835
    RealPath->append(Buffer, Buffer + strlen(Buffer));
836
#else
837
0
  char Buffer[PATH_MAX];
838
0
  if (hasProcSelfFD()) {
839
0
    char ProcPath[64];
840
0
    snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
841
0
    ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
842
0
    if (CharCount > 0)
843
0
      RealPath->append(Buffer, Buffer + CharCount);
844
0
  } else {
845
0
    SmallString<128> Storage;
846
0
    StringRef P = Name.toNullTerminatedStringRef(Storage);
847
848
    // Use ::realpath to get the real path name
849
0
    if (::realpath(P.begin(), Buffer) != nullptr)
850
0
      RealPath->append(Buffer, Buffer + strlen(Buffer));
851
0
  }
852
0
#endif
853
0
  return std::error_code();
854
0
}
855
856
Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
857
0
                                       SmallVectorImpl<char> *RealPath) {
858
0
  file_t ResultFD;
859
0
  std::error_code EC = openFileForRead(Name, ResultFD, Flags, RealPath);
860
0
  if (EC)
861
0
    return errorCodeToError(EC);
862
0
  return ResultFD;
863
0
}
864
865
0
void closeFile(file_t &F) {
866
0
  ::close(F);
867
0
  F = kInvalidFile;
868
0
}
869
870
template <typename T>
871
static std::error_code remove_directories_impl(const T &Entry,
872
0
                                               bool IgnoreErrors) {
873
0
  std::error_code EC;
874
0
  directory_iterator Begin(Entry, EC, false);
875
0
  directory_iterator End;
876
0
  while (Begin != End) {
877
0
    auto &Item = *Begin;
878
0
    ErrorOr<basic_file_status> st = Item.status();
879
0
    if (!st && !IgnoreErrors)
880
0
      return st.getError();
881
882
0
    if (is_directory(*st)) {
883
0
      EC = remove_directories_impl(Item, IgnoreErrors);
884
0
      if (EC && !IgnoreErrors)
885
0
        return EC;
886
0
    }
887
888
0
    EC = fs::remove(Item.path(), true);
889
0
    if (EC && !IgnoreErrors)
890
0
      return EC;
891
892
0
    Begin.increment(EC);
893
0
    if (EC && !IgnoreErrors)
894
0
      return EC;
895
0
  }
896
0
  return std::error_code();
897
0
}
Unexecuted instantiation: Path.cpp:std::__1::error_code llvh::sys::fs::remove_directories_impl<llvh::Twine>(llvh::Twine const&, bool)
Unexecuted instantiation: Path.cpp:std::__1::error_code llvh::sys::fs::remove_directories_impl<llvh::sys::fs::directory_entry>(llvh::sys::fs::directory_entry const&, bool)
898
899
0
std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
900
0
  auto EC = remove_directories_impl(path, IgnoreErrors);
901
0
  if (EC && !IgnoreErrors)
902
0
    return EC;
903
0
  EC = fs::remove(path, true);
904
0
  if (EC && !IgnoreErrors)
905
0
    return EC;
906
0
  return std::error_code();
907
0
}
908
909
std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
910
0
                          bool expand_tilde) {
911
0
  dest.clear();
912
0
  if (path.isTriviallyEmpty())
913
0
    return std::error_code();
914
915
0
  if (expand_tilde) {
916
0
    SmallString<128> Storage;
917
0
    path.toVector(Storage);
918
0
    expandTildeExpr(Storage);
919
0
    return real_path(Storage, dest, false);
920
0
  }
921
922
0
  SmallString<128> Storage;
923
0
  StringRef P = path.toNullTerminatedStringRef(Storage);
924
0
  char Buffer[PATH_MAX];
925
0
  if (::realpath(P.begin(), Buffer) == nullptr)
926
0
    return std::error_code(errno, std::generic_category());
927
0
  dest.append(Buffer, Buffer + strlen(Buffer));
928
0
  return std::error_code();
929
0
}
930
931
} // end namespace fs
932
933
namespace path {
934
935
0
bool home_directory(SmallVectorImpl<char> &result) {
936
0
  char *RequestedDir = getenv("HOME");
937
0
  if (!RequestedDir) {
938
0
    struct passwd *pw = getpwuid(getuid());
939
0
    if (pw && pw->pw_dir)
940
0
      RequestedDir = pw->pw_dir;
941
0
  }
942
0
  if (!RequestedDir)
943
0
    return false;
944
945
0
  result.clear();
946
0
  result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
947
0
  return true;
948
0
}
949
950
0
static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
951
  #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
952
  // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
953
  // macros defined in <unistd.h> on darwin >= 9
954
  int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
955
                         : _CS_DARWIN_USER_CACHE_DIR;
956
  size_t ConfLen = confstr(ConfName, nullptr, 0);
957
  if (ConfLen > 0) {
958
    do {
959
      Result.resize(ConfLen);
960
      ConfLen = confstr(ConfName, Result.data(), Result.size());
961
    } while (ConfLen > 0 && ConfLen != Result.size());
962
963
    if (ConfLen > 0) {
964
      assert(Result.back() == 0);
965
      Result.pop_back();
966
      return true;
967
    }
968
969
    Result.clear();
970
  }
971
  #endif
972
0
  return false;
973
0
}
974
975
0
static const char *getEnvTempDir() {
976
  // Check whether the temporary directory is specified by an environment
977
  // variable.
978
0
  const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
979
0
  for (const char *Env : EnvironmentVariables) {
980
0
    if (const char *Dir = std::getenv(Env))
981
0
      return Dir;
982
0
  }
983
984
0
  return nullptr;
985
0
}
986
987
0
static const char *getDefaultTempDir(bool ErasedOnReboot) {
988
0
#ifdef P_tmpdir
989
0
  if ((bool)P_tmpdir)
990
0
    return P_tmpdir;
991
0
#endif
992
993
0
  if (ErasedOnReboot)
994
0
    return "/tmp";
995
0
  return "/var/tmp";
996
0
}
997
998
0
void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
999
0
  Result.clear();
1000
1001
0
  if (ErasedOnReboot) {
1002
    // There is no env variable for the cache directory.
1003
0
    if (const char *RequestedDir = getEnvTempDir()) {
1004
0
      Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1005
0
      return;
1006
0
    }
1007
0
  }
1008
1009
0
  if (getDarwinConfDir(ErasedOnReboot, Result))
1010
0
    return;
1011
1012
0
  const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
1013
0
  Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1014
0
}
1015
1016
} // end namespace path
1017
1018
} // end namespace sys
1019
} // end namespace llvh