Skip to content

Commit 6a13bdb

Browse files
committed
bricks/common: catch error raised when printing final exception
It is possible for print functions to raise an exception, so we need to catch this when printing a final exception since the nlr stack is empty at that point and would otherwise cause a crash.
1 parent bf9870f commit 6a13bdb

1 file changed

Lines changed: 23 additions & 9 deletions

File tree

bricks/_common/micropython.c

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -105,16 +105,30 @@ static void mp_vfs_map_minimal_new_reader(mp_reader_t *reader, mp_vfs_map_minima
105105

106106
// Prints the exception that ended the program.
107107
static void print_final_exception(mp_obj_t exc, int ret) {
108-
// Handle graceful stop with button.
109-
if ((ret & PYEXEC_FORCED_EXIT) &&
110-
mp_obj_exception_match(exc, MP_OBJ_FROM_PTR(&mp_type_SystemExit))) {
111-
mp_printf(&mp_plat_print, "The program was stopped (%q).\n",
112-
((mp_obj_exception_t *)MP_OBJ_TO_PTR(exc))->base.type->name);
113-
return;
114-
}
108+
nlr_buf_t nlr;
109+
nlr.ret_val = NULL;
110+
111+
if (nlr_push(&nlr) == 0) {
112+
// Handle graceful stop with button.
113+
if ((ret & PYEXEC_FORCED_EXIT) &&
114+
mp_obj_exception_match(exc, MP_OBJ_FROM_PTR(&mp_type_SystemExit))) {
115+
mp_printf(&mp_plat_print, "The program was stopped (%q).\n",
116+
((mp_obj_exception_t *)MP_OBJ_TO_PTR(exc))->base.type->name);
117+
return;
118+
}
115119

116-
// Print unhandled exception with traceback.
117-
mp_obj_print_exception(&mp_plat_print, exc);
120+
// REVISIT: flash the light red a few times to indicate an unhandled exception?
121+
122+
// Print unhandled exception with traceback.
123+
mp_obj_print_exception(&mp_plat_print, exc);
124+
125+
nlr_pop();
126+
} else {
127+
// If we couldn't print the exception, just return. There is nothing
128+
// else we can do.
129+
130+
// REVISIT: flash the light with a different pattern here?
131+
}
118132
}
119133

120134
#if PBSYS_CONFIG_FEATURE_BUILTIN_USER_PROGRAM_REPL

0 commit comments

Comments
 (0)