다마고치 연구소 한국어판 소스 공개
This commit is contained in:
commit
db23855630
661 files changed
+503597
No files matched your search
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
# Build the core with the translator for the Unicorn test bed (m3main.c, memory as on the Paradise:
|
||||
# test/m3.ld). Objects one by one with the device's optimisation, so the linker script can place them.
|
||||
# sh test/build_m3.sh out.elf [flags], e.g. -DT18_JIT -DT18_JC_LINKED -DT18_PRAM_WR -DJH_BITS=8 -DJT_BITS=8 -DJ_HOT=8
|
||||
O=$1; shift
|
||||
cd "$(dirname "$0")/.." || exit 1
|
||||
D=$(mktemp -d)
|
||||
CF="-mcpu=cortex-m3 -mthumb -DPARADISE -ffreestanding -nostdlib -ffunction-sections -fdata-sections -Wall -Wno-unused-function"
|
||||
for f in test/m3main.c src/core/t18cpu.c src/core/t18soc.c src/core/t18jit.c; do
|
||||
n=$(basename $f .c); OPT=${OPT_ALL:--Os}; [ "$n" = t18cpu ] && OPT=-O2
|
||||
arm-none-eabi-gcc $CF $OPT "$@" -c $f -o $D/$n.o || exit 1
|
||||
done
|
||||
arm-none-eabi-gcc $CF -Wl,--gc-sections -T ${LD:-test/m3.ld} $D/m3main.o $D/t18cpu.o $D/t18soc.o $D/t18jit.o -lgcc -o $O && arm-none-eabi-size -A $O | head -8
|
||||
rm -rf $D
|
||||
@@ -0,0 +1,365 @@
|
||||
# T18 app (t18.bin, device program) in Unicorn with a simulated Paradise: hardware calls are caught,
|
||||
# the screen goes into a picture, the SysTick moves every RT instructions (96 MHz Cortex-M3).
|
||||
# python3 devt18.py <t18.elf> <paradise_image_with_t18> <ms> [KEYS="t:mask,..."] [SHOTS="t,t,..."] [OUT=dir]
|
||||
# Prints per second: emulated ms of the guest (100 % = real time).
|
||||
import sys, struct, subprocess, os
|
||||
from unicorn import *
|
||||
from unicorn.arm_const import *
|
||||
elf, img, total_ms = sys.argv[1], sys.argv[2], int(sys.argv[3])
|
||||
RT = int(os.environ.get('RT', '64000')) # instructions per millisecond (96 MHz, ~1.5 cycles each)
|
||||
out = os.environ.get('OUT', '.')
|
||||
syms = {}
|
||||
for l in subprocess.run(['arm-none-eabi-nm', elf], capture_output=True, text=True).stdout.splitlines():
|
||||
p = l.split()
|
||||
if len(p) == 3: syms[p[2]] = int(p[0], 16)
|
||||
fl = bytearray(open(img, 'rb').read())
|
||||
u = Uc(UC_ARCH_ARM, UC_MODE_THUMB | UC_MODE_MCLASS)
|
||||
# as on the Paradise: PRAM 64 KB (the stub copies 64 KB from 0xA0000), RAM at 0x20000000 only 4 KB,
|
||||
# flash window 0x10000000 = flash 0x11000.. (base 0x60011000)
|
||||
APPOFF = int(os.environ.get('APPOFF', '0xA0000'), 16) # test29: a program in the menu
|
||||
u.mem_map(0, 0x10000); u.mem_write(0, bytes(fl[APPOFF:APPOFF + 0x10000]))
|
||||
u.mem_map(0x18000000, 0x20000); u.mem_map(0x20000000, 0x2000 if os.environ.get('RAM8K') else 0x1000)
|
||||
u.mem_map(0x10000000, 0x1000000)
|
||||
# the flash window as measured on the device (1.6.6): 1 MB from the base register (0x4002F004), beyond that
|
||||
# something else (here zeros); NOT updated on flash writes (like a cache that keeps old lines). WIN16=1: old model
|
||||
def win_load(base):
|
||||
if os.environ.get('WIN16') == '1': u.mem_write(0x10000000, bytes(fl[0x11000:]) + bytes(0x11000)); return
|
||||
o = base - 0x60000000
|
||||
u.mem_write(0x10000000, bytes(fl[o:o + 0x100000]).ljust(0x100000, b'\xff') + bytes(0xF00000))
|
||||
WIN[0] = base
|
||||
WIN = [0x60011000]
|
||||
win_load(0x60011000)
|
||||
CACHE_READS = [0]
|
||||
UNC = [0]
|
||||
BLK = {}
|
||||
if os.environ.get('UNCOUNT'):
|
||||
def _unc(uc, acc, addr, size, val, ud):
|
||||
UNC[0] += 1; b = (addr - 0x60000000) >> 16; BLK[b] = BLK.get(b, 0) + 1
|
||||
u.hook_add(UC_HOOK_MEM_READ, _unc, begin=0x60000000, end=0x60FFFFFF)
|
||||
PRAM_BAD = [0]
|
||||
def pram_wr(uc, acc, addr, size, val, ud):
|
||||
pc = uc.reg_read(UC_ARM_REG_PC)
|
||||
if not (0x10000000 <= pc < 0x10100000 or 0x1800E600 <= pc < 0x18014400) or size not in (2, 4):
|
||||
PRAM_BAD[0] += 1
|
||||
if PRAM_BAD[0] < 5: print('PRAM written from pc', hex(pc), 'size', size, 'at', hex(addr))
|
||||
# PRAMQUIRK=1: the PRAM as found on the device (1.6.2): a halfword write fills the other half of its word
|
||||
# with the halfword written last (anywhere), not with what was there
|
||||
QL = [0]
|
||||
def pram_quirk(uc, acc, addr, size, val, ud):
|
||||
if size == 2:
|
||||
other = addr ^ 2
|
||||
uc.mem_write(other, struct.pack('<H', QL[0]))
|
||||
QL[0] = val & 0xFFFF
|
||||
elif size == 4: QL[0] = (val >> 16) & 0xFFFF
|
||||
if os.environ.get('PRAMQUIRK') == '1': u.hook_add(UC_HOOK_MEM_WRITE, pram_quirk, begin=0, end=0xFFFF)
|
||||
if os.environ.get('PRAMCHECK', '1') == '1': u.hook_add(UC_HOOK_MEM_WRITE, pram_wr, begin=0, end=0xFFFF)
|
||||
# Unicorn keeps old translations of code buffer addresses written by the program: drop them on each write
|
||||
JWLOG = [] if os.environ.get('JWLOG') else None
|
||||
if 't18_pram_w16' in syms and os.environ.get('PWHOOK', '1') == '1':
|
||||
def _pw(uc, ad, sz, ud):
|
||||
a = uc.reg_read(UC_ARM_REG_R0) & ~1
|
||||
uc.ctl_remove_cache(a & ~0x3FF, (a & ~0x3FF) + 0x800); _pw.n += 1
|
||||
if JWLOG is not None: JWLOG.append((a, uc.reg_read(UC_ARM_REG_R1) & 0xFFFF))
|
||||
_pw.n = 0; u.hook_add(UC_HOOK_CODE, _pw, begin=syms['t18_pram_w16'] & ~1, end=syms['t18_pram_w16'] & ~1)
|
||||
|
||||
u.mem_map(0x60000000, 0x1000000); u.mem_write(0x60000000, bytes(fl))
|
||||
u.mem_map(0x40000000, 0x100000)
|
||||
u.mem_write(0x4000B014, b'\x60\x00\x00\x00') # test6: UART1 line status: transmitter empty (T18_LINK sends hello frames)
|
||||
UTX = []
|
||||
def _utx(uc, acc, addr, size, val, ud): UTX.append(val & 0xFF)
|
||||
u.hook_add(UC_HOOK_MEM_WRITE, _utx, begin=0x4000B000, end=0x4000B000)
|
||||
def _xipw(uc, acc, addr, size, val, ud):
|
||||
if addr == 0x4002F004 and val != WIN[0]: win_load(val); uc.ctl_flush_tb()
|
||||
u.hook_add(UC_HOOK_MEM_WRITE, _xipw, begin=0x4002F004, end=0x4002F007); u.mem_map(0x45000000, 0x1000); u.mem_map(0xE000E000, 0x1000); u.mem_map(0xE0001000, 0x1000) # DWT (CYCCNT reads 0 here)
|
||||
fb = [[0] * 128 for _ in range(128)]
|
||||
rect = {'x0': 0, 'x1': 0, 'y': 0, 'x': 0}
|
||||
KS = []
|
||||
for p in os.environ.get('KEYS', '').split(','):
|
||||
if ':' in p: t, m = p.split(':'); KS.append((float(t), int(m)))
|
||||
SH = [float(x) for x in os.environ.get('SHOTS', '').split(',') if x]
|
||||
state = {'ms': 0, 'tone': [], 'flashw': 0, 'rows': 0}
|
||||
def keys():
|
||||
m = 0
|
||||
for t, v in KS:
|
||||
if state['ms'] / 1000.0 >= t: m = v
|
||||
return m
|
||||
def ret(uc, v=None):
|
||||
if v is not None: uc.reg_write(UC_ARM_REG_R0, v)
|
||||
uc.reg_write(UC_ARM_REG_PC, uc.reg_read(UC_ARM_REG_LR) | 1)
|
||||
def h_begin(uc):
|
||||
x0, y0, x1, y1 = (uc.reg_read(r) for r in (UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2, UC_ARM_REG_R3))
|
||||
rect.update(x0=x0, x1=x1, y=y0, x=x0); ret(uc)
|
||||
def h_row(uc):
|
||||
p, n = uc.reg_read(UC_ARM_REG_R0), uc.reg_read(UC_ARM_REG_R1)
|
||||
d = struct.unpack('<%dH' % n, uc.mem_read(p, 2 * n))
|
||||
for v in d:
|
||||
if rect['y'] < 128 and rect['x'] < 128: fb[rect['y']][rect['x']] = v
|
||||
rect['x'] += 1
|
||||
if rect['x'] >= rect['x1']: rect['x'] = rect['x0']; rect['y'] += 1
|
||||
state['rows'] += 1; ret(uc)
|
||||
def h_tone(uc): state['tone'].append((state['ms'], uc.reg_read(UC_ARM_REG_R0))); ret(uc)
|
||||
def h_btn(uc): ret(uc, keys())
|
||||
def h_upd(uc):
|
||||
ad, src = uc.reg_read(UC_ARM_REG_R0), uc.reg_read(UC_ARM_REG_R1)
|
||||
d = bytes(uc.mem_read(src, 0x1000)); a = ad & 0xFFF000
|
||||
if fl[a:a + 0x1000] == d: ret(uc, 0); return
|
||||
uc.mem_write(0x60000000 + a, d); fl[a:a + 0x1000] = d; state['flashw'] += 1; ret(uc, 1)
|
||||
if os.environ.get('FWLOG'): print('FW', state['ms'], hex(a))
|
||||
def h_erase(uc):
|
||||
a = uc.reg_read(UC_ARM_REG_R0) & 0xFFF000
|
||||
uc.mem_write(0x60000000 + a, b'\xff' * 0x1000); fl[a:a + 0x1000] = b'\xff' * 0x1000; state['flashw'] += 1; ret(uc)
|
||||
if os.environ.get('FWLOG'): print('FE', state['ms'], hex(a))
|
||||
def h_bl(uc):
|
||||
if os.environ.get('BLLOG'): print('BL', uc.reg_read(UC_ARM_REG_R0), 'at ms', state['ms'])
|
||||
ret(uc)
|
||||
def h_back(uc): state['back'] = 1; uc.emu_stop()
|
||||
def h_nop(uc): ret(uc)
|
||||
def h_fatal(uc): print('FATAL code', uc.reg_read(UC_ARM_REG_R0), 'info', hex(uc.reg_read(UC_ARM_REG_R1)), 'lr', hex(uc.reg_read(UC_ARM_REG_LR))); state['back'] = 1; uc.emu_stop()
|
||||
PANLOG = os.environ.get('PANLOG'); PAN = {'n': 0, 'last': None}
|
||||
def h_end(uc):
|
||||
# 1.6.13 test3: every picture the panel got (PANLOG=dir): what the user saw, frame by frame
|
||||
if PANLOG:
|
||||
d = struct.pack('<16384H', *[v for r in fb for v in r])
|
||||
if d != PAN['last']:
|
||||
PAN['last'] = d; open(os.path.join(PANLOG, 'p%05d_%07d.raw' % (PAN['n'], state['ms'])), 'wb').write(d); PAN['n'] += 1
|
||||
ret(uc)
|
||||
H = {'hw_px_begin': h_begin, 'hw_px_row': h_row, 'hw_px_end': h_end, 'hw_tone': h_tone, 'hw_buttons': h_btn,
|
||||
'flash_update4k': h_upd, 'flash_erase4k': h_erase, 'hw_back_to_paradise': h_back, 'hw_init': h_nop,
|
||||
'hw_backlight': h_bl, 'hw_bl_pwm_off': h_nop, 'hw_wdt_feed': h_nop}
|
||||
if not os.environ.get('FATALDRAW'): H['fatal'] = h_fatal
|
||||
for n, f in H.items():
|
||||
if n not in syms: print('no symbol', n); continue
|
||||
a = syms[n] & ~1
|
||||
if n == 'hw_init': # runs once from code that later becomes the translator's buffer: unhook after it
|
||||
HI = {}
|
||||
def h_init(uc, ad, sz, ud): ret(uc); uc.hook_del(HI['h'])
|
||||
HI['h'] = u.hook_add(UC_HOOK_CODE, h_init, begin=a, end=a)
|
||||
continue
|
||||
u.hook_add(UC_HOOK_CODE, (lambda f: lambda uc, ad, sz, ud: f(uc))(f), begin=a, end=a)
|
||||
def bad(uc, access, addr, size, value, ud):
|
||||
print('unmapped', access, hex(addr), 'pc', hex(uc.reg_read(UC_ARM_REG_PC))); return False
|
||||
u.hook_add(UC_HOOK_MEM_UNMAPPED, bad)
|
||||
def shot(name):
|
||||
from PIL import Image
|
||||
im = Image.new('RGB', (128, 128))
|
||||
for y in range(128):
|
||||
for x in range(128):
|
||||
v = fb[y][x]; im.putpixel((x, y), (((v >> 11) & 31) << 3, ((v >> 5) & 63) << 2, (v & 31) << 3))
|
||||
im.save(os.path.join(out, name))
|
||||
PROF = [float(x) * 1000 for x in os.environ.get('PROF', '').split(',') if x]
|
||||
import bisect, collections
|
||||
fs = []
|
||||
for l in subprocess.run(['arm-none-eabi-nm', '-S', elf], capture_output=True, text=True).stdout.splitlines():
|
||||
p = l.split()
|
||||
if len(p) == 4 and p[2] in 'tTwW': fs.append((int(p[0], 16), int(p[1], 16), p[3]))
|
||||
fs.sort(); fst = [x[0] for x in fs]; pc_cnt = collections.Counter(); prof_on = [False]
|
||||
jc = syms.get('JC', 0); jcl = syms.get('__bss_end', 0)
|
||||
def h_blk(uc, a, sz, ud):
|
||||
if not prof_on[0]: return
|
||||
if jc and jc <= a < jc + 0x8000: pc_cnt['<JIT code>'] += sz // 2; return
|
||||
i = bisect.bisect_right(fst, a) - 1
|
||||
pc_cnt[fs[i][2] if i >= 0 and a < fs[i][0] + fs[i][1] + 4 else '?%x' % a] += sz // 2
|
||||
if PROF: u.hook_add(UC_HOOK_BLOCK, h_blk)
|
||||
# SRAMFILL=seed: the SRAM full of leftovers as on the device (random bytes) before the start
|
||||
if os.environ.get('SRAMFILL'):
|
||||
import random; random.seed(int(os.environ['SRAMFILL'])); u.mem_write(0x18000000, bytes(random.getrandbits(8) for _ in range(0x20000)))
|
||||
# a Paradise clock in the SRAM, as the Paradise leaves it (PARA="2026-10-15 18:42:07", days/seconds base made up)
|
||||
if os.environ.get('PARA'):
|
||||
import datetime
|
||||
dt = datetime.datetime.strptime(os.environ['PARA'], '%Y-%m-%d %H:%M:%S'); cnt = int(os.environ.get('RTC0', '5000'))
|
||||
days = 650; tod = dt.hour * 3600 + dt.minute * 60 + dt.second; sek = (tod - cnt) % 86400
|
||||
o = 0x1BA4
|
||||
u.mem_write(0x18000000 + o - 0x10, struct.pack('<II', days, sek))
|
||||
u.mem_write(0x18000000 + o, struct.pack('<6H', dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second))
|
||||
EXEC = {}
|
||||
if os.environ.get('EXECLOG'):
|
||||
def _ex(uc, a, sz, ud):
|
||||
if a not in EXEC: EXEC[a] = bytes(uc.mem_read(a, sz))
|
||||
u.hook_add(UC_HOOK_CODE, _ex, begin=syms['__jc_start'], end=0xFFFF)
|
||||
# ALIGNCHK=1: LDRD/STRD/LDM/STM/PUSH/POP with an address that is not a multiple of 4 fault on the device
|
||||
# (UNALIGNED, even with the trap off); Unicorn does them. Checked on every such instruction executed.
|
||||
ALIGN_BAD = []
|
||||
if os.environ.get('ALIGNCHK'):
|
||||
import capstone
|
||||
_cs = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_THUMB | capstone.CS_MODE_MCLASS); _cs.detail = True
|
||||
_seen = {}
|
||||
def _al(uc, a, sz, ud):
|
||||
k = (a, bytes(uc.mem_read(a, sz)))
|
||||
ins = _seen.get(k)
|
||||
if ins is None:
|
||||
ins = next(_cs.disasm(k[1], a), None); _seen[k] = ins or False
|
||||
if not ins: return
|
||||
m = ins.mnemonic
|
||||
if not (m.startswith('ldrd') or m.startswith('strd') or m.startswith('ldm') or m.startswith('stm') or m.startswith('push') or m.startswith('pop')): return
|
||||
if m.startswith('push') or m.startswith('pop'): base = uc.reg_read(UC_ARM_REG_SP)
|
||||
else:
|
||||
op = [o for o in ins.operands if o.type == capstone.arm.ARM_OP_MEM]
|
||||
if op:
|
||||
base = uc.reg_read(ins.reg_name(op[0].mem.base) and getattr(__import__('unicorn.arm_const', fromlist=['x']), 'UC_ARM_REG_' + ins.reg_name(op[0].mem.base).upper().replace('SB', 'R9').replace('SL', 'R10').replace('FP', 'R11').replace('IP', 'R12'))) + op[0].mem.disp
|
||||
else:
|
||||
r = ins.operands[0].reg; nm = ins.reg_name(r).upper().replace('SB', 'R9').replace('SL', 'R10').replace('FP', 'R11').replace('IP', 'R12')
|
||||
base = uc.reg_read(getattr(__import__('unicorn.arm_const', fromlist=['x']), 'UC_ARM_REG_' + nm))
|
||||
if base & 3 and len(ALIGN_BAD) < 20:
|
||||
ALIGN_BAD.append((hex(a), ins.mnemonic, ins.op_str, hex(base))); print('UNALIGNED', hex(a), ins.mnemonic, ins.op_str, hex(base))
|
||||
u.hook_add(UC_HOOK_CODE, _al, begin=0, end=0xFFFF)
|
||||
u.hook_add(UC_HOOK_CODE, _al, begin=0x10000000, end=0x10100000)
|
||||
sp, rst = struct.unpack('<II', bytes(u.mem_read(0, 8)))
|
||||
u.reg_write(UC_ARM_REG_SP, sp)
|
||||
pc = rst; gms = syms['g_ms']; rtc0 = int(os.environ.get('RTC0', '5000'))
|
||||
st_sym = syms['g_t18st']
|
||||
si = 0; last = (0, 0)
|
||||
IRQ = os.environ.get('IRQ') == '1'
|
||||
import random as _r; IRQRND = _r.Random(int(os.environ.get('IRQSEED', '1')))
|
||||
IRQ_N = [0]
|
||||
if IRQ: u.mem_map(0x30000000, 0x1000); u.mem_write(0x30000000, b'\xfe\xe7' * 8) # return point of the handler (instead of EXC_RETURN)
|
||||
def systick_on(): return struct.unpack('<I', bytes(u.mem_read(0xE000E010, 4)))[0] & 2
|
||||
def irq_enter(pc):
|
||||
sp = u.reg_read(UC_ARM_REG_SP); xpsr = u.reg_read(UC_ARM_REG_XPSR)
|
||||
pad = sp & 4
|
||||
sp = (sp - 32 - pad) & 0xFFFFFFFF
|
||||
regs = [u.reg_read(r) for r in (UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2, UC_ARM_REG_R3, UC_ARM_REG_R12, UC_ARM_REG_LR)]
|
||||
u.mem_write(sp, struct.pack('<8I', *regs, pc & ~1, (xpsr | 0x01000000 | (0x200 if pad else 0)) & 0xFFFFFFFF))
|
||||
u.reg_write(UC_ARM_REG_SP, sp); u.reg_write(UC_ARM_REG_LR, 0x30000001)
|
||||
u.reg_write(UC_ARM_REG_PC, syms['SysTick_Handler'] | 1); IRQ_N[0] += 1
|
||||
if os.environ.get('IRQDBG') and IRQ_N[0] < 6: print('irq at', hex(pc), 'sp', hex(sp))
|
||||
def irq_return():
|
||||
sp = u.reg_read(UC_ARM_REG_SP); f = struct.unpack('<8I', bytes(u.mem_read(sp, 32)))
|
||||
for r, v in zip((UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2, UC_ARM_REG_R3, UC_ARM_REG_R12, UC_ARM_REG_LR), f[:6]): u.reg_write(r, v)
|
||||
sp += 32 + (4 if f[7] & 0x200 else 0)
|
||||
u.reg_write(UC_ARM_REG_SP, sp); u.reg_write(UC_ARM_REG_XPSR_NZCVQ, f[7] & 0xF8000000); u.reg_write(UC_ARM_REG_PC, f[6] | 1)
|
||||
if os.environ.get('IRQDBG') and IRQ_N[0] < 6: print('ret to', hex(f[6]), 'sp', hex(sp), 'gms', struct.unpack('<I', bytes(u.mem_read(gms, 4)))[0])
|
||||
# 1.6.9 test26 CLK_ECO: the AHB prescaler at 0x45000010 slows the core: RT >> sh instructions per ms
|
||||
state['sh'] = 0; state['shms'] = [0, 0, 0, 0]
|
||||
def _ahb(uc, acc, a, sz, v, ud):
|
||||
state['sh'] = v & 7
|
||||
if os.environ.get('ECOLOG'): print('AHB', v & 7, 'at ms', state['ms'])
|
||||
u.hook_add(UC_HOOK_MEM_WRITE, _ahb, begin=0x45000010, end=0x45000013)
|
||||
# 1.6.13 test1 T18_PW (as devt7.py): system clock source (0x4500000C: 0 IHRC 12 MHz, 4 PLL; status in bits 6:4), PLL
|
||||
# locked, RTC on with 1 s, deep sleep (PMU_CTRL bit 1, then WFI): the time runs on to the next RTC second or a key change
|
||||
u.mem_write(0x4500000C, struct.pack('<I', 0x44)); u.mem_write(0x45000008, struct.pack('<I', 0x55)); u.mem_write(0x45000200, struct.pack('<I', 0x80))
|
||||
state['ihrc'] = 0; state['pw'] = {'full': 0, 'ihrc': 0, 'sleep': 0}
|
||||
def _clk(uc, acc, a, sz, v, ud):
|
||||
state['ihrc'] = (v & 7) == 0
|
||||
uc.mem_write(0x4500000C, struct.pack('<I', (v & 7) | ((v & 7) << 4)))
|
||||
if os.environ.get('ECOLOG'): print('CLKSRC', v & 7, 'at ms', state['ms'])
|
||||
u.hook_add(UC_HOOK_MEM_WRITE, _clk, begin=0x4500000C, end=0x4500000F)
|
||||
def _clkr(uc, acc, a, sz, v, ud): # 1.7.2: the status bits follow the source (the write hook runs before the write itself)
|
||||
c = struct.unpack('<I', bytes(uc.mem_read(0x4500000C, 4)))[0]
|
||||
if ((c >> 4) & 7) != (c & 7): uc.mem_write(0x4500000C, struct.pack('<I', (c & 7) | ((c & 7) << 4)))
|
||||
u.hook_add(UC_HOOK_MEM_READ, _clkr, begin=0x4500000C, end=0x4500000F)
|
||||
def _pmu(uc, acc, a, sz, v, ud):
|
||||
if v & 2 and not state.get('dsleep'):
|
||||
t = state['ms']
|
||||
while True:
|
||||
t += 1
|
||||
if t % 1000 == 0 or t >= total_ms or any(t / 1000.0 >= kt > state['ms'] / 1000.0 for kt, _ in KS): break
|
||||
state['dsleep'] = t
|
||||
if t % 1000 == 0 and 'g_pw_rtcw' in syms: uc.mem_write(syms['g_pw_rtcw'], b'\x01') # the RTC interrupt ran
|
||||
if int(os.environ.get('RTCLAG', '0')):
|
||||
# 1.6.13 test3: the counter shows the new second only a few reads after the wake (32 kHz domain)
|
||||
state['rtc_new'] = rtc0 + t // 1000; state['rtclag'] = int(os.environ['RTCLAG'])
|
||||
else: uc.mem_write(0x45000304, struct.pack('<I', rtc0 + t // 1000))
|
||||
u.hook_add(UC_HOOK_MEM_WRITE, _pmu, begin=0x45000300, end=0x45000303)
|
||||
def _rtcrd(uc, acc, a, sz, v, ud):
|
||||
if 'rtc_new' in state:
|
||||
if state['rtclag'] > 0: state['rtclag'] -= 1
|
||||
else: uc.mem_write(0x45000304, struct.pack('<I', state.pop('rtc_new')))
|
||||
u.hook_add(UC_HOOK_MEM_READ, _rtcrd, begin=0x45000304, end=0x45000307)
|
||||
RTCLAGMS = int(os.environ.get('RTCLAGMS', '0'))
|
||||
if RTCLAGMS:
|
||||
# 1.6.13 test3: the counter shows a new second only RTCLAGMS ms after it began (the RTC interrupt comes on time)
|
||||
def _rtcms(uc, acc, a, sz, v, ud):
|
||||
eff = state.get('dsleep') or state['ms']
|
||||
uc.mem_write(0x45000304, struct.pack('<I', rtc0 + max(eff - RTCLAGMS, 0) // 1000))
|
||||
u.hook_add(UC_HOOK_MEM_READ, _rtcms, begin=0x45000304, end=0x45000307)
|
||||
if os.environ.get('OSCDBG'):
|
||||
_oc = collections.Counter()
|
||||
def _osc(uc, acc, a, sz, v, ud):
|
||||
if state['ms'] >= int(os.environ['OSCDBG']): _oc[(hex(a), struct.unpack('<I', bytes(uc.mem_read(a & ~3, 4)))[0])] += 1
|
||||
u.hook_add(UC_HOOK_MEM_READ, _osc, begin=0x45000000, end=0x45000013)
|
||||
import atexit; atexit.register(lambda: print('OSC reads', _oc.most_common(10)))
|
||||
while state['ms'] < total_ms and 'back' not in state:
|
||||
u.mem_write(0x45000304, struct.pack('<I', rtc0 + state['ms'] // 1000))
|
||||
try:
|
||||
if os.environ.get('FLUSHTB'): u.ctl_flush_tb()
|
||||
if IRQ:
|
||||
# the SysTick as a real exception: frame on the stack, handler, return through EXC_RETURN
|
||||
left = RT + IRQRND.randrange(-RT // 2, RT // 2)
|
||||
while left > 0:
|
||||
u.emu_start(pc | 1, 0x30000000, count=left)
|
||||
pc = u.reg_read(UC_ARM_REG_PC) & ~1
|
||||
if pc == 0x30000000: irq_return(); pc = u.reg_read(UC_ARM_REG_PC); left -= 100; continue
|
||||
break
|
||||
if u.reg_read(UC_ARM_REG_PRIMASK) & 1 or not systick_on(): state['pend'] = 1
|
||||
else: irq_enter(pc); pc = u.reg_read(UC_ARM_REG_PC)
|
||||
else:
|
||||
_sh = int(os.environ.get('IHRCSH', '3')) if state['ihrc'] else state['sh']
|
||||
u.emu_start(pc | 1, 0xFFFFFFF0, count=max(1, RT >> _sh)); state['shms'][min(_sh, 3)] += 1
|
||||
state['pw']['ihrc' if state['ihrc'] else 'full'] += 1
|
||||
except UcError as ex:
|
||||
print('error', ex, hex(u.reg_read(UC_ARM_REG_PC))); break
|
||||
pc = u.reg_read(UC_ARM_REG_PC)
|
||||
_ds = state.pop('dsleep', 0)
|
||||
if _ds:
|
||||
n = _ds - state['ms']; state['ms'] = _ds; state['pw']['sleep'] += n
|
||||
if os.environ.get('DBGSLEEP'): print('slept', n, 'to ms', state['ms'])
|
||||
if state['ms'] % 1000 == 0:
|
||||
st = struct.unpack('<8I', bytes(u.mem_read(st_sym, 32)))
|
||||
print('%4d s: emulated %4d ms (deep sleep)' % (state['ms'] // 1000, st[0] - last[0]), flush=True); last = st
|
||||
continue
|
||||
state['ms'] += 1
|
||||
_k = keys(); u.mem_write(0x40018000, struct.pack('<I', 0xFFFFFFFF & ~(((_k & 1) << 9) | ((_k & 2) << 10) | ((_k & 4) << 8) | ((_k & 8) << 5)))) # 1.7.2: GPIO0 pins (active low) for the key latch
|
||||
if os.environ.get('TRFROM') and int(os.environ['TRFROM']) <= state['ms'] <= int(os.environ['TRTO']) and state['ms'] % int(os.environ.get('TRSTEP','25')) == 0:
|
||||
_st = struct.unpack('<8I', bytes(u.mem_read(st_sym, 32))); print('TR', state['ms'], 'emu', _st[0], 'drop', _st[1], 'k', hex(_st[4]), hex(_st[5]), hex(_st[6]), _st[7], 'lag', state['ms'] - _st[0] - _st[1], 'sh', state['sh'], 'ihrc', state['ihrc'])
|
||||
if not IRQ:
|
||||
v = struct.unpack('<I', u.mem_read(gms, 4))[0]; u.mem_write(gms, struct.pack('<I', v + 1))
|
||||
if 'g_ms_raw' in syms: _r = syms['g_ms_raw']; u.mem_write(_r, struct.pack('<I', struct.unpack('<I', u.mem_read(_r, 4))[0] + 1))
|
||||
if os.environ.get('JSTAT') and state['ms'] % int(os.environ['JSTAT']) == 0 and state['ms'] <= 400:
|
||||
js = struct.unpack('<8I', bytes(u.mem_read(syms['t18_jit_stat'], 32))); jb = struct.unpack('<I', bytes(u.mem_read(syms['t18_jit_bytes'], 4)))[0]
|
||||
print('ms', state['ms'], 'blocks', js[0], 'flushes', js[3], 'bytes', jb, 'gpc', hex(struct.unpack('<I', bytes(u.mem_read(syms['g_tg'] + 60, 4)))[0]))
|
||||
if os.environ.get('GPC'):
|
||||
gpc = struct.unpack('<I', bytes(u.mem_read(syms['g_tg'] + 60, 4)))[0]
|
||||
lo, hi = [int(x, 16) for x in os.environ['GPC'].split('-')]
|
||||
if lo <= gpc < hi and state.get('gpcn', 0) < 20: state['gpcn'] = state.get('gpcn', 0) + 1; print('guest pc', hex(gpc), 'at ms', state['ms'], 'stage', struct.unpack('<I', bytes(u.mem_read(syms['g_stage'], 4)))[0])
|
||||
if si < len(SH) and state['ms'] >= SH[si] * 1000: shot('shot_%02d.png' % si); si += 1
|
||||
if PROF: prof_on[0] = PROF[0] <= state['ms'] < PROF[1]
|
||||
if os.environ.get('HISTRESET') and state['ms'] == int(os.environ['HISTRESET']): u.mem_write(0x20001000, bytes(256)) # test5: slow access histogram from here
|
||||
if state['ms'] % 1000 == 0:
|
||||
st = struct.unpack('<8I', bytes(u.mem_read(st_sym, 32)))
|
||||
if 'g_pres_n' in syms: pn = struct.unpack('<I', bytes(u.mem_read(syms['g_pres_n'], 4)))[0]; print(' pictures', pn - state.get('pn', 0)); state['pn'] = pn
|
||||
print('%4d s: emulated %4d ms, dropped %5d ms, flash writes %d, rows %d%s' % (state['ms'] // 1000, st[0] - last[0], st[1], state['flashw'], state['rows'], ', uncached reads %d' % UNC[0] if os.environ.get('UNCOUNT') else ''), flush=True); UNC[0] = 0
|
||||
for _s in os.environ.get('SYMSEC', '').split(','): # 1.7.4: 32-bit symbols each second
|
||||
if _s in syms: print(' %s %d' % (_s, struct.unpack('<I', bytes(u.mem_read(syms[_s], 4)))[0]))
|
||||
last = st
|
||||
st = struct.unpack('<8I', bytes(u.mem_read(st_sym, 32)))
|
||||
print('emulated ms', st[0], 'dropped ms', st[1], 'flash', st[2], 'map', st[3], 'lost', st[5])
|
||||
if '__stack_bottom' in syms and '__stack_top' in syms:
|
||||
lo, hi = syms['__stack_bottom'], syms['__stack_top']
|
||||
m = bytes(u.mem_read(lo + 4, hi - lo - 4)); k = next((i for i in range(0, len(m), 4) if m[i:i + 4] != b'\0\0\0\0'), len(m))
|
||||
print('stack used', hi - lo - 4 - k, 'of', hi - lo)
|
||||
if 'g_pool_n' in syms: print('hole pages used', struct.unpack('<I', bytes(u.mem_read(syms['g_pool_n'], 4)))[0])
|
||||
if 'g_para' in syms:
|
||||
import datetime
|
||||
v = struct.unpack('<I', bytes(u.mem_read(syms['g_para'], 4)))[0]
|
||||
print('Paradise clock found:', datetime.datetime.utcfromtimestamp(v) if v else 'no')
|
||||
print('interrupts', IRQ_N[0])
|
||||
if 'g_ncached' in syms: print('blocks through the cache', struct.unpack('<I', bytes(u.mem_read(syms['g_ncached'], 4)))[0])
|
||||
if os.environ.get('ALIGNCHK'): print('unaligned double/multiple accesses', len(ALIGN_BAD))
|
||||
print('ms', state['ms'], 'tones', len(state['tone']), 'back' if 'back' in state else '', 'pc', hex(pc), 'bad PRAM writes', PRAM_BAD[0])
|
||||
if PROF:
|
||||
tot = sum(pc_cnt.values())
|
||||
for k, v in pc_cnt.most_common(int(os.environ.get('PROFN','25'))): print(' %-24s %5.1f%%' % (k, 100.0 * v / tot))
|
||||
print('ms per clock step (96, 48, 24, 12 MHz):', state['shms'])
|
||||
print('power ms: full', state['pw']['full'], 'ihrc', state['pw']['ihrc'], 'deep sleep', state['pw']['sleep'])
|
||||
open(os.path.join(out, 'flash_after.bin'), 'wb').write(fl)
|
||||
if JWLOG is not None:
|
||||
open(os.environ['JWLOG'], 'w').write('\n'.join('%x %04x' % w for w in JWLOG))
|
||||
if EXEC:
|
||||
import pickle; pickle.dump(EXEC, open(os.environ['EXECLOG'], 'wb'))
|
||||
if os.environ.get('BLKOUT'): open(os.environ['BLKOUT'], 'w').write('\n'.join('%x %d' % kv for kv in sorted(BLK.items(), key=lambda kv: -kv[1])))
|
||||
if os.environ.get('PEEK'):
|
||||
for _p in os.environ['PEEK'].split(','):
|
||||
_a, _n = _p.split(':'); print('PEEK', _a, bytes(u.mem_read(int(_a, 16), int(_n))).hex())
|
||||
if os.environ.get('DUMPPRAM'): open(os.environ['DUMPPRAM'], 'wb').write(bytes(u.mem_read(0, 0x10000)))
|
||||
shot('shot_end.png')
|
||||
if os.environ.get('UARTLOG'): print('uart tx', len(UTX), 'bytes:', ' '.join('%02x' % b for b in UTX[:80]))
|
||||
@@ -0,0 +1,23 @@
|
||||
/* Memory as on the Paradise (src/app/link.ld): hot code and the code buffer in the PRAM, the rest of
|
||||
* the code in the flash window, stack and data in the SRAM hole, the rest of the SRAM is the guest's. */
|
||||
ENTRY(Reset_Handler)
|
||||
MEMORY { PRAM (rwx) : ORIGIN = 0x00000000, LENGTH = 0x10000
|
||||
XIP (rx) : ORIGIN = 0x100DF000, LENGTH = 0x10000
|
||||
HOLE (rw) : ORIGIN = 0x1800E600, LENGTH = 0x5E00 }
|
||||
SECTIONS {
|
||||
.xip : {
|
||||
*(.xiptext*)
|
||||
*t18jit.o(.text.translate_thumb .text.translate_arm .text.t_decode .text.a_decode .text.emit_* .text.block_begin .text.block_end* .text.modimm_up .text.t2_* .text.get_reg .text.set_reg .text.flush)
|
||||
*t18soc.o(.text.tg18_init .text.soc_reset .text.tg18_set_time .text.tg18_get_time)
|
||||
. = ALIGN(4);
|
||||
} > XIP
|
||||
.text : { KEEP(*(.vectors)) *(.text*) *(.rodata*) . = ALIGN(4); } > PRAM
|
||||
.stack (NOLOAD) : { . += 0x800; __stack_top = .; } > HOLE
|
||||
.data : { __data_start = .; *(.data*) . = ALIGN(4); __data_end = .; } > HOLE AT > PRAM
|
||||
__data_load = LOADADDR(.data);
|
||||
__jc_start = ALIGN(__data_load + SIZEOF(.data), 4);
|
||||
__jt_start = 0x10000 - 0x800;
|
||||
__jc_end = __jt_start;
|
||||
.bss (NOLOAD) : { __bss_start = .; *(.bss*) *(COMMON) . = ALIGN(4); __bss_end = .; } > HOLE
|
||||
/DISCARD/ : { *(.comment) *(.ARM.*) *(.note*) }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
ENTRY(Reset_Handler)
|
||||
MEMORY { PRAM (rwx) : ORIGIN = 0x00000000, LENGTH = 0x40000
|
||||
DATA (rw) : ORIGIN = 0x20000000, LENGTH = 0x10000 }
|
||||
SECTIONS {
|
||||
.text : { KEEP(*(.vectors)) *(.text*) *(.rodata*) . = ALIGN(4); } > PRAM
|
||||
.data : { *(.data*) . = ALIGN(4); } > PRAM
|
||||
.jitglue : { . = ALIGN(4); __glue_start = .; *(.jitglue) . = ALIGN(4); __glue_end = .; } > PRAM
|
||||
__glue_load = LOADADDR(.jitglue);
|
||||
.jitbuf (NOLOAD) : { . = ALIGN(4); *(.jitbuf) } > PRAM
|
||||
.bss (NOLOAD) : { __bss_start = .; *(.bss*) *(COMMON) . = ALIGN(4); __bss_end = .; } > DATA
|
||||
/DISCARD/ : { *(.comment) *(.ARM.*) *(.note*) }
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
/* T18 core on a Cortex-M3 in Unicorn (test bed for the translator).
|
||||
* Memory as on the Paradise: guest SRAM at 0x18000000, guest flash at 0x60000000 (uncached XIP).
|
||||
* Commands come through g_mb: 1 run <us>, 2 buttons <mask>, 3 hash, 4 picture, 5 set time. */
|
||||
#include "../src/core/t18soc.h"
|
||||
#include <string.h>
|
||||
#define FW ((uint8_t *)0x60000000u)
|
||||
uint8_t t18_flash_rd(uint32_t a) { return FW[a & 0x7FFFFF]; }
|
||||
#ifdef T18_FF_FAST
|
||||
extern uint8_t t18_fff[128]; /* a written block is no longer empty (the device maps a spare block then) */
|
||||
void t18_flash_prog(uint32_t a, uint8_t b) { FW[a & 0x7FFFFF] &= b; if (b != 0xFF) t18_fff[(a >> 16) & 127] = 0; }
|
||||
#else
|
||||
void t18_flash_prog(uint32_t a, uint8_t b) { FW[a & 0x7FFFFF] &= b; }
|
||||
#endif
|
||||
void t18_flash_erase(uint32_t a, uint32_t size) { memset(FW + (a & 0x7FFFFF), 0xFF, size); }
|
||||
static uint32_t g_t[3600 / 4];
|
||||
#ifndef NPOOL
|
||||
#define NPOOL 12
|
||||
#endif
|
||||
static uint8_t g_pool[NPOOL][T18_HOLE_PG] __attribute__((aligned(4))); static int g_pool_n;
|
||||
static uint8_t *hole_new(void) { if (g_pool_n >= NPOOL) return 0; uint8_t *p = g_pool[g_pool_n++]; memset(p, 0, T18_HOLE_PG); return p; }
|
||||
static void hole_free(void) { g_pool_n = 0; }
|
||||
#ifdef T18_PRAM_WR
|
||||
/* as on the Paradise: from the flash window, interrupts off (m3run.py checks where PRAM writes come from) */
|
||||
__attribute__((section(".xiptext"), noinline, used)) void t18_pram_w16(uint16_t *p, uint32_t v)
|
||||
{
|
||||
uint32_t pm;
|
||||
__asm__ volatile("mrs %0, primask\n cpsid i" : "=r"(pm) :: "memory");
|
||||
*(volatile uint16_t *)p = (uint16_t)v;
|
||||
__asm__ volatile("dsb\n isb\n msr primask, %0" :: "r"(pm) : "memory");
|
||||
}
|
||||
#endif
|
||||
volatile uint32_t g_mb[16];
|
||||
uint32_t g_pic_src, g_pic_len, g_pics;
|
||||
static void pres(void *u, uint32_t src, uint32_t len) { (void)u; g_pic_src = src; g_pic_len = len; g_pics++; }
|
||||
/* wait for the next command: g_mb[9] = sequence from the driver, g_mb[8] counts idle turns (4 instructions each) */
|
||||
__attribute__((noinline, naked)) void mb_spin(void) {
|
||||
__asm__ volatile("1: ldr r1, [r0, #36]\n cmp r1, r2\n add r3, r3, #1\n beq 1b\n str r3, [r0, #32]\n bx lr\n");
|
||||
}
|
||||
static uint32_t g_seq;
|
||||
static void mb_wait(void) {
|
||||
register volatile uint32_t *r0 __asm__("r0") = g_mb; register uint32_t r2 __asm__("r2") = g_seq; register uint32_t r3 __asm__("r3") = 0;
|
||||
__asm__ volatile("bl mb_spin" : "+r"(r0), "+r"(r2), "+r"(r3) : : "r1", "lr", "memory", "cc");
|
||||
g_seq = g_mb[9];
|
||||
}
|
||||
#ifdef T18_CLOCK_AFTER
|
||||
/* test: like the app, the time given with "time" is put back when the firmware loads its RTC */
|
||||
static int g_tm[6]; uint32_t g_cb_n; static int g_pend; /* like the app: 0.5 s later (the firmware sets its day counter after the RTC) */
|
||||
static void clock_after(void *t) { (void)t; g_cb_n++; if (g_tm[0]) g_pend = 1; }
|
||||
#endif
|
||||
static uint32_t fnv(const uint8_t *p, uint32_t n, uint32_t h) { for (uint32_t i = 0; i < n; i++) h = (h ^ p[i]) * 16777619u; return h; }
|
||||
int main(void)
|
||||
{
|
||||
tg18_t *T = (tg18_t *)g_t;
|
||||
if (tg18_struct_size() > sizeof g_t) { g_mb[15] = tg18_struct_size(); for (;;) mb_wait(); }
|
||||
t18_sram = (uint8_t *)0x18000000u; t18_hole_new = hole_new; t18_hole_free = hole_free;
|
||||
for (int i = 0; i < 128; i++) t18_fblk[i] = FW + (i << 16);
|
||||
#if defined(T18_FF_FAST) || defined(T18_EMPTY_SLOW)
|
||||
{ /* as on the device: empty blocks have no pointer (FF_FAST: the translator answers 0xFF) */
|
||||
for (int i = 0; i < 128; i++) { int e = 1; for (uint32_t k = 0; k < 0x10000u && e; k += 4) if (*(const uint32_t *)(FW + (i << 16) + k) != 0xFFFFFFFFu) e = 0;
|
||||
if (e) { t18_fblk[i] = 0;
|
||||
#ifdef T18_FF_FAST
|
||||
{ extern uint8_t t18_fff[128]; t18_fff[i] = 1; }
|
||||
#endif
|
||||
} } }
|
||||
#endif
|
||||
tg18_init(T, FW, 0x800000);
|
||||
tg18_set_present(T, pres, 0);
|
||||
for (;;) {
|
||||
mb_wait();
|
||||
#ifdef T18_HLE_FILL
|
||||
if (t18_hle_pc == 1u && t18_hle_find()) t18_jit_reset();
|
||||
#endif
|
||||
switch (g_mb[0]) {
|
||||
case 1:
|
||||
#ifdef T18_CLOCK_AFTER
|
||||
for (uint32_t us = g_mb[1]; us; ) { uint32_t k = us > 50000u ? 50000u : us; tg18_run_us(T, k); us -= k;
|
||||
if (g_pend && ++g_pend > 11) { g_pend = 0; tg18_set_time(T, g_tm[0], g_tm[1], g_tm[2], g_tm[3], g_tm[4], g_tm[5]); } }
|
||||
#else
|
||||
tg18_run_us(T, g_mb[1]);
|
||||
#endif
|
||||
break;
|
||||
case 2: tg18_set_buttons(T, (int)g_mb[1]); break;
|
||||
case 4: {
|
||||
#ifdef T18_JIT
|
||||
extern uint32_t t18_jit_stat[8], t18_interp[2];
|
||||
for (int i = 0; i < 6; i++) g_mb[1 + i] = t18_jit_stat[i];
|
||||
g_mb[11] = t18_jit_stat[6]; { extern uint32_t t18_jit_used(void); g_mb[12] = t18_jit_used(); }
|
||||
g_mb[13] = t18_jit_stat[7]; { extern uint32_t t18_jit_bytes; g_mb[14] = t18_jit_bytes; }
|
||||
g_mb[7] = t18_interp[0]; g_mb[10] = t18_interp[1];
|
||||
#endif
|
||||
break; }
|
||||
case 3: { arm7_t *c = tg18_cpu(T); g_mb[2] = (uint32_t)c->cycles; g_mb[3] = (uint32_t)(c->cycles >> 32); g_mb[4] = c->r[15]; { uint32_t h = 2166136261u; for (uint32_t o = 0; o < T18_SRAM_SIZE; o += 256) h = fnv(t18_sram_rp(o), 256, h); g_mb[5] = h; } g_mb[7] = (uint32_t)t18_oom | (uint32_t)g_pool_n << 8; break; }
|
||||
#ifdef T18_JIT_VERIFY
|
||||
case 6: { extern int t18_verify_on; t18_verify_on = 1; break; }
|
||||
#endif
|
||||
case 7: { /* load state + SRAM put by the driver at 0x61000000 - 0x40000 (g_mb[1] = state length) */
|
||||
const uint8_t *b = (const uint8_t *)0x60FC0000u; uint32_t n = g_mb[1];
|
||||
g_mb[2] = (uint32_t)tg18_load_state(T, b, n);
|
||||
for (uint32_t q = 0; q < T18_SRAM_SIZE; q += 4) t18_sram_wr(q, *(const uint32_t *)(b + n + q), 4);
|
||||
break; }
|
||||
case 5: tg18_set_time(T, (int)g_mb[1], (int)g_mb[2], (int)g_mb[3], (int)g_mb[4], (int)g_mb[5], (int)g_mb[6]);
|
||||
#ifdef T18_CLOCK_AFTER
|
||||
for (int i = 0; i < 6; i++) g_tm[i] = (int)g_mb[1 + i];
|
||||
tg18_set_rtc_cb(T, clock_after);
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
if (g_mb[0] != 4) { g_mb[1] = g_pic_src; g_mb[6] = g_pics; }
|
||||
}
|
||||
}
|
||||
#ifdef T18_JIT_VERIFY
|
||||
/* translation differs from the interpreter: report and stop (g_mb[0] = 0xBAD) */
|
||||
volatile uint32_t g_vf[80];
|
||||
void t18_verify_fail(uint32_t key, const arm7_t *b, const arm7_t *j, const arm7_t *r)
|
||||
{
|
||||
g_vf[0] = 0xBAD; g_vf[1] = key;
|
||||
for (int i = 0; i < 16; i++) { g_vf[2 + i] = b->r[i]; g_vf[18 + i] = j->r[i]; g_vf[34 + i] = r->r[i]; }
|
||||
g_vf[50] = b->cpsr; g_vf[51] = j->cpsr; g_vf[52] = r->cpsr;
|
||||
g_vf[53] = (uint32_t)j->cycles; g_vf[54] = (uint32_t)r->cycles; g_vf[55] = (uint32_t)b->cycles;
|
||||
for (;;) __asm__ volatile("bkpt #1");
|
||||
}
|
||||
#endif
|
||||
/* minimal runtime */
|
||||
void *memset(void *d, int c, unsigned n) { uint8_t *p = d; while (n && ((uintptr_t)p & 3)) { *p++ = (uint8_t)c; n--; } uint32_t w = (uint8_t)c * 0x01010101u; while (n >= 4) { *(uint32_t *)p = w; p += 4; n -= 4; } while (n--) *p++ = (uint8_t)c; return d; }
|
||||
void *memcpy(void *d, const void *s, unsigned n) { uint8_t *p = d; const uint8_t *q = s; if (!(((uintptr_t)p | (uintptr_t)q) & 3)) while (n >= 16) { uint32_t a = ((const uint32_t *)q)[0], b = ((const uint32_t *)q)[1], c = ((const uint32_t *)q)[2], e = ((const uint32_t *)q)[3]; ((uint32_t *)p)[0] = a; ((uint32_t *)p)[1] = b; ((uint32_t *)p)[2] = c; ((uint32_t *)p)[3] = e; p += 16; q += 16; n -= 16; } while (n--) *p++ = *q++; return d; }
|
||||
void *memmove(void *d, const void *s, unsigned n) { uint8_t *p = d; const uint8_t *q = s; if (p < q) while (n--) *p++ = *q++; else { p += n; q += n; while (n--) *--p = *--q; } return d; }
|
||||
int memcmp(const void *a, const void *b, unsigned n) { const uint8_t *p = a, *q = b; if (!(((uintptr_t)p | (uintptr_t)q) & 3)) while (n >= 4 && *(const uint32_t *)p == *(const uint32_t *)q) { p += 4; q += 4; n -= 4; } for (; n; n--, p++, q++) if (*p != *q) return *p - *q; return 0; }
|
||||
extern uint32_t __bss_start, __bss_end, __data_start, __data_end, __data_load, __stack_top;
|
||||
void Reset_Handler(void) {
|
||||
for (uint32_t *p = &__bss_start; p < &__bss_end; p++) *p = 0;
|
||||
for (uint32_t *d = &__data_start, *s = &__data_load; d < &__data_end; ) *d++ = *s++;
|
||||
main();
|
||||
}
|
||||
__attribute__((section(".vectors"), used)) const void *g_vec[2] = { (void *)&__stack_top, Reset_Handler }; /* stack in the hole, as on the Paradise */
|
||||
@@ -0,0 +1,52 @@
|
||||
# Profile host code by function (Unicorn block hook, sizes as instruction estimate).
|
||||
import sys, struct, subprocess, bisect, collections, os
|
||||
exec(open('test/m3run.py').read().split("import collections, os")[0])
|
||||
syms_s = []
|
||||
for l in subprocess.run(['arm-none-eabi-nm', '-S', '--size-sort', elf], capture_output=True, text=True).stdout.splitlines():
|
||||
p = l.split()
|
||||
if len(p) == 4 and p[2] in 'tTwW': syms_s.append((int(p[0], 16), int(p[1], 16), p[3]))
|
||||
syms_s.sort(); starts = [x[0] for x in syms_s]
|
||||
jc = syms.get('JC', syms.get('__jc_start', 0xFFFFFFF0)); print('JC', hex(jc))
|
||||
cnt = collections.Counter()
|
||||
calls = [0]
|
||||
samp = []
|
||||
ON = [False]
|
||||
def hb(uc, a, sz, ud):
|
||||
if not ON[0]: return
|
||||
calls[0] += 1
|
||||
if calls[0] % 50000 == 0: samp.append((hex(a), sz))
|
||||
if jc <= a < jc + int(os.environ.get("JCSZ", "16384")):
|
||||
cnt['<JIT code>'] += sz // 2; return
|
||||
i = bisect.bisect_right(starts, a) - 1
|
||||
nm = syms_s[i][2] if i >= 0 and a < syms_s[i][0] + syms_s[i][1] + 4 else '?%x' % a
|
||||
cnt[nm] += sz // 2
|
||||
K = 200000
|
||||
spin_pcs = set(range(syms['mb_spin'] & ~1, (syms['mb_spin'] & ~1) + 12, 2))
|
||||
def run(n):
|
||||
global pc
|
||||
m = 0
|
||||
while True:
|
||||
u.emu_start(pc, 0xFFFFFFFF, count=K); pc = u.reg_read(UC_ARM_REG_PC) | 1; m += K
|
||||
if u.reg_read(UC_ARM_REG_PC) & ~1 in spin_pcs and u.reg_read(UC_ARM_REG_R3) > 1000:
|
||||
print('count method: %d slices, spins %d -> %d' % (m // K, u.reg_read(UC_ARM_REG_R3), m - 4 * u.reg_read(UC_ARM_REG_R3))); return
|
||||
seq = 0
|
||||
def cmd(c, *a):
|
||||
global seq
|
||||
wr(0, c)
|
||||
for i, v in enumerate(a): wr(1 + i, v)
|
||||
seq += 1; wr(9, seq); u.reg_write(UC_ARM_REG_R3, 0); run(0)
|
||||
import os
|
||||
if os.environ.get('CODE'):
|
||||
def hc(uc, a, sz, ud): hb(uc, a, 2, None)
|
||||
u.hook_add(UC_HOOK_CODE, hc)
|
||||
else: u.hook_add(UC_HOOK_BLOCK, hb)
|
||||
run(0)
|
||||
if os.environ.get('LOADST'): # 1.6.13 test4: start from a ref state
|
||||
_b = open(os.environ['LOADST'], 'rb').read(); u.mem_write(0x60FC0000, _b); cmd(7, len(_b) - 0x20000)
|
||||
else: cmd(5, 2026, 10, 15, 8, 0, 0)
|
||||
cmd(1, int(float(sys.argv[3]) * 1000))
|
||||
ON[0] = True
|
||||
cmd(1, int(float(sys.argv[4]) * 1000))
|
||||
tot = sum(cnt.values())
|
||||
print('total approx %.1f M host instr, %d blocks' % (tot / 1e6, calls[0])); print(samp[:20])
|
||||
for k, v in cnt.most_common(30): print('%-28s %5.1f%%' % (k, 100 * v / tot))
|
||||
@@ -0,0 +1,382 @@
|
||||
import zlib
|
||||
import os
|
||||
# Drive the T18 core built for Cortex-M3 (m3main.c) in Unicorn with a script like host/ref.c.
|
||||
# python3 m3run.py <elf> <fw.bin> <script> [K] prints per command host instructions; hash lines like ref
|
||||
import sys, collections, struct, subprocess
|
||||
from unicorn import *
|
||||
from unicorn.arm_const import *
|
||||
elf, fw, script = sys.argv[1], sys.argv[2], sys.argv[3]
|
||||
K = int(sys.argv[4]) if len(sys.argv) > 4 else 200000
|
||||
syms = {}
|
||||
for l in subprocess.run(['arm-none-eabi-nm', elf], capture_output=True, text=True).stdout.splitlines():
|
||||
p = l.split()
|
||||
if len(p) == 3: syms[p[2]] = int(p[0], 16)
|
||||
u = Uc(UC_ARCH_ARM, UC_MODE_THUMB | UC_MODE_MCLASS)
|
||||
# as on the Paradise: PRAM 64 KB, flash window, SRAM 128 KB, RAM at 0x20000000 only 4 KB
|
||||
u.mem_map(0, int(os.environ.get('PRAMSZ', '0x10000'), 16)); u.mem_map(0x10000000, 0x100000); u.mem_map(0x18000000, 0x20000); u.mem_map(0x20000000, int(os.environ.get('RAM20', '0x1000'), 16))
|
||||
u.mem_map(0x60000000, 0x1000000); u.mem_write(0x60000000, open(fw, 'rb').read()[:0x800000].ljust(0x800000, b'\xff'))
|
||||
subprocess.run(['arm-none-eabi-objcopy', '-O', 'binary', '-j', '.text', '-j', '.data', elf, elf + '.bin'], check=True)
|
||||
subprocess.run(['arm-none-eabi-objcopy', '-O', 'binary', '-j', '.xip', elf, elf + '.xip'], check=True)
|
||||
img = open(elf + '.bin', 'rb').read()
|
||||
u.mem_write(0, img)
|
||||
u.mem_write(0x100DF000, open(elf + '.xip', 'rb').read())
|
||||
UNC = [0]
|
||||
LASTC = [(0, 0, 0, 0)]
|
||||
if os.environ.get('UNCOUNT', '1') == '1':
|
||||
UNB = collections.Counter() if os.environ.get('UNBLK') else None
|
||||
UNPC = collections.Counter() if os.environ.get('UNCPC') else None
|
||||
def _unc(uc, acc, addr, size, val, ud):
|
||||
UNC[0] += 1
|
||||
if UNB is not None: UNB[(addr >> 16) & 0xFF] += 1
|
||||
if UNPC is not None: UNPC[(uc.reg_read(UC_ARM_REG_PC), size)] += 1
|
||||
u.hook_add(UC_HOOK_MEM_READ, _unc, begin=0x60000000, end=0x60FFFFFF)
|
||||
PRAM_BAD = [0]
|
||||
def pram_wr(uc, acc, addr, size, val, ud):
|
||||
pc = uc.reg_read(UC_ARM_REG_PC)
|
||||
if not (0x10000000 <= pc < 0x10100000 or 0x1800E600 <= pc < 0x18014400) or size not in (2, 4):
|
||||
PRAM_BAD[0] += 1
|
||||
if PRAM_BAD[0] < 5: print('PRAM written from pc', hex(pc), 'size', size, 'at', hex(addr))
|
||||
if os.environ.get('PRAMCHECK', '1') == '1': u.hook_add(UC_HOOK_MEM_WRITE, pram_wr, begin=0, end=0xFFFF)
|
||||
# Unicorn keeps old translations of code buffer addresses written by the program: drop them on each write
|
||||
if 't18_pram_w16' in syms:
|
||||
def _pw(uc, ad, sz, ud):
|
||||
a = uc.reg_read(UC_ARM_REG_R0) & ~1
|
||||
uc.ctl_remove_cache(a & ~0x3FF, (a & ~0x3FF) + 0x800)
|
||||
u.hook_add(UC_HOOK_CODE, _pw, begin=syms['t18_pram_w16'] & ~1, end=syms['t18_pram_w16'] & ~1)
|
||||
|
||||
def bad(uc, acc, addr, size, val, ud):
|
||||
print('bad access', hex(addr), 'pc', hex(uc.reg_read(UC_ARM_REG_PC)), 'lr', hex(uc.reg_read(UC_ARM_REG_LR)), 'sp', hex(uc.reg_read(UC_ARM_REG_SP))); return False
|
||||
u.hook_add(UC_HOOK_MEM_INVALID, bad)
|
||||
MB = syms['g_mb']
|
||||
sp, entry = struct.unpack_from('<II', img, 0)
|
||||
u.reg_write(UC_ARM_REG_SP, sp); pc = entry | 1
|
||||
total = 0; seq = 0
|
||||
def rd(i): return struct.unpack('<I', u.mem_read(MB + 4 * i, 4))[0]
|
||||
def wr(i, v): u.mem_write(MB + 4 * i, struct.pack('<I', v & 0xFFFFFFFF))
|
||||
import collections, os
|
||||
TR = collections.deque(maxlen=40)
|
||||
if os.environ.get('DEBUG'):
|
||||
u.hook_add(UC_HOOK_BLOCK, lambda uc, a, sz, ud: TR.append(a))
|
||||
def crash(e):
|
||||
import capstone
|
||||
print('CRASH', e)
|
||||
for r, nm in [(UC_ARM_REG_R0,'r0'),(UC_ARM_REG_R1,'r1'),(UC_ARM_REG_R2,'r2'),(UC_ARM_REG_R3,'r3'),(UC_ARM_REG_R4,'r4'),(UC_ARM_REG_R5,'r5'),(UC_ARM_REG_R6,'r6'),(UC_ARM_REG_R7,'r7'),(UC_ARM_REG_R8,'r8'),(UC_ARM_REG_R9,'r9'),(UC_ARM_REG_R10,'r10'),(UC_ARM_REG_R11,'r11'),(UC_ARM_REG_R12,'r12'),(UC_ARM_REG_SP,'sp'),(UC_ARM_REG_LR,'lr'),(UC_ARM_REG_PC,'pc')]:
|
||||
print(nm, hex(u.reg_read(r)), end=' ')
|
||||
print()
|
||||
md = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_THUMB | capstone.CS_MODE_MCLASS)
|
||||
jc = syms.get('JC', syms.get('__jc_start', 0))
|
||||
for a in list(TR)[-12:]:
|
||||
print('block', hex(a), '(JC+%x)' % (a - jc) if jc <= a < jc + 0x10000 else '')
|
||||
last = [a for a in TR if jc <= a < jc + 0x10000]
|
||||
if len(last) > 1 and os.environ.get('DEBUG2'):
|
||||
a = last[-2] & ~1
|
||||
for i in md.disasm(bytes(u.mem_read(a, 400)), a): print(' p', hex(i.address), i.mnemonic, i.op_str)
|
||||
if 't18_hdbg' in syms: print('hdbg', ['%x' % x for x in struct.unpack('<8I', u.mem_read(syms['t18_hdbg'], 32))])
|
||||
jf = syms.get('j_fill')
|
||||
if jf: print('j_fill', ['%x' % x for x in struct.unpack('<2I', u.mem_read(jf, 8))], 'J', '%x' % struct.unpack('<I', u.mem_read(syms['J'], 4))[0], 'half', struct.unpack('<I', u.mem_read(syms['j_half'], 4))[0] if 'j_half' in syms else '?')
|
||||
if last:
|
||||
a = last[-1] & ~1
|
||||
code = bytes(u.mem_read(a, 160))
|
||||
for i in md.disasm(code, a): print(' ', hex(i.address), i.mnemonic, i.op_str)
|
||||
gpc = struct.unpack('<16I', u.mem_read(syms['g_t'], 64))
|
||||
print('guest regs', ' '.join('%08x' % x for x in gpc))
|
||||
sys.exit(1)
|
||||
def vfail(uc, intno, ud):
|
||||
if 'g_vf' not in syms: return
|
||||
v = struct.unpack('<80I', uc.mem_read(syms['g_vf'], 320))
|
||||
if v[0] != 0xBAD: return
|
||||
import capstone
|
||||
key = v[1]
|
||||
print('VERIFY FAIL block key %08x' % key)
|
||||
for nm, o in (('before', 2), ('jit ', 18), ('interp', 34)): print(nm, ' '.join('%08x' % x for x in v[o:o + 16]))
|
||||
print('cpsr', ' '.join('%08x' % x for x in v[50:53]), 'cycles jit %d interp %d start %d' % (v[53], v[54], v[55]))
|
||||
md = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_THUMB if key & 1 else capstone.CS_MODE_ARM)
|
||||
a = key & ~1
|
||||
src = bytes(uc.mem_read(0x18000000 + (a - 0xF8000000), 200)) if a >= 0xF8000000 else bytes(uc.mem_read(0x60000000 + (a - 0x20000000), 200))
|
||||
for i in list(md.disasm(src, a))[:40]: print(' ', hex(i.address), i.mnemonic, i.op_str)
|
||||
sys.exit(2)
|
||||
u.hook_add(UC_HOOK_INTR, vfail)
|
||||
FNCNT = collections.Counter()
|
||||
if os.environ.get('FNCOUNT'):
|
||||
for nm in os.environ['FNCOUNT'].split(','):
|
||||
def _fc(uc, a, sz, ud, nm=nm): FNCNT[nm] += 1
|
||||
u.hook_add(UC_HOOK_CODE, _fc, begin=syms[nm] & ~1, end=syms[nm] & ~1)
|
||||
KSEQ = [] if os.environ.get('KSEQ') else None
|
||||
if KSEQ is not None:
|
||||
def _ks(uc, a, sz, ud):
|
||||
if len(KSEQ) < 3000000: KSEQ.append(uc.reg_read(UC_ARM_REG_R11))
|
||||
u.hook_add(UC_HOOK_CODE, _ks, begin=syms['j_ind_key'] & ~1, end=syms['j_ind_key'] & ~1)
|
||||
CHKR = collections.Counter() if os.environ.get('CHKREG') else None
|
||||
CHKK = collections.Counter()
|
||||
if CHKR is not None:
|
||||
def _cr(uc, a, sz, nm):
|
||||
r11 = uc.reg_read(UC_ARM_REG_R11); lr = uc.reg_read(UC_ARM_REG_LR)
|
||||
info = struct.unpack('<H', bytes(uc.mem_read((lr & ~1), 2)))[0]
|
||||
o = (r11 - 0xF8000000) & 0xFFFFFFFF
|
||||
reg = 'sram' if o < 0x20000 and not (0xE600 <= o < 0x14400) else 'hole' if o < 0x20000 else 'flash' if 0x20000000 <= r11 < 0x20800000 else 'io%x' % (r11 >> 20)
|
||||
CHKR[(nm, reg, 'L' if info & 0x80 else 'S')] += 1
|
||||
if os.environ.get('CHKKEY'): k = struct.unpack('<HH', bytes(uc.mem_read((lr & ~1) + 4, 4))); CHKK[k[0] | k[1] << 16] += 1
|
||||
for nm in ('j_chk0','j_chk1','j_chk2','j_chkf0','j_chkf1','j_chkf2'):
|
||||
u.hook_add(UC_HOOK_CODE, _cr, nm, begin=syms[nm] & ~1, end=syms[nm] & ~1)
|
||||
JSH = collections.Counter() if os.environ.get('JSLOWH') else None
|
||||
if JSH is not None:
|
||||
def _js(uc, a, sz, ud):
|
||||
r11 = uc.reg_read(UC_ARM_REG_R11); lr = uc.reg_read(UC_ARM_REG_LR)
|
||||
info = struct.unpack('<I', bytes(uc.mem_read((lr & ~1) - 0 + 0, 4)))[0] if False else 0
|
||||
JSH[(r11 & ~0xFF)] += 1
|
||||
u.hook_add(UC_HOOK_CODE, _js, begin=syms['j_slow'] & ~1, end=syms['j_slow'] & ~1)
|
||||
if os.environ.get('JTRACE'):
|
||||
_tf = open(os.environ['JTRACE'], 'w'); _tend = int(os.environ.get('JTEND', '400000'))
|
||||
def _jt(uc, a, sz, ud):
|
||||
c = uc.reg_read(UC_ARM_REG_R0)
|
||||
v = struct.unpack('<17I', uc.mem_read(c, 68)); cy = struct.unpack('<Q', uc.mem_read(c + 184, 8))[0]
|
||||
if int(os.environ.get('JTBEG','0')) <= cy <= _tend: _tf.write('%d %s %x %x\n' % (cy, ' '.join('%x' % x for x in v[:16]), v[16] & 0xF000003F, zlib.crc32(bytes(uc.mem_read(0x18000000, 0xE600)))))
|
||||
a = syms['t18_jit_try'] & ~1
|
||||
u.hook_add(UC_HOOK_CODE, _jt, begin=a, end=a)
|
||||
if os.environ.get('JEV'):
|
||||
_cpu = [0]
|
||||
def _ev(uc, a, sz, nm):
|
||||
c = uc.reg_read(UC_ARM_REG_R0) if nm in ('j_enter', 'arm7_step') else 0
|
||||
cpu = c or _cpu[0]
|
||||
if c: _cpu[0] = c
|
||||
if not cpu: return
|
||||
cy = struct.unpack('<Q', uc.mem_read(cpu + 184, 8))[0]
|
||||
if int(os.environ.get('JTBEG','0')) <= cy <= _tend:
|
||||
pcv, cps = struct.unpack('<II', uc.mem_read(cpu + 60, 8))
|
||||
_tf.write(' ev %s r0=%x r1=%x r11=%x lr=%x cyc %d gpc %x cpsr %x\n' % (nm, uc.reg_read(UC_ARM_REG_R0), uc.reg_read(UC_ARM_REG_R1), uc.reg_read(UC_ARM_REG_R11), uc.reg_read(UC_ARM_REG_LR), cy, pcv, cps))
|
||||
for nm in ('j_enter', 't18_jit_lookup', 't18_jit_link', 'arm7_step', 't18_jh_slow', 't18_jit_exit', 'j_indbx', 'j_ind'):
|
||||
if nm in syms:
|
||||
b = syms[nm] & ~1
|
||||
u.hook_add(UC_HOOK_CODE, _ev, nm, begin=b, end=b)
|
||||
u.mem_map(0x30000000, 0x80000)
|
||||
EXACT = [0]
|
||||
EXON = [False]
|
||||
def _cnt(uc, a, sz, ud): EXACT[0] += 1
|
||||
PSAMP = {} if os.environ.get('PSAMP') else None
|
||||
_fsyms = sorted((v & ~1, k) for k, v in syms.items() if not k.startswith('__') and k not in ('JC',))
|
||||
import bisect
|
||||
def _fname(a):
|
||||
if syms.get('__jc_start', 0) <= a < syms.get('__jc_end', 0): return '<JIT code>'
|
||||
i = bisect.bisect_right(_fsyms, (a, '~')) - 1
|
||||
return _fsyms[i][1] if i >= 0 else '?'
|
||||
def psamp_report():
|
||||
if PSAMP is None: return
|
||||
agg = {}
|
||||
for a, c in PSAMP.items(): f = _fname(a); agg[f] = agg.get(f, 0) + c
|
||||
tot = sum(agg.values()) or 1
|
||||
print(' profile: ' + ', '.join('%s %d%%' % (f, c * 100 // tot) for f, c in sorted(agg.items(), key=lambda x: -x[1])[:14]))
|
||||
PSAMP.clear()
|
||||
TUS = (syms['__jc_start'], syms['__jc_end'], syms['t18_tu_pc']) if 't18_tu_pc' in syms and '__jc_end' in syms else None
|
||||
if os.environ.get('TUK'): K = int(os.environ['TUK'])
|
||||
def run_until_idle():
|
||||
global pc, total
|
||||
n = 0; e0 = EXACT[0]
|
||||
while True:
|
||||
try: u.emu_start(pc, 0xFFFFFFFF, count=K)
|
||||
except UcError as e: crash(e)
|
||||
pc = u.reg_read(UC_ARM_REG_PC) | 1; n += K
|
||||
if TUS is not None and TUS[0] <= (pc & ~1) < TUS[1]: u.mem_write(TUS[2], struct.pack('<I', pc))
|
||||
if PSAMP is not None: PSAMP[pc & ~1] = PSAMP.get(pc & ~1, 0) + 1
|
||||
# idle when spinning and spin counter grows
|
||||
if u.reg_read(UC_ARM_REG_PC) & ~1 in spin_pcs and u.reg_read(UC_ARM_REG_R3) > 1000:
|
||||
spins = u.reg_read(UC_ARM_REG_R3)
|
||||
ex = n - spins * 4
|
||||
if EXON[0]: print(' exact %d (sliced %d)' % (EXACT[0] - e0 - spins * 4, ex))
|
||||
total += ex
|
||||
return ex
|
||||
spin_pcs = set(range(syms['mb_spin'] & ~1, (syms['mb_spin'] & ~1) + 12, 2))
|
||||
def cmd(c, *a):
|
||||
global seq
|
||||
wr(0, c)
|
||||
for i, v in enumerate(a): wr(1 + i, v)
|
||||
seq += 1; wr(9, seq)
|
||||
u.reg_write(UC_ARM_REG_R3, 0)
|
||||
return run_until_idle()
|
||||
run_until_idle() # boot to the first wait
|
||||
ms_total = 0; host_total = 0
|
||||
for l in open(script):
|
||||
p = l.split()
|
||||
if not p: continue
|
||||
if p[0] == 'wait':
|
||||
ms = float(p[1]); ex = cmd(1, int(ms * 1000)); ms_total += ms; host_total += ex
|
||||
if os.environ.get('IDLELOG'): print(' '.join('%x' % x for x in struct.unpack('<64I', bytes(u.mem_read(syms['t18_idle_log'], 256)))))
|
||||
psamp_report()
|
||||
if CHKR is not None: print(' chk: ' + ', '.join('%s/%s/%s %d' % (k[0],k[1],k[2],v) for k, v in CHKR.most_common(14))); CHKR.clear()
|
||||
if os.environ.get('CHKKEY'): print(' keys: ' + ' '.join('%08x:%d' % kv for kv in CHKK.most_common(24))); CHKK.clear()
|
||||
if 't18_kstat' in syms:
|
||||
kb = struct.unpack('<40I', bytes(u.mem_read(syms['t18_kstat'], 160)))
|
||||
nm = ['COPY','HI','LDRPC','MEM','SPMEM','ADDPC','ADDSP','SPADJ','PUSH','POP','LDM','STM','BCC','B','BL','?','-','?','begin','end+exits']
|
||||
print(' kstat: ' + ' '.join('%s %d/%d=%.1f' % (nm[i], kb[i]*2, kb[20+i], kb[i]*2/max(kb[20+i],1)) for i in range(20) if kb[20+i]))
|
||||
if 't18_slow_hist' in syms:
|
||||
h = struct.unpack('<128I', bytes(u.mem_read(syms['t18_slow_hist'], 512)))
|
||||
top = sorted([(h[2*i+1], h[2*i]) for i in range(64) if h[2*i]], reverse=True)[:12]
|
||||
print(' slow: ' + ' '.join('%08x%s:%d' % (k & ~1, 'R' if k & 1 else 'W', c) for c, k in top))
|
||||
u.mem_write(syms['t18_slow_hist'], bytes(512))
|
||||
cy, ic = struct.unpack('<QQ', bytes(u.mem_read(syms['g_t'] + 184, 16))); isk = struct.unpack('<Q', bytes(u.mem_read(syms['g_t'] + 288, 8)))[0]
|
||||
ti = struct.unpack('<2I', bytes(u.mem_read(syms['t18_interp'], 8))) if 't18_interp' in syms else (0, 0)
|
||||
L = LASTC[0]; LASTC[0] = (cy, ic, isk, ti[0] + ti[1])
|
||||
print(' guest cycles %d M, idle %d M, skipped %d M, interpreted %d K' % ((cy - L[0]) // 1000000, (ic - L[1]) // 1000000, (isk - L[2]) // 1000000, (ti[0] + ti[1] - L[3]) // 1000))
|
||||
if os.environ.get('SYMDUMP'):
|
||||
for it in os.environ['SYMDUMP'].split(','):
|
||||
nm, n = it.split(':')
|
||||
if nm in syms:
|
||||
w = struct.unpack('<%dI' % int(n), bytes(u.mem_read(syms[nm], 4 * int(n)))); print(' ' + nm, ' '.join(str(x) for x in w)); u.mem_write(syms[nm], bytes(4 * int(n)))
|
||||
unc = UNC[0]; UNC[0] = 0
|
||||
if os.environ.get('UNCPC') and os.environ.get('UNCOUNT', '1') == '1':
|
||||
agg = collections.Counter()
|
||||
for (a, sz), c in UNPC.items(): agg[(_fname(a & ~1), sz)] += c
|
||||
print(' unc by fn: ' + ' '.join('%s/%d:%d' % (k[0], k[1], v) for k, v in agg.most_common(12))); UNPC.clear()
|
||||
if os.environ.get('UNBLK') and os.environ.get('UNCOUNT', '1') == '1':
|
||||
print(' blocks ' + ' '.join('%02x:%d' % kv for kv in UNB.most_common(30))); UNB.clear()
|
||||
print(' uncached reads %d (+%.1f Minstr/s at 96 each) bytes %d' % (unc, unc * 96 / ms / 1000, struct.unpack('<I', bytes(u.mem_read(syms['t18_jit_bytes'], 4)))[0]))
|
||||
js = struct.unpack('<8I', bytes(u.mem_read(syms['t18_jit_stat'], 32)))
|
||||
print('wait %8.0f ms host %10d instr %6.1f Minstr/s jit blocks %d entries %d flushes %d slow %d idle %d instr %d fr %s used %d' % (ms, ex, ex / ms / 1000, js[0], js[1], js[3], js[4], js[2], js[7], struct.unpack('<4I', bytes(u.mem_read(syms['t18_jit_fr'], 16))), struct.unpack('<I', bytes(u.mem_read(syms['J'], 4)))[0]))
|
||||
elif p[0] == 'press':
|
||||
m = 0
|
||||
for ch in p[1]: m |= {'A': 1, 'B': 2, 'C': 4}.get(ch, 0)
|
||||
ms = float(p[2]) if len(p) > 2 else 150
|
||||
cmd(2, m); ex = cmd(1, int(ms * 1000)); cmd(2, 0); ms_total += ms; host_total += ex
|
||||
elif p[0] == 'hash':
|
||||
cmd(3); cyc = rd(2) | rd(3) << 32
|
||||
print('cyc %d pc %08x sram %08x' % (cyc, rd(4), rd(5)))
|
||||
print(' hole pages %d%s' % (rd(7) >> 8, ' OUT OF PAGES' if rd(7) & 1 else ''), file=sys.stderr)
|
||||
elif p[0] == 'stat':
|
||||
cmd(4)
|
||||
print('ginstr %d bytes %d (%.1f/instr) ' % (rd(13), rd(14), rd(14) / max(1, rd(13))), end=''); print('blocks %d entries %d stuck %d flushes %d slow %d links %d lookups %d used %d | interp thumb %d arm %d' % (rd(1), rd(2), rd(3), rd(4), rd(5), rd(6), rd(11), rd(12), rd(7), rd(10)))
|
||||
elif p[0] == 'loadst':
|
||||
b = open(p[1], 'rb').read(); n = len(b) - 0x20000
|
||||
u.mem_write(0x60FC0000, b); cmd(7, n)
|
||||
if rd(2) & 0x80000000: print('loadst failed', rd(2)); sys.exit(3)
|
||||
elif p[0] == 'shot':
|
||||
src = rd(1); o = src - 0xF8000000
|
||||
if 0 <= o < 0x20000 and not (0xE600 <= o < 0x14400):
|
||||
open(p[1], 'wb').write(bytes(u.mem_read(0x18000000 + o, 128 * 128 * 2)))
|
||||
else: print('shot: picture at', hex(src))
|
||||
elif p[0] == 'time':
|
||||
cmd(5, *[int(x) for x in p[1:7]])
|
||||
elif p[0] == 'verify':
|
||||
cmd(6)
|
||||
elif p[0] == 'exact':
|
||||
EXON[0] = True; u.hook_add(UC_HOOK_CODE, _cnt); u.ctl_flush_tb()
|
||||
elif p[0] == 'prof':
|
||||
# host profile by function over <ms>; guest pcs at dispatcher entries too
|
||||
import bisect, collections
|
||||
syms_s = []
|
||||
for l2 in subprocess.run(['arm-none-eabi-nm', '-S', elf], capture_output=True, text=True).stdout.splitlines():
|
||||
q = l2.split()
|
||||
if len(q) == 4 and q[2] in 'tTwW': syms_s.append((int(q[0], 16), int(q[1], 16), q[3]))
|
||||
syms_s.sort(); starts = [x[0] for x in syms_s]
|
||||
jc = syms.get('JC', syms.get('__jc_start', 0)); jcsz = int(os.environ.get('JCSZ', str(syms['__jc_end'] - jc if '__jc_end' in syms else 32768)))
|
||||
cnt = collections.Counter(); gpc = collections.Counter(); jpc = collections.Counter()
|
||||
PFN = os.environ.get('PROFFN'); fpc = collections.Counter()
|
||||
LASTF = collections.deque(maxlen=6); WHY = collections.Counter(); WPC = int(os.environ.get('WHYPC', '0'), 16)
|
||||
def hcode(uc, a, sz, ud):
|
||||
if jc <= a < jc + jcsz:
|
||||
cnt['<JIT code>'] += 1; jpc[a] += 1
|
||||
if WPC and (not LASTF or LASTF[-1] != 'JIT'): LASTF.append('JIT')
|
||||
return
|
||||
i = bisect.bisect_right(starts, a) - 1
|
||||
nm = syms_s[i][2] if i >= 0 and a < syms_s[i][0] + syms_s[i][1] + 4 else '?'
|
||||
cnt[nm] += 1
|
||||
if nm == PFN: fpc[a] += 1
|
||||
if WPC and (not LASTF or LASTF[-1] != nm): LASTF.append(nm)
|
||||
def hjt(uc, a, sz, ud):
|
||||
c = uc.reg_read(UC_ARM_REG_R0); g = struct.unpack('<I', uc.mem_read(c + 60, 4))[0]; gpc[g] += 1
|
||||
if WPC and (g & ~1) == (WPC & ~1): WHY[' > '.join(list(LASTF)[-5:])] += 1
|
||||
if g == int(os.environ.get('WATCHPC', '0'), 16) and gpc[g] < int(os.environ.get('WATCHN', '4')):
|
||||
v = struct.unpack('<17I', uc.mem_read(c, 68)); x = struct.unpack('<QQIiii', uc.mem_read(c + 184, 32))
|
||||
print(' at %08x cpsr %08x cyc %d mult %d irq %d fiq %d halt %d r12 %08x lr %08x r3 %08x' % (g, v[16], x[0], x[2], x[3], x[4], x[5], v[12], v[14], v[3]))
|
||||
jh = syms.get('JH', syms.get('JHa', 0))
|
||||
for i in range(1024):
|
||||
k, off, mc, hot, none, hot2 = struct.unpack('<IHHBBB', u.mem_read(jh + 12 * i, 11)); code = syms['JC'] + 2 * (off - 1) if off else 0
|
||||
if k == g: print(' entry code %x maxcyc %d hot %d none %d' % (code, mc, hot, none))
|
||||
h1 = u.hook_add(UC_HOOK_CODE, hcode)
|
||||
h2 = u.hook_add(UC_HOOK_CODE, hjt, begin=syms['t18_jit_try'] & ~1, end=syms['t18_jit_try'] & ~1)
|
||||
u.ctl_flush_tb()
|
||||
ms = float(p[1]); cmd(1, int(ms * 1000))
|
||||
u.hook_del(h1); u.hook_del(h2)
|
||||
tot = sum(cnt.values())
|
||||
for k, v in cnt.most_common(22): print(' %-26s %5.1f%%' % (k, 100 * v / tot))
|
||||
import capstone
|
||||
md = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_THUMB)
|
||||
hot = sorted(jpc.items(), key=lambda x: -x[1])[:1]
|
||||
if hot:
|
||||
a0 = hot[0][0]
|
||||
# show the hottest 160 bytes around
|
||||
code = bytes(u.mem_read(a0 - 64, 224))
|
||||
for ins in md.disasm(code, a0 - 64): print(' %6d %x %s %s' % (jpc.get(ins.address, 0), ins.address, ins.mnemonic, ins.op_str))
|
||||
if PFN:
|
||||
md2 = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_THUMB | capstone.CS_MODE_MCLASS)
|
||||
fs = [x for x in syms_s if x[2] == PFN][0]
|
||||
code = bytes(u.mem_read(fs[0], fs[1]))
|
||||
for ins in md2.disasm(code, fs[0]):
|
||||
if fpc.get(ins.address, 0) * 2000 > sum(fpc.values()): print(' F %7d %x %s %s' % (fpc[ins.address], ins.address, ins.mnemonic, ins.op_str))
|
||||
for k, v in WHY.most_common(6): print(' why %6d %s' % (v, k))
|
||||
print(' dispatcher entries by guest pc:')
|
||||
for k, v in gpc.most_common(int(os.environ.get('PROFN', '15'))): print(' %08x %d' % (k, v))
|
||||
print('total %.1f s guest, %.0f M host instr, %.1f Minstr per guest second' % (ms_total / 1000, host_total / 1e6, host_total / ms_total / 1000))
|
||||
if os.environ.get('JKEYS'):
|
||||
lo, hi = [int(x, 16) for x in os.environ['JKEYS'].split('-')]
|
||||
jn = int(os.environ.get("JHN","1024"))
|
||||
jadr = [syms['JH'] + 12 * i for i in range(jn)] if 'JH' in syms else [syms['JHa'] + 12 * i for i in range(jn // 2)] + [int(os.environ.get('JHB', '0x20000100'), 16) + 12 * i for i in range(jn // 2)]
|
||||
jcs = syms.get('JC', syms.get('__jc_start'))
|
||||
for i in range(jn):
|
||||
k, off, mc, hot, none = struct.unpack('<IHHBB', u.mem_read(jadr[i], 10)); code = jcs + 2 * (off - 1) if off else 0
|
||||
if lo <= k < hi:
|
||||
print('key %08x code %x maxcyc %d hot %d none %d' % (k, code, mc, hot, none))
|
||||
if code and os.environ.get('JDIS'):
|
||||
import capstone
|
||||
md = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_THUMB)
|
||||
for ins in list(md.disasm(bytes(u.mem_read(code, 120)), code))[:int(os.environ['JDIS'])]: print(' %x %s %s' % (ins.address, ins.mnemonic, ins.op_str))
|
||||
if os.environ.get('BLKDUMP'):
|
||||
import capstone
|
||||
md = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_THUMB)
|
||||
lo, hi = [int(x, 16) for x in os.environ['BLKDUMP'].split('-')]
|
||||
p = syms['__jc_start']; jend = struct.unpack('<I', bytes(u.mem_read(syms['J'], 4)))[0]
|
||||
tot = {}
|
||||
while p + 8 <= jend:
|
||||
k0, k1, gl, hs = struct.unpack('<HHHH', bytes(u.mem_read(p, 8))); key = k0 | k1 << 16; code = p + 8
|
||||
if lo <= key < hi:
|
||||
print('block %08x guest %d hw, host %d bytes at %x' % (key, gl, 2 * hs, code))
|
||||
for ins in md.disasm(bytes(u.mem_read(code, 2 * hs)), code): print(' %x %s %s' % (ins.address, ins.mnemonic, ins.op_str))
|
||||
p = code + 2 * hs
|
||||
if os.environ.get('JDUMP'):
|
||||
import capstone
|
||||
want = int(os.environ['JDUMP'], 16); jh = syms['JH']
|
||||
for i in range(int(os.environ.get("JHN","512"))):
|
||||
k, off, mc = struct.unpack('<IHH', u.mem_read(jh + 12 * i, 8)); code = syms['JC'] + 2 * (off - 1) if off else 0
|
||||
if k == want and code:
|
||||
print('block %08x code %08x maxcyc %d' % (k, code, mc))
|
||||
md = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_THUMB)
|
||||
for ins in md.disasm(bytes(u.mem_read(code, 200)), code): print(' ', hex(ins.address), ins.mnemonic, ins.op_str)
|
||||
if os.environ.get('GDIS'):
|
||||
import capstone
|
||||
for it in os.environ['GDIS'].split(','):
|
||||
a, n, m = it.split(':'); a = int(a, 16); n = int(n, 16)
|
||||
md = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_THUMB if m == 't' else capstone.CS_MODE_ARM)
|
||||
src = bytes(u.mem_read(0x18000000 + (a - 0xF8000000), n)) if a >= 0xF8000000 else bytes(u.mem_read(0x60000000 + (a - 0x20000000), n))
|
||||
for ins in md.disasm(src, a): print(' ', hex(ins.address), ins.mnemonic, ins.op_str)
|
||||
if os.environ.get('SRAMDUMP'): open(os.environ['SRAMDUMP'], 'wb').write(bytes(u.mem_read(0x18000000, 0x20000)))
|
||||
if os.environ.get('LKDBG'):
|
||||
v = struct.unpack('<1536I', bytes(u.mem_read(0x20008000, 6144)))
|
||||
rows = sorted([(v[i + 2], v[i], v[i + 1]) for i in range(0, 1536, 3) if v[i]], reverse=True)
|
||||
for c, k, r in rows[:int(os.environ['LKDBG'])]: print('lk %08x r%d %d' % (k, r, c))
|
||||
if os.environ.get('IPCH'):
|
||||
v = struct.unpack('<2048I', bytes(u.mem_read(0x20008000, 8192)))
|
||||
rows = sorted([(v[i + 1], v[i]) for i in range(0, 2048, 2) if v[i + 1]], reverse=True)
|
||||
for c, pc in rows[:int(os.environ['IPCH'])]: print('ipc %08x %d' % (pc, c))
|
||||
if os.environ.get('TRYPCS'):
|
||||
v = struct.unpack('<%dI' % (1024 * 3), bytes(u.mem_read(0x20004000, 1024 * 12)))
|
||||
names = ['calls', 'stuck', 'sp', 'seq', 'noblock', 'none', 'budget', 'entered', 'target']
|
||||
rows = sorted([(v[i + 2], v[i], v[i + 1]) for i in range(0, len(v), 3) if v[i] and v[i + 1] != 0], reverse=True)
|
||||
for c, pc, r in [x for x in rows if x[2] != 3 or os.environ.get('TRYSEQ')][:int(os.environ['TRYPCS'])]: print('trypc %08x %-8s %d' % (pc, names[r], c))
|
||||
|
||||
if JSH is not None:
|
||||
tot = sum(JSH.values()); print('j_slow entries', tot)
|
||||
for k, v in JSH.most_common(20): print(' jslow %08x %d' % (k, v))
|
||||
|
||||
if FNCNT: print('fncount', ' '.join('%s=%d' % kv for kv in FNCNT.items()))
|
||||
|
||||
if KSEQ is not None: open(os.environ['KSEQ'], 'wb').write(struct.pack('<%dI' % len(KSEQ), *KSEQ))
|
||||
for _s in os.environ.get('SYMEND', '').split(','): # 1.6.13 test5: 32-bit values of symbols at the end
|
||||
if _s in syms: print('sym', _s, struct.unpack('<I', bytes(u.mem_read(syms[_s], 4)))[0])
|
||||
@@ -0,0 +1,44 @@
|
||||
# 1.6.13 test5: sampling profile (PC every K host instructions) of the T18 core in the M3 test bed, from a ref state.
|
||||
# LOADST=state python3 test/m3samp.py <elf> <fw> <warm s> <measure s>
|
||||
import sys, struct, subprocess, bisect, collections, os
|
||||
exec(open('test/m3run.py').read().split("import collections, os")[0])
|
||||
syms_s = []
|
||||
for l in subprocess.run(['arm-none-eabi-nm', '-S', '--size-sort', elf], capture_output=True, text=True).stdout.splitlines():
|
||||
p = l.split()
|
||||
if len(p) == 4 and p[2] in 'tTwW': syms_s.append((int(p[0], 16), int(p[1], 16), p[3]))
|
||||
syms_s.sort(); starts = [x[0] for x in syms_s]
|
||||
jc = syms.get('__jc_start', 0xFFFFFFF0); je = syms.get('__jc_end', jc)
|
||||
cnt = collections.Counter(); ON = [False]
|
||||
spin_pcs = set(range(syms['mb_spin'] & ~1, (syms['mb_spin'] & ~1) + 12, 2))
|
||||
KS = 997
|
||||
TU = [0]
|
||||
def name(a):
|
||||
if jc <= a < je: return '<JIT code>'
|
||||
i = bisect.bisect_right(starts, a) - 1
|
||||
return syms_s[i][2] if i >= 0 and a < syms_s[i][0] + syms_s[i][1] + 4 else '?%x' % a
|
||||
def run(n):
|
||||
global pc
|
||||
while True:
|
||||
u.emu_start(pc, 0xFFFFFFFF, count=KS); a = u.reg_read(UC_ARM_REG_PC); pc = a | 1
|
||||
TU[0] += 1
|
||||
if TU[0] % 70 == 0 and jc <= (a & ~1) < je and 't18_tu_pc' in syms: u.mem_write(syms['t18_tu_pc'], struct.pack('<I', a | 1)) # SysTick every ~70000
|
||||
if (a & ~1) in spin_pcs and u.reg_read(UC_ARM_REG_R3) > 1000: return
|
||||
if ON[0]:
|
||||
nm = name(a & ~1)
|
||||
if nm == 'mb_spin': continue
|
||||
cnt[nm] += 1
|
||||
if nm in ('arm7_run', 'exec_arm', 'idle_try'): cnt[' gpc %08x' % (u.reg_read(UC_ARM_REG_R0) if False else 0)] += 0
|
||||
seq = 0
|
||||
def cmd(c, *a):
|
||||
global seq
|
||||
wr(0, c)
|
||||
for i, v in enumerate(a): wr(1 + i, v)
|
||||
seq += 1; wr(9, seq); u.reg_write(UC_ARM_REG_R3, 0); run(0)
|
||||
run(0)
|
||||
_b = open(os.environ['LOADST'], 'rb').read(); u.mem_write(0x60FC0000, _b); cmd(7, len(_b) - 0x20000)
|
||||
cmd(1, int(float(sys.argv[3]) * 1000000))
|
||||
ON[0] = True
|
||||
cmd(1, int(float(sys.argv[4]) * 1000000))
|
||||
tot = sum(cnt.values())
|
||||
print('samples', tot)
|
||||
for k, v in cnt.most_common(40): print('%-28s %5.1f%%' % (k, 100 * v / tot))
|
||||
Reference in new issue
Block a user