다마고치 연구소 한국어판 소스 공개
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

+224
View File
@@ -0,0 +1,224 @@
# T18Emu for the Tamagotchi Paradise
An emulator for the Tamagotchi Meets and On (TG18 firmware, ARM7TDMI with the
GPEL3101A peripherals) that runs on the Paradise (Cortex-M3, 96 MHz). The
Studio builds it into the ROM together with the user's own 8 MB firmware. No
firmware is part of this repository.
- `t18.bin` and `t18x.bin`: the program. The TamaEmu launcher copies `t18.bin`
(64 KB at most) to PRAM and starts it; `t18x.bin` is the code that is not hot,
run from the flash window (flash 0x0F0000). Its settings block ("PMX8") is at
0x140 and is filled in by the Studio (`src/emu.js`, `t18Patch`). Flag bit 1:
set the clock to the Paradise's time at every start. Flag bit 12 (1.7.3 test7, `SESS_FLAG`): no session; only
the firmware's own save is written, an old session is dropped and the firmware boots as on the toy.
- `src/core`: the core from the T18Emu app by mameise, slimmed down for the
Paradise:
- `t18cpu.c`: ARM7TDMI interpreter. Guest SRAM (0xF8000000) is the Paradise
SRAM, the firmware is reached through a map of 64 KB blocks. Idle rounds:
a round of a loop that changes nothing (same registers, SRAM as before, only
reads of registers that hold still until the next event) is watched once,
then the further rounds up to the next event are skipped. The result is the
same as without skipping, instruction by instruction.
- `t18jit.c`: translator from ARM and Thumb code to Thumb-2 for the
Cortex-M3. A block only runs when the cycle budget covers it, so interrupts
come at the same instruction as in the interpreter; SRAM accesses are
direct, the rest goes to the SoC. `t2enc.h` encodes the instructions.
- `t18soc.c`: the SoC (timers, interrupts, RTC, SPI flash, DMA, LCD, tone).
- `src/app`: the Paradise side (`main.c`): screen, keys, tone, flash writes of
the firmware (two 4 KB sectors held in RAM; empty blocks the firmware writes
get 4 KB sectors from the spare blocks, `T18_SEC_SPARE`), session, clock note.
- `host/ref.c`: the core on the PC as the reference (script commands wait,
press, hash, shot, sram, flash, armprof, acnt).
- `test`: `m3main.c` with `m3run.py` runs the core with the translator in
Unicorn on a Cortex-M3 with the memory of the Paradise (PRAM 64 KB, RAM at
0x20000000 only 4 KB, writes into the PRAM only from the flash window) and compares with the reference (hash lines) and counts
host instructions per emulated second. `devt18.py` runs the whole `t18.bin` on
a simulated Paradise (screen pictures, keys, speed per second).
## Memory on the Paradise
The RAM at 0x20000000 has only 4 KB (mirrored 16 times), and they belong to the
Paradise firmware: nothing of T18Emu is there (1.5.0 put its data there, which
is why it hung on the device). Writing the PRAM while the CPU fetches code from
it corrupts instructions (known from TamaEmu), so the PRAM is only written by
`t18_pram_w16`, which writes whole words (1.6.2: a halfword write on the device
fills the other half of the word with the halfword written last) and runs from the SRAM (in `.data`, like the copy loop of
TamaEmu) with interrupts off. Without `T18_PRAM_WR_SRAM` it runs from the flash
window (1.5.1 to 1.5.3; E1 at the start on the device).
| Where | What |
| --- | --- |
| PRAM 0x00000000 (64 KB) | hot code; from `__jc_start` on (over the start code) the translated code |
| flash window 0x100DF000 (flash 0x0F0000) | the rest of the code (`.xip`), first word "T18X" and the build number |
| SRAM 0x18000000..0x18020000 | guest SRAM 0xF8000000 1:1, except for the hole |
| SRAM 0x1800E600..0x18014400 (the hole) | stack (2 KB, bottom), data, tables, pages for the guest's bytes in the hole |
The guest SRAM is the Paradise SRAM itself (host = guest + 0x20000000). All five
TG18 firmwares only zero 0xF800E600..0xF8014400 at the start and use a few
hundred bytes of it later (both stacks lie above it), so that range holds
T18Emu's own data. The guest's bytes there live in pages of 512 bytes, made on
the first non-zero write (8 pages; out of pages: red screen with code E2).
The translated code checks every SRAM access for the hole (two compares); the
stack pointer is used directly only above it (checked before each block that
uses it).
Errors show a red screen: E1 fault (two columns: PC LR, CFSR fault address, start
stage 1 to 8 and the firmware's PC, r0 r1, r2 r3, r12 xPSR, SP EXC_RETURN, HFSR and
the number of translated blocks with bit 31 set when the translator is off), E6
self test of PRAM code failed (the two results, expected 5A and A5), E2 out of
pages for the hole, E3 stack overflow, E4 the flash part is missing or from
another build, E5 state too big. The wheel goes back to the Paradise.
Holding B while T18Emu starts switches the translator off (interpreter only,
about 60 % speed, for tests on the device).
## Layout in the Paradise flash
| Offset | What |
| --- | --- |
| 0x0A0000 | program (copied to PRAM on start) |
| 0x0C0000 | block map as it is now ("T8MP": spares in use; at +0x144 "T8SS": the sector table of `T18_SEC_SPARE`) |
| 0x0C1000 | clock note ("T8NT": seconds counter and game time when leaving) |
| 0x0C2000 | session ("T8SS": CPU and SoC state, then the 128 KB SRAM) |
| 0x0F0000 | the code part of the program (`t18x.bin`, up to 64 KB) |
| free 64 KB blocks, from 0xF00000 and from 0xD40000 downwards | the firmware's used blocks, then up to 10 spares; the bottom stays for the field saves |
## Build
```
sh src/app/build.sh # arm-none-eabi-gcc; writes t18.bin and t18x.bin
KEEPELF=1 sh src/app/build.sh # keeps src/app/t18.elf for devt18.py
```
## Speed switches (1.6.8)
build.sh sets them (REL). Each one keeps the results bit for bit as the reference (checked without T18_OVERSHOOT):
- T18_IO_FAST: the device registers the firmware polls most (timer control, buttons, interrupt vector and mask) are
read straight from the translator's slow path, without io_rd in the flash window.
- T18_SPCHK_MOD: only blocks that move sp check it at their start (push, pop, add/sub sp; add/mov sp, rX is left
to the interpreter).
- T18_TIERUP: SysTick notes the interrupted pc in the code buffer; a block hit three times while it uses the shared
check routine is translated again with the checks inline.
- T18_IDLE_CAP, T18_IDLE_DISARM, T18_IDLE_PASS: idle tries away from the known idle pc stop after 256 steps; the
known idle pc is given up after 32 failed tries in a row; once tried in a run it no longer stops the translated code.
- T18_XRET: a conditional return from an exception (ldmcc ..., {..., pc}^) no longer splits the interrupt handler.
- T18_CLOCK_AFTER: when the firmware sets its battery clock (first setup), the Paradise's time is applied again
500 ms later.
- T18_RADIO: the Bluetooth module of the Meets/On (SPI 0xC0080000, chip select GPIO 0xC0000064 bit 12) answers
like the real one without a phone (register 0x0A boot/patch/running, register 0x08 bytes waiting, setup
answers, module memory reads, HCI Command Complete). Without it the camera (item box, Special) stayed at READY?
and took no key. About 300 bytes in the SoC struct, outside the saved state.
- T18_TONE_Q: the tone in real time. Tone changes are queued with the game time and played on the Paradise's
clock 300 ms after the first of a sequence; below 100 % a melody keeps its tempo (late by more than 200 ms:
timing starts anew).
- T18_IDLE_MEMO: the last skippable idle round at the known idle pc is kept with every value it read (memory and
registers that hold still); the same start and the same values now skip it without stepping (living room:
~900 rounds a second were single-stepped). The guest flash counts as one value (t18_flash_gen).
- T18_IDLE_BACKOFF=13: tries away from the idle pc back off up to 2000 << 13 master ticks after failing.
- T18_JH_PROBE=16: the block table searches 16 slots (with 8, busy keys pushed each other out before they got hot
and were interpreted every time).
- T18_JT_MUL: multiplicative hash for the indirect jump cache (the old one put 4 of the 10 busiest return
addresses of the egg scene into one set).
- 1.6.8-test3 T18_GROW2: grow up with the clock at x60 only for the game minute before a step (age set just before it),
the step and its animation in real time, 18 s for it before the next jump (test4, was 25 s); the game kept awake (tg18_set_keep_awake,
as Android). x60 all along was too much for the Paradise (slow animation) and let the game's minutes run (hunger,
illness). The Param address is only used inside the guest SRAM (PA_OK). On the PC: GROW2=1 with the script command
grow (T18_GROW_TEST): Bernd's Tama baby to Pompomtchi in 72 s, hunger 6, mood 30, never asleep.
- 1.6.9 test14 T18_SUM_FNV: the row check of present() (rotate by 5, xor per pixel pair) repeats its rotations every
32 pairs (64 pixels), folded to 16 bits for T18_LINK every 16 pairs: equal changes 32 pixels apart cancel, a row of
one colour always gives the same value. Rows that changed stayed old on the panel (AM/PM on the clock, frames in the
stats). Now FNV-1a per pixel pair (multiply). PC model (host/ref.c, FNV=1, STALE=1 prints rows that differ from the
buffer at the end of each pseq): clock page with A, old 1 to 2 rows, new 0. T18_ROW_RR: one row per picture (by
the time) goes out anyway. T18_PRES_FIRST: the row sums at 0x20000D00 are set to 0x5A5A at the start.
T18_WAKE_ASYNC (with WAKE_ASYNC in hw.c): the panel comes on in steps from the main loop (SLPOUT, 125 ms, DISPON,
20 ms, light, then a whole picture) instead of 145 ms of waiting in hw_backlight. In standby the firmware switches
the screen on for about 2 s with each call reminder (PC: every 60 s).
- 1.6.9 test11 and test12 (T18_PRESENT_GATE, presents at each transfer or gated) were worse on the device (slide from
the top, parts missing, old picture left): taken out again in test13, main.c and build.sh are as in test10
(T18_PRESENT_IDLE + T18_PRESENT_STABLE). The panel model in host/ref.c (-DT18_PANEL_MODEL -DT18_PRES_PARA,
POLICY=old|xfer, GATE=1) stays for later work. The code of test12 is in its handover.
- 1.6.8-test7 T18_LINK infrared: CONNECTION, TAMAGOTCHI between two Paradise. As the Android LinkManager the IR byte
stream goes 1:1 to the other device: ur_tx hands each byte to tg18_link_ir_out (sent as 'I' frames of up to 36
bytes, flushed every loop), ur_feed takes them from tg18_link_ir_in at line rate when tg18_link_ir_avail. The parser
takes 5A (PC) and A5 (another Paradise) as start, so two Paradise plugged together at the top talk directly; the Studio does not take part. Link block at 0x20000E00 now checked to stay below 0x20000F00 (test6 was 276 bytes and wrote
into the spare rows). Checked on the PC: host/pair.py runs two ref cores in lockstep (linkrun): playdate, both
connect, the guest appears in the host's room, TOGETHER AGAIN, guest home with PLAYED WITH ....
- 1.6.8-test6 T18_LINK: Bluetooth visits and marriages (mixing-meets.com) over the UART on the contacts (UART1 0x4000B000,
IRQ 37, 460800 8N1 as the flash program). Core: tg18_ble_connect / tg18_ble_from_phone (22 len data into the module's
queue, 64 bytes kept for the module's own answers), tg18_link_out (data for the phone, given by the platform), register
0x0A bit 0x0004 once connected and set up (as Android radio.c). Device: frames 5A type len data sum ('C' connect, 'W'
write, 'P' alive) and A5 .. ('H' hello every second, 'N' notification, 'K' write taken); ring buffer and state at
0x20000E00 (the row sums are 16 bit with T18_LINK). PC side: the bookmarklet in src/app.js (pmxBridge) replaces
navigator.bluetooth on the page with Web Serial. Checked on the PC: host/ref.c "blereplay <capture> <session>" (as
tools/ble/mmphone.py of the Android T18Emu) with Bernd's capture of a visit and marriage: same answers as the real
device (F0 0C 70 A1, F0 0D 04 01), the Tama comes home with an egg, the baby hatches. Navigation on the PC: CONNECTION,
APP, VISIT; back: A until GO BACK? YES, B. Note: a Tama with a call or flag +0x16 bit 7 set does not open CONNECTION.
- 1.6.8-test4 T18_DAY_FIX: the firmware counts the days itself (soft clock +0x2C, days since 2007-12-31, one up when the
hour goes from 23 to 0) and a new start loads them from its save (CONTINUE): time right, date of leaving. The note
(T18_NOTE_SEC) keeps the game's day and the clock's day at leaving (gday, rday; 0xFFFFFFFF in older notes); during the
first 5 minutes, when the game shows that day again, it gets the days since added once (not 23:55 to 0:05). A resumed
session needs nothing (tg18_set_time moves the day counter itself).
- 1.6.8-test3 T18_WAKE_START: 0.6 s after the start a sleeping game (screen dark) gets one short C, as the Android
T18Emu does when it becomes visible. Before, the screen stayed black until a key.
- 1.6.8-test1 T18_GROW (with ASK_EXTRA in ask.c): grow up from the settings (Param block address and the Sanrio flag
from the Studio in the settings at +428/+432, pictures at +436). Items: the Studio writes changed sectors of the
guest flash into the installed program in place (`t18RomWriteGuest` in src/emu.js: mapped blocks, sector table,
new pool sectors) and drops the session.
- test45 T18_SEC_SPARE: spares by the 4 KB sector for empty guest blocks (tables in the Paradise RAM, saved as "T8SS" in
the map sector). With 6 spare blocks the old way lost the 7th block the firmware writes (photo, diary).
- test44: RM_N (48) and W_LOG (32, was 64) can be set with -D; TQ_N 32. With 64 the build no longer fit the hole.
Code that runs before the flash window is set up (Reset_Handler up to hw_init) must stay in the PRAM;
build.sh checks it.
M3 (Minstr per guest second, plus uncached flash reads at 96 each): egg 121.7 -> 98.7, call 84.5 -> 80.5,
living room 75.8 -> 55.6. Exact as before (suite 20 of 20, without T18_OVERSHOOT).
## Tests
```
gcc -O2 -o ref host/ref.c src/core/t18soc.c src/core/t18cpu.c -lz
./ref fw_tg18.bin script.txt
gcc -O2 -DT18_HOLE_LO=0xE600u -DT18_HOLE_HI=0x14400u -o refh host/ref.c src/core/t18soc.c src/core/t18cpu.c -lz # the hole on the PC
sh test/build_m3.sh /tmp/m3.elf -DT18_JIT -DT18_JC_LINKED -DT18_PRAM_WR -DJH_BITS=8 -DJT_BITS=8 -DJ_HOT=8
python3 test/m3run.py /tmp/m3.elf fw_tg18.bin script.txt # same hash lines as ./ref
python3 test/devt18.py src/app/t18.elf paradise_with_t18.bin 30000 # PARA="2026-10-15 18:42:07": a Paradise clock in the SRAM
```
## Power save while the game sleeps (T18_PW, T18_LOOP_XIP, T18_WHEEL_RAW, 1.6.13 test1)
Measured on the PC (ref): without a key the TG18 firmware switches itself off after about 3 minutes (screen dark) and
then only waits for its RTC alarm (once a minute, on for about 100 ms) or a key; the core runs no instructions then
(off_run). The program still ran its loop every ms at 96 MHz (or the eco clock).
- T18_PW: game off, screen dark, no key, tone, link or grow-up: the chip from its internal 12 MHz RC, PLL and crystal
off; deep sleep once caught up, the RTC (1 s) or a key wakes it, the ms tick continues from the RTC (as T7Emu).
The game's time passes in steps of 8 ms with tg18_run_us_off (nothing runs while it is off; when the alarm or a key
switches it on, the platform goes back to 96 MHz first). Not dropped while off; screen dark: up to 5 s behind before
time is dropped (250 ms with the screen on).
- T18_LOOP_XIP: the main loop, present, tq_pump, lk_poll and the font of ask.c run from the flash window: the code
buffer in the PRAM starts at 0x83E4 instead of 0x9154 (+3.4 KB).
- T18_WHEEL_RAW: the wheel's long press is timed with a tick count that is never set ahead (deep sleep).
Device simulation (devt18.py now models clock source and deep sleep), 330 s from the start without a key: game off
from 194 s, then asleep 98 % of the time, awake at 12 MHz 1 %, at 96 MHz for the minute alarms. M3 test bed with the
device's buffer (babyh, 210 s guest, buffer from 0x826C): 63.6 -> 60.2 Minstr per guest second (-5 %), half the
buffer flushes (900 instead of 1817).
## Known addresses in the translator (T18_KNOWN, T18_SPEC, 1.6.13 test2)
M3 profile of the busy scenes: a third of the host time went into the slow path of memory accesses. The firmware
polls 0xD0000064 (SPI busy, always 0) before every register write and moves the bytes of the SPI flash through the
SPI registers 0xC0150000..0C (status, send, answer), six device accesses per byte, each through j_slow.
- T18_KNOWN: per block, registers with a value known while translating (MOV/MVN immediate, ADD/SUB immediate of a
known register or the pc, literal loads; Thumb: MOV/ADD/SUB #imm8, LDR pc, ADR, MOV high). A load or store at a known
address in the SRAM (not the hole, aligned) is done directly; 0xD0000064 is loaded as 0; the SPI registers go
straight to the SPI model (loads inline from the model's words, stores through j_sfw -> tg18_sf_fast).
- T18_SPEC: the same for these device registers when the base register was set before the block (the SPI loops):
the value it has when the block is translated is checked at run time (cmp/bne), otherwise the usual way. The glue
that translates from inside the code buffer (j_chain, the lookup of j_ind) writes r0..r7 into arm7_t first.
- The same accesses in the same order with the same cycles: M3 hash lines identical to the build without them.
M3 test bed (without T18_OVERSHOOT, hash lines compared): SPI phase (making the save) 173 -> 137 Minstr per guest
second (-21 %), the scene after it 107 -> 95 (-12 %), egg 27 -> 25 (-8 %).
+429
View File
@@ -0,0 +1,429 @@
/* PC run of the T18 core with the Paradise memory map (reference for the JIT and the device).
* ref <rom> <script> [csv]
* script: wait <ms> | press <A|B|C|AB..> [ms] | shot [file] | hash | state <file> | time y m d h mi s */
#include "../src/core/t18soc.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zlib.h>
#include <unistd.h>
#include <math.h>
static uint8_t *g_flash;
uint8_t t18_flash_rd(uint32_t a) { return g_flash[a & 0x7FFFFF]; }
void t18_flash_prog(uint32_t a, uint8_t b) { g_flash[a & 0x7FFFFF] &= b; }
void t18_flash_erase(uint32_t a, uint32_t size) { memset(g_flash + (a & 0x7FFFFF), 0xFF, size); }
static tg18_t *T;
#ifdef T18_PROF
static uint32_t *g_armh; static int g_profon;
static FILE *g_tr; static uint64_t g_trend, g_trbeg;
void t18_prof(uint32_t pc, uint32_t thumb) {
if (g_profon) g_armh[(pc >> 2) & 0x3FFFFF]++;
if (g_tr) { arm7_t *c = tg18_cpu(T); if (c->cycles > g_trend || c->cycles < g_trbeg) return;
fprintf(g_tr, "%llu", (unsigned long long)c->cycles); for (int i = 0; i < 16; i++) fprintf(g_tr, " %x", c->r[i]); fprintf(g_tr, " %x %lx\n", c->cpsr & 0xF000003Fu, crc32(0, t18_sram, 0x1F000)); }
}
#endif
static int nshot;
#ifdef T18_HLE_LOG
void t18_hle_log(arm7_t *c, uint32_t a0, uint32_t a1, uint32_t a2, uint32_t a3) { fprintf(stderr, "fill %.1f ms rows %u-%u cols %u-%u\n", (double)c->cycles / c->cyc_mult / 96000.0, a0 & 255, a1 & 255, a2 & 255, a3); }
#endif
#ifdef T18_HLE_FP
void t18_hle_fp(int k, uint32_t fa, uint32_t fp, uint32_t fs) { fprintf(stderr, "hle kind %d fill fp %08xu, pixel fp %08xu, sample fp %08xu\n", k, fa, fp, fs); }
#endif
#ifdef T18_HLE_CHECK
/* samples for the cycle fit (HLE_SAMPLES=file): the counters of t18hle.c and the guest's cycles of the routine */
static int hs_n;
void t18_hle_cfit(const uint32_t *cnt, int n, uint64_t cycles, int clean) {
if (!clean) return; hs_n++;
static FILE *sf; if (!sf && getenv("HLE_SAMPLES")) sf = fopen(getenv("HLE_SAMPLES"), "a");
if (sf) { for (int i = 0; i < n; i++) fprintf(sf, "%u ", cnt[i]); fprintf(sf, "%llu\n", (unsigned long long)cycles); fflush(sf); } }
static void hle_fit(void) { extern uint32_t t18_hle_bad, t18_hle_ok, t18_hle_cbad; fprintf(stderr, "hle check: %u same, %u different, %d samples, %u cycle sums off\n", t18_hle_ok, t18_hle_bad, hs_n, t18_hle_cbad); }
#endif
#ifdef T18_WMAP
uint8_t t18_wmap[512];
#endif
#ifdef T18_IDLE_DBG
static unsigned g_why[8];
extern uint32_t t18_w_bad_addr;
void t18_idle_dbg(int why, uint32_t p0, arm7_t *c, const uint32_t *r0) {
g_why[why]++;
if (c->cycles > 1000000ull && (g_why[why] % 20) == 1) {
fprintf(stderr, "why %d p0 %08x now %08x bad %08x:", why, p0, c->r[15], t18_w_bad_addr);
for (int i = 0; i < 16; i++) if (c->r[i] != r0[i]) fprintf(stderr, " r%d %x->%x", i, r0[i], c->r[i]);
fprintf(stderr, "\n");
}
}
#endif
#ifdef T18_PSTAT
static uint64_t ps_r[512], ps_w[512]; static uint8_t ps_nz[512];
static uint32_t sp_min[32]={0}, sp_max[32]; static uint32_t sp_hist[512];
void *t18_cur_cpu;
void t18_acnt(uint32_t a, uint32_t pc, int wr) { (void)pc; if (t18_cur_cpu) { arm7_t *cc = t18_cur_cpu; uint32_t m = cc->cpsr & 31, sp = cc->r[13]; if (!sp_min[m] || sp < sp_min[m]) sp_min[m] = sp; if (sp > sp_max[m]) sp_max[m] = sp; if (sp - 0xF8000000u < 0x20000u) sp_hist[(sp - 0xF8000000u) >> 8]++; } uint32_t o = a - 0xF8000000u; if (o < 0x20000u) { if (wr) ps_w[o >> 8]++; else ps_r[o >> 8]++; } }
static void ps_snap(void) { for (int i = 0; i < 512; i++) for (int k = 0; k < 256; k++) { uint32_t o = i * 256 + k; uint8_t v = *t18_sram_rp(o); if (v) { ps_nz[i] = 1; break; } } }
#endif
#if defined(T18_ACNT) && !defined(T18_PSTAT)
#include <stdint.h>
static uint32_t ak[1<<16], av[1<<16]; static uint32_t *kk; static int acn_on;
void t18_acnt(uint32_t a, uint32_t pc, int wr) {
if (!acn_on) return;
uint32_t key = (a & 0xFFFFFFFC) | wr; uint32_t h = (key * 2654435761u) >> 16;
while (ak[h] && ak[h] != key) h = (h + 1) & 0xFFFF;
ak[h] = key; av[h]++;
(void)kk;
}
#endif
#ifdef T18_LINK
/* test6: the phone side for the link (as tools/ble/mmphone.py of the Android T18Emu): notifications from the module */
static uint8_t lk_n[4096][24]; static int lk_nl[4096], lk_h, lk_t;
void tg18_link_out(const uint8_t *d, int n) { if (n > 24) n = 24; memcpy(lk_n[lk_t & 4095], d, (size_t)n); lk_nl[lk_t & 4095] = n; lk_t++; }
static void lk_run(int ms) { for (int i = 0; i < ms; i++) tg18_run_us(T, 1000); }
static void lk_send(const uint8_t *d, int n) { int k = 0; for (; k < 20000 && !tg18_ble_from_phone(T, d, n); k++) tg18_run_us(T, 1000); if (k >= 20000) printf(" write not taken (ready %d)\n", tg18_ble_ready(T)); }
/* wait for a notification starting with a, b (ms); returns its index or -1; everything before it is dropped */
static int lk_wait(int a, int b, int ms) {
for (int i = 0; i <= ms; i++) { while (lk_h < lk_t) { int k = lk_h++ & 4095; if (lk_nl[k] >= 2 && lk_n[k][0] == a && lk_n[k][1] == b) return k; } if (i < ms) tg18_run_us(T, 1000); }
return -1;
}
static void lk_hex(const char *tag, int k) { printf("%s", tag); if (k < 0) { printf(" none\n"); return; } for (int i = 0; i < lk_nl[k]; i++) printf(" %02X", lk_n[k][i]); printf("\n"); }
/* test7: infrared between two refs (visit of two Paradise): LKR/LKW are pipe fds from the driver; "linkrun <ms>"
* runs in lockstep, 1 ms at a time, exchanging what each infrared port sent */
static uint8_t ir_o[8192], ir_i[65536]; static int ir_on, ir_ih, ir_it;
void tg18_link_ir_out(uint8_t b) { if (ir_on < (int)sizeof ir_o) ir_o[ir_on++] = b; }
int tg18_link_ir_avail(void) { return ir_ih != ir_it; }
int tg18_link_ir_in(uint8_t *b) { if (ir_ih == ir_it) return 0; *b = ir_i[ir_ih++ & 65535]; return 1; }
static void lk_pairstep(void) {
static int fr = -2, fw = -1; if (fr == -2) { const char *a = getenv("LKR"), *b = getenv("LKW"); fr = a ? atoi(a) : -1; fw = b ? atoi(b) : -1; }
if (fr < 0 || fw < 0) return;
uint16_t n = (uint16_t)ir_on; if (write(fw, &n, 2) != 2 || (n && write(fw, ir_o, n) != n)) exit(3); ir_on = 0;
uint16_t m; if (read(fr, &m, 2) != 2) exit(3);
for (int got = 0; got < m;) { uint8_t tmp[512]; int k = read(fr, tmp, m - got > 512 ? 512 : m - got); if (k <= 0) exit(3); for (int i = 0; i < k; i++) ir_i[ir_it++ & 65535] = tmp[i]; got += k; }
}
/* replay session si of a Lauschposten capture: each phone message (F0 8D .. F0 CD) is written, then the device's status
* F0 0C is awaited, F0 8E 0D asks for its answer F0 0D .. F0 4D */
static void lk_replay(const char *fn, int si) {
static uint8_t w[3000][24]; static int wl[3000]; int nw = 0, sess = -1, inmsg = 0;
FILE *f = fopen(fn, "r"); if (!f) { printf("no capture\n"); return; }
char line[512];
int start[200], nm = 0;
while (fgets(line, sizeof line, f)) {
if (strstr(line, "Benachrichtigung EIN")) { sess++; inmsg = 0; continue; }
if (sess != si) continue;
char *q = strstr(line, "<< fff2"); if (!q) continue;
q = strchr(q, ':'); if (!q) continue; q++;
uint8_t b[24]; int n = 0; unsigned x; int c;
while (n < 24 && sscanf(q, " %2x%n", &x, &c) == 1) { b[n++] = (uint8_t)x; q += c; }
if (n >= 2 && b[0] == 0xF0 && b[1] == 0x8D) { inmsg = 1; start[nm++] = nw; }
if (n == 3 && b[0] == 0xF0 && b[1] == 0x8E && b[2] == 0x0D) continue;
if (!inmsg || nw >= 3000) continue;
memcpy(w[nw], b, (size_t)n); wl[nw++] = n;
if (n >= 2 && b[0] == 0xF0 && b[1] == 0xCD) inmsg = 0;
}
fclose(f); start[nm] = nw;
printf("session %d: %d messages, %d writes\n", si, nm, nw);
tg18_ble_connect(T, 1); lk_run(500); printf(" module set up: %d\n", tg18_ble_ready(T));
for (int m = 0; m < nm; m++) {
for (int i = start[m]; i < start[m + 1]; i++) { lk_send(w[i], wl[i]); lk_run(2); }
lk_hex(" status", lk_wait(0xF0, 0x0C, 8000));
lk_run(700);
static const uint8_t rq[3] = { 0xF0, 0x8E, 0x0D }; lk_send(rq, 3);
int h = lk_wait(0xF0, 0x0D, 8000); lk_hex(" answer", h);
int bytes = 0, e = -1;
for (int i = 0; i < 20000 && e < 0; i++) { while (lk_h < lk_t) { int k = lk_h++ & 4095; if (lk_nl[k] >= 2 && lk_n[k][0] == 0xF0 && lk_n[k][1] == 0x4D) { e = k; break; } bytes += lk_nl[k]; } if (e < 0) tg18_run_us(T, 1000); }
printf(" answer data %d bytes\n", bytes); lk_hex(" end", e);
lk_hex(" status", lk_wait(0xF0, 0x0C, 3000));
}
lk_run(2000); tg18_ble_connect(T, 0); lk_run(3000);
}
#endif
static uint32_t fnv(const uint8_t *p, size_t n, uint32_t h) { for (size_t i = 0; i < n; i++) h = (h ^ p[i]) * 16777619u; return h; }
/* hash over guest SRAM 0xF8000000..0xF801FFFF, whatever part is direct */
/* hash over the guest's view of its SRAM (with a hole: its pages, not the host bytes) */
static uint32_t sram_hash(void) { uint32_t h = 2166136261u; for (uint32_t o = 0; o < T18_SRAM_SIZE; o += 256) h = fnv(t18_sram_rp(o), 256, h); return h; }
#if T18_HOLE_HI > T18_HOLE_LO
static uint8_t g_pool[64][T18_HOLE_PG]; static int g_pool_n;
static uint8_t *hole_new(void) { if (g_pool_n >= (getenv("T18_NPOOL") ? atoi(getenv("T18_NPOOL")) : 64)) 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; }
#endif
#ifdef T18_PANEL_MODEL
/* 1.6.9 (test11): the Paradise's panel on the PC. The core hands the scanned buffer 30 times a second (T18_PRES_PARA);
* the policy of main.c decides when rows go to the panel (POLICY=old: T18_PRESENT_IDLE+STABLE, POLICY=calm:
* T18_PRESENT_CALM). pshot writes what the panel shows (backlight off: darkened). */
int t18_new_off; static uint32_t MQ = 16; static int m_xfer; static void m_present(int force); extern int m_endidle; static uint32_t m_ms; static uint32_t m_src, m_len; static uint16_t m_panel[128][128]; static uint32_t m_sum[128]; static int m_on, m_calm;
static void m_present_cb(void *u, uint32_t src, uint32_t len) { (void)u; if (getenv("SRCLOG") && (src != m_src || len != m_len)) fprintf(stderr, "src %08x len %u at %u\n", src, len, m_ms); m_src = src; m_len = len; if (m_xfer && m_on) m_present(0); }
static const uint16_t *m_row(uint32_t a) { uint32_t o = a - 0xF8000000u; static uint16_t tmp[128]; if (o >= T18_SRAM_SIZE - 256u) { memset(tmp, 0, 256); return tmp; } for (int i = 0; i < 256; i++) ((uint8_t *)tmp)[i] = *t18_sram_rp(o + i); return tmp; }
static int m_gate, m_full = 1; static uint32_t m_gate_ms;
static int m_held(void) { uint32_t rows = m_len / 256u, key = 0, black = 0; if (rows > 128) rows = 128;
for (uint32_t y = 0; y < rows; y++) { const uint16_t *p = m_row(m_src + y * 256u); int z = 1; for (int i = 0; i < 128; i++) { if (p[i] < 0x20u && p[i] && p[i] != 0x000Cu) key++; if (p[i]) z = 0; } black += (uint32_t)z; }
if (getenv("GDBG") && (key || black)) fprintf(stderr, "gate t=%u key=%u black=%u\n", m_ms, key, black);
if (key < 8u && black < 8u) { m_gate_ms = 0; return 0; }
if (!m_gate_ms) m_gate_ms = m_ms ? m_ms : 1; return m_ms - m_gate_ms < 1000u; }
static void m_present(int force) {
if (!m_len) return;
if (m_gate && !force && m_held()) return;
if (m_gate && m_full) force = 1; uint32_t rows = m_len / 256u; if (rows > 128) rows = 128;
static int fnv = -1; if (fnv < 0) fnv = getenv("FNV") != 0; /* test14: T18_SUM_FNV */
for (uint32_t y = 0; y < rows; y++) { const uint16_t *p = m_row(m_src + y * 256u); uint32_t sum = 0x9E3779B9u;
if (fnv) { sum = 0x811C9DC5u; for (int i = 0; i < 128; i += 2) sum = (sum ^ ((uint32_t)p[i] | (uint32_t)p[i + 1] << 16)) * 0x01000193u; sum ^= sum >> 13; }
else for (int i = 0; i < 128; i += 2) sum = (sum << 5 | sum >> 27) ^ ((uint32_t)p[i] | (uint32_t)p[i + 1] << 16);
sum ^= sum >> 16; sum &= 0xFFFF;
if (force || sum != m_sum[y]) memcpy(m_panel[y], p, 256); m_sum[y] = sum; }
m_full = 0;
}
static uint32_t m_hash(int step) { uint32_t h = 0x811C9DC5u, rows = m_len / 256u; if (rows > 128) rows = 128;
for (uint32_t y = 0; y < rows; y++) { const uint16_t *p = m_row(m_src + y * 256u); for (int i = 0; i < 128; i += step) h = (h ^ p[i]) * 16777619u; } return h; }
static int m_cleared(void) { uint32_t rows = m_len / 256u, n = 0; if (rows > 128) rows = 128;
for (uint32_t y = 0; y < rows; y++) { const uint16_t *p = m_row(m_src + y * 256u); int z = 1; for (int i = 0; i < 128; i++) if (p[i]) { z = 0; break; } n += z; } return n >= 24; }
static void m_tick(void) {
arm7_t *c = tg18_cpu(T); static uint64_t ic0, cy0; static uint32_t pt;
int on = tg18_power(T) && tg18_backlight(T) > 0;
if (m_xfer) { static int bl = -1; m_on = on; if (on != bl) { bl = on; if (on) { if (m_gate) m_full = 1; else m_present(1); } } return; }
if (!m_calm) {
static int bl = -1; if (on != bl) { if (getenv("BLLOG")) { uint32_t r_[4] = {0};
#ifdef T18_BLDBG
void tg18_bl_regs(tg18_t *, uint32_t *); tg18_bl_regs(T, r_); /* timer B (the light's PWM) */
#endif
fprintf(stderr, "bl %d at %u (power %d light %d) tb %x %x %x %x\n", on, m_ms, tg18_power(T), tg18_backlight(T), r_[0], r_[1], r_[2], r_[3]); } bl = on; m_on = on; if (on) { if (m_gate) m_full = 1; else m_present(1); } }
uint64_t ic = c->idle_cycles, cy = c->cycles; uint32_t tn = m_ms; int waited = (ic - ic0) * 4u > cy - cy0;
static uint32_t ht, h_last;
if (getenv("NEEDEND") && !m_endidle) waited = 0;
if (getenv("CONFIRM")) { static uint32_t ch; static int cd; int w = waited; waited = 0;
if (!w) cd = 0; else if (m_on && m_len && tn - pt >= 33u) { uint32_t h = m_hash(1); if (cd && h == ch) { waited = 1; cd = 0; } else { cd = 1; ch = h; } } }
if (m_on && m_len && waited && tn - pt >= 33u) { pt = tn; ht = tn; if (getenv("PLOG")) { static int k; char fn[64]; snprintf(fn, sizeof fn, "%s%04d_%d.raw", getenv("PLOG"), k++, m_endidle); FILE *o = fopen(fn, "wb"); uint32_t rows = m_len / 256u; for (uint32_t y = 0; y < 128; y++) fwrite(y < rows ? m_row(m_src + y * 256u) : m_panel[0], 2, 128, o); fclose(o); } m_present(0); }
else if (getenv("STABLE32")) { static uint32_t st, sh, shown;
if (m_on && m_len && tn - st >= 32u) { st = tn; uint32_t h = m_hash(1); if ((h == sh && h != shown && tn - pt >= 33u) || tn - pt >= 5000u) { pt = tn; shown = h; m_present(0); } sh = h; } }
else if (m_on && m_len && tn - ht >= 250u) { ht = tn; uint32_t h = m_hash(3); if ((h == h_last && tn - pt >= 250u) || tn - pt >= 5000u) { pt = tn; m_present(0); } h_last = h; }
ic0 = ic; cy0 = cy; return;
}
/* calm (the same as main.c): every 8 ms a check value of the picture; a picture goes out when the firmware
* waited in these 8 ms and the picture is the same as 8 ms before, or it holds still for 250 ms; after waking
* the first one goes out whole, and not while it is still the cleared buffer (2 s at most) */
static uint32_t h_prev, h_shown, t_shown, t_same, wake_t, n, t_busy; static int was_on, full = 1;
static uint64_t wi0, wc0;
m_on = on; if (!on || !m_len) { was_on = 0; ic0 = c->idle_cycles; cy0 = c->cycles; return; }
if ((++n & 1u)) return; /* every 8 ms */
uint64_t ic = c->idle_cycles, cy = c->cycles;
if (getenv("IDBG")) fprintf(stderr, "%u:%d ", m_ms, (int)((ic - wi0) * 100 / (cy - wc0 + 1)));
int idle = (ic - wi0) * 2u > cy - wc0; wi0 = ic; wc0 = cy; /* half of these 8 ms or more */ (void)ic0; (void)cy0; /* idle half of these 16 ms or more */
uint32_t tn = m_ms;
if (!idle) t_busy = tn;
if (!was_on) { was_on = 1; wake_t = tn; full = 1; h_shown = 0; }
uint32_t h = m_hash(4);
if (h != h_prev) t_same = tn; h_prev = h;
if (h == h_shown) return;
int quiet = (tn - t_busy < 16u) ? (tn - t_same >= 300u) : (tn - t_same >= MQ); /* busy: only a picture that settled */
int go = (quiet && tn - t_shown >= 33u) || tn - t_shown >= 1500u;
if (!go) return;
if (tn - wake_t < 2000u && m_cleared()) return;
if (m_cleared() && tn - t_shown < 1000u) return;
if (getenv("PDBG")) fprintf(stderr, "present t=%u quiet=%d same=%u busy=%u shown=%u\n", tn, quiet, tn - t_same, tn - t_busy, tn - t_shown);
m_present(full); full = 0; h_shown = h; t_shown = tn; (void)pt;
}
int m_endidle = 1; static int m_pn;
static void m_seclog(void) { static int on = -1; static uint32_t hl, tl; if (on < 0) on = getenv("SECLOG") != 0; if (!on) return;
uint32_t h = 0x811C9DC5u; for (int y = 66; y < 80; y++) for (int x = 78; x < 95; x++) h = (h ^ m_panel[y][x]) * 16777619u;
if (h != hl) { fprintf(stderr, "sec %u +%u\n", m_ms, m_ms - tl); hl = h; tl = m_ms; } }
static void m_run_ms(double ms) { static int sp, eu = -1; if (!sp) sp = getenv("SPEED") ? atoi(getenv("SPEED")) : 100; if (eu < 0) eu = getenv("ENDUS") ? atoi(getenv("ENDUS")) : 0;
for (uint32_t i = 0; i < (uint32_t)(ms / 4); i++) {
if (eu) { arm7_t *c = tg18_cpu(T); tg18_run_us(T, 4000 - eu); uint64_t i0 = c->idle_cycles, c0 = c->cycles; tg18_run_us(T, eu); m_endidle = (c->idle_cycles - i0) * 2u >= c->cycles - c0; }
else tg18_run_us(T, 4000);
m_ms += 400u / (uint32_t)sp; m_tick(); m_seclog(); } }
static void m_shot(const char *fn) { FILE *o = fopen(fn, "wb"); for (int y = 0; y < 128; y++) for (int x = 0; x < 128; x++) { uint16_t v = m_panel[y][x]; if (!m_on) v = (uint16_t)((v >> 2) & 0x39E7); fwrite(&v, 2, 1, o); } fclose(o); }
#endif
int main(int argc, char **argv)
{
if (argc < 3) { fprintf(stderr, "ref <rom> <script>\n"); return 1; }
g_flash = malloc(0x800000); memset(g_flash, 0xFF, 0x800000);
if (getenv("T18_NOIDLE")) t18_idle_on = 0;
FILE *f = fopen(argv[1], "rb"); size_t n = fread(g_flash, 1, 0x800000, f); fclose(f);
t18_sram = calloc(1, T18_SRAM_SIZE);
#if T18_HOLE_HI > T18_HOLE_LO
memset(t18_sram + T18_HOLE_LO, 0xA5, T18_HOLE_HI - T18_HOLE_LO); /* not the guest's: must never be used */
t18_hole_new = hole_new; t18_hole_free = hole_free;
#endif
for (int i = 0; i < 128; i++) t18_fblk[i] = g_flash + (i << 16);
T = calloc(1, tg18_struct_size());
#ifdef T18_PSTAT
{ extern void *t18_cur_cpu; t18_cur_cpu = tg18_cpu(T); }
#endif
tg18_init(T, g_flash, (uint32_t)n);
tg18_set_time(T, 2026, 10, 15, 8, 0, 0);
#ifdef T18_PANEL_MODEL
tg18_set_present(T, m_present_cb, 0); m_calm = getenv("POLICY") && !strcmp(getenv("POLICY"), "calm"); if (getenv("MQ")) MQ = (uint32_t)atoi(getenv("MQ")); m_xfer = getenv("POLICY") && !strcmp(getenv("POLICY"), "xfer"); m_gate = getenv("GATE") != 0;
#endif
#ifdef T18_PROF
if (argc > 4) { g_tr = fopen(argv[3], "w"); g_trend = strtoull(argv[4], 0, 0); if (argc > 5) g_trbeg = strtoull(argv[5], 0, 0); }
#endif
FILE *sc = fopen(argv[2], "r"); char l[256];
while (fgets(l, sizeof l, sc)) {
char cmd[32], a[128] = ""; int k = sscanf(l, "%31s %127s", cmd, a); if (k < 1) continue;
#ifdef T18_HLE_FILL
{ extern uint32_t t18_hle_q; if (getenv("HLE_Q")) t18_hle_q = (uint32_t)atoi(getenv("HLE_Q")); }
if (t18_hle_pc == 1u && t18_hle_find()) fprintf(stderr, "hle fill at %08x\n", t18_hle_pc);
#endif
if (!strcmp(cmd, "wait")) {
arm7_t *c = tg18_cpu(T); uint64_t c0 = c->cycles, i0 = c->idle_cycles, s0 = c->idle_skipped;
tg18_run_us(T, (uint32_t)(atof(a) * 1000));
#ifdef T18_PSTAT
ps_snap();
#endif
if (getenv("T18_ACT")) fprintf(stderr, "mult %u wait %6.0f ms: active %5.1f%% skipped %5.1f%% halted %5.1f%%\n", c->cyc_mult, atof(a),
100.0 * (double)(c->cycles - c0 - (c->idle_cycles - i0)) / (double)(c->cycles - c0),
100.0 * (double)(c->idle_skipped - s0) / (double)(c->cycles - c0),
100.0 * (double)((c->idle_cycles - i0) - (c->idle_skipped - s0)) / (double)(c->cycles - c0));
}
#ifdef T18_GROW_TEST
/* grow <adult 0..9 or -1> <param hex>: the grow-up of main.c (T18_GROW), step by step on the PC */
else if (!strcmp(cmd, "grow")) {
static const uint8_t AG[10] = {0,0,0,0,0,1,1,1,1,1}, AM[10] = {0,0,0,2,7,0,0,0,2,7}, AV[10] = {0,5,10,0,0,0,0,5,0,0};
static const uint16_t AO[10] = {0,0x140,0x141,0,0,0,0x144,0x145,0,0}, AT[4] = {0, 0x3C, 0x5DC, 0xB7C};
int who = atoi(a); unsigned pa = 0; sscanf(l, "%*s %*s %x", &pa); uint32_t P = pa - 0xF8000000u;
#define RD(o, n) ({ uint32_t v_ = 0; for (int i_ = 0; i_ < (n); i_++) v_ |= (uint32_t)*t18_sram_rp(P + (o) + i_) << (8 * i_); v_; })
#define WR(o, v, n) do { for (int i_ = 0; i_ < (n); i_++) t18_sram_wr(P + (o) + i_, ((v) >> (8 * i_)) & 0xFF, 1); } while (0)
int g2 = getenv("GROW2") != NULL, wakes = 0; unsigned gst = 0xFF; int hold = -1; /* test3: T18_GROW2 of main.c */
if (g2) tg18_set_keep_awake(T, 1); else tg18_set_clock_mult(T, 60);
int miss = -1, last = -1;
for (int t = 0; t < 4000; t++) {
if (!tg18_power(T)) { wakes++; tg18_set_buttons(T, 4); tg18_run_us(T, 120000); tg18_set_buttons(T, 0); }
tg18_run_us(T, 100000);
if (getenv("GSHOT") && (t % 20) == 0 && t < 600) { char fn[64]; snprintf(fn, sizeof fn, "%s%03d.raw", getenv("GSHOT"), t / 10); FILE *o = fopen(fn, "wb"); fwrite(tg18_picture(T), 2, 128 * 128, o); fclose(o); }
if (!RD(0, 3) && !RD(0x52, 1)) continue;
if (RD(0x16, 1) & 0x10) { fprintf(stderr, "grow: gone\n"); break; }
uint32_t st = RD(0x52, 1);
if (st != (uint32_t)last) { fprintf(stderr, "grow: t=%.1f s stage %u age %u gen %u\n", t / 10.0, st, RD(0x1C, 4), RD(0x3A, 2)); last = (int)st; }
if (st == 0) continue;
if (miss < 0) { miss = (int)RD(0x14, 1); int tm[6]; tg18_get_time(T, tm); if (tm[3] < 8 || tm[3] >= 19) tg18_set_time(T, tm[0], tm[1], tm[2], 12, 0, 0); }
if (st >= 4) { WR(0x14, (uint32_t)miss, 1); if (RD(0x36, 1) < 3) WR(0x36, 3, 1); WR(0x11, 100, 1); fprintf(stderr, "grow: adult, character %u\n", RD(0, 2)); break; }
if (RD(0x05, 1) < 6) WR(0x05, 6, 1);
if (RD(0x11, 1) < 30) WR(0x11, 30, 1);
{ uint32_t fl = RD(0x16, 1); if (fl & 1) { WR(0x16, fl & 0xFE, 1); WR(0x18, 0, 2); WR(0x0C, RD(0x0C, 1) & 0xF7, 1); } }
if (st == 3 && who >= 0 && RD(0x3A, 2) < 2) { WR(0x04, AG[who], 1); WR(0x14, AM[who], 1); for (int i = 0; i < 8; i++) WR(0x13E + i, 0, 1); if (AO[who]) WR(AO[who], AV[who], 1); }
if (g2) { if (st != gst) { if (gst != 0xFF) hold = t; gst = st; }
if (hold >= 0) { if (t - hold < 250) { tg18_set_clock_mult(T, getenv("HOLDMULT") ? atoi(getenv("HOLDMULT")) : 1); continue; } hold = -1; } }
uint32_t age = RD(0x1C, 4);
if (st <= 3 && (age < AT[st] - 1u || age > AT[st] + 5u)) { WR(0x1C, AT[st] - 1u, 4); age = AT[st] - 1u; }
if (g2) tg18_set_clock_mult(T, (st <= 3 && age < AT[st]) ? 60 : 1);
if (g2 && (t % 50) == 0) fprintf(stderr, "grow: t=%.1f st %u age %u hunger %u mood %u ill %u mult %d\n", t / 10.0, st, RD(0x1C, 4), RD(0x05, 1), RD(0x11, 1), RD(0x16, 1) & 1, tg18_clock_mult(T));
}
if (g2) { tg18_set_keep_awake(T, 0); fprintf(stderr, "grow: wakes %d\n", wakes); }
tg18_set_clock_mult(T, 1);
}
#endif
#ifdef T18_PANEL_MODEL
else if (!strcmp(cmd, "mwait")) m_run_ms(atof(a));
else if (!strcmp(cmd, "mpress")) { /* mpress <keys> [ms]: as press, the panel model running */
int m = 0; for (char *p = a; *p; p++) m |= *p == 'A' ? 1 : *p == 'B' ? 2 : *p == 'C' ? 4 : 0;
double ms = 150; sscanf(l, "%*s %*s %lf", &ms); tg18_set_buttons(T, m); m_run_ms(ms); tg18_set_buttons(T, 0); }
else if (!strcmp(cmd, "mdown")) { int m = 0; for (char *p = a; *p; p++) m |= *p == 'A' ? 1 : *p == 'B' ? 2 : *p == 'C' ? 4 : 0; tg18_set_buttons(T, m); } /* keys held from now (test11) */
else if (!strcmp(cmd, "mup")) tg18_set_buttons(T, 0);
#ifdef T18_BLDBG
else if (!strcmp(cmd, "irqt")) { /* irqt <n>: raise interrupt n for 1 ms, the device accesses meanwhile */
extern int t18_iotrace; void tg18_irq_dbg(tg18_t *, int, int);
t18_iotrace = 1; tg18_irq_dbg(T, atoi(a), 1); tg18_run_us(T, 300); tg18_irq_dbg(T, atoi(a), 0); tg18_run_us(T, 700); t18_iotrace = 0; fprintf(stderr, "-- end irq %s\n", a); }
else if (!strcmp(cmd, "trace")) { extern int t18_iotrace; t18_iotrace = atoi(a); }
else if (!strcmp(cmd, "reg")) { uint32_t tg18_reg_dbg(tg18_t *, uint32_t); unsigned a_ = (unsigned)strtoul(a, 0, 16); fprintf(stderr, "reg %08x = %08x\n", a_, tg18_reg_dbg(T, a_)); }
#endif
else if (!strcmp(cmd, "pshot")) m_shot(a);
else if (!strcmp(cmd, "slowrun")) { /* slowrun <ms> <pct>: the emulation at pct % of real time, time dropped as in main.c */
double ms = atof(a), pct = 88; sscanf(l, "%*s %*s %lf", &pct); double emu = 0, real = 0, lag = 0; uint32_t lost = 0;
for (real = 0; real < ms; real += 4) {
emu += 4 * pct / 100.0;
while (emu >= 4) { tg18_run_us(T, 4000); emu -= 4; m_tick(); }
m_ms += 4; m_seclog();
lag += 4 - 4 * pct / 100.0;
if (lag > 250) { uint32_t d = (uint32_t)(lag - 250); lag -= d; lost += d; if (lost >= 1000) { tg18_advance_offline(T, lost / 1000); lost %= 1000; } }
} }
else if (!strcmp(cmd, "fdur")) { /* fdur <ms>: how long each distinct picture of the buffer stays (4 ms steps) */
double ms = atof(a); uint32_t hl = 0, t0 = 0, k2 = 0;
for (uint32_t t = 0; t < (uint32_t)ms; t += 4) { tg18_run_us(T, 4000); uint32_t h = m_len ? m_hash(1) : 0;
if (h != hl) { if (t) fprintf(stderr, "%u ", t - t0); hl = h; t0 = t; if (getenv("FDUMP")) { char fn[64]; snprintf(fn, sizeof fn, "f%04u.raw", k2); FILE *o = fopen(fn, "wb"); uint32_t rows = m_len / 256u; for (uint32_t y = 0; y < 128; y++) fwrite(y < rows ? m_row(m_src + y * 256u) : m_panel[0], 2, 128, o); fclose(o); } k2++; } }
fprintf(stderr, "\n"); }
else if (!strcmp(cmd, "pseq")) { /* pseq <prefix> <ms> <step ms>: panel shots while running */
double ms = 1000, st = 20; sscanf(l, "%*s %*s %lf %lf", &ms, &st); int k2 = 0;
for (double t = 0; t < ms; t += st) { m_run_ms(st); char fn[200]; snprintf(fn, sizeof fn, "%s%03d.raw", a, k2++); m_shot(fn); }
if (getenv("STALE") && m_on && m_len) { int n = 0; uint32_t rows = m_len / 256u; if (rows > 128) rows = 128; for (uint32_t y = 0; y < rows; y++) if (memcmp(m_panel[y], m_row(m_src + y * 256u), 256)) n++; fprintf(stderr, "stale rows at the end of %s: %d\n", a, n); } }
#endif
else if (!strcmp(cmd, "press")) {
int m = 0; for (char *p = a; *p; p++) m |= *p == 'A' ? 1 : *p == 'B' ? 2 : *p == 'C' ? 4 : 0;
double ms = 150; sscanf(l, "%*s %*s %lf", &ms);
tg18_set_buttons(T, m); tg18_run_us(T, (uint32_t)(ms * 1000)); tg18_set_buttons(T, 0);
} else if (!strcmp(cmd, "shot")) {
char fn[160]; if (k > 1) snprintf(fn, sizeof fn, "%s", a); else snprintf(fn, sizeof fn, "shot%02d.raw", nshot++);
FILE *o = fopen(fn, "wb"); fwrite(tg18_picture(T), 2, 128 * 128, o); fclose(o);
#ifdef T18_PROF
} else if (!strcmp(cmd, "armprof")) {
if (!g_armh) g_armh = calloc(1 << 22, 4);
g_profon = 1; tg18_run_us(T, (uint32_t)(atof(a) * 1000)); g_profon = 0;
FILE *o = fopen("armprof.bin", "wb"); fwrite(g_armh, 4, 1 << 22, o); fclose(o);
#endif
#if defined(T18_ACNT) && !defined(T18_PSTAT)
} else if (!strcmp(cmd, "acnt")) {
acn_on = 1; tg18_run_us(T, (uint32_t)(atof(a) * 1000)); acn_on = 0;
uint64_t tot = 0, reg[16] = {0}; for (int i = 0; i < 65536; i++) { tot += av[i]; reg[ak[i] >> 28] += av[i]; }
printf("total %llu\n", (unsigned long long)tot);
for (int r = 0; r < 16; r++) if (reg[r]) printf("region %x: %llu\n", r, (unsigned long long)reg[r]);
{ /* per 4 KB flash page */
static uint32_t pg[2048]; memset(pg, 0, sizeof pg);
for (int i = 0; i < 65536; i++) if (av[i] && (ak[i] >> 28) == 2) pg[(ak[i] & 0x7FFFFF) >> 12] += av[i];
int np = 0; for (int i = 0; i < 2048; i++) if (pg[i]) np++;
printf("pages read %d:", np);
for (int i = 0; i < 2048; i++) if (pg[i]) printf(" %03x:%u", i, pg[i]);
printf("\n");
}
for (int n = 0; n < 25; n++) { int b = 0; for (int i = 1; i < 65536; i++) if (av[i] > av[b]) b = i; if (!av[b]) break; printf("%08x %c %u\n", ak[b] & ~1u, ak[b] & 1 ? 'W' : 'R', av[b]); av[b] = 0; }
#endif
} else if (!strcmp(cmd, "savest")) {
/* state, then the guest's SRAM (128 KB): for the M3 test bed (loadst) */
uint32_t n = tg18_state_size(T); uint8_t *b = malloc(n); tg18_save_state(T, b, n);
FILE *o = fopen(a, "wb"); fwrite(b, 1, n, o); for (uint32_t q = 0; q < T18_SRAM_SIZE; q++) fputc(*t18_sram_rp(q), o); fclose(o); free(b);
} else if (!strcmp(cmd, "loadst")) {
FILE *i = fopen(a, "rb"); uint32_t n = tg18_state_size(T); uint8_t *b = malloc(n + T18_SRAM_SIZE);
size_t got = fread(b, 1, n + T18_SRAM_SIZE, i); fclose(i);
if (got != n + T18_SRAM_SIZE || tg18_load_state(T, b, n) < 0) { fprintf(stderr, "loadst failed\n"); return 1; }
for (uint32_t q = 0; q < T18_SRAM_SIZE; q += 4) { uint32_t w; memcpy(&w, b + n + q, 4); t18_sram_wr(q, w, 4); }
free(b);
} else if (!strcmp(cmd, "flash")) {
FILE *o = fopen(a, "wb"); fwrite(g_flash, 1, 0x800000, o); fclose(o);
} else if (!strcmp(cmd, "peek")) { /* peek <guest SRAM address hex> <n>: bytes of the guest SRAM (test2) */
unsigned ad = 0, n = 16; sscanf(l, "%*s %x %u", &ad, &n);
printf("peek %08x:", ad); for (unsigned q = 0; q < n; q++) printf(" %02x", *t18_sram_rp(ad - 0xF8000000u + q)); printf("\n");
#ifdef T18_LINK
} else if (!strcmp(cmd, "linkrun")) { /* linkrun <ms>: lockstep with the other ref */
int ms = atoi(a); for (int i = 0; i < ms; i++) { tg18_run_us(T, 1000); lk_pairstep(); }
} else if (!strcmp(cmd, "blereplay")) { /* blereplay <capture> <session> */
int si = 0; char fn2[200]; sscanf(l, "%*s %199s %d", fn2, &si); lk_replay(fn2, si);
#endif
} else if (!strcmp(cmd, "poke")) { /* poke <guest SRAM address hex> <byte hex> (test6) */
unsigned ad = 0, val = 0; sscanf(l, "%*s %x %x", &ad, &val); t18_sram_wr(ad - 0xF8000000u, val & 0xFF, 1);
} else if (!strcmp(cmd, "power")) {
printf("power %d backlight %d\n", tg18_power(T), tg18_backlight(T));
} else if (!strcmp(cmd, "sram")) {
FILE *o = fopen(a, "wb"); for (uint32_t q = 0; q < T18_SRAM_SIZE; q++) fputc(*t18_sram_rp(q), o); fclose(o);
} else if (!strcmp(cmd, "hash")) {
arm7_t *c = tg18_cpu(T);
printf("cyc %llu pc %08x sram %08x\n", (unsigned long long)c->cycles, c->r[15], sram_hash());
#ifdef T18_IDLE_DBG
fprintf(stderr, "why ok %u noret %u bad %u cpsr %u regs %u attn %u target %u sram %u\n", g_why[0], g_why[1], g_why[2], g_why[3], g_why[4], g_why[5], g_why[6], g_why[7]);
#endif
fprintf(stderr, "idle skipped %.1f%%\n", 100.0 * (double)c->idle_skipped / (double)c->cycles);
}
}
#ifdef T18_PSTAT
for (int m = 0; m < 32; m++) if (sp_max[m]) fprintf(stderr, "mode %x sp %08x..%08x\n", m, sp_min[m], sp_max[m]);
for (int i = 0; i < 512; i++) if (sp_hist[i]) fprintf(stderr, "sp page %05x %u\n", i * 256, sp_hist[i]);
{ FILE *o = fopen("pstat.txt", "w"); for (int i = 0; i < 512; i++) fprintf(o, "%05x %d %llu %llu\n", i * 256, ps_nz[i], (unsigned long long)ps_r[i], (unsigned long long)ps_w[i]); fclose(o); }
#endif
#ifdef T18_WMAP
{ int hi = 0; for (int i = 0; i < 512; i++) if (t18_wmap[i]) hi = i;
fprintf(stderr, "highest written page %05x\n", hi << 8);
for (int i = 0; i < 512; i++) fputc(t18_wmap[i] ? '#' : '.', stderr); fputc('\n', stderr); }
#endif
#ifdef T18_HLE_CHECK
hle_fit();
#elif defined(T18_HLE_FILL)
fprintf(stderr, "hle fills %u\n", t18_hle_n);
#endif
return 0;
}
+48
View File
@@ -0,0 +1,48 @@
#!/bin/sh
# Build the T18 app for the Paradise (arm-none-eabi-gcc, Cortex-M3).
# Output: ../../t18.bin (PRAM part, loaded by the stub) and ../../t18x.bin (flash part, at T18_XIP_OFF).
set -e
cd "$(dirname "$0")"
E=../../../emu/src/emu
CC=${CC:-arm-none-eabi-gcc}
SRC="main.c t18app.h link.ld $E/hw.c $E/ask.c $E/ask.h $E/flash.c $E/libc.c $E/paraclock.h ../core/t18cpu.c ../core/t18cpu.h ../core/t18soc.c ../core/t18soc.h ../core/t18jit.c ../core/t18hle.c ../core/t2enc.h"
BUILD=$(cat $SRC | cksum | cut -d' ' -f1)
# 1.6.6: the switches that proved themselves are the default; T18_TEST=1 keeps the code screens and the speed display
REL="-DT18_HOTWIN -DT18_ROWSUM_RAM20 -DT18_JHDR -DT18_JH_SPLIT=0x20000100u -DT18_PRESENT_IDLE -DT18_PRESENT_STABLE -DT18_SUM_FNV -DT18_ROW_RR -DT18_PRES_FIRST -DT18_WAKE_ASYNC -DWAKE_ASYNC -DT18_SF_FAST -DT18_HOLE_FAST -DT18_TRY_SEQ -DT18_MEM_HELPER -DT18_FLUSH_IDLE -DT18_FF_FAST -DT18_IDLE_RUN -DT18_COMPACT_ON=40000000u -DT18_COMPACT_OFF=200000000u"
# 1.6.8: the switches of the test builds 1.6.7-test10..13 (measured on the device: egg 45 -> 63 %, call 56 -> 73 %)
REL="$REL -DT18_STM_SPLIT -DT18_SF_ASM -DT18_CHK_FLASH -DT18_CHK_HOLE -DT18_GFAIL_SHARED -DT18_SEQ_FAST -DT18_JT2 -DT18_SPCHK_LD -DT18_CYC32 -DT18_OVERSHOOT"
# 1.6.8 (test40): switches measured in the M3 test bed (egg -7 %, call -11 %, pet -5 %; same results as the reference)
REL="$REL -DT18_IO_FAST -DT18_SPCHK_MOD -DT18_TIERUP -DT18_IDLE_CAP=256 -DT18_IDLE_DISARM=32 -DT18_IDLE_PASS -DT18_XRET -DT18_CLOCK_AFTER -DPARA_BACK -DPARA_MB_KEEP -DPARA_FLASH -DPARA_FLASH_LATE -DPARA_CLEAN_CLK -DT18_CLK_DISC -DT18_MB_FIRST -DT18_LCD_FAST -DT18_PREWAKE -DT18_WAKE_KEEP -DT18_DARK_PEEK -DT18_PRES_SWEEP -DT18_NOTE_REL -DT18_CARE_TOOTH -DT18_MENU_QUIET -DHW_WAKE_ABORT -DT18_RADIO -DBL_PWM -DBL_MR3RST -DT18_TONE_Q -DT18_IDLE_MEMO -DT18_IDLE_BACKOFF=13 -DT18_JH_PROBE=16 -DT18_JT_MUL -DT18_SEC_SPARE -DT18_GROW -DT18_GROW2 -DT18_WAKE_START -DT18_DAY_FIX -DT18_LINK -DASK_EXTRA -DBAT_SHOW -DCLK_ECO -DECO_LAG=120 -DT18_WHEEL_WAKE -DT18_POOL_RECLAIM -DT18_CARE -DASK_NUM -DT18_PW -DT18_WHEEL_RAW -DT18_LOOP_XIP -DT18_KNOWN -DT18_SPEC -DT18_PW_RTCWAIT -DT18_PRESENT_CONFIRM -DT18_RAW_LABEL -DT18_CATCHUP_SMOOTH -DT18_PRESENT_S32 -DT18_CPU_SLOW=5 -DT18_CPU_ADAPT -DT18_IO_DIRECT -DT18_IO_FASTW -DT18_BL_STRICT -DASK_DIM -DASK_NEVER -DT18_DIM -DT18_CALL_LIGHT -DBAT_SMOOTH -DASK_LANG -DT18_LANG -DT18_ON_FULL -DT18_KEY_NOIDLE -DT18_KEY_FRESH=300 -DT18_KEY_OFFFF -DT18_KEY_LATCH -DT18_SWALLOW_LIT -DT18_KEY_FRESH_LIT -DT18_S32_EMU -DT18_S32_MS=72u -DBAT_GUARD -DBAT_PIC"
# 1.7.4 test3: the firmware's picture fill natively (core/t18hle.c, T18_HLE_FILL; T18_HLE_OS: compiled small,
# more room for translated code). Its state is in the hole: the stack 0x5B0 -> 0x560 (HLE path about 900 bytes deep).
# 1.7.4 test4: T18_PRES_FILL (a finished fill goes out as a picture: the walk to the park no longer stands still) and the
# game CPU at its full clock again (T18_CPU_SLOW 5 -> 4; the fill no longer costs the Paradise much, CPU_ADAPT still
# slows it when the Paradise falls behind)
[ -n "$T18_NO_HLE" ] || { REL="$(echo "$REL" | sed 's/-DT18_CPU_SLOW=5/-DT18_CPU_SLOW=4/') -DT18_HLE_FILL -DT18_HLE_OS -DT18_PRES_FILL -DT18_MENU_FILL -DT18_WAKE_FILL -DT18_PEEK_RAW"; STACKSZ=${STACKSZ:-0x560}; }
[ -n "$T18_TEST" ] || REL="$REL -DT18_QUIET_FATAL -DT18_NO_SPEED"
[ -n "$T18_TEST" ] && REL="$REL -DT18_TEST_KEYS"
[ -n "$T18_PLAIN" ] && REL=""
JHB=${JHB:-9}; T18_XIP_MORE=${T18_XIP_MORE-1}; JTB=${JTB:-9}; JHOT=${JHOT:-4} # 1.6.8: as in the test builds 10..13
CF="-mcpu=cortex-m3 -mthumb -ffreestanding -nostdlib -fno-common -ffunction-sections -fdata-sections -Wall -Wno-unused-function -DPARADISE -DT18_JIT -DT18_JC_LINKED -DT18_PRAM_WR -DT18_PRAM_WR_SRAM -DJH_BITS=${JHB:-8} -DJT_BITS=${JTB} -DJ_HOT=${JHOT} -DT18_BUILD=${BUILD}u -DFAST_LCD -DEXIT_KEY -DLCD_FASTCLK -DTONE_FIX -DHW_TONE_RESTART -DBL_SLEEP -DHW_OPTS -DSESS_ONCE -DSESS_AUTO -DOPT_MENU -DSESS_FLAG -I../core $REL $XCF"
O=""
for f in main.c $E/hw.c $E/ask.c $E/flash.c $E/libc.c ../core/t18cpu.c ../core/t18soc.c ../core/t18jit.c; do
n=$(basename $f .c); OPT=-Os; [ "$n" = t18cpu ] && OPT=-O2; [ "$n" = libc ] && OPT="-Os -fno-builtin -fno-tree-loop-distribute-patterns"
$CC $CF $OPT -c $f -o $n.o; O="$O $n.o"; done
# T18_XIP_MORE=1: rarely run code into the flash window as well (bigger code buffer)
# idle_try stays in the PRAM (1.6.6, T18_IDLE_RUN). 1.7.4 test3 (T18_ARM_PRAM=1 for the old place): the ARM interpreter
# (exec_arm, 5.4 KB) into the flash window: a few thousand ARM instructions a second are interpreted, the rest is
# translated; the PRAM gained is room for translated code (M3: room 61 -> 58 Minstr/s, with T18_HLE_FILL 42 -> 32)
[ -n "$T18_ARM_PRAM" ] && XM_DEF=.text.arm7_step || XM_DEF=".text.arm7_step .text.exec_arm"
XM_CPU=${XM_CPU:-$XM_DEF}
if [ -n "$T18_XIP_MORE" ]; then MORE='*ask.o(.text* .rodata*) *t18soc.o(.text.io_wr .text.io_rd .text.rq_push .text.rd32le .text.tg18_run_cycles .text.tmr_io_rd .text.tmr_io_wr) *t18cpu.o('"$XM_CPU"') *libgcc.a:_udivmoddi4.o(.text*)'; else MORE=''; fi
sed "s|XIPMORE|$MORE|;s|JTSIZE|$((8 << JTB))|;s|STACKSZ|${STACKSZ:-0x5B0}|" link.ld > link_gen.ld
$CC $CF -T link_gen.ld -Wl,--gc-sections -Wl,-Map=t18.map $O -lgcc -o t18.elf
# test43 fix: what runs before the flash window is set up (Reset_Handler up to hw_init) must be in the PRAM
for f in Reset_Handler para_clock para_mailbox para_leave_mark para_days hw_init; do
a=$(arm-none-eabi-nm t18.elf | awk -v f=$f '$3==f || index($3, f".")==1 {print $1; exit}')
[ -z "$a" ] || [ $((0x$a)) -lt $((0x10000000)) ] || { echo "build.sh: $f is in the flash window (0x$a), it runs before the window is set up"; exit 1; }
done
arm-none-eabi-objcopy -O binary -j .text -j .data -j .init t18.elf t18.bin
arm-none-eabi-objcopy -O binary -j .xip t18.elf t18x.bin
cp t18.bin ../../t18.bin; cp t18x.bin ../../t18x.bin; rm -f *.o t18.bin t18x.bin link_gen.ld; [ -n "$KEEPELF" ] || rm -f t18.elf t18.map
ls -l ../../t18.bin ../../t18x.bin
+45
View File
@@ -0,0 +1,45 @@
/* T18 app on the Paradise. The RAM at 0x20000000 has only 4 KB (the Paradise firmware's), so:
* PRAM 0x00000000 (64 KB, loaded by the stub): hot code; from __jc_start on (over the .data image and
* the start code) the code buffer of the translator.
* flash window (0x10000000 + flash offset - 0x11000): the rest of the code, flash T18_XIP_OFF (0xF0000).
* SRAM hole 0x1800E600..0x18014400: stack (bottom), data. 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 : {
__xip_magic = .;
KEEP(*(.xipmagic))
*(.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 .text.dp_operand* .text.a_shift* .text.cond_reads)
*t18soc.o(.text.tg18_init .text.soc_reset .text.tg18_save_state .text.tg18_load_state .text.tg18_state_size .text.tg18_set_time .text.tg18_get_time .text.tg18_advance_offline .text.reg_clear .text.tg18_set_addrs .text.tg18_get_addrs .text.tg18_set_present .text.days_from_civil .text.find_idle .text.tg18_struct_size .text.tg18_sf_regp .text.tg18_sf_ctlp .text.tg18_sf_outp)
*t18cpu.o(.text.arm7_init .text.arm7_reset .text.arm7_save .text.arm7_load .text.build_cond .text.t18_sram_clear)
/* 1.6.6: rarely run, out of the PRAM for a bigger code buffer (T18_XIP_MORE) */
XIPMORE
*(.rodata.t18_zero_pg)
. = ALIGN(4);
__xip_end = .;
} > XIP
.text : {
KEEP(*(.vectors))
KEEP(*(.pmxcfg))
*(.text*)
*(.rodata*)
. = ALIGN(4);
} > PRAM
.stack (NOLOAD) : { __stack_bottom = .; . += STACKSZ; __stack_top = .; } > HOLE /* build.sh STACKSZ (1.7.4: 0x560 with T18_HLE_FILL); 1.6.13 test6: 0x600 -> 0x5E0 (804 bytes used, measured); test21: 0x5D0 (16 bytes for BAT_GUARD); 1.7.2 test16: 0x5C0 (16 bytes for T18_CLK_DISC); test19: 0x5B0 (T18_WAKE_KEEP) */
.data : { __data_start = .; *(.ramfunc*) *(.data*) . = ALIGN(4); __data_end = .; } > HOLE AT > PRAM
__data_load = LOADADDR(.data);
.init : { KEEP(*(.initcode)) KEEP(*(.initdata*)) KEEP(*(.initcode_z)) . = ALIGN(4); } > PRAM
__prog_end = .;
__jc_start = ALIGN(__data_load, 4);
__jt_start = 0x10000 - JTSIZE; /* the translator's table for indirect jumps (8 << JT_BITS bytes, build.sh) */
__jc_end = __jt_start;
.bss (NOLOAD) : { __bss_start = .; *(.bss*) *(COMMON) . = ALIGN(4); __bss_end = .; } > HOLE
ASSERT(__prog_end <= 0xC000, "PRAM: too little room left for the translated code")
ASSERT(__xip_end - 0x100DF000 <= 0x10000, "flash part too big")
/DISCARD/ : { *(.comment) *(.ARM.*) *(.note*) }
}
+2394
View File
File diff suppressed because it is too large. Load diff
+47
View File
@@ -0,0 +1,47 @@
/* T18 (Meets/On, TG18 firmware) on the Tamagotchi Paradise: settings block and flash layout. */
#ifndef T18APP_H
#define T18APP_H
#include <stdint.h>
/* Settings block "PMX8" at 0x140 in the program, filled in by the Studio (src/emu.js, t18Patch).
* The firmware lies in the Paradise flash in 64 KB blocks wherever there was room: map[i] is the
* Paradise block (offset >> 16) of guest block i, 0xFFFF = erased (reads 0xFF). Blocks the guest
* writes later (its save data) come from the spare list, which the Studio leaves erased. */
#define T18_MAGIC 0x38584D50u /* "PMX8" */
#define T18_SPARE_MAX 64
typedef struct {
uint32_t magic, version;
uint32_t save_off; /* Paradise flash: map sector, settings, session (see main.c) */
uint32_t nspare;
uint16_t map[128];
uint16_t spare[T18_SPARE_MAX];
uint32_t flags; /* T18F_* */
uint32_t idle_addr, softrtc, dma_tab; /* found by the Studio in the firmware (tg18_set_addrs) */
uint32_t wall_cnt, wall_sod, wall_ymd; /* written by the Studio on the device: seconds counter, local time, date */
uint32_t param_addr; /* 1.6.8 (test47): the game's Param block in the guest SRAM (0xF800....), 0 = unknown */
uint32_t adult_flags; /* bit 0: Sanrio firmware (Flowertchi instead of Pompomtchi) */
uint32_t pic_off; /* pictures for grow up ("T8PI", the user's own, see src/emu.js), 0 = none */
} T18Cfg;
#define T18F_EN 1u /* English texts */
#define T18F_CLOCK 2u /* at every start the clock is set to the Paradise's time (nothing caught up) */
#define T18F_HOTWIN 4u /* the Studio put the hot firmware blocks into 0xF00000..0xFFFFFF and a second
* copy of the flash part at T18_XIP_HOT (see main.c, hot window) */
#define T18F_NOSESS 0x1000u /* 1.7.3 test7: no session (SESS_FLAG): only the firmware's own save is written */
/* code that is not hot: in the flash at T18_XIP_OFF, seen in the window 0x10000000 (base 0x60011000);
* it begins with T18_XIP_MAGIC and the build number of the program (T18_BUILD) */
#define T18_XIP_OFF 0xF0000u
#define T18_XIP_MAX 0x10000u
#define T18_XIP_MAGIC 0x58383154u /* "T18X" */
/* hot window (1.6.6): the cached flash window shows 1 MB from its base. With base 0x60F00000 it shows
* 0xF00000..0xFFFFFF; the flash part is then needed at 0xFDF000 (same link address 0x100DF000) */
#define T18_HOT_BASE 0xF00000u
#define T18_XIP_HOT (T18_HOT_BASE + T18_XIP_OFF - 0x11000u)
/* Paradise flash from save_off */
#define T18_MAP_SEC 0x0000u /* "T8MP": the map as it is now, with the spares in use */
#define T18_NOTE_SEC 0x1000u /* "T8NT": seconds counter and game time when leaving */
#define T18_SESS_SEC 0x2000u /* "T8SS": CPU and SoC state, then the SRAM (32 sectors) */
#define T18_SAVE_LEN 0x24000u
#endif
File diff suppressed because it is too large. Load diff
+129
View File
@@ -0,0 +1,129 @@
/* ARM7TDMI interpreter for T18 on the Paradise (instruction semantics from the T18Emu core). */
#ifndef T18CPU_H
#define T18CPU_H
#include <stdint.h>
/* Guest SRAM 0xF8000000, 128 KB (the TG18 window is 136 KB, but nothing above 128 KB is ever used:
* reads 0). It is direct memory at t18_sram (on the Paradise the Paradise SRAM itself, host = guest +
* 0x20000000), except for the hole [T18_HOLE_LO, T18_HOLE_HI): there the host memory holds the
* emulator's own data (stack, state, tables). The guest's bytes in the hole are kept in pages of
* 512 bytes that are made on the first write of a non-zero value (until then they read 0). All five
* TG18 firmwares only zero this range at the start and use a few hundred bytes of it later; both
* stacks lie above it. */
#define T18_SRAM_SIZE 0x20000u
#if defined(PARADISE) && !defined(T18_HOLE_LO)
#define T18_HOLE_LO 0xE600u
#define T18_HOLE_HI 0x14400u
#endif
#ifndef T18_HOLE_LO
#define T18_HOLE_LO 0u
#define T18_HOLE_HI 0u
#endif
#define T18_HOLE_PG 512u
#define T18_HOLE_N ((T18_HOLE_HI - T18_HOLE_LO) / T18_HOLE_PG)
static inline int t18_hole(uint32_t o) { return o - T18_HOLE_LO < T18_HOLE_HI - T18_HOLE_LO; }
/* a range [o, o + n) that touches the hole */
static inline int t18_hole_n(uint32_t o, uint32_t n) { return T18_HOLE_HI > T18_HOLE_LO && o < T18_HOLE_HI && o + n > T18_HOLE_LO; }
typedef struct arm7 arm7_t;
typedef uint32_t (*arm7_rd_fn)(void *ctx, uint32_t addr, int size);
typedef void (*arm7_wr_fn)(void *ctx, uint32_t addr, uint32_t val, int size);
struct arm7 {
uint32_t r[16];
uint32_t cpsr;
uint32_t spsr; /* current mode's spsr */
uint32_t bank_usr[7]; /* r8..r14 for usr/sys */
uint32_t bank_fiq[7]; /* r8..r14 fiq */
uint32_t bank_irq[2], bank_svc[2], bank_abt[2], bank_und[2];
uint32_t spsr_fiq, spsr_irq, spsr_svc, spsr_abt, spsr_und;
uint64_t cycles; /* master ticks */
uint64_t idle_cycles;
uint32_t cyc_mult; /* master ticks per CPU cycle */
int irq_line, fiq_line;
int halted;
uint32_t vector_base;
void *ctx;
arm7_rd_fn rd;
arm7_wr_fn wr;
/* store notify range (picture buffer), called before the store */
uint32_t note_lo, note_hi;
void (*note_fn)(void *ctx, uint32_t addr);
uint32_t last_pc;
int fault;
int attn; /* irq_line | fiq_line | halted, after every device access */
uint32_t *jtab; /* translator: return cache (pc, code) x 256 */
uint32_t jsave; /* translator: scratch word */
uint32_t jsplo; /* translator: host address of the lowest guest sp blocks may use (1.6.8) */
/* idle loops: skip whole rounds of a loop that changes nothing */
uint64_t idle_next; /* next check (master ticks) */
uint32_t idle_fail;
int watch; /* 1 while one round is watched */
int (*io_stable)(void *ctx, uint32_t a); /* reading a gives the same value until the next event */
uint64_t idle_skipped;
uint32_t idle_pc; /* pc where a round last held still (0 = none yet) */
uint64_t idle_win; /* target of the run in which idle_pc was already tried */
};
extern uint8_t *t18_sram; /* guest SRAM, 128 KB (the hole part is not the guest's) */
extern uint8_t *t18_hole_pg[T18_HOLE_N + 1]; /* pages of the hole, 0 = not made yet (reads 0) */
extern uint8_t *(*t18_hole_new)(void); /* platform: a zeroed page of 512 bytes, 0 = none left */
extern int t18_oom; /* a write into the hole was lost (no page left) */
const uint8_t *t18_sram_rp(uint32_t o); /* guest SRAM offset -> byte, valid up to the end of its 512-byte page */
uint8_t *t18_sram_wp(uint32_t o, int make); /* same for writing; 0 when it is a hole page not made (make: make it) */
uint32_t t18_sram_rd(uint32_t o, int size);
void t18_sram_wr(uint32_t o, uint32_t v, int size); /* makes the hole page only for a non-zero value */
void t18_sram_clear(void); /* all zero, hole pages given up (the platform takes them back) */
extern void (*t18_hole_free)(void); /* platform: all hole pages are free again */
extern const uint8_t *t18_fblk[128];
void arm7_init(arm7_t *c);
void arm7_reset(arm7_t *c, uint32_t pc);
int64_t arm7_run(arm7_t *c, uint64_t target);
int arm7_step(arm7_t *c);
extern int t18_idle_on;
void arm7_exception(arm7_t *c, uint32_t mode, uint32_t vec, uint32_t ret);
uint32_t arm7_read32(arm7_t *c, uint32_t a);
uint16_t arm7_read16(arm7_t *c, uint32_t a);
uint8_t arm7_read8(arm7_t *c, uint32_t a);
void arm7_write32(arm7_t *c, uint32_t a, uint32_t v);
void arm7_write16(arm7_t *c, uint32_t a, uint32_t v);
void arm7_write8(arm7_t *c, uint32_t a, uint8_t v);
void arm7_set_mode(arm7_t *c, uint32_t mode);
#define ARM7_T (1u<<5)
#define ARM7_F (1u<<6)
#define ARM7_I (1u<<7)
typedef struct {
uint32_t r[16], cpsr, spsr;
uint32_t bank_usr[7], bank_fiq[7], bank_irq[2], bank_svc[2], bank_abt[2], bank_und[2];
uint32_t spsr_fiq, spsr_irq, spsr_svc, spsr_abt, spsr_und;
uint64_t cycles;
int32_t halted, pad;
} arm7_state_t;
void arm7_save(arm7_t *c, arm7_state_t *s);
void arm7_load(arm7_t *c, const arm7_state_t *s);
#ifdef T18_HLE_FILL
extern uint32_t t18_hle_pc, t18_hle_n; /* 1.7.4: the firmware's picture fill natively (t18hle.c) */
int t18_hle_find(void);
extern volatile uint32_t t18_hle_done;
int t18_hle_busy(void);
#endif
#ifdef T18_RAW_LABEL
/* 1.6.13 test4: the firmware's label routine (Thumb "strh r0,[r5]" after a call of its per-pixel routine) writes
* colour table numbers into the picture first (blue box behind the name on a call); the panel keeps what was there
* at those pixels until the full picture draws them (as the Android T18Emu). t18_raw_pc: that strh (1 = unknown). */
extern uint32_t t18_raw_pc;
extern volatile uint32_t t18_raw_n, t18_raw_lo, t18_raw_hi; /* stores seen, lowest and highest address */
extern uint16_t t18_raw_v[4]; /* values written (a few colour table numbers) */
#endif
#ifdef T18_JIT
int t18_jit_try(arm7_t *c, uint64_t target);
extern int t18_jit_off;
int t18_jit_code_line(uint32_t sram_off);
int t18_jit_code_range(uint32_t sram_off, uint32_t len);
void t18_jit_written(arm7_t *c, uint32_t a, uint32_t n);
#endif
#endif
+427
View File
@@ -0,0 +1,427 @@
/* T18_HLE_FILL (1.7.4): the firmware's picture fill natively. Included by t18cpu.c.
* The firmware draws its picture with a Thumb routine in its SRAM (fairy v057: 0xF80061D8): for every pixel of a
* rectangle it calls a per-pixel routine that walks all layers from the top (20-byte records), samples the first
* one that covers the pixel and is not transparent, looks the colour up in three tables, blends the upper part
* of the screen in some scenes and stores RGB565. That was more than half of all guest instructions (more with
* twins: more layers). Here the same in C, with the layers of each row picked out once.
* Two forms of the per-pixel routine are known: kind 1 (fairy, magic, sanrio: the sampling in its own routine)
* and kind 2 (wondergarden, fantasy, pastel, sweets: inlined, the layer list 4 bytes earlier); both do the same.
* Same result as the firmware's code (checked against it in host/ref.c, T18_HLE_CHECK). Guest cycles are charged
* as the firmware's code would have used them (counters, fitted against the interpreter). Runs in slices up to
* the run's target: the guest pc stays at the routine until it is done; an interrupt in between returns to it
* and the fill goes on where it stopped.
* Author: mameise */
#ifndef T18_HLE_MAXL
#define T18_HLE_MAXL 64
#endif
uint8_t t18_flash_rd(uint32_t a);
uint32_t t18_hle_pc = 1u; /* the fill routine (Thumb, bit 0 clear); 1 = not found */
#if defined(T18_HLE_CHECK) || defined(T18_HLE_COUNT)
uint32_t t18_hle_n; /* fills done natively */
#endif
/* what the search found and where a fill stopped */
static struct {
uint32_t L, fbv, tr, lo; /* layer list, picture pointer, red table (green +0x200, blue +0x400), blend range */
uint8_t toff, kind, cnt, rec; /* table offset, form, layer count and first record in the list */
uint32_t sp, lr, a0, a1, a2, a3; /* the call in progress */
uint16_t idx; uint8_t y, x, on;
} hv;
static int32_t hf_hit;
/* share of the firmware's cycles a native fill is charged with, in 1/16 (16 = as the firmware's code) */
#ifndef T18_HLE_Q
#define T18_HLE_Q 16u
#endif
uint32_t t18_hle_q = T18_HLE_Q;
volatile uint32_t t18_hle_done; /* fills finished (T18_PRES_FILL in main.c: a finished picture goes out) */
int t18_hle_busy(void) { return hv.on; }
/* guest byte reads (images in the flash, tables in the SRAM): one copy of rd8, not one per use */
static __attribute__((noinline)) uint32_t hr8(arm7_t *c, uint32_t a) { return rd8(c, a); }
/* image bytes: straight from the flash block when it is mapped (as mp_r), else as the guest reads them */
static inline uint32_t im8(arm7_t *c, uint32_t a)
{
uint32_t o = a - 0x20000000u;
if (o < 0x800000u) { const uint8_t *b = t18_fblk[o >> 16]; if (b) return b[o & 0xFFFFu]; }
return hr8(c, a);
}
static inline uint32_t g16(const uint8_t *p) { return (uint32_t)p[0] | (uint32_t)p[1] << 8; }
static inline uint32_t g32(const uint8_t *p) { return g16(p) | g16(p + 2) << 16; }
static inline const uint8_t *sp_(uint32_t a) { return t18_sram + (a - 0xF8000000u); }
static inline uint32_t lit(uint32_t ins) { uint32_t op = g16(sp_(ins)); return g32(sp_(((ins + 4u) & ~3u) + (op & 0xFFu) * 4u)); }
static inline uint32_t bl_tgt(uint32_t a) { const uint8_t *p = sp_(a); uint32_t h = g16(p), l = g16(p + 2); int32_t off = (int32_t)((h & 0x7FFu) << 21) >> 9; return a + 4u + (uint32_t)off + ((l & 0x7FFu) << 1); }
#ifdef PARADISE
#define HLE_COLD __attribute__((section(".xiptext"), noinline))
#else
#define HLE_COLD
#endif
/* code fingerprint (halfwords; BL offsets, literal places and small ldrb offsets left out): FNV-1a */
HLE_COLD static uint32_t fp_code(uint32_t a, uint32_t len)
{
uint32_t h = 2166136261u; const uint8_t *p = sp_(a);
for (uint32_t i = 0; i < len; i += 2) {
uint32_t op = g16(p + i);
if ((op & 0xF800u) == 0xF000u) { i += 2; op = 0xF000u; }
else if ((op & 0xF800u) == 0x4800u) op &= 0xF800u;
else if ((op & 0xF800u) == 0x7800u && (op & 0x7C0u) <= 0x200u) op &= 0xF83Fu;
h = (h ^ op) * 16777619u;
}
return h;
}
/* fingerprints of the firmwares seen (T18_HLE_FP prints them) */
#define HF_FP_FILL 0x9B253DFAu /* the fill (both kinds) */
#define HF_FP_PIX1 0xC86488CFu /* kind 1: per-pixel routine and its sampling routine */
#define HF_FP_SMP1 0xED689851u
#define HF_FP_PIX2 0xAB5ABE09u /* kind 2: per-pixel routine with the sampling inside */
/* counters of what the firmware's code would have walked through (fitted in host/ref.c) */
enum { K_PIX, K_ROW, K_CALL, K_ST1, K_ST2, K_ST3, K_BLEND, K_NOHIT, K_XN, K_XB, K_FBP, K_S0, K_SH,
K_SW, K_YF, K_XF, K_B8, K_B4O, K_B4E, K_B10, K_B10Y, K_B10X, K_B10R, K_DIV, K_Z, K_H, K_DN, K_DB, K_N };
#ifdef T18_HLE_CHECK
uint32_t hk[K_N];
#define HK(k) (hk[k]++)
#else
#define HK(k) do { } while (0)
#endif
/* guest cycles per counter and kind: fitted against the interpreter (host/ref.c T18_HLE_CHECK, all 9 firmwares,
* about 1000 fills: 0.05 % off on average); NOHIT and H did not occur: estimates */
static const uint16_t HCT[2][K_N] = {
/* PIX ROW CALL ST1 ST2 ST3 BLEND NOHIT XN XB FBP S0 SH SW YF XF B8 B4O B4E B10 B10Y B10X B10R DIV Z H DN DB */
{ 0, 0, 0, 0, 0, 7, 122, 224, 75, 89, 322, 166, 390, 0, 21, 5, 0, 37, 0, 0, 2, 0, 0, 64, 16,25,43,56 },
{ 0, 0, 0, 0, 0, 7, 122, 224, 70, 86, 326, 154, 385, 0, 21, 5, 0, 29, 0, 0, 2, 0, 0, 61, 18,25,36,49 },
};
#define HC(k) (hc[k])
#define HKC(k) do { HK(k); *cy += HC(k); } while (0)
/* sampling of one layer at (x, y) inside it, as the firmware (layers turned by 90 degrees, rows with many layers) */
HLE_COLD static uint32_t smp(arm7_t *c, const uint8_t *e, uint32_t x, uint32_t y, uint32_t *cy, const uint16_t *hc)
{
uint32_t img = g32(e), f = g16(e + 14);
if (f & 0x40u) { uint32_t t = x; x = y; y = t; HKC(K_SW); }
if (f & 0x20u) { y = (e[9] - 1u - y) & 0xFFu; HKC(K_YF); }
if (f & 0x10u) { x = (e[8] - 1u - x) & 0xFFu; HKC(K_XF); }
uint32_t off = g16(e + 16);
if (f & 0x8000u) { HKC(K_B8); return im8(c, img + x + y * im8(c, img) + off + 6u); }
if (f & 0x400u) { HK(K_B10); if (!y) { HKC(K_B10Y); if (x <= 4u) { HKC(K_B10X); if (f & 0x800u) { HK(K_B10R); return 0; } } } }
uint32_t b = im8(c, img + y * (im8(c, img) >> 1) + off + (x >> 1) + 6u);
if (x & 1u) { HKC(K_B4O); return b >> 4; }
HK(K_B4E); return b & 15u;
}
/* per row: the layers that cover it (top first), each with what its sampling in this row needs, and the cycles of
* the other layers the walk passes above each. More than HLE_MAXR such layers: the row goes the slow way. */
#ifndef HLE_MAXR
#define HLE_MAXR 24
#endif
enum { M8 = 1, MXF = 2, MB10 = 4, MB11 = 8, MFB = 16, MDIV = 32, MSLOW = 64 };
typedef struct { const uint8_t *p; uint32_t ga; int16_t lx; uint16_t pre; uint8_t w, m, i, sc; } hent_t;
typedef struct { uint8_t n, slow; uint16_t tail; hent_t e[HLE_MAXR]; } hrow_t;
static inline uint32_t rej_kind(const uint8_t *e, uint32_t y)
{
if (!g32(e)) return K_Z;
if (g16(e + 14) & 0x4000u) return K_H;
int32_t dy = (int16_t)(uint16_t)(y - g16(e + 6));
if (dy < 0) return K_DN;
if (dy >= (int32_t)e[9]) return K_DB;
return 0;
}
/* a host pointer to n guest bytes at a (one flash block or plain SRAM), else 0 */
static inline const uint8_t *gptr(uint32_t a, uint32_t n)
{
uint32_t o = a - 0x20000000u;
if (o < 0x800000u) { const uint8_t *b = t18_fblk[o >> 16]; return b && (o & 0xFFFFu) + n <= 0x10000u ? b + (o & 0xFFFFu) : 0; }
o = a - 0xF8000000u;
return o < T18_SRAM_SIZE && T18_SRAM_SIZE - o >= n && !t18_hole_n(o, n) ? t18_sram + o : 0;
}
static void row_pick(arm7_t *c, hrow_t *rw, const uint8_t *R0, uint32_t n, uint32_t y, const uint16_t *hc)
{
uint32_t pre = 0;
rw->n = 0; rw->slow = 0;
for (int32_t i = (int32_t)n - 1; i >= 0; i--) {
const uint8_t *e = R0 + 20u * (uint32_t)i;
uint32_t k = rej_kind(e, y);
if (k) { pre += hc[k]; continue; }
if (rw->n >= HLE_MAXR) { rw->slow = 1; return; }
hent_t *E = &rw->e[rw->n++];
uint32_t f = g16(e + 14), w = e[8], dy = (y - g16(e + 6)) & 0xFFu, m = 0, sc = 0;
E->pre = (uint16_t)pre; E->lx = (int16_t)g16(e + 4); E->w = (uint8_t)w; E->i = (uint8_t)i; E->p = 0; E->ga = 0;
if (f & 0x1000u) m = MFB;
else if (f & 0x40u) m = MSLOW;
else {
uint32_t img = g32(e), yy = dy, st, len;
if (f & 0x20u) { yy = (e[9] - 1u - yy) & 0xFFu; sc += hc[K_YF]; }
if (f & 0x10u) { m |= MXF; sc += hc[K_XF]; }
if (f & 0x8000u) { m |= M8; sc += hc[K_B8]; st = im8(c, img); len = w; }
else { st = im8(c, img) >> 1; len = (w + 1u) >> 1;
if ((f & 0x400u) && !yy) { m |= MB10; sc += hc[K_B10Y]; if (f & 0x800u) m |= MB11; } }
E->ga = img + yy * st + g16(e + 16) + 6u; E->p = gptr(E->ga, len);
}
if (f & 0x2000u) m |= MDIV;
E->m = (uint8_t)m; E->sc = (uint8_t)sc;
}
rw->tail = (uint16_t)pre;
}
/* one pixel as the firmware's per-pixel routine: the first layer from the top that covers it and is not
* transparent; its value plus the layer's palette offset, 0 when none */
static inline uint32_t pixel(arm7_t *c, const hrow_t *rw, const uint8_t *R0, uint32_t x, uint32_t y, uint32_t fb, uint32_t *cy, const uint16_t *hc)
{
for (uint32_t j = 0; j < rw->n; j++) {
const hent_t *E = &rw->e[j];
int32_t dx = (int16_t)(uint16_t)(x - (uint32_t)(uint16_t)E->lx);
if (dx < 0) { HKC(K_XN); continue; }
if (dx >= (int32_t)E->w) { HKC(K_XB); continue; }
uint32_t m = E->m, v;
if (m & MFB) { HKC(K_FBP); *cy += E->pre; hf_hit = E->i; return rd16(c, fb + ((((y << 7) + x) & 0xFFFFu) << 1)); }
const uint8_t *e = R0 + 20u * E->i;
if (m & MSLOW) v = smp(c, e, (uint32_t)dx & 0xFFu, (y - g16(e + 6)) & 0xFFu, cy, hc);
else {
uint32_t xx = (m & MXF) ? E->w - 1u - (uint32_t)dx : (uint32_t)dx;
#ifdef T18_HLE_CHECK
{ uint32_t f = g16(e + 14); if (f & 0x20u) HK(K_YF); if (f & 0x10u) HK(K_XF); if (f & 0x400u && !(m & M8)) HK(K_B10); if (m & MB10) HK(K_B10Y); }
#endif
*cy += E->sc;
if (m & M8) { HK(K_B8); v = E->p ? E->p[xx] : im8(c, E->ga + xx); }
else {
if ((m & MB10) && xx <= 4u) HKC(K_B10X);
if ((m & (MB10 | MB11)) == (MB10 | MB11) && xx <= 4u) { HK(K_B10R); v = 0; }
else {
uint32_t b = E->p ? E->p[xx >> 1] : im8(c, E->ga + (xx >> 1));
if (xx & 1u) { HKC(K_B4O); v = b >> 4; } else { HK(K_B4E); v = b & 15u; }
}
}
}
if (m & MDIV) { /* the firmware's signed divide helper: only positive values here, 0 for a divisor 0 */
uint32_t d = hr8(c, g32(e) + 2u); HKC(K_DIV); v = d ? (~v & 0xFFFFu) % d : 0u; }
if (v) { HKC(K_SH); *cy += E->pre; hf_hit = E->i; return (v + g16(e + 12)) & 0xFFFFu; }
HKC(K_S0);
}
HKC(K_NOHIT); *cy += rw->tail; hf_hit = -1;
return 0;
}
/* a row with many layers: the walk as the firmware does it, layer by layer */
HLE_COLD static uint32_t pixel_all(arm7_t *c, const uint8_t *R0, uint32_t n, uint32_t x, uint32_t y, uint32_t fb, uint32_t *cy, const uint16_t *hc)
{
for (int32_t i = (int32_t)n - 1; i >= 0; i--) {
const uint8_t *e = R0 + 20u * (uint32_t)i;
uint32_t k = rej_kind(e, y);
if (k) { *cy += hc[k]; continue; }
int32_t dx = (int16_t)(uint16_t)(x - g16(e + 4));
if (dx < 0) { HKC(K_XN); continue; }
if (dx >= (int32_t)e[8]) { HKC(K_XB); continue; }
uint32_t f = g16(e + 14);
if (f & 0x1000u) { HKC(K_FBP); hf_hit = i; return rd16(c, fb + ((((y << 7) + x) & 0xFFFFu) << 1)); }
uint32_t v = smp(c, e, (uint32_t)dx & 0xFFu, (y - g16(e + 6)) & 0xFFu, cy, hc);
if (f & 0x2000u) { uint32_t d = hr8(c, g32(e) + 2u); HKC(K_DIV); v = d ? (~v & 0xFFFFu) % d : 0u; }
if (v) { HKC(K_SH); hf_hit = i; return (v + g16(e + 12)) & 0xFFFFu; }
HKC(K_S0);
}
HKC(K_NOHIT); hf_hit = -1;
return 0;
}
#ifdef T18_HLE_CHECK
/* the layers the walk passed above the hit (or all), by kind */
static void rej_count(const uint8_t *R0, uint32_t n, uint32_t y)
{
for (int32_t i = (int32_t)n - 1; i > hf_hit; i--) { uint32_t k = rej_kind(R0 + 20u * (uint32_t)i, y); if (k) hk[k]++; }
}
/* host/ref.c: the native fill into hf_dry (no guest writes, no cycles), the guest's code then runs and is compared */
uint16_t *hf_dry;
#define HF_SLICE (!hf_dry)
#else
#define HF_SLICE 1
#endif
/* the picture row straight in the SRAM when nothing has to see the writes (as blk_ptr), else 0 (wr16 each) */
static inline uint16_t *fb_row(arm7_t *c, uint32_t a, uint32_t n, uint32_t idx)
{
#ifdef T18_HLE_CHECK
if (hf_dry) return 0;
#endif
uint32_t len = n * 2u, o = a - 0xF8000000u;
if (c->watch || idx + n > 0x10000u || o >= T18_SRAM_SIZE || T18_SRAM_SIZE - o < len || t18_hole_n(o, len)) return 0;
if (c->note_hi > c->note_lo && a + len > c->note_lo && a < c->note_hi) return 0;
#ifdef T18_JIT
if (t18_jit_code_range(o, len)) return 0;
#endif
return (uint16_t *)(void *)(t18_sram + o);
}
#ifdef T18_HLE_OS
#define HLE_OPT __attribute__((optimize("Os"))) /* smaller: more room for translated code */
#else
#define HLE_OPT
#endif
/* 1: done (or a slice of it), 0: not taken (the guest code runs) */
HLE_OPT static int t18_hle_fill(arm7_t *c, uint64_t target)
{
const uint8_t *p = sp_(t18_hle_pc);
if (g32(p) != 0x465FB5F0u || g32(p + 12) != 0x9203B08Bu) { t18_hle_pc = 1u; return 0; } /* code gone: search again */
const uint8_t *L = sp_(hv.L), *R0 = L + hv.rec;
uint32_t n = L[hv.cnt];
if (c->watch || n > T18_HLE_MAXL) return 0;
const uint16_t *hc = HCT[hv.kind - 1u];
uint32_t mult = c->cyc_mult, cyc = 0;
if (!(hv.on && hv.sp == c->r[13] && hv.lr == c->r[14] && hv.a0 == c->r[0] && hv.a1 == c->r[1] && hv.a2 == c->r[2] && hv.a3 == c->r[3])) {
if (c->r[3] >= 255u || (c->r[1] & 0xFFu) == 255u) return 0; /* would run forever in the firmware too */
hv.sp = c->r[13]; hv.lr = c->r[14]; hv.a0 = c->r[0]; hv.a1 = c->r[1]; hv.a2 = c->r[2]; hv.a3 = c->r[3];
hv.idx = (uint16_t)(c->r[2] + (c->r[0] << 7)); hv.y = (uint8_t)c->r[0]; hv.x = (uint8_t)c->r[2]; hv.on = 1;
HK(K_CALL); cyc += HC(K_CALL);
}
uint32_t fb = rd32a(c, hv.fbv), y1 = hv.a1 & 0xFFu, x0 = hv.a2 & 0xFFu, x1 = hv.a3, adj = (hv.a2 - hv.a3 + 127u) & 0xFFFFu;
uint32_t lo = hr8(c, hv.lo), hi = hr8(c, hv.lo + 1u);
const uint8_t *T = sp_(hv.tr + hv.toff); /* the colour tables: SRAM outside the hole (checked by the search) */
uint32_t y = hv.y, x = hv.x, idx = hv.idx;
hrow_t rw;
while (y <= y1) {
row_pick(c, &rw, R0, n, y, hc);
uint16_t *fp = fb_row(c, fb + (idx << 1), x1 + 1u - x, idx);
while (x <= x1) {
uint32_t v = rw.slow ? pixel_all(c, R0, n, x, y, fb, &cyc, hc) : pixel(c, &rw, R0, x, y, fb, &cyc, hc);
#ifdef T18_HLE_CHECK
rej_count(R0, n, y);
#endif
uint32_t R, G, B;
if (v < 0x200u) { R = T[v]; G = T[0x200u + v]; B = T[0x400u + v]; }
else { uint32_t a = hv.tr + hv.toff + v; R = hr8(c, a); G = hr8(c, a + 0x200u); B = hr8(c, a + 0x400u); }
if (lo > v) { HK(K_ST1); cyc += HC(K_ST1); }
else if (hi <= v) { HK(K_ST2); cyc += HC(K_ST2); }
else if (y > 64u) { HK(K_ST3); cyc += HC(K_ST3); }
else {
R = ((R * y + 88u * (64u - y)) & 0xFFFFu) >> 6;
G = ((G * y + 81u * (64u - y)) & 0xFFFFu) >> 6;
B = ((B * y + 160u * (64u - y)) & 0xFFFFu) >> 6;
HK(K_BLEND); cyc += HC(K_BLEND);
}
HK(K_PIX); cyc += HC(K_PIX);
uint32_t px = (((R >> 3) & 0x1Fu) << 11) | ((G << 3) & 0x7E0u) | ((B & 0xFFu) >> 3);
#ifdef T18_HLE_CHECK
if (hf_dry) hf_dry[idx] = (uint16_t)px; else
#endif
if (fp) *fp++ = (uint16_t)px; else wr16(c, fb + (idx << 1), px);
idx = (idx + 1u) & 0xFFFFu; x = (x + 1u) & 0xFFu;
if (HF_SLICE && x <= x1 && c->cycles + (uint64_t)((cyc * t18_hle_q) >> 4) * mult >= target) {
hv.y = (uint8_t)y; hv.x = (uint8_t)x; hv.idx = (uint16_t)idx;
c->cycles += (uint64_t)((cyc * t18_hle_q) >> 4) * mult;
return 1;
}
}
idx = (idx + adj) & 0xFFFFu; y = (y + 1u) & 0xFFu; x = x0; HK(K_ROW); cyc += HC(K_ROW);
}
hv.on = 0;
#ifdef T18_HLE_CHECK
if (hf_dry) { uint32_t sum = 0; for (int k = 0; k < K_N; k++) sum += hk[k] * hc[k];
if (sum != cyc) { extern uint32_t t18_hle_cbad; t18_hle_cbad++; }
return 1; }
#endif
#if defined(T18_HLE_CHECK) || defined(T18_HLE_COUNT)
t18_hle_n++;
#endif
t18_hle_done++;
#ifdef T18_HLE_LOG
{ extern void t18_hle_log(arm7_t *, uint32_t, uint32_t, uint32_t, uint32_t); t18_hle_log(c, hv.a0, hv.a1, hv.a2, hv.a3); }
#endif
c->cycles += (uint64_t)((cyc * t18_hle_q) >> 4) * mult;
uint32_t lr = c->r[14];
c->r[0] = lr; c->r[15] = lr & ~1u;
if (!(lr & 1u)) c->cpsr &= ~ARM7_T;
return 1;
}
/* find the fill routine in the guest's SRAM (the firmware copies its code there); 1 when found */
HLE_COLD int t18_hle_find(void)
{
for (uint32_t o = 0x100u; o + 0x200u <= T18_SRAM_SIZE; o += 2) {
if (o + 0x200u > T18_HOLE_LO && o < T18_HOLE_HI) { o = T18_HOLE_HI; continue; }
const uint8_t *p = t18_sram + o;
/* push {r4-r7,lr}; mov r7,fp; mov r6,sl; mov r5,r9; mov r4,r8; push {r4-r7}; sub sp,#44; str r2,[sp,#12]; mov r8,r3 */
if (g32(p) != 0x465FB5F0u || g32(p + 4) != 0x464D4656u || g32(p + 8) != 0xB4F04644u || g32(p + 12) != 0x9203B08Bu || g16(p + 16) != 0x4698u) continue;
uint32_t a = 0xF8000000u + o;
if ((g16(p + 0xB0) & 0xF800u) != 0xF000u || fp_code(a, 0x1E8u) != HF_FP_FILL) continue;
uint32_t pix = bl_tgt(a + 0xB0u);
if (pix - 0xF8000000u >= T18_SRAM_SIZE - 0x280u) continue;
const uint8_t *q = sp_(pix);
uint32_t kind = 0, L = 0, fbl = 0, dvl = 0;
if (g16(q + 12) == 0xB087u && g16(q + 14) == 0x9004u && (g16(q + 16) & 0xFF00u) == 0x4B00u && g16(q + 18) == 0x7A1Cu) {
uint32_t sm = bl_tgt(pix + 0xE4u); /* kind 1: sub sp,#28; str r0,[sp,#16]; ldr r3,=list; ldrb r4,[r3,#8] */
#ifdef T18_HLE_FP
{ extern void t18_hle_fp(int, uint32_t, uint32_t, uint32_t); t18_hle_fp(1, fp_code(a, 0x1E8u), fp_code(pix, 0x130u), sm - 0xF8000000u < T18_SRAM_SIZE - 0xE0u ? fp_code(sm, 0xDCu) : 0); }
#endif
if (sm - 0xF8000000u >= T18_SRAM_SIZE - 0xE0u || fp_code(pix, 0x130u) != HF_FP_PIX1 || fp_code(sm, 0xDCu) != HF_FP_SMP1) continue;
kind = 1; L = lit(pix + 16u); fbl = lit(pix + 0x3Au); dvl = lit(pix + 0xF8u); hv.cnt = 8; hv.rec = 12;
} else if (g16(q + 12) == 0xB085u && (g16(q + 14) & 0xFF00u) == 0x4B00u && g16(q + 16) == 0x791Cu) {
#ifdef T18_HLE_FP
{ extern void t18_hle_fp(int, uint32_t, uint32_t, uint32_t); t18_hle_fp(2, fp_code(a, 0x1E8u), fp_code(pix, 0x27Cu), 0); }
#endif
if (fp_code(pix, 0x27Cu) != HF_FP_PIX2) continue; /* kind 2: sub sp,#20; ldr r3,=list; ldrb r4,[r3,#4] */
kind = 2; L = lit(pix + 14u); fbl = lit(pix + 0x23Au); dvl = lit(pix + 0xF0u); hv.cnt = 4; hv.rec = 8;
} else continue;
uint32_t tr = lit(a + 0x46u);
if (lit(a + 0x4Au) != tr + 0x200u || lit(a + 0xCAu) != tr + 0x400u || lit(a + 0xE2u) != lit(a + 0xD6u) + 1u || fbl != lit(a + 0x6Eu)) continue;
if (L - 0xF8000000u >= T18_SRAM_SIZE - 20u * 256u - 16u) continue;
{ uint32_t to = tr - 0xF8000000u; /* tables (3 x 0x200 + offset) in the SRAM, not in the hole */
if (to + 0x620u > T18_SRAM_SIZE || t18_hole_n(to, 0x620u)) continue; }
/* the divide helper of the "inverted" layers (bit 13): ARM __aeabi_idivmod as in all firmwares seen */
{ uint8_t b[16]; for (uint32_t i = 0; i < 16; i++) b[i] = t18_flash_rd((dvl - 0x20000000u + i) & 0x7FFFFFu);
if (dvl - 0x20000000u >= 0x800000u || g32(b) != 0xE3510000u || g32(b + 8) != 0xE92D4003u || g32(b + 12) != 0xEBFFFFB3u) continue; }
hv.kind = (uint8_t)kind; hv.L = L; hv.fbv = fbl; hv.tr = tr; hv.lo = lit(a + 0xD6u);
hv.toff = (uint8_t)((g16(p + 0xBC) >> 6) & 31u); hv.on = 0;
t18_hle_pc = a;
return 1;
}
return 0;
}
#ifdef T18_HLE_CHECK
#include <stdio.h>
#include <stdlib.h>
uint32_t t18_exc_n; /* exceptions taken (t18cpu.c) */
uint32_t t18_hle_cbad; /* fills whose charged cycles differ from the counters */
static struct { uint32_t on, sp, lr, fb, a0, a1, a2, a3; uint32_t cnt[K_N]; } ck;
uint64_t t18_hle_own; /* cycles of the routine's own code while checking (t18cpu.c) */
uint32_t t18_hle_bad, t18_hle_ok, t18_hle_dv, t18_hle_px, t18_hle_sm;
static inline int hle_own(uint32_t pc) { return ck.on && (pc - t18_hle_pc < 0x1E8u || pc - t18_hle_px < (hv.kind == 1 ? 0x130u : 0x27Cu) || (hv.kind == 1 && pc - t18_hle_sm < 0xDCu) || pc - t18_hle_dv < 0x144u); }
void t18_hle_cfit(const uint32_t *cnt, int n, uint64_t cycles, int clean); /* host/ref.c */
static void t18_hle_chk(arm7_t *c)
{
static uint16_t dry[65536];
if (ck.on && c->r[15] == (ck.lr & ~1u) && c->r[13] == ck.sp) {
ck.on = 0;
uint32_t y0 = ck.a0 & 0xFFu, y1 = ck.a1 & 0xFFu, x0 = ck.a2 & 0xFFu, idx = (ck.a2 + (ck.a0 << 7)) & 0xFFFFu, bad = 0;
for (uint32_t y = y0; y <= y1; y++) {
uint32_t i = idx;
for (uint32_t x = x0; x <= ck.a3; x++) { if (rd16(c, ck.fb + (i << 1)) != dry[i]) { if (!bad && getenv("HLE_DIFF")) fprintf(stderr, "diff x %u y %u guest %04x hle %04x\n", x, y, rd16(c, ck.fb + (i << 1)), dry[i]); bad++; } i = (i + 1u) & 0xFFFFu; }
idx = (idx + 128u) & 0xFFFFu;
}
if (bad && getenv("HLE_DIFF")) {
uint32_t sv[6]; memcpy(sv, c->r, 16); sv[4] = c->r[13]; sv[5] = c->r[14];
c->r[0] = ck.a0; c->r[1] = ck.a1; c->r[2] = ck.a2; c->r[3] = ck.a3; c->r[13] = ck.sp; c->r[14] = ck.lr;
hf_dry = dry; t18_hle_fill(c, ~0ull); hf_dry = 0;
memcpy(c->r, sv, 16); c->r[13] = sv[4]; c->r[14] = sv[5];
uint32_t bad2 = 0, i2 = (ck.a2 + (ck.a0 << 7)) & 0xFFFFu;
for (uint32_t y = y0; y <= y1; y++) { uint32_t i = i2; for (uint32_t x = x0; x <= ck.a3; x++) { if (rd16(c, ck.fb + (i << 1)) != dry[i]) bad2++; i = (i + 1u) & 0xFFFFu; } i2 = (i2 + 128u) & 0xFFFFu; }
fprintf(stderr, " computed again at the end: %u differ\n", bad2);
fprintf(stderr, " %u pixels differ of %u x %u, args %x %x %x %x, layers %u\n", bad, ck.a3 + 1u - x0, y1 + 1u - y0, ck.a0, ck.a1, ck.a2, ck.a3, sp_(hv.L)[hv.cnt]);
const uint8_t *R0 = sp_(hv.L) + hv.rec;
for (uint32_t i = 0; i < sp_(hv.L)[hv.cnt]; i++) { const uint8_t *e = R0 + 20u * i;
fprintf(stderr, " L%2u img %08x x %4x y %4x w %3u h %3u pal %4x f %04x off %4x\n", i, g32(e), g16(e+4), g16(e+6), e[8], e[9], g16(e+12), g16(e+14), g16(e+16)); }
}
if (bad) t18_hle_bad++; else t18_hle_ok++;
t18_hle_cfit(ck.cnt, K_N, t18_hle_own, !bad);
return;
}
if (!ck.on && t18_hle_pc != 1u && c->r[15] == t18_hle_pc && (c->cpsr & ARM7_T) && !c->watch) {
ck.sp = c->r[13]; ck.lr = c->r[14]; ck.a0 = c->r[0]; ck.a1 = c->r[1]; ck.a2 = c->r[2]; ck.a3 = c->r[3];
ck.fb = rd32a(c, hv.fbv); t18_hle_own = 0;
t18_hle_px = bl_tgt(t18_hle_pc + 0xB0u); t18_hle_sm = bl_tgt(t18_hle_px + 0xE4u);
t18_hle_dv = lit(t18_hle_px + (hv.kind == 1 ? 0xF8u : 0xF0u)) - 0x120u;
memset(hk, 0, sizeof hk); hf_dry = dry; int ok = t18_hle_fill(c, ~0ull); hf_dry = 0;
if (ok) { memcpy(ck.cnt, hk, sizeof ck.cnt); ck.on = 1; }
}
}
#endif
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+88
View File
@@ -0,0 +1,88 @@
/* TG18 (Meets/On) SoC model for the Paradise, from the T18Emu core. */
#ifndef T18SOC_H
#define T18SOC_H
#include <stdint.h>
#include "t18cpu.h"
#define TG18_W 128
#define TG18_H 128
#define TG18_FLASH_SIZE 0x800000
#define TG18_MASTER_HZ 96000000u
#define TG18_BTN_A 1
#define TG18_BTN_B 2
#define TG18_BTN_C 4
typedef struct tg18 tg18_t;
/* a finished picture: src = guest address of the buffer (RGB565, 128 wide), len in bytes */
typedef void (*t18_present_fn)(void *user, uint32_t src, uint32_t len);
/* platform: the guest's SPI flash (8 MB) */
uint8_t t18_flash_rd(uint32_t a);
void t18_flash_prog(uint32_t a, uint8_t b); /* program: bits only go from 1 to 0 */
void t18_flash_erase(uint32_t a, uint32_t size); /* a aligned to size (4, 32 or 64 KB) */
uint32_t tg18_struct_size(void);
void tg18_init(tg18_t *t, const uint8_t *rom, uint32_t len);
void tg18_reset(tg18_t *t);
void tg18_run_cycles(tg18_t *t, uint64_t target);
void tg18_run_us(tg18_t *t, uint32_t us);
/* 1.6.13 test1 (T18_PW): as tg18_run_us; while the game is switched off nothing runs; when it switches on (alarm, key)
* on() is called first (the platform goes back to full speed), then the rest of the time runs as usual */
void tg18_run_us_off(tg18_t *t, uint32_t us, void (*on)(void));
uint64_t tg18_cycles(tg18_t *t);
void tg18_set_buttons(tg18_t *t, int mask);
#ifdef T18_LINK
/* test6: phone side of the Bluetooth module over a link (Paradise UART) */
void tg18_link_out(const uint8_t *d, int n); /* given by the platform: data for the phone */
/* test7: infrared of a visit to and from the other Paradise (given by the platform) */
void tg18_link_ir_out(uint8_t b);
int tg18_link_ir_in(uint8_t *b);
int tg18_link_ir_avail(void);
void tg18_ble_connect(tg18_t *t, int on);
int tg18_ble_ready(tg18_t *t);
int tg18_ble_from_phone(tg18_t *t, const uint8_t *d, int n);
#endif
void tg18_set_present(tg18_t *t, t18_present_fn fn, void *user);
#ifndef PARADISE
const uint16_t *tg18_picture(tg18_t *t); /* PC: the last finished picture */
#endif
int tg18_frame_count(tg18_t *t);
int tg18_picture_count(tg18_t *t);
uint32_t tg18_tone_hz(tg18_t *t);
int tg18_backlight(tg18_t *t);
void tg18_set_time(tg18_t *t, int y, int mo, int d, int h, int mi, int s);
void tg18_get_time(tg18_t *t, int *out6);
extern int tg18_uhr_wecken;
void tg18_advance_offline(tg18_t *t, int64_t seconds);
void tg18_set_cpu_k(tg18_t *t, int k); /* T18_CPU_SLOW: the CPU at 4/k of its clock */
uint32_t tg18_state_size(tg18_t *t);
int tg18_save_state(tg18_t *t, uint8_t *buf, uint32_t len);
int tg18_load_state(tg18_t *t, const uint8_t *buf, uint32_t len);
int tg18_flash_dirty(tg18_t *t);
void tg18_flash_clean(tg18_t *t);
int tg18_power(tg18_t *t);
void tg18_set_rtc_cb(tg18_t *t, void (*cb)(void *t)); /* 1.6.8: firmware loaded the battery RTC */
void tg18_set_addrs(tg18_t *t, uint32_t idle_addr, uint32_t softrtc, uint32_t dma_tab);
void tg18_get_addrs(tg18_t *t, uint32_t *out3);
void tg18_set_param_addr(tg18_t *t, uint32_t a);
int tg18_attention(tg18_t *t);
uint32_t tg18_sysclk(tg18_t *t);
uint32_t tg18_boot_count(tg18_t *t);
arm7_t *tg18_cpu(tg18_t *t);
int tg18_sf_fast(void *ctx, uint32_t a, uint32_t *v, int wr); /* SPI flash registers, word access (1.6.6) */
void tg18_set_trace(tg18_t *t, int on);
int tg18_param_get16(tg18_t *t, uint32_t off);
int tg18_param_set16(tg18_t *t, uint32_t off, int v);
void tg18_set_clock_mult(tg18_t *t, int mult);
int tg18_clock_mult(tg18_t *t);
void tg18_set_keep_awake(tg18_t *t, int on);
uint32_t tg18_idle_addr(tg18_t *t);
void tg18_set_cpu_boost(tg18_t *t, int k);
int tg18_next_wake_s(tg18_t *t);
#ifdef T18_JIT
void t18_jit_reset(void);
#endif
#endif
+154
View File
@@ -0,0 +1,154 @@
/* Thumb-2 encoder for the T18 translator (Cortex-M3 code). Each function appends to *J. */
#ifndef T2ENC_H
#define T2ENC_H
#include <stdint.h>
extern uint16_t *J; /* write pointer (halfwords) */
/* every write into the code buffer goes through JW: on the Paradise the buffer is in the PRAM, where a
* write must not meet an instruction fetch from the PRAM (t18_pram_w16 runs from the flash window) */
#ifdef T18_PRAM_WR
void t18_pram_w16(uint16_t *p, uint32_t v);
#define JW(p, v) t18_pram_w16((p), (uint32_t)(v))
#else
#define JW(p, v) (*(p) = (uint16_t)(v))
#endif
static inline void E16(uint32_t h) { JW(J, h); J++; }
static inline void E32(uint32_t hw1, uint32_t hw2) { JW(J, hw1); JW(J + 1, hw2); J += 2; }
/* modified immediate (ThumbExpandImm): returns i:imm3:imm8 as 12 bits, or -1 */
static inline int t2_modimm(uint32_t v)
{
if (v < 256) return (int)v;
uint32_t b = v & 0xFF;
if (v == (b | b << 16) && b) return (int)(0x100 | b);
if (v == (b << 8 | b << 24) && b) return (int)(0x200 | b);
if (v == (b | b << 16 | b << 8 | b << 24) && b) return (int)(0x300 | b);
/* 1.6.6: the 8 bits straight from the highest and lowest set bit (was a loop over 24 rotations) */
int hb = 31 - __builtin_clz(v), lb = __builtin_ctz(v);
if (hb - lb <= 7) {
uint32_t sh = (uint32_t)hb - 7u; /* >= 1 as v >= 256 */
return (int)(((32u - sh) << 7) | ((v >> sh) & 0x7Fu));
}
if (!((v & 1u) && (v >> 31))) return -1; /* only a value around bit 0 can still fit */
for (int rot = 8; rot < 32; rot++) {
uint32_t x = (v << rot) | (v >> (32 - rot)); /* undo ror(rot) */
if (x >= 0x80 && x < 0x100) return (int)((rot << 7) | (x & 0x7F));
}
return -1;
}
/* data processing (modified immediate): op = 4-bit opcode, s = set flags */
static inline void t2_dpimm(int op, int s, int rd, int rn, int imm12)
{
E32(0xF000u | (uint32_t)((imm12 >> 11) & 1) << 10 | (uint32_t)op << 5 | (uint32_t)s << 4 | (uint32_t)rn,
(uint32_t)((imm12 >> 8) & 7) << 12 | (uint32_t)rd << 8 | (uint32_t)(imm12 & 0xFF));
}
enum { T2_AND = 0, T2_BIC = 1, T2_ORR = 2, T2_ORN = 3, T2_EOR = 4, T2_ADD = 8, T2_ADC = 10, T2_SBC = 11, T2_SUB = 13, T2_RSB = 14 };
/* ADDW / SUBW rd, rn, #0..4095 (no flags) */
static inline void t2_addw(int rd, int rn, uint32_t imm)
{
E32(0xF200u | ((imm >> 11) & 1) << 10 | (uint32_t)rn, ((imm >> 8) & 7) << 12 | (uint32_t)rd << 8 | (imm & 0xFF));
}
static inline void t2_subw(int rd, int rn, uint32_t imm)
{
E32(0xF2A0u | ((imm >> 11) & 1) << 10 | (uint32_t)rn, ((imm >> 8) & 7) << 12 | (uint32_t)rd << 8 | (imm & 0xFF));
}
/* MOVW / MOVT */
static inline void t2_movw(int rd, uint32_t imm)
{
E32(0xF240u | ((imm >> 11) & 1) << 10 | ((imm >> 12) & 15), ((imm >> 8) & 7) << 12 | (uint32_t)rd << 8 | (imm & 0xFF));
}
static inline void t2_movt(int rd, uint32_t imm)
{
E32(0xF2C0u | ((imm >> 11) & 1) << 10 | ((imm >> 12) & 15), ((imm >> 8) & 7) << 12 | (uint32_t)rd << 8 | (imm & 0xFF));
}
static inline void t2_mov32(int rd, uint32_t v)
{
int m = t2_modimm(v);
if (m >= 0) { t2_dpimm(2, 0, rd, 15, m); return; } /* MOV.W (ORR with rn=PC) */
int n = t2_modimm(~v);
if (n >= 0) { t2_dpimm(3, 0, rd, 15, n); return; } /* MVN.W */
t2_movw(rd, v & 0xFFFF);
if (v >> 16) t2_movt(rd, v >> 16);
}
/* add rd, rn, #v with any v (no flags); may use rd as temporary only if rd != rn */
static inline void t2_addi(int rd, int rn, uint32_t v)
{
if (v == 0) { if (rd != rn) E16(0x4600u | (uint32_t)(rd & 8) << 4 | (uint32_t)rn << 3 | (uint32_t)(rd & 7)); return; }
int m = t2_modimm(v);
if (m >= 0) { t2_dpimm(T2_ADD, 0, rd, rn, m); return; }
m = t2_modimm(0u - v);
if (m >= 0) { t2_dpimm(T2_SUB, 0, rd, rn, m); return; }
if (v < 4096) { t2_addw(rd, rn, v); return; }
if (0u - v < 4096) { t2_subw(rd, rn, 0u - v); return; }
/* the low 12 bits, then 8-bit windows from the top (each one is a modified immediate) */
uint32_t lo = v & 0xFFFu, hi = v & ~0xFFFu;
if (lo) { t2_addw(rd, rn, lo); rn = rd; }
while (hi) {
int top = 31 - __builtin_clz(hi), sh = top - 7;
uint32_t part = hi & (0xFFu << sh);
t2_dpimm(T2_ADD, 0, rd, rn, t2_modimm(part)); rn = rd; hi &= ~part;
}
}
/* MOV rd, rm (any registers, 16 bit) */
static inline void t2_mov(int rd, int rm) { if (rd != rm) E16(0x4600u | (uint32_t)(rd & 8) << 4 | (uint32_t)rm << 3 | (uint32_t)(rd & 7)); }
/* shifts by immediate, no flags: type 0 LSL 1 LSR 2 ASR 3 ROR */
static inline void t2_shi(int type, int rd, int rm, int n)
{
E32(0xEA4Fu, (uint32_t)((n >> 2) & 7) << 12 | (uint32_t)rd << 8 | (uint32_t)(n & 3) << 6 | (uint32_t)type << 4 | (uint32_t)rm);
}
/* register-register data processing with optional shift (no flags unless s) */
static inline void t2_dpreg(int op, int s, int rd, int rn, int rm, int type, int n)
{
E32(0xEA00u | (uint32_t)op << 5 | (uint32_t)s << 4 | (uint32_t)rn, (uint32_t)((n >> 2) & 7) << 12 | (uint32_t)rd << 8 | (uint32_t)(n & 3) << 6 | (uint32_t)type << 4 | (uint32_t)rm);
}
/* CMP.W rn, #imm (modified immediate) */
static inline void t2_cmpi(int rn, int imm12) { t2_dpimm(T2_SUB, 1, 15, rn, imm12); }
/* UBFX rd, rn, #lsb, #width */
static inline void t2_ubfx(int rd, int rn, int lsb, int width)
{
E32(0xF3C0u | (uint32_t)rn, (uint32_t)((lsb >> 2) & 7) << 12 | (uint32_t)rd << 8 | (uint32_t)(lsb & 3) << 6 | (uint32_t)(width - 1));
}
/* loads and stores, immediate 0..4095: size 0 byte 1 half 2 word; sign for loads */
static inline void t2_ldst_i(int load, int size, int sign, int rt, int rn, uint32_t imm)
{
uint32_t op = 0xF880u | (uint32_t)size << 5 | (uint32_t)load << 4 | (uint32_t)sign << 8;
E32(op | (uint32_t)rn, (uint32_t)rt << 12 | (imm & 0xFFF));
}
/* loads and stores, register offset (rn + rm) */
static inline void t2_ldst_r(int load, int size, int sign, int rt, int rn, int rm)
{
uint32_t op = 0xF800u | (uint32_t)size << 5 | (uint32_t)load << 4 | (uint32_t)sign << 8;
E32(op | (uint32_t)rn, (uint32_t)rt << 12 | (uint32_t)rm);
}
/* LDMIA.W rn!, {list} / STMDB.W rn!, {list} / LDMIA / STMIA without writeback */
static inline void t2_ldmia(int rn, uint32_t list, int wb) { E32(0xE890u | (uint32_t)wb << 5 | (uint32_t)rn, list); }
static inline void t2_stmia(int rn, uint32_t list, int wb) { E32(0xE880u | (uint32_t)wb << 5 | (uint32_t)rn, list); }
static inline void t2_stmdb(int rn, uint32_t list, int wb) { E32(0xE900u | (uint32_t)wb << 5 | (uint32_t)rn, list); }
/* MRS rd, APSR / MSR APSR_nzcvq, rn */
static inline void t2_mrs(int rd) { E32(0xF3EFu, 0x8000u | (uint32_t)rd << 8); }
static inline void t2_msr(int rn) { E32(0xF380u | (uint32_t)rn, 0x8800u); }
/* PUSH/POP (16 bit, low registers + lr/pc) */
static inline void t2_push(uint32_t list) { E16(0xB400u | (list & 0xFF) | ((list >> 14) & 1) << 8); }
static inline void t2_pop(uint32_t list) { E16(0xBC00u | (list & 0xFF) | ((list >> 15) & 1) << 8); }
/* branches: at = position of the instruction, to = target (halfword pointers) */
static inline void t2_b_at(uint16_t *at, const uint16_t *to)
{
int32_t off = (int32_t)((const char *)to - ((const char *)at + 4));
uint32_t s = (uint32_t)(off < 0), imm = (uint32_t)off >> 1;
uint32_t j1 = ((~(imm >> 22) ^ s) & 1), j2 = ((~(imm >> 21) ^ s) & 1);
JW(&at[0], 0xF000u | s << 10 | ((imm >> 11) & 0x3FF));
JW(&at[1], 0x9000u | j1 << 13 | j2 << 11 | (imm & 0x7FF));
}
static inline void t2_bl_at(uint16_t *at, const void *to)
{
t2_b_at(at, (const uint16_t *)to); JW(&at[1], at[1] | 0x4000u);
}
static inline void t2_bcc_at(uint16_t *at, const uint16_t *to, int cond)
{
int32_t off = (int32_t)((const char *)to - ((const char *)at + 4));
uint32_t s = (uint32_t)(off < 0), imm = (uint32_t)off >> 1;
uint32_t j1 = (imm >> 18) & 1, j2 = (imm >> 17) & 1;
JW(&at[0], 0xF000u | s << 10 | (uint32_t)cond << 6 | ((imm >> 11) & 0x3F));
JW(&at[1], 0x8000u | j1 << 13 | j2 << 11 | (imm & 0x7FF));
}
#endif
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+14
View File
@@ -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
+365
View File
@@ -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]))
+23
View File
@@ -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*) }
}
+12
View File
@@ -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*) }
}
+134
View File
@@ -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 */
+52
View File
@@ -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))
+382
View File
@@ -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])
+44
View File
@@ -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))