다마고치 연구소 한국어판 소스 공개
Paramix Studio / build (push) Canceled after 0s
Paramix Studio / pages (push) Canceled after 0s

This commit is contained in:
syskiller committed 2026-11-10 21:17:44 +09:00
commit db23855630
661 files changed
+503597

No files matched your search

+181
View File
@@ -0,0 +1,181 @@
# ArduboyEmu (ab.bin) in Unicorn, as devt7.py: hardware calls caught, the screen into a picture.
# into a picture, the SysTick is advanced every RT instructions (96 MHz Cortex-M3 ~ RT per ms).
# python3 devv3.py <v3.elf> <image with v3.bin at APPOFF> <ms> [KEYS="t:mask,..."] [SHOTS="t,t,..."] [OUT=dir]
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(['llvm-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)
u.ctl_set_cpu_model(UC_CPU_ARM_CORTEX_M4)
APPOFF = int(os.environ.get('APPOFF', '0xA0000'), 16) # program image (1.6.0: more programs elsewhere)
u.mem_map(0, 0x10000); u.mem_write(0, bytes(fl[APPOFF:APPOFF + 0x10000]))
u.mem_map(0x18000000, 0x20000); u.mem_map(0x20000000, 0x1000)
u.mem_map(0x10000000, 0x100000)
u.mem_map(0x60000000, 0x1000000); u.mem_write(0x60000000, bytes(fl))
u.mem_map(0x40000000, 0x100000); u.mem_map(0x45000000, 0x1000); u.mem_map(0xE000E000, 0x1000); u.mem_map(0xE0001000, 0x1000) # DWT (CYCCNT reads 0 here)
u.mem_write(0x4000B014, struct.pack('<I', 0x60)) # 1.6.9 T7_LINK: UART1 LSR, sender empty (nothing received)
cfg = APPOFF + 0x140
rom_off = struct.unpack_from('<I', fl, cfg + 8)[0]
u.mem_write(0x10000000, bytes(fl[rom_off:rom_off + 0x100000]))
XIPN = [0]
def _xipw(uc, acc, a, sz, v, ud): # 1.7.2 GB_PAGES: the window follows its base register
o = v - 0x60000000
if 0 <= o < 0x1000000: uc.mem_write(0x10000000, bytes(fl[o:o + 0x100000]).ljust(0x100000, b'\xff')); XIPN[0] += 1
u.hook_add(UC_HOOK_MEM_WRITE, _xipw, begin=0x4002F004, end=0x4002F007)
import atexit; atexit.register(lambda: print('window moves', XIPN[0]))
WH = [] # WHEEL='t:steps,...' (+ one way, - the other): the encoder phases at GPIO2
for p in os.environ.get('WHEEL', '').split(','):
if ':' in p: t, n = p.split(':'); WH.append([float(t), int(n)])
state_enc = {'ph': 0, 'q': []}
GRAY = [0, 1, 3, 2]
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': [], 'left': 0, 'flashw': 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, *a):
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, *a):
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
ret(uc)
def h_tone(uc, *a): state['tone'].append((state['ms'], uc.reg_read(UC_ARM_REG_R0))); ret(uc)
def h_btn(uc, *a): ret(uc, keys())
def h_prog(uc, *a):
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 & 0xFFFFFF
uc.mem_write(0x60000000 + a, d); fl[a:a + 0x1000] = d; state['flashw'] += 1; ret(uc)
def h_erase(uc, *a):
a = uc.reg_read(UC_ARM_REG_R0) & 0xFFFFFF
uc.mem_write(0x60000000 + a, b'\xff' * 0x1000); fl[a:a + 0x1000] = b'\xff' * 0x1000; ret(uc)
def h_back(uc, *a): state['back'] = 1; uc.emu_stop()
def h_nop(uc, *a): ret(uc)
H = {'hw_px_begin': h_begin, 'hw_px_row': h_row, 'hw_px_end': h_nop, 'hw_tone': h_tone, 'hw_buttons': h_btn,
'flash_prog4k': h_prog, 'flash_erase4k': h_erase, 'hw_back_to_paradise': h_back, 'hw_init': h_nop,
'hw_backlight': h_nop, 'hw_bl_pwm_off': h_nop, 'hw_wdt_feed': h_nop}
for n, f in H.items():
a = syms[n] & ~1
u.hook_add(UC_HOOK_CODE, (lambda f: lambda uc, ad, sz, ud: f(uc))(f), begin=a, end=a)
import builtins
if hasattr(builtins, '__gbprof'): u.hook_add(UC_HOOK_BLOCK, builtins.__gbprof[0])
if os.environ.get('CACHESIM'): # test38: the I-cache of the flash window (16 KB, 32-byte lines, WAYS ways, LRU): misses per frame
_ways = int(os.environ.get('WAYS', '4')); _sets = 16384 // 32 // _ways
_cs = [[] for _ in range(_sets)]; state['miss'] = 0; state['acc'] = 0
def _cr(uc, acc, a, sz, v, ud):
state['acc'] += 1
ln = (a - 0x10000000) >> 5; s = _cs[ln % _sets]
if ln in s: s.remove(ln); s.append(ln); return
state['miss'] += 1; s.append(ln)
if len(s) > _ways: s.pop(0)
u.hook_add(UC_HOOK_MEM_READ, _cr, begin=0x10000000, end=0x100FFFFF)
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)
# 1.6.9 test22 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)
if os.environ.get('MEMW'):
_mw = int(os.environ['MEMW'], 16)
u.hook_add(UC_HOOK_MEM_WRITE, lambda uc, acc, a, sz, v, ud: print('W %08x = %08x at ms %d' % (a, v, state['ms'])), begin=_mw, end=_mw + 0x3F)
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))
if os.environ.get('PMB'): # test: the Paradise's time in the mailbox (seconds since 1970, local)
_t = int(os.environ['PMB']); _c = int(os.environ.get('RTC0', '5000'))
u.mem_write(0x20000FC0, struct.pack('<IIII', 0x4B4C4350, _t, _c, (~_t) & 0xFFFFFFFF))
# 1.6.11 test2 GB_LINK: two of these joined by pipes, one exchange per ms (LINKW: pipe to write, LINKR: pipe to read)
LK = {'tx': bytearray(), 'n0': 0}
if os.environ.get('LINKW'):
def _uw(uc, acc, a, sz, v, ud):
LK['n0'] += 1
if LK['n0'] > 1: LK['tx'].append(v & 0xFF) # the first is the baud divisor
u.hook_add(UC_HOOK_MEM_WRITE, _uw, begin=0x4000B000, end=0x4000B000)
LK['w'] = os.fdopen(os.open(os.environ['LINKW'], os.O_RDWR), 'wb', buffering=0); LK['r'] = os.fdopen(os.open(os.environ['LINKR'], os.O_RDWR), 'rb', buffering=0) # (O_RDWR: no wait for the other end)
def link_ms():
d = bytes(LK['tx']); LK['tx'] = bytearray()
LK['w'].write(struct.pack('<H', len(d)) + d)
h = LK['r'].read(2)
while len(h) < 2: h += LK['r'].read(2 - len(h))
n = struct.unpack('<H', h)[0]; got = b''
while len(got) < n: got += LK['r'].read(n - len(got))
if got:
a = syms['g_pl']; rt = u.mem_read(a + 257, 1)[0]
for b in got: u.mem_write(a + rt, bytes([b])); rt = (rt + 1) & 0xFF
u.mem_write(a + 257, bytes([rt]))
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'))
emu_ms_sym = None
si = 0
while state['ms'] < total_ms and 'back' not in state:
u.mem_write(0x45000304, struct.pack('<I', rtc0 + state['ms'] // 1000))
try:
u.emu_start(pc | 1, 0xFFFFFFF0, count=max(1, RT >> state['sh'])); state['shms'][min(state['sh'], 3)] += 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)
state['ms'] += 1
if 'w' in LK: link_ms()
v = struct.unpack('<I', u.mem_read(gms, 4))[0]; u.mem_write(gms, struct.pack('<I', v + 1))
# 1.6.9 test13 T7_KEYQ: the GPIO as the keys say (pressed = 0) and the tick's press counter
km = keys(); u.mem_write(0x40018000, struct.pack('<I', 0xFFFFFFFF & ~(((km & 1) << 9) | ((km & 2) << 10) | ((km & 4) << 8) | ((km & 8) << 5))))
if 'g_kin' in syms:
e = km & ~state.get('kprev', 0) & 7; state['kprev'] = km
u.mem_write(syms['g_kprev'], bytes([km & 7]))
for i in range(3):
if e & (1 << i): a = syms['g_kin'] + i; u.mem_write(a, bytes([(u.mem_read(a, 1)[0] + 1) & 0xFF]))
for w in WH:
if w[1] and state['ms'] / 1000.0 >= w[0]:
d = 1 if w[1] > 0 else -1; state_enc['ph'] = (state_enc['ph'] + d) % 4; w[0] += 0.004 if (state_enc['ph'] % 4) else 0.02
if state_enc['ph'] == 0: w[1] -= d
u.mem_write(0x4001A000, struct.pack('<I', GRAY[state_enc['ph']]))
for pk in os.environ.get('POKE', '').split(','): # test: 'ms:symbol+off:byte' written once
if pk.count(':') == 2 and int(pk.split(':')[0]) == state['ms']:
_t, _a, _v = pk.split(':'); _n, _o = (_a.split('+') + ['0'])[:2]; u.mem_write(syms[_n] + int(_o, 0), bytes([int(_v, 0)]))
if os.environ.get('DROPLOG') and 'g_v3st' in syms:
_d = struct.unpack('<I', u.mem_read(syms['g_v3st'] + 4, 4))[0]
if _d != state.get('drop', 0): print('drop', _d - state.get('drop', 0), 'at ms', state['ms'], 'sh', state['sh']); state['drop'] = _d
if si < len(SH) and state['ms'] >= SH[si] * 1000: shot('shot_%02d.png' % si); si += 1
if 'miss' in state and state['ms'] % 1000 == 0:
_f = struct.unpack('<I', u.mem_read(syms['g_abst'], 4))[0]; _df = max(1, _f - state.get('f0', 0))
print('s %2d frames %3d misses/frame %6.0f reads/frame %7.0f' % (state['ms'] // 1000, _df, state['miss'] / _df, state['acc'] / _df))
state['f0'] = _f; state['miss'] = 0; state['acc'] = 0
st = struct.unpack('<4I', bytes(u.mem_read(syms['g_abst'], 16)))
print('ms run', st[0], 'pictures', st[1], 'ms dropped', st[2], 'last slice ms', st[3])
(os.environ.get('TONES') and print('tones:', state['tone']));print('ms', state['ms'], 'tones', len(state['tone']), 'flash writes', state['flashw'], 'back' if 'back' in state else '', 'pc', hex(pc))
print('ms per clock step (96, 48, 24, 12 MHz):', state['shms'])
open(os.path.join(out, 'flash_after.bin'), 'wb').write(fl)
shot('shot_end.png')
for _d in os.environ.get('DUMP', '').split(','): # test: 'symbol+off:len' printed at the end
if ':' in _d:
_a, _l = _d.split(':'); _n, _o = (_a.split('+') + ['0'])[:2]
print('DUMP', _d, bytes(u.mem_read(syms[_n] + int(_o, 0), int(_l, 0))).hex())
+92
View File
@@ -0,0 +1,92 @@
/* CPU check against simavr: random instruction runs (ALU, branches, skips), registers and SREG after each step.
* gcc -O1 -DAB_SINGLE -o fuzz fuzz.c ../src/core/avr.c -lsimavr -lelf && ./fuzz 3000 */
/* random ALU sequences: our core against simavr */
#include <simavr/sim_avr.h>
#include <simavr/sim_core.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../src/core/avr.h"
extern u32 ab_pc(void);
static u16 fl[AVR_FLASH_WORDS];
static unsigned rr(void) { return (unsigned)rand(); }
static u16 gen(void)
{
unsigned d = rr() & 31, r = rr() & 31, K = rr() & 255, d4 = rr() & 15, b = rr() & 7;
switch (rr() % 40) {
case 0: return 0x0C00 | (r & 16) << 5 | d << 4 | (r & 15); /* ADD */
case 1: return 0x1C00 | (r & 16) << 5 | d << 4 | (r & 15); /* ADC */
case 2: return 0x1800 | (r & 16) << 5 | d << 4 | (r & 15); /* SUB */
case 3: return 0x0800 | (r & 16) << 5 | d << 4 | (r & 15); /* SBC */
case 4: return 0x2000 | (r & 16) << 5 | d << 4 | (r & 15); /* AND */
case 5: return 0x2800 | (r & 16) << 5 | d << 4 | (r & 15); /* OR */
case 6: return 0x2400 | (r & 16) << 5 | d << 4 | (r & 15); /* EOR */
case 7: return 0x1400 | (r & 16) << 5 | d << 4 | (r & 15); /* CP */
case 8: return 0x0400 | (r & 16) << 5 | d << 4 | (r & 15); /* CPC */
case 9: return 0x2C00 | (r & 16) << 5 | d << 4 | (r & 15); /* MOV */
case 10: return 0x5000 | (K & 0xF0) << 4 | d4 << 4 | (K & 15); /* SUBI */
case 11: return 0x4000 | (K & 0xF0) << 4 | d4 << 4 | (K & 15); /* SBCI */
case 12: return 0x7000 | (K & 0xF0) << 4 | d4 << 4 | (K & 15); /* ANDI */
case 13: return 0x6000 | (K & 0xF0) << 4 | d4 << 4 | (K & 15); /* ORI */
case 14: return 0x3000 | (K & 0xF0) << 4 | d4 << 4 | (K & 15); /* CPI */
case 15: return 0x9400 | d << 4 | 0; /* COM */
case 16: return 0x9400 | d << 4 | 1; /* NEG */
case 17: return 0x9400 | d << 4 | 2; /* SWAP */
case 18: return 0x9400 | d << 4 | 3; /* INC */
case 19: return 0x9400 | d << 4 | 5; /* ASR */
case 20: return 0x9400 | d << 4 | 6; /* LSR */
case 21: return 0x9400 | d << 4 | 7; /* ROR */
case 22: return 0x9400 | d << 4 | 10; /* DEC */
case 23: return 0x9C00 | (r & 16) << 5 | d << 4 | (r & 15); /* MUL */
case 24: return 0x0200 | d4 << 4 | (rr() & 15); /* MULS */
case 25: return 0x0300 | (rr() & 0x88) | (rr() & 0x77); /* MULSU FMUL* */
case 26: return 0x9600 | (rr() & 0xFF); /* ADIW */
case 27: return 0x9700 | (rr() & 0xFF); /* SBIW */
case 28: return 0x0100 | (rr() & 0xFF); /* MOVW */
case 29: return 0xFA00 | d << 4 | b; /* BST */
case 30: return 0xF800 | d << 4 | b; /* BLD */
case 31: { static const int B[4] = { 0, 1, 5, 6 }; return 0x9408 | B[rr() & 3] << 4 | ((rr() & 1) << 7); } /* BSET/BCLR of C Z H T */
case 32: return 0xE000 | (K & 0xF0) << 4 | d4 << 4 | (K & 15); /* LDI */
case 34: case 35: return 0xF000 | (rr() & 0x400) | (1 << 3) | (rr() & 7); /* BRBS/BRBC .+1 */
case 36: return 0xFC00 | (rr() & 0x200) | d << 4 | b; /* SBRC/SBRS */
case 37: return 0x1000 | (r & 16) << 5 | d << 4 | (r & 15); /* CPSE */
default: return 0x0000;
}
}
int main(int argc, char **argv)
{
int seeds = argc > 1 ? atoi(argv[1]) : 200, fails = 0;
for (int sd = 1; sd <= seeds; sd++) {
srand(sd);
int n = 200;
for (int i = 0; i < n; i++) { fl[i] = gen(); if (fl[i] == 0x9478 || fl[i] == 0x94F8) fl[i] = 0; { unsigned o = fl[i] & 0xfc0f; if ((o == 0x940c || o == 0x940d || o == 0x940e || o == 0x940f || o == 0x9000 || o == 0x9200) && (fl[i] & 0xFE0F) != 0x9000) fl[i] = 0; } if ((fl[i] & 0xFE0F) == 0x9000 && i + 1 < n) { fl[++i] = 0x0100 + (rr() & 0x7FF); } }
fl[n] = 0xCFFF; /* rjmp . */
avr_t *a = avr_make_mcu_by_name("atmega32u4"); avr_init(a);
avr_loadcode(a, (uint8_t *)fl, (n + 1) * 2, 0);
ab_load(fl, n + 1); ab_reset();
unsigned sreg0 = rr() & 0x6F; sreg0 |= (((sreg0 >> 2) ^ (sreg0 >> 3)) & 1) << 4;
for (int i = 0; i < 32; i++) { u8 v = rr(); a->data[i] = v; A_D[i] = v; }
a->data[R_SREG] = sreg0; for (int i = 0; i < 8; i++) a->sreg[i] = (sreg0 >> i) & 1; A_D[0x5F] = sreg0;
for (int i = 0x100; i < 0xB00; i++) { u8 v = rr(); a->data[i] = v; A_D[i] = v; }
a->pc = 0;
for (int st = 0; st < n; st++) {
u16 w = fl[a->pc / 2];
if (a->pc / 2 >= n) break;
avr_run(a);
ab_run(1);
if (getenv("TR") && sd == atoi(getenv("TR"))) { unsigned s2 = 0; for (int i = 0; i < 8; i++) if (a->sreg[i]) s2 |= 1 << i; printf(" st %d op %04x sreg sim %02x ours %02x pc %x/%x cyc %llu/%u\n", st, w, s2, A_D[0x5F], a->pc/2, ab_pc(), (unsigned long long)a->cycle, A_CYC); }
unsigned s1 = 0; for (int i = 0; i < 8; i++) if (a->sreg[i]) s1 |= 1 << i;
int bad = s1 != A_D[0x5F] || a->pc / 2 != ab_pc(); for (int i = 0; i < 32; i++) if (a->data[i] != A_D[i]) bad = 1;
if (bad) {
printf("seed %d step %d at %x op %04x: sreg sim %02x ours %02x pc sim %x ours %x\n", sd, st, (unsigned)0, w, s1, A_D[0x5F], a->pc/2, ab_pc());
for (int i = 0; i < 32; i++) if (a->data[i] != A_D[i]) printf(" r%d sim %02x ours %02x\n", i, a->data[i], A_D[i]);
fails++; break;
}
}
avr_terminate(a);
if (fails > 10) break;
}
printf("fails %d\n", fails);
return 0;
}
+63
View File
@@ -0,0 +1,63 @@
/* PC test of the ArduboyEmu core: hostab game.hex seconds [KEYS="t:mask,..."] [SHOTS="t,..."] [OUT=dir]
* Writes the display as PGM pictures (128 x 64) at the shot times, prints frames, sound and timing. */
#include "../src/core/avr.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
static u16 g_fl[AVR_FLASH_WORDS];
extern u32 ab_pc(void);
static u32 g_hist[AVR_FLASH_WORDS];
static int hexval(const char *s, int n) { int v = 0; for (int i = 0; i < n; i++) { int c = s[i]; v = v * 16 + (c <= '9' ? c - '0' : (c | 32) - 'a' + 10); } return v; }
static u32 load_hex(const char *fn)
{
FILE *f = fopen(fn, "r"); if (!f) { perror(fn); exit(1); }
u8 *b = (u8 *)g_fl; memset(b, 0xFF, sizeof g_fl);
char l[600]; u32 hi = 0, top = 0;
while (fgets(l, sizeof l, f)) {
if (l[0] != ':') continue;
int n = hexval(l + 1, 2), ad = hexval(l + 3, 4), ty = hexval(l + 7, 2);
if (ty == 0) for (int i = 0; i < n; i++) { u32 a = hi + ad + i; if (a < sizeof g_fl) { b[a] = (u8)hexval(l + 9 + 2 * i, 2); if (a + 1 > top) top = a + 1; } }
else if (ty == 2) hi = hexval(l + 9, 4) << 4;
else if (ty == 4) hi = hexval(l + 9, 4) << 16;
}
fclose(f);
return (top + 1) / 2;
}
static void shot(const char *out, int k)
{
char fn[512]; snprintf(fn, sizeof fn, "%s/shot%02d.pgm", out, k);
FILE *f = fopen(fn, "wb"); fprintf(f, "P5 128 64 255\n");
for (int y = 0; y < 64; y++) for (int x = 0; x < 128; x++) {
int on = (A_GD[(y >> 3) * 128 + x] >> (y & 7)) & 1;
if (A_LCD.invert) on ^= 1;
if (!A_LCD.on) on = 0;
fputc(on ? 255 : 0, f);
}
fclose(f);
}
int main(int argc, char **argv)
{
u32 words = load_hex(argv[1]); double secs = atof(argv[2]);
const char *ks = getenv("KEYS"), *ss = getenv("SHOTS"), *out = getenv("OUT"); if (!out) out = ".";
double kt[64]; u32 km[64]; int nk = 0; double st[64]; int ns = 0;
if (ks) { const char *p = ks; while (*p && nk < 64) { kt[nk] = atof(p); const char *c = strchr(p, ':'); km[nk++] = (u32)atoi(c + 1); p = strchr(c, ','); if (!p) break; p++; } }
if (ss) { const char *p = ss; while (*p && ns < 64) { st[ns++] = atof(p); p = strchr(p, ','); if (!p) break; p++; } }
ab_load(g_fl, words); ab_reset();
for (u32 i = 0; i < AVR_EEP; i++) A_EEP[i] = 0xFF;
clock_t c0 = clock(); int si = 0; u32 tones = 0, lastf = 0;
u32 ms_n = (u32)(secs * 1000);
for (u32 ms = 0; ms < ms_n; ms++) {
double t = ms / 1000.0; A_KEYS = 0; for (int i = 0; i < nk; i++) if (t >= kt[i]) A_KEYS = km[i];
if (getenv("CALLER")) { u32 c = strtoul(getenv("CALLER"), 0, 16); for (u32 e = A_CYC + 16000; (s32)(A_CYC - e) < 0; ) { if (ab_pc() == c) { u32 sp = A_D[0x5D] | A_D[0x5E] << 8; g_hist[((A_D[sp + 1] << 8) | A_D[sp + 2]) & 0x3FFF]++; } ab_run(1); } } else
if (getenv("PCS")) for (int q = 0; q < 16; q++) { ab_run(1000); g_hist[ab_pc() & 0x3FFF]++; } else ab_run(16000);
if (ms % 50 == 49) { u32 hz = ab_tone(800000); if (hz) tones++; }
while (si < ns && t >= st[si]) shot(out, si++);
if (ms % 1000 == 999) { printf("t=%u s frames %u (+%u)\n", (ms + 1) / 1000, A_FRAMES, A_FRAMES - lastf); lastf = A_FRAMES; }
}
while (si < ns) shot(out, si++);
if (getenv("PCS") || getenv("CALLER")) { for (int k = 0; k < 8; k++) { u32 b = 0, bi = 0; for (u32 i = 0; i < AVR_FLASH_WORDS; i++) if (g_hist[i] > b) { b = g_hist[i]; bi = i; } printf("pc %04x (byte %05x) %u\n", bi, bi * 2, b); g_hist[bi] = 0; } }
double el = (double)(clock() - c0) / CLOCKS_PER_SEC;
printf("frames %u, tone windows %u, host %.2f s for %.1f s\n", A_FRAMES, tones, el, secs);
return 0;
}
+10
View File
@@ -0,0 +1,10 @@
#!/bin/bash
# smallest prefix of seed $1 that differs
lo=0; hi=200
while [ $((hi-lo)) -gt 1 ]; do m=$(((lo+hi)/2)); if ./run.sh $1 $m | grep -q ok; then lo=$m; else hi=$m; fi; done
echo "seed $1 first diff at body $hi"
python3 -c "
import sys; sys.path.insert(0,'/tmp/jf'); import gen
p=gen.gen($1,$hi); n=len(gen.gen($1,0))-3
for k,x in enumerate(p[n:n+$hi]): print(k, '%04x'%x)
" | tail -4
+9
View File
@@ -0,0 +1,9 @@
import sys
for d in sys.argv[1:]:
r=open(d+'/ref.txt').read().split(); j=open(d+'/jit.txt').read().split()
out=[]
for k,(a,b) in enumerate(zip(r,j)):
base = 0 if k==0 else 0x100
for i in range(0,len(a),2):
if a[i:i+2]!=b[i:i+2]: out.append('%x:%s/%s'%(base+i//2, a[i:i+2], b[i:i+2]))
print(d, ' '.join(out[:8]))
+83
View File
@@ -0,0 +1,83 @@
import random, sys, struct
def gen(seed, lim=10**9):
R = random.Random(seed); w = []
# init registers r0..r31 via r16
for r in list(range(0, 16)) + list(range(17, 32)):
v = R.randrange(256); w.append(0xE000 | (v & 0xF0) << 4 | (0 << 4) | (v & 15)) # ldi r16, v
w.append(0x2C00 | (r & 16) << 5 | (r & 15) << 4 | 0 | (16 & 16) << 5 | (16 & 15)) # mov r, r16 (placeholder fixed below)
# fix movs: mov rd, r16: 0010 11rd dddd rrrr with r=16 -> r bit4 at bit9
out = []
for i in range(0, len(w), 2):
out.append(w[i]); r = (list(range(0, 16)) + list(range(17, 32)))[i // 2]
out.append(0x2C00 | 0x200 | ((r & 16) << 4) | ((r & 15) << 4) | 0)
v = R.randrange(256); out.append(0xE000 | (v & 0xF0) << 4 | (v & 15))
# SREG: random consistent (S = N^V), no I
s = R.randrange(128) & 0x6F; s |= (((s >> 2) ^ (s >> 3)) & 1) << 4
out.append(0xE010 | (s & 0xF0) << 4 | (s & 15)) # ldi r17, s
out.append(0xBF1F) # out SREG, r17
out.append(0xE0A0); out.append(0xE0B1) # X = 0x100
out.append(0xE0C8); out.append(0xE0D1) # Y = 0x108
out.append(0xE0E0 | 0); out.append(0xE0F1) # Z = 0x100 (r30=0? ldi r30,0)
body = []
n = 120
i = 0
depth = 0
while i < n:
d = R.randrange(32); r = R.randrange(32); K = R.randrange(256); d4 = R.randrange(16); b = R.randrange(8)
c = R.randrange(46)
def dr(op): return op | (r & 16) << 5 | d << 4 | (r & 15)
if c < 10: x = dr([0x0C00,0x1C00,0x1800,0x0800,0x2000,0x2800,0x2400,0x1400,0x0400,0x2C00][c])
elif c < 15: x = [0x5000,0x4000,0x7000,0x6000,0x3000][c-10] | (K & 0xF0) << 4 | d4 << 4 | (K & 15)
elif c < 23: x = 0x9400 | d << 4 | [0,1,2,3,5,6,7,10][c-15]
elif c == 23: x = 0x9C00 | (r & 16) << 5 | d << 4 | (r & 15)
elif c == 24: x = 0x0200 | d4 << 4 | R.randrange(16)
elif c == 25: x = 0x0300 | R.randrange(256) & 0xFF
elif c == 26: x = 0x9600 | R.randrange(256) & 0x3F | 0x00 # adiw r24
elif c == 27: x = 0x9700 | R.randrange(256) & 0x3F
elif c == 28: x = 0x0100 | R.randrange(256)
elif c == 29: x = 0xFA00 | d << 4 | b
elif c == 30: x = 0xF800 | d << 4 | b
elif c == 31: x = 0x9408 | [0,1,5,6][R.randrange(4)] << 4 | R.randrange(2) << 7
elif c in (32, 33): x = 0xF000 | R.randrange(2) << 10 | 1 << 3 | R.choice([0,1,2,3,4,6,7]) # branch .+1 (not on H)
elif c == 34: x = 0xFC00 | R.randrange(2) << 9 | d << 4 | b
elif c == 35: x = 0x1000 | (r & 16) << 5 | d << 4 | (r & 15)
elif c == 36: # ld/st through X, Y, Z (pointers kept in 0x100..0x13F)
if d >= 26: d = 16
x = [0x900C,0x900D,0x9009,0x9001,0x920C,0x920D,0x9209,0x9201,0x8000,0x8200][R.randrange(10)] | d << 4
elif c == 37: # ldd/std Y+q
if d >= 26: d = 17
q = R.randrange(8); x = (0x8008 | (R.randrange(2) << 9) | d << 4 | q)
elif c == 38:
if not depth: continue
if d >= 26: d = 18
x = 0x900F | d << 4; depth -= 1 # pop
elif c == 39: x = 0x920F | d << 4; depth += 1 # push
elif c == 40: x = 0x95C8 # lpm
elif c == 41: x = 0x9004 | d << 4 # lpm rd, Z
elif c == 42: # reset pointers into range
body += [0xE0A0 | R.randrange(16), 0xE0B1, 0xE0C0 | R.randrange(8), 0xE0D1, 0xE0E0 | R.randrange(16), 0xE0F1]; i += 6; continue
elif c == 43: x = 0x0000 # (in rd, SREG: H differs on purpose)
elif c == 44: x = 0x9000 | (d % 26) << 4; body += [0, x, 0x0100 + R.randrange(0x40)]; i += 3; continue # lds
else: x = 0x9200 | d << 4; body += [0, x, 0x0100 + R.randrange(0x40)]; i += 3; continue # sts
# keep the pointers sane: never write r26..r31 with ALU ops
if c < 36 and c not in (28,) and ((x >> 4) & 31) >= 26 and c not in (32, 33, 34, 35, 29, 31): x = 0
if c == 28 and ((x >> 4) & 15) * 2 >= 26: x = 0
if c in (26, 27): x = x & ~0x30 # adiw/sbiw r24 only
body.append(x); i += 1
# avoid skips landing in the middle of a 2-word instruction: put a nop after each 2-word one
fixed = []
for k, x in enumerate(body):
fixed.append(x)
if (x & 0xFE0F) in (0x9000, 0x9200) and k + 1 < len(body): pass
prog = out + fixed[:lim] + [0x0000, 0x0000, 0xCFFF]
return prog
def to_hex(prog, fn):
b = b''.join(struct.pack('<H', x & 0xFFFF) for x in prog)
with open(fn, 'w') as f:
for a in range(0, len(b), 16):
c = b[a:a+16]; s = len(c) + (a >> 8) + (a & 255) + sum(c)
f.write(':%02X%04X00%s%02X\n' % (len(c), a, c.hex().upper(), (-s) & 255))
f.write(':00000001FF\n')
open(fn + '.bin', 'wb').write(b)
if __name__ == '__main__':
to_hex(gen(int(sys.argv[1]), int(sys.argv[3]) if len(sys.argv) > 3 else 10**9), sys.argv[2])
+13
View File
@@ -0,0 +1,13 @@
#include "../../src/core/avr.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static u16 fl[AVR_FLASH_WORDS];
int main(int argc, char **argv)
{
FILE *f = fopen(argv[1], "rb"); memset(fl, 0xFF, sizeof fl); size_t n = fread(fl, 1, sizeof fl, f); fclose(f);
ab_load(fl, (n + 1) / 2); ab_reset();
for (int ms = 0; ms < 30; ms++) ab_run(16000);
for (int i = 0; i < 96; i++) printf("%02x", A_D[i]); printf("\n");
for (int i = 0x100; i < 0x140; i++) printf("%02x", A_D[i]); printf("\n");
}
+10
View File
@@ -0,0 +1,10 @@
#!/bin/bash
# setup: cp * /tmp/jf; cd /tmp/jf; gcc -O1 -o ref ref.c <studio>/ab/src/core/avr.c; cp <studio>/ab/ab.bin <studio>/ab/src/app/ab.elf /tmp/jf (KEEPELF=1 build)
# run.sh seed: compare host interpreter and the device JIT (Unicorn)
s=$1; d=/tmp/jf/w$s${2:+_$2}; mkdir -p $d; cd /tmp/jf
python3 gen.py $s $d/p.hex $2
./ref $d/p.hex.bin > $d/ref.txt
cd /home/claude/studio/ab/test
python3 mkimg.py /tmp/jf/ab.bin $d/p.hex $d/img.bin
OUT=$d DUMP="g_mem+256:96,g_mem+512:64" python3 devab.py /tmp/jf/ab.elf $d/img.bin 40 2>&1 | grep DUMP | awk '{print $3}' > $d/jit.txt
if python3 /tmp/jf/same.py $d; then echo "seed $s ok"; rm -rf $d; else echo "seed $s DIFF"; fi
+5
View File
@@ -0,0 +1,5 @@
import sys
d=sys.argv[1]; r=open(d+'/ref.txt').read().split(); j=open(d+'/jit.txt').read().split()
if len(r)!=2 or len(j)!=2: sys.exit(1)
a=bytearray.fromhex(r[0]); b=bytearray.fromhex(j[0]); a[0x5f]&=0xDF; b[0x5f]&=0xDF
sys.exit(0 if a==b and r[1]==j[1] else 1)
+52
View File
@@ -0,0 +1,52 @@
/* lockstep against simavr on a game: gcc -O1 -DAB_SINGLE -o lock lock.c ../src/core/avr.c -lsimavr -lelf && ./lock game.hex steps
* (interrupts and I/O reads differ between the two: the simulator is followed there) */
/* lockstep: game hex in our core and simavr, instruction by instruction */
#include <simavr/sim_avr.h>
#include <simavr/sim_core.h>
#include <simavr/sim_hex.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../src/core/avr.h"
extern u32 ab_pc(void); extern void ab_set_pc(u32); extern void ab_wake(void);
static u16 fl[AVR_FLASH_WORDS];
int main(int argc, char **argv)
{
uint32_t sz, base; uint8_t *code = read_ihex_file(argv[1], &sz, &base);
long steps = atol(argv[2]);
memset(fl, 0xFF, sizeof fl); memcpy(fl, code, sz);
avr_t *a = avr_make_mcu_by_name("atmega32u4"); a->frequency = 16000000; avr_init(a);
avr_loadcode(a, code, sz, base);
ab_load(fl, (sz + 1) / 2); ab_reset();
long syncs = 0, irqs = 0; unsigned lastpc = 0;
static char hist[64][160]; int hn = 0;
for (long st = 0; st < steps; st++) {
unsigned pc0 = a->pc / 2;
u16 w = fl[pc0];
unsigned spa = a->data[0x5D] | a->data[0x5E] << 8, spb = A_D[0x5D] | A_D[0x5E] << 8, ourpc = ab_pc();
avr_run(a);
ab_run(1);
snprintf(hist[hn++ & 63], 160, "st %ld pc %04x/%04x op %04x sp %04x/%04x r24 %02x/%02x -> %04x/%04x sreg %02x", st, pc0, ourpc, w, spa, spb, a->data[24], A_D[24], a->pc/2, ab_pc(), A_D[0x5F]);
unsigned p1 = a->pc / 2, p2 = ab_pc();
int isld = (w & 0xF800) == 0xB000 || (w & 0xFE0F) == 0x9000 || (w & 0xFC00) == 0x9000 || (w & 0xD200) == 0x8000;
if (p1 != p2) {
int skio = (w & 0xFD00) == 0x9900; if (p1 < 0x56 || p2 < 0x56 || skio || p1 == pc0 || p2 == pc0) { /* one took an interrupt: follow the simulator */
for (int i = 0; i < 32; i++) A_D[i] = a->data[i];
for (int i = 0x100; i < 0xB00; i++) A_D[i] = a->data[i];
A_D[0x5D] = a->data[0x5D]; A_D[0x5E] = a->data[0x5E];
{ unsigned s1 = 0; for (int i = 0; i < 8; i++) if (a->sreg[i]) s1 |= 1 << i; A_D[0x5F] = s1; }
ab_wake(); ab_set_pc(p1); A_CYC = (u32)a->cycle; irqs++; continue;
}
for (int k = 0; k < 40; k++) puts(hist[(hn + 24 + k) & 63]);
printf("step %ld: pc sim %04x ours %04x (from %04x op %04x) cyc sim %llu ours %u\n", st, p1, p2, pc0, w, (unsigned long long)a->cycle, A_CYC); break; }
for (int i = 0; i < 32; i++) if (a->data[i] != A_D[i]) {
if (isld) { A_D[i] = a->data[i]; syncs++; }
else { for (int k = 0; k < 40; k++) puts(hist[(hn + 24 + k) & 63]); printf("step %ld pc %04x op %04x: r%d sim %02x ours %02x\n", st, pc0, w, i, a->data[i], A_D[i]); st = steps; break; }
}
if (0 && a->cycle != A_CYC) { printf("cycles step %ld pc %04x op %04x sim %llu ours %u\n", st, pc0, w, (unsigned long long)a->cycle, A_CYC); break; }
if (0) { for (int k = 0; k < 40; k++) puts(hist[(hn + 24 + k) & 63]); printf("SP differs at step %ld\n", st); break; }
lastpc = pc0;
}
printf("irqs %ld syncs %ld cyc sim %llu ours %u\n", irqs, syncs, (unsigned long long)a->cycle, A_CYC);
return 0;
}
+25
View File
@@ -0,0 +1,25 @@
# test image: ab.bin at 0xA0000 with its settings block, the game at 0x200000, the saves at 0x300000 (16 KB)
# python3 mkimg.py ab.bin game.hex out.bin [flags]
import sys, struct
app, hexf, out = sys.argv[1], sys.argv[2], sys.argv[3]
def hex2bin(fn):
b = bytearray(b'\xff' * 0x8000); top = 0; hi = 0
for l in open(fn):
l = l.strip()
if not l.startswith(':'): continue
n, ad, ty = int(l[1:3], 16), int(l[3:7], 16), int(l[7:9], 16)
if ty == 0:
for i in range(n):
a = hi + ad + i
if a < len(b): b[a] = int(l[9 + 2 * i:11 + 2 * i], 16); top = max(top, a + 1)
elif ty == 2: hi = int(l[9:13], 16) << 4
elif ty == 4: hi = int(l[9:13], 16) << 16
return bytes(b[:top + (top & 1)])
fl = bytearray(b'\xff' * 0x400000)
a = open(app, 'rb').read(); r = hex2bin(hexf)
fl[0xA0000:0xA0000 + len(a)] = a; fl[0x200000:0x200000 + len(r)] = r
flags = int(sys.argv[4]) if len(sys.argv) > 4 else 0
c = 0xA0000 + 0x140
struct.pack_into('<6I16s', fl, c, 0x50584241, 1, 0x200000, len(r), 0x300000, flags, b'ARDUBOY')
struct.pack_into('<12B', fl, c + 40, 4, 32, 8, 16, 1, 2, 0, 0, 0, 0, 0, 0)
open(out, 'wb').write(fl)
+19
View File
@@ -0,0 +1,19 @@
# count instructions per function (PROF=1 in devgb): exec devgb with a block hook
import os, sys, subprocess, bisect, collections
elf = sys.argv[1]
fs = []
for l in subprocess.run(['llvm-nm', '-S', '--size-sort', elf], capture_output=True, text=True).stdout.splitlines():
p = l.split()
if len(p) == 4 and p[2] in 'tT': fs.append((int(p[0], 16) & ~1, int(p[1], 16), p[3]))
fs.sort(); starts = [f[0] for f in fs]
cnt = collections.Counter()
def blk(uc, addr, size, ud):
i = bisect.bisect_right(starts, addr) - 1
if i >= 0 and addr < fs[i][0] + fs[i][1]: cnt[fs[i][2]] += size // 2
else: cnt['?'] += size // 2
import builtins
builtins.__gbprof = (blk, cnt)
exec(open(os.path.join(os.path.dirname(__file__), 'devab.py')).read())
tot = sum(cnt.values())
for n, c in cnt.most_common(25): print('%6.2f%% %s' % (100 * c / tot, n))
+15
View File
@@ -0,0 +1,15 @@
# where the time goes in the translated code: dispatcher stub vs blocks (python3 profj.py elf img ms)
import os, sys, subprocess, collections, builtins
elf = sys.argv[1]
syms0 = {}
for l in subprocess.run(['llvm-nm', elf], capture_output=True, text=True).stdout.splitlines():
p = l.split()
if len(p) == 3: syms0[p[2]] = int(p[0], 16)
cb = syms0['g_code']; cnt = collections.Counter(); tot = [0]
def blk(uc, addr, size, ud):
n = size // 2; tot[0] += n
if cb <= addr < cb + 0x10000: cnt['stub' if addr - cb < 0x50 else 'block'] += n
else: cnt['C'] += n
builtins.__gbprof = (blk, cnt)
exec(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'devab.py')).read())
for k, v in cnt.most_common(): print('%6.2f%% %s' % (100 * v / tot[0], k))
+23
View File
@@ -0,0 +1,23 @@
# instructions per source line (needs an ELF with -g): python3 profl.py elf img ms
import os, sys, subprocess, collections
elf = sys.argv[1]
cnt = collections.Counter()
def blk(uc, addr, size, ud): cnt[addr] += size // 2
import builtins
builtins.__gbprof = (blk, cnt)
exec(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'devab.py')).read())
# expand blocks to instruction addresses roughly: attribute the block to its first address
addrs = sorted(cnt)
out = subprocess.run(['llvm-addr2line', '-e', elf, '-f'] + [hex(a) for a in addrs], capture_output=True, text=True).stdout.splitlines()
# llvm-addr2line with -i prints inline chains; take the first file:line per address
res = collections.Counter(); i = 0; k = 0
lines = out
mp = {}
cur = 0
j = 0
for a in addrs:
fn = lines[j]; loc = lines[j + 1]; j += 2
while j < len(lines) and not lines[j].startswith('0x') and j + 1 < len(lines) and ':' in lines[j + 1] and not lines[j].startswith('/') and lines[j] != '??' and False: j += 2
res[(fn, loc.split('/')[-1])] += cnt[a]
tot = sum(res.values())
for (fn, loc), c in res.most_common(40): print('%6.2f%% %s %s' % (100 * c / tot, fn, loc))