From 0ecb6f06fb317e0695e602f209a820899a8c1186 Mon Sep 17 00:00:00 2001 From: Max Prokhorov Date: Thu, 29 May 2025 04:00:31 +0300 Subject: [PATCH] Stack Thunk - check saved a1 before using and zero after using (#9252) post #9224, allow to call 'stack_thunk_yield()' outside of bssl context Reset 'stack_thunk_save' before returning from 'thunk_...'ed function Skip invalid a1 load and yield with the current value --- cores/esp8266/StackThunk.cpp | 7 ++++++- cores/esp8266/StackThunk.h | 10 +++++++--- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/cores/esp8266/StackThunk.cpp b/cores/esp8266/StackThunk.cpp index baa793bdc..a0be352c7 100644 --- a/cores/esp8266/StackThunk.cpp +++ b/cores/esp8266/StackThunk.cpp @@ -73,6 +73,7 @@ void stack_thunk_add_ref() } stack_thunk_top = stack_thunk_ptr + _stackSize - 1; stack_thunk_save = NULL; + stack_thunk_yield_save = NULL; stack_thunk_repaint(); } } @@ -90,6 +91,7 @@ void stack_thunk_del_ref() stack_thunk_ptr = NULL; stack_thunk_top = NULL; stack_thunk_save = NULL; + stack_thunk_yield_save = NULL; } } @@ -175,15 +177,18 @@ asm( "movi a2, stack_thunk_yield_save\n\t" "s32i.n a1, a2, 0\n\t" "movi a2, stack_thunk_save\n\t" +/* But, only when inside of bssl stack (saved a1 != 0) */ + "l32i.n a3, a2, 0\n\t" + "beqz a3, stack_thunk_yield_do_yield\n\t" "l32i.n a1, a2, 0\n\t" /* optimistic_yield(10000) without extra l32r */ +"stack_thunk_yield_do_yield:\n\t" "movi a2, 0x10\n\t" "addmi a2, a2, 0x2700\n\t" "call0 optimistic_yield\n\t" /* Swap bearssl <-> cont stacks, again */ "movi a2, stack_thunk_yield_save\n\t" "l32i.n a1, a2, 0\n\t" - "\n" /* Restore caller */ "l32i.n a0, a1, 12\n\t" "addi a1, a1, 16\n\t" diff --git a/cores/esp8266/StackThunk.h b/cores/esp8266/StackThunk.h index 350775ec2..b7dd521e9 100644 --- a/cores/esp8266/StackThunk.h +++ b/cores/esp8266/StackThunk.h @@ -27,6 +27,8 @@ #ifndef _STACKTHUNK_H #define _STACKTHUNK_H +#include + #ifdef __cplusplus extern "C" { #endif @@ -80,9 +82,11 @@ thunk_"#fcnToThunk":\n\ call0 stack_thunk_fatal_smashing\n\ .L1"#fcnToThunk":\n\ movi a15, stack_thunk_save /* Restore A1(SP) */\n\ - l32i.n a1, a15, 0\n\ - l32i.n a15, a1, 8 /* Restore the saved registers */\n\ - l32i.n a0, a1, 12\n\ + l32i.n a1, a15, 0/* Restore A1(SP) */\n\ + movi a0, 0 /* Purge temporary storage */\n\ + s32i.n a0, a15, 0\n\ + l32i.n a15, a1, 8/* Restore A15 */\n\ + l32i.n a0, a1, 12/* Restore A0 */\n\ addi a1, a1, 16 /* Free up stack and return to caller */\n\ ret\n\ .size thunk_"#fcnToThunk", . - thunk_"#fcnToThunk"\n");