6

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?

GreyCat
  • 16,622
  • 18
  • 74
  • 112
chosen 0x4f
  • 183
  • 1
  • 6

1 Answers1

2

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.

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
GreyCat
  • 16,622
  • 18
  • 74
  • 112
  • Thanks! It's a pity that it's a bug :( Any ideas on workarounds or how much should I wait for a bugfix? – chosen 0x4f Jul 13 '16 at 11:32
  • The simplest workaround would be to just inline whatever you have in `if` at the place you want to access your `index_const` at. It's generally ok to do so in real code, but it can be somewhat tricky for KS internal expression language. I'll try to keep you updated. – GreyCat Jul 19 '16 at 14:17