fox-it / dissect.cstruct_legacy

A no-nonsense c-like structure parsing library for Python
MIT License
239 stars 25 forks source link

bitfield parsing problem when the total size of bitfields exceeds the type definition or the bitfield is not aligned #20

Open iamlook opened 2 years ago

iamlook commented 2 years ago

When the total size of the bitfields exceeds a type definition (such as the defined uint16 but the actual consecutively defined bitfields exceed 16 bits), or the fields are not aligned, the parsing will fail.

Example to reproduce the problem:

struct ppb
{
    uint16 igr : 1;
    uint16 l2crc : 1;
    uint16 len : 14;

    uint16 s : 4;
    uint16 type : 2;
    uint16 cpu_if : 1;
    uint16 s_if : 1;
    uint16 c_if : 1;
    uint16 p_if : 1;
    uint16 dscp : 6;

    uint16 rfc : 1;
    uint16 llc : 1;
    uint16 oam : 1;
    uint16 tcp : 1;
    uint16 udp : 1;
    uint16 bgd : 11;

    uint16 end : 11;
    uint16 l3 : 1;
    uint16 l4 : 1;
    uint16 rsvd : 3;

    uint16 eiden : 1;
    uint16 eid : 3;
    uint16 prien : 1;
    uint16 pri : 3;
    uint16 keep : 1;
    uint16 vel : 1;
    uint16 lrn : 1;
    uint16 cidx : 5;
};

try to fix it, modify dissect/cstruct/types/structure.py ,

--- a/structure.py
+++ b/structure.py
@@ -137,6 +137,8 @@ class Structure(BaseType):
             offset = stream.tell()

             if field.bits:
+                if bit_buffer._type and (bit_buffer._remaining == 0 or bit_buffer._remaining < field.bits):
+                    bit_buffer.flush()
                 bit_buffer.write(field.type, getattr(data, field.name), field.bits)
                 continue

pls check.

Sorry for my poor English. Thanks for the excellent project.