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 <tinyformat.h> 8 #include <util/syserror.h> 9 10 #include <cstring> 11 #include <string> 12 13 #if defined(WIN32) 14 #include <windows.h> 15 #endif 16 17 std::string SysErrorString(int err) 18 { 19 char buf[1024]; 20 /* Too bad there are three incompatible implementations of the 21 * thread-safe strerror. */ 22 const char *s = nullptr; 23 #ifdef WIN32 24 if (strerror_s(buf, sizeof(buf), err) == 0) s = buf; 25 #else 26 #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */ 27 s = strerror_r(err, buf, sizeof(buf)); 28 #else /* POSIX variant always returns message in buffer */ 29 if (strerror_r(err, buf, sizeof(buf)) == 0) s = buf; 30 #endif 31 #endif 32 if (s != nullptr) { 33 return strprintf("%s (%d)", s, err); 34 } else { 35 return strprintf("Unknown error (%d)", err); 36 } 37 } 38 39 #if defined(WIN32) 40 std::string Win32ErrorString(int err) 41 { 42 char buf[256]; 43 buf[0] = 0; 44 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK, 45 nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 46 buf, ARRAYSIZE(buf), nullptr)) { 47 return strprintf("%s (%d)", buf, err); 48 } else { 49 return strprintf("Unknown error (%d)", err); 50 } 51 } 52 #endif