invalid assembly generated for packed struct containing unpacked struct

Tony Minkoff
Tue Jun 6 17:26:00 GMT 2000

I do not have the gccbug script, so I'm just sending you the text of a
report.  The class is "c++", and the category is "wrong-code."

I'm not sure whether you'll consider it a compiler bug, but here goes.  The
following code is compiled for a SPARC target with GCC 2.95.2:

    struct SBar
        long    m_l;

    struct SFoo
        SBar            m_bar1;
        short           m_s;
        SBar            m_bar2;
    } __attribute__ ((packed));

    void foo( SFoo& d, const SFoo& s )
        d.m_bar1 = s.m_bar1;
        d.m_bar2 = s.m_bar2;

    SFoo f1, f2;

    int main( void )
        foo( f1, f2 );
        return 0;

A bus error occurs inside foo().

The (compiler-generated) assignment operator for SBar uses 4-byte load and
store operations, but the second SBar object embedded in a SFoo object is
not 4-byte aligned.  Hence the assignment causes a bus error.

Perhaps the compiler ought to issue a warning when any method (including a
compiler-generated, inlined method, such as SBar::operator=() in this
example) is called with an object that is not aligned in the manner normal
for the object's type.  (In this example, SBar is typically 4-byte aligned,
and its methods are implemented based on that assumption, so calling a
method on a SBar object that is not 4-byte aligned would issue a warning.)

In principle, when the only methods on the misaligned object are inlined or
compiler-generated methods (as is the case in this example), it should be
possible to generate correct code.  (When calling code residing in another
compilation unit, of course, it would not be possible.)  In this example,
the assembly code generated for foo() is demonstrably invalid for all
inputs-- because at least one SBar object must be misaligned in any SFoo
object-- and it is, in principle, possible to generate correct code.

Please let me know if I can help by providing any further information.

More information about the Gcc-bugs mailing list