🐛 Fix NULL pointer in SD sort without name caching (#28909)

With SDSORT_USES_RAM minus SDSORT_CACHE_NAMES and SDSORT_USES_STACK, the sortnames pointer is declared (as its declaration covers DISABLED(SDSORT_USES_STACK)) but the constructor only assigned it under ENABLED(SDSORT_CACHE_NAMES). presort() then writes through the NULL pointer via SET_SORTNAME, hard-faulting the board (e.g. LPC1768) as soon as an SD card with two or more files is mounted.

Assign sortnames whenever it is declared and not heap-allocated: whenever SDSORT_DYNAMIC_RAM is off and either SDSORT_CACHE_NAMES is on or SDSORT_USES_STACK is off. This also skips the wasted static allocation when SDSORT_DYNAMIC_RAM applies.

Add a build test (LPC1768/config-07) covering the crashing combo.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
CaldurG 2026-11-26 08:43:35 +01:00 • committed by GitHub
parent 7de72fd0ab
commit 830009b890
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 20 additions and 9 deletions

View file

@ -163,15 +163,13 @@ CardReader::CardReader() {
static uint8_t sort_order_static[SDSORT_LIMIT];
sort_order = sort_order_static;
#endif
#if ENABLED(SDSORT_CACHE_NAMES)
#if DISABLED(SDSORT_DYNAMIC_RAM)
static char sortshort_static[SDSORT_LIMIT][FILENAME_LENGTH];
sortshort = sortshort_static;
#endif
#if !ALL(SDSORT_DYNAMIC_RAM, SDSORT_USES_STACK)
static char sortnames_static[SDSORT_LIMIT][SORTED_LONGNAME_STORAGE];
sortnames = sortnames_static;
#endif
#if ENABLED(SDSORT_CACHE_NAMES) && DISABLED(SDSORT_DYNAMIC_RAM)
static char sortshort_static[SDSORT_LIMIT][FILENAME_LENGTH];
sortshort = sortshort_static;
#endif
#if ENABLED(SDSORT_USES_RAM) && DISABLED(SDSORT_DYNAMIC_RAM) && (ENABLED(SDSORT_CACHE_NAMES) || DISABLED(SDSORT_USES_STACK))
static char sortnames_static[SDSORT_LIMIT][SORTED_LONGNAME_STORAGE];
sortnames = sortnames_static;
#endif
sort_count = 0;

View file

@ -0,0 +1,13 @@
#
# Marlin Firmware
# Test: LPC1768/config-07.ini
#
# MKS SBASE with SD sorting using RAM without name caching.
#
[config:base]
motherboard = BOARD_MKS_SBASE
reprap_discount_smart_controller = on
sdsupport = on
sdcard_sort_alpha = on
sdsort_uses_ram = true