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"
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 "WindowsSupport.h"
32 // MinGW doesn't define this.
33 #ifndef _ERRNO_T_DEFINED
34 #define _ERRNO_T_DEFINED
39 # pragma comment(lib, "advapi32.lib") // This provides CryptAcquireContextW.
44 using llvm::sys::windows::UTF8ToUTF16;
45 using llvm::sys::windows::UTF16ToUTF8;
47 static error_code TempDir(SmallVectorImpl<char> &Result) {
48 SmallVector<wchar_t, 64> Res;
50 DWORD Len = ::GetTempPathW(Res.capacity(), Res.begin());
53 return windows_error(::GetLastError());
55 if (Len > Res.capacity()) {
61 return UTF16ToUTF8(Res.begin(), Res.size(), Result);
64 static bool is_separator(const wchar_t value) {
78 std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
79 SmallVector<wchar_t, MAX_PATH> PathName;
80 DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
82 // A zero return value indicates a failure other than insufficient space.
86 // Insufficient space is determined by a return value equal to the size of
87 // the buffer passed in.
88 if (Size == PathName.capacity())
91 // On success, GetModuleFileNameW returns the number of characters written to
92 // the buffer not including the NULL terminator.
93 PathName.set_size(Size);
95 // Convert the result from UTF-16 to UTF-8.
96 SmallVector<char, MAX_PATH> PathNameUTF8;
97 if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
100 return std::string(PathNameUTF8.data());
103 UniqueID file_status::getUniqueID() const {
104 // The file is uniquely identified by the volume serial number along
105 // with the 64-bit file identifier.
106 uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
107 static_cast<uint64_t>(FileIndexLow);
109 return UniqueID(VolumeSerialNumber, FileID);
112 TimeValue file_status::getLastModificationTime() const {
114 UI.LowPart = LastWriteTimeLow;
115 UI.HighPart = LastWriteTimeHigh;
118 Ret.fromWin32Time(UI.QuadPart);
122 error_code current_path(SmallVectorImpl<char> &result) {
123 SmallVector<wchar_t, MAX_PATH> cur_path;
124 DWORD len = MAX_PATH;
127 cur_path.reserve(len);
128 len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
130 // A zero return value indicates a failure other than insufficient space.
132 return windows_error(::GetLastError());
134 // If there's insufficient space, the len returned is larger than the len
136 } while (len > cur_path.capacity());
138 // On success, GetCurrentDirectoryW returns the number of characters not
139 // including the null-terminator.
140 cur_path.set_size(len);
141 return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
144 error_code create_directory(const Twine &path, bool IgnoreExisting) {
145 SmallString<128> path_storage;
146 SmallVector<wchar_t, 128> path_utf16;
148 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
152 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
153 error_code ec = windows_error(::GetLastError());
154 if (ec != windows_error::already_exists || !IgnoreExisting)
161 error_code normalize_separators(SmallVectorImpl<char> &Path) {
166 // We can't use symbolic links for windows.
167 error_code create_link(const Twine &to, const Twine &from) {
169 SmallString<128> from_storage;
170 SmallString<128> to_storage;
171 StringRef f = from.toStringRef(from_storage);
172 StringRef t = to.toStringRef(to_storage);
174 // Convert to utf-16.
175 SmallVector<wchar_t, 128> wide_from;
176 SmallVector<wchar_t, 128> wide_to;
177 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
178 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
180 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
181 return windows_error(::GetLastError());
186 error_code remove(const Twine &path, bool IgnoreNonExisting) {
187 SmallString<128> path_storage;
188 SmallVector<wchar_t, 128> path_utf16;
191 if (error_code EC = status(path, ST)) {
192 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
197 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
201 if (ST.type() == file_type::directory_file) {
202 if (!::RemoveDirectoryW(c_str(path_utf16))) {
203 error_code EC = windows_error(::GetLastError());
204 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
209 if (!::DeleteFileW(c_str(path_utf16))) {
210 error_code EC = windows_error(::GetLastError());
211 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
217 error_code rename(const Twine &from, const Twine &to) {
219 SmallString<128> from_storage;
220 SmallString<128> to_storage;
221 StringRef f = from.toStringRef(from_storage);
222 StringRef t = to.toStringRef(to_storage);
224 // Convert to utf-16.
225 SmallVector<wchar_t, 128> wide_from;
226 SmallVector<wchar_t, 128> wide_to;
227 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
228 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
230 error_code ec = error_code();
231 for (int i = 0; i < 2000; i++) {
232 if (::MoveFileExW(wide_from.begin(), wide_to.begin(),
233 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
235 ec = windows_error(::GetLastError());
236 if (ec != windows_error::access_denied)
238 // Retry MoveFile() at ACCESS_DENIED.
239 // System scanners (eg. indexer) might open the source file when
240 // It is written and closed.
247 error_code resize_file(const Twine &path, uint64_t size) {
248 SmallString<128> path_storage;
249 SmallVector<wchar_t, 128> path_utf16;
251 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
255 int fd = ::_wopen(path_utf16.begin(), O_BINARY | _O_RDWR, S_IWRITE);
257 return error_code(errno, generic_category());
258 #ifdef HAVE__CHSIZE_S
259 errno_t error = ::_chsize_s(fd, size);
261 errno_t error = ::_chsize(fd, size);
264 return error_code(error, generic_category());
267 error_code exists(const Twine &path, bool &result) {
268 SmallString<128> path_storage;
269 SmallVector<wchar_t, 128> path_utf16;
271 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
275 DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
277 if (attributes == INVALID_FILE_ATTRIBUTES) {
278 // See if the file didn't actually exist.
279 error_code ec = make_error_code(windows_error(::GetLastError()));
280 if (ec != windows_error::file_not_found &&
281 ec != windows_error::path_not_found)
289 bool can_write(const Twine &Path) {
290 // FIXME: take security attributes into account.
291 SmallString<128> PathStorage;
292 SmallVector<wchar_t, 128> PathUtf16;
294 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
297 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
298 return (Attr != INVALID_FILE_ATTRIBUTES) && !(Attr & FILE_ATTRIBUTE_READONLY);
301 bool can_execute(const Twine &Path) {
302 SmallString<128> PathStorage;
303 SmallVector<wchar_t, 128> PathUtf16;
305 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
308 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
309 return Attr != INVALID_FILE_ATTRIBUTES;
312 bool equivalent(file_status A, file_status B) {
313 assert(status_known(A) && status_known(B));
314 return A.FileIndexHigh == B.FileIndexHigh &&
315 A.FileIndexLow == B.FileIndexLow &&
316 A.FileSizeHigh == B.FileSizeHigh &&
317 A.FileSizeLow == B.FileSizeLow &&
318 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
319 A.LastWriteTimeLow == B.LastWriteTimeLow &&
320 A.VolumeSerialNumber == B.VolumeSerialNumber;
323 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
324 file_status fsA, fsB;
325 if (error_code ec = status(A, fsA)) return ec;
326 if (error_code ec = status(B, fsB)) return ec;
327 result = equivalent(fsA, fsB);
331 static bool isReservedName(StringRef path) {
332 // This list of reserved names comes from MSDN, at:
333 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
334 static const char *sReservedNames[] = { "nul", "con", "prn", "aux",
335 "com1", "com2", "com3", "com4", "com5", "com6",
336 "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
337 "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9" };
339 // First, check to see if this is a device namespace, which always
340 // starts with \\.\, since device namespaces are not legal file paths.
341 if (path.startswith("\\\\.\\"))
344 // Then compare against the list of ancient reserved names
345 for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
346 if (path.equals_lower(sReservedNames[i]))
350 // The path isn't what we consider reserved.
354 static error_code getStatus(HANDLE FileHandle, file_status &Result) {
355 if (FileHandle == INVALID_HANDLE_VALUE)
356 goto handle_status_error;
358 switch (::GetFileType(FileHandle)) {
360 llvm_unreachable("Don't know anything about this file type");
361 case FILE_TYPE_UNKNOWN: {
362 DWORD Err = ::GetLastError();
364 return windows_error(Err);
365 Result = file_status(file_type::type_unknown);
371 Result = file_status(file_type::character_file);
374 Result = file_status(file_type::fifo_file);
378 BY_HANDLE_FILE_INFORMATION Info;
379 if (!::GetFileInformationByHandle(FileHandle, &Info))
380 goto handle_status_error;
383 file_type Type = (Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
384 ? file_type::directory_file
385 : file_type::regular_file;
387 file_status(Type, Info.ftLastWriteTime.dwHighDateTime,
388 Info.ftLastWriteTime.dwLowDateTime,
389 Info.dwVolumeSerialNumber, Info.nFileSizeHigh,
390 Info.nFileSizeLow, Info.nFileIndexHigh, Info.nFileIndexLow);
395 error_code EC = windows_error(::GetLastError());
396 if (EC == windows_error::file_not_found ||
397 EC == windows_error::path_not_found)
398 Result = file_status(file_type::file_not_found);
399 else if (EC == windows_error::sharing_violation)
400 Result = file_status(file_type::type_unknown);
402 Result = file_status(file_type::status_error);
406 error_code status(const Twine &path, file_status &result) {
407 SmallString<128> path_storage;
408 SmallVector<wchar_t, 128> path_utf16;
410 StringRef path8 = path.toStringRef(path_storage);
411 if (isReservedName(path8)) {
412 result = file_status(file_type::character_file);
416 if (error_code ec = UTF8ToUTF16(path8, path_utf16))
419 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
420 if (attr == INVALID_FILE_ATTRIBUTES)
421 return getStatus(INVALID_HANDLE_VALUE, result);
423 // Handle reparse points.
424 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
426 ::CreateFileW(path_utf16.begin(),
427 0, // Attributes only.
428 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
431 FILE_FLAG_BACKUP_SEMANTICS,
434 return getStatus(INVALID_HANDLE_VALUE, result);
438 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
439 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
440 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0));
442 return getStatus(INVALID_HANDLE_VALUE, result);
444 return getStatus(h, result);
447 error_code status(int FD, file_status &Result) {
448 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
449 return getStatus(FileHandle, Result);
452 error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
454 UI.QuadPart = Time.toWin32Time();
456 FT.dwLowDateTime = UI.LowPart;
457 FT.dwHighDateTime = UI.HighPart;
458 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
459 if (!SetFileTime(FileHandle, NULL, &FT, &FT))
460 return windows_error(::GetLastError());
464 error_code get_magic(const Twine &path, uint32_t len,
465 SmallVectorImpl<char> &result) {
466 SmallString<128> path_storage;
467 SmallVector<wchar_t, 128> path_utf16;
470 // Convert path to UTF-16.
471 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
476 HANDLE file = ::CreateFileW(c_str(path_utf16),
481 FILE_ATTRIBUTE_READONLY,
483 if (file == INVALID_HANDLE_VALUE)
484 return windows_error(::GetLastError());
490 DWORD bytes_read = 0;
491 BOOL read_success = ::ReadFile(file, result.data(), len, &bytes_read, NULL);
492 error_code ec = windows_error(::GetLastError());
494 if (!read_success || (bytes_read != len)) {
495 // Set result size to the number of bytes read if it's valid.
496 if (bytes_read <= len)
497 result.set_size(bytes_read);
498 // ERROR_HANDLE_EOF is mapped to errc::value_too_large.
502 result.set_size(len);
506 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
508 // Make sure that the requested size fits within SIZE_T.
509 if (Size > std::numeric_limits<SIZE_T>::max()) {
510 if (FileDescriptor) {
512 _close(FileDescriptor);
514 ::CloseHandle(FileHandle);
515 return make_error_code(errc::invalid_argument);
520 case readonly: flprotect = PAGE_READONLY; break;
521 case readwrite: flprotect = PAGE_READWRITE; break;
522 case priv: flprotect = PAGE_WRITECOPY; break;
526 ::CreateFileMappingW(FileHandle, 0, flprotect,
527 (Offset + Size) >> 32,
528 (Offset + Size) & 0xffffffff,
530 if (FileMappingHandle == NULL) {
531 error_code ec = windows_error(GetLastError());
532 if (FileDescriptor) {
534 _close(FileDescriptor);
536 ::CloseHandle(FileHandle);
540 DWORD dwDesiredAccess;
542 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
543 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
544 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
546 Mapping = ::MapViewOfFile(FileMappingHandle,
551 if (Mapping == NULL) {
552 error_code ec = windows_error(GetLastError());
553 ::CloseHandle(FileMappingHandle);
554 if (FileDescriptor) {
556 _close(FileDescriptor);
558 ::CloseHandle(FileHandle);
563 MEMORY_BASIC_INFORMATION mbi;
564 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
566 error_code ec = windows_error(GetLastError());
567 ::UnmapViewOfFile(Mapping);
568 ::CloseHandle(FileMappingHandle);
569 if (FileDescriptor) {
571 _close(FileDescriptor);
573 ::CloseHandle(FileHandle);
576 Size = mbi.RegionSize;
579 // Close all the handles except for the view. It will keep the other handles
581 ::CloseHandle(FileMappingHandle);
582 if (FileDescriptor) {
584 _close(FileDescriptor); // Also closes FileHandle.
586 ::CloseHandle(FileHandle);
590 mapped_file_region::mapped_file_region(const Twine &path,
599 , FileHandle(INVALID_HANDLE_VALUE)
600 , FileMappingHandle() {
601 SmallString<128> path_storage;
602 SmallVector<wchar_t, 128> path_utf16;
604 // Convert path to UTF-16.
605 if ((ec = UTF8ToUTF16(path.toStringRef(path_storage), path_utf16)))
608 // Get file handle for creating a file mapping.
609 FileHandle = ::CreateFileW(c_str(path_utf16),
610 Mode == readonly ? GENERIC_READ
611 : GENERIC_READ | GENERIC_WRITE,
612 Mode == readonly ? FILE_SHARE_READ
615 Mode == readonly ? OPEN_EXISTING
617 Mode == readonly ? FILE_ATTRIBUTE_READONLY
618 : FILE_ATTRIBUTE_NORMAL,
620 if (FileHandle == INVALID_HANDLE_VALUE) {
621 ec = windows_error(::GetLastError());
626 ec = init(FileDescriptor, true, offset);
628 Mapping = FileMappingHandle = 0;
629 FileHandle = INVALID_HANDLE_VALUE;
634 mapped_file_region::mapped_file_region(int fd,
644 , FileHandle(INVALID_HANDLE_VALUE)
645 , FileMappingHandle() {
646 FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
647 if (FileHandle == INVALID_HANDLE_VALUE) {
649 _close(FileDescriptor);
651 ec = make_error_code(errc::bad_file_descriptor);
655 ec = init(FileDescriptor, closefd, offset);
657 Mapping = FileMappingHandle = 0;
658 FileHandle = INVALID_HANDLE_VALUE;
663 mapped_file_region::~mapped_file_region() {
665 ::UnmapViewOfFile(Mapping);
668 mapped_file_region::mapped_file_region(mapped_file_region &&other)
671 , Mapping(other.Mapping)
672 , FileDescriptor(other.FileDescriptor)
673 , FileHandle(other.FileHandle)
674 , FileMappingHandle(other.FileMappingHandle) {
675 other.Mapping = other.FileMappingHandle = 0;
676 other.FileHandle = INVALID_HANDLE_VALUE;
677 other.FileDescriptor = 0;
680 mapped_file_region::mapmode mapped_file_region::flags() const {
681 assert(Mapping && "Mapping failed but used anyway!");
685 uint64_t mapped_file_region::size() const {
686 assert(Mapping && "Mapping failed but used anyway!");
690 char *mapped_file_region::data() const {
691 assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
692 assert(Mapping && "Mapping failed but used anyway!");
693 return reinterpret_cast<char*>(Mapping);
696 const char *mapped_file_region::const_data() const {
697 assert(Mapping && "Mapping failed but used anyway!");
698 return reinterpret_cast<const char*>(Mapping);
701 int mapped_file_region::alignment() {
703 ::GetSystemInfo(&SysInfo);
704 return SysInfo.dwAllocationGranularity;
707 error_code detail::directory_iterator_construct(detail::DirIterState &it,
709 SmallVector<wchar_t, 128> path_utf16;
711 if (error_code ec = UTF8ToUTF16(path,
715 // Convert path to the format that Windows is happy with.
716 if (path_utf16.size() > 0 &&
717 !is_separator(path_utf16[path.size() - 1]) &&
718 path_utf16[path.size() - 1] != L':') {
719 path_utf16.push_back(L'\\');
720 path_utf16.push_back(L'*');
722 path_utf16.push_back(L'*');
725 // Get the first directory entry.
726 WIN32_FIND_DATAW FirstFind;
727 ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
729 return windows_error(::GetLastError());
731 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
732 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
733 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
734 FirstFind.cFileName[1] == L'.'))
735 if (!::FindNextFileW(FindHandle, &FirstFind)) {
736 error_code ec = windows_error(::GetLastError());
738 if (ec == windows_error::no_more_files)
739 return detail::directory_iterator_destruct(it);
742 FilenameLen = ::wcslen(FirstFind.cFileName);
744 // Construct the current directory entry.
745 SmallString<128> directory_entry_name_utf8;
746 if (error_code ec = UTF16ToUTF8(FirstFind.cFileName,
747 ::wcslen(FirstFind.cFileName),
748 directory_entry_name_utf8))
751 it.IterationHandle = intptr_t(FindHandle.take());
752 SmallString<128> directory_entry_path(path);
753 path::append(directory_entry_path, directory_entry_name_utf8.str());
754 it.CurrentEntry = directory_entry(directory_entry_path.str());
759 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
760 if (it.IterationHandle != 0)
761 // Closes the handle if it's valid.
762 ScopedFindHandle close(HANDLE(it.IterationHandle));
763 it.IterationHandle = 0;
764 it.CurrentEntry = directory_entry();
768 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
769 WIN32_FIND_DATAW FindData;
770 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
771 error_code ec = windows_error(::GetLastError());
773 if (ec == windows_error::no_more_files)
774 return detail::directory_iterator_destruct(it);
778 size_t FilenameLen = ::wcslen(FindData.cFileName);
779 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
780 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
781 FindData.cFileName[1] == L'.'))
782 return directory_iterator_increment(it);
784 SmallString<128> directory_entry_path_utf8;
785 if (error_code ec = UTF16ToUTF8(FindData.cFileName,
786 ::wcslen(FindData.cFileName),
787 directory_entry_path_utf8))
790 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
794 error_code openFileForRead(const Twine &Name, int &ResultFD) {
795 SmallString<128> PathStorage;
796 SmallVector<wchar_t, 128> PathUTF16;
798 if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
802 HANDLE H = ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
803 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
804 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
805 if (H == INVALID_HANDLE_VALUE) {
806 error_code EC = windows_error(::GetLastError());
807 // Provide a better error message when trying to open directories.
808 // This only runs if we failed to open the file, so there is probably
809 // no performances issues.
810 if (EC != windows_error::access_denied)
812 if (is_directory(Name))
813 return make_error_code(errc::is_a_directory);
817 int FD = ::_open_osfhandle(intptr_t(H), 0);
820 return windows_error::invalid_handle;
827 error_code openFileForWrite(const Twine &Name, int &ResultFD,
828 sys::fs::OpenFlags Flags, unsigned Mode) {
829 // Verify that we don't have both "append" and "excl".
830 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
831 "Cannot specify both 'excl' and 'append' file creation flags!");
833 SmallString<128> PathStorage;
834 SmallVector<wchar_t, 128> PathUTF16;
836 if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
840 DWORD CreationDisposition;
842 CreationDisposition = CREATE_NEW;
843 else if (Flags & F_Append)
844 CreationDisposition = OPEN_ALWAYS;
846 CreationDisposition = CREATE_ALWAYS;
848 DWORD Access = GENERIC_WRITE;
850 Access |= GENERIC_READ;
852 HANDLE H = ::CreateFileW(PathUTF16.begin(), Access,
853 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
854 CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
856 if (H == INVALID_HANDLE_VALUE) {
857 error_code EC = windows_error(::GetLastError());
858 // Provide a better error message when trying to open directories.
859 // This only runs if we failed to open the file, so there is probably
860 // no performances issues.
861 if (EC != windows_error::access_denied)
863 if (is_directory(Name))
864 return make_error_code(errc::is_a_directory);
869 if (Flags & F_Append)
870 OpenFlags |= _O_APPEND;
873 OpenFlags |= _O_TEXT;
875 int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
878 return windows_error::invalid_handle;
884 } // end namespace fs
888 bool home_directory(SmallVectorImpl<char> &result) {
889 wchar_t Path[MAX_PATH];
890 if (::SHGetFolderPathW(0, CSIDL_APPDATA | CSIDL_FLAG_CREATE, 0,
891 /*SHGFP_TYPE_CURRENT*/0, Path) != S_OK)
894 if (UTF16ToUTF8(Path, ::wcslen(Path), result))
900 } // end namespace path
903 llvm::error_code UTF8ToUTF16(llvm::StringRef utf8,
904 llvm::SmallVectorImpl<wchar_t> &utf16) {
906 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
907 utf8.size(), utf16.begin(), 0);
910 return llvm::windows_error(::GetLastError());
912 utf16.reserve(len + 1);
915 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
916 utf8.size(), utf16.begin(), utf16.size());
919 return llvm::windows_error(::GetLastError());
922 // Make utf16 null terminated.
926 return llvm::error_code();
929 llvm::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
930 llvm::SmallVectorImpl<char> &utf8) {
933 int len = ::WideCharToMultiByte(CP_UTF8, 0, utf16, utf16_len, utf8.begin(),
937 return llvm::windows_error(::GetLastError());
942 // Now do the actual conversion.
943 len = ::WideCharToMultiByte(CP_UTF8, 0, utf16, utf16_len, utf8.data(),
944 utf8.size(), NULL, NULL);
947 return llvm::windows_error(::GetLastError());
950 // Make utf8 null terminated.
954 return llvm::error_code();
956 } // end namespace windows
957 } // end namespace sys
958 } // end namespace llvm