chosen 0x4f - 1 year ago 110
Python Question

Kaitai Struct: calculated instances with a condition

I'm trying to get Kaitai Struct to reverse engineer a binary structure.

seq
fields work as intended, but
instances
don't seem to work as I want them to.

My binary format includes a header with a list of constants that I parse as
header
field with
consts
array subfield:

types:
seq:
# ...
- id: consts
type: u8
repeat: expr
repeat-expr: 0x10


However, when I try to use the following declaration:

instances:
index_const:
if: idx >= 0x40 and idx <= 0x4f


This one is intended to calculate a value of
index_const
by looking up into array of
header.consts
if and only if
idx
is in range of [0x40..0x4f].

I use Python as my target language and I assume that it should generate a code like:

    @property
def index_const(self):
if hasattr(self, '_m_index_const'):
return self._m_index_const
if self.idx >= 64 and self.idx <= 79:
return self._m_index_const


However, what I get is:

    @property
def index_const(self):
if hasattr(self, '_m_index_const'):
return self._m_index_const


Yeah, I guess it should be considered a bug. At the very least, compiler should either allow to use if in value instances and process it properly, or disallow if and issue an error message.
Thinking of it, I see no reason why if is allowed for regular instances, but treated this way for value instances.