Skip to content

Commit ba13fa2

Browse files
authored
[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.
1 parent abbf1f1 commit ba13fa2

File tree

17 files changed

+94
-93
lines changed

17 files changed

+94
-93
lines changed

clang-tools-extra/clangd/JSONTransport.cpp

+1-2
Original file line numberDiff line numberDiff line change
@@ -107,8 +107,7 @@ class JSONTransport : public Transport {
107107
return error(std::make_error_code(std::errc::operation_canceled),
108108
"Got signal, shutting down");
109109
if (ferror(In))
110-
return llvm::errorCodeToError(
111-
std::error_code(errno, std::system_category()));
110+
return llvm::errorCodeToError(llvm::errnoAsErrorCode());
112111
if (readRawMessage(JSON)) {
113112
ThreadCrashReporter ScopedReporter([&JSON]() {
114113
auto &OS = llvm::errs();

clang/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp

+3-6
Original file line numberDiff line numberDiff line change
@@ -333,8 +333,7 @@ llvm::Expected<std::unique_ptr<DirectoryWatcher>> clang::DirectoryWatcher::creat
333333
const int InotifyFD = inotify_init1(IN_CLOEXEC);
334334
if (InotifyFD == -1)
335335
return llvm::make_error<llvm::StringError>(
336-
std::string("inotify_init1() error: ") + strerror(errno),
337-
llvm::inconvertibleErrorCode());
336+
llvm::errnoAsErrorCode(), std::string(": inotify_init1()"));
338337

339338
const int InotifyWD = inotify_add_watch(
340339
InotifyFD, Path.str().c_str(),
@@ -346,15 +345,13 @@ llvm::Expected<std::unique_ptr<DirectoryWatcher>> clang::DirectoryWatcher::creat
346345
);
347346
if (InotifyWD == -1)
348347
return llvm::make_error<llvm::StringError>(
349-
std::string("inotify_add_watch() error: ") + strerror(errno),
350-
llvm::inconvertibleErrorCode());
348+
llvm::errnoAsErrorCode(), std::string(": inotify_add_watch()"));
351349

352350
auto InotifyPollingStopper = SemaphorePipe::create();
353351

354352
if (!InotifyPollingStopper)
355353
return llvm::make_error<llvm::StringError>(
356-
std::string("SemaphorePipe::create() error: ") + strerror(errno),
357-
llvm::inconvertibleErrorCode());
354+
llvm::errnoAsErrorCode(), std::string(": SemaphorePipe::create()"));
358355

359356
return std::make_unique<DirectoryWatcherLinux>(
360357
Path, Receiver, WaitForInitialSync, InotifyFD, InotifyWD,

llvm/include/llvm/Support/Error.h

+14
Original file line numberDiff line numberDiff line change
@@ -1180,6 +1180,20 @@ Error errorCodeToError(std::error_code EC);
11801180
/// will trigger a call to abort().
11811181
std::error_code errorToErrorCode(Error Err);
11821182

1183+
/// Helper to get errno as an std::error_code.
1184+
///
1185+
/// errno should always be represented using the generic category as that's what
1186+
/// both libc++ and libstdc++ do. On POSIX systems you can also represent them
1187+
/// using the system category, however this makes them compare differently for
1188+
/// values outside of those used by `std::errc` if one is generic and the other
1189+
/// is system.
1190+
///
1191+
/// See the libc++ and libstdc++ implementations of `default_error_condition` on
1192+
/// the system category for more details on what the difference is.
1193+
inline std::error_code errnoAsErrorCode() {
1194+
return std::error_code(errno, std::generic_category());
1195+
}
1196+
11831197
/// Convert an ErrorOr<T> to an Expected<T>.
11841198
template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
11851199
if (auto EC = EO.getError())

llvm/lib/ExecutionEngine/Orc/MemoryMapper.cpp

+3-6
Original file line numberDiff line numberDiff line change
@@ -241,8 +241,7 @@ void SharedMemoryMapper::reserve(size_t NumBytes,
241241

242242
int SharedMemoryFile = shm_open(SharedMemoryName.c_str(), O_RDWR, 0700);
243243
if (SharedMemoryFile < 0) {
244-
return OnReserved(errorCodeToError(
245-
std::error_code(errno, std::generic_category())));
244+
return OnReserved(errorCodeToError(errnoAsErrorCode()));
246245
}
247246

248247
// this prevents other processes from accessing it by name
@@ -251,8 +250,7 @@ void SharedMemoryMapper::reserve(size_t NumBytes,
251250
LocalAddr = mmap(nullptr, NumBytes, PROT_READ | PROT_WRITE, MAP_SHARED,
252251
SharedMemoryFile, 0);
253252
if (LocalAddr == MAP_FAILED) {
254-
return OnReserved(errorCodeToError(
255-
std::error_code(errno, std::generic_category())));
253+
return OnReserved(errorCodeToError(errnoAsErrorCode()));
256254
}
257255

258256
close(SharedMemoryFile);
@@ -376,8 +374,7 @@ void SharedMemoryMapper::release(ArrayRef<ExecutorAddr> Bases,
376374
#if defined(LLVM_ON_UNIX)
377375

378376
if (munmap(Reservations[Base].LocalAddr, Reservations[Base].Size) != 0)
379-
Err = joinErrors(std::move(Err), errorCodeToError(std::error_code(
380-
errno, std::generic_category())));
377+
Err = joinErrors(std::move(Err), errorCodeToError(errnoAsErrorCode()));
381378

382379
#elif defined(_WIN32)
383380

llvm/lib/ExecutionEngine/Orc/TargetProcess/ExecutorSharedMemoryMapperService.cpp

+5-6
Original file line numberDiff line numberDiff line change
@@ -62,15 +62,15 @@ ExecutorSharedMemoryMapperService::reserve(uint64_t Size) {
6262
int SharedMemoryFile =
6363
shm_open(SharedMemoryName.c_str(), O_RDWR | O_CREAT | O_EXCL, 0700);
6464
if (SharedMemoryFile < 0)
65-
return errorCodeToError(std::error_code(errno, std::generic_category()));
65+
return errorCodeToError(errnoAsErrorCode());
6666

6767
// by default size is 0
6868
if (ftruncate(SharedMemoryFile, Size) < 0)
69-
return errorCodeToError(std::error_code(errno, std::generic_category()));
69+
return errorCodeToError(errnoAsErrorCode());
7070

7171
void *Addr = mmap(nullptr, Size, PROT_NONE, MAP_SHARED, SharedMemoryFile, 0);
7272
if (Addr == MAP_FAILED)
73-
return errorCodeToError(std::error_code(errno, std::generic_category()));
73+
return errorCodeToError(errnoAsErrorCode());
7474

7575
close(SharedMemoryFile);
7676

@@ -140,7 +140,7 @@ Expected<ExecutorAddr> ExecutorSharedMemoryMapperService::initialize(
140140
NativeProt |= PROT_EXEC;
141141

142142
if (mprotect(Segment.Addr.toPtr<void *>(), Segment.Size, NativeProt))
143-
return errorCodeToError(std::error_code(errno, std::generic_category()));
143+
return errorCodeToError(errnoAsErrorCode());
144144

145145
#elif defined(_WIN32)
146146

@@ -240,8 +240,7 @@ Error ExecutorSharedMemoryMapperService::release(
240240
#if defined(LLVM_ON_UNIX)
241241

242242
if (munmap(Base.toPtr<void *>(), Size) != 0)
243-
Err = joinErrors(std::move(Err), errorCodeToError(std::error_code(
244-
errno, std::generic_category())));
243+
Err = joinErrors(std::move(Err), errorCodeToError(errnoAsErrorCode()));
245244

246245
#elif defined(_WIN32)
247246
(void)Size;

llvm/lib/Object/ArchiveWriter.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -926,7 +926,7 @@ Expected<std::string> computeArchiveRelativePath(StringRef From, StringRef To) {
926926
ErrorOr<SmallString<128>> PathToOrErr = canonicalizePath(To);
927927
ErrorOr<SmallString<128>> DirFromOrErr = canonicalizePath(From);
928928
if (!PathToOrErr || !DirFromOrErr)
929-
return errorCodeToError(std::error_code(errno, std::generic_category()));
929+
return errorCodeToError(errnoAsErrorCode());
930930

931931
const SmallString<128> &PathTo = *PathToOrErr;
932932
const SmallString<128> &DirFrom = sys::path::parent_path(*DirFromOrErr);

llvm/lib/Support/AutoConvert.cpp

+4-4
Original file line numberDiff line numberDiff line change
@@ -82,21 +82,21 @@ int enableAutoConversion(int FD) {
8282

8383
std::error_code llvm::disableAutoConversion(int FD) {
8484
if (::disableAutoConversion(FD) == -1)
85-
return std::error_code(errno, std::generic_category());
85+
return errnoAsErrorCode();
8686

8787
return std::error_code();
8888
}
8989

9090
std::error_code llvm::enableAutoConversion(int FD) {
9191
if (::enableAutoConversion(FD) == -1)
92-
return std::error_code(errno, std::generic_category());
92+
return errnoAsErrorCode();
9393

9494
return std::error_code();
9595
}
9696

9797
std::error_code llvm::restoreStdHandleAutoConversion(int FD) {
9898
if (::restoreStdHandleAutoConversion(FD) == -1)
99-
return std::error_code(errno, std::generic_category());
99+
return errnoAsErrorCode();
100100

101101
return std::error_code();
102102
}
@@ -111,7 +111,7 @@ std::error_code llvm::setFileTag(int FD, int CCSID, bool Text) {
111111
Tag.ft_rsvflags = 0;
112112

113113
if (fcntl(FD, F_SETTAG, &Tag) == -1)
114-
return std::error_code(errno, std::generic_category());
114+
return errnoAsErrorCode();
115115
return std::error_code();
116116
}
117117

llvm/lib/Support/LockFileManager.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ static std::error_code getHostID(SmallVectorImpl<char> &HostID) {
8787
struct timespec wait = {1, 0}; // 1 second.
8888
uuid_t uuid;
8989
if (gethostuuid(uuid, &wait) != 0)
90-
return std::error_code(errno, std::system_category());
90+
return errnoAsErrorCode();
9191

9292
uuid_string_t UUIDStr;
9393
uuid_unparse(uuid, UUIDStr);

llvm/lib/Support/Path.cpp

+7-12
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323
#include "llvm/Support/Process.h"
2424
#include "llvm/Support/Signals.h"
2525
#include <cctype>
26-
#include <cerrno>
2726

2827
#if !defined(_MSC_VER) && !defined(__MINGW32__)
2928
#include <unistd.h>
@@ -1010,7 +1009,7 @@ static std::error_code copy_file_internal(int ReadFD, int WriteFD) {
10101009
delete[] Buf;
10111010

10121011
if (BytesRead < 0 || BytesWritten < 0)
1013-
return std::error_code(errno, std::generic_category());
1012+
return errnoAsErrorCode();
10141013
return std::error_code();
10151014
}
10161015

@@ -1060,7 +1059,7 @@ ErrorOr<MD5::MD5Result> md5_contents(int FD) {
10601059
}
10611060

10621061
if (BytesRead < 0)
1063-
return std::error_code(errno, std::generic_category());
1062+
return errnoAsErrorCode();
10641063
MD5::MD5Result Result;
10651064
Hash.final(Result);
10661065
return Result;
@@ -1228,7 +1227,7 @@ TempFile::~TempFile() { assert(Done); }
12281227
Error TempFile::discard() {
12291228
Done = true;
12301229
if (FD != -1 && close(FD) == -1) {
1231-
std::error_code EC = std::error_code(errno, std::generic_category());
1230+
std::error_code EC = errnoAsErrorCode();
12321231
return errorCodeToError(EC);
12331232
}
12341233
FD = -1;
@@ -1297,10 +1296,8 @@ Error TempFile::keep(const Twine &Name) {
12971296
if (!RenameEC)
12981297
TmpName = "";
12991298

1300-
if (close(FD) == -1) {
1301-
std::error_code EC(errno, std::generic_category());
1302-
return errorCodeToError(EC);
1303-
}
1299+
if (close(FD) == -1)
1300+
return errorCodeToError(errnoAsErrorCode());
13041301
FD = -1;
13051302

13061303
return errorCodeToError(RenameEC);
@@ -1319,10 +1316,8 @@ Error TempFile::keep() {
13191316

13201317
TmpName = "";
13211318

1322-
if (close(FD) == -1) {
1323-
std::error_code EC(errno, std::generic_category());
1324-
return errorCodeToError(EC);
1325-
}
1319+
if (close(FD) == -1)
1320+
return errorCodeToError(errnoAsErrorCode());
13261321
FD = -1;
13271322

13281323
return Error::success();

llvm/lib/Support/RandomNumberGenerator.cpp

+4-3
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
#include "llvm/Support/CommandLine.h"
2020
#include "llvm/Support/Debug.h"
21+
#include "llvm/Support/Error.h"
2122
#include "llvm/Support/raw_ostream.h"
2223
#ifdef _WIN32
2324
#include "llvm/Support/Windows/WindowsSupport.h"
@@ -81,14 +82,14 @@ std::error_code llvm::getRandomBytes(void *Buffer, size_t Size) {
8182
std::error_code Ret;
8283
ssize_t BytesRead = read(Fd, Buffer, Size);
8384
if (BytesRead == -1)
84-
Ret = std::error_code(errno, std::system_category());
85+
Ret = errnoAsErrorCode();
8586
else if (BytesRead != static_cast<ssize_t>(Size))
8687
Ret = std::error_code(EIO, std::system_category());
8788
if (close(Fd) == -1)
88-
Ret = std::error_code(errno, std::system_category());
89+
Ret = errnoAsErrorCode();
8990

9091
return Ret;
9192
}
92-
return std::error_code(errno, std::system_category());
93+
return errnoAsErrorCode();
9394
#endif
9495
}

llvm/lib/Support/Unix/Memory.inc

+5-5
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ MemoryBlock Memory::allocateMappedMemory(size_t NumBytes,
8686
#else
8787
fd = open("/dev/zero", O_RDWR);
8888
if (fd == -1) {
89-
EC = std::error_code(errno, std::generic_category());
89+
EC = errnoAsErrorCode();
9090
return MemoryBlock();
9191
}
9292
#endif
@@ -122,7 +122,7 @@ MemoryBlock Memory::allocateMappedMemory(size_t NumBytes,
122122
return allocateMappedMemory(NumBytes, nullptr, PFlags, EC);
123123
}
124124

125-
EC = std::error_code(errno, std::generic_category());
125+
EC = errnoAsErrorCode();
126126
#if !defined(MAP_ANON)
127127
close(fd);
128128
#endif
@@ -153,7 +153,7 @@ std::error_code Memory::releaseMappedMemory(MemoryBlock &M) {
153153
return std::error_code();
154154

155155
if (0 != ::munmap(M.Address, M.AllocatedSize))
156-
return std::error_code(errno, std::generic_category());
156+
return errnoAsErrorCode();
157157

158158
M.Address = nullptr;
159159
M.AllocatedSize = 0;
@@ -186,7 +186,7 @@ std::error_code Memory::protectMappedMemory(const MemoryBlock &M,
186186
if (InvalidateCache && !(Protect & PROT_READ)) {
187187
int Result = ::mprotect((void *)Start, End - Start, Protect | PROT_READ);
188188
if (Result != 0)
189-
return std::error_code(errno, std::generic_category());
189+
return errnoAsErrorCode();
190190

191191
Memory::InvalidateInstructionCache(M.Address, M.AllocatedSize);
192192
InvalidateCache = false;
@@ -196,7 +196,7 @@ std::error_code Memory::protectMappedMemory(const MemoryBlock &M,
196196
int Result = ::mprotect((void *)Start, End - Start, Protect);
197197

198198
if (Result != 0)
199-
return std::error_code(errno, std::generic_category());
199+
return errnoAsErrorCode();
200200

201201
if (InvalidateCache)
202202
Memory::InvalidateInstructionCache(M.Address, M.AllocatedSize);

0 commit comments

Comments
 (0)