Skip to content

Commit 5e122b1

Browse files
committed
py/parse: Always free lexer even if an exception is raised.
Fixes issue adafruit#3843. Signed-off-by: Damien George <[email protected]>
1 parent c9089e7 commit 5e122b1

File tree

3 files changed

+17
-2
lines changed

3 files changed

+17
-2
lines changed

py/parse.c

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1023,6 +1023,9 @@ STATIC void push_result_rule(parser_t *parser, size_t src_line, uint8_t rule_id,
10231023
}
10241024

10251025
mp_parse_tree_t mp_parse(mp_lexer_t *lex, mp_parse_input_kind_t input_kind) {
1026+
// Set exception handler to free the lexer if an exception is raised.
1027+
MP_DEFINE_NLR_JUMP_CALLBACK_FUNCTION_1(ctx, mp_lexer_free, lex);
1028+
nlr_push_jump_callback(&ctx.callback, mp_call_function_1_from_nlr_jump_callback);
10261029

10271030
// initialise parser and allocate memory for its stacks
10281031

@@ -1370,8 +1373,8 @@ mp_parse_tree_t mp_parse(mp_lexer_t *lex, mp_parse_input_kind_t input_kind) {
13701373
m_del(rule_stack_t, parser.rule_stack, parser.rule_stack_alloc);
13711374
m_del(mp_parse_node_t, parser.result_stack, parser.result_stack_alloc);
13721375

1373-
// we also free the lexer on behalf of the caller
1374-
mp_lexer_free(lex);
1376+
// Deregister exception handler and free the lexer.
1377+
nlr_pop_jump_callback(true);
13751378

13761379
return parser.tree;
13771380
}

tests/extmod/vfs_userfs.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ def open(self, path, mode):
6868
"/data.txt": b"some data in a text file",
6969
"/usermod1.py": b"print('in usermod1')\nimport usermod2",
7070
"/usermod2.py": b"print('in usermod2')",
71+
"/usermod3.py": b"syntax error",
7172
}
7273
os.mount(UserFS(user_files), "/userfs")
7374

@@ -79,6 +80,12 @@ def open(self, path, mode):
7980
sys.path.append("/userfs")
8081
import usermod1
8182

83+
# import a .py file with a syntax error (file should be closed on error)
84+
try:
85+
import usermod3
86+
except SyntaxError:
87+
print("SyntaxError in usermod3")
88+
8289
# unmount and undo path addition
8390
os.umount("/userfs")
8491
sys.path.pop()

tests/extmod/vfs_userfs.py.exp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,8 @@ stat /usermod2.py
1010
open /usermod2.py rb
1111
ioctl 4 0
1212
in usermod2
13+
stat /usermod3
14+
stat /usermod3.py
15+
open /usermod3.py rb
16+
ioctl 4 0
17+
SyntaxError in usermod3

0 commit comments

Comments
 (0)