blob: c86c24e811e1b72cc05ef69f402334b8564aa4c1 [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. Spencer3cb84ef2010-12-03 01:21:28 +0000274error_code exists(const Twine &path, bool &result) {
275 SmallString<128> path_storage;
276 SmallVector<wchar_t, 128> path_utf16;
277
278 if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
279 path_utf16))
280 return ec;
281
282 DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
283
284 if (attributes == INVALID_FILE_ATTRIBUTES) {
285 // See if the file didn't actually exist.
286 error_code ec = make_error_code(windows_error(::GetLastError()));
287 if (ec != error_code(windows_error::file_not_found) &&
288 ec != error_code(windows_error::path_not_found))
289 return ec;
290 result = false;
291 } else
292 result = true;
293 return make_error_code(errc::success);
294}
295
296error_code unique_file(const Twine &model, int &result_fd,
297 SmallVectorImpl<char> &result_path) {
298 // Use result_path as temp storage.
299 result_path.set_size(0);
300 StringRef m = model.toStringRef(result_path);
301
302 SmallVector<wchar_t, 128> model_utf16;
303 if (error_code ec = UTF8ToUTF16(m, model_utf16)) return ec;
304
305 // Make model absolute by prepending a temp directory if it's not already.
306 bool absolute;
307 if (error_code ec = path::is_absolute(m, absolute)) return ec;
308
309 if (!absolute) {
310 SmallVector<wchar_t, 64> temp_dir;
311 if (error_code ec = TempDir(temp_dir)) return ec;
312 // Handle c: by removing it.
313 if (model_utf16.size() > 2 && model_utf16[1] == L':') {
314 model_utf16.erase(model_utf16.begin(), model_utf16.begin() + 2);
315 }
316 model_utf16.insert(model_utf16.begin(), temp_dir.begin(), temp_dir.end());
317 }
318
319 // Replace '%' with random chars. From here on, DO NOT modify model. It may be
320 // needed if the randomly chosen path already exists.
321 SmallVector<wchar_t, 128> random_path_utf16;
322
323 // Get a Crypto Provider for CryptGenRandom.
324 AutoCryptoProvider CryptoProvider;
325 BOOL success = ::CryptAcquireContextW(&CryptoProvider.CryptoProvider,
326 NULL,
327 NULL,
328 PROV_RSA_FULL,
329 NULL);
330 if (!success)
331 return make_error_code(windows_error(::GetLastError()));
332
333retry_random_path:
334 random_path_utf16.set_size(0);
335 for (SmallVectorImpl<wchar_t>::const_iterator i = model_utf16.begin(),
336 e = model_utf16.end();
337 i != e; ++i) {
338 if (*i == L'%') {
339 BYTE val = 0;
340 if (!::CryptGenRandom(CryptoProvider, 1, &val))
341 return make_error_code(windows_error(::GetLastError()));
342 random_path_utf16.push_back("0123456789abcdef"[val & 15]);
343 }
344 else
345 random_path_utf16.push_back(*i);
346 }
347 // Make random_path_utf16 null terminated.
348 random_path_utf16.push_back(0);
349 random_path_utf16.pop_back();
350
351 // Try to create + open the path.
352retry_create_file:
353 HANDLE TempFileHandle = ::CreateFileW(random_path_utf16.begin(),
354 GENERIC_READ | GENERIC_WRITE,
355 FILE_SHARE_READ,
356 NULL,
357 // Return ERROR_FILE_EXISTS if the file
358 // already exists.
359 CREATE_NEW,
360 FILE_ATTRIBUTE_TEMPORARY,
361 NULL);
362 if (TempFileHandle == INVALID_HANDLE_VALUE) {
363 // If the file existed, try again, otherwise, error.
364 error_code ec = make_error_code(windows_error(::GetLastError()));
365 if (ec == error_code(windows_error::file_exists))
366 goto retry_random_path;
367 // Check for non-existing parent directories.
368 if (ec == error_code(windows_error::path_not_found)) {
369 // Create the directories using result_path as temp storage.
370 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
371 random_path_utf16.size(), result_path))
372 return ec;
373 StringRef p(result_path.begin(), result_path.size());
374 SmallString<64> dir_to_create;
375 for (path::const_iterator i = path::begin(p),
376 e = --path::end(p); i != e; ++i) {
377 if (error_code ec = path::append(dir_to_create, *i)) return ec;
378 bool Exists;
379 if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
380 if (!Exists) {
381 // If c: doesn't exist, bail.
382 if (i->endswith(":"))
383 return ec;
384
385 SmallVector<wchar_t, 64> dir_to_create_utf16;
386 if (error_code ec = UTF8ToUTF16(dir_to_create, dir_to_create_utf16))
387 return ec;
388
389 // Create the directory.
390 if (!::CreateDirectoryW(dir_to_create_utf16.begin(), NULL))
391 return make_error_code(windows_error(::GetLastError()));
392 }
393 }
394 goto retry_create_file;
395 }
396 return ec;
397 }
398
399 // Set result_path to the utf-8 representation of the path.
400 if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
401 random_path_utf16.size(), result_path)) {
402 ::CloseHandle(TempFileHandle);
403 ::DeleteFileW(random_path_utf16.begin());
404 return ec;
405 }
406
407 // Convert the Windows API file handle into a C-runtime handle.
408 int fd = ::_open_osfhandle(intptr_t(TempFileHandle), 0);
409 if (fd == -1) {
410 ::CloseHandle(TempFileHandle);
411 ::DeleteFileW(random_path_utf16.begin());
412 // MSDN doesn't say anything about _open_osfhandle setting errno or
413 // GetLastError(), so just return invalid_handle.
414 return make_error_code(windows_error::invalid_handle);
415 }
416
417 result_fd = fd;
418 return make_error_code(errc::success);
419}
Michael J. Spencerbee0c382010-12-01 19:32:01 +0000420} // end namespace fs
Michael J. Spencerdffde992010-11-29 22:28:51 +0000421} // end namespace sys
422} // end namespace llvm