[Cryptography] GCC bug 30475 (was Re: bounded pointers in C)

Jerry Leichter leichter at lrw.com
Thu Apr 24 23:18:00 EDT 2014


On Apr 24, 2014, at 9:11 PM, Viktor Dukhovni <cryptography at dukhovni.org> wrote:

> On Thu, Apr 24, 2014 at 05:04:14PM -0700, Bear wrote:
> 
>> There are in fact conformant checks for signed overflow. 
>> 
>> For example, you can say 
>> 
>> if (MAXINT - al >= be) halt(2); // overflow check - not using assert()
>>                                // because we want this check in
>>                                // production code.
>> ce = al + be;                   // addition guaranteed not to overflow.
> 
> That's nice, but how do I do that for an "off_t", or other typedefed
> integral type, which has no explicit INTFOO_MAX macro?
> 
> Ideally something that does not introduce a C99 dependency and
> works even with older ANSI C compilers.
I believe C99 guarantees that int's representation is either 1's or 2's complement.  That makes it easy to produce the maximum value for a signed type. Assume we know T is some signed integral type.  Then:

T max = ~(T)0;
if (max == 0)
{	// 1's complement
	T sign_bit = 1;
	while (sign_bit > 0)
		sign_bit <<= 1;
	max = max ^ sign_bit;
}
else	// 2's complement
{	max = -(max + 1);
}

If we don't know whether T is signed or unsigned, it's easy enough to check:

T t = ~(T)0;
if (t < 0)
	<signed>
else	<unsigned>

Unfortunately, this doesn't produce a compile-time constant.  I don't know how to do that; it's probably not possible.
                                                        -- Jerry



More information about the cryptography mailing list