1 //===- llvm/Support/Win32/PathV2.cpp - 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 //===----------------------------------------------------------------------===//
24 #include <sys/types.h>
26 // MinGW doesn't define this.
27 #ifndef _ERRNO_T_DEFINED
28 #define _ERRNO_T_DEFINED
35 typedef BOOLEAN (WINAPI *PtrCreateSymbolicLinkW)(
36 /*__in*/ LPCWSTR lpSymlinkFileName,
37 /*__in*/ LPCWSTR lpTargetFileName,
38 /*__in*/ DWORD dwFlags);
40 PtrCreateSymbolicLinkW create_symbolic_link_api = PtrCreateSymbolicLinkW(
41 ::GetProcAddress(::GetModuleHandleA("kernel32.dll"),
42 "CreateSymbolicLinkW"));
44 error_code UTF8ToUTF16(const StringRef &utf8,
45 SmallVectorImpl<wchar_t> &utf16) {
46 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
47 utf8.begin(), utf8.size(),
51 return windows_error(::GetLastError());
53 utf16.reserve(len + 1);
56 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
57 utf8.begin(), utf8.size(),
58 utf16.begin(), utf16.size());
61 return windows_error(::GetLastError());
63 // Make utf16 null terminated.
70 error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
71 SmallVectorImpl<char> &utf8) {
73 int len = ::WideCharToMultiByte(CP_UTF8, 0,
79 return windows_error(::GetLastError());
84 // Now do the actual conversion.
85 len = ::WideCharToMultiByte(CP_UTF8, 0,
87 utf8.data(), utf8.size(),
91 return windows_error(::GetLastError());
93 // Make utf8 null terminated.
100 error_code TempDir(SmallVectorImpl<wchar_t> &result) {
102 DWORD len = ::GetTempPathW(result.capacity(), result.begin());
105 return windows_error(::GetLastError());
107 if (len > result.capacity()) {
112 result.set_size(len);
116 // Forwarder for ScopedHandle.
117 BOOL WINAPI CryptReleaseContext(HCRYPTPROV Provider) {
118 return ::CryptReleaseContext(Provider, 0);
121 typedef ScopedHandle<HCRYPTPROV, uintptr_t(-1),
122 BOOL (WINAPI*)(HCRYPTPROV), CryptReleaseContext>
124 bool is_separator(const wchar_t value) {
139 error_code current_path(SmallVectorImpl<char> &result) {
140 SmallVector<wchar_t, 128> cur_path;
141 cur_path.reserve(128);
143 DWORD len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
145 // A zero return value indicates a failure other than insufficient space.
147 return windows_error(::GetLastError());
149 // If there's insufficient space, the len returned is larger than the len
151 if (len > cur_path.capacity()) {
152 cur_path.reserve(len);
156 cur_path.set_size(len);
157 // cur_path now holds the current directory in utf-16. Convert to utf-8.
159 // Find out how much space we need. Sadly, this function doesn't return the
160 // size needed unless you tell it the result size is 0, which means you
161 // _always_ have to call it twice.
162 len = ::WideCharToMultiByte(CP_UTF8, 0,
163 cur_path.data(), cur_path.size(),
168 return make_error_code(windows_error(::GetLastError()));
171 result.set_size(len);
172 // Now do the actual conversion.
173 len = ::WideCharToMultiByte(CP_UTF8, 0,
174 cur_path.data(), cur_path.size(),
175 result.data(), result.size(),
178 return windows_error(::GetLastError());
183 error_code copy_file(const Twine &from, const Twine &to, copy_option copt) {
185 SmallString<128> from_storage;
186 SmallString<128> to_storage;
187 StringRef f = from.toStringRef(from_storage);
188 StringRef t = to.toStringRef(to_storage);
190 // Convert to utf-16.
191 SmallVector<wchar_t, 128> wide_from;
192 SmallVector<wchar_t, 128> wide_to;
193 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
194 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
197 BOOL res = ::CopyFileW(wide_from.begin(), wide_to.begin(),
198 copt != copy_option::overwrite_if_exists);
201 return windows_error(::GetLastError());
206 error_code create_directory(const Twine &path, bool &existed) {
207 SmallString<128> path_storage;
208 SmallVector<wchar_t, 128> path_utf16;
210 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
214 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
215 error_code ec = windows_error(::GetLastError());
216 if (ec == windows_error::already_exists)
226 error_code create_hard_link(const Twine &to, const Twine &from) {
228 SmallString<128> from_storage;
229 SmallString<128> to_storage;
230 StringRef f = from.toStringRef(from_storage);
231 StringRef t = to.toStringRef(to_storage);
233 // Convert to utf-16.
234 SmallVector<wchar_t, 128> wide_from;
235 SmallVector<wchar_t, 128> wide_to;
236 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
237 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
239 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
240 return windows_error(::GetLastError());
245 error_code create_symlink(const Twine &to, const Twine &from) {
246 // Only do it if the function is available at runtime.
247 if (!create_symbolic_link_api)
248 return make_error_code(errc::function_not_supported);
251 SmallString<128> from_storage;
252 SmallString<128> to_storage;
253 StringRef f = from.toStringRef(from_storage);
254 StringRef t = to.toStringRef(to_storage);
256 // Convert to utf-16.
257 SmallVector<wchar_t, 128> wide_from;
258 SmallVector<wchar_t, 128> wide_to;
259 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
260 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
262 if (!create_symbolic_link_api(wide_from.begin(), wide_to.begin(), 0))
263 return windows_error(::GetLastError());
268 error_code remove(const Twine &path, bool &existed) {
269 SmallString<128> path_storage;
270 SmallVector<wchar_t, 128> path_utf16;
272 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
276 if (!::DeleteFileW(path_utf16.begin())) {
277 error_code ec = windows_error(::GetLastError());
278 if (ec != windows_error::file_not_found)
287 error_code rename(const Twine &from, const Twine &to) {
289 SmallString<128> from_storage;
290 SmallString<128> to_storage;
291 StringRef f = from.toStringRef(from_storage);
292 StringRef t = to.toStringRef(to_storage);
294 // Convert to utf-16.
295 SmallVector<wchar_t, 128> wide_from;
296 SmallVector<wchar_t, 128> wide_to;
297 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
298 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
300 if (!::MoveFileW(wide_from.begin(), wide_to.begin()))
301 return windows_error(::GetLastError());
306 error_code resize_file(const Twine &path, uint64_t size) {
307 SmallString<128> path_storage;
308 SmallVector<wchar_t, 128> path_utf16;
310 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
314 int fd = ::_wopen(path_utf16.begin(), O_BINARY, S_IREAD | S_IWRITE);
316 return error_code(errno, generic_category());
317 #ifdef HAVE__CHSIZE_S
318 errno_t error = ::_chsize_s(fd, size);
320 errno_t error = ::_chsize(fd, size);
323 return error_code(error, generic_category());
326 error_code exists(const Twine &path, bool &result) {
327 SmallString<128> path_storage;
328 SmallVector<wchar_t, 128> path_utf16;
330 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
334 DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
336 if (attributes == INVALID_FILE_ATTRIBUTES) {
337 // See if the file didn't actually exist.
338 error_code ec = make_error_code(windows_error(::GetLastError()));
339 if (ec != windows_error::file_not_found &&
340 ec != windows_error::path_not_found)
348 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
350 SmallString<128> a_storage;
351 SmallString<128> b_storage;
352 StringRef a = A.toStringRef(a_storage);
353 StringRef b = B.toStringRef(b_storage);
355 // Convert to utf-16.
356 SmallVector<wchar_t, 128> wide_a;
357 SmallVector<wchar_t, 128> wide_b;
358 if (error_code ec = UTF8ToUTF16(a, wide_a)) return ec;
359 if (error_code ec = UTF8ToUTF16(b, wide_b)) return ec;
362 ::CreateFileW(wide_b.begin(),
364 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
367 FILE_FLAG_BACKUP_SEMANTICS,
371 ::CreateFileW(wide_a.begin(),
373 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
376 FILE_FLAG_BACKUP_SEMANTICS,
379 // If both handles are invalid, it's an error.
380 if (HandleA == INVALID_HANDLE_VALUE &&
381 HandleB == INVALID_HANDLE_VALUE)
382 return windows_error(::GetLastError());
384 // If only one is invalid, it's false.
385 if (HandleA == INVALID_HANDLE_VALUE &&
386 HandleB == INVALID_HANDLE_VALUE) {
391 // Get file information.
392 BY_HANDLE_FILE_INFORMATION InfoA, InfoB;
393 if (!::GetFileInformationByHandle(HandleA, &InfoA))
394 return windows_error(::GetLastError());
395 if (!::GetFileInformationByHandle(HandleB, &InfoB))
396 return windows_error(::GetLastError());
398 // See if it's all the same.
400 InfoA.dwVolumeSerialNumber == InfoB.dwVolumeSerialNumber &&
401 InfoA.nFileIndexHigh == InfoB.nFileIndexHigh &&
402 InfoA.nFileIndexLow == InfoB.nFileIndexLow &&
403 InfoA.nFileSizeHigh == InfoB.nFileSizeHigh &&
404 InfoA.nFileSizeLow == InfoB.nFileSizeLow &&
405 InfoA.ftLastWriteTime.dwLowDateTime ==
406 InfoB.ftLastWriteTime.dwLowDateTime &&
407 InfoA.ftLastWriteTime.dwHighDateTime ==
408 InfoB.ftLastWriteTime.dwHighDateTime;
413 error_code file_size(const Twine &path, uint64_t &result) {
414 SmallString<128> path_storage;
415 SmallVector<wchar_t, 128> path_utf16;
417 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
421 WIN32_FILE_ATTRIBUTE_DATA FileData;
422 if (!::GetFileAttributesExW(path_utf16.begin(),
423 ::GetFileExInfoStandard,
425 return windows_error(::GetLastError());
428 (uint64_t(FileData.nFileSizeHigh) << (sizeof(FileData.nFileSizeLow) * 8))
429 + FileData.nFileSizeLow;
434 error_code status(const Twine &path, file_status &result) {
435 SmallString<128> path_storage;
436 SmallVector<wchar_t, 128> path_utf16;
438 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
442 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
443 if (attr == INVALID_FILE_ATTRIBUTES)
444 goto handle_status_error;
446 // Handle reparse points.
447 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
449 ::CreateFileW(path_utf16.begin(),
450 0, // Attributes only.
451 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
454 FILE_FLAG_BACKUP_SEMANTICS,
456 if (h == INVALID_HANDLE_VALUE)
457 goto handle_status_error;
460 if (attr & FILE_ATTRIBUTE_DIRECTORY)
461 result = file_status(file_type::directory_file);
463 result = file_status(file_type::regular_file);
468 error_code ec = windows_error(::GetLastError());
469 if (ec == windows_error::file_not_found ||
470 ec == windows_error::path_not_found)
471 result = file_status(file_type::file_not_found);
472 else if (ec == windows_error::sharing_violation)
473 result = file_status(file_type::type_unknown);
475 result = file_status(file_type::status_error);
482 error_code unique_file(const Twine &model, int &result_fd,
483 SmallVectorImpl<char> &result_path) {
484 // Use result_path as temp storage.
485 result_path.set_size(0);
486 StringRef m = model.toStringRef(result_path);
488 SmallVector<wchar_t, 128> model_utf16;
489 if (error_code ec = UTF8ToUTF16(m, model_utf16)) return ec;
491 // Make model absolute by prepending a temp directory if it's not already.
492 bool absolute = path::is_absolute(m);
495 SmallVector<wchar_t, 64> temp_dir;
496 if (error_code ec = TempDir(temp_dir)) return ec;
497 // Handle c: by removing it.
498 if (model_utf16.size() > 2 && model_utf16[1] == L':') {
499 model_utf16.erase(model_utf16.begin(), model_utf16.begin() + 2);
501 model_utf16.insert(model_utf16.begin(), temp_dir.begin(), temp_dir.end());
504 // Replace '%' with random chars. From here on, DO NOT modify model. It may be
505 // needed if the randomly chosen path already exists.
506 SmallVector<wchar_t, 128> random_path_utf16;
508 // Get a Crypto Provider for CryptGenRandom.
510 if (!::CryptAcquireContextW(&HCPC,
515 return windows_error(::GetLastError());
516 ScopedCryptContext CryptoProvider(HCPC);
519 random_path_utf16.set_size(0);
520 for (SmallVectorImpl<wchar_t>::const_iterator i = model_utf16.begin(),
521 e = model_utf16.end();
525 if (!::CryptGenRandom(CryptoProvider, 1, &val))
526 return windows_error(::GetLastError());
527 random_path_utf16.push_back("0123456789abcdef"[val & 15]);
530 random_path_utf16.push_back(*i);
532 // Make random_path_utf16 null terminated.
533 random_path_utf16.push_back(0);
534 random_path_utf16.pop_back();
536 // Try to create + open the path.
538 HANDLE TempFileHandle = ::CreateFileW(random_path_utf16.begin(),
539 GENERIC_READ | GENERIC_WRITE,
542 // Return ERROR_FILE_EXISTS if the file
545 FILE_ATTRIBUTE_TEMPORARY,
547 if (TempFileHandle == INVALID_HANDLE_VALUE) {
548 // If the file existed, try again, otherwise, error.
549 error_code ec = windows_error(::GetLastError());
550 if (ec == windows_error::file_exists)
551 goto retry_random_path;
552 // Check for non-existing parent directories.
553 if (ec == windows_error::path_not_found) {
554 // Create the directories using result_path as temp storage.
555 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
556 random_path_utf16.size(), result_path))
558 StringRef p(result_path.begin(), result_path.size());
559 SmallString<64> dir_to_create;
560 for (path::const_iterator i = path::begin(p),
561 e = --path::end(p); i != e; ++i) {
562 path::append(dir_to_create, *i);
564 if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
566 // If c: doesn't exist, bail.
567 if (i->endswith(":"))
570 SmallVector<wchar_t, 64> dir_to_create_utf16;
571 if (error_code ec = UTF8ToUTF16(dir_to_create, dir_to_create_utf16))
574 // Create the directory.
575 if (!::CreateDirectoryW(dir_to_create_utf16.begin(), NULL))
576 return windows_error(::GetLastError());
579 goto retry_create_file;
584 // Set result_path to the utf-8 representation of the path.
585 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
586 random_path_utf16.size(), result_path)) {
587 ::CloseHandle(TempFileHandle);
588 ::DeleteFileW(random_path_utf16.begin());
592 // Convert the Windows API file handle into a C-runtime handle.
593 int fd = ::_open_osfhandle(intptr_t(TempFileHandle), 0);
595 ::CloseHandle(TempFileHandle);
596 ::DeleteFileW(random_path_utf16.begin());
597 // MSDN doesn't say anything about _open_osfhandle setting errno or
598 // GetLastError(), so just return invalid_handle.
599 return windows_error::invalid_handle;
606 error_code directory_iterator_construct(directory_iterator& it,
607 const StringRef &path) {
608 SmallVector<wchar_t, 128> path_utf16;
610 if (error_code ec = UTF8ToUTF16(path,
614 // Convert path to the format that Windows is happy with.
615 if (path_utf16.size() > 0 &&
616 !is_separator(path_utf16[path.size() - 1]) &&
617 path_utf16[path.size() - 1] != L':') {
618 path_utf16.push_back(L'\\');
619 path_utf16.push_back(L'*');
621 path_utf16.push_back(L'*');
624 // Get the first directory entry.
625 WIN32_FIND_DATAW FirstFind;
626 ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
628 return windows_error(::GetLastError());
630 // Construct the current directory entry.
631 SmallString<128> directory_entry_path_utf8;
632 if (error_code ec = UTF16ToUTF8(FirstFind.cFileName,
633 ::wcslen(FirstFind.cFileName),
634 directory_entry_path_utf8))
637 it.IterationHandle = intptr_t(FindHandle.take());
638 it.CurrentEntry = directory_entry(path);
639 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
644 error_code directory_iterator_destruct(directory_iterator& it) {
645 if (it.IterationHandle != 0)
646 // Closes the handle if it's valid.
647 ScopedFindHandle close(HANDLE(it.IterationHandle));
648 it.IterationHandle = 0;
649 it.CurrentEntry = directory_entry();
653 error_code directory_iterator_increment(directory_iterator& it) {
654 WIN32_FIND_DATAW FindData;
655 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
656 error_code ec = windows_error(::GetLastError());
658 if (ec == windows_error::no_more_files)
659 return directory_iterator_destruct(it);
663 SmallString<128> directory_entry_path_utf8;
664 if (error_code ec = UTF16ToUTF8(FindData.cFileName,
665 ::wcslen(FindData.cFileName),
666 directory_entry_path_utf8))
669 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
673 } // end namespace fs
674 } // end namespace sys
675 } // end namespace llvm