From f5327ba5cac39df2072b5a3fed0f84acb6408138 Mon Sep 17 00:00:00 2001 From: Trumeet Date: Fri, 22 Jul 2022 19:47:04 -0700 Subject: feat(libacron): complete Win32 error message formatting The former approach, strerror(3), is not working on Win32 errors (GetLastError()) or WinSock errors (WSAGetLastError()). Signed-off-by: Trumeet --- client/libacron/library.c | 1 + client/libacron/private/helpers.c | 36 ++++++++++++++++++++++++++++++++++-- client/libacron/private/helpers.h | 5 +++++ 3 files changed, 40 insertions(+), 2 deletions(-) diff --git a/client/libacron/library.c b/client/libacron/library.c index c014ed9..e2ee872 100644 --- a/client/libacron/library.c +++ b/client/libacron/library.c @@ -42,5 +42,6 @@ int ac_free(void) { } free(config); config = NULL; + helpers_cleanup(); return AC_E_OK; } \ No newline at end of file diff --git a/client/libacron/private/helpers.c b/client/libacron/private/helpers.c index 5a23e34..0cb452b 100644 --- a/client/libacron/private/helpers.c +++ b/client/libacron/private/helpers.c @@ -12,6 +12,10 @@ #include #include +#ifdef WIN32 +#include +#endif + int alloc(void *existing, unsigned int count, unsigned int bytes, @@ -49,17 +53,45 @@ int strdup2(const char *str, char **out) { return AC_E_OK; } +#ifdef WIN32 +static _Thread_local LPTSTR err_buf = NULL; +#else static _Thread_local char err_buf[1024]; +#endif char *strerror2(int errnum) { #ifdef WIN32 - /* Win32 strerror(3) is thread-safe. */ - return strerror(errnum); + if (err_buf) { + LocalFree(err_buf); + err_buf = NULL; + } + FormatMessage( + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + errnum, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPTSTR) &err_buf, + 0, + NULL); + if (!err_buf) { + return "Unknown error"; + } #else int r; if ((r = strerror_r(errnum, err_buf, sizeof(err_buf) / sizeof(char)))) { snprintf(err_buf, 1024, "%d (%d)", errnum, r); } +#endif return err_buf; +} + +void helpers_cleanup(void) { +#ifdef WIN32 + if (err_buf) { + LocalFree(err_buf); + err_buf = NULL; + } #endif } \ No newline at end of file diff --git a/client/libacron/private/helpers.h b/client/libacron/private/helpers.h index f1635a6..c6500b8 100644 --- a/client/libacron/private/helpers.h +++ b/client/libacron/private/helpers.h @@ -42,4 +42,9 @@ int strdup2(const char *str, char **out); */ char *strerror2(int errnum); +/** + * Cleanup any necessary memory during exit of the current thread. + */ +void helpers_cleanup(void); + #endif /* LIBAC_HELPERS_H */ -- cgit v1.2.3