blob: 6017fcedc33fca2077b0f3709f6a502faec3c30a [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
407static std::error_code removeFD(int FD) {
408 HANDLE Handle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
409 return setDeleteDisposition(Handle, true);
410}
411
Rafael Espindola3ecd2042017-11-28 01:41:22 +0000412/// In order to handle temporary files we want the following properties
413///
414/// * The temporary file is deleted on crashes
415/// * We can use (read, rename, etc) the temporary file.
416/// * We can cancel the delete to keep the file.
417///
418/// Using FILE_DISPOSITION_INFO with DeleteFile=true will create a file that is
419/// deleted on close, but it has a few problems:
420///
421/// * The file cannot be used. An attempt to open or rename the file will fail.
422/// This makes the temporary file almost useless, as it cannot be part of
423/// any other CreateFileW call in the current or in another process.
424/// * It is not atomic. A crash just after CreateFileW or just after canceling
425/// the delete will leave the file on disk.
426///
427/// Using FILE_FLAG_DELETE_ON_CLOSE solves the first issues and the first part
428/// of the second one, but there is no way to cancel it in place. What works is
429/// to create a second handle to prevent the deletion, close the first one and
430/// then clear DeleteFile with SetFileInformationByHandle. This requires
431/// changing the handle and file descriptor the caller uses.
432static std::error_code cancelDeleteOnClose(int &FD) {
433 HANDLE Handle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
434 SmallVector<wchar_t, MAX_PATH> Name;
435 if (std::error_code EC = realPathFromHandle(Handle, Name))
436 return EC;
437 HANDLE NewHandle =
438 ::CreateFileW(Name.data(), GENERIC_READ | GENERIC_WRITE | DELETE,
439 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
440 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
441 if (NewHandle == INVALID_HANDLE_VALUE)
442 return mapWindowsError(::GetLastError());
443 if (close(FD))
444 return mapWindowsError(::GetLastError());
445
Rafael Espindola20569e92017-12-05 16:40:56 +0000446 if (std::error_code EC = setDeleteDisposition(NewHandle, false))
447 return EC;
448
Rafael Espindola3ecd2042017-11-28 01:41:22 +0000449 FD = ::_open_osfhandle(intptr_t(NewHandle), 0);
450 if (FD == -1) {
451 ::CloseHandle(NewHandle);
452 return mapWindowsError(ERROR_INVALID_HANDLE);
453 }
454 return std::error_code();
455}
456
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000457static std::error_code rename_internal(HANDLE FromHandle, const Twine &To,
458 bool ReplaceIfExists) {
459 SmallVector<wchar_t, 0> ToWide;
460 if (auto EC = widenPath(To, ToWide))
461 return EC;
462
463 std::vector<char> RenameInfoBuf(sizeof(FILE_RENAME_INFO) - sizeof(wchar_t) +
464 (ToWide.size() * sizeof(wchar_t)));
465 FILE_RENAME_INFO &RenameInfo =
466 *reinterpret_cast<FILE_RENAME_INFO *>(RenameInfoBuf.data());
467 RenameInfo.ReplaceIfExists = ReplaceIfExists;
468 RenameInfo.RootDirectory = 0;
469 RenameInfo.FileNameLength = ToWide.size();
Adrian McCarthye6275c62017-10-09 17:50:01 +0000470 std::copy(ToWide.begin(), ToWide.end(), &RenameInfo.FileName[0]);
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000471
Hans Wennborg477c9742017-10-12 17:38:22 +0000472 SetLastError(ERROR_SUCCESS);
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000473 if (!SetFileInformationByHandle(FromHandle, FileRenameInfo, &RenameInfo,
Hans Wennborg477c9742017-10-12 17:38:22 +0000474 RenameInfoBuf.size())) {
475 unsigned Error = GetLastError();
476 if (Error == ERROR_SUCCESS)
477 Error = ERROR_CALL_NOT_IMPLEMENTED; // Wine doesn't always set error code.
478 return mapWindowsError(Error);
479 }
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000480
481 return std::error_code();
482}
483
Rafael Espindola5908aff2017-11-21 01:52:44 +0000484static std::error_code rename_handle(HANDLE FromHandle, const Twine &To) {
485 SmallVector<wchar_t, 128> WideTo;
486 if (std::error_code EC = widenPath(To, WideTo))
487 return EC;
488
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000489 // We normally expect this loop to succeed after a few iterations. If it
490 // requires more than 200 tries, it's more likely that the failures are due to
491 // a true error, so stop trying.
492 for (unsigned Retry = 0; Retry != 200; ++Retry) {
493 auto EC = rename_internal(FromHandle, To, true);
Hans Wennborg17701ab2017-10-11 22:04:14 +0000494
495 if (EC ==
496 std::error_code(ERROR_CALL_NOT_IMPLEMENTED, std::system_category())) {
497 // Wine doesn't support SetFileInformationByHandle in rename_internal.
498 // Fall back to MoveFileEx.
Rafael Espindola5908aff2017-11-21 01:52:44 +0000499 SmallVector<wchar_t, MAX_PATH> WideFrom;
500 if (std::error_code EC2 = realPathFromHandle(FromHandle, WideFrom))
501 return EC2;
Hans Wennborg17701ab2017-10-11 22:04:14 +0000502 if (::MoveFileExW(WideFrom.begin(), WideTo.begin(),
503 MOVEFILE_REPLACE_EXISTING))
504 return std::error_code();
505 return mapWindowsError(GetLastError());
506 }
507
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000508 if (!EC || EC != errc::permission_denied)
509 return EC;
Greg Bedwell7f68a712015-10-12 15:11:47 +0000510
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000511 // The destination file probably exists and is currently open in another
512 // process, either because the file was opened without FILE_SHARE_DELETE or
513 // it is mapped into memory (e.g. using MemoryBuffer). Rename it in order to
514 // move it out of the way of the source file. Use FILE_FLAG_DELETE_ON_CLOSE
515 // to arrange for the destination file to be deleted when the other process
516 // closes it.
517 ScopedFileHandle ToHandle(
518 ::CreateFileW(WideTo.begin(), GENERIC_READ | DELETE,
519 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
520 NULL, OPEN_EXISTING,
521 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL));
522 if (!ToHandle) {
523 auto EC = mapWindowsError(GetLastError());
524 // Another process might have raced with us and moved the existing file
525 // out of the way before we had a chance to open it. If that happens, try
526 // to rename the source file again.
527 if (EC == errc::no_such_file_or_directory)
Sunil Srivastava34fce932016-03-25 23:41:28 +0000528 continue;
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000529 return EC;
Sunil Srivastava34fce932016-03-25 23:41:28 +0000530 }
Greg Bedwell7f68a712015-10-12 15:11:47 +0000531
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000532 BY_HANDLE_FILE_INFORMATION FI;
533 if (!GetFileInformationByHandle(ToHandle, &FI))
534 return mapWindowsError(GetLastError());
Greg Bedwell7f68a712015-10-12 15:11:47 +0000535
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000536 // Try to find a unique new name for the destination file.
537 for (unsigned UniqueId = 0; UniqueId != 200; ++UniqueId) {
538 std::string TmpFilename = (To + ".tmp" + utostr(UniqueId)).str();
539 if (auto EC = rename_internal(ToHandle, TmpFilename, false)) {
540 if (EC == errc::file_exists || EC == errc::permission_denied) {
541 // Again, another process might have raced with us and moved the file
542 // before we could move it. Check whether this is the case, as it
543 // might have caused the permission denied error. If that was the
544 // case, we don't need to move it ourselves.
545 ScopedFileHandle ToHandle2(::CreateFileW(
546 WideTo.begin(), 0,
547 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
548 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
549 if (!ToHandle2) {
550 auto EC = mapWindowsError(GetLastError());
551 if (EC == errc::no_such_file_or_directory)
552 break;
553 return EC;
554 }
555 BY_HANDLE_FILE_INFORMATION FI2;
556 if (!GetFileInformationByHandle(ToHandle2, &FI2))
557 return mapWindowsError(GetLastError());
558 if (FI.nFileIndexHigh != FI2.nFileIndexHigh ||
559 FI.nFileIndexLow != FI2.nFileIndexLow ||
560 FI.dwVolumeSerialNumber != FI2.dwVolumeSerialNumber)
561 break;
562 continue;
563 }
564 return EC;
565 }
566 break;
567 }
568
569 // Okay, the old destination file has probably been moved out of the way at
570 // this point, so try to rename the source file again. Still, another
571 // process might have raced with us to create and open the destination
572 // file, so we need to keep doing this until we succeed.
NAKAMURA Takumi3b7f9952012-05-08 14:31:46 +0000573 }
Michael J. Spencer409f5562010-12-03 17:53:55 +0000574
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000575 // The most likely root cause.
576 return errc::permission_denied;
Michael J. Spencer409f5562010-12-03 17:53:55 +0000577}
578
Rafael Espindola3ecd2042017-11-28 01:41:22 +0000579static std::error_code rename_fd(int FromFD, const Twine &To) {
580 HANDLE FromHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FromFD));
581 return rename_handle(FromHandle, To);
582}
583
Rafael Espindola811d5e82017-11-21 05:35:45 +0000584std::error_code rename(const Twine &From, const Twine &To) {
585 // Convert to utf-16.
586 SmallVector<wchar_t, 128> WideFrom;
587 if (std::error_code EC = widenPath(From, WideFrom))
588 return EC;
589
590 ScopedFileHandle FromHandle;
591 // Retry this a few times to defeat badly behaved file system scanners.
592 for (unsigned Retry = 0; Retry != 200; ++Retry) {
593 if (Retry != 0)
594 ::Sleep(10);
595 FromHandle =
596 ::CreateFileW(WideFrom.begin(), GENERIC_READ | DELETE,
597 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
598 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
599 if (FromHandle)
600 break;
601 }
602 if (!FromHandle)
603 return mapWindowsError(GetLastError());
604
605 return rename_handle(FromHandle, To);
606}
607
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000608std::error_code resize_file(int FD, uint64_t Size) {
Michael J. Spencerca242f22010-12-03 18:48:56 +0000609#ifdef HAVE__CHSIZE_S
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000610 errno_t error = ::_chsize_s(FD, Size);
Michael J. Spencerca242f22010-12-03 18:48:56 +0000611#else
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000612 errno_t error = ::_chsize(FD, Size);
Michael J. Spencerca242f22010-12-03 18:48:56 +0000613#endif
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000614 return std::error_code(error, std::generic_category());
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000615}
616
Rafael Espindola281f23a2014-09-11 20:30:02 +0000617std::error_code access(const Twine &Path, AccessMode Mode) {
Rafael Espindola281f23a2014-09-11 20:30:02 +0000618 SmallVector<wchar_t, 128> PathUtf16;
Michael J. Spencer45710402010-12-03 01:21:28 +0000619
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000620 if (std::error_code EC = widenPath(Path, PathUtf16))
Rafael Espindola281f23a2014-09-11 20:30:02 +0000621 return EC;
Michael J. Spencer45710402010-12-03 01:21:28 +0000622
Rafael Espindola281f23a2014-09-11 20:30:02 +0000623 DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
Michael J. Spencer45710402010-12-03 01:21:28 +0000624
Rafael Espindola281f23a2014-09-11 20:30:02 +0000625 if (Attributes == INVALID_FILE_ATTRIBUTES) {
Michael J. Spencer45710402010-12-03 01:21:28 +0000626 // See if the file didn't actually exist.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000627 DWORD LastError = ::GetLastError();
628 if (LastError != ERROR_FILE_NOT_FOUND &&
629 LastError != ERROR_PATH_NOT_FOUND)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000630 return mapWindowsError(LastError);
Rafael Espindola281f23a2014-09-11 20:30:02 +0000631 return errc::no_such_file_or_directory;
632 }
633
634 if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
635 return errc::permission_denied;
636
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000637 return std::error_code();
Michael J. Spencer45710402010-12-03 01:21:28 +0000638}
639
Reid Kleckner89d4b1a2015-09-10 23:28:06 +0000640bool can_execute(const Twine &Path) {
641 return !access(Path, AccessMode::Execute) ||
642 !access(Path + ".exe", AccessMode::Execute);
643}
644
Michael J. Spencer203d7802011-12-12 06:04:28 +0000645bool equivalent(file_status A, file_status B) {
646 assert(status_known(A) && status_known(B));
Mehdi Amini1e39ef32016-03-25 07:30:21 +0000647 return A.FileIndexHigh == B.FileIndexHigh &&
648 A.FileIndexLow == B.FileIndexLow &&
649 A.FileSizeHigh == B.FileSizeHigh &&
650 A.FileSizeLow == B.FileSizeLow &&
651 A.LastAccessedTimeHigh == B.LastAccessedTimeHigh &&
652 A.LastAccessedTimeLow == B.LastAccessedTimeLow &&
653 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
654 A.LastWriteTimeLow == B.LastWriteTimeLow &&
655 A.VolumeSerialNumber == B.VolumeSerialNumber;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000656}
657
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000658std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000659 file_status fsA, fsB;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000660 if (std::error_code ec = status(A, fsA))
661 return ec;
662 if (std::error_code ec = status(B, fsB))
663 return ec;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000664 result = equivalent(fsA, fsB);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000665 return std::error_code();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000666}
667
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000668static bool isReservedName(StringRef path) {
669 // This list of reserved names comes from MSDN, at:
670 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
Craig Topper26260942015-10-18 05:15:34 +0000671 static const char *const sReservedNames[] = { "nul", "con", "prn", "aux",
672 "com1", "com2", "com3", "com4",
673 "com5", "com6", "com7", "com8",
674 "com9", "lpt1", "lpt2", "lpt3",
675 "lpt4", "lpt5", "lpt6", "lpt7",
676 "lpt8", "lpt9" };
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000677
678 // First, check to see if this is a device namespace, which always
679 // starts with \\.\, since device namespaces are not legal file paths.
680 if (path.startswith("\\\\.\\"))
681 return true;
682
Douglas Yung091d8fd2016-05-03 00:12:59 +0000683 // Then compare against the list of ancient reserved names.
Craig Topper58713212013-07-15 04:27:47 +0000684 for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000685 if (path.equals_lower(sReservedNames[i]))
686 return true;
687 }
688
689 // The path isn't what we consider reserved.
690 return false;
691}
692
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000693static file_type file_type_from_attrs(DWORD Attrs) {
694 return (Attrs & FILE_ATTRIBUTE_DIRECTORY) ? file_type::directory_file
695 : file_type::regular_file;
696}
697
698static perms perms_from_attrs(DWORD Attrs) {
699 return (Attrs & FILE_ATTRIBUTE_READONLY) ? (all_read | all_exe) : all_all;
700}
701
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000702static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000703 if (FileHandle == INVALID_HANDLE_VALUE)
704 goto handle_status_error;
705
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000706 switch (::GetFileType(FileHandle)) {
707 default:
Rafael Espindola81177c52013-07-18 18:42:52 +0000708 llvm_unreachable("Don't know anything about this file type");
709 case FILE_TYPE_UNKNOWN: {
710 DWORD Err = ::GetLastError();
711 if (Err != NO_ERROR)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000712 return mapWindowsError(Err);
Rafael Espindola81177c52013-07-18 18:42:52 +0000713 Result = file_status(file_type::type_unknown);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000714 return std::error_code();
Rafael Espindola81177c52013-07-18 18:42:52 +0000715 }
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000716 case FILE_TYPE_DISK:
717 break;
718 case FILE_TYPE_CHAR:
719 Result = file_status(file_type::character_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000720 return std::error_code();
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000721 case FILE_TYPE_PIPE:
722 Result = file_status(file_type::fifo_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000723 return std::error_code();
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000724 }
725
Rafael Espindola77021c92013-07-16 03:20:13 +0000726 BY_HANDLE_FILE_INFORMATION Info;
727 if (!::GetFileInformationByHandle(FileHandle, &Info))
728 goto handle_status_error;
729
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000730 Result = file_status(
731 file_type_from_attrs(Info.dwFileAttributes),
732 perms_from_attrs(Info.dwFileAttributes), Info.nNumberOfLinks,
733 Info.ftLastAccessTime.dwHighDateTime, Info.ftLastAccessTime.dwLowDateTime,
734 Info.ftLastWriteTime.dwHighDateTime, Info.ftLastWriteTime.dwLowDateTime,
735 Info.dwVolumeSerialNumber, Info.nFileSizeHigh, Info.nFileSizeLow,
736 Info.nFileIndexHigh, Info.nFileIndexLow);
737 return std::error_code();
Aaron Ballman345012d2017-03-13 12:24:51 +0000738
Rafael Espindola77021c92013-07-16 03:20:13 +0000739handle_status_error:
Rafael Espindolaa813d602014-06-11 03:58:34 +0000740 DWORD LastError = ::GetLastError();
741 if (LastError == ERROR_FILE_NOT_FOUND ||
742 LastError == ERROR_PATH_NOT_FOUND)
Rafael Espindola77021c92013-07-16 03:20:13 +0000743 Result = file_status(file_type::file_not_found);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000744 else if (LastError == ERROR_SHARING_VIOLATION)
Rafael Espindola77021c92013-07-16 03:20:13 +0000745 Result = file_status(file_type::type_unknown);
Rafael Espindola107b74c2013-07-31 00:10:25 +0000746 else
Rafael Espindola77021c92013-07-16 03:20:13 +0000747 Result = file_status(file_type::status_error);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000748 return mapWindowsError(LastError);
Rafael Espindola77021c92013-07-16 03:20:13 +0000749}
750
Zachary Turner82dd5422017-03-07 16:10:10 +0000751std::error_code status(const Twine &path, file_status &result, bool Follow) {
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000752 SmallString<128> path_storage;
753 SmallVector<wchar_t, 128> path_utf16;
754
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000755 StringRef path8 = path.toStringRef(path_storage);
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000756 if (isReservedName(path8)) {
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000757 result = file_status(file_type::character_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000758 return std::error_code();
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000759 }
760
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000761 if (std::error_code ec = widenPath(path8, path_utf16))
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000762 return ec;
763
764 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
765 if (attr == INVALID_FILE_ATTRIBUTES)
Rafael Espindola77021c92013-07-16 03:20:13 +0000766 return getStatus(INVALID_HANDLE_VALUE, result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000767
Zachary Turner82dd5422017-03-07 16:10:10 +0000768 DWORD Flags = FILE_FLAG_BACKUP_SEMANTICS;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000769 // Handle reparse points.
Zachary Turner82dd5422017-03-07 16:10:10 +0000770 if (!Follow && (attr & FILE_ATTRIBUTE_REPARSE_POINT))
771 Flags |= FILE_FLAG_OPEN_REPARSE_POINT;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000772
Rafael Espindolaa5932af2013-07-30 20:25:53 +0000773 ScopedFileHandle h(
774 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
Michael J. Spencer203d7802011-12-12 06:04:28 +0000775 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
Zachary Turner82dd5422017-03-07 16:10:10 +0000776 NULL, OPEN_EXISTING, Flags, 0));
777 if (!h)
778 return getStatus(INVALID_HANDLE_VALUE, result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000779
Zachary Turner82dd5422017-03-07 16:10:10 +0000780 return getStatus(h, result);
Rafael Espindola77021c92013-07-16 03:20:13 +0000781}
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000782
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000783std::error_code status(int FD, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000784 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
Aaron Ballman345012d2017-03-13 12:24:51 +0000785 return getStatus(FileHandle, Result);
786}
787
James Henderson566fdf42017-03-16 11:22:09 +0000788std::error_code setPermissions(const Twine &Path, perms Permissions) {
789 SmallVector<wchar_t, 128> PathUTF16;
790 if (std::error_code EC = widenPath(Path, PathUTF16))
791 return EC;
792
793 DWORD Attributes = ::GetFileAttributesW(PathUTF16.begin());
794 if (Attributes == INVALID_FILE_ATTRIBUTES)
795 return mapWindowsError(GetLastError());
796
797 // There are many Windows file attributes that are not to do with the file
798 // permissions (e.g. FILE_ATTRIBUTE_HIDDEN). We need to be careful to preserve
799 // them.
800 if (Permissions & all_write) {
801 Attributes &= ~FILE_ATTRIBUTE_READONLY;
802 if (Attributes == 0)
803 // FILE_ATTRIBUTE_NORMAL indicates no other attributes are set.
804 Attributes |= FILE_ATTRIBUTE_NORMAL;
805 }
806 else {
807 Attributes |= FILE_ATTRIBUTE_READONLY;
808 // FILE_ATTRIBUTE_NORMAL is not compatible with any other attributes, so
809 // remove it, if it is present.
810 Attributes &= ~FILE_ATTRIBUTE_NORMAL;
811 }
812
813 if (!::SetFileAttributesW(PathUTF16.begin(), Attributes))
814 return mapWindowsError(GetLastError());
815
816 return std::error_code();
817}
818
Aaron Ballman345012d2017-03-13 12:24:51 +0000819std::error_code setLastModificationAndAccessTime(int FD, TimePoint<> Time) {
820 FILETIME FT = toFILETIME(Time);
821 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000822 if (!SetFileTime(FileHandle, NULL, &FT, &FT))
Yaron Kerenf8e65172015-05-04 04:48:10 +0000823 return mapWindowsError(::GetLastError());
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000824 return std::error_code();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000825}
Nick Kledzik18497e92012-06-20 00:28:54 +0000826
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000827std::error_code mapped_file_region::init(int FD, uint64_t Offset,
828 mapmode Mode) {
Zachary Turneracd87912018-02-15 18:36:10 +0000829 this->FD = FD;
830 this->Mode = Mode;
Rafael Espindolaa23008a2014-12-16 03:10:29 +0000831 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
832 if (FileHandle == INVALID_HANDLE_VALUE)
833 return make_error_code(errc::bad_file_descriptor);
834
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000835 DWORD flprotect;
836 switch (Mode) {
837 case readonly: flprotect = PAGE_READONLY; break;
838 case readwrite: flprotect = PAGE_READWRITE; break;
839 case priv: flprotect = PAGE_WRITECOPY; break;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000840 }
841
Rafael Espindola369d5142014-12-16 02:53:35 +0000842 HANDLE FileMappingHandle =
David Majnemer17a44962013-10-07 09:52:36 +0000843 ::CreateFileMappingW(FileHandle, 0, flprotect,
Zachary Turnerab1ade42017-11-16 22:39:55 +0000844 Hi_32(Size),
845 Lo_32(Size),
David Majnemer17a44962013-10-07 09:52:36 +0000846 0);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000847 if (FileMappingHandle == NULL) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000848 std::error_code ec = mapWindowsError(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000849 return ec;
850 }
851
852 DWORD dwDesiredAccess;
853 switch (Mode) {
854 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
855 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
856 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000857 }
858 Mapping = ::MapViewOfFile(FileMappingHandle,
859 dwDesiredAccess,
860 Offset >> 32,
861 Offset & 0xffffffff,
862 Size);
863 if (Mapping == NULL) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000864 std::error_code ec = mapWindowsError(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000865 ::CloseHandle(FileMappingHandle);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000866 return ec;
867 }
868
869 if (Size == 0) {
870 MEMORY_BASIC_INFORMATION mbi;
871 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
872 if (Result == 0) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000873 std::error_code ec = mapWindowsError(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000874 ::UnmapViewOfFile(Mapping);
875 ::CloseHandle(FileMappingHandle);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000876 return ec;
877 }
878 Size = mbi.RegionSize;
879 }
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000880
881 // Close all the handles except for the view. It will keep the other handles
882 // alive.
883 ::CloseHandle(FileMappingHandle);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000884 return std::error_code();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000885}
886
Roman Lebedev1e053ab2017-09-27 17:24:34 +0000887mapped_file_region::mapped_file_region(int fd, mapmode mode, size_t length,
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000888 uint64_t offset, std::error_code &ec)
Rafael Espindolaa23008a2014-12-16 03:10:29 +0000889 : Size(length), Mapping() {
Rafael Espindola986f5ad2014-12-16 02:19:26 +0000890 ec = init(fd, offset, mode);
Rafael Espindolaa23008a2014-12-16 03:10:29 +0000891 if (ec)
Rafael Espindola369d5142014-12-16 02:53:35 +0000892 Mapping = 0;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000893}
894
895mapped_file_region::~mapped_file_region() {
Zachary Turneracd87912018-02-15 18:36:10 +0000896 if (Mapping) {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000897 ::UnmapViewOfFile(Mapping);
Zachary Turneracd87912018-02-15 18:36:10 +0000898
899 if (Mode == mapmode::readwrite) {
900 // There is a Windows kernel bug, the exact trigger conditions of which
901 // are not well understood. When triggered, dirty pages are not properly
902 // flushed and subsequent process's attempts to read a file can return
903 // invalid data. Calling FlushFileBuffers on the write handle is
904 // sufficient to ensure that this bug is not triggered.
905 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
906 if (FileHandle != INVALID_HANDLE_VALUE)
907 ::FlushFileBuffers(FileHandle);
908 }
909 }
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000910}
911
Roman Lebedev1e053ab2017-09-27 17:24:34 +0000912size_t mapped_file_region::size() const {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000913 assert(Mapping && "Mapping failed but used anyway!");
914 return Size;
915}
916
917char *mapped_file_region::data() const {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000918 assert(Mapping && "Mapping failed but used anyway!");
919 return reinterpret_cast<char*>(Mapping);
920}
921
922const char *mapped_file_region::const_data() const {
923 assert(Mapping && "Mapping failed but used anyway!");
924 return reinterpret_cast<const char*>(Mapping);
925}
926
927int mapped_file_region::alignment() {
928 SYSTEM_INFO SysInfo;
929 ::GetSystemInfo(&SysInfo);
930 return SysInfo.dwAllocationGranularity;
931}
932
Peter Collingbourneb4f1b882017-10-11 02:09:06 +0000933static basic_file_status status_from_find_data(WIN32_FIND_DATAW *FindData) {
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000934 return basic_file_status(file_type_from_attrs(FindData->dwFileAttributes),
935 perms_from_attrs(FindData->dwFileAttributes),
936 FindData->ftLastAccessTime.dwHighDateTime,
937 FindData->ftLastAccessTime.dwLowDateTime,
938 FindData->ftLastWriteTime.dwHighDateTime,
939 FindData->ftLastWriteTime.dwLowDateTime,
940 FindData->nFileSizeHigh, FindData->nFileSizeLow);
941}
942
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000943std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
Zachary Turner260bda32017-03-08 22:49:32 +0000944 StringRef path,
945 bool follow_symlinks) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000946 SmallVector<wchar_t, 128> path_utf16;
947
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000948 if (std::error_code ec = widenPath(path, path_utf16))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000949 return ec;
950
951 // Convert path to the format that Windows is happy with.
952 if (path_utf16.size() > 0 &&
953 !is_separator(path_utf16[path.size() - 1]) &&
954 path_utf16[path.size() - 1] != L':') {
955 path_utf16.push_back(L'\\');
956 path_utf16.push_back(L'*');
957 } else {
958 path_utf16.push_back(L'*');
959 }
960
961 // Get the first directory entry.
962 WIN32_FIND_DATAW FirstFind;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000963 ScopedFindHandle FindHandle(::FindFirstFileExW(
964 c_str(path_utf16), FindExInfoBasic, &FirstFind, FindExSearchNameMatch,
965 NULL, FIND_FIRST_EX_LARGE_FETCH));
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000966 if (!FindHandle)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000967 return mapWindowsError(::GetLastError());
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000968
Michael J. Spencer98879d72011-01-05 16:39:30 +0000969 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
970 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
971 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
972 FirstFind.cFileName[1] == L'.'))
973 if (!::FindNextFileW(FindHandle, &FirstFind)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000974 DWORD LastError = ::GetLastError();
Michael J. Spencer98879d72011-01-05 16:39:30 +0000975 // Check for end.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000976 if (LastError == ERROR_NO_MORE_FILES)
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000977 return detail::directory_iterator_destruct(it);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000978 return mapWindowsError(LastError);
Michael J. Spencer98879d72011-01-05 16:39:30 +0000979 } else
980 FilenameLen = ::wcslen(FirstFind.cFileName);
981
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000982 // Construct the current directory entry.
Michael J. Spencer98879d72011-01-05 16:39:30 +0000983 SmallString<128> directory_entry_name_utf8;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000984 if (std::error_code ec =
985 UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
986 directory_entry_name_utf8))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000987 return ec;
988
989 it.IterationHandle = intptr_t(FindHandle.take());
Michael J. Spencer98879d72011-01-05 16:39:30 +0000990 SmallString<128> directory_entry_path(path);
Yaron Keren92e1b622015-03-18 10:17:07 +0000991 path::append(directory_entry_path, directory_entry_name_utf8);
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000992 it.CurrentEntry = directory_entry(directory_entry_path, follow_symlinks,
993 status_from_find_data(&FirstFind));
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000994
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000995 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000996}
997
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000998std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000999 if (it.IterationHandle != 0)
1000 // Closes the handle if it's valid.
1001 ScopedFindHandle close(HANDLE(it.IterationHandle));
1002 it.IterationHandle = 0;
1003 it.CurrentEntry = directory_entry();
Rafael Espindolab4ad29b2014-06-13 02:36:09 +00001004 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001005}
1006
Rafael Espindolab4ad29b2014-06-13 02:36:09 +00001007std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001008 WIN32_FIND_DATAW FindData;
1009 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +00001010 DWORD LastError = ::GetLastError();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001011 // Check for end.
Rafael Espindolaa813d602014-06-11 03:58:34 +00001012 if (LastError == ERROR_NO_MORE_FILES)
Michael J. Spencer0a7625d2011-12-08 22:50:09 +00001013 return detail::directory_iterator_destruct(it);
Yaron Kerenf8e65172015-05-04 04:48:10 +00001014 return mapWindowsError(LastError);
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001015 }
1016
Michael J. Spencer98879d72011-01-05 16:39:30 +00001017 size_t FilenameLen = ::wcslen(FindData.cFileName);
1018 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
1019 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
1020 FindData.cFileName[1] == L'.'))
1021 return directory_iterator_increment(it);
1022
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001023 SmallString<128> directory_entry_path_utf8;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +00001024 if (std::error_code ec =
1025 UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
1026 directory_entry_path_utf8))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001027 return ec;
1028
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001029 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8),
1030 status_from_find_data(&FindData));
Rafael Espindolab4ad29b2014-06-13 02:36:09 +00001031 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001032}
1033
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001034ErrorOr<basic_file_status> directory_entry::status() const {
1035 return Status;
1036}
1037
Zachary Turner63db25b2018-06-04 19:38:11 +00001038static std::error_code nativeFileToFd(Expected<HANDLE> H, int &ResultFD,
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001039 OpenFlags Flags) {
1040 int CrtOpenFlags = 0;
1041 if (Flags & OF_Append)
1042 CrtOpenFlags |= _O_APPEND;
1043
1044 if (Flags & OF_Text)
1045 CrtOpenFlags |= _O_TEXT;
1046
Zachary Turner63db25b2018-06-04 19:38:11 +00001047 ResultFD = -1;
1048 if (!H)
1049 return errorToErrorCode(H.takeError());
1050
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001051 ResultFD = ::_open_osfhandle(intptr_t(*H), CrtOpenFlags);
Zachary Turner63db25b2018-06-04 19:38:11 +00001052 if (ResultFD == -1) {
1053 ::CloseHandle(*H);
1054 return mapWindowsError(ERROR_INVALID_HANDLE);
1055 }
1056 return std::error_code();
1057}
1058
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001059static DWORD nativeOpenFlags(OpenFlags Flags) {
1060 DWORD Result = 0;
1061 if (Flags & OF_Delete)
1062 Result |= FILE_FLAG_DELETE_ON_CLOSE;
1063
1064 if (Result == 0)
1065 Result = FILE_ATTRIBUTE_NORMAL;
1066 return Result;
Zachary Turner63db25b2018-06-04 19:38:11 +00001067}
1068
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001069static DWORD nativeDisposition(CreationDisposition Disp, OpenFlags Flags) {
1070 // This is a compatibility hack. Really we should respect the creation
1071 // disposition, but a lot of old code relied on the implicit assumption that
1072 // OF_Append implied it would open an existing file. Since the disposition is
1073 // now explicit and defaults to CD_CreateAlways, this assumption would cause
1074 // any usage of OF_Append to append to a new file, even if the file already
1075 // existed. A better solution might have two new creation dispositions:
1076 // CD_AppendAlways and CD_AppendNew. This would also address the problem of
1077 // OF_Append being used on a read-only descriptor, which doesn't make sense.
1078 if (Flags & OF_Append)
1079 return OPEN_ALWAYS;
Nick Kledzik18497e92012-06-20 00:28:54 +00001080
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001081 switch (Disp) {
1082 case CD_CreateAlways:
1083 return CREATE_ALWAYS;
1084 case CD_CreateNew:
1085 return CREATE_NEW;
1086 case CD_OpenAlways:
1087 return OPEN_ALWAYS;
1088 case CD_OpenExisting:
1089 return OPEN_EXISTING;
1090 }
1091 llvm_unreachable("unreachable!");
1092}
1093
1094static DWORD nativeAccess(FileAccess Access, OpenFlags Flags) {
1095 DWORD Result = 0;
1096 if (Access & FA_Read)
1097 Result |= GENERIC_READ;
1098 if (Access & FA_Write)
1099 Result |= GENERIC_WRITE;
1100 if (Flags & OF_Delete)
1101 Result |= DELETE;
1102 return Result;
1103}
1104
Zachary Turner9d2cfa62018-06-07 23:25:13 +00001105static std::error_code openNativeFileInternal(const Twine &Name,
1106 file_t &ResultFile, DWORD Disp,
1107 DWORD Access, DWORD Flags) {
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001108 SmallVector<wchar_t, 128> PathUTF16;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +00001109 if (std::error_code EC = widenPath(Name, PathUTF16))
Zachary Turner9d2cfa62018-06-07 23:25:13 +00001110 return EC;
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001111
Greg Bedwell7f68a712015-10-12 15:11:47 +00001112 HANDLE H =
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001113 ::CreateFileW(PathUTF16.begin(), Access,
Greg Bedwell7f68a712015-10-12 15:11:47 +00001114 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001115 NULL, Disp, Flags, NULL);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001116 if (H == INVALID_HANDLE_VALUE) {
Rafael Espindolaa813d602014-06-11 03:58:34 +00001117 DWORD LastError = ::GetLastError();
Yaron Kerenf8e65172015-05-04 04:48:10 +00001118 std::error_code EC = mapWindowsError(LastError);
Rafael Espindola331aeba2013-07-17 19:58:28 +00001119 // Provide a better error message when trying to open directories.
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001120 // This only runs if we failed to open the file, so there is probably
1121 // no performances issues.
Rafael Espindolaa813d602014-06-11 03:58:34 +00001122 if (LastError != ERROR_ACCESS_DENIED)
Zachary Turner9d2cfa62018-06-07 23:25:13 +00001123 return EC;
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001124 if (is_directory(Name))
Zachary Turner9d2cfa62018-06-07 23:25:13 +00001125 return make_error_code(errc::is_a_directory);
1126 return EC;
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001127 }
Zachary Turner9d2cfa62018-06-07 23:25:13 +00001128 ResultFile = H;
1129 return std::error_code();
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001130}
1131
Zachary Turner9d2cfa62018-06-07 23:25:13 +00001132Expected<file_t> openNativeFile(const Twine &Name, CreationDisposition Disp,
1133 FileAccess Access, OpenFlags Flags,
1134 unsigned Mode) {
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001135 // Verify that we don't have both "append" and "excl".
1136 assert((!(Disp == CD_CreateNew) || !(Flags & OF_Append)) &&
1137 "Cannot specify both 'CreateNew' and 'Append' file creation flags!");
1138
1139 DWORD NativeFlags = nativeOpenFlags(Flags);
1140 DWORD NativeDisp = nativeDisposition(Disp, Flags);
1141 DWORD NativeAccess = nativeAccess(Access, Flags);
1142
Zachary Turner9d2cfa62018-06-07 23:25:13 +00001143 file_t Result;
1144 std::error_code EC = openNativeFileInternal(Name, Result, NativeDisp,
1145 NativeAccess, NativeFlags);
1146 if (EC)
1147 return errorCodeToError(EC);
1148 return Result;
1149}
1150
1151std::error_code openFile(const Twine &Name, int &ResultFD,
1152 CreationDisposition Disp, FileAccess Access,
1153 OpenFlags Flags, unsigned int Mode) {
1154 Expected<file_t> Result = openNativeFile(Name, Disp, Access, Flags);
1155 if (!Result)
1156 return errorToErrorCode(Result.takeError());
1157
1158 return nativeFileToFd(*Result, ResultFD, Flags);
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001159}
1160
1161static std::error_code directoryRealPath(const Twine &Name,
1162 SmallVectorImpl<char> &RealPath) {
Zachary Turner9d2cfa62018-06-07 23:25:13 +00001163 file_t File;
1164 std::error_code EC = openNativeFileInternal(
1165 Name, File, OPEN_EXISTING, GENERIC_READ, FILE_FLAG_BACKUP_SEMANTICS);
1166 if (EC)
1167 return EC;
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001168
Zachary Turner9d2cfa62018-06-07 23:25:13 +00001169 EC = realPathFromHandle(File, RealPath);
1170 ::CloseHandle(File);
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001171 return EC;
1172}
1173
1174std::error_code openFileForRead(const Twine &Name, int &ResultFD,
1175 OpenFlags Flags,
1176 SmallVectorImpl<char> *RealPath) {
1177 Expected<HANDLE> NativeFile = openNativeFileForRead(Name, Flags, RealPath);
1178 return nativeFileToFd(std::move(NativeFile), ResultFD, OF_None);
1179}
1180
1181Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
1182 SmallVectorImpl<char> *RealPath) {
Zachary Turner9d2cfa62018-06-07 23:25:13 +00001183 Expected<file_t> Result =
1184 openNativeFile(Name, CD_OpenExisting, FA_Read, Flags);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001185
Taewook Ohd9153272016-06-13 15:54:56 +00001186 // Fetch the real name of the file, if the user asked
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001187 if (Result && RealPath)
1188 realPathFromHandle(*Result, *RealPath);
Taewook Ohd9153272016-06-13 15:54:56 +00001189
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001190 return std::move(Result);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001191}
Nick Kledzik18497e92012-06-20 00:28:54 +00001192
Zachary Turner63db25b2018-06-04 19:38:11 +00001193void closeFile(file_t &F) {
1194 ::CloseHandle(F);
1195 F = kInvalidFile;
Rafael Espindola67080ce2013-07-19 15:02:03 +00001196}
Taewook Ohd9153272016-06-13 15:54:56 +00001197
Zachary Turner260bda32017-03-08 22:49:32 +00001198std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1199 // Convert to utf-16.
1200 SmallVector<wchar_t, 128> Path16;
1201 std::error_code EC = widenPath(path, Path16);
1202 if (EC && !IgnoreErrors)
1203 return EC;
1204
1205 // SHFileOperation() accepts a list of paths, and so must be double null-
1206 // terminated to indicate the end of the list. The buffer is already null
1207 // terminated, but since that null character is not considered part of the
1208 // vector's size, pushing another one will just consume that byte. So we
1209 // need to push 2 null terminators.
1210 Path16.push_back(0);
1211 Path16.push_back(0);
1212
1213 SHFILEOPSTRUCTW shfos = {};
1214 shfos.wFunc = FO_DELETE;
1215 shfos.pFrom = Path16.data();
1216 shfos.fFlags = FOF_NO_UI;
1217
1218 int result = ::SHFileOperationW(&shfos);
1219 if (result != 0 && !IgnoreErrors)
1220 return mapWindowsError(result);
1221 return std::error_code();
1222}
1223
Zachary Turnere48ace62017-03-10 17:39:21 +00001224static void expandTildeExpr(SmallVectorImpl<char> &Path) {
1225 // Path does not begin with a tilde expression.
1226 if (Path.empty() || Path[0] != '~')
1227 return;
1228
1229 StringRef PathStr(Path.begin(), Path.size());
1230 PathStr = PathStr.drop_front();
Zachary Turner5c5091f2017-03-16 22:28:04 +00001231 StringRef Expr = PathStr.take_until([](char c) { return path::is_separator(c); });
Zachary Turnere48ace62017-03-10 17:39:21 +00001232
1233 if (!Expr.empty()) {
1234 // This is probably a ~username/ expression. Don't support this on Windows.
1235 return;
1236 }
1237
1238 SmallString<128> HomeDir;
1239 if (!path::home_directory(HomeDir)) {
1240 // For some reason we couldn't get the home directory. Just exit.
1241 return;
1242 }
1243
1244 // Overwrite the first character and insert the rest.
1245 Path[0] = HomeDir[0];
1246 Path.insert(Path.begin() + 1, HomeDir.begin() + 1, HomeDir.end());
1247}
1248
1249std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1250 bool expand_tilde) {
1251 dest.clear();
1252 if (path.isTriviallyEmpty())
1253 return std::error_code();
1254
1255 if (expand_tilde) {
1256 SmallString<128> Storage;
1257 path.toVector(Storage);
1258 expandTildeExpr(Storage);
1259 return real_path(Storage, dest, false);
1260 }
1261
1262 if (is_directory(path))
1263 return directoryRealPath(path, dest);
1264
1265 int fd;
Zachary Turner1f67a3c2018-06-07 19:58:58 +00001266 if (std::error_code EC =
1267 llvm::sys::fs::openFileForRead(path, fd, OF_None, &dest))
Zachary Turnere48ace62017-03-10 17:39:21 +00001268 return EC;
1269 ::close(fd);
1270 return std::error_code();
1271}
1272
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +00001273} // end namespace fs
Rui Ueyama471d0c52013-09-10 19:45:51 +00001274
Peter Collingbournef7d41012014-01-31 23:46:06 +00001275namespace path {
Pawel Bylica7c1f36a2015-11-02 14:57:24 +00001276static bool getKnownFolderPath(KNOWNFOLDERID folderId,
1277 SmallVectorImpl<char> &result) {
Pawel Bylica7187e4b2015-10-16 09:08:59 +00001278 wchar_t *path = nullptr;
1279 if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK)
1280 return false;
1281
1282 bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
1283 ::CoTaskMemFree(path);
1284 return ok;
1285}
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001286
1287bool getUserCacheDir(SmallVectorImpl<char> &Result) {
1288 return getKnownFolderPath(FOLDERID_LocalAppData, Result);
1289}
Pawel Bylica7187e4b2015-10-16 09:08:59 +00001290
Peter Collingbournef7d41012014-01-31 23:46:06 +00001291bool home_directory(SmallVectorImpl<char> &result) {
Pawel Bylica7187e4b2015-10-16 09:08:59 +00001292 return getKnownFolderPath(FOLDERID_Profile, result);
Peter Collingbournef7d41012014-01-31 23:46:06 +00001293}
1294
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001295static bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {
Pawel Bylica6e680b22015-11-06 23:44:23 +00001296 SmallVector<wchar_t, 1024> Buf;
1297 size_t Size = 1024;
1298 do {
1299 Buf.reserve(Size);
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001300 Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.capacity());
Pawel Bylica6e680b22015-11-06 23:44:23 +00001301 if (Size == 0)
1302 return false;
1303
1304 // Try again with larger buffer.
1305 } while (Size > Buf.capacity());
1306 Buf.set_size(Size);
1307
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001308 return !windows::UTF16ToUTF8(Buf.data(), Size, Res);
Pawel Bylica6e680b22015-11-06 23:44:23 +00001309}
1310
1311static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001312 const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};
1313 for (auto *Env : EnvironmentVariables) {
Pawel Bylica6e680b22015-11-06 23:44:23 +00001314 if (getTempDirEnvVar(Env, Res))
1315 return true;
1316 }
1317 return false;
1318}
1319
Rafael Espindola016a6d52014-08-26 14:47:52 +00001320void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1321 (void)ErasedOnReboot;
Pawel Bylica6e680b22015-11-06 23:44:23 +00001322 Result.clear();
Rafael Espindola016a6d52014-08-26 14:47:52 +00001323
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001324 // Check whether the temporary directory is specified by an environment var.
1325 // This matches GetTempPath logic to some degree. GetTempPath is not used
1326 // directly as it cannot handle evn var longer than 130 chars on Windows 7
1327 // (fixed on Windows 8).
1328 if (getTempDirEnvVar(Result)) {
1329 assert(!Result.empty() && "Unexpected empty path");
1330 native(Result); // Some Unix-like shells use Unix path separator in $TMP.
1331 fs::make_absolute(Result); // Make it absolute if not already.
Pawel Bylica6e680b22015-11-06 23:44:23 +00001332 return;
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001333 }
Rafael Espindola016a6d52014-08-26 14:47:52 +00001334
1335 // Fall back to a system default.
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001336 const char *DefaultResult = "C:\\Temp";
Rafael Espindola016a6d52014-08-26 14:47:52 +00001337 Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
1338}
Peter Collingbournef7d41012014-01-31 23:46:06 +00001339} // end namespace path
1340
Rui Ueyama471d0c52013-09-10 19:45:51 +00001341namespace windows {
Aaron Smith8a5ea612018-04-07 00:32:59 +00001342std::error_code CodePageToUTF16(unsigned codepage,
1343 llvm::StringRef original,
1344 llvm::SmallVectorImpl<wchar_t> &utf16) {
1345 if (!original.empty()) {
1346 int len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1347 original.size(), utf16.begin(), 0);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001348
Aaron Smith8a5ea612018-04-07 00:32:59 +00001349 if (len == 0) {
Yaron Kerenf8e65172015-05-04 04:48:10 +00001350 return mapWindowsError(::GetLastError());
Aaron Smith8a5ea612018-04-07 00:32:59 +00001351 }
Rui Ueyama471d0c52013-09-10 19:45:51 +00001352
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001353 utf16.reserve(len + 1);
1354 utf16.set_size(len);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001355
Aaron Smith8a5ea612018-04-07 00:32:59 +00001356 len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1357 original.size(), utf16.begin(), utf16.size());
Rui Ueyama471d0c52013-09-10 19:45:51 +00001358
Aaron Smith8a5ea612018-04-07 00:32:59 +00001359 if (len == 0) {
Yaron Kerenf8e65172015-05-04 04:48:10 +00001360 return mapWindowsError(::GetLastError());
Aaron Smith8a5ea612018-04-07 00:32:59 +00001361 }
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001362 }
Rui Ueyama471d0c52013-09-10 19:45:51 +00001363
1364 // Make utf16 null terminated.
1365 utf16.push_back(0);
1366 utf16.pop_back();
1367
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +00001368 return std::error_code();
Rui Ueyama471d0c52013-09-10 19:45:51 +00001369}
1370
Aaron Smith8a5ea612018-04-07 00:32:59 +00001371std::error_code UTF8ToUTF16(llvm::StringRef utf8,
1372 llvm::SmallVectorImpl<wchar_t> &utf16) {
1373 return CodePageToUTF16(CP_UTF8, utf8, utf16);
1374}
1375
1376std::error_code CurCPToUTF16(llvm::StringRef curcp,
1377 llvm::SmallVectorImpl<wchar_t> &utf16) {
1378 return CodePageToUTF16(CP_ACP, curcp, utf16);
1379}
1380
Rafael Espindola9c359662014-09-03 20:02:00 +00001381static
1382std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
1383 size_t utf16_len,
Aaron Smith8a5ea612018-04-07 00:32:59 +00001384 llvm::SmallVectorImpl<char> &converted) {
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001385 if (utf16_len) {
1386 // Get length.
Aaron Smith8a5ea612018-04-07 00:32:59 +00001387 int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.begin(),
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001388 0, NULL, NULL);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001389
Aaron Smith8a5ea612018-04-07 00:32:59 +00001390 if (len == 0) {
Yaron Kerenf8e65172015-05-04 04:48:10 +00001391 return mapWindowsError(::GetLastError());
Aaron Smith8a5ea612018-04-07 00:32:59 +00001392 }
Rui Ueyama471d0c52013-09-10 19:45:51 +00001393
Aaron Smith8a5ea612018-04-07 00:32:59 +00001394 converted.reserve(len);
1395 converted.set_size(len);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001396
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001397 // Now do the actual conversion.
Aaron Smith8a5ea612018-04-07 00:32:59 +00001398 len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.data(),
1399 converted.size(), NULL, NULL);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001400
Aaron Smith8a5ea612018-04-07 00:32:59 +00001401 if (len == 0) {
Yaron Kerenf8e65172015-05-04 04:48:10 +00001402 return mapWindowsError(::GetLastError());
Aaron Smith8a5ea612018-04-07 00:32:59 +00001403 }
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001404 }
Rui Ueyama471d0c52013-09-10 19:45:51 +00001405
Aaron Smith8a5ea612018-04-07 00:32:59 +00001406 // Make the new string null terminated.
1407 converted.push_back(0);
1408 converted.pop_back();
Rui Ueyama471d0c52013-09-10 19:45:51 +00001409
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +00001410 return std::error_code();
Rui Ueyama471d0c52013-09-10 19:45:51 +00001411}
Rafael Espindola9c359662014-09-03 20:02:00 +00001412
1413std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
1414 llvm::SmallVectorImpl<char> &utf8) {
1415 return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
1416}
1417
1418std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
Aaron Smith8a5ea612018-04-07 00:32:59 +00001419 llvm::SmallVectorImpl<char> &curcp) {
1420 return UTF16ToCodePage(CP_ACP, utf16, utf16_len, curcp);
Rafael Espindola9c359662014-09-03 20:02:00 +00001421}
Taewook Ohd9153272016-06-13 15:54:56 +00001422
Rui Ueyama471d0c52013-09-10 19:45:51 +00001423} // end namespace windows
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001424} // end namespace sys
1425} // end namespace llvm