-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathcstruct.py
More file actions
1894 lines (1441 loc) · 54.2 KB
/
cstruct.py
File metadata and controls
1894 lines (1441 loc) · 54.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2018 Fox-IT Security Research Team <srt@fox-it.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# TODO:
# - Rework definition parsing, maybe pycparser?
# - Change expression implementation
# - Lazy reading?
from __future__ import print_function
import re
import sys
import ast
import pprint
import string
import struct
import ctypes as _ctypes
from io import BytesIO
from collections import OrderedDict
try:
from builtins import bytes as newbytes
except ImportError:
newbytes = bytes
PY3 = sys.version_info > (3,)
if PY3:
long = int
xrange = range
DEBUG = False
COLOR_RED = '\033[1;31m'
COLOR_GREEN = '\033[1;32m'
COLOR_YELLOW = '\033[1;33m'
COLOR_BLUE = '\033[1;34m'
COLOR_PURPLE = '\033[1;35m'
COLOR_CYAN = '\033[1;36m'
COLOR_WHITE = '\033[1;37m'
COLOR_NORMAL = '\033[1;0m'
COLOR_BG_RED = '\033[1;41m\033[1;37m'
COLOR_BG_GREEN = '\033[1;42m\033[1;37m'
COLOR_BG_YELLOW = '\033[1;43m\033[1;37m'
COLOR_BG_BLUE = '\033[1;44m\033[1;37m'
COLOR_BG_PURPLE = '\033[1;45m\033[1;37m'
COLOR_BG_CYAN = '\033[1;46m\033[1;37m'
COLOR_BG_WHITE = '\033[1;47m\033[1;30m'
PRINTABLE = string.digits + string.ascii_letters + string.punctuation + " "
COMPILE_TEMPL = """
class {name}(Structure):
def __init__(self, cstruct, structure, source=None):
self.structure = structure
self.source = source
super({name}, self).__init__(cstruct, structure.name, structure.fields)
def _read(self, stream):
r = OrderedDict()
sizes = {{}}
bitreader = BitBuffer(stream, self.cstruct.endian)
{read_code}
return Instance(self, r, sizes)
def add_fields(self, name, type_, offset=None):
raise NotImplementedError("Can't add fields to a compiled structure")
def __repr__(self):
return '<Structure {name} +compiled>'
"""
class Error(Exception):
pass
class ParserError(Error):
pass
class CompilerError(Error):
pass
class ResolveError(Error):
pass
class NullPointerDereference(Error):
pass
def log(line, *args, **kwargs):
if not DEBUG:
return
print(line.format(*args, **kwargs), file=sys.stderr)
class cstruct(object):
"""Main class of cstruct. All types are registered in here.
Args:
endian: The endianness to use when parsing.
pointer: The pointer type to use for Pointers.
"""
DEF_CSTYLE = 1
def __init__(self, endian='<', pointer='uint64'):
self.endian = endian
self.consts = {}
self.lookups = {}
self.typedefs = {
'byte': 'int8',
'ubyte': 'uint8',
'uchar': 'uint8',
'short': 'int16',
'ushort': 'uint16',
'long': 'int32',
'ulong': 'uint32',
'ulong64': 'uint64',
'u1': 'uint8',
'u2': 'uint16',
'u4': 'uint32',
'u8': 'uint64',
'word': 'uint16',
'dword': 'uint32',
'longlong': 'int64',
'ulonglong': 'uint64',
'int': 'int32',
'unsigned int': 'uint32',
'int8': PackedType(self, 'int8', 1, 'b'),
'uint8': PackedType(self, 'uint8', 1, 'B'),
'int16': PackedType(self, 'int16', 2, 'h'),
'uint16': PackedType(self, 'uint16', 2, 'H'),
'int32': PackedType(self, 'int32', 4, 'i'),
'uint32': PackedType(self, 'uint32', 4, 'I'),
'int64': PackedType(self, 'int64', 8, 'q'),
'uint64': PackedType(self, 'uint64', 8, 'Q'),
'float': PackedType(self, 'float', 4, 'f'),
'double': PackedType(self, 'double', 8, 'd'),
'char': CharType(self),
'wchar': WcharType(self),
'int24': BytesInteger(self, 'int24', 3, True),
'uint24': BytesInteger(self, 'uint24', 3, False),
'int48': BytesInteger(self, 'int48', 6, True),
'uint48': BytesInteger(self, 'uint48', 6, False),
'void': VoidType(),
}
self.pointer = self.resolve(pointer)
def addtype(self, name, t, replace=False):
"""Add a type or type reference.
Args:
name: Name of the type to be added.
t: The type to be added. Can be a str reference to another type
or a compatible type class.
Raises:
ValueError: If the type already exists.
"""
name = name.lower()
if not replace and name.lower() in self.typedefs:
raise ValueError("Duplicate type: %s" % name)
self.typedefs[name] = t
def load(self, s, deftype=None, **kwargs):
"""Parse structures from the given definitions using the given definition type.
Definitions can be parsed using different parsers. Currently, there's
only one supported parser - DEF_CSTYLE. Parsers can add types and
modify this cstruct instance. Arguments can be passed to parsers
using kwargs.
Args:
s: The definition to parse.
deftype: The definition type to parse the definitions with.
**kwargs: Keyword arguments for parsers.
"""
deftype = deftype or cstruct.DEF_CSTYLE
if deftype == cstruct.DEF_CSTYLE:
parser = CStyleParser(self, **kwargs)
parser.parse(s)
def loadfile(self, s, deftype=None, **kwargs):
"""Load structure definitions from a file.
The given path will be read and parsed using the .load() function.
Args:
s: The path to load definitions from.
deftype: The definition type to parse the definitions with.
**kwargs: Keyword arguments for parsers.
"""
with open(s, 'r') as fh:
self.load(fh.read(), deftype, **kwargs)
def read(self, name, s):
"""Parse data using a given type.
Args:
name: Type name to read.
s: File-like object or byte string to parse.
Returns:
The parsed data.
"""
return self.resolve(name).read(s)
def resolve(self, name):
"""Resolve a type name to get the actual type object.
Types can be referenced using different names. When we want
the actual type object, we need to resolve these references.
Args:
name: Type name to resolve.
Returns:
The resolved type object.
Raises:
ResolveError: If the type can't be resolved.
"""
t = name
if not isinstance(t, str):
return t
for i in xrange(10):
if t.lower() not in self.typedefs:
raise ResolveError("Unknown type %s" % name)
t = self.typedefs[t.lower()]
if not isinstance(t, str):
return t
raise ResolveError("Recursion limit exceeded while resolving type %s" % name)
def __getattr__(self, attr):
if attr.lower() in self.typedefs:
return self.typedefs[attr.lower()]
if attr in self.consts:
return self.consts[attr]
raise AttributeError("Invalid Attribute: %s" % attr)
class Parser(object):
"""Base class for definition parsers.
Args:
cstruct: An instance of cstruct.
"""
def __init__(self, cstruct):
self.cstruct = cstruct
def parse(self, data):
"""This function should parse definitions to cstruct types.
Args:
data: Data to parse definitions from, usually a string.
"""
raise NotImplementedError()
class CStyleParser(Parser):
"""Definition parser for C-like structure syntax.
Args:
cstruct: An instance of cstruct
compiled: Whether structs should be compiled or not.
"""
def __init__(self, cstruct, compiled=True):
self.compiled = compiled
super(CStyleParser, self).__init__(cstruct)
# TODO: Implement proper parsing
def parse(self, data):
self._constants(data)
self._enums(data)
self._structs(data)
self._lookups(data, self.cstruct.consts)
def _constants(self, data):
r = re.finditer(r'#define\s+(?P<name>[^\s]+)\s+(?P<value>[^\r\n]+)\s*\n', data)
for t in r:
d = t.groupdict()
v = d['value'].rsplit('//')[0]
try:
v = ast.literal_eval(v)
except (ValueError, SyntaxError):
pass
self.cstruct.consts[d['name']] = v
def _enums(self, data):
r = re.finditer(
r'enum\s+(?P<name>[^\s:{]+)\s*(:\s*(?P<type>[^\s]+)\s*)?\{(?P<values>[^}]+)\}\s*;',
data,
)
for t in r:
d = t.groupdict()
nextval = 0
values = {}
for line in d['values'].split('\n'):
line, sep, comment = line.partition("//")
for v in line.split(","):
key, sep, val = v.partition("=")
key = key.strip()
val = val.strip()
if not key:
continue
if not val:
val = nextval
else:
val = Expression(self.cstruct, val).evaluate({})
nextval = val + 1
values[key] = val
if not d['type']:
d['type'] = 'uint32'
enum = Enum(
self.cstruct, d['name'], self.cstruct.resolve(d['type']), values
)
self.cstruct.addtype(enum.name, enum)
def _structs(self, data):
compiler = Compiler(self.cstruct)
r = re.finditer(
r'(#(?P<flags>(?:compile))\s+)?((?P<typedef>typedef)\s+)?(?P<type>[^\s]+)\s+(__attribute__\(\([^)]+\)\)\s*)?(?P<name>[^\s]+)?(?P<fields>\s*\{[^}]+\}(?P<defs>\s+[^;\n]+)?)?\s*;',
data,
)
for t in r:
d = t.groupdict()
if d['name']:
name = d['name']
elif d['defs']:
name = d['defs'].strip().split(',')[0].strip()
else:
raise ParserError("No name for struct")
if d['type'] == 'struct':
data = self._parse_fields(d['fields'][1:-1].strip())
st = Structure(self.cstruct, name, data)
if d['flags'] == 'compile' or self.compiled:
st = compiler.compile(st)
elif d['typedef'] == 'typedef':
st = d['type']
else:
continue
if d['name']:
self.cstruct.addtype(d['name'], st)
if d['defs']:
for td in d['defs'].strip().split(','):
td = td.strip()
self.cstruct.addtype(td, st)
def _parse_fields(self, s):
fields = re.finditer(
r'(?P<type>[^\s]+)\s+(?P<name>[^\s\[:]+)(\s*:\s*(?P<bits>\d+))?(\[(?P<count>[^;\n]*)\])?;',
s,
)
r = []
for f in fields:
d = f.groupdict()
if d['type'].startswith('//'):
continue
type_ = self.cstruct.resolve(d['type'])
d['name'] = d['name'].replace('(', '').replace(')', '')
# Maybe reimplement lazy type references later
# _type = TypeReference(self, d['type'])
if d['count'] is not None:
if d['count'] == '':
count = None
else:
count = Expression(self.cstruct, d['count'])
try:
count = count.evaluate()
except Exception:
pass
type_ = Array(self.cstruct, type_, count)
if d['name'].startswith('*'):
d['name'] = d['name'][1:]
type_ = Pointer(self.cstruct, type_)
field = Field(d['name'], type_, int(d['bits']) if d['bits'] else None)
r.append(field)
return r
def _lookups(self, data, consts):
r = re.finditer(r'\$(?P<name>[^\s]+) = ({[^}]+})\w*\n', data)
for t in r:
d = ast.literal_eval(t.group(2))
self.cstruct.lookups[t.group(1)] = dict(
[(self.cstruct.consts[k], v) for k, v in d.items()]
)
class Instance(object):
"""Holds parsed structure data."""
def __init__(self, type_, values, sizes=None):
object.__setattr__(self, '_type', type_)
object.__setattr__(self, '_values', values)
object.__setattr__(self, '_sizes', sizes)
def write(self, fh):
"""Write this structure to a writable file-like object.
Args:
fh: File-like objects that supports writing.
Returns:
The amount of bytes written.
"""
return self.__dict__['_type'].write(fh, self)
def dumps(self):
"""Dump this structure to a byte string.
Returns:
The raw bytes of this structure.
"""
s = BytesIO()
self.write(s)
return s.getvalue()
def __getattr__(self, attr):
if attr not in self.__dict__['_type'].lookup:
raise AttributeError("Invalid attribute: %r" % attr)
return self.__dict__['_values'][attr]
def __setattr__(self, attr, value):
if attr not in self.__dict__['_type'].lookup:
raise AttributeError("Invalid attribute: %r" % attr)
self.__dict__['_values'][attr] = value
def __getitem__(self, item):
return self.__dict__['_values'][item]
def __contains__(self, attr):
return attr in self.__dict__['_values']
def __repr__(self):
return '<%s %s>' % (
self.__dict__['_type'].name,
', '.join(
[
'%s=%s' % (k, hex(v) if isinstance(v, (int, long)) else repr(v))
for k, v in self.__dict__['_values'].items()
]
),
)
def __len__(self):
return len(self.dumps())
def _size(self, field):
return self.__dict__['_sizes'][field]
class PointerInstance(object):
"""Like the Instance class, but for structures referenced by a pointer."""
def __init__(self, t, stream, addr, ctx):
self._stream = stream
self._type = t
self._addr = addr
self._ctx = ctx
self._value = None
def _get(self):
log("Dereferencing pointer -> 0x{:016x} [{!r}]", self._addr, self._stream)
if self._addr == 0:
raise NullPointerDereference()
if self._value is None:
pos = self._stream.tell()
self._stream.seek(self._addr)
if isinstance(self._type, Array):
r = self._type._read(self._stream, self._ctx)
else:
r = self._type._read(self._stream)
self._stream.seek(pos)
self._value = r
return self._value
def __getattr__(self, attr):
return getattr(self._get(), attr)
def __str__(self):
return str(self._get())
def __nonzero__(self):
return self._addr != 0
def __repr__(self):
return "<Pointer {!r} @ 0x{:x}>".format(self._type, self._addr)
class Expression(object):
"""Expression parser for simple calculations in definitions."""
operators = [
('+', lambda a, b: a + b),
('-', lambda a, b: a - b),
('*', lambda a, b: a * b),
('/', lambda a, b: a / b),
('&', lambda a, b: a & b),
('|', lambda a, b: a | b),
('>>', lambda a, b: a >> b),
('<<', lambda a, b: a << b),
]
def __init__(self, cstruct, expr):
self.cstruct = cstruct
self.expr = expr
def evaluate(self, context=None):
context = context if context else {}
level = 0
levels = []
buf = ''
for i in xrange(len(self.expr)):
if self.expr[i] == '(':
level += 1
levels.append(buf)
buf = ''
continue
if self.expr[i] == ')':
level -= 1
val = self.evaluate_part(buf, context)
buf = levels.pop()
buf += str(val)
continue
buf += self.expr[i]
return self.evaluate_part(buf, context)
def evaluate_part(self, e, v):
e = e.strip()
for o in self.operators:
if o[0] in e:
a, b = e.rsplit(o[0], 1)
return o[1](self.evaluate_part(a, v), self.evaluate_part(b, v))
if e in v:
return v[e]
if e.startswith('0x'):
return int(e, 16)
if e in self.cstruct.consts:
return self.cstruct.consts[e]
return int(e)
def __repr__(self):
return self.expr
class BaseType(object):
"""Base class for cstruct type classes."""
def __init__(self, cstruct):
self.cstruct = cstruct
def reads(self, data):
"""Parse the given data according to the type that implements this class.
Args:
data: Byte string to parse.
Returns:
The parsed value of this type.
"""
data = BytesIO(data)
return self._read(data)
def dumps(self, data):
"""Dump the given data according to the type that implements this class.
Args:
data: Data to dump.
Returns:
The resulting bytes.
"""
out = BytesIO()
self._write(out, data)
return out.getvalue()
def read(self, obj, *args, **kwargs):
"""Parse the given data according to the type that implements this class.
Args:
obj: Data to parse. Can be a (byte) string or a file-like object.
Returns:
The parsed value of this type.
"""
if isinstance(obj, (str, bytes, newbytes)):
return self.reads(obj)
return self._read(obj)
def write(self, stream, data):
"""Write the given data to a writable file-like object according to the
type that implements this class.
Args:
stream: Writable file-like object to write to.
data: Data to write.
Returns:
The amount of bytes written.
"""
return self._write(stream, data)
def _read(self, stream):
raise NotImplementedError()
def _read_array(self, stream, count):
return [self._read(stream) for i in xrange(count)]
def _read_0(self, stream):
raise NotImplementedError()
def _write(self, stream, data):
raise NotImplementedError()
def _write_array(self, stream, data):
num = 0
for i in data:
num += self._write(stream, i)
return num
def _write_0(self, stream, data):
raise NotImplementedError()
def default(self):
"""Return a default value of this type."""
raise NotImplementedError()
def default_array(self):
"""Return a default array of this type."""
raise NotImplementedError()
def __getitem__(self, count):
return Array(self.cstruct, self, count)
def __call__(self, *args, **kwargs):
if len(args) > 0:
return self.read(*args, **kwargs)
r = self.default()
if kwargs:
for k, v in kwargs.items():
setattr(r, k, v)
return r
class RawType(BaseType):
"""Base class for raw types that have a name and size."""
def __init__(self, cstruct, name=None, size=0):
self.name = name
self.size = size
super(RawType, self).__init__(cstruct)
def __len__(self):
return self.size
def __repr__(self):
if self.name:
return self.name
return BaseType.__repr__(self)
class Structure(BaseType):
"""Type class for structures."""
def __init__(self, cstruct, name, fields=None):
self.name = name
self.size = None
self.lookup = OrderedDict()
self.fields = fields if fields else []
for f in self.fields:
self.lookup[f.name] = f
self._calc_offsets()
super(Structure, self).__init__(cstruct)
def _calc_offsets(self):
offset = 0
bitstype = None
bitsremaining = 0
for field in self.fields:
if field.bits:
if bitsremaining == 0 or field.type != bitstype:
bitstype = field.type
bitsremaining = bitstype.size * 8
if offset is not None:
field.offset = offset
offset += bitstype.size
else:
field.offset = None
bitsremaining -= field.bits
continue
field.offset = offset
if offset is not None:
try:
offset += len(field.type)
except TypeError:
offset = None
def _calc_size(self):
size = 0
bitstype = None
bitsremaining = 0
for field in self.fields:
if field.bits:
if bitsremaining == 0 or field.type != bitstype:
bitstype = field.type
bitsremaining = bitstype.size * 8
size += bitstype.size
bitsremaining -= field.bits
continue
fieldlen = len(field.type)
size += fieldlen
if field.offset is not None:
size = max(size, field.offset + fieldlen)
return size
def _read(self, stream, *args, **kwargs):
log("[Structure::read] {} {}", self.name, self.size)
bitbuffer = BitBuffer(stream, self.cstruct.endian)
struct_start = stream.tell()
r = OrderedDict()
sizes = {}
for field in self.fields:
start = stream.tell()
ft = self.cstruct.resolve(field.type)
if field.offset:
if start != struct_start + field.offset:
log(
"+ seeking to 0x{:x}+0x{:x} for {}".format(
struct_start, field.offset, field.name
)
)
stream.seek(struct_start + field.offset)
start = struct_start + field.offset
if field.bits:
r[field.name] = bitbuffer.read(ft, field.bits)
continue
else:
bitbuffer.reset()
if isinstance(ft, (Array, Pointer)):
v = ft._read(stream, r)
else:
v = ft._read(stream)
sizes[field.name] = stream.tell() - start
r[field.name] = v
return Instance(self, r, sizes)
def _write(self, stream, data):
bitbuffer = BitBuffer(stream, self.cstruct.endian)
num = 0
for field in self.fields:
if field.bits:
bitbuffer.write(field.type, getattr(data, field.name), field.bits)
continue
if bitbuffer._type:
bitbuffer.flush()
num += field.type._write(stream, getattr(data, field.name))
# Flush bitbuffer
if bitbuffer._type:
bitbuffer.flush()
return num
def add_field(self, name, type_, offset=None):
"""Add a field to this structure.
Args:
name: The field name.
type_: The field type.
offset: The field offset.
"""
field = Field(name, type_, offset=offset)
self.fields.append(field)
self.lookup[name] = field
self.size = None
setattr(self, name, field)
def default(self):
"""Create and return an empty Instance from this structure.
Returns:
An empty Instance from this structure.
"""
r = OrderedDict()
for field in self.fields:
r[field.name] = field.type.default()
return Instance(self, r)
def __len__(self):
if self.size is None:
self.size = self._calc_size()
return self.size
def __repr__(self):
return '<Structure {}>'.format(self.name)
def show(self, indent=0):
"""Pretty print this structure."""
if indent == 0:
print("struct {}".format(self.name))
for field in self.fields:
if field.offset is None:
offset = '0x??'
else:
offset = '0x{:02x}'.format(field.offset)
print("{}+{} {} {}".format(' ' * indent, offset, field.name, field.type))
if isinstance(field.type, Structure):
field.type.show(indent + 1)
class BitBuffer(object):
"""Implements a bit buffer that can read and write bit fields."""
def __init__(self, stream, endian):
self.stream = stream
self.endian = endian
self._type = None
self._buffer = 0
self._remaining = 0
def read(self, field_type, bits):
if self._remaining < 1 or self._type != field_type:
self._type = field_type
self._remaining = field_type.size * 8
self._buffer = field_type._read(self.stream)
if self.endian != '>':
v = self._buffer & ((1 << bits) - 1)
self._buffer >>= bits
self._remaining -= bits
else:
v = self._buffer & (
((1 << (self._remaining - bits)) - 1) ^ ((1 << self._remaining) - 1)
)
v >>= self._remaining - bits
self._remaining -= bits
return v
def write(self, field_type, data, bits):
if self._remaining == 0:
self._remaining = field_type.size * 8
self._type = field_type
if self.endian != '>':
self._buffer |= data << (self._type.size * 8 - self._remaining)
else:
self._buffer |= data << (self._remaining - bits)
self._remaining -= bits
def flush(self):
self._type._write(self.stream, self._buffer)
self._type = None
self._remaining = 0
self._buffer = 0
def reset(self):
self._type = None
self._buffer = 0
self._remaining = 0
class Field(object):
"""Holds a structure field."""
def __init__(self, name, type_, bits=None, offset=None):
self.name = name
self.type = type_
self.bits = bits
self.offset = offset
def __repr__(self):
return '<Field {} {}>'.format(self.name, self.type)
class Array(BaseType):
"""Implements a fixed or dynamically sized array type.
Example:
When using the default C-style parser, the following syntax is supported:
x[3] -> 3 -> static length.
x[] -> None -> null-terminated.
x[expr] -> expr -> dynamic length.
"""
def __init__(self, cstruct, type_, count):
self.type = type_
self.count = count
self.dynamic = isinstance(self.count, Expression) or self.count is None
super(Array, self).__init__(cstruct)
def _read(self, stream, context=None):
if self.count is None: