LLVM 24.0.0git
Path.inc
Go to the documentation of this file.
1//===- llvm/Support/Windows/Path.inc - Windows Path Impl --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Windows specific implementation of the Path API.
10//
11//===----------------------------------------------------------------------===//
12
13//===----------------------------------------------------------------------===//
14//=== WARNING: Implementation here must contain only generic Windows code that
15//=== is guaranteed to work on *all* Windows variants.
16//===----------------------------------------------------------------------===//
17
18#include "llvm/ADT/STLExtras.h"
22#include <fcntl.h>
23#include <sys/stat.h>
24#include <sys/types.h>
25
26// 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
29#include <shellapi.h>
30#include <shlobj.h>
31#include <winioctl.h>
32#include <winternl.h>
33
34#undef max
35
36// MinGW doesn't define this.
37#ifndef _ERRNO_T_DEFINED
38#define _ERRNO_T_DEFINED
39typedef int errno_t;
40#endif
41
42#ifdef _MSC_VER
43#pragma comment(lib, "advapi32.lib") // This provides CryptAcquireContextW.
44#pragma comment(lib, "ole32.lib") // This provides CoTaskMemFree
45#endif
46
47#ifndef __MINGW32__
48// The Windows SDK does not declare these types.
49// The WDK declares the types in `wdm.h` and `NtQueryVolumeInformationFile`
50// in `ntifs.h`.
51// MinGW-w64 declares all three in `winternl.h`.
52typedef enum _FSINFOCLASS { FileFsDeviceInformation = 4 } FS_INFORMATION_CLASS;
53
54typedef struct _FILE_FS_DEVICE_INFORMATION {
55 DEVICE_TYPE DeviceType;
56 ULONG Characteristics;
57} FILE_FS_DEVICE_INFORMATION;
58
59// Exported by `ntdll.dll`.
60extern "C" NTSYSAPI NTSTATUS NTAPI NtQueryVolumeInformationFile(
61 HANDLE FileHandle, PIO_STATUS_BLOCK IoStatusBlock, PVOID FsInformation,
62 ULONG Length, FS_INFORMATION_CLASS FsInformationClass);
63#endif
64
65// Defined only in `wdm.h` in WDK and MinGW-w64.
66#ifndef FILE_REMOVABLE_MEDIA
67#define FILE_REMOVABLE_MEDIA 0x00000001
68#endif
69#ifndef FILE_REMOTE_DEVICE
70#define FILE_REMOTE_DEVICE 0x00000010
71#endif
72
73using namespace llvm;
74
75using llvm::sys::windows::CurCPToUTF16;
76using llvm::sys::windows::UTF16ToUTF8;
77using llvm::sys::windows::UTF8ToUTF16;
79
80static bool is_separator(const wchar_t value) {
81 switch (value) {
82 case L'\\':
83 case L'/':
84 return true;
85 default:
86 return false;
87 }
88}
89
90// Long path path prefix constants (UTF-8).
91static constexpr llvm::StringLiteral LongPathPrefix8 = R"(\\?\)";
92static constexpr llvm::StringLiteral LongPathUNCPrefix8 = R"(\\?\UNC\)";
93
94// Long path prefix constants (UTF-16).
95static constexpr wchar_t LongPathPrefix16[] = LR"(\\?\)";
96static constexpr wchar_t LongPathUNCPrefix16[] = LR"(\\?\UNC\)";
97
98static constexpr DWORD LongPathPrefix16Len =
99 static_cast<DWORD>(std::size(LongPathPrefix16) - 1);
100static constexpr DWORD LongPathUNCPrefix16Len =
101 static_cast<DWORD>(std::size(LongPathUNCPrefix16) - 1);
102
103static void stripLongPathPrefix(wchar_t *&Data, DWORD &CountChars) {
104 if (CountChars >= LongPathUNCPrefix16Len &&
105 ::wmemcmp(Data, LongPathUNCPrefix16, LongPathUNCPrefix16Len) == 0) {
106 // Convert \\?\UNC\foo\bar to \\foo\bar
107 CountChars -= 6;
108 Data += 6;
109 Data[0] = L'\\';
110 } else if (CountChars >= LongPathPrefix16Len &&
111 ::wmemcmp(Data, LongPathPrefix16, LongPathPrefix16Len) == 0) {
112 // Convert \\?\C:\foo to C:\foo
113 CountChars -= 4;
114 Data += 4;
115 }
116}
117
118namespace llvm {
119namespace sys {
120namespace windows {
121
122// Convert a UTF-8 path to UTF-16. Also, if the absolute equivalent of the path
123// is longer than the limit that the Win32 Unicode File API can tolerate, make
124// it an absolute normalized path prefixed by '\\?\'.
125std::error_code widenPath(const Twine &Path8, SmallVectorImpl<wchar_t> &Path16,
126 size_t MaxPathLen) {
127 assert(MaxPathLen <= MAX_PATH);
128
129 // Several operations would convert Path8 to SmallString; more efficient to do
130 // it once up front.
131 SmallString<MAX_PATH> Path8Str;
132 Path8.toVector(Path8Str);
133
134 // If the path is a long path, mangled into forward slashes, normalize
135 // back to backslashes here.
136 if (Path8Str.starts_with("//?/"))
138
139 if (std::error_code EC = UTF8ToUTF16(Path8Str, Path16))
140 return EC;
141
142 const bool IsAbsolute = llvm::sys::path::is_absolute(Path8);
143 size_t CurPathLen;
144 if (IsAbsolute)
145 CurPathLen = 0; // No contribution from current_path needed.
146 else {
147 CurPathLen = ::GetCurrentDirectoryW(
148 0, NULL); // Returns the size including the null terminator.
149 if (CurPathLen == 0)
150 return mapWindowsError(::GetLastError());
151 }
152
153 if ((Path16.size() + CurPathLen) < MaxPathLen ||
154 Path8Str.starts_with(LongPathPrefix8))
155 return std::error_code();
156
157 if (!IsAbsolute) {
158 if (std::error_code EC = llvm::sys::fs::make_absolute(Path8Str))
159 return EC;
160 }
161
162 // Remove '.' and '..' because long paths treat these as real path components.
163 // Explicitly use the backslash form here, as we're prepending the \\?\
164 // prefix.
167
168 const StringRef RootName = llvm::sys::path::root_name(Path8Str);
169 assert(!RootName.empty() &&
170 "Root name cannot be empty for an absolute path!");
171
172 SmallString<2 * MAX_PATH> FullPath;
173 if (RootName[1] != ':') { // Check if UNC.
174 FullPath.append(LongPathUNCPrefix8);
175 FullPath.append(Path8Str.begin() + 2, Path8Str.end());
176 } else {
177 FullPath.append(LongPathPrefix8);
178 FullPath.append(Path8Str);
179 }
180
181 return UTF8ToUTF16(FullPath, Path16);
182}
183
184std::error_code makeLongFormPath(const Twine &Path8,
185 llvm::SmallVectorImpl<char> &Result8) {
186 SmallString<128> PathStorage;
187 StringRef PathStr = Path8.toStringRef(PathStorage);
188 bool HadPrefix = PathStr.starts_with(LongPathPrefix8);
189
191 if (std::error_code EC = widenPath(PathStr, Path16))
192 return EC;
193
194 // Start with a buffer equal to input.
196 DWORD Len = static_cast<DWORD>(Path16.size());
197
198 // Loop instead of a double call to be defensive against TOCTOU races.
199 do {
200 Long16.resize_for_overwrite(Len);
201
202 Len = ::GetLongPathNameW(Path16.data(), Long16.data(), Len);
203
204 // A zero return value indicates a failure other than insufficient space.
205 if (Len == 0)
206 return mapWindowsError(::GetLastError());
207
208 // If there's insufficient space, the return value is the required size in
209 // characters *including* the null terminator, and therefore greater than
210 // the buffer size we provided. Equality would imply success with no room
211 // for the terminator and should not occur for this API.
212 assert(Len != Long16.size());
213 } while (Len > Long16.size());
214
215 // On success, GetLongPathNameW returns the number of characters not
216 // including the null-terminator.
217 Long16.truncate(Len);
218
219 // Strip \\?\ or \\?\UNC\ long length prefix if it wasn't part of the
220 // original path.
221 wchar_t *Data = Long16.data();
222 if (!HadPrefix)
223 stripLongPathPrefix(Data, Len);
224
225 return sys::windows::UTF16ToUTF8(Data, Len, Result8);
226}
227
228} // end namespace windows
229
230namespace fs {
231
232const file_t::value_type file_t::Invalid = INVALID_HANDLE_VALUE;
233
234std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
235 auto BypassSandbox = sandbox::scopedDisable();
236
238 PathName.resize_for_overwrite(PathName.capacity());
239 DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.size());
240
241 // A zero return value indicates a failure other than insufficient space.
242 if (Size == 0)
243 return "";
244
245 // Insufficient space is determined by a return value equal to the size of
246 // the buffer passed in.
247 if (Size == PathName.capacity())
248 return "";
249
250 // On success, GetModuleFileNameW returns the number of characters written to
251 // the buffer not including the NULL terminator.
252 PathName.truncate(Size);
253
254 // Convert the result from UTF-16 to UTF-8.
255 SmallVector<char, MAX_PATH> PathNameUTF8;
256 if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
257 return "";
258
260
261 SmallString<256> RealPath;
262 sys::fs::real_path(PathNameUTF8, RealPath);
263 if (RealPath.size())
264 return std::string(RealPath);
265 return std::string(PathNameUTF8.data());
266}
267
269 return UniqueID(VolumeSerialNumber, PathHash);
270}
271
272ErrorOr<space_info> disk_space(const Twine &Path) {
273 ULARGE_INTEGER Avail, Total, Free;
275
276 if (std::error_code EC = widenPath(Path, PathUTF16))
277 return EC;
278
279 if (!::GetDiskFreeSpaceExW(PathUTF16.data(), &Avail, &Total, &Free))
280 return mapWindowsError(::GetLastError());
281
282 space_info SpaceInfo;
283 SpaceInfo.capacity = Total.QuadPart;
284 SpaceInfo.free = Free.QuadPart;
285 SpaceInfo.available = Avail.QuadPart;
286
287 return SpaceInfo;
288}
289
291 FILETIME Time;
292 Time.dwLowDateTime = LastAccessedTimeLow;
293 Time.dwHighDateTime = LastAccessedTimeHigh;
294 return toTimePoint(Time);
295}
296
298 FILETIME Time;
299 Time.dwLowDateTime = LastWriteTimeLow;
300 Time.dwHighDateTime = LastWriteTimeHigh;
301 return toTimePoint(Time);
302}
303
304uint32_t file_status::getLinkCount() const { return NumLinks; }
305
306std::error_code current_path(SmallVectorImpl<char> &result) {
308
310 DWORD len = MAX_PATH;
311
312 do {
313 cur_path.resize_for_overwrite(len);
314 len = ::GetCurrentDirectoryW(cur_path.size(), cur_path.data());
315
316 // A zero return value indicates a failure other than insufficient space.
317 if (len == 0)
318 return mapWindowsError(::GetLastError());
319
320 // If there's insufficient space, the len returned is larger than the len
321 // given.
322 } while (len > cur_path.size());
323
324 // On success, GetCurrentDirectoryW returns the number of characters not
325 // including the null-terminator.
326 cur_path.truncate(len);
327
328 if (std::error_code EC =
329 UTF16ToUTF8(cur_path.begin(), cur_path.size(), result))
330 return EC;
331
333 return std::error_code();
334}
335
336std::error_code set_current_path(const Twine &path) {
338
339 // Convert to utf-16.
341 if (std::error_code ec = widenPath(path, wide_path))
342 return ec;
343
344 if (!::SetCurrentDirectoryW(wide_path.begin()))
345 return mapWindowsError(::GetLastError());
346
347 return std::error_code();
348}
349
350std::error_code create_directory(const Twine &path, bool IgnoreExisting,
351 perms Perms) {
352 SmallVector<wchar_t, 128> path_utf16;
353
354 // CreateDirectoryW has a lower maximum path length as it must leave room for
355 // an 8.3 filename.
356 if (std::error_code ec = widenPath(path, path_utf16, MAX_PATH - 12))
357 return ec;
358
359 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
360 DWORD LastError = ::GetLastError();
361 if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
362 return mapWindowsError(LastError);
363 }
364
365 return std::error_code();
366}
367
368std::error_code create_symlink(const Twine &to, const Twine &from) {
369 // The Win32 API normally allows forward slashes, but under some cases it does
370 // not correctly handle them in the target of a symlink.
371 SmallString<128> ToStr;
373
376 if (std::error_code ec = widenPath(from, WideFrom))
377 return ec;
378 if (std::error_code ec = widenPath(ToStr, WideTo))
379 return ec;
380
381 // Windows requires SYMBOLIC_LINK_FLAG_DIRECTORY for directory symlinks, so
382 // check first what type the target is. Relative symlink targets are relative
383 // to the link's parent directory, not the CWD, so resolve accordingly before
384 // checking attributes.
385 SmallVector<wchar_t, 128> WideResolved;
386 const SmallVectorImpl<wchar_t> *AttrPath = &WideTo;
387
388 if (sys::path::is_relative(ToStr)) {
389 SmallString<128> FromStr;
390 from.toVector(FromStr);
391 SmallString<128> Resolved = sys::path::parent_path(FromStr);
392 sys::path::append(Resolved, ToStr);
393 if (std::error_code ec = widenPath(Resolved, WideResolved))
394 return ec;
395 AttrPath = &WideResolved;
396 }
397 DWORD Flags = 0;
398 DWORD Attr = ::GetFileAttributesW(AttrPath->begin());
399 if (Attr == INVALID_FILE_ATTRIBUTES) {
400 DWORD Err = ::GetLastError();
401 if (Err != ERROR_FILE_NOT_FOUND && Err != ERROR_PATH_NOT_FOUND)
402 return mapWindowsError(Err);
403 // Target doesn't exist. Default to a file symlink, matching the Unix
404 // behavior of allowing dangling symlinks.
405 } else if (Attr & FILE_ATTRIBUTE_DIRECTORY) {
406 Flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
407 }
408
409 // Try with SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE first, which works
410 // in non-UWP programs and when Developer Mode is enabled on Windows 10+.
411 if (::CreateSymbolicLinkW(WideFrom.begin(), WideTo.begin(),
412 Flags |
413 SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE))
414 return std::error_code();
415
416 // If the flag is not recognized (older Windows), retry without it.
417 DWORD Err = ::GetLastError();
418 if (Err == ERROR_INVALID_PARAMETER) {
419 if (::CreateSymbolicLinkW(WideFrom.begin(), WideTo.begin(), Flags))
420 return std::error_code();
421 Err = ::GetLastError();
422 }
423
424 return mapWindowsError(Err);
425}
426
427std::error_code create_link(const Twine &to, const Twine &from) {
428 std::error_code EC = create_symlink(to, from);
429 if (EC)
430 EC = create_hard_link(to, from);
431 return EC;
432}
433
434std::error_code create_hard_link(const Twine &to, const Twine &from) {
435 // Convert to utf-16.
438 if (std::error_code ec = widenPath(from, wide_from))
439 return ec;
440 if (std::error_code ec = widenPath(to, wide_to))
441 return ec;
442
443 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
444 return mapWindowsError(::GetLastError());
445
446 return std::error_code();
447}
448
449std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
450 SmallVector<wchar_t, 128> path_utf16;
451
452 if (std::error_code ec = widenPath(path, path_utf16))
453 return ec;
454
455 // We don't know whether this is a file or a directory, and remove() can
456 // accept both. The usual way to delete a file or directory is to use one of
457 // the DeleteFile or RemoveDirectory functions, but that requires you to know
458 // which one it is. We could stat() the file to determine that, but that would
459 // cost us additional system calls, which can be slow in a directory
460 // containing a large number of files. So instead we call CreateFile directly.
461 // The important part is the FILE_FLAG_DELETE_ON_CLOSE flag, which causes the
462 // file to be deleted once it is closed. We also use the flags
463 // FILE_FLAG_BACKUP_SEMANTICS (which allows us to open directories), and
464 // FILE_FLAG_OPEN_REPARSE_POINT (don't follow symlinks).
465 ScopedFileHandle h(::CreateFileW(
466 c_str(path_utf16), DELETE,
467 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
468 OPEN_EXISTING,
469 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS |
470 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_DELETE_ON_CLOSE,
471 NULL));
472 if (!h) {
473 std::error_code EC = mapWindowsError(::GetLastError());
474 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
475 return EC;
476 }
477
478 return std::error_code();
479}
480
481static std::error_code is_local_internal(SmallVectorImpl<wchar_t> &Path,
482 bool &Result) {
483 SmallVector<wchar_t, 128> VolumePath;
484 size_t Len = 128;
485 while (true) {
486 VolumePath.resize(Len);
487 BOOL Success =
488 ::GetVolumePathNameW(Path.data(), VolumePath.data(), VolumePath.size());
489
490 if (Success)
491 break;
492
493 DWORD Err = ::GetLastError();
494 if (Err != ERROR_INSUFFICIENT_BUFFER)
495 return mapWindowsError(Err);
496
497 Len *= 2;
498 }
499 // If the output buffer has exactly enough space for the path name, but not
500 // the null terminator, it will leave the output unterminated. Push a null
501 // terminator onto the end to ensure that this never happens.
502 VolumePath.push_back(L'\0');
503 VolumePath.truncate(wcslen(VolumePath.data()));
504 const wchar_t *P = VolumePath.data();
505
506 UINT Type = ::GetDriveTypeW(P);
507 switch (Type) {
508 case DRIVE_FIXED:
509 Result = true;
510 return std::error_code();
511 case DRIVE_REMOTE:
512 case DRIVE_CDROM:
513 case DRIVE_RAMDISK:
514 case DRIVE_REMOVABLE:
515 Result = false;
516 return std::error_code();
517 default:
519 }
520 llvm_unreachable("Unreachable!");
521}
522
523std::error_code is_local(const Twine &path, bool &result) {
525
528
529 SmallString<128> Storage;
530 StringRef P = path.toStringRef(Storage);
531
532 // Convert to utf-16.
534 if (std::error_code ec = widenPath(P, WidePath))
535 return ec;
536 return is_local_internal(WidePath, result);
537}
538
539static std::error_code realPathFromHandle(HANDLE H,
540 SmallVectorImpl<wchar_t> &Buffer,
541 DWORD flags = VOLUME_NAME_DOS) {
542 Buffer.resize_for_overwrite(Buffer.capacity());
543 DWORD CountChars = ::GetFinalPathNameByHandleW(
544 H, Buffer.begin(), Buffer.capacity(), FILE_NAME_NORMALIZED | flags);
545 if (CountChars && CountChars >= Buffer.capacity()) {
546 // The buffer wasn't big enough, try again. In this case the return value
547 // *does* indicate the size of the null terminator.
548 Buffer.resize_for_overwrite(CountChars);
549 CountChars = ::GetFinalPathNameByHandleW(H, Buffer.begin(), Buffer.size(),
550 FILE_NAME_NORMALIZED | flags);
551 }
552 Buffer.truncate(CountChars);
553 if (CountChars == 0)
554 return mapWindowsError(GetLastError());
555 return std::error_code();
556}
557
558static std::error_code realPathFromHandle(HANDLE H,
559 SmallVectorImpl<char> &RealPath) {
560 RealPath.clear();
562 if (std::error_code EC = realPathFromHandle(H, Buffer))
563 return EC;
564
565 // Strip the \\?\ prefix. We don't want it ending up in output, and such
566 // paths don't get canonicalized by file APIs.
567 wchar_t *Data = Buffer.data();
568 DWORD CountChars = Buffer.size();
569 stripLongPathPrefix(Data, CountChars);
570
571 // Convert the result from UTF-16 to UTF-8.
572 if (std::error_code EC = UTF16ToUTF8(Data, CountChars, RealPath))
573 return EC;
574
576 return std::error_code();
577}
578
579static std::error_code is_local_internal(HANDLE Handle, bool &Result) {
580 // Fast path for the common case: an ordinary local disk, one system call on
581 // the handle. Everything else goes through the path-based check below.
582 IO_STATUS_BLOCK IoStatus;
583 FILE_FS_DEVICE_INFORMATION Info;
584 if (::NtQueryVolumeInformationFile(Handle, &IoStatus, &Info, sizeof(Info),
585 FileFsDeviceInformation) >= 0 &&
586 (Info.DeviceType == FILE_DEVICE_DISK ||
587 Info.DeviceType == FILE_DEVICE_DISK_FILE_SYSTEM) &&
588 !(Info.Characteristics & (FILE_REMOVABLE_MEDIA | FILE_REMOTE_DEVICE))) {
589 Result = true;
590 return std::error_code();
591 }
592
594 if (std::error_code EC = realPathFromHandle(Handle, FinalPath))
595 return EC;
596 return is_local_internal(FinalPath, Result);
597}
598
599std::error_code is_local(int FD, bool &Result) {
601
602 HANDLE Handle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
603 return is_local_internal(Handle, Result);
604}
605
606static std::error_code setDeleteDisposition(HANDLE Handle, bool Delete) {
607 // Clear the FILE_DISPOSITION_INFO flag first, before checking if it's a
608 // network file. On Windows 7 the function realPathFromHandle() below fails
609 // if the FILE_DISPOSITION_INFO flag was already set to 'DeleteFile = true' by
610 // a prior call.
611 FILE_DISPOSITION_INFO Disposition;
612 Disposition.DeleteFile = false;
613 if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
614 sizeof(Disposition)))
615 return mapWindowsError(::GetLastError());
616 if (!Delete)
617 return std::error_code();
618
619 // Check if the file is on a network (non-local) drive. If so, don't
620 // continue when DeleteFile is true, since it prevents opening the file for
621 // writes.
622 bool IsLocal;
623 if (std::error_code EC = is_local_internal(Handle, IsLocal))
624 return EC;
625
626 if (!IsLocal)
627 return errc::not_supported;
628
629 // The file is on a local drive, we can safely set FILE_DISPOSITION_INFO's
630 // flag.
631 Disposition.DeleteFile = true;
632 if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
633 sizeof(Disposition)))
634 return mapWindowsError(::GetLastError());
635 return std::error_code();
636}
637
638static std::error_code rename_internal(HANDLE FromHandle, const Twine &To,
639 bool ReplaceIfExists) {
641 if (auto EC = widenPath(To, ToWide))
642 return EC;
643
644 std::vector<char> RenameInfoBuf(sizeof(FILE_RENAME_INFO) - sizeof(wchar_t) +
645 (ToWide.size() * sizeof(wchar_t)));
646 FILE_RENAME_INFO &RenameInfo =
647 *reinterpret_cast<FILE_RENAME_INFO *>(RenameInfoBuf.data());
648 RenameInfo.ReplaceIfExists = ReplaceIfExists;
649 RenameInfo.RootDirectory = 0;
650 RenameInfo.FileNameLength = ToWide.size() * sizeof(wchar_t);
651 std::copy(ToWide.begin(), ToWide.end(), &RenameInfo.FileName[0]);
652
653 SetLastError(ERROR_SUCCESS);
654 if (!SetFileInformationByHandle(FromHandle, FileRenameInfo, &RenameInfo,
655 RenameInfoBuf.size())) {
656 unsigned Error = GetLastError();
657 if (Error == ERROR_SUCCESS)
658 Error = ERROR_CALL_NOT_IMPLEMENTED; // Wine doesn't always set error code.
659 return mapWindowsError(Error);
660 }
661
662 return std::error_code();
663}
664
665static std::error_code rename_handle(HANDLE FromHandle, const Twine &To) {
667 if (std::error_code EC = widenPath(To, WideTo))
668 return EC;
669
670 // We normally expect this loop to succeed after a few iterations. If it
671 // requires more than 200 tries, it's more likely that the failures are due to
672 // a true error, so stop trying.
673 for (unsigned Retry = 0; Retry != 200; ++Retry) {
674 auto EC = rename_internal(FromHandle, To, true);
675
676 if (EC ==
677 std::error_code(ERROR_CALL_NOT_IMPLEMENTED, std::system_category())) {
678 // Wine doesn't support SetFileInformationByHandle in rename_internal.
679 // Fall back to MoveFileEx.
681 if (std::error_code EC2 = realPathFromHandle(FromHandle, WideFrom))
682 return EC2;
683 if (::MoveFileExW(WideFrom.begin(), WideTo.begin(),
684 MOVEFILE_REPLACE_EXISTING))
685 return std::error_code();
686 return mapWindowsError(GetLastError());
687 }
688
689 if (!EC || EC != errc::permission_denied)
690 return EC;
691
692 // The destination file probably exists and is currently open in another
693 // process, either because the file was opened without FILE_SHARE_DELETE or
694 // it is mapped into memory (e.g. using MemoryBuffer). Rename it in order to
695 // move it out of the way of the source file. Use FILE_FLAG_DELETE_ON_CLOSE
696 // to arrange for the destination file to be deleted when the other process
697 // closes it.
698 ScopedFileHandle ToHandle(
699 ::CreateFileW(WideTo.begin(), GENERIC_READ | DELETE,
700 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
701 NULL, OPEN_EXISTING,
702 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL));
703 if (!ToHandle) {
704 auto EC = mapWindowsError(GetLastError());
705 // Another process might have raced with us and moved the existing file
706 // out of the way before we had a chance to open it. If that happens, try
707 // to rename the source file again.
709 continue;
710 return EC;
711 }
712
713 BY_HANDLE_FILE_INFORMATION FI;
714 if (!GetFileInformationByHandle(ToHandle, &FI))
715 return mapWindowsError(GetLastError());
716
717 // Try to find a unique new name for the destination file.
718 for (unsigned UniqueId = 0; UniqueId != 200; ++UniqueId) {
719 std::string TmpFilename = (To + ".tmp" + utostr(UniqueId)).str();
720 if (auto EC = rename_internal(ToHandle, TmpFilename, false)) {
721 if (EC == errc::file_exists || EC == errc::permission_denied) {
722 // Again, another process might have raced with us and moved the file
723 // before we could move it. Check whether this is the case, as it
724 // might have caused the permission denied error. If that was the
725 // case, we don't need to move it ourselves.
726 ScopedFileHandle ToHandle2(::CreateFileW(
727 WideTo.begin(), 0,
728 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
729 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
730 if (!ToHandle2) {
731 auto EC = mapWindowsError(GetLastError());
733 break;
734 return EC;
735 }
736 BY_HANDLE_FILE_INFORMATION FI2;
737 if (!GetFileInformationByHandle(ToHandle2, &FI2))
738 return mapWindowsError(GetLastError());
739 if (FI.nFileIndexHigh != FI2.nFileIndexHigh ||
740 FI.nFileIndexLow != FI2.nFileIndexLow ||
741 FI.dwVolumeSerialNumber != FI2.dwVolumeSerialNumber)
742 break;
743 continue;
744 }
745 return EC;
746 }
747 break;
748 }
749
750 // Okay, the old destination file has probably been moved out of the way at
751 // this point, so try to rename the source file again. Still, another
752 // process might have raced with us to create and open the destination
753 // file, so we need to keep doing this until we succeed.
754 }
755
756 // The most likely root cause.
758}
759
760std::error_code rename(const Twine &From, const Twine &To) {
761 // Convert to utf-16.
763 if (std::error_code EC = widenPath(From, WideFrom))
764 return EC;
765
766 ScopedFileHandle FromHandle;
767 // Retry this a few times to defeat badly behaved file system scanners.
768 for (unsigned Retry = 0; Retry != 200; ++Retry) {
769 if (Retry != 0)
770 ::Sleep(10);
771 // `FILE_FLAG_BACKUP_SEMANTICS` must be used to create a handle to a
772 // directory.
773 FromHandle =
774 ::CreateFileW(WideFrom.begin(), GENERIC_READ | DELETE,
775 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
776 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
777 if (FromHandle)
778 break;
779
780 // We don't want to loop if the file doesn't exist.
781 auto EC = mapWindowsError(GetLastError());
783 return EC;
784 }
785 if (!FromHandle)
786 return mapWindowsError(GetLastError());
787
788 return rename_handle(FromHandle, To);
789}
790
791std::error_code resize_file(int FD, uint64_t Size) {
792#ifdef HAVE__CHSIZE_S
793 errno_t error = ::_chsize_s(FD, Size);
794#else
795 errno_t error = ::_chsize(FD, Size);
796#endif
797 return std::error_code(error, std::generic_category());
798}
799
800std::error_code resize_file_sparse(int FD, uint64_t Size) {
801 HANDLE hFile = reinterpret_cast<HANDLE>(::_get_osfhandle(FD));
802 DWORD temp;
803 if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, &temp,
804 NULL)) {
805 return mapWindowsError(GetLastError());
806 }
807 LARGE_INTEGER liSize;
808 liSize.QuadPart = Size;
809 if (!SetFilePointerEx(hFile, liSize, NULL, FILE_BEGIN) ||
810 !SetEndOfFile(hFile)) {
811 return mapWindowsError(GetLastError());
812 }
813 return std::error_code();
814}
815
816std::error_code access(const Twine &Path, AccessMode Mode) {
818
820
821 if (std::error_code EC = widenPath(Path, PathUtf16))
822 return EC;
823
824 DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
825
826 if (Attributes == INVALID_FILE_ATTRIBUTES) {
827 // Avoid returning unexpected error codes when querying for existence.
828 if (Mode == AccessMode::Exist)
830
831 // See if the file didn't actually exist.
832 DWORD LastError = ::GetLastError();
833 if (LastError != ERROR_FILE_NOT_FOUND && LastError != ERROR_PATH_NOT_FOUND)
834 return mapWindowsError(LastError);
836 }
837
838 if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
840
841 if (Mode == AccessMode::Execute && (Attributes & FILE_ATTRIBUTE_DIRECTORY))
843
844 return std::error_code();
845}
846
847bool can_execute(const Twine &Path) {
848 return !access(Path, AccessMode::Execute) ||
849 !access(Path + ".exe", AccessMode::Execute);
850}
851
854 return A.getUniqueID() == B.getUniqueID();
855}
856
857std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
859
860 file_status fsA, fsB;
861 if (std::error_code ec = status(A, fsA))
862 return ec;
863 if (std::error_code ec = status(B, fsB))
864 return ec;
865 result = equivalent(fsA, fsB);
866 return std::error_code();
867}
868
869static bool isReservedName(StringRef path) {
870 // This list of reserved names comes from MSDN, at:
871 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
872 static const char *const sReservedNames[] = {
873 "nul", "con", "prn", "aux", "com1", "com2", "com3", "com4",
874 "com5", "com6", "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
875 "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9"};
876
877 // First, check to see if this is a device namespace, which always
878 // starts with \\.\, since device namespaces are not legal file paths.
879 if (path.starts_with("\\\\.\\"))
880 return true;
881
882 // Then compare against the list of ancient reserved names.
883 for (size_t i = 0; i < std::size(sReservedNames); ++i) {
884 if (path.equals_insensitive(sReservedNames[i]))
885 return true;
886 }
887
888 // The path isn't what we consider reserved.
889 return false;
890}
891
892static file_type file_type_from_attrs(DWORD Attrs) {
893 return (Attrs & FILE_ATTRIBUTE_DIRECTORY) ? file_type::directory_file
895}
896
897static perms perms_from_attrs(DWORD Attrs) {
898 return (Attrs & FILE_ATTRIBUTE_READONLY) ? (all_read | all_exe) : all_all;
899}
900
901static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
903 if (FileHandle == INVALID_HANDLE_VALUE)
904 goto handle_status_error;
905
906 switch (::GetFileType(FileHandle)) {
907 default:
908 llvm_unreachable("Don't know anything about this file type");
909 case FILE_TYPE_UNKNOWN: {
910 DWORD Err = ::GetLastError();
911 if (Err != NO_ERROR)
912 return mapWindowsError(Err);
914 return std::error_code();
915 }
916 case FILE_TYPE_DISK:
917 break;
918 case FILE_TYPE_CHAR:
920 return std::error_code();
921 case FILE_TYPE_PIPE:
923 return std::error_code();
924 }
925
926 BY_HANDLE_FILE_INFORMATION Info;
927 if (!::GetFileInformationByHandle(FileHandle, &Info))
928 goto handle_status_error;
929
930 // File indices aren't necessarily stable after closing the file handle;
931 // instead hash a canonicalized path.
932 //
933 // For getting a canonical path to the file, call GetFinalPathNameByHandleW
934 // with VOLUME_NAME_NT. We don't really care exactly what the path looks
935 // like here, as long as it is canonical (e.g. doesn't differentiate between
936 // whether a file was referred to with upper/lower case names originally).
937 // The default format with VOLUME_NAME_DOS doesn't work with all file system
938 // drivers, such as ImDisk. (See
939 // https://github.com/rust-lang/rust/pull/86447.)
940 uint64_t PathHash;
941 if (std::error_code EC =
942 realPathFromHandle(FileHandle, ntPath, VOLUME_NAME_NT)) {
943 // If realPathFromHandle failed, fall back on the fields
944 // nFileIndex{High,Low} instead. They're not necessarily stable on all file
945 // systems as they're only documented as being unique/stable as long as the
946 // file handle is open - but they're a decent fallback if we couldn't get
947 // the canonical path.
948 PathHash = (static_cast<uint64_t>(Info.nFileIndexHigh) << 32ULL) |
949 static_cast<uint64_t>(Info.nFileIndexLow);
950 } else {
951 PathHash = hash_combine_range(ntPath);
952 }
953
955 file_type_from_attrs(Info.dwFileAttributes),
956 perms_from_attrs(Info.dwFileAttributes), Info.nNumberOfLinks,
957 Info.ftLastAccessTime.dwHighDateTime, Info.ftLastAccessTime.dwLowDateTime,
958 Info.ftLastWriteTime.dwHighDateTime, Info.ftLastWriteTime.dwLowDateTime,
959 Info.dwVolumeSerialNumber, Info.nFileSizeHigh, Info.nFileSizeLow,
960 PathHash);
961 return std::error_code();
962
963handle_status_error:
964 std::error_code Err = mapLastWindowsError();
965 if (Err == std::errc::no_such_file_or_directory)
967 else if (Err == std::errc::permission_denied)
969 else
971 return Err;
972}
973
974std::error_code status(const Twine &path, file_status &result, bool Follow) {
976
977 SmallString<128> path_storage;
978 SmallVector<wchar_t, 128> path_utf16;
979
980 StringRef path8 = path.toStringRef(path_storage);
981 if (isReservedName(path8)) {
983 return std::error_code();
984 }
985
986 if (std::error_code ec = widenPath(path8, path_utf16))
987 return ec;
988
989 DWORD Flags = FILE_FLAG_BACKUP_SEMANTICS;
990 if (!Follow) {
991 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
992 if (attr == INVALID_FILE_ATTRIBUTES)
993 return getStatus(INVALID_HANDLE_VALUE, result);
994
995 // Handle reparse points.
996 if (attr & FILE_ATTRIBUTE_REPARSE_POINT)
997 Flags |= FILE_FLAG_OPEN_REPARSE_POINT;
998 }
999
1001 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
1002 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
1003 NULL, OPEN_EXISTING, Flags, 0));
1004 if (!h)
1005 return getStatus(INVALID_HANDLE_VALUE, result);
1006
1007 return getStatus(h, result);
1008}
1009
1010std::error_code status(int FD, file_status &Result) {
1012
1013 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
1014 return getStatus(FileHandle, Result);
1015}
1016
1017std::error_code status(file_t FileHandle, file_status &Result) {
1019
1020 return getStatus(FileHandle.get(), Result);
1021}
1022
1023ErrorOr<uint64_t> file_size(file_t FileHandle) {
1024 LARGE_INTEGER FileSize;
1025 if (!::GetFileSizeEx(FileHandle.get(), &FileSize))
1026 return mapLastWindowsError();
1027 return FileSize.QuadPart;
1028}
1029
1030unsigned getUmask() { return 0; }
1031
1032std::error_code setPermissions(const Twine &Path, perms Permissions) {
1033 SmallVector<wchar_t, 128> PathUTF16;
1034 if (std::error_code EC = widenPath(Path, PathUTF16))
1035 return EC;
1036
1037 DWORD Attributes = ::GetFileAttributesW(PathUTF16.begin());
1038 if (Attributes == INVALID_FILE_ATTRIBUTES)
1039 return mapWindowsError(GetLastError());
1040
1041 // There are many Windows file attributes that are not to do with the file
1042 // permissions (e.g. FILE_ATTRIBUTE_HIDDEN). We need to be careful to preserve
1043 // them.
1044 if (Permissions & all_write) {
1045 Attributes &= ~FILE_ATTRIBUTE_READONLY;
1046 if (Attributes == 0)
1047 // FILE_ATTRIBUTE_NORMAL indicates no other attributes are set.
1048 Attributes |= FILE_ATTRIBUTE_NORMAL;
1049 } else {
1050 Attributes |= FILE_ATTRIBUTE_READONLY;
1051 // FILE_ATTRIBUTE_NORMAL is not compatible with any other attributes, so
1052 // remove it, if it is present.
1053 Attributes &= ~FILE_ATTRIBUTE_NORMAL;
1054 }
1055
1056 if (!::SetFileAttributesW(PathUTF16.begin(), Attributes))
1057 return mapWindowsError(GetLastError());
1058
1059 return std::error_code();
1060}
1061
1062std::error_code setPermissions(int FD, perms Permissions) {
1063 // FIXME Not implemented.
1064 return std::make_error_code(std::errc::not_supported);
1065}
1066
1067std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
1068 TimePoint<> ModificationTime) {
1069 FILETIME AccessFT = toFILETIME(AccessTime);
1070 FILETIME ModifyFT = toFILETIME(ModificationTime);
1071 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
1072 if (!SetFileTime(FileHandle, NULL, &AccessFT, &ModifyFT))
1073 return mapWindowsError(::GetLastError());
1074 return std::error_code();
1075}
1076
1077std::error_code mapped_file_region::init(sys::fs::file_t OrigFileHandle,
1078 uint64_t Offset, mapmode Mode,
1079 const char *Name) {
1080 this->Mode = Mode;
1081 if (!OrigFileHandle.isValid())
1083
1084 DWORD flprotect;
1085 switch (Mode) {
1086 case readonly:
1087 flprotect = PAGE_READONLY;
1088 break;
1089 case readwrite:
1090 flprotect = PAGE_READWRITE;
1091 break;
1092 case priv:
1093 flprotect = PAGE_WRITECOPY;
1094 break;
1095 }
1096
1097 SmallVector<wchar_t, 128> NameUTF16;
1098 if (Name)
1099 if (std::error_code EC = UTF8ToUTF16(Name, NameUTF16))
1100 return EC;
1101
1102 HANDLE FileMappingHandle =
1103 ::CreateFileMappingW(OrigFileHandle.get(), 0, flprotect, Hi_32(Size),
1104 Lo_32(Size), Name ? c_str(NameUTF16) : 0);
1105 if (FileMappingHandle == NULL) {
1106 std::error_code ec = mapWindowsError(GetLastError());
1107 return ec;
1108 }
1109
1110 DWORD dwDesiredAccess;
1111 switch (Mode) {
1112 case readonly:
1113 dwDesiredAccess = FILE_MAP_READ;
1114 break;
1115 case readwrite:
1116 dwDesiredAccess = FILE_MAP_WRITE;
1117 break;
1118 case priv:
1119 dwDesiredAccess = FILE_MAP_COPY;
1120 break;
1121 }
1122 Mapping = ::MapViewOfFile(FileMappingHandle, dwDesiredAccess, Offset >> 32,
1123 Offset & 0xffffffff, Size);
1124 if (Mapping == NULL) {
1125 std::error_code ec = mapWindowsError(GetLastError());
1126 ::CloseHandle(FileMappingHandle);
1127 return ec;
1128 }
1129
1130 if (Size == 0) {
1131 MEMORY_BASIC_INFORMATION mbi;
1132 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
1133 if (Result == 0) {
1134 std::error_code ec = mapWindowsError(GetLastError());
1135 ::UnmapViewOfFile(Mapping);
1136 ::CloseHandle(FileMappingHandle);
1137 return ec;
1138 }
1139 Size = mbi.RegionSize;
1140 }
1141
1142 // Close the file mapping handle, as it's kept alive by the file mapping. But
1143 // neither the file mapping nor the file mapping handle keep the file handle
1144 // alive, so we need to keep a reference to the file in case all other handles
1145 // are closed and the file is deleted, which may cause invalid data to be read
1146 // from the file.
1147 ::CloseHandle(FileMappingHandle);
1148 HANDLE H;
1149 if (!::DuplicateHandle(::GetCurrentProcess(), OrigFileHandle.get(),
1150 ::GetCurrentProcess(), &H, 0, 0,
1151 DUPLICATE_SAME_ACCESS)) {
1152 std::error_code ec = mapWindowsError(GetLastError());
1153 ::UnmapViewOfFile(Mapping);
1154 return ec;
1155 }
1156
1157 FileHandle = H;
1158 return std::error_code();
1159}
1160
1161mapped_file_region::mapped_file_region(sys::fs::file_t fd, mapmode mode,
1162 size_t length, uint64_t offset,
1163 std::error_code &ec, const char *name)
1164 : Size(length) {
1166
1167 ec = init(fd, offset, mode, name);
1168 if (ec)
1169 copyFrom(mapped_file_region());
1170}
1171
1172static bool hasFlushBufferKernelBug() {
1173 static bool Ret{GetWindowsOSVersion() < llvm::VersionTuple(10, 0, 0, 17763)};
1174 return Ret;
1175}
1176
1177static bool isEXE(StringRef Magic) {
1178 static const char PEMagic[] = {'P', 'E', '\0', '\0'};
1179 if (Magic.starts_with(StringRef("MZ")) && Magic.size() >= 0x3c + 4) {
1180 uint32_t off = read32le(Magic.data() + 0x3c);
1181 // PE/COFF file, either EXE or DLL.
1182 if (Magic.substr(off).starts_with(StringRef(PEMagic, sizeof(PEMagic))))
1183 return true;
1184 }
1185 return false;
1186}
1187
1188void mapped_file_region::unmapImpl() {
1189 if (Mapping) {
1190 // Flush sparse files to avoid data loss.
1191 BY_HANDLE_FILE_INFORMATION FI;
1192 if (::GetFileInformationByHandle(FileHandle.get(), &FI) &&
1193 (FI.dwFileAttributes & FILE_ATTRIBUTE_SPARSE_FILE) != 0)
1194 ::FlushViewOfFile(Mapping, Size);
1195
1196 bool Exe = isEXE(StringRef((char *)Mapping, Size));
1197
1198 ::UnmapViewOfFile(Mapping);
1199
1200 if (Mode == mapmode::readwrite) {
1201 bool DoFlush = Exe && hasFlushBufferKernelBug();
1202 // There is a Windows kernel bug, the exact trigger conditions of which
1203 // are not well understood. When triggered, dirty pages are not properly
1204 // flushed and subsequent process's attempts to read a file can return
1205 // invalid data. Calling FlushFileBuffers on the write handle is
1206 // sufficient to ensure that this bug is not triggered.
1207 // The bug only occurs when writing an executable and executing it right
1208 // after, under high I/O pressure.
1209 if (!DoFlush) {
1210 // Separately, on VirtualBox Shared Folder mounts, writes via memory
1211 // maps always end up unflushed (regardless of version of Windows),
1212 // unless flushed with this explicit call, if they are renamed with
1213 // SetFileInformationByHandle(FileRenameInfo) before closing the output
1214 // handle.
1215 //
1216 // As the flushing is quite expensive, use a heuristic to limit the
1217 // cases where we do the flushing. Only do the flushing if we aren't
1218 // sure we are on a local file system.
1219 bool IsLocal = false;
1220 // Not checking the return value here - if the check fails, assume the
1221 // file isn't local.
1222 is_local_internal(FileHandle.get(), IsLocal);
1223 DoFlush = !IsLocal;
1224 }
1225 if (DoFlush)
1226 ::FlushFileBuffers(FileHandle.get());
1227 }
1228
1229 ::CloseHandle(FileHandle.get());
1230 }
1231}
1232
1233void mapped_file_region::dontNeedImpl() {}
1234
1235void mapped_file_region::randomAccessImpl() {}
1236
1237void mapped_file_region::willNeedImpl() {
1238 struct MEMORY_RANGE_ENTRY {
1239 PVOID VirtualAddress;
1240 SIZE_T NumberOfBytes;
1241 };
1242 // PrefetchVirtualMemory is only available on Windows 8 and later. Since we
1243 // still support compilation on Windows 7, we load the function dynamically.
1244 typedef BOOL(WINAPI * PrefetchVirtualMemory_t)(
1245 HANDLE hProcess, ULONG_PTR NumberOfEntries,
1246 MEMORY_RANGE_ENTRY * VirtualAddresses, ULONG Flags);
1247
1248 static auto pfnPrefetchVirtualMemory = []() -> PrefetchVirtualMemory_t {
1249 HMODULE kernelM =
1251 if (!kernelM)
1252 return nullptr;
1253 return (PrefetchVirtualMemory_t)(void *)::GetProcAddress(
1254 kernelM, "PrefetchVirtualMemory");
1255 }();
1256 if (pfnPrefetchVirtualMemory) {
1257 MEMORY_RANGE_ENTRY Range{Mapping, Size};
1258 pfnPrefetchVirtualMemory(::GetCurrentProcess(), 1, &Range, 0);
1259 }
1260}
1261
1262std::error_code mapped_file_region::sync() const {
1263 if (!::FlushViewOfFile(Mapping, Size))
1264 return mapWindowsError(GetLastError());
1265 if (!::FlushFileBuffers(FileHandle.get()))
1266 return mapWindowsError(GetLastError());
1267 return std::error_code();
1268}
1269
1270int mapped_file_region::alignment() {
1271 SYSTEM_INFO SysInfo;
1272 ::GetSystemInfo(&SysInfo);
1273 return SysInfo.dwAllocationGranularity;
1274}
1275
1276static basic_file_status status_from_find_data(WIN32_FIND_DATAW *FindData) {
1277 return basic_file_status(file_type_from_attrs(FindData->dwFileAttributes),
1278 perms_from_attrs(FindData->dwFileAttributes),
1279 FindData->ftLastAccessTime.dwHighDateTime,
1280 FindData->ftLastAccessTime.dwLowDateTime,
1281 FindData->ftLastWriteTime.dwHighDateTime,
1282 FindData->ftLastWriteTime.dwLowDateTime,
1283 FindData->nFileSizeHigh, FindData->nFileSizeLow);
1284}
1285
1286std::error_code detail::directory_iterator_construct(detail::DirIterState &IT,
1287 StringRef Path,
1288 bool FollowSymlinks) {
1290
1291 SmallVector<wchar_t, 128> PathUTF16;
1292
1293 if (std::error_code EC = widenPath(Path, PathUTF16))
1294 return EC;
1295
1296 // Convert path to the format that Windows is happy with.
1297 size_t PathUTF16Len = PathUTF16.size();
1298 if (PathUTF16Len > 0 && !is_separator(PathUTF16[PathUTF16Len - 1]) &&
1299 PathUTF16[PathUTF16Len - 1] != L':') {
1300 PathUTF16.push_back(L'\\');
1301 PathUTF16.push_back(L'*');
1302 } else {
1303 PathUTF16.push_back(L'*');
1304 }
1305
1306 // Get the first directory entry.
1307 WIN32_FIND_DATAW FirstFind;
1308 ScopedFindHandle FindHandle(::FindFirstFileExW(
1309 c_str(PathUTF16), FindExInfoBasic, &FirstFind, FindExSearchNameMatch,
1310 NULL, FIND_FIRST_EX_LARGE_FETCH));
1311 if (!FindHandle)
1312 return mapWindowsError(::GetLastError());
1313
1314 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
1315 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
1316 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
1317 FirstFind.cFileName[1] == L'.'))
1318 if (!::FindNextFileW(FindHandle, &FirstFind)) {
1319 DWORD LastError = ::GetLastError();
1320 // Check for end.
1321 if (LastError == ERROR_NO_MORE_FILES)
1322 return detail::directory_iterator_destruct(IT);
1323 return mapWindowsError(LastError);
1324 } else {
1325 FilenameLen = ::wcslen(FirstFind.cFileName);
1326 }
1327
1328 // Construct the current directory entry.
1329 SmallString<128> DirectoryEntryNameUTF8;
1330 if (std::error_code EC =
1331 UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
1332 DirectoryEntryNameUTF8))
1333 return EC;
1334
1335 IT.IterationHandle = intptr_t(FindHandle.take());
1336 SmallString<128> DirectoryEntryPath(Path);
1337 path::append(DirectoryEntryPath, DirectoryEntryNameUTF8);
1338 IT.CurrentEntry =
1339 directory_entry(DirectoryEntryPath, FollowSymlinks,
1340 file_type_from_attrs(FirstFind.dwFileAttributes),
1341 status_from_find_data(&FirstFind));
1342
1343 return std::error_code();
1344}
1345
1346std::error_code detail::directory_iterator_destruct(detail::DirIterState &IT) {
1347 if (IT.IterationHandle != 0)
1348 // Closes the handle if it's valid.
1349 ScopedFindHandle close(HANDLE(IT.IterationHandle));
1350 IT.IterationHandle = 0;
1351 IT.CurrentEntry = directory_entry();
1352 return std::error_code();
1353}
1354
1355std::error_code detail::directory_iterator_increment(detail::DirIterState &IT) {
1357
1358 WIN32_FIND_DATAW FindData;
1359 if (!::FindNextFileW(HANDLE(IT.IterationHandle), &FindData)) {
1360 DWORD LastError = ::GetLastError();
1361 // Check for end.
1362 if (LastError == ERROR_NO_MORE_FILES)
1363 return detail::directory_iterator_destruct(IT);
1364 return mapWindowsError(LastError);
1365 }
1366
1367 size_t FilenameLen = ::wcslen(FindData.cFileName);
1368 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
1369 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
1370 FindData.cFileName[1] == L'.'))
1372
1373 SmallString<128> DirectoryEntryPathUTF8;
1374 if (std::error_code EC =
1375 UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
1376 DirectoryEntryPathUTF8))
1377 return EC;
1378
1379 IT.CurrentEntry.replace_filename(
1380 Twine(DirectoryEntryPathUTF8),
1381 file_type_from_attrs(FindData.dwFileAttributes),
1382 status_from_find_data(&FindData));
1383 return std::error_code();
1384}
1385
1386ErrorOr<basic_file_status> directory_entry::status() const { return Status; }
1387
1388static std::error_code nativeFileToFd(Expected<file_t> H, int &ResultFD,
1389 OpenFlags Flags) {
1390 int CrtOpenFlags = 0;
1391 if (Flags & OF_Append)
1392 CrtOpenFlags |= _O_APPEND;
1393
1394 if (Flags & OF_CRLF) {
1395 assert(Flags & OF_Text && "Flags set OF_CRLF without OF_Text");
1396 CrtOpenFlags |= _O_TEXT;
1397 }
1398
1399 ResultFD = -1;
1400 if (!H)
1401 return errorToErrorCode(H.takeError());
1402
1403 ResultFD = ::_open_osfhandle(intptr_t(H->get()), CrtOpenFlags);
1404 if (ResultFD == -1) {
1405 ::CloseHandle(H->get());
1406 return mapWindowsError(ERROR_INVALID_HANDLE);
1407 }
1408 return std::error_code();
1409}
1410
1411static DWORD nativeDisposition(CreationDisposition Disp, OpenFlags Flags) {
1412 // This is a compatibility hack. Really we should respect the creation
1413 // disposition, but a lot of old code relied on the implicit assumption that
1414 // OF_Append implied it would open an existing file. Since the disposition is
1415 // now explicit and defaults to CD_CreateAlways, this assumption would cause
1416 // any usage of OF_Append to append to a new file, even if the file already
1417 // existed. A better solution might have two new creation dispositions:
1418 // CD_AppendAlways and CD_AppendNew. This would also address the problem of
1419 // OF_Append being used on a read-only descriptor, which doesn't make sense.
1420 if (Flags & OF_Append)
1421 return OPEN_ALWAYS;
1422
1423 switch (Disp) {
1424 case CD_CreateAlways:
1425 return CREATE_ALWAYS;
1426 case CD_CreateNew:
1427 return CREATE_NEW;
1428 case CD_OpenAlways:
1429 return OPEN_ALWAYS;
1430 case CD_OpenExisting:
1431 return OPEN_EXISTING;
1432 }
1433 llvm_unreachable("unreachable!");
1434}
1435
1436static DWORD nativeAccess(FileAccess Access, OpenFlags Flags) {
1437 DWORD Result = 0;
1438 if (Access & FA_Read)
1439 Result |= GENERIC_READ;
1440 if (Access & FA_Write)
1441 Result |= GENERIC_WRITE;
1442 if (Flags & OF_Delete)
1443 Result |= DELETE;
1444 if (Flags & OF_UpdateAtime)
1445 Result |= FILE_WRITE_ATTRIBUTES;
1446 if (Flags & OF_UpdateAttributes)
1447 Result |= FILE_WRITE_ATTRIBUTES;
1448 return Result;
1449}
1450
1451static std::error_code openNativeFileInternal(const Twine &Name,
1452 file_t &ResultFile, DWORD Disp,
1453 DWORD Access, DWORD Flags,
1454 bool Inherit = false,
1455 bool AllowDirectory = false) {
1456 SmallVector<wchar_t, 128> PathUTF16;
1457 if (std::error_code EC = widenPath(Name, PathUTF16))
1458 return EC;
1459
1460 SECURITY_ATTRIBUTES SA;
1461 SA.nLength = sizeof(SA);
1462 SA.lpSecurityDescriptor = nullptr;
1463 SA.bInheritHandle = Inherit;
1464
1465 HANDLE H =
1466 ::CreateFileW(PathUTF16.begin(), Access,
1467 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &SA,
1468 Disp, Flags, NULL);
1469 if (H == INVALID_HANDLE_VALUE) {
1470 DWORD LastError = ::GetLastError();
1471 std::error_code EC = mapWindowsError(LastError);
1472 // Provide a better error message when trying to open directories.
1473 // This only runs if we failed to open the file, so there is probably
1474 // no performances issues.
1475 if (LastError != ERROR_ACCESS_DENIED)
1476 return EC;
1477 if (!AllowDirectory && is_directory(Name))
1479 return EC;
1480 }
1481 ResultFile = H;
1482 return std::error_code();
1483}
1484
1485Expected<file_t> openNativeFile(const Twine &Name, CreationDisposition Disp,
1486 FileAccess Access, OpenFlags Flags,
1487 unsigned Mode) {
1489
1490 // Verify that we don't have both "append" and "excl".
1491 assert((!(Disp == CD_CreateNew) || !(Flags & OF_Append)) &&
1492 "Cannot specify both 'CreateNew' and 'Append' file creation flags!");
1493
1494 DWORD NativeDisp = nativeDisposition(Disp, Flags);
1495 DWORD NativeAccess = nativeAccess(Access, Flags);
1496 DWORD NativeFlags = FILE_ATTRIBUTE_NORMAL;
1497 if (Flags & OF_OpenDirectory)
1498 NativeFlags |= FILE_FLAG_BACKUP_SEMANTICS;
1499
1500 bool Inherit = false;
1501 if (Flags & OF_ChildInherit)
1502 Inherit = true;
1503
1504 file_t Result;
1505 std::error_code EC = openNativeFileInternal(
1506 Name, Result, NativeDisp, NativeAccess, NativeFlags, Inherit,
1507 /*AllowDirectory=*/Flags & OF_OpenDirectory);
1508 if (EC)
1509 return errorCodeToError(EC);
1510
1511 if (Flags & OF_UpdateAtime) {
1512 FILETIME FileTime;
1513 SYSTEMTIME SystemTime;
1514 GetSystemTime(&SystemTime);
1515 if (SystemTimeToFileTime(&SystemTime, &FileTime) == 0 ||
1516 SetFileTime(Result.get(), NULL, &FileTime, NULL) == 0) {
1517 DWORD LastError = ::GetLastError();
1518 ::CloseHandle(Result.get());
1519 return errorCodeToError(mapWindowsError(LastError));
1520 }
1521 }
1522
1523 return Result;
1524}
1525
1526std::error_code openFile(const Twine &Name, int &ResultFD,
1527 CreationDisposition Disp, FileAccess Access,
1528 OpenFlags Flags, unsigned int Mode) {
1530
1531 Expected<file_t> Result = openNativeFile(Name, Disp, Access, Flags);
1532 if (!Result)
1533 return errorToErrorCode(Result.takeError());
1534
1535 return nativeFileToFd(std::move(Result), ResultFD, Flags);
1536}
1537
1538static std::error_code directoryRealPath(const Twine &Name,
1539 SmallVectorImpl<char> &RealPath) {
1540 file_t File;
1541 std::error_code EC = openNativeFileInternal(
1542 Name, File, OPEN_EXISTING, GENERIC_READ, FILE_FLAG_BACKUP_SEMANTICS);
1543 if (EC)
1544 return EC;
1545
1546 EC = realPathFromHandle(File.get(), RealPath);
1547 ::CloseHandle(File.get());
1548 return EC;
1549}
1550
1551std::error_code openFileForRead(const Twine &Name, int &ResultFD,
1552 OpenFlags Flags,
1553 SmallVectorImpl<char> *RealPath) {
1555
1556 Expected<file_t> NativeFile = openNativeFileForRead(Name, Flags, RealPath);
1557 return nativeFileToFd(std::move(NativeFile), ResultFD, OF_None);
1558}
1559
1560Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
1561 SmallVectorImpl<char> *RealPath) {
1563
1564 Expected<file_t> Result =
1565 openNativeFile(Name, CD_OpenExisting, FA_Read, Flags);
1566
1567 // Fetch the real name of the file, if the user asked
1568 if (Result && RealPath)
1569 realPathFromHandle(Result->get(), *RealPath);
1570
1571 return Result;
1572}
1573
1575 return reinterpret_cast<HANDLE>(::_get_osfhandle(FD));
1576}
1577
1578file_t getStdinHandle() { return ::GetStdHandle(STD_INPUT_HANDLE); }
1579file_t getStdoutHandle() { return ::GetStdHandle(STD_OUTPUT_HANDLE); }
1580file_t getStderrHandle() { return ::GetStdHandle(STD_ERROR_HANDLE); }
1581
1582static Expected<size_t> readNativeFileImpl(file_t FileHandle,
1584 OVERLAPPED *Overlap) {
1585 // ReadFile can only read 2GB at a time. The caller should check the number of
1586 // bytes and read in a loop until termination.
1587 DWORD BytesToRead =
1588 std::min(size_t(std::numeric_limits<DWORD>::max()), Buf.size());
1589 DWORD BytesRead = 0;
1590 if (::ReadFile(FileHandle.get(), Buf.data(), BytesToRead, &BytesRead,
1591 Overlap))
1592 return BytesRead;
1593 DWORD Err = ::GetLastError();
1594 // EOF is not an error.
1595 if (Err == ERROR_BROKEN_PIPE || Err == ERROR_HANDLE_EOF)
1596 return BytesRead;
1597 return errorCodeToError(mapWindowsError(Err));
1598}
1599
1600Expected<size_t> readNativeFile(file_t FileHandle, MutableArrayRef<char> Buf) {
1602
1603 return readNativeFileImpl(FileHandle, Buf, /*Overlap=*/nullptr);
1604}
1605
1606Expected<size_t> readNativeFileSlice(file_t FileHandle,
1608 uint64_t Offset) {
1610
1611 OVERLAPPED Overlapped = {};
1612 Overlapped.Offset = uint32_t(Offset);
1613 Overlapped.OffsetHigh = uint32_t(Offset >> 32);
1614 return readNativeFileImpl(FileHandle, Buf, &Overlapped);
1615}
1616
1617std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout,
1618 LockKind Kind) {
1619 DWORD Flags = Kind == LockKind::Exclusive ? LOCKFILE_EXCLUSIVE_LOCK : 0;
1620 Flags |= LOCKFILE_FAIL_IMMEDIATELY;
1621 OVERLAPPED OV = {};
1623 auto Start = std::chrono::steady_clock::now();
1624 auto End = Start + Timeout;
1625 do {
1626 if (::LockFileEx(File.get(), Flags, 0, MAXDWORD, MAXDWORD, &OV))
1627 return std::error_code();
1628 DWORD Error = ::GetLastError();
1629 if (Error == ERROR_LOCK_VIOLATION) {
1630 if (Timeout.count() == 0)
1631 break;
1632 ::Sleep(1);
1633 continue;
1634 }
1635 return mapWindowsError(Error);
1636 } while (std::chrono::steady_clock::now() < End);
1637 return mapWindowsError(ERROR_LOCK_VIOLATION);
1638}
1639
1640std::error_code lockFile(int FD, LockKind Kind) {
1641 DWORD Flags = Kind == LockKind::Exclusive ? LOCKFILE_EXCLUSIVE_LOCK : 0;
1642 OVERLAPPED OV = {};
1644 if (::LockFileEx(File.get(), Flags, 0, MAXDWORD, MAXDWORD, &OV))
1645 return std::error_code();
1646 DWORD Error = ::GetLastError();
1647 return mapWindowsError(Error);
1648}
1649
1650std::error_code unlockFile(int FD) {
1651 OVERLAPPED OV = {};
1653 if (::UnlockFileEx(File.get(), 0, MAXDWORD, MAXDWORD, &OV))
1654 return std::error_code();
1655 return mapWindowsError(::GetLastError());
1656}
1657
1658std::error_code closeFile(file_t &F) {
1659 file_t TmpF = F;
1661 if (!::CloseHandle(TmpF.get()))
1662 return mapWindowsError(::GetLastError());
1663 return std::error_code();
1664}
1665
1666std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1667 SmallString<128> NativePath;
1668 llvm::sys::path::native(path, NativePath, path::Style::windows_backslash);
1669 // Convert to utf-16.
1671 std::error_code EC = widenPath(NativePath, Path16);
1672 if (EC && !IgnoreErrors)
1673 return EC;
1674
1675 // SHFileOperation() accepts a list of paths, and so must be double null-
1676 // terminated to indicate the end of the list. The buffer is already null
1677 // terminated, but since that null character is not considered part of the
1678 // vector's size, pushing another one will just consume that byte. So we
1679 // need to push 2 null terminators.
1680 Path16.push_back(0);
1681 Path16.push_back(0);
1682
1683 HRESULT HR;
1684 do {
1685 HR =
1686 CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
1687 if (FAILED(HR))
1688 break;
1689 llvm::scope_exit Uninitialize([] { CoUninitialize(); });
1690 IFileOperation *FileOp = NULL;
1691 HR = CoCreateInstance(CLSID_FileOperation, NULL, CLSCTX_ALL,
1692 IID_PPV_ARGS(&FileOp));
1693 if (FAILED(HR))
1694 break;
1695 llvm::scope_exit FileOpRelease([&FileOp] { FileOp->Release(); });
1696 HR = FileOp->SetOperationFlags(FOF_NO_UI | FOFX_NOCOPYHOOKS);
1697 if (FAILED(HR))
1698 break;
1699 PIDLIST_ABSOLUTE PIDL = ILCreateFromPathW(Path16.data());
1700 llvm::scope_exit FreePIDL([&PIDL] { ILFree(PIDL); });
1701 IShellItem *ShItem = NULL;
1702 HR = SHCreateItemFromIDList(PIDL, IID_PPV_ARGS(&ShItem));
1703 if (FAILED(HR))
1704 break;
1705 llvm::scope_exit ShItemRelease([&ShItem] { ShItem->Release(); });
1706 HR = FileOp->DeleteItem(ShItem, NULL);
1707 if (FAILED(HR))
1708 break;
1709 HR = FileOp->PerformOperations();
1710 } while (false);
1711 if (FAILED(HR) && !IgnoreErrors)
1712 return mapWindowsError(HRESULT_CODE(HR));
1713 return std::error_code();
1714}
1715
1716static void expandTildeExpr(SmallVectorImpl<char> &Path) {
1717 // Path does not begin with a tilde expression.
1718 if (Path.empty() || Path[0] != '~')
1719 return;
1720
1721 StringRef PathStr(Path.begin(), Path.size());
1722 PathStr = PathStr.drop_front();
1723 StringRef Expr =
1724 PathStr.take_until([](char c) { return path::is_separator(c); });
1725
1726 if (!Expr.empty()) {
1727 // This is probably a ~username/ expression. Don't support this on Windows.
1728 return;
1729 }
1730
1731 SmallString<128> HomeDir;
1732 if (!path::home_directory(HomeDir)) {
1733 // For some reason we couldn't get the home directory. Just exit.
1734 return;
1735 }
1736
1737 // Overwrite the first character and insert the rest.
1738 Path[0] = HomeDir[0];
1739 Path.insert(Path.begin() + 1, HomeDir.begin() + 1, HomeDir.end());
1740}
1741
1742void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
1743 dest.clear();
1744 if (path.isTriviallyEmpty())
1745 return;
1746
1747 path.toVector(dest);
1748 expandTildeExpr(dest);
1749
1750 return;
1751}
1752
1753std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1754 bool expand_tilde) {
1756
1757 dest.clear();
1758 if (path.isTriviallyEmpty())
1759 return std::error_code();
1760
1761 if (expand_tilde) {
1762 SmallString<128> Storage;
1763 path.toVector(Storage);
1764 expandTildeExpr(Storage);
1765 return real_path(Storage, dest, false);
1766 }
1767
1768 if (is_directory(path))
1769 return directoryRealPath(path, dest);
1770
1771 int fd;
1772 if (std::error_code EC =
1773 llvm::sys::fs::openFileForRead(path, fd, OF_None, &dest))
1774 return EC;
1775 ::close(fd);
1776 return std::error_code();
1777}
1778
1779#if defined(__clang__)
1780#pragma clang diagnostic push
1781#pragma clang diagnostic ignored "-Wnested-anon-types"
1782#endif
1783// This struct is normally only available in the Windows Driver Kit (WDK)
1784// headers, not in the standard Windows SDK.
1785struct LLVM_REPARSE_DATA_BUFFER {
1786 unsigned long ReparseTag;
1787 unsigned short ReparseDataLength;
1788 unsigned short Reserved;
1789 union {
1790 struct {
1791 unsigned short SubstituteNameOffset;
1792 unsigned short SubstituteNameLength;
1793 unsigned short PrintNameOffset;
1794 unsigned short PrintNameLength;
1795 unsigned long Flags;
1796 wchar_t PathBuffer[1];
1797 } SymbolicLinkReparseBuffer;
1798 struct {
1799 unsigned short SubstituteNameOffset;
1800 unsigned short SubstituteNameLength;
1801 unsigned short PrintNameOffset;
1802 unsigned short PrintNameLength;
1803 wchar_t PathBuffer[1];
1804 } MountPointReparseBuffer;
1805 struct {
1806 unsigned char DataBuffer[1];
1807 } GenericReparseBuffer;
1808 };
1809};
1810#if defined(__clang__)
1811#pragma clang diagnostic pop
1812#endif
1813
1814std::error_code readlink(const Twine &path, SmallVectorImpl<char> &dest) {
1815 dest.clear();
1816
1817 SmallVector<wchar_t, 128> PathUTF16;
1818 if (std::error_code EC = widenPath(path, PathUTF16))
1819 return EC;
1820
1821 // Open the symlink without following it.
1822 ScopedFileHandle H(::CreateFileW(
1823 c_str(PathUTF16), FILE_READ_ATTRIBUTES,
1824 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1825 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
1826 NULL));
1827 if (!H)
1828 return mapWindowsError(::GetLastError());
1829
1830 // Read the reparse point data.
1831 union {
1832 LLVM_REPARSE_DATA_BUFFER RDB;
1833 char Buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
1834 };
1835 DWORD BytesReturned;
1836 if (!::DeviceIoControl(H, FSCTL_GET_REPARSE_POINT, NULL, 0, &RDB,
1837 sizeof(Buffer), &BytesReturned, NULL)) {
1838 DWORD Err = ::GetLastError();
1839 if (Err == ERROR_NOT_A_REPARSE_POINT)
1841 return mapWindowsError(Err);
1842 }
1843
1844 if (RDB.ReparseTag != IO_REPARSE_TAG_SYMLINK)
1846
1847 const auto &SLB = RDB.SymbolicLinkReparseBuffer;
1848 size_t PathBufOffset =
1849 offsetof(LLVM_REPARSE_DATA_BUFFER, SymbolicLinkReparseBuffer.PathBuffer);
1850
1851 // Prefer PrintName (user-friendly, e.g. "C:\foo") over SubstituteName
1852 // (NT-internal, e.g. "\??\C:\foo").
1853 USHORT NameOffset, NameLength;
1854 if (SLB.PrintNameLength != 0) {
1855 NameOffset = SLB.PrintNameOffset;
1856 NameLength = SLB.PrintNameLength;
1857 } else {
1858 NameOffset = SLB.SubstituteNameOffset;
1859 NameLength = SLB.SubstituteNameLength;
1860 }
1861
1862 // Validate that the returned data is large enough to contain the name.
1863 if (PathBufOffset + NameOffset + NameLength > BytesReturned)
1865
1866 const wchar_t *Target = SLB.PathBuffer + NameOffset / sizeof(wchar_t);
1867 USHORT TargetLen = NameLength / sizeof(wchar_t);
1868
1869 if (std::error_code EC = UTF16ToUTF8(Target, TargetLen, dest))
1870 return EC;
1871
1873 return std::error_code();
1874}
1875
1876} // end namespace fs
1877
1878namespace path {
1879static bool getKnownFolderPath(KNOWNFOLDERID folderId,
1880 SmallVectorImpl<char> &result) {
1881 wchar_t *path = nullptr;
1882 if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK)
1883 return false;
1884
1885 bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
1886 ::CoTaskMemFree(path);
1887 if (ok)
1889 return ok;
1890}
1891
1892bool home_directory(SmallVectorImpl<char> &result) {
1893 return getKnownFolderPath(FOLDERID_Profile, result);
1894}
1895
1896bool user_config_directory(SmallVectorImpl<char> &result) {
1897 // Either local or roaming appdata may be suitable in some cases, depending
1898 // on the data. Local is more conservative, Roaming may not always be correct.
1899 return getKnownFolderPath(FOLDERID_LocalAppData, result);
1900}
1901
1902bool cache_directory(SmallVectorImpl<char> &result) {
1903 return getKnownFolderPath(FOLDERID_LocalAppData, result);
1904}
1905
1906static bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {
1907 SmallVector<wchar_t, 1024> Buf;
1908 size_t Size = 1024;
1909 do {
1910 Buf.resize_for_overwrite(Size);
1911 Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.size());
1912 if (Size == 0)
1913 return false;
1914
1915 // Try again with larger buffer.
1916 } while (Size > Buf.size());
1917 Buf.truncate(Size);
1918
1919 return !windows::UTF16ToUTF8(Buf.data(), Size, Res);
1920}
1921
1922static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
1923 const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};
1924 for (auto *Env : EnvironmentVariables) {
1925 if (getTempDirEnvVar(Env, Res))
1926 return true;
1927 }
1928 return false;
1929}
1930
1931void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1932 (void)ErasedOnReboot;
1933 Result.clear();
1934
1935 // Check whether the temporary directory is specified by an environment var.
1936 // This matches GetTempPath logic to some degree. GetTempPath is not used
1937 // directly as it cannot handle evn var longer than 130 chars on Windows 7
1938 // (fixed on Windows 8).
1939 if (getTempDirEnvVar(Result)) {
1940 assert(!Result.empty() && "Unexpected empty path");
1941 native(Result); // Some Unix-like shells use Unix path separator in $TMP.
1942 fs::make_absolute(Result); // Make it absolute if not already.
1943 return;
1944 }
1945
1946 // Fall back to a system default.
1947 const char *DefaultResult = "C:\\Temp";
1948 Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
1950}
1951} // end namespace path
1952
1953namespace windows {
1954std::error_code CodePageToUTF16(unsigned codepage, llvm::StringRef original,
1955 llvm::SmallVectorImpl<wchar_t> &utf16) {
1956 if (!original.empty()) {
1957 int len =
1958 ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1959 original.size(), utf16.begin(), 0);
1960
1961 if (len == 0) {
1962 return mapWindowsError(::GetLastError());
1963 }
1964
1965 utf16.reserve(len + 1);
1966 utf16.resize_for_overwrite(len);
1967
1968 len =
1969 ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1970 original.size(), utf16.begin(), utf16.size());
1971
1972 if (len == 0) {
1973 return mapWindowsError(::GetLastError());
1974 }
1975 }
1976
1977 // Make utf16 null terminated.
1978 utf16.push_back(0);
1979 utf16.pop_back();
1980
1981 return std::error_code();
1982}
1983
1984std::error_code UTF8ToUTF16(llvm::StringRef utf8,
1985 llvm::SmallVectorImpl<wchar_t> &utf16) {
1986 return CodePageToUTF16(CP_UTF8, utf8, utf16);
1987}
1988
1989std::error_code CurCPToUTF16(llvm::StringRef curcp,
1990 llvm::SmallVectorImpl<wchar_t> &utf16) {
1991 return CodePageToUTF16(CP_ACP, curcp, utf16);
1992}
1993
1994static std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
1995 size_t utf16_len,
1996 llvm::SmallVectorImpl<char> &converted) {
1997 if (utf16_len) {
1998 // Get length.
1999 int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len,
2000 converted.begin(), 0, NULL, NULL);
2001
2002 if (len == 0) {
2003 return mapWindowsError(::GetLastError());
2004 }
2005
2006 converted.reserve(len + 1);
2007 converted.resize_for_overwrite(len);
2008
2009 // Now do the actual conversion.
2010 len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.data(),
2011 converted.size(), NULL, NULL);
2012
2013 if (len == 0) {
2014 return mapWindowsError(::GetLastError());
2015 }
2016 }
2017
2018 // Make the new string null terminated.
2019 converted.push_back(0);
2020 converted.pop_back();
2021
2022 return std::error_code();
2023}
2024
2025std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
2026 llvm::SmallVectorImpl<char> &utf8) {
2027 return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
2028}
2029
2030std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
2031 llvm::SmallVectorImpl<char> &curcp) {
2032 return UTF16ToCodePage(CP_ACP, utf16, utf16_len, curcp);
2033}
2034
2035} // end namespace windows
2036} // end namespace sys
2037} // end namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
AMDGPU Kernel Attributes
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate any type of IT block"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow complex IT blocks")))
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
DXIL Resource Access
amode Optimize addressing mode
#define offsetof(TYPE, MEMBER)
std::unique_ptr< MemoryBuffer > openFile(const Twine &Path)
Definition LibDriver.cpp:87
#define F(x, y, z)
Definition MD5.cpp:54
#define H(x, y, z)
Definition MD5.cpp:56
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
This file contains some templates that are useful if you are working with the STL at all.
static const char * name
#define error(X)
size_t size() const
Get the array size.
Definition ArrayRef.h:141
Represents either an error or a value T.
Definition ErrorOr.h:56
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
bool starts_with(StringRef Prefix) const
starts_with - Check if this string starts with the given Prefix.
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:68
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void resize_for_overwrite(size_type N)
Like resize, but T is POD, the new values won't be initialized.
void reserve(size_type N)
void truncate(size_type N)
Like resize, but requires that N is less than size().
void resize(size_type N)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition StringRef.h:888
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition StringRef.h:635
iterator begin() const
Definition StringRef.h:114
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
StringRef take_until(function_ref< bool(char)> F) const
Return the longest prefix of 'this' such that no character in the prefix satisfies the given predicat...
Definition StringRef.h:629
bool equals_insensitive(StringRef RHS) const
Check for string equality, ignoring case.
Definition StringRef.h:170
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
StringRef toStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single StringRef if it can be represented as such.
Definition Twine.h:461
LLVM_ABI void toVector(SmallVectorImpl< char > &Out) const
Append the concatenated string into the given SmallString or SmallVector.
Definition Twine.cpp:32
Represents a version number in the form major[.minor[.subminor[.build]]].
LLVM_ABI TimePoint getLastModificationTime() const
The file modification time as reported from the underlying file system.
LLVM_ABI TimePoint getLastAccessedTime() const
The file access time as reported from the underlying file system.
Represents the result of a call to sys::fs::status().
Definition FileSystem.h:214
LLVM_ABI uint32_t getLinkCount() const
LLVM_ABI UniqueID getUniqueID() const
@ priv
May modify via data, but changes are lost on destruction.
@ readonly
May only access map via const_data as read only.
@ readwrite
May access map via data and modify it. Written to path.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Characteristics
Definition COFF.h:138
initializer< Ty > init(const Ty &Val)
@ Resolved
Queried, materialization begun.
Definition Core.h:550
constexpr uint16_t Magic
Definition SFrame.h:32
uint32_t read32le(const void *P)
Definition Endian.h:412
LLVM_ABI std::error_code directory_iterator_increment(DirIterState &)
LLVM_ABI std::error_code readlink(const Twine &path, SmallVectorImpl< char > &output)
Read the target of a symbolic link.
LLVM_ABI bool can_execute(const Twine &Path)
Can we execute this file?
LLVM_ABI std::error_code closeFile(file_t &F)
Close the file object.
LLVM_ABI std::error_code rename(const Twine &from, const Twine &to)
Rename from to to.
LLVM_ABI std::error_code create_hard_link(const Twine &to, const Twine &from)
Create a hard link from from to to, or return an error.
LLVM_ABI std::error_code access(const Twine &Path, AccessMode Mode)
Can the file be accessed?
LLVM_ABI ErrorOr< space_info > disk_space(const Twine &Path)
Get disk space usage information.
LLVM_ABI Expected< size_t > readNativeFile(file_t FileHandle, MutableArrayRef< char > Buf)
Reads Buf.size() bytes from FileHandle into Buf.
LLVM_ABI unsigned getUmask()
Get file creation mode mask of the process.
LLVM_ABI bool exists(const basic_file_status &status)
Does file exist?
Definition Path.cpp:1107
LLVM_ABI Expected< file_t > openNativeFile(const Twine &Name, CreationDisposition Disp, FileAccess Access, OpenFlags Flags, unsigned Mode=0666)
Opens a file with the specified creation disposition, access mode, and flags and returns a platform-s...
LLVM_ABI file_t getStdoutHandle()
Return an open handle to standard out.
file_type
An enumeration for the file system's view of the type.
Definition FileSystem.h:54
LLVM_ABI std::error_code create_link(const Twine &to, const Twine &from)
Create a link from from to to.
LLVM_ABI std::error_code create_symlink(const Twine &to, const Twine &from)
Create a symbolic link from from to to.
LLVM_ABI void expand_tilde(const Twine &path, SmallVectorImpl< char > &output)
Expands ~ expressions to the user's home directory.
LLVM_ABI std::error_code lockFile(int FD, LockKind Kind=LockKind::Exclusive)
Lock the file.
LLVM_ABI std::error_code set_current_path(const Twine &path)
Set the current path.
LLVM_ABI std::error_code real_path(const Twine &path, SmallVectorImpl< char > &output, bool expand_tilde=false)
Collapse all .
@ CD_OpenExisting
CD_OpenExisting - When opening a file:
Definition FileSystem.h:775
@ CD_OpenAlways
CD_OpenAlways - When opening a file:
Definition FileSystem.h:780
@ CD_CreateAlways
CD_CreateAlways - When opening a file:
Definition FileSystem.h:765
@ CD_CreateNew
CD_CreateNew - When opening a file:
Definition FileSystem.h:770
LLVM_ABI Expected< size_t > readNativeFileSlice(file_t FileHandle, MutableArrayRef< char > Buf, uint64_t Offset)
Reads Buf.size() bytes from FileHandle at offset Offset into Buf.
LLVM_ABI std::string getMainExecutable(const char *argv0, void *MainExecAddr)
Return the path to the main executable, given the value of argv[0] from program startup and the addre...
LLVM_ABI Expected< file_t > openNativeFileForRead(const Twine &Name, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
LLVM_ABI bool status_known(const basic_file_status &s)
Is status available?
Definition Path.cpp:1111
LLVM_ABI std::error_code make_absolute(SmallVectorImpl< char > &path)
Make path an absolute path.
Definition Path.cpp:979
LLVM_ABI std::error_code resize_file_sparse(int FD, uint64_t Size)
Resize path to size with sparse files explicitly enabled.
LLVM_ABI std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout=std::chrono::milliseconds(0), LockKind Kind=LockKind::Exclusive)
Try to locks the file during the specified time.
LLVM_ABI std::error_code current_path(SmallVectorImpl< char > &result)
Get the current path.
LLVM_ABI std::error_code resize_file(int FD, uint64_t Size)
Resize path to size.
LLVM_ABI file_t convertFDToNativeFile(int FD)
Converts from a Posix file descriptor number to a native file handle.
LLVM_ABI std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
LLVM_ABI std::error_code create_directory(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create the directory in path.
LLVM_ABI std::error_code is_local(const Twine &path, bool &result)
Is the file mounted on a local filesystem?
LLVM_ABI std::error_code openFileForRead(const Twine &Name, int &ResultFD, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
LLVM_ABI std::error_code remove_directories(const Twine &path, bool IgnoreErrors=true)
Recursively delete a directory.
LLVM_ABI bool equivalent(file_status A, file_status B)
Do file_status's represent the same thing?
LLVM_ABI file_t getStderrHandle()
Return an open handle to standard error.
LLVM_ABI std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime, TimePoint<> ModificationTime)
Set the file modification and access time.
LLVM_ABI file_t getStdinHandle()
Return an open handle to standard in.
LLVM_ABI std::error_code unlockFile(int FD)
Unlock the file.
std::error_code file_size(const Twine &Path, uint64_t &Result)
Get file size.
Definition FileSystem.h:696
LLVM_ABI std::error_code setPermissions(const Twine &Path, perms Permissions)
Set file permissions.
LLVM_ABI bool is_directory(const basic_file_status &status)
Does status represent a directory?
Definition Path.cpp:1122
LLVM_ABI bool cache_directory(SmallVectorImpl< char > &result)
Get the directory where installed packages should put their machine-local cache, e....
LLVM_ABI bool user_config_directory(SmallVectorImpl< char > &result)
Get the directory where packages should read user-specific configurations.
LLVM_ABI bool remove_dots(SmallVectorImpl< char > &path, bool remove_dot_dot=false, Style style=Style::native)
Remove '.
Definition Path.cpp:779
LLVM_ABI bool has_root_path(const Twine &path, Style style=Style::native)
Has root path?
Definition Path.cpp:646
LLVM_ABI StringRef parent_path(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get parent path.
Definition Path.cpp:478
void make_preferred(SmallVectorImpl< char > &path, Style style=Style::native)
For Windows path styles, convert path to use the preferred path separators.
Definition Path.h:287
LLVM_ABI bool is_relative(const Twine &path, Style style=Style::native)
Is path relative?
Definition Path.cpp:716
LLVM_ABI void system_temp_directory(bool erasedOnReboot, SmallVectorImpl< char > &result)
Get the typical temporary directory for the system, e.g., "/var/tmp" or "C:/TEMP".
LLVM_ABI void native(const Twine &path, SmallVectorImpl< char > &result, Style style=Style::native)
Convert path to the native form.
Definition Path.cpp:551
LLVM_ABI bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
Definition Path.cpp:688
LLVM_ABI StringRef root_name(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get root name.
Definition Path.cpp:384
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:467
LLVM_ABI bool home_directory(SmallVectorImpl< char > &result)
Get the user's home directory.
LLVM_ABI bool is_separator(char value, Style style=Style::native)
Check whether the given char is a path separator on the host OS.
Definition Path.cpp:618
void violationIfEnabled()
Definition IOSandbox.h:37
ScopedSetting scopedDisable()
Definition IOSandbox.h:36
LLVM_ABI std::error_code makeLongFormPath(const Twine &Path8, llvm::SmallVectorImpl< char > &Result8)
Convert a UTF-8 path to a long form UTF-8 path expanding any short 8.3 form components.
LLVM_ABI std::error_code widenPath(const Twine &Path8, SmallVectorImpl< wchar_t > &Path16, size_t MaxPathLen=MAX_PATH)
Convert UTF-8 path to a suitable UTF-16 path for use with the Win32 Unicode File API.
LLVM_ABI HMODULE loadSystemModuleSecure(LPCWSTR lpModuleName)
Retrieves the handle to a in-memory system module such as ntdll.dll, while ensuring we're not retriev...
FILETIME toFILETIME(TimePoint<> TP)
std::chrono::time_point< std::chrono::system_clock, D > TimePoint
A time point on the system clock.
Definition Chrono.h:34
TimePoint< std::chrono::seconds > toTimePoint(std::time_t T)
Convert a std::time_t to a TimePoint.
Definition Chrono.h:65
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
LLVM_ABI std::error_code mapLastWindowsError()
std::error_code make_error_code(BitcodeError E)
SmallVectorImpl< T >::const_pointer c_str(SmallVectorImpl< T > &str)
LLVM_ABI llvm::VersionTuple GetWindowsOSVersion()
Returns the Windows version as Major.Minor.0.BuildNumber.
std::string utostr(uint64_t X, bool isNeg=false)
ScopedHandle< FindHandleTraits > ScopedFindHandle
@ no_such_file_or_directory
Definition Errc.h:65
@ file_exists
Definition Errc.h:48
@ bad_file_descriptor
Definition Errc.h:39
@ not_supported
Definition Errc.h:69
@ invalid_argument
Definition Errc.h:56
@ permission_denied
Definition Errc.h:71
@ is_a_directory
Definition Errc.h:59
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition MathExtras.h:151
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition MathExtras.h:156
@ Success
The lock was released successfully.
@ Timeout
Reached timeout while waiting for the owner to release the lock.
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp:107
LLVM_ABI std::error_code mapWindowsError(unsigned EV)
ScopedHandle< FileHandleTraits > ScopedFileHandle
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
Definition Error.cpp:113
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:287
This class wraps the platform specific file handle/descriptor type to provide an unified representati...
Definition File.h:21
static constexpr value_type Invalid
Value for an invalid file descriptor.
Definition File.h:31
value_type get() const
Get the underlying value and return a platform specific value.
Definition File.h:46
This class wraps the platform specific file handle/descriptor type to provide an unified representati...
Definition File.h:21
int value_type
A file descriptor on UNIX.
Definition File.h:29
bool isValid() const
Is a valid file.
Definition File.h:43
static constexpr value_type Invalid
Value for an invalid file descriptor.
Definition File.h:31
value_type get() const
Get the underlying value and return a platform specific value.
Definition File.h:46
space_info - Self explanatory.
Definition FileSystem.h:68