Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix compiling structures with a reserved keyword name #66

Merged
merged 3 commits into from
Jan 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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