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