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.
41 # pragma comment(lib, "ole32.lib") // This provides CoTaskMemFree
46 using llvm::sys::windows::UTF8ToUTF16;
47 using llvm::sys::windows::UTF16ToUTF8;
48 using llvm::sys::path::widenPath;
50 static bool is_separator(const wchar_t value) {
64 // Convert a UTF-8 path to UTF-16. Also, if the absolute equivalent of the
65 // path is longer than CreateDirectory can tolerate, make it absolute and
66 // prefixed by '\\?\'.
67 std::error_code widenPath(const Twine &Path8,
68 SmallVectorImpl<wchar_t> &Path16) {
69 const size_t MaxDirLen = MAX_PATH - 12; // Must leave room for 8.3 filename.
71 // Several operations would convert Path8 to SmallString; more efficient to
72 // do it once up front.
73 SmallString<128> Path8Str;
74 Path8.toVector(Path8Str);
76 // If we made this path absolute, how much longer would it get?
78 if (llvm::sys::path::is_absolute(Twine(Path8Str)))
79 CurPathLen = 0; // No contribution from current_path needed.
81 CurPathLen = ::GetCurrentDirectoryW(0, NULL);
83 return mapWindowsError(::GetLastError());
86 // Would the absolute path be longer than our limit?
87 if ((Path8Str.size() + CurPathLen) >= MaxDirLen &&
88 !Path8Str.startswith("\\\\?\\")) {
89 SmallString<2*MAX_PATH> FullPath("\\\\?\\");
91 SmallString<80> CurPath;
92 if (std::error_code EC = llvm::sys::fs::current_path(CurPath))
94 FullPath.append(CurPath);
96 // Traverse the requested path, canonicalizing . and .. as we go (because
97 // the \\?\ prefix is documented to treat them as real components).
98 // The iterators don't report separators and append() always attaches
99 // preferred_separator so we don't need to call native() on the result.
100 for (llvm::sys::path::const_iterator I = llvm::sys::path::begin(Path8Str),
101 E = llvm::sys::path::end(Path8Str);
103 if (I->size() == 1 && *I == ".")
105 if (I->size() == 2 && *I == "..")
106 llvm::sys::path::remove_filename(FullPath);
108 llvm::sys::path::append(FullPath, *I);
110 return UTF8ToUTF16(FullPath, Path16);
113 // Just use the caller's original path.
114 return UTF8ToUTF16(Path8Str, Path16);
116 } // end namespace path
120 std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
121 SmallVector<wchar_t, MAX_PATH> PathName;
122 DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
124 // A zero return value indicates a failure other than insufficient space.
128 // Insufficient space is determined by a return value equal to the size of
129 // the buffer passed in.
130 if (Size == PathName.capacity())
133 // On success, GetModuleFileNameW returns the number of characters written to
134 // the buffer not including the NULL terminator.
135 PathName.set_size(Size);
137 // Convert the result from UTF-16 to UTF-8.
138 SmallVector<char, MAX_PATH> PathNameUTF8;
139 if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
142 return std::string(PathNameUTF8.data());
145 UniqueID file_status::getUniqueID() const {
146 // The file is uniquely identified by the volume serial number along
147 // with the 64-bit file identifier.
148 uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
149 static_cast<uint64_t>(FileIndexLow);
151 return UniqueID(VolumeSerialNumber, FileID);
154 ErrorOr<space_info> disk_space(const Twine Path) {
155 PULARGE_INTEGER Avail, Total, Free;
156 if (!::GetDiskFreeSpaceExW(Path.str().c_str(), &Avail, &Total, &Free))
157 return mapWindowsError(::GetLastError());
158 space_info SpaceInfo;
160 (static_cast<uint64_t>(Total.HighPart) << 32) + Total.LowPart;
161 SpaceInfo.Free = (static_cast<uint64_t>(Free.HighPart) << 32) + Free.LowPart;
162 SpaceInfo.available =
163 (static_cast<uint64_t>(Avail.HighPart) << 32) + Avail.LowPart;
167 TimeValue file_status::getLastAccessedTime() const {
169 UI.LowPart = LastAccessedTimeLow;
170 UI.HighPart = LastAccessedTimeHigh;
173 Ret.fromWin32Time(UI.QuadPart);
177 TimeValue file_status::getLastModificationTime() const {
179 UI.LowPart = LastWriteTimeLow;
180 UI.HighPart = LastWriteTimeHigh;
183 Ret.fromWin32Time(UI.QuadPart);
187 std::error_code current_path(SmallVectorImpl<char> &result) {
188 SmallVector<wchar_t, MAX_PATH> cur_path;
189 DWORD len = MAX_PATH;
192 cur_path.reserve(len);
193 len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
195 // A zero return value indicates a failure other than insufficient space.
197 return mapWindowsError(::GetLastError());
199 // If there's insufficient space, the len returned is larger than the len
201 } while (len > cur_path.capacity());
203 // On success, GetCurrentDirectoryW returns the number of characters not
204 // including the null-terminator.
205 cur_path.set_size(len);
206 return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
209 std::error_code create_directory(const Twine &path, bool IgnoreExisting,
211 SmallVector<wchar_t, 128> path_utf16;
213 if (std::error_code ec = widenPath(path, path_utf16))
216 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
217 DWORD LastError = ::GetLastError();
218 if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
219 return mapWindowsError(LastError);
222 return std::error_code();
225 // We can't use symbolic links for windows.
226 std::error_code create_link(const Twine &to, const Twine &from) {
227 // Convert to utf-16.
228 SmallVector<wchar_t, 128> wide_from;
229 SmallVector<wchar_t, 128> wide_to;
230 if (std::error_code ec = widenPath(from, wide_from))
232 if (std::error_code ec = widenPath(to, wide_to))
235 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
236 return mapWindowsError(::GetLastError());
238 return std::error_code();
241 std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
242 SmallVector<wchar_t, 128> path_utf16;
245 if (std::error_code EC = status(path, ST)) {
246 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
248 return std::error_code();
251 if (std::error_code ec = widenPath(path, path_utf16))
254 if (ST.type() == file_type::directory_file) {
255 if (!::RemoveDirectoryW(c_str(path_utf16))) {
256 std::error_code EC = mapWindowsError(::GetLastError());
257 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
260 return std::error_code();
262 if (!::DeleteFileW(c_str(path_utf16))) {
263 std::error_code EC = mapWindowsError(::GetLastError());
264 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
267 return std::error_code();
270 std::error_code rename(const Twine &from, const Twine &to) {
271 // Convert to utf-16.
272 SmallVector<wchar_t, 128> wide_from;
273 SmallVector<wchar_t, 128> wide_to;
274 if (std::error_code ec = widenPath(from, wide_from))
276 if (std::error_code ec = widenPath(to, wide_to))
279 std::error_code ec = std::error_code();
281 // Retry while we see recoverable errors.
282 // System scanners (eg. indexer) might open the source file when it is written
285 bool TryReplace = true;
287 for (int i = 0; i < 2000; i++) {
292 // Try ReplaceFile first, as it is able to associate a new data stream
293 // with the destination even if the destination file is currently open.
294 if (::ReplaceFileW(wide_to.data(), wide_from.data(), NULL, 0, NULL, NULL))
295 return std::error_code();
297 DWORD ReplaceError = ::GetLastError();
298 ec = mapWindowsError(ReplaceError);
300 // If ReplaceFileW returned ERROR_UNABLE_TO_MOVE_REPLACEMENT or
301 // ERROR_UNABLE_TO_MOVE_REPLACEMENT_2, retry but only use MoveFileExW().
302 if (ReplaceError == ERROR_UNABLE_TO_MOVE_REPLACEMENT ||
303 ReplaceError == ERROR_UNABLE_TO_MOVE_REPLACEMENT_2) {
307 // If ReplaceFileW returned ERROR_UNABLE_TO_REMOVE_REPLACED, retry
308 // using ReplaceFileW().
309 if (ReplaceError == ERROR_UNABLE_TO_REMOVE_REPLACED)
311 // We get ERROR_FILE_NOT_FOUND if the destination file is missing.
312 // MoveFileEx can handle this case.
313 if (ReplaceError != ERROR_ACCESS_DENIED &&
314 ReplaceError != ERROR_FILE_NOT_FOUND &&
315 ReplaceError != ERROR_SHARING_VIOLATION)
319 if (::MoveFileExW(wide_from.begin(), wide_to.begin(),
320 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
321 return std::error_code();
323 DWORD MoveError = ::GetLastError();
324 ec = mapWindowsError(MoveError);
325 if (MoveError != ERROR_ACCESS_DENIED) break;
331 std::error_code resize_file(int FD, uint64_t Size) {
332 #ifdef HAVE__CHSIZE_S
333 errno_t error = ::_chsize_s(FD, Size);
335 errno_t error = ::_chsize(FD, Size);
337 return std::error_code(error, std::generic_category());
340 std::error_code access(const Twine &Path, AccessMode Mode) {
341 SmallVector<wchar_t, 128> PathUtf16;
343 if (std::error_code EC = widenPath(Path, PathUtf16))
346 DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
348 if (Attributes == INVALID_FILE_ATTRIBUTES) {
349 // See if the file didn't actually exist.
350 DWORD LastError = ::GetLastError();
351 if (LastError != ERROR_FILE_NOT_FOUND &&
352 LastError != ERROR_PATH_NOT_FOUND)
353 return mapWindowsError(LastError);
354 return errc::no_such_file_or_directory;
357 if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
358 return errc::permission_denied;
360 return std::error_code();
363 bool can_execute(const Twine &Path) {
364 return !access(Path, AccessMode::Execute) ||
365 !access(Path + ".exe", AccessMode::Execute);
368 bool equivalent(file_status A, file_status B) {
369 assert(status_known(A) && status_known(B));
370 return A.FileIndexHigh == B.FileIndexHigh &&
371 A.FileIndexLow == B.FileIndexLow &&
372 A.FileSizeHigh == B.FileSizeHigh &&
373 A.FileSizeLow == B.FileSizeLow &&
374 A.LastAccessedTimeHigh == B.LastAccessedTimeHigh &&
375 A.LastAccessedTimeLow == B.LastAccessedTimeLow &&
376 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
377 A.LastWriteTimeLow == B.LastWriteTimeLow &&
378 A.VolumeSerialNumber == B.VolumeSerialNumber;
381 std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
382 file_status fsA, fsB;
383 if (std::error_code ec = status(A, fsA))
385 if (std::error_code ec = status(B, fsB))
387 result = equivalent(fsA, fsB);
388 return std::error_code();
391 static bool isReservedName(StringRef path) {
392 // This list of reserved names comes from MSDN, at:
393 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
394 static const char *const sReservedNames[] = { "nul", "con", "prn", "aux",
395 "com1", "com2", "com3", "com4",
396 "com5", "com6", "com7", "com8",
397 "com9", "lpt1", "lpt2", "lpt3",
398 "lpt4", "lpt5", "lpt6", "lpt7",
401 // First, check to see if this is a device namespace, which always
402 // starts with \\.\, since device namespaces are not legal file paths.
403 if (path.startswith("\\\\.\\"))
406 // Then compare against the list of ancient reserved names
407 for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
408 if (path.equals_lower(sReservedNames[i]))
412 // The path isn't what we consider reserved.
416 static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
417 if (FileHandle == INVALID_HANDLE_VALUE)
418 goto handle_status_error;
420 switch (::GetFileType(FileHandle)) {
422 llvm_unreachable("Don't know anything about this file type");
423 case FILE_TYPE_UNKNOWN: {
424 DWORD Err = ::GetLastError();
426 return mapWindowsError(Err);
427 Result = file_status(file_type::type_unknown);
428 return std::error_code();
433 Result = file_status(file_type::character_file);
434 return std::error_code();
436 Result = file_status(file_type::fifo_file);
437 return std::error_code();
440 BY_HANDLE_FILE_INFORMATION Info;
441 if (!::GetFileInformationByHandle(FileHandle, &Info))
442 goto handle_status_error;
445 file_type Type = (Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
446 ? file_type::directory_file
447 : file_type::regular_file;
449 file_status(Type, Info.ftLastAccessTime.dwHighDateTime,
450 Info.ftLastAccessTime.dwLowDateTime,
451 Info.ftLastWriteTime.dwHighDateTime,
452 Info.ftLastWriteTime.dwLowDateTime,
453 Info.dwVolumeSerialNumber, Info.nFileSizeHigh,
454 Info.nFileSizeLow, Info.nFileIndexHigh, Info.nFileIndexLow);
455 return std::error_code();
459 DWORD LastError = ::GetLastError();
460 if (LastError == ERROR_FILE_NOT_FOUND ||
461 LastError == ERROR_PATH_NOT_FOUND)
462 Result = file_status(file_type::file_not_found);
463 else if (LastError == ERROR_SHARING_VIOLATION)
464 Result = file_status(file_type::type_unknown);
466 Result = file_status(file_type::status_error);
467 return mapWindowsError(LastError);
470 std::error_code status(const Twine &path, file_status &result) {
471 SmallString<128> path_storage;
472 SmallVector<wchar_t, 128> path_utf16;
474 StringRef path8 = path.toStringRef(path_storage);
475 if (isReservedName(path8)) {
476 result = file_status(file_type::character_file);
477 return std::error_code();
480 if (std::error_code ec = widenPath(path8, path_utf16))
483 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
484 if (attr == INVALID_FILE_ATTRIBUTES)
485 return getStatus(INVALID_HANDLE_VALUE, result);
487 // Handle reparse points.
488 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
490 ::CreateFileW(path_utf16.begin(),
491 0, // Attributes only.
492 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
495 FILE_FLAG_BACKUP_SEMANTICS,
498 return getStatus(INVALID_HANDLE_VALUE, result);
502 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
503 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
504 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0));
506 return getStatus(INVALID_HANDLE_VALUE, result);
508 return getStatus(h, result);
511 std::error_code status(int FD, file_status &Result) {
512 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
513 return getStatus(FileHandle, Result);
516 std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
518 UI.QuadPart = Time.toWin32Time();
520 FT.dwLowDateTime = UI.LowPart;
521 FT.dwHighDateTime = UI.HighPart;
522 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
523 if (!SetFileTime(FileHandle, NULL, &FT, &FT))
524 return mapWindowsError(::GetLastError());
525 return std::error_code();
528 std::error_code mapped_file_region::init(int FD, uint64_t Offset,
530 // Make sure that the requested size fits within SIZE_T.
531 if (Size > std::numeric_limits<SIZE_T>::max())
532 return make_error_code(errc::invalid_argument);
534 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
535 if (FileHandle == INVALID_HANDLE_VALUE)
536 return make_error_code(errc::bad_file_descriptor);
540 case readonly: flprotect = PAGE_READONLY; break;
541 case readwrite: flprotect = PAGE_READWRITE; break;
542 case priv: flprotect = PAGE_WRITECOPY; break;
545 HANDLE FileMappingHandle =
546 ::CreateFileMappingW(FileHandle, 0, flprotect,
547 (Offset + Size) >> 32,
548 (Offset + Size) & 0xffffffff,
550 if (FileMappingHandle == NULL) {
551 std::error_code ec = mapWindowsError(GetLastError());
555 DWORD dwDesiredAccess;
557 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
558 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
559 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
561 Mapping = ::MapViewOfFile(FileMappingHandle,
566 if (Mapping == NULL) {
567 std::error_code ec = mapWindowsError(GetLastError());
568 ::CloseHandle(FileMappingHandle);
573 MEMORY_BASIC_INFORMATION mbi;
574 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
576 std::error_code ec = mapWindowsError(GetLastError());
577 ::UnmapViewOfFile(Mapping);
578 ::CloseHandle(FileMappingHandle);
581 Size = mbi.RegionSize;
584 // Close all the handles except for the view. It will keep the other handles
586 ::CloseHandle(FileMappingHandle);
587 return std::error_code();
590 mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
591 uint64_t offset, std::error_code &ec)
592 : Size(length), Mapping() {
593 ec = init(fd, offset, mode);
598 mapped_file_region::~mapped_file_region() {
600 ::UnmapViewOfFile(Mapping);
603 uint64_t mapped_file_region::size() const {
604 assert(Mapping && "Mapping failed but used anyway!");
608 char *mapped_file_region::data() const {
609 assert(Mapping && "Mapping failed but used anyway!");
610 return reinterpret_cast<char*>(Mapping);
613 const char *mapped_file_region::const_data() const {
614 assert(Mapping && "Mapping failed but used anyway!");
615 return reinterpret_cast<const char*>(Mapping);
618 int mapped_file_region::alignment() {
620 ::GetSystemInfo(&SysInfo);
621 return SysInfo.dwAllocationGranularity;
624 std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
626 SmallVector<wchar_t, 128> path_utf16;
628 if (std::error_code ec = widenPath(path, path_utf16))
631 // Convert path to the format that Windows is happy with.
632 if (path_utf16.size() > 0 &&
633 !is_separator(path_utf16[path.size() - 1]) &&
634 path_utf16[path.size() - 1] != L':') {
635 path_utf16.push_back(L'\\');
636 path_utf16.push_back(L'*');
638 path_utf16.push_back(L'*');
641 // Get the first directory entry.
642 WIN32_FIND_DATAW FirstFind;
643 ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
645 return mapWindowsError(::GetLastError());
647 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
648 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
649 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
650 FirstFind.cFileName[1] == L'.'))
651 if (!::FindNextFileW(FindHandle, &FirstFind)) {
652 DWORD LastError = ::GetLastError();
654 if (LastError == ERROR_NO_MORE_FILES)
655 return detail::directory_iterator_destruct(it);
656 return mapWindowsError(LastError);
658 FilenameLen = ::wcslen(FirstFind.cFileName);
660 // Construct the current directory entry.
661 SmallString<128> directory_entry_name_utf8;
662 if (std::error_code ec =
663 UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
664 directory_entry_name_utf8))
667 it.IterationHandle = intptr_t(FindHandle.take());
668 SmallString<128> directory_entry_path(path);
669 path::append(directory_entry_path, directory_entry_name_utf8);
670 it.CurrentEntry = directory_entry(directory_entry_path);
672 return std::error_code();
675 std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
676 if (it.IterationHandle != 0)
677 // Closes the handle if it's valid.
678 ScopedFindHandle close(HANDLE(it.IterationHandle));
679 it.IterationHandle = 0;
680 it.CurrentEntry = directory_entry();
681 return std::error_code();
684 std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
685 WIN32_FIND_DATAW FindData;
686 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
687 DWORD LastError = ::GetLastError();
689 if (LastError == ERROR_NO_MORE_FILES)
690 return detail::directory_iterator_destruct(it);
691 return mapWindowsError(LastError);
694 size_t FilenameLen = ::wcslen(FindData.cFileName);
695 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
696 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
697 FindData.cFileName[1] == L'.'))
698 return directory_iterator_increment(it);
700 SmallString<128> directory_entry_path_utf8;
701 if (std::error_code ec =
702 UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
703 directory_entry_path_utf8))
706 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
707 return std::error_code();
710 std::error_code openFileForRead(const Twine &Name, int &ResultFD) {
711 SmallVector<wchar_t, 128> PathUTF16;
713 if (std::error_code EC = widenPath(Name, PathUTF16))
717 ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
718 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
719 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
720 if (H == INVALID_HANDLE_VALUE) {
721 DWORD LastError = ::GetLastError();
722 std::error_code EC = mapWindowsError(LastError);
723 // Provide a better error message when trying to open directories.
724 // This only runs if we failed to open the file, so there is probably
725 // no performances issues.
726 if (LastError != ERROR_ACCESS_DENIED)
728 if (is_directory(Name))
729 return make_error_code(errc::is_a_directory);
733 int FD = ::_open_osfhandle(intptr_t(H), 0);
736 return mapWindowsError(ERROR_INVALID_HANDLE);
740 return std::error_code();
743 std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
744 sys::fs::OpenFlags Flags, unsigned Mode) {
745 // Verify that we don't have both "append" and "excl".
746 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
747 "Cannot specify both 'excl' and 'append' file creation flags!");
749 SmallVector<wchar_t, 128> PathUTF16;
751 if (std::error_code EC = widenPath(Name, PathUTF16))
754 DWORD CreationDisposition;
756 CreationDisposition = CREATE_NEW;
757 else if (Flags & F_Append)
758 CreationDisposition = OPEN_ALWAYS;
760 CreationDisposition = CREATE_ALWAYS;
762 DWORD Access = GENERIC_WRITE;
764 Access |= GENERIC_READ;
766 HANDLE H = ::CreateFileW(PathUTF16.begin(), Access,
767 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
768 CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
770 if (H == INVALID_HANDLE_VALUE) {
771 DWORD LastError = ::GetLastError();
772 std::error_code EC = mapWindowsError(LastError);
773 // Provide a better error message when trying to open directories.
774 // This only runs if we failed to open the file, so there is probably
775 // no performances issues.
776 if (LastError != ERROR_ACCESS_DENIED)
778 if (is_directory(Name))
779 return make_error_code(errc::is_a_directory);
784 if (Flags & F_Append)
785 OpenFlags |= _O_APPEND;
788 OpenFlags |= _O_TEXT;
790 int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
793 return mapWindowsError(ERROR_INVALID_HANDLE);
797 return std::error_code();
799 } // end namespace fs
802 static bool getKnownFolderPath(KNOWNFOLDERID folderId,
803 SmallVectorImpl<char> &result) {
804 wchar_t *path = nullptr;
805 if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK)
808 bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
809 ::CoTaskMemFree(path);
813 bool getUserCacheDir(SmallVectorImpl<char> &Result) {
814 return getKnownFolderPath(FOLDERID_LocalAppData, Result);
817 bool home_directory(SmallVectorImpl<char> &result) {
818 return getKnownFolderPath(FOLDERID_Profile, result);
821 static bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {
822 SmallVector<wchar_t, 1024> Buf;
826 Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.capacity());
830 // Try again with larger buffer.
831 } while (Size > Buf.capacity());
834 return !windows::UTF16ToUTF8(Buf.data(), Size, Res);
837 static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
838 const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};
839 for (auto *Env : EnvironmentVariables) {
840 if (getTempDirEnvVar(Env, Res))
846 void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
847 (void)ErasedOnReboot;
850 // Check whether the temporary directory is specified by an environment var.
851 // This matches GetTempPath logic to some degree. GetTempPath is not used
852 // directly as it cannot handle evn var longer than 130 chars on Windows 7
853 // (fixed on Windows 8).
854 if (getTempDirEnvVar(Result)) {
855 assert(!Result.empty() && "Unexpected empty path");
856 native(Result); // Some Unix-like shells use Unix path separator in $TMP.
857 fs::make_absolute(Result); // Make it absolute if not already.
861 // Fall back to a system default.
862 const char *DefaultResult = "C:\\Temp";
863 Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
865 } // end namespace path
868 std::error_code UTF8ToUTF16(llvm::StringRef utf8,
869 llvm::SmallVectorImpl<wchar_t> &utf16) {
871 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
872 utf8.size(), utf16.begin(), 0);
875 return mapWindowsError(::GetLastError());
877 utf16.reserve(len + 1);
880 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
881 utf8.size(), utf16.begin(), utf16.size());
884 return mapWindowsError(::GetLastError());
887 // Make utf16 null terminated.
891 return std::error_code();
895 std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
897 llvm::SmallVectorImpl<char> &utf8) {
900 int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.begin(),
904 return mapWindowsError(::GetLastError());
909 // Now do the actual conversion.
910 len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.data(),
911 utf8.size(), NULL, NULL);
914 return mapWindowsError(::GetLastError());
917 // Make utf8 null terminated.
921 return std::error_code();
924 std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
925 llvm::SmallVectorImpl<char> &utf8) {
926 return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
929 std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
930 llvm::SmallVectorImpl<char> &utf8) {
931 return UTF16ToCodePage(CP_ACP, utf16, utf16_len, utf8);
933 } // end namespace windows
934 } // end namespace sys
935 } // end namespace llvm