Skip to content

Commit

Permalink
log: Use malloc for long messages.
Browse files Browse the repository at this point in the history
For short messages, use a stack buffer that is
significantly smaller than SDL_MAX_LOG_MESSAGE.

The rationale for this is that we don't want to risk
blowing the stack, while at the same time we would
like to not put pressure on the memory allocator unless
absolutely necessary.
  • Loading branch information
eloj authored and slouken committed Apr 29, 2022
1 parent 73448fe commit 645db21
Showing 1 changed file with 30 additions and 6 deletions.
36 changes: 30 additions & 6 deletions src/SDL_log.c
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@
#include <android/log.h>
#endif

/* The size of the stack buffer to use for rendering log messages. */
#define SDL_MAX_LOG_MESSAGE_STACK 256

#define DEFAULT_PRIORITY SDL_LOG_PRIORITY_CRITICAL
#define DEFAULT_ASSERT_PRIORITY SDL_LOG_PRIORITY_WARN
#define DEFAULT_APPLICATION_PRIORITY SDL_LOG_PRIORITY_INFO
Expand Down Expand Up @@ -285,8 +288,10 @@ GetCategoryPrefix(int category)
void
SDL_LogMessageV(int category, SDL_LogPriority priority, const char *fmt, va_list ap)
{
static char message[SDL_MAX_LOG_MESSAGE];
char *message = NULL;
char stack_buf[SDL_MAX_LOG_MESSAGE_STACK];
size_t len;
va_list aq;

/* Nothing to do if we don't have an output function */
if (!SDL_log_function) {
Expand All @@ -308,26 +313,45 @@ SDL_LogMessageV(int category, SDL_LogPriority priority, const char *fmt, va_list
log_function_mutex = SDL_CreateMutex();
}

if (log_function_mutex) {
SDL_LockMutex(log_function_mutex);
}
/* Render into stack buffer */
va_copy(aq, ap);
len = SDL_vsnprintf(stack_buf, sizeof(stack_buf), fmt, aq);
va_end(aq);

SDL_vsnprintf(message, SDL_MAX_LOG_MESSAGE, fmt, ap);
/* If message truncated, allocate and re-render */
if (len >= sizeof(stack_buf)) {
message = (char *)SDL_malloc(SDL_MAX_LOG_MESSAGE);
if (!message)
return;
va_copy(aq, ap);
len = SDL_vsnprintf(message, SDL_MAX_LOG_MESSAGE, fmt, aq);
va_end(aq);
} else {
message = stack_buf;
}

/* Chop off final endline. */
len = SDL_strlen(message);
if ((len > 0) && (message[len-1] == '\n')) {
message[--len] = '\0';
if ((len > 0) && (message[len-1] == '\r')) { /* catch "\r\n", too. */
message[--len] = '\0';
}
}

if (log_function_mutex) {
SDL_LockMutex(log_function_mutex);
}

SDL_log_function(SDL_log_userdata, category, priority, message);

if (log_function_mutex) {
SDL_UnlockMutex(log_function_mutex);
}

/* Free only if dynamically allocated */
if (message != stack_buf) {
SDL_free(message);
}
}

#if defined(__WIN32__) && !defined(HAVE_STDIO_H) && !defined(__WINRT__)
Expand Down

0 comments on commit 645db21

Please sign in to comment.