blob: c97ba5df5935331bba809ca3b9d7e55288594c42 [file] [log] [blame]
Michael J. Spencerdffde992010-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. Spencer3cb84ef2010-12-03 01:21:28 +000020#include <WinCrypt.h>
21#include <io.h>
Michael J. Spencerdffde992010-11-29 22:28:51 +000022
Michael J. Spencerbee0c382010-12-01 19:32:01 +000023using namespace llvm;
24
25namespace {
Michael J. Spencer998b4702010-12-03 17:53:23 +000026 typedef BOOLEAN (WINAPI *PtrCreateSymbolicLinkW)(
27 /*__in*/ LPCWSTR lpSymlinkFileName,
28 /*__in*/ LPCWSTR lpTargetFileName,
29 /*__in*/ DWORD dwFlags);
30
31 PtrCreateSymbolicLinkW create_symbolic_link_api = PtrCreateSymbolicLinkW(
Michael J. Spencer9b391c52010-12-03 07:41:25 +000032 ::GetProcAddress(::GetModuleHandleA("kernel32.dll"),
33 "CreateSymbolicLinkW"));
34
Michael J. Spencerbee0c382010-12-01 19:32:01 +000035 error_code UTF8ToUTF16(const StringRef &utf8,
36 SmallVectorImpl<wchar_t> &utf16) {
37 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
38 utf8.begin(), utf8.size(),
39 utf16.begin(), 0);
40
41 if (len == 0)
42 return make_error_code(windows_error(::GetLastError()));
43
44 utf16.reserve(len + 1);
45 utf16.set_size(len);
46
47 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
48 utf8.begin(), utf8.size(),
49 utf16.begin(), utf16.size());
50
51 if (len == 0)
52 return make_error_code(windows_error(::GetLastError()));
53
54 // Make utf16 null terminated.
55 utf16.push_back(0);
56 utf16.pop_back();
57
58 return make_error_code(errc::success);
59 }
Michael J. Spencer3cb84ef2010-12-03 01:21:28 +000060
61 error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
62 SmallVectorImpl<char> &utf8) {
63 // Get length.
64 int len = ::WideCharToMultiByte(CP_UTF8, NULL,
65 utf16, utf16_len,
66 utf8.begin(), 0,
67 NULL, NULL);
68
69 if (len == 0)
70 return make_error_code(windows_error(::GetLastError()));
71
72 utf8.reserve(len);
73 utf8.set_size(len);
74
75 // Now do the actual conversion.
76 len = ::WideCharToMultiByte(CP_UTF8, NULL,
77 utf16, utf16_len,
78 utf8.data(), utf8.size(),
79 NULL, NULL);
80
81 if (len == 0)
82 return make_error_code(windows_error(::GetLastError()));
83
84 // Make utf8 null terminated.
85 utf8.push_back(0);
86 utf8.pop_back();
87
88 return make_error_code(errc::success);
89 }
90
91 error_code TempDir(SmallVectorImpl<wchar_t> &result) {
92 retry_temp_dir:
93 DWORD len = ::GetTempPathW(result.capacity(), result.begin());
94
95 if (len == 0)
96 return make_error_code(windows_error(::GetLastError()));
97
98 if (len > result.capacity()) {
99 result.reserve(len);
100 goto retry_temp_dir;
101 }
102
103 result.set_size(len);
104 return make_error_code(errc::success);
105 }
106
107 struct AutoCryptoProvider {
108 HCRYPTPROV CryptoProvider;
109
110 ~AutoCryptoProvider() {
111 ::CryptReleaseContext(CryptoProvider, 0);
112 }
113
114 operator HCRYPTPROV() const {return CryptoProvider;}
115 };
Michael J. Spencerbee0c382010-12-01 19:32:01 +0000116}
117
Michael J. Spencerdffde992010-11-29 22:28:51 +0000118namespace llvm {
119namespace sys {
120namespace path {
121
122error_code current_path(SmallVectorImpl<char> &result) {
123 SmallVector<wchar_t, 128> cur_path;
124 cur_path.reserve(128);
125retry_cur_dir:
126 DWORD len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
127
128 // A zero return value indicates a failure other than insufficient space.
129 if (len == 0)
130 return make_error_code(windows_error(::GetLastError()));
131
132 // If there's insufficient space, the len returned is larger than the len
133 // given.
134 if (len > cur_path.capacity()) {
135 cur_path.reserve(len);
136 goto retry_cur_dir;
137 }
138
139 cur_path.set_size(len);
140 // cur_path now holds the current directory in utf-16. Convert to utf-8.
141
142 // Find out how much space we need. Sadly, this function doesn't return the
143 // size needed unless you tell it the result size is 0, which means you
144 // _always_ have to call it twice.
145 len = ::WideCharToMultiByte(CP_UTF8, NULL,
146 cur_path.data(), cur_path.size(),
147 result.data(), 0,
148 NULL, NULL);
149
150 if (len == 0)
151 return make_error_code(windows_error(::GetLastError()));
152
153 result.reserve(len);
154 result.set_size(len);
155 // Now do the actual conversion.
156 len = ::WideCharToMultiByte(CP_UTF8, NULL,
157 cur_path.data(), cur_path.size(),
158 result.data(), result.size(),
159 NULL, NULL);
160 if (len == 0)
161 return make_error_code(windows_error(::GetLastError()));
162
163 return make_error_code(errc::success);
164}
165
166} // end namespace path
Michael J. Spencerbee0c382010-12-01 19:32:01 +0000167
168namespace fs {
169
170error_code copy_file(const Twine &from, const Twine &to, copy_option copt) {
171 // Get arguments.
172 SmallString<128> from_storage;
173 SmallString<128> to_storage;
Michael J. Spencer2dbdeee2010-12-03 01:21:38 +0000174 StringRef f = from.toStringRef(from_storage);
175 StringRef t = to.toStringRef(to_storage);
Michael J. Spencerbee0c382010-12-01 19:32:01 +0000176
177 // Convert to utf-16.
178 SmallVector<wchar_t, 128> wide_from;
179 SmallVector<wchar_t, 128> wide_to;
180 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
181 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
182
183 // Copy the file.
184 BOOL res = ::CopyFileW(wide_from.begin(), wide_to.begin(),
185 copt != copy_option::overwrite_if_exists);
186
187 if (res == 0)
188 return make_error_code(windows_error(::GetLastError()));
189
190 return make_error_code(errc::success);
191}
192
Michael J. Spencerb83769f2010-12-03 05:42:11 +0000193error_code create_directory(const Twine &path, bool &existed) {
194 SmallString<128> path_storage;
195 SmallVector<wchar_t, 128> path_utf16;
196
197 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
198 path_utf16))
199 return ec;
200
201 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
202 error_code ec = make_error_code(windows_error(::GetLastError()));
203 if (ec == make_error_code(windows_error::already_exists))
204 existed = true;
205 else
206 return ec;
207 } else
208 existed = false;
209
210 return make_error_code(errc::success);
211}
212
Michael J. Spencerd7b305f2010-12-03 05:58:41 +0000213error_code create_hard_link(const Twine &to, const Twine &from) {
214 // Get arguments.
215 SmallString<128> from_storage;
216 SmallString<128> to_storage;
217 StringRef f = from.toStringRef(from_storage);
218 StringRef t = to.toStringRef(to_storage);
219
220 // Convert to utf-16.
221 SmallVector<wchar_t, 128> wide_from;
222 SmallVector<wchar_t, 128> wide_to;
223 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
224 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
225
226 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
227 return make_error_code(windows_error(::GetLastError()));
228
229 return make_error_code(errc::success);
230}
231
Michael J. Spencer9b391c52010-12-03 07:41:25 +0000232error_code create_symlink(const Twine &to, const Twine &from) {
233 // Only do it if the function is available at runtime.
234 if (!create_symbolic_link_api)
235 return make_error_code(errc::function_not_supported);
236
237 // Get arguments.
238 SmallString<128> from_storage;
239 SmallString<128> to_storage;
240 StringRef f = from.toStringRef(from_storage);
241 StringRef t = to.toStringRef(to_storage);
242
243 // Convert to utf-16.
244 SmallVector<wchar_t, 128> wide_from;
245 SmallVector<wchar_t, 128> wide_to;
246 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
247 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
248
249 if (!create_symbolic_link_api(wide_from.begin(), wide_to.begin(), NULL))
250 return make_error_code(windows_error(::GetLastError()));
251
252 return make_error_code(errc::success);
253}
254
Michael J. Spencer106aa732010-12-03 17:53:43 +0000255error_code remove(const Twine &path, bool &existed) {
256 SmallString<128> path_storage;
257 SmallVector<wchar_t, 128> path_utf16;
258
259 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
260 path_utf16))
261 return ec;
262
263 if (!::DeleteFileW(path_utf16.begin())) {
264 error_code ec = make_error_code(windows_error(::GetLastError()));
265 if (ec != make_error_code(windows_error::file_not_found))
266 return ec;
267 existed = false;
268 } else
269 existed = true;
270
271 return make_error_code(errc::success);
272}
273
Michael J. Spencera50b98c2010-12-03 17:53:55 +0000274error_code rename(const Twine &from, const Twine &to) {
275 // Get arguments.
276 SmallString<128> from_storage;
277 SmallString<128> to_storage;
278 StringRef f = from.toStringRef(from_storage);
279 StringRef t = to.toStringRef(to_storage);
280
281 // Convert to utf-16.
282 SmallVector<wchar_t, 128> wide_from;
283 SmallVector<wchar_t, 128> wide_to;
284 if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
285 if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
286
287 if (!::MoveFileW(wide_from.begin(), wide_to.begin()))
288 return make_error_code(windows_error(::GetLastError()));
289
290 return make_error_code(errc::success);
291}
292
Michael J. Spencer3cb84ef2010-12-03 01:21:28 +0000293error_code exists(const Twine &path, bool &result) {
294 SmallString<128> path_storage;
295 SmallVector<wchar_t, 128> path_utf16;
296
297 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
298 path_utf16))
299 return ec;
300
301 DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
302
303 if (attributes == INVALID_FILE_ATTRIBUTES) {
304 // See if the file didn't actually exist.
305 error_code ec = make_error_code(windows_error(::GetLastError()));
306 if (ec != error_code(windows_error::file_not_found) &&
307 ec != error_code(windows_error::path_not_found))
308 return ec;
309 result = false;
310 } else
311 result = true;
312 return make_error_code(errc::success);
313}
314
315error_code unique_file(const Twine &model, int &result_fd,
316 SmallVectorImpl<char> &result_path) {
317 // Use result_path as temp storage.
318 result_path.set_size(0);
319 StringRef m = model.toStringRef(result_path);
320
321 SmallVector<wchar_t, 128> model_utf16;
322 if (error_code ec = UTF8ToUTF16(m, model_utf16)) return ec;
323
324 // Make model absolute by prepending a temp directory if it's not already.
325 bool absolute;
326 if (error_code ec = path::is_absolute(m, absolute)) return ec;
327
328 if (!absolute) {
329 SmallVector<wchar_t, 64> temp_dir;
330 if (error_code ec = TempDir(temp_dir)) return ec;
331 // Handle c: by removing it.
332 if (model_utf16.size() > 2 && model_utf16[1] == L':') {
333 model_utf16.erase(model_utf16.begin(), model_utf16.begin() + 2);
334 }
335 model_utf16.insert(model_utf16.begin(), temp_dir.begin(), temp_dir.end());
336 }
337
338 // Replace '%' with random chars. From here on, DO NOT modify model. It may be
339 // needed if the randomly chosen path already exists.
340 SmallVector<wchar_t, 128> random_path_utf16;
341
342 // Get a Crypto Provider for CryptGenRandom.
343 AutoCryptoProvider CryptoProvider;
344 BOOL success = ::CryptAcquireContextW(&CryptoProvider.CryptoProvider,
345 NULL,
346 NULL,
347 PROV_RSA_FULL,
348 NULL);
349 if (!success)
350 return make_error_code(windows_error(::GetLastError()));
351
352retry_random_path:
353 random_path_utf16.set_size(0);
354 for (SmallVectorImpl<wchar_t>::const_iterator i = model_utf16.begin(),
355 e = model_utf16.end();
356 i != e; ++i) {
357 if (*i == L'%') {
358 BYTE val = 0;
359 if (!::CryptGenRandom(CryptoProvider, 1, &val))
360 return make_error_code(windows_error(::GetLastError()));
361 random_path_utf16.push_back("0123456789abcdef"[val & 15]);
362 }
363 else
364 random_path_utf16.push_back(*i);
365 }
366 // Make random_path_utf16 null terminated.
367 random_path_utf16.push_back(0);
368 random_path_utf16.pop_back();
369
370 // Try to create + open the path.
371retry_create_file:
372 HANDLE TempFileHandle = ::CreateFileW(random_path_utf16.begin(),
373 GENERIC_READ | GENERIC_WRITE,
374 FILE_SHARE_READ,
375 NULL,
376 // Return ERROR_FILE_EXISTS if the file
377 // already exists.
378 CREATE_NEW,
379 FILE_ATTRIBUTE_TEMPORARY,
380 NULL);
381 if (TempFileHandle == INVALID_HANDLE_VALUE) {
382 // If the file existed, try again, otherwise, error.
383 error_code ec = make_error_code(windows_error(::GetLastError()));
384 if (ec == error_code(windows_error::file_exists))
385 goto retry_random_path;
386 // Check for non-existing parent directories.
387 if (ec == error_code(windows_error::path_not_found)) {
388 // Create the directories using result_path as temp storage.
389 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
390 random_path_utf16.size(), result_path))
391 return ec;
392 StringRef p(result_path.begin(), result_path.size());
393 SmallString<64> dir_to_create;
394 for (path::const_iterator i = path::begin(p),
395 e = --path::end(p); i != e; ++i) {
396 if (error_code ec = path::append(dir_to_create, *i)) return ec;
397 bool Exists;
398 if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
399 if (!Exists) {
400 // If c: doesn't exist, bail.
401 if (i->endswith(":"))
402 return ec;
403
404 SmallVector<wchar_t, 64> dir_to_create_utf16;
405 if (error_code ec = UTF8ToUTF16(dir_to_create, dir_to_create_utf16))
406 return ec;
407
408 // Create the directory.
409 if (!::CreateDirectoryW(dir_to_create_utf16.begin(), NULL))
410 return make_error_code(windows_error(::GetLastError()));
411 }
412 }
413 goto retry_create_file;
414 }
415 return ec;
416 }
417
418 // Set result_path to the utf-8 representation of the path.
419 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
420 random_path_utf16.size(), result_path)) {
421 ::CloseHandle(TempFileHandle);
422 ::DeleteFileW(random_path_utf16.begin());
423 return ec;
424 }
425
426 // Convert the Windows API file handle into a C-runtime handle.
427 int fd = ::_open_osfhandle(intptr_t(TempFileHandle), 0);
428 if (fd == -1) {
429 ::CloseHandle(TempFileHandle);
430 ::DeleteFileW(random_path_utf16.begin());
431 // MSDN doesn't say anything about _open_osfhandle setting errno or
432 // GetLastError(), so just return invalid_handle.
433 return make_error_code(windows_error::invalid_handle);
434 }
435
436 result_fd = fd;
437 return make_error_code(errc::success);
438}
Michael J. Spencerbee0c382010-12-01 19:32:01 +0000439} // end namespace fs
Michael J. Spencerdffde992010-11-29 22:28:51 +0000440} // end namespace sys
441} // end namespace llvm