Path.inc 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582
  1. //===- llvm/Support/Windows/Path.inc - Windows Path Impl --------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the Windows specific implementation of the Path API.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. //===----------------------------------------------------------------------===//
  13. //=== WARNING: Implementation here must contain only generic Windows code that
  14. //=== is guaranteed to work on *all* Windows variants.
  15. //===----------------------------------------------------------------------===//
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/Support/ConvertUTF.h"
  18. #include "llvm/Support/WindowsError.h"
  19. #include <fcntl.h>
  20. #include <sys/stat.h>
  21. #include <sys/types.h>
  22. // These two headers must be included last, and make sure shlobj is required
  23. // after Windows.h to make sure it picks up our definition of _WIN32_WINNT
  24. #include "llvm/Support/Windows/WindowsSupport.h"
  25. #include <shellapi.h>
  26. #include <shlobj.h>
  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. #ifdef _MSC_VER
  34. # pragma comment(lib, "advapi32.lib") // This provides CryptAcquireContextW.
  35. # pragma comment(lib, "ole32.lib") // This provides CoTaskMemFree
  36. #endif
  37. using namespace llvm;
  38. using llvm::sys::windows::UTF8ToUTF16;
  39. using llvm::sys::windows::CurCPToUTF16;
  40. using llvm::sys::windows::UTF16ToUTF8;
  41. using llvm::sys::windows::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 windows {
  54. // Convert a UTF-8 path to UTF-16. Also, if the absolute equivalent of the path
  55. // is longer than the limit that the Win32 Unicode File API can tolerate, make
  56. // it an absolute normalized path prefixed by '\\?\'.
  57. std::error_code widenPath(const Twine &Path8, SmallVectorImpl<wchar_t> &Path16,
  58. size_t MaxPathLen) {
  59. assert(MaxPathLen <= MAX_PATH);
  60. // Several operations would convert Path8 to SmallString; more efficient to do
  61. // it once up front.
  62. SmallString<MAX_PATH> Path8Str;
  63. Path8.toVector(Path8Str);
  64. // If the path is a long path, mangled into forward slashes, normalize
  65. // back to backslashes here.
  66. if (Path8Str.startswith("//?/"))
  67. llvm::sys::path::native(Path8Str, path::Style::windows_backslash);
  68. if (std::error_code EC = UTF8ToUTF16(Path8Str, Path16))
  69. return EC;
  70. const bool IsAbsolute = llvm::sys::path::is_absolute(Path8);
  71. size_t CurPathLen;
  72. if (IsAbsolute)
  73. CurPathLen = 0; // No contribution from current_path needed.
  74. else {
  75. CurPathLen = ::GetCurrentDirectoryW(
  76. 0, NULL); // Returns the size including the null terminator.
  77. if (CurPathLen == 0)
  78. return mapWindowsError(::GetLastError());
  79. }
  80. const char *const LongPathPrefix = "\\\\?\\";
  81. if ((Path16.size() + CurPathLen) < MaxPathLen ||
  82. Path8Str.startswith(LongPathPrefix))
  83. return std::error_code();
  84. if (!IsAbsolute) {
  85. if (std::error_code EC = llvm::sys::fs::make_absolute(Path8Str))
  86. return EC;
  87. }
  88. // Remove '.' and '..' because long paths treat these as real path components.
  89. // Explicitly use the backslash form here, as we're prepending the \\?\
  90. // prefix.
  91. llvm::sys::path::native(Path8Str, path::Style::windows);
  92. llvm::sys::path::remove_dots(Path8Str, true, path::Style::windows);
  93. const StringRef RootName = llvm::sys::path::root_name(Path8Str);
  94. assert(!RootName.empty() &&
  95. "Root name cannot be empty for an absolute path!");
  96. SmallString<2 * MAX_PATH> FullPath(LongPathPrefix);
  97. if (RootName[1] != ':') { // Check if UNC.
  98. FullPath.append("UNC\\");
  99. FullPath.append(Path8Str.begin() + 2, Path8Str.end());
  100. } else
  101. FullPath.append(Path8Str);
  102. return UTF8ToUTF16(FullPath, Path16);
  103. }
  104. } // end namespace windows
  105. namespace fs {
  106. const file_t kInvalidFile = INVALID_HANDLE_VALUE;
  107. std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
  108. SmallVector<wchar_t, MAX_PATH> PathName;
  109. PathName.resize_for_overwrite(PathName.capacity());
  110. DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.size());
  111. // A zero return value indicates a failure other than insufficient space.
  112. if (Size == 0)
  113. return "";
  114. // Insufficient space is determined by a return value equal to the size of
  115. // the buffer passed in.
  116. if (Size == PathName.capacity())
  117. return "";
  118. // On success, GetModuleFileNameW returns the number of characters written to
  119. // the buffer not including the NULL terminator.
  120. PathName.truncate(Size);
  121. // Convert the result from UTF-16 to UTF-8.
  122. SmallVector<char, MAX_PATH> PathNameUTF8;
  123. if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
  124. return "";
  125. llvm::sys::path::make_preferred(PathNameUTF8);
  126. return std::string(PathNameUTF8.data());
  127. }
  128. UniqueID file_status::getUniqueID() const {
  129. // The file is uniquely identified by the volume serial number along
  130. // with the 64-bit file identifier.
  131. uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
  132. static_cast<uint64_t>(FileIndexLow);
  133. return UniqueID(VolumeSerialNumber, FileID);
  134. }
  135. ErrorOr<space_info> disk_space(const Twine &Path) {
  136. ULARGE_INTEGER Avail, Total, Free;
  137. if (!::GetDiskFreeSpaceExA(Path.str().c_str(), &Avail, &Total, &Free))
  138. return mapWindowsError(::GetLastError());
  139. space_info SpaceInfo;
  140. SpaceInfo.capacity =
  141. (static_cast<uint64_t>(Total.HighPart) << 32) + Total.LowPart;
  142. SpaceInfo.free = (static_cast<uint64_t>(Free.HighPart) << 32) + Free.LowPart;
  143. SpaceInfo.available =
  144. (static_cast<uint64_t>(Avail.HighPart) << 32) + Avail.LowPart;
  145. return SpaceInfo;
  146. }
  147. TimePoint<> basic_file_status::getLastAccessedTime() const {
  148. FILETIME Time;
  149. Time.dwLowDateTime = LastAccessedTimeLow;
  150. Time.dwHighDateTime = LastAccessedTimeHigh;
  151. return toTimePoint(Time);
  152. }
  153. TimePoint<> basic_file_status::getLastModificationTime() const {
  154. FILETIME Time;
  155. Time.dwLowDateTime = LastWriteTimeLow;
  156. Time.dwHighDateTime = LastWriteTimeHigh;
  157. return toTimePoint(Time);
  158. }
  159. uint32_t file_status::getLinkCount() const {
  160. return NumLinks;
  161. }
  162. std::error_code current_path(SmallVectorImpl<char> &result) {
  163. SmallVector<wchar_t, MAX_PATH> cur_path;
  164. DWORD len = MAX_PATH;
  165. do {
  166. cur_path.resize_for_overwrite(len);
  167. len = ::GetCurrentDirectoryW(cur_path.size(), cur_path.data());
  168. // A zero return value indicates a failure other than insufficient space.
  169. if (len == 0)
  170. return mapWindowsError(::GetLastError());
  171. // If there's insufficient space, the len returned is larger than the len
  172. // given.
  173. } while (len > cur_path.size());
  174. // On success, GetCurrentDirectoryW returns the number of characters not
  175. // including the null-terminator.
  176. cur_path.truncate(len);
  177. if (std::error_code EC =
  178. UTF16ToUTF8(cur_path.begin(), cur_path.size(), result))
  179. return EC;
  180. llvm::sys::path::make_preferred(result);
  181. return std::error_code();
  182. }
  183. std::error_code set_current_path(const Twine &path) {
  184. // Convert to utf-16.
  185. SmallVector<wchar_t, 128> wide_path;
  186. if (std::error_code ec = widenPath(path, wide_path))
  187. return ec;
  188. if (!::SetCurrentDirectoryW(wide_path.begin()))
  189. return mapWindowsError(::GetLastError());
  190. return std::error_code();
  191. }
  192. std::error_code create_directory(const Twine &path, bool IgnoreExisting,
  193. perms Perms) {
  194. SmallVector<wchar_t, 128> path_utf16;
  195. // CreateDirectoryW has a lower maximum path length as it must leave room for
  196. // an 8.3 filename.
  197. if (std::error_code ec = widenPath(path, path_utf16, MAX_PATH - 12))
  198. return ec;
  199. if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
  200. DWORD LastError = ::GetLastError();
  201. if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
  202. return mapWindowsError(LastError);
  203. }
  204. return std::error_code();
  205. }
  206. // We can't use symbolic links for windows.
  207. std::error_code create_link(const Twine &to, const Twine &from) {
  208. // Convert to utf-16.
  209. SmallVector<wchar_t, 128> wide_from;
  210. SmallVector<wchar_t, 128> wide_to;
  211. if (std::error_code ec = widenPath(from, wide_from))
  212. return ec;
  213. if (std::error_code ec = widenPath(to, wide_to))
  214. return ec;
  215. if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
  216. return mapWindowsError(::GetLastError());
  217. return std::error_code();
  218. }
  219. std::error_code create_hard_link(const Twine &to, const Twine &from) {
  220. return create_link(to, from);
  221. }
  222. std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
  223. SmallVector<wchar_t, 128> path_utf16;
  224. if (std::error_code ec = widenPath(path, path_utf16))
  225. return ec;
  226. // We don't know whether this is a file or a directory, and remove() can
  227. // accept both. The usual way to delete a file or directory is to use one of
  228. // the DeleteFile or RemoveDirectory functions, but that requires you to know
  229. // which one it is. We could stat() the file to determine that, but that would
  230. // cost us additional system calls, which can be slow in a directory
  231. // containing a large number of files. So instead we call CreateFile directly.
  232. // The important part is the FILE_FLAG_DELETE_ON_CLOSE flag, which causes the
  233. // file to be deleted once it is closed. We also use the flags
  234. // FILE_FLAG_BACKUP_SEMANTICS (which allows us to open directories), and
  235. // FILE_FLAG_OPEN_REPARSE_POINT (don't follow symlinks).
  236. ScopedFileHandle h(::CreateFileW(
  237. c_str(path_utf16), DELETE,
  238. FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
  239. OPEN_EXISTING,
  240. FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS |
  241. FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_DELETE_ON_CLOSE,
  242. NULL));
  243. if (!h) {
  244. std::error_code EC = mapWindowsError(::GetLastError());
  245. if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
  246. return EC;
  247. }
  248. return std::error_code();
  249. }
  250. static std::error_code is_local_internal(SmallVectorImpl<wchar_t> &Path,
  251. bool &Result) {
  252. SmallVector<wchar_t, 128> VolumePath;
  253. size_t Len = 128;
  254. while (true) {
  255. VolumePath.resize(Len);
  256. BOOL Success =
  257. ::GetVolumePathNameW(Path.data(), VolumePath.data(), VolumePath.size());
  258. if (Success)
  259. break;
  260. DWORD Err = ::GetLastError();
  261. if (Err != ERROR_INSUFFICIENT_BUFFER)
  262. return mapWindowsError(Err);
  263. Len *= 2;
  264. }
  265. // If the output buffer has exactly enough space for the path name, but not
  266. // the null terminator, it will leave the output unterminated. Push a null
  267. // terminator onto the end to ensure that this never happens.
  268. VolumePath.push_back(L'\0');
  269. VolumePath.truncate(wcslen(VolumePath.data()));
  270. const wchar_t *P = VolumePath.data();
  271. UINT Type = ::GetDriveTypeW(P);
  272. switch (Type) {
  273. case DRIVE_FIXED:
  274. Result = true;
  275. return std::error_code();
  276. case DRIVE_REMOTE:
  277. case DRIVE_CDROM:
  278. case DRIVE_RAMDISK:
  279. case DRIVE_REMOVABLE:
  280. Result = false;
  281. return std::error_code();
  282. default:
  283. return make_error_code(errc::no_such_file_or_directory);
  284. }
  285. llvm_unreachable("Unreachable!");
  286. }
  287. std::error_code is_local(const Twine &path, bool &result) {
  288. if (!llvm::sys::fs::exists(path) || !llvm::sys::path::has_root_path(path))
  289. return make_error_code(errc::no_such_file_or_directory);
  290. SmallString<128> Storage;
  291. StringRef P = path.toStringRef(Storage);
  292. // Convert to utf-16.
  293. SmallVector<wchar_t, 128> WidePath;
  294. if (std::error_code ec = widenPath(P, WidePath))
  295. return ec;
  296. return is_local_internal(WidePath, result);
  297. }
  298. static std::error_code realPathFromHandle(HANDLE H,
  299. SmallVectorImpl<wchar_t> &Buffer) {
  300. Buffer.resize_for_overwrite(Buffer.capacity());
  301. DWORD CountChars = ::GetFinalPathNameByHandleW(
  302. H, Buffer.begin(), Buffer.capacity(), FILE_NAME_NORMALIZED);
  303. if (CountChars && CountChars >= Buffer.capacity()) {
  304. // The buffer wasn't big enough, try again. In this case the return value
  305. // *does* indicate the size of the null terminator.
  306. Buffer.resize_for_overwrite(CountChars);
  307. CountChars = ::GetFinalPathNameByHandleW(
  308. H, Buffer.begin(), Buffer.size(), FILE_NAME_NORMALIZED);
  309. }
  310. Buffer.truncate(CountChars);
  311. if (CountChars == 0)
  312. return mapWindowsError(GetLastError());
  313. return std::error_code();
  314. }
  315. static std::error_code realPathFromHandle(HANDLE H,
  316. SmallVectorImpl<char> &RealPath) {
  317. RealPath.clear();
  318. SmallVector<wchar_t, MAX_PATH> Buffer;
  319. if (std::error_code EC = realPathFromHandle(H, Buffer))
  320. return EC;
  321. // Strip the \\?\ prefix. We don't want it ending up in output, and such
  322. // paths don't get canonicalized by file APIs.
  323. wchar_t *Data = Buffer.data();
  324. DWORD CountChars = Buffer.size();
  325. if (CountChars >= 8 && ::memcmp(Data, L"\\\\?\\UNC\\", 16) == 0) {
  326. // Convert \\?\UNC\foo\bar to \\foo\bar
  327. CountChars -= 6;
  328. Data += 6;
  329. Data[0] = '\\';
  330. } else if (CountChars >= 4 && ::memcmp(Data, L"\\\\?\\", 8) == 0) {
  331. // Convert \\?\c:\foo to c:\foo
  332. CountChars -= 4;
  333. Data += 4;
  334. }
  335. // Convert the result from UTF-16 to UTF-8.
  336. if (std::error_code EC = UTF16ToUTF8(Data, CountChars, RealPath))
  337. return EC;
  338. llvm::sys::path::make_preferred(RealPath);
  339. return std::error_code();
  340. }
  341. std::error_code is_local(int FD, bool &Result) {
  342. SmallVector<wchar_t, 128> FinalPath;
  343. HANDLE Handle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
  344. if (std::error_code EC = realPathFromHandle(Handle, FinalPath))
  345. return EC;
  346. return is_local_internal(FinalPath, Result);
  347. }
  348. static std::error_code setDeleteDisposition(HANDLE Handle, bool Delete) {
  349. // Clear the FILE_DISPOSITION_INFO flag first, before checking if it's a
  350. // network file. On Windows 7 the function realPathFromHandle() below fails
  351. // if the FILE_DISPOSITION_INFO flag was already set to 'DeleteFile = true' by
  352. // a prior call.
  353. FILE_DISPOSITION_INFO Disposition;
  354. Disposition.DeleteFile = false;
  355. if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
  356. sizeof(Disposition)))
  357. return mapWindowsError(::GetLastError());
  358. if (!Delete)
  359. return std::error_code();
  360. // Check if the file is on a network (non-local) drive. If so, don't
  361. // continue when DeleteFile is true, since it prevents opening the file for
  362. // writes.
  363. SmallVector<wchar_t, 128> FinalPath;
  364. if (std::error_code EC = realPathFromHandle(Handle, FinalPath))
  365. return EC;
  366. bool IsLocal;
  367. if (std::error_code EC = is_local_internal(FinalPath, IsLocal))
  368. return EC;
  369. if (!IsLocal)
  370. return errc::not_supported;
  371. // The file is on a local drive, we can safely set FILE_DISPOSITION_INFO's
  372. // flag.
  373. Disposition.DeleteFile = true;
  374. if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
  375. sizeof(Disposition)))
  376. return mapWindowsError(::GetLastError());
  377. return std::error_code();
  378. }
  379. static std::error_code rename_internal(HANDLE FromHandle, const Twine &To,
  380. bool ReplaceIfExists) {
  381. SmallVector<wchar_t, 0> ToWide;
  382. if (auto EC = widenPath(To, ToWide))
  383. return EC;
  384. std::vector<char> RenameInfoBuf(sizeof(FILE_RENAME_INFO) - sizeof(wchar_t) +
  385. (ToWide.size() * sizeof(wchar_t)));
  386. FILE_RENAME_INFO &RenameInfo =
  387. *reinterpret_cast<FILE_RENAME_INFO *>(RenameInfoBuf.data());
  388. RenameInfo.ReplaceIfExists = ReplaceIfExists;
  389. RenameInfo.RootDirectory = 0;
  390. RenameInfo.FileNameLength = ToWide.size() * sizeof(wchar_t);
  391. std::copy(ToWide.begin(), ToWide.end(), &RenameInfo.FileName[0]);
  392. SetLastError(ERROR_SUCCESS);
  393. if (!SetFileInformationByHandle(FromHandle, FileRenameInfo, &RenameInfo,
  394. RenameInfoBuf.size())) {
  395. unsigned Error = GetLastError();
  396. if (Error == ERROR_SUCCESS)
  397. Error = ERROR_CALL_NOT_IMPLEMENTED; // Wine doesn't always set error code.
  398. return mapWindowsError(Error);
  399. }
  400. return std::error_code();
  401. }
  402. static std::error_code rename_handle(HANDLE FromHandle, const Twine &To) {
  403. SmallVector<wchar_t, 128> WideTo;
  404. if (std::error_code EC = widenPath(To, WideTo))
  405. return EC;
  406. // We normally expect this loop to succeed after a few iterations. If it
  407. // requires more than 200 tries, it's more likely that the failures are due to
  408. // a true error, so stop trying.
  409. for (unsigned Retry = 0; Retry != 200; ++Retry) {
  410. auto EC = rename_internal(FromHandle, To, true);
  411. if (EC ==
  412. std::error_code(ERROR_CALL_NOT_IMPLEMENTED, std::system_category())) {
  413. // Wine doesn't support SetFileInformationByHandle in rename_internal.
  414. // Fall back to MoveFileEx.
  415. SmallVector<wchar_t, MAX_PATH> WideFrom;
  416. if (std::error_code EC2 = realPathFromHandle(FromHandle, WideFrom))
  417. return EC2;
  418. if (::MoveFileExW(WideFrom.begin(), WideTo.begin(),
  419. MOVEFILE_REPLACE_EXISTING))
  420. return std::error_code();
  421. return mapWindowsError(GetLastError());
  422. }
  423. if (!EC || EC != errc::permission_denied)
  424. return EC;
  425. // The destination file probably exists and is currently open in another
  426. // process, either because the file was opened without FILE_SHARE_DELETE or
  427. // it is mapped into memory (e.g. using MemoryBuffer). Rename it in order to
  428. // move it out of the way of the source file. Use FILE_FLAG_DELETE_ON_CLOSE
  429. // to arrange for the destination file to be deleted when the other process
  430. // closes it.
  431. ScopedFileHandle ToHandle(
  432. ::CreateFileW(WideTo.begin(), GENERIC_READ | DELETE,
  433. FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
  434. NULL, OPEN_EXISTING,
  435. FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL));
  436. if (!ToHandle) {
  437. auto EC = mapWindowsError(GetLastError());
  438. // Another process might have raced with us and moved the existing file
  439. // out of the way before we had a chance to open it. If that happens, try
  440. // to rename the source file again.
  441. if (EC == errc::no_such_file_or_directory)
  442. continue;
  443. return EC;
  444. }
  445. BY_HANDLE_FILE_INFORMATION FI;
  446. if (!GetFileInformationByHandle(ToHandle, &FI))
  447. return mapWindowsError(GetLastError());
  448. // Try to find a unique new name for the destination file.
  449. for (unsigned UniqueId = 0; UniqueId != 200; ++UniqueId) {
  450. std::string TmpFilename = (To + ".tmp" + utostr(UniqueId)).str();
  451. if (auto EC = rename_internal(ToHandle, TmpFilename, false)) {
  452. if (EC == errc::file_exists || EC == errc::permission_denied) {
  453. // Again, another process might have raced with us and moved the file
  454. // before we could move it. Check whether this is the case, as it
  455. // might have caused the permission denied error. If that was the
  456. // case, we don't need to move it ourselves.
  457. ScopedFileHandle ToHandle2(::CreateFileW(
  458. WideTo.begin(), 0,
  459. FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
  460. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
  461. if (!ToHandle2) {
  462. auto EC = mapWindowsError(GetLastError());
  463. if (EC == errc::no_such_file_or_directory)
  464. break;
  465. return EC;
  466. }
  467. BY_HANDLE_FILE_INFORMATION FI2;
  468. if (!GetFileInformationByHandle(ToHandle2, &FI2))
  469. return mapWindowsError(GetLastError());
  470. if (FI.nFileIndexHigh != FI2.nFileIndexHigh ||
  471. FI.nFileIndexLow != FI2.nFileIndexLow ||
  472. FI.dwVolumeSerialNumber != FI2.dwVolumeSerialNumber)
  473. break;
  474. continue;
  475. }
  476. return EC;
  477. }
  478. break;
  479. }
  480. // Okay, the old destination file has probably been moved out of the way at
  481. // this point, so try to rename the source file again. Still, another
  482. // process might have raced with us to create and open the destination
  483. // file, so we need to keep doing this until we succeed.
  484. }
  485. // The most likely root cause.
  486. return errc::permission_denied;
  487. }
  488. std::error_code rename(const Twine &From, const Twine &To) {
  489. // Convert to utf-16.
  490. SmallVector<wchar_t, 128> WideFrom;
  491. if (std::error_code EC = widenPath(From, WideFrom))
  492. return EC;
  493. ScopedFileHandle FromHandle;
  494. // Retry this a few times to defeat badly behaved file system scanners.
  495. for (unsigned Retry = 0; Retry != 200; ++Retry) {
  496. if (Retry != 0)
  497. ::Sleep(10);
  498. FromHandle =
  499. ::CreateFileW(WideFrom.begin(), GENERIC_READ | DELETE,
  500. FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
  501. NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  502. if (FromHandle)
  503. break;
  504. // We don't want to loop if the file doesn't exist.
  505. auto EC = mapWindowsError(GetLastError());
  506. if (EC == errc::no_such_file_or_directory)
  507. return EC;
  508. }
  509. if (!FromHandle)
  510. return mapWindowsError(GetLastError());
  511. return rename_handle(FromHandle, To);
  512. }
  513. std::error_code resize_file(int FD, uint64_t Size) {
  514. #ifdef HAVE__CHSIZE_S
  515. errno_t error = ::_chsize_s(FD, Size);
  516. #else
  517. errno_t error = ::_chsize(FD, Size);
  518. #endif
  519. return std::error_code(error, std::generic_category());
  520. }
  521. std::error_code access(const Twine &Path, AccessMode Mode) {
  522. SmallVector<wchar_t, 128> PathUtf16;
  523. if (std::error_code EC = widenPath(Path, PathUtf16))
  524. return EC;
  525. DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
  526. if (Attributes == INVALID_FILE_ATTRIBUTES) {
  527. // See if the file didn't actually exist.
  528. DWORD LastError = ::GetLastError();
  529. if (LastError != ERROR_FILE_NOT_FOUND &&
  530. LastError != ERROR_PATH_NOT_FOUND)
  531. return mapWindowsError(LastError);
  532. return errc::no_such_file_or_directory;
  533. }
  534. if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
  535. return errc::permission_denied;
  536. if (Mode == AccessMode::Execute && (Attributes & FILE_ATTRIBUTE_DIRECTORY))
  537. return errc::permission_denied;
  538. return std::error_code();
  539. }
  540. bool can_execute(const Twine &Path) {
  541. return !access(Path, AccessMode::Execute) ||
  542. !access(Path + ".exe", AccessMode::Execute);
  543. }
  544. bool equivalent(file_status A, file_status B) {
  545. assert(status_known(A) && status_known(B));
  546. return A.FileIndexHigh == B.FileIndexHigh &&
  547. A.FileIndexLow == B.FileIndexLow &&
  548. A.FileSizeHigh == B.FileSizeHigh &&
  549. A.FileSizeLow == B.FileSizeLow &&
  550. A.LastAccessedTimeHigh == B.LastAccessedTimeHigh &&
  551. A.LastAccessedTimeLow == B.LastAccessedTimeLow &&
  552. A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
  553. A.LastWriteTimeLow == B.LastWriteTimeLow &&
  554. A.VolumeSerialNumber == B.VolumeSerialNumber;
  555. }
  556. std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
  557. file_status fsA, fsB;
  558. if (std::error_code ec = status(A, fsA))
  559. return ec;
  560. if (std::error_code ec = status(B, fsB))
  561. return ec;
  562. result = equivalent(fsA, fsB);
  563. return std::error_code();
  564. }
  565. static bool isReservedName(StringRef path) {
  566. // This list of reserved names comes from MSDN, at:
  567. // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
  568. static const char *const sReservedNames[] = { "nul", "con", "prn", "aux",
  569. "com1", "com2", "com3", "com4",
  570. "com5", "com6", "com7", "com8",
  571. "com9", "lpt1", "lpt2", "lpt3",
  572. "lpt4", "lpt5", "lpt6", "lpt7",
  573. "lpt8", "lpt9" };
  574. // First, check to see if this is a device namespace, which always
  575. // starts with \\.\, since device namespaces are not legal file paths.
  576. if (path.startswith("\\\\.\\"))
  577. return true;
  578. // Then compare against the list of ancient reserved names.
  579. for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
  580. if (path.equals_insensitive(sReservedNames[i]))
  581. return true;
  582. }
  583. // The path isn't what we consider reserved.
  584. return false;
  585. }
  586. static file_type file_type_from_attrs(DWORD Attrs) {
  587. return (Attrs & FILE_ATTRIBUTE_DIRECTORY) ? file_type::directory_file
  588. : file_type::regular_file;
  589. }
  590. static perms perms_from_attrs(DWORD Attrs) {
  591. return (Attrs & FILE_ATTRIBUTE_READONLY) ? (all_read | all_exe) : all_all;
  592. }
  593. static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
  594. if (FileHandle == INVALID_HANDLE_VALUE)
  595. goto handle_status_error;
  596. switch (::GetFileType(FileHandle)) {
  597. default:
  598. llvm_unreachable("Don't know anything about this file type");
  599. case FILE_TYPE_UNKNOWN: {
  600. DWORD Err = ::GetLastError();
  601. if (Err != NO_ERROR)
  602. return mapWindowsError(Err);
  603. Result = file_status(file_type::type_unknown);
  604. return std::error_code();
  605. }
  606. case FILE_TYPE_DISK:
  607. break;
  608. case FILE_TYPE_CHAR:
  609. Result = file_status(file_type::character_file);
  610. return std::error_code();
  611. case FILE_TYPE_PIPE:
  612. Result = file_status(file_type::fifo_file);
  613. return std::error_code();
  614. }
  615. BY_HANDLE_FILE_INFORMATION Info;
  616. if (!::GetFileInformationByHandle(FileHandle, &Info))
  617. goto handle_status_error;
  618. Result = file_status(
  619. file_type_from_attrs(Info.dwFileAttributes),
  620. perms_from_attrs(Info.dwFileAttributes), Info.nNumberOfLinks,
  621. Info.ftLastAccessTime.dwHighDateTime, Info.ftLastAccessTime.dwLowDateTime,
  622. Info.ftLastWriteTime.dwHighDateTime, Info.ftLastWriteTime.dwLowDateTime,
  623. Info.dwVolumeSerialNumber, Info.nFileSizeHigh, Info.nFileSizeLow,
  624. Info.nFileIndexHigh, Info.nFileIndexLow);
  625. return std::error_code();
  626. handle_status_error:
  627. DWORD LastError = ::GetLastError();
  628. if (LastError == ERROR_FILE_NOT_FOUND ||
  629. LastError == ERROR_PATH_NOT_FOUND)
  630. Result = file_status(file_type::file_not_found);
  631. else if (LastError == ERROR_SHARING_VIOLATION)
  632. Result = file_status(file_type::type_unknown);
  633. else
  634. Result = file_status(file_type::status_error);
  635. return mapWindowsError(LastError);
  636. }
  637. std::error_code status(const Twine &path, file_status &result, bool Follow) {
  638. SmallString<128> path_storage;
  639. SmallVector<wchar_t, 128> path_utf16;
  640. StringRef path8 = path.toStringRef(path_storage);
  641. if (isReservedName(path8)) {
  642. result = file_status(file_type::character_file);
  643. return std::error_code();
  644. }
  645. if (std::error_code ec = widenPath(path8, path_utf16))
  646. return ec;
  647. DWORD attr = ::GetFileAttributesW(path_utf16.begin());
  648. if (attr == INVALID_FILE_ATTRIBUTES)
  649. return getStatus(INVALID_HANDLE_VALUE, result);
  650. DWORD Flags = FILE_FLAG_BACKUP_SEMANTICS;
  651. // Handle reparse points.
  652. if (!Follow && (attr & FILE_ATTRIBUTE_REPARSE_POINT))
  653. Flags |= FILE_FLAG_OPEN_REPARSE_POINT;
  654. ScopedFileHandle h(
  655. ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
  656. FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
  657. NULL, OPEN_EXISTING, Flags, 0));
  658. if (!h)
  659. return getStatus(INVALID_HANDLE_VALUE, result);
  660. return getStatus(h, result);
  661. }
  662. std::error_code status(int FD, file_status &Result) {
  663. HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
  664. return getStatus(FileHandle, Result);
  665. }
  666. std::error_code status(file_t FileHandle, file_status &Result) {
  667. return getStatus(FileHandle, Result);
  668. }
  669. unsigned getUmask() {
  670. return 0;
  671. }
  672. std::error_code setPermissions(const Twine &Path, perms Permissions) {
  673. SmallVector<wchar_t, 128> PathUTF16;
  674. if (std::error_code EC = widenPath(Path, PathUTF16))
  675. return EC;
  676. DWORD Attributes = ::GetFileAttributesW(PathUTF16.begin());
  677. if (Attributes == INVALID_FILE_ATTRIBUTES)
  678. return mapWindowsError(GetLastError());
  679. // There are many Windows file attributes that are not to do with the file
  680. // permissions (e.g. FILE_ATTRIBUTE_HIDDEN). We need to be careful to preserve
  681. // them.
  682. if (Permissions & all_write) {
  683. Attributes &= ~FILE_ATTRIBUTE_READONLY;
  684. if (Attributes == 0)
  685. // FILE_ATTRIBUTE_NORMAL indicates no other attributes are set.
  686. Attributes |= FILE_ATTRIBUTE_NORMAL;
  687. }
  688. else {
  689. Attributes |= FILE_ATTRIBUTE_READONLY;
  690. // FILE_ATTRIBUTE_NORMAL is not compatible with any other attributes, so
  691. // remove it, if it is present.
  692. Attributes &= ~FILE_ATTRIBUTE_NORMAL;
  693. }
  694. if (!::SetFileAttributesW(PathUTF16.begin(), Attributes))
  695. return mapWindowsError(GetLastError());
  696. return std::error_code();
  697. }
  698. std::error_code setPermissions(int FD, perms Permissions) {
  699. // FIXME Not implemented.
  700. return std::make_error_code(std::errc::not_supported);
  701. }
  702. std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
  703. TimePoint<> ModificationTime) {
  704. FILETIME AccessFT = toFILETIME(AccessTime);
  705. FILETIME ModifyFT = toFILETIME(ModificationTime);
  706. HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
  707. if (!SetFileTime(FileHandle, NULL, &AccessFT, &ModifyFT))
  708. return mapWindowsError(::GetLastError());
  709. return std::error_code();
  710. }
  711. std::error_code mapped_file_region::init(sys::fs::file_t OrigFileHandle,
  712. uint64_t Offset, mapmode Mode) {
  713. this->Mode = Mode;
  714. if (OrigFileHandle == INVALID_HANDLE_VALUE)
  715. return make_error_code(errc::bad_file_descriptor);
  716. DWORD flprotect;
  717. switch (Mode) {
  718. case readonly: flprotect = PAGE_READONLY; break;
  719. case readwrite: flprotect = PAGE_READWRITE; break;
  720. case priv: flprotect = PAGE_WRITECOPY; break;
  721. }
  722. HANDLE FileMappingHandle =
  723. ::CreateFileMappingW(OrigFileHandle, 0, flprotect,
  724. Hi_32(Size),
  725. Lo_32(Size),
  726. 0);
  727. if (FileMappingHandle == NULL) {
  728. std::error_code ec = mapWindowsError(GetLastError());
  729. return ec;
  730. }
  731. DWORD dwDesiredAccess;
  732. switch (Mode) {
  733. case readonly: dwDesiredAccess = FILE_MAP_READ; break;
  734. case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
  735. case priv: dwDesiredAccess = FILE_MAP_COPY; break;
  736. }
  737. Mapping = ::MapViewOfFile(FileMappingHandle,
  738. dwDesiredAccess,
  739. Offset >> 32,
  740. Offset & 0xffffffff,
  741. Size);
  742. if (Mapping == NULL) {
  743. std::error_code ec = mapWindowsError(GetLastError());
  744. ::CloseHandle(FileMappingHandle);
  745. return ec;
  746. }
  747. if (Size == 0) {
  748. MEMORY_BASIC_INFORMATION mbi;
  749. SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
  750. if (Result == 0) {
  751. std::error_code ec = mapWindowsError(GetLastError());
  752. ::UnmapViewOfFile(Mapping);
  753. ::CloseHandle(FileMappingHandle);
  754. return ec;
  755. }
  756. Size = mbi.RegionSize;
  757. }
  758. // Close the file mapping handle, as it's kept alive by the file mapping. But
  759. // neither the file mapping nor the file mapping handle keep the file handle
  760. // alive, so we need to keep a reference to the file in case all other handles
  761. // are closed and the file is deleted, which may cause invalid data to be read
  762. // from the file.
  763. ::CloseHandle(FileMappingHandle);
  764. if (!::DuplicateHandle(::GetCurrentProcess(), OrigFileHandle,
  765. ::GetCurrentProcess(), &FileHandle, 0, 0,
  766. DUPLICATE_SAME_ACCESS)) {
  767. std::error_code ec = mapWindowsError(GetLastError());
  768. ::UnmapViewOfFile(Mapping);
  769. return ec;
  770. }
  771. return std::error_code();
  772. }
  773. mapped_file_region::mapped_file_region(sys::fs::file_t fd, mapmode mode,
  774. size_t length, uint64_t offset,
  775. std::error_code &ec)
  776. : Size(length) {
  777. ec = init(fd, offset, mode);
  778. if (ec)
  779. copyFrom(mapped_file_region());
  780. }
  781. static bool hasFlushBufferKernelBug() {
  782. static bool Ret{GetWindowsOSVersion() < llvm::VersionTuple(10, 0, 0, 17763)};
  783. return Ret;
  784. }
  785. static bool isEXE(StringRef Magic) {
  786. static const char PEMagic[] = {'P', 'E', '\0', '\0'};
  787. if (Magic.startswith(StringRef("MZ")) && Magic.size() >= 0x3c + 4) {
  788. uint32_t off = read32le(Magic.data() + 0x3c);
  789. // PE/COFF file, either EXE or DLL.
  790. if (Magic.substr(off).startswith(StringRef(PEMagic, sizeof(PEMagic))))
  791. return true;
  792. }
  793. return false;
  794. }
  795. void mapped_file_region::unmapImpl() {
  796. if (Mapping) {
  797. bool Exe = isEXE(StringRef((char *)Mapping, Size));
  798. ::UnmapViewOfFile(Mapping);
  799. if (Mode == mapmode::readwrite && Exe && hasFlushBufferKernelBug()) {
  800. // There is a Windows kernel bug, the exact trigger conditions of which
  801. // are not well understood. When triggered, dirty pages are not properly
  802. // flushed and subsequent process's attempts to read a file can return
  803. // invalid data. Calling FlushFileBuffers on the write handle is
  804. // sufficient to ensure that this bug is not triggered.
  805. // The bug only occurs when writing an executable and executing it right
  806. // after, under high I/O pressure.
  807. ::FlushFileBuffers(FileHandle);
  808. }
  809. ::CloseHandle(FileHandle);
  810. }
  811. }
  812. void mapped_file_region::dontNeedImpl() {}
  813. int mapped_file_region::alignment() {
  814. SYSTEM_INFO SysInfo;
  815. ::GetSystemInfo(&SysInfo);
  816. return SysInfo.dwAllocationGranularity;
  817. }
  818. static basic_file_status status_from_find_data(WIN32_FIND_DATAW *FindData) {
  819. return basic_file_status(file_type_from_attrs(FindData->dwFileAttributes),
  820. perms_from_attrs(FindData->dwFileAttributes),
  821. FindData->ftLastAccessTime.dwHighDateTime,
  822. FindData->ftLastAccessTime.dwLowDateTime,
  823. FindData->ftLastWriteTime.dwHighDateTime,
  824. FindData->ftLastWriteTime.dwLowDateTime,
  825. FindData->nFileSizeHigh, FindData->nFileSizeLow);
  826. }
  827. std::error_code detail::directory_iterator_construct(detail::DirIterState &IT,
  828. StringRef Path,
  829. bool FollowSymlinks) {
  830. SmallVector<wchar_t, 128> PathUTF16;
  831. if (std::error_code EC = widenPath(Path, PathUTF16))
  832. return EC;
  833. // Convert path to the format that Windows is happy with.
  834. size_t PathUTF16Len = PathUTF16.size();
  835. if (PathUTF16Len > 0 && !is_separator(PathUTF16[PathUTF16Len - 1]) &&
  836. PathUTF16[PathUTF16Len - 1] != L':') {
  837. PathUTF16.push_back(L'\\');
  838. PathUTF16.push_back(L'*');
  839. } else {
  840. PathUTF16.push_back(L'*');
  841. }
  842. // Get the first directory entry.
  843. WIN32_FIND_DATAW FirstFind;
  844. ScopedFindHandle FindHandle(::FindFirstFileExW(
  845. c_str(PathUTF16), FindExInfoBasic, &FirstFind, FindExSearchNameMatch,
  846. NULL, FIND_FIRST_EX_LARGE_FETCH));
  847. if (!FindHandle)
  848. return mapWindowsError(::GetLastError());
  849. size_t FilenameLen = ::wcslen(FirstFind.cFileName);
  850. while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
  851. (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
  852. FirstFind.cFileName[1] == L'.'))
  853. if (!::FindNextFileW(FindHandle, &FirstFind)) {
  854. DWORD LastError = ::GetLastError();
  855. // Check for end.
  856. if (LastError == ERROR_NO_MORE_FILES)
  857. return detail::directory_iterator_destruct(IT);
  858. return mapWindowsError(LastError);
  859. } else
  860. FilenameLen = ::wcslen(FirstFind.cFileName);
  861. // Construct the current directory entry.
  862. SmallString<128> DirectoryEntryNameUTF8;
  863. if (std::error_code EC =
  864. UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
  865. DirectoryEntryNameUTF8))
  866. return EC;
  867. IT.IterationHandle = intptr_t(FindHandle.take());
  868. SmallString<128> DirectoryEntryPath(Path);
  869. path::append(DirectoryEntryPath, DirectoryEntryNameUTF8);
  870. IT.CurrentEntry =
  871. directory_entry(DirectoryEntryPath, FollowSymlinks,
  872. file_type_from_attrs(FirstFind.dwFileAttributes),
  873. status_from_find_data(&FirstFind));
  874. return std::error_code();
  875. }
  876. std::error_code detail::directory_iterator_destruct(detail::DirIterState &IT) {
  877. if (IT.IterationHandle != 0)
  878. // Closes the handle if it's valid.
  879. ScopedFindHandle close(HANDLE(IT.IterationHandle));
  880. IT.IterationHandle = 0;
  881. IT.CurrentEntry = directory_entry();
  882. return std::error_code();
  883. }
  884. std::error_code detail::directory_iterator_increment(detail::DirIterState &IT) {
  885. WIN32_FIND_DATAW FindData;
  886. if (!::FindNextFileW(HANDLE(IT.IterationHandle), &FindData)) {
  887. DWORD LastError = ::GetLastError();
  888. // Check for end.
  889. if (LastError == ERROR_NO_MORE_FILES)
  890. return detail::directory_iterator_destruct(IT);
  891. return mapWindowsError(LastError);
  892. }
  893. size_t FilenameLen = ::wcslen(FindData.cFileName);
  894. if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
  895. (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
  896. FindData.cFileName[1] == L'.'))
  897. return directory_iterator_increment(IT);
  898. SmallString<128> DirectoryEntryPathUTF8;
  899. if (std::error_code EC =
  900. UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
  901. DirectoryEntryPathUTF8))
  902. return EC;
  903. IT.CurrentEntry.replace_filename(
  904. Twine(DirectoryEntryPathUTF8),
  905. file_type_from_attrs(FindData.dwFileAttributes),
  906. status_from_find_data(&FindData));
  907. return std::error_code();
  908. }
  909. ErrorOr<basic_file_status> directory_entry::status() const {
  910. return Status;
  911. }
  912. static std::error_code nativeFileToFd(Expected<HANDLE> H, int &ResultFD,
  913. OpenFlags Flags) {
  914. int CrtOpenFlags = 0;
  915. if (Flags & OF_Append)
  916. CrtOpenFlags |= _O_APPEND;
  917. if (Flags & OF_CRLF) {
  918. assert(Flags & OF_Text && "Flags set OF_CRLF without OF_Text");
  919. CrtOpenFlags |= _O_TEXT;
  920. }
  921. ResultFD = -1;
  922. if (!H)
  923. return errorToErrorCode(H.takeError());
  924. ResultFD = ::_open_osfhandle(intptr_t(*H), CrtOpenFlags);
  925. if (ResultFD == -1) {
  926. ::CloseHandle(*H);
  927. return mapWindowsError(ERROR_INVALID_HANDLE);
  928. }
  929. return std::error_code();
  930. }
  931. static DWORD nativeDisposition(CreationDisposition Disp, OpenFlags Flags) {
  932. // This is a compatibility hack. Really we should respect the creation
  933. // disposition, but a lot of old code relied on the implicit assumption that
  934. // OF_Append implied it would open an existing file. Since the disposition is
  935. // now explicit and defaults to CD_CreateAlways, this assumption would cause
  936. // any usage of OF_Append to append to a new file, even if the file already
  937. // existed. A better solution might have two new creation dispositions:
  938. // CD_AppendAlways and CD_AppendNew. This would also address the problem of
  939. // OF_Append being used on a read-only descriptor, which doesn't make sense.
  940. if (Flags & OF_Append)
  941. return OPEN_ALWAYS;
  942. switch (Disp) {
  943. case CD_CreateAlways:
  944. return CREATE_ALWAYS;
  945. case CD_CreateNew:
  946. return CREATE_NEW;
  947. case CD_OpenAlways:
  948. return OPEN_ALWAYS;
  949. case CD_OpenExisting:
  950. return OPEN_EXISTING;
  951. }
  952. llvm_unreachable("unreachable!");
  953. }
  954. static DWORD nativeAccess(FileAccess Access, OpenFlags Flags) {
  955. DWORD Result = 0;
  956. if (Access & FA_Read)
  957. Result |= GENERIC_READ;
  958. if (Access & FA_Write)
  959. Result |= GENERIC_WRITE;
  960. if (Flags & OF_Delete)
  961. Result |= DELETE;
  962. if (Flags & OF_UpdateAtime)
  963. Result |= FILE_WRITE_ATTRIBUTES;
  964. return Result;
  965. }
  966. static std::error_code openNativeFileInternal(const Twine &Name,
  967. file_t &ResultFile, DWORD Disp,
  968. DWORD Access, DWORD Flags,
  969. bool Inherit = false) {
  970. SmallVector<wchar_t, 128> PathUTF16;
  971. if (std::error_code EC = widenPath(Name, PathUTF16))
  972. return EC;
  973. SECURITY_ATTRIBUTES SA;
  974. SA.nLength = sizeof(SA);
  975. SA.lpSecurityDescriptor = nullptr;
  976. SA.bInheritHandle = Inherit;
  977. HANDLE H =
  978. ::CreateFileW(PathUTF16.begin(), Access,
  979. FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &SA,
  980. Disp, Flags, NULL);
  981. if (H == INVALID_HANDLE_VALUE) {
  982. DWORD LastError = ::GetLastError();
  983. std::error_code EC = mapWindowsError(LastError);
  984. // Provide a better error message when trying to open directories.
  985. // This only runs if we failed to open the file, so there is probably
  986. // no performances issues.
  987. if (LastError != ERROR_ACCESS_DENIED)
  988. return EC;
  989. if (is_directory(Name))
  990. return make_error_code(errc::is_a_directory);
  991. return EC;
  992. }
  993. ResultFile = H;
  994. return std::error_code();
  995. }
  996. Expected<file_t> openNativeFile(const Twine &Name, CreationDisposition Disp,
  997. FileAccess Access, OpenFlags Flags,
  998. unsigned Mode) {
  999. // Verify that we don't have both "append" and "excl".
  1000. assert((!(Disp == CD_CreateNew) || !(Flags & OF_Append)) &&
  1001. "Cannot specify both 'CreateNew' and 'Append' file creation flags!");
  1002. DWORD NativeDisp = nativeDisposition(Disp, Flags);
  1003. DWORD NativeAccess = nativeAccess(Access, Flags);
  1004. bool Inherit = false;
  1005. if (Flags & OF_ChildInherit)
  1006. Inherit = true;
  1007. file_t Result;
  1008. std::error_code EC = openNativeFileInternal(
  1009. Name, Result, NativeDisp, NativeAccess, FILE_ATTRIBUTE_NORMAL, Inherit);
  1010. if (EC)
  1011. return errorCodeToError(EC);
  1012. if (Flags & OF_UpdateAtime) {
  1013. FILETIME FileTime;
  1014. SYSTEMTIME SystemTime;
  1015. GetSystemTime(&SystemTime);
  1016. if (SystemTimeToFileTime(&SystemTime, &FileTime) == 0 ||
  1017. SetFileTime(Result, NULL, &FileTime, NULL) == 0) {
  1018. DWORD LastError = ::GetLastError();
  1019. ::CloseHandle(Result);
  1020. return errorCodeToError(mapWindowsError(LastError));
  1021. }
  1022. }
  1023. return Result;
  1024. }
  1025. std::error_code openFile(const Twine &Name, int &ResultFD,
  1026. CreationDisposition Disp, FileAccess Access,
  1027. OpenFlags Flags, unsigned int Mode) {
  1028. Expected<file_t> Result = openNativeFile(Name, Disp, Access, Flags);
  1029. if (!Result)
  1030. return errorToErrorCode(Result.takeError());
  1031. return nativeFileToFd(*Result, ResultFD, Flags);
  1032. }
  1033. static std::error_code directoryRealPath(const Twine &Name,
  1034. SmallVectorImpl<char> &RealPath) {
  1035. file_t File;
  1036. std::error_code EC = openNativeFileInternal(
  1037. Name, File, OPEN_EXISTING, GENERIC_READ, FILE_FLAG_BACKUP_SEMANTICS);
  1038. if (EC)
  1039. return EC;
  1040. EC = realPathFromHandle(File, RealPath);
  1041. ::CloseHandle(File);
  1042. return EC;
  1043. }
  1044. std::error_code openFileForRead(const Twine &Name, int &ResultFD,
  1045. OpenFlags Flags,
  1046. SmallVectorImpl<char> *RealPath) {
  1047. Expected<HANDLE> NativeFile = openNativeFileForRead(Name, Flags, RealPath);
  1048. return nativeFileToFd(std::move(NativeFile), ResultFD, OF_None);
  1049. }
  1050. Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
  1051. SmallVectorImpl<char> *RealPath) {
  1052. Expected<file_t> Result =
  1053. openNativeFile(Name, CD_OpenExisting, FA_Read, Flags);
  1054. // Fetch the real name of the file, if the user asked
  1055. if (Result && RealPath)
  1056. realPathFromHandle(*Result, *RealPath);
  1057. return Result;
  1058. }
  1059. file_t convertFDToNativeFile(int FD) {
  1060. return reinterpret_cast<HANDLE>(::_get_osfhandle(FD));
  1061. }
  1062. file_t getStdinHandle() { return ::GetStdHandle(STD_INPUT_HANDLE); }
  1063. file_t getStdoutHandle() { return ::GetStdHandle(STD_OUTPUT_HANDLE); }
  1064. file_t getStderrHandle() { return ::GetStdHandle(STD_ERROR_HANDLE); }
  1065. Expected<size_t> readNativeFileImpl(file_t FileHandle,
  1066. MutableArrayRef<char> Buf,
  1067. OVERLAPPED *Overlap) {
  1068. // ReadFile can only read 2GB at a time. The caller should check the number of
  1069. // bytes and read in a loop until termination.
  1070. DWORD BytesToRead =
  1071. std::min(size_t(std::numeric_limits<DWORD>::max()), Buf.size());
  1072. DWORD BytesRead = 0;
  1073. if (::ReadFile(FileHandle, Buf.data(), BytesToRead, &BytesRead, Overlap))
  1074. return BytesRead;
  1075. DWORD Err = ::GetLastError();
  1076. // EOF is not an error.
  1077. if (Err == ERROR_BROKEN_PIPE || Err == ERROR_HANDLE_EOF)
  1078. return BytesRead;
  1079. return errorCodeToError(mapWindowsError(Err));
  1080. }
  1081. Expected<size_t> readNativeFile(file_t FileHandle, MutableArrayRef<char> Buf) {
  1082. return readNativeFileImpl(FileHandle, Buf, /*Overlap=*/nullptr);
  1083. }
  1084. Expected<size_t> readNativeFileSlice(file_t FileHandle,
  1085. MutableArrayRef<char> Buf,
  1086. uint64_t Offset) {
  1087. OVERLAPPED Overlapped = {};
  1088. Overlapped.Offset = uint32_t(Offset);
  1089. Overlapped.OffsetHigh = uint32_t(Offset >> 32);
  1090. return readNativeFileImpl(FileHandle, Buf, &Overlapped);
  1091. }
  1092. std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout) {
  1093. DWORD Flags = LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY;
  1094. OVERLAPPED OV = {};
  1095. file_t File = convertFDToNativeFile(FD);
  1096. auto Start = std::chrono::steady_clock::now();
  1097. auto End = Start + Timeout;
  1098. do {
  1099. if (::LockFileEx(File, Flags, 0, MAXDWORD, MAXDWORD, &OV))
  1100. return std::error_code();
  1101. DWORD Error = ::GetLastError();
  1102. if (Error == ERROR_LOCK_VIOLATION) {
  1103. ::Sleep(1);
  1104. continue;
  1105. }
  1106. return mapWindowsError(Error);
  1107. } while (std::chrono::steady_clock::now() < End);
  1108. return mapWindowsError(ERROR_LOCK_VIOLATION);
  1109. }
  1110. std::error_code lockFile(int FD) {
  1111. DWORD Flags = LOCKFILE_EXCLUSIVE_LOCK;
  1112. OVERLAPPED OV = {};
  1113. file_t File = convertFDToNativeFile(FD);
  1114. if (::LockFileEx(File, Flags, 0, MAXDWORD, MAXDWORD, &OV))
  1115. return std::error_code();
  1116. DWORD Error = ::GetLastError();
  1117. return mapWindowsError(Error);
  1118. }
  1119. std::error_code unlockFile(int FD) {
  1120. OVERLAPPED OV = {};
  1121. file_t File = convertFDToNativeFile(FD);
  1122. if (::UnlockFileEx(File, 0, MAXDWORD, MAXDWORD, &OV))
  1123. return std::error_code();
  1124. return mapWindowsError(::GetLastError());
  1125. }
  1126. std::error_code closeFile(file_t &F) {
  1127. file_t TmpF = F;
  1128. F = kInvalidFile;
  1129. if (!::CloseHandle(TmpF))
  1130. return mapWindowsError(::GetLastError());
  1131. return std::error_code();
  1132. }
  1133. std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
  1134. // Convert to utf-16.
  1135. SmallVector<wchar_t, 128> Path16;
  1136. std::error_code EC = widenPath(path, Path16);
  1137. if (EC && !IgnoreErrors)
  1138. return EC;
  1139. // SHFileOperation() accepts a list of paths, and so must be double null-
  1140. // terminated to indicate the end of the list. The buffer is already null
  1141. // terminated, but since that null character is not considered part of the
  1142. // vector's size, pushing another one will just consume that byte. So we
  1143. // need to push 2 null terminators.
  1144. Path16.push_back(0);
  1145. Path16.push_back(0);
  1146. SHFILEOPSTRUCTW shfos = {};
  1147. shfos.wFunc = FO_DELETE;
  1148. shfos.pFrom = Path16.data();
  1149. shfos.fFlags = FOF_NO_UI;
  1150. int result = ::SHFileOperationW(&shfos);
  1151. if (result != 0 && !IgnoreErrors)
  1152. return mapWindowsError(result);
  1153. return std::error_code();
  1154. }
  1155. static void expandTildeExpr(SmallVectorImpl<char> &Path) {
  1156. // Path does not begin with a tilde expression.
  1157. if (Path.empty() || Path[0] != '~')
  1158. return;
  1159. StringRef PathStr(Path.begin(), Path.size());
  1160. PathStr = PathStr.drop_front();
  1161. StringRef Expr = PathStr.take_until([](char c) { return path::is_separator(c); });
  1162. if (!Expr.empty()) {
  1163. // This is probably a ~username/ expression. Don't support this on Windows.
  1164. return;
  1165. }
  1166. SmallString<128> HomeDir;
  1167. if (!path::home_directory(HomeDir)) {
  1168. // For some reason we couldn't get the home directory. Just exit.
  1169. return;
  1170. }
  1171. // Overwrite the first character and insert the rest.
  1172. Path[0] = HomeDir[0];
  1173. Path.insert(Path.begin() + 1, HomeDir.begin() + 1, HomeDir.end());
  1174. }
  1175. void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
  1176. dest.clear();
  1177. if (path.isTriviallyEmpty())
  1178. return;
  1179. path.toVector(dest);
  1180. expandTildeExpr(dest);
  1181. return;
  1182. }
  1183. std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
  1184. bool expand_tilde) {
  1185. dest.clear();
  1186. if (path.isTriviallyEmpty())
  1187. return std::error_code();
  1188. if (expand_tilde) {
  1189. SmallString<128> Storage;
  1190. path.toVector(Storage);
  1191. expandTildeExpr(Storage);
  1192. return real_path(Storage, dest, false);
  1193. }
  1194. if (is_directory(path))
  1195. return directoryRealPath(path, dest);
  1196. int fd;
  1197. if (std::error_code EC =
  1198. llvm::sys::fs::openFileForRead(path, fd, OF_None, &dest))
  1199. return EC;
  1200. ::close(fd);
  1201. return std::error_code();
  1202. }
  1203. } // end namespace fs
  1204. namespace path {
  1205. static bool getKnownFolderPath(KNOWNFOLDERID folderId,
  1206. SmallVectorImpl<char> &result) {
  1207. wchar_t *path = nullptr;
  1208. if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK)
  1209. return false;
  1210. bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
  1211. ::CoTaskMemFree(path);
  1212. if (ok)
  1213. llvm::sys::path::make_preferred(result);
  1214. return ok;
  1215. }
  1216. bool home_directory(SmallVectorImpl<char> &result) {
  1217. return getKnownFolderPath(FOLDERID_Profile, result);
  1218. }
  1219. bool user_config_directory(SmallVectorImpl<char> &result) {
  1220. // Either local or roaming appdata may be suitable in some cases, depending
  1221. // on the data. Local is more conservative, Roaming may not always be correct.
  1222. return getKnownFolderPath(FOLDERID_LocalAppData, result);
  1223. }
  1224. bool cache_directory(SmallVectorImpl<char> &result) {
  1225. return getKnownFolderPath(FOLDERID_LocalAppData, result);
  1226. }
  1227. static bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {
  1228. SmallVector<wchar_t, 1024> Buf;
  1229. size_t Size = 1024;
  1230. do {
  1231. Buf.resize_for_overwrite(Size);
  1232. Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.size());
  1233. if (Size == 0)
  1234. return false;
  1235. // Try again with larger buffer.
  1236. } while (Size > Buf.size());
  1237. Buf.truncate(Size);
  1238. return !windows::UTF16ToUTF8(Buf.data(), Size, Res);
  1239. }
  1240. static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
  1241. const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};
  1242. for (auto *Env : EnvironmentVariables) {
  1243. if (getTempDirEnvVar(Env, Res))
  1244. return true;
  1245. }
  1246. return false;
  1247. }
  1248. void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
  1249. (void)ErasedOnReboot;
  1250. Result.clear();
  1251. // Check whether the temporary directory is specified by an environment var.
  1252. // This matches GetTempPath logic to some degree. GetTempPath is not used
  1253. // directly as it cannot handle evn var longer than 130 chars on Windows 7
  1254. // (fixed on Windows 8).
  1255. if (getTempDirEnvVar(Result)) {
  1256. assert(!Result.empty() && "Unexpected empty path");
  1257. native(Result); // Some Unix-like shells use Unix path separator in $TMP.
  1258. fs::make_absolute(Result); // Make it absolute if not already.
  1259. return;
  1260. }
  1261. // Fall back to a system default.
  1262. const char *DefaultResult = "C:\\Temp";
  1263. Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
  1264. llvm::sys::path::make_preferred(Result);
  1265. }
  1266. } // end namespace path
  1267. namespace windows {
  1268. std::error_code CodePageToUTF16(unsigned codepage,
  1269. llvm::StringRef original,
  1270. llvm::SmallVectorImpl<wchar_t> &utf16) {
  1271. if (!original.empty()) {
  1272. int len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
  1273. original.size(), utf16.begin(), 0);
  1274. if (len == 0) {
  1275. return mapWindowsError(::GetLastError());
  1276. }
  1277. utf16.reserve(len + 1);
  1278. utf16.resize_for_overwrite(len);
  1279. len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
  1280. original.size(), utf16.begin(), utf16.size());
  1281. if (len == 0) {
  1282. return mapWindowsError(::GetLastError());
  1283. }
  1284. }
  1285. // Make utf16 null terminated.
  1286. utf16.push_back(0);
  1287. utf16.pop_back();
  1288. return std::error_code();
  1289. }
  1290. std::error_code UTF8ToUTF16(llvm::StringRef utf8,
  1291. llvm::SmallVectorImpl<wchar_t> &utf16) {
  1292. return CodePageToUTF16(CP_UTF8, utf8, utf16);
  1293. }
  1294. std::error_code CurCPToUTF16(llvm::StringRef curcp,
  1295. llvm::SmallVectorImpl<wchar_t> &utf16) {
  1296. return CodePageToUTF16(CP_ACP, curcp, utf16);
  1297. }
  1298. static
  1299. std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
  1300. size_t utf16_len,
  1301. llvm::SmallVectorImpl<char> &converted) {
  1302. if (utf16_len) {
  1303. // Get length.
  1304. int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.begin(),
  1305. 0, NULL, NULL);
  1306. if (len == 0) {
  1307. return mapWindowsError(::GetLastError());
  1308. }
  1309. converted.reserve(len + 1);
  1310. converted.resize_for_overwrite(len);
  1311. // Now do the actual conversion.
  1312. len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.data(),
  1313. converted.size(), NULL, NULL);
  1314. if (len == 0) {
  1315. return mapWindowsError(::GetLastError());
  1316. }
  1317. }
  1318. // Make the new string null terminated.
  1319. converted.push_back(0);
  1320. converted.pop_back();
  1321. return std::error_code();
  1322. }
  1323. std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
  1324. llvm::SmallVectorImpl<char> &utf8) {
  1325. return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
  1326. }
  1327. std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
  1328. llvm::SmallVectorImpl<char> &curcp) {
  1329. return UTF16ToCodePage(CP_ACP, utf16, utf16_len, curcp);
  1330. }
  1331. } // end namespace windows
  1332. } // end namespace sys
  1333. } // end namespace llvm