Re: ✘integer overflow in expression

Daniel Franke dfoxfranke at gmail.com
Thu Sep 29 13:41:06 UTC 2016


This whole module is a big mess of undefined behavior.

If you're going to store time as a count of nanoseconds, then of
course you're going to overflow a 32-bit integer quickly. 'long' is 32
bits on most 32-bit ABIs. You want all your working variables to be
int64_t. The correct way to express an int64_t literal is

#include <stdint.h>
INT64_C(9999999999999)

But even a 64-bit integer risks overflow, because CLOCK_MONOTONIC has
an unspecified starting point. (tv_sec * NANOSECONDS) may not fit in
an int64_t. Since you only care about time differences and not
absolute times, you can get around this by normalizing your starting
point to tv_sec = 0. So declare

time_t s;

and then have your initialization be:

clock_gettime(CLOCK_MONOTONIC, &ts);
s = ts.tv_sec;
t = ts.tv_nsec;

and change the u assignment to read:

u = (tr.tv_sec - s) * NANOSECONDS + ts.tv_nsec;

In the printf statements, use the macro PRId64 to give you the correct
printf conversion specifier for an int64_t.

The col() function needs to be rewritten to make sure that casting its
return type to int won't overflow.

All the comments about forcing pages into memory are bizarre. Of
course the code that follows has to be there because otherwise gtod
will be used uninitialized. But no memory is being locked so there's
no guarantee that those pages will still be there by the time they're
used, especially given all the intervening context switches to call
clock_gettime().

clock_gettime()'s return value needs to be checked.


More information about the devel mailing list