36#ifndef _ERRNO_T_DEFINED
37#define _ERRNO_T_DEFINED
42#pragma comment(lib, "advapi32.lib")
43#pragma comment(lib, "ole32.lib")
48using llvm::sys::windows::CurCPToUTF16;
49using llvm::sys::windows::UTF16ToUTF8;
50using llvm::sys::windows::UTF8ToUTF16;
68static constexpr wchar_t LongPathPrefix16[] = LR
"(\\?\)";
69static constexpr wchar_t LongPathUNCPrefix16[] = LR
"(\\?\UNC\)";
71static constexpr DWORD LongPathPrefix16Len =
72 static_cast<DWORD
>(std::size(LongPathPrefix16) - 1);
73static constexpr DWORD LongPathUNCPrefix16Len =
74 static_cast<DWORD
>(std::size(LongPathUNCPrefix16) - 1);
76static void stripLongPathPrefix(
wchar_t *&
Data, DWORD &CountChars) {
77 if (CountChars >= LongPathUNCPrefix16Len &&
78 ::wmemcmp(
Data, LongPathUNCPrefix16, LongPathUNCPrefix16Len) == 0) {
83 }
else if (CountChars >= LongPathPrefix16Len &&
84 ::wmemcmp(
Data, LongPathPrefix16, LongPathPrefix16Len) == 0) {
98std::error_code
widenPath(
const Twine &Path8, SmallVectorImpl<wchar_t> &Path16,
100 assert(MaxPathLen <= MAX_PATH);
104 SmallString<MAX_PATH> Path8Str;
112 if (std::error_code EC = UTF8ToUTF16(Path8Str, Path16))
120 CurPathLen = ::GetCurrentDirectoryW(
126 if ((Path16.
size() + CurPathLen) < MaxPathLen ||
128 return std::error_code();
143 "Root name cannot be empty for an absolute path!");
145 SmallString<2 * MAX_PATH> FullPath;
146 if (RootName[1] !=
':') {
147 FullPath.
append(LongPathUNCPrefix8);
150 FullPath.
append(LongPathPrefix8);
151 FullPath.
append(Path8Str);
154 return UTF8ToUTF16(FullPath, Path16);
158 llvm::SmallVectorImpl<char> &Result8) {
159 SmallString<128> PathStorage;
160 StringRef PathStr = Path8.
toStringRef(PathStorage);
161 bool HadPrefix = PathStr.
starts_with(LongPathPrefix8);
164 if (std::error_code EC =
widenPath(PathStr, Path16))
175 Len = ::GetLongPathNameW(Path16.
data(), Long16.
data(), Len);
186 }
while (Len > Long16.
size());
196 stripLongPathPrefix(
Data, Len);
198 return sys::windows::UTF16ToUTF8(
Data, Len, Result8);
229 if (UTF16ToUTF8(PathName.
data(), PathName.
size(), PathNameUTF8))
234 SmallString<256> RealPath;
237 return std::string(RealPath);
238 return std::string(PathNameUTF8.
data());
242 return UniqueID(VolumeSerialNumber, PathHash);
245ErrorOr<space_info>
disk_space(
const Twine &Path) {
249 if (std::error_code EC =
widenPath(Path, PathUTF16))
252 if (!::GetDiskFreeSpaceExW(PathUTF16.
data(), &Avail, &
Total, &
Free))
257 SpaceInfo.free =
Free.QuadPart;
258 SpaceInfo.available = Avail.QuadPart;
265 Time.dwLowDateTime = LastAccessedTimeLow;
266 Time.dwHighDateTime = LastAccessedTimeHigh;
272 Time.dwLowDateTime = LastWriteTimeLow;
273 Time.dwHighDateTime = LastWriteTimeHigh;
279std::error_code
current_path(SmallVectorImpl<char> &result) {
283 DWORD len = MAX_PATH;
287 len = ::GetCurrentDirectoryW(cur_path.
size(), cur_path.
data());
295 }
while (len > cur_path.
size());
301 if (std::error_code EC =
302 UTF16ToUTF8(cur_path.
begin(), cur_path.
size(), result))
306 return std::error_code();
314 if (std::error_code ec =
widenPath(path, wide_path))
317 if (!::SetCurrentDirectoryW(wide_path.
begin()))
320 return std::error_code();
329 if (std::error_code ec =
widenPath(path, path_utf16, MAX_PATH - 12))
332 if (!::CreateDirectoryW(path_utf16.
begin(), NULL)) {
333 DWORD LastError = ::GetLastError();
334 if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
338 return std::error_code();
342std::error_code
create_link(
const Twine &to,
const Twine &from) {
346 if (std::error_code ec =
widenPath(from, wide_from))
348 if (std::error_code ec =
widenPath(to, wide_to))
351 if (!::CreateHardLinkW(wide_from.
begin(), wide_to.
begin(), NULL))
354 return std::error_code();
361std::error_code
remove(
const Twine &path,
bool IgnoreNonExisting) {
364 if (std::error_code ec =
widenPath(path, path_utf16))
378 c_str(path_utf16), DELETE,
379 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
381 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS |
382 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_DELETE_ON_CLOSE,
390 return std::error_code();
393static std::error_code is_local_internal(SmallVectorImpl<wchar_t> &Path,
400 ::GetVolumePathNameW(
Path.data(), VolumePath.
data(), VolumePath.
size());
405 DWORD Err = ::GetLastError();
406 if (Err != ERROR_INSUFFICIENT_BUFFER)
416 const wchar_t *
P = VolumePath.
data();
418 UINT
Type = ::GetDriveTypeW(
P);
422 return std::error_code();
426 case DRIVE_REMOVABLE:
428 return std::error_code();
435std::error_code
is_local(
const Twine &path,
bool &result) {
441 SmallString<128> Storage;
446 if (std::error_code ec =
widenPath(
P, WidePath))
448 return is_local_internal(WidePath, result);
451static std::error_code realPathFromHandle(HANDLE
H,
452 SmallVectorImpl<wchar_t> &Buffer,
453 DWORD flags = VOLUME_NAME_DOS) {
455 DWORD CountChars = ::GetFinalPathNameByHandleW(
456 H, Buffer.
begin(), Buffer.
capacity(), FILE_NAME_NORMALIZED | flags);
457 if (CountChars && CountChars >= Buffer.
capacity()) {
461 CountChars = ::GetFinalPathNameByHandleW(
H, Buffer.
begin(), Buffer.
size(),
462 FILE_NAME_NORMALIZED | flags);
467 return std::error_code();
470static std::error_code realPathFromHandle(HANDLE
H,
471 SmallVectorImpl<char> &RealPath) {
474 if (std::error_code EC = realPathFromHandle(
H, Buffer))
481 stripLongPathPrefix(
Data, CountChars);
484 if (std::error_code EC = UTF16ToUTF8(
Data, CountChars, RealPath))
488 return std::error_code();
491std::error_code
is_local(
int FD,
bool &Result) {
495 HANDLE Handle =
reinterpret_cast<HANDLE
>(_get_osfhandle(FD));
497 if (std::error_code EC = realPathFromHandle(Handle, FinalPath))
500 return is_local_internal(FinalPath, Result);
503static std::error_code setDeleteDisposition(HANDLE Handle,
bool Delete) {
508 FILE_DISPOSITION_INFO Disposition;
509 Disposition.DeleteFile =
false;
510 if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
511 sizeof(Disposition)))
514 return std::error_code();
520 if (std::error_code EC = realPathFromHandle(Handle, FinalPath))
524 if (std::error_code EC = is_local_internal(FinalPath, IsLocal))
532 Disposition.DeleteFile =
true;
533 if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
534 sizeof(Disposition)))
536 return std::error_code();
539static std::error_code rename_internal(HANDLE FromHandle,
const Twine &To,
540 bool ReplaceIfExists) {
545 std::vector<char> RenameInfoBuf(
sizeof(FILE_RENAME_INFO) -
sizeof(
wchar_t) +
546 (ToWide.
size() *
sizeof(
wchar_t)));
547 FILE_RENAME_INFO &RenameInfo =
548 *
reinterpret_cast<FILE_RENAME_INFO *
>(RenameInfoBuf.data());
549 RenameInfo.ReplaceIfExists = ReplaceIfExists;
550 RenameInfo.RootDirectory = 0;
551 RenameInfo.FileNameLength = ToWide.
size() *
sizeof(wchar_t);
552 std::copy(ToWide.
begin(), ToWide.
end(), &RenameInfo.FileName[0]);
554 SetLastError(ERROR_SUCCESS);
555 if (!SetFileInformationByHandle(FromHandle, FileRenameInfo, &RenameInfo,
556 RenameInfoBuf.size())) {
557 unsigned Error = GetLastError();
558 if (
Error == ERROR_SUCCESS)
559 Error = ERROR_CALL_NOT_IMPLEMENTED;
563 return std::error_code();
566static std::error_code rename_handle(HANDLE FromHandle,
const Twine &To) {
568 if (std::error_code EC =
widenPath(To, WideTo))
574 for (
unsigned Retry = 0; Retry != 200; ++Retry) {
575 auto EC = rename_internal(FromHandle, To,
true);
578 std::error_code(ERROR_CALL_NOT_IMPLEMENTED, std::system_category())) {
582 if (std::error_code EC2 = realPathFromHandle(FromHandle, WideFrom))
584 if (::MoveFileExW(WideFrom.
begin(), WideTo.
begin(),
585 MOVEFILE_REPLACE_EXISTING))
586 return std::error_code();
600 ::CreateFileW(WideTo.
begin(), GENERIC_READ | DELETE,
601 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
603 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL));
614 BY_HANDLE_FILE_INFORMATION FI;
615 if (!GetFileInformationByHandle(ToHandle, &FI))
619 for (
unsigned UniqueId = 0; UniqueId != 200; ++UniqueId) {
620 std::string TmpFilename = (To +
".tmp" +
utostr(UniqueId)).str();
621 if (
auto EC = rename_internal(ToHandle, TmpFilename,
false)) {
629 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
630 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
637 BY_HANDLE_FILE_INFORMATION FI2;
638 if (!GetFileInformationByHandle(ToHandle2, &FI2))
640 if (FI.nFileIndexHigh != FI2.nFileIndexHigh ||
641 FI.nFileIndexLow != FI2.nFileIndexLow ||
642 FI.dwVolumeSerialNumber != FI2.dwVolumeSerialNumber)
661std::error_code
rename(
const Twine &From,
const Twine &To) {
664 if (std::error_code EC =
widenPath(From, WideFrom))
669 for (
unsigned Retry = 0; Retry != 200; ++Retry) {
675 ::CreateFileW(WideFrom.
begin(), GENERIC_READ | DELETE,
676 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
677 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
689 return rename_handle(FromHandle, To);
698 return std::error_code(
error, std::generic_category());
702 HANDLE hFile =
reinterpret_cast<HANDLE
>(::_get_osfhandle(FD));
704 if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, &temp,
708 LARGE_INTEGER liSize;
709 liSize.QuadPart =
Size;
710 if (!SetFilePointerEx(hFile, liSize, NULL, FILE_BEGIN) ||
711 !SetEndOfFile(hFile)) {
714 return std::error_code();
722 if (std::error_code EC =
widenPath(Path, PathUtf16))
733 DWORD LastError = ::GetLastError();
734 if (LastError != ERROR_FILE_NOT_FOUND && LastError != ERROR_PATH_NOT_FOUND)
745 return std::error_code();
755 return A.getUniqueID() ==
B.getUniqueID();
758std::error_code
equivalent(
const Twine &
A,
const Twine &
B,
bool &result) {
762 if (std::error_code ec =
status(
A, fsA))
764 if (std::error_code ec =
status(
B, fsB))
767 return std::error_code();
770static bool isReservedName(StringRef path) {
773 static const char *
const sReservedNames[] = {
774 "nul",
"con",
"prn",
"aux",
"com1",
"com2",
"com3",
"com4",
775 "com5",
"com6",
"com7",
"com8",
"com9",
"lpt1",
"lpt2",
"lpt3",
776 "lpt4",
"lpt5",
"lpt6",
"lpt7",
"lpt8",
"lpt9"};
784 for (
size_t i = 0; i < std::size(sReservedNames); ++i) {
793static file_type file_type_from_attrs(DWORD Attrs) {
798static perms perms_from_attrs(DWORD Attrs) {
802static std::error_code getStatus(HANDLE FileHandle,
file_status &Result) {
804 if (FileHandle == INVALID_HANDLE_VALUE)
805 goto handle_status_error;
807 switch (::GetFileType(FileHandle)) {
810 case FILE_TYPE_UNKNOWN: {
811 DWORD Err = ::GetLastError();
815 return std::error_code();
821 return std::error_code();
824 return std::error_code();
827 BY_HANDLE_FILE_INFORMATION
Info;
828 if (!::GetFileInformationByHandle(FileHandle, &Info))
829 goto handle_status_error;
842 if (std::error_code EC =
843 realPathFromHandle(FileHandle, ntPath, VOLUME_NAME_NT)) {
849 PathHash = (
static_cast<uint64_t
>(
Info.nFileIndexHigh) << 32ULL) |
850 static_cast<uint64_t
>(
Info.nFileIndexLow);
856 file_type_from_attrs(
Info.dwFileAttributes),
857 perms_from_attrs(
Info.dwFileAttributes),
Info.nNumberOfLinks,
858 Info.ftLastAccessTime.dwHighDateTime,
Info.ftLastAccessTime.dwLowDateTime,
859 Info.ftLastWriteTime.dwHighDateTime,
Info.ftLastWriteTime.dwLowDateTime,
860 Info.dwVolumeSerialNumber,
Info.nFileSizeHigh,
Info.nFileSizeLow,
862 return std::error_code();
866 if (Err == std::errc::no_such_file_or_directory)
868 else if (Err == std::errc::permission_denied)
878 SmallString<128> path_storage;
882 if (isReservedName(path8)) {
884 return std::error_code();
887 if (std::error_code ec =
widenPath(path8, path_utf16))
892 DWORD attr = ::GetFileAttributesW(path_utf16.
begin());
893 if (attr == INVALID_FILE_ATTRIBUTES)
894 return getStatus(INVALID_HANDLE_VALUE, result);
897 if (attr & FILE_ATTRIBUTE_REPARSE_POINT)
898 Flags |= FILE_FLAG_OPEN_REPARSE_POINT;
902 ::CreateFileW(path_utf16.
begin(), 0,
903 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
904 NULL, OPEN_EXISTING, Flags, 0));
906 return getStatus(INVALID_HANDLE_VALUE, result);
908 return getStatus(h, result);
914 HANDLE FileHandle =
reinterpret_cast<HANDLE
>(_get_osfhandle(FD));
915 return getStatus(FileHandle, Result);
921 return getStatus(FileHandle, Result);
928 if (std::error_code EC =
widenPath(Path, PathUTF16))
953 return std::error_code();
958 return std::make_error_code(std::errc::not_supported);
964 FILETIME ModifyFT =
toFILETIME(ModificationTime);
965 HANDLE FileHandle =
reinterpret_cast<HANDLE
>(_get_osfhandle(FD));
966 if (!SetFileTime(FileHandle, NULL, &AccessFT, &ModifyFT))
968 return std::error_code();
971std::error_code mapped_file_region::init(
sys::fs::file_t OrigFileHandle,
974 if (OrigFileHandle == INVALID_HANDLE_VALUE)
980 flprotect = PAGE_READONLY;
983 flprotect = PAGE_READWRITE;
986 flprotect = PAGE_WRITECOPY;
990 HANDLE FileMappingHandle = ::CreateFileMappingW(OrigFileHandle, 0, flprotect,
992 if (FileMappingHandle == NULL) {
997 DWORD dwDesiredAccess;
1000 dwDesiredAccess = FILE_MAP_READ;
1003 dwDesiredAccess = FILE_MAP_WRITE;
1006 dwDesiredAccess = FILE_MAP_COPY;
1009 Mapping = ::MapViewOfFile(FileMappingHandle, dwDesiredAccess,
Offset >> 32,
1010 Offset & 0xffffffff, Size);
1011 if (Mapping == NULL) {
1013 ::CloseHandle(FileMappingHandle);
1018 MEMORY_BASIC_INFORMATION mbi;
1019 SIZE_T
Result = VirtualQuery(Mapping, &mbi,
sizeof(mbi));
1022 ::UnmapViewOfFile(Mapping);
1023 ::CloseHandle(FileMappingHandle);
1026 Size = mbi.RegionSize;
1034 ::CloseHandle(FileMappingHandle);
1035 if (!::DuplicateHandle(::GetCurrentProcess(), OrigFileHandle,
1036 ::GetCurrentProcess(), &FileHandle, 0, 0,
1037 DUPLICATE_SAME_ACCESS)) {
1039 ::UnmapViewOfFile(Mapping);
1043 return std::error_code();
1047 size_t length, uint64_t offset,
1048 std::error_code &ec)
1054 copyFrom(mapped_file_region());
1057static bool hasFlushBufferKernelBug() {
1063 static const char PEMagic[] = {
'P',
'E',
'\0',
'\0'};
1067 if (
Magic.substr(off).starts_with(
StringRef(PEMagic,
sizeof(PEMagic))))
1073void mapped_file_region::unmapImpl() {
1078 ::UnmapViewOfFile(Mapping);
1080 if (
Mode == mapmode::readwrite) {
1081 bool DoFlush =
Exe && hasFlushBufferKernelBug();
1099 bool IsLocal =
false;
1101 if (!realPathFromHandle(FileHandle, FinalPath)) {
1104 is_local_internal(FinalPath, IsLocal);
1109 ::FlushFileBuffers(FileHandle);
1112 ::CloseHandle(FileHandle);
1116void mapped_file_region::dontNeedImpl() {}
1118void mapped_file_region::willNeedImpl() {
1119 struct MEMORY_RANGE_ENTRY {
1120 PVOID VirtualAddress;
1121 SIZE_T NumberOfBytes;
1125 typedef BOOL(WINAPI * PrefetchVirtualMemory_t)(
1126 HANDLE hProcess, ULONG_PTR NumberOfEntries,
1127 MEMORY_RANGE_ENTRY * VirtualAddresses, ULONG Flags);
1129 static auto pfnPrefetchVirtualMemory = []() -> PrefetchVirtualMemory_t {
1134 return (PrefetchVirtualMemory_t)::GetProcAddress(kernelM,
1135 "PrefetchVirtualMemory");
1137 if (pfnPrefetchVirtualMemory) {
1138 MEMORY_RANGE_ENTRY
Range{Mapping,
Size};
1139 pfnPrefetchVirtualMemory(::GetCurrentProcess(), 1, &
Range, 0);
1143std::error_code mapped_file_region::sync()
const {
1144 if (!::FlushViewOfFile(Mapping,
Size))
1146 if (!::FlushFileBuffers(FileHandle))
1148 return std::error_code();
1151int mapped_file_region::alignment() {
1152 SYSTEM_INFO SysInfo;
1153 ::GetSystemInfo(&SysInfo);
1154 return SysInfo.dwAllocationGranularity;
1157static basic_file_status status_from_find_data(WIN32_FIND_DATAW *FindData) {
1158 return basic_file_status(file_type_from_attrs(FindData->dwFileAttributes),
1159 perms_from_attrs(FindData->dwFileAttributes),
1160 FindData->ftLastAccessTime.dwHighDateTime,
1161 FindData->ftLastAccessTime.dwLowDateTime,
1162 FindData->ftLastWriteTime.dwHighDateTime,
1163 FindData->ftLastWriteTime.dwLowDateTime,
1164 FindData->nFileSizeHigh, FindData->nFileSizeLow);
1167std::error_code detail::directory_iterator_construct(detail::DirIterState &
IT,
1169 bool FollowSymlinks) {
1174 if (std::error_code EC =
widenPath(Path, PathUTF16))
1178 size_t PathUTF16Len = PathUTF16.
size();
1179 if (PathUTF16Len > 0 && !
is_separator(PathUTF16[PathUTF16Len - 1]) &&
1180 PathUTF16[PathUTF16Len - 1] != L
':') {
1188 WIN32_FIND_DATAW FirstFind;
1190 c_str(PathUTF16), FindExInfoBasic, &FirstFind, FindExSearchNameMatch,
1191 NULL, FIND_FIRST_EX_LARGE_FETCH));
1195 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
1196 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L
'.') ||
1197 (FilenameLen == 2 && FirstFind.cFileName[0] == L
'.' &&
1198 FirstFind.cFileName[1] == L
'.'))
1199 if (!::FindNextFileW(FindHandle, &FirstFind)) {
1200 DWORD LastError = ::GetLastError();
1202 if (LastError == ERROR_NO_MORE_FILES)
1203 return detail::directory_iterator_destruct(
IT);
1206 FilenameLen = ::wcslen(FirstFind.cFileName);
1211 if (std::error_code EC =
1212 UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
1213 DirectoryEntryNameUTF8))
1216 IT.IterationHandle = intptr_t(FindHandle.take());
1218 path::append(DirectoryEntryPath, DirectoryEntryNameUTF8);
1220 directory_entry(DirectoryEntryPath, FollowSymlinks,
1221 file_type_from_attrs(FirstFind.dwFileAttributes),
1222 status_from_find_data(&FirstFind));
1224 return std::error_code();
1227std::error_code detail::directory_iterator_destruct(detail::DirIterState &
IT) {
1228 if (
IT.IterationHandle != 0)
1231 IT.IterationHandle = 0;
1232 IT.CurrentEntry = directory_entry();
1233 return std::error_code();
1236std::error_code detail::directory_iterator_increment(detail::DirIterState &
IT) {
1239 WIN32_FIND_DATAW FindData;
1240 if (!::FindNextFileW(HANDLE(
IT.IterationHandle), &FindData)) {
1241 DWORD LastError = ::GetLastError();
1243 if (LastError == ERROR_NO_MORE_FILES)
1244 return detail::directory_iterator_destruct(
IT);
1248 size_t FilenameLen = ::wcslen(FindData.cFileName);
1249 if ((FilenameLen == 1 && FindData.cFileName[0] == L
'.') ||
1250 (FilenameLen == 2 && FindData.cFileName[0] == L
'.' &&
1251 FindData.cFileName[1] == L
'.'))
1255 if (std::error_code EC =
1256 UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
1257 DirectoryEntryPathUTF8))
1260 IT.CurrentEntry.replace_filename(
1261 Twine(DirectoryEntryPathUTF8),
1262 file_type_from_attrs(FindData.dwFileAttributes),
1263 status_from_find_data(&FindData));
1264 return std::error_code();
1269static std::error_code nativeFileToFd(Expected<HANDLE>
H,
int &ResultFD,
1271 int CrtOpenFlags = 0;
1272 if (Flags & OF_Append)
1273 CrtOpenFlags |= _O_APPEND;
1275 if (Flags & OF_CRLF) {
1276 assert(Flags & OF_Text &&
"Flags set OF_CRLF without OF_Text");
1277 CrtOpenFlags |= _O_TEXT;
1284 ResultFD = ::_open_osfhandle(intptr_t(*
H), CrtOpenFlags);
1285 if (ResultFD == -1) {
1289 return std::error_code();
1292static DWORD nativeDisposition(CreationDisposition Disp, OpenFlags Flags) {
1301 if (Flags & OF_Append)
1306 return CREATE_ALWAYS;
1312 return OPEN_EXISTING;
1317static DWORD nativeAccess(FileAccess
Access, OpenFlags Flags) {
1323 if (Flags & OF_Delete)
1325 if (Flags & OF_UpdateAtime)
1326 Result |= FILE_WRITE_ATTRIBUTES;
1330static std::error_code openNativeFileInternal(
const Twine &Name,
1331 file_t &ResultFile, DWORD Disp,
1332 DWORD
Access, DWORD Flags,
1333 bool Inherit =
false) {
1335 if (std::error_code EC =
widenPath(Name, PathUTF16))
1338 SECURITY_ATTRIBUTES SA;
1339 SA.nLength =
sizeof(SA);
1340 SA.lpSecurityDescriptor =
nullptr;
1341 SA.bInheritHandle = Inherit;
1345 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &SA,
1347 if (
H == INVALID_HANDLE_VALUE) {
1348 DWORD LastError = ::GetLastError();
1353 if (LastError != ERROR_ACCESS_DENIED)
1360 return std::error_code();
1364 FileAccess
Access, OpenFlags Flags,
1369 assert((!(Disp == CD_CreateNew) || !(Flags & OF_Append)) &&
1370 "Cannot specify both 'CreateNew' and 'Append' file creation flags!");
1372 DWORD NativeDisp = nativeDisposition(Disp, Flags);
1373 DWORD NativeAccess = nativeAccess(
Access, Flags);
1375 bool Inherit =
false;
1376 if (Flags & OF_ChildInherit)
1380 std::error_code
EC = openNativeFileInternal(
1381 Name, Result, NativeDisp, NativeAccess, FILE_ATTRIBUTE_NORMAL, Inherit);
1385 if (Flags & OF_UpdateAtime) {
1387 SYSTEMTIME SystemTime;
1388 GetSystemTime(&SystemTime);
1389 if (SystemTimeToFileTime(&SystemTime, &FileTime) == 0 ||
1390 SetFileTime(Result, NULL, &FileTime, NULL) == 0) {
1391 DWORD LastError = ::GetLastError();
1392 ::CloseHandle(Result);
1401 CreationDisposition Disp, FileAccess
Access,
1402 OpenFlags Flags,
unsigned int Mode) {
1409 return nativeFileToFd(*Result, ResultFD, Flags);
1412static std::error_code directoryRealPath(
const Twine &Name,
1415 std::error_code
EC = openNativeFileInternal(
1416 Name, File, OPEN_EXISTING, GENERIC_READ, FILE_FLAG_BACKUP_SEMANTICS);
1420 EC = realPathFromHandle(File, RealPath);
1421 ::CloseHandle(File);
1431 return nativeFileToFd(std::move(NativeFile), ResultFD, OF_None);
1438 Expected<file_t>
Result =
1442 if (Result && RealPath)
1443 realPathFromHandle(*Result, *RealPath);
1449 return reinterpret_cast<HANDLE
>(::_get_osfhandle(FD));
1456static Expected<size_t> readNativeFileImpl(
file_t FileHandle,
1458 OVERLAPPED *Overlap) {
1462 std::min(
size_t(std::numeric_limits<DWORD>::max()), Buf.
size());
1463 DWORD BytesRead = 0;
1464 if (::ReadFile(FileHandle, Buf.
data(), BytesToRead, &BytesRead, Overlap))
1466 DWORD Err = ::GetLastError();
1468 if (Err == ERROR_BROKEN_PIPE || Err == ERROR_HANDLE_EOF)
1476 return readNativeFileImpl(FileHandle, Buf,
nullptr);
1484 OVERLAPPED Overlapped = {};
1487 return readNativeFileImpl(FileHandle, Buf, &Overlapped);
1492 DWORD Flags = Kind == LockKind::Exclusive ? LOCKFILE_EXCLUSIVE_LOCK : 0;
1493 Flags |= LOCKFILE_FAIL_IMMEDIATELY;
1496 auto Start = std::chrono::steady_clock::now();
1499 if (::LockFileEx(File, Flags, 0, MAXDWORD, MAXDWORD, &OV))
1500 return std::error_code();
1501 DWORD Error = ::GetLastError();
1502 if (Error == ERROR_LOCK_VIOLATION) {
1509 }
while (std::chrono::steady_clock::now() < End);
1513std::error_code
lockFile(
int FD, LockKind Kind) {
1514 DWORD Flags = Kind == LockKind::Exclusive ? LOCKFILE_EXCLUSIVE_LOCK : 0;
1517 if (::LockFileEx(File, Flags, 0, MAXDWORD, MAXDWORD, &OV))
1518 return std::error_code();
1519 DWORD Error = ::GetLastError();
1526 if (::UnlockFileEx(File, 0, MAXDWORD, MAXDWORD, &OV))
1527 return std::error_code();
1534 if (!::CloseHandle(TmpF))
1536 return std::error_code();
1544 std::error_code
EC =
widenPath(NativePath, Path16);
1545 if (EC && !IgnoreErrors)
1559 CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
1563 IFileOperation *FileOp = NULL;
1564 HR = CoCreateInstance(CLSID_FileOperation, NULL, CLSCTX_ALL,
1565 IID_PPV_ARGS(&FileOp));
1569 HR = FileOp->SetOperationFlags(FOF_NO_UI | FOFX_NOCOPYHOOKS);
1572 PIDLIST_ABSOLUTE PIDL = ILCreateFromPathW(Path16.
data());
1574 IShellItem *ShItem = NULL;
1575 HR = SHCreateItemFromIDList(PIDL, IID_PPV_ARGS(&ShItem));
1579 HR = FileOp->DeleteItem(ShItem, NULL);
1582 HR = FileOp->PerformOperations();
1584 if (FAILED(HR) && !IgnoreErrors)
1586 return std::error_code();
1591 if (
Path.empty() || Path[0] !=
'~')
1599 if (!Expr.
empty()) {
1611 Path[0] = HomeDir[0];
1617 if (
path.isTriviallyEmpty())
1620 path.toVector(dest);
1621 expandTildeExpr(dest);
1627 bool expand_tilde) {
1631 if (
path.isTriviallyEmpty())
1632 return std::error_code();
1636 path.toVector(Storage);
1637 expandTildeExpr(Storage);
1642 return directoryRealPath(
path, dest);
1645 if (std::error_code EC =
1649 return std::error_code();
1655static bool getKnownFolderPath(KNOWNFOLDERID folderId,
1656 SmallVectorImpl<char> &result) {
1657 wchar_t *path =
nullptr;
1658 if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE,
nullptr, &path) != S_OK)
1661 bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
1662 ::CoTaskMemFree(path);
1669 return getKnownFolderPath(FOLDERID_Profile, result);
1675 return getKnownFolderPath(FOLDERID_LocalAppData, result);
1679 return getKnownFolderPath(FOLDERID_LocalAppData, result);
1682static bool getTempDirEnvVar(
const wchar_t *Var, SmallVectorImpl<char> &Res) {
1683 SmallVector<wchar_t, 1024> Buf;
1687 Size = GetEnvironmentVariableW(Var, Buf.
data(), Buf.
size());
1695 return !windows::UTF16ToUTF8(Buf.
data(),
Size, Res);
1698static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
1699 const wchar_t *EnvironmentVariables[] = {
L"TMP",
L"TEMP",
L"USERPROFILE"};
1700 for (
auto *Env : EnvironmentVariables) {
1701 if (getTempDirEnvVar(Env, Res))
1708 (void)ErasedOnReboot;
1715 if (getTempDirEnvVar(Result)) {
1718 fs::make_absolute(Result);
1723 const char *DefaultResult =
"C:\\Temp";
1724 Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
1730std::error_code CodePageToUTF16(
unsigned codepage, llvm::StringRef original,
1731 llvm::SmallVectorImpl<wchar_t> &utf16) {
1732 if (!original.
empty()) {
1734 ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.
begin(),
1745 ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.
begin(),
1757 return std::error_code();
1760std::error_code UTF8ToUTF16(llvm::StringRef utf8,
1761 llvm::SmallVectorImpl<wchar_t> &utf16) {
1762 return CodePageToUTF16(CP_UTF8, utf8, utf16);
1765std::error_code CurCPToUTF16(llvm::StringRef curcp,
1766 llvm::SmallVectorImpl<wchar_t> &utf16) {
1767 return CodePageToUTF16(CP_ACP, curcp, utf16);
1770static std::error_code UTF16ToCodePage(
unsigned codepage,
const wchar_t *utf16,
1772 llvm::SmallVectorImpl<char> &converted) {
1775 int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len,
1776 converted.
begin(), 0, NULL, NULL);
1786 len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.
data(),
1787 converted.
size(), NULL, NULL);
1798 return std::error_code();
1801std::error_code UTF16ToUTF8(
const wchar_t *utf16,
size_t utf16_len,
1802 llvm::SmallVectorImpl<char> &utf8) {
1803 return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
1806std::error_code UTF16ToCurCP(
const wchar_t *utf16,
size_t utf16_len,
1807 llvm::SmallVectorImpl<char> &curcp) {
1808 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")
amode Optimize addressing mode
std::unique_ptr< MemoryBuffer > openFile(const Twine &Path)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
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.
void append(StringRef RHS)
Append from a StringRef.
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.
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
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.
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
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)
Remove '.
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.
void violationIfEnabled()
ScopedSetting scopedDisable()
LLVM_ABI std::error_code makeLongFormPath(const Twine &Path8, llvm::SmallVectorImpl< char > &Result8)
Convert a UTF-8 path to a long form UTF-8 path expanding any short 8.3 form components.
LLVM_ABI std::error_code widenPath(const Twine &Path8, SmallVectorImpl< wchar_t > &Path16, size_t MaxPathLen=MAX_PATH)
Convert UTF-8 path to a suitable UTF-16 path for use with the Win32 Unicode File API.
LLVM_ABI HMODULE loadSystemModuleSecure(LPCWSTR lpModuleName)
Retrieves the handle to a in-memory system module such as ntdll.dll, while ensuring we're not retriev...
FILETIME toFILETIME(TimePoint<> TP)
std::chrono::time_point< std::chrono::system_clock, D > TimePoint
A time point on the system clock.
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()
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.