Path.inc 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502
  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 <mach-o/dyld.h>
  36. #include <sys/attr.h>
  37. #include <copyfile.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. #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) || defined(__GNU__) || \
  119. (defined(__sun__) && defined(__svr4__))
  120. static int
  121. test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
  122. {
  123. struct stat sb;
  124. char fullpath[PATH_MAX];
  125. int chars = snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
  126. // We cannot write PATH_MAX characters because the string will be terminated
  127. // with a null character. Fail if truncation happened.
  128. if (chars >= PATH_MAX)
  129. return 1;
  130. if (!realpath(fullpath, ret))
  131. return 1;
  132. if (stat(fullpath, &sb) != 0)
  133. return 1;
  134. return 0;
  135. }
  136. static char *
  137. getprogpath(char ret[PATH_MAX], const char *bin)
  138. {
  139. if (bin == nullptr)
  140. return nullptr;
  141. /* First approach: absolute path. */
  142. if (bin[0] == '/') {
  143. if (test_dir(ret, "/", bin) == 0)
  144. return ret;
  145. return nullptr;
  146. }
  147. /* Second approach: relative path. */
  148. if (strchr(bin, '/')) {
  149. char cwd[PATH_MAX];
  150. if (!getcwd(cwd, PATH_MAX))
  151. return nullptr;
  152. if (test_dir(ret, cwd, bin) == 0)
  153. return ret;
  154. return nullptr;
  155. }
  156. /* Third approach: $PATH */
  157. char *pv;
  158. if ((pv = getenv("PATH")) == nullptr)
  159. return nullptr;
  160. char *s = strdup(pv);
  161. if (!s)
  162. return nullptr;
  163. char *state;
  164. for (char *t = strtok_r(s, ":", &state); t != nullptr;
  165. t = strtok_r(nullptr, ":", &state)) {
  166. if (test_dir(ret, t, bin) == 0) {
  167. free(s);
  168. return ret;
  169. }
  170. }
  171. free(s);
  172. return nullptr;
  173. }
  174. #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
  175. /// GetMainExecutable - Return the path to the main executable, given the
  176. /// value of argv[0] from program startup.
  177. std::string getMainExecutable(const char *argv0, void *MainAddr) {
  178. #if defined(__APPLE__)
  179. // On OS X the executable path is saved to the stack by dyld. Reading it
  180. // from there is much faster than calling dladdr, especially for large
  181. // binaries with symbols.
  182. char exe_path[PATH_MAX];
  183. uint32_t size = sizeof(exe_path);
  184. if (_NSGetExecutablePath(exe_path, &size) == 0) {
  185. char link_path[PATH_MAX];
  186. if (realpath(exe_path, link_path))
  187. return link_path;
  188. }
  189. #elif defined(__FreeBSD__)
  190. // On FreeBSD if the exec path specified in ELF auxiliary vectors is
  191. // preferred, if available. /proc/curproc/file and the KERN_PROC_PATHNAME
  192. // sysctl may not return the desired path if there are multiple hardlinks
  193. // to the file.
  194. char exe_path[PATH_MAX];
  195. #if __FreeBSD_version >= 1300057
  196. if (elf_aux_info(AT_EXECPATH, exe_path, sizeof(exe_path)) == 0) {
  197. char link_path[PATH_MAX];
  198. if (realpath(exe_path, link_path))
  199. return link_path;
  200. }
  201. #else
  202. // elf_aux_info(AT_EXECPATH, ... is not available in all supported versions,
  203. // fall back to finding the ELF auxiliary vectors after the process's
  204. // environment.
  205. char **p = ::environ;
  206. while (*p++ != 0)
  207. ;
  208. // Iterate through auxiliary vectors for AT_EXECPATH.
  209. for (Elf_Auxinfo *aux = (Elf_Auxinfo *)p; aux->a_type != AT_NULL; aux++) {
  210. if (aux->a_type == AT_EXECPATH) {
  211. char link_path[PATH_MAX];
  212. if (realpath((char *)aux->a_un.a_ptr, link_path))
  213. return link_path;
  214. }
  215. }
  216. #endif
  217. // Fall back to argv[0] if auxiliary vectors are not available.
  218. if (getprogpath(exe_path, argv0) != NULL)
  219. return exe_path;
  220. #elif defined(__NetBSD__) || defined(__OpenBSD__) || defined(__minix) || \
  221. defined(__DragonFly__) || defined(__FreeBSD_kernel__) || defined(_AIX)
  222. const char *curproc = "/proc/curproc/file";
  223. char exe_path[PATH_MAX];
  224. if (sys::fs::exists(curproc)) {
  225. ssize_t len = readlink(curproc, exe_path, sizeof(exe_path));
  226. if (len > 0) {
  227. // Null terminate the string for realpath. readlink never null
  228. // terminates its output.
  229. len = std::min(len, ssize_t(sizeof(exe_path) - 1));
  230. exe_path[len] = '\0';
  231. return exe_path;
  232. }
  233. }
  234. // If we don't have procfs mounted, fall back to argv[0]
  235. if (getprogpath(exe_path, argv0) != NULL)
  236. return exe_path;
  237. #elif defined(__linux__) || defined(__CYGWIN__) || defined(__gnu_hurd__)
  238. char exe_path[PATH_MAX];
  239. const char *aPath = "/proc/self/exe";
  240. if (sys::fs::exists(aPath)) {
  241. // /proc is not always mounted under Linux (chroot for example).
  242. ssize_t len = readlink(aPath, exe_path, sizeof(exe_path));
  243. if (len < 0)
  244. return "";
  245. // Null terminate the string for realpath. readlink never null
  246. // terminates its output.
  247. len = std::min(len, ssize_t(sizeof(exe_path) - 1));
  248. exe_path[len] = '\0';
  249. // On Linux, /proc/self/exe always looks through symlinks. However, on
  250. // GNU/Hurd, /proc/self/exe is a symlink to the path that was used to start
  251. // the program, and not the eventual binary file. Therefore, call realpath
  252. // so this behaves the same on all platforms.
  253. #if _POSIX_VERSION >= 200112 || defined(__GLIBC__)
  254. if (char *real_path = realpath(exe_path, nullptr)) {
  255. std::string ret = std::string(real_path);
  256. free(real_path);
  257. return ret;
  258. }
  259. #else
  260. char real_path[PATH_MAX];
  261. if (realpath(exe_path, real_path))
  262. return std::string(real_path);
  263. #endif
  264. }
  265. // Fall back to the classical detection.
  266. if (getprogpath(exe_path, argv0))
  267. return exe_path;
  268. #elif defined(__sun__) && defined(__svr4__)
  269. char exe_path[PATH_MAX];
  270. const char *aPath = "/proc/self/execname";
  271. if (sys::fs::exists(aPath)) {
  272. int fd = open(aPath, O_RDONLY);
  273. if (fd == -1)
  274. return "";
  275. if (read(fd, exe_path, sizeof(exe_path)) < 0)
  276. return "";
  277. return exe_path;
  278. }
  279. // Fall back to the classical detection.
  280. if (getprogpath(exe_path, argv0) != NULL)
  281. return exe_path;
  282. #elif defined(__MVS__)
  283. int token = 0;
  284. W_PSPROC buf;
  285. char exe_path[PS_PATHBLEN];
  286. pid_t pid = getpid();
  287. memset(&buf, 0, sizeof(buf));
  288. buf.ps_pathptr = exe_path;
  289. buf.ps_pathlen = sizeof(exe_path);
  290. while (true) {
  291. if ((token = w_getpsent(token, &buf, sizeof(buf))) <= 0)
  292. break;
  293. if (buf.ps_pid != pid)
  294. continue;
  295. char real_path[PATH_MAX];
  296. if (realpath(exe_path, real_path))
  297. return std::string(real_path);
  298. break; // Found entry, but realpath failed.
  299. }
  300. #elif defined(HAVE_DLFCN_H) && defined(HAVE_DLADDR)
  301. // Use dladdr to get executable path if available.
  302. Dl_info DLInfo;
  303. int err = dladdr(MainAddr, &DLInfo);
  304. if (err == 0)
  305. return "";
  306. // If the filename is a symlink, we need to resolve and return the location of
  307. // the actual executable.
  308. char link_path[PATH_MAX];
  309. if (realpath(DLInfo.dli_fname, link_path))
  310. return link_path;
  311. #else
  312. #error GetMainExecutable is not implemented on this host yet.
  313. #endif
  314. return "";
  315. }
  316. TimePoint<> basic_file_status::getLastAccessedTime() const {
  317. return toTimePoint(fs_st_atime, fs_st_atime_nsec);
  318. }
  319. TimePoint<> basic_file_status::getLastModificationTime() const {
  320. return toTimePoint(fs_st_mtime, fs_st_mtime_nsec);
  321. }
  322. UniqueID file_status::getUniqueID() const {
  323. return UniqueID(fs_st_dev, fs_st_ino);
  324. }
  325. uint32_t file_status::getLinkCount() const {
  326. return fs_st_nlinks;
  327. }
  328. ErrorOr<space_info> disk_space(const Twine &Path) {
  329. struct STATVFS Vfs;
  330. if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))
  331. return std::error_code(errno, std::generic_category());
  332. auto FrSize = STATVFS_F_FRSIZE(Vfs);
  333. space_info SpaceInfo;
  334. SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;
  335. SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize;
  336. SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize;
  337. return SpaceInfo;
  338. }
  339. std::error_code current_path(SmallVectorImpl<char> &result) {
  340. result.clear();
  341. const char *pwd = ::getenv("PWD");
  342. llvm::sys::fs::file_status PWDStatus, DotStatus;
  343. if (pwd && llvm::sys::path::is_absolute(pwd) &&
  344. !llvm::sys::fs::status(pwd, PWDStatus) &&
  345. !llvm::sys::fs::status(".", DotStatus) &&
  346. PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
  347. result.append(pwd, pwd + strlen(pwd));
  348. return std::error_code();
  349. }
  350. result.resize_for_overwrite(PATH_MAX);
  351. while (true) {
  352. if (::getcwd(result.data(), result.size()) == nullptr) {
  353. // See if there was a real error.
  354. if (errno != ENOMEM) {
  355. result.clear();
  356. return std::error_code(errno, std::generic_category());
  357. }
  358. // Otherwise there just wasn't enough space.
  359. result.resize_for_overwrite(result.capacity() * 2);
  360. } else
  361. break;
  362. }
  363. result.truncate(strlen(result.data()));
  364. return std::error_code();
  365. }
  366. std::error_code set_current_path(const Twine &path) {
  367. SmallString<128> path_storage;
  368. StringRef p = path.toNullTerminatedStringRef(path_storage);
  369. if (::chdir(p.begin()) == -1)
  370. return std::error_code(errno, std::generic_category());
  371. return std::error_code();
  372. }
  373. std::error_code create_directory(const Twine &path, bool IgnoreExisting,
  374. perms Perms) {
  375. SmallString<128> path_storage;
  376. StringRef p = path.toNullTerminatedStringRef(path_storage);
  377. if (::mkdir(p.begin(), Perms) == -1) {
  378. if (errno != EEXIST || !IgnoreExisting)
  379. return std::error_code(errno, std::generic_category());
  380. }
  381. return std::error_code();
  382. }
  383. // Note that we are using symbolic link because hard links are not supported by
  384. // all filesystems (SMB doesn't).
  385. std::error_code create_link(const Twine &to, const Twine &from) {
  386. // Get arguments.
  387. SmallString<128> from_storage;
  388. SmallString<128> to_storage;
  389. StringRef f = from.toNullTerminatedStringRef(from_storage);
  390. StringRef t = to.toNullTerminatedStringRef(to_storage);
  391. if (::symlink(t.begin(), f.begin()) == -1)
  392. return std::error_code(errno, std::generic_category());
  393. return std::error_code();
  394. }
  395. std::error_code create_hard_link(const Twine &to, const Twine &from) {
  396. // Get arguments.
  397. SmallString<128> from_storage;
  398. SmallString<128> to_storage;
  399. StringRef f = from.toNullTerminatedStringRef(from_storage);
  400. StringRef t = to.toNullTerminatedStringRef(to_storage);
  401. if (::link(t.begin(), f.begin()) == -1)
  402. return std::error_code(errno, std::generic_category());
  403. return std::error_code();
  404. }
  405. std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
  406. SmallString<128> path_storage;
  407. StringRef p = path.toNullTerminatedStringRef(path_storage);
  408. struct stat buf;
  409. if (lstat(p.begin(), &buf) != 0) {
  410. if (errno != ENOENT || !IgnoreNonExisting)
  411. return std::error_code(errno, std::generic_category());
  412. return std::error_code();
  413. }
  414. // Note: this check catches strange situations. In all cases, LLVM should
  415. // only be involved in the creation and deletion of regular files. This
  416. // check ensures that what we're trying to erase is a regular file. It
  417. // effectively prevents LLVM from erasing things like /dev/null, any block
  418. // special file, or other things that aren't "regular" files.
  419. if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
  420. return make_error_code(errc::operation_not_permitted);
  421. if (::remove(p.begin()) == -1) {
  422. if (errno != ENOENT || !IgnoreNonExisting)
  423. return std::error_code(errno, std::generic_category());
  424. }
  425. return std::error_code();
  426. }
  427. static bool is_local_impl(struct STATVFS &Vfs) {
  428. #if defined(__linux__) || defined(__GNU__)
  429. #ifndef NFS_SUPER_MAGIC
  430. #define NFS_SUPER_MAGIC 0x6969
  431. #endif
  432. #ifndef SMB_SUPER_MAGIC
  433. #define SMB_SUPER_MAGIC 0x517B
  434. #endif
  435. #ifndef CIFS_MAGIC_NUMBER
  436. #define CIFS_MAGIC_NUMBER 0xFF534D42
  437. #endif
  438. #ifdef __GNU__
  439. switch ((uint32_t)Vfs.__f_type) {
  440. #else
  441. switch ((uint32_t)Vfs.f_type) {
  442. #endif
  443. case NFS_SUPER_MAGIC:
  444. case SMB_SUPER_MAGIC:
  445. case CIFS_MAGIC_NUMBER:
  446. return false;
  447. default:
  448. return true;
  449. }
  450. #elif defined(__CYGWIN__)
  451. // Cygwin doesn't expose this information; would need to use Win32 API.
  452. return false;
  453. #elif defined(__Fuchsia__)
  454. // Fuchsia doesn't yet support remote filesystem mounts.
  455. return true;
  456. #elif defined(__EMSCRIPTEN__)
  457. // Emscripten doesn't currently support remote filesystem mounts.
  458. return true;
  459. #elif defined(__HAIKU__)
  460. // Haiku doesn't expose this information.
  461. return false;
  462. #elif defined(__sun)
  463. // statvfs::f_basetype contains a null-terminated FSType name of the mounted target
  464. StringRef fstype(Vfs.f_basetype);
  465. // NFS is the only non-local fstype??
  466. return !fstype.equals("nfs");
  467. #elif defined(_AIX)
  468. // Call mntctl; try more than twice in case of timing issues with a concurrent
  469. // mount.
  470. int Ret;
  471. size_t BufSize = 2048u;
  472. std::unique_ptr<char[]> Buf;
  473. int Tries = 3;
  474. while (Tries--) {
  475. Buf = std::make_unique<char[]>(BufSize);
  476. Ret = mntctl(MCTL_QUERY, BufSize, Buf.get());
  477. if (Ret != 0)
  478. break;
  479. BufSize = *reinterpret_cast<unsigned int *>(Buf.get());
  480. Buf.reset();
  481. }
  482. if (Ret == -1)
  483. // There was an error; "remote" is the conservative answer.
  484. return false;
  485. // Look for the correct vmount entry.
  486. char *CurObjPtr = Buf.get();
  487. while (Ret--) {
  488. struct vmount *Vp = reinterpret_cast<struct vmount *>(CurObjPtr);
  489. static_assert(sizeof(Vfs.f_fsid) == sizeof(Vp->vmt_fsid),
  490. "fsid length mismatch");
  491. if (memcmp(&Vfs.f_fsid, &Vp->vmt_fsid, sizeof Vfs.f_fsid) == 0)
  492. return (Vp->vmt_flags & MNT_REMOTE) == 0;
  493. CurObjPtr += Vp->vmt_length;
  494. }
  495. // vmount entry not found; "remote" is the conservative answer.
  496. return false;
  497. #elif defined(__MVS__)
  498. // The file system can have an arbitrary structure on z/OS; must go with the
  499. // conservative answer.
  500. return false;
  501. #else
  502. return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
  503. #endif
  504. }
  505. std::error_code is_local(const Twine &Path, bool &Result) {
  506. struct STATVFS Vfs;
  507. if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))
  508. return std::error_code(errno, std::generic_category());
  509. Result = is_local_impl(Vfs);
  510. return std::error_code();
  511. }
  512. std::error_code is_local(int FD, bool &Result) {
  513. struct STATVFS Vfs;
  514. if (::FSTATVFS(FD, &Vfs))
  515. return std::error_code(errno, std::generic_category());
  516. Result = is_local_impl(Vfs);
  517. return std::error_code();
  518. }
  519. std::error_code rename(const Twine &from, const Twine &to) {
  520. // Get arguments.
  521. SmallString<128> from_storage;
  522. SmallString<128> to_storage;
  523. StringRef f = from.toNullTerminatedStringRef(from_storage);
  524. StringRef t = to.toNullTerminatedStringRef(to_storage);
  525. if (::rename(f.begin(), t.begin()) == -1)
  526. return std::error_code(errno, std::generic_category());
  527. return std::error_code();
  528. }
  529. std::error_code resize_file(int FD, uint64_t Size) {
  530. // Use ftruncate as a fallback. It may or may not allocate space. At least on
  531. // OS X with HFS+ it does.
  532. if (::ftruncate(FD, Size) == -1)
  533. return std::error_code(errno, std::generic_category());
  534. return std::error_code();
  535. }
  536. static int convertAccessMode(AccessMode Mode) {
  537. switch (Mode) {
  538. case AccessMode::Exist:
  539. return F_OK;
  540. case AccessMode::Write:
  541. return W_OK;
  542. case AccessMode::Execute:
  543. return R_OK | X_OK; // scripts also need R_OK.
  544. }
  545. llvm_unreachable("invalid enum");
  546. }
  547. std::error_code access(const Twine &Path, AccessMode Mode) {
  548. SmallString<128> PathStorage;
  549. StringRef P = Path.toNullTerminatedStringRef(PathStorage);
  550. if (::access(P.begin(), convertAccessMode(Mode)) == -1)
  551. return std::error_code(errno, std::generic_category());
  552. if (Mode == AccessMode::Execute) {
  553. // Don't say that directories are executable.
  554. struct stat buf;
  555. if (0 != stat(P.begin(), &buf))
  556. return errc::permission_denied;
  557. if (!S_ISREG(buf.st_mode))
  558. return errc::permission_denied;
  559. }
  560. return std::error_code();
  561. }
  562. bool can_execute(const Twine &Path) {
  563. return !access(Path, AccessMode::Execute);
  564. }
  565. bool equivalent(file_status A, file_status B) {
  566. assert(status_known(A) && status_known(B));
  567. return A.fs_st_dev == B.fs_st_dev &&
  568. A.fs_st_ino == B.fs_st_ino;
  569. }
  570. std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
  571. file_status fsA, fsB;
  572. if (std::error_code ec = status(A, fsA))
  573. return ec;
  574. if (std::error_code ec = status(B, fsB))
  575. return ec;
  576. result = equivalent(fsA, fsB);
  577. return std::error_code();
  578. }
  579. static void expandTildeExpr(SmallVectorImpl<char> &Path) {
  580. StringRef PathStr(Path.begin(), Path.size());
  581. if (PathStr.empty() || !PathStr.startswith("~"))
  582. return;
  583. PathStr = PathStr.drop_front();
  584. StringRef Expr =
  585. PathStr.take_until([](char c) { return path::is_separator(c); });
  586. StringRef Remainder = PathStr.substr(Expr.size() + 1);
  587. SmallString<128> Storage;
  588. if (Expr.empty()) {
  589. // This is just ~/..., resolve it to the current user's home dir.
  590. if (!path::home_directory(Storage)) {
  591. // For some reason we couldn't get the home directory. Just exit.
  592. return;
  593. }
  594. // Overwrite the first character and insert the rest.
  595. Path[0] = Storage[0];
  596. Path.insert(Path.begin() + 1, Storage.begin() + 1, Storage.end());
  597. return;
  598. }
  599. // This is a string of the form ~username/, look up this user's entry in the
  600. // password database.
  601. struct passwd *Entry = nullptr;
  602. std::string User = Expr.str();
  603. Entry = ::getpwnam(User.c_str());
  604. if (!Entry) {
  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,
  660. Status.st_atime, atime_nsec, Status.st_mtime, mtime_nsec,
  661. Status.st_uid, 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 defined(__MVS__) || defined(_AIX)
  776. // If we don't have madvise, or it isn't beneficial, treat this as a no-op.
  777. return;
  778. #else
  779. if (Mapping)
  780. ::madvise(Mapping, Size, MADV_DONTNEED);
  781. #endif
  782. }
  783. int mapped_file_region::alignment() {
  784. return Process::getPageSizeEstimate();
  785. }
  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. #if !defined(F_GETPATH)
  841. static bool hasProcSelfFD() {
  842. // If we have a /proc filesystem mounted, we can quickly establish the
  843. // real name of the file with readlink
  844. static const bool Result = (::access("/proc/self/fd", R_OK) == 0);
  845. return Result;
  846. }
  847. #endif
  848. static int nativeOpenFlags(CreationDisposition Disp, OpenFlags Flags,
  849. FileAccess Access) {
  850. int Result = 0;
  851. if (Access == FA_Read)
  852. Result |= O_RDONLY;
  853. else if (Access == FA_Write)
  854. Result |= O_WRONLY;
  855. else if (Access == (FA_Read | FA_Write))
  856. Result |= O_RDWR;
  857. // This is for compatibility with old code that assumed OF_Append implied
  858. // would open an existing file. See Windows/Path.inc for a longer comment.
  859. if (Flags & OF_Append)
  860. Disp = CD_OpenAlways;
  861. if (Disp == CD_CreateNew) {
  862. Result |= O_CREAT; // Create if it doesn't exist.
  863. Result |= O_EXCL; // Fail if it does.
  864. } else if (Disp == CD_CreateAlways) {
  865. Result |= O_CREAT; // Create if it doesn't exist.
  866. Result |= O_TRUNC; // Truncate if it does.
  867. } else if (Disp == CD_OpenAlways) {
  868. Result |= O_CREAT; // Create if it doesn't exist.
  869. } else if (Disp == CD_OpenExisting) {
  870. // Nothing special, just don't add O_CREAT and we get these semantics.
  871. }
  872. // Using append mode with z/OS UTF-8 auto-conversion results in EINVAL when
  873. // calling write(). Instead we need to use lseek() to set offset to EOF after
  874. // open().
  875. #ifndef __MVS__
  876. if (Flags & OF_Append)
  877. Result |= O_APPEND;
  878. #endif
  879. #ifdef O_CLOEXEC
  880. if (!(Flags & OF_ChildInherit))
  881. Result |= O_CLOEXEC;
  882. #endif
  883. return Result;
  884. }
  885. std::error_code openFile(const Twine &Name, int &ResultFD,
  886. CreationDisposition Disp, FileAccess Access,
  887. OpenFlags Flags, unsigned Mode) {
  888. int OpenFlags = nativeOpenFlags(Disp, Flags, Access);
  889. SmallString<128> Storage;
  890. StringRef P = Name.toNullTerminatedStringRef(Storage);
  891. // Call ::open in a lambda to avoid overload resolution in RetryAfterSignal
  892. // when open is overloaded, such as in Bionic.
  893. auto Open = [&]() { return ::open(P.begin(), OpenFlags, Mode); };
  894. if ((ResultFD = sys::RetryAfterSignal(-1, Open)) < 0)
  895. return std::error_code(errno, std::generic_category());
  896. #ifndef O_CLOEXEC
  897. if (!(Flags & OF_ChildInherit)) {
  898. int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
  899. (void)r;
  900. assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
  901. }
  902. #endif
  903. #ifdef __MVS__
  904. /* Reason about auto-conversion and file tags. Setting the file tag only
  905. * applies if file is opened in write mode:
  906. *
  907. * Text file:
  908. * File exists File created
  909. * CD_CreateNew n/a conv: on
  910. * tag: set 1047
  911. * CD_CreateAlways conv: auto conv: on
  912. * tag: auto 1047 tag: set 1047
  913. * CD_OpenAlways conv: auto conv: on
  914. * tag: auto 1047 tag: set 1047
  915. * CD_OpenExisting conv: auto n/a
  916. * tag: unchanged
  917. *
  918. * Binary file:
  919. * File exists File created
  920. * CD_CreateNew n/a conv: off
  921. * tag: set binary
  922. * CD_CreateAlways conv: off conv: off
  923. * tag: auto binary tag: set binary
  924. * CD_OpenAlways conv: off conv: off
  925. * tag: auto binary tag: set binary
  926. * CD_OpenExisting conv: off n/a
  927. * tag: unchanged
  928. *
  929. * Actions:
  930. * conv: off -> auto-conversion is turned off
  931. * conv: on -> auto-conversion is turned on
  932. * conv: auto -> auto-conversion is turned on if the file is untagged
  933. * tag: set 1047 -> set the file tag to text encoded in 1047
  934. * tag: set binary -> set the file tag to binary
  935. * tag: auto 1047 -> set file tag to 1047 if not set
  936. * tag: auto binary -> set file tag to binary if not set
  937. * tag: unchanged -> do not care about the file tag
  938. *
  939. * It is not possible to distinguish between the cases "file exists" and
  940. * "file created". In the latter case, the file tag is not set and the file
  941. * size is zero. The decision table boils down to:
  942. *
  943. * the file tag is set if
  944. * - the file is opened for writing
  945. * - the create disposition is not equal to CD_OpenExisting
  946. * - the file tag is not set
  947. * - the file size is zero
  948. *
  949. * This only applies if the file is a regular file. E.g. enabling
  950. * auto-conversion for reading from /dev/null results in error EINVAL when
  951. * calling read().
  952. *
  953. * Using append mode with z/OS UTF-8 auto-conversion results in EINVAL when
  954. * calling write(). Instead we need to use lseek() to set offset to EOF after
  955. * open().
  956. */
  957. if ((Flags & OF_Append) && lseek(ResultFD, 0, SEEK_END) == -1)
  958. return std::error_code(errno, std::generic_category());
  959. struct stat Stat;
  960. if (fstat(ResultFD, &Stat) == -1)
  961. return std::error_code(errno, std::generic_category());
  962. if (S_ISREG(Stat.st_mode)) {
  963. bool DoSetTag = (Access & FA_Write) && (Disp != CD_OpenExisting) &&
  964. !Stat.st_tag.ft_txtflag && !Stat.st_tag.ft_ccsid &&
  965. Stat.st_size == 0;
  966. if (Flags & OF_Text) {
  967. if (auto EC = llvm::enableAutoConversion(ResultFD))
  968. return EC;
  969. if (DoSetTag) {
  970. if (auto EC = llvm::setFileTag(ResultFD, CCSID_IBM_1047, true))
  971. return EC;
  972. }
  973. } else {
  974. if (auto EC = llvm::disableAutoConversion(ResultFD))
  975. return EC;
  976. if (DoSetTag) {
  977. if (auto EC = llvm::setFileTag(ResultFD, FT_BINARY, false))
  978. return EC;
  979. }
  980. }
  981. }
  982. #endif
  983. return std::error_code();
  984. }
  985. Expected<int> openNativeFile(const Twine &Name, CreationDisposition Disp,
  986. FileAccess Access, OpenFlags Flags,
  987. unsigned Mode) {
  988. int FD;
  989. std::error_code EC = openFile(Name, FD, Disp, Access, Flags, Mode);
  990. if (EC)
  991. return errorCodeToError(EC);
  992. return FD;
  993. }
  994. std::error_code openFileForRead(const Twine &Name, int &ResultFD,
  995. OpenFlags Flags,
  996. SmallVectorImpl<char> *RealPath) {
  997. std::error_code EC =
  998. openFile(Name, ResultFD, CD_OpenExisting, FA_Read, Flags, 0666);
  999. if (EC)
  1000. return EC;
  1001. // Attempt to get the real name of the file, if the user asked
  1002. if(!RealPath)
  1003. return std::error_code();
  1004. RealPath->clear();
  1005. #if defined(F_GETPATH)
  1006. // When F_GETPATH is availble, it is the quickest way to get
  1007. // the real path name.
  1008. char Buffer[PATH_MAX];
  1009. if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
  1010. RealPath->append(Buffer, Buffer + strlen(Buffer));
  1011. #else
  1012. char Buffer[PATH_MAX];
  1013. if (hasProcSelfFD()) {
  1014. char ProcPath[64];
  1015. snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
  1016. ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
  1017. if (CharCount > 0)
  1018. RealPath->append(Buffer, Buffer + CharCount);
  1019. } else {
  1020. SmallString<128> Storage;
  1021. StringRef P = Name.toNullTerminatedStringRef(Storage);
  1022. // Use ::realpath to get the real path name
  1023. if (::realpath(P.begin(), Buffer) != nullptr)
  1024. RealPath->append(Buffer, Buffer + strlen(Buffer));
  1025. }
  1026. #endif
  1027. return std::error_code();
  1028. }
  1029. Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
  1030. SmallVectorImpl<char> *RealPath) {
  1031. file_t ResultFD;
  1032. std::error_code EC = openFileForRead(Name, ResultFD, Flags, RealPath);
  1033. if (EC)
  1034. return errorCodeToError(EC);
  1035. return ResultFD;
  1036. }
  1037. file_t getStdinHandle() { return 0; }
  1038. file_t getStdoutHandle() { return 1; }
  1039. file_t getStderrHandle() { return 2; }
  1040. Expected<size_t> readNativeFile(file_t FD, MutableArrayRef<char> Buf) {
  1041. #if defined(__APPLE__)
  1042. size_t Size = std::min<size_t>(Buf.size(), INT32_MAX);
  1043. #else
  1044. size_t Size = Buf.size();
  1045. #endif
  1046. ssize_t NumRead =
  1047. sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Size);
  1048. if (ssize_t(NumRead) == -1)
  1049. return errorCodeToError(std::error_code(errno, std::generic_category()));
  1050. return NumRead;
  1051. }
  1052. Expected<size_t> readNativeFileSlice(file_t FD, MutableArrayRef<char> Buf,
  1053. uint64_t Offset) {
  1054. #if defined(__APPLE__)
  1055. size_t Size = std::min<size_t>(Buf.size(), INT32_MAX);
  1056. #else
  1057. size_t Size = Buf.size();
  1058. #endif
  1059. #ifdef HAVE_PREAD
  1060. ssize_t NumRead =
  1061. sys::RetryAfterSignal(-1, ::pread, FD, Buf.data(), Size, Offset);
  1062. #else
  1063. if (lseek(FD, Offset, SEEK_SET) == -1)
  1064. return errorCodeToError(std::error_code(errno, std::generic_category()));
  1065. ssize_t NumRead =
  1066. sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Size);
  1067. #endif
  1068. if (NumRead == -1)
  1069. return errorCodeToError(std::error_code(errno, std::generic_category()));
  1070. return NumRead;
  1071. }
  1072. std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout) {
  1073. auto Start = std::chrono::steady_clock::now();
  1074. auto End = Start + Timeout;
  1075. do {
  1076. struct flock Lock;
  1077. memset(&Lock, 0, sizeof(Lock));
  1078. Lock.l_type = F_WRLCK;
  1079. Lock.l_whence = SEEK_SET;
  1080. Lock.l_start = 0;
  1081. Lock.l_len = 0;
  1082. if (::fcntl(FD, F_SETLK, &Lock) != -1)
  1083. return std::error_code();
  1084. int Error = errno;
  1085. if (Error != EACCES && Error != EAGAIN)
  1086. return std::error_code(Error, std::generic_category());
  1087. usleep(1000);
  1088. } while (std::chrono::steady_clock::now() < End);
  1089. return make_error_code(errc::no_lock_available);
  1090. }
  1091. std::error_code lockFile(int FD) {
  1092. struct flock Lock;
  1093. memset(&Lock, 0, sizeof(Lock));
  1094. Lock.l_type = F_WRLCK;
  1095. Lock.l_whence = SEEK_SET;
  1096. Lock.l_start = 0;
  1097. Lock.l_len = 0;
  1098. if (::fcntl(FD, F_SETLKW, &Lock) != -1)
  1099. return std::error_code();
  1100. int Error = errno;
  1101. return std::error_code(Error, std::generic_category());
  1102. }
  1103. std::error_code unlockFile(int FD) {
  1104. struct flock Lock;
  1105. Lock.l_type = F_UNLCK;
  1106. Lock.l_whence = SEEK_SET;
  1107. Lock.l_start = 0;
  1108. Lock.l_len = 0;
  1109. if (::fcntl(FD, F_SETLK, &Lock) != -1)
  1110. return std::error_code();
  1111. return std::error_code(errno, std::generic_category());
  1112. }
  1113. std::error_code closeFile(file_t &F) {
  1114. file_t TmpF = F;
  1115. F = kInvalidFile;
  1116. return Process::SafelyCloseFileDescriptor(TmpF);
  1117. }
  1118. template <typename T>
  1119. static std::error_code remove_directories_impl(const T &Entry,
  1120. bool IgnoreErrors) {
  1121. std::error_code EC;
  1122. directory_iterator Begin(Entry, EC, false);
  1123. directory_iterator End;
  1124. while (Begin != End) {
  1125. auto &Item = *Begin;
  1126. ErrorOr<basic_file_status> st = Item.status();
  1127. if (!st && !IgnoreErrors)
  1128. return st.getError();
  1129. if (is_directory(*st)) {
  1130. EC = remove_directories_impl(Item, IgnoreErrors);
  1131. if (EC && !IgnoreErrors)
  1132. return EC;
  1133. }
  1134. EC = fs::remove(Item.path(), true);
  1135. if (EC && !IgnoreErrors)
  1136. return EC;
  1137. Begin.increment(EC);
  1138. if (EC && !IgnoreErrors)
  1139. return EC;
  1140. }
  1141. return std::error_code();
  1142. }
  1143. std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
  1144. auto EC = remove_directories_impl(path, IgnoreErrors);
  1145. if (EC && !IgnoreErrors)
  1146. return EC;
  1147. EC = fs::remove(path, true);
  1148. if (EC && !IgnoreErrors)
  1149. return EC;
  1150. return std::error_code();
  1151. }
  1152. std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
  1153. bool expand_tilde) {
  1154. dest.clear();
  1155. if (path.isTriviallyEmpty())
  1156. return std::error_code();
  1157. if (expand_tilde) {
  1158. SmallString<128> Storage;
  1159. path.toVector(Storage);
  1160. expandTildeExpr(Storage);
  1161. return real_path(Storage, dest, false);
  1162. }
  1163. SmallString<128> Storage;
  1164. StringRef P = path.toNullTerminatedStringRef(Storage);
  1165. char Buffer[PATH_MAX];
  1166. if (::realpath(P.begin(), Buffer) == nullptr)
  1167. return std::error_code(errno, std::generic_category());
  1168. dest.append(Buffer, Buffer + strlen(Buffer));
  1169. return std::error_code();
  1170. }
  1171. std::error_code changeFileOwnership(int FD, uint32_t Owner, uint32_t Group) {
  1172. auto FChown = [&]() { return ::fchown(FD, Owner, Group); };
  1173. // Retry if fchown call fails due to interruption.
  1174. if ((sys::RetryAfterSignal(-1, FChown)) < 0)
  1175. return std::error_code(errno, std::generic_category());
  1176. return std::error_code();
  1177. }
  1178. } // end namespace fs
  1179. namespace path {
  1180. bool home_directory(SmallVectorImpl<char> &result) {
  1181. char *RequestedDir = getenv("HOME");
  1182. if (!RequestedDir) {
  1183. struct passwd *pw = getpwuid(getuid());
  1184. if (pw && pw->pw_dir)
  1185. RequestedDir = pw->pw_dir;
  1186. }
  1187. if (!RequestedDir)
  1188. return false;
  1189. result.clear();
  1190. result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
  1191. return true;
  1192. }
  1193. static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
  1194. #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
  1195. // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
  1196. // macros defined in <unistd.h> on darwin >= 9
  1197. int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
  1198. : _CS_DARWIN_USER_CACHE_DIR;
  1199. size_t ConfLen = confstr(ConfName, nullptr, 0);
  1200. if (ConfLen > 0) {
  1201. do {
  1202. Result.resize(ConfLen);
  1203. ConfLen = confstr(ConfName, Result.data(), Result.size());
  1204. } while (ConfLen > 0 && ConfLen != Result.size());
  1205. if (ConfLen > 0) {
  1206. assert(Result.back() == 0);
  1207. Result.pop_back();
  1208. return true;
  1209. }
  1210. Result.clear();
  1211. }
  1212. #endif
  1213. return false;
  1214. }
  1215. bool user_config_directory(SmallVectorImpl<char> &result) {
  1216. #ifdef __APPLE__
  1217. // Mac: ~/Library/Preferences/
  1218. if (home_directory(result)) {
  1219. append(result, "Library", "Preferences");
  1220. return true;
  1221. }
  1222. #else
  1223. // XDG_CONFIG_HOME as defined in the XDG Base Directory Specification:
  1224. // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
  1225. if (const char *RequestedDir = getenv("XDG_CONFIG_HOME")) {
  1226. result.clear();
  1227. result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
  1228. return true;
  1229. }
  1230. #endif
  1231. // Fallback: ~/.config
  1232. if (!home_directory(result)) {
  1233. return false;
  1234. }
  1235. append(result, ".config");
  1236. return true;
  1237. }
  1238. bool cache_directory(SmallVectorImpl<char> &result) {
  1239. #ifdef __APPLE__
  1240. if (getDarwinConfDir(false/*tempDir*/, result)) {
  1241. return true;
  1242. }
  1243. #else
  1244. // XDG_CACHE_HOME as defined in the XDG Base Directory Specification:
  1245. // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
  1246. if (const char *RequestedDir = getenv("XDG_CACHE_HOME")) {
  1247. result.clear();
  1248. result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
  1249. return true;
  1250. }
  1251. #endif
  1252. if (!home_directory(result)) {
  1253. return false;
  1254. }
  1255. append(result, ".cache");
  1256. return true;
  1257. }
  1258. static const char *getEnvTempDir() {
  1259. // Check whether the temporary directory is specified by an environment
  1260. // variable.
  1261. const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
  1262. for (const char *Env : EnvironmentVariables) {
  1263. if (const char *Dir = std::getenv(Env))
  1264. return Dir;
  1265. }
  1266. return nullptr;
  1267. }
  1268. static const char *getDefaultTempDir(bool ErasedOnReboot) {
  1269. #ifdef P_tmpdir
  1270. if ((bool)P_tmpdir)
  1271. return P_tmpdir;
  1272. #endif
  1273. if (ErasedOnReboot)
  1274. return "/tmp";
  1275. return "/var/tmp";
  1276. }
  1277. void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
  1278. Result.clear();
  1279. if (ErasedOnReboot) {
  1280. // There is no env variable for the cache directory.
  1281. if (const char *RequestedDir = getEnvTempDir()) {
  1282. Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
  1283. return;
  1284. }
  1285. }
  1286. if (getDarwinConfDir(ErasedOnReboot, Result))
  1287. return;
  1288. const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
  1289. Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
  1290. }
  1291. } // end namespace path
  1292. namespace fs {
  1293. #ifdef __APPLE__
  1294. /// This implementation tries to perform an APFS CoW clone of the file,
  1295. /// which can be much faster and uses less space.
  1296. /// Unfortunately fcopyfile(3) does not support COPYFILE_CLONE, so the
  1297. /// file descriptor variant of this function still uses the default
  1298. /// implementation.
  1299. std::error_code copy_file(const Twine &From, const Twine &To) {
  1300. std::string FromS = From.str();
  1301. std::string ToS = To.str();
  1302. #if __has_builtin(__builtin_available)
  1303. if (__builtin_available(macos 10.12, *)) {
  1304. // Optimistically try to use clonefile() and handle errors, rather than
  1305. // calling stat() to see if it'll work.
  1306. //
  1307. // Note: It's okay if From is a symlink. In contrast to the behaviour of
  1308. // copyfile() with COPYFILE_CLONE, clonefile() clones targets (not the
  1309. // symlink itself) unless the flag CLONE_NOFOLLOW is passed.
  1310. if (!clonefile(FromS.c_str(), ToS.c_str(), 0))
  1311. return std::error_code();
  1312. auto Errno = errno;
  1313. switch (Errno) {
  1314. case EEXIST: // To already exists.
  1315. case ENOTSUP: // Device does not support cloning.
  1316. case EXDEV: // From and To are on different devices.
  1317. break;
  1318. default:
  1319. // Anything else will also break copyfile().
  1320. return std::error_code(Errno, std::generic_category());
  1321. }
  1322. // TODO: For EEXIST, profile calling fs::generateUniqueName() and
  1323. // clonefile() in a retry loop (then rename() on success) before falling
  1324. // back to copyfile(). Depending on the size of the file this could be
  1325. // cheaper.
  1326. }
  1327. #endif
  1328. if (!copyfile(FromS.c_str(), ToS.c_str(), /*State=*/NULL, COPYFILE_DATA))
  1329. return std::error_code();
  1330. return std::error_code(errno, std::generic_category());
  1331. }
  1332. #endif // __APPLE__
  1333. } // end namespace fs
  1334. } // end namespace sys
  1335. } // end namespace llvm