dissect.cstruct 5.0.dev21__py3-none-any.whl → 5.0.dev23__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.
dissect/cstruct/parser.py CHANGED
@@ -6,9 +6,11 @@ from typing import TYPE_CHECKING
6
6
 
7
7
  from dissect.cstruct import compiler
8
8
  from dissect.cstruct.exception import (
9
+ DefinitionError,
9
10
  ExpressionParserError,
10
11
  LexerError,
11
12
  ParserError,
13
+ ResolveError,
12
14
  UnknownIdentifierError,
13
15
  )
14
16
  from dissect.cstruct.expression import Expression
@@ -85,23 +87,21 @@ class CStyleParser(Parser):
85
87
  self._reset_tokens(tokenize(data))
86
88
  self._parse()
87
89
 
88
- def _match(self, *types: TokenType) -> Token | None:
89
- """Consume and return the current token if it matches any of the given types, otherwise return None."""
90
- if self._current().type in types:
91
- return self._take()
92
- return None
90
+ def _error(self, msg: str, *, token: Token | None = None) -> ParserError:
91
+ return ParserError(self._error_message(msg, token=token))
93
92
 
94
- def _at(self, *types: TokenType) -> bool:
95
- """Return whether the current token matches any of the given types."""
96
- return self._tokens[self._pos].type in types
93
+ def _located(self, error: DefinitionError, token: Token) -> DefinitionError:
94
+ """Return the error with the line of the token, and keep its class."""
95
+ return type(error)(self._error_message(str(error), token=token))
97
96
 
98
- def _error(self, msg: str, *, token: Token | None = None) -> ParserError:
97
+ def _error_message(self, msg: str, *, token: Token | None = None) -> str:
98
+ """Return the message with the line of the token, the current token by default."""
99
99
  lineno = (token if token is not None else self._tokens[self._pos]).line
100
100
  if self._data is None:
101
- return ParserError(f"line {lineno}: {msg}")
101
+ return f"line {lineno}: {msg}"
102
102
 
103
103
  content = format_error_context(self._data, lineno)
104
- return ParserError(f"line {lineno}: {msg}\n{content}")
104
+ return f"line {lineno}: {msg}\n{content}"
105
105
 
106
106
  def _in_false_branch(self) -> bool:
107
107
  """Return whether we're currently in a false conditional branch."""
@@ -218,6 +218,12 @@ class CStyleParser(Parser):
218
218
  except (LexerError, ExpressionParserError):
219
219
  # If evaluation fails, just keep it as a string (e.g. for macro-like constants)
220
220
  pass
221
+ except ResolveError as e:
222
+ # E.g. sizeof of an unknown type
223
+ raise self._located(e, token) from e
224
+ except (ArithmeticError, ValueError) as e:
225
+ # E.g. a division by zero or sizeof of a type with a dynamic size
226
+ raise self._error(str(e), token=token) from None
221
227
 
222
228
  self.cs.add_const(name_token.value, value)
223
229
 
@@ -317,6 +323,7 @@ class CStyleParser(Parser):
317
323
 
318
324
  # Parse one or more typedef names with modifiers (pointers, arrays)
319
325
  while self._at(TokenType.IDENTIFIER, TokenType.STAR):
326
+ start_token = self._current()
320
327
  type_, name, bits = self._parse_field_name(base_type)
321
328
  if bits is not None:
322
329
  raise self._error("typedefs cannot have bitfields")
@@ -327,7 +334,10 @@ class CStyleParser(Parser):
327
334
  base_type.__name__ = name
328
335
  base_type.__qualname__ = name
329
336
 
330
- self.cs.add_type(name, type_)
337
+ try:
338
+ self.cs.add_type(name, type_)
339
+ except DefinitionError as e:
340
+ raise self._located(e, start_token) from e
331
341
 
332
342
  if not self._match(TokenType.COMMA):
333
343
  break
@@ -360,26 +370,37 @@ class CStyleParser(Parser):
360
370
  type = factory(name, [], align=self.align)
361
371
  if self.compiled and "nocompile" not in self._flags:
362
372
  type = compiler.compile_structure(type)
363
- self.cs.add_type(name, type)
373
+
374
+ try:
375
+ self.cs.add_type(name, type)
376
+ except DefinitionError as e:
377
+ raise self._located(e, start_token) from e
364
378
  else:
