dissect.cstruct 5.0.dev25__py3-none-any.whl → 5.0.dev26__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/bitbuffer.py +8 -1
- dissect/cstruct/compiler.py +39 -17
- dissect/cstruct/dump.py +1 -1
- dissect/cstruct/tools/stubgen.py +9 -2
- dissect/cstruct/types/base.py +125 -17
- dissect/cstruct/types/char.py +131 -24
- dissect/cstruct/types/enum.py +2 -1
- dissect/cstruct/types/int.py +7 -0
- dissect/cstruct/types/packed.py +18 -1
- dissect/cstruct/types/pointer.py +16 -12
- dissect/cstruct/types/structure.py +104 -26
- dissect/cstruct/types/void.py +9 -0
- dissect/cstruct/types/wchar.py +98 -13
- {dissect_cstruct-5.0.dev25.dist-info → dissect_cstruct-5.0.dev26.dist-info}/METADATA +41 -8
- dissect_cstruct-5.0.dev26.dist-info/RECORD +32 -0
- dissect_cstruct-5.0.dev25.dist-info/RECORD +0 -32
- {dissect_cstruct-5.0.dev25.dist-info → dissect_cstruct-5.0.dev26.dist-info}/WHEEL +0 -0
- {dissect_cstruct-5.0.dev25.dist-info → dissect_cstruct-5.0.dev26.dist-info}/entry_points.txt +0 -0
- {dissect_cstruct-5.0.dev25.dist-info → dissect_cstruct-5.0.dev26.dist-info}/licenses/COPYRIGHT +0 -0
- {dissect_cstruct-5.0.dev25.dist-info → dissect_cstruct-5.0.dev26.dist-info}/licenses/LICENSE +0 -0
- {dissect_cstruct-5.0.dev25.dist-info → dissect_cstruct-5.0.dev26.dist-info}/top_level.txt +0 -0
dissect/cstruct/bitbuffer.py
CHANGED
|
@@ -73,7 +73,14 @@ class BitBuffer:
|
|
|
73
73
|
|
|
74
74
|
def flush(self) -> None:
|
|
75
75
|
if self._type is not None:
|
|
76
|
-
|
|
76
|
+
buffer = self._buffer
|
|
77
|
+
if issubclass(self._type, bytes):
|
|
78
|
+
if self.endian == "<":
|
|
79
|
+
buffer = buffer.to_bytes(self._type.__size__, "little")
|
|
80
|
+
else:
|
|
81
|
+
buffer = buffer.to_bytes(self._type.__size__, "big")
|
|
82
|
+
|
|
83
|
+
self._type._write(self.stream, buffer, endian=self.endian)
|
|
77
84
|
self._type = None
|
|
78
85
|
self._remaining = 0
|
|
79
86
|
self._buffer = 0
|
dissect/cstruct/compiler.py
CHANGED
|
@@ -37,7 +37,13 @@ from dissect.cstruct.types import (
|
|
|
37
37
|
WcharArray,
|
|
38
38
|
)
|
|
39
39
|
from dissect.cstruct.types.enum import EnumMetaType
|
|
40
|
-
from dissect.cstruct.types.structure import
|
|
40
|
+
from dissect.cstruct.types.structure import (
|
|
41
|
+
StructureMetaType,
|
|
42
|
+
UnionMetaType,
|
|
43
|
+
UnionProxy,
|
|
44
|
+
_uses_generated_init,
|
|
45
|
+
_value_type,
|
|
46
|
+
)
|
|
41
47
|
from dissect.cstruct.util import ENDIANNESS_TO_BYTEORDER_MAP, _struct
|
|
42
48
|
|
|
43
49
|
if TYPE_CHECKING:
|
|
@@ -216,15 +222,15 @@ _PACKABLE_TYPES = (Array, Char, CharArray, Int, Packed, Pointer, Void, VoidArray
|
|
|
216
222
|
|
|
217
223
|
def _field_bytes(type_: type[BaseType], value: Any, endian: str) -> bytes:
|
|
218
224
|
"""Return the bytes of a char or wchar field that isn't of the right type yet or doesn't fit."""
|
|
219
|
-
|
|
220
|
-
if len(buf) > type_.__size__:
|
|
225
|
+
type_._write(out := io.BytesIO(), type_.__default__() if value is None else value, endian=endian)
|
|
226
|
+
if len(buf := out.getvalue()) > type_.__size__:
|
|
221
227
|
raise WriteError(f"Expected {type_.__size__} bytes for {type_.__name__}, got {len(buf)} instead.")
|
|
222
228
|
return buf
|
|
223
229
|
|
|
224
230
|
|
|
225
231
|
def _array_values(type_: type[Array], value: list[Any] | None) -> list[Any]:
|
|
226
|
-
"""Return the values of an array field that
|
|
227
|
-
return type_.__default__() if value is None else type_.
|
|
232
|
+
"""Return the values of an array field that isn't a list of the right size yet."""
|
|
233
|
+
return type_.__default__() if value is None else type_._entries(value)
|
|
228
234
|
|
|
229
235
|
|
|
230
236
|
def _or_default(value: Any, type_: type[BaseType]) -> Any:
|
|
@@ -235,6 +241,8 @@ def _or_default(value: Any, type_: type[BaseType]) -> Any:
|
|
|
235
241
|
# Globals that are available to all generated functions
|
|
236
242
|
_GLOBALS = {
|
|
237
243
|
"_type_call": type.__call__,
|
|
244
|
+
"_bytes_new": bytes.__new__,
|
|
245
|
+
"_str_new": str.__new__,
|
|
238
246
|
"_object_new": object.__new__,
|
|
239
247
|
"_setattr": setattr,
|
|
240
248
|
"_repeat": repeat,
|
|
@@ -412,6 +420,15 @@ class _ReadSourceGenerator(_SourceGenerator):
|
|
|
412
420
|
outro.append(f" obj.__dynamic_sizes__ = {sizes}")
|
|
413
421
|
outro.append(" return obj")
|
|
414
422
|
|
|
423
|
+
# Subclasses without their own __init__ or __new__ inherit __construct__, which also bypasses __init__
|
|
424
|
+
# It has a parameter for each field name, like the keyword arguments below
|
|
425
|
+
construct = self._add_symbol(self.cls.__construct__, "construct")
|
|
426
|
+
values = "".join(f", {var}" for var in dict(self._assigned).values())
|
|
427
|
+
outro.append(f"if cls.__construct__ is {construct}:")
|
|
428
|
+
outro.append(f" obj = {construct}(cls{values})")
|
|
429
|
+
outro.append(f" obj.__dynamic_sizes__ = {sizes}")
|
|
430
|
+
outro.append(" return obj")
|
|
431
|
+
|
|
415
432
|
# Using type.__call__ directly calls the __init__ method of the class
|
|
416
433
|
outro.append(f"obj = _type_call(cls, **{{{kwargs}}})")
|
|
417
434
|
outro.append(f"obj.__dynamic_sizes__ = {sizes}")
|
|
@@ -571,7 +588,16 @@ class _ReadSourceGenerator(_SourceGenerator):
|
|
|
571
588
|
lines.append("except _Error: raise")
|
|
572
589
|
lines.append(f"except (ArithmeticError, ValueError) as e: raise _ReadError({message!r} + str(e)) from e")
|
|
573
590
|
element = self._type_symbol(field.type.__type__)
|
|
574
|
-
|
|
591
|
+
entries = f"{element}._read_array(stream, _count, context={context}, endian=endian)"
|
|
592
|
+
|
|
593
|
+
# Create char and wchar arrays without the checks of their constructor
|
|
594
|
+
if issubclass(field.type, CharArray):
|
|
595
|
+
return f"_bytes_new({type_}, {entries})"
|
|
596
|
+
|
|
597
|
+
if issubclass(field.type, WcharArray):
|
|
598
|
+
return f"_str_new({type_}, {entries})"
|
|
599
|
+
|
|
600
|
+
return f"_type_call({type_}, {entries})"
|
|
575
601
|
|
|
576
602
|
def _generate_bits_source(self, field: Field) -> Iterator[str]:
|
|
577
603
|
"""Generate the code for reading a bit field."""
|
|
@@ -594,7 +620,7 @@ class _ReadSourceGenerator(_SourceGenerator):
|
|
|
594
620
|
lines.append(f"else: _bit_value = (_bit_buffer >> {remaining - field.bits}) & {mask}")
|
|
595
621
|
|
|
596
622
|
# Character bit fields are returned as the integer type they're read as
|
|
597
|
-
type_ = self._type_symbol(
|
|
623
|
+
type_ = self._type_symbol(_value_type(field))
|
|
598
624
|
|
|
599
625
|
if issubclass(field.type, (Enum, Flag)):
|
|
600
626
|
lines.append(_member_lookup(type_, "_bit_value"))
|
|
@@ -747,14 +773,14 @@ class _ReadSourceGenerator(_SourceGenerator):
|
|
|
747
773
|
|
|
748
774
|
lines.extend(target(field, f"_type_call({array}, {value})"))
|
|
749
775
|
|
|
750
|
-
elif issubclass(field_type, CharArray):
|
|
751
|
-
lines.extend(target(field, f"
|
|
776
|
+
elif issubclass(field_type, (Char, CharArray)):
|
|
777
|
+
lines.extend(target(field, f"_bytes_new({self._type_symbol(field.type)}, {getter})"))
|
|
752
778
|
|
|
753
779
|
elif issubclass(field_type, WcharArray) or issubclass(read_type, Wchar):
|
|
754
780
|
encoding = self._add_symbol(read_type.__encoding_map__, "encoding")
|
|
755
|
-
#
|
|
781
|
+
# Decoding like str() instead of .decode() also supports other bytes-like objects returned by the stream
|
|
756
782
|
type_ = self._type_symbol(field.type)
|
|
757
|
-
lines.extend(target(field, f"
|
|
783
|
+
lines.extend(target(field, f"_str_new({type_}, {getter}, {encoding}[endian], 'surrogatepass')"))
|
|
758
784
|
|
|
759
785
|
elif issubclass(field_type, Pointer):
|
|
760
786
|
context = self._context(lines)
|
|
@@ -1051,7 +1077,8 @@ class _WriteSourceGenerator(_SourceGenerator):
|
|
|
1051
1077
|
var = self._var("value")
|
|
1052
1078
|
num = field_type.__num_entries__
|
|
1053
1079
|
pack.lines.append(
|
|
1054
|
-
f"if ({var} := {value})
|
|
1080
|
+
f"if not isinstance({var} := {value}, list) or len({var}) != {num}: "
|
|
1081
|
+
f"{var} = _array_values({type_}, {var})"
|
|
1055
1082
|
)
|
|
1056
1083
|
|
|
1057
1084
|
# Entries can be enum members or plain integers, both can be packed as they are
|
|
@@ -1178,11 +1205,6 @@ def _can_inline_fields(fields: list[Field], size: int, is_union: bool, in_union:
|
|
|
1178
1205
|
return True
|
|
1179
1206
|
|
|
1180
1207
|
|
|
1181
|
-
def _uses_generated_init(type_: type[Structure]) -> bool:
|
|
1182
|
-
"""Return whether a structure type uses a generated ``__init__``, so we can bypass it by setting attributes."""
|
|
1183
|
-
return "__init__" in type_.__dict__ and type_.__new__ is object.__new__
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
1208
|
def _can_pack(type_: type[BaseType]) -> bool:
|
|
1187
1209
|
"""Determine if a value of a type can be written by packing it, instead of by using the ``_write`` method."""
|
|
1188
1210
|
if type_.__size__ is None:
|
dissect/cstruct/dump.py
CHANGED
|
@@ -465,7 +465,7 @@ def dumpstruct(
|
|
|
465
465
|
raise ValueError(f"Invalid output argument: {output!r} (should be 'print', 'string', 'dict' or 'json').")
|
|
466
466
|
|
|
467
467
|
if isinstance(obj, Structure):
|
|
468
|
-
data = obj
|
|
468
|
+
data = bytes(obj) if data is None else data
|
|
469
469
|
elif isinstance(obj, type) and issubclass(obj, Structure) and data is not None:
|
|
470
470
|
obj = obj(data)
|
|
471
471
|
else:
|
dissect/cstruct/tools/stubgen.py
CHANGED
|
@@ -158,7 +158,12 @@ def generate_structure_stub(
|
|
|
158
158
|
result = [f"class {name_prefix}{structure.__name__}({module_prefix}{structure.__base__.__name__}):"]
|
|
159
159
|
indent = " " * 4
|
|
160
160
|
|
|
161
|
-
|
|
161
|
+
# Fields can be named self, so prefix until there's no longer a clash
|
|
162
|
+
instance = "self"
|
|
163
|
+
while instance in structure.__members__:
|
|
164
|
+
instance = f"_{instance}"
|
|
165
|
+
|
|
166
|
+
args = [instance, "/"]
|
|
162
167
|
for field_name, field in structure.__members__.items():
|
|
163
168
|
inlined = False
|
|
164
169
|
|
|
@@ -182,7 +187,9 @@ def generate_structure_stub(
|
|
|
182
187
|
result.append(textwrap.indent(f"def __init__({', '.join(args)}): ...", prefix=indent))
|
|
183
188
|
result.append(textwrap.indent("@overload", prefix=indent))
|
|
184
189
|
result.append(
|
|
185
|
-
textwrap.indent(
|
|
190
|
+
textwrap.indent(
|
|
191
|
+
f"def __init__({instance}, fh: bytes | memoryview | bytearray | BinaryIO, /): ...", prefix=indent
|
|
192
|
+
)
|
|
186
193
|
)
|
|
187
194
|
result.append("")
|
|
188
195
|
return "\n".join(result)
|
dissect/cstruct/types/base.py
CHANGED
|
@@ -3,6 +3,7 @@ from __future__ import annotations
|
|
|
3
3
|
import contextlib
|
|
4
4
|
import functools
|
|
5
5
|
import struct
|
|
6
|
+
import sys
|
|
6
7
|
import warnings
|
|
7
8
|
from io import SEEK_CUR, BytesIO
|
|
8
9
|
from types import MethodType
|
|
@@ -44,17 +45,23 @@ class MetaType(type):
|
|
|
44
45
|
__ArrayType__: type[BaseArray] = "Array"
|
|
45
46
|
"""The array type for this type class."""
|
|
46
47
|
|
|
47
|
-
def __call__(cls, *args, **kwargs) -> Self: # type: ignore
|
|
48
|
-
"""
|
|
48
|
+
def __call__(cls, /, *args, **kwargs) -> Self: # type: ignore
|
|
49
|
+
"""Create a value of this type like its Python base type does, or parse it from data.
|
|
50
|
+
|
|
51
|
+
A bytes-like or file-like object is parsed, e.g. ``uint16(b"\\x01\\x00")`` is 1. Other values are given to the
|
|
52
|
+
Python base type, e.g. ``uint16("1")`` is 1 like ``int("1")``. Some types have exceptions, e.g. ``char(0x41)``
|
|
53
|
+
is ``b"A"``.
|
|
54
|
+
"""
|
|
49
55
|
if len(args) == 1 and not kwargs:
|
|
50
56
|
# Fast path for the most common case without keyword arguments
|
|
51
57
|
obj = args[0]
|
|
52
58
|
if type(obj) in _BUFFER_TYPES:
|
|
53
|
-
if len(obj) == cls.__size__ and isinstance(obj, bytes) and issubclass(cls, bytes):
|
|
54
|
-
# Shortcut for char/bytes type
|
|
55
|
-
return type.__call__(cls, obj)
|
|
56
59
|
return cls._read(BytesIO(obj), endian=cls.__cs__.endian)
|
|
57
60
|
|
|
61
|
+
if isinstance(obj, int):
|
|
62
|
+
# E.g. uint32(1)
|
|
63
|
+
return type.__call__(cls, obj)
|
|
64
|
+
|
|
58
65
|
if hasattr(obj, "read") and not isinstance(obj, cls):
|
|
59
66
|
return cls._read(obj, endian=cls.__cs__.endian)
|
|
60
67
|
|
|
@@ -69,10 +76,6 @@ class MetaType(type):
|
|
|
69
76
|
)
|
|
70
77
|
return cls._read(obj, endian=endian)
|
|
71
78
|
|
|
72
|
-
if isinstance(obj, bytes) and len(obj) == cls.__size__ and issubclass(cls, bytes):
|
|
73
|
-
# Shortcut for char/bytes type
|
|
74
|
-
return type.__call__(cls, *args, **kwargs)
|
|
75
|
-
|
|
76
79
|
if _is_buffer_type(obj):
|
|
77
80
|
return cls.reads(obj, endian=kwargs.get("endian"))
|
|
78
81
|
|
|
@@ -102,6 +105,23 @@ class MetaType(type):
|
|
|
102
105
|
"""Return the default value of this type."""
|
|
103
106
|
return cls()
|
|
104
107
|
|
|
108
|
+
def _normalize(cls, value: Any) -> Any:
|
|
109
|
+
"""Internal function for converting a value that is given to a field of this type when a structure is created.
|
|
110
|
+
|
|
111
|
+
Calls the type, so a field accepts the same values, e.g. ``uint16("1")`` and ``uint16(b"\\x01\\x00")``.
|
|
112
|
+
More bytes than the type needs raise a ``ValueError``, e.g. ``b"\\x01\\x00\\x02"`` for a ``uint16`` field.
|
|
113
|
+
|
|
114
|
+
Args:
|
|
115
|
+
value: The value to convert, never ``None``.
|
|
116
|
+
"""
|
|
117
|
+
if isinstance(value, _BUFFER_TYPES):
|
|
118
|
+
stream = BytesIO(value)
|
|
119
|
+
result = cls._read(stream, endian=cls.__cs__.endian)
|
|
120
|
+
if (size := stream.tell()) != len(value):
|
|
121
|
+
raise ValueError(f"Expected {size} bytes for {cls.__name__}, got {len(value)} instead.")
|
|
122
|
+
return result
|
|
123
|
+
return cls(value)
|
|
124
|
+
|
|
105
125
|
def reads(cls, data: bytes | memoryview | bytearray, *, endian: AllowedEndianness | None = None) -> Self: # type: ignore
|
|
106
126
|
"""Parse the given data from a bytes-like object.
|
|
107
127
|
|
|
@@ -334,10 +354,22 @@ class _overload:
|
|
|
334
354
|
|
|
335
355
|
|
|
336
356
|
def _instance_dumps(self: BaseType, *, endian: AllowedEndianness | None = None) -> bytes:
|
|
357
|
+
warnings.warn(
|
|
358
|
+
"The 'dumps' method on instances is deprecated, use 'bytes(obj)' instead, or 'cls.dumps(obj)' to include the"
|
|
359
|
+
" null terminator of a null-terminated array.",
|
|
360
|
+
DeprecationWarning,
|
|
361
|
+
stacklevel=2,
|
|
362
|
+
)
|
|
337
363
|
return MetaType.dumps(self.__class__, self, endian=endian)
|
|
338
364
|
|
|
339
365
|
|
|
340
366
|
def _instance_write(self: BaseType, stream: BinaryIO, *, endian: AllowedEndianness | None = None) -> int:
|
|
367
|
+
warnings.warn(
|
|
368
|
+
"The 'write' method on instances is deprecated, use 'stream.write(bytes(obj))' instead, or"
|
|
369
|
+
" 'cls.write(stream, obj)' to include the null terminator of a null-terminated array.",
|
|
370
|
+
DeprecationWarning,
|
|
371
|
+
stacklevel=2,
|
|
372
|
+
)
|
|
341
373
|
return MetaType.write(self.__class__, stream, self, endian=endian)
|
|
342
374
|
|
|
343
375
|
|
|
@@ -354,6 +386,15 @@ class BaseType(metaclass=MetaType):
|
|
|
354
386
|
|
|
355
387
|
return self.__class__.__size__
|
|
356
388
|
|
|
389
|
+
def __bytes__(self) -> bytes:
|
|
390
|
+
return MetaType.dumps(self.__class__, self)
|
|
391
|
+
|
|
392
|
+
if sys.version_info >= (3, 12):
|
|
393
|
+
# The buffer protocol of Python classes, so that e.g. ``fh.write(obj)`` works, needs Python 3.12 or newer.
|
|
394
|
+
# It gives the same bytes as ``bytes(obj)``.
|
|
395
|
+
def __buffer__(self, flags: int) -> memoryview:
|
|
396
|
+
return memoryview(bytes(self))
|
|
397
|
+
|
|
357
398
|
|
|
358
399
|
T = TypeVar("T", bound=BaseType)
|
|
359
400
|
|
|
@@ -409,25 +450,31 @@ class BaseArray(BaseType):
|
|
|
409
450
|
|
|
410
451
|
@classmethod
|
|
411
452
|
def _write(cls, stream: BinaryIO, data: list[Any], *, endian: Endianness) -> int:
|
|
453
|
+
if not isinstance(data, list) or (isinstance(cls.__num_entries__, int) and len(data) != cls.__num_entries__):
|
|
454
|
+
# E.g. a tuple, or a list of another size
|
|
455
|
+
data = cls._entries(data)
|
|
456
|
+
|
|
412
457
|
if cls.__null_terminated__:
|
|
413
458
|
return cls.__type__._write_0(stream, data, endian=endian)
|
|
414
459
|
|
|
415
|
-
if not cls.__dynamic__:
|
|
416
|
-
data = cls._pad(data)
|
|
417
|
-
|
|
418
460
|
return cls.__type__._write_array(stream, data, endian=endian)
|
|
419
461
|
|
|
420
462
|
@classmethod
|
|
421
|
-
def
|
|
422
|
-
"""Internal function for
|
|
463
|
+
def _entries(cls, data: list[Any] | tuple[Any, ...]) -> list[Any] | tuple[Any, ...]:
|
|
464
|
+
"""Internal function for checking the entries of an array, and padding them to its fixed number of entries.
|
|
423
465
|
|
|
424
466
|
Args:
|
|
425
467
|
data: The entries of the array.
|
|
426
468
|
"""
|
|
427
|
-
if
|
|
469
|
+
if not isinstance(data, (list, tuple)):
|
|
470
|
+
# E.g. bytes, which aren't converted to entries
|
|
471
|
+
raise TypeError(f"Expected a list, got {type(data).__name__}")
|
|
472
|
+
|
|
473
|
+
# Also an array of entries with a dynamic size, e.g. LEB128 or a structure, has a fixed number of entries
|
|
474
|
+
if isinstance(cls.__num_entries__, int) and (remaining := cls.__num_entries__ - (actual_size := len(data))):
|
|
428
475
|
if remaining < 0:
|
|
429
476
|
raise WriteError(f"Expected static array size {cls.__num_entries__}, got {actual_size} instead.")
|
|
430
|
-
data = data
|
|
477
|
+
data = [*data, *[cls.__type__.__default__()] * remaining]
|
|
431
478
|
|
|
432
479
|
return data
|
|
433
480
|
|
|
@@ -462,7 +509,68 @@ class BaseArray(BaseType):
|
|
|
462
509
|
return cls.__null_terminated__
|
|
463
510
|
|
|
464
511
|
|
|
465
|
-
class
|
|
512
|
+
class ArrayMetaType(MetaType):
|
|
513
|
+
"""Metaclass for array types."""
|
|
514
|
+
|
|
515
|
+
def __call__(cls, *args, **kwargs) -> Array:
|
|
516
|
+
if len(args) == 1 and not kwargs:
|
|
517
|
+
# Handle a few fast path cases
|
|
518
|
+
obj = args[0]
|
|
519
|
+
if hasattr(obj, "read") and not isinstance(obj, cls):
|
|
520
|
+
# E.g. uint8[4](fh)
|
|
521
|
+
return cls._read(obj, endian=cls.__cs__.endian)
|
|
522
|
+
|
|
523
|
+
if type(obj) in _BUFFER_TYPES:
|
|
524
|
+
# E.g. uint8[4](b"\x01\x02\x03\x04")
|
|
525
|
+
return cls._read(BytesIO(obj), endian=cls.__cs__.endian)
|
|
526
|
+
|
|
527
|
+
if not isinstance(obj, (list, tuple)):
|
|
528
|
+
# E.g. uint8[4](x for x in range(4))
|
|
529
|
+
if isinstance(obj, _BUFFER_TYPES):
|
|
530
|
+
# E.g. uint8[4](char[4](b"abcd"))
|
|
531
|
+
return cls._read(BytesIO(obj), endian=cls.__cs__.endian)
|
|
532
|
+
|
|
533
|
+
# list() would give the characters of a string, and a less clear error for an int
|
|
534
|
+
if isinstance(obj, (int, str)):
|
|
535
|
+
# E.g. uint8[4]("ab")
|
|
536
|
+
raise TypeError(f"Cannot create {cls.__name__} from {type(obj).__name__}")
|
|
537
|
+
|
|
538
|
+
# E.g. a generator, which has no length
|
|
539
|
+
obj = list(obj)
|
|
540
|
+
|
|
541
|
+
# E.g. initializing with a list-like
|
|
542
|
+
# Pad to the correct number of entries if the given value is too short
|
|
543
|
+
if isinstance(num_entries := cls.__num_entries__, int) and (actual_size := len(obj)) != num_entries:
|
|
544
|
+
# E.g. uint8[4]([1, 2])
|
|
545
|
+
if actual_size > num_entries:
|
|
546
|
+
# E.g. uint8[2]([1, 2, 3])
|
|
547
|
+
raise ValueError(f"Expected static array size {num_entries}, got {actual_size} instead.")
|
|
548
|
+
|
|
549
|
+
# Fill the default value, so that mutable entries like structures aren't shared
|
|
550
|
+
result = cls.__default__()
|
|
551
|
+
result[:actual_size] = obj
|
|
552
|
+
return result
|
|
553
|
+
|
|
554
|
+
return type.__call__(cls, obj)
|
|
555
|
+
|
|
556
|
+
if not args and not kwargs:
|
|
557
|
+
# Default value
|
|
558
|
+
# E.g. uint8[4]()
|
|
559
|
+
return cls.__default__()
|
|
560
|
+
|
|
561
|
+
# Everything else
|
|
562
|
+
# E.g. uint8[4](b"\x01\x02\x03\x04", endian=">")
|
|
563
|
+
return MetaType.__call__(cls, *args, **kwargs)
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
class Array(list[T], BaseArray, metaclass=ArrayMetaType):
|
|
567
|
+
def __bytes__(self) -> bytes:
|
|
568
|
+
# The byte representation of a null-terminated array doesn't include the null terminator.
|
|
569
|
+
if self.__null_terminated__:
|
|
570
|
+
return MetaType.dumps(self.__type__[len(self)], self)
|
|
571
|
+
|
|
572
|
+
return MetaType.dumps(self.__class__, self)
|
|
573
|
+
|
|
466
574
|
@classmethod
|
|
467
575
|
def _read(cls, stream: BinaryIO, *, context: dict[str, Any] | None = None, endian: Endianness) -> list[T]:
|
|
468
576
|
return type.__call__(cls, super()._read(stream, context=context, endian=endian))
|
dissect/cstruct/types/char.py
CHANGED
|
@@ -1,34 +1,125 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
+
from io import BytesIO
|
|
3
4
|
from typing import TYPE_CHECKING, Any, BinaryIO
|
|
4
5
|
|
|
5
6
|
from dissect.cstruct.exception import EOFError, WriteError
|
|
6
|
-
from dissect.cstruct.types.base import
|
|
7
|
+
from dissect.cstruct.types.base import (
|
|
8
|
+
_BUFFER_TYPES,
|
|
9
|
+
EOF,
|
|
10
|
+
BaseArray,
|
|
11
|
+
BaseType,
|
|
12
|
+
MetaType,
|
|
13
|
+
_is_buffer_type,
|
|
14
|
+
_is_seekable,
|
|
15
|
+
_read_null_terminated,
|
|
16
|
+
)
|
|
7
17
|
|
|
8
18
|
if TYPE_CHECKING:
|
|
19
|
+
from collections.abc import Iterable
|
|
20
|
+
|
|
9
21
|
from typing_extensions import Self
|
|
10
22
|
|
|
11
23
|
from dissect.cstruct.cstruct import Endianness
|
|
12
24
|
|
|
13
25
|
|
|
14
|
-
class
|
|
26
|
+
class CharMetaType(MetaType):
|
|
27
|
+
"""Metaclass for character and character array types."""
|
|
28
|
+
|
|
29
|
+
def __call__(cls, *args, **kwargs) -> Char | CharArray:
|
|
30
|
+
if len(args) == 1 and not kwargs:
|
|
31
|
+
# Handle a few fast path cases
|
|
32
|
+
obj = args[0]
|
|
33
|
+
if isinstance(obj, bytes):
|
|
34
|
+
if len(obj) == (size := cls.__size__):
|
|
35
|
+
# E.g. char[4](b"abcd")
|
|
36
|
+
return bytes.__new__(cls, obj)
|
|
37
|
+
|
|
38
|
+
# Take the data up to the static size
|
|
39
|
+
if size is not None:
|
|
40
|
+
if len(obj) < size:
|
|
41
|
+
# E.g. char[4](b"ab")
|
|
42
|
+
raise EOFError(f"Read {len(obj)} bytes, but expected {size}")
|
|
43
|
+
|
|
44
|
+
# E.g. char[4](b"abcdef")
|
|
45
|
+
return bytes.__new__(cls, obj[:size])
|
|
46
|
+
|
|
47
|
+
if isinstance(obj, list) and len(obj) == cls.__size__:
|
|
48
|
+
# E.g. char[2]([1, 2])
|
|
49
|
+
return bytes.__new__(cls, obj)
|
|
50
|
+
|
|
51
|
+
if isinstance(obj, (int, list)):
|
|
52
|
+
# E.g. char(0x41) or char[4]([1, 2])
|
|
53
|
+
return cls.__new__(cls, obj)
|
|
54
|
+
|
|
55
|
+
if type(obj) in _BUFFER_TYPES:
|
|
56
|
+
# E.g. char[None](b"ab\x00") or char[4](bytearray(b"abcd"))
|
|
57
|
+
return cls._read(BytesIO(obj), endian=cls.__cs__.endian)
|
|
58
|
+
|
|
59
|
+
if hasattr(obj, "read") and not isinstance(obj, cls):
|
|
60
|
+
# E.g. char[4](fh)
|
|
61
|
+
return cls._read(obj, endian=cls.__cs__.endian)
|
|
62
|
+
|
|
63
|
+
if not _is_buffer_type(obj):
|
|
64
|
+
# E.g. char[4]((1, 2))
|
|
65
|
+
return cls.__new__(cls, obj)
|
|
66
|
+
|
|
67
|
+
elif not args and not kwargs:
|
|
68
|
+
# Default value
|
|
69
|
+
# E.g. char[4]()
|
|
70
|
+
return cls.__default__()
|
|
71
|
+
|
|
72
|
+
# Everything else
|
|
73
|
+
# E.g. char[4](b"abcd", endian=">")
|
|
74
|
+
return MetaType.__call__(cls, *args, **kwargs)
|
|
75
|
+
|
|
76
|
+
def _normalize(cls, value: Any) -> Char | CharArray:
|
|
77
|
+
if isinstance(value, _BUFFER_TYPES):
|
|
78
|
+
# The bytes of a char field are its value, e.g. b"ab" is b"ab\x00\x00" for a char[4] field
|
|
79
|
+
return cls.__new__(cls, value)
|
|
80
|
+
return cls(value)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class CharArray(bytes, BaseArray, metaclass=CharMetaType):
|
|
15
84
|
"""Character array type for reading and writing byte strings."""
|
|
16
85
|
|
|
86
|
+
def __new__(cls, value: bytes | bytearray | memoryview | Iterable[int]) -> Self:
|
|
87
|
+
if isinstance(value, int):
|
|
88
|
+
raise TypeError(f"Cannot create {cls.__name__} from {type(value).__name__}")
|
|
89
|
+
|
|
90
|
+
if isinstance(value, str):
|
|
91
|
+
raise TypeError(f"Cannot create {cls.__name__} from {type(value).__name__}, encode to bytes first")
|
|
92
|
+
|
|
93
|
+
result = bytes.__new__(cls, value)
|
|
94
|
+
|
|
95
|
+
if not cls.__dynamic__ and (remaining := cls.__num_entries__ - (actual_size := len(result))):
|
|
96
|
+
if remaining < 0:
|
|
97
|
+
raise ValueError(f"Expected static array size {cls.__num_entries__}, got {actual_size} instead.")
|
|
98
|
+
result = bytes.__new__(cls, result + b"\x00" * remaining)
|
|
99
|
+
|
|
100
|
+
return result
|
|
101
|
+
|
|
102
|
+
def __bytes__(self) -> bytes:
|
|
103
|
+
# A char array is a bytes object, so give its content without the null terminator, like bytes does.
|
|
104
|
+
# Python 3.11 and newer use bytes.__bytes__ without this, but 3.10 would use BaseType.__bytes__.
|
|
105
|
+
return bytes(memoryview(self))
|
|
106
|
+
|
|
17
107
|
@classmethod
|
|
18
108
|
def __default__(cls) -> Self:
|
|
19
|
-
return
|
|
109
|
+
return bytes.__new__(cls, b"\x00" * (0 if cls.__dynamic__ or cls.__null_terminated__ else cls.__num_entries__))
|
|
20
110
|
|
|
21
111
|
@classmethod
|
|
22
112
|
def _read(cls, stream: BinaryIO, *, context: dict[str, Any] | None = None, endian: Endianness) -> Self:
|
|
23
|
-
return
|
|
113
|
+
return bytes.__new__(cls, super()._read(stream, context=context, endian=endian))
|
|
24
114
|
|
|
25
115
|
@classmethod
|
|
26
|
-
def _write(cls, stream: BinaryIO, data: bytes | bytearray |
|
|
27
|
-
#
|
|
28
|
-
if isinstance(data, (
|
|
116
|
+
def _write(cls, stream: BinaryIO, data: bytes | bytearray | memoryview, *, endian: Endianness) -> int:
|
|
117
|
+
# Convert other bytes-like data to bytes, so adding the null terminator and padding doesn't modify it in place
|
|
118
|
+
if isinstance(data, (bytearray, memoryview)):
|
|
29
119
|
data = bytes(data)
|
|
30
|
-
elif isinstance(data,
|
|
31
|
-
|
|
120
|
+
elif not isinstance(data, bytes):
|
|
121
|
+
hint = ", encode to bytes first" if isinstance(data, str) else ""
|
|
122
|
+
raise TypeError(f"Expected bytes, got {type(data).__name__}{hint}")
|
|
32
123
|
|
|
33
124
|
if cls.__null_terminated__:
|
|
34
125
|
data += b"\x00"
|
|
@@ -41,25 +132,43 @@ class CharArray(bytes, BaseArray):
|
|
|
41
132
|
return stream.write(data)
|
|
42
133
|
|
|
43
134
|
|
|
44
|
-
class Char(bytes, BaseType):
|
|
135
|
+
class Char(bytes, BaseType, metaclass=CharMetaType):
|
|
45
136
|
"""Character type for reading and writing bytes."""
|
|
46
137
|
|
|
47
138
|
__ArrayType__ = CharArray
|
|
48
139
|
|
|
140
|
+
def __new__(cls, value: bytes | int | Iterable[int]) -> Self:
|
|
141
|
+
# Convert an int to a single character
|
|
142
|
+
if isinstance(value, int):
|
|
143
|
+
return bytes.__new__(cls, (value,))
|
|
144
|
+
|
|
145
|
+
if isinstance(value, str):
|
|
146
|
+
raise TypeError(f"Cannot create {cls.__name__} from {type(value).__name__}, encode to bytes first")
|
|
147
|
+
|
|
148
|
+
result = bytes.__new__(cls, value)
|
|
149
|
+
|
|
150
|
+
if (actual_size := len(result)) > 1:
|
|
151
|
+
raise ValueError(f"Expected a single character, got {actual_size} instead.")
|
|
152
|
+
|
|
153
|
+
return result or cls.__default__()
|
|
154
|
+
|
|
155
|
+
def __bytes__(self) -> bytes:
|
|
156
|
+
return bytes(memoryview(self))
|
|
157
|
+
|
|
49
158
|
@classmethod
|
|
50
159
|
def __default__(cls) -> Self:
|
|
51
|
-
return
|
|
160
|
+
return bytes.__new__(cls, b"\x00")
|
|
52
161
|
|
|
53
162
|
@classmethod
|
|
54
163
|
def _read(cls, stream: BinaryIO, *, context: dict[str, Any] | None = None, endian: Endianness) -> Self:
|
|
55
|
-
return cls._read_array(stream, 1, context=context, endian=endian)
|
|
164
|
+
return bytes.__new__(cls, cls._read_array(stream, 1, context=context, endian=endian))
|
|
56
165
|
|
|
57
166
|
@classmethod
|
|
58
167
|
def _read_array(
|
|
59
168
|
cls, stream: BinaryIO, count: int, *, context: dict[str, Any] | None = None, endian: Endianness
|
|
60
|
-
) ->
|
|
169
|
+
) -> bytes:
|
|
61
170
|
if count == 0:
|
|
62
|
-
return
|
|
171
|
+
return b""
|
|
63
172
|
|
|
64
173
|
try:
|
|
65
174
|
data = stream.read(-1 if count == EOF else count)
|
|
@@ -69,12 +178,12 @@ class Char(bytes, BaseType):
|
|
|
69
178
|
if count != EOF and len(data) != count:
|
|
70
179
|
raise EOFError(f"Read {len(data)} bytes, but expected {count}")
|
|
71
180
|
|
|
72
|
-
return
|
|
181
|
+
return data
|
|
73
182
|
|
|
74
183
|
@classmethod
|
|
75
|
-
def _read_0(cls, stream: BinaryIO, *, context: dict[str, Any] | None = None, endian: Endianness) ->
|
|
184
|
+
def _read_0(cls, stream: BinaryIO, *, context: dict[str, Any] | None = None, endian: Endianness) -> bytes:
|
|
76
185
|
if _is_seekable(stream):
|
|
77
|
-
return
|
|
186
|
+
return _read_null_terminated(stream, 1)
|
|
78
187
|
|
|
79
188
|
buf = []
|
|
80
189
|
while True:
|
|
@@ -87,15 +196,13 @@ class Char(bytes, BaseType):
|
|
|
87
196
|
|
|
88
197
|
buf.append(byte)
|
|
89
198
|
|
|
90
|
-
return
|
|
199
|
+
return b"".join(buf)
|
|
91
200
|
|
|
92
201
|
@classmethod
|
|
93
|
-
def _write(cls, stream: BinaryIO, data: bytes
|
|
94
|
-
if isinstance(data,
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
if isinstance(data, str):
|
|
98
|
-
data = data.encode("latin-1")
|
|
202
|
+
def _write(cls, stream: BinaryIO, data: bytes, *, endian: Endianness) -> int:
|
|
203
|
+
if not isinstance(data, _BUFFER_TYPES):
|
|
204
|
+
hint = ", encode to bytes first" if isinstance(data, str) else ""
|
|
205
|
+
raise TypeError(f"Expected bytes, got {type(data).__name__}{hint}")
|
|
99
206
|
|
|
100
207
|
if (actual_size := len(data)) > 1:
|
|
101
208
|
raise WriteError(f"Expected a single character, got {actual_size} instead.")
|
dissect/cstruct/types/enum.py
CHANGED
|
@@ -49,7 +49,8 @@ class EnumMetaType(EnumMeta, MetaType):
|
|
|
49
49
|
if type(value) is not cls and (member := cls._value2member_map_.get(value)) is not None:
|
|
50
50
|
return member
|
|
51
51
|
|
|
52
|
-
|
|
52
|
+
# E.g. a member of another enum, which doesn't hash like its value
|
|
53
|
+
return super().__call__(value if type(value) is cls else int(value))
|
|
53
54
|
|
|
54
55
|
# We are constructing a new Enum class
|
|
55
56
|
# cs is the cstruct instance, but we can't isinstance check it due to circular imports
|
dissect/cstruct/types/int.py
CHANGED
|
@@ -18,6 +18,13 @@ class Int(int, BaseType):
|
|
|
18
18
|
|
|
19
19
|
__signed__: bool
|
|
20
20
|
|
|
21
|
+
@classmethod
|
|
22
|
+
def _normalize(cls, value: Any) -> Self:
|
|
23
|
+
if isinstance(value, int):
|
|
24
|
+
# Fast path for integers
|
|
25
|
+
return type.__call__(cls, value)
|
|
26
|
+
return MetaType._normalize(cls, value)
|
|
27
|
+
|
|
21
28
|
@classmethod
|
|
22
29
|
def _read(cls, stream: BinaryIO, *, context: dict[str, Any] | None = None, endian: Endianness) -> Self:
|
|
23
30
|
data = stream.read(cls.__size__)
|