4 ms·
Note that even if you try to manually correct the pointer to work on aligned data (read any initial bytes via char pointer and read the rest via uint32_t pointe
by ambrop7 10y ago
Note that even if you try to manually correct the pointer to work on aligned data (read any initial bytes via char pointer and read the rest via uint32_t pointer), you still generally have undefined behavior: strict-aliasing violation. And the worst thing here is that whether you do have a violation depends on how other code accesses the same data / how the object is initially declared. E.g., you're fine if the original declaration is char[] or uint32_t[], but not if it's uint16_t[]. Because that would entail access to the same data via both uint16_t and uint32_t, a violation of strict-aliasing.
Actually two out of three inet checksum implementations in lwIP have this bug [1].
And like the problem discovered in the article, this is NOT theoretical. I have personally seen code "miscompiled" due to strict aliasing violations (in that case, packed structures were involved).
I think the only way to do this "manual alignment handling" is to use assembly, either by writing the entire thing in assembly, or using inline asm sections for doing the individual 32-bit memory reads/writes.
Funny story... When I was looking for a fast inet checksum implementation to use for an embedded ARM project, I took the one from RTEMS, which is written in C with much inline asm, and like the lwIP code, it has strict aliasing violations (and also problems compiling correctly with clang). What I did was, compiled it to assembly with gcc once, then included this compiled assembly in the source code. Assuming that this was compiled correctly, I don't need to be afraid of future compiler change breaking it.
[1] http://git.savannah.gnu.org/cgit/lwip.git/tree/src/core/inet_chksum.c http://git.savannah.gnu.org/cgit/lwip.git/tree/src/core/inet...
- nikanj 10y agoFor what it's worth, people like Linus seem to despise the strict aliasing optimization. https://lkml.org/lkml/2003/2/26/158 https://lkml.org/lkml/2003/2/26/158
- dmm 10y agoStrict aliasing can worked around by casting through a union, essentially introducing a new type which can alias any of its component types. Mike Acton has a good description of it with lots of assembly examples here: http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html http://cellperformance.beyond3d.com/articles/2006/06/underst...