365
379
  # struct typename ... (type reference)
366
- return self.cs.resolve(name)
380
+ try:
381
+ return self.cs.resolve(name)
382
+ except ResolveError as e:
383
+ raise self._located(e, start_token) from e
367
384
 
368
385
  # Parse body
369
386
  self._expect(TokenType.LBRACE)
370
387
  fields = self._parse_field_list()
371
388
  self._expect(TokenType.RBRACE)
372
389
 
373
- if type is None:
374
- is_anonymous = name is None
375
- name = name or self.cs._next_anonymous()
390
+ # The fields are checked when the type is built from all of them, e.g. for a duplicate name
391
+ try:
392
+ if type is None:
393
+ is_anonymous = name is None
394
+ name = name or self.cs._next_anonymous()
376
395
 
377
- type = factory(name, fields, align=self.align, anonymous=is_anonymous)
378
- if self.compiled and "nocompile" not in self._flags:
379
- type = compiler.compile_structure(type)
380
- else:
381
- type.__fields__.extend(fields)
382
- type.commit()
396
+ type = factory(name, fields, align=self.align, anonymous=is_anonymous)
397
+ if self.compiled and "nocompile" not in self._flags:
398
+ type = compiler.compile_structure(type)
399
+ else:
400
+ type.__fields__.extend(fields)
401
+ type.commit()
402
+ except DefinitionError as e:
403
+ raise self._located(e, start_token) from e
383
404
 
384
405
  self._flags.clear()
385
406
  return type
@@ -402,6 +423,11 @@ class CStyleParser(Parser):
402
423
  parts.append(token.value)
403
424
  base_type_str = " ".join(parts)
404
425
 
426
+ try:
427
+ base_type = self.cs.resolve(base_type_str)
428
+ except ResolveError as e:
429
+ raise self._located(e, start_token) from e
430
+
405
431
  self._expect(TokenType.LBRACE)
406
432
 
407
433
  next_value = 1 if is_flag else 0
@@ -428,7 +454,10 @@ class CStyleParser(Parser):
428
454
 
429
455
  try:
430
456
  value = Expression(join_tokens(tokens)).evaluate(self.cs, values)
431
- except ExpressionParserError as e:
457
+ except ResolveError as e:
458
+ # E.g. sizeof of an unknown type
459
+ raise self._located(e, tokens[0]) from e
460
+ except (ExpressionParserError, ArithmeticError, ValueError) as e:
432
461
  raise self._error(str(e), token=tokens[0]) from None
433
462
  else:
434
463
  value = next_value
@@ -445,12 +474,15 @@ class CStyleParser(Parser):
445
474
  self._expect(TokenType.RBRACE)
446
475
 
447
476
  factory = self.cs._make_flag if is_flag else self.cs._make_enum
448
- type_ = factory(name or "", self.cs.resolve(base_type_str), values)
477
+ try:
478
+ type_ = factory(name or "", base_type, values)
449
479
 
450
- if name is not None:
451
- # Register the enum/flag type if it has a name
452
- # Anonymous enums/flags are handled in the top level parse loop
453
- self.cs.add_type(type_.__name__, type_)
480
+ if name is not None:
481
+ # Register the enum/flag type if it has a name
482
+ # Anonymous enums/flags are handled in the top level parse loop
483
+ self.cs.add_type(type_.__name__, type_)
484
+ except DefinitionError as e:
485
+ raise self._located(e, start_token) from e
454
486
 
455
487
  return type_
456
488
 
@@ -511,6 +543,7 @@ class CStyleParser(Parser):
511
543
 
512
544
  def _parse_array_dimensions(self, base_type: type[BaseType]) -> type[BaseType]:
513
545
  """Parse array dimensions following a field name, e.g., ``field[10][20]``."""
546
+ start_token = self._current()
514
547
  dimensions: list[int | Expression] = []
515
548
 
516
549
  while self._match(TokenType.LBRACKET):
@@ -519,13 +552,16 @@ class CStyleParser(Parser):
519
552
 
520
553
  count = None
521
554
  if tokens:
522
- count = Expression(join_tokens(tokens))
523
555
  try:
556
+ count = Expression(join_tokens(tokens))
524
557
  count = count.evaluate(self.cs)
