dissect.cstruct 5.0.dev14__tar.gz → 5.0.dev16__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 (82) hide show
  1. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/PKG-INFO +1 -1
  2. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect/cstruct/exception.py +4 -0
  3. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect/cstruct/expression.py +14 -18
  4. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect/cstruct/lexer.py +33 -15
  5. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect/cstruct/parser.py +56 -30
  6. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect.cstruct.egg-info/PKG-INFO +1 -1
  7. dissect_cstruct-5.0.dev16/dissect.cstruct.egg-info/scm_version.json +8 -0
  8. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_compiler.py +2 -2
  9. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_expression.py +9 -9
  10. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_lexer.py +8 -8
  11. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_parser.py +196 -16
  12. dissect_cstruct-5.0.dev14/dissect.cstruct.egg-info/scm_version.json +0 -8
  13. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/.git-blame-ignore-revs +0 -0
  14. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/.gitattributes +0 -0
  15. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/CHANGELOG.md +0 -0
  16. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/COPYRIGHT +0 -0
  17. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/LICENSE +0 -0
  18. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/MANIFEST.in +0 -0
  19. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/README.md +0 -0
  20. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect/cstruct/__init__.py +0 -0
  21. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect/cstruct/bitbuffer.py +0 -0
  22. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect/cstruct/compiler.py +0 -0
  23. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect/cstruct/cstruct.py +0 -0
  24. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect/cstruct/tools/__init__.py +0 -0
  25. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect/cstruct/tools/stubgen.py +0 -0
  26. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect/cstruct/types/__init__.py +0 -0
  27. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect/cstruct/types/base.py +0 -0
  28. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect/cstruct/types/char.py +0 -0
  29. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect/cstruct/types/enum.py +0 -0
  30. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect/cstruct/types/flag.py +0 -0
  31. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect/cstruct/types/int.py +0 -0
  32. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect/cstruct/types/leb128.py +0 -0
  33. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect/cstruct/types/packed.py +0 -0
  34. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect/cstruct/types/pointer.py +0 -0
  35. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect/cstruct/types/structure.py +0 -0
  36. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect/cstruct/types/void.py +0 -0
  37. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect/cstruct/types/wchar.py +0 -0
  38. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect/cstruct/util.py +0 -0
  39. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect.cstruct.egg-info/SOURCES.txt +0 -0
  40. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect.cstruct.egg-info/dependency_links.txt +0 -0
  41. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect.cstruct.egg-info/entry_points.txt +0 -0
  42. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect.cstruct.egg-info/requires.txt +0 -0
  43. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect.cstruct.egg-info/scm_file_list.json +0 -0
  44. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/dissect.cstruct.egg-info/top_level.txt +0 -0
  45. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/examples/disk.py +0 -0
  46. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/examples/mirai.py +0 -0
  47. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/examples/pe.py +0 -0
  48. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/examples/protobuf.py +0 -0
  49. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/examples/secdesc.py +0 -0
  50. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/pyproject.toml +0 -0
  51. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/setup.cfg +0 -0
  52. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/__init__.py +0 -0
  53. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/_data/testdef.txt +0 -0
  54. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/_docs/Makefile +0 -0
  55. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/_docs/__init__.py +0 -0
  56. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/_docs/conf.py +0 -0
  57. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/_docs/index.rst +0 -0
  58. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/conftest.py +0 -0
  59. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_align.py +0 -0
  60. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_annotations.py +0 -0
  61. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_basic.py +0 -0
  62. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_benchmark.py +0 -0
  63. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_bitbuffer.py +0 -0
  64. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_bitfield.py +0 -0
  65. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_ctypes.py +0 -0
  66. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_tools_stubgen.py +0 -0
  67. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_types_base.py +0 -0
  68. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_types_char.py +0 -0
  69. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_types_custom.py +0 -0
  70. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_types_enum.py +0 -0
  71. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_types_flag.py +0 -0
  72. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_types_int.py +0 -0
  73. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_types_leb128.py +0 -0
  74. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_types_packed.py +0 -0
  75. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_types_pointer.py +0 -0
  76. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_types_structure.py +0 -0
  77. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_types_union.py +0 -0
  78. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_types_void.py +0 -0
  79. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_types_wchar.py +0 -0
  80. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/test_utils.py +0 -0
  81. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tests/utils.py +0 -0
  82. {dissect_cstruct-5.0.dev14 → dissect_cstruct-5.0.dev16}/tox.ini +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dissect.cstruct
