From 4133c0304011ff7be23f47516aac20ed54505e7a Mon Sep 17 00:00:00 2001 From: Damien George Date: Fri, 16 Feb 2024 10:58:36 +1100 Subject: [PATCH] py/obj: Introduce mp_obj_malloc_with_finaliser to allocate and set type. Following 709e8328d9812a2e02da6fba65a03f9a873d60a2. Using this helps to reduce code size. And it ensure that the type is always set as soon as the object is allocated, which is important for the GC to function correctly. Signed-off-by: Damien George --- py/obj.c | 9 +++++++++ py/obj.h | 10 ++++++++++ 2 files changed, 19 insertions(+) diff --git a/py/obj.c b/py/obj.c index 5e01198b6f..e43451dadd 100644 --- a/py/obj.c +++ b/py/obj.c @@ -44,6 +44,15 @@ MP_NOINLINE void *mp_obj_malloc_helper(size_t num_bytes, const mp_obj_type_t *ty return base; } +#if MICROPY_ENABLE_FINALISER +// Allocates an object and also sets type, for mp_obj_malloc{,_var}_with_finaliser macros. +MP_NOINLINE void *mp_obj_malloc_with_finaliser_helper(size_t num_bytes, const mp_obj_type_t *type) { + mp_obj_base_t *base = (mp_obj_base_t *)m_malloc_with_finaliser(num_bytes); + base->type = type; + return base; +} +#endif + const mp_obj_type_t *MICROPY_WRAP_MP_OBJ_GET_TYPE(mp_obj_get_type)(mp_const_obj_t o_in) { #if MICROPY_OBJ_IMMEDIATE_OBJS && MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A diff --git a/py/obj.h b/py/obj.h index 5d49873ff9..bd0df3fd68 100644 --- a/py/obj.h +++ b/py/obj.h @@ -916,6 +916,16 @@ extern const struct _mp_obj_exception_t mp_const_GeneratorExit_obj; #define mp_obj_malloc_var(struct_type, var_field, var_type, var_num, obj_type) ((struct_type *)mp_obj_malloc_helper(offsetof(struct_type, var_field) + sizeof(var_type) * (var_num), obj_type)) void *mp_obj_malloc_helper(size_t num_bytes, const mp_obj_type_t *type); +// Object allocation macros for allocating objects that have a finaliser. +#if MICROPY_ENABLE_FINALISER +#define mp_obj_malloc_with_finaliser(struct_type, obj_type) ((struct_type *)mp_obj_malloc_with_finaliser_helper(sizeof(struct_type), obj_type)) +#define mp_obj_malloc_var_with_finaliser(struct_type, var_type, var_num, obj_type) ((struct_type *)mp_obj_malloc_with_finaliser_helper(sizeof(struct_type) + sizeof(var_type) * (var_num), obj_type)) +void *mp_obj_malloc_with_finaliser_helper(size_t num_bytes, const mp_obj_type_t *type); +#else +#define mp_obj_malloc_with_finaliser(struct_type, obj_type) mp_obj_malloc(struct_type, obj_type) +#define mp_obj_malloc_var_with_finaliser(struct_type, var_type, var_num, obj_type) mp_obj_malloc_var(struct_type, var_type, var_num, obj_type) +#endif + // These macros are derived from more primitive ones and are used to // check for more specific object types. // Note: these are kept as macros because inline functions sometimes use much