dissect.cstruct 5.0.dev16__py3-none-any.whl → 5.0.dev18__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
dissect/cstruct/util.py CHANGED
@@ -1,59 +1,17 @@
1
1
  from __future__ import annotations
2
2
 
3
- import os
4
- import pprint
5
- import string
6
3
  import struct
7
4
  import sys
8
- from enum import Enum
9
5
  from functools import lru_cache
10
6
  from typing import TYPE_CHECKING, Any
11
7
 
12
8
  if TYPE_CHECKING:
13
- from collections.abc import Iterator
14
9
  from typing import Literal
15
10
 
16
11
  from dissect.cstruct.cstruct import AllowedEndianness, Endianness
17
12
  from dissect.cstruct.types.base import BaseType
18
13
  from dissect.cstruct.types.structure import Structure
19
14
 
20
- # Regular ANSI colors
21
- COLOR_RED = "\033[0;31m"
22
- COLOR_GREEN = "\033[0;32m"
23
- COLOR_YELLOW = "\033[0;93m"
24
- COLOR_BLUE = "\033[0;34m"
25
- COLOR_PURPLE = "\033[0;35m"
26
- COLOR_CYAN = "\033[0;36m"
27
- COLOR_WHITE = "\033[0;37m"
28
- COLOR_BLACK = "\033[0;30m"
29
- COLOR_GREY = "\033[0;90m"
30
-
31
- # Bold ANSI colors
32
- COLOR_RED_BOLD = "\033[1;31m"
33
- COLOR_GREEN_BOLD = "\033[1;32m"
34
- COLOR_YELLOW_BOLD = "\033[1;33m"
35
- COLOR_BLUE_BOLD = "\033[1;34m"
36
- COLOR_PURPLE_BOLD = "\033[1;35m"
37
- COLOR_CYAN_BOLD = "\033[1;36m"
38
- COLOR_WHITE_BOLD = "\033[1;37m"
39
- COLOR_BLACK_BOLD = "\033[1;30m"
40
- COLOR_GREY_BOLD = "\033[1;90m"
41
-
42
- # Background ANSI colors
43
- COLOR_BG_RED = "\033[1;41m\033[1;37m"
44
- COLOR_BG_GREEN = "\033[1;42m\033[1;37m"
45
- COLOR_BG_YELLOW = "\033[1;43m\033[1;37m"
46
- COLOR_BG_BLUE = "\033[1;44m\033[1;37m"
47
- COLOR_BG_PURPLE = "\033[1;45m\033[1;37m"
48
- COLOR_BG_CYAN = "\033[1;46m\033[1;37m"
49
- COLOR_BG_WHITE = "\033[1;47m\033[1;30m"
50
-
51
- # Reset ANSI codes
52
- COLOR_CLEAR = "\033[0m"
53
- COLOR_CLEAR_BOLD = "\033[1;0m"
54
-
55
- PRINTABLE = string.digits + string.ascii_letters + string.punctuation + " "
56
-
57
15
 
58
16
  ENDIANNESS_TO_BYTEORDER_MAP: dict[AllowedEndianness, Literal["big", "little"]] = {
59
17
  "<": "little",
@@ -96,269 +54,6 @@ class classproperty:
96
54
  return self.fget(owner)
97
55
 
98
56
 
99
- Palette = list[tuple[int, str]]
100
-
101
-
102
- def _human_colors() -> dict[str, str]:
103
- """Generates a dictionary of characters with a human-readable ANSI color they should be in a hexdump.
104
-
105
- Coloring logic implementation derived from HexFriend and ImHex.
106
- """
107
- # Make all characters not in any rules below light green
108
- colors = {chr(char): COLOR_GREEN for char in range(256)}
109
-
110
- # Make all ASCII extended characters yellow
111
- for char in colors:
112
- if ord(char) & 0x80 == 0:
113
- colors[char] = COLOR_YELLOW
114
-
115
- # Make null bytes grey
116
- colors["\00"] = COLOR_GREY
117
-
118
- # Make printable ASCII characters bold white (0x32-0x7E)
119
- for char in PRINTABLE:
120
- colors[char] = COLOR_WHITE_BOLD
121
-
122
- # Make ASCII whitespace characters green bold (0x9, 0xA, 0xB, 0xC, 0xD, 0x20)
123
- for char in ("\t", "\n", "\11", "\12", "\r", "\20"):
124
- colors[char] = COLOR_GREEN_BOLD
125
-
126
- return colors
127
-
128
-
129
- HUMAN_COLORS = _human_colors()
130
-
131
-
132
- def _hexdump(
133
- data: bytes,
134
- *,
135
- palette: Palette | None = None,
136
- offset: int = 0,
137
- prefix: str = "",
138
- pretty: bool | None = False,
139
- autoskip: bool = False,
140
- ) -> Iterator[str]:
141
- """Hexdump some data.
142
-
143
- Args:
144
- data: Bytes to hexdump.
145
- palette: Colorize the hexdump using this color pattern.
146
- offset: Byte offset of the hexdump.
147
- prefix: Optional prefix.
148
- pretty: Use pretty colors, mutual exclusive with palette.
149
- autoskip: A single '*' replaces NUL-lines in the output.
150
- """
151
- if palette:
152
- palette = palette[::-1]
153
-
154
- # only happy little accidents
155
- if pretty and palette:
156
- raise ValueError("Cannot use argument 'pretty' in combination with 'palette', please pick one")
157
-
158
- remaining = 0
159
- active = None
160
- in_null_run = False
161
- in_collapsed_null_run = False
162
- last_offset = len(data) - 16
163
-
164
- for i in range(0, len(data), 16):
165
- values = ""
166
- chars = []
167
-
168
- for j in range(16):
169
- if not active and palette:
170
- remaining, active = palette.pop()
171
- while remaining == 0:
172
- if len(palette) == 0:
173
- # Last palette tuple is empty: print remaining whitespaces
174
- active = ""
175
- break
176
- else:
177
- remaining, active = palette.pop()
178
- values += active
179
- elif active and j == 0:
180
- values += active
181
-
182
- if i + j >= len(data):
183
- values += " "
184
- else:
185
- char = data[i + j]
186
- char = chr(char)
187
-
188
- print_char = char if char in PRINTABLE else "."
189
-
190
- if active:
191
- values += f"{ord(char):02x}"
192
- chars.append(active + print_char + COLOR_CLEAR_BOLD)
193
- else:
194
- if pretty and (color := HUMAN_COLORS.get(char, "")):
195
- values += f"{color}{ord(char):02x}{COLOR_CLEAR}"
196
- chars.append(color + print_char + COLOR_CLEAR)
197
- else:
198
- values += f"{ord(char):02x}"
199
- chars.append(print_char)
200
-
201
- remaining -= 1
202
- if remaining == 0:
203
- active = None
204
-
205
- if palette is not None:
206
- values += COLOR_CLEAR_BOLD
207
-
208
- if j == 15 and palette is not None:
209
- values += COLOR_CLEAR_BOLD
210
-
211
- values += " "
212
- if j == 7:
213
- values += " "
214
-
215
- if autoskip and 0 < i < last_offset and data[i : i + 16] == b"\x00" * 16:
216
- if in_null_run:
217
- if not in_collapsed_null_run:
218
- yield "*"
219
- in_collapsed_null_run = True
220
- continue
221
-
222
- # Keep the first interior NUL line visible, collapse from the second onwards.
223
- in_null_run = True
224
- else:
225
- in_null_run = False
226
- in_collapsed_null_run = False
227
-
228
- chars = "".join(chars)
229
- yield f"{prefix}{offset + i:08x} {values:48s} {chars}"
230
-
231
-
232
- def hexdump(
233
- data: bytes,
234
- *,
235
- palette: Palette | None = None,
236
- offset: int = 0,
237
- prefix: str = "",
238
- output: str = "print",
239
- pretty: bool | None = None,
240
- autoskip: bool = False,
241
- ) -> Iterator[str] | str | None:
242
- """Hexdump some data.
243
-
244
- Uses colored ANSI output with output type "print" by default. Disable with ``pretty=False``
245
- or set the environment variable ``NO_COLOR``.
246
-
247
- Args:
248
- data: Bytes to hexdump.
249
- palette: Colorize the hexdump using this color pattern.
250
- offset: Byte offset of the hexdump.
251
- prefix: Optional prefix.
252
- output: Output format, can be 'print', 'generator' or 'string'.
253
- pretty: Use pretty colors for improved human readability.
254
- autoskip: A single '*' replaces NUL-lines in the output.
255
- """
256
- # Enable pretty colors by default if ...
257
- if (
258
- output == "print" # the output type is set to 'print'
259
- and not palette # no palette is given (structdump only)
260
- and pretty is not False # pretty was not explicitly set to False
261
- and not os.environ.get("NO_COLOR") # and the environment allows colors
262
- ):
263
- pretty = True
264
-
265
- generator = _hexdump(data, palette=palette, offset=offset, prefix=prefix, pretty=pretty, autoskip=autoskip)
266
- if output == "print":
267
- print("\n".join(generator))
268
- return None
269
- if output == "generator":
270
- return generator
271
- if output == "string":
272
- return "\n".join(list(generator))
273
- raise ValueError(f"Invalid output argument: {output!r} (should be 'print', 'generator' or 'string').")
274
-
275
-
276
- def _dumpstruct(
277
- structure: Structure,
278
- data: bytes,
279
- offset: int,
280
- color: bool,
281
- output: str,
282
- autoskip: bool,
283
- ) -> str | None:
284
- palette = []
285
- colors = [
286
- (COLOR_RED_BOLD, COLOR_BG_RED),
287
- (COLOR_GREEN_BOLD, COLOR_BG_GREEN),
288
- (COLOR_YELLOW_BOLD, COLOR_BG_YELLOW),
289
- (COLOR_BLUE_BOLD, COLOR_BG_BLUE),
290
- (COLOR_PURPLE_BOLD, COLOR_BG_PURPLE),
291
- (COLOR_CYAN_BOLD, COLOR_BG_CYAN),
292
- (COLOR_WHITE_BOLD, COLOR_BG_WHITE),
293
- ]
294
- ci = 0
295
- out = [f"struct {structure.__class__.__name__}:"]
296
- foreground, background = None, None
297
- for field in structure.__class__.__fields__:
298
- if getattr(field.type, "anonymous", False):
299
- continue
300
-
301
- value = getattr(structure, field._name)
302
-
303
- if isinstance(value, int) and not isinstance(value, Enum):
304
- value = hex(value)
305
- elif isinstance(value, list):
306
- value = pprint.pformat(value)
307
- if "\n" in value:
308
- value = value.replace("\n", f"\n{' ' * (len(field._name) + 4)}")
309
- else:
310
- value = repr(value)
311
-
312
- if color:
313
- foreground, background = colors[ci % len(colors)]
314
- size = structure.__sizes__[field._name]
315
- palette.append((size, background))
316
- ci += 1
317
- out.append(f"- {foreground}{field._name}{COLOR_CLEAR_BOLD}: {value}")
318
- else:
319
- out.append(f"- {field._name}: {value}")
320
-
321
- out = "\n".join(out)
322
-
323
- if output == "print":
324
- print()
325
- hexdump(data, palette=palette, offset=offset, autoskip=autoskip)
326
- print()
327
- print(out)
328
- elif output == "string":
329
- return f"\n{hexdump(data, palette=palette, offset=offset, output='string', autoskip=autoskip)}\n\n{out}"
330
- return None
331
-
332
-
333
- def dumpstruct(
334
- obj: Structure | type[Structure],
335
- data: bytes | None = None,
336
- offset: int = 0,
337
- color: bool = True,
338
- autoskip: bool = False,
339
- output: str = "print",
340
- ) -> str | None:
341
- """Dump a structure or parsed structure instance.
342
-
343
- Prints a colorized hexdump and parsed structure output.
344
-
345
- Args:
346
- obj: Structure to dump.
347
- data: Bytes to parse the Structure on, if obj is not a parsed Structure already.
348
- offset: Byte offset of the hexdump.
349
- color: Colorize the hexdump and structure output.
350
- autoskip: A single '*' replaces NUL-lines in the output.
351
- output: Output format, can be 'print' or 'string'.
352
- """
353
- if output not in ("print", "string"):
354
- raise ValueError(f"Invalid output argument: {output!r} (should be 'print' or 'string').")
355
-
356
- if isinstance(obj, type) and data is not None:
357
- return _dumpstruct(obj(data), data, offset, color, output, autoskip)
358
-
359
- return _dumpstruct(obj, obj.dumps(), offset, color, output, autoskip)
360
-
361
-
362
57
  @lru_cache(1024)
363
58
  def _struct(endian: str, fmt: str) -> struct.Struct:
364
59
  return struct.Struct(f"{endian}{fmt}")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dissect.cstruct
3
- Version: 5.0.dev16
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
 
@@ -1,16 +1,18 @@
1
- dissect/cstruct/__init__.py,sha256=KOyNeUvu4c0JaAiyOfj7iftGwUIjTmD8MwHtFsLPLSU,1504
1
+ dissect/cstruct/__init__.py,sha256=eO8ddn6U2EA_ta2QNKe8jYNgDVYC3gDBrafZ9Qqq4UM,1528
2
2
  dissect/cstruct/bitbuffer.py,sha256=aNzY4lkWe8ffAc8j7FODXzwZc8gZwbey77UosyoYCsw,2711
3
3
  dissect/cstruct/compiler.py,sha256=0u58J5pB4izosBj8G4wiBI1JSAAgHFMLM63IaSG4YO4,54509
4
4
  dissect/cstruct/cstruct.py,sha256=mJerzPouWV29RdK5LqjGitDDMvNKcadoT2hj1zpExnM,26551
5
+ dissect/cstruct/declarative.py,sha256=5ubPtOyy6L5gJMFaPcbW3xYbTijZGMp0XJGxBeed1nE,14505
6
+ dissect/cstruct/dump.py,sha256=4PS4h9R9bmDveYMFBdkM1Nw1_wZy0UUES1CDc4qxtrA,18774
5
7
  dissect/cstruct/exception.py,sha256=box-mw6FoP6c3vndvYLcTeJCZVgIG8IQVPEAg4zW0C8,380
6
8
  dissect/cstruct/expression.py,sha256=SbZRv7ueasYU4k-4k2eV1fjwL3JTAgF2UBaBvNjwiv4,10736
7
9
  dissect/cstruct/lexer.py,sha256=N7eqCOlcaQriUUIswJv16i-CE_sahYXGO-YdFO0IKKY,20421
8
10
  dissect/cstruct/parser.py,sha256=6PovhIbicENg3jBgopdArupmQNd-Ti7rd_te9au4z6U,22569
9
- dissect/cstruct/util.py,sha256=vAf-kdOkk3zprW_gD6QmQeN3VIRgQqhPS4B_ha1jEpQ,18040
11
+ dissect/cstruct/util.py,sha256=wdHZL8HhjG8LnATAxpQd50PnUJDM6XBJ9r8WlDzX830,8373
10
12
  dissect/cstruct/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
13
  dissect/cstruct/tools/stubgen.py,sha256=MeZkLmSeNSLNcAEwlAdIGv1lKvlvK3UQ4WN85ovsxTM,7672
12
14
  dissect/cstruct/types/__init__.py,sha256=6P71Pu94Dv7RNjZpDZ19pqzx-G0QzmQw4q0-3zWALso,911
13
- dissect/cstruct/types/base.py,sha256=bbaxiHCVkoU6ugqn5RYishPQ5L6xGrPfQuejjro0K_g,18133
15
+ dissect/cstruct/types/base.py,sha256=NdCP9dJk6lrKPERYjR9qeD2gFzWd6krVSN4tAOqqkvI,18357
14
16
  dissect/cstruct/types/char.py,sha256=N19R7Zzn2uMuG-ULW5X2UgmgkLvjaBj1Td7AQQI93Fg,3417
15
17
  dissect/cstruct/types/enum.py,sha256=nOdI6vGtqTfPMhOBkKuiuOriIB2YHSt8Q9ruri37s3U,9177
16
18
  dissect/cstruct/types/flag.py,sha256=YxQHix8ZhK1qQX3J_Og7GJp_4JAxCwzUbUibuJeDaWQ,3479
@@ -18,13 +20,13 @@ dissect/cstruct/types/int.py,sha256=9RbdrkvAI28zATM97VVORQnras0XhLaVMtdPjJwpTH4,
18
20
  dissect/cstruct/types/leb128.py,sha256=V97XTJT_Xbw1LpTwTN1OkjPHuQQAQUxd8OGuA6yEDmE,2387
19
21
  dissect/cstruct/types/packed.py,sha256=NgCX0YWX8SH8z47atq0f39w9MBjU_eBFJtUisUWdO-M,3867
20
22
  dissect/cstruct/types/pointer.py,sha256=FNuB9bfENWRebbKX-R6Vs6xWPMHepjvOhhomeUhr7I8,3985
21
- dissect/cstruct/types/structure.py,sha256=mxDvurQ0oAjI2flykhAPlT-03280cDpwGTz0-bqbr-0,39558
23
+ dissect/cstruct/types/structure.py,sha256=DHsdtRfhcEPB4W9aBfctLflDH6xaBvxKuOtDWhSO7iQ,39675
22
24
  dissect/cstruct/types/void.py,sha256=fV4hKk50uop_EKbR1nfy1cdtAzvUYrSymXsdakCyFk8,1222
23
25
  dissect/cstruct/types/wchar.py,sha256=VrnPXsP_lsyA-1xr4D2aSIVijumMhUuZWNlDHcn12-s,3964
24
- dissect_cstruct-5.0.dev16.dist-info/licenses/COPYRIGHT,sha256=H-18RXfshdH9AdHwW2eO1Xa-5s6tY5eipHh5c0whDu4,316
25
- dissect_cstruct-5.0.dev16.dist-info/licenses/LICENSE,sha256=PhUqiw6jAh2KbBdVRPBq_hfAvfcTBin7nZ3CK7NQbTM,11341
26
- dissect_cstruct-5.0.dev16.dist-info/METADATA,sha256=xdol4wRzYoijmhDPLkLFrAn0S8-Ag4LquHg3MRZ3Hu8,9256
27
- dissect_cstruct-5.0.dev16.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
28
- dissect_cstruct-5.0.dev16.dist-info/entry_points.txt,sha256=z53zqZqwD2OLrAkRwrP4wTeiU9CQe7xrMly0T2c0_wQ,71
29
- dissect_cstruct-5.0.dev16.dist-info/top_level.txt,sha256=Mn-CQzEYsAbkxrUI0TnplHuXnGVKzxpDw_po_sXpvv4,8
30
- dissect_cstruct-5.0.dev16.dist-info/RECORD,,
26
+ dissect_cstruct-5.0.dev18.dist-info/licenses/COPYRIGHT,sha256=H-18RXfshdH9AdHwW2eO1Xa-5s6tY5eipHh5c0whDu4,316
27
+ dissect_cstruct-5.0.dev18.dist-info/licenses/LICENSE,sha256=PhUqiw6jAh2KbBdVRPBq_hfAvfcTBin7nZ3CK7NQbTM,11341
28
+ dissect_cstruct-5.0.dev18.dist-info/METADATA,sha256=cY4cQa56JsEILbAzrcmeh5M_akYena2rAgkg0SvxGWY,11448
29
+ dissect_cstruct-5.0.dev18.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
30
+ dissect_cstruct-5.0.dev18.dist-info/entry_points.txt,sha256=z53zqZqwD2OLrAkRwrP4wTeiU9CQe7xrMly0T2c0_wQ,71
31
+ dissect_cstruct-5.0.dev18.dist-info/top_level.txt,sha256=Mn-CQzEYsAbkxrUI0TnplHuXnGVKzxpDw_po_sXpvv4,8
32
+ dissect_cstruct-5.0.dev18.dist-info/RECORD,,