blob: d8a14b41cb2bc06f13eedaf192b909f004f72efa [file] [log] [blame]
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001//===- llvm/Support/Windows/Path.inc - Windows Path Impl --------*- C++ -*-===//
Michael J. Spencerebad2f92010-11-29 22:28:51 +00002//
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//
Rafael Espindolaf1fc3822013-06-26 19:33:03 +000010// This file implements the Windows specific implementation of the Path API.
Michael J. Spencerebad2f92010-11-29 22:28:51 +000011//
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
Craig Topperf18edae2013-07-15 07:15:05 +000019#include "llvm/ADT/STLExtras.h"
Rafael Espindola5c4f8292014-06-11 19:05:50 +000020#include "llvm/Support/WindowsError.h"
Michael J. Spencerc20a0322010-12-03 17:54:07 +000021#include <fcntl.h>
Michael J. Spencer45710402010-12-03 01:21:28 +000022#include <io.h>
Michael J. Spencerc20a0322010-12-03 17:54:07 +000023#include <sys/stat.h>
24#include <sys/types.h>
Michael J. Spencerebad2f92010-11-29 22:28:51 +000025
NAKAMURA Takumi04d39d72014-02-12 11:50:22 +000026// These two headers must be included last, and make sure shlobj is required
27// after Windows.h to make sure it picks up our definition of _WIN32_WINNT
Reid Klecknerd59e2fa2014-02-12 21:26:20 +000028#include "WindowsSupport.h"
Zachary Turner260bda32017-03-08 22:49:32 +000029#include <shellapi.h>
NAKAMURA Takumi04d39d72014-02-12 11:50:22 +000030#include <shlobj.h>
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000031
Michael J. Spenceref2284f2012-08-15 19:05:47 +000032#undef max
33
Michael J. Spencer60252472010-12-03 18:03:28 +000034// MinGW doesn't define this.
Michael J. Spencer521c3212010-12-03 18:04:11 +000035#ifndef _ERRNO_T_DEFINED
36#define _ERRNO_T_DEFINED
37typedef int errno_t;
Michael J. Spencer60252472010-12-03 18:03:28 +000038#endif
39
Reid Kleckner11da0042013-08-07 20:19:31 +000040#ifdef _MSC_VER
41# pragma comment(lib, "advapi32.lib") // This provides CryptAcquireContextW.
Reid Kleckner304af562016-01-12 18:33:49 +000042# pragma comment(lib, "ole32.lib") // This provides CoTaskMemFree
Reid Kleckner11da0042013-08-07 20:19:31 +000043#endif
44
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000045using namespace llvm;
46
Rui Ueyama471d0c52013-09-10 19:45:51 +000047using llvm::sys::windows::UTF8ToUTF16;
48using llvm::sys::windows::UTF16ToUTF8;
Paul Robinsonc38deee2014-11-24 18:05:29 +000049using llvm::sys::path::widenPath;
Rui Ueyama471d0c52013-09-10 19:45:51 +000050
Rafael Espindola37b012d2014-02-23 15:16:03 +000051static bool is_separator(const wchar_t value) {
52 switch (value) {
53 case L'\\':
54 case L'/':
55 return true;
56 default:
57 return false;
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +000058 }
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000059}
60
Paul Robinsonc38deee2014-11-24 18:05:29 +000061namespace llvm {
62namespace sys {
63namespace path {
64
Paul Robinsond9c4a9a2014-11-13 00:12:14 +000065// Convert a UTF-8 path to UTF-16. Also, if the absolute equivalent of the
66// path is longer than CreateDirectory can tolerate, make it absolute and
67// prefixed by '\\?\'.
Paul Robinsonc38deee2014-11-24 18:05:29 +000068std::error_code widenPath(const Twine &Path8,
69 SmallVectorImpl<wchar_t> &Path16) {
Paul Robinsond9c4a9a2014-11-13 00:12:14 +000070 const size_t MaxDirLen = MAX_PATH - 12; // Must leave room for 8.3 filename.
71
72 // Several operations would convert Path8 to SmallString; more efficient to
73 // do it once up front.
74 SmallString<128> Path8Str;
75 Path8.toVector(Path8Str);
76
77 // If we made this path absolute, how much longer would it get?
78 size_t CurPathLen;
79 if (llvm::sys::path::is_absolute(Twine(Path8Str)))
80 CurPathLen = 0; // No contribution from current_path needed.
81 else {
82 CurPathLen = ::GetCurrentDirectoryW(0, NULL);
83 if (CurPathLen == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +000084 return mapWindowsError(::GetLastError());
Paul Robinsond9c4a9a2014-11-13 00:12:14 +000085 }
86
87 // Would the absolute path be longer than our limit?
88 if ((Path8Str.size() + CurPathLen) >= MaxDirLen &&
89 !Path8Str.startswith("\\\\?\\")) {
90 SmallString<2*MAX_PATH> FullPath("\\\\?\\");
91 if (CurPathLen) {
92 SmallString<80> CurPath;
93 if (std::error_code EC = llvm::sys::fs::current_path(CurPath))
94 return EC;
95 FullPath.append(CurPath);
96 }
97 // Traverse the requested path, canonicalizing . and .. as we go (because
98 // the \\?\ prefix is documented to treat them as real components).
99 // The iterators don't report separators and append() always attaches
100 // preferred_separator so we don't need to call native() on the result.
101 for (llvm::sys::path::const_iterator I = llvm::sys::path::begin(Path8Str),
102 E = llvm::sys::path::end(Path8Str);
103 I != E; ++I) {
104 if (I->size() == 1 && *I == ".")
105 continue;
106 if (I->size() == 2 && *I == "..")
107 llvm::sys::path::remove_filename(FullPath);
108 else
109 llvm::sys::path::append(FullPath, *I);
110 }
111 return UTF8ToUTF16(FullPath, Path16);
112 }
113
114 // Just use the caller's original path.
115 return UTF8ToUTF16(Path8Str, Path16);
116}
Paul Robinsonc38deee2014-11-24 18:05:29 +0000117} // end namespace path
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000118
Michael J. Spencer20daa282010-12-07 01:22:31 +0000119namespace fs {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000120
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000121std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
David Majnemer17a44962013-10-07 09:52:36 +0000122 SmallVector<wchar_t, MAX_PATH> PathName;
123 DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
124
125 // A zero return value indicates a failure other than insufficient space.
126 if (Size == 0)
127 return "";
128
129 // Insufficient space is determined by a return value equal to the size of
130 // the buffer passed in.
131 if (Size == PathName.capacity())
132 return "";
133
134 // On success, GetModuleFileNameW returns the number of characters written to
135 // the buffer not including the NULL terminator.
136 PathName.set_size(Size);
137
138 // Convert the result from UTF-16 to UTF-8.
139 SmallVector<char, MAX_PATH> PathNameUTF8;
140 if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
141 return "";
142
143 return std::string(PathNameUTF8.data());
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000144}
145
Rafael Espindolad1230992013-07-29 21:55:38 +0000146UniqueID file_status::getUniqueID() const {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000147 // The file is uniquely identified by the volume serial number along
148 // with the 64-bit file identifier.
149 uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
150 static_cast<uint64_t>(FileIndexLow);
151
152 return UniqueID(VolumeSerialNumber, FileID);
153}
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000154
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000155ErrorOr<space_info> disk_space(const Twine &Path) {
156 ULARGE_INTEGER Avail, Total, Free;
157 if (!::GetDiskFreeSpaceExA(Path.str().c_str(), &Avail, &Total, &Free))
158 return mapWindowsError(::GetLastError());
159 space_info SpaceInfo;
160 SpaceInfo.capacity =
161 (static_cast<uint64_t>(Total.HighPart) << 32) + Total.LowPart;
Mehdi Amini64719152016-04-01 00:52:05 +0000162 SpaceInfo.free = (static_cast<uint64_t>(Free.HighPart) << 32) + Free.LowPart;
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000163 SpaceInfo.available =
164 (static_cast<uint64_t>(Avail.HighPart) << 32) + Avail.LowPart;
165 return SpaceInfo;
166}
167
Pavel Labath757ca882016-10-24 10:59:17 +0000168TimePoint<> file_status::getLastAccessedTime() const {
169 FILETIME Time;
170 Time.dwLowDateTime = LastAccessedTimeLow;
171 Time.dwHighDateTime = LastAccessedTimeHigh;
172 return toTimePoint(Time);
Mehdi Amini1e39ef32016-03-25 07:30:21 +0000173}
174
Pavel Labath757ca882016-10-24 10:59:17 +0000175TimePoint<> file_status::getLastModificationTime() const {
176 FILETIME Time;
177 Time.dwLowDateTime = LastWriteTimeLow;
178 Time.dwHighDateTime = LastWriteTimeHigh;
179 return toTimePoint(Time);
Rafael Espindoladb5d8fe2013-06-20 18:42:04 +0000180}
181
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000182std::error_code current_path(SmallVectorImpl<char> &result) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000183 SmallVector<wchar_t, MAX_PATH> cur_path;
184 DWORD len = MAX_PATH;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000185
David Majnemer61eae2e2013-10-07 01:00:07 +0000186 do {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000187 cur_path.reserve(len);
David Majnemer61eae2e2013-10-07 01:00:07 +0000188 len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000189
David Majnemer61eae2e2013-10-07 01:00:07 +0000190 // A zero return value indicates a failure other than insufficient space.
191 if (len == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000192 return mapWindowsError(::GetLastError());
David Majnemer61eae2e2013-10-07 01:00:07 +0000193
194 // If there's insufficient space, the len returned is larger than the len
195 // given.
196 } while (len > cur_path.capacity());
197
198 // On success, GetCurrentDirectoryW returns the number of characters not
199 // including the null-terminator.
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000200 cur_path.set_size(len);
Aaron Ballmanb16cf532013-08-16 17:53:28 +0000201 return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000202}
203
Pavel Labath2f096092017-01-24 10:32:03 +0000204std::error_code set_current_path(const Twine &path) {
205 // Convert to utf-16.
206 SmallVector<wchar_t, 128> wide_path;
207 if (std::error_code ec = widenPath(path, wide_path))
208 return ec;
209
210 if (!::SetCurrentDirectoryW(wide_path.begin()))
211 return mapWindowsError(::GetLastError());
212
213 return std::error_code();
214}
215
Frederic Riss6b9396c2015-08-06 21:04:55 +0000216std::error_code create_directory(const Twine &path, bool IgnoreExisting,
217 perms Perms) {
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000218 SmallVector<wchar_t, 128> path_utf16;
219
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000220 if (std::error_code ec = widenPath(path, path_utf16))
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000221 return ec;
222
223 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000224 DWORD LastError = ::GetLastError();
225 if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000226 return mapWindowsError(LastError);
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000227 }
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000228
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000229 return std::error_code();
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000230}
231
Rafael Espindola83f858e2014-03-11 18:40:24 +0000232// We can't use symbolic links for windows.
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000233std::error_code create_link(const Twine &to, const Twine &from) {
Michael J. Spencere0c45602010-12-03 05:58:41 +0000234 // Convert to utf-16.
235 SmallVector<wchar_t, 128> wide_from;
236 SmallVector<wchar_t, 128> wide_to;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000237 if (std::error_code ec = widenPath(from, wide_from))
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000238 return ec;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000239 if (std::error_code ec = widenPath(to, wide_to))
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000240 return ec;
Michael J. Spencere0c45602010-12-03 05:58:41 +0000241
242 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
Yaron Kerenf8e65172015-05-04 04:48:10 +0000243 return mapWindowsError(::GetLastError());
Michael J. Spencere0c45602010-12-03 05:58:41 +0000244
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000245 return std::error_code();
Michael J. Spencere0c45602010-12-03 05:58:41 +0000246}
247
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000248std::error_code create_hard_link(const Twine &to, const Twine &from) {
249 return create_link(to, from);
250}
251
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000252std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000253 SmallVector<wchar_t, 128> path_utf16;
254
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000255 file_status ST;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000256 if (std::error_code EC = status(path, ST)) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000257 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000258 return EC;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000259 return std::error_code();
Rafael Espindola107b74c2013-07-31 00:10:25 +0000260 }
Michael J. Spencer153749b2011-01-05 16:39:22 +0000261
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000262 if (std::error_code ec = widenPath(path, path_utf16))
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000263 return ec;
264
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000265 if (ST.type() == file_type::directory_file) {
Michael J. Spencer153749b2011-01-05 16:39:22 +0000266 if (!::RemoveDirectoryW(c_str(path_utf16))) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000267 std::error_code EC = mapWindowsError(::GetLastError());
Rafael Espindola2a826e42014-06-13 17:20:48 +0000268 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000269 return EC;
270 }
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000271 return std::error_code();
Michael J. Spencer153749b2011-01-05 16:39:22 +0000272 }
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000273 if (!::DeleteFileW(c_str(path_utf16))) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000274 std::error_code EC = mapWindowsError(::GetLastError());
Rafael Espindola2a826e42014-06-13 17:20:48 +0000275 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000276 return EC;
277 }
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000278 return std::error_code();
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000279}
280
Zachary Turner392ed9d2017-02-21 20:55:47 +0000281static std::error_code is_local_internal(SmallVectorImpl<wchar_t> &Path,
282 bool &Result) {
283 SmallVector<wchar_t, 128> VolumePath;
284 size_t Len = 128;
285 while (true) {
286 VolumePath.resize(Len);
287 BOOL Success =
288 ::GetVolumePathNameW(Path.data(), VolumePath.data(), VolumePath.size());
289
290 if (Success)
291 break;
292
293 DWORD Err = ::GetLastError();
294 if (Err != ERROR_INSUFFICIENT_BUFFER)
295 return mapWindowsError(Err);
296
297 Len *= 2;
298 }
299 // If the output buffer has exactly enough space for the path name, but not
300 // the null terminator, it will leave the output unterminated. Push a null
301 // terminator onto the end to ensure that this never happens.
302 VolumePath.push_back(L'\0');
303 VolumePath.set_size(wcslen(VolumePath.data()));
304 const wchar_t *P = VolumePath.data();
305
306 UINT Type = ::GetDriveTypeW(P);
307 switch (Type) {
308 case DRIVE_FIXED:
309 Result = true;
310 return std::error_code();
311 case DRIVE_REMOTE:
312 case DRIVE_CDROM:
313 case DRIVE_RAMDISK:
314 case DRIVE_REMOVABLE:
315 Result = false;
316 return std::error_code();
317 default:
318 return make_error_code(errc::no_such_file_or_directory);
319 }
320 llvm_unreachable("Unreachable!");
321}
322
323std::error_code is_local(const Twine &path, bool &result) {
324 if (!llvm::sys::fs::exists(path) || !llvm::sys::path::has_root_path(path))
325 return make_error_code(errc::no_such_file_or_directory);
326
327 SmallString<128> Storage;
328 StringRef P = path.toStringRef(Storage);
329
330 // Convert to utf-16.
331 SmallVector<wchar_t, 128> WidePath;
332 if (std::error_code ec = widenPath(P, WidePath))
333 return ec;
334 return is_local_internal(WidePath, result);
335}
336
337std::error_code is_local(int FD, bool &Result) {
338 SmallVector<wchar_t, 128> FinalPath;
339 HANDLE Handle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
340
341 size_t Len = 128;
342 do {
343 FinalPath.reserve(Len);
344 Len = ::GetFinalPathNameByHandleW(Handle, FinalPath.data(),
345 FinalPath.capacity() - 1, VOLUME_NAME_NT);
346 if (Len == 0)
347 return mapWindowsError(::GetLastError());
348 } while (Len > FinalPath.capacity());
349
350 FinalPath.set_size(Len);
351
352 return is_local_internal(FinalPath, Result);
353}
354
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000355std::error_code rename(const Twine &from, const Twine &to) {
Michael J. Spencer409f5562010-12-03 17:53:55 +0000356 // Convert to utf-16.
357 SmallVector<wchar_t, 128> wide_from;
358 SmallVector<wchar_t, 128> wide_to;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000359 if (std::error_code ec = widenPath(from, wide_from))
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000360 return ec;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000361 if (std::error_code ec = widenPath(to, wide_to))
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000362 return ec;
Michael J. Spencer409f5562010-12-03 17:53:55 +0000363
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000364 std::error_code ec = std::error_code();
Greg Bedwell7f68a712015-10-12 15:11:47 +0000365
Sunil Srivastava34fce932016-03-25 23:41:28 +0000366 // Retry while we see recoverable errors.
Greg Bedwell7f68a712015-10-12 15:11:47 +0000367 // System scanners (eg. indexer) might open the source file when it is written
368 // and closed.
369
Sunil Srivastava34fce932016-03-25 23:41:28 +0000370 bool TryReplace = true;
Greg Bedwell7f68a712015-10-12 15:11:47 +0000371
Sunil Srivastava34fce932016-03-25 23:41:28 +0000372 for (int i = 0; i < 2000; i++) {
373 if (i > 0)
374 ::Sleep(1);
375
376 if (TryReplace) {
377 // Try ReplaceFile first, as it is able to associate a new data stream
378 // with the destination even if the destination file is currently open.
379 if (::ReplaceFileW(wide_to.data(), wide_from.data(), NULL, 0, NULL, NULL))
380 return std::error_code();
381
382 DWORD ReplaceError = ::GetLastError();
383 ec = mapWindowsError(ReplaceError);
384
385 // If ReplaceFileW returned ERROR_UNABLE_TO_MOVE_REPLACEMENT or
386 // ERROR_UNABLE_TO_MOVE_REPLACEMENT_2, retry but only use MoveFileExW().
387 if (ReplaceError == ERROR_UNABLE_TO_MOVE_REPLACEMENT ||
388 ReplaceError == ERROR_UNABLE_TO_MOVE_REPLACEMENT_2) {
389 TryReplace = false;
390 continue;
391 }
392 // If ReplaceFileW returned ERROR_UNABLE_TO_REMOVE_REPLACED, retry
393 // using ReplaceFileW().
394 if (ReplaceError == ERROR_UNABLE_TO_REMOVE_REPLACED)
395 continue;
396 // We get ERROR_FILE_NOT_FOUND if the destination file is missing.
397 // MoveFileEx can handle this case.
398 if (ReplaceError != ERROR_ACCESS_DENIED &&
399 ReplaceError != ERROR_FILE_NOT_FOUND &&
400 ReplaceError != ERROR_SHARING_VIOLATION)
401 break;
402 }
Greg Bedwell7f68a712015-10-12 15:11:47 +0000403
NAKAMURA Takumi3b7f9952012-05-08 14:31:46 +0000404 if (::MoveFileExW(wide_from.begin(), wide_to.begin(),
405 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000406 return std::error_code();
Greg Bedwell7f68a712015-10-12 15:11:47 +0000407
408 DWORD MoveError = ::GetLastError();
409 ec = mapWindowsError(MoveError);
410 if (MoveError != ERROR_ACCESS_DENIED) break;
NAKAMURA Takumi3b7f9952012-05-08 14:31:46 +0000411 }
Michael J. Spencer409f5562010-12-03 17:53:55 +0000412
NAKAMURA Takumi3b7f9952012-05-08 14:31:46 +0000413 return ec;
Michael J. Spencer409f5562010-12-03 17:53:55 +0000414}
415
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000416std::error_code resize_file(int FD, uint64_t Size) {
Michael J. Spencerca242f22010-12-03 18:48:56 +0000417#ifdef HAVE__CHSIZE_S
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000418 errno_t error = ::_chsize_s(FD, Size);
Michael J. Spencerca242f22010-12-03 18:48:56 +0000419#else
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000420 errno_t error = ::_chsize(FD, Size);
Michael J. Spencerca242f22010-12-03 18:48:56 +0000421#endif
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000422 return std::error_code(error, std::generic_category());
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000423}
424
Rafael Espindola281f23a2014-09-11 20:30:02 +0000425std::error_code access(const Twine &Path, AccessMode Mode) {
Rafael Espindola281f23a2014-09-11 20:30:02 +0000426 SmallVector<wchar_t, 128> PathUtf16;
Michael J. Spencer45710402010-12-03 01:21:28 +0000427
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000428 if (std::error_code EC = widenPath(Path, PathUtf16))
Rafael Espindola281f23a2014-09-11 20:30:02 +0000429 return EC;
Michael J. Spencer45710402010-12-03 01:21:28 +0000430
Rafael Espindola281f23a2014-09-11 20:30:02 +0000431 DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
Michael J. Spencer45710402010-12-03 01:21:28 +0000432
Rafael Espindola281f23a2014-09-11 20:30:02 +0000433 if (Attributes == INVALID_FILE_ATTRIBUTES) {
Michael J. Spencer45710402010-12-03 01:21:28 +0000434 // See if the file didn't actually exist.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000435 DWORD LastError = ::GetLastError();
436 if (LastError != ERROR_FILE_NOT_FOUND &&
437 LastError != ERROR_PATH_NOT_FOUND)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000438 return mapWindowsError(LastError);
Rafael Espindola281f23a2014-09-11 20:30:02 +0000439 return errc::no_such_file_or_directory;
440 }
441
442 if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
443 return errc::permission_denied;
444
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000445 return std::error_code();
Michael J. Spencer45710402010-12-03 01:21:28 +0000446}
447
Reid Kleckner89d4b1a2015-09-10 23:28:06 +0000448bool can_execute(const Twine &Path) {
449 return !access(Path, AccessMode::Execute) ||
450 !access(Path + ".exe", AccessMode::Execute);
451}
452
Michael J. Spencer203d7802011-12-12 06:04:28 +0000453bool equivalent(file_status A, file_status B) {
454 assert(status_known(A) && status_known(B));
Mehdi Amini1e39ef32016-03-25 07:30:21 +0000455 return A.FileIndexHigh == B.FileIndexHigh &&
456 A.FileIndexLow == B.FileIndexLow &&
457 A.FileSizeHigh == B.FileSizeHigh &&
458 A.FileSizeLow == B.FileSizeLow &&
459 A.LastAccessedTimeHigh == B.LastAccessedTimeHigh &&
460 A.LastAccessedTimeLow == B.LastAccessedTimeLow &&
461 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
462 A.LastWriteTimeLow == B.LastWriteTimeLow &&
463 A.VolumeSerialNumber == B.VolumeSerialNumber;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000464}
465
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000466std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000467 file_status fsA, fsB;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000468 if (std::error_code ec = status(A, fsA))
469 return ec;
470 if (std::error_code ec = status(B, fsB))
471 return ec;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000472 result = equivalent(fsA, fsB);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000473 return std::error_code();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000474}
475
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000476static bool isReservedName(StringRef path) {
477 // This list of reserved names comes from MSDN, at:
478 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
Craig Topper26260942015-10-18 05:15:34 +0000479 static const char *const sReservedNames[] = { "nul", "con", "prn", "aux",
480 "com1", "com2", "com3", "com4",
481 "com5", "com6", "com7", "com8",
482 "com9", "lpt1", "lpt2", "lpt3",
483 "lpt4", "lpt5", "lpt6", "lpt7",
484 "lpt8", "lpt9" };
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000485
486 // First, check to see if this is a device namespace, which always
487 // starts with \\.\, since device namespaces are not legal file paths.
488 if (path.startswith("\\\\.\\"))
489 return true;
490
Douglas Yung091d8fd2016-05-03 00:12:59 +0000491 // Then compare against the list of ancient reserved names.
Craig Topper58713212013-07-15 04:27:47 +0000492 for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000493 if (path.equals_lower(sReservedNames[i]))
494 return true;
495 }
496
497 // The path isn't what we consider reserved.
498 return false;
499}
500
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000501static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000502 if (FileHandle == INVALID_HANDLE_VALUE)
503 goto handle_status_error;
504
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000505 switch (::GetFileType(FileHandle)) {
506 default:
Rafael Espindola81177c52013-07-18 18:42:52 +0000507 llvm_unreachable("Don't know anything about this file type");
508 case FILE_TYPE_UNKNOWN: {
509 DWORD Err = ::GetLastError();
510 if (Err != NO_ERROR)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000511 return mapWindowsError(Err);
Rafael Espindola81177c52013-07-18 18:42:52 +0000512 Result = file_status(file_type::type_unknown);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000513 return std::error_code();
Rafael Espindola81177c52013-07-18 18:42:52 +0000514 }
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000515 case FILE_TYPE_DISK:
516 break;
517 case FILE_TYPE_CHAR:
518 Result = file_status(file_type::character_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000519 return std::error_code();
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000520 case FILE_TYPE_PIPE:
521 Result = file_status(file_type::fifo_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000522 return std::error_code();
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000523 }
524
Rafael Espindola77021c92013-07-16 03:20:13 +0000525 BY_HANDLE_FILE_INFORMATION Info;
526 if (!::GetFileInformationByHandle(FileHandle, &Info))
527 goto handle_status_error;
528
Rafael Espindolaa5932af2013-07-30 20:25:53 +0000529 {
Aaron Ballman345012d2017-03-13 12:24:51 +0000530 file_type Type = (Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
531 ? file_type::directory_file
532 : file_type::regular_file;
533 Result =
534 file_status(Type, Info.ftLastAccessTime.dwHighDateTime,
535 Info.ftLastAccessTime.dwLowDateTime,
536 Info.ftLastWriteTime.dwHighDateTime,
537 Info.ftLastWriteTime.dwLowDateTime,
538 Info.dwVolumeSerialNumber, Info.nFileSizeHigh,
539 Info.nFileSizeLow, Info.nFileIndexHigh, Info.nFileIndexLow);
540 return std::error_code();
541 }
542
Rafael Espindola77021c92013-07-16 03:20:13 +0000543handle_status_error:
Rafael Espindolaa813d602014-06-11 03:58:34 +0000544 DWORD LastError = ::GetLastError();
545 if (LastError == ERROR_FILE_NOT_FOUND ||
546 LastError == ERROR_PATH_NOT_FOUND)
Rafael Espindola77021c92013-07-16 03:20:13 +0000547 Result = file_status(file_type::file_not_found);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000548 else if (LastError == ERROR_SHARING_VIOLATION)
Rafael Espindola77021c92013-07-16 03:20:13 +0000549 Result = file_status(file_type::type_unknown);
Rafael Espindola107b74c2013-07-31 00:10:25 +0000550 else
Rafael Espindola77021c92013-07-16 03:20:13 +0000551 Result = file_status(file_type::status_error);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000552 return mapWindowsError(LastError);
Rafael Espindola77021c92013-07-16 03:20:13 +0000553}
554
Zachary Turner82dd5422017-03-07 16:10:10 +0000555std::error_code status(const Twine &path, file_status &result, bool Follow) {
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000556 SmallString<128> path_storage;
557 SmallVector<wchar_t, 128> path_utf16;
558
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000559 StringRef path8 = path.toStringRef(path_storage);
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000560 if (isReservedName(path8)) {
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000561 result = file_status(file_type::character_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000562 return std::error_code();
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000563 }
564
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000565 if (std::error_code ec = widenPath(path8, path_utf16))
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000566 return ec;
567
568 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
569 if (attr == INVALID_FILE_ATTRIBUTES)
Rafael Espindola77021c92013-07-16 03:20:13 +0000570 return getStatus(INVALID_HANDLE_VALUE, result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000571
Zachary Turner82dd5422017-03-07 16:10:10 +0000572 DWORD Flags = FILE_FLAG_BACKUP_SEMANTICS;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000573 // Handle reparse points.
Zachary Turner82dd5422017-03-07 16:10:10 +0000574 if (!Follow && (attr & FILE_ATTRIBUTE_REPARSE_POINT))
575 Flags |= FILE_FLAG_OPEN_REPARSE_POINT;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000576
Rafael Espindolaa5932af2013-07-30 20:25:53 +0000577 ScopedFileHandle h(
578 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
Michael J. Spencer203d7802011-12-12 06:04:28 +0000579 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
Zachary Turner82dd5422017-03-07 16:10:10 +0000580 NULL, OPEN_EXISTING, Flags, 0));
581 if (!h)
582 return getStatus(INVALID_HANDLE_VALUE, result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000583
Zachary Turner82dd5422017-03-07 16:10:10 +0000584 return getStatus(h, result);
Rafael Espindola77021c92013-07-16 03:20:13 +0000585}
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000586
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000587std::error_code status(int FD, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000588 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
Aaron Ballman345012d2017-03-13 12:24:51 +0000589 return getStatus(FileHandle, Result);
590}
591
592std::error_code setLastModificationAndAccessTime(int FD, TimePoint<> Time) {
593 FILETIME FT = toFILETIME(Time);
594 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000595 if (!SetFileTime(FileHandle, NULL, &FT, &FT))
Yaron Kerenf8e65172015-05-04 04:48:10 +0000596 return mapWindowsError(::GetLastError());
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000597 return std::error_code();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000598}
Nick Kledzik18497e92012-06-20 00:28:54 +0000599
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000600std::error_code mapped_file_region::init(int FD, uint64_t Offset,
601 mapmode Mode) {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000602 // Make sure that the requested size fits within SIZE_T.
Rafael Espindola986f5ad2014-12-16 02:19:26 +0000603 if (Size > std::numeric_limits<SIZE_T>::max())
Rafael Espindola2a826e42014-06-13 17:20:48 +0000604 return make_error_code(errc::invalid_argument);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000605
Rafael Espindolaa23008a2014-12-16 03:10:29 +0000606 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
607 if (FileHandle == INVALID_HANDLE_VALUE)
608 return make_error_code(errc::bad_file_descriptor);
609
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000610 DWORD flprotect;
611 switch (Mode) {
612 case readonly: flprotect = PAGE_READONLY; break;
613 case readwrite: flprotect = PAGE_READWRITE; break;
614 case priv: flprotect = PAGE_WRITECOPY; break;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000615 }
616
Rafael Espindola369d5142014-12-16 02:53:35 +0000617 HANDLE FileMappingHandle =
David Majnemer17a44962013-10-07 09:52:36 +0000618 ::CreateFileMappingW(FileHandle, 0, flprotect,
619 (Offset + Size) >> 32,
620 (Offset + Size) & 0xffffffff,
621 0);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000622 if (FileMappingHandle == NULL) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000623 std::error_code ec = mapWindowsError(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000624 return ec;
625 }
626
627 DWORD dwDesiredAccess;
628 switch (Mode) {
629 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
630 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
631 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000632 }
633 Mapping = ::MapViewOfFile(FileMappingHandle,
634 dwDesiredAccess,
635 Offset >> 32,
636 Offset & 0xffffffff,
637 Size);
638 if (Mapping == NULL) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000639 std::error_code ec = mapWindowsError(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000640 ::CloseHandle(FileMappingHandle);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000641 return ec;
642 }
643
644 if (Size == 0) {
645 MEMORY_BASIC_INFORMATION mbi;
646 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
647 if (Result == 0) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000648 std::error_code ec = mapWindowsError(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000649 ::UnmapViewOfFile(Mapping);
650 ::CloseHandle(FileMappingHandle);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000651 return ec;
652 }
653 Size = mbi.RegionSize;
654 }
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000655
656 // Close all the handles except for the view. It will keep the other handles
657 // alive.
658 ::CloseHandle(FileMappingHandle);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000659 return std::error_code();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000660}
661
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000662mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
663 uint64_t offset, std::error_code &ec)
Rafael Espindolaa23008a2014-12-16 03:10:29 +0000664 : Size(length), Mapping() {
Rafael Espindola986f5ad2014-12-16 02:19:26 +0000665 ec = init(fd, offset, mode);
Rafael Espindolaa23008a2014-12-16 03:10:29 +0000666 if (ec)
Rafael Espindola369d5142014-12-16 02:53:35 +0000667 Mapping = 0;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000668}
669
670mapped_file_region::~mapped_file_region() {
671 if (Mapping)
672 ::UnmapViewOfFile(Mapping);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000673}
674
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000675uint64_t mapped_file_region::size() const {
676 assert(Mapping && "Mapping failed but used anyway!");
677 return Size;
678}
679
680char *mapped_file_region::data() const {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000681 assert(Mapping && "Mapping failed but used anyway!");
682 return reinterpret_cast<char*>(Mapping);
683}
684
685const char *mapped_file_region::const_data() const {
686 assert(Mapping && "Mapping failed but used anyway!");
687 return reinterpret_cast<const char*>(Mapping);
688}
689
690int mapped_file_region::alignment() {
691 SYSTEM_INFO SysInfo;
692 ::GetSystemInfo(&SysInfo);
693 return SysInfo.dwAllocationGranularity;
694}
695
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000696std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
Zachary Turner260bda32017-03-08 22:49:32 +0000697 StringRef path,
698 bool follow_symlinks) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000699 SmallVector<wchar_t, 128> path_utf16;
700
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000701 if (std::error_code ec = widenPath(path, path_utf16))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000702 return ec;
703
704 // Convert path to the format that Windows is happy with.
705 if (path_utf16.size() > 0 &&
706 !is_separator(path_utf16[path.size() - 1]) &&
707 path_utf16[path.size() - 1] != L':') {
708 path_utf16.push_back(L'\\');
709 path_utf16.push_back(L'*');
710 } else {
711 path_utf16.push_back(L'*');
712 }
713
714 // Get the first directory entry.
715 WIN32_FIND_DATAW FirstFind;
Michael J. Spencer751e9aa2010-12-09 17:37:18 +0000716 ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000717 if (!FindHandle)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000718 return mapWindowsError(::GetLastError());
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000719
Michael J. Spencer98879d72011-01-05 16:39:30 +0000720 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
721 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
722 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
723 FirstFind.cFileName[1] == L'.'))
724 if (!::FindNextFileW(FindHandle, &FirstFind)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000725 DWORD LastError = ::GetLastError();
Michael J. Spencer98879d72011-01-05 16:39:30 +0000726 // Check for end.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000727 if (LastError == ERROR_NO_MORE_FILES)
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000728 return detail::directory_iterator_destruct(it);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000729 return mapWindowsError(LastError);
Michael J. Spencer98879d72011-01-05 16:39:30 +0000730 } else
731 FilenameLen = ::wcslen(FirstFind.cFileName);
732
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000733 // Construct the current directory entry.
Michael J. Spencer98879d72011-01-05 16:39:30 +0000734 SmallString<128> directory_entry_name_utf8;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000735 if (std::error_code ec =
736 UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
737 directory_entry_name_utf8))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000738 return ec;
739
740 it.IterationHandle = intptr_t(FindHandle.take());
Michael J. Spencer98879d72011-01-05 16:39:30 +0000741 SmallString<128> directory_entry_path(path);
Yaron Keren92e1b622015-03-18 10:17:07 +0000742 path::append(directory_entry_path, directory_entry_name_utf8);
Zachary Turner260bda32017-03-08 22:49:32 +0000743 it.CurrentEntry = directory_entry(directory_entry_path, follow_symlinks);
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000744
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000745 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000746}
747
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000748std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000749 if (it.IterationHandle != 0)
750 // Closes the handle if it's valid.
751 ScopedFindHandle close(HANDLE(it.IterationHandle));
752 it.IterationHandle = 0;
753 it.CurrentEntry = directory_entry();
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000754 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000755}
756
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000757std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000758 WIN32_FIND_DATAW FindData;
759 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000760 DWORD LastError = ::GetLastError();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000761 // Check for end.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000762 if (LastError == ERROR_NO_MORE_FILES)
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000763 return detail::directory_iterator_destruct(it);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000764 return mapWindowsError(LastError);
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000765 }
766
Michael J. Spencer98879d72011-01-05 16:39:30 +0000767 size_t FilenameLen = ::wcslen(FindData.cFileName);
768 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
769 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
770 FindData.cFileName[1] == L'.'))
771 return directory_iterator_increment(it);
772
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000773 SmallString<128> directory_entry_path_utf8;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000774 if (std::error_code ec =
775 UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
776 directory_entry_path_utf8))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000777 return ec;
778
779 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000780 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000781}
782
Zachary Turnere48ace62017-03-10 17:39:21 +0000783static std::error_code realPathFromHandle(HANDLE H,
784 SmallVectorImpl<char> &RealPath) {
785 RealPath.clear();
786 llvm::SmallVector<wchar_t, MAX_PATH> Buffer;
787 DWORD CountChars = ::GetFinalPathNameByHandleW(
788 H, Buffer.begin(), Buffer.capacity() - 1, FILE_NAME_NORMALIZED);
789 if (CountChars > Buffer.capacity()) {
790 // The buffer wasn't big enough, try again. In this case the return value
791 // *does* indicate the size of the null terminator.
792 Buffer.reserve(CountChars);
793 CountChars = ::GetFinalPathNameByHandleW(
794 H, Buffer.data(), Buffer.capacity() - 1, FILE_NAME_NORMALIZED);
795 }
796 if (CountChars == 0)
797 return mapWindowsError(GetLastError());
798
799 const wchar_t *Data = Buffer.data();
800 if (CountChars >= 4) {
801 if (0 == ::memcmp(Data, L"\\\\?\\", 8)) {
802 CountChars -= 4;
803 Data += 4;
804 }
805 }
806
807 // Convert the result from UTF-16 to UTF-8.
808 return UTF16ToUTF8(Data, CountChars, RealPath);
809}
810
811static std::error_code directoryRealPath(const Twine &Name,
812 SmallVectorImpl<char> &RealPath) {
813 SmallVector<wchar_t, 128> PathUTF16;
814
815 if (std::error_code EC = widenPath(Name, PathUTF16))
816 return EC;
817
818 HANDLE H =
819 ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
820 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
821 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
822 if (H == INVALID_HANDLE_VALUE)
823 return mapWindowsError(GetLastError());
824 std::error_code EC = realPathFromHandle(H, RealPath);
825 ::CloseHandle(H);
826 return EC;
827}
828
Taewook Ohd9153272016-06-13 15:54:56 +0000829std::error_code openFileForRead(const Twine &Name, int &ResultFD,
830 SmallVectorImpl<char> *RealPath) {
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000831 SmallVector<wchar_t, 128> PathUTF16;
Nick Kledzik18497e92012-06-20 00:28:54 +0000832
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000833 if (std::error_code EC = widenPath(Name, PathUTF16))
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000834 return EC;
835
Greg Bedwell7f68a712015-10-12 15:11:47 +0000836 HANDLE H =
837 ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
838 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
839 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000840 if (H == INVALID_HANDLE_VALUE) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000841 DWORD LastError = ::GetLastError();
Yaron Kerenf8e65172015-05-04 04:48:10 +0000842 std::error_code EC = mapWindowsError(LastError);
Rafael Espindola331aeba2013-07-17 19:58:28 +0000843 // Provide a better error message when trying to open directories.
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000844 // This only runs if we failed to open the file, so there is probably
845 // no performances issues.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000846 if (LastError != ERROR_ACCESS_DENIED)
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000847 return EC;
848 if (is_directory(Name))
Rafael Espindola2a826e42014-06-13 17:20:48 +0000849 return make_error_code(errc::is_a_directory);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000850 return EC;
851 }
852
853 int FD = ::_open_osfhandle(intptr_t(H), 0);
854 if (FD == -1) {
855 ::CloseHandle(H);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000856 return mapWindowsError(ERROR_INVALID_HANDLE);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000857 }
858
Taewook Ohd9153272016-06-13 15:54:56 +0000859 // Fetch the real name of the file, if the user asked
Zachary Turnere48ace62017-03-10 17:39:21 +0000860 if (RealPath)
Zachary Turner3c0dc332017-03-10 18:33:41 +0000861 realPathFromHandle(H, *RealPath);
Taewook Ohd9153272016-06-13 15:54:56 +0000862
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000863 ResultFD = FD;
Zachary Turner3c0dc332017-03-10 18:33:41 +0000864 return std::error_code();
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000865}
Nick Kledzik18497e92012-06-20 00:28:54 +0000866
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000867std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
Rafael Espindola67080ce2013-07-19 15:02:03 +0000868 sys::fs::OpenFlags Flags, unsigned Mode) {
869 // Verify that we don't have both "append" and "excl".
870 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
871 "Cannot specify both 'excl' and 'append' file creation flags!");
872
Rafael Espindola67080ce2013-07-19 15:02:03 +0000873 SmallVector<wchar_t, 128> PathUTF16;
874
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000875 if (std::error_code EC = widenPath(Name, PathUTF16))
Rafael Espindola67080ce2013-07-19 15:02:03 +0000876 return EC;
877
878 DWORD CreationDisposition;
879 if (Flags & F_Excl)
880 CreationDisposition = CREATE_NEW;
NAKAMURA Takumiedf76152013-08-22 15:14:45 +0000881 else if (Flags & F_Append)
Rafael Espindola67080ce2013-07-19 15:02:03 +0000882 CreationDisposition = OPEN_ALWAYS;
883 else
884 CreationDisposition = CREATE_ALWAYS;
885
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000886 DWORD Access = GENERIC_WRITE;
887 if (Flags & F_RW)
888 Access |= GENERIC_READ;
889
890 HANDLE H = ::CreateFileW(PathUTF16.begin(), Access,
Rafael Espindola67080ce2013-07-19 15:02:03 +0000891 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
892 CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
893
894 if (H == INVALID_HANDLE_VALUE) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000895 DWORD LastError = ::GetLastError();
Yaron Kerenf8e65172015-05-04 04:48:10 +0000896 std::error_code EC = mapWindowsError(LastError);
Rafael Espindola67080ce2013-07-19 15:02:03 +0000897 // Provide a better error message when trying to open directories.
898 // This only runs if we failed to open the file, so there is probably
899 // no performances issues.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000900 if (LastError != ERROR_ACCESS_DENIED)
Rafael Espindola67080ce2013-07-19 15:02:03 +0000901 return EC;
902 if (is_directory(Name))
Rafael Espindola2a826e42014-06-13 17:20:48 +0000903 return make_error_code(errc::is_a_directory);
Rafael Espindola67080ce2013-07-19 15:02:03 +0000904 return EC;
905 }
906
907 int OpenFlags = 0;
908 if (Flags & F_Append)
909 OpenFlags |= _O_APPEND;
910
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000911 if (Flags & F_Text)
Rafael Espindola67080ce2013-07-19 15:02:03 +0000912 OpenFlags |= _O_TEXT;
913
914 int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
915 if (FD == -1) {
916 ::CloseHandle(H);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000917 return mapWindowsError(ERROR_INVALID_HANDLE);
Rafael Espindola67080ce2013-07-19 15:02:03 +0000918 }
919
920 ResultFD = FD;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000921 return std::error_code();
Rafael Espindola67080ce2013-07-19 15:02:03 +0000922}
Taewook Ohd9153272016-06-13 15:54:56 +0000923
924std::error_code getPathFromOpenFD(int FD, SmallVectorImpl<char> &ResultPath) {
925 HANDLE FileHandle = reinterpret_cast<HANDLE>(::_get_osfhandle(FD));
926 if (FileHandle == INVALID_HANDLE_VALUE)
927 return make_error_code(errc::bad_file_descriptor);
928
929 DWORD CharCount;
Aaron Ballman0ad00462016-06-21 14:24:48 +0000930 SmallVector<wchar_t, 1024> TempPath;
Taewook Ohd9153272016-06-13 15:54:56 +0000931 do {
Aaron Ballman0ad00462016-06-21 14:24:48 +0000932 CharCount = ::GetFinalPathNameByHandleW(FileHandle, TempPath.begin(),
933 TempPath.capacity(),
Aaron Ballman3dd74b82016-06-20 20:28:49 +0000934 FILE_NAME_NORMALIZED);
Aaron Ballman0ad00462016-06-21 14:24:48 +0000935 if (CharCount < TempPath.capacity())
Taewook Ohd9153272016-06-13 15:54:56 +0000936 break;
Aaron Ballman3dd74b82016-06-20 20:28:49 +0000937
938 // Reserve sufficient space for the path as well as the null character. Even
939 // though the API does not document that it is required, if we reserve just
940 // CharCount space, the function call will not store the resulting path and
941 // still report success.
Aaron Ballman0ad00462016-06-21 14:24:48 +0000942 TempPath.reserve(CharCount + 1);
Taewook Ohd9153272016-06-13 15:54:56 +0000943 } while (true);
944
945 if (CharCount == 0)
946 return mapWindowsError(::GetLastError());
947
Aaron Ballman0ad00462016-06-21 14:24:48 +0000948 TempPath.set_size(CharCount);
Taewook Ohd9153272016-06-13 15:54:56 +0000949
Aaron Ballman3dd74b82016-06-20 20:28:49 +0000950 // On earlier Windows releases, the character count includes the terminating
951 // null.
Aaron Ballman0ad00462016-06-21 14:24:48 +0000952 if (TempPath.back() == L'\0') {
953 --CharCount;
954 TempPath.pop_back();
955 }
Taewook Ohd9153272016-06-13 15:54:56 +0000956
Aaron Ballman0ad00462016-06-21 14:24:48 +0000957 return windows::UTF16ToUTF8(TempPath.data(), CharCount, ResultPath);
Taewook Ohd9153272016-06-13 15:54:56 +0000958}
Zachary Turner260bda32017-03-08 22:49:32 +0000959
960std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
961 // Convert to utf-16.
962 SmallVector<wchar_t, 128> Path16;
963 std::error_code EC = widenPath(path, Path16);
964 if (EC && !IgnoreErrors)
965 return EC;
966
967 // SHFileOperation() accepts a list of paths, and so must be double null-
968 // terminated to indicate the end of the list. The buffer is already null
969 // terminated, but since that null character is not considered part of the
970 // vector's size, pushing another one will just consume that byte. So we
971 // need to push 2 null terminators.
972 Path16.push_back(0);
973 Path16.push_back(0);
974
975 SHFILEOPSTRUCTW shfos = {};
976 shfos.wFunc = FO_DELETE;
977 shfos.pFrom = Path16.data();
978 shfos.fFlags = FOF_NO_UI;
979
980 int result = ::SHFileOperationW(&shfos);
981 if (result != 0 && !IgnoreErrors)
982 return mapWindowsError(result);
983 return std::error_code();
984}
985
Zachary Turnere48ace62017-03-10 17:39:21 +0000986static void expandTildeExpr(SmallVectorImpl<char> &Path) {
987 // Path does not begin with a tilde expression.
988 if (Path.empty() || Path[0] != '~')
989 return;
990
991 StringRef PathStr(Path.begin(), Path.size());
992 PathStr = PathStr.drop_front();
993 StringRef Expr = PathStr.take_until(path::is_separator);
994
995 if (!Expr.empty()) {
996 // This is probably a ~username/ expression. Don't support this on Windows.
997 return;
998 }
999
1000 SmallString<128> HomeDir;
1001 if (!path::home_directory(HomeDir)) {
1002 // For some reason we couldn't get the home directory. Just exit.
1003 return;
1004 }
1005
1006 // Overwrite the first character and insert the rest.
1007 Path[0] = HomeDir[0];
1008 Path.insert(Path.begin() + 1, HomeDir.begin() + 1, HomeDir.end());
1009}
1010
1011std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1012 bool expand_tilde) {
1013 dest.clear();
1014 if (path.isTriviallyEmpty())
1015 return std::error_code();
1016
1017 if (expand_tilde) {
1018 SmallString<128> Storage;
1019 path.toVector(Storage);
1020 expandTildeExpr(Storage);
1021 return real_path(Storage, dest, false);
1022 }
1023
1024 if (is_directory(path))
1025 return directoryRealPath(path, dest);
1026
1027 int fd;
1028 if (std::error_code EC = llvm::sys::fs::openFileForRead(path, fd, &dest))
1029 return EC;
1030 ::close(fd);
1031 return std::error_code();
1032}
1033
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +00001034} // end namespace fs
Rui Ueyama471d0c52013-09-10 19:45:51 +00001035
Peter Collingbournef7d41012014-01-31 23:46:06 +00001036namespace path {
Pawel Bylica7c1f36a2015-11-02 14:57:24 +00001037static bool getKnownFolderPath(KNOWNFOLDERID folderId,
1038 SmallVectorImpl<char> &result) {
Pawel Bylica7187e4b2015-10-16 09:08:59 +00001039 wchar_t *path = nullptr;
1040 if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK)
1041 return false;
1042
1043 bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
1044 ::CoTaskMemFree(path);
1045 return ok;
1046}
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001047
1048bool getUserCacheDir(SmallVectorImpl<char> &Result) {
1049 return getKnownFolderPath(FOLDERID_LocalAppData, Result);
1050}
Pawel Bylica7187e4b2015-10-16 09:08:59 +00001051
Peter Collingbournef7d41012014-01-31 23:46:06 +00001052bool home_directory(SmallVectorImpl<char> &result) {
Pawel Bylica7187e4b2015-10-16 09:08:59 +00001053 return getKnownFolderPath(FOLDERID_Profile, result);
Peter Collingbournef7d41012014-01-31 23:46:06 +00001054}
1055
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001056static bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {
Pawel Bylica6e680b22015-11-06 23:44:23 +00001057 SmallVector<wchar_t, 1024> Buf;
1058 size_t Size = 1024;
1059 do {
1060 Buf.reserve(Size);
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001061 Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.capacity());
Pawel Bylica6e680b22015-11-06 23:44:23 +00001062 if (Size == 0)
1063 return false;
1064
1065 // Try again with larger buffer.
1066 } while (Size > Buf.capacity());
1067 Buf.set_size(Size);
1068
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001069 return !windows::UTF16ToUTF8(Buf.data(), Size, Res);
Pawel Bylica6e680b22015-11-06 23:44:23 +00001070}
1071
1072static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001073 const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};
1074 for (auto *Env : EnvironmentVariables) {
Pawel Bylica6e680b22015-11-06 23:44:23 +00001075 if (getTempDirEnvVar(Env, Res))
1076 return true;
1077 }
1078 return false;
1079}
1080
Rafael Espindola016a6d52014-08-26 14:47:52 +00001081void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1082 (void)ErasedOnReboot;
Pawel Bylica6e680b22015-11-06 23:44:23 +00001083 Result.clear();
Rafael Espindola016a6d52014-08-26 14:47:52 +00001084
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001085 // Check whether the temporary directory is specified by an environment var.
1086 // This matches GetTempPath logic to some degree. GetTempPath is not used
1087 // directly as it cannot handle evn var longer than 130 chars on Windows 7
1088 // (fixed on Windows 8).
1089 if (getTempDirEnvVar(Result)) {
1090 assert(!Result.empty() && "Unexpected empty path");
1091 native(Result); // Some Unix-like shells use Unix path separator in $TMP.
1092 fs::make_absolute(Result); // Make it absolute if not already.
Pawel Bylica6e680b22015-11-06 23:44:23 +00001093 return;
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001094 }
Rafael Espindola016a6d52014-08-26 14:47:52 +00001095
1096 // Fall back to a system default.
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001097 const char *DefaultResult = "C:\\Temp";
Rafael Espindola016a6d52014-08-26 14:47:52 +00001098 Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
1099}
Peter Collingbournef7d41012014-01-31 23:46:06 +00001100} // end namespace path
1101
Rui Ueyama471d0c52013-09-10 19:45:51 +00001102namespace windows {
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +00001103std::error_code UTF8ToUTF16(llvm::StringRef utf8,
Rafael Espindolab4ad29b2014-06-13 02:36:09 +00001104 llvm::SmallVectorImpl<wchar_t> &utf16) {
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001105 if (!utf8.empty()) {
1106 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
1107 utf8.size(), utf16.begin(), 0);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001108
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001109 if (len == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +00001110 return mapWindowsError(::GetLastError());
Rui Ueyama471d0c52013-09-10 19:45:51 +00001111
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001112 utf16.reserve(len + 1);
1113 utf16.set_size(len);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001114
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001115 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
1116 utf8.size(), utf16.begin(), utf16.size());
Rui Ueyama471d0c52013-09-10 19:45:51 +00001117
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001118 if (len == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +00001119 return mapWindowsError(::GetLastError());
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001120 }
Rui Ueyama471d0c52013-09-10 19:45:51 +00001121
1122 // Make utf16 null terminated.
1123 utf16.push_back(0);
1124 utf16.pop_back();
1125
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +00001126 return std::error_code();
Rui Ueyama471d0c52013-09-10 19:45:51 +00001127}
1128
Rafael Espindola9c359662014-09-03 20:02:00 +00001129static
1130std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
1131 size_t utf16_len,
1132 llvm::SmallVectorImpl<char> &utf8) {
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001133 if (utf16_len) {
1134 // Get length.
Rafael Espindola9c359662014-09-03 20:02:00 +00001135 int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.begin(),
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001136 0, NULL, NULL);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001137
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001138 if (len == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +00001139 return mapWindowsError(::GetLastError());
Rui Ueyama471d0c52013-09-10 19:45:51 +00001140
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001141 utf8.reserve(len);
1142 utf8.set_size(len);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001143
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001144 // Now do the actual conversion.
Rafael Espindola9c359662014-09-03 20:02:00 +00001145 len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.data(),
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001146 utf8.size(), NULL, NULL);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001147
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001148 if (len == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +00001149 return mapWindowsError(::GetLastError());
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001150 }
Rui Ueyama471d0c52013-09-10 19:45:51 +00001151
1152 // Make utf8 null terminated.
1153 utf8.push_back(0);
1154 utf8.pop_back();
1155
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +00001156 return std::error_code();
Rui Ueyama471d0c52013-09-10 19:45:51 +00001157}
Rafael Espindola9c359662014-09-03 20:02:00 +00001158
1159std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
1160 llvm::SmallVectorImpl<char> &utf8) {
1161 return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
1162}
1163
1164std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
1165 llvm::SmallVectorImpl<char> &utf8) {
1166 return UTF16ToCodePage(CP_ACP, utf16, utf16_len, utf8);
1167}
Taewook Ohd9153272016-06-13 15:54:56 +00001168
Rui Ueyama471d0c52013-09-10 19:45:51 +00001169} // end namespace windows
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001170} // end namespace sys
1171} // end namespace llvm