dissect.cstruct 5.0.dev24__tar.gz → 5.0.dev26__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.dev24 → dissect_cstruct-5.0.dev26}/CHANGELOG.md +22 -1
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/PKG-INFO +41 -8
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/README.md +40 -7
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect/cstruct/bitbuffer.py +8 -1
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect/cstruct/compiler.py +39 -17
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect/cstruct/cstruct.py +48 -9
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect/cstruct/declarative.py +4 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect/cstruct/dump.py +1 -1
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect/cstruct/tools/stubgen.py +9 -2
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect/cstruct/types/base.py +125 -17
- dissect_cstruct-5.0.dev26/dissect/cstruct/types/char.py +210 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect/cstruct/types/enum.py +2 -1
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect/cstruct/types/int.py +7 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect/cstruct/types/packed.py +18 -1
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect/cstruct/types/pointer.py +16 -12
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect/cstruct/types/structure.py +104 -26
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect/cstruct/types/void.py +9 -0
- dissect_cstruct-5.0.dev26/dissect/cstruct/types/wchar.py +201 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect.cstruct.egg-info/PKG-INFO +41 -8
- dissect_cstruct-5.0.dev26/dissect.cstruct.egg-info/scm_version.json +8 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/examples/protobuf.py +1 -1
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_align.py +13 -13
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_annotations.py +1 -1
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_basic.py +99 -25
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_benchmark.py +1 -1
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_bitfield.py +25 -36
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_compiler.py +30 -26
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_declarative.py +29 -3
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_expression.py +16 -15
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_tools_stubgen.py +39 -18
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_types_base.py +152 -16
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_types_char.py +100 -38
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_types_custom.py +6 -3
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_types_enum.py +17 -17
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_types_flag.py +8 -7
- dissect_cstruct-5.0.dev26/tests/test_types_int.py +324 -0
- dissect_cstruct-5.0.dev26/tests/test_types_leb128.py +134 -0
- dissect_cstruct-5.0.dev26/tests/test_types_packed.py +219 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_types_pointer.py +40 -18
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_types_structure.py +353 -63
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_types_union.py +74 -41
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_types_void.py +6 -6
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_types_wchar.py +106 -55
- dissect_cstruct-5.0.dev26/tests/test_util.py +171 -0
- dissect_cstruct-5.0.dev24/dissect/cstruct/types/char.py +0 -103
- dissect_cstruct-5.0.dev24/dissect/cstruct/types/wchar.py +0 -116
- dissect_cstruct-5.0.dev24/dissect.cstruct.egg-info/scm_version.json +0 -8
- dissect_cstruct-5.0.dev24/tests/test_types_int.py +0 -452
- dissect_cstruct-5.0.dev24/tests/test_types_leb128.py +0 -205
- dissect_cstruct-5.0.dev24/tests/test_types_packed.py +0 -276
- dissect_cstruct-5.0.dev24/tests/test_util.py +0 -157
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/.git-blame-ignore-revs +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/.gitattributes +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/COPYRIGHT +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/LICENSE +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/MANIFEST.in +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect/cstruct/__init__.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect/cstruct/exception.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect/cstruct/expression.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect/cstruct/lexer.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect/cstruct/parser.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect/cstruct/tools/__init__.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect/cstruct/types/__init__.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect/cstruct/types/flag.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect/cstruct/types/leb128.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect/cstruct/util.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect.cstruct.egg-info/SOURCES.txt +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect.cstruct.egg-info/dependency_links.txt +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect.cstruct.egg-info/entry_points.txt +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect.cstruct.egg-info/requires.txt +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect.cstruct.egg-info/scm_file_list.json +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/dissect.cstruct.egg-info/top_level.txt +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/examples/disk.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/examples/mirai.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/examples/pe.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/examples/secdesc.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/pyproject.toml +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/setup.cfg +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/__init__.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/_data/testdef.txt +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/_docs/Makefile +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/_docs/__init__.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/_docs/conf.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/_docs/index.rst +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/conftest.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_bitbuffer.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_ctypes.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_dump.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_exception.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_lexer.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/test_parser.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tests/util.py +0 -0
- {dissect_cstruct-5.0.dev24 → dissect_cstruct-5.0.dev26}/tox.ini +0 -0
|
@@ -9,8 +9,9 @@ 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()`
|
|
12
|
+
- `asdict()` returns 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()`.
|
|
13
13
|
- `sizeof` and `offsetof` in expressions accept a type name like the type of a field, e.g. `sizeof(struct header *[4])`. An argument that isn't a type name raises an `ExpressionParserError` when the expression is created.
|
|
14
|
+
- `copy()` method (and `copy.copy()`) to copy a `cstruct` instance with its types, constants and settings. Changes to the copy, such as new definitions or a different endianness, don't affect the original. Enums and flags of a copy are separate classes, so their members don't compare equal to those of the original. Compare against the copied enum, or with the value instead: `c2.Color.RED == cs.Color.RED.value`.
|
|
14
15
|
|
|
15
16
|
### Changed
|
|
16
17
|
|
|
@@ -44,6 +45,25 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
|
44
45
|
- Errors that `load` raises include the line of the definition.
|
|
45
46
|
- `ArraySizeError` is removed. A value that is longer than its static array raises a `WriteError`.
|
|
46
47
|
- `write()` raises a `TypeError` for an object that can't be written to, like `read()` does.
|
|
48
|
+
- `bytes(obj)` works on instances of all types. It gives the byte representation of the value.
|
|
49
|
+
- For null-terminated arrays, it does not include the null terminator. Use `cls.dumps(obj)` to include the null terminator.
|
|
50
|
+
- For integer types, `bytearray(obj)` gives as many zero bytes as its value, e.g. `bytearray(cs.uint32(5))` gives 5 zero bytes. Use `bytearray(bytes(obj))` instead.
|
|
51
|
+
- `char` and `char` arrays no longer accept a string, when they're created or written. Encode the string to bytes first.
|
|
52
|
+
- Writing doesn't convert values anymore (e.g. `type.write(stream, value)`, or manually setting an attribute on a structure instance): a `char` doesn't accept an int, and `uint8` arrays don't accept bytes. Convert the value first, e.g. `cs.char(0x41)` or `cs.uint8[2](b"\x01\x02")`, or pass it as an argument when the structure is created.
|
|
53
|
+
- Creating a `char`, a `wchar` or an array from a value instead of from data:
|
|
54
|
+
- An int creates a `char` with that byte, e.g. `cs.char(0x41)` is `b"A"`.
|
|
55
|
+
- Arrays of all types with a fixed number of entries add default entries to a value with fewer entries, e.g. `cs.char[4]([0x41])` is `b"A\x00\x00\x00"`, `cs.wchar[4]("A")` is `"A\x00\x00\x00"` and `cs.uint8[4]([1])` and `cs.uleb128[4]([1])` are `[1, 0, 0, 0]`.
|
|
56
|
+
- A value with more entries than the array, or more than one character for a `char` or `wchar`, raises a `ValueError`.
|
|
57
|
+
- Without a value, the result is the default value, e.g. `cs.char()` is `b"\x00"` and `cs.uint8[4]()` is `[0, 0, 0, 0]`.
|
|
58
|
+
- `TypeError` is raised for unsupported values.
|
|
59
|
+
- On Python 3.12 and newer, instances of all types support the buffer protocol, so that e.g. `fh.write(obj)` works.
|
|
60
|
+
- Values that are given when a structure or union is created are converted to the types of their fields, like the type does. E.g. in `struct test { uint16 values[2]; }`, `cs.test(values=[1, 2]).values` is a `uint16[2]` and `cs.test(values=b"\x01\x00\x02\x00").values` is `[1, 2]`.
|
|
61
|
+
- More bytes than a field needs raise a `ValueError`, e.g. `cs.test(values=b"\x01\x00\x02\x00\x03\x00")`.
|
|
62
|
+
- Values that are set as attributes aren't converted, e.g. `cs.test().values = [1, 2]`. For performance reasons this is impractical.
|
|
63
|
+
|
|
64
|
+
### Deprecated
|
|
65
|
+
|
|
66
|
+
- `obj.dumps()` and `obj.write(fh)` on instances. Use `cls.dumps(obj)` and `cls.write(fh, obj)` instead.
|
|
47
67
|
|
|
48
68
|
### Fixed
|
|
49
69
|
|
|
@@ -63,6 +83,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
|
63
83
|
- An `Expression` is parsed when it's created. An invalid array size that refers to a field, e.g. `char a[n +]`, raises a `ParserError` during `load`, instead of an `ExpressionParserError` on every read.
|
|
64
84
|
- `offsetof` gives the offsets of C for the fields of a union and the fields of an anonymous nested structure or union, instead of an error or the offset in the nested type.
|
|
65
85
|
- An empty expression raises "not enough operands" instead of "too many operands".
|
|
86
|
+
- Writing an array with a fixed number of entries of a dynamic size, e.g. `uleb128 a[4]` or an array of structures with a dynamic size, pads it to its number of entries or raises a `WriteError` if it's too long, instead of writing as many entries as the value has.
|
|
66
87
|
|
|
67
88
|
## [4.5] - 20-05-2025
|
|
68
89
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: dissect.cstruct
|
|
3
|
-
Version: 5.0.
|
|
3
|
+
Version: 5.0.dev26
|
|
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
|
|
@@ -118,14 +118,13 @@ assert c_parser.Example.A == 0
|
|
|
118
118
|
assert c_parser.Example.C == 6
|
|
119
119
|
assert c_parser.Example(5) == c_parser.Example.B
|
|
120
120
|
|
|
121
|
-
assert result
|
|
121
|
+
assert bytes(result) == data
|
|
122
122
|
|
|
123
123
|
# You can also instantiate structures from Python by using kwargs
|
|
124
|
-
# Note that array sizes are not enforced
|
|
125
124
|
instance = c_parser.some_struct(
|
|
126
|
-
field_1=5, field_2="lorem", field_3="ipsum", field_4=[c_parser.Example.B, c_parser.Example.A]
|
|
125
|
+
field_1=5, field_2=b"lorem", field_3=b"ipsum", field_4=[c_parser.Example.B, c_parser.Example.A]
|
|
127
126
|
)
|
|
128
|
-
assert instance
|
|
127
|
+
assert bytes(instance) == b"\x05loremipsum\x05\x00\x00\x00"
|
|
129
128
|
|
|
130
129
|
```
|
|
131
130
|
|
|
@@ -160,7 +159,7 @@ header = Header(data)
|
|
|
160
159
|
assert header.data == b"KUSJESVANSRT"
|
|
161
160
|
assert header.flags == 5
|
|
162
161
|
assert header.trailer == b"<3"
|
|
163
|
-
assert header
|
|
162
|
+
assert bytes(header) == data
|
|
164
163
|
|
|
165
164
|
cs = cstruct(endian=">")
|
|
166
165
|
|
|
@@ -205,6 +204,40 @@ assert cs.uint24[2](b"\x01\x00\x00\x02\x00\x00") == [1, 2] # You can also parse
|
|
|
205
204
|
assert cs.char[None](b"hello world!\x00") == b"hello world!" # A list index of None means null terminated
|
|
206
205
|
```
|
|
207
206
|
|
|
207
|
+
### Creating values
|
|
208
|
+
A type creates a value like its Python base type does, e.g. `int` for `uint32` and `list` for arrays. Bytes-like and file-like objects are parsed instead.
|
|
209
|
+
|
|
210
|
+
```python
|
|
211
|
+
from dissect.cstruct import cstruct
|
|
212
|
+
|
|
213
|
+
cs = cstruct()
|
|
214
|
+
assert cs.uint32("5") == 5 # Like int("5")
|
|
215
|
+
assert cs.uint32(b"\x05\x00\x00\x00") == 5 # Parsed
|
|
216
|
+
assert cs.uint8[4]([1, 2]) == [1, 2, 0, 0] # Padded to the number of entries
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
Some types don't accept all the values of their Python base type:
|
|
220
|
+
- `char` and `char` arrays don't accept a `str`, encode it to bytes first. An `int` gives a single character, e.g. `cs.char(0x41)` is `b"A"`.
|
|
221
|
+
- `wchar` and `wchar` arrays only accept a `str`.
|
|
222
|
+
- Other arrays don't accept a `str` or an `int`.
|
|
223
|
+
|
|
224
|
+
A structure or union converts the values of its fields in the same way. A `char` field takes bytes as its value, and a structure field keeps a structure as it is. More bytes than a field needs raise a `ValueError`. Values that are set as attributes aren't converted for performance reasons.
|
|
225
|
+
|
|
226
|
+
```python
|
|
227
|
+
cs.load("""
|
|
228
|
+
struct example {
|
|
229
|
+
uint16 values[2];
|
|
230
|
+
char name[4];
|
|
231
|
+
};
|
|
232
|
+
""")
|
|
233
|
+
|
|
234
|
+
obj = cs.example(values=b"\x01\x00\x02\x00", name=b"ab")
|
|
235
|
+
assert obj.values == [1, 2] # Parsed
|
|
236
|
+
assert obj.name == b"ab\x00\x00" # Padded
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
Writing doesn't convert values. E.g. `cs.uint8[2].dumps(b"\x01\x02")` raises a `WriteError`. Use `cs.uint8[2].dumps([1, 2])` instead.
|
|
240
|
+
|
|
208
241
|
### Unions and nested structures
|
|
209
242
|
Unions and nested structures are supported, both anonymous and named.
|
|
210
243
|
|
|
@@ -248,7 +281,7 @@ assert a.c.a.a == 0x64616564
|
|
|
248
281
|
assert a.c.a.b == 0x66656562
|
|
249
282
|
assert a.c.b.b == b"deadbeef"
|
|
250
283
|
|
|
251
|
-
assert a
|
|
284
|
+
assert bytes(a) == b"ohaideadbeef"
|
|
252
285
|
|
|
253
286
|
b = c.test_anonymous(b"ohai\x39\x05\x00\x00\x28\x23\x00\x00deadbeef")
|
|
254
287
|
assert b.magic == b"ohai"
|
|
@@ -283,7 +316,7 @@ assert a.b == 0b1
|
|
|
283
316
|
assert a.c == 0xFF
|
|
284
317
|
assert a.d == 0b11
|
|
285
318
|
assert a.e == 0b111
|
|
286
|
-
assert a
|
|
319
|
+
assert bytes(a) == d
|
|
287
320
|
```
|
|
288
321
|
|
|
289
322
|
### Enums and Flags
|
|
@@ -90,14 +90,13 @@ assert c_parser.Example.A == 0
|
|
|
90
90
|
assert c_parser.Example.C == 6
|
|
91
91
|
assert c_parser.Example(5) == c_parser.Example.B
|
|
92
92
|
|
|
93
|
-
assert result
|
|
93
|
+
assert bytes(result) == data
|
|
94
94
|
|
|
95
95
|
# You can also instantiate structures from Python by using kwargs
|
|
96
|
-
# Note that array sizes are not enforced
|
|
97
96
|
instance = c_parser.some_struct(
|
|
98
|
-
field_1=5, field_2="lorem", field_3="ipsum", field_4=[c_parser.Example.B, c_parser.Example.A]
|
|
97
|
+
field_1=5, field_2=b"lorem", field_3=b"ipsum", field_4=[c_parser.Example.B, c_parser.Example.A]
|
|
99
98
|
)
|
|
100
|
-
assert instance
|
|
99
|
+
assert bytes(instance) == b"\x05loremipsum\x05\x00\x00\x00"
|
|
101
100
|
|
|
102
101
|
```
|
|
103
102
|
|
|
@@ -132,7 +131,7 @@ header = Header(data)
|
|
|
132
131
|
assert header.data == b"KUSJESVANSRT"
|
|
133
132
|
assert header.flags == 5
|
|
134
133
|
assert header.trailer == b"<3"
|
|
135
|
-
assert header
|
|
134
|
+
assert bytes(header) == data
|
|
136
135
|
|
|
137
136
|
cs = cstruct(endian=">")
|
|
138
137
|
|
|
@@ -177,6 +176,40 @@ assert cs.uint24[2](b"\x01\x00\x00\x02\x00\x00") == [1, 2] # You can also parse
|
|
|
177
176
|
assert cs.char[None](b"hello world!\x00") == b"hello world!" # A list index of None means null terminated
|
|
178
177
|
```
|
|
179
178
|
|
|
179
|
+
### Creating values
|
|
180
|
+
A type creates a value like its Python base type does, e.g. `int` for `uint32` and `list` for arrays. Bytes-like and file-like objects are parsed instead.
|
|
181
|
+
|
|
182
|
+
```python
|
|
183
|
+
from dissect.cstruct import cstruct
|
|
184
|
+
|
|
185
|
+
cs = cstruct()
|
|
186
|
+
assert cs.uint32("5") == 5 # Like int("5")
|
|
187
|
+
assert cs.uint32(b"\x05\x00\x00\x00") == 5 # Parsed
|
|
188
|
+
assert cs.uint8[4]([1, 2]) == [1, 2, 0, 0] # Padded to the number of entries
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
Some types don't accept all the values of their Python base type:
|
|
192
|
+
- `char` and `char` arrays don't accept a `str`, encode it to bytes first. An `int` gives a single character, e.g. `cs.char(0x41)` is `b"A"`.
|
|
193
|
+
- `wchar` and `wchar` arrays only accept a `str`.
|
|
194
|
+
- Other arrays don't accept a `str` or an `int`.
|
|
195
|
+
|
|
196
|
+
A structure or union converts the values of its fields in the same way. A `char` field takes bytes as its value, and a structure field keeps a structure as it is. More bytes than a field needs raise a `ValueError`. Values that are set as attributes aren't converted for performance reasons.
|
|
197
|
+
|
|
198
|
+
```python
|
|
199
|
+
cs.load("""
|
|
200
|
+
struct example {
|
|
201
|
+
uint16 values[2];
|
|
202
|
+
char name[4];
|
|
203
|
+
};
|
|
204
|
+
""")
|
|
205
|
+
|
|
206
|
+
obj = cs.example(values=b"\x01\x00\x02\x00", name=b"ab")
|
|
207
|
+
assert obj.values == [1, 2] # Parsed
|
|
208
|
+
assert obj.name == b"ab\x00\x00" # Padded
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
Writing doesn't convert values. E.g. `cs.uint8[2].dumps(b"\x01\x02")` raises a `WriteError`. Use `cs.uint8[2].dumps([1, 2])` instead.
|
|
212
|
+
|
|
180
213
|
### Unions and nested structures
|
|
181
214
|
Unions and nested structures are supported, both anonymous and named.
|
|
182
215
|
|
|
@@ -220,7 +253,7 @@ assert a.c.a.a == 0x64616564
|
|
|
220
253
|
assert a.c.a.b == 0x66656562
|
|
221
254
|
assert a.c.b.b == b"deadbeef"
|
|
222
255
|
|
|
223
|
-
assert a
|
|
256
|
+
assert bytes(a) == b"ohaideadbeef"
|
|
224
257
|
|
|
225
258
|
b = c.test_anonymous(b"ohai\x39\x05\x00\x00\x28\x23\x00\x00deadbeef")
|
|
226
259
|
assert b.magic == b"ohai"
|
|
@@ -255,7 +288,7 @@ assert a.b == 0b1
|
|
|
255
288
|
assert a.c == 0xFF
|
|
256
289
|
assert a.d == 0b11
|
|
257
290
|
assert a.e == 0b111
|
|
258
|
-
assert a
|
|
291
|
+
assert bytes(a) == d
|
|
259
292
|
```
|
|
260
293
|
|
|
261
294
|
### Enums and Flags
|
|
@@ -73,7 +73,14 @@ class BitBuffer:
|
|
|
73
73
|
|
|
74
74
|
def flush(self) -> None:
|
|
75
75
|
if self._type is not None:
|
|
76
|
-
|
|
76
|
+
buffer = self._buffer
|
|
77
|
+
if issubclass(self._type, bytes):
|
|
78
|
+
if self.endian == "<":
|
|
79
|
+
buffer = buffer.to_bytes(self._type.__size__, "little")
|
|
80
|
+
else:
|
|
81
|
+
buffer = buffer.to_bytes(self._type.__size__, "big")
|
|
82
|
+
|
|
83
|
+
self._type._write(self.stream, buffer, endian=self.endian)
|
|
77
84
|
self._type = None
|
|
78
85
|
self._remaining = 0
|
|
79
86
|
self._buffer = 0
|
|
@@ -37,7 +37,13 @@ from dissect.cstruct.types import (
|
|
|
37
37
|
WcharArray,
|
|
38
38
|
)
|
|
39
39
|
from dissect.cstruct.types.enum import EnumMetaType
|
|
40
|
-
from dissect.cstruct.types.structure import
|
|
40
|
+
from dissect.cstruct.types.structure import (
|
|
41
|
+
StructureMetaType,
|
|
42
|
+
UnionMetaType,
|
|
43
|
+
UnionProxy,
|
|
44
|
+
_uses_generated_init,
|
|
45
|
+
_value_type,
|
|
46
|
+
)
|
|
41
47
|
from dissect.cstruct.util import ENDIANNESS_TO_BYTEORDER_MAP, _struct
|
|
42
48
|
|
|
43
49
|
if TYPE_CHECKING:
|
|
@@ -216,15 +222,15 @@ _PACKABLE_TYPES = (Array, Char, CharArray, Int, Packed, Pointer, Void, VoidArray
|
|
|
216
222
|
|
|
217
223
|
def _field_bytes(type_: type[BaseType], value: Any, endian: str) -> bytes:
|
|
218
224
|
"""Return the bytes of a char or wchar field that isn't of the right type yet or doesn't fit."""
|
|
219
|
-
|
|
220
|
-
if len(buf) > type_.__size__:
|
|
225
|
+
type_._write(out := io.BytesIO(), type_.__default__() if value is None else value, endian=endian)
|
|
226
|
+
if len(buf := out.getvalue()) > type_.__size__:
|
|
221
227
|
raise WriteError(f"Expected {type_.__size__} bytes for {type_.__name__}, got {len(buf)} instead.")
|
|
222
228
|
return buf
|
|
223
229
|
|
|
224
230
|
|
|
225
231
|
def _array_values(type_: type[Array], value: list[Any] | None) -> list[Any]:
|
|
226
|
-
"""Return the values of an array field that
|
|
227
|
-
return type_.__default__() if value is None else type_.
|
|
232
|
+
"""Return the values of an array field that isn't a list of the right size yet."""
|
|
233
|
+
return type_.__default__() if value is None else type_._entries(value)
|
|
228
234
|
|
|
229
235
|
|
|
230
236
|
def _or_default(value: Any, type_: type[BaseType]) -> Any:
|
|
@@ -235,6 +241,8 @@ def _or_default(value: Any, type_: type[BaseType]) -> Any:
|
|
|
235
241
|
# Globals that are available to all generated functions
|
|
236
242
|
_GLOBALS = {
|
|
237
243
|
"_type_call": type.__call__,
|
|
244
|
+
"_bytes_new": bytes.__new__,
|
|
245
|
+
"_str_new": str.__new__,
|
|
238
246
|
"_object_new": object.__new__,
|
|
239
247
|
"_setattr": setattr,
|
|
240
248
|
"_repeat": repeat,
|
|
@@ -412,6 +420,15 @@ class _ReadSourceGenerator(_SourceGenerator):
|
|
|
412
420
|
outro.append(f" obj.__dynamic_sizes__ = {sizes}")
|
|
413
421
|
outro.append(" return obj")
|
|
414
422
|
|
|
423
|
+
# Subclasses without their own __init__ or __new__ inherit __construct__, which also bypasses __init__
|
|
424
|
+
# It has a parameter for each field name, like the keyword arguments below
|
|
425
|
+
construct = self._add_symbol(self.cls.__construct__, "construct")
|
|
426
|
+
values = "".join(f", {var}" for var in dict(self._assigned).values())
|
|
427
|
+
outro.append(f"if cls.__construct__ is {construct}:")
|
|
428
|
+
outro.append(f" obj = {construct}(cls{values})")
|
|
429
|
+
outro.append(f" obj.__dynamic_sizes__ = {sizes}")
|
|
430
|
+
outro.append(" return obj")
|
|
431
|
+
|
|
415
432
|
# Using type.__call__ directly calls the __init__ method of the class
|
|
416
433
|
outro.append(f"obj = _type_call(cls, **{{{kwargs}}})")
|
|
417
434
|
outro.append(f"obj.__dynamic_sizes__ = {sizes}")
|
|
@@ -571,7 +588,16 @@ class _ReadSourceGenerator(_SourceGenerator):
|
|
|
571
588
|
lines.append("except _Error: raise")
|
|
572
589
|
lines.append(f"except (ArithmeticError, ValueError) as e: raise _ReadError({message!r} + str(e)) from e")
|
|
573
590
|
element = self._type_symbol(field.type.__type__)
|
|
574
|
-
|
|
591
|
+
entries = f"{element}._read_array(stream, _count, context={context}, endian=endian)"
|
|
592
|
+
|
|
593
|
+
# Create char and wchar arrays without the checks of their constructor
|
|
594
|
+
if issubclass(field.type, CharArray):
|
|
595
|
+
return f"_bytes_new({type_}, {entries})"
|
|
596
|
+
|
|
597
|
+
if issubclass(field.type, WcharArray):
|
|
598
|
+
return f"_str_new({type_}, {entries})"
|
|
599
|
+
|
|
600
|
+
return f"_type_call({type_}, {entries})"
|
|
575
601
|
|
|
576
602
|
def _generate_bits_source(self, field: Field) -> Iterator[str]:
|
|
577
603
|
"""Generate the code for reading a bit field."""
|
|
@@ -594,7 +620,7 @@ class _ReadSourceGenerator(_SourceGenerator):
|
|
|
594
620
|
lines.append(f"else: _bit_value = (_bit_buffer >> {remaining - field.bits}) & {mask}")
|
|
595
621
|
|
|
596
622
|
# Character bit fields are returned as the integer type they're read as
|
|
597
|
-
type_ = self._type_symbol(
|
|
623
|
+
type_ = self._type_symbol(_value_type(field))
|
|
598
624
|
|
|
599
625
|
if issubclass(field.type, (Enum, Flag)):
|
|
600
626
|
lines.append(_member_lookup(type_, "_bit_value"))
|
|
@@ -747,14 +773,14 @@ class _ReadSourceGenerator(_SourceGenerator):
|
|
|
747
773
|
|
|
748
774
|
lines.extend(target(field, f"_type_call({array}, {value})"))
|
|
749
775
|
|
|
750
|
-
elif issubclass(field_type, CharArray):
|
|
751
|
-
lines.extend(target(field, f"
|
|
776
|
+
elif issubclass(field_type, (Char, CharArray)):
|
|
777
|
+
lines.extend(target(field, f"_bytes_new({self._type_symbol(field.type)}, {getter})"))
|
|
752
778
|
|
|
753
779
|
elif issubclass(field_type, WcharArray) or issubclass(read_type, Wchar):
|
|
754
780
|
encoding = self._add_symbol(read_type.__encoding_map__, "encoding")
|
|
755
|
-
#
|
|
781
|
+
# Decoding like str() instead of .decode() also supports other bytes-like objects returned by the stream
|
|
756
782
|
type_ = self._type_symbol(field.type)
|
|
757
|
-
lines.extend(target(field, f"
|
|
783
|
+
lines.extend(target(field, f"_str_new({type_}, {getter}, {encoding}[endian], 'surrogatepass')"))
|
|
758
784
|
|
|
759
785
|
elif issubclass(field_type, Pointer):
|
|
760
786
|
context = self._context(lines)
|
|
@@ -1051,7 +1077,8 @@ class _WriteSourceGenerator(_SourceGenerator):
|
|
|
1051
1077
|
var = self._var("value")
|
|
1052
1078
|
num = field_type.__num_entries__
|
|
1053
1079
|
pack.lines.append(
|
|
1054
|
-
f"if ({var} := {value})
|
|
1080
|
+
f"if not isinstance({var} := {value}, list) or len({var}) != {num}: "
|
|
1081
|
+
f"{var} = _array_values({type_}, {var})"
|
|
1055
1082
|
)
|
|
1056
1083
|
|
|
1057
1084
|
# Entries can be enum members or plain integers, both can be packed as they are
|
|
@@ -1178,11 +1205,6 @@ def _can_inline_fields(fields: list[Field], size: int, is_union: bool, in_union:
|
|
|
1178
1205
|
return True
|
|
1179
1206
|
|
|
1180
1207
|
|
|
1181
|
-
def _uses_generated_init(type_: type[Structure]) -> bool:
|
|
1182
|
-
"""Return whether a structure type uses a generated ``__init__``, so we can bypass it by setting attributes."""
|
|
1183
|
-
return "__init__" in type_.__dict__ and type_.__new__ is object.__new__
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
1208
|
def _can_pack(type_: type[BaseType]) -> bool:
|
|
1187
1209
|
"""Determine if a value of a type can be written by packing it, instead of by using the ``_write`` method."""
|
|
1188
1210
|
if type_.__size__ is None:
|
|
@@ -21,6 +21,7 @@ from dissect.cstruct.types import (
|
|
|
21
21
|
BaseType,
|
|
22
22
|
Char,
|
|
23
23
|
Enum,
|
|
24
|
+
Field,
|
|
24
25
|
Flag,
|
|
25
26
|
Int,
|
|
26
27
|
Packed,
|
|
@@ -36,10 +37,7 @@ if TYPE_CHECKING:
|
|
|
36
37
|
from collections.abc import Generator, Iterable
|
|
37
38
|
from typing import TypeAlias
|
|
38
39
|
|
|
39
|
-
from dissect.cstruct.types import
|
|
40
|
-
Array,
|
|
41
|
-
Field,
|
|
42
|
-
)
|
|
40
|
+
from dissect.cstruct.types import Array
|
|
43
41
|
|
|
44
42
|
|
|
45
43
|
T = TypeVar("T", bound=BaseType)
|
|
@@ -245,21 +243,62 @@ class cstruct:
|
|
|
245
243
|
raise AttributeError(f"'{type(self).__name__}' object has no attribute {attr!r}")
|
|
246
244
|
|
|
247
245
|
def __copy__(self) -> cstruct:
|
|
248
|
-
cs = cstruct(endian=self.endian
|
|
246
|
+
cs = cstruct(endian=self.endian)
|
|
249
247
|
cs._anonymous_count = self._anonymous_count
|
|
250
248
|
cs.includes = self.includes.copy()
|
|
251
249
|
|
|
252
|
-
#
|
|
250
|
+
# Copy the types as new classes, including the unregistered types they refer to
|
|
251
|
+
copies = {}
|
|
253
252
|
for name, type_ in self.types.items():
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
cs.add_type(name, new_type, replace=True)
|
|
253
|
+
cs.add_type(name, cs._copy_type(type_, copies), replace=True)
|
|
254
|
+
cs.pointer = cs._copy_type(self.pointer, copies)
|
|
257
255
|
|
|
258
256
|
for name, value in self.consts.items():
|
|
259
257
|
cs.add_const(name, value)
|
|
260
258
|
|
|
261
259
|
return cs
|
|
262
260
|
|
|
261
|
+
def _copy_type(self, type_: type[BaseType], copies: dict[type[BaseType], type[BaseType]]) -> type[BaseType]:
|
|
262
|
+
if type_ in copies:
|
|
263
|
+
return copies[type_]
|
|
264
|
+
|
|
265
|
+
if issubclass(type_, (Enum, Flag)):
|
|
266
|
+
# Enum classes with members can't be created from their namespace
|
|
267
|
+
factory = self._make_flag if issubclass(type_, Flag) else self._make_enum
|
|
268
|
+
values = {name: member.value for name, member in type_.__members__.items()}
|
|
269
|
+
copies[type_] = factory(type_.__name__, self._copy_type(type_.__type__, copies), values)
|
|
270
|
+
return copies[type_]
|
|
271
|
+
|
|
272
|
+
# A type is registered before its subclasses, e.g. a declarative structure, so the copy of its base exists
|
|
273
|
+
bases = tuple(copies.get(base, base) for base in type_.__bases__)
|
|
274
|
+
|
|
275
|
+
# The namespace of a class doesn't hold its qualified name, e.g. of a declarative structure in a function
|
|
276
|
+
attrs = {**vars(type_), "__qualname__": type_.__qualname__}
|
|
277
|
+
|
|
278
|
+
# Register the copy before copying the types it refers to, so that a structure can point to itself
|
|
279
|
+
if issubclass(type_, Structure):
|
|
280
|
+
attrs["__members__"] = []
|
|
281
|
+
|
|
282
|
+
new_type = copies[type_] = self._make_type(
|
|
283
|
+
type_.__name__,
|
|
284
|
+
bases,
|
|
285
|
+
type_.__size__,
|
|
286
|
+
alignment=type_.__alignment__,
|
|
287
|
+
attrs=attrs,
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
if issubclass(type_, (BaseArray, Pointer)):
|
|
291
|
+
new_type.__type__ = self._copy_type(type_.__type__, copies)
|
|
292
|
+
|
|
293
|
+
if issubclass(type_, Structure):
|
|
294
|
+
new_type.__fields__ = [
|
|
295
|
+
Field(field.name, self._copy_type(field.type, copies), field.bits, field.offset)
|
|
296
|
+
for field in type_.__fields__
|
|
297
|
+
]
|
|
298
|
+
new_type.commit()
|
|
299
|
+
|
|
300
|
+
return new_type
|
|
301
|
+
|
|
263
302
|
# Hidden from type checkers, which otherwise accept assigning any attribute, e.g. a misspelled one
|
|
264
303
|
if not TYPE_CHECKING:
|
|
265
304
|
|
|
@@ -395,6 +395,10 @@ class _Declarative:
|
|
|
395
395
|
def __init_subclass__(cls, *, cs: cstruct | None = None, align: bool | None = None, **kwargs):
|
|
396
396
|
super().__init_subclass__(**kwargs)
|
|
397
397
|
|
|
398
|
+
if "__fields__" in vars(cls):
|
|
399
|
+
# Created by cstruct with its fields, e.g. a copy made by cstruct.copy()
|
|
400
|
+
return
|
|
401
|
+
|
|
398
402
|
if cs is not None:
|
|
399
403
|
cls.__cs__ = cs
|
|
400
404
|
if align is not None:
|
|
@@ -465,7 +465,7 @@ def dumpstruct(
|
|
|
465
465
|
raise ValueError(f"Invalid output argument: {output!r} (should be 'print', 'string', 'dict' or 'json').")
|
|
466
466
|
|
|
467
467
|
if isinstance(obj, Structure):
|
|
468
|
-
data = obj
|
|
468
|
+
data = bytes(obj) if data is None else data
|
|
469
469
|
elif isinstance(obj, type) and issubclass(obj, Structure) and data is not None:
|
|
470
470
|
obj = obj(data)
|
|
471
471
|
else:
|
|
@@ -158,7 +158,12 @@ def generate_structure_stub(
|
|
|
158
158
|
result = [f"class {name_prefix}{structure.__name__}({module_prefix}{structure.__base__.__name__}):"]
|
|
159
159
|
indent = " " * 4
|
|
160
160
|
|
|
161
|
-
|
|
161
|
+
# Fields can be named self, so prefix until there's no longer a clash
|
|
162
|
+
instance = "self"
|
|
163
|
+
while instance in structure.__members__:
|
|
164
|
+
instance = f"_{instance}"
|
|
165
|
+
|
|
166
|
+
args = [instance, "/"]
|
|
162
167
|
for field_name, field in structure.__members__.items():
|
|
163
168
|
inlined = False
|
|
164
169
|
|
|
@@ -182,7 +187,9 @@ def generate_structure_stub(
|
|
|
182
187
|
result.append(textwrap.indent(f"def __init__({', '.join(args)}): ...", prefix=indent))
|
|
183
188
|
result.append(textwrap.indent("@overload", prefix=indent))
|
|
184
189
|
result.append(
|
|
185
|
-
textwrap.indent(
|
|
190
|
+
textwrap.indent(
|
|
191
|
+
f"def __init__({instance}, fh: bytes | memoryview | bytearray | BinaryIO, /): ...", prefix=indent
|
|
192
|
+
)
|
|
186
193
|
)
|
|
187
194
|
result.append("")
|
|
188
195
|
return "\n".join(result)
|