Skip to content

Commit 762d575

Browse files
committed
unix: Do a proper clean-up on sys.exit/SystemExit.
Addresses issue adafruit#859.
1 parent d368611 commit 762d575

1 file changed

Lines changed: 20 additions & 6 deletions

File tree

unix/main.c

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,10 @@ void microsocket_init();
6868
void time_init();
6969
void ffi_init();
7070

71+
#define FORCED_EXIT (0x100)
7172
// returns standard error codes: 0 for success, 1 for all other errors
73+
// if FORCED_EXIT bit is set then script raised SystemExit and the
74+
// value of the exit is in the lower 8 bits of the return value
7275
STATIC int execute_from_lexer(mp_lexer_t *lex, mp_parse_input_kind_t input_kind, bool is_repl) {
7376
if (lex == NULL) {
7477
return 1;
@@ -136,7 +139,7 @@ STATIC int execute_from_lexer(mp_lexer_t *lex, mp_parse_input_kind_t input_kind,
136139
if (exit_val != mp_const_none && !mp_obj_get_int_maybe(exit_val, &val)) {
137140
val = 1;
138141
}
139-
exit(val);
142+
return FORCED_EXIT | (val & 255);
140143
}
141144
mp_obj_print_exception((mp_obj_t)nlr.ret_val);
142145
return 1;
@@ -157,14 +160,14 @@ STATIC char *strjoin(const char *s1, int sep_char, const char *s2) {
157160
return s;
158161
}
159162

160-
STATIC void do_repl(void) {
163+
STATIC int do_repl(void) {
161164
printf("Micro Python " MICROPY_GIT_TAG " on " MICROPY_BUILD_DATE "; " MICROPY_PY_SYS_PLATFORM " version\n");
162165

163166
for (;;) {
164167
char *line = prompt(">>> ");
165168
if (line == NULL) {
166169
// EOF
167-
return;
170+
return 0;
168171
}
169172
while (mp_repl_continue_with_input(line)) {
170173
char *line2 = prompt("... ");
@@ -178,7 +181,10 @@ STATIC void do_repl(void) {
178181
}
179182

180183
mp_lexer_t *lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, line, strlen(line), false);
181-
execute_from_lexer(lex, MP_PARSE_SINGLE_INPUT, true);
184+
int ret = execute_from_lexer(lex, MP_PARSE_SINGLE_INPUT, true);
185+
if (ret & FORCED_EXIT) {
186+
return ret;
187+
}
182188
free(line);
183189
}
184190
}
@@ -361,6 +367,9 @@ int main(int argc, char **argv) {
361367
return usage(argv);
362368
}
363369
ret = do_str(argv[a + 1]);
370+
if (ret & FORCED_EXIT) {
371+
break;
372+
}
364373
a += 1;
365374
} else if (strcmp(argv[a], "-X") == 0) {
366375
a += 1;
@@ -401,12 +410,17 @@ int main(int argc, char **argv) {
401410
}
402411

403412
if (ret == NOTHING_EXECUTED) {
404-
do_repl();
405-
ret = 0;
413+
ret = do_repl();
406414
}
407415

408416
mp_deinit();
409417

418+
#if MICROPY_ENABLE_GC && !defined(NDEBUG)
419+
// We don't really need to free memory since we are about to exit the
420+
// process, but doing so helps to find memory leaks.
421+
free(heap);
422+
#endif
423+
410424
//printf("total bytes = %d\n", m_get_total_bytes_allocated());
411425
return ret;
412426
}

0 commit comments

Comments
 (0)