3
- Version: 5.0.dev14
3
+ Version: 5.0.dev16
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
@@ -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:
@@ -125,6 +125,7 @@ _SINGLE_CHARS = {
125
125
 
126
126
  _RE_IDENTIFIER = re.compile(r"[a-zA-Z_.][a-zA-Z0-9_.]*")
127
127
  _RE_WHITESPACE = re.compile(r"[ \t\r\n]+")
128
+ _RE_DEFINE_LITERAL = re.compile(r"""(["'])(?:\\.|(?!\1)[^\\\n])*\1""")
128
129
 
129
130
  IDENTIFIER_TYPES = set(_C_KEYWORDS.values()) | {TokenType.IDENTIFIER}
130
131
 
@@ -142,6 +143,11 @@ def format_error_context(data: str, lineno: int, window: int = 1) -> str:
142
143
  return "\n".join(f"{start + i + 1:>{no_len}}: {line}" for i, line in enumerate(context))
143
144
 
144
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
+
145
151
  class Lexer:
146
152
  """Lexer compatible with C-like syntax for struct definitions and preprocessor directives."""
147
153
 
@@ -292,10 +298,10 @@ class Lexer:
292
298
  if peek == "*":
293
299
  self._take(2) # Consume /*
294
300
  end = self.data.find("*/", self._pos)
295
- if end != -1:
296
- self._take(end - self._pos + 2)
297
- else:
298
- self._take(len(self.data) - self._pos)
301
+ if end == -1:
302
+ raise self._error("unterminated comment")
303
+
304
+ self._take(end - self._pos + 2)
299
305
 
300
306
  elif peek == "/":
301
307
  self._take(2) # Consume //
@@ -390,6 +396,23 @@ class Lexer:
390
396
 
391
397
  return result
392
398
 
399
+ def _read_define_value(self) -> str:
400
+ """Read the value of a ``#define`` up to the end of the line."""
401
+ value = []
402
+
403
+ while not self.eof and (ch := self._current()) != "\n":
404
+ if ch == "/" and self._peek() in ("/", "*"):
405
+ self._skip_comment()
406
+ value.append(" ")
407
+ elif ch in ('"', "'"):
408
+ if not (match := _RE_DEFINE_LITERAL.match(self.data, self._pos)):
409
+ raise self._error("unterminated string literal")
410
+ value.append(self._take(match.end() - self._pos))
411
+ else:
412
+ value.append(self._read_until("\n\"'/") or self._take())
413
+
414
+ return "".join(value).strip()
415
+
393
416
  def _read_preprocessor(self) -> None:
394
417
  """Read a preprocessor directive starting with ``#``."""
395
418
  line = self._line
@@ -423,12 +446,7 @@ class Lexer:
423
446
  raise self._error("expected identifier after '#define'", lineno=line)
424
447
  self._emit(TokenType.IDENTIFIER, name, line)
425
448
 
426
- self._skip_whitespace_and_comments()
427
- if self.eof or self._line != line:
428
- # No value, just a simple macro definition
429
- return
430
-
431
- if (value := self._read_until("\n")).strip():
449
+ if value := self._read_define_value():
432
450
  self._emit(TokenType.STRING, value, line)
433
451
 
434
452
  elif token_type == TokenType.PP_INCLUDE:
@@ -553,11 +571,11 @@ class TokenCursor:
553
571
  raise self._error(f"expected {expected}, got {actual}")
554
572
  return self._take()
555
573
 
556
- def _collect_until(self, *terminators: TokenType) -> str:
557
- """Collect token values until one of the terminators is reached, tracking nesting."""
574
+ def _collect_until(self, *terminators: TokenType) -> list[Token]:
575
+ """Collect tokens until one of the terminators is reached, tracking nesting."""
558
576
  terminators_set = set(terminators)
559
577
  start = self._current()
560
- parts: list[str] = []
578
+ tokens: list[Token] = []
561
579
  depth = 0
562
580
 
563
581
  while (token := self._current()).type != TokenType.EOF:
@@ -571,13 +589,13 @@ class TokenCursor:
571
589
  if depth < 0:
572
590
  raise self._error("unmatched closing bracket", token=token)
573
591
 
574
- parts.append(token.value)
592
+ tokens.append(token)
575
593
  self._pos += 1
576
594
 
577
595
  if depth > 0:
578
596
  raise self._error("unclosed opening bracket", token=start)
579
597
 
580
- return " ".join(parts)
598
+ return tokens
581
599
 
582
600
  def _error(self, msg: str, *, token: Token | None = None) -> Exception:
583
601
  """Subclasses should override to return an appropriate exception."""
@@ -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:
@@ -20,6 +21,10 @@ if TYPE_CHECKING:
20
21
  from dissect.cstruct.types import BaseType, Enum, Flag
21
22
 
22
23
 
24
+ # A string or the name of a constant in the value of a define
25
+ _RE_DEFINE_STRING = re.compile(r"""\s*(?:([bB]?)(["'])((?:\\.|(?!\2)[^\\\n])*)\2|([a-zA-Z_.][a-zA-Z0-9_.]*))""")
26
+
27
+
23
28
  class Parser(TokenCursor):
24
29
  """Base class for definition parsers.
25
30
 
@@ -42,7 +47,7 @@ class Parser(TokenCursor):
42
47
 
43
48
  def _join_line_continuations(string: str) -> str:
44
49
  # Join lines ending with backslash
45
- return re.sub(r"\\\n", "", string)
50
+ return re.sub(r"\\\r?\n", "", string)
46
51
 
47
52
 
48
53
  class CStyleParser(Parser):
@@ -138,11 +143,16 @@ class CStyleParser(Parser):
138
143
  elif token.type == TokenType.TYPEDEF:
139
144
  self._parse_typedef()
140
145
  elif token.type in (TokenType.STRUCT, TokenType.UNION):
141
- self._parse_struct_or_union()
146
+ type_ = self._parse_struct_or_union()
142
147
 
143
148
  # Skip variable declarations after struct/union definitions
144
- while not self._at(TokenType.SEMICOLON, TokenType.EOF):
145
- self._pos += 1
149
+ has_variable = self._at(TokenType.IDENTIFIER, TokenType.STAR)
150
+ while has_variable:
151
+ _, _, bits = self._parse_field_name(type_)
152
+ if bits is not None:
153
+ raise self._error("variables cannot have bitfields")
154
+
155
+ has_variable = self._match(TokenType.COMMA)
146
156
 
147
157
  self._expect(TokenType.SEMICOLON)
148
158
  elif token.type in (TokenType.ENUM, TokenType.FLAG):
@@ -174,21 +184,28 @@ class CStyleParser(Parser):
174
184
  value = self._take().value
175
185
 
176
186
  if value:
177
- if value[0] in ('"', "'"):
178
- quote = value[0]
179
- if value[-1] != quote:
180
- raise self._error("unterminated string literal", token=token)
181
-
182
- # Remove the surrounding quotes and flatten escape sequences
183
- value = value[1:-1].encode().decode("unicode_escape")
184
- elif value[:2].lower() in ("b'", 'b"'):
185
- quote = value[1]
186
- if value[-1] != quote:
187
- raise self._error("unterminated bytes literal", token=token)
188
-
189
- # Remove the leading b and surrounding quotes and flatten escape sequences
190
- value = value[2:-1].encode().decode("unicode_escape")
191
- value = ast.literal_eval(f"b{value!r}")
187
+ # Adjacent strings and constants that are strings are concatenated like in C
188
+ strings = []
189
+ pos = 0
190
+ if '"' in value or "'" in value:
191
+ while pos < len(value) and (match := _RE_DEFINE_STRING.match(value, pos)):
192
+ is_bytes, _, string, name = match.groups()
193
+ if name is None:
194
+ # Flatten escape sequences
195
+ string = string.encode().decode("unicode_escape")
196
+ strings.append(string.encode("latin-1") if is_bytes else string)
197
+ elif isinstance(constant := self.cs.consts.get(name), (str, bytes)):
198
+ strings.append(constant)
199
+ else:
200
+ break
201
+
202
+ pos = match.end()
203
+
204
+ if strings and pos == len(value):
205
+ try:
206
+ value = strings[0][:0].join(strings)
207
+ except TypeError:
208
+ raise self._error("cannot concatenate strings and bytes", token=token) from None
192
209
  else:
193
210
  try:
194
211
  # Lazy mode, try to evaluate as a Python literal first (for simple constants)
@@ -406,8 +423,13 @@ class CStyleParser(Parser):
406
423
  member_name = self._expect(TokenType.IDENTIFIER).value
407
424
 
408
425
  if self._match(TokenType.EQUALS):
409
- expression = self._collect_until(TokenType.COMMA, TokenType.RBRACE)
410
- value = Expression(expression).evaluate(self.cs, values)
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
411
433
  else:
412
434
  value = next_value
413
435
 
@@ -492,17 +514,21 @@ class CStyleParser(Parser):
492
514
  dimensions: list[int | Expression] = []
493
515
 
494
516
  while self._match(TokenType.LBRACKET):
495
- if self._at(TokenType.RBRACKET):
496
- dimensions.append(None)
497
- else:
498
- expression = self._collect_until(TokenType.RBRACKET)
499
- count = Expression(expression)
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))
500
523
  try:
501
524
  count = count.evaluate(self.cs)
502
- except Exception:
525
+ except UnknownIdentifierError:
526
+ # The size refers to a field, so it's evaluated when reading the structure
503
527
  pass
504
- dimensions.append(count)
505
- self._expect(TokenType.RBRACKET)
528
+ except ExpressionParserError as e:
529
+ raise self._error(str(e), token=tokens[0]) from None
530
+
531
+ dimensions.append(count)
506
532
 
507
533
  type_ = base_type
508
534
  for count in reversed(dimensions):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dissect.cstruct
3
- Version: 5.0.dev14
3
+ Version: 5.0.dev16
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
@@ -0,0 +1,8 @@
1
+ {
2
+ "tag": "5.0.dev0",
3
+ "distance": 16,
4
+ "node": "g0db75358d539974dba35bcabd13547e90c179370",
5
+ "dirty": true,
6
+ "branch": "main",
7
+ "node_date": "2026-11-05"
8
+ }
@@ -423,11 +423,11 @@ def test_compiled_dynamic_array_sizes() -> None:
423
423
  assert [line for line in lines if line.startswith("_count = ") or "._read" in line] == [
424
424
  "_count = max(0, int(_value0))",
425
425
  "_value3 = values['a'] = _type_call(_type3, _type4._read_array(stream, _count, context=values, endian=endian))",
426
- "_count = max(0, (int(_value0) - _identifier(cs, values, 'HDR', 1)))",
426
+ "_count = max(0, (int(_value0) - _identifier(cs, values, 'HDR')))",
427
427
  "_value4 = values['b'] = _type_call(_type5, _type6._read_array(stream, _count, context=values, endian=endian))",
428
428
  "_count = max(0, (int(_value1) * 2))",
429
429
  "_value5 = values['c'] = _type_call(_type7, _type8._read_array(stream, _count, context=values, endian=endian))",
430
- "_count = max(0, _identifier(cs, values, 'hdr.size', 1))",
430
+ "_count = max(0, _identifier(cs, values, 'hdr.size'))",
431
431
  "_value6 = values['d'] = _type_call(_type9, _type0._read_array(stream, _count, context=values, endian=endian))",
432
432
  "_count = max(0, (int(_value0) + _sizeof(cs, 'inner')))",
433
433
  "_value7 = values['e'] = _type_call(_type10, _type2._read_array("
@@ -4,7 +4,7 @@ from typing import TYPE_CHECKING, Any
4
4
 
5
5
  import pytest
6
6
 
7
- from dissect.cstruct.exception import ExpressionParserError, LexerError, ResolveError
7
+ from dissect.cstruct.exception import ExpressionParserError, LexerError, ResolveError, UnknownIdentifierError
8
8
  from dissect.cstruct.expression import SOURCE_GLOBALS, Expression
9
9
 
10
10
  if TYPE_CHECKING:
@@ -174,13 +174,13 @@ def test_expression(cs_with_consts: cstruct, expression: str, answer: int) -> No
174
174
  ),
175
175
  pytest.param(
176
176
  "UNKNOWN",
177
- ExpressionParserError,
177
+ UnknownIdentifierError,
178
178
  "Unknown identifier: 'UNKNOWN'",
179
179
  id="unknown-identifier",
180
180
  ),
181
181
  pytest.param(
182
182
  "UNKNOWN.UNKNOWN",
183
- ExpressionParserError,
183
+ UnknownIdentifierError,
184
184
  "Unknown identifier: 'UNKNOWN.UNKNOWN'",
185
185
  id="unknown-identifier",
186
186
  ),
@@ -261,7 +261,7 @@ def test_dotted_identifier_unknown_member(cs: cstruct) -> None:
261
261
  };
262
262
  """)
