Repository navigation
Expand file tree
/
Copy pathcore.py
More file actions
6447 lines (5096 loc) · 251 KB
/
Copy pathcore.py
File metadata and controls
6447 lines (5096 loc) · 251 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
# -*- coding: utf-8 -*-
import struct, io, binascii, itertools, collections, pickle, sys, os, hashlib, importlib, importlib.machinery, importlib.util
from construct.lib import *
from construct.expr import *
from construct.version import *
#===============================================================================
# exceptions
#===============================================================================
class ConstructError(Exception):
"""
This is the root of all exceptions raised by parsing classes in this library. Note that the helper functions in lib module can raise standard ValueError (but parsing classes are not allowed to).
"""
def __init__(self, message='', path=None):
self.path = path
if path is None:
super().__init__(message)
else:
message = "Error in path {}\n".format(path) + message
super().__init__(message)
class SizeofError(ConstructError):
"""
Parsing classes sizeof() methods are only allowed to either return an integer or raise SizeofError instead. Note that this exception can mean the parsing class cannot be measured apriori in principle, however it can also mean that it just cannot be measured in these particular circumstances (eg. there is a key missing in the context dictionary at this time).
"""
pass
class AdaptationError(ConstructError):
"""
Currently not used.
"""
pass
class ValidationError(ConstructError):
"""
Validator ExprValidator derived parsing classes can raise this exception: OneOf NoneOf. It can mean that the parse or build value is or is not one of specified values.
"""
pass
class StreamError(ConstructError):
"""
Almost all parsing classes can raise this exception: it can mean a variety of things. Maybe requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, could not write all bytes, stream is not seekable, stream is not tellable, etc. Note that there are a few parsing classes that do not use the stream to compute output and therefore do not raise this exception.
"""
pass
class FormatFieldError(ConstructError):
"""
Only one parsing class can raise this exception: FormatField. It can either mean the format string is invalid or the value is not valid for provided format string. See standard struct module for what is acceptable.
"""
pass
class IntegerError(ConstructError):
"""
Only some numeric parsing classes can raise this exception: BytesInteger BitsInteger VarInt ZigZag. It can mean either the length parameter is invalid, the value is not an integer, the value is negative or too low or too high for given parameters, or the selected endianness cannot be applied.
"""
pass
class StringError(ConstructError):
"""
Almost all parsing classes can raise this exception: It can mean a unicode string was passed instead of bytes, or a bytes was passed instead of a unicode string. Also some classes can raise it explicitly: PascalString CString GreedyString. It can mean no encoding or invalid encoding was selected. Note that currently, if the data cannot be encoded decoded given selected encoding then UnicodeEncodeError UnicodeDecodeError are raised, which are not rooted at ConstructError.
"""
pass
class MappingError(ConstructError):
"""
Few parsing classes can raise this exception: Enum FlagsEnum Mapping. It can mean the build value is not recognized and therefore cannot be mapped onto bytes.
"""
pass
class RangeError(ConstructError):
"""
Few parsing classes can raise this exception: Array PrefixedArray LazyArray. It can mean the count parameter is invalid, or the build object has too little or too many elements.
"""
pass
class RepeatError(ConstructError):
"""
Only one parsing class can raise this exception: RepeatUntil. It can mean none of the elements in build object passed the given predicate.
"""
pass
class ConstError(ConstructError):
"""
Only one parsing class can raise this exception: Const. It can mean the wrong data was parsed, or wrong object was built from.
"""
pass
class IndexFieldError(ConstructError):
"""
Only one parsing class can raise this exception: Index. It can mean the class was not nested in an array parsing class properly and therefore cannot access the _index context key.
"""
pass
class CheckError(ConstructError):
"""
Only one parsing class can raise this exception: Check. It can mean the condition lambda failed during a routine parsing building check.
"""
pass
class ExplicitError(ConstructError):
"""
Only one parsing class can raise this exception: Error. It can mean the parsing class was merely parsed or built with.
"""
pass
class NamedTupleError(ConstructError):
"""
Only one parsing class can raise this exception: NamedTuple. It can mean the subcon is not of a valid type.
"""
pass
class TimestampError(ConstructError):
"""
Only one parsing class can raise this exception: Timestamp. It can mean the subcon unit or epoch are invalid.
"""
pass
class UnionError(ConstructError):
"""
Only one parsing class can raise this exception: Union. It can mean none of given subcons was properly selected, or trying to build without providing a proper value.
"""
pass
class SelectError(ConstructError):
"""
Only one parsing class can raise this exception: Select. It can mean neither subcon succeded when parsing or building.
"""
pass
class SwitchError(ConstructError):
"""
Currently not used.
"""
pass
class StopFieldError(ConstructError):
"""
Only one parsing class can raise this exception: StopIf. It can mean the given condition was met during parsing or building.
"""
pass
class PaddingError(ConstructError):
"""
Multiple parsing classes can raise this exception: PaddedString Padding Padded Aligned FixedSized NullTerminated NullStripped. It can mean multiple issues: the encoded string or bytes takes more bytes than padding allows, length parameter was invalid, pattern terminator or pad is not a proper bytes value, modulus was less than 2.
"""
pass
class TerminatedError(ConstructError):
"""
Only one parsing class can raise this exception: Terminated. It can mean EOF was not found as expected during parsing.
"""
pass
class RawCopyError(ConstructError):
"""
Only one parsing class can raise this exception: RawCopy. It can mean it cannot build as both data and value keys are missing from build dict object.
"""
pass
class RotationError(ConstructError):
"""
Only one parsing class can raise this exception: ProcessRotateLeft. It can mean the specified group is less than 1, data is not of valid length.
"""
pass
class ChecksumError(ConstructError):
"""
Only one parsing class can raise this exception: Checksum. It can mean expected and actual checksum do not match.
"""
pass
class CancelParsing(ConstructError):
"""
This exception can only be raise explicitly by the user, and it causes the parsing class to stop what it is doing (interrupts parsing or building).
"""
pass
class CipherError(ConstructError):
"""
Two parsing classes can raise this exception: EncryptedSym EncryptedSymAead. It can mean none or invalid cipher object was provided.
"""
pass
#===============================================================================
# used internally
#===============================================================================
def singleton(arg):
x = arg()
return x
def stream_read(stream, length, path):
if length < 0:
raise StreamError("length must be non-negative, found %s" % length, path=path)
try:
data = stream.read(length)
except Exception:
raise StreamError("stream.read() failed, requested %s bytes" % (length,), path=path)
if len(data) != length:
raise StreamError("stream read less than specified amount, expected %d, found %d" % (length, len(data)), path=path)
return data
def stream_read_entire(stream, path):
try:
return stream.read()
except Exception:
raise StreamError("stream.read() failed when reading until EOF", path=path)
def stream_write(stream, data, length, path):
if not isinstance(data, bytes):
raise StringError("given non-bytes value, perhaps unicode? %r" % (data,), path=path)
if length < 0:
raise StreamError("length must be non-negative, found %s" % length, path=path)
if len(data) != length:
raise StreamError("bytes object of wrong length, expected %d, found %d" % (length, len(data)), path=path)
try:
written = stream.write(data)
except Exception:
raise StreamError("stream.write() failed, given %r" % (data,), path=path)
if written != length:
raise StreamError("stream written less than specified, expected %d, written %d" % (length, written), path=path)
def stream_seek(stream, offset, whence, path):
try:
return stream.seek(offset, whence)
except Exception:
raise StreamError("stream.seek() failed, offset %s, whence %s" % (offset, whence), path=path)
def stream_tell(stream, path):
try:
return stream.tell()
except Exception:
raise StreamError("stream.tell() failed", path=path)
def stream_size(stream):
try:
fallback = stream.tell()
end = stream.seek(0, 2)
stream.seek(fallback)
return end
except Exception:
raise StreamError("stream. seek() tell() failed", path="???")
def stream_iseof(stream):
try:
fallback = stream.tell()
data = stream.read(1)
stream.seek(fallback)
return not data
except Exception:
raise StreamError("stream. read() seek() tell() failed", path="???")
class BytesIOWithOffsets(io.BytesIO):
@staticmethod
def from_reading(stream, length: int, path: str):
offset = stream_tell(stream, path)
contents = stream_read(stream, length, path)
return BytesIOWithOffsets(contents, stream, offset)
def __init__(self, contents: bytes, parent_stream, offset: int):
super().__init__(contents)
self.parent_stream = parent_stream
self.parent_stream_offset = offset
def tell(self) -> int:
return super().tell() + self.parent_stream_offset
def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:
if whence != io.SEEK_SET:
super().seek(offset, whence)
else:
super().seek(offset - self.parent_stream_offset)
return self.tell()
class CodeGen:
def __init__(self):
self.blocks = []
self.nextid = 0
self.parsercache = {}
self.buildercache = {}
self.linkedinstances = {}
self.linkedparsers = {}
self.linkedbuilders = {}
self.userfunction = {}
def allocateId(self):
self.nextid += 1
return self.nextid
def append(self, block):
block = [s for s in block.splitlines() if s.strip()]
firstline = block[0]
trim = len(firstline) - len(firstline.lstrip())
block = "\n".join(s[trim:] for s in block)
if block not in self.blocks:
self.blocks.append(block)
def toString(self):
return "\n".join(self.blocks + [""])
class KsyGen:
def __init__(self):
self.instances = {}
self.enums = {}
self.types = {}
self.nextid = 0
def allocateId(self):
self.nextid += 1
return self.nextid
def hyphenatedict(d):
return {k.replace("_","-").rstrip("-"):v for k,v in d.items()}
def hyphenatelist(l):
return [hyphenatedict(d) for d in l]
def extractfield(sc):
if isinstance(sc, Renamed):
return extractfield(sc.subcon)
return sc
def evaluate(param, context):
return param(context) if callable(param) else param
#===============================================================================
# abstract constructs
#===============================================================================
class Construct(object):
r"""
The mother of all constructs.
This object is generally not directly instantiated, and it does not directly implement parsing and building, so it is largely only of interest to subclass implementors. There are also other abstract classes sitting on top of this one.
The external user API:
* `parse`
* `parse_stream`
* `parse_file`
* `build`
* `build_stream`
* `build_file`
* `sizeof`
* `compile`
* `benchmark`
Subclass authors should not override the external methods. Instead, another API is available:
* `_parse`
* `_build`
* `_sizeof`
* `_actualsize`
* `_emitparse`
* `_emitbuild`
* `_emitseq`
* `_emitprimitivetype`
* `_emitfulltype`
* `__getstate__`
* `__setstate__`
Attributes and Inheritance:
All constructs have a name and flags. The name is used for naming struct members and context dictionaries. Note that the name can be a string, or None by default. A single underscore "_" is a reserved name, used as up-level in nested containers. The name should be descriptive, short, and valid as a Python identifier, although these rules are not enforced. The flags specify additional behavioral information about this construct. Flags are used by enclosing constructs to determine a proper course of action. Flags are often inherited from inner subconstructs but that depends on each class.
"""
def __init__(self):
self.name = None
self.docs = ""
self.flagbuildnone = False
self.parsed = None
def __repr__(self):
return "<%s%s%s%s>" % (self.__class__.__name__, " "+self.name if self.name else "", " +nonbuild" if self.flagbuildnone else "", " +docs" if self.docs else "", )
def __getstate__(self):
attrs = {}
if hasattr(self, "__dict__"):
attrs.update(self.__dict__)
slots = []
c = self.__class__
while c is not None:
if hasattr(c, "__slots__"):
slots.extend(c.__slots__)
c = c.__base__
for name in slots:
if hasattr(self, name):
attrs[name] = getattr(self, name)
return attrs
def __setstate__(self, attrs):
for name, value in attrs.items():
setattr(self, name, value)
def __copy__(self):
self2 = object.__new__(self.__class__)
self2.__setstate__(self.__getstate__())
return self2
def parse(self, data, **contextkw):
r"""
Parse an in-memory buffer (often bytes object). Strings, buffers, memoryviews, and other complete buffers can be parsed with this method.
Whenever data cannot be read, ConstructError or its derivative is raised. This method is NOT ALLOWED to raise any other exceptions although (1) user-defined lambdas can raise arbitrary exceptions which are propagated (2) external libraries like numpy can raise arbitrary exceptions which are propagated (3) some list and dict lookups can raise IndexError and KeyError which are propagated.
Context entries are passed only as keyword parameters \*\*contextkw.
:param \*\*contextkw: context entries, usually empty
:returns: some value, usually based on bytes read from the stream but sometimes it is computed from nothing or from the context dictionary, sometimes its non-deterministic
:raises ConstructError: raised for any reason
"""
return self.parse_stream(io.BytesIO(data), **contextkw)
def parse_stream(self, stream, **contextkw):
r"""
Parse a stream. Files, pipes, sockets, and other streaming sources of data are handled by this method. See parse().
"""
context = Container(**contextkw)
context._parsing = True
context._building = False
context._sizing = False
context._params = context
try:
return self._parsereport(stream, context, "(parsing)")
except CancelParsing:
pass
def parse_file(self, filename, **contextkw):
r"""
Parse a closed binary file. See parse().
"""
with open(filename, 'rb') as f:
return self.parse_stream(f, **contextkw)
def _parsereport(self, stream, context, path):
obj = self._parse(stream, context, path)
if self.parsed is not None:
self.parsed(obj, context)
return obj
def _parse(self, stream, context, path):
"""Override in your subclass."""
raise NotImplementedError
def build(self, obj, **contextkw):
r"""
Build an object in memory (a bytes object).
Whenever data cannot be written, ConstructError or its derivative is raised. This method is NOT ALLOWED to raise any other exceptions although (1) user-defined lambdas can raise arbitrary exceptions which are propagated (2) external libraries like numpy can raise arbitrary exceptions which are propagated (3) some list and dict lookups can raise IndexError and KeyError which are propagated.
Context entries are passed only as keyword parameters \*\*contextkw.
:param \*\*contextkw: context entries, usually empty
:returns: bytes
:raises ConstructError: raised for any reason
"""
stream = io.BytesIO()
self.build_stream(obj, stream, **contextkw)
return stream.getvalue()
def build_stream(self, obj, stream, **contextkw):
r"""
Build an object directly into a stream. See build().
"""
context = Container(**contextkw)
context._parsing = False
context._building = True
context._sizing = False
context._params = context
self._build(obj, stream, context, "(building)")
def build_file(self, obj, filename, **contextkw):
r"""
Build an object into a closed binary file. See build().
"""
# Open the file for reading as well as writing. This allows builders to
# read back the stream just written. For example. RawCopy does this.
# See issue #888.
with open(filename, 'w+b') as f:
self.build_stream(obj, f, **contextkw)
def _build(self, obj, stream, context, path):
"""Override in your subclass."""
raise NotImplementedError
def sizeof(self, **contextkw):
r"""
Calculate the size of this object, optionally using a context.
Some constructs have fixed size (like FormatField), some have variable-size and can determine their size given a context entry (like Bytes(this.otherfield1)), and some cannot determine their size (like VarInt).
Whenever size cannot be determined, SizeofError is raised. This method is NOT ALLOWED to raise any other exception, even if eg. context dictionary is missing a key, or subcon propagates ConstructError-derivative exception.
Context entries are passed only as keyword parameters \*\*contextkw.
:param \*\*contextkw: context entries, usually empty
:returns: integer if computable, SizeofError otherwise
:raises SizeofError: size could not be determined in actual context, or is impossible to be determined
"""
context = Container(**contextkw)
context._parsing = False
context._building = False
context._sizing = True
context._params = context
return self._sizeof(context, "(sizeof)")
def _sizeof(self, context, path):
"""Override in your subclass."""
raise SizeofError(path=path)
def _actualsize(self, stream, context, path):
return self._sizeof(context, path)
def compile(self, filename=None):
"""
Transforms a construct into another construct that does same thing (has same parsing and building semantics) but is much faster when parsing. Already compiled instances just compile into itself.
Optionally, partial source code can be saved to a text file. This is meant only to inspect the generated code, not to import it from external scripts.
:returns: Compiled instance
"""
code = CodeGen()
code.append("""
# generated by Construct, this source is for inspection only! do not import!
from construct import *
from construct.lib import *
from io import BytesIO
import struct
import collections
import itertools
def restream(data, func):
return func(BytesIO(data))
def reuse(obj, func):
return func(obj)
linkedinstances = {}
linkedparsers = {}
linkedbuilders = {}
userfunction = {}
len_ = len
sum_ = sum
min_ = min
max_ = max
abs_ = abs
""")
code.append(f"""
def parseall(io, this):
return {self._compileparse(code)}
def buildall(obj, io, this):
return {self._compilebuild(code)}
compiled = Compiled(parseall, buildall)
""")
source = code.toString()
if filename:
with open(filename, "wt") as f:
f.write(source)
modulename = hexlify(hashlib.sha1(source.encode()).digest()).decode()
module_spec = importlib.machinery.ModuleSpec(modulename, None)
module = importlib.util.module_from_spec(module_spec)
c = compile(source, '', 'exec')
exec(c, module.__dict__)
module.linkedinstances = code.linkedinstances
module.linkedparsers = code.linkedparsers
module.linkedbuilders = code.linkedbuilders
module.userfunction = code.userfunction
compiled = module.compiled
compiled.source = source
compiled.module = module
compiled.modulename = modulename
compiled.defersubcon = self
return compiled
def _compileinstance(self, code):
"""Used internally."""
if id(self) in code.linkedinstances:
return
code.append(f"""
# linkedinstances[{id(self)}] is {self}
""")
field = extractfield(self)
code.linkedinstances[id(self)] = field
code.linkedparsers[id(self)] = field._parse
code.linkedbuilders[id(self)] = field._build
def _compileparse(self, code):
"""Used internally."""
try:
if id(self) in code.parsercache:
return code.parsercache[id(self)]
emitted = self._emitparse(code)
code.parsercache[id(self)] = emitted
return emitted
except NotImplementedError:
self._compileinstance(code)
return f"linkedparsers[{id(self)}](io, this, '(???)')"
def _compilebuild(self, code):
"""Used internally."""
try:
if id(self) in code.buildercache:
return code.buildercache[id(self)]
emitted = self._emitbuild(code)
code.buildercache[id(self)] = emitted
return emitted
except NotImplementedError:
self._compileinstance(code)
return f"linkedbuilders[{id(self)}](obj, io, this, '(???)')"
def _emitparse(self, code):
"""Override in your subclass."""
raise NotImplementedError
def _emitbuild(self, code):
"""Override in your subclass."""
raise NotImplementedError
def benchmark(self, sampledata, filename=None):
"""
Measures performance of your construct (its parsing and building runtime), both for the original instance and the compiled instance. Uses timeit module, over at min 1 loop, and at max over 100 millisecond time.
Optionally, results are saved to a text file for later inspection. Otherwise you can print the resulting string to terminal.
:param sampledata: bytes, a valid blob parsable by this construct
:param filename: optional, string, results are saved to that file
:returns: string containing measurements
"""
from timeit import timeit
sampleobj = self.parse(sampledata)
parsetime = timeit(lambda: self.parse(sampledata), number=1)
runs = int(0.1/parsetime)
if runs > 1:
parsetime = timeit(lambda: self.parse(sampledata), number=runs)/runs
parsetime = "{:.10f} sec/call".format(parsetime)
self.build(sampleobj)
buildtime = timeit(lambda: self.build(sampleobj), number=1)
runs = int(0.1/buildtime)
if runs > 1:
buildtime = timeit(lambda: self.build(sampleobj), number=runs)/runs
buildtime = "{:.10f} sec/call".format(buildtime)
compiled = self.compile()
compiled.parse(sampledata)
parsetime2 = timeit(lambda: compiled.parse(sampledata), number=1)
runs = int(0.1/parsetime2)
if runs > 1:
parsetime2 = timeit(lambda: compiled.parse(sampledata), number=runs)/runs
parsetime2 = "{:.10f} sec/call".format(parsetime2)
compiled.build(sampleobj)
buildtime2 = timeit(lambda: compiled.build(sampleobj), number=1)
runs = int(0.1/buildtime2)
if runs > 1:
buildtime2 = timeit(lambda: compiled.build(sampleobj), number=runs)/runs
buildtime2 = "{:.10f} sec/call".format(buildtime2)
lines = [
"Compiled instance performance:",
"parsing: {}",
"parsing compiled: {}",
"building: {}",
"building compiled: {}",
""
]
results = "\n".join(lines).format(parsetime, parsetime2, buildtime, buildtime2)
if filename:
with open(filename, "wt") as f:
f.write(results)
return results
def export_ksy(self, schemaname="unnamed_schema", filename=None):
from ruamel.yaml import YAML
yaml = YAML()
yaml.default_flow_style = False
output = io.StringIO()
gen = KsyGen()
main = dict(meta=dict(id=schemaname), seq=self._compileseq(gen), instances=gen.instances, enums=gen.enums, types=gen.types)
yaml.dump(main, output)
source = output.getvalue()
if filename:
with open(filename, "wt") as f:
f.write(source)
return source
def _compileseq(self, ksy, bitwise=False, recursion=0):
if recursion >= 3:
raise ConstructError("construct does not implement KSY export")
try:
return hyphenatelist(self._emitseq(ksy, bitwise))
except NotImplementedError:
return [dict(id="x", **self._compilefulltype(ksy, bitwise, recursion+1))]
def _compileprimitivetype(self, ksy, bitwise=False, recursion=0):
if recursion >= 3:
raise ConstructError("construct does not implement KSY export")
try:
return self._emitprimitivetype(ksy, bitwise)
except NotImplementedError:
name = "type_%s" % ksy.allocateId()
ksy.types[name] = dict(seq=self._compileseq(ksy, bitwise, recursion+1))
return name
def _compilefulltype(self, ksy, bitwise=False, recursion=0):
if recursion >= 3:
raise ConstructError("construct does not implement KSY export")
try:
return hyphenatedict(self._emitfulltype(ksy, bitwise))
except NotImplementedError:
return dict(type=self._compileprimitivetype(ksy, bitwise, recursion+1))
def _emitseq(self, ksy, bitwise):
"""Override in your subclass."""
raise NotImplementedError
def _emitprimitivetype(self, ksy, bitwise):
"""Override in your subclass."""
raise NotImplementedError
def _emitfulltype(self, ksy, bitwise):
"""Override in your subclass."""
raise NotImplementedError
def __rtruediv__(self, name):
"""
Used for renaming subcons, usually part of a Struct, like Struct("index" / Byte).
"""
return Renamed(self, newname=name)
__rdiv__ = __rtruediv__
def __mul__(self, other):
"""
Used for adding docstrings and parsed hooks to subcons, like "field" / Byte * "docstring" * processfunc.
"""
if isinstance(other, str):
return Renamed(self, newdocs=other)
if callable(other):
return Renamed(self, newparsed=other)
raise ConstructError("operator * can only be used with string or lambda")
def __rmul__(self, other):
"""
Used for adding docstrings and parsed hooks to subcons, like "field" / Byte * "docstring" * processfunc.
"""
if isinstance(other, str):
return Renamed(self, newdocs=other)
if callable(other):
return Renamed(self, newparsed=other)
raise ConstructError("operator * can only be used with string or lambda")
def __add__(self, other):
"""
Used for making Struct like ("index"/Byte + "prefix"/Byte).
"""
lhs = self.subcons if isinstance(self, Struct) else [self]
rhs = other.subcons if isinstance(other, Struct) else [other]
return Struct(*(lhs + rhs))
def __rshift__(self, other):
"""
Used for making Sequences like (Byte >> Short).
"""
lhs = self.subcons if isinstance(self, Sequence) else [self]
rhs = other.subcons if isinstance(other, Sequence) else [other]
return Sequence(*(lhs + rhs))
def __getitem__(self, count):
"""
Used for making Arrays like Byte[5] and Byte[this.count].
"""
if isinstance(count, slice):
raise ConstructError("subcon[N] syntax can only be used for Arrays, use GreedyRange(subcon) instead?")
if isinstance(count, int) or callable(count):
return Array(count, self)
raise ConstructError("subcon[N] syntax expects integer or context lambda")
class Subconstruct(Construct):
r"""
Abstract subconstruct (wraps an inner construct, inheriting its name and flags). Parsing and building is by default deferred to subcon, same as sizeof.
:param subcon: Construct instance
"""
def __init__(self, subcon):
if not isinstance(subcon, Construct):
raise TypeError("subcon should be a Construct field")
super().__init__()
self.subcon = subcon
self.flagbuildnone = subcon.flagbuildnone
def __repr__(self):
return "<%s%s%s%s %s>" % (self.__class__.__name__, " "+self.name if self.name else "", " +nonbuild" if self.flagbuildnone else "", " +docs" if self.docs else "", repr(self.subcon), )
def _parse(self, stream, context, path):
return self.subcon._parsereport(stream, context, path)
def _build(self, obj, stream, context, path):
return self.subcon._build(obj, stream, context, path)
def _sizeof(self, context, path):
return self.subcon._sizeof(context, path)
class Adapter(Subconstruct):
r"""
Abstract adapter class.
Needs to implement `_decode()` for parsing and `_encode()` for building.
:param subcon: Construct instance
"""
def _parse(self, stream, context, path):
obj = self.subcon._parsereport(stream, context, path)
return self._decode(obj, context, path)
def _build(self, obj, stream, context, path):
obj2 = self._encode(obj, context, path)
buildret = self.subcon._build(obj2, stream, context, path)
return obj
def _decode(self, obj, context, path):
raise NotImplementedError
def _encode(self, obj, context, path):
raise NotImplementedError
class SymmetricAdapter(Adapter):
r"""
Abstract adapter class.
Needs to implement `_decode()` only, for both parsing and building.
:param subcon: Construct instance
"""
def _encode(self, obj, context, path):
return self._decode(obj, context, path)
class Validator(SymmetricAdapter):
r"""
Abstract class that validates a condition on the encoded/decoded object.
Needs to implement `_validate()` that returns a bool (or a truthy value)
:param subcon: Construct instance
"""
def _decode(self, obj, context, path):
if not self._validate(obj, context, path):
raise ValidationError("object failed validation: %s" % (obj,), path=path)
return obj
def _validate(self, obj, context, path):
raise NotImplementedError
class Tunnel(Subconstruct):
r"""
Abstract class that allows other constructs to read part of the stream as if they were reading the entire stream. See Prefixed for example.
Needs to implement `_decode()` for parsing and `_encode()` for building.
"""
def _parse(self, stream, context, path):
data = stream_read_entire(stream, path) # reads entire stream
data = self._decode(data, context, path)
return self.subcon.parse(data, **context)
def _build(self, obj, stream, context, path):
stream2 = io.BytesIO()
buildret = self.subcon._build(obj, stream2, context, path)
data = stream2.getvalue()
data = self._encode(data, context, path)
stream_write(stream, data, len(data), path)
return obj
def _sizeof(self, context, path):
raise SizeofError(path=path)
def _decode(self, data, context, path):
raise NotImplementedError
def _encode(self, data, context, path):
raise NotImplementedError
class Compiled(Construct):
"""Used internally."""
def __init__(self, parsefunc, buildfunc):
super().__init__()
self.source = None
self.defersubcon = None
self.parsefunc = parsefunc
self.buildfunc = buildfunc
def _parse(self, stream, context, path):
return self.parsefunc(stream, context)
def _build(self, obj, stream, context, path):
return self.buildfunc(obj, stream, context)
def _sizeof(self, context, path):
return self.defersubcon._sizeof(context, path)
def compile(self, filename=None):
return self
def benchmark(self, sampledata, filename=None):
return self.defersubcon.benchmark(sampledata, filename)
#===============================================================================
# bytes and bits
#===============================================================================
class Bytes(Construct):
r"""
Field consisting of a specified number of bytes.
Parses into a bytes (of given length). Builds into the stream directly (but checks that given object matches specified length). Can also build from an integer for convenience (although BytesInteger should be used instead). Size is the specified length.
Can also build from a bytearray.
:param length: integer or context lambda
:raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
:raises StringError: building from non-bytes value, perhaps unicode
Can propagate any exception from the lambda, possibly non-ConstructError.
Example::
>>> d = Bytes(4)
>>> d.parse(b'beef')
b'beef'
>>> d.build(b'beef')
b'beef'
>>> d.build(0)
b'\x00\x00\x00\x00'
>>> d.sizeof()
4
>>> d = Struct(
... "length" / Int8ub,
... "data" / Bytes(this.length),
... )
>>> d.parse(b"\x04beef")
Container(length=4, data=b'beef')
>>> d.sizeof()
construct.core.SizeofError: cannot calculate size, key not found in context
"""
def __init__(self, length):
super().__init__()
self.length = length
def _parse(self, stream, context, path):
length = self.length(context) if callable(self.length) else self.length
return stream_read(stream, length, path)
def _build(self, obj, stream, context, path):
length = self.length(context) if callable(self.length) else self.length
data = integer2bytes(obj, length) if isinstance(obj, int) else obj
data = bytes(data) if type(data) is bytearray else data
stream_write(stream, data, length, path)
return data
def _sizeof(self, context, path):
try:
return self.length(context) if callable(self.length) else self.length
except (KeyError, AttributeError):
raise SizeofError("cannot calculate size, key not found in context", path=path)
def _emitparse(self, code):
return f"io.read({self.length})"
def _emitbuild(self, code):
return f"(io.write(obj), obj)[1]"
def _emitfulltype(self, ksy, bitwise):
return dict(size=self.length)
@singleton
class GreedyBytes(Construct):
r"""
Field consisting of unknown number of bytes.
Parses the stream to the end. Builds into the stream directly (without checks). Size is undefined.
Can also build from a bytearray.