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
37 typedef BOOLEAN (WINAPI *PtrCreateSymbolicLinkW)(
38 /*__in*/ LPCWSTR lpSymlinkFileName,
39 /*__in*/ LPCWSTR lpTargetFileName,
40 /*__in*/ DWORD dwFlags);
42 PtrCreateSymbolicLinkW create_symbolic_link_api = PtrCreateSymbolicLinkW(
43 ::GetProcAddress(::GetModuleHandleA("kernel32.dll"),
44 "CreateSymbolicLinkW"));
46 error_code UTF8ToUTF16(StringRef utf8, SmallVectorImpl<wchar_t> &utf16) {
47 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
48 utf8.begin(), utf8.size(),
52 return windows_error(::GetLastError());
54 utf16.reserve(len + 1);
57 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
58 utf8.begin(), utf8.size(),
59 utf16.begin(), utf16.size());
62 return windows_error(::GetLastError());
64 // Make utf16 null terminated.
68 return error_code::success();
71 error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
72 SmallVectorImpl<char> &utf8) {
74 int len = ::WideCharToMultiByte(CP_UTF8, 0,
80 return windows_error(::GetLastError());
85 // Now do the actual conversion.
86 len = ::WideCharToMultiByte(CP_UTF8, 0,
88 utf8.data(), utf8.size(),
92 return windows_error(::GetLastError());
94 // Make utf8 null terminated.
98 return error_code::success();
101 error_code TempDir(SmallVectorImpl<wchar_t> &result) {
103 DWORD len = ::GetTempPathW(result.capacity(), result.begin());
106 return windows_error(::GetLastError());
108 if (len > result.capacity()) {
113 result.set_size(len);
114 return error_code::success();
117 bool is_separator(const wchar_t value) {
128 // FIXME: mode should be used here and default to user r/w only,
129 // it currently comes in as a UNIX mode.
130 static error_code createUniqueEntity(const Twine &model, int &result_fd,
131 SmallVectorImpl<char> &result_path,
132 bool makeAbsolute, unsigned mode,
134 // Use result_path as temp storage.
135 result_path.set_size(0);
136 StringRef m = model.toStringRef(result_path);
138 SmallVector<wchar_t, 128> model_utf16;
139 if (error_code ec = UTF8ToUTF16(m, model_utf16)) return ec;
142 // Make model absolute by prepending a temp directory if it's not already.
143 bool absolute = sys::path::is_absolute(m);
146 SmallVector<wchar_t, 64> temp_dir;
147 if (error_code ec = TempDir(temp_dir)) return ec;
148 // Handle c: by removing it.
149 if (model_utf16.size() > 2 && model_utf16[1] == L':') {
150 model_utf16.erase(model_utf16.begin(), model_utf16.begin() + 2);
152 model_utf16.insert(model_utf16.begin(), temp_dir.begin(), temp_dir.end());
156 // Replace '%' with random chars. From here on, DO NOT modify model. It may be
157 // needed if the randomly chosen path already exists.
158 SmallVector<wchar_t, 128> random_path_utf16;
160 // Get a Crypto Provider for CryptGenRandom.
162 if (!::CryptAcquireContextW(&HCPC,
166 CRYPT_VERIFYCONTEXT))
167 return windows_error(::GetLastError());
168 ScopedCryptContext CryptoProvider(HCPC);
171 random_path_utf16.set_size(0);
172 for (SmallVectorImpl<wchar_t>::const_iterator i = model_utf16.begin(),
173 e = model_utf16.end();
177 if (!::CryptGenRandom(CryptoProvider, 1, &val))
178 return windows_error(::GetLastError());
179 random_path_utf16.push_back("0123456789abcdef"[val & 15]);
182 random_path_utf16.push_back(*i);
184 // Make random_path_utf16 null terminated.
185 random_path_utf16.push_back(0);
186 random_path_utf16.pop_back();
188 HANDLE TempFileHandle;
192 // Try to create + open the path.
194 ::CreateFileW(random_path_utf16.begin(), GENERIC_READ | GENERIC_WRITE,
195 FILE_SHARE_READ, NULL,
196 // Return ERROR_FILE_EXISTS if the file
198 CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY, NULL);
199 if (TempFileHandle == INVALID_HANDLE_VALUE) {
200 // If the file existed, try again, otherwise, error.
201 error_code ec = windows_error(::GetLastError());
202 if (ec == windows_error::file_exists)
203 goto retry_random_path;
208 // Convert the Windows API file handle into a C-runtime handle.
209 int fd = ::_open_osfhandle(intptr_t(TempFileHandle), 0);
211 ::CloseHandle(TempFileHandle);
212 ::DeleteFileW(random_path_utf16.begin());
213 // MSDN doesn't say anything about _open_osfhandle setting errno or
214 // GetLastError(), so just return invalid_handle.
215 return windows_error::invalid_handle;
223 DWORD attributes = ::GetFileAttributesW(random_path_utf16.begin());
224 if (attributes != INVALID_FILE_ATTRIBUTES)
225 goto retry_random_path;
226 error_code EC = make_error_code(windows_error(::GetLastError()));
227 if (EC != windows_error::file_not_found &&
228 EC != windows_error::path_not_found)
234 if (!::CreateDirectoryW(random_path_utf16.begin(), NULL)) {
235 error_code EC = windows_error(::GetLastError());
236 if (EC != windows_error::already_exists)
238 goto retry_random_path;
243 // Set result_path to the utf-8 representation of the path.
244 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
245 random_path_utf16.size(), result_path)) {
248 ::CloseHandle(TempFileHandle);
249 ::DeleteFileW(random_path_utf16.begin());
253 ::RemoveDirectoryW(random_path_utf16.begin());
259 return error_code::success();
266 std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
267 char pathname[MAX_PATH];
268 DWORD ret = ::GetModuleFileNameA(NULL, pathname, MAX_PATH);
269 return ret != MAX_PATH ? pathname : "";
273 TimeValue file_status::getLastModificationTime() const {
275 UI.LowPart = LastWriteTimeLow;
276 UI.HighPart = LastWriteTimeHigh;
279 Ret.fromWin32Time(UI.QuadPart);
283 error_code current_path(SmallVectorImpl<char> &result) {
284 SmallVector<wchar_t, 128> cur_path;
285 cur_path.reserve(128);
287 DWORD len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
289 // A zero return value indicates a failure other than insufficient space.
291 return windows_error(::GetLastError());
293 // If there's insufficient space, the len returned is larger than the len
295 if (len > cur_path.capacity()) {
296 cur_path.reserve(len);
300 cur_path.set_size(len);
301 // cur_path now holds the current directory in utf-16. Convert to utf-8.
303 // Find out how much space we need. Sadly, this function doesn't return the
304 // size needed unless you tell it the result size is 0, which means you
305 // _always_ have to call it twice.
306 len = ::WideCharToMultiByte(CP_UTF8, 0,
307 cur_path.data(), cur_path.size(),
312 return make_error_code(windows_error(::GetLastError()));
315 result.set_size(len);
316 // Now do the actual conversion.
317 len = ::WideCharToMultiByte(CP_UTF8, 0,
318 cur_path.data(), cur_path.size(),
319 result.data(), result.size(),
322 return windows_error(::GetLastError());
324 return error_code::success();
327 error_code create_directory(const Twine &path, bool &existed) {
328 SmallString<128> path_storage;
329 SmallVector<wchar_t, 128> path_utf16;
331 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
335 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
336 error_code ec = windows_error(::GetLastError());
337 if (ec == windows_error::already_exists)
344 return error_code::success();
347 error_code create_hard_link(const Twine &to, const Twine &from) {
349 SmallString<128> from_storage;
350 SmallString<128> to_storage;
351 StringRef f = from.toStringRef(from_storage);
352 StringRef t = to.toStringRef(to_storage);
354 // Convert to utf-16.
355 SmallVector<wchar_t, 128> wide_from;
356 SmallVector<wchar_t, 128> wide_to;
357 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
358 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
360 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
361 return windows_error(::GetLastError());
363 return error_code::success();
366 error_code create_symlink(const Twine &to, const Twine &from) {
367 // Only do it if the function is available at runtime.
368 if (!create_symbolic_link_api)
369 return make_error_code(errc::function_not_supported);
372 SmallString<128> from_storage;
373 SmallString<128> to_storage;
374 StringRef f = from.toStringRef(from_storage);
375 StringRef t = to.toStringRef(to_storage);
377 // Convert to utf-16.
378 SmallVector<wchar_t, 128> wide_from;
379 SmallVector<wchar_t, 128> wide_to;
380 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
381 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
383 if (!create_symbolic_link_api(wide_from.begin(), wide_to.begin(), 0))
384 return windows_error(::GetLastError());
386 return error_code::success();
389 error_code remove(const Twine &path, bool &existed) {
390 SmallString<128> path_storage;
391 SmallVector<wchar_t, 128> path_utf16;
394 if (error_code ec = status(path, st))
397 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
401 if (st.type() == file_type::directory_file) {
402 if (!::RemoveDirectoryW(c_str(path_utf16))) {
403 error_code ec = windows_error(::GetLastError());
404 if (ec != windows_error::file_not_found)
410 if (!::DeleteFileW(c_str(path_utf16))) {
411 error_code ec = windows_error(::GetLastError());
412 if (ec != windows_error::file_not_found)
419 return error_code::success();
422 error_code rename(const Twine &from, const Twine &to) {
424 SmallString<128> from_storage;
425 SmallString<128> to_storage;
426 StringRef f = from.toStringRef(from_storage);
427 StringRef t = to.toStringRef(to_storage);
429 // Convert to utf-16.
430 SmallVector<wchar_t, 128> wide_from;
431 SmallVector<wchar_t, 128> wide_to;
432 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
433 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
435 error_code ec = error_code::success();
436 for (int i = 0; i < 2000; i++) {
437 if (::MoveFileExW(wide_from.begin(), wide_to.begin(),
438 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
439 return error_code::success();
440 ec = windows_error(::GetLastError());
441 if (ec != windows_error::access_denied)
443 // Retry MoveFile() at ACCESS_DENIED.
444 // System scanners (eg. indexer) might open the source file when
445 // It is written and closed.
452 error_code resize_file(const Twine &path, uint64_t size) {
453 SmallString<128> path_storage;
454 SmallVector<wchar_t, 128> path_utf16;
456 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
460 int fd = ::_wopen(path_utf16.begin(), O_BINARY | _O_RDWR, S_IWRITE);
462 return error_code(errno, generic_category());
463 #ifdef HAVE__CHSIZE_S
464 errno_t error = ::_chsize_s(fd, size);
466 errno_t error = ::_chsize(fd, size);
469 return error_code(error, generic_category());
472 error_code exists(const Twine &path, bool &result) {
473 SmallString<128> path_storage;
474 SmallVector<wchar_t, 128> path_utf16;
476 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
480 DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
482 if (attributes == INVALID_FILE_ATTRIBUTES) {
483 // See if the file didn't actually exist.
484 error_code ec = make_error_code(windows_error(::GetLastError()));
485 if (ec != windows_error::file_not_found &&
486 ec != windows_error::path_not_found)
491 return error_code::success();
494 bool can_write(const Twine &Path) {
495 // FIXME: take security attributes into account.
496 SmallString<128> PathStorage;
497 SmallVector<wchar_t, 128> PathUtf16;
499 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
502 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
503 return (Attr != INVALID_FILE_ATTRIBUTES) && !(Attr & FILE_ATTRIBUTE_READONLY);
506 bool can_execute(const Twine &Path) {
507 SmallString<128> PathStorage;
508 SmallVector<wchar_t, 128> PathUtf16;
510 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
513 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
514 return Attr != INVALID_FILE_ATTRIBUTES;
517 bool equivalent(file_status A, file_status B) {
518 assert(status_known(A) && status_known(B));
519 return A.FileIndexHigh == B.FileIndexHigh &&
520 A.FileIndexLow == B.FileIndexLow &&
521 A.FileSizeHigh == B.FileSizeHigh &&
522 A.FileSizeLow == B.FileSizeLow &&
523 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
524 A.LastWriteTimeLow == B.LastWriteTimeLow &&
525 A.VolumeSerialNumber == B.VolumeSerialNumber;
528 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
529 file_status fsA, fsB;
530 if (error_code ec = status(A, fsA)) return ec;
531 if (error_code ec = status(B, fsB)) return ec;
532 result = equivalent(fsA, fsB);
533 return error_code::success();
536 error_code getUniqueID(const Twine Path, uint64_t &Result) {
538 if (error_code E = status(Path, Status))
541 // The file is uniquely identified by the volume serial number along
542 // with the 64-bit file identifier.
543 Result = (static_cast<uint64_t>(Status.FileIndexHigh) << 32ULL) |
544 static_cast<uint64_t>(Status.FileIndexLow);
546 // Because the serial number is 32-bits, but we've already used up all 64
547 // bits for the file index, XOR the serial number into the high 32 bits of
548 // the resulting value. We could potentially get collisons from this, but
549 // the likelihood is low.
550 Result ^= (static_cast<uint64_t>(Status.VolumeSerialNumber) << 32ULL);
552 return error_code::success();
555 static bool isReservedName(StringRef path) {
556 // This list of reserved names comes from MSDN, at:
557 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
558 static const char *sReservedNames[] = { "nul", "con", "prn", "aux",
559 "com1", "com2", "com3", "com4", "com5", "com6",
560 "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
561 "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9" };
563 // First, check to see if this is a device namespace, which always
564 // starts with \\.\, since device namespaces are not legal file paths.
565 if (path.startswith("\\\\.\\"))
568 // Then compare against the list of ancient reserved names
569 for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
570 if (path.equals_lower(sReservedNames[i]))
574 // The path isn't what we consider reserved.
578 static error_code getStatus(HANDLE FileHandle, file_status &Result) {
579 if (FileHandle == INVALID_HANDLE_VALUE)
580 goto handle_status_error;
582 BY_HANDLE_FILE_INFORMATION Info;
583 if (!::GetFileInformationByHandle(FileHandle, &Info))
584 goto handle_status_error;
586 Result = file_status(
587 file_type::regular_file, Info.ftLastWriteTime.dwHighDateTime,
588 Info.ftLastWriteTime.dwLowDateTime, Info.dwVolumeSerialNumber,
589 Info.nFileSizeHigh, Info.nFileSizeLow, Info.nFileIndexHigh,
591 return error_code::success();
594 error_code EC = windows_error(::GetLastError());
595 if (EC == windows_error::file_not_found ||
596 EC == windows_error::path_not_found)
597 Result = file_status(file_type::file_not_found);
598 else if (EC == windows_error::sharing_violation)
599 Result = file_status(file_type::type_unknown);
601 Result = file_status(file_type::status_error);
604 return error_code::success();
607 error_code status(const Twine &path, file_status &result) {
608 SmallString<128> path_storage;
609 SmallVector<wchar_t, 128> path_utf16;
611 StringRef path8 = path.toStringRef(path_storage);
612 if (isReservedName(path8)) {
613 result = file_status(file_type::character_file);
614 return error_code::success();
617 if (error_code ec = UTF8ToUTF16(path8, path_utf16))
620 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
621 if (attr == INVALID_FILE_ATTRIBUTES)
622 return getStatus(INVALID_HANDLE_VALUE, result);
624 // Handle reparse points.
625 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
627 ::CreateFileW(path_utf16.begin(),
628 0, // Attributes only.
629 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
632 FILE_FLAG_BACKUP_SEMANTICS,
635 return getStatus(INVALID_HANDLE_VALUE, result);
638 if (attr & FILE_ATTRIBUTE_DIRECTORY)
639 result = file_status(file_type::directory_file);
642 ::CreateFileW(path_utf16.begin(),
643 0, // Attributes only.
644 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
647 FILE_FLAG_BACKUP_SEMANTICS,
650 return getStatus(INVALID_HANDLE_VALUE, result);
651 BY_HANDLE_FILE_INFORMATION Info;
652 if (!::GetFileInformationByHandle(h, &Info))
653 return getStatus(INVALID_HANDLE_VALUE, result);
655 return getStatus(h, result);
657 return error_code::success();
660 error_code status(int FD, file_status &Result) {
661 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
662 return getStatus(FileHandle, Result);
665 error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
667 UI.QuadPart = Time.toWin32Time();
669 FT.dwLowDateTime = UI.LowPart;
670 FT.dwHighDateTime = UI.HighPart;
671 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
672 if (!SetFileTime(FileHandle, NULL, &FT, &FT))
673 return windows_error(::GetLastError());
674 return error_code::success();
677 error_code get_magic(const Twine &path, uint32_t len,
678 SmallVectorImpl<char> &result) {
679 SmallString<128> path_storage;
680 SmallVector<wchar_t, 128> path_utf16;
683 // Convert path to UTF-16.
684 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
689 HANDLE file = ::CreateFileW(c_str(path_utf16),
694 FILE_ATTRIBUTE_READONLY,
696 if (file == INVALID_HANDLE_VALUE)
697 return windows_error(::GetLastError());
703 DWORD bytes_read = 0;
704 BOOL read_success = ::ReadFile(file, result.data(), len, &bytes_read, NULL);
705 error_code ec = windows_error(::GetLastError());
707 if (!read_success || (bytes_read != len)) {
708 // Set result size to the number of bytes read if it's valid.
709 if (bytes_read <= len)
710 result.set_size(bytes_read);
711 // ERROR_HANDLE_EOF is mapped to errc::value_too_large.
715 result.set_size(len);
716 return error_code::success();
719 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
721 // Make sure that the requested size fits within SIZE_T.
722 if (Size > std::numeric_limits<SIZE_T>::max()) {
723 if (FileDescriptor) {
725 _close(FileDescriptor);
727 ::CloseHandle(FileHandle);
728 return make_error_code(errc::invalid_argument);
733 case readonly: flprotect = PAGE_READONLY; break;
734 case readwrite: flprotect = PAGE_READWRITE; break;
735 case priv: flprotect = PAGE_WRITECOPY; break;
738 FileMappingHandle = ::CreateFileMapping(FileHandle,
744 if (FileMappingHandle == NULL) {
745 error_code ec = windows_error(GetLastError());
746 if (FileDescriptor) {
748 _close(FileDescriptor);
750 ::CloseHandle(FileHandle);
754 DWORD dwDesiredAccess;
756 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
757 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
758 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
760 Mapping = ::MapViewOfFile(FileMappingHandle,
765 if (Mapping == NULL) {
766 error_code ec = windows_error(GetLastError());
767 ::CloseHandle(FileMappingHandle);
768 if (FileDescriptor) {
770 _close(FileDescriptor);
772 ::CloseHandle(FileHandle);
777 MEMORY_BASIC_INFORMATION mbi;
778 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
780 error_code ec = windows_error(GetLastError());
781 ::UnmapViewOfFile(Mapping);
782 ::CloseHandle(FileMappingHandle);
783 if (FileDescriptor) {
785 _close(FileDescriptor);
787 ::CloseHandle(FileHandle);
790 Size = mbi.RegionSize;
793 // Close all the handles except for the view. It will keep the other handles
795 ::CloseHandle(FileMappingHandle);
796 if (FileDescriptor) {
798 _close(FileDescriptor); // Also closes FileHandle.
800 ::CloseHandle(FileHandle);
801 return error_code::success();
804 mapped_file_region::mapped_file_region(const Twine &path,
813 , FileHandle(INVALID_HANDLE_VALUE)
814 , FileMappingHandle() {
815 SmallString<128> path_storage;
816 SmallVector<wchar_t, 128> path_utf16;
818 // Convert path to UTF-16.
819 if ((ec = UTF8ToUTF16(path.toStringRef(path_storage), path_utf16)))
822 // Get file handle for creating a file mapping.
823 FileHandle = ::CreateFileW(c_str(path_utf16),
824 Mode == readonly ? GENERIC_READ
825 : GENERIC_READ | GENERIC_WRITE,
826 Mode == readonly ? FILE_SHARE_READ
829 Mode == readonly ? OPEN_EXISTING
831 Mode == readonly ? FILE_ATTRIBUTE_READONLY
832 : FILE_ATTRIBUTE_NORMAL,
834 if (FileHandle == INVALID_HANDLE_VALUE) {
835 ec = windows_error(::GetLastError());
840 ec = init(FileDescriptor, true, offset);
842 Mapping = FileMappingHandle = 0;
843 FileHandle = INVALID_HANDLE_VALUE;
848 mapped_file_region::mapped_file_region(int fd,
858 , FileHandle(INVALID_HANDLE_VALUE)
859 , FileMappingHandle() {
860 FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
861 if (FileHandle == INVALID_HANDLE_VALUE) {
863 _close(FileDescriptor);
865 ec = make_error_code(errc::bad_file_descriptor);
869 ec = init(FileDescriptor, closefd, offset);
871 Mapping = FileMappingHandle = 0;
872 FileHandle = INVALID_HANDLE_VALUE;
877 mapped_file_region::~mapped_file_region() {
879 ::UnmapViewOfFile(Mapping);
882 #if LLVM_HAS_RVALUE_REFERENCES
883 mapped_file_region::mapped_file_region(mapped_file_region &&other)
886 , Mapping(other.Mapping)
887 , FileDescriptor(other.FileDescriptor)
888 , FileHandle(other.FileHandle)
889 , FileMappingHandle(other.FileMappingHandle) {
890 other.Mapping = other.FileMappingHandle = 0;
891 other.FileHandle = INVALID_HANDLE_VALUE;
892 other.FileDescriptor = 0;
896 mapped_file_region::mapmode mapped_file_region::flags() const {
897 assert(Mapping && "Mapping failed but used anyway!");
901 uint64_t mapped_file_region::size() const {
902 assert(Mapping && "Mapping failed but used anyway!");
906 char *mapped_file_region::data() const {
907 assert(Mode != readonly && "Cannot get non const data for readonly mapping!");
908 assert(Mapping && "Mapping failed but used anyway!");
909 return reinterpret_cast<char*>(Mapping);
912 const char *mapped_file_region::const_data() const {
913 assert(Mapping && "Mapping failed but used anyway!");
914 return reinterpret_cast<const char*>(Mapping);
917 int mapped_file_region::alignment() {
919 ::GetSystemInfo(&SysInfo);
920 return SysInfo.dwAllocationGranularity;
923 error_code detail::directory_iterator_construct(detail::DirIterState &it,
925 SmallVector<wchar_t, 128> path_utf16;
927 if (error_code ec = UTF8ToUTF16(path,
931 // Convert path to the format that Windows is happy with.
932 if (path_utf16.size() > 0 &&
933 !is_separator(path_utf16[path.size() - 1]) &&
934 path_utf16[path.size() - 1] != L':') {
935 path_utf16.push_back(L'\\');
936 path_utf16.push_back(L'*');
938 path_utf16.push_back(L'*');
941 // Get the first directory entry.
942 WIN32_FIND_DATAW FirstFind;
943 ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
945 return windows_error(::GetLastError());
947 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
948 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
949 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
950 FirstFind.cFileName[1] == L'.'))
951 if (!::FindNextFileW(FindHandle, &FirstFind)) {
952 error_code ec = windows_error(::GetLastError());
954 if (ec == windows_error::no_more_files)
955 return detail::directory_iterator_destruct(it);
958 FilenameLen = ::wcslen(FirstFind.cFileName);
960 // Construct the current directory entry.
961 SmallString<128> directory_entry_name_utf8;
962 if (error_code ec = UTF16ToUTF8(FirstFind.cFileName,
963 ::wcslen(FirstFind.cFileName),
964 directory_entry_name_utf8))
967 it.IterationHandle = intptr_t(FindHandle.take());
968 SmallString<128> directory_entry_path(path);
969 path::append(directory_entry_path, directory_entry_name_utf8.str());
970 it.CurrentEntry = directory_entry(directory_entry_path.str());
972 return error_code::success();
975 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
976 if (it.IterationHandle != 0)
977 // Closes the handle if it's valid.
978 ScopedFindHandle close(HANDLE(it.IterationHandle));
979 it.IterationHandle = 0;
980 it.CurrentEntry = directory_entry();
981 return error_code::success();
984 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
985 WIN32_FIND_DATAW FindData;
986 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
987 error_code ec = windows_error(::GetLastError());
989 if (ec == windows_error::no_more_files)
990 return detail::directory_iterator_destruct(it);
994 size_t FilenameLen = ::wcslen(FindData.cFileName);
995 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
996 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
997 FindData.cFileName[1] == L'.'))
998 return directory_iterator_increment(it);
1000 SmallString<128> directory_entry_path_utf8;
1001 if (error_code ec = UTF16ToUTF8(FindData.cFileName,
1002 ::wcslen(FindData.cFileName),
1003 directory_entry_path_utf8))
1006 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
1007 return error_code::success();
1010 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
1011 bool map_writable, void *&result) {
1012 assert(0 && "NOT IMPLEMENTED");
1013 return windows_error::invalid_function;
1016 error_code unmap_file_pages(void *base, size_t size) {
1017 assert(0 && "NOT IMPLEMENTED");
1018 return windows_error::invalid_function;
1021 error_code openFileForRead(const Twine &Name, int &ResultFD) {
1022 SmallString<128> PathStorage;
1023 SmallVector<wchar_t, 128> PathUTF16;
1025 if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
1029 HANDLE H = ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
1030 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1031 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1032 if (H == INVALID_HANDLE_VALUE) {
1033 error_code EC = windows_error(::GetLastError());
1034 // Provide a better error message when trying to open directories.
1035 // This only runs if we failed to open the file, so there is probably
1036 // no performances issues.
1037 if (EC != windows_error::access_denied)
1039 if (is_directory(Name))
1040 return error_code(errc::is_a_directory, posix_category());
1044 int FD = ::_open_osfhandle(intptr_t(H), 0);
1047 return windows_error::invalid_handle;
1051 return error_code::success();
1054 } // end namespace fs
1055 } // end namespace sys
1056 } // end namespace llvm