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