فهرست منبع

mingw: Add formatLastError as wrapper function for FormatMessage

Tatsuhiro Tsujikawa 9 سال پیش
والد
کامیت
25243da039
4فایلهای تغییر یافته به همراه35 افزوده شده و 13 حذف شده
  1. 5 7
      src/AbstractDiskWriter.cc
  2. 5 6
      src/SocketCore.cc
  3. 18 0
      src/util.cc
  4. 7 0
      src/util.h

+ 5 - 7
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__

+ 5 - 6
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

+ 18 - 0
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<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 aria2

+ 7 - 0
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