diff --git a/src/AbstractDiskWriter.cc b/src/AbstractDiskWriter.cc index 931ee88a..b3b4bd8d 100644 --- a/src/AbstractDiskWriter.cc +++ b/src/AbstractDiskWriter.cc @@ -93,15 +93,13 @@ namespace { std::string fileStrerror(int errNum) { #ifdef __MINGW32__ - static char buf[256]; - if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - 0, errNum, - // Default language - MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (LPTSTR)&buf, - sizeof(buf), 0) == 0) { + auto msg = util::formatLastError(errNum); + if (msg.empty()) { + char buf[256]; snprintf(buf, sizeof(buf), "File I/O error %x", errNum); + return buf; } - return buf; + return msg; #else // !__MINGW32__ return util::safeStrerror(errNum); #endif // !__MINGW32__ diff --git a/src/SocketCore.cc b/src/SocketCore.cc index 8358527e..50e974f5 100644 --- a/src/SocketCore.cc +++ b/src/SocketCore.cc @@ -105,14 +105,13 @@ std::string errorMsg(int errNum) #ifndef __MINGW32__ return util::safeStrerror(errNum); #else - static char buf[256]; - if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - nullptr, errNum, - MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (LPTSTR)&buf, - sizeof(buf), nullptr) == 0) { + auto msg = util::formatLastError(errNum); + if (msg.empty()) { + char buf[256]; snprintf(buf, sizeof(buf), EX_SOCKET_UNKNOWN_ERROR, errNum, errNum); + return buf; } - return buf; + return msg; #endif // __MINGW32__ } } // namespace diff --git a/src/util.cc b/src/util.cc index 5353ff04..7cfbf237 100644 --- a/src/util.cc +++ b/src/util.cc @@ -2087,6 +2087,24 @@ TLSVersion toTLSVersion(const std::string& ver) } #endif // ENABLE_SSL + +#ifdef __MINGW32__ +std::string formatLastError(int errNum) +{ + std::array buf; + if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + nullptr, errNum, + // Default language + MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), + static_cast(buf.data()), buf.size(), + nullptr) == 0) { + return ""; + } + + return buf.data(); +} +#endif // __MINGW32__ + } // namespace util } // namespace aria2 diff --git a/src/util.h b/src/util.h index e7ebb816..fe802af4 100644 --- a/src/util.h +++ b/src/util.h @@ -855,6 +855,13 @@ bool tlsHostnameMatch(const std::string& pattern, const std::string& hostname); TLSVersion toTLSVersion(const std::string& ver); #endif // ENABLE_SSL +#ifdef __MINGW32__ +// Formats error message for error code errNum, which is the return +// value of GetLastError(). On error, this function returns empty +// string. +std::string formatLastError(int errNum); +#endif // __MINGW32__ + } // namespace util } // namespace aria2