blob: e98150713bb1644f651ec971e3e8659904fd7f96 [file] [log] [blame]
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001//===- llvm/Support/Win32/PathV2.cpp - Windows Path Impl --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Windows specific implementation of the PathV2 API.
11//
12//===----------------------------------------------------------------------===//
13
14//===----------------------------------------------------------------------===//
15//=== WARNING: Implementation here must contain only generic Windows code that
16//=== is guaranteed to work on *all* Windows variants.
17//===----------------------------------------------------------------------===//
18
19#include "Windows.h"
Michael J. Spencer45710402010-12-03 01:21:28 +000020#include <WinCrypt.h>
Michael J. Spencerc20a0322010-12-03 17:54:07 +000021#include <fcntl.h>
Michael J. Spencer45710402010-12-03 01:21:28 +000022#include <io.h>
Michael J. Spencerc20a0322010-12-03 17:54:07 +000023#include <sys/stat.h>
24#include <sys/types.h>
Michael J. Spencerebad2f92010-11-29 22:28:51 +000025
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000026using namespace llvm;
27
28namespace {
Michael J. Spencer772caff52010-12-03 17:53:23 +000029 typedef BOOLEAN (WINAPI *PtrCreateSymbolicLinkW)(
30 /*__in*/ LPCWSTR lpSymlinkFileName,
31 /*__in*/ LPCWSTR lpTargetFileName,
32 /*__in*/ DWORD dwFlags);
33
34 PtrCreateSymbolicLinkW create_symbolic_link_api = PtrCreateSymbolicLinkW(
Michael J. Spencer7ee6d5d2010-12-03 07:41:25 +000035 ::GetProcAddress(::GetModuleHandleA("kernel32.dll"),
36 "CreateSymbolicLinkW"));
37
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000038 error_code UTF8ToUTF16(const StringRef &utf8,
39 SmallVectorImpl<wchar_t> &utf16) {
40 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
41 utf8.begin(), utf8.size(),
42 utf16.begin(), 0);
43
44 if (len == 0)
45 return make_error_code(windows_error(::GetLastError()));
46
47 utf16.reserve(len + 1);
48 utf16.set_size(len);
49
50 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
51 utf8.begin(), utf8.size(),
52 utf16.begin(), utf16.size());
53
54 if (len == 0)
55 return make_error_code(windows_error(::GetLastError()));
56
57 // Make utf16 null terminated.
58 utf16.push_back(0);
59 utf16.pop_back();
60
61 return make_error_code(errc::success);
62 }
Michael J. Spencer45710402010-12-03 01:21:28 +000063
64 error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
65 SmallVectorImpl<char> &utf8) {
66 // Get length.
67 int len = ::WideCharToMultiByte(CP_UTF8, NULL,
68 utf16, utf16_len,
69 utf8.begin(), 0,
70 NULL, NULL);
71
72 if (len == 0)
73 return make_error_code(windows_error(::GetLastError()));
74
75 utf8.reserve(len);
76 utf8.set_size(len);
77
78 // Now do the actual conversion.
79 len = ::WideCharToMultiByte(CP_UTF8, NULL,
80 utf16, utf16_len,
81 utf8.data(), utf8.size(),
82 NULL, NULL);
83
84 if (len == 0)
85 return make_error_code(windows_error(::GetLastError()));
86
87 // Make utf8 null terminated.
88 utf8.push_back(0);
89 utf8.pop_back();
90
91 return make_error_code(errc::success);
92 }
93
94 error_code TempDir(SmallVectorImpl<wchar_t> &result) {
95 retry_temp_dir:
96 DWORD len = ::GetTempPathW(result.capacity(), result.begin());
97
98 if (len == 0)
99 return make_error_code(windows_error(::GetLastError()));
100
101 if (len > result.capacity()) {
102 result.reserve(len);
103 goto retry_temp_dir;
104 }
105
106 result.set_size(len);
107 return make_error_code(errc::success);
108 }
109
110 struct AutoCryptoProvider {
111 HCRYPTPROV CryptoProvider;
112
113 ~AutoCryptoProvider() {
114 ::CryptReleaseContext(CryptoProvider, 0);
115 }
116
117 operator HCRYPTPROV() const {return CryptoProvider;}
118 };
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000119}
120
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000121namespace llvm {
122namespace sys {
123namespace path {
124
125error_code current_path(SmallVectorImpl<char> &result) {
126 SmallVector<wchar_t, 128> cur_path;
127 cur_path.reserve(128);
128retry_cur_dir:
129 DWORD len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
130
131 // A zero return value indicates a failure other than insufficient space.
132 if (len == 0)
133 return make_error_code(windows_error(::GetLastError()));
134
135 // If there's insufficient space, the len returned is larger than the len
136 // given.
137 if (len > cur_path.capacity()) {
138 cur_path.reserve(len);
139 goto retry_cur_dir;
140 }
141
142 cur_path.set_size(len);
143 // cur_path now holds the current directory in utf-16. Convert to utf-8.
144
145 // Find out how much space we need. Sadly, this function doesn't return the
146 // size needed unless you tell it the result size is 0, which means you
147 // _always_ have to call it twice.
148 len = ::WideCharToMultiByte(CP_UTF8, NULL,
149 cur_path.data(), cur_path.size(),
150 result.data(), 0,
151 NULL, NULL);
152
153 if (len == 0)
154 return make_error_code(windows_error(::GetLastError()));
155
156 result.reserve(len);
157 result.set_size(len);
158 // Now do the actual conversion.
159 len = ::WideCharToMultiByte(CP_UTF8, NULL,
160 cur_path.data(), cur_path.size(),
161 result.data(), result.size(),
162 NULL, NULL);
163 if (len == 0)
164 return make_error_code(windows_error(::GetLastError()));
165
166 return make_error_code(errc::success);
167}
168
169} // end namespace path
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000170
171namespace fs {
172
173error_code copy_file(const Twine &from, const Twine &to, copy_option copt) {
174 // Get arguments.
175 SmallString<128> from_storage;
176 SmallString<128> to_storage;
Michael J. Spencera41772a2010-12-03 01:21:38 +0000177 StringRef f = from.toStringRef(from_storage);
178 StringRef t = to.toStringRef(to_storage);
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000179
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;
185
186 // Copy the file.
187 BOOL res = ::CopyFileW(wide_from.begin(), wide_to.begin(),
188 copt != copy_option::overwrite_if_exists);
189
190 if (res == 0)
191 return make_error_code(windows_error(::GetLastError()));
192
193 return make_error_code(errc::success);
194}
195
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000196error_code create_directory(const Twine &path, bool &existed) {
197 SmallString<128> path_storage;
198 SmallVector<wchar_t, 128> path_utf16;
199
200 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
201 path_utf16))
202 return ec;
203
204 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
205 error_code ec = make_error_code(windows_error(::GetLastError()));
206 if (ec == make_error_code(windows_error::already_exists))
207 existed = true;
208 else
209 return ec;
210 } else
211 existed = false;
212
213 return make_error_code(errc::success);
214}
215
Michael J. Spencere0c45602010-12-03 05:58:41 +0000216error_code create_hard_link(const Twine &to, const Twine &from) {
217 // Get arguments.
218 SmallString<128> from_storage;
219 SmallString<128> to_storage;
220 StringRef f = from.toStringRef(from_storage);
221 StringRef t = to.toStringRef(to_storage);
222
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;
228
229 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
230 return make_error_code(windows_error(::GetLastError()));
231
232 return make_error_code(errc::success);
233}
234
Michael J. Spencer7ee6d5d2010-12-03 07:41:25 +0000235error_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);
239
240 // Get arguments.
241 SmallString<128> from_storage;
242 SmallString<128> to_storage;
243 StringRef f = from.toStringRef(from_storage);
244 StringRef t = to.toStringRef(to_storage);
245
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;
251
252 if (!create_symbolic_link_api(wide_from.begin(), wide_to.begin(), NULL))
253 return make_error_code(windows_error(::GetLastError()));
254
255 return make_error_code(errc::success);
256}
257
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000258error_code remove(const Twine &path, bool &existed) {
259 SmallString<128> path_storage;
260 SmallVector<wchar_t, 128> path_utf16;
261
262 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
263 path_utf16))
264 return ec;
265
266 if (!::DeleteFileW(path_utf16.begin())) {
267 error_code ec = make_error_code(windows_error(::GetLastError()));
268 if (ec != make_error_code(windows_error::file_not_found))
269 return ec;
270 existed = false;
271 } else
272 existed = true;
273
274 return make_error_code(errc::success);
275}
276
Michael J. Spencer409f5562010-12-03 17:53:55 +0000277error_code rename(const Twine &from, const Twine &to) {
278 // Get arguments.
279 SmallString<128> from_storage;
280 SmallString<128> to_storage;
281 StringRef f = from.toStringRef(from_storage);
282 StringRef t = to.toStringRef(to_storage);
283
284 // Convert to utf-16.
285 SmallVector<wchar_t, 128> wide_from;
286 SmallVector<wchar_t, 128> wide_to;
287 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
288 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
289
290 if (!::MoveFileW(wide_from.begin(), wide_to.begin()))
291 return make_error_code(windows_error(::GetLastError()));
292
293 return make_error_code(errc::success);
294}
295
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000296error_code resize_file(const Twine &path, uint64_t size) {
297 SmallString<128> path_storage;
298 SmallVector<wchar_t, 128> path_utf16;
299
300 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
301 path_utf16))
302 return ec;
303
304 int fd = ::_wopen(path_utf16.begin(), O_BINARY, S_IREAD | S_IWRITE);
305 if (fd == -1)
306 return error_code(errno, generic_category());
307 errno_t error = ::_chsize_s(fd, size);
308 ::close(fd);
309 return error_code(error, generic_category());
310}
311
Michael J. Spencer45710402010-12-03 01:21:28 +0000312error_code exists(const Twine &path, bool &result) {
313 SmallString<128> path_storage;
314 SmallVector<wchar_t, 128> path_utf16;
315
316 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
317 path_utf16))
318 return ec;
319
320 DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
321
322 if (attributes == INVALID_FILE_ATTRIBUTES) {
323 // See if the file didn't actually exist.
324 error_code ec = make_error_code(windows_error(::GetLastError()));
325 if (ec != error_code(windows_error::file_not_found) &&
326 ec != error_code(windows_error::path_not_found))
327 return ec;
328 result = false;
329 } else
330 result = true;
331 return make_error_code(errc::success);
332}
333
334error_code unique_file(const Twine &model, int &result_fd,
335 SmallVectorImpl<char> &result_path) {
336 // Use result_path as temp storage.
337 result_path.set_size(0);
338 StringRef m = model.toStringRef(result_path);
339
340 SmallVector<wchar_t, 128> model_utf16;
341 if (error_code ec = UTF8ToUTF16(m, model_utf16)) return ec;
342
343 // Make model absolute by prepending a temp directory if it's not already.
344 bool absolute;
345 if (error_code ec = path::is_absolute(m, absolute)) return ec;
346
347 if (!absolute) {
348 SmallVector<wchar_t, 64> temp_dir;
349 if (error_code ec = TempDir(temp_dir)) return ec;
350 // Handle c: by removing it.
351 if (model_utf16.size() > 2 && model_utf16[1] == L':') {
352 model_utf16.erase(model_utf16.begin(), model_utf16.begin() + 2);
353 }
354 model_utf16.insert(model_utf16.begin(), temp_dir.begin(), temp_dir.end());
355 }
356
357 // Replace '%' with random chars. From here on, DO NOT modify model. It may be
358 // needed if the randomly chosen path already exists.
359 SmallVector<wchar_t, 128> random_path_utf16;
360
361 // Get a Crypto Provider for CryptGenRandom.
362 AutoCryptoProvider CryptoProvider;
363 BOOL success = ::CryptAcquireContextW(&CryptoProvider.CryptoProvider,
364 NULL,
365 NULL,
366 PROV_RSA_FULL,
367 NULL);
368 if (!success)
369 return make_error_code(windows_error(::GetLastError()));
370
371retry_random_path:
372 random_path_utf16.set_size(0);
373 for (SmallVectorImpl<wchar_t>::const_iterator i = model_utf16.begin(),
374 e = model_utf16.end();
375 i != e; ++i) {
376 if (*i == L'%') {
377 BYTE val = 0;
378 if (!::CryptGenRandom(CryptoProvider, 1, &val))
379 return make_error_code(windows_error(::GetLastError()));
380 random_path_utf16.push_back("0123456789abcdef"[val & 15]);
381 }
382 else
383 random_path_utf16.push_back(*i);
384 }
385 // Make random_path_utf16 null terminated.
386 random_path_utf16.push_back(0);
387 random_path_utf16.pop_back();
388
389 // Try to create + open the path.
390retry_create_file:
391 HANDLE TempFileHandle = ::CreateFileW(random_path_utf16.begin(),
392 GENERIC_READ | GENERIC_WRITE,
393 FILE_SHARE_READ,
394 NULL,
395 // Return ERROR_FILE_EXISTS if the file
396 // already exists.
397 CREATE_NEW,
398 FILE_ATTRIBUTE_TEMPORARY,
399 NULL);
400 if (TempFileHandle == INVALID_HANDLE_VALUE) {
401 // If the file existed, try again, otherwise, error.
402 error_code ec = make_error_code(windows_error(::GetLastError()));
403 if (ec == error_code(windows_error::file_exists))
404 goto retry_random_path;
405 // Check for non-existing parent directories.
406 if (ec == error_code(windows_error::path_not_found)) {
407 // Create the directories using result_path as temp storage.
408 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
409 random_path_utf16.size(), result_path))
410 return ec;
411 StringRef p(result_path.begin(), result_path.size());
412 SmallString<64> dir_to_create;
413 for (path::const_iterator i = path::begin(p),
414 e = --path::end(p); i != e; ++i) {
415 if (error_code ec = path::append(dir_to_create, *i)) return ec;
416 bool Exists;
417 if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
418 if (!Exists) {
419 // If c: doesn't exist, bail.
420 if (i->endswith(":"))
421 return ec;
422
423 SmallVector<wchar_t, 64> dir_to_create_utf16;
424 if (error_code ec = UTF8ToUTF16(dir_to_create, dir_to_create_utf16))
425 return ec;
426
427 // Create the directory.
428 if (!::CreateDirectoryW(dir_to_create_utf16.begin(), NULL))
429 return make_error_code(windows_error(::GetLastError()));
430 }
431 }
432 goto retry_create_file;
433 }
434 return ec;
435 }
436
437 // Set result_path to the utf-8 representation of the path.
438 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
439 random_path_utf16.size(), result_path)) {
440 ::CloseHandle(TempFileHandle);
441 ::DeleteFileW(random_path_utf16.begin());
442 return ec;
443 }
444
445 // Convert the Windows API file handle into a C-runtime handle.
446 int fd = ::_open_osfhandle(intptr_t(TempFileHandle), 0);
447 if (fd == -1) {
448 ::CloseHandle(TempFileHandle);
449 ::DeleteFileW(random_path_utf16.begin());
450 // MSDN doesn't say anything about _open_osfhandle setting errno or
451 // GetLastError(), so just return invalid_handle.
452 return make_error_code(windows_error::invalid_handle);
453 }
454
455 result_fd = fd;
456 return make_error_code(errc::success);
457}
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +0000458} // end namespace fs
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000459} // end namespace sys
460} // end namespace llvm