Path.inc 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. //===- llvm/Support/Windows/Path.inc - Windows Path Impl --------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the Windows specific implementation of the Path API.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //===----------------------------------------------------------------------===//
  14. //=== WARNING: Implementation here must contain only generic Windows code that
  15. //=== is guaranteed to work on *all* Windows variants.
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/Support/WindowsError.h"
  19. #include <fcntl.h>
  20. #include <io.h>
  21. #include <sys/stat.h>
  22. #include <sys/types.h>
  23. // These two headers must be included last, and make sure shlobj is required
  24. // after Windows.h to make sure it picks up our definition of _WIN32_WINNT
  25. #include "WindowsSupport.h"
  26. // #include <shlobj.h> // HLSL Change - no support for writing to home directory
  27. #undef max
  28. // MinGW doesn't define this.
  29. #ifndef _ERRNO_T_DEFINED
  30. #define _ERRNO_T_DEFINED
  31. typedef int errno_t;
  32. #endif
  33. #if 0 // HLSL Change Starts
  34. #ifdef _MSC_VER
  35. # pragma comment(lib, "advapi32.lib") // This provides CryptAcquireContextW.
  36. #endif
  37. #endif // HLSL Change Ends
  38. using namespace llvm;
  39. using llvm::sys::windows::UTF8ToUTF16;
  40. using llvm::sys::windows::UTF16ToUTF8;
  41. using llvm::sys::path::widenPath;
  42. static bool is_separator(const wchar_t value) {
  43. switch (value) {
  44. case L'\\':
  45. case L'/':
  46. return true;
  47. default:
  48. return false;
  49. }
  50. }
  51. namespace llvm {
  52. namespace sys {
  53. namespace path {
  54. // Convert a UTF-8 path to UTF-16. Also, if the absolute equivalent of the
  55. // path is longer than CreateDirectory can tolerate, make it absolute and
  56. // prefixed by '\\?\'.
  57. std::error_code widenPath(const Twine &Path8,
  58. SmallVectorImpl<wchar_t> &Path16) {
  59. const size_t MaxDirLen = MAX_PATH - 12; // Must leave room for 8.3 filename.
  60. // Several operations would convert Path8 to SmallString; more efficient to
  61. // do it once up front.
  62. SmallString<128> Path8Str;
  63. Path8.toVector(Path8Str);
  64. // If we made this path absolute, how much longer would it get?
  65. size_t CurPathLen;
  66. if (llvm::sys::path::is_absolute(Twine(Path8Str)))
  67. CurPathLen = 0; // No contribution from current_path needed.
  68. else {
  69. CurPathLen = ::GetCurrentDirectoryW(0, NULL);
  70. if (CurPathLen == 0)
  71. return mapWindowsError(::GetLastError());
  72. }
  73. // Would the absolute path be longer than our limit?
  74. if ((Path8Str.size() + CurPathLen) >= MaxDirLen &&
  75. !Path8Str.startswith("\\\\?\\")) {
  76. SmallString<2*MAX_PATH> FullPath("\\\\?\\");
  77. if (CurPathLen) {
  78. SmallString<80> CurPath;
  79. if (std::error_code EC = llvm::sys::fs::current_path(CurPath))
  80. return EC;
  81. FullPath.append(CurPath);
  82. }
  83. // Traverse the requested path, canonicalizing . and .. as we go (because
  84. // the \\?\ prefix is documented to treat them as real components).
  85. // The iterators don't report separators and append() always attaches
  86. // preferred_separator so we don't need to call native() on the result.
  87. for (llvm::sys::path::const_iterator I = llvm::sys::path::begin(Path8Str),
  88. E = llvm::sys::path::end(Path8Str);
  89. I != E; ++I) {
  90. if (I->size() == 1 && *I == ".")
  91. continue;
  92. if (I->size() == 2 && *I == "..")
  93. llvm::sys::path::remove_filename(FullPath);
  94. else
  95. llvm::sys::path::append(FullPath, *I);
  96. }
  97. return UTF8ToUTF16(FullPath, Path16);
  98. }
  99. // Just use the caller's original path.
  100. return UTF8ToUTF16(Path8Str, Path16);
  101. }
  102. } // end namespace path
  103. namespace fs {
  104. std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
  105. SmallVector<wchar_t, MAX_PATH> PathName;
  106. DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
  107. // A zero return value indicates a failure other than insufficient space.
  108. if (Size == 0)
  109. return "";
  110. // Insufficient space is determined by a return value equal to the size of
  111. // the buffer passed in.
  112. if (Size == PathName.capacity())
  113. return "";
  114. // On success, GetModuleFileNameW returns the number of characters written to
  115. // the buffer not including the NULL terminator.
  116. PathName.set_size(Size);
  117. // Convert the result from UTF-16 to UTF-8.
  118. SmallVector<char, MAX_PATH> PathNameUTF8;
  119. if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
  120. return "";
  121. return std::string(PathNameUTF8.data());
  122. }
  123. UniqueID file_status::getUniqueID() const {
  124. // The file is uniquely identified by the volume serial number along
  125. // with the 64-bit file identifier.
  126. uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
  127. static_cast<uint64_t>(FileIndexLow);
  128. return UniqueID(VolumeSerialNumber, FileID);
  129. }
  130. TimeValue file_status::getLastModificationTime() const {
  131. ULARGE_INTEGER UI;
  132. UI.LowPart = LastWriteTimeLow;
  133. UI.HighPart = LastWriteTimeHigh;
  134. TimeValue Ret;
  135. Ret.fromWin32Time(UI.QuadPart);
  136. return Ret;
  137. }
  138. std::error_code current_path(SmallVectorImpl<char> &result) {
  139. SmallVector<wchar_t, MAX_PATH> cur_path;
  140. DWORD len = MAX_PATH;
  141. do {
  142. cur_path.reserve(len);
  143. len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
  144. // A zero return value indicates a failure other than insufficient space.
  145. if (len == 0)
  146. return mapWindowsError(::GetLastError());
  147. // If there's insufficient space, the len returned is larger than the len
  148. // given.
  149. } while (len > cur_path.capacity());
  150. // On success, GetCurrentDirectoryW returns the number of characters not
  151. // including the null-terminator.
  152. cur_path.set_size(len);
  153. return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
  154. }
  155. std::error_code create_directory(const Twine &path, bool IgnoreExisting) {
  156. SmallVector<wchar_t, 128> path_utf16;
  157. if (std::error_code ec = widenPath(path, path_utf16))
  158. return ec;
  159. if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
  160. DWORD LastError = ::GetLastError();
  161. if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
  162. return mapWindowsError(LastError);
  163. }
  164. return std::error_code();
  165. }
  166. // We can't use symbolic links for windows.
  167. std::error_code create_link(const Twine &to, const Twine &from) {
  168. // Convert to utf-16.
  169. SmallVector<wchar_t, 128> wide_from;
  170. SmallVector<wchar_t, 128> wide_to;
  171. if (std::error_code ec = widenPath(from, wide_from))
  172. return ec;
  173. if (std::error_code ec = widenPath(to, wide_to))
  174. return ec;
  175. if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
  176. return mapWindowsError(::GetLastError());
  177. return std::error_code();
  178. }
  179. std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
  180. SmallVector<wchar_t, 128> path_utf16;
  181. file_status ST;
  182. if (std::error_code EC = status(path, ST)) {
  183. if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
  184. return EC;
  185. return std::error_code();
  186. }
  187. if (std::error_code ec = widenPath(path, path_utf16))
  188. return ec;
  189. if (ST.type() == file_type::directory_file) {
  190. if (!::RemoveDirectoryW(c_str(path_utf16))) {
  191. std::error_code EC = mapWindowsError(::GetLastError());
  192. if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
  193. return EC;
  194. }
  195. return std::error_code();
  196. }
  197. if (!::DeleteFileW(c_str(path_utf16))) {
  198. std::error_code EC = mapWindowsError(::GetLastError());
  199. if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
  200. return EC;
  201. }
  202. return std::error_code();
  203. }
  204. std::error_code rename(const Twine &from, const Twine &to) {
  205. // Convert to utf-16.
  206. SmallVector<wchar_t, 128> wide_from;
  207. SmallVector<wchar_t, 128> wide_to;
  208. if (std::error_code ec = widenPath(from, wide_from))
  209. return ec;
  210. if (std::error_code ec = widenPath(to, wide_to))
  211. return ec;
  212. std::error_code ec = std::error_code();
  213. for (int i = 0; i < 2000; i++) {
  214. if (::MoveFileExW(wide_from.begin(), wide_to.begin(),
  215. MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
  216. return std::error_code();
  217. DWORD LastError = ::GetLastError();
  218. ec = mapWindowsError(LastError);
  219. if (LastError != ERROR_ACCESS_DENIED)
  220. break;
  221. // Retry MoveFile() at ACCESS_DENIED.
  222. // System scanners (eg. indexer) might open the source file when
  223. // It is written and closed.
  224. ::Sleep(1);
  225. }
  226. return ec;
  227. }
  228. std::error_code resize_file(int FD, uint64_t Size) {
  229. #ifdef HAVE__CHSIZE_S
  230. errno_t error = ::_chsize_s(FD, Size);
  231. #else
  232. errno_t error = ::_chsize(FD, Size);
  233. #endif
  234. return std::error_code(error, std::generic_category());
  235. }
  236. std::error_code access(const Twine &Path, AccessMode Mode) {
  237. SmallVector<wchar_t, 128> PathUtf16;
  238. if (std::error_code EC = widenPath(Path, PathUtf16))
  239. return EC;
  240. DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
  241. if (Attributes == INVALID_FILE_ATTRIBUTES) {
  242. // See if the file didn't actually exist.
  243. DWORD LastError = ::GetLastError();
  244. if (LastError != ERROR_FILE_NOT_FOUND &&
  245. LastError != ERROR_PATH_NOT_FOUND)
  246. return mapWindowsError(LastError);
  247. return errc::no_such_file_or_directory;
  248. }
  249. if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
  250. return errc::permission_denied;
  251. return std::error_code();
  252. }
  253. bool equivalent(file_status A, file_status B) {
  254. assert(status_known(A) && status_known(B));
  255. return A.FileIndexHigh == B.FileIndexHigh &&
  256. A.FileIndexLow == B.FileIndexLow &&
  257. A.FileSizeHigh == B.FileSizeHigh &&
  258. A.FileSizeLow == B.FileSizeLow &&
  259. A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
  260. A.LastWriteTimeLow == B.LastWriteTimeLow &&
  261. A.VolumeSerialNumber == B.VolumeSerialNumber;
  262. }
  263. std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
  264. file_status fsA, fsB;
  265. if (std::error_code ec = status(A, fsA))
  266. return ec;
  267. if (std::error_code ec = status(B, fsB))
  268. return ec;
  269. result = equivalent(fsA, fsB);
  270. return std::error_code();
  271. }
  272. static bool isReservedName(StringRef path) {
  273. // This list of reserved names comes from MSDN, at:
  274. // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
  275. static const char *sReservedNames[] = { "nul", "con", "prn", "aux",
  276. "com1", "com2", "com3", "com4", "com5", "com6",
  277. "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
  278. "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9" };
  279. // First, check to see if this is a device namespace, which always
  280. // starts with \\.\, since device namespaces are not legal file paths.
  281. if (path.startswith("\\\\.\\"))
  282. return true;
  283. // Then compare against the list of ancient reserved names
  284. for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
  285. if (path.equals_lower(sReservedNames[i]))
  286. return true;
  287. }
  288. // The path isn't what we consider reserved.
  289. return false;
  290. }
  291. static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
  292. if (FileHandle == INVALID_HANDLE_VALUE)
  293. goto handle_status_error;
  294. switch (::GetFileType(FileHandle)) {
  295. default:
  296. llvm_unreachable("Don't know anything about this file type");
  297. case FILE_TYPE_UNKNOWN: {
  298. DWORD Err = ::GetLastError();
  299. if (Err != NO_ERROR)
  300. return mapWindowsError(Err);
  301. Result = file_status(file_type::type_unknown);
  302. return std::error_code();
  303. }
  304. case FILE_TYPE_DISK:
  305. break;
  306. case FILE_TYPE_CHAR:
  307. Result = file_status(file_type::character_file);
  308. return std::error_code();
  309. case FILE_TYPE_PIPE:
  310. Result = file_status(file_type::fifo_file);
  311. return std::error_code();
  312. }
  313. BY_HANDLE_FILE_INFORMATION Info;
  314. if (!::GetFileInformationByHandle(FileHandle, &Info))
  315. goto handle_status_error;
  316. {
  317. file_type Type = (Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  318. ? file_type::directory_file
  319. : file_type::regular_file;
  320. Result =
  321. file_status(Type, Info.ftLastWriteTime.dwHighDateTime,
  322. Info.ftLastWriteTime.dwLowDateTime,
  323. Info.dwVolumeSerialNumber, Info.nFileSizeHigh,
  324. Info.nFileSizeLow, Info.nFileIndexHigh, Info.nFileIndexLow);
  325. return std::error_code();
  326. }
  327. handle_status_error:
  328. DWORD LastError = ::GetLastError();
  329. if (LastError == ERROR_FILE_NOT_FOUND ||
  330. LastError == ERROR_PATH_NOT_FOUND)
  331. Result = file_status(file_type::file_not_found);
  332. else if (LastError == ERROR_SHARING_VIOLATION)
  333. Result = file_status(file_type::type_unknown);
  334. else
  335. Result = file_status(file_type::status_error);
  336. return mapWindowsError(LastError);
  337. }
  338. std::error_code status(const Twine &path, file_status &result) {
  339. SmallString<128> path_storage;
  340. SmallVector<wchar_t, 128> path_utf16;
  341. StringRef path8 = path.toStringRef(path_storage);
  342. if (isReservedName(path8)) {
  343. result = file_status(file_type::character_file);
  344. return std::error_code();
  345. }
  346. if (std::error_code ec = widenPath(path8, path_utf16))
  347. return ec;
  348. DWORD attr = ::GetFileAttributesW(path_utf16.begin());
  349. if (attr == INVALID_FILE_ATTRIBUTES)
  350. return getStatus(INVALID_HANDLE_VALUE, result);
  351. // Handle reparse points.
  352. if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
  353. ScopedFileHandle h(
  354. ::CreateFileW(path_utf16.begin(),
  355. 0, // Attributes only.
  356. FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
  357. NULL,
  358. OPEN_EXISTING,
  359. FILE_FLAG_BACKUP_SEMANTICS,
  360. 0));
  361. if (!h)
  362. return getStatus(INVALID_HANDLE_VALUE, result);
  363. }
  364. ScopedFileHandle h(
  365. ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
  366. FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
  367. NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0));
  368. if (!h)
  369. return getStatus(INVALID_HANDLE_VALUE, result);
  370. return getStatus(h, result);
  371. }
  372. std::error_code status(int FD, file_status &Result) {
  373. HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
  374. return getStatus(FileHandle, Result);
  375. }
  376. std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
  377. ULARGE_INTEGER UI;
  378. UI.QuadPart = Time.toWin32Time();
  379. FILETIME FT;
  380. FT.dwLowDateTime = UI.LowPart;
  381. FT.dwHighDateTime = UI.HighPart;
  382. HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
  383. if (!SetFileTime(FileHandle, NULL, &FT, &FT))
  384. return mapWindowsError(::GetLastError());
  385. return std::error_code();
  386. }
  387. std::error_code mapped_file_region::init(int FD, uint64_t Offset,
  388. mapmode Mode) {
  389. // Make sure that the requested size fits within SIZE_T.
  390. if (Size > std::numeric_limits<SIZE_T>::max())
  391. return make_error_code(errc::invalid_argument);
  392. HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
  393. if (FileHandle == INVALID_HANDLE_VALUE)
  394. return make_error_code(errc::bad_file_descriptor);
  395. DWORD flprotect;
  396. switch (Mode) {
  397. case readonly: flprotect = PAGE_READONLY; break;
  398. case readwrite: flprotect = PAGE_READWRITE; break;
  399. case priv: flprotect = PAGE_WRITECOPY; break;
  400. }
  401. HANDLE FileMappingHandle =
  402. ::CreateFileMappingW(FileHandle, 0, flprotect,
  403. (Offset + Size) >> 32,
  404. (Offset + Size) & 0xffffffff,
  405. 0);
  406. if (FileMappingHandle == NULL) {
  407. std::error_code ec = mapWindowsError(GetLastError());
  408. return ec;
  409. }
  410. DWORD dwDesiredAccess;
  411. switch (Mode) {
  412. case readonly: dwDesiredAccess = FILE_MAP_READ; break;
  413. case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
  414. case priv: dwDesiredAccess = FILE_MAP_COPY; break;
  415. }
  416. Mapping = ::MapViewOfFile(FileMappingHandle,
  417. dwDesiredAccess,
  418. Offset >> 32,
  419. Offset & 0xffffffff,
  420. Size);
  421. if (Mapping == NULL) {
  422. std::error_code ec = mapWindowsError(GetLastError());
  423. ::CloseHandle(FileMappingHandle);
  424. return ec;
  425. }
  426. if (Size == 0) {
  427. MEMORY_BASIC_INFORMATION mbi;
  428. SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
  429. if (Result == 0) {
  430. std::error_code ec = mapWindowsError(GetLastError());
  431. ::UnmapViewOfFile(Mapping);
  432. ::CloseHandle(FileMappingHandle);
  433. return ec;
  434. }
  435. Size = mbi.RegionSize;
  436. }
  437. // Close all the handles except for the view. It will keep the other handles
  438. // alive.
  439. ::CloseHandle(FileMappingHandle);
  440. return std::error_code();
  441. }
  442. mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
  443. uint64_t offset, std::error_code &ec)
  444. : Size(length), Mapping() {
  445. ec = init(fd, offset, mode);
  446. if (ec)
  447. Mapping = 0;
  448. }
  449. mapped_file_region::~mapped_file_region() {
  450. if (Mapping)
  451. ::UnmapViewOfFile(Mapping);
  452. }
  453. uint64_t mapped_file_region::size() const {
  454. assert(Mapping && "Mapping failed but used anyway!");
  455. return Size;
  456. }
  457. char *mapped_file_region::data() const {
  458. assert(Mapping && "Mapping failed but used anyway!");
  459. return reinterpret_cast<char*>(Mapping);
  460. }
  461. const char *mapped_file_region::const_data() const {
  462. assert(Mapping && "Mapping failed but used anyway!");
  463. return reinterpret_cast<const char*>(Mapping);
  464. }
  465. int mapped_file_region::alignment() {
  466. SYSTEM_INFO SysInfo;
  467. ::GetSystemInfo(&SysInfo);
  468. return SysInfo.dwAllocationGranularity;
  469. }
  470. std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
  471. StringRef path){
  472. SmallVector<wchar_t, 128> path_utf16;
  473. if (std::error_code ec = widenPath(path, path_utf16))
  474. return ec;
  475. // Convert path to the format that Windows is happy with.
  476. if (path_utf16.size() > 0 &&
  477. !is_separator(path_utf16[path.size() - 1]) &&
  478. path_utf16[path.size() - 1] != L':') {
  479. path_utf16.push_back(L'\\');
  480. path_utf16.push_back(L'*');
  481. } else {
  482. path_utf16.push_back(L'*');
  483. }
  484. // Get the first directory entry.
  485. WIN32_FIND_DATAW FirstFind;
  486. ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
  487. if (!FindHandle)
  488. return mapWindowsError(::GetLastError());
  489. size_t FilenameLen = ::wcslen(FirstFind.cFileName);
  490. while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
  491. (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
  492. FirstFind.cFileName[1] == L'.'))
  493. if (!::FindNextFileW(FindHandle, &FirstFind)) {
  494. DWORD LastError = ::GetLastError();
  495. // Check for end.
  496. if (LastError == ERROR_NO_MORE_FILES)
  497. return detail::directory_iterator_destruct(it);
  498. return mapWindowsError(LastError);
  499. } else
  500. FilenameLen = ::wcslen(FirstFind.cFileName);
  501. // Construct the current directory entry.
  502. SmallString<128> directory_entry_name_utf8;
  503. if (std::error_code ec =
  504. UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
  505. directory_entry_name_utf8))
  506. return ec;
  507. it.IterationHandle = intptr_t(FindHandle.take());
  508. SmallString<128> directory_entry_path(path);
  509. path::append(directory_entry_path, directory_entry_name_utf8);
  510. it.CurrentEntry = directory_entry(directory_entry_path);
  511. return std::error_code();
  512. }
  513. std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
  514. if (it.IterationHandle != 0)
  515. // Closes the handle if it's valid.
  516. ScopedFindHandle close(HANDLE(it.IterationHandle));
  517. it.IterationHandle = 0;
  518. it.CurrentEntry = directory_entry();
  519. return std::error_code();
  520. }
  521. std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
  522. WIN32_FIND_DATAW FindData;
  523. if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
  524. DWORD LastError = ::GetLastError();
  525. // Check for end.
  526. if (LastError == ERROR_NO_MORE_FILES)
  527. return detail::directory_iterator_destruct(it);
  528. return mapWindowsError(LastError);
  529. }
  530. size_t FilenameLen = ::wcslen(FindData.cFileName);
  531. if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
  532. (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
  533. FindData.cFileName[1] == L'.'))
  534. return directory_iterator_increment(it);
  535. SmallString<128> directory_entry_path_utf8;
  536. if (std::error_code ec =
  537. UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
  538. directory_entry_path_utf8))
  539. return ec;
  540. it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
  541. return std::error_code();
  542. }
  543. std::error_code openFileForRead(const Twine &Name, int &ResultFD) {
  544. SmallVector<wchar_t, 128> PathUTF16;
  545. if (std::error_code EC = widenPath(Name, PathUTF16))
  546. return EC;
  547. HANDLE H = ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
  548. FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
  549. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  550. if (H == INVALID_HANDLE_VALUE) {
  551. DWORD LastError = ::GetLastError();
  552. std::error_code EC = mapWindowsError(LastError);
  553. // Provide a better error message when trying to open directories.
  554. // This only runs if we failed to open the file, so there is probably
  555. // no performances issues.
  556. if (LastError != ERROR_ACCESS_DENIED)
  557. return EC;
  558. if (is_directory(Name))
  559. return make_error_code(errc::is_a_directory);
  560. return EC;
  561. }
  562. int FD = ::_open_osfhandle(intptr_t(H), 0);
  563. if (FD == -1) {
  564. ::CloseHandle(H);
  565. return mapWindowsError(ERROR_INVALID_HANDLE);
  566. }
  567. ResultFD = FD;
  568. return std::error_code();
  569. }
  570. std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
  571. sys::fs::OpenFlags Flags, unsigned Mode) {
  572. // Verify that we don't have both "append" and "excl".
  573. assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
  574. "Cannot specify both 'excl' and 'append' file creation flags!");
  575. SmallVector<wchar_t, 128> PathUTF16;
  576. if (std::error_code EC = widenPath(Name, PathUTF16))
  577. return EC;
  578. DWORD CreationDisposition;
  579. if (Flags & F_Excl)
  580. CreationDisposition = CREATE_NEW;
  581. else if (Flags & F_Append)
  582. CreationDisposition = OPEN_ALWAYS;
  583. else
  584. CreationDisposition = CREATE_ALWAYS;
  585. DWORD Access = GENERIC_WRITE;
  586. if (Flags & F_RW)
  587. Access |= GENERIC_READ;
  588. HANDLE H = ::CreateFileW(PathUTF16.begin(), Access,
  589. FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
  590. CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
  591. if (H == INVALID_HANDLE_VALUE) {
  592. DWORD LastError = ::GetLastError();
  593. std::error_code EC = mapWindowsError(LastError);
  594. // Provide a better error message when trying to open directories.
  595. // This only runs if we failed to open the file, so there is probably
  596. // no performances issues.
  597. if (LastError != ERROR_ACCESS_DENIED)
  598. return EC;
  599. if (is_directory(Name))
  600. return make_error_code(errc::is_a_directory);
  601. return EC;
  602. }
  603. int OpenFlags = 0;
  604. if (Flags & F_Append)
  605. OpenFlags |= _O_APPEND;
  606. if (Flags & F_Text)
  607. OpenFlags |= _O_TEXT;
  608. int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
  609. if (FD == -1) {
  610. ::CloseHandle(H);
  611. return mapWindowsError(ERROR_INVALID_HANDLE);
  612. }
  613. ResultFD = FD;
  614. return std::error_code();
  615. }
  616. } // end namespace fs
  617. namespace path {
  618. bool home_directory(SmallVectorImpl<char> &result) {
  619. #if 0 // HLSL Change Starts
  620. wchar_t Path[MAX_PATH];
  621. if (::SHGetFolderPathW(0, CSIDL_APPDATA | CSIDL_FLAG_CREATE, 0,
  622. /*SHGFP_TYPE_CURRENT*/0, Path) != S_OK)
  623. return false;
  624. if (UTF16ToUTF8(Path, ::wcslen(Path), result))
  625. return false;
  626. return true;
  627. #else
  628. return false;
  629. #endif // HLSL Change Ends
  630. }
  631. static bool getTempDirEnvVar(const char *Var, SmallVectorImpl<char> &Res) {
  632. SmallVector<wchar_t, 128> NameUTF16;
  633. if (windows::UTF8ToUTF16(Var, NameUTF16))
  634. return false;
  635. SmallVector<wchar_t, 1024> Buf;
  636. size_t Size = 1024;
  637. do {
  638. Buf.reserve(Size);
  639. Size =
  640. GetEnvironmentVariableW(NameUTF16.data(), Buf.data(), Buf.capacity());
  641. if (Size == 0)
  642. return false;
  643. // Try again with larger buffer.
  644. } while (Size > Buf.capacity());
  645. Buf.set_size(Size);
  646. if (windows::UTF16ToUTF8(Buf.data(), Size, Res))
  647. return false;
  648. return true;
  649. }
  650. static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
  651. const char *EnvironmentVariables[] = {"TMP", "TEMP", "USERPROFILE"};
  652. for (const char *Env : EnvironmentVariables) {
  653. if (getTempDirEnvVar(Env, Res))
  654. return true;
  655. }
  656. return false;
  657. }
  658. void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
  659. (void)ErasedOnReboot;
  660. Result.clear();
  661. // Check whether the temporary directory is specified by an environment
  662. // variable.
  663. if (getTempDirEnvVar(Result))
  664. return;
  665. // Fall back to a system default.
  666. const char *DefaultResult = "C:\\TEMP";
  667. Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
  668. }
  669. } // end namespace path
  670. namespace windows {
  671. std::error_code UTF8ToUTF16(llvm::StringRef utf8,
  672. llvm::SmallVectorImpl<wchar_t> &utf16) {
  673. if (!utf8.empty()) {
  674. int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
  675. utf8.size(), utf16.begin(), 0);
  676. if (len == 0)
  677. return mapWindowsError(::GetLastError());
  678. utf16.reserve(len + 1);
  679. utf16.set_size(len);
  680. len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
  681. utf8.size(), utf16.begin(), utf16.size());
  682. if (len == 0)
  683. return mapWindowsError(::GetLastError());
  684. }
  685. // Make utf16 null terminated.
  686. utf16.push_back(0);
  687. utf16.pop_back();
  688. return std::error_code();
  689. }
  690. static
  691. std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
  692. size_t utf16_len,
  693. llvm::SmallVectorImpl<char> &utf8) {
  694. if (utf16_len) {
  695. // Get length.
  696. int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.begin(),
  697. 0, NULL, NULL);
  698. if (len == 0)
  699. return mapWindowsError(::GetLastError());
  700. utf8.reserve(len);
  701. utf8.set_size(len);
  702. // Now do the actual conversion.
  703. len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.data(),
  704. utf8.size(), NULL, NULL);
  705. if (len == 0)
  706. return mapWindowsError(::GetLastError());
  707. }
  708. // Make utf8 null terminated.
  709. utf8.push_back(0);
  710. utf8.pop_back();
  711. return std::error_code();
  712. }
  713. std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
  714. llvm::SmallVectorImpl<char> &utf8) {
  715. return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
  716. }
  717. std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
  718. llvm::SmallVectorImpl<char> &utf8) {
  719. return UTF16ToCodePage(CP_ACP, utf16, utf16_len, utf8);
  720. }
  721. } // end namespace windows
  722. } // end namespace sys
  723. } // end namespace llvm