forked from ptitSeb/box86
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rebuild_printer.py
executable file
·1985 lines (1770 loc) · 64.3 KB
/
rebuild_printer.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
import os
import re
import sys
from math import ceil
"""
Generates src/dynarec/arm_printer.c
===
See src/dynarec/arm_instructions.txt (the input file) for the syntax documentation.
"""
# Helper class to avoid displaying '\x1b[' on errors
class string(str):
def __repr__(self):
return str(self)
def nextAvailable(num):
return 8 if num <= 8 else (16 if num <= 16 else (32 if num <= 32 else 64))
def int2hex(i, finsz=-1):
if (finsz == -1) and (i == 0): return "0x0"
elif i == 0: return "0x" + ("0" * finsz)
ret = ""
while i != 0:
ret += str(i % 16) if i % 16 < 10 else chr(ord('A') + (i % 16) - 10)
i = i // 16
rl = len(ret)
if rl < finsz:
ret = ret + ("0" * (finsz - rl))
return "0x" + ''.join(reversed(ret))
def arr2hex(a, forceBin=False):
if forceBin:
return "0b" + ''.join(map(str, a))
else:
al = len(a)
return int2hex(sum(v * 2**(al - i - 1) for i, v in enumerate(a)), ceil(al / 4))
def sz2str(sz, forceBin=False):
return int2hex(2 ** sz - 1) if not forceBin else ("0b" + "1" * sz)
def main(root, ver, __debug_forceAllDebugging=False):
# Initialize variables
output = ""
# Debugging variable
invalidationCount = 0
tabCount = 1
def append(strg):
assert("\t" not in strg)
nonlocal output, tabCount
strg = strg.split("\n")
for s in strg[:-1]:
if s.endswith("{"):
tabCount = tabCount + 1
if s.startswith("}") and output.endswith("\t"):
tabCount = tabCount - 1
output = output[:-1]
output = output + s + "\n" + "\t" * tabCount
if strg[-1].startswith("}") and output.endswith("\t"):
tabCount = tabCount - 1
output = output[:-1]
output = output + strg[-1]
insts = None
# Read the instruction and exit if nothing changed since last run
with open(os.path.join(root, "src", "dynarec", "arm_instructions.txt"), 'r') as file:
insts = file.read()
# Get all actual instructions
# Ignore white lines and lines beginning with either !, ; or #
insts = list(filter(lambda l: not re.match("^\s*$", l) and not re.match("^([!;#])", l), insts.split('\n')))
try:
# Do not open with `with` to be able to open it in writing mode
last = open(os.path.join(root, "src", "dynarec", "last_run.txt"), 'r')
if '\n'.join(insts) == last.read():
last.close()
with open(os.path.join(root, "src", "dynarec", "last_run.txt"), 'w') as f:
f.write('\n'.join(insts))
return 0
last.close()
except OSError:
# No last run file
pass
for lnno, line in enumerate(insts):
ln = line.strip()
def fail(errType, reas, allow_use_curSplt=True):
"""
Throw an error of type `errType`, with `reas` as the reason.
Appends the line number and the erroring line.
`allow_use_curSplt` is a boolean, set to False if you want to ignore `curSplt` (no colored line)
"""
try:
nonlocal curSplt
if allow_use_curSplt and (curSplt >= 0):
# Get a colorized line
# (Blah blah [CSI-color change][Here is the error][CSI-color change] blah)
line = ""
alreadyChanged = 0
csp = 0
while csp < curSplt:
if spltln[csp] == '\x00':
alreadyChanged = 1
curSplt = curSplt + 1
else:
if alreadyChanged == 0:
line = line + spltln[csp] + " "
elif alreadyChanged == 1:
line = line + spltln[csp] + "<"
alreadyChanged = 2
else:
line = line + spltln[csp] + ">"
alreadyChanged = 1
csp = csp + 1
if spltln[csp] == '\x00':
alreadyChanged = 1
curSplt = curSplt + 1
csp = csp + 1
line = line + "\033[31m[\033[91m" + spltln[csp] + "\033[31m]\033[m"
if alreadyChanged == 0:
line = line + " "
elif alreadyChanged == 1:
line = line + "<"
alreadyChanged = 2
else:
line = line + ">"
alreadyChanged = 1
csp = csp + 1
while csp < len(spltln):
if spltln[csp] == '\x00':
alreadyChanged = 1
curSplt = curSplt + 1
else:
if alreadyChanged == 0:
line = line + spltln[csp] + " "
elif alreadyChanged == 1:
line = line + spltln[csp] + "<"
alreadyChanged = 2
else:
line = line + spltln[csp] + ">"
alreadyChanged = 1
csp = csp + 1
raise errType(string(str(reas) + " (" + str(lnno + 1) + ": " + line[:-1] + ")"))
else:
# No colored line
raise errType(str(reas) + " (" + str(lnno + 1) + ": " + ln + ")")
except errType as e:
# Raise a BaseException as an error wrapper
# (otherwise it will be caught and the line will be re-appended)
raise BaseException("[Error wrapper]") from e
spltln = ln.split(' ')
curSplt = -1
mask = [0] * 32
correctBits = [0] * 32
curBit = 32
ocurBit = -1
req = ''
imms = [] # Immediates
parm = [] # Custom variable length parameters
variables = {}
def generate_bin_test(positions=[], specifics=[]):
"""
Generates the if statement at the beginning.
You may use positions and specifics to implement a "multiple choice if":
- positions is an array that contains a bit position (MSB = 0)
- specifics is an array of arrays the same length as positions that contains a tuple (mask, correctBit)
that is at position positions[current_pos]
"""
if specifics == []:
append("if ((opcode & " + arr2hex(mask) + ") == " + arr2hex(correctBits) + ") {\n")
else:
l = len(positions)
if any(map(lambda v: (v < 0) or (v > 31), positions)):
fail(
AssertionError,
"generate_bin_tests requires a valid positions ({}) and specifics ({})!".format(
len(positions), len(specifics)
)
)
if any(map(lambda s: len(s) != l, specifics)):
fail(
AssertionError,
"generate_bin_tests requires the same length for positions ({}) and each element "
"of the specifics array ({})!".format(
len(positions), [len(s) for s in specifics]
)
)
inner = []
for specific in specifics:
for i, (m, c) in zip(positions, specific):
mask[i] = m
correctBits[i] = c
inner.append("((opcode & " + arr2hex(mask) + ") == " + arr2hex(correctBits) + ")")
append("if (" + " || ".join(inner) + ") {\n")
def parse_var_requirements():
"""
Parse the `/` restrictions on the bit fields
"""
nonlocal req
while req != '':
key = req[0]
req = req[1:]
if key == '=':
if len(req) < ocurBit - curBit:
fail(KeyError, "Not enough data in constraint value (type '=' for val " + val + ")")
for i in range(ocurBit - curBit):
if req[0] == 'x':
req = req[1:]
continue
elif (req[0] != '0') and (req[0] != '1'):
fail(KeyError, "Invalid constraint '" + key + "..." + req[0] + "'")
mask[32 - ocurBit + i] = 1
correctBits[32 - ocurBit + i] = ord(req[0]) - ord('0')
req = req[1:]
elif (ord(key) >= ord('0')) and (ord(key) <= ord('9')):
if req == '':
fail(KeyError, "Not enough data in constraint value (type '" + key + "' for val " + \
val + ")")
elif (req[0] != '0') and (req[0] != '1'):
fail(KeyError, "Invalid constraint '" + key + req[0] + "'")
mask[31 - curBit + ord('0') - ord(key)] = 1
correctBits[31 - curBit + ord('0') - ord(key)] = ord(req[0]) - ord('0')
req = req[1:]
elif (ord(key) >= ord('A')) and (ord(key) <= ord('F')):
if req == '':
fail(KeyError, "Not enough data in constraint value (type '" + key + "' for val " + \
val + ")")
elif (req[0] != '0') and (req[0] != '1'):
fail(KeyError, "Invalid constraint '" + key + req[0] + "'")
mask[31 - curBit + ord('A') + 10 - ord(key)] = 1
correctBits[31 - curBit + ord('A') + 10 - ord(key)] = ord(req[0]) - ord('0')
req = req[1:]
def add_custom_variables():
nonlocal curSplt
# Check for any custom variables
if len(parm) == 1:
# One parameter, name it param
append("int param = (opcode >> " + str(parm[0][0]) + ") & " + sz2str(parm[0][1]) + ";\n")
else:
# Multiple parameters, name them "param" paramNr "_" paramBitsSize
for i, p in enumerate(parm):
append(
"int param" + str(i + 1) + "_" + str(p[1]) + " = (opcode >> " + \
str(p[0]) + ") & " + sz2str(p[1]) + ";\n"
)
if spltln[curSplt] == '@':
# Additional custom modifications
append("\n")
curSplt = curSplt + 1
while spltln[curSplt] != '@':
if '=' in spltln[curSplt]:
# Add an `if` statement
eq = spltln[curSplt]
# Read initialization statement...
curSplt = curSplt + 1
oldSplt = curSplt
while spltln[curSplt][-1] != '@':
curSplt = curSplt + 1
if len(spltln) == curSplt:
fail(KeyError, "End of '=' switch not found!")
# Always initialize if necessary
if oldSplt != curSplt:
append(' '.join(spltln[oldSplt:curSplt]) + ";\n")
ifs = [""]
if spltln[curSplt] == '@@':
# Custom ifs
# Also, requires only a single '='
if eq != "=":
fail(ValueError, "Too many '=' switches (@@ modifier)")
# Extract the statements
statements = []
while spltln[curSplt] == '@@':
curSplt = curSplt + 1
statement = spltln[curSplt]
while spltln[curSplt][-1] != '@':
curSplt = curSplt + 1
statement = statement + " " + spltln[curSplt]
if len(spltln) == curSplt:
fail(KeyError, "End of '=' switch (@@ modifier) not found!")
statements.append(statement[:-1])
curSplt = curSplt + 1
# Unified eq length
eq = statements + [0]
# Make the ifs array
for stmt in statements:
ifs[-1] = ifs[-1] + "if (" + stmt + ") {\n"
ifs.append("} else ")
ifs[-1] = ifs[-1] + "{\n"
else:
# Standard if
eq = eq.split('=')
for e in eq[1:]:
ifs[-1] = ifs[-1] + "if (" + eq[0] + " == " + e + ") {\n"
ifs.append("} else ")
ifs[-1] = ifs[-1] + "{\n"
if spltln[curSplt] == '!@':
# Custom statements
curSplt = curSplt + 1
# Extract the common value
commonPart = spltln[curSplt]
while spltln[curSplt][-1] != '@':
curSplt = curSplt + 1
commonPart = commonPart + " " + spltln[curSplt]
if len(spltln) == curSplt:
fail(KeyError, "End of '=' switch (!@ modifier) not found!")
commonPart = commonPart[:-1].replace("\\n", "\n")
curSplt = curSplt + 1
# Extract the parts
commonPart = commonPart.split('%')
if len(commonPart) < 2:
fail(ValueError, "No replacement place!")
for if_ in ifs[:-1]:
append(if_)
# For each '%', append the preceding part and the variable part
for common in commonPart[:-1]:
insert = spltln[curSplt]
while spltln[curSplt][-1] != '@':
curSplt = curSplt + 1
insert = insert + " " + spltln[curSplt]
if len(spltln) == curSplt:
fail(
KeyError,
"End of '=' switch (!@ modifier, repl1 i=" + str(i) + \
" part) not found!"
)
insert = insert[:-1].replace("\\n", "\n")
append(common + insert)
curSplt = curSplt + 1
append(commonPart[-1] + ";\n")
# Finish with the `else` part
append(ifs[-1])
# For each '%', append the preceding part and the variable part
for common in commonPart[:-1]:
insert = spltln[curSplt]
while spltln[curSplt][-1] != '@':
curSplt = curSplt + 1
insert = insert + " " + spltln[curSplt]
if len(spltln) == curSplt:
fail(KeyError, "End of '=' switch (!@ modifier, repl2 part) not found!")
insert = insert[:-1].replace("\\n", "\n")
append(common + insert)
curSplt = curSplt + 1
append(commonPart[-1] + ";\n}\n")
else:
# Standard statements
dynvars = [dynvar.split(',') for dynvar in spltln[curSplt].split(';')]
dynvars[-1][-1] = dynvars[-1][-1][:-1]
curSplt = curSplt + 1
if any(len(dynvar) != len(eq) + 1 for dynvar in dynvars):
fail(ValueError, "Not enough/too many possibilities in switch")
# Reorganize dynvars so it matches [[variables], [set-if-A-true], ..., [set-else]]
dynvars = list(map(lambda i: [dv[i] for dv in dynvars], range(len(dynvars[0]))))
for if_, vals in zip(ifs[:-1], dynvars[1:]):
append(if_)
for var, val in zip(dynvars[0], vals):
append(var + " = " + val + ";\n")
# Else
append(ifs[-1])
for var, val in zip(dynvars[0], dynvars[-1]):
append(var + " = " + val + ";\n")
append("}\n")
elif spltln[curSplt] == "set":
# Set a (new?) variable
curSplt = curSplt + 1
oldSplt = curSplt
while spltln[curSplt][-1] != '@':
curSplt = curSplt + 1
if len(spltln) == curSplt:
fail(KeyError, "End of '=' switch not found!")
# If the statement is empty just add a blank line
if (oldSplt == curSplt) and (spltln[curSplt] == "@"):
append("\n")
else:
append(' '.join(spltln[oldSplt:curSplt + 1])[:-1] + ";\n")
curSplt = curSplt + 1
else:
fail(KeyError, "Unknown custom statement type '" + spltln[curSplt] + "'")
curSplt = curSplt + 1
try:
if spltln[0] == "ARM_":
# ARM instruction
variables["cond"] = -1
variables["registers"] = {
"d": [-1, -1, -1, -1, -1], # Register: #, ##, Rd, RdLo, RdHi
"t": [-1, -1, -1], # Register: #, ##, Rt
"n": [-1, -1, -1], # Register: #, ##, Rn
"m": [-1, -1, -1], # Register: #, ##, Rm
"a": [-1, -1, -1] # Register: #, ##, Ra
}
variables["reglist16"] = -1 # Register list (16-bits)
variables["s"] = -1 # Set flags
variables["u"] = -1 # Unsigned
variables["r"] = -1 # Rotate
variables["sb"] = [-1, -1, -1] # lsb, msb
variables["w"] = -1 # wback
for i, val in enumerate(spltln[1:]):
if '/' in val:
ocurBit = curBit
req = val.split('/')
val, req = req[0], '/'.join(req[1:])
if val == '0':
curBit = curBit - 1
mask[31 - curBit] = 1
elif val == '1':
curBit = curBit - 1
mask[31 - curBit] = 1
correctBits[31 - curBit] = 1
elif (val == '(0)') or (val == '(1)'):
# Ignore, even though the result should be undefined...
curBit = curBit - 1
elif val == 'cond':
curBit = curBit - 4
variables["cond"] = curBit
elif val == 'Rd':
curBit = curBit - 4
variables["registers"]["d"][2] = curBit
elif val == 'RdLo':
curBit = curBit - 4
variables["registers"]["d"][3] = curBit
elif val == 'RdHi':
curBit = curBit - 4
variables["registers"]["d"][4] = curBit
elif val == 'Rt':
curBit = curBit - 4
variables["registers"]["t"][2] = curBit
elif val == 'Rn':
curBit = curBit - 4
variables["registers"]["n"][2] = curBit
elif val == 'Rm':
curBit = curBit - 4
variables["registers"]["m"][2] = curBit
elif val == 'Ra':
curBit = curBit - 4
variables["registers"]["a"][2] = curBit
elif val == 'S':
curBit = curBit - 1
variables["s"] = curBit
elif val == 'U':
curBit = curBit - 1
variables["u"] = curBit
elif val == 'W':
curBit = curBit - 1
variables["w"] = curBit
elif val == 'rotate':
curBit = curBit - 2
variables["r"] = curBit
elif val == 'lsb':
curBit = curBit - 5
variables["sb"][0] = curBit
elif val == 'msb':
curBit = curBit - 5
variables["sb"][1] = curBit
elif val == 'widthm1':
curBit = curBit - 5
variables["sb"][2] = curBit
elif val == 'register_list':
curBit = curBit - 16
variables["reglist16"] = curBit
elif val == 'sat_imm':
curBit = curBit - 4
imms.append([curBit, 4])
elif val.startswith('@<') and val.endswith('>'):
parmlen = int(val[2:-1])
curBit = curBit - parmlen
parm.append([curBit, parmlen])
elif val.startswith('imm'):
if val.endswith('H') or val.endswith('L'): val = val[:-1]
immsz = int(val[3:])
curBit = curBit - immsz
imms.append([curBit, immsz])
else:
fail(KeyError, "Unknown value '" + val + "'")
curSplt = i + 2
parse_var_requirements()
if curBit == 0:
break
elif curBit < 0:
fail(KeyError, "Current bit too low (" + str(curBit) + ")")
if curSplt == -1:
fail(KeyError, "Not enough arguments")
generate_bin_test()
# Add C variables
if variables["s"] != -1:
append("int s = (opcode >> " + str(variables["s"]) + ") & 1;\n")
if variables["cond"] != -1:
if mask[31 - variables["cond"]] == 0:
append("const char* cond = conds[(opcode >> " + str(variables["cond"]) + ") & 0xF];\n")
else:
variables["cond"] = -2
if variables["registers"]["d"][2] != -1:
append("int rd = (opcode >> " + str(variables["registers"]["d"][2]) + ") & 0xF;\n")
if variables["registers"]["d"][3] != -1:
assert(variables["registers"]["d"][4] != -1)
append("int rdlo = (opcode >> " + str(variables["registers"]["d"][3]) + ") & 0xF;\n")
append("int rdhi = (opcode >> " + str(variables["registers"]["d"][4]) + ") & 0xF;\n")
if variables["registers"]["t"][2] != -1:
append("int rt = (opcode >> " + str(variables["registers"]["t"][2]) + ") & 0xF;\n")
if variables["registers"]["n"][2] != -1:
append("int rn = (opcode >> " + str(variables["registers"]["n"][2]) + ") & 0xF;\n")
if variables["registers"]["m"][2] != -1:
append("int rm = (opcode >> " + str(variables["registers"]["m"][2]) + ") & 0xF;\n")
if variables["registers"]["a"][2] != -1:
append("int ra = (opcode >> " + str(variables["registers"]["a"][2]) + ") & 0xF;\n")
if variables["u"] != -1:
append("int u = (opcode >> " + str(variables["u"]) + ") & 1;\n")
if variables["w"] != -1:
append("int w = (opcode >> " + str(variables["w"]) + ") & 1;\n")
if variables["r"] != -1:
append("int rot = (opcode >> " + str(variables["r"]) + ") & 3;\nchar tmprot[8] = {0};\n")
append("if (rot) {\nsprintf(tmprot, \" ror %d\", rot * 8);\n}\n")
if variables["sb"][0] != -1:
append("int lsb = (opcode >> " + str(variables["sb"][0]) + ") & 0x1F;\n")
if variables["sb"][1] != -1:
append("int msb = (opcode >> " + str(variables["sb"][1]) + ") & 0x1F;\n")
if variables["sb"][2] != -1:
append("int widthm1 = (opcode >> " + str(variables["sb"][2]) + ") & 0x1F;\n")
if variables["reglist16"] != -1:
append("int reglist = (opcode >> " + str(variables["reglist16"]) + ") & 0xFFFF;\n")
if imms != []:
immssz = sum(map(lambda v: v[1], imms))
tmp = "(" * len(imms)
for immpos, immsz in imms:
if tmp[-1] != '(': tmp = tmp + " << " + str(immsz) + ") | "
tmp = tmp + "((opcode >> " + str(immpos) + ") & " + sz2str(immsz) + ")"
tmp = tmp[1:]
append("uint" + str(nextAvailable(immssz)) + "_t imm" + str(immssz) + " = " + tmp + ";\n")
# Destroy imms since we don't need it anymore, but we do need immssz
imms = immssz
add_custom_variables()
append("\nsprintf(ret, \"")
# Assemble the variables into the printf
instText = ' '.join(spltln[curSplt:]).split('<')
instText = [instTextPart.split('>') for instTextPart in instText]
instText = [itp for itp2 in instText for itp in itp2]
# Make the failures nicer
spltln = spltln[:curSplt] + ["\x00"] + instText
printf_args = ""
for idx, text in enumerate(instText):
text = text.replace("&l", "<").replace("&g", ">")
if "+/-" in text:
text = text.replace("+/-", "%s")
printf_args = printf_args + ", (u ? \"\" : \"-\")"
if "{!}" in text:
text = text.replace("{!}", "%s")
printf_args = printf_args + ", (w ? \"!\" : \"\")"
skiprbr = False
if idx % 2:
if text == "c":
if variables["cond"] != -1:
append("%s")
printf_args = printf_args + ", cond"
elif text == "Rd":
append("%s")
printf_args = printf_args + ", regname[rd]"
elif text == "RdLo":
append("%s")
printf_args = printf_args + ", regname[rdlo]"
elif text == "RdHi":
append("%s")
printf_args = printf_args + ", regname[rdhi]"
elif text == "Rt":
append("%s")
printf_args = printf_args + ", regname[rt]"
elif text == "Rt2":
append("%s")
printf_args = printf_args + ", regname[rt + 1]"
elif text == "Rn":
append("%s")
printf_args = printf_args + ", regname[rn]"
elif text == "Rm":
append("%s")
printf_args = printf_args + ", regname[rm]"
elif text == "Ra":
append("%s")
printf_args = printf_args + ", regname[ra]"
elif text == "const":
assert(imms == 12)
append("0x%x")
printf_args = printf_args + ", print_modified_imm_ARM(imm12)"
elif text == "rotation":
if output.endswith("{, "):
output = output[:-3]
skiprbr = True
append("%s")
printf_args = printf_args + ", tmprot"
elif text == "label":
append("%+d")
printf_args = printf_args + ", (imm24 & 0x800000 ? imm24 | 0xFF000000 : imm24) + 2"
elif text == "lsb":
append("%d")
printf_args = printf_args + ", lsb"
elif text == "width":
append("%d")
printf_args = printf_args + (", msb - lsb + 1" if variables["sb"][1] != -1 else ", widthm1 + 1")
elif text == "registers":
append("%s")
printf_args = printf_args + ", print_register_list(reglist, 16)"
elif text == "imm":
#append("0x%0" + str(ceil(imms / 4)) + "x")
append("0x%x")
printf_args = printf_args + ", imm" + str(imms)
elif text.startswith("imm"):
if variables["u"] != -1:
append("%d")
else:
#append("0x%0" + str(ceil(int(text[3:]) / 4)) + "x")
append("0x%x")
printf_args = printf_args + ", " + text
else:
fail(KeyError, "Unknown variable " + text)
elif text.endswith("{S}"):
append(text[:-3] + "%s")
printf_args = printf_args + ", (s ? \"S\" : \"\")"
else:
if text == "":
continue
text = text.split('\\')
while len(text) > 1:
if text[1][0] == '%':
modifier, text[1] = '%', text[1][1:]
while (len(text[1]) > 1) \
and (text[1][0] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+']):
modifier, text[1] = modifier + text[1][0], text[1][1:]
modifier, text[1] = modifier + text[1][0], text[1][1:]
append(text[0] + modifier)
else:
append(text[0] + "%s")
printf_args = printf_args + ", " + text[1]
text = text[2:]
if len(text) == 0:
fail(AssertionError, "Substitution not finished")
if skiprbr and (text[0][0] == "}"):
text[0] = text[0][1:]
append(text[0])
curSplt = curSplt + 1
append("\"" + printf_args + ");\n} else ")
elif (spltln[0].upper() == "ARMS") or (spltln[0] == "ARM$"):
# ARM Shift instruction
# ARMs is only with immediate, ARM$ is only with register
variables["cond"] = -1
variables["registers"] = {
"d": [-1, -1, -1], # Register: #, ##, Rd
"t": [-1, -1, -1], # Register: #, ##, Rt
"n": [-1, -1, -1], # Register: #, ##, Rn
"m": [-1, -1, -1] # Register: #, ##, Rm
}
variables["s"] = -1 # Set flags
variables["u"] = -1 # Unsigned shift
variables["w"] = -1 # wback (used in adressing)
variables["shift"] = False # Shift already detected?
for i, val in enumerate(spltln[1:]):
if '/' in val:
ocurBit = curBit
req = val.split('/')
val, req = req[0], '/'.join(req[1:])
if val == '0':
curBit = curBit - 1
mask[31 - curBit] = 1
elif val == '1':
curBit = curBit - 1
mask[31 - curBit] = 1
correctBits[31 - curBit] = 1
elif (val == '(0)') or (val == '(1)'):
# Ignore, even though the result should be undefined...
curBit = curBit - 1
elif val == 'cond':
curBit = curBit - 4
variables["cond"] = curBit
elif val == 'Rd':
curBit = curBit - 4
variables["registers"]["d"][2] = curBit
elif val == 'Rt':
curBit = curBit - 4
variables["registers"]["t"][2] = curBit
elif val == 'Rn':
curBit = curBit - 4
variables["registers"]["n"][2] = curBit
elif val == 'Rm':
curBit = curBit - 4
variables["registers"]["m"][2] = curBit
elif val == 'S':
curBit = curBit - 1
variables["s"] = curBit
elif val == 'U':
curBit = curBit - 1
variables["u"] = curBit
elif val == 'W':
curBit = curBit - 1
variables["w"] = curBit
elif val == 'type':
curBit = curBit - 2
imms.append([curBit, 2])
variables["shift"] = True
elif val == 'sat_imm':
curBit = curBit - 5
imms.append([curBit, 5, True])
elif val == 'sh':
curBit = curBit - 1
elif val.startswith('@<') and val.endswith('>'):
parmlen = int(val[2:-1])
curBit = curBit - parmlen
parm.append([curBit, parmlen])
elif val.startswith('imm'):
if variables["shift"]: fail(ValueError, "Immediate after a 'type' value detected")
immsz = int(val[3:])
curBit = curBit - immsz
imms.append([curBit, immsz])
variables["shift"] = immsz == 12
else:
fail(KeyError, "Unknown value '" + val + "'")
curSplt = i + 2
parse_var_requirements()
if curBit == 0:
break
elif curBit < 0:
fail(KeyError, "Current bit too low (" + str(curBit) + ")")
if curSplt == -1:
fail(KeyError, "Not enough arguments")
# There is not necessarily an explicit shift when using an ARMs
elif not variables["shift"] and (spltln[0] == "ARMS"):
fail(KeyError, "No shift detected")
# Assumption:
# bytes 11-4 are [imm5 type 0] (then auto-complete for [Rs 0 type 1 Rm])
if (spltln[0] == "ARMS") and ((mask[20:24] + mask[25:28] != [0, 0, 0, 0, 0, 0, 1]) \
or ((correctBits[27] != 0) or (len(imms) != 2) or (imms[0] != [7, 5]))):
fail(NotImplementedError, "Unknown case with shift")
if (spltln[0] == "ARMS"):
generate_bin_test([24, 27], [[(0, 0), (1, 0)], [(1, 0), (1, 1)]])
else:
generate_bin_test()
# Add C variables
if variables["s"] != -1:
append("int s = (opcode >> " + str(variables["s"]) + ") & 1;\n")
if variables["cond"] != -1:
if mask[31 - variables["cond"]] == 0:
append("const char* cond = conds[(opcode >> " + str(variables["cond"]) + ") & 0xF];\n")
else:
variables["cond"] = -2
if variables["registers"]["d"][2] != -1:
append("int rd = (opcode >> " + str(variables["registers"]["d"][2]) + ") & 0xF;\n")
if variables["registers"]["t"][2] != -1:
append("int rt = (opcode >> " + str(variables["registers"]["t"][2]) + ") & 0xF;\n")
if variables["registers"]["n"][2] != -1:
append("int rn = (opcode >> " + str(variables["registers"]["n"][2]) + ") & 0xF;\n")
if variables["registers"]["m"][2] != -1:
append("int rm = (opcode >> " + str(variables["registers"]["m"][2]) + ") & 0xF;\n")
if variables["u"] != -1:
append("int u = (opcode >> " + str(variables["u"]) + ") & 1;\n")
if variables["w"] != -1:
append("int w = (opcode >> " + str(variables["w"]) + ") & 1;\n")
if (len(imms) == 2) and (len(imms[0]) == 3):
append("uint8_t imm = ((opcode >> " + str(imms[0][0]) + ") & 0x1F) + 1;\n")
append("uint8_t shift = ((opcode >> 4) & " + \
("0xFF)" if (spltln[0] == "ARMS") else ("0xFE)" if (spltln[0] == "ARMs") else "0xFF) | 0x01")) + \
";\n")
add_custom_variables()
append("\nsprintf(ret, \"")
# Assemble the variables into the printf
instText = ' '.join(spltln[curSplt:]).split('<')
instText = [instTextPart.split('>') for instTextPart in instText]
instText = [itp for itp2 in instText for itp in itp2]
# Make the failures nicer
spltln = spltln[:curSplt] + ["\x00"] + instText
printf_args = ""
for idx, text in enumerate(instText):
text = text.replace("&l", "<").replace("&g", ">")
if "+/-" in text:
text = text.replace("+/-", "%s")
printf_args = printf_args + ", (u ? \"\" : \"-\")"
if "{!}" in text:
text = text.replace("{!}", "%s")
printf_args = printf_args + ", (w ? \"!\" : \"\")"
if idx % 2:
if text == "c":
if variables["cond"] != -1:
append("%s")
printf_args = printf_args + ", cond"
elif text == "Rd":
append("%s")
printf_args = printf_args + ", regname[rd]"
elif text == "Rt":
append("%s")
printf_args = printf_args + ", regname[rt]"
elif text == "Rt2":
append("%s")
printf_args = printf_args + ", regname[rt + 1]"
elif text == "Rn":
append("%s")
printf_args = printf_args + ", regname[rn]"
elif text == "Rm":
append("%s")
printf_args = printf_args + ", regname[rm]"
elif text == "imm":
append("%d")
printf_args = printf_args + ", imm"
elif text == "shift":
# Tricky, since it is optional, but I want to have a pure copy-paste of the official doc
# so we remove the end of the output if necessary
# Otherwise it is as usual, however we use the print_shift method
comma = "0"
if output.endswith("{, "):
output = output[:-3]
comma = "1"
append("%s")
printf_args = printf_args + ", print_shift(shift, " + comma + ")"
else:
fail(KeyError, "Unknown variable " + text)
elif text.endswith("{S}"):
append(text[:-3] + "%s")
printf_args = printf_args + ", (s ? \"S\" : \"\")"
elif text.startswith("}"):
append(text[1:])
else:
if text == "":
continue
text = text.split('\\')
while len(text) > 1:
if text[1][0] == '%':
modifier, text[1] = '%', text[1][1:]
while (len(text[1]) > 1) \
and (text[1][0] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+']):
modifier, text[1] = modifier + text[1][0], text[1][1:]
modifier, text[1] = modifier + text[1][0], text[1][1:]
append(text[0] + modifier)
else:
append(text[0] + "%s")
printf_args = printf_args + ", " + text[1]
text = text[2:]
if len(text) == 0:
fail(AssertionError, "Substitution not finished")
append(text[0])
curSplt = curSplt + 1
append("\"" + printf_args + ");\n} else ")
elif spltln[0] == "NEON":
# NEON (advanced SIMD) instruction
variables["registers"] = {
"d": [-1, -1, -1], # Register: D, Vd, ##
"t": [-1, -1, -1], # Register: #, ##, Rt
"n": [-1, -1, -1], # Register: N, Vn, ##
"m": [-1, -1, -1] # Register: M, Vm, ##
}
variables["op"] = -1 # Operation
variables["u"] = -1 # Unsigned
variables["f"] = -1 # Floating-point
variables["sz"] = [-1, 0] # Operation size: pos, len
variables["cmode"] = -1 # Used with immediates
variables["q"] = -1 # Quadword
for i, val in enumerate(spltln[1:]):
if '/' in val:
ocurBit = curBit
req = val.split('/')
val, req = req[0], '/'.join(req[1:])
if val == '0':
curBit = curBit - 1
mask[31 - curBit] = 1
elif val == '1':
curBit = curBit - 1
mask[31 - curBit] = 1
correctBits[31 - curBit] = 1
elif (val == '(0)') or (val == '(1)'):
# Ignore, even though the result should be undefined...
curBit = curBit - 1
elif val == 'D':
curBit = curBit - 1
variables["registers"]["d"][0] = curBit
elif val == 'Vd':
curBit = curBit - 4
variables["registers"]["d"][1] = curBit
elif val == 'Rt':
curBit = curBit - 4
variables["registers"]["t"][2] = curBit
elif val == 'N':
curBit = curBit - 1
variables["registers"]["n"][0] = curBit
elif val == 'Vn':
curBit = curBit - 4
variables["registers"]["n"][1] = curBit
elif val == 'Rn':
curBit = curBit - 4
variables["registers"]["n"][2] = curBit
elif val == 'M':
curBit = curBit - 1
variables["registers"]["m"][0] = curBit
elif val == 'Vm':
curBit = curBit - 4
variables["registers"]["m"][1] = curBit
elif val == 'Rm':
curBit = curBit - 4
variables["registers"]["m"][2] = curBit
elif val == 'U':