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