dissect.cstruct 5.0.dev16__tar.gz → 5.0.dev18__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.dev16 → dissect_cstruct-5.0.dev18}/CHANGELOG.md +7 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/PKG-INFO +56 -2
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/README.md +55 -1
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect/cstruct/__init__.py +1 -2
- dissect_cstruct-5.0.dev18/dissect/cstruct/declarative.py +460 -0
- dissect_cstruct-5.0.dev18/dissect/cstruct/dump.py +509 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect/cstruct/types/base.py +8 -2
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect/cstruct/types/structure.py +4 -3
- dissect_cstruct-5.0.dev18/dissect/cstruct/util.py +287 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect.cstruct.egg-info/PKG-INFO +56 -2
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect.cstruct.egg-info/SOURCES.txt +6 -2
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect.cstruct.egg-info/scm_file_list.json +6 -2
- dissect_cstruct-5.0.dev18/dissect.cstruct.egg-info/scm_version.json +8 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/examples/disk.py +46 -34
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/examples/mirai.py +7 -2
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/examples/pe.py +31 -26
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/examples/protobuf.py +4 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/examples/secdesc.py +29 -28
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/pyproject.toml +3 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_align.py +1 -1
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_basic.py +1 -2
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_bitfield.py +1 -2
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_compiler.py +1 -2
- dissect_cstruct-5.0.dev18/tests/test_declarative.py +506 -0
- dissect_cstruct-5.0.dev18/tests/test_dump.py +1052 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_parser.py +1 -1
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_types_base.py +11 -2
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_types_char.py +1 -2
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_types_enum.py +1 -1
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_types_flag.py +1 -2
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_types_int.py +1 -1
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_types_packed.py +1 -1
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_types_pointer.py +1 -2
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_types_structure.py +5 -2
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_types_union.py +1 -2
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_types_void.py +1 -1
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_types_wchar.py +1 -2
- dissect_cstruct-5.0.dev18/tests/test_util.py +102 -0
- dissect_cstruct-5.0.dev16/dissect/cstruct/util.py +0 -592
- dissect_cstruct-5.0.dev16/dissect.cstruct.egg-info/scm_version.json +0 -8
- dissect_cstruct-5.0.dev16/tests/test_utils.py +0 -351
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/.git-blame-ignore-revs +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/.gitattributes +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/COPYRIGHT +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/LICENSE +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/MANIFEST.in +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect/cstruct/bitbuffer.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect/cstruct/compiler.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect/cstruct/cstruct.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect/cstruct/exception.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect/cstruct/expression.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect/cstruct/lexer.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect/cstruct/parser.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect/cstruct/tools/__init__.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect/cstruct/tools/stubgen.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect/cstruct/types/__init__.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect/cstruct/types/char.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect/cstruct/types/enum.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect/cstruct/types/flag.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect/cstruct/types/int.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect/cstruct/types/leb128.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect/cstruct/types/packed.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect/cstruct/types/pointer.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect/cstruct/types/void.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect/cstruct/types/wchar.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect.cstruct.egg-info/dependency_links.txt +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect.cstruct.egg-info/entry_points.txt +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect.cstruct.egg-info/requires.txt +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/dissect.cstruct.egg-info/top_level.txt +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/setup.cfg +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/__init__.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/_data/testdef.txt +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/_docs/Makefile +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/_docs/__init__.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/_docs/conf.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/_docs/index.rst +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/conftest.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_annotations.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_benchmark.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_bitbuffer.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_ctypes.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_expression.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_lexer.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_tools_stubgen.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_types_custom.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tests/test_types_leb128.py +0 -0
- /dissect_cstruct-5.0.dev16/tests/utils.py → /dissect_cstruct-5.0.dev18/tests/util.py +0 -0
- {dissect_cstruct-5.0.dev16 → dissect_cstruct-5.0.dev18}/tox.ini +0 -0
|
@@ -6,6 +6,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- Declarative syntax for structures and unions in `dissect.cstruct.declarative`, using classes with type annotations.
|
|
12
|
+
|
|
9
13
|
### Changed
|
|
10
14
|
|
|
11
15
|
- Optimize storage of field sizes.
|
|
@@ -24,9 +28,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
|
24
28
|
- Improve writing performance:
|
|
25
29
|
- The compiler now generates code for writing structures and unions too! It uses a similar approach, grouping fields and writes where possible.
|
|
26
30
|
- `obj.dumps()` and `obj.write()` no longer create a `functools.partial` on every access. As a result, they no longer accept a `value` argument.
|
|
31
|
+
- `dumpstruct` can return a tree of all fields with their offset, size and value, with `output="dict"` or `output="json"`. `dumpstruct` and `hexdump` moved from `dissect.cstruct.util` to `dissect.cstruct.dump`.
|
|
32
|
+
- `dumpstruct` shows the fields of every element of an array of structures or unions.
|
|
27
33
|
|
|
28
34
|
### Fixed
|
|
29
35
|
|
|
36
|
+
- `dumpstruct` colors the right bytes of structures with padding and unions.
|
|
30
37
|
- Structures and unions no longer share nested structures and arrays between their default values.
|
|
31
38
|
- Unions can be created with default values and read if they have doubly nested structures or nested unions.
|
|
32
39
|
- Writing a `bytearray` to a `char` array no longer modifies the `bytearray`.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: dissect.cstruct
|
|
3
|
-
Version: 5.0.
|
|
3
|
+
Version: 5.0.dev18
|
|
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
|
|
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
|
|
|
@@ -101,7 +101,7 @@ assert instance.dumps() == b"\x05loremipsum\x05\x00\x00\x00"
|
|
|
101
101
|
|
|
102
102
|
```
|
|
103
103
|
|
|
104
|
-
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
|
|
104
|
+
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__)`.
|
|
105
105
|
|
|
106
106
|
More examples can be found in the `examples` directory.
|
|
107
107
|
|
|
@@ -109,6 +109,60 @@ More examples can be found in the `examples` directory.
|
|
|
109
109
|
### Structure parsing
|
|
110
110
|
Write simple C-like structures and use them to parse binary data, as can be seen in the examples.
|
|
111
111
|
|
|
112
|
+
### Declarative structure definitions
|
|
113
|
+
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.
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
from typing import Annotated
|
|
117
|
+
|
|
118
|
+
from dissect.cstruct import cstruct
|
|
119
|
+
from dissect.cstruct.declarative import EOF, Struct, char, field, pointer, uint8, uint16, uint32
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class Header(Struct):
|
|
123
|
+
magic: uint8[4]
|
|
124
|
+
size: uint32
|
|
125
|
+
data: char["size"] # Array sizes can refer to other fields
|
|
126
|
+
flags: Annotated[uint16, field(bits=4)] # Or field(uint16, bits=4)
|
|
127
|
+
trailer: char[EOF] # Reads until the end of the data
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
data = b"ohai\x0c\x00\x00\x00KUSJESVANSRT\x05\x00<3"
|
|
131
|
+
header = Header(data)
|
|
132
|
+
assert header.data == b"KUSJESVANSRT"
|
|
133
|
+
assert header.flags == 5
|
|
134
|
+
assert header.trailer == b"<3"
|
|
135
|
+
assert header.dumps() == data
|
|
136
|
+
|
|
137
|
+
cs = cstruct(endian=">")
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class Node(Struct, cs=cs):
|
|
141
|
+
value: uint32
|
|
142
|
+
next: pointer["Node"] # A structure can point to itself
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class NamedNode(Node): # A subclass starts with the fields of its parent
|
|
146
|
+
name: char[None] # A list index of None means null terminated
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
cs.load("struct list { uint32 count; NamedNode head; };") # Usable in C-like definitions
|
|
150
|
+
|
|
151
|
+
node = cs.list(b"\x00\x00\x00\x01" + b"\x00\x00\x00\x07" + b"\x00" * 8 + b"<3\x00").head
|
|
152
|
+
assert node.value == 7
|
|
153
|
+
assert node.name == b"<3"
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
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.
|
|
157
|
+
|
|
158
|
+
> [!NOTE]
|
|
159
|
+
> 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:
|
|
160
|
+
>
|
|
161
|
+
> ```toml
|
|
162
|
+
> [tool.ruff.lint.flake8-type-checking]
|
|
163
|
+
> runtime-evaluated-base-classes = ["dissect.cstruct.declarative.Struct", "dissect.cstruct.declarative.Union"]
|
|
164
|
+
> ```
|
|
165
|
+
|
|
112
166
|
### Type parsing
|
|
113
167
|
Aside from loading structure definitions, any of the supported types can be used individually for parsing data. For example, the following is all supported:
|
|
114
168
|
|
|
@@ -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`."""
|