dissect.cstruct 5.0.dev20__tar.gz → 5.0.dev22__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 (88) hide show
  1. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/CHANGELOG.md +19 -2
  2. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/PKG-INFO +1 -1
  3. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect/cstruct/__init__.py +12 -0
  4. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect/cstruct/bitbuffer.py +5 -3
  5. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect/cstruct/compiler.py +25 -14
  6. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect/cstruct/cstruct.py +12 -10
  7. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect/cstruct/declarative.py +3 -2
  8. dissect_cstruct-5.0.dev22/dissect/cstruct/exception.py +47 -0
  9. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect/cstruct/expression.py +142 -79
  10. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect/cstruct/lexer.py +15 -6
  11. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect/cstruct/parser.py +77 -34
  12. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect/cstruct/types/base.py +27 -5
  13. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect/cstruct/types/char.py +8 -4
  14. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect/cstruct/types/enum.py +2 -1
  15. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect/cstruct/types/int.py +23 -6
  16. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect/cstruct/types/leb128.py +19 -6
  17. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect/cstruct/types/packed.py +12 -6
  18. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect/cstruct/types/pointer.py +6 -2
  19. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect/cstruct/types/structure.py +11 -2
  20. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect/cstruct/types/wchar.py +16 -8
  21. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect/cstruct/util.py +22 -5
  22. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect.cstruct.egg-info/PKG-INFO +1 -1
  23. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect.cstruct.egg-info/SOURCES.txt +1 -0
  24. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect.cstruct.egg-info/scm_file_list.json +1 -0
  25. dissect_cstruct-5.0.dev22/dissect.cstruct.egg-info/scm_version.json +8 -0
  26. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_basic.py +32 -9
  27. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_bitbuffer.py +2 -1
  28. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_bitfield.py +30 -1
  29. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_compiler.py +23 -22
  30. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_declarative.py +7 -4
  31. dissect_cstruct-5.0.dev22/tests/test_exception.py +63 -0
  32. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_expression.py +133 -22
  33. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_parser.py +107 -1
  34. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_types_base.py +65 -6
  35. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_types_char.py +12 -8
  36. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_types_enum.py +2 -1
  37. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_types_int.py +18 -13
  38. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_types_leb128.py +3 -1
  39. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_types_packed.py +24 -4
  40. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_types_pointer.py +10 -3
  41. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_types_structure.py +11 -8
  42. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_types_union.py +1 -1
  43. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_types_wchar.py +15 -11
  44. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_util.py +56 -1
  45. dissect_cstruct-5.0.dev20/dissect/cstruct/exception.py +0 -33
  46. dissect_cstruct-5.0.dev20/dissect.cstruct.egg-info/scm_version.json +0 -8
  47. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/.git-blame-ignore-revs +0 -0
  48. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/.gitattributes +0 -0
  49. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/COPYRIGHT +0 -0
  50. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/LICENSE +0 -0
  51. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/MANIFEST.in +0 -0
  52. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/README.md +0 -0
  53. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect/cstruct/dump.py +0 -0
  54. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect/cstruct/tools/__init__.py +0 -0
  55. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect/cstruct/tools/stubgen.py +0 -0
  56. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect/cstruct/types/__init__.py +0 -0
  57. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect/cstruct/types/flag.py +0 -0
  58. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect/cstruct/types/void.py +0 -0
  59. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect.cstruct.egg-info/dependency_links.txt +0 -0
  60. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect.cstruct.egg-info/entry_points.txt +0 -0
  61. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect.cstruct.egg-info/requires.txt +0 -0
  62. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/dissect.cstruct.egg-info/top_level.txt +0 -0
  63. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/examples/disk.py +0 -0
  64. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/examples/mirai.py +0 -0
  65. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/examples/pe.py +0 -0
  66. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/examples/protobuf.py +0 -0
  67. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/examples/secdesc.py +0 -0
  68. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/pyproject.toml +0 -0
  69. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/setup.cfg +0 -0
  70. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/__init__.py +0 -0
  71. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/_data/testdef.txt +0 -0
  72. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/_docs/Makefile +0 -0
  73. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/_docs/__init__.py +0 -0
  74. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/_docs/conf.py +0 -0
  75. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/_docs/index.rst +0 -0
  76. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/conftest.py +0 -0
  77. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_align.py +0 -0
  78. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_annotations.py +0 -0
  79. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_benchmark.py +0 -0
  80. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_ctypes.py +0 -0
  81. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_dump.py +0 -0
  82. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_lexer.py +0 -0
  83. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_tools_stubgen.py +0 -0
  84. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_types_custom.py +0 -0
  85. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_types_flag.py +0 -0
  86. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/test_types_void.py +0 -0
  87. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tests/util.py +0 -0
  88. {dissect_cstruct-5.0.dev20 → dissect_cstruct-5.0.dev22}/tox.ini +0 -0
@@ -10,12 +10,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
10
10
 
11
11
  - Declarative syntax for structures and unions in `dissect.cstruct.declarative`, using classes with type annotations.
12
12
  - `asdict()` and the `_asdict()` method return the field values of a structure or union as a dict, with nested structures as dicts and arrays as lists. `asjson()` returns them as a JSON string, with bytes as base64 and enum members as numbers. `JSONEncoder` encodes structures as part of other data with `json.dumps()`.
13
+ - `sizeof` and `offsetof` in expressions accept a type name like the type of a field, e.g. `sizeof(struct header *[4])`. An argument that isn't a type name raises an `ExpressionParserError` when the expression is created.
13
14
 
