dissect.cstruct 5.0.dev15__tar.gz → 5.0.dev17__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 (86) hide show
  1. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/CHANGELOG.md +3 -0
  2. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/PKG-INFO +1 -1
  3. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect/cstruct/__init__.py +1 -2
  4. dissect_cstruct-5.0.dev17/dissect/cstruct/dump.py +509 -0
  5. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect/cstruct/exception.py +4 -0
  6. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect/cstruct/expression.py +14 -18
  7. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect/cstruct/lexer.py +10 -5
  8. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect/cstruct/parser.py +21 -11
  9. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect/cstruct/types/structure.py +2 -1
  10. dissect_cstruct-5.0.dev17/dissect/cstruct/util.py +287 -0
  11. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect.cstruct.egg-info/PKG-INFO +1 -1
  12. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect.cstruct.egg-info/SOURCES.txt +4 -2
  13. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect.cstruct.egg-info/scm_file_list.json +4 -2
  14. dissect_cstruct-5.0.dev17/dissect.cstruct.egg-info/scm_version.json +8 -0
  15. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/examples/disk.py +46 -34
  16. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/examples/mirai.py +7 -2
  17. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/examples/pe.py +31 -26
  18. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/examples/protobuf.py +4 -0
  19. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/examples/secdesc.py +29 -28
  20. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_align.py +1 -1
  21. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_basic.py +1 -2
  22. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_bitfield.py +1 -2
  23. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_compiler.py +3 -4
  24. dissect_cstruct-5.0.dev17/tests/test_dump.py +1052 -0
  25. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_expression.py +9 -9
  26. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_parser.py +73 -1
  27. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_types_base.py +1 -2
  28. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_types_char.py +1 -2
  29. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_types_enum.py +1 -1
  30. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_types_flag.py +1 -2
  31. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_types_int.py +1 -1
  32. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_types_packed.py +1 -1
  33. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_types_pointer.py +1 -2
  34. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_types_structure.py +5 -2
  35. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_types_union.py +1 -2
  36. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_types_void.py +1 -1
  37. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_types_wchar.py +1 -2
  38. dissect_cstruct-5.0.dev17/tests/test_util.py +102 -0
  39. dissect_cstruct-5.0.dev15/dissect/cstruct/util.py +0 -592
  40. dissect_cstruct-5.0.dev15/dissect.cstruct.egg-info/scm_version.json +0 -8
  41. dissect_cstruct-5.0.dev15/tests/test_utils.py +0 -351
  42. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/.git-blame-ignore-revs +0 -0
  43. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/.gitattributes +0 -0
  44. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/COPYRIGHT +0 -0
  45. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/LICENSE +0 -0
  46. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/MANIFEST.in +0 -0
  47. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/README.md +0 -0
  48. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect/cstruct/bitbuffer.py +0 -0
  49. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect/cstruct/compiler.py +0 -0
  50. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect/cstruct/cstruct.py +0 -0
  51. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect/cstruct/tools/__init__.py +0 -0
  52. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect/cstruct/tools/stubgen.py +0 -0
  53. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect/cstruct/types/__init__.py +0 -0
  54. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect/cstruct/types/base.py +0 -0
  55. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect/cstruct/types/char.py +0 -0
  56. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect/cstruct/types/enum.py +0 -0
  57. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect/cstruct/types/flag.py +0 -0
  58. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect/cstruct/types/int.py +0 -0
  59. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect/cstruct/types/leb128.py +0 -0
  60. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect/cstruct/types/packed.py +0 -0
  61. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect/cstruct/types/pointer.py +0 -0
  62. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect/cstruct/types/void.py +0 -0
  63. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect/cstruct/types/wchar.py +0 -0
  64. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect.cstruct.egg-info/dependency_links.txt +0 -0
  65. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect.cstruct.egg-info/entry_points.txt +0 -0
  66. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect.cstruct.egg-info/requires.txt +0 -0
  67. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/dissect.cstruct.egg-info/top_level.txt +0 -0
  68. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/pyproject.toml +0 -0
  69. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/setup.cfg +0 -0
  70. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/__init__.py +0 -0
  71. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/_data/testdef.txt +0 -0
  72. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/_docs/Makefile +0 -0
  73. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/_docs/__init__.py +0 -0
  74. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/_docs/conf.py +0 -0
  75. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/_docs/index.rst +0 -0
  76. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/conftest.py +0 -0
  77. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_annotations.py +0 -0
  78. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_benchmark.py +0 -0
  79. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_bitbuffer.py +0 -0
  80. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_ctypes.py +0 -0
  81. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_lexer.py +0 -0
  82. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_tools_stubgen.py +0 -0
  83. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_types_custom.py +0 -0
  84. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tests/test_types_leb128.py +0 -0
  85. /dissect_cstruct-5.0.dev15/tests/utils.py → /dissect_cstruct-5.0.dev17/tests/util.py +0 -0
  86. {dissect_cstruct-5.0.dev15 → dissect_cstruct-5.0.dev17}/tox.ini +0 -0
