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>
26 // The Windows.h header must be the last one included.
31 // MinGW doesn't define this.
32 #ifndef _ERRNO_T_DEFINED
33 #define _ERRNO_T_DEFINED
38 # pragma comment(lib, "advapi32.lib") // This provides CryptAcquireContextW.
43 using llvm::sys::windows::UTF8ToUTF16;
44 using llvm::sys::windows::UTF16ToUTF8;
47 typedef BOOLEAN (WINAPI *PtrCreateSymbolicLinkW)(
48 /*__in*/ LPCWSTR lpSymlinkFileName,
49 /*__in*/ LPCWSTR lpTargetFileName,
50 /*__in*/ DWORD dwFlags);
52 PtrCreateSymbolicLinkW create_symbolic_link_api =
53 PtrCreateSymbolicLinkW(::GetProcAddress(
54 ::GetModuleHandleW(L"Kernel32.dll"), "CreateSymbolicLinkW"));
56 error_code TempDir(SmallVectorImpl<wchar_t> &result) {
58 DWORD len = ::GetTempPathW(result.capacity(), result.begin());
61 return windows_error(::GetLastError());
63 if (len > result.capacity()) {
69 return error_code::success();
72 bool is_separator(const wchar_t value) {
83 // FIXME: mode should be used here and default to user r/w only,
84 // it currently comes in as a UNIX mode.
85 static error_code createUniqueEntity(const Twine &model, int &result_fd,
86 SmallVectorImpl<char> &result_path,
87 bool makeAbsolute, unsigned mode,
89 // Use result_path as temp storage.
90 result_path.set_size(0);
91 StringRef m = model.toStringRef(result_path);
93 SmallVector<wchar_t, 128> model_utf16;
94 if (error_code ec = UTF8ToUTF16(m, model_utf16)) return ec;
97 // Make model absolute by prepending a temp directory if it's not already.
98 bool absolute = sys::path::is_absolute(m);
101 SmallVector<wchar_t, 64> temp_dir;
102 if (error_code ec = TempDir(temp_dir)) return ec;
103 // Handle c: by removing it.
104 if (model_utf16.size() > 2 && model_utf16[1] == L':') {
105 model_utf16.erase(model_utf16.begin(), model_utf16.begin() + 2);
107 model_utf16.insert(model_utf16.begin(), temp_dir.begin(), temp_dir.end());
111 // Replace '%' with random chars. From here on, DO NOT modify model. It may be
112 // needed if the randomly chosen path already exists.
113 SmallVector<wchar_t, 128> random_path_utf16;
115 // Get a Crypto Provider for CryptGenRandom.
117 if (!::CryptAcquireContextW(&HCPC,
121 CRYPT_VERIFYCONTEXT))
122 return windows_error(::GetLastError());
123 ScopedCryptContext CryptoProvider(HCPC);
126 random_path_utf16.set_size(0);
127 for (SmallVectorImpl<wchar_t>::const_iterator i = model_utf16.begin(),
128 e = model_utf16.end();
132 if (!::CryptGenRandom(CryptoProvider, 1, &val))
133 return windows_error(::GetLastError());
134 random_path_utf16.push_back(L"0123456789abcdef"[val & 15]);
137 random_path_utf16.push_back(*i);
139 // Make random_path_utf16 null terminated.
140 random_path_utf16.push_back(0);
141 random_path_utf16.pop_back();
143 HANDLE TempFileHandle = INVALID_HANDLE_VALUE;
147 // Try to create + open the path.
149 ::CreateFileW(random_path_utf16.begin(), GENERIC_READ | GENERIC_WRITE,
150 FILE_SHARE_READ, NULL,
151 // Return ERROR_FILE_EXISTS if the file
153 CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY, NULL);
154 if (TempFileHandle == INVALID_HANDLE_VALUE) {
155 // If the file existed, try again, otherwise, error.
156 error_code ec = windows_error(::GetLastError());
157 if (ec == windows_error::file_exists)
158 goto retry_random_path;
163 // Convert the Windows API file handle into a C-runtime handle.
164 int fd = ::_open_osfhandle(intptr_t(TempFileHandle), 0);
166 ::CloseHandle(TempFileHandle);
167 ::DeleteFileW(random_path_utf16.begin());
168 // MSDN doesn't say anything about _open_osfhandle setting errno or
169 // GetLastError(), so just return invalid_handle.
170 return windows_error::invalid_handle;
178 DWORD attributes = ::GetFileAttributesW(random_path_utf16.begin());
179 if (attributes != INVALID_FILE_ATTRIBUTES)
180 goto retry_random_path;
181 error_code EC = make_error_code(windows_error(::GetLastError()));
182 if (EC != windows_error::file_not_found &&
183 EC != windows_error::path_not_found)
189 if (!::CreateDirectoryW(random_path_utf16.begin(), NULL)) {
190 error_code EC = windows_error(::GetLastError());
191 if (EC != windows_error::already_exists)
193 goto retry_random_path;
198 // Set result_path to the utf-8 representation of the path.
199 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
200 random_path_utf16.size(), result_path)) {
203 ::CloseHandle(TempFileHandle);
204 ::DeleteFileW(random_path_utf16.begin());
208 ::RemoveDirectoryW(random_path_utf16.begin());
214 return error_code::success();
221 std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
222 SmallVector<wchar_t, MAX_PATH> PathName;
223 DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
225 // A zero return value indicates a failure other than insufficient space.
229 // Insufficient space is determined by a return value equal to the size of
230 // the buffer passed in.
231 if (Size == PathName.capacity())
234 // On success, GetModuleFileNameW returns the number of characters written to
235 // the buffer not including the NULL terminator.
236 PathName.set_size(Size);
238 // Convert the result from UTF-16 to UTF-8.
239 SmallVector<char, MAX_PATH> PathNameUTF8;
240 if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
243 return std::string(PathNameUTF8.data());
246 UniqueID file_status::getUniqueID() const {
247 // The file is uniquely identified by the volume serial number along
248 // with the 64-bit file identifier.
249 uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
250 static_cast<uint64_t>(FileIndexLow);
252 return UniqueID(VolumeSerialNumber, FileID);
255 TimeValue file_status::getLastModificationTime() const {
257 UI.LowPart = LastWriteTimeLow;
258 UI.HighPart = LastWriteTimeHigh;
261 Ret.fromWin32Time(UI.QuadPart);
265 error_code current_path(SmallVectorImpl<char> &result) {
266 SmallVector<wchar_t, MAX_PATH> cur_path;
267 DWORD len = MAX_PATH;
270 cur_path.reserve(len);
271 len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
273 // A zero return value indicates a failure other than insufficient space.
275 return windows_error(::GetLastError());
277 // If there's insufficient space, the len returned is larger than the len
279 } while (len > cur_path.capacity());
281 // On success, GetCurrentDirectoryW returns the number of characters not
282 // including the null-terminator.
283 cur_path.set_size(len);
284 return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
287 error_code create_directory(const Twine &path, bool &existed) {
288 SmallString<128> path_storage;
289 SmallVector<wchar_t, 128> path_utf16;
291 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
295 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
296 error_code ec = windows_error(::GetLastError());
297 if (ec == windows_error::already_exists)
304 return error_code::success();
307 error_code create_hard_link(const Twine &to, const Twine &from) {
309 SmallString<128> from_storage;
310 SmallString<128> to_storage;
311 StringRef f = from.toStringRef(from_storage);
312 StringRef t = to.toStringRef(to_storage);
314 // Convert to utf-16.
315 SmallVector<wchar_t, 128> wide_from;
316 SmallVector<wchar_t, 128> wide_to;
317 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
318 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
320 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
321 return windows_error(::GetLastError());
323 return error_code::success();
326 error_code create_symlink(const Twine &to, const Twine &from) {
327 // Only do it if the function is available at runtime.
328 if (!create_symbolic_link_api)
329 return make_error_code(errc::function_not_supported);
332 SmallString<128> from_storage;
333 SmallString<128> to_storage;
334 StringRef f = from.toStringRef(from_storage);
335 StringRef t = to.toStringRef(to_storage);
337 // Convert to utf-16.
338 SmallVector<wchar_t, 128> wide_from;
339 SmallVector<wchar_t, 128> wide_to;
340 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
341 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
343 if (!create_symbolic_link_api(wide_from.begin(), wide_to.begin(), 0))
344 return windows_error(::GetLastError());
346 return error_code::success();
349 error_code remove(const Twine &path, bool &existed) {
350 SmallString<128> path_storage;
351 SmallVector<wchar_t, 128> path_utf16;
354 error_code EC = status(path, st);
356 if (EC == windows_error::file_not_found ||
357 EC == windows_error::path_not_found) {
359 return error_code::success();
364 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
368 if (st.type() == file_type::directory_file) {
369 if (!::RemoveDirectoryW(c_str(path_utf16))) {
370 error_code ec = windows_error(::GetLastError());
371 if (ec != windows_error::file_not_found)
377 if (!::DeleteFileW(c_str(path_utf16))) {
378 error_code ec = windows_error(::GetLastError());
379 if (ec != windows_error::file_not_found)
386 return error_code::success();
389 error_code rename(const Twine &from, const Twine &to) {
391 SmallString<128> from_storage;
392 SmallString<128> to_storage;
393 StringRef f = from.toStringRef(from_storage);
394 StringRef t = to.toStringRef(to_storage);
396 // Convert to utf-16.
397 SmallVector<wchar_t, 128> wide_from;
398 SmallVector<wchar_t, 128> wide_to;
399 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
400 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
402 error_code ec = error_code::success();
403 for (int i = 0; i < 2000; i++) {
404 if (::MoveFileExW(wide_from.begin(), wide_to.begin(),
405 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
406 return error_code::success();
407 ec = windows_error(::GetLastError());
408 if (ec != windows_error::access_denied)
410 // Retry MoveFile() at ACCESS_DENIED.
411 // System scanners (eg. indexer) might open the source file when
412 // It is written and closed.
419 error_code resize_file(const Twine &path, uint64_t size) {
420 SmallString<128> path_storage;
421 SmallVector<wchar_t, 128> path_utf16;
423 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
427 int fd = ::_wopen(path_utf16.begin(), O_BINARY | _O_RDWR, S_IWRITE);
429 return error_code(errno, generic_category());
430 #ifdef HAVE__CHSIZE_S
431 errno_t error = ::_chsize_s(fd, size);
433 errno_t error = ::_chsize(fd, size);
436 return error_code(error, generic_category());
439 error_code exists(const Twine &path, bool &result) {
440 SmallString<128> path_storage;
441 SmallVector<wchar_t, 128> path_utf16;
443 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
447 DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
449 if (attributes == INVALID_FILE_ATTRIBUTES) {
450 // See if the file didn't actually exist.
451 error_code ec = make_error_code(windows_error(::GetLastError()));
452 if (ec != windows_error::file_not_found &&
453 ec != windows_error::path_not_found)
458 return error_code::success();
461 bool can_write(const Twine &Path) {
462 // FIXME: take security attributes into account.
463 SmallString<128> PathStorage;
464 SmallVector<wchar_t, 128> PathUtf16;
466 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
469 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
470 return (Attr != INVALID_FILE_ATTRIBUTES) && !(Attr & FILE_ATTRIBUTE_READONLY);
473 bool can_execute(const Twine &Path) {
474 SmallString<128> PathStorage;
475 SmallVector<wchar_t, 128> PathUtf16;
477 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
480 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
481 return Attr != INVALID_FILE_ATTRIBUTES;
484 bool equivalent(file_status A, file_status B) {
485 assert(status_known(A) && status_known(B));
486 return A.FileIndexHigh == B.FileIndexHigh &&
487 A.FileIndexLow == B.FileIndexLow &&
488 A.FileSizeHigh == B.FileSizeHigh &&
489 A.FileSizeLow == B.FileSizeLow &&
490 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
491 A.LastWriteTimeLow == B.LastWriteTimeLow &&
492 A.VolumeSerialNumber == B.VolumeSerialNumber;
495 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
496 file_status fsA, fsB;
497 if (error_code ec = status(A, fsA)) return ec;
498 if (error_code ec = status(B, fsB)) return ec;
499 result = equivalent(fsA, fsB);
500 return error_code::success();
503 static bool isReservedName(StringRef path) {
504 // This list of reserved names comes from MSDN, at:
505 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
506 static const char *sReservedNames[] = { "nul", "con", "prn", "aux",
507 "com1", "com2", "com3", "com4", "com5", "com6",
508 "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
509 "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9" };
511 // First, check to see if this is a device namespace, which always
512 // starts with \\.\, since device namespaces are not legal file paths.
513 if (path.startswith("\\\\.\\"))
516 // Then compare against the list of ancient reserved names
517 for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
518 if (path.equals_lower(sReservedNames[i]))
522 // The path isn't what we consider reserved.
526 static error_code getStatus(HANDLE FileHandle, file_status &Result) {
527 if (FileHandle == INVALID_HANDLE_VALUE)
528 goto handle_status_error;
530 switch (::GetFileType(FileHandle)) {
532 llvm_unreachable("Don't know anything about this file type");
533 case FILE_TYPE_UNKNOWN: {
534 DWORD Err = ::GetLastError();
536 return windows_error(Err);
537 Result = file_status(file_type::type_unknown);
538 return error_code::success();
543 Result = file_status(file_type::character_file);
544 return error_code::success();
546 Result = file_status(file_type::fifo_file);
547 return error_code::success();
550 BY_HANDLE_FILE_INFORMATION Info;
551 if (!::GetFileInformationByHandle(FileHandle, &Info))
552 goto handle_status_error;
555 file_type Type = (Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
556 ? file_type::directory_file
557 : file_type::regular_file;
559 file_status(Type, Info.ftLastWriteTime.dwHighDateTime,
560 Info.ftLastWriteTime.dwLowDateTime,
561 Info.dwVolumeSerialNumber, Info.nFileSizeHigh,
562 Info.nFileSizeLow, Info.nFileIndexHigh, Info.nFileIndexLow);
563 return error_code::success();
567 error_code EC = windows_error(::GetLastError());
568 if (EC == windows_error::file_not_found ||
569 EC == windows_error::path_not_found)
570 Result = file_status(file_type::file_not_found);
571 else if (EC == windows_error::sharing_violation)
572 Result = file_status(file_type::type_unknown);
574 Result = file_status(file_type::status_error);
578 error_code status(const Twine &path, file_status &result) {
579 SmallString<128> path_storage;
580 SmallVector<wchar_t, 128> path_utf16;
582 StringRef path8 = path.toStringRef(path_storage);
583 if (isReservedName(path8)) {
584 result = file_status(file_type::character_file);
585 return error_code::success();
588 if (error_code ec = UTF8ToUTF16(path8, path_utf16))
591 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
592 if (attr == INVALID_FILE_ATTRIBUTES)
593 return getStatus(INVALID_HANDLE_VALUE, result);
595 // Handle reparse points.
596 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
598 ::CreateFileW(path_utf16.begin(),
599 0, // Attributes only.
600 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
603 FILE_FLAG_BACKUP_SEMANTICS,
606 return getStatus(INVALID_HANDLE_VALUE, result);
610 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
611 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
612 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0));
614 return getStatus(INVALID_HANDLE_VALUE, result);
616 return getStatus(h, result);
619 error_code status(int FD, file_status &Result) {
620 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
621 return getStatus(FileHandle, Result);
624 error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
626 UI.QuadPart = Time.toWin32Time();
628 FT.dwLowDateTime = UI.LowPart;
629 FT.dwHighDateTime = UI.HighPart;
630 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
631 if (!SetFileTime(FileHandle, NULL, &FT, &FT))
632 return windows_error(::GetLastError());
633 return error_code::success();
636 error_code get_magic(const Twine &path, uint32_t len,
637 SmallVectorImpl<char> &result) {
638 SmallString<128> path_storage;
639 SmallVector<wchar_t, 128> path_utf16;
642 // Convert path to UTF-16.
643 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
648 HANDLE file = ::CreateFileW(c_str(path_utf16),
653 FILE_ATTRIBUTE_READONLY,
655 if (file == INVALID_HANDLE_VALUE)
656 return windows_error(::GetLastError());
662 DWORD bytes_read = 0;
663 BOOL read_success = ::ReadFile(file, result.data(), len, &bytes_read, NULL);
664 error_code ec = windows_error(::GetLastError());
666 if (!read_success || (bytes_read != len)) {
667 // Set result size to the number of bytes read if it's valid.
668 if (bytes_read <= len)
669 result.set_size(bytes_read);
670 // ERROR_HANDLE_EOF is mapped to errc::value_too_large.
674 result.set_size(len);
675 return error_code::success();
678 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
680 // Make sure that the requested size fits within SIZE_T.
681 if (Size > std::numeric_limits<SIZE_T>::max()) {
682 if (FileDescriptor) {
684 _close(FileDescriptor);
686 ::CloseHandle(FileHandle);
687 return make_error_code(errc::invalid_argument);
692 case readonly: flprotect = PAGE_READONLY; break;
693 case readwrite: flprotect = PAGE_READWRITE; break;
694 case priv: flprotect = PAGE_WRITECOPY; break;
698 ::CreateFileMappingW(FileHandle, 0, flprotect,
699 (Offset + Size) >> 32,
700 (Offset + Size) & 0xffffffff,
702 if (FileMappingHandle == NULL) {
703 error_code ec = windows_error(GetLastError());
704 if (FileDescriptor) {
706 _close(FileDescriptor);
708 ::CloseHandle(FileHandle);
712 DWORD dwDesiredAccess;
714 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
715 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
716 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
718 Mapping = ::MapViewOfFile(FileMappingHandle,
723 if (Mapping == NULL) {
724 error_code ec = windows_error(GetLastError());
725 ::CloseHandle(FileMappingHandle);
726 if (FileDescriptor) {
728 _close(FileDescriptor);
730 ::CloseHandle(FileHandle);
735 MEMORY_BASIC_INFORMATION mbi;
736 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
738 error_code ec = windows_error(GetLastError());
739 ::UnmapViewOfFile(Mapping);
740 ::CloseHandle(FileMappingHandle);
741 if (FileDescriptor) {
743 _close(FileDescriptor);
745 ::CloseHandle(FileHandle);
748 Size = mbi.RegionSize;
751 // Close all the handles except for the view. It will keep the other handles
753 ::CloseHandle(FileMappingHandle);
754 if (FileDescriptor) {
756 _close(FileDescriptor); // Also closes FileHandle.
758 ::CloseHandle(FileHandle);
759 return error_code::success();
762 mapped_file_region::mapped_file_region(const Twine &path,
771 , FileHandle(INVALID_HANDLE_VALUE)
772 , FileMappingHandle() {
773 SmallString<128> path_storage;
774 SmallVector<wchar_t, 128> path_utf16;
776 // Convert path to UTF-16.
777 if ((ec = UTF8ToUTF16(path.toStringRef(path_storage), path_utf16)))
780 // Get file handle for creating a file mapping.
781 FileHandle = ::CreateFileW(c_str(path_utf16),
782 Mode == readonly ? GENERIC_READ
783 : GENERIC_READ | GENERIC_WRITE,
784 Mode == readonly ? FILE_SHARE_READ
787 Mode == readonly ? OPEN_EXISTING
789 Mode == readonly ? FILE_ATTRIBUTE_READONLY
790 : FILE_ATTRIBUTE_NORMAL,
792 if (FileHandle == INVALID_HANDLE_VALUE) {
793 ec = windows_error(::GetLastError());
798 ec = init(FileDescriptor, true, offset);
800 Mapping = FileMappingHandle = 0;
801 FileHandle = INVALID_HANDLE_VALUE;
806 mapped_file_region::mapped_file_region(int fd,
816 , FileHandle(INVALID_HANDLE_VALUE)
817 , FileMappingHandle() {
818 FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
819 if (FileHandle == INVALID_HANDLE_VALUE) {
821 _close(FileDescriptor);
823 ec = make_error_code(errc::bad_file_descriptor);
827 ec = init(FileDescriptor, closefd, offset);
829 Mapping = FileMappingHandle = 0;
830 FileHandle = INVALID_HANDLE_VALUE;
835 mapped_file_region::~mapped_file_region() {
837 ::UnmapViewOfFile(Mapping);
840 #if LLVM_HAS_RVALUE_REFERENCES
841 mapped_file_region::mapped_file_region(mapped_file_region &&other)
844 , Mapping(other.Mapping)
845 , FileDescriptor(other.FileDescriptor)
846 , FileHandle(other.FileHandle)
847 , FileMappingHandle(other.FileMappingHandle) {
848 other.Mapping = other.FileMappingHandle = 0;
849 other.FileHandle = INVALID_HANDLE_VALUE;
850 other.FileDescriptor = 0;
854 mapped_file_region::mapmode mapped_file_region::flags() const {
855 assert(Mapping && "Mapping failed but used anyway!");
859 uint64_t mapped_file_region::size() const {
860 assert(Mapping && "Mapping failed but used anyway!");
864 char *mapped_file_region::data() const {
865 assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
866 assert(Mapping && "Mapping failed but used anyway!");
867 return reinterpret_cast<char*>(Mapping);
870 const char *mapped_file_region::const_data() const {
871 assert(Mapping && "Mapping failed but used anyway!");
872 return reinterpret_cast<const char*>(Mapping);
875 int mapped_file_region::alignment() {
877 ::GetSystemInfo(&SysInfo);
878 return SysInfo.dwAllocationGranularity;
881 error_code detail::directory_iterator_construct(detail::DirIterState &it,
883 SmallVector<wchar_t, 128> path_utf16;
885 if (error_code ec = UTF8ToUTF16(path,
889 // Convert path to the format that Windows is happy with.
890 if (path_utf16.size() > 0 &&
891 !is_separator(path_utf16[path.size() - 1]) &&
892 path_utf16[path.size() - 1] != L':') {
893 path_utf16.push_back(L'\\');
894 path_utf16.push_back(L'*');
896 path_utf16.push_back(L'*');
899 // Get the first directory entry.
900 WIN32_FIND_DATAW FirstFind;
901 ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
903 return windows_error(::GetLastError());
905 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
906 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
907 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
908 FirstFind.cFileName[1] == L'.'))
909 if (!::FindNextFileW(FindHandle, &FirstFind)) {
910 error_code ec = windows_error(::GetLastError());
912 if (ec == windows_error::no_more_files)
913 return detail::directory_iterator_destruct(it);
916 FilenameLen = ::wcslen(FirstFind.cFileName);
918 // Construct the current directory entry.
919 SmallString<128> directory_entry_name_utf8;
920 if (error_code ec = UTF16ToUTF8(FirstFind.cFileName,
921 ::wcslen(FirstFind.cFileName),
922 directory_entry_name_utf8))
925 it.IterationHandle = intptr_t(FindHandle.take());
926 SmallString<128> directory_entry_path(path);
927 path::append(directory_entry_path, directory_entry_name_utf8.str());
928 it.CurrentEntry = directory_entry(directory_entry_path.str());
930 return error_code::success();
933 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
934 if (it.IterationHandle != 0)
935 // Closes the handle if it's valid.
936 ScopedFindHandle close(HANDLE(it.IterationHandle));
937 it.IterationHandle = 0;
938 it.CurrentEntry = directory_entry();
939 return error_code::success();
942 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
943 WIN32_FIND_DATAW FindData;
944 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
945 error_code ec = windows_error(::GetLastError());
947 if (ec == windows_error::no_more_files)
948 return detail::directory_iterator_destruct(it);
952 size_t FilenameLen = ::wcslen(FindData.cFileName);
953 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
954 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
955 FindData.cFileName[1] == L'.'))
956 return directory_iterator_increment(it);
958 SmallString<128> directory_entry_path_utf8;
959 if (error_code ec = UTF16ToUTF8(FindData.cFileName,
960 ::wcslen(FindData.cFileName),
961 directory_entry_path_utf8))
964 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
965 return error_code::success();
968 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
969 bool map_writable, void *&result) {
970 assert(0 && "NOT IMPLEMENTED");
971 return windows_error::invalid_function;
974 error_code unmap_file_pages(void *base, size_t size) {
975 assert(0 && "NOT IMPLEMENTED");
976 return windows_error::invalid_function;
979 error_code openFileForRead(const Twine &Name, int &ResultFD) {
980 SmallString<128> PathStorage;
981 SmallVector<wchar_t, 128> PathUTF16;
983 if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
987 HANDLE H = ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
988 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
989 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
990 if (H == INVALID_HANDLE_VALUE) {
991 error_code EC = windows_error(::GetLastError());
992 // Provide a better error message when trying to open directories.
993 // This only runs if we failed to open the file, so there is probably
994 // no performances issues.
995 if (EC != windows_error::access_denied)
997 if (is_directory(Name))
998 return error_code(errc::is_a_directory, posix_category());
1002 int FD = ::_open_osfhandle(intptr_t(H), 0);
1005 return windows_error::invalid_handle;
1009 return error_code::success();
1012 error_code openFileForWrite(const Twine &Name, int &ResultFD,
1013 sys::fs::OpenFlags Flags, unsigned Mode) {
1014 // Verify that we don't have both "append" and "excl".
1015 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
1016 "Cannot specify both 'excl' and 'append' file creation flags!");
1018 SmallString<128> PathStorage;
1019 SmallVector<wchar_t, 128> PathUTF16;
1021 if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
1025 DWORD CreationDisposition;
1027 CreationDisposition = CREATE_NEW;
1028 else if (Flags & F_Append)
1029 CreationDisposition = OPEN_ALWAYS;
1031 CreationDisposition = CREATE_ALWAYS;
1033 HANDLE H = ::CreateFileW(PathUTF16.begin(), GENERIC_WRITE,
1034 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1035 CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
1037 if (H == INVALID_HANDLE_VALUE) {
1038 error_code EC = windows_error(::GetLastError());
1039 // Provide a better error message when trying to open directories.
1040 // This only runs if we failed to open the file, so there is probably
1041 // no performances issues.
1042 if (EC != windows_error::access_denied)
1044 if (is_directory(Name))
1045 return error_code(errc::is_a_directory, posix_category());
1050 if (Flags & F_Append)
1051 OpenFlags |= _O_APPEND;
1053 if (!(Flags & F_Binary))
1054 OpenFlags |= _O_TEXT;
1056 int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
1059 return windows_error::invalid_handle;
1063 return error_code::success();
1065 } // end namespace fs
1069 bool home_directory(SmallVectorImpl<char> &result) {
1070 wchar_t Path[MAX_PATH];
1071 if (::SHGetFolderPathW(0, CSIDL_APPDATA | CSIDL_FLAG_CREATE, 0,
1072 SHGFP_TYPE_CURRENT, Path) != S_OK)
1075 if (UTF16ToUTF8(Path, ::wcslen(Path), result))
1081 } // end namespace path
1084 llvm::error_code UTF8ToUTF16(llvm::StringRef utf8,
1085 llvm::SmallVectorImpl<wchar_t> &utf16) {
1086 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
1087 utf8.begin(), utf8.size(),
1091 return llvm::windows_error(::GetLastError());
1093 utf16.reserve(len + 1);
1094 utf16.set_size(len);
1096 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
1097 utf8.begin(), utf8.size(),
1098 utf16.begin(), utf16.size());
1101 return llvm::windows_error(::GetLastError());
1103 // Make utf16 null terminated.
1107 return llvm::error_code::success();
1110 llvm::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
1111 llvm::SmallVectorImpl<char> &utf8) {
1113 int len = ::WideCharToMultiByte(CP_UTF8, 0,
1119 return llvm::windows_error(::GetLastError());
1124 // Now do the actual conversion.
1125 len = ::WideCharToMultiByte(CP_UTF8, 0,
1127 utf8.data(), utf8.size(),
1131 return llvm::windows_error(::GetLastError());
1133 // Make utf8 null terminated.
1137 return llvm::error_code::success();
1139 } // end namespace windows
1140 } // end namespace sys
1141 } // end namespace llvm