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 // These two headers must be included last, and make sure shlobj is required
26 // after Windows.h to make sure it picks up our definition of _WIN32_WINNT
27 #include "WindowsSupport.h"
32 // MinGW doesn't define this.
33 #ifndef _ERRNO_T_DEFINED
34 #define _ERRNO_T_DEFINED
39 # pragma comment(lib, "advapi32.lib") // This provides CryptAcquireContextW.
44 using llvm::sys::windows::UTF8ToUTF16;
45 using llvm::sys::windows::UTF16ToUTF8;
48 error_code TempDir(SmallVectorImpl<wchar_t> &result) {
50 DWORD len = ::GetTempPathW(result.capacity(), result.begin());
53 return windows_error(::GetLastError());
55 if (len > result.capacity()) {
61 return error_code::success();
64 bool is_separator(const wchar_t value) {
75 // FIXME: mode should be used here and default to user r/w only,
76 // it currently comes in as a UNIX mode.
77 static error_code createUniqueEntity(const Twine &model, int &result_fd,
78 SmallVectorImpl<char> &result_path,
79 bool makeAbsolute, unsigned mode,
81 // Use result_path as temp storage.
82 result_path.set_size(0);
83 StringRef m = model.toStringRef(result_path);
85 SmallVector<wchar_t, 128> model_utf16;
86 if (error_code ec = UTF8ToUTF16(m, model_utf16)) return ec;
89 // Make model absolute by prepending a temp directory if it's not already.
90 bool absolute = sys::path::is_absolute(m);
93 SmallVector<wchar_t, 64> temp_dir;
94 if (error_code ec = TempDir(temp_dir)) return ec;
95 // Handle c: by removing it.
96 if (model_utf16.size() > 2 && model_utf16[1] == L':') {
97 model_utf16.erase(model_utf16.begin(), model_utf16.begin() + 2);
99 model_utf16.insert(model_utf16.begin(), temp_dir.begin(), temp_dir.end());
103 // Replace '%' with random chars. From here on, DO NOT modify model. It may be
104 // needed if the randomly chosen path already exists.
105 SmallVector<wchar_t, 128> random_path_utf16;
108 random_path_utf16.set_size(0);
109 for (SmallVectorImpl<wchar_t>::const_iterator i = model_utf16.begin(),
110 e = model_utf16.end();
113 unsigned val = sys::Process::GetRandomNumber();
114 random_path_utf16.push_back(L"0123456789abcdef"[val & 15]);
117 random_path_utf16.push_back(*i);
119 // Make random_path_utf16 null terminated.
120 random_path_utf16.push_back(0);
121 random_path_utf16.pop_back();
123 HANDLE TempFileHandle = INVALID_HANDLE_VALUE;
127 // Try to create + open the path.
129 ::CreateFileW(random_path_utf16.begin(), GENERIC_READ | GENERIC_WRITE,
130 FILE_SHARE_READ, NULL,
131 // Return ERROR_FILE_EXISTS if the file
133 CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY, NULL);
134 if (TempFileHandle == INVALID_HANDLE_VALUE) {
135 // If the file existed, try again, otherwise, error.
136 error_code ec = windows_error(::GetLastError());
137 if (ec == windows_error::file_exists)
138 goto retry_random_path;
143 // Convert the Windows API file handle into a C-runtime handle.
144 int fd = ::_open_osfhandle(intptr_t(TempFileHandle), 0);
146 ::CloseHandle(TempFileHandle);
147 ::DeleteFileW(random_path_utf16.begin());
148 // MSDN doesn't say anything about _open_osfhandle setting errno or
149 // GetLastError(), so just return invalid_handle.
150 return windows_error::invalid_handle;
158 DWORD attributes = ::GetFileAttributesW(random_path_utf16.begin());
159 if (attributes != INVALID_FILE_ATTRIBUTES)
160 goto retry_random_path;
161 error_code EC = make_error_code(windows_error(::GetLastError()));
162 if (EC != windows_error::file_not_found &&
163 EC != windows_error::path_not_found)
169 if (!::CreateDirectoryW(random_path_utf16.begin(), NULL)) {
170 error_code EC = windows_error(::GetLastError());
171 if (EC != windows_error::already_exists)
173 goto retry_random_path;
178 // Set result_path to the utf-8 representation of the path.
179 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
180 random_path_utf16.size(), result_path)) {
183 ::CloseHandle(TempFileHandle);
184 ::DeleteFileW(random_path_utf16.begin());
188 ::RemoveDirectoryW(random_path_utf16.begin());
194 return error_code::success();
201 std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
202 SmallVector<wchar_t, MAX_PATH> PathName;
203 DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
205 // A zero return value indicates a failure other than insufficient space.
209 // Insufficient space is determined by a return value equal to the size of
210 // the buffer passed in.
211 if (Size == PathName.capacity())
214 // On success, GetModuleFileNameW returns the number of characters written to
215 // the buffer not including the NULL terminator.
216 PathName.set_size(Size);
218 // Convert the result from UTF-16 to UTF-8.
219 SmallVector<char, MAX_PATH> PathNameUTF8;
220 if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
223 return std::string(PathNameUTF8.data());
226 UniqueID file_status::getUniqueID() const {
227 // The file is uniquely identified by the volume serial number along
228 // with the 64-bit file identifier.
229 uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
230 static_cast<uint64_t>(FileIndexLow);
232 return UniqueID(VolumeSerialNumber, FileID);
235 TimeValue file_status::getLastModificationTime() const {
237 UI.LowPart = LastWriteTimeLow;
238 UI.HighPart = LastWriteTimeHigh;
241 Ret.fromWin32Time(UI.QuadPart);
245 error_code current_path(SmallVectorImpl<char> &result) {
246 SmallVector<wchar_t, MAX_PATH> cur_path;
247 DWORD len = MAX_PATH;
250 cur_path.reserve(len);
251 len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
253 // A zero return value indicates a failure other than insufficient space.
255 return windows_error(::GetLastError());
257 // If there's insufficient space, the len returned is larger than the len
259 } while (len > cur_path.capacity());
261 // On success, GetCurrentDirectoryW returns the number of characters not
262 // including the null-terminator.
263 cur_path.set_size(len);
264 return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
267 error_code create_directory(const Twine &path, bool IgnoreExisting) {
268 SmallString<128> path_storage;
269 SmallVector<wchar_t, 128> path_utf16;
271 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
275 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
276 error_code ec = windows_error(::GetLastError());
277 if (ec != windows_error::already_exists || !IgnoreExisting)
281 return error_code::success();
284 error_code create_hard_link(const Twine &to, const Twine &from) {
286 SmallString<128> from_storage;
287 SmallString<128> to_storage;
288 StringRef f = from.toStringRef(from_storage);
289 StringRef t = to.toStringRef(to_storage);
291 // Convert to utf-16.
292 SmallVector<wchar_t, 128> wide_from;
293 SmallVector<wchar_t, 128> wide_to;
294 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
295 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
297 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
298 return windows_error(::GetLastError());
300 return error_code::success();
303 error_code remove(const Twine &path, bool IgnoreNonExisting) {
304 SmallString<128> path_storage;
305 SmallVector<wchar_t, 128> path_utf16;
308 if (error_code EC = status(path, ST)) {
309 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
311 return error_code::success();
314 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
318 if (ST.type() == file_type::directory_file) {
319 if (!::RemoveDirectoryW(c_str(path_utf16))) {
320 error_code EC = windows_error(::GetLastError());
321 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
324 return error_code::success();
326 if (!::DeleteFileW(c_str(path_utf16))) {
327 error_code EC = windows_error(::GetLastError());
328 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
331 return error_code::success();
334 error_code rename(const Twine &from, const Twine &to) {
336 SmallString<128> from_storage;
337 SmallString<128> to_storage;
338 StringRef f = from.toStringRef(from_storage);
339 StringRef t = to.toStringRef(to_storage);
341 // Convert to utf-16.
342 SmallVector<wchar_t, 128> wide_from;
343 SmallVector<wchar_t, 128> wide_to;
344 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
345 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
347 error_code ec = error_code::success();
348 for (int i = 0; i < 2000; i++) {
349 if (::MoveFileExW(wide_from.begin(), wide_to.begin(),
350 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
351 return error_code::success();
352 ec = windows_error(::GetLastError());
353 if (ec != windows_error::access_denied)
355 // Retry MoveFile() at ACCESS_DENIED.
356 // System scanners (eg. indexer) might open the source file when
357 // It is written and closed.
364 error_code resize_file(const Twine &path, uint64_t size) {
365 SmallString<128> path_storage;
366 SmallVector<wchar_t, 128> path_utf16;
368 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
372 int fd = ::_wopen(path_utf16.begin(), O_BINARY | _O_RDWR, S_IWRITE);
374 return error_code(errno, generic_category());
375 #ifdef HAVE__CHSIZE_S
376 errno_t error = ::_chsize_s(fd, size);
378 errno_t error = ::_chsize(fd, size);
381 return error_code(error, generic_category());
384 error_code exists(const Twine &path, bool &result) {
385 SmallString<128> path_storage;
386 SmallVector<wchar_t, 128> path_utf16;
388 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
392 DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
394 if (attributes == INVALID_FILE_ATTRIBUTES) {
395 // See if the file didn't actually exist.
396 error_code ec = make_error_code(windows_error(::GetLastError()));
397 if (ec != windows_error::file_not_found &&
398 ec != windows_error::path_not_found)
403 return error_code::success();
406 bool can_write(const Twine &Path) {
407 // FIXME: take security attributes into account.
408 SmallString<128> PathStorage;
409 SmallVector<wchar_t, 128> PathUtf16;
411 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
414 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
415 return (Attr != INVALID_FILE_ATTRIBUTES) && !(Attr & FILE_ATTRIBUTE_READONLY);
418 bool can_execute(const Twine &Path) {
419 SmallString<128> PathStorage;
420 SmallVector<wchar_t, 128> PathUtf16;
422 if (UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
425 DWORD Attr = ::GetFileAttributesW(PathUtf16.begin());
426 return Attr != INVALID_FILE_ATTRIBUTES;
429 bool equivalent(file_status A, file_status B) {
430 assert(status_known(A) && status_known(B));
431 return A.FileIndexHigh == B.FileIndexHigh &&
432 A.FileIndexLow == B.FileIndexLow &&
433 A.FileSizeHigh == B.FileSizeHigh &&
434 A.FileSizeLow == B.FileSizeLow &&
435 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
436 A.LastWriteTimeLow == B.LastWriteTimeLow &&
437 A.VolumeSerialNumber == B.VolumeSerialNumber;
440 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
441 file_status fsA, fsB;
442 if (error_code ec = status(A, fsA)) return ec;
443 if (error_code ec = status(B, fsB)) return ec;
444 result = equivalent(fsA, fsB);
445 return error_code::success();
448 static bool isReservedName(StringRef path) {
449 // This list of reserved names comes from MSDN, at:
450 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
451 static const char *sReservedNames[] = { "nul", "con", "prn", "aux",
452 "com1", "com2", "com3", "com4", "com5", "com6",
453 "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
454 "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9" };
456 // First, check to see if this is a device namespace, which always
457 // starts with \\.\, since device namespaces are not legal file paths.
458 if (path.startswith("\\\\.\\"))
461 // Then compare against the list of ancient reserved names
462 for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
463 if (path.equals_lower(sReservedNames[i]))
467 // The path isn't what we consider reserved.
471 static error_code getStatus(HANDLE FileHandle, file_status &Result) {
472 if (FileHandle == INVALID_HANDLE_VALUE)
473 goto handle_status_error;
475 switch (::GetFileType(FileHandle)) {
477 llvm_unreachable("Don't know anything about this file type");
478 case FILE_TYPE_UNKNOWN: {
479 DWORD Err = ::GetLastError();
481 return windows_error(Err);
482 Result = file_status(file_type::type_unknown);
483 return error_code::success();
488 Result = file_status(file_type::character_file);
489 return error_code::success();
491 Result = file_status(file_type::fifo_file);
492 return error_code::success();
495 BY_HANDLE_FILE_INFORMATION Info;
496 if (!::GetFileInformationByHandle(FileHandle, &Info))
497 goto handle_status_error;
500 file_type Type = (Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
501 ? file_type::directory_file
502 : file_type::regular_file;
504 file_status(Type, Info.ftLastWriteTime.dwHighDateTime,
505 Info.ftLastWriteTime.dwLowDateTime,
506 Info.dwVolumeSerialNumber, Info.nFileSizeHigh,
507 Info.nFileSizeLow, Info.nFileIndexHigh, Info.nFileIndexLow);
508 return error_code::success();
512 error_code EC = windows_error(::GetLastError());
513 if (EC == windows_error::file_not_found ||
514 EC == windows_error::path_not_found)
515 Result = file_status(file_type::file_not_found);
516 else if (EC == windows_error::sharing_violation)
517 Result = file_status(file_type::type_unknown);
519 Result = file_status(file_type::status_error);
523 error_code status(const Twine &path, file_status &result) {
524 SmallString<128> path_storage;
525 SmallVector<wchar_t, 128> path_utf16;
527 StringRef path8 = path.toStringRef(path_storage);
528 if (isReservedName(path8)) {
529 result = file_status(file_type::character_file);
530 return error_code::success();
533 if (error_code ec = UTF8ToUTF16(path8, path_utf16))
536 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
537 if (attr == INVALID_FILE_ATTRIBUTES)
538 return getStatus(INVALID_HANDLE_VALUE, result);
540 // Handle reparse points.
541 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
543 ::CreateFileW(path_utf16.begin(),
544 0, // Attributes only.
545 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
548 FILE_FLAG_BACKUP_SEMANTICS,
551 return getStatus(INVALID_HANDLE_VALUE, result);
555 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
556 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
557 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0));
559 return getStatus(INVALID_HANDLE_VALUE, result);
561 return getStatus(h, result);
564 error_code status(int FD, file_status &Result) {
565 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
566 return getStatus(FileHandle, Result);
569 error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
571 UI.QuadPart = Time.toWin32Time();
573 FT.dwLowDateTime = UI.LowPart;
574 FT.dwHighDateTime = UI.HighPart;
575 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
576 if (!SetFileTime(FileHandle, NULL, &FT, &FT))
577 return windows_error(::GetLastError());
578 return error_code::success();
581 error_code get_magic(const Twine &path, uint32_t len,
582 SmallVectorImpl<char> &result) {
583 SmallString<128> path_storage;
584 SmallVector<wchar_t, 128> path_utf16;
587 // Convert path to UTF-16.
588 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
593 HANDLE file = ::CreateFileW(c_str(path_utf16),
598 FILE_ATTRIBUTE_READONLY,
600 if (file == INVALID_HANDLE_VALUE)
601 return windows_error(::GetLastError());
607 DWORD bytes_read = 0;
608 BOOL read_success = ::ReadFile(file, result.data(), len, &bytes_read, NULL);
609 error_code ec = windows_error(::GetLastError());
611 if (!read_success || (bytes_read != len)) {
612 // Set result size to the number of bytes read if it's valid.
613 if (bytes_read <= len)
614 result.set_size(bytes_read);
615 // ERROR_HANDLE_EOF is mapped to errc::value_too_large.
619 result.set_size(len);
620 return error_code::success();
623 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
625 // Make sure that the requested size fits within SIZE_T.
626 if (Size > std::numeric_limits<SIZE_T>::max()) {
627 if (FileDescriptor) {
629 _close(FileDescriptor);
631 ::CloseHandle(FileHandle);
632 return make_error_code(errc::invalid_argument);
637 case readonly: flprotect = PAGE_READONLY; break;
638 case readwrite: flprotect = PAGE_READWRITE; break;
639 case priv: flprotect = PAGE_WRITECOPY; break;
643 ::CreateFileMappingW(FileHandle, 0, flprotect,
644 (Offset + Size) >> 32,
645 (Offset + Size) & 0xffffffff,
647 if (FileMappingHandle == NULL) {
648 error_code ec = windows_error(GetLastError());
649 if (FileDescriptor) {
651 _close(FileDescriptor);
653 ::CloseHandle(FileHandle);
657 DWORD dwDesiredAccess;
659 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
660 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
661 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
663 Mapping = ::MapViewOfFile(FileMappingHandle,
668 if (Mapping == NULL) {
669 error_code ec = windows_error(GetLastError());
670 ::CloseHandle(FileMappingHandle);
671 if (FileDescriptor) {
673 _close(FileDescriptor);
675 ::CloseHandle(FileHandle);
680 MEMORY_BASIC_INFORMATION mbi;
681 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
683 error_code ec = windows_error(GetLastError());
684 ::UnmapViewOfFile(Mapping);
685 ::CloseHandle(FileMappingHandle);
686 if (FileDescriptor) {
688 _close(FileDescriptor);
690 ::CloseHandle(FileHandle);
693 Size = mbi.RegionSize;
696 // Close all the handles except for the view. It will keep the other handles
698 ::CloseHandle(FileMappingHandle);
699 if (FileDescriptor) {
701 _close(FileDescriptor); // Also closes FileHandle.
703 ::CloseHandle(FileHandle);
704 return error_code::success();
707 mapped_file_region::mapped_file_region(const Twine &path,
716 , FileHandle(INVALID_HANDLE_VALUE)
717 , FileMappingHandle() {
718 SmallString<128> path_storage;
719 SmallVector<wchar_t, 128> path_utf16;
721 // Convert path to UTF-16.
722 if ((ec = UTF8ToUTF16(path.toStringRef(path_storage), path_utf16)))
725 // Get file handle for creating a file mapping.
726 FileHandle = ::CreateFileW(c_str(path_utf16),
727 Mode == readonly ? GENERIC_READ
728 : GENERIC_READ | GENERIC_WRITE,
729 Mode == readonly ? FILE_SHARE_READ
732 Mode == readonly ? OPEN_EXISTING
734 Mode == readonly ? FILE_ATTRIBUTE_READONLY
735 : FILE_ATTRIBUTE_NORMAL,
737 if (FileHandle == INVALID_HANDLE_VALUE) {
738 ec = windows_error(::GetLastError());
743 ec = init(FileDescriptor, true, offset);
745 Mapping = FileMappingHandle = 0;
746 FileHandle = INVALID_HANDLE_VALUE;
751 mapped_file_region::mapped_file_region(int fd,
761 , FileHandle(INVALID_HANDLE_VALUE)
762 , FileMappingHandle() {
763 FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
764 if (FileHandle == INVALID_HANDLE_VALUE) {
766 _close(FileDescriptor);
768 ec = make_error_code(errc::bad_file_descriptor);
772 ec = init(FileDescriptor, closefd, offset);
774 Mapping = FileMappingHandle = 0;
775 FileHandle = INVALID_HANDLE_VALUE;
780 mapped_file_region::~mapped_file_region() {
782 ::UnmapViewOfFile(Mapping);
785 #if LLVM_HAS_RVALUE_REFERENCES
786 mapped_file_region::mapped_file_region(mapped_file_region &&other)
789 , Mapping(other.Mapping)
790 , FileDescriptor(other.FileDescriptor)
791 , FileHandle(other.FileHandle)
792 , FileMappingHandle(other.FileMappingHandle) {
793 other.Mapping = other.FileMappingHandle = 0;
794 other.FileHandle = INVALID_HANDLE_VALUE;
795 other.FileDescriptor = 0;
799 mapped_file_region::mapmode mapped_file_region::flags() const {
800 assert(Mapping && "Mapping failed but used anyway!");
804 uint64_t mapped_file_region::size() const {
805 assert(Mapping && "Mapping failed but used anyway!");
809 char *mapped_file_region::data() const {
810 assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
811 assert(Mapping && "Mapping failed but used anyway!");
812 return reinterpret_cast<char*>(Mapping);
815 const char *mapped_file_region::const_data() const {
816 assert(Mapping && "Mapping failed but used anyway!");
817 return reinterpret_cast<const char*>(Mapping);
820 int mapped_file_region::alignment() {
822 ::GetSystemInfo(&SysInfo);
823 return SysInfo.dwAllocationGranularity;
826 error_code detail::directory_iterator_construct(detail::DirIterState &it,
828 SmallVector<wchar_t, 128> path_utf16;
830 if (error_code ec = UTF8ToUTF16(path,
834 // Convert path to the format that Windows is happy with.
835 if (path_utf16.size() > 0 &&
836 !is_separator(path_utf16[path.size() - 1]) &&
837 path_utf16[path.size() - 1] != L':') {
838 path_utf16.push_back(L'\\');
839 path_utf16.push_back(L'*');
841 path_utf16.push_back(L'*');
844 // Get the first directory entry.
845 WIN32_FIND_DATAW FirstFind;
846 ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
848 return windows_error(::GetLastError());
850 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
851 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
852 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
853 FirstFind.cFileName[1] == L'.'))
854 if (!::FindNextFileW(FindHandle, &FirstFind)) {
855 error_code ec = windows_error(::GetLastError());
857 if (ec == windows_error::no_more_files)
858 return detail::directory_iterator_destruct(it);
861 FilenameLen = ::wcslen(FirstFind.cFileName);
863 // Construct the current directory entry.
864 SmallString<128> directory_entry_name_utf8;
865 if (error_code ec = UTF16ToUTF8(FirstFind.cFileName,
866 ::wcslen(FirstFind.cFileName),
867 directory_entry_name_utf8))
870 it.IterationHandle = intptr_t(FindHandle.take());
871 SmallString<128> directory_entry_path(path);
872 path::append(directory_entry_path, directory_entry_name_utf8.str());
873 it.CurrentEntry = directory_entry(directory_entry_path.str());
875 return error_code::success();
878 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
879 if (it.IterationHandle != 0)
880 // Closes the handle if it's valid.
881 ScopedFindHandle close(HANDLE(it.IterationHandle));
882 it.IterationHandle = 0;
883 it.CurrentEntry = directory_entry();
884 return error_code::success();
887 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
888 WIN32_FIND_DATAW FindData;
889 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
890 error_code ec = windows_error(::GetLastError());
892 if (ec == windows_error::no_more_files)
893 return detail::directory_iterator_destruct(it);
897 size_t FilenameLen = ::wcslen(FindData.cFileName);
898 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
899 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
900 FindData.cFileName[1] == L'.'))
901 return directory_iterator_increment(it);
903 SmallString<128> directory_entry_path_utf8;
904 if (error_code ec = UTF16ToUTF8(FindData.cFileName,
905 ::wcslen(FindData.cFileName),
906 directory_entry_path_utf8))
909 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
910 return error_code::success();
913 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
914 bool map_writable, void *&result) {
915 assert(0 && "NOT IMPLEMENTED");
916 return windows_error::invalid_function;
919 error_code unmap_file_pages(void *base, size_t size) {
920 assert(0 && "NOT IMPLEMENTED");
921 return windows_error::invalid_function;
924 error_code openFileForRead(const Twine &Name, int &ResultFD) {
925 SmallString<128> PathStorage;
926 SmallVector<wchar_t, 128> PathUTF16;
928 if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
932 HANDLE H = ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
933 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
934 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
935 if (H == INVALID_HANDLE_VALUE) {
936 error_code EC = windows_error(::GetLastError());
937 // Provide a better error message when trying to open directories.
938 // This only runs if we failed to open the file, so there is probably
939 // no performances issues.
940 if (EC != windows_error::access_denied)
942 if (is_directory(Name))
943 return error_code(errc::is_a_directory, posix_category());
947 int FD = ::_open_osfhandle(intptr_t(H), 0);
950 return windows_error::invalid_handle;
954 return error_code::success();
957 error_code openFileForWrite(const Twine &Name, int &ResultFD,
958 sys::fs::OpenFlags Flags, unsigned Mode) {
959 // Verify that we don't have both "append" and "excl".
960 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
961 "Cannot specify both 'excl' and 'append' file creation flags!");
963 SmallString<128> PathStorage;
964 SmallVector<wchar_t, 128> PathUTF16;
966 if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
970 DWORD CreationDisposition;
972 CreationDisposition = CREATE_NEW;
973 else if (Flags & F_Append)
974 CreationDisposition = OPEN_ALWAYS;
976 CreationDisposition = CREATE_ALWAYS;
978 HANDLE H = ::CreateFileW(PathUTF16.begin(), GENERIC_WRITE,
979 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
980 CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
982 if (H == INVALID_HANDLE_VALUE) {
983 error_code EC = windows_error(::GetLastError());
984 // Provide a better error message when trying to open directories.
985 // This only runs if we failed to open the file, so there is probably
986 // no performances issues.
987 if (EC != windows_error::access_denied)
989 if (is_directory(Name))
990 return error_code(errc::is_a_directory, posix_category());
995 if (Flags & F_Append)
996 OpenFlags |= _O_APPEND;
998 if (!(Flags & F_Binary))
999 OpenFlags |= _O_TEXT;
1001 int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
1004 return windows_error::invalid_handle;
1008 return error_code::success();
1010 } // end namespace fs
1014 bool home_directory(SmallVectorImpl<char> &result) {
1015 wchar_t Path[MAX_PATH];
1016 if (::SHGetFolderPathW(0, CSIDL_APPDATA | CSIDL_FLAG_CREATE, 0,
1017 /*SHGFP_TYPE_CURRENT*/0, Path) != S_OK)
1020 if (UTF16ToUTF8(Path, ::wcslen(Path), result))
1026 } // end namespace path
1029 llvm::error_code UTF8ToUTF16(llvm::StringRef utf8,
1030 llvm::SmallVectorImpl<wchar_t> &utf16) {
1031 if (!utf8.empty()) {
1032 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
1033 utf8.size(), utf16.begin(), 0);
1036 return llvm::windows_error(::GetLastError());
1038 utf16.reserve(len + 1);
1039 utf16.set_size(len);
1041 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
1042 utf8.size(), utf16.begin(), utf16.size());
1045 return llvm::windows_error(::GetLastError());
1048 // Make utf16 null terminated.
1052 return llvm::error_code::success();
1055 llvm::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
1056 llvm::SmallVectorImpl<char> &utf8) {
1059 int len = ::WideCharToMultiByte(CP_UTF8, 0, utf16, utf16_len, utf8.begin(),
1063 return llvm::windows_error(::GetLastError());
1068 // Now do the actual conversion.
1069 len = ::WideCharToMultiByte(CP_UTF8, 0, utf16, utf16_len, utf8.data(),
1070 utf8.size(), NULL, NULL);
1073 return llvm::windows_error(::GetLastError());
1076 // Make utf8 null terminated.
1080 return llvm::error_code::success();
1082 } // end namespace windows
1083 } // end namespace sys
1084 } // end namespace llvm