Support/FileSystem: Add unique_file and exists implementations.
[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.toNullTerminatedStringRef(from_storage);
166   StringRef t = to.toNullTerminatedStringRef(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 exists(const Twine &path, bool &result) {
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   DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
193
194   if (attributes == INVALID_FILE_ATTRIBUTES) {
195     // See if the file didn't actually exist.
196     error_code ec = make_error_code(windows_error(::GetLastError()));
197     if (ec != error_code(windows_error::file_not_found) &&
198         ec != error_code(windows_error::path_not_found))
199       return ec;
200     result = false;
201   } else
202     result = true;
203   return make_error_code(errc::success);
204 }
205
206 error_code unique_file(const Twine &model, int &result_fd,
207                              SmallVectorImpl<char> &result_path) {
208   // Use result_path as temp storage.
209   result_path.set_size(0);
210   StringRef m = model.toStringRef(result_path);
211
212   SmallVector<wchar_t, 128> model_utf16;
213   if (error_code ec = UTF8ToUTF16(m, model_utf16)) return ec;
214
215   // Make model absolute by prepending a temp directory if it's not already.
216   bool absolute;
217   if (error_code ec = path::is_absolute(m, absolute)) return ec;
218
219   if (!absolute) {
220     SmallVector<wchar_t, 64> temp_dir;
221     if (error_code ec = TempDir(temp_dir)) return ec;
222     // Handle c: by removing it.
223     if (model_utf16.size() > 2 && model_utf16[1] == L':') {
224       model_utf16.erase(model_utf16.begin(), model_utf16.begin() + 2);
225     }
226     model_utf16.insert(model_utf16.begin(), temp_dir.begin(), temp_dir.end());
227   }
228
229   // Replace '%' with random chars. From here on, DO NOT modify model. It may be
230   // needed if the randomly chosen path already exists.
231   SmallVector<wchar_t, 128> random_path_utf16;
232
233   // Get a Crypto Provider for CryptGenRandom.
234   AutoCryptoProvider CryptoProvider;
235   BOOL success = ::CryptAcquireContextW(&CryptoProvider.CryptoProvider,
236                                         NULL,
237                                         NULL,
238                                         PROV_RSA_FULL,
239                                         NULL);
240   if (!success)
241     return make_error_code(windows_error(::GetLastError()));
242
243 retry_random_path:
244   random_path_utf16.set_size(0);
245   for (SmallVectorImpl<wchar_t>::const_iterator i = model_utf16.begin(),
246                                                 e = model_utf16.end();
247                                                 i != e; ++i) {
248     if (*i == L'%') {
249       BYTE val = 0;
250       if (!::CryptGenRandom(CryptoProvider, 1, &val))
251           return make_error_code(windows_error(::GetLastError()));
252       random_path_utf16.push_back("0123456789abcdef"[val & 15]);
253     }
254     else
255       random_path_utf16.push_back(*i);
256   }
257   // Make random_path_utf16 null terminated.
258   random_path_utf16.push_back(0);
259   random_path_utf16.pop_back();
260
261   // Try to create + open the path.
262 retry_create_file:
263   HANDLE TempFileHandle = ::CreateFileW(random_path_utf16.begin(),
264                                         GENERIC_READ | GENERIC_WRITE,
265                                         FILE_SHARE_READ,
266                                         NULL,
267                                         // Return ERROR_FILE_EXISTS if the file
268                                         // already exists.
269                                         CREATE_NEW,
270                                         FILE_ATTRIBUTE_TEMPORARY,
271                                         NULL);
272   if (TempFileHandle == INVALID_HANDLE_VALUE) {
273     // If the file existed, try again, otherwise, error.
274     error_code ec = make_error_code(windows_error(::GetLastError()));
275     if (ec == error_code(windows_error::file_exists))
276       goto retry_random_path;
277     // Check for non-existing parent directories.
278     if (ec == error_code(windows_error::path_not_found)) {
279       // Create the directories using result_path as temp storage.
280       if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
281                                       random_path_utf16.size(), result_path))
282         return ec;
283       StringRef p(result_path.begin(), result_path.size());
284       SmallString<64> dir_to_create;
285       for (path::const_iterator i = path::begin(p),
286                                 e = --path::end(p); i != e; ++i) {
287         if (error_code ec = path::append(dir_to_create, *i)) return ec;
288         bool Exists;
289         if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
290         if (!Exists) {
291           // If c: doesn't exist, bail.
292           if (i->endswith(":"))
293             return ec;
294
295           SmallVector<wchar_t, 64> dir_to_create_utf16;
296           if (error_code ec = UTF8ToUTF16(dir_to_create, dir_to_create_utf16))
297             return ec;
298
299           // Create the directory.
300           if (!::CreateDirectoryW(dir_to_create_utf16.begin(), NULL))
301             return make_error_code(windows_error(::GetLastError()));
302         }
303       }
304       goto retry_create_file;
305     }
306     return ec;
307   }
308
309   // Set result_path to the utf-8 representation of the path.
310   if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
311                                   random_path_utf16.size(), result_path)) {
312     ::CloseHandle(TempFileHandle);
313     ::DeleteFileW(random_path_utf16.begin());
314     return ec;
315   }
316
317   // Convert the Windows API file handle into a C-runtime handle.
318   int fd = ::_open_osfhandle(intptr_t(TempFileHandle), 0);
319   if (fd == -1) {
320     ::CloseHandle(TempFileHandle);
321     ::DeleteFileW(random_path_utf16.begin());
322     // MSDN doesn't say anything about _open_osfhandle setting errno or
323     // GetLastError(), so just return invalid_handle.
324     return make_error_code(windows_error::invalid_handle);
325   }
326
327   result_fd = fd;
328   return make_error_code(errc::success);
329 }
330 } // end namespace fs
331 } // end namespace sys
332 } // end namespace llvm