31 #ifdef HAVE_SYS_MMAN_H 39 #include <mach-o/dyld.h> 50 #if defined(__GNU__) && !defined(PATH_MAX) 51 # define PATH_MAX 4096 54 #include <sys/types.h> 55 #if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && \ 57 #include <sys/statvfs.h> 58 #define STATVFS statvfs 59 #define FSTATVFS fstatvfs 60 #define STATVFS_F_FRSIZE(vfs) vfs.f_frsize 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> 69 #if defined(HAVE_LINUX_NFS_FS_H) 70 #include <linux/nfs_fs.h> 72 #if defined(HAVE_LINUX_SMB_H) 73 #include <linux/smb.h> 78 #include <sys/mount.h> 80 #define STATVFS statfs 81 #define FSTATVFS fstatfs 82 #define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize) 85 #if defined(__NetBSD__) 86 #define STATVFS_F_FLAG(vfs) (vfs).f_flag 88 #define STATVFS_F_FLAG(vfs) (vfs).f_flags 99 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \ 100 defined(__minix) || defined(__FreeBSD_kernel__) || defined(__linux__) || \ 101 defined(__CYGWIN__) || defined(__DragonFly__) || defined(_AIX) 103 test_dir(
char ret[PATH_MAX],
const char *dir,
const char *bin)
106 char fullpath[PATH_MAX];
108 snprintf(fullpath, PATH_MAX,
"%s/%s", dir, bin);
109 if (!realpath(fullpath, ret))
111 if (stat(fullpath, &sb) != 0)
118 getprogpath(
char ret[PATH_MAX],
const char *bin)
124 if (test_dir(ret,
"/", bin) == 0)
130 if (strchr(bin,
'/')) {
132 if (!getcwd(cwd, PATH_MAX))
134 if (test_dir(ret, cwd, bin) == 0)
140 if ((pv = getenv(
"PATH")) ==
nullptr)
145 while ((t = strsep(&s,
":")) !=
nullptr) {
146 if (test_dir(ret, t, bin) == 0) {
154 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__ 159 #if defined(__APPLE__) 163 char exe_path[MAXPATHLEN];
165 if (_NSGetExecutablePath(exe_path, &size) == 0) {
166 char link_path[MAXPATHLEN];
167 if (realpath(exe_path, link_path))
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];
175 if (getprogpath(exe_path, argv0) != NULL)
177 #elif defined(__linux__) || defined(__CYGWIN__) 178 char exe_path[MAXPATHLEN];
182 ssize_t len = readlink(aPath.str().c_str(), exe_path,
sizeof(exe_path));
184 return std::string(exe_path, len);
187 if (getprogpath(exe_path, argv0))
190 #elif defined(HAVE_DLFCN_H) && defined(HAVE_DLADDR) 193 int err = dladdr(MainAddr, &DLInfo);
199 char link_path[MAXPATHLEN];
200 if (realpath(DLInfo.dli_fname, link_path))
203 #error GetMainExecutable is not implemented on this host yet. 217 return UniqueID(fs_st_dev, fs_st_ino);
226 if (::STATVFS(Path.
str().c_str(), &Vfs))
227 return std::error_code(errno, std::generic_category());
228 auto FrSize = STATVFS_F_FRSIZE(Vfs);
229 space_info SpaceInfo;
230 SpaceInfo.capacity =
static_cast<uint64_t
>(Vfs.f_blocks) * FrSize;
231 SpaceInfo.free =
static_cast<uint64_t
>(Vfs.f_bfree) * FrSize;
232 SpaceInfo.available =
static_cast<uint64_t
>(Vfs.f_bavail) * FrSize;
239 const char *pwd = ::getenv(
"PWD");
245 result.
append(pwd, pwd + strlen(pwd));
246 return std::error_code();
257 if (::getcwd(result.
data(), result.
capacity()) ==
nullptr) {
260 return std::error_code(errno, std::generic_category());
268 return std::error_code();
275 if (::chdir(p.
begin()) == -1)
276 return std::error_code(errno, std::generic_category());
278 return std::error_code();
287 if (errno != EEXIST || !IgnoreExisting)
288 return std::error_code(errno, std::generic_category());
291 return std::error_code();
304 return std::error_code(errno, std::generic_category());
306 return std::error_code();
317 return std::error_code(errno, std::generic_category());
319 return std::error_code();
322 std::error_code
remove(
const Twine &path,
bool IgnoreNonExisting) {
324 StringRef p = path.toNullTerminatedStringRef(path_storage);
327 if (lstat(p.
begin(), &buf) != 0) {
328 if (errno != ENOENT || !IgnoreNonExisting)
329 return std::error_code(errno, std::generic_category());
330 return std::error_code();
338 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
341 if (::
remove(p.
begin()) == -1) {
342 if (errno != ENOENT || !IgnoreNonExisting)
343 return std::error_code(errno, std::generic_category());
346 return std::error_code();
349 static bool is_local_impl(
struct STATVFS &Vfs) {
350 #if defined(__linux__) 351 #ifndef NFS_SUPER_MAGIC 352 #define NFS_SUPER_MAGIC 0x6969 354 #ifndef SMB_SUPER_MAGIC 355 #define SMB_SUPER_MAGIC 0x517B 357 #ifndef CIFS_MAGIC_NUMBER 358 #define CIFS_MAGIC_NUMBER 0xFF534D42 361 case NFS_SUPER_MAGIC:
362 case SMB_SUPER_MAGIC:
363 case CIFS_MAGIC_NUMBER:
368 #elif defined(__CYGWIN__) 371 #elif defined(__Fuchsia__) 374 #elif defined(__HAIKU__) 381 return !fstype.equals(
"nfs");
383 return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
389 if (::STATVFS(Path.
str().c_str(), &Vfs))
390 return std::error_code(errno, std::generic_category());
392 Result = is_local_impl(Vfs);
393 return std::error_code();
396 std::error_code
is_local(
int FD,
bool &Result) {
398 if (::FSTATVFS(FD, &Vfs))
399 return std::error_code(errno, std::generic_category());
401 Result = is_local_impl(Vfs);
402 return std::error_code();
413 return std::error_code(errno, std::generic_category());
415 return std::error_code();
419 #if defined(HAVE_POSIX_FALLOCATE) 422 if (
int Err = ::posix_fallocate(FD, 0, Size)) {
423 if (Err != EINVAL && Err != EOPNOTSUPP)
424 return std::error_code(Err, std::generic_category());
429 if (::ftruncate(FD, Size) == -1)
430 return std::error_code(errno, std::generic_category());
432 return std::error_code();
451 if (::
access(P.
begin(), convertAccessMode(Mode)) == -1)
452 return std::error_code(errno, std::generic_category());
457 if (0 != stat(P.
begin(), &buf))
459 if (!S_ISREG(buf.st_mode))
463 return std::error_code();
472 return A.fs_st_dev == B.fs_st_dev &&
473 A.fs_st_ino == B.fs_st_ino;
477 file_status fsA, fsB;
478 if (std::error_code ec =
status(A, fsA))
480 if (std::error_code ec =
status(B, fsB))
483 return std::error_code();
488 if (PathStr.empty() || !PathStr.startswith(
"~"))
504 Path[0] = Storage[0];
511 struct passwd *Entry =
nullptr;
513 Entry = ::getpwnam(User.c_str());
522 Path.
append(Entry->pw_dir, Entry->pw_dir + strlen(Entry->pw_dir));
526 static std::error_code fillStatus(
int StatRet,
const struct stat &Status,
527 file_status &Result) {
529 std::error_code ec(errno, std::generic_category());
539 if (S_ISDIR(Status.st_mode))
541 else if (S_ISREG(Status.st_mode))
543 else if (S_ISBLK(Status.st_mode))
545 else if (S_ISCHR(Status.st_mode))
547 else if (S_ISFIFO(Status.st_mode))
549 else if (S_ISSOCK(Status.st_mode))
551 else if (S_ISLNK(Status.st_mode))
555 Result = file_status(Type, Perms, Status.st_dev, Status.st_nlink,
556 Status.st_ino, Status.st_atime, Status.st_mtime,
557 Status.st_uid, Status.st_gid, Status.st_size);
559 return std::error_code();
562 std::error_code
status(
const Twine &Path, file_status &Result,
bool Follow) {
567 int StatRet = (Follow ? ::stat : ::lstat)(P.
begin(), &Status);
568 return fillStatus(StatRet, Status, Result);
571 std::error_code
status(
int FD, file_status &Result) {
573 int StatRet = ::fstat(FD, &Status);
574 return fillStatus(StatRet, Status, Result);
581 if (::chmod(P.
begin(), Permissions))
582 return std::error_code(errno, std::generic_category());
583 return std::error_code();
587 #if defined(HAVE_FUTIMENS) 590 if (::futimens(FD, Times))
591 return std::error_code(errno, std::generic_category());
592 return std::error_code();
593 #elif defined(HAVE_FUTIMES) 596 std::chrono::time_point_cast<std::chrono::microseconds>(Time));
597 if (::futimes(FD, Times))
598 return std::error_code(errno, std::generic_category());
599 return std::error_code();
601 #warning Missing futimes() and futimens() 610 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
611 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
612 #if defined(__APPLE__) 622 if (Mode == readonly) {
623 #if defined(MAP_RESILIENT_CODESIGN) 624 flags |= MAP_RESILIENT_CODESIGN;
626 #if defined(MAP_RESILIENT_MEDIA) 627 flags |= MAP_RESILIENT_MEDIA;
630 #endif // #if defined (__APPLE__) 632 Mapping = ::mmap(
nullptr, Size, prot, flags, FD, Offset);
633 if (Mapping == MAP_FAILED)
634 return std::error_code(errno, std::generic_category());
635 return std::error_code();
639 uint64_t offset, std::error_code &ec)
640 : Size(length), Mapping(), Mode(mode) {
642 ec =
init(fd, offset, mode);
647 mapped_file_region::~mapped_file_region() {
649 ::munmap(Mapping, Size);
653 assert(Mapping &&
"Mapping failed but used anyway!");
657 char *mapped_file_region::data()
const {
658 assert(Mapping &&
"Mapping failed but used anyway!");
659 return reinterpret_cast<char*
>(Mapping);
662 const char *mapped_file_region::const_data()
const {
663 assert(Mapping &&
"Mapping failed but used anyway!");
664 return reinterpret_cast<const char*
>(Mapping);
667 int mapped_file_region::alignment() {
673 bool follow_symlinks) {
675 DIR *directory = ::opendir(path_null.c_str());
677 return std::error_code(errno, std::generic_category());
679 it.IterationHandle =
reinterpret_cast<intptr_t>(directory);
682 it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks);
687 if (it.IterationHandle)
688 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
689 it.IterationHandle = 0;
690 it.CurrentEntry = directory_entry();
691 return std::error_code();
696 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
697 if (cur_dir ==
nullptr && errno != 0) {
698 return std::error_code(errno, std::generic_category());
699 }
else if (cur_dir !=
nullptr) {
701 if ((
name.size() == 1 &&
name[0] ==
'.') ||
704 it.CurrentEntry.replace_filename(
name);
708 return std::error_code();
713 if (
auto EC =
fs::status(Path, s, FollowSymlinks))
718 #if !defined(F_GETPATH) 719 static bool hasProcSelfFD() {
722 static const bool Result = (
::access(
"/proc/self/fd", R_OK) == 0);
754 if (Flags & F_Append)
768 int OpenFlags = nativeOpenFlags(Disp, Flags, Access);
774 return std::error_code(errno, std::generic_category());
777 int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
779 assert(r == 0 &&
"fcntl(F_SETFD, FD_CLOEXEC) failed");
782 return std::error_code();
790 std::error_code
EC =
openFile(Name, FD, Disp, Access, Flags, Mode);
806 return std::error_code();
808 #if defined(F_GETPATH) 811 char Buffer[MAXPATHLEN];
812 if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
813 RealPath->
append(Buffer, Buffer + strlen(Buffer));
815 char Buffer[PATH_MAX];
816 if (hasProcSelfFD()) {
818 snprintf(ProcPath,
sizeof(ProcPath),
"/proc/self/fd/%d", ResultFD);
819 ssize_t CharCount = ::readlink(ProcPath, Buffer,
sizeof(Buffer));
821 RealPath->
append(Buffer, Buffer + CharCount);
827 if (::realpath(P.
begin(), Buffer) !=
nullptr)
828 RealPath->
append(Buffer, Buffer + strlen(Buffer));
831 return std::error_code();
848 template <
typename T>
849 static std::error_code remove_directories_impl(
const T &Entry,
852 directory_iterator Begin(Entry, EC,
false);
853 directory_iterator End;
854 while (Begin != End) {
857 if (!st && !IgnoreErrors)
861 EC = remove_directories_impl(Item, IgnoreErrors);
862 if (EC && !IgnoreErrors)
867 if (EC && !IgnoreErrors)
871 if (EC && !IgnoreErrors)
874 return std::error_code();
878 auto EC = remove_directories_impl(path, IgnoreErrors);
879 if (EC && !IgnoreErrors)
882 if (EC && !IgnoreErrors)
884 return std::error_code();
891 return std::error_code();
896 expandTildeExpr(Storage);
902 char Buffer[PATH_MAX];
903 if (::realpath(P.
begin(), Buffer) ==
nullptr)
904 return std::error_code(errno, std::generic_category());
905 dest.
append(Buffer, Buffer + strlen(Buffer));
906 return std::error_code();
914 char *RequestedDir = getenv(
"HOME");
916 struct passwd *pw = getpwuid(getuid());
917 if (pw && pw->pw_dir)
918 RequestedDir = pw->pw_dir;
924 result.
append(RequestedDir, RequestedDir + strlen(RequestedDir));
929 #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR) 932 int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
933 : _CS_DARWIN_USER_CACHE_DIR;
934 size_t ConfLen = confstr(ConfName,
nullptr, 0);
938 ConfLen = confstr(ConfName, Result.
data(), Result.
size());
939 }
while (ConfLen > 0 && ConfLen != Result.
size());
957 if (
const char *XdgCacheDir = std::getenv(
"XDG_CACHE_HOME")) {
959 Result.
append(XdgCacheDir, XdgCacheDir + strlen(XdgCacheDir));
964 if (getDarwinConfDir(
false, Result))
976 static const char *getEnvTempDir() {
979 const char *EnvironmentVariables[] = {
"TMPDIR",
"TMP",
"TEMP",
"TEMPDIR"};
980 for (
const char *Env : EnvironmentVariables) {
981 if (
const char *Dir = std::getenv(Env))
988 static const char *getDefaultTempDir(
bool ErasedOnReboot) {
1002 if (ErasedOnReboot) {
1004 if (
const char *RequestedDir = getEnvTempDir()) {
1005 Result.
append(RequestedDir, RequestedDir + strlen(RequestedDir));
1010 if (getDarwinConfDir(ErasedOnReboot, Result))
1013 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
1014 Result.
append(RequestedDir, RequestedDir + strlen(RequestedDir));
const file_t kInvalidFile
bool is_separator(char value, Style style=Style::native)
Check whether the given char is a path separator on the host OS.
bool can_execute(const Twine &Path)
Can we execute this file?
Represents either an error or a value T.
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
bool status_known(const basic_file_status &s)
Is status available?
Compute iterated dominance frontiers using a linear time algorithm.
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.
void closeFile(file_t &F)
Close the file object.
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
bool isTriviallyEmpty() const
Check if this twine is trivially empty; a false return value does not necessarily mean the twine is e...
std::error_code setLastModificationAndAccessTime(int FD, TimePoint<> Time)
Set the file modification and access time.
std::error_code current_path(SmallVectorImpl< char > &result)
Get the current path.
bool is_directory(const basic_file_status &status)
Does status represent a directory?
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...
void reserve(size_type N)
std::error_code remove_directories(const Twine &path, bool IgnoreErrors=true)
Recursively delete a directory.
Represents the result of a call to sys::fs::status().
LLVM_ATTRIBUTE_ALWAYS_INLINE TimePoint< std::chrono::seconds > toTimePoint(std::time_t T)
Convert a std::time_t to a TimePoint.
CD_OpenAlways - When opening a file:
struct timespec toTimeSpec(TimePoint<> TP)
Convert a time point to struct timespec.
mapped_file_region()=delete
amode Optimize addressing mode
std::error_code directory_iterator_increment(DirIterState &)
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
std::error_code make_error_code(BitcodeError E)
bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
Tagged union holding either a T or a Error.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef take_until(function_ref< bool(char)> F) const
Return the longest prefix of 'this' such that no character in the prefix satisfies the given predicat...
When a child process is launched, this file should remain open in the child process.
CD_CreateNew - When opening a file:
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
std::error_code is_local(const Twine &path, bool &result)
Is the file mounted on a local filesystem?
std::error_code create_link(const Twine &to, const Twine &from)
Create a link from from to to.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
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...
std::error_code real_path(const Twine &path, SmallVectorImpl< char > &output, bool expand_tilde=false)
Collapse all .
initializer< Ty > init(const Ty &Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
The instances of the Type class are immutable: once they are created, they are never changed...
std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
UniqueID getUniqueID() const
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
std::error_code getError() const
uint32_t getLinkCount() const
TimePoint getLastModificationTime() const
StringRef toNullTerminatedStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single null terminated StringRef if it can be represented as such...
std::error_code resize_file(int FD, uint64_t Size)
Resize path to size.
auto RetryAfterSignal(const FailT &Fail, const Fun &F, const Args &... As) -> decltype(F(As...))
struct timeval toTimeVal(TimePoint< std::chrono::microseconds > TP)
Convert a time point to struct timeval.
std::error_code create_hard_link(const Twine &to, const Twine &from)
Create a hard link from from to to, or return an error.
void toVector(SmallVectorImpl< char > &Out) const
Append the concatenated string into the given SmallString or SmallVector.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static unsigned getPageSize()
std::error_code rename(const Twine &from, const Twine &to)
Rename from to to.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
std::error_code directory_iterator_construct(DirIterState &, StringRef, bool)
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.
std::error_code setPermissions(const Twine &Path, perms Permissions)
Set file permissions.
iterator insert(iterator I, T &&Elt)
std::error_code set_current_path(const Twine &path)
Set the current path.
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
ErrorOr< space_info > disk_space(const Twine &Path)
Get disk space usage information.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
std::error_code directory_iterator_destruct(DirIterState &)
pointer data()
Return a pointer to the vector's buffer, even if empty().
file_type
An enumeration for the file system's view of the type.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
std::error_code create_directory(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create the directory in path.
std::string str() const
Return the twine contents as a std::string.
void system_temp_directory(bool erasedOnReboot, SmallVectorImpl< char > &result)
Get the typical temporary directory for the system, e.g., "/var/tmp" or "C:/TEMP".
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool equivalent(file_status A, file_status B)
Do file_status's represent the same thing?
CD_CreateAlways - When opening a file:
void set_size(size_t Size)
Set the array size to N, which the current array must have enough capacity for.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
bool home_directory(SmallVectorImpl< char > &result)
Get the user's home directory.
std::error_code access(const Twine &Path, AccessMode Mode)
Can the file be accessed?
StringRef - Represent a constant reference to a string, i.e.
CD_OpenAlways - When opening a file:
TimePoint getLastAccessedTime() const
bool exists(const basic_file_status &status)
Does file exist?