sprof: check pread size and offset for overflow

DJ Delorie dj@redhat.com
Thu Oct 16 02:22:31 GMT 2025


Collin Funk <collin.funk1@gmail.com> writes:
> Wouldn't it be easier to just use __builtin_add_overflow, check the
> result, and then do the comparison? I think that would be easier to
> read.

I want to do more than just check the sum, I want to check that every
aspect of this math is "inside" the file.  Any bad data is an error.

I tweaked the logic and the comment to better explain this:

  /* We're depending on data that's being read from the file, so be a
     bit paranoid here and make sure the requests are reasonable -
     i.e. both size and offset are nonnegative and smaller than the
     file size, as well as the offset of the end of the data.  PREAD
     would have failed anyway, but this is more robust and explains
     what happened better.  */
#define PCHECK(s,l) if ((s) < 0  || (s) > st.st_size			\
			|| (l) < 0 || (l) > st.st_size			\
			|| ((s)+(l)) < 0 || ((s)+(l)) > st.st_size)	\
    error (EXIT_FAILURE, ERANGE,					\


Only one of the six checks would use the builtin, and that would make
the expression less consistent.

Also, technically, we don't need to check size < 0 since size is
unsigned (size_t) but I like including it for consistency and to guard
against potential argument swapping.  My build didn't complain about an
unneeded compare.



More information about the Libc-alpha mailing list