dissect.cstruct 5.0.dev18__tar.gz → 5.0.dev19__tar.gz
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-5.0.dev18 → dissect_cstruct-5.0.dev19}/CHANGELOG.md +1 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/PKG-INFO +33 -1
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/README.md +32 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/__init__.py +4 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/dump.py +3 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/types/structure.py +88 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect.cstruct.egg-info/PKG-INFO +33 -1
- dissect_cstruct-5.0.dev19/dissect.cstruct.egg-info/scm_version.json +8 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_declarative.py +17 -1
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_types_structure.py +145 -1
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_types_union.py +45 -1
- dissect_cstruct-5.0.dev18/dissect.cstruct.egg-info/scm_version.json +0 -8
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/.git-blame-ignore-revs +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/.gitattributes +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/COPYRIGHT +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/LICENSE +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/MANIFEST.in +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/bitbuffer.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/compiler.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/cstruct.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/declarative.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/exception.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/expression.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/lexer.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/parser.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/tools/__init__.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/tools/stubgen.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/types/__init__.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/types/base.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/types/char.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/types/enum.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/types/flag.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/types/int.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/types/leb128.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/types/packed.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/types/pointer.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/types/void.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/types/wchar.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect/cstruct/util.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect.cstruct.egg-info/SOURCES.txt +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect.cstruct.egg-info/dependency_links.txt +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect.cstruct.egg-info/entry_points.txt +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect.cstruct.egg-info/requires.txt +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect.cstruct.egg-info/scm_file_list.json +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect.cstruct.egg-info/top_level.txt +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/examples/disk.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/examples/mirai.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/examples/pe.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/examples/protobuf.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/examples/secdesc.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/pyproject.toml +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/setup.cfg +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/__init__.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/_data/testdef.txt +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/_docs/Makefile +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/_docs/__init__.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/_docs/conf.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/_docs/index.rst +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/conftest.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_align.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_annotations.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_basic.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_benchmark.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_bitbuffer.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_bitfield.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_compiler.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_ctypes.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_dump.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_expression.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_lexer.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_parser.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_tools_stubgen.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_types_base.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_types_char.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_types_custom.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_types_enum.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_types_flag.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_types_int.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_types_leb128.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_types_packed.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_types_pointer.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_types_void.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_types_wchar.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/test_util.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tests/util.py +0 -0
- {dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/tox.ini +0 -0
|
@@ -9,6 +9,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
|
9
9
|
### Added
|
|
10
10
|
|
|
11
11
|
- Declarative syntax for structures and unions in `dissect.cstruct.declarative`, using classes with type annotations.
|
|
12
|
+
- `asdict()` and the `_asdict()` method return the field values of a structure or union as a dict, with nested structures as dicts and arrays as lists. `asjson()` returns them as a JSON string, with bytes as base64 and enum members as numbers. `JSONEncoder` encodes structures as part of other data with `json.dumps()`.
|
|
12
13
|
|
|
13
14
|
### Changed
|
|
14
15
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: dissect.cstruct
|
|
3
|
-
Version: 5.0.
|
|
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
|
|
@@ -312,6 +312,38 @@ assert example.magic == 1337
|
|
|
312
312
|
assert example.data == b"arbitrary length data"
|
|
313
313
|
```
|
|
314
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
|
+
|
|
315
347
|
### Custom definition parsers
|
|
316
348
|
Don't like the C-like definition syntax? Write your own syntax parser!
|
|
317
349
|
|
|
@@ -284,6 +284,38 @@ assert example.magic == 1337
|
|
|
284
284
|
assert example.data == b"arbitrary length data"
|
|
285
285
|
```
|
|
286
286
|
|
|
287
|
+
### Converting to dicts and JSON
|
|
288
|
+
`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.
|
|
289
|
+
|
|
290
|
+
`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()`.
|
|
291
|
+
|
|
292
|
+
```python
|
|
293
|
+
import json
|
|
294
|
+
|
|
295
|
+
from dissect.cstruct import JSONEncoder, asdict, asjson, cstruct
|
|
296
|
+
|
|
297
|
+
c_def = """
|
|
298
|
+
enum Type : uint8 {
|
|
299
|
+
FILE = 1,
|
|
300
|
+
DIRECTORY = 2
|
|
301
|
+
};
|
|
302
|
+
|
|
303
|
+
struct entry {
|
|
304
|
+
Type type;
|
|
305
|
+
char name[4];
|
|
306
|
+
uint32 sizes[2];
|
|
307
|
+
};
|
|
308
|
+
"""
|
|
309
|
+
|
|
310
|
+
c = cstruct().load(c_def)
|
|
311
|
+
|
|
312
|
+
entry = c.entry(b"\x01test\x01\x00\x00\x00\x02\x00\x00\x00")
|
|
313
|
+
assert asdict(entry) == {"type": c.Type.FILE, "name": b"test", "sizes": [1, 2]}
|
|
314
|
+
assert entry._asdict() == asdict(entry)
|
|
315
|
+
assert asjson(entry) == '{"type": 1, "name": "dGVzdA==", "sizes": [1, 2]}'
|
|
316
|
+
assert json.dumps({"entries": [entry]}, cls=JSONEncoder) == f'{{"entries": [{asjson(entry)}]}}'
|
|
317
|
+
```
|
|
318
|
+
|
|
287
319
|
### Custom definition parsers
|
|
288
320
|
Don't like the C-like definition syntax? Write your own syntax parser!
|
|
289
321
|
|
|
@@ -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",
|
|
@@ -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,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
|
|
@@ -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.
|
|
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
|
|
@@ -312,6 +312,38 @@ assert example.magic == 1337
|
|
|
312
312
|
assert example.data == b"arbitrary length data"
|
|
313
313
|
```
|
|
314
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
|
+
|
|
315
347
|
### Custom definition parsers
|
|
316
348
|
Don't like the C-like definition syntax? Write your own syntax parser!
|
|
317
349
|
|
|
@@ -22,7 +22,7 @@ from dissect.cstruct.declarative import (
|
|
|
22
22
|
uint64,
|
|
23
23
|
)
|
|
24
24
|
from dissect.cstruct.types.pointer import Pointer
|
|
25
|
-
from dissect.cstruct.types.structure import Structure, StructureMetaType, UnionMetaType
|
|
25
|
+
from dissect.cstruct.types.structure import Structure, StructureMetaType, UnionMetaType, asdict
|
|
26
26
|
from dissect.cstruct.types.structure import Union as CUnion
|
|
27
27
|
|
|
28
28
|
# Module level cstruct instance to exercise bound-type inference through stringified annotations
|
|
@@ -418,6 +418,22 @@ def test_char_and_bytes(cs: cstruct) -> None:
|
|
|
418
418
|
assert obj.value == 1
|
|
419
419
|
|
|
420
420
|
|
|
421
|
+
def test_asdict(cs: cstruct) -> None:
|
|
422
|
+
"""Test that asdict has the fields of a structure, not its other attributes."""
|
|
423
|
+
|
|
424
|
+
class Header(Struct, cs=cs):
|
|
425
|
+
magic: char[4]
|
|
426
|
+
size: uint32
|
|
427
|
+
|
|
428
|
+
@property
|
|
429
|
+
def total_size(self) -> int:
|
|
430
|
+
return self.size + 8
|
|
431
|
+
|
|
432
|
+
obj = Header(b"test\x01\x00\x00\x00")
|
|
433
|
+
assert obj.total_size == 9
|
|
434
|
+
assert asdict(obj) == {"magic": b"test", "size": 1}
|
|
435
|
+
|
|
436
|
+
|
|
421
437
|
def test_endian(cs: cstruct) -> None:
|
|
422
438
|
big = cstruct(endian=">")
|
|
423
439
|
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
3
|
import inspect
|
|
4
|
+
import json
|
|
4
5
|
from io import BytesIO
|
|
5
6
|
from textwrap import dedent
|
|
6
7
|
from types import MethodType
|
|
@@ -13,7 +14,7 @@ from dissect.cstruct.exception import ArraySizeError, ResolveError
|
|
|
13
14
|
from dissect.cstruct.types import structure
|
|
14
15
|
from dissect.cstruct.types.base import Array, BaseType
|
|
15
16
|
from dissect.cstruct.types.pointer import Pointer
|
|
16
|
-
from dissect.cstruct.types.structure import Field, Structure, StructureMetaType
|
|
17
|
+
from dissect.cstruct.types.structure import Field, JSONEncoder, Structure, StructureMetaType, asdict, asjson
|
|
17
18
|
from tests.util import verify_compiled
|
|
18
19
|
|
|
19
20
|
|
|
@@ -308,6 +309,149 @@ def test_structure_values_dict(cs: cstruct, compiled: bool) -> None:
|
|
|
308
309
|
assert values.keys() == {"magic", "wmagic", "a", "b", "c", "string", "wstring"}
|
|
309
310
|
|
|
310
311
|
|
|
312
|
+
def test_structure_asdict(cs: cstruct, compiled: bool) -> None:
|
|
313
|
+
"""Test that asdict converts nested structures and arrays, and returns other values as they are."""
|
|
314
|
+
cdef = """
|
|
315
|
+
enum Color : uint8 {
|
|
316
|
+
RED = 1
|
|
317
|
+
};
|
|
318
|
+
|
|
319
|
+
struct inner {
|
|
320
|
+
uint8 x;
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
struct test {
|
|
324
|
+
uint32 a;
|
|
325
|
+
Color color;
|
|
326
|
+
char magic[4];
|
|
327
|
+
wchar wmagic[2];
|
|
328
|
+
inner nested;
|
|
329
|
+
inner arr[2];
|
|
330
|
+
uint8 matrix[2][2];
|
|
331
|
+
char names[2][2];
|
|
332
|
+
struct {
|
|
333
|
+
uint8 anon;
|
|
334
|
+
};
|
|
335
|
+
uint8 class;
|
|
336
|
+
uint8 _;
|
|
337
|
+
uint8 _;
|
|
338
|
+
uint8 bits : 4;
|
|
339
|
+
Color color_bits : 4;
|
|
340
|
+
};
|
|
341
|
+
"""
|
|
342
|
+
cs.load(cdef, compiled=compiled)
|
|
343
|
+
|
|
344
|
+
assert verify_compiled(cs.test, compiled)
|
|
345
|
+
|
|
346
|
+
buf = b"\x01\x00\x00\x00\x01testh\x00i\x00\x07\x08\x09\x01\x02\x03\x04abcd\x05\x06\xaa\xbb\x12"
|
|
347
|
+
obj = cs.test(buf)
|
|
348
|
+
|
|
349
|
+
result = asdict(obj)
|
|
350
|
+
assert result == {
|
|
351
|
+
"a": 1,
|
|
352
|
+
"color": cs.Color.RED,
|
|
353
|
+
"magic": b"test",
|
|
354
|
+
"wmagic": "hi",
|
|
355
|
+
"nested": {"x": 7},
|
|
356
|
+
"arr": [{"x": 8}, {"x": 9}],
|
|
357
|
+
"matrix": [[1, 2], [3, 4]],
|
|
358
|
+
"names": [b"ab", b"cd"],
|
|
359
|
+
"anon": 5,
|
|
360
|
+
"class": 6,
|
|
361
|
+
"_": 0xBB,
|
|
362
|
+
"bits": 2,
|
|
363
|
+
"color_bits": cs.Color.RED,
|
|
364
|
+
}
|
|
365
|
+
assert list(result) == list(cs.test.__members__)
|
|
366
|
+
assert result["color"] is cs.Color.RED
|
|
367
|
+
|
|
368
|
+
# The dicts and lists are new
|
|
369
|
+
result["arr"][0]["x"] = 0
|
|
370
|
+
result["matrix"][0][0] = 0
|
|
371
|
+
assert obj.arr[0].x == 8
|
|
372
|
+
assert obj.matrix[0][0] == 1
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def test_structure_asdict_pointer(cs: cstruct, compiled: bool) -> None:
|
|
376
|
+
"""Test that asdict doesn't dereference pointers, which may be null."""
|
|
377
|
+
cdef = """
|
|
378
|
+
struct node {
|
|
379
|
+
uint32 value;
|
|
380
|
+
struct node *next;
|
|
381
|
+
};
|
|
382
|
+
"""
|
|
383
|
+
cs.pointer = cs.uint32
|
|
384
|
+
cs.load(cdef, compiled=compiled)
|
|
385
|
+
|
|
386
|
+
assert verify_compiled(cs.node, compiled)
|
|
387
|
+
|
|
388
|
+
obj = cs.node(b"\x01\x00\x00\x00\x08\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00")
|
|
389
|
+
|
|
390
|
+
result = asdict(obj)
|
|
391
|
+
assert result == {"value": 1, "next": 8}
|
|
392
|
+
assert result["next"] is obj.next
|
|
393
|
+
|
|
394
|
+
assert asdict(obj.next.dereference()) == {"value": 2, "next": 0}
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def test_structure_asdict_invalid(cs: cstruct) -> None:
|
|
398
|
+
"""Test that asdict and asjson only accept structure instances."""
|
|
399
|
+
cs.load("struct test { uint8 a; };")
|
|
400
|
+
|
|
401
|
+
with pytest.raises(TypeError, match=r"^asdict\(\) should be called on Structure instances$"):
|
|
402
|
+
asdict(cs.test)
|
|
403
|
+
|
|
404
|
+
with pytest.raises(TypeError, match=r"^asdict\(\) should be called on Structure instances$"):
|
|
405
|
+
asjson(1)
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def test_structure_asjson(cs: cstruct, compiled: bool) -> None:
|
|
409
|
+
"""Test that bytes are encoded as base64, void as null, and enums, flags and pointers as integers."""
|
|
410
|
+
cdef = """
|
|
411
|
+
enum Color : uint8 {
|
|
412
|
+
RED = 1
|
|
413
|
+
};
|
|
414
|
+
|
|
415
|
+
flag Perm : uint8 {
|
|
416
|
+
R = 1,
|
|
417
|
+
W = 2
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
struct inner {
|
|
421
|
+
uint8 x;
|
|
422
|
+
};
|
|
423
|
+
|
|
424
|
+
struct test {
|
|
425
|
+
Color color;
|
|
426
|
+
Perm perm;
|
|
427
|
+
char magic[4];
|
|
428
|
+
wchar wmagic[2];
|
|
429
|
+
float f;
|
|
430
|
+
void nothing;
|
|
431
|
+
inner nested;
|
|
432
|
+
char *name;
|
|
433
|
+
};
|
|
434
|
+
"""
|
|
435
|
+
cs.pointer = cs.uint32
|
|
436
|
+
cs.load(cdef, compiled=compiled)
|
|
437
|
+
|
|
438
|
+
assert verify_compiled(cs.test, compiled)
|
|
439
|
+
|
|
440
|
+
obj = cs.test(b"\x01\x03\x00\xffabh\x00i\x00\x00\x00\xc0\x3f\x07\x10\x00\x00\x00")
|
|
441
|
+
|
|
442
|
+
expected = (
|
|
443
|
+
'{"color": 1, "perm": 3, "magic": "AP9hYg==", "wmagic": "hi", "f": 1.5, "nothing": null, '
|
|
444
|
+
'"nested": {"x": 7}, "name": 16}'
|
|
445
|
+
)
|
|
446
|
+
assert asjson(obj) == expected
|
|
447
|
+
assert json.dumps({"header": obj, "nested": [obj.nested]}, cls=JSONEncoder) == (
|
|
448
|
+
f'{{"header": {expected}, "nested": [{{"x": 7}}]}}'
|
|
449
|
+
)
|
|
450
|
+
|
|
451
|
+
assert asjson(obj.nested, indent=1) == '{\n "x": 7\n}'
|
|
452
|
+
assert json.dumps(bytearray(b"\x00\xff"), cls=JSONEncoder) == '"AP8="'
|
|
453
|
+
|
|
454
|
+
|
|
311
455
|
def test_structure_definition_simple_be(cs: cstruct, compiled: bool) -> None:
|
|
312
456
|
cdef = """
|
|
313
457
|
struct test {
|
|
@@ -2,6 +2,7 @@ from __future__ import annotations
|
|
|
2
2
|
|
|
3
3
|
import inspect
|
|
4
4
|
import io
|
|
5
|
+
import json
|
|
5
6
|
from textwrap import dedent
|
|
6
7
|
|
|
7
8
|
import pytest
|
|
@@ -10,7 +11,7 @@ from dissect.cstruct import compiler
|
|
|
10
11
|
from dissect.cstruct.cstruct import cstruct
|
|
11
12
|
from dissect.cstruct.types import structure
|
|
12
13
|
from dissect.cstruct.types.base import Array, BaseType
|
|
13
|
-
from dissect.cstruct.types.structure import Field, Union, UnionProxy
|
|
14
|
+
from dissect.cstruct.types.structure import Field, JSONEncoder, Union, UnionProxy, asdict
|
|
14
15
|
from tests.util import parsed_state, source_lines, verify_compiled
|
|
15
16
|
|
|
16
17
|
|
|
@@ -885,6 +886,49 @@ def test_union_in_union(cs: cstruct, compiled: bool) -> None:
|
|
|
885
886
|
assert obj.dumps() == b"\x02"
|
|
886
887
|
|
|
887
888
|
|
|
889
|
+
def test_union_asdict(cs: cstruct, compiled: bool) -> None:
|
|
890
|
+
"""Test that asdict has all fields of a union, and unwraps the proxies of structures in (nested) unions."""
|
|
891
|
+
cdef = """
|
|
892
|
+
struct inner {
|
|
893
|
+
uint8 x;
|
|
894
|
+
uint8 y;
|
|
895
|
+
};
|
|
896
|
+
|
|
897
|
+
union test {
|
|
898
|
+
inner nested;
|
|
899
|
+
uint16 raw;
|
|
900
|
+
struct {
|
|
901
|
+
uint8 lo;
|
|
902
|
+
uint8 hi;
|
|
903
|
+
};
|
|
904
|
+
};
|
|
905
|
+
|
|
906
|
+
union outer {
|
|
907
|
+
test u;
|
|
908
|
+
uint16 raw;
|
|
909
|
+
};
|
|
910
|
+
|
|
911
|
+
struct holder {
|
|
912
|
+
uint8 a;
|
|
913
|
+
test u;
|
|
914
|
+
};
|
|
915
|
+
"""
|
|
916
|
+
cs.load(cdef, compiled=compiled)
|
|
917
|
+
|
|
918
|
+
assert verify_compiled(cs.test, compiled)
|
|
919
|
+
assert verify_compiled(cs.holder, compiled)
|
|
920
|
+
|
|
921
|
+
test = {"nested": {"x": 1, "y": 2}, "raw": 0x0201, "lo": 1, "hi": 2}
|
|
922
|
+
assert asdict(cs.test(b"\x01\x02")) == test
|
|
923
|
+
assert asdict(cs.holder(b"\x00\x01\x02")) == {"a": 0, "u": test}
|
|
924
|
+
|
|
925
|
+
obj = cs.outer(b"\x01\x02")
|
|
926
|
+
assert isinstance(obj.u.nested.__target__, UnionProxy)
|
|
927
|
+
assert asdict(obj) == {"u": test, "raw": 0x0201}
|
|
928
|
+
assert asdict(obj.u.nested) == {"x": 1, "y": 2}
|
|
929
|
+
assert json.dumps(obj.u.nested, cls=JSONEncoder) == '{"x": 1, "y": 2}'
|
|
930
|
+
|
|
931
|
+
|
|
888
932
|
def test_union_write_largest_field(cs: cstruct, compiled: bool) -> None:
|
|
889
933
|
"""Test that a union is written by its largest field, and raises errors for invalid and missing values."""
|
|
890
934
|
cdef = """
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect.cstruct.egg-info/SOURCES.txt
RENAMED
|
File without changes
|
|
File without changes
|
{dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect.cstruct.egg-info/entry_points.txt
RENAMED
|
File without changes
|
{dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect.cstruct.egg-info/requires.txt
RENAMED
|
File without changes
|
{dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect.cstruct.egg-info/scm_file_list.json
RENAMED
|
File without changes
|
{dissect_cstruct-5.0.dev18 → dissect_cstruct-5.0.dev19}/dissect.cstruct.egg-info/top_level.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|