dissect.cstruct 5.0.dev17__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.
Files changed (85) hide show
  1. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/CHANGELOG.md +4 -0
  2. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/PKG-INFO +56 -2
  3. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/README.md +55 -1
  4. dissect_cstruct-5.0.dev18/dissect/cstruct/declarative.py +460 -0
  5. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect/cstruct/types/base.py +8 -2
  6. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect/cstruct/types/structure.py +2 -2
  7. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect.cstruct.egg-info/PKG-INFO +56 -2
  8. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect.cstruct.egg-info/SOURCES.txt +2 -0
  9. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect.cstruct.egg-info/scm_file_list.json +2 -0
  10. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect.cstruct.egg-info/scm_version.json +2 -2
  11. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/pyproject.toml +3 -0
  12. dissect_cstruct-5.0.dev18/tests/test_declarative.py +506 -0
  13. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_types_base.py +10 -0
  14. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/.git-blame-ignore-revs +0 -0
  15. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/.gitattributes +0 -0
  16. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/COPYRIGHT +0 -0
  17. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/LICENSE +0 -0
  18. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/MANIFEST.in +0 -0
  19. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect/cstruct/__init__.py +0 -0
  20. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect/cstruct/bitbuffer.py +0 -0
  21. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect/cstruct/compiler.py +0 -0
  22. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect/cstruct/cstruct.py +0 -0
  23. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect/cstruct/dump.py +0 -0
  24. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect/cstruct/exception.py +0 -0
  25. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect/cstruct/expression.py +0 -0
  26. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect/cstruct/lexer.py +0 -0
  27. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect/cstruct/parser.py +0 -0
  28. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect/cstruct/tools/__init__.py +0 -0
  29. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect/cstruct/tools/stubgen.py +0 -0
  30. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect/cstruct/types/__init__.py +0 -0
  31. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect/cstruct/types/char.py +0 -0
  32. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect/cstruct/types/enum.py +0 -0
  33. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect/cstruct/types/flag.py +0 -0
  34. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect/cstruct/types/int.py +0 -0
  35. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect/cstruct/types/leb128.py +0 -0
  36. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect/cstruct/types/packed.py +0 -0
  37. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect/cstruct/types/pointer.py +0 -0
  38. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect/cstruct/types/void.py +0 -0
  39. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect/cstruct/types/wchar.py +0 -0
  40. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect/cstruct/util.py +0 -0
  41. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect.cstruct.egg-info/dependency_links.txt +0 -0
  42. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect.cstruct.egg-info/entry_points.txt +0 -0
  43. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect.cstruct.egg-info/requires.txt +0 -0
  44. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/dissect.cstruct.egg-info/top_level.txt +0 -0
  45. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/examples/disk.py +0 -0
  46. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/examples/mirai.py +0 -0
  47. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/examples/pe.py +0 -0
  48. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/examples/protobuf.py +0 -0
  49. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/examples/secdesc.py +0 -0
  50. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/setup.cfg +0 -0
  51. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/__init__.py +0 -0
  52. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/_data/testdef.txt +0 -0
  53. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/_docs/Makefile +0 -0
  54. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/_docs/__init__.py +0 -0
  55. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/_docs/conf.py +0 -0
  56. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/_docs/index.rst +0 -0
  57. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/conftest.py +0 -0
  58. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_align.py +0 -0
  59. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_annotations.py +0 -0
  60. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_basic.py +0 -0
  61. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_benchmark.py +0 -0
  62. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_bitbuffer.py +0 -0
  63. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_bitfield.py +0 -0
  64. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_compiler.py +0 -0
  65. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_ctypes.py +0 -0
  66. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_dump.py +0 -0
  67. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_expression.py +0 -0
  68. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_lexer.py +0 -0
  69. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_parser.py +0 -0
  70. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_tools_stubgen.py +0 -0
  71. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_types_char.py +0 -0
  72. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_types_custom.py +0 -0
  73. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_types_enum.py +0 -0
  74. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_types_flag.py +0 -0
  75. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_types_int.py +0 -0
  76. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_types_leb128.py +0 -0
  77. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_types_packed.py +0 -0
  78. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_types_pointer.py +0 -0
  79. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_types_structure.py +0 -0
  80. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_types_union.py +0 -0
  81. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_types_void.py +0 -0
  82. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_types_wchar.py +0 -0
  83. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/test_util.py +0 -0
  84. {dissect_cstruct-5.0.dev17 → dissect_cstruct-5.0.dev18}/tests/util.py +0 -0
  85. {dissect_cstruct-5.0.dev17 → 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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dissect.cstruct
3
- Version: 5.0.dev17
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 also inspect the resulting source code by accessing the source attribute of the structure: `print(c_parser.some_struct.source)`.
132
+ By default, all structures are compiled into classes that provide optimised performance. You can disable this by passing a `compiled=False` keyword argument to the `.load()` call. You can inspect the resulting source code by accessing the source attribute of the structure: `print(c_parser.some_struct._read.__source__)` or `print(c_parser.some_struct._write_.__source__)`.
133
133
 
134
134
  More examples can be found in the `examples` directory.
135
135
 
@@ -137,6 +137,60 @@ More examples can be found in the `examples` directory.
137
137
  ### Structure parsing
138
138
  Write simple C-like structures and use them to parse binary data, as can be seen in the examples.
139
139
 
140
+ ### Declarative structure definitions
141
+ Instead of with a C-like definition, structures can also be defined in Python by subclassing `Struct` (or `Union`) and annotating the fields. The resulting classes are regular cstruct structures.
142
+
143
+ ```python
144
+ from typing import Annotated
145
+
146
+ from dissect.cstruct import cstruct
147
+ from dissect.cstruct.declarative import EOF, Struct, char, field, pointer, uint8, uint16, uint32
148
+
149
+
150
+ class Header(Struct):
151
+ magic: uint8[4]
152
+ size: uint32
153
+ data: char["size"] # Array sizes can refer to other fields
154
+ flags: Annotated[uint16, field(bits=4)] # Or field(uint16, bits=4)
155
+ trailer: char[EOF] # Reads until the end of the data
156
+
157
+
158
+ data = b"ohai\x0c\x00\x00\x00KUSJESVANSRT\x05\x00<3"
159
+ header = Header(data)
160
+ assert header.data == b"KUSJESVANSRT"
161
+ assert header.flags == 5
162
+ assert header.trailer == b"<3"
163
+ assert header.dumps() == data
164
+
165
+ cs = cstruct(endian=">")
166
+
167
+
168
+ class Node(Struct, cs=cs):
169
+ value: uint32
170
+ next: pointer["Node"] # A structure can point to itself
171
+
172
+
173
+ class NamedNode(Node): # A subclass starts with the fields of its parent
174
+ name: char[None] # A list index of None means null terminated
175
+
176
+
177
+ cs.load("struct list { uint32 count; NamedNode head; };") # Usable in C-like definitions
178
+
179
+ node = cs.list(b"\x00\x00\x00\x01" + b"\x00\x00\x00\x07" + b"\x00" * 8 + b"<3\x00").head
180
+ assert node.value == 7
181
+ assert node.name == b"<3"
182
+ ```
183
+
184
+ Each structure is registered in a cstruct instance, which can be passed with the `cs` class keyword argument, together with `align=True` for aligned structures. Without one, a structure uses the cstruct instance of the first bound type or structure in its annotations, or a new cstruct instance.
185
+
186
+ > [!NOTE]
187
+ > Field annotations are evaluated when the class is created. If your project uses Ruff's `flake8-type-checking` (`TC`) rules, add `Struct` and `Union` to the runtime-evaluated base classes, so that imports only used in field annotations are not moved into a `TYPE_CHECKING` block:
188
+ >
189
+ > ```toml
190
+ > [tool.ruff.lint.flake8-type-checking]
191
+ > runtime-evaluated-base-classes = ["dissect.cstruct.declarative.Struct", "dissect.cstruct.declarative.Union"]
192
+ > ```
193
+
140
194
  ### Type parsing
141
195
  Aside from loading structure definitions, any of the supported types can be used individually for parsing data. For example, the following is all supported:
142
196
 
@@ -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 also inspect the resulting source code by accessing the source attribute of the structure: `print(c_parser.some_struct.source)`.
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
 
@@ -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`."""
@@ -1,5 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import contextlib
3
4
  import functools
4
5
  import warnings
5
6
  from io import SEEK_CUR, BytesIO
@@ -7,6 +8,7 @@ from types import MethodType
7
8
  from typing import TYPE_CHECKING, Any, BinaryIO, ClassVar, TypeVar
8
9
 
9
10
  from dissect.cstruct.exception import ArraySizeError
11
+ from dissect.cstruct.expression import Expression
10
12
  from dissect.cstruct.util import classproperty, normalize_endianness
11
13
 
12
14
  if TYPE_CHECKING:
@@ -15,7 +17,6 @@ if TYPE_CHECKING:
15
17
  from typing_extensions import Self
16
18
 
17
19
  from dissect.cstruct.cstruct import AllowedEndianness, Endianness, cstruct
18
- from dissect.cstruct.expression import Expression
19
20
 
20
21
 
21
22
  EOF = -0xE0F # Negative counts are illegal anyway, so abuse that for our EOF sentinel
@@ -73,8 +74,13 @@ class MetaType(type):
73
74
 
74
75
  return type.__call__(cls, *args, **kwargs)
75
76
 
76
- def __getitem__(cls, num_entries: int | Expression | None) -> type[BaseArray]:
77
+ def __getitem__(cls, num_entries: int | str | Expression | None) -> type[BaseArray]:
77
78
  """Create a new array with the given number of entries."""
79
+ if isinstance(num_entries, str):
80
+ num_entries = Expression(num_entries)
81
+ with contextlib.suppress(Exception):
82
+ num_entries = num_entries.evaluate(cls.__cs__)
83
+
78
84
  return cls.__cs__._make_array(cls, num_entries)
79
85
 
80
86
  def __bool__(cls) -> bool:
@@ -69,11 +69,11 @@ class StructureMetaType(MetaType):
69
69
  __compiled__ = False
70
70
  __static_sizes__: dict[str, int] # Cache of static sizes by field name
71
71
 
72
- def __new__(metacls, name: str, bases: tuple[type, ...], classdict: dict[str, Any]) -> Self: # type: ignore
72
+ def __new__(metacls, name: str, bases: tuple[type, ...], classdict: dict[str, Any], **kwargs) -> Self: # type: ignore
73
73
  if (fields := classdict.pop("__members__", None)) is not None:
74
74
  metacls._update_fields(metacls, fields, align=classdict.get("__align__", False), classdict=classdict)
75
75
 
76
- return super().__new__(metacls, name, bases, classdict)
76
+ return super().__new__(metacls, name, bases, classdict, **kwargs)
77
77
 
78
78
  def __call__(cls, *args, **kwargs) -> Self: # type: ignore
79
79
  if len(args) == 1 and not kwargs: