blob: d34aa763124c9aaced0f36459df1564979b44ba7 [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"
Zachary Turnerb44d7a02018-06-01 22:23:46 +000020#include "llvm/Support/ConvertUTF.h"
Rafael Espindola5c4f8292014-06-11 19:05:50 +000021#include "llvm/Support/WindowsError.h"
Michael J. Spencerc20a0322010-12-03 17:54:07 +000022#include <fcntl.h>
Michael J. Spencer45710402010-12-03 01:21:28 +000023#include <io.h>
Michael J. Spencerc20a0322010-12-03 17:54:07 +000024#include <sys/stat.h>
25#include <sys/types.h>
Michael J. Spencerebad2f92010-11-29 22:28:51 +000026
NAKAMURA Takumi04d39d72014-02-12 11:50:22 +000027// These two headers must be included last, and make sure shlobj is required
28// after Windows.h to make sure it picks up our definition of _WIN32_WINNT
Reid Klecknerd59e2fa2014-02-12 21:26:20 +000029#include "WindowsSupport.h"
Zachary Turner260bda32017-03-08 22:49:32 +000030#include <shellapi.h>
NAKAMURA Takumi04d39d72014-02-12 11:50:22 +000031#include <shlobj.h>
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000032
Michael J. Spenceref2284f2012-08-15 19:05:47 +000033#undef max
34
Michael J. Spencer60252472010-12-03 18:03:28 +000035// MinGW doesn't define this.
Michael J. Spencer521c3212010-12-03 18:04:11 +000036#ifndef _ERRNO_T_DEFINED
37#define _ERRNO_T_DEFINED
38typedef int errno_t;
Michael J. Spencer60252472010-12-03 18:03:28 +000039#endif
40
Reid Kleckner11da0042013-08-07 20:19:31 +000041#ifdef _MSC_VER
42# pragma comment(lib, "advapi32.lib") // This provides CryptAcquireContextW.
Reid Kleckner304af562016-01-12 18:33:49 +000043# pragma comment(lib, "ole32.lib") // This provides CoTaskMemFree
Reid Kleckner11da0042013-08-07 20:19:31 +000044#endif
45
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000046using namespace llvm;
47
Rui Ueyama471d0c52013-09-10 19:45:51 +000048using llvm::sys::windows::UTF8ToUTF16;
Aaron Smith8a5ea612018-04-07 00:32:59 +000049using llvm::sys::windows::CurCPToUTF16;
Rui Ueyama471d0c52013-09-10 19:45:51 +000050using llvm::sys::windows::UTF16ToUTF8;
Paul Robinsonc38deee2014-11-24 18:05:29 +000051using llvm::sys::path::widenPath;
Rui Ueyama471d0c52013-09-10 19:45:51 +000052
Rafael Espindola37b012d2014-02-23 15:16:03 +000053static bool is_separator(const wchar_t value) {
54 switch (value) {
55 case L'\\':
56 case L'/':
57 return true;
58 default:
59 return false;
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +000060 }
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000061}
62
Paul Robinsonc38deee2014-11-24 18:05:29 +000063namespace llvm {
64namespace sys {
65namespace path {
66
Aaron Smith02caafd72018-04-18 15:26:26 +000067// Convert a UTF-8 path to UTF-16. Also, if the absolute equivalent of the
Paul Robinsond9c4a9a2014-11-13 00:12:14 +000068// path is longer than CreateDirectory can tolerate, make it absolute and
69// prefixed by '\\?\'.
Paul Robinsonc38deee2014-11-24 18:05:29 +000070std::error_code widenPath(const Twine &Path8,
71 SmallVectorImpl<wchar_t> &Path16) {
Paul Robinsond9c4a9a2014-11-13 00:12:14 +000072 const size_t MaxDirLen = MAX_PATH - 12; // Must leave room for 8.3 filename.
73
74 // Several operations would convert Path8 to SmallString; more efficient to
75 // do it once up front.
Aaron Smith02caafd72018-04-18 15:26:26 +000076 SmallString<128> Path8Str;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +000077 Path8.toVector(Path8Str);
78
79 // If we made this path absolute, how much longer would it get?
80 size_t CurPathLen;
81 if (llvm::sys::path::is_absolute(Twine(Path8Str)))
82 CurPathLen = 0; // No contribution from current_path needed.
83 else {
84 CurPathLen = ::GetCurrentDirectoryW(0, NULL);
85 if (CurPathLen == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +000086 return mapWindowsError(::GetLastError());
Paul Robinsond9c4a9a2014-11-13 00:12:14 +000087 }
88
89 // Would the absolute path be longer than our limit?
90 if ((Path8Str.size() + CurPathLen) >= MaxDirLen &&
91 !Path8Str.startswith("\\\\?\\")) {
92 SmallString<2*MAX_PATH> FullPath("\\\\?\\");
93 if (CurPathLen) {
94 SmallString<80> CurPath;
95 if (std::error_code EC = llvm::sys::fs::current_path(CurPath))
96 return EC;
97 FullPath.append(CurPath);
98 }
Pirama Arumuga Nainar3d48bb52017-08-21 20:49:44 +000099 // Traverse the requested path, canonicalizing . and .. (because the \\?\
100 // prefix is documented to treat them as real components). Ignore
101 // separators, which can be returned from the iterator if the path has a
102 // drive name. We don't need to call native() on the result since append()
103 // always attaches preferred_separator.
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000104 for (llvm::sys::path::const_iterator I = llvm::sys::path::begin(Path8Str),
105 E = llvm::sys::path::end(Path8Str);
106 I != E; ++I) {
Pirama Arumuga Nainar3d48bb52017-08-21 20:49:44 +0000107 if (I->size() == 1 && is_separator((*I)[0]))
108 continue;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000109 if (I->size() == 1 && *I == ".")
110 continue;
111 if (I->size() == 2 && *I == "..")
112 llvm::sys::path::remove_filename(FullPath);
113 else
114 llvm::sys::path::append(FullPath, *I);
115 }
Aaron Smith02caafd72018-04-18 15:26:26 +0000116 return UTF8ToUTF16(FullPath, Path16);
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000117 }
118
Aaron Smith02caafd72018-04-18 15:26:26 +0000119 // Just use the caller's original path.
120 return UTF8ToUTF16(Path8Str, Path16);
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000121}
Paul Robinsonc38deee2014-11-24 18:05:29 +0000122} // end namespace path
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000123
Michael J. Spencer20daa282010-12-07 01:22:31 +0000124namespace fs {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000125
Zachary Turner63db25b2018-06-04 19:38:11 +0000126const file_t kInvalidFile = INVALID_HANDLE_VALUE;
127
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000128std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
David Majnemer17a44962013-10-07 09:52:36 +0000129 SmallVector<wchar_t, MAX_PATH> PathName;
130 DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
131
132 // A zero return value indicates a failure other than insufficient space.
133 if (Size == 0)
134 return "";
135
136 // Insufficient space is determined by a return value equal to the size of
137 // the buffer passed in.
138 if (Size == PathName.capacity())
139 return "";
140
141 // On success, GetModuleFileNameW returns the number of characters written to
142 // the buffer not including the NULL terminator.
143 PathName.set_size(Size);
144
145 // Convert the result from UTF-16 to UTF-8.
146 SmallVector<char, MAX_PATH> PathNameUTF8;
147 if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
148 return "";
149
150 return std::string(PathNameUTF8.data());
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000151}
152
Rafael Espindolad1230992013-07-29 21:55:38 +0000153UniqueID file_status::getUniqueID() const {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000154 // The file is uniquely identified by the volume serial number along
155 // with the 64-bit file identifier.
156 uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
157 static_cast<uint64_t>(FileIndexLow);
158
159 return UniqueID(VolumeSerialNumber, FileID);
160}
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000161
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000162ErrorOr<space_info> disk_space(const Twine &Path) {
163 ULARGE_INTEGER Avail, Total, Free;
164 if (!::GetDiskFreeSpaceExA(Path.str().c_str(), &Avail, &Total, &Free))
165 return mapWindowsError(::GetLastError());
166 space_info SpaceInfo;
167 SpaceInfo.capacity =
168 (static_cast<uint64_t>(Total.HighPart) << 32) + Total.LowPart;
Mehdi Amini64719152016-04-01 00:52:05 +0000169 SpaceInfo.free = (static_cast<uint64_t>(Free.HighPart) << 32) + Free.LowPart;
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000170 SpaceInfo.available =
171 (static_cast<uint64_t>(Avail.HighPart) << 32) + Avail.LowPart;
172 return SpaceInfo;
173}
174
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000175TimePoint<> basic_file_status::getLastAccessedTime() const {
Pavel Labath757ca882016-10-24 10:59:17 +0000176 FILETIME Time;
177 Time.dwLowDateTime = LastAccessedTimeLow;
178 Time.dwHighDateTime = LastAccessedTimeHigh;
179 return toTimePoint(Time);
Mehdi Amini1e39ef32016-03-25 07:30:21 +0000180}
181
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000182TimePoint<> basic_file_status::getLastModificationTime() const {
Pavel Labath757ca882016-10-24 10:59:17 +0000183 FILETIME Time;
184 Time.dwLowDateTime = LastWriteTimeLow;
185 Time.dwHighDateTime = LastWriteTimeHigh;
186 return toTimePoint(Time);
Rafael Espindoladb5d8fe2013-06-20 18:42:04 +0000187}
188
Zachary Turner5821a3b2017-03-20 23:55:20 +0000189uint32_t file_status::getLinkCount() const {
190 return NumLinks;
191}
192
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000193std::error_code current_path(SmallVectorImpl<char> &result) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000194 SmallVector<wchar_t, MAX_PATH> cur_path;
195 DWORD len = MAX_PATH;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000196
David Majnemer61eae2e2013-10-07 01:00:07 +0000197 do {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000198 cur_path.reserve(len);
David Majnemer61eae2e2013-10-07 01:00:07 +0000199 len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000200
David Majnemer61eae2e2013-10-07 01:00:07 +0000201 // A zero return value indicates a failure other than insufficient space.
202 if (len == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000203 return mapWindowsError(::GetLastError());
David Majnemer61eae2e2013-10-07 01:00:07 +0000204
205 // If there's insufficient space, the len returned is larger than the len
206 // given.
207 } while (len > cur_path.capacity());
208
209 // On success, GetCurrentDirectoryW returns the number of characters not
210 // including the null-terminator.
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000211 cur_path.set_size(len);
Aaron Ballmanb16cf532013-08-16 17:53:28 +0000212 return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000213}
214
Pavel Labath2f096092017-01-24 10:32:03 +0000215std::error_code set_current_path(const Twine &path) {
216 // Convert to utf-16.
217 SmallVector<wchar_t, 128> wide_path;
218 if (std::error_code ec = widenPath(path, wide_path))
219 return ec;
220
221 if (!::SetCurrentDirectoryW(wide_path.begin()))
222 return mapWindowsError(::GetLastError());
223
224 return std::error_code();
225}
226
Frederic Riss6b9396c2015-08-06 21:04:55 +0000227std::error_code create_directory(const Twine &path, bool IgnoreExisting,
228 perms Perms) {
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000229 SmallVector<wchar_t, 128> path_utf16;
230
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000231 if (std::error_code ec = widenPath(path, path_utf16))
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000232 return ec;
233
234 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000235 DWORD LastError = ::GetLastError();
236 if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000237 return mapWindowsError(LastError);
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000238 }
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000239
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000240 return std::error_code();
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000241}
242
Rafael Espindola83f858e2014-03-11 18:40:24 +0000243// We can't use symbolic links for windows.
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000244std::error_code create_link(const Twine &to, const Twine &from) {
Michael J. Spencere0c45602010-12-03 05:58:41 +0000245 // Convert to utf-16.
246 SmallVector<wchar_t, 128> wide_from;
247 SmallVector<wchar_t, 128> wide_to;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000248 if (std::error_code ec = widenPath(from, wide_from))
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000249 return ec;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000250 if (std::error_code ec = widenPath(to, wide_to))
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000251 return ec;
Michael J. Spencere0c45602010-12-03 05:58:41 +0000252
253 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
Yaron Kerenf8e65172015-05-04 04:48:10 +0000254 return mapWindowsError(::GetLastError());
Michael J. Spencere0c45602010-12-03 05:58:41 +0000255
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000256 return std::error_code();
Michael J. Spencere0c45602010-12-03 05:58:41 +0000257}
258
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000259std::error_code create_hard_link(const Twine &to, const Twine &from) {
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +0000260 return create_link(to, from);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000261}
262
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000263std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000264 SmallVector<wchar_t, 128> path_utf16;
265
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
Peter Collingbourne0f9e8892017-10-10 19:39:46 +0000269 // We don't know whether this is a file or a directory, and remove() can
270 // accept both. The usual way to delete a file or directory is to use one of
271 // the DeleteFile or RemoveDirectory functions, but that requires you to know
272 // which one it is. We could stat() the file to determine that, but that would
273 // cost us additional system calls, which can be slow in a directory
274 // containing a large number of files. So instead we call CreateFile directly.
275 // The important part is the FILE_FLAG_DELETE_ON_CLOSE flag, which causes the
276 // file to be deleted once it is closed. We also use the flags
277 // FILE_FLAG_BACKUP_SEMANTICS (which allows us to open directories), and
278 // FILE_FLAG_OPEN_REPARSE_POINT (don't follow symlinks).
279 ScopedFileHandle h(::CreateFileW(
280 c_str(path_utf16), DELETE,
281 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
282 OPEN_EXISTING,
283 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS |
284 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_DELETE_ON_CLOSE,
285 NULL));
286 if (!h) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000287 std::error_code EC = mapWindowsError(::GetLastError());
Rafael Espindola2a826e42014-06-13 17:20:48 +0000288 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000289 return EC;
290 }
Peter Collingbourne0f9e8892017-10-10 19:39:46 +0000291
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000292 return std::error_code();
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000293}
294
Zachary Turner392ed9d2017-02-21 20:55:47 +0000295static std::error_code is_local_internal(SmallVectorImpl<wchar_t> &Path,
296 bool &Result) {
297 SmallVector<wchar_t, 128> VolumePath;
298 size_t Len = 128;
299 while (true) {
300 VolumePath.resize(Len);
301 BOOL Success =
302 ::GetVolumePathNameW(Path.data(), VolumePath.data(), VolumePath.size());
303
304 if (Success)
305 break;
306
307 DWORD Err = ::GetLastError();
308 if (Err != ERROR_INSUFFICIENT_BUFFER)
309 return mapWindowsError(Err);
310
311 Len *= 2;
312 }
313 // If the output buffer has exactly enough space for the path name, but not
314 // the null terminator, it will leave the output unterminated. Push a null
315 // terminator onto the end to ensure that this never happens.
316 VolumePath.push_back(L'\0');
317 VolumePath.set_size(wcslen(VolumePath.data()));
318 const wchar_t *P = VolumePath.data();
319
320 UINT Type = ::GetDriveTypeW(P);
321 switch (Type) {
322 case DRIVE_FIXED:
323 Result = true;
324 return std::error_code();
325 case DRIVE_REMOTE:
326 case DRIVE_CDROM:
327 case DRIVE_RAMDISK:
328 case DRIVE_REMOVABLE:
329 Result = false;
330 return std::error_code();
331 default:
332 return make_error_code(errc::no_such_file_or_directory);
333 }
334 llvm_unreachable("Unreachable!");
335}
336
337std::error_code is_local(const Twine &path, bool &result) {
338 if (!llvm::sys::fs::exists(path) || !llvm::sys::path::has_root_path(path))
339 return make_error_code(errc::no_such_file_or_directory);
340
341 SmallString<128> Storage;
342 StringRef P = path.toStringRef(Storage);
343
344 // Convert to utf-16.
345 SmallVector<wchar_t, 128> WidePath;
346 if (std::error_code ec = widenPath(P, WidePath))
347 return ec;
348 return is_local_internal(WidePath, result);
349}
350
Rafael Espindola041299e2017-11-18 02:05:59 +0000351static std::error_code realPathFromHandle(HANDLE H,
Rafael Espindola8dc0e102017-11-18 02:12:53 +0000352 SmallVectorImpl<wchar_t> &Buffer) {
353 DWORD CountChars = ::GetFinalPathNameByHandleW(
354 H, Buffer.begin(), Buffer.capacity() - 1, FILE_NAME_NORMALIZED);
355 if (CountChars > Buffer.capacity()) {
356 // The buffer wasn't big enough, try again. In this case the return value
357 // *does* indicate the size of the null terminator.
358 Buffer.reserve(CountChars);
359 CountChars = ::GetFinalPathNameByHandleW(
360 H, Buffer.data(), Buffer.capacity() - 1, FILE_NAME_NORMALIZED);
361 }
362 if (CountChars == 0)
363 return mapWindowsError(GetLastError());
364 Buffer.set_size(CountChars);
365 return std::error_code();
366}
367
368static std::error_code realPathFromHandle(HANDLE H,
369 SmallVectorImpl<char> &RealPath) {
370 RealPath.clear();
371 SmallVector<wchar_t, MAX_PATH> Buffer;
372 if (std::error_code EC = realPathFromHandle(H, Buffer))
373 return EC;
374
375 const wchar_t *Data = Buffer.data();
376 DWORD CountChars = Buffer.size();
377 if (CountChars >= 4) {
378 if (0 == ::memcmp(Data, L"\\\\?\\", 8)) {
379 CountChars -= 4;
380 Data += 4;
381 }
382 }
383
384 // Convert the result from UTF-16 to UTF-8.
385 return UTF16ToUTF8(Data, CountChars, RealPath);
386}
Rafael Espindola041299e2017-11-18 02:05:59 +0000387
Zachary Turner392ed9d2017-02-21 20:55:47 +0000388std::error_code is_local(int FD, bool &Result) {
389 SmallVector<wchar_t, 128> FinalPath;
390 HANDLE Handle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
391
Rafael Espindola041299e2017-11-18 02:05:59 +0000392 if (std::error_code EC = realPathFromHandle(Handle, FinalPath))
393 return EC;
Zachary Turner392ed9d2017-02-21 20:55:47 +0000394
395 return is_local_internal(FinalPath, Result);
396}
397
Rafael Espindola20569e92017-12-05 16:40:56 +0000398static std::error_code setDeleteDisposition(HANDLE Handle, bool Delete) {
399 FILE_DISPOSITION_INFO Disposition;
400 Disposition.DeleteFile = Delete;
401 if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
402 sizeof(Disposition)))
403 return mapWindowsError(::GetLastError());
404 return std::error_code();
405}
406
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000407static std::error_code rename_internal(HANDLE FromHandle, const Twine &To,
408 bool ReplaceIfExists) {
409 SmallVector<wchar_t, 0> ToWide;
410 if (auto EC = widenPath(To, ToWide))
411 return EC;
412
413 std::vector<char> RenameInfoBuf(sizeof(FILE_RENAME_INFO) - sizeof(wchar_t) +
414 (ToWide.size() * sizeof(wchar_t)));
415 FILE_RENAME_INFO &RenameInfo =
416 *reinterpret_cast<FILE_RENAME_INFO *>(RenameInfoBuf.data());
417 RenameInfo.ReplaceIfExists = ReplaceIfExists;
418 RenameInfo.RootDirectory = 0;
Shoaib Meenai96929fd2018-12-13 00:08:25 +0000419 RenameInfo.FileNameLength = ToWide.size() * sizeof(wchar_t);
Adrian McCarthye6275c62017-10-09 17:50:01 +0000420 std::copy(ToWide.begin(), ToWide.end(), &RenameInfo.FileName[0]);
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000421
Hans Wennborg477c9742017-10-12 17:38:22 +0000422 SetLastError(ERROR_SUCCESS);
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000423 if (!SetFileInformationByHandle(FromHandle, FileRenameInfo, &RenameInfo,
Hans Wennborg477c9742017-10-12 17:38:22 +0000424 RenameInfoBuf.size())) {
425 unsigned Error = GetLastError();
426 if (Error == ERROR_SUCCESS)
427 Error = ERROR_CALL_NOT_IMPLEMENTED; // Wine doesn't always set error code.
428 return mapWindowsError(Error);
429 }
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000430
431 return std::error_code();
432}
433
Rafael Espindola5908aff2017-11-21 01:52:44 +0000434static std::error_code rename_handle(HANDLE FromHandle, const Twine &To) {
435 SmallVector<wchar_t, 128> WideTo;
436 if (std::error_code EC = widenPath(To, WideTo))
437 return EC;
438
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000439 // We normally expect this loop to succeed after a few iterations. If it
440 // requires more than 200 tries, it's more likely that the failures are due to
441 // a true error, so stop trying.
442 for (unsigned Retry = 0; Retry != 200; ++Retry) {
443 auto EC = rename_internal(FromHandle, To, true);
Hans Wennborg17701ab2017-10-11 22:04:14 +0000444
445 if (EC ==
446 std::error_code(ERROR_CALL_NOT_IMPLEMENTED, std::system_category())) {
447 // Wine doesn't support SetFileInformationByHandle in rename_internal.
448 // Fall back to MoveFileEx.
Rafael Espindola5908aff2017-11-21 01:52:44 +0000449 SmallVector<wchar_t, MAX_PATH> WideFrom;
450 if (std::error_code EC2 = realPathFromHandle(FromHandle, WideFrom))
451 return EC2;
Hans Wennborg17701ab2017-10-11 22:04:14 +0000452 if (::MoveFileExW(WideFrom.begin(), WideTo.begin(),
Jeremy Morse01940652018-08-03 10:13:35 +0000453 MOVEFILE_REPLACE_EXISTING))
Hans Wennborg17701ab2017-10-11 22:04:14 +0000454 return std::error_code();
455 return mapWindowsError(GetLastError());
456 }
457
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000458 if (!EC || EC != errc::permission_denied)
459 return EC;
Greg Bedwell7f68a712015-10-12 15:11:47 +0000460
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000461 // The destination file probably exists and is currently open in another
462 // process, either because the file was opened without FILE_SHARE_DELETE or
463 // it is mapped into memory (e.g. using MemoryBuffer). Rename it in order to
464 // move it out of the way of the source file. Use FILE_FLAG_DELETE_ON_CLOSE
465 // to arrange for the destination file to be deleted when the other process
466 // closes it.
467 ScopedFileHandle ToHandle(
468 ::CreateFileW(WideTo.begin(), GENERIC_READ | DELETE,
469 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
470 NULL, OPEN_EXISTING,
471 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL));
472 if (!ToHandle) {
473 auto EC = mapWindowsError(GetLastError());
474 // Another process might have raced with us and moved the existing file
475 // out of the way before we had a chance to open it. If that happens, try
476 // to rename the source file again.
477 if (EC == errc::no_such_file_or_directory)
Sunil Srivastava34fce932016-03-25 23:41:28 +0000478 continue;
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000479 return EC;
Sunil Srivastava34fce932016-03-25 23:41:28 +0000480 }
Greg Bedwell7f68a712015-10-12 15:11:47 +0000481
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000482 BY_HANDLE_FILE_INFORMATION FI;
483 if (!GetFileInformationByHandle(ToHandle, &FI))
484 return mapWindowsError(GetLastError());
Greg Bedwell7f68a712015-10-12 15:11:47 +0000485
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000486 // Try to find a unique new name for the destination file.
487 for (unsigned UniqueId = 0; UniqueId != 200; ++UniqueId) {
488 std::string TmpFilename = (To + ".tmp" + utostr(UniqueId)).str();
489 if (auto EC = rename_internal(ToHandle, TmpFilename, false)) {
490 if (EC == errc::file_exists || EC == errc::permission_denied) {
491 // Again, another process might have raced with us and moved the file
492 // before we could move it. Check whether this is the case, as it
493 // might have caused the permission denied error. If that was the
494 // case, we don't need to move it ourselves.
495 ScopedFileHandle ToHandle2(::CreateFileW(
496 WideTo.begin(), 0,
497 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
498 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
499 if (!ToHandle2) {
500 auto EC = mapWindowsError(GetLastError());
501 if (EC == errc::no_such_file_or_directory)
502 break;
503 return EC;
504 }
505 BY_HANDLE_FILE_INFORMATION FI2;
506 if (!GetFileInformationByHandle(ToHandle2, &FI2))
507 return mapWindowsError(GetLastError());
508 if (FI.nFileIndexHigh != FI2.nFileIndexHigh ||
509 FI.nFileIndexLow != FI2.nFileIndexLow ||
510 FI.dwVolumeSerialNumber != FI2.dwVolumeSerialNumber)
511 break;
512 continue;
513 }
514 return EC;
515 }
516 break;
517 }
518
519 // Okay, the old destination file has probably been moved out of the way at
520 // this point, so try to rename the source file again. Still, another
521 // process might have raced with us to create and open the destination
522 // file, so we need to keep doing this until we succeed.
NAKAMURA Takumi3b7f9952012-05-08 14:31:46 +0000523 }
Michael J. Spencer409f5562010-12-03 17:53:55 +0000524
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000525 // The most likely root cause.
526 return errc::permission_denied;
Michael J. Spencer409f5562010-12-03 17:53:55 +0000527}
528
Rafael Espindola3ecd2042017-11-28 01:41:22 +0000529static std::error_code rename_fd(int FromFD, const Twine &To) {
530 HANDLE FromHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FromFD));
531 return rename_handle(FromHandle, To);
532}
533
Rafael Espindola811d5e82017-11-21 05:35:45 +0000534std::error_code rename(const Twine &From, const Twine &To) {
535 // Convert to utf-16.
536 SmallVector<wchar_t, 128> WideFrom;
537 if (std::error_code EC = widenPath(From, WideFrom))
538 return EC;
539
540 ScopedFileHandle FromHandle;
541 // Retry this a few times to defeat badly behaved file system scanners.
542 for (unsigned Retry = 0; Retry != 200; ++Retry) {
543 if (Retry != 0)
544 ::Sleep(10);
545 FromHandle =
546 ::CreateFileW(WideFrom.begin(), GENERIC_READ | DELETE,
547 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
548 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
549 if (FromHandle)
550 break;
551 }
552 if (!FromHandle)
553 return mapWindowsError(GetLastError());
554
555 return rename_handle(FromHandle, To);
556}
557
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000558std::error_code resize_file(int FD, uint64_t Size) {
Michael J. Spencerca242f22010-12-03 18:48:56 +0000559#ifdef HAVE__CHSIZE_S
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000560 errno_t error = ::_chsize_s(FD, Size);
Michael J. Spencerca242f22010-12-03 18:48:56 +0000561#else
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000562 errno_t error = ::_chsize(FD, Size);
Michael J. Spencerca242f22010-12-03 18:48:56 +0000563#endif
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000564 return std::error_code(error, std::generic_category());
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000565}
566
Rafael Espindola281f23a2014-09-11 20:30:02 +0000567std::error_code access(const Twine &Path, AccessMode Mode) {
Rafael Espindola281f23a2014-09-11 20:30:02 +0000568 SmallVector<wchar_t, 128> PathUtf16;
Michael J. Spencer45710402010-12-03 01:21:28 +0000569
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000570 if (std::error_code EC = widenPath(Path, PathUtf16))
Rafael Espindola281f23a2014-09-11 20:30:02 +0000571 return EC;
Michael J. Spencer45710402010-12-03 01:21:28 +0000572
Rafael Espindola281f23a2014-09-11 20:30:02 +0000573 DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
Michael J. Spencer45710402010-12-03 01:21:28 +0000574
Rafael Espindola281f23a2014-09-11 20:30:02 +0000575 if (Attributes == INVALID_FILE_ATTRIBUTES) {
Michael J. Spencer45710402010-12-03 01:21:28 +0000576 // See if the file didn't actually exist.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000577 DWORD LastError = ::GetLastError();
578 if (LastError != ERROR_FILE_NOT_FOUND &&
579 LastError != ERROR_PATH_NOT_FOUND)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000580 return mapWindowsError(LastError);
Rafael Espindola281f23a2014-09-11 20:30:02 +0000581 return errc::no_such_file_or_directory;
582 }
583
584 if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
585 return errc::permission_denied;
586
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000587 return std::error_code();
Michael J. Spencer45710402010-12-03 01:21:28 +0000588}
589
Reid Kleckner89d4b1a2015-09-10 23:28:06 +0000590bool can_execute(const Twine &Path) {
591 return !access(Path, AccessMode::Execute) ||
592 !access(Path + ".exe", AccessMode::Execute);
593}
594
Michael J. Spencer203d7802011-12-12 06:04:28 +0000595bool equivalent(file_status A, file_status B) {
596 assert(status_known(A) && status_known(B));
Mehdi Amini1e39ef32016-03-25 07:30:21 +0000597 return A.FileIndexHigh == B.FileIndexHigh &&
598 A.FileIndexLow == B.FileIndexLow &&
599 A.FileSizeHigh == B.FileSizeHigh &&
600 A.FileSizeLow == B.FileSizeLow &&
601 A.LastAccessedTimeHigh == B.LastAccessedTimeHigh &&
602 A.LastAccessedTimeLow == B.LastAccessedTimeLow &&
603 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
604 A.LastWriteTimeLow == B.LastWriteTimeLow &&
605 A.VolumeSerialNumber == B.VolumeSerialNumber;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000606}
607
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000608std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000609 file_status fsA, fsB;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000610 if (std::error_code ec = status(A, fsA))
611 return ec;
612 if (std::error_code ec = status(B, fsB))
613 return ec;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000614 result = equivalent(fsA, fsB);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000615 return std::error_code();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000616}
617
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000618static bool isReservedName(StringRef path) {
619 // This list of reserved names comes from MSDN, at:
620 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
Craig Topper26260942015-10-18 05:15:34 +0000621 static const char *const sReservedNames[] = { "nul", "con", "prn", "aux",
622 "com1", "com2", "com3", "com4",
623 "com5", "com6", "com7", "com8",
624 "com9", "lpt1", "lpt2", "lpt3",
625 "lpt4", "lpt5", "lpt6", "lpt7",
626 "lpt8", "lpt9" };
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000627
628 // First, check to see if this is a device namespace, which always
629 // starts with \\.\, since device namespaces are not legal file paths.
630 if (path.startswith("\\\\.\\"))
631 return true;
632
Douglas Yung091d8fd2016-05-03 00:12:59 +0000633 // Then compare against the list of ancient reserved names.
Craig Topper58713212013-07-15 04:27:47 +0000634 for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000635 if (path.equals_lower(sReservedNames[i]))
636 return true;
637 }
638
639 // The path isn't what we consider reserved.
640 return false;
641}
642
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000643static file_type file_type_from_attrs(DWORD Attrs) {
644 return (Attrs & FILE_ATTRIBUTE_DIRECTORY) ? file_type::directory_file
645 : file_type::regular_file;
646}
647
648static perms perms_from_attrs(DWORD Attrs) {
649 return (Attrs & FILE_ATTRIBUTE_READONLY) ? (all_read | all_exe) : all_all;
650}
651
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000652static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000653 if (FileHandle == INVALID_HANDLE_VALUE)
654 goto handle_status_error;
655
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000656 switch (::GetFileType(FileHandle)) {
657 default:
Rafael Espindola81177c52013-07-18 18:42:52 +0000658 llvm_unreachable("Don't know anything about this file type");
659 case FILE_TYPE_UNKNOWN: {
660 DWORD Err = ::GetLastError();
661 if (Err != NO_ERROR)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000662 return mapWindowsError(Err);
Rafael Espindola81177c52013-07-18 18:42:52 +0000663 Result = file_status(file_type::type_unknown);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000664 return std::error_code();
Rafael Espindola81177c52013-07-18 18:42:52 +0000665 }
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000666 case FILE_TYPE_DISK:
667 break;
668 case FILE_TYPE_CHAR:
669 Result = file_status(file_type::character_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000670 return std::error_code();
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000671 case FILE_TYPE_PIPE:
672 Result = file_status(file_type::fifo_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000673 return std::error_code();
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000674 }
675
Rafael Espindola77021c92013-07-16 03:20:13 +0000676 BY_HANDLE_FILE_INFORMATION Info;
677 if (!::GetFileInformationByHandle(FileHandle, &Info))
678 goto handle_status_error;
679
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000680 Result = file_status(
681 file_type_from_attrs(Info.dwFileAttributes),
682 perms_from_attrs(Info.dwFileAttributes), Info.nNumberOfLinks,
683 Info.ftLastAccessTime.dwHighDateTime, Info.ftLastAccessTime.dwLowDateTime,
684 Info.ftLastWriteTime.dwHighDateTime, Info.ftLastWriteTime.dwLowDateTime,
685 Info.dwVolumeSerialNumber, Info.nFileSizeHigh, Info.nFileSizeLow,
686 Info.nFileIndexHigh, Info.nFileIndexLow);
687 return std::error_code();
Aaron Ballman345012d2017-03-13 12:24:51 +0000688
Rafael Espindola77021c92013-07-16 03:20:13 +0000689handle_status_error:
Rafael Espindolaa813d602014-06-11 03:58:34 +0000690 DWORD LastError = ::GetLastError();
691 if (LastError == ERROR_FILE_NOT_FOUND ||
692 LastError == ERROR_PATH_NOT_FOUND)
Rafael Espindola77021c92013-07-16 03:20:13 +0000693 Result = file_status(file_type::file_not_found);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000694 else if (LastError == ERROR_SHARING_VIOLATION)
Rafael Espindola77021c92013-07-16 03:20:13 +0000695 Result = file_status(file_type::type_unknown);
Rafael Espindola107b74c2013-07-31 00:10:25 +0000696 else
Rafael Espindola77021c92013-07-16 03:20:13 +0000697 Result = file_status(file_type::status_error);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000698 return mapWindowsError(LastError);
Rafael Espindola77021c92013-07-16 03:20:13 +0000699}
700
Zachary Turner82dd5422017-03-07 16:10:10 +0000701std::error_code status(const Twine &path, file_status &result, bool Follow) {
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000702 SmallString<128> path_storage;
703 SmallVector<wchar_t, 128> path_utf16;
704
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000705 StringRef path8 = path.toStringRef(path_storage);
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000706 if (isReservedName(path8)) {
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000707 result = file_status(file_type::character_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000708 return std::error_code();
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000709 }
710
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000711 if (std::error_code ec = widenPath(path8, path_utf16))
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000712 return ec;
713
714 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
715 if (attr == INVALID_FILE_ATTRIBUTES)
Rafael Espindola77021c92013-07-16 03:20:13 +0000716 return getStatus(INVALID_HANDLE_VALUE, result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000717
Zachary Turner82dd5422017-03-07 16:10:10 +0000718 DWORD Flags = FILE_FLAG_BACKUP_SEMANTICS;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000719 // Handle reparse points.
Zachary Turner82dd5422017-03-07 16:10:10 +0000720 if (!Follow && (attr & FILE_ATTRIBUTE_REPARSE_POINT))
721 Flags |= FILE_FLAG_OPEN_REPARSE_POINT;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000722
Rafael Espindolaa5932af2013-07-30 20:25:53 +0000723 ScopedFileHandle h(
724 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
Michael J. Spencer203d7802011-12-12 06:04:28 +0000725 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
Zachary Turner82dd5422017-03-07 16:10:10 +0000726 NULL, OPEN_EXISTING, Flags, 0));
727 if (!h)
728 return getStatus(INVALID_HANDLE_VALUE, result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000729
Zachary Turner82dd5422017-03-07 16:10:10 +0000730 return getStatus(h, result);
Rafael Espindola77021c92013-07-16 03:20:13 +0000731}
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000732
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000733std::error_code status(int FD, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000734 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
Aaron Ballman345012d2017-03-13 12:24:51 +0000735 return getStatus(FileHandle, Result);
736}
737
James Henderson566fdf42017-03-16 11:22:09 +0000738std::error_code setPermissions(const Twine &Path, perms Permissions) {
739 SmallVector<wchar_t, 128> PathUTF16;
740 if (std::error_code EC = widenPath(Path, PathUTF16))
741 return EC;
742
743 DWORD Attributes = ::GetFileAttributesW(PathUTF16.begin());
744 if (Attributes == INVALID_FILE_ATTRIBUTES)
745 return mapWindowsError(GetLastError());
746
747 // There are many Windows file attributes that are not to do with the file
748 // permissions (e.g. FILE_ATTRIBUTE_HIDDEN). We need to be careful to preserve
749 // them.
750 if (Permissions & all_write) {
751 Attributes &= ~FILE_ATTRIBUTE_READONLY;
752 if (Attributes == 0)
753 // FILE_ATTRIBUTE_NORMAL indicates no other attributes are set.
754 Attributes |= FILE_ATTRIBUTE_NORMAL;
755 }
756 else {
757 Attributes |= FILE_ATTRIBUTE_READONLY;
758 // FILE_ATTRIBUTE_NORMAL is not compatible with any other attributes, so
759 // remove it, if it is present.
760 Attributes &= ~FILE_ATTRIBUTE_NORMAL;
761 }
762
763 if (!::SetFileAttributesW(PathUTF16.begin(), Attributes))
764 return mapWindowsError(GetLastError());
765
766 return std::error_code();
767}
768
Jordan Rupprecht97ea4852018-08-13 23:03:45 +0000769std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
770 TimePoint<> ModificationTime) {
771 FILETIME AccessFT = toFILETIME(AccessTime);
772 FILETIME ModifyFT = toFILETIME(ModificationTime);
Aaron Ballman345012d2017-03-13 12:24:51 +0000773 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
Jordan Rupprecht97ea4852018-08-13 23:03:45 +0000774 if (!SetFileTime(FileHandle, NULL, &AccessFT, &ModifyFT))
Yaron Kerenf8e65172015-05-04 04:48:10 +0000775 return mapWindowsError(::GetLastError());
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000776 return std::error_code();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000777}
Nick Kledzik18497e92012-06-20 00:28:54 +0000778
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000779std::error_code mapped_file_region::init(int FD, uint64_t Offset,
780 mapmode Mode) {
Zachary Turneracd87912018-02-15 18:36:10 +0000781 this->Mode = Mode;
Peter Collingbourne881ba102018-06-13 18:03:14 +0000782 HANDLE OrigFileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
783 if (OrigFileHandle == INVALID_HANDLE_VALUE)
Rafael Espindolaa23008a2014-12-16 03:10:29 +0000784 return make_error_code(errc::bad_file_descriptor);
785
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000786 DWORD flprotect;
787 switch (Mode) {
788 case readonly: flprotect = PAGE_READONLY; break;
789 case readwrite: flprotect = PAGE_READWRITE; break;
790 case priv: flprotect = PAGE_WRITECOPY; break;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000791 }
792
Rafael Espindola369d5142014-12-16 02:53:35 +0000793 HANDLE FileMappingHandle =
Peter Collingbourne881ba102018-06-13 18:03:14 +0000794 ::CreateFileMappingW(OrigFileHandle, 0, flprotect,
Zachary Turnerab1ade42017-11-16 22:39:55 +0000795 Hi_32(Size),
796 Lo_32(Size),
David Majnemer17a44962013-10-07 09:52:36 +0000797 0);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000798 if (FileMappingHandle == NULL) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000799 std::error_code ec = mapWindowsError(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000800 return ec;
801 }
802
803 DWORD dwDesiredAccess;
804 switch (Mode) {
805 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
806 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
807 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000808 }
809 Mapping = ::MapViewOfFile(FileMappingHandle,
810 dwDesiredAccess,
811 Offset >> 32,
812 Offset & 0xffffffff,
813 Size);
814 if (Mapping == NULL) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000815 std::error_code ec = mapWindowsError(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000816 ::CloseHandle(FileMappingHandle);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000817 return ec;
818 }
819
820 if (Size == 0) {
821 MEMORY_BASIC_INFORMATION mbi;
822 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
823 if (Result == 0) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000824 std::error_code ec = mapWindowsError(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000825 ::UnmapViewOfFile(Mapping);
826 ::CloseHandle(FileMappingHandle);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000827 return ec;
828 }
829 Size = mbi.RegionSize;
830 }
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000831
Peter Collingbourne881ba102018-06-13 18:03:14 +0000832 // Close the file mapping handle, as it's kept alive by the file mapping. But
833 // neither the file mapping nor the file mapping handle keep the file handle
834 // alive, so we need to keep a reference to the file in case all other handles
835 // are closed and the file is deleted, which may cause invalid data to be read
836 // from the file.
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000837 ::CloseHandle(FileMappingHandle);
Peter Collingbourne881ba102018-06-13 18:03:14 +0000838 if (!::DuplicateHandle(::GetCurrentProcess(), OrigFileHandle,
839 ::GetCurrentProcess(), &FileHandle, 0, 0,
840 DUPLICATE_SAME_ACCESS)) {
841 std::error_code ec = mapWindowsError(GetLastError());
842 ::UnmapViewOfFile(Mapping);
843 return ec;
844 }
845
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000846 return std::error_code();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000847}
848
Roman Lebedev1e053ab2017-09-27 17:24:34 +0000849mapped_file_region::mapped_file_region(int fd, mapmode mode, size_t length,
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000850 uint64_t offset, std::error_code &ec)
Rafael Espindolaa23008a2014-12-16 03:10:29 +0000851 : Size(length), Mapping() {
Rafael Espindola986f5ad2014-12-16 02:19:26 +0000852 ec = init(fd, offset, mode);
Rafael Espindolaa23008a2014-12-16 03:10:29 +0000853 if (ec)
Rafael Espindola369d5142014-12-16 02:53:35 +0000854 Mapping = 0;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000855}
856
Alexandre Ganea3b9b4d22018-11-05 19:14:10 +0000857static bool hasFlushBufferKernelBug() {
858 static bool Ret{GetWindowsOSVersion() < llvm::VersionTuple(10, 0, 0, 17763)};
859 return Ret;
860}
861
862static bool isEXE(StringRef Magic) {
863 static const char PEMagic[] = {'P', 'E', '\0', '\0'};
864 if (Magic.startswith(StringRef("MZ")) && Magic.size() >= 0x3c + 4) {
865 uint32_t off = read32le(Magic.data() + 0x3c);
866 // PE/COFF file, either EXE or DLL.
867 if (Magic.substr(off).startswith(StringRef(PEMagic, sizeof(PEMagic))))
868 return true;
869 }
870 return false;
871}
872
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000873mapped_file_region::~mapped_file_region() {
Zachary Turneracd87912018-02-15 18:36:10 +0000874 if (Mapping) {
Alexandre Ganea3b9b4d22018-11-05 19:14:10 +0000875
876 bool Exe = isEXE(StringRef((char *)Mapping, Size));
877
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000878 ::UnmapViewOfFile(Mapping);
Zachary Turneracd87912018-02-15 18:36:10 +0000879
Alexandre Ganea3b9b4d22018-11-05 19:14:10 +0000880 if (Mode == mapmode::readwrite && Exe && hasFlushBufferKernelBug()) {
Zachary Turneracd87912018-02-15 18:36:10 +0000881 // There is a Windows kernel bug, the exact trigger conditions of which
882 // are not well understood. When triggered, dirty pages are not properly
883 // flushed and subsequent process's attempts to read a file can return
884 // invalid data. Calling FlushFileBuffers on the write handle is
885 // sufficient to ensure that this bug is not triggered.
Alexandre Ganea3b9b4d22018-11-05 19:14:10 +0000886 // The bug only occurs when writing an executable and executing it right
887 // after, under high I/O pressure.
Peter Collingbourne881ba102018-06-13 18:03:14 +0000888 ::FlushFileBuffers(FileHandle);
Zachary Turneracd87912018-02-15 18:36:10 +0000889 }
Peter Collingbourne881ba102018-06-13 18:03:14 +0000890
891 ::CloseHandle(FileHandle);
Zachary Turneracd87912018-02-15 18:36:10 +0000892 }
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000893}
894
Roman Lebedev1e053ab2017-09-27 17:24:34 +0000895size_t mapped_file_region::size() const {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000896 assert(Mapping && "Mapping failed but used anyway!");
897 return Size;
898}
899
900char *mapped_file_region::data() const {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000901 assert(Mapping && "Mapping failed but used anyway!");
902 return reinterpret_cast<char*>(Mapping);
903}
904
905const char *mapped_file_region::const_data() const {
906 assert(Mapping && "Mapping failed but used anyway!");
907 return reinterpret_cast<const char*>(Mapping);
908}
909
910int mapped_file_region::alignment() {
911 SYSTEM_INFO SysInfo;
912 ::GetSystemInfo(&SysInfo);
913 return SysInfo.dwAllocationGranularity;
914}
915
Peter Collingbourneb4f1b882017-10-11 02:09:06 +0000916static basic_file_status status_from_find_data(WIN32_FIND_DATAW *FindData) {
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000917 return basic_file_status(file_type_from_attrs(FindData->dwFileAttributes),
918 perms_from_attrs(FindData->dwFileAttributes),
919 FindData->ftLastAccessTime.dwHighDateTime,
920 FindData->ftLastAccessTime.dwLowDateTime,
921 FindData->ftLastWriteTime.dwHighDateTime,
922 FindData->ftLastWriteTime.dwLowDateTime,
923 FindData->nFileSizeHigh, FindData->nFileSizeLow);
924}
925
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000926std::error_code detail::directory_iterator_construct(detail::DirIterState &IT,
927 StringRef Path,
928 bool FollowSymlinks) {
929 SmallVector<wchar_t, 128> PathUTF16;
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000930
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000931 if (std::error_code EC = widenPath(Path, PathUTF16))
932 return EC;
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000933
934 // Convert path to the format that Windows is happy with.
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000935 if (PathUTF16.size() > 0 &&
936 !is_separator(PathUTF16[Path.size() - 1]) &&
937 PathUTF16[Path.size() - 1] != L':') {
938 PathUTF16.push_back(L'\\');
939 PathUTF16.push_back(L'*');
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000940 } else {
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000941 PathUTF16.push_back(L'*');
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000942 }
943
944 // Get the first directory entry.
945 WIN32_FIND_DATAW FirstFind;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000946 ScopedFindHandle FindHandle(::FindFirstFileExW(
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000947 c_str(PathUTF16), FindExInfoBasic, &FirstFind, FindExSearchNameMatch,
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000948 NULL, FIND_FIRST_EX_LARGE_FETCH));
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000949 if (!FindHandle)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000950 return mapWindowsError(::GetLastError());
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000951
Michael J. Spencer98879d72011-01-05 16:39:30 +0000952 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
953 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
954 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
955 FirstFind.cFileName[1] == L'.'))
956 if (!::FindNextFileW(FindHandle, &FirstFind)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000957 DWORD LastError = ::GetLastError();
Michael J. Spencer98879d72011-01-05 16:39:30 +0000958 // Check for end.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000959 if (LastError == ERROR_NO_MORE_FILES)
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000960 return detail::directory_iterator_destruct(IT);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000961 return mapWindowsError(LastError);
Michael J. Spencer98879d72011-01-05 16:39:30 +0000962 } else
963 FilenameLen = ::wcslen(FirstFind.cFileName);
964
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000965 // Construct the current directory entry.
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000966 SmallString<128> DirectoryEntryNameUTF8;
967 if (std::error_code EC =
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000968 UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000969 DirectoryEntryNameUTF8))
970 return EC;
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000971
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000972 IT.IterationHandle = intptr_t(FindHandle.take());
973 SmallString<128> DirectoryEntryPath(Path);
974 path::append(DirectoryEntryPath, DirectoryEntryNameUTF8);
975 IT.CurrentEntry =
976 directory_entry(DirectoryEntryPath, FollowSymlinks,
977 file_type_from_attrs(FirstFind.dwFileAttributes),
978 status_from_find_data(&FirstFind));
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000979
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000980 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000981}
982
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000983std::error_code detail::directory_iterator_destruct(detail::DirIterState &IT) {
984 if (IT.IterationHandle != 0)
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000985 // Closes the handle if it's valid.
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000986 ScopedFindHandle close(HANDLE(IT.IterationHandle));
987 IT.IterationHandle = 0;
988 IT.CurrentEntry = directory_entry();
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000989 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000990}
991
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000992std::error_code detail::directory_iterator_increment(detail::DirIterState &IT) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000993 WIN32_FIND_DATAW FindData;
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000994 if (!::FindNextFileW(HANDLE(IT.IterationHandle), &FindData)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000995 DWORD LastError = ::GetLastError();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000996 // Check for end.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000997 if (LastError == ERROR_NO_MORE_FILES)
Kristina Brooks3a55d1e2018-09-12 22:08:10 +0000998 return detail::directory_iterator_destruct(IT);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000999 return mapWindowsError(LastError);
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001000 }
1001
Michael J. Spencer98879d72011-01-05 16:39:30 +00001002 size_t FilenameLen = ::wcslen(FindData.cFileName);
1003 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
1004 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
1005 FindData.cFileName[1] == L'.'))
Kristina Brooks3a55d1e2018-09-12 22:08:10 +00001006 return directory_iterator_increment(IT);
Michael J. Spencer98879d72011-01-05 16:39:30 +00001007
Kristina Brooks3a55d1e2018-09-12 22:08:10 +00001008 SmallString<128> DirectoryEntryPathUTF8;
1009 if (std::error_code EC =
Rafael Espindolab4ad29b2014-06-13 02:36:09 +00001010 UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
Kristina Brooks3a55d1e2018-09-12 22:08:10 +00001011 DirectoryEntryPathUTF8))
1012 return EC;
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001013
Kristina Brooks3a55d1e2018-09-12 22:08:10 +00001014 IT.CurrentEntry.replace_filename(
1015 Twine(DirectoryEntryPathUTF8),
1016 file_type_from_attrs(FindData.dwFileAttributes),
1017 status_from_find_data(&FindData));
Rafael Espindolab4ad29b2014-06-13 02:36:09 +00001018 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001019}
1020
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001021ErrorOr<basic_file_status> directory_entry::status() const {
1022 return Status;
1023}
1024
Zachary Turner63db25b2018-06-04 19:38:11 +00001025static std::error_code nativeFileToFd(Expected<HANDLE> H, int &ResultFD,
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001026 OpenFlags Flags) {
1027 int CrtOpenFlags = 0;
1028 if (Flags & OF_Append)
1029 CrtOpenFlags |= _O_APPEND;
1030
1031 if (Flags & OF_Text)
1032 CrtOpenFlags |= _O_TEXT;
1033
Zachary Turner63db25b2018-06-04 19:38:11 +00001034 ResultFD = -1;
1035 if (!H)
1036 return errorToErrorCode(H.takeError());
1037
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001038 ResultFD = ::_open_osfhandle(intptr_t(*H), CrtOpenFlags);
Zachary Turner63db25b2018-06-04 19:38:11 +00001039 if (ResultFD == -1) {
1040 ::CloseHandle(*H);
1041 return mapWindowsError(ERROR_INVALID_HANDLE);
1042 }
1043 return std::error_code();
1044}
1045
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001046static DWORD nativeDisposition(CreationDisposition Disp, OpenFlags Flags) {
1047 // This is a compatibility hack. Really we should respect the creation
1048 // disposition, but a lot of old code relied on the implicit assumption that
1049 // OF_Append implied it would open an existing file. Since the disposition is
1050 // now explicit and defaults to CD_CreateAlways, this assumption would cause
1051 // any usage of OF_Append to append to a new file, even if the file already
1052 // existed. A better solution might have two new creation dispositions:
1053 // CD_AppendAlways and CD_AppendNew. This would also address the problem of
1054 // OF_Append being used on a read-only descriptor, which doesn't make sense.
1055 if (Flags & OF_Append)
1056 return OPEN_ALWAYS;
Nick Kledzik18497e92012-06-20 00:28:54 +00001057
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001058 switch (Disp) {
1059 case CD_CreateAlways:
1060 return CREATE_ALWAYS;
1061 case CD_CreateNew:
1062 return CREATE_NEW;
1063 case CD_OpenAlways:
1064 return OPEN_ALWAYS;
1065 case CD_OpenExisting:
1066 return OPEN_EXISTING;
1067 }
1068 llvm_unreachable("unreachable!");
1069}
1070
1071static DWORD nativeAccess(FileAccess Access, OpenFlags Flags) {
1072 DWORD Result = 0;
1073 if (Access & FA_Read)
1074 Result |= GENERIC_READ;
1075 if (Access & FA_Write)
1076 Result |= GENERIC_WRITE;
1077 if (Flags & OF_Delete)
1078 Result |= DELETE;
Andrew Ng089303d2018-07-04 14:17:10 +00001079 if (Flags & OF_UpdateAtime)
1080 Result |= FILE_WRITE_ATTRIBUTES;
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001081 return Result;
1082}
1083
Zachary Turner9d2cfa62018-06-07 23:25:13 +00001084static std::error_code openNativeFileInternal(const Twine &Name,
1085 file_t &ResultFile, DWORD Disp,
Zachary Turner6edfecb2018-06-08 15:15:56 +00001086 DWORD Access, DWORD Flags,
1087 bool Inherit = false) {
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001088 SmallVector<wchar_t, 128> PathUTF16;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +00001089 if (std::error_code EC = widenPath(Name, PathUTF16))
Zachary Turner9d2cfa62018-06-07 23:25:13 +00001090 return EC;
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001091
Zachary Turner6edfecb2018-06-08 15:15:56 +00001092 SECURITY_ATTRIBUTES SA;
1093 SA.nLength = sizeof(SA);
1094 SA.lpSecurityDescriptor = nullptr;
1095 SA.bInheritHandle = Inherit;
1096
Greg Bedwell7f68a712015-10-12 15:11:47 +00001097 HANDLE H =
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001098 ::CreateFileW(PathUTF16.begin(), Access,
Zachary Turner6edfecb2018-06-08 15:15:56 +00001099 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &SA,
1100 Disp, Flags, NULL);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001101 if (H == INVALID_HANDLE_VALUE) {
Rafael Espindolaa813d602014-06-11 03:58:34 +00001102 DWORD LastError = ::GetLastError();
Yaron Kerenf8e65172015-05-04 04:48:10 +00001103 std::error_code EC = mapWindowsError(LastError);
Rafael Espindola331aeba2013-07-17 19:58:28 +00001104 // Provide a better error message when trying to open directories.
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001105 // This only runs if we failed to open the file, so there is probably
1106 // no performances issues.
Rafael Espindolaa813d602014-06-11 03:58:34 +00001107 if (LastError != ERROR_ACCESS_DENIED)
Zachary Turner9d2cfa62018-06-07 23:25:13 +00001108 return EC;
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001109 if (is_directory(Name))
Zachary Turner9d2cfa62018-06-07 23:25:13 +00001110 return make_error_code(errc::is_a_directory);
1111 return EC;
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001112 }
Zachary Turner9d2cfa62018-06-07 23:25:13 +00001113 ResultFile = H;
1114 return std::error_code();
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001115}
1116
Zachary Turner9d2cfa62018-06-07 23:25:13 +00001117Expected<file_t> openNativeFile(const Twine &Name, CreationDisposition Disp,
1118 FileAccess Access, OpenFlags Flags,
1119 unsigned Mode) {
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001120 // Verify that we don't have both "append" and "excl".
1121 assert((!(Disp == CD_CreateNew) || !(Flags & OF_Append)) &&
1122 "Cannot specify both 'CreateNew' and 'Append' file creation flags!");
1123
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001124 DWORD NativeDisp = nativeDisposition(Disp, Flags);
1125 DWORD NativeAccess = nativeAccess(Access, Flags);
1126
Zachary Turner6edfecb2018-06-08 15:15:56 +00001127 bool Inherit = false;
1128 if (Flags & OF_ChildInherit)
1129 Inherit = true;
1130
Zachary Turner9d2cfa62018-06-07 23:25:13 +00001131 file_t Result;
Zachary Turner6edfecb2018-06-08 15:15:56 +00001132 std::error_code EC = openNativeFileInternal(
Peter Collingbourne881ba102018-06-13 18:03:14 +00001133 Name, Result, NativeDisp, NativeAccess, FILE_ATTRIBUTE_NORMAL, Inherit);
Zachary Turner9d2cfa62018-06-07 23:25:13 +00001134 if (EC)
1135 return errorCodeToError(EC);
Andrew Ng089303d2018-07-04 14:17:10 +00001136
1137 if (Flags & OF_UpdateAtime) {
1138 FILETIME FileTime;
1139 SYSTEMTIME SystemTime;
1140 GetSystemTime(&SystemTime);
1141 if (SystemTimeToFileTime(&SystemTime, &FileTime) == 0 ||
1142 SetFileTime(Result, NULL, &FileTime, NULL) == 0) {
1143 DWORD LastError = ::GetLastError();
1144 ::CloseHandle(Result);
1145 return errorCodeToError(mapWindowsError(LastError));
1146 }
1147 }
1148
Peter Collingbourne881ba102018-06-13 18:03:14 +00001149 if (Flags & OF_Delete) {
1150 if ((EC = setDeleteDisposition(Result, true))) {
1151 ::CloseHandle(Result);
1152 return errorCodeToError(EC);
1153 }
1154 }
Zachary Turner9d2cfa62018-06-07 23:25:13 +00001155 return Result;
1156}
1157
1158std::error_code openFile(const Twine &Name, int &ResultFD,
1159 CreationDisposition Disp, FileAccess Access,
1160 OpenFlags Flags, unsigned int Mode) {
1161 Expected<file_t> Result = openNativeFile(Name, Disp, Access, Flags);
1162 if (!Result)
1163 return errorToErrorCode(Result.takeError());
1164
1165 return nativeFileToFd(*Result, ResultFD, Flags);
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001166}
1167
1168static std::error_code directoryRealPath(const Twine &Name,
1169 SmallVectorImpl<char> &RealPath) {
Zachary Turner9d2cfa62018-06-07 23:25:13 +00001170 file_t File;
1171 std::error_code EC = openNativeFileInternal(
1172 Name, File, OPEN_EXISTING, GENERIC_READ, FILE_FLAG_BACKUP_SEMANTICS);
1173 if (EC)
1174 return EC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001175
Zachary Turner9d2cfa62018-06-07 23:25:13 +00001176 EC = realPathFromHandle(File, RealPath);
1177 ::CloseHandle(File);
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001178 return EC;
1179}
1180
1181std::error_code openFileForRead(const Twine &Name, int &ResultFD,
1182 OpenFlags Flags,
1183 SmallVectorImpl<char> *RealPath) {
1184 Expected<HANDLE> NativeFile = openNativeFileForRead(Name, Flags, RealPath);
1185 return nativeFileToFd(std::move(NativeFile), ResultFD, OF_None);
1186}
1187
1188Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
1189 SmallVectorImpl<char> *RealPath) {
Zachary Turner9d2cfa62018-06-07 23:25:13 +00001190 Expected<file_t> Result =
1191 openNativeFile(Name, CD_OpenExisting, FA_Read, Flags);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001192
Taewook Ohd9153272016-06-13 15:54:56 +00001193 // Fetch the real name of the file, if the user asked
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001194 if (Result && RealPath)
1195 realPathFromHandle(*Result, *RealPath);
Taewook Ohd9153272016-06-13 15:54:56 +00001196
Zachary Turner15243d52018-06-10 20:57:14 +00001197 return Result;
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001198}
Nick Kledzik18497e92012-06-20 00:28:54 +00001199
Zachary Turner63db25b2018-06-04 19:38:11 +00001200void closeFile(file_t &F) {
1201 ::CloseHandle(F);
1202 F = kInvalidFile;
Rafael Espindola67080ce2013-07-19 15:02:03 +00001203}
Taewook Ohd9153272016-06-13 15:54:56 +00001204
Zachary Turner260bda32017-03-08 22:49:32 +00001205std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1206 // Convert to utf-16.
1207 SmallVector<wchar_t, 128> Path16;
1208 std::error_code EC = widenPath(path, Path16);
1209 if (EC && !IgnoreErrors)
1210 return EC;
1211
1212 // SHFileOperation() accepts a list of paths, and so must be double null-
1213 // terminated to indicate the end of the list. The buffer is already null
1214 // terminated, but since that null character is not considered part of the
1215 // vector's size, pushing another one will just consume that byte. So we
1216 // need to push 2 null terminators.
1217 Path16.push_back(0);
1218 Path16.push_back(0);
1219
1220 SHFILEOPSTRUCTW shfos = {};
1221 shfos.wFunc = FO_DELETE;
1222 shfos.pFrom = Path16.data();
1223 shfos.fFlags = FOF_NO_UI;
1224
1225 int result = ::SHFileOperationW(&shfos);
1226 if (result != 0 && !IgnoreErrors)
1227 return mapWindowsError(result);
1228 return std::error_code();
1229}
1230
Zachary Turnere48ace62017-03-10 17:39:21 +00001231static void expandTildeExpr(SmallVectorImpl<char> &Path) {
1232 // Path does not begin with a tilde expression.
1233 if (Path.empty() || Path[0] != '~')
1234 return;
1235
1236 StringRef PathStr(Path.begin(), Path.size());
1237 PathStr = PathStr.drop_front();
Zachary Turner5c5091f2017-03-16 22:28:04 +00001238 StringRef Expr = PathStr.take_until([](char c) { return path::is_separator(c); });
Zachary Turnere48ace62017-03-10 17:39:21 +00001239
1240 if (!Expr.empty()) {
1241 // This is probably a ~username/ expression. Don't support this on Windows.
1242 return;
1243 }
1244
1245 SmallString<128> HomeDir;
1246 if (!path::home_directory(HomeDir)) {
1247 // For some reason we couldn't get the home directory. Just exit.
1248 return;
1249 }
1250
1251 // Overwrite the first character and insert the rest.
1252 Path[0] = HomeDir[0];
1253 Path.insert(Path.begin() + 1, HomeDir.begin() + 1, HomeDir.end());
1254}
1255
Jonas Devlieghereb23f4302018-11-13 18:23:32 +00001256void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
1257 dest.clear();
1258 if (path.isTriviallyEmpty())
1259 return;
1260
1261 path.toVector(dest);
1262 expandTildeExpr(dest);
1263
1264 return;
1265}
1266
Zachary Turnere48ace62017-03-10 17:39:21 +00001267std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1268 bool expand_tilde) {
1269 dest.clear();
1270 if (path.isTriviallyEmpty())
1271 return std::error_code();
1272
1273 if (expand_tilde) {
1274 SmallString<128> Storage;
1275 path.toVector(Storage);
1276 expandTildeExpr(Storage);
1277 return real_path(Storage, dest, false);
1278 }
1279
1280 if (is_directory(path))
1281 return directoryRealPath(path, dest);
1282
1283 int fd;
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001284 if (std::error_code EC =
1285 llvm::sys::fs::openFileForRead(path, fd, OF_None, &dest))
Zachary Turnere48ace62017-03-10 17:39:21 +00001286 return EC;
1287 ::close(fd);
1288 return std::error_code();
1289}
1290
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +00001291} // end namespace fs
Rui Ueyama471d0c52013-09-10 19:45:51 +00001292
Peter Collingbournef7d41012014-01-31 23:46:06 +00001293namespace path {
Pawel Bylica7c1f36a2015-11-02 14:57:24 +00001294static bool getKnownFolderPath(KNOWNFOLDERID folderId,
1295 SmallVectorImpl<char> &result) {
Pawel Bylica7187e4b2015-10-16 09:08:59 +00001296 wchar_t *path = nullptr;
1297 if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK)
1298 return false;
1299
1300 bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
1301 ::CoTaskMemFree(path);
1302 return ok;
1303}
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001304
Peter Collingbournef7d41012014-01-31 23:46:06 +00001305bool home_directory(SmallVectorImpl<char> &result) {
Pawel Bylica7187e4b2015-10-16 09:08:59 +00001306 return getKnownFolderPath(FOLDERID_Profile, result);
Peter Collingbournef7d41012014-01-31 23:46:06 +00001307}
1308
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001309static bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {
Pawel Bylica6e680b22015-11-06 23:44:23 +00001310 SmallVector<wchar_t, 1024> Buf;
1311 size_t Size = 1024;
1312 do {
1313 Buf.reserve(Size);
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001314 Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.capacity());
Pawel Bylica6e680b22015-11-06 23:44:23 +00001315 if (Size == 0)
1316 return false;
1317
1318 // Try again with larger buffer.
1319 } while (Size > Buf.capacity());
1320 Buf.set_size(Size);
1321
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001322 return !windows::UTF16ToUTF8(Buf.data(), Size, Res);
Pawel Bylica6e680b22015-11-06 23:44:23 +00001323}
1324
1325static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001326 const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};
1327 for (auto *Env : EnvironmentVariables) {
Pawel Bylica6e680b22015-11-06 23:44:23 +00001328 if (getTempDirEnvVar(Env, Res))
1329 return true;
1330 }
1331 return false;
1332}
1333
Rafael Espindola016a6d52014-08-26 14:47:52 +00001334void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1335 (void)ErasedOnReboot;
Pawel Bylica6e680b22015-11-06 23:44:23 +00001336 Result.clear();
Rafael Espindola016a6d52014-08-26 14:47:52 +00001337
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001338 // Check whether the temporary directory is specified by an environment var.
1339 // This matches GetTempPath logic to some degree. GetTempPath is not used
1340 // directly as it cannot handle evn var longer than 130 chars on Windows 7
1341 // (fixed on Windows 8).
1342 if (getTempDirEnvVar(Result)) {
1343 assert(!Result.empty() && "Unexpected empty path");
1344 native(Result); // Some Unix-like shells use Unix path separator in $TMP.
1345 fs::make_absolute(Result); // Make it absolute if not already.
Pawel Bylica6e680b22015-11-06 23:44:23 +00001346 return;
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001347 }
Rafael Espindola016a6d52014-08-26 14:47:52 +00001348
1349 // Fall back to a system default.
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001350 const char *DefaultResult = "C:\\Temp";
Rafael Espindola016a6d52014-08-26 14:47:52 +00001351 Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
1352}
Peter Collingbournef7d41012014-01-31 23:46:06 +00001353} // end namespace path
1354
Rui Ueyama471d0c52013-09-10 19:45:51 +00001355namespace windows {
Aaron Smith8a5ea612018-04-07 00:32:59 +00001356std::error_code CodePageToUTF16(unsigned codepage,
1357 llvm::StringRef original,
1358 llvm::SmallVectorImpl<wchar_t> &utf16) {
1359 if (!original.empty()) {
1360 int len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1361 original.size(), utf16.begin(), 0);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001362
Aaron Smith8a5ea612018-04-07 00:32:59 +00001363 if (len == 0) {
Yaron Kerenf8e65172015-05-04 04:48:10 +00001364 return mapWindowsError(::GetLastError());
Aaron Smith8a5ea612018-04-07 00:32:59 +00001365 }
Rui Ueyama471d0c52013-09-10 19:45:51 +00001366
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001367 utf16.reserve(len + 1);
1368 utf16.set_size(len);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001369
Aaron Smith8a5ea612018-04-07 00:32:59 +00001370 len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1371 original.size(), utf16.begin(), utf16.size());
Rui Ueyama471d0c52013-09-10 19:45:51 +00001372
Aaron Smith8a5ea612018-04-07 00:32:59 +00001373 if (len == 0) {
Yaron Kerenf8e65172015-05-04 04:48:10 +00001374 return mapWindowsError(::GetLastError());
Aaron Smith8a5ea612018-04-07 00:32:59 +00001375 }
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001376 }
Rui Ueyama471d0c52013-09-10 19:45:51 +00001377
1378 // Make utf16 null terminated.
1379 utf16.push_back(0);
1380 utf16.pop_back();
1381
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +00001382 return std::error_code();
Rui Ueyama471d0c52013-09-10 19:45:51 +00001383}
1384
Aaron Smith8a5ea612018-04-07 00:32:59 +00001385std::error_code UTF8ToUTF16(llvm::StringRef utf8,
1386 llvm::SmallVectorImpl<wchar_t> &utf16) {
1387 return CodePageToUTF16(CP_UTF8, utf8, utf16);
1388}
1389
1390std::error_code CurCPToUTF16(llvm::StringRef curcp,
1391 llvm::SmallVectorImpl<wchar_t> &utf16) {
1392 return CodePageToUTF16(CP_ACP, curcp, utf16);
1393}
1394
Rafael Espindola9c359662014-09-03 20:02:00 +00001395static
1396std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
1397 size_t utf16_len,
Aaron Smith8a5ea612018-04-07 00:32:59 +00001398 llvm::SmallVectorImpl<char> &converted) {
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001399 if (utf16_len) {
1400 // Get length.
Aaron Smith8a5ea612018-04-07 00:32:59 +00001401 int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.begin(),
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001402 0, NULL, NULL);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001403
Aaron Smith8a5ea612018-04-07 00:32:59 +00001404 if (len == 0) {
Yaron Kerenf8e65172015-05-04 04:48:10 +00001405 return mapWindowsError(::GetLastError());
Aaron Smith8a5ea612018-04-07 00:32:59 +00001406 }
Rui Ueyama471d0c52013-09-10 19:45:51 +00001407
Aaron Smith8a5ea612018-04-07 00:32:59 +00001408 converted.reserve(len);
1409 converted.set_size(len);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001410
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001411 // Now do the actual conversion.
Aaron Smith8a5ea612018-04-07 00:32:59 +00001412 len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.data(),
1413 converted.size(), NULL, NULL);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001414
Aaron Smith8a5ea612018-04-07 00:32:59 +00001415 if (len == 0) {
Yaron Kerenf8e65172015-05-04 04:48:10 +00001416 return mapWindowsError(::GetLastError());
Aaron Smith8a5ea612018-04-07 00:32:59 +00001417 }
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001418 }
Rui Ueyama471d0c52013-09-10 19:45:51 +00001419
Aaron Smith8a5ea612018-04-07 00:32:59 +00001420 // Make the new string null terminated.
1421 converted.push_back(0);
1422 converted.pop_back();
Rui Ueyama471d0c52013-09-10 19:45:51 +00001423
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +00001424 return std::error_code();
Rui Ueyama471d0c52013-09-10 19:45:51 +00001425}
Rafael Espindola9c359662014-09-03 20:02:00 +00001426
1427std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
1428 llvm::SmallVectorImpl<char> &utf8) {
1429 return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
1430}
1431
1432std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
Aaron Smith8a5ea612018-04-07 00:32:59 +00001433 llvm::SmallVectorImpl<char> &curcp) {
1434 return UTF16ToCodePage(CP_ACP, utf16, utf16_len, curcp);
Rafael Espindola9c359662014-09-03 20:02:00 +00001435}
Taewook Ohd9153272016-06-13 15:54:56 +00001436
Rui Ueyama471d0c52013-09-10 19:45:51 +00001437} // end namespace windows
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001438} // end namespace sys
1439} // end namespace llvm