263
263
 
264
- with pytest.raises(ExpressionParserError, match="Unknown identifier: 'color\\.NOTAMEMBER'"):
264
+ with pytest.raises(UnknownIdentifierError, match="Unknown identifier: 'color\\.NOTAMEMBER'"):
265
265
  Expression("color.NOTAMEMBER").evaluate(cs)
266
266
 
267
267
 
@@ -354,9 +354,9 @@ def test_expression_source_invalid(cs: cstruct, source: str) -> None:
354
354
  # Numbers in other bases
355
355
  ("0x10 + 0b101 - 0o7", "((16 + 5) - 7)"),
356
356
  # Functions, and identifiers that are resolved from the context
357
- ("sizeof(test) * X - -1", "((_sizeof(cs, 'test') * _identifier(cs, context, 'X', 1)) - (-1))"),
357
+ ("sizeof(test) * X - -1", "((_sizeof(cs, 'test') * _identifier(cs, context, 'X')) - (-1))"),
358
358
  ("offsetof(test, b) + a", "(_offsetof(cs, 'test', 'b') + a)"),
359
- ("hdr.size * 4", "(_identifier(cs, context, 'hdr.size', 1) * 4)"),
359
+ ("hdr.size * 4", "(_identifier(cs, context, 'hdr.size') * 4)"),
360
360
  ],
