blob: 8dac0e4482bd6050e34b1b608537ff1a17eb9593 [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
Zachary Turner5821a3b2017-03-20 23:55:20 +0000182uint32_t file_status::getLinkCount() const {
183 return NumLinks;
184}
185
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000186std::error_code current_path(SmallVectorImpl<char> &result) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000187 SmallVector<wchar_t, MAX_PATH> cur_path;
188 DWORD len = MAX_PATH;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000189
David Majnemer61eae2e2013-10-07 01:00:07 +0000190 do {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000191 cur_path.reserve(len);
David Majnemer61eae2e2013-10-07 01:00:07 +0000192 len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000193
David Majnemer61eae2e2013-10-07 01:00:07 +0000194 // A zero return value indicates a failure other than insufficient space.
195 if (len == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000196 return mapWindowsError(::GetLastError());
David Majnemer61eae2e2013-10-07 01:00:07 +0000197
198 // If there's insufficient space, the len returned is larger than the len
199 // given.
200 } while (len > cur_path.capacity());
201
202 // On success, GetCurrentDirectoryW returns the number of characters not
203 // including the null-terminator.
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000204 cur_path.set_size(len);
Aaron Ballmanb16cf532013-08-16 17:53:28 +0000205 return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000206}
207
Pavel Labath2f096092017-01-24 10:32:03 +0000208std::error_code set_current_path(const Twine &path) {
209 // Convert to utf-16.
210 SmallVector<wchar_t, 128> wide_path;
211 if (std::error_code ec = widenPath(path, wide_path))
212 return ec;
213
214 if (!::SetCurrentDirectoryW(wide_path.begin()))
215 return mapWindowsError(::GetLastError());
216
217 return std::error_code();
218}
219
Frederic Riss6b9396c2015-08-06 21:04:55 +0000220std::error_code create_directory(const Twine &path, bool IgnoreExisting,
221 perms Perms) {
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000222 SmallVector<wchar_t, 128> path_utf16;
223
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000224 if (std::error_code ec = widenPath(path, path_utf16))
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000225 return ec;
226
227 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000228 DWORD LastError = ::GetLastError();
229 if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000230 return mapWindowsError(LastError);
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000231 }
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000232
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000233 return std::error_code();
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000234}
235
Rafael Espindola83f858e2014-03-11 18:40:24 +0000236// We can't use symbolic links for windows.
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000237std::error_code create_link(const Twine &to, const Twine &from) {
Michael J. Spencere0c45602010-12-03 05:58:41 +0000238 // Convert to utf-16.
239 SmallVector<wchar_t, 128> wide_from;
240 SmallVector<wchar_t, 128> wide_to;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000241 if (std::error_code ec = widenPath(from, wide_from))
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000242 return ec;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000243 if (std::error_code ec = widenPath(to, wide_to))
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000244 return ec;
Michael J. Spencere0c45602010-12-03 05:58:41 +0000245
246 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
Yaron Kerenf8e65172015-05-04 04:48:10 +0000247 return mapWindowsError(::GetLastError());
Michael J. Spencere0c45602010-12-03 05:58:41 +0000248
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000249 return std::error_code();
Michael J. Spencere0c45602010-12-03 05:58:41 +0000250}
251
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000252std::error_code create_hard_link(const Twine &to, const Twine &from) {
253 return create_link(to, from);
254}
255
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000256std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000257 SmallVector<wchar_t, 128> path_utf16;
258
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000259 file_status ST;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000260 if (std::error_code EC = status(path, ST)) {
Rafael Espindola2a826e42014-06-13 17:20:48 +0000261 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000262 return EC;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000263 return std::error_code();
Rafael Espindola107b74c2013-07-31 00:10:25 +0000264 }
Michael J. Spencer153749b2011-01-05 16:39:22 +0000265
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000266 if (std::error_code ec = widenPath(path, path_utf16))
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000267 return ec;
268
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000269 if (ST.type() == file_type::directory_file) {
Michael J. Spencer153749b2011-01-05 16:39:22 +0000270 if (!::RemoveDirectoryW(c_str(path_utf16))) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000271 std::error_code EC = mapWindowsError(::GetLastError());
Rafael Espindola2a826e42014-06-13 17:20:48 +0000272 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000273 return EC;
274 }
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000275 return std::error_code();
Michael J. Spencer153749b2011-01-05 16:39:22 +0000276 }
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000277 if (!::DeleteFileW(c_str(path_utf16))) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000278 std::error_code EC = mapWindowsError(::GetLastError());
Rafael Espindola2a826e42014-06-13 17:20:48 +0000279 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000280 return EC;
281 }
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000282 return std::error_code();
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000283}
284
Zachary Turner392ed9d2017-02-21 20:55:47 +0000285static std::error_code is_local_internal(SmallVectorImpl<wchar_t> &Path,
286 bool &Result) {
287 SmallVector<wchar_t, 128> VolumePath;
288 size_t Len = 128;
289 while (true) {
290 VolumePath.resize(Len);
291 BOOL Success =
292 ::GetVolumePathNameW(Path.data(), VolumePath.data(), VolumePath.size());
293
294 if (Success)
295 break;
296
297 DWORD Err = ::GetLastError();
298 if (Err != ERROR_INSUFFICIENT_BUFFER)
299 return mapWindowsError(Err);
300
301 Len *= 2;
302 }
303 // If the output buffer has exactly enough space for the path name, but not
304 // the null terminator, it will leave the output unterminated. Push a null
305 // terminator onto the end to ensure that this never happens.
306 VolumePath.push_back(L'\0');
307 VolumePath.set_size(wcslen(VolumePath.data()));
308 const wchar_t *P = VolumePath.data();
309
310 UINT Type = ::GetDriveTypeW(P);
311 switch (Type) {
312 case DRIVE_FIXED:
313 Result = true;
314 return std::error_code();
315 case DRIVE_REMOTE:
316 case DRIVE_CDROM:
317 case DRIVE_RAMDISK:
318 case DRIVE_REMOVABLE:
319 Result = false;
320 return std::error_code();
321 default:
322 return make_error_code(errc::no_such_file_or_directory);
323 }
324 llvm_unreachable("Unreachable!");
325}
326
327std::error_code is_local(const Twine &path, bool &result) {
328 if (!llvm::sys::fs::exists(path) || !llvm::sys::path::has_root_path(path))
329 return make_error_code(errc::no_such_file_or_directory);
330
331 SmallString<128> Storage;
332 StringRef P = path.toStringRef(Storage);
333
334 // Convert to utf-16.
335 SmallVector<wchar_t, 128> WidePath;
336 if (std::error_code ec = widenPath(P, WidePath))
337 return ec;
338 return is_local_internal(WidePath, result);
339}
340
341std::error_code is_local(int FD, bool &Result) {
342 SmallVector<wchar_t, 128> FinalPath;
343 HANDLE Handle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
344
345 size_t Len = 128;
346 do {
347 FinalPath.reserve(Len);
348 Len = ::GetFinalPathNameByHandleW(Handle, FinalPath.data(),
349 FinalPath.capacity() - 1, VOLUME_NAME_NT);
350 if (Len == 0)
351 return mapWindowsError(::GetLastError());
352 } while (Len > FinalPath.capacity());
353
354 FinalPath.set_size(Len);
355
356 return is_local_internal(FinalPath, Result);
357}
358
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000359std::error_code rename(const Twine &from, const Twine &to) {
Michael J. Spencer409f5562010-12-03 17:53:55 +0000360 // Convert to utf-16.
361 SmallVector<wchar_t, 128> wide_from;
362 SmallVector<wchar_t, 128> wide_to;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000363 if (std::error_code ec = widenPath(from, wide_from))
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000364 return ec;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000365 if (std::error_code ec = widenPath(to, wide_to))
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000366 return ec;
Michael J. Spencer409f5562010-12-03 17:53:55 +0000367
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000368 std::error_code ec = std::error_code();
Greg Bedwell7f68a712015-10-12 15:11:47 +0000369
Sunil Srivastava34fce932016-03-25 23:41:28 +0000370 // Retry while we see recoverable errors.
Greg Bedwell7f68a712015-10-12 15:11:47 +0000371 // System scanners (eg. indexer) might open the source file when it is written
372 // and closed.
373
Sunil Srivastava34fce932016-03-25 23:41:28 +0000374 bool TryReplace = true;
Greg Bedwell7f68a712015-10-12 15:11:47 +0000375
Sunil Srivastava34fce932016-03-25 23:41:28 +0000376 for (int i = 0; i < 2000; i++) {
377 if (i > 0)
378 ::Sleep(1);
379
380 if (TryReplace) {
381 // Try ReplaceFile first, as it is able to associate a new data stream
382 // with the destination even if the destination file is currently open.
383 if (::ReplaceFileW(wide_to.data(), wide_from.data(), NULL, 0, NULL, NULL))
384 return std::error_code();
385
386 DWORD ReplaceError = ::GetLastError();
387 ec = mapWindowsError(ReplaceError);
388
389 // If ReplaceFileW returned ERROR_UNABLE_TO_MOVE_REPLACEMENT or
390 // ERROR_UNABLE_TO_MOVE_REPLACEMENT_2, retry but only use MoveFileExW().
391 if (ReplaceError == ERROR_UNABLE_TO_MOVE_REPLACEMENT ||
392 ReplaceError == ERROR_UNABLE_TO_MOVE_REPLACEMENT_2) {
393 TryReplace = false;
394 continue;
395 }
396 // If ReplaceFileW returned ERROR_UNABLE_TO_REMOVE_REPLACED, retry
397 // using ReplaceFileW().
398 if (ReplaceError == ERROR_UNABLE_TO_REMOVE_REPLACED)
399 continue;
400 // We get ERROR_FILE_NOT_FOUND if the destination file is missing.
401 // MoveFileEx can handle this case.
402 if (ReplaceError != ERROR_ACCESS_DENIED &&
403 ReplaceError != ERROR_FILE_NOT_FOUND &&
404 ReplaceError != ERROR_SHARING_VIOLATION)
405 break;
406 }
Greg Bedwell7f68a712015-10-12 15:11:47 +0000407
NAKAMURA Takumi3b7f9952012-05-08 14:31:46 +0000408 if (::MoveFileExW(wide_from.begin(), wide_to.begin(),
409 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000410 return std::error_code();
Greg Bedwell7f68a712015-10-12 15:11:47 +0000411
412 DWORD MoveError = ::GetLastError();
413 ec = mapWindowsError(MoveError);
414 if (MoveError != ERROR_ACCESS_DENIED) break;
NAKAMURA Takumi3b7f9952012-05-08 14:31:46 +0000415 }
Michael J. Spencer409f5562010-12-03 17:53:55 +0000416
NAKAMURA Takumi3b7f9952012-05-08 14:31:46 +0000417 return ec;
Michael J. Spencer409f5562010-12-03 17:53:55 +0000418}
419
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000420std::error_code resize_file(int FD, uint64_t Size) {
Michael J. Spencerca242f22010-12-03 18:48:56 +0000421#ifdef HAVE__CHSIZE_S
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000422 errno_t error = ::_chsize_s(FD, Size);
Michael J. Spencerca242f22010-12-03 18:48:56 +0000423#else
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000424 errno_t error = ::_chsize(FD, Size);
Michael J. Spencerca242f22010-12-03 18:48:56 +0000425#endif
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000426 return std::error_code(error, std::generic_category());
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000427}
428
Rafael Espindola281f23a2014-09-11 20:30:02 +0000429std::error_code access(const Twine &Path, AccessMode Mode) {
Rafael Espindola281f23a2014-09-11 20:30:02 +0000430 SmallVector<wchar_t, 128> PathUtf16;
Michael J. Spencer45710402010-12-03 01:21:28 +0000431
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000432 if (std::error_code EC = widenPath(Path, PathUtf16))
Rafael Espindola281f23a2014-09-11 20:30:02 +0000433 return EC;
Michael J. Spencer45710402010-12-03 01:21:28 +0000434
Rafael Espindola281f23a2014-09-11 20:30:02 +0000435 DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
Michael J. Spencer45710402010-12-03 01:21:28 +0000436
Rafael Espindola281f23a2014-09-11 20:30:02 +0000437 if (Attributes == INVALID_FILE_ATTRIBUTES) {
Michael J. Spencer45710402010-12-03 01:21:28 +0000438 // See if the file didn't actually exist.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000439 DWORD LastError = ::GetLastError();
440 if (LastError != ERROR_FILE_NOT_FOUND &&
441 LastError != ERROR_PATH_NOT_FOUND)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000442 return mapWindowsError(LastError);
Rafael Espindola281f23a2014-09-11 20:30:02 +0000443 return errc::no_such_file_or_directory;
444 }
445
446 if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
447 return errc::permission_denied;
448
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000449 return std::error_code();
Michael J. Spencer45710402010-12-03 01:21:28 +0000450}
451
Reid Kleckner89d4b1a2015-09-10 23:28:06 +0000452bool can_execute(const Twine &Path) {
453 return !access(Path, AccessMode::Execute) ||
454 !access(Path + ".exe", AccessMode::Execute);
455}
456
Michael J. Spencer203d7802011-12-12 06:04:28 +0000457bool equivalent(file_status A, file_status B) {
458 assert(status_known(A) && status_known(B));
Mehdi Amini1e39ef32016-03-25 07:30:21 +0000459 return A.FileIndexHigh == B.FileIndexHigh &&
460 A.FileIndexLow == B.FileIndexLow &&
461 A.FileSizeHigh == B.FileSizeHigh &&
462 A.FileSizeLow == B.FileSizeLow &&
463 A.LastAccessedTimeHigh == B.LastAccessedTimeHigh &&
464 A.LastAccessedTimeLow == B.LastAccessedTimeLow &&
465 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
466 A.LastWriteTimeLow == B.LastWriteTimeLow &&
467 A.VolumeSerialNumber == B.VolumeSerialNumber;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000468}
469
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000470std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000471 file_status fsA, fsB;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000472 if (std::error_code ec = status(A, fsA))
473 return ec;
474 if (std::error_code ec = status(B, fsB))
475 return ec;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000476 result = equivalent(fsA, fsB);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000477 return std::error_code();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000478}
479
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000480static bool isReservedName(StringRef path) {
481 // This list of reserved names comes from MSDN, at:
482 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
Craig Topper26260942015-10-18 05:15:34 +0000483 static const char *const sReservedNames[] = { "nul", "con", "prn", "aux",
484 "com1", "com2", "com3", "com4",
485 "com5", "com6", "com7", "com8",
486 "com9", "lpt1", "lpt2", "lpt3",
487 "lpt4", "lpt5", "lpt6", "lpt7",
488 "lpt8", "lpt9" };
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000489
490 // First, check to see if this is a device namespace, which always
491 // starts with \\.\, since device namespaces are not legal file paths.
492 if (path.startswith("\\\\.\\"))
493 return true;
494
Douglas Yung091d8fd2016-05-03 00:12:59 +0000495 // Then compare against the list of ancient reserved names.
Craig Topper58713212013-07-15 04:27:47 +0000496 for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000497 if (path.equals_lower(sReservedNames[i]))
498 return true;
499 }
500
501 // The path isn't what we consider reserved.
502 return false;
503}
504
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000505static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000506 if (FileHandle == INVALID_HANDLE_VALUE)
507 goto handle_status_error;
508
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000509 switch (::GetFileType(FileHandle)) {
510 default:
Rafael Espindola81177c52013-07-18 18:42:52 +0000511 llvm_unreachable("Don't know anything about this file type");
512 case FILE_TYPE_UNKNOWN: {
513 DWORD Err = ::GetLastError();
514 if (Err != NO_ERROR)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000515 return mapWindowsError(Err);
Rafael Espindola81177c52013-07-18 18:42:52 +0000516 Result = file_status(file_type::type_unknown);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000517 return std::error_code();
Rafael Espindola81177c52013-07-18 18:42:52 +0000518 }
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000519 case FILE_TYPE_DISK:
520 break;
521 case FILE_TYPE_CHAR:
522 Result = file_status(file_type::character_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000523 return std::error_code();
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000524 case FILE_TYPE_PIPE:
525 Result = file_status(file_type::fifo_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000526 return std::error_code();
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000527 }
528
Rafael Espindola77021c92013-07-16 03:20:13 +0000529 BY_HANDLE_FILE_INFORMATION Info;
530 if (!::GetFileInformationByHandle(FileHandle, &Info))
531 goto handle_status_error;
532
Rafael Espindolaa5932af2013-07-30 20:25:53 +0000533 {
Aaron Ballman345012d2017-03-13 12:24:51 +0000534 file_type Type = (Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
535 ? file_type::directory_file
536 : file_type::regular_file;
James Henderson566fdf42017-03-16 11:22:09 +0000537 perms Permissions = (Info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
538 ? (all_read | all_exe)
539 : all_all;
540 Result = file_status(
Zachary Turner5821a3b2017-03-20 23:55:20 +0000541 Type, Permissions, Info.nNumberOfLinks,
542 Info.ftLastAccessTime.dwHighDateTime,
James Henderson566fdf42017-03-16 11:22:09 +0000543 Info.ftLastAccessTime.dwLowDateTime,
544 Info.ftLastWriteTime.dwHighDateTime, Info.ftLastWriteTime.dwLowDateTime,
545 Info.dwVolumeSerialNumber, Info.nFileSizeHigh, Info.nFileSizeLow,
546 Info.nFileIndexHigh, Info.nFileIndexLow);
Aaron Ballman345012d2017-03-13 12:24:51 +0000547 return std::error_code();
548 }
549
Rafael Espindola77021c92013-07-16 03:20:13 +0000550handle_status_error:
Rafael Espindolaa813d602014-06-11 03:58:34 +0000551 DWORD LastError = ::GetLastError();
552 if (LastError == ERROR_FILE_NOT_FOUND ||
553 LastError == ERROR_PATH_NOT_FOUND)
Rafael Espindola77021c92013-07-16 03:20:13 +0000554 Result = file_status(file_type::file_not_found);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000555 else if (LastError == ERROR_SHARING_VIOLATION)
Rafael Espindola77021c92013-07-16 03:20:13 +0000556 Result = file_status(file_type::type_unknown);
Rafael Espindola107b74c2013-07-31 00:10:25 +0000557 else
Rafael Espindola77021c92013-07-16 03:20:13 +0000558 Result = file_status(file_type::status_error);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000559 return mapWindowsError(LastError);
Rafael Espindola77021c92013-07-16 03:20:13 +0000560}
561
Zachary Turner82dd5422017-03-07 16:10:10 +0000562std::error_code status(const Twine &path, file_status &result, bool Follow) {
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000563 SmallString<128> path_storage;
564 SmallVector<wchar_t, 128> path_utf16;
565
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000566 StringRef path8 = path.toStringRef(path_storage);
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000567 if (isReservedName(path8)) {
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000568 result = file_status(file_type::character_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000569 return std::error_code();
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000570 }
571
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000572 if (std::error_code ec = widenPath(path8, path_utf16))
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000573 return ec;
574
575 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
576 if (attr == INVALID_FILE_ATTRIBUTES)
Rafael Espindola77021c92013-07-16 03:20:13 +0000577 return getStatus(INVALID_HANDLE_VALUE, result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000578
Zachary Turner82dd5422017-03-07 16:10:10 +0000579 DWORD Flags = FILE_FLAG_BACKUP_SEMANTICS;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000580 // Handle reparse points.
Zachary Turner82dd5422017-03-07 16:10:10 +0000581 if (!Follow && (attr & FILE_ATTRIBUTE_REPARSE_POINT))
582 Flags |= FILE_FLAG_OPEN_REPARSE_POINT;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000583
Rafael Espindolaa5932af2013-07-30 20:25:53 +0000584 ScopedFileHandle h(
585 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
Michael J. Spencer203d7802011-12-12 06:04:28 +0000586 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
Zachary Turner82dd5422017-03-07 16:10:10 +0000587 NULL, OPEN_EXISTING, Flags, 0));
588 if (!h)
589 return getStatus(INVALID_HANDLE_VALUE, result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000590
Zachary Turner82dd5422017-03-07 16:10:10 +0000591 return getStatus(h, result);
Rafael Espindola77021c92013-07-16 03:20:13 +0000592}
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000593
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000594std::error_code status(int FD, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000595 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
Aaron Ballman345012d2017-03-13 12:24:51 +0000596 return getStatus(FileHandle, Result);
597}
598
James Henderson566fdf42017-03-16 11:22:09 +0000599std::error_code setPermissions(const Twine &Path, perms Permissions) {
600 SmallVector<wchar_t, 128> PathUTF16;
601 if (std::error_code EC = widenPath(Path, PathUTF16))
602 return EC;
603
604 DWORD Attributes = ::GetFileAttributesW(PathUTF16.begin());
605 if (Attributes == INVALID_FILE_ATTRIBUTES)
606 return mapWindowsError(GetLastError());
607
608 // There are many Windows file attributes that are not to do with the file
609 // permissions (e.g. FILE_ATTRIBUTE_HIDDEN). We need to be careful to preserve
610 // them.
611 if (Permissions & all_write) {
612 Attributes &= ~FILE_ATTRIBUTE_READONLY;
613 if (Attributes == 0)
614 // FILE_ATTRIBUTE_NORMAL indicates no other attributes are set.
615 Attributes |= FILE_ATTRIBUTE_NORMAL;
616 }
617 else {
618 Attributes |= FILE_ATTRIBUTE_READONLY;
619 // FILE_ATTRIBUTE_NORMAL is not compatible with any other attributes, so
620 // remove it, if it is present.
621 Attributes &= ~FILE_ATTRIBUTE_NORMAL;
622 }
623
624 if (!::SetFileAttributesW(PathUTF16.begin(), Attributes))
625 return mapWindowsError(GetLastError());
626
627 return std::error_code();
628}
629
Aaron Ballman345012d2017-03-13 12:24:51 +0000630std::error_code setLastModificationAndAccessTime(int FD, TimePoint<> Time) {
631 FILETIME FT = toFILETIME(Time);
632 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000633 if (!SetFileTime(FileHandle, NULL, &FT, &FT))
Yaron Kerenf8e65172015-05-04 04:48:10 +0000634 return mapWindowsError(::GetLastError());
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000635 return std::error_code();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000636}
Nick Kledzik18497e92012-06-20 00:28:54 +0000637
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000638std::error_code mapped_file_region::init(int FD, uint64_t Offset,
639 mapmode Mode) {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000640 // Make sure that the requested size fits within SIZE_T.
Rafael Espindola986f5ad2014-12-16 02:19:26 +0000641 if (Size > std::numeric_limits<SIZE_T>::max())
Rafael Espindola2a826e42014-06-13 17:20:48 +0000642 return make_error_code(errc::invalid_argument);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000643
Rafael Espindolaa23008a2014-12-16 03:10:29 +0000644 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
645 if (FileHandle == INVALID_HANDLE_VALUE)
646 return make_error_code(errc::bad_file_descriptor);
647
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000648 DWORD flprotect;
649 switch (Mode) {
650 case readonly: flprotect = PAGE_READONLY; break;
651 case readwrite: flprotect = PAGE_READWRITE; break;
652 case priv: flprotect = PAGE_WRITECOPY; break;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000653 }
654
Rafael Espindola369d5142014-12-16 02:53:35 +0000655 HANDLE FileMappingHandle =
David Majnemer17a44962013-10-07 09:52:36 +0000656 ::CreateFileMappingW(FileHandle, 0, flprotect,
657 (Offset + Size) >> 32,
658 (Offset + Size) & 0xffffffff,
659 0);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000660 if (FileMappingHandle == NULL) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000661 std::error_code ec = mapWindowsError(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000662 return ec;
663 }
664
665 DWORD dwDesiredAccess;
666 switch (Mode) {
667 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
668 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
669 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000670 }
671 Mapping = ::MapViewOfFile(FileMappingHandle,
672 dwDesiredAccess,
673 Offset >> 32,
674 Offset & 0xffffffff,
675 Size);
676 if (Mapping == NULL) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000677 std::error_code ec = mapWindowsError(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000678 ::CloseHandle(FileMappingHandle);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000679 return ec;
680 }
681
682 if (Size == 0) {
683 MEMORY_BASIC_INFORMATION mbi;
684 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
685 if (Result == 0) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000686 std::error_code ec = mapWindowsError(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000687 ::UnmapViewOfFile(Mapping);
688 ::CloseHandle(FileMappingHandle);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000689 return ec;
690 }
691 Size = mbi.RegionSize;
692 }
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000693
694 // Close all the handles except for the view. It will keep the other handles
695 // alive.
696 ::CloseHandle(FileMappingHandle);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000697 return std::error_code();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000698}
699
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000700mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
701 uint64_t offset, std::error_code &ec)
Rafael Espindolaa23008a2014-12-16 03:10:29 +0000702 : Size(length), Mapping() {
Rafael Espindola986f5ad2014-12-16 02:19:26 +0000703 ec = init(fd, offset, mode);
Rafael Espindolaa23008a2014-12-16 03:10:29 +0000704 if (ec)
Rafael Espindola369d5142014-12-16 02:53:35 +0000705 Mapping = 0;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000706}
707
708mapped_file_region::~mapped_file_region() {
709 if (Mapping)
710 ::UnmapViewOfFile(Mapping);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000711}
712
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000713uint64_t mapped_file_region::size() const {
714 assert(Mapping && "Mapping failed but used anyway!");
715 return Size;
716}
717
718char *mapped_file_region::data() const {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000719 assert(Mapping && "Mapping failed but used anyway!");
720 return reinterpret_cast<char*>(Mapping);
721}
722
723const char *mapped_file_region::const_data() const {
724 assert(Mapping && "Mapping failed but used anyway!");
725 return reinterpret_cast<const char*>(Mapping);
726}
727
728int mapped_file_region::alignment() {
729 SYSTEM_INFO SysInfo;
730 ::GetSystemInfo(&SysInfo);
731 return SysInfo.dwAllocationGranularity;
732}
733
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000734std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
Zachary Turner260bda32017-03-08 22:49:32 +0000735 StringRef path,
736 bool follow_symlinks) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000737 SmallVector<wchar_t, 128> path_utf16;
738
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000739 if (std::error_code ec = widenPath(path, path_utf16))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000740 return ec;
741
742 // Convert path to the format that Windows is happy with.
743 if (path_utf16.size() > 0 &&
744 !is_separator(path_utf16[path.size() - 1]) &&
745 path_utf16[path.size() - 1] != L':') {
746 path_utf16.push_back(L'\\');
747 path_utf16.push_back(L'*');
748 } else {
749 path_utf16.push_back(L'*');
750 }
751
752 // Get the first directory entry.
753 WIN32_FIND_DATAW FirstFind;
Michael J. Spencer751e9aa2010-12-09 17:37:18 +0000754 ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000755 if (!FindHandle)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000756 return mapWindowsError(::GetLastError());
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000757
Michael J. Spencer98879d72011-01-05 16:39:30 +0000758 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
759 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
760 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
761 FirstFind.cFileName[1] == L'.'))
762 if (!::FindNextFileW(FindHandle, &FirstFind)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000763 DWORD LastError = ::GetLastError();
Michael J. Spencer98879d72011-01-05 16:39:30 +0000764 // Check for end.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000765 if (LastError == ERROR_NO_MORE_FILES)
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000766 return detail::directory_iterator_destruct(it);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000767 return mapWindowsError(LastError);
Michael J. Spencer98879d72011-01-05 16:39:30 +0000768 } else
769 FilenameLen = ::wcslen(FirstFind.cFileName);
770
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000771 // Construct the current directory entry.
Michael J. Spencer98879d72011-01-05 16:39:30 +0000772 SmallString<128> directory_entry_name_utf8;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000773 if (std::error_code ec =
774 UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
775 directory_entry_name_utf8))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000776 return ec;
777
778 it.IterationHandle = intptr_t(FindHandle.take());
Michael J. Spencer98879d72011-01-05 16:39:30 +0000779 SmallString<128> directory_entry_path(path);
Yaron Keren92e1b622015-03-18 10:17:07 +0000780 path::append(directory_entry_path, directory_entry_name_utf8);
Zachary Turner260bda32017-03-08 22:49:32 +0000781 it.CurrentEntry = directory_entry(directory_entry_path, follow_symlinks);
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000782
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000783 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000784}
785
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000786std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000787 if (it.IterationHandle != 0)
788 // Closes the handle if it's valid.
789 ScopedFindHandle close(HANDLE(it.IterationHandle));
790 it.IterationHandle = 0;
791 it.CurrentEntry = directory_entry();
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000792 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000793}
794
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000795std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000796 WIN32_FIND_DATAW FindData;
797 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000798 DWORD LastError = ::GetLastError();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000799 // Check for end.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000800 if (LastError == ERROR_NO_MORE_FILES)
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000801 return detail::directory_iterator_destruct(it);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000802 return mapWindowsError(LastError);
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000803 }
804
Michael J. Spencer98879d72011-01-05 16:39:30 +0000805 size_t FilenameLen = ::wcslen(FindData.cFileName);
806 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
807 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
808 FindData.cFileName[1] == L'.'))
809 return directory_iterator_increment(it);
810
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000811 SmallString<128> directory_entry_path_utf8;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000812 if (std::error_code ec =
813 UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
814 directory_entry_path_utf8))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000815 return ec;
816
817 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000818 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000819}
820
Zachary Turnere48ace62017-03-10 17:39:21 +0000821static std::error_code realPathFromHandle(HANDLE H,
822 SmallVectorImpl<char> &RealPath) {
823 RealPath.clear();
824 llvm::SmallVector<wchar_t, MAX_PATH> Buffer;
825 DWORD CountChars = ::GetFinalPathNameByHandleW(
826 H, Buffer.begin(), Buffer.capacity() - 1, FILE_NAME_NORMALIZED);
827 if (CountChars > Buffer.capacity()) {
828 // The buffer wasn't big enough, try again. In this case the return value
829 // *does* indicate the size of the null terminator.
830 Buffer.reserve(CountChars);
831 CountChars = ::GetFinalPathNameByHandleW(
832 H, Buffer.data(), Buffer.capacity() - 1, FILE_NAME_NORMALIZED);
833 }
834 if (CountChars == 0)
835 return mapWindowsError(GetLastError());
836
837 const wchar_t *Data = Buffer.data();
838 if (CountChars >= 4) {
839 if (0 == ::memcmp(Data, L"\\\\?\\", 8)) {
840 CountChars -= 4;
841 Data += 4;
842 }
843 }
844
845 // Convert the result from UTF-16 to UTF-8.
846 return UTF16ToUTF8(Data, CountChars, RealPath);
847}
848
849static std::error_code directoryRealPath(const Twine &Name,
850 SmallVectorImpl<char> &RealPath) {
851 SmallVector<wchar_t, 128> PathUTF16;
852
853 if (std::error_code EC = widenPath(Name, PathUTF16))
854 return EC;
855
856 HANDLE H =
857 ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
858 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
859 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
860 if (H == INVALID_HANDLE_VALUE)
861 return mapWindowsError(GetLastError());
862 std::error_code EC = realPathFromHandle(H, RealPath);
863 ::CloseHandle(H);
864 return EC;
865}
866
Taewook Ohd9153272016-06-13 15:54:56 +0000867std::error_code openFileForRead(const Twine &Name, int &ResultFD,
868 SmallVectorImpl<char> *RealPath) {
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000869 SmallVector<wchar_t, 128> PathUTF16;
Nick Kledzik18497e92012-06-20 00:28:54 +0000870
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000871 if (std::error_code EC = widenPath(Name, PathUTF16))
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000872 return EC;
873
Greg Bedwell7f68a712015-10-12 15:11:47 +0000874 HANDLE H =
875 ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
876 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
877 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000878 if (H == INVALID_HANDLE_VALUE) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000879 DWORD LastError = ::GetLastError();
Yaron Kerenf8e65172015-05-04 04:48:10 +0000880 std::error_code EC = mapWindowsError(LastError);
Rafael Espindola331aeba2013-07-17 19:58:28 +0000881 // Provide a better error message when trying to open directories.
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000882 // This only runs if we failed to open the file, so there is probably
883 // no performances issues.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000884 if (LastError != ERROR_ACCESS_DENIED)
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000885 return EC;
886 if (is_directory(Name))
Rafael Espindola2a826e42014-06-13 17:20:48 +0000887 return make_error_code(errc::is_a_directory);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000888 return EC;
889 }
890
891 int FD = ::_open_osfhandle(intptr_t(H), 0);
892 if (FD == -1) {
893 ::CloseHandle(H);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000894 return mapWindowsError(ERROR_INVALID_HANDLE);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000895 }
896
Taewook Ohd9153272016-06-13 15:54:56 +0000897 // Fetch the real name of the file, if the user asked
Zachary Turnere48ace62017-03-10 17:39:21 +0000898 if (RealPath)
Zachary Turner3c0dc332017-03-10 18:33:41 +0000899 realPathFromHandle(H, *RealPath);
Taewook Ohd9153272016-06-13 15:54:56 +0000900
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000901 ResultFD = FD;
Zachary Turner3c0dc332017-03-10 18:33:41 +0000902 return std::error_code();
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000903}
Nick Kledzik18497e92012-06-20 00:28:54 +0000904
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000905std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
Rafael Espindola67080ce2013-07-19 15:02:03 +0000906 sys::fs::OpenFlags Flags, unsigned Mode) {
907 // Verify that we don't have both "append" and "excl".
908 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
909 "Cannot specify both 'excl' and 'append' file creation flags!");
910
Rafael Espindola67080ce2013-07-19 15:02:03 +0000911 SmallVector<wchar_t, 128> PathUTF16;
912
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000913 if (std::error_code EC = widenPath(Name, PathUTF16))
Rafael Espindola67080ce2013-07-19 15:02:03 +0000914 return EC;
915
916 DWORD CreationDisposition;
917 if (Flags & F_Excl)
918 CreationDisposition = CREATE_NEW;
NAKAMURA Takumiedf76152013-08-22 15:14:45 +0000919 else if (Flags & F_Append)
Rafael Espindola67080ce2013-07-19 15:02:03 +0000920 CreationDisposition = OPEN_ALWAYS;
921 else
922 CreationDisposition = CREATE_ALWAYS;
923
Rafael Espindola7a0b6402014-02-24 03:07:41 +0000924 DWORD Access = GENERIC_WRITE;
925 if (Flags & F_RW)
926 Access |= GENERIC_READ;
927
Reid Klecknercefb3332017-08-04 21:52:00 +0000928 HANDLE H =
929 ::CreateFileW(PathUTF16.begin(), Access,
930 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
931 NULL, CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
Rafael Espindola67080ce2013-07-19 15:02:03 +0000932
933 if (H == INVALID_HANDLE_VALUE) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000934 DWORD LastError = ::GetLastError();
Yaron Kerenf8e65172015-05-04 04:48:10 +0000935 std::error_code EC = mapWindowsError(LastError);
Rafael Espindola67080ce2013-07-19 15:02:03 +0000936 // Provide a better error message when trying to open directories.
937 // This only runs if we failed to open the file, so there is probably
938 // no performances issues.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000939 if (LastError != ERROR_ACCESS_DENIED)
Rafael Espindola67080ce2013-07-19 15:02:03 +0000940 return EC;
941 if (is_directory(Name))
Rafael Espindola2a826e42014-06-13 17:20:48 +0000942 return make_error_code(errc::is_a_directory);
Rafael Espindola67080ce2013-07-19 15:02:03 +0000943 return EC;
944 }
945
946 int OpenFlags = 0;
947 if (Flags & F_Append)
948 OpenFlags |= _O_APPEND;
949
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000950 if (Flags & F_Text)
Rafael Espindola67080ce2013-07-19 15:02:03 +0000951 OpenFlags |= _O_TEXT;
952
953 int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
954 if (FD == -1) {
955 ::CloseHandle(H);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000956 return mapWindowsError(ERROR_INVALID_HANDLE);
Rafael Espindola67080ce2013-07-19 15:02:03 +0000957 }
958
959 ResultFD = FD;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000960 return std::error_code();
Rafael Espindola67080ce2013-07-19 15:02:03 +0000961}
Taewook Ohd9153272016-06-13 15:54:56 +0000962
Zachary Turner260bda32017-03-08 22:49:32 +0000963std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
964 // Convert to utf-16.
965 SmallVector<wchar_t, 128> Path16;
966 std::error_code EC = widenPath(path, Path16);
967 if (EC && !IgnoreErrors)
968 return EC;
969
970 // SHFileOperation() accepts a list of paths, and so must be double null-
971 // terminated to indicate the end of the list. The buffer is already null
972 // terminated, but since that null character is not considered part of the
973 // vector's size, pushing another one will just consume that byte. So we
974 // need to push 2 null terminators.
975 Path16.push_back(0);
976 Path16.push_back(0);
977
978 SHFILEOPSTRUCTW shfos = {};
979 shfos.wFunc = FO_DELETE;
980 shfos.pFrom = Path16.data();
981 shfos.fFlags = FOF_NO_UI;
982
983 int result = ::SHFileOperationW(&shfos);
984 if (result != 0 && !IgnoreErrors)
985 return mapWindowsError(result);
986 return std::error_code();
987}
988
Zachary Turnere48ace62017-03-10 17:39:21 +0000989static void expandTildeExpr(SmallVectorImpl<char> &Path) {
990 // Path does not begin with a tilde expression.
991 if (Path.empty() || Path[0] != '~')
992 return;
993
994 StringRef PathStr(Path.begin(), Path.size());
995 PathStr = PathStr.drop_front();
Zachary Turner5c5091f2017-03-16 22:28:04 +0000996 StringRef Expr = PathStr.take_until([](char c) { return path::is_separator(c); });
Zachary Turnere48ace62017-03-10 17:39:21 +0000997
998 if (!Expr.empty()) {
999 // This is probably a ~username/ expression. Don't support this on Windows.
1000 return;
1001 }
1002
1003 SmallString<128> HomeDir;
1004 if (!path::home_directory(HomeDir)) {
1005 // For some reason we couldn't get the home directory. Just exit.
1006 return;
1007 }
1008
1009 // Overwrite the first character and insert the rest.
1010 Path[0] = HomeDir[0];
1011 Path.insert(Path.begin() + 1, HomeDir.begin() + 1, HomeDir.end());
1012}
1013
1014std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1015 bool expand_tilde) {
1016 dest.clear();
1017 if (path.isTriviallyEmpty())
1018 return std::error_code();
1019
1020 if (expand_tilde) {
1021 SmallString<128> Storage;
1022 path.toVector(Storage);
1023 expandTildeExpr(Storage);
1024 return real_path(Storage, dest, false);
1025 }
1026
1027 if (is_directory(path))
1028 return directoryRealPath(path, dest);
1029
1030 int fd;
1031 if (std::error_code EC = llvm::sys::fs::openFileForRead(path, fd, &dest))
1032 return EC;
1033 ::close(fd);
1034 return std::error_code();
1035}
1036
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +00001037} // end namespace fs
Rui Ueyama471d0c52013-09-10 19:45:51 +00001038
Peter Collingbournef7d41012014-01-31 23:46:06 +00001039namespace path {
Pawel Bylica7c1f36a2015-11-02 14:57:24 +00001040static bool getKnownFolderPath(KNOWNFOLDERID folderId,
1041 SmallVectorImpl<char> &result) {
Pawel Bylica7187e4b2015-10-16 09:08:59 +00001042 wchar_t *path = nullptr;
1043 if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK)
1044 return false;
1045
1046 bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
1047 ::CoTaskMemFree(path);
1048 return ok;
1049}
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001050
1051bool getUserCacheDir(SmallVectorImpl<char> &Result) {
1052 return getKnownFolderPath(FOLDERID_LocalAppData, Result);
1053}
Pawel Bylica7187e4b2015-10-16 09:08:59 +00001054
Peter Collingbournef7d41012014-01-31 23:46:06 +00001055bool home_directory(SmallVectorImpl<char> &result) {
Pawel Bylica7187e4b2015-10-16 09:08:59 +00001056 return getKnownFolderPath(FOLDERID_Profile, result);
Peter Collingbournef7d41012014-01-31 23:46:06 +00001057}
1058
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001059static bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {
Pawel Bylica6e680b22015-11-06 23:44:23 +00001060 SmallVector<wchar_t, 1024> Buf;
1061 size_t Size = 1024;
1062 do {
1063 Buf.reserve(Size);
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001064 Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.capacity());
Pawel Bylica6e680b22015-11-06 23:44:23 +00001065 if (Size == 0)
1066 return false;
1067
1068 // Try again with larger buffer.
1069 } while (Size > Buf.capacity());
1070 Buf.set_size(Size);
1071
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001072 return !windows::UTF16ToUTF8(Buf.data(), Size, Res);
Pawel Bylica6e680b22015-11-06 23:44:23 +00001073}
1074
1075static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001076 const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};
1077 for (auto *Env : EnvironmentVariables) {
Pawel Bylica6e680b22015-11-06 23:44:23 +00001078 if (getTempDirEnvVar(Env, Res))
1079 return true;
1080 }
1081 return false;
1082}
1083
Rafael Espindola016a6d52014-08-26 14:47:52 +00001084void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1085 (void)ErasedOnReboot;
Pawel Bylica6e680b22015-11-06 23:44:23 +00001086 Result.clear();
Rafael Espindola016a6d52014-08-26 14:47:52 +00001087
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001088 // Check whether the temporary directory is specified by an environment var.
1089 // This matches GetTempPath logic to some degree. GetTempPath is not used
1090 // directly as it cannot handle evn var longer than 130 chars on Windows 7
1091 // (fixed on Windows 8).
1092 if (getTempDirEnvVar(Result)) {
1093 assert(!Result.empty() && "Unexpected empty path");
1094 native(Result); // Some Unix-like shells use Unix path separator in $TMP.
1095 fs::make_absolute(Result); // Make it absolute if not already.
Pawel Bylica6e680b22015-11-06 23:44:23 +00001096 return;
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001097 }
Rafael Espindola016a6d52014-08-26 14:47:52 +00001098
1099 // Fall back to a system default.
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001100 const char *DefaultResult = "C:\\Temp";
Rafael Espindola016a6d52014-08-26 14:47:52 +00001101 Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
1102}
Peter Collingbournef7d41012014-01-31 23:46:06 +00001103} // end namespace path
1104
Rui Ueyama471d0c52013-09-10 19:45:51 +00001105namespace windows {
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +00001106std::error_code UTF8ToUTF16(llvm::StringRef utf8,
Rafael Espindolab4ad29b2014-06-13 02:36:09 +00001107 llvm::SmallVectorImpl<wchar_t> &utf16) {
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001108 if (!utf8.empty()) {
1109 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
1110 utf8.size(), utf16.begin(), 0);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001111
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001112 if (len == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +00001113 return mapWindowsError(::GetLastError());
Rui Ueyama471d0c52013-09-10 19:45:51 +00001114
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001115 utf16.reserve(len + 1);
1116 utf16.set_size(len);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001117
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001118 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
1119 utf8.size(), utf16.begin(), utf16.size());
Rui Ueyama471d0c52013-09-10 19:45:51 +00001120
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001121 if (len == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +00001122 return mapWindowsError(::GetLastError());
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001123 }
Rui Ueyama471d0c52013-09-10 19:45:51 +00001124
1125 // Make utf16 null terminated.
1126 utf16.push_back(0);
1127 utf16.pop_back();
1128
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +00001129 return std::error_code();
Rui Ueyama471d0c52013-09-10 19:45:51 +00001130}
1131
Rafael Espindola9c359662014-09-03 20:02:00 +00001132static
1133std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
1134 size_t utf16_len,
1135 llvm::SmallVectorImpl<char> &utf8) {
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001136 if (utf16_len) {
1137 // Get length.
Rafael Espindola9c359662014-09-03 20:02:00 +00001138 int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.begin(),
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001139 0, NULL, NULL);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001140
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001141 if (len == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +00001142 return mapWindowsError(::GetLastError());
Rui Ueyama471d0c52013-09-10 19:45:51 +00001143
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001144 utf8.reserve(len);
1145 utf8.set_size(len);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001146
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001147 // Now do the actual conversion.
Rafael Espindola9c359662014-09-03 20:02:00 +00001148 len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.data(),
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001149 utf8.size(), NULL, NULL);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001150
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001151 if (len == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +00001152 return mapWindowsError(::GetLastError());
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001153 }
Rui Ueyama471d0c52013-09-10 19:45:51 +00001154
1155 // Make utf8 null terminated.
1156 utf8.push_back(0);
1157 utf8.pop_back();
1158
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +00001159 return std::error_code();
Rui Ueyama471d0c52013-09-10 19:45:51 +00001160}
Rafael Espindola9c359662014-09-03 20:02:00 +00001161
1162std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
1163 llvm::SmallVectorImpl<char> &utf8) {
1164 return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
1165}
1166
1167std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
1168 llvm::SmallVectorImpl<char> &utf8) {
1169 return UTF16ToCodePage(CP_ACP, utf16, utf16_len, utf8);
1170}
Taewook Ohd9153272016-06-13 15:54:56 +00001171
Rui Ueyama471d0c52013-09-10 19:45:51 +00001172} // end namespace windows
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001173} // end namespace sys
1174} // end namespace llvm