1 //===- llvm/Support/Windows/PathV2.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 PathV2 API.
12 //===----------------------------------------------------------------------===//
14 //===----------------------------------------------------------------------===//
15 //=== WARNING: Implementation here must contain only generic Windows code that
16 //=== is guaranteed to work on *all* Windows variants.
17 //===----------------------------------------------------------------------===//
23 #include <sys/types.h>
27 // MinGW doesn't define this.
28 #ifndef _ERRNO_T_DEFINED
29 #define _ERRNO_T_DEFINED
36 typedef BOOLEAN (WINAPI *PtrCreateSymbolicLinkW)(
37 /*__in*/ LPCWSTR lpSymlinkFileName,
38 /*__in*/ LPCWSTR lpTargetFileName,
39 /*__in*/ DWORD dwFlags);
41 PtrCreateSymbolicLinkW create_symbolic_link_api = PtrCreateSymbolicLinkW(
42 ::GetProcAddress(::GetModuleHandleA("kernel32.dll"),
43 "CreateSymbolicLinkW"));
45 error_code UTF8ToUTF16(StringRef utf8, SmallVectorImpl<wchar_t> &utf16) {
46 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
47 utf8.begin(), utf8.size(),
51 return windows_error(::GetLastError());
53 utf16.reserve(len + 1);
56 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
57 utf8.begin(), utf8.size(),
58 utf16.begin(), utf16.size());
61 return windows_error(::GetLastError());
63 // Make utf16 null terminated.
67 return error_code::success();
70 error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
71 SmallVectorImpl<char> &utf8) {
73 int len = ::WideCharToMultiByte(CP_UTF8, 0,
79 return windows_error(::GetLastError());
84 // Now do the actual conversion.
85 len = ::WideCharToMultiByte(CP_UTF8, 0,
87 utf8.data(), utf8.size(),
91 return windows_error(::GetLastError());
93 // Make utf8 null terminated.
97 return error_code::success();
100 error_code TempDir(SmallVectorImpl<wchar_t> &result) {
102 DWORD len = ::GetTempPathW(result.capacity(), result.begin());
105 return windows_error(::GetLastError());
107 if (len > result.capacity()) {
112 result.set_size(len);
113 return error_code::success();
116 bool is_separator(const wchar_t value) {
131 TimeValue file_status::getLastModificationTime() const {
133 UI.LowPart = LastWriteTimeLow;
134 UI.HighPart = LastWriteTimeHigh;
137 Ret.fromWin32Time(UI.QuadPart);
141 error_code current_path(SmallVectorImpl<char> &result) {
142 SmallVector<wchar_t, 128> cur_path;
143 cur_path.reserve(128);
145 DWORD len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
147 // A zero return value indicates a failure other than insufficient space.
149 return windows_error(::GetLastError());
151 // If there's insufficient space, the len returned is larger than the len
153 if (len > cur_path.capacity()) {
154 cur_path.reserve(len);
158 cur_path.set_size(len);
159 // cur_path now holds the current directory in utf-16. Convert to utf-8.
161 // Find out how much space we need. Sadly, this function doesn't return the
162 // size needed unless you tell it the result size is 0, which means you
163 // _always_ have to call it twice.
164 len = ::WideCharToMultiByte(CP_UTF8, 0,
165 cur_path.data(), cur_path.size(),
170 return make_error_code(windows_error(::GetLastError()));
173 result.set_size(len);
174 // Now do the actual conversion.
175 len = ::WideCharToMultiByte(CP_UTF8, 0,
176 cur_path.data(), cur_path.size(),
177 result.data(), result.size(),
180 return windows_error(::GetLastError());
182 return error_code::success();
185 error_code copy_file(const Twine &from, const Twine &to, copy_option copt) {
187 SmallString<128> from_storage;
188 SmallString<128> to_storage;
189 StringRef f = from.toStringRef(from_storage);
190 StringRef t = to.toStringRef(to_storage);
192 // Convert to utf-16.
193 SmallVector<wchar_t, 128> wide_from;
194 SmallVector<wchar_t, 128> wide_to;
195 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
196 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
199 BOOL res = ::CopyFileW(wide_from.begin(), wide_to.begin(),
200 copt != copy_option::overwrite_if_exists);
203 return windows_error(::GetLastError());
205 return error_code::success();
208 error_code create_directory(const Twine &path, bool &existed) {
209 SmallString<128> path_storage;
210 SmallVector<wchar_t, 128> path_utf16;
212 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
216 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
217 error_code ec = windows_error(::GetLastError());
218 if (ec == windows_error::already_exists)
225 return error_code::success();
228 error_code create_hard_link(const Twine &to, const Twine &from) {
230 SmallString<128> from_storage;
231 SmallString<128> to_storage;
232 StringRef f = from.toStringRef(from_storage);
233 StringRef t = to.toStringRef(to_storage);
235 // Convert to utf-16.
236 SmallVector<wchar_t, 128> wide_from;
237 SmallVector<wchar_t, 128> wide_to;
238 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
239 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
241 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
242 return windows_error(::GetLastError());
244 return error_code::success();
247 error_code create_symlink(const Twine &to, const Twine &from) {
248 // Only do it if the function is available at runtime.
249 if (!create_symbolic_link_api)
250 return make_error_code(errc::function_not_supported);
253 SmallString<128> from_storage;
254 SmallString<128> to_storage;
255 StringRef f = from.toStringRef(from_storage);
256 StringRef t = to.toStringRef(to_storage);
258 // Convert to utf-16.
259 SmallVector<wchar_t, 128> wide_from;
260 SmallVector<wchar_t, 128> wide_to;
261 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
262 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
264 if (!create_symbolic_link_api(wide_from.begin(), wide_to.begin(), 0))
265 return windows_error(::GetLastError());
267 return error_code::success();
270 error_code remove(const Twine &path, bool &existed) {
271 SmallString<128> path_storage;
272 SmallVector<wchar_t, 128> path_utf16;
275 if (error_code ec = status(path, st))
278 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
282 if (st.type() == file_type::directory_file) {
283 if (!::RemoveDirectoryW(c_str(path_utf16))) {
284 error_code ec = windows_error(::GetLastError());
285 if (ec != windows_error::file_not_found)
291 if (!::DeleteFileW(c_str(path_utf16))) {
292 error_code ec = windows_error(::GetLastError());
293 if (ec != windows_error::file_not_found)
300 return error_code::success();
303 error_code rename(const Twine &from, const Twine &to) {
305 SmallString<128> from_storage;
306 SmallString<128> to_storage;
307 StringRef f = from.toStringRef(from_storage);
308 StringRef t = to.toStringRef(to_storage);
310 // Convert to utf-16.
311 SmallVector<wchar_t, 128> wide_from;
312 SmallVector<wchar_t, 128> wide_to;
313 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
314 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
316 error_code ec = error_code::success();
317 for (int i = 0; i < 2000; i++) {
318 if (::MoveFileExW(wide_from.begin(), wide_to.begin(),
319 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
320 return error_code::success();
321 ec = windows_error(::GetLastError());
322 if (ec != windows_error::access_denied)
324 // Retry MoveFile() at ACCESS_DENIED.
325 // System scanners (eg. indexer) might open the source file when
326 // It is written and closed.
333 error_code resize_file(const Twine &path, uint64_t size) {
334 SmallString<128> path_storage;
335 SmallVector<wchar_t, 128> path_utf16;
337 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
341 int fd = ::_wopen(path_utf16.begin(), O_BINARY | _O_RDWR, S_IWRITE);
343 return error_code(errno, generic_category());
344 #ifdef HAVE__CHSIZE_S
345 errno_t error = ::_chsize_s(fd, size);
347 errno_t error = ::_chsize(fd, size);
350 return error_code(error, generic_category());
353 error_code exists(const Twine &path, bool &result) {
354 SmallString<128> path_storage;
355 SmallVector<wchar_t, 128> path_utf16;
357 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
361 DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
363 if (attributes == INVALID_FILE_ATTRIBUTES) {
364 // See if the file didn't actually exist.
365 error_code ec = make_error_code(windows_error(::GetLastError()));
366 if (ec != windows_error::file_not_found &&
367 ec != windows_error::path_not_found)
372 return error_code::success();
375 bool can_write(const Twine &Path) {
376 // FIXME: take security attributes into account.
377 SmallString<128> PathStorage;
378 SmallVector<wchar_t, 128> PathUtf16;
380 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
383 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
384 return (Attr != INVALID_FILE_ATTRIBUTES) && !(Attr & FILE_ATTRIBUTE_READONLY);
387 bool can_execute(const Twine &Path) {
388 SmallString<128> PathStorage;
389 SmallVector<wchar_t, 128> PathUtf16;
391 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
394 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
395 return Attr != INVALID_FILE_ATTRIBUTES;
398 bool equivalent(file_status A, file_status B) {
399 assert(status_known(A) && status_known(B));
400 return A.FileIndexHigh == B.FileIndexHigh &&
401 A.FileIndexLow == B.FileIndexLow &&
402 A.FileSizeHigh == B.FileSizeHigh &&
403 A.FileSizeLow == B.FileSizeLow &&
404 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
405 A.LastWriteTimeLow == B.LastWriteTimeLow &&
406 A.VolumeSerialNumber == B.VolumeSerialNumber;
409 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
410 file_status fsA, fsB;
411 if (error_code ec = status(A, fsA)) return ec;
412 if (error_code ec = status(B, fsB)) return ec;
413 result = equivalent(fsA, fsB);
414 return error_code::success();
417 error_code file_size(const Twine &path, uint64_t &result) {
418 SmallString<128> path_storage;
419 SmallVector<wchar_t, 128> path_utf16;
421 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
425 WIN32_FILE_ATTRIBUTE_DATA FileData;
426 if (!::GetFileAttributesExW(path_utf16.begin(),
427 ::GetFileExInfoStandard,
429 return windows_error(::GetLastError());
432 (uint64_t(FileData.nFileSizeHigh) << (sizeof(FileData.nFileSizeLow) * 8))
433 + FileData.nFileSizeLow;
435 return error_code::success();
438 error_code getUniqueID(const Twine Path, uint64_t &Result) {
440 if (error_code E = status(Path, Status))
443 // The file is uniquely identified by the volume serial number along
444 // with the 64-bit file identifier.
445 Result = (static_cast<uint64_t>(Status.FileIndexHigh) << 32ULL) |
446 static_cast<uint64_t>(Status.FileIndexLow);
448 // Because the serial number is 32-bits, but we've already used up all 64
449 // bits for the file index, XOR the serial number into the high 32 bits of
450 // the resulting value. We could potentially get collisons from this, but
451 // the likelihood is low.
452 Result ^= (static_cast<uint64_t>(Status.VolumeSerialNumber) << 32ULL);
454 return error_code::success();
457 static bool isReservedName(StringRef path) {
458 // This list of reserved names comes from MSDN, at:
459 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
460 static const char *sReservedNames[] = { "nul", "con", "prn", "aux",
461 "com1", "com2", "com3", "com4", "com5", "com6",
462 "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
463 "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9" };
465 // First, check to see if this is a device namespace, which always
466 // starts with \\.\, since device namespaces are not legal file paths.
467 if (path.startswith("\\\\.\\"))
470 // Then compare against the list of ancient reserved names
471 for (size_t i = 0; i < sizeof(sReservedNames) / sizeof(const char *); ++i) {
472 if (path.equals_lower(sReservedNames[i]))
476 // The path isn't what we consider reserved.
480 error_code status(const Twine &path, file_status &result) {
481 SmallString<128> path_storage;
482 SmallVector<wchar_t, 128> path_utf16;
484 StringRef path8 = path.toStringRef(path_storage);
485 if (isReservedName(path8)) {
486 result = file_status(file_type::character_file);
487 return error_code::success();
490 if (error_code ec = UTF8ToUTF16(path8, path_utf16))
493 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
494 if (attr == INVALID_FILE_ATTRIBUTES)
495 goto handle_status_error;
497 // Handle reparse points.
498 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
500 ::CreateFileW(path_utf16.begin(),
501 0, // Attributes only.
502 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
505 FILE_FLAG_BACKUP_SEMANTICS,
508 goto handle_status_error;
511 if (attr & FILE_ATTRIBUTE_DIRECTORY)
512 result = file_status(file_type::directory_file);
514 result = file_status(file_type::regular_file);
516 ::CreateFileW(path_utf16.begin(),
517 0, // Attributes only.
518 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
521 FILE_FLAG_BACKUP_SEMANTICS,
524 goto handle_status_error;
525 BY_HANDLE_FILE_INFORMATION Info;
526 if (!::GetFileInformationByHandle(h, &Info))
527 goto handle_status_error;
528 result.FileIndexHigh = Info.nFileIndexHigh;
529 result.FileIndexLow = Info.nFileIndexLow;
530 result.FileSizeHigh = Info.nFileSizeHigh;
531 result.FileSizeLow = Info.nFileSizeLow;
532 result.LastWriteTimeHigh = Info.ftLastWriteTime.dwHighDateTime;
533 result.LastWriteTimeLow = Info.ftLastWriteTime.dwLowDateTime;
534 result.VolumeSerialNumber = Info.dwVolumeSerialNumber;
537 return error_code::success();
540 error_code ec = windows_error(::GetLastError());
541 if (ec == windows_error::file_not_found ||
542 ec == windows_error::path_not_found)
543 result = file_status(file_type::file_not_found);
544 else if (ec == windows_error::sharing_violation)
545 result = file_status(file_type::type_unknown);
547 result = file_status(file_type::status_error);
551 return error_code::success();
555 // Modifies permissions on a file.
556 error_code permissions(const Twine &path, perms prms) {
557 #if 0 // verify code below before enabling:
558 // If the permissions bits are not trying to modify
559 // "write" permissions, there is nothing to do.
560 if (!(prms & (owner_write|group_write|others_write)))
561 return error_code::success();
563 SmallString<128> path_storage;
564 SmallVector<wchar_t, 128> path_utf16;
566 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
570 DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
572 if (prms & add_perms) {
573 attributes &= ~FILE_ATTRIBUTE_READONLY;
575 else if (prms & remove_perms) {
576 attributes |= FILE_ATTRIBUTE_READONLY;
579 assert(0 && "neither add_perms or remove_perms is set");
582 if ( ! ::SetFileAttributesW(path_utf16.begin(), attributes))
583 return windows_error(::GetLastError());
585 return error_code::success();
588 error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
590 UI.QuadPart = Time.toWin32Time();
592 FT.dwLowDateTime = UI.LowPart;
593 FT.dwHighDateTime = UI.HighPart;
594 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
595 if (!SetFileTime(FileHandle, NULL, &FT, &FT))
596 return windows_error(::GetLastError());
597 return error_code::success();
600 // FIXME: mode should be used here and default to user r/w only,
601 // it currently comes in as a UNIX mode.
602 error_code unique_file(const Twine &model, int &result_fd,
603 SmallVectorImpl<char> &result_path,
604 bool makeAbsolute, unsigned mode) {
605 // Use result_path as temp storage.
606 result_path.set_size(0);
607 StringRef m = model.toStringRef(result_path);
609 SmallVector<wchar_t, 128> model_utf16;
610 if (error_code ec = UTF8ToUTF16(m, model_utf16)) return ec;
613 // Make model absolute by prepending a temp directory if it's not already.
614 bool absolute = path::is_absolute(m);
617 SmallVector<wchar_t, 64> temp_dir;
618 if (error_code ec = TempDir(temp_dir)) return ec;
619 // Handle c: by removing it.
620 if (model_utf16.size() > 2 && model_utf16[1] == L':') {
621 model_utf16.erase(model_utf16.begin(), model_utf16.begin() + 2);
623 model_utf16.insert(model_utf16.begin(), temp_dir.begin(), temp_dir.end());
627 // Replace '%' with random chars. From here on, DO NOT modify model. It may be
628 // needed if the randomly chosen path already exists.
629 SmallVector<wchar_t, 128> random_path_utf16;
631 // Get a Crypto Provider for CryptGenRandom.
633 if (!::CryptAcquireContextW(&HCPC,
637 CRYPT_VERIFYCONTEXT))
638 return windows_error(::GetLastError());
639 ScopedCryptContext CryptoProvider(HCPC);
642 random_path_utf16.set_size(0);
643 for (SmallVectorImpl<wchar_t>::const_iterator i = model_utf16.begin(),
644 e = model_utf16.end();
648 if (!::CryptGenRandom(CryptoProvider, 1, &val))
649 return windows_error(::GetLastError());
650 random_path_utf16.push_back("0123456789abcdef"[val & 15]);
653 random_path_utf16.push_back(*i);
655 // Make random_path_utf16 null terminated.
656 random_path_utf16.push_back(0);
657 random_path_utf16.pop_back();
659 // Make sure we don't fall into an infinite loop by constantly trying
660 // to create the parent path.
661 bool TriedToCreateParent = false;
663 // Try to create + open the path.
665 HANDLE TempFileHandle = ::CreateFileW(random_path_utf16.begin(),
666 GENERIC_READ | GENERIC_WRITE,
669 // Return ERROR_FILE_EXISTS if the file
672 FILE_ATTRIBUTE_TEMPORARY,
674 if (TempFileHandle == INVALID_HANDLE_VALUE) {
675 // If the file existed, try again, otherwise, error.
676 error_code ec = windows_error(::GetLastError());
677 if (ec == windows_error::file_exists)
678 goto retry_random_path;
679 // Check for non-existing parent directories.
680 if (ec == windows_error::path_not_found && !TriedToCreateParent) {
681 TriedToCreateParent = true;
683 // Create the directories using result_path as temp storage.
684 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
685 random_path_utf16.size(), result_path))
687 StringRef p(result_path.begin(), result_path.size());
688 SmallString<64> dir_to_create;
689 for (path::const_iterator i = path::begin(p),
690 e = --path::end(p); i != e; ++i) {
691 path::append(dir_to_create, *i);
693 if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
695 // If c: doesn't exist, bail.
696 if (i->endswith(":"))
699 SmallVector<wchar_t, 64> dir_to_create_utf16;
700 if (error_code ec = UTF8ToUTF16(dir_to_create, dir_to_create_utf16))
703 // Create the directory.
704 if (!::CreateDirectoryW(dir_to_create_utf16.begin(), NULL))
705 return windows_error(::GetLastError());
708 goto retry_create_file;
713 // Set result_path to the utf-8 representation of the path.
714 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
715 random_path_utf16.size(), result_path)) {
716 ::CloseHandle(TempFileHandle);
717 ::DeleteFileW(random_path_utf16.begin());
721 // Convert the Windows API file handle into a C-runtime handle.
722 int fd = ::_open_osfhandle(intptr_t(TempFileHandle), 0);
724 ::CloseHandle(TempFileHandle);
725 ::DeleteFileW(random_path_utf16.begin());
726 // MSDN doesn't say anything about _open_osfhandle setting errno or
727 // GetLastError(), so just return invalid_handle.
728 return windows_error::invalid_handle;
732 return error_code::success();
735 error_code get_magic(const Twine &path, uint32_t len,
736 SmallVectorImpl<char> &result) {
737 SmallString<128> path_storage;
738 SmallVector<wchar_t, 128> path_utf16;
741 // Convert path to UTF-16.
742 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
747 HANDLE file = ::CreateFileW(c_str(path_utf16),
752 FILE_ATTRIBUTE_READONLY,
754 if (file == INVALID_HANDLE_VALUE)
755 return windows_error(::GetLastError());
761 DWORD bytes_read = 0;
762 BOOL read_success = ::ReadFile(file, result.data(), len, &bytes_read, NULL);
763 error_code ec = windows_error(::GetLastError());
765 if (!read_success || (bytes_read != len)) {
766 // Set result size to the number of bytes read if it's valid.
767 if (bytes_read <= len)
768 result.set_size(bytes_read);
769 // ERROR_HANDLE_EOF is mapped to errc::value_too_large.
773 result.set_size(len);
774 return error_code::success();
777 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
779 // Make sure that the requested size fits within SIZE_T.
780 if (Size > std::numeric_limits<SIZE_T>::max()) {
781 if (FileDescriptor) {
783 _close(FileDescriptor);
785 ::CloseHandle(FileHandle);
786 return make_error_code(errc::invalid_argument);
791 case readonly: flprotect = PAGE_READONLY; break;
792 case readwrite: flprotect = PAGE_READWRITE; break;
793 case priv: flprotect = PAGE_WRITECOPY; break;
794 default: llvm_unreachable("invalid mapping mode");
797 FileMappingHandle = ::CreateFileMapping(FileHandle,
803 if (FileMappingHandle == NULL) {
804 error_code ec = windows_error(GetLastError());
805 if (FileDescriptor) {
807 _close(FileDescriptor);
809 ::CloseHandle(FileHandle);
813 DWORD dwDesiredAccess;
815 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
816 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
817 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
818 default: llvm_unreachable("invalid mapping mode");
820 Mapping = ::MapViewOfFile(FileMappingHandle,
825 if (Mapping == NULL) {
826 error_code ec = windows_error(GetLastError());
827 ::CloseHandle(FileMappingHandle);
828 if (FileDescriptor) {
830 _close(FileDescriptor);
832 ::CloseHandle(FileHandle);
837 MEMORY_BASIC_INFORMATION mbi;
838 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
840 error_code ec = windows_error(GetLastError());
841 ::UnmapViewOfFile(Mapping);
842 ::CloseHandle(FileMappingHandle);
843 if (FileDescriptor) {
845 _close(FileDescriptor);
847 ::CloseHandle(FileHandle);
850 Size = mbi.RegionSize;
853 // Close all the handles except for the view. It will keep the other handles
855 ::CloseHandle(FileMappingHandle);
856 if (FileDescriptor) {
858 _close(FileDescriptor); // Also closes FileHandle.
860 ::CloseHandle(FileHandle);
861 return error_code::success();
864 mapped_file_region::mapped_file_region(const Twine &path,
873 , FileHandle(INVALID_HANDLE_VALUE)
874 , FileMappingHandle() {
875 SmallString<128> path_storage;
876 SmallVector<wchar_t, 128> path_utf16;
878 // Convert path to UTF-16.
879 if ((ec = UTF8ToUTF16(path.toStringRef(path_storage), path_utf16)))
882 // Get file handle for creating a file mapping.
883 FileHandle = ::CreateFileW(c_str(path_utf16),
884 Mode == readonly ? GENERIC_READ
885 : GENERIC_READ | GENERIC_WRITE,
886 Mode == readonly ? FILE_SHARE_READ
889 Mode == readonly ? OPEN_EXISTING
891 Mode == readonly ? FILE_ATTRIBUTE_READONLY
892 : FILE_ATTRIBUTE_NORMAL,
894 if (FileHandle == INVALID_HANDLE_VALUE) {
895 ec = windows_error(::GetLastError());
900 ec = init(FileDescriptor, true, offset);
902 Mapping = FileMappingHandle = 0;
903 FileHandle = INVALID_HANDLE_VALUE;
908 mapped_file_region::mapped_file_region(int fd,
918 , FileHandle(INVALID_HANDLE_VALUE)
919 , FileMappingHandle() {
920 FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
921 if (FileHandle == INVALID_HANDLE_VALUE) {
923 _close(FileDescriptor);
925 ec = make_error_code(errc::bad_file_descriptor);
929 ec = init(FileDescriptor, closefd, offset);
931 Mapping = FileMappingHandle = 0;
932 FileHandle = INVALID_HANDLE_VALUE;
937 mapped_file_region::~mapped_file_region() {
939 ::UnmapViewOfFile(Mapping);
942 #if LLVM_HAS_RVALUE_REFERENCES
943 mapped_file_region::mapped_file_region(mapped_file_region &&other)
946 , Mapping(other.Mapping)
947 , FileDescriptor(other.FileDescriptor)
948 , FileHandle(other.FileHandle)
949 , FileMappingHandle(other.FileMappingHandle) {
950 other.Mapping = other.FileMappingHandle = 0;
951 other.FileHandle = INVALID_HANDLE_VALUE;
952 other.FileDescriptor = 0;
956 mapped_file_region::mapmode mapped_file_region::flags() const {
957 assert(Mapping && "Mapping failed but used anyway!");
961 uint64_t mapped_file_region::size() const {
962 assert(Mapping && "Mapping failed but used anyway!");
966 char *mapped_file_region::data() const {
967 assert(Mode != readonly && "Cannot get non const data for readonly mapping!");
968 assert(Mapping && "Mapping failed but used anyway!");
969 return reinterpret_cast<char*>(Mapping);
972 const char *mapped_file_region::const_data() const {
973 assert(Mapping && "Mapping failed but used anyway!");
974 return reinterpret_cast<const char*>(Mapping);
977 int mapped_file_region::alignment() {
979 ::GetSystemInfo(&SysInfo);
980 return SysInfo.dwAllocationGranularity;
983 error_code detail::directory_iterator_construct(detail::DirIterState &it,
985 SmallVector<wchar_t, 128> path_utf16;
987 if (error_code ec = UTF8ToUTF16(path,
991 // Convert path to the format that Windows is happy with.
992 if (path_utf16.size() > 0 &&
993 !is_separator(path_utf16[path.size() - 1]) &&
994 path_utf16[path.size() - 1] != L':') {
995 path_utf16.push_back(L'\\');
996 path_utf16.push_back(L'*');
998 path_utf16.push_back(L'*');
1001 // Get the first directory entry.
1002 WIN32_FIND_DATAW FirstFind;
1003 ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
1005 return windows_error(::GetLastError());
1007 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
1008 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
1009 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
1010 FirstFind.cFileName[1] == L'.'))
1011 if (!::FindNextFileW(FindHandle, &FirstFind)) {
1012 error_code ec = windows_error(::GetLastError());
1014 if (ec == windows_error::no_more_files)
1015 return detail::directory_iterator_destruct(it);
1018 FilenameLen = ::wcslen(FirstFind.cFileName);
1020 // Construct the current directory entry.
1021 SmallString<128> directory_entry_name_utf8;
1022 if (error_code ec = UTF16ToUTF8(FirstFind.cFileName,
1023 ::wcslen(FirstFind.cFileName),
1024 directory_entry_name_utf8))
1027 it.IterationHandle = intptr_t(FindHandle.take());
1028 SmallString<128> directory_entry_path(path);
1029 path::append(directory_entry_path, directory_entry_name_utf8.str());
1030 it.CurrentEntry = directory_entry(directory_entry_path.str());
1032 return error_code::success();
1035 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
1036 if (it.IterationHandle != 0)
1037 // Closes the handle if it's valid.
1038 ScopedFindHandle close(HANDLE(it.IterationHandle));
1039 it.IterationHandle = 0;
1040 it.CurrentEntry = directory_entry();
1041 return error_code::success();
1044 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
1045 WIN32_FIND_DATAW FindData;
1046 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
1047 error_code ec = windows_error(::GetLastError());
1049 if (ec == windows_error::no_more_files)
1050 return detail::directory_iterator_destruct(it);
1054 size_t FilenameLen = ::wcslen(FindData.cFileName);
1055 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
1056 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
1057 FindData.cFileName[1] == L'.'))
1058 return directory_iterator_increment(it);
1060 SmallString<128> directory_entry_path_utf8;
1061 if (error_code ec = UTF16ToUTF8(FindData.cFileName,
1062 ::wcslen(FindData.cFileName),
1063 directory_entry_path_utf8))
1066 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
1067 return error_code::success();
1070 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
1071 bool map_writable, void *&result) {
1072 assert(0 && "NOT IMPLEMENTED");
1073 return windows_error::invalid_function;
1076 error_code unmap_file_pages(void *base, size_t size) {
1077 assert(0 && "NOT IMPLEMENTED");
1078 return windows_error::invalid_function;
1083 } // end namespace fs
1084 } // end namespace sys
1085 } // end namespace llvm