361
361
  )
362
362
  def test_expression_source_code(cs: cstruct, expression: str, source: str) -> None:
@@ -380,6 +380,6 @@ def test_expression_source_code(cs: cstruct, expression: str, source: str) -> No
380
380
 
381
381
 
382
382
  def test_expression_source_context() -> None:
383
- """Test that identifiers are resolved from the context with the given name, with their line number."""
384
- expected = "(_identifier(cs, values, 'X', 1) + _identifier(cs, values, 'b', 2))"
385
- assert Expression("X +\nb").source(context="values") == expected
383
+ """Test that identifiers are resolved from the context with the given name."""
384
+ expected = "(_identifier(cs, values, 'X') + _identifier(cs, values, 'b'))"
385
+ assert Expression("X + b").source(context="values") == expected
@@ -90,14 +90,6 @@ from dissect.cstruct.lexer import TokenType, tokenize
90
90
  [TokenType.PP_DEFINE, TokenType.IDENTIFIER, TokenType.STRING],
91
91
  ["define", "FOO", "ADCRYPT\00"],
92
92
  ),
93
- (
94
- """
95
- #define FOO (1 \
96
- + 2)
97
- """,
98
- [TokenType.PP_DEFINE, TokenType.IDENTIFIER, TokenType.STRING],
99
- ["define", "FOO", "(1 + 2)"],
100
- ),
101
93
  ("#undef", [TokenType.PP_UNDEF], ["undef"]),
