PathV2.inc revision b83769f36afe5221ca6aa7741561801836a179cb
1//===- 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"
20#include <WinCrypt.h>
21#include <io.h>
22
23using namespace llvm;
24
25namespace {
26  error_code UTF8ToUTF16(const StringRef &utf8,
27                               SmallVectorImpl<wchar_t> &utf16) {
28    int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
29                                    utf8.begin(), utf8.size(),
30                                    utf16.begin(), 0);
31
32    if (len == 0)
33      return make_error_code(windows_error(::GetLastError()));
34
35    utf16.reserve(len + 1);
36    utf16.set_size(len);
37
38    len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
39                                    utf8.begin(), utf8.size(),
40                                    utf16.begin(), utf16.size());
41
42    if (len == 0)
43      return make_error_code(windows_error(::GetLastError()));
44
45    // Make utf16 null terminated.
46    utf16.push_back(0);
47    utf16.pop_back();
48
49    return make_error_code(errc::success);
50  }
51
52  error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
53                               SmallVectorImpl<char> &utf8) {
54    // Get length.
55    int len = ::WideCharToMultiByte(CP_UTF8, NULL,
56                                    utf16, utf16_len,
57                                    utf8.begin(), 0,
58                                    NULL, NULL);
59
60    if (len == 0)
61      return make_error_code(windows_error(::GetLastError()));
62
63    utf8.reserve(len);
64    utf8.set_size(len);
65
66    // Now do the actual conversion.
67    len = ::WideCharToMultiByte(CP_UTF8, NULL,
68                                utf16, utf16_len,
69                                utf8.data(), utf8.size(),
70                                NULL, NULL);
71
72    if (len == 0)
73      return make_error_code(windows_error(::GetLastError()));
74
75    // Make utf8 null terminated.
76    utf8.push_back(0);
77    utf8.pop_back();
78
79    return make_error_code(errc::success);
80  }
81
82  error_code TempDir(SmallVectorImpl<wchar_t> &result) {
83  retry_temp_dir:
84    DWORD len = ::GetTempPathW(result.capacity(), result.begin());
85
86    if (len == 0)
87      return make_error_code(windows_error(::GetLastError()));
88
89    if (len > result.capacity()) {
90      result.reserve(len);
91      goto retry_temp_dir;
92    }
93
94    result.set_size(len);
95    return make_error_code(errc::success);
96  }
97
98  struct AutoCryptoProvider {
99    HCRYPTPROV CryptoProvider;
100
101    ~AutoCryptoProvider() {
102      ::CryptReleaseContext(CryptoProvider, 0);
103    }
104
105    operator HCRYPTPROV() const {return CryptoProvider;}
106  };
107}
108
109namespace llvm {
110namespace sys  {
111namespace path {
112
113error_code current_path(SmallVectorImpl<char> &result) {
114  SmallVector<wchar_t, 128> cur_path;
115  cur_path.reserve(128);
116retry_cur_dir:
117  DWORD len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
118
119  // A zero return value indicates a failure other than insufficient space.
120  if (len == 0)
121    return make_error_code(windows_error(::GetLastError()));
122
123  // If there's insufficient space, the len returned is larger than the len
124  // given.
125  if (len > cur_path.capacity()) {
126    cur_path.reserve(len);
127    goto retry_cur_dir;
128  }
129
130  cur_path.set_size(len);
131  // cur_path now holds the current directory in utf-16. Convert to utf-8.
132
133  // Find out how much space we need. Sadly, this function doesn't return the
134  // size needed unless you tell it the result size is 0, which means you
135  // _always_ have to call it twice.
136  len = ::WideCharToMultiByte(CP_UTF8, NULL,
137                              cur_path.data(), cur_path.size(),
138                              result.data(), 0,
139                              NULL, NULL);
140
141  if (len == 0)
142    return make_error_code(windows_error(::GetLastError()));
143
144  result.reserve(len);
145  result.set_size(len);
146  // Now do the actual conversion.
147  len = ::WideCharToMultiByte(CP_UTF8, NULL,
148                              cur_path.data(), cur_path.size(),
149                              result.data(), result.size(),
150                              NULL, NULL);
151  if (len == 0)
152    return make_error_code(windows_error(::GetLastError()));
153
154  return make_error_code(errc::success);
155}
156
157} // end namespace path
158
159namespace fs {
160
161error_code copy_file(const Twine &from, const Twine &to, copy_option copt) {
162  // Get arguments.
163  SmallString<128> from_storage;
164  SmallString<128> to_storage;
165  StringRef f = from.toStringRef(from_storage);
166  StringRef t = to.toStringRef(to_storage);
167
168  // Convert to utf-16.
169  SmallVector<wchar_t, 128> wide_from;
170  SmallVector<wchar_t, 128> wide_to;
171  if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
172  if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
173
174  // Copy the file.
175  BOOL res = ::CopyFileW(wide_from.begin(), wide_to.begin(),
176                         copt != copy_option::overwrite_if_exists);
177
178  if (res == 0)
179    return make_error_code(windows_error(::GetLastError()));
180
181  return make_error_code(errc::success);
182}
183
184error_code create_directory(const Twine &path, bool &existed) {
185  SmallString<128> path_storage;
186  SmallVector<wchar_t, 128> path_utf16;
187
188  if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
189                                  path_utf16))
190    return ec;
191
192  if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
193    error_code ec = make_error_code(windows_error(::GetLastError()));
194    if (ec == make_error_code(windows_error::already_exists))
195      existed = true;
196    else
197      return ec;
198  } else
199    existed = false;
200
201  return make_error_code(errc::success);
202}
203
204error_code exists(const Twine &path, bool &result) {
205  SmallString<128> path_storage;
206  SmallVector<wchar_t, 128> path_utf16;
207
208  if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
209                                  path_utf16))
210    return ec;
211
212  DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
213
214  if (attributes == INVALID_FILE_ATTRIBUTES) {
215    // See if the file didn't actually exist.
216    error_code ec = make_error_code(windows_error(::GetLastError()));
217    if (ec != error_code(windows_error::file_not_found) &&
218        ec != error_code(windows_error::path_not_found))
219      return ec;
220    result = false;
221  } else
222    result = true;
223  return make_error_code(errc::success);
224}
225
226error_code unique_file(const Twine &model, int &result_fd,
227                             SmallVectorImpl<char> &result_path) {
228  // Use result_path as temp storage.
229  result_path.set_size(0);
230  StringRef m = model.toStringRef(result_path);
231
232  SmallVector<wchar_t, 128> model_utf16;
233  if (error_code ec = UTF8ToUTF16(m, model_utf16)) return ec;
234
235  // Make model absolute by prepending a temp directory if it's not already.
236  bool absolute;
237  if (error_code ec = path::is_absolute(m, absolute)) return ec;
238
239  if (!absolute) {
240    SmallVector<wchar_t, 64> temp_dir;
241    if (error_code ec = TempDir(temp_dir)) return ec;
242    // Handle c: by removing it.
243    if (model_utf16.size() > 2 && model_utf16[1] == L':') {
244      model_utf16.erase(model_utf16.begin(), model_utf16.begin() + 2);
245    }
246    model_utf16.insert(model_utf16.begin(), temp_dir.begin(), temp_dir.end());
247  }
248
249  // Replace '%' with random chars. From here on, DO NOT modify model. It may be
250  // needed if the randomly chosen path already exists.
251  SmallVector<wchar_t, 128> random_path_utf16;
252
253  // Get a Crypto Provider for CryptGenRandom.
254  AutoCryptoProvider CryptoProvider;
255  BOOL success = ::CryptAcquireContextW(&CryptoProvider.CryptoProvider,
256                                        NULL,
257                                        NULL,
258                                        PROV_RSA_FULL,
259                                        NULL);
260  if (!success)
261    return make_error_code(windows_error(::GetLastError()));
262
263retry_random_path:
264  random_path_utf16.set_size(0);
265  for (SmallVectorImpl<wchar_t>::const_iterator i = model_utf16.begin(),
266                                                e = model_utf16.end();
267                                                i != e; ++i) {
268    if (*i == L'%') {
269      BYTE val = 0;
270      if (!::CryptGenRandom(CryptoProvider, 1, &val))
271          return make_error_code(windows_error(::GetLastError()));
272      random_path_utf16.push_back("0123456789abcdef"[val & 15]);
273    }
274    else
275      random_path_utf16.push_back(*i);
276  }
277  // Make random_path_utf16 null terminated.
278  random_path_utf16.push_back(0);
279  random_path_utf16.pop_back();
280
281  // Try to create + open the path.
282retry_create_file:
283  HANDLE TempFileHandle = ::CreateFileW(random_path_utf16.begin(),
284                                        GENERIC_READ | GENERIC_WRITE,
285                                        FILE_SHARE_READ,
286                                        NULL,
287                                        // Return ERROR_FILE_EXISTS if the file
288                                        // already exists.
289                                        CREATE_NEW,
290                                        FILE_ATTRIBUTE_TEMPORARY,
291                                        NULL);
292  if (TempFileHandle == INVALID_HANDLE_VALUE) {
293    // If the file existed, try again, otherwise, error.
294    error_code ec = make_error_code(windows_error(::GetLastError()));
295    if (ec == error_code(windows_error::file_exists))
296      goto retry_random_path;
297    // Check for non-existing parent directories.
298    if (ec == error_code(windows_error::path_not_found)) {
299      // Create the directories using result_path as temp storage.
300      if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
301                                      random_path_utf16.size(), result_path))
302        return ec;
303      StringRef p(result_path.begin(), result_path.size());
304      SmallString<64> dir_to_create;
305      for (path::const_iterator i = path::begin(p),
306                                e = --path::end(p); i != e; ++i) {
307        if (error_code ec = path::append(dir_to_create, *i)) return ec;
308        bool Exists;
309        if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
310        if (!Exists) {
311          // If c: doesn't exist, bail.
312          if (i->endswith(":"))
313            return ec;
314
315          SmallVector<wchar_t, 64> dir_to_create_utf16;
316          if (error_code ec = UTF8ToUTF16(dir_to_create, dir_to_create_utf16))
317            return ec;
318
319          // Create the directory.
320          if (!::CreateDirectoryW(dir_to_create_utf16.begin(), NULL))
321            return make_error_code(windows_error(::GetLastError()));
322        }
323      }
324      goto retry_create_file;
325    }
326    return ec;
327  }
328
329  // Set result_path to the utf-8 representation of the path.
330  if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
331                                  random_path_utf16.size(), result_path)) {
332    ::CloseHandle(TempFileHandle);
333    ::DeleteFileW(random_path_utf16.begin());
334    return ec;
335  }
336
337  // Convert the Windows API file handle into a C-runtime handle.
338  int fd = ::_open_osfhandle(intptr_t(TempFileHandle), 0);
339  if (fd == -1) {
340    ::CloseHandle(TempFileHandle);
341    ::DeleteFileW(random_path_utf16.begin());
342    // MSDN doesn't say anything about _open_osfhandle setting errno or
343    // GetLastError(), so just return invalid_handle.
344    return make_error_code(windows_error::invalid_handle);
345  }
346
347  result_fd = fd;
348  return make_error_code(errc::success);
349}
350} // end namespace fs
351} // end namespace sys
352} // end namespace llvm
353