2
0

MSFileSystem.inc.cpp 36 KB

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