#!/system/bin/sh
# 抓 TigerTally fread 阻塞的 pipe 写端进程，命中后立即 dump 该进程身份/冻结状态。
PKG="my.com.tngdigital.ewallet"

am force-stop "$PKG" 2>/dev/null
sleep 1
am start -n "$PKG/.ui.SplashActivity" 2>/dev/null

i=0
while [ $i -lt 60 ]; do
  i=$((i+1))
  pid=""
  for p in $(pidof "$PKG"); do
    if [ "$(tr '\0' ' ' < /proc/$p/cmdline 2>/dev/null | tr -d ' ')" = "$PKG" ]; then pid=$p; break; fi
  done
  if [ -z "$pid" ]; then sleep 0.5; continue; fi

  for d in /proc/$pid/task/*/; do
    t="${d%/}"
    s=$(cat "$t/syscall" 2>/dev/null)
    case "$s" in
      63*)
        c=$(cat "$t/comm" 2>/dev/null)
        case "$c" in
          *pool*|*Tiger*|*tiger*|*tally*|*Tally*)
            fd=$(echo "$s" | awk '{print $2}')
            fd=$((fd))
            tgt=$(readlink "/proc/$pid/fd/$fd" 2>/dev/null)
            echo "[$i] MAIN pid=$pid TID=${t##*/} comm=$c wchan=$(cat "$t/wchan" 2>/dev/null)"
            echo "[$i] MAIN fd=$fd -> $tgt"
            ino=$(echo "$tgt" | sed 's/.*\[//; s/\]//')
            [ -z "$ino" ] && continue
            echo "[$i] writer-search inode=$ino:"
            for wp in $(find /proc/[0-9]*/fd -lname "*$ino*" 2>/dev/null); do
              echo "[$i]   $wp"
            done
            # dump 所有非主进程端点
            for wp in $(find /proc/[0-9]*/fd -lname "*$ino*" 2>/dev/null); do
              wproc=$(echo "$wp" | cut -d/ -f3)
              [ "$wproc" = "$pid" ] && continue
              wfd=$(echo "$wp" | cut -d/ -f5)
              echo "[$i] WRITER proc=$wproc fd=$wfd"
              echo "[$i]   cmdline: $(tr '\0' ' ' < /proc/$wproc/cmdline 2>/dev/null)"
              echo "[$i]   comm: $(cat /proc/$wproc/comm 2>/dev/null) state=$(cat /proc/$wproc/stat 2>/dev/null | awk '{print $3}')"
              cg=$(cat /proc/$wproc/cgroup 2>/dev/null | grep -v freezer | head -1)
              echo "[$i]   cgroup: $cg"
              # cgroup v2 freezer
              cgpath=$(echo "$cg" | sed 's/^[0-9]*://')
              if [ -f "/sys/fs/cgroup${cgpath}/cgroup.freeze" ]; then
                echo "[$i]   cgroup.freeze=$(cat /sys/fs/cgroup${cgpath}/cgroup.freeze 2>/dev/null)"
              fi
              echo "[$i]   threads(wchan):"
              for td in /proc/$wproc/task/*/; do
                ttn=${td%/}
                echo "[$i]     ${ttn##*/} $(cat $ttn/comm 2>/dev/null) $(cat $ttn/wchan 2>/dev/null)"
              done
            done
            ;;
        esac
        ;;
    esac
  done
  sleep 0.4
done
echo "=== scan done ==="
