Path.inc 20 KB

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