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"
24 #include <sys/types.h>
28 // MinGW doesn't define this.
29 #ifndef _ERRNO_T_DEFINED
30 #define _ERRNO_T_DEFINED
35 # pragma comment(lib, "advapi32.lib") // This provides CryptAcquireContextW.
40 using llvm::sys::windows::UTF8ToUTF16;
41 using llvm::sys::windows::UTF16ToUTF8;
44 typedef BOOLEAN (WINAPI *PtrCreateSymbolicLinkW)(
45 /*__in*/ LPCWSTR lpSymlinkFileName,
46 /*__in*/ LPCWSTR lpTargetFileName,
47 /*__in*/ DWORD dwFlags);
49 PtrCreateSymbolicLinkW create_symbolic_link_api = PtrCreateSymbolicLinkW(
50 ::GetProcAddress(::GetModuleHandleA("kernel32.dll"),
51 "CreateSymbolicLinkW"));
53 error_code TempDir(SmallVectorImpl<wchar_t> &result) {
55 DWORD len = ::GetTempPathW(result.capacity(), result.begin());
58 return windows_error(::GetLastError());
60 if (len > result.capacity()) {
66 return error_code::success();
69 bool is_separator(const wchar_t value) {
80 // FIXME: mode should be used here and default to user r/w only,
81 // it currently comes in as a UNIX mode.
82 static error_code createUniqueEntity(const Twine &model, int &result_fd,
83 SmallVectorImpl<char> &result_path,
84 bool makeAbsolute, unsigned mode,
86 // Use result_path as temp storage.
87 result_path.set_size(0);
88 StringRef m = model.toStringRef(result_path);
90 SmallVector<wchar_t, 128> model_utf16;
91 if (error_code ec = UTF8ToUTF16(m, model_utf16)) return ec;
94 // Make model absolute by prepending a temp directory if it's not already.
95 bool absolute = sys::path::is_absolute(m);
98 SmallVector<wchar_t, 64> temp_dir;
99 if (error_code ec = TempDir(temp_dir)) return ec;
100 // Handle c: by removing it.
101 if (model_utf16.size() > 2 && model_utf16[1] == L':') {
102 model_utf16.erase(model_utf16.begin(), model_utf16.begin() + 2);
104 model_utf16.insert(model_utf16.begin(), temp_dir.begin(), temp_dir.end());
108 // Replace '%' with random chars. From here on, DO NOT modify model. It may be
109 // needed if the randomly chosen path already exists.
110 SmallVector<wchar_t, 128> random_path_utf16;
112 // Get a Crypto Provider for CryptGenRandom.
114 if (!::CryptAcquireContextW(&HCPC,
118 CRYPT_VERIFYCONTEXT))
119 return windows_error(::GetLastError());
120 ScopedCryptContext CryptoProvider(HCPC);
123 random_path_utf16.set_size(0);
124 for (SmallVectorImpl<wchar_t>::const_iterator i = model_utf16.begin(),
125 e = model_utf16.end();
129 if (!::CryptGenRandom(CryptoProvider, 1, &val))
130 return windows_error(::GetLastError());
131 random_path_utf16.push_back("0123456789abcdef"[val & 15]);
134 random_path_utf16.push_back(*i);
136 // Make random_path_utf16 null terminated.
137 random_path_utf16.push_back(0);
138 random_path_utf16.pop_back();
140 HANDLE TempFileHandle = INVALID_HANDLE_VALUE;
144 // Try to create + open the path.
146 ::CreateFileW(random_path_utf16.begin(), GENERIC_READ | GENERIC_WRITE,
147 FILE_SHARE_READ, NULL,
148 // Return ERROR_FILE_EXISTS if the file
150 CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY, NULL);
151 if (TempFileHandle == INVALID_HANDLE_VALUE) {
152 // If the file existed, try again, otherwise, error.
153 error_code ec = windows_error(::GetLastError());
154 if (ec == windows_error::file_exists)
155 goto retry_random_path;
160 // Convert the Windows API file handle into a C-runtime handle.
161 int fd = ::_open_osfhandle(intptr_t(TempFileHandle), 0);
163 ::CloseHandle(TempFileHandle);
164 ::DeleteFileW(random_path_utf16.begin());
165 // MSDN doesn't say anything about _open_osfhandle setting errno or
166 // GetLastError(), so just return invalid_handle.
167 return windows_error::invalid_handle;
175 DWORD attributes = ::GetFileAttributesW(random_path_utf16.begin());
176 if (attributes != INVALID_FILE_ATTRIBUTES)
177 goto retry_random_path;
178 error_code EC = make_error_code(windows_error(::GetLastError()));
179 if (EC != windows_error::file_not_found &&
180 EC != windows_error::path_not_found)
186 if (!::CreateDirectoryW(random_path_utf16.begin(), NULL)) {
187 error_code EC = windows_error(::GetLastError());
188 if (EC != windows_error::already_exists)
190 goto retry_random_path;
195 // Set result_path to the utf-8 representation of the path.
196 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
197 random_path_utf16.size(), result_path)) {
200 ::CloseHandle(TempFileHandle);
201 ::DeleteFileW(random_path_utf16.begin());
205 ::RemoveDirectoryW(random_path_utf16.begin());
211 return error_code::success();
218 std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
219 char pathname[MAX_PATH];
220 DWORD ret = ::GetModuleFileNameA(NULL, pathname, MAX_PATH);
221 return ret != MAX_PATH ? pathname : "";
224 UniqueID file_status::getUniqueID() const {
225 // The file is uniquely identified by the volume serial number along
226 // with the 64-bit file identifier.
227 uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
228 static_cast<uint64_t>(FileIndexLow);
230 return UniqueID(VolumeSerialNumber, FileID);
233 TimeValue file_status::getLastModificationTime() const {
235 UI.LowPart = LastWriteTimeLow;
236 UI.HighPart = LastWriteTimeHigh;
239 Ret.fromWin32Time(UI.QuadPart);
243 error_code current_path(SmallVectorImpl<char> &result) {
244 SmallVector<wchar_t, 128> cur_path;
245 cur_path.reserve(128);
247 DWORD len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
249 // A zero return value indicates a failure other than insufficient space.
251 return windows_error(::GetLastError());
253 // If there's insufficient space, the len returned is larger than the len
255 if (len > cur_path.capacity()) {
256 cur_path.reserve(len);
260 cur_path.set_size(len);
261 return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
264 error_code create_directory(const Twine &path, bool &existed) {
265 SmallString<128> path_storage;
266 SmallVector<wchar_t, 128> path_utf16;
268 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
272 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
273 error_code ec = windows_error(::GetLastError());
274 if (ec == windows_error::already_exists)
281 return error_code::success();
284 error_code create_hard_link(const Twine &to, const Twine &from) {
286 SmallString<128> from_storage;
287 SmallString<128> to_storage;
288 StringRef f = from.toStringRef(from_storage);
289 StringRef t = to.toStringRef(to_storage);
291 // Convert to utf-16.
292 SmallVector<wchar_t, 128> wide_from;
293 SmallVector<wchar_t, 128> wide_to;
294 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
295 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
297 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
298 return windows_error(::GetLastError());
300 return error_code::success();
303 error_code create_symlink(const Twine &to, const Twine &from) {
304 // Only do it if the function is available at runtime.
305 if (!create_symbolic_link_api)
306 return make_error_code(errc::function_not_supported);
309 SmallString<128> from_storage;
310 SmallString<128> to_storage;
311 StringRef f = from.toStringRef(from_storage);
312 StringRef t = to.toStringRef(to_storage);
314 // Convert to utf-16.
315 SmallVector<wchar_t, 128> wide_from;
316 SmallVector<wchar_t, 128> wide_to;
317 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
318 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
320 if (!create_symbolic_link_api(wide_from.begin(), wide_to.begin(), 0))
321 return windows_error(::GetLastError());
323 return error_code::success();
326 error_code remove(const Twine &path, bool &existed) {
327 SmallString<128> path_storage;
328 SmallVector<wchar_t, 128> path_utf16;
331 error_code EC = status(path, st);
333 if (EC == windows_error::file_not_found ||
334 EC == windows_error::path_not_found) {
336 return error_code::success();
341 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
345 if (st.type() == file_type::directory_file) {
346 if (!::RemoveDirectoryW(c_str(path_utf16))) {
347 error_code ec = windows_error(::GetLastError());
348 if (ec != windows_error::file_not_found)
354 if (!::DeleteFileW(c_str(path_utf16))) {
355 error_code ec = windows_error(::GetLastError());
356 if (ec != windows_error::file_not_found)
363 return error_code::success();
366 error_code rename(const Twine &from, const Twine &to) {
368 SmallString<128> from_storage;
369 SmallString<128> to_storage;
370 StringRef f = from.toStringRef(from_storage);
371 StringRef t = to.toStringRef(to_storage);
373 // Convert to utf-16.
374 SmallVector<wchar_t, 128> wide_from;
375 SmallVector<wchar_t, 128> wide_to;
376 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
377 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
379 error_code ec = error_code::success();
380 for (int i = 0; i < 2000; i++) {
381 if (::MoveFileExW(wide_from.begin(), wide_to.begin(),
382 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
383 return error_code::success();
384 ec = windows_error(::GetLastError());
385 if (ec != windows_error::access_denied)
387 // Retry MoveFile() at ACCESS_DENIED.
388 // System scanners (eg. indexer) might open the source file when
389 // It is written and closed.
396 error_code resize_file(const Twine &path, uint64_t size) {
397 SmallString<128> path_storage;
398 SmallVector<wchar_t, 128> path_utf16;
400 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
404 int fd = ::_wopen(path_utf16.begin(), O_BINARY | _O_RDWR, S_IWRITE);
406 return error_code(errno, generic_category());
407 #ifdef HAVE__CHSIZE_S
408 errno_t error = ::_chsize_s(fd, size);
410 errno_t error = ::_chsize(fd, size);
413 return error_code(error, generic_category());
416 error_code exists(const Twine &path, bool &result) {
417 SmallString<128> path_storage;
418 SmallVector<wchar_t, 128> path_utf16;
420 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
424 DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
426 if (attributes == INVALID_FILE_ATTRIBUTES) {
427 // See if the file didn't actually exist.
428 error_code ec = make_error_code(windows_error(::GetLastError()));
429 if (ec != windows_error::file_not_found &&
430 ec != windows_error::path_not_found)
435 return error_code::success();
438 bool can_write(const Twine &Path) {
439 // FIXME: take security attributes into account.
440 SmallString<128> PathStorage;
441 SmallVector<wchar_t, 128> PathUtf16;
443 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
446 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
447 return (Attr != INVALID_FILE_ATTRIBUTES) && !(Attr & FILE_ATTRIBUTE_READONLY);
450 bool can_execute(const Twine &Path) {
451 SmallString<128> PathStorage;
452 SmallVector<wchar_t, 128> PathUtf16;
454 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
457 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
458 return Attr != INVALID_FILE_ATTRIBUTES;
461 bool equivalent(file_status A, file_status B) {
462 assert(status_known(A) && status_known(B));
463 return A.FileIndexHigh == B.FileIndexHigh &&
464 A.FileIndexLow == B.FileIndexLow &&
465 A.FileSizeHigh == B.FileSizeHigh &&
466 A.FileSizeLow == B.FileSizeLow &&
467 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
468 A.LastWriteTimeLow == B.LastWriteTimeLow &&
469 A.VolumeSerialNumber == B.VolumeSerialNumber;
472 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
473 file_status fsA, fsB;
474 if (error_code ec = status(A, fsA)) return ec;
475 if (error_code ec = status(B, fsB)) return ec;
476 result = equivalent(fsA, fsB);
477 return error_code::success();
480 static bool isReservedName(StringRef path) {
481 // This list of reserved names comes from MSDN, at:
482 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
483 static const char *sReservedNames[] = { "nul", "con", "prn", "aux",
484 "com1", "com2", "com3", "com4", "com5", "com6",
485 "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
486 "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9" };
488 // First, check to see if this is a device namespace, which always
489 // starts with \\.\, since device namespaces are not legal file paths.
490 if (path.startswith("\\\\.\\"))
493 // Then compare against the list of ancient reserved names
494 for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
495 if (path.equals_lower(sReservedNames[i]))
499 // The path isn't what we consider reserved.
503 static error_code getStatus(HANDLE FileHandle, file_status &Result) {
504 if (FileHandle == INVALID_HANDLE_VALUE)
505 goto handle_status_error;
507 switch (::GetFileType(FileHandle)) {
509 llvm_unreachable("Don't know anything about this file type");
510 case FILE_TYPE_UNKNOWN: {
511 DWORD Err = ::GetLastError();
513 return windows_error(Err);
514 Result = file_status(file_type::type_unknown);
515 return error_code::success();
520 Result = file_status(file_type::character_file);
521 return error_code::success();
523 Result = file_status(file_type::fifo_file);
524 return error_code::success();
527 BY_HANDLE_FILE_INFORMATION Info;
528 if (!::GetFileInformationByHandle(FileHandle, &Info))
529 goto handle_status_error;
532 file_type Type = (Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
533 ? file_type::directory_file
534 : file_type::regular_file;
536 file_status(Type, Info.ftLastWriteTime.dwHighDateTime,
537 Info.ftLastWriteTime.dwLowDateTime,
538 Info.dwVolumeSerialNumber, Info.nFileSizeHigh,
539 Info.nFileSizeLow, Info.nFileIndexHigh, Info.nFileIndexLow);
540 return error_code::success();
544 error_code EC = windows_error(::GetLastError());
545 if (EC == windows_error::file_not_found ||
546 EC == windows_error::path_not_found)
547 Result = file_status(file_type::file_not_found);
548 else if (EC == windows_error::sharing_violation)
549 Result = file_status(file_type::type_unknown);
551 Result = file_status(file_type::status_error);
555 error_code status(const Twine &path, file_status &result) {
556 SmallString<128> path_storage;
557 SmallVector<wchar_t, 128> path_utf16;
559 StringRef path8 = path.toStringRef(path_storage);
560 if (isReservedName(path8)) {
561 result = file_status(file_type::character_file);
562 return error_code::success();
565 if (error_code ec = UTF8ToUTF16(path8, path_utf16))
568 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
569 if (attr == INVALID_FILE_ATTRIBUTES)
570 return getStatus(INVALID_HANDLE_VALUE, result);
572 // Handle reparse points.
573 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
575 ::CreateFileW(path_utf16.begin(),
576 0, // Attributes only.
577 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
580 FILE_FLAG_BACKUP_SEMANTICS,
583 return getStatus(INVALID_HANDLE_VALUE, result);
587 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
588 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
589 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0));
591 return getStatus(INVALID_HANDLE_VALUE, result);
593 return getStatus(h, result);
596 error_code status(int FD, file_status &Result) {
597 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
598 return getStatus(FileHandle, Result);
601 error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
603 UI.QuadPart = Time.toWin32Time();
605 FT.dwLowDateTime = UI.LowPart;
606 FT.dwHighDateTime = UI.HighPart;
607 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
608 if (!SetFileTime(FileHandle, NULL, &FT, &FT))
609 return windows_error(::GetLastError());
610 return error_code::success();
613 error_code get_magic(const Twine &path, uint32_t len,
614 SmallVectorImpl<char> &result) {
615 SmallString<128> path_storage;
616 SmallVector<wchar_t, 128> path_utf16;
619 // Convert path to UTF-16.
620 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
625 HANDLE file = ::CreateFileW(c_str(path_utf16),
630 FILE_ATTRIBUTE_READONLY,
632 if (file == INVALID_HANDLE_VALUE)
633 return windows_error(::GetLastError());
639 DWORD bytes_read = 0;
640 BOOL read_success = ::ReadFile(file, result.data(), len, &bytes_read, NULL);
641 error_code ec = windows_error(::GetLastError());
643 if (!read_success || (bytes_read != len)) {
644 // Set result size to the number of bytes read if it's valid.
645 if (bytes_read <= len)
646 result.set_size(bytes_read);
647 // ERROR_HANDLE_EOF is mapped to errc::value_too_large.
651 result.set_size(len);
652 return error_code::success();
655 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
657 // Make sure that the requested size fits within SIZE_T.
658 if (Size > std::numeric_limits<SIZE_T>::max()) {
659 if (FileDescriptor) {
661 _close(FileDescriptor);
663 ::CloseHandle(FileHandle);
664 return make_error_code(errc::invalid_argument);
669 case readonly: flprotect = PAGE_READONLY; break;
670 case readwrite: flprotect = PAGE_READWRITE; break;
671 case priv: flprotect = PAGE_WRITECOPY; break;
674 FileMappingHandle = ::CreateFileMapping(FileHandle,
677 (Offset + Size) >> 32,
678 (Offset + Size) & 0xffffffff,
680 if (FileMappingHandle == NULL) {
681 error_code ec = windows_error(GetLastError());
682 if (FileDescriptor) {
684 _close(FileDescriptor);
686 ::CloseHandle(FileHandle);
690 DWORD dwDesiredAccess;
692 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
693 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
694 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
696 Mapping = ::MapViewOfFile(FileMappingHandle,
701 if (Mapping == NULL) {
702 error_code ec = windows_error(GetLastError());
703 ::CloseHandle(FileMappingHandle);
704 if (FileDescriptor) {
706 _close(FileDescriptor);
708 ::CloseHandle(FileHandle);
713 MEMORY_BASIC_INFORMATION mbi;
714 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
716 error_code ec = windows_error(GetLastError());
717 ::UnmapViewOfFile(Mapping);
718 ::CloseHandle(FileMappingHandle);
719 if (FileDescriptor) {
721 _close(FileDescriptor);
723 ::CloseHandle(FileHandle);
726 Size = mbi.RegionSize;
729 // Close all the handles except for the view. It will keep the other handles
731 ::CloseHandle(FileMappingHandle);
732 if (FileDescriptor) {
734 _close(FileDescriptor); // Also closes FileHandle.
736 ::CloseHandle(FileHandle);
737 return error_code::success();
740 mapped_file_region::mapped_file_region(const Twine &path,
749 , FileHandle(INVALID_HANDLE_VALUE)
750 , FileMappingHandle() {
751 SmallString<128> path_storage;
752 SmallVector<wchar_t, 128> path_utf16;
754 // Convert path to UTF-16.
755 if ((ec = UTF8ToUTF16(path.toStringRef(path_storage), path_utf16)))
758 // Get file handle for creating a file mapping.
759 FileHandle = ::CreateFileW(c_str(path_utf16),
760 Mode == readonly ? GENERIC_READ
761 : GENERIC_READ | GENERIC_WRITE,
762 Mode == readonly ? FILE_SHARE_READ
765 Mode == readonly ? OPEN_EXISTING
767 Mode == readonly ? FILE_ATTRIBUTE_READONLY
768 : FILE_ATTRIBUTE_NORMAL,
770 if (FileHandle == INVALID_HANDLE_VALUE) {
771 ec = windows_error(::GetLastError());
776 ec = init(FileDescriptor, true, offset);
778 Mapping = FileMappingHandle = 0;
779 FileHandle = INVALID_HANDLE_VALUE;
784 mapped_file_region::mapped_file_region(int fd,
794 , FileHandle(INVALID_HANDLE_VALUE)
795 , FileMappingHandle() {
796 FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
797 if (FileHandle == INVALID_HANDLE_VALUE) {
799 _close(FileDescriptor);
801 ec = make_error_code(errc::bad_file_descriptor);
805 ec = init(FileDescriptor, closefd, offset);
807 Mapping = FileMappingHandle = 0;
808 FileHandle = INVALID_HANDLE_VALUE;
813 mapped_file_region::~mapped_file_region() {
815 ::UnmapViewOfFile(Mapping);
818 #if LLVM_HAS_RVALUE_REFERENCES
819 mapped_file_region::mapped_file_region(mapped_file_region &&other)
822 , Mapping(other.Mapping)
823 , FileDescriptor(other.FileDescriptor)
824 , FileHandle(other.FileHandle)
825 , FileMappingHandle(other.FileMappingHandle) {
826 other.Mapping = other.FileMappingHandle = 0;
827 other.FileHandle = INVALID_HANDLE_VALUE;
828 other.FileDescriptor = 0;
832 mapped_file_region::mapmode mapped_file_region::flags() const {
833 assert(Mapping && "Mapping failed but used anyway!");
837 uint64_t mapped_file_region::size() const {
838 assert(Mapping && "Mapping failed but used anyway!");
842 char *mapped_file_region::data() const {
843 assert(Mode != readonly && "Cannot get non const data for readonly mapping!");
844 assert(Mapping && "Mapping failed but used anyway!");
845 return reinterpret_cast<char*>(Mapping);
848 const char *mapped_file_region::const_data() const {
849 assert(Mapping && "Mapping failed but used anyway!");
850 return reinterpret_cast<const char*>(Mapping);
853 int mapped_file_region::alignment() {
855 ::GetSystemInfo(&SysInfo);
856 return SysInfo.dwAllocationGranularity;
859 error_code detail::directory_iterator_construct(detail::DirIterState &it,
861 SmallVector<wchar_t, 128> path_utf16;
863 if (error_code ec = UTF8ToUTF16(path,
867 // Convert path to the format that Windows is happy with.
868 if (path_utf16.size() > 0 &&
869 !is_separator(path_utf16[path.size() - 1]) &&
870 path_utf16[path.size() - 1] != L':') {
871 path_utf16.push_back(L'\\');
872 path_utf16.push_back(L'*');
874 path_utf16.push_back(L'*');
877 // Get the first directory entry.
878 WIN32_FIND_DATAW FirstFind;
879 ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
881 return windows_error(::GetLastError());
883 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
884 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
885 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
886 FirstFind.cFileName[1] == L'.'))
887 if (!::FindNextFileW(FindHandle, &FirstFind)) {
888 error_code ec = windows_error(::GetLastError());
890 if (ec == windows_error::no_more_files)
891 return detail::directory_iterator_destruct(it);
894 FilenameLen = ::wcslen(FirstFind.cFileName);
896 // Construct the current directory entry.
897 SmallString<128> directory_entry_name_utf8;
898 if (error_code ec = UTF16ToUTF8(FirstFind.cFileName,
899 ::wcslen(FirstFind.cFileName),
900 directory_entry_name_utf8))
903 it.IterationHandle = intptr_t(FindHandle.take());
904 SmallString<128> directory_entry_path(path);
905 path::append(directory_entry_path, directory_entry_name_utf8.str());
906 it.CurrentEntry = directory_entry(directory_entry_path.str());
908 return error_code::success();
911 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
912 if (it.IterationHandle != 0)
913 // Closes the handle if it's valid.
914 ScopedFindHandle close(HANDLE(it.IterationHandle));
915 it.IterationHandle = 0;
916 it.CurrentEntry = directory_entry();
917 return error_code::success();
920 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
921 WIN32_FIND_DATAW FindData;
922 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
923 error_code ec = windows_error(::GetLastError());
925 if (ec == windows_error::no_more_files)
926 return detail::directory_iterator_destruct(it);
930 size_t FilenameLen = ::wcslen(FindData.cFileName);
931 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
932 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
933 FindData.cFileName[1] == L'.'))
934 return directory_iterator_increment(it);
936 SmallString<128> directory_entry_path_utf8;
937 if (error_code ec = UTF16ToUTF8(FindData.cFileName,
938 ::wcslen(FindData.cFileName),
939 directory_entry_path_utf8))
942 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
943 return error_code::success();
946 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
947 bool map_writable, void *&result) {
948 assert(0 && "NOT IMPLEMENTED");
949 return windows_error::invalid_function;
952 error_code unmap_file_pages(void *base, size_t size) {
953 assert(0 && "NOT IMPLEMENTED");
954 return windows_error::invalid_function;
957 error_code openFileForRead(const Twine &Name, int &ResultFD) {
958 SmallString<128> PathStorage;
959 SmallVector<wchar_t, 128> PathUTF16;
961 if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
965 HANDLE H = ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
966 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
967 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
968 if (H == INVALID_HANDLE_VALUE) {
969 error_code EC = windows_error(::GetLastError());
970 // Provide a better error message when trying to open directories.
971 // This only runs if we failed to open the file, so there is probably
972 // no performances issues.
973 if (EC != windows_error::access_denied)
975 if (is_directory(Name))
976 return error_code(errc::is_a_directory, posix_category());
980 int FD = ::_open_osfhandle(intptr_t(H), 0);
983 return windows_error::invalid_handle;
987 return error_code::success();
990 error_code openFileForWrite(const Twine &Name, int &ResultFD,
991 sys::fs::OpenFlags Flags, unsigned Mode) {
992 // Verify that we don't have both "append" and "excl".
993 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
994 "Cannot specify both 'excl' and 'append' file creation flags!");
996 SmallString<128> PathStorage;
997 SmallVector<wchar_t, 128> PathUTF16;
999 if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
1003 DWORD CreationDisposition;
1005 CreationDisposition = CREATE_NEW;
1006 else if (Flags & F_Append)
1007 CreationDisposition = OPEN_ALWAYS;
1009 CreationDisposition = CREATE_ALWAYS;
1011 HANDLE H = ::CreateFileW(PathUTF16.begin(), GENERIC_WRITE,
1012 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1013 CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
1015 if (H == INVALID_HANDLE_VALUE) {
1016 error_code EC = windows_error(::GetLastError());
1017 // Provide a better error message when trying to open directories.
1018 // This only runs if we failed to open the file, so there is probably
1019 // no performances issues.
1020 if (EC != windows_error::access_denied)
1022 if (is_directory(Name))
1023 return error_code(errc::is_a_directory, posix_category());
1028 if (Flags & F_Append)
1029 OpenFlags |= _O_APPEND;
1031 if (!(Flags & F_Binary))
1032 OpenFlags |= _O_TEXT;
1034 int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
1037 return windows_error::invalid_handle;
1041 return error_code::success();
1043 } // end namespace fs
1046 llvm::error_code UTF8ToUTF16(llvm::StringRef utf8,
1047 llvm::SmallVectorImpl<wchar_t> &utf16) {
1048 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
1049 utf8.begin(), utf8.size(),
1053 return llvm::windows_error(::GetLastError());
1055 utf16.reserve(len + 1);
1056 utf16.set_size(len);
1058 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
1059 utf8.begin(), utf8.size(),
1060 utf16.begin(), utf16.size());
1063 return llvm::windows_error(::GetLastError());
1065 // Make utf16 null terminated.
1069 return llvm::error_code::success();
1072 llvm::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
1073 llvm::SmallVectorImpl<char> &utf8) {
1075 int len = ::WideCharToMultiByte(CP_UTF8, 0,
1081 return llvm::windows_error(::GetLastError());
1086 // Now do the actual conversion.
1087 len = ::WideCharToMultiByte(CP_UTF8, 0,
1089 utf8.data(), utf8.size(),
1093 return llvm::windows_error(::GetLastError());
1095 // Make utf8 null terminated.
1099 return llvm::error_code::success();
1101 } // end namespace windows
1102 } // end namespace sys
1103 } // end namespace llvm