Skip to content

Commit 9bd823d

Browse files
committed
ports/stm32: Use static heap for Zephyr threading to avoid overlap.
When MICROPY_ZEPHYR_THREADING is enabled, thread stacks are allocated in .noinit section via K_THREAD_STACK_ARRAY_DEFINE. The linker places .noinit immediately after .bss, at the same address as the dynamic heap start (_heap_start = _ebss), causing catastrophic memory corruption. Use a static heap array in .bss section instead, ensuring clear separation between heap and thread stack memory regions. Heap size is set to 40KB for boards with limited RAM (NUCLEO_F429ZI with 192KB) to accommodate 50KB of thread stacks plus other data. Signed-off-by: Andrew Leech <[email protected]> Signed-off-by: Andrew Leech <[email protected]>
1 parent 30d2f1c commit 9bd823d

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

ports/stm32/main.c

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,13 @@ static bool init_sdcard_fs(void) {
310310
#endif
311311

312312
#if MICROPY_ZEPHYR_THREADING
313+
// Static heap for Zephyr threading builds to avoid overlap with thread stacks
314+
// Thread stacks go into .noinit section after .bss, so we use a static array in .bss
315+
// This ensures clear separation between heap and thread stack memory regions
316+
// Reduced to 40KB to fit in NUCLEO_F429ZI RAM (192KB total) with thread stacks (50KB)
317+
#define MICROPY_HEAP_SIZE (40 * 1024)
318+
static char heap[MICROPY_HEAP_SIZE];
319+
313320
// Zephyr threading entry point - called by Zephyr kernel after z_cstart()
314321
// This function runs in z_main_thread context after kernel initialization
315322
void micropython_main_thread_entry(void *p1, void *p2, void *p3) {
@@ -351,8 +358,8 @@ void micropython_main_thread_entry(void *p1, void *p2, void *p3) {
351358
// Stack limit init (symbols declared in gccollect.h)
352359
mp_cstack_init_with_top(&_estack, (char *)&_estack - (char *)&_sstack);
353360

354-
// GC init
355-
gc_init(MICROPY_HEAP_START, MICROPY_HEAP_END);
361+
// GC init with static heap (avoids overlap with thread stacks in .noinit section)
362+
gc_init(heap, heap + sizeof(heap));
356363

357364
#if MICROPY_ENABLE_PYSTACK
358365
static mp_obj_t pystack[384];

0 commit comments

Comments
 (0)