Skip to content

Commit 8fa9264

Browse files
committed
unix/unix_mphal: Handle exceptions in call to dupterm's .read().
1 parent 467504d commit 8fa9264

1 file changed

Lines changed: 28 additions & 6 deletions

File tree

unix/unix_mphal.c

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -108,23 +108,45 @@ void mp_hal_stdio_mode_orig(void) {
108108

109109
#endif
110110

111-
int mp_hal_stdin_rx_chr(void) {
112-
unsigned char c;
113-
#if MICROPY_PY_OS_DUPTERM
114-
while (MP_STATE_PORT(term_obj) != MP_OBJ_NULL) {
111+
static int call_dupterm_read(void) {
112+
nlr_buf_t nlr;
113+
if (nlr_push(&nlr) == 0) {
115114
mp_obj_t read_m[3];
116115
mp_load_method(MP_STATE_PORT(term_obj), MP_QSTR_read, read_m);
117116
read_m[2] = MP_OBJ_NEW_SMALL_INT(1);
118117
mp_obj_t res = mp_call_method_n_kw(1, 0, read_m);
119118
if (res == mp_const_none) {
120-
break;
119+
return -1;
121120
}
122121
mp_buffer_info_t bufinfo;
123122
mp_get_buffer_raise(res, &bufinfo, MP_BUFFER_READ);
124123
if (bufinfo.len == 0) {
124+
mp_printf(&mp_plat_print, "dupterm: EOF received, deactivating\n");
125+
MP_STATE_PORT(term_obj) = NULL;
126+
return -1;
127+
}
128+
nlr_pop();
129+
return *(byte*)bufinfo.buf;
130+
} else {
131+
// Temporarily disable dupterm to avoid infinite recursion
132+
mp_obj_t save_term = MP_STATE_PORT(term_obj);
133+
MP_STATE_PORT(term_obj) = NULL;
134+
mp_printf(&mp_plat_print, "dupterm: ");
135+
mp_obj_print_exception(&mp_plat_print, nlr.ret_val);
136+
MP_STATE_PORT(term_obj) = save_term;
137+
}
138+
139+
return -1;
140+
}
141+
142+
int mp_hal_stdin_rx_chr(void) {
143+
unsigned char c;
144+
#if MICROPY_PY_OS_DUPTERM
145+
while (MP_STATE_PORT(term_obj) != MP_OBJ_NULL) {
146+
int c = call_dupterm_read();
147+
if (c == -1) {
125148
break;
126149
}
127-
c = *(byte*)bufinfo.buf;
128150
if (c == '\n') {
129151
c = '\r';
130152
}

0 commit comments

Comments
 (0)