From 2bc282d216ba3eae7a263eef90c9b11da6064457 Mon Sep 17 00:00:00 2001 From: Charlie Savage Date: Wed, 19 Apr 2023 22:38:29 -0700 Subject: On Windows FormatMessageA can return a NULL message - for example when trying to load a 32bit dll from a 64 bit program (garbage.so in the test suite). Since the passed in buffer contains junk data the resulting error message full of garbage characters which makes it impossible to know what the problem is. This commit updates the message so that it at least returns the error code (in this case 193) which makes it possible to debug the problem. --- ext/ffi_c/DynamicLibrary.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/ext/ffi_c/DynamicLibrary.c b/ext/ffi_c/DynamicLibrary.c index 9bfe86e..6c27ec6 100644 --- a/ext/ffi_c/DynamicLibrary.c +++ b/ext/ffi_c/DynamicLibrary.c @@ -225,8 +225,16 @@ dl_open(const char* name, int flags) static void dl_error(char* buf, int size) { - FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), - 0, buf, size, NULL); + // Get the last error code + DWORD error = GetLastError(); + + // Get the associated message + LPSTR message = NULL; + FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, + NULL, error, 0, (LPSTR)&message, 0, NULL); + + // Update the passed in buffer + snprintf(buf, size, "Failed with error %d: %s", error, message); } #endif -- cgit v1.2.1