Skip to content

Commit 397697a

Browse files
committed
py/persistentcode: Always close reader even if an exception is raised.
Fixes issue adafruit#3874. Signed-off-by: Damien George <[email protected]>
1 parent 5e122b1 commit 397697a

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

py/persistentcode.c

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -391,6 +391,10 @@ STATIC mp_raw_code_t *load_raw_code(mp_reader_t *reader, mp_module_context_t *co
391391
}
392392

393393
void mp_raw_code_load(mp_reader_t *reader, mp_compiled_module_t *cm) {
394+
// Set exception handler to close the reader if an exception is raised.
395+
MP_DEFINE_NLR_JUMP_CALLBACK_FUNCTION_1(ctx, reader->close, reader->data);
396+
nlr_push_jump_callback(&ctx.callback, mp_call_function_1_from_nlr_jump_callback);
397+
394398
byte header[4];
395399
read_bytes(reader, header, sizeof(header));
396400
byte arch = MPY_FEATURE_DECODE_ARCH(header[2]);
@@ -435,7 +439,8 @@ void mp_raw_code_load(mp_reader_t *reader, mp_compiled_module_t *cm) {
435439
cm->n_obj = n_obj;
436440
#endif
437441

438-
reader->close(reader->data);
442+
// Deregister exception handler and close the reader.
443+
nlr_pop_jump_callback(true);
439444
}
440445

441446
void mp_raw_code_load_mem(const byte *buf, size_t len, mp_compiled_module_t *context) {

tests/extmod/vfs_userfs.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ def open(self, path, mode):
6969
"/usermod1.py": b"print('in usermod1')\nimport usermod2",
7070
"/usermod2.py": b"print('in usermod2')",
7171
"/usermod3.py": b"syntax error",
72+
"/usermod4.mpy": b"syntax error",
7273
}
7374
os.mount(UserFS(user_files), "/userfs")
7475

@@ -86,6 +87,12 @@ def open(self, path, mode):
8687
except SyntaxError:
8788
print("SyntaxError in usermod3")
8889

90+
# import a .mpy file with a syntax error (file should be closed on error)
91+
try:
92+
import usermod4
93+
except ValueError:
94+
print("ValueError in usermod4")
95+
8996
# unmount and undo path addition
9097
os.umount("/userfs")
9198
sys.path.pop()

tests/extmod/vfs_userfs.py.exp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,9 @@ stat /usermod3.py
1515
open /usermod3.py rb
1616
ioctl 4 0
1717
SyntaxError in usermod3
18+
stat /usermod4
19+
stat /usermod4.py
20+
stat /usermod4.mpy
21+
open /usermod4.mpy rb
22+
ioctl 4 0
23+
ValueError in usermod4

0 commit comments

Comments
 (0)