Conver...ary::C(3pm)
๐ NAME ๐
so like, Convert::Binary::C(3pm) โ straight from the User Contributed Perl Documentation crew ๐ซถ โ and it does Binary Data Conversion using C Types. that's the whole vibe, bestie โจ
โจ SYNOPSIS โจ
๐ธ Simple
use Convert::Binary::C;
#---------------------------------------------
# Create a new object and parse embedded code
#---------------------------------------------
my $c = Convert::Binary::C->new->parse(<<ENDC);
enum Month { JAN, FEB, MAR, APR, MAY, JUN,
JUL, AUG, SEP, OCT, NOV, DEC };
struct Date {
int year;
enum Month month;
int day;
};
ENDC
#-----------------------------------------------
# Pack Perl data structure into a binary string
#-----------------------------------------------
my $date = { year => 2002, month => 'DEC', day => 24 };
my $packed = $c->pack('Date', $date);
๐ซ Advanced
use Convert::Binary::C;
use Data::Dumper;
#---------------------
# Create a new object
#---------------------
my $c = Convert::Binary::C->new(ByteOrder => 'BigEndian');
#---------------------------------------------------
# Add include paths and global preprocessor defines
#---------------------------------------------------
$c->Include('/usr/lib/gcc/x86_64-pc-linux-gnu/10.2.0/include',
'/usr/lib/gcc/x86_64-pc-linux-gnu/10.2.0/include-fixed',
'/usr/include')
->Define(qw( __USE_POSIX __USE_ISOC99=1 ));
#----------------------------------
# Parse the 'time.h' header file
#----------------------------------
$c->parse_file('time.h');
#---------------------------------------
# See which files the object depends on
#---------------------------------------
print Dumper([$c->dependencies]);
#-----------------------------------------------------------
# See if struct timespec is defined and dump its definition
#-----------------------------------------------------------
if ($c->def('struct timespec')) {
print Dumper($c->struct('timespec'));
}
#-------------------------------
# Create some binary dummy data
#-------------------------------
my $data = "binary_test_string";
#--------------------------------------------------------
# Unpack $data according to 'struct timespec' definition
#--------------------------------------------------------
if (length($data) >= $c->sizeof('timespec')) {
my $perl = $c->unpack('timespec', $data);
print Dumper($perl);
}
#--------------------------------------------------------
# See which member lies at offset 5 of 'struct timespec'
#--------------------------------------------------------
my $member = $c->member('timespec', 5);
print "member('timespec', 5) = '$member'\n";
๐ DESCRIPTION ๐
k so Convert::Binary::C is a preprocessor and a parser for C type definitions ๐
. it's super configurable, it handles arbitrarily complex data structures, no cap. its object-oriented interface has pack and unpack methods that act as replacements for Perl's own pack and unpack โ and they let you use actual C types instead of a string representation of the data structure when you're converting binary data back and forth into Perl's complex data structures ๐ฆ
fr fr, what Convert::Binary::C does is not very different from what a C compiler does โ except it doesn't compile the source into an object file or an executable. it just parses the code and lets Perl use the enumerations, structs, unions and typedefs that got defined inside your C source for binary data conversion, kinda like Perl's pack and unpack ๐
and on top of that? the module hands you a lot of convenience methods to pull information about the C types it already parsed ๐
๐ง Background and History ๐ง
okay storytime, this is genuinely cute โ it's the author's origin arc ๐
in late 2000, they wrote a real-time debugging interface for an embedded medical device that let them send data out of that device over its integrated Ethernet adapter. the interface was printf()-like, so you could easily send out strings or numbers. but you could also send out what they called arbitrary data, which was intended for arbitrary blocks of the device's memory โจ
another part of this real-time debugger was a Perl application running on their workstation that gathered all the messages sent out from the embedded device. it printed all the strings and numbers, and hex-dumped the arbitrary data. but manually parsing a couple of 300 byte hex-dumps of a complex C structure is not only frustrating โ it's also error-prone and time consuming ๐ญ
using unpack to retrieve the contents of a C structure works fine for small structures and if you don't have to deal with struct member alignment. but otherwise? maintaining that code can be as awful as deciphering hex-dumps ๐
since they didn't find anything on the CPAN to solve the problem, they wrote a little module that translated simple C structs into unpack strings. it worked! but it was slow. and since it couldn't deal with struct member alignment, they soon found themselves adding padding bytes everywhere. so again โ two sources to maintain, and changing one forced touching the other ๐
all in all, this little module made the task a bit easier, but it was far from what they were thinking of:
- A module that could directly use the source they've been coding for the embedded device, without any modifications.
- A module that could be configured to match the properties of the different compilers and target platforms they were using.
- A module that was fast enough to decode a great amount of binary data even on their slow workstation.
they didn't know how to pull these off until they read something about XS. at least it seemed like it could solve the performance problems. BUT โ writing a C parser in C isn't easier than writing one in Perl, and writing a C preprocessor from scratch is even worse ๐ญ
fortunately enough, after a few weeks of searching they found both: a lean, open-source C preprocessor library, and a reusable YACC grammar for ANSI-C ๐ that was the beginning of the development of Convert::Binary::C in late 2001 ๐
now they're successfully using the module in their embedded environment since long before it appeared on CPAN. from their point of view, it's exactly what they had in mind: it's fast, flexible, easy to use and portable. and it doesn't require external programs or other Perl modules ๐
๐ About this document ๐
this document describes how to use Convert::Binary::C. a lot of different features get presented, and the example code sometimes uses Perl's more advanced language elements. if your experience with Perl is rather limited, you should know how to use Perl's very good documentation system ๐
to look up one of the manpages, use the perldoc command. for example,
perldoc perl
will show you Perl's main manpage. to look up a specific Perl function, use perldoc -f:
perldoc -f map
gives you more information about the map function. you can also search the FAQ using perldoc -q:
perldoc -q array
will give you everything you ever wanted to know about Perl arrays. but now, let's go on with some real stuff! ๐
๐ Why use Convert::Binary::C? ๐
say you want to pack (or unpack) data according to the following C structure:
struct foo {
char ary[3];
unsigned short baz;
int bar;
};
you could of course use Perl's pack and unpack functions:
@ary = (1, 2, 3);
$baz = 40000;
$bar = -4711;
$binary = pack 'c3 S i', @ary, $baz, $bar;
but this implies that the struct members are byte aligned. if they were long aligned (which is the default for most compilers), you'd have to write
$binary = pack 'c3 x S x2 i', @ary, $baz, $bar;
which doesn't really increase readability ๐
now imagine you need to pack the data for a completely different architecture with different byte order. you'd look into the pack manpage again and perhaps come up with this:
$binary = pack 'c3 x n x2 N', @ary, $baz, $bar;
however, if you try to unpack $foo again, your signed values have turned into unsigned ones ๐
all this can still be managed with Perl. but imagine your structures get more complex? imagine you need to support different platforms? imagine you need to make changes to the structures? you'll not only have to change the C source but also dozens of pack strings in your Perl code. this is no fun. and Perl should be fun ๐ค
now, wouldn't it be great if you could just read in the C source you've already written and use all the types defined there for packing and unpacking? that's what Convert::Binary::C does โจ
๐ Creating a Convert::Binary::C object ๐
to use Convert::Binary::C just say
use Convert::Binary::C;
to load the module. its interface is completely object oriented, so it doesn't export any functions ๐ซถ
next, you need to create a new Convert::Binary::C object. this can be done by either
$c = Convert::Binary::C->new;
or
$c = Convert::Binary::C->new;
(yes bestie, both of them say the same thing โ that's what it says, i'm just the messenger ๐)
you can optionally pass configuration options to the constructor as described in the next section ๐ธ
๐ Configuring the object ๐
to configure a Convert::Binary::C object, you can either call the configure method or directly pass the configuration options to the constructor. if you want to change byte order and alignment, you can use
$c->configure(ByteOrder => 'LittleEndian',
Alignment => 2);
or you can change the construction code to
$c = Convert::Binary::C->new(ByteOrder => 'LittleEndian',
Alignment => 2);
either way, the object will now know that it should use little endian (Intel) byte order and 2-byte struct member alignment for packing and unpacking ๐
alternatively, you can use the option names as names of methods to configure the object, like:
$c->ByteOrder('LittleEndian');
you can also retrieve information about the current configuration of a Convert::Binary::C object. for details, see the section about the configure method ๐
๐ฆ Parsing C code ๐ฆ
Convert::Binary::C allows two ways of parsing C source. either by parsing external C header or C source files:
$c->parse_file('header.h');
or by parsing C code embedded in your script:
$c->parse(<<'CCODE');
struct foo {
char ary[3];
unsigned short baz;
int bar;
};
CCODE
now the object $c will know everything about struct foo ๐ the example above uses a so-called here-document. it allows one to easily embed multi-line strings in your code. you can find more about here-documents in perldata or perlop ๐
since the parse and parse_file methods throw an exception when a parse error occurs, you usually want to catch these in an eval block:
eval { $c->parse_file('header.h') };
if ($@) {
# handle error appropriately
}
Perl's special $@ variable is gonna be an empty string when everything went fine (and bestie, an empty string is a false value in boolean context, so it fails the vibe check on purpose ๐
), or an error string if something went wrong. Success = falsy, failure = the tea. ๐ซ
And okay, another lil feature that I am obsessed with: parse and parse_file both return a reference to their object on success, exactly like configure does when you're configuring the object. So you can chain like the main character you are:
my $c = eval {
Convert::Binary::C->new(Include => ['/usr/include'])
->parse_file('header.h')
};
if ($@) {
# handle error appropriately
}
๐ Packing and unpacking ๐
Convert::Binary::C has two methods, pack and unpack, and they act similar to the functions of the same denominator in Perl. To do the packing we described up above, you'd write:
$data = {
ary => [1, 2, 3],
baz => 40000,
bar => -4711,
};
$binary = $c->pack('foo', $data);
Unpacking works exactly the same way โ the only glow-up is that the unpack method takes a byte string as its input and hands you back a reference to a (possibly very complex) Perl data structure. โจ
$binary = get_data_from_memory();
$data = $c->unpack('foo', $binary);
Now you can easily access all of the values, no cap:
print "foo.ary[1] = $data->{ary}[1]\n";
Or, even more conveniently, use the Data::Dumper module:
use Data::Dumper;
print Dumper($data);
And the output would look something like this:
$VAR1 = {
'ary' => [
42,
48,
100
],
'baz' => 5000,
'bar' => -271
};
๐ง Preprocessor configuration ๐ง
Convert::Binary::C uses Thomas Pornin's ucpp as an internal C preprocessor. It's compliant to ISO-C99, so you literally do not have to worry about using even weird preprocessor constructs in your code. She ate. ๐ฅ
If your C source contains includes or depends upon preprocessor defines, you may need to configure the internal preprocessor. That's what the Include and Define configuration options are for, bestie:
$c->configure(Include => ['/usr/include',
'/home/mhx/include'],
Define => [qw( NDEBUG FOO=42 )]);
If your code uses system includes, it is most likely that you will need to define the symbols that are usually defined by the compiler. ๐ซถ
On some operating systems, the system includes require the preprocessor to predefine a certain set of assertions. Assertions are supported by ucpp, and you can define them either in the source code using #assert, or as a property of the Convert::Binary::C object using Assert:
$c->configure(Assert => ['predicate(answer)']);
Information about defined macros can be retrieved from the preprocessor, but only as long as its configuration isn't changed. The preprocessor gets implicitly reset if you change one of the following configuration options, so heads up:
IncludeDefineAssertHasCPPCommentsHasMacroVAARGS
๐ Supported pragma directives ๐
Convert::Binary::C supports the pack pragma to locally override struct member alignment. The supported syntax is as follows:
#pragma pack( ALIGN )
Sets the new alignment to ALIGN. If ALIGN is 0, resets the alignment to its original value.
#pragma pack
Resets the alignment to its original value.
#pragma pack( push, ALIGN )
Saves the current alignment on a stack and sets the new alignment to ALIGN. If ALIGN is 0, sets the alignment to the default alignment.
#pragma pack( pop )
Restores the alignment to the last value saved on the stack.
/* Example assumes sizeof( short ) == 2, sizeof( long ) == 4. */
#pragma pack(1)
struct nopad {
char a; /* no padding bytes between 'a' and 'b' */
long b;
};
#pragma pack /* reset to "native" alignment */
#pragma pack( push, 2 )
struct pad {
char a; /* one padding byte between 'a' and 'b' */
long b;
#pragma pack( push, 1 )
struct {
char c; /* no padding between 'c' and 'd' */
short d;
} e; /* sizeof( e ) == 3 */
#pragma pack( pop ); /* back to pack( 2 ) */
long f; /* one padding byte between 'e' and 'f' */
};
#pragma pack( pop ); /* back to "native" */
The pack pragma as it is currently implemented only affects the maximum struct member alignment. There are compilers that also allow one to specify the minimum struct member alignment. This is not supported by Convert::Binary::C. ๐
๐ Automatic configuration using ccconfig ๐
As there are over 20 different configuration options, setting all of them correctly can be a lengthy and tedious task. Not the slay we're looking for. ๐ญ
The ccconfig script, which is bundled with this module, aims at automatically determining the correct compiler configuration by testing the compiler executable. It works for both, native and cross compilers. Iconic behaviour, honestly. ๐
โญ UNDERSTANDING TYPES โญ
This section covers one of the fundamental features of Convert::Binary::C. It's how type expressions โ referred to as TYPEs in the method reference โ are handled by the module. Pay attention bestie, this is the good part. ๐
Many of the methods, namely pack, unpack, sizeof, typeof, member, offsetof, def, initializer and tag, are passed a TYPE to operate on as their first argument.
๐ Standard Types ๐
These are trivial, fr fr. Standard types are simply enum names, struct names, union names, or typedefs. Almost every method that wants a TYPE will accept a standard type.
For enums, structs and unions, the prefixes enum, struct and union are optional. However, if a typedef with the same name exists, like in
struct foo {
int bar;
};
typedef int foo;
you will have to use the prefix to distinguish between the struct and the typedef. Otherwise, a typedef is always given preference. Periodt.
๐ธ Basic Types ๐ธ
Basic types, or atomic types, are int or char, for example. It's possible to use these basic types without having parsed any code. You can simply do
$c = Convert::Binary::C->new;
$size = $c->sizeof('unsigned long');
$data = $c->pack('short int', 42);
Even though the above works fine, it is not possible to define more complex types on the fly, so
$size = $c->sizeof('struct { int a, b; }');
will result in an error. ๐
Basic types are not supported by all methods. For example, it makes no sense to use member or offsetof on a basic type. Using typeof isn't very useful, but it is supported. Lowkey a waste of time, highkey valid.
๐ฆ Member Expressions ๐ฆ
This is by far the most complex part, depending on the complexity of your data structures. Any standard type that defines a compound or an array may be followed by a member expression to select only a certain part of the data type. Say you have parsed the following C code:
struct foo {
long type;
struct {
short x, y;
} array[20];
};
typedef struct foo matrix[8][8];
You may want to know the size of the array member of struct foo. That's quite easy:
print $c->sizeof('foo.array'), " bytes";
will print
80 bytes
depending of course on the ShortSize you configured.
If you wanted to unpack only a single column of matrix, that's easy as well (and of course it doesn't matter which index you use):
$column = $c->unpack('matrix[2]', $data);
Just like in C, it is possible to use out-of-bounds array indices. This means that, for example, despite array being declared to have 20 elements, the following code
$size = $c->sizeof('foo.array[4711]');
$offset = $c->offsetof('foo', 'array[-13]');
is perfectly valid and will result in:
$size = 4
$offset = -44
Member expressions can be arbitrarily complex:
$type = $c->typeof('matrix[2][3].array[7].y');
print "the type is $type";
will, for example, print
the type is short
Member expressions are also used as the second argument to offsetof.
โจ Offsets โจ
Members returned by the member method have an optional offset suffix to indicate that the given offset doesn't point to the start of that member. For example,
$member = $c->member('matrix', 1431);
print $member;
will print
[2][0].array[3].y+1
If you would use this as a member expression, like in
$size = $c->sizeof("matrix $member");
the offset suffix will simply be ignored. Actually, it will be ignored for all methods if it's used in the first argument.
When used in the second argument to offsetof, it will usually do what you mean, i.e. the offset suffix, if present, will be considered when determining the offset. This behaviour ensures that
$member = $c->member('foo', 43);
$offset = $c->offsetof('foo', $member);
print "'$member' is located at offset $offset of struct foo";
will always correctly set $offset:
'.array[8].y+1' is located at offset 43 of struct foo
If this is not what you mean, e.g. because you want to know the offset where the member returned by member starts, you just have to remove the suffix:
$member =~ s/\+\d+$//;
$offset = $c->offsetof('foo', $member);
print "'$member' starts at offset $offset of struct foo";
This would then print:
'.array[8].y' starts at offset 42 of struct foo
๐ USING TAGS ๐
In a nutshell, tags are properties that you can attach to types. Cute lil stickers for your structs, basically. ๐
You can add tags to types using the tag method, and remove them using tag or untag, for example:
# Attach 'Format' and 'Hooks' tags
$c->tag('type', Format => 'String', Hooks => { pack => \&rout });
$c->untag('type', 'Format'); # Remove only 'Format' tag
$c->untag('type'); # Remove all tags
You can also use tag to see which tags are attached to a type, for example:
$tags = $c->tag('type');
This would give you:
$tags = {
'Hooks' => {
'pack' => \&rout
},
'Format' => 'String'
};
Currently, there are only a couple of different tags that influence the way data is packed and unpacked. There are probably more tags to come in the future. Stay tuned bestie. ๐
๐ The Format Tag ๐
One of the tags currently available is the Format tag. Using this tag, you can tell a Convert::Binary::C object to pack and unpack a certain data type in a special way.
For example, if you have a (fixed length) string type
typedef char str_type[40];
this type would, by default, be unpacked as an array of chars. That's because it is only an array of chars, and Convert::Binary::C doesn't know it is actually used as a string.
But bestie, you can just tell Convert::Binary::C that str_type is a C string with the Format tag:
$c->tag('str_type', Format => 'String');
And then unpack (and obviously pack too) will treat that binary data like a null-terminated C string, periodt:
$binary = "Hello World!\n\0 this is just some dummy data";
$hello = $c->unpack('str_type', $binary);
print $hello;
Which would print:
Hello World!
And of course it works the other way around too:
use Data::Hexdumper;
$binary = $c->pack('str_type', "Just another C::B::C hacker");
print hexdump(data => $binary);
Would print:
0x0000 : 4A 75 73 74 20 61 6E 6F 74 68 65 72 20 43 3A 3A : Just.another.C::
0x0010 : 42 3A 3A 43 20 68 61 63 6B 65 72 00 00 00 00 00 : B::C.hacker.....
0x0020 : 00 00 00 00 00 00 00 00 : ........
Now, if you want Convert::Binary::C to not interpret the binary data at all, you can set the Format tag to Binary. At first glance this might seem useless, because pack and unpack would just pass through the unmodified binary data. But no cap, it's actually useful because you can tag not only whole types, but also compound members. For example:
$c->parse(<<ENDC);
struct packet {
unsigned short header;
unsigned short flags;
unsigned char payload[28];
};
ENDC
$c->tag('packet.payload', Format => 'Binary');
Which would let you write:
read FILE, $payload, $c->sizeof('packet.payload');
$packet = {
header => 4711,
flags => 0xf00f,
payload => $payload,
};
$binary = $c->pack('packet', $packet);
print hexdump(data => $binary);
And this would print something like:
0x0000 : 12 67 F0 0F 6E 6F 0A 6E 6F 0A 6E 6F 0A 6E 6F 0A : .g..no.no.no.no.
0x0010 : 6E 6F 0A 6E 6F 0A 6E 6F 0A 6E 6F 0A 6E 6F 0A 6E : no.no.no.no.no.n
For obvious reasons, you can't attach a Format tag to bitfield members. Trying to do so will make the tag method throw an exception. So don't do it. ๐
๐ The ByteOrder Tag ๐
The ByteOrder tag lets you override the byte order of certain types or members. The implementation of this tag is considered experimental and may be subject to changes in the future. So keep that in mind, bestie.
Usually it doesn't make much sense to override the byte order, but there may be applications where a sub-structure is packed in a different byte order than the surrounding structure.
Take, for example, the following code:
$c = Convert::Binary::C->new(ByteOrder => 'BigEndian',
OrderMembers => 1);
$c->parse(<<'ENDC');
typedef unsigned short u_16;
struct coords_3d {
int x, y, z;
};
struct coords_msg {
u_16 header;
u_16 length;
struct coords_3d coords;
};
ENDC
Assume that while coords_msg is big endian, the embedded coordinates coords_3d are stored in little endian format for some reason. In C, you'll have to handle this manually.
But using Convert::Binary::C, you can simply attach a ByteOrder tag to either the coords_3d structure or to the coords member of the coords_msg structure. Both will work in this case. The only difference is that if you tag the coords member, coords_3d will only be treated as little endian if you pack or unpack the coords_msg structure. (BTW, you could also tag all members of coords_3d individually, but that would be inefficient.)
So, let's attach the ByteOrder tag to the coords member:
$c->tag('coords_msg.coords', ByteOrder => 'LittleEndian');
Assume the following binary message:
0x0000 : 00 2A 00 0C FF FF FF FF 02 00 00 00 2A 00 00 00 : .*..........*...
If you unpack this message...
$msg = $c->unpack('coords_msg', $binary);
...you will get the following data structure:
$msg = {
'header' => 42,
'length' => 12,
'coords' => {
'x' => -1,
'y' => 2,
'z' => 42
}
};
Without the ByteOrder tag, you would get:
$msg = {
'header' => 42,
'length' => 12,
'coords' => {
'x' => -1,
'y' => 33554432,
'z' => 704643072
}
};
The ByteOrder tag is a recursive tag, i.e. it applies to all children of the tagged object recursively. Of course, it's also possible to override a ByteOrder tag by attaching another ByteOrder tag to a child type. Confused? Here's an example. In addition to tagging the coords member as little endian, we now tag coords_3d.y as big endian:
$c->tag('coords_3d.y', ByteOrder => 'BigEndian');
$msg = $c->unpack('coords_msg', $binary);
This will return the following data structure:
$msg = {
'header' => 42,
'length' => 12,
'coords' => {
'x' => -1,
'y' => 33554432,
'z' => 42
}
};
Note that if you tag both a type and a member of that type within a compound, the tag attached to the type itself has higher precedence. Using the example above, if you would attach a ByteOrder tag to both coords_msg.coords and coords_3d, the tag attached to coords_3d would always win.
Also note that the ByteOrder tag might not work as expected along with bitfields, which is why the implementation is considered experimental. Bitfields are currently not affected by the ByteOrder tag at all. This is because the byte order would affect the bitfield layout, and a consistent implementation supporting multiple layouts of the same struct would be quite bulky and probably slow down the whole module.
If you really need the correct behaviour, you can use the following trick:
$le = Convert::Binary::C->new(ByteOrder => 'LittleEndian');
$le->parse(<<'ENDC');
typedef unsigned short u_16;
typedef unsigned long u_32;
struct message {
u_16 header;
u_16 length;
struct {
u_32 a;
u_32 b;
u_32 c : 7;
u_32 d : 5;
u_32 e : 20;
} data;
};
ENDC
$be = $le->clone->ByteOrder('BigEndian');
$le->tag('message.data', Format => 'Binary', Hooks => {
unpack => sub { $be->unpack('message.data', @_) },
pack => sub { $be->pack('message.data', @_) },
});
$msg = $le->unpack('message', $binary);
This uses the Format and Hooks tags along with a big endian clone of the original little endian object. It attaches hooks to the little endian object and in the hooks it uses the big endian object to pack and unpack the binary data. So clever. ๐ง
๐ธ The Dimension Tag ๐ธ
The Dimension tag allows you to override the declared dimension of an array for packing or unpacking data. The implementation of this tag is considered very experimental and will definitely change in a future release. So don't get too attached, bestie.
That being said, the Dimension tag is primarily useful to support variable length arrays. Usually, you have to write the following code for such a variable length array in C:
struct c_message
{
unsigned count;
char data[1];
};
So, because you cannot declare an empty array, you declare an array with a single element. If you have a ISO-C99 compliant compiler, you can write this code instead:
struct c99_message
{
unsigned count;
char data[];
};
This explicitly tells the compiler that data is a flexible array member. Convert::Binary::C already uses this information to handle flexible array members in a special way.
As you can see in the following example, the two types are treated differently:
$data = pack 'NC*', 3, 1..8;
$uc = $c->unpack('c_message', $data);
$uc99 = $c->unpack('c99_message', $data);
This will result in:
$uc = {'count' => 3,'data' => [1]};
$uc99 = {'count' => 3,'data' => [1,2,3,4,5,6,7,8]};
However, only few compilers support ISO-C99, and you probably don't want to change your existing code only to get some extra features when using Convert::Binary::C.
So it is possible to attach a tag to the data member of the c_message struct that tells Convert::Binary::C to treat the array as if it were flexible:
$c->tag('c_message.data', Dimension => '*');
Now both c_message and c99_message will behave exactly the same when using pack or unpack. Repeating the above code:
$uc = $c->unpack('c_message', $data);
This will result in:
$uc = {'count' => 3,'data' => [1,2,3,4,5,6,7,8]};
But there's more you can do. Even though it probably doesn't make much sense, you can tag a fixed dimension to an array:
$c->tag('c_message.data', Dimension => '5');
This will obviously result in:
$uc = {'count' => 3,'data' => [1,2,3,4,5]};
A more useful way to use the Dimension tag is to set it to the name of a member in the same compound:
$c->tag('c_message.data', Dimension => 'count');
Convert::Binary::C will now use the value of that member to determine the size of the array, so unpacking will result in:
$uc = {'count' => 3,'data' => [1,2,3]};
Of course, you can also tag flexible array members. And yes, it's also possible to use more complex member expressions:
$c->parse(<<ENDC);
struct msg_header
{
unsigned len[2];
};
struct more_complex
{
struct msg_header hdr;
char data[];
};
ENDC
$data = pack 'NNC*', 42, 7, 1 .. 10;
$c->tag('more_complex.data', Dimension => 'hdr.len[1]');
$u = $c->unpack('more_complex', $data);
The result will be:
$u = {
'hdr' => {
'len' => [
42,
7
]
},
'data' => [
1,
2,
3,
4,
5,
6,
7
]
};
By the way, it's also possible to tag arrays that are not embedded inside a compound:
$c->parse(<<ENDC);
typedef unsigned short short_array[];
ENDC
$c->tag('short_array', Dimension => '5');
$u = $c->unpack('short_array', $data);
Resulting in:
$u = [0,42,0,7,258];
The final and most powerful way to define a Dimension tag is to pass it a subroutine reference. The referenced subroutine can execute whatever code is necessary to determine the size of the tagged array:
sub get_size
{
my $m = shift;
return $m->{hdr}{len}[0] / $m->{hdr}{len}[1];
}
$c->tag('more_complex.data', Dimension => \&get_size);
$u = $c->unpack('more_complex', $data);
As you can probably guess from the code above, the subroutine is being passed a reference to a hash that stores the already unpacked part of the compound that's embedding the tagged array. It's giving this:
$u = {
'hdr' => {
'len' => [
42,
7
]
},
'data' => [
1,
2,
3,
4,
5,
6
]
};
bestie, you can also pass custom arguments to the subroutines by using the arg method. this is similar to the functionality offered by the Hooks tag.
of course, all that also works for the pack method as well.
however, the current implementation has at least one shortcoming, which is why it's experimental: the Dimension tag doesn't impact compound layout. this means that while you can alter the size of an array in the middle of a compound, the offset of the members after that array won't be impacted. I'd rather like to see the layout adapt dynamically, so this is what I'm hoping to implement in the future. ๐
โจ The Hooks Tag โจ
Hooks are a special kind of tag that can be extremely useful. like, they're basically the main character of tags.
Using hooks, you can easily override the way pack and unpack handle data using your own subroutines. if you define hooks for a certain data type, each time this data type is processed the corresponding hook will be called to allow you to modify that data. it's giving control freak, but in a good way.
โจ Basic Hooks โจ
Here's an example. let's assume the following C code has been parsed:
typedef unsigned int u_32;
typedef u_32 ProtoId;
typedef ProtoId MyProtoId;
struct MsgHeader {
MyProtoId id;
u_32 len;
};
struct String {
u_32 len;
char buf[];
};
You could now use the types above and, for example, unpack binary data representing a MsgHeader like this:
$msg_header = $c->unpack('MsgHeader', $data);
This would give you:
$msg_header = {
'id' => 42,
'len' => 13
};
Instead of dealing with ProtoId's as integers, you would rather like to have them as clear text. you could provide subroutines to convert between clear text and integers:
%proto = (
CATS => 1,
DOGS => 42,
HEDGEHOGS => 4711,
);
%rproto = reverse %proto;
sub ProtoId_unpack {
$rproto{$_[0]} || 'unknown protocol'
}
sub ProtoId_pack {
$proto{$_[0]} or die 'unknown protocol'
}
You can now register these subroutines by attaching a Hooks tag to ProtoId using the tag method:
$c->tag('ProtoId', Hooks => { pack => \&ProtoId_pack,
unpack => \&ProtoId_unpack });
Doing exactly the same unpack on MsgHeader again would now return:
$msg_header = {
'id' => 'DOGS',
'len' => 13
};
Actually, if you don't need the reverse operation, you don't even have to register a pack hook. or, even better, you can have a more intelligent unpack hook that creates a dual-typed variable:
use Scalar::Util qw(dualvar);
sub ProtoId_unpack2 {
dualvar $_[0], $rproto{$_[0]} || 'unknown protocol'
}
$c->tag('ProtoId', Hooks => { unpack => \&ProtoId_unpack2 });
$msg_header = $c->unpack('MsgHeader', $data);
Just as before, this would print
$msg_header = {
'id' => 'DOGS',
'len' => 13
};
but without requiring a pack hook for packing, at least as long as you keep the variable dual-typed.
Hooks are usually called with exactly one argument, which is the data that should be processed (see Advanced Hooks for details on how to customize hook arguments). they are called in scalar context and expected to return the processed data.
To get rid of registered hooks, you can either undefine only certain hooks
$c->tag('ProtoId', Hooks => { pack => undef });
or all hooks:
$c->tag('ProtoId', Hooks => undef);
Of course, hooks are not restricted to handling integer values. you could just as well attach hooks for the String struct from the code above. a useful example would be to have these hooks:
sub string_unpack {
my $s = shift;
pack "c$s->{len}", @{$s->{buf}};
}
sub string_pack {
my $s = shift;
return {
len => length $s,
buf => [ unpack 'c*', $s ],
}
}
(Don't be confused by the fact that the unpack hook uses pack and the pack hook uses unpack. and also see Advanced Hooks for a more clever approach.)
While you would normally get the following output when unpacking a String
$string = {
'len' => 12,
'buf' => [
72,
101,
108,
108,
111,
32,
87,
111,
114,
108,
100,
33
]
};
you could just register the hooks using
$c->tag('String', Hooks => { pack => \&string_pack,
unpack => \&string_unpack });
and you would get a nice human-readable Perl string:
$string = 'Hello World!';
Packing a string turns out to be just as easy:
use Data::Hexdumper;
$data = $c->pack('String', 'Just another Perl hacker,');
print hexdump(data => $data);
This would print:
0x0000 : 00 00 00 19 4A 75 73 74 20 61 6E 6F 74 68 65 72 : ....Just.another
0x0010 : 20 50 65 72 6C 20 68 61 63 6B 65 72 2C : .Perl.hacker,
If you want to find out if or which hooks are registered for a certain type, you can also use the tag method:
$hooks = $c->tag('String', 'Hooks');
This would return:
$hooks = {
'unpack' => \&string_unpack,
'pack' => \&string_pack
};
๐ง Advanced Hooks ๐ง
It is also possible to combine hooks with using the Format tag. this can be useful if you know better than Convert::Binary::C how to interpret the binary data. in the previous section, we've handled this type
struct String {
u_32 len;
char buf[];
};
with the following hooks:
sub string_unpack {
my $s = shift;
pack "c$s->{len}", @{$s->{buf}};
}
sub string_pack {
my $s = shift;
return {
len => length $s,
buf => [ unpack 'c*', $s ],
}
}
$c->tag('String', Hooks => { pack => \&string_pack,
unpack => \&string_unpack });
As you can see in the hook code, buf is expected to be an array of characters. for the unpack case Convert::Binary::C first turns the binary data into a Perl array, and then the hook packs it back into a string. the intermediate array creation and destruction is completely useless. same thing, of course, for the pack case.
Here's a clever way to handle this. just tag buf as binary
$c->tag('String.buf', Format => 'Binary');
and use the following hooks instead:
sub string_unpack2 {
my $s = shift;
substr $s->{buf}, 0, $s->{len};
}
sub string_pack2 {
my $s = shift;
return {
len => length $s,
buf => $s,
}
}
$c->tag('String', Hooks => { pack => \&string_pack2,
unpack => \&string_unpack2 });
This will be exactly equivalent to the old code, but faster and probably even much easier to understand.
But hooks are even more powerful. you can customize the arguments that are passed to your hooks and you can use arg to pass certain special arguments, such as the name of the type that is currently being processed by the hook.
The following example shows how it is easily possible to peek into the perl internals using hooks.
use Config;
$c = Convert::Binary::C->new(%CC, OrderMembers => 1);
$c->Include(["$Config{archlib}/CORE", @{$c->Include}]);
$c->parse(<<ENDC);
#include "EXTERN.h"
#include "perl.h"
ENDC
$c->tag($_, Hooks => { unpack_ptr => [\&unpack_ptr,
$c->arg(qw(SELF TYPE DATA))] })
for qw( XPVAV XPVHV );
First, we add the perl core include path and parse perl.h. Then, we add an unpack_ptr hook for a couple of the internal data types.
The unpack_ptr and pack_ptr hooks are called whenever a pointer to a certain data structure is processed. this is by far the most experimental part of the hooks feature, as this includes any kind of pointer. there's no way for the hook to know the difference between a plain pointer, or a pointer to a pointer, or a pointer to an array (this is because the difference doesn't matter anywhere else in Convert::Binary::C).
But the hook above makes use of another very interesting feature: it uses arg to pass special arguments to the hook subroutine. usually, the hook subroutine is simply passed a single data argument. but using the above definition, it'll get a reference to the calling object (SELF), the name of the type being processed (TYPE) and the data (DATA).
But how does our hook look like?
sub unpack_ptr {
my($self, $type, $ptr) = @_;
$ptr or return '<NULL>';
my $size = $self->sizeof($type);
$self->unpack($type, unpack("P$size", pack('Q', $ptr)));
}
As you can see, the hook is rather simple. first, it receives the arguments mentioned above. it performs a quick check if the pointer is NULL and shouldn't be processed any further. Next, it determines the size of the type being processed. and finally, it'll just use the Pn unpack template to read from that memory location and recursively call unpack to unpack the type. (and yes, this may of course again call other hooks.)
Now, let's test that:
my $ref = { foo => 42, bar => 4711 };
my $ptr = hex(("$ref" =~ /\(0x([[:xdigit:]]+)\)$/)[0]);
print Dumper(unpack_ptr($c, 'AV', $ptr));
Just for the fun of it, we create a blessed array reference. But how do we get a pointer to the corresponding AV? this is rather easy, as the address of the AV is just the hex value that appears when using the array reference in string context. so we just grab that and turn it into decimal. all that's left to do is just call our hook, as it can already handle AV pointers. And this is what we get:
$VAR1 = {
'sv_any' => {
'xmg_stash' => 0,
'xmg_u' => {
'xmg_magic' => 0,
'xmg_hash_index' => 0
},
'xav_fill' => 2,
'xav_max' => 7,
'xav_alloc' => 0
},
'sv_refcnt' => 1,
'sv_flags' => 536870924,
'sv_u' => {
'svu_pv' => '94716517508048',
'svu_iv' => '94716517508048',
'svu_uv' => '94716517508048',
'svu_nv' => '4.67961773944475e-310',
'svu_rv' => '94716517508048',
'svu_array' => '94716517508048',
'svu_hash' => '94716517508048',
'svu_gp' => '94716517508048',
'svu_fp' => '94716517508048'
}
};
okay so yeah, pulling that kind of stunt with unpack_ptr hooks is technically super doable, but bestie, you genuinely have to know what you're doing and be so careful, because of all those limitations we just talked about ๐. it's really easy to slide straight into a segmentation fault when you're dereferencing pointers into memory that isn't yours. like, not your memory, not your problem, not your vibe โ crash.
๐ฆ Performance
using hooks is not free, bestie. nothing is โจ. in performance-critical applications you have to keep in mind that hooks are literally just perl subroutines, and they get called once for every single value of a registered type that's being packed or unpacked.
if only like 10% of your values actually need their hooks fired, you'll barely notice the difference (assuming your hooks are implemented efficiently, whichโฆ do that ๐). but if all the values need hooks called, that alone can make packing and unpacking go from iconic to painfully slow. it's giving molasses.
๐ Tag Order
Since you can attach multiple tags to a single type, the order the tags get processed in actually matters. here's the little table showing the processing order:
pack unpack
---------------------
Hooks Format
Format ByteOrder
ByteOrder Hooks
general rule of thumb, the Hooks tag is always the first thing processed when you're packing data, and the last thing processed when you're unpacking data. main character status: first in, last out ๐
Format and ByteOrder are exclusive, but when you hand over both, the Format tag wins. periodt.
๐ METHODS
๐ธ new
new
new OPTION1 => VALUE1, OPTION2 => VALUE2, ...
The constructor is your girl for making a brand new Convert::Binary::C object. you can keep it super simple and just do
$c = Convert::Binary::C->new;
no extra arguments needed, object acquired ๐. or, if you're feeling fancy, you can pass it any of the arguments that are described down in the configure method. your call, queen.
๐ configure
configure
configure OPTION
configure OPTION1 => VALUE1, OPTION2 => VALUE2, ...
This method does double duty: it configures an existing Convert::Binary::C object, or it fetches the current config of one. two jobs, one icon โจ
Configuring it: the list of options is made of key and value pairs, so it must have an even number of elements. configure (and also new if you're using it with configuration options) will throw an exception if you hand it an odd number of elements. so like, don't do that ๐. normal configuration looks like this:
$c->configure(ByteOrder => 'BigEndian', IntSize => 2);
Getting one value: to grab the current value of a single configuration option, pass configure a single argument โ the name of the option โ like:
$order = $c->configure('ByteOrder');
Getting literally everything: if you want the values of all the configuration options at once, just call configure with zero arguments and it'll return a reference to a hash table holding the entire object configuration. this is chef's kiss with the Data::Dumper module, for example:
use Convert::Binary::C;
use Data::Dumper;
$c = Convert::Binary::C->new(Define => ['DEBUGGING', 'FOO=123'],
Include => ['/usr/include']);
print Dumper($c->configure);
Which will print something like this:
$VAR1 = {
'DisabledKeywords' => [],
'HasCPPComments' => 1,
'UnsignedChars' => 0,
'LongDoubleSize' => 16,
'OrderMembers' => 1,
'CompoundAlignment' => 1,
'UnsignedBitfields' => 0,
'DoubleSize' => 8,
'Assert' => [],
'PointerSize' => 8,
'ByteOrder' => 'LittleEndian',
'Warnings' => 0,
'LongSize' => 8,
'Include' => [
'/usr/include'
],
'EnumType' => 'Integer',
'EnumSize' => 4,
'ShortSize' => 2,
'IntSize' => 4,
'StdCVersion' => 199901,
'HostedC' => 1,
'Alignment' => 1,
'HasMacroVAARGS' => 1,
'KeywordMap' => {},
'Define' => [
'DEBUGGING',
'FOO=123'
],
'LongLongSize' => 8,
'CharSize' => 1,
'FloatSize' => 4,
'Bitfields' => {
'Engine' => 'Generic'
}
};
Since you're probably not gonna write a whole configure call when all you want is to change one little configuration item, you can use any configuration option name as a method name. like:
$c->ByteOrder('LittleEndian') if $c->IntSize < 4;
(and yeah, that example doesn't make very much senseโฆ ;-)
But heads up: configuration methods that can take lists โ namely Include, Define and Assert, but not DisabledKeywords โ may behave slightly differently than their configure equivalent. if you pass these methods a single argument that's an array reference, the current list gets replaced by the new one, which is exactly the behaviour of the matching configure call. so these two are equivalent:
$c->configure(Define => ['foo', 'bar=123']);
$c->Define(['foo', 'bar=123']);
But if you pass a list of strings instead of an array reference (which you cannot do when using configure), the new list items get appended to the current list, so:
$c = Convert::Binary::C->new(Include => ['/include']);
$c->Include('/usr/include', '/usr/local/include');
print Dumper($c->Include);
$c->Include(['/usr/local/include']);
print Dumper($c->Include);
will first print all three include paths, but in the end only "/usr/local/include" will be configured:
$VAR1 = [
'/include',
'/usr/include',
'/usr/local/include'
];
$VAR1 = [
'/usr/local/include'
];
Also bestie, configuration methods chain ๐, because they return a reference to their object when called as a set method. so if that's your vibe, you can configure your object like this:
$c = Convert::Binary::C->new(IntSize => 4)
->Define(qw( __DEBUG__ DB_LEVEL=3 ))
->ByteOrder('BigEndian');
$c->configure(EnumType => 'Both', Alignment => 4)
->Include('/usr/include', '/usr/local/include');
In the example above, qw( ... ) is the word list quoting operator. it returns a list of all the non-whitespace sequences, and it's especially useful for configuring preprocessor defines or assertions. the following assignments are equivalent:
@array = ('one', 'two', 'three');
@array = qw(one two three);
You can configure the following options. unknown options, as well as invalid values for an option, will cause the object to throw exceptions. no sneaky business ๐ซ
โญ IntSize => 0 | 1 | 2 | 4 | 8
Set the number of bytes an integer takes up. this is in most cases 2 or 4. if you set it to zero, the size of an integer on the host system gets used. that's also the default unless it's been overridden by CBC_DEFAULT_INT_SIZE at compile time.
๐ CharSize => 0 | 1 | 2 | 4 | 8
Set the number of bytes a char takes up. this rarely needs changing, except for some platforms that literally don't care about bytes โ DSPs, for example ๐. if you set this to zero, the size of a char on the host system gets used. that's also the default unless it's been overridden by CBC_DEFAULT_CHAR_SIZE at compile time.
๐ ShortSize => 0 | 1 | 2 | 4 | 8
Set the number of bytes a short integer takes up. even though integers explicitly declared as short should always be 16 bit, there are compilers out there that make a short 8 bit wide. wild, i know ๐ญ. if you set it to zero, the size of a short integer on the host system gets used. that's also the default unless it's been overridden by CBC_DEFAULT_SHORT_SIZE at compile time.
๐ฆ LongSize => 0 | 1 | 2 | 4 | 8
Set the number of bytes a long integer takes up. if set to zero, the size of a long integer on the host system gets used. that's also the default unless it's been overridden by CBC_DEFAULT_LONG_SIZE at compile time.
๐ LongLongSize => 0 | 1 | 2 | 4 | 8
Set the number of bytes a long long integer takes up. if set to zero, the size of a long long integer on the host system โ or 8 โ gets used. that's also the default unless it's been overridden by CBC_DEFAULT_LONG_LONG_SIZE at compile time.
๐ฅ FloatSize => 0 | 1 | 2 | 4 | 8 | 12 | 16
Set the number of bytes a single precision floating point value takes up. if you set it to zero, the size of a float on the host system gets used. that's also the default unless it's been overridden by CBC_DEFAULT_FLOAT_SIZE at compile time. for all the deets on floating point support, go peek at FLOATING POINT VALUES.
"DoubleSize" => 0 | 1 | 2 | 4 | 8 | 12 | 16โ sets how many bytes a double precision floating point value takes up. Set it to zero and the size of adoubleon the host system gets used instead. Zero is also the default, unless it got overridden byCBC_DEFAULT_DOUBLE_SIZEback at compile time. Want the full tea on float handling? That's over in "FLOATING POINT VALUES"."LongDoubleSize" => 0 | 1 | 2 | 4 | 8 | 12 | 16โ okay so this sets the number of bytes occupied by a double precision floating point value (yes bestie, the manpage really does say "double precision" right here, we don't make the rules ๐ ). If you set it to zero, the size of along doubleon the host system gets used โ or 12. Zero is also the default unlessCBC_DEFAULT_LONG_DOUBLE_SIZEoverrode it at compile time. For the whole floating point situation, see "FLOATING POINT VALUES"."PointerSize" => 0 | 1 | 2 | 4 | 8โ sets the number of bytes a pointer takes up. In most cases that's 2 or 4. Set it to zero and the size of a pointer on the host system gets used, which is also the default โ unlessCBC_DEFAULT_PTR_SIZEcame through and overrode it at compile time."EnumSize" => -1 | 0 | 1 | 2 | 4 | 8โ sets the number of bytes an enumeration type takes up. On most systems that's equal to the size of an integer, and that's the default too. However, some compilers make the size of an enumeration type depend on how much space the largest enumerator needs, so it can swing anywhere between 1 and 8.
Say you've got
enum foo {
ONE = 100, TWO = 200
};
this one occupies one byte, because the whole enum can be represented as an unsigned one-byte value. But then
enum foo {
ONE = -100, TWO = 200
};
occupies two bytes, because the -100 forces the type to be signed, and 200 doesn't fit into a signed one-byte value. So the type you end up with is a signed two-byte value. If that's the behaviour you need, set EnumSize to 0.
Some compilers try to follow this strategy but genuinely do not care whether the enum has signed values or not โ they just always declare an enum as signed. On a compiler like that, given
enum one { ONE = -100, TWO = 100 };
enum two { ONE = 100, TWO = 200 };
enum one will occupy only one byte, while enum two will occupy two bytes, even though it could have been represented by an unsigned one-byte value. If that's how your compiler behaves, set EnumSize to -1. ๐ซถ
"Alignment" => 0 | 1 | 2 | 4 | 8 | 16โ sets the struct member alignment, i.e. it controls where padding bytes get inserted between struct members. It sets the alignment globally, for all structs/unions. That said, it can be overridden from inside the source code with the commonpackpragma, as explained in "Supported pragma directives". The default alignment is1, which means no padding bytes get inserted at all. A setting of0means native alignment, i.e. the alignment of the system that Convert::Binary::C was compiled on. You can figure out the native properties with thenativefunction. โจ
The Alignment option is similar to the -Zp[n] option of the Intel compiler. It globally specifies the maximum boundary to which struct members are aligned. Take the following structure, with the sizes of char, short, long and double being 1, 2, 4 and 8 respectively.
struct align {
char a;
short b, c;
long d;
double e;
};
With an alignment of 1 (the default), the struct members would be packed tightly:
0 1 2 3 4 5 6 7 8 9 10 11 12
+---+---+---+---+---+---+---+---+---+---+---+---+
| a | b | c | d | ...
+---+---+---+---+---+---+---+---+---+---+---+---+
12 13 14 15 16 17
+---+---+---+---+---+
... e |
+---+---+---+---+---+
With an alignment of 2, the struct members larger than one byte get aligned to 2-byte boundaries, which gives you a single padding byte between a and b.
0 1 2 3 4 5 6 7 8 9 10 11 12
+---+---+---+---+---+---+---+---+---+---+---+---+
| a | * | b | c | d | ...
+---+---+---+---+---+---+---+---+---+---+---+---+
12 13 14 15 16 17 18
+---+---+---+---+---+---+
... e |
+---+---+---+---+---+---+
With an alignment of 4, struct members of size 2 get aligned to 2-byte boundaries and larger struct members get aligned to 4-byte boundaries:
0 1 2 3 4 5 6 7 8 9 10 11 12
+---+---+---+---+---+---+---+---+---+---+---+---+
| a | * | b | c | * | * | d | ...
+---+---+---+---+---+---+---+---+---+---+---+---+
12 13 14 15 16 17 18 19 20
+---+---+---+---+---+---+---+---+
... | e |
+---+---+---+---+---+---+---+---+
This layout of the struct members lets the compiler generate optimized code, because aligned members can be accessed more easily by the underlying architecture. ๐ฅ
And finally, setting the alignment to 8 will align doubles to 8-byte boundaries:
0 1 2 3 4 5 6 7 8 9 10 11 12
+---+---+---+---+---+---+---+---+---+---+---+---+
| a | * | b | c | * | * | d | ...
+---+---+---+---+---+---+---+---+---+---+---+---+
12 13 14 15 16 17 18 19 20 21 22 23 24
+---+---+---+---+---+---+---+---+---+---+---+---+
... | * | * | * | * | e |
+---+---+---+---+---+---+---+---+---+---+---+---+
Bumping the alignment any higher doesn't alter the layout of our structure, because only members larger than 8 bytes would be affected.
The alignment of a structure depends on its largest member and on the setting of the Alignment option. With Alignment set to 2, a structure holding a long would be aligned to a 2-byte boundary, while a structure containing only chars would have no alignment restrictions at all. (Unfortunately, that's not the whole story. See the "CompoundAlignment" option for the details. ๐)
Here's another example. Assuming 8-byte alignment, the following two structs will both have a size of 16 bytes:
struct one {
char c;
double d;
};
struct two {
double d;
char c;
};
That's clear enough for struct one, because the member d has to be aligned to an 8-byte boundary, so 7 padding bytes get inserted after c. But for struct two, the padding bytes get inserted at the end of the structure, which doesn't make much sense immediately. It makes perfect sense though once you think about an array of struct two. Every double has to be aligned to an 8-byte boundary, so every array element would have to occupy 16 bytes. With that in mind, it'd be weird if a struct two variable had a different size โ and it would make this widely used construct
struct two array[] = { {1.0, 0}, {2.0, 1} };
int elements = sizeof(array) / sizeof(struct two);
impossible.
The alignment behaviour described here seems to be common to all compilers. However, not all compilers have an option to configure their default alignment.
"CompoundAlignment" => 0 | 1 | 2 | 4 | 8 | 16โ usually, the alignment of a compound (that's astructor aunion) depends only on its largest member and on the setting of theAlignmentoption. BUT โ there are architectures and compilers out there where compounds can have different alignment constraints.
For most platforms and compilers, the alignment constraint for compounds is 1 byte. So on most platforms
struct onebyte {
char byte;
};
will have an alignment of 1 and also a size of 1. But if you're on an ARM architecture, that same struct onebyte will have an alignment of 4, and therefore also a size of 4. ๐ญ
You can configure this by setting CompoundAlignment to 4. That'll make sure the alignment of compounds is always 4.
Setting CompoundAlignment to 0 means native compound alignment, i.e. the compound alignment of the system that Convert::Binary::C was compiled on. You can determine the native properties with the native function.
There are also compilers for certain platforms that let you adjust the compound alignment. And if you're not aware that your compiler/architecture has a compound alignment other than 1, strange things can happen. If, for example, the compound alignment is 2 and you have something like
typedef unsigned char U8;
struct msg_head {
U8 cmd;
struct {
U8 hi;
U8 low;
} crc16;
U8 len;
};
there's literally one padding byte that gets shoved in before the embedded "crc16" struct and after the "len" member, which is most probably not what you intended, bestie:
0 1 2 3 4 5 6
+-----+-----+-----+-----+-----+-----+
| cmd | * | hi | low | len | * |
+-----+-----+-----+-----+-----+-----+
and also, heads up ๐ both "#pragma pack" and the "Alignment" option can override "CompoundAlignment". so if you set "CompoundAlignment" to 4, but "Alignment" to 2, compounds are actually aligned on 2-byte boundaries. the vibes are layered, it's giving nested config ๐
"ByteOrder" => 'BigEndian' | 'LittleEndian'
set the byte order for integers bigger than a single byte. both little endian (Intel, least significant byte first) and big endian (Motorola, most significant byte first) are supported, so pick your fighter ๐
the default byte order is the same as the host system, unless it got overridden by "CBC_DEFAULT_BYTEORDER" at compile time.
"EnumType" => 'Integer' | 'String' | 'Both'
this one controls the type that enumeration constants are gonna have in the data structures returned by the "unpack" method. so if you've got these definitions:
typedef enum {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
} Weekday;
typedef enum {
JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY,
AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER
} Month;
typedef struct {
int year;
Month month;
int day;
Weekday weekday;
} Date;
and a byte string that holds a packed Date struct, then here's what you get when you call the "unpack" method ๐
"Integer"
enumeration constants come back as plain integers. it's fast, but lowkey not very useful. also it's the default.
$date = {
'year' => 2002,
'month' => 0,
'day' => 7,
'weekday' => 1
};
"String"
enumeration constants come back as strings. this creates a string constant for every unpacked enumeration constant, so it eats up more time and memory. but ngl the result might be more useful to you.
$date = {
'year' => 2002,
'month' => 'JANUARY',
'day' => 7,
'weekday' => 'MONDAY'
};
"Both"
enumeration constants come back as double typed scalars. if you evaluate it in string context, the enumeration constant is a string; if you evaluate it in numeric context, it's an integer. literally the best of both worlds, icon behavior โจ
$date = $c->EnumType('Both')->unpack('Date', $binary);
printf "Weekday = %s (%d)\n\n", $date->{weekday},
$date->{weekday};
if ($date->{month} == 0) {
print "It's $date->{month}, happy new year!\n\n";
}
print Dumper($date);
this will print:
Weekday = MONDAY (1)
It's JANUARY, happy new year!
$VAR1 = {
'year' => 2002,
'month' => 'JANUARY',
'day' => 7,
'weekday' => 'MONDAY'
};
"DisabledKeywords" => [ KEYWORDS ]
this option lets you selectively deactivate certain keywords in the C parser. some C compilers don't have the complete ANSI keyword set, i.e. they don't recognize keywords like "const" or "void", for example. so if you do
typedef int void;
on such a compiler, that's usually.ok. but if you parse it with an ANSI compiler, it's gonna be a syntax error ๐ to parse the above code correctly, you gotta disable the "void" keyword in the Convert::Binary::C parser:
$c->DisabledKeywords([qw( void )]);
by default, the Convert::Binary::C parser recognizes the keywords "inline" and "restrict". if your compiler doesn't have these new keywords, it usually doesn't even matter. it only matters if you're using the keywords as identifiers, like in
typedef struct inline {
int a, b;
} restrict;
in that case you'll have to disable these ISO-C99 keywords:
$c->DisabledKeywords([qw( inline restrict )]);
the parser lets you disable the following keywords:
asm
auto
const
double
enum
extern
float
inline
long
register
restrict
short
signed
static
unsigned
void
volatile
"KeywordMap" => { KEYWORD => TOKEN, ... }
this one lets you add new keywords to the parser. these new keywords can either be mapped to existing tokens, or just straight up ignored. for example, recent versions of the GNU compiler recognize the keywords "__signed__" and "__extension__". the first one is obviously a synonym for "signed", while the second one is literally just a marker for a language extension.
using the preprocessor, you could of course do this:
$c->Define(qw( __signed__=signed __extension__= ));
however โ the preprocessor symbols could get undefined or redefined in the code, and
#ifdef __signed__
# undef __signed__
#endif
typedef __extension__ __signed__ long long s_quad;
would generate a parse error, because "__signed__" is an unexpected identifier ๐ญ
so instead of utilizing the preprocessor, you've gotta create mappings for the new keywords directly in the parser using "KeywordMap". in the above example, you wanna map "__signed__" to the built-in C keyword "signed" and ignore "__extension__". this could be done with the following code:
$c->KeywordMap({ __signed__ => 'signed',
__extension__ => undef });
you can specify any valid identifier as a hash key, and either a valid C keyword or "undef" as a hash value. once you've configured the object that way, you could parse even
#ifdef __signed__
# undef __signed__
#endif
typedef __extension__ __signed__ long long s_quad;
without any problems, periodt ๐
and get this โ "KeywordMap" and "DisabledKeywords" perfectly work together. you could, for example, disable the "signed" keyword, but still have "__signed__" mapped to the original "signed" token:
$c->configure(DisabledKeywords => [ 'signed' ],
KeywordMap => { __signed__ => 'signed' });
this would allow you to define
typedef __signed__ long signed;
which would normally be a syntax error because "signed" cannot be used as an identifier. chef's kiss ๐ซถ
"UnsignedChars" => 0 | 1
use this boolean option if you want characters to be unsigned when they're specified without an explicit "signed" or "unsigned" type specifier. by default, characters are signed.
"UnsignedBitfields" => 0 | 1
use this boolean option if you want bitfields to be unsigned when they're specified without an explicit "signed" or "unsigned" type specifier. by default, bitfields are signed.
"Warnings" => 0 | 1
use this boolean option if you want warnings to be issued during the parsing of source code. currently, warnings are only reported by the preprocessor, so don't expect the output to cover everything ๐
by default, warnings are turned off and only errors get reported. however, even these errors are turned off if you run without the -w flag.
"HasCPPComments" => 0 | 1
use this option to turn C++ comments on or off. by default, C++ comments are enabled. disabling C++ comments may be necessary if your code includes strange things like:
one = 4 //* <- divide */ 4;
two = 2;
with C++ comments, the above gets interpreted as
one = 4
two = 2;
which will obviously be a syntax error ๐ but without C++ comments, it gets interpreted as
one = 4 / 4;
two = 2;
which is correct. girlies supporting weird legacy code, rise ๐ธ
"HasMacroVAARGS" => 0 | 1
use this option to turn the "__VA_ARGS__" macro expansion on or off. if it's enabled (which is the default), you can use variable length argument lists in your preprocessor macros.
#define DEBUG( ... ) fprintf( stderr, __VA_ARGS__ )
there's normally no reason to turn that feature off. it's giving useful, keep it.
"StdCVersion" => undef | INTEGER
use this option to change the value of the preprocessor's predefined "__STDC_VERSION__" macro. when it's set to "undef", the macro will not be defined.
"HostedC" => undef | 0 | 1
use this option to change the value of the preprocessor's predefined "__STDC_HOSTED__" macro. when it's set to "undef", the macro will not be defined.
"Include" => [ INCLUDES ]โ sets the include path for the internal preprocessor ๐ the value is a reference to an array of strings, and each string is a directory that gets searched for includes."Define" => [ DEFINES ]โ defines symbols in the preprocessor โจ again, the value is a reference to an array of strings. Each string is either just a symbol, or an assignment to a symbol. This is completely equivalent to what the-Doption does for basically every preprocessor out there.
So like, this next one defines the symbol FOO, and defines BAR to be 12345:
$c->configure(Define => [qw( FOO BAR=12345 )]);
"Assert" => [ ASSERTIONS ]โ makes assertions in the preprocessor. If you don't know what assertions are, don't even stress bestie, because they're deprecated anyway ๐ญ they are, however, used in some system's include files. The value is an array reference, just like for the macro definitions. Only the way the assertions are defined is a bit different and mimics the way they're defined with the"#assert"directive:
$c->configure(Assert => ['foo(bar)']);
"OrderMembers" => 0 | 1โ okay so when you use"unpack"on compounds and iterate over the returned hash, the order of the compound members is generally not preserved, because hash tables are gonna hash table ๐ it's not even guaranteed that the order is the same between different runs of the same program. Which is so annoying if you literally just want to dump your data structures and the compound members keep showing up in a different order every single time ๐
By setting "OrderMembers" to a non-zero value, all hashes returned by "unpack" get tied to a class that preserves the order of the hash keys โจ this way, all compound members will be returned in the correct order just as they are defined in your C code. iconic.
use Convert::Binary::C;
use Data::Dumper;
$c = Convert::Binary::C->new->parse(<<'ENDC');
struct test {
char one;
char two;
struct {
char never;
char change;
char this;
char order;
} three;
char four;
};
ENDC
$data = "Convert";
$u1 = $c->unpack('test', $data);
$c->OrderMembers(1);
$u2 = $c->unpack('test', $data);
print Data::Dumper->Dump([$u1, $u2], [qw(u1 u2)]);
This will print something like:
$u1 = {
'one' => 67,
'two' => 111,
'three' => {
'never' => 110,
'change' => 118,
'this' => 101,
'order' => 114
},
'four' => 116
};
$u2 = {
'one' => 67,
'two' => 111,
'three' => {
'never' => 110,
'change' => 118,
'this' => 101,
'order' => 114
},
'four' => 116
};
To be able to use this option, you have to install one of the following modules: Tie::Hash::Indexed, Hash::Ordered or Tie::IxHash ๐ซถ if more than one of these modules is installed, Convert::Binary::C will use them in that order of preference.
When using this option, keep in mind that tied hashes are significantly slower and consume more memory than ordinary hashes, even when the class they're tied to is implemented efficiently. So don't turn this option on if you don't have to, bestie, fr fr.
You can also influence hash member ordering by using the "CBC_ORDER_MEMBERS" environment variable ๐
"Bitfields" => { OPTION => VALUE, ... }โ use this to specify and configure a bitfield layouting engine ๐ง you can choose an engine by passing its name to the"Engine"option, like:
$c->configure(Bitfields => { Engine => 'Generic' });
Each engine can have its own set of options, although currently none of them does.
You can choose between the following bitfield engines:
"Generic"โ this engine implements the behaviour of most UNIX C compilers, including GCC. It does not handle packed bitfields yet."Microsoft"โ this engine implements the behaviour of Microsoft's"cl"compiler. It should be fairly complete and can handle packed bitfields."Simple"โ this engine is only used for testing the bitfield infrastructure inConvert::Binary::C. There's usually no reason to use it.
So here's the tea: you can reconfigure all options even after you have parsed some code ๐
the changes will be applied to the already parsed definitions. This works as long as array lengths are not affected by the changes. If you have Alignment and IntSize set to 4 and parse code like this:
typedef struct {
char abc;
int day;
} foo;
struct bar {
foo zap[2*sizeof(foo)];
};
the array "zap" in "struct bar" will obviously have 16 elements. If you reconfigure the alignment to 1 now, the size of "foo" is now 5 instead of 8. While the alignment is adjusted correctly, the number of elements in array "zap" will still be 16 and will not be changed to 10 ๐ญ so like, watch out for that.
โจ parse โจ
"parse" CODEโ parses a string of valid C code ๐ all enumeration, compound and type definitions are extracted. You can call the"parse"and"parse_file"methods as often as you like to add further definitions to theConvert::Binary::Cobject.
"parse" will throw an exception if an error occurs. On success, the method returns a reference to its object ๐
See "Parsing C code" for an example.
โจ parse_file โจ
"parse_file" FILEโ parses a C source file ๐ธ all enumeration, compound and type definitions are extracted. You can call the"parse"and"parse_file"methods as often as you like to add further definitions to theConvert::Binary::Cobject.
"parse_file" will search the include path given via the "Include" option for the file if it cannot find it in the current directory.
"parse_file" will throw an exception if an error occurs. On success, the method returns a reference to its object ๐ซถ
See "Parsing C code" for an example.
When calling "parse" or "parse_file" multiple times, you may use types previously defined, but you are not allowed to redefine types. The state of the preprocessor is also saved, so you may also use defines from a previous parse. This works only as long as the preprocessor is not reset. See "Preprocessor configuration" for details.
When you're parsing C source files instead of C header files, note that local definitions are ignored ๐ this means that type definitions hidden within functions will not be recognized by Convert::Binary::C. This is necessary because different functions (even different blocks within the same function) can define types with the same name:
void my_func(int i)
{
if (i < 10)
{
enum digit { ONE, TWO, THREE } x = ONE;
printf("%d, %d\n", i, x);
}
else
{
enum digit { THREE, TWO, ONE } x = ONE;
printf("%d, %d\n", i, x);
}
}
The above is a valid piece of C code, but it's not possible for Convert::Binary::C to distinguish between the different definitions of "enum digit", as they're only defined locally within the corresponding block. it's giving "same name, different block, good luck" ๐ญ
โจ clean โจ
"clean"โ clears all information that has been collected during previous calls to"parse"or"parse_file"โจ you can use this method if you want to parse some entirely different code, but with the same configuration.
The "clean" method returns a reference to its object ๐
โจ clone โจ
"clone"โ makes the object return an exact independent copy of itself ๐ฆ
$c = Convert::Binary::C->new(Include => ['/usr/include']);
$c->parse_file('definitions.c');
$clone = $c->clone;
The above code is technically equivalent (Mostly. Actually, using "sourcify" and "parse" might alter the order of the parsed data, which would make methods such as "compound" return the definitions in a different order.) to:
$c = Convert::Binary::C->new(Include => ['/usr/include']);
$c->parse_file('definitions.c');
$clone = Convert::Binary::C->new(%{$c->configure});
$clone->parse($c->sourcify);
Using "clone" is just a lot faster ๐ฅ no cap.
โจ def โจ
"def" NAME"def" TYPEโ if you need to know if a definition for a certain type name exists, use this method ๐ you pass it the name of an enum, struct, union or typedef, and it will return a non-empty string being either"enum","struct","union", or"typedef"if there's a definition for the type in question, an empty string if there's no such definition, or"undef"if the name is completely unknown. And if the type can be interpreted as a basic type,"basic"will be returned ๐
If you hand over a TYPE, the output switches up a little. If that member is actually a thing, def hands you back member. If it's not a thing, or the type is literally incapable of having members, you get the empty string back. And if the type's name is completely unknown to us? undef. Which is lowkey perfect if you just wanna vibe-check whether some member lives inside a compound ๐
use Convert::Binary::C;
my $c = Convert::Binary::C->new->parse(<<'ENDC');
typedef struct __not not;
typedef struct __not *ptr;
struct foo {
enum bar *xxx;
};
typedef int quad[4];
ENDC
for my $type (qw( not ptr foo bar xxx foo.xxx foo.abc xxx.yyy
quad quad[3] quad[5] quad[-3] short[1] ),
'unsigned long')
{
my $def = $c->def($type);
printf "%-14s => %s\n",
$type, defined $def ? "'$def'" : 'undef';
}
And here's what def would serve back to you, no cap:
not => ''
ptr => 'typedef'
foo => 'struct'
bar => ''
xxx => undef
foo.xxx => 'member'
foo.abc => ''
xxx.yyy => undef
quad => 'typedef'
quad[3] => 'member'
quad[5] => 'member'
quad[-3] => 'member'
short[1] => undef
unsigned long => 'basic'
So the vibe check is: if def returns a non-empty string, you're totally safe to use any of the other methods with that type's name, or with that member expression. Slay ๐ซถ
About arrays, bestie โ heads up โ the index into an array does not have to sit inside the bounds of the array's definition. Just like in C, fr fr. Up there,quad[5]andquad[-3]are valid members of thequadarray, even though it's declared with only four elements. C said "bounds? never heard of her." ๐ญ
And when the typedef namespace overlaps with the namespace of enums/structs/unions, def will give preference to the typedef and thus return the string typedef. But you can force the interpretation as an enum, struct or union by putting enum, struct or union in front of the type's name. Not me picking favorites, but also... yeah ๐คญ
โจ defined โจ
"defined" MACRO
Use the defined method to find out if a certain macro is defined โ literally exactly like you'd use the preprocessor's defined operator. For example, this code:
use Convert::Binary::C;
my $c = Convert::Binary::C->new->parse(<<'ENDC');
#define ADD(a, b) ((a) + (b))
#if 1
# define DEFINED
#else
# define UNDEFINED
#endif
ENDC
for my $macro (qw( ADD DEFINED UNDEFINED )) {
my $not = $c->defined($macro) ? '' : ' not';
print "Macro '$macro' is$not defined.\n";
}
would print:
Macro 'ADD' is defined.
Macro 'DEFINED' is defined.
Macro 'UNDEFINED' is not defined.
You do gotta keep in mind that this only works as long as the preprocessor is not reset. See "Preprocessor configuration" for the details, bestie ๐
โจ pack โจ
"pack" TYPE
"pack" TYPE, DATA
"pack" TYPE, DATA, STRING
Use this method to pack a complex data structure into a binary string, according to a type definition that's been previously parsed. DATA has to be a scalar matching the type definition. C structures and unions are represented by references to Perl hashes, and C arrays by references to Perl arrays. Iconic.
use Convert::Binary::C;
use Data::Dumper;
use Data::Hexdumper;
$c = Convert::Binary::C->new( ByteOrder => 'BigEndian'
, LongSize => 4
, ShortSize => 2
)
->parse(<<'ENDC');
struct test {
char ary[3];
union {
short word[2];
long quad;
} uni;
};
ENDC
Hashes don't have to contain a key for each compound member, and arrays may be truncated:
$binary = $c->pack('test', { ary => [1, 2], uni => { quad => 42 } });
Elements you didn't define in the Perl data structure get set to zero in the packed byte string. And if you pass undef as the second parameter, or just straight-up omit it, the whole string gets initialized with zero bytes. On success, the packed byte string is returned โจ
print hexdump(data => $binary);
The above code would print:
0x0000 : 01 02 00 00 00 00 2A : ......*
You could also use unpack and dump the data structure.
$unpacked = $c->unpack('test', $binary);
print Data::Dumper->Dump([$unpacked], ['unpacked']);
This would print:
$unpacked = {
'ary' => [
1,
2,
0
],
'uni' => {
'word' => [
0,
42
],
'quad' => 42
}
};
If TYPE refers to a compound object, you can pack any member of that compound object. Just add a member expression to the type name, exactly like you'd access the member in C:
$array = $c->pack('test.ary', [1, 2, 3]);
print hexdump(data => $array);
$value = $c->pack('test.uni.word[1]', 2);
print hexdump(data => $value);
This would give you:
0x0000 : 01 02 03 : ...
0x0000 : 00 02 : ..
Call pack with the optional STRING argument if you wanna use an existing binary string to insert the data. If it's called in a void context, pack will directly modify the string you passed as the third argument. Otherwise, a copy of the string is created, and pack will modify and return the copy โ so the original string stays exactly how it was. Original stays unbothered ๐
The 3-argument version may be useful if you only wanna change a few members of a complex data structure without having to unpack everything, change the members, and then pack again โ which could waste lots of memory and CPU cycles. So instead of doing something like
$test = $c->unpack('test', $binary);
$test->{uni}{quad} = 4711;
$new = $c->pack('test', $test);
to change the uni.quad member of $packed, you could simply do either
$new = $c->pack('test', { uni => { quad => 4711 } }, $binary);
or
$c->pack('test', { uni => { quad => 4711 } }, $binary);
while the latter would directly modify $packed. Besides this code being a lot shorter (and maybe even more readable), it can be significantly faster when you're dealing with really big data blocks. Efficiency? Obsessed ๐ฅ
If the length of the input string is less than the size required by the type, the string (or its copy) is extended, and the extended part gets initialized to zero. If the length is more than the size required by the type, the string is kept at that length โ and also, a copy would be an exact copy of that string. No trimming, no editing, we respect the length ๐
$too_short = pack "C*", (1 .. 4);
$too_long = pack "C*", (1 .. 20);
$c->pack('test', { uni => { quad => 0x4711 } }, $too_short);
print "too_short:\n", hexdump(data => $too_short);
$copy = $c->pack('test', { uni => { quad => 0x4711 } }, $too_long);
print "\ncopy:\n", hexdump(data => $copy);
This would print:
too_short:
0x0000 : 01 02 03 00 00 47 11 : .....G.
copy:
0x0000 : 01 02 03 00 00 47 11 08 09 0A 0B 0C 0D 0E 0F 10 : .....G..........
0x0010 : 11 12 13 14 : ....
โจ unpack โจ
"unpack" TYPE, STRING
Use this method to unpack a binary string and create an arbitrarily complex Perl data structure, based on a previously parsed type definition. Main character energy fr fr โจ
use Convert::Binary::C;
use Data::Dumper;
$c = Convert::Binary::C->new( ByteOrder => 'BigEndian'
, LongSize => 4
, ShortSize => 2
)
->parse( <<'ENDC' );
struct test {
char ary[3];
union {
short word[2];
long *quad;
} uni;
};
ENDC
# Generate some binary dummy data
$binary = pack "C*", 1 .. $c->sizeof('test');
On failure โ like, say, if the specified type can't be found โ the method will throw an exception ๐ญ On success, a reference to a complex Perl data structure is returned, which you can directly dump using the Data::Dumper module:
$unpacked = $c->unpack('test', $binary);
print Dumper($unpacked);
This would print:
$VAR1 = {
'ary' => [
1,
2,
3
],
'uni' => {
'word' => [
1029,
1543
],
'quad' => '289644378304612875'
}
};
If TYPE refers to a compound object, you can unpack any member of that compound object. Just add a member expression to the type name, exactly like you'd access the member in C:
$binary2 = substr $binary, $c->offsetof('test', 'uni.word');
$unpack1 = $unpacked->{uni}{word};
$unpack2 = $c->unpack('test.uni.word', $binary2);
print Data::Dumper->Dump([$unpack1, $unpack2], [qw(unpack1 unpack2)]);
You'll literally see the output is the exact same for both $unpack1 and $unpack2, no cap:
$unpack1 = [
1029,
1543
];
$unpack2 = [
1029,
1543
];
And when unpack gets called in list context, it will unpack as many elements as possible from STRING โ including zero if STRING isn't long enough. She's giving "I did what I could" energy ๐
๐ initializer ๐
initializer TYPE
initializer TYPE, DATA
okay so the initializer method is your bestie for retrieving an initializer string for a certain TYPE. Super useful if you've got a huge compound type and you only need to initialize, like, two members โ or if you just wanna generate initializers automatically because typing by hand is not the vibe:
struct date {
unsigned year : 12;
unsigned month: 4;
unsigned day : 5;
unsigned hour : 5;
unsigned min : 6;
};
typedef struct {
enum { DATE, QWORD } type;
short number;
union {
struct date date;
unsigned long qword;
} choice;
} data;
So given the above code has been parsed:
$init = $c->initializer('data');
print "data x = $init;\n";
would print this:
data x = {
0,
0,
{
{
0,
0,
0,
0,
0
}
}
};
You could directly drop that into a C program, though ngl it probably isn't very useful yet. It gets SO much better once you actually tell it how you want the type initialized:
$data = {
type => 'QWORD',
choice => {
date => { month => 12, day => 24 },
qword => 4711,
},
stuff => 'yes?',
};
$init = $c->initializer('data', $data);
print "data x = $init;\n";
Which prints:
data x = {
QWORD,
0,
{
{
0,
12,
24,
0,
0
}
}
};
Here's the tea โ โ since only the first member of a union can be initialized, choice.qword gets ignored. And you will not be warned about the fact that you probably tried to initialize a member that isn't the first one. That's considered a feature bestie, because it lets you use unpack to generate the initializer data:
$data = $c->unpack('data', $binary);
$init = $c->initializer('data', $data);
Because unpack unpacks all union members, you'd otherwise have to go in and delete all but the first one before feeding it into initializer. Exhausting. We don't do that here ๐
Also, stuff is ignored too, because it actually isn't a member of data. And you won't be warned about that either. ๐
๐ฆ sizeof ๐ฆ
sizeof TYPE
This method hands you the size of a C type in bytes. And if it can't find the type? It will throw an exception. Periodt.
If your type defines some kind of compound object, you can ask for the size of a member of that compound object instead:
$size = $c->sizeof('test.uni.word[1]');
This would set $size to 2. Slay.
โจ typeof โจ
typeof TYPE
This one returns the type of a C member. While that only really makes sense for compound types, it's totally legal to use it on non-compound types too. Can't find the type? Exception, again. It's consistent, we love that.
The typeof method works on any valid member โ even arrays or unnamed types. It always returns a string holding the name (or, for unnamed types, only the class) of the type, optionally followed by a '*' character to flag that it's a pointer type, and optionally followed by one or more array dimensions if it's an array type. And if the type is a bitfield, the type name gets followed by a colon and the number of bits:
struct test {
char ary[3];
union {
short word[2];
long *quad;
} uni;
struct {
unsigned short six:6;
unsigned short ten:10;
} bits;
};
Given the above C code has been parsed, calls to typeof return these values:
$c->typeof('test') => 'struct test'
$c->typeof('test.ary') => 'char [3]'
$c->typeof('test.uni') => 'union'
$c->typeof('test.uni.quad') => 'long *'
$c->typeof('test.uni.word') => 'short [2]'
$c->typeof('test.uni.word[1]') => 'short'
$c->typeof('test.bits') => 'struct'
$c->typeof('test.bits.six') => 'unsigned short :6'
$c->typeof('test.bits.ten') => 'unsigned short :10'
Obsessed with how clean that is ๐ญ
๐ offsetof ๐
offsetof TYPE, MEMBER
You can use offsetof just like the C macro of the same denominator ๐ โ all it does is return the offset (in bytes) of MEMBER relative to TYPE.
use Convert::Binary::C;
$c = Convert::Binary::C->new( Alignment => 4
, LongSize => 4
, PointerSize => 4
)
->parse(<<'ENDC');
typedef struct {
char abc;
long day;
int *ptr;
} week;
struct test {
week zap[8];
};
ENDC
@args = (
['test', 'zap[5].day' ],
['test.zap[2]', 'day' ],
['test', 'zap[5].day+1'],
['test', 'zap[-3].ptr' ],
);
for (@args) {
my $offset = eval { $c->offsetof(@$_) };
printf "\$c->offsetof('%s', '%s') => $offset\n", @$_;
}
That final loop prints:
$c->offsetof('test', 'zap[5].day') => 64
$c->offsetof('test.zap[2]', 'day') => 4
$c->offsetof('test', 'zap[5].day+1') => 65
$c->offsetof('test', 'zap[-3].ptr') => -28
Let's break it down bestie:
- The first iteration is just showing that the offset of
zap[5].dayis64relative to the beginning ofstruct test. - You may additionally specify a member for the type passed as the first argument, like the second iteration does.
- The offset suffix is supported by
offsetoftoo, so the third iteration correctly prints65. Cute! - And the last iteration demonstrates that even out-of-bounds array indices get handled correctly, just like they are in C. Brave. Feral. Love that for us.
Unlike the C macro, offsetof also works on array types:
$offset = $c->offsetof('test.zap', '[3].ptr+2');
print "offset = $offset";
Which prints:
offset = 46
If TYPE is a compound, MEMBER may optionally be prefixed with a dot, so:
printf "offset = %d\n", $c->offsetof('week', 'day');
printf "offset = %d\n", $c->offsetof('week', '.day');
are both equivalent and will print
offset = 4
offset = 4
This lets you:
- use the C macro style, without a leading dot, and
- directly use the output of the
membermethod โ which includes a leading dot for compound types โ as input for the MEMBER argument. Chef's kiss ๐ค
๐ member ๐
member TYPE
member TYPE, OFFSET
You can think of member as being the reverse of the offsetof method. But since this is way more complex, there's no equivalent to member in the C language. It's giving exclusive โจ
Usually you'd use this method when you wanna retrieve the name of the member located at a specific offset of a previously parsed type:
use Convert::Binary::C;
$c = Convert::Binary::C->new( Alignment => 4
, LongSize => 4
, PointerSize => 4
)
->parse(<<'ENDC');
typedef struct {
char abc;
long day;
int *ptr;
} week;
struct test {
week zap[8];
};
ENDC
for my $offset (24, 39, 69, 99) {
print "\$c->member('test', $offset)";
my $member = eval { $c->member('test', $offset) };
print $@ ? "\n exception: $@" : " => '$member'\n";
}
This will print:
$c->member('test', 24) => '.zap[2].abc'
$c->member('test', 39) => '.zap[3]+3'
$c->member('test', 69) => '.zap[5].ptr+1'
$c->member('test', 99)
exception: Offset 99 out of range (0 <= offset < 96)
- The output of the first iteration is obvious, bestie. The member
zap[2].abcis located at offset24ofstruct test. - In the second iteration, the offset points into a region of padding bytes, so no member of
weekcan be named. Instead of a member name, the offset relative tozap[3]gets appended. - In the third iteration, the offset points to
zap[5].ptr. However,zap[5].ptris located at68, not at69, and thus the remaining offset of1is also appended. - The last iteration throws an exception, because offset
99isn't valid forstruct testโ the whole thing is only 96 bytes big ๐ญ. And yeah, you could argue that's inconsistent, sinceoffsetofhappily deals with out-of-bounds array members. But bestie, the moment you have more than one level of array nesting, there's literally an infinite number of out-of-bounds members for a single given offset, so returning a list of all of them would be straight-up impossible. ๐
You can also slide in a member for the type you passed as the first argument:
$member = $c->member('test.zap[2]', 6);
print $member;
This will print:
.day+2
Just like offsetof, member also eats array types:
$member = $c->member('test.zap', 42);
print $member;
This will print:
[3].day+2
Okay so structs are pretty obvious, but unions? That's where it gets tricky. Because a single offset usually points at more than one member of a union, the algorithm has โจrulesโจ for picking the best member:
- The first non-compound member that's referenced without an offset has the highest priority. ๐
- If no member is referenced without an offset, then the first non-compound member that's referenced with an offset gets returned.
- Otherwise, the first padding region that shows up gets taken. ๐
As an example, with 4-byte alignment and this union:
union choice {
struct {
char color[2];
long size;
char taste;
} apple;
char grape[3];
struct {
long weight;
short price[3];
} melon;
};
the member method would hand you back whatever's in the Member column of this table. The Type column shows what typeof gives you when you pass the corresponding member:
Offset Member Type
--------------------------------------
0 .apple.color[0] 'char'
1 .apple.color[1] 'char'
2 .grape[2] 'char'
3 .melon.weight+3 'long'
4 .apple.size 'long'
5 .apple.size+1 'long'
6 .melon.price[1] 'short'
7 .apple.size+3 'long'
8 .apple.taste 'char'
9 .melon.price[2]+1 'short'
10 .apple+10 'struct'
11 .apple+11 'struct'
Think of it like a stack of all the union members, and you're peering through the stack looking for the shiniest piece you can see. โจ The beginning of a member (those uppercase letters) is always shinier than the rest of that member, and padding regions (the dashes) aren't shiny at all, nope, zero sparkle. ๐
Offset 0 1 2 3 4 5 6 7 8 9 10 11
-------------------------------------------------------
apple (C) (C) - - (S) (s) s (s) (T) - (-) (-)
grape G G (G)
melon W w w (w) P p (P) p P (p) - -
If you look through that stack top to bottom, you land on the parenthesized members. ๐
Alternatively, if you're not just here for the single best member, you can call member in list context, and it'll return all the members referenced by the given offset:
Offset Member Type
--------------------------------------
0 .apple.color[0] 'char'
.grape[0] 'char'
.melon.weight 'long'
1 .apple.color[1] 'char'
.grape[1] 'char'
.melon.weight+1 'long'
2 .grape[2] 'char'
.melon.weight+2 'long'
.apple+2 'struct'
3 .melon.weight+3 'long'
.apple+3 'struct'
4 .apple.size 'long'
.melon.price[0] 'short'
5 .apple.size+1 'long'
.melon.price[0]+1 'short'
6 .melon.price[1] 'short'
.apple.size+2 'long'
7 .apple.size+3 'long'
.melon.price[1]+1 'short'
8 .apple.taste 'char'
.melon.price[2] 'short'
9 .melon.price[2]+1 'short'
.apple+9 'struct'
10 .apple+10 'struct'
.melon+10 'struct'
11 .apple+11 'struct'
.melon+11 'struct'
The first member returned is always the best member. ๐ฅ The rest are sorted by those rules up above. That means members referenced without an offset come first, followed by members referenced with an offset. Padding regions? They're at the very end, like always picked last for dodgeball. ๐ญ
If you don't pass OFFSET in the method call, member returns a list of every possible member of TYPE:
print "$_\n" for $c->member('choice');
This will print:
.apple.color[0]
.apple.color[1]
.apple.size
.apple.taste
.grape[0]
.grape[1]
.grape[2]
.melon.weight
.melon.price[0]
.melon.price[1]
.melon.price[2]
And in scalar context? You get the number of possible members back. ๐ข
๐ tag ๐
"tag" TYPE
"tag" TYPE, TAG
"tag" TYPE, TAG1 => VALUE1, TAG2 => VALUE2, ...
The tag method lets you tag properties onto a TYPE. It's kinda like having configure, but for individual types. ๐
Peep USING TAGS for an example.
Heads up bestie: while you can tag whole types and compound members, you cannot tag array members. Like, you can't treata[1]anda[2]differently. Sorry, them's the rules. ๐ซถ
Also note that in code like this:
struct test {
int a;
struct {
int x;
} b, c;
};
if you tag test.b.x, it'll implicitly tag test.c.x too. (not me finding out the hard way ๐ญ)
You can also tag basic types if you really wanna do that, for example:
$c->tag('int', Format => 'Binary');
To remove a tag from a type, you can either set that tag to undef, like:
$c->tag('test', Hooks => undef);
or just use untag. ๐
To check if a tag is attached to a type, or to grab the value of a tag, pass only the type and the tag name to tag:
$c->tag('test.a', Format => 'Binary');
$hooks = $c->tag('test.a', 'Hooks');
$format = $c->tag('test.a', 'Format');
This will give you:
$hooks = undef;
$format = 'Binary';
To see which tags are attached to a type, pass only the type. Now tag returns a hash reference holding all the tags attached to that type:
$tags = $c->tag('test.a');
This will give you:
$tags = {
'Format' => 'Binary'
};
tag throws an exception if an error happens. ๐จ And if you call it as a set method, it returns a reference to its object, so you can chain consecutive method calls together like the icon you are. โจ
Note that when a compound is inlined, tags attached to the inlined compound are ignored. For example:
$c->parse(<<ENDC);
struct header {
int id;
int len;
unsigned flags;
};
struct message {
struct header;
short samples[32];
};
ENDC
for my $type (qw( header message header.len )) {
$c->tag($type, Hooks => { unpack => sub { print "unpack: $type\n"; @_ } });
}
for my $type (qw( header message )) {
print "[unpacking $type]\n";
$u = $c->unpack($type, $data);
}
This will print:
[unpacking header]
unpack: header.len
unpack: header
[unpacking message]
unpack: header.len
unpack: message
So as you can see from that output, tags attached to members of inlined compounds (header.len) are still handled. ๐ซถ
<div></div>
โจ The following tags can be configured:
"Format" => 'Binary' | 'String'
The Format tag lets you control the way binary data gets converted by pack and unpack. ๐
If you tag a TYPE as Binary, it won't be converted at all โ it just gets passed through as a binary string.
If you tag it as String, it's treated like a null-terminated C string โ unpack converts the C string to a Perl string, and vice versa.
Peep The Format Tag for an example. ๐
"ByteOrder" => 'BigEndian' | 'LittleEndian'
The ByteOrder tag lets you explicitly set the byte order of a TYPE. ๐
Peep The ByteOrder Tag for an example.
"Dimension" => '*'
"Dimension" => VALUE
"Dimension" => MEMBER
"Dimension" => SUB
"Dimension" => [ SUB, ARGS ]
The Dimension tag lets you change the size of an array dynamically. ๐
You can tag fixed size arrays as being flexible using '*'. This is handy if you can't use flexible array members in your source code.
$c->tag('type.array', Dimension => '*');
You can also tag an array to have a fixed size different from the one it was originally declared with.
$c->tag('type.array', Dimension => 42);
If the array is a member of a compound, bestie, you can also tag it so its size just follows the value of another member in that same compound. So cute, so convenient:
$c->tag('type.array', Dimension => 'count');
And finally โ plot twist โ you can hand it a subroutine that gets called whenever the array's size needs to be figured out:
$c->tag('type.array', Dimension => \&get_count);
By default, and if that array is a compound member, the subroutine gets passed a reference to the hash that stores the data for the compound. ๐
You can also make Convert::Binary::C pass extra arguments to that subroutine by handing it an array reference instead of a plain subroutine reference. That array holds the subroutine ref in the first slot plus a list of arguments after it. And yes, you can define special arguments with the arg method:
$c->tag('type.array', Dimension => [\&get_count, $c->arg('SELF'), 42]);
Peep "The Dimension Tag" for a whole bunch of examples. ๐
โจ "Hooks" => { HOOK => SUB, HOOK => [ SUB, ARGS ], ... }, ... โจ
Okay so the Hooks tag is how you register subroutines as hooks.
Hooks get called whenever a certain "TYPE" is packed or unpacked. Heads up bestie: hooks are currently considered an experimental feature. ๐
"HOOK" can be one of these:
packunpackpack_ptrunpack_ptr
pack and unpack hooks fire when their "TYPE" is being processed, while pack_ptr and unpack_ptr hooks fire when pointers to their "TYPE" are being processed. ๐ฏ
SUB is a reference to a subroutine that usually takes one input argument, does its lil thing, and returns one output argument.
Alternatively you can pass a custom list of arguments to the hook by using an array reference instead of SUB โ first element is the subroutine reference, and the rest are the arguments to pass in. That way you can even feed special arguments to the hook using the arg method. ๐ซถ
Here are a few examples of registering hooks:
$c->tag('ObjectType', Hooks => {
pack => \&obj_pack,
unpack => \&obj_unpack
});
$c->tag('ProtocolId', Hooks => {
unpack => sub { $protos[$_[0]] }
});
$c->tag('ProtocolId', Hooks => {
unpack_ptr => [sub {
sprintf "$_[0]:{0x%X}", $_[1]
},
$c->arg('TYPE', 'DATA')
],
});
Not me pointing out that the example above registers both an unpack hook and an unpack_ptr hook for ProtocolId โ with two separate calls to tag. And the way that works is: as long as you don't explicitly overwrite a previously registered hook, it won't get modified or removed just because you register other hooks for the same "TYPE". ๐
Wanna nuke all registered hooks for a type? Just remove the Hooks tag:
$c->untag('ProtocolId', 'Hooks');
And if you only want to remove a single hook, pass undef as SUB instead of a subroutine reference:
$c->tag('ObjectType', Hooks => { pack => undef });
And if every last hook is gone? The whole Hooks tag dips out too. ๐
See "The Hooks Tag" for examples on how to actually use hooks.
๐ untag ๐
untag TYPE
untag TYPE, TAG1, TAG2, ...
Use the untag method to remove one, more, or literally all tags from a type. Pass no tag names at all? Every tag attached to that type gets removed. Pass names? Only the listed ones go. โ๏ธ
See "USING TAGS" for an example.
๐ arg ๐
arg 'ARG', ...
Creates placeholders for special arguments that get passed to hooks or other subroutines. These arguments are currently:
"SELF"โ a reference to the calling Convert::Binary::C object. Super handy if you need to work with the object from inside the subroutine. ๐"TYPE"โ the name of the type that's currently being processed by the hook."DATA"โ the data argument that's passed to the subroutine."HOOK"โ the type of hook as which the subroutine was called, for examplepackorunpack_ptr.
arg returns a placeholder for each argument you hand it. But lowkey note: not all arguments may be supported, depending on the context of the subroutine. ๐
๐ฆ dependencies ๐ฆ
dependencies
After some code has been parsed with either the parse or parse_file methods, the dependencies method lets you pull info about every file the object depends on โ i.e. every file that has been parsed. Obsessed.
In scalar context, the method returns a hash reference. Each key is the name of a file, and each value is another hash reference holding that file's size, modification time (mtime), and change time (ctime) at the exact moment it was parsed. โญ
use Convert::Binary::C;
use Data::Dumper;
#----------------------------------------------------------
# Create object, set include path, parse 'string.h' header
#----------------------------------------------------------
my $c = Convert::Binary::C->new
->Include('/usr/lib/gcc/x86_64-pc-linux-gnu/10.2.0/include',
'/usr/lib/gcc/x86_64-pc-linux-gnu/10.2.0/include-fixed',
'/usr/include')
->parse_file('string.h');
#----------------------------------------------------------
# Get dependencies of the object, extract dependency files
#----------------------------------------------------------
my $depend = $c->dependencies;
my @files = keys %$depend;
#-----------------------------
# Dump dependencies and files
#-----------------------------
print Data::Dumper->Dump([$depend, \@files],
[qw( depend *files )]);
The code above would print something like this:
$depend = {
'/usr/include/sys/cdefs.h' => {
'size' => 20051,
'mtime' => 1604969938,
'ctime' => 1604969964
},
'/usr/include/gnu/stubs-32.h' => {
'size' => 449,
'mtime' => 1604969908,
'ctime' => 1604969964
},
'/usr/include/bits/wordsize.h' => {
'size' => 442,
'mtime' => 1604969934,
'ctime' => 1604969964
},
'/usr/lib/gcc/x86_64-pc-linux-gnu/10.2.0/include/stddef.h' => {
'size' => 12959,
'mtime' => 1604974286,
'ctime' => 1604975398
},
'/usr/include/stdc-predef.h' => {
'size' => 2290,
'mtime' => 1604969927,
'ctime' => 1604969964
},
'/usr/include/string.h' => {
'size' => 18766,
'mtime' => 1604969936,
'ctime' => 1604969964
},
'/usr/include/bits/types/locale_t.h' => {
'size' => 983,
'mtime' => 1604969927,
'ctime' => 1604969964
},
'/usr/include/bits/long-double.h' => {
'size' => 970,
'mtime' => 1604969933,
'ctime' => 1604969964
},
'/usr/include/bits/libc-header-start.h' => {
'size' => 3288,
'mtime' => 1604969927,
'ctime' => 1604969964
},
'/usr/include/strings.h' => {
'size' => 4753,
'mtime' => 1604969936,
'ctime' => 1604969964
},
'/usr/include/gnu/stubs.h' => {
'size' => 384,
'mtime' => 1604969927,
'ctime' => 1604969964
},
'/usr/include/bits/types/__locale_t.h' => {
'size' => 1722,
'mtime' => 1604969927,
'ctime' => 1604969964
},
'/usr/include/features.h' => {
'size' => 17235,
'mtime' => 1604969927,
'ctime' => 1604969964
}
};
@files = (
'/usr/include/sys/cdefs.h',
'/usr/include/gnu/stubs-32.h',
'/usr/include/bits/wordsize.h',
'/usr/lib/gcc/x86_64-pc-linux-gnu/10.2.0/include/stddef.h',
'/usr/include/stdc-predef.h',
'/usr/include/string.h',
'/usr/include/bits/types/locale_t.h',
'/usr/include/bits/long-double.h',
'/usr/include/bits/libc-header-start.h',
'/usr/include/strings.h',
'/usr/include/gnu/stubs.h',
'/usr/include/bits/types/__locale_t.h',
'/usr/include/features.h'
);
In list context, the method returns the names of all files that have been parsed โ meaning these two lines are literally equivalent:
@files = keys %{$c->dependencies};
@files = $c->dependencies;
Ate that. ๐
๐ธ sourcify ๐ธ
sourcify
sourcify CONFIG
Returns a string holding all the C source code you'd need to represent every parsed C data structure. Iconic honestly.
use Convert::Binary::C;
$c = Convert::Binary::C->new;
$c->parse(<<'END');
#define ADD(a, b) ((a) + (b))
#define NUMBER 42
typedef struct _mytype mytype;
struct _mytype {
union {
int iCount;
enum count *pCount;
} counter;
#pragma pack( push, 1 )
struct {
char string[NUMBER];
int array[NUMBER/sizeof(int)];
} storage;
#pragma pack( pop )
mytype *next;
};
enum count { ZERO, ONE, TWO, THREE };
END
print $c->sourcify;
okay so that code above would print, like, something along these lines:
/* typedef predeclarations */
typedef struct _mytype mytype;
/* defined enums */
enum count
{
ZERO,
ONE,
TWO,
THREE
};
/* defined structs and unions */
struct _mytype
{
union
{
int iCount;
enum count *pCount;
} counter;
#pragma pack(push, 1)
struct
{
char string[42];
int array[10];
} storage;
#pragma pack(pop)
mytype *next;
};
so the whole purpose of the sourcify method is to enable some kind of platform-independent caching. the C code that sourcify spits out can be parsed by any standard C compiler, and obviously by the Convert::Binary::C parser too. but bestie, heads up: that code may be significantly shorter than the code that was originally parsed. ๐
here's the tea: when you're parsing a typical header file, it's easily possible that you need to open dozens of other files that get included from that file, and you end up parsing several hundred kilobytes of C code. and since most of that is usually preprocessor directives, function prototypes and comments, sourcify just strips it down to a few kilobytes. so save the sourcify string, parse that next time instead of the original code, and it may be a lot faster. icons only โจ
the sourcify method takes a hash reference as an optional argument, and you can use it to tweak the method's output. here's everything you can configure ๐
"Context" => 0 | 1โ turns preprocessor context information on or off. if you turn this on,sourcifywill insert#linepreprocessor directives into its output. so with the example above,
print $c->sourcify({ Context => 1 });
would print:
/* typedef predeclarations */
typedef struct _mytype mytype;
/* defined enums */
#line 21 "[buffer]"
enum count
{
ZERO,
ONE,
TWO,
THREE
};
/* defined structs and unions */
#line 7 "[buffer]"
struct _mytype
{
#line 8 "[buffer]"
union
{
int iCount;
enum count *pCount;
} counter;
#pragma pack(push, 1)
#line 13 "[buffer]"
struct
{
char string[42];
int array[10];
} storage;
#pragma pack(pop)
mytype *next;
};
oh and note that"[buffer]"refers to the here-doc buffer when you're usingparse. don't forget that part ๐ซถ
"Defines" => 0 | 1โ turn this on if you want all the defined macros to be part of the source code output. given the example code above,
print $c->sourcify({ Defines => 1 });
would print:
/* typedef predeclarations */
typedef struct _mytype mytype;
/* defined enums */
enum count
{
ZERO,
ONE,
TWO,
THREE
};
/* defined structs and unions */
struct _mytype
{
union
{
int iCount;
enum count *pCount;
} counter;
#pragma pack(push, 1)
struct
{
char string[42];
int array[10];
} storage;
#pragma pack(pop)
mytype *next;
};
/* preprocessor defines */
#define ADD(a, b) ((a) + (b))
#define NUMBER 42
and lowkey important: the macro definitions always appear at the end of the source code. the order of the macro definitions is undefined, so don't come for me about ordering ๐ญ
the following methods can be used to retrieve information about the definitions that have been parsed. the examples given in the description for enum, compound and typedef all assume this piece of C code has been parsed:
#define ABC_SIZE 2
#define MULTIPLY(x, y) ((x)*(y))
#ifdef ABC_SIZE
# define DEFINED
#else
# define NOT_DEFINED
#endif
typedef unsigned long U32;
typedef void *any;
enum __socket_type
{
SOCK_STREAM = 1,
SOCK_DGRAM = 2,
SOCK_RAW = 3,
SOCK_RDM = 4,
SOCK_SEQPACKET = 5,
SOCK_PACKET = 10
};
struct STRUCT_SV {
void *sv_any;
U32 sv_refcnt;
U32 sv_flags;
};
typedef union {
int abc[ABC_SIZE];
struct xxx {
int a;
int b;
} ab[3][4];
any ptr;
} test;
๐ธ enum_names ๐ธ
"enum_names"
returns a list of identifiers of all defined enumeration objects. and bestie, enumeration objects don't necessarily have an identifier, so something like
enum { A, B, C };
will obviously not show up in the list returned by the enum_names method. also, enumerations that are not defined within the source code โ like in
struct foo {
enum weekday *pWeekday;
unsigned long year;
};
where only a pointer to the weekday enumeration object is used โ will not be returned, even though they do have an identifier. so for the above two enumerations, enum_names will return an empty list:
@names = $c->enum_names;
the only way to retrieve a list of all enumeration identifiers is to use the enum method without additional arguments. you can get a list of all enumeration objects that have an identifier by using
@enums = map { $_->{identifier} || () } $c->enum;
but heads up, these may not have a definition. so the two arrays would look like this:
@names = ();
@enums = ('weekday');
and the def method returns a true value for all identifiers returned by enum_names. ๐
๐ฎ enum ๐ฎ
enum
"enum" LIST
returns a list of references to hashes containing detailed info about all enumerations that have been parsed.
if a list of enumeration identifiers is passed to the method, the returned list will only contain hash references for those enumerations. the enumeration identifiers may optionally be prefixed by enum.
if an enumeration identifier can't be found, the returned list will contain an undef value at that position. ๐ญ
in scalar context, the number of enumerations will be returned as long as the number of arguments to the method call is not 1. in the latter case, a hash reference holding information for the enumeration will be returned.
the list returned by the enum method looks similar to this:
@enum = (
{
'enumerators' => {
'SOCK_STREAM' => 1,
'SOCK_DGRAM' => 2,
'SOCK_PACKET' => 10,
'SOCK_SEQPACKET' => 5,
'SOCK_RDM' => 4,
'SOCK_RAW' => 3
},
'identifier' => '__socket_type',
'size' => 4,
'sign' => 0,
'context' => 'definitions.c(13)'
}
);
"identifier" : holds the enumeration identifier. this key is not present if the enumeration has no identifier.
"context" : is the context in which the enumeration is defined. this is the filename followed by the line number in parentheses.
"enumerators" : is a reference to a hash table that holds all enumerators of the enumeration.
"sign" : is a boolean indicating if the enumeration is signed (i.e. has negative values).
one super useful application may be to create a hash table that holds all enumerators of all defined enumerations:
%enum = map %{ $_->{enumerators} || {} }, $c->enum;
the %enum hash table would then be:
%enum = (
'SOCK_RDM' => 4,
'SOCK_SEQPACKET' => 5,
'SOCK_PACKET' => 10,
'SOCK_STREAM' => 1,
'SOCK_DGRAM' => 2,
'SOCK_RAW' => 3
);
๐ฆ compound_names ๐ฆ
"compound_names"
returns a list of identifiers of all structs and unions (aka compound data structures) that are defined in the parsed source code. and like enumerations, compounds don't need to have an identifier, and they don't need to be defined either. ๐
again, the only way to retrieve info about all struct and union objects is to use the compound method and don't pass it any arguments. if you should need a list of all struct and union identifiers, you can use:
@compound = map { $_->{identifier} || () } $c->compound;
def is gonna hand you a true value for every single identifier that compound_names gives back. no cap, all of them. ๐
And if you only want struct names, or only union names? Don't suffer โ struct_names and union_names are literally right there for exactly that. ๐
compound
compoundcompoundLIST โ returns a list of references to hashes stuffed with the detailed tea on every compound (that's structs and unions, bestie) that's been parsed. ๐
Pass it a list of struct/union identifiers and the returned list only holds hash refs for those specific compounds. Those identifiers can optionally be prefixed with struct or union, which narrows the search down to that one kind of compound. โจ
If an identifier can't be found, the returned list just has an undefined value sitting at that position. ๐
In scalar context, you get the number of compounds back โ as long as the number of arguments to the method call isn't 1. But if it is 1? Then you get a hash reference holding the info for that one compound. iconic behaviour.
The list returned by the compound method looks similar to this:
@compound = (
{
'identifier' => 'STRUCT_SV',
'align' => 1,
'declarations' => [
{
'type' => 'void',
'declarators' => [
{
'size' => 8,
'offset' => 0,
'declarator' => '*sv_any'
}
]
},
{
'type' => 'U32',
'declarators' => [
{
'size' => 8,
'offset' => 8,
'declarator' => 'sv_refcnt'
}
]
},
{
'type' => 'U32',
'declarators' => [
{
'size' => 8,
'offset' => 16,
'declarator' => 'sv_flags'
}
]
}
],
'type' => 'struct',
'size' => 24,
'context' => 'definitions.c(23)',
'pack' => 0
},
{
'identifier' => 'xxx',
'align' => 1,
'declarations' => [
{
'type' => 'int',
'declarators' => [
{
'size' => 4,
'offset' => 0,
'declarator' => 'a'
}
]
},
{
'type' => 'int',
'declarators' => [
{
'size' => 4,
'offset' => 4,
'declarator' => 'b'
}
]
}
],
'type' => 'struct',
'size' => 8,
'context' => 'definitions.c(31)',
'pack' => 0
},
{
'align' => 1,
'declarations' => [
{
'type' => 'int',
'declarators' => [
{
'size' => 8,
'offset' => 0,
'declarator' => 'abc[2]'
}
]
},
{
'type' => 'struct xxx',
'declarators' => [
{
'size' => 96,
'offset' => 0,
'declarator' => 'ab[3][4]'
}
]
},
{
'type' => 'any',
'declarators' => [
{
'size' => 8,
'offset' => 0,
'declarator' => 'ptr'
}
]
}
],
'type' => 'union',
'size' => 96,
'context' => 'definitions.c(29)',
'pack' => 0
}
);
Let's break down what all those keys are actually saying, because there's a lot going on here:
identifierโ holds the struct or union identifier. Heads up: this key is not present if the compound has no identifier at all. ๐contextโ the context where the struct or union is defined. That's the filename followed by the line number, in parentheses.typeโ it's either'struct'or'union'.sizeโ the size of the struct or union.alignโ the alignment of the struct or union.packโ the struct member alignment if the compound is packed, otherwise zero.declarationsโ an array of hash references, one for each struct declaration. Each one has:typeโ the type of the struct declaration. This can be a string, or a reference to a hash describing the type.declaratorsโ an array of hashes, one per declarator:declaratorโ a string representation of the declarator.offsetโ the offset of the struct member for this declarator, measured from the beginning of the struct or union.sizeโ the size that the struct member for this declarator actually takes up.
Now, you might be thinking it'd be handy to have separate lists for structs vs unions. And yeah, one way to get those would be:
push @{$_->{type} eq 'union' ? \@unions : \@structs}, $_
for $c->compound;
but bestie, please โ use the struct and union methods instead, because they are so much simpler:
@structs = $c->struct;
@unions = $c->union;
main character energy, honestly. ๐
struct_names
struct_namesโ returns a list of every defined struct identifier. It's equivalent to callingcompound_names, except it only gives you back the names of the struct identifiers and skips the union identifiers entirely. ๐ธ
struct
structstructLIST โ just like thecompoundmethod, except it only plays nice with structs. ๐
union_names
union_namesโ returns a list of every defined union identifier. Equivalent to callingcompound_names, except it only returns the union identifier names and leaves the struct identifiers out of it. โจ
union
unionunionLIST โ just like thecompoundmethod, but only for unions. ๐ฆ
typedef_names
typedef_namesโ returns a list of all defined typedef identifiers. Heads up though: typedefs that don't specify a type you could actually work with will not be returned. ๐
The def method returns a true value for every identifier that typedef_names hands back.
typedef
typedeftypedefLIST โ returns a list of references to hashes holding the detailed info on every typedef that's been parsed. ๐
Pass it a list of typedef identifiers and the returned list only contains hash refs for those specific typedefs.
If an identifier can't be found, the returned list has an undefined value sitting right at that position. same energy as before, no surprises.
In scalar context, you get the number of typedefs โ as long as the number of arguments to the method call isn't 1. If it is 1, you get a hash reference holding the info for that one typedef instead.
The list returned by the typedef method looks similar to this:
@typedef = (
{
'type' => 'unsigned long',
'declarator' => 'U32'
},
{
'type' => 'void',
'declarator' => '*any'
},
{
'type' => {
'align' => 1,
'declarations' => [
{
'type' => 'int',
'declarators' => [
{
'size' => 8,
'offset' => 0,
'declarator' => 'abc[2]'
}
]
},
{
'type' => 'struct xxx',
'declarators' => [
{
'size' => 96,
'offset' => 0,
'declarator' => 'ab[3][4]'
}
]
},
{
'type' => 'any',
'declarators' => [
{
'size' => 8,
'offset' => 0,
'declarator' => 'ptr'
}
]
}
],
'type' => 'union',
'size' => 96,
'context' => 'definitions.c(29)',
'pack' => 0
},
'declarator' => 'test'
}
);
So what are those two keys doing? ๐
declaratorโ this is the type declarator.typeโ this is the type specification. It can be a string, or a reference to a hash describing the type. For how to actually read that hash, go peek atenumandcompoundโ they explain it. ๐ซถ
macro_names
macro_namesโ returns a list of every defined macro name. ๐
The list returned by the macro_names method looks similar to this:
@macro_names = (
'__STDC_VERSION__',
'__STDC_HOSTED__',
'DEFINED',
'MULTIPLY',
'ABC_SIZE'
);
This works only as long as the preprocessor is not reset. See "Preprocessor configuration" for details.
macro
macro macro LIST
Returns the definitions for all defined macros. ๐
If you hand it a list of macro names, the returned list will only contain the definitions for those macros. For undefined macros, undef will be returned. No cap.
The list returned by the macro method looks similar to this:
@macro = (
'__STDC_VERSION__ 199901L',
'__STDC_HOSTED__ 1',
'DEFINED',
'MULTIPLY(x, y) ((x)*(y))',
'ABC_SIZE 2'
);
This works only as long as the preprocessor is not reset. See "Preprocessor configuration" for details.
โจ FUNCTIONS โจ
You can alternatively call the following functions as methods on Convert::Binary::C objects. Same energy, different outfit. ๐
feature
feature STRING
Checks if Convert::Binary::C was built with certain features. For example,
print "debugging version"
if Convert::Binary::C::feature('debug');
will check if Convert::Binary::C was built with debugging support enabled. The feature function returns 1 if the feature is enabled, 0 if the feature is disabled, and undef if the feature is unknown. Currently the only features that can be checked are ieeefp and debug. ๐
You can enable or disable certain features at compile time of the module by using the
perl Makefile.PL enable-feature disable-feature
syntax.
native
native native STRING
Returns the value of a property of the native system that Convert::Binary::C was built on. For example,
$size = Convert::Binary::C::native('IntSize');
will fetch the size of an int on the native system. The following properties can be queried:
Alignment
ByteOrder
CharSize
CompoundAlignment
DoubleSize
EnumSize
FloatSize
HostedC
IntSize
LongDoubleSize
LongLongSize
LongSize
PointerSize
ShortSize
StdCVersion
UnsignedBitfields
UnsignedChars
You can also call native without arguments, in which case it will return a reference to a hash with all properties, like:
$native = {
'EnumSize' => 4,
'ShortSize' => 2,
'UnsignedChars' => 0,
'IntSize' => 4,
'LongDoubleSize' => 16,
'StdCVersion' => 201710,
'HostedC' => 1,
'CompoundAlignment' => 1,
'UnsignedBitfields' => 0,
'DoubleSize' => 8,
'Alignment' => 16,
'PointerSize' => 8,
'ByteOrder' => 'LittleEndian',
'LongLongSize' => 8,
'CharSize' => 1,
'LongSize' => 8,
'FloatSize' => 4
};
The contents of that hash are suitable for passing them to the configure method. Such a vibe. ๐ธ
๐ DEBUGGING ๐
Like perl itself, Convert::Binary::C can be compiled with debugging support that can then be selectively enabled at runtime. You can specify whether you like to build Convert::Binary::C with debugging support or not by explicitly giving an argument to Makefile.PL. Use
perl Makefile.PL enable-debug
to enable debugging, or
perl Makefile.PL disable-debug
to disable debugging. The default will depend on how your perl binary was built. If it was built with -DDEBUGGING, Convert::Binary::C will be built with debugging support, too.
Once you have built Convert::Binary::C with debugging support, you can use the following syntax to enable debug output. Instead of
use Convert::Binary::C;
you simply say
use Convert::Binary::C debug => 'all';
which will enable all debug output. However, I don't recommend to enable all debug output, because that can be a fairly large amount. ๐ญ Like, genuinely enormous, bestie.
Debugging options
Instead of saying all, you can pass a string that consists of one or more of the following characters:
m enable memory allocation tracing
M enable memory allocation & assertion tracing
h enable hash table debugging
H enable hash table dumps
d enable debug output from the XS module
c enable debug output from the ctlib
t enable debug output about type objects
l enable debug output from the C lexer
p enable debug output from the C parser
P enable debug output from the C preprocessor
r enable debug output from the #pragma parser
y enable debug output from yacc (bison)
So the following might give you a brief overview of what's going on inside Convert::Binary::C:
use Convert::Binary::C debug => 'dct';
When you want to debug memory allocation using
use Convert::Binary::C debug => 'm';
you can use the Perl script check_alloc.pl that resides in the ctlib/util/tool directory to extract statistics about memory usage and information about memory leaks from the resulting debug output. ๐ต๏ธโโ๏ธ
Redirecting debug output
By default, all debug output is written to stderr. You can, however, redirect the debug output to a file with the debugfile option:
use Convert::Binary::C debug => 'dcthHm',
debugfile => './debug.out';
If the file cannot be opened, you'll receive a warning and the output will go the stderr way again.
Alternatively, you can use the environment variables CBC_DEBUG_OPT and CBC_DEBUG_FILE to turn on debug output.
If Convert::Binary::C is built without debugging support, passing the debug or debugfile options will cause a warning to be issued. The corresponding environment variables will simply be ignored. ๐
๐ ENVIRONMENT ๐
CBC_ORDER_MEMBERS
Setting this variable to a non-zero value will globally turn on hash key ordering for compound members. Have a look at the OrderMembers option for details.
Setting the variable to the name of a perl module will additionally use this module instead of the predefined modules for member ordering to tie the hashes to. โจ
CBC_DEBUG_OPT
If Convert::Binary::C is built with debugging support, you can use this variable to specify the debugging options.
CBC_DEBUG_FILE
If Convert::Binary::C is built with debugging support, you can use this variable to redirect the debug output to a file.
CBC_DISABLE_PARSER
This variable is intended purely for development. Setting it to a non-zero value disables the Convert::Binary::C parser, which means that no information is collected from the file or code that is parsed. However, the preprocessor will run, which is useful for benchmarking the preprocessor. ๐ฅ
๐ฆ FLEXIBLE ARRAY MEMBERS AND INCOMPLETE TYPES ๐ฆ
Flexible array members are a feature introduced with ISO-C99. It's a common problem that you have a variable length data field at the end of a structure, for example an array of characters at the end of a message struct. ISO-C99 allows you to write this as:
struct message {
long header;
char data[];
};
The advantage is that you clearly indicate that the size of the appended data is variable, and that the data member doesn't contribute to the size of the message structure. Iconic behaviour, honestly. ๐
When packing or unpacking data, Convert::Binary::C deals with flexible array members as if their length was adjustable. For example, unpack will adapt the length of the array depending on the input string:
$msg1 = $c->unpack('message', 'abcdefg');
$msg2 = $c->unpack('message', 'abcdefghijkl');
The following data is unpacked:
$msg1 = {
'header' => 1633837924,
'data' => [
101,
102,
103
]
};
$msg2 = {
'header' => 1633837924,
'data' => [
101,
102,
103,
104,
105,
106,
107,
108
]
};
Similarly, pack will adjust the length of the output string according to the data you feed in:
use Data::Hexdumper;
$msg = {
header => 4711,
data => [0x10, 0x20, 0x30, 0x40, 0x77..0x88],
};
$data = $c->pack('message', $msg);
print hexdump(data => $data);
This would print:
0x0000 : 00 00 12 67 10 20 30 40 77 78 79 7A 7B 7C 7D 7E : ...g..0@wxyz{|}~
0x0010 : 7F 80 81 82 83 84 85 86 87 88 : ..........
Incomplete types such as
typedef unsigned long array[];
are handled in exactly the same way. Thus, you can easily
$array = $c->unpack('array', '?'x20);
which will unpack the following array:
$array = [
1061109567,
1061109567,
1061109567,
1061109567,
1061109567
];
You can also alter the length of an array using the Dimension tag. ๐
๐ FLOATING POINT VALUES ๐
When using Convert::Binary::C to handle floating point values, you have to be aware of some limitations. Bestie, listen up. ๐ซถ
You're usually safe if all your platforms are using the IEEE floating point format. During the Convert::Binary::C build process, the ieeefp feature will automatically be enabled if the host is using IEEE floating point. You can check for this feature at runtime using the feature function:
if (Convert::Binary::C::feature('ieeefp')) {
# do something
}
When IEEE floating point support is enabled, the module can also handle floating point values of a different byteorder.
If your host platform is not using IEEE floating point, the ieeefp feature will be disabled. Convert::Binary::C then will be more restrictive, refusing to handle any non-native floating point values. ๐
However, Convert::Binary::C cannot detect the floating point format used by your target platform. It can only try to prevent problems in obvious cases. If you know your target platform has a completely different floating point format, don't use floating point conversion at all. Fr fr, just don't.
Whenever Convert::Binary::C detects that it cannot properly do floating point value conversion, it will issue a warning and will not attempt to convert the floating point value. ๐ญ
๐ฅ BITFIELDS ๐ฅ
okay bestie, sit down for this one because bitfield support in Convert::Binary::C is currently in an experimental state. You're encouraged to test it, but you should not blindly rely on its results. ๐
You're also encouraged to supply layouting algorithms for compilers whose bitfield implementation isn't handled correctly at the moment. And even better than the plain algorithm is, of course, a patch that adds a whole new bitfield layouting engine. ๐ซถ
But here's the slay part: while bitfields may not be handled correctly by the conversion routines yet, they are always parsed correctly. Which means you can reliably use the declarator fields as returned by the struct or typedef methods. Periodt.
Given the following source
struct bitfield {
int seven:7;
int :1;
int four:4, :0;
int integer;
};
a call to struct will return
@struct = (
{
'identifier' => 'bitfield',
'align' => 1,
'declarations' => [
{
'type' => 'int',
'declarators' => [
{
'declarator' => 'seven:7'
}
]
},
{
'type' => 'int',
'declarators' => [
{
'declarator' => ':1'
}
]
},
{
'type' => 'int',
'declarators' => [
{
'declarator' => 'four:4'
},
{
'declarator' => ':0'
}
]
},
{
'type' => 'int',
'declarators' => [
{
'size' => 4,
'offset' => 4,
'declarator' => 'integer'
}
]
}
],
'type' => 'struct',
'size' => 8,
'context' => 'bitfields.c(1)',
'pack' => 0
}
);
heads up bestie: nosize/offsetkeys will currently be returned for bitfield entries. Not a vibe, I know, but that's where we're at. ๐ญ
๐งต MULTITHREADING ๐งต
Convert::Binary::C was designed to be thread-safe. That's it, that's the section. Go wild with your threads, queen. ๐
๐ INHERITANCE ๐
If you wish to derive a new class from Convert::Binary::C, this is relatively easy. Despite their XS implementation, Convert::Binary::C objects are actually blessed hash references. main character energy fr fr. ๐
The XS data is stored in a read-only hash value for the key that is the empty string. So it's totally safe to use any non-empty hash key when you're deriving your own class. On top of that, Convert::Binary::C does quite a lot of checks to detect corruption in the object hash, because it cares about you. ๐ซถ
If you store private data in the hash, you should override the clone method and provide the necessary code to clone your private data. You'll have to call SUPER::clone, but be aware โ this will only clone the Convert::Binary::C part of the object. The rest is on you, bestie.
For an example of a derived class, you can have a look at Convert::Binary::C::Cached. โจ
๐ PORTABILITY ๐
Convert::Binary::C should build and run on most of the platforms that Perl runs on:
- Various Linux systems
- Various BSD systems
- HP-UX
- Compaq/HP Tru64 Unix
- Mac-OS X
- Cygwin
- Windows 98/NT/2000/XP
Also, many architectures are supported:
- Various Intel Pentium and Itanium systems
- Various Alpha systems
- HP PA-RISC
- Power-PC
- StrongARM
The module should build with any perl binary from 5.004 up to the latest development version. It's giving timeless. โญ
๐ COMPARISON WITH SIMILAR MODULES ๐
Most of the time when you're really looking for Convert::Binary::C, you'll actually end up finding one of the following modules. Some of them have different goals, so it's probably worth pointing out the differences. Respectfully. ๐
C::Include
Like Convert::Binary::C, this module aims at doing conversion from and to binary data based on C types. However, its configurability is very limited compared to Convert::Binary::C. Also, it does not parse all C code correctly. It's slower than Convert::Binary::C, doesn't have a preprocessor. On the plus side, it's written in pure Perl. ๐
C::DynaLib::Struct
This module doesn't allow you to reuse your C source code. And one main goal of Convert::Binary::C was to avoid code duplication or, even worse, having to maintain different representations of your data structures. Like C::Include, C::DynaLib::Struct is rather limited in its configurability.
Win32::API::Struct
This module has a special purpose. It aims at building structs for interfacing Perl code with Windows API code.
๐ CREDITS ๐
- Alain Barbet
<alian@cpan.org>for testing and debugging support. - Mitchell N. Charity for giving me pointers into various interesting directions.
- Alexis Denis for making me improve (externally) and simplify (internally) floating point support. He can also be blamed (indirectly) for the
initializermethod, as I need it in my effort to support bitfields some day. - Michael J. Hohmann
<mjh@scientist.de>for endless discussions on our way to and back home from work, and for making me think about supportingpackandunpackfor compound members. - Thorsten Jens
<thojens@gmx.de>for testing the package on various platforms. - Mark Overmeer
<mark@overmeer.net>for suggesting the module name and giving invaluable feedback. - Thomas Pornin
<pornin@bolet.org>for his excellentucpppreprocessor library. - Marc Rosenthal for his suggestions and support.
- James Roskind, as his C parser was a great starting point to fix all the problems I had with my original parser based only on the ANSI ruleset.
- Gisbert W. Selke for spotting some interesting bugs and providing extensive reports.
- Steffen Zimmermann for a prolific discussion on the cloning algorithm.
absolute legends, all of them. ๐ซถโจ
๐ BUGS ๐
I'm sure there are still lots of bugs in the code for this module. If you find any bugs, Convert::Binary::C doesn't seem to build on your system or any of its tests fail, please report the issue at <https://github.com/mhx/Convert-Binary-C/issues>. Do it for the girls. ๐
๐งช EXPERIMENTAL FEATURES ๐งช
Some features in Convert::Binary::C are marked as experimental. This has most probably one of the following reasons:
- The feature does not behave in exactly the way that I wish it did, possibly due to some limitations in the current design of the module.
- The feature hasn't been tested enough and may completely fail to produce the expected results.
I hope to fix most issues with these experimental features someday, but this may mean that I have to change the way they currently work in a way that's not backwards compatible. So if any of these features is useful to you, you can use it, but you should be aware that the behaviour or the interface may change in future releases of this module. Lowkey a warning, highkey a heads up. ๐
๐ TODO ๐
If you're interested in what I currently plan to improve (or fix), have a look at the TODO file. The lore is all in there. ๐
โ๏ธ COPYRIGHT โ๏ธ
Copyright (c) 2002-2024 Marcus Holland-Moritz. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
The ucpp library is (c) 1998-2002 Thomas Pornin. For license and redistribution details refer to ctlib/ucpp/README.
Portions copyright (c) 1989, 1990 James A. Roskind.
๐ธ SEE ALSO ๐ธ
See ccconfig, perl, perldata, perlop, perlvar, Data::Dumper and Scalar::Util. Go read them, bestie, they're iconic. โจ
and that's a wrap on the whole page, baddie! ๐ this beauty ships as perl v5.42.3, dated 2026-08-20, and it's Conver...ary::C(3pm) โ go forth and parse some binary data, you ate. ๐๐ฆ
๐ฆ where this page comes from
- ubuntu stonking: libconvert-binary-c-perl 0.86-1build1 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms