Missed some StringRefRefs.
[oota-llvm.git] / lib / Support / Windows / PathV2.inc
1 //===- llvm/Support/Windows/PathV2.inc - 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 <fcntl.h>
22 #include <io.h>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25
26 // MinGW doesn't define this.
27 #ifndef _ERRNO_T_DEFINED
28 #define _ERRNO_T_DEFINED
29 typedef int errno_t;
30 #endif
31
32 using namespace llvm;
33
34 namespace {
35   typedef BOOLEAN (WINAPI *PtrCreateSymbolicLinkW)(
36     /*__in*/ LPCWSTR lpSymlinkFileName,
37     /*__in*/ LPCWSTR lpTargetFileName,
38     /*__in*/ DWORD dwFlags);
39
40   PtrCreateSymbolicLinkW create_symbolic_link_api = PtrCreateSymbolicLinkW(
41     ::GetProcAddress(::GetModuleHandleA("kernel32.dll"),
42                      "CreateSymbolicLinkW"));
43
44   error_code UTF8ToUTF16(StringRef utf8, SmallVectorImpl<wchar_t> &utf16) {
45     int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
46                                     utf8.begin(), utf8.size(),
47                                     utf16.begin(), 0);
48
49     if (len == 0)
50       return windows_error(::GetLastError());
51
52     utf16.reserve(len + 1);
53     utf16.set_size(len);
54
55     len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
56                                     utf8.begin(), utf8.size(),
57                                     utf16.begin(), utf16.size());
58
59     if (len == 0)
60       return windows_error(::GetLastError());
61
62     // Make utf16 null terminated.
63     utf16.push_back(0);
64     utf16.pop_back();
65
66     return success;
67   }
68
69   error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
70                                SmallVectorImpl<char> &utf8) {
71     // Get length.
72     int len = ::WideCharToMultiByte(CP_UTF8, 0,
73                                     utf16, utf16_len,
74                                     utf8.begin(), 0,
75                                     NULL, NULL);
76
77     if (len == 0)
78       return windows_error(::GetLastError());
79
80     utf8.reserve(len);
81     utf8.set_size(len);
82
83     // Now do the actual conversion.
84     len = ::WideCharToMultiByte(CP_UTF8, 0,
85                                 utf16, utf16_len,
86                                 utf8.data(), utf8.size(),
87                                 NULL, NULL);
88
89     if (len == 0)
90       return windows_error(::GetLastError());
91
92     // Make utf8 null terminated.
93     utf8.push_back(0);
94     utf8.pop_back();
95
96     return success;
97   }
98
99   error_code TempDir(SmallVectorImpl<wchar_t> &result) {
100   retry_temp_dir:
101     DWORD len = ::GetTempPathW(result.capacity(), result.begin());
102
103     if (len == 0)
104       return windows_error(::GetLastError());
105
106     if (len > result.capacity()) {
107       result.reserve(len);
108       goto retry_temp_dir;
109     }
110
111     result.set_size(len);
112     return success;
113   }
114
115   // Forwarder for ScopedHandle.
116   BOOL WINAPI CryptReleaseContext(HCRYPTPROV Provider) {
117     return ::CryptReleaseContext(Provider, 0);
118   }
119
120   typedef ScopedHandle<HCRYPTPROV, uintptr_t(-1),
121                        BOOL (WINAPI*)(HCRYPTPROV), CryptReleaseContext>
122     ScopedCryptContext;
123   bool is_separator(const wchar_t value) {
124     switch (value) {
125     case L'\\':
126     case L'/':
127       return true;
128     default:
129       return false;
130     }
131   }
132 }
133
134 namespace llvm {
135 namespace sys  {
136 namespace fs {
137
138 error_code current_path(SmallVectorImpl<char> &result) {
139   SmallVector<wchar_t, 128> cur_path;
140   cur_path.reserve(128);
141 retry_cur_dir:
142   DWORD len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
143
144   // A zero return value indicates a failure other than insufficient space.
145   if (len == 0)
146     return windows_error(::GetLastError());
147
148   // If there's insufficient space, the len returned is larger than the len
149   // given.
150   if (len > cur_path.capacity()) {
151     cur_path.reserve(len);
152     goto retry_cur_dir;
153   }
154
155   cur_path.set_size(len);
156   // cur_path now holds the current directory in utf-16. Convert to utf-8.
157
158   // Find out how much space we need. Sadly, this function doesn't return the
159   // size needed unless you tell it the result size is 0, which means you
160   // _always_ have to call it twice.
161   len = ::WideCharToMultiByte(CP_UTF8, 0,
162                               cur_path.data(), cur_path.size(),
163                               result.data(), 0,
164                               NULL, NULL);
165
166   if (len == 0)
167     return make_error_code(windows_error(::GetLastError()));
168
169   result.reserve(len);
170   result.set_size(len);
171   // Now do the actual conversion.
172   len = ::WideCharToMultiByte(CP_UTF8, 0,
173                               cur_path.data(), cur_path.size(),
174                               result.data(), result.size(),
175                               NULL, NULL);
176   if (len == 0)
177     return windows_error(::GetLastError());
178
179   return success;
180 }
181
182 error_code copy_file(const Twine &from, const Twine &to, copy_option copt) {
183   // Get arguments.
184   SmallString<128> from_storage;
185   SmallString<128> to_storage;
186   StringRef f = from.toStringRef(from_storage);
187   StringRef t = to.toStringRef(to_storage);
188
189   // Convert to utf-16.
190   SmallVector<wchar_t, 128> wide_from;
191   SmallVector<wchar_t, 128> wide_to;
192   if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
193   if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
194
195   // Copy the file.
196   BOOL res = ::CopyFileW(wide_from.begin(), wide_to.begin(),
197                          copt != copy_option::overwrite_if_exists);
198
199   if (res == 0)
200     return windows_error(::GetLastError());
201
202   return success;
203 }
204
205 error_code create_directory(const Twine &path, bool &existed) {
206   SmallString<128> path_storage;
207   SmallVector<wchar_t, 128> path_utf16;
208
209   if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
210                                   path_utf16))
211     return ec;
212
213   if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
214     error_code ec = windows_error(::GetLastError());
215     if (ec == windows_error::already_exists)
216       existed = true;
217     else
218       return ec;
219   } else
220     existed = false;
221
222   return success;
223 }
224
225 error_code create_hard_link(const Twine &to, const Twine &from) {
226   // Get arguments.
227   SmallString<128> from_storage;
228   SmallString<128> to_storage;
229   StringRef f = from.toStringRef(from_storage);
230   StringRef t = to.toStringRef(to_storage);
231
232   // Convert to utf-16.
233   SmallVector<wchar_t, 128> wide_from;
234   SmallVector<wchar_t, 128> wide_to;
235   if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
236   if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
237
238   if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
239     return windows_error(::GetLastError());
240
241   return success;
242 }
243
244 error_code create_symlink(const Twine &to, const Twine &from) {
245   // Only do it if the function is available at runtime.
246   if (!create_symbolic_link_api)
247     return make_error_code(errc::function_not_supported);
248
249   // Get arguments.
250   SmallString<128> from_storage;
251   SmallString<128> to_storage;
252   StringRef f = from.toStringRef(from_storage);
253   StringRef t = to.toStringRef(to_storage);
254
255   // Convert to utf-16.
256   SmallVector<wchar_t, 128> wide_from;
257   SmallVector<wchar_t, 128> wide_to;
258   if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
259   if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
260
261   if (!create_symbolic_link_api(wide_from.begin(), wide_to.begin(), 0))
262     return windows_error(::GetLastError());
263
264   return success;
265 }
266
267 error_code remove(const Twine &path, bool &existed) {
268   SmallString<128> path_storage;
269   SmallVector<wchar_t, 128> path_utf16;
270
271   if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
272                                   path_utf16))
273     return ec;
274
275   if (!::DeleteFileW(path_utf16.begin())) {
276     error_code ec = windows_error(::GetLastError());
277     if (ec != windows_error::file_not_found)
278       return ec;
279     existed = false;
280   } else
281     existed = true;
282
283   return success;
284 }
285
286 error_code rename(const Twine &from, const Twine &to) {
287   // Get arguments.
288   SmallString<128> from_storage;
289   SmallString<128> to_storage;
290   StringRef f = from.toStringRef(from_storage);
291   StringRef t = to.toStringRef(to_storage);
292
293   // Convert to utf-16.
294   SmallVector<wchar_t, 128> wide_from;
295   SmallVector<wchar_t, 128> wide_to;
296   if (error_code ec = UTF8ToUTF16(f, wide_from)) return ec;
297   if (error_code ec = UTF8ToUTF16(t, wide_to)) return ec;
298
299   if (!::MoveFileW(wide_from.begin(), wide_to.begin()))
300     return windows_error(::GetLastError());
301
302   return success;
303 }
304
305 error_code resize_file(const Twine &path, uint64_t size) {
306   SmallString<128> path_storage;
307   SmallVector<wchar_t, 128> path_utf16;
308
309   if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
310                                   path_utf16))
311     return ec;
312
313   int fd = ::_wopen(path_utf16.begin(), O_BINARY, S_IREAD | S_IWRITE);
314   if (fd == -1)
315     return error_code(errno, generic_category());
316 #ifdef HAVE__CHSIZE_S
317   errno_t error = ::_chsize_s(fd, size);
318 #else
319   errno_t error = ::_chsize(fd, size);
320 #endif
321   ::close(fd);
322   return error_code(error, generic_category());
323 }
324
325 error_code exists(const Twine &path, bool &result) {
326   SmallString<128> path_storage;
327   SmallVector<wchar_t, 128> path_utf16;
328
329   if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
330                                   path_utf16))
331     return ec;
332
333   DWORD attributes = ::GetFileAttributesW(path_utf16.begin());
334
335   if (attributes == INVALID_FILE_ATTRIBUTES) {
336     // See if the file didn't actually exist.
337     error_code ec = make_error_code(windows_error(::GetLastError()));
338     if (ec != windows_error::file_not_found &&
339         ec != windows_error::path_not_found)
340       return ec;
341     result = false;
342   } else
343     result = true;
344   return success;
345 }
346
347 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
348   // Get arguments.
349   SmallString<128> a_storage;
350   SmallString<128> b_storage;
351   StringRef a = A.toStringRef(a_storage);
352   StringRef b = B.toStringRef(b_storage);
353
354   // Convert to utf-16.
355   SmallVector<wchar_t, 128> wide_a;
356   SmallVector<wchar_t, 128> wide_b;
357   if (error_code ec = UTF8ToUTF16(a, wide_a)) return ec;
358   if (error_code ec = UTF8ToUTF16(b, wide_b)) return ec;
359
360   AutoHandle HandleB(
361     ::CreateFileW(wide_b.begin(),
362                   0,
363                   FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
364                   0,
365                   OPEN_EXISTING,
366                   FILE_FLAG_BACKUP_SEMANTICS,
367                   0));
368
369   AutoHandle HandleA(
370     ::CreateFileW(wide_a.begin(),
371                   0,
372                   FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
373                   0,
374                   OPEN_EXISTING,
375                   FILE_FLAG_BACKUP_SEMANTICS,
376                   0));
377
378   // If both handles are invalid, it's an error.
379   if (HandleA == INVALID_HANDLE_VALUE &&
380       HandleB == INVALID_HANDLE_VALUE)
381     return windows_error(::GetLastError());
382
383   // If only one is invalid, it's false.
384   if (HandleA == INVALID_HANDLE_VALUE &&
385       HandleB == INVALID_HANDLE_VALUE) {
386     result = false;
387     return success;
388   }
389
390   // Get file information.
391   BY_HANDLE_FILE_INFORMATION InfoA, InfoB;
392   if (!::GetFileInformationByHandle(HandleA, &InfoA))
393     return windows_error(::GetLastError());
394   if (!::GetFileInformationByHandle(HandleB, &InfoB))
395     return windows_error(::GetLastError());
396
397   // See if it's all the same.
398   result =
399     InfoA.dwVolumeSerialNumber           == InfoB.dwVolumeSerialNumber &&
400     InfoA.nFileIndexHigh                 == InfoB.nFileIndexHigh &&
401     InfoA.nFileIndexLow                  == InfoB.nFileIndexLow &&
402     InfoA.nFileSizeHigh                  == InfoB.nFileSizeHigh &&
403     InfoA.nFileSizeLow                   == InfoB.nFileSizeLow &&
404     InfoA.ftLastWriteTime.dwLowDateTime  ==
405       InfoB.ftLastWriteTime.dwLowDateTime &&
406     InfoA.ftLastWriteTime.dwHighDateTime ==
407       InfoB.ftLastWriteTime.dwHighDateTime;
408
409   return success;
410 }
411
412 error_code file_size(const Twine &path, uint64_t &result) {
413   SmallString<128> path_storage;
414   SmallVector<wchar_t, 128> path_utf16;
415
416   if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
417                                   path_utf16))
418     return ec;
419
420   WIN32_FILE_ATTRIBUTE_DATA FileData;
421   if (!::GetFileAttributesExW(path_utf16.begin(),
422                               ::GetFileExInfoStandard,
423                               &FileData))
424     return windows_error(::GetLastError());
425
426   result =
427     (uint64_t(FileData.nFileSizeHigh) << (sizeof(FileData.nFileSizeLow) * 8))
428     + FileData.nFileSizeLow;
429
430   return success;
431 }
432
433 error_code status(const Twine &path, file_status &result) {
434   SmallString<128> path_storage;
435   SmallVector<wchar_t, 128> path_utf16;
436
437   if (error_code ec = UTF8ToUTF16(path.toStringRef(path_storage),
438                                   path_utf16))
439     return ec;
440
441   DWORD attr = ::GetFileAttributesW(path_utf16.begin());
442   if (attr == INVALID_FILE_ATTRIBUTES)
443     goto handle_status_error;
444
445   // Handle reparse points.
446   if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
447     AutoHandle h(
448       ::CreateFileW(path_utf16.begin(),
449                     0, // Attributes only.
450                     FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
451                     NULL,
452                     OPEN_EXISTING,
453                     FILE_FLAG_BACKUP_SEMANTICS,
454                     0));
455     if (h == INVALID_HANDLE_VALUE)
456       goto handle_status_error;
457   }
458
459   if (attr & FILE_ATTRIBUTE_DIRECTORY)
460     result = file_status(file_type::directory_file);
461   else
462     result = file_status(file_type::regular_file);
463
464   return success;
465
466 handle_status_error:
467   error_code ec = windows_error(::GetLastError());
468   if (ec == windows_error::file_not_found ||
469       ec == windows_error::path_not_found)
470     result = file_status(file_type::file_not_found);
471   else if (ec == windows_error::sharing_violation)
472     result = file_status(file_type::type_unknown);
473   else {
474     result = file_status(file_type::status_error);
475     return ec;
476   }
477
478   return success;
479 }
480
481 error_code unique_file(const Twine &model, int &result_fd,
482                              SmallVectorImpl<char> &result_path) {
483   // Use result_path as temp storage.
484   result_path.set_size(0);
485   StringRef m = model.toStringRef(result_path);
486
487   SmallVector<wchar_t, 128> model_utf16;
488   if (error_code ec = UTF8ToUTF16(m, model_utf16)) return ec;
489
490   // Make model absolute by prepending a temp directory if it's not already.
491   bool absolute = path::is_absolute(m);
492
493   if (!absolute) {
494     SmallVector<wchar_t, 64> temp_dir;
495     if (error_code ec = TempDir(temp_dir)) return ec;
496     // Handle c: by removing it.
497     if (model_utf16.size() > 2 && model_utf16[1] == L':') {
498       model_utf16.erase(model_utf16.begin(), model_utf16.begin() + 2);
499     }
500     model_utf16.insert(model_utf16.begin(), temp_dir.begin(), temp_dir.end());
501   }
502
503   // Replace '%' with random chars. From here on, DO NOT modify model. It may be
504   // needed if the randomly chosen path already exists.
505   SmallVector<wchar_t, 128> random_path_utf16;
506
507   // Get a Crypto Provider for CryptGenRandom.
508   HCRYPTPROV HCPC;
509   if (!::CryptAcquireContextW(&HCPC,
510                               NULL,
511                               NULL,
512                               PROV_RSA_FULL,
513                               0))
514     return windows_error(::GetLastError());
515   ScopedCryptContext CryptoProvider(HCPC);
516
517 retry_random_path:
518   random_path_utf16.set_size(0);
519   for (SmallVectorImpl<wchar_t>::const_iterator i = model_utf16.begin(),
520                                                 e = model_utf16.end();
521                                                 i != e; ++i) {
522     if (*i == L'%') {
523       BYTE val = 0;
524       if (!::CryptGenRandom(CryptoProvider, 1, &val))
525           return windows_error(::GetLastError());
526       random_path_utf16.push_back("0123456789abcdef"[val & 15]);
527     }
528     else
529       random_path_utf16.push_back(*i);
530   }
531   // Make random_path_utf16 null terminated.
532   random_path_utf16.push_back(0);
533   random_path_utf16.pop_back();
534
535   // Try to create + open the path.
536 retry_create_file:
537   HANDLE TempFileHandle = ::CreateFileW(random_path_utf16.begin(),
538                                         GENERIC_READ | GENERIC_WRITE,
539                                         FILE_SHARE_READ,
540                                         NULL,
541                                         // Return ERROR_FILE_EXISTS if the file
542                                         // already exists.
543                                         CREATE_NEW,
544                                         FILE_ATTRIBUTE_TEMPORARY,
545                                         NULL);
546   if (TempFileHandle == INVALID_HANDLE_VALUE) {
547     // If the file existed, try again, otherwise, error.
548     error_code ec = windows_error(::GetLastError());
549     if (ec == windows_error::file_exists)
550       goto retry_random_path;
551     // Check for non-existing parent directories.
552     if (ec == windows_error::path_not_found) {
553       // Create the directories using result_path as temp storage.
554       if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
555                                       random_path_utf16.size(), result_path))
556         return ec;
557       StringRef p(result_path.begin(), result_path.size());
558       SmallString<64> dir_to_create;
559       for (path::const_iterator i = path::begin(p),
560                                 e = --path::end(p); i != e; ++i) {
561         path::append(dir_to_create, *i);
562         bool Exists;
563         if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
564         if (!Exists) {
565           // If c: doesn't exist, bail.
566           if (i->endswith(":"))
567             return ec;
568
569           SmallVector<wchar_t, 64> dir_to_create_utf16;
570           if (error_code ec = UTF8ToUTF16(dir_to_create, dir_to_create_utf16))
571             return ec;
572
573           // Create the directory.
574           if (!::CreateDirectoryW(dir_to_create_utf16.begin(), NULL))
575             return windows_error(::GetLastError());
576         }
577       }
578       goto retry_create_file;
579     }
580     return ec;
581   }
582
583   // Set result_path to the utf-8 representation of the path.
584   if (error_code ec = UTF16ToUTF8(random_path_utf16.begin(),
585                                   random_path_utf16.size(), result_path)) {
586     ::CloseHandle(TempFileHandle);
587     ::DeleteFileW(random_path_utf16.begin());
588     return ec;
589   }
590
591   // Convert the Windows API file handle into a C-runtime handle.
592   int fd = ::_open_osfhandle(intptr_t(TempFileHandle), 0);
593   if (fd == -1) {
594     ::CloseHandle(TempFileHandle);
595     ::DeleteFileW(random_path_utf16.begin());
596     // MSDN doesn't say anything about _open_osfhandle setting errno or
597     // GetLastError(), so just return invalid_handle.
598     return windows_error::invalid_handle;
599   }
600
601   result_fd = fd;
602   return success;
603 }
604
605 error_code directory_iterator_construct(directory_iterator &it, StringRef path){
606   SmallVector<wchar_t, 128> path_utf16;
607
608   if (error_code ec = UTF8ToUTF16(path,
609                                   path_utf16))
610     return ec;
611
612   // Convert path to the format that Windows is happy with.
613   if (path_utf16.size() > 0 &&
614       !is_separator(path_utf16[path.size() - 1]) &&
615       path_utf16[path.size() - 1] != L':') {
616     path_utf16.push_back(L'\\');
617     path_utf16.push_back(L'*');
618   } else {
619     path_utf16.push_back(L'*');
620   }
621
622   //  Get the first directory entry.
623   WIN32_FIND_DATAW FirstFind;
624   ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
625   if (!FindHandle)
626     return windows_error(::GetLastError());
627
628   // Construct the current directory entry.
629   SmallString<128> directory_entry_path_utf8;
630   if (error_code ec = UTF16ToUTF8(FirstFind.cFileName,
631                                   ::wcslen(FirstFind.cFileName),
632                                   directory_entry_path_utf8))
633     return ec;
634
635   it.IterationHandle = intptr_t(FindHandle.take());
636   it.CurrentEntry = directory_entry(path);
637   it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
638
639   return success;
640 }
641
642 error_code directory_iterator_destruct(directory_iterator& it) {
643   if (it.IterationHandle != 0)
644     // Closes the handle if it's valid.
645     ScopedFindHandle close(HANDLE(it.IterationHandle));
646   it.IterationHandle = 0;
647   it.CurrentEntry = directory_entry();
648   return success;
649 }
650
651 error_code directory_iterator_increment(directory_iterator& it) {
652   WIN32_FIND_DATAW FindData;
653   if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
654     error_code ec = windows_error(::GetLastError());
655     // Check for end.
656     if (ec == windows_error::no_more_files)
657       return directory_iterator_destruct(it);
658     return ec;
659   }
660
661   SmallString<128> directory_entry_path_utf8;
662   if (error_code ec = UTF16ToUTF8(FindData.cFileName,
663                                   ::wcslen(FindData.cFileName),
664                                   directory_entry_path_utf8))
665     return ec;
666
667   it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
668   return success;
669 }
670
671 } // end namespace fs
672 } // end namespace sys
673 } // end namespace llvm