MSFileSystem.inc.cpp 34 KB

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