1 //===- llvm/Support/Windows/Path.inc - Windows Path Impl --------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the Windows specific implementation of the Path API.
11 //===----------------------------------------------------------------------===//
13 //===----------------------------------------------------------------------===//
14 //=== WARNING: Implementation here must contain only generic Windows code that
15 //=== is guaranteed to work on *all* Windows variants.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/Support/ConvertUTF.h"
20 #include "llvm/Support/WindowsError.h"
23 #include <sys/types.h>
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"
33 // MinGW doesn't define this.
34 #ifndef _ERRNO_T_DEFINED
35 #define _ERRNO_T_DEFINED
40 # pragma comment(lib, "advapi32.lib") // This provides CryptAcquireContextW.
41 # pragma comment(lib, "ole32.lib") // This provides CoTaskMemFree
46 using llvm::sys::windows::UTF8ToUTF16;
47 using llvm::sys::windows::CurCPToUTF16;
48 using llvm::sys::windows::UTF16ToUTF8;
49 using llvm::sys::windows::widenPath;
51 static bool is_separator(const wchar_t value) {
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 '\\?\'.
68 std::error_code widenPath(const Twine &Path8, SmallVectorImpl<wchar_t> &Path16,
70 assert(MaxPathLen <= MAX_PATH);
72 // Several operations would convert Path8 to SmallString; more efficient to do
74 SmallString<MAX_PATH> Path8Str;
75 Path8.toVector(Path8Str);
77 if (std::error_code EC = UTF8ToUTF16(Path8Str, Path16))
80 const bool IsAbsolute = llvm::sys::path::is_absolute(Path8);
83 CurPathLen = 0; // No contribution from current_path needed.
85 CurPathLen = ::GetCurrentDirectoryW(
86 0, NULL); // Returns the size including the null terminator.
88 return mapWindowsError(::GetLastError());
91 const char *const LongPathPrefix = "\\\\?\\";
93 if ((Path16.size() + CurPathLen) < MaxPathLen ||
94 Path8Str.startswith(LongPathPrefix))
95 return std::error_code();
98 if (std::error_code EC = llvm::sys::fs::make_absolute(Path8Str))
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);
106 const StringRef RootName = llvm::sys::path::root_name(Path8Str);
107 assert(!RootName.empty() &&
108 "Root name cannot be empty for an absolute path!");
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());
115 FullPath.append(Path8Str);
117 return UTF8ToUTF16(FullPath, Path16);
120 } // end namespace windows
124 const file_t kInvalidFile = INVALID_HANDLE_VALUE;
126 std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
127 SmallVector<wchar_t, MAX_PATH> PathName;
128 DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
130 // A zero return value indicates a failure other than insufficient space.
134 // Insufficient space is determined by a return value equal to the size of
135 // the buffer passed in.
136 if (Size == PathName.capacity())
139 // On success, GetModuleFileNameW returns the number of characters written to
140 // the buffer not including the NULL terminator.
141 PathName.set_size(Size);
143 // Convert the result from UTF-16 to UTF-8.
144 SmallVector<char, MAX_PATH> PathNameUTF8;
145 if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
148 return std::string(PathNameUTF8.data());
151 UniqueID 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);
157 return UniqueID(VolumeSerialNumber, FileID);
160 ErrorOr<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;
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;
173 TimePoint<> basic_file_status::getLastAccessedTime() const {
175 Time.dwLowDateTime = LastAccessedTimeLow;
176 Time.dwHighDateTime = LastAccessedTimeHigh;
177 return toTimePoint(Time);
180 TimePoint<> basic_file_status::getLastModificationTime() const {
182 Time.dwLowDateTime = LastWriteTimeLow;
183 Time.dwHighDateTime = LastWriteTimeHigh;
184 return toTimePoint(Time);
187 uint32_t file_status::getLinkCount() const {
191 std::error_code current_path(SmallVectorImpl<char> &result) {
192 SmallVector<wchar_t, MAX_PATH> cur_path;
193 DWORD len = MAX_PATH;
196 cur_path.reserve(len);
197 len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
199 // A zero return value indicates a failure other than insufficient space.
201 return mapWindowsError(::GetLastError());
203 // If there's insufficient space, the len returned is larger than the len
205 } while (len > cur_path.capacity());
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);
213 std::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))
219 if (!::SetCurrentDirectoryW(wide_path.begin()))
220 return mapWindowsError(::GetLastError());
222 return std::error_code();
225 std::error_code create_directory(const Twine &path, bool IgnoreExisting,
227 SmallVector<wchar_t, 128> path_utf16;
229 // CreateDirectoryW has a lower maximum path length as it must leave room for
231 if (std::error_code ec = widenPath(path, path_utf16, MAX_PATH - 12))
234 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
235 DWORD LastError = ::GetLastError();
236 if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
237 return mapWindowsError(LastError);
240 return std::error_code();
243 // We can't use symbolic links for windows.
244 std::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))
250 if (std::error_code ec = widenPath(to, wide_to))
253 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
254 return mapWindowsError(::GetLastError());
256 return std::error_code();
259 std::error_code create_hard_link(const Twine &to, const Twine &from) {
260 return create_link(to, from);
263 std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
264 SmallVector<wchar_t, 128> path_utf16;
266 if (std::error_code ec = widenPath(path, path_utf16))
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,
283 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS |
284 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_DELETE_ON_CLOSE,
287 std::error_code EC = mapWindowsError(::GetLastError());
288 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
292 return std::error_code();
295 static std::error_code is_local_internal(SmallVectorImpl<wchar_t> &Path,
297 SmallVector<wchar_t, 128> VolumePath;
300 VolumePath.resize(Len);
302 ::GetVolumePathNameW(Path.data(), VolumePath.data(), VolumePath.size());
307 DWORD Err = ::GetLastError();
308 if (Err != ERROR_INSUFFICIENT_BUFFER)
309 return mapWindowsError(Err);
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();
320 UINT Type = ::GetDriveTypeW(P);
324 return std::error_code();
328 case DRIVE_REMOVABLE:
330 return std::error_code();
332 return make_error_code(errc::no_such_file_or_directory);
334 llvm_unreachable("Unreachable!");
337 std::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);
341 SmallString<128> Storage;
342 StringRef P = path.toStringRef(Storage);
344 // Convert to utf-16.
345 SmallVector<wchar_t, 128> WidePath;
346 if (std::error_code ec = widenPath(P, WidePath))
348 return is_local_internal(WidePath, result);
351 static 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);
363 return mapWindowsError(GetLastError());
364 Buffer.set_size(CountChars);
365 return std::error_code();
368 static std::error_code realPathFromHandle(HANDLE H,
369 SmallVectorImpl<char> &RealPath) {
371 SmallVector<wchar_t, MAX_PATH> Buffer;
372 if (std::error_code EC = realPathFromHandle(H, Buffer))
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
384 } else if (CountChars >= 4 && ::memcmp(Data, L"\\\\?\\", 8) == 0) {
385 // Convert \\?\c:\foo to c:\foo
390 // Convert the result from UTF-16 to UTF-8.
391 return UTF16ToUTF8(Data, CountChars, RealPath);
394 std::error_code is_local(int FD, bool &Result) {
395 SmallVector<wchar_t, 128> FinalPath;
396 HANDLE Handle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
398 if (std::error_code EC = realPathFromHandle(Handle, FinalPath))
401 return is_local_internal(FinalPath, Result);
404 static 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
409 FILE_DISPOSITION_INFO Disposition;
410 Disposition.DeleteFile = false;
411 if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
412 sizeof(Disposition)))
413 return mapWindowsError(::GetLastError());
415 return std::error_code();
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))
426 if (std::error_code EC = is_local_internal(FinalPath, IsLocal))
430 return std::error_code();
432 // The file is on a local drive, we can safely set FILE_DISPOSITION_INFO's
434 Disposition.DeleteFile = true;
435 if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
436 sizeof(Disposition)))
437 return mapWindowsError(::GetLastError());
438 return std::error_code();
441 static 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))
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]);
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);
465 return std::error_code();
468 static 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))
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);
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))
486 if (::MoveFileExW(WideFrom.begin(), WideTo.begin(),
487 MOVEFILE_REPLACE_EXISTING))
488 return std::error_code();
489 return mapWindowsError(GetLastError());
492 if (!EC || EC != errc::permission_denied)
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
501 ScopedFileHandle ToHandle(
502 ::CreateFileW(WideTo.begin(), GENERIC_READ | DELETE,
503 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
505 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL));
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)
516 BY_HANDLE_FILE_INFORMATION FI;
517 if (!GetFileInformationByHandle(ToHandle, &FI))
518 return mapWindowsError(GetLastError());
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(
531 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
532 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
534 auto EC = mapWindowsError(GetLastError());
535 if (EC == errc::no_such_file_or_directory)
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)
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.
559 // The most likely root cause.
560 return errc::permission_denied;
563 std::error_code rename(const Twine &From, const Twine &To) {
564 // Convert to utf-16.
565 SmallVector<wchar_t, 128> WideFrom;
566 if (std::error_code EC = widenPath(From, WideFrom))
569 ScopedFileHandle FromHandle;
570 // Retry this a few times to defeat badly behaved file system scanners.
571 for (unsigned Retry = 0; Retry != 200; ++Retry) {
575 ::CreateFileW(WideFrom.begin(), GENERIC_READ | DELETE,
576 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
577 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
581 // We don't want to loop if the file doesn't exist.
582 auto EC = mapWindowsError(GetLastError());
583 if (EC == errc::no_such_file_or_directory)
587 return mapWindowsError(GetLastError());
589 return rename_handle(FromHandle, To);
592 std::error_code resize_file(int FD, uint64_t Size) {
593 #ifdef HAVE__CHSIZE_S
594 errno_t error = ::_chsize_s(FD, Size);
596 errno_t error = ::_chsize(FD, Size);
598 return std::error_code(error, std::generic_category());
601 std::error_code access(const Twine &Path, AccessMode Mode) {
602 SmallVector<wchar_t, 128> PathUtf16;
604 if (std::error_code EC = widenPath(Path, PathUtf16))
607 DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
609 if (Attributes == INVALID_FILE_ATTRIBUTES) {
610 // See if the file didn't actually exist.
611 DWORD LastError = ::GetLastError();
612 if (LastError != ERROR_FILE_NOT_FOUND &&
613 LastError != ERROR_PATH_NOT_FOUND)
614 return mapWindowsError(LastError);
615 return errc::no_such_file_or_directory;
618 if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
619 return errc::permission_denied;
621 if (Mode == AccessMode::Execute && (Attributes & FILE_ATTRIBUTE_DIRECTORY))
622 return errc::permission_denied;
624 return std::error_code();
627 bool can_execute(const Twine &Path) {
628 return !access(Path, AccessMode::Execute) ||
629 !access(Path + ".exe", AccessMode::Execute);
632 bool equivalent(file_status A, file_status B) {
633 assert(status_known(A) && status_known(B));
634 return A.FileIndexHigh == B.FileIndexHigh &&
635 A.FileIndexLow == B.FileIndexLow &&
636 A.FileSizeHigh == B.FileSizeHigh &&
637 A.FileSizeLow == B.FileSizeLow &&
638 A.LastAccessedTimeHigh == B.LastAccessedTimeHigh &&
639 A.LastAccessedTimeLow == B.LastAccessedTimeLow &&
640 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
641 A.LastWriteTimeLow == B.LastWriteTimeLow &&
642 A.VolumeSerialNumber == B.VolumeSerialNumber;
645 std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
646 file_status fsA, fsB;
647 if (std::error_code ec = status(A, fsA))
649 if (std::error_code ec = status(B, fsB))
651 result = equivalent(fsA, fsB);
652 return std::error_code();
655 static bool isReservedName(StringRef path) {
656 // This list of reserved names comes from MSDN, at:
657 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
658 static const char *const sReservedNames[] = { "nul", "con", "prn", "aux",
659 "com1", "com2", "com3", "com4",
660 "com5", "com6", "com7", "com8",
661 "com9", "lpt1", "lpt2", "lpt3",
662 "lpt4", "lpt5", "lpt6", "lpt7",
665 // First, check to see if this is a device namespace, which always
666 // starts with \\.\, since device namespaces are not legal file paths.
667 if (path.startswith("\\\\.\\"))
670 // Then compare against the list of ancient reserved names.
671 for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
672 if (path.equals_insensitive(sReservedNames[i]))
676 // The path isn't what we consider reserved.
680 static file_type file_type_from_attrs(DWORD Attrs) {
681 return (Attrs & FILE_ATTRIBUTE_DIRECTORY) ? file_type::directory_file
682 : file_type::regular_file;
685 static perms perms_from_attrs(DWORD Attrs) {
686 return (Attrs & FILE_ATTRIBUTE_READONLY) ? (all_read | all_exe) : all_all;
689 static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
690 if (FileHandle == INVALID_HANDLE_VALUE)
691 goto handle_status_error;
693 switch (::GetFileType(FileHandle)) {
695 llvm_unreachable("Don't know anything about this file type");
696 case FILE_TYPE_UNKNOWN: {
697 DWORD Err = ::GetLastError();
699 return mapWindowsError(Err);
700 Result = file_status(file_type::type_unknown);
701 return std::error_code();
706 Result = file_status(file_type::character_file);
707 return std::error_code();
709 Result = file_status(file_type::fifo_file);
710 return std::error_code();
713 BY_HANDLE_FILE_INFORMATION Info;
714 if (!::GetFileInformationByHandle(FileHandle, &Info))
715 goto handle_status_error;
717 Result = file_status(
718 file_type_from_attrs(Info.dwFileAttributes),
719 perms_from_attrs(Info.dwFileAttributes), Info.nNumberOfLinks,
720 Info.ftLastAccessTime.dwHighDateTime, Info.ftLastAccessTime.dwLowDateTime,
721 Info.ftLastWriteTime.dwHighDateTime, Info.ftLastWriteTime.dwLowDateTime,
722 Info.dwVolumeSerialNumber, Info.nFileSizeHigh, Info.nFileSizeLow,
723 Info.nFileIndexHigh, Info.nFileIndexLow);
724 return std::error_code();
727 DWORD LastError = ::GetLastError();
728 if (LastError == ERROR_FILE_NOT_FOUND ||
729 LastError == ERROR_PATH_NOT_FOUND)
730 Result = file_status(file_type::file_not_found);
731 else if (LastError == ERROR_SHARING_VIOLATION)
732 Result = file_status(file_type::type_unknown);
734 Result = file_status(file_type::status_error);
735 return mapWindowsError(LastError);
738 std::error_code status(const Twine &path, file_status &result, bool Follow) {
739 SmallString<128> path_storage;
740 SmallVector<wchar_t, 128> path_utf16;
742 StringRef path8 = path.toStringRef(path_storage);
743 if (isReservedName(path8)) {
744 result = file_status(file_type::character_file);
745 return std::error_code();
748 if (std::error_code ec = widenPath(path8, path_utf16))
751 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
752 if (attr == INVALID_FILE_ATTRIBUTES)
753 return getStatus(INVALID_HANDLE_VALUE, result);
755 DWORD Flags = FILE_FLAG_BACKUP_SEMANTICS;
756 // Handle reparse points.
757 if (!Follow && (attr & FILE_ATTRIBUTE_REPARSE_POINT))
758 Flags |= FILE_FLAG_OPEN_REPARSE_POINT;
761 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
762 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
763 NULL, OPEN_EXISTING, Flags, 0));
765 return getStatus(INVALID_HANDLE_VALUE, result);
767 return getStatus(h, result);
770 std::error_code status(int FD, file_status &Result) {
771 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
772 return getStatus(FileHandle, Result);
775 std::error_code status(file_t FileHandle, file_status &Result) {
776 return getStatus(FileHandle, Result);
779 unsigned getUmask() {
783 std::error_code setPermissions(const Twine &Path, perms Permissions) {
784 SmallVector<wchar_t, 128> PathUTF16;
785 if (std::error_code EC = widenPath(Path, PathUTF16))
788 DWORD Attributes = ::GetFileAttributesW(PathUTF16.begin());
789 if (Attributes == INVALID_FILE_ATTRIBUTES)
790 return mapWindowsError(GetLastError());
792 // There are many Windows file attributes that are not to do with the file
793 // permissions (e.g. FILE_ATTRIBUTE_HIDDEN). We need to be careful to preserve
795 if (Permissions & all_write) {
796 Attributes &= ~FILE_ATTRIBUTE_READONLY;
798 // FILE_ATTRIBUTE_NORMAL indicates no other attributes are set.
799 Attributes |= FILE_ATTRIBUTE_NORMAL;
802 Attributes |= FILE_ATTRIBUTE_READONLY;
803 // FILE_ATTRIBUTE_NORMAL is not compatible with any other attributes, so
804 // remove it, if it is present.
805 Attributes &= ~FILE_ATTRIBUTE_NORMAL;
808 if (!::SetFileAttributesW(PathUTF16.begin(), Attributes))
809 return mapWindowsError(GetLastError());
811 return std::error_code();
814 std::error_code setPermissions(int FD, perms Permissions) {
815 // FIXME Not implemented.
816 return std::make_error_code(std::errc::not_supported);
819 std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
820 TimePoint<> ModificationTime) {
821 FILETIME AccessFT = toFILETIME(AccessTime);
822 FILETIME ModifyFT = toFILETIME(ModificationTime);
823 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
824 if (!SetFileTime(FileHandle, NULL, &AccessFT, &ModifyFT))
825 return mapWindowsError(::GetLastError());
826 return std::error_code();
829 std::error_code mapped_file_region::init(sys::fs::file_t OrigFileHandle,
830 uint64_t Offset, mapmode Mode) {
832 if (OrigFileHandle == INVALID_HANDLE_VALUE)
833 return make_error_code(errc::bad_file_descriptor);
837 case readonly: flprotect = PAGE_READONLY; break;
838 case readwrite: flprotect = PAGE_READWRITE; break;
839 case priv: flprotect = PAGE_WRITECOPY; break;
842 HANDLE FileMappingHandle =
843 ::CreateFileMappingW(OrigFileHandle, 0, flprotect,
847 if (FileMappingHandle == NULL) {
848 std::error_code ec = mapWindowsError(GetLastError());
852 DWORD dwDesiredAccess;
854 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
855 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
856 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
858 Mapping = ::MapViewOfFile(FileMappingHandle,
863 if (Mapping == NULL) {
864 std::error_code ec = mapWindowsError(GetLastError());
865 ::CloseHandle(FileMappingHandle);
870 MEMORY_BASIC_INFORMATION mbi;
871 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
873 std::error_code ec = mapWindowsError(GetLastError());
874 ::UnmapViewOfFile(Mapping);
875 ::CloseHandle(FileMappingHandle);
878 Size = mbi.RegionSize;
881 // Close the file mapping handle, as it's kept alive by the file mapping. But
882 // neither the file mapping nor the file mapping handle keep the file handle
883 // alive, so we need to keep a reference to the file in case all other handles
884 // are closed and the file is deleted, which may cause invalid data to be read
886 ::CloseHandle(FileMappingHandle);
887 if (!::DuplicateHandle(::GetCurrentProcess(), OrigFileHandle,
888 ::GetCurrentProcess(), &FileHandle, 0, 0,
889 DUPLICATE_SAME_ACCESS)) {
890 std::error_code ec = mapWindowsError(GetLastError());
891 ::UnmapViewOfFile(Mapping);
895 return std::error_code();
898 mapped_file_region::mapped_file_region(sys::fs::file_t fd, mapmode mode,
899 size_t length, uint64_t offset,
902 ec = init(fd, offset, mode);
904 copyFrom(mapped_file_region());
907 static bool hasFlushBufferKernelBug() {
908 static bool Ret{GetWindowsOSVersion() < llvm::VersionTuple(10, 0, 0, 17763)};
912 static bool isEXE(StringRef Magic) {
913 static const char PEMagic[] = {'P', 'E', '\0', '\0'};
914 if (Magic.startswith(StringRef("MZ")) && Magic.size() >= 0x3c + 4) {
915 uint32_t off = read32le(Magic.data() + 0x3c);
916 // PE/COFF file, either EXE or DLL.
917 if (Magic.substr(off).startswith(StringRef(PEMagic, sizeof(PEMagic))))
923 void mapped_file_region::unmapImpl() {
926 bool Exe = isEXE(StringRef((char *)Mapping, Size));
928 ::UnmapViewOfFile(Mapping);
930 if (Mode == mapmode::readwrite && Exe && hasFlushBufferKernelBug()) {
931 // There is a Windows kernel bug, the exact trigger conditions of which
932 // are not well understood. When triggered, dirty pages are not properly
933 // flushed and subsequent process's attempts to read a file can return
934 // invalid data. Calling FlushFileBuffers on the write handle is
935 // sufficient to ensure that this bug is not triggered.
936 // The bug only occurs when writing an executable and executing it right
937 // after, under high I/O pressure.
938 ::FlushFileBuffers(FileHandle);
941 ::CloseHandle(FileHandle);
945 int mapped_file_region::alignment() {
947 ::GetSystemInfo(&SysInfo);
948 return SysInfo.dwAllocationGranularity;
951 static basic_file_status status_from_find_data(WIN32_FIND_DATAW *FindData) {
952 return basic_file_status(file_type_from_attrs(FindData->dwFileAttributes),
953 perms_from_attrs(FindData->dwFileAttributes),
954 FindData->ftLastAccessTime.dwHighDateTime,
955 FindData->ftLastAccessTime.dwLowDateTime,
956 FindData->ftLastWriteTime.dwHighDateTime,
957 FindData->ftLastWriteTime.dwLowDateTime,
958 FindData->nFileSizeHigh, FindData->nFileSizeLow);
961 std::error_code detail::directory_iterator_construct(detail::DirIterState &IT,
963 bool FollowSymlinks) {
964 SmallVector<wchar_t, 128> PathUTF16;
966 if (std::error_code EC = widenPath(Path, PathUTF16))
969 // Convert path to the format that Windows is happy with.
970 size_t PathUTF16Len = PathUTF16.size();
971 if (PathUTF16Len > 0 && !is_separator(PathUTF16[PathUTF16Len - 1]) &&
972 PathUTF16[PathUTF16Len - 1] != L':') {
973 PathUTF16.push_back(L'\\');
974 PathUTF16.push_back(L'*');
976 PathUTF16.push_back(L'*');
979 // Get the first directory entry.
980 WIN32_FIND_DATAW FirstFind;
981 ScopedFindHandle FindHandle(::FindFirstFileExW(
982 c_str(PathUTF16), FindExInfoBasic, &FirstFind, FindExSearchNameMatch,
983 NULL, FIND_FIRST_EX_LARGE_FETCH));
985 return mapWindowsError(::GetLastError());
987 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
988 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
989 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
990 FirstFind.cFileName[1] == L'.'))
991 if (!::FindNextFileW(FindHandle, &FirstFind)) {
992 DWORD LastError = ::GetLastError();
994 if (LastError == ERROR_NO_MORE_FILES)
995 return detail::directory_iterator_destruct(IT);
996 return mapWindowsError(LastError);
998 FilenameLen = ::wcslen(FirstFind.cFileName);
1000 // Construct the current directory entry.
1001 SmallString<128> DirectoryEntryNameUTF8;
1002 if (std::error_code EC =
1003 UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
1004 DirectoryEntryNameUTF8))
1007 IT.IterationHandle = intptr_t(FindHandle.take());
1008 SmallString<128> DirectoryEntryPath(Path);
1009 path::append(DirectoryEntryPath, DirectoryEntryNameUTF8);
1011 directory_entry(DirectoryEntryPath, FollowSymlinks,
1012 file_type_from_attrs(FirstFind.dwFileAttributes),
1013 status_from_find_data(&FirstFind));
1015 return std::error_code();
1018 std::error_code detail::directory_iterator_destruct(detail::DirIterState &IT) {
1019 if (IT.IterationHandle != 0)
1020 // Closes the handle if it's valid.
1021 ScopedFindHandle close(HANDLE(IT.IterationHandle));
1022 IT.IterationHandle = 0;
1023 IT.CurrentEntry = directory_entry();
1024 return std::error_code();
1027 std::error_code detail::directory_iterator_increment(detail::DirIterState &IT) {
1028 WIN32_FIND_DATAW FindData;
1029 if (!::FindNextFileW(HANDLE(IT.IterationHandle), &FindData)) {
1030 DWORD LastError = ::GetLastError();
1032 if (LastError == ERROR_NO_MORE_FILES)
1033 return detail::directory_iterator_destruct(IT);
1034 return mapWindowsError(LastError);
1037 size_t FilenameLen = ::wcslen(FindData.cFileName);
1038 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
1039 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
1040 FindData.cFileName[1] == L'.'))
1041 return directory_iterator_increment(IT);
1043 SmallString<128> DirectoryEntryPathUTF8;
1044 if (std::error_code EC =
1045 UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
1046 DirectoryEntryPathUTF8))
1049 IT.CurrentEntry.replace_filename(
1050 Twine(DirectoryEntryPathUTF8),
1051 file_type_from_attrs(FindData.dwFileAttributes),
1052 status_from_find_data(&FindData));
1053 return std::error_code();
1056 ErrorOr<basic_file_status> directory_entry::status() const {
1060 static std::error_code nativeFileToFd(Expected<HANDLE> H, int &ResultFD,
1062 int CrtOpenFlags = 0;
1063 if (Flags & OF_Append)
1064 CrtOpenFlags |= _O_APPEND;
1066 if (Flags & OF_CRLF) {
1067 assert(Flags & OF_Text && "Flags set OF_CRLF without OF_Text");
1068 CrtOpenFlags |= _O_TEXT;
1073 return errorToErrorCode(H.takeError());
1075 ResultFD = ::_open_osfhandle(intptr_t(*H), CrtOpenFlags);
1076 if (ResultFD == -1) {
1078 return mapWindowsError(ERROR_INVALID_HANDLE);
1080 return std::error_code();
1083 static DWORD nativeDisposition(CreationDisposition Disp, OpenFlags Flags) {
1084 // This is a compatibility hack. Really we should respect the creation
1085 // disposition, but a lot of old code relied on the implicit assumption that
1086 // OF_Append implied it would open an existing file. Since the disposition is
1087 // now explicit and defaults to CD_CreateAlways, this assumption would cause
1088 // any usage of OF_Append to append to a new file, even if the file already
1089 // existed. A better solution might have two new creation dispositions:
1090 // CD_AppendAlways and CD_AppendNew. This would also address the problem of
1091 // OF_Append being used on a read-only descriptor, which doesn't make sense.
1092 if (Flags & OF_Append)
1096 case CD_CreateAlways:
1097 return CREATE_ALWAYS;
1102 case CD_OpenExisting:
1103 return OPEN_EXISTING;
1105 llvm_unreachable("unreachable!");
1108 static DWORD nativeAccess(FileAccess Access, OpenFlags Flags) {
1110 if (Access & FA_Read)
1111 Result |= GENERIC_READ;
1112 if (Access & FA_Write)
1113 Result |= GENERIC_WRITE;
1114 if (Flags & OF_Delete)
1116 if (Flags & OF_UpdateAtime)
1117 Result |= FILE_WRITE_ATTRIBUTES;
1121 static std::error_code openNativeFileInternal(const Twine &Name,
1122 file_t &ResultFile, DWORD Disp,
1123 DWORD Access, DWORD Flags,
1124 bool Inherit = false) {
1125 SmallVector<wchar_t, 128> PathUTF16;
1126 if (std::error_code EC = widenPath(Name, PathUTF16))
1129 SECURITY_ATTRIBUTES SA;
1130 SA.nLength = sizeof(SA);
1131 SA.lpSecurityDescriptor = nullptr;
1132 SA.bInheritHandle = Inherit;
1135 ::CreateFileW(PathUTF16.begin(), Access,
1136 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &SA,
1138 if (H == INVALID_HANDLE_VALUE) {
1139 DWORD LastError = ::GetLastError();
1140 std::error_code EC = mapWindowsError(LastError);
1141 // Provide a better error message when trying to open directories.
1142 // This only runs if we failed to open the file, so there is probably
1143 // no performances issues.
1144 if (LastError != ERROR_ACCESS_DENIED)
1146 if (is_directory(Name))
1147 return make_error_code(errc::is_a_directory);
1151 return std::error_code();
1154 Expected<file_t> openNativeFile(const Twine &Name, CreationDisposition Disp,
1155 FileAccess Access, OpenFlags Flags,
1157 // Verify that we don't have both "append" and "excl".
1158 assert((!(Disp == CD_CreateNew) || !(Flags & OF_Append)) &&
1159 "Cannot specify both 'CreateNew' and 'Append' file creation flags!");
1161 DWORD NativeDisp = nativeDisposition(Disp, Flags);
1162 DWORD NativeAccess = nativeAccess(Access, Flags);
1164 bool Inherit = false;
1165 if (Flags & OF_ChildInherit)
1169 std::error_code EC = openNativeFileInternal(
1170 Name, Result, NativeDisp, NativeAccess, FILE_ATTRIBUTE_NORMAL, Inherit);
1172 return errorCodeToError(EC);
1174 if (Flags & OF_UpdateAtime) {
1176 SYSTEMTIME SystemTime;
1177 GetSystemTime(&SystemTime);
1178 if (SystemTimeToFileTime(&SystemTime, &FileTime) == 0 ||
1179 SetFileTime(Result, NULL, &FileTime, NULL) == 0) {
1180 DWORD LastError = ::GetLastError();
1181 ::CloseHandle(Result);
1182 return errorCodeToError(mapWindowsError(LastError));
1186 if (Flags & OF_Delete) {
1187 if ((EC = setDeleteDisposition(Result, true))) {
1188 ::CloseHandle(Result);
1189 return errorCodeToError(EC);
1195 std::error_code openFile(const Twine &Name, int &ResultFD,
1196 CreationDisposition Disp, FileAccess Access,
1197 OpenFlags Flags, unsigned int Mode) {
1198 Expected<file_t> Result = openNativeFile(Name, Disp, Access, Flags);
1200 return errorToErrorCode(Result.takeError());
1202 return nativeFileToFd(*Result, ResultFD, Flags);
1205 static std::error_code directoryRealPath(const Twine &Name,
1206 SmallVectorImpl<char> &RealPath) {
1208 std::error_code EC = openNativeFileInternal(
1209 Name, File, OPEN_EXISTING, GENERIC_READ, FILE_FLAG_BACKUP_SEMANTICS);
1213 EC = realPathFromHandle(File, RealPath);
1214 ::CloseHandle(File);
1218 std::error_code openFileForRead(const Twine &Name, int &ResultFD,
1220 SmallVectorImpl<char> *RealPath) {
1221 Expected<HANDLE> NativeFile = openNativeFileForRead(Name, Flags, RealPath);
1222 return nativeFileToFd(std::move(NativeFile), ResultFD, OF_None);
1225 Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
1226 SmallVectorImpl<char> *RealPath) {
1227 Expected<file_t> Result =
1228 openNativeFile(Name, CD_OpenExisting, FA_Read, Flags);
1230 // Fetch the real name of the file, if the user asked
1231 if (Result && RealPath)
1232 realPathFromHandle(*Result, *RealPath);
1237 file_t convertFDToNativeFile(int FD) {
1238 return reinterpret_cast<HANDLE>(::_get_osfhandle(FD));
1241 file_t getStdinHandle() { return ::GetStdHandle(STD_INPUT_HANDLE); }
1242 file_t getStdoutHandle() { return ::GetStdHandle(STD_OUTPUT_HANDLE); }
1243 file_t getStderrHandle() { return ::GetStdHandle(STD_ERROR_HANDLE); }
1245 Expected<size_t> readNativeFileImpl(file_t FileHandle,
1246 MutableArrayRef<char> Buf,
1247 OVERLAPPED *Overlap) {
1248 // ReadFile can only read 2GB at a time. The caller should check the number of
1249 // bytes and read in a loop until termination.
1251 std::min(size_t(std::numeric_limits<DWORD>::max()), Buf.size());
1252 DWORD BytesRead = 0;
1253 if (::ReadFile(FileHandle, Buf.data(), BytesToRead, &BytesRead, Overlap))
1255 DWORD Err = ::GetLastError();
1256 // EOF is not an error.
1257 if (Err == ERROR_BROKEN_PIPE || Err == ERROR_HANDLE_EOF)
1259 return errorCodeToError(mapWindowsError(Err));
1262 Expected<size_t> readNativeFile(file_t FileHandle, MutableArrayRef<char> Buf) {
1263 return readNativeFileImpl(FileHandle, Buf, /*Overlap=*/nullptr);
1266 Expected<size_t> readNativeFileSlice(file_t FileHandle,
1267 MutableArrayRef<char> Buf,
1269 OVERLAPPED Overlapped = {};
1270 Overlapped.Offset = uint32_t(Offset);
1271 Overlapped.OffsetHigh = uint32_t(Offset >> 32);
1272 return readNativeFileImpl(FileHandle, Buf, &Overlapped);
1275 std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout) {
1276 DWORD Flags = LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY;
1278 file_t File = convertFDToNativeFile(FD);
1279 auto Start = std::chrono::steady_clock::now();
1280 auto End = Start + Timeout;
1282 if (::LockFileEx(File, Flags, 0, MAXDWORD, MAXDWORD, &OV))
1283 return std::error_code();
1284 DWORD Error = ::GetLastError();
1285 if (Error == ERROR_LOCK_VIOLATION) {
1289 return mapWindowsError(Error);
1290 } while (std::chrono::steady_clock::now() < End);
1291 return mapWindowsError(ERROR_LOCK_VIOLATION);
1294 std::error_code lockFile(int FD) {
1295 DWORD Flags = LOCKFILE_EXCLUSIVE_LOCK;
1297 file_t File = convertFDToNativeFile(FD);
1298 if (::LockFileEx(File, Flags, 0, MAXDWORD, MAXDWORD, &OV))
1299 return std::error_code();
1300 DWORD Error = ::GetLastError();
1301 return mapWindowsError(Error);
1304 std::error_code unlockFile(int FD) {
1306 file_t File = convertFDToNativeFile(FD);
1307 if (::UnlockFileEx(File, 0, MAXDWORD, MAXDWORD, &OV))
1308 return std::error_code();
1309 return mapWindowsError(::GetLastError());
1312 std::error_code closeFile(file_t &F) {
1315 if (!::CloseHandle(TmpF))
1316 return mapWindowsError(::GetLastError());
1317 return std::error_code();
1320 std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1321 // Convert to utf-16.
1322 SmallVector<wchar_t, 128> Path16;
1323 std::error_code EC = widenPath(path, Path16);
1324 if (EC && !IgnoreErrors)
1327 // SHFileOperation() accepts a list of paths, and so must be double null-
1328 // terminated to indicate the end of the list. The buffer is already null
1329 // terminated, but since that null character is not considered part of the
1330 // vector's size, pushing another one will just consume that byte. So we
1331 // need to push 2 null terminators.
1332 Path16.push_back(0);
1333 Path16.push_back(0);
1335 SHFILEOPSTRUCTW shfos = {};
1336 shfos.wFunc = FO_DELETE;
1337 shfos.pFrom = Path16.data();
1338 shfos.fFlags = FOF_NO_UI;
1340 int result = ::SHFileOperationW(&shfos);
1341 if (result != 0 && !IgnoreErrors)
1342 return mapWindowsError(result);
1343 return std::error_code();
1346 static void expandTildeExpr(SmallVectorImpl<char> &Path) {
1347 // Path does not begin with a tilde expression.
1348 if (Path.empty() || Path[0] != '~')
1351 StringRef PathStr(Path.begin(), Path.size());
1352 PathStr = PathStr.drop_front();
1353 StringRef Expr = PathStr.take_until([](char c) { return path::is_separator(c); });
1355 if (!Expr.empty()) {
1356 // This is probably a ~username/ expression. Don't support this on Windows.
1360 SmallString<128> HomeDir;
1361 if (!path::home_directory(HomeDir)) {
1362 // For some reason we couldn't get the home directory. Just exit.
1366 // Overwrite the first character and insert the rest.
1367 Path[0] = HomeDir[0];
1368 Path.insert(Path.begin() + 1, HomeDir.begin() + 1, HomeDir.end());
1371 void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
1373 if (path.isTriviallyEmpty())
1376 path.toVector(dest);
1377 expandTildeExpr(dest);
1382 std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1383 bool expand_tilde) {
1385 if (path.isTriviallyEmpty())
1386 return std::error_code();
1389 SmallString<128> Storage;
1390 path.toVector(Storage);
1391 expandTildeExpr(Storage);
1392 return real_path(Storage, dest, false);
1395 if (is_directory(path))
1396 return directoryRealPath(path, dest);
1399 if (std::error_code EC =
1400 llvm::sys::fs::openFileForRead(path, fd, OF_None, &dest))
1403 return std::error_code();
1406 } // end namespace fs
1409 static bool getKnownFolderPath(KNOWNFOLDERID folderId,
1410 SmallVectorImpl<char> &result) {
1411 wchar_t *path = nullptr;
1412 if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK)
1415 bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
1416 ::CoTaskMemFree(path);
1420 bool home_directory(SmallVectorImpl<char> &result) {
1421 return getKnownFolderPath(FOLDERID_Profile, result);
1424 bool user_config_directory(SmallVectorImpl<char> &result) {
1425 // Either local or roaming appdata may be suitable in some cases, depending
1426 // on the data. Local is more conservative, Roaming may not always be correct.
1427 return getKnownFolderPath(FOLDERID_LocalAppData, result);
1430 bool cache_directory(SmallVectorImpl<char> &result) {
1431 return getKnownFolderPath(FOLDERID_LocalAppData, result);
1434 static bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {
1435 SmallVector<wchar_t, 1024> Buf;
1439 Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.capacity());
1443 // Try again with larger buffer.
1444 } while (Size > Buf.capacity());
1447 return !windows::UTF16ToUTF8(Buf.data(), Size, Res);
1450 static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
1451 const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};
1452 for (auto *Env : EnvironmentVariables) {
1453 if (getTempDirEnvVar(Env, Res))
1459 void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1460 (void)ErasedOnReboot;
1463 // Check whether the temporary directory is specified by an environment var.
1464 // This matches GetTempPath logic to some degree. GetTempPath is not used
1465 // directly as it cannot handle evn var longer than 130 chars on Windows 7
1466 // (fixed on Windows 8).
1467 if (getTempDirEnvVar(Result)) {
1468 assert(!Result.empty() && "Unexpected empty path");
1469 native(Result); // Some Unix-like shells use Unix path separator in $TMP.
1470 fs::make_absolute(Result); // Make it absolute if not already.
1474 // Fall back to a system default.
1475 const char *DefaultResult = "C:\\Temp";
1476 Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
1478 } // end namespace path
1481 std::error_code CodePageToUTF16(unsigned codepage,
1482 llvm::StringRef original,
1483 llvm::SmallVectorImpl<wchar_t> &utf16) {
1484 if (!original.empty()) {
1485 int len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1486 original.size(), utf16.begin(), 0);
1489 return mapWindowsError(::GetLastError());
1492 utf16.reserve(len + 1);
1493 utf16.set_size(len);
1495 len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1496 original.size(), utf16.begin(), utf16.size());
1499 return mapWindowsError(::GetLastError());
1503 // Make utf16 null terminated.
1507 return std::error_code();
1510 std::error_code UTF8ToUTF16(llvm::StringRef utf8,
1511 llvm::SmallVectorImpl<wchar_t> &utf16) {
1512 return CodePageToUTF16(CP_UTF8, utf8, utf16);
1515 std::error_code CurCPToUTF16(llvm::StringRef curcp,
1516 llvm::SmallVectorImpl<wchar_t> &utf16) {
1517 return CodePageToUTF16(CP_ACP, curcp, utf16);
1521 std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
1523 llvm::SmallVectorImpl<char> &converted) {
1526 int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.begin(),
1530 return mapWindowsError(::GetLastError());
1533 converted.reserve(len);
1534 converted.set_size(len);
1536 // Now do the actual conversion.
1537 len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.data(),
1538 converted.size(), NULL, NULL);
1541 return mapWindowsError(::GetLastError());
1545 // Make the new string null terminated.
1546 converted.push_back(0);
1547 converted.pop_back();
1549 return std::error_code();
1552 std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
1553 llvm::SmallVectorImpl<char> &utf8) {
1554 return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
1557 std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
1558 llvm::SmallVectorImpl<char> &curcp) {
1559 return UTF16ToCodePage(CP_ACP, utf16, utf16_len, curcp);
1562 } // end namespace windows
1563 } // end namespace sys
1564 } // end namespace llvm