mingw: Add formatLastError as wrapper function for FormatMessage

pull/547/head
Tatsuhiro Tsujikawa 2016-01-28 22:25:46 +09:00
parent ad6d799b98
commit 25243da039
4 changed files with 35 additions and 13 deletions

View File

@ -93,15 +93,13 @@ namespace {
std::string fileStrerror(int errNum) std::string fileStrerror(int errNum)
{ {
#ifdef __MINGW32__ #ifdef __MINGW32__
static char buf[256]; auto msg = util::formatLastError(errNum);
if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, if (msg.empty()) {
0, errNum, char buf[256];
// Default language
MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (LPTSTR)&buf,
sizeof(buf), 0) == 0) {
snprintf(buf, sizeof(buf), "File I/O error %x", errNum); snprintf(buf, sizeof(buf), "File I/O error %x", errNum);
return buf;
} }
return buf; return msg;
#else // !__MINGW32__ #else // !__MINGW32__
return util::safeStrerror(errNum); return util::safeStrerror(errNum);
#endif // !__MINGW32__ #endif // !__MINGW32__

View File

@ -105,14 +105,13 @@ std::string errorMsg(int errNum)
#ifndef __MINGW32__ #ifndef __MINGW32__
return util::safeStrerror(errNum); return util::safeStrerror(errNum);
#else #else
static char buf[256]; auto msg = util::formatLastError(errNum);
if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, if (msg.empty()) {
nullptr, errNum, char buf[256];
MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (LPTSTR)&buf,
sizeof(buf), nullptr) == 0) {
snprintf(buf, sizeof(buf), EX_SOCKET_UNKNOWN_ERROR, errNum, errNum); snprintf(buf, sizeof(buf), EX_SOCKET_UNKNOWN_ERROR, errNum, errNum);
return buf;
} }
return buf; return msg;
#endif // __MINGW32__ #endif // __MINGW32__
} }
} // namespace } // namespace

View File

@ -2087,6 +2087,24 @@ TLSVersion toTLSVersion(const std::string& ver)
} }
#endif // ENABLE_SSL #endif // ENABLE_SSL
#ifdef __MINGW32__
std::string formatLastError(int errNum)
{
std::array<char, 4_k> buf;
if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, errNum,
// Default language
MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
static_cast<LPTSTR>(buf.data()), buf.size(),
nullptr) == 0) {
return "";
}
return buf.data();
}
#endif // __MINGW32__
} // namespace util } // namespace util
} // namespace aria2 } // namespace aria2

View File

@ -855,6 +855,13 @@ bool tlsHostnameMatch(const std::string& pattern, const std::string& hostname);
TLSVersion toTLSVersion(const std::string& ver); TLSVersion toTLSVersion(const std::string& ver);
#endif // ENABLE_SSL #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 util
} // namespace aria2 } // namespace aria2