@@ -24,9 +24,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
24
24
  - Improve writing performance:
25
25
  - The compiler now generates code for writing structures and unions too! It uses a similar approach, grouping fields and writes where possible.
26
26
  - `obj.dumps()` and `obj.write()` no longer create a `functools.partial` on every access. As a result, they no longer accept a `value` argument.
27
+ - `dumpstruct` can return a tree of all fields with their offset, size and value, with `output="dict"` or `output="json"`. `dumpstruct` and `hexdump` moved from `dissect.cstruct.util` to `dissect.cstruct.dump`.
28
+ - `dumpstruct` shows the fields of every element of an array of structures or unions.
27
29
 
28
30
  ### Fixed
29
31
 
32
+ - `dumpstruct` colors the right bytes of structures with padding and unions.
30
33
  - Structures and unions no longer share nested structures and arrays between their default values.
31
34
  - Unions can be created with default values and read if they have doubly nested structures or nested unions.
32
35
  - Writing a `bytearray` to a `char` array no longer modifies the `bytearray`.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dissect.cstruct
3
- Version: 5.0.dev15
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
@@ -2,6 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  from dissect.cstruct.bitbuffer import BitBuffer
4
4
  from dissect.cstruct.cstruct import cstruct, ctypes, ctypes_type
5
+ from dissect.cstruct.dump import dumpstruct, hexdump
5
6
  from dissect.cstruct.exception import (
6
7
  Error,
7
8
  NullPointerDereference,
@@ -29,11 +30,9 @@ from dissect.cstruct.types import (
29
30
  WcharArray,
30
31
  )
31
32
  from dissect.cstruct.util import (
32
- dumpstruct,
33
33
  f16,
34
34
  f32,
35
35
  f64,
36
- hexdump,
37
36
  p8,
38
37
  p16,
39
38
  p32,
@@ -0,0 +1,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}"
@@ -27,3 +27,7 @@ class ArraySizeError(Error):
27
27
 
28
28
  class ExpressionParserError(Error):
29
29
  pass
30
+
31
+
32
+ class UnknownIdentifierError(ExpressionParserError):
33
+ pass
@@ -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 _error(msg: str, line: int) -> ExpressionParserError:
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 _error(f"Unknown identifier: '{ident}'", line)
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 _error(f"Unknown identifier: '{ident}'", line)
106
+ raise UnknownIdentifierError(f"Unknown identifier: '{ident}'")
111
107
 
112
108
  try:
113
109
  return int(obj)
114
110
  except (ValueError, TypeError):
115
- raise _error(f"Identifier '{ident}' does not resolve to an integer", line)
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, token: Token) -> int:
133
- return _identifier(self.cs, self.context, ident, token.line)
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, token: Token) -> 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}, {token.line})"
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 _error(msg, (token if token is not None else self._current()).line)
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, token))
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: