dao
dao copied to clipboard
Prevent overflow in integer arguments of dao_(c|m|re)alloc functions
OpenBSD adopted a solution to overflows when allocating memory. They created wrapper:
void *reallocarray(void *optr, size_t nmemb, size_t size)
{
/* most of the times, the numbers are smaller and division is too costly
nmemb*size << sqrt(SIZE_MAX+1)*sqrt(SIZE_MAX+1) */
if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
nmemb > 0 && SIZE_MAX / nmemb < size) {
errno = ENOMEM;
return NULL;
}
return realloc(optr, size * nmemb);
}
It's hard to say, whether it is or is not more important than on other places where multiplication is used, but reading a whole file bigger than half of the addressable memory into memory definitely should not crash Dao. In Dao, we have a lot of reallocs without integer overflow checks.
Btw if we wanted to implement it, we would need a more generic variant, perhaps macro, due to variable number of multiplication operands (not just two).