-
Notifications
You must be signed in to change notification settings - Fork 17
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Structure layout disagreeing with C compilers #63
Comments
There is also a similar issue with unions: #include <windows.h>
#include <stdio.h>
typedef union _TEST2 {
__int64 Field64;
__int32 Fields32x3[3];
} TEST2;
int wmain(int argc, wchar_t* argv[]) {
wprintf_s(L"Total size %zd\r\n", sizeof(TEST2));
return 0;
} This C program outputs Parsing the same definition with from dissect import cstruct
cparser = cstruct.cstruct()
cparser.load("""
union TEST2 {
__int64 Field64;
__int32 Fields32x3[3];
}
""", align=True)
print('Total size', cparser.TEST2.size, 'with alignment', cparser.TEST2.alignment) So, it looks like you also forgot to align the total size in |
I don't think we should change the default for The alignment feature should be better documented though, with a few examples like the ones you demonstrated.
Agreed. We do not currently have plans or a use-case for this ourselves, though. If you would be willing to work on this then your contribution would be more than welcome! The union alignment looks like a bug that needs to be fixed. |
I noticed that
cstruct
mixes field packing rules, which makes it compute wrong offsets/sizes and disagree with C compilers about the layout of some structures.Here is an example C program to use as a staring point:
It gives the following output:
As you can see, the compiler inserted a 4-byte padding before
Field64
due to its natural alignment of 8 and adjusted the total size to 16 bytes,Now here is a program that parses the same definition using the default settings in
cstruct
:It gives a different result:
As you can see,
cstruct
did not insert a 4-byte padding beforeField64
.Loading the same definition with
align=True
yields the correct result:If I understand it right,
align=False
is supposed to act similar to wrapping the definition in#include <pshpack1.h>
/#include <poppack.h>
and should trigger compact packing of fields that ignores their natural alignment. This is not, however, the default behavior for C. I think you should consider changing the defaults to usealign=True
to make sure thatcstruct
's defaults agree with C defaults.Additionally, it might be useful to add support for different packing overrides, i.e.,
#include <pshpack1.h>
,#include <pshpack2.h>
,#include <pshpack4.h>
, etc.UPD: removed the wrong example which lead to wrong conclusions, sorry about that
The text was updated successfully, but these errors were encountered: