35#include <mach-o/dyld.h>
37#if __has_include(<sys/clonefile.h>)
38#include <sys/clonefile.h>
40#elif defined(__FreeBSD__)
42#if __FreeBSD_version >= 1300057
45#include <machine/elf.h>
48#elif defined(__DragonFly__)
66#define PATH_MAX _XOPEN_PATH_MAX
71#if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && \
72 !defined(__linux__) && !defined(__FreeBSD_kernel__) && !defined(_AIX) && \
73 !defined(__managarm__)
74#include <sys/statvfs.h>
75#define STATVFS statvfs
76#define FSTATVFS fstatvfs
77#define STATVFS_F_FRSIZE(vfs) vfs.f_frsize
79#if defined(__OpenBSD__) || defined(__FreeBSD__)
82#elif defined(__linux__) || defined(__managarm__)
83#if defined(HAVE_LINUX_MAGIC_H)
84#include <linux/magic.h>
86#if defined(HAVE_LINUX_NFS_FS_H)
87#include <linux/nfs_fs.h>
89#if defined(HAVE_LINUX_SMB_H)
95#include <sys/statfs.h>
101#include <sys/vmount.h>
103#include <sys/mount.h>
105#define STATVFS statfs
106#define FSTATVFS fstatfs
107#define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
110#if defined(__NetBSD__) || defined(__DragonFly__) || defined(__GNU__) || \
112#define STATVFS_F_FLAG(vfs) (vfs).f_flag
114#define STATVFS_F_FLAG(vfs) (vfs).f_flags
125#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \
126 defined(__FreeBSD_kernel__) || defined(__linux__) || \
127 defined(__CYGWIN__) || defined(__DragonFly__) || defined(_AIX) || \
128 defined(__GNU__) || \
129 (defined(__sun__) && defined(__svr4__) || defined(__HAIKU__)) || \
130 defined(__managarm__)
131static int test_dir(
char ret[
PATH_MAX],
const char *dir,
const char *bin) {
135 int chars = snprintf(fullpath,
PATH_MAX,
"%s/%s", dir, bin);
140 if (!realpath(fullpath, ret))
142 if (stat(fullpath, &sb) != 0)
148static char *getprogpath(
char ret[
PATH_MAX],
const char *bin) {
154 if (test_dir(ret,
"/", bin) == 0)
160 if (strchr(bin,
'/')) {
164 if (test_dir(ret, cwd, bin) == 0)
171 if ((pv = getenv(
"PATH")) ==
nullptr)
173 char *s = strdup(pv);
177 for (
char *t = strtok_r(s,
":", &state); t !=
nullptr;
178 t = strtok_r(
nullptr,
":", &state)) {
179 if (test_dir(ret, t, bin) == 0) {
192#if defined(__APPLE__)
197 uint32_t
size =
sizeof(exe_path);
198 if (_NSGetExecutablePath(exe_path, &
size) == 0) {
200 if (realpath(exe_path, link_path))
203#elif defined(__FreeBSD__)
209#if __FreeBSD_version >= 1300057
210 if (elf_aux_info(AT_EXECPATH, exe_path,
sizeof(exe_path)) == 0) {
212 if (realpath(exe_path, link_path))
219 char **
p = ::environ;
223 for (Elf_Auxinfo *aux = (Elf_Auxinfo *)p; aux->a_type != AT_NULL; aux++) {
224 if (aux->a_type == AT_EXECPATH) {
226 if (realpath((
char *)aux->a_un.a_ptr, link_path))
232 if (getprogpath(exe_path, argv0) != NULL)
234#elif defined(_AIX) || defined(__DragonFly__) || defined(__FreeBSD_kernel__) || \
236 const char *curproc =
"/proc/curproc/file";
239 ssize_t len = readlink(curproc, exe_path,
sizeof(exe_path));
243 len = std::min(len, ssize_t(
sizeof(exe_path) - 1));
244 exe_path[len] =
'\0';
249 if (getprogpath(exe_path, argv0) != NULL)
251#elif defined(__linux__) || defined(__CYGWIN__) || defined(__gnu_hurd__) || \
252 defined(__managarm__)
254 const char *aPath =
"/proc/self/exe";
257 ssize_t len = readlink(aPath, exe_path,
sizeof(exe_path));
263 len = std::min(len, ssize_t(
sizeof(exe_path) - 1));
264 exe_path[len] =
'\0';
270#if _POSIX_VERSION >= 200112 || defined(__GLIBC__)
271 if (
char *
real_path = realpath(exe_path,
nullptr)) {
272 std::string ret = std::string(
real_path);
283 if (getprogpath(exe_path, argv0))
285#elif defined(__OpenBSD__) || defined(__HAIKU__)
288 if (getprogpath(exe_path, argv0) != NULL)
290#elif defined(__sun__) && defined(__svr4__)
292 const char *aPath =
"/proc/self/execname";
294 int fd = open(aPath, O_RDONLY);
297 if (
read(fd, exe_path,
sizeof(exe_path)) < 0)
302 if (getprogpath(exe_path, argv0) != NULL)
304#elif defined(__MVS__)
307 char exe_path[PS_PATHBLEN];
308 pid_t pid = getpid();
310 memset(&buf, 0,
sizeof(buf));
311 buf.ps_pathptr = exe_path;
312 buf.ps_pathlen =
sizeof(exe_path);
315 if ((token = w_getpsent(token, &buf,
sizeof(buf))) <= 0)
317 if (buf.ps_pid != pid)
324#elif defined(HAVE_DLOPEN)
327 int err = dladdr(MainAddr, &DLInfo);
334 if (realpath(DLInfo.dli_fname, link_path))
337#error GetMainExecutable is not implemented on this host yet.
351 return UniqueID(fs_st_dev, fs_st_ino);
356ErrorOr<space_info>
disk_space(
const Twine &Path) {
358 if (::STATVFS(
const_cast<char *
>(
Path.str().c_str()), &Vfs))
360 auto FrSize = STATVFS_F_FRSIZE(Vfs);
362 SpaceInfo.
capacity =
static_cast<uint64_t
>(Vfs.f_blocks) * FrSize;
363 SpaceInfo.free =
static_cast<uint64_t
>(Vfs.f_bfree) * FrSize;
364 SpaceInfo.available =
static_cast<uint64_t
>(Vfs.f_bavail) * FrSize;
368std::error_code
current_path(SmallVectorImpl<char> &result) {
371 const char *pwd = ::getenv(
"PWD");
372 llvm::sys::fs::file_status PWDStatus, DotStatus;
377 result.
append(pwd, pwd + strlen(pwd));
378 return std::error_code();
384 if (::getcwd(result.
data(), result.
size()) ==
nullptr) {
386 if (errno != ENOMEM) {
398 return std::error_code();
402 SmallString<128> path_storage;
405 if (::chdir(
p.begin()) == -1)
408 return std::error_code();
413 SmallString<128> path_storage;
416 if (::mkdir(
p.begin(), Perms) == -1) {
417 if (errno != EEXIST || !IgnoreExisting)
421 return std::error_code();
426std::error_code
create_link(
const Twine &to,
const Twine &from) {
428 SmallString<128> from_storage;
429 SmallString<128> to_storage;
433 if (::symlink(t.
begin(),
f.begin()) == -1)
436 return std::error_code();
441 SmallString<128> from_storage;
442 SmallString<128> to_storage;
446 if (::link(t.
begin(),
f.begin()) == -1)
449 return std::error_code();
452std::error_code
remove(
const Twine &path,
bool IgnoreNonExisting) {
453 SmallString<128> path_storage;
454 StringRef
p = path.toNullTerminatedStringRef(path_storage);
457 if (lstat(
p.begin(), &buf) != 0) {
458 if (errno != ENOENT || !IgnoreNonExisting)
460 return std::error_code();
468 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
472 if (errno != ENOENT || !IgnoreNonExisting)
476 return std::error_code();
479static bool is_local_impl(
struct STATVFS &Vfs) {
480#if defined(__linux__) || defined(__GNU__) || defined(__managarm__)
481#ifndef NFS_SUPER_MAGIC
482#define NFS_SUPER_MAGIC 0x6969
484#ifndef SMB_SUPER_MAGIC
485#define SMB_SUPER_MAGIC 0x517B
487#ifndef CIFS_MAGIC_NUMBER
488#define CIFS_MAGIC_NUMBER 0xFF534D42
490#if defined(__GNU__) && ((__GLIBC__ < 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ < 39)))
491 switch ((uint32_t)Vfs.__f_type) {
493 switch ((uint32_t)Vfs.f_type) {
495 case NFS_SUPER_MAGIC:
496 case SMB_SUPER_MAGIC:
497 case CIFS_MAGIC_NUMBER:
502#elif defined(__CYGWIN__)
505#elif defined(__Fuchsia__)
508#elif defined(__EMSCRIPTEN__)
511#elif defined(__HAIKU__)
517 StringRef fstype(Vfs.f_basetype);
519 return fstype !=
"nfs";
524 size_t BufSize = 2048
u;
525 std::unique_ptr<char[]> Buf;
528 Buf = std::make_unique<char[]>(BufSize);
529 Ret = mntctl(MCTL_QUERY, BufSize, Buf.get());
532 BufSize = *
reinterpret_cast<unsigned int *
>(Buf.get());
541 char *CurObjPtr = Buf.get();
543 struct vmount *Vp =
reinterpret_cast<struct vmount *
>(CurObjPtr);
544 static_assert(
sizeof(Vfs.f_fsid) ==
sizeof(Vp->vmt_fsid),
545 "fsid length mismatch");
546 if (
memcmp(&Vfs.f_fsid, &Vp->vmt_fsid,
sizeof Vfs.f_fsid) == 0)
547 return (Vp->vmt_flags & MNT_REMOTE) == 0;
549 CurObjPtr += Vp->vmt_length;
554#elif defined(__MVS__)
559 return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
563std::error_code
is_local(
const Twine &Path,
bool &Result) {
565 if (::STATVFS(
const_cast<char *
>(
Path.str().c_str()), &Vfs))
568 Result = is_local_impl(Vfs);
569 return std::error_code();
572std::error_code
is_local(
int FD,
bool &Result) {
574 if (::FSTATVFS(FD, &Vfs))
577 Result = is_local_impl(Vfs);
578 return std::error_code();
581std::error_code
rename(
const Twine &from,
const Twine &to) {
583 SmallString<128> from_storage;
584 SmallString<128> to_storage;
591 return std::error_code();
597 if (::ftruncate(FD,
Size) == -1)
600 return std::error_code();
621 SmallString<128> PathStorage;
622 StringRef
P =
Path.toNullTerminatedStringRef(PathStorage);
630 if (0 != stat(
P.begin(), &buf))
632 if (!S_ISREG(buf.st_mode))
636 return std::error_code();
645 return A.fs_st_dev ==
B.fs_st_dev &&
A.fs_st_ino ==
B.fs_st_ino;
648std::error_code
equivalent(
const Twine &
A,
const Twine &
B,
bool &result) {
650 if (std::error_code ec =
status(
A, fsA))
652 if (std::error_code ec =
status(
B, fsB))
655 return std::error_code();
658static void expandTildeExpr(SmallVectorImpl<char> &Path) {
659 StringRef PathStr(
Path.begin(),
Path.size());
660 if (PathStr.empty() || !PathStr.starts_with(
"~"))
663 PathStr = PathStr.drop_front();
666 StringRef Remainder = PathStr.substr(Expr.
size() + 1);
667 SmallString<128> Storage;
676 Path[0] = Storage[0];
683 std::unique_ptr<char[]> Buf;
684 long BufSize = sysconf(_SC_GETPW_R_SIZE_MAX);
687 Buf = std::make_unique<char[]>(BufSize);
690 struct passwd *
Entry =
nullptr;
691 getpwnam_r(
User.c_str(), &Pwd, Buf.get(), BufSize, &Entry);
693 if (!Entry || !
Entry->pw_dir) {
704void expand_tilde(
const Twine &path, SmallVectorImpl<char> &dest) {
710 expandTildeExpr(dest);
716 else if (S_ISREG(
Mode))
718 else if (S_ISBLK(
Mode))
720 else if (S_ISCHR(
Mode))
722 else if (S_ISFIFO(
Mode))
724 else if (S_ISSOCK(
Mode))
726 else if (S_ISLNK(
Mode))
731static std::error_code fillStatus(
int StatRet,
const struct stat &Status,
742 uint32_t atime_nsec, mtime_nsec;
743#if defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
744 atime_nsec = Status.st_atimespec.tv_nsec;
745 mtime_nsec = Status.st_mtimespec.tv_nsec;
746#elif defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
747 atime_nsec = Status.st_atim.tv_nsec;
748 mtime_nsec = Status.st_mtim.tv_nsec;
750 atime_nsec = mtime_nsec = 0;
755 Status.st_nlink, Status.st_ino, Status.st_atime,
756 atime_nsec, Status.st_mtime, mtime_nsec, Status.st_uid,
757 Status.st_gid, Status.st_size);
759 return std::error_code();
763 SmallString<128> PathStorage;
764 StringRef
P =
Path.toNullTerminatedStringRef(PathStorage);
767 int StatRet = (Follow ? ::stat : ::lstat)(
P.begin(), &Status);
768 return fillStatus(StatRet, Status, Result);
773 int StatRet = ::fstat(FD, &Status);
774 return fillStatus(StatRet, Status, Result);
780 unsigned Mask = ::umask(0);
786 SmallString<128> PathStorage;
787 StringRef
P =
Path.toNullTerminatedStringRef(PathStorage);
789 if (::chmod(
P.begin(), Permissions))
791 return std::error_code();
795 if (::fchmod(FD, Permissions))
797 return std::error_code();
802#if defined(HAVE_FUTIMENS)
806 if (::futimens(FD, Times))
808 return std::error_code();
809#elif defined(HAVE_FUTIMES)
812 std::chrono::time_point_cast<std::chrono::microseconds>(AccessTime));
814 sys::toTimeVal(std::chrono::time_point_cast<std::chrono::microseconds>(
816 if (::futimes(FD, Times))
818 return std::error_code();
819#elif defined(__MVS__)
821 memset(&Attr, 0,
sizeof(Attr));
822 Attr.att_atimechg = 1;
824 Attr.att_mtimechg = 1;
826 if (::__fchattr(FD, &Attr,
sizeof(Attr)) != 0)
828 return std::error_code();
830#warning Missing futimes() and futimens()
835std::error_code mapped_file_region::init(
int FD, uint64_t
Offset,
839 int flags = (Mode ==
readwrite) ? MAP_SHARED : MAP_PRIVATE;
840 int prot = (Mode ==
readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
841#if defined(MAP_NORESERVE)
842 flags |= MAP_NORESERVE;
844#if defined(__APPLE__)
855#if defined(MAP_RESILIENT_CODESIGN)
856 flags |= MAP_RESILIENT_CODESIGN;
858#if defined(MAP_RESILIENT_MEDIA)
859 flags |= MAP_RESILIENT_MEDIA;
864 Mapping = ::mmap(
nullptr, Size, prot, flags, FD,
Offset);
865 if (Mapping == MAP_FAILED)
867 return std::error_code();
871 uint64_t offset, std::error_code &ec)
876 copyFrom(mapped_file_region());
879void mapped_file_region::unmapImpl() {
881 ::munmap(Mapping,
Size);
884std::error_code mapped_file_region::sync()
const {
885 if (
int Res = ::msync(Mapping,
Size, MS_SYNC))
886 return std::error_code(Res, std::generic_category());
887 return std::error_code();
890void mapped_file_region::dontNeedImpl() {
894#if defined(__MVS__) || defined(_AIX)
896#elif defined(POSIX_MADV_DONTNEED)
897 ::posix_madvise(Mapping,
Size, POSIX_MADV_DONTNEED);
899 ::madvise(Mapping,
Size, MADV_DONTNEED);
905std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
907 bool follow_symlinks) {
909 DIR *directory = ::opendir(path_null.c_str());
913 it.IterationHandle =
reinterpret_cast<intptr_t
>(directory);
916 it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks);
920std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
921 if (it.IterationHandle)
922 ::closedir(
reinterpret_cast<DIR *
>(it.IterationHandle));
923 it.IterationHandle = 0;
924 it.CurrentEntry = directory_entry();
925 return std::error_code();
928static file_type direntType(dirent *Entry) {
935 return typeForMode(DTTOIF(Entry->d_type));
938 return file_type::type_unknown;
942std::error_code detail::directory_iterator_increment(detail::DirIterState &It) {
944 dirent *CurDir = ::readdir(
reinterpret_cast<DIR *
>(It.IterationHandle));
945 if (CurDir ==
nullptr && errno != 0) {
947 }
else if (CurDir !=
nullptr) {
949 if ((
Name.size() == 1 && Name[0] ==
'.') ||
950 (
Name.size() == 2 && Name[0] ==
'.' && Name[1] ==
'.'))
952 It.CurrentEntry.replace_filename(Name, direntType(CurDir));
957 return std::error_code();
962 if (
auto EC =
fs::status(Path, s, FollowSymlinks))
971#if !defined(__FreeBSD__) && !defined(__OpenBSD__)
972#define TRY_PROC_SELF_FD
975#if !defined(F_GETPATH) && defined(TRY_PROC_SELF_FD)
976static bool hasProcSelfFD() {
979 static const bool Result = (::access(
"/proc/self/fd", R_OK) == 0);
984static int nativeOpenFlags(CreationDisposition Disp, OpenFlags Flags,
989 else if (
Access == FA_Write)
991 else if (
Access == (FA_Read | FA_Write))
996 if (Flags & OF_Append)
999 if (Disp == CD_CreateNew) {
1002 }
else if (Disp == CD_CreateAlways) {
1005 }
else if (Disp == CD_OpenAlways) {
1007 }
else if (Disp == CD_OpenExisting) {
1015 if (Flags & OF_Append)
1020 if (!(Flags & OF_ChildInherit))
1028 CreationDisposition Disp, FileAccess
Access,
1029 OpenFlags Flags,
unsigned Mode) {
1036 auto Open = [&]() { return ::open(
P.begin(), OpenFlags,
Mode); };
1040 if (!(Flags & OF_ChildInherit)) {
1041 int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
1043 assert(r == 0 &&
"fcntl(F_SETFD, FD_CLOEXEC) failed");
1101 if ((Flags & OF_Append) && lseek(ResultFD, 0, SEEK_END) == -1)
1104 if (fstat(ResultFD, &Stat) == -1)
1106 if (S_ISREG(Stat.st_mode)) {
1107 bool DoSetTag = (
Access &
FA_Write) && (Disp != CD_OpenExisting) &&
1108 !Stat.st_tag.ft_txtflag && !Stat.st_tag.ft_ccsid &&
1110 if (Flags & OF_Text) {
1111 if (
auto EC = llvm::enableAutoConversion(ResultFD))
1114 if (
auto EC = llvm::setzOSFileTag(ResultFD,
CCSID_IBM_1047,
true))
1118 if (
auto EC = llvm::disableAutoConversion(ResultFD))
1121 if (
auto EC = llvm::setzOSFileTag(ResultFD, FT_BINARY,
false))
1128 return std::error_code();
1132 FileAccess
Access, OpenFlags Flags,
1145 std::error_code
EC =
1146 openFile(Name, ResultFD, CD_OpenExisting, FA_Read, Flags, 0666);
1152 return std::error_code();
1154#if defined(F_GETPATH)
1158 if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
1159 RealPath->
append(Buffer, Buffer + strlen(Buffer));
1162#if defined(TRY_PROC_SELF_FD)
1163 if (hasProcSelfFD()) {
1165 snprintf(ProcPath,
sizeof(ProcPath),
"/proc/self/fd/%d", ResultFD);
1166 ssize_t CharCount = ::readlink(ProcPath, Buffer,
sizeof(Buffer));
1168 RealPath->
append(Buffer, Buffer + CharCount);
1175 if (::realpath(
P.begin(), Buffer) !=
nullptr)
1176 RealPath->
append(Buffer, Buffer + strlen(Buffer));
1177#if defined(TRY_PROC_SELF_FD)
1181 return std::error_code();
1198#if defined(__APPLE__)
1199 size_t Size = std::min<size_t>(Buf.
size(), INT32_MAX);
1208#if defined(__MVS__) || defined(_AIX)
1210 if (fstat(FD, &
Status) == -1)
1212 if (S_ISDIR(
Status.st_mode))
1220#if defined(__APPLE__)
1221 size_t Size = std::min<size_t>(Buf.
size(), INT32_MAX);
1229 if (lseek(FD,
Offset, SEEK_SET) == -1)
1240 auto Start = std::chrono::steady_clock::now();
1244 memset(&Lock, 0,
sizeof(Lock));
1246 case LockKind::Exclusive:
1247 Lock.l_type = F_WRLCK;
1249 case LockKind::Shared:
1250 Lock.l_type = F_RDLCK;
1253 Lock.l_whence = SEEK_SET;
1256 if (::fcntl(FD, F_SETLK, &Lock) != -1)
1257 return std::error_code();
1259 if (Error != EACCES && Error != EAGAIN)
1260 return std::error_code(Error, std::generic_category());
1264 }
while (std::chrono::steady_clock::now() < End);
1268std::error_code
lockFile(
int FD, LockKind Kind) {
1270 memset(&Lock, 0,
sizeof(Lock));
1272 case LockKind::Exclusive:
1273 Lock.l_type = F_WRLCK;
1275 case LockKind::Shared:
1276 Lock.l_type = F_RDLCK;
1279 Lock.l_whence = SEEK_SET;
1282 if (::fcntl(FD, F_SETLKW, &Lock) != -1)
1283 return std::error_code();
1289 Lock.l_type = F_UNLCK;
1290 Lock.l_whence = SEEK_SET;
1293 if (::fcntl(FD, F_SETLK, &Lock) != -1)
1294 return std::error_code();
1304template <
typename T>
1305static std::error_code remove_directories_impl(
const T &Entry,
1306 bool IgnoreErrors) {
1308 directory_iterator Begin(Entry, EC,
false);
1309 directory_iterator End;
1310 while (Begin != End) {
1311 auto &Item = *Begin;
1315 EC = remove_directories_impl(Item, IgnoreErrors);
1316 if (EC && !IgnoreErrors)
1321 if (EC && !IgnoreErrors)
1323 }
else if (!IgnoreErrors) {
1327 Begin.increment(EC);
1328 if (EC && !IgnoreErrors)
1331 return std::error_code();
1335 auto EC = remove_directories_impl(
path, IgnoreErrors);
1336 if (EC && !IgnoreErrors)
1339 if (EC && !IgnoreErrors)
1341 return std::error_code();
1345 bool expand_tilde) {
1347 if (
path.isTriviallyEmpty())
1348 return std::error_code();
1352 path.toVector(Storage);
1353 expandTildeExpr(Storage);
1360 if (::realpath(
P.begin(), Buffer) ==
nullptr)
1362 dest.
append(Buffer, Buffer + strlen(Buffer));
1363 return std::error_code();
1367 auto FChown = [&]() { return ::fchown(FD, Owner, Group); };
1371 return std::error_code();
1379 std::unique_ptr<char[]> Buf;
1380 char *RequestedDir = getenv(
"HOME");
1381 if (!RequestedDir) {
1382 long BufSize = sysconf(_SC_GETPW_R_SIZE_MAX);
1385 Buf = std::make_unique<char[]>(BufSize);
1387 struct passwd *pw =
nullptr;
1388 getpwuid_r(getuid(), &Pwd, Buf.get(), BufSize, &pw);
1389 if (pw && pw->pw_dir)
1390 RequestedDir = pw->pw_dir;
1396 result.
append(RequestedDir, RequestedDir + strlen(RequestedDir));
1400static bool getDarwinConfDir(
bool TempDir, SmallVectorImpl<char> &Result) {
1401#if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
1404 int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR : _CS_DARWIN_USER_CACHE_DIR;
1405 size_t ConfLen = confstr(ConfName,
nullptr, 0);
1409 ConfLen = confstr(ConfName,
Result.data(),
Result.size());
1410 }
while (ConfLen > 0 && ConfLen !=
Result.size());
1428 append(result,
"Library",
"Preferences");
1434 if (
const char *RequestedDir = getenv(
"XDG_CONFIG_HOME")) {
1436 result.
append(RequestedDir, RequestedDir + strlen(RequestedDir));
1444 append(result,
".config");
1450 if (getDarwinConfDir(
false , result)) {
1456 if (
const char *RequestedDir = getenv(
"XDG_CACHE_HOME")) {
1458 result.
append(RequestedDir, RequestedDir + strlen(RequestedDir));
1465 append(result,
".cache");
1469static const char *getEnvTempDir() {
1472 const char *EnvironmentVariables[] = {
"TMPDIR",
"TMP",
"TEMP",
"TEMPDIR"};
1473 for (
const char *Env : EnvironmentVariables) {
1474 if (
const char *Dir = std::getenv(Env))
1481static const char *getDefaultTempDir(
bool ErasedOnReboot) {
1495 if (ErasedOnReboot) {
1497 if (
const char *RequestedDir = getEnvTempDir()) {
1498 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1503 if (getDarwinConfDir(ErasedOnReboot, Result))
1506 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
1507 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1520std::error_code
copy_file(
const Twine &From,
const Twine &To) {
1521 std::string FromS = From.
str();
1522 std::string ToS = To.
str();
1523#if __has_builtin(__builtin_available)
1524 if (__builtin_available(macos 10.12, *)) {
1531 if (!clonefile(FromS.c_str(), ToS.c_str(), 0))
1532 return std::error_code();
1542 return std::error_code(Errno, std::generic_category());
1551 if (!copyfile(FromS.c_str(), ToS.c_str(), NULL, COPYFILE_DATA))
1552 return std::error_code();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
amode Optimize addressing mode
std::unique_ptr< MemoryBuffer > openFile(const Twine &Path)
Merge contiguous icmps into a memcmp
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
LLVM_ABI const file_t kInvalidFile
Represents the result of a call to sys::fs::status().
size_t size() const
size - Get the array size.
Represents either an error or a value T.
std::error_code getError() const
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void resize_for_overwrite(size_type N)
Like resize, but T is POD, the new values won't be initialized.
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void truncate(size_type N)
Like resize, but requires that N is less than size().
pointer data()
Return a pointer to the vector's buffer, even if empty().
StringRef - Represent a constant reference to a string, i.e.
std::string str() const
str - Get the contents as an std::string.
constexpr bool empty() const
empty - Check if the string is empty.
constexpr size_t size() const
size - Get the string size.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
LLVM_ABI StringRef toNullTerminatedStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single null terminated StringRef if it can be represented as such.
bool isTriviallyEmpty() const
Check if this twine is trivially empty; a false return value does not necessarily mean the twine is e...
LLVM_ABI void toVector(SmallVectorImpl< char > &Out) const
Append the concatenated string into the given SmallString or SmallVector.
static LLVM_ABI std::error_code SafelyCloseFileDescriptor(int FD)
static unsigned getPageSizeEstimate()
Get the process's estimated page size.
uint32_t fs_st_mtime_nsec
uint32_t fs_st_atime_nsec
LLVM_ABI TimePoint getLastModificationTime() const
The file modification time as reported from the underlying file system.
LLVM_ABI TimePoint getLastAccessedTime() const
The file access time as reported from the underlying file system.
Represents the result of a call to sys::fs::status().
LLVM_ABI uint32_t getLinkCount() const
LLVM_ABI UniqueID getUniqueID() const
mapped_file_region()=default
@ readonly
May only access map via const_data as read only.
@ readwrite
May access map via data and modify it. Written to path.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
initializer< Ty > init(const Ty &Val)
@ User
could "use" a pointer
value_type read(const void *memory, endianness endian)
Read a value of a particular endianness from memory.
LLVM_ABI std::error_code directory_iterator_destruct(DirIterState &)
LLVM_ABI std::error_code directory_iterator_increment(DirIterState &)
LLVM_ABI bool can_execute(const Twine &Path)
Can we execute this file?
LLVM_ABI std::error_code closeFile(file_t &F)
Close the file object.
LLVM_ABI std::error_code rename(const Twine &from, const Twine &to)
Rename from to to.
LLVM_ABI std::error_code create_hard_link(const Twine &to, const Twine &from)
Create a hard link from from to to, or return an error.
LLVM_ABI const file_t kInvalidFile
LLVM_ABI std::error_code access(const Twine &Path, AccessMode Mode)
Can the file be accessed?
LLVM_ABI ErrorOr< space_info > disk_space(const Twine &Path)
Get disk space usage information.
LLVM_ABI Expected< size_t > readNativeFile(file_t FileHandle, MutableArrayRef< char > Buf)
Reads Buf.size() bytes from FileHandle into Buf.
LLVM_ABI unsigned getUmask()
Get file creation mode mask of the process.
LLVM_ABI bool exists(const basic_file_status &status)
Does file exist?
LLVM_ABI Expected< file_t > openNativeFile(const Twine &Name, CreationDisposition Disp, FileAccess Access, OpenFlags Flags, unsigned Mode=0666)
Opens a file with the specified creation disposition, access mode, and flags and returns a platform-s...
LLVM_ABI file_t getStdoutHandle()
Return an open handle to standard out.
file_type
An enumeration for the file system's view of the type.
LLVM_ABI std::error_code create_link(const Twine &to, const Twine &from)
Create a link from from to to.
LLVM_ABI void expand_tilde(const Twine &path, SmallVectorImpl< char > &output)
Expands ~ expressions to the user's home directory.
LLVM_ABI std::error_code lockFile(int FD, LockKind Kind=LockKind::Exclusive)
Lock the file.
LLVM_ABI std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
LLVM_ABI std::error_code set_current_path(const Twine &path)
Set the current path.
LLVM_ABI std::error_code real_path(const Twine &path, SmallVectorImpl< char > &output, bool expand_tilde=false)
Collapse all .
@ CD_OpenAlways
CD_OpenAlways - When opening a file:
LLVM_ABI Expected< size_t > readNativeFileSlice(file_t FileHandle, MutableArrayRef< char > Buf, uint64_t Offset)
Reads Buf.size() bytes from FileHandle at offset Offset into Buf.
LLVM_ABI std::error_code changeFileOwnership(int FD, uint32_t Owner, uint32_t Group)
Change ownership of a file.
LLVM_ABI std::string getMainExecutable(const char *argv0, void *MainExecAddr)
Return the path to the main executable, given the value of argv[0] from program startup and the addre...
LLVM_ABI Expected< file_t > openNativeFileForRead(const Twine &Name, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
LLVM_ABI bool status_known(const basic_file_status &s)
Is status available?
LLVM_ABI std::error_code resize_file_sparse(int FD, uint64_t Size)
Resize path to size with sparse files explicitly enabled.
LLVM_ABI std::error_code copy_file(const Twine &From, const Twine &To)
Copy the contents of From to To.
LLVM_ABI std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout=std::chrono::milliseconds(0), LockKind Kind=LockKind::Exclusive)
Try to locks the file during the specified time.
LLVM_ABI std::error_code current_path(SmallVectorImpl< char > &result)
Get the current path.
LLVM_ABI std::error_code resize_file(int FD, uint64_t Size)
Resize path to size.
LLVM_ABI std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
LLVM_ABI std::error_code create_directory(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create the directory in path.
LLVM_ABI std::error_code is_local(const Twine &path, bool &result)
Is the file mounted on a local filesystem?
LLVM_ABI std::error_code openFileForRead(const Twine &Name, int &ResultFD, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
LLVM_ABI std::error_code remove_directories(const Twine &path, bool IgnoreErrors=true)
Recursively delete a directory.
LLVM_ABI bool equivalent(file_status A, file_status B)
Do file_status's represent the same thing?
LLVM_ABI file_t getStderrHandle()
Return an open handle to standard error.
LLVM_ABI std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime, TimePoint<> ModificationTime)
Set the file modification and access time.
LLVM_ABI file_t getStdinHandle()
Return an open handle to standard in.
LLVM_ABI std::error_code unlockFile(int FD)
Unlock the file.
LLVM_ABI std::error_code setPermissions(const Twine &Path, perms Permissions)
Set file permissions.
LLVM_ABI bool is_directory(const basic_file_status &status)
Does status represent a directory?
LLVM_ABI bool cache_directory(SmallVectorImpl< char > &result)
Get the directory where installed packages should put their machine-local cache, e....
LLVM_ABI bool user_config_directory(SmallVectorImpl< char > &result)
Get the directory where packages should read user-specific configurations.
LLVM_ABI void system_temp_directory(bool erasedOnReboot, SmallVectorImpl< char > &result)
Get the typical temporary directory for the system, e.g., "/var/tmp" or "C:/TEMP".
LLVM_ABI bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
LLVM_ABI bool home_directory(SmallVectorImpl< char > &result)
Get the user's home directory.
LLVM_ABI bool is_separator(char value, Style style=Style::native)
Check whether the given char is a path separator on the host OS.
decltype(auto) RetryAfterSignal(const FailT &Fail, const Fun &F, const Args &... As)
std::chrono::time_point< std::chrono::system_clock, D > TimePoint
A time point on the system clock.
TimePoint< std::chrono::seconds > toTimePoint(std::time_t T)
Convert a std::time_t to a TimePoint.
struct timespec toTimeSpec(TimePoint<> TP)
Convert a time point to struct timespec.
struct timeval toTimeVal(TimePoint< std::chrono::microseconds > TP)
Convert a time point to struct timeval.
std::time_t toTimeT(TimePoint<> TP)
Convert a TimePoint to std::time_t.
This is an optimization pass for GlobalISel generic memory operations.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
std::error_code make_error_code(BitcodeError E)
@ no_such_file_or_directory
@ operation_not_permitted
@ Timeout
Reached timeout while waiting for the owner to release the lock.
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
std::error_code errnoAsErrorCode()
Helper to get errno as an std::error_code.
space_info - Self explanatory.