d374dccdeb6ebf8aadc184d51fa6f67d8fc85a31
[oota-llvm.git] / lib / Support / Windows / PathV2.inc
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
23 using namespace llvm;
24
25 namespace {
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
109 namespace llvm {
110 namespace sys  {
111 namespace path {
112
113 error_code current_path(SmallVectorImpl<char> &result) {
114   SmallVector<wchar_t, 128> cur_path;
115   cur_path.reserve(128);
116 retry_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
159 namespace fs {
160
161 error_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
184 error_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
204 error_code create_hard_link(const Twine &to, const Twine &from) {
205   // Get arguments.
206   SmallString<128> from_storage;
207   SmallString<128> to_storage;
208   StringRef f = from.toStringRef(from_storage);
209   StringRef t = to.toStringRef(to_storage);
210
211   // Convert to utf-16.
212   SmallVector<wchar_t, 128> wide_from;
213   SmallVector<wchar_t, 128> wide_to;
214   if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
215   if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
216
217   if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
218     return make_error_code(windows_error(::GetLastError()));
219
220   return make_error_code(errc::success);
221 }
222
223 error_code exists(const Twine &path, bool &result) {
224   SmallString<128> path_storage;
225   SmallVector<wchar_t, 128> path_utf16;
226
227   if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
228                                   path_utf16))
229     return ec;
230
231   DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
232
233   if (attributes == INVALID_FILE_ATTRIBUTES) {
234     // See if the file didn't actually exist.
235     error_code ec = make_error_code(windows_error(::GetLastError()));
236     if (ec != error_code(windows_error::file_not_found) &&
237         ec != error_code(windows_error::path_not_found))
238       return ec;
239     result = false;
240   } else
241     result = true;
242   return make_error_code(errc::success);
243 }
244
245 error_code unique_file(const Twine &model, int &result_fd,
246                              SmallVectorImpl<char> &result_path) {
247   // Use result_path as temp storage.
248   result_path.set_size(0);
249   StringRef m = model.toStringRef(result_path);
250
251   SmallVector<wchar_t, 128> model_utf16;
252   if (error_code ec = UTF8ToUTF16(m, model_utf16)) return ec;
253
254   // Make model absolute by prepending a temp directory if it's not already.
255   bool absolute;
256   if (error_code ec = path::is_absolute(m, absolute)) return ec;
257
258   if (!absolute) {
259     SmallVector<wchar_t, 64> temp_dir;
260     if (error_code ec = TempDir(temp_dir)) return ec;
261     // Handle c: by removing it.
262     if (model_utf16.size() > 2 && model_utf16[1] == L':') {
263       model_utf16.erase(model_utf16.begin(), model_utf16.begin() + 2);
264     }
265     model_utf16.insert(model_utf16.begin(), temp_dir.begin(), temp_dir.end());
266   }
267
268   // Replace '%' with random chars. From here on, DO NOT modify model. It may be
269   // needed if the randomly chosen path already exists.
270   SmallVector<wchar_t, 128> random_path_utf16;
271
272   // Get a Crypto Provider for CryptGenRandom.
273   AutoCryptoProvider CryptoProvider;
274   BOOL success = ::CryptAcquireContextW(&CryptoProvider.CryptoProvider,
275                                         NULL,
276                                         NULL,
277                                         PROV_RSA_FULL,
278                                         NULL);
279   if (!success)
280     return make_error_code(windows_error(::GetLastError()));
281
282 retry_random_path:
283   random_path_utf16.set_size(0);
284   for (SmallVectorImpl<wchar_t>::const_iterator i = model_utf16.begin(),
285                                                 e = model_utf16.end();
286                                                 i != e; ++i) {
287     if (*i == L'%') {
288       BYTE val = 0;
289       if (!::CryptGenRandom(CryptoProvider, 1, &val))
290           return make_error_code(windows_error(::GetLastError()));
291       random_path_utf16.push_back("0123456789abcdef"[val & 15]);
292     }
293     else
294       random_path_utf16.push_back(*i);
295   }
296   // Make random_path_utf16 null terminated.
297   random_path_utf16.push_back(0);
298   random_path_utf16.pop_back();
299
300   // Try to create + open the path.
301 retry_create_file:
302   HANDLE TempFileHandle = ::CreateFileW(random_path_utf16.begin(),
303                                         GENERIC_READ | GENERIC_WRITE,
304                                         FILE_SHARE_READ,
305                                         NULL,
306                                         // Return ERROR_FILE_EXISTS if the file
307                                         // already exists.
308                                         CREATE_NEW,
309                                         FILE_ATTRIBUTE_TEMPORARY,
310                                         NULL);
311   if (TempFileHandle == INVALID_HANDLE_VALUE) {
312     // If the file existed, try again, otherwise, error.
313     error_code ec = make_error_code(windows_error(::GetLastError()));
314     if (ec == error_code(windows_error::file_exists))
315       goto retry_random_path;
316     // Check for non-existing parent directories.
317     if (ec == error_code(windows_error::path_not_found)) {
318       // Create the directories using result_path as temp storage.
319       if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
320                                       random_path_utf16.size(), result_path))
321         return ec;
322       StringRef p(result_path.begin(), result_path.size());
323       SmallString<64> dir_to_create;
324       for (path::const_iterator i = path::begin(p),
325                                 e = --path::end(p); i != e; ++i) {
326         if (error_code ec = path::append(dir_to_create, *i)) return ec;
327         bool Exists;
328         if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
329         if (!Exists) {
330           // If c: doesn't exist, bail.
331           if (i->endswith(":"))
332             return ec;
333
334           SmallVector<wchar_t, 64> dir_to_create_utf16;
335           if (error_code ec = UTF8ToUTF16(dir_to_create, dir_to_create_utf16))
336             return ec;
337
338           // Create the directory.
339           if (!::CreateDirectoryW(dir_to_create_utf16.begin(), NULL))
340             return make_error_code(windows_error(::GetLastError()));
341         }
342       }
343       goto retry_create_file;
344     }
345     return ec;
346   }
347
348   // Set result_path to the utf-8 representation of the path.
349   if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
350                                   random_path_utf16.size(), result_path)) {
351     ::CloseHandle(TempFileHandle);
352     ::DeleteFileW(random_path_utf16.begin());
353     return ec;
354   }
355
356   // Convert the Windows API file handle into a C-runtime handle.
357   int fd = ::_open_osfhandle(intptr_t(TempFileHandle), 0);
358   if (fd == -1) {
359     ::CloseHandle(TempFileHandle);
360     ::DeleteFileW(random_path_utf16.begin());
361     // MSDN doesn't say anything about _open_osfhandle setting errno or
362     // GetLastError(), so just return invalid_handle.
363     return make_error_code(windows_error::invalid_handle);
364   }
365
366   result_fd = fd;
367   return make_error_code(errc::success);
368 }
369 } // end namespace fs
370 } // end namespace sys
371 } // end namespace llvm