31 #ifdef HAVE_SYS_MMAN_H
36 # define NAMLEN(dirent) strlen((dirent)->d_name)
38 # define dirent direct
39 # define NAMLEN(dirent) (dirent)->d_namlen
41 # include <sys/ndir.h>
52 #include <mach-o/dyld.h>
63 #if defined(__GNU__) && !defined(PATH_MAX)
64 # define PATH_MAX 4096
67 #include <sys/types.h>
68 #if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__ANDROID__)
69 #include <sys/statvfs.h>
70 #define STATVFS statvfs
71 #define STATVFS_F_FRSIZE(vfs) vfs.f_frsize
74 #include <sys/param.h>
75 #include <sys/mount.h>
76 #elif defined(__ANDROID__)
79 #include <sys/mount.h>
81 #define STATVFS statfs
82 #define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
91 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
92 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
93 defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__) || \
96 test_dir(
char ret[PATH_MAX],
const char *dir,
const char *bin)
99 char fullpath[PATH_MAX];
101 snprintf(fullpath, PATH_MAX,
"%s/%s", dir, bin);
102 if (!realpath(fullpath, ret))
104 if (stat(fullpath, &sb) != 0)
111 getprogpath(
char ret[PATH_MAX],
const char *bin)
117 if (test_dir(ret,
"/", bin) == 0)
123 if (strchr(bin,
'/')) {
125 if (!getcwd(cwd, PATH_MAX))
127 if (test_dir(ret, cwd, bin) == 0)
133 if ((pv = getenv(
"PATH")) ==
nullptr)
138 while ((t = strsep(&s,
":")) !=
nullptr) {
139 if (test_dir(ret, t, bin) == 0) {
147 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
152 #if defined(__APPLE__)
156 char exe_path[MAXPATHLEN];
158 if (_NSGetExecutablePath(exe_path, &size) == 0) {
159 char link_path[MAXPATHLEN];
160 if (realpath(exe_path, link_path))
163 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
164 defined(__OpenBSD__) || defined(__minix) || defined(__DragonFly__) || \
165 defined(__FreeBSD_kernel__) || defined(_AIX)
166 char exe_path[PATH_MAX];
168 if (getprogpath(exe_path, argv0) != NULL)
170 #elif defined(__linux__) || defined(__CYGWIN__)
171 char exe_path[MAXPATHLEN];
175 ssize_t len = readlink(aPath.str().c_str(), exe_path,
sizeof(exe_path));
177 return std::string(exe_path, len);
180 if (getprogpath(exe_path, argv0))
183 #elif defined(HAVE_DLFCN_H)
186 int err = dladdr(MainAddr, &DLInfo);
192 char link_path[MAXPATHLEN];
193 if (realpath(DLInfo.dli_fname, link_path))
196 #error GetMainExecutable is not implemented on this host yet.
210 return UniqueID(fs_st_dev, fs_st_ino);
215 if (::STATVFS(Path.
str().c_str(), &Vfs))
216 return std::error_code(errno, std::generic_category());
217 auto FrSize = STATVFS_F_FRSIZE(Vfs);
218 space_info SpaceInfo;
219 SpaceInfo.capacity =
static_cast<uint64_t
>(Vfs.f_blocks) * FrSize;
220 SpaceInfo.free =
static_cast<uint64_t
>(Vfs.f_bfree) * FrSize;
221 SpaceInfo.available =
static_cast<uint64_t
>(Vfs.f_bavail) * FrSize;
228 const char *pwd = ::getenv(
"PWD");
234 result.
append(pwd, pwd + strlen(pwd));
235 return std::error_code();
246 if (::getcwd(result.
data(), result.
capacity()) ==
nullptr) {
249 return std::error_code(errno, std::generic_category());
257 return std::error_code();
265 if (::mkdir(p.
begin(), Perms) == -1) {
266 if (errno != EEXIST || !IgnoreExisting)
267 return std::error_code(errno, std::generic_category());
270 return std::error_code();
283 return std::error_code(errno, std::generic_category());
285 return std::error_code();
296 return std::error_code(errno, std::generic_category());
298 return std::error_code();
301 std::error_code
remove(
const Twine &path,
bool IgnoreNonExisting) {
306 if (lstat(p.
begin(), &buf) != 0) {
307 if (errno != ENOENT || !IgnoreNonExisting)
308 return std::error_code(errno, std::generic_category());
309 return std::error_code();
317 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
320 if (::
remove(p.
begin()) == -1) {
321 if (errno != ENOENT || !IgnoreNonExisting)
322 return std::error_code(errno, std::generic_category());
325 return std::error_code();
336 return std::error_code(errno, std::generic_category());
338 return std::error_code();
341 std::error_code
resize_file(
int FD, uint64_t Size) {
342 #if defined(HAVE_POSIX_FALLOCATE)
345 if (
int Err = ::posix_fallocate(FD, 0, Size))
346 return std::error_code(Err, std::generic_category());
350 if (::ftruncate(FD, Size) == -1)
351 return std::error_code(errno, std::generic_category());
354 return std::error_code();
373 if (::
access(P.
begin(), convertAccessMode(Mode)) == -1)
374 return std::error_code(errno, std::generic_category());
379 if (0 != stat(P.
begin(), &buf))
381 if (!S_ISREG(buf.st_mode))
385 return std::error_code();
394 return A.fs_st_dev == B.fs_st_dev &&
395 A.fs_st_ino == B.fs_st_ino;
399 file_status fsA, fsB;
400 if (std::error_code ec =
status(A, fsA))
402 if (std::error_code ec =
status(B, fsB))
405 return std::error_code();
408 static std::error_code fillStatus(
int StatRet,
const struct stat &
Status,
409 file_status &Result) {
411 std::error_code ec(errno, std::generic_category());
421 if (S_ISDIR(Status.st_mode))
423 else if (S_ISREG(Status.st_mode))
425 else if (S_ISBLK(Status.st_mode))
427 else if (S_ISCHR(Status.st_mode))
429 else if (S_ISFIFO(Status.st_mode))
431 else if (S_ISSOCK(Status.st_mode))
434 perms Perms =
static_cast<perms>(Status.st_mode);
436 file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_atime,
437 Status.st_mtime, Status.st_uid, Status.st_gid,
440 return std::error_code();
443 std::error_code
status(
const Twine &Path, file_status &Result) {
449 return fillStatus(StatRet, Status, Result);
452 std::error_code
status(
int FD, file_status &Result) {
454 int StatRet = ::fstat(FD, &Status);
455 return fillStatus(StatRet, Status, Result);
459 #if defined(HAVE_FUTIMENS)
462 if (::futimens(FD, Times))
463 return std::error_code(errno, std::generic_category());
464 return std::error_code();
465 #elif defined(HAVE_FUTIMES)
468 std::chrono::time_point_cast<std::chrono::microseconds>(Time));
469 if (::futimes(FD, Times))
470 return std::error_code(errno, std::generic_category());
471 return std::error_code();
473 #warning Missing futimes() and futimens()
482 int flags = (Mode ==
readwrite) ? MAP_SHARED : MAP_PRIVATE;
483 int prot = (Mode ==
readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
484 Mapping = ::mmap(
nullptr, Size, prot, flags, FD, Offset);
485 if (Mapping == MAP_FAILED)
486 return std::error_code(errno, std::generic_category());
487 return std::error_code();
491 uint64_t offset, std::error_code &ec)
492 : Size(length), Mapping() {
494 if (length > std::numeric_limits<size_t>::max()) {
499 ec =
init(fd, offset, mode);
504 mapped_file_region::~mapped_file_region() {
506 ::munmap(Mapping, Size);
509 uint64_t mapped_file_region::size()
const {
510 assert(Mapping &&
"Mapping failed but used anyway!");
514 char *mapped_file_region::data()
const {
515 assert(Mapping &&
"Mapping failed but used anyway!");
516 return reinterpret_cast<char*
>(Mapping);
519 const char *mapped_file_region::const_data()
const {
520 assert(Mapping &&
"Mapping failed but used anyway!");
521 return reinterpret_cast<const char*
>(Mapping);
524 int mapped_file_region::alignment() {
531 DIR *directory = ::opendir(path_null.c_str());
533 return std::error_code(errno, std::generic_category());
535 it.IterationHandle =
reinterpret_cast<intptr_t>(directory);
538 it.CurrentEntry = directory_entry(path_null.str());
543 if (it.IterationHandle)
544 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
545 it.IterationHandle = 0;
546 it.CurrentEntry = directory_entry();
547 return std::error_code();
552 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
553 if (cur_dir ==
nullptr && errno != 0) {
554 return std::error_code(errno, std::generic_category());
555 }
else if (cur_dir !=
nullptr) {
557 if ((
name.size() == 1 &&
name[0] ==
'.') ||
560 it.CurrentEntry.replace_filename(
name);
564 return std::error_code();
567 #if !defined(F_GETPATH)
568 static bool hasProcSelfFD() {
571 static const bool Result = (
::access(
"/proc/self/fd", R_OK) == 0);
580 while ((ResultFD = open(P.
begin(), O_RDONLY)) < 0) {
582 return std::error_code(errno, std::generic_category());
586 return std::error_code();
588 #if defined(F_GETPATH)
591 char Buffer[MAXPATHLEN];
592 if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
593 RealPath->
append(Buffer, Buffer + strlen(Buffer));
595 char Buffer[PATH_MAX];
596 if (hasProcSelfFD()) {
598 snprintf(ProcPath,
sizeof(ProcPath),
"/proc/self/fd/%d", ResultFD);
599 ssize_t CharCount = ::readlink(ProcPath, Buffer,
sizeof(Buffer));
601 RealPath->
append(Buffer, Buffer + CharCount);
604 if (::realpath(P.
begin(), Buffer) !=
nullptr)
605 RealPath->
append(Buffer, Buffer + strlen(Buffer));
608 return std::error_code();
615 "Cannot specify both 'excl' and 'append' file creation flags!");
622 OpenFlags |= O_WRONLY;
625 OpenFlags |= O_APPEND;
627 OpenFlags |= O_TRUNC;
636 return std::error_code(errno, std::generic_category());
638 return std::error_code();
645 #if defined(F_GETPATH)
648 ResultPath.
reserve(MAXPATHLEN);
649 if (::fcntl(FD, F_GETPATH, ResultPath.
begin()) == -1)
650 return std::error_code(errno, std::generic_category());
657 if (!fs::hasProcSelfFD())
662 snprintf(ProcPath,
sizeof(ProcPath),
"/proc/self/fd/%d", FD);
663 ssize_t CharCount = ::readlink(ProcPath, ResultPath.
begin(), ResultPath.
capacity());
665 return std::error_code(errno, std::generic_category());
668 if (static_cast<size_t>(CharCount) == ResultPath.
capacity()) {
671 if (::lstat(ProcPath, &sb) < 0)
672 return std::error_code(errno, std::generic_category());
674 ResultPath.
reserve(sb.st_size + 1);
675 CharCount = ::readlink(ProcPath, ResultPath.
begin(), ResultPath.
capacity());
677 return std::error_code(errno, std::generic_category());
680 if (CharCount > sb.st_size)
681 return std::error_code(ENAMETOOLONG, std::generic_category());
683 ResultPath.
set_size(static_cast<size_t>(CharCount));
685 return std::error_code();
693 if (
char *RequestedDir = getenv(
"HOME")) {
695 result.
append(RequestedDir, RequestedDir + strlen(RequestedDir));
703 #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
706 int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
707 : _CS_DARWIN_USER_CACHE_DIR;
708 size_t ConfLen = confstr(ConfName,
nullptr, 0);
712 ConfLen = confstr(ConfName, Result.
data(), Result.
size());
713 }
while (ConfLen > 0 && ConfLen != Result.
size());
731 if (
const char *XdgCacheDir = std::getenv(
"XDG_CACHE_HOME")) {
733 Result.
append(XdgCacheDir, XdgCacheDir + strlen(XdgCacheDir));
738 if (getDarwinConfDir(
false, Result))
750 static const char *getEnvTempDir() {
753 const char *EnvironmentVariables[] = {
"TMPDIR",
"TMP",
"TEMP",
"TEMPDIR"};
754 for (
const char *Env : EnvironmentVariables) {
755 if (
const char *Dir = std::getenv(Env))
762 static const char *getDefaultTempDir(
bool ErasedOnReboot) {
776 if (ErasedOnReboot) {
778 if (
const char *RequestedDir = getEnvTempDir()) {
779 Result.
append(RequestedDir, RequestedDir + strlen(RequestedDir));
784 if (getDarwinConfDir(ErasedOnReboot, Result))
787 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
788 Result.
append(RequestedDir, RequestedDir + strlen(RequestedDir));
F_Append - When opening a file, if it already exists append to the existing file instead of returning...
bool can_execute(const Twine &Path)
Can we execute this file?
Represents either an error or a value T.
size_t capacity() const
Return the total number of elements in the currently allocated buffer.
std::error_code openFileForRead(const Twine &Name, int &ResultFD, SmallVectorImpl< char > *RealPath=nullptr)
F_Excl - When opening a file, this flag makes raw_fd_ostream report an error if the file already exis...
UniqueID getUniqueID() const
std::error_code setLastModificationAndAccessTime(int FD, TimePoint<> Time)
Set the file modification and access time.
opt Optimize addressing mode
std::error_code current_path(SmallVectorImpl< char > &result)
Get the current path.
void reserve(size_type N)
file_status - Represents the result of a call to stat and friends.
LLVM_ATTRIBUTE_ALWAYS_INLINE TimePoint< std::chrono::seconds > toTimePoint(std::time_t T)
Convert a std::time_t to a TimePoint.
bool status_known(file_status s)
Is status available?
struct timespec toTimeSpec(TimePoint<> TP)
Convert a time point to struct timespec.
mapped_file_region()=delete
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.
std::string str() const
Return the twine contents as a std::string.
struct fuzzer::@269 Flags
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)
Is path absolute?
May access map via data and modify it. Written to path.
May only access map via const_data as read only.
std::error_code create_link(const Twine &to, const Twine &from)
Create a link from from to to.
Open the file for read and write.
static GCRegistry::Add< OcamlGC > B("ocaml","ocaml 3.10-compatible GC")
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...
initializer< Ty > init(const Ty &Val)
The instances of the Type class are immutable: once they are created, they are never changed...
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
std::error_code directory_iterator_construct(DirIterState &, StringRef)
TimePoint getLastAccessedTime() const
std::error_code resize_file(int FD, uint64_t Size)
Resize path to size.
struct timeval toTimeVal(TimePoint< std::chrono::microseconds > TP)
Convert a time point to struct timeval.
std::error_code getPathFromOpenFD(int FD, SmallVectorImpl< char > &ResultPath)
Fetch a path to an open file, as specified by a file descriptor.
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 append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the 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.
ErrorOr< space_info > disk_space(const Twine &Path)
Get disk space usage information.
void set_size(size_type N)
Set the array size to N, which the current array must have enough capacity for.
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.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
TimePoint getLastModificationTime() const
std::error_code create_directory(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create the directory in path.
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?
StringRef toNullTerminatedStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single null terminated StringRef if it can be represented as such...
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.
std::error_code status(const Twine &path, file_status &result)
Get file status as if by POSIX stat().
bool exists(file_status status)
Does file exist?
static GCRegistry::Add< ErlangGC > A("erlang","erlang-compatible garbage collector")
std::error_code openFileForWrite(const Twine &Name, int &ResultFD, OpenFlags Flags, unsigned Mode=0666)