dissect.cstruct 5.0.dev21__py3-none-any.whl → 5.0.dev23__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dissect/cstruct/__init__.py +12 -0
- dissect/cstruct/bitbuffer.py +5 -3
- dissect/cstruct/compiler.py +21 -10
- dissect/cstruct/cstruct.py +8 -6
- dissect/cstruct/declarative.py +3 -2
- dissect/cstruct/exception.py +29 -15
- dissect/cstruct/expression.py +142 -79
- dissect/cstruct/lexer.py +15 -6
- dissect/cstruct/parser.py +77 -34
- dissect/cstruct/types/base.py +27 -5
- dissect/cstruct/types/char.py +8 -4
- dissect/cstruct/types/enum.py +2 -1
- dissect/cstruct/types/int.py +7 -1
- dissect/cstruct/types/leb128.py +2 -1
- dissect/cstruct/types/packed.py +11 -6
- dissect/cstruct/types/pointer.py +6 -2
- dissect/cstruct/types/structure.py +11 -2
- dissect/cstruct/types/wchar.py +16 -8
- dissect/cstruct/util.py +22 -5
- {dissect_cstruct-5.0.dev21.dist-info → dissect_cstruct-5.0.dev23.dist-info}/METADATA +1 -1
- dissect_cstruct-5.0.dev23.dist-info/RECORD +32 -0
- dissect_cstruct-5.0.dev21.dist-info/RECORD +0 -32
- {dissect_cstruct-5.0.dev21.dist-info → dissect_cstruct-5.0.dev23.dist-info}/WHEEL +0 -0
- {dissect_cstruct-5.0.dev21.dist-info → dissect_cstruct-5.0.dev23.dist-info}/entry_points.txt +0 -0
- {dissect_cstruct-5.0.dev21.dist-info → dissect_cstruct-5.0.dev23.dist-info}/licenses/COPYRIGHT +0 -0
- {dissect_cstruct-5.0.dev21.dist-info → dissect_cstruct-5.0.dev23.dist-info}/licenses/LICENSE +0 -0
- {dissect_cstruct-5.0.dev21.dist-info → dissect_cstruct-5.0.dev23.dist-info}/top_level.txt +0 -0
dissect/cstruct/__init__.py
CHANGED
|
@@ -4,10 +4,16 @@ from dissect.cstruct.bitbuffer import BitBuffer
|
|
|
4
4
|
from dissect.cstruct.cstruct import cstruct, ctypes, ctypes_type
|
|
5
5
|
from dissect.cstruct.dump import dumpstruct, hexdump
|
|
6
6
|
from dissect.cstruct.exception import (
|
|
7
|
+
DefinitionError,
|
|
7
8
|
Error,
|
|
9
|
+
ExpressionParserError,
|
|
10
|
+
LexerError,
|
|
8
11
|
NullPointerDereference,
|
|
9
12
|
ParserError,
|
|
13
|
+
ReadError,
|
|
10
14
|
ResolveError,
|
|
15
|
+
UnknownIdentifierError,
|
|
16
|
+
WriteError,
|
|
11
17
|
)
|
|
12
18
|
from dissect.cstruct.expression import Expression
|
|
13
19
|
from dissect.cstruct.types import (
|
|
@@ -60,24 +66,30 @@ __all__ = [
|
|
|
60
66
|
"BitBuffer",
|
|
61
67
|
"Char",
|
|
62
68
|
"CharArray",
|
|
69
|
+
"DefinitionError",
|
|
63
70
|
"Enum",
|
|
64
71
|
"Error",
|
|
65
72
|
"Expression",
|
|
73
|
+
"ExpressionParserError",
|
|
66
74
|
"Field",
|
|
67
75
|
"Flag",
|
|
68
76
|
"Int",
|
|
69
77
|
"JSONEncoder",
|
|
78
|
+
"LexerError",
|
|
70
79
|
"MetaType",
|
|
71
80
|
"NullPointerDereference",
|
|
72
81
|
"Packed",
|
|
73
82
|
"ParserError",
|
|
74
83
|
"Pointer",
|
|
84
|
+
"ReadError",
|
|
75
85
|
"ResolveError",
|
|
76
86
|
"Structure",
|
|
77
87
|
"Union",
|
|
88
|
+
"UnknownIdentifierError",
|
|
78
89
|
"Void",
|
|
79
90
|
"Wchar",
|
|
80
91
|
"WcharArray",
|
|
92
|
+
"WriteError",
|
|
81
93
|
"asdict",
|
|
82
94
|
"asjson",
|
|
83
95
|
"cstruct",
|
dissect/cstruct/bitbuffer.py
CHANGED
|
@@ -2,6 +2,8 @@ from __future__ import annotations
|
|
|
2
2
|
|
|
3
3
|
from typing import TYPE_CHECKING, BinaryIO
|
|
4
4
|
|
|
5
|
+
from dissect.cstruct.exception import DefinitionError
|
|
6
|
+
|
|
5
7
|
if TYPE_CHECKING:
|
|
6
8
|
from dissect.cstruct.types import BaseType
|
|
7
9
|
|
|
@@ -20,7 +22,7 @@ class BitBuffer:
|
|
|
20
22
|
def read(self, field_type: type[BaseType], bits: int) -> int:
|
|
21
23
|
if self._remaining == 0 or self._type != field_type:
|
|
22
24
|
if field_type.__size__ is None:
|
|
23
|
-
raise
|
|
25
|
+
raise DefinitionError("Reading variable-length fields is unsupported")
|
|
24
26
|
|
|
25
27
|
self._type = field_type
|
|
26
28
|
self._remaining = field_type.__size__ * 8
|
|
@@ -33,7 +35,7 @@ class BitBuffer:
|
|
|
33
35
|
self._buffer = int.from_bytes(self._buffer, "big")
|
|
34
36
|
|
|
35
37
|
if bits > self._remaining:
|
|
36
|
-
raise
|
|
38
|
+
raise DefinitionError("Reading straddled bits is unsupported")
|
|
37
39
|
|
|
38
40
|
if self.endian == "<":
|
|
39
41
|
v = self._buffer & ((1 << bits) - 1)
|
|
@@ -52,7 +54,7 @@ class BitBuffer:
|
|
|
52
54
|
self.flush()
|
|
53
55
|
|
|
54
56
|
if field_type.__size__ is None:
|
|
55
|
-
raise
|
|
57
|
+
raise DefinitionError("Writing variable-length fields is unsupported")
|
|
56
58
|
|
|
57
59
|
self._remaining = field_type.__size__ * 8
|
|
58
60
|
self._type = field_type
|
dissect/cstruct/compiler.py
CHANGED
|
@@ -12,7 +12,13 @@ from operator import itemgetter
|
|
|
12
12
|
from textwrap import indent
|
|
13
13
|
from typing import TYPE_CHECKING, Any
|
|
14
14
|
|
|
15
|
-
from dissect.cstruct.exception import
|
|
15
|
+
from dissect.cstruct.exception import (
|
|
16
|
+
DefinitionError,
|
|
17
|
+
EOFError,
|
|
18
|
+
Error,
|
|
19
|
+
ReadError,
|
|
20
|
+
WriteError,
|
|
21
|
+
)
|
|
16
22
|
from dissect.cstruct.expression import SOURCE_GLOBALS, Expression
|
|
17
23
|
from dissect.cstruct.types import (
|
|
18
24
|
Array,
|
|
@@ -212,7 +218,7 @@ def _field_bytes(type_: type[BaseType], value: Any, endian: str) -> bytes:
|
|
|
212
218
|
"""Return the bytes of a char or wchar field that isn't of the right type yet or doesn't fit."""
|
|
213
219
|
buf = type_.dumps(type_.__default__() if value is None else value, endian=endian)
|
|
214
220
|
if len(buf) > type_.__size__:
|
|
215
|
-
raise
|
|
221
|
+
raise WriteError(f"Expected {type_.__size__} bytes for {type_.__name__}, got {len(buf)} instead.")
|
|
216
222
|
return buf
|
|
217
223
|
|
|
218
224
|
|
|
@@ -241,6 +247,11 @@ _GLOBALS = {
|
|
|
241
247
|
"_struct_write": StructureMetaType._write,
|
|
242
248
|
"_union_write": UnionMetaType._write,
|
|
243
249
|
"_struct_error": struct.error,
|
|
250
|
+
"_Error": Error,
|
|
251
|
+
"_EOFError": EOFError,
|
|
252
|
+
"_ReadError": ReadError,
|
|
253
|
+
"_WriteError": WriteError,
|
|
254
|
+
"_DefinitionError": DefinitionError,
|
|
244
255
|
"_field_bytes": _field_bytes,
|
|
245
256
|
"_array_values": _array_values,
|
|
246
257
|
"_or_default": _or_default,
|
|
@@ -552,13 +563,13 @@ class _ReadSourceGenerator(_SourceGenerator):
|
|
|
552
563
|
# Integer fields that were read before are used directly
|
|
553
564
|
types = {field._name: field.type for field in self.fields}
|
|
554
565
|
variables = {name: f"int({var})" for name, var in self._assigned if issubclass(types[name], _INTEGER_TYPES)}
|
|
555
|
-
|
|
556
|
-
count = num_entries.source(variables, context)
|
|
557
|
-
except ExpressionParserError:
|
|
558
|
-
# Invalid expressions raise their error when reading the array
|
|
559
|
-
return read
|
|
566
|
+
count = num_entries.source(variables, context)
|
|
560
567
|
|
|
561
|
-
|
|
568
|
+
# E.g. a division by a field that is zero.
|
|
569
|
+
message = f"Invalid array size '{num_entries.expression}': "
|
|
570
|
+
lines.append(f"try: _count = max(0, {count})")
|
|
571
|
+
lines.append("except _Error: raise")
|
|
572
|
+
lines.append(f"except (ArithmeticError, ValueError) as e: raise _ReadError({message!r} + str(e)) from e")
|
|
562
573
|
element = self._type_symbol(field.type.__type__)
|
|
563
574
|
return f"_type_call({type_}, {element}._read_array(stream, _count, context={context}, endian=endian))"
|
|
564
575
|
|
|
@@ -573,7 +584,7 @@ class _ReadSourceGenerator(_SourceGenerator):
|
|
|
573
584
|
lines.append(f"_bit_buffer = {self._type_symbol(read_type)}._read(stream, endian=endian)")
|
|
574
585
|
|
|
575
586
|
if field.bits > remaining:
|
|
576
|
-
lines.append('raise
|
|
587
|
+
lines.append('raise _DefinitionError("Reading straddled bits is unsupported")')
|
|
577
588
|
yield _block(lines)
|
|
578
589
|
return
|
|
579
590
|
|
|
@@ -1251,7 +1262,7 @@ def _member_lookup(type_: str, value: str) -> str:
|
|
|
1251
1262
|
|
|
1252
1263
|
def _check_eof(size: int) -> str:
|
|
1253
1264
|
"""Return the code to raise an ``EOFError`` if fewer than ``size`` bytes were read into ``buf``."""
|
|
1254
|
-
return f'if len(buf) != {size}: raise
|
|
1265
|
+
return f'if len(buf) != {size}: raise _EOFError(f"Read {{len(buf)}} bytes, but expected {size}")'
|
|
1255
1266
|
|
|
1256
1267
|
|
|
1257
1268
|
def _block(lines: list[str]) -> str:
|
dissect/cstruct/cstruct.py
CHANGED
|
@@ -12,7 +12,7 @@ from functools import lru_cache
|
|
|
12
12
|
from pathlib import Path
|
|
13
13
|
from typing import TYPE_CHECKING, Any, BinaryIO, Literal, TypeVar, cast
|
|
14
14
|
|
|
15
|
-
from dissect.cstruct.exception import ResolveError
|
|
15
|
+
from dissect.cstruct.exception import DefinitionError, ResolveError
|
|
16
16
|
from dissect.cstruct.expression import Expression
|
|
17
17
|
from dissect.cstruct.parser import CStyleParser
|
|
18
18
|
from dissect.cstruct.types import (
|
|
@@ -285,11 +285,11 @@ class cstruct:
|
|
|
285
285
|
replace: Whether to replace the type if it already exists.
|
|
286
286
|
|
|
287
287
|
Raises:
|
|
288
|
-
|
|
288
|
+
DefinitionError: If the type already exists.
|
|
289
289
|
"""
|
|
290
290
|
typeobj = self.resolve(type_)
|
|
291
291
|
if not replace and (existing := self.types.get(name)) is not None and existing is not typeobj:
|
|
292
|
-
raise
|
|
292
|
+
raise DefinitionError(f"Duplicate type: {name}")
|
|
293
293
|
|
|
294
294
|
self.types[name] = typeobj
|
|
295
295
|
self._add_attr(name, typeobj)
|
|
@@ -532,11 +532,13 @@ class cstruct:
|
|
|
532
532
|
if num_entries is None:
|
|
533
533
|
null_terminated = True
|
|
534
534
|
size = None
|
|
535
|
-
elif isinstance(num_entries, Expression)
|
|
535
|
+
elif isinstance(num_entries, Expression):
|
|
536
|
+
size = None
|
|
537
|
+
elif num_entries < 0:
|
|
538
|
+
raise DefinitionError(f"Array size must not be negative: {num_entries}")
|
|
539
|
+
elif type_.__dynamic__:
|
|
536
540
|
size = None
|
|
537
541
|
else:
|
|
538
|
-
if type_.__size__ is None:
|
|
539
|
-
raise ValueError(f"Cannot create array of dynamic type: {type_.__name__}")
|
|
540
542
|
size = num_entries * type_.__size__
|
|
541
543
|
|
|
542
544
|
name = f"{type_.__name__}[]" if null_terminated else f"{type_.__name__}[{num_entries}]"
|
dissect/cstruct/declarative.py
CHANGED
|
@@ -60,6 +60,7 @@ from typing import TYPE_CHECKING, Annotated, Any, BinaryIO, ForwardRef, get_args
|
|
|
60
60
|
|
|
61
61
|
from dissect.cstruct import compiler
|
|
62
62
|
from dissect.cstruct.cstruct import cstruct
|
|
63
|
+
from dissect.cstruct.exception import DefinitionError
|
|
63
64
|
from dissect.cstruct.types.base import BaseArray, MetaType
|
|
64
65
|
from dissect.cstruct.types.structure import Field
|
|
65
66
|
from dissect.cstruct.types.structure import Structure as _Structure
|
|
@@ -370,7 +371,7 @@ def _resolve_type(type_: Any, cs: cstruct) -> type:
|
|
|
370
371
|
if isinstance(type_, str):
|
|
371
372
|
return _resolve_string(type_, cs)
|
|
372
373
|
|
|
373
|
-
raise
|
|
374
|
+
raise DefinitionError(f"Unsupported field annotation: {type_!r}")
|
|
374
375
|
|
|
375
376
|
|
|
376
377
|
def _resolve_field(cls: type, name: str, spec: FieldSpec) -> Field:
|
|
@@ -380,7 +381,7 @@ def _resolve_field(cls: type, name: str, spec: FieldSpec) -> Field:
|
|
|
380
381
|
while issubclass(embedded, BaseArray):
|
|
381
382
|
embedded = embedded.__type__
|
|
382
383
|
if embedded is cls:
|
|
383
|
-
raise
|
|
384
|
+
raise DefinitionError(f"Field {name!r} embeds {cls.__name__!r} in itself, use a pointer instead")
|
|
384
385
|
|
|
385
386
|
return Field(name, type_, spec.bits, spec.offset)
|
|
386
387
|
|
dissect/cstruct/exception.py
CHANGED
|
@@ -1,33 +1,47 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
+
import builtins
|
|
4
|
+
|
|
3
5
|
|
|
4
6
|
class Error(Exception):
|
|
5
|
-
|
|
7
|
+
"""Base class for all exceptions."""
|
|
6
8
|
|
|
7
9
|
|
|
8
|
-
class
|
|
9
|
-
|
|
10
|
+
class DefinitionError(Error, ValueError):
|
|
11
|
+
"""A type definition is invalid."""
|
|
10
12
|
|
|
11
13
|
|
|
12
|
-
class
|
|
13
|
-
|
|
14
|
+
class LexerError(DefinitionError):
|
|
15
|
+
"""The type definition can't be tokenized."""
|
|
14
16
|
|
|
15
17
|
|
|
16
|
-
class
|
|
17
|
-
|
|
18
|
+
class ParserError(DefinitionError):
|
|
19
|
+
"""The type definition can't be parsed."""
|
|
18
20
|
|
|
19
21
|
|
|
20
|
-
class
|
|
21
|
-
|
|
22
|
+
class ResolveError(DefinitionError):
|
|
23
|
+
"""The type definition can't be resolved."""
|
|
22
24
|
|
|
23
25
|
|
|
24
|
-
class
|
|
25
|
-
|
|
26
|
+
class ExpressionParserError(DefinitionError):
|
|
27
|
+
"""The expression can't be parsed."""
|
|
26
28
|
|
|
27
29
|
|
|
28
|
-
class ExpressionParserError
|
|
29
|
-
|
|
30
|
+
class UnknownIdentifierError(ExpressionParserError):
|
|
31
|
+
"""The identifier is not defined."""
|
|
30
32
|
|
|
31
33
|
|
|
32
|
-
class
|
|
33
|
-
|
|
34
|
+
class ReadError(Error, ValueError):
|
|
35
|
+
"""The data can't be parsed."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class NullPointerDereference(ReadError):
|
|
39
|
+
"""A pointer is null, but it was dereferenced."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class WriteError(Error, ValueError):
|
|
43
|
+
"""The value can't be written."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class EOFError(Error, builtins.EOFError):
|
|
47
|
+
"""The data ends before the value does."""
|
dissect/cstruct/expression.py
CHANGED
|
@@ -2,7 +2,7 @@ from __future__ import annotations
|
|
|
2
2
|
|
|
3
3
|
from typing import TYPE_CHECKING, Any
|
|
4
4
|
|
|
5
|
-
from dissect.cstruct.exception import ExpressionParserError, UnknownIdentifierError
|
|
5
|
+
from dissect.cstruct.exception import DefinitionError, ExpressionParserError, UnknownIdentifierError
|
|
6
6
|
from dissect.cstruct.lexer import IDENTIFIER_TYPES, Lexer, TokenCursor, TokenType, join_tokens
|
|
7
7
|
from dissect.cstruct.util import offsetof, sizeof
|
|
8
8
|
|
|
@@ -11,6 +11,7 @@ if TYPE_CHECKING:
|
|
|
11
11
|
|
|
12
12
|
from dissect.cstruct import cstruct
|
|
13
13
|
from dissect.cstruct.lexer import Token
|
|
14
|
+
from dissect.cstruct.types import BaseType
|
|
14
15
|
|
|
15
16
|
_MISSING = object()
|
|
16
17
|
|
|
@@ -73,12 +74,28 @@ PRECEDENCE_LEVELS = {
|
|
|
73
74
|
}
|
|
74
75
|
|
|
75
76
|
|
|
76
|
-
def
|
|
77
|
-
|
|
77
|
+
def _resolve_type(cs: cstruct, name: str, pointers: int, dimensions: list[int]) -> type[BaseType]:
|
|
78
|
+
"""Resolve the type of ``sizeof`` or ``offsetof`` like the type of a field, e.g. ``uint8 *[4]``."""
|
|
79
|
+
type_ = cs.resolve(name)
|
|
80
|
+
for _ in range(pointers):
|
|
81
|
+
type_ = cs._make_pointer(type_)
|
|
82
|
+
for count in reversed(dimensions):
|
|
83
|
+
type_ = cs._make_array(type_, max(0, count))
|
|
84
|
+
return type_
|
|
78
85
|
|
|
79
86
|
|
|
80
|
-
def
|
|
81
|
-
|
|
87
|
+
def _sizeof(type_: type[BaseType]) -> int:
|
|
88
|
+
try:
|
|
89
|
+
return sizeof(type_)
|
|
90
|
+
except TypeError:
|
|
91
|
+
raise DefinitionError(f"Type '{type_.__name__}' has a dynamic size") from None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _offsetof(type_: type[BaseType], field: str) -> int:
|
|
95
|
+
try:
|
|
96
|
+
return offsetof(type_, field)
|
|
97
|
+
except (TypeError, ValueError) as e:
|
|
98
|
+
raise DefinitionError(str(e)) from None
|
|
82
99
|
|
|
83
100
|
|
|
84
101
|
FUNCTIONS: dict[TokenType, Callable[..., int]] = {
|
|
@@ -112,7 +129,7 @@ def _identifier(cs: cstruct, context: dict[str, Any], ident: str) -> int:
|
|
|
112
129
|
|
|
113
130
|
|
|
114
131
|
# Globals used by the source code of an expression
|
|
115
|
-
SOURCE_GLOBALS = {func.__name__: func for func in (_identifier, *FUNCTIONS.values())}
|
|
132
|
+
SOURCE_GLOBALS = {func.__name__: func for func in (_identifier, _resolve_type, *FUNCTIONS.values())}
|
|
116
133
|
|
|
117
134
|
|
|
118
135
|
class _Evaluator:
|
|
@@ -134,8 +151,14 @@ class _Evaluator:
|
|
|
134
151
|
def binary(self, operator: TokenType, left: int, right: int) -> int:
|
|
135
152
|
return BINARY_OPERATORS[operator](left, right)
|
|
136
153
|
|
|
137
|
-
def function(self, operator: TokenType, args:
|
|
138
|
-
|
|
154
|
+
def function(self, operator: TokenType, args: tuple[Any, ...]) -> int:
|
|
155
|
+
(name, pointers, dimensions), *fields = args
|
|
156
|
+
if pointers or dimensions:
|
|
157
|
+
counts = [dimension._run(self) for dimension in dimensions]
|
|
158
|
+
type_ = _resolve_type(self.cs, name, pointers, counts)
|
|
159
|
+
else:
|
|
160
|
+
type_ = self.cs.resolve(name)
|
|
161
|
+
return FUNCTIONS[operator](type_, *fields)
|
|
139
162
|
|
|
140
163
|
|
|
141
164
|
class _SourceBuilder:
|
|
@@ -159,8 +182,14 @@ class _SourceBuilder:
|
|
|
159
182
|
def binary(self, operator: TokenType, left: str, right: str) -> str:
|
|
160
183
|
return f"({left} {OPERATOR_SOURCE[operator]} {right})"
|
|
161
184
|
|
|
162
|
-
def function(self, operator: TokenType, args:
|
|
163
|
-
|
|
185
|
+
def function(self, operator: TokenType, args: tuple[Any, ...]) -> str:
|
|
186
|
+
(name, pointers, dimensions), *fields = args
|
|
187
|
+
if pointers or dimensions:
|
|
188
|
+
counts = ", ".join(dimension._run(self) for dimension in dimensions)
|
|
189
|
+
type_ = f"_resolve_type(cs, {name!r}, {pointers}, [{counts}])"
|
|
190
|
+
else:
|
|
191
|
+
type_ = f"cs.resolve({name!r})"
|
|
192
|
+
return f"{FUNCTIONS[operator].__name__}({', '.join([type_, *map(repr, fields)])})"
|
|
164
193
|
|
|
165
194
|
|
|
166
195
|
def precedence(o1: TokenType, o2: TokenType) -> bool:
|
|
@@ -171,62 +200,36 @@ def precedence(o1: TokenType, o2: TokenType) -> bool:
|
|
|
171
200
|
|
|
172
201
|
|
|
173
202
|
class Expression(TokenCursor):
|
|
174
|
-
"""Expression parser for calculations in definitions.
|
|
203
|
+
"""Expression parser for calculations in definitions.
|
|
204
|
+
|
|
205
|
+
The expression is parsed when it's created, so a syntax error raises right away.
|
|
206
|
+
Calculating with invalid operands (e.g. division by zero) raises an exception when evaluating.
|
|
207
|
+
|
|
208
|
+
Raises:
|
|
209
|
+
ExpressionParserError: If the expression is invalid.
|
|
210
|
+
"""
|
|
175
211
|
|
|
176
212
|
def __init__(self, expression: str):
|
|
177
213
|
self.expression = expression
|
|
178
214
|
|
|
179
215
|
tokens = Lexer(expression).tokenize()
|
|
180
216
|
super().__init__(tokens)
|
|
181
|
-
self.
|
|
182
|
-
self._queue: list[int | str] = []
|
|
217
|
+
self._postfix = self._parse()
|
|
183
218
|
|
|
184
219
|
def __repr__(self) -> str:
|
|
185
220
|
return self.expression
|
|
186
221
|
|
|
187
|
-
def _reset(self) -> None:
|
|
188
|
-
"""Reset the expression state for a new input."""
|
|
189
|
-
self._reset_cursor()
|
|
190
|
-
self._stack = []
|
|
191
|
-
self._queue = []
|
|
192
|
-
|
|
193
222
|
def _error(self, msg: str, *, token: Token | None = None) -> ExpressionParserError:
|
|
194
223
|
return ExpressionParserError(msg)
|
|
195
224
|
|
|
196
|
-
def _evaluate_expression(self, backend: _Evaluator | _SourceBuilder) -> None:
|
|
197
|
-
operator = self._stack.pop(-1)
|
|
198
|
-
result = 0
|
|
199
|
-
|
|
200
|
-
if operator in UNARY_OPERATORS:
|
|
201
|
-
if len(self._queue) < 1:
|
|
202
|
-
raise ExpressionParserError("Invalid expression: not enough operands")
|
|
203
|
-
|
|
204
|
-
result = backend.unary(operator, self._queue.pop(-1))
|
|
205
|
-
elif operator in BINARY_OPERATORS:
|
|
206
|
-
if len(self._queue) < 2:
|
|
207
|
-
raise ExpressionParserError("Invalid expression: not enough operands")
|
|
208
|
-
|
|
209
|
-
right = self._queue.pop(-1)
|
|
210
|
-
left = self._queue.pop(-1)
|
|
211
|
-
result = backend.binary(operator, left, right)
|
|
212
|
-
elif operator in FUNCTION_TOKENS:
|
|
213
|
-
num_args = FUNCTION_TOKENS[operator]
|
|
214
|
-
if len(self._queue) < num_args:
|
|
215
|
-
raise ExpressionParserError("Invalid expression: not enough operands")
|
|
216
|
-
|
|
217
|
-
args = [self._queue.pop(-1) for _ in range(num_args)][::-1]
|
|
218
|
-
result = backend.function(operator, args)
|
|
219
|
-
|
|
220
|
-
self._queue.append(result)
|
|
221
|
-
|
|
222
225
|
def evaluate(self, cs: cstruct, context: dict[str, int] | None = None) -> int:
|
|
223
|
-
"""Evaluates an expression
|
|
226
|
+
"""Evaluates an expression.
|
|
224
227
|
|
|
225
228
|
Args:
|
|
226
229
|
cs: The cstruct instance to evaluate against.
|
|
227
230
|
context: The context to evaluate against.
|
|
228
231
|
"""
|
|
229
|
-
return self.
|
|
232
|
+
return self._run(_Evaluator(cs, context or {}))
|
|
230
233
|
|
|
231
234
|
def source(self, variables: dict[str, str] | None = None, context: str = "context") -> str:
|
|
232
235
|
"""Return the Python source code of this expression.
|
|
@@ -235,54 +238,111 @@ class Expression(TokenCursor):
|
|
|
235
238
|
variables: The source code map for accessing local variables.
|
|
236
239
|
context: The symbol name of the context.
|
|
237
240
|
"""
|
|
238
|
-
return self.
|
|
241
|
+
return self._run(_SourceBuilder(variables or {}, context))
|
|
242
|
+
|
|
243
|
+
def _run(self, backend: _Evaluator | _SourceBuilder) -> int | str:
|
|
244
|
+
"""Calculate the expression from its postfix notation."""
|
|
245
|
+
stack = []
|
|
246
|
+
|
|
247
|
+
for type_, value in self._postfix:
|
|
248
|
+
if type_ in BINARY_OPERATORS:
|
|
249
|
+
right = stack.pop()
|
|
250
|
+
stack[-1] = backend.binary(type_, stack[-1], right)
|
|
251
|
+
elif type_ in UNARY_OPERATORS:
|
|
252
|
+
stack[-1] = backend.unary(type_, stack[-1])
|
|
253
|
+
elif type_ in FUNCTION_TOKENS:
|
|
254
|
+
stack.append(backend.function(type_, value))
|
|
255
|
+
elif type_ == TokenType.NUMBER:
|
|
256
|
+
stack.append(backend.number(value))
|
|
257
|
+
else:
|
|
258
|
+
stack.append(backend.identifier(value))
|
|
259
|
+
|
|
260
|
+
return stack[0]
|
|
261
|
+
|
|
262
|
+
def _pop_operator(self, stack: list[TokenType], output: list[tuple[TokenType, Any]], operands: int) -> int:
|
|
263
|
+
"""Move an operator from the stack to the output, and return the amount of values the output calculates."""
|
|
264
|
+
operator = stack.pop(-1)
|
|
265
|
+
needed = 2 if operator in BINARY_OPERATORS else 1
|
|
266
|
+
if operands < needed:
|
|
267
|
+
raise ExpressionParserError("Invalid expression: not enough operands")
|
|
268
|
+
|
|
269
|
+
output.append((operator, None))
|
|
270
|
+
return operands - needed + 1
|
|
271
|
+
|
|
272
|
+
def _parse_type_name(self) -> tuple[str, int, list[Expression]]:
|
|
273
|
+
"""Parse a type name like the type of a field, e.g. ``struct header *[4]``."""
|
|
274
|
+
# Types share a single namespace, so the kind of a type is optional
|
|
275
|
+
self._match(TokenType.STRUCT, TokenType.UNION, TokenType.ENUM, TokenType.FLAG)
|
|
239
276
|
|
|
240
|
-
|
|
241
|
-
|
|
277
|
+
if not self._at(TokenType.IDENTIFIER):
|
|
278
|
+
raise self._error(f"expected a type name, got {self._describe(self._current())}")
|
|
279
|
+
|
|
280
|
+
# E.g. unsigned long long
|
|
281
|
+
parts = []
|
|
282
|
+
while token := self._match(TokenType.IDENTIFIER):
|
|
283
|
+
parts.append(token.value)
|
|
284
|
+
|
|
285
|
+
pointers = 0
|
|
286
|
+
while self._match(TokenType.STAR):
|
|
287
|
+
pointers += 1
|
|
288
|
+
|
|
289
|
+
dimensions = []
|
|
290
|
+
while self._match(TokenType.LBRACKET):
|
|
291
|
+
if not (tokens := self._collect_until(TokenType.RBRACKET)):
|
|
292
|
+
raise self._error("expected an array size")
|
|
293
|
+
self._expect(TokenType.RBRACKET)
|
|
294
|
+
dimensions.append(Expression(join_tokens(tokens)))
|
|
295
|
+
|
|
296
|
+
return " ".join(parts), pointers, dimensions
|
|
297
|
+
|
|
298
|
+
def _parse(self) -> list[tuple[TokenType, Any]]:
|
|
299
|
+
"""Convert the expression to postfix notation using a Shunting-Yard implementation."""
|
|
300
|
+
output: list[tuple[TokenType, Any]] = []
|
|
301
|
+
stack: list[TokenType] = []
|
|
302
|
+
# The amount of values the output calculates
|
|
303
|
+
operands = 0
|
|
242
304
|
|
|
243
305
|
while (token := self._current()).type != TokenType.EOF:
|
|
244
306
|
if token.type == TokenType.NUMBER:
|
|
245
|
-
|
|
307
|
+
output.append((TokenType.NUMBER, int(self._take().value, 0)))
|
|
308
|
+
operands += 1
|
|
246
309
|
|
|
247
310
|
elif token.type in OPERATORS:
|
|
248
|
-
while (
|
|
249
|
-
|
|
250
|
-
and self._stack[-1] != TokenType.LPAREN
|
|
251
|
-
and precedence(self._stack[-1], token.type)
|
|
252
|
-
):
|
|
253
|
-
self._evaluate_expression(backend)
|
|
311
|
+
while len(stack) != 0 and stack[-1] != TokenType.LPAREN and precedence(stack[-1], token.type):
|
|
312
|
+
operands = self._pop_operator(stack, output, operands)
|
|
254
313
|
|
|
255
|
-
|
|
314
|
+
stack.append(self._take().type)
|
|
256
315
|
|
|
257
316
|
elif token.type in FUNCTION_TOKENS:
|
|
258
317
|
func = self._take().type
|
|
259
|
-
self._stack.append(func)
|
|
260
318
|
|
|
261
319
|
self._expect(TokenType.LPAREN)
|
|
262
320
|
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
321
|
+
# The type, followed by the names of fields
|
|
322
|
+
args = [self._parse_type_name()]
|
|
323
|
+
for _ in range(FUNCTION_TOKENS[func] - 1):
|
|
266
324
|
self._expect(TokenType.COMMA)
|
|
267
|
-
|
|
325
|
+
if not self._at(*IDENTIFIER_TYPES):
|
|
326
|
+
raise self._error(f"expected a field name, got {self._describe(self._current())}")
|
|
327
|
+
args.append(self._take().value)
|
|
268
328
|
|
|
269
|
-
self._queue.append(join_tokens(self._collect_until(TokenType.RPAREN)))
|
|
270
329
|
self._expect(TokenType.RPAREN)
|
|
271
330
|
|
|
272
|
-
|
|
273
|
-
|
|
331
|
+
output.append((func, tuple(args)))
|
|
332
|
+
operands += 1
|
|
274
333
|
|
|
275
334
|
elif token.type in IDENTIFIER_TYPES:
|
|
276
|
-
|
|
335
|
+
output.append((token.type, self._take().value))
|
|
336
|
+
operands += 1
|
|
277
337
|
|
|
278
338
|
elif token.type == TokenType.LPAREN:
|
|
279
339
|
if self._previous().type == TokenType.NUMBER:
|
|
280
340
|
raise self._error(
|
|
281
|
-
f"Parser expected sizeof or an
|
|
341
|
+
f"Parser expected sizeof or an arithmethic operator instead got: '{self._previous().value}'",
|
|
282
342
|
token=self._previous(),
|
|
283
343
|
)
|
|
284
344
|
|
|
285
|
-
|
|
345
|
+
stack.append(self._take().type)
|
|
286
346
|
|
|
287
347
|
elif token.type == TokenType.RPAREN:
|
|
288
348
|
if self._previous().type == TokenType.LPAREN:
|
|
@@ -291,26 +351,29 @@ class Expression(TokenCursor):
|
|
|
291
351
|
token=self._previous(),
|
|
292
352
|
)
|
|
293
353
|
|
|
294
|
-
if len(
|
|
354
|
+
if len(stack) == 0:
|
|
295
355
|
raise self._error("Mismatched parentheses")
|
|
296
356
|
|
|
297
|
-
while
|
|
298
|
-
self.
|
|
299
|
-
if len(
|
|
357
|
+
while stack[-1] != TokenType.LPAREN:
|
|
358
|
+
operands = self._pop_operator(stack, output, operands)
|
|
359
|
+
if len(stack) == 0:
|
|
300
360
|
raise self._error("Mismatched parentheses")
|
|
301
361
|
|
|
302
|
-
|
|
362
|
+
stack.pop(-1) # Pop the '('
|
|
303
363
|
self._take()
|
|
304
364
|
|
|
305
365
|
else:
|
|
306
366
|
raise self._error(f"Unmatched token: '{token.value}'", token=token)
|
|
307
367
|
|
|
308
|
-
while len(
|
|
309
|
-
if TokenType.LPAREN in
|
|
368
|
+
while len(stack) != 0:
|
|
369
|
+
if TokenType.LPAREN in stack:
|
|
310
370
|
raise self._error("Mismatched parentheses")
|
|
311
|
-
self.
|
|
371
|
+
operands = self._pop_operator(stack, output, operands)
|
|
372
|
+
|
|
373
|
+
if operands == 0:
|
|
374
|
+
raise self._error("Invalid expression: not enough operands")
|
|
312
375
|
|
|
313
|
-
if
|
|
376
|
+
if operands > 1:
|
|
314
377
|
raise self._error("Invalid expression: too many operands")
|
|
315
378
|
|
|
316
|
-
return
|
|
379
|
+
return output
|
dissect/cstruct/lexer.py
CHANGED
|
@@ -532,10 +532,6 @@ class TokenCursor:
|
|
|
532
532
|
self._tokens = tokens
|
|
533
533
|
self._pos = 0
|
|
534
534
|
|
|
535
|
-
def _reset_cursor(self) -> None:
|
|
536
|
-
"""Reset only the cursor position while keeping the current tokens."""
|
|
537
|
-
self._pos = 0
|
|
538
|
-
|
|
539
535
|
def _assert_not_eof(self) -> None:
|
|
540
536
|
"""Raise an error if EOF is reached."""
|
|
541
537
|
if self._tokens[self._pos].type == TokenType.EOF:
|
|
@@ -561,14 +557,27 @@ class TokenCursor:
|
|
|
561
557
|
self._pos += 1
|
|
562
558
|
return token
|
|
563
559
|
|
|
560
|
+
def _match(self, *types: TokenType) -> Token | None:
|
|
561
|
+
"""Consume and return the current token if it matches any of the given types, otherwise return ``None``."""
|
|
562
|
+
if self._current().type in types:
|
|
563
|
+
return self._take()
|
|
564
|
+
return None
|
|
565
|
+
|
|
566
|
+
def _at(self, *types: TokenType) -> bool:
|
|
567
|
+
"""Return whether the current token matches any of the given types."""
|
|
568
|
+
return self._tokens[self._pos].type in types
|
|
569
|
+
|
|
570
|
+
def _describe(self, token: Token) -> str:
|
|
571
|
+
"""Describe a token for an error message."""
|
|
572
|
+
return "end of input" if token.type == TokenType.EOF else token.value
|
|
573
|
+
|
|
564
574
|
def _expect(self, *types: TokenType) -> Token:
|
|
565
575
|
"""Consume and return the current token if it matches, otherwise raise an error."""
|
|
566
576
|
token = self._current()
|
|
567
577
|
if token.type not in types:
|
|
568
|
-
actual = "end of input" if token.type == TokenType.EOF else token.value
|
|
569
578
|
expected = " or ".join(t.value for t in types)
|
|
570
579
|
expected = f"one of {expected}" if len(types) > 1 else expected
|
|
571
|
-
raise self._error(f"expected {expected}, got {
|
|
580
|
+
raise self._error(f"expected {expected}, got {self._describe(token)}")
|
|
572
581
|
return self._take()
|
|
573
582
|
|
|
574
583
|
def _collect_until(self, *terminators: TokenType) -> list[Token]:
|