"""Exercise QTM 1.49's actual ARM Load, Info and ReadNoteWord implementations.
Requires Unicorn on the test host. OS_File and OS service boundaries are mocked.
The unmodified player and the same MOD buffer layout ship in the app.
"""
from pathlib import Path
import re, struct
from unicorn import Uc, UC_ARCH_ARM, UC_MODE_ARM, UC_HOOK_INTR
from unicorn.arm_const import *
root=Path(__file__).resolve().parent
folder=root.parent.parent/'!Xmas26/Tracker'
dll=(folder/'QTMModule').read_bytes()
kit=(folder/'Mix/DJDeck').read_bytes()
base,work,deck,ret=0x100000,0x200000,0x400000,0x110000
m=Uc(UC_ARCH_ARM,UC_MODE_ARM)
m.mem_map(base,0x20000);m.mem_write(base,dll);m.mem_map(work,0x100000);m.mem_map(deck,0x200000)
reg=[UC_ARM_REG_R0,UC_ARM_REG_R1,UC_ARM_REG_R2,UC_ARM_REG_R3,UC_ARM_REG_R4,UC_ARM_REG_R5,UC_ARM_REG_R6]
def swi(machine,_number,_ctx):
    pc=m.reg_read(UC_ARM_REG_PC)
    n=int.from_bytes(m.mem_read(pc-4,4),'little')&0xffffff
    if n==0x20008:
        op=m.reg_read(reg[0])
        if op==5:m.reg_write(reg[0],1);m.reg_write(reg[4],len(kit))
        elif op==255:m.mem_write(m.reg_read(reg[2]),kit)
        else:raise AssertionError(('OS_File',op))
    m.reg_write(UC_ARM_REG_CPSR,m.reg_read(UC_ARM_REG_CPSR)&~(1<<28))
m.hook_add(UC_HOOK_INTR,swi)
def call(addr,*args):
    for idx,val in enumerate(args):m.reg_write(reg[idx],val&0xffffffff)
    m.reg_write(UC_ARM_REG_R12,work);m.reg_write(UC_ARM_REG_CPSR,0x13)
    m.reg_write(UC_ARM_REG_SP,work+0xf0000);m.reg_write(UC_ARM_REG_LR,ret)
    m.emu_start(addr,ret,count=10000000)
    assert m.reg_read(UC_ARM_REG_PC)==ret and m.reg_read(UC_ARM_REG_CPSR)&(1<<28)==0
    return [m.reg_read(i) for i in reg]
# Module 1.49 SWI dispatch table of ARM branch instructions.
dispatch=struct.unpack_from('<I',dll,32)[0]+44
def service(number,*args):
    pc=dispatch+number*4
    word=struct.unpack_from('<I',dll,pc)[0];assert word>>24==0xea
    return call(base+pc+8+((word&0xffffff)<<2),*args)
service(0,work+0x5000,deck)
info=service(5);assert info[4]==len(kit) and info[6]==deck
assert bytes(m.mem_read(deck+1080,4))==b'8CHN'
# Use the actual fast-copy instructions supplied to BASIC, then read the
# edited pattern through QTM's own note decoder on each of the 120 patterns.
words=re.findall(r'djcode%!\d+=&([0-9A-F]{8})',(root/'DJMix').read_text());assert len(words)==5
code=work+0x8000;m.mem_write(code,b''.join(struct.pack('<I',int(w,16)) for w in words))
src=work+0x9000
for pat in range(120):
    row=(pat*13)%64
    events=b''
    for ch in range(8):
        sid=(pat+ch)%16+1;volume=16+(pat+ch)%48
        events+=bytes(((sid&16)|1,64,((sid&15)<<4)|12,volume))
    m.mem_write(src,events)
    call(code,src,deck+1084+pat*2048+row*32,32)
    for ch in range(8):
        result=service(33,pat,row,ch+1)
        assert result[4:7]==[(pat+ch)%16+1,12,16+(pat+ch)%48]
print('PASS: the supplied QTM 1.49 module accepted the caller-owned deck and read 960 edited notes across 120 patterns on emulated ARM.')
