Simplify implementation of save_err_str() Check return value of FormatMessageA() function and remove copy_string() function as it is not needed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
diff --git a/dlfcn.c b/dlfcn.c
index 475b069..8687c51 100644
--- a/dlfcn.c
+++ b/dlfcn.c
@@ -133,45 +133,41 @@ static char error_buffer[65535];
static char *current_error;
static char dlerror_buffer[65536];
-static int copy_string( char *dest, int dest_size, const char *src )
-{
- int i = 0;
-
- /* gcc should optimize this out */
- if( !src || !dest )
- return 0;
-
- for( i = 0 ; i < dest_size-1 ; i++ )
- {
- if( !src[i] )
- break;
- else
- dest[i] = src[i];
- }
- dest[i] = '\0';
-
- return i;
-}
-
static void save_err_str( const char *str )
{
DWORD dwMessageId;
- DWORD pos;
+ DWORD ret;
+ size_t pos, len;
dwMessageId = GetLastError( );
if( dwMessageId == 0 )
return;
+ len = strlen( str );
+ if( len > sizeof( error_buffer ) - 5 )
+ len = sizeof( error_buffer ) - 5;
+
/* Format error message to:
* "<argument to function that failed>": <Windows localized error message>
*/
- pos = copy_string( error_buffer, sizeof(error_buffer), "\"" );
- pos += copy_string( error_buffer+pos, sizeof(error_buffer)-pos, str );
- pos += copy_string( error_buffer+pos, sizeof(error_buffer)-pos, "\": " );
- pos += FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwMessageId,
+ pos = 0;
+ error_buffer[pos++] = '"';
+ memcpy( error_buffer+pos, str, len );
+ pos += len;
+ error_buffer[pos++] = '"';
+ error_buffer[pos++] = ':';
+ error_buffer[pos++] = ' ';
+
+ ret = FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwMessageId,
MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),
- error_buffer+pos, sizeof(error_buffer)-pos, NULL );
+ error_buffer+pos, (DWORD) (sizeof(error_buffer)-pos), NULL );
+ pos += ret;
+
+ /* When FormatMessageA() fails it returns zero and does not touch buffer
+ * so add trailing null byte */
+ if( ret == 0 )
+ error_buffer[pos] = '\0';
if( pos > 1 )
{