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 //===----------------------------------------------------------------------===//
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(StringRef utf8, SmallVectorImpl<wchar_t> &utf16) {
45 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
46 utf8.begin(), utf8.size(),
50 return windows_error(::GetLastError());
52 utf16.reserve(len + 1);
55 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
56 utf8.begin(), utf8.size(),
57 utf16.begin(), utf16.size());
60 return windows_error(::GetLastError());
62 // Make utf16 null terminated.
69 error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
70 SmallVectorImpl<char> &utf8) {
72 int len = ::WideCharToMultiByte(CP_UTF8, 0,
78 return windows_error(::GetLastError());
83 // Now do the actual conversion.
84 len = ::WideCharToMultiByte(CP_UTF8, 0,
86 utf8.data(), utf8.size(),
90 return windows_error(::GetLastError());
92 // Make utf8 null terminated.
99 error_code TempDir(SmallVectorImpl<wchar_t> &result) {
101 DWORD len = ::GetTempPathW(result.capacity(), result.begin());
104 return windows_error(::GetLastError());
106 if (len > result.capacity()) {
111 result.set_size(len);
115 // Forwarder for ScopedHandle.
116 BOOL WINAPI CryptReleaseContext(HCRYPTPROV Provider) {
117 return ::CryptReleaseContext(Provider, 0);
120 typedef ScopedHandle<HCRYPTPROV, uintptr_t(-1),
121 BOOL (WINAPI*)(HCRYPTPROV), CryptReleaseContext>
123 bool is_separator(const wchar_t value) {
138 error_code current_path(SmallVectorImpl<char> &result) {
139 SmallVector<wchar_t, 128> cur_path;
140 cur_path.reserve(128);
142 DWORD len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
144 // A zero return value indicates a failure other than insufficient space.
146 return windows_error(::GetLastError());
148 // If there's insufficient space, the len returned is larger than the len
150 if (len > cur_path.capacity()) {
151 cur_path.reserve(len);
155 cur_path.set_size(len);
156 // cur_path now holds the current directory in utf-16. Convert to utf-8.
158 // Find out how much space we need. Sadly, this function doesn't return the
159 // size needed unless you tell it the result size is 0, which means you
160 // _always_ have to call it twice.
161 len = ::WideCharToMultiByte(CP_UTF8, 0,
162 cur_path.data(), cur_path.size(),
167 return make_error_code(windows_error(::GetLastError()));
170 result.set_size(len);
171 // Now do the actual conversion.
172 len = ::WideCharToMultiByte(CP_UTF8, 0,
173 cur_path.data(), cur_path.size(),
174 result.data(), result.size(),
177 return windows_error(::GetLastError());
182 error_code copy_file(const Twine &from, const Twine &to, copy_option copt) {
184 SmallString<128> from_storage;
185 SmallString<128> to_storage;
186 StringRef f = from.toStringRef(from_storage);
187 StringRef t = to.toStringRef(to_storage);
189 // Convert to utf-16.
190 SmallVector<wchar_t, 128> wide_from;
191 SmallVector<wchar_t, 128> wide_to;
192 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
193 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
196 BOOL res = ::CopyFileW(wide_from.begin(), wide_to.begin(),
197 copt != copy_option::overwrite_if_exists);
200 return windows_error(::GetLastError());
205 error_code create_directory(const Twine &path, bool &existed) {
206 SmallString<128> path_storage;
207 SmallVector<wchar_t, 128> path_utf16;
209 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
213 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
214 error_code ec = windows_error(::GetLastError());
215 if (ec == windows_error::already_exists)
225 error_code create_hard_link(const Twine &to, const Twine &from) {
227 SmallString<128> from_storage;
228 SmallString<128> to_storage;
229 StringRef f = from.toStringRef(from_storage);
230 StringRef t = to.toStringRef(to_storage);
232 // Convert to utf-16.
233 SmallVector<wchar_t, 128> wide_from;
234 SmallVector<wchar_t, 128> wide_to;
235 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
236 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
238 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
239 return windows_error(::GetLastError());
244 error_code create_symlink(const Twine &to, const Twine &from) {
245 // Only do it if the function is available at runtime.
246 if (!create_symbolic_link_api)
247 return make_error_code(errc::function_not_supported);
250 SmallString<128> from_storage;
251 SmallString<128> to_storage;
252 StringRef f = from.toStringRef(from_storage);
253 StringRef t = to.toStringRef(to_storage);
255 // Convert to utf-16.
256 SmallVector<wchar_t, 128> wide_from;
257 SmallVector<wchar_t, 128> wide_to;
258 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
259 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
261 if (!create_symbolic_link_api(wide_from.begin(), wide_to.begin(), 0))
262 return windows_error(::GetLastError());
267 error_code remove(const Twine &path, bool &existed) {
268 SmallString<128> path_storage;
269 SmallVector<wchar_t, 128> path_utf16;
272 if (error_code ec = status(path, st))
275 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
279 if (st.type() == file_type::directory_file) {
280 if (!::RemoveDirectoryW(c_str(path_utf16))) {
281 error_code ec = windows_error(::GetLastError());
282 if (ec != windows_error::file_not_found)
288 if (!::DeleteFileW(c_str(path_utf16))) {
289 error_code ec = windows_error(::GetLastError());
290 if (ec != windows_error::file_not_found)
300 error_code rename(const Twine &from, const Twine &to) {
302 SmallString<128> from_storage;
303 SmallString<128> to_storage;
304 StringRef f = from.toStringRef(from_storage);
305 StringRef t = to.toStringRef(to_storage);
307 // Convert to utf-16.
308 SmallVector<wchar_t, 128> wide_from;
309 SmallVector<wchar_t, 128> wide_to;
310 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
311 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
313 if (!::MoveFileW(wide_from.begin(), wide_to.begin()))
314 return windows_error(::GetLastError());
319 error_code resize_file(const Twine &path, uint64_t size) {
320 SmallString<128> path_storage;
321 SmallVector<wchar_t, 128> path_utf16;
323 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
327 int fd = ::_wopen(path_utf16.begin(), O_BINARY, S_IREAD | S_IWRITE);
329 return error_code(errno, generic_category());
330 #ifdef HAVE__CHSIZE_S
331 errno_t error = ::_chsize_s(fd, size);
333 errno_t error = ::_chsize(fd, size);
336 return error_code(error, generic_category());
339 error_code exists(const Twine &path, bool &result) {
340 SmallString<128> path_storage;
341 SmallVector<wchar_t, 128> path_utf16;
343 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
347 DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
349 if (attributes == INVALID_FILE_ATTRIBUTES) {
350 // See if the file didn't actually exist.
351 error_code ec = make_error_code(windows_error(::GetLastError()));
352 if (ec != windows_error::file_not_found &&
353 ec != windows_error::path_not_found)
361 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
363 SmallString<128> a_storage;
364 SmallString<128> b_storage;
365 StringRef a = A.toStringRef(a_storage);
366 StringRef b = B.toStringRef(b_storage);
368 // Convert to utf-16.
369 SmallVector<wchar_t, 128> wide_a;
370 SmallVector<wchar_t, 128> wide_b;
371 if (error_code ec = UTF8ToUTF16(a, wide_a)) return ec;
372 if (error_code ec = UTF8ToUTF16(b, wide_b)) return ec;
375 ::CreateFileW(wide_b.begin(),
377 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
380 FILE_FLAG_BACKUP_SEMANTICS,
384 ::CreateFileW(wide_a.begin(),
386 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
389 FILE_FLAG_BACKUP_SEMANTICS,
392 // If both handles are invalid, it's an error.
393 if (HandleA == INVALID_HANDLE_VALUE &&
394 HandleB == INVALID_HANDLE_VALUE)
395 return windows_error(::GetLastError());
397 // If only one is invalid, it's false.
398 if (HandleA == INVALID_HANDLE_VALUE &&
399 HandleB == INVALID_HANDLE_VALUE) {
404 // Get file information.
405 BY_HANDLE_FILE_INFORMATION InfoA, InfoB;
406 if (!::GetFileInformationByHandle(HandleA, &InfoA))
407 return windows_error(::GetLastError());
408 if (!::GetFileInformationByHandle(HandleB, &InfoB))
409 return windows_error(::GetLastError());
411 // See if it's all the same.
413 InfoA.dwVolumeSerialNumber == InfoB.dwVolumeSerialNumber &&
414 InfoA.nFileIndexHigh == InfoB.nFileIndexHigh &&
415 InfoA.nFileIndexLow == InfoB.nFileIndexLow &&
416 InfoA.nFileSizeHigh == InfoB.nFileSizeHigh &&
417 InfoA.nFileSizeLow == InfoB.nFileSizeLow &&
418 InfoA.ftLastWriteTime.dwLowDateTime ==
419 InfoB.ftLastWriteTime.dwLowDateTime &&
420 InfoA.ftLastWriteTime.dwHighDateTime ==
421 InfoB.ftLastWriteTime.dwHighDateTime;
426 error_code file_size(const Twine &path, uint64_t &result) {
427 SmallString<128> path_storage;
428 SmallVector<wchar_t, 128> path_utf16;
430 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
434 WIN32_FILE_ATTRIBUTE_DATA FileData;
435 if (!::GetFileAttributesExW(path_utf16.begin(),
436 ::GetFileExInfoStandard,
438 return windows_error(::GetLastError());
441 (uint64_t(FileData.nFileSizeHigh) << (sizeof(FileData.nFileSizeLow) * 8))
442 + FileData.nFileSizeLow;
447 error_code status(const Twine &path, file_status &result) {
448 SmallString<128> path_storage;
449 SmallVector<wchar_t, 128> path_utf16;
451 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
455 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
456 if (attr == INVALID_FILE_ATTRIBUTES)
457 goto handle_status_error;
459 // Handle reparse points.
460 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
462 ::CreateFileW(path_utf16.begin(),
463 0, // Attributes only.
464 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
467 FILE_FLAG_BACKUP_SEMANTICS,
469 if (h == INVALID_HANDLE_VALUE)
470 goto handle_status_error;
473 if (attr & FILE_ATTRIBUTE_DIRECTORY)
474 result = file_status(file_type::directory_file);
476 result = file_status(file_type::regular_file);
481 error_code ec = windows_error(::GetLastError());
482 if (ec == windows_error::file_not_found ||
483 ec == windows_error::path_not_found)
484 result = file_status(file_type::file_not_found);
485 else if (ec == windows_error::sharing_violation)
486 result = file_status(file_type::type_unknown);
488 result = file_status(file_type::status_error);
495 error_code unique_file(const Twine &model, int &result_fd,
496 SmallVectorImpl<char> &result_path) {
497 // Use result_path as temp storage.
498 result_path.set_size(0);
499 StringRef m = model.toStringRef(result_path);
501 SmallVector<wchar_t, 128> model_utf16;
502 if (error_code ec = UTF8ToUTF16(m, model_utf16)) return ec;
504 // Make model absolute by prepending a temp directory if it's not already.
505 bool absolute = path::is_absolute(m);
508 SmallVector<wchar_t, 64> temp_dir;
509 if (error_code ec = TempDir(temp_dir)) return ec;
510 // Handle c: by removing it.
511 if (model_utf16.size() > 2 && model_utf16[1] == L':') {
512 model_utf16.erase(model_utf16.begin(), model_utf16.begin() + 2);
514 model_utf16.insert(model_utf16.begin(), temp_dir.begin(), temp_dir.end());
517 // Replace '%' with random chars. From here on, DO NOT modify model. It may be
518 // needed if the randomly chosen path already exists.
519 SmallVector<wchar_t, 128> random_path_utf16;
521 // Get a Crypto Provider for CryptGenRandom.
523 if (!::CryptAcquireContextW(&HCPC,
528 return windows_error(::GetLastError());
529 ScopedCryptContext CryptoProvider(HCPC);
532 random_path_utf16.set_size(0);
533 for (SmallVectorImpl<wchar_t>::const_iterator i = model_utf16.begin(),
534 e = model_utf16.end();
538 if (!::CryptGenRandom(CryptoProvider, 1, &val))
539 return windows_error(::GetLastError());
540 random_path_utf16.push_back("0123456789abcdef"[val & 15]);
543 random_path_utf16.push_back(*i);
545 // Make random_path_utf16 null terminated.
546 random_path_utf16.push_back(0);
547 random_path_utf16.pop_back();
549 // Try to create + open the path.
551 HANDLE TempFileHandle = ::CreateFileW(random_path_utf16.begin(),
552 GENERIC_READ | GENERIC_WRITE,
555 // Return ERROR_FILE_EXISTS if the file
558 FILE_ATTRIBUTE_TEMPORARY,
560 if (TempFileHandle == INVALID_HANDLE_VALUE) {
561 // If the file existed, try again, otherwise, error.
562 error_code ec = windows_error(::GetLastError());
563 if (ec == windows_error::file_exists)
564 goto retry_random_path;
565 // Check for non-existing parent directories.
566 if (ec == windows_error::path_not_found) {
567 // Create the directories using result_path as temp storage.
568 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
569 random_path_utf16.size(), result_path))
571 StringRef p(result_path.begin(), result_path.size());
572 SmallString<64> dir_to_create;
573 for (path::const_iterator i = path::begin(p),
574 e = --path::end(p); i != e; ++i) {
575 path::append(dir_to_create, *i);
577 if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
579 // If c: doesn't exist, bail.
580 if (i->endswith(":"))
583 SmallVector<wchar_t, 64> dir_to_create_utf16;
584 if (error_code ec = UTF8ToUTF16(dir_to_create, dir_to_create_utf16))
587 // Create the directory.
588 if (!::CreateDirectoryW(dir_to_create_utf16.begin(), NULL))
589 return windows_error(::GetLastError());
592 goto retry_create_file;
597 // Set result_path to the utf-8 representation of the path.
598 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
599 random_path_utf16.size(), result_path)) {
600 ::CloseHandle(TempFileHandle);
601 ::DeleteFileW(random_path_utf16.begin());
605 // Convert the Windows API file handle into a C-runtime handle.
606 int fd = ::_open_osfhandle(intptr_t(TempFileHandle), 0);
608 ::CloseHandle(TempFileHandle);
609 ::DeleteFileW(random_path_utf16.begin());
610 // MSDN doesn't say anything about _open_osfhandle setting errno or
611 // GetLastError(), so just return invalid_handle.
612 return windows_error::invalid_handle;
619 error_code directory_iterator_construct(directory_iterator &it, StringRef path){
620 SmallVector<wchar_t, 128> path_utf16;
622 if (error_code ec = UTF8ToUTF16(path,
626 // Convert path to the format that Windows is happy with.
627 if (path_utf16.size() > 0 &&
628 !is_separator(path_utf16[path.size() - 1]) &&
629 path_utf16[path.size() - 1] != L':') {
630 path_utf16.push_back(L'\\');
631 path_utf16.push_back(L'*');
633 path_utf16.push_back(L'*');
636 // Get the first directory entry.
637 WIN32_FIND_DATAW FirstFind;
638 ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
640 return windows_error(::GetLastError());
642 // Construct the current directory entry.
643 SmallString<128> directory_entry_path_utf8;
644 if (error_code ec = UTF16ToUTF8(FirstFind.cFileName,
645 ::wcslen(FirstFind.cFileName),
646 directory_entry_path_utf8))
649 it.IterationHandle = intptr_t(FindHandle.take());
650 it.CurrentEntry = directory_entry(path);
651 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
656 error_code directory_iterator_destruct(directory_iterator& it) {
657 if (it.IterationHandle != 0)
658 // Closes the handle if it's valid.
659 ScopedFindHandle close(HANDLE(it.IterationHandle));
660 it.IterationHandle = 0;
661 it.CurrentEntry = directory_entry();
665 error_code directory_iterator_increment(directory_iterator& it) {
666 WIN32_FIND_DATAW FindData;
667 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
668 error_code ec = windows_error(::GetLastError());
670 if (ec == windows_error::no_more_files)
671 return directory_iterator_destruct(it);
675 SmallString<128> directory_entry_path_utf8;
676 if (error_code ec = UTF16ToUTF8(FindData.cFileName,
677 ::wcslen(FindData.cFileName),
678 directory_entry_path_utf8))
681 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
685 } // end namespace fs
686 } // end namespace sys
687 } // end namespace llvm