35#ifndef _ERRNO_T_DEFINED
36#define _ERRNO_T_DEFINED
41#pragma comment(lib, "advapi32.lib")
42#pragma comment(lib, "ole32.lib")
47using llvm::sys::windows::CurCPToUTF16;
48using llvm::sys::windows::UTF16ToUTF8;
49using llvm::sys::windows::UTF8ToUTF16;
69std::error_code
widenPath(
const Twine &Path8, SmallVectorImpl<wchar_t> &Path16,
71 assert(MaxPathLen <= MAX_PATH);
75 SmallString<MAX_PATH> Path8Str;
83 if (std::error_code EC = UTF8ToUTF16(Path8Str, Path16))
91 CurPathLen = ::GetCurrentDirectoryW(
97 const char *
const LongPathPrefix =
"\\\\?\\";
99 if ((Path16.
size() + CurPathLen) < MaxPathLen ||
101 return std::error_code();
116 "Root name cannot be empty for an absolute path!");
118 SmallString<2 * MAX_PATH> FullPath(LongPathPrefix);
119 if (RootName[1] !=
':') {
120 FullPath.append(
"UNC\\");
121 FullPath.append(Path8Str.
begin() + 2, Path8Str.
end());
123 FullPath.append(Path8Str);
126 return UTF8ToUTF16(FullPath, Path16);
155 if (UTF16ToUTF8(PathName.
data(), PathName.
size(), PathNameUTF8))
160 SmallString<256> RealPath;
163 return std::string(RealPath);
164 return std::string(PathNameUTF8.
data());
168 return UniqueID(VolumeSerialNumber, PathHash);
171ErrorOr<space_info>
disk_space(
const Twine &Path) {
173 if (!::GetDiskFreeSpaceExA(
Path.str().c_str(), &Avail, &
Total, &
Free))
177 (
static_cast<uint64_t
>(
Total.HighPart) << 32) +
Total.LowPart;
178 SpaceInfo.free = (
static_cast<uint64_t
>(
Free.HighPart) << 32) +
Free.LowPart;
179 SpaceInfo.available =
180 (
static_cast<uint64_t
>(Avail.HighPart) << 32) + Avail.LowPart;
186 Time.dwLowDateTime = LastAccessedTimeLow;
187 Time.dwHighDateTime = LastAccessedTimeHigh;
193 Time.dwLowDateTime = LastWriteTimeLow;
194 Time.dwHighDateTime = LastWriteTimeHigh;
200std::error_code
current_path(SmallVectorImpl<char> &result) {
202 DWORD len = MAX_PATH;
206 len = ::GetCurrentDirectoryW(cur_path.
size(), cur_path.
data());
214 }
while (len > cur_path.
size());
220 if (std::error_code EC =
221 UTF16ToUTF8(cur_path.
begin(), cur_path.
size(), result))
225 return std::error_code();
231 if (std::error_code ec =
widenPath(path, wide_path))
234 if (!::SetCurrentDirectoryW(wide_path.
begin()))
237 return std::error_code();
246 if (std::error_code ec =
widenPath(path, path_utf16, MAX_PATH - 12))
249 if (!::CreateDirectoryW(path_utf16.
begin(), NULL)) {
250 DWORD LastError = ::GetLastError();
251 if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
255 return std::error_code();
259std::error_code
create_link(
const Twine &to,
const Twine &from) {
263 if (std::error_code ec =
widenPath(from, wide_from))
265 if (std::error_code ec =
widenPath(to, wide_to))
268 if (!::CreateHardLinkW(wide_from.
begin(), wide_to.
begin(), NULL))
271 return std::error_code();
278std::error_code
remove(
const Twine &path,
bool IgnoreNonExisting) {
281 if (std::error_code ec =
widenPath(path, path_utf16))
295 c_str(path_utf16), DELETE,
296 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
298 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS |
299 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_DELETE_ON_CLOSE,
307 return std::error_code();
310static std::error_code is_local_internal(SmallVectorImpl<wchar_t> &Path,
317 ::GetVolumePathNameW(
Path.data(), VolumePath.
data(), VolumePath.
size());
322 DWORD Err = ::GetLastError();
323 if (Err != ERROR_INSUFFICIENT_BUFFER)
333 const wchar_t *
P = VolumePath.
data();
335 UINT
Type = ::GetDriveTypeW(
P);
339 return std::error_code();
343 case DRIVE_REMOVABLE:
345 return std::error_code();
352std::error_code
is_local(
const Twine &path,
bool &result) {
356 SmallString<128> Storage;
361 if (std::error_code ec =
widenPath(
P, WidePath))
363 return is_local_internal(WidePath, result);
366static std::error_code realPathFromHandle(HANDLE
H,
367 SmallVectorImpl<wchar_t> &Buffer,
368 DWORD flags = VOLUME_NAME_DOS) {
370 DWORD CountChars = ::GetFinalPathNameByHandleW(
371 H, Buffer.
begin(), Buffer.
capacity(), FILE_NAME_NORMALIZED | flags);
372 if (CountChars && CountChars >= Buffer.
capacity()) {
376 CountChars = ::GetFinalPathNameByHandleW(
H, Buffer.
begin(), Buffer.
size(),
377 FILE_NAME_NORMALIZED | flags);
382 return std::error_code();
385static std::error_code realPathFromHandle(HANDLE
H,
386 SmallVectorImpl<char> &RealPath) {
389 if (std::error_code EC = realPathFromHandle(
H, Buffer))
396 if (CountChars >= 8 &&
::memcmp(
Data, L
"\\\\?\\UNC\\", 16) == 0) {
401 }
else if (CountChars >= 4 &&
::memcmp(
Data, L
"\\\\?\\", 8) == 0) {
408 if (std::error_code EC = UTF16ToUTF8(
Data, CountChars, RealPath))
412 return std::error_code();
415std::error_code
is_local(
int FD,
bool &Result) {
417 HANDLE Handle =
reinterpret_cast<HANDLE
>(_get_osfhandle(FD));
419 if (std::error_code EC = realPathFromHandle(Handle, FinalPath))
422 return is_local_internal(FinalPath, Result);
425static std::error_code setDeleteDisposition(HANDLE Handle,
bool Delete) {
430 FILE_DISPOSITION_INFO Disposition;
431 Disposition.DeleteFile =
false;
432 if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
433 sizeof(Disposition)))
436 return std::error_code();
442 if (std::error_code EC = realPathFromHandle(Handle, FinalPath))
446 if (std::error_code EC = is_local_internal(FinalPath, IsLocal))
454 Disposition.DeleteFile =
true;
455 if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
456 sizeof(Disposition)))
458 return std::error_code();
461static std::error_code rename_internal(HANDLE FromHandle,
const Twine &To,
462 bool ReplaceIfExists) {
467 std::vector<char> RenameInfoBuf(
sizeof(FILE_RENAME_INFO) -
sizeof(
wchar_t) +
468 (ToWide.
size() *
sizeof(
wchar_t)));
469 FILE_RENAME_INFO &RenameInfo =
470 *
reinterpret_cast<FILE_RENAME_INFO *
>(RenameInfoBuf.data());
471 RenameInfo.ReplaceIfExists = ReplaceIfExists;
472 RenameInfo.RootDirectory = 0;
473 RenameInfo.FileNameLength = ToWide.
size() *
sizeof(wchar_t);
474 std::copy(ToWide.
begin(), ToWide.
end(), &RenameInfo.FileName[0]);
476 SetLastError(ERROR_SUCCESS);
477 if (!SetFileInformationByHandle(FromHandle, FileRenameInfo, &RenameInfo,
478 RenameInfoBuf.size())) {
479 unsigned Error = GetLastError();
480 if (
Error == ERROR_SUCCESS)
481 Error = ERROR_CALL_NOT_IMPLEMENTED;
485 return std::error_code();
488static std::error_code rename_handle(HANDLE FromHandle,
const Twine &To) {
490 if (std::error_code EC =
widenPath(To, WideTo))
496 for (
unsigned Retry = 0; Retry != 200; ++Retry) {
497 auto EC = rename_internal(FromHandle, To,
true);
500 std::error_code(ERROR_CALL_NOT_IMPLEMENTED, std::system_category())) {
504 if (std::error_code EC2 = realPathFromHandle(FromHandle, WideFrom))
506 if (::MoveFileExW(WideFrom.
begin(), WideTo.
begin(),
507 MOVEFILE_REPLACE_EXISTING))
508 return std::error_code();
522 ::CreateFileW(WideTo.
begin(), GENERIC_READ | DELETE,
523 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
525 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL));
536 BY_HANDLE_FILE_INFORMATION FI;
537 if (!GetFileInformationByHandle(ToHandle, &FI))
541 for (
unsigned UniqueId = 0; UniqueId != 200; ++UniqueId) {
542 std::string TmpFilename = (To +
".tmp" +
utostr(UniqueId)).str();
543 if (
auto EC = rename_internal(ToHandle, TmpFilename,
false)) {
551 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
552 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
559 BY_HANDLE_FILE_INFORMATION FI2;
560 if (!GetFileInformationByHandle(ToHandle2, &FI2))
562 if (FI.nFileIndexHigh != FI2.nFileIndexHigh ||
563 FI.nFileIndexLow != FI2.nFileIndexLow ||
564 FI.dwVolumeSerialNumber != FI2.dwVolumeSerialNumber)
583std::error_code
rename(
const Twine &From,
const Twine &To) {
586 if (std::error_code EC =
widenPath(From, WideFrom))
591 for (
unsigned Retry = 0; Retry != 200; ++Retry) {
595 ::CreateFileW(WideFrom.
begin(), GENERIC_READ | DELETE,
596 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
597 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
609 return rename_handle(FromHandle, To);
618 return std::error_code(
error, std::generic_category());
622 HANDLE hFile =
reinterpret_cast<HANDLE
>(::_get_osfhandle(FD));
624 if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, &temp,
628 LARGE_INTEGER liSize;
629 liSize.QuadPart =
Size;
630 if (!SetFilePointerEx(hFile, liSize, NULL, FILE_BEGIN) ||
631 !SetEndOfFile(hFile)) {
634 return std::error_code();
640 if (std::error_code EC =
widenPath(Path, PathUtf16))
651 DWORD LastError = ::GetLastError();
652 if (LastError != ERROR_FILE_NOT_FOUND && LastError != ERROR_PATH_NOT_FOUND)
663 return std::error_code();
673 return A.getUniqueID() ==
B.getUniqueID();
676std::error_code
equivalent(
const Twine &
A,
const Twine &
B,
bool &result) {
678 if (std::error_code ec =
status(
A, fsA))
680 if (std::error_code ec =
status(
B, fsB))
683 return std::error_code();
686static bool isReservedName(StringRef path) {
689 static const char *
const sReservedNames[] = {
690 "nul",
"con",
"prn",
"aux",
"com1",
"com2",
"com3",
"com4",
691 "com5",
"com6",
"com7",
"com8",
"com9",
"lpt1",
"lpt2",
"lpt3",
692 "lpt4",
"lpt5",
"lpt6",
"lpt7",
"lpt8",
"lpt9"};
700 for (
size_t i = 0; i < std::size(sReservedNames); ++i) {
709static file_type file_type_from_attrs(DWORD Attrs) {
714static perms perms_from_attrs(DWORD Attrs) {
718static std::error_code getStatus(HANDLE FileHandle,
file_status &Result) {
720 if (FileHandle == INVALID_HANDLE_VALUE)
721 goto handle_status_error;
723 switch (::GetFileType(FileHandle)) {
726 case FILE_TYPE_UNKNOWN: {
727 DWORD Err = ::GetLastError();
731 return std::error_code();
737 return std::error_code();
740 return std::error_code();
743 BY_HANDLE_FILE_INFORMATION
Info;
744 if (!::GetFileInformationByHandle(FileHandle, &
Info))
745 goto handle_status_error;
758 if (std::error_code EC =
759 realPathFromHandle(FileHandle, ntPath, VOLUME_NAME_NT)) {
765 PathHash = (
static_cast<uint64_t
>(
Info.nFileIndexHigh) << 32ULL) |
766 static_cast<uint64_t
>(
Info.nFileIndexLow);
772 file_type_from_attrs(
Info.dwFileAttributes),
773 perms_from_attrs(
Info.dwFileAttributes),
Info.nNumberOfLinks,
774 Info.ftLastAccessTime.dwHighDateTime,
Info.ftLastAccessTime.dwLowDateTime,
775 Info.ftLastWriteTime.dwHighDateTime,
Info.ftLastWriteTime.dwLowDateTime,
776 Info.dwVolumeSerialNumber,
Info.nFileSizeHigh,
Info.nFileSizeLow,
778 return std::error_code();
782 if (Err == std::errc::no_such_file_or_directory)
784 else if (Err == std::errc::permission_denied)
792 SmallString<128> path_storage;
796 if (isReservedName(path8)) {
798 return std::error_code();
801 if (std::error_code ec =
widenPath(path8, path_utf16))
806 DWORD attr = ::GetFileAttributesW(path_utf16.
begin());
807 if (attr == INVALID_FILE_ATTRIBUTES)
808 return getStatus(INVALID_HANDLE_VALUE, result);
811 if (attr & FILE_ATTRIBUTE_REPARSE_POINT)
812 Flags |= FILE_FLAG_OPEN_REPARSE_POINT;
816 ::CreateFileW(path_utf16.
begin(), 0,
817 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
818 NULL, OPEN_EXISTING, Flags, 0));
820 return getStatus(INVALID_HANDLE_VALUE, result);
822 return getStatus(h, result);
826 HANDLE FileHandle =
reinterpret_cast<HANDLE
>(_get_osfhandle(FD));
827 return getStatus(FileHandle, Result);
831 return getStatus(FileHandle, Result);
838 if (std::error_code EC =
widenPath(Path, PathUTF16))
863 return std::error_code();
868 return std::make_error_code(std::errc::not_supported);
874 FILETIME ModifyFT =
toFILETIME(ModificationTime);
875 HANDLE FileHandle =
reinterpret_cast<HANDLE
>(_get_osfhandle(FD));
876 if (!SetFileTime(FileHandle, NULL, &AccessFT, &ModifyFT))
878 return std::error_code();
881std::error_code mapped_file_region::init(
sys::fs::file_t OrigFileHandle,
884 if (OrigFileHandle == INVALID_HANDLE_VALUE)
890 flprotect = PAGE_READONLY;
893 flprotect = PAGE_READWRITE;
896 flprotect = PAGE_WRITECOPY;
900 HANDLE FileMappingHandle = ::CreateFileMappingW(OrigFileHandle, 0, flprotect,
902 if (FileMappingHandle == NULL) {
907 DWORD dwDesiredAccess;
910 dwDesiredAccess = FILE_MAP_READ;
913 dwDesiredAccess = FILE_MAP_WRITE;
916 dwDesiredAccess = FILE_MAP_COPY;
919 Mapping = ::MapViewOfFile(FileMappingHandle, dwDesiredAccess,
Offset >> 32,
920 Offset & 0xffffffff, Size);
921 if (Mapping == NULL) {
923 ::CloseHandle(FileMappingHandle);
928 MEMORY_BASIC_INFORMATION mbi;
929 SIZE_T
Result = VirtualQuery(Mapping, &mbi,
sizeof(mbi));
932 ::UnmapViewOfFile(Mapping);
933 ::CloseHandle(FileMappingHandle);
936 Size = mbi.RegionSize;
944 ::CloseHandle(FileMappingHandle);
945 if (!::DuplicateHandle(::GetCurrentProcess(), OrigFileHandle,
946 ::GetCurrentProcess(), &FileHandle, 0, 0,
947 DUPLICATE_SAME_ACCESS)) {
949 ::UnmapViewOfFile(Mapping);
953 return std::error_code();
957 size_t length, uint64_t offset,
962 copyFrom(mapped_file_region());
965static bool hasFlushBufferKernelBug() {
971 static const char PEMagic[] = {
'P',
'E',
'\0',
'\0'};
975 if (
Magic.substr(off).starts_with(
StringRef(PEMagic,
sizeof(PEMagic))))
981void mapped_file_region::unmapImpl() {
986 ::UnmapViewOfFile(Mapping);
988 if (
Mode == mapmode::readwrite) {
989 bool DoFlush =
Exe && hasFlushBufferKernelBug();
1007 bool IsLocal =
false;
1009 if (!realPathFromHandle(FileHandle, FinalPath)) {
1012 is_local_internal(FinalPath, IsLocal);
1017 ::FlushFileBuffers(FileHandle);
1020 ::CloseHandle(FileHandle);
1024void mapped_file_region::dontNeedImpl() {}
1026std::error_code mapped_file_region::sync()
const {
1027 if (!::FlushViewOfFile(Mapping,
Size))
1029 if (!::FlushFileBuffers(FileHandle))
1031 return std::error_code();
1034int mapped_file_region::alignment() {
1035 SYSTEM_INFO SysInfo;
1036 ::GetSystemInfo(&SysInfo);
1037 return SysInfo.dwAllocationGranularity;
1040static basic_file_status status_from_find_data(WIN32_FIND_DATAW *FindData) {
1041 return basic_file_status(file_type_from_attrs(FindData->dwFileAttributes),
1042 perms_from_attrs(FindData->dwFileAttributes),
1043 FindData->ftLastAccessTime.dwHighDateTime,
1044 FindData->ftLastAccessTime.dwLowDateTime,
1045 FindData->ftLastWriteTime.dwHighDateTime,
1046 FindData->ftLastWriteTime.dwLowDateTime,
1047 FindData->nFileSizeHigh, FindData->nFileSizeLow);
1050std::error_code detail::directory_iterator_construct(detail::DirIterState &
IT,
1052 bool FollowSymlinks) {
1055 if (std::error_code EC =
widenPath(Path, PathUTF16))
1059 size_t PathUTF16Len = PathUTF16.
size();
1060 if (PathUTF16Len > 0 && !
is_separator(PathUTF16[PathUTF16Len - 1]) &&
1061 PathUTF16[PathUTF16Len - 1] != L
':') {
1069 WIN32_FIND_DATAW FirstFind;
1071 c_str(PathUTF16), FindExInfoBasic, &FirstFind, FindExSearchNameMatch,
1072 NULL, FIND_FIRST_EX_LARGE_FETCH));
1076 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
1077 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L
'.') ||
1078 (FilenameLen == 2 && FirstFind.cFileName[0] == L
'.' &&
1079 FirstFind.cFileName[1] == L
'.'))
1080 if (!::FindNextFileW(FindHandle, &FirstFind)) {
1081 DWORD LastError = ::GetLastError();
1083 if (LastError == ERROR_NO_MORE_FILES)
1084 return detail::directory_iterator_destruct(
IT);
1087 FilenameLen = ::wcslen(FirstFind.cFileName);
1092 if (std::error_code EC =
1093 UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
1094 DirectoryEntryNameUTF8))
1097 IT.IterationHandle = intptr_t(FindHandle.take());
1099 path::append(DirectoryEntryPath, DirectoryEntryNameUTF8);
1101 directory_entry(DirectoryEntryPath, FollowSymlinks,
1102 file_type_from_attrs(FirstFind.dwFileAttributes),
1103 status_from_find_data(&FirstFind));
1105 return std::error_code();
1108std::error_code detail::directory_iterator_destruct(detail::DirIterState &
IT) {
1109 if (
IT.IterationHandle != 0)
1112 IT.IterationHandle = 0;
1113 IT.CurrentEntry = directory_entry();
1114 return std::error_code();
1117std::error_code detail::directory_iterator_increment(detail::DirIterState &
IT) {
1118 WIN32_FIND_DATAW FindData;
1119 if (!::FindNextFileW(HANDLE(
IT.IterationHandle), &FindData)) {
1120 DWORD LastError = ::GetLastError();
1122 if (LastError == ERROR_NO_MORE_FILES)
1123 return detail::directory_iterator_destruct(
IT);
1127 size_t FilenameLen = ::wcslen(FindData.cFileName);
1128 if ((FilenameLen == 1 && FindData.cFileName[0] == L
'.') ||
1129 (FilenameLen == 2 && FindData.cFileName[0] == L
'.' &&
1130 FindData.cFileName[1] == L
'.'))
1134 if (std::error_code EC =
1135 UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
1136 DirectoryEntryPathUTF8))
1139 IT.CurrentEntry.replace_filename(
1140 Twine(DirectoryEntryPathUTF8),
1141 file_type_from_attrs(FindData.dwFileAttributes),
1142 status_from_find_data(&FindData));
1143 return std::error_code();
1148static std::error_code nativeFileToFd(Expected<HANDLE>
H,
int &ResultFD,
1150 int CrtOpenFlags = 0;
1151 if (Flags & OF_Append)
1152 CrtOpenFlags |= _O_APPEND;
1154 if (Flags & OF_CRLF) {
1155 assert(Flags & OF_Text &&
"Flags set OF_CRLF without OF_Text");
1156 CrtOpenFlags |= _O_TEXT;
1163 ResultFD = ::_open_osfhandle(intptr_t(*
H), CrtOpenFlags);
1164 if (ResultFD == -1) {
1168 return std::error_code();
1171static DWORD nativeDisposition(CreationDisposition Disp, OpenFlags Flags) {
1180 if (Flags & OF_Append)
1185 return CREATE_ALWAYS;
1191 return OPEN_EXISTING;
1196static DWORD nativeAccess(FileAccess
Access, OpenFlags Flags) {
1202 if (Flags & OF_Delete)
1204 if (Flags & OF_UpdateAtime)
1205 Result |= FILE_WRITE_ATTRIBUTES;
1209static std::error_code openNativeFileInternal(
const Twine &Name,
1210 file_t &ResultFile, DWORD Disp,
1211 DWORD
Access, DWORD Flags,
1212 bool Inherit =
false) {
1214 if (std::error_code EC =
widenPath(Name, PathUTF16))
1217 SECURITY_ATTRIBUTES SA;
1218 SA.nLength =
sizeof(SA);
1219 SA.lpSecurityDescriptor =
nullptr;
1220 SA.bInheritHandle = Inherit;
1224 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &SA,
1226 if (
H == INVALID_HANDLE_VALUE) {
1227 DWORD LastError = ::GetLastError();
1232 if (LastError != ERROR_ACCESS_DENIED)
1239 return std::error_code();
1243 FileAccess
Access, OpenFlags Flags,
1246 assert((!(Disp == CD_CreateNew) || !(Flags & OF_Append)) &&
1247 "Cannot specify both 'CreateNew' and 'Append' file creation flags!");
1249 DWORD NativeDisp = nativeDisposition(Disp, Flags);
1250 DWORD NativeAccess = nativeAccess(
Access, Flags);
1252 bool Inherit =
false;
1253 if (Flags & OF_ChildInherit)
1257 std::error_code
EC = openNativeFileInternal(
1258 Name, Result, NativeDisp, NativeAccess, FILE_ATTRIBUTE_NORMAL, Inherit);
1262 if (Flags & OF_UpdateAtime) {
1264 SYSTEMTIME SystemTime;
1265 GetSystemTime(&SystemTime);
1266 if (SystemTimeToFileTime(&SystemTime, &FileTime) == 0 ||
1267 SetFileTime(Result, NULL, &FileTime, NULL) == 0) {
1268 DWORD LastError = ::GetLastError();
1269 ::CloseHandle(Result);
1278 CreationDisposition Disp, FileAccess
Access,
1279 OpenFlags Flags,
unsigned int Mode) {
1284 return nativeFileToFd(*Result, ResultFD, Flags);
1287static std::error_code directoryRealPath(
const Twine &Name,
1290 std::error_code
EC = openNativeFileInternal(
1291 Name, File, OPEN_EXISTING, GENERIC_READ, FILE_FLAG_BACKUP_SEMANTICS);
1295 EC = realPathFromHandle(File, RealPath);
1296 ::CloseHandle(File);
1304 return nativeFileToFd(std::move(NativeFile), ResultFD, OF_None);
1309 Expected<file_t>
Result =
1313 if (Result && RealPath)
1314 realPathFromHandle(*Result, *RealPath);
1320 return reinterpret_cast<HANDLE
>(::_get_osfhandle(FD));
1327Expected<size_t> readNativeFileImpl(
file_t FileHandle,
1329 OVERLAPPED *Overlap) {
1333 std::min(
size_t(std::numeric_limits<DWORD>::max()), Buf.
size());
1334 DWORD BytesRead = 0;
1335 if (::ReadFile(FileHandle, Buf.
data(), BytesToRead, &BytesRead, Overlap))
1337 DWORD Err = ::GetLastError();
1339 if (Err == ERROR_BROKEN_PIPE || Err == ERROR_HANDLE_EOF)
1345 return readNativeFileImpl(FileHandle, Buf,
nullptr);
1351 OVERLAPPED Overlapped = {};
1354 return readNativeFileImpl(FileHandle, Buf, &Overlapped);
1359 DWORD Flags = Kind == LockKind::Exclusive ? LOCKFILE_EXCLUSIVE_LOCK : 0;
1360 Flags |= LOCKFILE_FAIL_IMMEDIATELY;
1363 auto Start = std::chrono::steady_clock::now();
1366 if (::LockFileEx(File, Flags, 0, MAXDWORD, MAXDWORD, &OV))
1367 return std::error_code();
1368 DWORD Error = ::GetLastError();
1369 if (Error == ERROR_LOCK_VIOLATION) {
1376 }
while (std::chrono::steady_clock::now() < End);
1380std::error_code
lockFile(
int FD, LockKind Kind) {
1381 DWORD Flags = Kind == LockKind::Exclusive ? LOCKFILE_EXCLUSIVE_LOCK : 0;
1384 if (::LockFileEx(File, Flags, 0, MAXDWORD, MAXDWORD, &OV))
1385 return std::error_code();
1386 DWORD Error = ::GetLastError();
1393 if (::UnlockFileEx(File, 0, MAXDWORD, MAXDWORD, &OV))
1394 return std::error_code();
1401 if (!::CloseHandle(TmpF))
1403 return std::error_code();
1411 std::error_code
EC =
widenPath(NativePath, Path16);
1412 if (EC && !IgnoreErrors)
1426 CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
1430 IFileOperation *FileOp = NULL;
1431 HR = CoCreateInstance(CLSID_FileOperation, NULL, CLSCTX_ALL,
1432 IID_PPV_ARGS(&FileOp));
1435 auto FileOpRelease =
make_scope_exit([&FileOp] { FileOp->Release(); });
1436 HR = FileOp->SetOperationFlags(FOF_NO_UI | FOFX_NOCOPYHOOKS);
1439 PIDLIST_ABSOLUTE PIDL = ILCreateFromPathW(Path16.
data());
1441 IShellItem *ShItem = NULL;
1442 HR = SHCreateItemFromIDList(PIDL, IID_PPV_ARGS(&ShItem));
1445 auto ShItemRelease =
make_scope_exit([&ShItem] { ShItem->Release(); });
1446 HR = FileOp->DeleteItem(ShItem, NULL);
1449 HR = FileOp->PerformOperations();
1451 if (FAILED(HR) && !IgnoreErrors)
1453 return std::error_code();
1458 if (
Path.empty() || Path[0] !=
'~')
1462 PathStr = PathStr.drop_front();
1466 if (!Expr.
empty()) {
1478 Path[0] = HomeDir[0];
1484 if (
path.isTriviallyEmpty())
1487 path.toVector(dest);
1488 expandTildeExpr(dest);
1494 bool expand_tilde) {
1496 if (
path.isTriviallyEmpty())
1497 return std::error_code();
1501 path.toVector(Storage);
1502 expandTildeExpr(Storage);
1507 return directoryRealPath(
path, dest);
1510 if (std::error_code EC =
1514 return std::error_code();
1520static bool getKnownFolderPath(KNOWNFOLDERID folderId,
1521 SmallVectorImpl<char> &result) {
1522 wchar_t *path =
nullptr;
1523 if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE,
nullptr, &path) != S_OK)
1526 bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
1527 ::CoTaskMemFree(path);
1534 return getKnownFolderPath(FOLDERID_Profile, result);
1540 return getKnownFolderPath(FOLDERID_LocalAppData, result);
1544 return getKnownFolderPath(FOLDERID_LocalAppData, result);
1547static bool getTempDirEnvVar(
const wchar_t *Var, SmallVectorImpl<char> &Res) {
1548 SmallVector<wchar_t, 1024> Buf;
1552 Size = GetEnvironmentVariableW(Var, Buf.
data(), Buf.
size());
1560 return !windows::UTF16ToUTF8(Buf.
data(),
Size, Res);
1563static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
1564 const wchar_t *EnvironmentVariables[] = {
L"TMP",
L"TEMP",
L"USERPROFILE"};
1565 for (
auto *Env : EnvironmentVariables) {
1566 if (getTempDirEnvVar(Env, Res))
1573 (void)ErasedOnReboot;
1580 if (getTempDirEnvVar(Result)) {
1583 fs::make_absolute(Result);
1588 const char *DefaultResult =
"C:\\Temp";
1589 Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
1595std::error_code CodePageToUTF16(
unsigned codepage, llvm::StringRef original,
1596 llvm::SmallVectorImpl<wchar_t> &utf16) {
1597 if (!original.
empty()) {
1599 ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.
begin(),
1610 ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.
begin(),
1622 return std::error_code();
1625std::error_code UTF8ToUTF16(llvm::StringRef utf8,
1626 llvm::SmallVectorImpl<wchar_t> &utf16) {
1627 return CodePageToUTF16(CP_UTF8, utf8, utf16);
1630std::error_code CurCPToUTF16(llvm::StringRef curcp,
1631 llvm::SmallVectorImpl<wchar_t> &utf16) {
1632 return CodePageToUTF16(CP_ACP, curcp, utf16);
1635static std::error_code UTF16ToCodePage(
unsigned codepage,
const wchar_t *utf16,
1637 llvm::SmallVectorImpl<char> &converted) {
1640 int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len,
1641 converted.
begin(), 0, NULL, NULL);
1651 len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.
data(),
1652 converted.
size(), NULL, NULL);
1663 return std::error_code();
1666std::error_code UTF16ToUTF8(
const wchar_t *utf16,
size_t utf16_len,
1667 llvm::SmallVectorImpl<char> &utf8) {
1668 return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
1671std::error_code UTF16ToCurCP(
const wchar_t *utf16,
size_t utf16_len,
1672 llvm::SmallVectorImpl<char> &curcp) {
1673 return UTF16ToCodePage(CP_ACP, utf16, utf16_len, curcp);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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
amode Optimize addressing mode
std::unique_ptr< MemoryBuffer > openFile(const Twine &Path)
Merge contiguous icmps into a memcmp
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")))
LLVM_ABI const file_t kInvalidFile
size_t size() const
size - Get the array size.
Represents either an error or a value T.
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...
StringRef toStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single StringRef if it can be represented as such.
LLVM_ABI void toVector(SmallVectorImpl< char > &Out) const
Append the concatenated string into the given SmallString or SmallVector.
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().
LLVM_ABI uint32_t getLinkCount() const
LLVM_ABI 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)
LLVM_ABI std::error_code directory_iterator_increment(DirIterState &)
LLVM_ABI bool can_execute(const Twine &Path)
Can we execute this file?
LLVM_ABI std::error_code closeFile(file_t &F)
Close the file object.
LLVM_ABI std::error_code rename(const Twine &from, const Twine &to)
Rename from to to.
LLVM_ABI std::error_code create_hard_link(const Twine &to, const Twine &from)
Create a hard link from from to to, or return an error.
LLVM_ABI const file_t kInvalidFile
LLVM_ABI std::error_code access(const Twine &Path, AccessMode Mode)
Can the file be accessed?
LLVM_ABI ErrorOr< space_info > disk_space(const Twine &Path)
Get disk space usage information.
LLVM_ABI Expected< size_t > readNativeFile(file_t FileHandle, MutableArrayRef< char > Buf)
Reads Buf.size() bytes from FileHandle into Buf.
LLVM_ABI unsigned getUmask()
Get file creation mode mask of the process.
LLVM_ABI bool exists(const basic_file_status &status)
Does file exist?
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.
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:
@ CD_OpenAlways
CD_OpenAlways - When opening a file:
@ CD_CreateAlways
CD_CreateAlways - When opening a file:
@ CD_CreateNew
CD_CreateNew - When opening a file:
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?
LLVM_ABI std::error_code make_absolute(SmallVectorImpl< char > &path)
Make path an absolute path.
LLVM_ABI std::error_code resize_file_sparse(int FD, uint64_t Size)
Resize path to size with sparse files explicitly enabled.
LLVM_ABI std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout=std::chrono::milliseconds(0), LockKind Kind=LockKind::Exclusive)
Try to locks the file during the specified time.
LLVM_ABI std::error_code current_path(SmallVectorImpl< char > &result)
Get the current path.
LLVM_ABI std::error_code resize_file(int FD, uint64_t Size)
Resize path to size.
LLVM_ABI file_t convertFDToNativeFile(int FD)
Converts from a Posix file descriptor number to a native file handle.
LLVM_ABI std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
LLVM_ABI std::error_code create_directory(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create the directory in path.
LLVM_ABI std::error_code is_local(const Twine &path, bool &result)
Is the file mounted on a local filesystem?
LLVM_ABI std::error_code openFileForRead(const Twine &Name, int &ResultFD, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
LLVM_ABI std::error_code remove_directories(const Twine &path, bool IgnoreErrors=true)
Recursively delete a directory.
LLVM_ABI bool equivalent(file_status A, file_status B)
Do file_status's represent the same thing?
LLVM_ABI file_t getStderrHandle()
Return an open handle to standard error.
LLVM_ABI std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime, TimePoint<> ModificationTime)
Set the file modification and access time.
LLVM_ABI file_t getStdinHandle()
Return an open handle to standard in.
LLVM_ABI std::error_code unlockFile(int FD)
Unlock the file.
LLVM_ABI std::error_code setPermissions(const Twine &Path, perms Permissions)
Set file permissions.
LLVM_ABI bool is_directory(const basic_file_status &status)
Does status represent a directory?
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 '.
LLVM_ABI bool has_root_path(const Twine &path, Style style=Style::native)
Has root path?
void make_preferred(SmallVectorImpl< char > &path, Style style=Style::native)
For Windows path styles, convert path to use the preferred path separators.
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.
LLVM_ABI bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
LLVM_ABI StringRef root_name(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get root name.
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
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.
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.
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.
LLVM_ABI std::error_code mapLastWindowsError()
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
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
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
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.
@ 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
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
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.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
space_info - Self explanatory.