34#ifndef _ERRNO_T_DEFINED
35#define _ERRNO_T_DEFINED
40#pragma comment(lib, "advapi32.lib")
41#pragma comment(lib, "ole32.lib")
46using llvm::sys::windows::CurCPToUTF16;
47using llvm::sys::windows::UTF16ToUTF8;
48using llvm::sys::windows::UTF8ToUTF16;
70 assert(MaxPathLen <= MAX_PATH);
82 if (std::error_code EC = UTF8ToUTF16(Path8Str, Path16))
90 CurPathLen = ::GetCurrentDirectoryW(
96 const char *
const LongPathPrefix =
"\\\\?\\";
98 if ((Path16.
size() + CurPathLen) < MaxPathLen ||
100 return std::error_code();
115 "Root name cannot be empty for an absolute path!");
118 if (RootName[1] !=
':') {
119 FullPath.append(
"UNC\\");
120 FullPath.append(Path8Str.
begin() + 2, Path8Str.
end());
122 FullPath.append(Path8Str);
124 return UTF8ToUTF16(FullPath, Path16);
153 if (UTF16ToUTF8(PathName.
data(), PathName.
size(), PathNameUTF8))
161 return std::string(RealPath);
162 return std::string(PathNameUTF8.
data());
166 return UniqueID(VolumeSerialNumber, PathHash);
171 if (!::GetDiskFreeSpaceExA(
Path.str().c_str(), &Avail, &
Total, &
Free))
173 space_info SpaceInfo;
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;
184 Time.dwLowDateTime = LastAccessedTimeLow;
185 Time.dwHighDateTime = LastAccessedTimeHigh;
191 Time.dwLowDateTime = LastWriteTimeLow;
192 Time.dwHighDateTime = LastWriteTimeHigh;
200 DWORD len = MAX_PATH;
204 len = ::GetCurrentDirectoryW(cur_path.
size(), cur_path.
data());
212 }
while (len > cur_path.
size());
218 if (std::error_code EC =
219 UTF16ToUTF8(cur_path.
begin(), cur_path.
size(), result))
223 return std::error_code();
229 if (std::error_code ec =
widenPath(path, wide_path))
232 if (!::SetCurrentDirectoryW(wide_path.
begin()))
235 return std::error_code();
244 if (std::error_code ec =
widenPath(path, path_utf16, MAX_PATH - 12))
247 if (!::CreateDirectoryW(path_utf16.
begin(), NULL)) {
248 DWORD LastError = ::GetLastError();
249 if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
253 return std::error_code();
261 if (std::error_code ec =
widenPath(from, wide_from))
263 if (std::error_code ec =
widenPath(to, wide_to))
266 if (!::CreateHardLinkW(wide_from.
begin(), wide_to.
begin(), NULL))
269 return std::error_code();
276std::error_code
remove(
const Twine &path,
bool IgnoreNonExisting) {
279 if (std::error_code ec =
widenPath(path, path_utf16))
293 c_str(path_utf16), DELETE,
294 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
296 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS |
297 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_DELETE_ON_CLOSE,
305 return std::error_code();
315 ::GetVolumePathNameW(
Path.data(), VolumePath.
data(), VolumePath.
size());
320 DWORD Err = ::GetLastError();
321 if (Err != ERROR_INSUFFICIENT_BUFFER)
331 const wchar_t *
P = VolumePath.
data();
333 UINT
Type = ::GetDriveTypeW(
P);
337 return std::error_code();
341 case DRIVE_REMOVABLE:
343 return std::error_code();
359 if (std::error_code ec =
widenPath(
P, WidePath))
361 return is_local_internal(WidePath, result);
364static std::error_code realPathFromHandle(HANDLE
H,
366 DWORD flags = VOLUME_NAME_DOS) {
368 DWORD CountChars = ::GetFinalPathNameByHandleW(
369 H, Buffer.
begin(), Buffer.
capacity(), FILE_NAME_NORMALIZED | flags);
370 if (CountChars && CountChars >= Buffer.
capacity()) {
374 CountChars = ::GetFinalPathNameByHandleW(
H, Buffer.
begin(), Buffer.
size(),
375 FILE_NAME_NORMALIZED | flags);
380 return std::error_code();
383static std::error_code realPathFromHandle(HANDLE
H,
387 if (std::error_code EC = realPathFromHandle(
H, Buffer))
394 if (CountChars >= 8 &&
::memcmp(
Data, L
"\\\\?\\UNC\\", 16) == 0) {
399 }
else if (CountChars >= 4 &&
::memcmp(
Data, L
"\\\\?\\", 8) == 0) {
406 if (std::error_code EC = UTF16ToUTF8(
Data, CountChars, RealPath))
410 return std::error_code();
413std::error_code
is_local(
int FD,
bool &Result) {
415 HANDLE Handle =
reinterpret_cast<HANDLE
>(_get_osfhandle(FD));
417 if (std::error_code EC = realPathFromHandle(Handle, FinalPath))
420 return is_local_internal(FinalPath, Result);
423static std::error_code setDeleteDisposition(HANDLE Handle,
bool Delete) {
428 FILE_DISPOSITION_INFO Disposition;
429 Disposition.DeleteFile =
false;
430 if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
431 sizeof(Disposition)))
434 return std::error_code();
440 if (std::error_code EC = realPathFromHandle(Handle, FinalPath))
444 if (std::error_code EC = is_local_internal(FinalPath, IsLocal))
452 Disposition.DeleteFile =
true;
453 if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
454 sizeof(Disposition)))
456 return std::error_code();
459static std::error_code rename_internal(HANDLE FromHandle,
const Twine &To,
460 bool ReplaceIfExists) {
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]);
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;
483 return std::error_code();
486static std::error_code rename_handle(HANDLE FromHandle,
const Twine &To) {
488 if (std::error_code EC =
widenPath(To, WideTo))
494 for (
unsigned Retry = 0; Retry != 200; ++Retry) {
495 auto EC = rename_internal(FromHandle, To,
true);
498 std::error_code(ERROR_CALL_NOT_IMPLEMENTED, std::system_category())) {
502 if (std::error_code EC2 = realPathFromHandle(FromHandle, WideFrom))
504 if (::MoveFileExW(WideFrom.
begin(), WideTo.
begin(),
505 MOVEFILE_REPLACE_EXISTING))
506 return std::error_code();
520 ::CreateFileW(WideTo.
begin(), GENERIC_READ | DELETE,
521 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
523 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL));
534 BY_HANDLE_FILE_INFORMATION FI;
535 if (!GetFileInformationByHandle(ToHandle, &FI))
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)) {
549 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
550 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
557 BY_HANDLE_FILE_INFORMATION FI2;
558 if (!GetFileInformationByHandle(ToHandle2, &FI2))
560 if (FI.nFileIndexHigh != FI2.nFileIndexHigh ||
561 FI.nFileIndexLow != FI2.nFileIndexLow ||
562 FI.dwVolumeSerialNumber != FI2.dwVolumeSerialNumber)
589 for (
unsigned Retry = 0; Retry != 200; ++Retry) {
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);
607 return rename_handle(FromHandle, To);
616 return std::error_code(
error, std::generic_category());
622 if (std::error_code EC =
widenPath(Path, PathUtf16))
627 if (Attributes == INVALID_FILE_ATTRIBUTES) {
633 DWORD LastError = ::GetLastError();
634 if (LastError != ERROR_FILE_NOT_FOUND && LastError != ERROR_PATH_NOT_FOUND)
645 return std::error_code();
655 return A.getUniqueID() ==
B.getUniqueID();
659 file_status fsA, fsB;
660 if (std::error_code ec =
status(
A, fsA))
662 if (std::error_code ec =
status(
B, fsB))
665 return std::error_code();
668static bool isReservedName(
StringRef path) {
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"};
682 for (
size_t i = 0; i < std::size(sReservedNames); ++i) {
691static file_type file_type_from_attrs(DWORD Attrs) {
696static perms perms_from_attrs(DWORD Attrs) {
700static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
702 if (FileHandle == INVALID_HANDLE_VALUE)
703 goto handle_status_error;
705 switch (::GetFileType(FileHandle)) {
708 case FILE_TYPE_UNKNOWN: {
709 DWORD Err = ::GetLastError();
713 return std::error_code();
719 return std::error_code();
722 return std::error_code();
725 BY_HANDLE_FILE_INFORMATION
Info;
726 if (!::GetFileInformationByHandle(FileHandle, &
Info))
727 goto handle_status_error;
740 if (std::error_code EC =
741 realPathFromHandle(FileHandle, ntPath, VOLUME_NAME_NT)) {
747 PathHash = (
static_cast<uint64_t>(
Info.nFileIndexHigh) << 32ULL) |
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,
760 return std::error_code();
764 if (Err == std::errc::no_such_file_or_directory)
766 else if (Err == std::errc::permission_denied)
773std::error_code
status(
const Twine &path, file_status &result,
bool Follow) {
778 if (isReservedName(path8)) {
780 return std::error_code();
783 if (std::error_code ec =
widenPath(path8, path_utf16))
788 DWORD attr = ::GetFileAttributesW(path_utf16.
begin());
789 if (attr == INVALID_FILE_ATTRIBUTES)
790 return getStatus(INVALID_HANDLE_VALUE, result);
793 if (attr & FILE_ATTRIBUTE_REPARSE_POINT)
794 Flags |= FILE_FLAG_OPEN_REPARSE_POINT;
798 ::CreateFileW(path_utf16.
begin(), 0,
799 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
800 NULL, OPEN_EXISTING, Flags, 0));
802 return getStatus(INVALID_HANDLE_VALUE, result);
804 return getStatus(h, result);
807std::error_code
status(
int FD, file_status &Result) {
808 HANDLE FileHandle =
reinterpret_cast<HANDLE
>(_get_osfhandle(FD));
809 return getStatus(FileHandle, Result);
812std::error_code
status(
file_t FileHandle, file_status &Result) {
813 return getStatus(FileHandle, Result);
820 if (std::error_code EC =
widenPath(Path, PathUTF16))
824 if (Attributes == INVALID_FILE_ATTRIBUTES)
842 if (!::SetFileAttributesW(PathUTF16.
begin(), Attributes))
845 return std::error_code();
850 return std::make_error_code(std::errc::not_supported);
856 FILETIME ModifyFT =
toFILETIME(ModificationTime);
857 HANDLE FileHandle =
reinterpret_cast<HANDLE
>(_get_osfhandle(FD));
858 if (!SetFileTime(FileHandle, NULL, &AccessFT, &ModifyFT))
860 return std::error_code();
863std::error_code mapped_file_region::init(
sys::fs::file_t OrigFileHandle,
866 if (OrigFileHandle == INVALID_HANDLE_VALUE)
872 flprotect = PAGE_READONLY;
875 flprotect = PAGE_READWRITE;
878 flprotect = PAGE_WRITECOPY;
882 HANDLE FileMappingHandle = ::CreateFileMappingW(OrigFileHandle, 0, flprotect,
884 if (FileMappingHandle == NULL) {
889 DWORD dwDesiredAccess;
892 dwDesiredAccess = FILE_MAP_READ;
895 dwDesiredAccess = FILE_MAP_WRITE;
898 dwDesiredAccess = FILE_MAP_COPY;
901 Mapping = ::MapViewOfFile(FileMappingHandle, dwDesiredAccess,
Offset >> 32,
902 Offset & 0xffffffff, Size);
903 if (Mapping == NULL) {
905 ::CloseHandle(FileMappingHandle);
910 MEMORY_BASIC_INFORMATION mbi;
911 SIZE_T
Result = VirtualQuery(Mapping, &mbi,
sizeof(mbi));
914 ::UnmapViewOfFile(Mapping);
915 ::CloseHandle(FileMappingHandle);
918 Size = mbi.RegionSize;
926 ::CloseHandle(FileMappingHandle);
927 if (!::DuplicateHandle(::GetCurrentProcess(), OrigFileHandle,
928 ::GetCurrentProcess(), &FileHandle, 0, 0,
929 DUPLICATE_SAME_ACCESS)) {
931 ::UnmapViewOfFile(Mapping);
935 return std::error_code();
944 copyFrom(mapped_file_region());
947static bool hasFlushBufferKernelBug() {
953 static const char PEMagic[] = {
'P',
'E',
'\0',
'\0'};
957 if (
Magic.substr(off).starts_with(
StringRef(PEMagic,
sizeof(PEMagic))))
963void mapped_file_region::unmapImpl() {
968 ::UnmapViewOfFile(Mapping);
970 if (
Mode == mapmode::readwrite) {
971 bool DoFlush =
Exe && hasFlushBufferKernelBug();
989 bool IsLocal =
false;
991 if (!realPathFromHandle(FileHandle, FinalPath)) {
994 is_local_internal(FinalPath, IsLocal);
999 ::FlushFileBuffers(FileHandle);
1002 ::CloseHandle(FileHandle);
1006void mapped_file_region::dontNeedImpl() {}
1008int mapped_file_region::alignment() {
1009 SYSTEM_INFO SysInfo;
1010 ::GetSystemInfo(&SysInfo);
1011 return SysInfo.dwAllocationGranularity;
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);
1024std::error_code detail::directory_iterator_construct(detail::DirIterState &
IT,
1026 bool FollowSymlinks) {
1029 if (std::error_code EC =
widenPath(Path, PathUTF16))
1033 size_t PathUTF16Len = PathUTF16.
size();
1034 if (PathUTF16Len > 0 && !
is_separator(PathUTF16[PathUTF16Len - 1]) &&
1035 PathUTF16[PathUTF16Len - 1] != L
':') {
1043 WIN32_FIND_DATAW FirstFind;
1045 c_str(PathUTF16), FindExInfoBasic, &FirstFind, FindExSearchNameMatch,
1046 NULL, FIND_FIRST_EX_LARGE_FETCH));
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();
1057 if (LastError == ERROR_NO_MORE_FILES)
1058 return detail::directory_iterator_destruct(
IT);
1061 FilenameLen = ::wcslen(FirstFind.cFileName);
1065 if (std::error_code EC =
1066 UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
1067 DirectoryEntryNameUTF8))
1070 IT.IterationHandle = intptr_t(FindHandle.take());
1072 path::append(DirectoryEntryPath, DirectoryEntryNameUTF8);
1074 directory_entry(DirectoryEntryPath, FollowSymlinks,
1075 file_type_from_attrs(FirstFind.dwFileAttributes),
1076 status_from_find_data(&FirstFind));
1078 return std::error_code();
1081std::error_code detail::directory_iterator_destruct(detail::DirIterState &
IT) {
1082 if (
IT.IterationHandle != 0)
1085 IT.IterationHandle = 0;
1086 IT.CurrentEntry = directory_entry();
1087 return std::error_code();
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();
1095 if (LastError == ERROR_NO_MORE_FILES)
1096 return detail::directory_iterator_destruct(
IT);
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
'.'))
1107 if (std::error_code EC =
1108 UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
1109 DirectoryEntryPathUTF8))
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();
1123 int CrtOpenFlags = 0;
1124 if (Flags & OF_Append)
1125 CrtOpenFlags |= _O_APPEND;
1127 if (Flags & OF_CRLF) {
1128 assert(Flags & OF_Text &&
"Flags set OF_CRLF without OF_Text");
1129 CrtOpenFlags |= _O_TEXT;
1136 ResultFD = ::_open_osfhandle(intptr_t(*
H), CrtOpenFlags);
1137 if (ResultFD == -1) {
1141 return std::error_code();
1144static DWORD nativeDisposition(CreationDisposition Disp, OpenFlags Flags) {
1153 if (Flags & OF_Append)
1158 return CREATE_ALWAYS;
1164 return OPEN_EXISTING;
1169static DWORD nativeAccess(FileAccess Access, OpenFlags Flags) {
1171 if (Access & FA_Read)
1173 if (Access & FA_Write)
1175 if (Flags & OF_Delete)
1177 if (Flags & OF_UpdateAtime)
1178 Result |= FILE_WRITE_ATTRIBUTES;
1182static std::error_code openNativeFileInternal(
const Twine &
Name,
1183 file_t &ResultFile, DWORD Disp,
1184 DWORD Access, DWORD Flags,
1185 bool Inherit =
false) {
1190 SECURITY_ATTRIBUTES SA;
1191 SA.nLength =
sizeof(SA);
1192 SA.lpSecurityDescriptor =
nullptr;
1193 SA.bInheritHandle = Inherit;
1196 ::CreateFileW(PathUTF16.
begin(), Access,
1197 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &SA,
1199 if (
H == INVALID_HANDLE_VALUE) {
1200 DWORD LastError = ::GetLastError();
1205 if (LastError != ERROR_ACCESS_DENIED)
1212 return std::error_code();
1216 FileAccess Access, OpenFlags Flags,
1219 assert((!(Disp == CD_CreateNew) || !(Flags & OF_Append)) &&
1220 "Cannot specify both 'CreateNew' and 'Append' file creation flags!");
1222 DWORD NativeDisp = nativeDisposition(Disp, Flags);
1223 DWORD NativeAccess = nativeAccess(Access, Flags);
1225 bool Inherit =
false;
1226 if (Flags & OF_ChildInherit)
1230 std::error_code
EC = openNativeFileInternal(
1231 Name, Result, NativeDisp, NativeAccess, FILE_ATTRIBUTE_NORMAL, Inherit);
1235 if (Flags & OF_UpdateAtime) {
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);
1251 CreationDisposition Disp, FileAccess Access,
1252 OpenFlags Flags,
unsigned int Mode) {
1257 return nativeFileToFd(*Result, ResultFD, Flags);
1260static std::error_code directoryRealPath(
const Twine &
Name,
1263 std::error_code
EC = openNativeFileInternal(
1264 Name, File, OPEN_EXISTING, GENERIC_READ, FILE_FLAG_BACKUP_SEMANTICS);
1268 EC = realPathFromHandle(File, RealPath);
1269 ::CloseHandle(File);
1277 return nativeFileToFd(std::move(NativeFile), ResultFD, OF_None);
1286 if (Result && RealPath)
1287 realPathFromHandle(*Result, *RealPath);
1293 return reinterpret_cast<HANDLE
>(::_get_osfhandle(FD));
1302 OVERLAPPED *Overlap) {
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))
1310 DWORD Err = ::GetLastError();
1312 if (Err == ERROR_BROKEN_PIPE || Err == ERROR_HANDLE_EOF)
1318 return readNativeFileImpl(FileHandle, Buf,
nullptr);
1324 OVERLAPPED Overlapped = {};
1327 return readNativeFileImpl(FileHandle, Buf, &Overlapped);
1330std::error_code
tryLockFile(
int FD, std::chrono::milliseconds Timeout) {
1331 DWORD Flags = LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY;
1334 auto Start = std::chrono::steady_clock::now();
1335 auto End = Start + Timeout;
1337 if (::LockFileEx(File, Flags, 0, MAXDWORD, MAXDWORD, &OV))
1338 return std::error_code();
1340 if (
Error == ERROR_LOCK_VIOLATION) {
1345 }
while (std::chrono::steady_clock::now() <
End);
1353 if (::LockFileEx(File, Flags, 0, MAXDWORD, MAXDWORD, &OV))
1354 return std::error_code();
1362 if (::UnlockFileEx(File, 0, MAXDWORD, MAXDWORD, &OV))
1363 return std::error_code();
1370 if (!::CloseHandle(TmpF))
1372 return std::error_code();
1379 if (EC && !IgnoreErrors)
1390 SHFILEOPSTRUCTW shfos = {};
1391 shfos.wFunc = FO_DELETE;
1392 shfos.pFrom = Path16.
data();
1393 shfos.fFlags = FOF_NO_UI;
1395 int result = ::SHFileOperationW(&shfos);
1396 if (result != 0 && !IgnoreErrors)
1398 return std::error_code();
1403 if (
Path.empty() || Path[0] !=
'~')
1407 PathStr = PathStr.drop_front();
1409 PathStr.
take_until([](
char c) {
return path::is_separator(c); });
1411 if (!Expr.
empty()) {
1417 if (!path::home_directory(HomeDir)) {
1423 Path[0] = HomeDir[0];
1433 expandTildeExpr(dest);
1439 bool expand_tilde) {
1442 return std::error_code();
1447 expandTildeExpr(Storage);
1452 return directoryRealPath(path, dest);
1455 if (std::error_code EC =
1459 return std::error_code();
1465static bool getKnownFolderPath(KNOWNFOLDERID folderId,
1467 wchar_t *path =
nullptr;
1468 if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE,
nullptr, &path) != S_OK)
1471 bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
1472 ::CoTaskMemFree(path);
1479 return getKnownFolderPath(FOLDERID_Profile, result);
1485 return getKnownFolderPath(FOLDERID_LocalAppData, result);
1489 return getKnownFolderPath(FOLDERID_LocalAppData, result);
1497 Size = GetEnvironmentVariableW(Var, Buf.
data(), Buf.
size());
1505 return !windows::UTF16ToUTF8(Buf.
data(),
Size, Res);
1509 const wchar_t *EnvironmentVariables[] = {
L"TMP",
L"TEMP",
L"USERPROFILE"};
1510 for (
auto *Env : EnvironmentVariables) {
1511 if (getTempDirEnvVar(Env, Res))
1518 (void)ErasedOnReboot;
1525 if (getTempDirEnvVar(Result)) {
1528 fs::make_absolute(Result);
1533 const char *DefaultResult =
"C:\\Temp";
1534 Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
1540std::error_code CodePageToUTF16(
unsigned codepage,
llvm::StringRef original,
1542 if (!original.
empty()) {
1544 ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.
begin(),
1555 ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.
begin(),
1567 return std::error_code();
1572 return CodePageToUTF16(CP_UTF8, utf8, utf16);
1577 return CodePageToUTF16(CP_ACP, curcp, utf16);
1580static std::error_code UTF16ToCodePage(
unsigned codepage,
const wchar_t *utf16,
1585 int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len,
1586 converted.
begin(), 0, NULL, NULL);
1596 len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.
data(),
1597 converted.
size(), NULL, NULL);
1608 return std::error_code();
1611std::error_code UTF16ToUTF8(
const wchar_t *utf16,
size_t utf16_len,
1613 return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
1616std::error_code UTF16ToCurCP(
const wchar_t *utf16,
size_t utf16_len,
1618 return UTF16ToCodePage(CP_ACP, utf16, utf16_len, curcp);
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
Given that RA is a live value
amode Optimize addressing mode
std::unique_ptr< MemoryBuffer > openFile(const Twine &Path)
Merge contiguous icmps into a memcmp
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())
size_t size() const
size - Get the array size.
Represents either an error or a value T.
Lightweight error class with error context and mandatory checking.
Tagged union holding either a T or a Error.
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
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 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.
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr bool empty() const
empty - Check if the string is empty.
constexpr size_t size() const
size - Get the string size.
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...
bool equals_insensitive(StringRef RHS) const
Check for string equality, ignoring case.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
bool isTriviallyEmpty() const
Check if this twine is trivially empty; a false return value does not necessarily mean the twine is e...
StringRef toStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single StringRef if it can be represented as such.
void toVector(SmallVectorImpl< char > &Out) const
Append the concatenated string into the given SmallString or SmallVector.
The instances of the Type class are immutable: once they are created, they are never changed.
Represents a version number in the form major[.minor[.subminor[.build]]].
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
mapped_file_region()=default
@ 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)
uint32_t read32le(const void *P)
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 ¤t_directory, SmallVectorImpl< char > &path)
Make path an absolute path.
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?
file_type
An enumeration for the file system's view of the type.
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:
@ CD_OpenAlways
CD_OpenAlways - When opening a file:
@ CD_CreateAlways
CD_CreateAlways - When opening a file:
@ CD_CreateNew
CD_CreateNew - When opening a file:
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?
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.
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?
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 '.
bool has_root_path(const Twine &path, Style style=Style::native)
Has root path?
StringRef root_name(StringRef path, Style style=Style::native)
Get root name.
void make_preferred(SmallVectorImpl< char > &path, Style style=Style::native)
For Windows path styles, convert path to use the preferred path separators.
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.
bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
bool is_separator(char value, Style style=Style::native)
Check whether the given char is a path separator on the host OS.
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.
TimePoint< std::chrono::seconds > toTimePoint(std::time_t T)
Convert a std::time_t to a TimePoint.
This is an optimization pass for GlobalISel generic memory operations.
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
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
std::error_code mapWindowsError(unsigned EV)
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.