MSFileSystem.inc.cpp 36 KB

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