Skip to content

c: check for size overflow in moocore_malloc() - #107

Open
krrish612 wants to merge 2 commits into
multi-objective:mainfrom
krrish612:malloc-overflow-check
Open

krrish612 wants to merge 2 commits into
multi-objective:mainfrom
krrish612:malloc-overflow-check

Conversation

@krrish612

Copy link
Copy Markdown

This picks off the FIXME in moocore_malloc() ("Check multiplication overflow"), which is the first item in #11.

Right now nmemb * size is passed straight to malloc(). If the product wraps around, you get a small buffer back and a very confused program a few lines later. This adds the usual nmemb > SIZE_MAX / size check (same idea as reallocarray()), and reports it through moocore_perror(), so it behaves like any other failed allocation, including under R where that turns into an R error.

I kept it deliberately small: one function, no changes to any call site. I didn't touch the remaining raw malloc/realloc calls. Happy to do those in follow-ups if you want, say a moocore_realloc() and then converting call sites file by file, so each PR stays easy to review.

How I checked it, on Ubuntu with make all DEBUG=1 (so ASan and -Wall -Wextra -Wconversion): it builds without new warnings, make test passes, a call like moocore_malloc(SIZE_MAX/2, 4, ...) now stops with size overflow and exit code 1, and a normal MOOCORE_MALLOC(10, int) works as before.

Refs #11

moocore_malloc() computed nmemb * size without checking whether the
product wraps around, so a huge nmemb could quietly ask malloc() for a
tiny buffer. Reject it up front, the same way reallocarray() does, and
report it through moocore_perror() like a failed allocation.

This resolves the FIXME in common.h and is a first step for multi-objective#11.
@MLopez-Ibanez

Copy link
Copy Markdown
Contributor

Thanks!

I would prefer to use the standard ckd_mul in <stdckdint.h> if that is available. See https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3096.pdf
Otherwise, define it in terms of __builtin_mul_overflow like glibc does, if available (it should be available for GCC and Clang at least), or define it using the idea from reallocarray() if neither option is available. See the links in the comment on how to use the builtin and how to test for it.

The use of the standard or the builtin saves one multiplication: https://godbolt.org/z/vqPeKcbea

When the minimum required C version becomes C23, we can delete the fall-backs.

Use <stdckdint.h> where available, fall back to
__builtin_mul_overflow, and to a manual check otherwise. In
eaf_create(), pass maxsize as nmemb so the wrapper checks that
product.

This branch has not been deployed

No deployments
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