Getting rid of Unaligned Accesses (UA)

Jay Estabrook Jay.Estabrook at hp.com
Thu May 22 19:13:28 UTC 2008


Maciej W. Rozycki wrote:
> 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.

Well, I tried asking one Alpha GCC guru, but never got a reply; I've
been reluctant to try them all, so I tried here first... ;-}

>> 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?

Pointer to a UNION of different datatypes, so the pointer may be asked
to point to anything from a char to a double.

>> 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.

Doesn't the "packed" normally get applied to a struct?

In this case, since it's a UNION, what would "packed' mean?

>> 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.

Understood; the GCC versions mentioned above were released during
the normal Fedora-8 ship (-23) and update (-37) cycles.

Thanks.

--Jay++




More information about the axp-list mailing list