LLVM 20.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"
21#include <fcntl.h>
22#include <sys/stat.h>
23#include <sys/types.h>
24
25// These two headers must be included last, and make sure shlobj is required
26// after Windows.h to make sure it picks up our definition of _WIN32_WINNT
28#include <shellapi.h>
29#include <shlobj.h>
30
31#undef max
32
33// MinGW doesn't define this.
34#ifndef _ERRNO_T_DEFINED
35#define _ERRNO_T_DEFINED
36typedef int errno_t;
37#endif
38
39#ifdef _MSC_VER
40#pragma comment(lib, "advapi32.lib") // This provides CryptAcquireContextW.
41#pragma comment(lib, "ole32.lib") // This provides CoTaskMemFree
42#endif
43
44using namespace llvm;
45
46using llvm::sys::windows::CurCPToUTF16;
47using llvm::sys::windows::UTF16ToUTF8;
48using llvm::sys::windows::UTF8ToUTF16;
50
51static bool is_separator(const wchar_t value) {
52 switch (value) {
53 case L'\\':
54 case L'/':
55 return true;
56 default:
57 return false;
58 }
59}
60
61namespace llvm {
62namespace sys {
63namespace windows {
64
65// Convert a UTF-8 path to UTF-16. Also, if the absolute equivalent of the path
66// is longer than the limit that the Win32 Unicode File API can tolerate, make
67// it an absolute normalized path prefixed by '\\?\'.
68std::error_code widenPath(const Twine &Path8, SmallVectorImpl<wchar_t> &Path16,
69 size_t MaxPathLen) {
70 assert(MaxPathLen <= MAX_PATH);
71
72 // Several operations would convert Path8 to SmallString; more efficient to do
73 // it once up front.
74 SmallString<MAX_PATH> Path8Str;
75 Path8.toVector(Path8Str);
76
77 // If the path is a long path, mangled into forward slashes, normalize
78 // back to backslashes here.
79 if (Path8Str.starts_with("//?/"))
81
82 if (std::error_code EC = UTF8ToUTF16(Path8Str, Path16))
83 return EC;
84
85 const bool IsAbsolute = llvm::sys::path::is_absolute(Path8);
86 size_t CurPathLen;
87 if (IsAbsolute)
88 CurPathLen = 0; // No contribution from current_path needed.
89 else {
90 CurPathLen = ::GetCurrentDirectoryW(
91 0, NULL); // Returns the size including the null terminator.
92 if (CurPathLen == 0)
93 return mapWindowsError(::GetLastError());
94 }
95
96 const char *const LongPathPrefix = "\\\\?\\";
97
98 if ((Path16.size() + CurPathLen) < MaxPathLen ||
99 Path8Str.starts_with(LongPathPrefix))
100 return std::error_code();
101
102 if (!IsAbsolute) {
103 if (std::error_code EC = llvm::sys::fs::make_absolute(Path8Str))
104 return EC;
105 }
106
107 // Remove '.' and '..' because long paths treat these as real path components.
108 // Explicitly use the backslash form here, as we're prepending the \\?\
109 // prefix.
112
113 const StringRef RootName = llvm::sys::path::root_name(Path8Str);
114 assert(!RootName.empty() &&
115 "Root name cannot be empty for an absolute path!");
116
117 SmallString<2 * MAX_PATH> FullPath(LongPathPrefix);
118 if (RootName[1] != ':') { // Check if UNC.
119 FullPath.append("UNC\\");
120 FullPath.append(Path8Str.begin() + 2, Path8Str.end());
121 } else
122 FullPath.append(Path8Str);
123
124 return UTF8ToUTF16(FullPath, Path16);
125}
126
127} // end namespace windows
128
129namespace fs {
130
131const file_t kInvalidFile = INVALID_HANDLE_VALUE;
132
133std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
135 PathName.resize_for_overwrite(PathName.capacity());
136 DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.size());
137
138 // A zero return value indicates a failure other than insufficient space.
139 if (Size == 0)
140 return "";
141
142 // Insufficient space is determined by a return value equal to the size of
143 // the buffer passed in.
144 if (Size == PathName.capacity())
145 return "";
146
147 // On success, GetModuleFileNameW returns the number of characters written to
148 // the buffer not including the NULL terminator.
149 PathName.truncate(Size);
150
151 // Convert the result from UTF-16 to UTF-8.
152 SmallVector<char, MAX_PATH> PathNameUTF8;
153 if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
154 return "";
155
157
158 SmallString<256> RealPath;
159 sys::fs::real_path(PathNameUTF8, RealPath);
160 if (RealPath.size())
161 return std::string(RealPath);
162 return std::string(PathNameUTF8.data());
163}
164
165UniqueID file_status::getUniqueID() const {
166 return UniqueID(VolumeSerialNumber, PathHash);
167}
168
170 ULARGE_INTEGER Avail, Total, Free;
171 if (!::GetDiskFreeSpaceExA(Path.str().c_str(), &Avail, &Total, &Free))
172 return mapWindowsError(::GetLastError());
173 space_info SpaceInfo;
174 SpaceInfo.capacity =
175 (static_cast<uint64_t>(Total.HighPart) << 32) + Total.LowPart;
176 SpaceInfo.free = (static_cast<uint64_t>(Free.HighPart) << 32) + Free.LowPart;
177 SpaceInfo.available =
178 (static_cast<uint64_t>(Avail.HighPart) << 32) + Avail.LowPart;
179 return SpaceInfo;
180}
181
183 FILETIME Time;
184 Time.dwLowDateTime = LastAccessedTimeLow;
185 Time.dwHighDateTime = LastAccessedTimeHigh;
186 return toTimePoint(Time);
187}
188
190 FILETIME Time;
191 Time.dwLowDateTime = LastWriteTimeLow;
192 Time.dwHighDateTime = LastWriteTimeHigh;
193 return toTimePoint(Time);
194}
195
196uint32_t file_status::getLinkCount() const { return NumLinks; }
197
198std::error_code current_path(SmallVectorImpl<char> &result) {
200 DWORD len = MAX_PATH;
201
202 do {
203 cur_path.resize_for_overwrite(len);
204 len = ::GetCurrentDirectoryW(cur_path.size(), cur_path.data());
205
206 // A zero return value indicates a failure other than insufficient space.
207 if (len == 0)
208 return mapWindowsError(::GetLastError());
209
210 // If there's insufficient space, the len returned is larger than the len
211 // given.
212 } while (len > cur_path.size());
213
214 // On success, GetCurrentDirectoryW returns the number of characters not
215 // including the null-terminator.
216 cur_path.truncate(len);
217
218 if (std::error_code EC =
219 UTF16ToUTF8(cur_path.begin(), cur_path.size(), result))
220 return EC;
221
223 return std::error_code();
224}
225
226std::error_code set_current_path(const Twine &path) {
227 // Convert to utf-16.
229 if (std::error_code ec = widenPath(path, wide_path))
230 return ec;
231
232 if (!::SetCurrentDirectoryW(wide_path.begin()))
233 return mapWindowsError(::GetLastError());
234
235 return std::error_code();
236}
237
238std::error_code create_directory(const Twine &path, bool IgnoreExisting,
239 perms Perms) {
240 SmallVector<wchar_t, 128> path_utf16;
241
242 // CreateDirectoryW has a lower maximum path length as it must leave room for
243 // an 8.3 filename.
244 if (std::error_code ec = widenPath(path, path_utf16, MAX_PATH - 12))
245 return ec;
246
247 if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
248 DWORD LastError = ::GetLastError();
249 if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
250 return mapWindowsError(LastError);
251 }
252
253 return std::error_code();
254}
255
256// We can't use symbolic links for windows.
257std::error_code create_link(const Twine &to, const Twine &from) {
258 // Convert to utf-16.
261 if (std::error_code ec = widenPath(from, wide_from))
262 return ec;
263 if (std::error_code ec = widenPath(to, wide_to))
264 return ec;
265
266 if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
267 return mapWindowsError(::GetLastError());
268
269 return std::error_code();
270}
271
272std::error_code create_hard_link(const Twine &to, const Twine &from) {
273 return create_link(to, from);
274}
275
276std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
277 SmallVector<wchar_t, 128> path_utf16;
278
279 if (std::error_code ec = widenPath(path, path_utf16))
280 return ec;
281
282 // We don't know whether this is a file or a directory, and remove() can
283 // accept both. The usual way to delete a file or directory is to use one of
284 // the DeleteFile or RemoveDirectory functions, but that requires you to know
285 // which one it is. We could stat() the file to determine that, but that would
286 // cost us additional system calls, which can be slow in a directory
287 // containing a large number of files. So instead we call CreateFile directly.
288 // The important part is the FILE_FLAG_DELETE_ON_CLOSE flag, which causes the
289 // file to be deleted once it is closed. We also use the flags
290 // FILE_FLAG_BACKUP_SEMANTICS (which allows us to open directories), and
291 // FILE_FLAG_OPEN_REPARSE_POINT (don't follow symlinks).
292 ScopedFileHandle h(::CreateFileW(
293 c_str(path_utf16), DELETE,
294 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
295 OPEN_EXISTING,
296 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS |
297 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_DELETE_ON_CLOSE,
298 NULL));
299 if (!h) {
300 std::error_code EC = mapWindowsError(::GetLastError());
301 if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
302 return EC;
303 }
304
305 return std::error_code();
306}
307
308static std::error_code is_local_internal(SmallVectorImpl<wchar_t> &Path,
309 bool &Result) {
310 SmallVector<wchar_t, 128> VolumePath;
311 size_t Len = 128;
312 while (true) {
313 VolumePath.resize(Len);
314 BOOL Success =
315 ::GetVolumePathNameW(Path.data(), VolumePath.data(), VolumePath.size());
316
317 if (Success)
318 break;
319
320 DWORD Err = ::GetLastError();
321 if (Err != ERROR_INSUFFICIENT_BUFFER)
322 return mapWindowsError(Err);
323
324 Len *= 2;
325 }
326 // If the output buffer has exactly enough space for the path name, but not
327 // the null terminator, it will leave the output unterminated. Push a null
328 // terminator onto the end to ensure that this never happens.
329 VolumePath.push_back(L'\0');
330 VolumePath.truncate(wcslen(VolumePath.data()));
331 const wchar_t *P = VolumePath.data();
332
333 UINT Type = ::GetDriveTypeW(P);
334 switch (Type) {
335 case DRIVE_FIXED:
336 Result = true;
337 return std::error_code();
338 case DRIVE_REMOTE:
339 case DRIVE_CDROM:
340 case DRIVE_RAMDISK:
341 case DRIVE_REMOVABLE:
342 Result = false;
343 return std::error_code();
344 default:
346 }
347 llvm_unreachable("Unreachable!");
348}
349
350std::error_code is_local(const Twine &path, bool &result) {
353
354 SmallString<128> Storage;
355 StringRef P = path.toStringRef(Storage);
356
357 // Convert to utf-16.
359 if (std::error_code ec = widenPath(P, WidePath))
360 return ec;
361 return is_local_internal(WidePath, result);
362}
363
364static std::error_code realPathFromHandle(HANDLE H,
366 DWORD flags = VOLUME_NAME_DOS) {
367 Buffer.resize_for_overwrite(Buffer.capacity());
368 DWORD CountChars = ::GetFinalPathNameByHandleW(
369 H, Buffer.begin(), Buffer.capacity(), FILE_NAME_NORMALIZED | flags);
370 if (CountChars && CountChars >= Buffer.capacity()) {
371 // The buffer wasn't big enough, try again. In this case the return value
372 // *does* indicate the size of the null terminator.
373 Buffer.resize_for_overwrite(CountChars);
374 CountChars = ::GetFinalPathNameByHandleW(H, Buffer.begin(), Buffer.size(),
375 FILE_NAME_NORMALIZED | flags);
376 }
377 Buffer.truncate(CountChars);
378 if (CountChars == 0)
379 return mapWindowsError(GetLastError());
380 return std::error_code();
381}
382
383static std::error_code realPathFromHandle(HANDLE H,
384 SmallVectorImpl<char> &RealPath) {
385 RealPath.clear();
387 if (std::error_code EC = realPathFromHandle(H, Buffer))
388 return EC;
389
390 // Strip the \\?\ prefix. We don't want it ending up in output, and such
391 // paths don't get canonicalized by file APIs.
392 wchar_t *Data = Buffer.data();
393 DWORD CountChars = Buffer.size();
394 if (CountChars >= 8 && ::memcmp(Data, L"\\\\?\\UNC\\", 16) == 0) {
395 // Convert \\?\UNC\foo\bar to \\foo\bar
396 CountChars -= 6;
397 Data += 6;
398 Data[0] = '\\';
399 } else if (CountChars >= 4 && ::memcmp(Data, L"\\\\?\\", 8) == 0) {
400 // Convert \\?\c:\foo to c:\foo
401 CountChars -= 4;
402 Data += 4;
403 }
404
405 // Convert the result from UTF-16 to UTF-8.
406 if (std::error_code EC = UTF16ToUTF8(Data, CountChars, RealPath))
407 return EC;
408
410 return std::error_code();
411}
412
413std::error_code is_local(int FD, bool &Result) {
415 HANDLE Handle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
416
417 if (std::error_code EC = realPathFromHandle(Handle, FinalPath))
418 return EC;
419
420 return is_local_internal(FinalPath, Result);
421}
422
423static std::error_code setDeleteDisposition(HANDLE Handle, bool Delete) {
424 // Clear the FILE_DISPOSITION_INFO flag first, before checking if it's a
425 // network file. On Windows 7 the function realPathFromHandle() below fails
426 // if the FILE_DISPOSITION_INFO flag was already set to 'DeleteFile = true' by
427 // a prior call.
428 FILE_DISPOSITION_INFO Disposition;
429 Disposition.DeleteFile = false;
430 if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
431 sizeof(Disposition)))
432 return mapWindowsError(::GetLastError());
433 if (!Delete)
434 return std::error_code();
435
436 // Check if the file is on a network (non-local) drive. If so, don't
437 // continue when DeleteFile is true, since it prevents opening the file for
438 // writes.
440 if (std::error_code EC = realPathFromHandle(Handle, FinalPath))
441 return EC;
442
443 bool IsLocal;
444 if (std::error_code EC = is_local_internal(FinalPath, IsLocal))
445 return EC;
446
447 if (!IsLocal)
448 return errc::not_supported;
449
450 // The file is on a local drive, we can safely set FILE_DISPOSITION_INFO's
451 // flag.
452 Disposition.DeleteFile = true;
453 if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
454 sizeof(Disposition)))
455 return mapWindowsError(::GetLastError());
456 return std::error_code();
457}
458
459static std::error_code rename_internal(HANDLE FromHandle, const Twine &To,
460 bool ReplaceIfExists) {
462 if (auto EC = widenPath(To, ToWide))
463 return EC;
464
465 std::vector<char> RenameInfoBuf(sizeof(FILE_RENAME_INFO) - sizeof(wchar_t) +
466 (ToWide.size() * sizeof(wchar_t)));
467 FILE_RENAME_INFO &RenameInfo =
468 *reinterpret_cast<FILE_RENAME_INFO *>(RenameInfoBuf.data());
469 RenameInfo.ReplaceIfExists = ReplaceIfExists;
470 RenameInfo.RootDirectory = 0;
471 RenameInfo.FileNameLength = ToWide.size() * sizeof(wchar_t);
472 std::copy(ToWide.begin(), ToWide.end(), &RenameInfo.FileName[0]);
473
474 SetLastError(ERROR_SUCCESS);
475 if (!SetFileInformationByHandle(FromHandle, FileRenameInfo, &RenameInfo,
476 RenameInfoBuf.size())) {
477 unsigned Error = GetLastError();
478 if (Error == ERROR_SUCCESS)
479 Error = ERROR_CALL_NOT_IMPLEMENTED; // Wine doesn't always set error code.
480 return mapWindowsError(Error);
481 }
482
483 return std::error_code();
484}
485
486static std::error_code rename_handle(HANDLE FromHandle, const Twine &To) {
488 if (std::error_code EC = widenPath(To, WideTo))
489 return EC;
490
491 // We normally expect this loop to succeed after a few iterations. If it
492 // requires more than 200 tries, it's more likely that the failures are due to
493 // a true error, so stop trying.
494 for (unsigned Retry = 0; Retry != 200; ++Retry) {
495 auto EC = rename_internal(FromHandle, To, true);
496
497 if (EC ==
498 std::error_code(ERROR_CALL_NOT_IMPLEMENTED, std::system_category())) {
499 // Wine doesn't support SetFileInformationByHandle in rename_internal.
500 // Fall back to MoveFileEx.
502 if (std::error_code EC2 = realPathFromHandle(FromHandle, WideFrom))
503 return EC2;
504 if (::MoveFileExW(WideFrom.begin(), WideTo.begin(),
505 MOVEFILE_REPLACE_EXISTING))
506 return std::error_code();
507 return mapWindowsError(GetLastError());
508 }
509
510 if (!EC || EC != errc::permission_denied)
511 return EC;
512
513 // The destination file probably exists and is currently open in another
514 // process, either because the file was opened without FILE_SHARE_DELETE or
515 // it is mapped into memory (e.g. using MemoryBuffer). Rename it in order to
516 // move it out of the way of the source file. Use FILE_FLAG_DELETE_ON_CLOSE
517 // to arrange for the destination file to be deleted when the other process
518 // closes it.
519 ScopedFileHandle ToHandle(
520 ::CreateFileW(WideTo.begin(), GENERIC_READ | DELETE,
521 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
522 NULL, OPEN_EXISTING,
523 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL));
524 if (!ToHandle) {
525 auto EC = mapWindowsError(GetLastError());
526 // Another process might have raced with us and moved the existing file
527 // out of the way before we had a chance to open it. If that happens, try
528 // to rename the source file again.
530 continue;
531 return EC;
532 }
533
534 BY_HANDLE_FILE_INFORMATION FI;
535 if (!GetFileInformationByHandle(ToHandle, &FI))
536 return mapWindowsError(GetLastError());
537
538 // Try to find a unique new name for the destination file.
539 for (unsigned UniqueId = 0; UniqueId != 200; ++UniqueId) {
540 std::string TmpFilename = (To + ".tmp" + utostr(UniqueId)).str();
541 if (auto EC = rename_internal(ToHandle, TmpFilename, false)) {
542 if (EC == errc::file_exists || EC == errc::permission_denied) {
543 // Again, another process might have raced with us and moved the file
544 // before we could move it. Check whether this is the case, as it
545 // might have caused the permission denied error. If that was the
546 // case, we don't need to move it ourselves.
547 ScopedFileHandle ToHandle2(::CreateFileW(
548 WideTo.begin(), 0,
549 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
550 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
551 if (!ToHandle2) {
552 auto EC = mapWindowsError(GetLastError());
554 break;
555 return EC;
556 }
557 BY_HANDLE_FILE_INFORMATION FI2;
558 if (!GetFileInformationByHandle(ToHandle2, &FI2))
559 return mapWindowsError(GetLastError());
560 if (FI.nFileIndexHigh != FI2.nFileIndexHigh ||
561 FI.nFileIndexLow != FI2.nFileIndexLow ||
562 FI.dwVolumeSerialNumber != FI2.dwVolumeSerialNumber)
563 break;
564 continue;
565 }
566 return EC;
567 }
568 break;
569 }
570
571 // Okay, the old destination file has probably been moved out of the way at
572 // this point, so try to rename the source file again. Still, another
573 // process might have raced with us to create and open the destination
574 // file, so we need to keep doing this until we succeed.
575 }
576
577 // The most likely root cause.
579}
580
581std::error_code rename(const Twine &From, const Twine &To) {
582 // Convert to utf-16.
584 if (std::error_code EC = widenPath(From, WideFrom))
585 return EC;
586
587 ScopedFileHandle FromHandle;
588 // Retry this a few times to defeat badly behaved file system scanners.
589 for (unsigned Retry = 0; Retry != 200; ++Retry) {
590 if (Retry != 0)
591 ::Sleep(10);
592 FromHandle =
593 ::CreateFileW(WideFrom.begin(), GENERIC_READ | DELETE,
594 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
595 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
596 if (FromHandle)
597 break;
598
599 // We don't want to loop if the file doesn't exist.
600 auto EC = mapWindowsError(GetLastError());
602 return EC;
603 }
604 if (!FromHandle)
605 return mapWindowsError(GetLastError());
606
607 return rename_handle(FromHandle, To);
608}
609
610std::error_code resize_file(int FD, uint64_t Size) {
611#ifdef HAVE__CHSIZE_S
612 errno_t error = ::_chsize_s(FD, Size);
613#else
614 errno_t error = ::_chsize(FD, Size);
615#endif
616 return std::error_code(error, std::generic_category());
617}
618
619std::error_code access(const Twine &Path, AccessMode Mode) {
621
622 if (std::error_code EC = widenPath(Path, PathUtf16))
623 return EC;
624
625 DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
626
627 if (Attributes == INVALID_FILE_ATTRIBUTES) {
628 // Avoid returning unexpected error codes when querying for existence.
629 if (Mode == AccessMode::Exist)
631
632 // See if the file didn't actually exist.
633 DWORD LastError = ::GetLastError();
634 if (LastError != ERROR_FILE_NOT_FOUND && LastError != ERROR_PATH_NOT_FOUND)
635 return mapWindowsError(LastError);
637 }
638
639 if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
641
642 if (Mode == AccessMode::Execute && (Attributes & FILE_ATTRIBUTE_DIRECTORY))
644
645 return std::error_code();
646}
647
648bool can_execute(const Twine &Path) {
649 return !access(Path, AccessMode::Execute) ||
650 !access(Path + ".exe", AccessMode::Execute);
651}
652
653bool equivalent(file_status A, file_status B) {
655 return A.getUniqueID() == B.getUniqueID();
656}
657
658std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
659 file_status fsA, fsB;
660 if (std::error_code ec = status(A, fsA))
661 return ec;
662 if (std::error_code ec = status(B, fsB))
663 return ec;
664 result = equivalent(fsA, fsB);
665 return std::error_code();
666}
667
668static bool isReservedName(StringRef path) {
669 // This list of reserved names comes from MSDN, at:
670 // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
671 static const char *const sReservedNames[] = {
672 "nul", "con", "prn", "aux", "com1", "com2", "com3", "com4",
673 "com5", "com6", "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
674 "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9"};
675
676 // First, check to see if this is a device namespace, which always
677 // starts with \\.\, since device namespaces are not legal file paths.
678 if (path.starts_with("\\\\.\\"))
679 return true;
680
681 // Then compare against the list of ancient reserved names.
682 for (size_t i = 0; i < std::size(sReservedNames); ++i) {
683 if (path.equals_insensitive(sReservedNames[i]))
684 return true;
685 }
686
687 // The path isn't what we consider reserved.
688 return false;
689}
690
691static file_type file_type_from_attrs(DWORD Attrs) {
692 return (Attrs & FILE_ATTRIBUTE_DIRECTORY) ? file_type::directory_file
694}
695
696static perms perms_from_attrs(DWORD Attrs) {
697 return (Attrs & FILE_ATTRIBUTE_READONLY) ? (all_read | all_exe) : all_all;
698}
699
700static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
702 if (FileHandle == INVALID_HANDLE_VALUE)
703 goto handle_status_error;
704
705 switch (::GetFileType(FileHandle)) {
706 default:
707 llvm_unreachable("Don't know anything about this file type");
708 case FILE_TYPE_UNKNOWN: {
709 DWORD Err = ::GetLastError();
710 if (Err != NO_ERROR)
711 return mapWindowsError(Err);
712 Result = file_status(file_type::type_unknown);
713 return std::error_code();
714 }
715 case FILE_TYPE_DISK:
716 break;
717 case FILE_TYPE_CHAR:
718 Result = file_status(file_type::character_file);
719 return std::error_code();
720 case FILE_TYPE_PIPE:
721 Result = file_status(file_type::fifo_file);
722 return std::error_code();
723 }
724
725 BY_HANDLE_FILE_INFORMATION Info;
726 if (!::GetFileInformationByHandle(FileHandle, &Info))
727 goto handle_status_error;
728
729 // File indices aren't necessarily stable after closing the file handle;
730 // instead hash a canonicalized path.
731 //
732 // For getting a canonical path to the file, call GetFinalPathNameByHandleW
733 // with VOLUME_NAME_NT. We don't really care exactly what the path looks
734 // like here, as long as it is canonical (e.g. doesn't differentiate between
735 // whether a file was referred to with upper/lower case names originally).
736 // The default format with VOLUME_NAME_DOS doesn't work with all file system
737 // drivers, such as ImDisk. (See
738 // https://github.com/rust-lang/rust/pull/86447.)
739 uint64_t PathHash;
740 if (std::error_code EC =
741 realPathFromHandle(FileHandle, ntPath, VOLUME_NAME_NT)) {
742 // If realPathFromHandle failed, fall back on the fields
743 // nFileIndex{High,Low} instead. They're not necessarily stable on all file
744 // systems as they're only documented as being unique/stable as long as the
745 // file handle is open - but they're a decent fallback if we couldn't get
746 // the canonical path.
747 PathHash = (static_cast<uint64_t>(Info.nFileIndexHigh) << 32ULL) |
748 static_cast<uint64_t>(Info.nFileIndexLow);
749 } else {
750 PathHash = hash_combine_range(ntPath.begin(), ntPath.end());
751 }
752
753 Result = file_status(
754 file_type_from_attrs(Info.dwFileAttributes),
755 perms_from_attrs(Info.dwFileAttributes), Info.nNumberOfLinks,
756 Info.ftLastAccessTime.dwHighDateTime, Info.ftLastAccessTime.dwLowDateTime,
757 Info.ftLastWriteTime.dwHighDateTime, Info.ftLastWriteTime.dwLowDateTime,
758 Info.dwVolumeSerialNumber, Info.nFileSizeHigh, Info.nFileSizeLow,
759 PathHash);
760 return std::error_code();
761
762handle_status_error:
763 std::error_code Err = mapLastWindowsError();
764 if (Err == std::errc::no_such_file_or_directory)
765 Result = file_status(file_type::file_not_found);
766 else if (Err == std::errc::permission_denied)
767 Result = file_status(file_type::type_unknown);
768 else
769 Result = file_status(file_type::status_error);
770 return Err;
771}
772
773std::error_code status(const Twine &path, file_status &result, bool Follow) {
774 SmallString<128> path_storage;
775 SmallVector<wchar_t, 128> path_utf16;
776
777 StringRef path8 = path.toStringRef(path_storage);
778 if (isReservedName(path8)) {
779 result = file_status(file_type::character_file);
780 return std::error_code();
781 }
782
783 if (std::error_code ec = widenPath(path8, path_utf16))
784 return ec;
785
786 DWORD Flags = FILE_FLAG_BACKUP_SEMANTICS;
787 if (!Follow) {
788 DWORD attr = ::GetFileAttributesW(path_utf16.begin());
789 if (attr == INVALID_FILE_ATTRIBUTES)
790 return getStatus(INVALID_HANDLE_VALUE, result);
791
792 // Handle reparse points.
793 if (attr & FILE_ATTRIBUTE_REPARSE_POINT)
794 Flags |= FILE_FLAG_OPEN_REPARSE_POINT;
795 }
796
798 ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
799 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
800 NULL, OPEN_EXISTING, Flags, 0));
801 if (!h)
802 return getStatus(INVALID_HANDLE_VALUE, result);
803
804 return getStatus(h, result);
805}
806
807std::error_code status(int FD, file_status &Result) {
808 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
809 return getStatus(FileHandle, Result);
810}
811
812std::error_code status(file_t FileHandle, file_status &Result) {
813 return getStatus(FileHandle, Result);
814}
815
816unsigned getUmask() { return 0; }
817
818std::error_code setPermissions(const Twine &Path, perms Permissions) {
820 if (std::error_code EC = widenPath(Path, PathUTF16))
821 return EC;
822
823 DWORD Attributes = ::GetFileAttributesW(PathUTF16.begin());
824 if (Attributes == INVALID_FILE_ATTRIBUTES)
825 return mapWindowsError(GetLastError());
826
827 // There are many Windows file attributes that are not to do with the file
828 // permissions (e.g. FILE_ATTRIBUTE_HIDDEN). We need to be careful to preserve
829 // them.
830 if (Permissions & all_write) {
831 Attributes &= ~FILE_ATTRIBUTE_READONLY;
832 if (Attributes == 0)
833 // FILE_ATTRIBUTE_NORMAL indicates no other attributes are set.
834 Attributes |= FILE_ATTRIBUTE_NORMAL;
835 } else {
836 Attributes |= FILE_ATTRIBUTE_READONLY;
837 // FILE_ATTRIBUTE_NORMAL is not compatible with any other attributes, so
838 // remove it, if it is present.
839 Attributes &= ~FILE_ATTRIBUTE_NORMAL;
840 }
841
842 if (!::SetFileAttributesW(PathUTF16.begin(), Attributes))
843 return mapWindowsError(GetLastError());
844
845 return std::error_code();
846}
847
848std::error_code setPermissions(int FD, perms Permissions) {
849 // FIXME Not implemented.
850 return std::make_error_code(std::errc::not_supported);
851}
852
853std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
854 TimePoint<> ModificationTime) {
855 FILETIME AccessFT = toFILETIME(AccessTime);
856 FILETIME ModifyFT = toFILETIME(ModificationTime);
857 HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
858 if (!SetFileTime(FileHandle, NULL, &AccessFT, &ModifyFT))
859 return mapWindowsError(::GetLastError());
860 return std::error_code();
861}
862
863std::error_code mapped_file_region::init(sys::fs::file_t OrigFileHandle,
864 uint64_t Offset, mapmode Mode) {
865 this->Mode = Mode;
866 if (OrigFileHandle == INVALID_HANDLE_VALUE)
868
869 DWORD flprotect;
870 switch (Mode) {
871 case readonly:
872 flprotect = PAGE_READONLY;
873 break;
874 case readwrite:
875 flprotect = PAGE_READWRITE;
876 break;
877 case priv:
878 flprotect = PAGE_WRITECOPY;
879 break;
880 }
881
882 HANDLE FileMappingHandle = ::CreateFileMappingW(OrigFileHandle, 0, flprotect,
883 Hi_32(Size), Lo_32(Size), 0);
884 if (FileMappingHandle == NULL) {
885 std::error_code ec = mapWindowsError(GetLastError());
886 return ec;
887 }
888
889 DWORD dwDesiredAccess;
890 switch (Mode) {
891 case readonly:
892 dwDesiredAccess = FILE_MAP_READ;
893 break;
894 case readwrite:
895 dwDesiredAccess = FILE_MAP_WRITE;
896 break;
897 case priv:
898 dwDesiredAccess = FILE_MAP_COPY;
899 break;
900 }
901 Mapping = ::MapViewOfFile(FileMappingHandle, dwDesiredAccess, Offset >> 32,
902 Offset & 0xffffffff, Size);
903 if (Mapping == NULL) {
904 std::error_code ec = mapWindowsError(GetLastError());
905 ::CloseHandle(FileMappingHandle);
906 return ec;
907 }
908
909 if (Size == 0) {
910 MEMORY_BASIC_INFORMATION mbi;
911 SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
912 if (Result == 0) {
913 std::error_code ec = mapWindowsError(GetLastError());
914 ::UnmapViewOfFile(Mapping);
915 ::CloseHandle(FileMappingHandle);
916 return ec;
917 }
918 Size = mbi.RegionSize;
919 }
920
921 // Close the file mapping handle, as it's kept alive by the file mapping. But
922 // neither the file mapping nor the file mapping handle keep the file handle
923 // alive, so we need to keep a reference to the file in case all other handles
924 // are closed and the file is deleted, which may cause invalid data to be read
925 // from the file.
926 ::CloseHandle(FileMappingHandle);
927 if (!::DuplicateHandle(::GetCurrentProcess(), OrigFileHandle,
928 ::GetCurrentProcess(), &FileHandle, 0, 0,
929 DUPLICATE_SAME_ACCESS)) {
930 std::error_code ec = mapWindowsError(GetLastError());
931 ::UnmapViewOfFile(Mapping);
932 return ec;
933 }
934
935 return std::error_code();
936}
937
939 size_t length, uint64_t offset,
940 std::error_code &ec)
941 : Size(length) {
942 ec = init(fd, offset, mode);
943 if (ec)
944 copyFrom(mapped_file_region());
945}
946
947static bool hasFlushBufferKernelBug() {
948 static bool Ret{GetWindowsOSVersion() < llvm::VersionTuple(10, 0, 0, 17763)};
949 return Ret;
950}
951
952static bool isEXE(StringRef Magic) {
953 static const char PEMagic[] = {'P', 'E', '\0', '\0'};
954 if (Magic.starts_with(StringRef("MZ")) && Magic.size() >= 0x3c + 4) {
955 uint32_t off = read32le(Magic.data() + 0x3c);
956 // PE/COFF file, either EXE or DLL.
957 if (Magic.substr(off).starts_with(StringRef(PEMagic, sizeof(PEMagic))))
958 return true;
959 }
960 return false;
961}
962
963void mapped_file_region::unmapImpl() {
964 if (Mapping) {
965
966 bool Exe = isEXE(StringRef((char *)Mapping, Size));
967
968 ::UnmapViewOfFile(Mapping);
969
970 if (Mode == mapmode::readwrite) {
971 bool DoFlush = Exe && hasFlushBufferKernelBug();
972 // There is a Windows kernel bug, the exact trigger conditions of which
973 // are not well understood. When triggered, dirty pages are not properly
974 // flushed and subsequent process's attempts to read a file can return
975 // invalid data. Calling FlushFileBuffers on the write handle is
976 // sufficient to ensure that this bug is not triggered.
977 // The bug only occurs when writing an executable and executing it right
978 // after, under high I/O pressure.
979 if (!DoFlush) {
980 // Separately, on VirtualBox Shared Folder mounts, writes via memory
981 // maps always end up unflushed (regardless of version of Windows),
982 // unless flushed with this explicit call, if they are renamed with
983 // SetFileInformationByHandle(FileRenameInfo) before closing the output
984 // handle.
985 //
986 // As the flushing is quite expensive, use a heuristic to limit the
987 // cases where we do the flushing. Only do the flushing if we aren't
988 // sure we are on a local file system.
989 bool IsLocal = false;
991 if (!realPathFromHandle(FileHandle, FinalPath)) {
992 // Not checking the return value here - if the check fails, assume the
993 // file isn't local.
994 is_local_internal(FinalPath, IsLocal);
995 }
996 DoFlush = !IsLocal;
997 }
998 if (DoFlush)
999 ::FlushFileBuffers(FileHandle);
1000 }
1001
1002 ::CloseHandle(FileHandle);
1003 }
1004}
1005
1006void mapped_file_region::dontNeedImpl() {}
1007
1008int mapped_file_region::alignment() {
1009 SYSTEM_INFO SysInfo;
1010 ::GetSystemInfo(&SysInfo);
1011 return SysInfo.dwAllocationGranularity;
1012}
1013
1014static basic_file_status status_from_find_data(WIN32_FIND_DATAW *FindData) {
1015 return basic_file_status(file_type_from_attrs(FindData->dwFileAttributes),
1016 perms_from_attrs(FindData->dwFileAttributes),
1017 FindData->ftLastAccessTime.dwHighDateTime,
1018 FindData->ftLastAccessTime.dwLowDateTime,
1019 FindData->ftLastWriteTime.dwHighDateTime,
1020 FindData->ftLastWriteTime.dwLowDateTime,
1021 FindData->nFileSizeHigh, FindData->nFileSizeLow);
1022}
1023
1024std::error_code detail::directory_iterator_construct(detail::DirIterState &IT,
1025 StringRef Path,
1026 bool FollowSymlinks) {
1027 SmallVector<wchar_t, 128> PathUTF16;
1028
1029 if (std::error_code EC = widenPath(Path, PathUTF16))
1030 return EC;
1031
1032 // Convert path to the format that Windows is happy with.
1033 size_t PathUTF16Len = PathUTF16.size();
1034 if (PathUTF16Len > 0 && !is_separator(PathUTF16[PathUTF16Len - 1]) &&
1035 PathUTF16[PathUTF16Len - 1] != L':') {
1036 PathUTF16.push_back(L'\\');
1037 PathUTF16.push_back(L'*');
1038 } else {
1039 PathUTF16.push_back(L'*');
1040 }
1041
1042 // Get the first directory entry.
1043 WIN32_FIND_DATAW FirstFind;
1044 ScopedFindHandle FindHandle(::FindFirstFileExW(
1045 c_str(PathUTF16), FindExInfoBasic, &FirstFind, FindExSearchNameMatch,
1046 NULL, FIND_FIRST_EX_LARGE_FETCH));
1047 if (!FindHandle)
1048 return mapWindowsError(::GetLastError());
1049
1050 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
1051 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
1052 (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
1053 FirstFind.cFileName[1] == L'.'))
1054 if (!::FindNextFileW(FindHandle, &FirstFind)) {
1055 DWORD LastError = ::GetLastError();
1056 // Check for end.
1057 if (LastError == ERROR_NO_MORE_FILES)
1058 return detail::directory_iterator_destruct(IT);
1059 return mapWindowsError(LastError);
1060 } else
1061 FilenameLen = ::wcslen(FirstFind.cFileName);
1062
1063 // Construct the current directory entry.
1064 SmallString<128> DirectoryEntryNameUTF8;
1065 if (std::error_code EC =
1066 UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
1067 DirectoryEntryNameUTF8))
1068 return EC;
1069
1070 IT.IterationHandle = intptr_t(FindHandle.take());
1071 SmallString<128> DirectoryEntryPath(Path);
1072 path::append(DirectoryEntryPath, DirectoryEntryNameUTF8);
1073 IT.CurrentEntry =
1074 directory_entry(DirectoryEntryPath, FollowSymlinks,
1075 file_type_from_attrs(FirstFind.dwFileAttributes),
1076 status_from_find_data(&FirstFind));
1077
1078 return std::error_code();
1079}
1080
1081std::error_code detail::directory_iterator_destruct(detail::DirIterState &IT) {
1082 if (IT.IterationHandle != 0)
1083 // Closes the handle if it's valid.
1084 ScopedFindHandle close(HANDLE(IT.IterationHandle));
1085 IT.IterationHandle = 0;
1086 IT.CurrentEntry = directory_entry();
1087 return std::error_code();
1088}
1089
1090std::error_code detail::directory_iterator_increment(detail::DirIterState &IT) {
1091 WIN32_FIND_DATAW FindData;
1092 if (!::FindNextFileW(HANDLE(IT.IterationHandle), &FindData)) {
1093 DWORD LastError = ::GetLastError();
1094 // Check for end.
1095 if (LastError == ERROR_NO_MORE_FILES)
1096 return detail::directory_iterator_destruct(IT);
1097 return mapWindowsError(LastError);
1098 }
1099
1100 size_t FilenameLen = ::wcslen(FindData.cFileName);
1101 if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
1102 (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
1103 FindData.cFileName[1] == L'.'))
1105
1106 SmallString<128> DirectoryEntryPathUTF8;
1107 if (std::error_code EC =
1108 UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
1109 DirectoryEntryPathUTF8))
1110 return EC;
1111
1112 IT.CurrentEntry.replace_filename(
1113 Twine(DirectoryEntryPathUTF8),
1114 file_type_from_attrs(FindData.dwFileAttributes),
1115 status_from_find_data(&FindData));
1116 return std::error_code();
1117}
1118
1119ErrorOr<basic_file_status> directory_entry::status() const { return Status; }
1120
1121static std::error_code nativeFileToFd(Expected<HANDLE> H, int &ResultFD,
1122 OpenFlags Flags) {
1123 int CrtOpenFlags = 0;
1124 if (Flags & OF_Append)
1125 CrtOpenFlags |= _O_APPEND;
1126
1127 if (Flags & OF_CRLF) {
1128 assert(Flags & OF_Text && "Flags set OF_CRLF without OF_Text");
1129 CrtOpenFlags |= _O_TEXT;
1130 }
1131
1132 ResultFD = -1;
1133 if (!H)
1134 return errorToErrorCode(H.takeError());
1135
1136 ResultFD = ::_open_osfhandle(intptr_t(*H), CrtOpenFlags);
1137 if (ResultFD == -1) {
1138 ::CloseHandle(*H);
1139 return mapWindowsError(ERROR_INVALID_HANDLE);
1140 }
1141 return std::error_code();
1142}
1143
1144static DWORD nativeDisposition(CreationDisposition Disp, OpenFlags Flags) {
1145 // This is a compatibility hack. Really we should respect the creation
1146 // disposition, but a lot of old code relied on the implicit assumption that
1147 // OF_Append implied it would open an existing file. Since the disposition is
1148 // now explicit and defaults to CD_CreateAlways, this assumption would cause
1149 // any usage of OF_Append to append to a new file, even if the file already
1150 // existed. A better solution might have two new creation dispositions:
1151 // CD_AppendAlways and CD_AppendNew. This would also address the problem of
1152 // OF_Append being used on a read-only descriptor, which doesn't make sense.
1153 if (Flags & OF_Append)
1154 return OPEN_ALWAYS;
1155
1156 switch (Disp) {
1157 case CD_CreateAlways:
1158 return CREATE_ALWAYS;
1159 case CD_CreateNew:
1160 return CREATE_NEW;
1161 case CD_OpenAlways:
1162 return OPEN_ALWAYS;
1163 case CD_OpenExisting:
1164 return OPEN_EXISTING;
1165 }
1166 llvm_unreachable("unreachable!");
1167}
1168
1169static DWORD nativeAccess(FileAccess Access, OpenFlags Flags) {
1170 DWORD Result = 0;
1171 if (Access & FA_Read)
1172 Result |= GENERIC_READ;
1173 if (Access & FA_Write)
1174 Result |= GENERIC_WRITE;
1175 if (Flags & OF_Delete)
1176 Result |= DELETE;
1177 if (Flags & OF_UpdateAtime)
1178 Result |= FILE_WRITE_ATTRIBUTES;
1179 return Result;
1180}
1181
1182static std::error_code openNativeFileInternal(const Twine &Name,
1183 file_t &ResultFile, DWORD Disp,
1184 DWORD Access, DWORD Flags,
1185 bool Inherit = false) {
1186 SmallVector<wchar_t, 128> PathUTF16;
1187 if (std::error_code EC = widenPath(Name, PathUTF16))
1188 return EC;
1189
1190 SECURITY_ATTRIBUTES SA;
1191 SA.nLength = sizeof(SA);
1192 SA.lpSecurityDescriptor = nullptr;
1193 SA.bInheritHandle = Inherit;
1194
1195 HANDLE H =
1196 ::CreateFileW(PathUTF16.begin(), Access,
1197 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &SA,
1198 Disp, Flags, NULL);
1199 if (H == INVALID_HANDLE_VALUE) {
1200 DWORD LastError = ::GetLastError();
1201 std::error_code EC = mapWindowsError(LastError);
1202 // Provide a better error message when trying to open directories.
1203 // This only runs if we failed to open the file, so there is probably
1204 // no performances issues.
1205 if (LastError != ERROR_ACCESS_DENIED)
1206 return EC;
1207 if (is_directory(Name))
1208 return make_error_code(errc::is_a_directory);
1209 return EC;
1210 }
1211 ResultFile = H;
1212 return std::error_code();
1213}
1214
1215Expected<file_t> openNativeFile(const Twine &Name, CreationDisposition Disp,
1216 FileAccess Access, OpenFlags Flags,
1217 unsigned Mode) {
1218 // Verify that we don't have both "append" and "excl".
1219 assert((!(Disp == CD_CreateNew) || !(Flags & OF_Append)) &&
1220 "Cannot specify both 'CreateNew' and 'Append' file creation flags!");
1221
1222 DWORD NativeDisp = nativeDisposition(Disp, Flags);
1223 DWORD NativeAccess = nativeAccess(Access, Flags);
1224
1225 bool Inherit = false;
1226 if (Flags & OF_ChildInherit)
1227 Inherit = true;
1228
1229 file_t Result;
1230 std::error_code EC = openNativeFileInternal(
1231 Name, Result, NativeDisp, NativeAccess, FILE_ATTRIBUTE_NORMAL, Inherit);
1232 if (EC)
1233 return errorCodeToError(EC);
1234
1235 if (Flags & OF_UpdateAtime) {
1236 FILETIME FileTime;
1237 SYSTEMTIME SystemTime;
1238 GetSystemTime(&SystemTime);
1239 if (SystemTimeToFileTime(&SystemTime, &FileTime) == 0 ||
1240 SetFileTime(Result, NULL, &FileTime, NULL) == 0) {
1241 DWORD LastError = ::GetLastError();
1242 ::CloseHandle(Result);
1243 return errorCodeToError(mapWindowsError(LastError));
1244 }
1245 }
1246
1247 return Result;
1248}
1249
1250std::error_code openFile(const Twine &Name, int &ResultFD,
1251 CreationDisposition Disp, FileAccess Access,
1252 OpenFlags Flags, unsigned int Mode) {
1254 if (!Result)
1255 return errorToErrorCode(Result.takeError());
1256
1257 return nativeFileToFd(*Result, ResultFD, Flags);
1258}
1259
1260static std::error_code directoryRealPath(const Twine &Name,
1261 SmallVectorImpl<char> &RealPath) {
1262 file_t File;
1263 std::error_code EC = openNativeFileInternal(
1264 Name, File, OPEN_EXISTING, GENERIC_READ, FILE_FLAG_BACKUP_SEMANTICS);
1265 if (EC)
1266 return EC;
1267
1268 EC = realPathFromHandle(File, RealPath);
1269 ::CloseHandle(File);
1270 return EC;
1271}
1272
1273std::error_code openFileForRead(const Twine &Name, int &ResultFD,
1274 OpenFlags Flags,
1275 SmallVectorImpl<char> *RealPath) {
1276 Expected<HANDLE> NativeFile = openNativeFileForRead(Name, Flags, RealPath);
1277 return nativeFileToFd(std::move(NativeFile), ResultFD, OF_None);
1278}
1279
1280Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
1281 SmallVectorImpl<char> *RealPath) {
1283 openNativeFile(Name, CD_OpenExisting, FA_Read, Flags);
1284
1285 // Fetch the real name of the file, if the user asked
1286 if (Result && RealPath)
1287 realPathFromHandle(*Result, *RealPath);
1288
1289 return Result;
1290}
1291
1293 return reinterpret_cast<HANDLE>(::_get_osfhandle(FD));
1294}
1295
1296file_t getStdinHandle() { return ::GetStdHandle(STD_INPUT_HANDLE); }
1297file_t getStdoutHandle() { return ::GetStdHandle(STD_OUTPUT_HANDLE); }
1298file_t getStderrHandle() { return ::GetStdHandle(STD_ERROR_HANDLE); }
1299
1300Expected<size_t> readNativeFileImpl(file_t FileHandle,
1302 OVERLAPPED *Overlap) {
1303 // ReadFile can only read 2GB at a time. The caller should check the number of
1304 // bytes and read in a loop until termination.
1305 DWORD BytesToRead =
1306 std::min(size_t(std::numeric_limits<DWORD>::max()), Buf.size());
1307 DWORD BytesRead = 0;
1308 if (::ReadFile(FileHandle, Buf.data(), BytesToRead, &BytesRead, Overlap))
1309 return BytesRead;
1310 DWORD Err = ::GetLastError();
1311 // EOF is not an error.
1312 if (Err == ERROR_BROKEN_PIPE || Err == ERROR_HANDLE_EOF)
1313 return BytesRead;
1314 return errorCodeToError(mapWindowsError(Err));
1315}
1316
1318 return readNativeFileImpl(FileHandle, Buf, /*Overlap=*/nullptr);
1319}
1320
1321Expected<size_t> readNativeFileSlice(file_t FileHandle,
1323 uint64_t Offset) {
1324 OVERLAPPED Overlapped = {};
1325 Overlapped.Offset = uint32_t(Offset);
1326 Overlapped.OffsetHigh = uint32_t(Offset >> 32);
1327 return readNativeFileImpl(FileHandle, Buf, &Overlapped);
1328}
1329
1330std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout) {
1331 DWORD Flags = LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY;
1332 OVERLAPPED OV = {};
1334 auto Start = std::chrono::steady_clock::now();
1335 auto End = Start + Timeout;
1336 do {
1337 if (::LockFileEx(File, Flags, 0, MAXDWORD, MAXDWORD, &OV))
1338 return std::error_code();
1339 DWORD Error = ::GetLastError();
1340 if (Error == ERROR_LOCK_VIOLATION) {
1341 ::Sleep(1);
1342 continue;
1343 }
1344 return mapWindowsError(Error);
1345 } while (std::chrono::steady_clock::now() < End);
1346 return mapWindowsError(ERROR_LOCK_VIOLATION);
1347}
1348
1349std::error_code lockFile(int FD) {
1350 DWORD Flags = LOCKFILE_EXCLUSIVE_LOCK;
1351 OVERLAPPED OV = {};
1353 if (::LockFileEx(File, Flags, 0, MAXDWORD, MAXDWORD, &OV))
1354 return std::error_code();
1355 DWORD Error = ::GetLastError();
1356 return mapWindowsError(Error);
1357}
1358
1359std::error_code unlockFile(int FD) {
1360 OVERLAPPED OV = {};
1362 if (::UnlockFileEx(File, 0, MAXDWORD, MAXDWORD, &OV))
1363 return std::error_code();
1364 return mapWindowsError(::GetLastError());
1365}
1366
1367std::error_code closeFile(file_t &F) {
1368 file_t TmpF = F;
1369 F = kInvalidFile;
1370 if (!::CloseHandle(TmpF))
1371 return mapWindowsError(::GetLastError());
1372 return std::error_code();
1373}
1374
1375std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1376 // Convert to utf-16.
1378 std::error_code EC = widenPath(path, Path16);
1379 if (EC && !IgnoreErrors)
1380 return EC;
1381
1382 // SHFileOperation() accepts a list of paths, and so must be double null-
1383 // terminated to indicate the end of the list. The buffer is already null
1384 // terminated, but since that null character is not considered part of the
1385 // vector's size, pushing another one will just consume that byte. So we
1386 // need to push 2 null terminators.
1387 Path16.push_back(0);
1388 Path16.push_back(0);
1389
1390 HRESULT HR;
1391 do {
1392 HR =
1393 CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
1394 if (FAILED(HR))
1395 break;
1396 auto Uninitialize = make_scope_exit([] { CoUninitialize(); });
1397 IFileOperation *FileOp = NULL;
1398 HR = CoCreateInstance(CLSID_FileOperation, NULL, CLSCTX_ALL,
1399 IID_PPV_ARGS(&FileOp));
1400 if (FAILED(HR))
1401 break;
1402 auto FileOpRelease = make_scope_exit([&FileOp] { FileOp->Release(); });
1403 HR = FileOp->SetOperationFlags(FOF_NO_UI | FOFX_NOCOPYHOOKS);
1404 if (FAILED(HR))
1405 break;
1406 PIDLIST_ABSOLUTE PIDL = ILCreateFromPathW(Path16.data());
1407 auto FreePIDL = make_scope_exit([&PIDL] { ILFree(PIDL); });
1408 IShellItem *ShItem = NULL;
1409 HR = SHCreateItemFromIDList(PIDL, IID_PPV_ARGS(&ShItem));
1410 if (FAILED(HR))
1411 break;
1412 auto ShItemRelease = make_scope_exit([&ShItem] { ShItem->Release(); });
1413 HR = FileOp->DeleteItem(ShItem, NULL);
1414 if (FAILED(HR))
1415 break;
1416 HR = FileOp->PerformOperations();
1417 } while (false);
1418 if (FAILED(HR) && !IgnoreErrors)
1419 return mapWindowsError(HRESULT_CODE(HR));
1420 return std::error_code();
1421}
1422
1423static void expandTildeExpr(SmallVectorImpl<char> &Path) {
1424 // Path does not begin with a tilde expression.
1425 if (Path.empty() || Path[0] != '~')
1426 return;
1427
1428 StringRef PathStr(Path.begin(), Path.size());
1429 PathStr = PathStr.drop_front();
1430 StringRef Expr =
1431 PathStr.take_until([](char c) { return path::is_separator(c); });
1432
1433 if (!Expr.empty()) {
1434 // This is probably a ~username/ expression. Don't support this on Windows.
1435 return;
1436 }
1437
1438 SmallString<128> HomeDir;
1439 if (!path::home_directory(HomeDir)) {
1440 // For some reason we couldn't get the home directory. Just exit.
1441 return;
1442 }
1443
1444 // Overwrite the first character and insert the rest.
1445 Path[0] = HomeDir[0];
1446 Path.insert(Path.begin() + 1, HomeDir.begin() + 1, HomeDir.end());
1447}
1448
1449void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
1450 dest.clear();
1451 if (path.isTriviallyEmpty())
1452 return;
1453
1454 path.toVector(dest);
1455 expandTildeExpr(dest);
1456
1457 return;
1458}
1459
1460std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1461 bool expand_tilde) {
1462 dest.clear();
1463 if (path.isTriviallyEmpty())
1464 return std::error_code();
1465
1466 if (expand_tilde) {
1467 SmallString<128> Storage;
1468 path.toVector(Storage);
1469 expandTildeExpr(Storage);
1470 return real_path(Storage, dest, false);
1471 }
1472
1473 if (is_directory(path))
1474 return directoryRealPath(path, dest);
1475
1476 int fd;
1477 if (std::error_code EC =
1478 llvm::sys::fs::openFileForRead(path, fd, OF_None, &dest))
1479 return EC;
1480 ::close(fd);
1481 return std::error_code();
1482}
1483
1484} // end namespace fs
1485
1486namespace path {
1487static bool getKnownFolderPath(KNOWNFOLDERID folderId,
1488 SmallVectorImpl<char> &result) {
1489 wchar_t *path = nullptr;
1490 if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK)
1491 return false;
1492
1493 bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
1494 ::CoTaskMemFree(path);
1495 if (ok)
1497 return ok;
1498}
1499
1501 return getKnownFolderPath(FOLDERID_Profile, result);
1502}
1503
1505 // Either local or roaming appdata may be suitable in some cases, depending
1506 // on the data. Local is more conservative, Roaming may not always be correct.
1507 return getKnownFolderPath(FOLDERID_LocalAppData, result);
1508}
1509
1511 return getKnownFolderPath(FOLDERID_LocalAppData, result);
1512}
1513
1514static bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {
1516 size_t Size = 1024;
1517 do {
1519 Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.size());
1520 if (Size == 0)
1521 return false;
1522
1523 // Try again with larger buffer.
1524 } while (Size > Buf.size());
1525 Buf.truncate(Size);
1526
1527 return !windows::UTF16ToUTF8(Buf.data(), Size, Res);
1528}
1529
1530static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
1531 const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};
1532 for (auto *Env : EnvironmentVariables) {
1533 if (getTempDirEnvVar(Env, Res))
1534 return true;
1535 }
1536 return false;
1537}
1538
1539void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1540 (void)ErasedOnReboot;
1541 Result.clear();
1542
1543 // Check whether the temporary directory is specified by an environment var.
1544 // This matches GetTempPath logic to some degree. GetTempPath is not used
1545 // directly as it cannot handle evn var longer than 130 chars on Windows 7
1546 // (fixed on Windows 8).
1547 if (getTempDirEnvVar(Result)) {
1548 assert(!Result.empty() && "Unexpected empty path");
1549 native(Result); // Some Unix-like shells use Unix path separator in $TMP.
1550 fs::make_absolute(Result); // Make it absolute if not already.
1551 return;
1552 }
1553
1554 // Fall back to a system default.
1555 const char *DefaultResult = "C:\\Temp";
1556 Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
1558}
1559} // end namespace path
1560
1561namespace windows {
1562std::error_code CodePageToUTF16(unsigned codepage, llvm::StringRef original,
1564 if (!original.empty()) {
1565 int len =
1566 ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1567 original.size(), utf16.begin(), 0);
1568
1569 if (len == 0) {
1570 return mapWindowsError(::GetLastError());
1571 }
1572
1573 utf16.reserve(len + 1);
1574 utf16.resize_for_overwrite(len);
1575
1576 len =
1577 ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1578 original.size(), utf16.begin(), utf16.size());
1579
1580 if (len == 0) {
1581 return mapWindowsError(::GetLastError());
1582 }
1583 }
1584
1585 // Make utf16 null terminated.
1586 utf16.push_back(0);
1587 utf16.pop_back();
1588
1589 return std::error_code();
1590}
1591
1592std::error_code UTF8ToUTF16(llvm::StringRef utf8,
1594 return CodePageToUTF16(CP_UTF8, utf8, utf16);
1595}
1596
1597std::error_code CurCPToUTF16(llvm::StringRef curcp,
1599 return CodePageToUTF16(CP_ACP, curcp, utf16);
1600}
1601
1602static std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
1603 size_t utf16_len,
1604 llvm::SmallVectorImpl<char> &converted) {
1605 if (utf16_len) {
1606 // Get length.
1607 int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len,
1608 converted.begin(), 0, NULL, NULL);
1609
1610 if (len == 0) {
1611 return mapWindowsError(::GetLastError());
1612 }
1613
1614 converted.reserve(len + 1);
1615 converted.resize_for_overwrite(len);
1616
1617 // Now do the actual conversion.
1618 len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.data(),
1619 converted.size(), NULL, NULL);
1620
1621 if (len == 0) {
1622 return mapWindowsError(::GetLastError());
1623 }
1624 }
1625
1626 // Make the new string null terminated.
1627 converted.push_back(0);
1628 converted.pop_back();
1629
1630 return std::error_code();
1631}
1632
1633std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
1635 return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
1636}
1637
1638std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
1640 return UTF16ToCodePage(CP_ACP, utf16, utf16_len, curcp);
1641}
1642
1643} // end namespace windows
1644} // end namespace sys
1645} // end namespace llvm
#define Success
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")))
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
DXIL Resource Access
Given that RA is a live value
std::string Name
uint64_t Size
bool End
Definition: ELF_riscv.cpp:480
uint64_t Offset
Definition: ELF_riscv.cpp:478
amode Optimize addressing mode
std::unique_ptr< MemoryBuffer > openFile(const Twine &Path)
Definition: LibDriver.cpp:100
#define F(x, y, z)
Definition: MD5.cpp:55
#define H(x, y, z)
Definition: MD5.cpp:57
Merge contiguous icmps into a memcmp
Definition: MergeICmps.cpp:911
#define P(N)
static cl::opt< RegAllocEvictionAdvisorAnalysis::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Development, "development", "for training")))
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
#define error(X)
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:168
Represents either an error or a value T.
Definition: ErrorOr.h:56
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
Tagged union holding either a T or a Error.
Definition: Error.h:481
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:310
T * data() const
Definition: ArrayRef.h:357
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.
Definition: SmallString.h:120
size_t capacity() const
Definition: SmallVector.h:79
size_t size() const
Definition: SmallVector.h:78
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:573
void resize_for_overwrite(size_type N)
Like resize, but T is POD, the new values won't be initialized.
Definition: SmallVector.h:641
void reserve(size_type N)
Definition: SmallVector.h:663
void truncate(size_type N)
Like resize, but requires that N is less than size().
Definition: SmallVector.h:644
void resize(size_type N)
Definition: SmallVector.h:638
void push_back(const T &Elt)
Definition: SmallVector.h:413
pointer data()
Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:286
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:265
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:147
iterator begin() const
Definition: StringRef.h:116
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:150
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:603
bool equals_insensitive(StringRef RHS) const
Check for string equality, ignoring case.
Definition: StringRef.h:176
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
bool isTriviallyEmpty() const
Check if this twine is trivially empty; a false return value does not necessarily mean the twine is e...
Definition: Twine.h:429
StringRef toStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single StringRef if it can be represented as such.
Definition: Twine.h:492
void toVector(SmallVectorImpl< char > &Out) const
Append the concatenated string into the given SmallString or SmallVector.
Definition: Twine.cpp:32
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:29
TimePoint getLastAccessedTime() const
The file access time as reported from the underlying file system.
TimePoint getLastModificationTime() const
The file modification time as reported from the underlying file system.
uint32_t getLinkCount() const
UniqueID getUniqueID() const
@ priv
May modify via data, but changes are lost on destruction.
Definition: FileSystem.h:1271
@ readonly
May only access map via const_data as read only.
Definition: FileSystem.h:1269
@ readwrite
May access map via data and modify it. Written to path.
Definition: FileSystem.h:1270
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const uint64_t Magic
Definition: CodeGenData.h:276
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
uint32_t read32le(const void *P)
Definition: Endian.h:425
std::error_code directory_iterator_increment(DirIterState &)
std::error_code unlockFile(int FD)
Unlock the file.
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...
std::error_code remove_directories(const Twine &path, bool IgnoreErrors=true)
Recursively delete a directory.
std::error_code create_link(const Twine &to, const Twine &from)
Create a link from from to to.
bool equivalent(file_status A, file_status B)
Do file_status's represent the same thing?
void make_absolute(const Twine &current_directory, SmallVectorImpl< char > &path)
Make path an absolute path.
Definition: Path.cpp:906
const file_t kInvalidFile
std::error_code real_path(const Twine &path, SmallVectorImpl< char > &output, bool expand_tilde=false)
Collapse all .
std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout=std::chrono::milliseconds(0))
Try to locks the file during the specified time.
Expected< size_t > readNativeFile(file_t FileHandle, MutableArrayRef< char > Buf)
Reads Buf.size() bytes from FileHandle into Buf.
std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime, TimePoint<> ModificationTime)
Set the file modification and access time.
std::error_code closeFile(file_t &F)
Close the file object.
file_t getStdoutHandle()
Return an open handle to standard out.
std::error_code rename(const Twine &from, const Twine &to)
Rename from to to.
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.
void expand_tilde(const Twine &path, SmallVectorImpl< char > &output)
Expands ~ expressions to the user's home directory.
Expected< size_t > readNativeFileSlice(file_t FileHandle, MutableArrayRef< char > Buf, uint64_t Offset)
Reads Buf.size() bytes from FileHandle at offset Offset into Buf.
std::error_code access(const Twine &Path, AccessMode Mode)
Can the file be accessed?
std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
bool exists(const basic_file_status &status)
Does file exist?
Definition: Path.cpp:1077
file_type
An enumeration for the file system's view of the type.
Definition: FileSystem.h:65
std::error_code create_hard_link(const Twine &to, const Twine &from)
Create a hard link from from to to, or return an error.
std::error_code resize_file(int FD, uint64_t Size)
Resize path to size.
std::error_code create_directory(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create the directory in path.
std::error_code lockFile(int FD)
Lock the file.
@ CD_OpenExisting
CD_OpenExisting - When opening a file:
Definition: FileSystem.h:740
@ CD_OpenAlways
CD_OpenAlways - When opening a file:
Definition: FileSystem.h:745
@ CD_CreateAlways
CD_CreateAlways - When opening a file:
Definition: FileSystem.h:730
@ CD_CreateNew
CD_CreateNew - When opening a file:
Definition: FileSystem.h:735
std::error_code set_current_path(const Twine &path)
Set the current path.
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...
ErrorOr< space_info > disk_space(const Twine &Path)
Get disk space usage information.
file_t getStderrHandle()
Return an open handle to standard error.
bool status_known(const basic_file_status &s)
Is status available?
Definition: Path.cpp:1081
std::error_code is_local(const Twine &path, bool &result)
Is the file mounted on a local filesystem?
file_t convertFDToNativeFile(int FD)
Converts from a Posix file descriptor number to a native file handle.
Definition: FileSystem.h:990
bool can_execute(const Twine &Path)
Can we execute this file?
unsigned getUmask()
Get file creation mode mask of the process.
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.
std::error_code current_path(SmallVectorImpl< char > &result)
Get the current path.
std::error_code setPermissions(const Twine &Path, perms Permissions)
Set file permissions.
bool is_directory(const basic_file_status &status)
Does status represent a directory?
Definition: Path.cpp:1092
file_t getStdinHandle()
Return an open handle to standard in.
bool user_config_directory(SmallVectorImpl< char > &result)
Get the directory where packages should read user-specific configurations.
bool home_directory(SmallVectorImpl< char > &result)
Get the user's home directory.
bool remove_dots(SmallVectorImpl< char > &path, bool remove_dot_dot=false, Style style=Style::native)
In-place remove any '.
Definition: Path.cpp:715
bool has_root_path(const Twine &path, Style style=Style::native)
Has root path?
Definition: Path.cpp:629
StringRef root_name(StringRef path, Style style=Style::native)
Get root name.
Definition: Path.cpp:373
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:269
bool cache_directory(SmallVectorImpl< char > &result)
Get the directory where installed packages should put their machine-local cache, e....
void system_temp_directory(bool erasedOnReboot, SmallVectorImpl< char > &result)
Get the typical temporary directory for the system, e.g., "/var/tmp" or "C:/TEMP".
void native(const Twine &path, SmallVectorImpl< char > &result, Style style=Style::native)
Convert path to the native form.
Definition: Path.cpp:540
bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
Definition: Path.cpp:671
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:601
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.
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: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:480
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
Definition: ScopeExit.h:59
std::error_code make_error_code(BitcodeError E)
std::error_code mapLastWindowsError()
llvm::VersionTuple GetWindowsOSVersion()
Returns the Windows version as Major.Minor.0.BuildNumber.
SmallVectorImpl< T >::const_pointer c_str(SmallVectorImpl< T > &str)
@ no_such_file_or_directory
@ bad_file_descriptor
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition: MathExtras.h:154
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition: MathExtras.h:159
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:111
std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
Definition: Error.cpp:117
std::error_code mapWindowsError(unsigned EV)
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition: Hashing.h:468