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 make_error_code(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 make_error_code(windows_error(::GetLastError()));
63 // Make utf16 null terminated.
67 return make_error_code(errc::success);
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 make_error_code(windows_error(::GetLastError()));
84 // Now do the actual conversion.
85 len = ::WideCharToMultiByte(CP_UTF8, 0,
87 utf8.data(), utf8.size(),
91 return make_error_code(windows_error(::GetLastError()));
93 // Make utf8 null terminated.
97 return make_error_code(errc::success);
100 error_code TempDir(SmallVectorImpl<wchar_t> &result) {
102 DWORD len = ::GetTempPathW(result.capacity(), result.begin());
105 return make_error_code(windows_error(::GetLastError()));
107 if (len > result.capacity()) {
112 result.set_size(len);
113 return make_error_code(errc::success);
116 struct AutoCryptoProvider {
117 HCRYPTPROV CryptoProvider;
119 ~AutoCryptoProvider() {
120 ::CryptReleaseContext(CryptoProvider, 0);
123 operator HCRYPTPROV() const {return CryptoProvider;}
131 error_code current_path(SmallVectorImpl<char> &result) {
132 SmallVector<wchar_t, 128> cur_path;
133 cur_path.reserve(128);
135 DWORD len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
137 // A zero return value indicates a failure other than insufficient space.
139 return make_error_code(windows_error(::GetLastError()));
141 // If there's insufficient space, the len returned is larger than the len
143 if (len > cur_path.capacity()) {
144 cur_path.reserve(len);
148 cur_path.set_size(len);
149 // cur_path now holds the current directory in utf-16. Convert to utf-8.
151 // Find out how much space we need. Sadly, this function doesn't return the
152 // size needed unless you tell it the result size is 0, which means you
153 // _always_ have to call it twice.
154 len = ::WideCharToMultiByte(CP_UTF8, 0,
155 cur_path.data(), cur_path.size(),
160 return make_error_code(windows_error(::GetLastError()));
163 result.set_size(len);
164 // Now do the actual conversion.
165 len = ::WideCharToMultiByte(CP_UTF8, 0,
166 cur_path.data(), cur_path.size(),
167 result.data(), result.size(),
170 return make_error_code(windows_error(::GetLastError()));
172 return make_error_code(errc::success);
175 } // end namespace path
179 error_code copy_file(const Twine &from, const Twine &to, copy_option copt) {
181 SmallString<128> from_storage;
182 SmallString<128> to_storage;
183 StringRef f = from.toStringRef(from_storage);
184 StringRef t = to.toStringRef(to_storage);
186 // Convert to utf-16.
187 SmallVector<wchar_t, 128> wide_from;
188 SmallVector<wchar_t, 128> wide_to;
189 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
190 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
193 BOOL res = ::CopyFileW(wide_from.begin(), wide_to.begin(),
194 copt != copy_option::overwrite_if_exists);
197 return make_error_code(windows_error(::GetLastError()));
199 return make_error_code(errc::success);
202 error_code create_directory(const Twine &path, bool &existed) {
203 SmallString<128> path_storage;
204 SmallVector<wchar_t, 128> path_utf16;
206 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
210 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
211 error_code ec = make_error_code(windows_error(::GetLastError()));
212 if (ec == make_error_code(windows_error::already_exists))
219 return make_error_code(errc::success);
222 error_code create_hard_link(const Twine &to, const Twine &from) {
224 SmallString<128> from_storage;
225 SmallString<128> to_storage;
226 StringRef f = from.toStringRef(from_storage);
227 StringRef t = to.toStringRef(to_storage);
229 // Convert to utf-16.
230 SmallVector<wchar_t, 128> wide_from;
231 SmallVector<wchar_t, 128> wide_to;
232 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
233 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
235 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
236 return make_error_code(windows_error(::GetLastError()));
238 return make_error_code(errc::success);
241 error_code create_symlink(const Twine &to, const Twine &from) {
242 // Only do it if the function is available at runtime.
243 if (!create_symbolic_link_api)
244 return make_error_code(errc::function_not_supported);
247 SmallString<128> from_storage;
248 SmallString<128> to_storage;
249 StringRef f = from.toStringRef(from_storage);
250 StringRef t = to.toStringRef(to_storage);
252 // Convert to utf-16.
253 SmallVector<wchar_t, 128> wide_from;
254 SmallVector<wchar_t, 128> wide_to;
255 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
256 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
258 if (!create_symbolic_link_api(wide_from.begin(), wide_to.begin(), 0))
259 return make_error_code(windows_error(::GetLastError()));
261 return make_error_code(errc::success);
264 error_code remove(const Twine &path, bool &existed) {
265 SmallString<128> path_storage;
266 SmallVector<wchar_t, 128> path_utf16;
268 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
272 if (!::DeleteFileW(path_utf16.begin())) {
273 error_code ec = make_error_code(windows_error(::GetLastError()));
274 if (ec != make_error_code(windows_error::file_not_found))
280 return make_error_code(errc::success);
283 error_code rename(const Twine &from, const Twine &to) {
285 SmallString<128> from_storage;
286 SmallString<128> to_storage;
287 StringRef f = from.toStringRef(from_storage);
288 StringRef t = to.toStringRef(to_storage);
290 // Convert to utf-16.
291 SmallVector<wchar_t, 128> wide_from;
292 SmallVector<wchar_t, 128> wide_to;
293 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
294 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
296 if (!::MoveFileW(wide_from.begin(), wide_to.begin()))
297 return make_error_code(windows_error(::GetLastError()));
299 return make_error_code(errc::success);
302 error_code resize_file(const Twine &path, uint64_t size) {
303 SmallString<128> path_storage;
304 SmallVector<wchar_t, 128> path_utf16;
306 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
310 int fd = ::_wopen(path_utf16.begin(), O_BINARY, S_IREAD | S_IWRITE);
312 return error_code(errno, generic_category());
313 #ifdef HAVE__CHSIZE_S
314 errno_t error = ::_chsize_s(fd, size);
316 errno_t error = ::_chsize(fd, size);
319 return error_code(error, generic_category());
322 error_code exists(const Twine &path, bool &result) {
323 SmallString<128> path_storage;
324 SmallVector<wchar_t, 128> path_utf16;
326 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
330 DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
332 if (attributes == INVALID_FILE_ATTRIBUTES) {
333 // See if the file didn't actually exist.
334 error_code ec = make_error_code(windows_error(::GetLastError()));
335 if (ec != error_code(windows_error::file_not_found) &&
336 ec != error_code(windows_error::path_not_found))
341 return make_error_code(errc::success);
344 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
346 SmallString<128> a_storage;
347 SmallString<128> b_storage;
348 StringRef a = A.toStringRef(a_storage);
349 StringRef b = B.toStringRef(b_storage);
351 // Convert to utf-16.
352 SmallVector<wchar_t, 128> wide_a;
353 SmallVector<wchar_t, 128> wide_b;
354 if (error_code ec = UTF8ToUTF16(a, wide_a)) return ec;
355 if (error_code ec = UTF8ToUTF16(b, wide_b)) return ec;
358 ::CreateFileW(wide_b.begin(),
360 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
363 FILE_FLAG_BACKUP_SEMANTICS,
367 ::CreateFileW(wide_a.begin(),
369 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
372 FILE_FLAG_BACKUP_SEMANTICS,
375 // If both handles are invalid, it's an error.
376 if (HandleA == INVALID_HANDLE_VALUE &&
377 HandleB == INVALID_HANDLE_VALUE)
378 return make_error_code(windows_error(::GetLastError()));
380 // If only one is invalid, it's false.
381 if (HandleA == INVALID_HANDLE_VALUE &&
382 HandleB == INVALID_HANDLE_VALUE) {
384 return make_error_code(errc::success);
387 // Get file information.
388 BY_HANDLE_FILE_INFORMATION InfoA, InfoB;
389 if (!::GetFileInformationByHandle(HandleA, &InfoA))
390 return make_error_code(windows_error(::GetLastError()));
391 if (!::GetFileInformationByHandle(HandleB, &InfoB))
392 return make_error_code(windows_error(::GetLastError()));
394 // See if it's all the same.
396 InfoA.dwVolumeSerialNumber == InfoB.dwVolumeSerialNumber &&
397 InfoA.nFileIndexHigh == InfoB.nFileIndexHigh &&
398 InfoA.nFileIndexLow == InfoB.nFileIndexLow &&
399 InfoA.nFileSizeHigh == InfoB.nFileSizeHigh &&
400 InfoA.nFileSizeLow == InfoB.nFileSizeLow &&
401 InfoA.ftLastWriteTime.dwLowDateTime ==
402 InfoB.ftLastWriteTime.dwLowDateTime &&
403 InfoA.ftLastWriteTime.dwHighDateTime ==
404 InfoB.ftLastWriteTime.dwHighDateTime;
406 return make_error_code(errc::success);
409 error_code file_size(const Twine &path, uint64_t &result) {
410 SmallString<128> path_storage;
411 SmallVector<wchar_t, 128> path_utf16;
413 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
417 WIN32_FILE_ATTRIBUTE_DATA FileData;
418 if (!::GetFileAttributesExW(path_utf16.begin(),
419 ::GetFileExInfoStandard,
421 return make_error_code(windows_error(::GetLastError()));
424 (uint64_t(FileData.nFileSizeHigh) << (sizeof(FileData.nFileSizeLow) * 8))
425 + FileData.nFileSizeLow;
427 return make_error_code(errc::success);
430 error_code unique_file(const Twine &model, int &result_fd,
431 SmallVectorImpl<char> &result_path) {
432 // Use result_path as temp storage.
433 result_path.set_size(0);
434 StringRef m = model.toStringRef(result_path);
436 SmallVector<wchar_t, 128> model_utf16;
437 if (error_code ec = UTF8ToUTF16(m, model_utf16)) return ec;
439 // Make model absolute by prepending a temp directory if it's not already.
441 if (error_code ec = path::is_absolute(m, absolute)) return ec;
444 SmallVector<wchar_t, 64> temp_dir;
445 if (error_code ec = TempDir(temp_dir)) return ec;
446 // Handle c: by removing it.
447 if (model_utf16.size() > 2 && model_utf16[1] == L':') {
448 model_utf16.erase(model_utf16.begin(), model_utf16.begin() + 2);
450 model_utf16.insert(model_utf16.begin(), temp_dir.begin(), temp_dir.end());
453 // Replace '%' with random chars. From here on, DO NOT modify model. It may be
454 // needed if the randomly chosen path already exists.
455 SmallVector<wchar_t, 128> random_path_utf16;
457 // Get a Crypto Provider for CryptGenRandom.
458 AutoCryptoProvider CryptoProvider;
459 BOOL success = ::CryptAcquireContextW(&CryptoProvider.CryptoProvider,
465 return make_error_code(windows_error(::GetLastError()));
468 random_path_utf16.set_size(0);
469 for (SmallVectorImpl<wchar_t>::const_iterator i = model_utf16.begin(),
470 e = model_utf16.end();
474 if (!::CryptGenRandom(CryptoProvider, 1, &val))
475 return make_error_code(windows_error(::GetLastError()));
476 random_path_utf16.push_back("0123456789abcdef"[val & 15]);
479 random_path_utf16.push_back(*i);
481 // Make random_path_utf16 null terminated.
482 random_path_utf16.push_back(0);
483 random_path_utf16.pop_back();
485 // Try to create + open the path.
487 HANDLE TempFileHandle = ::CreateFileW(random_path_utf16.begin(),
488 GENERIC_READ | GENERIC_WRITE,
491 // Return ERROR_FILE_EXISTS if the file
494 FILE_ATTRIBUTE_TEMPORARY,
496 if (TempFileHandle == INVALID_HANDLE_VALUE) {
497 // If the file existed, try again, otherwise, error.
498 error_code ec = make_error_code(windows_error(::GetLastError()));
499 if (ec == error_code(windows_error::file_exists))
500 goto retry_random_path;
501 // Check for non-existing parent directories.
502 if (ec == error_code(windows_error::path_not_found)) {
503 // Create the directories using result_path as temp storage.
504 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
505 random_path_utf16.size(), result_path))
507 StringRef p(result_path.begin(), result_path.size());
508 SmallString<64> dir_to_create;
509 for (path::const_iterator i = path::begin(p),
510 e = --path::end(p); i != e; ++i) {
511 if (error_code ec = path::append(dir_to_create, *i)) return ec;
513 if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
515 // If c: doesn't exist, bail.
516 if (i->endswith(":"))
519 SmallVector<wchar_t, 64> dir_to_create_utf16;
520 if (error_code ec = UTF8ToUTF16(dir_to_create, dir_to_create_utf16))
523 // Create the directory.
524 if (!::CreateDirectoryW(dir_to_create_utf16.begin(), NULL))
525 return make_error_code(windows_error(::GetLastError()));
528 goto retry_create_file;
533 // Set result_path to the utf-8 representation of the path.
534 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
535 random_path_utf16.size(), result_path)) {
536 ::CloseHandle(TempFileHandle);
537 ::DeleteFileW(random_path_utf16.begin());
541 // Convert the Windows API file handle into a C-runtime handle.
542 int fd = ::_open_osfhandle(intptr_t(TempFileHandle), 0);
544 ::CloseHandle(TempFileHandle);
545 ::DeleteFileW(random_path_utf16.begin());
546 // MSDN doesn't say anything about _open_osfhandle setting errno or
547 // GetLastError(), so just return invalid_handle.
548 return make_error_code(windows_error::invalid_handle);
552 return make_error_code(errc::success);
554 } // end namespace fs
555 } // end namespace sys
556 } // end namespace llvm