SDL: log: Fix unlikely out-of-bounds issue. (df145)

From df145a9649730713d15c1444e37f47d4f3c3bf51 Mon Sep 17 00:00:00 2001
From: Eddy Jansson <[EMAIL REDACTED]>
Date: Thu, 4 Dec 2025 20:43:30 +0100
Subject: [PATCH] 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.

(cherry picked from commit 2cb9a4fcc14121305e9a0975ded67bc67a66ae57)
---
 src/SDL_log.c | 22 ++++++++++++++--------
 1 file changed, 14 insertions(+), 8 deletions(-)

diff --git a/src/SDL_log.c b/src/SDL_log.c
index 10a814ff1b272..0a378e29200e6 100644
--- a/src/SDL_log.c
+++ b/src/SDL_log.c
@@ -597,15 +597,21 @@ void SDL_LogMessageV(int category, SDL_LogPriority priority, SDL_PRINTF_FORMAT_S
     }
 
     // If message truncated, allocate and re-render
-    if (len >= sizeof(stack_buf) && SDL_size_add_check_overflow(len, 1, &len_plus_term)) {
-        // Allocate exactly what we need, including the zero-terminator
-        message = (char *)SDL_malloc(len_plus_term);
-        if (!message) {
-            return;
+    if (len >= sizeof(stack_buf)) {
+        if (SDL_size_add_check_overflow(len, 1, &len_plus_term)) {
+            // Allocate exactly what we need, including the zero-terminator
+            message = (char *)SDL_malloc(len_plus_term);
+            if (!message) {
+                return;
+            }
+            va_copy(aq, ap);
+            len = SDL_vsnprintf(message, len_plus_term, fmt, aq);
+            va_end(aq);
+        } else {
+            // Allocation would overflow, use truncated message
+            message = stack_buf;
+            len = sizeof(stack_buf);
         }
-        va_copy(aq, ap);
-        len = SDL_vsnprintf(message, len_plus_term, fmt, aq);
-        va_end(aq);
     } else {
         message = stack_buf;
     }