dissect.cstruct 5.0.dev16__py3-none-any.whl → 5.0.dev18__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.
@@ -2,6 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  from dissect.cstruct.bitbuffer import BitBuffer
4
4
  from dissect.cstruct.cstruct import cstruct, ctypes, ctypes_type
5
+ from dissect.cstruct.dump import dumpstruct, hexdump
5
6
  from dissect.cstruct.exception import (
6
7
  Error,
7
8
  NullPointerDereference,
@@ -29,11 +30,9 @@ from dissect.cstruct.types import (
29
30
  WcharArray,
30
31
  )
31
32
  from dissect.cstruct.util import (
32
- dumpstruct,
33
33
  f16,
34
34
  f32,
35
35
  f64,
36
- hexdump,
37
36
  p8,
38
37
  p16,
39
38
  p32,
@@ -0,0 +1,460 @@
1
+ """Declarative syntax for defining cstruct structures.
2
+
3
+ This module is an optional convenience layer on top of cstruct. It offers a Pythonic way to declare structures by
4
+ subclassing :class:`Struct` (or :class:`Union`) and annotating the fields::
5
+
6
+ from dissect.cstruct.declarative import Struct, uint8, uint32, uint64
7
+
8
+
9
+ class Header(Struct):
10
+ magic: uint8[4]
11
+ version: uint32
12
+
13
+
14
+ class File(Struct):
15
+ header: Header # structures can reference each other
16
+ size: uint64
17
+
18
+ The resulting classes are regular cstruct structures. Each structure is registered in a cstruct instance, which can
19
+ be passed as a class keyword argument, together with ``align``::
20
+
21
+ cs = cstruct(endian=">")
22
+
23
+
24
+ class Header(Struct, cs=cs, align=True): ...
25
+
26
+ Without one, a structure uses the cstruct instance of the first bound type or structure in its annotations, or a new
27
+ cstruct instance. To reuse the same options for many structures, subclass a base class without fields that has them::
28
+
29
+ class Base(Struct, cs=cs):
30
+ pass
31
+
32
+
33
+ class Header(Base): ...
34
+
35
+ A field annotation can be any of the following:
36
+
37
+ * A type of this module, e.g. ``uint32``, ``uint8[4]``, ``uint8["size"]``, ``char[EOF]`` or ``pointer[uint32]``.
38
+ * A bound cstruct type, e.g. ``cs.uint32`` or ``cs.uint8[4]``.
39
+ * Another structure, e.g. ``Header``.
40
+ * The name of a cstruct type as a string, optionally followed by pointers and array dimensions, e.g. ``"DWORD*[4]"``.
41
+ * A :func:`field` for bit fields and explicit offsets, e.g. ``field(uint16, bits=4)``. For type checkers, use it
42
+ as :data:`typing.Annotated` metadata instead, e.g. ``Annotated[uint16, field(bits=4)]``.
43
+
44
+ A structure can point to itself (``next: pointer["Node"]``), but not embed itself. A subclass of a structure starts
45
+ with the fields of its parent.
46
+
47
+ Field annotations are evaluated at runtime. Projects using Ruff's ``flake8-type-checking`` (``TC``) rules should add
48
+ :class:`Struct` and :class:`Union` to the runtime-evaluated base classes, so that imports only used in field
49
+ annotations are not moved into a ``TYPE_CHECKING`` block::
50
+
51
+ [tool.ruff.lint.flake8-type-checking]
52
+ runtime-evaluated-base-classes = ["dissect.cstruct.declarative.Struct", "dissect.cstruct.declarative.Union"]
53
+ """
54
+
55
+ from __future__ import annotations
56
+
57
+ import ast
58
+ import sys
59
+ from typing import TYPE_CHECKING, Annotated, Any, BinaryIO, ForwardRef, get_args, get_origin
60
+
61
+ from dissect.cstruct import compiler
62
+ from dissect.cstruct.cstruct import cstruct
63
+ from dissect.cstruct.types.base import BaseArray, MetaType
64
+ from dissect.cstruct.types.structure import Field
65
+ from dissect.cstruct.types.structure import Structure as _Structure
66
+ from dissect.cstruct.types.structure import Union as _Union
67
+
68
+
69
+ class _Ref:
70
+ """Base class for type references, which are resolved against the cstruct instance of a structure."""
71
+
72
+ __slots__ = ()
73
+
74
+ def __call__(self, *args, **kwargs) -> Any:
75
+ # Python 3.10 only allows callables as the type of typing.Annotated
76
+ raise TypeError(f"{self!r} is a type reference and cannot be instantiated")
77
+
78
+ def __getitem__(self, count: int | str | None) -> ArrayRef:
79
+ """Support the ``uint8[4]`` array syntax."""
80
+ return ArrayRef(self, count)
81
+
82
+ def _resolve(self, cs: cstruct) -> type:
83
+ raise NotImplementedError
84
+
85
+
86
+ class TypeRef(_Ref):
87
+ """A reference to a cstruct type by name, e.g. :data:`uint32`."""
88
+
89
+ __slots__ = ("name",)
90
+
91
+ def __init__(self, name: str):
92
+ self.name = name
93
+
94
+ def _resolve(self, cs: cstruct) -> type:
95
+ return cs.resolve(self.name)
96
+
97
+ def __repr__(self) -> str:
98
+ return f"<TypeRef {self.name}>"
99
+
100
+
101
+ class ArrayRef(_Ref):
102
+ """A reference to an array of a type."""
103
+
104
+ __slots__ = ("count", "type")
105
+
106
+ def __init__(self, type_: Any, count: int | str | None):
107
+ self.type = type_
108
+ self.count = count
109
+
110
+ def _resolve(self, cs: cstruct) -> type:
111
+ return _resolve_type(self.type, cs)[self.count]
112
+
113
+ def __repr__(self) -> str:
114
+ return f"<ArrayRef {self.type!r}[{self.count}]>"
115
+
116
+
117
+ class PointerRef(_Ref):
118
+ """A reference to a pointer to a type."""
119
+
120
+ __slots__ = ("type",)
121
+
122
+ def __init__(self, type_: Any):
123
+ self.type = type_
124
+
125
+ def _resolve(self, cs: cstruct) -> type:
126
+ return cs._make_pointer(_resolve_type(self.type, cs))
127
+
128
+ def __repr__(self) -> str:
129
+ return f"<PointerRef {self.type!r}>"
130
+
131
+
132
+ class _PointerFactory:
133
+ """Factory for the ``pointer[type]`` syntax."""
134
+
135
+ def __getitem__(self, item: Any) -> PointerRef:
136
+ return PointerRef(item)
137
+
138
+
139
+ class FieldSpec:
140
+ """A field with a bit size or explicit offset. See :func:`field`."""
141
+
142
+ __slots__ = ("bits", "offset", "type")
143
+
144
+ def __init__(self, type_: Any = None, bits: int | None = None, offset: int | None = None):
145
+ self.type = type_
146
+ self.bits = bits
147
+ self.offset = offset
148
+
149
+
150
+ def field(type_: Any = None, *, bits: int | None = None, offset: int | None = None) -> FieldSpec:
151
+ """Describe a bit field or a field at an explicit offset.
152
+
153
+ For example::
154
+
155
+ class Example(Struct):
156
+ flags: field(uint16, bits=4)
157
+ tail: field(uint32, offset=0x10)
158
+
159
+ For type checkers, omit the type and use it as :data:`typing.Annotated` metadata instead::
160
+
161
+ class Example(Struct):
162
+ flags: Annotated[uint16, field(bits=4)]
163
+ tail: Annotated[uint32, field(offset=0x10)]
164
+
165
+ Args:
166
+ type_: The field type. Omitted when used as :data:`typing.Annotated` metadata.
167
+ bits: The amount of bits for a bit field.
168
+ offset: The offset of the field within the structure.
169
+ """
170
+ return FieldSpec(type_, bits=bits, offset=offset)
171
+
172
+
173
+ if TYPE_CHECKING:
174
+ from typing import TypeVar
175
+
176
+ _T = TypeVar("_T")
177
+
178
+ # For type checkers, the types are subclasses of their Python counterpart, so that ``version: uint32`` and
179
+ # ``magic: uint8[4]`` are valid type expressions. At runtime they are type references.
180
+ class _int(int):
181
+ __slots__ = ()
182
+
183
+ def __class_getitem__(cls, count: Any) -> type[list[int]]: ...
184
+
185
+ class _bytes(bytes):
186
+ __slots__ = ()
187
+
188
+ def __class_getitem__(cls, count: Any) -> type[bytes]: ...
189
+
190
+ class _str(str):
191
+ __slots__ = ()
192
+
193
+ def __class_getitem__(cls, count: Any) -> type[str]: ...
194
+
195
+ _builtin_float = float
196
+
197
+ class _float(_builtin_float):
198
+ __slots__ = ()
199
+
200
+ def __class_getitem__(cls, count: Any) -> type[list[_builtin_float]]: ...
201
+
202
+ class uint8(_int): ...
203
+
204
+ class uint16(_int): ...
205
+
206
+ class uint24(_int): ...
207
+
208
+ class uint32(_int): ...
209
+
210
+ class uint48(_int): ...
211
+
212
+ class uint64(_int): ...
213
+
214
+ class uint128(_int): ...
215
+
216
+ class int8(_int): ...
217
+
218
+ class int16(_int): ...
219
+
220
+ class int24(_int): ...
221
+
222
+ class int32(_int): ...
223
+
224
+ class int48(_int): ...
225
+
226
+ class int64(_int): ...
227
+
228
+ class int128(_int): ...
229
+
230
+ class uleb128(_int): ...
231
+
232
+ class ileb128(_int): ...
233
+
234
+ class float16(_float): ...
235
+
236
+ class float(_float): ...
237
+
238
+ class double(_float): ...
239
+
240
+ class char(_bytes): ...
241
+
242
+ class wchar(_str): ...
243
+
244
+ void = None
245
+
246
+ class pointer:
247
+ def __class_getitem__(cls, item: type[_T]) -> type[_T]: ...
248
+ else:
249
+ pointer = _PointerFactory()
250
+
251
+ uint8 = TypeRef("uint8")
252
+ uint16 = TypeRef("uint16")
253
+ uint24 = TypeRef("uint24")
254
+ uint32 = TypeRef("uint32")
255
+ uint48 = TypeRef("uint48")
256
+ uint64 = TypeRef("uint64")
257
+ uint128 = TypeRef("uint128")
258
+
259
+ int8 = TypeRef("int8")
260
+ int16 = TypeRef("int16")
261
+ int24 = TypeRef("int24")
262
+ int32 = TypeRef("int32")
263
+ int48 = TypeRef("int48")
264
+ int64 = TypeRef("int64")
265
+ int128 = TypeRef("int128")
266
+
267
+ uleb128 = TypeRef("uleb128")
268
+ ileb128 = TypeRef("ileb128")
269
+
270
+ float16 = TypeRef("float16")
271
+ float = TypeRef("float")
272
+ double = TypeRef("double")
273
+
274
+ char = TypeRef("char")
275
+ wchar = TypeRef("wchar")
276
+ void = TypeRef("void")
277
+
278
+ # An array count that reads until the end of the stream, like ``char data[EOF]`` in a definition
279
+ EOF = "EOF"
280
+
281
+
282
+ def _get_annotations(cls: type) -> dict[str, Any]:
283
+ """Return the annotations defined on the class itself, as strings or (with Python < 3.14) objects."""
284
+ if sys.version_info >= (3, 14):
285
+ import annotationlib # novermin
286
+
287
+ # The string format doesn't fail on forward references. They are evaluated like the strings of
288
+ # ``from __future__ import annotations``.
289
+ return annotationlib.get_annotations(cls, format=annotationlib.Format.STRING) # novermin
290
+ return cls.__dict__.get("__annotations__", {})
291
+
292
+
293
+ def _eval(annotation: Any, globalns: dict[str, Any], localns: dict[str, Any]) -> Any:
294
+ """Evaluate a string annotation.
295
+
296
+ A string that isn't valid Python or uses names that aren't defined in the scope of the structure, such as
297
+ ``"unsigned short"``, ``"DWORD"`` or ``"int"``, is returned as is, to be resolved as the name of a cstruct type.
298
+ """
299
+ if not isinstance(annotation, str):
300
+ return annotation
301
+
302
+ try:
303
+ expression = ast.parse(annotation, mode="eval")
304
+ except SyntaxError:
305
+ return annotation
306
+
307
+ # Checked instead of catching a NameError, because the builtins (e.g. ``int``) must not be used
308
+ names = (node.id for node in ast.walk(expression) if isinstance(node, ast.Name))
309
+ if any(name not in localns and name not in globalns for name in names):
310
+ return annotation
311
+
312
+ return eval(compile(expression, "<annotation>", "eval"), globalns, localns)
313
+
314
+
315
+ def _parse_annotation(annotation: Any, globalns: dict[str, Any], localns: dict[str, Any]) -> FieldSpec:
316
+ annotation = _eval(annotation, globalns, localns)
317
+
318
+ if isinstance(annotation, FieldSpec):
319
+ spec = annotation
320
+ elif get_origin(annotation) is Annotated:
321
+ type_, *metadata = get_args(annotation)
322
+ if isinstance(type_, ForwardRef):
323
+ # E.g. Annotated["uint16", ...]
324
+ type_ = type_.__forward_arg__
325
+ spec = next((meta for meta in metadata if isinstance(meta, FieldSpec)), FieldSpec())
326
+ spec = FieldSpec(type_, bits=spec.bits, offset=spec.offset)
327
+ else:
328
+ spec = FieldSpec(annotation)
329
+
330
+ # A new FieldSpec, because a field() can be shared between structures
331
+ return FieldSpec(_eval(spec.type, globalns, localns), bits=spec.bits, offset=spec.offset)
332
+
333
+
334
+ def _bound_cs(type_: Any) -> cstruct | None:
335
+ while isinstance(type_, (ArrayRef, PointerRef)):
336
+ type_ = type_.type
337
+ return type_.__cs__ if isinstance(type_, MetaType) else None
338
+
339
+
340
+ def _resolve_string(text: str, cs: cstruct) -> type:
341
+ """Resolve the name of a cstruct type, optionally followed by pointers and array dimensions.
342
+
343
+ Array dimensions are applied from left to right, like the subscript syntax. So ``"uint8[4][2]"`` is the same as
344
+ ``cs.uint8[4][2]``: two arrays of four ``uint8``. An empty dimension is a null-terminated array.
345
+ """
346
+ text = text.strip()
347
+
348
+ counts = []
349
+ while text.endswith("]"):
350
+ text, _, count = text[:-1].rpartition("[")
351
+ counts.insert(0, count.strip() or None)
352
+ text = text.rstrip()
353
+
354
+ type_ = cs.resolve(text.rstrip("* "))
355
+ for _ in range(text.count("*")):
356
+ type_ = cs._make_pointer(type_)
357
+ for count in counts:
358
+ type_ = type_[count]
359
+
360
+ return type_
361
+
362
+
363
+ def _resolve_type(type_: Any, cs: cstruct) -> type:
364
+ if isinstance(type_, MetaType):
365
+ return type_
366
+
367
+ if isinstance(type_, _Ref):
368
+ return type_._resolve(cs)
369
+
370
+ if isinstance(type_, str):
371
+ return _resolve_string(type_, cs)
372
+
373
+ raise TypeError(f"Unsupported field annotation: {type_!r}")
374
+
375
+
376
+ def _resolve_field(cls: type, name: str, spec: FieldSpec) -> Field:
377
+ type_ = _resolve_type(spec.type, cls.__cs__)
378
+
379
+ embedded = type_
380
+ while issubclass(embedded, BaseArray):
381
+ embedded = embedded.__type__
382
+ if embedded is cls:
383
+ raise TypeError(f"Field {name!r} embeds {cls.__name__!r} in itself, use a pointer instead")
384
+
385
+ return Field(name, type_, spec.bits, spec.offset)
386
+
387
+
388
+ class _Declarative:
389
+ """Turns an annotated subclass of :class:`Struct` or :class:`Union` into a cstruct structure."""
390
+
391
+ __align__ = False
392
+ __anonymous__ = False
393
+
394
+ def __init_subclass__(cls, *, cs: cstruct | None = None, align: bool | None = None, **kwargs):
395
+ super().__init_subclass__(**kwargs)
396
+
397
+ if cs is not None:
398
+ cls.__cs__ = cs
399
+ if align is not None:
400
+ cls.__align__ = align
401
+
402
+ # The scope of the class statement, skipping StructureMetaType.__new__. Its locals are needed to evaluate
403
+ # annotations that refer to other structures defined in a function.
404
+ frame = sys._getframe(2)
405
+ localns = {**frame.f_locals, **vars(cls)}
406
+ specs = {
407
+ name: _parse_annotation(annotation, frame.f_globals, localns)
408
+ for name, annotation in _get_annotations(cls).items()
409
+ }
410
+
411
+ fields = [
412
+ Field(inherited.name, inherited.type, inherited.bits, inherited.offset)
413
+ for base in cls.__bases__
414
+ for inherited in getattr(base, "__fields__", [])
415
+ ]
416
+ if not specs and not fields:
417
+ # A base class that only has options for its subclasses
418
+ return
419
+
420
+ if (cs := getattr(cls, "__cs__", None)) is None:
421
+ cs = cls.__cs__ = next(filter(None, map(_bound_cs, (spec.type for spec in specs.values()))), None)
422
+ if cs is None:
423
+ cs = cls.__cs__ = cstruct()
424
+
425
+ # Register the class without fields first, so that it can point to itself
426
+ cls.__fields__ = []
427
+ cls.commit()
428
+ cs.add_type(cls.__name__, cls)
429
+
430
+ try:
431
+ cls.__fields__ = fields + [_resolve_field(cls, name, spec) for name, spec in specs.items()]
432
+ cls.commit()
433
+ except Exception:
434
+ # Don't leave a structure without its fields registered
435
+ del cs.types[cls.__name__]
436
+ vars(cs).pop(cls.__name__, None)
437
+ raise
438
+
439
+ compiler.compile_structure(cls)
440
+
441
+ if TYPE_CHECKING:
442
+
443
+ def __init__(self, fh: bytes | memoryview | bytearray | BinaryIO | None = ..., /, **kwargs) -> None: ...
444
+
445
+
446
+ class Struct(_Declarative, _Structure):
447
+ """Base class for declarative structures.
448
+
449
+ For example::
450
+
451
+ class Header(Struct):
452
+ magic: uint8[4]
453
+ version: uint32
454
+
455
+ The class keyword arguments are ``cs`` and ``align``. See :mod:`dissect.cstruct.declarative`.
456
+ """
457
+
458
+
459
+ class Union(_Declarative, _Union):
460
+ """Base class for declarative unions. See :class:`Struct`."""