Skip to content

Commit 2cb9a4f

Browse files
elojslouken
authored andcommitted
log: Fix unlikely out-of-bounds issue.
In the unlikely case that the overflow check should fail, the else clause would switch to the truncated stack message without updating the len variable. This would contain the return value from vsnprintf(), meaning it could point beyond the buffer. The subsequent code which trims NL and CR from the buffer, would then read -- and possibly write -- out-of-bounds. To fix this, we split the two joint conditions into separate if-clauses, and adjust the len variable in the case where we know the message buffer was truncated.
1 parent bc17a89 commit 2cb9a4f

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

src/SDL_log.c

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -612,15 +612,21 @@ void SDL_LogMessageV(int category, SDL_LogPriority priority, SDL_PRINTF_FORMAT_S
612612
}
613613

614614
// If message truncated, allocate and re-render
615-
if (len >= sizeof(stack_buf) && SDL_size_add_check_overflow(len, 1, &len_plus_term)) {
616-
// Allocate exactly what we need, including the zero-terminator
617-
message = (char *)SDL_malloc(len_plus_term);
618-
if (!message) {
619-
return;
615+
if (len >= sizeof(stack_buf)) {
616+
if (SDL_size_add_check_overflow(len, 1, &len_plus_term)) {
617+
// Allocate exactly what we need, including the zero-terminator
618+
message = (char *)SDL_malloc(len_plus_term);
619+
if (!message) {
620+
return;
621+
}
622+
va_copy(aq, ap);
623+
len = SDL_vsnprintf(message, len_plus_term, fmt, aq);
624+
va_end(aq);
625+
} else {
626+
// Allocation would overflow, use truncated message
627+
message = stack_buf;
628+
len = sizeof(stack_buf);
620629
}
621-
va_copy(aq, ap);
622-
len = SDL_vsnprintf(message, len_plus_term, fmt, aq);
623-
va_end(aq);
624630
} else {
625631
message = stack_buf;
626632
}

0 commit comments

Comments
 (0)