[PATCH v3 01/16] common: introduce HAS_ARCH_SJLJ

Ahmad Fatoum a.fatoum at pengutronix.de
Wed Mar 10 08:47:45 GMT 2021


From: Ahmad Fatoum <ahmad at a3f.at>

setjmp stores the registers comprising the execution context into a
jmp_buf and longjmp switches to that context and continues execution just
after the setjmp that allocated that jmp_buf.

setjmp/longjmp can have multiple uses:

  - Handle return from firmware that clobbers registers. This is why we
    already have a setjmp/longjmp ARM

  - Do exception handling[1]

  - Port over scripting language VMs that use sjlj for context switching

  - Implement stackless coroutines in C.

These coroutines would be stackless, because jumping to a setjmp down the
call stack means that the code there will clobber the stack below it.
On resuming the coroutine, it will run with a stack changed in the
interim leading to undefined behavior.

There are ways around that without resorting to custom Assembly:

  - Allocate a buffer on the scheduler's stack, so coroutine can
    grow into them
     -> Problem: exploits Undefined behavior

  - Yield first time on scheduler stack, then patch jmp_buf to point at
    another stack
     -> Problem: Code switching stacks should not itself use the stack

  - Construct a new jmp_buf with user-supplied return address and stack top:
    int initjmp(jmp_buf jmp, void __noreturn (*func)(void), void *stack_top);

The latter could also be reused as a portable way of setting up a stack
in early init code.

We are going to implement green threads in later commits, so add a
symbol that can be selected to indicate architecture support for setjmp,
longjmp and the new initjmp.

[1]: https://www.spinics.net/lists/u-boot-v2/msg41322.html

Signed-off-by: Ahmad Fatoum <ahmad at a3f.at>
---
 common/Kconfig | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/common/Kconfig b/common/Kconfig
index edadcc9f4979..c0ff57bcdba4 100644
--- a/common/Kconfig
+++ b/common/Kconfig
@@ -28,6 +28,11 @@ config HAS_DMA
 	  Drivers that depend on a DMA implementation can depend on this
 	  config, so that you don't get a compilation error.
 
+config HAS_ARCH_SJLJ
+	bool
+	help
+	  Architecture has support implemented for setjmp()/longjmp()/initjmp()
+
 config GENERIC_GPIO
 	bool
 
-- 
2.29.2




More information about the barebox mailing list