1 //===- llvm/Support/Windows/Path.inc - Windows Path Impl --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Windows specific implementation of the Path API.
12 //===----------------------------------------------------------------------===//
14 //===----------------------------------------------------------------------===//
15 //=== WARNING: Implementation here must contain only generic Windows code that
16 //=== is guaranteed to work on *all* Windows variants.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/ADT/STLExtras.h"
23 #include <sys/types.h>
25 // The Windows.h header must be the last one included.
30 // MinGW doesn't define this.
31 #ifndef _ERRNO_T_DEFINED
32 #define _ERRNO_T_DEFINED
37 # pragma comment(lib, "advapi32.lib") // This provides CryptAcquireContextW.
42 using llvm::sys::windows::UTF8ToUTF16;
43 using llvm::sys::windows::UTF16ToUTF8;
46 typedef BOOLEAN (WINAPI *PtrCreateSymbolicLinkW)(
47 /*__in*/ LPCWSTR lpSymlinkFileName,
48 /*__in*/ LPCWSTR lpTargetFileName,
49 /*__in*/ DWORD dwFlags);
51 PtrCreateSymbolicLinkW create_symbolic_link_api =
52 PtrCreateSymbolicLinkW(::GetProcAddress(
53 ::GetModuleHandleW(L"Kernel32.dll"), "CreateSymbolicLinkW"));
55 error_code TempDir(SmallVectorImpl<wchar_t> &result) {
57 DWORD len = ::GetTempPathW(result.capacity(), result.begin());
60 return windows_error(::GetLastError());
62 if (len > result.capacity()) {
68 return error_code::success();
71 bool is_separator(const wchar_t value) {
82 // FIXME: mode should be used here and default to user r/w only,
83 // it currently comes in as a UNIX mode.
84 static error_code createUniqueEntity(const Twine &model, int &result_fd,
85 SmallVectorImpl<char> &result_path,
86 bool makeAbsolute, unsigned mode,
88 // Use result_path as temp storage.
89 result_path.set_size(0);
90 StringRef m = model.toStringRef(result_path);
92 SmallVector<wchar_t, 128> model_utf16;
93 if (error_code ec = UTF8ToUTF16(m, model_utf16)) return ec;
96 // Make model absolute by prepending a temp directory if it's not already.
97 bool absolute = sys::path::is_absolute(m);
100 SmallVector<wchar_t, 64> temp_dir;
101 if (error_code ec = TempDir(temp_dir)) return ec;
102 // Handle c: by removing it.
103 if (model_utf16.size() > 2 && model_utf16[1] == L':') {
104 model_utf16.erase(model_utf16.begin(), model_utf16.begin() + 2);
106 model_utf16.insert(model_utf16.begin(), temp_dir.begin(), temp_dir.end());
110 // Replace '%' with random chars. From here on, DO NOT modify model. It may be
111 // needed if the randomly chosen path already exists.
112 SmallVector<wchar_t, 128> random_path_utf16;
114 // Get a Crypto Provider for CryptGenRandom.
116 if (!::CryptAcquireContextW(&HCPC,
120 CRYPT_VERIFYCONTEXT))
121 return windows_error(::GetLastError());
122 ScopedCryptContext CryptoProvider(HCPC);
125 random_path_utf16.set_size(0);
126 for (SmallVectorImpl<wchar_t>::const_iterator i = model_utf16.begin(),
127 e = model_utf16.end();
131 if (!::CryptGenRandom(CryptoProvider, 1, &val))
132 return windows_error(::GetLastError());
133 random_path_utf16.push_back(L"0123456789abcdef"[val & 15]);
136 random_path_utf16.push_back(*i);
138 // Make random_path_utf16 null terminated.
139 random_path_utf16.push_back(0);
140 random_path_utf16.pop_back();
142 HANDLE TempFileHandle = INVALID_HANDLE_VALUE;
146 // Try to create + open the path.
148 ::CreateFileW(random_path_utf16.begin(), GENERIC_READ | GENERIC_WRITE,
149 FILE_SHARE_READ, NULL,
150 // Return ERROR_FILE_EXISTS if the file
152 CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY, NULL);
153 if (TempFileHandle == INVALID_HANDLE_VALUE) {
154 // If the file existed, try again, otherwise, error.
155 error_code ec = windows_error(::GetLastError());
156 if (ec == windows_error::file_exists)
157 goto retry_random_path;
162 // Convert the Windows API file handle into a C-runtime handle.
163 int fd = ::_open_osfhandle(intptr_t(TempFileHandle), 0);
165 ::CloseHandle(TempFileHandle);
166 ::DeleteFileW(random_path_utf16.begin());
167 // MSDN doesn't say anything about _open_osfhandle setting errno or
168 // GetLastError(), so just return invalid_handle.
169 return windows_error::invalid_handle;
177 DWORD attributes = ::GetFileAttributesW(random_path_utf16.begin());
178 if (attributes != INVALID_FILE_ATTRIBUTES)
179 goto retry_random_path;
180 error_code EC = make_error_code(windows_error(::GetLastError()));
181 if (EC != windows_error::file_not_found &&
182 EC != windows_error::path_not_found)
188 if (!::CreateDirectoryW(random_path_utf16.begin(), NULL)) {
189 error_code EC = windows_error(::GetLastError());
190 if (EC != windows_error::already_exists)
192 goto retry_random_path;
197 // Set result_path to the utf-8 representation of the path.
198 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
199 random_path_utf16.size(), result_path)) {
202 ::CloseHandle(TempFileHandle);
203 ::DeleteFileW(random_path_utf16.begin());
207 ::RemoveDirectoryW(random_path_utf16.begin());
213 return error_code::success();
220 std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
221 SmallVector<wchar_t, MAX_PATH> PathName;
222 DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
224 // A zero return value indicates a failure other than insufficient space.
228 // Insufficient space is determined by a return value equal to the size of
229 // the buffer passed in.
230 if (Size == PathName.capacity())
233 // On success, GetModuleFileNameW returns the number of characters written to
234 // the buffer not including the NULL terminator.
235 PathName.set_size(Size);
237 // Convert the result from UTF-16 to UTF-8.
238 SmallVector<char, MAX_PATH> PathNameUTF8;
239 if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
242 return std::string(PathNameUTF8.data());
245 UniqueID file_status::getUniqueID() const {
246 // The file is uniquely identified by the volume serial number along
247 // with the 64-bit file identifier.
248 uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
249 static_cast<uint64_t>(FileIndexLow);
251 return UniqueID(VolumeSerialNumber, FileID);
254 TimeValue file_status::getLastModificationTime() const {
256 UI.LowPart = LastWriteTimeLow;
257 UI.HighPart = LastWriteTimeHigh;
260 Ret.fromWin32Time(UI.QuadPart);
264 error_code current_path(SmallVectorImpl<char> &result) {
265 SmallVector<wchar_t, MAX_PATH> cur_path;
266 DWORD len = MAX_PATH;
269 cur_path.reserve(len);
270 len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
272 // A zero return value indicates a failure other than insufficient space.
274 return windows_error(::GetLastError());
276 // If there's insufficient space, the len returned is larger than the len
278 } while (len > cur_path.capacity());
280 // On success, GetCurrentDirectoryW returns the number of characters not
281 // including the null-terminator.
282 cur_path.set_size(len);
283 return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
286 error_code create_directory(const Twine &path, bool &existed) {
287 SmallString<128> path_storage;
288 SmallVector<wchar_t, 128> path_utf16;
290 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
294 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
295 error_code ec = windows_error(::GetLastError());
296 if (ec == windows_error::already_exists)
303 return error_code::success();
306 error_code create_hard_link(const Twine &to, const Twine &from) {
308 SmallString<128> from_storage;
309 SmallString<128> to_storage;
310 StringRef f = from.toStringRef(from_storage);
311 StringRef t = to.toStringRef(to_storage);
313 // Convert to utf-16.
314 SmallVector<wchar_t, 128> wide_from;
315 SmallVector<wchar_t, 128> wide_to;
316 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
317 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
319 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
320 return windows_error(::GetLastError());
322 return error_code::success();
325 error_code create_symlink(const Twine &to, const Twine &from) {
326 // Only do it if the function is available at runtime.
327 if (!create_symbolic_link_api)
328 return make_error_code(errc::function_not_supported);
331 SmallString<128> from_storage;
332 SmallString<128> to_storage;
333 StringRef f = from.toStringRef(from_storage);
334 StringRef t = to.toStringRef(to_storage);
336 // Convert to utf-16.
337 SmallVector<wchar_t, 128> wide_from;
338 SmallVector<wchar_t, 128> wide_to;
339 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
340 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
342 if (!create_symbolic_link_api(wide_from.begin(), wide_to.begin(), 0))
343 return windows_error(::GetLastError());
345 return error_code::success();
348 error_code remove(const Twine &path, bool &existed) {
349 SmallString<128> path_storage;
350 SmallVector<wchar_t, 128> path_utf16;
353 error_code EC = status(path, st);
355 if (EC == windows_error::file_not_found ||
356 EC == windows_error::path_not_found) {
358 return error_code::success();
363 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
367 if (st.type() == file_type::directory_file) {
368 if (!::RemoveDirectoryW(c_str(path_utf16))) {
369 error_code ec = windows_error(::GetLastError());
370 if (ec != windows_error::file_not_found)
376 if (!::DeleteFileW(c_str(path_utf16))) {
377 error_code ec = windows_error(::GetLastError());
378 if (ec != windows_error::file_not_found)
385 return error_code::success();
388 error_code rename(const Twine &from, const Twine &to) {
390 SmallString<128> from_storage;
391 SmallString<128> to_storage;
392 StringRef f = from.toStringRef(from_storage);
393 StringRef t = to.toStringRef(to_storage);
395 // Convert to utf-16.
396 SmallVector<wchar_t, 128> wide_from;
397 SmallVector<wchar_t, 128> wide_to;
398 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
399 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
401 error_code ec = error_code::success();
402 for (int i = 0; i < 2000; i++) {
403 if (::MoveFileExW(wide_from.begin(), wide_to.begin(),
404 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
405 return error_code::success();
406 ec = windows_error(::GetLastError());
407 if (ec != windows_error::access_denied)
409 // Retry MoveFile() at ACCESS_DENIED.
410 // System scanners (eg. indexer) might open the source file when
411 // It is written and closed.
418 error_code resize_file(const Twine &path, uint64_t size) {
419 SmallString<128> path_storage;
420 SmallVector<wchar_t, 128> path_utf16;
422 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
426 int fd = ::_wopen(path_utf16.begin(), O_BINARY | _O_RDWR, S_IWRITE);
428 return error_code(errno, generic_category());
429 #ifdef HAVE__CHSIZE_S
430 errno_t error = ::_chsize_s(fd, size);
432 errno_t error = ::_chsize(fd, size);
435 return error_code(error, generic_category());
438 error_code exists(const Twine &path, bool &result) {
439 SmallString<128> path_storage;
440 SmallVector<wchar_t, 128> path_utf16;
442 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
446 DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
448 if (attributes == INVALID_FILE_ATTRIBUTES) {
449 // See if the file didn't actually exist.
450 error_code ec = make_error_code(windows_error(::GetLastError()));
451 if (ec != windows_error::file_not_found &&
452 ec != windows_error::path_not_found)
457 return error_code::success();
460 bool can_write(const Twine &Path) {
461 // FIXME: take security attributes into account.
462 SmallString<128> PathStorage;
463 SmallVector<wchar_t, 128> PathUtf16;
465 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
468 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
469 return (Attr != INVALID_FILE_ATTRIBUTES) && !(Attr & FILE_ATTRIBUTE_READONLY);
472 bool can_execute(const Twine &Path) {
473 SmallString<128> PathStorage;
474 SmallVector<wchar_t, 128> PathUtf16;
476 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
479 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
480 return Attr != INVALID_FILE_ATTRIBUTES;
483 bool equivalent(file_status A, file_status B) {
484 assert(status_known(A) && status_known(B));
485 return A.FileIndexHigh == B.FileIndexHigh &&
486 A.FileIndexLow == B.FileIndexLow &&
487 A.FileSizeHigh == B.FileSizeHigh &&
488 A.FileSizeLow == B.FileSizeLow &&
489 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
490 A.LastWriteTimeLow == B.LastWriteTimeLow &&
491 A.VolumeSerialNumber == B.VolumeSerialNumber;
494 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
495 file_status fsA, fsB;
496 if (error_code ec = status(A, fsA)) return ec;
497 if (error_code ec = status(B, fsB)) return ec;
498 result = equivalent(fsA, fsB);
499 return error_code::success();
502 static bool isReservedName(StringRef path) {
503 // This list of reserved names comes from MSDN, at:
504 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
505 static const char *sReservedNames[] = { "nul", "con", "prn", "aux",
506 "com1", "com2", "com3", "com4", "com5", "com6",
507 "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
508 "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9" };
510 // First, check to see if this is a device namespace, which always
511 // starts with \\.\, since device namespaces are not legal file paths.
512 if (path.startswith("\\\\.\\"))
515 // Then compare against the list of ancient reserved names
516 for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
517 if (path.equals_lower(sReservedNames[i]))
521 // The path isn't what we consider reserved.
525 static error_code getStatus(HANDLE FileHandle, file_status &Result) {
526 if (FileHandle == INVALID_HANDLE_VALUE)
527 goto handle_status_error;
529 switch (::GetFileType(FileHandle)) {
531 llvm_unreachable("Don't know anything about this file type");
532 case FILE_TYPE_UNKNOWN: {
533 DWORD Err = ::GetLastError();
535 return windows_error(Err);
536 Result = file_status(file_type::type_unknown);
537 return error_code::success();
542 Result = file_status(file_type::character_file);
543 return error_code::success();
545 Result = file_status(file_type::fifo_file);
546 return error_code::success();
549 BY_HANDLE_FILE_INFORMATION Info;
550 if (!::GetFileInformationByHandle(FileHandle, &Info))
551 goto handle_status_error;
554 file_type Type = (Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
555 ? file_type::directory_file
556 : file_type::regular_file;
558 file_status(Type, Info.ftLastWriteTime.dwHighDateTime,
559 Info.ftLastWriteTime.dwLowDateTime,
560 Info.dwVolumeSerialNumber, Info.nFileSizeHigh,
561 Info.nFileSizeLow, Info.nFileIndexHigh, Info.nFileIndexLow);
562 return error_code::success();
566 error_code EC = windows_error(::GetLastError());
567 if (EC == windows_error::file_not_found ||
568 EC == windows_error::path_not_found)
569 Result = file_status(file_type::file_not_found);
570 else if (EC == windows_error::sharing_violation)
571 Result = file_status(file_type::type_unknown);
573 Result = file_status(file_type::status_error);
577 error_code status(const Twine &path, file_status &result) {
578 SmallString<128> path_storage;
579 SmallVector<wchar_t, 128> path_utf16;
581 StringRef path8 = path.toStringRef(path_storage);
582 if (isReservedName(path8)) {
583 result = file_status(file_type::character_file);
584 return error_code::success();
587 if (error_code ec = UTF8ToUTF16(path8, path_utf16))
590 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
591 if (attr == INVALID_FILE_ATTRIBUTES)
592 return getStatus(INVALID_HANDLE_VALUE, result);
594 // Handle reparse points.
595 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
597 ::CreateFileW(path_utf16.begin(),
598 0, // Attributes only.
599 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
602 FILE_FLAG_BACKUP_SEMANTICS,
605 return getStatus(INVALID_HANDLE_VALUE, result);
609 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
610 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
611 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0));
613 return getStatus(INVALID_HANDLE_VALUE, result);
615 return getStatus(h, result);
618 error_code status(int FD, file_status &Result) {
619 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
620 return getStatus(FileHandle, Result);
623 error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
625 UI.QuadPart = Time.toWin32Time();
627 FT.dwLowDateTime = UI.LowPart;
628 FT.dwHighDateTime = UI.HighPart;
629 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
630 if (!SetFileTime(FileHandle, NULL, &FT, &FT))
631 return windows_error(::GetLastError());
632 return error_code::success();
635 error_code get_magic(const Twine &path, uint32_t len,
636 SmallVectorImpl<char> &result) {
637 SmallString<128> path_storage;
638 SmallVector<wchar_t, 128> path_utf16;
641 // Convert path to UTF-16.
642 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
647 HANDLE file = ::CreateFileW(c_str(path_utf16),
652 FILE_ATTRIBUTE_READONLY,
654 if (file == INVALID_HANDLE_VALUE)
655 return windows_error(::GetLastError());
661 DWORD bytes_read = 0;
662 BOOL read_success = ::ReadFile(file, result.data(), len, &bytes_read, NULL);
663 error_code ec = windows_error(::GetLastError());
665 if (!read_success || (bytes_read != len)) {
666 // Set result size to the number of bytes read if it's valid.
667 if (bytes_read <= len)
668 result.set_size(bytes_read);
669 // ERROR_HANDLE_EOF is mapped to errc::value_too_large.
673 result.set_size(len);
674 return error_code::success();
677 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
679 // Make sure that the requested size fits within SIZE_T.
680 if (Size > std::numeric_limits<SIZE_T>::max()) {
681 if (FileDescriptor) {
683 _close(FileDescriptor);
685 ::CloseHandle(FileHandle);
686 return make_error_code(errc::invalid_argument);
691 case readonly: flprotect = PAGE_READONLY; break;
692 case readwrite: flprotect = PAGE_READWRITE; break;
693 case priv: flprotect = PAGE_WRITECOPY; break;
697 ::CreateFileMappingW(FileHandle, 0, flprotect,
698 (Offset + Size) >> 32,
699 (Offset + Size) & 0xffffffff,
701 if (FileMappingHandle == NULL) {
702 error_code ec = windows_error(GetLastError());
703 if (FileDescriptor) {
705 _close(FileDescriptor);
707 ::CloseHandle(FileHandle);
711 DWORD dwDesiredAccess;
713 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
714 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
715 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
717 Mapping = ::MapViewOfFile(FileMappingHandle,
722 if (Mapping == NULL) {
723 error_code ec = windows_error(GetLastError());
724 ::CloseHandle(FileMappingHandle);
725 if (FileDescriptor) {
727 _close(FileDescriptor);
729 ::CloseHandle(FileHandle);
734 MEMORY_BASIC_INFORMATION mbi;
735 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
737 error_code ec = windows_error(GetLastError());
738 ::UnmapViewOfFile(Mapping);
739 ::CloseHandle(FileMappingHandle);
740 if (FileDescriptor) {
742 _close(FileDescriptor);
744 ::CloseHandle(FileHandle);
747 Size = mbi.RegionSize;
750 // Close all the handles except for the view. It will keep the other handles
752 ::CloseHandle(FileMappingHandle);
753 if (FileDescriptor) {
755 _close(FileDescriptor); // Also closes FileHandle.
757 ::CloseHandle(FileHandle);
758 return error_code::success();
761 mapped_file_region::mapped_file_region(const Twine &path,
770 , FileHandle(INVALID_HANDLE_VALUE)
771 , FileMappingHandle() {
772 SmallString<128> path_storage;
773 SmallVector<wchar_t, 128> path_utf16;
775 // Convert path to UTF-16.
776 if ((ec = UTF8ToUTF16(path.toStringRef(path_storage), path_utf16)))
779 // Get file handle for creating a file mapping.
780 FileHandle = ::CreateFileW(c_str(path_utf16),
781 Mode == readonly ? GENERIC_READ
782 : GENERIC_READ | GENERIC_WRITE,
783 Mode == readonly ? FILE_SHARE_READ
786 Mode == readonly ? OPEN_EXISTING
788 Mode == readonly ? FILE_ATTRIBUTE_READONLY
789 : FILE_ATTRIBUTE_NORMAL,
791 if (FileHandle == INVALID_HANDLE_VALUE) {
792 ec = windows_error(::GetLastError());
797 ec = init(FileDescriptor, true, offset);
799 Mapping = FileMappingHandle = 0;
800 FileHandle = INVALID_HANDLE_VALUE;
805 mapped_file_region::mapped_file_region(int fd,
815 , FileHandle(INVALID_HANDLE_VALUE)
816 , FileMappingHandle() {
817 FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
818 if (FileHandle == INVALID_HANDLE_VALUE) {
820 _close(FileDescriptor);
822 ec = make_error_code(errc::bad_file_descriptor);
826 ec = init(FileDescriptor, closefd, offset);
828 Mapping = FileMappingHandle = 0;
829 FileHandle = INVALID_HANDLE_VALUE;
834 mapped_file_region::~mapped_file_region() {
836 ::UnmapViewOfFile(Mapping);
839 #if LLVM_HAS_RVALUE_REFERENCES
840 mapped_file_region::mapped_file_region(mapped_file_region &&other)
843 , Mapping(other.Mapping)
844 , FileDescriptor(other.FileDescriptor)
845 , FileHandle(other.FileHandle)
846 , FileMappingHandle(other.FileMappingHandle) {
847 other.Mapping = other.FileMappingHandle = 0;
848 other.FileHandle = INVALID_HANDLE_VALUE;
849 other.FileDescriptor = 0;
853 mapped_file_region::mapmode mapped_file_region::flags() const {
854 assert(Mapping && "Mapping failed but used anyway!");
858 uint64_t mapped_file_region::size() const {
859 assert(Mapping && "Mapping failed but used anyway!");
863 char *mapped_file_region::data() const {
864 assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
865 assert(Mapping && "Mapping failed but used anyway!");
866 return reinterpret_cast<char*>(Mapping);
869 const char *mapped_file_region::const_data() const {
870 assert(Mapping && "Mapping failed but used anyway!");
871 return reinterpret_cast<const char*>(Mapping);
874 int mapped_file_region::alignment() {
876 ::GetSystemInfo(&SysInfo);
877 return SysInfo.dwAllocationGranularity;
880 error_code detail::directory_iterator_construct(detail::DirIterState &it,
882 SmallVector<wchar_t, 128> path_utf16;
884 if (error_code ec = UTF8ToUTF16(path,
888 // Convert path to the format that Windows is happy with.
889 if (path_utf16.size() > 0 &&
890 !is_separator(path_utf16[path.size() - 1]) &&
891 path_utf16[path.size() - 1] != L':') {
892 path_utf16.push_back(L'\\');
893 path_utf16.push_back(L'*');
895 path_utf16.push_back(L'*');
898 // Get the first directory entry.
899 WIN32_FIND_DATAW FirstFind;
900 ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
902 return windows_error(::GetLastError());
904 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
905 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
906 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
907 FirstFind.cFileName[1] == L'.'))
908 if (!::FindNextFileW(FindHandle, &FirstFind)) {
909 error_code ec = windows_error(::GetLastError());
911 if (ec == windows_error::no_more_files)
912 return detail::directory_iterator_destruct(it);
915 FilenameLen = ::wcslen(FirstFind.cFileName);
917 // Construct the current directory entry.
918 SmallString<128> directory_entry_name_utf8;
919 if (error_code ec = UTF16ToUTF8(FirstFind.cFileName,
920 ::wcslen(FirstFind.cFileName),
921 directory_entry_name_utf8))
924 it.IterationHandle = intptr_t(FindHandle.take());
925 SmallString<128> directory_entry_path(path);
926 path::append(directory_entry_path, directory_entry_name_utf8.str());
927 it.CurrentEntry = directory_entry(directory_entry_path.str());
929 return error_code::success();
932 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
933 if (it.IterationHandle != 0)
934 // Closes the handle if it's valid.
935 ScopedFindHandle close(HANDLE(it.IterationHandle));
936 it.IterationHandle = 0;
937 it.CurrentEntry = directory_entry();
938 return error_code::success();
941 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
942 WIN32_FIND_DATAW FindData;
943 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
944 error_code ec = windows_error(::GetLastError());
946 if (ec == windows_error::no_more_files)
947 return detail::directory_iterator_destruct(it);
951 size_t FilenameLen = ::wcslen(FindData.cFileName);
952 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
953 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
954 FindData.cFileName[1] == L'.'))
955 return directory_iterator_increment(it);
957 SmallString<128> directory_entry_path_utf8;
958 if (error_code ec = UTF16ToUTF8(FindData.cFileName,
959 ::wcslen(FindData.cFileName),
960 directory_entry_path_utf8))
963 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
964 return error_code::success();
967 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
968 bool map_writable, void *&result) {
969 assert(0 && "NOT IMPLEMENTED");
970 return windows_error::invalid_function;
973 error_code unmap_file_pages(void *base, size_t size) {
974 assert(0 && "NOT IMPLEMENTED");
975 return windows_error::invalid_function;
978 error_code openFileForRead(const Twine &Name, int &ResultFD) {
979 SmallString<128> PathStorage;
980 SmallVector<wchar_t, 128> PathUTF16;
982 if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
986 HANDLE H = ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
987 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
988 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
989 if (H == INVALID_HANDLE_VALUE) {
990 error_code EC = windows_error(::GetLastError());
991 // Provide a better error message when trying to open directories.
992 // This only runs if we failed to open the file, so there is probably
993 // no performances issues.
994 if (EC != windows_error::access_denied)
996 if (is_directory(Name))
997 return error_code(errc::is_a_directory, posix_category());
1001 int FD = ::_open_osfhandle(intptr_t(H), 0);
1004 return windows_error::invalid_handle;
1008 return error_code::success();
1011 error_code openFileForWrite(const Twine &Name, int &ResultFD,
1012 sys::fs::OpenFlags Flags, unsigned Mode) {
1013 // Verify that we don't have both "append" and "excl".
1014 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
1015 "Cannot specify both 'excl' and 'append' file creation flags!");
1017 SmallString<128> PathStorage;
1018 SmallVector<wchar_t, 128> PathUTF16;
1020 if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
1024 DWORD CreationDisposition;
1026 CreationDisposition = CREATE_NEW;
1027 else if (Flags & F_Append)
1028 CreationDisposition = OPEN_ALWAYS;
1030 CreationDisposition = CREATE_ALWAYS;
1032 HANDLE H = ::CreateFileW(PathUTF16.begin(), GENERIC_WRITE,
1033 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1034 CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
1036 if (H == INVALID_HANDLE_VALUE) {
1037 error_code EC = windows_error(::GetLastError());
1038 // Provide a better error message when trying to open directories.
1039 // This only runs if we failed to open the file, so there is probably
1040 // no performances issues.
1041 if (EC != windows_error::access_denied)
1043 if (is_directory(Name))
1044 return error_code(errc::is_a_directory, posix_category());
1049 if (Flags & F_Append)
1050 OpenFlags |= _O_APPEND;
1052 if (!(Flags & F_Binary))
1053 OpenFlags |= _O_TEXT;
1055 int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
1058 return windows_error::invalid_handle;
1062 return error_code::success();
1064 } // end namespace fs
1067 llvm::error_code UTF8ToUTF16(llvm::StringRef utf8,
1068 llvm::SmallVectorImpl<wchar_t> &utf16) {
1069 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
1070 utf8.begin(), utf8.size(),
1074 return llvm::windows_error(::GetLastError());
1076 utf16.reserve(len + 1);
1077 utf16.set_size(len);
1079 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
1080 utf8.begin(), utf8.size(),
1081 utf16.begin(), utf16.size());
1084 return llvm::windows_error(::GetLastError());
1086 // Make utf16 null terminated.
1090 return llvm::error_code::success();
1093 llvm::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
1094 llvm::SmallVectorImpl<char> &utf8) {
1096 int len = ::WideCharToMultiByte(CP_UTF8, 0,
1102 return llvm::windows_error(::GetLastError());
1107 // Now do the actual conversion.
1108 len = ::WideCharToMultiByte(CP_UTF8, 0,
1110 utf8.data(), utf8.size(),
1114 return llvm::windows_error(::GetLastError());
1116 // Make utf8 null terminated.
1120 return llvm::error_code::success();
1122 } // end namespace windows
1123 } // end namespace sys
1124 } // end namespace llvm