112 points · by theastrowolfe · 6y ago · 112 comments
I was recently doing that in the context of improving a language’s library support for something that had to go through the OS SDK. I don’t miss the days when that stuff was the norm.
struct Obj
{
int foo;
bool bar;
}
then we were storing those in a custom hashmap using these as keys, where the hashing function was basically hashing bits of each stored object, without any awareness of what's in the object.The bug was found when someone did something like:
void DoSomething(Obj obj)
{
if(!map.has(obj))
map.add(obj, new Whatever());
map[obj].blah(); //CRASH null pointer exception
}
I was like.....well, if there is no key "obj" in the map, we insert one....and yet literally one line after it doesn't have a value for that key??? How can this be?Well, it can be because even though the struct looks like it takes 5 bytes, in reality it's 8 bytes because it's getting padded. So a naive hashing method that just looks at bits is hashing your 5 bytes of actual data + 3 bytes of garbage, which means that two "identical" objects are very unlikely to actually produce the same hash.
C++20 now has a "hashable" concept to help with this, but it still requires the programmer to be aware of structure packing.
Because not every structure was packed, depending on your include order, some structures would be packed differently in different compilation units.
Except, for the only structures this happened for, the packed packing was coincidentally the same as the default packing ... when the program was compiled 32-bits. Attempting to switch from a 32-bit executable to a 64-bit executable resulted in mysterious segfaults as different compilation units disagreed on where different fields were.
Fun times!
E.g. if you initialize a C struct or C++ object the "usual way":
Obj obj = { };
There will most definitely be junk in the padding bytes.
There is no way in C++ to get at the padding bytes unless you're using undefined behaviour. How does the hash function work? Pointer aliasing using reinterpret_cast? Pointer aliasing using C-style casts? Typing punning through the old union switcheroo?
I'm sorry, you can easily solve this problem in K&R C from 1979.
1. Arranging fields to pack things that are shorter than 4 bytes along 4 byte boundaries.
2. Manually arranging data buffers in very specific layouts (this is less about the original post, more about a different interpretation of "packing").
Aside from what I mentioned above, more commonly you will run into this in interop scenarios, such as calling C/C++ API's from C#. Thankfully those scenarios are few and far between.
https://www.nongnu.org/txr/txr-manpage.html#N-027D075C
This is the result of empirical investigation.
The description also covers allocation of non-bitfields (paragraph 3) and the padding of the structure (paragraph 9) which require few words.
I felt that the bitfield handling is so obscure that it had to be documented in detail. If someone is to know exactly what the layout will be, the documentation can't just be "oh, it will behave like a GCC struct". Well, what will that do? That is not adequately documented anywhere.
If I have to work with bitfields in just C, I can use that as a reference to understand what the compiler will do (at least if it's anything compatible with GCC).
https://itanium-cxx-abi.github.io/cxx-abi/abi.html
This was originally developed as a joint effort to make compilers ABI-compatible on Itanium, but it's also used (by GCC, clang, Intel's proprietary compiler and others) on x86-64.
An old Hacker News comment said that it's from Intel; it's not, it was a joint effort with lots of work from CodeSourcery and Red Hat folks.
"The size and alignment of a type which is a POD for the purpose of layout is as specified by the base (C) ABI"
The links in 1.5 Base Documents are old and broken.
The details are not obvious; like the fact that a zero width bitfield like "int : 0" that appears etween two members that are not bitfields actually does something. E.g. this has size 5:
struct {
char c1;
int : 0; // zero-width bit-field must be unnamed
char c2;
};
This is basically because c1 is de-facto considered to be 8 allocated bits out of an int-wide cell, leaving 24 bits in that cell. The int : 0 sees that a field has been partially filled and so increments to the next int-wide field (according to my documented hypothesis).ISO C says (or did say in 1999) only this: "A bit-field declaration with no declarator, but only a colon and a width, indicates an unnamed bit-field.105) As a special case, a bit-field structure member with a width of 0 indicates that no further bit-field is to be packed into the unit in which the previous bit-field, if any, was placed."
No "further bit-field" is to be packed, but in this example there is neither a previous nor next bit field. So you might expect that there is no effect. In the GCC model of "all allocated so far are just bits", it has an effect.
Footnote 105 says just that "An unnamed bit-field structure member is useful for padding to conform to externally imposed layouts" which is more or less self-evident.
Oh wow; I just realized that the empty bit-field has an effect if it is the last member also:
struct { // now size 8!
char c1;
int : 0;
char c2;
int : 0;
};
This is predicted by my documentation, but it should be spelled out in an explicit remark.It's a useful feature of GCC bit-fields because you can conform to certain external layouts without having to use bit-fields at all, other than the zero-width ones.
People like you who are willing and able to do this are pillars for the whole of our field. You're a hero. :)
Example:
Word : constant := 4; -- storage element is byte, 4 bytes per word
type State is (A,M,W,P); type Mode is (Fix, Dec, Exp, Signif);
type Byte_Mask is array (0..7) of Boolean; type State_Mask is array (State) of Boolean; type Mode_Mask is array (Mode) of Boolean;
type Program_Status_Word is record System_Mask : Byte_Mask;
Protection_Key : Integer range 0 .. 3;
Machine_State : State_Mask;
Interrupt_Cause : Interruption_Code;
Ilc : Integer range 0 .. 3;
Cc : Integer range 0 .. 3;
Program_Mask : Mode_Mask;
Inst_Address : Address;
end record;
for Program_Status_Word use
record
System_Mask at 0*Word range 0 .. 7;
Protection_Key at 0*Word range 10 .. 11; -- bits 8,9 unused
Machine_State at 0*Word range 12 .. 15;
Interrupt_Cause at 0*Word range 16 .. 31;
Ilc at 1*Word range 0 .. 1; -- second word
Cc at 1*Word range 2 .. 3;
Program_Mask at 1*Word range 4 .. 7;
Inst_Address at 1*Word range 8 .. 31;
end record;
for Program_Status_Word'Size use 8*System.Storage_Unit;
for Program_Status_Word'Alignment use 8;
More info:
https://www.adaic.org/resources/add_content/standards/05aarm...I keep hoping the Zig developer will do a deep dive on Ada and bring over more of this kind of precise control. A language where I have this kind of control over layout, but can still spell `end record;` as `}`, is ideal for some projects I have in mind.
I’m not sure why “use a different language” is such a common reply to any language specific discussion.
People will also do silly things like casting between types in ways that rely on similarly written structures having similar memory layouts. So C is probably a bad language to turn this on by default in
IMHO there are just as many arguments for automatic reordering as there are against it (e.g. creating structs that are layed over memory mapped IO registers, or just optimizing a struct for certain cache-efficient access patterns). In my opinion it's sufficient to know about the existance of alignment-padding, and how to work around it if needed (for instance reordering the struct members manually, or using #pragma pack)
People do quite often rely on the first struct element being at the start of the struct. Memcpy:ing directly between structs and network/disk is also common, but naughty. Both struct padding and endianness already break that.
Typically if I define a 8bit as the first element, I need to be certain those 8bits are first even if that wastes three more bytes to align on the next variable.
It seems like something like that could be useful rather than making programmers try to order their structs by hand.
There is almost never a difference to the user what order things are structured. Although to be fair this does get tricky with unions of structure over structure.
I always assumed that in C++, the memory layout could change a lot between compilers (the location of the pointer to the vtable for example). Do you know if it's true, and if the layout do change, could you give an example?
Usually, but not always. In most cases there is one efficient way to pack the structure and still maintain member alignment, but there's not requirement that the amount of padding looks like this.
> I always assumed that in C++, the memory layout could change a lot between compilers (the location of the pointer to the vtable for example). Do you know if it's true, and if the layout do change, could you give an example?
Yes, once you have a non-POD type the memory layout can be fairly arbitrary as you cannot really inspect it and compilers are free to lay it out as they wish.
However this isn't universally true. Some platforms might not have a well defined C ABI.
If you need to squeeze out all padding, use compiler directives like '#pragma pack', but be aware of the performance implications.