blob: dceaaa1542cc7593cf585530ef643adb27bf95be [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 }
Pirama Arumuga Nainar3d48bb52017-08-21 20:49:44 +000097 // Traverse the requested path, canonicalizing . and .. (because the \\?\
98 // prefix is documented to treat them as real components). Ignore
99 // separators, which can be returned from the iterator if the path has a
100 // drive name. We don't need to call native() on the result since append()
101 // always attaches preferred_separator.
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000102 for (llvm::sys::path::const_iterator I = llvm::sys::path::begin(Path8Str),
103 E = llvm::sys::path::end(Path8Str);
104 I != E; ++I) {
Pirama Arumuga Nainar3d48bb52017-08-21 20:49:44 +0000105 if (I->size() == 1 && is_separator((*I)[0]))
106 continue;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000107 if (I->size() == 1 && *I == ".")
108 continue;
109 if (I->size() == 2 && *I == "..")
110 llvm::sys::path::remove_filename(FullPath);
111 else
112 llvm::sys::path::append(FullPath, *I);
113 }
114 return UTF8ToUTF16(FullPath, Path16);
115 }
116
117 // Just use the caller's original path.
118 return UTF8ToUTF16(Path8Str, Path16);
119}
Paul Robinsonc38deee2014-11-24 18:05:29 +0000120} // end namespace path
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000121
Michael J. Spencer20daa282010-12-07 01:22:31 +0000122namespace fs {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000123
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000124std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
David Majnemer17a44962013-10-07 09:52:36 +0000125 SmallVector<wchar_t, MAX_PATH> PathName;
126 DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
127
128 // A zero return value indicates a failure other than insufficient space.
129 if (Size == 0)
130 return "";
131
132 // Insufficient space is determined by a return value equal to the size of
133 // the buffer passed in.
134 if (Size == PathName.capacity())
135 return "";
136
137 // On success, GetModuleFileNameW returns the number of characters written to
138 // the buffer not including the NULL terminator.
139 PathName.set_size(Size);
140
141 // Convert the result from UTF-16 to UTF-8.
142 SmallVector<char, MAX_PATH> PathNameUTF8;
143 if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
144 return "";
145
146 return std::string(PathNameUTF8.data());
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000147}
148
Rafael Espindolad1230992013-07-29 21:55:38 +0000149UniqueID file_status::getUniqueID() const {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000150 // The file is uniquely identified by the volume serial number along
151 // with the 64-bit file identifier.
152 uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
153 static_cast<uint64_t>(FileIndexLow);
154
155 return UniqueID(VolumeSerialNumber, FileID);
156}
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000157
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000158ErrorOr<space_info> disk_space(const Twine &Path) {
159 ULARGE_INTEGER Avail, Total, Free;
160 if (!::GetDiskFreeSpaceExA(Path.str().c_str(), &Avail, &Total, &Free))
161 return mapWindowsError(::GetLastError());
162 space_info SpaceInfo;
163 SpaceInfo.capacity =
164 (static_cast<uint64_t>(Total.HighPart) << 32) + Total.LowPart;
Mehdi Amini64719152016-04-01 00:52:05 +0000165 SpaceInfo.free = (static_cast<uint64_t>(Free.HighPart) << 32) + Free.LowPart;
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000166 SpaceInfo.available =
167 (static_cast<uint64_t>(Avail.HighPart) << 32) + Avail.LowPart;
168 return SpaceInfo;
169}
170
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000171TimePoint<> basic_file_status::getLastAccessedTime() const {
Pavel Labath757ca882016-10-24 10:59:17 +0000172 FILETIME Time;
173 Time.dwLowDateTime = LastAccessedTimeLow;
174 Time.dwHighDateTime = LastAccessedTimeHigh;
175 return toTimePoint(Time);
Mehdi Amini1e39ef32016-03-25 07:30:21 +0000176}
177
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000178TimePoint<> basic_file_status::getLastModificationTime() const {
Pavel Labath757ca882016-10-24 10:59:17 +0000179 FILETIME Time;
180 Time.dwLowDateTime = LastWriteTimeLow;
181 Time.dwHighDateTime = LastWriteTimeHigh;
182 return toTimePoint(Time);
Rafael Espindoladb5d8fe2013-06-20 18:42:04 +0000183}
184
Zachary Turner5821a3b2017-03-20 23:55:20 +0000185uint32_t file_status::getLinkCount() const {
186 return NumLinks;
187}
188
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000189std::error_code current_path(SmallVectorImpl<char> &result) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000190 SmallVector<wchar_t, MAX_PATH> cur_path;
191 DWORD len = MAX_PATH;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000192
David Majnemer61eae2e2013-10-07 01:00:07 +0000193 do {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000194 cur_path.reserve(len);
David Majnemer61eae2e2013-10-07 01:00:07 +0000195 len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000196
David Majnemer61eae2e2013-10-07 01:00:07 +0000197 // A zero return value indicates a failure other than insufficient space.
198 if (len == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000199 return mapWindowsError(::GetLastError());
David Majnemer61eae2e2013-10-07 01:00:07 +0000200
201 // If there's insufficient space, the len returned is larger than the len
202 // given.
203 } while (len > cur_path.capacity());
204
205 // On success, GetCurrentDirectoryW returns the number of characters not
206 // including the null-terminator.
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000207 cur_path.set_size(len);
Aaron Ballmanb16cf532013-08-16 17:53:28 +0000208 return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000209}
210
Pavel Labath2f096092017-01-24 10:32:03 +0000211std::error_code set_current_path(const Twine &path) {
212 // Convert to utf-16.
213 SmallVector<wchar_t, 128> wide_path;
214 if (std::error_code ec = widenPath(path, wide_path))
215 return ec;
216
217 if (!::SetCurrentDirectoryW(wide_path.begin()))
218 return mapWindowsError(::GetLastError());
219
220 return std::error_code();
221}
222
Frederic Riss6b9396c2015-08-06 21:04:55 +0000223std::error_code create_directory(const Twine &path, bool IgnoreExisting,
224 perms Perms) {
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000225 SmallVector<wchar_t, 128> path_utf16;
226
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000227 if (std::error_code ec = widenPath(path, path_utf16))
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000228 return ec;
229
230 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000231 DWORD LastError = ::GetLastError();
232 if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000233 return mapWindowsError(LastError);
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000234 }
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000235
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000236 return std::error_code();
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000237}
238
Rafael Espindola83f858e2014-03-11 18:40:24 +0000239// We can't use symbolic links for windows.
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000240std::error_code create_link(const Twine &to, const Twine &from) {
Michael J. Spencere0c45602010-12-03 05:58:41 +0000241 // Convert to utf-16.
242 SmallVector<wchar_t, 128> wide_from;
243 SmallVector<wchar_t, 128> wide_to;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000244 if (std::error_code ec = widenPath(from, wide_from))
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000245 return ec;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000246 if (std::error_code ec = widenPath(to, wide_to))
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000247 return ec;
Michael J. Spencere0c45602010-12-03 05:58:41 +0000248
249 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
Yaron Kerenf8e65172015-05-04 04:48:10 +0000250 return mapWindowsError(::GetLastError());
Michael J. Spencere0c45602010-12-03 05:58:41 +0000251
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000252 return std::error_code();
Michael J. Spencere0c45602010-12-03 05:58:41 +0000253}
254
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000255std::error_code create_hard_link(const Twine &to, const Twine &from) {
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +0000256 return create_link(to, from);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000257}
258
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000259std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000260 SmallVector<wchar_t, 128> path_utf16;
261
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
Peter Collingbourne0f9e8892017-10-10 19:39:46 +0000265 // We don't know whether this is a file or a directory, and remove() can
266 // accept both. The usual way to delete a file or directory is to use one of
267 // the DeleteFile or RemoveDirectory functions, but that requires you to know
268 // which one it is. We could stat() the file to determine that, but that would
269 // cost us additional system calls, which can be slow in a directory
270 // containing a large number of files. So instead we call CreateFile directly.
271 // The important part is the FILE_FLAG_DELETE_ON_CLOSE flag, which causes the
272 // file to be deleted once it is closed. We also use the flags
273 // FILE_FLAG_BACKUP_SEMANTICS (which allows us to open directories), and
274 // FILE_FLAG_OPEN_REPARSE_POINT (don't follow symlinks).
275 ScopedFileHandle h(::CreateFileW(
276 c_str(path_utf16), DELETE,
277 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
278 OPEN_EXISTING,
279 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS |
280 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_DELETE_ON_CLOSE,
281 NULL));
282 if (!h) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000283 std::error_code EC = mapWindowsError(::GetLastError());
Rafael Espindola2a826e42014-06-13 17:20:48 +0000284 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000285 return EC;
286 }
Peter Collingbourne0f9e8892017-10-10 19:39:46 +0000287
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000288 return std::error_code();
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000289}
290
Zachary Turner392ed9d2017-02-21 20:55:47 +0000291static std::error_code is_local_internal(SmallVectorImpl<wchar_t> &Path,
292 bool &Result) {
293 SmallVector<wchar_t, 128> VolumePath;
294 size_t Len = 128;
295 while (true) {
296 VolumePath.resize(Len);
297 BOOL Success =
298 ::GetVolumePathNameW(Path.data(), VolumePath.data(), VolumePath.size());
299
300 if (Success)
301 break;
302
303 DWORD Err = ::GetLastError();
304 if (Err != ERROR_INSUFFICIENT_BUFFER)
305 return mapWindowsError(Err);
306
307 Len *= 2;
308 }
309 // If the output buffer has exactly enough space for the path name, but not
310 // the null terminator, it will leave the output unterminated. Push a null
311 // terminator onto the end to ensure that this never happens.
312 VolumePath.push_back(L'\0');
313 VolumePath.set_size(wcslen(VolumePath.data()));
314 const wchar_t *P = VolumePath.data();
315
316 UINT Type = ::GetDriveTypeW(P);
317 switch (Type) {
318 case DRIVE_FIXED:
319 Result = true;
320 return std::error_code();
321 case DRIVE_REMOTE:
322 case DRIVE_CDROM:
323 case DRIVE_RAMDISK:
324 case DRIVE_REMOVABLE:
325 Result = false;
326 return std::error_code();
327 default:
328 return make_error_code(errc::no_such_file_or_directory);
329 }
330 llvm_unreachable("Unreachable!");
331}
332
333std::error_code is_local(const Twine &path, bool &result) {
334 if (!llvm::sys::fs::exists(path) || !llvm::sys::path::has_root_path(path))
335 return make_error_code(errc::no_such_file_or_directory);
336
337 SmallString<128> Storage;
338 StringRef P = path.toStringRef(Storage);
339
340 // Convert to utf-16.
341 SmallVector<wchar_t, 128> WidePath;
342 if (std::error_code ec = widenPath(P, WidePath))
343 return ec;
344 return is_local_internal(WidePath, result);
345}
346
Rafael Espindola041299e2017-11-18 02:05:59 +0000347static std::error_code realPathFromHandle(HANDLE H,
Rafael Espindola8dc0e102017-11-18 02:12:53 +0000348 SmallVectorImpl<wchar_t> &Buffer) {
349 DWORD CountChars = ::GetFinalPathNameByHandleW(
350 H, Buffer.begin(), Buffer.capacity() - 1, FILE_NAME_NORMALIZED);
351 if (CountChars > Buffer.capacity()) {
352 // The buffer wasn't big enough, try again. In this case the return value
353 // *does* indicate the size of the null terminator.
354 Buffer.reserve(CountChars);
355 CountChars = ::GetFinalPathNameByHandleW(
356 H, Buffer.data(), Buffer.capacity() - 1, FILE_NAME_NORMALIZED);
357 }
358 if (CountChars == 0)
359 return mapWindowsError(GetLastError());
360 Buffer.set_size(CountChars);
361 return std::error_code();
362}
363
364static std::error_code realPathFromHandle(HANDLE H,
365 SmallVectorImpl<char> &RealPath) {
366 RealPath.clear();
367 SmallVector<wchar_t, MAX_PATH> Buffer;
368 if (std::error_code EC = realPathFromHandle(H, Buffer))
369 return EC;
370
371 const wchar_t *Data = Buffer.data();
372 DWORD CountChars = Buffer.size();
373 if (CountChars >= 4) {
374 if (0 == ::memcmp(Data, L"\\\\?\\", 8)) {
375 CountChars -= 4;
376 Data += 4;
377 }
378 }
379
380 // Convert the result from UTF-16 to UTF-8.
381 return UTF16ToUTF8(Data, CountChars, RealPath);
382}
Rafael Espindola041299e2017-11-18 02:05:59 +0000383
Zachary Turner392ed9d2017-02-21 20:55:47 +0000384std::error_code is_local(int FD, bool &Result) {
385 SmallVector<wchar_t, 128> FinalPath;
386 HANDLE Handle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
387
Rafael Espindola041299e2017-11-18 02:05:59 +0000388 if (std::error_code EC = realPathFromHandle(Handle, FinalPath))
389 return EC;
Zachary Turner392ed9d2017-02-21 20:55:47 +0000390
391 return is_local_internal(FinalPath, Result);
392}
393
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000394static std::error_code rename_internal(HANDLE FromHandle, const Twine &To,
395 bool ReplaceIfExists) {
396 SmallVector<wchar_t, 0> ToWide;
397 if (auto EC = widenPath(To, ToWide))
398 return EC;
399
400 std::vector<char> RenameInfoBuf(sizeof(FILE_RENAME_INFO) - sizeof(wchar_t) +
401 (ToWide.size() * sizeof(wchar_t)));
402 FILE_RENAME_INFO &RenameInfo =
403 *reinterpret_cast<FILE_RENAME_INFO *>(RenameInfoBuf.data());
404 RenameInfo.ReplaceIfExists = ReplaceIfExists;
405 RenameInfo.RootDirectory = 0;
406 RenameInfo.FileNameLength = ToWide.size();
Adrian McCarthye6275c62017-10-09 17:50:01 +0000407 std::copy(ToWide.begin(), ToWide.end(), &RenameInfo.FileName[0]);
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000408
Hans Wennborg477c9742017-10-12 17:38:22 +0000409 SetLastError(ERROR_SUCCESS);
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000410 if (!SetFileInformationByHandle(FromHandle, FileRenameInfo, &RenameInfo,
Hans Wennborg477c9742017-10-12 17:38:22 +0000411 RenameInfoBuf.size())) {
412 unsigned Error = GetLastError();
413 if (Error == ERROR_SUCCESS)
414 Error = ERROR_CALL_NOT_IMPLEMENTED; // Wine doesn't always set error code.
415 return mapWindowsError(Error);
416 }
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000417
418 return std::error_code();
419}
420
Rafael Espindola5908aff2017-11-21 01:52:44 +0000421static std::error_code rename_handle(HANDLE FromHandle, const Twine &To) {
422 SmallVector<wchar_t, 128> WideTo;
423 if (std::error_code EC = widenPath(To, WideTo))
424 return EC;
425
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000426 // We normally expect this loop to succeed after a few iterations. If it
427 // requires more than 200 tries, it's more likely that the failures are due to
428 // a true error, so stop trying.
429 for (unsigned Retry = 0; Retry != 200; ++Retry) {
430 auto EC = rename_internal(FromHandle, To, true);
Hans Wennborg17701ab2017-10-11 22:04:14 +0000431
432 if (EC ==
433 std::error_code(ERROR_CALL_NOT_IMPLEMENTED, std::system_category())) {
434 // Wine doesn't support SetFileInformationByHandle in rename_internal.
435 // Fall back to MoveFileEx.
Rafael Espindola5908aff2017-11-21 01:52:44 +0000436 SmallVector<wchar_t, MAX_PATH> WideFrom;
437 if (std::error_code EC2 = realPathFromHandle(FromHandle, WideFrom))
438 return EC2;
Hans Wennborg17701ab2017-10-11 22:04:14 +0000439 if (::MoveFileExW(WideFrom.begin(), WideTo.begin(),
440 MOVEFILE_REPLACE_EXISTING))
441 return std::error_code();
442 return mapWindowsError(GetLastError());
443 }
444
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000445 if (!EC || EC != errc::permission_denied)
446 return EC;
Greg Bedwell7f68a712015-10-12 15:11:47 +0000447
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000448 // The destination file probably exists and is currently open in another
449 // process, either because the file was opened without FILE_SHARE_DELETE or
450 // it is mapped into memory (e.g. using MemoryBuffer). Rename it in order to
451 // move it out of the way of the source file. Use FILE_FLAG_DELETE_ON_CLOSE
452 // to arrange for the destination file to be deleted when the other process
453 // closes it.
454 ScopedFileHandle ToHandle(
455 ::CreateFileW(WideTo.begin(), GENERIC_READ | DELETE,
456 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
457 NULL, OPEN_EXISTING,
458 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL));
459 if (!ToHandle) {
460 auto EC = mapWindowsError(GetLastError());
461 // Another process might have raced with us and moved the existing file
462 // out of the way before we had a chance to open it. If that happens, try
463 // to rename the source file again.
464 if (EC == errc::no_such_file_or_directory)
Sunil Srivastava34fce932016-03-25 23:41:28 +0000465 continue;
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000466 return EC;
Sunil Srivastava34fce932016-03-25 23:41:28 +0000467 }
Greg Bedwell7f68a712015-10-12 15:11:47 +0000468
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000469 BY_HANDLE_FILE_INFORMATION FI;
470 if (!GetFileInformationByHandle(ToHandle, &FI))
471 return mapWindowsError(GetLastError());
Greg Bedwell7f68a712015-10-12 15:11:47 +0000472
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000473 // Try to find a unique new name for the destination file.
474 for (unsigned UniqueId = 0; UniqueId != 200; ++UniqueId) {
475 std::string TmpFilename = (To + ".tmp" + utostr(UniqueId)).str();
476 if (auto EC = rename_internal(ToHandle, TmpFilename, false)) {
477 if (EC == errc::file_exists || EC == errc::permission_denied) {
478 // Again, another process might have raced with us and moved the file
479 // before we could move it. Check whether this is the case, as it
480 // might have caused the permission denied error. If that was the
481 // case, we don't need to move it ourselves.
482 ScopedFileHandle ToHandle2(::CreateFileW(
483 WideTo.begin(), 0,
484 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
485 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
486 if (!ToHandle2) {
487 auto EC = mapWindowsError(GetLastError());
488 if (EC == errc::no_such_file_or_directory)
489 break;
490 return EC;
491 }
492 BY_HANDLE_FILE_INFORMATION FI2;
493 if (!GetFileInformationByHandle(ToHandle2, &FI2))
494 return mapWindowsError(GetLastError());
495 if (FI.nFileIndexHigh != FI2.nFileIndexHigh ||
496 FI.nFileIndexLow != FI2.nFileIndexLow ||
497 FI.dwVolumeSerialNumber != FI2.dwVolumeSerialNumber)
498 break;
499 continue;
500 }
501 return EC;
502 }
503 break;
504 }
505
506 // Okay, the old destination file has probably been moved out of the way at
507 // this point, so try to rename the source file again. Still, another
508 // process might have raced with us to create and open the destination
509 // file, so we need to keep doing this until we succeed.
NAKAMURA Takumi3b7f9952012-05-08 14:31:46 +0000510 }
Michael J. Spencer409f5562010-12-03 17:53:55 +0000511
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000512 // The most likely root cause.
513 return errc::permission_denied;
Michael J. Spencer409f5562010-12-03 17:53:55 +0000514}
515
Rafael Espindola811d5e82017-11-21 05:35:45 +0000516std::error_code rename(const Twine &From, const Twine &To) {
517 // Convert to utf-16.
518 SmallVector<wchar_t, 128> WideFrom;
519 if (std::error_code EC = widenPath(From, WideFrom))
520 return EC;
521
522 ScopedFileHandle FromHandle;
523 // Retry this a few times to defeat badly behaved file system scanners.
524 for (unsigned Retry = 0; Retry != 200; ++Retry) {
525 if (Retry != 0)
526 ::Sleep(10);
527 FromHandle =
528 ::CreateFileW(WideFrom.begin(), GENERIC_READ | DELETE,
529 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
530 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
531 if (FromHandle)
532 break;
533 }
534 if (!FromHandle)
535 return mapWindowsError(GetLastError());
536
537 return rename_handle(FromHandle, To);
538}
539
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000540std::error_code resize_file(int FD, uint64_t Size) {
Michael J. Spencerca242f22010-12-03 18:48:56 +0000541#ifdef HAVE__CHSIZE_S
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000542 errno_t error = ::_chsize_s(FD, Size);
Michael J. Spencerca242f22010-12-03 18:48:56 +0000543#else
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000544 errno_t error = ::_chsize(FD, Size);
Michael J. Spencerca242f22010-12-03 18:48:56 +0000545#endif
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000546 return std::error_code(error, std::generic_category());
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000547}
548
Rafael Espindola281f23a2014-09-11 20:30:02 +0000549std::error_code access(const Twine &Path, AccessMode Mode) {
Rafael Espindola281f23a2014-09-11 20:30:02 +0000550 SmallVector<wchar_t, 128> PathUtf16;
Michael J. Spencer45710402010-12-03 01:21:28 +0000551
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000552 if (std::error_code EC = widenPath(Path, PathUtf16))
Rafael Espindola281f23a2014-09-11 20:30:02 +0000553 return EC;
Michael J. Spencer45710402010-12-03 01:21:28 +0000554
Rafael Espindola281f23a2014-09-11 20:30:02 +0000555 DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
Michael J. Spencer45710402010-12-03 01:21:28 +0000556
Rafael Espindola281f23a2014-09-11 20:30:02 +0000557 if (Attributes == INVALID_FILE_ATTRIBUTES) {
Michael J. Spencer45710402010-12-03 01:21:28 +0000558 // See if the file didn't actually exist.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000559 DWORD LastError = ::GetLastError();
560 if (LastError != ERROR_FILE_NOT_FOUND &&
561 LastError != ERROR_PATH_NOT_FOUND)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000562 return mapWindowsError(LastError);
Rafael Espindola281f23a2014-09-11 20:30:02 +0000563 return errc::no_such_file_or_directory;
564 }
565
566 if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
567 return errc::permission_denied;
568
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000569 return std::error_code();
Michael J. Spencer45710402010-12-03 01:21:28 +0000570}
571
Reid Kleckner89d4b1a2015-09-10 23:28:06 +0000572bool can_execute(const Twine &Path) {
573 return !access(Path, AccessMode::Execute) ||
574 !access(Path + ".exe", AccessMode::Execute);
575}
576
Michael J. Spencer203d7802011-12-12 06:04:28 +0000577bool equivalent(file_status A, file_status B) {
578 assert(status_known(A) && status_known(B));
Mehdi Amini1e39ef32016-03-25 07:30:21 +0000579 return A.FileIndexHigh == B.FileIndexHigh &&
580 A.FileIndexLow == B.FileIndexLow &&
581 A.FileSizeHigh == B.FileSizeHigh &&
582 A.FileSizeLow == B.FileSizeLow &&
583 A.LastAccessedTimeHigh == B.LastAccessedTimeHigh &&
584 A.LastAccessedTimeLow == B.LastAccessedTimeLow &&
585 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
586 A.LastWriteTimeLow == B.LastWriteTimeLow &&
587 A.VolumeSerialNumber == B.VolumeSerialNumber;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000588}
589
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000590std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000591 file_status fsA, fsB;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000592 if (std::error_code ec = status(A, fsA))
593 return ec;
594 if (std::error_code ec = status(B, fsB))
595 return ec;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000596 result = equivalent(fsA, fsB);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000597 return std::error_code();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000598}
599
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000600static bool isReservedName(StringRef path) {
601 // This list of reserved names comes from MSDN, at:
602 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
Craig Topper26260942015-10-18 05:15:34 +0000603 static const char *const sReservedNames[] = { "nul", "con", "prn", "aux",
604 "com1", "com2", "com3", "com4",
605 "com5", "com6", "com7", "com8",
606 "com9", "lpt1", "lpt2", "lpt3",
607 "lpt4", "lpt5", "lpt6", "lpt7",
608 "lpt8", "lpt9" };
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000609
610 // First, check to see if this is a device namespace, which always
611 // starts with \\.\, since device namespaces are not legal file paths.
612 if (path.startswith("\\\\.\\"))
613 return true;
614
Douglas Yung091d8fd2016-05-03 00:12:59 +0000615 // Then compare against the list of ancient reserved names.
Craig Topper58713212013-07-15 04:27:47 +0000616 for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000617 if (path.equals_lower(sReservedNames[i]))
618 return true;
619 }
620
621 // The path isn't what we consider reserved.
622 return false;
623}
624
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000625static file_type file_type_from_attrs(DWORD Attrs) {
626 return (Attrs & FILE_ATTRIBUTE_DIRECTORY) ? file_type::directory_file
627 : file_type::regular_file;
628}
629
630static perms perms_from_attrs(DWORD Attrs) {
631 return (Attrs & FILE_ATTRIBUTE_READONLY) ? (all_read | all_exe) : all_all;
632}
633
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000634static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000635 if (FileHandle == INVALID_HANDLE_VALUE)
636 goto handle_status_error;
637
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000638 switch (::GetFileType(FileHandle)) {
639 default:
Rafael Espindola81177c52013-07-18 18:42:52 +0000640 llvm_unreachable("Don't know anything about this file type");
641 case FILE_TYPE_UNKNOWN: {
642 DWORD Err = ::GetLastError();
643 if (Err != NO_ERROR)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000644 return mapWindowsError(Err);
Rafael Espindola81177c52013-07-18 18:42:52 +0000645 Result = file_status(file_type::type_unknown);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000646 return std::error_code();
Rafael Espindola81177c52013-07-18 18:42:52 +0000647 }
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000648 case FILE_TYPE_DISK:
649 break;
650 case FILE_TYPE_CHAR:
651 Result = file_status(file_type::character_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000652 return std::error_code();
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000653 case FILE_TYPE_PIPE:
654 Result = file_status(file_type::fifo_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000655 return std::error_code();
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000656 }
657
Rafael Espindola77021c92013-07-16 03:20:13 +0000658 BY_HANDLE_FILE_INFORMATION Info;
659 if (!::GetFileInformationByHandle(FileHandle, &Info))
660 goto handle_status_error;
661
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000662 Result = file_status(
663 file_type_from_attrs(Info.dwFileAttributes),
664 perms_from_attrs(Info.dwFileAttributes), Info.nNumberOfLinks,
665 Info.ftLastAccessTime.dwHighDateTime, Info.ftLastAccessTime.dwLowDateTime,
666 Info.ftLastWriteTime.dwHighDateTime, Info.ftLastWriteTime.dwLowDateTime,
667 Info.dwVolumeSerialNumber, Info.nFileSizeHigh, Info.nFileSizeLow,
668 Info.nFileIndexHigh, Info.nFileIndexLow);
669 return std::error_code();
Aaron Ballman345012d2017-03-13 12:24:51 +0000670
Rafael Espindola77021c92013-07-16 03:20:13 +0000671handle_status_error:
Rafael Espindolaa813d602014-06-11 03:58:34 +0000672 DWORD LastError = ::GetLastError();
673 if (LastError == ERROR_FILE_NOT_FOUND ||
674 LastError == ERROR_PATH_NOT_FOUND)
Rafael Espindola77021c92013-07-16 03:20:13 +0000675 Result = file_status(file_type::file_not_found);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000676 else if (LastError == ERROR_SHARING_VIOLATION)
Rafael Espindola77021c92013-07-16 03:20:13 +0000677 Result = file_status(file_type::type_unknown);
Rafael Espindola107b74c2013-07-31 00:10:25 +0000678 else
Rafael Espindola77021c92013-07-16 03:20:13 +0000679 Result = file_status(file_type::status_error);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000680 return mapWindowsError(LastError);
Rafael Espindola77021c92013-07-16 03:20:13 +0000681}
682
Zachary Turner82dd5422017-03-07 16:10:10 +0000683std::error_code status(const Twine &path, file_status &result, bool Follow) {
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000684 SmallString<128> path_storage;
685 SmallVector<wchar_t, 128> path_utf16;
686
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000687 StringRef path8 = path.toStringRef(path_storage);
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000688 if (isReservedName(path8)) {
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000689 result = file_status(file_type::character_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000690 return std::error_code();
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000691 }
692
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000693 if (std::error_code ec = widenPath(path8, path_utf16))
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000694 return ec;
695
696 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
697 if (attr == INVALID_FILE_ATTRIBUTES)
Rafael Espindola77021c92013-07-16 03:20:13 +0000698 return getStatus(INVALID_HANDLE_VALUE, result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000699
Zachary Turner82dd5422017-03-07 16:10:10 +0000700 DWORD Flags = FILE_FLAG_BACKUP_SEMANTICS;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000701 // Handle reparse points.
Zachary Turner82dd5422017-03-07 16:10:10 +0000702 if (!Follow && (attr & FILE_ATTRIBUTE_REPARSE_POINT))
703 Flags |= FILE_FLAG_OPEN_REPARSE_POINT;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000704
Rafael Espindolaa5932af2013-07-30 20:25:53 +0000705 ScopedFileHandle h(
706 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
Michael J. Spencer203d7802011-12-12 06:04:28 +0000707 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
Zachary Turner82dd5422017-03-07 16:10:10 +0000708 NULL, OPEN_EXISTING, Flags, 0));
709 if (!h)
710 return getStatus(INVALID_HANDLE_VALUE, result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000711
Zachary Turner82dd5422017-03-07 16:10:10 +0000712 return getStatus(h, result);
Rafael Espindola77021c92013-07-16 03:20:13 +0000713}
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000714
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000715std::error_code status(int FD, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000716 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
Aaron Ballman345012d2017-03-13 12:24:51 +0000717 return getStatus(FileHandle, Result);
718}
719
James Henderson566fdf42017-03-16 11:22:09 +0000720std::error_code setPermissions(const Twine &Path, perms Permissions) {
721 SmallVector<wchar_t, 128> PathUTF16;
722 if (std::error_code EC = widenPath(Path, PathUTF16))
723 return EC;
724
725 DWORD Attributes = ::GetFileAttributesW(PathUTF16.begin());
726 if (Attributes == INVALID_FILE_ATTRIBUTES)
727 return mapWindowsError(GetLastError());
728
729 // There are many Windows file attributes that are not to do with the file
730 // permissions (e.g. FILE_ATTRIBUTE_HIDDEN). We need to be careful to preserve
731 // them.
732 if (Permissions & all_write) {
733 Attributes &= ~FILE_ATTRIBUTE_READONLY;
734 if (Attributes == 0)
735 // FILE_ATTRIBUTE_NORMAL indicates no other attributes are set.
736 Attributes |= FILE_ATTRIBUTE_NORMAL;
737 }
738 else {
739 Attributes |= FILE_ATTRIBUTE_READONLY;
740 // FILE_ATTRIBUTE_NORMAL is not compatible with any other attributes, so
741 // remove it, if it is present.
742 Attributes &= ~FILE_ATTRIBUTE_NORMAL;
743 }
744
745 if (!::SetFileAttributesW(PathUTF16.begin(), Attributes))
746 return mapWindowsError(GetLastError());
747
748 return std::error_code();
749}
750
Aaron Ballman345012d2017-03-13 12:24:51 +0000751std::error_code setLastModificationAndAccessTime(int FD, TimePoint<> Time) {
752 FILETIME FT = toFILETIME(Time);
753 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000754 if (!SetFileTime(FileHandle, NULL, &FT, &FT))
Yaron Kerenf8e65172015-05-04 04:48:10 +0000755 return mapWindowsError(::GetLastError());
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000756 return std::error_code();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000757}
Nick Kledzik18497e92012-06-20 00:28:54 +0000758
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000759std::error_code mapped_file_region::init(int FD, uint64_t Offset,
760 mapmode Mode) {
Rafael Espindolaa23008a2014-12-16 03:10:29 +0000761 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
762 if (FileHandle == INVALID_HANDLE_VALUE)
763 return make_error_code(errc::bad_file_descriptor);
764
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000765 DWORD flprotect;
766 switch (Mode) {
767 case readonly: flprotect = PAGE_READONLY; break;
768 case readwrite: flprotect = PAGE_READWRITE; break;
769 case priv: flprotect = PAGE_WRITECOPY; break;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000770 }
771
Rafael Espindola369d5142014-12-16 02:53:35 +0000772 HANDLE FileMappingHandle =
David Majnemer17a44962013-10-07 09:52:36 +0000773 ::CreateFileMappingW(FileHandle, 0, flprotect,
Zachary Turnerab1ade42017-11-16 22:39:55 +0000774 Hi_32(Size),
775 Lo_32(Size),
David Majnemer17a44962013-10-07 09:52:36 +0000776 0);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000777 if (FileMappingHandle == NULL) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000778 std::error_code ec = mapWindowsError(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000779 return ec;
780 }
781
782 DWORD dwDesiredAccess;
783 switch (Mode) {
784 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
785 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
786 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000787 }
788 Mapping = ::MapViewOfFile(FileMappingHandle,
789 dwDesiredAccess,
790 Offset >> 32,
791 Offset & 0xffffffff,
792 Size);
793 if (Mapping == NULL) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000794 std::error_code ec = mapWindowsError(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000795 ::CloseHandle(FileMappingHandle);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000796 return ec;
797 }
798
799 if (Size == 0) {
800 MEMORY_BASIC_INFORMATION mbi;
801 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
802 if (Result == 0) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000803 std::error_code ec = mapWindowsError(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000804 ::UnmapViewOfFile(Mapping);
805 ::CloseHandle(FileMappingHandle);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000806 return ec;
807 }
808 Size = mbi.RegionSize;
809 }
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000810
811 // Close all the handles except for the view. It will keep the other handles
812 // alive.
813 ::CloseHandle(FileMappingHandle);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000814 return std::error_code();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000815}
816
Roman Lebedev1e053ab2017-09-27 17:24:34 +0000817mapped_file_region::mapped_file_region(int fd, mapmode mode, size_t length,
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000818 uint64_t offset, std::error_code &ec)
Rafael Espindolaa23008a2014-12-16 03:10:29 +0000819 : Size(length), Mapping() {
Rafael Espindola986f5ad2014-12-16 02:19:26 +0000820 ec = init(fd, offset, mode);
Rafael Espindolaa23008a2014-12-16 03:10:29 +0000821 if (ec)
Rafael Espindola369d5142014-12-16 02:53:35 +0000822 Mapping = 0;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000823}
824
825mapped_file_region::~mapped_file_region() {
826 if (Mapping)
827 ::UnmapViewOfFile(Mapping);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000828}
829
Roman Lebedev1e053ab2017-09-27 17:24:34 +0000830size_t mapped_file_region::size() const {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000831 assert(Mapping && "Mapping failed but used anyway!");
832 return Size;
833}
834
835char *mapped_file_region::data() const {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000836 assert(Mapping && "Mapping failed but used anyway!");
837 return reinterpret_cast<char*>(Mapping);
838}
839
840const char *mapped_file_region::const_data() const {
841 assert(Mapping && "Mapping failed but used anyway!");
842 return reinterpret_cast<const char*>(Mapping);
843}
844
845int mapped_file_region::alignment() {
846 SYSTEM_INFO SysInfo;
847 ::GetSystemInfo(&SysInfo);
848 return SysInfo.dwAllocationGranularity;
849}
850
Peter Collingbourneb4f1b882017-10-11 02:09:06 +0000851static basic_file_status status_from_find_data(WIN32_FIND_DATAW *FindData) {
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000852 return basic_file_status(file_type_from_attrs(FindData->dwFileAttributes),
853 perms_from_attrs(FindData->dwFileAttributes),
854 FindData->ftLastAccessTime.dwHighDateTime,
855 FindData->ftLastAccessTime.dwLowDateTime,
856 FindData->ftLastWriteTime.dwHighDateTime,
857 FindData->ftLastWriteTime.dwLowDateTime,
858 FindData->nFileSizeHigh, FindData->nFileSizeLow);
859}
860
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000861std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
Zachary Turner260bda32017-03-08 22:49:32 +0000862 StringRef path,
863 bool follow_symlinks) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000864 SmallVector<wchar_t, 128> path_utf16;
865
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000866 if (std::error_code ec = widenPath(path, path_utf16))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000867 return ec;
868
869 // Convert path to the format that Windows is happy with.
870 if (path_utf16.size() > 0 &&
871 !is_separator(path_utf16[path.size() - 1]) &&
872 path_utf16[path.size() - 1] != L':') {
873 path_utf16.push_back(L'\\');
874 path_utf16.push_back(L'*');
875 } else {
876 path_utf16.push_back(L'*');
877 }
878
879 // Get the first directory entry.
880 WIN32_FIND_DATAW FirstFind;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000881 ScopedFindHandle FindHandle(::FindFirstFileExW(
882 c_str(path_utf16), FindExInfoBasic, &FirstFind, FindExSearchNameMatch,
883 NULL, FIND_FIRST_EX_LARGE_FETCH));
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000884 if (!FindHandle)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000885 return mapWindowsError(::GetLastError());
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000886
Michael J. Spencer98879d72011-01-05 16:39:30 +0000887 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
888 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
889 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
890 FirstFind.cFileName[1] == L'.'))
891 if (!::FindNextFileW(FindHandle, &FirstFind)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000892 DWORD LastError = ::GetLastError();
Michael J. Spencer98879d72011-01-05 16:39:30 +0000893 // Check for end.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000894 if (LastError == ERROR_NO_MORE_FILES)
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000895 return detail::directory_iterator_destruct(it);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000896 return mapWindowsError(LastError);
Michael J. Spencer98879d72011-01-05 16:39:30 +0000897 } else
898 FilenameLen = ::wcslen(FirstFind.cFileName);
899
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000900 // Construct the current directory entry.
Michael J. Spencer98879d72011-01-05 16:39:30 +0000901 SmallString<128> directory_entry_name_utf8;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000902 if (std::error_code ec =
903 UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
904 directory_entry_name_utf8))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000905 return ec;
906
907 it.IterationHandle = intptr_t(FindHandle.take());
Michael J. Spencer98879d72011-01-05 16:39:30 +0000908 SmallString<128> directory_entry_path(path);
Yaron Keren92e1b622015-03-18 10:17:07 +0000909 path::append(directory_entry_path, directory_entry_name_utf8);
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000910 it.CurrentEntry = directory_entry(directory_entry_path, follow_symlinks,
911 status_from_find_data(&FirstFind));
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000912
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000913 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000914}
915
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000916std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000917 if (it.IterationHandle != 0)
918 // Closes the handle if it's valid.
919 ScopedFindHandle close(HANDLE(it.IterationHandle));
920 it.IterationHandle = 0;
921 it.CurrentEntry = directory_entry();
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000922 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000923}
924
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000925std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000926 WIN32_FIND_DATAW FindData;
927 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000928 DWORD LastError = ::GetLastError();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000929 // Check for end.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000930 if (LastError == ERROR_NO_MORE_FILES)
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000931 return detail::directory_iterator_destruct(it);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000932 return mapWindowsError(LastError);
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000933 }
934
Michael J. Spencer98879d72011-01-05 16:39:30 +0000935 size_t FilenameLen = ::wcslen(FindData.cFileName);
936 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
937 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
938 FindData.cFileName[1] == L'.'))
939 return directory_iterator_increment(it);
940
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000941 SmallString<128> directory_entry_path_utf8;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000942 if (std::error_code ec =
943 UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
944 directory_entry_path_utf8))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000945 return ec;
946
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000947 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8),
948 status_from_find_data(&FindData));
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000949 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000950}
951
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000952ErrorOr<basic_file_status> directory_entry::status() const {
953 return Status;
954}
955
Zachary Turnere48ace62017-03-10 17:39:21 +0000956static std::error_code directoryRealPath(const Twine &Name,
957 SmallVectorImpl<char> &RealPath) {
958 SmallVector<wchar_t, 128> PathUTF16;
959
960 if (std::error_code EC = widenPath(Name, PathUTF16))
961 return EC;
962
963 HANDLE H =
964 ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
965 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
966 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
967 if (H == INVALID_HANDLE_VALUE)
968 return mapWindowsError(GetLastError());
969 std::error_code EC = realPathFromHandle(H, RealPath);
970 ::CloseHandle(H);
971 return EC;
972}
973
Taewook Ohd9153272016-06-13 15:54:56 +0000974std::error_code openFileForRead(const Twine &Name, int &ResultFD,
975 SmallVectorImpl<char> *RealPath) {
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000976 SmallVector<wchar_t, 128> PathUTF16;
Nick Kledzik18497e92012-06-20 00:28:54 +0000977
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000978 if (std::error_code EC = widenPath(Name, PathUTF16))
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000979 return EC;
980
Greg Bedwell7f68a712015-10-12 15:11:47 +0000981 HANDLE H =
982 ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
983 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
984 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000985 if (H == INVALID_HANDLE_VALUE) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000986 DWORD LastError = ::GetLastError();
Yaron Kerenf8e65172015-05-04 04:48:10 +0000987 std::error_code EC = mapWindowsError(LastError);
Rafael Espindola331aeba2013-07-17 19:58:28 +0000988 // Provide a better error message when trying to open directories.
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000989 // This only runs if we failed to open the file, so there is probably
990 // no performances issues.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000991 if (LastError != ERROR_ACCESS_DENIED)
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000992 return EC;
993 if (is_directory(Name))
Rafael Espindola2a826e42014-06-13 17:20:48 +0000994 return make_error_code(errc::is_a_directory);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +0000995 return EC;
996 }
997
998 int FD = ::_open_osfhandle(intptr_t(H), 0);
999 if (FD == -1) {
1000 ::CloseHandle(H);
Yaron Kerenf8e65172015-05-04 04:48:10 +00001001 return mapWindowsError(ERROR_INVALID_HANDLE);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001002 }
1003
Taewook Ohd9153272016-06-13 15:54:56 +00001004 // Fetch the real name of the file, if the user asked
Zachary Turnere48ace62017-03-10 17:39:21 +00001005 if (RealPath)
Zachary Turner3c0dc332017-03-10 18:33:41 +00001006 realPathFromHandle(H, *RealPath);
Taewook Ohd9153272016-06-13 15:54:56 +00001007
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001008 ResultFD = FD;
Zachary Turner3c0dc332017-03-10 18:33:41 +00001009 return std::error_code();
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001010}
Nick Kledzik18497e92012-06-20 00:28:54 +00001011
Rafael Espindolab4ad29b2014-06-13 02:36:09 +00001012std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
Rafael Espindola67080ce2013-07-19 15:02:03 +00001013 sys::fs::OpenFlags Flags, unsigned Mode) {
1014 // Verify that we don't have both "append" and "excl".
1015 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
1016 "Cannot specify both 'excl' and 'append' file creation flags!");
1017
Rafael Espindola67080ce2013-07-19 15:02:03 +00001018 SmallVector<wchar_t, 128> PathUTF16;
1019
Paul Robinsond9c4a9a2014-11-13 00:12:14 +00001020 if (std::error_code EC = widenPath(Name, PathUTF16))
Rafael Espindola67080ce2013-07-19 15:02:03 +00001021 return EC;
1022
1023 DWORD CreationDisposition;
1024 if (Flags & F_Excl)
1025 CreationDisposition = CREATE_NEW;
NAKAMURA Takumiedf76152013-08-22 15:14:45 +00001026 else if (Flags & F_Append)
Rafael Espindola67080ce2013-07-19 15:02:03 +00001027 CreationDisposition = OPEN_ALWAYS;
1028 else
1029 CreationDisposition = CREATE_ALWAYS;
1030
Rafael Espindola7a0b6402014-02-24 03:07:41 +00001031 DWORD Access = GENERIC_WRITE;
1032 if (Flags & F_RW)
1033 Access |= GENERIC_READ;
1034
Reid Klecknercefb3332017-08-04 21:52:00 +00001035 HANDLE H =
1036 ::CreateFileW(PathUTF16.begin(), Access,
1037 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1038 NULL, CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
Rafael Espindola67080ce2013-07-19 15:02:03 +00001039
1040 if (H == INVALID_HANDLE_VALUE) {
Rafael Espindolaa813d602014-06-11 03:58:34 +00001041 DWORD LastError = ::GetLastError();
Yaron Kerenf8e65172015-05-04 04:48:10 +00001042 std::error_code EC = mapWindowsError(LastError);
Rafael Espindola67080ce2013-07-19 15:02:03 +00001043 // Provide a better error message when trying to open directories.
1044 // This only runs if we failed to open the file, so there is probably
1045 // no performances issues.
Rafael Espindolaa813d602014-06-11 03:58:34 +00001046 if (LastError != ERROR_ACCESS_DENIED)
Rafael Espindola67080ce2013-07-19 15:02:03 +00001047 return EC;
1048 if (is_directory(Name))
Rafael Espindola2a826e42014-06-13 17:20:48 +00001049 return make_error_code(errc::is_a_directory);
Rafael Espindola67080ce2013-07-19 15:02:03 +00001050 return EC;
1051 }
1052
1053 int OpenFlags = 0;
1054 if (Flags & F_Append)
1055 OpenFlags |= _O_APPEND;
1056
Rafael Espindola90c7f1c2014-02-24 18:20:12 +00001057 if (Flags & F_Text)
Rafael Espindola67080ce2013-07-19 15:02:03 +00001058 OpenFlags |= _O_TEXT;
1059
1060 int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
1061 if (FD == -1) {
1062 ::CloseHandle(H);
Yaron Kerenf8e65172015-05-04 04:48:10 +00001063 return mapWindowsError(ERROR_INVALID_HANDLE);
Rafael Espindola67080ce2013-07-19 15:02:03 +00001064 }
1065
1066 ResultFD = FD;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +00001067 return std::error_code();
Rafael Espindola67080ce2013-07-19 15:02:03 +00001068}
Taewook Ohd9153272016-06-13 15:54:56 +00001069
Zachary Turner260bda32017-03-08 22:49:32 +00001070std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1071 // Convert to utf-16.
1072 SmallVector<wchar_t, 128> Path16;
1073 std::error_code EC = widenPath(path, Path16);
1074 if (EC && !IgnoreErrors)
1075 return EC;
1076
1077 // SHFileOperation() accepts a list of paths, and so must be double null-
1078 // terminated to indicate the end of the list. The buffer is already null
1079 // terminated, but since that null character is not considered part of the
1080 // vector's size, pushing another one will just consume that byte. So we
1081 // need to push 2 null terminators.
1082 Path16.push_back(0);
1083 Path16.push_back(0);
1084
1085 SHFILEOPSTRUCTW shfos = {};
1086 shfos.wFunc = FO_DELETE;
1087 shfos.pFrom = Path16.data();
1088 shfos.fFlags = FOF_NO_UI;
1089
1090 int result = ::SHFileOperationW(&shfos);
1091 if (result != 0 && !IgnoreErrors)
1092 return mapWindowsError(result);
1093 return std::error_code();
1094}
1095
Zachary Turnere48ace62017-03-10 17:39:21 +00001096static void expandTildeExpr(SmallVectorImpl<char> &Path) {
1097 // Path does not begin with a tilde expression.
1098 if (Path.empty() || Path[0] != '~')
1099 return;
1100
1101 StringRef PathStr(Path.begin(), Path.size());
1102 PathStr = PathStr.drop_front();
Zachary Turner5c5091f2017-03-16 22:28:04 +00001103 StringRef Expr = PathStr.take_until([](char c) { return path::is_separator(c); });
Zachary Turnere48ace62017-03-10 17:39:21 +00001104
1105 if (!Expr.empty()) {
1106 // This is probably a ~username/ expression. Don't support this on Windows.
1107 return;
1108 }
1109
1110 SmallString<128> HomeDir;
1111 if (!path::home_directory(HomeDir)) {
1112 // For some reason we couldn't get the home directory. Just exit.
1113 return;
1114 }
1115
1116 // Overwrite the first character and insert the rest.
1117 Path[0] = HomeDir[0];
1118 Path.insert(Path.begin() + 1, HomeDir.begin() + 1, HomeDir.end());
1119}
1120
1121std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1122 bool expand_tilde) {
1123 dest.clear();
1124 if (path.isTriviallyEmpty())
1125 return std::error_code();
1126
1127 if (expand_tilde) {
1128 SmallString<128> Storage;
1129 path.toVector(Storage);
1130 expandTildeExpr(Storage);
1131 return real_path(Storage, dest, false);
1132 }
1133
1134 if (is_directory(path))
1135 return directoryRealPath(path, dest);
1136
1137 int fd;
1138 if (std::error_code EC = llvm::sys::fs::openFileForRead(path, fd, &dest))
1139 return EC;
1140 ::close(fd);
1141 return std::error_code();
1142}
1143
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +00001144} // end namespace fs
Rui Ueyama471d0c52013-09-10 19:45:51 +00001145
Peter Collingbournef7d41012014-01-31 23:46:06 +00001146namespace path {
Pawel Bylica7c1f36a2015-11-02 14:57:24 +00001147static bool getKnownFolderPath(KNOWNFOLDERID folderId,
1148 SmallVectorImpl<char> &result) {
Pawel Bylica7187e4b2015-10-16 09:08:59 +00001149 wchar_t *path = nullptr;
1150 if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK)
1151 return false;
1152
1153 bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
1154 ::CoTaskMemFree(path);
1155 return ok;
1156}
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001157
1158bool getUserCacheDir(SmallVectorImpl<char> &Result) {
1159 return getKnownFolderPath(FOLDERID_LocalAppData, Result);
1160}
Pawel Bylica7187e4b2015-10-16 09:08:59 +00001161
Peter Collingbournef7d41012014-01-31 23:46:06 +00001162bool home_directory(SmallVectorImpl<char> &result) {
Pawel Bylica7187e4b2015-10-16 09:08:59 +00001163 return getKnownFolderPath(FOLDERID_Profile, result);
Peter Collingbournef7d41012014-01-31 23:46:06 +00001164}
1165
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001166static bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {
Pawel Bylica6e680b22015-11-06 23:44:23 +00001167 SmallVector<wchar_t, 1024> Buf;
1168 size_t Size = 1024;
1169 do {
1170 Buf.reserve(Size);
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001171 Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.capacity());
Pawel Bylica6e680b22015-11-06 23:44:23 +00001172 if (Size == 0)
1173 return false;
1174
1175 // Try again with larger buffer.
1176 } while (Size > Buf.capacity());
1177 Buf.set_size(Size);
1178
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001179 return !windows::UTF16ToUTF8(Buf.data(), Size, Res);
Pawel Bylica6e680b22015-11-06 23:44:23 +00001180}
1181
1182static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001183 const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};
1184 for (auto *Env : EnvironmentVariables) {
Pawel Bylica6e680b22015-11-06 23:44:23 +00001185 if (getTempDirEnvVar(Env, Res))
1186 return true;
1187 }
1188 return false;
1189}
1190
Rafael Espindola016a6d52014-08-26 14:47:52 +00001191void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1192 (void)ErasedOnReboot;
Pawel Bylica6e680b22015-11-06 23:44:23 +00001193 Result.clear();
Rafael Espindola016a6d52014-08-26 14:47:52 +00001194
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001195 // Check whether the temporary directory is specified by an environment var.
1196 // This matches GetTempPath logic to some degree. GetTempPath is not used
1197 // directly as it cannot handle evn var longer than 130 chars on Windows 7
1198 // (fixed on Windows 8).
1199 if (getTempDirEnvVar(Result)) {
1200 assert(!Result.empty() && "Unexpected empty path");
1201 native(Result); // Some Unix-like shells use Unix path separator in $TMP.
1202 fs::make_absolute(Result); // Make it absolute if not already.
Pawel Bylica6e680b22015-11-06 23:44:23 +00001203 return;
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001204 }
Rafael Espindola016a6d52014-08-26 14:47:52 +00001205
1206 // Fall back to a system default.
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001207 const char *DefaultResult = "C:\\Temp";
Rafael Espindola016a6d52014-08-26 14:47:52 +00001208 Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
1209}
Peter Collingbournef7d41012014-01-31 23:46:06 +00001210} // end namespace path
1211
Rui Ueyama471d0c52013-09-10 19:45:51 +00001212namespace windows {
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +00001213std::error_code UTF8ToUTF16(llvm::StringRef utf8,
Rafael Espindolab4ad29b2014-06-13 02:36:09 +00001214 llvm::SmallVectorImpl<wchar_t> &utf16) {
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001215 if (!utf8.empty()) {
1216 int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
1217 utf8.size(), utf16.begin(), 0);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001218
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001219 if (len == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +00001220 return mapWindowsError(::GetLastError());
Rui Ueyama471d0c52013-09-10 19:45:51 +00001221
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001222 utf16.reserve(len + 1);
1223 utf16.set_size(len);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001224
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001225 len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
1226 utf8.size(), utf16.begin(), utf16.size());
Rui Ueyama471d0c52013-09-10 19:45:51 +00001227
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001228 if (len == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +00001229 return mapWindowsError(::GetLastError());
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001230 }
Rui Ueyama471d0c52013-09-10 19:45:51 +00001231
1232 // Make utf16 null terminated.
1233 utf16.push_back(0);
1234 utf16.pop_back();
1235
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +00001236 return std::error_code();
Rui Ueyama471d0c52013-09-10 19:45:51 +00001237}
1238
Rafael Espindola9c359662014-09-03 20:02:00 +00001239static
1240std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
1241 size_t utf16_len,
1242 llvm::SmallVectorImpl<char> &utf8) {
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001243 if (utf16_len) {
1244 // Get length.
Rafael Espindola9c359662014-09-03 20:02:00 +00001245 int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.begin(),
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001246 0, NULL, NULL);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001247
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001248 if (len == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +00001249 return mapWindowsError(::GetLastError());
Rui Ueyama471d0c52013-09-10 19:45:51 +00001250
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001251 utf8.reserve(len);
1252 utf8.set_size(len);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001253
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001254 // Now do the actual conversion.
Rafael Espindola9c359662014-09-03 20:02:00 +00001255 len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.data(),
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001256 utf8.size(), NULL, NULL);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001257
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001258 if (len == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +00001259 return mapWindowsError(::GetLastError());
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001260 }
Rui Ueyama471d0c52013-09-10 19:45:51 +00001261
1262 // Make utf8 null terminated.
1263 utf8.push_back(0);
1264 utf8.pop_back();
1265
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +00001266 return std::error_code();
Rui Ueyama471d0c52013-09-10 19:45:51 +00001267}
Rafael Espindola9c359662014-09-03 20:02:00 +00001268
1269std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
1270 llvm::SmallVectorImpl<char> &utf8) {
1271 return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
1272}
1273
1274std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
1275 llvm::SmallVectorImpl<char> &utf8) {
1276 return UTF16ToCodePage(CP_ACP, utf16, utf16_len, utf8);
1277}
Taewook Ohd9153272016-06-13 15:54:56 +00001278
Rui Ueyama471d0c52013-09-10 19:45:51 +00001279} // end namespace windows
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001280} // end namespace sys
1281} // end namespace llvm