diff --git a/app/src/util/log.c b/app/src/util/log.c index a285fffb..d8d7cd70 100644 --- a/app/src/util/log.c +++ b/app/src/util/log.c @@ -1,5 +1,8 @@ #include "log.h" +#if _WIN32 +# include +#endif #include static SDL_LogPriority @@ -51,3 +54,24 @@ sc_get_log_level(void) { SDL_LogPriority sdl_log = SDL_LogGetPriority(SDL_LOG_CATEGORY_APPLICATION); return log_level_sdl_to_sc(sdl_log); } + +#ifdef _WIN32 +bool +sc_log_windows_error(const char *prefix, int error) { + assert(prefix); + + char *message; + DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM; + DWORD lang_id = MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US); + int ret = + FormatMessage(flags, NULL, error, lang_id, (char *) &message, 0, NULL); + if (ret <= 0) { + return false; + } + + // Note: message already contains a trailing '\n' + LOGE("%s: [%d] %s", prefix, error, message); + LocalFree(message); + return true; +} +#endif diff --git a/app/src/util/log.h b/app/src/util/log.h index 231e0846..e3efdbe5 100644 --- a/app/src/util/log.h +++ b/app/src/util/log.h @@ -26,4 +26,10 @@ sc_set_log_level(enum sc_log_level level); enum sc_log_level sc_get_log_level(void); +#ifdef _WIN32 +// Log system error (typically returned by GetLastError() or similar) +bool +sc_log_windows_error(const char *prefix, int error); +#endif + #endif diff --git a/app/src/util/net.c b/app/src/util/net.c index 565db2e9..b18566be 100644 --- a/app/src/util/net.c +++ b/app/src/util/net.c @@ -117,14 +117,7 @@ set_cloexec_flag(sc_raw_socket raw_sock) { static void net_perror(const char *s) { #ifdef _WIN32 - int error = WSAGetLastError(); - char *wsa_message; - FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, - NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (char *) &wsa_message, 0, NULL); - // no explicit '\n', wsa_message already contains a trailing '\n' - fprintf(stderr, "%s: [%d] %s", s, error, wsa_message); - LocalFree(wsa_message); + sc_log_windows_error(s, WSAGetLastError()); #else perror(s); #endif