[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Bug-gnulib] checking for overflow

From: Paul Eggert
Subject: Re: [Bug-gnulib] checking for overflow
Date: 20 Oct 2003 15:33:05 -0700
User-agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.3

Bruno Haible <address@hidden> writes:

>   a) About the technical means: We could use gcc's flag -ftrapv (which
>      should, starting with gcc-3.4, finally work).

I assume by "use -ftrapv" you mean that we debug with -ftrapv.  I
doubt whether this is a good idea, as there are too many cases where
signed overflow is benign.

>      Or do we put the checking into the code, assuming that normal
>      int opeations are modulo 2^32 ?

For unsigned calculations like size_t, it's safe to assume that
computations are modulo SIZE_MAX + 1.  The C standard guarantees that
unsigned int arithmetic is modulo UINT_MAX+1, and similarly for other
unsigned types.

Some gnulib code uses signed int operations for sizes, but such code
is almost invariably buggy, and should use size_t calculations

Things get a little tricky if we want to worry about hosts where
SIZE_MAX <= INT_MAX, since on such hosts size_t values promote to int,
but I don't know of any such hosts so fixing that problem is low
priority.  (The fix for such a problem usually is trivial and has no
run-time cost and doesn't contort the code much so I generally put the
fix in if I see the problem; but it is low priority.)

>   b) Which places are considered dangerous? Only those where an overflow
>      can easily happen when unintended, as in multiplication (xcalloc
>      and friends)? Or does _any_ addition of a size_t to another size_t
>      count as overflow opportunity?

The former is closer to being right, but one must sometimes do overflow
checking for addition too.  gnulib/README says this:

 * If two nonoverlapping objects have sizes S and T represented as
   size_t values, then S + T cannot overflow.  This assumption is true
   for all practical hosts with flat address spaces, but it is not
   always true for hosts with segmented address spaces.

which means that, for example, if S and T are nonoverlapping strings,
then (strlen (S) + strlen (T) + 2) cannot overflow.  Another example:
if S is a string, then strlen (S) + 1000 cannot overflow, since there
sum of the sizes of the other objects in your program must be at least
1000.  Some of these assumptions are not written down, unfortunately;
in particular, that "+ 1000" assumption isn't written down.

reply via email to

[Prev in Thread] Current Thread [Next in Thread]