dissect.cstruct 5.0.dev20__py3-none-any.whl → 5.0.dev22__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.
@@ -4,10 +4,16 @@ from dissect.cstruct.bitbuffer import BitBuffer
4
4
  from dissect.cstruct.cstruct import cstruct, ctypes, ctypes_type
5
5
  from dissect.cstruct.dump import dumpstruct, hexdump
6
6
  from dissect.cstruct.exception import (
7
+ DefinitionError,
7
8
  Error,
9
+ ExpressionParserError,
10
+ LexerError,
8
11
  NullPointerDereference,
9
12
  ParserError,
13
+ ReadError,
10
14
  ResolveError,
15
+ UnknownIdentifierError,
16
+ WriteError,
11
17
  )
12
18
  from dissect.cstruct.expression import Expression
13
19
  from dissect.cstruct.types import (
@@ -60,24 +66,30 @@ __all__ = [
60
66
  "BitBuffer",
61
67
  "Char",
62
68
  "CharArray",
69
+ "DefinitionError",
63
70
  "Enum",
64
71
  "Error",
65
72
  "Expression",
73
+ "ExpressionParserError",
66
74
  "Field",
67
75
  "Flag",
68
76
  "Int",
69
77
  "JSONEncoder",
78
+ "LexerError",
70
79
  "MetaType",
71
80
  "NullPointerDereference",
72
81
  "Packed",
73
82
  "ParserError",
74
83
  "Pointer",
84
+ "ReadError",
75
85
  "ResolveError",
76
86
  "Structure",
77
87
  "Union",
88
+ "UnknownIdentifierError",
78
89
  "Void",
79
90
  "Wchar",
80
91
  "WcharArray",
92
+ "WriteError",
81
93
  "asdict",
82
94
  "asjson",
83
95
  "cstruct",
@@ -2,6 +2,8 @@ from __future__ import annotations
2
2
 
3
3
  from typing import TYPE_CHECKING, BinaryIO
4
4
 
5
+ from dissect.cstruct.exception import DefinitionError
6
+
5
7
  if TYPE_CHECKING:
6
8
  from dissect.cstruct.types import BaseType
7
9
 
@@ -20,7 +22,7 @@ class BitBuffer:
20
22
  def read(self, field_type: type[BaseType], bits: int) -> int:
21
23
  if self._remaining == 0 or self._type != field_type:
22
24
  if field_type.__size__ is None:
23
- raise ValueError("Reading variable-length fields is unsupported")
25
+ raise DefinitionError("Reading variable-length fields is unsupported")
24
26
 
25
27
  self._type = field_type
26
28
  self._remaining = field_type.__size__ * 8
@@ -33,7 +35,7 @@ class BitBuffer:
33
35
  self._buffer = int.from_bytes(self._buffer, "big")
34
36
 
35
37
  if bits > self._remaining:
36
- raise ValueError("Reading straddled bits is unsupported")
38
+ raise DefinitionError("Reading straddled bits is unsupported")
37
39
 
38
40
  if self.endian == "<":
39
41
  v = self._buffer & ((1 << bits) - 1)
@@ -52,7 +54,7 @@ class BitBuffer:
52
54
  self.flush()
53
55
 
54
56
  if field_type.__size__ is None:
55
- raise ValueError("Writing variable-length fields is unsupported")
57
+ raise DefinitionError("Writing variable-length fields is unsupported")
56
58
 
57
59
  self._remaining = field_type.__size__ * 8
58
60
  self._type = field_type
@@ -12,7 +12,13 @@ from operator import itemgetter
12
12
  from textwrap import indent
13
13
  from typing import TYPE_CHECKING, Any
14
14
 
15
- from dissect.cstruct.exception import ArraySizeError, ExpressionParserError
15
+ from dissect.cstruct.exception import (
16
+ DefinitionError,
17
+ EOFError,
18
+ Error,
19
+ ReadError,
20
+ WriteError,
21
+ )
16
22
  from dissect.cstruct.expression import SOURCE_GLOBALS, Expression
17
23
  from dissect.cstruct.types import (
18
24
  Array,
@@ -212,7 +218,7 @@ def _field_bytes(type_: type[BaseType], value: Any, endian: str) -> bytes:
212
218
  """Return the bytes of a char or wchar field that isn't of the right type yet or doesn't fit."""
213
219
  buf = type_.dumps(type_.__default__() if value is None else value, endian=endian)
214
220
  if len(buf) > type_.__size__:
215
- raise ArraySizeError(f"Expected {type_.__size__} bytes for {type_.__name__}, got {len(buf)} instead.")
221
+ raise WriteError(f"Expected {type_.__size__} bytes for {type_.__name__}, got {len(buf)} instead.")
216
222
  return buf
217
223
 
218
224
 
@@ -241,6 +247,11 @@ _GLOBALS = {
241
247
  "_struct_write": StructureMetaType._write,
242
248
  "_union_write": UnionMetaType._write,
243
249
  "_struct_error": struct.error,
250
+ "_Error": Error,
251
+ "_EOFError": EOFError,
252
+ "_ReadError": ReadError,
253
+ "_WriteError": WriteError,
254
+ "_DefinitionError": DefinitionError,
244
255
  "_field_bytes": _field_bytes,
245
256
  "_array_values": _array_values,
246
257
  "_or_default": _or_default,
@@ -552,13 +563,13 @@ class _ReadSourceGenerator(_SourceGenerator):
552
563
  # Integer fields that were read before are used directly
553
564
  types = {field._name: field.type for field in self.fields}
554
565
  variables = {name: f"int({var})" for name, var in self._assigned if issubclass(types[name], _INTEGER_TYPES)}
555
- try:
556
- count = num_entries.source(variables, context)
557
- except ExpressionParserError:
558
- # Invalid expressions raise their error when reading the array
559
- return read
566
+ count = num_entries.source(variables, context)
560
567
 
561
- lines.append(f"_count = max(0, {count})")
568
+ # E.g. a division by a field that is zero.
569
+ message = f"Invalid array size '{num_entries.expression}': "
570
+ lines.append(f"try: _count = max(0, {count})")
571
+ lines.append("except _Error: raise")
572
+ lines.append(f"except (ArithmeticError, ValueError) as e: raise _ReadError({message!r} + str(e)) from e")
562
573
  element = self._type_symbol(field.type.__type__)
563
574
  return f"_type_call({type_}, {element}._read_array(stream, _count, context={context}, endian=endian))"
564
575
 
@@ -573,7 +584,7 @@ class _ReadSourceGenerator(_SourceGenerator):
573
584
  lines.append(f"_bit_buffer = {self._type_symbol(read_type)}._read(stream, endian=endian)")
574
585
 
575
586
  if field.bits > remaining:
576
- lines.append('raise ValueError("Reading straddled bits is unsupported")')
587
+ lines.append('raise _DefinitionError("Reading straddled bits is unsupported")')
577
588
  yield _block(lines)
578
589
  return
579
590
 
@@ -722,7 +733,7 @@ class _ReadSourceGenerator(_SourceGenerator):
722
733
  if issubclass(read_type, Int):
723
734
  # Everything that's read as an integer type is sliced directly out of the buffer
724
735
  elem_size = read_type.__size__
725
- signed = bool(read_type.signed)
736
+ signed = bool(read_type.__signed__)
726
737
  lines.append(f"_array_buf = {getter}")
727
738
  raw = f"_int_from_bytes(_array_buf[i:i + {elem_size}], _byteorder[endian], signed={signed})"
728
739
  getter = f"[{raw} for i in range(0, {count}, {elem_size})]"
@@ -753,7 +764,7 @@ class _ReadSourceGenerator(_SourceGenerator):
753
764
  elif issubclass(field_type, (Enum, Flag)):
754
765
  # Fast path the member lookup, the slow path takes care of unknown values
755
766
  if issubclass(read_type, Int):
756
- raw = f"_int_from_bytes({getter}, _byteorder[endian], signed={bool(read_type.signed)})"
767
+ raw = f"_int_from_bytes({getter}, _byteorder[endian], signed={bool(read_type.__signed__)})"
757
768
  else:
758
769
  raw = getter
759
770
 
@@ -762,7 +773,7 @@ class _ReadSourceGenerator(_SourceGenerator):
762
773
  lines.extend(target(field, "_member"))
763
774
 
764
775
  elif issubclass(read_type, Int):
765
- signed = bool(read_type.signed)
776
+ signed = bool(read_type.__signed__)
766
777
  value = f"_int_from_bytes({getter}, _byteorder[endian], signed={signed})"
767
778
  lines.extend(target(field, f"_type_call({self._type_symbol(field.type)}, {value})"))
768
779
 
@@ -1208,7 +1219,7 @@ def _has_default_write(type_: type[BaseType], base: type[BaseType]) -> bool:
1208
1219
 
1209
1220
  def _int_to_bytes(type_: type[Int], value: str) -> str:
1210
1221
  """Return the code to convert a value of an integer type to bytes."""
1211
- return f"{value}.to_bytes({type_.__size__}, _byteorder[endian], signed={bool(type_.signed)})"
1222
+ return f"{value}.to_bytes({type_.__size__}, _byteorder[endian], signed={bool(type_.__signed__)})"
1212
1223
 
1213
1224
 
1214
1225
  def _get_attribute(var: str, name: str) -> str:
@@ -1251,7 +1262,7 @@ def _member_lookup(type_: str, value: str) -> str:
1251
1262
 
1252
1263
  def _check_eof(size: int) -> str:
1253
1264
  """Return the code to raise an ``EOFError`` if fewer than ``size`` bytes were read into ``buf``."""
1254
- return f'if len(buf) != {size}: raise EOFError(f"Read {{len(buf)}} bytes, but expected {size}")'
1265
+ return f'if len(buf) != {size}: raise _EOFError(f"Read {{len(buf)}} bytes, but expected {size}")'
1255
1266
 
1256
1267
 
1257
1268
  def _block(lines: list[str]) -> str:
@@ -12,7 +12,7 @@ from functools import lru_cache
12
12
  from pathlib import Path
13
13
  from typing import TYPE_CHECKING, Any, BinaryIO, Literal, TypeVar, cast
14
14
 
15
- from dissect.cstruct.exception import ResolveError
15
+ from dissect.cstruct.exception import DefinitionError, ResolveError
16
16
  from dissect.cstruct.expression import Expression
17
17
  from dissect.cstruct.parser import CStyleParser
18
18
  from dissect.cstruct.types import (
@@ -90,8 +90,8 @@ class cstruct:
90
90
  "int128": self._make_int_type("int128", 16, True, alignment=16),
91
91
  "uint128": self._make_int_type("uint128", 16, False, alignment=16),
92
92
 
93
- "uleb128": self._make_type("uleb128", (LEB128,), None, attrs={"signed": False}),
94
- "ileb128": self._make_type("ileb128", (LEB128,), None, attrs={"signed": True}),
93
+ "uleb128": self._make_type("uleb128", (LEB128,), None, attrs={"__signed__": False}),
94
+ "ileb128": self._make_type("ileb128", (LEB128,), None, attrs={"__signed__": True}),
95
95
 
96
96
  "void": self._make_type("void", (Void,), 0),
97
97
 
@@ -285,11 +285,11 @@ class cstruct:
285
285
  replace: Whether to replace the type if it already exists.
286
286
 
287
287
  Raises:
288
- ValueError: If the type already exists.
288
+ DefinitionError: If the type already exists.
289
289
  """
290
290
  typeobj = self.resolve(type_)
291
291
  if not replace and (existing := self.types.get(name)) is not None and existing is not typeobj:
292
- raise ValueError(f"Duplicate type: {name}")
292
+ raise DefinitionError(f"Duplicate type: {name}")
293
293
 
294
294
  self.types[name] = typeobj
295
295
  self._add_attr(name, typeobj)
@@ -532,11 +532,13 @@ class cstruct:
532
532
  if num_entries is None:
533
533
  null_terminated = True
534
534
  size = None
535
- elif isinstance(num_entries, Expression) or type_.__dynamic__:
535
+ elif isinstance(num_entries, Expression):
536
+ size = None
537
+ elif num_entries < 0:
538
+ raise DefinitionError(f"Array size must not be negative: {num_entries}")
539
+ elif type_.__dynamic__:
536
540
  size = None
537
541
  else:
538
- if type_.__size__ is None:
539
- raise ValueError(f"Cannot create array of dynamic type: {type_.__name__}")
540
542
  size = num_entries * type_.__size__
541
543
 
542
544
  name = f"{type_.__name__}[]" if null_terminated else f"{type_.__name__}[{num_entries}]"
@@ -552,7 +554,7 @@ class cstruct:
552
554
  return cast("type[Array]", self._make_type(name, bases, size, alignment=type_.__alignment__, attrs=attrs))
553
555
 
554
556
  def _make_int_type(self, name: str, size: int, signed: bool, *, alignment: int | None = None) -> type[Int]:
555
- return cast("type[Int]", self._make_type(name, (Int,), size, alignment=alignment, attrs={"signed": signed}))
557
+ return cast("type[Int]", self._make_type(name, (Int,), size, alignment=alignment, attrs={"__signed__": signed}))
556
558
 
557
559
  def _make_packed_type(self, name: str, fmt: str, base: type, *, alignment: int | None = None) -> type[Packed]:
558
560
  return cast(
@@ -562,7 +564,7 @@ class cstruct:
562
564
  (base, Packed),
563
565
  struct.calcsize(fmt),
564
566
  alignment=alignment,
565
- attrs={"__fmt__": fmt},
567
+ attrs={"__fmt__": fmt, "__signed__": fmt.islower()},
566
568
  ),
567
569
  )
568
570
 
@@ -60,6 +60,7 @@ from typing import TYPE_CHECKING, Annotated, Any, BinaryIO, ForwardRef, get_args
60
60
 
61
61
  from dissect.cstruct import compiler
62
62
  from dissect.cstruct.cstruct import cstruct
63
+ from dissect.cstruct.exception import DefinitionError
63
64
  from dissect.cstruct.types.base import BaseArray, MetaType
64
65
  from dissect.cstruct.types.structure import Field
65
66
  from dissect.cstruct.types.structure import Structure as _Structure
@@ -370,7 +371,7 @@ def _resolve_type(type_: Any, cs: cstruct) -> type:
370
371
  if isinstance(type_, str):
371
372
  return _resolve_string(type_, cs)
372
373
 
373
- raise TypeError(f"Unsupported field annotation: {type_!r}")
374
+ raise DefinitionError(f"Unsupported field annotation: {type_!r}")
374
375
 
375
376
 
376
377
  def _resolve_field(cls: type, name: str, spec: FieldSpec) -> Field:
@@ -380,7 +381,7 @@ def _resolve_field(cls: type, name: str, spec: FieldSpec) -> Field:
380
381
  while issubclass(embedded, BaseArray):
381
382
  embedded = embedded.__type__
382
383
  if embedded is cls:
383
- raise TypeError(f"Field {name!r} embeds {cls.__name__!r} in itself, use a pointer instead")
384
+ raise DefinitionError(f"Field {name!r} embeds {cls.__name__!r} in itself, use a pointer instead")
384
385
 
385
386
  return Field(name, type_, spec.bits, spec.offset)
386
387
 
@@ -1,33 +1,47 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import builtins
4
+
3
5
 
4
6
  class Error(Exception):
5
- pass
7
+ """Base class for all exceptions."""
6
8
 
7
9
 
8
- class LexerError(Error):
9
- pass
10
+ class DefinitionError(Error, ValueError):
11
+ """A type definition is invalid."""
10
12
 
11
13
 
12
- class ParserError(Error):
13
- pass
14
+ class LexerError(DefinitionError):
15
+ """The type definition can't be tokenized."""
14
16
 
15
17
 
16
- class ResolveError(Error):
17
- pass
18
+ class ParserError(DefinitionError):
19
+ """The type definition can't be parsed."""
18
20
 
19
21
 
20
- class NullPointerDereference(Error):
21
- pass
22
+ class ResolveError(DefinitionError):
23
+ """The type definition can't be resolved."""
22
24
 
23
25
 
24
- class ArraySizeError(Error):
25
- pass
26
+ class ExpressionParserError(DefinitionError):
27
+ """The expression can't be parsed."""
26
28
 
27
29
 
28
- class ExpressionParserError(Error):
29
- pass
30
+ class UnknownIdentifierError(ExpressionParserError):
31
+ """The identifier is not defined."""
30
32
 
31
33
 
32
- class UnknownIdentifierError(ExpressionParserError):
33
- pass
34
+ class ReadError(Error, ValueError):
35
+ """The data can't be parsed."""
36
+
37
+
38
+ class NullPointerDereference(ReadError):
39
+ """A pointer is null, but it was dereferenced."""
40
+
41
+
42
+ class WriteError(Error, ValueError):
43
+ """The value can't be written."""
44
+
45
+
46
+ class EOFError(Error, builtins.EOFError):
47
+ """The data ends before the value does."""