-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathriscvsim.py
More file actions
executable file
·2271 lines (1987 loc) · 87.2 KB
/
riscvsim.py
File metadata and controls
executable file
·2271 lines (1987 loc) · 87.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
# a risc-v disassembler ans simulator. using the definitions from the riscv-opcodes repository.
import re
import os
import os.path
from binascii import a2b_hex
import struct
import random
# TODO:
# -DONE add support for multiple fuction calls
# -DONE add support for function calls to include args
# specified as: (a0, a1, ...)
# - DONE improve indent algorithm - correlate with stackpointer.
# - add i/o handlers.
# TODO: make misa.S configurable
# - NF5 tests need S mode
# - Titan-M2 runs without S mode
# TODO: support irq calls -> note TODO in trap-handler.
# TODO: extract code for devices from mem.store, mem.load
# TODO: add fast (in-python) implementations for certains calls, like memset, memcpu, sha256, modexp
# TODO: implement pmp memory protection
# TODO: merge disassemble and simulate functions
# todo: add special handlers for certain memory addresses
# todo: add special handlers for certain subroutines.
# register names:
# compressed:
# 0 1 2 3 4 5 6 7
# x8 x9 x10 x11 x12 x13 x14 x15
# (f)s0 (f)s1 (f)a0 (f)a1 (f)a2 (f)a3 (f)a4 (f)a5
# conventions:
# x0 = zero
# x1 = ra : return address
# x2 = sp : stack pointer
# x3 = gp : global pointer
# x4 = tp : thread pointer
# x5 = : alternate link register
# x5-x7 = t0-t2 : temporary registers: not preserved
# x8-x9 = s0-s1 : callee saved regs
# x10-x17 = a0-a7 : argument regs
# x18-x27 = s2-s11 : callee saved regs
# x28-x31 = t3-t6 : temporrary regs: not preserved
# or more compact:
# 0 1 2 3 4 5 6 7
# 00: 00 ra sp gp tp t0 t1 t2
# 08: s0 s1 a0 a1 a2 a3 a4 a5
# 10: a6 a7 s2 s3 s4 s5 s6 s7
# 18: s8 s9 sA sB t3 t4 t5 t6
# floating point regs
# f0-f7 = ft0-ft7
# f8-f9 = fs0-fs1
# f10-f17 = fa0-fa7
# f18-f27 = fs2-fs11
# f28-f31 = ft8-ft11
# note that 0x7c0-0x7ff is listed as 'Machine-Level CSR, Custom R/W'
# note that 0x800-0x8ff is listed as 'Unprivileged, User-Level CSR, Custom R/W'
# 0300 mstatus - machine status register
# 1 - SIE S-mode interrupt enable
# 3 - MIE M-mode interrupt enable
# 5 - SPIE S-mode privileged interrupt enable
# 6 - UBE U-mode big-endian memory reads
# 7 - MPIE M-mode privileged interrupt enable
# 8 - SPP S-mode previous privilege mode
# 10,9 - VS Vector-extension unit status (0 = off, 1 = initial, 2 = clean, 3 = dirty)
# 12,11 - MPP M-mode previous privilege mode
# 14,13 - FS Floating-Point unit status (0 = off, 1 = initial, 2 = clean, 3 = dirty)
# 16,15 - XS Usermode-extension unit status (0 = off, 1 = some on, 2 = some clean, 3 = some dirty)
# 17 - MPRV Modify Privilege
# 18 - SUM permit supervisor user memory access
# 19 - MXR Make executable readable
# 20 - TVM Trap Virtual Memory
# 21 - TW Timeout Wait -> WFI has timeout in lower privilege levels
# 22 - TSR Trap SRET ( supervisor return )
# 31 - SD any of VS|FS|XS dirty
# 0304 mie - machine interrupt enable register
# 0305 mtvec - machine trap handler base address
# 0340 mscratch- scratch reg or machine trap handlers
# 0341 mepc - machine exception program counter
# 0342 mcause - machine trap cause
# 0343 mtval - machine bad address or instruction
# 0344 mip - machine interrupt pending
# 0b00 mcycle - machine cycle counter
# exceptions
# * E_Fetch_Addr_Align() => 0, # "misaligned-fetch",
# * E_Fetch_Access_Fault() => 1, # "fetch-access-fault",
# * E_Illegal_Instr() => 2, # "illegal-instruction",
# * E_Breakpoint() => 3, # "breakpoint",
# * E_Load_Addr_Align() => 4, # "misaligned-load",
# * E_Load_Access_Fault() => 5, # "load-access-fault",
# * E_SAMO_Addr_Align() => 6, # "misaliged-store/amo",
# * E_SAMO_Access_Fault() => 7, # "store/amo-access-fault",
# * E_U_EnvCall() => 8, # "u-call",
# * E_S_EnvCall() => 9, # "s-call",
# * E_Reserved_10() => 10, # "reserved-0",
# * E_M_EnvCall() => 11, # "m-call",
# * E_Fetch_Page_Fault() => 12, # "fetch-page-fault",
# * E_Load_Page_Fault() => 13, # "load-page-fault",
# * E_Reserved_14() => 14, # "reserved-1",
# * E_SAMO_Page_Fault() => 15, # "store/amo-page-fault",
# bits are in medeleg register
# interrupt type:
# * I_U_Software => 0x00, # USI
# * I_S_Software => 0x01, # SSI
# * I_M_Software => 0x03, # MSI
# * I_U_Timer => 0x04, # UTI
# * I_S_Timer => 0x05, # STI
# * I_M_Timer => 0x07, # MTI
# * I_U_External => 0x08, # UEI
# * I_S_External => 0x09, # SEI
# * I_M_External => 0x0b # MEI
# bits are in mip, mie, mideleg registers
# pmp
# cfgbits: L 00 AA X W R
# L = locked: readonly until reset
# X = execute perm -> E_Fetch_Access_Fault
# W = write perm -> E_SAMO_Access_Fault
# R = read perm -> E_Load_Access_Fault
# AA = matchtype:
# 00 -> none
# 01 -> TOR : pmpaddr[-1] <= addr < pmpaddr
# 10 -> NA4 : pmpaddr <= addr < pmpaddr+4
# 11 -> NAPOT : pmpaddr <= addr < pmpaddr+size
# pmpaddr are stored >>2
# pmpaddr ends in 01...1 -> this is te NAPOT-size >>3 -1
#
# arch: 01=rv32, 10=rv64, 11=rv128
# mode: 00=user, 01=super, 11=machine
# instruction patterns:
# ..aa -> 16-bit, aa!=11
# ...bbb11 -> 32-bit, bb!=111
# ......011111 -> 48-bit
# .........0111111 -> 64-bit
# **nnn......1111111 -> 80+16*nnn -bit, nnn!=111
# ***nnn......1111111 -> >192-bit
#base instruction types:
# 1098765|43210 |98765 |432 |10987 |6543210
# |31 25|24 20|19 15|14 12|11 7|6 0|
# +-------+-------+-------+-------+--------+--------+
# | func7 | rs2 | rs1 | func3 | rd | opcode | R-type
# | ----imm12---- | rs1 | func3 | rd | opcode | I-type
# | immh12| rs2 | rs1 | func3 | imml12 | opcode | S-type + B-type
# | -------------imm20----------- | rd | opcode | U-type + J-type
# major opcode groups:
#
#bit65\ 0 1 2 3 4 5 6 7 <-bits4-2
# 0 LOAD LOAD-FP custom-0 MISC-MEM OP-IMM AUIPC OP-IMM-32 48b
# 1 STORE STORE-FP custom-1 AMO OP LUI OP-32 64b
# 2 MADD MSUB NMSUB NMADD OP-FP OP-V cust2/ru128 48b
# 3 BRANCH JALR reserved JAL SYSTEM reserved cust3/ru128 >80b
def undef(x):
return "?"*8 if x is None else f"{x:08x}"
def maskbits(n):
""" return a value with the lowest 'n' bits set to one. """
return (1<<n)-1
def reorderbits(value, *bitspec):
"""
bitspec specifies where a bit from that position should be copied to, in big-endian order
This function is used to decode values using the bit-order as specified in the riscv-spec.
"""
# in imm20 order:
# 20 10-1 11 19-12 -> ofs bits
# 19 18-9 8 7-0 -> imm20 bits
# in ofs order:
# 20 19-12 11 10-1 -> ofs bits
# 19 7-0 8 18-9 -> imm20 bits
result = 0
for b in bitspec[::-1]:
if type(b) == tuple:
h, l = b
bits = value & ((1<<(h-l+1))-1)
value >>= h-l+1
result |= bits<<l
else:
bit = value&1
value >>= 1
result |= bit<<b
return result
def signed(val, bits):
"""
Sign-extend the value from 'bits'
example:
0 1 2 3 4 5 6 7 val
0 1 2 3 -4 -3 -2 -1 signed(val, 3)
"""
val &= maskbits(bits)
if val >= 1<<(bits-1):
return val - (1<<bits)
return val
def unsigned(val, bits=32):
"""
converts 'val' to a 32-bit unsigned value
"""
return val & maskbits(bits)
class NamedBitFields:
"""
Create named bitfields.
The specification is passed using keyword arguments, where an integer
value indicates a single bit, and a tuple indicates an inclusive range of bits.
example spec:
mstatus = NamedBitFields(SPP=8, MPP=(12,11), FS=(14,13), XS=(16,15))
mstatus.MPP = 1
access to all 32 bits using the `bits()` method.
"""
def __init__(self, **spec):
self._spec = spec
self._value = 0
def bits(self): return self._value
def setbits(self, value): self._value = value
def __getattr__(self, name):
match bits := self._spec.get(name):
case (hi, lo):
return self._value>>lo & maskbits(hi-lo+1)
case int(bit):
return self._value>>bit & 1
case None:
raise AttributeError()
def __setattr__(self, name, value):
if name.startswith('_'):
return super().__setattr__(name, value)
match bits := self._spec.get(name):
case (hi, lo):
m = maskbits(hi-lo+1)
self._value &= ~(m<<lo)
self._value |= (value&m)<<lo
case int(bit):
self._value &= ~(1<<bit)
self._value |= (value&1)<<bit
case None:
return super().__setattr__(name, value)
def __repr__(self):
txt = ""
for k in self._spec.keys():
txt += " %s=%d" % (k, getattr(self, k))
return txt
class Instruction:
"""
Represent a decoded instruction.
This is the object returned by InstructionPattern.decode()
"""
def __init__(self, opc, mnemonic, args):
self.opc = opc
self.mnemonic = mnemonic
self.args = dict(args)
def __str__(self):
argstr = ", ".join("%s=0x%x" % (k, v) for k, v in self.args.items())
return f"{self.mnemonic}\t{argstr}"
def __getattr__(self, name):
if name in self.args:
return self.args[name]
print("known attr: ", self.args)
raise AttributeError()
class InstructionPattern:
"""
Represents a instruction pattern from the riscv-opcodes repository
"""
def __init__(self, line, decoder):
self.decoder = decoder
self.insnname = None
self.comment = None
self.ignoremask = 0
self.valuemask = 0
self.value = 0
self.namedmask = 0
self.named = []
self.parse(line)
def parse(self, line):
if m := re.match(r'''^(?:\$pseudo_op\s+\S+\s+)?(\S+)\s+(\S.*?\S)\s*(?:#\s*(.*))?$''', line):
self.insnname = m.group(1)
fieldspec = m.group(2)
self.comment = m.group(3)
for spec in re.split(r'\s+', fieldspec):
if m := re.match(r'^(\d+)(?:\.\.(\d+))?=(\d\w*|ignore)$', spec):
# hi..lo=value
b1 = int(m.group(1), 0)
b0 = int(m.group(2), 0) if m.group(2) else b1
val = int(m.group(3), 0) if m.group(3) != 'ignore' else None
#print(spec, "->", b1, b0, val)
newmask = maskbits(b1-b0+1)<<b0
if self.allmasks() & newmask:
print("WARN: bits already masked: %s" % spec)
if val is not None:
self.valuemask |= newmask
self.value |= val<<b0
else:
self.ignoremask |= newmask
elif spec in self.decoder.namedbitfields:
# names like: rs1, rd, etc.
self.named.append(spec)
b1, b0 = self.decoder.namedbitfields[spec]
#print(spec, "->", b1, b0)
newmask = maskbits(b1-b0+1)<<b0
if self.allmasks() & newmask:
print("WARN: bits already maked: %s" % spec)
self.namedmask |= newmask
# print("spec is named: %s(%d,%d) -> %x" % (spec, b1, b0, newmask))
elif self.decoder.args.verbose:
"""
note: currently one unhandled case:
riscv-crypto/tools/opcodes-crypto-scalar-rv64
aes64ks1i rd rs1 rcon rcon:<=10 31..30=0 29..25=0b11000 24=1 14..12=0b001 6..0=0x13
"""
print("WARN: unknown spec: %s" % spec)
else:
print("WARN: unrecognised opcode line: %s" % line)
if self.namedmask & self.valuemask:
print("WARN: mask overlap")
elif self.namedmask & self.ignoremask:
print("WARN: mask overlap")
elif self.ignoremask & self.valuemask:
print("WARN: mask overlap")
allbits = self.allmasks()
if allbits > 0x10000:
allbits ^= maskbits(32)
else:
allbits ^= maskbits(16)
if allbits:
print("WARN: unused bits: %8x - %s" % (allbits, line))
def allmasks(self):
return self.namedmask | self.valuemask | self.ignoremask
def matches(self, opc):
if opc & ~ self.allmasks():
return False
return (opc & self.valuemask) == self.value
def decode(self, opc):
info = []
for f in self.named:
b1, b0 = self.decoder.namedbitfields[f]
mask = maskbits(b1-b0+1)<<b0
info.append((f, (opc&mask)>>b0))
return Instruction(opc, self.insnname, info)
class InstructionDecoder:
"""
Reads instruction definitions from riscv-opcodes, and uses that information to decode
opcodes.
"""
def __init__(self, args):
self.args = args
self.instructions = []
self.namedbitfields = dict()
self.csr_regs = dict()
self.load()
def load(self):
basepath = os.path.dirname(os.path.realpath(__file__))
self.loadconstants(os.path.join(basepath, "riscv-opcodes/constants.py"))
self.loadconstants(os.path.join(basepath, "riscv-crypto/bin/parse_opcodes.py"))
for opcfilename, sectionname in self.enumopcodefiles():
with open(opcfilename, "r") as fh:
for op in self.readopcodefile(fh):
op.srcfile = sectionname
self.instructions.append(op)
for spec in self.google_custom_insn():
self.instructions.append(InstructionPattern(spec, self))
def google_custom_insn(self):
# opcode f3 imm12
yield "gbswap32 rd rs1 6..0=0x0b 14..12=0 31..20=0x018"
yield "grbitscan rd rs1 6..0=0x0b 14..12=2 31..20=0x400"
yield "gbitscan rd rs1 6..0=0x0b 14..12=2 31..20=0x000"
yield "gclrbit rd rs1 rs2 6..0=0x2b 14..12=1 31..25=0x00"
yield "gsetbit rd rs1 rs2 6..0=0x2b 14..12=1 31..25=0x20"
yield "gclrbiti rd rs1 shamt 6..0=0x0b 14..12=1 31..27=0x00"
yield "gsetbiti rd rs1 shamt 6..0=0x0b 14..12=1 31..27=0x08"
yield "illegal 15..0=0"
def loadconstants(self, fn):
# loads constants used in the instruction definitions.
for line in open(fn):
if m := re.match(r"^\s*\(\s*(0x\w\w\w)\s*,\s*'(\S+)'\),", line):
regnum = int(m[1], 0)
regname = m[2]
if regnum in self.csr_regs:
# note: this happens for:
# csr07b2: dscratch0 / dscratch
# csr0f15: mconfigptr / mentropy
if self.csr_regs[regnum] != regname:
if self.args.verbose:
print("WARNING: multiple names for csr%04x: %s / %s" % (regnum, self.csr_regs[regnum], regname))
else:
self.csr_regs[regnum] = regname
elif m := re.match(r"arg_?lut\['(\S+)'\s*\] *= *\(\s*(\d+),\s*(\d+)\s*\)", line):
fieldname = m[1]
highbit = int(m[2])
lowbit = int(m[3])
if fieldname in self.namedbitfields:
if self.namedbitfields[fieldname] != (highbit, lowbit):
if self.args.verbose:
# note: inconsistency in defs for main/cryptp: shamt -> main: (26, 20) / crypto: (25, 20)
print("WARNING: incompatible field def: %s -> %s / %s" % (fieldname, self.namedbitfields[fieldname], (highbit, lowbit)))
else:
self.namedbitfields[fieldname] = (highbit, lowbit)
def readopcodefile(self, fh):
while True:
line = fh.readline()
if not line:
# eof
break
line = line.rstrip("\n")
if m := re.match(r'^\s*#', line):
# skip comments
pass
elif m := re.match(r'''^\$import \S+''', line):
pass
elif not line:
# skip empty
pass
elif line.startswith("c.addiw "):
# one exception: c.addiw is rv64+rv128, while c.jal is rv32 for the same opcode.
pass
elif line.startswith("$"):
pass
else:
yield InstructionPattern(line, self)
def enumopcodefiles(self):
basepath = os.path.dirname(os.path.realpath(__file__))
for opcdir in ("riscv-opcodes", "riscv-crypto/tools"):
for path, dirs, files in os.walk(os.path.join(basepath, opcdir)):
if ".git" in dirs:
dirs.remove(".git")
for fn in files:
if fn.find(".") >= 0: continue
if fn in ("Makefile", "LICENSE" ,"Gemfile"): continue
if m := re.match(r'opcodes-(\S+)', fn):
yield os.path.join(path, fn), m.group(1)
elif m := re.match(r'rv(\S+)', fn):
yield os.path.join(path, fn), m.group(1)
else:
print("WARN: unmatched filename: ", fn)
def decodeinsn(self, opc):
"""
searches the instruction table for a matching opcode.
returns an Instruction object when found.
returns None when the instruction is unknown.
"""
matches = []
for insn in self.instructions:
if insn.matches(opc):
# make sure the match with most fixed bits is found
# for example:
# riscv-opcodes/rv_c
# c.addi16sp c_nzimm10hi c_nzimm10lo 1..0=1 15..13=3 11..7=2
# c.lui rd_n2 c_nzimm18hi c_nzimm18lo 1..0=1 15..13=3
# n=0000107c v=0000ef83
# n=00001ffc v=0000e003
# other problem: cpu specific insn
# c.jal c_imm12 1..0=1 15..13=1 riscv-opcodes/rv32_c
# c.addiw rd_rs1 c_imm6lo c_imm6hi 1..0=1 15..13=1 riscv-opcodes/rv64_c + riscv-opcodes/unratified/rv128_c
matches.append((insn.namedmask, insn.valuemask, insn.ignoremask, insn))
matches = sorted(matches, key=lambda m:m[1])
if matches:
return matches[-1][-1].decode(opc)
def analyzeopcodes(self, opcodelist):
"""
print decoding information for the given opcodes.
"""
for opcbytes in opcodelist:
opc = int.from_bytes(opcbytes, 'little')
matches = []
for insn in self.instructions:
if insn.matches(opc):
# make sure the match with most fixed bits is found
# for example:
# riscv-opcodes/rv_c
# c.addi16sp c_nzimm10hi c_nzimm10lo 1..0=1 15..13=3 11..7=2
# c.lui rd_n2 c_nzimm18hi c_nzimm18lo 1..0=1 15..13=3
# n=0000107c v=0000ef83
# n=00001ffc v=0000e003
# other problem: cpu specific insn
# c.jal c_imm12 1..0=1 15..13=1 riscv-opcodes/rv32_c
# c.addiw rd_rs1 c_imm6lo c_imm6hi 1..0=1 15..13=1 riscv-opcodes/rv64_c + riscv-opcodes/unratified/rv128_c
matches.append((insn.namedmask, insn.valuemask, insn.ignoremask, insn))
matches = sorted(matches, key=lambda m:m[1])
if not matches:
print("%08x: WARN: no matches for opcode" % (opc))
#lif args.debugdecoder:
# for a,b,c, m in matches:
# print("%08x: [%08x:%08x:%08x] -> %s" % (opc, a,b,c, m.decode(opc)))
else:
insn = matches[-1][-1].decode(opc)
print("%08x: %s" % (opc, insn))
class PRIV:
"""
Named constants for the privilege levels.
"""
USER = 0
SUPER = 1
MACHINE= 3
@staticmethod
def name(x):
match x:
case PRIV.USER:
return "user"
case PRIV.SUPER:
return "super"
case PRIV.MACHINE:
return "machine"
@staticmethod
def decode(x):
match x:
case 'user': return PRIV.USER
case 'super': return PRIV.SUPER
case 'machine': return PRIV.MACHINE
class CPU:
"""
Keep state for the risc-v cpu.
"""
# class dicts.
_csrnames = { }
_csrnums = { }
_regnames = [ "zero", "ra", "sp", "gp", "tp" ]
_rnums = { }
def __init__(self, args):
self.args = args
if not self._csrnums:
# init class dict on first use.
for k, v in self._csrnames.items():
self._csrnums[v] = k
if not self._rnums:
# init class dict on first use.
for rnum in range(32):
self._rnums[self.regname(rnum)] = rnum
self.triggers = dict()
self.pc = 0
self.nextpc = 0
self._regs = [None] * 32
self._regs[0] = 0 # zero reg.
self._csregs = [None] * 4096
self._curpriv = PRIV.MACHINE
self.mstatus = NamedBitFields(UIE=0, SIE=1, MIE=3, UPIE=4, SPIE=5, MPIE=7,
SPP=8, MPP=(12,11), FS=(14,13), XS=(16,15),
MPRV=17, SUM=18, MXR=19, TVM=20, TW=21, TSR=22)
bitnames = { chr(65+i):i for i in range(26) }
self.misa = NamedBitFields(**bitnames, MXL=(31,30))
ARCH_32 = 1
ARCH_64 = 2
ARCH_128 = 3
self.misa.MXL = ARCH_32
self.misa.C = 1 # C-extension
self.misa.E = 1 # RV32E base ISA
self.misa.I = 1 # RV32I base ISA
self.misa.M = 1 # have mul/div
self.misa.S = 1 # have supervisor mode
self.misa.U = 1 # have user mode
# misa.A - atomics
# misa.F - float
# misa.D - double
# reset values
self.mstatus.MIE = 0
self.mstatus.MPRV = 0
self.mcause = 0
self.mcycle = 0
self.medeleg = 0 # initially 0, optionally support delegate to priv=super mode.
self.mhartid = 0 # always 0, since we are emulating a single core cpu.
self.csr7c4 = 0 # Titan-M2 specific
self.pc = 0
def __getattr__(self, name):
"""
Convenience accessors, so I can access registers and CSRs by name.
"""
if name in self._csrnums:
return self.getcsreg(self._csrnums[name])
elif name in self._rnums:
return self.reg(self._rnums[name])
else:
print("unknown attr: %s" % name)
raise AttributeError()
def __setattr__(self, name, value):
# convenience setters
if name in self._csrnums:
self.setcsreg(self._csrnums[name], value)
elif name in self._rnums:
self.setreg(self._rnums[name], value)
else:
super().__setattr__(name, value)
def reg(self, num):
# access reg by number
if self._regs[num] is None:
print("read from uninitialized reg %s" % self.regname(num))
return self._regs[num] or 0
def setreg(self, num, value):
# set reg by number
if num==0:
print("WARN: write to zero register")
return
if self.args.trace:
print("change reg %s from %s -> %08x" % (self.regname(num), undef(self._regs[num]), value & 0xFFFFFFFF))
self._regs[num] = value & 0xFFFFFFFF
if t := self.triggers.get(num):
t(value & 0xFFFFFFFF)
def getcsreg(self, num):
# get csreg object by register number
if self._csregs[num] is None:
print("read from uninitialized csreg %s" % self.csregname(num))
return self._csregs[num] or 0
def csreg(self, num):
# get csreg numerical value by register number
r = self.getcsreg(num)
if isinstance(r,NamedBitFields):
return r.bits()
return r
def setcsreg(self, num, value):
# set csreg by number
r = self._csregs[num]
if isinstance(r, NamedBitFields):
if self.args.trace:
print("change csreg %s from %08x -> %08x" % (self.csregname(num), r.bits(), value))
r.setbits(value)
elif isinstance(value, NamedBitFields):
if self.args.trace:
print("change csreg %s to a bitfield" % (self.csregname(num)))
# this is where the register is converted to NamedBitFields
self._csregs[num] = value
else:
if self.args.trace:
print("change csreg %s from %s -> %08x" % (self.csregname(num), undef(r), value))
self._csregs[num] = value & 0xFFFFFFFF
def priv(self):
return self._curpriv
def setpriv(self, p):
print("change priv from %s to %s" % (PRIV.name(self._curpriv), PRIV.name(p)))
self._curpriv = p
def dump(self):
# dump current state
print("pc = %08x" % self.pc)
for i, r in enumerate(self._regs):
if (i%8)==0:
print("x%02d:" % i, end="")
print(" %s" % undef(r), end="")
if (i%8)==7:
match i//8:
case 0: print(" - zero, ra, sp, gp, tp, t0-t2")
case 1: print(" - s0, s1, a0-a5")
case 2: print(" - a6, a7, s2-s7")
case 3: print(" - s8-s11, t3-t6")
def translate_regname(self, name):
""" name to register number """
if m := re.match(r'^x(\d+)', name):
return int(m[1])
elif m := re.match(r'^t(\d+)', name):
t = int(m[1])
if t<3: return t+5
else: return t+25
elif m := re.match(r'^s(\d+)', name):
s = int(m[1])
if s<2: return s+8
else: return s+16
elif m := re.match(r'^a(\d+)', name):
a = int(m[1])
return a + 10
if name in self._rnums:
return self._rnums[name]
raise Exception("invalid regname")
def regname(self, num):
""" regnum to name """
if num < 0:
raise Exception("invalid regnum")
if num < len(self._regnames):
return self._regnames[num]
if num < 8: return f"t{num-5}"
if num < 10: return f"s{num-8}"
if num < 18: return f"a{num-10}"
if num < 28: return f"s{num-16}"
if num < 32: return f"t{num-25}"
raise Exception("invalid regnum")
def csregname(self, num):
""" regnum to name """
if num in self._csrnames:
return self._csrnames[num]
return f"csr{num:03x}"
def translate_csregname(self, name):
""" name to register number """
if name in self._csrnums:
return self._csrnums[name]
if m := re.match(r'csr([0-9a-f]+)', name):
return int(m[1], 16)
print(name)
raise Exception("unknown csregname")
class BreakException(Exception):
pass
class IllegalInstruction(Exception):
pass
# TODO
# a device plugin has:
# methods called by Memory:
# load(addr, size, value) -> value
# store(addr, size, value)
# methods called by CPU:
# tick(cpu)
class Memory:
"""
keep track of memory contents.
"""
def __init__(self, args):
# memory contains bytes
self.enablebreak = False
self.memory = dict()
self.args = args
self.excluderanges = []
self.pmp = None
self.f_0008 = None
self.n_7b0044 = 0
def loadvalue(self, addr, size, recursed=False):
""" load a 'size'-bit value from memory address 'addr' """
if not recursed and self.pmp:
if not self.pmp.mayread(addr, size):
raise InvalidMemoryAccess()
if size==8:
# default value is 0 for memory
res = self.memory.get(addr & 0xFFFFFFFF, None)
if res is None:
print("read uninitialized memory %08x" % addr)
res = random.randint(0,255) if self.args.randomize else 0
self.storevalue(addr, size, res, True)
else:
res = self.loadvalue(addr, size//2, True) | (self.loadvalue(addr+size//16, size//2, True)<<(size//2))
if not recursed and self.args.trace:
print("load %08x:%02d -> %0*x" % (addr, size, size//4, res))
return self.check_plugins_load(addr, size, res)
def storevalue(self, addr, size, value, recursed=False):
""" store a 'size'-bit value at memory address 'addr' """
if not recursed and self.args.trace:
print("store %08x:%02d := %0*x" % (addr, size, size//4, value))
if self.enablebreak and addr in self.args.breakstores:
print("break because store at %x" % addr)
raise BreakException()
if size==8:
self.memory[addr & 0xFFFFFFFF] = value&0xFF
else:
self.storevalue(addr, size//2, value, True)
self.storevalue(addr+size//16, size//2, value>>(size//2), True)
self.check_plugins_store(addr, size, value)
def hexdump(self, addr, data):
for i, b in enumerate(data):
if i%64 == 0:
print("%08x: " % (addr + i), end="")
print(" %02x" % b, end="")
if (i+1)%64 == 0:
print()
print()
def dump(self):
bufaddr = None
buf = []
for a, v in sorted(self.memory.items()):
if self.exclude(a):
continue
if bufaddr is None or bufaddr+len(buf) < a:
if buf:
self.hexdump(bufaddr, buf)
buf = []
bufaddr = a
buf.append(v)
if buf:
self.hexdump(bufaddr, buf)
def loadprogram(self, addr, pgm):
# pgm is the commandline specified byte sequence.
# encoded as a sequence of byte strings
o = addr
for opcbytes in pgm:
for i, b in enumerate(opcbytes):
self.storevalue(o+i, 8, b, True)
o += len(opcbytes)
def loadimage(self, addr, data):
"""
loads a raw binary image.
"""
for i, b in enumerate(data):
self.storevalue(addr+i, 8, b, True)
def addexclude(self, a, b):
self.excluderanges.append( (a, b) )
def exclude(self, a):
for r in self.excluderanges:
if r[0] <= a < r[1]:
return True
def check_plugins_load(self, addr, size, res):
if addr == 0x40630014 and size==32:
# increment timer
res += 15
self.storevalue(addr, size, res, True)
if addr in (0x40110004, 0x40110008) and res != 0xe89d48b7:
if self.f_0008 is None:
self.f_0008 = 2
elif self.f_0008:
self.f_0008 -= 1
else:
self.f_0008 = None
res = 0
self.storevalue(addr, size, res, True)
return res
def check_plugins_store(self, addr, size, value):
if addr == 0x40110010 and size==32 and value==0x00fb0043:
# 'flash' erase
self.storevalue(0x0017b000, 32, 0xFFFFFFFF, True)
self.storevalue(0x0017b004, 32, 0xFFFFFFFF, True)
self.n_7b0044 = 0
elif addr == 0x40110010 and size==32 and value==0x007b0044:
# 'flash' ?
if self.n_7b0044 == 0:
self.storevalue(0x0017b000, 32, 0x73614aff, True)
self.n_7b0044 = 1
else:
self.storevalue(0x0017b000, 32, 0x73614af0, True)
self.storevalue(0x0017b004, 32, 0x00000001, True)
elif addr == 0x40110010 and size==32 and value==0x00f98003:
# 'flash' erase
self.storevalue(0x000f9800, 32, 0xFFFFFFFF, True)
self.storevalue(0x000f9804, 32, 0xFFFFFFFF, True)
self.n_7b0044 = 0
elif addr == 0x40110010 and size==32 and value==0x00798004:
# 'flash' ?
if self.n_7b0044 == 0:
self.storevalue(0x000f9800, 32, 0x73614aff, True)
self.n_7b0044 = 1
else:
self.storevalue(0x000f9800, 32, 0x73614af0, True)
self.storevalue(0x000f9804, 32, 0x00000001, True)
elif addr == 0x40620010 and size==32 and (value & 9)==9:
# satisfy FUN_000a90f4
self.storevalue(addr, 32, 0, True)
elif addr == 0x40620000 and size==32 and value!=0:
# FUN_000a9202 wahts 0x40620004 to be != 0
self.storevalue(0x40620004, 32, 1, True)
elif addr == 0x40620000 and size==32 and value==0:
# FUN_0008254e, FUN_0008268c wahts 0x40620004 to be == 0
self.storevalue(0x40620004, 32, 0, True)
class NameResolver:
"""
resolve offsets to name[+delta], or name to an offset.
"""
def __init__(self):
# names is a list of tuples(ofs, name), and kept sorted by offset.
self.names = []
self.byname = dict()
def load(self, fn):
"""
load names from the given file.
The file has a simple format, where
each line starts with a name and address.
I use the output of the ghidra 'ctrl-t' symbol table, and copy-paste that to a file.
"""
x = dict()
for line in open(fn, "r"):
if m := re.match(r'^(\S+)\t(\w+)', line):
addr = int(m[2], 16)
name = m[1]
x[addr] = name
self.names.extend(x.items())
self.names = sorted(self.names)
self.byname = { n: o for o, n in self.names }
def getname(self, ofs):
if not self.names:
# names list is empty -> anything is unknown
return "unknown"
a = 0
b = len(self.names)
if ofs < self.names[a][0]:
# ofs is before first item -> unknown
return "unknown"
elif ofs > self.names[b-1][0]:
# ofs is after last item -> last + delta
return "%s+%x" % (self.names[b-1][1], ofs-self.names[b-1][0])
# otherwise do a binary search