-
Notifications
You must be signed in to change notification settings - Fork 6
/
warpy.py
executable file
·2822 lines (2525 loc) · 98.4 KB
/
warpy.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 python
INFO = False # informational logging
TRACE = False # trace instructions/stacks
DEBUG = False # verbose logging
#INFO = True # informational logging
#TRACE = True # trace instructions/stacks
#DEBUG = True # verbose logging
VALIDATE= True
import sys, os, math, time
IS_RPYTHON = sys.argv[0].endswith('rpython')
sys.path.append(os.path.abspath('./pypy2-v5.6.0-src'))
if IS_RPYTHON:
# JIT Stuff
from rpython.jit.codewriter.policy import JitPolicy
def jitpolicy(driver):
return JitPolicy()
from rpython.rlib.jit import JitDriver, elidable, unroll_safe, promote
from rpython.rtyper.lltypesystem import lltype
from rpython.rtyper.lltypesystem.lloperation import llop
from rpython.rlib.listsort import TimSort
from rpython.rlib.rstruct.ieee import float_unpack, float_pack
from rpython.rlib.rfloat import round_double
from rpython.rlib.rarithmetic import (
intmask, string_to_int)
from pypy.objspace.std.objspace import StdObjSpace
from pypy.objspace.std.floatobject import W_FloatObject
_tmpspace = StdObjSpace()
_tmpspace.call_function = lambda f, a: a
class IntSort(TimSort):
def lt(self, a, b):
assert isinstance(a, int)
assert isinstance(b, int)
return a < b
def do_sort(a):
IntSort(a).sort()
@elidable
def unpack_f32(i32):
return float_unpack(i32, 4)
@elidable
def unpack_f64(i64):
return float_unpack(i64, 8)
@elidable
def pack_f32(f32):
return float_pack(f32, 4)
@elidable
def pack_f64(f64):
return float_pack(f64, 8)
@elidable
def fround(val, digits):
return round_double(val, digits)
@elidable
def float_fromhex(s):
fo = W_FloatObject.descr_fromhex(_tmpspace, None, s)
return fo.floatval
else:
import traceback
import struct
def elidable(f): return f
def unroll_safe(f): return f
def promote(x): pass
def do_sort(a):
a.sort()
def unpack_f32(i32):
return struct.unpack('f', struct.pack('i', i32))[0]
def unpack_f64(i64):
return struct.unpack('d', struct.pack('q', i64))[0]
def pack_f32(f32):
return struct.unpack('i', struct.pack('f', f32))[0]
def pack_f64(f64):
return struct.unpack('q', struct.pack('d', f64))[0]
def intmask(i): return i
def string_to_int(s, base=10): return int(s, base)
def fround(val, digits):
return round(val, digits)
def float_fromhex(s):
return float.fromhex(s)
######################################
# Basic low-level types/classes
######################################
class WAException(Exception):
def __init__(self, message):
self.message = message
class ExitException(Exception):
def __init__(self, code):
self.code = code
class Type():
def __init__(self, index, form, params, results):
self.index = index
self.form = form
self.params = params
self.results = results
self.mask = 0x80
class Code():
pass
class Block(Code):
def __init__(self, kind, type, start):
self.kind = kind # block opcode (0x00 for init_expr)
self.type = type # value_type
self.locals = []
self.start = start
self.end = 0
self.else_addr = 0
self.br_addr = 0
def update(self, end, br_addr):
self.end = end
self.br_addr = br_addr
class Function(Code):
def __init__(self, type, index):
self.type = type # value_type
self.index = index
self.locals = []
self.start = 0
self.end = 0
self.else_addr = 0
self.br_addr = 0
def update(self, locals, start, end):
self.locals = locals
self.start = start
self.end = end
self.br_addr = end
class FunctionImport(Code):
def __init__(self, type, module, field):
self.type = type # value_type
self.module = module
self.field = field
fname = "%s.%s" % (module, field)
if not fname in ["spectest.print", "spectest.print_i32",
"env.printline", "env.readline", "env.read_file",
"env.get_time_ms", "env.exit"]:
raise Exception("function import %s not found" % (fname))
######################################
# WebAssembly spec data
######################################
MAGIC = 0x6d736100
VERSION = 0x01 # MVP
STACK_SIZE = 65536
CALLSTACK_SIZE = 8192
I32 = 0x7f # -0x01
I64 = 0x7e # -0x02
F32 = 0x7d # -0x03
F64 = 0x7c # -0x04
ANYFUNC = 0x70 # -0x10
FUNC = 0x60 # -0x20
BLOCK = 0x40 # -0x40
VALUE_TYPE = { I32 : 'i32',
I64 : 'i64',
F32 : 'f32',
F64 : 'f64',
ANYFUNC : 'anyfunc',
FUNC : 'func',
BLOCK : 'block_type' }
# Block types/signatures for blocks, loops, ifs
BLOCK_TYPE = { I32 : Type(-1, BLOCK, [], [I32]),
I64 : Type(-1, BLOCK, [], [I64]),
F32 : Type(-1, BLOCK, [], [F32]),
F64 : Type(-1, BLOCK, [], [F64]),
BLOCK : Type(-1, BLOCK, [], []) }
BLOCK_NAMES = { 0x00 : "fn", # TODO: something else?
0x02 : "block",
0x03 : "loop",
0x04 : "if",
0x05 : "else" }
EXTERNAL_KIND_NAMES = { 0x0 : "Function",
0x1 : "Table",
0x2 : "Memory",
0x3 : "Global" }
# ID : section name
SECTION_NAMES = { 0 : 'Custom',
1 : 'Type',
2 : 'Import',
3 : 'Function',
4 : 'Table',
5 : 'Memory',
6 : 'Global',
7 : 'Export',
8 : 'Start',
9 : 'Element',
10 : 'Code',
11 : 'Data' }
# opcode name immediate(s)
OPERATOR_INFO = {
# Control flow operators
0x00 : ['unreachable', ''],
0x01 : ['nop', ''],
0x02 : ['block', 'block_type'],
0x03 : ['loop', 'block_type'],
0x04 : ['if', 'block_type'],
0x05 : ['else', ''],
0x06 : ['RESERVED', ''],
0x07 : ['RESERVED', ''],
0x08 : ['RESERVED', ''],
0x09 : ['RESERVED', ''],
0x0a : ['RESERVED', ''],
0x0b : ['end', ''],
0x0c : ['br', 'varuint32'],
0x0d : ['br_if', 'varuint32'],
0x0e : ['br_table', 'br_table'],
0x0f : ['return', ''],
# Call operators
0x10 : ['call', 'varuint32'],
0x11 : ['call_indirect', 'varuint32+varuint1'],
0x12 : ['RESERVED', ''],
0x13 : ['RESERVED', ''],
0x14 : ['RESERVED', ''],
0x15 : ['RESERVED', ''],
0x16 : ['RESERVED', ''],
0x17 : ['RESERVED', ''],
0x18 : ['RESERVED', ''],
0x19 : ['RESERVED', ''],
# Parametric operators
0x1a : ['drop', ''],
0x1b : ['select', ''],
0x1c : ['RESERVED', ''],
0x1d : ['RESERVED', ''],
0x1e : ['RESERVED', ''],
0x1f : ['RESERVED', ''],
# Variable access
0x20 : ['get_local', 'varuint32'],
0x21 : ['set_local', 'varuint32'],
0x22 : ['tee_local', 'varuint32'],
0x23 : ['get_global', 'varuint32'],
0x24 : ['set_global', 'varuint32'],
0x25 : ['RESERVED', ''],
0x26 : ['RESERVED', ''],
0x27 : ['RESERVED', ''],
# Memory-related operators
0x28 : ['i32.load', 'memory_immediate'],
0x29 : ['i64.load', 'memory_immediate'],
0x2a : ['f32.load', 'memory_immediate'],
0x2b : ['f64.load', 'memory_immediate'],
0x2c : ['i32.load8_s', 'memory_immediate'],
0x2d : ['i32.load8_u', 'memory_immediate'],
0x2e : ['i32.load16_s', 'memory_immediate'],
0x2f : ['i32.load16_u', 'memory_immediate'],
0x30 : ['i64.load8_s', 'memory_immediate'],
0x31 : ['i64.load8_u', 'memory_immediate'],
0x32 : ['i64.load16_s', 'memory_immediate'],
0x33 : ['i64.load16_u', 'memory_immediate'],
0x34 : ['i64.load32_s', 'memory_immediate'],
0x35 : ['i64.load32_u', 'memory_immediate'],
0x36 : ['i32.store', 'memory_immediate'],
0x37 : ['i64.store', 'memory_immediate'],
0x38 : ['f32.store', 'memory_immediate'],
0x39 : ['f64.store', 'memory_immediate'],
0x3a : ['i32.store8', 'memory_immediate'],
0x3b : ['i32.store16', 'memory_immediate'],
0x3c : ['i64.store8', 'memory_immediate'],
0x3d : ['i64.store16', 'memory_immediate'],
0x3e : ['i64.store32', 'memory_immediate'],
0x3f : ['current_memory', 'varuint1'],
0x40 : ['grow_memory', 'varuint1'],
# Constants
0x41 : ['i32.const', 'varint32'],
0x42 : ['i64.const', 'varint64'],
0x43 : ['f32.const', 'uint32'],
0x44 : ['f64.const', 'uint64'],
# Comparison operators
0x45 : ['i32.eqz', ''],
0x46 : ['i32.eq', ''],
0x47 : ['i32.ne', ''],
0x48 : ['i32.lt_s', ''],
0x49 : ['i32.lt_u', ''],
0x4a : ['i32.gt_s', ''],
0x4b : ['i32.gt_u', ''],
0x4c : ['i32.le_s', ''],
0x4d : ['i32.le_u', ''],
0x4e : ['i32.ge_s', ''],
0x4f : ['i32.ge_u', ''],
0x50 : ['i64.eqz', ''],
0x51 : ['i64.eq', ''],
0x52 : ['i64.ne', ''],
0x53 : ['i64.lt_s', ''],
0x54 : ['i64.lt_u', ''],
0x55 : ['i64.gt_s', ''],
0x56 : ['i64.gt_u', ''],
0x57 : ['i64.le_s', ''],
0x58 : ['i64.le_u', ''],
0x59 : ['i64.ge_s', ''],
0x5a : ['i64.ge_u', ''],
0x5b : ['f32.eq', ''],
0x5c : ['f32.ne', ''],
0x5d : ['f32.lt', ''],
0x5e : ['f32.gt', ''],
0x5f : ['f32.le', ''],
0x60 : ['f32.ge', ''],
0x61 : ['f64.eq', ''],
0x62 : ['f64.ne', ''],
0x63 : ['f64.lt', ''],
0x64 : ['f64.gt', ''],
0x65 : ['f64.le', ''],
0x66 : ['f64.ge', ''],
# Numeric operators
0x67 : ['i32.clz', ''],
0x68 : ['i32.ctz', ''],
0x69 : ['i32.popcnt', ''],
0x6a : ['i32.add', ''],
0x6b : ['i32.sub', ''],
0x6c : ['i32.mul', ''],
0x6d : ['i32.div_s', ''],
0x6e : ['i32.div_u', ''],
0x6f : ['i32.rem_s', ''],
0x70 : ['i32.rem_u', ''],
0x71 : ['i32.and', ''],
0x72 : ['i32.or', ''],
0x73 : ['i32.xor', ''],
0x74 : ['i32.shl', ''],
0x75 : ['i32.shr_s', ''],
0x76 : ['i32.shr_u', ''],
0x77 : ['i32.rotl', ''],
0x78 : ['i32.rotr', ''],
0x79 : ['i64.clz', ''],
0x7a : ['i64.ctz', ''],
0x7b : ['i64.popcnt', ''],
0x7c : ['i64.add', ''],
0x7d : ['i64.sub', ''],
0x7e : ['i64.mul', ''],
0x7f : ['i64.div_s', ''],
0x80 : ['i64.div_u', ''],
0x81 : ['i64.rem_s', ''],
0x82 : ['i64.rem_u', ''],
0x83 : ['i64.and', ''],
0x84 : ['i64.or', ''],
0x85 : ['i64.xor', ''],
0x86 : ['i64.shl', ''],
0x87 : ['i64.shr_s', ''],
0x88 : ['i64.shr_u', ''],
0x89 : ['i64.rotl', ''],
0x8a : ['i64.rotr', ''],
0x8b : ['f32.abs', ''],
0x8c : ['f32.neg', ''],
0x8d : ['f32.ceil', ''],
0x8e : ['f32.floor', ''],
0x8f : ['f32.trunc', ''],
0x90 : ['f32.nearest', ''],
0x91 : ['f32.sqrt', ''],
0x92 : ['f32.add', ''],
0x93 : ['f32.sub', ''],
0x94 : ['f32.mul', ''],
0x95 : ['f32.div', ''],
0x96 : ['f32.min', ''],
0x97 : ['f32.max', ''],
0x98 : ['f32.copysign', ''],
0x99 : ['f64.abs', ''],
0x9a : ['f64.neg', ''],
0x9b : ['f64.ceil', ''],
0x9c : ['f64.floor', ''],
0x9d : ['f64.trunc', ''],
0x9e : ['f64.nearest', ''],
0x9f : ['f64.sqrt', ''],
0xa0 : ['f64.add', ''],
0xa1 : ['f64.sub', ''],
0xa2 : ['f64.mul', ''],
0xa3 : ['f64.div', ''],
0xa4 : ['f64.min', ''],
0xa5 : ['f64.max', ''],
0xa6 : ['f64.copysign', ''],
# Conversions
0xa7 : ['i32.wrap_i64', ''],
0xa8 : ['i32.trunc_f32_s', ''],
0xa9 : ['i32.trunc_f32_u', ''],
0xaa : ['i32.trunc_f64_s', ''],
0xab : ['i32.trunc_f64_u', ''],
0xac : ['i64.extend_i32_s', ''],
0xad : ['i64.extend_i32_u', ''],
0xae : ['i64.trunc_f32_s', ''],
0xaf : ['i64.trunc_f32_u', ''],
0xb0 : ['i64.trunc_f64_s', ''],
0xb1 : ['i64.trunc_f64_u', ''],
0xb2 : ['f32.convert_i32_s', ''],
0xb3 : ['f32.convert_i32_u', ''],
0xb4 : ['f32.convert_i64_s', ''],
0xb5 : ['f32.convert_i64_u', ''],
0xb6 : ['f32.demote_f64', ''],
0xb7 : ['f64.convert_i32_s', ''],
0xb8 : ['f64.convert_i32_u', ''],
0xb9 : ['f64.convert_i64_s', ''],
0xba : ['f64.convert_i64_u', ''],
0xbb : ['f64.promote_f32', ''],
# Reinterpretations
0xbc : ['i32.reinterpret_f32', ''],
0xbd : ['i64.reinterpret_f64', ''],
0xbe : ['f32.reinterpret_i32', ''],
0xbf : ['f64.reinterpret_i64', ''],
}
LOAD_SIZE = { 0x28 : 4,
0x29 : 8,
0x2a : 4,
0x2b : 8,
0x2c : 1,
0x2d : 1,
0x2e : 2,
0x2f : 2,
0x30 : 1,
0x31 : 1,
0x32 : 2,
0x33 : 2,
0x34 : 4,
0x35 : 4,
0x36 : 4,
0x37 : 8,
0x38 : 4,
0x39 : 8,
0x3a : 1,
0x3b : 2,
0x3c : 1,
0x3d : 2,
0x3e : 4,
0x40 : 1,
0x41 : 2,
0x42 : 1,
0x43 : 2,
0x44 : 4 }
######################################
# General Functions
######################################
def info(str, end='\n'):
if INFO:
os.write(2, str + end)
#if end == '': sys.stderr.flush()
def debug(str, end='\n'):
if DEBUG:
os.write(2, str + end)
#if end == '': sys.stderr.flush()
# math functions
def unpack_nan32(i32):
if IS_RPYTHON:
return float_unpack(i32, 4)
else:
return struct.unpack('f', struct.pack('I', i32))[0]
def unpack_nan64(i64):
if IS_RPYTHON:
return float_unpack(i64, 8)
else:
return struct.unpack('d', struct.pack('Q', i64))[0]
@elidable
def parse_nan(type, arg):
if type == F32: v = unpack_nan32(0x7fc00000)
else: v = unpack_nan64(0x7ff8000000000000)
return v
@elidable
def parse_number(type, arg):
arg = "".join([c for c in arg if c != '_'])
if type == I32:
if arg[0:2] == '0x': v = (I32, string_to_int(arg,16), 0.0)
elif arg[0:3] == '-0x': v = (I32, string_to_int(arg,16), 0.0)
else: v = (I32, string_to_int(arg,10), 0.0)
elif type == I64:
if arg[0:2] == '0x': v = (I64, string_to_int(arg,16), 0.0)
elif arg[0:3] == '-0x': v = (I64, string_to_int(arg,16), 0.0)
else: v = (I64, string_to_int(arg,10), 0.0)
elif type == F32:
if arg.find('nan')>=0: v = (F32, 0, parse_nan(type, arg))
elif arg.find('inf')>=0: v = (F32, 0, float_fromhex(arg))
elif arg[0:2] == '0x': v = (F32, 0, float_fromhex(arg))
elif arg[0:3] == '-0x': v = (F32, 0, float_fromhex(arg))
else: v = (F32, 0, float(arg))
elif type == F64:
if arg.find('nan')>=0: v = (F64, 0, parse_nan(type, arg))
elif arg.find('inf')>=0: v = (F64, 0, float_fromhex(arg))
elif arg[0:2] == '0x': v = (F64, 0, float_fromhex(arg))
elif arg[0:3] == '-0x': v = (F64, 0, float_fromhex(arg))
else: v = (F64, 0, float(arg))
else:
raise Exception("invalid number %s" % arg)
return v
# Integer division that rounds towards 0 (like C)
@elidable
def idiv_s(a,b):
return a//b if a*b>0 else (a+(-a%b))//b
@elidable
def irem_s(a,b):
return a%b if a*b>0 else -(-a%b)
#
@elidable
def rotl32(a,cnt):
return (((a << (cnt % 0x20)) & 0xffffffff)
| (a >> (0x20 - (cnt % 0x20))))
@elidable
def rotr32(a,cnt):
return ((a >> (cnt % 0x20))
| ((a << (0x20 - (cnt % 0x20))) & 0xffffffff))
@elidable
def rotl64(a,cnt):
return (((a << (cnt % 0x40)) & 0xffffffffffffffff)
| (a >> (0x40 - (cnt % 0x40))))
@elidable
def rotr64(a,cnt):
return ((a >> (cnt % 0x40))
| ((a << (0x40 - (cnt % 0x40))) & 0xffffffffffffffff))
@elidable
def bytes2uint8(b):
return b[0]
@elidable
def bytes2int8(b):
val = b[0]
if val & 0x80:
return val - 0x100
else:
return val
#
@elidable
def bytes2uint16(b):
return (b[1]<<8) + b[0]
@elidable
def bytes2int16(b):
val = (b[1]<<8) + b[0]
if val & 0x8000:
return val - 0x10000
else:
return val
#
@elidable
def bytes2uint32(b):
return (b[3]<<24) + (b[2]<<16) + (b[1]<<8) + b[0]
@elidable
def uint322bytes(v):
return [0xff & (v),
0xff & (v>>8),
0xff & (v>>16),
0xff & (v>>24)]
@elidable
def bytes2int32(b):
val = (b[3]<<24) + (b[2]<<16) + (b[1]<<8) + b[0]
if val & 0x80000000:
return val - 0x100000000
else:
return val
@elidable
def int2uint32(i):
return i & 0xffffffff
@elidable
def int2int32(i):
val = i & 0xffffffff
if val & 0x80000000:
return val - 0x100000000
else:
return val
#
@elidable
def bytes2uint64(b):
return ((b[7]<<56) + (b[6]<<48) + (b[5]<<40) + (b[4]<<32) +
(b[3]<<24) + (b[2]<<16) + (b[1]<<8) + b[0])
@elidable
def uint642bytes(v):
return [0xff & (v),
0xff & (v>>8),
0xff & (v>>16),
0xff & (v>>24),
0xff & (v>>32),
0xff & (v>>40),
0xff & (v>>48),
0xff & (v>>56)]
if IS_RPYTHON:
@elidable
def bytes2int64(b):
return bytes2uint64(b)
else:
def bytes2int64(b):
val = ((b[7]<<56) + (b[6]<<48) + (b[5]<<40) + (b[4]<<32) +
(b[3]<<24) + (b[2]<<16) + (b[1]<<8) + b[0])
if val & 0x8000000000000000:
return val - 0x10000000000000000
else:
return val
#
if IS_RPYTHON:
@elidable
def int2uint64(i):
return intmask(i)
else:
def int2uint64(i):
return i & 0xffffffffffffffff
if IS_RPYTHON:
@elidable
def int2int64(i):
return i
else:
def int2int64(i):
val = i & 0xffffffffffffffff
if val & 0x8000000000000000:
return val - 0x10000000000000000
else:
return val
# https://en.wikipedia.org/wiki/LEB128
@elidable
def read_LEB(bytes, pos, maxbits=32, signed=False):
result = 0
shift = 0
bcnt = 0
startpos = pos
while True:
byte = bytes[pos]
pos += 1
result |= ((byte & 0x7f)<<shift)
shift +=7
if (byte & 0x80) == 0:
break
# Sanity check length against maxbits
bcnt += 1
if bcnt > math.ceil(maxbits/7.0):
raise Exception("Unsigned LEB at byte %s overflow" %
startpos)
if signed and (shift < maxbits) and (byte & 0x40):
# Sign extend
result |= - (1 << shift)
return (pos, result)
@elidable
def read_I32(bytes, pos):
assert pos >= 0
return bytes2uint32(bytes[pos:pos+4])
@elidable
def read_I64(bytes, pos):
assert pos >= 0
return bytes2uint64(bytes[pos:pos+8])
@elidable
def read_F32(bytes, pos):
assert pos >= 0
bits = bytes2int32(bytes[pos:pos+4])
num = unpack_f32(bits)
# fround hangs if called with nan
if math.isnan(num): return num
return fround(num, 5)
@elidable
def read_F64(bytes, pos):
assert pos >= 0
bits = bytes2int64(bytes[pos:pos+8])
return unpack_f64(bits)
def write_I32(bytes, pos, ival):
bytes[pos:pos+4] = uint322bytes(ival)
def write_I64(bytes, pos, ival):
bytes[pos:pos+8] = uint642bytes(ival)
def write_F32(bytes, pos, fval):
ival = intmask(pack_f32(fval))
bytes[pos:pos+4] = uint322bytes(ival)
def write_F64(bytes, pos, fval):
ival = intmask(pack_f64(fval))
bytes[pos:pos+8] = uint642bytes(ival)
def value_repr(val):
vt, ival, fval = val
vtn = VALUE_TYPE[vt]
if vtn in ('i32', 'i64'):
return "%s:%s" % (hex(ival), vtn)
elif vtn in ('f32', 'f64'):
if IS_RPYTHON:
# TODO: fix this to be like python
return "%f:%s" % (fval, vtn)
else:
str = "%.7g" % fval
if str.find('.') < 0:
return "%f:%s" % (fval, vtn)
else:
return "%s:%s" % (str, vtn)
else:
raise Exception("unknown value type %s" % vtn)
def type_repr(t):
return "<index: %s, form: %s, params: %s, results: %s, mask: %s>" % (
t.index, VALUE_TYPE[t.form],
[VALUE_TYPE[p] for p in t.params],
[VALUE_TYPE[r] for r in t.results], hex(t.mask))
def export_repr(e):
return "<kind: %s, field: '%s', index: 0x%x>" % (
EXTERNAL_KIND_NAMES[e.kind], e.field, e.index)
def func_repr(f):
if isinstance(f, FunctionImport):
return "<type: 0x%x, import: '%s.%s'>" % (
f.type.index, f.module, f.field)
else:
return "<type: 0x%x, locals: %s, start: 0x%x, end: 0x%x>" % (
f.type.index, [VALUE_TYPE[p] for p in f.locals],
f.start, f.end)
def block_repr(block):
if isinstance(block, Block):
return "%s<0/0->%d>" % (
BLOCK_NAMES[block.kind],
len(block.type.results))
elif isinstance(block, Function):
return "fn%d<%d/%d->%d>" % (
block.index, len(block.type.params),
len(block.locals), len(block.type.results))
def stack_repr(sp, fp, stack):
res = []
for i in range(sp+1):
if i == fp:
res.append("*")
res.append(value_repr(stack[i]))
return "[" + " ".join(res) + "]"
def callstack_repr(csp, bs):
return "[" + " ".join(["%s(sp:%d/fp:%d/ra:0x%x)" % (
block_repr(bs[i][0]),bs[i][1],bs[i][2],bs[i][3])
for i in range(csp+1)]) + "]"
def dump_stacks(sp, stack, fp, csp, callstack):
debug(" * stack: %s" % (
stack_repr(sp, fp, stack)))
debug(" * callstack: %s" % (
callstack_repr(csp, callstack)))
def byte_code_repr(bytes):
res = []
for val in bytes:
if val < 16:
res.append("%x" % val)
else:
res.append("%x" % val)
return "[" + ",".join(res) + "]"
def skip_immediates(code, pos):
opcode = code[pos]
pos += 1
vals = []
imtype = OPERATOR_INFO[opcode][1]
if 'varuint1' == imtype:
pos, v = read_LEB(code, pos, 1)
vals.append(v)
elif 'varint32' == imtype:
pos, v = read_LEB(code, pos, 32)
vals.append(v)
elif 'varuint32' == imtype:
pos, v = read_LEB(code, pos, 32)
vals.append(v)
elif 'varuint32+varuint1' == imtype:
pos, v = read_LEB(code, pos, 32)
vals.append(v)
pos, v = read_LEB(code, pos, 1)
vals.append(v)
elif 'varint64' == imtype:
pos, v = read_LEB(code, pos, 64)
vals.append(v)
elif 'varuint64' == imtype:
pos, v = read_LEB(code, pos, 64)
vals.append(v)
elif 'uint32' == imtype:
vals.append(read_F32(code, pos))
pos += 4
elif 'uint64' == imtype:
vals.append(read_F64(code, pos))
pos += 8
elif 'block_type' == imtype:
pos, v = read_LEB(code, pos, 7) # block type signature
vals.append(v)
elif 'memory_immediate' == imtype:
pos, v = read_LEB(code, pos, 32) # flags
vals.append(v)
pos, v = read_LEB(code, pos, 32) # offset
vals.append(v)
elif 'br_table' == imtype:
pos, count = read_LEB(code, pos, 32) # target count
vals.append(count)
for i in range(count):
pos, v = read_LEB(code, pos, 32) # target
vals.append(v)
pos, v = read_LEB(code, pos, 32) # default target
vals.append(v)
elif '' == imtype:
pass # no immediates
else:
raise Exception("unknown immediate type %s" % imtype)
return pos, vals
def find_blocks(code, start, end, block_map):
pos = start
# stack of blocks with current at top: (opcode, pos) tuples
opstack = []
#
# Build the map of blocks
#
opcode = 0
while pos <= end:
opcode = code[pos]
#debug("0x%x: %s, opstack: %s" % (
# pos, OPERATOR_INFO[opcode][0],
# ["%d,%s,0x%x" % (o,s.index,p) for o,s,p in opstack]))
if 0x02 <= opcode <= 0x04: # block, loop, if
block = Block(opcode, BLOCK_TYPE[code[pos+1]], pos)
opstack.append(block)
block_map[pos] = block
elif 0x05 == opcode: # mark else positions
assert opstack[-1].kind == 0x04, "else not matched with if"
opstack[-1].else_addr = pos+1
elif 0x0b == opcode: # end
if pos == end: break
block = opstack.pop()
if block.kind == 0x03: # loop: label after start
block.update(pos, block.start+2)
else: # block/if: label at end
block.update(pos, pos)
pos, _ = skip_immediates(code, pos)
assert opcode == 0xb, "function block did not end with 0xb"
assert len(opstack) == 0, "function ended in middle of block"
#debug("block_map: %s" % block_map)
return block_map
@unroll_safe
def pop_block(stack, callstack, sp, fp, csp):
block, orig_sp, orig_fp, ra = callstack[csp]
csp -= 1
t = block.type
# Validate return value if there is one
if VALIDATE:
if len(t.results) > 1:
raise Exception("multiple return values unimplemented")
if len(t.results) > sp+1:
raise Exception("stack underflow")
if len(t.results) == 1:
# Restore main value stack, saving top return value
save = stack[sp]
sp -= 1
if save[0] != t.results[0]:
raise WAException("call signature mismatch: %s != %s (%s)" % (
VALUE_TYPE[t.results[0]], VALUE_TYPE[save[0]],
value_repr(save)))
# Restore value stack to original size prior to call/block
if orig_sp < sp:
sp = orig_sp
# Put back return value if we have one
sp += 1
stack[sp] = save
else:
# Restore value stack to original size prior to call/block
if orig_sp < sp:
sp = orig_sp
return block, ra, sp, orig_fp, csp
@unroll_safe
def do_call(stack, callstack, sp, fp, csp, func, pc, indirect=False):
# Push block, stack size and return address onto callstack
t = func.type
csp += 1
callstack[csp] = (func, sp-len(t.params), fp, pc)
# Update the pos/instruction counter to the function
pc = func.start
if TRACE:
info(" Calling function 0x%x, start: 0x%x, end: 0x%x, %d locals, %d params, %d results" % (
func.index, func.start, func.end,
len(func.locals), len(t.params), len(t.results)))
# set frame pointer to include parameters
fp = sp - len(t.params) + 1
# push locals (dropping extras)
for lidx in range(len(func.locals)):
ltype = func.locals[lidx]
sp += 1
stack[sp] = (ltype, 0, 0.0)
return pc, sp, fp, csp
@unroll_safe
def do_call_import(stack, sp, memory, import_function, func):
t = func.type
args = []
for idx in range(len(t.params)-1, -1, -1):
arg = stack[sp]
sp -= 1
args.append(arg)
# if VALIDATE:
# # make sure args match type signature
# ptype = t.params[idx]
# if ptype != arg[0]:
# raise WAException("call signature mismatch: %s != %s" % (
# VALUE_TYPE[ptype], VALUE_TYPE[arg[0]]))
# Workaround rpython failure to identify type
results = [(0, 0, 0.0)]
results.pop()
args.reverse()
results.extend(import_function(func.module, func.field, memory, args))