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