Path.inc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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. //=== WARNING: Implementation here must contain only generic UNIX code that
  15. //=== is guaranteed to work on *all* UNIX variants.
  16. //===----------------------------------------------------------------------===//
  17. #include "Unix.h"
  18. #include <limits.h>
  19. #include <stdio.h>
  20. #if HAVE_SYS_STAT_H
  21. #include <sys/stat.h>
  22. #endif
  23. #if HAVE_FCNTL_H
  24. #include <fcntl.h>
  25. #endif
  26. #ifdef HAVE_SYS_MMAN_H
  27. #include <sys/mman.h>
  28. #endif
  29. #if HAVE_DIRENT_H
  30. # include <dirent.h>
  31. # define NAMLEN(dirent) strlen((dirent)->d_name)
  32. #else
  33. # define dirent direct
  34. # define NAMLEN(dirent) (dirent)->d_namlen
  35. # if HAVE_SYS_NDIR_H
  36. # include <sys/ndir.h>
  37. # endif
  38. # if HAVE_SYS_DIR_H
  39. # include <sys/dir.h>
  40. # endif
  41. # if HAVE_NDIR_H
  42. # include <ndir.h>
  43. # endif
  44. #endif
  45. #ifdef __APPLE__
  46. #include <mach-o/dyld.h>
  47. #endif
  48. // Both stdio.h and cstdio are included via different pathes and
  49. // stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
  50. // either.
  51. #undef ferror
  52. #undef feof
  53. // For GNU Hurd
  54. #if defined(__GNU__) && !defined(PATH_MAX)
  55. # define PATH_MAX 4096
  56. #endif
  57. using namespace llvm;
  58. namespace llvm {
  59. namespace sys {
  60. namespace fs {
  61. #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
  62. defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
  63. defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__)
  64. static int
  65. test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
  66. {
  67. struct stat sb;
  68. char fullpath[PATH_MAX];
  69. snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
  70. if (realpath(fullpath, ret) == NULL)
  71. return (1);
  72. if (stat(fullpath, &sb) != 0)
  73. return (1);
  74. return (0);
  75. }
  76. static char *
  77. getprogpath(char ret[PATH_MAX], const char *bin)
  78. {
  79. char *pv, *s, *t;
  80. /* First approach: absolute path. */
  81. if (bin[0] == '/') {
  82. if (test_dir(ret, "/", bin) == 0)
  83. return (ret);
  84. return (NULL);
  85. }
  86. /* Second approach: relative path. */
  87. if (strchr(bin, '/') != NULL) {
  88. char cwd[PATH_MAX];
  89. if (getcwd(cwd, PATH_MAX) == NULL)
  90. return (NULL);
  91. if (test_dir(ret, cwd, bin) == 0)
  92. return (ret);
  93. return (NULL);
  94. }
  95. /* Third approach: $PATH */
  96. if ((pv = getenv("PATH")) == NULL)
  97. return (NULL);
  98. s = pv = strdup(pv);
  99. if (pv == NULL)
  100. return (NULL);
  101. while ((t = strsep(&s, ":")) != NULL) {
  102. if (test_dir(ret, t, bin) == 0) {
  103. free(pv);
  104. return (ret);
  105. }
  106. }
  107. free(pv);
  108. return (NULL);
  109. }
  110. #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
  111. /// GetMainExecutable - Return the path to the main executable, given the
  112. /// value of argv[0] from program startup.
  113. std::string getMainExecutable(const char *argv0, void *MainAddr) {
  114. #if defined(__APPLE__)
  115. // On OS X the executable path is saved to the stack by dyld. Reading it
  116. // from there is much faster than calling dladdr, especially for large
  117. // binaries with symbols.
  118. char exe_path[MAXPATHLEN];
  119. uint32_t size = sizeof(exe_path);
  120. if (_NSGetExecutablePath(exe_path, &size) == 0) {
  121. char link_path[MAXPATHLEN];
  122. if (realpath(exe_path, link_path))
  123. return link_path;
  124. }
  125. #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
  126. defined(__OpenBSD__) || defined(__minix) || defined(__DragonFly__) || \
  127. defined(__FreeBSD_kernel__)
  128. char exe_path[PATH_MAX];
  129. if (getprogpath(exe_path, argv0) != NULL)
  130. return exe_path;
  131. #elif defined(__linux__) || defined(__CYGWIN__)
  132. char exe_path[MAXPATHLEN];
  133. StringRef aPath("/proc/self/exe");
  134. if (sys::fs::exists(aPath)) {
  135. // /proc is not always mounted under Linux (chroot for example).
  136. ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
  137. if (len >= 0)
  138. return std::string(exe_path, len);
  139. } else {
  140. // Fall back to the classical detection.
  141. if (getprogpath(exe_path, argv0) != NULL)
  142. return exe_path;
  143. }
  144. #elif defined(HAVE_DLFCN_H)
  145. // Use dladdr to get executable path if available.
  146. Dl_info DLInfo;
  147. int err = dladdr(MainAddr, &DLInfo);
  148. if (err == 0)
  149. return "";
  150. // If the filename is a symlink, we need to resolve and return the location of
  151. // the actual executable.
  152. char link_path[MAXPATHLEN];
  153. if (realpath(DLInfo.dli_fname, link_path))
  154. return link_path;
  155. #else
  156. #error GetMainExecutable is not implemented on this host yet.
  157. #endif
  158. return "";
  159. }
  160. TimeValue file_status::getLastModificationTime() const {
  161. TimeValue Ret;
  162. Ret.fromEpochTime(fs_st_mtime);
  163. return Ret;
  164. }
  165. UniqueID file_status::getUniqueID() const {
  166. return UniqueID(fs_st_dev, fs_st_ino);
  167. }
  168. std::error_code current_path(SmallVectorImpl<char> &result) {
  169. result.clear();
  170. const char *pwd = ::getenv("PWD");
  171. llvm::sys::fs::file_status PWDStatus, DotStatus;
  172. if (pwd && llvm::sys::path::is_absolute(pwd) &&
  173. !llvm::sys::fs::status(pwd, PWDStatus) &&
  174. !llvm::sys::fs::status(".", DotStatus) &&
  175. PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
  176. result.append(pwd, pwd + strlen(pwd));
  177. return std::error_code();
  178. }
  179. #ifdef MAXPATHLEN
  180. result.reserve(MAXPATHLEN);
  181. #else
  182. // For GNU Hurd
  183. result.reserve(1024);
  184. #endif
  185. while (true) {
  186. if (::getcwd(result.data(), result.capacity()) == nullptr) {
  187. // See if there was a real error.
  188. if (errno != ENOMEM)
  189. return std::error_code(errno, std::generic_category());
  190. // Otherwise there just wasn't enough space.
  191. result.reserve(result.capacity() * 2);
  192. } else
  193. break;
  194. }
  195. result.set_size(strlen(result.data()));
  196. return std::error_code();
  197. }
  198. std::error_code create_directory(const Twine &path, bool IgnoreExisting) {
  199. SmallString<128> path_storage;
  200. StringRef p = path.toNullTerminatedStringRef(path_storage);
  201. if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
  202. if (errno != EEXIST || !IgnoreExisting)
  203. return std::error_code(errno, std::generic_category());
  204. }
  205. return std::error_code();
  206. }
  207. // Note that we are using symbolic link because hard links are not supported by
  208. // all filesystems (SMB doesn't).
  209. std::error_code create_link(const Twine &to, const Twine &from) {
  210. // Get arguments.
  211. SmallString<128> from_storage;
  212. SmallString<128> to_storage;
  213. StringRef f = from.toNullTerminatedStringRef(from_storage);
  214. StringRef t = to.toNullTerminatedStringRef(to_storage);
  215. if (::symlink(t.begin(), f.begin()) == -1)
  216. return std::error_code(errno, std::generic_category());
  217. return std::error_code();
  218. }
  219. std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
  220. SmallString<128> path_storage;
  221. StringRef p = path.toNullTerminatedStringRef(path_storage);
  222. struct stat buf;
  223. if (lstat(p.begin(), &buf) != 0) {
  224. if (errno != ENOENT || !IgnoreNonExisting)
  225. return std::error_code(errno, std::generic_category());
  226. return std::error_code();
  227. }
  228. // Note: this check catches strange situations. In all cases, LLVM should
  229. // only be involved in the creation and deletion of regular files. This
  230. // check ensures that what we're trying to erase is a regular file. It
  231. // effectively prevents LLVM from erasing things like /dev/null, any block
  232. // special file, or other things that aren't "regular" files.
  233. if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
  234. return make_error_code(errc::operation_not_permitted);
  235. if (::remove(p.begin()) == -1) {
  236. if (errno != ENOENT || !IgnoreNonExisting)
  237. return std::error_code(errno, std::generic_category());
  238. }
  239. return std::error_code();
  240. }
  241. std::error_code rename(const Twine &from, const Twine &to) {
  242. // Get arguments.
  243. SmallString<128> from_storage;
  244. SmallString<128> to_storage;
  245. StringRef f = from.toNullTerminatedStringRef(from_storage);
  246. StringRef t = to.toNullTerminatedStringRef(to_storage);
  247. if (::rename(f.begin(), t.begin()) == -1)
  248. return std::error_code(errno, std::generic_category());
  249. return std::error_code();
  250. }
  251. std::error_code resize_file(int FD, uint64_t Size) {
  252. if (::ftruncate(FD, Size) == -1)
  253. return std::error_code(errno, std::generic_category());
  254. return std::error_code();
  255. }
  256. static int convertAccessMode(AccessMode Mode) {
  257. switch (Mode) {
  258. case AccessMode::Exist:
  259. return F_OK;
  260. case AccessMode::Write:
  261. return W_OK;
  262. case AccessMode::Execute:
  263. return R_OK | X_OK; // scripts also need R_OK.
  264. }
  265. llvm_unreachable("invalid enum");
  266. }
  267. std::error_code access(const Twine &Path, AccessMode Mode) {
  268. SmallString<128> PathStorage;
  269. StringRef P = Path.toNullTerminatedStringRef(PathStorage);
  270. if (::access(P.begin(), convertAccessMode(Mode)) == -1)
  271. return std::error_code(errno, std::generic_category());
  272. if (Mode == AccessMode::Execute) {
  273. // Don't say that directories are executable.
  274. struct stat buf;
  275. if (0 != stat(P.begin(), &buf))
  276. return errc::permission_denied;
  277. if (!S_ISREG(buf.st_mode))
  278. return errc::permission_denied;
  279. }
  280. return std::error_code();
  281. }
  282. bool equivalent(file_status A, file_status B) {
  283. assert(status_known(A) && status_known(B));
  284. return A.fs_st_dev == B.fs_st_dev &&
  285. A.fs_st_ino == B.fs_st_ino;
  286. }
  287. std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
  288. file_status fsA, fsB;
  289. if (std::error_code ec = status(A, fsA))
  290. return ec;
  291. if (std::error_code ec = status(B, fsB))
  292. return ec;
  293. result = equivalent(fsA, fsB);
  294. return std::error_code();
  295. }
  296. static std::error_code fillStatus(int StatRet, const struct stat &Status,
  297. file_status &Result) {
  298. if (StatRet != 0) {
  299. std::error_code ec(errno, std::generic_category());
  300. if (ec == errc::no_such_file_or_directory)
  301. Result = file_status(file_type::file_not_found);
  302. else
  303. Result = file_status(file_type::status_error);
  304. return ec;
  305. }
  306. file_type Type = file_type::type_unknown;
  307. if (S_ISDIR(Status.st_mode))
  308. Type = file_type::directory_file;
  309. else if (S_ISREG(Status.st_mode))
  310. Type = file_type::regular_file;
  311. else if (S_ISBLK(Status.st_mode))
  312. Type = file_type::block_file;
  313. else if (S_ISCHR(Status.st_mode))
  314. Type = file_type::character_file;
  315. else if (S_ISFIFO(Status.st_mode))
  316. Type = file_type::fifo_file;
  317. else if (S_ISSOCK(Status.st_mode))
  318. Type = file_type::socket_file;
  319. perms Perms = static_cast<perms>(Status.st_mode);
  320. Result =
  321. file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
  322. Status.st_uid, Status.st_gid, Status.st_size);
  323. return std::error_code();
  324. }
  325. std::error_code status(const Twine &Path, file_status &Result) {
  326. SmallString<128> PathStorage;
  327. StringRef P = Path.toNullTerminatedStringRef(PathStorage);
  328. struct stat Status;
  329. int StatRet = ::stat(P.begin(), &Status);
  330. return fillStatus(StatRet, Status, Result);
  331. }
  332. std::error_code status(int FD, file_status &Result) {
  333. struct stat Status;
  334. int StatRet = ::fstat(FD, &Status);
  335. return fillStatus(StatRet, Status, Result);
  336. }
  337. std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
  338. #if defined(HAVE_FUTIMENS)
  339. timespec Times[2];
  340. Times[0].tv_sec = Time.toEpochTime();
  341. Times[0].tv_nsec = 0;
  342. Times[1] = Times[0];
  343. if (::futimens(FD, Times))
  344. return std::error_code(errno, std::generic_category());
  345. return std::error_code();
  346. #elif defined(HAVE_FUTIMES)
  347. timeval Times[2];
  348. Times[0].tv_sec = Time.toEpochTime();
  349. Times[0].tv_usec = 0;
  350. Times[1] = Times[0];
  351. if (::futimes(FD, Times))
  352. return std::error_code(errno, std::generic_category());
  353. return std::error_code();
  354. #else
  355. #warning Missing futimes() and futimens()
  356. return make_error_code(errc::function_not_supported);
  357. #endif
  358. }
  359. std::error_code mapped_file_region::init(int FD, uint64_t Offset,
  360. mapmode Mode) {
  361. assert(Size != 0);
  362. int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
  363. int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
  364. Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
  365. if (Mapping == MAP_FAILED)
  366. return std::error_code(errno, std::generic_category());
  367. return std::error_code();
  368. }
  369. mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
  370. uint64_t offset, std::error_code &ec)
  371. : Size(length), Mapping() {
  372. // Make sure that the requested size fits within SIZE_T.
  373. if (length > std::numeric_limits<size_t>::max()) {
  374. ec = make_error_code(errc::invalid_argument);
  375. return;
  376. }
  377. ec = init(fd, offset, mode);
  378. if (ec)
  379. Mapping = nullptr;
  380. }
  381. mapped_file_region::~mapped_file_region() {
  382. if (Mapping)
  383. ::munmap(Mapping, Size);
  384. }
  385. uint64_t mapped_file_region::size() const {
  386. assert(Mapping && "Mapping failed but used anyway!");
  387. return Size;
  388. }
  389. char *mapped_file_region::data() const {
  390. assert(Mapping && "Mapping failed but used anyway!");
  391. return reinterpret_cast<char*>(Mapping);
  392. }
  393. const char *mapped_file_region::const_data() const {
  394. assert(Mapping && "Mapping failed but used anyway!");
  395. return reinterpret_cast<const char*>(Mapping);
  396. }
  397. int mapped_file_region::alignment() {
  398. return Process::getPageSize();
  399. }
  400. std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
  401. StringRef path){
  402. SmallString<128> path_null(path);
  403. DIR *directory = ::opendir(path_null.c_str());
  404. if (!directory)
  405. return std::error_code(errno, std::generic_category());
  406. it.IterationHandle = reinterpret_cast<intptr_t>(directory);
  407. // Add something for replace_filename to replace.
  408. path::append(path_null, ".");
  409. it.CurrentEntry = directory_entry(path_null.str());
  410. return directory_iterator_increment(it);
  411. }
  412. std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
  413. if (it.IterationHandle)
  414. ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
  415. it.IterationHandle = 0;
  416. it.CurrentEntry = directory_entry();
  417. return std::error_code();
  418. }
  419. std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
  420. errno = 0;
  421. dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
  422. if (cur_dir == nullptr && errno != 0) {
  423. return std::error_code(errno, std::generic_category());
  424. } else if (cur_dir != nullptr) {
  425. StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
  426. if ((name.size() == 1 && name[0] == '.') ||
  427. (name.size() == 2 && name[0] == '.' && name[1] == '.'))
  428. return directory_iterator_increment(it);
  429. it.CurrentEntry.replace_filename(name);
  430. } else
  431. return directory_iterator_destruct(it);
  432. return std::error_code();
  433. }
  434. std::error_code openFileForRead(const Twine &Name, int &ResultFD) {
  435. SmallString<128> Storage;
  436. StringRef P = Name.toNullTerminatedStringRef(Storage);
  437. while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
  438. if (errno != EINTR)
  439. return std::error_code(errno, std::generic_category());
  440. }
  441. return std::error_code();
  442. }
  443. std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
  444. sys::fs::OpenFlags Flags, unsigned Mode) {
  445. // Verify that we don't have both "append" and "excl".
  446. assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
  447. "Cannot specify both 'excl' and 'append' file creation flags!");
  448. int OpenFlags = O_CREAT;
  449. if (Flags & F_RW)
  450. OpenFlags |= O_RDWR;
  451. else
  452. OpenFlags |= O_WRONLY;
  453. if (Flags & F_Append)
  454. OpenFlags |= O_APPEND;
  455. else
  456. OpenFlags |= O_TRUNC;
  457. if (Flags & F_Excl)
  458. OpenFlags |= O_EXCL;
  459. SmallString<128> Storage;
  460. StringRef P = Name.toNullTerminatedStringRef(Storage);
  461. while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
  462. if (errno != EINTR)
  463. return std::error_code(errno, std::generic_category());
  464. }
  465. return std::error_code();
  466. }
  467. } // end namespace fs
  468. namespace path {
  469. bool home_directory(SmallVectorImpl<char> &result) {
  470. if (char *RequestedDir = getenv("HOME")) {
  471. result.clear();
  472. result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
  473. return true;
  474. }
  475. return false;
  476. }
  477. static const char *getEnvTempDir() {
  478. // Check whether the temporary directory is specified by an environment
  479. // variable.
  480. const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
  481. for (const char *Env : EnvironmentVariables) {
  482. if (const char *Dir = std::getenv(Env))
  483. return Dir;
  484. }
  485. return nullptr;
  486. }
  487. static const char *getDefaultTempDir(bool ErasedOnReboot) {
  488. #ifdef P_tmpdir
  489. if ((bool)P_tmpdir)
  490. return P_tmpdir;
  491. #endif
  492. if (ErasedOnReboot)
  493. return "/tmp";
  494. return "/var/tmp";
  495. }
  496. void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
  497. Result.clear();
  498. if (ErasedOnReboot) {
  499. // There is no env variable for the cache directory.
  500. if (const char *RequestedDir = getEnvTempDir()) {
  501. Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
  502. return;
  503. }
  504. }
  505. #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
  506. // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
  507. // macros defined in <unistd.h> on darwin >= 9
  508. int ConfName = ErasedOnReboot? _CS_DARWIN_USER_TEMP_DIR
  509. : _CS_DARWIN_USER_CACHE_DIR;
  510. size_t ConfLen = confstr(ConfName, nullptr, 0);
  511. if (ConfLen > 0) {
  512. do {
  513. Result.resize(ConfLen);
  514. ConfLen = confstr(ConfName, Result.data(), Result.size());
  515. } while (ConfLen > 0 && ConfLen != Result.size());
  516. if (ConfLen > 0) {
  517. assert(Result.back() == 0);
  518. Result.pop_back();
  519. return;
  520. }
  521. Result.clear();
  522. }
  523. #endif
  524. const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
  525. Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
  526. }
  527. } // end namespace path
  528. } // end namespace sys
  529. } // end namespace llvm