MSFileSystem.inc.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  1. //===- llvm/Support/Windows/MSFileSystem.cpp - DXCompiler Impl --*- C++ -*-===//
  2. ///////////////////////////////////////////////////////////////////////////////
  3. // //
  4. // MSFileSystem.inc.cpp //
  5. // Copyright (C) Microsoft Corporation. All rights reserved. //
  6. // This file is distributed under the University of Illinois Open Source //
  7. // License. See LICENSE.TXT for details. //
  8. // //
  9. // This file implements the Windows specific implementation of the Path API. //
  10. // //
  11. ///////////////////////////////////////////////////////////////////////////////
  12. #include "llvm/ADT/STLExtras.h"
  13. #define NOMINMAX
  14. #include "WindowsSupport.h"
  15. #include <fcntl.h>
  16. #ifdef _WIN32
  17. #include <io.h>
  18. #endif
  19. #include <sys/stat.h>
  20. #include <sys/types.h>
  21. #include <system_error>
  22. #include "llvm/Support/WindowsError.h"
  23. #include "llvm/Support/MSFileSystem.h"
  24. // MinGW doesn't define this.
  25. #ifndef _ERRNO_T_DEFINED
  26. #define _ERRNO_T_DEFINED
  27. typedef int errno_t;
  28. #endif
  29. using namespace llvm;
  30. using std::error_code;
  31. using std::system_category;
  32. using llvm::sys::windows::UTF8ToUTF16;
  33. using llvm::sys::windows::UTF16ToUTF8;
  34. using llvm::sys::path::widenPath;
  35. namespace llvm {
  36. namespace sys {
  37. namespace windows {
  38. error_code UTF8ToUTF16(llvm::StringRef utf8,
  39. llvm::SmallVectorImpl<wchar_t> &utf16);
  40. error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
  41. llvm::SmallVectorImpl<char> &utf8);
  42. } // llvm::sys::windows
  43. namespace fs {
  44. ///////////////////////////////////////////////////////////////////////////////////////////////////
  45. // Per-thread MSFileSystem support.
  46. static DWORD g_FileSystemTls;
  47. error_code SetupPerThreadFileSystem() throw()
  48. {
  49. assert(g_FileSystemTls == 0 && "otherwise this has already been initialized");
  50. g_FileSystemTls = TlsAlloc();
  51. if (g_FileSystemTls == TLS_OUT_OF_INDEXES)
  52. {
  53. g_FileSystemTls = 0;
  54. return mapWindowsError(::GetLastError());
  55. }
  56. return error_code();
  57. }
  58. void CleanupPerThreadFileSystem() throw()
  59. {
  60. TlsFree(g_FileSystemTls);
  61. g_FileSystemTls = 0;
  62. }
  63. MSFileSystemRef GetCurrentThreadFileSystem() throw()
  64. {
  65. return (MSFileSystemRef)TlsGetValue(g_FileSystemTls);
  66. }
  67. error_code SetCurrentThreadFileSystem(MSFileSystemRef value) throw()
  68. {
  69. // For now, disallow reentrancy in APIs (i.e., replace the current instance with another one).
  70. if (value != nullptr)
  71. {
  72. MSFileSystemRef current = GetCurrentThreadFileSystem();
  73. if (current != nullptr)
  74. {
  75. return error_code(ERROR_POSSIBLE_DEADLOCK, system_category());
  76. }
  77. }
  78. if (!TlsSetValue(g_FileSystemTls, value))
  79. {
  80. return mapWindowsError(::GetLastError());
  81. }
  82. return error_code();
  83. }
  84. ///////////////////////////////////////////////////////////////////////////////////////////////////
  85. // Support for CRT-like file stream functions.
  86. int msf_read(int fd, void* buffer, unsigned int count)
  87. {
  88. MSFileSystemRef fsr = GetCurrentThreadFileSystem();
  89. if (fsr == nullptr) {
  90. errno = EBADF;
  91. return -1;
  92. }
  93. return fsr->Read(fd, buffer, count);
  94. }
  95. int msf_write(int fd, const void* buffer, unsigned int count)
  96. {
  97. MSFileSystemRef fsr = GetCurrentThreadFileSystem();
  98. if (fsr == nullptr) {
  99. errno = EBADF;
  100. return -1;
  101. }
  102. return fsr->Write(fd, buffer, count);
  103. }
  104. int msf_close(int fd)
  105. {
  106. MSFileSystemRef fsr = GetCurrentThreadFileSystem();
  107. if (fsr == nullptr) {
  108. errno = EBADF;
  109. return -1;
  110. }
  111. return fsr->close(fd);
  112. }
  113. long msf_lseek(int fd, long offset, int origin)
  114. {
  115. MSFileSystemRef fsr = GetCurrentThreadFileSystem();
  116. if (fsr == nullptr) {
  117. errno = EBADF;
  118. return -1;
  119. }
  120. return fsr->lseek(fd, offset, origin);
  121. }
  122. int msf_setmode(int fd, int mode)
  123. {
  124. MSFileSystemRef fsr = GetCurrentThreadFileSystem();
  125. if (fsr == nullptr) {
  126. errno = EBADF;
  127. return -1;
  128. }
  129. return fsr->setmode(fd, mode);
  130. }
  131. } } }
  132. ///////////////////////////////////////////////////////////////////////////////////////////////////
  133. // MSFileSystem-based support for Path APIs.
  134. typedef llvm::sys::fs::MSFileSystemRef MSFileSystemRef;
  135. static
  136. error_code GetCurrentThreadFileSystemOrError(_Outptr_ MSFileSystemRef* pResult) throw()
  137. {
  138. *pResult = ::llvm::sys::fs::GetCurrentThreadFileSystem();
  139. // It is an error to have an I/O API invoked without having installed support
  140. // for it. We handle it gracefully in case there is problem while shutting
  141. // down, but this is a bug that should be fixed.
  142. assert(*pResult);
  143. if (*pResult == nullptr) {
  144. return mapWindowsError(ERROR_NOT_READY);
  145. }
  146. return error_code();
  147. }
  148. static bool is_separator(const wchar_t value) {
  149. switch (value) {
  150. case L'\\':
  151. case L'/':
  152. return true;
  153. default:
  154. return false;
  155. }
  156. }
  157. // TODO: consider erasing this
  158. namespace {
  159. error_code TempDir(_In_ MSFileSystemRef fsr, SmallVectorImpl<wchar_t> &result) {
  160. retry_temp_dir:
  161. DWORD len = fsr->GetTempPathW(result.capacity(), result.begin());
  162. if (len == 0)
  163. return mapWindowsError(::GetLastError());
  164. if (len > result.capacity()) {
  165. result.reserve(len);
  166. goto retry_temp_dir;
  167. }
  168. result.set_size(len);
  169. return error_code();
  170. }
  171. }
  172. namespace llvm {
  173. namespace sys {
  174. namespace path {
  175. // Convert a UTF-8 path to UTF-16. Also, if the absolute equivalent of the
  176. // path is longer than CreateDirectory can tolerate, make it absolute and
  177. // prefixed by '\\?\'.
  178. std::error_code widenPath(const Twine &Path8,
  179. SmallVectorImpl<wchar_t> &Path16) {
  180. const size_t MaxDirLen = MAX_PATH - 12; // Must leave room for 8.3 filename.
  181. // Several operations would convert Path8 to SmallString; more efficient to
  182. // do it once up front.
  183. SmallString<128> Path8Str;
  184. Path8.toVector(Path8Str);
  185. // If we made this path absolute, how much longer would it get?
  186. size_t CurPathLen;
  187. if (llvm::sys::path::is_absolute(Twine(Path8Str)))
  188. CurPathLen = 0; // No contribution from current_path needed.
  189. else {
  190. CurPathLen = ::GetCurrentDirectoryW(0, NULL);
  191. if (CurPathLen == 0)
  192. return mapWindowsError(::GetLastError());
  193. }
  194. // Would the absolute path be longer than our limit?
  195. if ((Path8Str.size() + CurPathLen) >= MaxDirLen &&
  196. !Path8Str.startswith("\\\\?\\")) {
  197. SmallString<2 * MAX_PATH> FullPath("\\\\?\\");
  198. if (CurPathLen) {
  199. SmallString<80> CurPath;
  200. if (std::error_code EC = llvm::sys::fs::current_path(CurPath))
  201. return EC;
  202. FullPath.append(CurPath);
  203. }
  204. // Traverse the requested path, canonicalizing . and .. as we go (because
  205. // the \\?\ prefix is documented to treat them as real components).
  206. // The iterators don't report separators and append() always attaches
  207. // preferred_separator so we don't need to call native() on the result.
  208. for (llvm::sys::path::const_iterator I = llvm::sys::path::begin(Path8Str),
  209. E = llvm::sys::path::end(Path8Str);
  210. I != E; ++I) {
  211. if (I->size() == 1 && *I == ".")
  212. continue;
  213. if (I->size() == 2 && *I == "..")
  214. llvm::sys::path::remove_filename(FullPath);
  215. else
  216. llvm::sys::path::append(FullPath, *I);
  217. }
  218. return UTF8ToUTF16(FullPath, Path16);
  219. }
  220. // Just use the caller's original path.
  221. return UTF8ToUTF16(Path8Str, Path16);
  222. }
  223. } // end namespace path
  224. namespace fs {
  225. std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
  226. MSFileSystemRef fsr;
  227. if (error_code ec = GetCurrentThreadFileSystemOrError(&fsr)) return "";
  228. SmallVector<wchar_t, MAX_PATH> PathName;
  229. DWORD Size = fsr->GetMainModuleFileNameW(PathName.data(), PathName.capacity());
  230. // A zero return value indicates a failure other than insufficient space.
  231. if (Size == 0)
  232. return "";
  233. // Insufficient space is determined by a return value equal to the size of
  234. // the buffer passed in.
  235. if (Size == PathName.capacity())
  236. return "";
  237. // On success, GetModuleFileNameW returns the number of characters written to
  238. // the buffer not including the NULL terminator.
  239. PathName.set_size(Size);
  240. // Convert the result from UTF-16 to UTF-8.
  241. SmallVector<char, MAX_PATH> PathNameUTF8;
  242. if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
  243. return "";
  244. return std::string(PathNameUTF8.data());
  245. }
  246. UniqueID file_status::getUniqueID() const {
  247. // The file is uniquely identified by the volume serial number along
  248. // with the 64-bit file identifier.
  249. uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
  250. static_cast<uint64_t>(FileIndexLow);
  251. return UniqueID(VolumeSerialNumber, FileID);
  252. }
  253. TimeValue file_status::getLastModificationTime() const {
  254. ULARGE_INTEGER UI;
  255. UI.LowPart = LastWriteTimeLow;
  256. UI.HighPart = LastWriteTimeHigh;
  257. TimeValue Ret;
  258. Ret.fromWin32Time(UI.QuadPart);
  259. return Ret;
  260. }
  261. error_code current_path(SmallVectorImpl<char> &result) {
  262. MSFileSystemRef fsr;
  263. if (error_code ec = GetCurrentThreadFileSystemOrError(&fsr)) return ec;
  264. SmallVector<wchar_t, MAX_PATH> cur_path;
  265. DWORD len = MAX_PATH;
  266. do {
  267. cur_path.reserve(len);
  268. len = fsr->GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
  269. // A zero return value indicates a failure other than insufficient space.
  270. if (len == 0)
  271. return mapWindowsError(::GetLastError());
  272. // If there's insufficient space, the len returned is larger than the len
  273. // given.
  274. } while (len > cur_path.capacity());
  275. // On success, GetCurrentDirectoryW returns the number of characters not
  276. // including the null-terminator.
  277. cur_path.set_size(len);
  278. return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
  279. }
  280. std::error_code create_directory(const Twine &path, bool IgnoreExisting) {
  281. MSFileSystemRef fsr;
  282. if (error_code ec = GetCurrentThreadFileSystemOrError(&fsr)) return ec;
  283. SmallString<128> path_storage;
  284. SmallVector<wchar_t, 128> path_utf16;
  285. if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage), path_utf16))
  286. return ec;
  287. if (!fsr->CreateDirectoryW(path_utf16.begin())) {
  288. DWORD LastError = ::GetLastError();
  289. if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
  290. return mapWindowsError(LastError);
  291. }
  292. return std::error_code();
  293. }
  294. // We can't use symbolic links for windows.
  295. std::error_code create_link(const Twine &to, const Twine &from) {
  296. MSFileSystemRef fsr;
  297. if (error_code ec = GetCurrentThreadFileSystemOrError(&fsr)) return ec;
  298. // Convert to utf-16.
  299. SmallVector<wchar_t, 128> wide_from;
  300. SmallVector<wchar_t, 128> wide_to;
  301. if (std::error_code ec = widenPath(from, wide_from))
  302. return ec;
  303. if (std::error_code ec = widenPath(to, wide_to))
  304. return ec;
  305. if (!fsr->CreateHardLinkW(wide_from.begin(), wide_to.begin()))
  306. return mapWindowsError(::GetLastError());
  307. return std::error_code();
  308. }
  309. std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
  310. MSFileSystemRef fsr;
  311. if (error_code ec = GetCurrentThreadFileSystemOrError(&fsr)) return ec;
  312. SmallVector<wchar_t, 128> path_utf16;
  313. file_status ST;
  314. if (std::error_code EC = status(path, ST)) {
  315. if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
  316. return EC;
  317. return std::error_code();
  318. }
  319. if (std::error_code ec = widenPath(path, path_utf16))
  320. return ec;
  321. if (ST.type() == file_type::directory_file) {
  322. if (!fsr->RemoveDirectoryW(c_str(path_utf16))) {
  323. std::error_code EC = mapWindowsError(::GetLastError());
  324. if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
  325. return EC;
  326. }
  327. return std::error_code();
  328. }
  329. if (!fsr->DeleteFileW(c_str(path_utf16))) {
  330. std::error_code EC = mapWindowsError(::GetLastError());
  331. if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
  332. return EC;
  333. }
  334. return std::error_code();
  335. }
  336. error_code rename(const Twine &from, const Twine &to) {
  337. MSFileSystemRef fsr;
  338. if (error_code ec = GetCurrentThreadFileSystemOrError(&fsr)) return ec;
  339. // Get arguments.
  340. SmallString<128> from_storage;
  341. SmallString<128> to_storage;
  342. StringRef f = from.toStringRef(from_storage);
  343. StringRef t = to.toStringRef(to_storage);
  344. // Convert to utf-16.
  345. SmallVector<wchar_t, 128> wide_from;
  346. SmallVector<wchar_t, 128> wide_to;
  347. if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
  348. if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
  349. error_code ec = error_code();
  350. for (int i = 0; i < 2000; i++) {
  351. if (fsr->MoveFileExW(wide_from.begin(), wide_to.begin(),
  352. MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
  353. return error_code();
  354. ec = mapWindowsError(::GetLastError());
  355. if (ec != std::errc::permission_denied)
  356. break;
  357. // Retry MoveFile() at ACCESS_DENIED.
  358. // System scanners (eg. indexer) might open the source file when
  359. // It is written and closed.
  360. ::Sleep(1);
  361. }
  362. return ec;
  363. }
  364. error_code resize_file(const Twine &path, uint64_t size) {
  365. SmallString<128> path_storage;
  366. SmallVector<wchar_t, 128> path_utf16;
  367. MSFileSystemRef fsr;
  368. if (error_code ec = GetCurrentThreadFileSystemOrError(&fsr)) return ec;
  369. if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
  370. path_utf16))
  371. return ec;
  372. return error_code(fsr->resize_file(path_utf16.begin(), size), std::generic_category());
  373. }
  374. error_code exists(const Twine &path, bool &result) {
  375. MSFileSystemRef fsr;
  376. if (error_code ec = GetCurrentThreadFileSystemOrError(&fsr)) return ec;
  377. SmallString<128> path_storage;
  378. SmallVector<wchar_t, 128> path_utf16;
  379. if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
  380. path_utf16))
  381. return ec;
  382. DWORD attributes = fsr->GetFileAttributesW(path_utf16.begin());
  383. if (attributes == INVALID_FILE_ATTRIBUTES) {
  384. // See if the file didn't actually exist.
  385. error_code ec = mapWindowsError(::GetLastError());
  386. if (ec != std::errc::no_such_file_or_directory)
  387. return ec;
  388. result = false;
  389. } else
  390. result = true;
  391. return error_code();
  392. }
  393. std::error_code access(const Twine &Path, AccessMode Mode) {
  394. MSFileSystemRef fsr;
  395. if (error_code ec = GetCurrentThreadFileSystemOrError(&fsr)) return ec;
  396. SmallString<128> PathStorage;
  397. SmallVector<wchar_t, 128> PathUtf16;
  398. StringRef P = Path.toNullTerminatedStringRef(PathStorage);
  399. if (error_code ec = UTF8ToUTF16(P, PathUtf16))
  400. return ec;
  401. DWORD Attr = fsr->GetFileAttributesW(PathUtf16.begin());
  402. // TODO: look at GetLastError as well.
  403. if (Attr == INVALID_FILE_ATTRIBUTES) {
  404. return make_error_code(std::errc::no_such_file_or_directory);
  405. }
  406. switch (Mode) {
  407. case AccessMode::Exist:
  408. case AccessMode::Execute:
  409. // Consider: directories should not be executable.
  410. return std::error_code();
  411. default:
  412. assert(Mode == AccessMode::Write && "no other enum value allowed");
  413. case AccessMode::Write:
  414. return !(Attr & FILE_ATTRIBUTE_READONLY) ?
  415. std::error_code() : make_error_code(std::errc::permission_denied);
  416. }
  417. }
  418. bool equivalent(file_status A, file_status B) {
  419. assert(status_known(A) && status_known(B));
  420. return A.FileIndexHigh == B.FileIndexHigh &&
  421. A.FileIndexLow == B.FileIndexLow &&
  422. A.FileSizeHigh == B.FileSizeHigh &&
  423. A.FileSizeLow == B.FileSizeLow &&
  424. A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
  425. A.LastWriteTimeLow == B.LastWriteTimeLow &&
  426. A.VolumeSerialNumber == B.VolumeSerialNumber;
  427. }
  428. error_code equivalent(const Twine &A, const Twine &B, bool &result) {
  429. file_status fsA, fsB;
  430. if (error_code ec = status(A, fsA)) return ec;
  431. if (error_code ec = status(B, fsB)) return ec;
  432. result = equivalent(fsA, fsB);
  433. return error_code();
  434. }
  435. static bool isReservedName(StringRef path) {
  436. // This list of reserved names comes from MSDN, at:
  437. // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
  438. static const char *sReservedNames[] = { "nul", "con", "prn", "aux",
  439. "com1", "com2", "com3", "com4", "com5", "com6",
  440. "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
  441. "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9" };
  442. // First, check to see if this is a device namespace, which always
  443. // starts with \\.\, since device namespaces are not legal file paths.
  444. if (path.startswith("\\\\.\\"))
  445. return true;
  446. // Then compare against the list of ancient reserved names
  447. for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
  448. if (path.equals_lower(sReservedNames[i]))
  449. return true;
  450. }
  451. // The path isn't what we consider reserved.
  452. return false;
  453. }
  454. static error_code getStatus(HANDLE FileHandle, file_status &Result) {
  455. if (FileHandle == INVALID_HANDLE_VALUE)
  456. goto handle_status_error;
  457. MSFileSystemRef fsr;
  458. if (error_code ec = GetCurrentThreadFileSystemOrError(&fsr)) return ec;
  459. switch (fsr->GetFileType(FileHandle)) {
  460. default:
  461. llvm_unreachable("Don't know anything about this file type");
  462. case FILE_TYPE_UNKNOWN: {
  463. DWORD Err = ::GetLastError();
  464. if (Err != NO_ERROR)
  465. return mapWindowsError(Err);
  466. Result = file_status(file_type::type_unknown);
  467. return error_code();
  468. }
  469. case FILE_TYPE_DISK:
  470. break;
  471. case FILE_TYPE_CHAR:
  472. Result = file_status(file_type::character_file);
  473. return error_code();
  474. case FILE_TYPE_PIPE:
  475. Result = file_status(file_type::fifo_file);
  476. return error_code();
  477. }
  478. BY_HANDLE_FILE_INFORMATION Info;
  479. if (!fsr->GetFileInformationByHandle(FileHandle, &Info))
  480. goto handle_status_error;
  481. {
  482. file_type Type = (Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  483. ? file_type::directory_file
  484. : file_type::regular_file;
  485. Result =
  486. file_status(Type, Info.ftLastWriteTime.dwHighDateTime,
  487. Info.ftLastWriteTime.dwLowDateTime,
  488. Info.dwVolumeSerialNumber, Info.nFileSizeHigh,
  489. Info.nFileSizeLow, Info.nFileIndexHigh, Info.nFileIndexLow);
  490. return error_code();
  491. }
  492. handle_status_error:
  493. error_code EC = mapWindowsError(::GetLastError());
  494. if (EC == std::errc::no_such_file_or_directory)
  495. Result = file_status(file_type::file_not_found);
  496. else
  497. Result = file_status(file_type::status_error);
  498. return EC;
  499. }
  500. error_code status(const Twine &path, file_status &result) {
  501. MSFileSystemRef fsr;
  502. if (error_code ec = GetCurrentThreadFileSystemOrError(&fsr)) return ec;
  503. SmallString<128> path_storage;
  504. SmallVector<wchar_t, 128> path_utf16;
  505. StringRef path8 = path.toStringRef(path_storage);
  506. if (isReservedName(path8)) {
  507. result = file_status(file_type::character_file);
  508. return error_code();
  509. }
  510. if (error_code ec = UTF8ToUTF16(path8, path_utf16))
  511. return ec;
  512. DWORD attr = fsr->GetFileAttributesW(path_utf16.begin());
  513. if (attr == INVALID_FILE_ATTRIBUTES)
  514. return getStatus(INVALID_HANDLE_VALUE, result);
  515. // Handle reparse points.
  516. if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
  517. ScopedFileHandle h(
  518. fsr->CreateFileW(path_utf16.begin(),
  519. 0, // Attributes only.
  520. FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
  521. OPEN_EXISTING,
  522. FILE_FLAG_BACKUP_SEMANTICS));
  523. if (!h)
  524. return getStatus(INVALID_HANDLE_VALUE, result);
  525. }
  526. ScopedFileHandle h(
  527. fsr->CreateFileW(path_utf16.begin(), 0, // Attributes only.
  528. FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
  529. OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS));
  530. if (!h)
  531. return getStatus(INVALID_HANDLE_VALUE, result);
  532. return getStatus(h, result);
  533. }
  534. error_code status(int FD, file_status &Result) {
  535. MSFileSystemRef fsr;
  536. if (error_code ec = GetCurrentThreadFileSystemOrError(&fsr)) return ec;
  537. HANDLE FileHandle = reinterpret_cast<HANDLE>(fsr->get_osfhandle(FD));
  538. return getStatus(FileHandle, Result);
  539. }
  540. error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
  541. MSFileSystemRef fsr;
  542. if (error_code ec = GetCurrentThreadFileSystemOrError(&fsr)) return ec;
  543. ULARGE_INTEGER UI;
  544. UI.QuadPart = Time.toWin32Time();
  545. FILETIME FT;
  546. FT.dwLowDateTime = UI.LowPart;
  547. FT.dwHighDateTime = UI.HighPart;
  548. HANDLE FileHandle = reinterpret_cast<HANDLE>(fsr->get_osfhandle(FD));
  549. if (!fsr->SetFileTime(FileHandle, NULL, &FT, &FT))
  550. return mapWindowsError(::GetLastError());
  551. return error_code();
  552. }
  553. error_code get_magic(const Twine &path, uint32_t len,
  554. SmallVectorImpl<char> &result) {
  555. MSFileSystemRef fsr;
  556. if (error_code ec = GetCurrentThreadFileSystemOrError(&fsr)) return ec;
  557. SmallString<128> path_storage;
  558. SmallVector<wchar_t, 128> path_utf16;
  559. result.set_size(0);
  560. // Convert path to UTF-16.
  561. if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
  562. path_utf16))
  563. return ec;
  564. // Open file.
  565. HANDLE file = fsr->CreateFileW(c_str(path_utf16),
  566. GENERIC_READ,
  567. FILE_SHARE_READ,
  568. OPEN_EXISTING,
  569. FILE_ATTRIBUTE_READONLY);
  570. if (file == INVALID_HANDLE_VALUE)
  571. return mapWindowsError(::GetLastError());
  572. // Allocate buffer.
  573. result.reserve(len);
  574. // Get magic!
  575. DWORD bytes_read = 0;
  576. BOOL read_success = fsr->ReadFile(file, result.data(), len, &bytes_read);
  577. error_code ec = mapWindowsError(::GetLastError());
  578. fsr->CloseHandle(file);
  579. if (!read_success || (bytes_read != len)) {
  580. // Set result size to the number of bytes read if it's valid.
  581. if (bytes_read <= len)
  582. result.set_size(bytes_read);
  583. // ERROR_HANDLE_EOF is mapped to errc::value_too_large.
  584. return ec;
  585. }
  586. result.set_size(len);
  587. return error_code();
  588. }
  589. error_code mapped_file_region::init(int FD, uint64_t Offset, mapmode Mode) {
  590. MSFileSystemRef fsr;
  591. if (error_code ec = GetCurrentThreadFileSystemOrError(&fsr)) return ec;
  592. // Make sure that the requested size fits within SIZE_T.
  593. if (Size > std::numeric_limits<SIZE_T>::max())
  594. return make_error_code(errc::invalid_argument);
  595. HANDLE FileHandle = reinterpret_cast<HANDLE>(fsr->get_osfhandle(FD));
  596. if (FileHandle == INVALID_HANDLE_VALUE)
  597. return make_error_code(errc::bad_file_descriptor);
  598. DWORD flprotect;
  599. switch (Mode) {
  600. case readonly: flprotect = PAGE_READONLY; break;
  601. case readwrite: flprotect = PAGE_READWRITE; break;
  602. case priv: flprotect = PAGE_WRITECOPY; break;
  603. }
  604. HANDLE FileMappingHandle =
  605. fsr->CreateFileMappingW(FileHandle, flprotect,
  606. (Offset + Size) >> 32,
  607. (Offset + Size) & 0xffffffff);
  608. if (FileMappingHandle == NULL) {
  609. std::error_code ec = mapWindowsError(GetLastError());
  610. return ec;
  611. }
  612. DWORD dwDesiredAccess;
  613. switch (Mode) {
  614. case readonly: dwDesiredAccess = FILE_MAP_READ; break;
  615. case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
  616. case priv: dwDesiredAccess = FILE_MAP_COPY; break;
  617. }
  618. Mapping = fsr->MapViewOfFile(FileMappingHandle,
  619. dwDesiredAccess,
  620. Offset >> 32,
  621. Offset & 0xffffffff,
  622. Size);
  623. if (Mapping == NULL) {
  624. std::error_code ec = mapWindowsError(GetLastError());
  625. fsr->CloseHandle(FileMappingHandle);
  626. return ec;
  627. }
  628. if (Size == 0) {
  629. MEMORY_BASIC_INFORMATION mbi;
  630. SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi)); // TODO: do we need to plumb through fsr?
  631. if (Result == 0) {
  632. std::error_code ec = mapWindowsError(GetLastError());
  633. fsr->UnmapViewOfFile(Mapping);
  634. fsr->CloseHandle(FileMappingHandle);
  635. return ec;
  636. }
  637. Size = mbi.RegionSize;
  638. }
  639. // Close all the handles except for the view. It will keep the other handles
  640. // alive.
  641. fsr->CloseHandle(FileMappingHandle);
  642. return std::error_code();
  643. }
  644. mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
  645. uint64_t offset, std::error_code &ec)
  646. : Size(length), Mapping() {
  647. ec = init(fd, offset, mode);
  648. if (ec)
  649. Mapping = 0;
  650. }
  651. mapped_file_region::~mapped_file_region() {
  652. if (Mapping)
  653. GetCurrentThreadFileSystem()->UnmapViewOfFile(Mapping);
  654. }
  655. uint64_t mapped_file_region::size() const {
  656. assert(Mapping && "Mapping failed but used anyway!");
  657. return Size;
  658. }
  659. char *mapped_file_region::data() const {
  660. assert(Mapping && "Mapping failed but used anyway!");
  661. return reinterpret_cast<char*>(Mapping);
  662. }
  663. const char *mapped_file_region::const_data() const {
  664. assert(Mapping && "Mapping failed but used anyway!");
  665. return reinterpret_cast<const char*>(Mapping);
  666. }
  667. int mapped_file_region::alignment() {
  668. SYSTEM_INFO SysInfo;
  669. ::GetSystemInfo(&SysInfo);
  670. return SysInfo.dwAllocationGranularity;
  671. }
  672. error_code detail::directory_iterator_construct(detail::DirIterState &it,
  673. StringRef path) {
  674. MSFileSystemRef fsr;
  675. if (error_code ec = GetCurrentThreadFileSystemOrError(&fsr)) return ec;
  676. SmallVector<wchar_t, 128> path_utf16;
  677. if (error_code ec = UTF8ToUTF16(path,
  678. path_utf16))
  679. return ec;
  680. // Convert path to the format that Windows is happy with.
  681. if (path_utf16.size() > 0 &&
  682. !is_separator(path_utf16[path.size() - 1]) &&
  683. path_utf16[path.size() - 1] != L':') {
  684. path_utf16.push_back(L'\\');
  685. path_utf16.push_back(L'*');
  686. } else {
  687. path_utf16.push_back(L'*');
  688. }
  689. // Get the first directory entry.
  690. WIN32_FIND_DATAW FirstFind;
  691. ScopedFindHandle FindHandle(fsr->FindFirstFileW(c_str(path_utf16), &FirstFind));
  692. if (!FindHandle)
  693. return mapWindowsError(::GetLastError());
  694. size_t FilenameLen = ::wcslen(FirstFind.cFileName);
  695. while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
  696. (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
  697. FirstFind.cFileName[1] == L'.'))
  698. if (!fsr->FindNextFileW(FindHandle, &FirstFind)) {
  699. DWORD lastError = ::GetLastError();
  700. // Check for end.
  701. if (lastError == ERROR_NO_MORE_FILES) // no more files
  702. return detail::directory_iterator_destruct(it);
  703. return mapWindowsError(lastError);
  704. } else
  705. FilenameLen = ::wcslen(FirstFind.cFileName);
  706. // Construct the current directory entry.
  707. SmallString<128> directory_entry_name_utf8;
  708. if (error_code ec = UTF16ToUTF8(FirstFind.cFileName,
  709. ::wcslen(FirstFind.cFileName),
  710. directory_entry_name_utf8))
  711. return ec;
  712. it.IterationHandle = intptr_t(FindHandle.take());
  713. SmallString<128> directory_entry_path(path);
  714. path::append(directory_entry_path, directory_entry_name_utf8.str());
  715. it.CurrentEntry = directory_entry(directory_entry_path.str());
  716. return error_code();
  717. }
  718. error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
  719. if (it.IterationHandle != 0)
  720. // Closes the handle if it's valid.
  721. ScopedFindHandle close(HANDLE(it.IterationHandle));
  722. it.IterationHandle = 0;
  723. it.CurrentEntry = directory_entry();
  724. return error_code();
  725. }
  726. error_code detail::directory_iterator_increment(detail::DirIterState &it) {
  727. MSFileSystemRef fsr;
  728. if (error_code ec = GetCurrentThreadFileSystemOrError(&fsr)) return ec;
  729. WIN32_FIND_DATAW FindData;
  730. if (!fsr->FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
  731. DWORD lastError = ::GetLastError();
  732. // Check for end.
  733. if (lastError == ERROR_NO_MORE_FILES) // no more files
  734. return detail::directory_iterator_destruct(it);
  735. return mapWindowsError(lastError);
  736. }
  737. size_t FilenameLen = ::wcslen(FindData.cFileName);
  738. if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
  739. (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
  740. FindData.cFileName[1] == L'.'))
  741. return directory_iterator_increment(it);
  742. SmallString<128> directory_entry_path_utf8;
  743. if (error_code ec = UTF16ToUTF8(FindData.cFileName,
  744. ::wcslen(FindData.cFileName),
  745. directory_entry_path_utf8))
  746. return ec;
  747. it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
  748. return error_code();
  749. }
  750. error_code openFileForRead(const Twine &Name, int &ResultFD) {
  751. MSFileSystemRef fsr;
  752. if (error_code ec = GetCurrentThreadFileSystemOrError(&fsr)) return ec;
  753. SmallString<128> PathStorage;
  754. SmallVector<wchar_t, 128> PathUTF16;
  755. if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
  756. PathUTF16))
  757. return EC;
  758. HANDLE H = fsr->CreateFileW(PathUTF16.begin(), GENERIC_READ,
  759. FILE_SHARE_READ | FILE_SHARE_WRITE,
  760. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
  761. if (H == INVALID_HANDLE_VALUE) {
  762. DWORD LastError = ::GetLastError();
  763. std::error_code EC = mapWindowsError(LastError);
  764. // Provide a better error message when trying to open directories.
  765. // This only runs if we failed to open the file, so there is probably
  766. // no performances issues.
  767. if (LastError != ERROR_ACCESS_DENIED)
  768. return EC;
  769. if (is_directory(Name))
  770. return make_error_code(errc::is_a_directory);
  771. return EC;
  772. }
  773. int FD = fsr->open_osfhandle(intptr_t(H), 0);
  774. if (FD == -1) {
  775. fsr->CloseHandle(H);
  776. return mapWindowsError(ERROR_INVALID_HANDLE);
  777. }
  778. ResultFD = FD;
  779. return error_code();
  780. }
  781. error_code openFileForWrite(const Twine &Name, int &ResultFD,
  782. sys::fs::OpenFlags Flags, unsigned Mode) {
  783. MSFileSystemRef fsr;
  784. if (error_code ec = GetCurrentThreadFileSystemOrError(&fsr)) return ec;
  785. // Verify that we don't have both "append" and "excl".
  786. assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
  787. "Cannot specify both 'excl' and 'append' file creation flags!");
  788. SmallString<128> PathStorage;
  789. SmallVector<wchar_t, 128> PathUTF16;
  790. if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
  791. PathUTF16))
  792. return EC;
  793. DWORD CreationDisposition;
  794. if (Flags & F_Excl)
  795. CreationDisposition = CREATE_NEW;
  796. else if (Flags & F_Append)
  797. CreationDisposition = OPEN_ALWAYS;
  798. else
  799. CreationDisposition = CREATE_ALWAYS;
  800. HANDLE H = fsr->CreateFileW(PathUTF16.begin(), GENERIC_WRITE,
  801. FILE_SHARE_READ | FILE_SHARE_WRITE,
  802. CreationDisposition, FILE_ATTRIBUTE_NORMAL);
  803. if (H == INVALID_HANDLE_VALUE) {
  804. DWORD LastError = ::GetLastError();
  805. std::error_code EC = mapWindowsError(LastError);
  806. // Provide a better error message when trying to open directories.
  807. // This only runs if we failed to open the file, so there is probably
  808. // no performances issues.
  809. if (LastError != ERROR_ACCESS_DENIED)
  810. return EC;
  811. if (is_directory(Name))
  812. return make_error_code(errc::is_a_directory);
  813. return EC;
  814. }
  815. int OpenFlags = 0;
  816. if (Flags & F_Append)
  817. OpenFlags |= _O_APPEND;
  818. if (Flags & F_Text)
  819. OpenFlags |= _O_TEXT;
  820. int FD = fsr->open_osfhandle(intptr_t(H), OpenFlags);
  821. if (FD == -1) {
  822. fsr->CloseHandle(H);
  823. return mapWindowsError(ERROR_INVALID_HANDLE);
  824. }
  825. ResultFD = FD;
  826. return error_code();
  827. }
  828. } // end namespace fs
  829. namespace path {
  830. void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
  831. (void)ErasedOnReboot;
  832. Result.clear();
  833. MSFileSystemRef fsr;
  834. if (error_code ec = GetCurrentThreadFileSystemOrError(&fsr)) return;
  835. SmallVector<wchar_t, 128> result;
  836. DWORD len;
  837. retry_temp_dir:
  838. len = fsr->GetTempPathW(result.capacity(), result.begin());
  839. if (len == 0)
  840. return; // mapWindowsError(::GetLastError());
  841. if (len > result.capacity()) {
  842. result.reserve(len);
  843. goto retry_temp_dir;
  844. }
  845. result.set_size(len);
  846. UTF16ToUTF8(result.begin(), result.size(), Result);
  847. }
  848. } // end namespace path
  849. namespace windows {
  850. std::error_code ACPToUTF16(llvm::StringRef acp,
  851. llvm::SmallVectorImpl<wchar_t> &utf16) {
  852. int len = ::MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS,
  853. acp.begin(), acp.size(),
  854. utf16.begin(), 0);
  855. if (len == 0)
  856. return mapWindowsError(::GetLastError());
  857. utf16.reserve(len + 1);
  858. utf16.set_size(len);
  859. len = ::MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS,
  860. acp.begin(), acp.size(),
  861. utf16.begin(), utf16.size());
  862. if (len == 0)
  863. return mapWindowsError(::GetLastError());
  864. // Make utf16 null terminated.
  865. utf16.push_back(0);
  866. utf16.pop_back();
  867. return error_code();
  868. }
  869. std::error_code ACPToUTF8(const char *acp, size_t acp_len,
  870. llvm::SmallVectorImpl<char> &utf8) {
  871. llvm::SmallVector<wchar_t, 128> utf16;
  872. std::error_code ec = ACPToUTF16(StringRef(acp, acp_len), utf16);
  873. if (ec) return ec;
  874. return UTF16ToUTF8(utf16.begin(), utf16.size(), utf8);
  875. }
  876. std::error_code UTF8ToUTF16(llvm::StringRef utf8,
  877. llvm::SmallVectorImpl<wchar_t> &utf16) {
  878. int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
  879. utf8.begin(), utf8.size(),
  880. utf16.begin(), 0);
  881. if (len == 0)
  882. return mapWindowsError(::GetLastError());
  883. utf16.reserve(len + 1);
  884. utf16.set_size(len);
  885. len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
  886. utf8.begin(), utf8.size(),
  887. utf16.begin(), utf16.size());
  888. if (len == 0)
  889. return mapWindowsError(::GetLastError());
  890. // Make utf16 null terminated.
  891. utf16.push_back(0);
  892. utf16.pop_back();
  893. return error_code();
  894. }
  895. static
  896. std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
  897. size_t utf16_len,
  898. llvm::SmallVectorImpl<char> &utf8) {
  899. if (utf16_len) {
  900. // Get length.
  901. int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.begin(),
  902. 0, NULL, NULL);
  903. if (len == 0)
  904. return mapWindowsError(::GetLastError());
  905. utf8.reserve(len);
  906. utf8.set_size(len);
  907. // Now do the actual conversion.
  908. len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.data(),
  909. utf8.size(), NULL, NULL);
  910. if (len == 0)
  911. return mapWindowsError(::GetLastError());
  912. }
  913. // Make utf8 null terminated.
  914. utf8.push_back(0);
  915. utf8.pop_back();
  916. return std::error_code();
  917. }
  918. std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
  919. llvm::SmallVectorImpl<char> &utf8) {
  920. return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
  921. }
  922. std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
  923. llvm::SmallVectorImpl<char> &utf8) {
  924. return UTF16ToCodePage(CP_ACP, utf16, utf16_len, utf8);
  925. }
  926. } // end namespace windows
  927. } // end namespace sys
  928. } // end namespace llvm