From a3998d0626d90bb5d84e61eefd4b3be2b15a6739 Mon Sep 17 00:00:00 2001 From: microDev <70126934+microDev1@users.noreply.github.com> Date: Fri, 30 Jul 2021 08:36:24 +0530 Subject: [PATCH 1/5] add atexit module --- lib/utils/pyexec.c | 8 ++ locale/circuitpython.pot | 18 ++-- main.c | 9 ++ .../mpconfigboard.mk | 1 + py/circuitpy_defns.mk | 4 + py/circuitpy_mpconfig.h | 8 ++ py/circuitpy_mpconfig.mk | 3 + shared-bindings/atexit/__init__.c | 89 +++++++++++++++++++ shared-module/atexit/__init__.c | 87 ++++++++++++++++++ shared-module/atexit/__init__.h | 39 ++++++++ 10 files changed, 255 insertions(+), 11 deletions(-) create mode 100644 shared-bindings/atexit/__init__.c create mode 100644 shared-module/atexit/__init__.c create mode 100644 shared-module/atexit/__init__.h diff --git a/lib/utils/pyexec.c b/lib/utils/pyexec.c index 2651189915..0362729b09 100644 --- a/lib/utils/pyexec.c +++ b/lib/utils/pyexec.c @@ -44,6 +44,10 @@ #include "lib/utils/pyexec.h" #include "genhdr/mpversion.h" +#if CIRCUITPY_ATEXIT +#include "shared-module/atexit/__init__.h" +#endif + pyexec_mode_kind_t pyexec_mode_kind = PYEXEC_MODE_FRIENDLY_REPL; int pyexec_system_exit = 0; @@ -127,6 +131,10 @@ STATIC int parse_compile_execute(const void *source, mp_parse_input_kind_t input start = mp_hal_ticks_ms(); #endif mp_call_function_0(module_fun); + // execute exit handlers (if any). + #if CIRCUITPY_ATEXIT + shared_module_atexit_execute(); + #endif mp_hal_set_interrupt_char(-1); // disable interrupt mp_handle_pending(true); // handle any pending exceptions (and any callbacks) nlr_pop(); diff --git a/locale/circuitpython.pot b/locale/circuitpython.pot index 81531c0cbd..e29bfd1ae6 100644 --- a/locale/circuitpython.pot +++ b/locale/circuitpython.pot @@ -185,7 +185,7 @@ msgstr "" msgid "'%q' object is not an iterator" msgstr "" -#: py/objtype.c py/runtime.c +#: py/objtype.c py/runtime.c shared-module/atexit/__init__.c msgid "'%q' object is not callable" msgstr "" @@ -1185,11 +1185,6 @@ msgstr "" msgid "Input/output error" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#, c-format -msgid "Missing jmp_pin. Instruction %d jumps on pin" -msgstr "" - #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c #, c-format msgid "Instruction %d shifts in more bits than pin count" @@ -1506,6 +1501,11 @@ msgstr "" msgid "Missing first_set_pin. Instruction %d sets pin(s)" msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#, c-format +msgid "Missing jmp_pin. Instruction %d jumps on pin" +msgstr "" + #: shared-bindings/busio/UART.c shared-bindings/displayio/Group.c msgid "Must be a %q subclass." msgstr "" @@ -2510,7 +2510,7 @@ msgid "argument name reused" msgstr "" #: py/argcheck.c shared-bindings/_stage/__init__.c -#: shared-bindings/digitalio/DigitalInOut.c shared-bindings/gamepad/GamePad.c +#: shared-bindings/digitalio/DigitalInOut.c msgid "argument num/types mismatch" msgstr "" @@ -3594,10 +3594,6 @@ msgstr "" msgid "no active exception to reraise" msgstr "" -#: shared-bindings/socket/__init__.c shared-module/network/__init__.c -msgid "no available NIC" -msgstr "" - #: py/compile.c msgid "no binding for nonlocal found" msgstr "" diff --git a/main.c b/main.c index 13caf4beb7..887b1c1d16 100755 --- a/main.c +++ b/main.c @@ -70,6 +70,10 @@ #include "shared-bindings/alarm/__init__.h" #endif +#if CIRCUITPY_ATEXIT +#include "shared-module/atexit/__init__.h" +#endif + #if CIRCUITPY_BLEIO #include "shared-bindings/_bleio/__init__.h" #include "supervisor/shared/bluetooth/bluetooth.h" @@ -253,6 +257,11 @@ STATIC void cleanup_after_vm(supervisor_allocation* heap, mp_obj_t exception) { // Reset port-independent devices, like CIRCUITPY_BLEIO_HCI. reset_devices(); + + #if CIRCUITPY_ATEXIT + atexit_reset(); + #endif + // Turn off the display and flush the filesystem before the heap disappears. #if CIRCUITPY_DISPLAYIO reset_displays(); diff --git a/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/mpconfigboard.mk b/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/mpconfigboard.mk index a617947f9c..a0bef7ada0 100644 --- a/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/mpconfigboard.mk +++ b/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/mpconfigboard.mk @@ -20,6 +20,7 @@ CIRCUITPY_ROTARYIO = 0 CIRCUITPY_RTC = 0 CIRCUITPY_USB_MIDI = 0 +CIRCUITPY_ATEXIT = 0 CIRCUITPY_PIXELBUF = 1 CIRCUITPY_BUSDEVICE = 1 diff --git a/py/circuitpy_defns.mk b/py/circuitpy_defns.mk index 5bf46039a7..938dcbd8b4 100644 --- a/py/circuitpy_defns.mk +++ b/py/circuitpy_defns.mk @@ -114,6 +114,9 @@ endif ifeq ($(CIRCUITPY_ANALOGIO),1) SRC_PATTERNS += analogio/% endif +ifeq ($(CIRCUITPY_ATEXIT),1) +SRC_PATTERNS += atexit/% +endif ifeq ($(CIRCUITPY_AUDIOBUSIO),1) SRC_PATTERNS += audiobusio/% endif @@ -471,6 +474,7 @@ SRC_SHARED_MODULE_ALL = \ _stage/__init__.c \ aesio/__init__.c \ aesio/aes.c \ + atexit/__init__.c \ audiocore/RawSample.c \ audiocore/WaveFile.c \ audiocore/__init__.c \ diff --git a/py/circuitpy_mpconfig.h b/py/circuitpy_mpconfig.h index 8e31f0411b..7dfdf7f311 100644 --- a/py/circuitpy_mpconfig.h +++ b/py/circuitpy_mpconfig.h @@ -255,6 +255,13 @@ extern const struct _mp_obj_module_t analogio_module; #define ANALOGIO_MODULE #endif +#if CIRCUITPY_ATEXIT +extern const struct _mp_obj_module_t atexit_module; +#define ATEXIT_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR_atexit), (mp_obj_t)&atexit_module }, +#else +#define ATEXIT_MODULE +#endif + #if CIRCUITPY_AUDIOBUSIO #define AUDIOBUSIO_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR_audiobusio), (mp_obj_t)&audiobusio_module }, extern const struct _mp_obj_module_t audiobusio_module; @@ -853,6 +860,7 @@ extern const struct _mp_obj_module_t msgpack_module; AESIO_MODULE \ ALARM_MODULE \ ANALOGIO_MODULE \ + ATEXIT_MODULE \ AUDIOBUSIO_MODULE \ AUDIOCORE_MODULE \ AUDIOIO_MODULE \ diff --git a/py/circuitpy_mpconfig.mk b/py/circuitpy_mpconfig.mk index 3d72be7491..904ad0ed11 100644 --- a/py/circuitpy_mpconfig.mk +++ b/py/circuitpy_mpconfig.mk @@ -48,6 +48,9 @@ CFLAGS += -DCIRCUITPY_ALARM=$(CIRCUITPY_ALARM) CIRCUITPY_ANALOGIO ?= 1 CFLAGS += -DCIRCUITPY_ANALOGIO=$(CIRCUITPY_ANALOGIO) +CIRCUITPY_ATEXIT ?= 1 +CFLAGS += -DCIRCUITPY_ATEXIT=$(CIRCUITPY_ATEXIT) + CIRCUITPY_AUDIOBUSIO ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_AUDIOBUSIO=$(CIRCUITPY_AUDIOBUSIO) diff --git a/shared-bindings/atexit/__init__.c b/shared-bindings/atexit/__init__.c new file mode 100644 index 0000000000..0f4ea26ee9 --- /dev/null +++ b/shared-bindings/atexit/__init__.c @@ -0,0 +1,89 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 microDev + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "shared-module/atexit/__init__.h" + +//| """Atexit Module +//| +//| This module defines functions to register and unregister cleanup functions. +//| Functions thus registered are automatically executed upon normal vm termination. +//| +//| """ +//| ... +//| + +//| def register(func: Callable[..., Any], *args: Optional[Any], **kwargs: Optional[Any]) -> Callable[..., Any]: +//| +//| """Register func as a function to be executed at termination. +//| +//| Any optional arguments that are to be passed to func must be passed as arguments to register(). +//| It is possible to register the same function and arguments more than once. +//| +//| At normal program termination (for instance, if `sys.exit()` is called or the vm execution completes), +//| all functions registered are called in order of there registration. +//| +//| If an exception is raised during execution of the exit handlers, a traceback is printed and the execution stops. +//| +//| This function returns func, which makes it possible to use it as a decorator. +//| +//| """ +//| ... +//| +STATIC mp_obj_t atexit_register(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + shared_module_atexit_register(pos_args[0], (n_args - 1), ((n_args > 1) ? &pos_args[1] : NULL), kw_args); + return pos_args[0]; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_KW(atexit_register_obj, 1, atexit_register); + +//| def unregister(func: Callable[..., Any]) -> None: +//| +//| """Remove func from the list of functions to be run at termination. +//| +//| `unregister()` silently does nothing if func was not previously registered. If func has been registered more than once, +//| every occurrence of that function in the atexit call stack will be removed. +//| +//| """ +//| ... +//| +STATIC mp_obj_t atexit_unregister(const mp_obj_t self_in) { + shared_module_atexit_unregister(&self_in); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(atexit_unregister_obj, atexit_unregister); + +STATIC const mp_rom_map_elem_t atexit_module_globals_table[] = { + // module name + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_atexit) }, + // module functions + { MP_ROM_QSTR(MP_QSTR_register), MP_ROM_PTR(&atexit_register_obj) }, + { MP_ROM_QSTR(MP_QSTR_unregister), MP_ROM_PTR(&atexit_unregister_obj) }, +}; +STATIC MP_DEFINE_CONST_DICT(atexit_module_globals, atexit_module_globals_table); + +const mp_obj_module_t atexit_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&atexit_module_globals, +}; diff --git a/shared-module/atexit/__init__.c b/shared-module/atexit/__init__.c new file mode 100644 index 0000000000..7c55b13f67 --- /dev/null +++ b/shared-module/atexit/__init__.c @@ -0,0 +1,87 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 microDev + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "py/runtime.h" +#include "shared-module/atexit/__init__.h" + +typedef struct _atexit_callback_t { + size_t n_pos, n_kw; + mp_obj_t func, *args; +} atexit_callback_t; + +size_t callback_len = 0; +atexit_callback_t *callback = NULL; + +void atexit_reset(void) { + callback_len = 0; + m_free(callback); + callback = NULL; +} + +void shared_module_atexit_register(mp_obj_t *func, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + if (!mp_obj_is_callable(func)) { + mp_raise_TypeError_varg(translate("'%q' object is not callable"), mp_obj_get_type_qstr(func)); + } + size_t n_kw_args = (kw_args) ? kw_args->used : 0; + atexit_callback_t cb = { + .n_pos = 0, + .n_kw = 0, + .func = func, + .args = ((n_args + n_kw_args) == 0) ? NULL : m_malloc((n_args + (2 * n_kw_args)) * sizeof(mp_obj_t), false) + }; + for (; cb.n_pos < n_args; cb.n_pos++) { + cb.args[cb.n_pos] = pos_args[cb.n_pos]; + } + for (size_t i = cb.n_pos; cb.n_kw < n_kw_args; i++, cb.n_kw++) { + cb.args[i] = kw_args[cb.n_kw].table->key; + cb.args[i += 1] = kw_args[cb.n_kw].table->value; + } + if (!callback) { + callback = (atexit_callback_t *)m_realloc(callback, sizeof(cb)); + } + callback[callback_len++] = cb; +} + +void shared_module_atexit_unregister(const mp_obj_t *func) { + for (size_t i = 0; i < callback_len; i++) { + if (callback[i].func == func) { + callback[i].n_pos = 0; + callback[i].n_kw = 0; + callback[i].func = mp_const_none; + callback[i].args = NULL; + } + } +} + +void shared_module_atexit_execute(void) { + if (callback) { + for (size_t i = 0; i < callback_len; i++) { + if (callback[i].func != mp_const_none) { + mp_call_function_n_kw(callback[i].func, callback[i].n_pos, callback[i].n_kw, callback[i].args); + } + } + } +} diff --git a/shared-module/atexit/__init__.h b/shared-module/atexit/__init__.h new file mode 100644 index 0000000000..48cf0744db --- /dev/null +++ b/shared-module/atexit/__init__.h @@ -0,0 +1,39 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2021 microDev + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_SHARED_MODULE_ATEXIT___INIT___H +#define MICROPY_INCLUDED_SHARED_MODULE_ATEXIT___INIT___H + +#include "py/obj.h" + +extern void atexit_reset(void); + +extern void shared_module_atexit_register(mp_obj_t *func, + size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args); +extern void shared_module_atexit_unregister(const mp_obj_t *func); +extern void shared_module_atexit_execute(void); + +#endif // MICROPY_INCLUDED_SHARED_MODULE_ATEXIT___INIT___H From 49388511227f006cfa30d921d5e0e095c0141a8a Mon Sep 17 00:00:00 2001 From: microDev <70126934+microDev1@users.noreply.github.com> Date: Fri, 30 Jul 2021 10:00:00 +0530 Subject: [PATCH 2/5] remove legacy sys.atexit() implementation --- ports/unix/main.c | 7 ------- ports/unix/mpconfigport.h | 1 - py/modsys.c | 18 ------------------ py/mpconfig.h | 5 ----- py/mpstate.h | 5 ----- py/runtime.c | 4 ---- tests/misc/sys_atexit.py | 21 --------------------- tests/misc/sys_atexit.py.exp | 2 -- tests/unix/extra_coverage.py.exp | 8 ++++---- 9 files changed, 4 insertions(+), 67 deletions(-) delete mode 100644 tests/misc/sys_atexit.py delete mode 100644 tests/misc/sys_atexit.py.exp diff --git a/ports/unix/main.c b/ports/unix/main.c index 55bdc22082..b69df90354 100644 --- a/ports/unix/main.c +++ b/ports/unix/main.c @@ -690,13 +690,6 @@ MP_NOINLINE int main_(int argc, char **argv) { MP_STATE_THREAD(prof_trace_callback) = MP_OBJ_NULL; #endif - #if MICROPY_PY_SYS_ATEXIT - // Beware, the sys.settrace callback should be disabled before running sys.atexit. - if (mp_obj_is_callable(MP_STATE_VM(sys_exitfunc))) { - mp_call_function_0(MP_STATE_VM(sys_exitfunc)); - } - #endif - #if MICROPY_PY_MICROPYTHON_MEM_INFO if (mp_verbose_flag) { mp_micropython_mem_info(0, NULL); diff --git a/ports/unix/mpconfigport.h b/ports/unix/mpconfigport.h index 99da47f31b..194f46b2da 100644 --- a/ports/unix/mpconfigport.h +++ b/ports/unix/mpconfigport.h @@ -106,7 +106,6 @@ #define MICROPY_PY_BUILTINS_SLICE_ATTRS (1) #define MICROPY_PY_BUILTINS_SLICE_INDICES (1) #define MICROPY_PY_SYS_EXIT (1) -#define MICROPY_PY_SYS_ATEXIT (1) #if MICROPY_PY_SYS_SETTRACE #define MICROPY_PERSISTENT_CODE_SAVE (1) #define MICROPY_COMP_CONST (0) diff --git a/py/modsys.c b/py/modsys.c index cbd1712920..1e31a04d27 100644 --- a/py/modsys.c +++ b/py/modsys.c @@ -166,16 +166,6 @@ STATIC mp_obj_t mp_sys_getsizeof(mp_obj_t obj) { STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_sys_getsizeof_obj, mp_sys_getsizeof); #endif -#if MICROPY_PY_SYS_ATEXIT -// atexit(callback): Callback is called when sys.exit is called. -STATIC mp_obj_t mp_sys_atexit(mp_obj_t obj) { - mp_obj_t old = MP_STATE_VM(sys_exitfunc); - MP_STATE_VM(sys_exitfunc) = obj; - return old; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_sys_atexit_obj, mp_sys_atexit); -#endif - #if MICROPY_PY_SYS_SETTRACE // settrace(tracefunc): Set the system’s trace function. STATIC mp_obj_t mp_sys_settrace(mp_obj_t obj) { @@ -237,14 +227,6 @@ STATIC const mp_rom_map_elem_t mp_module_sys_globals_table[] = { #if MICROPY_PY_SYS_GETSIZEOF { MP_ROM_QSTR(MP_QSTR_getsizeof), MP_ROM_PTR(&mp_sys_getsizeof_obj) }, #endif - - /* - * Extensions to CPython - */ - - #if MICROPY_PY_SYS_ATEXIT - { MP_ROM_QSTR(MP_QSTR_atexit), MP_ROM_PTR(&mp_sys_atexit_obj) }, - #endif }; STATIC MP_DEFINE_CONST_DICT(mp_module_sys_globals, mp_module_sys_globals_table); diff --git a/py/mpconfig.h b/py/mpconfig.h index 2cd2a0d356..8419a50d5e 100644 --- a/py/mpconfig.h +++ b/py/mpconfig.h @@ -1311,11 +1311,6 @@ typedef double mp_float_t; #define MICROPY_PY_SYS_EXIT (1) #endif -// Whether to provide "sys.atexit" function (MicroPython extension) -#ifndef MICROPY_PY_SYS_ATEXIT -#define MICROPY_PY_SYS_ATEXIT (0) -#endif - // Whether to provide "sys.settrace" function #ifndef MICROPY_PY_SYS_SETTRACE #define MICROPY_PY_SYS_SETTRACE (0) diff --git a/py/mpstate.h b/py/mpstate.h index 423463109d..e868a773bf 100644 --- a/py/mpstate.h +++ b/py/mpstate.h @@ -157,11 +157,6 @@ typedef struct _mp_state_vm_t { mp_obj_base_t *cur_exception; #endif - #if MICROPY_PY_SYS_ATEXIT - // exposed through sys.atexit function - mp_obj_t sys_exitfunc; - #endif - // dictionary for the __main__ module mp_obj_dict_t dict_main; diff --git a/py/runtime.c b/py/runtime.c index ceb5e83b14..ba0d59dffa 100644 --- a/py/runtime.c +++ b/py/runtime.c @@ -130,10 +130,6 @@ void mp_init(void) { sizeof(MP_STATE_VM(fs_user_mount)) - MICROPY_FATFS_NUM_PERSISTENT); #endif - #if MICROPY_PY_SYS_ATEXIT - MP_STATE_VM(sys_exitfunc) = mp_const_none; - #endif - #if MICROPY_PY_SYS_SETTRACE MP_STATE_THREAD(prof_trace_callback) = MP_OBJ_NULL; MP_STATE_THREAD(prof_callback_is_executing) = false; diff --git a/tests/misc/sys_atexit.py b/tests/misc/sys_atexit.py deleted file mode 100644 index e9c5693f97..0000000000 --- a/tests/misc/sys_atexit.py +++ /dev/null @@ -1,21 +0,0 @@ -# test sys.atexit() function - -import sys - -try: - sys.atexit -except AttributeError: - print("SKIP") - raise SystemExit - -some_var = None - - -def do_at_exit(): - print("done at exit:", some_var) - - -sys.atexit(do_at_exit) - -some_var = "ok" -print("done before exit") diff --git a/tests/misc/sys_atexit.py.exp b/tests/misc/sys_atexit.py.exp deleted file mode 100644 index 3cbdae9a5a..0000000000 --- a/tests/misc/sys_atexit.py.exp +++ /dev/null @@ -1,2 +0,0 @@ -done before exit -done at exit: ok diff --git a/tests/unix/extra_coverage.py.exp b/tests/unix/extra_coverage.py.exp index 9a451ebd65..7d87c4f92a 100644 --- a/tests/unix/extra_coverage.py.exp +++ b/tests/unix/extra_coverage.py.exp @@ -41,10 +41,10 @@ ime utime utimeq -argv atexit byteorder exc_info -exit getsizeof implementation maxsize -modules path platform stderr -stdin stdout version version_info +argv byteorder exc_info exit +getsizeof implementation maxsize modules +path platform stderr stdin +stdout version version_info ementation # attrtuple (start=1, stop=2, step=3) From 1c4a6c3667ec1c2005c967b115ab9412336fe151 Mon Sep 17 00:00:00 2001 From: microDev <70126934+microDev1@users.noreply.github.com> Date: Sun, 1 Aug 2021 14:01:40 +0530 Subject: [PATCH 3/5] atexit module refinements - add test for atexit module - add callback to gc collection - fix callback memory allocation - execute callback on both code and repl exit --- lib/utils/pyexec.c | 8 ------- main.c | 10 ++++++++ .../mpconfigboard.mk | 1 - py/circuitpy_mpconfig.mk | 2 +- shared-bindings/atexit/__init__.c | 10 +++++--- shared-module/atexit/__init__.c | 23 +++++++++++-------- shared-module/atexit/__init__.h | 1 + tests/circuitpython/atexit_test.py | 22 ++++++++++++++++++ 8 files changed, 54 insertions(+), 23 deletions(-) create mode 100644 tests/circuitpython/atexit_test.py diff --git a/lib/utils/pyexec.c b/lib/utils/pyexec.c index 0362729b09..2651189915 100644 --- a/lib/utils/pyexec.c +++ b/lib/utils/pyexec.c @@ -44,10 +44,6 @@ #include "lib/utils/pyexec.h" #include "genhdr/mpversion.h" -#if CIRCUITPY_ATEXIT -#include "shared-module/atexit/__init__.h" -#endif - pyexec_mode_kind_t pyexec_mode_kind = PYEXEC_MODE_FRIENDLY_REPL; int pyexec_system_exit = 0; @@ -131,10 +127,6 @@ STATIC int parse_compile_execute(const void *source, mp_parse_input_kind_t input start = mp_hal_ticks_ms(); #endif mp_call_function_0(module_fun); - // execute exit handlers (if any). - #if CIRCUITPY_ATEXIT - shared_module_atexit_execute(); - #endif mp_hal_set_interrupt_char(-1); // disable interrupt mp_handle_pending(true); // handle any pending exceptions (and any callbacks) nlr_pop(); diff --git a/main.c b/main.c index 887b1c1d16..8216713901 100755 --- a/main.c +++ b/main.c @@ -217,6 +217,9 @@ STATIC bool maybe_run_list(const char * const * filenames, pyexec_result_t* exec decompress(compressed, decompressed); mp_hal_stdout_tx_str(decompressed); pyexec_file(filename, exec_result); + #if CIRCUITPY_ATEXIT + shared_module_atexit_execute(); + #endif return true; } @@ -766,6 +769,9 @@ STATIC int run_repl(void) { } else { exit_code = pyexec_friendly_repl(); } + #if CIRCUITPY_ATEXIT + shared_module_atexit_execute(); + #endif cleanup_after_vm(heap, MP_OBJ_SENTINEL); #if CIRCUITPY_STATUS_LED status_led_init(); @@ -881,6 +887,10 @@ void gc_collect(void) { common_hal_alarm_gc_collect(); #endif + #if CIRCUITPY_ATEXIT + atexit_gc_collect(); + #endif + #if CIRCUITPY_DISPLAYIO displayio_gc_collect(); #endif diff --git a/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/mpconfigboard.mk b/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/mpconfigboard.mk index a0bef7ada0..a617947f9c 100644 --- a/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/mpconfigboard.mk +++ b/ports/atmel-samd/boards/adafruit_proxlight_trinkey_m0/mpconfigboard.mk @@ -20,7 +20,6 @@ CIRCUITPY_ROTARYIO = 0 CIRCUITPY_RTC = 0 CIRCUITPY_USB_MIDI = 0 -CIRCUITPY_ATEXIT = 0 CIRCUITPY_PIXELBUF = 1 CIRCUITPY_BUSDEVICE = 1 diff --git a/py/circuitpy_mpconfig.mk b/py/circuitpy_mpconfig.mk index 904ad0ed11..315d6ba52c 100644 --- a/py/circuitpy_mpconfig.mk +++ b/py/circuitpy_mpconfig.mk @@ -48,7 +48,7 @@ CFLAGS += -DCIRCUITPY_ALARM=$(CIRCUITPY_ALARM) CIRCUITPY_ANALOGIO ?= 1 CFLAGS += -DCIRCUITPY_ANALOGIO=$(CIRCUITPY_ANALOGIO) -CIRCUITPY_ATEXIT ?= 1 +CIRCUITPY_ATEXIT ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_ATEXIT=$(CIRCUITPY_ATEXIT) CIRCUITPY_AUDIOBUSIO ?= $(CIRCUITPY_FULL_BUILD) diff --git a/shared-bindings/atexit/__init__.c b/shared-bindings/atexit/__init__.c index 0f4ea26ee9..2d6faf9c72 100644 --- a/shared-bindings/atexit/__init__.c +++ b/shared-bindings/atexit/__init__.c @@ -31,6 +31,9 @@ //| This module defines functions to register and unregister cleanup functions. //| Functions thus registered are automatically executed upon normal vm termination. //| +//| These functions are run in the reverse order in which they were registered; +//| if you register ``A``, ``B``, and ``C``, they will be run in the order ``C``, ``B``, ``A``. +//| //| """ //| ... //| @@ -39,13 +42,14 @@ //| //| """Register func as a function to be executed at termination. //| -//| Any optional arguments that are to be passed to func must be passed as arguments to register(). +//| Any optional arguments that are to be passed to func must be passed as arguments to `register()`. //| It is possible to register the same function and arguments more than once. //| //| At normal program termination (for instance, if `sys.exit()` is called or the vm execution completes), -//| all functions registered are called in order of there registration. +//| all functions registered are called in last in, first out order. //| -//| If an exception is raised during execution of the exit handlers, a traceback is printed and the execution stops. +//| If an exception is raised during execution of the exit handler, +//| a traceback is printed (unless `SystemExit` is raised) and the execution stops. //| //| This function returns func, which makes it possible to use it as a decorator. //| diff --git a/shared-module/atexit/__init__.c b/shared-module/atexit/__init__.c index 7c55b13f67..01ebc49254 100644 --- a/shared-module/atexit/__init__.c +++ b/shared-module/atexit/__init__.c @@ -24,6 +24,7 @@ * THE SOFTWARE. */ +#include "py/gc.h" #include "py/runtime.h" #include "shared-module/atexit/__init__.h" @@ -32,8 +33,8 @@ typedef struct _atexit_callback_t { mp_obj_t func, *args; } atexit_callback_t; -size_t callback_len = 0; -atexit_callback_t *callback = NULL; +static size_t callback_len = 0; +static atexit_callback_t *callback = NULL; void atexit_reset(void) { callback_len = 0; @@ -41,6 +42,10 @@ void atexit_reset(void) { callback = NULL; } +void atexit_gc_collect(void) { + gc_collect_ptr(callback); +} + void shared_module_atexit_register(mp_obj_t *func, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { if (!mp_obj_is_callable(func)) { mp_raise_TypeError_varg(translate("'%q' object is not callable"), mp_obj_get_type_qstr(func)); @@ -50,24 +55,22 @@ void shared_module_atexit_register(mp_obj_t *func, size_t n_args, const mp_obj_t .n_pos = 0, .n_kw = 0, .func = func, - .args = ((n_args + n_kw_args) == 0) ? NULL : m_malloc((n_args + (2 * n_kw_args)) * sizeof(mp_obj_t), false) + .args = (n_args + n_kw_args) ? m_malloc((n_args + (n_kw_args * 2)) * sizeof(mp_obj_t), false) : NULL }; for (; cb.n_pos < n_args; cb.n_pos++) { cb.args[cb.n_pos] = pos_args[cb.n_pos]; } for (size_t i = cb.n_pos; cb.n_kw < n_kw_args; i++, cb.n_kw++) { - cb.args[i] = kw_args[cb.n_kw].table->key; - cb.args[i += 1] = kw_args[cb.n_kw].table->value; - } - if (!callback) { - callback = (atexit_callback_t *)m_realloc(callback, sizeof(cb)); + cb.args[i] = kw_args->table[cb.n_kw].key; + cb.args[i += 1] = kw_args->table[cb.n_kw].value; } + callback = (atexit_callback_t *)m_realloc(callback, (callback_len + 1) * sizeof(cb)); callback[callback_len++] = cb; } void shared_module_atexit_unregister(const mp_obj_t *func) { for (size_t i = 0; i < callback_len; i++) { - if (callback[i].func == func) { + if (callback[i].func == *func) { callback[i].n_pos = 0; callback[i].n_kw = 0; callback[i].func = mp_const_none; @@ -78,7 +81,7 @@ void shared_module_atexit_unregister(const mp_obj_t *func) { void shared_module_atexit_execute(void) { if (callback) { - for (size_t i = 0; i < callback_len; i++) { + for (size_t i = callback_len; i-- > 0;) { if (callback[i].func != mp_const_none) { mp_call_function_n_kw(callback[i].func, callback[i].n_pos, callback[i].n_kw, callback[i].args); } diff --git a/shared-module/atexit/__init__.h b/shared-module/atexit/__init__.h index 48cf0744db..d637a57008 100644 --- a/shared-module/atexit/__init__.h +++ b/shared-module/atexit/__init__.h @@ -30,6 +30,7 @@ #include "py/obj.h" extern void atexit_reset(void); +extern void atexit_gc_collect(void); extern void shared_module_atexit_register(mp_obj_t *func, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args); diff --git a/tests/circuitpython/atexit_test.py b/tests/circuitpython/atexit_test.py new file mode 100644 index 0000000000..b689f5a508 --- /dev/null +++ b/tests/circuitpython/atexit_test.py @@ -0,0 +1,22 @@ +# test atexit module + +try: + import atexit +except ImportError: + print("SKIP") + raise SystemExit + + +@atexit.register +def skip_at_exit(): + print("skip at exit") + + +@atexit.register +def do_at_exit(*args, **kwargs): + print("done at exit:", args, kwargs) + + +atexit.unregister(skip_at_exit) +atexit.register(do_at_exit, "ok", 1, arg="2", param=(3, 4)) +print("done before exit") From bdf8bc58ed2cc7b678573aceca850eb67fe0fa8d Mon Sep 17 00:00:00 2001 From: microDev <70126934+microDev1@users.noreply.github.com> Date: Mon, 16 Aug 2021 22:22:22 +0530 Subject: [PATCH 4/5] allow exception raise inside atexit callback --- lib/utils/pyexec.c | 94 +++++++++++++++++++++------------ lib/utils/pyexec.h | 4 ++ main.c | 8 ++- shared-module/atexit/__init__.c | 16 +++--- shared-module/atexit/__init__.h | 8 ++- 5 files changed, 85 insertions(+), 45 deletions(-) diff --git a/lib/utils/pyexec.c b/lib/utils/pyexec.c index 2651189915..6ffe5d70a7 100644 --- a/lib/utils/pyexec.c +++ b/lib/utils/pyexec.c @@ -44,6 +44,10 @@ #include "lib/utils/pyexec.h" #include "genhdr/mpversion.h" +#if CIRCUITPY_ATEXIT +#include "shared-module/atexit/__init__.h" +#endif + pyexec_mode_kind_t pyexec_mode_kind = PYEXEC_MODE_FRIENDLY_REPL; int pyexec_system_exit = 0; @@ -58,6 +62,7 @@ STATIC bool repl_display_debugging_info = 0; #define EXEC_FLAG_SOURCE_IS_VSTR (16) #define EXEC_FLAG_SOURCE_IS_FILENAME (32) #define EXEC_FLAG_SOURCE_IS_READER (64) +#define EXEC_FLAG_SOURCE_IS_ATEXIT (128) // parses, compiles and executes the code in the lexer // frees the lexer before returning @@ -81,44 +86,49 @@ STATIC int parse_compile_execute(const void *source, mp_parse_input_kind_t input nlr.ret_val = NULL; if (nlr_push(&nlr) == 0) { mp_obj_t module_fun; - #if MICROPY_MODULE_FROZEN_MPY - if (exec_flags & EXEC_FLAG_SOURCE_IS_RAW_CODE) { - // source is a raw_code object, create the function - module_fun = mp_make_function_from_raw_code(source, MP_OBJ_NULL, MP_OBJ_NULL); - } else + #if CIRCUITPY_ATEXIT + if (!(exec_flags & EXEC_FLAG_SOURCE_IS_ATEXIT)) #endif { - #if MICROPY_ENABLE_COMPILER - mp_lexer_t *lex; - if (exec_flags & EXEC_FLAG_SOURCE_IS_VSTR) { - const vstr_t *vstr = source; - lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, vstr->buf, vstr->len, 0); - } else if (exec_flags & EXEC_FLAG_SOURCE_IS_READER) { - lex = mp_lexer_new(MP_QSTR__lt_stdin_gt_, *(mp_reader_t *)source); - } else if (exec_flags & EXEC_FLAG_SOURCE_IS_FILENAME) { - lex = mp_lexer_new_from_file(source); - } else { - lex = (mp_lexer_t *)source; - } - // source is a lexer, parse and compile the script - qstr source_name = lex->source_name; - if (input_kind == MP_PARSE_FILE_INPUT) { - mp_store_global(MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name)); - } - mp_parse_tree_t parse_tree = mp_parse(lex, input_kind); - module_fun = mp_compile(&parse_tree, source_name, exec_flags & EXEC_FLAG_IS_REPL); - // Clear the parse tree because it has a heap pointer we don't need anymore. - *((uint32_t volatile *)&parse_tree.chunk) = 0; - #else - mp_raise_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("script compilation not supported")); + #if MICROPY_MODULE_FROZEN_MPY + if (exec_flags & EXEC_FLAG_SOURCE_IS_RAW_CODE) { + // source is a raw_code object, create the function + module_fun = mp_make_function_from_raw_code(source, MP_OBJ_NULL, MP_OBJ_NULL); + } else #endif - } + { + #if MICROPY_ENABLE_COMPILER + mp_lexer_t *lex; + if (exec_flags & EXEC_FLAG_SOURCE_IS_VSTR) { + const vstr_t *vstr = source; + lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, vstr->buf, vstr->len, 0); + } else if (exec_flags & EXEC_FLAG_SOURCE_IS_READER) { + lex = mp_lexer_new(MP_QSTR__lt_stdin_gt_, *(mp_reader_t *)source); + } else if (exec_flags & EXEC_FLAG_SOURCE_IS_FILENAME) { + lex = mp_lexer_new_from_file(source); + } else { + lex = (mp_lexer_t *)source; + } + // source is a lexer, parse and compile the script + qstr source_name = lex->source_name; + if (input_kind == MP_PARSE_FILE_INPUT) { + mp_store_global(MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name)); + } + mp_parse_tree_t parse_tree = mp_parse(lex, input_kind); + module_fun = mp_compile(&parse_tree, source_name, exec_flags & EXEC_FLAG_IS_REPL); + // Clear the parse tree because it has a heap pointer we don't need anymore. + *((uint32_t volatile *)&parse_tree.chunk) = 0; + #else + mp_raise_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("script compilation not supported")); + #endif + } - // If the code was loaded from a file it's likely to be running for a while so we'll long - // live it and collect any garbage before running. - if (input_kind == MP_PARSE_FILE_INPUT) { - module_fun = make_obj_long_lived(module_fun, 6); - gc_collect(); + // If the code was loaded from a file it's likely to be running for a while so we'll long + // live it and collect any garbage before running. + if (input_kind == MP_PARSE_FILE_INPUT) { + module_fun = make_obj_long_lived(module_fun, 6); + gc_collect(); + } } // execute code @@ -126,7 +136,15 @@ STATIC int parse_compile_execute(const void *source, mp_parse_input_kind_t input #if MICROPY_REPL_INFO start = mp_hal_ticks_ms(); #endif - mp_call_function_0(module_fun); + #if CIRCUITPY_ATEXIT + if (exec_flags & EXEC_FLAG_SOURCE_IS_ATEXIT) { + atexit_callback_t *callback = (atexit_callback_t *)source; + mp_call_function_n_kw(callback->func, callback->n_pos, callback->n_kw, callback->args); + } else + #endif + { + mp_call_function_0(module_fun); + } mp_hal_set_interrupt_char(-1); // disable interrupt mp_handle_pending(true); // handle any pending exceptions (and any callbacks) nlr_pop(); @@ -741,6 +759,12 @@ int pyexec_frozen_module(const char *name, pyexec_result_t *result) { } #endif +#if CIRCUITPY_ATEXIT +int pyexec_exit_handler(const void *source, pyexec_result_t *result) { + return parse_compile_execute(source, MP_PARSE_FILE_INPUT, EXEC_FLAG_SOURCE_IS_ATEXIT, result); +} +#endif + #if MICROPY_REPL_INFO mp_obj_t pyb_set_repl_info(mp_obj_t o_value) { repl_display_debugging_info = mp_obj_get_int(o_value); diff --git a/lib/utils/pyexec.h b/lib/utils/pyexec.h index 6f0252cfed..3d3c2d6c53 100644 --- a/lib/utils/pyexec.h +++ b/lib/utils/pyexec.h @@ -59,6 +59,10 @@ void pyexec_event_repl_init(void); int pyexec_event_repl_process_char(int c); extern uint8_t pyexec_repl_active; +#if CIRCUITPY_ATEXIT +int pyexec_exit_handler(const void *source, pyexec_result_t *result); +#endif + #if MICROPY_REPL_INFO mp_obj_t pyb_set_repl_info(mp_obj_t o_value); MP_DECLARE_CONST_FUN_OBJ_1(pyb_set_repl_info_obj); diff --git a/main.c b/main.c index 8216713901..74a706e063 100755 --- a/main.c +++ b/main.c @@ -218,7 +218,7 @@ STATIC bool maybe_run_list(const char * const * filenames, pyexec_result_t* exec mp_hal_stdout_tx_str(decompressed); pyexec_file(filename, exec_result); #if CIRCUITPY_ATEXIT - shared_module_atexit_execute(); + shared_module_atexit_execute(exec_result); #endif return true; } @@ -770,7 +770,11 @@ STATIC int run_repl(void) { exit_code = pyexec_friendly_repl(); } #if CIRCUITPY_ATEXIT - shared_module_atexit_execute(); + pyexec_result_t result; + shared_module_atexit_execute(&result); + if (result.return_code == PYEXEC_DEEP_SLEEP) { + exit_code = PYEXEC_DEEP_SLEEP; + } #endif cleanup_after_vm(heap, MP_OBJ_SENTINEL); #if CIRCUITPY_STATUS_LED diff --git a/shared-module/atexit/__init__.c b/shared-module/atexit/__init__.c index 01ebc49254..56271bbab8 100644 --- a/shared-module/atexit/__init__.c +++ b/shared-module/atexit/__init__.c @@ -28,11 +28,6 @@ #include "py/runtime.h" #include "shared-module/atexit/__init__.h" -typedef struct _atexit_callback_t { - size_t n_pos, n_kw; - mp_obj_t func, *args; -} atexit_callback_t; - static size_t callback_len = 0; static atexit_callback_t *callback = NULL; @@ -79,11 +74,18 @@ void shared_module_atexit_unregister(const mp_obj_t *func) { } } -void shared_module_atexit_execute(void) { +void shared_module_atexit_execute(pyexec_result_t *result) { if (callback) { for (size_t i = callback_len; i-- > 0;) { if (callback[i].func != mp_const_none) { - mp_call_function_n_kw(callback[i].func, callback[i].n_pos, callback[i].n_kw, callback[i].args); + if (result != NULL) { + pyexec_result_t res; + if (pyexec_exit_handler(&callback[i], &res) == PYEXEC_DEEP_SLEEP) { + *result = res; + } + } else { + pyexec_exit_handler(&callback[i], NULL); + } } } } diff --git a/shared-module/atexit/__init__.h b/shared-module/atexit/__init__.h index d637a57008..befccb3ea8 100644 --- a/shared-module/atexit/__init__.h +++ b/shared-module/atexit/__init__.h @@ -28,6 +28,12 @@ #define MICROPY_INCLUDED_SHARED_MODULE_ATEXIT___INIT___H #include "py/obj.h" +#include "lib/utils/pyexec.h" + +typedef struct _atexit_callback_t { + size_t n_pos, n_kw; + mp_obj_t func, *args; +} atexit_callback_t; extern void atexit_reset(void); extern void atexit_gc_collect(void); @@ -35,6 +41,6 @@ extern void atexit_gc_collect(void); extern void shared_module_atexit_register(mp_obj_t *func, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args); extern void shared_module_atexit_unregister(const mp_obj_t *func); -extern void shared_module_atexit_execute(void); +extern void shared_module_atexit_execute(pyexec_result_t *result); #endif // MICROPY_INCLUDED_SHARED_MODULE_ATEXIT___INIT___H From 6c763762d468308420aa51e61f881879a1e5f778 Mon Sep 17 00:00:00 2001 From: microDev <70126934+microDev1@users.noreply.github.com> Date: Tue, 17 Aug 2021 10:10:10 +0530 Subject: [PATCH 5/5] restore sys.atexit() to prevent merge conflict --- ports/unix/main.c | 7 +++++++ py/modsys.c | 18 ++++++++++++++++++ py/mpconfig.h | 5 +++++ py/mpstate.h | 5 +++++ py/runtime.c | 4 ++++ 5 files changed, 39 insertions(+) diff --git a/ports/unix/main.c b/ports/unix/main.c index b69df90354..55bdc22082 100644 --- a/ports/unix/main.c +++ b/ports/unix/main.c @@ -690,6 +690,13 @@ MP_NOINLINE int main_(int argc, char **argv) { MP_STATE_THREAD(prof_trace_callback) = MP_OBJ_NULL; #endif + #if MICROPY_PY_SYS_ATEXIT + // Beware, the sys.settrace callback should be disabled before running sys.atexit. + if (mp_obj_is_callable(MP_STATE_VM(sys_exitfunc))) { + mp_call_function_0(MP_STATE_VM(sys_exitfunc)); + } + #endif + #if MICROPY_PY_MICROPYTHON_MEM_INFO if (mp_verbose_flag) { mp_micropython_mem_info(0, NULL); diff --git a/py/modsys.c b/py/modsys.c index 1e31a04d27..cbd1712920 100644 --- a/py/modsys.c +++ b/py/modsys.c @@ -166,6 +166,16 @@ STATIC mp_obj_t mp_sys_getsizeof(mp_obj_t obj) { STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_sys_getsizeof_obj, mp_sys_getsizeof); #endif +#if MICROPY_PY_SYS_ATEXIT +// atexit(callback): Callback is called when sys.exit is called. +STATIC mp_obj_t mp_sys_atexit(mp_obj_t obj) { + mp_obj_t old = MP_STATE_VM(sys_exitfunc); + MP_STATE_VM(sys_exitfunc) = obj; + return old; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_sys_atexit_obj, mp_sys_atexit); +#endif + #if MICROPY_PY_SYS_SETTRACE // settrace(tracefunc): Set the system’s trace function. STATIC mp_obj_t mp_sys_settrace(mp_obj_t obj) { @@ -227,6 +237,14 @@ STATIC const mp_rom_map_elem_t mp_module_sys_globals_table[] = { #if MICROPY_PY_SYS_GETSIZEOF { MP_ROM_QSTR(MP_QSTR_getsizeof), MP_ROM_PTR(&mp_sys_getsizeof_obj) }, #endif + + /* + * Extensions to CPython + */ + + #if MICROPY_PY_SYS_ATEXIT + { MP_ROM_QSTR(MP_QSTR_atexit), MP_ROM_PTR(&mp_sys_atexit_obj) }, + #endif }; STATIC MP_DEFINE_CONST_DICT(mp_module_sys_globals, mp_module_sys_globals_table); diff --git a/py/mpconfig.h b/py/mpconfig.h index 8419a50d5e..2cd2a0d356 100644 --- a/py/mpconfig.h +++ b/py/mpconfig.h @@ -1311,6 +1311,11 @@ typedef double mp_float_t; #define MICROPY_PY_SYS_EXIT (1) #endif +// Whether to provide "sys.atexit" function (MicroPython extension) +#ifndef MICROPY_PY_SYS_ATEXIT +#define MICROPY_PY_SYS_ATEXIT (0) +#endif + // Whether to provide "sys.settrace" function #ifndef MICROPY_PY_SYS_SETTRACE #define MICROPY_PY_SYS_SETTRACE (0) diff --git a/py/mpstate.h b/py/mpstate.h index e868a773bf..423463109d 100644 --- a/py/mpstate.h +++ b/py/mpstate.h @@ -157,6 +157,11 @@ typedef struct _mp_state_vm_t { mp_obj_base_t *cur_exception; #endif + #if MICROPY_PY_SYS_ATEXIT + // exposed through sys.atexit function + mp_obj_t sys_exitfunc; + #endif + // dictionary for the __main__ module mp_obj_dict_t dict_main; diff --git a/py/runtime.c b/py/runtime.c index ba0d59dffa..ceb5e83b14 100644 --- a/py/runtime.c +++ b/py/runtime.c @@ -130,6 +130,10 @@ void mp_init(void) { sizeof(MP_STATE_VM(fs_user_mount)) - MICROPY_FATFS_NUM_PERSISTENT); #endif + #if MICROPY_PY_SYS_ATEXIT + MP_STATE_VM(sys_exitfunc) = mp_const_none; + #endif + #if MICROPY_PY_SYS_SETTRACE MP_STATE_THREAD(prof_trace_callback) = MP_OBJ_NULL; MP_STATE_THREAD(prof_callback_is_executing) = false;