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