1679 lines · plain
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-exception6//7//===----------------------------------------------------------------------===//8//9// This file implements the Windows specific implementation of the Path API.10//11//===----------------------------------------------------------------------===//12 13//===----------------------------------------------------------------------===//14//=== WARNING: Implementation here must contain only generic Windows code that15//=== is guaranteed to work on *all* Windows variants.16//===----------------------------------------------------------------------===//17 18#include "llvm/ADT/STLExtras.h"19#include "llvm/Support/ConvertUTF.h"20#include "llvm/Support/WindowsError.h"21#include <fcntl.h>22#include <sys/stat.h>23#include <sys/types.h>24 25// These two headers must be included last, and make sure shlobj is required26// after Windows.h to make sure it picks up our definition of _WIN32_WINNT27#include "llvm/Support/Windows/WindowsSupport.h"28#include <shellapi.h>29#include <shlobj.h>30#include <winioctl.h>31 32#undef max33 34// MinGW doesn't define this.35#ifndef _ERRNO_T_DEFINED36#define _ERRNO_T_DEFINED37typedef int errno_t;38#endif39 40#ifdef _MSC_VER41#pragma comment(lib, "advapi32.lib") // This provides CryptAcquireContextW.42#pragma comment(lib, "ole32.lib") // This provides CoTaskMemFree43#endif44 45using namespace llvm;46 47using llvm::sys::windows::CurCPToUTF16;48using llvm::sys::windows::UTF16ToUTF8;49using llvm::sys::windows::UTF8ToUTF16;50using llvm::sys::windows::widenPath;51 52static bool is_separator(const wchar_t value) {53 switch (value) {54 case L'\\':55 case L'/':56 return true;57 default:58 return false;59 }60}61 62namespace llvm {63namespace sys {64namespace windows {65 66// Convert a UTF-8 path to UTF-16. Also, if the absolute equivalent of the path67// is longer than the limit that the Win32 Unicode File API can tolerate, make68// it an absolute normalized path prefixed by '\\?\'.69std::error_code widenPath(const Twine &Path8, SmallVectorImpl<wchar_t> &Path16,70 size_t MaxPathLen) {71 assert(MaxPathLen <= MAX_PATH);72 73 // Several operations would convert Path8 to SmallString; more efficient to do74 // it once up front.75 SmallString<MAX_PATH> Path8Str;76 Path8.toVector(Path8Str);77 78 // If the path is a long path, mangled into forward slashes, normalize79 // back to backslashes here.80 if (Path8Str.starts_with("//?/"))81 llvm::sys::path::native(Path8Str, path::Style::windows_backslash);82 83 if (std::error_code EC = UTF8ToUTF16(Path8Str, Path16))84 return EC;85 86 const bool IsAbsolute = llvm::sys::path::is_absolute(Path8);87 size_t CurPathLen;88 if (IsAbsolute)89 CurPathLen = 0; // No contribution from current_path needed.90 else {91 CurPathLen = ::GetCurrentDirectoryW(92 0, NULL); // Returns the size including the null terminator.93 if (CurPathLen == 0)94 return mapWindowsError(::GetLastError());95 }96 97 const char *const LongPathPrefix = "\\\\?\\";98 99 if ((Path16.size() + CurPathLen) < MaxPathLen ||100 Path8Str.starts_with(LongPathPrefix))101 return std::error_code();102 103 if (!IsAbsolute) {104 if (std::error_code EC = llvm::sys::fs::make_absolute(Path8Str))105 return EC;106 }107 108 // Remove '.' and '..' because long paths treat these as real path components.109 // Explicitly use the backslash form here, as we're prepending the \\?\110 // prefix.111 llvm::sys::path::native(Path8Str, path::Style::windows);112 llvm::sys::path::remove_dots(Path8Str, true, path::Style::windows);113 114 const StringRef RootName = llvm::sys::path::root_name(Path8Str);115 assert(!RootName.empty() &&116 "Root name cannot be empty for an absolute path!");117 118 SmallString<2 * MAX_PATH> FullPath(LongPathPrefix);119 if (RootName[1] != ':') { // Check if UNC.120 FullPath.append("UNC\\");121 FullPath.append(Path8Str.begin() + 2, Path8Str.end());122 } else {123 FullPath.append(Path8Str);124 }125 126 return UTF8ToUTF16(FullPath, Path16);127}128 129} // end namespace windows130 131namespace fs {132 133const file_t kInvalidFile = INVALID_HANDLE_VALUE;134 135std::string getMainExecutable(const char *argv0, void *MainExecAddr) {136 SmallVector<wchar_t, MAX_PATH> PathName;137 PathName.resize_for_overwrite(PathName.capacity());138 DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.size());139 140 // A zero return value indicates a failure other than insufficient space.141 if (Size == 0)142 return "";143 144 // Insufficient space is determined by a return value equal to the size of145 // the buffer passed in.146 if (Size == PathName.capacity())147 return "";148 149 // On success, GetModuleFileNameW returns the number of characters written to150 // the buffer not including the NULL terminator.151 PathName.truncate(Size);152 153 // Convert the result from UTF-16 to UTF-8.154 SmallVector<char, MAX_PATH> PathNameUTF8;155 if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))156 return "";157 158 llvm::sys::path::make_preferred(PathNameUTF8);159 160 SmallString<256> RealPath;161 sys::fs::real_path(PathNameUTF8, RealPath);162 if (RealPath.size())163 return std::string(RealPath);164 return std::string(PathNameUTF8.data());165}166 167UniqueID file_status::getUniqueID() const {168 return UniqueID(VolumeSerialNumber, PathHash);169}170 171ErrorOr<space_info> disk_space(const Twine &Path) {172 ULARGE_INTEGER Avail, Total, Free;173 if (!::GetDiskFreeSpaceExA(Path.str().c_str(), &Avail, &Total, &Free))174 return mapWindowsError(::GetLastError());175 space_info SpaceInfo;176 SpaceInfo.capacity =177 (static_cast<uint64_t>(Total.HighPart) << 32) + Total.LowPart;178 SpaceInfo.free = (static_cast<uint64_t>(Free.HighPart) << 32) + Free.LowPart;179 SpaceInfo.available =180 (static_cast<uint64_t>(Avail.HighPart) << 32) + Avail.LowPart;181 return SpaceInfo;182}183 184TimePoint<> basic_file_status::getLastAccessedTime() const {185 FILETIME Time;186 Time.dwLowDateTime = LastAccessedTimeLow;187 Time.dwHighDateTime = LastAccessedTimeHigh;188 return toTimePoint(Time);189}190 191TimePoint<> basic_file_status::getLastModificationTime() const {192 FILETIME Time;193 Time.dwLowDateTime = LastWriteTimeLow;194 Time.dwHighDateTime = LastWriteTimeHigh;195 return toTimePoint(Time);196}197 198uint32_t file_status::getLinkCount() const { return NumLinks; }199 200std::error_code current_path(SmallVectorImpl<char> &result) {201 SmallVector<wchar_t, MAX_PATH> cur_path;202 DWORD len = MAX_PATH;203 204 do {205 cur_path.resize_for_overwrite(len);206 len = ::GetCurrentDirectoryW(cur_path.size(), cur_path.data());207 208 // A zero return value indicates a failure other than insufficient space.209 if (len == 0)210 return mapWindowsError(::GetLastError());211 212 // If there's insufficient space, the len returned is larger than the len213 // given.214 } while (len > cur_path.size());215 216 // On success, GetCurrentDirectoryW returns the number of characters not217 // including the null-terminator.218 cur_path.truncate(len);219 220 if (std::error_code EC =221 UTF16ToUTF8(cur_path.begin(), cur_path.size(), result))222 return EC;223 224 llvm::sys::path::make_preferred(result);225 return std::error_code();226}227 228std::error_code set_current_path(const Twine &path) {229 // Convert to utf-16.230 SmallVector<wchar_t, 128> wide_path;231 if (std::error_code ec = widenPath(path, wide_path))232 return ec;233 234 if (!::SetCurrentDirectoryW(wide_path.begin()))235 return mapWindowsError(::GetLastError());236 237 return std::error_code();238}239 240std::error_code create_directory(const Twine &path, bool IgnoreExisting,241 perms Perms) {242 SmallVector<wchar_t, 128> path_utf16;243 244 // CreateDirectoryW has a lower maximum path length as it must leave room for245 // an 8.3 filename.246 if (std::error_code ec = widenPath(path, path_utf16, MAX_PATH - 12))247 return ec;248 249 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {250 DWORD LastError = ::GetLastError();251 if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)252 return mapWindowsError(LastError);253 }254 255 return std::error_code();256}257 258// We can't use symbolic links for windows.259std::error_code create_link(const Twine &to, const Twine &from) {260 // Convert to utf-16.261 SmallVector<wchar_t, 128> wide_from;262 SmallVector<wchar_t, 128> wide_to;263 if (std::error_code ec = widenPath(from, wide_from))264 return ec;265 if (std::error_code ec = widenPath(to, wide_to))266 return ec;267 268 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))269 return mapWindowsError(::GetLastError());270 271 return std::error_code();272}273 274std::error_code create_hard_link(const Twine &to, const Twine &from) {275 return create_link(to, from);276}277 278std::error_code remove(const Twine &path, bool IgnoreNonExisting) {279 SmallVector<wchar_t, 128> path_utf16;280 281 if (std::error_code ec = widenPath(path, path_utf16))282 return ec;283 284 // We don't know whether this is a file or a directory, and remove() can285 // accept both. The usual way to delete a file or directory is to use one of286 // the DeleteFile or RemoveDirectory functions, but that requires you to know287 // which one it is. We could stat() the file to determine that, but that would288 // cost us additional system calls, which can be slow in a directory289 // containing a large number of files. So instead we call CreateFile directly.290 // The important part is the FILE_FLAG_DELETE_ON_CLOSE flag, which causes the291 // file to be deleted once it is closed. We also use the flags292 // FILE_FLAG_BACKUP_SEMANTICS (which allows us to open directories), and293 // FILE_FLAG_OPEN_REPARSE_POINT (don't follow symlinks).294 ScopedFileHandle h(::CreateFileW(295 c_str(path_utf16), DELETE,296 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,297 OPEN_EXISTING,298 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS |299 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_DELETE_ON_CLOSE,300 NULL));301 if (!h) {302 std::error_code EC = mapWindowsError(::GetLastError());303 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)304 return EC;305 }306 307 return std::error_code();308}309 310static std::error_code is_local_internal(SmallVectorImpl<wchar_t> &Path,311 bool &Result) {312 SmallVector<wchar_t, 128> VolumePath;313 size_t Len = 128;314 while (true) {315 VolumePath.resize(Len);316 BOOL Success =317 ::GetVolumePathNameW(Path.data(), VolumePath.data(), VolumePath.size());318 319 if (Success)320 break;321 322 DWORD Err = ::GetLastError();323 if (Err != ERROR_INSUFFICIENT_BUFFER)324 return mapWindowsError(Err);325 326 Len *= 2;327 }328 // If the output buffer has exactly enough space for the path name, but not329 // the null terminator, it will leave the output unterminated. Push a null330 // terminator onto the end to ensure that this never happens.331 VolumePath.push_back(L'\0');332 VolumePath.truncate(wcslen(VolumePath.data()));333 const wchar_t *P = VolumePath.data();334 335 UINT Type = ::GetDriveTypeW(P);336 switch (Type) {337 case DRIVE_FIXED:338 Result = true;339 return std::error_code();340 case DRIVE_REMOTE:341 case DRIVE_CDROM:342 case DRIVE_RAMDISK:343 case DRIVE_REMOVABLE:344 Result = false;345 return std::error_code();346 default:347 return make_error_code(errc::no_such_file_or_directory);348 }349 llvm_unreachable("Unreachable!");350}351 352std::error_code is_local(const Twine &path, bool &result) {353 if (!llvm::sys::fs::exists(path) || !llvm::sys::path::has_root_path(path))354 return make_error_code(errc::no_such_file_or_directory);355 356 SmallString<128> Storage;357 StringRef P = path.toStringRef(Storage);358 359 // Convert to utf-16.360 SmallVector<wchar_t, 128> WidePath;361 if (std::error_code ec = widenPath(P, WidePath))362 return ec;363 return is_local_internal(WidePath, result);364}365 366static std::error_code realPathFromHandle(HANDLE H,367 SmallVectorImpl<wchar_t> &Buffer,368 DWORD flags = VOLUME_NAME_DOS) {369 Buffer.resize_for_overwrite(Buffer.capacity());370 DWORD CountChars = ::GetFinalPathNameByHandleW(371 H, Buffer.begin(), Buffer.capacity(), FILE_NAME_NORMALIZED | flags);372 if (CountChars && CountChars >= Buffer.capacity()) {373 // The buffer wasn't big enough, try again. In this case the return value374 // *does* indicate the size of the null terminator.375 Buffer.resize_for_overwrite(CountChars);376 CountChars = ::GetFinalPathNameByHandleW(H, Buffer.begin(), Buffer.size(),377 FILE_NAME_NORMALIZED | flags);378 }379 Buffer.truncate(CountChars);380 if (CountChars == 0)381 return mapWindowsError(GetLastError());382 return std::error_code();383}384 385static std::error_code realPathFromHandle(HANDLE H,386 SmallVectorImpl<char> &RealPath) {387 RealPath.clear();388 SmallVector<wchar_t, MAX_PATH> Buffer;389 if (std::error_code EC = realPathFromHandle(H, Buffer))390 return EC;391 392 // Strip the \\?\ prefix. We don't want it ending up in output, and such393 // paths don't get canonicalized by file APIs.394 wchar_t *Data = Buffer.data();395 DWORD CountChars = Buffer.size();396 if (CountChars >= 8 && ::memcmp(Data, L"\\\\?\\UNC\\", 16) == 0) {397 // Convert \\?\UNC\foo\bar to \\foo\bar398 CountChars -= 6;399 Data += 6;400 Data[0] = '\\';401 } else if (CountChars >= 4 && ::memcmp(Data, L"\\\\?\\", 8) == 0) {402 // Convert \\?\c:\foo to c:\foo403 CountChars -= 4;404 Data += 4;405 }406 407 // Convert the result from UTF-16 to UTF-8.408 if (std::error_code EC = UTF16ToUTF8(Data, CountChars, RealPath))409 return EC;410 411 llvm::sys::path::make_preferred(RealPath);412 return std::error_code();413}414 415std::error_code is_local(int FD, bool &Result) {416 SmallVector<wchar_t, 128> FinalPath;417 HANDLE Handle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));418 419 if (std::error_code EC = realPathFromHandle(Handle, FinalPath))420 return EC;421 422 return is_local_internal(FinalPath, Result);423}424 425static std::error_code setDeleteDisposition(HANDLE Handle, bool Delete) {426 // Clear the FILE_DISPOSITION_INFO flag first, before checking if it's a427 // network file. On Windows 7 the function realPathFromHandle() below fails428 // if the FILE_DISPOSITION_INFO flag was already set to 'DeleteFile = true' by429 // a prior call.430 FILE_DISPOSITION_INFO Disposition;431 Disposition.DeleteFile = false;432 if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,433 sizeof(Disposition)))434 return mapWindowsError(::GetLastError());435 if (!Delete)436 return std::error_code();437 438 // Check if the file is on a network (non-local) drive. If so, don't439 // continue when DeleteFile is true, since it prevents opening the file for440 // writes.441 SmallVector<wchar_t, 128> FinalPath;442 if (std::error_code EC = realPathFromHandle(Handle, FinalPath))443 return EC;444 445 bool IsLocal;446 if (std::error_code EC = is_local_internal(FinalPath, IsLocal))447 return EC;448 449 if (!IsLocal)450 return errc::not_supported;451 452 // The file is on a local drive, we can safely set FILE_DISPOSITION_INFO's453 // flag.454 Disposition.DeleteFile = true;455 if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,456 sizeof(Disposition)))457 return mapWindowsError(::GetLastError());458 return std::error_code();459}460 461static std::error_code rename_internal(HANDLE FromHandle, const Twine &To,462 bool ReplaceIfExists) {463 SmallVector<wchar_t, 0> ToWide;464 if (auto EC = widenPath(To, ToWide))465 return EC;466 467 std::vector<char> RenameInfoBuf(sizeof(FILE_RENAME_INFO) - sizeof(wchar_t) +468 (ToWide.size() * sizeof(wchar_t)));469 FILE_RENAME_INFO &RenameInfo =470 *reinterpret_cast<FILE_RENAME_INFO *>(RenameInfoBuf.data());471 RenameInfo.ReplaceIfExists = ReplaceIfExists;472 RenameInfo.RootDirectory = 0;473 RenameInfo.FileNameLength = ToWide.size() * sizeof(wchar_t);474 std::copy(ToWide.begin(), ToWide.end(), &RenameInfo.FileName[0]);475 476 SetLastError(ERROR_SUCCESS);477 if (!SetFileInformationByHandle(FromHandle, FileRenameInfo, &RenameInfo,478 RenameInfoBuf.size())) {479 unsigned Error = GetLastError();480 if (Error == ERROR_SUCCESS)481 Error = ERROR_CALL_NOT_IMPLEMENTED; // Wine doesn't always set error code.482 return mapWindowsError(Error);483 }484 485 return std::error_code();486}487 488static std::error_code rename_handle(HANDLE FromHandle, const Twine &To) {489 SmallVector<wchar_t, 128> WideTo;490 if (std::error_code EC = widenPath(To, WideTo))491 return EC;492 493 // We normally expect this loop to succeed after a few iterations. If it494 // requires more than 200 tries, it's more likely that the failures are due to495 // a true error, so stop trying.496 for (unsigned Retry = 0; Retry != 200; ++Retry) {497 auto EC = rename_internal(FromHandle, To, true);498 499 if (EC ==500 std::error_code(ERROR_CALL_NOT_IMPLEMENTED, std::system_category())) {501 // Wine doesn't support SetFileInformationByHandle in rename_internal.502 // Fall back to MoveFileEx.503 SmallVector<wchar_t, MAX_PATH> WideFrom;504 if (std::error_code EC2 = realPathFromHandle(FromHandle, WideFrom))505 return EC2;506 if (::MoveFileExW(WideFrom.begin(), WideTo.begin(),507 MOVEFILE_REPLACE_EXISTING))508 return std::error_code();509 return mapWindowsError(GetLastError());510 }511 512 if (!EC || EC != errc::permission_denied)513 return EC;514 515 // The destination file probably exists and is currently open in another516 // process, either because the file was opened without FILE_SHARE_DELETE or517 // it is mapped into memory (e.g. using MemoryBuffer). Rename it in order to518 // move it out of the way of the source file. Use FILE_FLAG_DELETE_ON_CLOSE519 // to arrange for the destination file to be deleted when the other process520 // closes it.521 ScopedFileHandle ToHandle(522 ::CreateFileW(WideTo.begin(), GENERIC_READ | DELETE,523 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,524 NULL, OPEN_EXISTING,525 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL));526 if (!ToHandle) {527 auto EC = mapWindowsError(GetLastError());528 // Another process might have raced with us and moved the existing file529 // out of the way before we had a chance to open it. If that happens, try530 // to rename the source file again.531 if (EC == errc::no_such_file_or_directory)532 continue;533 return EC;534 }535 536 BY_HANDLE_FILE_INFORMATION FI;537 if (!GetFileInformationByHandle(ToHandle, &FI))538 return mapWindowsError(GetLastError());539 540 // Try to find a unique new name for the destination file.541 for (unsigned UniqueId = 0; UniqueId != 200; ++UniqueId) {542 std::string TmpFilename = (To + ".tmp" + utostr(UniqueId)).str();543 if (auto EC = rename_internal(ToHandle, TmpFilename, false)) {544 if (EC == errc::file_exists || EC == errc::permission_denied) {545 // Again, another process might have raced with us and moved the file546 // before we could move it. Check whether this is the case, as it547 // might have caused the permission denied error. If that was the548 // case, we don't need to move it ourselves.549 ScopedFileHandle ToHandle2(::CreateFileW(550 WideTo.begin(), 0,551 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,552 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));553 if (!ToHandle2) {554 auto EC = mapWindowsError(GetLastError());555 if (EC == errc::no_such_file_or_directory)556 break;557 return EC;558 }559 BY_HANDLE_FILE_INFORMATION FI2;560 if (!GetFileInformationByHandle(ToHandle2, &FI2))561 return mapWindowsError(GetLastError());562 if (FI.nFileIndexHigh != FI2.nFileIndexHigh ||563 FI.nFileIndexLow != FI2.nFileIndexLow ||564 FI.dwVolumeSerialNumber != FI2.dwVolumeSerialNumber)565 break;566 continue;567 }568 return EC;569 }570 break;571 }572 573 // Okay, the old destination file has probably been moved out of the way at574 // this point, so try to rename the source file again. Still, another575 // process might have raced with us to create and open the destination576 // file, so we need to keep doing this until we succeed.577 }578 579 // The most likely root cause.580 return errc::permission_denied;581}582 583std::error_code rename(const Twine &From, const Twine &To) {584 // Convert to utf-16.585 SmallVector<wchar_t, 128> WideFrom;586 if (std::error_code EC = widenPath(From, WideFrom))587 return EC;588 589 ScopedFileHandle FromHandle;590 // Retry this a few times to defeat badly behaved file system scanners.591 for (unsigned Retry = 0; Retry != 200; ++Retry) {592 if (Retry != 0)593 ::Sleep(10);594 FromHandle =595 ::CreateFileW(WideFrom.begin(), GENERIC_READ | DELETE,596 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,597 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);598 if (FromHandle)599 break;600 601 // We don't want to loop if the file doesn't exist.602 auto EC = mapWindowsError(GetLastError());603 if (EC == errc::no_such_file_or_directory)604 return EC;605 }606 if (!FromHandle)607 return mapWindowsError(GetLastError());608 609 return rename_handle(FromHandle, To);610}611 612std::error_code resize_file(int FD, uint64_t Size) {613#ifdef HAVE__CHSIZE_S614 errno_t error = ::_chsize_s(FD, Size);615#else616 errno_t error = ::_chsize(FD, Size);617#endif618 return std::error_code(error, std::generic_category());619}620 621std::error_code resize_file_sparse(int FD, uint64_t Size) {622 HANDLE hFile = reinterpret_cast<HANDLE>(::_get_osfhandle(FD));623 DWORD temp;624 if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, &temp,625 NULL)) {626 return mapWindowsError(GetLastError());627 }628 LARGE_INTEGER liSize;629 liSize.QuadPart = Size;630 if (!SetFilePointerEx(hFile, liSize, NULL, FILE_BEGIN) ||631 !SetEndOfFile(hFile)) {632 return mapWindowsError(GetLastError());633 }634 return std::error_code();635}636 637std::error_code access(const Twine &Path, AccessMode Mode) {638 SmallVector<wchar_t, 128> PathUtf16;639 640 if (std::error_code EC = widenPath(Path, PathUtf16))641 return EC;642 643 DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());644 645 if (Attributes == INVALID_FILE_ATTRIBUTES) {646 // Avoid returning unexpected error codes when querying for existence.647 if (Mode == AccessMode::Exist)648 return errc::no_such_file_or_directory;649 650 // See if the file didn't actually exist.651 DWORD LastError = ::GetLastError();652 if (LastError != ERROR_FILE_NOT_FOUND && LastError != ERROR_PATH_NOT_FOUND)653 return mapWindowsError(LastError);654 return errc::no_such_file_or_directory;655 }656 657 if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))658 return errc::permission_denied;659 660 if (Mode == AccessMode::Execute && (Attributes & FILE_ATTRIBUTE_DIRECTORY))661 return errc::permission_denied;662 663 return std::error_code();664}665 666bool can_execute(const Twine &Path) {667 return !access(Path, AccessMode::Execute) ||668 !access(Path + ".exe", AccessMode::Execute);669}670 671bool equivalent(file_status A, file_status B) {672 assert(status_known(A) && status_known(B));673 return A.getUniqueID() == B.getUniqueID();674}675 676std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {677 file_status fsA, fsB;678 if (std::error_code ec = status(A, fsA))679 return ec;680 if (std::error_code ec = status(B, fsB))681 return ec;682 result = equivalent(fsA, fsB);683 return std::error_code();684}685 686static bool isReservedName(StringRef path) {687 // This list of reserved names comes from MSDN, at:688 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx689 static const char *const sReservedNames[] = {690 "nul", "con", "prn", "aux", "com1", "com2", "com3", "com4",691 "com5", "com6", "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",692 "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9"};693 694 // First, check to see if this is a device namespace, which always695 // starts with \\.\, since device namespaces are not legal file paths.696 if (path.starts_with("\\\\.\\"))697 return true;698 699 // Then compare against the list of ancient reserved names.700 for (size_t i = 0; i < std::size(sReservedNames); ++i) {701 if (path.equals_insensitive(sReservedNames[i]))702 return true;703 }704 705 // The path isn't what we consider reserved.706 return false;707}708 709static file_type file_type_from_attrs(DWORD Attrs) {710 return (Attrs & FILE_ATTRIBUTE_DIRECTORY) ? file_type::directory_file711 : file_type::regular_file;712}713 714static perms perms_from_attrs(DWORD Attrs) {715 return (Attrs & FILE_ATTRIBUTE_READONLY) ? (all_read | all_exe) : all_all;716}717 718static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {719 SmallVector<wchar_t, MAX_PATH> ntPath;720 if (FileHandle == INVALID_HANDLE_VALUE)721 goto handle_status_error;722 723 switch (::GetFileType(FileHandle)) {724 default:725 llvm_unreachable("Don't know anything about this file type");726 case FILE_TYPE_UNKNOWN: {727 DWORD Err = ::GetLastError();728 if (Err != NO_ERROR)729 return mapWindowsError(Err);730 Result = file_status(file_type::type_unknown);731 return std::error_code();732 }733 case FILE_TYPE_DISK:734 break;735 case FILE_TYPE_CHAR:736 Result = file_status(file_type::character_file);737 return std::error_code();738 case FILE_TYPE_PIPE:739 Result = file_status(file_type::fifo_file);740 return std::error_code();741 }742 743 BY_HANDLE_FILE_INFORMATION Info;744 if (!::GetFileInformationByHandle(FileHandle, &Info))745 goto handle_status_error;746 747 // File indices aren't necessarily stable after closing the file handle;748 // instead hash a canonicalized path.749 //750 // For getting a canonical path to the file, call GetFinalPathNameByHandleW751 // with VOLUME_NAME_NT. We don't really care exactly what the path looks752 // like here, as long as it is canonical (e.g. doesn't differentiate between753 // whether a file was referred to with upper/lower case names originally).754 // The default format with VOLUME_NAME_DOS doesn't work with all file system755 // drivers, such as ImDisk. (See756 // https://github.com/rust-lang/rust/pull/86447.)757 uint64_t PathHash;758 if (std::error_code EC =759 realPathFromHandle(FileHandle, ntPath, VOLUME_NAME_NT)) {760 // If realPathFromHandle failed, fall back on the fields761 // nFileIndex{High,Low} instead. They're not necessarily stable on all file762 // systems as they're only documented as being unique/stable as long as the763 // file handle is open - but they're a decent fallback if we couldn't get764 // the canonical path.765 PathHash = (static_cast<uint64_t>(Info.nFileIndexHigh) << 32ULL) |766 static_cast<uint64_t>(Info.nFileIndexLow);767 } else {768 PathHash = hash_combine_range(ntPath);769 }770 771 Result = file_status(772 file_type_from_attrs(Info.dwFileAttributes),773 perms_from_attrs(Info.dwFileAttributes), Info.nNumberOfLinks,774 Info.ftLastAccessTime.dwHighDateTime, Info.ftLastAccessTime.dwLowDateTime,775 Info.ftLastWriteTime.dwHighDateTime, Info.ftLastWriteTime.dwLowDateTime,776 Info.dwVolumeSerialNumber, Info.nFileSizeHigh, Info.nFileSizeLow,777 PathHash);778 return std::error_code();779 780handle_status_error:781 std::error_code Err = mapLastWindowsError();782 if (Err == std::errc::no_such_file_or_directory)783 Result = file_status(file_type::file_not_found);784 else if (Err == std::errc::permission_denied)785 Result = file_status(file_type::type_unknown);786 else787 Result = file_status(file_type::status_error);788 return Err;789}790 791std::error_code status(const Twine &path, file_status &result, bool Follow) {792 SmallString<128> path_storage;793 SmallVector<wchar_t, 128> path_utf16;794 795 StringRef path8 = path.toStringRef(path_storage);796 if (isReservedName(path8)) {797 result = file_status(file_type::character_file);798 return std::error_code();799 }800 801 if (std::error_code ec = widenPath(path8, path_utf16))802 return ec;803 804 DWORD Flags = FILE_FLAG_BACKUP_SEMANTICS;805 if (!Follow) {806 DWORD attr = ::GetFileAttributesW(path_utf16.begin());807 if (attr == INVALID_FILE_ATTRIBUTES)808 return getStatus(INVALID_HANDLE_VALUE, result);809 810 // Handle reparse points.811 if (attr & FILE_ATTRIBUTE_REPARSE_POINT)812 Flags |= FILE_FLAG_OPEN_REPARSE_POINT;813 }814 815 ScopedFileHandle h(816 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.817 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,818 NULL, OPEN_EXISTING, Flags, 0));819 if (!h)820 return getStatus(INVALID_HANDLE_VALUE, result);821 822 return getStatus(h, result);823}824 825std::error_code status(int FD, file_status &Result) {826 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));827 return getStatus(FileHandle, Result);828}829 830std::error_code status(file_t FileHandle, file_status &Result) {831 return getStatus(FileHandle, Result);832}833 834unsigned getUmask() { return 0; }835 836std::error_code setPermissions(const Twine &Path, perms Permissions) {837 SmallVector<wchar_t, 128> PathUTF16;838 if (std::error_code EC = widenPath(Path, PathUTF16))839 return EC;840 841 DWORD Attributes = ::GetFileAttributesW(PathUTF16.begin());842 if (Attributes == INVALID_FILE_ATTRIBUTES)843 return mapWindowsError(GetLastError());844 845 // There are many Windows file attributes that are not to do with the file846 // permissions (e.g. FILE_ATTRIBUTE_HIDDEN). We need to be careful to preserve847 // them.848 if (Permissions & all_write) {849 Attributes &= ~FILE_ATTRIBUTE_READONLY;850 if (Attributes == 0)851 // FILE_ATTRIBUTE_NORMAL indicates no other attributes are set.852 Attributes |= FILE_ATTRIBUTE_NORMAL;853 } else {854 Attributes |= FILE_ATTRIBUTE_READONLY;855 // FILE_ATTRIBUTE_NORMAL is not compatible with any other attributes, so856 // remove it, if it is present.857 Attributes &= ~FILE_ATTRIBUTE_NORMAL;858 }859 860 if (!::SetFileAttributesW(PathUTF16.begin(), Attributes))861 return mapWindowsError(GetLastError());862 863 return std::error_code();864}865 866std::error_code setPermissions(int FD, perms Permissions) {867 // FIXME Not implemented.868 return std::make_error_code(std::errc::not_supported);869}870 871std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,872 TimePoint<> ModificationTime) {873 FILETIME AccessFT = toFILETIME(AccessTime);874 FILETIME ModifyFT = toFILETIME(ModificationTime);875 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));876 if (!SetFileTime(FileHandle, NULL, &AccessFT, &ModifyFT))877 return mapWindowsError(::GetLastError());878 return std::error_code();879}880 881std::error_code mapped_file_region::init(sys::fs::file_t OrigFileHandle,882 uint64_t Offset, mapmode Mode) {883 this->Mode = Mode;884 if (OrigFileHandle == INVALID_HANDLE_VALUE)885 return make_error_code(errc::bad_file_descriptor);886 887 DWORD flprotect;888 switch (Mode) {889 case readonly:890 flprotect = PAGE_READONLY;891 break;892 case readwrite:893 flprotect = PAGE_READWRITE;894 break;895 case priv:896 flprotect = PAGE_WRITECOPY;897 break;898 }899 900 HANDLE FileMappingHandle = ::CreateFileMappingW(OrigFileHandle, 0, flprotect,901 Hi_32(Size), Lo_32(Size), 0);902 if (FileMappingHandle == NULL) {903 std::error_code ec = mapWindowsError(GetLastError());904 return ec;905 }906 907 DWORD dwDesiredAccess;908 switch (Mode) {909 case readonly:910 dwDesiredAccess = FILE_MAP_READ;911 break;912 case readwrite:913 dwDesiredAccess = FILE_MAP_WRITE;914 break;915 case priv:916 dwDesiredAccess = FILE_MAP_COPY;917 break;918 }919 Mapping = ::MapViewOfFile(FileMappingHandle, dwDesiredAccess, Offset >> 32,920 Offset & 0xffffffff, Size);921 if (Mapping == NULL) {922 std::error_code ec = mapWindowsError(GetLastError());923 ::CloseHandle(FileMappingHandle);924 return ec;925 }926 927 if (Size == 0) {928 MEMORY_BASIC_INFORMATION mbi;929 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));930 if (Result == 0) {931 std::error_code ec = mapWindowsError(GetLastError());932 ::UnmapViewOfFile(Mapping);933 ::CloseHandle(FileMappingHandle);934 return ec;935 }936 Size = mbi.RegionSize;937 }938 939 // Close the file mapping handle, as it's kept alive by the file mapping. But940 // neither the file mapping nor the file mapping handle keep the file handle941 // alive, so we need to keep a reference to the file in case all other handles942 // are closed and the file is deleted, which may cause invalid data to be read943 // from the file.944 ::CloseHandle(FileMappingHandle);945 if (!::DuplicateHandle(::GetCurrentProcess(), OrigFileHandle,946 ::GetCurrentProcess(), &FileHandle, 0, 0,947 DUPLICATE_SAME_ACCESS)) {948 std::error_code ec = mapWindowsError(GetLastError());949 ::UnmapViewOfFile(Mapping);950 return ec;951 }952 953 return std::error_code();954}955 956mapped_file_region::mapped_file_region(sys::fs::file_t fd, mapmode mode,957 size_t length, uint64_t offset,958 std::error_code &ec)959 : Size(length) {960 ec = init(fd, offset, mode);961 if (ec)962 copyFrom(mapped_file_region());963}964 965static bool hasFlushBufferKernelBug() {966 static bool Ret{GetWindowsOSVersion() < llvm::VersionTuple(10, 0, 0, 17763)};967 return Ret;968}969 970static bool isEXE(StringRef Magic) {971 static const char PEMagic[] = {'P', 'E', '\0', '\0'};972 if (Magic.starts_with(StringRef("MZ")) && Magic.size() >= 0x3c + 4) {973 uint32_t off = read32le(Magic.data() + 0x3c);974 // PE/COFF file, either EXE or DLL.975 if (Magic.substr(off).starts_with(StringRef(PEMagic, sizeof(PEMagic))))976 return true;977 }978 return false;979}980 981void mapped_file_region::unmapImpl() {982 if (Mapping) {983 984 bool Exe = isEXE(StringRef((char *)Mapping, Size));985 986 ::UnmapViewOfFile(Mapping);987 988 if (Mode == mapmode::readwrite) {989 bool DoFlush = Exe && hasFlushBufferKernelBug();990 // There is a Windows kernel bug, the exact trigger conditions of which991 // are not well understood. When triggered, dirty pages are not properly992 // flushed and subsequent process's attempts to read a file can return993 // invalid data. Calling FlushFileBuffers on the write handle is994 // sufficient to ensure that this bug is not triggered.995 // The bug only occurs when writing an executable and executing it right996 // after, under high I/O pressure.997 if (!DoFlush) {998 // Separately, on VirtualBox Shared Folder mounts, writes via memory999 // maps always end up unflushed (regardless of version of Windows),1000 // unless flushed with this explicit call, if they are renamed with1001 // SetFileInformationByHandle(FileRenameInfo) before closing the output1002 // handle.1003 //1004 // As the flushing is quite expensive, use a heuristic to limit the1005 // cases where we do the flushing. Only do the flushing if we aren't1006 // sure we are on a local file system.1007 bool IsLocal = false;1008 SmallVector<wchar_t, 128> FinalPath;1009 if (!realPathFromHandle(FileHandle, FinalPath)) {1010 // Not checking the return value here - if the check fails, assume the1011 // file isn't local.1012 is_local_internal(FinalPath, IsLocal);1013 }1014 DoFlush = !IsLocal;1015 }1016 if (DoFlush)1017 ::FlushFileBuffers(FileHandle);1018 }1019 1020 ::CloseHandle(FileHandle);1021 }1022}1023 1024void mapped_file_region::dontNeedImpl() {}1025 1026std::error_code mapped_file_region::sync() const {1027 if (!::FlushViewOfFile(Mapping, Size))1028 return mapWindowsError(GetLastError());1029 if (!::FlushFileBuffers(FileHandle))1030 return mapWindowsError(GetLastError());1031 return std::error_code();1032}1033 1034int mapped_file_region::alignment() {1035 SYSTEM_INFO SysInfo;1036 ::GetSystemInfo(&SysInfo);1037 return SysInfo.dwAllocationGranularity;1038}1039 1040static basic_file_status status_from_find_data(WIN32_FIND_DATAW *FindData) {1041 return basic_file_status(file_type_from_attrs(FindData->dwFileAttributes),1042 perms_from_attrs(FindData->dwFileAttributes),1043 FindData->ftLastAccessTime.dwHighDateTime,1044 FindData->ftLastAccessTime.dwLowDateTime,1045 FindData->ftLastWriteTime.dwHighDateTime,1046 FindData->ftLastWriteTime.dwLowDateTime,1047 FindData->nFileSizeHigh, FindData->nFileSizeLow);1048}1049 1050std::error_code detail::directory_iterator_construct(detail::DirIterState &IT,1051 StringRef Path,1052 bool FollowSymlinks) {1053 SmallVector<wchar_t, 128> PathUTF16;1054 1055 if (std::error_code EC = widenPath(Path, PathUTF16))1056 return EC;1057 1058 // Convert path to the format that Windows is happy with.1059 size_t PathUTF16Len = PathUTF16.size();1060 if (PathUTF16Len > 0 && !is_separator(PathUTF16[PathUTF16Len - 1]) &&1061 PathUTF16[PathUTF16Len - 1] != L':') {1062 PathUTF16.push_back(L'\\');1063 PathUTF16.push_back(L'*');1064 } else {1065 PathUTF16.push_back(L'*');1066 }1067 1068 // Get the first directory entry.1069 WIN32_FIND_DATAW FirstFind;1070 ScopedFindHandle FindHandle(::FindFirstFileExW(1071 c_str(PathUTF16), FindExInfoBasic, &FirstFind, FindExSearchNameMatch,1072 NULL, FIND_FIRST_EX_LARGE_FETCH));1073 if (!FindHandle)1074 return mapWindowsError(::GetLastError());1075 1076 size_t FilenameLen = ::wcslen(FirstFind.cFileName);1077 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||1078 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&1079 FirstFind.cFileName[1] == L'.'))1080 if (!::FindNextFileW(FindHandle, &FirstFind)) {1081 DWORD LastError = ::GetLastError();1082 // Check for end.1083 if (LastError == ERROR_NO_MORE_FILES)1084 return detail::directory_iterator_destruct(IT);1085 return mapWindowsError(LastError);1086 } else {1087 FilenameLen = ::wcslen(FirstFind.cFileName);1088 }1089 1090 // Construct the current directory entry.1091 SmallString<128> DirectoryEntryNameUTF8;1092 if (std::error_code EC =1093 UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),1094 DirectoryEntryNameUTF8))1095 return EC;1096 1097 IT.IterationHandle = intptr_t(FindHandle.take());1098 SmallString<128> DirectoryEntryPath(Path);1099 path::append(DirectoryEntryPath, DirectoryEntryNameUTF8);1100 IT.CurrentEntry =1101 directory_entry(DirectoryEntryPath, FollowSymlinks,1102 file_type_from_attrs(FirstFind.dwFileAttributes),1103 status_from_find_data(&FirstFind));1104 1105 return std::error_code();1106}1107 1108std::error_code detail::directory_iterator_destruct(detail::DirIterState &IT) {1109 if (IT.IterationHandle != 0)1110 // Closes the handle if it's valid.1111 ScopedFindHandle close(HANDLE(IT.IterationHandle));1112 IT.IterationHandle = 0;1113 IT.CurrentEntry = directory_entry();1114 return std::error_code();1115}1116 1117std::error_code detail::directory_iterator_increment(detail::DirIterState &IT) {1118 WIN32_FIND_DATAW FindData;1119 if (!::FindNextFileW(HANDLE(IT.IterationHandle), &FindData)) {1120 DWORD LastError = ::GetLastError();1121 // Check for end.1122 if (LastError == ERROR_NO_MORE_FILES)1123 return detail::directory_iterator_destruct(IT);1124 return mapWindowsError(LastError);1125 }1126 1127 size_t FilenameLen = ::wcslen(FindData.cFileName);1128 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||1129 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&1130 FindData.cFileName[1] == L'.'))1131 return directory_iterator_increment(IT);1132 1133 SmallString<128> DirectoryEntryPathUTF8;1134 if (std::error_code EC =1135 UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),1136 DirectoryEntryPathUTF8))1137 return EC;1138 1139 IT.CurrentEntry.replace_filename(1140 Twine(DirectoryEntryPathUTF8),1141 file_type_from_attrs(FindData.dwFileAttributes),1142 status_from_find_data(&FindData));1143 return std::error_code();1144}1145 1146ErrorOr<basic_file_status> directory_entry::status() const { return Status; }1147 1148static std::error_code nativeFileToFd(Expected<HANDLE> H, int &ResultFD,1149 OpenFlags Flags) {1150 int CrtOpenFlags = 0;1151 if (Flags & OF_Append)1152 CrtOpenFlags |= _O_APPEND;1153 1154 if (Flags & OF_CRLF) {1155 assert(Flags & OF_Text && "Flags set OF_CRLF without OF_Text");1156 CrtOpenFlags |= _O_TEXT;1157 }1158 1159 ResultFD = -1;1160 if (!H)1161 return errorToErrorCode(H.takeError());1162 1163 ResultFD = ::_open_osfhandle(intptr_t(*H), CrtOpenFlags);1164 if (ResultFD == -1) {1165 ::CloseHandle(*H);1166 return mapWindowsError(ERROR_INVALID_HANDLE);1167 }1168 return std::error_code();1169}1170 1171static DWORD nativeDisposition(CreationDisposition Disp, OpenFlags Flags) {1172 // This is a compatibility hack. Really we should respect the creation1173 // disposition, but a lot of old code relied on the implicit assumption that1174 // OF_Append implied it would open an existing file. Since the disposition is1175 // now explicit and defaults to CD_CreateAlways, this assumption would cause1176 // any usage of OF_Append to append to a new file, even if the file already1177 // existed. A better solution might have two new creation dispositions:1178 // CD_AppendAlways and CD_AppendNew. This would also address the problem of1179 // OF_Append being used on a read-only descriptor, which doesn't make sense.1180 if (Flags & OF_Append)1181 return OPEN_ALWAYS;1182 1183 switch (Disp) {1184 case CD_CreateAlways:1185 return CREATE_ALWAYS;1186 case CD_CreateNew:1187 return CREATE_NEW;1188 case CD_OpenAlways:1189 return OPEN_ALWAYS;1190 case CD_OpenExisting:1191 return OPEN_EXISTING;1192 }1193 llvm_unreachable("unreachable!");1194}1195 1196static DWORD nativeAccess(FileAccess Access, OpenFlags Flags) {1197 DWORD Result = 0;1198 if (Access & FA_Read)1199 Result |= GENERIC_READ;1200 if (Access & FA_Write)1201 Result |= GENERIC_WRITE;1202 if (Flags & OF_Delete)1203 Result |= DELETE;1204 if (Flags & OF_UpdateAtime)1205 Result |= FILE_WRITE_ATTRIBUTES;1206 return Result;1207}1208 1209static std::error_code openNativeFileInternal(const Twine &Name,1210 file_t &ResultFile, DWORD Disp,1211 DWORD Access, DWORD Flags,1212 bool Inherit = false) {1213 SmallVector<wchar_t, 128> PathUTF16;1214 if (std::error_code EC = widenPath(Name, PathUTF16))1215 return EC;1216 1217 SECURITY_ATTRIBUTES SA;1218 SA.nLength = sizeof(SA);1219 SA.lpSecurityDescriptor = nullptr;1220 SA.bInheritHandle = Inherit;1221 1222 HANDLE H =1223 ::CreateFileW(PathUTF16.begin(), Access,1224 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &SA,1225 Disp, Flags, NULL);1226 if (H == INVALID_HANDLE_VALUE) {1227 DWORD LastError = ::GetLastError();1228 std::error_code EC = mapWindowsError(LastError);1229 // Provide a better error message when trying to open directories.1230 // This only runs if we failed to open the file, so there is probably1231 // no performances issues.1232 if (LastError != ERROR_ACCESS_DENIED)1233 return EC;1234 if (is_directory(Name))1235 return make_error_code(errc::is_a_directory);1236 return EC;1237 }1238 ResultFile = H;1239 return std::error_code();1240}1241 1242Expected<file_t> openNativeFile(const Twine &Name, CreationDisposition Disp,1243 FileAccess Access, OpenFlags Flags,1244 unsigned Mode) {1245 // Verify that we don't have both "append" and "excl".1246 assert((!(Disp == CD_CreateNew) || !(Flags & OF_Append)) &&1247 "Cannot specify both 'CreateNew' and 'Append' file creation flags!");1248 1249 DWORD NativeDisp = nativeDisposition(Disp, Flags);1250 DWORD NativeAccess = nativeAccess(Access, Flags);1251 1252 bool Inherit = false;1253 if (Flags & OF_ChildInherit)1254 Inherit = true;1255 1256 file_t Result;1257 std::error_code EC = openNativeFileInternal(1258 Name, Result, NativeDisp, NativeAccess, FILE_ATTRIBUTE_NORMAL, Inherit);1259 if (EC)1260 return errorCodeToError(EC);1261 1262 if (Flags & OF_UpdateAtime) {1263 FILETIME FileTime;1264 SYSTEMTIME SystemTime;1265 GetSystemTime(&SystemTime);1266 if (SystemTimeToFileTime(&SystemTime, &FileTime) == 0 ||1267 SetFileTime(Result, NULL, &FileTime, NULL) == 0) {1268 DWORD LastError = ::GetLastError();1269 ::CloseHandle(Result);1270 return errorCodeToError(mapWindowsError(LastError));1271 }1272 }1273 1274 return Result;1275}1276 1277std::error_code openFile(const Twine &Name, int &ResultFD,1278 CreationDisposition Disp, FileAccess Access,1279 OpenFlags Flags, unsigned int Mode) {1280 Expected<file_t> Result = openNativeFile(Name, Disp, Access, Flags);1281 if (!Result)1282 return errorToErrorCode(Result.takeError());1283 1284 return nativeFileToFd(*Result, ResultFD, Flags);1285}1286 1287static std::error_code directoryRealPath(const Twine &Name,1288 SmallVectorImpl<char> &RealPath) {1289 file_t File;1290 std::error_code EC = openNativeFileInternal(1291 Name, File, OPEN_EXISTING, GENERIC_READ, FILE_FLAG_BACKUP_SEMANTICS);1292 if (EC)1293 return EC;1294 1295 EC = realPathFromHandle(File, RealPath);1296 ::CloseHandle(File);1297 return EC;1298}1299 1300std::error_code openFileForRead(const Twine &Name, int &ResultFD,1301 OpenFlags Flags,1302 SmallVectorImpl<char> *RealPath) {1303 Expected<HANDLE> NativeFile = openNativeFileForRead(Name, Flags, RealPath);1304 return nativeFileToFd(std::move(NativeFile), ResultFD, OF_None);1305}1306 1307Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,1308 SmallVectorImpl<char> *RealPath) {1309 Expected<file_t> Result =1310 openNativeFile(Name, CD_OpenExisting, FA_Read, Flags);1311 1312 // Fetch the real name of the file, if the user asked1313 if (Result && RealPath)1314 realPathFromHandle(*Result, *RealPath);1315 1316 return Result;1317}1318 1319file_t convertFDToNativeFile(int FD) {1320 return reinterpret_cast<HANDLE>(::_get_osfhandle(FD));1321}1322 1323file_t getStdinHandle() { return ::GetStdHandle(STD_INPUT_HANDLE); }1324file_t getStdoutHandle() { return ::GetStdHandle(STD_OUTPUT_HANDLE); }1325file_t getStderrHandle() { return ::GetStdHandle(STD_ERROR_HANDLE); }1326 1327Expected<size_t> readNativeFileImpl(file_t FileHandle,1328 MutableArrayRef<char> Buf,1329 OVERLAPPED *Overlap) {1330 // ReadFile can only read 2GB at a time. The caller should check the number of1331 // bytes and read in a loop until termination.1332 DWORD BytesToRead =1333 std::min(size_t(std::numeric_limits<DWORD>::max()), Buf.size());1334 DWORD BytesRead = 0;1335 if (::ReadFile(FileHandle, Buf.data(), BytesToRead, &BytesRead, Overlap))1336 return BytesRead;1337 DWORD Err = ::GetLastError();1338 // EOF is not an error.1339 if (Err == ERROR_BROKEN_PIPE || Err == ERROR_HANDLE_EOF)1340 return BytesRead;1341 return errorCodeToError(mapWindowsError(Err));1342}1343 1344Expected<size_t> readNativeFile(file_t FileHandle, MutableArrayRef<char> Buf) {1345 return readNativeFileImpl(FileHandle, Buf, /*Overlap=*/nullptr);1346}1347 1348Expected<size_t> readNativeFileSlice(file_t FileHandle,1349 MutableArrayRef<char> Buf,1350 uint64_t Offset) {1351 OVERLAPPED Overlapped = {};1352 Overlapped.Offset = uint32_t(Offset);1353 Overlapped.OffsetHigh = uint32_t(Offset >> 32);1354 return readNativeFileImpl(FileHandle, Buf, &Overlapped);1355}1356 1357std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout,1358 LockKind Kind) {1359 DWORD Flags = Kind == LockKind::Exclusive ? LOCKFILE_EXCLUSIVE_LOCK : 0;1360 Flags |= LOCKFILE_FAIL_IMMEDIATELY;1361 OVERLAPPED OV = {};1362 file_t File = convertFDToNativeFile(FD);1363 auto Start = std::chrono::steady_clock::now();1364 auto End = Start + Timeout;1365 do {1366 if (::LockFileEx(File, Flags, 0, MAXDWORD, MAXDWORD, &OV))1367 return std::error_code();1368 DWORD Error = ::GetLastError();1369 if (Error == ERROR_LOCK_VIOLATION) {1370 if (Timeout.count() == 0)1371 break;1372 ::Sleep(1);1373 continue;1374 }1375 return mapWindowsError(Error);1376 } while (std::chrono::steady_clock::now() < End);1377 return mapWindowsError(ERROR_LOCK_VIOLATION);1378}1379 1380std::error_code lockFile(int FD, LockKind Kind) {1381 DWORD Flags = Kind == LockKind::Exclusive ? LOCKFILE_EXCLUSIVE_LOCK : 0;1382 OVERLAPPED OV = {};1383 file_t File = convertFDToNativeFile(FD);1384 if (::LockFileEx(File, Flags, 0, MAXDWORD, MAXDWORD, &OV))1385 return std::error_code();1386 DWORD Error = ::GetLastError();1387 return mapWindowsError(Error);1388}1389 1390std::error_code unlockFile(int FD) {1391 OVERLAPPED OV = {};1392 file_t File = convertFDToNativeFile(FD);1393 if (::UnlockFileEx(File, 0, MAXDWORD, MAXDWORD, &OV))1394 return std::error_code();1395 return mapWindowsError(::GetLastError());1396}1397 1398std::error_code closeFile(file_t &F) {1399 file_t TmpF = F;1400 F = kInvalidFile;1401 if (!::CloseHandle(TmpF))1402 return mapWindowsError(::GetLastError());1403 return std::error_code();1404}1405 1406std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {1407 SmallString<128> NativePath;1408 llvm::sys::path::native(path, NativePath, path::Style::windows_backslash);1409 // Convert to utf-16.1410 SmallVector<wchar_t, 128> Path16;1411 std::error_code EC = widenPath(NativePath, Path16);1412 if (EC && !IgnoreErrors)1413 return EC;1414 1415 // SHFileOperation() accepts a list of paths, and so must be double null-1416 // terminated to indicate the end of the list. The buffer is already null1417 // terminated, but since that null character is not considered part of the1418 // vector's size, pushing another one will just consume that byte. So we1419 // need to push 2 null terminators.1420 Path16.push_back(0);1421 Path16.push_back(0);1422 1423 HRESULT HR;1424 do {1425 HR =1426 CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);1427 if (FAILED(HR))1428 break;1429 auto Uninitialize = make_scope_exit([] { CoUninitialize(); });1430 IFileOperation *FileOp = NULL;1431 HR = CoCreateInstance(CLSID_FileOperation, NULL, CLSCTX_ALL,1432 IID_PPV_ARGS(&FileOp));1433 if (FAILED(HR))1434 break;1435 auto FileOpRelease = make_scope_exit([&FileOp] { FileOp->Release(); });1436 HR = FileOp->SetOperationFlags(FOF_NO_UI | FOFX_NOCOPYHOOKS);1437 if (FAILED(HR))1438 break;1439 PIDLIST_ABSOLUTE PIDL = ILCreateFromPathW(Path16.data());1440 auto FreePIDL = make_scope_exit([&PIDL] { ILFree(PIDL); });1441 IShellItem *ShItem = NULL;1442 HR = SHCreateItemFromIDList(PIDL, IID_PPV_ARGS(&ShItem));1443 if (FAILED(HR))1444 break;1445 auto ShItemRelease = make_scope_exit([&ShItem] { ShItem->Release(); });1446 HR = FileOp->DeleteItem(ShItem, NULL);1447 if (FAILED(HR))1448 break;1449 HR = FileOp->PerformOperations();1450 } while (false);1451 if (FAILED(HR) && !IgnoreErrors)1452 return mapWindowsError(HRESULT_CODE(HR));1453 return std::error_code();1454}1455 1456static void expandTildeExpr(SmallVectorImpl<char> &Path) {1457 // Path does not begin with a tilde expression.1458 if (Path.empty() || Path[0] != '~')1459 return;1460 1461 StringRef PathStr(Path.begin(), Path.size());1462 PathStr = PathStr.drop_front();1463 StringRef Expr =1464 PathStr.take_until([](char c) { return path::is_separator(c); });1465 1466 if (!Expr.empty()) {1467 // This is probably a ~username/ expression. Don't support this on Windows.1468 return;1469 }1470 1471 SmallString<128> HomeDir;1472 if (!path::home_directory(HomeDir)) {1473 // For some reason we couldn't get the home directory. Just exit.1474 return;1475 }1476 1477 // Overwrite the first character and insert the rest.1478 Path[0] = HomeDir[0];1479 Path.insert(Path.begin() + 1, HomeDir.begin() + 1, HomeDir.end());1480}1481 1482void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {1483 dest.clear();1484 if (path.isTriviallyEmpty())1485 return;1486 1487 path.toVector(dest);1488 expandTildeExpr(dest);1489 1490 return;1491}1492 1493std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,1494 bool expand_tilde) {1495 dest.clear();1496 if (path.isTriviallyEmpty())1497 return std::error_code();1498 1499 if (expand_tilde) {1500 SmallString<128> Storage;1501 path.toVector(Storage);1502 expandTildeExpr(Storage);1503 return real_path(Storage, dest, false);1504 }1505 1506 if (is_directory(path))1507 return directoryRealPath(path, dest);1508 1509 int fd;1510 if (std::error_code EC =1511 llvm::sys::fs::openFileForRead(path, fd, OF_None, &dest))1512 return EC;1513 ::close(fd);1514 return std::error_code();1515}1516 1517} // end namespace fs1518 1519namespace path {1520static bool getKnownFolderPath(KNOWNFOLDERID folderId,1521 SmallVectorImpl<char> &result) {1522 wchar_t *path = nullptr;1523 if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK)1524 return false;1525 1526 bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);1527 ::CoTaskMemFree(path);1528 if (ok)1529 llvm::sys::path::make_preferred(result);1530 return ok;1531}1532 1533bool home_directory(SmallVectorImpl<char> &result) {1534 return getKnownFolderPath(FOLDERID_Profile, result);1535}1536 1537bool user_config_directory(SmallVectorImpl<char> &result) {1538 // Either local or roaming appdata may be suitable in some cases, depending1539 // on the data. Local is more conservative, Roaming may not always be correct.1540 return getKnownFolderPath(FOLDERID_LocalAppData, result);1541}1542 1543bool cache_directory(SmallVectorImpl<char> &result) {1544 return getKnownFolderPath(FOLDERID_LocalAppData, result);1545}1546 1547static bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {1548 SmallVector<wchar_t, 1024> Buf;1549 size_t Size = 1024;1550 do {1551 Buf.resize_for_overwrite(Size);1552 Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.size());1553 if (Size == 0)1554 return false;1555 1556 // Try again with larger buffer.1557 } while (Size > Buf.size());1558 Buf.truncate(Size);1559 1560 return !windows::UTF16ToUTF8(Buf.data(), Size, Res);1561}1562 1563static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {1564 const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};1565 for (auto *Env : EnvironmentVariables) {1566 if (getTempDirEnvVar(Env, Res))1567 return true;1568 }1569 return false;1570}1571 1572void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {1573 (void)ErasedOnReboot;1574 Result.clear();1575 1576 // Check whether the temporary directory is specified by an environment var.1577 // This matches GetTempPath logic to some degree. GetTempPath is not used1578 // directly as it cannot handle evn var longer than 130 chars on Windows 71579 // (fixed on Windows 8).1580 if (getTempDirEnvVar(Result)) {1581 assert(!Result.empty() && "Unexpected empty path");1582 native(Result); // Some Unix-like shells use Unix path separator in $TMP.1583 fs::make_absolute(Result); // Make it absolute if not already.1584 return;1585 }1586 1587 // Fall back to a system default.1588 const char *DefaultResult = "C:\\Temp";1589 Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));1590 llvm::sys::path::make_preferred(Result);1591}1592} // end namespace path1593 1594namespace windows {1595std::error_code CodePageToUTF16(unsigned codepage, llvm::StringRef original,1596 llvm::SmallVectorImpl<wchar_t> &utf16) {1597 if (!original.empty()) {1598 int len =1599 ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),1600 original.size(), utf16.begin(), 0);1601 1602 if (len == 0) {1603 return mapWindowsError(::GetLastError());1604 }1605 1606 utf16.reserve(len + 1);1607 utf16.resize_for_overwrite(len);1608 1609 len =1610 ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),1611 original.size(), utf16.begin(), utf16.size());1612 1613 if (len == 0) {1614 return mapWindowsError(::GetLastError());1615 }1616 }1617 1618 // Make utf16 null terminated.1619 utf16.push_back(0);1620 utf16.pop_back();1621 1622 return std::error_code();1623}1624 1625std::error_code UTF8ToUTF16(llvm::StringRef utf8,1626 llvm::SmallVectorImpl<wchar_t> &utf16) {1627 return CodePageToUTF16(CP_UTF8, utf8, utf16);1628}1629 1630std::error_code CurCPToUTF16(llvm::StringRef curcp,1631 llvm::SmallVectorImpl<wchar_t> &utf16) {1632 return CodePageToUTF16(CP_ACP, curcp, utf16);1633}1634 1635static std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,1636 size_t utf16_len,1637 llvm::SmallVectorImpl<char> &converted) {1638 if (utf16_len) {1639 // Get length.1640 int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len,1641 converted.begin(), 0, NULL, NULL);1642 1643 if (len == 0) {1644 return mapWindowsError(::GetLastError());1645 }1646 1647 converted.reserve(len + 1);1648 converted.resize_for_overwrite(len);1649 1650 // Now do the actual conversion.1651 len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.data(),1652 converted.size(), NULL, NULL);1653 1654 if (len == 0) {1655 return mapWindowsError(::GetLastError());1656 }1657 }1658 1659 // Make the new string null terminated.1660 converted.push_back(0);1661 converted.pop_back();1662 1663 return std::error_code();1664}1665 1666std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,1667 llvm::SmallVectorImpl<char> &utf8) {1668 return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);1669}1670 1671std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,1672 llvm::SmallVectorImpl<char> &curcp) {1673 return UTF16ToCodePage(CP_ACP, utf16, utf16_len, curcp);1674}1675 1676} // end namespace windows1677} // end namespace sys1678} // end namespace llvm1679