#!/usr/bin/env python3
from pathlib import Path

DIR = Path(__file__).resolve().parents[1] / "apks" / "tng"
KILL = [bytes.fromhex(x) for x in (
    "281080d2", "28108052", "481080d2", "48108052", "681080d2", "68108052",
)]
SVC = bytes.fromhex("010000d4")
EXIT = [bytes.fromhex(x) for x in ("c80b80d2", "ba0b80d2")]  # exit_group, exit

for so in sorted(DIR.glob("lib*.so")):
    data = so.read_bytes()
    pairs = 0
    for imm in KILL:
        i = 0
        while True:
            j = data.find(imm, i)
            if j < 0:
                break
            if SVC in data[j:j + 36]:
                pairs += 1
                if pairs <= 10:
                    print(f"{so.name} KILL+SVC @0x{j:x} d={data[j:j+36].find(SVC)}")
            i = j + 4
    ep = 0
    for imm in EXIT:
        i = 0
        while True:
            j = data.find(imm, i)
            if j < 0:
                break
            if SVC in data[j:j + 36]:
                ep += 1
                if ep <= 8:
                    print(f"{so.name} EXIT+SVC @0x{j:x}")
            i = j + 4
    print(
        f"{so.name}: size={len(data)} svc0={data.count(SVC)} "
        f"kill+svc={pairs} exit+svc={ep} "
        f"abort={data.count(b'abort')} kill={data.count(b'kill')}"
    )
