dissect.cstruct 5.0.dev15__py3-none-any.whl → 5.0.dev17__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/__init__.py +1 -2
- dissect/cstruct/dump.py +509 -0
- dissect/cstruct/exception.py +4 -0
- dissect/cstruct/expression.py +14 -18
- dissect/cstruct/lexer.py +10 -5
- dissect/cstruct/parser.py +21 -11
- dissect/cstruct/types/structure.py +2 -1
- dissect/cstruct/util.py +0 -305
- {dissect_cstruct-5.0.dev15.dist-info → dissect_cstruct-5.0.dev17.dist-info}/METADATA +1 -1
- {dissect_cstruct-5.0.dev15.dist-info → dissect_cstruct-5.0.dev17.dist-info}/RECORD +15 -14
- {dissect_cstruct-5.0.dev15.dist-info → dissect_cstruct-5.0.dev17.dist-info}/WHEEL +0 -0
- {dissect_cstruct-5.0.dev15.dist-info → dissect_cstruct-5.0.dev17.dist-info}/entry_points.txt +0 -0
- {dissect_cstruct-5.0.dev15.dist-info → dissect_cstruct-5.0.dev17.dist-info}/licenses/COPYRIGHT +0 -0
- {dissect_cstruct-5.0.dev15.dist-info → dissect_cstruct-5.0.dev17.dist-info}/licenses/LICENSE +0 -0
- {dissect_cstruct-5.0.dev15.dist-info → dissect_cstruct-5.0.dev17.dist-info}/top_level.txt +0 -0
dissect/cstruct/__init__.py
CHANGED
|
@@ -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,
|
dissect/cstruct/dump.py
ADDED
|
@@ -0,0 +1,509 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import pprint
|
|
6
|
+
import string
|
|
7
|
+
from enum import Enum
|
|
8
|
+
from typing import TYPE_CHECKING, Any, Literal
|
|
9
|
+
|
|
10
|
+
from dissect.cstruct.types.base import BaseArray
|
|
11
|
+
from dissect.cstruct.types.enum import EnumMetaType
|
|
12
|
+
from dissect.cstruct.types.pointer import Pointer
|
|
13
|
+
from dissect.cstruct.types.structure import Structure, Union, UnionProxy
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from collections.abc import Iterator
|
|
17
|
+
|
|
18
|
+
from dissect.cstruct.types.base import BaseType
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
# Regular ANSI colors
|
|
22
|
+
COLOR_RED = "\033[0;31m"
|
|
23
|
+
COLOR_GREEN = "\033[0;32m"
|
|
24
|
+
COLOR_YELLOW = "\033[0;93m"
|
|
25
|
+
COLOR_BLUE = "\033[0;34m"
|
|
26
|
+
COLOR_PURPLE = "\033[0;35m"
|
|
27
|
+
COLOR_CYAN = "\033[0;36m"
|
|
28
|
+
COLOR_WHITE = "\033[0;37m"
|
|
29
|
+
COLOR_BLACK = "\033[0;30m"
|
|
30
|
+
COLOR_GREY = "\033[0;90m"
|
|
31
|
+
|
|
32
|
+
# Bold ANSI colors
|
|
33
|
+
COLOR_RED_BOLD = "\033[1;31m"
|
|
34
|
+
COLOR_GREEN_BOLD = "\033[1;32m"
|
|
35
|
+
COLOR_YELLOW_BOLD = "\033[1;33m"
|
|
36
|
+
COLOR_BLUE_BOLD = "\033[1;34m"
|
|
37
|
+
COLOR_PURPLE_BOLD = "\033[1;35m"
|
|
38
|
+
COLOR_CYAN_BOLD = "\033[1;36m"
|
|
39
|
+
COLOR_WHITE_BOLD = "\033[1;37m"
|
|
40
|
+
COLOR_BLACK_BOLD = "\033[1;30m"
|
|
41
|
+
COLOR_GREY_BOLD = "\033[1;90m"
|
|
42
|
+
|
|
43
|
+
# Background ANSI colors
|
|
44
|
+
COLOR_BG_RED = "\033[1;41m\033[1;37m"
|
|
45
|
+
COLOR_BG_GREEN = "\033[1;42m\033[1;37m"
|
|
46
|
+
COLOR_BG_YELLOW = "\033[1;43m\033[1;37m"
|
|
47
|
+
COLOR_BG_BLUE = "\033[1;44m\033[1;37m"
|
|
48
|
+
COLOR_BG_PURPLE = "\033[1;45m\033[1;37m"
|
|
49
|
+
COLOR_BG_CYAN = "\033[1;46m\033[1;37m"
|
|
50
|
+
COLOR_BG_WHITE = "\033[1;47m\033[1;30m"
|
|
51
|
+
|
|
52
|
+
# Reset ANSI codes
|
|
53
|
+
COLOR_CLEAR = "\033[0m"
|
|
54
|
+
|
|
55
|
+
PRINTABLE = string.digits + string.ascii_letters + string.punctuation + " "
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
Palette = list[tuple[int, str]]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _human_colors() -> dict[str, str]:
|
|
62
|
+
"""Generates a dictionary of characters with a human-readable ANSI color they should be in a hexdump.
|
|
63
|
+
|
|
64
|
+
Coloring logic implementation derived from HexFriend and ImHex.
|
|
65
|
+
"""
|
|
66
|
+
# Make all characters not in any rules below light green
|
|
67
|
+
colors = {chr(char): COLOR_GREEN for char in range(256)}
|
|
68
|
+
|
|
69
|
+
# Make all 7-bit ASCII characters yellow
|
|
70
|
+
for char in colors:
|
|
71
|
+
if ord(char) & 0x80 == 0:
|
|
72
|
+
colors[char] = COLOR_YELLOW
|
|
73
|
+
|
|
74
|
+
# Make null bytes grey
|
|
75
|
+
colors["\00"] = COLOR_GREY
|
|
76
|
+
|
|
77
|
+
# Make printable ASCII characters bold white (0x32-0x7E)
|
|
78
|
+
for char in PRINTABLE:
|
|
79
|
+
colors[char] = COLOR_WHITE_BOLD
|
|
80
|
+
|
|
81
|
+
# Make ASCII whitespace characters green bold (0x9, 0xA, 0xB, 0xC, 0xD, 0x20)
|
|
82
|
+
for char in ("\t", "\n", "\v", "\f", "\r", " "):
|
|
83
|
+
colors[char] = COLOR_GREEN_BOLD
|
|
84
|
+
|
|
85
|
+
return colors
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
HUMAN_COLORS = _human_colors()
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _hexdump(
|
|
92
|
+
data: bytes,
|
|
93
|
+
*,
|
|
94
|
+
palette: Palette | None = None,
|
|
95
|
+
offset: int = 0,
|
|
96
|
+
prefix: str = "",
|
|
97
|
+
pretty: bool | None = False,
|
|
98
|
+
autoskip: bool = False,
|
|
99
|
+
) -> Iterator[str]:
|
|
100
|
+
"""Hexdump some data.
|
|
101
|
+
|
|
102
|
+
Args:
|
|
103
|
+
data: Bytes to hexdump.
|
|
104
|
+
palette: Colorize the hexdump using this color pattern. An empty color leaves those bytes uncolored.
|
|
105
|
+
offset: Byte offset of the hexdump.
|
|
106
|
+
prefix: Optional prefix.
|
|
107
|
+
pretty: Use pretty colors, mutual exclusive with palette.
|
|
108
|
+
autoskip: A single '*' replaces NUL-lines in the output.
|
|
109
|
+
"""
|
|
110
|
+
if palette:
|
|
111
|
+
palette = palette[::-1]
|
|
112
|
+
|
|
113
|
+
# only happy little accidents
|
|
114
|
+
if pretty and palette:
|
|
115
|
+
raise ValueError("Cannot use argument 'pretty' in combination with 'palette', please pick one")
|
|
116
|
+
|
|
117
|
+
remaining = 0
|
|
118
|
+
active = None
|
|
119
|
+
in_null_run = False
|
|
120
|
+
in_collapsed_null_run = False
|
|
121
|
+
last_offset = len(data) - 16
|
|
122
|
+
|
|
123
|
+
for i in range(0, len(data), 16):
|
|
124
|
+
values = ""
|
|
125
|
+
chars = []
|
|
126
|
+
|
|
127
|
+
for j in range(16):
|
|
128
|
+
if remaining <= 0 and palette:
|
|
129
|
+
remaining, active = palette.pop()
|
|
130
|
+
while remaining == 0:
|
|
131
|
+
if len(palette) == 0:
|
|
132
|
+
# Last palette tuple is empty: print remaining whitespaces
|
|
133
|
+
active = ""
|
|
134
|
+
break
|
|
135
|
+
else:
|
|
136
|
+
remaining, active = palette.pop()
|
|
137
|
+
values += active
|
|
138
|
+
elif active and j == 0:
|
|
139
|
+
values += active
|
|
140
|
+
|
|
141
|
+
if i + j >= len(data):
|
|
142
|
+
values += " "
|
|
143
|
+
else:
|
|
144
|
+
char = data[i + j]
|
|
145
|
+
char = chr(char)
|
|
146
|
+
|
|
147
|
+
print_char = char if char in PRINTABLE else "."
|
|
148
|
+
|
|
149
|
+
if active:
|
|
150
|
+
values += f"{ord(char):02x}"
|
|
151
|
+
chars.append(active + print_char + COLOR_CLEAR)
|
|
152
|
+
else:
|
|
153
|
+
if pretty and (color := HUMAN_COLORS.get(char, "")):
|
|
154
|
+
values += f"{color}{ord(char):02x}{COLOR_CLEAR}"
|
|
155
|
+
chars.append(color + print_char + COLOR_CLEAR)
|
|
156
|
+
else:
|
|
157
|
+
values += f"{ord(char):02x}"
|
|
158
|
+
chars.append(print_char)
|
|
159
|
+
|
|
160
|
+
remaining -= 1
|
|
161
|
+
if remaining == 0:
|
|
162
|
+
active = None
|
|
163
|
+
|
|
164
|
+
if palette is not None:
|
|
165
|
+
values += COLOR_CLEAR
|
|
166
|
+
|
|
167
|
+
if j == 15 and palette is not None:
|
|
168
|
+
values += COLOR_CLEAR
|
|
169
|
+
|
|
170
|
+
values += " "
|
|
171
|
+
if j == 7:
|
|
172
|
+
values += " "
|
|
173
|
+
|
|
174
|
+
if autoskip and 0 < i < last_offset and data[i : i + 16] == b"\x00" * 16:
|
|
175
|
+
if in_null_run:
|
|
176
|
+
if not in_collapsed_null_run:
|
|
177
|
+
yield "*"
|
|
178
|
+
in_collapsed_null_run = True
|
|
179
|
+
continue
|
|
180
|
+
|
|
181
|
+
# Keep the first interior NUL line visible, collapse from the second onwards.
|
|
182
|
+
in_null_run = True
|
|
183
|
+
else:
|
|
184
|
+
in_null_run = False
|
|
185
|
+
in_collapsed_null_run = False
|
|
186
|
+
|
|
187
|
+
chars = "".join(chars)
|
|
188
|
+
yield f"{prefix}{offset + i:08x} {values:48s} {chars}"
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def hexdump(
|
|
192
|
+
data: bytes,
|
|
193
|
+
*,
|
|
194
|
+
palette: Palette | None = None,
|
|
195
|
+
offset: int = 0,
|
|
196
|
+
prefix: str = "",
|
|
197
|
+
output: Literal["print", "generator", "string"] = "print",
|
|
198
|
+
pretty: bool | None = None,
|
|
199
|
+
autoskip: bool = False,
|
|
200
|
+
) -> Iterator[str] | str | None:
|
|
201
|
+
"""Hexdump some data.
|
|
202
|
+
|
|
203
|
+
Uses colored ANSI output with output type "print" by default. Disable with ``pretty=False``
|
|
204
|
+
or set the environment variable ``NO_COLOR``.
|
|
205
|
+
|
|
206
|
+
Args:
|
|
207
|
+
data: Bytes to hexdump.
|
|
208
|
+
palette: Colorize the hexdump using this color pattern.
|
|
209
|
+
offset: Byte offset of the hexdump.
|
|
210
|
+
prefix: Optional prefix.
|
|
211
|
+
output: Output format, can be 'print', 'generator' or 'string'.
|
|
212
|
+
pretty: Use pretty colors for improved human readability.
|
|
213
|
+
autoskip: A single '*' replaces NUL-lines in the output.
|
|
214
|
+
"""
|
|
215
|
+
# Enable pretty colors by default if ...
|
|
216
|
+
if (
|
|
217
|
+
output == "print" # the output type is set to 'print'
|
|
218
|
+
and not palette # no palette is given (structdump only)
|
|
219
|
+
and pretty is not False # pretty was not explicitly set to False
|
|
220
|
+
and not os.environ.get("NO_COLOR") # and the environment allows colors
|
|
221
|
+
):
|
|
222
|
+
pretty = True
|
|
223
|
+
|
|
224
|
+
generator = _hexdump(data, palette=palette, offset=offset, prefix=prefix, pretty=pretty, autoskip=autoskip)
|
|
225
|
+
if output == "print":
|
|
226
|
+
print("\n".join(generator))
|
|
227
|
+
return None
|
|
228
|
+
if output == "generator":
|
|
229
|
+
return generator
|
|
230
|
+
if output == "string":
|
|
231
|
+
return "\n".join(list(generator))
|
|
232
|
+
raise ValueError(f"Invalid output argument: {output!r} (should be 'print', 'generator' or 'string').")
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _format_value(value: Any) -> str | None:
|
|
236
|
+
"""Format a structure field value for human-readable display."""
|
|
237
|
+
if value is None:
|
|
238
|
+
return None
|
|
239
|
+
if isinstance(value, (str, Pointer, Enum)):
|
|
240
|
+
return repr(value)
|
|
241
|
+
if isinstance(value, int):
|
|
242
|
+
return hex(value)
|
|
243
|
+
if isinstance(value, list):
|
|
244
|
+
return pprint.pformat(value)
|
|
245
|
+
return str(value)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _describe_fields(structure: Structure, start: int | None) -> list[dict[str, Any]]:
|
|
249
|
+
"""Describe the fields of ``structure`` as nodes, with offsets into the dumped data.
|
|
250
|
+
|
|
251
|
+
The offsets follow ``Structure._read``: explicit field offsets, alignment padding and bit fields sharing a
|
|
252
|
+
storage unit. They are ``None`` after a field of unknown size, e.g. a dynamic field of a structure that
|
|
253
|
+
wasn't parsed.
|
|
254
|
+
"""
|
|
255
|
+
nodes: list[dict[str, Any]] = []
|
|
256
|
+
sizes = structure.__sizes__
|
|
257
|
+
is_union = isinstance(structure, Union)
|
|
258
|
+
|
|
259
|
+
offset = start
|
|
260
|
+
bits_type = None
|
|
261
|
+
bits_offset = None
|
|
262
|
+
bits_remaining = 0
|
|
263
|
+
|
|
264
|
+
for field in structure.__class__.__fields__:
|
|
265
|
+
if field.offset is not None and start is not None:
|
|
266
|
+
offset = start + field.offset
|
|
267
|
+
elif is_union:
|
|
268
|
+
offset = start
|
|
269
|
+
elif structure.__align__ and offset is not None:
|
|
270
|
+
offset += -offset & (field.alignment - 1)
|
|
271
|
+
|
|
272
|
+
# Of fields with a repeated name ("_"), a structure only keeps the value and size of the last one
|
|
273
|
+
if structure.__class__.__lookup__[field._name] is field:
|
|
274
|
+
value, size = getattr(structure, field._name), sizes.get(field._name)
|
|
275
|
+
else:
|
|
276
|
+
value, size = None, field.type.__size__
|
|
277
|
+
|
|
278
|
+
if field.bits:
|
|
279
|
+
field_type = field.type.__type__ if isinstance(field.type, EnumMetaType) else field.type
|
|
280
|
+
# Like BitBuffer, start a new storage unit when the current one is full or the type changes
|
|
281
|
+
if bits_remaining == 0 or field_type != bits_type:
|
|
282
|
+
bits_type = field_type
|
|
283
|
+
bits_offset = offset
|
|
284
|
+
bits_remaining = field_type.__size__ * 8
|
|
285
|
+
if offset is not None:
|
|
286
|
+
offset += field_type.__size__
|
|
287
|
+
|
|
288
|
+
bits_remaining -= field.bits
|
|
289
|
+
nodes.append(
|
|
290
|
+
{
|
|
291
|
+
"name": field._name,
|
|
292
|
+
"type": field.type.__name__,
|
|
293
|
+
"offset": bits_offset,
|
|
294
|
+
"size": field_type.__size__,
|
|
295
|
+
"bits": field.bits,
|
|
296
|
+
"display": _format_value(value),
|
|
297
|
+
}
|
|
298
|
+
)
|
|
299
|
+
continue
|
|
300
|
+
|
|
301
|
+
bits_type = None
|
|
302
|
+
|
|
303
|
+
# Anonymous struct/union members have no name, their fields are accessed on the parent
|
|
304
|
+
name = None if field.name is None else f"{field.name}{_array_dimensions(field.type)[1]}"
|
|
305
|
+
nodes.append(_describe_value(name, field.type, value, offset, size))
|
|
306
|
+
|
|
307
|
+
if offset is not None:
|
|
308
|
+
offset = None if size is None else offset + size
|
|
309
|
+
|
|
310
|
+
return nodes
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _describe_value(
|
|
314
|
+
name: str | None, type_: type[BaseType], value: Any, offset: int | None, size: int | None
|
|
315
|
+
) -> dict[str, Any]:
|
|
316
|
+
"""Describe a field or array element as a node.
|
|
317
|
+
|
|
318
|
+
Structures and unions, and arrays of them, get their fields or elements as child nodes. Other values, including
|
|
319
|
+
arrays of other types, are formatted as a human-readable ``display``.
|
|
320
|
+
"""
|
|
321
|
+
if isinstance(value, UnionProxy):
|
|
322
|
+
# Nested Structure members inside a Union are proxied; unwrap to the real Structure
|
|
323
|
+
value = value.__target__
|
|
324
|
+
|
|
325
|
+
base_type = _array_dimensions(type_)[0]
|
|
326
|
+
is_structure = issubclass(base_type, Structure)
|
|
327
|
+
node = {
|
|
328
|
+
"name": name,
|
|
329
|
+
"type": None if is_structure and base_type.__anonymous__ else base_type.__name__,
|
|
330
|
+
"offset": offset,
|
|
331
|
+
"size": size,
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
if isinstance(value, Structure):
|
|
335
|
+
node["kind"] = "union" if isinstance(value, Union) else "struct"
|
|
336
|
+
node["fields"] = _describe_fields(value, offset)
|
|
337
|
+
elif is_structure and isinstance(value, list):
|
|
338
|
+
node["kind"] = "array"
|
|
339
|
+
node["fields"] = []
|
|
340
|
+
element_type = type_.__type__
|
|
341
|
+
for i, element in enumerate(value):
|
|
342
|
+
element_node = _describe_value(f"[{i}]", element_type, element, offset, element_type.__size__)
|
|
343
|
+
node["fields"].append(element_node)
|
|
344
|
+
if offset is not None:
|
|
345
|
+
offset = None if element_node["size"] is None else offset + element_node["size"]
|
|
346
|
+
else:
|
|
347
|
+
node["display"] = _format_value(value)
|
|
348
|
+
|
|
349
|
+
if size is None and node["offset"] is not None and "fields" in node:
|
|
350
|
+
# Parsing doesn't record the sizes of array elements, so a dynamic element ends where its last field ends
|
|
351
|
+
ends = [
|
|
352
|
+
child["offset"] + child["size"] for child in node["fields"] if None not in (child["offset"], child["size"])
|
|
353
|
+
]
|
|
354
|
+
if len(ends) == len(node["fields"]):
|
|
355
|
+
end = max(ends, default=node["offset"])
|
|
356
|
+
if isinstance(value, Structure) and value.__align__:
|
|
357
|
+
end += -end & (value.__alignment__ - 1)
|
|
358
|
+
node["size"] = end - node["offset"]
|
|
359
|
+
|
|
360
|
+
return node
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _array_dimensions(type_: type[BaseType]) -> tuple[type[BaseType], str]:
|
|
364
|
+
"""Return the element type of a (multi-dimensional) array type and its dimensions in C order, e.g. ``[2][3]``."""
|
|
365
|
+
dimensions = ""
|
|
366
|
+
while issubclass(type_, BaseArray):
|
|
367
|
+
count = type_.__num_entries__
|
|
368
|
+
dimensions += f"[{'' if count is None else count}]"
|
|
369
|
+
type_ = type_.__type__
|
|
370
|
+
return type_, dimensions
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
DUMP_COLORS = [
|
|
374
|
+
(COLOR_RED_BOLD, COLOR_BG_RED),
|
|
375
|
+
(COLOR_GREEN_BOLD, COLOR_BG_GREEN),
|
|
376
|
+
(COLOR_YELLOW_BOLD, COLOR_BG_YELLOW),
|
|
377
|
+
(COLOR_BLUE_BOLD, COLOR_BG_BLUE),
|
|
378
|
+
(COLOR_PURPLE_BOLD, COLOR_BG_PURPLE),
|
|
379
|
+
(COLOR_CYAN_BOLD, COLOR_BG_CYAN),
|
|
380
|
+
(COLOR_WHITE_BOLD, COLOR_BG_WHITE),
|
|
381
|
+
]
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _render_fields(
|
|
385
|
+
nodes: list[dict[str, Any]],
|
|
386
|
+
indent: int,
|
|
387
|
+
lines: list[tuple[int, str, str | None]],
|
|
388
|
+
palette: Palette,
|
|
389
|
+
colored_end: int,
|
|
390
|
+
) -> int:
|
|
391
|
+
"""Add an ``(indent, name, value)`` line per field to ``lines``, and the hexdump colors to ``palette``.
|
|
392
|
+
|
|
393
|
+
Line ``i`` gets color ``i`` of ``DUMP_COLORS``. The bytes of a value or a union get the background color of
|
|
394
|
+
their (first) line, unless they overlap bytes that are already colored, such as union members and bit fields
|
|
395
|
+
after the first one in a storage unit. A struct leaves the coloring to its fields.
|
|
396
|
+
|
|
397
|
+
Returns the end offset of the colored bytes.
|
|
398
|
+
"""
|
|
399
|
+
for node in nodes:
|
|
400
|
+
offset, size = node["offset"], node["size"]
|
|
401
|
+
if ("display" in node or node["kind"] == "union") and offset is not None and size and offset >= colored_end:
|
|
402
|
+
if offset > colored_end:
|
|
403
|
+
# Leave padding uncolored
|
|
404
|
+
palette.append((offset - colored_end, ""))
|
|
405
|
+
palette.append((size, DUMP_COLORS[len(lines) % len(DUMP_COLORS)][1]))
|
|
406
|
+
colored_end = offset + size
|
|
407
|
+
|
|
408
|
+
if "fields" not in node:
|
|
409
|
+
lines.append((indent, node["name"], node["display"]))
|
|
410
|
+
elif node["name"] is None:
|
|
411
|
+
colored_end = _render_fields(node["fields"], indent, lines, palette, colored_end)
|
|
412
|
+
else:
|
|
413
|
+
lines.append((indent, node["name"], None))
|
|
414
|
+
colored_end = _render_fields(node["fields"], indent + 1, lines, palette, colored_end)
|
|
415
|
+
|
|
416
|
+
return colored_end
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def dumpstruct(
|
|
420
|
+
obj: Structure | type[Structure],
|
|
421
|
+
data: bytes | None = None,
|
|
422
|
+
offset: int = 0,
|
|
423
|
+
color: bool = True,
|
|
424
|
+
autoskip: bool = False,
|
|
425
|
+
output: Literal["print", "string", "dict", "json"] = "print",
|
|
426
|
+
) -> str | dict[str, Any] | None:
|
|
427
|
+
"""Dump a structure or parsed structure instance.
|
|
428
|
+
|
|
429
|
+
Prints a colorized hexdump and parsed structure output.
|
|
430
|
+
|
|
431
|
+
The ``dict`` and ``json`` output formats describe the structure as a tree:
|
|
432
|
+
- bytes: hex string of the raw data
|
|
433
|
+
- type: type name of the structure
|
|
434
|
+
- kind: ``struct`` or ``union``
|
|
435
|
+
- fields: list of field nodes
|
|
436
|
+
|
|
437
|
+
A field node has a ``name``, ``type``, ``offset`` and ``size``, where ``offset`` is the position in ``bytes``.
|
|
438
|
+
Values have a human-readable ``display``. Bit fields also have ``bits``, and share the ``offset`` and ``size`` of
|
|
439
|
+
their storage unit. Nested structs and unions have a ``kind`` and ``fields`` instead of a ``display``, and so do
|
|
440
|
+
arrays of them: ``kind`` is ``array`` and ``fields`` are the elements, named ``[0]``, ``[1]``, etc.
|
|
441
|
+
Anonymous struct/union members (``struct { ... };``) have no ``name``, anonymous types have no ``type``.
|
|
442
|
+
``offset`` and ``size`` are ``None`` when they're unknown, and so is the ``display`` of a field the structure
|
|
443
|
+
doesn't keep (all but the last of repeated ``_`` fields).
|
|
444
|
+
|
|
445
|
+
For an array, ``name`` includes the dimensions as written in the definition and ``type`` is the element type,
|
|
446
|
+
e.g. ``uint8 matrix[2][3];`` has ``name`` ``matrix[2][3]`` and ``type`` ``uint8``.
|
|
447
|
+
|
|
448
|
+
Args:
|
|
449
|
+
obj: :class:`~dissect.cstruct.types.structure.Structure` to dump.
|
|
450
|
+
data: Bytes to parse the :class:`~dissect.cstruct.types.structure.Structure` on,
|
|
451
|
+
if obj is not a parsed :class:`~dissect.cstruct.types.structure.Structure` already.
|
|
452
|
+
offset: Byte offset of the hexdump.
|
|
453
|
+
color: Colorize the hexdump and structure output.
|
|
454
|
+
autoskip: A single '*' replaces NUL-lines in the output.
|
|
455
|
+
output: Output format, can be ``print``, ``string``, ``dict`` or ``json``.
|
|
456
|
+
|
|
457
|
+
Returns:
|
|
458
|
+
Formatted string when ``output="string"``, a dict when ``output="dict"``,
|
|
459
|
+
a JSON string when ``output="json"``, or ``None`` when ``output="print"``.
|
|
460
|
+
"""
|
|
461
|
+
if output not in ("print", "string", "dict", "json"):
|
|
462
|
+
raise ValueError(f"Invalid output argument: {output!r} (should be 'print', 'string', 'dict' or 'json').")
|
|
463
|
+
|
|
464
|
+
if isinstance(obj, Structure):
|
|
465
|
+
data = obj.dumps() if data is None else data
|
|
466
|
+
elif isinstance(obj, type) and issubclass(obj, Structure) and data is not None:
|
|
467
|
+
obj = obj(data)
|
|
468
|
+
else:
|
|
469
|
+
raise ValueError("Invalid arguments: expected a Structure instance, or a Structure class with data.")
|
|
470
|
+
|
|
471
|
+
result = {
|
|
472
|
+
"bytes": data.hex(),
|
|
473
|
+
"type": obj.__class__.__name__,
|
|
474
|
+
"kind": "union" if isinstance(obj, Union) else "struct",
|
|
475
|
+
"fields": _describe_fields(obj, 0),
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
if output in ("dict", "json"):
|
|
479
|
+
return result if output == "dict" else json.dumps(result, indent=4)
|
|
480
|
+
|
|
481
|
+
lines: list[tuple[int, str, str | None]] = []
|
|
482
|
+
palette: Palette = []
|
|
483
|
+
_render_fields(result["fields"], 0, lines, palette, 0)
|
|
484
|
+
|
|
485
|
+
out = [f"{result['kind']} {result['type']}:"]
|
|
486
|
+
for ci, (indent, name, value) in enumerate(lines):
|
|
487
|
+
pad = " " * indent
|
|
488
|
+
value = "" if value is None else f" {value}"
|
|
489
|
+
if "\n" in value:
|
|
490
|
+
# Align continuation lines of multi-line values with the value start
|
|
491
|
+
value = value.replace("\n", f"\n{pad}{' ' * (len(name) + 4)}")
|
|
492
|
+
|
|
493
|
+
if color:
|
|
494
|
+
foreground, _ = DUMP_COLORS[ci % len(DUMP_COLORS)]
|
|
495
|
+
out.append(f"{pad}- {foreground}{name}{COLOR_CLEAR}:{value}")
|
|
496
|
+
else:
|
|
497
|
+
out.append(f"{pad}- {name}:{value}")
|
|
498
|
+
|
|
499
|
+
out = "\n".join(out)
|
|
500
|
+
palette = palette if color else None
|
|
501
|
+
|
|
502
|
+
if output == "print":
|
|
503
|
+
print()
|
|
504
|
+
hexdump(data, palette=palette, offset=offset, autoskip=autoskip)
|
|
505
|
+
print()
|
|
506
|
+
print(out)
|
|
507
|
+
return None
|
|
508
|
+
|
|
509
|
+
return f"\n{hexdump(data, palette=palette, offset=offset, output='string', autoskip=autoskip)}\n\n{out}"
|
dissect/cstruct/exception.py
CHANGED
dissect/cstruct/expression.py
CHANGED
|
@@ -2,8 +2,8 @@ from __future__ import annotations
|
|
|
2
2
|
|
|
3
3
|
from typing import TYPE_CHECKING, Any
|
|
4
4
|
|
|
5
|
-
from dissect.cstruct.exception import ExpressionParserError
|
|
6
|
-
from dissect.cstruct.lexer import IDENTIFIER_TYPES, Lexer, TokenCursor, TokenType
|
|
5
|
+
from dissect.cstruct.exception import ExpressionParserError, UnknownIdentifierError
|
|
6
|
+
from dissect.cstruct.lexer import IDENTIFIER_TYPES, Lexer, TokenCursor, TokenType, join_tokens
|
|
7
7
|
from dissect.cstruct.util import offsetof, sizeof
|
|
8
8
|
|
|
9
9
|
if TYPE_CHECKING:
|
|
@@ -87,11 +87,7 @@ FUNCTIONS: dict[TokenType, Callable[..., int]] = {
|
|
|
87
87
|
}
|
|
88
88
|
|
|
89
89
|
|
|
90
|
-
def
|
|
91
|
-
return ExpressionParserError(f"line {line}: {msg}")
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
def _identifier(cs: cstruct, context: dict[str, Any], ident: str, line: int) -> int:
|
|
90
|
+
def _identifier(cs: cstruct, context: dict[str, Any], ident: str) -> int:
|
|
95
91
|
"""Resolve an identifier to an integer value."""
|
|
96
92
|
obj = None
|
|
97
93
|
for i, part in enumerate(ident.split(".")):
|
|
@@ -103,16 +99,16 @@ def _identifier(cs: cstruct, context: dict[str, Any], ident: str, line: int) ->
|
|
|
103
99
|
elif part in cs.types:
|
|
104
100
|
obj = cs.types[part]
|
|
105
101
|
else:
|
|
106
|
-
raise
|
|
102
|
+
raise UnknownIdentifierError(f"Unknown identifier: '{ident}'")
|
|
107
103
|
else:
|
|
108
104
|
obj = obj.get(part, _MISSING) if isinstance(obj, dict) else getattr(obj, part, _MISSING)
|
|
109
105
|
if obj is _MISSING:
|
|
110
|
-
raise
|
|
106
|
+
raise UnknownIdentifierError(f"Unknown identifier: '{ident}'")
|
|
111
107
|
|
|
112
108
|
try:
|
|
113
109
|
return int(obj)
|
|
114
110
|
except (ValueError, TypeError):
|
|
115
|
-
raise
|
|
111
|
+
raise ExpressionParserError(f"Identifier '{ident}' does not resolve to an integer")
|
|
116
112
|
|
|
117
113
|
|
|
118
114
|
# Globals used by the source code of an expression
|
|
@@ -129,8 +125,8 @@ class _Evaluator:
|
|
|
129
125
|
def number(self, value: int) -> int:
|
|
130
126
|
return value
|
|
131
127
|
|
|
132
|
-
def identifier(self, ident: str
|
|
133
|
-
return _identifier(self.cs, self.context, ident
|
|
128
|
+
def identifier(self, ident: str) -> int:
|
|
129
|
+
return _identifier(self.cs, self.context, ident)
|
|
134
130
|
|
|
135
131
|
def unary(self, operator: TokenType, value: int) -> int:
|
|
136
132
|
return UNARY_OPERATORS[operator](value)
|
|
@@ -152,10 +148,10 @@ class _SourceBuilder:
|
|
|
152
148
|
def number(self, value: int) -> str:
|
|
153
149
|
return repr(value)
|
|
154
150
|
|
|
155
|
-
def identifier(self, ident: str
|
|
151
|
+
def identifier(self, ident: str) -> str:
|
|
156
152
|
if ident in self.variables:
|
|
157
153
|
return self.variables[ident]
|
|
158
|
-
return f"_identifier(cs, {self.context}, {ident!r}
|
|
154
|
+
return f"_identifier(cs, {self.context}, {ident!r})"
|
|
159
155
|
|
|
160
156
|
def unary(self, operator: TokenType, value: str) -> str:
|
|
161
157
|
return f"({OPERATOR_SOURCE[operator]}{value})"
|
|
@@ -195,7 +191,7 @@ class Expression(TokenCursor):
|
|
|
195
191
|
self._queue = []
|
|
196
192
|
|
|
197
193
|
def _error(self, msg: str, *, token: Token | None = None) -> ExpressionParserError:
|
|
198
|
-
return
|
|
194
|
+
return ExpressionParserError(msg)
|
|
199
195
|
|
|
200
196
|
def _evaluate_expression(self, backend: _Evaluator | _SourceBuilder) -> None:
|
|
201
197
|
operator = self._stack.pop(-1)
|
|
@@ -266,18 +262,18 @@ class Expression(TokenCursor):
|
|
|
266
262
|
|
|
267
263
|
num_args = FUNCTION_TOKENS[func]
|
|
268
264
|
while num_args > 1:
|
|
269
|
-
self._queue.append(self._collect_until(TokenType.COMMA))
|
|
265
|
+
self._queue.append(join_tokens(self._collect_until(TokenType.COMMA)))
|
|
270
266
|
self._expect(TokenType.COMMA)
|
|
271
267
|
num_args -= 1
|
|
272
268
|
|
|
273
|
-
self._queue.append(self._collect_until(TokenType.RPAREN))
|
|
269
|
+
self._queue.append(join_tokens(self._collect_until(TokenType.RPAREN)))
|
|
274
270
|
self._expect(TokenType.RPAREN)
|
|
275
271
|
|
|
276
272
|
# Evaluate immediately
|
|
277
273
|
self._evaluate_expression(backend)
|
|
278
274
|
|
|
279
275
|
elif token.type in IDENTIFIER_TYPES:
|
|
280
|
-
self._queue.append(backend.identifier(self._take().value
|
|
276
|
+
self._queue.append(backend.identifier(self._take().value))
|
|
281
277
|
|
|
282
278
|
elif token.type == TokenType.LPAREN:
|
|
283
279
|
if self._previous().type == TokenType.NUMBER:
|
dissect/cstruct/lexer.py
CHANGED
|
@@ -143,6 +143,11 @@ def format_error_context(data: str, lineno: int, window: int = 1) -> str:
|
|
|
143
143
|
return "\n".join(f"{start + i + 1:>{no_len}}: {line}" for i, line in enumerate(context))
|
|
144
144
|
|
|
145
145
|
|
|
146
|
+
def join_tokens(tokens: list[Token]) -> str:
|
|
147
|
+
"""Join the values of the tokens with spaces, e.g. to evaluate them as an expression."""
|
|
148
|
+
return " ".join(token.value for token in tokens)
|
|
149
|
+
|
|
150
|
+
|
|
146
151
|
class Lexer:
|
|
147
152
|
"""Lexer compatible with C-like syntax for struct definitions and preprocessor directives."""
|
|
148
153
|
|
|
@@ -566,11 +571,11 @@ class TokenCursor:
|
|
|
566
571
|
raise self._error(f"expected {expected}, got {actual}")
|
|
567
572
|
return self._take()
|
|
568
573
|
|
|
569
|
-
def _collect_until(self, *terminators: TokenType) ->
|
|
570
|
-
"""Collect
|
|
574
|
+
def _collect_until(self, *terminators: TokenType) -> list[Token]:
|
|
575
|
+
"""Collect tokens until one of the terminators is reached, tracking nesting."""
|
|
571
576
|
terminators_set = set(terminators)
|
|
572
577
|
start = self._current()
|
|
573
|
-
|
|
578
|
+
tokens: list[Token] = []
|
|
574
579
|
depth = 0
|
|
575
580
|
|
|
576
581
|
while (token := self._current()).type != TokenType.EOF:
|
|
@@ -584,13 +589,13 @@ class TokenCursor:
|
|
|
584
589
|
if depth < 0:
|
|
585
590
|
raise self._error("unmatched closing bracket", token=token)
|
|
586
591
|
|
|
587
|
-
|
|
592
|
+
tokens.append(token)
|
|
588
593
|
self._pos += 1
|
|
589
594
|
|
|
590
595
|
if depth > 0:
|
|
591
596
|
raise self._error("unclosed opening bracket", token=start)
|
|
592
597
|
|
|
593
|
-
return
|
|
598
|
+
return tokens
|
|
594
599
|
|
|
595
600
|
def _error(self, msg: str, *, token: Token | None = None) -> Exception:
|
|
596
601
|
"""Subclasses should override to return an appropriate exception."""
|
dissect/cstruct/parser.py
CHANGED
|
@@ -9,9 +9,10 @@ from dissect.cstruct.exception import (
|
|
|
9
9
|
ExpressionParserError,
|
|
10
10
|
LexerError,
|
|
11
11
|
ParserError,
|
|
12
|
+
UnknownIdentifierError,
|
|
12
13
|
)
|
|
13
14
|
from dissect.cstruct.expression import Expression
|
|
14
|
-
from dissect.cstruct.lexer import IDENTIFIER_TYPES, TokenCursor, TokenType, format_error_context, tokenize
|
|
15
|
+
from dissect.cstruct.lexer import IDENTIFIER_TYPES, TokenCursor, TokenType, format_error_context, join_tokens, tokenize
|
|
15
16
|
from dissect.cstruct.types import BaseArray, BaseType, Field, Structure
|
|
16
17
|
|
|
17
18
|
if TYPE_CHECKING:
|
|
@@ -422,8 +423,13 @@ class CStyleParser(Parser):
|
|
|
422
423
|
member_name = self._expect(TokenType.IDENTIFIER).value
|
|
423
424
|
|
|
424
425
|
if self._match(TokenType.EQUALS):
|
|
425
|
-
|
|
426
|
-
|
|
426
|
+
if not (tokens := self._collect_until(TokenType.COMMA, TokenType.RBRACE)):
|
|
427
|
+
raise self._error("expected an expression")
|
|
428
|
+
|
|
429
|
+
try:
|
|
430
|
+
value = Expression(join_tokens(tokens)).evaluate(self.cs, values)
|
|
431
|
+
except ExpressionParserError as e:
|
|
432
|
+
raise self._error(str(e), token=tokens[0]) from None
|
|
427
433
|
else:
|
|
428
434
|
value = next_value
|
|
429
435
|
|
|
@@ -508,17 +514,21 @@ class CStyleParser(Parser):
|
|
|
508
514
|
dimensions: list[int | Expression] = []
|
|
509
515
|
|
|
510
516
|
while self._match(TokenType.LBRACKET):
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
517
|
+
tokens = self._collect_until(TokenType.RBRACKET)
|
|
518
|
+
self._expect(TokenType.RBRACKET)
|
|
519
|
+
|
|
520
|
+
count = None
|
|
521
|
+
if tokens:
|
|
522
|
+
count = Expression(join_tokens(tokens))
|
|
516
523
|
try:
|
|
517
524
|
count = count.evaluate(self.cs)
|
|
518
|
-
except
|
|
525
|
+
except UnknownIdentifierError:
|
|
526
|
+
# The size refers to a field, so it's evaluated when reading the structure
|
|
519
527
|
pass
|
|
520
|
-
|
|
521
|
-
|
|
528
|
+
except ExpressionParserError as e:
|
|
529
|
+
raise self._error(str(e), token=tokens[0]) from None
|
|
530
|
+
|
|
531
|
+
dimensions.append(count)
|
|
522
532
|
|
|
523
533
|
type_ = base_type
|
|
524
534
|
for count in reversed(dimensions):
|
|
@@ -535,7 +535,8 @@ class Structure(BaseType, metaclass=StructureMetaType):
|
|
|
535
535
|
|
|
536
536
|
@property
|
|
537
537
|
def __sizes__(self) -> Mapping[str, int | None]:
|
|
538
|
-
|
|
538
|
+
# Structures created from values instead of parsed have no dynamic sizes
|
|
539
|
+
return ChainMap(self.__class__.__static_sizes__, getattr(self, "__dynamic_sizes__", {}))
|
|
539
540
|
|
|
540
541
|
|
|
541
542
|
class StructureValuesProxy(MutableMapping):
|
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.
|
|
3
|
+
Version: 5.0.dev17
|
|
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
|
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
dissect/cstruct/__init__.py,sha256=
|
|
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/
|
|
6
|
-
dissect/cstruct/
|
|
7
|
-
dissect/cstruct/
|
|
8
|
-
dissect/cstruct/
|
|
9
|
-
dissect/cstruct/
|
|
5
|
+
dissect/cstruct/dump.py,sha256=4PS4h9R9bmDveYMFBdkM1Nw1_wZy0UUES1CDc4qxtrA,18774
|
|
6
|
+
dissect/cstruct/exception.py,sha256=box-mw6FoP6c3vndvYLcTeJCZVgIG8IQVPEAg4zW0C8,380
|
|
7
|
+
dissect/cstruct/expression.py,sha256=SbZRv7ueasYU4k-4k2eV1fjwL3JTAgF2UBaBvNjwiv4,10736
|
|
8
|
+
dissect/cstruct/lexer.py,sha256=N7eqCOlcaQriUUIswJv16i-CE_sahYXGO-YdFO0IKKY,20421
|
|
9
|
+
dissect/cstruct/parser.py,sha256=6PovhIbicENg3jBgopdArupmQNd-Ti7rd_te9au4z6U,22569
|
|
10
|
+
dissect/cstruct/util.py,sha256=wdHZL8HhjG8LnATAxpQd50PnUJDM6XBJ9r8WlDzX830,8373
|
|
10
11
|
dissect/cstruct/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
11
12
|
dissect/cstruct/tools/stubgen.py,sha256=MeZkLmSeNSLNcAEwlAdIGv1lKvlvK3UQ4WN85ovsxTM,7672
|
|
12
13
|
dissect/cstruct/types/__init__.py,sha256=6P71Pu94Dv7RNjZpDZ19pqzx-G0QzmQw4q0-3zWALso,911
|
|
@@ -18,13 +19,13 @@ dissect/cstruct/types/int.py,sha256=9RbdrkvAI28zATM97VVORQnras0XhLaVMtdPjJwpTH4,
|
|
|
18
19
|
dissect/cstruct/types/leb128.py,sha256=V97XTJT_Xbw1LpTwTN1OkjPHuQQAQUxd8OGuA6yEDmE,2387
|
|
19
20
|
dissect/cstruct/types/packed.py,sha256=NgCX0YWX8SH8z47atq0f39w9MBjU_eBFJtUisUWdO-M,3867
|
|
20
21
|
dissect/cstruct/types/pointer.py,sha256=FNuB9bfENWRebbKX-R6Vs6xWPMHepjvOhhomeUhr7I8,3985
|
|
21
|
-
dissect/cstruct/types/structure.py,sha256=
|
|
22
|
+
dissect/cstruct/types/structure.py,sha256=oY0Gx3b4wc9p74WgZjp38OnC2il_T9LLuBJaOBNbFVg,39655
|
|
22
23
|
dissect/cstruct/types/void.py,sha256=fV4hKk50uop_EKbR1nfy1cdtAzvUYrSymXsdakCyFk8,1222
|
|
23
24
|
dissect/cstruct/types/wchar.py,sha256=VrnPXsP_lsyA-1xr4D2aSIVijumMhUuZWNlDHcn12-s,3964
|
|
24
|
-
dissect_cstruct-5.0.
|
|
25
|
-
dissect_cstruct-5.0.
|
|
26
|
-
dissect_cstruct-5.0.
|
|
27
|
-
dissect_cstruct-5.0.
|
|
28
|
-
dissect_cstruct-5.0.
|
|
29
|
-
dissect_cstruct-5.0.
|
|
30
|
-
dissect_cstruct-5.0.
|
|
25
|
+
dissect_cstruct-5.0.dev17.dist-info/licenses/COPYRIGHT,sha256=H-18RXfshdH9AdHwW2eO1Xa-5s6tY5eipHh5c0whDu4,316
|
|
26
|
+
dissect_cstruct-5.0.dev17.dist-info/licenses/LICENSE,sha256=PhUqiw6jAh2KbBdVRPBq_hfAvfcTBin7nZ3CK7NQbTM,11341
|
|
27
|
+
dissect_cstruct-5.0.dev17.dist-info/METADATA,sha256=ImSng8tdv9I4QBU9NCE9cEPLeM6Z5DilPE5im_YmEyg,9256
|
|
28
|
+
dissect_cstruct-5.0.dev17.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
29
|
+
dissect_cstruct-5.0.dev17.dist-info/entry_points.txt,sha256=z53zqZqwD2OLrAkRwrP4wTeiU9CQe7xrMly0T2c0_wQ,71
|
|
30
|
+
dissect_cstruct-5.0.dev17.dist-info/top_level.txt,sha256=Mn-CQzEYsAbkxrUI0TnplHuXnGVKzxpDw_po_sXpvv4,8
|
|
31
|
+
dissect_cstruct-5.0.dev17.dist-info/RECORD,,
|
|
File without changes
|
{dissect_cstruct-5.0.dev15.dist-info → dissect_cstruct-5.0.dev17.dist-info}/entry_points.txt
RENAMED
|
File without changes
|
{dissect_cstruct-5.0.dev15.dist-info → dissect_cstruct-5.0.dev17.dist-info}/licenses/COPYRIGHT
RENAMED
|
File without changes
|
{dissect_cstruct-5.0.dev15.dist-info → dissect_cstruct-5.0.dev17.dist-info}/licenses/LICENSE
RENAMED
|
File without changes
|
|
File without changes
|