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, NULL,
79 return make_error_code(windows_error(::GetLastError()));
84 // Now do the actual conversion.
85 len = ::WideCharToMultiByte(CP_UTF8, NULL,
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, NULL,
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, NULL,
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(), NULL))
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 unique_file(const Twine &model, int &result_fd,
345 SmallVectorImpl<char> &result_path) {
346 // Use result_path as temp storage.
347 result_path.set_size(0);
348 StringRef m = model.toStringRef(result_path);
350 SmallVector<wchar_t, 128> model_utf16;
351 if (error_code ec = UTF8ToUTF16(m, model_utf16)) return ec;
353 // Make model absolute by prepending a temp directory if it's not already.
355 if (error_code ec = path::is_absolute(m, absolute)) return ec;
358 SmallVector<wchar_t, 64> temp_dir;
359 if (error_code ec = TempDir(temp_dir)) return ec;
360 // Handle c: by removing it.
361 if (model_utf16.size() > 2 && model_utf16[1] == L':') {
362 model_utf16.erase(model_utf16.begin(), model_utf16.begin() + 2);
364 model_utf16.insert(model_utf16.begin(), temp_dir.begin(), temp_dir.end());
367 // Replace '%' with random chars. From here on, DO NOT modify model. It may be
368 // needed if the randomly chosen path already exists.
369 SmallVector<wchar_t, 128> random_path_utf16;
371 // Get a Crypto Provider for CryptGenRandom.
372 AutoCryptoProvider CryptoProvider;
373 BOOL success = ::CryptAcquireContextW(&CryptoProvider.CryptoProvider,
379 return make_error_code(windows_error(::GetLastError()));
382 random_path_utf16.set_size(0);
383 for (SmallVectorImpl<wchar_t>::const_iterator i = model_utf16.begin(),
384 e = model_utf16.end();
388 if (!::CryptGenRandom(CryptoProvider, 1, &val))
389 return make_error_code(windows_error(::GetLastError()));
390 random_path_utf16.push_back("0123456789abcdef"[val & 15]);
393 random_path_utf16.push_back(*i);
395 // Make random_path_utf16 null terminated.
396 random_path_utf16.push_back(0);
397 random_path_utf16.pop_back();
399 // Try to create + open the path.
401 HANDLE TempFileHandle = ::CreateFileW(random_path_utf16.begin(),
402 GENERIC_READ | GENERIC_WRITE,
405 // Return ERROR_FILE_EXISTS if the file
408 FILE_ATTRIBUTE_TEMPORARY,
410 if (TempFileHandle == INVALID_HANDLE_VALUE) {
411 // If the file existed, try again, otherwise, error.
412 error_code ec = make_error_code(windows_error(::GetLastError()));
413 if (ec == error_code(windows_error::file_exists))
414 goto retry_random_path;
415 // Check for non-existing parent directories.
416 if (ec == error_code(windows_error::path_not_found)) {
417 // Create the directories using result_path as temp storage.
418 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
419 random_path_utf16.size(), result_path))
421 StringRef p(result_path.begin(), result_path.size());
422 SmallString<64> dir_to_create;
423 for (path::const_iterator i = path::begin(p),
424 e = --path::end(p); i != e; ++i) {
425 if (error_code ec = path::append(dir_to_create, *i)) return ec;
427 if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
429 // If c: doesn't exist, bail.
430 if (i->endswith(":"))
433 SmallVector<wchar_t, 64> dir_to_create_utf16;
434 if (error_code ec = UTF8ToUTF16(dir_to_create, dir_to_create_utf16))
437 // Create the directory.
438 if (!::CreateDirectoryW(dir_to_create_utf16.begin(), NULL))
439 return make_error_code(windows_error(::GetLastError()));
442 goto retry_create_file;
447 // Set result_path to the utf-8 representation of the path.
448 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
449 random_path_utf16.size(), result_path)) {
450 ::CloseHandle(TempFileHandle);
451 ::DeleteFileW(random_path_utf16.begin());
455 // Convert the Windows API file handle into a C-runtime handle.
456 int fd = ::_open_osfhandle(intptr_t(TempFileHandle), 0);
458 ::CloseHandle(TempFileHandle);
459 ::DeleteFileW(random_path_utf16.begin());
460 // MSDN doesn't say anything about _open_osfhandle setting errno or
461 // GetLastError(), so just return invalid_handle.
462 return make_error_code(windows_error::invalid_handle);
466 return make_error_code(errc::success);
468 } // end namespace fs
469 } // end namespace sys
470 } // end namespace llvm