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 error_code create_hard_link(const Twine &to, const Twine &from) {
163 SmallString<128> from_storage;
164 SmallString<128> to_storage;
165 StringRef f = from.toStringRef(from_storage);
166 StringRef t = to.toStringRef(to_storage);
168 // Convert to utf-16.
169 SmallVector<wchar_t, 128> wide_from;
170 SmallVector<wchar_t, 128> wide_to;
171 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
172 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
174 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
175 return windows_error(::GetLastError());
177 return error_code::success();
180 error_code remove(const Twine &path, bool IgnoreNonExisting) {
181 SmallString<128> path_storage;
182 SmallVector<wchar_t, 128> path_utf16;
185 if (error_code EC = status(path, ST)) {
186 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
188 return error_code::success();
191 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
195 if (ST.type() == file_type::directory_file) {
196 if (!::RemoveDirectoryW(c_str(path_utf16))) {
197 error_code EC = windows_error(::GetLastError());
198 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
201 return error_code::success();
203 if (!::DeleteFileW(c_str(path_utf16))) {
204 error_code EC = windows_error(::GetLastError());
205 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
208 return error_code::success();
211 error_code rename(const Twine &from, const Twine &to) {
213 SmallString<128> from_storage;
214 SmallString<128> to_storage;
215 StringRef f = from.toStringRef(from_storage);
216 StringRef t = to.toStringRef(to_storage);
218 // Convert to utf-16.
219 SmallVector<wchar_t, 128> wide_from;
220 SmallVector<wchar_t, 128> wide_to;
221 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
222 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
224 error_code ec = error_code::success();
225 for (int i = 0; i < 2000; i++) {
226 if (::MoveFileExW(wide_from.begin(), wide_to.begin(),
227 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
228 return error_code::success();
229 ec = windows_error(::GetLastError());
230 if (ec != windows_error::access_denied)
232 // Retry MoveFile() at ACCESS_DENIED.
233 // System scanners (eg. indexer) might open the source file when
234 // It is written and closed.
241 error_code resize_file(const Twine &path, uint64_t size) {
242 SmallString<128> path_storage;
243 SmallVector<wchar_t, 128> path_utf16;
245 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
249 int fd = ::_wopen(path_utf16.begin(), O_BINARY | _O_RDWR, S_IWRITE);
251 return error_code(errno, generic_category());
252 #ifdef HAVE__CHSIZE_S
253 errno_t error = ::_chsize_s(fd, size);
255 errno_t error = ::_chsize(fd, size);
258 return error_code(error, generic_category());
261 error_code exists(const Twine &path, bool &result) {
262 SmallString<128> path_storage;
263 SmallVector<wchar_t, 128> path_utf16;
265 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
269 DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
271 if (attributes == INVALID_FILE_ATTRIBUTES) {
272 // See if the file didn't actually exist.
273 error_code ec = make_error_code(windows_error(::GetLastError()));
274 if (ec != windows_error::file_not_found &&
275 ec != windows_error::path_not_found)
280 return error_code::success();
283 bool can_write(const Twine &Path) {
284 // FIXME: take security attributes into account.
285 SmallString<128> PathStorage;
286 SmallVector<wchar_t, 128> PathUtf16;
288 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
291 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
292 return (Attr != INVALID_FILE_ATTRIBUTES) && !(Attr & FILE_ATTRIBUTE_READONLY);
295 bool can_execute(const Twine &Path) {
296 SmallString<128> PathStorage;
297 SmallVector<wchar_t, 128> PathUtf16;
299 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
302 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
303 return Attr != INVALID_FILE_ATTRIBUTES;
306 bool equivalent(file_status A, file_status B) {
307 assert(status_known(A) && status_known(B));
308 return A.FileIndexHigh == B.FileIndexHigh &&
309 A.FileIndexLow == B.FileIndexLow &&
310 A.FileSizeHigh == B.FileSizeHigh &&
311 A.FileSizeLow == B.FileSizeLow &&
312 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
313 A.LastWriteTimeLow == B.LastWriteTimeLow &&
314 A.VolumeSerialNumber == B.VolumeSerialNumber;
317 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
318 file_status fsA, fsB;
319 if (error_code ec = status(A, fsA)) return ec;
320 if (error_code ec = status(B, fsB)) return ec;
321 result = equivalent(fsA, fsB);
322 return error_code::success();
325 static bool isReservedName(StringRef path) {
326 // This list of reserved names comes from MSDN, at:
327 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
328 static const char *sReservedNames[] = { "nul", "con", "prn", "aux",
329 "com1", "com2", "com3", "com4", "com5", "com6",
330 "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
331 "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9" };
333 // First, check to see if this is a device namespace, which always
334 // starts with \\.\, since device namespaces are not legal file paths.
335 if (path.startswith("\\\\.\\"))
338 // Then compare against the list of ancient reserved names
339 for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
340 if (path.equals_lower(sReservedNames[i]))
344 // The path isn't what we consider reserved.
348 static error_code getStatus(HANDLE FileHandle, file_status &Result) {
349 if (FileHandle == INVALID_HANDLE_VALUE)
350 goto handle_status_error;
352 switch (::GetFileType(FileHandle)) {
354 llvm_unreachable("Don't know anything about this file type");
355 case FILE_TYPE_UNKNOWN: {
356 DWORD Err = ::GetLastError();
358 return windows_error(Err);
359 Result = file_status(file_type::type_unknown);
360 return error_code::success();
365 Result = file_status(file_type::character_file);
366 return error_code::success();
368 Result = file_status(file_type::fifo_file);
369 return error_code::success();
372 BY_HANDLE_FILE_INFORMATION Info;
373 if (!::GetFileInformationByHandle(FileHandle, &Info))
374 goto handle_status_error;
377 file_type Type = (Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
378 ? file_type::directory_file
379 : file_type::regular_file;
381 file_status(Type, Info.ftLastWriteTime.dwHighDateTime,
382 Info.ftLastWriteTime.dwLowDateTime,
383 Info.dwVolumeSerialNumber, Info.nFileSizeHigh,
384 Info.nFileSizeLow, Info.nFileIndexHigh, Info.nFileIndexLow);
385 return error_code::success();
389 error_code EC = windows_error(::GetLastError());
390 if (EC == windows_error::file_not_found ||
391 EC == windows_error::path_not_found)
392 Result = file_status(file_type::file_not_found);
393 else if (EC == windows_error::sharing_violation)
394 Result = file_status(file_type::type_unknown);
396 Result = file_status(file_type::status_error);
400 error_code status(const Twine &path, file_status &result) {
401 SmallString<128> path_storage;
402 SmallVector<wchar_t, 128> path_utf16;
404 StringRef path8 = path.toStringRef(path_storage);
405 if (isReservedName(path8)) {
406 result = file_status(file_type::character_file);
407 return error_code::success();
410 if (error_code ec = UTF8ToUTF16(path8, path_utf16))
413 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
414 if (attr == INVALID_FILE_ATTRIBUTES)
415 return getStatus(INVALID_HANDLE_VALUE, result);
417 // Handle reparse points.
418 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
420 ::CreateFileW(path_utf16.begin(),
421 0, // Attributes only.
422 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
425 FILE_FLAG_BACKUP_SEMANTICS,
428 return getStatus(INVALID_HANDLE_VALUE, result);
432 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
433 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
434 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0));
436 return getStatus(INVALID_HANDLE_VALUE, result);
438 return getStatus(h, result);
441 error_code status(int FD, file_status &Result) {
442 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
443 return getStatus(FileHandle, Result);
446 error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
448 UI.QuadPart = Time.toWin32Time();
450 FT.dwLowDateTime = UI.LowPart;
451 FT.dwHighDateTime = UI.HighPart;
452 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
453 if (!SetFileTime(FileHandle, NULL, &FT, &FT))
454 return windows_error(::GetLastError());
455 return error_code::success();
458 error_code get_magic(const Twine &path, uint32_t len,
459 SmallVectorImpl<char> &result) {
460 SmallString<128> path_storage;
461 SmallVector<wchar_t, 128> path_utf16;
464 // Convert path to UTF-16.
465 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
470 HANDLE file = ::CreateFileW(c_str(path_utf16),
475 FILE_ATTRIBUTE_READONLY,
477 if (file == INVALID_HANDLE_VALUE)
478 return windows_error(::GetLastError());
484 DWORD bytes_read = 0;
485 BOOL read_success = ::ReadFile(file, result.data(), len, &bytes_read, NULL);
486 error_code ec = windows_error(::GetLastError());
488 if (!read_success || (bytes_read != len)) {
489 // Set result size to the number of bytes read if it's valid.
490 if (bytes_read <= len)
491 result.set_size(bytes_read);
492 // ERROR_HANDLE_EOF is mapped to errc::value_too_large.
496 result.set_size(len);
497 return error_code::success();
500 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
502 // Make sure that the requested size fits within SIZE_T.
503 if (Size > std::numeric_limits<SIZE_T>::max()) {
504 if (FileDescriptor) {
506 _close(FileDescriptor);
508 ::CloseHandle(FileHandle);
509 return make_error_code(errc::invalid_argument);
514 case readonly: flprotect = PAGE_READONLY; break;
515 case readwrite: flprotect = PAGE_READWRITE; break;
516 case priv: flprotect = PAGE_WRITECOPY; break;
520 ::CreateFileMappingW(FileHandle, 0, flprotect,
521 (Offset + Size) >> 32,
522 (Offset + Size) & 0xffffffff,
524 if (FileMappingHandle == NULL) {
525 error_code ec = windows_error(GetLastError());
526 if (FileDescriptor) {
528 _close(FileDescriptor);
530 ::CloseHandle(FileHandle);
534 DWORD dwDesiredAccess;
536 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
537 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
538 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
540 Mapping = ::MapViewOfFile(FileMappingHandle,
545 if (Mapping == NULL) {
546 error_code ec = windows_error(GetLastError());
547 ::CloseHandle(FileMappingHandle);
548 if (FileDescriptor) {
550 _close(FileDescriptor);
552 ::CloseHandle(FileHandle);
557 MEMORY_BASIC_INFORMATION mbi;
558 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
560 error_code ec = windows_error(GetLastError());
561 ::UnmapViewOfFile(Mapping);
562 ::CloseHandle(FileMappingHandle);
563 if (FileDescriptor) {
565 _close(FileDescriptor);
567 ::CloseHandle(FileHandle);
570 Size = mbi.RegionSize;
573 // Close all the handles except for the view. It will keep the other handles
575 ::CloseHandle(FileMappingHandle);
576 if (FileDescriptor) {
578 _close(FileDescriptor); // Also closes FileHandle.
580 ::CloseHandle(FileHandle);
581 return error_code::success();
584 mapped_file_region::mapped_file_region(const Twine &path,
593 , FileHandle(INVALID_HANDLE_VALUE)
594 , FileMappingHandle() {
595 SmallString<128> path_storage;
596 SmallVector<wchar_t, 128> path_utf16;
598 // Convert path to UTF-16.
599 if ((ec = UTF8ToUTF16(path.toStringRef(path_storage), path_utf16)))
602 // Get file handle for creating a file mapping.
603 FileHandle = ::CreateFileW(c_str(path_utf16),
604 Mode == readonly ? GENERIC_READ
605 : GENERIC_READ | GENERIC_WRITE,
606 Mode == readonly ? FILE_SHARE_READ
609 Mode == readonly ? OPEN_EXISTING
611 Mode == readonly ? FILE_ATTRIBUTE_READONLY
612 : FILE_ATTRIBUTE_NORMAL,
614 if (FileHandle == INVALID_HANDLE_VALUE) {
615 ec = windows_error(::GetLastError());
620 ec = init(FileDescriptor, true, offset);
622 Mapping = FileMappingHandle = 0;
623 FileHandle = INVALID_HANDLE_VALUE;
628 mapped_file_region::mapped_file_region(int fd,
638 , FileHandle(INVALID_HANDLE_VALUE)
639 , FileMappingHandle() {
640 FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
641 if (FileHandle == INVALID_HANDLE_VALUE) {
643 _close(FileDescriptor);
645 ec = make_error_code(errc::bad_file_descriptor);
649 ec = init(FileDescriptor, closefd, offset);
651 Mapping = FileMappingHandle = 0;
652 FileHandle = INVALID_HANDLE_VALUE;
657 mapped_file_region::~mapped_file_region() {
659 ::UnmapViewOfFile(Mapping);
662 #if LLVM_HAS_RVALUE_REFERENCES
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;
676 mapped_file_region::mapmode mapped_file_region::flags() const {
677 assert(Mapping && "Mapping failed but used anyway!");
681 uint64_t mapped_file_region::size() const {
682 assert(Mapping && "Mapping failed but used anyway!");
686 char *mapped_file_region::data() const {
687 assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
688 assert(Mapping && "Mapping failed but used anyway!");
689 return reinterpret_cast<char*>(Mapping);
692 const char *mapped_file_region::const_data() const {
693 assert(Mapping && "Mapping failed but used anyway!");
694 return reinterpret_cast<const char*>(Mapping);
697 int mapped_file_region::alignment() {
699 ::GetSystemInfo(&SysInfo);
700 return SysInfo.dwAllocationGranularity;
703 error_code detail::directory_iterator_construct(detail::DirIterState &it,
705 SmallVector<wchar_t, 128> path_utf16;
707 if (error_code ec = UTF8ToUTF16(path,
711 // Convert path to the format that Windows is happy with.
712 if (path_utf16.size() > 0 &&
713 !is_separator(path_utf16[path.size() - 1]) &&
714 path_utf16[path.size() - 1] != L':') {
715 path_utf16.push_back(L'\\');
716 path_utf16.push_back(L'*');
718 path_utf16.push_back(L'*');
721 // Get the first directory entry.
722 WIN32_FIND_DATAW FirstFind;
723 ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
725 return windows_error(::GetLastError());
727 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
728 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
729 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
730 FirstFind.cFileName[1] == L'.'))
731 if (!::FindNextFileW(FindHandle, &FirstFind)) {
732 error_code ec = windows_error(::GetLastError());
734 if (ec == windows_error::no_more_files)
735 return detail::directory_iterator_destruct(it);
738 FilenameLen = ::wcslen(FirstFind.cFileName);
740 // Construct the current directory entry.
741 SmallString<128> directory_entry_name_utf8;
742 if (error_code ec = UTF16ToUTF8(FirstFind.cFileName,
743 ::wcslen(FirstFind.cFileName),
744 directory_entry_name_utf8))
747 it.IterationHandle = intptr_t(FindHandle.take());
748 SmallString<128> directory_entry_path(path);
749 path::append(directory_entry_path, directory_entry_name_utf8.str());
750 it.CurrentEntry = directory_entry(directory_entry_path.str());
752 return error_code::success();
755 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
756 if (it.IterationHandle != 0)
757 // Closes the handle if it's valid.
758 ScopedFindHandle close(HANDLE(it.IterationHandle));
759 it.IterationHandle = 0;
760 it.CurrentEntry = directory_entry();
761 return error_code::success();
764 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
765 WIN32_FIND_DATAW FindData;
766 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
767 error_code ec = windows_error(::GetLastError());
769 if (ec == windows_error::no_more_files)
770 return detail::directory_iterator_destruct(it);
774 size_t FilenameLen = ::wcslen(FindData.cFileName);
775 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
776 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
777 FindData.cFileName[1] == L'.'))
778 return directory_iterator_increment(it);
780 SmallString<128> directory_entry_path_utf8;
781 if (error_code ec = UTF16ToUTF8(FindData.cFileName,
782 ::wcslen(FindData.cFileName),
783 directory_entry_path_utf8))
786 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
787 return error_code::success();
790 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
791 bool map_writable, void *&result) {
792 assert(0 && "NOT IMPLEMENTED");
793 return windows_error::invalid_function;
796 error_code unmap_file_pages(void *base, size_t size) {
797 assert(0 && "NOT IMPLEMENTED");
798 return windows_error::invalid_function;
801 error_code openFileForRead(const Twine &Name, int &ResultFD) {
802 SmallString<128> PathStorage;
803 SmallVector<wchar_t, 128> PathUTF16;
805 if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
809 HANDLE H = ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
810 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
811 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
812 if (H == INVALID_HANDLE_VALUE) {
813 error_code EC = windows_error(::GetLastError());
814 // Provide a better error message when trying to open directories.
815 // This only runs if we failed to open the file, so there is probably
816 // no performances issues.
817 if (EC != windows_error::access_denied)
819 if (is_directory(Name))
820 return error_code(errc::is_a_directory, posix_category());
824 int FD = ::_open_osfhandle(intptr_t(H), 0);
827 return windows_error::invalid_handle;
831 return error_code::success();
834 error_code openFileForWrite(const Twine &Name, int &ResultFD,
835 sys::fs::OpenFlags Flags, unsigned Mode) {
836 // Verify that we don't have both "append" and "excl".
837 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
838 "Cannot specify both 'excl' and 'append' file creation flags!");
840 SmallString<128> PathStorage;
841 SmallVector<wchar_t, 128> PathUTF16;
843 if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
847 DWORD CreationDisposition;
849 CreationDisposition = CREATE_NEW;
850 else if (Flags & F_Append)
851 CreationDisposition = OPEN_ALWAYS;
853 CreationDisposition = CREATE_ALWAYS;
855 DWORD Access = GENERIC_WRITE;
857 Access |= GENERIC_READ;
859 HANDLE H = ::CreateFileW(PathUTF16.begin(), Access,
860 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
861 CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
863 if (H == INVALID_HANDLE_VALUE) {
864 error_code EC = windows_error(::GetLastError());
865 // Provide a better error message when trying to open directories.
866 // This only runs if we failed to open the file, so there is probably
867 // no performances issues.
868 if (EC != windows_error::access_denied)
870 if (is_directory(Name))
871 return error_code(errc::is_a_directory, posix_category());
876 if (Flags & F_Append)
877 OpenFlags |= _O_APPEND;
880 OpenFlags |= _O_TEXT;
882 int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
885 return windows_error::invalid_handle;
889 return error_code::success();
891 } // end namespace fs
895 bool home_directory(SmallVectorImpl<char> &result) {
896 wchar_t Path[MAX_PATH];
897 if (::SHGetFolderPathW(0, CSIDL_APPDATA | CSIDL_FLAG_CREATE, 0,
898 /*SHGFP_TYPE_CURRENT*/0, Path) != S_OK)
901 if (UTF16ToUTF8(Path, ::wcslen(Path), result))
907 } // end namespace path
910 llvm::error_code UTF8ToUTF16(llvm::StringRef utf8,
911 llvm::SmallVectorImpl<wchar_t> &utf16) {
913 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
914 utf8.size(), utf16.begin(), 0);
917 return llvm::windows_error(::GetLastError());
919 utf16.reserve(len + 1);
922 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
923 utf8.size(), utf16.begin(), utf16.size());
926 return llvm::windows_error(::GetLastError());
929 // Make utf16 null terminated.
933 return llvm::error_code::success();
936 llvm::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
937 llvm::SmallVectorImpl<char> &utf8) {
940 int len = ::WideCharToMultiByte(CP_UTF8, 0, utf16, utf16_len, utf8.begin(),
944 return llvm::windows_error(::GetLastError());
949 // Now do the actual conversion.
950 len = ::WideCharToMultiByte(CP_UTF8, 0, utf16, utf16_len, utf8.data(),
951 utf8.size(), NULL, NULL);
954 return llvm::windows_error(::GetLastError());
957 // Make utf8 null terminated.
961 return llvm::error_code::success();
963 } // end namespace windows
964 } // end namespace sys
965 } // end namespace llvm