dissect.cstruct 5.0.dev14__py3-none-any.whl → 5.0.dev16__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.
@@ -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:
dissect/cstruct/lexer.py CHANGED
@@ -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."""
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:
@@ -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
@@ -2,10 +2,10 @@ dissect/cstruct/__init__.py,sha256=KOyNeUvu4c0JaAiyOfj7iftGwUIjTmD8MwHtFsLPLSU,1
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/exception.py,sha256=RqD08LuBkbMqa3iQ1A05DNN8XgEmQR_SUnguwe9LGo8,316
6
- dissect/cstruct/expression.py,sha256=Y27-N48BomBoRFozbWhGDF_DS2lfklRwWVUbCzGnxHE,10873
7
- dissect/cstruct/lexer.py,sha256=NDUfAWgyxgRNRuVO8ExXQ51LqQXS2mv9bywVa_M7tFQ,19665
8
- dissect/cstruct/parser.py,sha256=5vz1frbenevKyn-CobKyp9_22dnEbFej_nUXQeL5W8U,21368
5
+ dissect/cstruct/exception.py,sha256=box-mw6FoP6c3vndvYLcTeJCZVgIG8IQVPEAg4zW0C8,380
6
+ dissect/cstruct/expression.py,sha256=SbZRv7ueasYU4k-4k2eV1fjwL3JTAgF2UBaBvNjwiv4,10736
7
+ dissect/cstruct/lexer.py,sha256=N7eqCOlcaQriUUIswJv16i-CE_sahYXGO-YdFO0IKKY,20421
8
+ dissect/cstruct/parser.py,sha256=6PovhIbicENg3jBgopdArupmQNd-Ti7rd_te9au4z6U,22569
9
9
  dissect/cstruct/util.py,sha256=vAf-kdOkk3zprW_gD6QmQeN3VIRgQqhPS4B_ha1jEpQ,18040
10
10
  dissect/cstruct/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
11
  dissect/cstruct/tools/stubgen.py,sha256=MeZkLmSeNSLNcAEwlAdIGv1lKvlvK3UQ4WN85ovsxTM,7672
@@ -21,10 +21,10 @@ dissect/cstruct/types/pointer.py,sha256=FNuB9bfENWRebbKX-R6Vs6xWPMHepjvOhhomeUhr
21
21
  dissect/cstruct/types/structure.py,sha256=mxDvurQ0oAjI2flykhAPlT-03280cDpwGTz0-bqbr-0,39558
22
22
  dissect/cstruct/types/void.py,sha256=fV4hKk50uop_EKbR1nfy1cdtAzvUYrSymXsdakCyFk8,1222
23
23
  dissect/cstruct/types/wchar.py,sha256=VrnPXsP_lsyA-1xr4D2aSIVijumMhUuZWNlDHcn12-s,3964
24
- dissect_cstruct-5.0.dev14.dist-info/licenses/COPYRIGHT,sha256=H-18RXfshdH9AdHwW2eO1Xa-5s6tY5eipHh5c0whDu4,316
25
- dissect_cstruct-5.0.dev14.dist-info/licenses/LICENSE,sha256=PhUqiw6jAh2KbBdVRPBq_hfAvfcTBin7nZ3CK7NQbTM,11341
26
- dissect_cstruct-5.0.dev14.dist-info/METADATA,sha256=0EhDz7fNITZQWzSYoy46-j0nObu4B1Am3-nEipozmxc,9256
27
- dissect_cstruct-5.0.dev14.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
28
- dissect_cstruct-5.0.dev14.dist-info/entry_points.txt,sha256=z53zqZqwD2OLrAkRwrP4wTeiU9CQe7xrMly0T2c0_wQ,71
29
- dissect_cstruct-5.0.dev14.dist-info/top_level.txt,sha256=Mn-CQzEYsAbkxrUI0TnplHuXnGVKzxpDw_po_sXpvv4,8
30
- dissect_cstruct-5.0.dev14.dist-info/RECORD,,
24
+ dissect_cstruct-5.0.dev16.dist-info/licenses/COPYRIGHT,sha256=H-18RXfshdH9AdHwW2eO1Xa-5s6tY5eipHh5c0whDu4,316
25
+ dissect_cstruct-5.0.dev16.dist-info/licenses/LICENSE,sha256=PhUqiw6jAh2KbBdVRPBq_hfAvfcTBin7nZ3CK7NQbTM,11341
26
+ dissect_cstruct-5.0.dev16.dist-info/METADATA,sha256=xdol4wRzYoijmhDPLkLFrAn0S8-Ag4LquHg3MRZ3Hu8,9256
27
+ dissect_cstruct-5.0.dev16.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
28
+ dissect_cstruct-5.0.dev16.dist-info/entry_points.txt,sha256=z53zqZqwD2OLrAkRwrP4wTeiU9CQe7xrMly0T2c0_wQ,71
29
+ dissect_cstruct-5.0.dev16.dist-info/top_level.txt,sha256=Mn-CQzEYsAbkxrUI0TnplHuXnGVKzxpDw_po_sXpvv4,8
30
+ dissect_cstruct-5.0.dev16.dist-info/RECORD,,