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