syserror.cpp
1 // Copyright (c) 2020-present The Bitcoin Core developers 2 // Distributed under the MIT software license, see the accompanying 3 // file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 5 #include <bitcoin-build-config.h> // IWYU pragma: keep 6 7 #include <util/syserror.h> 8 9 #include <tinyformat.h> 10 11 #include <cstring> 12 #include <string> 13 14 #if defined(WIN32) 15 #include <windows.h> 16 #endif 17 18 std::string SysErrorString(int err) 19 { 20 char buf[1024]; 21 /* Too bad there are three incompatible implementations of the 22 * thread-safe strerror. */ 23 const char *s = nullptr; 24 #ifdef WIN32 25 if (strerror_s(buf, sizeof(buf), err) == 0) s = buf; 26 #else 27 #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */ 28 s = strerror_r(err, buf, sizeof(buf)); 29 #else /* POSIX variant always returns message in buffer */ 30 if (strerror_r(err, buf, sizeof(buf)) == 0) s = buf; 31 #endif 32 #endif 33 if (s != nullptr) { 34 return strprintf("%s (%d)", s, err); 35 } else { 36 return strprintf("Unknown error (%d)", err); 37 } 38 } 39 40 #if defined(WIN32) 41 std::string Win32ErrorString(int err) 42 { 43 char buf[256]; 44 buf[0] = 0; 45 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK, 46 nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 47 buf, ARRAYSIZE(buf), nullptr)) { 48 return strprintf("%s (%d)", buf, err); 49 } else { 50 return strprintf("Unknown error (%d)", err); 51 } 52 } 53 #endif