[v2] sprof: check pread size and offset for overflow
Paul Eggert
eggert@cs.ucla.edu
Thu Oct 16 23:46:05 GMT 2025
On 2025-10-16 12:23, DJ Delorie wrote:
> +#define PCHECK(sz,off) if ((sz) > st.st_size \
> + || (off_t)(off) < 0 || (off_t)(off) > st.st_size \
> + ((sz)+(off_t)(off)) > st.st_size) \
This still could have undefined behavior, as the addition in the last
line could have signed integer overflow.
What you're trying to say here, is that SZ and OFF are both nonnegative,
and that their sum is less than ST.st_size. I suggest saying that more
directly, with something like this:
void
pcheck (long long int off, long long int sz, off_t file_size)
{
long long int end_off;
if (off < 0 || sz < 0
|| __builtin_add_overflow (off, sz, &end_off)
|| file_size < end_off)
error (EXIT_FAILURE, ERANGE,
_("read outside of file extents %lld + %lld > %lld"),
off, sz, (long long int) file_size);
}
With GCC -O2 this typically generates three conditional branches; we can
cut it down to two if that kind of efficiency is relevant here.
More information about the Libc-alpha
mailing list