diff options
author | Billy Donahue <billy.donahue@mongodb.com> | 2022-04-28 07:39:29 +0000 |
---|---|---|
committer | Evergreen Agent <no-reply@evergreen.mongodb.com> | 2022-04-28 08:28:54 +0000 |
commit | 5b17ba836945f2b7cbcc77a643311f41fe7b7b6e (patch) | |
tree | 11aa849763d123d755eb0d9c30215904acdef4c2 /src/mongo | |
parent | 30260c79d9e09dee6c68637f87db6c4bdf16cbfe (diff) | |
download | mongo-5b17ba836945f2b7cbcc77a643311f41fe7b7b6e.tar.gz |
SERVER-41353 replace errnoWithDescription with an API based on std::error_code
Diffstat (limited to 'src/mongo')
56 files changed, 836 insertions, 718 deletions
diff --git a/src/mongo/crypto/symmetric_crypto_windows.cpp b/src/mongo/crypto/symmetric_crypto_windows.cpp index b43675b82b8..10ea5ed3c9c 100644 --- a/src/mongo/crypto/symmetric_crypto_windows.cpp +++ b/src/mongo/crypto/symmetric_crypto_windows.cpp @@ -65,7 +65,7 @@ std::string statusWithDescription(NTSTATUS status) { ULONG errorCode = RtlNtStatusToDosErrorFunc(status); if (errorCode != ERROR_MR_MID_NOT_FOUND) { - return errnoWithDescription(errorCode); + return errorMessage(systemError(errorCode)); } } } diff --git a/src/mongo/db/initialize_server_global_state.cpp b/src/mongo/db/initialize_server_global_state.cpp index 4dc953ff8ce..340ad49d7e9 100644 --- a/src/mongo/db/initialize_server_global_state.cpp +++ b/src/mongo/db/initialize_server_global_state.cpp @@ -66,7 +66,7 @@ namespace mongo { #ifndef _WIN32 static void croak(StringData prefix, int savedErr = errno) { - std::cout << prefix << ": " << errnoWithDescription(savedErr) << std::endl; + std::cout << prefix << ": " << errorMessage(posixError(savedErr)) << std::endl; quickExit(EXIT_ABRUPT); } @@ -85,10 +85,11 @@ void signalForkSuccess() { if (savedErr == EPIPE) break; // The pipe read side has closed. else { + auto ec = posixError(savedErr); LOGV2_WARNING(4656300, "Write to child pipe failed", - "errno"_attr = savedErr, - "errnoDesc"_attr = errnoWithDescription(savedErr)); + "errno"_attr = ec.value(), + "errnoDesc"_attr = errorMessage(ec)); quickExit(1); } } else if (nw == 0) { @@ -98,11 +99,11 @@ void signalForkSuccess() { } } if (close(*f) == -1) { - int savedErr = errno; + auto ec = lastPosixError(); LOGV2_WARNING(4656301, "Closing write pipe failed", - "errno"_attr = savedErr, - "errnoDesc"_attr = errnoWithDescription(savedErr)); + "errno"_attr = ec.value(), + "errnoDesc"_attr = errorMessage(ec)); } *f = -1; } diff --git a/src/mongo/db/mongod_main.cpp b/src/mongo/db/mongod_main.cpp index 94aaa958448..b079161955a 100644 --- a/src/mongo/db/mongod_main.cpp +++ b/src/mongo/db/mongod_main.cpp @@ -936,9 +936,9 @@ Status shutdownProcessByDBPathPidFile(const std::string& dbpath) { std::cout << "Killing process with pid: " << pid << std::endl; int ret = kill(pid, SIGTERM); if (ret) { - int e = errno; + auto ec = lastSystemError(); return {ErrorCodes::OperationFailed, - str::stream() << "Failed to kill process: " << errnoWithDescription(e)}; + str::stream() << "Failed to kill process: " << errorMessage(ec)}; } // Wait for process to terminate. diff --git a/src/mongo/db/operation_cpu_timer.cpp b/src/mongo/db/operation_cpu_timer.cpp index b870e621909..f37f0b99da4 100644 --- a/src/mongo/db/operation_cpu_timer.cpp +++ b/src/mongo/db/operation_cpu_timer.cpp @@ -59,9 +59,9 @@ namespace { Nanoseconds getThreadCPUTime() { struct timespec t; if (auto ret = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &t); ret != 0) { - int ec = errno; - iassert(Status(ErrorCodes::InternalError, - "Unable to get time: {}"_format(errnoWithDescription(ec)))); + auto ec = lastSystemError(); + iassert( + Status(ErrorCodes::InternalError, "Unable to get time: {}"_format(errorMessage(ec)))); } return Seconds(t.tv_sec) + Nanoseconds(t.tv_nsec); } diff --git a/src/mongo/db/repl/isself.cpp b/src/mongo/db/repl/isself.cpp index 243a1c065f0..886d5b739e6 100644 --- a/src/mongo/db/repl/isself.cpp +++ b/src/mongo/db/repl/isself.cpp @@ -89,20 +89,6 @@ MONGO_INITIALIZER(GenerateInstanceId)(InitializerContext*) { namespace { /** - * Helper to convert a message from a networking function to a string. - * Needed because errnoWithDescription uses strerror on linux, when - * we need gai_strerror. - */ -std::string stringifyError(int code) { -#if FASTPATH_UNIX - return gai_strerror(code); -#elif defined(_WIN32) - // FormatMessage in errnoWithDescription works here on windows - return errnoWithDescription(code); -#endif -} - -/** * Resolves a host and port to a list of IP addresses. This requires a syscall. If the * ipv6enabled parameter is true, both IPv6 and IPv4 addresses will be returned. */ @@ -121,11 +107,12 @@ std::vector<std::string> getAddrsForHost(const std::string& iporhost, int err = getaddrinfo(iporhost.c_str(), portNum.c_str(), &hints, &addrs); if (err) { + auto ec = addrInfoError(err); LOGV2_WARNING(21207, "getaddrinfo(\"{host}\") failed: {error}", "getaddrinfo() failed", "host"_attr = iporhost, - "error"_attr = stringifyError(err)); + "error"_attr = errorMessage(ec)); return out; } @@ -139,10 +126,11 @@ std::vector<std::string> getAddrsForHost(const std::string& iporhost, err = getnameinfo( addr->ai_addr, addr->ai_addrlen, host, NI_MAXHOST, nullptr, 0, NI_NUMERICHOST); if (err) { + auto ec = addrInfoError(err); LOGV2_WARNING(21208, "getnameinfo() failed: {error}", "getnameinfo() failed", - "error"_attr = stringifyError(err)); + "error"_attr = errorMessage(ec)); continue; } out.push_back(host); @@ -281,12 +269,12 @@ std::vector<std::string> getBoundAddrs(const bool ipv6enabled) { ifaddrs* addrs; - int err = getifaddrs(&addrs); - if (err) { + if (getifaddrs(&addrs)) { + auto ec = lastSystemError(); LOGV2_WARNING(21210, "getifaddrs failure: {error}", "getifaddrs() failed", - "error"_attr = errnoWithDescription(err)); + "error"_attr = errorMessage(ec)); return out; } ON_BLOCK_EXIT([&] { freeifaddrs(addrs); }); @@ -299,7 +287,7 @@ std::vector<std::string> getBoundAddrs(const bool ipv6enabled) { char host[NI_MAXHOST]; if (family == AF_INET || (ipv6enabled && (family == AF_INET6))) { - err = getnameinfo( + int err = getnameinfo( addr->ifa_addr, (family == AF_INET ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)), host, @@ -311,7 +299,7 @@ std::vector<std::string> getBoundAddrs(const bool ipv6enabled) { LOGV2_WARNING(21211, "getnameinfo() failed: {error}", "getnameinfo() failed", - "error"_attr = gai_strerror(err)); + "error"_attr = errorMessage(addrInfoError(err))); continue; } out.push_back(host); @@ -351,7 +339,7 @@ std::vector<std::string> getBoundAddrs(const bool ipv6enabled) { LOGV2_WARNING(21212, "GetAdaptersAddresses() failed: {error}", "GetAdaptersAddresses() failed", - "error"_attr = errnoWithDescription(err)); + "error"_attr = errorMessage(systemError(err))); return out; } diff --git a/src/mongo/db/server_options_test.cpp b/src/mongo/db/server_options_test.cpp index b608e3f1658..c8ef037ee40 100644 --- a/src/mongo/db/server_options_test.cpp +++ b/src/mongo/db/server_options_test.cpp @@ -815,7 +815,10 @@ TEST(SetupOptions, UnlinkedCwd) { // Naive rmdir of cwd doesn't work on Solaris doesn't work (no matter how it's specified). // So we use a subprocess to unlink the dir. pid_t pid = fork(); - ASSERT_NOT_EQUALS(pid, -1) << "unable to fork: " << ::mongo::errnoWithDescription(); + if (pid == -1) { + auto ec = lastSystemError(); + FAIL("unable to fork") << errorMessage(ec); + } if (pid == 0) { // Subprocess // No exceptions, ASSERT(), FAIL() or logging. diff --git a/src/mongo/db/startup_warnings_mongod.cpp b/src/mongo/db/startup_warnings_mongod.cpp index 60e5bc1f134..dcc90c3dfc2 100644 --- a/src/mongo/db/startup_warnings_mongod.cpp +++ b/src/mongo/db/startup_warnings_mongod.cpp @@ -96,11 +96,11 @@ StatusWith<std::string> StartupWarningsMongod::readTransparentHugePagesParameter std::string line; if (!std::getline(ifs, line)) { - int errorcode = errno; - return StatusWith<std::string>( - ErrorCodes::FileStreamFailed, - str::stream() << "failed to read from " << filename << ": " - << ((ifs.eof()) ? "EOF" : errnoWithDescription(errorcode))); + auto ec = lastSystemError(); + return StatusWith<std::string>(ErrorCodes::FileStreamFailed, + str::stream() + << "failed to read from " << filename << ": " + << ((ifs.eof()) ? "EOF" : errorMessage(ec))); } std::string::size_type posBegin = line.find("["); @@ -188,10 +188,11 @@ void logMongodStartupWarnings(const StorageGlobalParams& storageParams, std::string line; // we only need the first line std::getline(f, line); if (f.fail()) { + auto ec = lastSystemError(); LOGV2_WARNING_OPTIONS(22200, {logv2::LogTag::kStartupWarnings}, "Failed to read from /proc/self/numa_maps", - "error"_attr = errnoWithDescription()); + "error"_attr = errorMessage(ec)); } else { // skip over pointer std::string::size_type where = line.find(' '); @@ -324,12 +325,12 @@ void logMongodStartupWarnings(const StorageGlobalParams& storageParams, "recommendedMinimum"_attr = minNumFiles); } } else { - const auto errmsg = errnoWithDescription(); + auto ec = lastSystemError(); LOGV2_WARNING_OPTIONS(22186, {logv2::LogTag::kStartupWarnings}, "getrlimit failed: {error}", "getrlimit failed", - "error"_attr = errmsg); + "error"_attr = errorMessage(ec)); } // Solaris does not have RLIMIT_MEMLOCK, these are exposed via getrctl(2) instead @@ -352,12 +353,12 @@ void logMongodStartupWarnings(const StorageGlobalParams& storageParams, minLockedPages * ProcessInfo::getPageSize()); } } else { - const auto errmsg = errnoWithDescription(); + auto ec = lastSystemError(); LOGV2_WARNING_OPTIONS(22190, {logv2::LogTag::kStartupWarnings}, "** WARNING: getrlimit failed: {error}", "getrlimit failed", - "error"_attr = errmsg); + "error"_attr = errorMessage(ec)); } #endif #endif diff --git a/src/mongo/db/storage/remove_saver.cpp b/src/mongo/db/storage/remove_saver.cpp index 950d390d63e..5cd5f367567 100644 --- a/src/mongo/db/storage/remove_saver.cpp +++ b/src/mongo/db/storage/remove_saver.cpp @@ -97,12 +97,13 @@ RemoveSaver::~RemoveSaver() { _out->write(reinterpret_cast<const char*>(protectedBuffer.get()), resultLen); if (_out->fail()) { + auto ec = lastSystemError(); LOGV2_FATAL(34351, "Couldn't write finalized DataProtector data to: {file} for remove " "saving: {error}", "Couldn't write finalized DataProtector for remove saving", "file"_attr = _file.generic_string(), - "error"_attr = redact(errnoWithDescription())); + "error"_attr = redact(errorMessage(ec))); } protectedBuffer.reset(new uint8_t[protectedSizeMax]); @@ -128,12 +129,13 @@ RemoveSaver::~RemoveSaver() { _out->write(reinterpret_cast<const char*>(protectedBuffer.get()), resultLen); if (_out->fail()) { + auto ec = lastSystemError(); LOGV2_FATAL(34354, "Couldn't write finalizeTag from DataProtector to: {file} for " "remove saving: {error}", "Couldn't write finalizeTag from DataProtector for remove saving", "file"_attr = _file.generic_string(), - "error"_attr = redact(errnoWithDescription())); + "error"_attr = redact(errorMessage(ec))); } _storage->dumpBuffer(); @@ -145,12 +147,13 @@ Status RemoveSaver::goingToDelete(const BSONObj& o) { _out = _storage->makeOstream(_file, _root); if (_out->fail()) { + auto ec = lastSystemError(); string msg = str::stream() << "couldn't create file: " << _file.string() - << " for remove saving: " << redact(errnoWithDescription()); + << " for remove saving: " << redact(errorMessage(ec)); LOGV2_ERROR(23734, "Failed to create file for remove saving", "file"_attr = _file.generic_string(), - "error"_attr = redact(errnoWithDescription())); + "error"_attr = redact(errorMessage(ec))); _out.reset(); _out = nullptr; return Status(ErrorCodes::FileNotOpen, msg); @@ -183,7 +186,7 @@ Status RemoveSaver::goingToDelete(const BSONObj& o) { _out->write(reinterpret_cast<const char*>(data), dataSize); if (_out->fail()) { - auto errorStr = redact(errnoWithDescription()); + auto errorStr = redact(errorMessage(lastSystemError())); string msg = str::stream() << "couldn't write document to file: " << _file.string() << " for remove saving: " << errorStr; LOGV2_ERROR(23735, diff --git a/src/mongo/db/storage/storage_engine_lock_file_posix.cpp b/src/mongo/db/storage/storage_engine_lock_file_posix.cpp index 0d67885718a..bb96b23bffd 100644 --- a/src/mongo/db/storage/storage_engine_lock_file_posix.cpp +++ b/src/mongo/db/storage/storage_engine_lock_file_posix.cpp @@ -69,13 +69,15 @@ void flushMyDirectory(const boost::filesystem::path& file) { LOGV2_DEBUG(22275, 1, "flushing directory {dir_string}", "dir_string"_attr = dir.string()); int fd = ::open(dir.string().c_str(), O_RDONLY); // DO NOT THROW OR ASSERT BEFORE CLOSING - massert(40387, - str::stream() << "Couldn't open directory '" << dir.string() - << "' for flushing: " << errnoWithDescription(), - fd >= 0); + if (fd < 0) { + auto ec = lastPosixError(); + msgasserted(40387, + str::stream() << "Couldn't open directory '" << dir.string() + << "' for flushing: " << errorMessage(ec)); + } if (fsync(fd) != 0) { - int e = errno; - if (e == EINVAL) { // indicates filesystem does not support synchronization + auto ec = lastPosixError(); + if (ec == posixError(EINVAL)) { // indicates filesystem does not support synchronization if (!_warnedAboutFilesystem) { LOGV2_OPTIONS( 22276, @@ -89,7 +91,7 @@ void flushMyDirectory(const boost::filesystem::path& file) { close(fd); massert(40388, str::stream() << "Couldn't fsync directory '" << dir.string() - << "': " << errnoWithDescription(e), + << "': " << errorMessage(ec), false); } } @@ -145,8 +147,8 @@ Status StorageEngineLockFile::open() { int lockFile = ::open(_filespec.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (lockFile < 0) { - int errorcode = errno; - if (errorcode == EACCES) { + auto ec = lastPosixError(); + if (ec == posixError(EACCES)) { return Status(ErrorCodes::IllegalOperation, str::stream() << "Attempted to create a lock file on a read-only directory: " @@ -154,7 +156,7 @@ Status StorageEngineLockFile::open() { } return Status(ErrorCodes::DBPathInUse, str::stream() << "Unable to create/open the lock file: " << _filespec << " (" - << errnoWithDescription(errorcode) << ")." + << errorMessage(ec) << ")." << " Ensure the user executing mongod is the owner of the lock " "file and has the appropriate permissions. Also make sure " "that another mongod instance is not already running on the " @@ -162,11 +164,11 @@ Status StorageEngineLockFile::open() { } int ret = ::flock(lockFile, LOCK_EX | LOCK_NB); if (ret != 0) { - int errorcode = errno; + auto ec = lastPosixError(); ::close(lockFile); return Status(ErrorCodes::DBPathInUse, str::stream() << "Unable to lock the lock file: " << _filespec << " (" - << errnoWithDescription(errorcode) << ")." + << errorMessage(ec) << ")." << " Another mongod instance is already running on the " << _dbpath << " directory"); } @@ -191,18 +193,18 @@ Status StorageEngineLockFile::writeString(StringData str) { } if (::ftruncate(_lockFileHandle->_fd, 0)) { - int errorcode = errno; + auto ec = lastPosixError(); return Status(ErrorCodes::FileStreamFailed, str::stream() << "Unable to write string to file (ftruncate failed): " - << _filespec << ' ' << errnoWithDescription(errorcode)); + << _filespec << ' ' << errorMessage(ec)); } int bytesWritten = ::write(_lockFileHandle->_fd, str.rawData(), str.size()); if (bytesWritten < 0) { - int errorcode = errno; + auto ec = lastPosixError(); return Status(ErrorCodes::FileStreamFailed, str::stream() << "Unable to write string " << str << " to file: " << _filespec - << ' ' << errnoWithDescription(errorcode)); + << ' ' << errorMessage(ec)); } else if (bytesWritten == 0) { return Status(ErrorCodes::FileStreamFailed, @@ -211,11 +213,11 @@ Status StorageEngineLockFile::writeString(StringData str) { } if (::fsync(_lockFileHandle->_fd)) { - int errorcode = errno; + auto ec = lastPosixError(); return Status(ErrorCodes::FileStreamFailed, - str::stream() << "Unable to write process id " << str - << " to file (fsync failed): " << _filespec << ' ' - << errnoWithDescription(errorcode)); + str::stream() + << "Unable to write process id " << str + << " to file (fsync failed): " << _filespec << ' ' << errorMessage(ec)); } flushMyDirectory(_filespec); @@ -232,11 +234,8 @@ void StorageEngineLockFile::clearPidAndUnlock() { // time that was attempted, there was a race condition // with StorageEngineLockFile::open(). if (::ftruncate(_lockFileHandle->_fd, 0)) { - int errorcode = errno; - LOGV2(22280, - "couldn't remove fs lock {errnoWithDescription_errorcode}", - "Couldn't remove fs lock", - "error"_attr = errnoWithDescription(errorcode)); + auto ec = lastPosixError(); + LOGV2(22280, "Couldn't remove fs lock", "error"_attr = errorMessage(ec)); } close(); } diff --git a/src/mongo/db/storage/storage_engine_lock_file_windows.cpp b/src/mongo/db/storage/storage_engine_lock_file_windows.cpp index 0c45fed0a70..07dfbffd9d2 100644 --- a/src/mongo/db/storage/storage_engine_lock_file_windows.cpp +++ b/src/mongo/db/storage/storage_engine_lock_file_windows.cpp @@ -52,17 +52,17 @@ Status _truncateFile(HANDLE handle) { LARGE_INTEGER largeint; largeint.QuadPart = 0; if (::SetFilePointerEx(handle, largeint, NULL, FILE_BEGIN) == FALSE) { - int errorcode = GetLastError(); + auto ec = lastSystemError(); return Status(ErrorCodes::FileStreamFailed, str::stream() << "Unable to truncate lock file (SetFilePointerEx failed) " - << errnoWithDescription(errorcode)); + << errorMessage(ec)); } if (::SetEndOfFile(handle) == FALSE) { - int errorcode = GetLastError(); + auto ec = lastSystemError(); return Status(ErrorCodes::FileStreamFailed, str::stream() << "Unable to truncate lock file (SetEndOfFile failed) " - << errnoWithDescription(errorcode)); + << errorMessage(ec)); } return Status::OK(); @@ -119,8 +119,8 @@ Status StorageEngineLockFile::open() { NULL); if (lockFileHandle == INVALID_HANDLE_VALUE) { - int errorcode = GetLastError(); - if (errorcode == ERROR_ACCESS_DENIED) { + auto ec = lastSystemError(); + if (ec == systemError(ERROR_ACCESS_DENIED)) { return Status(ErrorCodes::IllegalOperation, str::stream() << "Attempted to create a lock file on a read-only directory: " @@ -128,7 +128,7 @@ Status StorageEngineLockFile::open() { } return Status(ErrorCodes::DBPathInUse, str::stream() << "Unable to create/open the lock file: " << _filespec << " (" - << errnoWithDescription(errorcode) << ")." + << errorMessage(ec) << ")." << " Ensure the user executing mongod is the owner of the lock " "file and has the appropriate permissions. Also make sure " "that another mongod instance is not already running on the " @@ -164,10 +164,10 @@ Status StorageEngineLockFile::writeString(StringData str) { static_cast<DWORD>(str.size()), &bytesWritten, NULL) == FALSE) { - int errorcode = GetLastError(); + auto ec = lastSystemError(); return Status(ErrorCodes::FileStreamFailed, str::stream() << "Unable to write string " << str << " to file: " << _filespec - << ' ' << errnoWithDescription(errorcode)); + << ' ' << errorMessage(ec)); } else if (bytesWritten == 0) { return Status(ErrorCodes::FileStreamFailed, str::stream() << "Unable to write string " << str << " to file: " << _filespec diff --git a/src/mongo/db/storage/storage_engine_metadata.cpp b/src/mongo/db/storage/storage_engine_metadata.cpp index 07b21b448e1..2bb7c548af8 100644 --- a/src/mongo/db/storage/storage_engine_metadata.cpp +++ b/src/mongo/db/storage/storage_engine_metadata.cpp @@ -234,13 +234,15 @@ void flushMyDirectory(const boost::filesystem::path& file) { LOGV2_DEBUG(22284, 1, "flushing directory {dir_string}", "dir_string"_attr = dir.string()); int fd = ::open(dir.string().c_str(), O_RDONLY); // DO NOT THROW OR ASSERT BEFORE CLOSING - massert(13650, - str::stream() << "Couldn't open directory '" << dir.string() - << "' for flushing: " << errnoWithDescription(), - fd >= 0); + if (fd < 0) { + auto ec = lastPosixError(); + msgasserted(13650, + str::stream() << "Couldn't open directory '" << dir.string() + << "' for flushing: " << errorMessage(ec)); + } if (fsync(fd) != 0) { - int e = errno; - if (e == EINVAL) { // indicates filesystem does not support synchronization + auto ec = lastPosixError(); + if (ec == posixError(EINVAL)) { // indicates filesystem does not support synchronization if (!_warnedAboutFilesystem) { LOGV2_OPTIONS( 22285, @@ -252,10 +254,9 @@ void flushMyDirectory(const boost::filesystem::path& file) { } } else { close(fd); - massert(13651, - str::stream() << "Couldn't fsync directory '" << dir.string() - << "': " << errnoWithDescription(e), - false); + msgasserted(13651, + str::stream() << "Couldn't fsync directory '" << dir.string() + << "': " << errorMessage(ec)); } } close(fd); @@ -273,20 +274,20 @@ Status StorageEngineMetadata::write() const { { std::ofstream ofs(metadataTempPath.c_str(), std::ios_base::out | std::ios_base::binary); if (!ofs) { + auto ec = lastSystemError(); return Status(ErrorCodes::FileNotOpen, - str::stream() - << "Failed to write metadata to " << metadataTempPath.string() << ": " - << errnoWithDescription()); + str::stream() << "Failed to write metadata to " + << metadataTempPath.string() << ": " << errorMessage(ec)); } BSONObj obj = BSON( "storage" << BSON("engine" << _storageEngine << "options" << _storageEngineOptions)); ofs.write(obj.objdata(), obj.objsize()); if (!ofs) { + auto ec = lastSystemError(); return Status(ErrorCodes::OperationFailed, - str::stream() - << "Failed to write BSON data to " << metadataTempPath.string() - << ": " << errnoWithDescription()); + str::stream() << "Failed to write BSON data to " + << metadataTempPath.string() << ": " << errorMessage(ec)); } } diff --git a/src/mongo/db/storage/storage_file_util.cpp b/src/mongo/db/storage/storage_file_util.cpp index 3f68fdebe70..6073acf89d0 100644 --- a/src/mongo/db/storage/storage_file_util.cpp +++ b/src/mongo/db/storage/storage_file_util.cpp @@ -71,20 +71,21 @@ Status fsyncParentDirectory(const boost::filesystem::path& file) { int fd = ::open(dir.string().c_str(), O_RDONLY); if (fd < 0) { + auto ec = lastPosixError(); return {ErrorCodes::FileOpenFailed, str::stream() << "Failed to open directory " << dir.string() - << " for flushing: " << errnoWithDescription()}; + << " for flushing: " << errorMessage(ec)}; } if (fsync(fd) != 0) { - int e = errno; - if (e == EINVAL) { + auto ec = lastPosixError(); + if (ec == posixError(EINVAL)) { LOGV2_WARNING(22290, "Could not fsync directory because this file system is not supported."); } else { close(fd); return {ErrorCodes::OperationFailed, str::stream() << "Failed to fsync directory '" << dir.string() - << "': " << errnoWithDescription(e)}; + << "': " << errorMessage(ec)}; } } close(fd); diff --git a/src/mongo/db/storage/storage_repair_observer.cpp b/src/mongo/db/storage/storage_repair_observer.cpp index 44bc890f3e8..29c0037716b 100644 --- a/src/mongo/db/storage/storage_repair_observer.cpp +++ b/src/mongo/db/storage/storage_repair_observer.cpp @@ -122,11 +122,12 @@ void StorageRepairObserver::_touchRepairIncompleteFile() { boost::filesystem::ofstream fileStream(_repairIncompleteFilePath); fileStream << "This file indicates that a repair operation is in progress or incomplete."; if (fileStream.fail()) { + auto ec = lastSystemError(); LOGV2_FATAL_NOTRACE(50920, "Failed to write to file {file}: {error}", "Failed to write to file", "file"_attr = _repairIncompleteFilePath.generic_string(), - "error"_attr = errnoWithDescription()); + "error"_attr = errorMessage(ec)); } fileStream.close(); diff --git a/src/mongo/db/storage/wiredtiger/wiredtiger_util.cpp b/src/mongo/db/storage/wiredtiger/wiredtiger_util.cpp index d4e48faafe9..eaba1639480 100644 --- a/src/mongo/db/storage/wiredtiger/wiredtiger_util.cpp +++ b/src/mongo/db/storage/wiredtiger/wiredtiger_util.cpp @@ -98,10 +98,11 @@ void createTableChecksFile() { "incomplete." << std::endl; if (fileStream.fail()) { + auto ec = lastSystemError(); LOGV2_FATAL_NOTRACE(4366400, "Failed to write to file", "file"_attr = path.generic_string(), - "error"_attr = errnoWithDescription()); + "error"_attr = errorMessage(ec)); } fileStream.close(); diff --git a/src/mongo/db/traffic_reader.cpp b/src/mongo/db/traffic_reader.cpp index c6a4ade2b48..0258f20e6a5 100644 --- a/src/mongo/db/traffic_reader.cpp +++ b/src/mongo/db/traffic_reader.cpp @@ -94,7 +94,7 @@ bool readBytes(size_t toRead, char* buf, int fd) { uassert(ErrorCodes::FileStreamFailed, str::stream() << "failed to read bytes: errno(" << ec.value() << ") : " << errorMessage(ec), - ec.value() == EINTR); + ec == posixError(EINTR)); continue; } else if (r == 0) { diff --git a/src/mongo/dbtests/jsontests.cpp b/src/mongo/dbtests/jsontests.cpp index cb16219f51d..94d1028f95e 100644 --- a/src/mongo/dbtests/jsontests.cpp +++ b/src/mongo/dbtests/jsontests.cpp @@ -402,7 +402,8 @@ public: char* _oldTimezonePtr = getenv("TZ"); _oldTimezone = std::string(_oldTimezonePtr ? _oldTimezonePtr : ""); if (-1 == putenv(tzEnvString)) { - FAIL(errnoWithDescription()); + auto ec = lastSystemError(); + FAIL(errorMessage(ec)); } tzset(); } @@ -418,7 +419,8 @@ public: } #else if (-1 == setenv("TZ", _oldTimezone.c_str(), 1)) { - FAIL(errnoWithDescription()); + auto ec = lastSystemError(); + FAIL(errorMessage(ec)); } #endif } else { @@ -431,7 +433,8 @@ public: } #else if (-1 == unsetenv("TZ")) { - FAIL(errnoWithDescription()); + auto ec = lastSystemError(); + FAIL(errorMessage(ec)); } #endif } diff --git a/src/mongo/platform/shared_library_windows.cpp b/src/mongo/platform/shared_library_windows.cpp index 5f51c7bc4e7..2b0873d103b 100644 --- a/src/mongo/platform/shared_library_windows.cpp +++ b/src/mongo/platform/shared_library_windows.cpp @@ -44,11 +44,11 @@ namespace mongo { SharedLibrary::~SharedLibrary() { if (_handle) { if (FreeLibrary(static_cast<HMODULE>(_handle)) == 0) { - DWORD lasterror = GetLastError(); + auto ec = lastSystemError(); LOGV2_DEBUG(22614, 2, "Load library close failed: {errnoWithDescription_lasterror}", - "errnoWithDescription_lasterror"_attr = errnoWithDescription(lasterror)); + "errnoWithDescription_lasterror"_attr = errorMessage(ec)); } } } @@ -62,9 +62,10 @@ StatusWith<std::unique_ptr<SharedLibrary>> SharedLibrary::create( HMODULE handle = LoadLibraryW(full_path.c_str()); if (handle == nullptr) { + auto ec = lastSystemError(); return StatusWith<std::unique_ptr<SharedLibrary>>(ErrorCodes::InternalError, str::stream() << "Load library failed: " - << errnoWithDescription()); + << errorMessage(ec)); } return StatusWith<std::unique_ptr<SharedLibrary>>( @@ -82,7 +83,7 @@ StatusWith<void*> SharedLibrary::getSymbol(StringData name) { if (gle != ERROR_PROC_NOT_FOUND) { return StatusWith<void*>(ErrorCodes::InternalError, str::stream() << "GetProcAddress failed for symbol: " - << errnoWithDescription()); + << errorMessage(systemError(gle))); } } diff --git a/src/mongo/shell/linenoise.cpp b/src/mongo/shell/linenoise.cpp index 679578d133b..364b1041d7c 100644 --- a/src/mongo/shell/linenoise.cpp +++ b/src/mongo/shell/linenoise.cpp @@ -2774,9 +2774,9 @@ namespace { mongo::Status linenoiseFileError(mongo::ErrorCodes::Error code, const char* what, const char* filename, - const std::string& ewd) { + std::error_code ec) { std::stringstream ss; - ss << "Unable to " << what << " file " << filename << ": " << ewd; + ss << "Unable to " << what << " file " << filename << ": " << mongo::errorMessage(ec); return {code, ss.str()}; } } // namespace @@ -2787,39 +2787,39 @@ mongo::Status linenoiseHistorySave(const char* filename) { #if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE || defined(__APPLE__) int fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR); if (fd == -1) { - const auto ewd = mongo::errnoWithDescription(); - return linenoiseFileError(mongo::ErrorCodes::FileOpenFailed, "open()", filename, ewd); + auto ec = mongo::lastSystemError(); + return linenoiseFileError(mongo::ErrorCodes::FileOpenFailed, "open()", filename, ec); } fp = fdopen(fd, "wt"); if (fp == nullptr) { - const auto ewd = mongo::errnoWithDescription(); + auto ec = mongo::lastSystemError(); // We've already failed, so no need to report any close() failure. (void)close(fd); - return linenoiseFileError(mongo::ErrorCodes::FileOpenFailed, "fdopen()", filename, ewd); + return linenoiseFileError(mongo::ErrorCodes::FileOpenFailed, "fdopen()", filename, ec); } #else fp = fopen(filename, "wt"); if (fp == nullptr) { - const auto ewd = mongo::errnoWithDescription(); - return linenoiseFileError(mongo::ErrorCodes::FileOpenFailed, "fopen()", filename, ewd); + auto ec = mongo::lastSystemError(); + return linenoiseFileError(mongo::ErrorCodes::FileOpenFailed, "fopen()", filename, ec); } #endif // _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE || defined(__APPLE__) for (int j = 0; j < historyLen; ++j) { if (history[j][0] != '\0') { if (fprintf(fp, "%s\n", history[j]) < 0) { - const auto ewd = mongo::errnoWithDescription(); + auto ec = mongo::lastSystemError(); // We've already failed, so no need to report any fclose() failure. (void)fclose(fp); return linenoiseFileError( - mongo::ErrorCodes::FileStreamFailed, "fprintf() to", filename, ewd); + mongo::ErrorCodes::FileStreamFailed, "fprintf() to", filename, ec); } } } // Closing fp also causes fd to be closed. if (fclose(fp) != 0) { - const auto ewd = mongo::errnoWithDescription(); - return linenoiseFileError(mongo::ErrorCodes::FileStreamFailed, "fclose()", filename, ewd); + auto ec = mongo::lastSystemError(); + return linenoiseFileError(mongo::ErrorCodes::FileStreamFailed, "fclose()", filename, ec); } return mongo::Status::OK(); } @@ -2833,8 +2833,8 @@ mongo::Status linenoiseHistoryLoad(const char* filename) { // For example, it's always the case when the shell is run for the first time. return mongo::Status::OK(); } - const auto ewd = mongo::errnoWithDescription(); - return linenoiseFileError(mongo::ErrorCodes::FileOpenFailed, "fopen()", filename, ewd); + auto ec = mongo::lastSystemError(); + return linenoiseFileError(mongo::ErrorCodes::FileOpenFailed, "fopen()", filename, ec); } bool historyLinesTruncated = false; @@ -2861,15 +2861,15 @@ mongo::Status linenoiseHistoryLoad(const char* filename) { // fgets() returns NULL on error or EOF (with nothing read). // So if we aren't EOF, it must have been an error. if (!feof(fp)) { - const auto ewd = mongo::errnoWithDescription(); + auto ec = mongo::lastSystemError(); // We've already failed, so no need to report any fclose() failure. (void)fclose(fp); return linenoiseFileError( - mongo::ErrorCodes::FileStreamFailed, "fgets() from", filename, ewd); + mongo::ErrorCodes::FileStreamFailed, "fgets() from", filename, ec); } if (fclose(fp) != 0) { - const auto ewd = mongo::errnoWithDescription(); - return linenoiseFileError(mongo::ErrorCodes::FileStreamFailed, "fclose()", filename, ewd); + auto ec = mongo::lastSystemError(); + return linenoiseFileError(mongo::ErrorCodes::FileStreamFailed, "fclose()", filename, ec); } return mongo::Status::OK(); } diff --git a/src/mongo/shell/mongo_main.cpp b/src/mongo/shell/mongo_main.cpp index b6cac96d526..4570170e9a7 100644 --- a/src/mongo/shell/mongo_main.cpp +++ b/src/mongo/shell/mongo_main.cpp @@ -599,7 +599,8 @@ static void edit(const std::string& whatToEdit) { FILE* tempFileStream; tempFileStream = fopen(filename.c_str(), "wt"); if (!tempFileStream) { - std::cout << "couldn't create temp file (" << filename << "): " << errnoWithDescription() + auto ec = lastPosixError(); + std::cout << "couldn't create temp file (" << filename << "): " << errorMessage(ec) << std::endl; return; } @@ -607,9 +608,8 @@ static void edit(const std::string& whatToEdit) { // Write JSON into the temp file size_t fileSize = js.size(); if (fwrite(js.data(), sizeof(char), fileSize, tempFileStream) != fileSize) { - int systemErrno = errno; - std::cout << "failed to write to temp file: " << errnoWithDescription(systemErrno) - << std::endl; + auto ec = lastPosixError(); + std::cout << "failed to write to temp file: " << errorMessage(ec) << std::endl; fclose(tempFileStream); remove(filename.c_str()); return; @@ -625,9 +625,9 @@ static void edit(const std::string& whatToEdit) { }(); if (ret) { if (ret == -1) { - int systemErrno = errno; - std::cout << "failed to launch $EDITOR (" << editor - << "): " << errnoWithDescription(systemErrno) << std::endl; + auto ec = lastPosixError(); + std::cout << "failed to launch $EDITOR (" << editor << "): " << errorMessage(ec) + << std::endl; } else std::cout << "editor exited with error (" << ret << "), not applying changes" << std::endl; @@ -638,7 +638,8 @@ static void edit(const std::string& whatToEdit) { // The editor gave return code zero, so read the file back in tempFileStream = fopen(filename.c_str(), "rt"); if (!tempFileStream) { - std::cout << "couldn't open temp file on return from editor: " << errnoWithDescription() + auto ec = lastPosixError(); + std::cout << "couldn't open temp file on return from editor: " << errorMessage(ec) << std::endl; remove(filename.c_str()); return; @@ -649,7 +650,8 @@ static void edit(const std::string& whatToEdit) { char buf[1024]; bytes = fread(buf, sizeof(char), sizeof buf, tempFileStream); if (ferror(tempFileStream)) { - std::cout << "failed to read temp file: " << errnoWithDescription() << std::endl; + auto ec = lastPosixError(); + std::cout << "failed to read temp file: " << errorMessage(ec) << std::endl; fclose(tempFileStream); remove(filename.c_str()); return; diff --git a/src/mongo/shell/shell_utils_extended.cpp b/src/mongo/shell/shell_utils_extended.cpp index 6cd6dc6ed0d..a77c66f603d 100644 --- a/src/mongo/shell/shell_utils_extended.cpp +++ b/src/mongo/shell/shell_utils_extended.cpp @@ -142,7 +142,8 @@ BSONObj cd(const BSONObj& args, void* data) { return BSONObj(); } #endif - uasserted(16832, str::stream() << "cd command failed: " << errnoWithDescription()); + auto ec = lastSystemError(); + uasserted(16832, str::stream() << "cd command failed: " << errorMessage(ec)); return BSONObj(); } diff --git a/src/mongo/shell/shell_utils_launcher.cpp b/src/mongo/shell/shell_utils_launcher.cpp index 0f6b6f2cf42..a649dca0ed3 100644 --- a/src/mongo/shell/shell_utils_launcher.cpp +++ b/src/mongo/shell/shell_utils_launcher.cpp @@ -136,8 +136,8 @@ void safeClose(int fd) { const ScopedSignalBlocker block; #endif if (close(fd) != 0) { - const auto ewd = errnoWithDescription(); - LOGV2_ERROR(22829, "Failed to close fd", "fd"_attr = fd, "error"_attr = ewd); + auto ec = lastPosixError(); + LOGV2_ERROR(22829, "Failed to close fd", "fd"_attr = fd, "error"_attr = errorMessage(ec)); fassertFailed(40318); } } @@ -258,9 +258,10 @@ bool ProgramRegistry::waitForPid(const ProcessId pid, const bool block, int* con if (ret == WAIT_TIMEOUT) { return false; } else if (ret != WAIT_OBJECT_0) { - const auto ewd = errnoWithDescription(); - LOGV2_INFO( - 22811, "ProgramRegistry::waitForPid: WaitForSingleObject failed", "error"_attr = ewd); + auto ec = lastSystemError(); + LOGV2_INFO(22811, + "ProgramRegistry::waitForPid: WaitForSingleObject failed", + "error"_attr = errorMessage(ec)); } DWORD tmp; @@ -279,8 +280,8 @@ bool ProgramRegistry::waitForPid(const ProcessId pid, const bool block, int* con unregisterProgram(pid); return true; } else { - const auto ewd = errnoWithDescription(); - LOGV2_INFO(22812, "GetExitCodeProcess failed", "error"_attr = ewd); + auto ec = lastSystemError(); + LOGV2_INFO(22812, "GetExitCodeProcess failed", "error"_attr = errorMessage(ec)); return false; } #else @@ -558,10 +559,9 @@ void ProgramRunner::start() { // Holding the lock for the duration of those events prevents the leaks and thus the // associated deadlocks. stdx::lock_guard<Latch> lk(_createProcessMtx); - int status = pipe(pipeEnds); - if (status != 0) { - const auto ewd = errnoWithDescription(); - LOGV2_ERROR(22830, "Failed to create pipe", "error"_attr = ewd); + if (pipe(pipeEnds)) { + auto ec = lastPosixError(); + LOGV2_ERROR(22830, "Failed to create pipe", "error"_attr = errorMessage(ec)); fassertFailed(16701); } #ifndef _WIN32 @@ -569,16 +569,16 @@ void ProgramRunner::start() { // about to fork do *not* inherit the file descriptors for the pipe. If grandchild processes // could inherit the FD for the pipe, than the pipe wouldn't close on child process exit. On // windows, instead the handle inherit flag is turned off after the call to CreateProcess. - status = fcntl(pipeEnds[0], F_SETFD, FD_CLOEXEC); - if (status != 0) { - const auto ewd = errnoWithDescription(); - LOGV2_ERROR(22831, "Failed to set FD_CLOEXEC on pipe end 0", "error"_attr = ewd); + if (fcntl(pipeEnds[0], F_SETFD, FD_CLOEXEC)) { + auto ec = lastPosixError(); + LOGV2_ERROR( + 22831, "Failed to set FD_CLOEXEC on pipe end 0", "error"_attr = errorMessage(ec)); fassertFailed(40308); } - status = fcntl(pipeEnds[1], F_SETFD, FD_CLOEXEC); - if (status != 0) { - const auto ewd = errnoWithDescription(); - LOGV2_ERROR(22832, "Failed to set FD_CLOEXEC on pipe end 1", "error"_attr = ewd); + if (fcntl(pipeEnds[1], F_SETFD, FD_CLOEXEC)) { + auto ec = lastPosixError(); + LOGV2_ERROR( + 22832, "Failed to set FD_CLOEXEC on pipe end 1", "error"_attr = errorMessage(ec)); fassertFailed(40317); } #endif @@ -772,8 +772,8 @@ void ProgramRunner::launchProcess(int child_stdout) { &si, &pi) != 0; if (!success) { - const auto ewd = errnoWithDescription(); - ss << "couldn't start process " << _argv[0] << "; " << ewd; + const auto ec = lastSystemError(); + ss << "couldn't start process " << _argv[0] << "; " << errorMessage(ec); uasserted(14042, ss.str()); } @@ -803,8 +803,8 @@ void ProgramRunner::launchProcess(int child_stdout) { if (nativePid == -1) { // Fork failed so it is time for the process to exit - const auto ewd = errnoWithDescription(); - cout << "ProgramRunner is unable to fork child process: " << ewd << endl; + const auto ec = lastPosixError(); + cout << "ProgramRunner is unable to fork child process: " << errorMessage(ec) << endl; fassertFailed(34363); } @@ -968,13 +968,11 @@ BSONObj ResetDbpath(const BSONObj& a, void* data) { // will retry on all errors. auto wpath = toNativeString(path.c_str()); retryWithBackOff([wpath]() { - BOOL ret = CreateDirectoryW(wpath.c_str(), NULL); - if (!ret) { - auto gle = GetLastError(); - uassert(6088702, - str::stream() << "CreateDirectory failed with unexpected error: " - << errnoWithDescription(gle), - gle != ERROR_SUCCESS); + if (!CreateDirectoryW(wpath.c_str(), nullptr)) { + auto ec = lastSystemError(); + uasserted(6088702, + str::stream() + << "CreateDirectory failed with unexpected error: " << errorMessage(ec)); } }); #else @@ -1060,10 +1058,9 @@ inline void kill_wrapper(ProcessId pid, int sig, int port, const BSONObj& opt) { HANDLE event = OpenEventA(EVENT_MODIFY_STATE, FALSE, eventName.c_str()); if (event == nullptr) { - int gle = GetLastError(); - if (gle != ERROR_FILE_NOT_FOUND) { - const auto ewd = errnoWithDescription(); - LOGV2_WARNING(22827, "kill_wrapper OpenEvent failed", "error"_attr = ewd); + auto ec = lastSystemError(); + if (ec != systemError(ERROR_FILE_NOT_FOUND)) { + LOGV2_WARNING(22827, "kill_wrapper OpenEvent failed", "error"_attr = errorMessage(ec)); } else { LOGV2_INFO( 22815, @@ -1109,19 +1106,18 @@ inline void kill_wrapper(ProcessId pid, int sig, int port, const BSONObj& opt) { bool result = SetEvent(event); if (!result) { - const auto ewd = errnoWithDescription(); - LOGV2_ERROR(22833, "kill_wrapper SetEvent failed", "error"_attr = ewd); + auto ec = lastSystemError(); + LOGV2_ERROR(22833, "kill_wrapper SetEvent failed", "error"_attr = errorMessage(ec)); return; } #else - int x = kill(pid.toNative(), sig); - if (x) { - if (errno == ESRCH) { + if (kill(pid.toNative(), sig)) { + auto ec = lastPosixError(); + if (ec == posixError(ESRCH)) { } else { - const auto ewd = errnoWithDescription(); - LOGV2_INFO(22816, "Kill failed", "error"_attr = ewd); + LOGV2_INFO(22816, "Kill failed", "error"_attr = errorMessage(ec)); uasserted(ErrorCodes::UnknownError, - "kill({}, {}) failed: {}"_format(pid.toNative(), sig, ewd)); + "kill({}, {}) failed: {}"_format(pid.toNative(), sig, errorMessage(ec))); } } diff --git a/src/mongo/transport/asio_utils.cpp b/src/mongo/transport/asio_utils.cpp index 8e8368ff586..01ff620ee9e 100644 --- a/src/mongo/transport/asio_utils.cpp +++ b/src/mongo/transport/asio_utils.cpp @@ -114,8 +114,8 @@ StatusWith<unsigned> pollASIOSocket(asio::generic::stream_protocol::socket& sock }; int result = ::select(fd + 1, fdsPtr(0), fdsPtr(1), fdsPtr(2), &timeoutTv); if (result == SOCKET_ERROR) { - auto errDesc = errnoWithDescription(WSAGetLastError()); - return {ErrorCodes::InternalError, errDesc}; + auto ec = lastSocketError(); + return {ErrorCodes::InternalError, errorMessage(ec)}; } else if (result == 0) { return {ErrorCodes::NetworkTimeout, "Timed out waiting for poll"}; } @@ -150,8 +150,8 @@ StatusWith<unsigned> pollASIOSocket(asio::generic::stream_protocol::socket& sock } while (result == -1 && errno == EINTR); if (result == -1) { - int errCode = errno; - return {ErrorCodes::InternalError, errnoWithDescription(errCode)}; + auto ec = lastPosixError(); + return {ErrorCodes::InternalError, errorMessage(ec)}; } else if (result == 0) { return {ErrorCodes::NetworkTimeout, "Timed out waiting for poll"}; } diff --git a/src/mongo/transport/baton_asio_linux.cpp b/src/mongo/transport/baton_asio_linux.cpp index 412c3b98aff..69404e843a7 100644 --- a/src/mongo/transport/baton_asio_linux.cpp +++ b/src/mongo/transport/baton_asio_linux.cpp @@ -66,21 +66,7 @@ struct EventFDHolder { EventFDHolder(const EventFDHolder&) = delete; EventFDHolder& operator=(const EventFDHolder&) = delete; - EventFDHolder() : fd(::eventfd(0, EFD_CLOEXEC)) { - // On error, -1 is returned and `errno` is set - if (fd < 0) { - const auto savedErrno = errno; - const auto errorCode = savedErrno == EMFILE || savedErrno == ENFILE - ? ErrorCodes::TooManyFilesOpen - : ErrorCodes::UnknownError; - Status status(errorCode, - fmt::format("error in creating eventfd: {}, errno: {}", - errnoWithDescription(savedErrno), - savedErrno)); - LOGV2_ERROR(6328201, "Unable to create eventfd object", "error"_attr = status); - iasserted(status); - } - } + EventFDHolder() = default; ~EventFDHolder() { ::close(fd); @@ -106,7 +92,27 @@ struct EventFDHolder { } } - const int fd; +private: + static int _initFd() { + int fd = ::eventfd(0, EFD_CLOEXEC); + // On error, -1 is returned and `errno` is set + if (fd < 0) { + auto ec = lastPosixError(); + const auto errorCode = ec == posixError(EMFILE) || ec == posixError(ENFILE) + ? ErrorCodes::TooManyFilesOpen + : ErrorCodes::UnknownError; + Status status(errorCode, + fmt::format("error in creating eventfd: {}, errno: {}", + errorMessage(ec), + ec.value())); + LOGV2_ERROR(6328201, "Unable to create eventfd object", "error"_attr = status); + iasserted(status); + } + return fd; + } + +public: + const int fd = _initFd(); }; const auto getEventFDForClient = Client::declareDecoration<EventFDHolder>(); @@ -349,9 +355,10 @@ std::list<Promise<void>> TransportLayerASIO::BatonASIO::_poll(stdx::unique_lock< blockBatonASIOBeforePoll.pauseWhileSet(); int timeout = deadline ? Milliseconds(*deadline - now).count() : -1; int events = ::poll(_pollSet.data(), _pollSet.size(), timeout); - const auto savedErrno = errno; - if (events < 0 && savedErrno != EINTR) { - LOGV2_FATAL(50834, "error in poll", "error"_attr = errnoWithDescription(savedErrno)); + if (events < 0) { + auto ec = lastSystemError(); + if (ec != systemError(EINTR)) + LOGV2_FATAL(50834, "error in poll", "error"_attr = errorMessage(ec)); } return events; }(); diff --git a/src/mongo/transport/service_executor_utils.cpp b/src/mongo/transport/service_executor_utils.cpp index 43e505d7d71..7dcdb6cab8d 100644 --- a/src/mongo/transport/service_executor_utils.cpp +++ b/src/mongo/transport/service_executor_utils.cpp @@ -86,11 +86,10 @@ Status launchServiceWorkerThread(unique_function<void()> task) noexcept { if (limits.rlim_cur >= kStackSize) { int failed = pthread_attr_setstacksize(&attrs, kStackSize); if (failed) { - const auto ewd = errnoWithDescription(failed); LOGV2_WARNING(22949, "pthread_attr_setstacksize failed: {error}", "pthread_attr_setstacksize failed", - "error"_attr = ewd); + "error"_attr = errorMessage(posixError(failed))); } } else if (limits.rlim_cur < kStackSize) { LOGV2_WARNING(22950, @@ -116,17 +115,17 @@ Status launchServiceWorkerThread(unique_function<void()> task) noexcept { {logv2::UserAssertAfterLog()}, "pthread_create failed: error: {error}", "pthread_create failed", - "error"_attr = errnoWithDescription(failed)); + "error"_attr = errorMessage(posixError(failed))); } else if (failed < 0) { - auto savedErrno = errno; + auto ec = lastPosixError(); LOGV2_ERROR_OPTIONS(4850901, {logv2::UserAssertAfterLog()}, "pthread_create failed with a negative return code: {code}, errno: " "{errno}, error: {error}", "pthread_create failed with a negative return code", "code"_attr = failed, - "errno"_attr = savedErrno, - "error"_attr = errnoWithDescription(savedErrno)); + "errno"_attr = ec.value(), + "error"_attr = errorMessage(ec)); } ctx.release(); diff --git a/src/mongo/transport/transport_layer_asio.cpp b/src/mongo/transport/transport_layer_asio.cpp index 3c93c105dad..e2fc9c5eb52 100644 --- a/src/mongo/transport/transport_layer_asio.cpp +++ b/src/mongo/transport/transport_layer_asio.cpp @@ -913,8 +913,8 @@ namespace { bool trySetSockOpt(int level, int opt, int val) { auto sock = ::socket(AF_INET, SOCK_STREAM, 0); if (sock == -1) { - int ec = errno; - LOGV2_WARNING(5128700, "socket() failed", "error"_attr = errnoWithDescription(ec)); + auto ec = lastSocketError(); + LOGV2_WARNING(5128700, "socket() failed", "error"_attr = errorMessage(ec)); return false; } @@ -1112,13 +1112,16 @@ Status TransportLayerASIO::setup() { for (const auto& addr : endpoints) { #ifndef _WIN32 if (addr.family() == AF_UNIX) { - if (::unlink(addr.toString().c_str()) == -1 && errno != ENOENT) { - LOGV2_ERROR(23024, - "Failed to unlink socket file {path} {error}", - "Failed to unlink socket file", - "path"_attr = addr.toString().c_str(), - "error"_attr = errnoWithDescription(errno)); - fassertFailedNoTrace(40486); + if (::unlink(addr.toString().c_str()) == -1) { + auto ec = lastPosixError(); + if (ec != posixError(ENOENT)) { + LOGV2_ERROR(23024, + "Failed to unlink socket file {path} {error}", + "Failed to unlink socket file", + "path"_attr = addr.toString().c_str(), + "error"_attr = errorMessage(ec)); + fassertFailedNoTrace(40486); + } } } #endif @@ -1188,11 +1191,12 @@ Status TransportLayerASIO::setup() { #ifndef _WIN32 if (addr.family() == AF_UNIX) { if (::chmod(addr.toString().c_str(), serverGlobalParams.unixSocketPermissions) == -1) { + auto ec = lastPosixError(); LOGV2_ERROR(23026, "Failed to chmod socket file {path} {error}", "Failed to chmod socket file", "path"_attr = addr.toString().c_str(), - "error"_attr = errnoWithDescription(errno)); + "error"_attr = errorMessage(ec)); fassertFailedNoTrace(40487); } } @@ -1288,12 +1292,12 @@ void TransportLayerASIO::_runListener() noexcept { LOGV2( 23017, "removing socket file: {path}", "removing socket file", "path"_attr = path); if (::unlink(path.c_str()) != 0) { - const auto ewd = errnoWithDescription(); + auto ec = lastPosixError(); LOGV2_WARNING(23022, "Unable to remove UNIX socket {path}: {error}", "Unable to remove UNIX socket", "path"_attr = path, - "error"_attr = ewd); + "error"_attr = errorMessage(ec)); } } } diff --git a/src/mongo/unittest/death_test.cpp b/src/mongo/unittest/death_test.cpp index cf191a9dc34..8365ed5f5cf 100644 --- a/src/mongo/unittest/death_test.cpp +++ b/src/mongo/unittest/death_test.cpp @@ -82,19 +82,20 @@ public: using std::runtime_error::runtime_error; }; -#define LOG_AND_THROW_WITH_ERRNO(expr) logAndThrowWithErrnoAt(expr, __FILE__, __LINE__, errno) +#define LOG_AND_THROW_WITH_ERRNO(expr) logAndThrowWithErrnoAt(expr, __FILE__, __LINE__) -void logAndThrowWithErrnoAt(StringData expr, StringData file, unsigned line, int err) { +void logAndThrowWithErrnoAt(StringData expr, StringData file, unsigned line) { + auto ec = lastPosixError(); LOGV2_ERROR(24138, "{expr} failed: {error} @{file}:{line}", "expression failed", "expr"_attr = expr, - "error"_attr = errnoWithDescription(err), + "error"_attr = errorMessage(ec), "file"_attr = file, "line"_attr = line); breakpoint(); throw DeathTestSyscallException( - "{} failed: {} @{}:{}"_format(expr, errnoWithDescription(err), file, line)); + "{} failed: {} @{}:{}"_format(expr, errorMessage(ec), file, line)); } diff --git a/src/mongo/util/concurrency/thread_name.cpp b/src/mongo/util/concurrency/thread_name.cpp index 1a950c24bfa..b5f81ea16cf 100644 --- a/src/mongo/util/concurrency/thread_name.cpp +++ b/src/mongo/util/concurrency/thread_name.cpp @@ -144,7 +144,7 @@ void setOSThreadName(StringData threadName) { LOGV2(23102, "Ignoring error from setting thread name: {error}", "Ignoring error from setting thread name", - "error"_attr = errnoWithDescription(error)); + "error"_attr = errorMessage(posixError(error))); } #elif defined(__linux__) && defined(MONGO_CONFIG_HAVE_PTHREAD_SETNAME_NP) // Do not set thread name on the main() thread. Setting the name on main thread breaks @@ -168,7 +168,7 @@ void setOSThreadName(StringData threadName) { LOGV2(23103, "Ignoring error from setting thread name: {error}", "Ignoring error from setting thread name", - "error"_attr = errnoWithDescription(error)); + "error"_attr = errorMessage(posixError(error))); } } #endif diff --git a/src/mongo/util/concurrency/ticketholder.cpp b/src/mongo/util/concurrency/ticketholder.cpp index 30523f97f0f..fa413e52133 100644 --- a/src/mongo/util/concurrency/ticketholder.cpp +++ b/src/mongo/util/concurrency/ticketholder.cpp @@ -54,7 +54,7 @@ namespace { void failWithErrno(int err) { LOGV2_FATAL(28604, "error in Ticketholder: {errnoWithDescription_err}", - "errnoWithDescription_err"_attr = errnoWithDescription(err)); + "errnoWithDescription_err"_attr = errorMessage(posixError(err))); } /* diff --git a/src/mongo/util/dns_query_windows-impl.h b/src/mongo/util/dns_query_windows-impl.h index 84653c7a486..ebb97bf520e 100644 --- a/src/mongo/util/dns_query_windows-impl.h +++ b/src/mongo/util/dns_query_windows-impl.h @@ -279,16 +279,16 @@ public: const DNSQueryClass class_, const DNSQueryType type) { PDNS_RECORDA queryResults; - auto ec = DnsQuery_UTF8(service.c_str(), - WORD(type), - DNS_QUERY_BYPASS_CACHE, - nullptr, - reinterpret_cast<PDNS_RECORD*>(&queryResults), - nullptr); - - if (ec) { + auto e = DnsQuery_UTF8(service.c_str(), + WORD(type), + DNS_QUERY_BYPASS_CACHE, + nullptr, + reinterpret_cast<PDNS_RECORD*>(&queryResults), + nullptr); + if (e) { + auto ec = systemError(e); uasserted(ErrorCodes::DNSHostNotFound, - "Failed to look up service \""s + "\":"s + errnoWithDescription(ec)); + "Failed to look up service \""s + "\":"s + errorMessage(ec)); } return DNSResponse{service, queryResults}; } diff --git a/src/mongo/util/errno_util.cpp b/src/mongo/util/errno_util.cpp index 6e75b4b511a..a9c326f3ae8 100644 --- a/src/mongo/util/errno_util.cpp +++ b/src/mongo/util/errno_util.cpp @@ -33,10 +33,34 @@ #include <fmt/format.h> #include <system_error> +#ifndef _WIN32 +#include <netdb.h> +#endif + namespace mongo { using namespace fmt::literals; +class AddrInfoErrorCategory : public std::error_category { +public: + const char* name() const noexcept override { + return "getaddrinfo"; + } + + std::string message(int e) const override { +#ifdef _WIN32 + return systemError(e).message(); +#else + return gai_strerror(e); +#endif + } +}; + +const std::error_category& addrInfoCategory() { + static auto p = new AddrInfoErrorCategory; + return *p; +} + std::string errorMessage(std::error_code ec) { std::string r = ec.message(); bool vague = false; diff --git a/src/mongo/util/errno_util.h b/src/mongo/util/errno_util.h index 0464c38a409..408cebf528c 100644 --- a/src/mongo/util/errno_util.h +++ b/src/mongo/util/errno_util.h @@ -37,6 +37,29 @@ namespace mongo { /** + * Returns category to use for POSIX errno error codes. + * On POSIX, `errno` codes are the `std::system_category`. + * On Windows, the `errno` codes are the `std::generic_category`. + */ +inline const std::error_category& posixCategory() { +#ifdef _WIN32 + return std::generic_category(); +#else + return std::system_category(); +#endif +} + +/** Wraps POSIX `errno` value in an appropriate `std::error_code`. */ +inline std::error_code posixError(int e) { + return std::error_code(e, posixCategory()); +} + +/** Wraps `e` in a `std::error_code` with `std::system_category`. */ +inline std::error_code systemError(int e) { + return std::error_code(e, std::system_category()); +} + +/** * Returns `{errno, std::generic_category()}`. * Windows has both Windows errors and POSIX errors. That is, there's a * `GetLastError` and an `errno`. They are tracked separately, and unrelated to @@ -48,22 +71,25 @@ namespace mongo { * On POSIX systems, `std::system_category` is potentially a superset of * `std::generic_category`, so `lastSystemError` should be preferred for * handling system errors. + * + * Guaranteed to not modify `errno`. */ inline std::error_code lastPosixError() { - return std::error_code(errno, std::generic_category()); + return posixError(errno); } /** * On POSIX, returns `{errno, std::system_category()}`. * On Windows, returns `{GetLastError(), std::system_category()}`, but see `lastPosixError`. + * + * Guaranteed to not modify the system error code variable. */ inline std::error_code lastSystemError() { #ifdef _WIN32 - int e = GetLastError(); + return systemError(GetLastError()); #else - int e = errno; + return systemError(errno); #endif - return std::error_code(e, std::system_category()); } /** @@ -77,14 +103,30 @@ inline std::error_code lastSystemError() { */ std::string errorMessage(std::error_code ec); -/** A system error code's error message. */ -inline std::string errnoWithDescription(int e) { - return errorMessage(std::error_code{e, std::system_category()}); +/** + * A category for `getaddrinfo` or `getnameinfo` (i.e. the netdb.h library) + * results. Uses `gai_error` on Unix systems. On Windows, these errors are + * compatible with the system error space. + */ +const std::error_category& addrInfoCategory(); + +/** Wrap `e` in a `std::error_code` with `addrInfoCategory`. */ +inline std::error_code addrInfoError(int e) { + return std::error_code(e, addrInfoCategory()); } -/** The last system error code's error message. */ -inline std::string errnoWithDescription() { - return errorMessage(lastSystemError()); +/** + * Portable wrapper for socket API calls. On POSIX platforms this is just + * `lastSystemError`. On Windows, Winsock API callers must query last error with + * `WSAGetLastError` instead of `GetLastError`. The Winsock errors can use the + * same error code category as other Windows API calls. + */ +inline std::error_code lastSocketError() { +#ifdef _WIN32 + return systemError(WSAGetLastError()); +#else + return lastSystemError(); +#endif } } // namespace mongo diff --git a/src/mongo/util/errno_util_test.cpp b/src/mongo/util/errno_util_test.cpp index e39a8b66175..670b7c7304d 100644 --- a/src/mongo/util/errno_util_test.cpp +++ b/src/mongo/util/errno_util_test.cpp @@ -37,37 +37,49 @@ #include "mongo/unittest/unittest.h" #include "mongo/util/errno_util.h" +namespace mongo { namespace { -using namespace mongo; const std::string kUnknownError = "Unknown error"; -TEST(ErrnoWithDescription, CommonErrors) { +/** Force a predictable error message language. */ +void initLanguage() { #if defined(_WIN32) - // Force error messages to be returned in en-US. LANGID lang = MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US); ASSERT_EQ(SetThreadUILanguage(lang), lang); - - ASSERT_STRING_OMITS(errnoWithDescription(ERROR_SUCCESS), kUnknownError); - ASSERT_STRING_OMITS(errnoWithDescription(ERROR_FILE_NOT_FOUND), kUnknownError); - ASSERT_STRING_OMITS(errnoWithDescription(ERROR_PATH_NOT_FOUND), kUnknownError); - ASSERT_STRING_OMITS(errnoWithDescription(ERROR_TOO_MANY_OPEN_FILES), kUnknownError); - ASSERT_STRING_OMITS(errnoWithDescription(ERROR_ACCESS_DENIED), kUnknownError); - ASSERT_STRING_OMITS(errnoWithDescription(ERROR_PRIVILEGE_NOT_HELD), kUnknownError); #else - // Force the minimal locale to ensure the standard error message localization text. ASSERT(setlocale(LC_MESSAGES, "C")); +#endif +} - ASSERT_STRING_OMITS(errnoWithDescription(EPERM), kUnknownError); - ASSERT_STRING_OMITS(errnoWithDescription(ENOENT), kUnknownError); - ASSERT_STRING_OMITS(errnoWithDescription(EIO), kUnknownError); - ASSERT_STRING_OMITS(errnoWithDescription(EBADF), kUnknownError); - ASSERT_STRING_OMITS(errnoWithDescription(ENOMEM), kUnknownError); - ASSERT_STRING_OMITS(errnoWithDescription(EACCES), kUnknownError); +TEST(ErrnoWithDescription, CommonErrors) { +#if defined(_WIN32) + static const std::array knownErrors{ + ERROR_SUCCESS, + ERROR_FILE_NOT_FOUND, + ERROR_PATH_NOT_FOUND, + ERROR_TOO_MANY_OPEN_FILES, + ERROR_ACCESS_DENIED, + ERROR_PRIVILEGE_NOT_HELD, + }; +#else + static const std::array knownErrors{ + EPERM, + ENOENT, + EIO, + EBADF, + ENOMEM, + EACCES, + }; #endif - // INT_MAX is currently invalid. In the unlikely event that it becomes valid, then this check - // will have to be removed or adjusted. - ASSERT_STRING_CONTAINS(errnoWithDescription(INT_MAX), kUnknownError); + initLanguage(); + + for (auto e : knownErrors) + ASSERT_STRING_OMITS(errorMessage(systemError(e)), kUnknownError); + + // Update if INT_MAX becomes a valid code. + ASSERT_STRING_CONTAINS(errorMessage(systemError(INT_MAX)), kUnknownError); } } // namespace +} // namespace mongo diff --git a/src/mongo/util/exception_filter_win32.cpp b/src/mongo/util/exception_filter_win32.cpp index ce8e30ebbdb..a78820335a5 100644 --- a/src/mongo/util/exception_filter_win32.cpp +++ b/src/mongo/util/exception_filter_win32.cpp @@ -62,11 +62,11 @@ void doMinidumpWithException(struct _EXCEPTION_POINTERS* exceptionInfo) { DWORD ret = GetModuleFileNameW(nullptr, &moduleFileName[0], ARRAYSIZE(moduleFileName)); if (ret == 0) { - int gle = GetLastError(); + auto ec = lastSystemError(); LOGV2(23130, "GetModuleFileName failed {error}", "GetModuleFileName failed", - "error"_attr = errnoWithDescription(gle)); + "error"_attr = errorMessage(ec)); // Fallback name wcscpy_s(moduleFileName, L"mongo"); @@ -88,12 +88,12 @@ void doMinidumpWithException(struct _EXCEPTION_POINTERS* exceptionInfo) { HANDLE hFile = CreateFileW( dumpName.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (INVALID_HANDLE_VALUE == hFile) { - DWORD lasterr = GetLastError(); + auto ec = lastSystemError(); LOGV2(23131, "Failed to open minidump file {dumpName}: {error}", "Failed to open minidump file", "dumpName"_attr = toUtf8String(dumpName.c_str()), - "error"_attr = errnoWithDescription(lasterr)); + "error"_attr = errorMessage(ec)); return; } @@ -122,11 +122,11 @@ void doMinidumpWithException(struct _EXCEPTION_POINTERS* exceptionInfo) { nullptr, nullptr); if (FALSE == bstatus) { - DWORD lasterr = GetLastError(); + auto ec = lastSystemError(); LOGV2(23133, "Failed to create minidump: {error}", "Failed to create minidump", - "error"_attr = errnoWithDescription(lasterr)); + "error"_attr = errorMessage(ec)); } CloseHandle(hFile); diff --git a/src/mongo/util/file.cpp b/src/mongo/util/file.cpp index 42af8332d4b..69570df96fa 100644 --- a/src/mongo/util/file.cpp +++ b/src/mongo/util/file.cpp @@ -71,23 +71,23 @@ intmax_t File::freeSpace(const std::string& path) { nullptr)) { // ptr to returned total free return avail.QuadPart; } - DWORD dosError = GetLastError(); + auto ec = lastSystemError(); LOGV2(23140, "In File::freeSpace(), GetDiskFreeSpaceEx for '{path}' failed with {error}", "In File::freeSpace(), GetDiskFreeSpaceEx failed", "path"_attr = path, - "error"_attr = errnoWithDescription(dosError)); + "error"_attr = errorMessage(ec)); return -1; } void File::fsync() const { if (FlushFileBuffers(_handle) == 0) { - DWORD dosError = GetLastError(); + auto ec = lastSystemError(); LOGV2(23141, "In File::fsync(), FlushFileBuffers for '{fileName}' failed with {error}", "In File::fsync(), FlushFileBuffers failed", "fileName"_attr = _name, - "error"_attr = errnoWithDescription(dosError)); + "error"_attr = errorMessage(ec)); } } @@ -101,12 +101,12 @@ fileofs File::len() { return li.QuadPart; } _bad = true; - DWORD dosError = GetLastError(); + auto ec = lastSystemError(); LOGV2(23142, "In File::len(), GetFileSizeEx for '{fileName}' failed with {error}", "In File::len(), GetFileSizeEx failed", "fileName"_attr = _name, - "error"_attr = errnoWithDescription(dosError)); + "error"_attr = errorMessage(ec)); return 0; } @@ -121,12 +121,12 @@ void File::open(const char* filename, bool readOnly, bool direct) { nullptr); // template _bad = !is_open(); if (_bad) { - DWORD dosError = GetLastError(); + auto ec = lastSystemError(); LOGV2(23143, "In File::open(), CreateFileW for '{fileName}' failed with {error}", "In File::open(), CreateFileW failed", "fileName"_attr = _name, - "error"_attr = errnoWithDescription(dosError)); + "error"_attr = errorMessage(ec)); } } @@ -135,25 +135,25 @@ void File::read(fileofs o, char* data, unsigned len) { li.QuadPart = o; if (SetFilePointerEx(_handle, li, nullptr, FILE_BEGIN) == 0) { _bad = true; - DWORD dosError = GetLastError(); + auto ec = lastSystemError(); LOGV2(23144, "In File::read(), SetFilePointerEx for '{fileName}' tried to set the file pointer to " "{failPointer} but failed with {error}", "In File::read(), SetFilePointerEx failed to set file pointer", "fileName"_attr = _name, "failPointer"_attr = o, - "error"_attr = errnoWithDescription(dosError)); + "error"_attr = errorMessage(ec)); return; } DWORD bytesRead; if (!ReadFile(_handle, data, len, &bytesRead, 0)) { _bad = true; - DWORD dosError = GetLastError(); + auto ec = lastSystemError(); LOGV2(23145, "In File::read(), ReadFile for '{fileName}' failed with {error}", "In File::read(), ReadFile failed", "fileName"_attr = _name, - "error"_attr = errnoWithDescription(dosError)); + "error"_attr = errorMessage(ec)); } else if (bytesRead != len) { _bad = true; msgasserted(10438, @@ -171,24 +171,24 @@ void File::truncate(fileofs size) { li.QuadPart = size; if (SetFilePointerEx(_handle, li, nullptr, FILE_BEGIN) == 0) { _bad = true; - DWORD dosError = GetLastError(); + auto ec = lastSystemError(); LOGV2(23146, "In File::truncate(), SetFilePointerEx for '{fileName}' tried to set the file " "pointer to {filePointer} but failed with {error}", "In File::truncate(), SetFilePointerEx failed to set file pointer", "fileName"_attr = _name, "filePointer"_attr = size, - "error"_attr = errnoWithDescription(dosError)); + "error"_attr = errorMessage(ec)); return; } if (SetEndOfFile(_handle) == 0) { _bad = true; - DWORD dosError = GetLastError(); + auto ec = lastSystemError(); LOGV2(23147, "In File::truncate(), SetEndOfFile for '{fileName}' failed with {error}", "In File::truncate(), SetEndOfFile failed", "fileName"_attr = _name, - "error"_attr = errnoWithDescription(dosError)); + "error"_attr = errorMessage(ec)); } } @@ -197,7 +197,7 @@ void File::write(fileofs o, const char* data, unsigned len) { li.QuadPart = o; if (SetFilePointerEx(_handle, li, nullptr, FILE_BEGIN) == 0) { _bad = true; - DWORD dosError = GetLastError(); + auto ec = lastSystemError(); LOGV2( 23148, "In File::write(), SetFilePointerEx for '{fileName}' tried to set the file pointer to " @@ -205,13 +205,13 @@ void File::write(fileofs o, const char* data, unsigned len) { "In File::write(), SetFilePointerEx failed to set file pointer", "fileName"_attr = _name, "filePointer"_attr = o, - "error"_attr = errnoWithDescription(dosError)); + "error"_attr = errorMessage(ec)); return; } DWORD bytesWritten; if (WriteFile(_handle, data, len, &bytesWritten, nullptr) == 0) { _bad = true; - DWORD dosError = GetLastError(); + auto ec = lastSystemError(); LOGV2(23149, "In File::write(), WriteFile for '{fileName}' tried to write {bytesToWrite} bytes " "but only wrote {bytesWritten} bytes, failing with {error}", @@ -219,7 +219,7 @@ void File::write(fileofs o, const char* data, unsigned len) { "fileName"_attr = _name, "bytesToWrite"_attr = len, "bytesWritten"_attr = bytesWritten, - "error"_attr = errnoWithDescription(dosError)); + "error"_attr = errorMessage(ec)); } } @@ -239,21 +239,23 @@ intmax_t File::freeSpace(const std::string& path) { if (statvfs(path.c_str(), &info) == 0) { return static_cast<intmax_t>(info.f_bavail) * info.f_frsize; } + auto ec = lastSystemError(); LOGV2(23150, "In File::freeSpace(), statvfs for '{path}' failed with {error}", "In File::freeSpace(), statvfs failed", "path"_attr = path, - "error"_attr = errnoWithDescription()); + "error"_attr = errorMessage(ec)); return -1; } void File::fsync() const { if (::fsync(_fd)) { + auto ec = lastSystemError(); LOGV2(23151, "In File::fsync(), ::fsync for '{fileName}' failed with {error}", "In File::fsync(), ::fsync failed", "fileName"_attr = _name, - "error"_attr = errnoWithDescription()); + "error"_attr = errorMessage(ec)); } } @@ -267,11 +269,12 @@ fileofs File::len() { return o; } _bad = true; + auto ec = lastSystemError(); LOGV2(23152, "In File::len(), lseek for '{fileName}' failed with {error}", "In File::len(), lseek failed", "fileName"_attr = _name, - "error"_attr = errnoWithDescription()); + "error"_attr = errorMessage(ec)); return 0; } @@ -290,23 +293,25 @@ void File::open(const char* filename, bool readOnly, bool direct) { S_IRUSR | S_IWUSR); _bad = !is_open(); if (_bad) { + auto ec = lastSystemError(); LOGV2(23153, "In File::open(), ::open for '{fileName}' failed with {error}", "In File::open(), ::open failed", "fileName"_attr = _name, - "error"_attr = errnoWithDescription()); + "error"_attr = errorMessage(ec)); } } void File::read(fileofs o, char* data, unsigned len) { ssize_t bytesRead = ::pread(_fd, data, len, o); if (bytesRead == -1) { + auto ec = lastSystemError(); _bad = true; LOGV2(23154, "In File::read(), ::pread for '{fileName}' failed with {error}", "In File::read(), ::pread failed", "fileName"_attr = _name, - "error"_attr = errnoWithDescription()); + "error"_attr = errorMessage(ec)); } else if (bytesRead != static_cast<ssize_t>(len)) { _bad = true; msgasserted(16569, @@ -321,6 +326,7 @@ void File::truncate(fileofs size) { return; } if (ftruncate(_fd, size) != 0) { + auto ec = lastSystemError(); _bad = true; LOGV2(23155, "In File::truncate(), ftruncate for '{fileName}' tried to set the file pointer to " @@ -328,7 +334,7 @@ void File::truncate(fileofs size) { "In File::truncate(), ftruncate failed to set file pointer", "fileName"_attr = _name, "filePointer"_attr = size, - "error"_attr = errnoWithDescription()); + "error"_attr = errorMessage(ec)); return; } } @@ -336,6 +342,9 @@ void File::truncate(fileofs size) { void File::write(fileofs o, const char* data, unsigned len) { ssize_t bytesWritten = ::pwrite(_fd, data, len, o); if (bytesWritten != static_cast<ssize_t>(len)) { + std::error_code ec; + if (bytesWritten == -1) + ec = lastSystemError(); _bad = true; LOGV2(23156, "In File::write(), ::pwrite for '{fileName}' tried to write {bytesToWrite} bytes but " @@ -344,7 +353,7 @@ void File::write(fileofs o, const char* data, unsigned len) { "fileName"_attr = _name, "bytesToWrite"_attr = len, "bytesWritten"_attr = bytesWritten, - "error"_attr = errnoWithDescription()); + "error"_attr = errorMessage(ec)); } } diff --git a/src/mongo/util/net/hostname_canonicalization.cpp b/src/mongo/util/net/hostname_canonicalization.cpp index f11ee345480..e43979b0711 100644 --- a/src/mongo/util/net/hostname_canonicalization.cpp +++ b/src/mongo/util/net/hostname_canonicalization.cpp @@ -91,15 +91,15 @@ StatusWith<std::vector<std::string>> getHostFQDNs(std::string hostName, int err; auto nativeHostName = shim_toNativeString(hostName.c_str()); if ((err = shim_getaddrinfo(nativeHostName.c_str(), nullptr, &hints, &info)) != 0) { - auto errorStr = getAddrInfoStrError(err); + auto ec = addrInfoError(err); LOGV2_DEBUG(23170, 3, "Failed to obtain address information for host {hostName}: {error}", "Failed to obtain address information for host", "hostName"_attr = hostName, - "error"_attr = errorStr); + "error"_attr = errorMessage(ec)); - return Status(ErrorCodes::BadValue, errorStr); + return Status(ErrorCodes::BadValue, errorMessage(ec)); } const ScopeGuard guard(shim_freeaddrinfo); @@ -137,7 +137,7 @@ StatusWith<std::vector<std::string>> getHostFQDNs(std::string hostName, getNameInfoError << "Unknown address family: " << p->ai_family; } - getNameInfoError << ": \"" << getAddrInfoStrError(err); + getNameInfoError << ": \"" << errorMessage(addrInfoError(err)); } getNameInfoErrors.push_back(getNameInfoError.str()); } diff --git a/src/mongo/util/net/http_client_winhttp.cpp b/src/mongo/util/net/http_client_winhttp.cpp index d972e60065e..993dfa9ab72 100644 --- a/src/mongo/util/net/http_client_winhttp.cpp +++ b/src/mongo/util/net/http_client_winhttp.cpp @@ -175,9 +175,11 @@ public: MONGO_UNREACHABLE; } - const auto uassertWithErrno = [](StringData reason, bool ok) { - const auto msg = errnoWithDescription(GetLastError()); - uassert(ErrorCodes::OperationFailed, str::stream() << reason << ": " << msg, ok); + const auto uassertWithLastSystemError = [](StringData reason, bool ok) { + auto ec = lastSystemError(); + uassert(ErrorCodes::OperationFailed, + str::stream() << reason << ": " << errorMessage(ec), + ok); }; // Break down URL for handling below. @@ -210,23 +212,24 @@ public: WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); - uassertWithErrno("Failed creating an HTTP session", session); + uassertWithLastSystemError("Failed creating an HTTP session", session); DWORD setting; DWORD settingLength = sizeof(setting); setting = WINHTTP_OPTION_REDIRECT_POLICY_NEVER; - uassertWithErrno( + uassertWithLastSystemError( "Failed setting HTTP session option", WinHttpSetOption(session, WINHTTP_OPTION_REDIRECT_POLICY, &setting, settingLength)); DWORD connectTimeout = durationCount<Milliseconds>(_connectTimeout); DWORD totalTimeout = durationCount<Milliseconds>(_timeout); - uassertWithErrno("Failed setting HTTP timeout", - WinHttpSetTimeouts( - session, connectTimeout, connectTimeout, totalTimeout, totalTimeout)); + uassertWithLastSystemError( + "Failed setting HTTP timeout", + WinHttpSetTimeouts( + session, connectTimeout, connectTimeout, totalTimeout, totalTimeout)); connect = WinHttpConnect(session, url.hostname.c_str(), url.port, 0); - uassertWithErrno("Failed connecting to remote host", connect); + uassertWithLastSystemError("Failed connecting to remote host", connect); request = WinHttpOpenRequest(connect, method, @@ -235,7 +238,7 @@ public: WINHTTP_NO_REFERER, const_cast<LPCWSTR*>(kAcceptTypes), url.https ? WINHTTP_FLAG_SECURE : 0); - uassertWithErrno("Failed initializing HTTP request", request); + uassertWithLastSystemError("Failed initializing HTTP request", request); if (!url.username.empty() || !url.password.empty()) { auto result = WinHttpSetCredentials(request, @@ -244,50 +247,50 @@ public: url.username.c_str(), url.password.c_str(), 0); - uassertWithErrno("Failed setting authentication credentials", result); + uassertWithLastSystemError("Failed setting authentication credentials", result); } - uassertWithErrno( + uassertWithLastSystemError( "Failed sending HTTP request", WinHttpSendRequest(request, _headers.c_str(), -1L, data, data_len, data_len, 0)); if (!WinHttpReceiveResponse(request, nullptr)) { // Carve out timeout which doesn't translate well. - const auto err = GetLastError(); - if (err == ERROR_WINHTTP_TIMEOUT) { + auto ec = lastSystemError(); + if (ec == systemError(ERROR_WINHTTP_TIMEOUT)) { uasserted(ErrorCodes::OperationFailed, "Timeout was reached"); } - const auto msg = errnoWithDescription(err); uasserted(ErrorCodes::OperationFailed, str::stream() << "Failed receiving response from server" - << ": " << msg); + << ": " << errorMessage(ec)); } DWORD statusCode = 0; DWORD statusCodeLength = sizeof(statusCode); - uassertWithErrno("Error querying status from server", - WinHttpQueryHeaders(request, - WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, - WINHTTP_HEADER_NAME_BY_INDEX, - &statusCode, - &statusCodeLength, - WINHTTP_NO_HEADER_INDEX)); + uassertWithLastSystemError( + "Error querying status from server", + WinHttpQueryHeaders(request, + WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, + WINHTTP_HEADER_NAME_BY_INDEX, + &statusCode, + &statusCodeLength, + WINHTTP_NO_HEADER_INDEX)); DWORD len = 0; std::vector<char> buffer; DataBuilder ret(4096); for (;;) { len = 0; - uassertWithErrno("Failed receiving response data", - WinHttpQueryDataAvailable(request, &len)); + uassertWithLastSystemError("Failed receiving response data", + WinHttpQueryDataAvailable(request, &len)); if (!len) { break; } buffer.resize(len); - uassertWithErrno("Failed reading response data", - WinHttpReadData(request, buffer.data(), len, &len)); + uassertWithLastSystemError("Failed reading response data", + WinHttpReadData(request, buffer.data(), len, &len)); ConstDataRange cdr(buffer.data(), len); ret.writeAndAdvance(cdr); @@ -302,13 +305,13 @@ public: WINHTTP_NO_HEADER_INDEX) && (GetLastError() == ERROR_INSUFFICIENT_BUFFER)) { buffer.resize(len); - uassertWithErrno("Error querying headers from server", - WinHttpQueryHeaders(request, - WINHTTP_QUERY_RAW_HEADERS_CRLF, - WINHTTP_HEADER_NAME_BY_INDEX, - &buffer[0], - &len, - WINHTTP_NO_HEADER_INDEX)); + uassertWithLastSystemError("Error querying headers from server", + WinHttpQueryHeaders(request, + WINHTTP_QUERY_RAW_HEADERS_CRLF, + WINHTTP_HEADER_NAME_BY_INDEX, + &buffer[0], + &len, + WINHTTP_NO_HEADER_INDEX)); headers.writeAndAdvance(ConstDataRange(buffer.data(), len)); } diff --git a/src/mongo/util/net/sock.cpp b/src/mongo/util/net/sock.cpp index 3a42470524a..9420f7d7946 100644 --- a/src/mongo/util/net/sock.cpp +++ b/src/mongo/util/net/sock.cpp @@ -96,13 +96,9 @@ bool setBlock(int fd, bool block) { #endif } -void networkWarnWithDescription(const Socket& socket, StringData call, int errorCode = -1) { -#ifdef _WIN32 - if (errorCode == -1) { - errorCode = WSAGetLastError(); - } -#endif - auto ewd = errnoWithDescription(errorCode); +void networkWarnWithDescription(const Socket& socket, + StringData call, + std::error_code ec = lastSocketError()) { LOGV2_WARNING(23190, "failed to connect to {remoteSocketAddress}:{remoteSocketAddressPort}, " "in({call}), reason: {error}", @@ -110,7 +106,7 @@ void networkWarnWithDescription(const Socket& socket, StringData call, int error "remoteSocketAddress"_attr = socket.remoteAddr().getAddr(), "remoteSocketAddressPort"_attr = socket.remoteAddr().getPort(), "call"_attr = call, - "error"_attr = ewd); + "error"_attr = errorMessage(ec)); } const double kMaxConnectTimeoutMS = 5000; @@ -122,18 +118,22 @@ void setSockTimeouts(int sock, double secs) { DWORD timeout = secs * 1000; // Windows timeout is a DWORD, in milliseconds. int status = setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<char*>(&timeout), sizeof(DWORD)); - if (report && (status == SOCKET_ERROR)) + if (report && (status == SOCKET_ERROR)) { + auto ec = lastSocketError(); LOGV2(23177, "unable to set SO_RCVTIMEO: {reason}", "Unable to set SO_RCVTIMEO", - "reason"_attr = errnoWithDescription(WSAGetLastError())); + "reason"_attr = errorMessage(ec)); + } status = setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<char*>(&timeout), sizeof(DWORD)); - if (kDebugBuild && report && (status == SOCKET_ERROR)) + if (kDebugBuild && report && (status == SOCKET_ERROR)) { + auto ec = lastSocketError(); LOGV2(23178, "unable to set SO_SNDTIMEO: {reason}", "Unable to set SO_SNDTIME0", - "reason"_attr = errnoWithDescription(WSAGetLastError())); + "reason"_attr = errorMessage(ec)); + } #else struct timeval tv; tv.tv_sec = (int)secs; @@ -157,41 +157,37 @@ void disableNagle(int sock) { const int level = SOL_SOCKET; #endif - if (setsockopt(sock, level, TCP_NODELAY, (char*)&x, sizeof(x))) + if (setsockopt(sock, level, TCP_NODELAY, (char*)&x, sizeof(x))) { + auto ec = lastSocketError(); LOGV2_ERROR(23195, "disableNagle failed: {error}", "DisableNagle failed", - "error"_attr = errnoWithDescription()); + "error"_attr = errorMessage(ec)); + } #ifdef SO_KEEPALIVE - if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char*)&x, sizeof(x))) + if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char*)&x, sizeof(x))) { + auto ec = lastSocketError(); LOGV2_ERROR(23196, "SO_KEEPALIVE failed: {error}", "SO_KEEPALIVE failed", - "error"_attr = errnoWithDescription()); + "error"_attr = errorMessage(ec)); + } #endif setSocketKeepAliveParams(sock, logv2::LogSeverity::Error()); } -int socketGetLastError() { -#ifdef _WIN32 - return WSAGetLastError(); -#else - return errno; -#endif -} - SockAddr getLocalAddrForBoundSocketFd(int fd) { SockAddr result; - int rc = getsockname(fd, result.raw(), &result.addressSize); - if (rc != 0) { + if (getsockname(fd, result.raw(), &result.addressSize)) { + auto ec = lastSocketError(); LOGV2_WARNING(23191, "Could not resolve local address for socket with fd {fd}: " "{error}", "Could not resolve local address for socket with fd", "fd"_attr = fd, - "error"_attr = getAddrInfoStrError(socketGetLastError())); + "error"_attr = errorMessage(ec)); result = SockAddr(); } return result; @@ -323,14 +319,15 @@ bool Socket::connect(const SockAddr& remote, Milliseconds connectTimeoutMillis) bool connectSucceeded = ::connect(_fd, _remote.raw(), _remote.addressSize) == 0; if (!connectSucceeded) { + auto ec = lastSocketError(); #ifdef _WIN32 - if (WSAGetLastError() != WSAEWOULDBLOCK) { - networkWarnWithDescription(*this, "connect"); + if (ec != systemError(WSAEWOULDBLOCK)) { + networkWarnWithDescription(*this, "connect", ec); return false; } #else - if (errno != EINTR && errno != EINPROGRESS) { - networkWarnWithDescription(*this, "connect"); + if (ec != posixError(EINTR) && ec != posixError(EINPROGRESS)) { + networkWarnWithDescription(*this, "connect", ec); return false; } #endif @@ -380,7 +377,8 @@ bool Socket::connect(const SockAddr& remote, Milliseconds connectTimeoutMillis) return false; } if (optVal != 0) { - networkWarnWithDescription(*this, "checking socket for error after poll", optVal); + networkWarnWithDescription( + *this, "checking socket for error after poll", systemError(optVal)); return false; } @@ -570,13 +568,15 @@ int Socket::_recv(char* buf, int max) { } void Socket::handleSendError(int ret, const char* context) { + const auto ec = lastSocketError(); + auto isTimeoutCode = [](std::error_code e) { #if defined(_WIN32) - const int mongo_errno = WSAGetLastError(); - if (mongo_errno == WSAETIMEDOUT && _timeout != 0) { + return e == systemError(WSAETIMEDOUT); #else - const int mongo_errno = errno; - if ((mongo_errno == EAGAIN || mongo_errno == EWOULDBLOCK) && _timeout != 0) { + return e == posixError(EAGAIN) || e == posixError(EWOULDBLOCK); #endif + }; + if (isTimeoutCode(ec) && _timeout != 0) { LOGV2_DEBUG(23181, _logLevel.toInt(), "Socket {context} send() timed out {remoteHost}", @@ -584,13 +584,13 @@ void Socket::handleSendError(int ret, const char* context) { "context"_attr = context, "remoteHost"_attr = remoteString()); throwSocketError(SocketErrorKind::SEND_TIMEOUT, remoteString()); - } else if (mongo_errno != EINTR) { + } else if (ec != posixError(EINTR)) { LOGV2_DEBUG(23182, _logLevel.toInt(), "Socket {context} send() {error} {remoteHost}", "Socket send() to remote host failed", "context"_attr = context, - "error"_attr = errnoWithDescription(mongo_errno), + "error"_attr = errorMessage(ec), "remoteHost"_attr = remoteString()); throwSocketError(SocketErrorKind::SEND_ERROR, remoteString()); } @@ -606,24 +606,20 @@ void Socket::handleRecvError(int ret, int len) { throwSocketError(SocketErrorKind::CLOSED, remoteString()); } -// ret < 0 -#if defined(_WIN32) - int e = WSAGetLastError(); -#else - int e = errno; + // ret < 0 + auto ec = lastSocketError(); #if defined(EINTR) - if (e == EINTR) { + if (ec == posixError(EINTR)) { return; } #endif -#endif + if ((ec == posixError(EAGAIN) #if defined(_WIN32) - // Windows - if ((e == EAGAIN || e == WSAETIMEDOUT) && _timeout > 0) { -#else - if (e == EAGAIN && _timeout > 0) { + || ec == systemError(WSAETIMEDOUT) #endif + ) && + _timeout > 0) { // this is a timeout LOGV2_DEBUG(23184, _logLevel.toInt(), @@ -637,7 +633,7 @@ void Socket::handleRecvError(int ret, int len) { _logLevel.toInt(), "Socket recv() {error} {remoteHost}", "Socket recv() error", - "error"_attr = errnoWithDescription(e), + "error"_attr = errorMessage(ec), "remoteHost"_attr = remoteString()); throwSocketError(SocketErrorKind::RECV_ERROR, remoteString()); } @@ -689,6 +685,7 @@ bool Socket::isStillConnected() { // Poll( info[], size, timeout ) - timeout == 0 => nonblocking int nEvents = socketPoll(&pollInfo, 1, 0); + auto ec = lastSocketError(); LOGV2_DEBUG( 23186, 2, @@ -709,7 +706,7 @@ bool Socket::isStillConnected() { "Socket poll() to remote host failed during connectivity check", "idleTimeSecs"_attr = idleTimeSecs, "remoteHost"_attr = remoteString(), - "error"_attr = causedBy(errnoWithDescription())); + "error"_attr = causedBy(errorMessage(ec))); // Return true since it's not clear that we're disconnected. return true; @@ -731,6 +728,7 @@ bool Socket::isStillConnected() { int recvd = ::recv(_fd, testBuf, testBufLength, portRecvFlags); if (recvd < 0) { + auto ec = lastSocketError(); // An error occurred during recv, warn and log errno LOGV2_WARNING(23194, "Socket recv() failed during connectivity check (idle {idleTimeSecs} " @@ -738,7 +736,7 @@ bool Socket::isStillConnected() { "Socket recv() failed during connectivity check", "idleTimeSecs"_attr = idleTimeSecs, "remoteHost"_attr = remoteString(), - "error"_attr = causedBy(errnoWithDescription())); + "error"_attr = causedBy(errorMessage(ec))); } else if (recvd > 0) { // We got nonzero data from this socket, very weird? // Log and warn at runtime, log and abort at devtime diff --git a/src/mongo/util/net/sockaddr.cpp b/src/mongo/util/net/sockaddr.cpp index 1a2b058cbf3..a3a0ae8753d 100644 --- a/src/mongo/util/net/sockaddr.cpp +++ b/src/mongo/util/net/sockaddr.cpp @@ -97,8 +97,8 @@ AddrInfoPtr resolveAddrInfo(StringData hostOrIp, int port, sa_family_t familyHin }; auto validateResolution = [](AddrError addrErr) -> AddrInfoPtr { - uassert(ErrorCodes::HostUnreachable, getAddrInfoStrError(addrErr.err), addrErr.err == 0); - + auto ec = addrInfoError(addrErr.err); + uassert(ErrorCodes::HostUnreachable, errorMessage(ec), !ec); return std::move(addrErr.addr); }; @@ -117,15 +117,6 @@ AddrInfoPtr resolveAddrInfo(StringData hostOrIp, int port, sa_family_t familyHin } // namespace -std::string getAddrInfoStrError(int code) { -#if !defined(_WIN32) - return gai_strerror(code); -#else - /* gai_strerrorA is not threadsafe on windows. don't use it. */ - return errnoWithDescription(code); -#endif -} - SockAddr::SockAddr() { addressSize = sizeof(sa); memset(&sa, 0, sizeof(sa)); @@ -308,8 +299,9 @@ std::string SockAddr::getAddr() const { const int buflen = 128; char buffer[buflen]; int ret = getnameinfo(raw(), addressSize, buffer, buflen, nullptr, 0, NI_NUMERICHOST); - massert( - 13082, str::stream() << "getnameinfo error " << getAddrInfoStrError(ret), ret == 0); + massert(13082, + str::stream() << "getnameinfo error " << errorMessage(addrInfoError(ret)), + ret == 0); return buffer; } diff --git a/src/mongo/util/net/sockaddr.h b/src/mongo/util/net/sockaddr.h index 66b985274c2..79e08ba1045 100644 --- a/src/mongo/util/net/sockaddr.h +++ b/src/mongo/util/net/sockaddr.h @@ -63,9 +63,6 @@ struct sockaddr_un { #endif // _WIN32 -// Generate a string representation for getaddrinfo return codes -std::string getAddrInfoStrError(int code); - /** * Wrapper around os representation of network address. */ diff --git a/src/mongo/util/net/socket_utils.cpp b/src/mongo/util/net/socket_utils.cpp index d4236cafa28..f15bb3ca96b 100644 --- a/src/mongo/util/net/socket_utils.cpp +++ b/src/mongo/util/net/socket_utils.cpp @@ -69,11 +69,11 @@ namespace mongo { const struct WinsockInit { WinsockInit() { WSADATA d; - if (WSAStartup(MAKEWORD(2, 2), &d) != 0) { + if (int e = WSAStartup(MAKEWORD(2, 2), &d)) { LOGV2(23201, "ERROR: wsastartup failed {error}", "ERROR: wsastartup failed", - "error"_attr = errnoWithDescription()); + "error"_attr = errorMessage(systemError(e))); quickExit(EXIT_NTSERVICE_ERROR); } } @@ -150,12 +150,12 @@ void setSocketKeepAliveParams(int sock, &sent, nullptr, nullptr)) { - int wsaErr = WSAGetLastError(); + auto ec = lastSocketError(); LOGV2_DEBUG(23204, logSeverity, "failed setting keepalive values: {error}", "Failed setting keepalive values", - "error"_attr = errnoWithDescription(wsaErr)); + "error"_attr = errorMessage(ec)); } } #elif defined(__APPLE__) || defined(__linux__) @@ -165,13 +165,13 @@ void setSocketKeepAliveParams(int sock, socklen_t optValLen = sizeof(rawOptVal); if (getsockopt(sock, level, optnum, reinterpret_cast<char*>(&rawOptVal), &optValLen)) { - int savedErrno = errno; + auto ec = lastSystemError(); LOGV2_DEBUG(23205, logSeverity, "can't get {optname}: {error}", "Can't get socket option", "optname"_attr = optname, - "error"_attr = errnoWithDescription(savedErrno)); + "error"_attr = errorMessage(ec)); } if (optVal > maxVal) { @@ -179,13 +179,13 @@ void setSocketKeepAliveParams(int sock, socklen_t maxValLen = sizeof(rawMaxVal); if (setsockopt(sock, level, optnum, reinterpret_cast<char*>(&rawMaxVal), maxValLen)) { - int savedErrno = errno; + auto ec = lastSystemError(); LOGV2_DEBUG(23206, logSeverity, "can't set {optname}: {error}", "Can't set socket option", "optname"_attr = optname, - "error"_attr = errnoWithDescription(savedErrno)); + "error"_attr = errorMessage(ec)); } } }; @@ -234,10 +234,11 @@ std::string getHostName() { char buf[256]; int ec = gethostname(buf, 127); if (ec || *buf == 0) { + auto ec = lastSocketError(); LOGV2(23202, "can't get this server's hostname {error}", "Can't get this server's hostname", - "error"_attr = errnoWithDescription()); + "error"_attr = errorMessage(ec)); return ""; } return buf; diff --git a/src/mongo/util/net/ssl/impl/error.ipp b/src/mongo/util/net/ssl/impl/error.ipp index abe179c33a7..fd2c5f5c2c2 100644 --- a/src/mongo/util/net/ssl/impl/error.ipp +++ b/src/mongo/util/net/ssl/impl/error.ipp @@ -40,7 +40,7 @@ public: if (value == asio::ssl::error::no_renegotiation) { return "peer requested renegotiation, which is not supported"; } - return mongo::errnoWithDescription(value); + return std::system_category().message(value); } #elif MONGO_CONFIG_SSL_PROVIDER == MONGO_CONFIG_SSL_PROVIDER_OPENSSL std::string message(int value) const { diff --git a/src/mongo/util/net/ssl_manager_openssl.cpp b/src/mongo/util/net/ssl_manager_openssl.cpp index f2ddee148c7..7651d286be1 100644 --- a/src/mongo/util/net/ssl_manager_openssl.cpp +++ b/src/mongo/util/net/ssl_manager_openssl.cpp @@ -3561,10 +3561,11 @@ void SSLManagerOpenSSL::_handleSSLError(SSLConnectionOpenSSL* conn, int ret) { } else if (ret == 0) { LOGV2_ERROR(23261, "Unexpected EOF encountered during SSL communication"); } else { + auto ec = lastSystemError(); LOGV2_ERROR(23262, "The SSL BIO reported an I/O error {error}", "The SSL BIO reported an I/O error", - "error"_attr = errnoWithDescription()); + "error"_attr = errorMessage(ec)); } break; case SSL_ERROR_SSL: { diff --git a/src/mongo/util/net/ssl_manager_windows.cpp b/src/mongo/util/net/ssl_manager_windows.cpp index adf86ae847f..fbaa983b0fb 100644 --- a/src/mongo/util/net/ssl_manager_windows.cpp +++ b/src/mongo/util/net/ssl_manager_windows.cpp @@ -488,12 +488,11 @@ StatusWith<UniqueCertChainEngine> initChainEngine(CERT_CHAIN_ENGINE_CONFIG* chai chainEngineConfig->dwFlags = flags; HCERTCHAINENGINE chainEngine; - BOOL ret = CertCreateCertificateChainEngine(chainEngineConfig, &chainEngine); - if (!ret) { - DWORD gle = GetLastError(); + if (!CertCreateCertificateChainEngine(chainEngineConfig, &chainEngine)) { + auto ec = lastSystemError(); return Status(ErrorCodes::InvalidSSLConfiguration, - str::stream() << "CertCreateCertificateChainEngine failed: " - << errnoWithDescription(gle)); + str::stream() + << "CertCreateCertificateChainEngine failed: " << errorMessage(ec)); } return {chainEngine}; @@ -633,32 +632,30 @@ StatusWith<std::string> readFile(StringData fileName) { StatusWith<std::vector<BYTE>> decodePEMBlob(StringData blob) { DWORD decodeLen{0}; - BOOL ret = CryptStringToBinaryA( - blob.rawData(), blob.size(), CRYPT_STRING_BASE64HEADER, NULL, &decodeLen, NULL, NULL); - if (!ret) { - DWORD gle = GetLastError(); - if (gle != ERROR_MORE_DATA) { + if (!CryptStringToBinaryA( + blob.rawData(), blob.size(), CRYPT_STRING_BASE64HEADER, NULL, &decodeLen, NULL, NULL)) { + auto ec = lastSystemError(); + if (ec != systemError(ERROR_MORE_DATA)) { return Status(ErrorCodes::InvalidSSLConfiguration, str::stream() << "CryptStringToBinary failed to get size of key: " - << errnoWithDescription(gle)); + << errorMessage(ec)); } } std::vector<BYTE> binaryBlobBuf; binaryBlobBuf.resize(decodeLen); - ret = CryptStringToBinaryA(blob.rawData(), - blob.size(), - CRYPT_STRING_BASE64HEADER, - binaryBlobBuf.data(), - &decodeLen, - NULL, - NULL); - if (!ret) { - DWORD gle = GetLastError(); + if (!CryptStringToBinaryA(blob.rawData(), + blob.size(), + CRYPT_STRING_BASE64HEADER, + binaryBlobBuf.data(), + &decodeLen, + NULL, + NULL)) { + auto ec = lastSystemError(); return Status(ErrorCodes::InvalidSSLConfiguration, - str::stream() << "CryptStringToBinary failed to read key: " - << errnoWithDescription(gle)); + str::stream() + << "CryptStringToBinary failed to read key: " << errorMessage(ec)); } return std::move(binaryBlobBuf); @@ -669,27 +666,31 @@ StatusWith<std::vector<BYTE>> decodeObject(const char* structType, size_t length) { DWORD decodeLen{0}; - BOOL ret = - CryptDecodeObjectEx(X509_ASN_ENCODING, structType, data, length, 0, NULL, NULL, &decodeLen); - if (!ret) { - DWORD gle = GetLastError(); - if (gle != ERROR_MORE_DATA) { + if (!CryptDecodeObjectEx( + X509_ASN_ENCODING, structType, data, length, 0, NULL, NULL, &decodeLen)) { + auto ec = lastSystemError(); + if (ec != systemError(ERROR_MORE_DATA)) { return Status(ErrorCodes::InvalidSSLConfiguration, str::stream() << "CryptDecodeObjectEx failed to get size of object: " - << errnoWithDescription(gle)); + << errorMessage(ec)); } } std::vector<BYTE> binaryBlobBuf; binaryBlobBuf.resize(decodeLen); - ret = CryptDecodeObjectEx( - X509_ASN_ENCODING, structType, data, length, 0, NULL, binaryBlobBuf.data(), &decodeLen); - if (!ret) { - DWORD gle = GetLastError(); + if (!CryptDecodeObjectEx(X509_ASN_ENCODING, + structType, + data, + length, + 0, + NULL, + binaryBlobBuf.data(), + &decodeLen)) { + auto ec = lastSystemError(); return Status(ErrorCodes::InvalidSSLConfiguration, - str::stream() << "CryptDecodeObjectEx failed to read object: " - << errnoWithDescription(gle)); + str::stream() + << "CryptDecodeObjectEx failed to read object: " << errorMessage(ec)); } return std::move(binaryBlobBuf); @@ -733,11 +734,11 @@ StatusWith<std::vector<UniqueCertificate>> readCAPEMBuffer(StringData buffer) { PCCERT_CONTEXT cert = CertCreateCertificateContext(X509_ASN_ENCODING, certBuf.data(), certBuf.size()); - if (cert == NULL) { - DWORD gle = GetLastError(); + if (!cert) { + auto ec = lastSystemError(); return Status(ErrorCodes::InvalidSSLConfiguration, str::stream() << "CertCreateCertificateContext failed to decode cert: " - << errnoWithDescription(gle)); + << errorMessage(ec)); } certs.emplace_back(cert); @@ -748,14 +749,11 @@ StatusWith<std::vector<UniqueCertificate>> readCAPEMBuffer(StringData buffer) { Status addCertificatesToStore(HCERTSTORE certStore, std::vector<UniqueCertificate>& certificates) { for (auto& cert : certificates) { - BOOL ret = - CertAddCertificateContextToStore(certStore, cert.get(), CERT_STORE_ADD_NEW, NULL); - - if (!ret) { - DWORD gle = GetLastError(); + if (!CertAddCertificateContextToStore(certStore, cert.get(), CERT_STORE_ADD_NEW, NULL)) { + auto ec = lastSystemError(); return Status(ErrorCodes::InvalidSSLConfiguration, - str::stream() << "CertAddCertificateContextToStore Failed " - << errnoWithDescription(gle)); + str::stream() + << "CertAddCertificateContextToStore Failed " << errorMessage(ec)); } } @@ -816,34 +814,32 @@ StatusWith<UniqueCertificateWithPrivateKey> readCertPEMFile(StringData fileName, PCCERT_CONTEXT cert = CertCreateCertificateContext(X509_ASN_ENCODING, certBuf.data(), certBuf.size()); - if (cert == NULL) { - DWORD gle = GetLastError(); + if (!cert) { + auto ec = lastSystemError(); return Status(ErrorCodes::InvalidSSLConfiguration, str::stream() << "CertCreateCertificateContext failed to decode cert: " - << errnoWithDescription(gle)); + << errorMessage(ec)); } UniqueCertificate tempCertHolder(cert); HCERTSTORE store = CertOpenStore( CERT_STORE_PROV_MEMORY, 0, NULL, CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG, NULL); - if (store == NULL) { - DWORD gle = GetLastError(); + if (!store) { + auto ec = lastSystemError(); return Status(ErrorCodes::InvalidSSLConfiguration, - str::stream() << "CertOpenStore failed to create memory store: " - << errnoWithDescription(gle)); + str::stream() + << "CertOpenStore failed to create memory store: " << errorMessage(ec)); } UniqueCertStore storeHolder(store); // Add the newly created certificate to the memory store, this makes a copy - BOOL ret = CertAddCertificateContextToStore(store, cert, CERT_STORE_ADD_NEW, NULL); - - if (!ret) { - DWORD gle = GetLastError(); + if (!CertAddCertificateContextToStore(store, cert, CERT_STORE_ADD_NEW, NULL)) { + auto ec = lastSystemError(); return Status(ErrorCodes::InvalidSSLConfiguration, str::stream() << "CertAddCertificateContextToStore Memory Failed " - << errnoWithDescription(gle)); + << errorMessage(ec)); } // Get the certificate from the store so we attach the private key to the cert in the store @@ -938,47 +934,45 @@ StatusWith<UniqueCertificateWithPrivateKey> readCertPEMFile(StringData fileName, // default // container is shared across processes owned by the same user. // Note: Server side Schannel requires CRYPT_VERIFYCONTEXT off - ret = CryptAcquireContextW( - &hProv, wstr.c_str(), MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET | CRYPT_SILENT); - if (!ret) { - DWORD gle = GetLastError(); - - if (gle == NTE_EXISTS) { - - ret = CryptAcquireContextW( - &hProv, wstr.c_str(), MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_SILENT); - if (!ret) { - DWORD gle = GetLastError(); + if (!CryptAcquireContextW(&hProv, + wstr.c_str(), + MS_ENHANCED_PROV, + PROV_RSA_FULL, + CRYPT_NEWKEYSET | CRYPT_SILENT)) { + auto ec = lastSystemError(); + if (ec == systemError(NTE_EXISTS)) { + if (!CryptAcquireContextW( + &hProv, wstr.c_str(), MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_SILENT)) { + auto ec = lastSystemError(); return Status(ErrorCodes::InvalidSSLConfiguration, - str::stream() << "CryptAcquireContextW failed " - << errnoWithDescription(gle)); + str::stream() + << "CryptAcquireContextW failed " << errorMessage(ec)); } } else { return Status(ErrorCodes::InvalidSSLConfiguration, - str::stream() - << "CryptAcquireContextW failed " << errnoWithDescription(gle)); + str::stream() << "CryptAcquireContextW failed " << errorMessage(ec)); } } } else { // Use a transient key container for the key - ret = CryptAcquireContextW( - &hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT); - if (!ret) { - DWORD gle = GetLastError(); + if (!CryptAcquireContextW(&hProv, + NULL, + MS_ENHANCED_PROV, + PROV_RSA_FULL, + CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { + auto ec = lastSystemError(); return Status(ErrorCodes::InvalidSSLConfiguration, - str::stream() - << "CryptAcquireContextW failed " << errnoWithDescription(gle)); + str::stream() << "CryptAcquireContextW failed " << errorMessage(ec)); } } UniqueCryptProvider cryptProvider(hProv); HCRYPTKEY hkey; - ret = CryptImportKey(hProv, privateKey.data(), privateKey.size(), 0, 0, &hkey); - if (!ret) { - DWORD gle = GetLastError(); + if (!CryptImportKey(hProv, privateKey.data(), privateKey.size(), 0, 0, &hkey)) { + auto ec = lastSystemError(); return Status(ErrorCodes::InvalidSSLConfiguration, - str::stream() << "CryptImportKey failed " << errnoWithDescription(gle)); + str::stream() << "CryptImportKey failed " << errorMessage(ec)); } UniqueCryptKey keyHolder(hkey); @@ -995,21 +989,20 @@ StatusWith<UniqueCertificateWithPrivateKey> readCertPEMFile(StringData fileName, if (!CertSetCertificateContextProperty( certHolder.get(), CERT_KEY_PROV_INFO_PROP_ID, 0, &keyProvInfo)) { - DWORD gle = GetLastError(); + auto ec = lastSystemError(); return Status(ErrorCodes::InvalidSSLConfiguration, - str::stream() << "CertSetCertificateContextProperty Failed " - << errnoWithDescription(gle)); + str::stream() + << "CertSetCertificateContextProperty Failed " << errorMessage(ec)); } } // NOTE: This is used to set the certificate for client side SChannel - ret = CertSetCertificateContextProperty( - cert, CERT_KEY_PROV_HANDLE_PROP_ID, 0, (const void*)hProv); - if (!ret) { - DWORD gle = GetLastError(); + if (!CertSetCertificateContextProperty( + cert, CERT_KEY_PROV_HANDLE_PROP_ID, 0, (const void*)hProv)) { + auto ec = lastSystemError(); return Status(ErrorCodes::InvalidSSLConfiguration, - str::stream() << "CertSetCertificateContextProperty failed " - << errnoWithDescription(gle)); + str::stream() + << "CertSetCertificateContextProperty failed " << errorMessage(ec)); } // Add the extra certificates into the same certificate store as the certificate @@ -1081,22 +1074,19 @@ Status readCRLPEMFile(HCERTSTORE certStore, StringData fileName) { auto certBuf = swCert.getValue(); PCCRL_CONTEXT crl = CertCreateCRLContext(X509_ASN_ENCODING, certBuf.data(), certBuf.size()); - if (crl == NULL) { - DWORD gle = GetLastError(); + if (!crl) { + auto ec = lastSystemError(); return Status(ErrorCodes::InvalidSSLConfiguration, - str::stream() << "CertCreateCRLContext failed to decode crl: " - << errnoWithDescription(gle)); + str::stream() + << "CertCreateCRLContext failed to decode crl: " << errorMessage(ec)); } UniqueCRL crlHolder(crl); - BOOL ret = CertAddCRLContextToStore(certStore, crl, CERT_STORE_ADD_NEW, NULL); - - if (!ret) { - DWORD gle = GetLastError(); + if (!CertAddCRLContextToStore(certStore, crl, CERT_STORE_ADD_NEW, NULL)) { + auto ec = lastSystemError(); return Status(ErrorCodes::InvalidSSLConfiguration, - str::stream() - << "CertAddCRLContextToStore Failed " << errnoWithDescription(gle)); + str::stream() << "CertAddCRLContextToStore Failed " << errorMessage(ec)); } } @@ -1105,10 +1095,10 @@ Status readCRLPEMFile(HCERTSTORE certStore, StringData fileName) { StatusWith<UniqueCertStore> readCertChains(StringData caFile, StringData crlFile) { UniqueCertStore certStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, NULL, 0, NULL); - if (certStore == nullptr) { - DWORD gle = GetLastError(); + if (!certStore) { + auto ec = lastSystemError(); return Status(ErrorCodes::InvalidSSLConfiguration, - str::stream() << "CertOpenStore Failed " << errnoWithDescription(gle)); + str::stream() << "CertOpenStore Failed " << errorMessage(ec)); } auto status = readCAPEMFile(certStore, caFile); @@ -1139,11 +1129,11 @@ StatusWith<UniqueCertificate> loadCertificateSelectorFromStore( storeType | CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG | CERT_STORE_READONLY_FLAG, L"My"); - if (store == NULL) { - DWORD gle = GetLastError(); + if (!store) { + auto ec = lastSystemError(); return Status(ErrorCodes::InvalidSSLConfiguration, str::stream() << "CertOpenStore failed to open store 'My' from '" << storeName - << "': " << errnoWithDescription(gle)); + << "': " << errorMessage(ec)); } UniqueCertStore storeHolder(store); @@ -1157,14 +1147,14 @@ StatusWith<UniqueCertificate> loadCertificateSelectorFromStore( CERT_FIND_SUBJECT_STR, wstr.c_str(), NULL); - if (cert == NULL) { - DWORD gle = GetLastError(); + if (!cert) { + auto ec = lastSystemError(); return Status( ErrorCodes::InvalidSSLConfiguration, str::stream() << "CertFindCertificateInStore failed to find cert with subject name '" << selector.subject.c_str() << "' in 'My' store in '" << storeName - << "': " << errnoWithDescription(gle)); + << "': " << errorMessage(ec)); } return UniqueCertificate(cert); @@ -1178,15 +1168,14 @@ StatusWith<UniqueCertificate> loadCertificateSelectorFromStore( CERT_FIND_HASH, &hashBlob, NULL); - if (cert == NULL) { - DWORD gle = GetLastError(); + if (!cert) { + auto ec = lastSystemError(); return Status(ErrorCodes::InvalidSSLConfiguration, str::stream() << "CertFindCertificateInStore failed to find cert with thumbprint '" << hexblob::encode(selector.thumbprint.data(), selector.thumbprint.size()) - << "' in 'My' store in '" << storeName - << "': " << errnoWithDescription(gle)); + << "' in 'My' store in '" << storeName << "': " << errorMessage(ec)); } return UniqueCertificate(cert); @@ -1220,27 +1209,26 @@ StatusWith<UniqueCertificate> loadAndValidateCertificateSelector( DWORD dwKeySpec; BOOL freeProvider; HCRYPTPROV hCryptProv; - BOOL ret = CryptAcquireCertificatePrivateKey(swCert.getValue().get(), - CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG, - NULL, - &hCryptProv, - &dwKeySpec, - &freeProvider); - if (!ret) { - DWORD gle = GetLastError(); - if (gle == CRYPT_E_NO_KEY_PROPERTY) { + if (!CryptAcquireCertificatePrivateKey(swCert.getValue().get(), + CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG, + NULL, + &hCryptProv, + &dwKeySpec, + &freeProvider)) { + auto ec = lastSystemError(); + if (ec == systemError(CRYPT_E_NO_KEY_PROPERTY)) { return Status(ErrorCodes::InvalidSSLConfiguration, str::stream() << "Could not find private key attached to the selected certificate"); - } else if (gle == NTE_BAD_KEYSET) { + } else if (ec == systemError(NTE_BAD_KEYSET)) { return Status(ErrorCodes::InvalidSSLConfiguration, str::stream() << "Could not read private key attached to the selected " "certificate, ensure it exists and check the private " "key permissions"); } else { return Status(ErrorCodes::InvalidSSLConfiguration, - str::stream() << "CryptAcquireCertificatePrivateKey failed " - << errnoWithDescription(gle)); + str::stream() + << "CryptAcquireCertificatePrivateKey failed " << errorMessage(ec)); } } @@ -1751,19 +1739,17 @@ Status validatePeerCertificate(const std::string& remoteHost, auto before = Date_t::now(); PCCERT_CHAIN_CONTEXT chainContext; - BOOL ret = CertGetCertificateChain(certChainEngine, - cert, - NULL, - cert->hCertStore, - &certChainPara, - CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT, - NULL, - &chainContext); - if (!ret) { - DWORD gle = GetLastError(); + if (!CertGetCertificateChain(certChainEngine, + cert, + NULL, + cert->hCertStore, + &certChainPara, + CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT, + NULL, + &chainContext)) { + auto ec = lastSystemError(); return Status(ErrorCodes::InvalidSSLConfiguration, - str::stream() - << "CertGetCertificateChain failed: " << errnoWithDescription(gle)); + str::stream() << "CertGetCertificateChain failed: " << errorMessage(ec)); } auto after = Date_t::now(); @@ -1803,15 +1789,16 @@ Status validatePeerCertificate(const std::string& remoteHost, memset(&certChainPolicyStatus, 0, sizeof(certChainPolicyStatus)); certChainPolicyStatus.cbSize = sizeof(certChainPolicyStatus); - ret = CertVerifyCertificateChainPolicy( - CERT_CHAIN_POLICY_SSL, certChainHolder.get(), &chain_policy_para, &certChainPolicyStatus); // This means something really went wrong, this should not happen. - if (!ret) { - DWORD gle = GetLastError(); + if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, + certChainHolder.get(), + &chain_policy_para, + &certChainPolicyStatus)) { + auto ec = lastSystemError(); return Status(ErrorCodes::InvalidSSLConfiguration, - str::stream() << "CertVerifyCertificateChainPolicy failed: " - << errnoWithDescription(gle)); + str::stream() + << "CertVerifyCertificateChainPolicy failed: " << errorMessage(ec)); } auto swSubjectName = getCertificateSubjectName(cert); @@ -1849,17 +1836,16 @@ Status validatePeerCertificate(const std::string& remoteHost, // We know the CNs do not match, are there any other issues? sslCertChainPolicy.fdwChecks = SECURITY_FLAG_IGNORE_CERT_CN_INVALID; - ret = CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, - certChainHolder.get(), - &chain_policy_para, - &certChainPolicyStatus); // This means something really went wrong, this should not happen. - if (!ret) { - DWORD gle = GetLastError(); + if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, + certChainHolder.get(), + &chain_policy_para, + &certChainPolicyStatus)) { + auto ec = lastSystemError(); return Status(ErrorCodes::InvalidSSLConfiguration, str::stream() << "CertVerifyCertificateChainPolicy2 failed: " - << errnoWithDescription(gle)); + << errorMessage(ec)); } if (certChainPolicyStatus.dwError == S_OK || @@ -1913,7 +1899,8 @@ Status validatePeerCertificate(const std::string& remoteHost, "SSL peer certificate validation failed ({errorCode}): {error}", "SSL peer certificate validation failed", "errorCode"_attr = unsignedHex(certChainPolicyStatus.dwError), - "error"_attr = errnoWithDescription(certChainPolicyStatus.dwError)); + "error"_attr = + errorMessage(systemError(certChainPolicyStatus.dwError))); if (certChainPolicyStatus.dwError == CERT_E_CN_NO_MATCH) { LOGV2_WARNING(23275, @@ -1941,14 +1928,14 @@ Status validatePeerCertificate(const std::string& remoteHost, str::stream msg; msg << "SSL peer certificate validation failed: (" << unsignedHex(certChainPolicyStatus.dwError) << ")" - << errnoWithDescription(certChainPolicyStatus.dwError); + << errorMessage(systemError(certChainPolicyStatus.dwError)); LOGV2_ERROR(23279, "SSL peer certificate validation failed: ({errorCode}){error}", "SSL peer certificate validation failed", "errorCode"_attr = unsignedHex(certChainPolicyStatus.dwError), - "error"_attr = errnoWithDescription(certChainPolicyStatus.dwError)); + "error"_attr = errorMessage(systemError(certChainPolicyStatus.dwError))); return Status(ErrorCodes::SSLHandshakeFailed, msg); } } @@ -2104,10 +2091,10 @@ Status getCertInfo(CertInformationToLog* info, PCCERT_CONTEXT cert) { if (!CertGetCertificateContextProperty( cert, CERT_SHA1_HASH_PROP_ID, info->thumbprint.data(), &bufSize)) { - DWORD gle = GetLastError(); + auto ec = lastSystemError(); return Status(ErrorCodes::InvalidSSLConfiguration, str::stream() << "getCertInfo failed to get certificate thumbprint: " - << errnoWithDescription(gle)); + << errorMessage(ec)); } info->hexEncodedThumbprint = hexblob::encode(info->thumbprint.data(), info->thumbprint.size()); @@ -2125,10 +2112,10 @@ Status getCRLInfo(CRLInformationToLog* info, PCCRL_CONTEXT crl) { if (!CertGetCRLContextProperty( crl, CERT_SHA1_HASH_PROP_ID, info->thumbprint.data(), &bufSize)) { - DWORD gle = GetLastError(); + auto ec = lastSystemError(); return Status(ErrorCodes::InvalidSSLConfiguration, - str::stream() << "getCRLInfo failed to get CRL thumbprint: " - << errnoWithDescription(gle)); + str::stream() + << "getCRLInfo failed to get CRL thumbprint: " << errorMessage(ec)); } info->validityNotBefore = diff --git a/src/mongo/util/ntservice.cpp b/src/mongo/util/ntservice.cpp index e59533a6b44..1abef2bdb2b 100644 --- a/src/mongo/util/ntservice.cpp +++ b/src/mongo/util/ntservice.cpp @@ -455,10 +455,10 @@ void installServiceOrDie(const wstring& serviceName, BOOL ret = ::ChangeServiceConfig2( schService, SERVICE_CONFIG_PRESHUTDOWN_INFO, &servicePreshutdownInfo); if (!ret) { - DWORD gle = ::GetLastError(); + auto ec = lastSystemError(); LOGV2_ERROR(23317, "Failed to set timeout for pre-shutdown notification", - "__error__"_attr = errnoWithDescription(gle)); + "__error__"_attr = errorMessage(ec)); serviceInstalled = false; } diff --git a/src/mongo/util/options_parser/options_parser.cpp b/src/mongo/util/options_parser/options_parser.cpp index ad51118032b..4146d5b63a0 100644 --- a/src/mongo/util/options_parser/options_parser.cpp +++ b/src/mongo/util/options_parser/options_parser.cpp @@ -1364,8 +1364,9 @@ Status checkFileOwnershipAndMode(int fd, mode_t prohibit, StringData modeDesc) { struct stat stats; if (::fstat(fd, &stats) == -1) { - const auto& ewd = errnoWithDescription(); - return {ErrorCodes::InvalidPath, str::stream() << "Error reading file metadata: " << ewd}; + auto ec = lastSystemError(); + return {ErrorCodes::InvalidPath, + str::stream() << "Error reading file metadata: " << errorMessage(ec)}; } if (stats.st_uid != ::getuid()) { @@ -1437,8 +1438,9 @@ Status OptionsParser::readConfigFile(const std::string& filename, #endif if (fd < 0) { - const auto& ewd = errnoWithDescription(); - return {ErrorCodes::InternalError, str::stream() << "Error opening config file: " << ewd}; + auto ec = lastPosixError(); + return {ErrorCodes::InternalError, + str::stream() << "Error opening config file: " << errorMessage(ec)}; } #ifdef _WIN32 diff --git a/src/mongo/util/password.cpp b/src/mongo/util/password.cpp index 49a4a54db02..447cbd2ca13 100644 --- a/src/mongo/util/password.cpp +++ b/src/mongo/util/password.cpp @@ -59,14 +59,16 @@ std::string askPassword() { if (isatty(stdinfd)) { int i = tcgetattr(stdinfd, &termio); if (i == -1) { - std::cerr << "Cannot get terminal attributes " << errnoWithDescription() << std::endl; + auto ec = lastSystemError(); + std::cerr << "Cannot get terminal attributes " << errorMessage(ec) << std::endl; return std::string(); } old = termio.c_lflag; termio.c_lflag &= ~ECHO; i = tcsetattr(stdinfd, TCSANOW, &termio); if (i == -1) { - std::cerr << "Cannot set terminal attributes " << errnoWithDescription() << std::endl; + auto ec = lastSystemError(); + std::cerr << "Cannot set terminal attributes " << errorMessage(ec) << std::endl; return std::string(); } } @@ -77,33 +79,38 @@ std::string askPassword() { termio.c_lflag = old; int i = tcsetattr(stdinfd, TCSANOW, &termio); if (i == -1) { - std::cerr << "Cannot set terminal attributes " << errnoWithDescription() << std::endl; + auto ec = lastSystemError(); + std::cerr << "Cannot set terminal attributes " << errorMessage(ec) << std::endl; return std::string(); } } #else HANDLE stdinh = GetStdHandle(STD_INPUT_HANDLE); if (stdinh == INVALID_HANDLE_VALUE) { - std::cerr << "Cannot get stdin handle " << GetLastError() << "\n"; + auto ec = lastSystemError(); + std::cerr << "Cannot get stdin handle " << errorMessage(ec) << "\n"; return std::string(); } DWORD old; if (!GetConsoleMode(stdinh, &old)) { - std::cerr << "Cannot get console mode " << GetLastError() << "\n"; + auto ec = lastSystemError(); + std::cerr << "Cannot get console mode " << errorMessage(ec) << "\n"; return std::string(); } DWORD noecho = ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT; if (!SetConsoleMode(stdinh, noecho)) { - std::cerr << "Cannot set console mode " << GetLastError() << "\n"; + auto ec = lastSystemError(); + std::cerr << "Cannot set console mode " << errorMessage(ec) << "\n"; return std::string(); } getline(std::cin, password); if (!SetConsoleMode(stdinh, old)) { - std::cerr << "Cannot set console mode " << GetLastError() << "\n"; + auto ec = lastSystemError(); + std::cerr << "Cannot set console mode " << errorMessage(ec) << "\n"; return std::string(); } #endif diff --git a/src/mongo/util/perfctr_collect.cpp b/src/mongo/util/perfctr_collect.cpp index 7b9c6413608..0fe8926f7b1 100644 --- a/src/mongo/util/perfctr_collect.cpp +++ b/src/mongo/util/perfctr_collect.cpp @@ -54,10 +54,9 @@ MONGO_INITIALIZER(PdhInit)(InitializerContext* context) { hPdhLibrary = LoadLibraryW(L"pdh.dll"); if (nullptr == hPdhLibrary) { - DWORD gle = GetLastError(); + auto ec = lastSystemError(); uasserted(ErrorCodes::WindowsPdhError, - str::stream() << "LoadLibrary of pdh.dll failed with " - << errnoWithDescription(gle)); + str::stream() << "LoadLibrary of pdh.dll failed with " << errorMessage(ec)); } } diff --git a/src/mongo/util/processinfo_linux.cpp b/src/mongo/util/processinfo_linux.cpp index 37e3d2ea3fc..49b95e5093e 100644 --- a/src/mongo/util/processinfo_linux.cpp +++ b/src/mongo/util/processinfo_linux.cpp @@ -75,8 +75,8 @@ public: auto name = "/proc/{}/stat"_format(pid.asUInt32()); FILE* f = fopen(name.c_str(), "r"); if (!f) { - auto e = errno; - msgasserted(13538, "couldn't open [{}] {}"_format(name, errnoWithDescription(e))); + auto ec = lastSystemError(); + msgasserted(13538, "couldn't open [{}] {}"_format(name, errorMessage(ec))); } int found = fscanf(f, "%d %127s %c " @@ -664,10 +664,10 @@ void ProcessInfo::SystemInfo::collectSystemInfo() { LinuxSysHelper::getLinuxDistro(distroName, distroVersion); if (uname(&unameData) == -1) { - auto e = errno; + auto ec = lastSystemError(); LOGV2(23339, "Unable to collect detailed system information", - "error"_attr = errnoWithDescription(e)); + "error"_attr = errorMessage(ec)); } osType = "Linux"; diff --git a/src/mongo/util/processinfo_solaris.cpp b/src/mongo/util/processinfo_solaris.cpp index 95598132526..5fbb815985c 100644 --- a/src/mongo/util/processinfo_solaris.cpp +++ b/src/mongo/util/processinfo_solaris.cpp @@ -68,15 +68,17 @@ static std::string readLineFromFile(const char* fname) { struct ProcPsinfo { ProcPsinfo() { FILE* f = fopen("/proc/self/psinfo", "r"); - massert(16846, - str::stream() << "couldn't open \"/proc/self/psinfo\": " << errnoWithDescription(), - f); + if (!f) { + auto ec = lastSystemError(); + msgasserted(16846, + str::stream() + << "couldn't open \"/proc/self/psinfo\": " << errorMessage(ec)); + } size_t num = fread(&psinfo, sizeof(psinfo), 1, f); - int err = errno; + auto ec = lastSystemError(); fclose(f); massert(16847, - str::stream() << "couldn't read from \"/proc/self/psinfo\": " - << errnoWithDescription(err), + str::stream() << "couldn't read from \"/proc/self/psinfo\": " << errorMessage(ec), num == 1); } psinfo_t psinfo; @@ -85,15 +87,16 @@ struct ProcPsinfo { struct ProcUsage { ProcUsage() { FILE* f = fopen("/proc/self/usage", "r"); - massert(16848, - str::stream() << "couldn't open \"/proc/self/usage\": " << errnoWithDescription(), - f); + if (!f) { + auto ec = lastSystemError(); + msgasserted( + 16848, str::stream() << "couldn't open \"/proc/self/usage\": " << errorMessage(ec)); + } size_t num = fread(&prusage, sizeof(prusage), 1, f); - int err = errno; + auto ec = lastSystemError(); fclose(f); massert(16849, - str::stream() << "couldn't read from \"/proc/self/usage\": " - << errnoWithDescription(err), + str::stream() << "couldn't read from \"/proc/self/usage\": " << errorMessage(ec), num == 1); } prusage_t prusage; @@ -202,9 +205,10 @@ bool ProcessInfo::checkNumaEnabled() { lgrp_cookie_t cookie = lgrp_init(LGRP_VIEW_OS); if (cookie == LGRP_COOKIE_NONE) { + auto ec = lastSystemError(); LOGV2_WARNING(23362, "lgrp_init failed: {errnoWithDescription}", - "errnoWithDescription"_attr = errnoWithDescription()); + "errnoWithDescription"_attr = errorMessage(ec)); return false; } @@ -213,9 +217,10 @@ bool ProcessInfo::checkNumaEnabled() { int groups = lgrp_nlgrps(cookie); if (groups == -1) { + auto ec = lastSystemError(); LOGV2_WARNING(23363, "lgrp_nlgrps failed: {errnoWithDescription}", - "errnoWithDescription"_attr = errnoWithDescription()); + "errnoWithDescription"_attr = errorMessage(ec)); return false; } diff --git a/src/mongo/util/processinfo_windows.cpp b/src/mongo/util/processinfo_windows.cpp index 5cf7edbdee2..214ef5643cd 100644 --- a/src/mongo/util/processinfo_windows.cpp +++ b/src/mongo/util/processinfo_windows.cpp @@ -77,10 +77,10 @@ LpiRecords getLogicalProcessorInformationRecords() { lpiRecords.slpiRecords = std::unique_ptr<SlpiBuf[]>( new SlpiBuf[((returnLength - 1) / sizeof(Slpi)) + 1]); } else { - DWORD gle = GetLastError(); + auto ec = lastSystemError(); LOGV2_WARNING(23811, "GetLogicalProcessorInformation failed", - "error"_attr = errnoWithDescription(gle)); + "error"_attr = errorMessage(ec)); return LpiRecords{}; } } @@ -147,8 +147,8 @@ int ProcessInfo::getVirtualMemorySize() { mse.dwLength = sizeof(mse); BOOL status = GlobalMemoryStatusEx(&mse); if (!status) { - DWORD gle = GetLastError(); - LOGV2_ERROR(23812, "GlobalMemoryStatusEx failed", "error"_attr = errnoWithDescription(gle)); + auto ec = lastSystemError(); + LOGV2_ERROR(23812, "GlobalMemoryStatusEx failed", "error"_attr = errorMessage(ec)); fassert(28621, status); } @@ -161,8 +161,8 @@ int ProcessInfo::getResidentSize() { PROCESS_MEMORY_COUNTERS pmc; BOOL status = GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)); if (!status) { - DWORD gle = GetLastError(); - LOGV2_ERROR(23813, "GetProcessMemoryInfo failed", "error"_attr = errnoWithDescription(gle)); + auto ec = lastSystemError(); + LOGV2_ERROR(23813, "GetProcessMemoryInfo failed", "error"_attr = errorMessage(ec)); fassert(28622, status); } @@ -193,32 +193,32 @@ void ProcessInfo::getExtraInfo(BSONObjBuilder& info) { bool getFileVersion(const char* filePath, DWORD& fileVersionMS, DWORD& fileVersionLS) { DWORD verSize = GetFileVersionInfoSizeA(filePath, NULL); if (verSize == 0) { - DWORD gle = GetLastError(); + auto ec = lastSystemError(); LOGV2_WARNING(23807, "GetFileVersionInfoSizeA failed", "path"_attr = filePath, - "error"_attr = errnoWithDescription(gle)); + "error"_attr = errorMessage(ec)); return false; } std::unique_ptr<char[]> verData(new char[verSize]); if (GetFileVersionInfoA(filePath, NULL, verSize, verData.get()) == 0) { - DWORD gle = GetLastError(); + auto ec = lastSystemError(); LOGV2_WARNING(23808, "GetFileVersionInfoSizeA failed", "path"_attr = filePath, - "error"_attr = errnoWithDescription(gle)); + "error"_attr = errorMessage(ec)); return false; } UINT size; VS_FIXEDFILEINFO* verInfo; if (VerQueryValueA(verData.get(), "\\", (LPVOID*)&verInfo, &size) == 0) { - DWORD gle = GetLastError(); + auto ec = lastSystemError(); LOGV2_WARNING(23809, "VerQueryValueA failed", "path"_attr = filePath, - "error"_attr = errnoWithDescription(gle)); + "error"_attr = errorMessage(ec)); return false; } diff --git a/src/mongo/util/procparser.cpp b/src/mongo/util/procparser.cpp index 599608c9cc8..c1d85bbf71a 100644 --- a/src/mongo/util/procparser.cpp +++ b/src/mongo/util/procparser.cpp @@ -92,10 +92,10 @@ constexpr auto kSysBlockDeviceDirectoryName = "device"; StatusWith<std::string> readFileAsString(StringData filename) { int fd = open(filename.toString().c_str(), 0); if (fd == -1) { - int err = errno; + auto ec = lastSystemError(); return Status(ErrorCodes::FileOpenFailed, str::stream() << "Failed to open file " << filename - << " with error: " << errnoWithDescription(err)); + << " with error: " << errorMessage(ec)); } ScopeGuard scopedGuard([fd] { close(fd); }); @@ -114,17 +114,18 @@ StatusWith<std::string> readFileAsString(StringData filename) { size_read = read(fd, buf.data(), kFileBufferSize); if (size_read == -1) { - int err = errno; + auto ec = lastPosixError(); - // Retry if we hit EGAIN or EINTR a few times before giving up - if (retry < kFileReadRetryCount && (err == EAGAIN || err == EINTR)) { + // Retry if we hit EAGAIN or EINTR a few times before giving up + if (retry < kFileReadRetryCount && + (ec == posixError(EAGAIN) || ec == posixError(EINTR))) { ++retry; continue; } return Status(ErrorCodes::FileStreamFailed, str::stream() << "Failed to read file " << filename - << " with error: " << errnoWithDescription(err)); + << " with error: " << errorMessage(ec)); } break; diff --git a/src/mongo/util/shell_exec.cpp b/src/mongo/util/shell_exec.cpp index 1adc02dbd4f..cff6e13da75 100644 --- a/src/mongo/util/shell_exec.cpp +++ b/src/mongo/util/shell_exec.cpp @@ -67,41 +67,51 @@ public: // Close our end of stdin immediately to signal child we have no data. HANDLE dummy = nullptr; - uassert(ErrorCodes::OperationFailed, - str::stream() << "Unable to create stdin pipe for subprocess: " - << errnoWithDescription(), - CreatePipe(&dummy, &_startup.hStdInput, &sa, kExecBufferSizeBytes)); + if (!CreatePipe(&dummy, &_startup.hStdInput, &sa, kExecBufferSizeBytes)) { + auto ec = lastSystemError(); + uasserted(ErrorCodes::OperationFailed, + str::stream() + << "Unable to create stdin pipe for subprocess: " << errorMessage(ec)); + } CloseHandle(dummy); - uassert(ErrorCodes::OperationFailed, - str::stream() << "Unable to create stdout pipe for subprocess: " - << errnoWithDescription(), - CreatePipe(&_stdout, &_startup.hStdOutput, &sa, kExecBufferSizeBytes)); + if (!CreatePipe(&_stdout, &_startup.hStdOutput, &sa, kExecBufferSizeBytes)) { + auto ec = lastSystemError(); + uasserted(ErrorCodes::OperationFailed, + str::stream() + << "Unable to create stdout pipe for subprocess: " << errorMessage(ec)); + } - uassert(ErrorCodes::OperationFailed, - str::stream() << "Unable to create stderr pipe for subprocess: " - << errnoWithDescription(), - CreatePipe(&_stderr, &_startup.hStdError, &sa, kExecBufferSizeBytes)); + if (!CreatePipe(&_stderr, &_startup.hStdError, &sa, kExecBufferSizeBytes)) { + auto ec = lastSystemError(); + uasserted(ErrorCodes::OperationFailed, + str::stream() + << "Unable to create stderr pipe for subprocess: " << errorMessage(ec)); + } DWORD mode = PIPE_NOWAIT; - uassert(ErrorCodes::OperationFailed, - str::stream() << "Unable to set non-blocking for subprocess: " - << errnoWithDescription(), - SetNamedPipeHandleState(_stdout, &mode, nullptr, nullptr)); + if (!SetNamedPipeHandleState(_stdout, &mode, nullptr, nullptr)) { + auto ec = lastSystemError(); + uasserted(ErrorCodes::OperationFailed, + str::stream() + << "Unable to set non-blocking for subprocess: " << errorMessage(ec)); + } auto wideCmd = toWideString(cmd.c_str()); - uassert(ErrorCodes::OperationFailed, - str::stream() << "Unable to launch command: " << errnoWithDescription(), - CreateProcessW(nullptr, - const_cast<wchar_t*>(wideCmd.c_str()), - &sa, - &sa, - true, - CREATE_NO_WINDOW, - nullptr, - nullptr, - &_startup, - &_process)); + if (!CreateProcessW(nullptr, + const_cast<wchar_t*>(wideCmd.c_str()), + &sa, + &sa, + true, + CREATE_NO_WINDOW, + nullptr, + nullptr, + &_startup, + &_process)) { + auto ec = lastSystemError(); + uasserted(ErrorCodes::OperationFailed, + str::stream() << "Unable to launch command: " << errorMessage(ec)); + } } int close() { @@ -109,15 +119,19 @@ public: return _exitcode; } - uassert(ErrorCodes::OperationFailed, - str::stream() << "Failed retreiving exit code from subprocess: " - << errnoWithDescription(), - GetExitCodeProcess(_process.hProcess, &_exitcode)); + if (!GetExitCodeProcess(_process.hProcess, &_exitcode)) { + auto ec = lastSystemError(); + uasserted(ErrorCodes::OperationFailed, + str::stream() + << "Failed retreiving exit code from subprocess: " << errorMessage(ec)); + } if (_exitcode == STILL_ACTIVE) { - uassert(ErrorCodes::OperationFailed, - str::stream() << "Failed terminating subprocess: " << errnoWithDescription(), - TerminateProcess(_process.hProcess, 1)); + if (!TerminateProcess(_process.hProcess, 1)) { + auto ec = lastSystemError(); + uasserted(ErrorCodes::OperationFailed, + str::stream() << "Failed terminating subprocess: " << errorMessage(ec)); + } _exitcode = 1; } @@ -129,10 +143,12 @@ public: return true; } - uassert(ErrorCodes::OperationFailed, - str::stream() << "Failed retreiving status of subprocess: " - << errnoWithDescription(), - GetExitCodeProcess(_process.hProcess, &_exitcode)); + if (!GetExitCodeProcess(_process.hProcess, &_exitcode)) { + auto ec = lastSystemError(); + uasserted(ErrorCodes::OperationFailed, + str::stream() + << "Failed retreiving status of subprocess: " << errorMessage(ec)); + } return _exitcode != STILL_ACTIVE; } @@ -144,7 +160,7 @@ public: } else if (ret == WAIT_TIMEOUT) { return {ErrorCodes::OperationFailed, "Timeout expired"}; } else { - return {ErrorCodes::OperationFailed, errnoWithDescription()}; + return {ErrorCodes::OperationFailed, errorMessage(lastSystemError())}; } } @@ -156,9 +172,11 @@ public: char buf[kExecBufferSizeBytes]; DWORD read = 0; - uassert(ErrorCodes::OperationFailed, - str::stream() << "Failed reading from subprocess: " << errnoWithDescription(), - ReadFile(_stdout, buf, std::min<size_t>(sizeof(buf), len), &read, nullptr)); + if (!ReadFile(_stdout, buf, std::min<size_t>(sizeof(buf), len), &read, nullptr)) { + auto ec = lastSystemError(); + uasserted(ErrorCodes::OperationFailed, + str::stream() << "Failed reading from subprocess: " << errorMessage(ec)); + } if (read == 0) { CloseHandle(_stdout); @@ -207,9 +225,11 @@ class ProcessStream { public: ProcessStream(const std::string& cmd) { _fp = ::popen(cmd.c_str(), "r"); - uassert(ErrorCodes::OperationFailed, - str::stream() << "Unable to launch command: " << errnoWithDescription(), - _fp); + if (!_fp) { + auto ec = lastSystemError(); + uasserted(ErrorCodes::OperationFailed, + str::stream() << "Unable to launch command: " << errorMessage(ec)); + } _fd = fileno(_fp); } @@ -234,7 +254,7 @@ public: auto ret = poll(&fds, 1, durationCount<Milliseconds>(duration)); if (ret < 0) { - return {ErrorCodes::OperationFailed, errnoWithDescription()}; + return {ErrorCodes::OperationFailed, errorMessage(lastSystemError())}; } else if (ret == 0) { return {ErrorCodes::OperationFailed, "Timeout expired"}; } else { diff --git a/src/mongo/util/signal_handlers.cpp b/src/mongo/util/signal_handlers.cpp index 95a4bee2ccc..c063600f5c8 100644 --- a/src/mongo/util/signal_handlers.cpp +++ b/src/mongo/util/signal_handlers.cpp @@ -122,10 +122,11 @@ void eventProcessingThread() { HANDLE event = CreateEventA(nullptr, TRUE, FALSE, eventName.c_str()); if (event == nullptr) { + auto ec = lastSystemError(); LOGV2_WARNING(23382, "eventProcessingThread CreateEvent failed: {error}", "eventProcessingThread CreateEvent failed", - "error"_attr = errnoWithDescription()); + "error"_attr = errorMessage(ec)); return; } @@ -134,16 +135,18 @@ void eventProcessingThread() { int returnCode = WaitForSingleObject(event, INFINITE); if (returnCode != WAIT_OBJECT_0) { if (returnCode == WAIT_FAILED) { + auto ec = lastSystemError(); LOGV2_WARNING(23383, "eventProcessingThread WaitForSingleObject failed: {error}", "eventProcessingThread WaitForSingleObject failed", - "error"_attr = errnoWithDescription()); + "error"_attr = errorMessage(ec)); return; } else { + auto ec = systemError(returnCode); LOGV2_WARNING(23384, "eventProcessingThread WaitForSingleObject failed: {error}", "eventProcessingThread WaitForSingleObject failed", - "error"_attr = errnoWithDescription(returnCode)); + "error"_attr = errorMessage(ec)); return; } } diff --git a/src/mongo/util/stacktrace_windows.cpp b/src/mongo/util/stacktrace_windows.cpp index 99ceea9e937..ad9dc61acc6 100644 --- a/src/mongo/util/stacktrace_windows.cpp +++ b/src/mongo/util/stacktrace_windows.cpp @@ -95,8 +95,9 @@ public: const auto symbolPath = symbolPathBuilder.str(); if (!SymInitializeW(handle, symbolPath.c_str(), TRUE)) { + auto ec = lastSystemError(); LOGV2_ERROR( - 31443, "Stack trace initialization failed", "error"_attr = errnoWithDescription()); + 31443, "Stack trace initialization failed", "error"_attr = errorMessage(ec)); return; } diff --git a/src/mongo/util/time_support_test.cpp b/src/mongo/util/time_support_test.cpp index 9306e789137..c90c7c64de1 100644 --- a/src/mongo/util/time_support_test.cpp +++ b/src/mongo/util/time_support_test.cpp @@ -100,7 +100,8 @@ MONGO_INITIALIZER(SetTimeZoneToEasternForTest)(InitializerContext*) { int ret = putenv(tzEnvString); #endif if (ret == -1) { - uasserted(ErrorCodes::BadValue, errnoWithDescription()); + auto ec = lastPosixError(); + uasserted(ErrorCodes::BadValue, errorMessage(ec)); } tzset(); } diff --git a/src/mongo/watchdog/watchdog.cpp b/src/mongo/watchdog/watchdog.cpp index ec3253d805e..1190097067e 100644 --- a/src/mongo/watchdog/watchdog.cpp +++ b/src/mongo/watchdog/watchdog.cpp @@ -351,24 +351,24 @@ void checkFile(OperationContext* opCtx, const boost::filesystem::path& file) { FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { - std::uint32_t gle = ::GetLastError(); + auto ec = lastSystemError(); LOGV2_FATAL_CONTINUE(23416, "CreateFile failed for '{file_generic_string}' with error: " "{errnoWithDescription_gle}", "file_generic_string"_attr = file.generic_string(), - "errnoWithDescription_gle"_attr = errnoWithDescription(gle)); - fassertNoTrace(4074, gle == 0); + "errnoWithDescription_gle"_attr = errorMessage(ec)); + fassertNoTrace(4074, !ec); } DWORD bytesWrittenTotal; if (!WriteFile(hFile, nowStr.c_str(), nowStr.size(), &bytesWrittenTotal, NULL)) { - std::uint32_t gle = ::GetLastError(); + auto ec = lastSystemError(); LOGV2_FATAL_CONTINUE( 23417, "WriteFile failed for '{file_generic_string}' with error: {errnoWithDescription_gle}", "file_generic_string"_attr = file.generic_string(), - "errnoWithDescription_gle"_attr = errnoWithDescription(gle)); - fassertNoTrace(4075, gle == 0); + "errnoWithDescription_gle"_attr = errorMessage(ec)); + fassertNoTrace(4075, !ec); } if (bytesWrittenTotal != nowStr.size()) { @@ -381,36 +381,36 @@ void checkFile(OperationContext* opCtx, const boost::filesystem::path& file) { } else { if (!FlushFileBuffers(hFile)) { - std::uint32_t gle = ::GetLastError(); + auto ec = lastSystemError(); LOGV2_FATAL_CONTINUE(23418, "FlushFileBuffers failed for '{file_generic_string}' with error: " "{errnoWithDescription_gle}", "file_generic_string"_attr = file.generic_string(), - "errnoWithDescription_gle"_attr = errnoWithDescription(gle)); - fassertNoTrace(4076, gle == 0); + "errnoWithDescription_gle"_attr = errorMessage(ec)); + fassertNoTrace(4076, !ec); } DWORD newOffset = SetFilePointer(hFile, 0, 0, FILE_BEGIN); if (newOffset != 0) { - std::uint32_t gle = ::GetLastError(); + auto ec = lastSystemError(); LOGV2_FATAL_CONTINUE(23419, "SetFilePointer failed for '{file_generic_string}' with error: " "{errnoWithDescription_gle}", "file_generic_string"_attr = file.generic_string(), - "errnoWithDescription_gle"_attr = errnoWithDescription(gle)); - fassertNoTrace(4077, gle == 0); + "errnoWithDescription_gle"_attr = errorMessage(ec)); + fassertNoTrace(4077, !ec); } DWORD bytesRead; auto readBuffer = std::make_unique<char[]>(nowStr.size()); if (!ReadFile(hFile, readBuffer.get(), nowStr.size(), &bytesRead, NULL)) { - std::uint32_t gle = ::GetLastError(); + auto ec = lastSystemError(); LOGV2_FATAL_CONTINUE(23420, "ReadFile failed for '{file_generic_string}' with error: " "{errnoWithDescription_gle}", "file_generic_string"_attr = file.generic_string(), - "errnoWithDescription_gle"_attr = errnoWithDescription(gle)); - fassertNoTrace(4078, gle == 0); + "errnoWithDescription_gle"_attr = errorMessage(ec)); + fassertNoTrace(4078, !ec); } if (bytesRead != bytesWrittenTotal) { @@ -437,13 +437,13 @@ void checkFile(OperationContext* opCtx, const boost::filesystem::path& file) { } if (!CloseHandle(hFile)) { - std::uint32_t gle = ::GetLastError(); + auto ec = lastSystemError(); LOGV2_FATAL_CONTINUE( 23423, "CloseHandle failed for '{file_generic_string}' with error: {errnoWithDescription_gle}", "file_generic_string"_attr = file.generic_string(), - "errnoWithDescription_gle"_attr = errnoWithDescription(gle)); - fassertNoTrace(4079, gle == 0); + "errnoWithDescription_gle"_attr = errorMessage(ec)); + fassertNoTrace(4079, !ec); } } @@ -466,13 +466,13 @@ void checkFile(OperationContext* opCtx, const boost::filesystem::path& file) { int fd = open(file.generic_string().c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); if (fd == -1) { - auto err = errno; + auto ec = lastSystemError(); LOGV2_FATAL_CONTINUE( 23424, "open failed for '{file_generic_string}' with error: {errnoWithDescription_err}", "file_generic_string"_attr = file.generic_string(), - "errnoWithDescription_err"_attr = errnoWithDescription(err)); - fassertNoTrace(4080, err == 0); + "errnoWithDescription_err"_attr = errorMessage(ec)); + fassertNoTrace(4080, !ec); } size_t bytesWrittenTotal = 0; @@ -480,8 +480,8 @@ void checkFile(OperationContext* opCtx, const boost::filesystem::path& file) { ssize_t bytesWrittenInWrite = write(fd, nowStr.c_str() + bytesWrittenTotal, nowStr.size() - bytesWrittenTotal); if (bytesWrittenInWrite == -1) { - auto err = errno; - if (err == EINTR) { + auto ec = lastSystemError(); + if (ec == systemError(EINTR)) { continue; } @@ -489,8 +489,8 @@ void checkFile(OperationContext* opCtx, const boost::filesystem::path& file) { 23425, "write failed for '{file_generic_string}' with error: {errnoWithDescription_err}", "file_generic_string"_attr = file.generic_string(), - "errnoWithDescription_err"_attr = errnoWithDescription(err)); - fassertNoTrace(4081, err == 0); + "errnoWithDescription_err"_attr = errorMessage(ec)); + fassertNoTrace(4081, !ec); } // Warn if the write was incomplete @@ -507,13 +507,13 @@ void checkFile(OperationContext* opCtx, const boost::filesystem::path& file) { } if (fsync(fd)) { - auto err = errno; + auto ec = lastSystemError(); LOGV2_FATAL_CONTINUE( 23426, "fsync failed for '{file_generic_string}' with error: {errnoWithDescription_err}", "file_generic_string"_attr = file.generic_string(), - "errnoWithDescription_err"_attr = errnoWithDescription(err)); - fassertNoTrace(4082, err == 0); + "errnoWithDescription_err"_attr = errorMessage(ec)); + fassertNoTrace(4082, !ec); } auto readBuffer = std::make_unique<char[]>(nowStr.size()); @@ -522,8 +522,8 @@ void checkFile(OperationContext* opCtx, const boost::filesystem::path& file) { ssize_t bytesReadInRead = pread( fd, readBuffer.get() + bytesReadTotal, nowStr.size() - bytesReadTotal, bytesReadTotal); if (bytesReadInRead == -1) { - auto err = errno; - if (err == EINTR) { + auto ec = lastSystemError(); + if (ec == systemError(EINTR)) { continue; } @@ -531,8 +531,8 @@ void checkFile(OperationContext* opCtx, const boost::filesystem::path& file) { 23427, "read failed for '{file_generic_string}' with error: {errnoWithDescription_err}", "file_generic_string"_attr = file.generic_string(), - "errnoWithDescription_err"_attr = errnoWithDescription(err)); - fassertNoTrace(4083, err == 0); + "errnoWithDescription_err"_attr = errorMessage(ec)); + fassertNoTrace(4083, !ec); } else if (bytesReadInRead == 0) { LOGV2_FATAL_NOTRACE( 50719, @@ -567,13 +567,13 @@ void checkFile(OperationContext* opCtx, const boost::filesystem::path& file) { } if (close(fd)) { - auto err = errno; + auto ec = lastSystemError(); LOGV2_FATAL_CONTINUE( 23430, "close failed for '{file_generic_string}' with error: {errnoWithDescription_err}", "file_generic_string"_attr = file.generic_string(), - "errnoWithDescription_err"_attr = errnoWithDescription(err)); - fassertNoTrace(4084, err == 0); + "errnoWithDescription_err"_attr = errorMessage(ec)); + fassertNoTrace(4084, !ec); } } |