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 create_symbolic_link(const Twine &to, const Twine &from) {
182 SmallString<128> from_storage;
183 SmallString<128> to_storage;
184 StringRef f = from.toStringRef(from_storage);
185 StringRef t = to.toStringRef(to_storage);
187 // Convert to utf-16.
188 SmallVector<wchar_t, 128> wide_from;
189 SmallVector<wchar_t, 128> wide_to;
190 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
191 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
193 if (!::CreateSymbolicLinkW(wide_from.begin(), wide_to.begin(), NULL))
194 return windows_error(::GetLastError());
196 return error_code::success();
199 error_code remove(const Twine &path, bool IgnoreNonExisting) {
200 SmallString<128> path_storage;
201 SmallVector<wchar_t, 128> path_utf16;
204 if (error_code EC = status(path, ST)) {
205 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
207 return error_code::success();
210 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
214 if (ST.type() == file_type::directory_file) {
215 if (!::RemoveDirectoryW(c_str(path_utf16))) {
216 error_code EC = windows_error(::GetLastError());
217 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
220 return error_code::success();
222 if (!::DeleteFileW(c_str(path_utf16))) {
223 error_code EC = windows_error(::GetLastError());
224 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
227 return error_code::success();
230 error_code rename(const Twine &from, const Twine &to) {
232 SmallString<128> from_storage;
233 SmallString<128> to_storage;
234 StringRef f = from.toStringRef(from_storage);
235 StringRef t = to.toStringRef(to_storage);
237 // Convert to utf-16.
238 SmallVector<wchar_t, 128> wide_from;
239 SmallVector<wchar_t, 128> wide_to;
240 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
241 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
243 error_code ec = error_code::success();
244 for (int i = 0; i < 2000; i++) {
245 if (::MoveFileExW(wide_from.begin(), wide_to.begin(),
246 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
247 return error_code::success();
248 ec = windows_error(::GetLastError());
249 if (ec != windows_error::access_denied)
251 // Retry MoveFile() at ACCESS_DENIED.
252 // System scanners (eg. indexer) might open the source file when
253 // It is written and closed.
260 error_code resize_file(const Twine &path, uint64_t size) {
261 SmallString<128> path_storage;
262 SmallVector<wchar_t, 128> path_utf16;
264 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
268 int fd = ::_wopen(path_utf16.begin(), O_BINARY | _O_RDWR, S_IWRITE);
270 return error_code(errno, generic_category());
271 #ifdef HAVE__CHSIZE_S
272 errno_t error = ::_chsize_s(fd, size);
274 errno_t error = ::_chsize(fd, size);
277 return error_code(error, generic_category());
280 error_code exists(const Twine &path, bool &result) {
281 SmallString<128> path_storage;
282 SmallVector<wchar_t, 128> path_utf16;
284 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
288 DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
290 if (attributes == INVALID_FILE_ATTRIBUTES) {
291 // See if the file didn't actually exist.
292 error_code ec = make_error_code(windows_error(::GetLastError()));
293 if (ec != windows_error::file_not_found &&
294 ec != windows_error::path_not_found)
299 return error_code::success();
302 bool can_write(const Twine &Path) {
303 // FIXME: take security attributes into account.
304 SmallString<128> PathStorage;
305 SmallVector<wchar_t, 128> PathUtf16;
307 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
310 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
311 return (Attr != INVALID_FILE_ATTRIBUTES) && !(Attr & FILE_ATTRIBUTE_READONLY);
314 bool can_execute(const Twine &Path) {
315 SmallString<128> PathStorage;
316 SmallVector<wchar_t, 128> PathUtf16;
318 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
321 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
322 return Attr != INVALID_FILE_ATTRIBUTES;
325 bool equivalent(file_status A, file_status B) {
326 assert(status_known(A) && status_known(B));
327 return A.FileIndexHigh == B.FileIndexHigh &&
328 A.FileIndexLow == B.FileIndexLow &&
329 A.FileSizeHigh == B.FileSizeHigh &&
330 A.FileSizeLow == B.FileSizeLow &&
331 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
332 A.LastWriteTimeLow == B.LastWriteTimeLow &&
333 A.VolumeSerialNumber == B.VolumeSerialNumber;
336 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
337 file_status fsA, fsB;
338 if (error_code ec = status(A, fsA)) return ec;
339 if (error_code ec = status(B, fsB)) return ec;
340 result = equivalent(fsA, fsB);
341 return error_code::success();
344 static bool isReservedName(StringRef path) {
345 // This list of reserved names comes from MSDN, at:
346 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
347 static const char *sReservedNames[] = { "nul", "con", "prn", "aux",
348 "com1", "com2", "com3", "com4", "com5", "com6",
349 "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
350 "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9" };
352 // First, check to see if this is a device namespace, which always
353 // starts with \\.\, since device namespaces are not legal file paths.
354 if (path.startswith("\\\\.\\"))
357 // Then compare against the list of ancient reserved names
358 for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
359 if (path.equals_lower(sReservedNames[i]))
363 // The path isn't what we consider reserved.
367 static error_code getStatus(HANDLE FileHandle, file_status &Result) {
368 if (FileHandle == INVALID_HANDLE_VALUE)
369 goto handle_status_error;
371 switch (::GetFileType(FileHandle)) {
373 llvm_unreachable("Don't know anything about this file type");
374 case FILE_TYPE_UNKNOWN: {
375 DWORD Err = ::GetLastError();
377 return windows_error(Err);
378 Result = file_status(file_type::type_unknown);
379 return error_code::success();
384 Result = file_status(file_type::character_file);
385 return error_code::success();
387 Result = file_status(file_type::fifo_file);
388 return error_code::success();
391 BY_HANDLE_FILE_INFORMATION Info;
392 if (!::GetFileInformationByHandle(FileHandle, &Info))
393 goto handle_status_error;
396 file_type Type = (Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
397 ? file_type::directory_file
398 : file_type::regular_file;
400 file_status(Type, Info.ftLastWriteTime.dwHighDateTime,
401 Info.ftLastWriteTime.dwLowDateTime,
402 Info.dwVolumeSerialNumber, Info.nFileSizeHigh,
403 Info.nFileSizeLow, Info.nFileIndexHigh, Info.nFileIndexLow);
404 return error_code::success();
408 error_code EC = windows_error(::GetLastError());
409 if (EC == windows_error::file_not_found ||
410 EC == windows_error::path_not_found)
411 Result = file_status(file_type::file_not_found);
412 else if (EC == windows_error::sharing_violation)
413 Result = file_status(file_type::type_unknown);
415 Result = file_status(file_type::status_error);
419 error_code status(const Twine &path, file_status &result) {
420 SmallString<128> path_storage;
421 SmallVector<wchar_t, 128> path_utf16;
423 StringRef path8 = path.toStringRef(path_storage);
424 if (isReservedName(path8)) {
425 result = file_status(file_type::character_file);
426 return error_code::success();
429 if (error_code ec = UTF8ToUTF16(path8, path_utf16))
432 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
433 if (attr == INVALID_FILE_ATTRIBUTES)
434 return getStatus(INVALID_HANDLE_VALUE, result);
436 // Handle reparse points.
437 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
439 ::CreateFileW(path_utf16.begin(),
440 0, // Attributes only.
441 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
444 FILE_FLAG_BACKUP_SEMANTICS,
447 return getStatus(INVALID_HANDLE_VALUE, result);
451 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
452 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
453 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0));
455 return getStatus(INVALID_HANDLE_VALUE, result);
457 return getStatus(h, result);
460 error_code status(int FD, file_status &Result) {
461 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
462 return getStatus(FileHandle, Result);
465 error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
467 UI.QuadPart = Time.toWin32Time();
469 FT.dwLowDateTime = UI.LowPart;
470 FT.dwHighDateTime = UI.HighPart;
471 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
472 if (!SetFileTime(FileHandle, NULL, &FT, &FT))
473 return windows_error(::GetLastError());
474 return error_code::success();
477 error_code get_magic(const Twine &path, uint32_t len,
478 SmallVectorImpl<char> &result) {
479 SmallString<128> path_storage;
480 SmallVector<wchar_t, 128> path_utf16;
483 // Convert path to UTF-16.
484 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
489 HANDLE file = ::CreateFileW(c_str(path_utf16),
494 FILE_ATTRIBUTE_READONLY,
496 if (file == INVALID_HANDLE_VALUE)
497 return windows_error(::GetLastError());
503 DWORD bytes_read = 0;
504 BOOL read_success = ::ReadFile(file, result.data(), len, &bytes_read, NULL);
505 error_code ec = windows_error(::GetLastError());
507 if (!read_success || (bytes_read != len)) {
508 // Set result size to the number of bytes read if it's valid.
509 if (bytes_read <= len)
510 result.set_size(bytes_read);
511 // ERROR_HANDLE_EOF is mapped to errc::value_too_large.
515 result.set_size(len);
516 return error_code::success();
519 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
521 // Make sure that the requested size fits within SIZE_T.
522 if (Size > std::numeric_limits<SIZE_T>::max()) {
523 if (FileDescriptor) {
525 _close(FileDescriptor);
527 ::CloseHandle(FileHandle);
528 return make_error_code(errc::invalid_argument);
533 case readonly: flprotect = PAGE_READONLY; break;
534 case readwrite: flprotect = PAGE_READWRITE; break;
535 case priv: flprotect = PAGE_WRITECOPY; break;
539 ::CreateFileMappingW(FileHandle, 0, flprotect,
540 (Offset + Size) >> 32,
541 (Offset + Size) & 0xffffffff,
543 if (FileMappingHandle == NULL) {
544 error_code ec = windows_error(GetLastError());
545 if (FileDescriptor) {
547 _close(FileDescriptor);
549 ::CloseHandle(FileHandle);
553 DWORD dwDesiredAccess;
555 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
556 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
557 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
559 Mapping = ::MapViewOfFile(FileMappingHandle,
564 if (Mapping == NULL) {
565 error_code ec = windows_error(GetLastError());
566 ::CloseHandle(FileMappingHandle);
567 if (FileDescriptor) {
569 _close(FileDescriptor);
571 ::CloseHandle(FileHandle);
576 MEMORY_BASIC_INFORMATION mbi;
577 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
579 error_code ec = windows_error(GetLastError());
580 ::UnmapViewOfFile(Mapping);
581 ::CloseHandle(FileMappingHandle);
582 if (FileDescriptor) {
584 _close(FileDescriptor);
586 ::CloseHandle(FileHandle);
589 Size = mbi.RegionSize;
592 // Close all the handles except for the view. It will keep the other handles
594 ::CloseHandle(FileMappingHandle);
595 if (FileDescriptor) {
597 _close(FileDescriptor); // Also closes FileHandle.
599 ::CloseHandle(FileHandle);
600 return error_code::success();
603 mapped_file_region::mapped_file_region(const Twine &path,
612 , FileHandle(INVALID_HANDLE_VALUE)
613 , FileMappingHandle() {
614 SmallString<128> path_storage;
615 SmallVector<wchar_t, 128> path_utf16;
617 // Convert path to UTF-16.
618 if ((ec = UTF8ToUTF16(path.toStringRef(path_storage), path_utf16)))
621 // Get file handle for creating a file mapping.
622 FileHandle = ::CreateFileW(c_str(path_utf16),
623 Mode == readonly ? GENERIC_READ
624 : GENERIC_READ | GENERIC_WRITE,
625 Mode == readonly ? FILE_SHARE_READ
628 Mode == readonly ? OPEN_EXISTING
630 Mode == readonly ? FILE_ATTRIBUTE_READONLY
631 : FILE_ATTRIBUTE_NORMAL,
633 if (FileHandle == INVALID_HANDLE_VALUE) {
634 ec = windows_error(::GetLastError());
639 ec = init(FileDescriptor, true, offset);
641 Mapping = FileMappingHandle = 0;
642 FileHandle = INVALID_HANDLE_VALUE;
647 mapped_file_region::mapped_file_region(int fd,
657 , FileHandle(INVALID_HANDLE_VALUE)
658 , FileMappingHandle() {
659 FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
660 if (FileHandle == INVALID_HANDLE_VALUE) {
662 _close(FileDescriptor);
664 ec = make_error_code(errc::bad_file_descriptor);
668 ec = init(FileDescriptor, closefd, offset);
670 Mapping = FileMappingHandle = 0;
671 FileHandle = INVALID_HANDLE_VALUE;
676 mapped_file_region::~mapped_file_region() {
678 ::UnmapViewOfFile(Mapping);
681 mapped_file_region::mapped_file_region(mapped_file_region &&other)
684 , Mapping(other.Mapping)
685 , FileDescriptor(other.FileDescriptor)
686 , FileHandle(other.FileHandle)
687 , FileMappingHandle(other.FileMappingHandle) {
688 other.Mapping = other.FileMappingHandle = 0;
689 other.FileHandle = INVALID_HANDLE_VALUE;
690 other.FileDescriptor = 0;
693 mapped_file_region::mapmode mapped_file_region::flags() const {
694 assert(Mapping && "Mapping failed but used anyway!");
698 uint64_t mapped_file_region::size() const {
699 assert(Mapping && "Mapping failed but used anyway!");
703 char *mapped_file_region::data() const {
704 assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
705 assert(Mapping && "Mapping failed but used anyway!");
706 return reinterpret_cast<char*>(Mapping);
709 const char *mapped_file_region::const_data() const {
710 assert(Mapping && "Mapping failed but used anyway!");
711 return reinterpret_cast<const char*>(Mapping);
714 int mapped_file_region::alignment() {
716 ::GetSystemInfo(&SysInfo);
717 return SysInfo.dwAllocationGranularity;
720 error_code detail::directory_iterator_construct(detail::DirIterState &it,
722 SmallVector<wchar_t, 128> path_utf16;
724 if (error_code ec = UTF8ToUTF16(path,
728 // Convert path to the format that Windows is happy with.
729 if (path_utf16.size() > 0 &&
730 !is_separator(path_utf16[path.size() - 1]) &&
731 path_utf16[path.size() - 1] != L':') {
732 path_utf16.push_back(L'\\');
733 path_utf16.push_back(L'*');
735 path_utf16.push_back(L'*');
738 // Get the first directory entry.
739 WIN32_FIND_DATAW FirstFind;
740 ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
742 return windows_error(::GetLastError());
744 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
745 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
746 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
747 FirstFind.cFileName[1] == L'.'))
748 if (!::FindNextFileW(FindHandle, &FirstFind)) {
749 error_code ec = windows_error(::GetLastError());
751 if (ec == windows_error::no_more_files)
752 return detail::directory_iterator_destruct(it);
755 FilenameLen = ::wcslen(FirstFind.cFileName);
757 // Construct the current directory entry.
758 SmallString<128> directory_entry_name_utf8;
759 if (error_code ec = UTF16ToUTF8(FirstFind.cFileName,
760 ::wcslen(FirstFind.cFileName),
761 directory_entry_name_utf8))
764 it.IterationHandle = intptr_t(FindHandle.take());
765 SmallString<128> directory_entry_path(path);
766 path::append(directory_entry_path, directory_entry_name_utf8.str());
767 it.CurrentEntry = directory_entry(directory_entry_path.str());
769 return error_code::success();
772 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
773 if (it.IterationHandle != 0)
774 // Closes the handle if it's valid.
775 ScopedFindHandle close(HANDLE(it.IterationHandle));
776 it.IterationHandle = 0;
777 it.CurrentEntry = directory_entry();
778 return error_code::success();
781 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
782 WIN32_FIND_DATAW FindData;
783 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
784 error_code ec = windows_error(::GetLastError());
786 if (ec == windows_error::no_more_files)
787 return detail::directory_iterator_destruct(it);
791 size_t FilenameLen = ::wcslen(FindData.cFileName);
792 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
793 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
794 FindData.cFileName[1] == L'.'))
795 return directory_iterator_increment(it);
797 SmallString<128> directory_entry_path_utf8;
798 if (error_code ec = UTF16ToUTF8(FindData.cFileName,
799 ::wcslen(FindData.cFileName),
800 directory_entry_path_utf8))
803 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
804 return error_code::success();
807 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
808 bool map_writable, void *&result) {
809 assert(0 && "NOT IMPLEMENTED");
810 return windows_error::invalid_function;
813 error_code unmap_file_pages(void *base, size_t size) {
814 assert(0 && "NOT IMPLEMENTED");
815 return windows_error::invalid_function;
818 error_code openFileForRead(const Twine &Name, int &ResultFD) {
819 SmallString<128> PathStorage;
820 SmallVector<wchar_t, 128> PathUTF16;
822 if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
826 HANDLE H = ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
827 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
828 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
829 if (H == INVALID_HANDLE_VALUE) {
830 error_code EC = windows_error(::GetLastError());
831 // Provide a better error message when trying to open directories.
832 // This only runs if we failed to open the file, so there is probably
833 // no performances issues.
834 if (EC != windows_error::access_denied)
836 if (is_directory(Name))
837 return error_code(errc::is_a_directory, posix_category());
841 int FD = ::_open_osfhandle(intptr_t(H), 0);
844 return windows_error::invalid_handle;
848 return error_code::success();
851 error_code openFileForWrite(const Twine &Name, int &ResultFD,
852 sys::fs::OpenFlags Flags, unsigned Mode) {
853 // Verify that we don't have both "append" and "excl".
854 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
855 "Cannot specify both 'excl' and 'append' file creation flags!");
857 SmallString<128> PathStorage;
858 SmallVector<wchar_t, 128> PathUTF16;
860 if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
864 DWORD CreationDisposition;
866 CreationDisposition = CREATE_NEW;
867 else if (Flags & F_Append)
868 CreationDisposition = OPEN_ALWAYS;
870 CreationDisposition = CREATE_ALWAYS;
872 DWORD Access = GENERIC_WRITE;
874 Access |= GENERIC_READ;
876 HANDLE H = ::CreateFileW(PathUTF16.begin(), Access,
877 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
878 CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
880 if (H == INVALID_HANDLE_VALUE) {
881 error_code EC = windows_error(::GetLastError());
882 // Provide a better error message when trying to open directories.
883 // This only runs if we failed to open the file, so there is probably
884 // no performances issues.
885 if (EC != windows_error::access_denied)
887 if (is_directory(Name))
888 return error_code(errc::is_a_directory, posix_category());
893 if (Flags & F_Append)
894 OpenFlags |= _O_APPEND;
897 OpenFlags |= _O_TEXT;
899 int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
902 return windows_error::invalid_handle;
906 return error_code::success();
908 } // end namespace fs
912 bool home_directory(SmallVectorImpl<char> &result) {
913 wchar_t Path[MAX_PATH];
914 if (::SHGetFolderPathW(0, CSIDL_APPDATA | CSIDL_FLAG_CREATE, 0,
915 /*SHGFP_TYPE_CURRENT*/0, Path) != S_OK)
918 if (UTF16ToUTF8(Path, ::wcslen(Path), result))
924 } // end namespace path
927 llvm::error_code UTF8ToUTF16(llvm::StringRef utf8,
928 llvm::SmallVectorImpl<wchar_t> &utf16) {
930 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
931 utf8.size(), utf16.begin(), 0);
934 return llvm::windows_error(::GetLastError());
936 utf16.reserve(len + 1);
939 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
940 utf8.size(), utf16.begin(), utf16.size());
943 return llvm::windows_error(::GetLastError());
946 // Make utf16 null terminated.
950 return llvm::error_code::success();
953 llvm::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
954 llvm::SmallVectorImpl<char> &utf8) {
957 int len = ::WideCharToMultiByte(CP_UTF8, 0, utf16, utf16_len, utf8.begin(),
961 return llvm::windows_error(::GetLastError());
966 // Now do the actual conversion.
967 len = ::WideCharToMultiByte(CP_UTF8, 0, utf16, utf16_len, utf8.data(),
968 utf8.size(), NULL, NULL);
971 return llvm::windows_error(::GetLastError());
974 // Make utf8 null terminated.
978 return llvm::error_code::success();
980 } // end namespace windows
981 } // end namespace sys
982 } // end namespace llvm