forked from micropython/micropython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mpy-tool.py
executable file
·1821 lines (1592 loc) · 64.9 KB
/
mpy-tool.py
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
#!/usr/bin/env python3
#
# This file is part of the MicroPython project, http://micropython.org/
#
# The MIT License (MIT)
#
# Copyright (c) 2016-2019 Damien P. George
#
# 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.
# Python 2/3 compatibility code
from __future__ import print_function
import platform
if platform.python_version_tuple()[0] == "2":
from binascii import hexlify as hexlify_py2
str_cons = lambda val, enc=None: str(val)
bytes_cons = lambda val, enc=None: bytearray(val)
is_str_type = lambda o: isinstance(o, str)
is_bytes_type = lambda o: type(o) is bytearray
is_int_type = lambda o: isinstance(o, int) or isinstance(o, long) # noqa: F821
def hexlify_to_str(b):
x = hexlify_py2(b)
return ":".join(x[i : i + 2] for i in range(0, len(x), 2))
else:
from binascii import hexlify
str_cons = str
bytes_cons = bytes
is_str_type = lambda o: isinstance(o, str)
is_bytes_type = lambda o: isinstance(o, bytes)
is_int_type = lambda o: isinstance(o, int)
def hexlify_to_str(b):
return str(hexlify(b, ":"), "ascii")
# end compatibility code
import sys
import struct
sys.path.append(sys.path[0] + "/../py")
import makeqstrdata as qstrutil
# Threshold of str length below which it will be turned into a qstr when freezing.
# This helps to reduce frozen code size because qstrs are more efficient to encode
# as objects than full mp_obj_str_t instances.
PERSISTENT_STR_INTERN_THRESHOLD = 25
class MPYReadError(Exception):
def __init__(self, filename, msg):
self.filename = filename
self.msg = msg
def __str__(self):
return "%s: %s" % (self.filename, self.msg)
class FreezeError(Exception):
def __init__(self, rawcode, msg):
self.rawcode = rawcode
self.msg = msg
def __str__(self):
return "error while freezing %s: %s" % (self.rawcode.source_file, self.msg)
class Config:
MPY_VERSION = 6
MPY_SUB_VERSION = 1
MICROPY_LONGINT_IMPL_NONE = 0
MICROPY_LONGINT_IMPL_LONGLONG = 1
MICROPY_LONGINT_IMPL_MPZ = 2
config = Config()
MP_CODE_BYTECODE = 2
MP_CODE_NATIVE_PY = 3
MP_CODE_NATIVE_VIPER = 4
MP_CODE_NATIVE_ASM = 5
MP_NATIVE_ARCH_NONE = 0
MP_NATIVE_ARCH_X86 = 1
MP_NATIVE_ARCH_X64 = 2
MP_NATIVE_ARCH_ARMV6 = 3
MP_NATIVE_ARCH_ARMV6M = 4
MP_NATIVE_ARCH_ARMV7M = 5
MP_NATIVE_ARCH_ARMV7EM = 6
MP_NATIVE_ARCH_ARMV7EMSP = 7
MP_NATIVE_ARCH_ARMV7EMDP = 8
MP_NATIVE_ARCH_XTENSA = 9
MP_NATIVE_ARCH_XTENSAWIN = 10
MP_PERSISTENT_OBJ_FUN_TABLE = 0
MP_PERSISTENT_OBJ_NONE = 1
MP_PERSISTENT_OBJ_FALSE = 2
MP_PERSISTENT_OBJ_TRUE = 3
MP_PERSISTENT_OBJ_ELLIPSIS = 4
MP_PERSISTENT_OBJ_STR = 5
MP_PERSISTENT_OBJ_BYTES = 6
MP_PERSISTENT_OBJ_INT = 7
MP_PERSISTENT_OBJ_FLOAT = 8
MP_PERSISTENT_OBJ_COMPLEX = 9
MP_PERSISTENT_OBJ_TUPLE = 10
MP_SCOPE_FLAG_VIPERRELOC = 0x10
MP_SCOPE_FLAG_VIPERRODATA = 0x20
MP_SCOPE_FLAG_VIPERBSS = 0x40
MP_BC_MASK_EXTRA_BYTE = 0x9E
MP_BC_FORMAT_BYTE = 0
MP_BC_FORMAT_QSTR = 1
MP_BC_FORMAT_VAR_UINT = 2
MP_BC_FORMAT_OFFSET = 3
mp_unary_op_method_name = (
"__pos__",
"__neg__",
"__invert__",
"<not>",
)
mp_binary_op_method_name = (
"__lt__",
"__gt__",
"__eq__",
"__le__",
"__ge__",
"__ne__",
"<in>",
"<is>",
"<exception match>",
"__ior__",
"__ixor__",
"__iand__",
"__ilshift__",
"__irshift__",
"__iadd__",
"__isub__",
"__imul__",
"__imatmul__",
"__ifloordiv__",
"__itruediv__",
"__imod__",
"__ipow__",
"__or__",
"__xor__",
"__and__",
"__lshift__",
"__rshift__",
"__add__",
"__sub__",
"__mul__",
"__matmul__",
"__floordiv__",
"__truediv__",
"__mod__",
"__pow__",
)
class Opcode:
# fmt: off
# Load, Store, Delete, Import, Make, Build, Unpack, Call, Jump, Exception, For, sTack, Return, Yield, Op
MP_BC_BASE_RESERVED = (0x00) # ----------------
MP_BC_BASE_QSTR_O = (0x10) # LLLLLLSSSDDII---
MP_BC_BASE_VINT_E = (0x20) # MMLLLLSSDDBBBBBB
MP_BC_BASE_VINT_O = (0x30) # UUMMCCCC--------
MP_BC_BASE_JUMP_E = (0x40) # J-JJJJJEEEEF----
MP_BC_BASE_BYTE_O = (0x50) # LLLLSSDTTTTTEEFF
MP_BC_BASE_BYTE_E = (0x60) # --BREEEYYI------
MP_BC_LOAD_CONST_SMALL_INT_MULTI = (0x70) # LLLLLLLLLLLLLLLL
# = (0x80) # LLLLLLLLLLLLLLLL
# = (0x90) # LLLLLLLLLLLLLLLL
# = (0xa0) # LLLLLLLLLLLLLLLL
MP_BC_LOAD_FAST_MULTI = (0xb0) # LLLLLLLLLLLLLLLL
MP_BC_STORE_FAST_MULTI = (0xc0) # SSSSSSSSSSSSSSSS
MP_BC_UNARY_OP_MULTI = (0xd0) # OOOOOOO
MP_BC_BINARY_OP_MULTI = (0xd7) # OOOOOOOOO
# = (0xe0) # OOOOOOOOOOOOOOOO
# = (0xf0) # OOOOOOOOOO------
MP_BC_LOAD_CONST_SMALL_INT_MULTI_NUM = 64
MP_BC_LOAD_CONST_SMALL_INT_MULTI_EXCESS = 16
MP_BC_LOAD_FAST_MULTI_NUM = 16
MP_BC_STORE_FAST_MULTI_NUM = 16
MP_BC_UNARY_OP_MULTI_NUM = 4 # MP_UNARY_OP_NUM_BYTECODE
MP_BC_BINARY_OP_MULTI_NUM = 35 # MP_BINARY_OP_NUM_BYTECODE
MP_BC_LOAD_CONST_FALSE = (MP_BC_BASE_BYTE_O + 0x00)
MP_BC_LOAD_CONST_NONE = (MP_BC_BASE_BYTE_O + 0x01)
MP_BC_LOAD_CONST_TRUE = (MP_BC_BASE_BYTE_O + 0x02)
MP_BC_LOAD_CONST_SMALL_INT = (MP_BC_BASE_VINT_E + 0x02) # signed var-int
MP_BC_LOAD_CONST_STRING = (MP_BC_BASE_QSTR_O + 0x00) # qstr
MP_BC_LOAD_CONST_OBJ = (MP_BC_BASE_VINT_E + 0x03) # ptr
MP_BC_LOAD_NULL = (MP_BC_BASE_BYTE_O + 0x03)
MP_BC_LOAD_FAST_N = (MP_BC_BASE_VINT_E + 0x04) # uint
MP_BC_LOAD_DEREF = (MP_BC_BASE_VINT_E + 0x05) # uint
MP_BC_LOAD_NAME = (MP_BC_BASE_QSTR_O + 0x01) # qstr
MP_BC_LOAD_GLOBAL = (MP_BC_BASE_QSTR_O + 0x02) # qstr
MP_BC_LOAD_ATTR = (MP_BC_BASE_QSTR_O + 0x03) # qstr
MP_BC_LOAD_METHOD = (MP_BC_BASE_QSTR_O + 0x04) # qstr
MP_BC_LOAD_SUPER_METHOD = (MP_BC_BASE_QSTR_O + 0x05) # qstr
MP_BC_LOAD_BUILD_CLASS = (MP_BC_BASE_BYTE_O + 0x04)
MP_BC_LOAD_SUBSCR = (MP_BC_BASE_BYTE_O + 0x05)
MP_BC_STORE_FAST_N = (MP_BC_BASE_VINT_E + 0x06) # uint
MP_BC_STORE_DEREF = (MP_BC_BASE_VINT_E + 0x07) # uint
MP_BC_STORE_NAME = (MP_BC_BASE_QSTR_O + 0x06) # qstr
MP_BC_STORE_GLOBAL = (MP_BC_BASE_QSTR_O + 0x07) # qstr
MP_BC_STORE_ATTR = (MP_BC_BASE_QSTR_O + 0x08) # qstr
MP_BC_STORE_SUBSCR = (MP_BC_BASE_BYTE_O + 0x06)
MP_BC_DELETE_FAST = (MP_BC_BASE_VINT_E + 0x08) # uint
MP_BC_DELETE_DEREF = (MP_BC_BASE_VINT_E + 0x09) # uint
MP_BC_DELETE_NAME = (MP_BC_BASE_QSTR_O + 0x09) # qstr
MP_BC_DELETE_GLOBAL = (MP_BC_BASE_QSTR_O + 0x0a) # qstr
MP_BC_DUP_TOP = (MP_BC_BASE_BYTE_O + 0x07)
MP_BC_DUP_TOP_TWO = (MP_BC_BASE_BYTE_O + 0x08)
MP_BC_POP_TOP = (MP_BC_BASE_BYTE_O + 0x09)
MP_BC_ROT_TWO = (MP_BC_BASE_BYTE_O + 0x0a)
MP_BC_ROT_THREE = (MP_BC_BASE_BYTE_O + 0x0b)
MP_BC_UNWIND_JUMP = (MP_BC_BASE_JUMP_E + 0x00) # signed relative bytecode offset; then a byte
MP_BC_JUMP = (MP_BC_BASE_JUMP_E + 0x02) # signed relative bytecode offset
MP_BC_POP_JUMP_IF_TRUE = (MP_BC_BASE_JUMP_E + 0x03) # signed relative bytecode offset
MP_BC_POP_JUMP_IF_FALSE = (MP_BC_BASE_JUMP_E + 0x04) # signed relative bytecode offset
MP_BC_JUMP_IF_TRUE_OR_POP = (MP_BC_BASE_JUMP_E + 0x05) # unsigned relative bytecode offset
MP_BC_JUMP_IF_FALSE_OR_POP = (MP_BC_BASE_JUMP_E + 0x06) # unsigned relative bytecode offset
MP_BC_SETUP_WITH = (MP_BC_BASE_JUMP_E + 0x07) # unsigned relative bytecode offset
MP_BC_SETUP_EXCEPT = (MP_BC_BASE_JUMP_E + 0x08) # unsigned relative bytecode offset
MP_BC_SETUP_FINALLY = (MP_BC_BASE_JUMP_E + 0x09) # unsigned relative bytecode offset
MP_BC_POP_EXCEPT_JUMP = (MP_BC_BASE_JUMP_E + 0x0a) # unsigned relative bytecode offset
MP_BC_FOR_ITER = (MP_BC_BASE_JUMP_E + 0x0b) # unsigned relative bytecode offset
MP_BC_WITH_CLEANUP = (MP_BC_BASE_BYTE_O + 0x0c)
MP_BC_END_FINALLY = (MP_BC_BASE_BYTE_O + 0x0d)
MP_BC_GET_ITER = (MP_BC_BASE_BYTE_O + 0x0e)
MP_BC_GET_ITER_STACK = (MP_BC_BASE_BYTE_O + 0x0f)
MP_BC_BUILD_TUPLE = (MP_BC_BASE_VINT_E + 0x0a) # uint
MP_BC_BUILD_LIST = (MP_BC_BASE_VINT_E + 0x0b) # uint
MP_BC_BUILD_MAP = (MP_BC_BASE_VINT_E + 0x0c) # uint
MP_BC_STORE_MAP = (MP_BC_BASE_BYTE_E + 0x02)
MP_BC_BUILD_SET = (MP_BC_BASE_VINT_E + 0x0d) # uint
MP_BC_BUILD_SLICE = (MP_BC_BASE_VINT_E + 0x0e) # uint
MP_BC_STORE_COMP = (MP_BC_BASE_VINT_E + 0x0f) # uint
MP_BC_UNPACK_SEQUENCE = (MP_BC_BASE_VINT_O + 0x00) # uint
MP_BC_UNPACK_EX = (MP_BC_BASE_VINT_O + 0x01) # uint
MP_BC_RETURN_VALUE = (MP_BC_BASE_BYTE_E + 0x03)
MP_BC_RAISE_LAST = (MP_BC_BASE_BYTE_E + 0x04)
MP_BC_RAISE_OBJ = (MP_BC_BASE_BYTE_E + 0x05)
MP_BC_RAISE_FROM = (MP_BC_BASE_BYTE_E + 0x06)
MP_BC_YIELD_VALUE = (MP_BC_BASE_BYTE_E + 0x07)
MP_BC_YIELD_FROM = (MP_BC_BASE_BYTE_E + 0x08)
MP_BC_MAKE_FUNCTION = (MP_BC_BASE_VINT_O + 0x02) # uint
MP_BC_MAKE_FUNCTION_DEFARGS = (MP_BC_BASE_VINT_O + 0x03) # uint
MP_BC_MAKE_CLOSURE = (MP_BC_BASE_VINT_E + 0x00) # uint; extra byte
MP_BC_MAKE_CLOSURE_DEFARGS = (MP_BC_BASE_VINT_E + 0x01) # uint; extra byte
MP_BC_CALL_FUNCTION = (MP_BC_BASE_VINT_O + 0x04) # uint
MP_BC_CALL_FUNCTION_VAR_KW = (MP_BC_BASE_VINT_O + 0x05) # uint
MP_BC_CALL_METHOD = (MP_BC_BASE_VINT_O + 0x06) # uint
MP_BC_CALL_METHOD_VAR_KW = (MP_BC_BASE_VINT_O + 0x07) # uint
MP_BC_IMPORT_NAME = (MP_BC_BASE_QSTR_O + 0x0b) # qstr
MP_BC_IMPORT_FROM = (MP_BC_BASE_QSTR_O + 0x0c) # qstr
MP_BC_IMPORT_STAR = (MP_BC_BASE_BYTE_E + 0x09)
# fmt: on
# Create sets of related opcodes.
ALL_OFFSET_SIGNED = (
MP_BC_UNWIND_JUMP,
MP_BC_JUMP,
MP_BC_POP_JUMP_IF_TRUE,
MP_BC_POP_JUMP_IF_FALSE,
)
# Create a dict mapping opcode value to opcode name.
mapping = ["unknown" for _ in range(256)]
for op_name in list(locals()):
if op_name.startswith("MP_BC_"):
mapping[locals()[op_name]] = op_name[len("MP_BC_") :]
for i in range(MP_BC_LOAD_CONST_SMALL_INT_MULTI_NUM):
name = "LOAD_CONST_SMALL_INT %d" % (i - MP_BC_LOAD_CONST_SMALL_INT_MULTI_EXCESS)
mapping[MP_BC_LOAD_CONST_SMALL_INT_MULTI + i] = name
for i in range(MP_BC_LOAD_FAST_MULTI_NUM):
mapping[MP_BC_LOAD_FAST_MULTI + i] = "LOAD_FAST %d" % i
for i in range(MP_BC_STORE_FAST_MULTI_NUM):
mapping[MP_BC_STORE_FAST_MULTI + i] = "STORE_FAST %d" % i
for i in range(MP_BC_UNARY_OP_MULTI_NUM):
mapping[MP_BC_UNARY_OP_MULTI + i] = "UNARY_OP %d %s" % (i, mp_unary_op_method_name[i])
for i in range(MP_BC_BINARY_OP_MULTI_NUM):
mapping[MP_BC_BINARY_OP_MULTI + i] = "BINARY_OP %d %s" % (i, mp_binary_op_method_name[i])
def __init__(self, offset, fmt, opcode_byte, arg, extra_arg):
self.offset = offset
self.fmt = fmt
self.opcode_byte = opcode_byte
self.arg = arg
self.extra_arg = extra_arg
# This definition of a small int covers all possible targets, in the sense that every
# target can encode as a small int, an integer that passes this test. The minimum is set
# by MICROPY_OBJ_REPR_B on a 16-bit machine, where there are 14 bits for the small int.
def mp_small_int_fits(i):
return -0x2000 <= i <= 0x1FFF
def mp_encode_uint(val, signed=False):
encoded = bytearray([val & 0x7F])
val >>= 7
while val != 0 and val != -1:
encoded.insert(0, 0x80 | (val & 0x7F))
val >>= 7
if signed:
if val == -1 and encoded[0] & 0x40 == 0:
encoded.insert(0, 0xFF)
elif val == 0 and encoded[0] & 0x40 != 0:
encoded.insert(0, 0x80)
return encoded
def mp_opcode_decode(bytecode, ip):
opcode = bytecode[ip]
ip_start = ip
f = (0x000003A4 >> (2 * ((opcode) >> 4))) & 3
ip += 1
arg = None
extra_arg = None
if f in (MP_BC_FORMAT_QSTR, MP_BC_FORMAT_VAR_UINT):
arg = bytecode[ip] & 0x7F
if opcode == Opcode.MP_BC_LOAD_CONST_SMALL_INT and arg & 0x40 != 0:
arg |= -1 << 7
while bytecode[ip] & 0x80 != 0:
ip += 1
arg = arg << 7 | bytecode[ip] & 0x7F
ip += 1
elif f == MP_BC_FORMAT_OFFSET:
if bytecode[ip] & 0x80 == 0:
arg = bytecode[ip]
ip += 1
if opcode in Opcode.ALL_OFFSET_SIGNED:
arg -= 0x40
else:
arg = bytecode[ip] & 0x7F | bytecode[ip + 1] << 7
ip += 2
if opcode in Opcode.ALL_OFFSET_SIGNED:
arg -= 0x4000
if opcode & MP_BC_MASK_EXTRA_BYTE == 0:
extra_arg = bytecode[ip]
ip += 1
return f, ip - ip_start, arg, extra_arg
def mp_opcode_encode(opcode):
overflow = False
encoded = bytearray([opcode.opcode_byte])
if opcode.fmt in (MP_BC_FORMAT_QSTR, MP_BC_FORMAT_VAR_UINT):
signed = opcode.opcode_byte == Opcode.MP_BC_LOAD_CONST_SMALL_INT
encoded.extend(mp_encode_uint(opcode.arg, signed))
elif opcode.fmt == MP_BC_FORMAT_OFFSET:
is_signed = opcode.opcode_byte in Opcode.ALL_OFFSET_SIGNED
# The -2 accounts for this jump opcode taking 2 bytes (at least).
bytecode_offset = opcode.target.offset - opcode.offset - 2
# Check if the bytecode_offset is small enough to use a 1-byte encoding.
if (is_signed and -64 <= bytecode_offset <= 63) or (
not is_signed and bytecode_offset <= 127
):
# Use a 1-byte jump offset.
if is_signed:
bytecode_offset += 0x40
overflow = not (0 <= bytecode_offset <= 0x7F)
encoded.append(bytecode_offset & 0x7F)
else:
bytecode_offset -= 1
if is_signed:
bytecode_offset += 0x4000
overflow = not (0 <= bytecode_offset <= 0x7FFF)
encoded.append(0x80 | (bytecode_offset & 0x7F))
encoded.append((bytecode_offset >> 7) & 0xFF)
if opcode.extra_arg is not None:
encoded.append(opcode.extra_arg)
return overflow, encoded
def read_prelude_sig(read_byte):
z = read_byte()
# xSSSSEAA
S = (z >> 3) & 0xF
E = (z >> 2) & 0x1
F = 0
A = z & 0x3
K = 0
D = 0
n = 0
while z & 0x80:
z = read_byte()
# xFSSKAED
S |= (z & 0x30) << (2 * n)
E |= (z & 0x02) << n
F |= ((z & 0x40) >> 6) << n
A |= (z & 0x4) << n
K |= ((z & 0x08) >> 3) << n
D |= (z & 0x1) << n
n += 1
S += 1
return S, E, F, A, K, D
def read_prelude_size(read_byte):
I = 0
C = 0
n = 0
while True:
z = read_byte()
# xIIIIIIC
I |= ((z & 0x7E) >> 1) << (6 * n)
C |= (z & 1) << n
if not (z & 0x80):
break
n += 1
return I, C
# See py/bc.h:MP_BC_PRELUDE_SIZE_ENCODE macro.
def encode_prelude_size(I, C):
# Encode bit-wise as: xIIIIIIC
encoded = bytearray()
while True:
z = (I & 0x3F) << 1 | (C & 1)
C >>= 1
I >>= 6
if C | I:
z |= 0x80
encoded.append(z)
if not C | I:
return encoded
def extract_prelude(bytecode, ip):
def local_read_byte():
b = bytecode[ip_ref[0]]
ip_ref[0] += 1
return b
ip_ref = [ip] # to close over ip in Python 2 and 3
# Read prelude signature.
(
n_state,
n_exc_stack,
scope_flags,
n_pos_args,
n_kwonly_args,
n_def_pos_args,
) = read_prelude_sig(local_read_byte)
offset_prelude_size = ip_ref[0]
# Read prelude size.
n_info, n_cell = read_prelude_size(local_read_byte)
offset_source_info = ip_ref[0]
# Extract simple_name and argument qstrs (var uints).
args = []
for arg_num in range(1 + n_pos_args + n_kwonly_args):
value = 0
while True:
b = local_read_byte()
value = (value << 7) | (b & 0x7F)
if b & 0x80 == 0:
break
args.append(value)
offset_line_info = ip_ref[0]
offset_closure_info = offset_source_info + n_info
offset_opcodes = offset_source_info + n_info + n_cell
return (
offset_prelude_size,
offset_source_info,
offset_line_info,
offset_closure_info,
offset_opcodes,
(n_state, n_exc_stack, scope_flags, n_pos_args, n_kwonly_args, n_def_pos_args),
(n_info, n_cell),
args,
)
class QStrType:
def __init__(self, str):
self.str = str
self.qstr_esc = qstrutil.qstr_escape(self.str)
self.qstr_id = "MP_QSTR_" + self.qstr_esc
class GlobalQStrList:
def __init__(self):
# Initialise global list of qstrs with static qstrs
self.qstrs = [None] # MP_QSTRnull should never be referenced
for n in qstrutil.static_qstr_list:
self.qstrs.append(QStrType(n))
def add(self, s):
q = QStrType(s)
self.qstrs.append(q)
return q
def get_by_index(self, i):
return self.qstrs[i]
def find_by_str(self, s):
for q in self.qstrs:
if q is not None and q.str == s:
return q
return None
class MPFunTable:
def __repr__(self):
return "mp_fun_table"
class CompiledModule:
def __init__(
self,
mpy_source_file,
mpy_segments,
header,
qstr_table,
obj_table,
raw_code,
qstr_table_file_offset,
obj_table_file_offset,
raw_code_file_offset,
escaped_name,
):
self.mpy_source_file = mpy_source_file
self.mpy_segments = mpy_segments
self.source_file = qstr_table[0]
self.header = header
self.qstr_table = qstr_table
self.obj_table = obj_table
self.raw_code = raw_code
self.qstr_table_file_offset = qstr_table_file_offset
self.obj_table_file_offset = obj_table_file_offset
self.raw_code_file_offset = raw_code_file_offset
self.escaped_name = escaped_name
def hexdump(self):
with open(self.mpy_source_file, "rb") as f:
WIDTH = 16
COL_OFF = "\033[0m"
COL_TABLE = (
("", ""), # META
("\033[0;31m", "\033[0;91m"), # QSTR
("\033[0;32m", "\033[0;92m"), # OBJ
("\033[0;34m", "\033[0;94m"), # CODE
)
cur_col = ""
cur_col_index = 0
offset = 0
segment_index = 0
while True:
data = bytes_cons(f.read(WIDTH))
if not data:
break
# Print out the hex dump of this line of data.
line_hex = cur_col
line_chr = cur_col
line_comment = ""
for i in range(len(data)):
# Determine the colour of the data, if any, and the line comment.
while segment_index < len(self.mpy_segments):
if offset + i == self.mpy_segments[segment_index].start:
cur_col = COL_TABLE[self.mpy_segments[segment_index].kind][
cur_col_index
]
cur_col_index = 1 - cur_col_index
line_hex += cur_col
line_chr += cur_col
line_comment += " %s%s%s" % (
cur_col,
self.mpy_segments[segment_index].name,
COL_OFF,
)
if offset + i == self.mpy_segments[segment_index].end:
cur_col = ""
line_hex += COL_OFF
line_chr += COL_OFF
segment_index += 1
else:
break
# Add to the hex part of the line.
if i % 2 == 0:
line_hex += " "
line_hex += "%02x" % data[i]
# Add to the characters part of the line.
if 0x20 <= data[i] <= 0x7E:
line_chr += "%s" % chr(data[i])
else:
line_chr += "."
# Print out this line.
if cur_col:
line_hex += COL_OFF
line_chr += COL_OFF
pad = " " * ((WIDTH - len(data)) * 5 // 2)
print("%08x:%s%s %s %s" % (offset, line_hex, pad, line_chr, line_comment))
offset += WIDTH
def disassemble(self):
print("mpy_source_file:", self.mpy_source_file)
print("source_file:", self.source_file.str)
print("header:", hexlify_to_str(self.header))
print("qstr_table[%u]:" % len(self.qstr_table))
for q in self.qstr_table:
print(" %s" % q.str)
print("obj_table:", self.obj_table)
self.raw_code.disassemble()
def freeze(self, compiled_module_index):
print()
print("/" * 80)
print("// frozen module %s" % self.escaped_name)
print("// - original source file: %s" % self.mpy_source_file)
print("// - frozen file name: %s" % self.source_file.str)
print("// - .mpy header: %s" % ":".join("%02x" % b for b in self.header))
print()
self.raw_code.freeze()
print()
self.freeze_constants()
print()
print("static const mp_frozen_module_t frozen_module_%s = {" % self.escaped_name)
print(" .constants = {")
if len(self.qstr_table):
print(
" .qstr_table = (qstr_short_t *)&const_qstr_table_data_%s,"
% self.escaped_name
)
else:
print(" .qstr_table = NULL,")
if len(self.obj_table):
print(" .obj_table = (mp_obj_t *)&const_obj_table_data_%s," % self.escaped_name)
else:
print(" .obj_table = NULL,")
print(" },")
print(" .rc = &raw_code_%s," % self.raw_code.escaped_name)
print("};")
def freeze_constant_obj(self, obj_name, obj):
global const_str_content, const_int_content, const_obj_content
if isinstance(obj, MPFunTable):
return "&mp_fun_table"
elif obj is None:
return "MP_ROM_NONE"
elif obj is False:
return "MP_ROM_FALSE"
elif obj is True:
return "MP_ROM_TRUE"
elif obj is Ellipsis:
return "MP_ROM_PTR(&mp_const_ellipsis_obj)"
elif is_str_type(obj) or is_bytes_type(obj):
if len(obj) == 0:
if is_str_type(obj):
return "MP_ROM_QSTR(MP_QSTR_)"
else:
return "MP_ROM_PTR(&mp_const_empty_bytes_obj)"
if is_str_type(obj):
q = global_qstrs.find_by_str(obj)
if q:
return "MP_ROM_QSTR(%s)" % q.qstr_id
obj = bytes_cons(obj, "utf8")
obj_type = "mp_type_str"
else:
obj_type = "mp_type_bytes"
print(
'static const mp_obj_str_t %s = {{&%s}, %u, %u, (const byte*)"%s"};'
% (
obj_name,
obj_type,
qstrutil.compute_hash(obj, config.MICROPY_QSTR_BYTES_IN_HASH),
len(obj),
"".join(("\\x%02x" % b) for b in obj),
)
)
const_str_content += len(obj)
const_obj_content += 4 * 4
return "MP_ROM_PTR(&%s)" % obj_name
elif is_int_type(obj):
if mp_small_int_fits(obj):
# Encode directly as a small integer object.
return "MP_ROM_INT(%d)" % obj
elif config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_NONE:
raise FreezeError(self, "target does not support long int")
elif config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_LONGLONG:
# TODO
raise FreezeError(self, "freezing int to long-long is not implemented")
elif config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_MPZ:
neg = 0
if obj < 0:
obj = -obj
neg = 1
bits_per_dig = config.MPZ_DIG_SIZE
digs = []
z = obj
while z:
digs.append(z & ((1 << bits_per_dig) - 1))
z >>= bits_per_dig
ndigs = len(digs)
digs = ",".join(("%#x" % d) for d in digs)
print(
"static const mp_obj_int_t %s = {{&mp_type_int}, "
"{.neg=%u, .fixed_dig=1, .alloc=%u, .len=%u, .dig=(uint%u_t*)(const uint%u_t[]){%s}}};"
% (obj_name, neg, ndigs, ndigs, bits_per_dig, bits_per_dig, digs)
)
const_int_content += (digs.count(",") + 1) * bits_per_dig // 8
const_obj_content += 4 * 4
return "MP_ROM_PTR(&%s)" % obj_name
elif isinstance(obj, float):
macro_name = "%s_macro" % obj_name
print(
"#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_B"
)
print(
"static const mp_obj_float_t %s = {{&mp_type_float}, (mp_float_t)%.16g};"
% (obj_name, obj)
)
print("#define %s MP_ROM_PTR(&%s)" % (macro_name, obj_name))
print("#elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C")
n = struct.unpack("<I", struct.pack("<f", obj))[0]
n = ((n & ~0x3) | 2) + 0x80800000
print("#define %s ((mp_rom_obj_t)(0x%08x))" % (macro_name, n))
print("#elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D")
n = struct.unpack("<Q", struct.pack("<d", obj))[0]
n += 0x8004000000000000
print("#define %s ((mp_rom_obj_t)(0x%016x))" % (macro_name, n))
print("#endif")
const_obj_content += 3 * 4
return macro_name
elif isinstance(obj, complex):
print(
"static const mp_obj_complex_t %s = {{&mp_type_complex}, (mp_float_t)%.16g, (mp_float_t)%.16g};"
% (obj_name, obj.real, obj.imag)
)
return "MP_ROM_PTR(&%s)" % obj_name
elif type(obj) is tuple:
if len(obj) == 0:
return "MP_ROM_PTR(&mp_const_empty_tuple_obj)"
else:
obj_refs = []
for i, sub_obj in enumerate(obj):
sub_obj_name = "%s_%u" % (obj_name, i)
obj_refs.append(self.freeze_constant_obj(sub_obj_name, sub_obj))
print(
"static const mp_rom_obj_tuple_t %s = {{&mp_type_tuple}, %d, {"
% (obj_name, len(obj))
)
for ref in obj_refs:
print(" %s," % ref)
print("}};")
return "MP_ROM_PTR(&%s)" % obj_name
else:
raise FreezeError(self, "freezing of object %r is not implemented" % (obj,))
def freeze_constants(self):
if len(self.qstr_table):
print(
"static const qstr_short_t const_qstr_table_data_%s[%u] = {"
% (self.escaped_name, len(self.qstr_table))
)
for q in self.qstr_table:
print(" %s," % q.qstr_id)
print("};")
if not len(self.obj_table):
return
# generate constant objects
print()
print("// constants")
obj_refs = []
for i, obj in enumerate(self.obj_table):
obj_name = "const_obj_%s_%u" % (self.escaped_name, i)
obj_refs.append(self.freeze_constant_obj(obj_name, obj))
# generate constant table
print()
print("// constant table")
print(
"static const mp_rom_obj_t const_obj_table_data_%s[%u] = {"
% (self.escaped_name, len(self.obj_table))
)
for ref in obj_refs:
print(" %s," % ref)
print("};")
global const_table_ptr_content
const_table_ptr_content += len(self.obj_table)
class RawCode(object):
# a set of all escaped names, to make sure they are unique
escaped_names = set()
# convert code kind number to string
code_kind_str = {
MP_CODE_BYTECODE: "MP_CODE_BYTECODE",
MP_CODE_NATIVE_PY: "MP_CODE_NATIVE_PY",
MP_CODE_NATIVE_VIPER: "MP_CODE_NATIVE_VIPER",
MP_CODE_NATIVE_ASM: "MP_CODE_NATIVE_ASM",
}
def __init__(self, parent_name, qstr_table, fun_data, prelude_offset, code_kind):
self.qstr_table = qstr_table
self.fun_data = fun_data
self.prelude_offset = prelude_offset
self.code_kind = code_kind
if code_kind in (MP_CODE_BYTECODE, MP_CODE_NATIVE_PY):
(
self.offset_prelude_size,
self.offset_source_info,
self.offset_line_info,
self.offset_closure_info,
self.offset_opcodes,
self.prelude_signature,
self.prelude_size,
self.names,
) = extract_prelude(self.fun_data, prelude_offset)
self.scope_flags = self.prelude_signature[2]
self.n_pos_args = self.prelude_signature[3]
self.simple_name = self.qstr_table[self.names[0]]
else:
self.simple_name = self.qstr_table[0]
escaped_name = parent_name + "_" + self.simple_name.qstr_esc
# make sure the escaped name is unique
i = 2
unique_escaped_name = escaped_name
while unique_escaped_name in self.escaped_names:
unique_escaped_name = escaped_name + str(i)
i += 1
self.escaped_names.add(unique_escaped_name)
self.escaped_name = unique_escaped_name
def disassemble_children(self):
print(" children:", [rc.simple_name.str for rc in self.children])
for rc in self.children:
rc.disassemble()
def freeze_children(self, prelude_ptr=None):
# Freeze children and generate table of children.
if len(self.children):
for rc in self.children:
print("// child of %s" % self.escaped_name)
rc.freeze()
print()
print("static const mp_raw_code_t *const children_%s[] = {" % self.escaped_name)
for rc in self.children:
print(" &raw_code_%s," % rc.escaped_name)
if prelude_ptr:
print(" (void *)%s," % prelude_ptr)
print("};")
print()
def freeze_raw_code(self, prelude_ptr=None, type_sig=0):
# Generate mp_raw_code_t.
print("static const mp_raw_code_t raw_code_%s = {" % self.escaped_name)
print(" .kind = %s," % RawCode.code_kind_str[self.code_kind])
print(" .scope_flags = 0x%02x," % self.scope_flags)
print(" .n_pos_args = %u," % self.n_pos_args)
print(" .fun_data = fun_data_%s," % self.escaped_name)
print(" #if MICROPY_PERSISTENT_CODE_SAVE || MICROPY_DEBUG_PRINTERS")
print(" .fun_data_len = %u," % len(self.fun_data))
print(" #endif")
if len(self.children):
print(" .children = (void *)&children_%s," % self.escaped_name)
elif prelude_ptr:
print(" .children = (void *)%s," % prelude_ptr)
else:
print(" .children = NULL,")
print(" #if MICROPY_PERSISTENT_CODE_SAVE")
print(" .n_children = %u," % len(self.children))
if self.code_kind == MP_CODE_BYTECODE:
print(" #if MICROPY_PY_SYS_SETTRACE")
print(" .prelude = {")
print(" .n_state = %u," % self.prelude_signature[0])
print(" .n_exc_stack = %u," % self.prelude_signature[1])
print(" .scope_flags = %u," % self.prelude_signature[2])
print(" .n_pos_args = %u," % self.prelude_signature[3])
print(" .n_kwonly_args = %u," % self.prelude_signature[4])
print(" .n_def_pos_args = %u," % self.prelude_signature[5])
print(" .qstr_block_name_idx = %u," % self.names[0])
print(
" .line_info = fun_data_%s + %u,"
% (self.escaped_name, self.offset_line_info)
)
print(
" .line_info_top = fun_data_%s + %u,"
% (self.escaped_name, self.offset_closure_info)
)
print(
" .opcodes = fun_data_%s + %u," % (self.escaped_name, self.offset_opcodes)
)
print(" },")
print(" .line_of_definition = %u," % 0) # TODO
print(" #endif")
print(" #if MICROPY_EMIT_MACHINE_CODE")
print(" .prelude_offset = %u," % self.prelude_offset)
print(" #endif")
print(" #endif")
print(" #if MICROPY_EMIT_MACHINE_CODE")
print(" .type_sig = %u," % type_sig)
print(" #endif")
print("};")
global raw_code_count, raw_code_content
raw_code_count += 1
raw_code_content += 4 * 4
class RawCodeBytecode(RawCode):
def __init__(self, parent_name, qstr_table, obj_table, fun_data):
self.obj_table = obj_table
super(RawCodeBytecode, self).__init__(
parent_name, qstr_table, fun_data, 0, MP_CODE_BYTECODE
)
def disassemble(self):
bc = self.fun_data
print("simple_name:", self.simple_name.str)
print(" raw bytecode:", len(bc), hexlify_to_str(bc))
print(" prelude:", self.prelude_signature)
print(" args:", [self.qstr_table[i].str for i in self.names[1:]])
print(" line info:", hexlify_to_str(bc[self.offset_line_info : self.offset_opcodes]))
ip = self.offset_opcodes
while ip < len(bc):
fmt, sz, arg, _ = mp_opcode_decode(bc, ip)
if bc[ip] == Opcode.MP_BC_LOAD_CONST_OBJ:
arg = repr(self.obj_table[arg])
if fmt == MP_BC_FORMAT_QSTR:
arg = self.qstr_table[arg].str
elif fmt in (MP_BC_FORMAT_VAR_UINT, MP_BC_FORMAT_OFFSET):
pass
else:
arg = ""
print(
" %-11s %s %s" % (hexlify_to_str(bc[ip : ip + sz]), Opcode.mapping[bc[ip]], arg)
)
ip += sz
self.disassemble_children()
def freeze(self):
# generate bytecode data
bc = self.fun_data
print(
"// frozen bytecode for file %s, scope %s"
% (self.qstr_table[0].str, self.escaped_name)
)