"""DIMENSION 1 / query 7: who WRITES the store screen's selected-category field.

FUN_18007dab0 reads *(int*)(screen+0x290) and hands it to FUN_1800147f0 as the
group ordinal. FUN_18007dbd0 reads screen+0x294 as SERVER_ID and screen+0x298 as
a callback string. Those three are set by whatever handles the incoming UI
message.

HYPOTHESIS: the writer copies a value straight out of the Flash message. If it
copies the tile's ASSET_ID (displayGroupAssetId) rather than its CHILD_CATEGORY
(the group ordinal), then non-contiguous displayGroupAssetId values break the
drill-down, which is the reported bug.

CONTROL: 0x294 and 0x298 are enumerated by the same scan. They are known to be
read by FUN_18007dbd0, so if the scan cannot find their writers either, the scan
is at fault rather than the code, and no absence claim is made.
"""
import traceback

OUT = "/tmp/claude-1000/-home-alex-Documents-OpenFUT/8e521ca1-ca3e-4138-bb96-df1744dd1d30/scratchpad/store/q7_out.txt"
buf = []
def P(*a):
    s = " ".join(str(x) for x in a)
    buf.append(s)
    print(s)

try:
    targets = (0x290, 0x294, 0x298, 0x2c8, 0x2cc)
    hits = {t: [] for t in targets}
    it = listing.getInstructions(True)
    n = 0
    while it.hasNext():
        ins = it.next()
        n += 1
        txt = str(ins)
        for i in range(ins.getNumOperands()):
            for o in ins.getOpObjects(i):
                try:
                    v = int(o.getValue())
                except Exception:
                    continue
                if v in targets:
                    f = fm.getFunctionContaining(ins.getAddress())
                    hits[v].append((int(ins.getAddress().getOffset()),
                                    f.getName() if f else "?", txt))
    P("instructions scanned:", n)
    for t in targets:
        P("")
        P("=" * 70)
        P("displacement/immediate %#x : %d instruction(s)" % (t, len(hits[t])))
        P("=" * 70)
        for a, fn, txt in hits[t]:
            P("   %-12s %-28s %s" % (hex(a), fn, txt))
except Exception:
    P(traceback.format_exc())

open(OUT, "w").write("\n".join(buf))
print("WROTE", OUT)
