import capstone, struct, sys
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
data = open("../content/BTL4OPT.EXE","rb").read()
# established mapping (from dis_4b2980.py usage): file offset = VA - 0x400000 - 0xc00 adjustments;
# use the section table: .text typically RVA 0x1000, raw 0x400/0x600.  Recover from PE header.
pe = struct.unpack_from("<I", data, 0x3c)[0]
nsec = struct.unpack_from("<H", data, pe+6)[0]
opt = pe+24; szopt = struct.unpack_from("<H", data, pe+20)[0]
sec0 = opt+szopt
imgbase = struct.unpack_from("<I", data, opt+28)[0]
secs=[]
for i in range(nsec):
    off=sec0+i*40
    name=data[off:off+8].rstrip(b"\0").decode()
    vsz,va,rsz,ra=struct.unpack_from("<IIII",data,off+8)
    secs.append((name,va,rsz,ra))
text=[s for s in secs if s[0]=="CODE"][0]
va0=imgbase+text[1]; ra0=text[3]; n=text[2]
md=capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_32)
md.detail=True
code=data[ra0:ra0+n]
hits=[]
# quick byte-pattern prescan for disp32 0x768/0x76c/0x770 little-endian
import re
for target,label in [(0x768,"0x768"),(0x76c,"0x76c"),(0x770,"0x770")]:
    pat=struct.pack("<I",target)
    for m in re.finditer(re.escape(pat),code):
        start=max(0,m.start()-8)
        for ins in md.disasm(code[start:m.start()+12], va0+start):
            if ins.op_str and label in ins.op_str and ("ptr [" in ins.op_str):
                # writes: mov [reg+disp], src  OR fstp
                if ins.mnemonic in ("mov","fstp","fst") and ins.op_str.index("[")<ins.op_str.index(","):
                    hits.append((ins.address,f"{ins.mnemonic} {ins.op_str}"))
                elif ins.mnemonic in ("fld","fcomp","fcom","mov") :
                    pass
seen=set()
for a,t in sorted(hits):
    if (a,t) not in seen:
        seen.add((a,t)); print(f"0x{a:x}: {t}")