102
94
  ("#ifdef", [TokenType.PP_IFDEF], ["ifdef"]),
103
95
  ("#ifndef", [TokenType.PP_IFNDEF], ["ifndef"]),
@@ -174,6 +166,14 @@ def test_token(src: str, types: list[TokenType], values: list[str]) -> None:
174
166
  ("#include", "unexpected end of input"),
175
167
  ("#include <missing_end", "unexpected end of input"),
176
168
  ('#include "missing_end', "unexpected end of input"),
169
+ ('#define A "x\ny"\n#define B 2\n', "line 1: unterminated string literal"),
170
+ ('#define A "x\n#define B "y"\n', "line 1: unterminated string literal"),
171
+ ('#define A "x', "line 1: unterminated string literal"),
172
+ ("#define A 'x\n", "line 1: unterminated string literal"),
173
+ ("#define A it's\n", "line 1: unterminated string literal"),
174
+ ("/* unterminated", "line 1: unterminated comment"),
175
+ ("struct a {\n uint8 b; /* c\n};\n", "line 2: unterminated comment"),
176
+ ("#define A 1 /* c\n#define B 2\n", "line 1: unterminated comment"),
177
177
  ("@", "unexpected character"),
178
178
  ("`", "unexpected character"),
179
179
  ],
@@ -41,6 +41,65 @@ def test_struct(cs: cstruct, compiled: bool) -> None:
41
41
  cs.resolve(name)