525
558
  except UnknownIdentifierError:
526
559
  # The size refers to a field, so it's evaluated when reading the structure
527
560
  pass
528
- except ExpressionParserError as e:
561
+ except ResolveError as e:
562
+ # E.g. sizeof of an unknown type
563
+ raise self._located(e, tokens[0]) from e
564
+ except (ExpressionParserError, ArithmeticError, ValueError) as e:
529
565
  raise self._error(str(e), token=tokens[0]) from None
530
566
 
531
567
  dimensions.append(count)
@@ -533,8 +569,12 @@ class CStyleParser(Parser):
533
569
  type_ = base_type
534
570
  for count in reversed(dimensions):
535
571
  if issubclass(type_, BaseArray) and count is None:
536
- raise ParserError("Depth required for multi-dimensional array")
537
- type_ = self.cs._make_array(type_, count)
572
+ raise self._error("Depth required for multi-dimensional array", token=start_token)
573
+
574
+ try:
575
+ type_ = self.cs._make_array(type_, count)
576
+ except DefinitionError as e:
577
+ raise self._located(e, start_token) from e
538
578
 
539
579
  return type_
540
580
 
@@ -587,4 +627,7 @@ class CStyleParser(Parser):
587
627
  else:
588
628
  break
589
629
 
590
- return self.cs.resolve(" ".join(parts))
630
+ try:
631
+ return self.cs.resolve(" ".join(parts))
632
+ except ResolveError as e:
633
+ raise self._located(e, first) from e
@@ -2,12 +2,13 @@ from __future__ import annotations
2
2
 
3
3
  import contextlib
4
4
  import functools
5
+ import struct
5
6
  import warnings
6
7
  from io import SEEK_CUR, BytesIO
7
8
  from types import MethodType
8
9
  from typing import TYPE_CHECKING, Any, BinaryIO, ClassVar, TypeVar
9
10
 
10
- from dissect.cstruct.exception import ArraySizeError
11
+ from dissect.cstruct.exception import EOFError, Error, ReadError, WriteError
11
12
  from dissect.cstruct.expression import Expression
12
13
  from dissect.cstruct.util import classproperty, normalize_endianness
13
14
 
@@ -23,6 +24,9 @@ EOF = -0xE0F # Negative counts are illegal anyway, so abuse that for our EOF se
23
24
 
24
25
  _IMMUTABLE_TYPES = (int, float, bytes, str)
25
26
 
27
+ # Errors of values that can't be written, e.g. a number out of range or a missing field of a structure
28
+ _WRITE_ERRORS = (struct.error, OverflowError, TypeError, ValueError, AttributeError)
29
+
26
30
 
27
31
  class MetaType(type):
28
32
  """Base metaclass for cstruct type classes."""
@@ -144,8 +148,17 @@ class MetaType(type):
144
148
  Returns:
145
149
  The amount of bytes written.
146
150
  """
151
+ if not hasattr(stream, "write"):
152
+ raise TypeError("Invalid object type")
153
+
147
154
  endian = normalize_endianness(endian) if endian is not None else cls.__cs__.endian
148
- return cls._write(stream, value, endian=endian)
155
+
156
+ try:
157
+ return cls._write(stream, value, endian=endian)
158
+ except (OSError, Error):
159
+ raise
160
+ except _WRITE_ERRORS as e:
161
+ raise WriteError(f"Cannot write {cls.__name__}: {e}") from e
149
162
 
150
163
  def dumps(cls, value: Any, *, endian: AllowedEndianness | None = None) -> bytes:
151
164
  """Dump a value to a byte string.
@@ -161,7 +174,12 @@ class MetaType(type):
161
174
  endian = normalize_endianness(endian) if endian is not None else cls.__cs__.endian
162
175
 
163
176
  out = BytesIO()
164
- cls._write(out, value, endian=endian)
177
+ try:
178
+ cls._write(out, value, endian=endian)
179
+ except Error:
180
+ raise
181
+ except _WRITE_ERRORS as e:
182
+ raise WriteError(f"Cannot write {cls.__name__}: {e}") from e
165
183
  return out.getvalue()
166
184
 
167
185
  def _read(cls, stream: BinaryIO, *, context: dict[str, Any] | None = None, endian: Endianness) -> Self: # type: ignore
