dissect.cstruct 5.0.dev17__py3-none-any.whl → 5.0.dev19__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.
@@ -29,6 +29,7 @@ from dissect.cstruct.types import (
29
29
  Wchar,
30
30
  WcharArray,
31
31
  )
32
+ from dissect.cstruct.types.structure import JSONEncoder, asdict, asjson
32
33
  from dissect.cstruct.util import (
33
34
  f16,
34
35
  f32,
@@ -65,6 +66,7 @@ __all__ = [
65
66
  "Field",
66
67
  "Flag",
67
68
  "Int",
69
+ "JSONEncoder",
68
70
  "MetaType",
69
71
  "NullPointerDereference",
70
72
  "Packed",
@@ -76,6 +78,8 @@ __all__ = [
76
78
  "Void",
77
79
  "Wchar",
78
80
  "WcharArray",
81
+ "asdict",
82
+ "asjson",
79
83
  "cstruct",
80
84
  "ctypes",
81
85
  "ctypes_type",
@@ -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`."""
dissect/cstruct/dump.py CHANGED
@@ -428,6 +428,9 @@ def dumpstruct(
428
428
 
429
429
  Prints a colorized hexdump and parsed structure output.
430
430
 
431
+ Note that this is different from :func:`asdict` and :func:`asjson`: those functions return the field values of a
432
+ structure or union, while this function describes the layout of the structure (hex bytes, offsets, display strings).
433
+
431
434
  The ``dict`` and ``json`` output formats describe the structure as a tree:
432
435
  - bytes: hex string of the raw data
433
436
  - type: type name of the structure
@@ -1,5 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import contextlib
3
4
  import functools
4
5
  import warnings
5
6
  from io import SEEK_CUR, BytesIO
@@ -7,6 +8,7 @@ from types import MethodType
7
8
  from typing import TYPE_CHECKING, Any, BinaryIO, ClassVar, TypeVar
8
9
 
9
10
  from dissect.cstruct.exception import ArraySizeError
11
+ from dissect.cstruct.expression import Expression
10
12
  from dissect.cstruct.util import classproperty, normalize_endianness
11
13
 
12
14
  if TYPE_CHECKING:
@@ -15,7 +17,6 @@ if TYPE_CHECKING:
15
17
  from typing_extensions import Self
16
18
 
17
19
  from dissect.cstruct.cstruct import AllowedEndianness, Endianness, cstruct
18
- from dissect.cstruct.expression import Expression
19
20
 
20
21
 
21
22
  EOF = -0xE0F # Negative counts are illegal anyway, so abuse that for our EOF sentinel
@@ -73,8 +74,13 @@ class MetaType(type):
73
74
 
74
75
  return type.__call__(cls, *args, **kwargs)
75
76
 
76
- def __getitem__(cls, num_entries: int | Expression | None) -> type[BaseArray]:
77
+ def __getitem__(cls, num_entries: int | str | Expression | None) -> type[BaseArray]:
77
78
  """Create a new array with the given number of entries."""
79
+ if isinstance(num_entries, str):
80
+ num_entries = Expression(num_entries)
81
+ with contextlib.suppress(Exception):
82
+ num_entries = num_entries.evaluate(cls.__cs__)
83
+
78
84
  return cls.__cs__._make_array(cls, num_entries)
79
85
 
80
86
  def __bool__(cls) -> bool:
@@ -1,6 +1,8 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import base64
3
4
  import io
5
+ import json
4
6
  import warnings
5
7
  from collections import ChainMap
6
8
  from collections.abc import MutableMapping
@@ -26,6 +28,7 @@ from dissect.cstruct.types.base import (
26
28
  )
27
29
  from dissect.cstruct.types.enum import EnumMetaType
28
30
  from dissect.cstruct.types.pointer import Pointer
31
+ from dissect.cstruct.types.void import Void
29
32
 
30
33
  if TYPE_CHECKING:
31
34
  from collections.abc import Callable, Iterator, Mapping
@@ -69,11 +72,11 @@ class StructureMetaType(MetaType):
69
72
  __compiled__ = False
70
73
  __static_sizes__: dict[str, int] # Cache of static sizes by field name
71
74
 
72
- def __new__(metacls, name: str, bases: tuple[type, ...], classdict: dict[str, Any]) -> Self: # type: ignore
75
+ def __new__(metacls, name: str, bases: tuple[type, ...], classdict: dict[str, Any], **kwargs) -> Self: # type: ignore
73
76
  if (fields := classdict.pop("__members__", None)) is not None:
74
77
  metacls._update_fields(metacls, fields, align=classdict.get("__align__", False), classdict=classdict)
75
78
 
76
- return super().__new__(metacls, name, bases, classdict)
79
+ return super().__new__(metacls, name, bases, classdict, **kwargs)
77
80
 
78
81
  def __call__(cls, *args, **kwargs) -> Self: # type: ignore
79
82
  if len(args) == 1 and not kwargs:
@@ -808,6 +811,91 @@ class UnionProxy:
808
811
  self.__union__._rebuild(self.__attr__)
809
812
 
810
813
 
814
+ def asdict(obj: Structure | UnionProxy) -> dict[str, Any]:
815
+ """Return the field values of a structure or union as a dict, like :func:`dataclasses.asdict`.
816
+
817
+ The keys are the field names in :attr:`StructureMetaType.__members__`, so the fields of anonymous structures and
818
+ unions are part of the parent, and a union has all of its fields. Nested structures and unions become dicts and
819
+ arrays become lists. Other values are returned as they are: enum members stay enum members, and pointers are not
820
+ dereferenced.
821
+
822
+ Note that this is different from :func:`dumpstruct` called with ``output="dict"``: this function returns a
823
+ dictionary with pairs of field names and values, rather than a dictionary that describes the layout of the
824
+ structure (hex bytes, offsets, display strings).
825
+
826
+ Args:
827
+ obj: The structure or union to convert.
828
+
829
+ Raises:
830
+ TypeError: If ``obj`` is not a structure or union instance.
831
+ """
832
+ while isinstance(obj, UnionProxy):
833
+ obj = obj.__target__
834
+
835
+ if not isinstance(obj, Structure):
836
+ raise TypeError("asdict() should be called on Structure instances")
837
+
838
+ return _asdict_value(obj)
839
+
840
+
841
+ def _asdict_value(value: Any) -> Any:
842
+ # Structures in a union are proxied
843
+ while isinstance(value, UnionProxy):
844
+ value = value.__target__
845
+
846
+ if isinstance(value, Structure):
847
+ return {name: _asdict_value(getattr(value, name)) for name in value.__class__.__members__}
848
+
849
+ if isinstance(value, (list, tuple)):
850
+ # The entries of an array of other types are returned as they are, copying them is much faster
851
+ if isinstance(value, BaseArray) and not issubclass(value.__type__, (Structure, BaseArray)):
852
+ return list(value)
853
+ return [_asdict_value(item) for item in value]
854
+
855
+ return value
856
+
857
+
858
+ class JSONEncoder(json.JSONEncoder):
859
+ """JSON encoder for structures and unions, and the values of their fields.
860
+
861
+ Structures and unions are encoded as objects with the fields of :func:`asdict`. Bytes, such as the values of
862
+ ``char`` arrays, are encoded as base64 strings and ``void`` values as ``null``. Enum and flag members and pointers
863
+ are integers, which :mod:`json` encodes as numbers.
864
+
865
+ Example:
866
+ >>> json.dumps({"header": header}, cls=JSONEncoder)
867
+ """
868
+
869
+ def default(self, o: Any) -> Any:
870
+ if isinstance(o, (Structure, UnionProxy)):
871
+ return asdict(o)
872
+
873
+ if isinstance(o, _BUFFER_TYPES):
874
+ return base64.b64encode(o).decode()
875
+
876
+ if isinstance(o, Void):
877
+ return None
878
+
879
+ return super().default(o)
880
+
881
+
882
+ def asjson(obj: Structure | UnionProxy, **kwargs) -> str:
883
+ """Return the field values of a structure or union as a JSON string, encoded with :class:`JSONEncoder`.
884
+
885
+ Note that this is different from :func:`dumpstruct` called with ``output="json"``: this function returns a
886
+ JSON string with pairs of field names and values, rather than a JSON string that describes the layout of the
887
+ structure (hex bytes, offsets, display strings).
888
+
889
+ Args:
890
+ obj: The structure or union to convert.
891
+ **kwargs: Keyword arguments for :func:`json.dumps`, e.g. ``indent``.
892
+
893
+ Raises:
894
+ TypeError: If ``obj`` is not a structure or union instance.
895
+ """
896
+ return json.dumps(asdict(obj), cls=JSONEncoder, **kwargs)
897
+
898
+
811
899
  def attrsetter(path: str) -> Callable[[Any], Any]:
812
900
  path, _, attr = path.rpartition(".")
813
901
  path = path.split(".")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dissect.cstruct
3
- Version: 5.0.dev17
3
+ Version: 5.0.dev19
4
4
  Summary: A Dissect module implementing a parser for C-like structures: structure parsing in Python made easy
5
5
  Author-email: Dissect Team <dissect@fox-it.com>
6
6
  License-Expression: Apache-2.0
@@ -129,7 +129,7 @@ assert instance.dumps() == b"\x05loremipsum\x05\x00\x00\x00"
129
129
 
130
130
  ```
131
131
 
132
- By default, all structures are compiled into classes that provide optimised performance. You can disable this by passing a `compiled=False` keyword argument to the `.load()` call. You can also inspect the resulting source code by accessing the source attribute of the structure: `print(c_parser.some_struct.source)`.
132
+ By default, all structures are compiled into classes that provide optimised performance. You can disable this by passing a `compiled=False` keyword argument to the `.load()` call. You can inspect the resulting source code by accessing the source attribute of the structure: `print(c_parser.some_struct._read.__source__)` or `print(c_parser.some_struct._write_.__source__)`.
133
133
 
134
134
  More examples can be found in the `examples` directory.
135
135
 
@@ -137,6 +137,60 @@ More examples can be found in the `examples` directory.
137
137
  ### Structure parsing
138
138
  Write simple C-like structures and use them to parse binary data, as can be seen in the examples.
139
139
 
140
+ ### Declarative structure definitions
141
+ Instead of with a C-like definition, structures can also be defined in Python by subclassing `Struct` (or `Union`) and annotating the fields. The resulting classes are regular cstruct structures.
142
+
143
+ ```python
144
+ from typing import Annotated
145
+
146
+ from dissect.cstruct import cstruct
147
+ from dissect.cstruct.declarative import EOF, Struct, char, field, pointer, uint8, uint16, uint32
148
+
149
+
150
+ class Header(Struct):
151
+ magic: uint8[4]
152
+ size: uint32
153
+ data: char["size"] # Array sizes can refer to other fields
154
+ flags: Annotated[uint16, field(bits=4)] # Or field(uint16, bits=4)
155
+ trailer: char[EOF] # Reads until the end of the data
156
+
157
+
158
+ data = b"ohai\x0c\x00\x00\x00KUSJESVANSRT\x05\x00<3"
159
+ header = Header(data)
160
+ assert header.data == b"KUSJESVANSRT"
161
+ assert header.flags == 5
162
+ assert header.trailer == b"<3"
163
+ assert header.dumps() == data
164
+
165
+ cs = cstruct(endian=">")
166
+
167
+
168
+ class Node(Struct, cs=cs):
169
+ value: uint32
170
+ next: pointer["Node"] # A structure can point to itself
171
+
172
+
173
+ class NamedNode(Node): # A subclass starts with the fields of its parent
174
+ name: char[None] # A list index of None means null terminated
175
+
176
+
177
+ cs.load("struct list { uint32 count; NamedNode head; };") # Usable in C-like definitions
178
+
179
+ node = cs.list(b"\x00\x00\x00\x01" + b"\x00\x00\x00\x07" + b"\x00" * 8 + b"<3\x00").head
180
+ assert node.value == 7
181
+ assert node.name == b"<3"
182
+ ```
183
+
184
+ Each structure is registered in a cstruct instance, which can be passed with the `cs` class keyword argument, together with `align=True` for aligned structures. Without one, a structure uses the cstruct instance of the first bound type or structure in its annotations, or a new cstruct instance.
185
+
186
+ > [!NOTE]
187
+ > Field annotations are evaluated when the class is created. If your project uses Ruff's `flake8-type-checking` (`TC`) rules, add `Struct` and `Union` to the runtime-evaluated base classes, so that imports only used in field annotations are not moved into a `TYPE_CHECKING` block:
188
+ >
189
+ > ```toml
190
+ > [tool.ruff.lint.flake8-type-checking]
191
+ > runtime-evaluated-base-classes = ["dissect.cstruct.declarative.Struct", "dissect.cstruct.declarative.Union"]
192
+ > ```
193
+
140
194
  ### Type parsing
141
195
  Aside from loading structure definitions, any of the supported types can be used individually for parsing data. For example, the following is all supported:
142
196
 
@@ -258,6 +312,38 @@ assert example.magic == 1337
258
312
  assert example.data == b"arbitrary length data"
259
313
  ```
260
314
 
315
+ ### Converting to dicts and JSON
316
+ `asdict()` returns the field values of a structure or union as a dict, like `dataclasses.asdict()`. The method `_asdict()` does the same, like `namedtuple`. Nested structures and unions become dicts and arrays become lists. Other values are returned as they are, so enum members stay enum members and pointers are not dereferenced.
317
+
318
+ `asjson()` returns the same values as a JSON string. Bytes are encoded as base64 strings, and enum and flag members and pointers as numbers. To encode structures as part of other data, use `JSONEncoder` with `json.dumps()`.
319
+
320
+ ```python
321
+ import json
322
+
323
+ from dissect.cstruct import JSONEncoder, asdict, asjson, cstruct
324
+
325
+ c_def = """
326
+ enum Type : uint8 {
327
+ FILE = 1,
328
+ DIRECTORY = 2
329
+ };
330
+
331
+ struct entry {
332
+ Type type;
333
+ char name[4];
334
+ uint32 sizes[2];
335
+ };
336
+ """
337
+
338
+ c = cstruct().load(c_def)
339
+
340
+ entry = c.entry(b"\x01test\x01\x00\x00\x00\x02\x00\x00\x00")
341
+ assert asdict(entry) == {"type": c.Type.FILE, "name": b"test", "sizes": [1, 2]}
342
+ assert entry._asdict() == asdict(entry)
343
+ assert asjson(entry) == '{"type": 1, "name": "dGVzdA==", "sizes": [1, 2]}'
344
+ assert json.dumps({"entries": [entry]}, cls=JSONEncoder) == f'{{"entries": [{asjson(entry)}]}}'
345
+ ```
346
+
261
347
  ### Custom definition parsers
262
348
  Don't like the C-like definition syntax? Write your own syntax parser!
263
349
 
@@ -1,8 +1,9 @@
1
- dissect/cstruct/__init__.py,sha256=eO8ddn6U2EA_ta2QNKe8jYNgDVYC3gDBrafZ9Qqq4UM,1528
1
+ dissect/cstruct/__init__.py,sha256=ti1VYFx1MtZuDcMks14haNvUw0IZYjRo346ChzhqPls,1647
2
2
  dissect/cstruct/bitbuffer.py,sha256=aNzY4lkWe8ffAc8j7FODXzwZc8gZwbey77UosyoYCsw,2711
3
3
  dissect/cstruct/compiler.py,sha256=0u58J5pB4izosBj8G4wiBI1JSAAgHFMLM63IaSG4YO4,54509
4
4
  dissect/cstruct/cstruct.py,sha256=mJerzPouWV29RdK5LqjGitDDMvNKcadoT2hj1zpExnM,26551
5
- dissect/cstruct/dump.py,sha256=4PS4h9R9bmDveYMFBdkM1Nw1_wZy0UUES1CDc4qxtrA,18774
5
+ dissect/cstruct/declarative.py,sha256=5ubPtOyy6L5gJMFaPcbW3xYbTijZGMp0XJGxBeed1nE,14505
6
+ dissect/cstruct/dump.py,sha256=MxVJmn6v6cJs1Ud2FEmN0DaxKCUYOJk0YX4pWh1-1FQ,19013
6
7
  dissect/cstruct/exception.py,sha256=box-mw6FoP6c3vndvYLcTeJCZVgIG8IQVPEAg4zW0C8,380
7
8
  dissect/cstruct/expression.py,sha256=SbZRv7ueasYU4k-4k2eV1fjwL3JTAgF2UBaBvNjwiv4,10736
8
9
  dissect/cstruct/lexer.py,sha256=N7eqCOlcaQriUUIswJv16i-CE_sahYXGO-YdFO0IKKY,20421
@@ -11,7 +12,7 @@ dissect/cstruct/util.py,sha256=wdHZL8HhjG8LnATAxpQd50PnUJDM6XBJ9r8WlDzX830,8373
11
12
  dissect/cstruct/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
13
  dissect/cstruct/tools/stubgen.py,sha256=MeZkLmSeNSLNcAEwlAdIGv1lKvlvK3UQ4WN85ovsxTM,7672
13
14
  dissect/cstruct/types/__init__.py,sha256=6P71Pu94Dv7RNjZpDZ19pqzx-G0QzmQw4q0-3zWALso,911
14
- dissect/cstruct/types/base.py,sha256=bbaxiHCVkoU6ugqn5RYishPQ5L6xGrPfQuejjro0K_g,18133
15
+ dissect/cstruct/types/base.py,sha256=NdCP9dJk6lrKPERYjR9qeD2gFzWd6krVSN4tAOqqkvI,18357
15
16
  dissect/cstruct/types/char.py,sha256=N19R7Zzn2uMuG-ULW5X2UgmgkLvjaBj1Td7AQQI93Fg,3417
16
17
  dissect/cstruct/types/enum.py,sha256=nOdI6vGtqTfPMhOBkKuiuOriIB2YHSt8Q9ruri37s3U,9177
17
18
  dissect/cstruct/types/flag.py,sha256=YxQHix8ZhK1qQX3J_Og7GJp_4JAxCwzUbUibuJeDaWQ,3479
@@ -19,13 +20,13 @@ dissect/cstruct/types/int.py,sha256=9RbdrkvAI28zATM97VVORQnras0XhLaVMtdPjJwpTH4,
19
20
  dissect/cstruct/types/leb128.py,sha256=V97XTJT_Xbw1LpTwTN1OkjPHuQQAQUxd8OGuA6yEDmE,2387
20
21
  dissect/cstruct/types/packed.py,sha256=NgCX0YWX8SH8z47atq0f39w9MBjU_eBFJtUisUWdO-M,3867
21
22
  dissect/cstruct/types/pointer.py,sha256=FNuB9bfENWRebbKX-R6Vs6xWPMHepjvOhhomeUhr7I8,3985
22
- dissect/cstruct/types/structure.py,sha256=oY0Gx3b4wc9p74WgZjp38OnC2il_T9LLuBJaOBNbFVg,39655
23
+ dissect/cstruct/types/structure.py,sha256=EfsYgRNMcwvnUm6PStPu7yK_9BtRiJTaBlXDj0Eua7Y,43076
23
24
  dissect/cstruct/types/void.py,sha256=fV4hKk50uop_EKbR1nfy1cdtAzvUYrSymXsdakCyFk8,1222
24
25
  dissect/cstruct/types/wchar.py,sha256=VrnPXsP_lsyA-1xr4D2aSIVijumMhUuZWNlDHcn12-s,3964
25
- dissect_cstruct-5.0.dev17.dist-info/licenses/COPYRIGHT,sha256=H-18RXfshdH9AdHwW2eO1Xa-5s6tY5eipHh5c0whDu4,316
26
- dissect_cstruct-5.0.dev17.dist-info/licenses/LICENSE,sha256=PhUqiw6jAh2KbBdVRPBq_hfAvfcTBin7nZ3CK7NQbTM,11341
27
- dissect_cstruct-5.0.dev17.dist-info/METADATA,sha256=ImSng8tdv9I4QBU9NCE9cEPLeM6Z5DilPE5im_YmEyg,9256
28
- dissect_cstruct-5.0.dev17.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
29
- dissect_cstruct-5.0.dev17.dist-info/entry_points.txt,sha256=z53zqZqwD2OLrAkRwrP4wTeiU9CQe7xrMly0T2c0_wQ,71
30
- dissect_cstruct-5.0.dev17.dist-info/top_level.txt,sha256=Mn-CQzEYsAbkxrUI0TnplHuXnGVKzxpDw_po_sXpvv4,8
31
- dissect_cstruct-5.0.dev17.dist-info/RECORD,,
26
+ dissect_cstruct-5.0.dev19.dist-info/licenses/COPYRIGHT,sha256=H-18RXfshdH9AdHwW2eO1Xa-5s6tY5eipHh5c0whDu4,316
27
+ dissect_cstruct-5.0.dev19.dist-info/licenses/LICENSE,sha256=PhUqiw6jAh2KbBdVRPBq_hfAvfcTBin7nZ3CK7NQbTM,11341
28
+ dissect_cstruct-5.0.dev19.dist-info/METADATA,sha256=PkvBGlKF3RzyeIbZcPiTfDIo4cAY420raalRrq6vSJg,12661
29
+ dissect_cstruct-5.0.dev19.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
30
+ dissect_cstruct-5.0.dev19.dist-info/entry_points.txt,sha256=z53zqZqwD2OLrAkRwrP4wTeiU9CQe7xrMly0T2c0_wQ,71
31
+ dissect_cstruct-5.0.dev19.dist-info/top_level.txt,sha256=Mn-CQzEYsAbkxrUI0TnplHuXnGVKzxpDw_po_sXpvv4,8
32
+ dissect_cstruct-5.0.dev19.dist-info/RECORD,,