Skip to content

Commit ba13fa2

Browse files
authoredMar 9, 2024··
[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);

‎llvm/lib/Support/Unix/Path.inc

+33-34
Original file line numberDiff line numberDiff line change
@@ -357,7 +357,7 @@ uint32_t file_status::getLinkCount() const { return fs_st_nlinks; }
357357
ErrorOr<space_info> disk_space(const Twine &Path) {
358358
struct STATVFS Vfs;
359359
if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))
360-
return std::error_code(errno, std::generic_category());
360+
return errnoAsErrorCode();
361361
auto FrSize = STATVFS_F_FRSIZE(Vfs);
362362
space_info SpaceInfo;
363363
SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;
@@ -386,7 +386,7 @@ std::error_code current_path(SmallVectorImpl<char> &result) {
386386
// See if there was a real error.
387387
if (errno != ENOMEM) {
388388
result.clear();
389-
return std::error_code(errno, std::generic_category());
389+
return errnoAsErrorCode();
390390
}
391391
// Otherwise there just wasn't enough space.
392392
result.resize_for_overwrite(result.capacity() * 2);
@@ -403,7 +403,7 @@ std::error_code set_current_path(const Twine &path) {
403403
StringRef p = path.toNullTerminatedStringRef(path_storage);
404404

405405
if (::chdir(p.begin()) == -1)
406-
return std::error_code(errno, std::generic_category());
406+
return errnoAsErrorCode();
407407

408408
return std::error_code();
409409
}
@@ -415,7 +415,7 @@ std::error_code create_directory(const Twine &path, bool IgnoreExisting,
415415

416416
if (::mkdir(p.begin(), Perms) == -1) {
417417
if (errno != EEXIST || !IgnoreExisting)
418-
return std::error_code(errno, std::generic_category());
418+
return errnoAsErrorCode();
419419
}
420420

421421
return std::error_code();
@@ -431,7 +431,7 @@ std::error_code create_link(const Twine &to, const Twine &from) {
431431
StringRef t = to.toNullTerminatedStringRef(to_storage);
432432

433433
if (::symlink(t.begin(), f.begin()) == -1)
434-
return std::error_code(errno, std::generic_category());
434+
return errnoAsErrorCode();
435435

436436
return std::error_code();
437437
}
@@ -444,7 +444,7 @@ std::error_code create_hard_link(const Twine &to, const Twine &from) {
444444
StringRef t = to.toNullTerminatedStringRef(to_storage);
445445

446446
if (::link(t.begin(), f.begin()) == -1)
447-
return std::error_code(errno, std::generic_category());
447+
return errnoAsErrorCode();
448448

449449
return std::error_code();
450450
}
@@ -456,7 +456,7 @@ std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
456456
struct stat buf;
457457
if (lstat(p.begin(), &buf) != 0) {
458458
if (errno != ENOENT || !IgnoreNonExisting)
459-
return std::error_code(errno, std::generic_category());
459+
return errnoAsErrorCode();
460460
return std::error_code();
461461
}
462462

@@ -470,7 +470,7 @@ std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
470470

471471
if (::remove(p.begin()) == -1) {
472472
if (errno != ENOENT || !IgnoreNonExisting)
473-
return std::error_code(errno, std::generic_category());
473+
return errnoAsErrorCode();
474474
}
475475

476476
return std::error_code();
@@ -563,7 +563,7 @@ static bool is_local_impl(struct STATVFS &Vfs) {
563563
std::error_code is_local(const Twine &Path, bool &Result) {
564564
struct STATVFS Vfs;
565565
if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))
566-
return std::error_code(errno, std::generic_category());
566+
return errnoAsErrorCode();
567567

568568
Result = is_local_impl(Vfs);
569569
return std::error_code();
@@ -572,7 +572,7 @@ std::error_code is_local(const Twine &Path, bool &Result) {
572572
std::error_code is_local(int FD, bool &Result) {
573573
struct STATVFS Vfs;
574574
if (::FSTATVFS(FD, &Vfs))
575-
return std::error_code(errno, std::generic_category());
575+
return errnoAsErrorCode();
576576

577577
Result = is_local_impl(Vfs);
578578
return std::error_code();
@@ -586,7 +586,7 @@ std::error_code rename(const Twine &from, const Twine &to) {
586586
StringRef t = to.toNullTerminatedStringRef(to_storage);
587587

588588
if (::rename(f.begin(), t.begin()) == -1)
589-
return std::error_code(errno, std::generic_category());
589+
return errnoAsErrorCode();
590590

591591
return std::error_code();
592592
}
@@ -595,7 +595,7 @@ std::error_code resize_file(int FD, uint64_t Size) {
595595
// Use ftruncate as a fallback. It may or may not allocate space. At least on
596596
// OS X with HFS+ it does.
597597
if (::ftruncate(FD, Size) == -1)
598-
return std::error_code(errno, std::generic_category());
598+
return errnoAsErrorCode();
599599

600600
return std::error_code();
601601
}
@@ -617,7 +617,7 @@ std::error_code access(const Twine &Path, AccessMode Mode) {
617617
StringRef P = Path.toNullTerminatedStringRef(PathStorage);
618618

619619
if (::access(P.begin(), convertAccessMode(Mode)) == -1)
620-
return std::error_code(errno, std::generic_category());
620+
return errnoAsErrorCode();
621621

622622
if (Mode == AccessMode::Execute) {
623623
// Don't say that directories are executable.
@@ -726,7 +726,7 @@ static file_type typeForMode(mode_t Mode) {
726726
static std::error_code fillStatus(int StatRet, const struct stat &Status,
727727
file_status &Result) {
728728
if (StatRet != 0) {
729-
std::error_code EC(errno, std::generic_category());
729+
std::error_code EC = errnoAsErrorCode();
730730
if (EC == errc::no_such_file_or_directory)
731731
Result = file_status(file_type::file_not_found);
732732
else
@@ -782,13 +782,13 @@ std::error_code setPermissions(const Twine &Path, perms Permissions) {
782782
StringRef P = Path.toNullTerminatedStringRef(PathStorage);
783783

784784
if (::chmod(P.begin(), Permissions))
785-
return std::error_code(errno, std::generic_category());
785+
return errnoAsErrorCode();
786786
return std::error_code();
787787
}
788788

789789
std::error_code setPermissions(int FD, perms Permissions) {
790790
if (::fchmod(FD, Permissions))
791-
return std::error_code(errno, std::generic_category());
791+
return errnoAsErrorCode();
792792
return std::error_code();
793793
}
794794

@@ -799,7 +799,7 @@ std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
799799
Times[0] = sys::toTimeSpec(AccessTime);
800800
Times[1] = sys::toTimeSpec(ModificationTime);
801801
if (::futimens(FD, Times))
802-
return std::error_code(errno, std::generic_category());
802+
return errnoAsErrorCode();
803803
return std::error_code();
804804
#elif defined(HAVE_FUTIMES)
805805
timeval Times[2];
@@ -809,7 +809,7 @@ std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
809809
sys::toTimeVal(std::chrono::time_point_cast<std::chrono::microseconds>(
810810
ModificationTime));
811811
if (::futimes(FD, Times))
812-
return std::error_code(errno, std::generic_category());
812+
return errnoAsErrorCode();
813813
return std::error_code();
814814
#elif defined(__MVS__)
815815
attrib_t Attr;
@@ -819,7 +819,7 @@ std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
819819
Attr.att_mtimechg = 1;
820820
Attr.att_mtime = sys::toTimeT(ModificationTime);
821821
if (::__fchattr(FD, &Attr, sizeof(Attr)) != 0)
822-
return std::error_code(errno, std::generic_category());
822+
return errnoAsErrorCode();
823823
return std::error_code();
824824
#else
825825
#warning Missing futimes() and futimens()
@@ -858,7 +858,7 @@ std::error_code mapped_file_region::init(int FD, uint64_t Offset,
858858

859859
Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
860860
if (Mapping == MAP_FAILED)
861-
return std::error_code(errno, std::generic_category());
861+
return errnoAsErrorCode();
862862
return std::error_code();
863863
}
864864

@@ -897,7 +897,7 @@ std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
897897
SmallString<128> path_null(path);
898898
DIR *directory = ::opendir(path_null.c_str());
899899
if (!directory)
900-
return std::error_code(errno, std::generic_category());
900+
return errnoAsErrorCode();
901901

902902
it.IterationHandle = reinterpret_cast<intptr_t>(directory);
903903
// Add something for replace_filename to replace.
@@ -932,7 +932,7 @@ std::error_code detail::directory_iterator_increment(detail::DirIterState &It) {
932932
errno = 0;
933933
dirent *CurDir = ::readdir(reinterpret_cast<DIR *>(It.IterationHandle));
934934
if (CurDir == nullptr && errno != 0) {
935-
return std::error_code(errno, std::generic_category());
935+
return errnoAsErrorCode();
936936
} else if (CurDir != nullptr) {
937937
StringRef Name(CurDir->d_name);
938938
if ((Name.size() == 1 && Name[0] == '.') ||
@@ -1023,7 +1023,7 @@ std::error_code openFile(const Twine &Name, int &ResultFD,
10231023
// when open is overloaded, such as in Bionic.
10241024
auto Open = [&]() { return ::open(P.begin(), OpenFlags, Mode); };
10251025
if ((ResultFD = sys::RetryAfterSignal(-1, Open)) < 0)
1026-
return std::error_code(errno, std::generic_category());
1026+
return errnoAsErrorCode();
10271027
#ifndef O_CLOEXEC
10281028
if (!(Flags & OF_ChildInherit)) {
10291029
int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
@@ -1087,10 +1087,10 @@ std::error_code openFile(const Twine &Name, int &ResultFD,
10871087
* open().
10881088
*/
10891089
if ((Flags & OF_Append) && lseek(ResultFD, 0, SEEK_END) == -1)
1090-
return std::error_code(errno, std::generic_category());
1090+
return errnoAsErrorCode();
10911091
struct stat Stat;
10921092
if (fstat(ResultFD, &Stat) == -1)
1093-
return std::error_code(errno, std::generic_category());
1093+
return errnoAsErrorCode();
10941094
if (S_ISREG(Stat.st_mode)) {
10951095
bool DoSetTag = (Access & FA_Write) && (Disp != CD_OpenExisting) &&
10961096
!Stat.st_tag.ft_txtflag && !Stat.st_tag.ft_ccsid &&
@@ -1190,7 +1190,7 @@ Expected<size_t> readNativeFile(file_t FD, MutableArrayRef<char> Buf) {
11901190
#endif
11911191
ssize_t NumRead = sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Size);
11921192
if (ssize_t(NumRead) == -1)
1193-
return errorCodeToError(std::error_code(errno, std::generic_category()));
1193+
return errorCodeToError(errnoAsErrorCode());
11941194
return NumRead;
11951195
}
11961196

@@ -1206,11 +1206,11 @@ Expected<size_t> readNativeFileSlice(file_t FD, MutableArrayRef<char> Buf,
12061206
sys::RetryAfterSignal(-1, ::pread, FD, Buf.data(), Size, Offset);
12071207
#else
12081208
if (lseek(FD, Offset, SEEK_SET) == -1)
1209-
return errorCodeToError(std::error_code(errno, std::generic_category()));
1209+
return errorCodeToError(errnoAsErrorCode());
12101210
ssize_t NumRead = sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Size);
12111211
#endif
12121212
if (NumRead == -1)
1213-
return errorCodeToError(std::error_code(errno, std::generic_category()));
1213+
return errorCodeToError(errnoAsErrorCode());
12141214
return NumRead;
12151215
}
12161216

@@ -1243,8 +1243,7 @@ std::error_code lockFile(int FD) {
12431243
Lock.l_len = 0;
12441244
if (::fcntl(FD, F_SETLKW, &Lock) != -1)
12451245
return std::error_code();
1246-
int Error = errno;
1247-
return std::error_code(Error, std::generic_category());
1246+
return errnoAsErrorCode();
12481247
}
12491248

12501249
std::error_code unlockFile(int FD) {
@@ -1255,7 +1254,7 @@ std::error_code unlockFile(int FD) {
12551254
Lock.l_len = 0;
12561255
if (::fcntl(FD, F_SETLK, &Lock) != -1)
12571256
return std::error_code();
1258-
return std::error_code(errno, std::generic_category());
1257+
return errnoAsErrorCode();
12591258
}
12601259

12611260
std::error_code closeFile(file_t &F) {
@@ -1321,7 +1320,7 @@ std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
13211320
StringRef P = path.toNullTerminatedStringRef(Storage);
13221321
char Buffer[PATH_MAX];
13231322
if (::realpath(P.begin(), Buffer) == nullptr)
1324-
return std::error_code(errno, std::generic_category());
1323+
return errnoAsErrorCode();
13251324
dest.append(Buffer, Buffer + strlen(Buffer));
13261325
return std::error_code();
13271326
}
@@ -1330,7 +1329,7 @@ std::error_code changeFileOwnership(int FD, uint32_t Owner, uint32_t Group) {
13301329
auto FChown = [&]() { return ::fchown(FD, Owner, Group); };
13311330
// Retry if fchown call fails due to interruption.
13321331
if ((sys::RetryAfterSignal(-1, FChown)) < 0)
1333-
return std::error_code(errno, std::generic_category());
1332+
return errnoAsErrorCode();
13341333
return std::error_code();
13351334
}
13361335

@@ -1513,7 +1512,7 @@ std::error_code copy_file(const Twine &From, const Twine &To) {
15131512
#endif
15141513
if (!copyfile(FromS.c_str(), ToS.c_str(), /*State=*/NULL, COPYFILE_DATA))
15151514
return std::error_code();
1516-
return std::error_code(errno, std::generic_category());
1515+
return errnoAsErrorCode();
15171516
}
15181517
#endif // __APPLE__
15191518

‎llvm/lib/Support/Unix/Process.inc

+6-6
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ Expected<unsigned> Process::getPageSize() {
8686
#error Cannot get the page size on this machine
8787
#endif
8888
if (page_size == -1)
89-
return errorCodeToError(std::error_code(errno, std::generic_category()));
89+
return errorCodeToError(errnoAsErrorCode());
9090

9191
return static_cast<unsigned>(page_size);
9292
}
@@ -235,7 +235,7 @@ std::error_code Process::FixupStandardFileDescriptors() {
235235
assert(errno && "expected errno to be set if fstat failed!");
236236
// fstat should return EBADF if the file descriptor is closed.
237237
if (errno != EBADF)
238-
return std::error_code(errno, std::generic_category());
238+
return errnoAsErrorCode();
239239
}
240240
// if fstat succeeds, move on to the next FD.
241241
if (!errno)
@@ -247,13 +247,13 @@ std::error_code Process::FixupStandardFileDescriptors() {
247247
// RetryAfterSignal when open is overloaded, such as in Bionic.
248248
auto Open = [&]() { return ::open("/dev/null", O_RDWR); };
249249
if ((NullFD = RetryAfterSignal(-1, Open)) < 0)
250-
return std::error_code(errno, std::generic_category());
250+
return errnoAsErrorCode();
251251
}
252252

253253
if (NullFD == StandardFD)
254254
FDC.keepOpen();
255255
else if (dup2(NullFD, StandardFD) < 0)
256-
return std::error_code(errno, std::generic_category());
256+
return errnoAsErrorCode();
257257
}
258258
return std::error_code();
259259
}
@@ -262,15 +262,15 @@ std::error_code Process::SafelyCloseFileDescriptor(int FD) {
262262
// Create a signal set filled with *all* signals.
263263
sigset_t FullSet, SavedSet;
264264
if (sigfillset(&FullSet) < 0 || sigfillset(&SavedSet) < 0)
265-
return std::error_code(errno, std::generic_category());
265+
return errnoAsErrorCode();
266266

267267
// Atomically swap our current signal mask with a full mask.
268268
#if LLVM_ENABLE_THREADS
269269
if (int EC = pthread_sigmask(SIG_SETMASK, &FullSet, &SavedSet))
270270
return std::error_code(EC, std::generic_category());
271271
#else
272272
if (sigprocmask(SIG_SETMASK, &FullSet, &SavedSet) < 0)
273-
return std::error_code(errno, std::generic_category());
273+
return errnoAsErrorCode();
274274
#endif
275275
// Attempt to close the file descriptor.
276276
// We need to save the error, if one occurs, because our subsequent call to

‎llvm/lib/Support/Windows/Process.inc

+1-1
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,7 @@ std::error_code Process::FixupStandardFileDescriptors() {
276276

277277
std::error_code Process::SafelyCloseFileDescriptor(int FD) {
278278
if (::close(FD) < 0)
279-
return std::error_code(errno, std::generic_category());
279+
return errnoAsErrorCode();
280280
return std::error_code();
281281
}
282282

‎llvm/lib/Support/Windows/Program.inc

+2-2
Original file line numberDiff line numberDiff line change
@@ -506,14 +506,14 @@ std::error_code llvm::sys::ChangeStdoutMode(sys::fs::OpenFlags Flags) {
506506
std::error_code sys::ChangeStdinToBinary() {
507507
int result = _setmode(_fileno(stdin), _O_BINARY);
508508
if (result == -1)
509-
return std::error_code(errno, std::generic_category());
509+
return errnoAsErrorCode();
510510
return std::error_code();
511511
}
512512

513513
std::error_code sys::ChangeStdoutToBinary() {
514514
int result = _setmode(_fileno(stdout), _O_BINARY);
515515
if (result == -1)
516-
return std::error_code(errno, std::generic_category());
516+
return errnoAsErrorCode();
517517
return std::error_code();
518518
}
519519

‎llvm/lib/Support/raw_ostream.cpp

+3-3
Original file line numberDiff line numberDiff line change
@@ -794,7 +794,7 @@ void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
794794
}
795795
#endif
796796
// Otherwise it's a non-recoverable error. Note it and quit.
797-
error_detected(std::error_code(errno, std::generic_category()));
797+
error_detected(errnoAsErrorCode());
798798
break;
799799
}
800800

@@ -824,7 +824,7 @@ uint64_t raw_fd_ostream::seek(uint64_t off) {
824824
pos = ::lseek(FD, off, SEEK_SET);
825825
#endif
826826
if (pos == (uint64_t)-1)
827-
error_detected(std::error_code(errno, std::generic_category()));
827+
error_detected(errnoAsErrorCode());
828828
return pos;
829829
}
830830

@@ -946,7 +946,7 @@ ssize_t raw_fd_stream::read(char *Ptr, size_t Size) {
946946
if (Ret >= 0)
947947
inc_pos(Ret);
948948
else
949-
error_detected(std::error_code(errno, std::generic_category()));
949+
error_detected(errnoAsErrorCode());
950950
return Ret;
951951
}
952952

‎llvm/lib/Support/raw_socket_stream.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ static std::error_code getLastSocketErrorCode() {
5252
#ifdef _WIN32
5353
return std::error_code(::WSAGetLastError(), std::system_category());
5454
#else
55-
return std::error_code(errno, std::system_category());
55+
return errnoAsErrorCode();
5656
#endif
5757
}
5858

0 commit comments

Comments
 (0)
Please sign in to comment.