@@ -380,10 +398,14 @@ class BaseArray(BaseType):
380
398
 
381
399
  try:
382
400
  return max(0, cls.__num_entries__.evaluate(cls.__cs__, context))
383
- except Exception:
401
+ except Error:
402
+ # E.g. an unknown identifier, which is also what EOF evaluates to
384
403
  if cls.__num_entries__.expression != "EOF":
385
404
  raise
386
405
  return EOF
406
+ except (ArithmeticError, ValueError) as e:
407
+ # E.g. a division by a field that is zero
408
+ raise ReadError(f"Invalid array size '{cls.__num_entries__.expression}': {e}") from e
387
409
 
388
410
  @classmethod
389
411
  def _write(cls, stream: BinaryIO, data: list[Any], *, endian: Endianness) -> int:
@@ -404,7 +426,7 @@ class BaseArray(BaseType):
404
426
  """
405
427
  if remaining := cls.__num_entries__ - (actual_size := len(data)):
406
428
  if remaining < 0:
407
- raise ArraySizeError(f"Expected static array size {cls.__num_entries__}, got {actual_size} instead.")
429
+ raise WriteError(f"Expected static array size {cls.__num_entries__}, got {actual_size} instead.")
408
430
  data = data + [cls.__type__.__default__()] * remaining
409
431
 
410
432
  return data
@@ -2,7 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  from typing import TYPE_CHECKING, Any, BinaryIO
4
4
 
5
- from dissect.cstruct.exception import ArraySizeError
5
+ from dissect.cstruct.exception import EOFError, WriteError
6
6
  from dissect.cstruct.types.base import EOF, BaseArray, BaseType, _is_seekable, _read_null_terminated
7
7
 
8
8
  if TYPE_CHECKING:
@@ -35,7 +35,7 @@ class CharArray(bytes, BaseArray):
35
35
 
36
36
  if not cls.__dynamic__ and (remaining := cls.__num_entries__ - (actual_size := len(data))):
37
37
  if remaining < 0:
38
- raise ArraySizeError(f"Expected static array size {cls.__num_entries__}, got {actual_size} instead.")
38
+ raise WriteError(f"Expected static array size {cls.__num_entries__}, got {actual_size} instead.")
39
39
  data += b"\x00" * remaining
40
40
 
41
41
  return stream.write(data)
@@ -61,7 +61,11 @@ class Char(bytes, BaseType):
61
61
  if count == 0:
62
62
  return type.__call__(cls, b"")
63
63
 
64
- data = stream.read(-1 if count == EOF else count)
64
+ try:
65
+ data = stream.read(-1 if count == EOF else count)
66
+ except OverflowError:
67
+ raise EOFError(f"Read 0 bytes, but expected {count}") from None
68
+
65
69
  if count != EOF and len(data) != count:
66
70
  raise EOFError(f"Read {len(data)} bytes, but expected {count}")
67
71
 
@@ -94,6 +98,6 @@ class Char(bytes, BaseType):
94
98
  data = data.encode("latin-1")
95
99
 
96
100
  if (actual_size := len(data)) > 1:
97
- raise ValueError(f"Expected a single character, got {actual_size} instead.")
101
+ raise WriteError(f"Expected a single character, got {actual_size} instead.")
98
102
 
99
103
  return stream.write(data or b"\x00")
@@ -4,6 +4,7 @@ import sys
4
4
  from enum import EnumMeta, IntEnum, IntFlag
5
5
  from typing import TYPE_CHECKING, Any, BinaryIO, TypeVar, overload
6
6
 
7
+ from dissect.cstruct.exception import DefinitionError
7
8
  from dissect.cstruct.types.base import BaseType, MetaType
8
9
 
9
10
  if TYPE_CHECKING:
@@ -54,7 +55,7 @@ class EnumMetaType(EnumMeta, MetaType):
54
55
  # cs is the cstruct instance, but we can't isinstance check it due to circular imports
55
56
  cs = value
56
57
  if not issubclass(type_, int):
57
- raise TypeError("Enum can only be created from int type")
58
+ raise DefinitionError("Enum can only be created from int type")
58
59
 
59
60
  enum_cls = super().__call__(name, *args, **kwargs)
60
61
  enum_cls.__cs__ = cs
@@ -3,6 +3,7 @@ from __future__ import annotations
3
3
  import warnings
4
4
  from typing import TYPE_CHECKING, Any, BinaryIO
5
5
 
6
+ from dissect.cstruct.exception import EOFError
6
7
  from dissect.cstruct.types.base import EOF, BaseType, MetaType
7
8
  from dissect.cstruct.util import ENDIANNESS_TO_BYTEORDER_MAP, classproperty
8
9
 
@@ -35,7 +36,12 @@ class Int(int, BaseType):
35
36
 
36
37
  size = cls.__size__
37
38
  length = size * count
38
- data = stream.read(length)
39
+
40
+ try:
41
+ data = stream.read(length)
42
+ except OverflowError:
43
+ raise EOFError(f"Read 0 bytes, but expected {length}") from None
44
+
39
45
  if len(data) != length:
40
46
  raise EOFError(f"Read {len(data) % size} bytes, but expected {size}")
41
47
 
@@ -3,6 +3,7 @@ from __future__ import annotations
3
3
  import warnings
4
4
  from typing import TYPE_CHECKING, Any, BinaryIO
5
5
 
6
+ from dissect.cstruct.exception import EOFError, WriteError
6
7
  from dissect.cstruct.types.base import BaseType
7
8
  from dissect.cstruct.util import classproperty
8
9
 
@@ -56,7 +57,7 @@ class LEB128(int, BaseType):
56
57
  def _write(cls, stream: BinaryIO, data: int, *, endian: Endianness) -> int:
57
58
  # only write negative numbers when in signed mode
58
59
  if data < 0 and not cls.__signed__:
59
- raise ValueError("Attempt to encode a negative integer using unsigned LEB128 encoding")
60
+ raise WriteError("Attempt to encode a negative integer using unsigned LEB128 encoding")
60
61
 
61
62
  result = bytearray()
62
63
  while True:
@@ -4,6 +4,7 @@ import warnings
4
4
  from itertools import repeat
5
5
  from typing import TYPE_CHECKING, Any, BinaryIO, Generic, TypeVar
6
6
 
7
+ from dissect.cstruct.exception import EOFError
7
8
  from dissect.cstruct.types.base import EOF, BaseType, MetaType, _is_buffer_type
8
9
  from dissect.cstruct.util import _struct, classproperty
9
10
 
@@ -65,17 +66,21 @@ class Packed(BaseType, Generic[T], metaclass=PackedMetaType):
65
66
  ) -> list[Self]:
66
67
  if count == EOF:
67
68
  data = stream.read()
68
- length = len(data)
69
- count = length // cls.__size__
69
+ count, remainder = divmod(len(data), cls.__size__)
70
+ if remainder:
71
+ raise EOFError(f"Read {remainder} bytes, but expected {cls.__size__}")
70
72
  else:
71
73
  length = cls.__size__ * count
72
- data = stream.read(length)
73
74
 
74
- fmt = _struct(endian, f"{count}{cls.__fmt__}")
75
+ try:
76
+ data = stream.read(length)
77
+ except OverflowError:
78
+ raise EOFError(f"Read 0 bytes, but expected {length}") from None
75
79
 
76
- if len(data) != length:
77
- raise EOFError(f"Read {len(data)} bytes, but expected {length}")
80
+ if len(data) != length:
81
+ raise EOFError(f"Read {len(data)} bytes, but expected {length}")
78
82
 
83
+ fmt = _struct(endian, f"{count}{cls.__fmt__}")
79
84
  return list(map(cls.__new__, repeat(cls), fmt.unpack(data)))
80
85
 
81
86
  @classmethod
@@ -3,7 +3,7 @@ from __future__ import annotations
3
3
  from functools import cache
4
4
  from typing import TYPE_CHECKING, Any, BinaryIO, Generic, TypeVar
5
5
 
6
- from dissect.cstruct.exception import NullPointerDereference
6
+ from dissect.cstruct.exception import EOFError, NullPointerDereference
7
7
  from dissect.cstruct.types.base import BaseType, normalize_endianness
8
8
  from dissect.cstruct.types.char import Char
9
9
  from dissect.cstruct.types.void import Void
@@ -109,7 +109,11 @@ class Pointer(int, BaseType, Generic[T]):
109
109
  return None
110
110
 
111
111
  position = self.__stream.tell()
112
- self.__stream.seek(self)
112
+
113
+ try:
114
+ self.__stream.seek(self)
115
+ except OverflowError:
116
+ raise EOFError(f"Offset {int(self):#x} is beyond the end of the stream") from None
113
117
 
114
118
  if issubclass(self.__type__, Char):
115
119
  # This makes the assumption that a char pointer is a null-terminated string
@@ -16,6 +16,7 @@ from types import FunctionType
16
16
  from typing import TYPE_CHECKING, Any, BinaryIO
17
17
 
18
18
  from dissect.cstruct.bitbuffer import BitBuffer
19
+ from dissect.cstruct.exception import DefinitionError
19
20
  from dissect.cstruct.expression import Expression
20
21
  from dissect.cstruct.lexer import IDENTIFIER_TYPES
21
22
  from dissect.cstruct.types.base import (
@@ -26,7 +27,10 @@ from dissect.cstruct.types.base import (
26
27
  MetaType,
27
28
  _is_buffer_type,
28
29
  )
30
+ from dissect.cstruct.types.char import Char
29
31
  from dissect.cstruct.types.enum import EnumMetaType
32
+ from dissect.cstruct.types.int import Int
33
+ from dissect.cstruct.types.packed import Packed
30
34
  from dissect.cstruct.types.pointer import Pointer
31
35
  from dissect.cstruct.types.void import Void
32
36
 
@@ -106,7 +110,7 @@ class StructureMetaType(MetaType):
106
110
  static_sizes = {}
107
111
  for field in fields:
108
112
  if field._name in lookup and field._name != "_":
109
- raise ValueError(f"Duplicate field name: {field._name}")
113
+ raise DefinitionError(f"Duplicate field name: {field._name}")
110
114
 
111
115
  if not field.type.__dynamic__:
112
116
  static_sizes[field._name] = field.type.__size__
@@ -189,6 +193,11 @@ class StructureMetaType(MetaType):
189
193
  if isinstance(field_type, EnumMetaType):
190
194
  field_type = field_type.__type__
191
195
 
196
+ if not issubclass(field_type, (Int, Char)) and not (
197
+ issubclass(field_type, Packed) and issubclass(field_type, int)
198
+ ):
199
+ raise DefinitionError(f"Bit fields of type {field.type.__name__} are unsupported")
200
+
192
201
  # Bit fields have special logic
193
202
  if (
194
203
  # Exhausted a bit field
@@ -213,7 +222,7 @@ class StructureMetaType(MetaType):
213
222
  bits_remaining -= field.bits
214
223
 
215
224
  if bits_remaining < 0:
216
- raise ValueError("Straddled bit fields are unsupported")
225
+ raise DefinitionError("Straddled bit fields are unsupported")
217
226
  else:
218
227
  # Reset bits stuff
219
228
  bits_type = None
@@ -3,7 +3,7 @@ from __future__ import annotations
3
3
  import sys
4
4
  from typing import TYPE_CHECKING, Any, BinaryIO, ClassVar
5
5
 
6
- from dissect.cstruct.exception import ArraySizeError
6
+ from dissect.cstruct.exception import EOFError, WriteError
7
7
  from dissect.cstruct.types.base import EOF, BaseArray, BaseType, _is_seekable, _read_null_terminated
8
8
 
9
9
  if TYPE_CHECKING:
@@ -33,7 +33,7 @@ class WcharArray(str, BaseArray):
33
33
  # A surrogate pair is a single character that takes up two entries of the array
34
34
  if not cls.__dynamic__ and (remaining := cls.__num_entries__ - (actual_size := len(buf) // 2)):
35
35
  if remaining < 0:
36
- raise ArraySizeError(f"Expected static array size {cls.__num_entries__}, got {actual_size} instead.")
36
+ raise WriteError(f"Expected static array size {cls.__num_entries__}, got {actual_size} instead.")
37
37
  buf += b"\x00\x00" * remaining
38
38
 
39
39
  return stream.write(buf)
@@ -69,12 +69,20 @@ class Wchar(str, BaseType):
69
69
  if count == 0:
70
70
  return type.__call__(cls, "")
71
71
 
72
- if count != EOF:
73
- count *= 2
72
+ if count == EOF:
73
+ data = stream.read()
74
+ if len(data) % 2:
75
+ raise EOFError("Read 1 bytes, but expected 2")
76
+ else:
77
+ length = count * 2
74
78
 
75
- data = stream.read(-1 if count == EOF else count)
76
- if count != EOF and len(data) != count:
77
- raise EOFError(f"Read {len(data)} bytes, but expected {count}")
79
+ try:
80
+ data = stream.read(length)
81
+ except OverflowError:
82
+ raise EOFError(f"Read 0 bytes, but expected {length}") from None
83
+
84
+ if len(data) != length:
85
+ raise EOFError(f"Read {len(data)} bytes, but expected {length}")
78
86
 
79
87
  return type.__call__(cls, str(data, cls.__encoding_map__[endian], "surrogatepass"))
80
88
 
@@ -103,6 +111,6 @@ class Wchar(str, BaseType):
103
111
 
104
112
  # A surrogate pair is a single character that doesn't fit in a single wchar
105
113
  if (actual_size := len(buf) // 2) > 1:
106
- raise ValueError(f"Expected a single character, got {actual_size} instead.")
114
+ raise WriteError(f"Expected a single character, got {actual_size} instead.")
107
115
 
108
116
  return stream.write(buf or b"\x00\x00")
dissect/cstruct/util.py CHANGED
@@ -279,9 +279,26 @@ def sizeof(type_: type[BaseType] | BaseType) -> int:
279
279
 
280
280
 
281
281
  def offsetof(type_: type[Structure], name: str) -> int:
282
- """Get the offset of a field in a structure."""
283
- if (field := type_.__members__.get(name)) is None:
282
+ """Get the offset of a field in a structure or union, like ``offsetof`` in C.
283
+
284
+ Like in C, the fields of an anonymous nested structure or union are fields of the type that contains it.
285
+ """
286
+ from dissect.cstruct.types.structure import Structure, Union
287
+
288
+ if not issubclass(type_, Structure):
289
+ raise TypeError(f"Type '{type_.__name__}' is not a structure")
290
+ if (member := type_.__members__.get(name)) is None:
284
291
  raise ValueError(f"Structure '{type_.__name__}' does not have a field named '{name}'")
285
- if (offset := field.offset) is None:
286
- raise ValueError(f"Field '{field._name}' of structure '{type_.__name__}' does not have a known offset")
287
- return offset
292
+
293
+ field = next(
294
+ field
295
+ for field in type_.__fields__
296
+ if field is member or (field.name is None and field.type.__members__.get(name) is member)
297
+ )
298
+
299
+ # The fields of a union start at the start of the union, unless they have an offset of their own
300
+ offset = 0 if field.offset is None and issubclass(type_, Union) else field.offset
301
+ if offset is None:
302
+ raise ValueError(f"Field '{name}' of structure '{type_.__name__}' does not have a known offset")
303
+
304
+ return offset if field is member else offset + offsetof(field.type, name)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dissect.cstruct
3
- Version: 5.0.dev21
3
+ Version: 5.0.dev23
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,32 @@
1
+ dissect/cstruct/__init__.py,sha256=6WCBCk9iTJiKjzfkYCZAwWkIh3FnxEuCe_y2TSUJ2bU,1905
2
+ dissect/cstruct/bitbuffer.py,sha256=FpvyoDuio0hLfUtyqb2OUg1SpDVnblxMVNtAbYLPzVk,2781
3
+ dissect/cstruct/compiler.py,sha256=6mK2CdUnfWdQIu0_1qIL1NCaaqlv5eJcvlamMsGfEAg,54781
4
+ dissect/cstruct/cstruct.py,sha256=_oA-nYhaanETPtSyGUpIKKoZ6Rw1PYNmnzLhoQtq2lE,26639
5
+ dissect/cstruct/declarative.py,sha256=GPU208IsslegjFug9udduu-6fhmV2CIfIf6oY76ycEw,14571
6
+ dissect/cstruct/dump.py,sha256=W5ISbaZ-1YmWXKzh-x6pDt5_SlpFRDhD9GGNyv1MnLw,19016
7
+ dissect/cstruct/exception.py,sha256=8b_nLXacWGdQ3BhZN-DOOEr4gp5Vacni6etwDKqYHis,988
8
+ dissect/cstruct/expression.py,sha256=HMDKuZmPElZF88dC6FdEpUO_yUTCSw-WU7wI_XsgYEY,13592
9
+ dissect/cstruct/lexer.py,sha256=INbr9yEVua43VvPmmnWUy392jLgTeLv2-k2M22Pe1zE,20838
10
+ dissect/cstruct/parser.py,sha256=9e1R027YqZw3mhAEORdEzdAUWcifNR3youChwJ_momU,24610
11
+ dissect/cstruct/util.py,sha256=-qBoVSK_uwJ_tFt7bELS-EtipFQ6ebkRZBHAD3iYy5Q,9099
12
+ dissect/cstruct/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
+ dissect/cstruct/tools/stubgen.py,sha256=MeZkLmSeNSLNcAEwlAdIGv1lKvlvK3UQ4WN85ovsxTM,7672
14
+ dissect/cstruct/types/__init__.py,sha256=6P71Pu94Dv7RNjZpDZ19pqzx-G0QzmQw4q0-3zWALso,911
15
+ dissect/cstruct/types/base.py,sha256=tMwLBArs-lsrjr-gyGP4oRKivhF9PFZER8mC92WsFAc,19292
16
+ dissect/cstruct/types/char.py,sha256=CA9-xVA2UbwV3CnfjYOrCIl-Y41QjhJVU4VFn2ZXe3s,3543
17
+ dissect/cstruct/types/enum.py,sha256=H67ACZM3svwySAW4IgstcnqeuGCzmuKIL2IbQV3RgSk,9089
18
+ dissect/cstruct/types/flag.py,sha256=YxQHix8ZhK1qQX3J_Og7GJp_4JAxCwzUbUibuJeDaWQ,3479
19
+ dissect/cstruct/types/int.py,sha256=DBTpQjF6R2zEy0ItXPfO5OHTUwaJqEMTOu7kxuzMGho,2615
20
+ dissect/cstruct/types/leb128.py,sha256=WJ7FQXRsmsdDZJWm2lOe3SEkEJqXfQTIFYpmOajXv0s,2835
21
+ dissect/cstruct/types/packed.py,sha256=sLMrUjRLzlTR4FzRLsPnnAJANhunhUBzbvcMRnGe94A,4181
22
+ dissect/cstruct/types/pointer.py,sha256=pIxiDGosRu1jhchdcA3Zm7yIXkPUh2UKnIt8kxUygf0,4138
23
+ dissect/cstruct/types/structure.py,sha256=T28ZncDWG2QtkQcpKNwfpNmk5_77IgW0idDxHINzcFY,43638
24
+ dissect/cstruct/types/void.py,sha256=fV4hKk50uop_EKbR1nfy1cdtAzvUYrSymXsdakCyFk8,1222
25
+ dissect/cstruct/types/wchar.py,sha256=eJyOWdT8Y3k8gM9QNE0NeXBwcAGRcp4aUkIBezAYe0c,4225
26
+ dissect_cstruct-5.0.dev23.dist-info/licenses/COPYRIGHT,sha256=H-18RXfshdH9AdHwW2eO1Xa-5s6tY5eipHh5c0whDu4,316
27
+ dissect_cstruct-5.0.dev23.dist-info/licenses/LICENSE,sha256=PhUqiw6jAh2KbBdVRPBq_hfAvfcTBin7nZ3CK7NQbTM,11341
28
+ dissect_cstruct-5.0.dev23.dist-info/METADATA,sha256=eQgWU9nvZudjaEMIBnx-wYEeufln_6bTfWhXIwwPyPc,12661
29
+ dissect_cstruct-5.0.dev23.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
30
+ dissect_cstruct-5.0.dev23.dist-info/entry_points.txt,sha256=z53zqZqwD2OLrAkRwrP4wTeiU9CQe7xrMly0T2c0_wQ,71
31
+ dissect_cstruct-5.0.dev23.dist-info/top_level.txt,sha256=Mn-CQzEYsAbkxrUI0TnplHuXnGVKzxpDw_po_sXpvv4,8
32
+ dissect_cstruct-5.0.dev23.dist-info/RECORD,,