1 //===- llvm/Support/Windows/PathV2.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 PathV2 API.
12 //===----------------------------------------------------------------------===//
14 //===----------------------------------------------------------------------===//
15 //=== WARNING: Implementation here must contain only generic Windows code that
16 //=== is guaranteed to work on *all* Windows variants.
17 //===----------------------------------------------------------------------===//
23 #include <sys/types.h>
25 // MinGW doesn't define this.
26 #ifndef _ERRNO_T_DEFINED
27 #define _ERRNO_T_DEFINED
34 typedef BOOLEAN (WINAPI *PtrCreateSymbolicLinkW)(
35 /*__in*/ LPCWSTR lpSymlinkFileName,
36 /*__in*/ LPCWSTR lpTargetFileName,
37 /*__in*/ DWORD dwFlags);
39 PtrCreateSymbolicLinkW create_symbolic_link_api = PtrCreateSymbolicLinkW(
40 ::GetProcAddress(::GetModuleHandleA("kernel32.dll"),
41 "CreateSymbolicLinkW"));
43 error_code UTF8ToUTF16(StringRef utf8, SmallVectorImpl<wchar_t> &utf16) {
44 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
45 utf8.begin(), utf8.size(),
49 return windows_error(::GetLastError());
51 utf16.reserve(len + 1);
54 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
55 utf8.begin(), utf8.size(),
56 utf16.begin(), utf16.size());
59 return windows_error(::GetLastError());
61 // Make utf16 null terminated.
68 error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
69 SmallVectorImpl<char> &utf8) {
71 int len = ::WideCharToMultiByte(CP_UTF8, 0,
77 return windows_error(::GetLastError());
82 // Now do the actual conversion.
83 len = ::WideCharToMultiByte(CP_UTF8, 0,
85 utf8.data(), utf8.size(),
89 return windows_error(::GetLastError());
91 // Make utf8 null terminated.
98 error_code TempDir(SmallVectorImpl<wchar_t> &result) {
100 DWORD len = ::GetTempPathW(result.capacity(), result.begin());
103 return windows_error(::GetLastError());
105 if (len > result.capacity()) {
110 result.set_size(len);
114 bool is_separator(const wchar_t value) {
129 error_code current_path(SmallVectorImpl<char> &result) {
130 SmallVector<wchar_t, 128> cur_path;
131 cur_path.reserve(128);
133 DWORD len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
135 // A zero return value indicates a failure other than insufficient space.
137 return windows_error(::GetLastError());
139 // If there's insufficient space, the len returned is larger than the len
141 if (len > cur_path.capacity()) {
142 cur_path.reserve(len);
146 cur_path.set_size(len);
147 // cur_path now holds the current directory in utf-16. Convert to utf-8.
149 // Find out how much space we need. Sadly, this function doesn't return the
150 // size needed unless you tell it the result size is 0, which means you
151 // _always_ have to call it twice.
152 len = ::WideCharToMultiByte(CP_UTF8, 0,
153 cur_path.data(), cur_path.size(),
158 return make_error_code(windows_error(::GetLastError()));
161 result.set_size(len);
162 // Now do the actual conversion.
163 len = ::WideCharToMultiByte(CP_UTF8, 0,
164 cur_path.data(), cur_path.size(),
165 result.data(), result.size(),
168 return windows_error(::GetLastError());
173 error_code copy_file(const Twine &from, const Twine &to, copy_option copt) {
175 SmallString<128> from_storage;
176 SmallString<128> to_storage;
177 StringRef f = from.toStringRef(from_storage);
178 StringRef t = to.toStringRef(to_storage);
180 // Convert to utf-16.
181 SmallVector<wchar_t, 128> wide_from;
182 SmallVector<wchar_t, 128> wide_to;
183 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
184 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
187 BOOL res = ::CopyFileW(wide_from.begin(), wide_to.begin(),
188 copt != copy_option::overwrite_if_exists);
191 return windows_error(::GetLastError());
196 error_code create_directory(const Twine &path, bool &existed) {
197 SmallString<128> path_storage;
198 SmallVector<wchar_t, 128> path_utf16;
200 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
204 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
205 error_code ec = windows_error(::GetLastError());
206 if (ec == windows_error::already_exists)
216 error_code create_hard_link(const Twine &to, const Twine &from) {
218 SmallString<128> from_storage;
219 SmallString<128> to_storage;
220 StringRef f = from.toStringRef(from_storage);
221 StringRef t = to.toStringRef(to_storage);
223 // Convert to utf-16.
224 SmallVector<wchar_t, 128> wide_from;
225 SmallVector<wchar_t, 128> wide_to;
226 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
227 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
229 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
230 return windows_error(::GetLastError());
235 error_code create_symlink(const Twine &to, const Twine &from) {
236 // Only do it if the function is available at runtime.
237 if (!create_symbolic_link_api)
238 return make_error_code(errc::function_not_supported);
241 SmallString<128> from_storage;
242 SmallString<128> to_storage;
243 StringRef f = from.toStringRef(from_storage);
244 StringRef t = to.toStringRef(to_storage);
246 // Convert to utf-16.
247 SmallVector<wchar_t, 128> wide_from;
248 SmallVector<wchar_t, 128> wide_to;
249 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
250 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
252 if (!create_symbolic_link_api(wide_from.begin(), wide_to.begin(), 0))
253 return windows_error(::GetLastError());
258 error_code remove(const Twine &path, bool &existed) {
259 SmallString<128> path_storage;
260 SmallVector<wchar_t, 128> path_utf16;
263 if (error_code ec = status(path, st))
266 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
270 if (st.type() == file_type::directory_file) {
271 if (!::RemoveDirectoryW(c_str(path_utf16))) {
272 error_code ec = windows_error(::GetLastError());
273 if (ec != windows_error::file_not_found)
279 if (!::DeleteFileW(c_str(path_utf16))) {
280 error_code ec = windows_error(::GetLastError());
281 if (ec != windows_error::file_not_found)
291 error_code rename(const Twine &from, const Twine &to) {
293 SmallString<128> from_storage;
294 SmallString<128> to_storage;
295 StringRef f = from.toStringRef(from_storage);
296 StringRef t = to.toStringRef(to_storage);
298 // Convert to utf-16.
299 SmallVector<wchar_t, 128> wide_from;
300 SmallVector<wchar_t, 128> wide_to;
301 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
302 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
304 if (!::MoveFileExW(wide_from.begin(), wide_to.begin(),
305 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
306 return windows_error(::GetLastError());
311 error_code resize_file(const Twine &path, uint64_t size) {
312 SmallString<128> path_storage;
313 SmallVector<wchar_t, 128> path_utf16;
315 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
319 int fd = ::_wopen(path_utf16.begin(), O_BINARY, S_IREAD | S_IWRITE);
321 return error_code(errno, generic_category());
322 #ifdef HAVE__CHSIZE_S
323 errno_t error = ::_chsize_s(fd, size);
325 errno_t error = ::_chsize(fd, size);
328 return error_code(error, generic_category());
331 error_code exists(const Twine &path, bool &result) {
332 SmallString<128> path_storage;
333 SmallVector<wchar_t, 128> path_utf16;
335 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
339 DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
341 if (attributes == INVALID_FILE_ATTRIBUTES) {
342 // See if the file didn't actually exist.
343 error_code ec = make_error_code(windows_error(::GetLastError()));
344 if (ec != windows_error::file_not_found &&
345 ec != windows_error::path_not_found)
353 bool equivalent(file_status A, file_status B) {
354 assert(status_known(A) && status_known(B));
355 return A.FileIndexHigh == B.FileIndexHigh &&
356 A.FileIndexLow == B.FileIndexLow &&
357 A.FileSizeHigh == B.FileSizeHigh &&
358 A.FileSizeLow == B.FileSizeLow &&
359 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
360 A.LastWriteTimeLow == B.LastWriteTimeLow &&
361 A.VolumeSerialNumber == B.VolumeSerialNumber;
364 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
365 file_status fsA, fsB;
366 if (error_code ec = status(A, fsA)) return ec;
367 if (error_code ec = status(B, fsB)) return ec;
368 result = equivalent(fsA, fsB);
372 error_code file_size(const Twine &path, uint64_t &result) {
373 SmallString<128> path_storage;
374 SmallVector<wchar_t, 128> path_utf16;
376 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
380 WIN32_FILE_ATTRIBUTE_DATA FileData;
381 if (!::GetFileAttributesExW(path_utf16.begin(),
382 ::GetFileExInfoStandard,
384 return windows_error(::GetLastError());
387 (uint64_t(FileData.nFileSizeHigh) << (sizeof(FileData.nFileSizeLow) * 8))
388 + FileData.nFileSizeLow;
393 static bool isReservedName(StringRef path) {
394 // This list of reserved names comes from MSDN, at:
395 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
396 static const char *sReservedNames[] = { "nul", "con", "prn", "aux",
397 "com1", "com2", "com3", "com4", "com5", "com6",
398 "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
399 "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9" };
401 // First, check to see if this is a device namespace, which always
402 // starts with \\.\, since device namespaces are not legal file paths.
403 if (path.startswith("\\\\.\\"))
406 // Then compare against the list of ancient reserved names
407 for (size_t i = 0; i < sizeof(sReservedNames) / sizeof(const char *); ++i) {
408 if (path.equals_lower(sReservedNames[i]))
412 // The path isn't what we consider reserved.
416 error_code status(const Twine &path, file_status &result) {
417 SmallString<128> path_storage;
418 SmallVector<wchar_t, 128> path_utf16;
420 StringRef path8 = path.toStringRef(path_storage);
421 if (isReservedName(path8)) {
422 result = file_status(file_type::character_file);
426 if (error_code ec = UTF8ToUTF16(path8, path_utf16))
429 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
430 if (attr == INVALID_FILE_ATTRIBUTES)
431 goto handle_status_error;
433 // Handle reparse points.
434 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
436 ::CreateFileW(path_utf16.begin(),
437 0, // Attributes only.
438 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
441 FILE_FLAG_BACKUP_SEMANTICS,
444 goto handle_status_error;
447 if (attr & FILE_ATTRIBUTE_DIRECTORY)
448 result = file_status(file_type::directory_file);
450 result = file_status(file_type::regular_file);
452 ::CreateFileW(path_utf16.begin(),
453 0, // Attributes only.
454 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
457 FILE_FLAG_BACKUP_SEMANTICS,
460 goto handle_status_error;
461 BY_HANDLE_FILE_INFORMATION Info;
462 if (!::GetFileInformationByHandle(h, &Info))
463 goto handle_status_error;
464 result.FileIndexHigh = Info.nFileIndexHigh;
465 result.FileIndexLow = Info.nFileIndexLow;
466 result.FileSizeHigh = Info.nFileSizeHigh;
467 result.FileSizeLow = Info.nFileSizeLow;
468 result.LastWriteTimeHigh = Info.ftLastWriteTime.dwHighDateTime;
469 result.LastWriteTimeLow = Info.ftLastWriteTime.dwLowDateTime;
470 result.VolumeSerialNumber = Info.dwVolumeSerialNumber;
476 error_code ec = windows_error(::GetLastError());
477 if (ec == windows_error::file_not_found ||
478 ec == windows_error::path_not_found)
479 result = file_status(file_type::file_not_found);
480 else if (ec == windows_error::sharing_violation)
481 result = file_status(file_type::type_unknown);
483 result = file_status(file_type::status_error);
490 error_code unique_file(const Twine &model, int &result_fd,
491 SmallVectorImpl<char> &result_path,
493 // Use result_path as temp storage.
494 result_path.set_size(0);
495 StringRef m = model.toStringRef(result_path);
497 SmallVector<wchar_t, 128> model_utf16;
498 if (error_code ec = UTF8ToUTF16(m, model_utf16)) return ec;
501 // Make model absolute by prepending a temp directory if it's not already.
502 bool absolute = path::is_absolute(m);
505 SmallVector<wchar_t, 64> temp_dir;
506 if (error_code ec = TempDir(temp_dir)) return ec;
507 // Handle c: by removing it.
508 if (model_utf16.size() > 2 && model_utf16[1] == L':') {
509 model_utf16.erase(model_utf16.begin(), model_utf16.begin() + 2);
511 model_utf16.insert(model_utf16.begin(), temp_dir.begin(), temp_dir.end());
515 // Replace '%' with random chars. From here on, DO NOT modify model. It may be
516 // needed if the randomly chosen path already exists.
517 SmallVector<wchar_t, 128> random_path_utf16;
519 // Get a Crypto Provider for CryptGenRandom.
521 if (!::CryptAcquireContextW(&HCPC,
525 CRYPT_VERIFYCONTEXT))
526 return windows_error(::GetLastError());
527 ScopedCryptContext CryptoProvider(HCPC);
530 random_path_utf16.set_size(0);
531 for (SmallVectorImpl<wchar_t>::const_iterator i = model_utf16.begin(),
532 e = model_utf16.end();
536 if (!::CryptGenRandom(CryptoProvider, 1, &val))
537 return windows_error(::GetLastError());
538 random_path_utf16.push_back("0123456789abcdef"[val & 15]);
541 random_path_utf16.push_back(*i);
543 // Make random_path_utf16 null terminated.
544 random_path_utf16.push_back(0);
545 random_path_utf16.pop_back();
547 // Try to create + open the path.
549 HANDLE TempFileHandle = ::CreateFileW(random_path_utf16.begin(),
550 GENERIC_READ | GENERIC_WRITE,
553 // Return ERROR_FILE_EXISTS if the file
556 FILE_ATTRIBUTE_TEMPORARY,
558 if (TempFileHandle == INVALID_HANDLE_VALUE) {
559 // If the file existed, try again, otherwise, error.
560 error_code ec = windows_error(::GetLastError());
561 if (ec == windows_error::file_exists)
562 goto retry_random_path;
563 // Check for non-existing parent directories.
564 if (ec == windows_error::path_not_found) {
565 // Create the directories using result_path as temp storage.
566 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
567 random_path_utf16.size(), result_path))
569 StringRef p(result_path.begin(), result_path.size());
570 SmallString<64> dir_to_create;
571 for (path::const_iterator i = path::begin(p),
572 e = --path::end(p); i != e; ++i) {
573 path::append(dir_to_create, *i);
575 if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
577 // If c: doesn't exist, bail.
578 if (i->endswith(":"))
581 SmallVector<wchar_t, 64> dir_to_create_utf16;
582 if (error_code ec = UTF8ToUTF16(dir_to_create, dir_to_create_utf16))
585 // Create the directory.
586 if (!::CreateDirectoryW(dir_to_create_utf16.begin(), NULL))
587 return windows_error(::GetLastError());
590 goto retry_create_file;
595 // Set result_path to the utf-8 representation of the path.
596 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
597 random_path_utf16.size(), result_path)) {
598 ::CloseHandle(TempFileHandle);
599 ::DeleteFileW(random_path_utf16.begin());
603 // Convert the Windows API file handle into a C-runtime handle.
604 int fd = ::_open_osfhandle(intptr_t(TempFileHandle), 0);
606 ::CloseHandle(TempFileHandle);
607 ::DeleteFileW(random_path_utf16.begin());
608 // MSDN doesn't say anything about _open_osfhandle setting errno or
609 // GetLastError(), so just return invalid_handle.
610 return windows_error::invalid_handle;
617 error_code get_magic(const Twine &path, uint32_t len,
618 SmallVectorImpl<char> &result) {
619 SmallString<128> path_storage;
620 SmallVector<wchar_t, 128> path_utf16;
623 // Convert path to UTF-16.
624 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
629 HANDLE file = ::CreateFileW(c_str(path_utf16),
634 FILE_ATTRIBUTE_READONLY,
636 if (file == INVALID_HANDLE_VALUE)
637 return windows_error(::GetLastError());
643 DWORD bytes_read = 0;
644 BOOL read_success = ::ReadFile(file, result.data(), len, &bytes_read, NULL);
645 error_code ec = windows_error(::GetLastError());
647 if (!read_success || (bytes_read != len)) {
648 // Set result size to the number of bytes read if it's valid.
649 if (bytes_read <= len)
650 result.set_size(bytes_read);
651 // ERROR_HANDLE_EOF is mapped to errc::value_too_large.
655 result.set_size(len);
659 error_code detail::directory_iterator_construct(detail::DirIterState &it,
661 SmallVector<wchar_t, 128> path_utf16;
663 if (error_code ec = UTF8ToUTF16(path,
667 // Convert path to the format that Windows is happy with.
668 if (path_utf16.size() > 0 &&
669 !is_separator(path_utf16[path.size() - 1]) &&
670 path_utf16[path.size() - 1] != L':') {
671 path_utf16.push_back(L'\\');
672 path_utf16.push_back(L'*');
674 path_utf16.push_back(L'*');
677 // Get the first directory entry.
678 WIN32_FIND_DATAW FirstFind;
679 ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
681 return windows_error(::GetLastError());
683 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
684 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
685 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
686 FirstFind.cFileName[1] == L'.'))
687 if (!::FindNextFileW(FindHandle, &FirstFind)) {
688 error_code ec = windows_error(::GetLastError());
690 if (ec == windows_error::no_more_files)
691 return detail::directory_iterator_destruct(it);
694 FilenameLen = ::wcslen(FirstFind.cFileName);
696 // Construct the current directory entry.
697 SmallString<128> directory_entry_name_utf8;
698 if (error_code ec = UTF16ToUTF8(FirstFind.cFileName,
699 ::wcslen(FirstFind.cFileName),
700 directory_entry_name_utf8))
703 it.IterationHandle = intptr_t(FindHandle.take());
704 SmallString<128> directory_entry_path(path);
705 path::append(directory_entry_path, directory_entry_name_utf8.str());
706 it.CurrentEntry = directory_entry(directory_entry_path.str());
711 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
712 if (it.IterationHandle != 0)
713 // Closes the handle if it's valid.
714 ScopedFindHandle close(HANDLE(it.IterationHandle));
715 it.IterationHandle = 0;
716 it.CurrentEntry = directory_entry();
720 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
721 WIN32_FIND_DATAW FindData;
722 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
723 error_code ec = windows_error(::GetLastError());
725 if (ec == windows_error::no_more_files)
726 return detail::directory_iterator_destruct(it);
730 size_t FilenameLen = ::wcslen(FindData.cFileName);
731 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
732 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
733 FindData.cFileName[1] == L'.'))
734 return directory_iterator_increment(it);
736 SmallString<128> directory_entry_path_utf8;
737 if (error_code ec = UTF16ToUTF8(FindData.cFileName,
738 ::wcslen(FindData.cFileName),
739 directory_entry_path_utf8))
742 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
746 } // end namespace fs
747 } // end namespace sys
748 } // end namespace llvm