b25: S12v2-full + B66-ELF + S16 baked

This commit is contained in:
lumia-emu
2026-09-13 12:01:19 +00:00
parent 48969c60f3
commit 7eef1340b6
4 changed files with 197 additions and 17 deletions
+7 -2
View File
@@ -105,5 +105,10 @@
вход → `bx lr` (lr = брошенный-но-валидный `0x80076CD`). вход → `bx lr` (lr = брошенный-но-валидный `0x80076CD`).
- Poll `[0x73A100]` (lsls#29+bpl = проверка bit2!): SBL только читает → - Poll `[0x73A100]` (lsls#29+bpl = проверка bit2!): SBL только читает →
фабрикация bit2=1 (b24 scaffold, обе стороны). фабрикация bit2=1 (b24 scaffold, обе стороны).
- `blx #0x8006964` в файловые нули паддинга (PBL scratch) → S12 (b24 - `blx #0x8006964` в файловые нули паддинга (PBL scratch) → S12v2 (b25
scaffold, без ELF): `bx lr` (caller игнорирует r0). scaffold, ARM! т.к. blx-imm на чётный): preset ip=S16 + ACK bit1
`[0x73A100]` (side effect для poll#2) + `bx lr`. Литерал `[0x8006980]`.
- Helper-pop `0x8007B66` читает scratch (счётчики 0-4 вместо pushed lr,
фреймы съедены null-циклами) → S16 (b25): цепочка S12(ip) → B66
(`pop``bx ip`, 2B без пожирания) → S16 (restore r7, прыжок
`0x8007779`). B66-патч в ELF (b25), S12/S16 в scaffold.
+38 -8
View File
@@ -104,15 +104,15 @@ static void saimaa_tmr_init(Object *obj)
/* Stubs region handle for set_readonly after scaffold implant. */ /* Stubs region handle for set_readonly after scaffold implant. */
static MemoryRegion *saimaa_stubs_mr; static MemoryRegion *saimaa_stubs_mr;
/* DDRLOW stub trap [0x08006B80,0x08006CA0): serves the scaffolded bytes /* DDRLOW stub trap [0x08006B80,0x08006CE0): serves the scaffolded bytes
* (S/maze/S6/banner/S7/S9/S10 stubs) on read/fetch, ignores SBL * (S/maze/S6/banner/S7/S9/S10/S16 stubs) on read/fetch, ignores SBL
* heap-clobber writes. Uni parity: deferred-restore guard in sbl_uni.py * heap-clobber writes. Uni parity: deferred-restore guard in sbl_uni.py
* (wider: [0x080068C0,0x08006CA0), also covers PBL stub). * (wider: [0x080068C0,0x08006CE0), also covers PBL stub).
* Snapshot is taken AFTER ELF load + all stub writes (readback). * Snapshot is taken AFTER ELF load + all stub writes (readback).
* PBL stub [0x080068C0,0x080068F4) and the ELF-text gap below stay plain * PBL stub [0x080068C0,0x080068F4) and the ELF-text gap below stay plain
* RAM: PBL runs once (if at all), gap holds real hot SBL code. */ * RAM: PBL runs once (if at all), gap holds real hot SBL code. */
#define SAIMAA_DSTUB_BASE 0x08006B80 #define SAIMAA_DSTUB_BASE 0x08006B80
#define SAIMAA_DSTUB_SIZE 0x00000120 #define SAIMAA_DSTUB_SIZE 0x00000160
static uint8_t saimaa_dstub_mem[SAIMAA_DSTUB_SIZE]; static uint8_t saimaa_dstub_mem[SAIMAA_DSTUB_SIZE];
static uint64_t saimaa_dstub_read(void *opaque, hwaddr off, unsigned size) static uint64_t saimaa_dstub_read(void *opaque, hwaddr off, unsigned size)
@@ -710,11 +710,41 @@ static void saimaa_machine_init(MachineState *machine)
uint32_t v = 0x47702000; uint32_t v = 0x47702000;
cpu_physical_memory_write(0x00221EF8, &v, 4); cpu_physical_memory_write(0x00221EF8, &v, 4);
} }
/* S12-stub (b25, 2B @0x08006964): blx-to-padding becomes /* S12-stub (b25, 32B @0x08006964, ARM): blx-to-padding
* bx lr (caller ignores r0). PBL would place ARM helper. */ * becomes movw/movt ip (=S16) + ACK peripheral bit1
* ([0x073A100], literal pool after code) + bx lr.
* PBL would place the real ARM helper here. */
{ {
uint16_t v = 0x4770; static const uint8_t s12[] = {
cpu_physical_memory_write(0x08006964, &v, 2); 0xc1, 0xcc, 0x06, 0xe3, 0x00, 0xc8, 0x40, 0xe3,
0x0c, 0x30, 0x9f, 0xe5, 0x00, 0x20, 0x93, 0xe5,
0x02, 0x20, 0x82, 0xe3, 0x00, 0x20, 0x83, 0xe5,
0x1e, 0xff, 0x2f, 0xe1, 0x00, 0xa1, 0x73, 0x00,
};
size_t k;
for (k = 0; k < sizeof(s12); k += 4) {
uint32_t word = 0;
size_t n = sizeof(s12) - k < 4 ? sizeof(s12) - k : 4;
__builtin_memcpy(&word, &s12[k], n);
cpu_physical_memory_write(0x08006964 + k, &word, 4);
}
}
/* S16-stublet (b25, 18B @0x08006CC0): helper-pop chain exit.
* restore r7 (peripheral base); jump to poll resumption
* 0x8007779 via ip. Entered via B66 bx ip (ip preset by S12). */
{
static const uint8_t s16[] = {
0x4a, 0xf2, 0x00, 0x07, 0xc0, 0xf2, 0x73, 0x07,
0x47, 0xf2, 0x79, 0x7c, 0xc0, 0xf6, 0x00, 0x0c,
0x60, 0x47,
};
size_t k;
for (k = 0; k < sizeof(s16); k += 4) {
uint32_t word = 0;
size_t n = sizeof(s16) - k < 4 ? sizeof(s16) - k : 4;
__builtin_memcpy(&word, &s16[k], n);
cpu_physical_memory_write(0x08006CC0 + k, &word, 4);
}
} }
{ {
uint32_t fill = 0x08006B8D; uint32_t fill = 0x08006B8D;
+89
View File
@@ -955,6 +955,95 @@ def main():
save(d, 'img0_b24.elf') save(d, 'img0_b24.elf')
# b25 = b24 + helper-pop S16 chain (0x8007B66 pop{r4,pc} -> bx ip):
# the pop reads scratch ([sp+4] = counters 0..4, frames marched by
# null-cycles) instead of pushed lr. bx ip uses ip preset by S12
# (ARM stub at 0x8006964) to S16 (0x08006CC0, scaffold): restore r7
# (peripheral base) and jump to poll-loop resumption 0x8007779.
# 2B patch, no eating (bx ip = 0x47c0 fits the pop slot).
d = bytearray(base)
for va, (a, b) in BLX2BL.items():
set4(d, va, b)
for va, exp, new in [
(0x802F664, 'e4f77efc', 'c046c046'),
(0x802F672, 'e6f7bbfa', 'c046c046'),
(0x802F678, 'e9f7fef9', 'c046c046'),
(0x801B71E, '9847fee7', 'c046c046'),
(0x8008396, 'fef780f9', 'c046c046'),
(0x8016184, 'fdf790fc', 'c046c046'),
(0x801B76C, '280b0508', '00000708'),
(0x8017AFC, 'bde8fc87', 'eef74fb8'),
(0x802F690, '9847fee7', 'c046c046'),
(0x801671C, '9847fee7', 'c046c046'),
(0x8013BAC, 'f8bd0a4a', 'f3f730b8'),
(0x801B6BE, 'bde8f081', 'ebf7c3ba'),
(0x8016720, '10bd0000', 'f0f7b2ba'),
]:
assert hx(d, va) == exp, (hex(va), hx(d, va))
set4(d, va, new)
# Full bl idiom at 0x8006682 (bl + pop, 6B) -> NOPs (see b18).
o = off(0x8006682)
assert d[o:o + 6].hex() == '00f001f807bd', hx(d, 0x8006682, 6)
d[o:o + 6] = bytes.fromhex('c046c046c046')
o = off(0x8013AA8)
assert d[o:o + 4].hex() == '07f026be', hx(d, 0x8013AA8)
d[o:o + 4] = bytes.fromhex('c046c046')
o = off(0x8013BA6)
assert d[o:o + 2].hex() == 'b888', (hex(0x8013BA6), hx(d, 0x8013BA6, 2))
d[o:o + 2] = bytes.fromhex('ff20')
# Logger S8 (see b21).
o = off(0x8034810)
assert d[o:o + 4].hex() == 'bde8fc87', hx(d, 0x8034810)
d[o:o + 2] = bytes.fromhex('7047')
# Clock S11 (see b24).
o = off(0x800E988)
assert d[o:o + 2].hex() == '10bd', hx(d, 0x800E988, 2)
d[o:o + 2] = bytes.fromhex('7047')
# Helper-pop S16 chain: pop{r4,pc} (2B 10bd) -> bx ip (2B 4760;
# ip preset by S12 to S16). 0x47c0 would be bx lr (wrong reg!).
o = off(0x8007B66)
assert d[o:o + 2].hex() == '10bd', hx(d, 0x8007B66, 2)
d[o:o + 2] = bytes.fromhex('6047')
save(d, 'img0_b25.elf')
+63 -7
View File
@@ -104,6 +104,12 @@ def main():
calls = [] if "--calltrace" in sys.argv else None calls = [] if "--calltrace" in sys.argv else None
rets = [] if "--retrace" in sys.argv else None rets = [] if "--retrace" in sys.argv else None
qlog = [] if "--querylog" in sys.argv else None qlog = [] if "--querylog" in sys.argv else None
_traps = []
_trap_n = [0]
if "--trap" in sys.argv:
_traps = [int(x, 0) for x in sys.argv[sys.argv.index("--trap") + 1].split(",")]
if "--trapn" in sys.argv:
_trap_n = [int(sys.argv[sys.argv.index("--trapn") + 1])]
_spmax = [0x085FFF00] _spmax = [0x085FFF00]
_splog = [] if "--spytrack" in sys.argv else None _splog = [] if "--spytrack" in sys.argv else None
elog = [] if "--entrylog" in sys.argv else None elog = [] if "--entrylog" in sys.argv else None
@@ -145,6 +151,23 @@ def main():
except Exception: except Exception:
thumb = 1 thumb = 1
hist.append((addr, thumb)) hist.append((addr, thumb))
if _traps and addr in _traps:
try:
vals = [mu.reg_read(_REGS[i]) for i in range(8)]
except Exception:
vals = []
print(f"TRAP {addr:#x} insn#{count[0]} r0-r7={[hex(x) for x in vals]} sp={mu.reg_read(UC_ARM_REG_SP):#x} lr={mu.reg_read(_LR):#x}")
try:
print(f" [73A100]={bytes(mu.mem_read(0x073A100, 4)).hex()}")
except Exception as e:
print(f" [73A100] unreadable: {e}")
_trap_n[0] -= 1
if _trap_n[0] <= 0 and "--trapn" in sys.argv:
mu.emu_stop()
return
if "--trapn" not in sys.argv:
mu.emu_stop()
return
if qlog is not None and addr in (0x8017EA4, 0x8017C60): if qlog is not None and addr in (0x8017EA4, 0x8017C60):
try: try:
vals = [mu.reg_read(_REGS[i]) for i in range(8)] vals = [mu.reg_read(_REGS[i]) for i in range(8)]
@@ -163,6 +186,9 @@ def main():
except Exception: except Exception:
_th = -1 _th = -1
elog.append((count[0], _prev[0], addr, _th)) elog.append((count[0], _prev[0], addr, _th))
if not inside and _inrng[_i]:
if len(elog) < 20000:
elog.append((count[0], _prev[0], -addr, 2))
_inrng[_i] = inside _inrng[_i] = inside
_prev[0] = addr _prev[0] = addr
if calls is not None and size in (2, 4): if calls is not None and size in (2, 4):
@@ -186,6 +212,15 @@ def main():
bxt = -1 bxt = -1
if len(calls) < 8000: if len(calls) < 8000:
calls.append((addr, 100 + bxrm, bxt)) calls.append((addr, 100 + bxrm, bxt))
# pop {..,pc} (0xBD00+): log stacked target
if calls is not None and (h & 0xFF00) == 0xBD00:
try:
_sp = mu.reg_read(UC_ARM_REG_SP)
_tgt = struct.unpack("<I", mu.mem_read(_sp, 4))[0]
except Exception:
_tgt = -1
if len(calls) < 12000:
calls.append((addr, 300, _tgt))
if rets is not None and 0x8017E00 <= addr < 0x8018000: if rets is not None and 0x8017E00 <= addr < 0x8018000:
# pop {..,pc} (0xBD00+) or bx lr (0x4770) # pop {..,pc} (0xBD00+) or bx lr (0x4770)
if h == 0x4770 or (h & 0xFF00) == 0xBD00: if h == 0x4770 or (h & 0xFF00) == 0xBD00:
@@ -345,10 +380,19 @@ def main():
# to the dispatcher via stale lr (TZ bringup deferred). # to the dispatcher via stale lr (TZ bringup deferred).
# NOTE: overwrites 4B of real ARM trampoline (recoverable from ELF). # NOTE: overwrites 4B of real ARM trampoline (recoverable from ELF).
mu.mem_write(0x00221EF8, bytes([0x00, 0x20, 0x70, 0x47])) mu.mem_write(0x00221EF8, bytes([0x00, 0x20, 0x70, 0x47]))
# S12-stub (b25): blx #0x8006964 lands in file-zero padding (PBL # S12-stub (b25): blx #0x8006964 (BLX-imm to even => ARM mode!) lands
# would place an ARM helper there at runtime). Caller ignores r0 # in file-zero padding (PBL would place an ARM helper). ARM version:
# (movs r0,#0 after), so bx lr no-op return is safe. # movw/movt ip (=S16 addr, for the pop-site chain); ldr r3,[pc,#12]
mu.mem_write(0x08006964, bytes([0x70, 0x47])) # (literal [0x8006980] = 0x073A100); ACK peripheral bit1 (the real
# helper's side effect that poll#2 waits for); bx lr.
mu.mem_write(0x08006964, bytes.fromhex(
"c1cc06e300c840e30c309fe5002093e5022082e3002083e5"
"1eff2fe100a17300"))
# S16-stublet (b25, 18B @0x08006CC0): helper-pop chain exit.
# restore r7 (=0x73A000 peripheral base, trashed by labyrinth pops);
# jump to poll-loop resumption 0x8007779 via ip.
mu.mem_write(0x08006CC0, bytes.fromhex(
"4af20007c0f2730747f2797cc0f6000c6047"))
# stack zone fill (STUBV odd) # stack zone fill (STUBV odd)
mu.mem_write(0x085F0000, struct.pack("<I", STUBV) * (0x10000 // 4)) mu.mem_write(0x085F0000, struct.pack("<I", STUBV) * (0x10000 // 4))
# pop-site slots (sp values from traces) # pop-site slots (sp values from traces)
@@ -385,7 +429,7 @@ def main():
# --- end parity --- # --- end parity ---
# stub range is readonly on HW/QEMU: ignore SBL heap-clobber writes, # stub range is readonly on HW/QEMU: ignore SBL heap-clobber writes,
# keep maze/stublets intact (restore-on-write with reentrancy guard) # keep maze/stublets intact (restore-on-write with reentrancy guard)
STUB_LO, STUB_HI = 0x080068C0, 0x08006CA0 # +S7/S9/S10 + banner STUB_LO, STUB_HI = 0x080068C0, 0x08006CE0 # +S7/S9/S10/S16 + banner
stub_snap = bytes(mu.mem_read(STUB_LO, STUB_HI - STUB_LO)) stub_snap = bytes(mu.mem_read(STUB_LO, STUB_HI - STUB_LO))
_inww = [False] _inww = [False]
_swn = [0] _swn = [0]
@@ -498,9 +542,15 @@ def main():
if elog is not None: if elog is not None:
print(f"entries: {len(elog)}") print(f"entries: {len(elog)}")
for n, prev, cur, th in elog[:10]: for n, prev, cur, th in elog[:10]:
print(f" FIRST insn#{n} {prev:#x} -> {cur:#x}{'t' if th == 1 else ('a' if th == 0 else '?')}") if cur < 0:
print(f" FIRST EXIT insn#{n} {prev:#x} -> {(-cur):#x}")
else:
print(f" FIRST insn#{n} {prev:#x} -> {cur:#x}{'t' if th == 1 else ('a' if th == 0 else '?')}")
for n, prev, cur, th in elog[-10:]: for n, prev, cur, th in elog[-10:]:
print(f" LAST insn#{n} {prev:#x} -> {cur:#x}{'t' if th == 1 else ('a' if th == 0 else '?')}") if cur < 0:
print(f" LAST EXIT insn#{n} {prev:#x} -> {(-cur):#x}")
else:
print(f" LAST insn#{n} {prev:#x} -> {cur:#x}{'t' if th == 1 else ('a' if th == 0 else '?')}")
if _splog is not None: if _splog is not None:
print(f"sp-highs: {len(_splog)}") print(f"sp-highs: {len(_splog)}")
for n, pc, sp in _splog: for n, pc, sp in _splog:
@@ -523,6 +573,12 @@ def main():
print(f"bl-immed: {len(bls)}") print(f"bl-immed: {len(bls)}")
for pc, tgt in bls[-30:]: for pc, tgt in bls[-30:]:
print(f" {pc:#x}: bl #{tgt:#x}") print(f" {pc:#x}: bl #{tgt:#x}")
pops = [(pc, tgt) for pc, rm, tgt in calls if rm == 300]
print(f"pop-pc: {len(pops)}")
for pc, tgt in pops[:15]:
print(f" FIRST {pc:#x}: pop-> {tgt:#x}" if tgt >= 0 else f" FIRST {pc:#x}: pop-> ?")
for pc, tgt in pops[-15:]:
print(f" LAST {pc:#x}: pop-> {tgt:#x}" if tgt >= 0 else f" LAST {pc:#x}: pop-> ?")
for pc, rm, tgt in calls[-12:]: for pc, rm, tgt in calls[-12:]:
if rm == 200: if rm == 200:
continue continue