42
42
 
43
43
 
44
+ def test_struct_variables(cs: cstruct) -> None:
45
+ """Test that all forms of variable declarations after a struct or union definition are silently ignored."""
46
+ cdef = """
47
+ #define SIZE 2
48
+
49
+ struct test {
50
+ uint8 a;
51
+ } b[4], *c[SIZE], d[2][3], e[];
52
+
53
+ union test1 {
54
+ uint8 a;
55
+ } f;
56
+
57
+ struct test g, *h;
58
+
59
+ typedef uint8 test2;
60
+ """
61
+ cs.load(cdef)
62
+
63
+ assert cs.resolve("test") is cs.test
64
+ assert cs.resolve("test1") is cs.test1
65
+ assert cs.resolve("test2") is cs.uint8
66
+
67
+ for name in ("b", "c", "d", "e", "f", "g", "h"):
68
+ with pytest.raises(ResolveError, match=f"Unknown type {name}"):
69
+ cs.resolve(name)
70
+
71
+
72
+ @pytest.mark.parametrize(
73
+ ("cdef", "match"),
74
+ [
75
+ # A missing semicolon before the next definition
76
+ ("struct a { uint8 x; }\nstruct b { uint8 x; };", "line 2: expected ;, got struct"),
77
+ ("struct a { uint8 x; }\nunion b { uint8 x; };", "line 2: expected ;, got union"),
78
+ ("struct a { uint8 x; }\nenum b : uint8 { C };", "line 2: expected ;, got enum"),
79
+ ("struct a { uint8 x; }\nflag b : uint8 { C };", "line 2: expected ;, got flag"),
80
+ ("struct a { uint8 x; }\ntypedef uint8 b;", "line 2: expected ;, got typedef"),
81
+ ("struct a { uint8 x; }\n#define B 1", "line 2: expected ;, got define"),
82
+ ("struct a { uint8 x; }\n#[nocompile]\nstruct b { uint8 x; };", "line 2: expected ;, got nocompile"),
83
+ ("union a { uint8 x; }\ntypedef uint8 b;", "line 2: expected ;, got typedef"),
84
+ ("struct a { uint8 x; } b\ntypedef uint8 c;", "line 2: expected ;, got typedef"),
85
+ ("struct a { uint8 x; }", "line 1: expected ;, got end of input"),
86
+ ("struct a { uint8 x; } b", "line 1: expected ;, got end of input"),
87
+ # Invalid variable declarations
88
+ ("struct a { uint8 x; } b c;", "line 1: expected ;, got c"),
89
+ ("struct a { uint8 x; } 1;", "line 1: expected ;, got 1"),
90
+ ("struct a { uint8 x; } , b;", "line 1: expected ;, got ,"),
91
+ ("struct a { uint8 x; } b,;", "line 1: expected one of .*, got ;"),
92
+ ("struct a { uint8 x; } *;", "line 1: expected one of .*, got ;"),
93
+ ("struct a { uint8 x; } b[2;", "line 1: expected ], got end of input"),
94
+ ("struct a { uint8 x; } b : 4;", "line 1: variables cannot have bitfields"),
95
+ ],
96
+ )
97
+ def test_struct_invalid_variables(cs: cstruct, cdef: str, match: str) -> None:
98
+ """Test that nothing other than variable declarations and a semicolon can follow a struct or union definition."""
99
+ with pytest.raises(ParserError, match=match):
100
+ cs.load(cdef)
101
+
102
+
44
103
  def test_nested_structs(cs: cstruct, compiled: bool) -> None:
45
104
  """Test parsing of nested structs, including anonymous ones."""
