24 #include <sys/types.h> 35 #ifndef _ERRNO_T_DEFINED 36 #define _ERRNO_T_DEFINED 41 # pragma comment(lib, "advapi32.lib") // This provides CryptAcquireContextW. 42 # pragma comment(lib, "ole32.lib") // This provides CoTaskMemFree 47 using llvm::sys::windows::UTF8ToUTF16;
48 using llvm::sys::windows::CurCPToUTF16;
49 using llvm::sys::windows::UTF16ToUTF8;
50 using llvm::sys::path::widenPath;
69 std::error_code widenPath(
const Twine &Path8,
71 const size_t MaxDirLen = MAX_PATH - 12;
83 CurPathLen = ::GetCurrentDirectoryW(0, NULL);
89 if ((Path8Str.
size() + CurPathLen) >= MaxDirLen &&
96 FullPath.append(CurPath);
108 if (
I->size() == 1 && *
I ==
".")
110 if (
I->size() == 2 && *
I ==
"..")
115 return UTF8ToUTF16(FullPath, Path16);
119 return UTF8ToUTF16(Path8Str, Path16);
146 if (UTF16ToUTF8(PathName.
data(), PathName.
size(), PathNameUTF8))
149 return std::string(PathNameUTF8.
data());
155 uint64_t FileID = (
static_cast<uint64_t
>(FileIndexHigh) << 32ULL) |
156 static_cast<uint64_t
>(FileIndexLow);
158 return UniqueID(VolumeSerialNumber, FileID);
162 ULARGE_INTEGER Avail, Total, Free;
163 if (!::GetDiskFreeSpaceExA(Path.
str().c_str(), &Avail, &Total, &Free))
165 space_info SpaceInfo;
167 (
static_cast<uint64_t
>(Total.HighPart) << 32) + Total.LowPart;
168 SpaceInfo.free = (
static_cast<uint64_t
>(Free.HighPart) << 32) + Free.LowPart;
169 SpaceInfo.available =
170 (
static_cast<uint64_t
>(Avail.HighPart) << 32) + Avail.LowPart;
174 TimePoint<> basic_file_status::getLastAccessedTime()
const {
176 Time.dwLowDateTime = LastAccessedTimeLow;
177 Time.dwHighDateTime = LastAccessedTimeHigh;
181 TimePoint<> basic_file_status::getLastModificationTime()
const {
183 Time.dwLowDateTime = LastWriteTimeLow;
184 Time.dwHighDateTime = LastWriteTimeHigh;
188 uint32_t file_status::getLinkCount()
const {
194 DWORD len = MAX_PATH;
198 len = ::GetCurrentDirectoryW(cur_path.
capacity(), cur_path.
data());
206 }
while (len > cur_path.
capacity());
211 return UTF16ToUTF8(cur_path.
begin(), cur_path.
size(), result);
217 if (std::error_code ec = widenPath(path, wide_path))
220 if (!::SetCurrentDirectoryW(wide_path.
begin()))
223 return std::error_code();
230 if (std::error_code ec = widenPath(path, path_utf16))
233 if (!::CreateDirectoryW(path_utf16.
begin(), NULL)) {
234 DWORD LastError = ::GetLastError();
235 if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
239 return std::error_code();
247 if (std::error_code ec = widenPath(from, wide_from))
249 if (std::error_code ec = widenPath(to, wide_to))
252 if (!::CreateHardLinkW(wide_from.
begin(), wide_to.
begin(), NULL))
255 return std::error_code();
262 std::error_code
remove(
const Twine &path,
bool IgnoreNonExisting) {
265 if (std::error_code ec = widenPath(path, path_utf16))
279 c_str(path_utf16), DELETE,
280 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
282 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS |
283 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_DELETE_ON_CLOSE,
291 return std::error_code();
301 ::GetVolumePathNameW(Path.
data(), VolumePath.
data(), VolumePath.
size());
306 DWORD Err = ::GetLastError();
307 if (Err != ERROR_INSUFFICIENT_BUFFER)
317 const wchar_t *
P = VolumePath.
data();
319 UINT
Type = ::GetDriveTypeW(P);
323 return std::error_code();
327 case DRIVE_REMOVABLE:
329 return std::error_code();
345 if (std::error_code ec = widenPath(P, WidePath))
347 return is_local_internal(WidePath, result);
350 static std::error_code realPathFromHandle(HANDLE
H,
352 DWORD CountChars = ::GetFinalPathNameByHandleW(
353 H, Buffer.
begin(), Buffer.
capacity() - 1, FILE_NAME_NORMALIZED);
354 if (CountChars > Buffer.
capacity()) {
358 CountChars = ::GetFinalPathNameByHandleW(
359 H, Buffer.
data(), Buffer.
capacity() - 1, FILE_NAME_NORMALIZED);
364 return std::error_code();
367 static std::error_code realPathFromHandle(HANDLE H,
371 if (std::error_code EC = realPathFromHandle(H, Buffer))
378 if (CountChars >= 8 && ::
memcmp(Data, L
"\\\\?\\UNC\\", 16) == 0) {
383 }
else if (CountChars >= 4 && ::
memcmp(Data, L
"\\\\?\\", 8) == 0) {
390 return UTF16ToUTF8(Data, CountChars, RealPath);
393 std::error_code
is_local(
int FD,
bool &Result) {
395 HANDLE Handle =
reinterpret_cast<HANDLE
>(_get_osfhandle(FD));
397 if (std::error_code EC = realPathFromHandle(Handle, FinalPath))
400 return is_local_internal(FinalPath, Result);
403 static std::error_code setDeleteDisposition(HANDLE Handle,
bool Delete) {
404 FILE_DISPOSITION_INFO Disposition;
405 Disposition.DeleteFile = Delete;
406 if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
407 sizeof(Disposition)))
409 return std::error_code();
412 static std::error_code rename_internal(HANDLE FromHandle,
const Twine &To,
413 bool ReplaceIfExists) {
415 if (
auto EC = widenPath(To, ToWide))
418 std::vector<char> RenameInfoBuf(
sizeof(FILE_RENAME_INFO) -
sizeof(
wchar_t) +
419 (ToWide.
size() *
sizeof(wchar_t)));
420 FILE_RENAME_INFO &RenameInfo =
421 *
reinterpret_cast<FILE_RENAME_INFO *
>(RenameInfoBuf.data());
422 RenameInfo.ReplaceIfExists = ReplaceIfExists;
423 RenameInfo.RootDirectory = 0;
424 RenameInfo.FileNameLength = ToWide.
size() *
sizeof(wchar_t);
427 SetLastError(ERROR_SUCCESS);
428 if (!SetFileInformationByHandle(FromHandle, FileRenameInfo, &RenameInfo,
429 RenameInfoBuf.size())) {
430 unsigned Error = GetLastError();
431 if (Error == ERROR_SUCCESS)
432 Error = ERROR_CALL_NOT_IMPLEMENTED;
436 return std::error_code();
439 static std::error_code rename_handle(HANDLE FromHandle,
const Twine &To) {
441 if (std::error_code EC = widenPath(To, WideTo))
447 for (
unsigned Retry = 0; Retry != 200; ++Retry) {
448 auto EC = rename_internal(FromHandle, To,
true);
451 std::error_code(ERROR_CALL_NOT_IMPLEMENTED, std::system_category())) {
455 if (std::error_code EC2 = realPathFromHandle(FromHandle, WideFrom))
457 if (::MoveFileExW(WideFrom.
begin(), WideTo.
begin(),
458 MOVEFILE_REPLACE_EXISTING))
459 return std::error_code();
473 ::CreateFileW(WideTo.
begin(), GENERIC_READ | DELETE,
474 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
476 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL));
487 BY_HANDLE_FILE_INFORMATION FI;
488 if (!GetFileInformationByHandle(ToHandle, &FI))
492 for (
unsigned UniqueId = 0; UniqueId != 200; ++UniqueId) {
493 std::string TmpFilename = (To +
".tmp" +
utostr(UniqueId)).str();
494 if (
auto EC = rename_internal(ToHandle, TmpFilename,
false)) {
502 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
503 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
510 BY_HANDLE_FILE_INFORMATION FI2;
511 if (!GetFileInformationByHandle(ToHandle2, &FI2))
513 if (FI.nFileIndexHigh != FI2.nFileIndexHigh ||
514 FI.nFileIndexLow != FI2.nFileIndexLow ||
515 FI.dwVolumeSerialNumber != FI2.dwVolumeSerialNumber)
534 static std::error_code rename_fd(
int FromFD,
const Twine &To) {
535 HANDLE FromHandle =
reinterpret_cast<HANDLE
>(_get_osfhandle(FromFD));
536 return rename_handle(FromHandle, To);
542 if (std::error_code EC = widenPath(From, WideFrom))
547 for (
unsigned Retry = 0; Retry != 200; ++Retry) {
551 ::CreateFileW(WideFrom.
begin(), GENERIC_READ | DELETE,
552 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
553 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
560 return rename_handle(FromHandle, To);
563 std::error_code
resize_file(
int FD, uint64_t Size) {
564 #ifdef HAVE__CHSIZE_S 565 errno_t
error = ::_chsize_s(FD, Size);
567 errno_t error = ::_chsize(FD, Size);
569 return std::error_code(error, std::generic_category());
575 if (std::error_code EC = widenPath(Path, PathUtf16))
578 DWORD Attributes = ::GetFileAttributesW(PathUtf16.
begin());
580 if (Attributes == INVALID_FILE_ATTRIBUTES) {
582 DWORD LastError = ::GetLastError();
583 if (LastError != ERROR_FILE_NOT_FOUND &&
584 LastError != ERROR_PATH_NOT_FOUND)
589 if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
592 return std::error_code();
602 return A.FileIndexHigh == B.FileIndexHigh &&
603 A.FileIndexLow == B.FileIndexLow &&
604 A.FileSizeHigh == B.FileSizeHigh &&
605 A.FileSizeLow == B.FileSizeLow &&
606 A.LastAccessedTimeHigh == B.LastAccessedTimeHigh &&
607 A.LastAccessedTimeLow == B.LastAccessedTimeLow &&
608 A.LastWriteTimeHigh == B.LastWriteTimeHigh &&
609 A.LastWriteTimeLow == B.LastWriteTimeLow &&
610 A.VolumeSerialNumber == B.VolumeSerialNumber;
614 file_status fsA, fsB;
615 if (std::error_code ec =
status(A, fsA))
617 if (std::error_code ec =
status(B, fsB))
620 return std::error_code();
623 static bool isReservedName(
StringRef path) {
626 static const char *
const sReservedNames[] = {
"nul",
"con",
"prn",
"aux",
627 "com1",
"com2",
"com3",
"com4",
628 "com5",
"com6",
"com7",
"com8",
629 "com9",
"lpt1",
"lpt2",
"lpt3",
630 "lpt4",
"lpt5",
"lpt6",
"lpt7",
649 return (Attrs & FILE_ATTRIBUTE_DIRECTORY) ? file_type::directory_file
650 : file_type::regular_file;
657 static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
658 if (FileHandle == INVALID_HANDLE_VALUE)
659 goto handle_status_error;
661 switch (::GetFileType(FileHandle)) {
664 case FILE_TYPE_UNKNOWN: {
665 DWORD Err = ::GetLastError();
668 Result = file_status(file_type::type_unknown);
669 return std::error_code();
674 Result = file_status(file_type::character_file);
675 return std::error_code();
677 Result = file_status(file_type::fifo_file);
678 return std::error_code();
681 BY_HANDLE_FILE_INFORMATION
Info;
682 if (!::GetFileInformationByHandle(FileHandle, &Info))
683 goto handle_status_error;
685 Result = file_status(
686 file_type_from_attrs(Info.dwFileAttributes),
687 perms_from_attrs(Info.dwFileAttributes), Info.nNumberOfLinks,
688 Info.ftLastAccessTime.dwHighDateTime, Info.ftLastAccessTime.dwLowDateTime,
689 Info.ftLastWriteTime.dwHighDateTime, Info.ftLastWriteTime.dwLowDateTime,
690 Info.dwVolumeSerialNumber, Info.nFileSizeHigh, Info.nFileSizeLow,
691 Info.nFileIndexHigh, Info.nFileIndexLow);
692 return std::error_code();
695 DWORD LastError = ::GetLastError();
696 if (LastError == ERROR_FILE_NOT_FOUND ||
697 LastError == ERROR_PATH_NOT_FOUND)
698 Result = file_status(file_type::file_not_found);
699 else if (LastError == ERROR_SHARING_VIOLATION)
700 Result = file_status(file_type::type_unknown);
702 Result = file_status(file_type::status_error);
706 std::error_code
status(
const Twine &path, file_status &result,
bool Follow) {
711 if (isReservedName(path8)) {
712 result = file_status(file_type::character_file);
713 return std::error_code();
716 if (std::error_code ec = widenPath(path8, path_utf16))
719 DWORD attr = ::GetFileAttributesW(path_utf16.
begin());
720 if (attr == INVALID_FILE_ATTRIBUTES)
721 return getStatus(INVALID_HANDLE_VALUE, result);
723 DWORD Flags = FILE_FLAG_BACKUP_SEMANTICS;
725 if (!Follow && (attr & FILE_ATTRIBUTE_REPARSE_POINT))
726 Flags |= FILE_FLAG_OPEN_REPARSE_POINT;
729 ::CreateFileW(path_utf16.
begin(), 0,
730 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
731 NULL, OPEN_EXISTING, Flags, 0));
733 return getStatus(INVALID_HANDLE_VALUE, result);
735 return getStatus(h, result);
738 std::error_code
status(
int FD, file_status &Result) {
739 HANDLE FileHandle =
reinterpret_cast<HANDLE
>(_get_osfhandle(FD));
740 return getStatus(FileHandle, Result);
743 std::error_code
status(
file_t FileHandle, file_status &Result) {
744 return getStatus(FileHandle, Result);
753 if (std::error_code EC = widenPath(Path, PathUTF16))
756 DWORD Attributes = ::GetFileAttributesW(PathUTF16.
begin());
757 if (Attributes == INVALID_FILE_ATTRIBUTES)
764 Attributes &= ~FILE_ATTRIBUTE_READONLY;
767 Attributes |= FILE_ATTRIBUTE_NORMAL;
770 Attributes |= FILE_ATTRIBUTE_READONLY;
773 Attributes &= ~FILE_ATTRIBUTE_NORMAL;
776 if (!::SetFileAttributesW(PathUTF16.
begin(), Attributes))
779 return std::error_code();
788 TimePoint<> ModificationTime) {
790 FILETIME ModifyFT =
toFILETIME(ModificationTime);
791 HANDLE FileHandle =
reinterpret_cast<HANDLE
>(_get_osfhandle(FD));
792 if (!SetFileTime(FileHandle, NULL, &AccessFT, &ModifyFT))
794 return std::error_code();
798 uint64_t
Offset, mapmode Mode) {
800 if (OrigFileHandle == INVALID_HANDLE_VALUE)
805 case readonly: flprotect = PAGE_READONLY;
break;
806 case readwrite: flprotect = PAGE_READWRITE;
break;
807 case priv: flprotect = PAGE_WRITECOPY;
break;
810 HANDLE FileMappingHandle =
811 ::CreateFileMappingW(OrigFileHandle, 0, flprotect,
815 if (FileMappingHandle == NULL) {
820 DWORD dwDesiredAccess;
822 case readonly: dwDesiredAccess = FILE_MAP_READ;
break;
823 case readwrite: dwDesiredAccess = FILE_MAP_WRITE;
break;
824 case priv: dwDesiredAccess = FILE_MAP_COPY;
break;
826 Mapping = ::MapViewOfFile(FileMappingHandle,
831 if (Mapping == NULL) {
833 ::CloseHandle(FileMappingHandle);
838 MEMORY_BASIC_INFORMATION mbi;
839 SIZE_T Result = VirtualQuery(Mapping, &mbi,
sizeof(mbi));
842 ::UnmapViewOfFile(Mapping);
843 ::CloseHandle(FileMappingHandle);
846 Size = mbi.RegionSize;
854 ::CloseHandle(FileMappingHandle);
855 if (!::DuplicateHandle(::GetCurrentProcess(), OrigFileHandle,
856 ::GetCurrentProcess(), &FileHandle, 0, 0,
857 DUPLICATE_SAME_ACCESS)) {
859 ::UnmapViewOfFile(Mapping);
863 return std::error_code();
867 size_t length, uint64_t offset,
869 : Size(length), Mapping() {
870 ec =
init(fd, offset, mode);
875 static bool hasFlushBufferKernelBug() {
881 static const char PEMagic[] = {
'P',
'E',
'\0',
'\0'};
891 mapped_file_region::~mapped_file_region() {
896 ::UnmapViewOfFile(Mapping);
898 if (Mode == mapmode::readwrite && Exe && hasFlushBufferKernelBug()) {
906 ::FlushFileBuffers(FileHandle);
909 ::CloseHandle(FileHandle);
914 assert(Mapping &&
"Mapping failed but used anyway!");
918 char *mapped_file_region::data()
const {
919 assert(Mapping &&
"Mapping failed but used anyway!");
920 return reinterpret_cast<char*
>(Mapping);
923 const char *mapped_file_region::const_data()
const {
924 assert(Mapping &&
"Mapping failed but used anyway!");
925 return reinterpret_cast<const char*
>(Mapping);
928 int mapped_file_region::alignment() {
930 ::GetSystemInfo(&SysInfo);
931 return SysInfo.dwAllocationGranularity;
934 static basic_file_status status_from_find_data(WIN32_FIND_DATAW *FindData) {
935 return basic_file_status(file_type_from_attrs(FindData->dwFileAttributes),
936 perms_from_attrs(FindData->dwFileAttributes),
937 FindData->ftLastAccessTime.dwHighDateTime,
938 FindData->ftLastAccessTime.dwLowDateTime,
939 FindData->ftLastWriteTime.dwHighDateTime,
940 FindData->ftLastWriteTime.dwLowDateTime,
941 FindData->nFileSizeHigh, FindData->nFileSizeLow);
946 bool FollowSymlinks) {
949 if (std::error_code EC = widenPath(Path, PathUTF16))
953 if (PathUTF16.
size() > 0 &&
955 PathUTF16[Path.
size() - 1] != L
':') {
963 WIN32_FIND_DATAW FirstFind;
965 c_str(PathUTF16), FindExInfoBasic, &FirstFind, FindExSearchNameMatch,
966 NULL, FIND_FIRST_EX_LARGE_FETCH));
970 size_t FilenameLen = ::wcslen(FirstFind.cFileName);
971 while ((FilenameLen == 1 && FirstFind.cFileName[0] == L
'.') ||
972 (FilenameLen == 2 && FirstFind.cFileName[0] == L
'.' &&
973 FirstFind.cFileName[1] == L
'.'))
974 if (!::FindNextFileW(FindHandle, &FirstFind)) {
975 DWORD LastError = ::GetLastError();
977 if (LastError == ERROR_NO_MORE_FILES)
981 FilenameLen = ::wcslen(FirstFind.cFileName);
985 if (std::error_code EC =
986 UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
987 DirectoryEntryNameUTF8))
990 IT.IterationHandle =
intptr_t(FindHandle.take());
992 path::append(DirectoryEntryPath, DirectoryEntryNameUTF8);
994 directory_entry(DirectoryEntryPath, FollowSymlinks,
995 file_type_from_attrs(FirstFind.dwFileAttributes),
996 status_from_find_data(&FirstFind));
998 return std::error_code();
1002 if (IT.IterationHandle != 0)
1005 IT.IterationHandle = 0;
1006 IT.CurrentEntry = directory_entry();
1007 return std::error_code();
1011 WIN32_FIND_DATAW FindData;
1012 if (!::FindNextFileW(HANDLE(IT.IterationHandle), &FindData)) {
1013 DWORD LastError = ::GetLastError();
1015 if (LastError == ERROR_NO_MORE_FILES)
1020 size_t FilenameLen = ::wcslen(FindData.cFileName);
1021 if ((FilenameLen == 1 && FindData.cFileName[0] == L
'.') ||
1022 (FilenameLen == 2 && FindData.cFileName[0] == L
'.' &&
1023 FindData.cFileName[1] == L
'.'))
1027 if (std::error_code EC =
1028 UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
1029 DirectoryEntryPathUTF8))
1032 IT.CurrentEntry.replace_filename(
1033 Twine(DirectoryEntryPathUTF8),
1034 file_type_from_attrs(FindData.dwFileAttributes),
1035 status_from_find_data(&FindData));
1036 return std::error_code();
1045 int CrtOpenFlags = 0;
1047 CrtOpenFlags |= _O_APPEND;
1050 CrtOpenFlags |= _O_TEXT;
1056 ResultFD = ::_open_osfhandle(
intptr_t(*H), CrtOpenFlags);
1057 if (ResultFD == -1) {
1061 return std::error_code();
1073 if (Flags & OF_Append)
1078 return CREATE_ALWAYS;
1084 return OPEN_EXISTING;
1092 Result |= GENERIC_READ;
1094 Result |= GENERIC_WRITE;
1098 Result |= FILE_WRITE_ATTRIBUTES;
1102 static std::error_code openNativeFileInternal(
const Twine &
Name,
1105 bool Inherit =
false) {
1107 if (std::error_code EC = widenPath(Name, PathUTF16))
1110 SECURITY_ATTRIBUTES SA;
1111 SA.nLength =
sizeof(SA);
1112 SA.lpSecurityDescriptor =
nullptr;
1113 SA.bInheritHandle = Inherit;
1116 ::CreateFileW(PathUTF16.
begin(), Access,
1117 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &SA,
1119 if (H == INVALID_HANDLE_VALUE) {
1120 DWORD LastError = ::GetLastError();
1125 if (LastError != ERROR_ACCESS_DENIED)
1132 return std::error_code();
1140 "Cannot specify both 'CreateNew' and 'Append' file creation flags!");
1142 DWORD NativeDisp = nativeDisposition(Disp, Flags);
1143 DWORD NativeAccess = nativeAccess(Access, Flags);
1145 bool Inherit =
false;
1150 std::error_code EC = openNativeFileInternal(
1151 Name, Result, NativeDisp, NativeAccess, FILE_ATTRIBUTE_NORMAL, Inherit);
1157 SYSTEMTIME SystemTime;
1158 GetSystemTime(&SystemTime);
1159 if (SystemTimeToFileTime(&SystemTime, &FileTime) == 0 ||
1160 SetFileTime(Result, NULL, &FileTime, NULL) == 0) {
1161 DWORD LastError = ::GetLastError();
1162 ::CloseHandle(Result);
1167 if (Flags & OF_Delete) {
1168 if ((EC = setDeleteDisposition(Result,
true))) {
1169 ::CloseHandle(Result);
1183 return nativeFileToFd(*Result, ResultFD, Flags);
1186 static std::error_code directoryRealPath(
const Twine &Name,
1189 std::error_code EC = openNativeFileInternal(
1190 Name, File, OPEN_EXISTING, GENERIC_READ, FILE_FLAG_BACKUP_SEMANTICS);
1194 EC = realPathFromHandle(File, RealPath);
1195 ::CloseHandle(File);
1203 return nativeFileToFd(std::move(NativeFile), ResultFD,
OF_None);
1212 if (Result && RealPath)
1213 realPathFromHandle(*Result, *RealPath);
1219 return reinterpret_cast<HANDLE
>(::_get_osfhandle(FD));
1228 OVERLAPPED *Overlap) {
1233 DWORD BytesRead = 0;
1234 if (::ReadFile(FileHandle, Buf.
data(), BytesToRead, &BytesRead, Overlap))
1236 DWORD Err = ::GetLastError();
1238 if (Err == ERROR_BROKEN_PIPE || Err == ERROR_HANDLE_EOF)
1244 return readNativeFileImpl(FileHandle, Buf,
nullptr);
1250 OVERLAPPED Overlapped = {};
1251 Overlapped.Offset =
uint32_t(Offset);
1252 Overlapped.OffsetHigh =
uint32_t(Offset >> 32);
1253 return readNativeFileImpl(FileHandle, Buf, &Overlapped);
1259 if (!::CloseHandle(TmpF))
1261 return std::error_code();
1267 std::error_code EC = widenPath(path, Path16);
1268 if (EC && !IgnoreErrors)
1279 SHFILEOPSTRUCTW shfos = {};
1280 shfos.wFunc = FO_DELETE;
1281 shfos.pFrom = Path16.
data();
1282 shfos.fFlags = FOF_NO_UI;
1284 int result = ::SHFileOperationW(&shfos);
1285 if (result != 0 && !IgnoreErrors)
1287 return std::error_code();
1292 if (Path.
empty() || Path[0] !=
'~')
1299 if (!Expr.
empty()) {
1311 Path[0] = HomeDir[0];
1321 expandTildeExpr(dest);
1330 return std::error_code();
1335 expandTildeExpr(Storage);
1340 return directoryRealPath(path, dest);
1343 if (std::error_code EC =
1347 return std::error_code();
1353 static bool getKnownFolderPath(KNOWNFOLDERID folderId,
1355 wchar_t *path =
nullptr;
1356 if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE,
nullptr, &path) != S_OK)
1359 bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
1360 ::CoTaskMemFree(path);
1365 return getKnownFolderPath(FOLDERID_Profile, result);
1373 Size = GetEnvironmentVariableW(Var, Buf.
data(), Buf.
capacity());
1381 return !windows::UTF16ToUTF8(Buf.
data(),
Size, Res);
1385 const wchar_t *EnvironmentVariables[] = {L
"TMP", L
"TEMP", L
"USERPROFILE"};
1386 for (
auto *Env : EnvironmentVariables) {
1387 if (getTempDirEnvVar(Env, Res))
1394 (void)ErasedOnReboot;
1401 if (getTempDirEnvVar(Result)) {
1402 assert(!Result.
empty() &&
"Unexpected empty path");
1409 const char *DefaultResult =
"C:\\Temp";
1410 Result.
append(DefaultResult, DefaultResult + strlen(DefaultResult));
1415 std::error_code CodePageToUTF16(
unsigned codepage,
1418 if (!original.
empty()) {
1419 int len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.
begin(),
1429 len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.
begin(),
1441 return std::error_code();
1446 return CodePageToUTF16(CP_UTF8, utf8, utf16);
1451 return CodePageToUTF16(CP_ACP, curcp, utf16);
1455 std::error_code UTF16ToCodePage(
unsigned codepage,
const wchar_t *utf16,
1460 int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.
begin(),
1471 len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.
data(),
1472 converted.
size(), NULL, NULL);
1483 return std::error_code();
1486 std::error_code UTF16ToUTF8(
const wchar_t *utf16,
size_t utf16_len,
1488 return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
1491 std::error_code UTF16ToCurCP(
const wchar_t *utf16,
size_t utf16_len,
1493 return UTF16ToCodePage(CP_ACP, utf16, utf16_len, curcp);
const file_t kInvalidFile
bool is_separator(char value, Style style=Style::native)
Check whether the given char is a path separator on the host OS.
const_iterator end(StringRef path)
Get end iterator over path.
bool can_execute(const Twine &Path)
Can we execute this file?
Represents either an error or a value T.
void remove_filename(SmallVectorImpl< char > &path, Style style=Style::native)
Remove the last component from path unless it is the root dir.
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
bool status_known(const basic_file_status &s)
Is status available?
This class represents lattice values for constants.
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_NODISCARD 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...
FILETIME toFILETIME(TimePoint<> TP)
LLVM_NODISCARD bool equals_lower(StringRef RHS) const
equals_lower - Check for string equality, ignoring case.
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
file_t getStderrHandle()
Return an open handle to standard error.
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
void push_back(const T &Elt)
bool isTriviallyEmpty() const
Check if this twine is trivially empty; a false return value does not necessarily mean the twine is e...
std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime, TimePoint<> ModificationTime)
Set the file modification and access time.
StringRef toStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single StringRef if it can be represented as such.
std::error_code current_path(SmallVectorImpl< char > &result)
Get the current path.
bool is_directory(const basic_file_status &status)
Does status represent a directory?
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...
Error takeError()
Take ownership of the stored error.
void reserve(size_type N)
std::error_code remove_directories(const Twine &path, bool IgnoreErrors=true)
Recursively delete a directory.
CD_OpenExisting - When opening a file:
Expected< size_t > readNativeFileSlice(file_t FileHandle, MutableArrayRef< char > Buf, uint64_t Offset)
Reads Buf.size() bytes from FileHandle at offset Offset into Buf.
file_t convertFDToNativeFile(int FD)
Converts from a Posix file descriptor number to a native file handle.
amode Optimize addressing mode
std::error_code directory_iterator_increment(DirIterState &)
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVM_NODISCARD StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
void make_absolute(const Twine ¤t_directory, SmallVectorImpl< char > &path)
Make path an absolute path.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
std::error_code make_error_code(BitcodeError E)
bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
Tagged union holding either a T or a Error.
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
When a child process is launched, this file should remain open in the child process.
unsigned getUmask()
Get file creation mode mask of the process.
CD_CreateNew - When opening a file:
std::error_code is_local(const Twine &path, bool &result)
Is the file mounted on a local filesystem?
std::error_code create_link(const Twine &to, const Twine &from)
Create a link from from to to.
LLVM_NODISCARD size_t size() const
size - Get the string size.
file_t getStdinHandle()
Return an open handle to standard in.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
Delete the file on close. Only makes a difference on windows.
The file should be opened in text mode on platforms that make this distinction.
Analysis containing CSE Info
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 real_path(const Twine &path, SmallVectorImpl< char > &output, bool expand_tilde=false)
Collapse all .
initializer< Ty > init(const Ty &Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
The instances of the Type class are immutable: once they are created, they are never changed...
void expand_tilde(const Twine &path, SmallVectorImpl< char > &output)
Expands ~ expressions to the user's home directory.
std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
Instrumentation for Order File
size_t size() const
size - Get the array size.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
void set_size(size_t N)
Set the array size to N, which the current array must have enough capacity for.
std::error_code getUniqueID(const Twine Path, UniqueID &Result)
std::error_code mapWindowsError(unsigned EV)
std::error_code resize_file(int FD, uint64_t Size)
Resize path to size.
Expected< size_t > readNativeFile(file_t FileHandle, MutableArrayRef< char > Buf)
Reads Buf.size() bytes from FileHandle into Buf.
std::error_code create_hard_link(const Twine &to, const Twine &from)
Create a hard link from from to to, or return an error.
void toVector(SmallVectorImpl< char > &Out) const
Append the concatenated string into the given SmallString or SmallVector.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Force files Atime to be updated on access. Only makes a difference on windows.
static const char *const Magic
llvm::VersionTuple GetWindowsOSVersion()
Returns the Windows version as Major.Minor.0.BuildNumber.
SmallVectorImpl< T >::const_pointer c_str(SmallVectorImpl< T > &str)
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
std::error_code directory_iterator_construct(DirIterState &, StringRef, bool)
BlockVerifier::State From
Align max(MaybeAlign Lhs, Align Rhs)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
constexpr size_t array_lengthof(T(&)[N])
Find the length of an array.
The file should be opened in append mode.
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 closeFile(file_t &F)
Close the file object.
std::error_code setPermissions(const Twine &Path, perms Permissions)
Set file permissions.
std::string utostr(uint64_t X, bool isNeg=false)
iterator insert(iterator I, T &&Elt)
std::error_code set_current_path(const Twine &path)
Set the current path.
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::ZeroOrMore, cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate IT block based on arch"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow deprecated IT based on ARMv8"), clEnumValN(NoRestrictedIT, "arm-no-restrict-it", "Allow IT blocks based on ARMv7")))
bool has_root_path(const Twine &path, Style style=Style::native)
Has root path?
ErrorOr< space_info > disk_space(const Twine &Path)
Get disk space usage information.
bool startswith(StringRef Prefix) const
startswith - Check if this string starts with the given Prefix.
std::error_code directory_iterator_destruct(DirIterState &)
Represents a version number in the form major[.minor[.subminor[.build]]].
pointer data()
Return a pointer to the vector's buffer, even if empty().
Merge contiguous icmps into a memcmp
file_type
An enumeration for the file system's view of the type.
LLVM_NODISCARD bool empty() const
uint32_t read32le(const void *P)
static bool Execute(ProcessInfo &PI, StringRef Program, ArrayRef< StringRef > Args, Optional< ArrayRef< StringRef >> Env, ArrayRef< Optional< StringRef >> Redirects, unsigned MemoryLimit, std::string *ErrMsg)
static void rename(GlobalValue *GV)
static const char PEMagic[]
std::error_code create_directory(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create the directory in path.
std::string str() const
Return the twine contents as a std::string.
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_NODISCARD const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool equivalent(file_status A, file_status B)
Do file_status's represent the same thing?
CD_CreateAlways - When opening a file:
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Lightweight error class with error context and mandatory checking.
bool home_directory(SmallVectorImpl< char > &result)
Get the user's home directory.
file_t getStdoutHandle()
Return an open handle to standard out.
std::error_code access(const Twine &Path, AccessMode Mode)
Can the file be accessed?
StringRef - Represent a constant reference to a string, i.e.
CD_OpenAlways - When opening a file:
bool exists(const basic_file_status &status)
Does file exist?
OutputIt copy(R &&Range, OutputIt Out)
std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
TimePoint< std::chrono::seconds > toTimePoint(std::time_t T)
Convert a std::time_t to a TimePoint.