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;
116 random_path_utf16.set_size(0);
117 for (SmallVectorImpl<wchar_t>::const_iterator i = model_utf16.begin(),
118 e = model_utf16.end();
121 unsigned val = sys::Process::GetRandomNumber();
122 random_path_utf16.push_back(L"0123456789abcdef"[val & 15]);
125 random_path_utf16.push_back(*i);
127 // Make random_path_utf16 null terminated.
128 random_path_utf16.push_back(0);
129 random_path_utf16.pop_back();
131 HANDLE TempFileHandle = INVALID_HANDLE_VALUE;
135 // Try to create + open the path.
137 ::CreateFileW(random_path_utf16.begin(), GENERIC_READ | GENERIC_WRITE,
138 FILE_SHARE_READ, NULL,
139 // Return ERROR_FILE_EXISTS if the file
141 CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY, NULL);
142 if (TempFileHandle == INVALID_HANDLE_VALUE) {
143 // If the file existed, try again, otherwise, error.
144 error_code ec = windows_error(::GetLastError());
145 if (ec == windows_error::file_exists)
146 goto retry_random_path;
151 // Convert the Windows API file handle into a C-runtime handle.
152 int fd = ::_open_osfhandle(intptr_t(TempFileHandle), 0);
154 ::CloseHandle(TempFileHandle);
155 ::DeleteFileW(random_path_utf16.begin());
156 // MSDN doesn't say anything about _open_osfhandle setting errno or
157 // GetLastError(), so just return invalid_handle.
158 return windows_error::invalid_handle;
166 DWORD attributes = ::GetFileAttributesW(random_path_utf16.begin());
167 if (attributes != INVALID_FILE_ATTRIBUTES)
168 goto retry_random_path;
169 error_code EC = make_error_code(windows_error(::GetLastError()));
170 if (EC != windows_error::file_not_found &&
171 EC != windows_error::path_not_found)
177 if (!::CreateDirectoryW(random_path_utf16.begin(), NULL)) {
178 error_code EC = windows_error(::GetLastError());
179 if (EC != windows_error::already_exists)
181 goto retry_random_path;
186 // Set result_path to the utf-8 representation of the path.
187 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
188 random_path_utf16.size(), result_path)) {
191 ::CloseHandle(TempFileHandle);
192 ::DeleteFileW(random_path_utf16.begin());
196 ::RemoveDirectoryW(random_path_utf16.begin());
202 return error_code::success();
209 std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
210 SmallVector<wchar_t, MAX_PATH> PathName;
211 DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
213 // A zero return value indicates a failure other than insufficient space.
217 // Insufficient space is determined by a return value equal to the size of
218 // the buffer passed in.
219 if (Size == PathName.capacity())
222 // On success, GetModuleFileNameW returns the number of characters written to
223 // the buffer not including the NULL terminator.
224 PathName.set_size(Size);
226 // Convert the result from UTF-16 to UTF-8.
227 SmallVector<char, MAX_PATH> PathNameUTF8;
228 if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
231 return std::string(PathNameUTF8.data());
234 UniqueID file_status::getUniqueID() const {
235 // The file is uniquely identified by the volume serial number along
236 // with the 64-bit file identifier.
237 uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
238 static_cast<uint64_t>(FileIndexLow);
240 return UniqueID(VolumeSerialNumber, FileID);
243 TimeValue file_status::getLastModificationTime() const {
245 UI.LowPart = LastWriteTimeLow;
246 UI.HighPart = LastWriteTimeHigh;
249 Ret.fromWin32Time(UI.QuadPart);
253 error_code current_path(SmallVectorImpl<char> &result) {
254 SmallVector<wchar_t, MAX_PATH> cur_path;
255 DWORD len = MAX_PATH;
258 cur_path.reserve(len);
259 len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
261 // A zero return value indicates a failure other than insufficient space.
263 return windows_error(::GetLastError());
265 // If there's insufficient space, the len returned is larger than the len
267 } while (len > cur_path.capacity());
269 // On success, GetCurrentDirectoryW returns the number of characters not
270 // including the null-terminator.
271 cur_path.set_size(len);
272 return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
275 error_code create_directory(const Twine &path, bool &existed) {
276 SmallString<128> path_storage;
277 SmallVector<wchar_t, 128> path_utf16;
279 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
283 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
284 error_code ec = windows_error(::GetLastError());
285 if (ec == windows_error::already_exists)
292 return error_code::success();
295 error_code create_hard_link(const Twine &to, const Twine &from) {
297 SmallString<128> from_storage;
298 SmallString<128> to_storage;
299 StringRef f = from.toStringRef(from_storage);
300 StringRef t = to.toStringRef(to_storage);
302 // Convert to utf-16.
303 SmallVector<wchar_t, 128> wide_from;
304 SmallVector<wchar_t, 128> wide_to;
305 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
306 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
308 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
309 return windows_error(::GetLastError());
311 return error_code::success();
314 error_code create_symlink(const Twine &to, const Twine &from) {
315 // Only do it if the function is available at runtime.
316 if (!create_symbolic_link_api)
317 return make_error_code(errc::function_not_supported);
320 SmallString<128> from_storage;
321 SmallString<128> to_storage;
322 StringRef f = from.toStringRef(from_storage);
323 StringRef t = to.toStringRef(to_storage);
325 // Convert to utf-16.
326 SmallVector<wchar_t, 128> wide_from;
327 SmallVector<wchar_t, 128> wide_to;
328 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
329 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
331 if (!create_symbolic_link_api(wide_from.begin(), wide_to.begin(), 0))
332 return windows_error(::GetLastError());
334 return error_code::success();
337 error_code remove(const Twine &path, bool &existed) {
338 SmallString<128> path_storage;
339 SmallVector<wchar_t, 128> path_utf16;
342 error_code EC = status(path, st);
344 if (EC == windows_error::file_not_found ||
345 EC == windows_error::path_not_found) {
347 return error_code::success();
352 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
356 if (st.type() == file_type::directory_file) {
357 if (!::RemoveDirectoryW(c_str(path_utf16))) {
358 error_code ec = windows_error(::GetLastError());
359 if (ec != windows_error::file_not_found)
365 if (!::DeleteFileW(c_str(path_utf16))) {
366 error_code ec = windows_error(::GetLastError());
367 if (ec != windows_error::file_not_found)
374 return error_code::success();
377 error_code rename(const Twine &from, const Twine &to) {
379 SmallString<128> from_storage;
380 SmallString<128> to_storage;
381 StringRef f = from.toStringRef(from_storage);
382 StringRef t = to.toStringRef(to_storage);
384 // Convert to utf-16.
385 SmallVector<wchar_t, 128> wide_from;
386 SmallVector<wchar_t, 128> wide_to;
387 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
388 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
390 error_code ec = error_code::success();
391 for (int i = 0; i < 2000; i++) {
392 if (::MoveFileExW(wide_from.begin(), wide_to.begin(),
393 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
394 return error_code::success();
395 ec = windows_error(::GetLastError());
396 if (ec != windows_error::access_denied)
398 // Retry MoveFile() at ACCESS_DENIED.
399 // System scanners (eg. indexer) might open the source file when
400 // It is written and closed.
407 error_code resize_file(const Twine &path, uint64_t size) {
408 SmallString<128> path_storage;
409 SmallVector<wchar_t, 128> path_utf16;
411 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
415 int fd = ::_wopen(path_utf16.begin(), O_BINARY | _O_RDWR, S_IWRITE);
417 return error_code(errno, generic_category());
418 #ifdef HAVE__CHSIZE_S
419 errno_t error = ::_chsize_s(fd, size);
421 errno_t error = ::_chsize(fd, size);
424 return error_code(error, generic_category());
427 error_code exists(const Twine &path, bool &result) {
428 SmallString<128> path_storage;
429 SmallVector<wchar_t, 128> path_utf16;
431 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
435 DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
437 if (attributes == INVALID_FILE_ATTRIBUTES) {
438 // See if the file didn't actually exist.
439 error_code ec = make_error_code(windows_error(::GetLastError()));
440 if (ec != windows_error::file_not_found &&
441 ec != windows_error::path_not_found)
446 return error_code::success();
449 bool can_write(const Twine &Path) {
450 // FIXME: take security attributes into account.
451 SmallString<128> PathStorage;
452 SmallVector<wchar_t, 128> PathUtf16;
454 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
457 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
458 return (Attr != INVALID_FILE_ATTRIBUTES) && !(Attr & FILE_ATTRIBUTE_READONLY);
461 bool can_execute(const Twine &Path) {
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;
472 bool equivalent(file_status A, file_status B) {
473 assert(status_known(A) && status_known(B));
474 return A.FileIndexHigh == B.FileIndexHigh &&
475 A.FileIndexLow == B.FileIndexLow &&
476 A.FileSizeHigh == B.FileSizeHigh &&
477 A.FileSizeLow == B.FileSizeLow &&
478 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
479 A.LastWriteTimeLow == B.LastWriteTimeLow &&
480 A.VolumeSerialNumber == B.VolumeSerialNumber;
483 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
484 file_status fsA, fsB;
485 if (error_code ec = status(A, fsA)) return ec;
486 if (error_code ec = status(B, fsB)) return ec;
487 result = equivalent(fsA, fsB);
488 return error_code::success();
491 static bool isReservedName(StringRef path) {
492 // This list of reserved names comes from MSDN, at:
493 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
494 static const char *sReservedNames[] = { "nul", "con", "prn", "aux",
495 "com1", "com2", "com3", "com4", "com5", "com6",
496 "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
497 "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9" };
499 // First, check to see if this is a device namespace, which always
500 // starts with \\.\, since device namespaces are not legal file paths.
501 if (path.startswith("\\\\.\\"))
504 // Then compare against the list of ancient reserved names
505 for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
506 if (path.equals_lower(sReservedNames[i]))
510 // The path isn't what we consider reserved.
514 static error_code getStatus(HANDLE FileHandle, file_status &Result) {
515 if (FileHandle == INVALID_HANDLE_VALUE)
516 goto handle_status_error;
518 switch (::GetFileType(FileHandle)) {
520 llvm_unreachable("Don't know anything about this file type");
521 case FILE_TYPE_UNKNOWN: {
522 DWORD Err = ::GetLastError();
524 return windows_error(Err);
525 Result = file_status(file_type::type_unknown);
526 return error_code::success();
531 Result = file_status(file_type::character_file);
532 return error_code::success();
534 Result = file_status(file_type::fifo_file);
535 return error_code::success();
538 BY_HANDLE_FILE_INFORMATION Info;
539 if (!::GetFileInformationByHandle(FileHandle, &Info))
540 goto handle_status_error;
543 file_type Type = (Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
544 ? file_type::directory_file
545 : file_type::regular_file;
547 file_status(Type, Info.ftLastWriteTime.dwHighDateTime,
548 Info.ftLastWriteTime.dwLowDateTime,
549 Info.dwVolumeSerialNumber, Info.nFileSizeHigh,
550 Info.nFileSizeLow, Info.nFileIndexHigh, Info.nFileIndexLow);
551 return error_code::success();
555 error_code EC = windows_error(::GetLastError());
556 if (EC == windows_error::file_not_found ||
557 EC == windows_error::path_not_found)
558 Result = file_status(file_type::file_not_found);
559 else if (EC == windows_error::sharing_violation)
560 Result = file_status(file_type::type_unknown);
562 Result = file_status(file_type::status_error);
566 error_code status(const Twine &path, file_status &result) {
567 SmallString<128> path_storage;
568 SmallVector<wchar_t, 128> path_utf16;
570 StringRef path8 = path.toStringRef(path_storage);
571 if (isReservedName(path8)) {
572 result = file_status(file_type::character_file);
573 return error_code::success();
576 if (error_code ec = UTF8ToUTF16(path8, path_utf16))
579 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
580 if (attr == INVALID_FILE_ATTRIBUTES)
581 return getStatus(INVALID_HANDLE_VALUE, result);
583 // Handle reparse points.
584 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
586 ::CreateFileW(path_utf16.begin(),
587 0, // Attributes only.
588 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
591 FILE_FLAG_BACKUP_SEMANTICS,
594 return getStatus(INVALID_HANDLE_VALUE, result);
598 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
599 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
600 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0));
602 return getStatus(INVALID_HANDLE_VALUE, result);
604 return getStatus(h, result);
607 error_code status(int FD, file_status &Result) {
608 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
609 return getStatus(FileHandle, Result);
612 error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
614 UI.QuadPart = Time.toWin32Time();
616 FT.dwLowDateTime = UI.LowPart;
617 FT.dwHighDateTime = UI.HighPart;
618 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
619 if (!SetFileTime(FileHandle, NULL, &FT, &FT))
620 return windows_error(::GetLastError());
621 return error_code::success();
624 error_code get_magic(const Twine &path, uint32_t len,
625 SmallVectorImpl<char> &result) {
626 SmallString<128> path_storage;
627 SmallVector<wchar_t, 128> path_utf16;
630 // Convert path to UTF-16.
631 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
636 HANDLE file = ::CreateFileW(c_str(path_utf16),
641 FILE_ATTRIBUTE_READONLY,
643 if (file == INVALID_HANDLE_VALUE)
644 return windows_error(::GetLastError());
650 DWORD bytes_read = 0;
651 BOOL read_success = ::ReadFile(file, result.data(), len, &bytes_read, NULL);
652 error_code ec = windows_error(::GetLastError());
654 if (!read_success || (bytes_read != len)) {
655 // Set result size to the number of bytes read if it's valid.
656 if (bytes_read <= len)
657 result.set_size(bytes_read);
658 // ERROR_HANDLE_EOF is mapped to errc::value_too_large.
662 result.set_size(len);
663 return error_code::success();
666 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
668 // Make sure that the requested size fits within SIZE_T.
669 if (Size > std::numeric_limits<SIZE_T>::max()) {
670 if (FileDescriptor) {
672 _close(FileDescriptor);
674 ::CloseHandle(FileHandle);
675 return make_error_code(errc::invalid_argument);
680 case readonly: flprotect = PAGE_READONLY; break;
681 case readwrite: flprotect = PAGE_READWRITE; break;
682 case priv: flprotect = PAGE_WRITECOPY; break;
686 ::CreateFileMappingW(FileHandle, 0, flprotect,
687 (Offset + Size) >> 32,
688 (Offset + Size) & 0xffffffff,
690 if (FileMappingHandle == NULL) {
691 error_code ec = windows_error(GetLastError());
692 if (FileDescriptor) {
694 _close(FileDescriptor);
696 ::CloseHandle(FileHandle);
700 DWORD dwDesiredAccess;
702 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
703 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
704 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
706 Mapping = ::MapViewOfFile(FileMappingHandle,
711 if (Mapping == NULL) {
712 error_code ec = windows_error(GetLastError());
713 ::CloseHandle(FileMappingHandle);
714 if (FileDescriptor) {
716 _close(FileDescriptor);
718 ::CloseHandle(FileHandle);
723 MEMORY_BASIC_INFORMATION mbi;
724 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
726 error_code ec = windows_error(GetLastError());
727 ::UnmapViewOfFile(Mapping);
728 ::CloseHandle(FileMappingHandle);
729 if (FileDescriptor) {
731 _close(FileDescriptor);
733 ::CloseHandle(FileHandle);
736 Size = mbi.RegionSize;
739 // Close all the handles except for the view. It will keep the other handles
741 ::CloseHandle(FileMappingHandle);
742 if (FileDescriptor) {
744 _close(FileDescriptor); // Also closes FileHandle.
746 ::CloseHandle(FileHandle);
747 return error_code::success();
750 mapped_file_region::mapped_file_region(const Twine &path,
759 , FileHandle(INVALID_HANDLE_VALUE)
760 , FileMappingHandle() {
761 SmallString<128> path_storage;
762 SmallVector<wchar_t, 128> path_utf16;
764 // Convert path to UTF-16.
765 if ((ec = UTF8ToUTF16(path.toStringRef(path_storage), path_utf16)))
768 // Get file handle for creating a file mapping.
769 FileHandle = ::CreateFileW(c_str(path_utf16),
770 Mode == readonly ? GENERIC_READ
771 : GENERIC_READ | GENERIC_WRITE,
772 Mode == readonly ? FILE_SHARE_READ
775 Mode == readonly ? OPEN_EXISTING
777 Mode == readonly ? FILE_ATTRIBUTE_READONLY
778 : FILE_ATTRIBUTE_NORMAL,
780 if (FileHandle == INVALID_HANDLE_VALUE) {
781 ec = windows_error(::GetLastError());
786 ec = init(FileDescriptor, true, offset);
788 Mapping = FileMappingHandle = 0;
789 FileHandle = INVALID_HANDLE_VALUE;
794 mapped_file_region::mapped_file_region(int fd,
804 , FileHandle(INVALID_HANDLE_VALUE)
805 , FileMappingHandle() {
806 FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
807 if (FileHandle == INVALID_HANDLE_VALUE) {
809 _close(FileDescriptor);
811 ec = make_error_code(errc::bad_file_descriptor);
815 ec = init(FileDescriptor, closefd, offset);
817 Mapping = FileMappingHandle = 0;
818 FileHandle = INVALID_HANDLE_VALUE;
823 mapped_file_region::~mapped_file_region() {
825 ::UnmapViewOfFile(Mapping);
828 #if LLVM_HAS_RVALUE_REFERENCES
829 mapped_file_region::mapped_file_region(mapped_file_region &&other)
832 , Mapping(other.Mapping)
833 , FileDescriptor(other.FileDescriptor)
834 , FileHandle(other.FileHandle)
835 , FileMappingHandle(other.FileMappingHandle) {
836 other.Mapping = other.FileMappingHandle = 0;
837 other.FileHandle = INVALID_HANDLE_VALUE;
838 other.FileDescriptor = 0;
842 mapped_file_region::mapmode mapped_file_region::flags() const {
843 assert(Mapping && "Mapping failed but used anyway!");
847 uint64_t mapped_file_region::size() const {
848 assert(Mapping && "Mapping failed but used anyway!");
852 char *mapped_file_region::data() const {
853 assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
854 assert(Mapping && "Mapping failed but used anyway!");
855 return reinterpret_cast<char*>(Mapping);
858 const char *mapped_file_region::const_data() const {
859 assert(Mapping && "Mapping failed but used anyway!");
860 return reinterpret_cast<const char*>(Mapping);
863 int mapped_file_region::alignment() {
865 ::GetSystemInfo(&SysInfo);
866 return SysInfo.dwAllocationGranularity;
869 error_code detail::directory_iterator_construct(detail::DirIterState &it,
871 SmallVector<wchar_t, 128> path_utf16;
873 if (error_code ec = UTF8ToUTF16(path,
877 // Convert path to the format that Windows is happy with.
878 if (path_utf16.size() > 0 &&
879 !is_separator(path_utf16[path.size() - 1]) &&
880 path_utf16[path.size() - 1] != L':') {
881 path_utf16.push_back(L'\\');
882 path_utf16.push_back(L'*');
884 path_utf16.push_back(L'*');
887 // Get the first directory entry.
888 WIN32_FIND_DATAW FirstFind;
889 ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
891 return windows_error(::GetLastError());
893 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
894 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
895 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
896 FirstFind.cFileName[1] == L'.'))
897 if (!::FindNextFileW(FindHandle, &FirstFind)) {
898 error_code ec = windows_error(::GetLastError());
900 if (ec == windows_error::no_more_files)
901 return detail::directory_iterator_destruct(it);
904 FilenameLen = ::wcslen(FirstFind.cFileName);
906 // Construct the current directory entry.
907 SmallString<128> directory_entry_name_utf8;
908 if (error_code ec = UTF16ToUTF8(FirstFind.cFileName,
909 ::wcslen(FirstFind.cFileName),
910 directory_entry_name_utf8))
913 it.IterationHandle = intptr_t(FindHandle.take());
914 SmallString<128> directory_entry_path(path);
915 path::append(directory_entry_path, directory_entry_name_utf8.str());
916 it.CurrentEntry = directory_entry(directory_entry_path.str());
918 return error_code::success();
921 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
922 if (it.IterationHandle != 0)
923 // Closes the handle if it's valid.
924 ScopedFindHandle close(HANDLE(it.IterationHandle));
925 it.IterationHandle = 0;
926 it.CurrentEntry = directory_entry();
927 return error_code::success();
930 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
931 WIN32_FIND_DATAW FindData;
932 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
933 error_code ec = windows_error(::GetLastError());
935 if (ec == windows_error::no_more_files)
936 return detail::directory_iterator_destruct(it);
940 size_t FilenameLen = ::wcslen(FindData.cFileName);
941 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
942 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
943 FindData.cFileName[1] == L'.'))
944 return directory_iterator_increment(it);
946 SmallString<128> directory_entry_path_utf8;
947 if (error_code ec = UTF16ToUTF8(FindData.cFileName,
948 ::wcslen(FindData.cFileName),
949 directory_entry_path_utf8))
952 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
953 return error_code::success();
956 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
957 bool map_writable, void *&result) {
958 assert(0 && "NOT IMPLEMENTED");
959 return windows_error::invalid_function;
962 error_code unmap_file_pages(void *base, size_t size) {
963 assert(0 && "NOT IMPLEMENTED");
964 return windows_error::invalid_function;
967 error_code openFileForRead(const Twine &Name, int &ResultFD) {
968 SmallString<128> PathStorage;
969 SmallVector<wchar_t, 128> PathUTF16;
971 if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
975 HANDLE H = ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
976 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
977 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
978 if (H == INVALID_HANDLE_VALUE) {
979 error_code EC = windows_error(::GetLastError());
980 // Provide a better error message when trying to open directories.
981 // This only runs if we failed to open the file, so there is probably
982 // no performances issues.
983 if (EC != windows_error::access_denied)
985 if (is_directory(Name))
986 return error_code(errc::is_a_directory, posix_category());
990 int FD = ::_open_osfhandle(intptr_t(H), 0);
993 return windows_error::invalid_handle;
997 return error_code::success();
1000 error_code openFileForWrite(const Twine &Name, int &ResultFD,
1001 sys::fs::OpenFlags Flags, unsigned Mode) {
1002 // Verify that we don't have both "append" and "excl".
1003 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
1004 "Cannot specify both 'excl' and 'append' file creation flags!");
1006 SmallString<128> PathStorage;
1007 SmallVector<wchar_t, 128> PathUTF16;
1009 if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
1013 DWORD CreationDisposition;
1015 CreationDisposition = CREATE_NEW;
1016 else if (Flags & F_Append)
1017 CreationDisposition = OPEN_ALWAYS;
1019 CreationDisposition = CREATE_ALWAYS;
1021 HANDLE H = ::CreateFileW(PathUTF16.begin(), GENERIC_WRITE,
1022 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1023 CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
1025 if (H == INVALID_HANDLE_VALUE) {
1026 error_code EC = windows_error(::GetLastError());
1027 // Provide a better error message when trying to open directories.
1028 // This only runs if we failed to open the file, so there is probably
1029 // no performances issues.
1030 if (EC != windows_error::access_denied)
1032 if (is_directory(Name))
1033 return error_code(errc::is_a_directory, posix_category());
1038 if (Flags & F_Append)
1039 OpenFlags |= _O_APPEND;
1041 if (!(Flags & F_Binary))
1042 OpenFlags |= _O_TEXT;
1044 int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
1047 return windows_error::invalid_handle;
1051 return error_code::success();
1053 } // end namespace fs
1057 bool home_directory(SmallVectorImpl<char> &result) {
1058 wchar_t Path[MAX_PATH];
1059 if (::SHGetFolderPathW(0, CSIDL_APPDATA | CSIDL_FLAG_CREATE, 0,
1060 /*SHGFP_TYPE_CURRENT*/0, Path) != S_OK)
1063 if (UTF16ToUTF8(Path, ::wcslen(Path), result))
1069 } // end namespace path
1072 llvm::error_code UTF8ToUTF16(llvm::StringRef utf8,
1073 llvm::SmallVectorImpl<wchar_t> &utf16) {
1074 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
1075 utf8.begin(), utf8.size(),
1079 return llvm::windows_error(::GetLastError());
1081 utf16.reserve(len + 1);
1082 utf16.set_size(len);
1084 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
1085 utf8.begin(), utf8.size(),
1086 utf16.begin(), utf16.size());
1089 return llvm::windows_error(::GetLastError());
1091 // Make utf16 null terminated.
1095 return llvm::error_code::success();
1098 llvm::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
1099 llvm::SmallVectorImpl<char> &utf8) {
1101 int len = ::WideCharToMultiByte(CP_UTF8, 0,
1107 return llvm::windows_error(::GetLastError());
1112 // Now do the actual conversion.
1113 len = ::WideCharToMultiByte(CP_UTF8, 0,
1115 utf8.data(), utf8.size(),
1119 return llvm::windows_error(::GetLastError());
1121 // Make utf8 null terminated.
1125 return llvm::error_code::success();
1127 } // end namespace windows
1128 } // end namespace sys
1129 } // end namespace llvm