"""D2 QUICK SELL, batch 8: which of item+0x38 / item+0x3c does the client READ?

WHY IT MATTERS. In FUN_18013fe00 the two are mutually exclusive:
    item+0x38 = discardValue exactly as the server sent it (atom 0xd7)
    item+0x3c = the locally computed fallback, written ONLY when item+0x38 == 0
So if the UI reads +0x3c alone, serving a non-zero discardValue would make the
quick-sell figure render as 0. If it reads +0x38 alone, our current seed of 0 would
render 0 -- which contradicts the live club items, which all carry a correct value
in +0x3c and 0 in +0x38. The likely shape is a getter "return +0x38 ? +0x38 : +0x3c"
or a caller that ORs them. Find it.

METHOD. Scan every function; keep the ones whose instruction text contains BOTH a
"+ 0x38]" and a "+ 0x3c]" memory operand. Print the small ones in full. This is a
text search over decoded operands, so it catches loads through ANY base register,
which is the form an accessor uses -- unlike an RBP-displacement search.

CONTROL: FUN_18013fe00 itself must appear in the list (it has the store to +0x198
and +0x19c, but those are RBP+0x198 not "+ 0x38", so instead the control is
FUN_180141660, which is known to touch obj+0x54/+0x58/+0xb4 through RCX and must
show up in an equivalent scan for "+ 0x54]" and "+ 0x58]"). Both scans are printed.
"""
import traceback

try:
    def scan(a_txt, b_txt, maxins=60):
        out = []
        it = fm.getFunctions(True)
        while it.hasNext():
            f = it.next()
            ii = listing.getInstructions(f.getBody(), True)
            n = 0
            ha = hb = False
            while ii.hasNext():
                t = str(ii.next())
                n += 1
                if a_txt in t:
                    ha = True
                if b_txt in t:
                    hb = True
            if ha and hb:
                out.append((int(f.getEntryPoint().getOffset()), f.getName(), n))
        return out

    print("##### CONTROL scan: '+ 0x54]' and '+ 0x58]' #####")
    ctl = scan("+ 0x54]", "+ 0x58]")
    print("  %d functions; FUN_180141660 present: %s"
          % (len(ctl), any(e == 0x180141660 for e, _, _ in ctl)))

    print("\n##### TARGET scan: '+ 0x38]' and '+ 0x3c]' #####")
    tgt = scan("+ 0x38]", "+ 0x3c]")
    print("  %d functions" % len(tgt))
    small = [t for t in tgt if t[2] <= 40]
    print("  %d of them are <= 40 instructions" % len(small))
    for e, nm, n in sorted(small, key=lambda x: x[2]):
        src = dec(e)
        print("=" * 78)
        print("%#x %s  %d instructions  len(src)=%d" % (e, nm, n, len(src)))
        print("=" * 78)
        print(src)
    print("\n  --- larger candidates (names only) ---")
    for e, nm, n in sorted(tgt, key=lambda x: x[2]):
        if n > 40:
            print("     %#x %s %d ins" % (e, nm, n))

except Exception:
    traceback.print_exc()
