Path.inc 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518
  1. //===- llvm/Support/Unix/Path.inc - Unix Path Implementation ----*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the Unix specific implementation of the Path API.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. //===----------------------------------------------------------------------===//
  13. //=== WARNING: Implementation here must contain only generic UNIX code that
  14. //=== is guaranteed to work on *all* UNIX variants.
  15. //===----------------------------------------------------------------------===//
  16. #include "Unix.h"
  17. #include <limits.h>
  18. #include <stdio.h>
  19. #if HAVE_SYS_STAT_H
  20. #include <sys/stat.h>
  21. #endif
  22. #if HAVE_FCNTL_H
  23. #include <fcntl.h>
  24. #endif
  25. #ifdef HAVE_UNISTD_H
  26. #include <unistd.h>
  27. #endif
  28. #ifdef HAVE_SYS_MMAN_H
  29. #include <sys/mman.h>
  30. #endif
  31. #include <dirent.h>
  32. #include <pwd.h>
  33. #include <sys/file.h>
  34. #ifdef __APPLE__
  35. #include <copyfile.h>
  36. #include <mach-o/dyld.h>
  37. #include <sys/attr.h>
  38. #if __has_include(<sys/clonefile.h>)
  39. #include <sys/clonefile.h>
  40. #endif
  41. #elif defined(__FreeBSD__)
  42. #include <osreldate.h>
  43. #if __FreeBSD_version >= 1300057
  44. #include <sys/auxv.h>
  45. #else
  46. #error #include <machine/elf.h>
  47. extern char **environ;
  48. #endif
  49. #elif defined(__DragonFly__)
  50. #include <sys/mount.h>
  51. #elif defined(__MVS__)
  52. #include "llvm/Support/AutoConvert.h"
  53. #error #include <sys/ps.h>
  54. #endif
  55. // Both stdio.h and cstdio are included via different paths and
  56. // stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
  57. // either.
  58. #undef ferror
  59. #undef feof
  60. #if !defined(PATH_MAX)
  61. // For GNU Hurd
  62. #if defined(__GNU__)
  63. #define PATH_MAX 4096
  64. #elif defined(__MVS__)
  65. #define PATH_MAX _XOPEN_PATH_MAX
  66. #endif
  67. #endif
  68. #include <sys/types.h>
  69. #if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && \
  70. !defined(__linux__) && !defined(__FreeBSD_kernel__) && !defined(_AIX)
  71. #include <sys/statvfs.h>
  72. #define STATVFS statvfs
  73. #define FSTATVFS fstatvfs
  74. #define STATVFS_F_FRSIZE(vfs) vfs.f_frsize
  75. #else
  76. #if defined(__OpenBSD__) || defined(__FreeBSD__)
  77. #include <sys/mount.h>
  78. #include <sys/param.h>
  79. #elif defined(__linux__)
  80. #if defined(HAVE_LINUX_MAGIC_H)
  81. #include <linux/magic.h>
  82. #else
  83. #if defined(HAVE_LINUX_NFS_FS_H)
  84. #include <linux/nfs_fs.h>
  85. #endif
  86. #if defined(HAVE_LINUX_SMB_H)
  87. #error #include <linux/smb.h>
  88. #endif
  89. #endif
  90. #include <sys/vfs.h>
  91. #elif defined(_AIX)
  92. #include <sys/statfs.h>
  93. // <sys/vmount.h> depends on `uint` to be a typedef from <sys/types.h> to
  94. // `uint_t`; however, <sys/types.h> does not always declare `uint`. We provide
  95. // the typedef prior to including <sys/vmount.h> to work around this issue.
  96. typedef uint_t uint;
  97. #include <sys/vmount.h>
  98. #else
  99. #include <sys/mount.h>
  100. #endif
  101. #define STATVFS statfs
  102. #define FSTATVFS fstatfs
  103. #define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
  104. #endif
  105. #if defined(__NetBSD__) || defined(__DragonFly__) || defined(__GNU__) || \
  106. defined(__MVS__)
  107. #define STATVFS_F_FLAG(vfs) (vfs).f_flag
  108. #else
  109. #define STATVFS_F_FLAG(vfs) (vfs).f_flags
  110. #endif
  111. using namespace llvm;
  112. namespace llvm {
  113. namespace sys {
  114. namespace fs {
  115. const file_t kInvalidFile = -1;
  116. #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \
  117. defined(__minix) || defined(__FreeBSD_kernel__) || defined(__linux__) || \
  118. defined(__CYGWIN__) || defined(__DragonFly__) || defined(_AIX) || \
  119. defined(__GNU__) || (defined(__sun__) && defined(__svr4__))
  120. static int test_dir(char ret[PATH_MAX], const char *dir, const char *bin) {
  121. struct stat sb;
  122. char fullpath[PATH_MAX];
  123. int chars = snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
  124. // We cannot write PATH_MAX characters because the string will be terminated
  125. // with a null character. Fail if truncation happened.
  126. if (chars >= PATH_MAX)
  127. return 1;
  128. if (!realpath(fullpath, ret))
  129. return 1;
  130. if (stat(fullpath, &sb) != 0)
  131. return 1;
  132. return 0;
  133. }
  134. static char *getprogpath(char ret[PATH_MAX], const char *bin) {
  135. if (bin == nullptr)
  136. return nullptr;
  137. /* First approach: absolute path. */
  138. if (bin[0] == '/') {
  139. if (test_dir(ret, "/", bin) == 0)
  140. return ret;
  141. return nullptr;
  142. }
  143. /* Second approach: relative path. */
  144. if (strchr(bin, '/')) {
  145. char cwd[PATH_MAX];
  146. if (!getcwd(cwd, PATH_MAX))
  147. return nullptr;
  148. if (test_dir(ret, cwd, bin) == 0)
  149. return ret;
  150. return nullptr;
  151. }
  152. /* Third approach: $PATH */
  153. char *pv;
  154. if ((pv = getenv("PATH")) == nullptr)
  155. return nullptr;
  156. char *s = strdup(pv);
  157. if (!s)
  158. return nullptr;
  159. char *state;
  160. for (char *t = strtok_r(s, ":", &state); t != nullptr;
  161. t = strtok_r(nullptr, ":", &state)) {
  162. if (test_dir(ret, t, bin) == 0) {
  163. free(s);
  164. return ret;
  165. }
  166. }
  167. free(s);
  168. return nullptr;
  169. }
  170. #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
  171. /// GetMainExecutable - Return the path to the main executable, given the
  172. /// value of argv[0] from program startup.
  173. std::string getMainExecutableImpl(const char *argv0, void *MainAddr) {
  174. #if defined(__APPLE__)
  175. // On OS X the executable path is saved to the stack by dyld. Reading it
  176. // from there is much faster than calling dladdr, especially for large
  177. // binaries with symbols.
  178. char exe_path[PATH_MAX];
  179. uint32_t size = sizeof(exe_path);
  180. if (_NSGetExecutablePath(exe_path, &size) == 0) {
  181. char link_path[PATH_MAX];
  182. if (realpath(exe_path, link_path))
  183. return link_path;
  184. }
  185. #elif defined(__FreeBSD__)
  186. // On FreeBSD if the exec path specified in ELF auxiliary vectors is
  187. // preferred, if available. /proc/curproc/file and the KERN_PROC_PATHNAME
  188. // sysctl may not return the desired path if there are multiple hardlinks
  189. // to the file.
  190. char exe_path[PATH_MAX];
  191. #if __FreeBSD_version >= 1300057
  192. if (elf_aux_info(AT_EXECPATH, exe_path, sizeof(exe_path)) == 0) {
  193. char link_path[PATH_MAX];
  194. if (realpath(exe_path, link_path))
  195. return link_path;
  196. }
  197. #else
  198. // elf_aux_info(AT_EXECPATH, ... is not available in all supported versions,
  199. // fall back to finding the ELF auxiliary vectors after the process's
  200. // environment.
  201. char **p = ::environ;
  202. while (*p++ != 0)
  203. ;
  204. // Iterate through auxiliary vectors for AT_EXECPATH.
  205. for (Elf_Auxinfo *aux = (Elf_Auxinfo *)p; aux->a_type != AT_NULL; aux++) {
  206. if (aux->a_type == AT_EXECPATH) {
  207. char link_path[PATH_MAX];
  208. if (realpath((char *)aux->a_un.a_ptr, link_path))
  209. return link_path;
  210. }
  211. }
  212. #endif
  213. // Fall back to argv[0] if auxiliary vectors are not available.
  214. if (getprogpath(exe_path, argv0) != NULL)
  215. return exe_path;
  216. #elif defined(__NetBSD__) || defined(__OpenBSD__) || defined(__minix) || \
  217. defined(__DragonFly__) || defined(__FreeBSD_kernel__) || defined(_AIX)
  218. const char *curproc = "/proc/curproc/file";
  219. char exe_path[PATH_MAX];
  220. if (sys::fs::exists(curproc)) {
  221. ssize_t len = readlink(curproc, exe_path, sizeof(exe_path));
  222. if (len > 0) {
  223. // Null terminate the string for realpath. readlink never null
  224. // terminates its output.
  225. len = std::min(len, ssize_t(sizeof(exe_path) - 1));
  226. exe_path[len] = '\0';
  227. return exe_path;
  228. }
  229. }
  230. // If we don't have procfs mounted, fall back to argv[0]
  231. if (getprogpath(exe_path, argv0) != NULL)
  232. return exe_path;
  233. #elif defined(__linux__) || defined(__CYGWIN__) || defined(__gnu_hurd__)
  234. char exe_path[PATH_MAX];
  235. const char *aPath = "/proc/self/exe";
  236. if (sys::fs::exists(aPath)) {
  237. // /proc is not always mounted under Linux (chroot for example).
  238. ssize_t len = readlink(aPath, exe_path, sizeof(exe_path));
  239. if (len < 0)
  240. return "";
  241. // Null terminate the string for realpath. readlink never null
  242. // terminates its output.
  243. len = std::min(len, ssize_t(sizeof(exe_path) - 1));
  244. exe_path[len] = '\0';
  245. // On Linux, /proc/self/exe always looks through symlinks. However, on
  246. // GNU/Hurd, /proc/self/exe is a symlink to the path that was used to start
  247. // the program, and not the eventual binary file. Therefore, call realpath
  248. // so this behaves the same on all platforms.
  249. #if _POSIX_VERSION >= 200112 || defined(__GLIBC__)
  250. if (char *real_path = realpath(exe_path, nullptr)) {
  251. std::string ret = std::string(real_path);
  252. free(real_path);
  253. return ret;
  254. }
  255. #else
  256. char real_path[PATH_MAX];
  257. if (realpath(exe_path, real_path))
  258. return std::string(real_path);
  259. #endif
  260. }
  261. // Fall back to the classical detection.
  262. if (getprogpath(exe_path, argv0))
  263. return exe_path;
  264. #elif defined(__sun__) && defined(__svr4__)
  265. char exe_path[PATH_MAX];
  266. const char *aPath = "/proc/self/execname";
  267. if (sys::fs::exists(aPath)) {
  268. int fd = open(aPath, O_RDONLY);
  269. if (fd == -1)
  270. return "";
  271. if (read(fd, exe_path, sizeof(exe_path)) < 0)
  272. return "";
  273. return exe_path;
  274. }
  275. // Fall back to the classical detection.
  276. if (getprogpath(exe_path, argv0) != NULL)
  277. return exe_path;
  278. #elif defined(__MVS__)
  279. int token = 0;
  280. W_PSPROC buf;
  281. char exe_path[PS_PATHBLEN];
  282. pid_t pid = getpid();
  283. memset(&buf, 0, sizeof(buf));
  284. buf.ps_pathptr = exe_path;
  285. buf.ps_pathlen = sizeof(exe_path);
  286. while (true) {
  287. if ((token = w_getpsent(token, &buf, sizeof(buf))) <= 0)
  288. break;
  289. if (buf.ps_pid != pid)
  290. continue;
  291. char real_path[PATH_MAX];
  292. if (realpath(exe_path, real_path))
  293. return std::string(real_path);
  294. break; // Found entry, but realpath failed.
  295. }
  296. #elif defined(HAVE_DLFCN_H) && defined(HAVE_DLADDR)
  297. // Use dladdr to get executable path if available.
  298. Dl_info DLInfo;
  299. int err = dladdr(MainAddr, &DLInfo);
  300. if (err == 0)
  301. return "";
  302. // If the filename is a symlink, we need to resolve and return the location of
  303. // the actual executable.
  304. char link_path[PATH_MAX];
  305. if (realpath(DLInfo.dli_fname, link_path))
  306. return link_path;
  307. #else
  308. #error GetMainExecutable is not implemented on this host yet.
  309. #endif
  310. return "";
  311. }
  312. TimePoint<> basic_file_status::getLastAccessedTime() const {
  313. return toTimePoint(fs_st_atime, fs_st_atime_nsec);
  314. }
  315. TimePoint<> basic_file_status::getLastModificationTime() const {
  316. return toTimePoint(fs_st_mtime, fs_st_mtime_nsec);
  317. }
  318. UniqueID file_status::getUniqueID() const {
  319. return UniqueID(fs_st_dev, fs_st_ino);
  320. }
  321. uint32_t file_status::getLinkCount() const { return fs_st_nlinks; }
  322. ErrorOr<space_info> disk_space(const Twine &Path) {
  323. struct STATVFS Vfs;
  324. if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))
  325. return std::error_code(errno, std::generic_category());
  326. auto FrSize = STATVFS_F_FRSIZE(Vfs);
  327. space_info SpaceInfo;
  328. SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;
  329. SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize;
  330. SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize;
  331. return SpaceInfo;
  332. }
  333. std::error_code current_path(SmallVectorImpl<char> &result) {
  334. result.clear();
  335. const char *pwd = ::getenv("PWD");
  336. llvm::sys::fs::file_status PWDStatus, DotStatus;
  337. if (pwd && llvm::sys::path::is_absolute(pwd) &&
  338. !llvm::sys::fs::status(pwd, PWDStatus) &&
  339. !llvm::sys::fs::status(".", DotStatus) &&
  340. PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
  341. result.append(pwd, pwd + strlen(pwd));
  342. return std::error_code();
  343. }
  344. result.resize_for_overwrite(PATH_MAX);
  345. while (true) {
  346. if (::getcwd(result.data(), result.size()) == nullptr) {
  347. // See if there was a real error.
  348. if (errno != ENOMEM) {
  349. result.clear();
  350. return std::error_code(errno, std::generic_category());
  351. }
  352. // Otherwise there just wasn't enough space.
  353. result.resize_for_overwrite(result.capacity() * 2);
  354. } else
  355. break;
  356. }
  357. result.truncate(strlen(result.data()));
  358. return std::error_code();
  359. }
  360. std::error_code set_current_path(const Twine &path) {
  361. SmallString<128> path_storage;
  362. StringRef p = path.toNullTerminatedStringRef(path_storage);
  363. if (::chdir(p.begin()) == -1)
  364. return std::error_code(errno, std::generic_category());
  365. return std::error_code();
  366. }
  367. std::error_code create_directory(const Twine &path, bool IgnoreExisting,
  368. perms Perms) {
  369. SmallString<128> path_storage;
  370. StringRef p = path.toNullTerminatedStringRef(path_storage);
  371. if (::mkdir(p.begin(), Perms) == -1) {
  372. if (errno != EEXIST || !IgnoreExisting)
  373. return std::error_code(errno, std::generic_category());
  374. }
  375. return std::error_code();
  376. }
  377. // Note that we are using symbolic link because hard links are not supported by
  378. // all filesystems (SMB doesn't).
  379. std::error_code create_link(const Twine &to, const Twine &from) {
  380. // Get arguments.
  381. SmallString<128> from_storage;
  382. SmallString<128> to_storage;
  383. StringRef f = from.toNullTerminatedStringRef(from_storage);
  384. StringRef t = to.toNullTerminatedStringRef(to_storage);
  385. if (::symlink(t.begin(), f.begin()) == -1)
  386. return std::error_code(errno, std::generic_category());
  387. return std::error_code();
  388. }
  389. std::error_code create_hard_link(const Twine &to, const Twine &from) {
  390. // Get arguments.
  391. SmallString<128> from_storage;
  392. SmallString<128> to_storage;
  393. StringRef f = from.toNullTerminatedStringRef(from_storage);
  394. StringRef t = to.toNullTerminatedStringRef(to_storage);
  395. if (::link(t.begin(), f.begin()) == -1)
  396. return std::error_code(errno, std::generic_category());
  397. return std::error_code();
  398. }
  399. std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
  400. SmallString<128> path_storage;
  401. StringRef p = path.toNullTerminatedStringRef(path_storage);
  402. struct stat buf;
  403. if (lstat(p.begin(), &buf) != 0) {
  404. if (errno != ENOENT || !IgnoreNonExisting)
  405. return std::error_code(errno, std::generic_category());
  406. return std::error_code();
  407. }
  408. // Note: this check catches strange situations. In all cases, LLVM should
  409. // only be involved in the creation and deletion of regular files. This
  410. // check ensures that what we're trying to erase is a regular file. It
  411. // effectively prevents LLVM from erasing things like /dev/null, any block
  412. // special file, or other things that aren't "regular" files.
  413. if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
  414. return make_error_code(errc::operation_not_permitted);
  415. if (::remove(p.begin()) == -1) {
  416. if (errno != ENOENT || !IgnoreNonExisting)
  417. return std::error_code(errno, std::generic_category());
  418. }
  419. return std::error_code();
  420. }
  421. static bool is_local_impl(struct STATVFS &Vfs) {
  422. #if defined(__linux__) || defined(__GNU__)
  423. #ifndef NFS_SUPER_MAGIC
  424. #define NFS_SUPER_MAGIC 0x6969
  425. #endif
  426. #ifndef SMB_SUPER_MAGIC
  427. #define SMB_SUPER_MAGIC 0x517B
  428. #endif
  429. #ifndef CIFS_MAGIC_NUMBER
  430. #define CIFS_MAGIC_NUMBER 0xFF534D42
  431. #endif
  432. #ifdef __GNU__
  433. switch ((uint32_t)Vfs.__f_type) {
  434. #else
  435. switch ((uint32_t)Vfs.f_type) {
  436. #endif
  437. case NFS_SUPER_MAGIC:
  438. case SMB_SUPER_MAGIC:
  439. case CIFS_MAGIC_NUMBER:
  440. return false;
  441. default:
  442. return true;
  443. }
  444. #elif defined(__CYGWIN__)
  445. // Cygwin doesn't expose this information; would need to use Win32 API.
  446. return false;
  447. #elif defined(__Fuchsia__)
  448. // Fuchsia doesn't yet support remote filesystem mounts.
  449. return true;
  450. #elif defined(__EMSCRIPTEN__)
  451. // Emscripten doesn't currently support remote filesystem mounts.
  452. return true;
  453. #elif defined(__HAIKU__)
  454. // Haiku doesn't expose this information.
  455. return false;
  456. #elif defined(__sun)
  457. // statvfs::f_basetype contains a null-terminated FSType name of the mounted
  458. // target
  459. StringRef fstype(Vfs.f_basetype);
  460. // NFS is the only non-local fstype??
  461. return !fstype.equals("nfs");
  462. #elif defined(_AIX)
  463. // Call mntctl; try more than twice in case of timing issues with a concurrent
  464. // mount.
  465. int Ret;
  466. size_t BufSize = 2048u;
  467. std::unique_ptr<char[]> Buf;
  468. int Tries = 3;
  469. while (Tries--) {
  470. Buf = std::make_unique<char[]>(BufSize);
  471. Ret = mntctl(MCTL_QUERY, BufSize, Buf.get());
  472. if (Ret != 0)
  473. break;
  474. BufSize = *reinterpret_cast<unsigned int *>(Buf.get());
  475. Buf.reset();
  476. }
  477. if (Ret == -1)
  478. // There was an error; "remote" is the conservative answer.
  479. return false;
  480. // Look for the correct vmount entry.
  481. char *CurObjPtr = Buf.get();
  482. while (Ret--) {
  483. struct vmount *Vp = reinterpret_cast<struct vmount *>(CurObjPtr);
  484. static_assert(sizeof(Vfs.f_fsid) == sizeof(Vp->vmt_fsid),
  485. "fsid length mismatch");
  486. if (memcmp(&Vfs.f_fsid, &Vp->vmt_fsid, sizeof Vfs.f_fsid) == 0)
  487. return (Vp->vmt_flags & MNT_REMOTE) == 0;
  488. CurObjPtr += Vp->vmt_length;
  489. }
  490. // vmount entry not found; "remote" is the conservative answer.
  491. return false;
  492. #elif defined(__MVS__)
  493. // The file system can have an arbitrary structure on z/OS; must go with the
  494. // conservative answer.
  495. return false;
  496. #else
  497. return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
  498. #endif
  499. }
  500. std::error_code is_local(const Twine &Path, bool &Result) {
  501. struct STATVFS Vfs;
  502. if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))
  503. return std::error_code(errno, std::generic_category());
  504. Result = is_local_impl(Vfs);
  505. return std::error_code();
  506. }
  507. std::error_code is_local(int FD, bool &Result) {
  508. struct STATVFS Vfs;
  509. if (::FSTATVFS(FD, &Vfs))
  510. return std::error_code(errno, std::generic_category());
  511. Result = is_local_impl(Vfs);
  512. return std::error_code();
  513. }
  514. std::error_code rename(const Twine &from, const Twine &to) {
  515. // Get arguments.
  516. SmallString<128> from_storage;
  517. SmallString<128> to_storage;
  518. StringRef f = from.toNullTerminatedStringRef(from_storage);
  519. StringRef t = to.toNullTerminatedStringRef(to_storage);
  520. if (::rename(f.begin(), t.begin()) == -1)
  521. return std::error_code(errno, std::generic_category());
  522. return std::error_code();
  523. }
  524. std::error_code resize_file(int FD, uint64_t Size) {
  525. // Use ftruncate as a fallback. It may or may not allocate space. At least on
  526. // OS X with HFS+ it does.
  527. if (::ftruncate(FD, Size) == -1)
  528. return std::error_code(errno, std::generic_category());
  529. return std::error_code();
  530. }
  531. static int convertAccessMode(AccessMode Mode) {
  532. switch (Mode) {
  533. case AccessMode::Exist:
  534. return F_OK;
  535. case AccessMode::Write:
  536. return W_OK;
  537. case AccessMode::Execute:
  538. return R_OK | X_OK; // scripts also need R_OK.
  539. }
  540. llvm_unreachable("invalid enum");
  541. }
  542. std::error_code access(const Twine &Path, AccessMode Mode) {
  543. SmallString<128> PathStorage;
  544. StringRef P = Path.toNullTerminatedStringRef(PathStorage);
  545. if (::access(P.begin(), convertAccessMode(Mode)) == -1)
  546. return std::error_code(errno, std::generic_category());
  547. if (Mode == AccessMode::Execute) {
  548. // Don't say that directories are executable.
  549. struct stat buf;
  550. if (0 != stat(P.begin(), &buf))
  551. return errc::permission_denied;
  552. if (!S_ISREG(buf.st_mode))
  553. return errc::permission_denied;
  554. }
  555. return std::error_code();
  556. }
  557. bool can_execute(const Twine &Path) {
  558. return !access(Path, AccessMode::Execute);
  559. }
  560. bool equivalent(file_status A, file_status B) {
  561. assert(status_known(A) && status_known(B));
  562. return A.fs_st_dev == B.fs_st_dev && A.fs_st_ino == B.fs_st_ino;
  563. }
  564. std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
  565. file_status fsA, fsB;
  566. if (std::error_code ec = status(A, fsA))
  567. return ec;
  568. if (std::error_code ec = status(B, fsB))
  569. return ec;
  570. result = equivalent(fsA, fsB);
  571. return std::error_code();
  572. }
  573. static void expandTildeExpr(SmallVectorImpl<char> &Path) {
  574. StringRef PathStr(Path.begin(), Path.size());
  575. if (PathStr.empty() || !PathStr.startswith("~"))
  576. return;
  577. PathStr = PathStr.drop_front();
  578. StringRef Expr =
  579. PathStr.take_until([](char c) { return path::is_separator(c); });
  580. StringRef Remainder = PathStr.substr(Expr.size() + 1);
  581. SmallString<128> Storage;
  582. if (Expr.empty()) {
  583. // This is just ~/..., resolve it to the current user's home dir.
  584. if (!path::home_directory(Storage)) {
  585. // For some reason we couldn't get the home directory. Just exit.
  586. return;
  587. }
  588. // Overwrite the first character and insert the rest.
  589. Path[0] = Storage[0];
  590. Path.insert(Path.begin() + 1, Storage.begin() + 1, Storage.end());
  591. return;
  592. }
  593. // This is a string of the form ~username/, look up this user's entry in the
  594. // password database.
  595. std::unique_ptr<char[]> Buf;
  596. long BufSize = sysconf(_SC_GETPW_R_SIZE_MAX);
  597. if (BufSize <= 0)
  598. BufSize = 16384;
  599. Buf = std::make_unique<char[]>(BufSize);
  600. struct passwd Pwd;
  601. std::string User = Expr.str();
  602. struct passwd *Entry = nullptr;
  603. getpwnam_r(User.c_str(), &Pwd, Buf.get(), BufSize, &Entry);
  604. if (!Entry || !Entry->pw_dir) {
  605. // Unable to look up the entry, just return back the original path.
  606. return;
  607. }
  608. Storage = Remainder;
  609. Path.clear();
  610. Path.append(Entry->pw_dir, Entry->pw_dir + strlen(Entry->pw_dir));
  611. llvm::sys::path::append(Path, Storage);
  612. }
  613. void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
  614. dest.clear();
  615. if (path.isTriviallyEmpty())
  616. return;
  617. path.toVector(dest);
  618. expandTildeExpr(dest);
  619. }
  620. static file_type typeForMode(mode_t Mode) {
  621. if (S_ISDIR(Mode))
  622. return file_type::directory_file;
  623. else if (S_ISREG(Mode))
  624. return file_type::regular_file;
  625. else if (S_ISBLK(Mode))
  626. return file_type::block_file;
  627. else if (S_ISCHR(Mode))
  628. return file_type::character_file;
  629. else if (S_ISFIFO(Mode))
  630. return file_type::fifo_file;
  631. else if (S_ISSOCK(Mode))
  632. return file_type::socket_file;
  633. else if (S_ISLNK(Mode))
  634. return file_type::symlink_file;
  635. return file_type::type_unknown;
  636. }
  637. static std::error_code fillStatus(int StatRet, const struct stat &Status,
  638. file_status &Result) {
  639. if (StatRet != 0) {
  640. std::error_code EC(errno, std::generic_category());
  641. if (EC == errc::no_such_file_or_directory)
  642. Result = file_status(file_type::file_not_found);
  643. else
  644. Result = file_status(file_type::status_error);
  645. return EC;
  646. }
  647. uint32_t atime_nsec, mtime_nsec;
  648. #if defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
  649. atime_nsec = Status.st_atimespec.tv_nsec;
  650. mtime_nsec = Status.st_mtimespec.tv_nsec;
  651. #elif defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
  652. atime_nsec = Status.st_atim.tv_nsec;
  653. mtime_nsec = Status.st_mtim.tv_nsec;
  654. #else
  655. atime_nsec = mtime_nsec = 0;
  656. #endif
  657. perms Perms = static_cast<perms>(Status.st_mode) & all_perms;
  658. Result = file_status(typeForMode(Status.st_mode), Perms, Status.st_dev,
  659. Status.st_nlink, Status.st_ino, Status.st_atime,
  660. atime_nsec, Status.st_mtime, mtime_nsec, Status.st_uid,
  661. Status.st_gid, Status.st_size);
  662. return std::error_code();
  663. }
  664. std::error_code status(const Twine &Path, file_status &Result, bool Follow) {
  665. SmallString<128> PathStorage;
  666. StringRef P = Path.toNullTerminatedStringRef(PathStorage);
  667. struct stat Status;
  668. int StatRet = (Follow ? ::stat : ::lstat)(P.begin(), &Status);
  669. return fillStatus(StatRet, Status, Result);
  670. }
  671. std::error_code status(int FD, file_status &Result) {
  672. struct stat Status;
  673. int StatRet = ::fstat(FD, &Status);
  674. return fillStatus(StatRet, Status, Result);
  675. }
  676. unsigned getUmask() {
  677. // Chose arbitary new mask and reset the umask to the old mask.
  678. // umask(2) never fails so ignore the return of the second call.
  679. unsigned Mask = ::umask(0);
  680. (void)::umask(Mask);
  681. return Mask;
  682. }
  683. std::error_code setPermissions(const Twine &Path, perms Permissions) {
  684. SmallString<128> PathStorage;
  685. StringRef P = Path.toNullTerminatedStringRef(PathStorage);
  686. if (::chmod(P.begin(), Permissions))
  687. return std::error_code(errno, std::generic_category());
  688. return std::error_code();
  689. }
  690. std::error_code setPermissions(int FD, perms Permissions) {
  691. if (::fchmod(FD, Permissions))
  692. return std::error_code(errno, std::generic_category());
  693. return std::error_code();
  694. }
  695. std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
  696. TimePoint<> ModificationTime) {
  697. #if defined(HAVE_FUTIMENS)
  698. timespec Times[2];
  699. Times[0] = sys::toTimeSpec(AccessTime);
  700. Times[1] = sys::toTimeSpec(ModificationTime);
  701. if (::futimens(FD, Times))
  702. return std::error_code(errno, std::generic_category());
  703. return std::error_code();
  704. #elif defined(HAVE_FUTIMES)
  705. timeval Times[2];
  706. Times[0] = sys::toTimeVal(
  707. std::chrono::time_point_cast<std::chrono::microseconds>(AccessTime));
  708. Times[1] =
  709. sys::toTimeVal(std::chrono::time_point_cast<std::chrono::microseconds>(
  710. ModificationTime));
  711. if (::futimes(FD, Times))
  712. return std::error_code(errno, std::generic_category());
  713. return std::error_code();
  714. #elif defined(__MVS__)
  715. attrib_t Attr;
  716. memset(&Attr, 0, sizeof(Attr));
  717. Attr.att_atimechg = 1;
  718. Attr.att_atime = sys::toTimeT(AccessTime);
  719. Attr.att_mtimechg = 1;
  720. Attr.att_mtime = sys::toTimeT(ModificationTime);
  721. if (::__fchattr(FD, &Attr, sizeof(Attr)) != 0)
  722. return std::error_code(errno, std::generic_category());
  723. return std::error_code();
  724. #else
  725. #warning Missing futimes() and futimens()
  726. return make_error_code(errc::function_not_supported);
  727. #endif
  728. }
  729. std::error_code mapped_file_region::init(int FD, uint64_t Offset,
  730. mapmode Mode) {
  731. assert(Size != 0);
  732. int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
  733. int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
  734. #if defined(MAP_NORESERVE)
  735. flags |= MAP_NORESERVE;
  736. #endif
  737. #if defined(__APPLE__)
  738. //----------------------------------------------------------------------
  739. // Newer versions of MacOSX have a flag that will allow us to read from
  740. // binaries whose code signature is invalid without crashing by using
  741. // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media
  742. // is mapped we can avoid crashing and return zeroes to any pages we try
  743. // to read if the media becomes unavailable by using the
  744. // MAP_RESILIENT_MEDIA flag. These flags are only usable when mapping
  745. // with PROT_READ, so take care not to specify them otherwise.
  746. //----------------------------------------------------------------------
  747. if (Mode == readonly) {
  748. #if defined(MAP_RESILIENT_CODESIGN)
  749. flags |= MAP_RESILIENT_CODESIGN;
  750. #endif
  751. #if defined(MAP_RESILIENT_MEDIA)
  752. flags |= MAP_RESILIENT_MEDIA;
  753. #endif
  754. }
  755. #endif // #if defined (__APPLE__)
  756. Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
  757. if (Mapping == MAP_FAILED)
  758. return std::error_code(errno, std::generic_category());
  759. return std::error_code();
  760. }
  761. mapped_file_region::mapped_file_region(int fd, mapmode mode, size_t length,
  762. uint64_t offset, std::error_code &ec)
  763. : Size(length), Mode(mode) {
  764. (void)Mode;
  765. ec = init(fd, offset, mode);
  766. if (ec)
  767. copyFrom(mapped_file_region());
  768. }
  769. void mapped_file_region::unmapImpl() {
  770. if (Mapping)
  771. ::munmap(Mapping, Size);
  772. }
  773. void mapped_file_region::dontNeedImpl() {
  774. assert(Mode == mapped_file_region::readonly);
  775. if (!Mapping)
  776. return;
  777. #if defined(__MVS__) || defined(_AIX)
  778. // If we don't have madvise, or it isn't beneficial, treat this as a no-op.
  779. #elif defined(POSIX_MADV_DONTNEED)
  780. ::posix_madvise(Mapping, Size, POSIX_MADV_DONTNEED);
  781. #else
  782. ::madvise(Mapping, Size, MADV_DONTNEED);
  783. #endif
  784. }
  785. int mapped_file_region::alignment() { return Process::getPageSizeEstimate(); }
  786. std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
  787. StringRef path,
  788. bool follow_symlinks) {
  789. SmallString<128> path_null(path);
  790. DIR *directory = ::opendir(path_null.c_str());
  791. if (!directory)
  792. return std::error_code(errno, std::generic_category());
  793. it.IterationHandle = reinterpret_cast<intptr_t>(directory);
  794. // Add something for replace_filename to replace.
  795. path::append(path_null, ".");
  796. it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks);
  797. return directory_iterator_increment(it);
  798. }
  799. std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
  800. if (it.IterationHandle)
  801. ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
  802. it.IterationHandle = 0;
  803. it.CurrentEntry = directory_entry();
  804. return std::error_code();
  805. }
  806. static file_type direntType(dirent *Entry) {
  807. // Most platforms provide the file type in the dirent: Linux/BSD/Mac.
  808. // The DTTOIF macro lets us reuse our status -> type conversion.
  809. // Note that while glibc provides a macro to see if this is supported,
  810. // _DIRENT_HAVE_D_TYPE, it's not defined on BSD/Mac, so we test for the
  811. // d_type-to-mode_t conversion macro instead.
  812. #if defined(DTTOIF)
  813. return typeForMode(DTTOIF(Entry->d_type));
  814. #else
  815. // Other platforms such as Solaris require a stat() to get the type.
  816. return file_type::type_unknown;
  817. #endif
  818. }
  819. std::error_code detail::directory_iterator_increment(detail::DirIterState &It) {
  820. errno = 0;
  821. dirent *CurDir = ::readdir(reinterpret_cast<DIR *>(It.IterationHandle));
  822. if (CurDir == nullptr && errno != 0) {
  823. return std::error_code(errno, std::generic_category());
  824. } else if (CurDir != nullptr) {
  825. StringRef Name(CurDir->d_name);
  826. if ((Name.size() == 1 && Name[0] == '.') ||
  827. (Name.size() == 2 && Name[0] == '.' && Name[1] == '.'))
  828. return directory_iterator_increment(It);
  829. It.CurrentEntry.replace_filename(Name, direntType(CurDir));
  830. } else
  831. return directory_iterator_destruct(It);
  832. return std::error_code();
  833. }
  834. ErrorOr<basic_file_status> directory_entry::status() const {
  835. file_status s;
  836. if (auto EC = fs::status(Path, s, FollowSymlinks))
  837. return EC;
  838. return s;
  839. }
  840. //
  841. // FreeBSD optionally provides /proc/self/fd, but it is incompatible with
  842. // Linux. The thing to use is realpath.
  843. //
  844. #if !defined(__FreeBSD__)
  845. #define TRY_PROC_SELF_FD
  846. #endif
  847. #if !defined(F_GETPATH) && defined(TRY_PROC_SELF_FD)
  848. static bool hasProcSelfFD() {
  849. // If we have a /proc filesystem mounted, we can quickly establish the
  850. // real name of the file with readlink
  851. static const bool Result = (::access("/proc/self/fd", R_OK) == 0);
  852. return Result;
  853. }
  854. #endif
  855. static int nativeOpenFlags(CreationDisposition Disp, OpenFlags Flags,
  856. FileAccess Access) {
  857. int Result = 0;
  858. if (Access == FA_Read)
  859. Result |= O_RDONLY;
  860. else if (Access == FA_Write)
  861. Result |= O_WRONLY;
  862. else if (Access == (FA_Read | FA_Write))
  863. Result |= O_RDWR;
  864. // This is for compatibility with old code that assumed OF_Append implied
  865. // would open an existing file. See Windows/Path.inc for a longer comment.
  866. if (Flags & OF_Append)
  867. Disp = CD_OpenAlways;
  868. if (Disp == CD_CreateNew) {
  869. Result |= O_CREAT; // Create if it doesn't exist.
  870. Result |= O_EXCL; // Fail if it does.
  871. } else if (Disp == CD_CreateAlways) {
  872. Result |= O_CREAT; // Create if it doesn't exist.
  873. Result |= O_TRUNC; // Truncate if it does.
  874. } else if (Disp == CD_OpenAlways) {
  875. Result |= O_CREAT; // Create if it doesn't exist.
  876. } else if (Disp == CD_OpenExisting) {
  877. // Nothing special, just don't add O_CREAT and we get these semantics.
  878. }
  879. // Using append mode with z/OS UTF-8 auto-conversion results in EINVAL when
  880. // calling write(). Instead we need to use lseek() to set offset to EOF after
  881. // open().
  882. #ifndef __MVS__
  883. if (Flags & OF_Append)
  884. Result |= O_APPEND;
  885. #endif
  886. #ifdef O_CLOEXEC
  887. if (!(Flags & OF_ChildInherit))
  888. Result |= O_CLOEXEC;
  889. #endif
  890. return Result;
  891. }
  892. std::error_code openFile(const Twine &Name, int &ResultFD,
  893. CreationDisposition Disp, FileAccess Access,
  894. OpenFlags Flags, unsigned Mode) {
  895. int OpenFlags = nativeOpenFlags(Disp, Flags, Access);
  896. SmallString<128> Storage;
  897. StringRef P = Name.toNullTerminatedStringRef(Storage);
  898. // Call ::open in a lambda to avoid overload resolution in RetryAfterSignal
  899. // when open is overloaded, such as in Bionic.
  900. auto Open = [&]() { return ::open(P.begin(), OpenFlags, Mode); };
  901. if ((ResultFD = sys::RetryAfterSignal(-1, Open)) < 0)
  902. return std::error_code(errno, std::generic_category());
  903. #ifndef O_CLOEXEC
  904. if (!(Flags & OF_ChildInherit)) {
  905. int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
  906. (void)r;
  907. assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
  908. }
  909. #endif
  910. #ifdef __MVS__
  911. /* Reason about auto-conversion and file tags. Setting the file tag only
  912. * applies if file is opened in write mode:
  913. *
  914. * Text file:
  915. * File exists File created
  916. * CD_CreateNew n/a conv: on
  917. * tag: set 1047
  918. * CD_CreateAlways conv: auto conv: on
  919. * tag: auto 1047 tag: set 1047
  920. * CD_OpenAlways conv: auto conv: on
  921. * tag: auto 1047 tag: set 1047
  922. * CD_OpenExisting conv: auto n/a
  923. * tag: unchanged
  924. *
  925. * Binary file:
  926. * File exists File created
  927. * CD_CreateNew n/a conv: off
  928. * tag: set binary
  929. * CD_CreateAlways conv: off conv: off
  930. * tag: auto binary tag: set binary
  931. * CD_OpenAlways conv: off conv: off
  932. * tag: auto binary tag: set binary
  933. * CD_OpenExisting conv: off n/a
  934. * tag: unchanged
  935. *
  936. * Actions:
  937. * conv: off -> auto-conversion is turned off
  938. * conv: on -> auto-conversion is turned on
  939. * conv: auto -> auto-conversion is turned on if the file is untagged
  940. * tag: set 1047 -> set the file tag to text encoded in 1047
  941. * tag: set binary -> set the file tag to binary
  942. * tag: auto 1047 -> set file tag to 1047 if not set
  943. * tag: auto binary -> set file tag to binary if not set
  944. * tag: unchanged -> do not care about the file tag
  945. *
  946. * It is not possible to distinguish between the cases "file exists" and
  947. * "file created". In the latter case, the file tag is not set and the file
  948. * size is zero. The decision table boils down to:
  949. *
  950. * the file tag is set if
  951. * - the file is opened for writing
  952. * - the create disposition is not equal to CD_OpenExisting
  953. * - the file tag is not set
  954. * - the file size is zero
  955. *
  956. * This only applies if the file is a regular file. E.g. enabling
  957. * auto-conversion for reading from /dev/null results in error EINVAL when
  958. * calling read().
  959. *
  960. * Using append mode with z/OS UTF-8 auto-conversion results in EINVAL when
  961. * calling write(). Instead we need to use lseek() to set offset to EOF after
  962. * open().
  963. */
  964. if ((Flags & OF_Append) && lseek(ResultFD, 0, SEEK_END) == -1)
  965. return std::error_code(errno, std::generic_category());
  966. struct stat Stat;
  967. if (fstat(ResultFD, &Stat) == -1)
  968. return std::error_code(errno, std::generic_category());
  969. if (S_ISREG(Stat.st_mode)) {
  970. bool DoSetTag = (Access & FA_Write) && (Disp != CD_OpenExisting) &&
  971. !Stat.st_tag.ft_txtflag && !Stat.st_tag.ft_ccsid &&
  972. Stat.st_size == 0;
  973. if (Flags & OF_Text) {
  974. if (auto EC = llvm::enableAutoConversion(ResultFD))
  975. return EC;
  976. if (DoSetTag) {
  977. if (auto EC = llvm::setFileTag(ResultFD, CCSID_IBM_1047, true))
  978. return EC;
  979. }
  980. } else {
  981. if (auto EC = llvm::disableAutoConversion(ResultFD))
  982. return EC;
  983. if (DoSetTag) {
  984. if (auto EC = llvm::setFileTag(ResultFD, FT_BINARY, false))
  985. return EC;
  986. }
  987. }
  988. }
  989. #endif
  990. return std::error_code();
  991. }
  992. Expected<int> openNativeFile(const Twine &Name, CreationDisposition Disp,
  993. FileAccess Access, OpenFlags Flags,
  994. unsigned Mode) {
  995. int FD;
  996. std::error_code EC = openFile(Name, FD, Disp, Access, Flags, Mode);
  997. if (EC)
  998. return errorCodeToError(EC);
  999. return FD;
  1000. }
  1001. std::error_code openFileForRead(const Twine &Name, int &ResultFD,
  1002. OpenFlags Flags,
  1003. SmallVectorImpl<char> *RealPath) {
  1004. std::error_code EC =
  1005. openFile(Name, ResultFD, CD_OpenExisting, FA_Read, Flags, 0666);
  1006. if (EC)
  1007. return EC;
  1008. // Attempt to get the real name of the file, if the user asked
  1009. if (!RealPath)
  1010. return std::error_code();
  1011. RealPath->clear();
  1012. #if defined(F_GETPATH)
  1013. // When F_GETPATH is availble, it is the quickest way to get
  1014. // the real path name.
  1015. char Buffer[PATH_MAX];
  1016. if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
  1017. RealPath->append(Buffer, Buffer + strlen(Buffer));
  1018. #else
  1019. char Buffer[PATH_MAX];
  1020. #if defined(TRY_PROC_SELF_FD)
  1021. if (hasProcSelfFD()) {
  1022. char ProcPath[64];
  1023. snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
  1024. ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
  1025. if (CharCount > 0)
  1026. RealPath->append(Buffer, Buffer + CharCount);
  1027. } else {
  1028. #endif
  1029. SmallString<128> Storage;
  1030. StringRef P = Name.toNullTerminatedStringRef(Storage);
  1031. // Use ::realpath to get the real path name
  1032. if (::realpath(P.begin(), Buffer) != nullptr)
  1033. RealPath->append(Buffer, Buffer + strlen(Buffer));
  1034. #if defined(TRY_PROC_SELF_FD)
  1035. }
  1036. #endif
  1037. #endif
  1038. return std::error_code();
  1039. }
  1040. Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
  1041. SmallVectorImpl<char> *RealPath) {
  1042. file_t ResultFD;
  1043. std::error_code EC = openFileForRead(Name, ResultFD, Flags, RealPath);
  1044. if (EC)
  1045. return errorCodeToError(EC);
  1046. return ResultFD;
  1047. }
  1048. file_t getStdinHandle() { return 0; }
  1049. file_t getStdoutHandle() { return 1; }
  1050. file_t getStderrHandle() { return 2; }
  1051. Expected<size_t> readNativeFile(file_t FD, MutableArrayRef<char> Buf) {
  1052. #if defined(__APPLE__)
  1053. size_t Size = std::min<size_t>(Buf.size(), INT32_MAX);
  1054. #else
  1055. size_t Size = Buf.size();
  1056. #endif
  1057. ssize_t NumRead = sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Size);
  1058. if (ssize_t(NumRead) == -1)
  1059. return errorCodeToError(std::error_code(errno, std::generic_category()));
  1060. return NumRead;
  1061. }
  1062. Expected<size_t> readNativeFileSlice(file_t FD, MutableArrayRef<char> Buf,
  1063. uint64_t Offset) {
  1064. #if defined(__APPLE__)
  1065. size_t Size = std::min<size_t>(Buf.size(), INT32_MAX);
  1066. #else
  1067. size_t Size = Buf.size();
  1068. #endif
  1069. #ifdef HAVE_PREAD
  1070. ssize_t NumRead =
  1071. sys::RetryAfterSignal(-1, ::pread, FD, Buf.data(), Size, Offset);
  1072. #else
  1073. if (lseek(FD, Offset, SEEK_SET) == -1)
  1074. return errorCodeToError(std::error_code(errno, std::generic_category()));
  1075. ssize_t NumRead = sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Size);
  1076. #endif
  1077. if (NumRead == -1)
  1078. return errorCodeToError(std::error_code(errno, std::generic_category()));
  1079. return NumRead;
  1080. }
  1081. std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout) {
  1082. auto Start = std::chrono::steady_clock::now();
  1083. auto End = Start + Timeout;
  1084. do {
  1085. struct flock Lock;
  1086. memset(&Lock, 0, sizeof(Lock));
  1087. Lock.l_type = F_WRLCK;
  1088. Lock.l_whence = SEEK_SET;
  1089. Lock.l_start = 0;
  1090. Lock.l_len = 0;
  1091. if (::fcntl(FD, F_SETLK, &Lock) != -1)
  1092. return std::error_code();
  1093. int Error = errno;
  1094. if (Error != EACCES && Error != EAGAIN)
  1095. return std::error_code(Error, std::generic_category());
  1096. usleep(1000);
  1097. } while (std::chrono::steady_clock::now() < End);
  1098. return make_error_code(errc::no_lock_available);
  1099. }
  1100. std::error_code lockFile(int FD) {
  1101. struct flock Lock;
  1102. memset(&Lock, 0, sizeof(Lock));
  1103. Lock.l_type = F_WRLCK;
  1104. Lock.l_whence = SEEK_SET;
  1105. Lock.l_start = 0;
  1106. Lock.l_len = 0;
  1107. if (::fcntl(FD, F_SETLKW, &Lock) != -1)
  1108. return std::error_code();
  1109. int Error = errno;
  1110. return std::error_code(Error, std::generic_category());
  1111. }
  1112. std::error_code unlockFile(int FD) {
  1113. struct flock Lock;
  1114. Lock.l_type = F_UNLCK;
  1115. Lock.l_whence = SEEK_SET;
  1116. Lock.l_start = 0;
  1117. Lock.l_len = 0;
  1118. if (::fcntl(FD, F_SETLK, &Lock) != -1)
  1119. return std::error_code();
  1120. return std::error_code(errno, std::generic_category());
  1121. }
  1122. std::error_code closeFile(file_t &F) {
  1123. file_t TmpF = F;
  1124. F = kInvalidFile;
  1125. return Process::SafelyCloseFileDescriptor(TmpF);
  1126. }
  1127. template <typename T>
  1128. static std::error_code remove_directories_impl(const T &Entry,
  1129. bool IgnoreErrors) {
  1130. std::error_code EC;
  1131. directory_iterator Begin(Entry, EC, false);
  1132. directory_iterator End;
  1133. while (Begin != End) {
  1134. auto &Item = *Begin;
  1135. ErrorOr<basic_file_status> st = Item.status();
  1136. if (st) {
  1137. if (is_directory(*st)) {
  1138. EC = remove_directories_impl(Item, IgnoreErrors);
  1139. if (EC && !IgnoreErrors)
  1140. return EC;
  1141. }
  1142. EC = fs::remove(Item.path(), true);
  1143. if (EC && !IgnoreErrors)
  1144. return EC;
  1145. } else if (!IgnoreErrors) {
  1146. return st.getError();
  1147. }
  1148. Begin.increment(EC);
  1149. if (EC && !IgnoreErrors)
  1150. return EC;
  1151. }
  1152. return std::error_code();
  1153. }
  1154. std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
  1155. auto EC = remove_directories_impl(path, IgnoreErrors);
  1156. if (EC && !IgnoreErrors)
  1157. return EC;
  1158. EC = fs::remove(path, true);
  1159. if (EC && !IgnoreErrors)
  1160. return EC;
  1161. return std::error_code();
  1162. }
  1163. std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
  1164. bool expand_tilde) {
  1165. dest.clear();
  1166. if (path.isTriviallyEmpty())
  1167. return std::error_code();
  1168. if (expand_tilde) {
  1169. SmallString<128> Storage;
  1170. path.toVector(Storage);
  1171. expandTildeExpr(Storage);
  1172. return real_path(Storage, dest, false);
  1173. }
  1174. SmallString<128> Storage;
  1175. StringRef P = path.toNullTerminatedStringRef(Storage);
  1176. char Buffer[PATH_MAX];
  1177. if (::realpath(P.begin(), Buffer) == nullptr)
  1178. return std::error_code(errno, std::generic_category());
  1179. dest.append(Buffer, Buffer + strlen(Buffer));
  1180. return std::error_code();
  1181. }
  1182. std::error_code changeFileOwnership(int FD, uint32_t Owner, uint32_t Group) {
  1183. auto FChown = [&]() { return ::fchown(FD, Owner, Group); };
  1184. // Retry if fchown call fails due to interruption.
  1185. if ((sys::RetryAfterSignal(-1, FChown)) < 0)
  1186. return std::error_code(errno, std::generic_category());
  1187. return std::error_code();
  1188. }
  1189. } // end namespace fs
  1190. namespace path {
  1191. bool home_directory(SmallVectorImpl<char> &result) {
  1192. std::unique_ptr<char[]> Buf;
  1193. char *RequestedDir = getenv("HOME");
  1194. if (!RequestedDir) {
  1195. long BufSize = sysconf(_SC_GETPW_R_SIZE_MAX);
  1196. if (BufSize <= 0)
  1197. BufSize = 16384;
  1198. Buf = std::make_unique<char[]>(BufSize);
  1199. struct passwd Pwd;
  1200. struct passwd *pw = nullptr;
  1201. getpwuid_r(getuid(), &Pwd, Buf.get(), BufSize, &pw);
  1202. if (pw && pw->pw_dir)
  1203. RequestedDir = pw->pw_dir;
  1204. }
  1205. if (!RequestedDir)
  1206. return false;
  1207. result.clear();
  1208. result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
  1209. return true;
  1210. }
  1211. static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
  1212. #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
  1213. // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
  1214. // macros defined in <unistd.h> on darwin >= 9
  1215. int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR : _CS_DARWIN_USER_CACHE_DIR;
  1216. size_t ConfLen = confstr(ConfName, nullptr, 0);
  1217. if (ConfLen > 0) {
  1218. do {
  1219. Result.resize(ConfLen);
  1220. ConfLen = confstr(ConfName, Result.data(), Result.size());
  1221. } while (ConfLen > 0 && ConfLen != Result.size());
  1222. if (ConfLen > 0) {
  1223. assert(Result.back() == 0);
  1224. Result.pop_back();
  1225. return true;
  1226. }
  1227. Result.clear();
  1228. }
  1229. #endif
  1230. return false;
  1231. }
  1232. bool user_config_directory(SmallVectorImpl<char> &result) {
  1233. #ifdef __APPLE__
  1234. // Mac: ~/Library/Preferences/
  1235. if (home_directory(result)) {
  1236. append(result, "Library", "Preferences");
  1237. return true;
  1238. }
  1239. #else
  1240. // XDG_CONFIG_HOME as defined in the XDG Base Directory Specification:
  1241. // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
  1242. if (const char *RequestedDir = getenv("XDG_CONFIG_HOME")) {
  1243. result.clear();
  1244. result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
  1245. return true;
  1246. }
  1247. #endif
  1248. // Fallback: ~/.config
  1249. if (!home_directory(result)) {
  1250. return false;
  1251. }
  1252. append(result, ".config");
  1253. return true;
  1254. }
  1255. bool cache_directory(SmallVectorImpl<char> &result) {
  1256. #ifdef __APPLE__
  1257. if (getDarwinConfDir(false /*tempDir*/, result)) {
  1258. return true;
  1259. }
  1260. #else
  1261. // XDG_CACHE_HOME as defined in the XDG Base Directory Specification:
  1262. // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
  1263. if (const char *RequestedDir = getenv("XDG_CACHE_HOME")) {
  1264. result.clear();
  1265. result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
  1266. return true;
  1267. }
  1268. #endif
  1269. if (!home_directory(result)) {
  1270. return false;
  1271. }
  1272. append(result, ".cache");
  1273. return true;
  1274. }
  1275. static const char *getEnvTempDir() {
  1276. // Check whether the temporary directory is specified by an environment
  1277. // variable.
  1278. const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
  1279. for (const char *Env : EnvironmentVariables) {
  1280. if (const char *Dir = std::getenv(Env))
  1281. return Dir;
  1282. }
  1283. return nullptr;
  1284. }
  1285. static const char *getDefaultTempDir(bool ErasedOnReboot) {
  1286. #ifdef P_tmpdir
  1287. if ((bool)P_tmpdir)
  1288. return P_tmpdir;
  1289. #endif
  1290. if (ErasedOnReboot)
  1291. return "/tmp";
  1292. return "/var/tmp";
  1293. }
  1294. void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
  1295. Result.clear();
  1296. if (ErasedOnReboot) {
  1297. // There is no env variable for the cache directory.
  1298. if (const char *RequestedDir = getEnvTempDir()) {
  1299. Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
  1300. return;
  1301. }
  1302. }
  1303. if (getDarwinConfDir(ErasedOnReboot, Result))
  1304. return;
  1305. const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
  1306. Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
  1307. }
  1308. } // end namespace path
  1309. namespace fs {
  1310. #ifdef __APPLE__
  1311. /// This implementation tries to perform an APFS CoW clone of the file,
  1312. /// which can be much faster and uses less space.
  1313. /// Unfortunately fcopyfile(3) does not support COPYFILE_CLONE, so the
  1314. /// file descriptor variant of this function still uses the default
  1315. /// implementation.
  1316. std::error_code copy_file(const Twine &From, const Twine &To) {
  1317. std::string FromS = From.str();
  1318. std::string ToS = To.str();
  1319. #if __has_builtin(__builtin_available)
  1320. if (__builtin_available(macos 10.12, *)) {
  1321. // Optimistically try to use clonefile() and handle errors, rather than
  1322. // calling stat() to see if it'll work.
  1323. //
  1324. // Note: It's okay if From is a symlink. In contrast to the behaviour of
  1325. // copyfile() with COPYFILE_CLONE, clonefile() clones targets (not the
  1326. // symlink itself) unless the flag CLONE_NOFOLLOW is passed.
  1327. if (!clonefile(FromS.c_str(), ToS.c_str(), 0))
  1328. return std::error_code();
  1329. auto Errno = errno;
  1330. switch (Errno) {
  1331. case EEXIST: // To already exists.
  1332. case ENOTSUP: // Device does not support cloning.
  1333. case EXDEV: // From and To are on different devices.
  1334. break;
  1335. default:
  1336. // Anything else will also break copyfile().
  1337. return std::error_code(Errno, std::generic_category());
  1338. }
  1339. // TODO: For EEXIST, profile calling fs::generateUniqueName() and
  1340. // clonefile() in a retry loop (then rename() on success) before falling
  1341. // back to copyfile(). Depending on the size of the file this could be
  1342. // cheaper.
  1343. }
  1344. #endif
  1345. if (!copyfile(FromS.c_str(), ToS.c_str(), /*State=*/NULL, COPYFILE_DATA))
  1346. return std::error_code();
  1347. return std::error_code(errno, std::generic_category());
  1348. }
  1349. #endif // __APPLE__
  1350. } // end namespace fs
  1351. } // end namespace sys
  1352. } // end namespace llvm