Skip to content

Commit 3a83b80

Browse files
committed
nlr: Add implementation using setjmp/longjmp.
Having an optimized asm implementation is good, but if we want portability, that's it.
1 parent a1c6720 commit 3a83b80

3 files changed

Lines changed: 36 additions & 1 deletion

File tree

py/nlr.h

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,14 @@
22
// exception handling, basically a stack of setjmp/longjmp buffers
33

44
#include <limits.h>
5+
#include <setjmp.h>
56

67
typedef struct _nlr_buf_t nlr_buf_t;
78
struct _nlr_buf_t {
89
// the entries here must all be machine word size
910
nlr_buf_t *prev;
1011
void *ret_val;
12+
#if !MICROPY_NLR_SETJMP
1113
#if defined(__i386__)
1214
void *regs[6];
1315
#elif defined(__x86_64__)
@@ -19,13 +21,29 @@ struct _nlr_buf_t {
1921
#elif defined(__thumb2__)
2022
void *regs[10];
2123
#else
22-
#error Unknown arch in nlr.h
24+
#define MICROPY_NLR_SETJMP (1)
25+
#warning "No native NLR support for this arch, using setjmp implementation"
26+
#endif
27+
#endif
28+
29+
#if MICROPY_NLR_SETJMP
30+
jmp_buf jmpbuf;
2331
#endif
2432
};
2533

34+
#if MICROPY_NLR_SETJMP
35+
extern nlr_buf_t *nlr_setjmp_top;
36+
void nlr_setjmp_jump(void *val) __attribute__((noreturn));
37+
// nlr_push() must be defined as a macro, because "The stack context will be
38+
// invalidated if the function which called setjmp() returns."
39+
#define nlr_push(buf) ((buf)->prev = nlr_setjmp_top, nlr_setjmp_top = (buf), setjmp((buf)->jmpbuf))
40+
#define nlr_pop() { nlr_setjmp_top = nlr_setjmp_top->prev; }
41+
#define nlr_jump(val) nlr_setjmp_jump(val)
42+
#else
2643
unsigned int nlr_push(nlr_buf_t *);
2744
void nlr_pop(void);
2845
void nlr_jump(void *val) __attribute__((noreturn));
46+
#endif
2947

3048
// This must be implemented by a port. It's called by nlr_jump
3149
// if no nlr buf has been pushed. It must not return, but rather

py/nlrsetjmp.c

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
#include <setjmp.h>
2+
#include <stdio.h>
3+
#include "nlr.h"
4+
5+
#if MICROPY_NLR_SETJMP
6+
7+
nlr_buf_t *nlr_setjmp_top;
8+
9+
void nlr_setjmp_jump(void *val) {
10+
nlr_buf_t *buf = nlr_setjmp_top;
11+
nlr_setjmp_top = buf->prev;
12+
buf->ret_val = val;
13+
longjmp(buf->jmpbuf, 1);
14+
}
15+
16+
#endif

py/py.mk

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ PY_O_BASENAME = \
1010
nlrx86.o \
1111
nlrx64.o \
1212
nlrthumb.o \
13+
nlrsetjmp.o \
1314
malloc.o \
1415
gc.o \
1516
qstr.o \

0 commit comments

Comments
 (0)