[llvm][Support] Add and use errnoAsErrorCode (#84423)

LLVM is inconsistent about how it converts `errno` to `std::error_code`.
This can cause problems because values outside of `std::errc` compare
differently if one is system and one is generic on POSIX systems.

This is even more of a problem on Windows where use of the system
category is just wrong, as that is for Windows errors, which have a
completely different mapping than POSIX/generic errors. This patch fixes
one instance of this mistake in `JSONTransport.cpp`.

This patch adds `errnoAsErrorCode()` which makes it so people do not
need to think about this issue in the future. It also cleans up a lot of
usage of `errno` in LLVM and Clang.
This commit is contained in:
Michael Spencer 2024-03-08 23:30:33 -08:00 committed by GitHub
parent abbf1f1882
commit ba13fa2a5d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
17 changed files with 94 additions and 93 deletions

View File

@ -107,8 +107,7 @@ public:
return error(std::make_error_code(std::errc::operation_canceled), return error(std::make_error_code(std::errc::operation_canceled),
"Got signal, shutting down"); "Got signal, shutting down");
if (ferror(In)) if (ferror(In))
return llvm::errorCodeToError( return llvm::errorCodeToError(llvm::errnoAsErrorCode());
std::error_code(errno, std::system_category()));
if (readRawMessage(JSON)) { if (readRawMessage(JSON)) {
ThreadCrashReporter ScopedReporter([&JSON]() { ThreadCrashReporter ScopedReporter([&JSON]() {
auto &OS = llvm::errs(); auto &OS = llvm::errs();

View File

@ -333,8 +333,7 @@ llvm::Expected<std::unique_ptr<DirectoryWatcher>> clang::DirectoryWatcher::creat
const int InotifyFD = inotify_init1(IN_CLOEXEC); const int InotifyFD = inotify_init1(IN_CLOEXEC);
if (InotifyFD == -1) if (InotifyFD == -1)
return llvm::make_error<llvm::StringError>( return llvm::make_error<llvm::StringError>(
std::string("inotify_init1() error: ") + strerror(errno), llvm::errnoAsErrorCode(), std::string(": inotify_init1()"));
llvm::inconvertibleErrorCode());
const int InotifyWD = inotify_add_watch( const int InotifyWD = inotify_add_watch(
InotifyFD, Path.str().c_str(), InotifyFD, Path.str().c_str(),
@ -346,15 +345,13 @@ llvm::Expected<std::unique_ptr<DirectoryWatcher>> clang::DirectoryWatcher::creat
); );
if (InotifyWD == -1) if (InotifyWD == -1)
return llvm::make_error<llvm::StringError>( return llvm::make_error<llvm::StringError>(
std::string("inotify_add_watch() error: ") + strerror(errno), llvm::errnoAsErrorCode(), std::string(": inotify_add_watch()"));
llvm::inconvertibleErrorCode());
auto InotifyPollingStopper = SemaphorePipe::create(); auto InotifyPollingStopper = SemaphorePipe::create();
if (!InotifyPollingStopper) if (!InotifyPollingStopper)
return llvm::make_error<llvm::StringError>( return llvm::make_error<llvm::StringError>(
std::string("SemaphorePipe::create() error: ") + strerror(errno), llvm::errnoAsErrorCode(), std::string(": SemaphorePipe::create()"));
llvm::inconvertibleErrorCode());
return std::make_unique<DirectoryWatcherLinux>( return std::make_unique<DirectoryWatcherLinux>(
Path, Receiver, WaitForInitialSync, InotifyFD, InotifyWD, Path, Receiver, WaitForInitialSync, InotifyFD, InotifyWD,

View File

@ -1180,6 +1180,20 @@ Error errorCodeToError(std::error_code EC);
/// will trigger a call to abort(). /// will trigger a call to abort().
std::error_code errorToErrorCode(Error Err); std::error_code errorToErrorCode(Error Err);
/// Helper to get errno as an std::error_code.
///
/// errno should always be represented using the generic category as that's what
/// both libc++ and libstdc++ do. On POSIX systems you can also represent them
/// using the system category, however this makes them compare differently for
/// values outside of those used by `std::errc` if one is generic and the other
/// is system.
///
/// See the libc++ and libstdc++ implementations of `default_error_condition` on
/// the system category for more details on what the difference is.
inline std::error_code errnoAsErrorCode() {
return std::error_code(errno, std::generic_category());
}
/// Convert an ErrorOr<T> to an Expected<T>. /// Convert an ErrorOr<T> to an Expected<T>.
template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) { template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
if (auto EC = EO.getError()) if (auto EC = EO.getError())

View File

@ -241,8 +241,7 @@ void SharedMemoryMapper::reserve(size_t NumBytes,
int SharedMemoryFile = shm_open(SharedMemoryName.c_str(), O_RDWR, 0700); int SharedMemoryFile = shm_open(SharedMemoryName.c_str(), O_RDWR, 0700);
if (SharedMemoryFile < 0) { if (SharedMemoryFile < 0) {
return OnReserved(errorCodeToError( return OnReserved(errorCodeToError(errnoAsErrorCode()));
std::error_code(errno, std::generic_category())));
} }
// this prevents other processes from accessing it by name // this prevents other processes from accessing it by name
@ -251,8 +250,7 @@ void SharedMemoryMapper::reserve(size_t NumBytes,
LocalAddr = mmap(nullptr, NumBytes, PROT_READ | PROT_WRITE, MAP_SHARED, LocalAddr = mmap(nullptr, NumBytes, PROT_READ | PROT_WRITE, MAP_SHARED,
SharedMemoryFile, 0); SharedMemoryFile, 0);
if (LocalAddr == MAP_FAILED) { if (LocalAddr == MAP_FAILED) {
return OnReserved(errorCodeToError( return OnReserved(errorCodeToError(errnoAsErrorCode()));
std::error_code(errno, std::generic_category())));
} }
close(SharedMemoryFile); close(SharedMemoryFile);
@ -376,8 +374,7 @@ void SharedMemoryMapper::release(ArrayRef<ExecutorAddr> Bases,
#if defined(LLVM_ON_UNIX) #if defined(LLVM_ON_UNIX)
if (munmap(Reservations[Base].LocalAddr, Reservations[Base].Size) != 0) if (munmap(Reservations[Base].LocalAddr, Reservations[Base].Size) != 0)
Err = joinErrors(std::move(Err), errorCodeToError(std::error_code( Err = joinErrors(std::move(Err), errorCodeToError(errnoAsErrorCode()));
errno, std::generic_category())));
#elif defined(_WIN32) #elif defined(_WIN32)

View File

@ -62,15 +62,15 @@ ExecutorSharedMemoryMapperService::reserve(uint64_t Size) {
int SharedMemoryFile = int SharedMemoryFile =
shm_open(SharedMemoryName.c_str(), O_RDWR | O_CREAT | O_EXCL, 0700); shm_open(SharedMemoryName.c_str(), O_RDWR | O_CREAT | O_EXCL, 0700);
if (SharedMemoryFile < 0) if (SharedMemoryFile < 0)
return errorCodeToError(std::error_code(errno, std::generic_category())); return errorCodeToError(errnoAsErrorCode());
// by default size is 0 // by default size is 0
if (ftruncate(SharedMemoryFile, Size) < 0) if (ftruncate(SharedMemoryFile, Size) < 0)
return errorCodeToError(std::error_code(errno, std::generic_category())); return errorCodeToError(errnoAsErrorCode());
void *Addr = mmap(nullptr, Size, PROT_NONE, MAP_SHARED, SharedMemoryFile, 0); void *Addr = mmap(nullptr, Size, PROT_NONE, MAP_SHARED, SharedMemoryFile, 0);
if (Addr == MAP_FAILED) if (Addr == MAP_FAILED)
return errorCodeToError(std::error_code(errno, std::generic_category())); return errorCodeToError(errnoAsErrorCode());
close(SharedMemoryFile); close(SharedMemoryFile);
@ -140,7 +140,7 @@ Expected<ExecutorAddr> ExecutorSharedMemoryMapperService::initialize(
NativeProt |= PROT_EXEC; NativeProt |= PROT_EXEC;
if (mprotect(Segment.Addr.toPtr<void *>(), Segment.Size, NativeProt)) if (mprotect(Segment.Addr.toPtr<void *>(), Segment.Size, NativeProt))
return errorCodeToError(std::error_code(errno, std::generic_category())); return errorCodeToError(errnoAsErrorCode());
#elif defined(_WIN32) #elif defined(_WIN32)
@ -240,8 +240,7 @@ Error ExecutorSharedMemoryMapperService::release(
#if defined(LLVM_ON_UNIX) #if defined(LLVM_ON_UNIX)
if (munmap(Base.toPtr<void *>(), Size) != 0) if (munmap(Base.toPtr<void *>(), Size) != 0)
Err = joinErrors(std::move(Err), errorCodeToError(std::error_code( Err = joinErrors(std::move(Err), errorCodeToError(errnoAsErrorCode()));
errno, std::generic_category())));
#elif defined(_WIN32) #elif defined(_WIN32)
(void)Size; (void)Size;

View File

@ -926,7 +926,7 @@ Expected<std::string> computeArchiveRelativePath(StringRef From, StringRef To) {
ErrorOr<SmallString<128>> PathToOrErr = canonicalizePath(To); ErrorOr<SmallString<128>> PathToOrErr = canonicalizePath(To);
ErrorOr<SmallString<128>> DirFromOrErr = canonicalizePath(From); ErrorOr<SmallString<128>> DirFromOrErr = canonicalizePath(From);
if (!PathToOrErr || !DirFromOrErr) if (!PathToOrErr || !DirFromOrErr)
return errorCodeToError(std::error_code(errno, std::generic_category())); return errorCodeToError(errnoAsErrorCode());
const SmallString<128> &PathTo = *PathToOrErr; const SmallString<128> &PathTo = *PathToOrErr;
const SmallString<128> &DirFrom = sys::path::parent_path(*DirFromOrErr); const SmallString<128> &DirFrom = sys::path::parent_path(*DirFromOrErr);

View File

@ -82,21 +82,21 @@ int enableAutoConversion(int FD) {
std::error_code llvm::disableAutoConversion(int FD) { std::error_code llvm::disableAutoConversion(int FD) {
if (::disableAutoConversion(FD) == -1) if (::disableAutoConversion(FD) == -1)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
return std::error_code(); return std::error_code();
} }
std::error_code llvm::enableAutoConversion(int FD) { std::error_code llvm::enableAutoConversion(int FD) {
if (::enableAutoConversion(FD) == -1) if (::enableAutoConversion(FD) == -1)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
return std::error_code(); return std::error_code();
} }
std::error_code llvm::restoreStdHandleAutoConversion(int FD) { std::error_code llvm::restoreStdHandleAutoConversion(int FD) {
if (::restoreStdHandleAutoConversion(FD) == -1) if (::restoreStdHandleAutoConversion(FD) == -1)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
return std::error_code(); return std::error_code();
} }
@ -111,7 +111,7 @@ std::error_code llvm::setFileTag(int FD, int CCSID, bool Text) {
Tag.ft_rsvflags = 0; Tag.ft_rsvflags = 0;
if (fcntl(FD, F_SETTAG, &Tag) == -1) if (fcntl(FD, F_SETTAG, &Tag) == -1)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
return std::error_code(); return std::error_code();
} }

View File

@ -87,7 +87,7 @@ static std::error_code getHostID(SmallVectorImpl<char> &HostID) {
struct timespec wait = {1, 0}; // 1 second. struct timespec wait = {1, 0}; // 1 second.
uuid_t uuid; uuid_t uuid;
if (gethostuuid(uuid, &wait) != 0) if (gethostuuid(uuid, &wait) != 0)
return std::error_code(errno, std::system_category()); return errnoAsErrorCode();
uuid_string_t UUIDStr; uuid_string_t UUIDStr;
uuid_unparse(uuid, UUIDStr); uuid_unparse(uuid, UUIDStr);

View File

@ -23,7 +23,6 @@
#include "llvm/Support/Process.h" #include "llvm/Support/Process.h"
#include "llvm/Support/Signals.h" #include "llvm/Support/Signals.h"
#include <cctype> #include <cctype>
#include <cerrno>
#if !defined(_MSC_VER) && !defined(__MINGW32__) #if !defined(_MSC_VER) && !defined(__MINGW32__)
#include <unistd.h> #include <unistd.h>
@ -1010,7 +1009,7 @@ static std::error_code copy_file_internal(int ReadFD, int WriteFD) {
delete[] Buf; delete[] Buf;
if (BytesRead < 0 || BytesWritten < 0) if (BytesRead < 0 || BytesWritten < 0)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
return std::error_code(); return std::error_code();
} }
@ -1060,7 +1059,7 @@ ErrorOr<MD5::MD5Result> md5_contents(int FD) {
} }
if (BytesRead < 0) if (BytesRead < 0)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
MD5::MD5Result Result; MD5::MD5Result Result;
Hash.final(Result); Hash.final(Result);
return Result; return Result;
@ -1228,7 +1227,7 @@ TempFile::~TempFile() { assert(Done); }
Error TempFile::discard() { Error TempFile::discard() {
Done = true; Done = true;
if (FD != -1 && close(FD) == -1) { if (FD != -1 && close(FD) == -1) {
std::error_code EC = std::error_code(errno, std::generic_category()); std::error_code EC = errnoAsErrorCode();
return errorCodeToError(EC); return errorCodeToError(EC);
} }
FD = -1; FD = -1;
@ -1297,10 +1296,8 @@ Error TempFile::keep(const Twine &Name) {
if (!RenameEC) if (!RenameEC)
TmpName = ""; TmpName = "";
if (close(FD) == -1) { if (close(FD) == -1)
std::error_code EC(errno, std::generic_category()); return errorCodeToError(errnoAsErrorCode());
return errorCodeToError(EC);
}
FD = -1; FD = -1;
return errorCodeToError(RenameEC); return errorCodeToError(RenameEC);
@ -1319,10 +1316,8 @@ Error TempFile::keep() {
TmpName = ""; TmpName = "";
if (close(FD) == -1) { if (close(FD) == -1)
std::error_code EC(errno, std::generic_category()); return errorCodeToError(errnoAsErrorCode());
return errorCodeToError(EC);
}
FD = -1; FD = -1;
return Error::success(); return Error::success();

View File

@ -18,6 +18,7 @@
#include "llvm/Support/CommandLine.h" #include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h" #include "llvm/Support/Debug.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/raw_ostream.h" #include "llvm/Support/raw_ostream.h"
#ifdef _WIN32 #ifdef _WIN32
#include "llvm/Support/Windows/WindowsSupport.h" #include "llvm/Support/Windows/WindowsSupport.h"
@ -81,14 +82,14 @@ std::error_code llvm::getRandomBytes(void *Buffer, size_t Size) {
std::error_code Ret; std::error_code Ret;
ssize_t BytesRead = read(Fd, Buffer, Size); ssize_t BytesRead = read(Fd, Buffer, Size);
if (BytesRead == -1) if (BytesRead == -1)
Ret = std::error_code(errno, std::system_category()); Ret = errnoAsErrorCode();
else if (BytesRead != static_cast<ssize_t>(Size)) else if (BytesRead != static_cast<ssize_t>(Size))
Ret = std::error_code(EIO, std::system_category()); Ret = std::error_code(EIO, std::system_category());
if (close(Fd) == -1) if (close(Fd) == -1)
Ret = std::error_code(errno, std::system_category()); Ret = errnoAsErrorCode();
return Ret; return Ret;
} }
return std::error_code(errno, std::system_category()); return errnoAsErrorCode();
#endif #endif
} }

View File

@ -86,7 +86,7 @@ MemoryBlock Memory::allocateMappedMemory(size_t NumBytes,
#else #else
fd = open("/dev/zero", O_RDWR); fd = open("/dev/zero", O_RDWR);
if (fd == -1) { if (fd == -1) {
EC = std::error_code(errno, std::generic_category()); EC = errnoAsErrorCode();
return MemoryBlock(); return MemoryBlock();
} }
#endif #endif
@ -122,7 +122,7 @@ MemoryBlock Memory::allocateMappedMemory(size_t NumBytes,
return allocateMappedMemory(NumBytes, nullptr, PFlags, EC); return allocateMappedMemory(NumBytes, nullptr, PFlags, EC);
} }
EC = std::error_code(errno, std::generic_category()); EC = errnoAsErrorCode();
#if !defined(MAP_ANON) #if !defined(MAP_ANON)
close(fd); close(fd);
#endif #endif
@ -153,7 +153,7 @@ std::error_code Memory::releaseMappedMemory(MemoryBlock &M) {
return std::error_code(); return std::error_code();
if (0 != ::munmap(M.Address, M.AllocatedSize)) if (0 != ::munmap(M.Address, M.AllocatedSize))
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
M.Address = nullptr; M.Address = nullptr;
M.AllocatedSize = 0; M.AllocatedSize = 0;
@ -186,7 +186,7 @@ std::error_code Memory::protectMappedMemory(const MemoryBlock &M,
if (InvalidateCache && !(Protect & PROT_READ)) { if (InvalidateCache && !(Protect & PROT_READ)) {
int Result = ::mprotect((void *)Start, End - Start, Protect | PROT_READ); int Result = ::mprotect((void *)Start, End - Start, Protect | PROT_READ);
if (Result != 0) if (Result != 0)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
Memory::InvalidateInstructionCache(M.Address, M.AllocatedSize); Memory::InvalidateInstructionCache(M.Address, M.AllocatedSize);
InvalidateCache = false; InvalidateCache = false;
@ -196,7 +196,7 @@ std::error_code Memory::protectMappedMemory(const MemoryBlock &M,
int Result = ::mprotect((void *)Start, End - Start, Protect); int Result = ::mprotect((void *)Start, End - Start, Protect);
if (Result != 0) if (Result != 0)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
if (InvalidateCache) if (InvalidateCache)
Memory::InvalidateInstructionCache(M.Address, M.AllocatedSize); Memory::InvalidateInstructionCache(M.Address, M.AllocatedSize);

View File

@ -357,7 +357,7 @@ uint32_t file_status::getLinkCount() const { return fs_st_nlinks; }
ErrorOr<space_info> disk_space(const Twine &Path) { ErrorOr<space_info> disk_space(const Twine &Path) {
struct STATVFS Vfs; struct STATVFS Vfs;
if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs)) if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
auto FrSize = STATVFS_F_FRSIZE(Vfs); auto FrSize = STATVFS_F_FRSIZE(Vfs);
space_info SpaceInfo; space_info SpaceInfo;
SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize; SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;
@ -386,7 +386,7 @@ std::error_code current_path(SmallVectorImpl<char> &result) {
// See if there was a real error. // See if there was a real error.
if (errno != ENOMEM) { if (errno != ENOMEM) {
result.clear(); result.clear();
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
} }
// Otherwise there just wasn't enough space. // Otherwise there just wasn't enough space.
result.resize_for_overwrite(result.capacity() * 2); result.resize_for_overwrite(result.capacity() * 2);
@ -403,7 +403,7 @@ std::error_code set_current_path(const Twine &path) {
StringRef p = path.toNullTerminatedStringRef(path_storage); StringRef p = path.toNullTerminatedStringRef(path_storage);
if (::chdir(p.begin()) == -1) if (::chdir(p.begin()) == -1)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
return std::error_code(); return std::error_code();
} }
@ -415,7 +415,7 @@ std::error_code create_directory(const Twine &path, bool IgnoreExisting,
if (::mkdir(p.begin(), Perms) == -1) { if (::mkdir(p.begin(), Perms) == -1) {
if (errno != EEXIST || !IgnoreExisting) if (errno != EEXIST || !IgnoreExisting)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
} }
return std::error_code(); return std::error_code();
@ -431,7 +431,7 @@ std::error_code create_link(const Twine &to, const Twine &from) {
StringRef t = to.toNullTerminatedStringRef(to_storage); StringRef t = to.toNullTerminatedStringRef(to_storage);
if (::symlink(t.begin(), f.begin()) == -1) if (::symlink(t.begin(), f.begin()) == -1)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
return std::error_code(); return std::error_code();
} }
@ -444,7 +444,7 @@ std::error_code create_hard_link(const Twine &to, const Twine &from) {
StringRef t = to.toNullTerminatedStringRef(to_storage); StringRef t = to.toNullTerminatedStringRef(to_storage);
if (::link(t.begin(), f.begin()) == -1) if (::link(t.begin(), f.begin()) == -1)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
return std::error_code(); return std::error_code();
} }
@ -456,7 +456,7 @@ std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
struct stat buf; struct stat buf;
if (lstat(p.begin(), &buf) != 0) { if (lstat(p.begin(), &buf) != 0) {
if (errno != ENOENT || !IgnoreNonExisting) if (errno != ENOENT || !IgnoreNonExisting)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
return std::error_code(); return std::error_code();
} }
@ -470,7 +470,7 @@ std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
if (::remove(p.begin()) == -1) { if (::remove(p.begin()) == -1) {
if (errno != ENOENT || !IgnoreNonExisting) if (errno != ENOENT || !IgnoreNonExisting)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
} }
return std::error_code(); return std::error_code();
@ -563,7 +563,7 @@ static bool is_local_impl(struct STATVFS &Vfs) {
std::error_code is_local(const Twine &Path, bool &Result) { std::error_code is_local(const Twine &Path, bool &Result) {
struct STATVFS Vfs; struct STATVFS Vfs;
if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs)) if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
Result = is_local_impl(Vfs); Result = is_local_impl(Vfs);
return std::error_code(); return std::error_code();
@ -572,7 +572,7 @@ std::error_code is_local(const Twine &Path, bool &Result) {
std::error_code is_local(int FD, bool &Result) { std::error_code is_local(int FD, bool &Result) {
struct STATVFS Vfs; struct STATVFS Vfs;
if (::FSTATVFS(FD, &Vfs)) if (::FSTATVFS(FD, &Vfs))
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
Result = is_local_impl(Vfs); Result = is_local_impl(Vfs);
return std::error_code(); return std::error_code();
@ -586,7 +586,7 @@ std::error_code rename(const Twine &from, const Twine &to) {
StringRef t = to.toNullTerminatedStringRef(to_storage); StringRef t = to.toNullTerminatedStringRef(to_storage);
if (::rename(f.begin(), t.begin()) == -1) if (::rename(f.begin(), t.begin()) == -1)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
return std::error_code(); return std::error_code();
} }
@ -595,7 +595,7 @@ std::error_code resize_file(int FD, uint64_t Size) {
// Use ftruncate as a fallback. It may or may not allocate space. At least on // Use ftruncate as a fallback. It may or may not allocate space. At least on
// OS X with HFS+ it does. // OS X with HFS+ it does.
if (::ftruncate(FD, Size) == -1) if (::ftruncate(FD, Size) == -1)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
return std::error_code(); return std::error_code();
} }
@ -617,7 +617,7 @@ std::error_code access(const Twine &Path, AccessMode Mode) {
StringRef P = Path.toNullTerminatedStringRef(PathStorage); StringRef P = Path.toNullTerminatedStringRef(PathStorage);
if (::access(P.begin(), convertAccessMode(Mode)) == -1) if (::access(P.begin(), convertAccessMode(Mode)) == -1)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
if (Mode == AccessMode::Execute) { if (Mode == AccessMode::Execute) {
// Don't say that directories are executable. // Don't say that directories are executable.
@ -726,7 +726,7 @@ static file_type typeForMode(mode_t Mode) {
static std::error_code fillStatus(int StatRet, const struct stat &Status, static std::error_code fillStatus(int StatRet, const struct stat &Status,
file_status &Result) { file_status &Result) {
if (StatRet != 0) { if (StatRet != 0) {
std::error_code EC(errno, std::generic_category()); std::error_code EC = errnoAsErrorCode();
if (EC == errc::no_such_file_or_directory) if (EC == errc::no_such_file_or_directory)
Result = file_status(file_type::file_not_found); Result = file_status(file_type::file_not_found);
else else
@ -782,13 +782,13 @@ std::error_code setPermissions(const Twine &Path, perms Permissions) {
StringRef P = Path.toNullTerminatedStringRef(PathStorage); StringRef P = Path.toNullTerminatedStringRef(PathStorage);
if (::chmod(P.begin(), Permissions)) if (::chmod(P.begin(), Permissions))
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
return std::error_code(); return std::error_code();
} }
std::error_code setPermissions(int FD, perms Permissions) { std::error_code setPermissions(int FD, perms Permissions) {
if (::fchmod(FD, Permissions)) if (::fchmod(FD, Permissions))
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
return std::error_code(); return std::error_code();
} }
@ -799,7 +799,7 @@ std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
Times[0] = sys::toTimeSpec(AccessTime); Times[0] = sys::toTimeSpec(AccessTime);
Times[1] = sys::toTimeSpec(ModificationTime); Times[1] = sys::toTimeSpec(ModificationTime);
if (::futimens(FD, Times)) if (::futimens(FD, Times))
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
return std::error_code(); return std::error_code();
#elif defined(HAVE_FUTIMES) #elif defined(HAVE_FUTIMES)
timeval Times[2]; timeval Times[2];
@ -809,7 +809,7 @@ std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
sys::toTimeVal(std::chrono::time_point_cast<std::chrono::microseconds>( sys::toTimeVal(std::chrono::time_point_cast<std::chrono::microseconds>(
ModificationTime)); ModificationTime));
if (::futimes(FD, Times)) if (::futimes(FD, Times))
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
return std::error_code(); return std::error_code();
#elif defined(__MVS__) #elif defined(__MVS__)
attrib_t Attr; attrib_t Attr;
@ -819,7 +819,7 @@ std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
Attr.att_mtimechg = 1; Attr.att_mtimechg = 1;
Attr.att_mtime = sys::toTimeT(ModificationTime); Attr.att_mtime = sys::toTimeT(ModificationTime);
if (::__fchattr(FD, &Attr, sizeof(Attr)) != 0) if (::__fchattr(FD, &Attr, sizeof(Attr)) != 0)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
return std::error_code(); return std::error_code();
#else #else
#warning Missing futimes() and futimens() #warning Missing futimes() and futimens()
@ -858,7 +858,7 @@ std::error_code mapped_file_region::init(int FD, uint64_t Offset,
Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset); Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
if (Mapping == MAP_FAILED) if (Mapping == MAP_FAILED)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
return std::error_code(); return std::error_code();
} }
@ -897,7 +897,7 @@ std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
SmallString<128> path_null(path); SmallString<128> path_null(path);
DIR *directory = ::opendir(path_null.c_str()); DIR *directory = ::opendir(path_null.c_str());
if (!directory) if (!directory)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
it.IterationHandle = reinterpret_cast<intptr_t>(directory); it.IterationHandle = reinterpret_cast<intptr_t>(directory);
// Add something for replace_filename to replace. // Add something for replace_filename to replace.
@ -932,7 +932,7 @@ std::error_code detail::directory_iterator_increment(detail::DirIterState &It) {
errno = 0; errno = 0;
dirent *CurDir = ::readdir(reinterpret_cast<DIR *>(It.IterationHandle)); dirent *CurDir = ::readdir(reinterpret_cast<DIR *>(It.IterationHandle));
if (CurDir == nullptr && errno != 0) { if (CurDir == nullptr && errno != 0) {
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
} else if (CurDir != nullptr) { } else if (CurDir != nullptr) {
StringRef Name(CurDir->d_name); StringRef Name(CurDir->d_name);
if ((Name.size() == 1 && Name[0] == '.') || if ((Name.size() == 1 && Name[0] == '.') ||
@ -1023,7 +1023,7 @@ std::error_code openFile(const Twine &Name, int &ResultFD,
// when open is overloaded, such as in Bionic. // when open is overloaded, such as in Bionic.
auto Open = [&]() { return ::open(P.begin(), OpenFlags, Mode); }; auto Open = [&]() { return ::open(P.begin(), OpenFlags, Mode); };
if ((ResultFD = sys::RetryAfterSignal(-1, Open)) < 0) if ((ResultFD = sys::RetryAfterSignal(-1, Open)) < 0)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
#ifndef O_CLOEXEC #ifndef O_CLOEXEC
if (!(Flags & OF_ChildInherit)) { if (!(Flags & OF_ChildInherit)) {
int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC); int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
@ -1087,10 +1087,10 @@ std::error_code openFile(const Twine &Name, int &ResultFD,
* open(). * open().
*/ */
if ((Flags & OF_Append) && lseek(ResultFD, 0, SEEK_END) == -1) if ((Flags & OF_Append) && lseek(ResultFD, 0, SEEK_END) == -1)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
struct stat Stat; struct stat Stat;
if (fstat(ResultFD, &Stat) == -1) if (fstat(ResultFD, &Stat) == -1)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
if (S_ISREG(Stat.st_mode)) { if (S_ISREG(Stat.st_mode)) {
bool DoSetTag = (Access & FA_Write) && (Disp != CD_OpenExisting) && bool DoSetTag = (Access & FA_Write) && (Disp != CD_OpenExisting) &&
!Stat.st_tag.ft_txtflag && !Stat.st_tag.ft_ccsid && !Stat.st_tag.ft_txtflag && !Stat.st_tag.ft_ccsid &&
@ -1190,7 +1190,7 @@ Expected<size_t> readNativeFile(file_t FD, MutableArrayRef<char> Buf) {
#endif #endif
ssize_t NumRead = sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Size); ssize_t NumRead = sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Size);
if (ssize_t(NumRead) == -1) if (ssize_t(NumRead) == -1)
return errorCodeToError(std::error_code(errno, std::generic_category())); return errorCodeToError(errnoAsErrorCode());
return NumRead; return NumRead;
} }
@ -1206,11 +1206,11 @@ Expected<size_t> readNativeFileSlice(file_t FD, MutableArrayRef<char> Buf,
sys::RetryAfterSignal(-1, ::pread, FD, Buf.data(), Size, Offset); sys::RetryAfterSignal(-1, ::pread, FD, Buf.data(), Size, Offset);
#else #else
if (lseek(FD, Offset, SEEK_SET) == -1) if (lseek(FD, Offset, SEEK_SET) == -1)
return errorCodeToError(std::error_code(errno, std::generic_category())); return errorCodeToError(errnoAsErrorCode());
ssize_t NumRead = sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Size); ssize_t NumRead = sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Size);
#endif #endif
if (NumRead == -1) if (NumRead == -1)
return errorCodeToError(std::error_code(errno, std::generic_category())); return errorCodeToError(errnoAsErrorCode());
return NumRead; return NumRead;
} }
@ -1243,8 +1243,7 @@ std::error_code lockFile(int FD) {
Lock.l_len = 0; Lock.l_len = 0;
if (::fcntl(FD, F_SETLKW, &Lock) != -1) if (::fcntl(FD, F_SETLKW, &Lock) != -1)
return std::error_code(); return std::error_code();
int Error = errno; return errnoAsErrorCode();
return std::error_code(Error, std::generic_category());
} }
std::error_code unlockFile(int FD) { std::error_code unlockFile(int FD) {
@ -1255,7 +1254,7 @@ std::error_code unlockFile(int FD) {
Lock.l_len = 0; Lock.l_len = 0;
if (::fcntl(FD, F_SETLK, &Lock) != -1) if (::fcntl(FD, F_SETLK, &Lock) != -1)
return std::error_code(); return std::error_code();
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
} }
std::error_code closeFile(file_t &F) { std::error_code closeFile(file_t &F) {
@ -1321,7 +1320,7 @@ std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
StringRef P = path.toNullTerminatedStringRef(Storage); StringRef P = path.toNullTerminatedStringRef(Storage);
char Buffer[PATH_MAX]; char Buffer[PATH_MAX];
if (::realpath(P.begin(), Buffer) == nullptr) if (::realpath(P.begin(), Buffer) == nullptr)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
dest.append(Buffer, Buffer + strlen(Buffer)); dest.append(Buffer, Buffer + strlen(Buffer));
return std::error_code(); return std::error_code();
} }
@ -1330,7 +1329,7 @@ std::error_code changeFileOwnership(int FD, uint32_t Owner, uint32_t Group) {
auto FChown = [&]() { return ::fchown(FD, Owner, Group); }; auto FChown = [&]() { return ::fchown(FD, Owner, Group); };
// Retry if fchown call fails due to interruption. // Retry if fchown call fails due to interruption.
if ((sys::RetryAfterSignal(-1, FChown)) < 0) if ((sys::RetryAfterSignal(-1, FChown)) < 0)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
return std::error_code(); return std::error_code();
} }
@ -1513,7 +1512,7 @@ std::error_code copy_file(const Twine &From, const Twine &To) {
#endif #endif
if (!copyfile(FromS.c_str(), ToS.c_str(), /*State=*/NULL, COPYFILE_DATA)) if (!copyfile(FromS.c_str(), ToS.c_str(), /*State=*/NULL, COPYFILE_DATA))
return std::error_code(); return std::error_code();
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
} }
#endif // __APPLE__ #endif // __APPLE__

View File

@ -86,7 +86,7 @@ Expected<unsigned> Process::getPageSize() {
#error Cannot get the page size on this machine #error Cannot get the page size on this machine
#endif #endif
if (page_size == -1) if (page_size == -1)
return errorCodeToError(std::error_code(errno, std::generic_category())); return errorCodeToError(errnoAsErrorCode());
return static_cast<unsigned>(page_size); return static_cast<unsigned>(page_size);
} }
@ -235,7 +235,7 @@ std::error_code Process::FixupStandardFileDescriptors() {
assert(errno && "expected errno to be set if fstat failed!"); assert(errno && "expected errno to be set if fstat failed!");
// fstat should return EBADF if the file descriptor is closed. // fstat should return EBADF if the file descriptor is closed.
if (errno != EBADF) if (errno != EBADF)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
} }
// if fstat succeeds, move on to the next FD. // if fstat succeeds, move on to the next FD.
if (!errno) if (!errno)
@ -247,13 +247,13 @@ std::error_code Process::FixupStandardFileDescriptors() {
// RetryAfterSignal when open is overloaded, such as in Bionic. // RetryAfterSignal when open is overloaded, such as in Bionic.
auto Open = [&]() { return ::open("/dev/null", O_RDWR); }; auto Open = [&]() { return ::open("/dev/null", O_RDWR); };
if ((NullFD = RetryAfterSignal(-1, Open)) < 0) if ((NullFD = RetryAfterSignal(-1, Open)) < 0)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
} }
if (NullFD == StandardFD) if (NullFD == StandardFD)
FDC.keepOpen(); FDC.keepOpen();
else if (dup2(NullFD, StandardFD) < 0) else if (dup2(NullFD, StandardFD) < 0)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
} }
return std::error_code(); return std::error_code();
} }
@ -262,7 +262,7 @@ std::error_code Process::SafelyCloseFileDescriptor(int FD) {
// Create a signal set filled with *all* signals. // Create a signal set filled with *all* signals.
sigset_t FullSet, SavedSet; sigset_t FullSet, SavedSet;
if (sigfillset(&FullSet) < 0 || sigfillset(&SavedSet) < 0) if (sigfillset(&FullSet) < 0 || sigfillset(&SavedSet) < 0)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
// Atomically swap our current signal mask with a full mask. // Atomically swap our current signal mask with a full mask.
#if LLVM_ENABLE_THREADS #if LLVM_ENABLE_THREADS
@ -270,7 +270,7 @@ std::error_code Process::SafelyCloseFileDescriptor(int FD) {
return std::error_code(EC, std::generic_category()); return std::error_code(EC, std::generic_category());
#else #else
if (sigprocmask(SIG_SETMASK, &FullSet, &SavedSet) < 0) if (sigprocmask(SIG_SETMASK, &FullSet, &SavedSet) < 0)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
#endif #endif
// Attempt to close the file descriptor. // Attempt to close the file descriptor.
// We need to save the error, if one occurs, because our subsequent call to // We need to save the error, if one occurs, because our subsequent call to

View File

@ -276,7 +276,7 @@ std::error_code Process::FixupStandardFileDescriptors() {
std::error_code Process::SafelyCloseFileDescriptor(int FD) { std::error_code Process::SafelyCloseFileDescriptor(int FD) {
if (::close(FD) < 0) if (::close(FD) < 0)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
return std::error_code(); return std::error_code();
} }

View File

@ -506,14 +506,14 @@ std::error_code llvm::sys::ChangeStdoutMode(sys::fs::OpenFlags Flags) {
std::error_code sys::ChangeStdinToBinary() { std::error_code sys::ChangeStdinToBinary() {
int result = _setmode(_fileno(stdin), _O_BINARY); int result = _setmode(_fileno(stdin), _O_BINARY);
if (result == -1) if (result == -1)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
return std::error_code(); return std::error_code();
} }
std::error_code sys::ChangeStdoutToBinary() { std::error_code sys::ChangeStdoutToBinary() {
int result = _setmode(_fileno(stdout), _O_BINARY); int result = _setmode(_fileno(stdout), _O_BINARY);
if (result == -1) if (result == -1)
return std::error_code(errno, std::generic_category()); return errnoAsErrorCode();
return std::error_code(); return std::error_code();
} }

View File

@ -794,7 +794,7 @@ void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
} }
#endif #endif
// Otherwise it's a non-recoverable error. Note it and quit. // Otherwise it's a non-recoverable error. Note it and quit.
error_detected(std::error_code(errno, std::generic_category())); error_detected(errnoAsErrorCode());
break; break;
} }
@ -824,7 +824,7 @@ uint64_t raw_fd_ostream::seek(uint64_t off) {
pos = ::lseek(FD, off, SEEK_SET); pos = ::lseek(FD, off, SEEK_SET);
#endif #endif
if (pos == (uint64_t)-1) if (pos == (uint64_t)-1)
error_detected(std::error_code(errno, std::generic_category())); error_detected(errnoAsErrorCode());
return pos; return pos;
} }
@ -946,7 +946,7 @@ ssize_t raw_fd_stream::read(char *Ptr, size_t Size) {
if (Ret >= 0) if (Ret >= 0)
inc_pos(Ret); inc_pos(Ret);
else else
error_detected(std::error_code(errno, std::generic_category())); error_detected(errnoAsErrorCode());
return Ret; return Ret;
} }

View File

@ -52,7 +52,7 @@ static std::error_code getLastSocketErrorCode() {
#ifdef _WIN32 #ifdef _WIN32
return std::error_code(::WSAGetLastError(), std::system_category()); return std::error_code(::WSAGetLastError(), std::system_category());
#else #else
return std::error_code(errno, std::system_category()); return errnoAsErrorCode();
#endif #endif
} }