1 //===- llvm/Support/Windows/Path.inc - Windows Path Impl --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Windows specific implementation of the Path API.
12 //===----------------------------------------------------------------------===//
14 //===----------------------------------------------------------------------===//
15 //=== WARNING: Implementation here must contain only generic Windows code that
16 //=== is guaranteed to work on *all* Windows variants.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/Support/WindowsError.h"
24 #include <sys/types.h>
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"
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.
45 using llvm::sys::windows::UTF8ToUTF16;
46 using llvm::sys::windows::UTF16ToUTF8;
48 static std::error_code windows_error(DWORD E) {
49 return mapWindowsError(E);
52 static bool is_separator(const wchar_t value) {
66 std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
67 SmallVector<wchar_t, MAX_PATH> PathName;
68 DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
70 // A zero return value indicates a failure other than insufficient space.
74 // Insufficient space is determined by a return value equal to the size of
75 // the buffer passed in.
76 if (Size == PathName.capacity())
79 // On success, GetModuleFileNameW returns the number of characters written to
80 // the buffer not including the NULL terminator.
81 PathName.set_size(Size);
83 // Convert the result from UTF-16 to UTF-8.
84 SmallVector<char, MAX_PATH> PathNameUTF8;
85 if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
88 return std::string(PathNameUTF8.data());
91 UniqueID file_status::getUniqueID() const {
92 // The file is uniquely identified by the volume serial number along
93 // with the 64-bit file identifier.
94 uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
95 static_cast<uint64_t>(FileIndexLow);
97 return UniqueID(VolumeSerialNumber, FileID);
100 TimeValue file_status::getLastModificationTime() const {
102 UI.LowPart = LastWriteTimeLow;
103 UI.HighPart = LastWriteTimeHigh;
106 Ret.fromWin32Time(UI.QuadPart);
110 std::error_code current_path(SmallVectorImpl<char> &result) {
111 SmallVector<wchar_t, MAX_PATH> cur_path;
112 DWORD len = MAX_PATH;
115 cur_path.reserve(len);
116 len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
118 // A zero return value indicates a failure other than insufficient space.
120 return windows_error(::GetLastError());
122 // If there's insufficient space, the len returned is larger than the len
124 } while (len > cur_path.capacity());
126 // On success, GetCurrentDirectoryW returns the number of characters not
127 // including the null-terminator.
128 cur_path.set_size(len);
129 return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
132 std::error_code create_directory(const Twine &path, bool IgnoreExisting) {
133 SmallString<128> path_storage;
134 SmallVector<wchar_t, 128> path_utf16;
136 if (std::error_code ec =
137 UTF8ToUTF16(path.toStringRef(path_storage), path_utf16))
140 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
141 DWORD LastError = ::GetLastError();
142 if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
143 return windows_error(LastError);
146 return std::error_code();
149 // We can't use symbolic links for windows.
150 std::error_code create_link(const Twine &to, const Twine &from) {
152 SmallString<128> from_storage;
153 SmallString<128> to_storage;
154 StringRef f = from.toStringRef(from_storage);
155 StringRef t = to.toStringRef(to_storage);
157 // Convert to utf-16.
158 SmallVector<wchar_t, 128> wide_from;
159 SmallVector<wchar_t, 128> wide_to;
160 if (std::error_code ec = UTF8ToUTF16(f, wide_from))
162 if (std::error_code ec = UTF8ToUTF16(t, wide_to))
165 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
166 return windows_error(::GetLastError());
168 return std::error_code();
171 std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
172 SmallString<128> path_storage;
173 SmallVector<wchar_t, 128> path_utf16;
176 if (std::error_code EC = status(path, ST)) {
177 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
179 return std::error_code();
182 if (std::error_code ec =
183 UTF8ToUTF16(path.toStringRef(path_storage), path_utf16))
186 if (ST.type() == file_type::directory_file) {
187 if (!::RemoveDirectoryW(c_str(path_utf16))) {
188 std::error_code EC = windows_error(::GetLastError());
189 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
192 return std::error_code();
194 if (!::DeleteFileW(c_str(path_utf16))) {
195 std::error_code EC = windows_error(::GetLastError());
196 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
199 return std::error_code();
202 std::error_code rename(const Twine &from, const Twine &to) {
204 SmallString<128> from_storage;
205 SmallString<128> to_storage;
206 StringRef f = from.toStringRef(from_storage);
207 StringRef t = to.toStringRef(to_storage);
209 // Convert to utf-16.
210 SmallVector<wchar_t, 128> wide_from;
211 SmallVector<wchar_t, 128> wide_to;
212 if (std::error_code ec = UTF8ToUTF16(f, wide_from))
214 if (std::error_code ec = UTF8ToUTF16(t, wide_to))
217 std::error_code ec = std::error_code();
218 for (int i = 0; i < 2000; i++) {
219 if (::MoveFileExW(wide_from.begin(), wide_to.begin(),
220 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
221 return std::error_code();
222 DWORD LastError = ::GetLastError();
223 if (LastError != ERROR_ACCESS_DENIED)
225 // Retry MoveFile() at ACCESS_DENIED.
226 // System scanners (eg. indexer) might open the source file when
227 // It is written and closed.
234 std::error_code resize_file(const Twine &path, uint64_t size) {
235 SmallString<128> path_storage;
236 SmallVector<wchar_t, 128> path_utf16;
238 if (std::error_code ec =
239 UTF8ToUTF16(path.toStringRef(path_storage), path_utf16))
242 int fd = ::_wopen(path_utf16.begin(), O_BINARY | _O_RDWR, S_IWRITE);
244 return std::error_code(errno, std::generic_category());
245 #ifdef HAVE__CHSIZE_S
246 errno_t error = ::_chsize_s(fd, size);
248 errno_t error = ::_chsize(fd, size);
251 return std::error_code(error, std::generic_category());
254 std::error_code access(const Twine &Path, AccessMode Mode) {
255 SmallString<128> PathStorage;
256 SmallVector<wchar_t, 128> PathUtf16;
258 if (std::error_code EC =
259 UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
262 DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
264 if (Attributes == INVALID_FILE_ATTRIBUTES) {
265 // See if the file didn't actually exist.
266 DWORD LastError = ::GetLastError();
267 if (LastError != ERROR_FILE_NOT_FOUND &&
268 LastError != ERROR_PATH_NOT_FOUND)
269 return windows_error(LastError);
270 return errc::no_such_file_or_directory;
273 if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
274 return errc::permission_denied;
276 return std::error_code();
279 bool equivalent(file_status A, file_status B) {
280 assert(status_known(A) && status_known(B));
281 return A.FileIndexHigh == B.FileIndexHigh &&
282 A.FileIndexLow == B.FileIndexLow &&
283 A.FileSizeHigh == B.FileSizeHigh &&
284 A.FileSizeLow == B.FileSizeLow &&
285 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
286 A.LastWriteTimeLow == B.LastWriteTimeLow &&
287 A.VolumeSerialNumber == B.VolumeSerialNumber;
290 std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
291 file_status fsA, fsB;
292 if (std::error_code ec = status(A, fsA))
294 if (std::error_code ec = status(B, fsB))
296 result = equivalent(fsA, fsB);
297 return std::error_code();
300 static bool isReservedName(StringRef path) {
301 // This list of reserved names comes from MSDN, at:
302 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
303 static const char *sReservedNames[] = { "nul", "con", "prn", "aux",
304 "com1", "com2", "com3", "com4", "com5", "com6",
305 "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
306 "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9" };
308 // First, check to see if this is a device namespace, which always
309 // starts with \\.\, since device namespaces are not legal file paths.
310 if (path.startswith("\\\\.\\"))
313 // Then compare against the list of ancient reserved names
314 for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
315 if (path.equals_lower(sReservedNames[i]))
319 // The path isn't what we consider reserved.
323 static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
324 if (FileHandle == INVALID_HANDLE_VALUE)
325 goto handle_status_error;
327 switch (::GetFileType(FileHandle)) {
329 llvm_unreachable("Don't know anything about this file type");
330 case FILE_TYPE_UNKNOWN: {
331 DWORD Err = ::GetLastError();
333 return windows_error(Err);
334 Result = file_status(file_type::type_unknown);
335 return std::error_code();
340 Result = file_status(file_type::character_file);
341 return std::error_code();
343 Result = file_status(file_type::fifo_file);
344 return std::error_code();
347 BY_HANDLE_FILE_INFORMATION Info;
348 if (!::GetFileInformationByHandle(FileHandle, &Info))
349 goto handle_status_error;
352 file_type Type = (Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
353 ? file_type::directory_file
354 : file_type::regular_file;
356 file_status(Type, Info.ftLastWriteTime.dwHighDateTime,
357 Info.ftLastWriteTime.dwLowDateTime,
358 Info.dwVolumeSerialNumber, Info.nFileSizeHigh,
359 Info.nFileSizeLow, Info.nFileIndexHigh, Info.nFileIndexLow);
360 return std::error_code();
364 DWORD LastError = ::GetLastError();
365 if (LastError == ERROR_FILE_NOT_FOUND ||
366 LastError == ERROR_PATH_NOT_FOUND)
367 Result = file_status(file_type::file_not_found);
368 else if (LastError == ERROR_SHARING_VIOLATION)
369 Result = file_status(file_type::type_unknown);
371 Result = file_status(file_type::status_error);
372 return windows_error(LastError);
375 std::error_code status(const Twine &path, file_status &result) {
376 SmallString<128> path_storage;
377 SmallVector<wchar_t, 128> path_utf16;
379 StringRef path8 = path.toStringRef(path_storage);
380 if (isReservedName(path8)) {
381 result = file_status(file_type::character_file);
382 return std::error_code();
385 if (std::error_code ec = UTF8ToUTF16(path8, path_utf16))
388 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
389 if (attr == INVALID_FILE_ATTRIBUTES)
390 return getStatus(INVALID_HANDLE_VALUE, result);
392 // Handle reparse points.
393 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
395 ::CreateFileW(path_utf16.begin(),
396 0, // Attributes only.
397 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
400 FILE_FLAG_BACKUP_SEMANTICS,
403 return getStatus(INVALID_HANDLE_VALUE, result);
407 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
408 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
409 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0));
411 return getStatus(INVALID_HANDLE_VALUE, result);
413 return getStatus(h, result);
416 std::error_code status(int FD, file_status &Result) {
417 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
418 return getStatus(FileHandle, Result);
421 std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
423 UI.QuadPart = Time.toWin32Time();
425 FT.dwLowDateTime = UI.LowPart;
426 FT.dwHighDateTime = UI.HighPart;
427 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
428 if (!SetFileTime(FileHandle, NULL, &FT, &FT))
429 return windows_error(::GetLastError());
430 return std::error_code();
433 std::error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
435 // Make sure that the requested size fits within SIZE_T.
436 if (Size > std::numeric_limits<SIZE_T>::max()) {
437 if (FileDescriptor) {
439 _close(FileDescriptor);
441 ::CloseHandle(FileHandle);
442 return make_error_code(errc::invalid_argument);
447 case readonly: flprotect = PAGE_READONLY; break;
448 case readwrite: flprotect = PAGE_READWRITE; break;
449 case priv: flprotect = PAGE_WRITECOPY; break;
453 ::CreateFileMappingW(FileHandle, 0, flprotect,
454 (Offset + Size) >> 32,
455 (Offset + Size) & 0xffffffff,
457 if (FileMappingHandle == NULL) {
458 std::error_code ec = windows_error(GetLastError());
459 if (FileDescriptor) {
461 _close(FileDescriptor);
463 ::CloseHandle(FileHandle);
467 DWORD dwDesiredAccess;
469 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
470 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
471 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
473 Mapping = ::MapViewOfFile(FileMappingHandle,
478 if (Mapping == NULL) {
479 std::error_code ec = windows_error(GetLastError());
480 ::CloseHandle(FileMappingHandle);
481 if (FileDescriptor) {
483 _close(FileDescriptor);
485 ::CloseHandle(FileHandle);
490 MEMORY_BASIC_INFORMATION mbi;
491 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
493 std::error_code ec = windows_error(GetLastError());
494 ::UnmapViewOfFile(Mapping);
495 ::CloseHandle(FileMappingHandle);
496 if (FileDescriptor) {
498 _close(FileDescriptor);
500 ::CloseHandle(FileHandle);
503 Size = mbi.RegionSize;
506 // Close all the handles except for the view. It will keep the other handles
508 ::CloseHandle(FileMappingHandle);
509 if (FileDescriptor) {
511 _close(FileDescriptor); // Also closes FileHandle.
513 ::CloseHandle(FileHandle);
514 return std::error_code();
517 mapped_file_region::mapped_file_region(const Twine &path,
526 , FileHandle(INVALID_HANDLE_VALUE)
527 , FileMappingHandle() {
528 SmallString<128> path_storage;
529 SmallVector<wchar_t, 128> path_utf16;
531 // Convert path to UTF-16.
532 if ((ec = UTF8ToUTF16(path.toStringRef(path_storage), path_utf16)))
535 // Get file handle for creating a file mapping.
536 FileHandle = ::CreateFileW(c_str(path_utf16),
537 Mode == readonly ? GENERIC_READ
538 : GENERIC_READ | GENERIC_WRITE,
539 Mode == readonly ? FILE_SHARE_READ
542 Mode == readonly ? OPEN_EXISTING
544 Mode == readonly ? FILE_ATTRIBUTE_READONLY
545 : FILE_ATTRIBUTE_NORMAL,
547 if (FileHandle == INVALID_HANDLE_VALUE) {
548 ec = windows_error(::GetLastError());
553 ec = init(FileDescriptor, true, offset);
555 Mapping = FileMappingHandle = 0;
556 FileHandle = INVALID_HANDLE_VALUE;
561 mapped_file_region::mapped_file_region(int fd,
571 , FileHandle(INVALID_HANDLE_VALUE)
572 , FileMappingHandle() {
573 FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
574 if (FileHandle == INVALID_HANDLE_VALUE) {
576 _close(FileDescriptor);
578 ec = make_error_code(errc::bad_file_descriptor);
582 ec = init(FileDescriptor, closefd, offset);
584 Mapping = FileMappingHandle = 0;
585 FileHandle = INVALID_HANDLE_VALUE;
590 mapped_file_region::~mapped_file_region() {
592 ::UnmapViewOfFile(Mapping);
595 mapped_file_region::mapped_file_region(mapped_file_region &&other)
598 , Mapping(other.Mapping)
599 , FileDescriptor(other.FileDescriptor)
600 , FileHandle(other.FileHandle)
601 , FileMappingHandle(other.FileMappingHandle) {
602 other.Mapping = other.FileMappingHandle = 0;
603 other.FileHandle = INVALID_HANDLE_VALUE;
604 other.FileDescriptor = 0;
607 mapped_file_region::mapmode mapped_file_region::flags() const {
608 assert(Mapping && "Mapping failed but used anyway!");
612 uint64_t mapped_file_region::size() const {
613 assert(Mapping && "Mapping failed but used anyway!");
617 char *mapped_file_region::data() const {
618 assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
619 assert(Mapping && "Mapping failed but used anyway!");
620 return reinterpret_cast<char*>(Mapping);
623 const char *mapped_file_region::const_data() const {
624 assert(Mapping && "Mapping failed but used anyway!");
625 return reinterpret_cast<const char*>(Mapping);
628 int mapped_file_region::alignment() {
630 ::GetSystemInfo(&SysInfo);
631 return SysInfo.dwAllocationGranularity;
634 std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
636 SmallVector<wchar_t, 128> path_utf16;
638 if (std::error_code ec = UTF8ToUTF16(path, path_utf16))
641 // Convert path to the format that Windows is happy with.
642 if (path_utf16.size() > 0 &&
643 !is_separator(path_utf16[path.size() - 1]) &&
644 path_utf16[path.size() - 1] != L':') {
645 path_utf16.push_back(L'\\');
646 path_utf16.push_back(L'*');
648 path_utf16.push_back(L'*');
651 // Get the first directory entry.
652 WIN32_FIND_DATAW FirstFind;
653 ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
655 return windows_error(::GetLastError());
657 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
658 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
659 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
660 FirstFind.cFileName[1] == L'.'))
661 if (!::FindNextFileW(FindHandle, &FirstFind)) {
662 DWORD LastError = ::GetLastError();
664 if (LastError == ERROR_NO_MORE_FILES)
665 return detail::directory_iterator_destruct(it);
666 return windows_error(LastError);
668 FilenameLen = ::wcslen(FirstFind.cFileName);
670 // Construct the current directory entry.
671 SmallString<128> directory_entry_name_utf8;
672 if (std::error_code ec =
673 UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
674 directory_entry_name_utf8))
677 it.IterationHandle = intptr_t(FindHandle.take());
678 SmallString<128> directory_entry_path(path);
679 path::append(directory_entry_path, directory_entry_name_utf8.str());
680 it.CurrentEntry = directory_entry(directory_entry_path.str());
682 return std::error_code();
685 std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
686 if (it.IterationHandle != 0)
687 // Closes the handle if it's valid.
688 ScopedFindHandle close(HANDLE(it.IterationHandle));
689 it.IterationHandle = 0;
690 it.CurrentEntry = directory_entry();
691 return std::error_code();
694 std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
695 WIN32_FIND_DATAW FindData;
696 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
697 DWORD LastError = ::GetLastError();
699 if (LastError == ERROR_NO_MORE_FILES)
700 return detail::directory_iterator_destruct(it);
701 return windows_error(LastError);
704 size_t FilenameLen = ::wcslen(FindData.cFileName);
705 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
706 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
707 FindData.cFileName[1] == L'.'))
708 return directory_iterator_increment(it);
710 SmallString<128> directory_entry_path_utf8;
711 if (std::error_code ec =
712 UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
713 directory_entry_path_utf8))
716 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
717 return std::error_code();
720 std::error_code openFileForRead(const Twine &Name, int &ResultFD) {
721 SmallString<128> PathStorage;
722 SmallVector<wchar_t, 128> PathUTF16;
724 if (std::error_code EC =
725 UTF8ToUTF16(Name.toStringRef(PathStorage), PathUTF16))
728 HANDLE H = ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
729 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
730 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
731 if (H == INVALID_HANDLE_VALUE) {
732 DWORD LastError = ::GetLastError();
733 std::error_code EC = windows_error(LastError);
734 // Provide a better error message when trying to open directories.
735 // This only runs if we failed to open the file, so there is probably
736 // no performances issues.
737 if (LastError != ERROR_ACCESS_DENIED)
739 if (is_directory(Name))
740 return make_error_code(errc::is_a_directory);
744 int FD = ::_open_osfhandle(intptr_t(H), 0);
747 return windows_error(ERROR_INVALID_HANDLE);
751 return std::error_code();
754 std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
755 sys::fs::OpenFlags Flags, unsigned Mode) {
756 // Verify that we don't have both "append" and "excl".
757 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
758 "Cannot specify both 'excl' and 'append' file creation flags!");
760 SmallString<128> PathStorage;
761 SmallVector<wchar_t, 128> PathUTF16;
763 if (std::error_code EC =
764 UTF8ToUTF16(Name.toStringRef(PathStorage), PathUTF16))
767 DWORD CreationDisposition;
769 CreationDisposition = CREATE_NEW;
770 else if (Flags & F_Append)
771 CreationDisposition = OPEN_ALWAYS;
773 CreationDisposition = CREATE_ALWAYS;
775 DWORD Access = GENERIC_WRITE;
777 Access |= GENERIC_READ;
779 HANDLE H = ::CreateFileW(PathUTF16.begin(), Access,
780 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
781 CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
783 if (H == INVALID_HANDLE_VALUE) {
784 DWORD LastError = ::GetLastError();
785 std::error_code EC = windows_error(LastError);
786 // Provide a better error message when trying to open directories.
787 // This only runs if we failed to open the file, so there is probably
788 // no performances issues.
789 if (LastError != ERROR_ACCESS_DENIED)
791 if (is_directory(Name))
792 return make_error_code(errc::is_a_directory);
797 if (Flags & F_Append)
798 OpenFlags |= _O_APPEND;
801 OpenFlags |= _O_TEXT;
803 int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
806 return windows_error(ERROR_INVALID_HANDLE);
810 return std::error_code();
812 } // end namespace fs
816 bool home_directory(SmallVectorImpl<char> &result) {
817 wchar_t Path[MAX_PATH];
818 if (::SHGetFolderPathW(0, CSIDL_APPDATA | CSIDL_FLAG_CREATE, 0,
819 /*SHGFP_TYPE_CURRENT*/0, Path) != S_OK)
822 if (UTF16ToUTF8(Path, ::wcslen(Path), result))
828 static bool getTempDirEnvVar(const char *Var, SmallVectorImpl<char> &Res) {
829 SmallVector<wchar_t, 128> NameUTF16;
830 if (windows::UTF8ToUTF16(Var, NameUTF16))
833 SmallVector<wchar_t, 1024> Buf;
838 GetEnvironmentVariableW(NameUTF16.data(), Buf.data(), Buf.capacity());
842 // Try again with larger buffer.
843 } while (Size > Buf.capacity());
846 if (windows::UTF16ToUTF8(Buf.data(), Size, Res))
851 static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
852 const char *EnvironmentVariables[] = {"TMP", "TEMP", "USERPROFILE"};
853 for (const char *Env : EnvironmentVariables) {
854 if (getTempDirEnvVar(Env, Res))
860 void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
861 (void)ErasedOnReboot;
864 // Check whether the temporary directory is specified by an environment
866 if (getTempDirEnvVar(Result))
869 // Fall back to a system default.
870 const char *DefaultResult = "C:\\TEMP";
871 Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
873 } // end namespace path
876 std::error_code UTF8ToUTF16(llvm::StringRef utf8,
877 llvm::SmallVectorImpl<wchar_t> &utf16) {
879 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
880 utf8.size(), utf16.begin(), 0);
883 return windows_error(::GetLastError());
885 utf16.reserve(len + 1);
888 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
889 utf8.size(), utf16.begin(), utf16.size());
892 return windows_error(::GetLastError());
895 // Make utf16 null terminated.
899 return std::error_code();
903 std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
905 llvm::SmallVectorImpl<char> &utf8) {
908 int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.begin(),
912 return windows_error(::GetLastError());
917 // Now do the actual conversion.
918 len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.data(),
919 utf8.size(), NULL, NULL);
922 return windows_error(::GetLastError());
925 // Make utf8 null terminated.
929 return std::error_code();
932 std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
933 llvm::SmallVectorImpl<char> &utf8) {
934 return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
937 std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
938 llvm::SmallVectorImpl<char> &utf8) {
939 return UTF16ToCodePage(CP_ACP, utf16, utf16_len, utf8);
941 } // end namespace windows
942 } // end namespace sys
943 } // end namespace llvm