46
105
  cdef = """
@@ -248,14 +307,18 @@ def test_define(cs: cstruct) -> None:
248
307
  #define NULLSTR "ADCRYPT\00"
249
308
  #define NULLBYTES b"ADCRYPT\00"
250
309
  #define ARBITRARYBYTES b"\x00\x01\x02"
251
- #define MULTILINE (1 + \
252
- 2 + \
310
+ #define MULTILINE (1 + \\
311
+ 2 + \\
253
312
  3)
254
- #define QUOTES "\'\"a'b\""
313
+ #define QUOTES "'\\"a'b\\""
255
314
  #define ESCAPE "\\'\\"a'b\\"\\n"
256
315
  #define BYTES_ESCAPE b"`\\n"
257
316
  #define FUNC(x) ( x == 0 )
258
317
  #define TERNARY(x) ( x ? 1 : 0 )
318
+ #define STR_CONCAT "say " STR
319
+ #define BYTES_CONCAT BYTES b"!"
320
+ #define STR_AND_NUMBER "a" CONST
321
+ #define RAW_AND_RAW RAW RAW
259
322
  """
260
323
  cs.load(cdef)
261
324
 
@@ -275,6 +338,16 @@ def test_define(cs: cstruct) -> None:
275
338
  # We don't evaluate function-like macros yet, so they should be stored as their raw string representation
276
339
  assert cs.consts["FUNC"] == "(x) ( x == 0 )"
277
340
  assert cs.consts["TERNARY"] == "(x) ( x ? 1 : 0 )"
341
+ # Adjacent strings and constants that are strings are concatenated like in C
342
+ assert cs.consts["STR_CONCAT"] == "say hello"
343
+ assert cs.consts["BYTES_CONCAT"] == b"world!"
344
+ # A constant that isn't a string can't be concatenated, so the value is kept as it is
345
+ assert cs.consts["STR_AND_NUMBER"] == '"a" CONST'
346
+ # Without a string in the value we don't know whether these are strings, they could also just be raw values
347
+ assert cs.consts["RAW_AND_RAW"] == "RAW RAW"
348
+
349
+ with pytest.raises(ParserError, match="line 1: cannot concatenate strings and bytes"):
350
+ cs.load('#define MIXED "a" b"b"')
278
351
 
279
352
 
280
353
  def test_define_flag_value(cs: cstruct) -> None:
@@ -427,19 +500,6 @@ def test_conditional_parsing_error(cs: cstruct) -> None:
427
500
  cs.load(cdef)
428
501
 
429
502
 
430
- def test_multiline_define(cs: cstruct) -> None:
431
- """Test parsing of multi-line ``#define`` directives."""
432
- cdef = """
433
- #define MULTILINE_DEF (1 + \\
434
- 2 + \\
435
- 3)
436
- """
437
- cs.load(cdef)
438
-
439
- assert "MULTILINE_DEF" in cs.consts
440
- assert cs.consts["MULTILINE_DEF"] == 6
441
-
442
-
443
503
  def test_multiple_declarators(cs: cstruct) -> None:
444
504
  """Test parsing of multiple declarators in a single struct field declaration."""
