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
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::value_type file_t::Invalid = 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;
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.get(), 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 const char *Name) {
1035 this->Mode = Mode;
1036 if (!OrigFileHandle.isValid())
1038
1039 DWORD flprotect;
1040 switch (Mode) {
1041 case readonly:
1042 flprotect = PAGE_READONLY;
1043 break;
1044 case readwrite:
1045 flprotect = PAGE_READWRITE;
1046 break;
1047 case priv:
1048 flprotect = PAGE_WRITECOPY;
1049 break;
1050 }
1051
1052 SmallVector<wchar_t, 128> NameUTF16;
1053 if (Name)
1054 if (std::error_code EC = UTF8ToUTF16(Name, NameUTF16))
1055 return EC;
1056
1057 HANDLE FileMappingHandle =
1058 ::CreateFileMappingW(OrigFileHandle.get(), 0, flprotect, Hi_32(Size),
1059 Lo_32(Size), Name ? c_str(NameUTF16) : 0);
1060 if (FileMappingHandle == NULL) {
1061 std::error_code ec = mapWindowsError(GetLastError());
1062 return ec;
1063 }
1064
1065 DWORD dwDesiredAccess;
1066 switch (Mode) {
1067 case readonly:
1068 dwDesiredAccess = FILE_MAP_READ;
1069 break;
1070 case readwrite:
1071 dwDesiredAccess = FILE_MAP_WRITE;
1072 break;
1073 case priv:
1074 dwDesiredAccess = FILE_MAP_COPY;
1075 break;
1076 }
1077 Mapping = ::MapViewOfFile(FileMappingHandle, dwDesiredAccess, Offset >> 32,
1078 Offset & 0xffffffff, Size);
1079 if (Mapping == NULL) {
1080 std::error_code ec = mapWindowsError(GetLastError());
1081 ::CloseHandle(FileMappingHandle);
1082 return ec;
1083 }
1084
1085 if (Size == 0) {
1086 MEMORY_BASIC_INFORMATION mbi;
1087 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
1088 if (Result == 0) {
1089 std::error_code ec = mapWindowsError(GetLastError());
1090 ::UnmapViewOfFile(Mapping);
1091 ::CloseHandle(FileMappingHandle);
1092 return ec;
1093 }
1094 Size = mbi.RegionSize;
1095 }
1096
1097 // Close the file mapping handle, as it's kept alive by the file mapping. But
1098 // neither the file mapping nor the file mapping handle keep the file handle
1099 // alive, so we need to keep a reference to the file in case all other handles
1100 // are closed and the file is deleted, which may cause invalid data to be read
1101 // from the file.
1102 ::CloseHandle(FileMappingHandle);
1103 HANDLE H;
1104 if (!::DuplicateHandle(::GetCurrentProcess(), OrigFileHandle.get(),
1105 ::GetCurrentProcess(), &H, 0, 0,
1106 DUPLICATE_SAME_ACCESS)) {
1107 std::error_code ec = mapWindowsError(GetLastError());
1108 ::UnmapViewOfFile(Mapping);
1109 return ec;
1110 }
1111
1112 FileHandle = H;
1113 return std::error_code();
1114}
1115
1116mapped_file_region::mapped_file_region(sys::fs::file_t fd, mapmode mode,
1117 size_t length, uint64_t offset,
1118 std::error_code &ec, const char *name)
1119 : Size(length) {
1121
1122 ec = init(fd, offset, mode, name);
1123 if (ec)
1124 copyFrom(mapped_file_region());
1125}
1126
1127static bool hasFlushBufferKernelBug() {
1128 static bool Ret{GetWindowsOSVersion() < llvm::VersionTuple(10, 0, 0, 17763)};
1129 return Ret;
1130}
1131
1132static bool isEXE(StringRef Magic) {
1133 static const char PEMagic[] = {'P', 'E', '\0', '\0'};
1134 if (Magic.starts_with(StringRef("MZ")) && Magic.size() >= 0x3c + 4) {
1135 uint32_t off = read32le(Magic.data() + 0x3c);
1136 // PE/COFF file, either EXE or DLL.
1137 if (Magic.substr(off).starts_with(StringRef(PEMagic, sizeof(PEMagic))))
1138 return true;
1139 }
1140 return false;
1141}
1142
1143void mapped_file_region::unmapImpl() {
1144 if (Mapping) {
1145
1146 bool Exe = isEXE(StringRef((char *)Mapping, Size));
1147
1148 ::UnmapViewOfFile(Mapping);
1149
1150 if (Mode == mapmode::readwrite) {
1151 bool DoFlush = Exe && hasFlushBufferKernelBug();
1152 // There is a Windows kernel bug, the exact trigger conditions of which
1153 // are not well understood. When triggered, dirty pages are not properly
1154 // flushed and subsequent process's attempts to read a file can return
1155 // invalid data. Calling FlushFileBuffers on the write handle is
1156 // sufficient to ensure that this bug is not triggered.
1157 // The bug only occurs when writing an executable and executing it right
1158 // after, under high I/O pressure.
1159 if (!DoFlush) {
1160 // Separately, on VirtualBox Shared Folder mounts, writes via memory
1161 // maps always end up unflushed (regardless of version of Windows),
1162 // unless flushed with this explicit call, if they are renamed with
1163 // SetFileInformationByHandle(FileRenameInfo) before closing the output
1164 // handle.
1165 //
1166 // As the flushing is quite expensive, use a heuristic to limit the
1167 // cases where we do the flushing. Only do the flushing if we aren't
1168 // sure we are on a local file system.
1169 bool IsLocal = false;
1170 SmallVector<wchar_t, 128> FinalPath;
1171 if (!realPathFromHandle(FileHandle.get(), FinalPath)) {
1172 // Not checking the return value here - if the check fails, assume the
1173 // file isn't local.
1174 is_local_internal(FinalPath, IsLocal);
1175 }
1176 DoFlush = !IsLocal;
1177 }
1178 if (DoFlush)
1179 ::FlushFileBuffers(FileHandle.get());
1180 }
1181
1182 ::CloseHandle(FileHandle.get());
1183 }
1184}
1185
1186void mapped_file_region::dontNeedImpl() {}
1187
1188void mapped_file_region::randomAccessImpl() {}
1189
1190void mapped_file_region::willNeedImpl() {
1191 struct MEMORY_RANGE_ENTRY {
1192 PVOID VirtualAddress;
1193 SIZE_T NumberOfBytes;
1194 };
1195 // PrefetchVirtualMemory is only available on Windows 8 and later. Since we
1196 // still support compilation on Windows 7, we load the function dynamically.
1197 typedef BOOL(WINAPI * PrefetchVirtualMemory_t)(
1198 HANDLE hProcess, ULONG_PTR NumberOfEntries,
1199 MEMORY_RANGE_ENTRY * VirtualAddresses, ULONG Flags);
1200
1201 static auto pfnPrefetchVirtualMemory = []() -> PrefetchVirtualMemory_t {
1202 HMODULE kernelM =
1204 if (!kernelM)
1205 return nullptr;
1206 return (PrefetchVirtualMemory_t)(void *)::GetProcAddress(
1207 kernelM, "PrefetchVirtualMemory");
1208 }();
1209 if (pfnPrefetchVirtualMemory) {
1210 MEMORY_RANGE_ENTRY Range{Mapping, Size};
1211 pfnPrefetchVirtualMemory(::GetCurrentProcess(), 1, &Range, 0);
1212 }
1213}
1214
1215std::error_code mapped_file_region::sync() const {
1216 if (!::FlushViewOfFile(Mapping, Size))
1217 return mapWindowsError(GetLastError());
1218 if (!::FlushFileBuffers(FileHandle.get()))
1219 return mapWindowsError(GetLastError());
1220 return std::error_code();
1221}
1222
1223int mapped_file_region::alignment() {
1224 SYSTEM_INFO SysInfo;
1225 ::GetSystemInfo(&SysInfo);
1226 return SysInfo.dwAllocationGranularity;
1227}
1228
1229static basic_file_status status_from_find_data(WIN32_FIND_DATAW *FindData) {
1230 return basic_file_status(file_type_from_attrs(FindData->dwFileAttributes),
1231 perms_from_attrs(FindData->dwFileAttributes),
1232 FindData->ftLastAccessTime.dwHighDateTime,
1233 FindData->ftLastAccessTime.dwLowDateTime,
1234 FindData->ftLastWriteTime.dwHighDateTime,
1235 FindData->ftLastWriteTime.dwLowDateTime,
1236 FindData->nFileSizeHigh, FindData->nFileSizeLow);
1237}
1238
1239std::error_code detail::directory_iterator_construct(detail::DirIterState &IT,
1240 StringRef Path,
1241 bool FollowSymlinks) {
1243
1244 SmallVector<wchar_t, 128> PathUTF16;
1245
1246 if (std::error_code EC = widenPath(Path, PathUTF16))
1247 return EC;
1248
1249 // Convert path to the format that Windows is happy with.
1250 size_t PathUTF16Len = PathUTF16.size();
1251 if (PathUTF16Len > 0 && !is_separator(PathUTF16[PathUTF16Len - 1]) &&
1252 PathUTF16[PathUTF16Len - 1] != L':') {
1253 PathUTF16.push_back(L'\\');
1254 PathUTF16.push_back(L'*');
1255 } else {
1256 PathUTF16.push_back(L'*');
1257 }
1258
1259 // Get the first directory entry.
1260 WIN32_FIND_DATAW FirstFind;
1261 ScopedFindHandle FindHandle(::FindFirstFileExW(
1262 c_str(PathUTF16), FindExInfoBasic, &FirstFind, FindExSearchNameMatch,
1263 NULL, FIND_FIRST_EX_LARGE_FETCH));
1264 if (!FindHandle)
1265 return mapWindowsError(::GetLastError());
1266
1267 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
1268 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
1269 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
1270 FirstFind.cFileName[1] == L'.'))
1271 if (!::FindNextFileW(FindHandle, &FirstFind)) {
1272 DWORD LastError = ::GetLastError();
1273 // Check for end.
1274 if (LastError == ERROR_NO_MORE_FILES)
1275 return detail::directory_iterator_destruct(IT);
1276 return mapWindowsError(LastError);
1277 } else {
1278 FilenameLen = ::wcslen(FirstFind.cFileName);
1279 }
1280
1281 // Construct the current directory entry.
1282 SmallString<128> DirectoryEntryNameUTF8;
1283 if (std::error_code EC =
1284 UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
1285 DirectoryEntryNameUTF8))
1286 return EC;
1287
1288 IT.IterationHandle = intptr_t(FindHandle.take());
1289 SmallString<128> DirectoryEntryPath(Path);
1290 path::append(DirectoryEntryPath, DirectoryEntryNameUTF8);
1291 IT.CurrentEntry =
1292 directory_entry(DirectoryEntryPath, FollowSymlinks,
1293 file_type_from_attrs(FirstFind.dwFileAttributes),
1294 status_from_find_data(&FirstFind));
1295
1296 return std::error_code();
1297}
1298
1299std::error_code detail::directory_iterator_destruct(detail::DirIterState &IT) {
1300 if (IT.IterationHandle != 0)
1301 // Closes the handle if it's valid.
1302 ScopedFindHandle close(HANDLE(IT.IterationHandle));
1303 IT.IterationHandle = 0;
1304 IT.CurrentEntry = directory_entry();
1305 return std::error_code();
1306}
1307
1308std::error_code detail::directory_iterator_increment(detail::DirIterState &IT) {
1310
1311 WIN32_FIND_DATAW FindData;
1312 if (!::FindNextFileW(HANDLE(IT.IterationHandle), &FindData)) {
1313 DWORD LastError = ::GetLastError();
1314 // Check for end.
1315 if (LastError == ERROR_NO_MORE_FILES)
1316 return detail::directory_iterator_destruct(IT);
1317 return mapWindowsError(LastError);
1318 }
1319
1320 size_t FilenameLen = ::wcslen(FindData.cFileName);
1321 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
1322 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
1323 FindData.cFileName[1] == L'.'))
1325
1326 SmallString<128> DirectoryEntryPathUTF8;
1327 if (std::error_code EC =
1328 UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
1329 DirectoryEntryPathUTF8))
1330 return EC;
1331
1332 IT.CurrentEntry.replace_filename(
1333 Twine(DirectoryEntryPathUTF8),
1334 file_type_from_attrs(FindData.dwFileAttributes),
1335 status_from_find_data(&FindData));
1336 return std::error_code();
1337}
1338
1339ErrorOr<basic_file_status> directory_entry::status() const { return Status; }
1340
1341static std::error_code nativeFileToFd(Expected<file_t> H, int &ResultFD,
1342 OpenFlags Flags) {
1343 int CrtOpenFlags = 0;
1344 if (Flags & OF_Append)
1345 CrtOpenFlags |= _O_APPEND;
1346
1347 if (Flags & OF_CRLF) {
1348 assert(Flags & OF_Text && "Flags set OF_CRLF without OF_Text");
1349 CrtOpenFlags |= _O_TEXT;
1350 }
1351
1352 ResultFD = -1;
1353 if (!H)
1354 return errorToErrorCode(H.takeError());
1355
1356 ResultFD = ::_open_osfhandle(intptr_t(H->get()), CrtOpenFlags);
1357 if (ResultFD == -1) {
1358 ::CloseHandle(H->get());
1359 return mapWindowsError(ERROR_INVALID_HANDLE);
1360 }
1361 return std::error_code();
1362}
1363
1364static DWORD nativeDisposition(CreationDisposition Disp, OpenFlags Flags) {
1365 // This is a compatibility hack. Really we should respect the creation
1366 // disposition, but a lot of old code relied on the implicit assumption that
1367 // OF_Append implied it would open an existing file. Since the disposition is
1368 // now explicit and defaults to CD_CreateAlways, this assumption would cause
1369 // any usage of OF_Append to append to a new file, even if the file already
1370 // existed. A better solution might have two new creation dispositions:
1371 // CD_AppendAlways and CD_AppendNew. This would also address the problem of
1372 // OF_Append being used on a read-only descriptor, which doesn't make sense.
1373 if (Flags & OF_Append)
1374 return OPEN_ALWAYS;
1375
1376 switch (Disp) {
1377 case CD_CreateAlways:
1378 return CREATE_ALWAYS;
1379 case CD_CreateNew:
1380 return CREATE_NEW;
1381 case CD_OpenAlways:
1382 return OPEN_ALWAYS;
1383 case CD_OpenExisting:
1384 return OPEN_EXISTING;
1385 }
1386 llvm_unreachable("unreachable!");
1387}
1388
1389static DWORD nativeAccess(FileAccess Access, OpenFlags Flags) {
1390 DWORD Result = 0;
1391 if (Access & FA_Read)
1392 Result |= GENERIC_READ;
1393 if (Access & FA_Write)
1394 Result |= GENERIC_WRITE;
1395 if (Flags & OF_Delete)
1396 Result |= DELETE;
1397 if (Flags & OF_UpdateAtime)
1398 Result |= FILE_WRITE_ATTRIBUTES;
1399 if (Flags & OF_UpdateAttributes)
1400 Result |= FILE_WRITE_ATTRIBUTES;
1401 return Result;
1402}
1403
1404static std::error_code openNativeFileInternal(const Twine &Name,
1405 file_t &ResultFile, DWORD Disp,
1406 DWORD Access, DWORD Flags,
1407 bool Inherit = false,
1408 bool AllowDirectory = false) {
1409 SmallVector<wchar_t, 128> PathUTF16;
1410 if (std::error_code EC = widenPath(Name, PathUTF16))
1411 return EC;
1412
1413 SECURITY_ATTRIBUTES SA;
1414 SA.nLength = sizeof(SA);
1415 SA.lpSecurityDescriptor = nullptr;
1416 SA.bInheritHandle = Inherit;
1417
1418 HANDLE H =
1419 ::CreateFileW(PathUTF16.begin(), Access,
1420 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &SA,
1421 Disp, Flags, NULL);
1422 if (H == INVALID_HANDLE_VALUE) {
1423 DWORD LastError = ::GetLastError();
1424 std::error_code EC = mapWindowsError(LastError);
1425 // Provide a better error message when trying to open directories.
1426 // This only runs if we failed to open the file, so there is probably
1427 // no performances issues.
1428 if (LastError != ERROR_ACCESS_DENIED)
1429 return EC;
1430 if (!AllowDirectory && is_directory(Name))
1432 return EC;
1433 }
1434 ResultFile = H;
1435 return std::error_code();
1436}
1437
1438Expected<file_t> openNativeFile(const Twine &Name, CreationDisposition Disp,
1439 FileAccess Access, OpenFlags Flags,
1440 unsigned Mode) {
1442
1443 // Verify that we don't have both "append" and "excl".
1444 assert((!(Disp == CD_CreateNew) || !(Flags & OF_Append)) &&
1445 "Cannot specify both 'CreateNew' and 'Append' file creation flags!");
1446
1447 DWORD NativeDisp = nativeDisposition(Disp, Flags);
1448 DWORD NativeAccess = nativeAccess(Access, Flags);
1449 DWORD NativeFlags = FILE_ATTRIBUTE_NORMAL;
1450 if (Flags & OF_OpenDirectory)
1451 NativeFlags |= FILE_FLAG_BACKUP_SEMANTICS;
1452
1453 bool Inherit = false;
1454 if (Flags & OF_ChildInherit)
1455 Inherit = true;
1456
1457 file_t Result;
1458 std::error_code EC = openNativeFileInternal(
1459 Name, Result, NativeDisp, NativeAccess, NativeFlags, Inherit,
1460 /*AllowDirectory=*/Flags & OF_OpenDirectory);
1461 if (EC)
1462 return errorCodeToError(EC);
1463
1464 if (Flags & OF_UpdateAtime) {
1465 FILETIME FileTime;
1466 SYSTEMTIME SystemTime;
1467 GetSystemTime(&SystemTime);
1468 if (SystemTimeToFileTime(&SystemTime, &FileTime) == 0 ||
1469 SetFileTime(Result.get(), NULL, &FileTime, NULL) == 0) {
1470 DWORD LastError = ::GetLastError();
1471 ::CloseHandle(Result.get());
1472 return errorCodeToError(mapWindowsError(LastError));
1473 }
1474 }
1475
1476 return Result;
1477}
1478
1479std::error_code openFile(const Twine &Name, int &ResultFD,
1480 CreationDisposition Disp, FileAccess Access,
1481 OpenFlags Flags, unsigned int Mode) {
1483
1484 Expected<file_t> Result = openNativeFile(Name, Disp, Access, Flags);
1485 if (!Result)
1486 return errorToErrorCode(Result.takeError());
1487
1488 return nativeFileToFd(std::move(Result), ResultFD, Flags);
1489}
1490
1491static std::error_code directoryRealPath(const Twine &Name,
1492 SmallVectorImpl<char> &RealPath) {
1493 file_t File;
1494 std::error_code EC = openNativeFileInternal(
1495 Name, File, OPEN_EXISTING, GENERIC_READ, FILE_FLAG_BACKUP_SEMANTICS);
1496 if (EC)
1497 return EC;
1498
1499 EC = realPathFromHandle(File.get(), RealPath);
1500 ::CloseHandle(File.get());
1501 return EC;
1502}
1503
1504std::error_code openFileForRead(const Twine &Name, int &ResultFD,
1505 OpenFlags Flags,
1506 SmallVectorImpl<char> *RealPath) {
1508
1509 Expected<file_t> NativeFile = openNativeFileForRead(Name, Flags, RealPath);
1510 return nativeFileToFd(std::move(NativeFile), ResultFD, OF_None);
1511}
1512
1513Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
1514 SmallVectorImpl<char> *RealPath) {
1516
1517 Expected<file_t> Result =
1518 openNativeFile(Name, CD_OpenExisting, FA_Read, Flags);
1519
1520 // Fetch the real name of the file, if the user asked
1521 if (Result && RealPath)
1522 realPathFromHandle(Result->get(), *RealPath);
1523
1524 return Result;
1525}
1526
1528 return reinterpret_cast<HANDLE>(::_get_osfhandle(FD));
1529}
1530
1531file_t getStdinHandle() { return ::GetStdHandle(STD_INPUT_HANDLE); }
1532file_t getStdoutHandle() { return ::GetStdHandle(STD_OUTPUT_HANDLE); }
1533file_t getStderrHandle() { return ::GetStdHandle(STD_ERROR_HANDLE); }
1534
1535static Expected<size_t> readNativeFileImpl(file_t FileHandle,
1537 OVERLAPPED *Overlap) {
1538 // ReadFile can only read 2GB at a time. The caller should check the number of
1539 // bytes and read in a loop until termination.
1540 DWORD BytesToRead =
1541 std::min(size_t(std::numeric_limits<DWORD>::max()), Buf.size());
1542 DWORD BytesRead = 0;
1543 if (::ReadFile(FileHandle.get(), Buf.data(), BytesToRead, &BytesRead,
1544 Overlap))
1545 return BytesRead;
1546 DWORD Err = ::GetLastError();
1547 // EOF is not an error.
1548 if (Err == ERROR_BROKEN_PIPE || Err == ERROR_HANDLE_EOF)
1549 return BytesRead;
1550 return errorCodeToError(mapWindowsError(Err));
1551}
1552
1553Expected<size_t> readNativeFile(file_t FileHandle, MutableArrayRef<char> Buf) {
1555
1556 return readNativeFileImpl(FileHandle, Buf, /*Overlap=*/nullptr);
1557}
1558
1559Expected<size_t> readNativeFileSlice(file_t FileHandle,
1561 uint64_t Offset) {
1563
1564 OVERLAPPED Overlapped = {};
1565 Overlapped.Offset = uint32_t(Offset);
1566 Overlapped.OffsetHigh = uint32_t(Offset >> 32);
1567 return readNativeFileImpl(FileHandle, Buf, &Overlapped);
1568}
1569
1570std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout,
1571 LockKind Kind) {
1572 DWORD Flags = Kind == LockKind::Exclusive ? LOCKFILE_EXCLUSIVE_LOCK : 0;
1573 Flags |= LOCKFILE_FAIL_IMMEDIATELY;
1574 OVERLAPPED OV = {};
1576 auto Start = std::chrono::steady_clock::now();
1577 auto End = Start + Timeout;
1578 do {
1579 if (::LockFileEx(File.get(), Flags, 0, MAXDWORD, MAXDWORD, &OV))
1580 return std::error_code();
1581 DWORD Error = ::GetLastError();
1582 if (Error == ERROR_LOCK_VIOLATION) {
1583 if (Timeout.count() == 0)
1584 break;
1585 ::Sleep(1);
1586 continue;
1587 }
1588 return mapWindowsError(Error);
1589 } while (std::chrono::steady_clock::now() < End);
1590 return mapWindowsError(ERROR_LOCK_VIOLATION);
1591}
1592
1593std::error_code lockFile(int FD, LockKind Kind) {
1594 DWORD Flags = Kind == LockKind::Exclusive ? LOCKFILE_EXCLUSIVE_LOCK : 0;
1595 OVERLAPPED OV = {};
1597 if (::LockFileEx(File.get(), Flags, 0, MAXDWORD, MAXDWORD, &OV))
1598 return std::error_code();
1599 DWORD Error = ::GetLastError();
1600 return mapWindowsError(Error);
1601}
1602
1603std::error_code unlockFile(int FD) {
1604 OVERLAPPED OV = {};
1606 if (::UnlockFileEx(File.get(), 0, MAXDWORD, MAXDWORD, &OV))
1607 return std::error_code();
1608 return mapWindowsError(::GetLastError());
1609}
1610
1611std::error_code closeFile(file_t &F) {
1612 file_t TmpF = F;
1614 if (!::CloseHandle(TmpF.get()))
1615 return mapWindowsError(::GetLastError());
1616 return std::error_code();
1617}
1618
1619std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1620 SmallString<128> NativePath;
1621 llvm::sys::path::native(path, NativePath, path::Style::windows_backslash);
1622 // Convert to utf-16.
1624 std::error_code EC = widenPath(NativePath, Path16);
1625 if (EC && !IgnoreErrors)
1626 return EC;
1627
1628 // SHFileOperation() accepts a list of paths, and so must be double null-
1629 // terminated to indicate the end of the list. The buffer is already null
1630 // terminated, but since that null character is not considered part of the
1631 // vector's size, pushing another one will just consume that byte. So we
1632 // need to push 2 null terminators.
1633 Path16.push_back(0);
1634 Path16.push_back(0);
1635
1636 HRESULT HR;
1637 do {
1638 HR =
1639 CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
1640 if (FAILED(HR))
1641 break;
1642 llvm::scope_exit Uninitialize([] { CoUninitialize(); });
1643 IFileOperation *FileOp = NULL;
1644 HR = CoCreateInstance(CLSID_FileOperation, NULL, CLSCTX_ALL,
1645 IID_PPV_ARGS(&FileOp));
1646 if (FAILED(HR))
1647 break;
1648 llvm::scope_exit FileOpRelease([&FileOp] { FileOp->Release(); });
1649 HR = FileOp->SetOperationFlags(FOF_NO_UI | FOFX_NOCOPYHOOKS);
1650 if (FAILED(HR))
1651 break;
1652 PIDLIST_ABSOLUTE PIDL = ILCreateFromPathW(Path16.data());
1653 llvm::scope_exit FreePIDL([&PIDL] { ILFree(PIDL); });
1654 IShellItem *ShItem = NULL;
1655 HR = SHCreateItemFromIDList(PIDL, IID_PPV_ARGS(&ShItem));
1656 if (FAILED(HR))
1657 break;
1658 llvm::scope_exit ShItemRelease([&ShItem] { ShItem->Release(); });
1659 HR = FileOp->DeleteItem(ShItem, NULL);
1660 if (FAILED(HR))
1661 break;
1662 HR = FileOp->PerformOperations();
1663 } while (false);
1664 if (FAILED(HR) && !IgnoreErrors)
1665 return mapWindowsError(HRESULT_CODE(HR));
1666 return std::error_code();
1667}
1668
1669static void expandTildeExpr(SmallVectorImpl<char> &Path) {
1670 // Path does not begin with a tilde expression.
1671 if (Path.empty() || Path[0] != '~')
1672 return;
1673
1674 StringRef PathStr(Path.begin(), Path.size());
1675 PathStr = PathStr.drop_front();
1676 StringRef Expr =
1677 PathStr.take_until([](char c) { return path::is_separator(c); });
1678
1679 if (!Expr.empty()) {
1680 // This is probably a ~username/ expression. Don't support this on Windows.
1681 return;
1682 }
1683
1684 SmallString<128> HomeDir;
1685 if (!path::home_directory(HomeDir)) {
1686 // For some reason we couldn't get the home directory. Just exit.
1687 return;
1688 }
1689
1690 // Overwrite the first character and insert the rest.
1691 Path[0] = HomeDir[0];
1692 Path.insert(Path.begin() + 1, HomeDir.begin() + 1, HomeDir.end());
1693}
1694
1695void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
1696 dest.clear();
1697 if (path.isTriviallyEmpty())
1698 return;
1699
1700 path.toVector(dest);
1701 expandTildeExpr(dest);
1702
1703 return;
1704}
1705
1706std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1707 bool expand_tilde) {
1709
1710 dest.clear();
1711 if (path.isTriviallyEmpty())
1712 return std::error_code();
1713
1714 if (expand_tilde) {
1715 SmallString<128> Storage;
1716 path.toVector(Storage);
1717 expandTildeExpr(Storage);
1718 return real_path(Storage, dest, false);
1719 }
1720
1721 if (is_directory(path))
1722 return directoryRealPath(path, dest);
1723
1724 int fd;
1725 if (std::error_code EC =
1726 llvm::sys::fs::openFileForRead(path, fd, OF_None, &dest))
1727 return EC;
1728 ::close(fd);
1729 return std::error_code();
1730}
1731
1732#if defined(__clang__)
1733#pragma clang diagnostic push
1734#pragma clang diagnostic ignored "-Wnested-anon-types"
1735#endif
1736// This struct is normally only available in the Windows Driver Kit (WDK)
1737// headers, not in the standard Windows SDK.
1738struct LLVM_REPARSE_DATA_BUFFER {
1739 unsigned long ReparseTag;
1740 unsigned short ReparseDataLength;
1741 unsigned short Reserved;
1742 union {
1743 struct {
1744 unsigned short SubstituteNameOffset;
1745 unsigned short SubstituteNameLength;
1746 unsigned short PrintNameOffset;
1747 unsigned short PrintNameLength;
1748 unsigned long Flags;
1749 wchar_t PathBuffer[1];
1750 } SymbolicLinkReparseBuffer;
1751 struct {
1752 unsigned short SubstituteNameOffset;
1753 unsigned short SubstituteNameLength;
1754 unsigned short PrintNameOffset;
1755 unsigned short PrintNameLength;
1756 wchar_t PathBuffer[1];
1757 } MountPointReparseBuffer;
1758 struct {
1759 unsigned char DataBuffer[1];
1760 } GenericReparseBuffer;
1761 };
1762};
1763#if defined(__clang__)
1764#pragma clang diagnostic pop
1765#endif
1766
1767std::error_code readlink(const Twine &path, SmallVectorImpl<char> &dest) {
1768 dest.clear();
1769
1770 SmallVector<wchar_t, 128> PathUTF16;
1771 if (std::error_code EC = widenPath(path, PathUTF16))
1772 return EC;
1773
1774 // Open the symlink without following it.
1775 ScopedFileHandle H(::CreateFileW(
1776 c_str(PathUTF16), FILE_READ_ATTRIBUTES,
1777 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1778 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
1779 NULL));
1780 if (!H)
1781 return mapWindowsError(::GetLastError());
1782
1783 // Read the reparse point data.
1784 union {
1785 LLVM_REPARSE_DATA_BUFFER RDB;
1786 char Buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
1787 };
1788 DWORD BytesReturned;
1789 if (!::DeviceIoControl(H, FSCTL_GET_REPARSE_POINT, NULL, 0, &RDB,
1790 sizeof(Buffer), &BytesReturned, NULL)) {
1791 DWORD Err = ::GetLastError();
1792 if (Err == ERROR_NOT_A_REPARSE_POINT)
1794 return mapWindowsError(Err);
1795 }
1796
1797 if (RDB.ReparseTag != IO_REPARSE_TAG_SYMLINK)
1799
1800 const auto &SLB = RDB.SymbolicLinkReparseBuffer;
1801 size_t PathBufOffset =
1802 offsetof(LLVM_REPARSE_DATA_BUFFER, SymbolicLinkReparseBuffer.PathBuffer);
1803
1804 // Prefer PrintName (user-friendly, e.g. "C:\foo") over SubstituteName
1805 // (NT-internal, e.g. "\??\C:\foo").
1806 USHORT NameOffset, NameLength;
1807 if (SLB.PrintNameLength != 0) {
1808 NameOffset = SLB.PrintNameOffset;
1809 NameLength = SLB.PrintNameLength;
1810 } else {
1811 NameOffset = SLB.SubstituteNameOffset;
1812 NameLength = SLB.SubstituteNameLength;
1813 }
1814
1815 // Validate that the returned data is large enough to contain the name.
1816 if (PathBufOffset + NameOffset + NameLength > BytesReturned)
1818
1819 const wchar_t *Target = SLB.PathBuffer + NameOffset / sizeof(wchar_t);
1820 USHORT TargetLen = NameLength / sizeof(wchar_t);
1821
1822 if (std::error_code EC = UTF16ToUTF8(Target, TargetLen, dest))
1823 return EC;
1824
1826 return std::error_code();
1827}
1828
1829} // end namespace fs
1830
1831namespace path {
1832static bool getKnownFolderPath(KNOWNFOLDERID folderId,
1833 SmallVectorImpl<char> &result) {
1834 wchar_t *path = nullptr;
1835 if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK)
1836 return false;
1837
1838 bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
1839 ::CoTaskMemFree(path);
1840 if (ok)
1842 return ok;
1843}
1844
1845bool home_directory(SmallVectorImpl<char> &result) {
1846 return getKnownFolderPath(FOLDERID_Profile, result);
1847}
1848
1849bool user_config_directory(SmallVectorImpl<char> &result) {
1850 // Either local or roaming appdata may be suitable in some cases, depending
1851 // on the data. Local is more conservative, Roaming may not always be correct.
1852 return getKnownFolderPath(FOLDERID_LocalAppData, result);
1853}
1854
1855bool cache_directory(SmallVectorImpl<char> &result) {
1856 return getKnownFolderPath(FOLDERID_LocalAppData, result);
1857}
1858
1859static bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {
1860 SmallVector<wchar_t, 1024> Buf;
1861 size_t Size = 1024;
1862 do {
1864 Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.size());
1865 if (Size == 0)
1866 return false;
1867
1868 // Try again with larger buffer.
1869 } while (Size > Buf.size());
1870 Buf.truncate(Size);
1871
1872 return !windows::UTF16ToUTF8(Buf.data(), Size, Res);
1873}
1874
1875static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
1876 const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};
1877 for (auto *Env : EnvironmentVariables) {
1878 if (getTempDirEnvVar(Env, Res))
1879 return true;
1880 }
1881 return false;
1882}
1883
1884void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1885 (void)ErasedOnReboot;
1886 Result.clear();
1887
1888 // Check whether the temporary directory is specified by an environment var.
1889 // This matches GetTempPath logic to some degree. GetTempPath is not used
1890 // directly as it cannot handle evn var longer than 130 chars on Windows 7
1891 // (fixed on Windows 8).
1892 if (getTempDirEnvVar(Result)) {
1893 assert(!Result.empty() && "Unexpected empty path");
1894 native(Result); // Some Unix-like shells use Unix path separator in $TMP.
1895 fs::make_absolute(Result); // Make it absolute if not already.
1896 return;
1897 }
1898
1899 // Fall back to a system default.
1900 const char *DefaultResult = "C:\\Temp";
1901 Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
1903}
1904} // end namespace path
1905
1906namespace windows {
1907std::error_code CodePageToUTF16(unsigned codepage, llvm::StringRef original,
1908 llvm::SmallVectorImpl<wchar_t> &utf16) {
1909 if (!original.empty()) {
1910 int len =
1911 ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1912 original.size(), utf16.begin(), 0);
1913
1914 if (len == 0) {
1915 return mapWindowsError(::GetLastError());
1916 }
1917
1918 utf16.reserve(len + 1);
1919 utf16.resize_for_overwrite(len);
1920
1921 len =
1922 ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1923 original.size(), utf16.begin(), utf16.size());
1924
1925 if (len == 0) {
1926 return mapWindowsError(::GetLastError());
1927 }
1928 }
1929
1930 // Make utf16 null terminated.
1931 utf16.push_back(0);
1932 utf16.pop_back();
1933
1934 return std::error_code();
1935}
1936
1937std::error_code UTF8ToUTF16(llvm::StringRef utf8,
1938 llvm::SmallVectorImpl<wchar_t> &utf16) {
1939 return CodePageToUTF16(CP_UTF8, utf8, utf16);
1940}
1941
1942std::error_code CurCPToUTF16(llvm::StringRef curcp,
1943 llvm::SmallVectorImpl<wchar_t> &utf16) {
1944 return CodePageToUTF16(CP_ACP, curcp, utf16);
1945}
1946
1947static std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
1948 size_t utf16_len,
1949 llvm::SmallVectorImpl<char> &converted) {
1950 if (utf16_len) {
1951 // Get length.
1952 int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len,
1953 converted.begin(), 0, NULL, NULL);
1954
1955 if (len == 0) {
1956 return mapWindowsError(::GetLastError());
1957 }
1958
1959 converted.reserve(len + 1);
1960 converted.resize_for_overwrite(len);
1961
1962 // Now do the actual conversion.
1963 len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.data(),
1964 converted.size(), NULL, NULL);
1965
1966 if (len == 0) {
1967 return mapWindowsError(::GetLastError());
1968 }
1969 }
1970
1971 // Make the new string null terminated.
1972 converted.push_back(0);
1973 converted.pop_back();
1974
1975 return std::error_code();
1976}
1977
1978std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
1979 llvm::SmallVectorImpl<char> &utf8) {
1980 return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
1981}
1982
1983std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
1984 llvm::SmallVectorImpl<char> &curcp) {
1985 return UTF16ToCodePage(CP_ACP, utf16, utf16_len, curcp);
1986}
1987
1988} // end namespace windows
1989} // end namespace sys
1990} // end namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned 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.
initializer< Ty > init(const Ty &Val)
@ Resolved
Queried, materialization begun.
Definition Core.h:549
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: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: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.
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
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