On 01/10/2011 11:28 AM, Andy Green wrote:
On 01/10/11 11:14, Somebody in the thread at some point said:
>> struct mystruct *p = (struct mystruct *)&buffer[n];
>>
>> On x86 this code is always OK, although it may run faster or slower
>> depending on alignment.
>
> Yes, but in C code this is always a bug, and should always be fixed.
Well, as I said I worked on radiotap which does this and I believe
the kernel may have code like this for skbs; the network stack
over-allocates behind the packet and afterwards so the various
layers of networking protocol can prepend and append stuff to the
payload without having to copy the payload (see struct skb). That's
quite a powerful technique since it can have a lot of value to use a
structure to access this data in terms of code clarity if nothing
else. But the added stuff may be at funny intra-word offsets since
it's allocating backwards.
> Even on x86 it may not always generate code that does what you want:
> gcc is perfectly entitled to assume that an unaligned pointer is
> never used. And even now, x86 has a big performance hit for word
> accesses that straddle a cache line boundary.
I don't know about gcc being able to discard unaligned pointers, and
have never observed it to my knowledge. That's just a "C lawyer"
possibility or actually can happen?
Both. It doesn't happen, but according to the language specification
it could. However, we've seen quite enough of "this is only a
language lawyer's theoretical possibility" bugs turning into real
bugs.
For radiotap parsing, which has structures at arbitrary byte offsets
depending on what went before, the answer was to use an unaligned
struct alright but ensure bytewise accessors were used to touch the
data.
That's a good solution.
In the case of SHA, though, I suspect this is just a misoptimization.
Andrew.