py/scheduler: Implement VM abort flag and mp_sched_vm_abort().

This is intended to be used by the very outer caller of the VM/runtime.  It
allows setting a top-level NLR handler that can be jumped to directly, in
order to forcefully abort the VM/runtime.

Enable using:

    #define MICROPY_ENABLE_VM_ABORT (1)

Set up the handler at the top level using:

    nlr_buf_t nlr;
    nlr.ret_val = NULL;
    if (nlr_push(&nlr) == 0) {
        nlr_set_abort(&nlr);
        // call into the VM/runtime
        ...
        nlr_pop();
    } else {
        if (nlr.ret_val == NULL) {
            // handle abort
            ...
        } else {
            // handle other exception that propagated to the top level
            ...
        }
    }
    nlr_set_abort(NULL);

Schedule an abort, eg from an interrupt handler, using:

    mp_sched_vm_abort();

Signed-off-by: Damien George <damien@micropython.org>
This commit is contained in:
Damien George
2022-12-16 17:31:21 +11:00
parent 5d4bfce034
commit d54208a2ff
7 changed files with 62 additions and 2 deletions

View File

@@ -101,9 +101,16 @@
typedef struct _nlr_buf_t nlr_buf_t;
struct _nlr_buf_t {
// the entries here must all be machine word size
// The entries in this struct must all be machine word size.
// Pointer to the previous nlr_buf_t in the chain.
// Or NULL if it's the top-level one.
nlr_buf_t *prev;
void *ret_val; // always a concrete object (an exception instance)
// The exception that is being raised:
// - NULL means the jump is because of a VM abort (only if MICROPY_ENABLE_VM_ABORT enabled)
// - otherwise it's always a concrete object (an exception instance)
void *ret_val;
#if MICROPY_NLR_SETJMP
jmp_buf jmpbuf;
@@ -149,6 +156,12 @@ unsigned int nlr_push_tail(nlr_buf_t *top);
void nlr_pop(void);
NORETURN void nlr_jump(void *val);
#if MICROPY_ENABLE_VM_ABORT
#define nlr_set_abort(buf) MP_STATE_VM(nlr_abort) = buf
#define nlr_get_abort() MP_STATE_VM(nlr_abort)
NORETURN void nlr_jump_abort(void);
#endif
// This must be implemented by a port. It's called by nlr_jump
// if no nlr buf has been pushed. It must not return, but rather
// should bail out with a fatal error.