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)
158 return error_code::success();
161 // We can't use symbolic links for windows.
162 error_code create_link(const Twine &to, const Twine &from) {
164 SmallString<128> from_storage;
165 SmallString<128> to_storage;
166 StringRef f = from.toStringRef(from_storage);
167 StringRef t = to.toStringRef(to_storage);
169 // Convert to utf-16.
170 SmallVector<wchar_t, 128> wide_from;
171 SmallVector<wchar_t, 128> wide_to;
172 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
173 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
175 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
176 return windows_error(::GetLastError());
178 return error_code::success();
181 error_code remove(const Twine &path, bool IgnoreNonExisting) {
182 SmallString<128> path_storage;
183 SmallVector<wchar_t, 128> path_utf16;
186 if (error_code EC = status(path, ST)) {
187 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
189 return error_code::success();
192 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
196 if (ST.type() == file_type::directory_file) {
197 if (!::RemoveDirectoryW(c_str(path_utf16))) {
198 error_code EC = windows_error(::GetLastError());
199 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
202 return error_code::success();
204 if (!::DeleteFileW(c_str(path_utf16))) {
205 error_code EC = windows_error(::GetLastError());
206 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
209 return error_code::success();
212 error_code rename(const Twine &from, const Twine &to) {
214 SmallString<128> from_storage;
215 SmallString<128> to_storage;
216 StringRef f = from.toStringRef(from_storage);
217 StringRef t = to.toStringRef(to_storage);
219 // Convert to utf-16.
220 SmallVector<wchar_t, 128> wide_from;
221 SmallVector<wchar_t, 128> wide_to;
222 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
223 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
225 error_code ec = error_code::success();
226 for (int i = 0; i < 2000; i++) {
227 if (::MoveFileExW(wide_from.begin(), wide_to.begin(),
228 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
229 return error_code::success();
230 ec = windows_error(::GetLastError());
231 if (ec != windows_error::access_denied)
233 // Retry MoveFile() at ACCESS_DENIED.
234 // System scanners (eg. indexer) might open the source file when
235 // It is written and closed.
242 error_code resize_file(const Twine &path, uint64_t size) {
243 SmallString<128> path_storage;
244 SmallVector<wchar_t, 128> path_utf16;
246 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
250 int fd = ::_wopen(path_utf16.begin(), O_BINARY | _O_RDWR, S_IWRITE);
252 return error_code(errno, generic_category());
253 #ifdef HAVE__CHSIZE_S
254 errno_t error = ::_chsize_s(fd, size);
256 errno_t error = ::_chsize(fd, size);
259 return error_code(error, generic_category());
262 error_code exists(const Twine &path, bool &result) {
263 SmallString<128> path_storage;
264 SmallVector<wchar_t, 128> path_utf16;
266 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
270 DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
272 if (attributes == INVALID_FILE_ATTRIBUTES) {
273 // See if the file didn't actually exist.
274 error_code ec = make_error_code(windows_error(::GetLastError()));
275 if (ec != windows_error::file_not_found &&
276 ec != windows_error::path_not_found)
281 return error_code::success();
284 bool can_write(const Twine &Path) {
285 // FIXME: take security attributes into account.
286 SmallString<128> PathStorage;
287 SmallVector<wchar_t, 128> PathUtf16;
289 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
292 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
293 return (Attr != INVALID_FILE_ATTRIBUTES) && !(Attr & FILE_ATTRIBUTE_READONLY);
296 bool can_execute(const Twine &Path) {
297 SmallString<128> PathStorage;
298 SmallVector<wchar_t, 128> PathUtf16;
300 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
303 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
304 return Attr != INVALID_FILE_ATTRIBUTES;
307 bool equivalent(file_status A, file_status B) {
308 assert(status_known(A) && status_known(B));
309 return A.FileIndexHigh == B.FileIndexHigh &&
310 A.FileIndexLow == B.FileIndexLow &&
311 A.FileSizeHigh == B.FileSizeHigh &&
312 A.FileSizeLow == B.FileSizeLow &&
313 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
314 A.LastWriteTimeLow == B.LastWriteTimeLow &&
315 A.VolumeSerialNumber == B.VolumeSerialNumber;
318 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
319 file_status fsA, fsB;
320 if (error_code ec = status(A, fsA)) return ec;
321 if (error_code ec = status(B, fsB)) return ec;
322 result = equivalent(fsA, fsB);
323 return error_code::success();
326 static bool isReservedName(StringRef path) {
327 // This list of reserved names comes from MSDN, at:
328 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
329 static const char *sReservedNames[] = { "nul", "con", "prn", "aux",
330 "com1", "com2", "com3", "com4", "com5", "com6",
331 "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
332 "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9" };
334 // First, check to see if this is a device namespace, which always
335 // starts with \\.\, since device namespaces are not legal file paths.
336 if (path.startswith("\\\\.\\"))
339 // Then compare against the list of ancient reserved names
340 for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
341 if (path.equals_lower(sReservedNames[i]))
345 // The path isn't what we consider reserved.
349 static error_code getStatus(HANDLE FileHandle, file_status &Result) {
350 if (FileHandle == INVALID_HANDLE_VALUE)
351 goto handle_status_error;
353 switch (::GetFileType(FileHandle)) {
355 llvm_unreachable("Don't know anything about this file type");
356 case FILE_TYPE_UNKNOWN: {
357 DWORD Err = ::GetLastError();
359 return windows_error(Err);
360 Result = file_status(file_type::type_unknown);
361 return error_code::success();
366 Result = file_status(file_type::character_file);
367 return error_code::success();
369 Result = file_status(file_type::fifo_file);
370 return error_code::success();
373 BY_HANDLE_FILE_INFORMATION Info;
374 if (!::GetFileInformationByHandle(FileHandle, &Info))
375 goto handle_status_error;
378 file_type Type = (Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
379 ? file_type::directory_file
380 : file_type::regular_file;
382 file_status(Type, Info.ftLastWriteTime.dwHighDateTime,
383 Info.ftLastWriteTime.dwLowDateTime,
384 Info.dwVolumeSerialNumber, Info.nFileSizeHigh,
385 Info.nFileSizeLow, Info.nFileIndexHigh, Info.nFileIndexLow);
386 return error_code::success();
390 error_code EC = windows_error(::GetLastError());
391 if (EC == windows_error::file_not_found ||
392 EC == windows_error::path_not_found)
393 Result = file_status(file_type::file_not_found);
394 else if (EC == windows_error::sharing_violation)
395 Result = file_status(file_type::type_unknown);
397 Result = file_status(file_type::status_error);
401 error_code status(const Twine &path, file_status &result) {
402 SmallString<128> path_storage;
403 SmallVector<wchar_t, 128> path_utf16;
405 StringRef path8 = path.toStringRef(path_storage);
406 if (isReservedName(path8)) {
407 result = file_status(file_type::character_file);
408 return error_code::success();
411 if (error_code ec = UTF8ToUTF16(path8, path_utf16))
414 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
415 if (attr == INVALID_FILE_ATTRIBUTES)
416 return getStatus(INVALID_HANDLE_VALUE, result);
418 // Handle reparse points.
419 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
421 ::CreateFileW(path_utf16.begin(),
422 0, // Attributes only.
423 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
426 FILE_FLAG_BACKUP_SEMANTICS,
429 return getStatus(INVALID_HANDLE_VALUE, result);
433 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
434 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
435 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0));
437 return getStatus(INVALID_HANDLE_VALUE, result);
439 return getStatus(h, result);
442 error_code status(int FD, file_status &Result) {
443 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
444 return getStatus(FileHandle, Result);
447 error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
449 UI.QuadPart = Time.toWin32Time();
451 FT.dwLowDateTime = UI.LowPart;
452 FT.dwHighDateTime = UI.HighPart;
453 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
454 if (!SetFileTime(FileHandle, NULL, &FT, &FT))
455 return windows_error(::GetLastError());
456 return error_code::success();
459 error_code get_magic(const Twine &path, uint32_t len,
460 SmallVectorImpl<char> &result) {
461 SmallString<128> path_storage;
462 SmallVector<wchar_t, 128> path_utf16;
465 // Convert path to UTF-16.
466 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
471 HANDLE file = ::CreateFileW(c_str(path_utf16),
476 FILE_ATTRIBUTE_READONLY,
478 if (file == INVALID_HANDLE_VALUE)
479 return windows_error(::GetLastError());
485 DWORD bytes_read = 0;
486 BOOL read_success = ::ReadFile(file, result.data(), len, &bytes_read, NULL);
487 error_code ec = windows_error(::GetLastError());
489 if (!read_success || (bytes_read != len)) {
490 // Set result size to the number of bytes read if it's valid.
491 if (bytes_read <= len)
492 result.set_size(bytes_read);
493 // ERROR_HANDLE_EOF is mapped to errc::value_too_large.
497 result.set_size(len);
498 return error_code::success();
501 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
503 // Make sure that the requested size fits within SIZE_T.
504 if (Size > std::numeric_limits<SIZE_T>::max()) {
505 if (FileDescriptor) {
507 _close(FileDescriptor);
509 ::CloseHandle(FileHandle);
510 return make_error_code(errc::invalid_argument);
515 case readonly: flprotect = PAGE_READONLY; break;
516 case readwrite: flprotect = PAGE_READWRITE; break;
517 case priv: flprotect = PAGE_WRITECOPY; break;
521 ::CreateFileMappingW(FileHandle, 0, flprotect,
522 (Offset + Size) >> 32,
523 (Offset + Size) & 0xffffffff,
525 if (FileMappingHandle == NULL) {
526 error_code ec = windows_error(GetLastError());
527 if (FileDescriptor) {
529 _close(FileDescriptor);
531 ::CloseHandle(FileHandle);
535 DWORD dwDesiredAccess;
537 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
538 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
539 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
541 Mapping = ::MapViewOfFile(FileMappingHandle,
546 if (Mapping == NULL) {
547 error_code ec = windows_error(GetLastError());
548 ::CloseHandle(FileMappingHandle);
549 if (FileDescriptor) {
551 _close(FileDescriptor);
553 ::CloseHandle(FileHandle);
558 MEMORY_BASIC_INFORMATION mbi;
559 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
561 error_code ec = windows_error(GetLastError());
562 ::UnmapViewOfFile(Mapping);
563 ::CloseHandle(FileMappingHandle);
564 if (FileDescriptor) {
566 _close(FileDescriptor);
568 ::CloseHandle(FileHandle);
571 Size = mbi.RegionSize;
574 // Close all the handles except for the view. It will keep the other handles
576 ::CloseHandle(FileMappingHandle);
577 if (FileDescriptor) {
579 _close(FileDescriptor); // Also closes FileHandle.
581 ::CloseHandle(FileHandle);
582 return error_code::success();
585 mapped_file_region::mapped_file_region(const Twine &path,
594 , FileHandle(INVALID_HANDLE_VALUE)
595 , FileMappingHandle() {
596 SmallString<128> path_storage;
597 SmallVector<wchar_t, 128> path_utf16;
599 // Convert path to UTF-16.
600 if ((ec = UTF8ToUTF16(path.toStringRef(path_storage), path_utf16)))
603 // Get file handle for creating a file mapping.
604 FileHandle = ::CreateFileW(c_str(path_utf16),
605 Mode == readonly ? GENERIC_READ
606 : GENERIC_READ | GENERIC_WRITE,
607 Mode == readonly ? FILE_SHARE_READ
610 Mode == readonly ? OPEN_EXISTING
612 Mode == readonly ? FILE_ATTRIBUTE_READONLY
613 : FILE_ATTRIBUTE_NORMAL,
615 if (FileHandle == INVALID_HANDLE_VALUE) {
616 ec = windows_error(::GetLastError());
621 ec = init(FileDescriptor, true, offset);
623 Mapping = FileMappingHandle = 0;
624 FileHandle = INVALID_HANDLE_VALUE;
629 mapped_file_region::mapped_file_region(int fd,
639 , FileHandle(INVALID_HANDLE_VALUE)
640 , FileMappingHandle() {
641 FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
642 if (FileHandle == INVALID_HANDLE_VALUE) {
644 _close(FileDescriptor);
646 ec = make_error_code(errc::bad_file_descriptor);
650 ec = init(FileDescriptor, closefd, offset);
652 Mapping = FileMappingHandle = 0;
653 FileHandle = INVALID_HANDLE_VALUE;
658 mapped_file_region::~mapped_file_region() {
660 ::UnmapViewOfFile(Mapping);
663 mapped_file_region::mapped_file_region(mapped_file_region &&other)
666 , Mapping(other.Mapping)
667 , FileDescriptor(other.FileDescriptor)
668 , FileHandle(other.FileHandle)
669 , FileMappingHandle(other.FileMappingHandle) {
670 other.Mapping = other.FileMappingHandle = 0;
671 other.FileHandle = INVALID_HANDLE_VALUE;
672 other.FileDescriptor = 0;
675 mapped_file_region::mapmode mapped_file_region::flags() const {
676 assert(Mapping && "Mapping failed but used anyway!");
680 uint64_t mapped_file_region::size() const {
681 assert(Mapping && "Mapping failed but used anyway!");
685 char *mapped_file_region::data() const {
686 assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
687 assert(Mapping && "Mapping failed but used anyway!");
688 return reinterpret_cast<char*>(Mapping);
691 const char *mapped_file_region::const_data() const {
692 assert(Mapping && "Mapping failed but used anyway!");
693 return reinterpret_cast<const char*>(Mapping);
696 int mapped_file_region::alignment() {
698 ::GetSystemInfo(&SysInfo);
699 return SysInfo.dwAllocationGranularity;
702 error_code detail::directory_iterator_construct(detail::DirIterState &it,
704 SmallVector<wchar_t, 128> path_utf16;
706 if (error_code ec = UTF8ToUTF16(path,
710 // Convert path to the format that Windows is happy with.
711 if (path_utf16.size() > 0 &&
712 !is_separator(path_utf16[path.size() - 1]) &&
713 path_utf16[path.size() - 1] != L':') {
714 path_utf16.push_back(L'\\');
715 path_utf16.push_back(L'*');
717 path_utf16.push_back(L'*');
720 // Get the first directory entry.
721 WIN32_FIND_DATAW FirstFind;
722 ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
724 return windows_error(::GetLastError());
726 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
727 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
728 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
729 FirstFind.cFileName[1] == L'.'))
730 if (!::FindNextFileW(FindHandle, &FirstFind)) {
731 error_code ec = windows_error(::GetLastError());
733 if (ec == windows_error::no_more_files)
734 return detail::directory_iterator_destruct(it);
737 FilenameLen = ::wcslen(FirstFind.cFileName);
739 // Construct the current directory entry.
740 SmallString<128> directory_entry_name_utf8;
741 if (error_code ec = UTF16ToUTF8(FirstFind.cFileName,
742 ::wcslen(FirstFind.cFileName),
743 directory_entry_name_utf8))
746 it.IterationHandle = intptr_t(FindHandle.take());
747 SmallString<128> directory_entry_path(path);
748 path::append(directory_entry_path, directory_entry_name_utf8.str());
749 it.CurrentEntry = directory_entry(directory_entry_path.str());
751 return error_code::success();
754 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
755 if (it.IterationHandle != 0)
756 // Closes the handle if it's valid.
757 ScopedFindHandle close(HANDLE(it.IterationHandle));
758 it.IterationHandle = 0;
759 it.CurrentEntry = directory_entry();
760 return error_code::success();
763 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
764 WIN32_FIND_DATAW FindData;
765 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
766 error_code ec = windows_error(::GetLastError());
768 if (ec == windows_error::no_more_files)
769 return detail::directory_iterator_destruct(it);
773 size_t FilenameLen = ::wcslen(FindData.cFileName);
774 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
775 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
776 FindData.cFileName[1] == L'.'))
777 return directory_iterator_increment(it);
779 SmallString<128> directory_entry_path_utf8;
780 if (error_code ec = UTF16ToUTF8(FindData.cFileName,
781 ::wcslen(FindData.cFileName),
782 directory_entry_path_utf8))
785 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
786 return error_code::success();
789 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
790 bool map_writable, void *&result) {
791 assert(0 && "NOT IMPLEMENTED");
792 return windows_error::invalid_function;
795 error_code unmap_file_pages(void *base, size_t size) {
796 assert(0 && "NOT IMPLEMENTED");
797 return windows_error::invalid_function;
800 error_code openFileForRead(const Twine &Name, int &ResultFD) {
801 SmallString<128> PathStorage;
802 SmallVector<wchar_t, 128> PathUTF16;
804 if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
808 HANDLE H = ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
809 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
810 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
811 if (H == INVALID_HANDLE_VALUE) {
812 error_code EC = windows_error(::GetLastError());
813 // Provide a better error message when trying to open directories.
814 // This only runs if we failed to open the file, so there is probably
815 // no performances issues.
816 if (EC != windows_error::access_denied)
818 if (is_directory(Name))
819 return error_code(errc::is_a_directory, posix_category());
823 int FD = ::_open_osfhandle(intptr_t(H), 0);
826 return windows_error::invalid_handle;
830 return error_code::success();
833 error_code openFileForWrite(const Twine &Name, int &ResultFD,
834 sys::fs::OpenFlags Flags, unsigned Mode) {
835 // Verify that we don't have both "append" and "excl".
836 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
837 "Cannot specify both 'excl' and 'append' file creation flags!");
839 SmallString<128> PathStorage;
840 SmallVector<wchar_t, 128> PathUTF16;
842 if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
846 DWORD CreationDisposition;
848 CreationDisposition = CREATE_NEW;
849 else if (Flags & F_Append)
850 CreationDisposition = OPEN_ALWAYS;
852 CreationDisposition = CREATE_ALWAYS;
854 DWORD Access = GENERIC_WRITE;
856 Access |= GENERIC_READ;
858 HANDLE H = ::CreateFileW(PathUTF16.begin(), Access,
859 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
860 CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
862 if (H == INVALID_HANDLE_VALUE) {
863 error_code EC = windows_error(::GetLastError());
864 // Provide a better error message when trying to open directories.
865 // This only runs if we failed to open the file, so there is probably
866 // no performances issues.
867 if (EC != windows_error::access_denied)
869 if (is_directory(Name))
870 return error_code(errc::is_a_directory, posix_category());
875 if (Flags & F_Append)
876 OpenFlags |= _O_APPEND;
879 OpenFlags |= _O_TEXT;
881 int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
884 return windows_error::invalid_handle;
888 return error_code::success();
890 } // end namespace fs
894 bool home_directory(SmallVectorImpl<char> &result) {
895 wchar_t Path[MAX_PATH];
896 if (::SHGetFolderPathW(0, CSIDL_APPDATA | CSIDL_FLAG_CREATE, 0,
897 /*SHGFP_TYPE_CURRENT*/0, Path) != S_OK)
900 if (UTF16ToUTF8(Path, ::wcslen(Path), result))
906 } // end namespace path
909 llvm::error_code UTF8ToUTF16(llvm::StringRef utf8,
910 llvm::SmallVectorImpl<wchar_t> &utf16) {
912 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
913 utf8.size(), utf16.begin(), 0);
916 return llvm::windows_error(::GetLastError());
918 utf16.reserve(len + 1);
921 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
922 utf8.size(), utf16.begin(), utf16.size());
925 return llvm::windows_error(::GetLastError());
928 // Make utf16 null terminated.
932 return llvm::error_code::success();
935 llvm::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
936 llvm::SmallVectorImpl<char> &utf8) {
939 int len = ::WideCharToMultiByte(CP_UTF8, 0, utf16, utf16_len, utf8.begin(),
943 return llvm::windows_error(::GetLastError());
948 // Now do the actual conversion.
949 len = ::WideCharToMultiByte(CP_UTF8, 0, utf16, utf16_len, utf8.data(),
950 utf8.size(), NULL, NULL);
953 return llvm::windows_error(::GetLastError());
956 // Make utf8 null terminated.
960 return llvm::error_code::success();
962 } // end namespace windows
963 } // end namespace sys
964 } // end namespace llvm