destructor - utility to print C structure layout
overview
destructor provides a way to print the layout (in memory)
of a C structure.
For a similar utility that uses DWARF debugging info instead of parsing, check out pahole.
download
destructor is a single phython script:
- destructor (python script, 8.2kB)
You'll need to chmod 755 destructor, and put it somewhere in
your PATH in order to run it.
usage
To decompose a struct, just define the struct in a header file, and
run destructor header.h:
[jk@pokey ~]$ cat in.h #include <sys/stat.h> struct test { int i; struct stat stat; char c; long l; }; [jk@pokey ~]$ destructor in.h struct test { [ 0: 4] int i [ 8: 88] struct stat stat [ 96: 1] char c [ 100: 4] long l }
The output shows the starting byte and size of each member of the struct.
To explicitly show padding added by the compiler, use the
--padding option:
[jk@pokey ~]$ destructor --padding in.h
struct test {
[ 0: 4] int i
[ 4]
[ 8: 88] struct stat stat
[ 96: 1] char c
[ 3]
[ 100: 4] long l
}
You can add extra cflags after any options, and before the header argument. This can be handy if your header file needs extra include paths. In this case, we see what the structure looks like when built for a 64-bit app:
[jk@pokey ~]$ destructor --padding -- -m64 in.h
struct test {
[ 0: 4] int i
[ 4]
[ 8: 144] struct stat stat
[ 152: 1] char c
[ 7]
[ 160: 8] long l
}
You may need a -- to separate cflags from other options.
how it works
Destructor parses your struct definition, and generates C source to print the layout data of the struct. It then parses this layout data, and formats it for printing.
If you'd like to modify the destructor program, this header file: destructor-test.h (C header, 1.6kB), contains a few handy testcases for different member definitions.
limitations
The parser in desctructor is fairly simple, and so can't handle structs
with nested curly brackets (ie, it can't parse a struct that contains a
definition of another struct or union) or multiple fields defined in one
statement (ie int a,b;).