Skip to content

Commit

Permalink
py/persistentcode: Always close reader even if an exception is raised.
Browse files Browse the repository at this point in the history
Fixes issue adafruit#3874.

Signed-off-by: Damien George <damien@micropython.org>
  • Loading branch information
dpgeorge committed Sep 14, 2023
1 parent 5e122b1 commit 397697a
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
7 changes: 6 additions & 1 deletion py/persistentcode.c
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,10 @@ STATIC mp_raw_code_t *load_raw_code(mp_reader_t *reader, mp_module_context_t *co
}

void mp_raw_code_load(mp_reader_t *reader, mp_compiled_module_t *cm) {
// Set exception handler to close the reader if an exception is raised.
MP_DEFINE_NLR_JUMP_CALLBACK_FUNCTION_1(ctx, reader->close, reader->data);
nlr_push_jump_callback(&ctx.callback, mp_call_function_1_from_nlr_jump_callback);

byte header[4];
read_bytes(reader, header, sizeof(header));
byte arch = MPY_FEATURE_DECODE_ARCH(header[2]);
Expand Down Expand Up @@ -435,7 +439,8 @@ void mp_raw_code_load(mp_reader_t *reader, mp_compiled_module_t *cm) {
cm->n_obj = n_obj;
#endif

reader->close(reader->data);
// Deregister exception handler and close the reader.
nlr_pop_jump_callback(true);
}

void mp_raw_code_load_mem(const byte *buf, size_t len, mp_compiled_module_t *context) {
Expand Down
7 changes: 7 additions & 0 deletions tests/extmod/vfs_userfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ def open(self, path, mode):
"/usermod1.py": b"print('in usermod1')\nimport usermod2",
"/usermod2.py": b"print('in usermod2')",
"/usermod3.py": b"syntax error",
"/usermod4.mpy": b"syntax error",
}
os.mount(UserFS(user_files), "/userfs")

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

# import a .mpy file with a syntax error (file should be closed on error)
try:
import usermod4
except ValueError:
print("ValueError in usermod4")

# unmount and undo path addition
os.umount("/userfs")
sys.path.pop()
6 changes: 6 additions & 0 deletions tests/extmod/vfs_userfs.py.exp
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,9 @@ stat /usermod3.py
open /usermod3.py rb
ioctl 4 0
SyntaxError in usermod3
stat /usermod4
stat /usermod4.py
stat /usermod4.mpy
open /usermod4.mpy rb
ioctl 4 0
ValueError in usermod4

0 comments on commit 397697a

Please sign in to comment.