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) { 907 ec = init(fd, offset, mode); 908 if (ec) 909 copyFrom(mapped_file_region()); 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 928void mapped_file_region::unmapImpl() { 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 950int mapped_file_region::alignment() { 951 SYSTEM_INFO SysInfo; 952 ::GetSystemInfo(&SysInfo); 953 return SysInfo.dwAllocationGranularity; 954} 955 956static basic_file_status status_from_find_data(WIN32_FIND_DATAW *FindData) { 957 return basic_file_status(file_type_from_attrs(FindData->dwFileAttributes), 958 perms_from_attrs(FindData->dwFileAttributes), 959 FindData->ftLastAccessTime.dwHighDateTime, 960 FindData->ftLastAccessTime.dwLowDateTime, 961 FindData->ftLastWriteTime.dwHighDateTime, 962 FindData->ftLastWriteTime.dwLowDateTime, 963 FindData->nFileSizeHigh, FindData->nFileSizeLow); 964} 965 966std::error_code detail::directory_iterator_construct(detail::DirIterState &IT, 967 StringRef Path, 968 bool FollowSymlinks) { 969 SmallVector<wchar_t, 128> PathUTF16; 970 971 if (std::error_code EC = widenPath(Path, PathUTF16)) 972 return EC; 973 974 // Convert path to the format that Windows is happy with. 975 size_t PathUTF16Len = PathUTF16.size(); 976 if (PathUTF16Len > 0 && !is_separator(PathUTF16[PathUTF16Len - 1]) && 977 PathUTF16[PathUTF16Len - 1] != L':') { 978 PathUTF16.push_back(L'\\'); 979 PathUTF16.push_back(L'*'); 980 } else { 981 PathUTF16.push_back(L'*'); 982 } 983 984 // Get the first directory entry. 985 WIN32_FIND_DATAW FirstFind; 986 ScopedFindHandle FindHandle(::FindFirstFileExW( 987 c_str(PathUTF16), FindExInfoBasic, &FirstFind, FindExSearchNameMatch, 988 NULL, FIND_FIRST_EX_LARGE_FETCH)); 989 if (!FindHandle) 990 return mapWindowsError(::GetLastError()); 991 992 size_t FilenameLen = ::wcslen(FirstFind.cFileName); 993 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') || 994 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' && 995 FirstFind.cFileName[1] == L'.')) 996 if (!::FindNextFileW(FindHandle, &FirstFind)) { 997 DWORD LastError = ::GetLastError(); 998 // Check for end. 999 if (LastError == ERROR_NO_MORE_FILES) 1000 return detail::directory_iterator_destruct(IT); 1001 return mapWindowsError(LastError); 1002 } else 1003 FilenameLen = ::wcslen(FirstFind.cFileName); 1004 1005 // Construct the current directory entry. 1006 SmallString<128> DirectoryEntryNameUTF8; 1007 if (std::error_code EC = 1008 UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName), 1009 DirectoryEntryNameUTF8)) 1010 return EC; 1011 1012 IT.IterationHandle = intptr_t(FindHandle.take()); 1013 SmallString<128> DirectoryEntryPath(Path); 1014 path::append(DirectoryEntryPath, DirectoryEntryNameUTF8); 1015 IT.CurrentEntry = 1016 directory_entry(DirectoryEntryPath, FollowSymlinks, 1017 file_type_from_attrs(FirstFind.dwFileAttributes), 1018 status_from_find_data(&FirstFind)); 1019 1020 return std::error_code(); 1021} 1022 1023std::error_code detail::directory_iterator_destruct(detail::DirIterState &IT) { 1024 if (IT.IterationHandle != 0) 1025 // Closes the handle if it's valid. 1026 ScopedFindHandle close(HANDLE(IT.IterationHandle)); 1027 IT.IterationHandle = 0; 1028 IT.CurrentEntry = directory_entry(); 1029 return std::error_code(); 1030} 1031 1032std::error_code detail::directory_iterator_increment(detail::DirIterState &IT) { 1033 WIN32_FIND_DATAW FindData; 1034 if (!::FindNextFileW(HANDLE(IT.IterationHandle), &FindData)) { 1035 DWORD LastError = ::GetLastError(); 1036 // Check for end. 1037 if (LastError == ERROR_NO_MORE_FILES) 1038 return detail::directory_iterator_destruct(IT); 1039 return mapWindowsError(LastError); 1040 } 1041 1042 size_t FilenameLen = ::wcslen(FindData.cFileName); 1043 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') || 1044 (FilenameLen == 2 && FindData.cFileName[0] == L'.' && 1045 FindData.cFileName[1] == L'.')) 1046 return directory_iterator_increment(IT); 1047 1048 SmallString<128> DirectoryEntryPathUTF8; 1049 if (std::error_code EC = 1050 UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName), 1051 DirectoryEntryPathUTF8)) 1052 return EC; 1053 1054 IT.CurrentEntry.replace_filename( 1055 Twine(DirectoryEntryPathUTF8), 1056 file_type_from_attrs(FindData.dwFileAttributes), 1057 status_from_find_data(&FindData)); 1058 return std::error_code(); 1059} 1060 1061ErrorOr<basic_file_status> directory_entry::status() const { 1062 return Status; 1063} 1064 1065static std::error_code nativeFileToFd(Expected<HANDLE> H, int &ResultFD, 1066 OpenFlags Flags) { 1067 int CrtOpenFlags = 0; 1068 if (Flags & OF_Append) 1069 CrtOpenFlags |= _O_APPEND; 1070 1071 if (Flags & OF_CRLF) { 1072 assert(Flags & OF_Text && "Flags set OF_CRLF without OF_Text"); 1073 CrtOpenFlags |= _O_TEXT; 1074 } 1075 1076 ResultFD = -1; 1077 if (!H) 1078 return errorToErrorCode(H.takeError()); 1079 1080 ResultFD = ::_open_osfhandle(intptr_t(*H), CrtOpenFlags); 1081 if (ResultFD == -1) { 1082 ::CloseHandle(*H); 1083 return mapWindowsError(ERROR_INVALID_HANDLE); 1084 } 1085 return std::error_code(); 1086} 1087 1088static DWORD nativeDisposition(CreationDisposition Disp, OpenFlags Flags) { 1089 // This is a compatibility hack. Really we should respect the creation 1090 // disposition, but a lot of old code relied on the implicit assumption that 1091 // OF_Append implied it would open an existing file. Since the disposition is 1092 // now explicit and defaults to CD_CreateAlways, this assumption would cause 1093 // any usage of OF_Append to append to a new file, even if the file already 1094 // existed. A better solution might have two new creation dispositions: 1095 // CD_AppendAlways and CD_AppendNew. This would also address the problem of 1096 // OF_Append being used on a read-only descriptor, which doesn't make sense. 1097 if (Flags & OF_Append) 1098 return OPEN_ALWAYS; 1099 1100 switch (Disp) { 1101 case CD_CreateAlways: 1102 return CREATE_ALWAYS; 1103 case CD_CreateNew: 1104 return CREATE_NEW; 1105 case CD_OpenAlways: 1106 return OPEN_ALWAYS; 1107 case CD_OpenExisting: 1108 return OPEN_EXISTING; 1109 } 1110 llvm_unreachable("unreachable!"); 1111} 1112 1113static DWORD nativeAccess(FileAccess Access, OpenFlags Flags) { 1114 DWORD Result = 0; 1115 if (Access & FA_Read) 1116 Result |= GENERIC_READ; 1117 if (Access & FA_Write) 1118 Result |= GENERIC_WRITE; 1119 if (Flags & OF_Delete) 1120 Result |= DELETE; 1121 if (Flags & OF_UpdateAtime) 1122 Result |= FILE_WRITE_ATTRIBUTES; 1123 return Result; 1124} 1125 1126static std::error_code openNativeFileInternal(const Twine &Name, 1127 file_t &ResultFile, DWORD Disp, 1128 DWORD Access, DWORD Flags, 1129 bool Inherit = false) { 1130 SmallVector<wchar_t, 128> PathUTF16; 1131 if (std::error_code EC = widenPath(Name, PathUTF16)) 1132 return EC; 1133 1134 SECURITY_ATTRIBUTES SA; 1135 SA.nLength = sizeof(SA); 1136 SA.lpSecurityDescriptor = nullptr; 1137 SA.bInheritHandle = Inherit; 1138 1139 HANDLE H = 1140 ::CreateFileW(PathUTF16.begin(), Access, 1141 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &SA, 1142 Disp, Flags, NULL); 1143 if (H == INVALID_HANDLE_VALUE) { 1144 DWORD LastError = ::GetLastError(); 1145 std::error_code EC = mapWindowsError(LastError); 1146 // Provide a better error message when trying to open directories. 1147 // This only runs if we failed to open the file, so there is probably 1148 // no performances issues. 1149 if (LastError != ERROR_ACCESS_DENIED) 1150 return EC; 1151 if (is_directory(Name)) 1152 return make_error_code(errc::is_a_directory); 1153 return EC; 1154 } 1155 ResultFile = H; 1156 return std::error_code(); 1157} 1158 1159Expected<file_t> openNativeFile(const Twine &Name, CreationDisposition Disp, 1160 FileAccess Access, OpenFlags Flags, 1161 unsigned Mode) { 1162 // Verify that we don't have both "append" and "excl". 1163 assert((!(Disp == CD_CreateNew) || !(Flags & OF_Append)) && 1164 "Cannot specify both 'CreateNew' and 'Append' file creation flags!"); 1165 1166 DWORD NativeDisp = nativeDisposition(Disp, Flags); 1167 DWORD NativeAccess = nativeAccess(Access, Flags); 1168 1169 bool Inherit = false; 1170 if (Flags & OF_ChildInherit) 1171 Inherit = true; 1172 1173 file_t Result; 1174 std::error_code EC = openNativeFileInternal( 1175 Name, Result, NativeDisp, NativeAccess, FILE_ATTRIBUTE_NORMAL, Inherit); 1176 if (EC) 1177 return errorCodeToError(EC); 1178 1179 if (Flags & OF_UpdateAtime) { 1180 FILETIME FileTime; 1181 SYSTEMTIME SystemTime; 1182 GetSystemTime(&SystemTime); 1183 if (SystemTimeToFileTime(&SystemTime, &FileTime) == 0 || 1184 SetFileTime(Result, NULL, &FileTime, NULL) == 0) { 1185 DWORD LastError = ::GetLastError(); 1186 ::CloseHandle(Result); 1187 return errorCodeToError(mapWindowsError(LastError)); 1188 } 1189 } 1190 1191 if (Flags & OF_Delete) { 1192 if ((EC = setDeleteDisposition(Result, true))) { 1193 ::CloseHandle(Result); 1194 return errorCodeToError(EC); 1195 } 1196 } 1197 return Result; 1198} 1199 1200std::error_code openFile(const Twine &Name, int &ResultFD, 1201 CreationDisposition Disp, FileAccess Access, 1202 OpenFlags Flags, unsigned int Mode) { 1203 Expected<file_t> Result = openNativeFile(Name, Disp, Access, Flags); 1204 if (!Result) 1205 return errorToErrorCode(Result.takeError()); 1206 1207 return nativeFileToFd(*Result, ResultFD, Flags); 1208} 1209 1210static std::error_code directoryRealPath(const Twine &Name, 1211 SmallVectorImpl<char> &RealPath) { 1212 file_t File; 1213 std::error_code EC = openNativeFileInternal( 1214 Name, File, OPEN_EXISTING, GENERIC_READ, FILE_FLAG_BACKUP_SEMANTICS); 1215 if (EC) 1216 return EC; 1217 1218 EC = realPathFromHandle(File, RealPath); 1219 ::CloseHandle(File); 1220 return EC; 1221} 1222 1223std::error_code openFileForRead(const Twine &Name, int &ResultFD, 1224 OpenFlags Flags, 1225 SmallVectorImpl<char> *RealPath) { 1226 Expected<HANDLE> NativeFile = openNativeFileForRead(Name, Flags, RealPath); 1227 return nativeFileToFd(std::move(NativeFile), ResultFD, OF_None); 1228} 1229 1230Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags, 1231 SmallVectorImpl<char> *RealPath) { 1232 Expected<file_t> Result = 1233 openNativeFile(Name, CD_OpenExisting, FA_Read, Flags); 1234 1235 // Fetch the real name of the file, if the user asked 1236 if (Result && RealPath) 1237 realPathFromHandle(*Result, *RealPath); 1238 1239 return Result; 1240} 1241 1242file_t convertFDToNativeFile(int FD) { 1243 return reinterpret_cast<HANDLE>(::_get_osfhandle(FD)); 1244} 1245 1246file_t getStdinHandle() { return ::GetStdHandle(STD_INPUT_HANDLE); } 1247file_t getStdoutHandle() { return ::GetStdHandle(STD_OUTPUT_HANDLE); } 1248file_t getStderrHandle() { return ::GetStdHandle(STD_ERROR_HANDLE); } 1249 1250Expected<size_t> readNativeFileImpl(file_t FileHandle, 1251 MutableArrayRef<char> Buf, 1252 OVERLAPPED *Overlap) { 1253 // ReadFile can only read 2GB at a time. The caller should check the number of 1254 // bytes and read in a loop until termination. 1255 DWORD BytesToRead = 1256 std::min(size_t(std::numeric_limits<DWORD>::max()), Buf.size()); 1257 DWORD BytesRead = 0; 1258 if (::ReadFile(FileHandle, Buf.data(), BytesToRead, &BytesRead, Overlap)) 1259 return BytesRead; 1260 DWORD Err = ::GetLastError(); 1261 // EOF is not an error. 1262 if (Err == ERROR_BROKEN_PIPE || Err == ERROR_HANDLE_EOF) 1263 return BytesRead; 1264 return errorCodeToError(mapWindowsError(Err)); 1265} 1266 1267Expected<size_t> readNativeFile(file_t FileHandle, MutableArrayRef<char> Buf) { 1268 return readNativeFileImpl(FileHandle, Buf, /*Overlap=*/nullptr); 1269} 1270 1271Expected<size_t> readNativeFileSlice(file_t FileHandle, 1272 MutableArrayRef<char> Buf, 1273 uint64_t Offset) { 1274 OVERLAPPED Overlapped = {}; 1275 Overlapped.Offset = uint32_t(Offset); 1276 Overlapped.OffsetHigh = uint32_t(Offset >> 32); 1277 return readNativeFileImpl(FileHandle, Buf, &Overlapped); 1278} 1279 1280std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout) { 1281 DWORD Flags = LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY; 1282 OVERLAPPED OV = {}; 1283 file_t File = convertFDToNativeFile(FD); 1284 auto Start = std::chrono::steady_clock::now(); 1285 auto End = Start + Timeout; 1286 do { 1287 if (::LockFileEx(File, Flags, 0, MAXDWORD, MAXDWORD, &OV)) 1288 return std::error_code(); 1289 DWORD Error = ::GetLastError(); 1290 if (Error == ERROR_LOCK_VIOLATION) { 1291 ::Sleep(1); 1292 continue; 1293 } 1294 return mapWindowsError(Error); 1295 } while (std::chrono::steady_clock::now() < End); 1296 return mapWindowsError(ERROR_LOCK_VIOLATION); 1297} 1298 1299std::error_code lockFile(int FD) { 1300 DWORD Flags = LOCKFILE_EXCLUSIVE_LOCK; 1301 OVERLAPPED OV = {}; 1302 file_t File = convertFDToNativeFile(FD); 1303 if (::LockFileEx(File, Flags, 0, MAXDWORD, MAXDWORD, &OV)) 1304 return std::error_code(); 1305 DWORD Error = ::GetLastError(); 1306 return mapWindowsError(Error); 1307} 1308 1309std::error_code unlockFile(int FD) { 1310 OVERLAPPED OV = {}; 1311 file_t File = convertFDToNativeFile(FD); 1312 if (::UnlockFileEx(File, 0, MAXDWORD, MAXDWORD, &OV)) 1313 return std::error_code(); 1314 return mapWindowsError(::GetLastError()); 1315} 1316 1317std::error_code closeFile(file_t &F) { 1318 file_t TmpF = F; 1319 F = kInvalidFile; 1320 if (!::CloseHandle(TmpF)) 1321 return mapWindowsError(::GetLastError()); 1322 return std::error_code(); 1323} 1324 1325std::error_code remove_directories(const Twine &path, bool IgnoreErrors) { 1326 // Convert to utf-16. 1327 SmallVector<wchar_t, 128> Path16; 1328 std::error_code EC = widenPath(path, Path16); 1329 if (EC && !IgnoreErrors) 1330 return EC; 1331 1332 // SHFileOperation() accepts a list of paths, and so must be double null- 1333 // terminated to indicate the end of the list. The buffer is already null 1334 // terminated, but since that null character is not considered part of the 1335 // vector's size, pushing another one will just consume that byte. So we 1336 // need to push 2 null terminators. 1337 Path16.push_back(0); 1338 Path16.push_back(0); 1339 1340 SHFILEOPSTRUCTW shfos = {}; 1341 shfos.wFunc = FO_DELETE; 1342 shfos.pFrom = Path16.data(); 1343 shfos.fFlags = FOF_NO_UI; 1344 1345 int result = ::SHFileOperationW(&shfos); 1346 if (result != 0 && !IgnoreErrors) 1347 return mapWindowsError(result); 1348 return std::error_code(); 1349} 1350 1351static void expandTildeExpr(SmallVectorImpl<char> &Path) { 1352 // Path does not begin with a tilde expression. 1353 if (Path.empty() || Path[0] != '~') 1354 return; 1355 1356 StringRef PathStr(Path.begin(), Path.size()); 1357 PathStr = PathStr.drop_front(); 1358 StringRef Expr = PathStr.take_until([](char c) { return path::is_separator(c); }); 1359 1360 if (!Expr.empty()) { 1361 // This is probably a ~username/ expression. Don't support this on Windows. 1362 return; 1363 } 1364 1365 SmallString<128> HomeDir; 1366 if (!path::home_directory(HomeDir)) { 1367 // For some reason we couldn't get the home directory. Just exit. 1368 return; 1369 } 1370 1371 // Overwrite the first character and insert the rest. 1372 Path[0] = HomeDir[0]; 1373 Path.insert(Path.begin() + 1, HomeDir.begin() + 1, HomeDir.end()); 1374} 1375 1376void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) { 1377 dest.clear(); 1378 if (path.isTriviallyEmpty()) 1379 return; 1380 1381 path.toVector(dest); 1382 expandTildeExpr(dest); 1383 1384 return; 1385} 1386 1387std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest, 1388 bool expand_tilde) { 1389 dest.clear(); 1390 if (path.isTriviallyEmpty()) 1391 return std::error_code(); 1392 1393 if (expand_tilde) { 1394 SmallString<128> Storage; 1395 path.toVector(Storage); 1396 expandTildeExpr(Storage); 1397 return real_path(Storage, dest, false); 1398 } 1399 1400 if (is_directory(path)) 1401 return directoryRealPath(path, dest); 1402 1403 int fd; 1404 if (std::error_code EC = 1405 llvm::sys::fs::openFileForRead(path, fd, OF_None, &dest)) 1406 return EC; 1407 ::close(fd); 1408 return std::error_code(); 1409} 1410 1411} // end namespace fs 1412 1413namespace path { 1414static bool getKnownFolderPath(KNOWNFOLDERID folderId, 1415 SmallVectorImpl<char> &result) { 1416 wchar_t *path = nullptr; 1417 if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK) 1418 return false; 1419 1420 bool ok = !UTF16ToUTF8(path, ::wcslen(path), result); 1421 ::CoTaskMemFree(path); 1422 return ok; 1423} 1424 1425bool home_directory(SmallVectorImpl<char> &result) { 1426 return getKnownFolderPath(FOLDERID_Profile, result); 1427} 1428 1429bool user_config_directory(SmallVectorImpl<char> &result) { 1430 // Either local or roaming appdata may be suitable in some cases, depending 1431 // on the data. Local is more conservative, Roaming may not always be correct. 1432 return getKnownFolderPath(FOLDERID_LocalAppData, result); 1433} 1434 1435bool cache_directory(SmallVectorImpl<char> &result) { 1436 return getKnownFolderPath(FOLDERID_LocalAppData, result); 1437} 1438 1439static bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) { 1440 SmallVector<wchar_t, 1024> Buf; 1441 size_t Size = 1024; 1442 do { 1443 Buf.reserve(Size); 1444 Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.capacity()); 1445 if (Size == 0) 1446 return false; 1447 1448 // Try again with larger buffer. 1449 } while (Size > Buf.capacity()); 1450 Buf.set_size(Size); 1451 1452 return !windows::UTF16ToUTF8(Buf.data(), Size, Res); 1453} 1454 1455static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) { 1456 const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"}; 1457 for (auto *Env : EnvironmentVariables) { 1458 if (getTempDirEnvVar(Env, Res)) 1459 return true; 1460 } 1461 return false; 1462} 1463 1464void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) { 1465 (void)ErasedOnReboot; 1466 Result.clear(); 1467 1468 // Check whether the temporary directory is specified by an environment var. 1469 // This matches GetTempPath logic to some degree. GetTempPath is not used 1470 // directly as it cannot handle evn var longer than 130 chars on Windows 7 1471 // (fixed on Windows 8). 1472 if (getTempDirEnvVar(Result)) { 1473 assert(!Result.empty() && "Unexpected empty path"); 1474 native(Result); // Some Unix-like shells use Unix path separator in $TMP. 1475 fs::make_absolute(Result); // Make it absolute if not already. 1476 return; 1477 } 1478 1479 // Fall back to a system default. 1480 const char *DefaultResult = "C:\\Temp"; 1481 Result.append(DefaultResult, DefaultResult + strlen(DefaultResult)); 1482} 1483} // end namespace path 1484 1485namespace windows { 1486std::error_code CodePageToUTF16(unsigned codepage, 1487 llvm::StringRef original, 1488 llvm::SmallVectorImpl<wchar_t> &utf16) { 1489 if (!original.empty()) { 1490 int len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(), 1491 original.size(), utf16.begin(), 0); 1492 1493 if (len == 0) { 1494 return mapWindowsError(::GetLastError()); 1495 } 1496 1497 utf16.reserve(len + 1); 1498 utf16.set_size(len); 1499 1500 len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(), 1501 original.size(), utf16.begin(), utf16.size()); 1502 1503 if (len == 0) { 1504 return mapWindowsError(::GetLastError()); 1505 } 1506 } 1507 1508 // Make utf16 null terminated. 1509 utf16.push_back(0); 1510 utf16.pop_back(); 1511 1512 return std::error_code(); 1513} 1514 1515std::error_code UTF8ToUTF16(llvm::StringRef utf8, 1516 llvm::SmallVectorImpl<wchar_t> &utf16) { 1517 return CodePageToUTF16(CP_UTF8, utf8, utf16); 1518} 1519 1520std::error_code CurCPToUTF16(llvm::StringRef curcp, 1521 llvm::SmallVectorImpl<wchar_t> &utf16) { 1522 return CodePageToUTF16(CP_ACP, curcp, utf16); 1523} 1524 1525static 1526std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16, 1527 size_t utf16_len, 1528 llvm::SmallVectorImpl<char> &converted) { 1529 if (utf16_len) { 1530 // Get length. 1531 int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.begin(), 1532 0, NULL, NULL); 1533 1534 if (len == 0) { 1535 return mapWindowsError(::GetLastError()); 1536 } 1537 1538 converted.reserve(len); 1539 converted.set_size(len); 1540 1541 // Now do the actual conversion. 1542 len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.data(), 1543 converted.size(), NULL, NULL); 1544 1545 if (len == 0) { 1546 return mapWindowsError(::GetLastError()); 1547 } 1548 } 1549 1550 // Make the new string null terminated. 1551 converted.push_back(0); 1552 converted.pop_back(); 1553 1554 return std::error_code(); 1555} 1556 1557std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len, 1558 llvm::SmallVectorImpl<char> &utf8) { 1559 return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8); 1560} 1561 1562std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len, 1563 llvm::SmallVectorImpl<char> &curcp) { 1564 return UTF16ToCodePage(CP_ACP, utf16, utf16_len, curcp); 1565} 1566 1567} // end namespace windows 1568} // end namespace sys 1569} // end namespace llvm 1570