445
505
  cdef = """
@@ -570,6 +630,78 @@ def test_preprocessor_define_from_enum_in_struct(cs: cstruct) -> None:
570
630
  assert cs.packet.__members__["payload"].type.__num_entries__ == 20
571
631
 
572
632
 
633
+ @pytest.mark.parametrize(
634
+ ("cdef", "message"),
635
+ [
636
+ (
637
+ """
638
+ struct test {
639
+ uint8 a;
640
+ char b[N];
641
+ };
642
+ """,
643
+ """\
644
+ line 4: Identifier 'N' does not resolve to an integer
645
+ 2: struct test {
646
+ 3: uint8 a;
647
+ 4: char b[N];
648
+ """,
649
+ ),
650
+ (
651
+ """
652
+ struct test {
653
+ uint8 a;
654
+ char b[4 4];
655
+ };
656
+ """,
657
+ """\
658
+ line 4: Invalid expression: too many operands
659
+ 2: struct test {
660
+ 3: uint8 a;
661
+ 4: char b[4 4];
662
+ """,
663
+ ),
664
+ (
665
+ """
666
+ enum test : uint8 {
667
+ A = 1,
668
+ B = A +,
669
+ C
670
+ };
671
+ """,
672
+ """\
673
+ line 4: Invalid expression: not enough operands
674
+ 2: enum test : uint8 {
675
+ 3: A = 1,
676
+ 4: B = A +,
677
+ """,
678
+ ),
679
+ (
680
+ """
681
+ enum test : uint8 {
682
+ A = 1,
683
+ B = ,
684
+ C
685
+ };
686
+ """,
687
+ """\
688
+ line 4: expected an expression
689
+ 2: enum test : uint8 {
690
+ 3: A = 1,
691
+ 4: B = ,
692
+ """,
693
+ ),
694
+ ],
695
+ )
696
+ def test_expression_invalid(cs: cstruct, cdef: str, message: str) -> None:
697
+ """Test that an array size or enum value that is missing or can't be evaluated is an error at its line."""
698
+ cs.load("#define N LENGTH")
699
+
700
+ with pytest.raises(ParserError) as exc_info:
701
+ cs.load(textwrap.dedent(cdef))
702
+ assert str(exc_info.value) == textwrap.dedent(message.rstrip())
703
+
704
+
573
705
  def test_error_context(cs: cstruct) -> None:
574
706
  """Test the context window around errors: 1 line before, the error line, up to 2 lines after."""
575
707
  # Error on line 1: no preceding lines available; shows lines 1, 2, 3
@@ -595,3 +727,51 @@ def test_error_context(cs: cstruct) -> None:
595
727
  3: 69
596
728
  """.rstrip()
597
729
  )
730
+
731
+
732
+ @pytest.mark.parametrize(
733
+ ("value", "expected"),
734
+ [
735
+ # A comment is replaced by a space, after which the value continues
736
+ ("data /* c */", "data"),
737
+ ("a/* c */b", "a b"),
738
+ ("data /* c\n#define C 3\n d */", "data"),
739
+ ("data // c", "data"),
740
+ ("1 // it's", 1),
741
+ ("http://x", "http:"),
742
+ ("1 /* c\n d */ + 2", 3),
743
+ ("/* c\n d */ 1", 1),
744
+ ("/* c */", ""),
745
+ # Comments after and in strings
746
+ ('"a" /* c\n d */', "a"),
747
+ ('"a" // it\'s "b"', "a"),
748
+ ("'b' /* c\n d */", "b"),
749
+ ('b"c" // c', b"c"),
750
+ ("b'd' /* c */", b"d"),
751
+ ('"\\"f\\"" // c', '"f"'),
752
+ ('"it\'s /* c */ // d"', "it's /* c */ // d"),
753
+ # Escapes and spaces in strings
754
+ ('"a\\\\"', "a\\"),
755
+ ('"a b"', "a b"),
756
+ ('b"\\xff"', b"\xff"),
757
+ # Line continuations are joined first
758
+ ('"a\\\nb"', "ab"),
759
+ ("1 /* c */ + \\\n 2", 3),
760
+ ('"a" // c \\\n "b"', "a"),
761
+ ("1 + \\\r\n 2\r", 3),
762
+ # Adjacent strings are concatenated
763
+ ('"bar" /* c */ \\\n "zomg"', "barzomg"),
764
+ # CRLF line endings
765
+ ('"a"\r', "a"),
766
+ ("data\r", "data"),
767
+ # Anything that isn't only strings is kept as it is, like other macro-like constants
768
+ ('"a" + 1', '"a" + 1'),
769
+ ],
770
+ )
771
+ def test_define_value(cs: cstruct, value: str, expected: int | str | bytes) -> None:
772
+ """Test that the value of a ``#define`` follows the rules of C for comments, continuations and strings."""
773
+ cs.load(f"#define A {value}\n#define B 2\n")
774
+
775
+ assert cs.consts["A"] == expected
776
+ assert cs.consts["B"] == 2
777
+ assert "C" not in cs.consts
@@ -1,8 +0,0 @@
1
- {
2
- "tag": "5.0.dev0",
3
- "distance": 14,
4
- "node": "g2688580e0f466b79d4fc7fb94562f0defb978796",
5
- "dirty": true,
6
- "branch": "main",
7
- "node_date": "2026-11-04"
8
- }