28 #ifdef HAVE_SYS_MMAN_H
33 # define NAMLEN(dirent) strlen((dirent)->d_name)
35 # define dirent direct
36 # define NAMLEN(dirent) (dirent)->d_namlen
38 # include <sys/ndir.h>
49 #include <mach-o/dyld.h>
59 #if defined(__GNU__) && !defined(PATH_MAX)
60 # define PATH_MAX 4096
68 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
69 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
70 defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__)
72 test_dir(
char ret[PATH_MAX],
const char *dir,
const char *bin)
75 char fullpath[PATH_MAX];
77 snprintf(fullpath, PATH_MAX,
"%s/%s", dir, bin);
78 if (realpath(fullpath, ret) == NULL)
80 if (stat(fullpath, &sb) != 0)
87 getprogpath(
char ret[PATH_MAX],
const char *bin)
93 if (test_dir(ret,
"/", bin) == 0)
99 if (strchr(bin,
'/') != NULL) {
101 if (getcwd(cwd, PATH_MAX) == NULL)
103 if (test_dir(ret, cwd, bin) == 0)
109 if ((pv = getenv(
"PATH")) == NULL)
114 while ((t = strsep(&s,
":")) != NULL) {
115 if (test_dir(ret, t, bin) == 0) {
123 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
128 #if defined(__APPLE__)
132 char exe_path[MAXPATHLEN];
133 uint32_t
size =
sizeof(exe_path);
134 if (_NSGetExecutablePath(exe_path, &size) == 0) {
135 char link_path[MAXPATHLEN];
136 if (realpath(exe_path, link_path))
139 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
140 defined(__OpenBSD__) || defined(__minix) || defined(__DragonFly__) || \
141 defined(__FreeBSD_kernel__)
142 char exe_path[PATH_MAX];
144 if (getprogpath(exe_path, argv0) != NULL)
146 #elif defined(__linux__) || defined(__CYGWIN__)
147 char exe_path[MAXPATHLEN];
151 ssize_t len = readlink(aPath.str().c_str(), exe_path,
sizeof(exe_path));
153 return std::string(exe_path, len);
156 if (getprogpath(exe_path, argv0) != NULL)
159 #elif defined(HAVE_DLFCN_H)
162 int err = dladdr(MainAddr, &DLInfo);
168 char link_path[MAXPATHLEN];
169 if (realpath(DLInfo.dli_fname, link_path))
172 #error GetMainExecutable is not implemented on this host yet.
179 Ret.fromEpochTime(fs_st_mtime);
184 return UniqueID(fs_st_dev, fs_st_ino);
190 const char *pwd = ::getenv(
"PWD");
196 result.
append(pwd, pwd + strlen(pwd));
197 return std::error_code();
208 if (::getcwd(result.
data(), result.
capacity()) ==
nullptr) {
211 return std::error_code(errno, std::generic_category());
219 return std::error_code();
226 if (::mkdir(p.
begin(), S_IRWXU | S_IRWXG) == -1) {
227 if (errno != EEXIST || !IgnoreExisting)
228 return std::error_code(errno, std::generic_category());
231 return std::error_code();
244 return std::error_code(errno, std::generic_category());
246 return std::error_code();
249 std::error_code
remove(
const Twine &path,
bool IgnoreNonExisting) {
254 if (lstat(p.
begin(), &buf) != 0) {
255 if (errno != ENOENT || !IgnoreNonExisting)
256 return std::error_code(errno, std::generic_category());
257 return std::error_code();
265 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
268 if (::
remove(p.
begin()) == -1) {
269 if (errno != ENOENT || !IgnoreNonExisting)
270 return std::error_code(errno, std::generic_category());
273 return std::error_code();
284 return std::error_code(errno, std::generic_category());
286 return std::error_code();
289 std::error_code
resize_file(
int FD, uint64_t Size) {
290 if (::ftruncate(FD, Size) == -1)
291 return std::error_code(errno, std::generic_category());
293 return std::error_code();
296 static int convertAccessMode(
AccessMode Mode) {
312 if (::
access(P.
begin(), convertAccessMode(Mode)) == -1)
313 return std::error_code(errno, std::generic_category());
318 if (0 != stat(P.
begin(), &buf))
320 if (!S_ISREG(buf.st_mode))
324 return std::error_code();
329 return A.fs_st_dev == B.fs_st_dev &&
330 A.fs_st_ino == B.fs_st_ino;
334 file_status fsA, fsB;
335 if (std::error_code ec =
status(A, fsA))
337 if (std::error_code ec =
status(B, fsB))
340 return std::error_code();
343 static std::error_code fillStatus(
int StatRet,
const struct stat &
Status,
344 file_status &Result) {
346 std::error_code ec(errno, std::generic_category());
356 if (S_ISDIR(Status.st_mode))
358 else if (S_ISREG(Status.st_mode))
360 else if (S_ISBLK(Status.st_mode))
362 else if (S_ISCHR(Status.st_mode))
364 else if (S_ISFIFO(Status.st_mode))
366 else if (S_ISSOCK(Status.st_mode))
369 perms Perms =
static_cast<perms>(Status.st_mode);
371 file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
372 Status.st_uid, Status.st_gid, Status.st_size);
374 return std::error_code();
377 std::error_code
status(
const Twine &Path, file_status &Result) {
383 return fillStatus(StatRet, Status, Result);
386 std::error_code
status(
int FD, file_status &Result) {
388 int StatRet = ::fstat(FD, &Status);
389 return fillStatus(StatRet, Status, Result);
393 #if defined(HAVE_FUTIMENS)
395 Times[0].tv_sec = Time.toEpochTime();
396 Times[0].tv_nsec = 0;
398 if (::futimens(FD, Times))
399 return std::error_code(errno, std::generic_category());
400 return std::error_code();
401 #elif defined(HAVE_FUTIMES)
403 Times[0].tv_sec = Time.toEpochTime();
404 Times[0].tv_usec = 0;
406 if (::futimes(FD, Times))
407 return std::error_code(errno, std::generic_category());
408 return std::error_code();
410 #warning Missing futimes() and futimens()
419 int flags = (Mode ==
readwrite) ? MAP_SHARED : MAP_PRIVATE;
420 int prot = (Mode ==
readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
421 Mapping = ::mmap(
nullptr, Size, prot, flags, FD, Offset);
422 if (Mapping == MAP_FAILED)
423 return std::error_code(errno, std::generic_category());
424 return std::error_code();
427 mapped_file_region::mapped_file_region(
int fd, mapmode mode, uint64_t length,
428 uint64_t offset, std::error_code &ec)
429 : Size(length), Mapping() {
431 if (length > std::numeric_limits<size_t>::max()) {
436 ec =
init(fd, offset, mode);
441 mapped_file_region::~mapped_file_region() {
443 ::munmap(Mapping, Size);
447 assert(Mapping &&
"Mapping failed but used anyway!");
451 char *mapped_file_region::data()
const {
452 assert(Mapping &&
"Mapping failed but used anyway!");
453 return reinterpret_cast<char*
>(Mapping);
456 const char *mapped_file_region::const_data()
const {
457 assert(Mapping &&
"Mapping failed but used anyway!");
458 return reinterpret_cast<const char*
>(Mapping);
461 int mapped_file_region::alignment() {
468 DIR *directory = ::opendir(path_null.c_str());
470 return std::error_code(errno, std::generic_category());
472 it.IterationHandle =
reinterpret_cast<intptr_t>(directory);
475 it.CurrentEntry = directory_entry(path_null.str());
480 if (it.IterationHandle)
481 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
482 it.IterationHandle = 0;
483 it.CurrentEntry = directory_entry();
484 return std::error_code();
489 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
490 if (cur_dir ==
nullptr && errno != 0) {
491 return std::error_code(errno, std::generic_category());
492 }
else if (cur_dir !=
nullptr) {
494 if ((
name.size() == 1 &&
name[0] ==
'.') ||
497 it.CurrentEntry.replace_filename(
name);
501 return std::error_code();
507 while ((ResultFD = open(P.
begin(), O_RDONLY)) < 0) {
509 return std::error_code(errno, std::generic_category());
511 return std::error_code();
518 "Cannot specify both 'excl' and 'append' file creation flags!");
525 OpenFlags |= O_WRONLY;
528 OpenFlags |= O_APPEND;
530 OpenFlags |= O_TRUNC;
539 return std::error_code(errno, std::generic_category());
541 return std::error_code();
549 if (
char *RequestedDir = getenv(
"HOME")) {
551 result.
append(RequestedDir, RequestedDir + strlen(RequestedDir));
558 static const char *getEnvTempDir() {
561 const char *EnvironmentVariables[] = {
"TMPDIR",
"TMP",
"TEMP",
"TEMPDIR"};
562 for (
const char *Env : EnvironmentVariables) {
563 if (
const char *Dir = std::getenv(Env))
570 static const char *getDefaultTempDir(
bool ErasedOnReboot) {
584 if (ErasedOnReboot) {
586 if (
const char *RequestedDir = getEnvTempDir()) {
587 Result.
append(RequestedDir, RequestedDir + strlen(RequestedDir));
592 #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
595 int ConfName = ErasedOnReboot? _CS_DARWIN_USER_TEMP_DIR
596 : _CS_DARWIN_USER_CACHE_DIR;
597 size_t ConfLen = confstr(ConfName,
nullptr, 0);
601 ConfLen = confstr(ConfName, Result.
data(), Result.
size());
602 }
while (ConfLen > 0 && ConfLen != Result.
size());
605 assert(Result.
back() == 0);
614 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
615 Result.
append(RequestedDir, RequestedDir + strlen(RequestedDir));
F_Append - When opening a file, if it already exists append to the existing file instead of returning...
size_t capacity() const
Return the total number of elements in the currently allocated buffer.
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 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.
bool status_known(file_status s)
Is status available?
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...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
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_directory(const Twine &path, bool IgnoreExisting=true)
Create the directory in path.
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.
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...
std::error_code directory_iterator_construct(DirIterState &, StringRef)
std::error_code resize_file(int FD, uint64_t Size)
Resize path to size.
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time)
Set the file modification and access time.
static unsigned getPageSize()
std::error_code rename(const Twine &from, const Twine &to)
Rename from to to.
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.
std::error_code openFileForRead(const Twine &Name, int &ResultFD)
void system_temp_directory(bool erasedOnReboot, SmallVectorImpl< char > &result)
Get the typical temporary directory for the system, e.g., "/var/tmp" or "C:/TEMP".
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...
TimeValue getLastModificationTime() const
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?
std::error_code openFileForWrite(const Twine &Name, int &ResultFD, OpenFlags Flags, unsigned Mode=0666)