Getting rid of Unaligned Accesses (UA)

Maciej W. Rozycki macro at linux-mips.org
Thu May 22 19:10:57 UTC 2008


On Thu, 22 May 2008, Jay Estabrook wrote:

> I hope there's someone(s) out there that might have comments to offer
> on how best to coerce the GCC compiler into generating the code WE want,
> rather than what GCC wants.

 It might be a good question to ask at a GCC list.

> To fix an unaligned access (UA) problem in "dbus",  a union pointer
> address which was not always aligned (gcc assumes they are, by default,
> it seems), I changed something like the following, which appears in the
> file: dbus-marshal-basic.c:dbus_marshal_read_basic():
> 
>     vp->byt = _dbus_get_byte(str, pos);
> to:
>     *((char*)&vp->byt) = _dbus_get_byte(str, pos);

 How's vp defined?

> Under GCC-4.1.2-23, this generated code that did the appropriate things
> to prevent a UA.
> 
> HOWEVER, when I built it under GCC-4.1.2-37, it reverted to the original
> bad code (always assuming alignment). I had to change it yet again, to
> the following:
> 
>     *((volatile char*)&vp->byt) = _dbus_get_byte(str, pos);
> 
> to get it to produce the good code again.
> 
> So, my question: is the final version (using "volatile") the only real
> way to guarantee good code in this (and similar) instance?
> 
> Or is there another more (or less) obvious way to do so?

 Well, __attribute__((packed)) used to be the usual way to ask GCC to
assume the worst when it comes to alignment while keeping the data size
intact.  It has worked for years and if it got broken at any point, then
it is a bug in GCC.

> I certainly didn't expect the behavior to change like this between
> releases and not major/minor versions... :-\

 Well, from time to time distributors add their own breakage on top of
what's there in the respective pieces of software already.

  Maciej




More information about the axp-list mailing list