py/misc: Change sizeof to offsetof for variable-length alloc.

This fixes the case where e.g.

    struct foo_t {
      mp_obj_t x;
      uint16_t y;
      char buf[];
    };

will have `sizeof(struct foo_t)==8`, but `offsetof(struct foo_t, buf)==6`.

When computing the size to allocate for `m_new_obj_var` we need to use
offsetof to avoid over-allocating. This is important especially when it
might cause it to spill over into another GC block.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
This commit is contained in:
Jim Mussared
2023-11-03 14:19:55 +11:00
committed by Damien George
parent c85db05244
commit b6a9778484
11 changed files with 24 additions and 24 deletions

View File

@@ -235,7 +235,7 @@ STATIC mp_obj_t mod_thread_start_new_thread(size_t n_args, const mp_obj_t *args)
// check for keyword arguments
if (n_args == 2) {
// just position arguments
th_args = m_new_obj_var(thread_entry_args_t, mp_obj_t, pos_args_len);
th_args = m_new_obj_var(thread_entry_args_t, args, mp_obj_t, pos_args_len);
th_args->n_kw = 0;
} else {
// positional and keyword arguments
@@ -243,7 +243,7 @@ STATIC mp_obj_t mod_thread_start_new_thread(size_t n_args, const mp_obj_t *args)
mp_raise_TypeError(MP_ERROR_TEXT("expecting a dict for keyword args"));
}
mp_map_t *map = &((mp_obj_dict_t *)MP_OBJ_TO_PTR(args[2]))->map;
th_args = m_new_obj_var(thread_entry_args_t, mp_obj_t, pos_args_len + 2 * map->used);
th_args = m_new_obj_var(thread_entry_args_t, args, mp_obj_t, pos_args_len + 2 * map->used);
th_args->n_kw = map->used;
// copy across the keyword arguments
for (size_t i = 0, n = pos_args_len; i < map->alloc; ++i) {