Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:
  header:
    seq:
      # ...
      - id: consts
        type: u8
        repeat: expr
        repeat-expr: 0x10

However, when I try to use the following declaration:

instances:
  index_const:
    value: '_root.header.consts[idx - 0x40]'
    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:
            self._m_index_const = self._root.header.consts[(self.idx - 64)];
            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

        self._m_index_const = self._root.header.consts[(self.idx - 64)];
        return self._m_index_const

Is it just me, am I missing something obvious, or is it a bug in Kaitai Struct?

like image 595
chosen 0x4f Avatar asked Jul 12 '16 16:07

chosen 0x4f


1 Answers

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.

Thanks for reporting it, I've submitted an issue.


Update: The issue is now marked as closed.

if_instances test now tests that. ... Closing this one as solved.

like image 150
GreyCat Avatar answered Oct 04 '22 22:10

GreyCat