Skip to content

fixed realloc(0) may alloc min unit memory on some allocator #1050

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from

Conversation

penneryu
Copy link
Contributor

@penneryu penneryu commented May 6, 2025

On some memory allocators, such as hardened_malloc, realloc(0) will allocate a minimum unit of memory (16 bytes)

The hardened_malloc is used on grapheneos, a common operating system on android.

h_malloc.c

static inline void *allocate_small(unsigned arena, size_t requested_size) {
    struct size_info info = get_size_info(requested_size);
    size_t size = likely(info.size) ? info.size : 16;

    struct size_class *c = &ro.size_class_metadata[arena][info.class];
    size_t slots = get_slots(info.class);
    size_t slab_size = get_slab_size(slots, size);
    ...

@saghul
Copy link
Contributor

saghul commented May 6, 2025

lre_realloc calls js_realloc_rt, which looks as follows:

void *js_realloc_rt(JSRuntime *rt, void *ptr, size_t size)
{
    size_t old_size;
    JSMallocState *s;

    if (!ptr) {
        if (size == 0)
            return NULL;
        return js_malloc_rt(rt, size);
    }
    if (unlikely(size == 0)) {
        js_free_rt(rt, ptr);
        return NULL;
    }
    old_size = rt->mf.js_malloc_usable_size(ptr);
    s = &rt->malloc_state;
    /* When malloc_limit is 0 (unlimited), malloc_limit - 1 will be SIZE_MAX. */
    if (s->malloc_size + size - old_size > s->malloc_limit - 1)
        return NULL;

    ptr = rt->mf.js_realloc(s->opaque, ptr, size);
    if (!ptr)
        return NULL;

    s->malloc_size += rt->mf.js_malloc_usable_size(ptr) - old_size;
    return ptr;
}

Since we already call js_free_rt if size if 0, I think your case is already handled, isn't it?

@penneryu
Copy link
Contributor Author

penneryu commented May 6, 2025

Yes indeed, I missed this, I will close this PR

@penneryu penneryu closed this May 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants