This is the mail archive of the
gcc-bugs@gcc.gnu.org
mailing list for the GCC project.
[Bug c/51628] New: __attribute__((packed)) is unsafe in some cases
- From: "Keith.S.Thompson at gmail dot com" <gcc-bugzilla at gcc dot gnu dot org>
- To: gcc-bugs at gcc dot gnu dot org
- Date: Mon, 19 Dec 2011 22:58:07 +0000
- Subject: [Bug c/51628] New: __attribute__((packed)) is unsafe in some cases
- Auto-submitted: auto-generated
http://gcc.gnu.org/bugzilla/show_bug.cgi?id=51628
Bug #: 51628
Summary: __attribute__((packed)) is unsafe in some cases
Classification: Unclassified
Product: gcc
Version: 4.5.1
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c
AssignedTo: unassigned@gcc.gnu.org
ReportedBy: Keith.S.Thompson@gmail.com
Created attachment 26147
--> http://gcc.gnu.org/bugzilla/attachment.cgi?id=26147
packed.c test case with output in a comment
I've seen this problem with gcc 4.5.1 on SPARC Solaris 9. I presume it will
affect other versions of gcc on other platforms with strict alignment
requirements (unlike x86, which supports misaligned accesses in hardware as I
understand it). I think it also applies to "#pragma pack".
The gcc extension __attribute__(packed), which applied to a struct, has the
following semantics (quoting the gcc documentation for 4.5.2):
The `packed' attribute specifies that a variable or structure field
should have the smallest possible alignment--one byte for a
variable, and one bit for a field, unless you specify a larger
value with the `aligned' attribute.
When a program accesses a misaligned member of a packed struct, the compiler
generates whatever code is necessary to read or write the correct value.
If the address of a misaligned member is stored in a pointer object,
dereferencing that pointer doesn't give the compiler an opportunity to generate
that extra code.
The attached program demonstrates the problem, and includes (as a comment) the
output I get on Ubuntu x86 (ok) and Solaris 9 SPARC (bus error).
See also
http://stackoverflow.com/questions/8568432/is-gccs-attribute-packed-pragma-pack-unsafe/
I don't believe it would be practical to fix this (though there might be some
clever solution I haven't thought of). But at least I suggest mentioning this
issue in the documentation.