From d2a3cd7ac4283045b3692ae8d83afe833fbe65e6 Mon Sep 17 00:00:00 2001 From: YAMAMOTO Takashi Date: Fri, 9 Feb 2024 14:03:00 +0900 Subject: [PATCH] embed: Improve stack top estimation. Obtaining the stack-top via a few function calls may yield a pointer which is too deep within the stack. So require the user to obtain it from a higher level (or via some other means). Fixes issue #11781. Signed-off-by: YAMAMOTO Takashi --- examples/embedding/main.c | 9 ++++++++- ports/embed/port/embed_util.c | 4 ++-- ports/embed/port/micropython_embed.h | 2 +- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/examples/embedding/main.c b/examples/embedding/main.c index ee673fc93a..7530580369 100644 --- a/examples/embedding/main.c +++ b/examples/embedding/main.c @@ -31,7 +31,14 @@ static char heap[8 * 1024]; int main() { // Initialise MicroPython. - mp_embed_init(&heap[0], sizeof(heap)); + // + // Note: &stack_top below should be good enough for many cases. + // However, depending on environment, there might be more appropriate + // ways to get the stack top value. + // eg. pthread_get_stackaddr_np, pthread_getattr_np, + // __builtin_frame_address/__builtin_stack_address, etc. + int stack_top; + mp_embed_init(&heap[0], sizeof(heap), &stack_top); // Run the example scripts (they will be compiled first). mp_embed_exec_str(example_1); diff --git a/ports/embed/port/embed_util.c b/ports/embed/port/embed_util.c index 14f5089770..c5bc8c973b 100644 --- a/ports/embed/port/embed_util.c +++ b/ports/embed/port/embed_util.c @@ -34,8 +34,8 @@ #include "port/micropython_embed.h" // Initialise the runtime. -void mp_embed_init(void *gc_heap, size_t gc_heap_size) { - mp_stack_ctrl_init(); +void mp_embed_init(void *gc_heap, size_t gc_heap_size, void *stack_top) { + mp_stack_set_top(stack_top); gc_init(gc_heap, (uint8_t *)gc_heap + gc_heap_size); mp_init(); } diff --git a/ports/embed/port/micropython_embed.h b/ports/embed/port/micropython_embed.h index bf55d9b2b4..09341c93e4 100644 --- a/ports/embed/port/micropython_embed.h +++ b/ports/embed/port/micropython_embed.h @@ -29,7 +29,7 @@ #include #include -void mp_embed_init(void *gc_heap, size_t gc_heap_size); +void mp_embed_init(void *gc_heap, size_t gc_heap_size, void *stack_top); void mp_embed_deinit(void); // Only available if MICROPY_ENABLE_COMPILER is enabled.