<div dir="ltr">On Fri, Oct 25, 2013 at 1:10 PM, Jeffrey Yasskin <span dir="ltr"><<a href="mailto:jyasskin@google.com" target="_blank">jyasskin@google.com</a>></span> wrote:<br><div class="gmail_extra"><div class="gmail_quote">
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div class="im">On Fri, Oct 25, 2013 at 12:50 PM, Jens Maurer <<a href="mailto:Jens.Maurer@gmx.net">Jens.Maurer@gmx.net</a>> wrote:<br>
> On 10/25/2013 09:36 PM, John Regehr wrote:<br>
>>> What reason do you have to believe that crypto is using any signed<br>
>>> arithmetic? I would not.<br>
>><br>
>> Here's an example that's at least slightly interesting, from the latest<br>
>> version of LibTomCrypt:<br>
>><br>
>> kappa[i] =<br>
>> (key[pos ] << 24) ^<br>
>> (key[pos + 1] << 16) ^<br>
>> (key[pos + 2] << 8) ^<br>
>> (key[pos + 3] );<br>
>><br>
>> key is a pointer to unsigned char. Of course, the array element becomes<br>
>> signed after promotion. The shift by 24 then executes an undefined<br>
>> behavior whenever the shifted value is >127.<br>
>><br>
>> So the interesting thing is that the developer is basically doing things<br>
>> right and getting hosed by the arithmetic conversions.<br>
><br>
> If I'm reading 5p10 correctly, this should help (and is consistently<br>
> expressing intent):<br>
><br>
> kappa[i] =<br>
> (key[pos ] << 24u) ^<br>
> (key[pos + 1] << 16u) ^<br>
> (key[pos + 2] << 8u) ^<br>
> (key[pos + 3] );<br>
><br>
> Jens<br>
<br>
</div>Nope: [expr.shift]p1 says, "The type of the result is that of the<br>
promoted left operand."<br></blockquote><div><br></div><div>I believe John is correct. 5.8/1 says we perform <i>integral promotions</i> on the operands, not the <i>usual arithmetic conversions</i>. Clang, g++, and EDG agree -- the type of (unsigned char)0 << 0u is int.</div>
<div> </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
However, I think p2 saves our intrepid developer in C++14: "Otherwise,<br>
if E1 has a signed type and non-negative value, and E1 × 2^E2 is<br>
representable in the corresponding unsigned type of the result type,<br>
then that value, converted to the result type, is the<br>
resulting value;"</blockquote><div><br></div><div>We gave this defined behavior as a DR, so I view this code has having de facto defined behavior in C++11 and C++98 too. But it's UB in C.</div><div><br></div><div>
In other words, we've already fixed this one (for some value of "fixed").</div></div></div></div>