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 //===----------------------------------------------------------------------===//
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) {
127 // FIXME: mode should be used here and default to user r/w only,
128 // it currently comes in as a UNIX mode.
129 static error_code createUniqueEntity(const Twine &model, int &result_fd,
130 SmallVectorImpl<char> &result_path,
131 bool makeAbsolute, unsigned mode,
133 // Use result_path as temp storage.
134 result_path.set_size(0);
135 StringRef m = model.toStringRef(result_path);
137 SmallVector<wchar_t, 128> model_utf16;
138 if (error_code ec = UTF8ToUTF16(m, model_utf16)) return ec;
141 // Make model absolute by prepending a temp directory if it's not already.
142 bool absolute = sys::path::is_absolute(m);
145 SmallVector<wchar_t, 64> temp_dir;
146 if (error_code ec = TempDir(temp_dir)) return ec;
147 // Handle c: by removing it.
148 if (model_utf16.size() > 2 && model_utf16[1] == L':') {
149 model_utf16.erase(model_utf16.begin(), model_utf16.begin() + 2);
151 model_utf16.insert(model_utf16.begin(), temp_dir.begin(), temp_dir.end());
155 // Replace '%' with random chars. From here on, DO NOT modify model. It may be
156 // needed if the randomly chosen path already exists.
157 SmallVector<wchar_t, 128> random_path_utf16;
159 // Get a Crypto Provider for CryptGenRandom.
161 if (!::CryptAcquireContextW(&HCPC,
165 CRYPT_VERIFYCONTEXT))
166 return windows_error(::GetLastError());
167 ScopedCryptContext CryptoProvider(HCPC);
170 random_path_utf16.set_size(0);
171 for (SmallVectorImpl<wchar_t>::const_iterator i = model_utf16.begin(),
172 e = model_utf16.end();
176 if (!::CryptGenRandom(CryptoProvider, 1, &val))
177 return windows_error(::GetLastError());
178 random_path_utf16.push_back("0123456789abcdef"[val & 15]);
181 random_path_utf16.push_back(*i);
183 // Make random_path_utf16 null terminated.
184 random_path_utf16.push_back(0);
185 random_path_utf16.pop_back();
187 HANDLE TempFileHandle;
191 // Try to create + open the path.
193 ::CreateFileW(random_path_utf16.begin(), GENERIC_READ | GENERIC_WRITE,
194 FILE_SHARE_READ, NULL,
195 // Return ERROR_FILE_EXISTS if the file
197 CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY, NULL);
198 if (TempFileHandle == INVALID_HANDLE_VALUE) {
199 // If the file existed, try again, otherwise, error.
200 error_code ec = windows_error(::GetLastError());
201 if (ec == windows_error::file_exists)
202 goto retry_random_path;
207 // Convert the Windows API file handle into a C-runtime handle.
208 int fd = ::_open_osfhandle(intptr_t(TempFileHandle), 0);
210 ::CloseHandle(TempFileHandle);
211 ::DeleteFileW(random_path_utf16.begin());
212 // MSDN doesn't say anything about _open_osfhandle setting errno or
213 // GetLastError(), so just return invalid_handle.
214 return windows_error::invalid_handle;
222 DWORD attributes = ::GetFileAttributesW(random_path_utf16.begin());
223 if (attributes != INVALID_FILE_ATTRIBUTES)
224 goto retry_random_path;
225 error_code EC = make_error_code(windows_error(::GetLastError()));
226 if (EC != windows_error::file_not_found &&
227 EC != windows_error::path_not_found)
233 if (!::CreateDirectoryW(random_path_utf16.begin(), NULL)) {
234 error_code EC = windows_error(::GetLastError());
235 if (EC != windows_error::already_exists)
237 goto retry_random_path;
242 // Set result_path to the utf-8 representation of the path.
243 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
244 random_path_utf16.size(), result_path)) {
247 ::CloseHandle(TempFileHandle);
248 ::DeleteFileW(random_path_utf16.begin());
252 ::RemoveDirectoryW(random_path_utf16.begin());
258 return error_code::success();
265 std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
266 char pathname[MAX_PATH];
267 DWORD ret = ::GetModuleFileNameA(NULL, pathname, MAX_PATH);
268 return ret != MAX_PATH ? pathname : "";
272 TimeValue file_status::getLastModificationTime() const {
274 UI.LowPart = LastWriteTimeLow;
275 UI.HighPart = LastWriteTimeHigh;
278 Ret.fromWin32Time(UI.QuadPart);
282 error_code current_path(SmallVectorImpl<char> &result) {
283 SmallVector<wchar_t, 128> cur_path;
284 cur_path.reserve(128);
286 DWORD len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
288 // A zero return value indicates a failure other than insufficient space.
290 return windows_error(::GetLastError());
292 // If there's insufficient space, the len returned is larger than the len
294 if (len > cur_path.capacity()) {
295 cur_path.reserve(len);
299 cur_path.set_size(len);
300 // cur_path now holds the current directory in utf-16. Convert to utf-8.
302 // Find out how much space we need. Sadly, this function doesn't return the
303 // size needed unless you tell it the result size is 0, which means you
304 // _always_ have to call it twice.
305 len = ::WideCharToMultiByte(CP_UTF8, 0,
306 cur_path.data(), cur_path.size(),
311 return make_error_code(windows_error(::GetLastError()));
314 result.set_size(len);
315 // Now do the actual conversion.
316 len = ::WideCharToMultiByte(CP_UTF8, 0,
317 cur_path.data(), cur_path.size(),
318 result.data(), result.size(),
321 return windows_error(::GetLastError());
323 return error_code::success();
326 error_code copy_file(const Twine &from, const Twine &to, copy_option copt) {
328 SmallString<128> from_storage;
329 SmallString<128> to_storage;
330 StringRef f = from.toStringRef(from_storage);
331 StringRef t = to.toStringRef(to_storage);
333 // Convert to utf-16.
334 SmallVector<wchar_t, 128> wide_from;
335 SmallVector<wchar_t, 128> wide_to;
336 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
337 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
340 BOOL res = ::CopyFileW(wide_from.begin(), wide_to.begin(),
341 copt != copy_option::overwrite_if_exists);
344 return windows_error(::GetLastError());
346 return error_code::success();
349 error_code create_directory(const Twine &path, bool &existed) {
350 SmallString<128> path_storage;
351 SmallVector<wchar_t, 128> path_utf16;
353 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
357 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
358 error_code ec = windows_error(::GetLastError());
359 if (ec == windows_error::already_exists)
366 return error_code::success();
369 error_code create_hard_link(const Twine &to, const Twine &from) {
371 SmallString<128> from_storage;
372 SmallString<128> to_storage;
373 StringRef f = from.toStringRef(from_storage);
374 StringRef t = to.toStringRef(to_storage);
376 // Convert to utf-16.
377 SmallVector<wchar_t, 128> wide_from;
378 SmallVector<wchar_t, 128> wide_to;
379 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
380 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
382 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
383 return windows_error(::GetLastError());
385 return error_code::success();
388 error_code create_symlink(const Twine &to, const Twine &from) {
389 // Only do it if the function is available at runtime.
390 if (!create_symbolic_link_api)
391 return make_error_code(errc::function_not_supported);
394 SmallString<128> from_storage;
395 SmallString<128> to_storage;
396 StringRef f = from.toStringRef(from_storage);
397 StringRef t = to.toStringRef(to_storage);
399 // Convert to utf-16.
400 SmallVector<wchar_t, 128> wide_from;
401 SmallVector<wchar_t, 128> wide_to;
402 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
403 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
405 if (!create_symbolic_link_api(wide_from.begin(), wide_to.begin(), 0))
406 return windows_error(::GetLastError());
408 return error_code::success();
411 error_code remove(const Twine &path, bool &existed) {
412 SmallString<128> path_storage;
413 SmallVector<wchar_t, 128> path_utf16;
416 if (error_code ec = status(path, st))
419 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
423 if (st.type() == file_type::directory_file) {
424 if (!::RemoveDirectoryW(c_str(path_utf16))) {
425 error_code ec = windows_error(::GetLastError());
426 if (ec != windows_error::file_not_found)
432 if (!::DeleteFileW(c_str(path_utf16))) {
433 error_code ec = windows_error(::GetLastError());
434 if (ec != windows_error::file_not_found)
441 return error_code::success();
444 error_code rename(const Twine &from, const Twine &to) {
446 SmallString<128> from_storage;
447 SmallString<128> to_storage;
448 StringRef f = from.toStringRef(from_storage);
449 StringRef t = to.toStringRef(to_storage);
451 // Convert to utf-16.
452 SmallVector<wchar_t, 128> wide_from;
453 SmallVector<wchar_t, 128> wide_to;
454 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
455 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
457 error_code ec = error_code::success();
458 for (int i = 0; i < 2000; i++) {
459 if (::MoveFileExW(wide_from.begin(), wide_to.begin(),
460 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
461 return error_code::success();
462 ec = windows_error(::GetLastError());
463 if (ec != windows_error::access_denied)
465 // Retry MoveFile() at ACCESS_DENIED.
466 // System scanners (eg. indexer) might open the source file when
467 // It is written and closed.
474 error_code resize_file(const Twine &path, uint64_t size) {
475 SmallString<128> path_storage;
476 SmallVector<wchar_t, 128> path_utf16;
478 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
482 int fd = ::_wopen(path_utf16.begin(), O_BINARY | _O_RDWR, S_IWRITE);
484 return error_code(errno, generic_category());
485 #ifdef HAVE__CHSIZE_S
486 errno_t error = ::_chsize_s(fd, size);
488 errno_t error = ::_chsize(fd, size);
491 return error_code(error, generic_category());
494 error_code exists(const Twine &path, bool &result) {
495 SmallString<128> path_storage;
496 SmallVector<wchar_t, 128> path_utf16;
498 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
502 DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
504 if (attributes == INVALID_FILE_ATTRIBUTES) {
505 // See if the file didn't actually exist.
506 error_code ec = make_error_code(windows_error(::GetLastError()));
507 if (ec != windows_error::file_not_found &&
508 ec != windows_error::path_not_found)
513 return error_code::success();
516 bool can_write(const Twine &Path) {
517 // FIXME: take security attributes into account.
518 SmallString<128> PathStorage;
519 SmallVector<wchar_t, 128> PathUtf16;
521 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
524 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
525 return (Attr != INVALID_FILE_ATTRIBUTES) && !(Attr & FILE_ATTRIBUTE_READONLY);
528 bool can_execute(const Twine &Path) {
529 SmallString<128> PathStorage;
530 SmallVector<wchar_t, 128> PathUtf16;
532 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
535 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
536 return Attr != INVALID_FILE_ATTRIBUTES;
539 bool equivalent(file_status A, file_status B) {
540 assert(status_known(A) && status_known(B));
541 return A.FileIndexHigh == B.FileIndexHigh &&
542 A.FileIndexLow == B.FileIndexLow &&
543 A.FileSizeHigh == B.FileSizeHigh &&
544 A.FileSizeLow == B.FileSizeLow &&
545 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
546 A.LastWriteTimeLow == B.LastWriteTimeLow &&
547 A.VolumeSerialNumber == B.VolumeSerialNumber;
550 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
551 file_status fsA, fsB;
552 if (error_code ec = status(A, fsA)) return ec;
553 if (error_code ec = status(B, fsB)) return ec;
554 result = equivalent(fsA, fsB);
555 return error_code::success();
558 error_code file_size(const Twine &path, uint64_t &result) {
559 SmallString<128> path_storage;
560 SmallVector<wchar_t, 128> path_utf16;
562 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
566 WIN32_FILE_ATTRIBUTE_DATA FileData;
567 if (!::GetFileAttributesExW(path_utf16.begin(),
568 ::GetFileExInfoStandard,
570 return windows_error(::GetLastError());
573 (uint64_t(FileData.nFileSizeHigh) << (sizeof(FileData.nFileSizeLow) * 8))
574 + FileData.nFileSizeLow;
576 return error_code::success();
579 error_code getUniqueID(const Twine Path, uint64_t &Result) {
581 if (error_code E = status(Path, Status))
584 // The file is uniquely identified by the volume serial number along
585 // with the 64-bit file identifier.
586 Result = (static_cast<uint64_t>(Status.FileIndexHigh) << 32ULL) |
587 static_cast<uint64_t>(Status.FileIndexLow);
589 // Because the serial number is 32-bits, but we've already used up all 64
590 // bits for the file index, XOR the serial number into the high 32 bits of
591 // the resulting value. We could potentially get collisons from this, but
592 // the likelihood is low.
593 Result ^= (static_cast<uint64_t>(Status.VolumeSerialNumber) << 32ULL);
595 return error_code::success();
598 static bool isReservedName(StringRef path) {
599 // This list of reserved names comes from MSDN, at:
600 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
601 static const char *sReservedNames[] = { "nul", "con", "prn", "aux",
602 "com1", "com2", "com3", "com4", "com5", "com6",
603 "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
604 "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9" };
606 // First, check to see if this is a device namespace, which always
607 // starts with \\.\, since device namespaces are not legal file paths.
608 if (path.startswith("\\\\.\\"))
611 // Then compare against the list of ancient reserved names
612 for (size_t i = 0; i < sizeof(sReservedNames) / sizeof(const char *); ++i) {
613 if (path.equals_lower(sReservedNames[i]))
617 // The path isn't what we consider reserved.
621 error_code status(const Twine &path, file_status &result) {
622 SmallString<128> path_storage;
623 SmallVector<wchar_t, 128> path_utf16;
625 StringRef path8 = path.toStringRef(path_storage);
626 if (isReservedName(path8)) {
627 result = file_status(file_type::character_file);
628 return error_code::success();
631 if (error_code ec = UTF8ToUTF16(path8, path_utf16))
634 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
635 if (attr == INVALID_FILE_ATTRIBUTES)
636 goto handle_status_error;
638 // Handle reparse points.
639 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
641 ::CreateFileW(path_utf16.begin(),
642 0, // Attributes only.
643 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
646 FILE_FLAG_BACKUP_SEMANTICS,
649 goto handle_status_error;
652 if (attr & FILE_ATTRIBUTE_DIRECTORY)
653 result = file_status(file_type::directory_file);
655 result = file_status(file_type::regular_file);
657 ::CreateFileW(path_utf16.begin(),
658 0, // Attributes only.
659 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
662 FILE_FLAG_BACKUP_SEMANTICS,
665 goto handle_status_error;
666 BY_HANDLE_FILE_INFORMATION Info;
667 if (!::GetFileInformationByHandle(h, &Info))
668 goto handle_status_error;
669 result.FileIndexHigh = Info.nFileIndexHigh;
670 result.FileIndexLow = Info.nFileIndexLow;
671 result.FileSizeHigh = Info.nFileSizeHigh;
672 result.FileSizeLow = Info.nFileSizeLow;
673 result.LastWriteTimeHigh = Info.ftLastWriteTime.dwHighDateTime;
674 result.LastWriteTimeLow = Info.ftLastWriteTime.dwLowDateTime;
675 result.VolumeSerialNumber = Info.dwVolumeSerialNumber;
678 return error_code::success();
681 error_code ec = windows_error(::GetLastError());
682 if (ec == windows_error::file_not_found ||
683 ec == windows_error::path_not_found)
684 result = file_status(file_type::file_not_found);
685 else if (ec == windows_error::sharing_violation)
686 result = file_status(file_type::type_unknown);
688 result = file_status(file_type::status_error);
692 return error_code::success();
696 // Modifies permissions on a file.
697 error_code permissions(const Twine &path, perms prms) {
698 #if 0 // verify code below before enabling:
699 // If the permissions bits are not trying to modify
700 // "write" permissions, there is nothing to do.
701 if (!(prms & (owner_write|group_write|others_write)))
702 return error_code::success();
704 SmallString<128> path_storage;
705 SmallVector<wchar_t, 128> path_utf16;
707 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
711 DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
713 if (prms & add_perms) {
714 attributes &= ~FILE_ATTRIBUTE_READONLY;
716 else if (prms & remove_perms) {
717 attributes |= FILE_ATTRIBUTE_READONLY;
720 assert(0 && "neither add_perms or remove_perms is set");
723 if ( ! ::SetFileAttributesW(path_utf16.begin(), attributes))
724 return windows_error(::GetLastError());
726 return error_code::success();
729 error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
731 UI.QuadPart = Time.toWin32Time();
733 FT.dwLowDateTime = UI.LowPart;
734 FT.dwHighDateTime = UI.HighPart;
735 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
736 if (!SetFileTime(FileHandle, NULL, &FT, &FT))
737 return windows_error(::GetLastError());
738 return error_code::success();
741 error_code get_magic(const Twine &path, uint32_t len,
742 SmallVectorImpl<char> &result) {
743 SmallString<128> path_storage;
744 SmallVector<wchar_t, 128> path_utf16;
747 // Convert path to UTF-16.
748 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
753 HANDLE file = ::CreateFileW(c_str(path_utf16),
758 FILE_ATTRIBUTE_READONLY,
760 if (file == INVALID_HANDLE_VALUE)
761 return windows_error(::GetLastError());
767 DWORD bytes_read = 0;
768 BOOL read_success = ::ReadFile(file, result.data(), len, &bytes_read, NULL);
769 error_code ec = windows_error(::GetLastError());
771 if (!read_success || (bytes_read != len)) {
772 // Set result size to the number of bytes read if it's valid.
773 if (bytes_read <= len)
774 result.set_size(bytes_read);
775 // ERROR_HANDLE_EOF is mapped to errc::value_too_large.
779 result.set_size(len);
780 return error_code::success();
783 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
785 // Make sure that the requested size fits within SIZE_T.
786 if (Size > std::numeric_limits<SIZE_T>::max()) {
787 if (FileDescriptor) {
789 _close(FileDescriptor);
791 ::CloseHandle(FileHandle);
792 return make_error_code(errc::invalid_argument);
797 case readonly: flprotect = PAGE_READONLY; break;
798 case readwrite: flprotect = PAGE_READWRITE; break;
799 case priv: flprotect = PAGE_WRITECOPY; break;
800 default: llvm_unreachable("invalid mapping mode");
803 FileMappingHandle = ::CreateFileMapping(FileHandle,
809 if (FileMappingHandle == NULL) {
810 error_code ec = windows_error(GetLastError());
811 if (FileDescriptor) {
813 _close(FileDescriptor);
815 ::CloseHandle(FileHandle);
819 DWORD dwDesiredAccess;
821 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
822 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
823 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
824 default: llvm_unreachable("invalid mapping mode");
826 Mapping = ::MapViewOfFile(FileMappingHandle,
831 if (Mapping == NULL) {
832 error_code ec = windows_error(GetLastError());
833 ::CloseHandle(FileMappingHandle);
834 if (FileDescriptor) {
836 _close(FileDescriptor);
838 ::CloseHandle(FileHandle);
843 MEMORY_BASIC_INFORMATION mbi;
844 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
846 error_code ec = windows_error(GetLastError());
847 ::UnmapViewOfFile(Mapping);
848 ::CloseHandle(FileMappingHandle);
849 if (FileDescriptor) {
851 _close(FileDescriptor);
853 ::CloseHandle(FileHandle);
856 Size = mbi.RegionSize;
859 // Close all the handles except for the view. It will keep the other handles
861 ::CloseHandle(FileMappingHandle);
862 if (FileDescriptor) {
864 _close(FileDescriptor); // Also closes FileHandle.
866 ::CloseHandle(FileHandle);
867 return error_code::success();
870 mapped_file_region::mapped_file_region(const Twine &path,
879 , FileHandle(INVALID_HANDLE_VALUE)
880 , FileMappingHandle() {
881 SmallString<128> path_storage;
882 SmallVector<wchar_t, 128> path_utf16;
884 // Convert path to UTF-16.
885 if ((ec = UTF8ToUTF16(path.toStringRef(path_storage), path_utf16)))
888 // Get file handle for creating a file mapping.
889 FileHandle = ::CreateFileW(c_str(path_utf16),
890 Mode == readonly ? GENERIC_READ
891 : GENERIC_READ | GENERIC_WRITE,
892 Mode == readonly ? FILE_SHARE_READ
895 Mode == readonly ? OPEN_EXISTING
897 Mode == readonly ? FILE_ATTRIBUTE_READONLY
898 : FILE_ATTRIBUTE_NORMAL,
900 if (FileHandle == INVALID_HANDLE_VALUE) {
901 ec = windows_error(::GetLastError());
906 ec = init(FileDescriptor, true, offset);
908 Mapping = FileMappingHandle = 0;
909 FileHandle = INVALID_HANDLE_VALUE;
914 mapped_file_region::mapped_file_region(int fd,
924 , FileHandle(INVALID_HANDLE_VALUE)
925 , FileMappingHandle() {
926 FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
927 if (FileHandle == INVALID_HANDLE_VALUE) {
929 _close(FileDescriptor);
931 ec = make_error_code(errc::bad_file_descriptor);
935 ec = init(FileDescriptor, closefd, offset);
937 Mapping = FileMappingHandle = 0;
938 FileHandle = INVALID_HANDLE_VALUE;
943 mapped_file_region::~mapped_file_region() {
945 ::UnmapViewOfFile(Mapping);
948 #if LLVM_HAS_RVALUE_REFERENCES
949 mapped_file_region::mapped_file_region(mapped_file_region &&other)
952 , Mapping(other.Mapping)
953 , FileDescriptor(other.FileDescriptor)
954 , FileHandle(other.FileHandle)
955 , FileMappingHandle(other.FileMappingHandle) {
956 other.Mapping = other.FileMappingHandle = 0;
957 other.FileHandle = INVALID_HANDLE_VALUE;
958 other.FileDescriptor = 0;
962 mapped_file_region::mapmode mapped_file_region::flags() const {
963 assert(Mapping && "Mapping failed but used anyway!");
967 uint64_t mapped_file_region::size() const {
968 assert(Mapping && "Mapping failed but used anyway!");
972 char *mapped_file_region::data() const {
973 assert(Mode != readonly && "Cannot get non const data for readonly mapping!");
974 assert(Mapping && "Mapping failed but used anyway!");
975 return reinterpret_cast<char*>(Mapping);
978 const char *mapped_file_region::const_data() const {
979 assert(Mapping && "Mapping failed but used anyway!");
980 return reinterpret_cast<const char*>(Mapping);
983 int mapped_file_region::alignment() {
985 ::GetSystemInfo(&SysInfo);
986 return SysInfo.dwAllocationGranularity;
989 error_code detail::directory_iterator_construct(detail::DirIterState &it,
991 SmallVector<wchar_t, 128> path_utf16;
993 if (error_code ec = UTF8ToUTF16(path,
997 // Convert path to the format that Windows is happy with.
998 if (path_utf16.size() > 0 &&
999 !is_separator(path_utf16[path.size() - 1]) &&
1000 path_utf16[path.size() - 1] != L':') {
1001 path_utf16.push_back(L'\\');
1002 path_utf16.push_back(L'*');
1004 path_utf16.push_back(L'*');
1007 // Get the first directory entry.
1008 WIN32_FIND_DATAW FirstFind;
1009 ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
1011 return windows_error(::GetLastError());
1013 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
1014 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
1015 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
1016 FirstFind.cFileName[1] == L'.'))
1017 if (!::FindNextFileW(FindHandle, &FirstFind)) {
1018 error_code ec = windows_error(::GetLastError());
1020 if (ec == windows_error::no_more_files)
1021 return detail::directory_iterator_destruct(it);
1024 FilenameLen = ::wcslen(FirstFind.cFileName);
1026 // Construct the current directory entry.
1027 SmallString<128> directory_entry_name_utf8;
1028 if (error_code ec = UTF16ToUTF8(FirstFind.cFileName,
1029 ::wcslen(FirstFind.cFileName),
1030 directory_entry_name_utf8))
1033 it.IterationHandle = intptr_t(FindHandle.take());
1034 SmallString<128> directory_entry_path(path);
1035 path::append(directory_entry_path, directory_entry_name_utf8.str());
1036 it.CurrentEntry = directory_entry(directory_entry_path.str());
1038 return error_code::success();
1041 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
1042 if (it.IterationHandle != 0)
1043 // Closes the handle if it's valid.
1044 ScopedFindHandle close(HANDLE(it.IterationHandle));
1045 it.IterationHandle = 0;
1046 it.CurrentEntry = directory_entry();
1047 return error_code::success();
1050 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
1051 WIN32_FIND_DATAW FindData;
1052 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
1053 error_code ec = windows_error(::GetLastError());
1055 if (ec == windows_error::no_more_files)
1056 return detail::directory_iterator_destruct(it);
1060 size_t FilenameLen = ::wcslen(FindData.cFileName);
1061 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
1062 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
1063 FindData.cFileName[1] == L'.'))
1064 return directory_iterator_increment(it);
1066 SmallString<128> directory_entry_path_utf8;
1067 if (error_code ec = UTF16ToUTF8(FindData.cFileName,
1068 ::wcslen(FindData.cFileName),
1069 directory_entry_path_utf8))
1072 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
1073 return error_code::success();
1076 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
1077 bool map_writable, void *&result) {
1078 assert(0 && "NOT IMPLEMENTED");
1079 return windows_error::invalid_function;
1082 error_code unmap_file_pages(void *base, size_t size) {
1083 assert(0 && "NOT IMPLEMENTED");
1084 return windows_error::invalid_function;
1089 } // end namespace fs
1090 } // end namespace sys
1091 } // end namespace llvm