14
15
  ### Changed
15
16
 
16
17
  - Optimize storage of field sizes.
17
18
  - Rename `_sizes` property of `Structure` to `__sizes__`.
18
19
  - Rename `_values` property of `Structure` to `__values__`.
20
+ - Rename the `signed` attribute of integer and LEB128 types to `__signed__`, like the other attributes of types. The `signed` property is deprecated.
19
21
  - Added `load` argument to `cstruct` class, allowing direct initialization with a definition (i.e. `cstruct(cdef)` instead of `cstruct().load(cdef)`. Other arguments to `cstruct` are now keyword only.
20
22
  - Replace `compiler.compile` and the `Compiler` class with `compiler.compile_structure`.
21
23
  - Improve parsing performance:
@@ -31,6 +33,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
31
33
  - `obj.dumps()` and `obj.write()` no longer create a `functools.partial` on every access. As a result, they no longer accept a `value` argument.
32
34
  - `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`.
33
35
  - `dumpstruct` shows the fields of every element of an array of structures or unions.
36
+ - Errors are subclasses of `dissect.cstruct.Error`: `DefinitionError` for invalid definitions, `ReadError` for data that can't be parsed and `WriteError` for values that can't be written. All three are also subclasses of `ValueError`.
37
+ - A short read raises `dissect.cstruct.exception.EOFError`, which is a subclass of `Error` and of the built-in `EOFError`. This has also been made more consistent in many places, such as `wchar`, which previously raised a `UnicodeDecodeError`.
38
+ - Arithmetic errors in expressions, such as division by zero, now raise a `ReadError`.
39
+ - A value that can't be written raises a `WriteError` with the original error as its cause
40
+ - Invalid definitions raise a `DefinitionError`.
41
+ - A constant expression that can't be calculated during `load`, e.g. a division by zero, raises a `ParserError`.
42
+ - `offsetof` raises a `TypeError` for a type that isn't a structure, instead of an `AttributeError` or an error about a missing field. In an expression, the errors of `sizeof` and `offsetof` raise a `DefinitionError`.
43
+ - Errors that `load` raises include the line of the definition.
44
+ - `ArraySizeError` is removed. A value that is longer than its static array raises a `WriteError`.
45
+ - `write()` raises a `TypeError` for an object that can't be written to, like `read()` does.
34
46
 
35
47
  ### Fixed
36
48
 
@@ -39,12 +51,17 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
39
51
  - Unions can be created with default values and read if they have doubly nested structures or nested unions.
40
52
  - Writing a `bytearray` to a `char` array no longer modifies the `bytearray`.
41
53
  - Writing a structure correctly returns the amount of bytes written, including padding and bit fields.
42
- - Writing a structure raises an `AttributeError` for missing attributes and for values of a nested structure field that aren't a structure, instead of writing default values.
54
+ - Writing a structure raises a `WriteError` for missing attributes and for values of a nested structure field that aren't a structure, instead of writing default values.
43
55
  - A surrogate pair takes up two entries of a `wchar` array, so writing it no longer writes more bytes than the size of the array.
44
56
  - A `wchar` string can hold a lone surrogate, instead of raising an error for the whole structure when reading or writing it. Bytes are written back as they were stored.
45
- - Writing more than a single character to a `char` or `wchar` raises a `ValueError`, instead of writing all of it and moving the fields after it. An empty value is padded.
57
+ - Writing more than a single character to a `char` or `wchar` raises a `WriteError`, instead of writing all of it and moving the fields after it. An empty value is padded.
46
58
  - A plain integer can be written to an enum or flag field, including a bit field.
47
59
  - `dumpstruct` shows the fields of a structure in a union in a union, instead of only its `repr`.
60
+ - Writing a value that doesn't fit in its bit field raises a `WriteError`, instead of changing the fields next to it.
61
+ - Bit fields of a type that isn't an integer, `char`, enum or flag raise a `DefinitionError` when they're defined, instead of an error or wrong bytes when they're read or written.
62
+ - An `Expression` is parsed when it's created. An invalid array size that refers to a field, e.g. `char a[n +]`, raises a `ParserError` during `load`, instead of an `ExpressionParserError` on every read.
63
+ - `offsetof` gives the offsets of C for the fields of a union and the fields of an anonymous nested structure or union, instead of an error or the offset in the nested type.
64
+ - An empty expression raises "not enough operands" instead of "too many operands".
48
65
 
49
66
  ## [4.5] - 20-05-2025
50
67
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dissect.cstruct
3
- Version: 5.0.dev20
3
+ Version: 5.0.dev22
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
@@ -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
 
@@ -0,0 +1,47 @@
1
+ from __future__ import annotations
2
+
3
+ import builtins
4
+
5
+
6
+ class Error(Exception):
7
+ """Base class for all exceptions."""
8
+
9
+
10
+ class DefinitionError(Error, ValueError):
11
+ """A type definition is invalid."""
12
+
13
+
14
+ class LexerError(DefinitionError):
15
+ """The type definition can't be tokenized."""
16
+
17
+
18
+ class ParserError(DefinitionError):
19
+ """The type definition can't be parsed."""
20
+
21
+
22
+ class ResolveError(DefinitionError):
23
+ """The type definition can't be resolved."""
24
+
25
+
26
+ class ExpressionParserError(DefinitionError):
27
+ """The expression can't be parsed."""
28
+
29
+
30
+ class UnknownIdentifierError(ExpressionParserError):
31
+ """The identifier is not defined."""
32
+
33
+
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."""