blob: 3621ac4ad86f4ccfd14b90489795231f2100a5c1 [file] [log] [blame]
Rafael Espindolaf1fc3822013-06-26 19:33:03 +00001//===- llvm/Support/Windows/Path.inc - Windows Path Impl --------*- C++ -*-===//
Michael J. Spencerebad2f92010-11-29 22:28:51 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Rafael Espindolaf1fc3822013-06-26 19:33:03 +000010// This file implements the Windows specific implementation of the Path API.
Michael J. Spencerebad2f92010-11-29 22:28:51 +000011//
12//===----------------------------------------------------------------------===//
13
14//===----------------------------------------------------------------------===//
15//=== WARNING: Implementation here must contain only generic Windows code that
16//=== is guaranteed to work on *all* Windows variants.
17//===----------------------------------------------------------------------===//
18
Craig Topperf18edae2013-07-15 07:15:05 +000019#include "llvm/ADT/STLExtras.h"
Rafael Espindola5c4f8292014-06-11 19:05:50 +000020#include "llvm/Support/WindowsError.h"
Michael J. Spencerc20a0322010-12-03 17:54:07 +000021#include <fcntl.h>
Michael J. Spencer45710402010-12-03 01:21:28 +000022#include <io.h>
Michael J. Spencerc20a0322010-12-03 17:54:07 +000023#include <sys/stat.h>
24#include <sys/types.h>
Michael J. Spencerebad2f92010-11-29 22:28:51 +000025
NAKAMURA Takumi04d39d72014-02-12 11:50:22 +000026// These two headers must be included last, and make sure shlobj is required
27// after Windows.h to make sure it picks up our definition of _WIN32_WINNT
Reid Klecknerd59e2fa2014-02-12 21:26:20 +000028#include "WindowsSupport.h"
Zachary Turner260bda32017-03-08 22:49:32 +000029#include <shellapi.h>
NAKAMURA Takumi04d39d72014-02-12 11:50:22 +000030#include <shlobj.h>
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000031
Michael J. Spenceref2284f2012-08-15 19:05:47 +000032#undef max
33
Michael J. Spencer60252472010-12-03 18:03:28 +000034// MinGW doesn't define this.
Michael J. Spencer521c3212010-12-03 18:04:11 +000035#ifndef _ERRNO_T_DEFINED
36#define _ERRNO_T_DEFINED
37typedef int errno_t;
Michael J. Spencer60252472010-12-03 18:03:28 +000038#endif
39
Reid Kleckner11da0042013-08-07 20:19:31 +000040#ifdef _MSC_VER
41# pragma comment(lib, "advapi32.lib") // This provides CryptAcquireContextW.
Reid Kleckner304af562016-01-12 18:33:49 +000042# pragma comment(lib, "ole32.lib") // This provides CoTaskMemFree
Reid Kleckner11da0042013-08-07 20:19:31 +000043#endif
44
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000045using namespace llvm;
46
Rui Ueyama471d0c52013-09-10 19:45:51 +000047using llvm::sys::windows::UTF8ToUTF16;
Aaron Smith8a5ea612018-04-07 00:32:59 +000048using llvm::sys::windows::CurCPToUTF16;
Rui Ueyama471d0c52013-09-10 19:45:51 +000049using llvm::sys::windows::UTF16ToUTF8;
Paul Robinsonc38deee2014-11-24 18:05:29 +000050using llvm::sys::path::widenPath;
Rui Ueyama471d0c52013-09-10 19:45:51 +000051
Rafael Espindola37b012d2014-02-23 15:16:03 +000052static bool is_separator(const wchar_t value) {
53 switch (value) {
54 case L'\\':
55 case L'/':
56 return true;
57 default:
58 return false;
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +000059 }
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +000060}
61
Paul Robinsonc38deee2014-11-24 18:05:29 +000062namespace llvm {
63namespace sys {
64namespace path {
65
Aaron Smith8a5ea612018-04-07 00:32:59 +000066// Convert a (likely) UTF-8 path to UTF-16. Also, if the absolute equivalent of the
Paul Robinsond9c4a9a2014-11-13 00:12:14 +000067// path is longer than CreateDirectory can tolerate, make it absolute and
68// prefixed by '\\?\'.
Paul Robinsonc38deee2014-11-24 18:05:29 +000069std::error_code widenPath(const Twine &Path8,
70 SmallVectorImpl<wchar_t> &Path16) {
Paul Robinsond9c4a9a2014-11-13 00:12:14 +000071 const size_t MaxDirLen = MAX_PATH - 12; // Must leave room for 8.3 filename.
72
73 // Several operations would convert Path8 to SmallString; more efficient to
74 // do it once up front.
Aaron Smith8a5ea612018-04-07 00:32:59 +000075 SmallString<2*MAX_PATH> Path8Str;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +000076 Path8.toVector(Path8Str);
77
78 // If we made this path absolute, how much longer would it get?
79 size_t CurPathLen;
80 if (llvm::sys::path::is_absolute(Twine(Path8Str)))
81 CurPathLen = 0; // No contribution from current_path needed.
82 else {
83 CurPathLen = ::GetCurrentDirectoryW(0, NULL);
84 if (CurPathLen == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +000085 return mapWindowsError(::GetLastError());
Paul Robinsond9c4a9a2014-11-13 00:12:14 +000086 }
87
88 // Would the absolute path be longer than our limit?
89 if ((Path8Str.size() + CurPathLen) >= MaxDirLen &&
90 !Path8Str.startswith("\\\\?\\")) {
91 SmallString<2*MAX_PATH> FullPath("\\\\?\\");
92 if (CurPathLen) {
93 SmallString<80> CurPath;
94 if (std::error_code EC = llvm::sys::fs::current_path(CurPath))
95 return EC;
96 FullPath.append(CurPath);
97 }
Pirama Arumuga Nainar3d48bb52017-08-21 20:49:44 +000098 // Traverse the requested path, canonicalizing . and .. (because the \\?\
99 // prefix is documented to treat them as real components). Ignore
100 // separators, which can be returned from the iterator if the path has a
101 // drive name. We don't need to call native() on the result since append()
102 // always attaches preferred_separator.
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000103 for (llvm::sys::path::const_iterator I = llvm::sys::path::begin(Path8Str),
104 E = llvm::sys::path::end(Path8Str);
105 I != E; ++I) {
Pirama Arumuga Nainar3d48bb52017-08-21 20:49:44 +0000106 if (I->size() == 1 && is_separator((*I)[0]))
107 continue;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000108 if (I->size() == 1 && *I == ".")
109 continue;
110 if (I->size() == 2 && *I == "..")
111 llvm::sys::path::remove_filename(FullPath);
112 else
113 llvm::sys::path::append(FullPath, *I);
114 }
Aaron Smith8a5ea612018-04-07 00:32:59 +0000115 Path8Str = FullPath;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000116 }
117
Aaron Smith8a5ea612018-04-07 00:32:59 +0000118 // Path8Str now contains the full path or the original path
119 // If the conversion from UTF8 to UTF16 fails because of ERROR_NO_UNICODE_TRANSLATION,
120 // we also try using the current code page before giving up
121 auto ec = UTF8ToUTF16(Path8Str, Path16);
122 if (ec == mapWindowsError(ERROR_NO_UNICODE_TRANSLATION)) {
123 ec = CurCPToUTF16(Path8Str, Path16);
124 }
125 return ec;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000126}
Paul Robinsonc38deee2014-11-24 18:05:29 +0000127} // end namespace path
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000128
Michael J. Spencer20daa282010-12-07 01:22:31 +0000129namespace fs {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000130
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000131std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
David Majnemer17a44962013-10-07 09:52:36 +0000132 SmallVector<wchar_t, MAX_PATH> PathName;
133 DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
134
135 // A zero return value indicates a failure other than insufficient space.
136 if (Size == 0)
137 return "";
138
139 // Insufficient space is determined by a return value equal to the size of
140 // the buffer passed in.
141 if (Size == PathName.capacity())
142 return "";
143
144 // On success, GetModuleFileNameW returns the number of characters written to
145 // the buffer not including the NULL terminator.
146 PathName.set_size(Size);
147
148 // Convert the result from UTF-16 to UTF-8.
149 SmallVector<char, MAX_PATH> PathNameUTF8;
150 if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
151 return "";
152
153 return std::string(PathNameUTF8.data());
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000154}
155
Rafael Espindolad1230992013-07-29 21:55:38 +0000156UniqueID file_status::getUniqueID() const {
Rafael Espindola7f822a92013-07-29 21:26:49 +0000157 // The file is uniquely identified by the volume serial number along
158 // with the 64-bit file identifier.
159 uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
160 static_cast<uint64_t>(FileIndexLow);
161
162 return UniqueID(VolumeSerialNumber, FileID);
163}
Rafael Espindolae03dfd92013-06-26 05:01:35 +0000164
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000165ErrorOr<space_info> disk_space(const Twine &Path) {
166 ULARGE_INTEGER Avail, Total, Free;
167 if (!::GetDiskFreeSpaceExA(Path.str().c_str(), &Avail, &Total, &Free))
168 return mapWindowsError(::GetLastError());
169 space_info SpaceInfo;
170 SpaceInfo.capacity =
171 (static_cast<uint64_t>(Total.HighPart) << 32) + Total.LowPart;
Mehdi Amini64719152016-04-01 00:52:05 +0000172 SpaceInfo.free = (static_cast<uint64_t>(Free.HighPart) << 32) + Free.LowPart;
Mehdi Aminie2d8f1b2016-04-01 00:18:08 +0000173 SpaceInfo.available =
174 (static_cast<uint64_t>(Avail.HighPart) << 32) + Avail.LowPart;
175 return SpaceInfo;
176}
177
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000178TimePoint<> basic_file_status::getLastAccessedTime() const {
Pavel Labath757ca882016-10-24 10:59:17 +0000179 FILETIME Time;
180 Time.dwLowDateTime = LastAccessedTimeLow;
181 Time.dwHighDateTime = LastAccessedTimeHigh;
182 return toTimePoint(Time);
Mehdi Amini1e39ef32016-03-25 07:30:21 +0000183}
184
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000185TimePoint<> basic_file_status::getLastModificationTime() const {
Pavel Labath757ca882016-10-24 10:59:17 +0000186 FILETIME Time;
187 Time.dwLowDateTime = LastWriteTimeLow;
188 Time.dwHighDateTime = LastWriteTimeHigh;
189 return toTimePoint(Time);
Rafael Espindoladb5d8fe2013-06-20 18:42:04 +0000190}
191
Zachary Turner5821a3b2017-03-20 23:55:20 +0000192uint32_t file_status::getLinkCount() const {
193 return NumLinks;
194}
195
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000196std::error_code current_path(SmallVectorImpl<char> &result) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000197 SmallVector<wchar_t, MAX_PATH> cur_path;
198 DWORD len = MAX_PATH;
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000199
David Majnemer61eae2e2013-10-07 01:00:07 +0000200 do {
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000201 cur_path.reserve(len);
David Majnemer61eae2e2013-10-07 01:00:07 +0000202 len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000203
David Majnemer61eae2e2013-10-07 01:00:07 +0000204 // A zero return value indicates a failure other than insufficient space.
205 if (len == 0)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000206 return mapWindowsError(::GetLastError());
David Majnemer61eae2e2013-10-07 01:00:07 +0000207
208 // If there's insufficient space, the len returned is larger than the len
209 // given.
210 } while (len > cur_path.capacity());
211
212 // On success, GetCurrentDirectoryW returns the number of characters not
213 // including the null-terminator.
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000214 cur_path.set_size(len);
Aaron Ballmanb16cf532013-08-16 17:53:28 +0000215 return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
Michael J. Spencerebad2f92010-11-29 22:28:51 +0000216}
217
Pavel Labath2f096092017-01-24 10:32:03 +0000218std::error_code set_current_path(const Twine &path) {
219 // Convert to utf-16.
220 SmallVector<wchar_t, 128> wide_path;
221 if (std::error_code ec = widenPath(path, wide_path))
222 return ec;
223
224 if (!::SetCurrentDirectoryW(wide_path.begin()))
225 return mapWindowsError(::GetLastError());
226
227 return std::error_code();
228}
229
Frederic Riss6b9396c2015-08-06 21:04:55 +0000230std::error_code create_directory(const Twine &path, bool IgnoreExisting,
231 perms Perms) {
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000232 SmallVector<wchar_t, 128> path_utf16;
233
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000234 if (std::error_code ec = widenPath(path, path_utf16))
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000235 return ec;
236
237 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000238 DWORD LastError = ::GetLastError();
239 if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000240 return mapWindowsError(LastError);
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000241 }
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000242
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000243 return std::error_code();
Michael J. Spencer31e310c2010-12-03 05:42:11 +0000244}
245
Rafael Espindola83f858e2014-03-11 18:40:24 +0000246// We can't use symbolic links for windows.
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000247std::error_code create_link(const Twine &to, const Twine &from) {
Michael J. Spencere0c45602010-12-03 05:58:41 +0000248 // Convert to utf-16.
249 SmallVector<wchar_t, 128> wide_from;
250 SmallVector<wchar_t, 128> wide_to;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000251 if (std::error_code ec = widenPath(from, wide_from))
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000252 return ec;
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000253 if (std::error_code ec = widenPath(to, wide_to))
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000254 return ec;
Michael J. Spencere0c45602010-12-03 05:58:41 +0000255
256 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
Yaron Kerenf8e65172015-05-04 04:48:10 +0000257 return mapWindowsError(::GetLastError());
Michael J. Spencere0c45602010-12-03 05:58:41 +0000258
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000259 return std::error_code();
Michael J. Spencere0c45602010-12-03 05:58:41 +0000260}
261
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000262std::error_code create_hard_link(const Twine &to, const Twine &from) {
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +0000263 return create_link(to, from);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000264}
265
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000266std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000267 SmallVector<wchar_t, 128> path_utf16;
268
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000269 if (std::error_code ec = widenPath(path, path_utf16))
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000270 return ec;
271
Peter Collingbourne0f9e8892017-10-10 19:39:46 +0000272 // We don't know whether this is a file or a directory, and remove() can
273 // accept both. The usual way to delete a file or directory is to use one of
274 // the DeleteFile or RemoveDirectory functions, but that requires you to know
275 // which one it is. We could stat() the file to determine that, but that would
276 // cost us additional system calls, which can be slow in a directory
277 // containing a large number of files. So instead we call CreateFile directly.
278 // The important part is the FILE_FLAG_DELETE_ON_CLOSE flag, which causes the
279 // file to be deleted once it is closed. We also use the flags
280 // FILE_FLAG_BACKUP_SEMANTICS (which allows us to open directories), and
281 // FILE_FLAG_OPEN_REPARSE_POINT (don't follow symlinks).
282 ScopedFileHandle h(::CreateFileW(
283 c_str(path_utf16), DELETE,
284 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
285 OPEN_EXISTING,
286 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS |
287 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_DELETE_ON_CLOSE,
288 NULL));
289 if (!h) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000290 std::error_code EC = mapWindowsError(::GetLastError());
Rafael Espindola2a826e42014-06-13 17:20:48 +0000291 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
Rafael Espindola5c20ac02014-02-23 13:56:14 +0000292 return EC;
293 }
Peter Collingbourne0f9e8892017-10-10 19:39:46 +0000294
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000295 return std::error_code();
Michael J. Spencer6e74e112010-12-03 17:53:43 +0000296}
297
Zachary Turner392ed9d2017-02-21 20:55:47 +0000298static std::error_code is_local_internal(SmallVectorImpl<wchar_t> &Path,
299 bool &Result) {
300 SmallVector<wchar_t, 128> VolumePath;
301 size_t Len = 128;
302 while (true) {
303 VolumePath.resize(Len);
304 BOOL Success =
305 ::GetVolumePathNameW(Path.data(), VolumePath.data(), VolumePath.size());
306
307 if (Success)
308 break;
309
310 DWORD Err = ::GetLastError();
311 if (Err != ERROR_INSUFFICIENT_BUFFER)
312 return mapWindowsError(Err);
313
314 Len *= 2;
315 }
316 // If the output buffer has exactly enough space for the path name, but not
317 // the null terminator, it will leave the output unterminated. Push a null
318 // terminator onto the end to ensure that this never happens.
319 VolumePath.push_back(L'\0');
320 VolumePath.set_size(wcslen(VolumePath.data()));
321 const wchar_t *P = VolumePath.data();
322
323 UINT Type = ::GetDriveTypeW(P);
324 switch (Type) {
325 case DRIVE_FIXED:
326 Result = true;
327 return std::error_code();
328 case DRIVE_REMOTE:
329 case DRIVE_CDROM:
330 case DRIVE_RAMDISK:
331 case DRIVE_REMOVABLE:
332 Result = false;
333 return std::error_code();
334 default:
335 return make_error_code(errc::no_such_file_or_directory);
336 }
337 llvm_unreachable("Unreachable!");
338}
339
340std::error_code is_local(const Twine &path, bool &result) {
341 if (!llvm::sys::fs::exists(path) || !llvm::sys::path::has_root_path(path))
342 return make_error_code(errc::no_such_file_or_directory);
343
344 SmallString<128> Storage;
345 StringRef P = path.toStringRef(Storage);
346
347 // Convert to utf-16.
348 SmallVector<wchar_t, 128> WidePath;
349 if (std::error_code ec = widenPath(P, WidePath))
350 return ec;
351 return is_local_internal(WidePath, result);
352}
353
Rafael Espindola041299e2017-11-18 02:05:59 +0000354static std::error_code realPathFromHandle(HANDLE H,
Rafael Espindola8dc0e102017-11-18 02:12:53 +0000355 SmallVectorImpl<wchar_t> &Buffer) {
356 DWORD CountChars = ::GetFinalPathNameByHandleW(
357 H, Buffer.begin(), Buffer.capacity() - 1, FILE_NAME_NORMALIZED);
358 if (CountChars > Buffer.capacity()) {
359 // The buffer wasn't big enough, try again. In this case the return value
360 // *does* indicate the size of the null terminator.
361 Buffer.reserve(CountChars);
362 CountChars = ::GetFinalPathNameByHandleW(
363 H, Buffer.data(), Buffer.capacity() - 1, FILE_NAME_NORMALIZED);
364 }
365 if (CountChars == 0)
366 return mapWindowsError(GetLastError());
367 Buffer.set_size(CountChars);
368 return std::error_code();
369}
370
371static std::error_code realPathFromHandle(HANDLE H,
372 SmallVectorImpl<char> &RealPath) {
373 RealPath.clear();
374 SmallVector<wchar_t, MAX_PATH> Buffer;
375 if (std::error_code EC = realPathFromHandle(H, Buffer))
376 return EC;
377
378 const wchar_t *Data = Buffer.data();
379 DWORD CountChars = Buffer.size();
380 if (CountChars >= 4) {
381 if (0 == ::memcmp(Data, L"\\\\?\\", 8)) {
382 CountChars -= 4;
383 Data += 4;
384 }
385 }
386
387 // Convert the result from UTF-16 to UTF-8.
388 return UTF16ToUTF8(Data, CountChars, RealPath);
389}
Rafael Espindola041299e2017-11-18 02:05:59 +0000390
Zachary Turner392ed9d2017-02-21 20:55:47 +0000391std::error_code is_local(int FD, bool &Result) {
392 SmallVector<wchar_t, 128> FinalPath;
393 HANDLE Handle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
394
Rafael Espindola041299e2017-11-18 02:05:59 +0000395 if (std::error_code EC = realPathFromHandle(Handle, FinalPath))
396 return EC;
Zachary Turner392ed9d2017-02-21 20:55:47 +0000397
398 return is_local_internal(FinalPath, Result);
399}
400
Rafael Espindola20569e92017-12-05 16:40:56 +0000401static std::error_code setDeleteDisposition(HANDLE Handle, bool Delete) {
402 FILE_DISPOSITION_INFO Disposition;
403 Disposition.DeleteFile = Delete;
404 if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
405 sizeof(Disposition)))
406 return mapWindowsError(::GetLastError());
407 return std::error_code();
408}
409
410static std::error_code removeFD(int FD) {
411 HANDLE Handle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
412 return setDeleteDisposition(Handle, true);
413}
414
Rafael Espindola3ecd2042017-11-28 01:41:22 +0000415/// In order to handle temporary files we want the following properties
416///
417/// * The temporary file is deleted on crashes
418/// * We can use (read, rename, etc) the temporary file.
419/// * We can cancel the delete to keep the file.
420///
421/// Using FILE_DISPOSITION_INFO with DeleteFile=true will create a file that is
422/// deleted on close, but it has a few problems:
423///
424/// * The file cannot be used. An attempt to open or rename the file will fail.
425/// This makes the temporary file almost useless, as it cannot be part of
426/// any other CreateFileW call in the current or in another process.
427/// * It is not atomic. A crash just after CreateFileW or just after canceling
428/// the delete will leave the file on disk.
429///
430/// Using FILE_FLAG_DELETE_ON_CLOSE solves the first issues and the first part
431/// of the second one, but there is no way to cancel it in place. What works is
432/// to create a second handle to prevent the deletion, close the first one and
433/// then clear DeleteFile with SetFileInformationByHandle. This requires
434/// changing the handle and file descriptor the caller uses.
435static std::error_code cancelDeleteOnClose(int &FD) {
436 HANDLE Handle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
437 SmallVector<wchar_t, MAX_PATH> Name;
438 if (std::error_code EC = realPathFromHandle(Handle, Name))
439 return EC;
440 HANDLE NewHandle =
441 ::CreateFileW(Name.data(), GENERIC_READ | GENERIC_WRITE | DELETE,
442 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
443 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
444 if (NewHandle == INVALID_HANDLE_VALUE)
445 return mapWindowsError(::GetLastError());
446 if (close(FD))
447 return mapWindowsError(::GetLastError());
448
Rafael Espindola20569e92017-12-05 16:40:56 +0000449 if (std::error_code EC = setDeleteDisposition(NewHandle, false))
450 return EC;
451
Rafael Espindola3ecd2042017-11-28 01:41:22 +0000452 FD = ::_open_osfhandle(intptr_t(NewHandle), 0);
453 if (FD == -1) {
454 ::CloseHandle(NewHandle);
455 return mapWindowsError(ERROR_INVALID_HANDLE);
456 }
457 return std::error_code();
458}
459
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000460static std::error_code rename_internal(HANDLE FromHandle, const Twine &To,
461 bool ReplaceIfExists) {
462 SmallVector<wchar_t, 0> ToWide;
463 if (auto EC = widenPath(To, ToWide))
464 return EC;
465
466 std::vector<char> RenameInfoBuf(sizeof(FILE_RENAME_INFO) - sizeof(wchar_t) +
467 (ToWide.size() * sizeof(wchar_t)));
468 FILE_RENAME_INFO &RenameInfo =
469 *reinterpret_cast<FILE_RENAME_INFO *>(RenameInfoBuf.data());
470 RenameInfo.ReplaceIfExists = ReplaceIfExists;
471 RenameInfo.RootDirectory = 0;
472 RenameInfo.FileNameLength = ToWide.size();
Adrian McCarthye6275c62017-10-09 17:50:01 +0000473 std::copy(ToWide.begin(), ToWide.end(), &RenameInfo.FileName[0]);
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000474
Hans Wennborg477c9742017-10-12 17:38:22 +0000475 SetLastError(ERROR_SUCCESS);
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000476 if (!SetFileInformationByHandle(FromHandle, FileRenameInfo, &RenameInfo,
Hans Wennborg477c9742017-10-12 17:38:22 +0000477 RenameInfoBuf.size())) {
478 unsigned Error = GetLastError();
479 if (Error == ERROR_SUCCESS)
480 Error = ERROR_CALL_NOT_IMPLEMENTED; // Wine doesn't always set error code.
481 return mapWindowsError(Error);
482 }
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000483
484 return std::error_code();
485}
486
Rafael Espindola5908aff2017-11-21 01:52:44 +0000487static std::error_code rename_handle(HANDLE FromHandle, const Twine &To) {
488 SmallVector<wchar_t, 128> WideTo;
489 if (std::error_code EC = widenPath(To, WideTo))
490 return EC;
491
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000492 // We normally expect this loop to succeed after a few iterations. If it
493 // requires more than 200 tries, it's more likely that the failures are due to
494 // a true error, so stop trying.
495 for (unsigned Retry = 0; Retry != 200; ++Retry) {
496 auto EC = rename_internal(FromHandle, To, true);
Hans Wennborg17701ab2017-10-11 22:04:14 +0000497
498 if (EC ==
499 std::error_code(ERROR_CALL_NOT_IMPLEMENTED, std::system_category())) {
500 // Wine doesn't support SetFileInformationByHandle in rename_internal.
501 // Fall back to MoveFileEx.
Rafael Espindola5908aff2017-11-21 01:52:44 +0000502 SmallVector<wchar_t, MAX_PATH> WideFrom;
503 if (std::error_code EC2 = realPathFromHandle(FromHandle, WideFrom))
504 return EC2;
Hans Wennborg17701ab2017-10-11 22:04:14 +0000505 if (::MoveFileExW(WideFrom.begin(), WideTo.begin(),
506 MOVEFILE_REPLACE_EXISTING))
507 return std::error_code();
508 return mapWindowsError(GetLastError());
509 }
510
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000511 if (!EC || EC != errc::permission_denied)
512 return EC;
Greg Bedwell7f68a712015-10-12 15:11:47 +0000513
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000514 // The destination file probably exists and is currently open in another
515 // process, either because the file was opened without FILE_SHARE_DELETE or
516 // it is mapped into memory (e.g. using MemoryBuffer). Rename it in order to
517 // move it out of the way of the source file. Use FILE_FLAG_DELETE_ON_CLOSE
518 // to arrange for the destination file to be deleted when the other process
519 // closes it.
520 ScopedFileHandle ToHandle(
521 ::CreateFileW(WideTo.begin(), GENERIC_READ | DELETE,
522 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
523 NULL, OPEN_EXISTING,
524 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL));
525 if (!ToHandle) {
526 auto EC = mapWindowsError(GetLastError());
527 // Another process might have raced with us and moved the existing file
528 // out of the way before we had a chance to open it. If that happens, try
529 // to rename the source file again.
530 if (EC == errc::no_such_file_or_directory)
Sunil Srivastava34fce932016-03-25 23:41:28 +0000531 continue;
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000532 return EC;
Sunil Srivastava34fce932016-03-25 23:41:28 +0000533 }
Greg Bedwell7f68a712015-10-12 15:11:47 +0000534
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000535 BY_HANDLE_FILE_INFORMATION FI;
536 if (!GetFileInformationByHandle(ToHandle, &FI))
537 return mapWindowsError(GetLastError());
Greg Bedwell7f68a712015-10-12 15:11:47 +0000538
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000539 // Try to find a unique new name for the destination file.
540 for (unsigned UniqueId = 0; UniqueId != 200; ++UniqueId) {
541 std::string TmpFilename = (To + ".tmp" + utostr(UniqueId)).str();
542 if (auto EC = rename_internal(ToHandle, TmpFilename, false)) {
543 if (EC == errc::file_exists || EC == errc::permission_denied) {
544 // Again, another process might have raced with us and moved the file
545 // before we could move it. Check whether this is the case, as it
546 // might have caused the permission denied error. If that was the
547 // case, we don't need to move it ourselves.
548 ScopedFileHandle ToHandle2(::CreateFileW(
549 WideTo.begin(), 0,
550 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
551 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
552 if (!ToHandle2) {
553 auto EC = mapWindowsError(GetLastError());
554 if (EC == errc::no_such_file_or_directory)
555 break;
556 return EC;
557 }
558 BY_HANDLE_FILE_INFORMATION FI2;
559 if (!GetFileInformationByHandle(ToHandle2, &FI2))
560 return mapWindowsError(GetLastError());
561 if (FI.nFileIndexHigh != FI2.nFileIndexHigh ||
562 FI.nFileIndexLow != FI2.nFileIndexLow ||
563 FI.dwVolumeSerialNumber != FI2.dwVolumeSerialNumber)
564 break;
565 continue;
566 }
567 return EC;
568 }
569 break;
570 }
571
572 // Okay, the old destination file has probably been moved out of the way at
573 // this point, so try to rename the source file again. Still, another
574 // process might have raced with us to create and open the destination
575 // file, so we need to keep doing this until we succeed.
NAKAMURA Takumi3b7f9952012-05-08 14:31:46 +0000576 }
Michael J. Spencer409f5562010-12-03 17:53:55 +0000577
Peter Collingbourne80e31f12017-10-06 17:14:36 +0000578 // The most likely root cause.
579 return errc::permission_denied;
Michael J. Spencer409f5562010-12-03 17:53:55 +0000580}
581
Rafael Espindola3ecd2042017-11-28 01:41:22 +0000582static std::error_code rename_fd(int FromFD, const Twine &To) {
583 HANDLE FromHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FromFD));
584 return rename_handle(FromHandle, To);
585}
586
Rafael Espindola811d5e82017-11-21 05:35:45 +0000587std::error_code rename(const Twine &From, const Twine &To) {
588 // Convert to utf-16.
589 SmallVector<wchar_t, 128> WideFrom;
590 if (std::error_code EC = widenPath(From, WideFrom))
591 return EC;
592
593 ScopedFileHandle FromHandle;
594 // Retry this a few times to defeat badly behaved file system scanners.
595 for (unsigned Retry = 0; Retry != 200; ++Retry) {
596 if (Retry != 0)
597 ::Sleep(10);
598 FromHandle =
599 ::CreateFileW(WideFrom.begin(), GENERIC_READ | DELETE,
600 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
601 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
602 if (FromHandle)
603 break;
604 }
605 if (!FromHandle)
606 return mapWindowsError(GetLastError());
607
608 return rename_handle(FromHandle, To);
609}
610
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000611std::error_code resize_file(int FD, uint64_t Size) {
Michael J. Spencerca242f22010-12-03 18:48:56 +0000612#ifdef HAVE__CHSIZE_S
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000613 errno_t error = ::_chsize_s(FD, Size);
Michael J. Spencerca242f22010-12-03 18:48:56 +0000614#else
Rafael Espindola59aaa6c2014-12-12 17:55:12 +0000615 errno_t error = ::_chsize(FD, Size);
Michael J. Spencerca242f22010-12-03 18:48:56 +0000616#endif
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000617 return std::error_code(error, std::generic_category());
Michael J. Spencerc20a0322010-12-03 17:54:07 +0000618}
619
Rafael Espindola281f23a2014-09-11 20:30:02 +0000620std::error_code access(const Twine &Path, AccessMode Mode) {
Rafael Espindola281f23a2014-09-11 20:30:02 +0000621 SmallVector<wchar_t, 128> PathUtf16;
Michael J. Spencer45710402010-12-03 01:21:28 +0000622
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000623 if (std::error_code EC = widenPath(Path, PathUtf16))
Rafael Espindola281f23a2014-09-11 20:30:02 +0000624 return EC;
Michael J. Spencer45710402010-12-03 01:21:28 +0000625
Rafael Espindola281f23a2014-09-11 20:30:02 +0000626 DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
Michael J. Spencer45710402010-12-03 01:21:28 +0000627
Rafael Espindola281f23a2014-09-11 20:30:02 +0000628 if (Attributes == INVALID_FILE_ATTRIBUTES) {
Michael J. Spencer45710402010-12-03 01:21:28 +0000629 // See if the file didn't actually exist.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000630 DWORD LastError = ::GetLastError();
631 if (LastError != ERROR_FILE_NOT_FOUND &&
632 LastError != ERROR_PATH_NOT_FOUND)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000633 return mapWindowsError(LastError);
Rafael Espindola281f23a2014-09-11 20:30:02 +0000634 return errc::no_such_file_or_directory;
635 }
636
637 if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
638 return errc::permission_denied;
639
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000640 return std::error_code();
Michael J. Spencer45710402010-12-03 01:21:28 +0000641}
642
Reid Kleckner89d4b1a2015-09-10 23:28:06 +0000643bool can_execute(const Twine &Path) {
644 return !access(Path, AccessMode::Execute) ||
645 !access(Path + ".exe", AccessMode::Execute);
646}
647
Michael J. Spencer203d7802011-12-12 06:04:28 +0000648bool equivalent(file_status A, file_status B) {
649 assert(status_known(A) && status_known(B));
Mehdi Amini1e39ef32016-03-25 07:30:21 +0000650 return A.FileIndexHigh == B.FileIndexHigh &&
651 A.FileIndexLow == B.FileIndexLow &&
652 A.FileSizeHigh == B.FileSizeHigh &&
653 A.FileSizeLow == B.FileSizeLow &&
654 A.LastAccessedTimeHigh == B.LastAccessedTimeHigh &&
655 A.LastAccessedTimeLow == B.LastAccessedTimeLow &&
656 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
657 A.LastWriteTimeLow == B.LastWriteTimeLow &&
658 A.VolumeSerialNumber == B.VolumeSerialNumber;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000659}
660
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000661std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
Michael J. Spencer203d7802011-12-12 06:04:28 +0000662 file_status fsA, fsB;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000663 if (std::error_code ec = status(A, fsA))
664 return ec;
665 if (std::error_code ec = status(B, fsB))
666 return ec;
Michael J. Spencer203d7802011-12-12 06:04:28 +0000667 result = equivalent(fsA, fsB);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000668 return std::error_code();
Michael J. Spencer376d3872010-12-03 18:49:13 +0000669}
670
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000671static bool isReservedName(StringRef path) {
672 // This list of reserved names comes from MSDN, at:
673 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
Craig Topper26260942015-10-18 05:15:34 +0000674 static const char *const sReservedNames[] = { "nul", "con", "prn", "aux",
675 "com1", "com2", "com3", "com4",
676 "com5", "com6", "com7", "com8",
677 "com9", "lpt1", "lpt2", "lpt3",
678 "lpt4", "lpt5", "lpt6", "lpt7",
679 "lpt8", "lpt9" };
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000680
681 // First, check to see if this is a device namespace, which always
682 // starts with \\.\, since device namespaces are not legal file paths.
683 if (path.startswith("\\\\.\\"))
684 return true;
685
Douglas Yung091d8fd2016-05-03 00:12:59 +0000686 // Then compare against the list of ancient reserved names.
Craig Topper58713212013-07-15 04:27:47 +0000687 for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000688 if (path.equals_lower(sReservedNames[i]))
689 return true;
690 }
691
692 // The path isn't what we consider reserved.
693 return false;
694}
695
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000696static file_type file_type_from_attrs(DWORD Attrs) {
697 return (Attrs & FILE_ATTRIBUTE_DIRECTORY) ? file_type::directory_file
698 : file_type::regular_file;
699}
700
701static perms perms_from_attrs(DWORD Attrs) {
702 return (Attrs & FILE_ATTRIBUTE_READONLY) ? (all_read | all_exe) : all_all;
703}
704
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000705static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000706 if (FileHandle == INVALID_HANDLE_VALUE)
707 goto handle_status_error;
708
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000709 switch (::GetFileType(FileHandle)) {
710 default:
Rafael Espindola81177c52013-07-18 18:42:52 +0000711 llvm_unreachable("Don't know anything about this file type");
712 case FILE_TYPE_UNKNOWN: {
713 DWORD Err = ::GetLastError();
714 if (Err != NO_ERROR)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000715 return mapWindowsError(Err);
Rafael Espindola81177c52013-07-18 18:42:52 +0000716 Result = file_status(file_type::type_unknown);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000717 return std::error_code();
Rafael Espindola81177c52013-07-18 18:42:52 +0000718 }
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000719 case FILE_TYPE_DISK:
720 break;
721 case FILE_TYPE_CHAR:
722 Result = file_status(file_type::character_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000723 return std::error_code();
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000724 case FILE_TYPE_PIPE:
725 Result = file_status(file_type::fifo_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000726 return std::error_code();
NAKAMURA Takumi8b01da42013-07-18 17:00:54 +0000727 }
728
Rafael Espindola77021c92013-07-16 03:20:13 +0000729 BY_HANDLE_FILE_INFORMATION Info;
730 if (!::GetFileInformationByHandle(FileHandle, &Info))
731 goto handle_status_error;
732
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000733 Result = file_status(
734 file_type_from_attrs(Info.dwFileAttributes),
735 perms_from_attrs(Info.dwFileAttributes), Info.nNumberOfLinks,
736 Info.ftLastAccessTime.dwHighDateTime, Info.ftLastAccessTime.dwLowDateTime,
737 Info.ftLastWriteTime.dwHighDateTime, Info.ftLastWriteTime.dwLowDateTime,
738 Info.dwVolumeSerialNumber, Info.nFileSizeHigh, Info.nFileSizeLow,
739 Info.nFileIndexHigh, Info.nFileIndexLow);
740 return std::error_code();
Aaron Ballman345012d2017-03-13 12:24:51 +0000741
Rafael Espindola77021c92013-07-16 03:20:13 +0000742handle_status_error:
Rafael Espindolaa813d602014-06-11 03:58:34 +0000743 DWORD LastError = ::GetLastError();
744 if (LastError == ERROR_FILE_NOT_FOUND ||
745 LastError == ERROR_PATH_NOT_FOUND)
Rafael Espindola77021c92013-07-16 03:20:13 +0000746 Result = file_status(file_type::file_not_found);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000747 else if (LastError == ERROR_SHARING_VIOLATION)
Rafael Espindola77021c92013-07-16 03:20:13 +0000748 Result = file_status(file_type::type_unknown);
Rafael Espindola107b74c2013-07-31 00:10:25 +0000749 else
Rafael Espindola77021c92013-07-16 03:20:13 +0000750 Result = file_status(file_type::status_error);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000751 return mapWindowsError(LastError);
Rafael Espindola77021c92013-07-16 03:20:13 +0000752}
753
Zachary Turner82dd5422017-03-07 16:10:10 +0000754std::error_code status(const Twine &path, file_status &result, bool Follow) {
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000755 SmallString<128> path_storage;
756 SmallVector<wchar_t, 128> path_utf16;
757
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000758 StringRef path8 = path.toStringRef(path_storage);
Benjamin Kramer58994ec2011-08-20 21:36:38 +0000759 if (isReservedName(path8)) {
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000760 result = file_status(file_type::character_file);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000761 return std::error_code();
NAKAMURA Takumia3d47492011-03-16 02:53:32 +0000762 }
763
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000764 if (std::error_code ec = widenPath(path8, path_utf16))
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000765 return ec;
766
767 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
768 if (attr == INVALID_FILE_ATTRIBUTES)
Rafael Espindola77021c92013-07-16 03:20:13 +0000769 return getStatus(INVALID_HANDLE_VALUE, result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000770
Zachary Turner82dd5422017-03-07 16:10:10 +0000771 DWORD Flags = FILE_FLAG_BACKUP_SEMANTICS;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000772 // Handle reparse points.
Zachary Turner82dd5422017-03-07 16:10:10 +0000773 if (!Follow && (attr & FILE_ATTRIBUTE_REPARSE_POINT))
774 Flags |= FILE_FLAG_OPEN_REPARSE_POINT;
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000775
Rafael Espindolaa5932af2013-07-30 20:25:53 +0000776 ScopedFileHandle h(
777 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
Michael J. Spencer203d7802011-12-12 06:04:28 +0000778 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
Zachary Turner82dd5422017-03-07 16:10:10 +0000779 NULL, OPEN_EXISTING, Flags, 0));
780 if (!h)
781 return getStatus(INVALID_HANDLE_VALUE, result);
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000782
Zachary Turner82dd5422017-03-07 16:10:10 +0000783 return getStatus(h, result);
Rafael Espindola77021c92013-07-16 03:20:13 +0000784}
Michael J. Spencerdb5576a2010-12-04 00:32:40 +0000785
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000786std::error_code status(int FD, file_status &Result) {
Rafael Espindola77021c92013-07-16 03:20:13 +0000787 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
Aaron Ballman345012d2017-03-13 12:24:51 +0000788 return getStatus(FileHandle, Result);
789}
790
James Henderson566fdf42017-03-16 11:22:09 +0000791std::error_code setPermissions(const Twine &Path, perms Permissions) {
792 SmallVector<wchar_t, 128> PathUTF16;
793 if (std::error_code EC = widenPath(Path, PathUTF16))
794 return EC;
795
796 DWORD Attributes = ::GetFileAttributesW(PathUTF16.begin());
797 if (Attributes == INVALID_FILE_ATTRIBUTES)
798 return mapWindowsError(GetLastError());
799
800 // There are many Windows file attributes that are not to do with the file
801 // permissions (e.g. FILE_ATTRIBUTE_HIDDEN). We need to be careful to preserve
802 // them.
803 if (Permissions & all_write) {
804 Attributes &= ~FILE_ATTRIBUTE_READONLY;
805 if (Attributes == 0)
806 // FILE_ATTRIBUTE_NORMAL indicates no other attributes are set.
807 Attributes |= FILE_ATTRIBUTE_NORMAL;
808 }
809 else {
810 Attributes |= FILE_ATTRIBUTE_READONLY;
811 // FILE_ATTRIBUTE_NORMAL is not compatible with any other attributes, so
812 // remove it, if it is present.
813 Attributes &= ~FILE_ATTRIBUTE_NORMAL;
814 }
815
816 if (!::SetFileAttributesW(PathUTF16.begin(), Attributes))
817 return mapWindowsError(GetLastError());
818
819 return std::error_code();
820}
821
Aaron Ballman345012d2017-03-13 12:24:51 +0000822std::error_code setLastModificationAndAccessTime(int FD, TimePoint<> Time) {
823 FILETIME FT = toFILETIME(Time);
824 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000825 if (!SetFileTime(FileHandle, NULL, &FT, &FT))
Yaron Kerenf8e65172015-05-04 04:48:10 +0000826 return mapWindowsError(::GetLastError());
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000827 return std::error_code();
Rafael Espindola4a3365c2013-06-20 20:56:14 +0000828}
Nick Kledzik18497e92012-06-20 00:28:54 +0000829
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000830std::error_code mapped_file_region::init(int FD, uint64_t Offset,
831 mapmode Mode) {
Zachary Turneracd87912018-02-15 18:36:10 +0000832 this->FD = FD;
833 this->Mode = Mode;
Rafael Espindolaa23008a2014-12-16 03:10:29 +0000834 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
835 if (FileHandle == INVALID_HANDLE_VALUE)
836 return make_error_code(errc::bad_file_descriptor);
837
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000838 DWORD flprotect;
839 switch (Mode) {
840 case readonly: flprotect = PAGE_READONLY; break;
841 case readwrite: flprotect = PAGE_READWRITE; break;
842 case priv: flprotect = PAGE_WRITECOPY; break;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000843 }
844
Rafael Espindola369d5142014-12-16 02:53:35 +0000845 HANDLE FileMappingHandle =
David Majnemer17a44962013-10-07 09:52:36 +0000846 ::CreateFileMappingW(FileHandle, 0, flprotect,
Zachary Turnerab1ade42017-11-16 22:39:55 +0000847 Hi_32(Size),
848 Lo_32(Size),
David Majnemer17a44962013-10-07 09:52:36 +0000849 0);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000850 if (FileMappingHandle == NULL) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000851 std::error_code ec = mapWindowsError(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000852 return ec;
853 }
854
855 DWORD dwDesiredAccess;
856 switch (Mode) {
857 case readonly: dwDesiredAccess = FILE_MAP_READ; break;
858 case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
859 case priv: dwDesiredAccess = FILE_MAP_COPY; break;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000860 }
861 Mapping = ::MapViewOfFile(FileMappingHandle,
862 dwDesiredAccess,
863 Offset >> 32,
864 Offset & 0xffffffff,
865 Size);
866 if (Mapping == NULL) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000867 std::error_code ec = mapWindowsError(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000868 ::CloseHandle(FileMappingHandle);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000869 return ec;
870 }
871
872 if (Size == 0) {
873 MEMORY_BASIC_INFORMATION mbi;
874 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
875 if (Result == 0) {
Yaron Kerenf8e65172015-05-04 04:48:10 +0000876 std::error_code ec = mapWindowsError(GetLastError());
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000877 ::UnmapViewOfFile(Mapping);
878 ::CloseHandle(FileMappingHandle);
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000879 return ec;
880 }
881 Size = mbi.RegionSize;
882 }
Michael J. Spencer42ad29f2013-03-14 00:20:10 +0000883
884 // Close all the handles except for the view. It will keep the other handles
885 // alive.
886 ::CloseHandle(FileMappingHandle);
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000887 return std::error_code();
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000888}
889
Roman Lebedev1e053ab2017-09-27 17:24:34 +0000890mapped_file_region::mapped_file_region(int fd, mapmode mode, size_t length,
Rafael Espindola7eb1f182014-12-11 20:12:55 +0000891 uint64_t offset, std::error_code &ec)
Rafael Espindolaa23008a2014-12-16 03:10:29 +0000892 : Size(length), Mapping() {
Rafael Espindola986f5ad2014-12-16 02:19:26 +0000893 ec = init(fd, offset, mode);
Rafael Espindolaa23008a2014-12-16 03:10:29 +0000894 if (ec)
Rafael Espindola369d5142014-12-16 02:53:35 +0000895 Mapping = 0;
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000896}
897
898mapped_file_region::~mapped_file_region() {
Zachary Turneracd87912018-02-15 18:36:10 +0000899 if (Mapping) {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000900 ::UnmapViewOfFile(Mapping);
Zachary Turneracd87912018-02-15 18:36:10 +0000901
902 if (Mode == mapmode::readwrite) {
903 // There is a Windows kernel bug, the exact trigger conditions of which
904 // are not well understood. When triggered, dirty pages are not properly
905 // flushed and subsequent process's attempts to read a file can return
906 // invalid data. Calling FlushFileBuffers on the write handle is
907 // sufficient to ensure that this bug is not triggered.
908 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
909 if (FileHandle != INVALID_HANDLE_VALUE)
910 ::FlushFileBuffers(FileHandle);
911 }
912 }
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000913}
914
Roman Lebedev1e053ab2017-09-27 17:24:34 +0000915size_t mapped_file_region::size() const {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000916 assert(Mapping && "Mapping failed but used anyway!");
917 return Size;
918}
919
920char *mapped_file_region::data() const {
Michael J. Spenceref2284f2012-08-15 19:05:47 +0000921 assert(Mapping && "Mapping failed but used anyway!");
922 return reinterpret_cast<char*>(Mapping);
923}
924
925const char *mapped_file_region::const_data() const {
926 assert(Mapping && "Mapping failed but used anyway!");
927 return reinterpret_cast<const char*>(Mapping);
928}
929
930int mapped_file_region::alignment() {
931 SYSTEM_INFO SysInfo;
932 ::GetSystemInfo(&SysInfo);
933 return SysInfo.dwAllocationGranularity;
934}
935
Peter Collingbourneb4f1b882017-10-11 02:09:06 +0000936static basic_file_status status_from_find_data(WIN32_FIND_DATAW *FindData) {
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000937 return basic_file_status(file_type_from_attrs(FindData->dwFileAttributes),
938 perms_from_attrs(FindData->dwFileAttributes),
939 FindData->ftLastAccessTime.dwHighDateTime,
940 FindData->ftLastAccessTime.dwLowDateTime,
941 FindData->ftLastWriteTime.dwHighDateTime,
942 FindData->ftLastWriteTime.dwLowDateTime,
943 FindData->nFileSizeHigh, FindData->nFileSizeLow);
944}
945
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000946std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
Zachary Turner260bda32017-03-08 22:49:32 +0000947 StringRef path,
948 bool follow_symlinks) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000949 SmallVector<wchar_t, 128> path_utf16;
950
Paul Robinsond9c4a9a2014-11-13 00:12:14 +0000951 if (std::error_code ec = widenPath(path, path_utf16))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000952 return ec;
953
954 // Convert path to the format that Windows is happy with.
955 if (path_utf16.size() > 0 &&
956 !is_separator(path_utf16[path.size() - 1]) &&
957 path_utf16[path.size() - 1] != L':') {
958 path_utf16.push_back(L'\\');
959 path_utf16.push_back(L'*');
960 } else {
961 path_utf16.push_back(L'*');
962 }
963
964 // Get the first directory entry.
965 WIN32_FIND_DATAW FirstFind;
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000966 ScopedFindHandle FindHandle(::FindFirstFileExW(
967 c_str(path_utf16), FindExInfoBasic, &FirstFind, FindExSearchNameMatch,
968 NULL, FIND_FIRST_EX_LARGE_FETCH));
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000969 if (!FindHandle)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000970 return mapWindowsError(::GetLastError());
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000971
Michael J. Spencer98879d72011-01-05 16:39:30 +0000972 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
973 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
974 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
975 FirstFind.cFileName[1] == L'.'))
976 if (!::FindNextFileW(FindHandle, &FirstFind)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +0000977 DWORD LastError = ::GetLastError();
Michael J. Spencer98879d72011-01-05 16:39:30 +0000978 // Check for end.
Rafael Espindolaa813d602014-06-11 03:58:34 +0000979 if (LastError == ERROR_NO_MORE_FILES)
Michael J. Spencer0a7625d2011-12-08 22:50:09 +0000980 return detail::directory_iterator_destruct(it);
Yaron Kerenf8e65172015-05-04 04:48:10 +0000981 return mapWindowsError(LastError);
Michael J. Spencer98879d72011-01-05 16:39:30 +0000982 } else
983 FilenameLen = ::wcslen(FirstFind.cFileName);
984
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000985 // Construct the current directory entry.
Michael J. Spencer98879d72011-01-05 16:39:30 +0000986 SmallString<128> directory_entry_name_utf8;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000987 if (std::error_code ec =
988 UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
989 directory_entry_name_utf8))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000990 return ec;
991
992 it.IterationHandle = intptr_t(FindHandle.take());
Michael J. Spencer98879d72011-01-05 16:39:30 +0000993 SmallString<128> directory_entry_path(path);
Yaron Keren92e1b622015-03-18 10:17:07 +0000994 path::append(directory_entry_path, directory_entry_name_utf8);
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000995 it.CurrentEntry = directory_entry(directory_entry_path, follow_symlinks,
996 status_from_find_data(&FirstFind));
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000997
Rafael Espindolab4ad29b2014-06-13 02:36:09 +0000998 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +0000999}
1000
Rafael Espindolab4ad29b2014-06-13 02:36:09 +00001001std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001002 if (it.IterationHandle != 0)
1003 // Closes the handle if it's valid.
1004 ScopedFindHandle close(HANDLE(it.IterationHandle));
1005 it.IterationHandle = 0;
1006 it.CurrentEntry = directory_entry();
Rafael Espindolab4ad29b2014-06-13 02:36:09 +00001007 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001008}
1009
Rafael Espindolab4ad29b2014-06-13 02:36:09 +00001010std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001011 WIN32_FIND_DATAW FindData;
1012 if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
Rafael Espindolaa813d602014-06-11 03:58:34 +00001013 DWORD LastError = ::GetLastError();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001014 // Check for end.
Rafael Espindolaa813d602014-06-11 03:58:34 +00001015 if (LastError == ERROR_NO_MORE_FILES)
Michael J. Spencer0a7625d2011-12-08 22:50:09 +00001016 return detail::directory_iterator_destruct(it);
Yaron Kerenf8e65172015-05-04 04:48:10 +00001017 return mapWindowsError(LastError);
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001018 }
1019
Michael J. Spencer98879d72011-01-05 16:39:30 +00001020 size_t FilenameLen = ::wcslen(FindData.cFileName);
1021 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
1022 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
1023 FindData.cFileName[1] == L'.'))
1024 return directory_iterator_increment(it);
1025
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001026 SmallString<128> directory_entry_path_utf8;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +00001027 if (std::error_code ec =
1028 UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
1029 directory_entry_path_utf8))
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001030 return ec;
1031
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001032 it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8),
1033 status_from_find_data(&FindData));
Rafael Espindolab4ad29b2014-06-13 02:36:09 +00001034 return std::error_code();
Michael J. Spencer7ecd94c2010-12-06 04:28:42 +00001035}
1036
Peter Collingbourne0dfdb442017-10-10 22:19:46 +00001037ErrorOr<basic_file_status> directory_entry::status() const {
1038 return Status;
1039}
1040
Zachary Turnere48ace62017-03-10 17:39:21 +00001041static std::error_code directoryRealPath(const Twine &Name,
1042 SmallVectorImpl<char> &RealPath) {
1043 SmallVector<wchar_t, 128> PathUTF16;
1044
1045 if (std::error_code EC = widenPath(Name, PathUTF16))
1046 return EC;
1047
1048 HANDLE H =
1049 ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
1050 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1051 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1052 if (H == INVALID_HANDLE_VALUE)
1053 return mapWindowsError(GetLastError());
1054 std::error_code EC = realPathFromHandle(H, RealPath);
1055 ::CloseHandle(H);
1056 return EC;
1057}
1058
Taewook Ohd9153272016-06-13 15:54:56 +00001059std::error_code openFileForRead(const Twine &Name, int &ResultFD,
1060 SmallVectorImpl<char> *RealPath) {
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001061 SmallVector<wchar_t, 128> PathUTF16;
Nick Kledzik18497e92012-06-20 00:28:54 +00001062
Paul Robinsond9c4a9a2014-11-13 00:12:14 +00001063 if (std::error_code EC = widenPath(Name, PathUTF16))
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001064 return EC;
1065
Greg Bedwell7f68a712015-10-12 15:11:47 +00001066 HANDLE H =
1067 ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
1068 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1069 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001070 if (H == INVALID_HANDLE_VALUE) {
Rafael Espindolaa813d602014-06-11 03:58:34 +00001071 DWORD LastError = ::GetLastError();
Yaron Kerenf8e65172015-05-04 04:48:10 +00001072 std::error_code EC = mapWindowsError(LastError);
Rafael Espindola331aeba2013-07-17 19:58:28 +00001073 // Provide a better error message when trying to open directories.
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001074 // This only runs if we failed to open the file, so there is probably
1075 // no performances issues.
Rafael Espindolaa813d602014-06-11 03:58:34 +00001076 if (LastError != ERROR_ACCESS_DENIED)
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001077 return EC;
1078 if (is_directory(Name))
Rafael Espindola2a826e42014-06-13 17:20:48 +00001079 return make_error_code(errc::is_a_directory);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001080 return EC;
1081 }
1082
1083 int FD = ::_open_osfhandle(intptr_t(H), 0);
1084 if (FD == -1) {
1085 ::CloseHandle(H);
Yaron Kerenf8e65172015-05-04 04:48:10 +00001086 return mapWindowsError(ERROR_INVALID_HANDLE);
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001087 }
1088
Taewook Ohd9153272016-06-13 15:54:56 +00001089 // Fetch the real name of the file, if the user asked
Zachary Turnere48ace62017-03-10 17:39:21 +00001090 if (RealPath)
Zachary Turner3c0dc332017-03-10 18:33:41 +00001091 realPathFromHandle(H, *RealPath);
Taewook Ohd9153272016-06-13 15:54:56 +00001092
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001093 ResultFD = FD;
Zachary Turner3c0dc332017-03-10 18:33:41 +00001094 return std::error_code();
Rafael Espindolaa0d9b6b2013-07-17 14:58:25 +00001095}
Nick Kledzik18497e92012-06-20 00:28:54 +00001096
Rafael Espindolab4ad29b2014-06-13 02:36:09 +00001097std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
Rafael Espindola67080ce2013-07-19 15:02:03 +00001098 sys::fs::OpenFlags Flags, unsigned Mode) {
1099 // Verify that we don't have both "append" and "excl".
1100 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
1101 "Cannot specify both 'excl' and 'append' file creation flags!");
1102
Rafael Espindola67080ce2013-07-19 15:02:03 +00001103 SmallVector<wchar_t, 128> PathUTF16;
1104
Paul Robinsond9c4a9a2014-11-13 00:12:14 +00001105 if (std::error_code EC = widenPath(Name, PathUTF16))
Rafael Espindola67080ce2013-07-19 15:02:03 +00001106 return EC;
1107
1108 DWORD CreationDisposition;
1109 if (Flags & F_Excl)
1110 CreationDisposition = CREATE_NEW;
Zachary Turneradad3302018-03-08 20:34:47 +00001111 else if ((Flags & F_Append) || (Flags & F_NoTrunc))
Rafael Espindola67080ce2013-07-19 15:02:03 +00001112 CreationDisposition = OPEN_ALWAYS;
1113 else
1114 CreationDisposition = CREATE_ALWAYS;
1115
Rafael Espindola7a0b6402014-02-24 03:07:41 +00001116 DWORD Access = GENERIC_WRITE;
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001117 DWORD Attributes = FILE_ATTRIBUTE_NORMAL;
Rafael Espindola7a0b6402014-02-24 03:07:41 +00001118 if (Flags & F_RW)
1119 Access |= GENERIC_READ;
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001120 if (Flags & F_Delete) {
Rafael Espindolabce112c2017-11-28 00:12:44 +00001121 Access |= DELETE;
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001122 Attributes |= FILE_FLAG_DELETE_ON_CLOSE;
1123 }
Rafael Espindola7a0b6402014-02-24 03:07:41 +00001124
Reid Klecknercefb3332017-08-04 21:52:00 +00001125 HANDLE H =
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001126 ::CreateFileW(PathUTF16.data(), Access,
Reid Klecknercefb3332017-08-04 21:52:00 +00001127 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
Rafael Espindola3ecd2042017-11-28 01:41:22 +00001128 NULL, CreationDisposition, Attributes, NULL);
Rafael Espindola67080ce2013-07-19 15:02:03 +00001129
1130 if (H == INVALID_HANDLE_VALUE) {
Rafael Espindolaa813d602014-06-11 03:58:34 +00001131 DWORD LastError = ::GetLastError();
Yaron Kerenf8e65172015-05-04 04:48:10 +00001132 std::error_code EC = mapWindowsError(LastError);
Rafael Espindola67080ce2013-07-19 15:02:03 +00001133 // Provide a better error message when trying to open directories.
1134 // This only runs if we failed to open the file, so there is probably
1135 // no performances issues.
Rafael Espindolaa813d602014-06-11 03:58:34 +00001136 if (LastError != ERROR_ACCESS_DENIED)
Rafael Espindola67080ce2013-07-19 15:02:03 +00001137 return EC;
1138 if (is_directory(Name))
Rafael Espindola2a826e42014-06-13 17:20:48 +00001139 return make_error_code(errc::is_a_directory);
Rafael Espindola67080ce2013-07-19 15:02:03 +00001140 return EC;
1141 }
1142
1143 int OpenFlags = 0;
1144 if (Flags & F_Append)
1145 OpenFlags |= _O_APPEND;
1146
Rafael Espindola90c7f1c2014-02-24 18:20:12 +00001147 if (Flags & F_Text)
Rafael Espindola67080ce2013-07-19 15:02:03 +00001148 OpenFlags |= _O_TEXT;
1149
1150 int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
1151 if (FD == -1) {
1152 ::CloseHandle(H);
Yaron Kerenf8e65172015-05-04 04:48:10 +00001153 return mapWindowsError(ERROR_INVALID_HANDLE);
Rafael Espindola67080ce2013-07-19 15:02:03 +00001154 }
1155
1156 ResultFD = FD;
Rafael Espindolab4ad29b2014-06-13 02:36:09 +00001157 return std::error_code();
Rafael Espindola67080ce2013-07-19 15:02:03 +00001158}
Taewook Ohd9153272016-06-13 15:54:56 +00001159
Zachary Turner260bda32017-03-08 22:49:32 +00001160std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1161 // Convert to utf-16.
1162 SmallVector<wchar_t, 128> Path16;
1163 std::error_code EC = widenPath(path, Path16);
1164 if (EC && !IgnoreErrors)
1165 return EC;
1166
1167 // SHFileOperation() accepts a list of paths, and so must be double null-
1168 // terminated to indicate the end of the list. The buffer is already null
1169 // terminated, but since that null character is not considered part of the
1170 // vector's size, pushing another one will just consume that byte. So we
1171 // need to push 2 null terminators.
1172 Path16.push_back(0);
1173 Path16.push_back(0);
1174
1175 SHFILEOPSTRUCTW shfos = {};
1176 shfos.wFunc = FO_DELETE;
1177 shfos.pFrom = Path16.data();
1178 shfos.fFlags = FOF_NO_UI;
1179
1180 int result = ::SHFileOperationW(&shfos);
1181 if (result != 0 && !IgnoreErrors)
1182 return mapWindowsError(result);
1183 return std::error_code();
1184}
1185
Zachary Turnere48ace62017-03-10 17:39:21 +00001186static void expandTildeExpr(SmallVectorImpl<char> &Path) {
1187 // Path does not begin with a tilde expression.
1188 if (Path.empty() || Path[0] != '~')
1189 return;
1190
1191 StringRef PathStr(Path.begin(), Path.size());
1192 PathStr = PathStr.drop_front();
Zachary Turner5c5091f2017-03-16 22:28:04 +00001193 StringRef Expr = PathStr.take_until([](char c) { return path::is_separator(c); });
Zachary Turnere48ace62017-03-10 17:39:21 +00001194
1195 if (!Expr.empty()) {
1196 // This is probably a ~username/ expression. Don't support this on Windows.
1197 return;
1198 }
1199
1200 SmallString<128> HomeDir;
1201 if (!path::home_directory(HomeDir)) {
1202 // For some reason we couldn't get the home directory. Just exit.
1203 return;
1204 }
1205
1206 // Overwrite the first character and insert the rest.
1207 Path[0] = HomeDir[0];
1208 Path.insert(Path.begin() + 1, HomeDir.begin() + 1, HomeDir.end());
1209}
1210
1211std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1212 bool expand_tilde) {
1213 dest.clear();
1214 if (path.isTriviallyEmpty())
1215 return std::error_code();
1216
1217 if (expand_tilde) {
1218 SmallString<128> Storage;
1219 path.toVector(Storage);
1220 expandTildeExpr(Storage);
1221 return real_path(Storage, dest, false);
1222 }
1223
1224 if (is_directory(path))
1225 return directoryRealPath(path, dest);
1226
1227 int fd;
1228 if (std::error_code EC = llvm::sys::fs::openFileForRead(path, fd, &dest))
1229 return EC;
1230 ::close(fd);
1231 return std::error_code();
1232}
1233
Michael J. Spencer9fc1d9d2010-12-01 19:32:01 +00001234} // end namespace fs
Rui Ueyama471d0c52013-09-10 19:45:51 +00001235
Peter Collingbournef7d41012014-01-31 23:46:06 +00001236namespace path {
Pawel Bylica7c1f36a2015-11-02 14:57:24 +00001237static bool getKnownFolderPath(KNOWNFOLDERID folderId,
1238 SmallVectorImpl<char> &result) {
Pawel Bylica7187e4b2015-10-16 09:08:59 +00001239 wchar_t *path = nullptr;
1240 if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK)
1241 return false;
1242
1243 bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
1244 ::CoTaskMemFree(path);
1245 return ok;
1246}
Pawel Bylica0e97e5c2015-11-02 09:49:17 +00001247
1248bool getUserCacheDir(SmallVectorImpl<char> &Result) {
1249 return getKnownFolderPath(FOLDERID_LocalAppData, Result);
1250}
Pawel Bylica7187e4b2015-10-16 09:08:59 +00001251
Peter Collingbournef7d41012014-01-31 23:46:06 +00001252bool home_directory(SmallVectorImpl<char> &result) {
Pawel Bylica7187e4b2015-10-16 09:08:59 +00001253 return getKnownFolderPath(FOLDERID_Profile, result);
Peter Collingbournef7d41012014-01-31 23:46:06 +00001254}
1255
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001256static bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {
Pawel Bylica6e680b22015-11-06 23:44:23 +00001257 SmallVector<wchar_t, 1024> Buf;
1258 size_t Size = 1024;
1259 do {
1260 Buf.reserve(Size);
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001261 Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.capacity());
Pawel Bylica6e680b22015-11-06 23:44:23 +00001262 if (Size == 0)
1263 return false;
1264
1265 // Try again with larger buffer.
1266 } while (Size > Buf.capacity());
1267 Buf.set_size(Size);
1268
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001269 return !windows::UTF16ToUTF8(Buf.data(), Size, Res);
Pawel Bylica6e680b22015-11-06 23:44:23 +00001270}
1271
1272static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001273 const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};
1274 for (auto *Env : EnvironmentVariables) {
Pawel Bylica6e680b22015-11-06 23:44:23 +00001275 if (getTempDirEnvVar(Env, Res))
1276 return true;
1277 }
1278 return false;
1279}
1280
Rafael Espindola016a6d52014-08-26 14:47:52 +00001281void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1282 (void)ErasedOnReboot;
Pawel Bylica6e680b22015-11-06 23:44:23 +00001283 Result.clear();
Rafael Espindola016a6d52014-08-26 14:47:52 +00001284
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001285 // Check whether the temporary directory is specified by an environment var.
1286 // This matches GetTempPath logic to some degree. GetTempPath is not used
1287 // directly as it cannot handle evn var longer than 130 chars on Windows 7
1288 // (fixed on Windows 8).
1289 if (getTempDirEnvVar(Result)) {
1290 assert(!Result.empty() && "Unexpected empty path");
1291 native(Result); // Some Unix-like shells use Unix path separator in $TMP.
1292 fs::make_absolute(Result); // Make it absolute if not already.
Pawel Bylica6e680b22015-11-06 23:44:23 +00001293 return;
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001294 }
Rafael Espindola016a6d52014-08-26 14:47:52 +00001295
1296 // Fall back to a system default.
Pawel Bylicaa90e7452015-11-17 16:54:32 +00001297 const char *DefaultResult = "C:\\Temp";
Rafael Espindola016a6d52014-08-26 14:47:52 +00001298 Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
1299}
Peter Collingbournef7d41012014-01-31 23:46:06 +00001300} // end namespace path
1301
Rui Ueyama471d0c52013-09-10 19:45:51 +00001302namespace windows {
Aaron Smith8a5ea612018-04-07 00:32:59 +00001303std::error_code CodePageToUTF16(unsigned codepage,
1304 llvm::StringRef original,
1305 llvm::SmallVectorImpl<wchar_t> &utf16) {
1306 if (!original.empty()) {
1307 int len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1308 original.size(), utf16.begin(), 0);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001309
Aaron Smith8a5ea612018-04-07 00:32:59 +00001310 if (len == 0) {
Yaron Kerenf8e65172015-05-04 04:48:10 +00001311 return mapWindowsError(::GetLastError());
Aaron Smith8a5ea612018-04-07 00:32:59 +00001312 }
Rui Ueyama471d0c52013-09-10 19:45:51 +00001313
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001314 utf16.reserve(len + 1);
1315 utf16.set_size(len);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001316
Aaron Smith8a5ea612018-04-07 00:32:59 +00001317 len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1318 original.size(), utf16.begin(), utf16.size());
Rui Ueyama471d0c52013-09-10 19:45:51 +00001319
Aaron Smith8a5ea612018-04-07 00:32:59 +00001320 if (len == 0) {
Yaron Kerenf8e65172015-05-04 04:48:10 +00001321 return mapWindowsError(::GetLastError());
Aaron Smith8a5ea612018-04-07 00:32:59 +00001322 }
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001323 }
Rui Ueyama471d0c52013-09-10 19:45:51 +00001324
1325 // Make utf16 null terminated.
1326 utf16.push_back(0);
1327 utf16.pop_back();
1328
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +00001329 return std::error_code();
Rui Ueyama471d0c52013-09-10 19:45:51 +00001330}
1331
Aaron Smith8a5ea612018-04-07 00:32:59 +00001332std::error_code UTF8ToUTF16(llvm::StringRef utf8,
1333 llvm::SmallVectorImpl<wchar_t> &utf16) {
1334 return CodePageToUTF16(CP_UTF8, utf8, utf16);
1335}
1336
1337std::error_code CurCPToUTF16(llvm::StringRef curcp,
1338 llvm::SmallVectorImpl<wchar_t> &utf16) {
1339 return CodePageToUTF16(CP_ACP, curcp, utf16);
1340}
1341
Rafael Espindola9c359662014-09-03 20:02:00 +00001342static
1343std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
1344 size_t utf16_len,
Aaron Smith8a5ea612018-04-07 00:32:59 +00001345 llvm::SmallVectorImpl<char> &converted) {
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001346 if (utf16_len) {
1347 // Get length.
Aaron Smith8a5ea612018-04-07 00:32:59 +00001348 int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.begin(),
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001349 0, NULL, NULL);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001350
Aaron Smith8a5ea612018-04-07 00:32:59 +00001351 if (len == 0) {
Yaron Kerenf8e65172015-05-04 04:48:10 +00001352 return mapWindowsError(::GetLastError());
Aaron Smith8a5ea612018-04-07 00:32:59 +00001353 }
Rui Ueyama471d0c52013-09-10 19:45:51 +00001354
Aaron Smith8a5ea612018-04-07 00:32:59 +00001355 converted.reserve(len);
1356 converted.set_size(len);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001357
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001358 // Now do the actual conversion.
Aaron Smith8a5ea612018-04-07 00:32:59 +00001359 len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.data(),
1360 converted.size(), NULL, NULL);
Rui Ueyama471d0c52013-09-10 19:45:51 +00001361
Aaron Smith8a5ea612018-04-07 00:32:59 +00001362 if (len == 0) {
Yaron Kerenf8e65172015-05-04 04:48:10 +00001363 return mapWindowsError(::GetLastError());
Aaron Smith8a5ea612018-04-07 00:32:59 +00001364 }
Michael J. Spencer7a3a5102014-02-20 20:46:23 +00001365 }
Rui Ueyama471d0c52013-09-10 19:45:51 +00001366
Aaron Smith8a5ea612018-04-07 00:32:59 +00001367 // Make the new string null terminated.
1368 converted.push_back(0);
1369 converted.pop_back();
Rui Ueyama471d0c52013-09-10 19:45:51 +00001370
Rafael Espindola0a5f9cf2014-06-12 14:11:22 +00001371 return std::error_code();
Rui Ueyama471d0c52013-09-10 19:45:51 +00001372}
Rafael Espindola9c359662014-09-03 20:02:00 +00001373
1374std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
1375 llvm::SmallVectorImpl<char> &utf8) {
1376 return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
1377}
1378
1379std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
Aaron Smith8a5ea612018-04-07 00:32:59 +00001380 llvm::SmallVectorImpl<char> &curcp) {
1381 return UTF16ToCodePage(CP_ACP, utf16, utf16_len, curcp);
Rafael Espindola9c359662014-09-03 20:02:00 +00001382}
Taewook Ohd9153272016-06-13 15:54:56 +00001383
Rui Ueyama471d0c52013-09-10 19:45:51 +00001384} // end namespace windows
Michael J. Spencerebad2f92010-11-29 22:28:51 +00001385} // end namespace sys
1386} // end namespace llvm