Skip to content
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

mrs_realloc: avoid copies when space is available #2133

Merged
merged 1 commit into from
Jul 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions lib/libc/stdlib/malloc/mrs/mrs.c
Original file line number Diff line number Diff line change
Expand Up @@ -1515,6 +1515,21 @@ mrs_realloc(void *ptr, size_t size)
mrs_debug_printf("mrs_realloc: called ptr %p ptr size %zu new size %zu\n",
brooksdavis marked this conversation as resolved.
Show resolved Hide resolved
ptr, old_size, size);

/*
* If the new size fits in the current allocation and we won't
* be wasting too much space, just return the existing pointer.
*
* Only try to reclaim space by copying if we'd recover at least
* half of the allocated storage. In other cases we can't tell
* the difference between shrinking and linear growth into a
* large over-allocation (e.g., growing into snmalloc's
* power-of-two buckets by 1K) and we especially want to avoid
* copying such cases.
*/
if (ptr != NULL && cheri_gettag(ptr) && cheri_getoffset(ptr) == 0 &&
size <= old_size && old_size - size <= (old_size >> 1))
return (ptr);

void *new_alloc = mrs_malloc(size);

/*
Expand Down
Loading