SDL_image: Fix heap-buffer-overflow WRITE in LBM palette (CWE-122) (4f370)

From 4f3700485ef7ecef0b93dd15b0ae9268edc5d0fb Mon Sep 17 00:00:00 2001
From: Jorge Barredo Ferreira <[EMAIL REDACTED]>
Date: Mon, 6 Apr 2026 19:29:38 +0200
Subject: [PATCH] Fix heap-buffer-overflow WRITE in LBM palette (CWE-122)

When nbplanes > 8 without HAM flag, nbrcolorsfinal exceeds 256,
causing writes past the palette buffer. Reject nbplanes > 8 for
paletted images.

(cherry picked from commit 2fe0746733c9f280d2c344bce231dd70fdf3bdb8)
---
 src/IMG_lbm.c | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/src/IMG_lbm.c b/src/IMG_lbm.c
index 66215e6f0..bb10f9006 100644
--- a/src/IMG_lbm.c
+++ b/src/IMG_lbm.c
@@ -232,6 +232,13 @@ SDL_Surface *IMG_LoadLBM_RW( SDL_RWops *src )
 
     nbplanes = bmhd.planes;
 
+    /* Sanity check: nbplanes must not exceed 8 for paletted images.
+       Higher values cause 1<<nbplanes to exceed the 256-entry palette. */
+    if ( !pbm && nbplanes > 8 && nbplanes != 24 && flagHAM == 0 ) {
+        SDL_SetError("LBM: invalid number of bitplanes (%u)", nbplanes);
+        goto done;
+    }
+
     if ( pbm )                         /* File format : 'Packed Bitmap' */
     {
         bytesperline *= 8;