Skip to content

Commit

Permalink
Fix compiling structures with a reserved keyword name
Browse files Browse the repository at this point in the history
  • Loading branch information
Schamper committed Jan 6, 2024
1 parent ffbf4f8 commit d1b024f
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
7 changes: 6 additions & 1 deletion dissect/cstruct/compiler.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import keyword
import struct
from collections import OrderedDict
from textwrap import dedent
Expand Down Expand Up @@ -75,6 +76,8 @@ def compile(self, structure: Structure) -> Structure:
return structure

structure_name = structure.name
if keyword.iskeyword(structure_name):
structure_name += "_"

try:
# Generate struct class based on provided structure type
Expand Down Expand Up @@ -104,7 +107,9 @@ def compile(self, structure: Structure) -> Structure:
}

exec(code_object, env)
return env[structure_name](self.cstruct, structure, source)
klass = env[structure_name]
klass.__name__ = structure.name
return klass(self.cstruct, structure, source)

def gen_struct_class(self, name: str, structure: Structure) -> str:
blocks = []
Expand Down
25 changes: 25 additions & 0 deletions tests/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -546,3 +546,28 @@ def test_report_array_size_mismatch():

with pytest.raises(ArraySizeError):
a.dumps()


@pytest.mark.parametrize("compiled", [True, False])
def test_reserved_keyword(compiled: bool):
cdef = """
struct in {
uint8 a;
};
struct class {
uint8 a;
};
struct for {
uint8 a;
};
"""
cs = cstruct.cstruct(endian="<")
cs.load(cdef, compiled=compiled)

for name in ["in", "class", "for"]:
assert name in cs.typedefs
assert verify_compiled(cs.resolve(name), compiled)

assert cs.resolve(name)(b"\x01").a == 1

0 comments on commit d1b024f

Please sign in to comment.