Commit de7dae33bcbd0a02aa60573bc21421c3663677a0

Authored by yibo
1 parent 700a802c

feat(wechathook): 语音全合成打通 ✅ — uploadvoice cgi 服务器接受(errCode=0+svrMsgId)

修好派发:裸 z2.b(g) 不 wire 回调 → 场景永不完成、dv6 空。正确派发 =
modelbase.i.l()(注册响应消费者 d + 返回 pq5.g deferred)+ pq5.g.l(timeoutMs)
终端订阅触发 cgi。加 sVoiceCgiKeepAlive 强引用防 deferred 弱持有的 i 被 GC。

真机 filehelper 验证(纯合成,无录音/无 hot-swap):
  RESP try=1 svrMsgId(11)=6727180359918674774
  VOICECGI-RESULT errType=0 errCode=0 errMsg=null respClass=r45.dv6
= 服务器接受请求(errCode=0) + 分配 msgId(>0) = 投递成功。

诊断 hook hookVoiceCgiResult(modelbase.i onSceneEnd 按签名定位) 确认 errCode。
广播 SEND_VOICE_CGI --es to --es src_path <SILK> --ei duration。SILK 须 WeChat
进程可读(用其自身 voice2 文件或 chown 到 WeChat uid;/sdcard 会 EACCES)。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
xhs_lsposed_a16_fix/backups/WeChatHook_20260707_voice-cgi-WORKING.java 0 → 100644
  1 +package com.example.wechathook;
  2 +
  3 +import android.app.Activity;
  4 +import android.content.BroadcastReceiver;
  5 +import android.content.Context;
  6 +import android.content.Intent;
  7 +import android.content.IntentFilter;
  8 +import android.os.Bundle;
  9 +import android.os.Handler;
  10 +import android.os.Looper;
  11 +import android.view.View;
  12 +import java.lang.reflect.Proxy;
  13 +import de.robv.android.xposed.IXposedHookLoadPackage;
  14 +import de.robv.android.xposed.XC_MethodHook;
  15 +import de.robv.android.xposed.XposedBridge;
  16 +import de.robv.android.xposed.XposedHelpers;
  17 +import de.robv.android.xposed.callbacks.XC_LoadPackage;
  18 +
  19 +public class WeChatHook implements IXposedHookLoadPackage {
  20 +
  21 + private static final String ACTION_SEND = "com.hermes.wechat.SEND_MSG_INTERNAL";
  22 + private static final String ACTION_SEND_IMAGE = "com.hermes.wechat.SEND_IMAGE_INTERNAL";
  23 + private static final String ACTION_SEND_VOICE = "com.hermes.wechat.SEND_VOICE_INTERNAL";
  24 + private static final String ACTION_SEND_VOICE_CGI = "com.hermes.wechat.SEND_VOICE_CGI";
  25 + private static final String ACTION_ARM_SWAP = "com.hermes.wechat.ARM_VOICE_SWAP";
  26 + private static final String ACTION_DUMP_API = "com.hermes.wechat.DUMP_WECHAT_API";
  27 +
  28 + // ── Voice hot-swap state (the route that actually delivers) ────────────────
  29 + // Fully-synthetic voice (SEND_VOICE_INTERNAL) can build the message shell but
  30 + // can never upload the SILK to WeChat's CDN (upload is locked inside jg0.x's
  31 + // Kotlin coroutine). So instead we let the user trigger a REAL recording (hold
  32 + // "按住说话") and intercept jg0.x.w — the CDN uploadAttach step — replacing the
  33 + // recorded SILK bytes (w21.t.a) with our TTS SILK. WeChat's own machinery then
  34 + // uploads + delivers our audio. Armed by ARM_VOICE_SWAP; consumed once.
  35 + private static volatile boolean sSwapArmed = false;
  36 + private static volatile byte[] sSwapSilk = null; // TTS SILK bytes to inject
  37 + private static volatile int sSwapDuration = 0; // ms, replaces the recorded duration
  38 + // Safety: an arm auto-expires at this wall-clock time (set to arm + audio duration
  39 + // + 10s slack). The swap fires only on release AFTER a full hold, so the window must
  40 + // outlast the hold; past it, a stale arm silently dies instead of hijacking a later
  41 + // unrelated recording.
  42 + private static volatile long sSwapExpiresAt = 0;
  43 + // Cached f9 setter map (column -> methodName), built once on first voice send
  44 + // (sF9SetterMap is declared alongside probeAllF9Setters below)
  45 + // Thread-locals for voice send: voiceId and SILK bytes to inject into f9 ctor
  46 + private static final ThreadLocal<String> sPendingVoiceId = new ThreadLocal<>();
  47 + private static final ThreadLocal<byte[]> sPendingLvBuffer = new ThreadLocal<>();
  48 + // Captures the f9 that called convertTo() (= the one written to DB); used to populate r0.i.
  49 + private static final ThreadLocal<Object> sDatabaseF9 = new ThreadLocal<>();
  50 + private static ClassLoader sWeChatCL; // pre-Tinker classloader (from handleLoadPackage)
  51 + private static volatile ClassLoader sTinkerCL; // Tinker-patched classloader (from App.onCreate)
  52 + private static volatile Context sAppContext;
  53 + private static volatile boolean sFsGReady = false;
  54 + // Set true while WE are calling newInstance so r0Hook can distinguish us from WeChat
  55 + private static volatile boolean sCalledByUs = false;
  56 + // Network dispatcher captured from a real WeChat r0 at H()-entry; needed by CDN upload
  57 + private static volatile Object sCapturedDispatcher = null;
  58 + private static volatile Object sPt0E0Instance = null; // pt0.e0 singleton, captured from r() hook
  59 + // Keeps synthetic-voice-cgi i/deferred objects strongly referenced (the deferred
  60 + // holds the CgiLifecycleObserver weakly, so without this GC kills the in-flight send).
  61 + private static final java.util.List<Object> sVoiceCgiKeepAlive = new java.util.concurrent.CopyOnWriteArrayList<>();
  62 + private static volatile Object sImgPlugin = null; // b80.u instance, captured from pj/Bi hook
  63 + private static volatile Object sRealImgParams = null; // last real o70.h, captured for replication
  64 + private static volatile Object sRealImgK = null; // last real o70.k (oj insert object)
  65 + private static final ThreadLocal<Long> sPendingMsgLocalId = new ThreadLocal<>(); // msgId from DB insert
  66 + // Logged-in user's wxid, auto-discovered from first real voice message send
  67 + private static volatile String sMyWxid = null;
  68 + // Pending send: stored when broadcast arrives before gm0.j1 is initialized
  69 + private static volatile String sPendingTalker = null;
  70 + private static volatile String sPendingText = null;
  71 + private static volatile String sPendingProc = null;
  72 +
  73 + @Override
  74 + public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) throws Throwable {
  75 + if (!"com.tencent.mm".equals(lpparam.packageName)) return;
  76 + // Use android.util.Log directly so it appears even before VectorLegacyBridge is ready
  77 + android.util.Log.i("WeChatHookEarly", "INIT proc=" + lpparam.processName
  78 + + " pid=" + android.os.Process.myPid());
  79 + XposedBridge.log("[WeChatHook] Injected into WeChat " + lpparam.processName
  80 + + " pid=" + android.os.Process.myPid());
  81 + ClassLoader cl = lpparam.classLoader;
  82 + sWeChatCL = cl;
  83 +
  84 + // Tablet login hooks — DISABLED. User switched to normal direct (primary)
  85 + // login. The bk.A/B tablet-spoof would make WeChat think it's a tablet
  86 + // mid-session and can re-trigger the beta "体验资格" gate on this test build,
  87 + // kicking the login. Keep them off so restarts don't disturb direct login.
  88 + // hookInTabletEnv(cl);
  89 + // hookProbe(cl);
  90 + // hookLoginHistoryUIInitView(cl);
  91 + // hookLoginUIInitView(cl);
  92 + // hookLoginSelectUICheck(cl);
  93 + // hookLoginButtonClick(cl);
  94 +
  95 + // WCDB diagnostic: which process writes? + media ContentValues dump
  96 + hookWCDB(cl, lpparam.processName);
  97 +
  98 + // Factory method discovery: dumps w11.s1 signatures + hooks all static methods
  99 + // so that when WeChat UI sends image/voice we capture the exact API call.
  100 + hookFactoryMethods(cl, lpparam.processName);
  101 +
  102 + // MediaPlayer hook: captures voice file paths when WeChat plays voice messages.
  103 + // This reveals the voice2/{dir1}/{dir2}/msg_{id}.amr naming formula.
  104 + hookMediaPlayer(lpparam.processName);
  105 +
  106 + // Hook gm0.j1.g() to detect when DI kernel is ready — runs in ALL processes.
  107 + // This enables the pending-send mechanism: if broadcast arrives before DI init,
  108 + // we store the args and retry once g() fires.
  109 + hookDIInit(cl, lpparam.processName);
  110 +
  111 + // Send hook in ALL WeChat processes — we need to find which one can actually send.
  112 + // The broadcast receiver registered in each process will all receive the intent;
  113 + // whichever process has gm0.j1 initialized will succeed.
  114 + hookSendMessage(cl, lpparam.processName);
  115 +
  116 + // Hook w11.r0.H(String) to trace CDN upload: log r0 String fields + file access.
  117 + hookR0H(cl, lpparam.processName);
  118 +
  119 + // Capture the live network dispatcher com.tencent.mm.modelbase.m2 (MicroMsg.RDispatcher)
  120 + // at construction. Synthetic voice sends need the REAL m2 to actually reach the
  121 + // network; without it we'd fall back to a fake $Proxy that never sends.
  122 + hookDispatcher(cl, lpparam.processName);
  123 +
  124 + // Instrument the voice-upload service w21.g1 (voiceinfo table): on a REAL voice
  125 + // send, dump the exact w21.w0 upload-task fields so we can replicate them for
  126 + // synthetic voice (the last missing step = CDN audio upload).
  127 + hookVoiceUpload(cl, lpparam.processName);
  128 +
  129 + // Image send: hook the non-suspend plugin methods b80.u.pj/Bi (o70.h) — the
  130 + // actual image-send entry the coroutine calls. Capture the b80.u instance +
  131 + // dump the full o70.h a REAL send builds, so we can replicate it directly.
  132 + hookImageSend(cl, lpparam.processName);
  133 + // Capture the SendImgProxyUI launch Intent (real gallery send goes through it),
  134 + // so we can replay the whole real send flow via `am start`.
  135 + hookSendImgProxyUI(cl, lpparam.processName);
  136 +
  137 + // Hook pt0.e0 — the voice-send coroutine class found in the stack trace.
  138 + // Real voice sends don't use r0.H(); we need to find where CDN upload actually fires.
  139 + hookPt0E0(cl, lpparam.processName);
  140 +
  141 + // Surgical voice-send entry probe (jg0.x + qi3.f0/g0 only). On this fresh
  142 + // reinstall the send runs in the base CL (no Tinker patch yet), so hook here.
  143 + hookVoiceProbe(cl, lpparam.processName);
  144 +
  145 + // Voice hot-swap: intercept jg0.x.w (CDN uploadAttach) to replace the recorded
  146 + // SILK with our TTS audio during a real (user- or A11y-triggered) recording.
  147 + // This is the ONE route that actually delivers synthetic voice.
  148 + hookVoiceSwap(cl, lpparam.processName);
  149 +
  150 + // Trace the CDN upload submission (dn.m task + assigned aeskey/fileId) on a real
  151 + // voice send — the layer full-synthesis was missing (addSendTask / CdnManager).
  152 + hookCdnTrace(cl, lpparam.processName);
  153 + // Capture the real uploadvoice cgi request (this device uses inline-cgi, not CDN).
  154 + hookVoiceCgiCapture(cl, lpparam.processName);
  155 + hookVoiceCgiResult(cl, lpparam.processName);
  156 + }
  157 +
  158 + // ── WCDB hook ──────────────────────────────────────────────────────────────
  159 + // Intercepts every INSERT into the message table.
  160 + // For msgtype 3 (image) and 34 (voice) logs the full ContentValues so we can
  161 + // reverse-engineer the exact schema WeChat uses when building those messages.
  162 + private void hookWCDB(ClassLoader cl, String procName) {
  163 + try {
  164 + XposedHelpers.findAndHookMethod(
  165 + "com.tencent.wcdb.database.SQLiteDatabase", cl,
  166 + "insertWithOnConflict",
  167 + String.class, String.class, android.content.ContentValues.class, int.class,
  168 + new XC_MethodHook() {
  169 + private boolean textLogged = false;
  170 + @Override
  171 + protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
  172 + String table = (String) param.args[0];
  173 + if (table == null) return;
  174 + android.content.ContentValues cv =
  175 + (android.content.ContentValues) param.args[2];
  176 +
  177 + // Determine msgtype from ContentValues (key may be "type" or "msgtype")
  178 + Object rawType = null;
  179 + if (cv != null) {
  180 + rawType = cv.get("type");
  181 + if (rawType == null) rawType = cv.get("msgtype");
  182 + if (rawType == null) rawType = cv.get("msgType");
  183 + }
  184 + int msgtype = -1;
  185 + try { if (rawType != null) msgtype = Integer.parseInt(rawType.toString()); }
  186 + catch (NumberFormatException ignored) {}
  187 +
  188 + if (msgtype == 3 || msgtype == 34) {
  189 + // Image (3) or Voice (34): dump full ContentValues + stack
  190 + String cvStr = cv != null ? cv.toString() : "null";
  191 + String stack = android.util.Log.getStackTraceString(new Throwable());
  192 + if (stack.length() > 4000) stack = stack.substring(0, 4000) + "…";
  193 + XposedBridge.log("[WeChatHook] WCDB MEDIA INSERT table=" + table
  194 + + " msgtype=" + msgtype
  195 + + " proc=" + procName
  196 + + "\nContentValues=" + cvStr
  197 + + "\nStack=" + stack);
  198 + } else if (msgtype == 1) {
  199 + // Text: only log once (to confirm which process writes)
  200 + if (!textLogged) {
  201 + textLogged = true;
  202 + String stack = android.util.Log.getStackTraceString(new Throwable());
  203 + if (stack.length() > 3000) stack = stack.substring(0, 3000) + "…";
  204 + XposedBridge.log("[WeChatHook] WCDB TEXT INSERT table=" + table
  205 + + " proc=" + procName + "\n" + stack);
  206 + } else {
  207 + XposedBridge.log("[WeChatHook] WCDB TEXT table=" + table
  208 + + " proc=" + procName);
  209 + }
  210 + }
  211 + }
  212 + });
  213 + XposedBridge.log("[WeChatHook] WCDB hook OK in " + procName);
  214 + } catch (Throwable t) {
  215 + XposedBridge.log("[WeChatHook] WCDB hook failed in " + procName + ": " + t);
  216 + }
  217 + }
  218 +
  219 + // ── MediaPlayer hook: reveals voice file path format ─────────────────────
  220 + // When WeChat plays a voice message it calls MediaPlayer.setDataSource(path).
  221 + // We log any path under voice2/ to see the full path including subdirectory,
  222 + // which reveals the formula WeChat uses to map voice file IDs to directories.
  223 + private void hookMediaPlayer(String procName) {
  224 + try {
  225 + XposedHelpers.findAndHookMethod("android.media.MediaPlayer", null,
  226 + "setDataSource", String.class, new XC_MethodHook() {
  227 + @Override
  228 + protected void beforeHookedMethod(MethodHookParam p) throws Throwable {
  229 + String path = (String) p.args[0];
  230 + if (path != null && path.contains("voice2")) {
  231 + XposedBridge.log("[WeChatHook] MediaPlayer.setDataSource VOICE="
  232 + + path + " proc=" + procName);
  233 + }
  234 + }
  235 + });
  236 + XposedBridge.log("[WeChatHook] MediaPlayer hook OK in " + procName);
  237 + } catch (Throwable t) {
  238 + XposedBridge.log("[WeChatHook] MediaPlayer hook failed in " + procName + ": " + t);
  239 + }
  240 + }
  241 +
  242 + // ── f9.convertTo() hook: maps f9 fields to DB columns ─────────────────────
  243 + // Captures ContentValues produced by convertTo() for image (3) and voice (34).
  244 + // From these ContentValues we know which f9 setter corresponds to which DB column
  245 + // (imgPath, content, talker, etc.) so we can construct f9 programmatically.
  246 + private void hookF9ConvertTo(ClassLoader cl, String procName) {
  247 + try {
  248 + XposedHelpers.findAndHookMethod("com.tencent.mm.storage.f9", cl,
  249 + "convertTo", new XC_MethodHook() {
  250 + @Override
  251 + protected void afterHookedMethod(MethodHookParam p) throws Throwable {
  252 + if (p.hasThrowable()) return;
  253 + android.content.ContentValues cv =
  254 + (android.content.ContentValues) p.getResult();
  255 + if (cv == null) return;
  256 + Object rawType = cv.get("type");
  257 + if (rawType == null) rawType = cv.get("msgtype");
  258 + if (rawType == null) return;
  259 + int msgtype = -1;
  260 + try { msgtype = Integer.parseInt(rawType.toString()); } catch (Throwable e) {}
  261 + if (msgtype == 3 && !sCalledByUs) {
  262 + // Dump full call stack once for a real IMAGE send so we can find
  263 + // the top-level app entry point to replicate for API image send.
  264 + XposedBridge.log("[WeChatHook] convertTo IMAGE STACK (real send):\n"
  265 + + android.util.Log.getStackTraceString(new Exception()));
  266 + }
  267 + if (msgtype == 34) {
  268 + // Dump call stack once for real sends to find the CDN upload caller.
  269 + if (!sCalledByUs) {
  270 + XposedBridge.log("[WeChatHook] convertTo STACK (real send):\n"
  271 + + android.util.Log.getStackTraceString(new Exception()));
  272 + }
  273 + // Auto-discover logged-in user's wxid from real UI voice sends.
  274 + // We look for isSend=1 messages (user's own sends) and extract
  275 + // fromusername from the voicemsg XML, cache as sMyWxid.
  276 + if (sMyWxid == null && !sCalledByUs) {
  277 + Object isSend = cv.get("isSend");
  278 + Object contentVal = cv.get("content");
  279 + if (isSend instanceof Integer && ((Integer)isSend) == 1
  280 + && contentVal instanceof String) {
  281 + String c = (String) contentVal;
  282 + int fi = c.indexOf("fromusername=\"");
  283 + if (fi >= 0) {
  284 + int start = fi + "fromusername=\"".length();
  285 + int end = c.indexOf("\"", start);
  286 + if (end > start) {
  287 + String wxid = c.substring(start, end);
  288 + if (!wxid.isEmpty()) {
  289 + sMyWxid = wxid;
  290 + XposedBridge.log("[WeChatHook] auto-discovered sMyWxid=" + wxid);
  291 + }
  292 + }
  293 + }
  294 + }
  295 + }
  296 + }
  297 + if (msgtype == 3 || msgtype == 34) {
  298 + // Inject lvbuffer (SILK bytes) if we're sending voice via hook.
  299 + // sPendingLvBuffer is still set here — convertTo fires INSIDE
  300 + // the r0 constructor which runs before our finally-block clears it.
  301 + byte[] pendingLv = sPendingLvBuffer.get();
  302 + if (pendingLv != null && !(cv.get("lvbuffer") instanceof byte[])) {
  303 + cv.put("lvbuffer", pendingLv);
  304 + XposedBridge.log("[WeChatHook] convertTo: injected lvbuffer " + pendingLv.length + " bytes");
  305 + }
  306 + // Capture the DB-bound f9 (the one convertTo() runs on).
  307 + // This is the correct object for r0.i: it has content + msgId set.
  308 + if (pendingLv != null) {
  309 + sDatabaseF9.set(p.thisObject);
  310 + // Capture msgLocalId for pt0.e0.s() CDN trigger
  311 + try {
  312 + Object msgIdObj = cv.get("msgId");
  313 + if (msgIdObj != null) {
  314 + long mid = Long.parseLong(msgIdObj.toString());
  315 + sPendingMsgLocalId.set(mid);
  316 + XposedBridge.log("[WeChatHook] convertTo: captured msgLocalId=" + mid);
  317 + }
  318 + } catch (Throwable ignored) {}
  319 + // Do NOT force status=4 here.
  320 + // Forcing status=4 before H() causes H() to skip CDN upload
  321 + // (WeChat checks status and exits early if already "delivered").
  322 + // Let H() set status=4 naturally after successful CDN upload.
  323 + // Ensure flag and msgSvrId are present (missing from our sends).
  324 + if (cv.get("flag") == null) cv.put("flag", 0);
  325 + if (cv.get("msgSvrId") == null) cv.put("msgSvrId", 0L);
  326 + XposedBridge.log("[WeChatHook] convertTo: initial INSERT (status not forced, H() will set it)");
  327 + }
  328 + // Log full ContentValues including lvbuffer details
  329 + StringBuilder sb = new StringBuilder();
  330 + sb.append("[WeChatHook] f9.convertTo() msgtype=").append(msgtype)
  331 + .append(" proc=").append(procName).append("\nContentValues=").append(cv);
  332 + Object lvbuf = cv.get("lvbuffer");
  333 + if (lvbuf instanceof byte[]) {
  334 + byte[] b = (byte[]) lvbuf;
  335 + StringBuilder hex = new StringBuilder();
  336 + int show = Math.min(b.length, 32);
  337 + for (int i = 0; i < show; i++)
  338 + hex.append(String.format("%02x", b[i] & 0xff));
  339 + sb.append("\nlvbuffer len=").append(b.length).append(" hex=").append(hex);
  340 + } else {
  341 + sb.append("\nlvbuffer=null");
  342 + }
  343 + XposedBridge.log(sb.toString());
  344 + }
  345 + }
  346 + });
  347 + XposedBridge.log("[WeChatHook] f9.convertTo hook OK in " + procName);
  348 + } catch (Throwable t) {
  349 + XposedBridge.log("[WeChatHook] f9.convertTo hook failed in " + procName + ": " + t);
  350 + }
  351 + }
  352 +
  353 + // ── f9 constructor imgPath injector ───────────────────────────────────────
  354 + // Hooks ALL f9 constructors. When sPendingVoiceId is set on the calling thread,
  355 + // immediately calls the discovered imgPath setter on the newly created f9 object.
  356 + // This fires INSIDE the r0 constructor (before its internal f9.convertTo() call),
  357 + // so the DB insert from r0 constructor already has the correct voice file ID.
  358 + private void hookF9ImgPathInjector(ClassLoader cl, String procName) {
  359 + try {
  360 + Class<?> f9Class = XposedHelpers.findClass("com.tencent.mm.storage.f9", cl);
  361 + XC_MethodHook injHook = new XC_MethodHook() {
  362 + @Override
  363 + protected void afterHookedMethod(MethodHookParam param) throws Throwable {
  364 + String pending = sPendingVoiceId.get();
  365 + if (pending == null) return;
  366 + java.util.Map<String, String> sm = sF9SetterMap;
  367 + if (sm == null) return;
  368 + // Inject imgPath
  369 + String setter = sm.get("imgPath");
  370 + if (setter != null) {
  371 + XposedHelpers.callMethod(param.thisObject, setter, pending);
  372 + XposedBridge.log("[WeChatHook] f9 ctor injected imgPath=" + pending + " via " + setter);
  373 + }
  374 + // Inject lvbuffer (SILK bytes) so WeChat treats the voice as locally available
  375 + byte[] lvbuf = sPendingLvBuffer.get();
  376 + String lvSetter = sm.get("lvbuffer:bytes");
  377 + if (lvbuf != null && lvSetter != null) {
  378 + XposedHelpers.callMethod(param.thisObject, lvSetter, (Object) lvbuf);
  379 + XposedBridge.log("[WeChatHook] f9 ctor injected lvbuffer len=" + lvbuf.length + " via " + lvSetter);
  380 + } else {
  381 + XposedBridge.log("[WeChatHook] f9 ctor lvbuffer skip: lvbuf=" + (lvbuf==null?"null":"ok") + " setter=" + lvSetter);
  382 + }
  383 + // sDatabaseF9 is captured in convertTo() — that's the correct DB-bound f9.
  384 + }
  385 + };
  386 + int hooked = 0;
  387 + for (java.lang.reflect.Constructor<?> ctor : f9Class.getDeclaredConstructors()) {
  388 + XposedBridge.hookMethod(ctor, injHook);
  389 + hooked++;
  390 + }
  391 + XposedBridge.log("[WeChatHook] f9 ctor injector OK in " + procName + " (" + hooked + " ctors)");
  392 + } catch (Throwable t) {
  393 + XposedBridge.log("[WeChatHook] f9 ctor injector failed in " + procName + ": " + t);
  394 + }
  395 + }
  396 +
  397 + // ── Image send via internal API ────────────────────────────────────────────
  398 + // Calls the gallery's own static image-send helper:
  399 + // j33.d0.k(long imgId, String path, String talker, boolean, int, boolean,
  400 + // GalleryItem$MediaItem)
  401 + // This is exactly what the album picker calls (traced via a real image send's
  402 + // convertTo stack → b80.u.oj → b80.s coroutine → built from o70.h; d0.k is the
  403 + // top-level builder). It builds o70.h (PreBuildParams) and launches the send
  404 + // coroutine internally (thumbnail gen + CDN upload + DB insert), fire-and-forget.
  405 + // The old w11.s1.b(IMAGE) path built an incomplete r1 → n1.a() NPE; abandoned.
  406 + private static void sendImageViaAPI(String talker, String imagePath) throws Throwable {
  407 + ClassLoader cl = sTinkerCL != null ? sTinkerCL : sWeChatCL;
  408 + if (cl == null) throw new IllegalStateException("classloader null");
  409 + // Replicate the REAL image send captured by hookImageSend: build the exact
  410 + // o70.h (PreBuildParams) that b80.u.pj() receives on a genuine send, then call
  411 + // b80.u.pj(o70.h) directly (non-suspend), skipping the whole gallery/coroutine UI.
  412 + //
  413 + // Captured real o70.h (fields are single letters a–l):
  414 + // a=r6 preBuildFolder, e=imgPath, g=toUserName(talker), c=source(0), d=0,
  415 + // f=imgId(0 ok), h=compressType(0), k=Uri(null for pj), b=UUID(auto)
  416 + //
  417 + // r6 folder = lp0.b.h0(gm0.j1.b().j() + "_MsgImgUploadFSC") (= g80.o.c7()).
  418 + // plugin b80.u = i95.n0.c(o70.e.class) (fallback to hook-captured instance).
  419 + // b80.u image plugin = i95.n0.c(o70.e.class) (fallback to hook-captured instance).
  420 + Object imgPlugin = sImgPlugin;
  421 + if (imgPlugin == null) {
  422 + Class<?> n0 = XposedHelpers.findClass("i95.n0", cl);
  423 + Class<?> o70e = XposedHelpers.findClass("o70.e", cl);
  424 + imgPlugin = XposedHelpers.callStaticMethod(n0, "c", o70e);
  425 + }
  426 + if (imgPlugin == null) throw new IllegalStateException("b80.u image plugin null");
  427 +
  428 + // r6 pre-build folder = lp0.b.h0(gm0.j1.b().j() + "_MsgImgUploadFSC") (= g80.o.c7()).
  429 + Object m = XposedHelpers.callStaticMethod(XposedHelpers.findClass("gm0.j1", cl), "b");
  430 + Object prefix = XposedHelpers.callMethod(m, "j");
  431 + Class<?> lp0b = XposedHelpers.findClass("lp0.b", cl);
  432 + Object r6 = XposedHelpers.callStaticMethod(lp0b, "h0", prefix + "_MsgImgUploadFSC");
  433 +
  434 + // Build o70.k (the batch send object) — fields captured from a real oj(o70.k):
  435 + // a=r6, b=UUID(auto), c=talker, d=source, f=compressType, g=List<o70.i>
  436 + Class<?> o70k = XposedHelpers.findClass("o70.k", cl);
  437 + Object k = XposedHelpers.newInstance(o70k, r6);
  438 + XposedHelpers.setObjectField(k, "c", talker); // toUserName
  439 + // source (field d) — real send used 3; set via reflection (int field).
  440 + try { java.lang.reflect.Field df = o70k.getDeclaredField("d"); df.setAccessible(true); df.setInt(k, 3); } catch (Throwable ignored) {}
  441 + // o70.i(imgPath, Uri, Long imgId) — give it a file:// Uri so the CDN upload has
  442 + // a readable source (real sends pass a MediaStore content:// Uri).
  443 + Class<?> o70i = XposedHelpers.findClass("o70.i", cl);
  444 + android.net.Uri fileUri = android.net.Uri.fromFile(new java.io.File(imagePath));
  445 + Object item = XposedHelpers.newInstance(o70i,
  446 + new Class<?>[]{String.class, android.net.Uri.class, Long.class},
  447 + imagePath, fileUri, Long.valueOf(0L));
  448 + java.util.List<Object> list = new java.util.ArrayList<>();
  449 + list.add(item);
  450 + XposedHelpers.setObjectField(k, "g", list);
  451 + String clientId = (String) XposedHelpers.getObjectField(k, "b");
  452 +
  453 + // Replicate b80.s coroutine's per-item prebuild loop: build o70.h from k+item,
  454 + // then pj (stage compressed image + thumbnail into r6).
  455 + Class<?> o70h = XposedHelpers.findClass("o70.h", cl);
  456 + Object h = XposedHelpers.newInstance(o70h, r6);
  457 + XposedHelpers.callMethod(h, "b", clientId); // clientId (field b)
  458 + XposedHelpers.setObjectField(h, "e", imagePath); // imgPath
  459 + XposedHelpers.setObjectField(h, "g", talker); // toUserName
  460 + XposedHelpers.setObjectField(h, "k", fileUri); // Uri (source for staging/upload)
  461 + try { java.lang.reflect.Field hc = o70h.getDeclaredField("c"); hc.setAccessible(true); hc.setInt(h, 3); } catch (Throwable ignored) {} // source
  462 + // d(rotate)/h(compressType) default 0. f(imgId) 0.
  463 + XposedBridge.log("[WeChatHook] sendImageViaAPI: built o70.k+o70.h e=" + imagePath + " g=" + talker
  464 + + " plugin=" + imgPlugin.getClass().getName());
  465 +
  466 + sCalledByUs = true;
  467 + try {
  468 + if (!(Boolean) XposedHelpers.callMethod(imgPlugin, "Bi", h, "thumb.jpg")) {
  469 + XposedHelpers.callMethod(imgPlugin, "pj", h); // prebuild (stage)
  470 + try { XposedHelpers.callMethod(imgPlugin, "nj", h, 10000); } catch (Throwable ignored) {}
  471 + }
  472 + java.util.ArrayList<?> res = (java.util.ArrayList<?>)
  473 + XposedHelpers.callMethod(imgPlugin, "oj", k); // insert + build descriptors
  474 + XposedBridge.log("[WeChatHook] sendImageViaAPI: oj() DONE to=" + talker
  475 + + " res=" + (res == null ? "null" : "size=" + res.size()));
  476 +
  477 + // ── Last mile: submit each o70.l descriptor to the CDN upload service ──
  478 + // oj() only inserts the msg (f9) + ImgInfo (b0) and RETURNS List<o70.l>
  479 + // upload descriptors — it does NOT start the CDN upload. The real flow
  480 + // (pe5.f.a) loops the list and, per item, builds r70.g + k70.i0 crossParams
  481 + // and calls the d1 img-send service's oj(r70.g, o70.l), which launches the
  482 + // CDN upload coroutine (e80.c). Without this, the full image never uploads
  483 + // (thumbnail renders but the send spins forever). jadx field names f30xxxN
  484 + // map to the real single-letter dex field N (verified: o70.k "d"=source).
  485 + // v70.w.oj builds a ViewModel via ViewModelProvider.get → must run on the
  486 + // main thread; the broadcast receiver already dispatches us there.
  487 + if (res != null && !res.isEmpty()) {
  488 + Class<?> n0 = XposedHelpers.findClass("i95.n0", cl);
  489 + Object cdnSvc = XposedHelpers.callStaticMethod(
  490 + n0, "c", XposedHelpers.findClass("xs.d1", cl)); // → v70.w (MsgImgFeatureService)
  491 + String selfWxid = null;
  492 + try { selfWxid = (String) XposedHelpers.callStaticMethod(
  493 + XposedHelpers.findClass("c01.z1", cl), "r"); } catch (Throwable ignored) {}
  494 + if (selfWxid == null) selfWxid = ""; // API accepts "" (pe5.f.a does the same)
  495 + Class<?> i0cls = XposedHelpers.findClass("k70.i0", cl);
  496 + Class<?> r70g = XposedHelpers.findClass("r70.g", cl);
  497 + int compressType = 0;
  498 + try { java.lang.reflect.Field cf = o70k.getDeclaredField("f"); cf.setAccessible(true); compressType = cf.getInt(k); } catch (Throwable ignored) {}
  499 + int submitted = 0;
  500 + for (Object l : res) {
  501 + // crossParams: only source (field a) matters for a plain photo;
  502 + // mirror quote(t)/long(u) from the descriptor (usually null/0).
  503 + Object crossParams = XposedHelpers.newInstance(i0cls);
  504 + try { java.lang.reflect.Field af = i0cls.getDeclaredField("a"); af.setAccessible(true); af.setInt(crossParams, 3); } catch (Throwable ignored) {}
  505 + try { XposedHelpers.setObjectField(crossParams, "t", XposedHelpers.getObjectField(l, "s")); } catch (Throwable ignored) {}
  506 + try {
  507 + java.lang.reflect.Field lr = l.getClass().getDeclaredField("r"); lr.setAccessible(true);
  508 + java.lang.reflect.Field iu = i0cls.getDeclaredField("u"); iu.setAccessible(true);
  509 + iu.setLong(crossParams, lr.getLong(l));
  510 + } catch (Throwable ignored) {}
  511 + String builtPath = (String) XposedHelpers.getObjectField(l, "e"); // pre-built compressed path
  512 + Object gVar = XposedHelpers.newInstance(r70g,
  513 + new Class<?>[]{String.class, int.class, String.class, String.class, i0cls},
  514 + builtPath, compressType, selfWxid, talker, crossParams);
  515 + XposedHelpers.callMethod(cdnSvc, "oj", gVar, l); // → e80.c CDN upload coroutine
  516 + submitted++;
  517 + }
  518 + XposedBridge.log("[WeChatHook] sendImageViaAPI: CDN submit DONE items=" + submitted
  519 + + " self=" + selfWxid + " compress=" + compressType);
  520 + }
  521 + } finally { sCalledByUs = false; }
  522 + }
  523 +
  524 + // ── Probe all f9 setter→column mappings (String + int, one-shot) ──────────
  525 + // Calls each String setter and each void(int) method with a unique marker,
  526 + // then calls convertTo() to see which ContentValues key reflects the marker.
  527 + // Returns a Map<columnName, setterMethodName>.
  528 + private static volatile java.util.Map<String, String> sF9SetterMap = null;
  529 +
  530 + private static java.util.Map<String, String> probeAllF9Setters(Class<?> f9Class) {
  531 + java.util.Map<String, String> result = new java.util.HashMap<>();
  532 +
  533 + // String setters (known from class dump)
  534 + for (String sn : new String[]{"Z0", "C1", "D1", "a1", "d1", "h1", "i1"}) {
  535 + try {
  536 + Object probe = XposedHelpers.newInstance(f9Class);
  537 + XposedHelpers.callMethod(probe, sn, "PROBE_" + sn);
  538 + android.content.ContentValues cv = (android.content.ContentValues)
  539 + XposedHelpers.callMethod(probe, "convertTo");
  540 + for (String key : cv.keySet()) {
  541 + Object val = cv.get(key);
  542 + if (("PROBE_" + sn).equals(val != null ? val.toString() : "")) {
  543 + result.put(key, sn);
  544 + XposedBridge.log("[WeChatHook] f9 str setter " + sn + " -> " + key);
  545 + }
  546 + }
  547 + } catch (Throwable t) {
  548 + XposedBridge.log("[WeChatHook] f9 probe str " + sn + ": " + t);
  549 + }
  550 + }
  551 +
  552 + // Int setters: scan all void(int) methods
  553 + try {
  554 + for (java.lang.reflect.Method m : f9Class.getDeclaredMethods()) {
  555 + if (m.getReturnType() != void.class) continue;
  556 + java.lang.Class<?>[] pt = m.getParameterTypes();
  557 + if (pt.length != 1 || pt[0] != int.class) continue;
  558 + m.setAccessible(true);
  559 + try {
  560 + Object probe = XposedHelpers.newInstance(f9Class);
  561 + m.invoke(probe, 88888);
  562 + android.content.ContentValues cv = (android.content.ContentValues)
  563 + XposedHelpers.callMethod(probe, "convertTo");
  564 + for (String key : cv.keySet()) {
  565 + Object val = cv.get(key);
  566 + if (val instanceof Integer && (Integer) val == 88888) {
  567 + result.put(key, m.getName());
  568 + XposedBridge.log("[WeChatHook] f9 int setter " + m.getName() + " -> " + key);
  569 + }
  570 + }
  571 + } catch (Throwable ignored) {}
  572 + }
  573 + } catch (Throwable t) {
  574 + XposedBridge.log("[WeChatHook] f9 int probe scan failed: " + t);
  575 + }
  576 +
  577 + // byte[] setters: scan all void(byte[]) methods — discovers lvbuffer setter
  578 + try {
  579 + for (java.lang.reflect.Method m : f9Class.getDeclaredMethods()) {
  580 + if (m.getReturnType() != void.class) continue;
  581 + java.lang.Class<?>[] pt = m.getParameterTypes();
  582 + if (pt.length != 1 || pt[0] != byte[].class) continue;
  583 + m.setAccessible(true);
  584 + // Marker: a 4-byte sentinel we can recognize in cv
  585 + byte[] marker = new byte[]{(byte)0xDE, (byte)0xAD, (byte)0xBE, (byte)0xEF};
  586 + try {
  587 + Object probe = XposedHelpers.newInstance(f9Class);
  588 + m.invoke(probe, (Object) marker);
  589 + android.content.ContentValues cv = (android.content.ContentValues)
  590 + XposedHelpers.callMethod(probe, "convertTo");
  591 + for (String key : cv.keySet()) {
  592 + Object val = cv.get(key);
  593 + if (val instanceof byte[]) {
  594 + byte[] got = (byte[]) val;
  595 + if (got.length == 4 && got[0] == (byte)0xDE && got[1] == (byte)0xAD) {
  596 + result.put(key + ":bytes", m.getName());
  597 + XposedBridge.log("[WeChatHook] f9 bytes setter " + m.getName() + " -> " + key);
  598 + }
  599 + }
  600 + }
  601 + } catch (Throwable ignored) {}
  602 + }
  603 + } catch (Throwable t) {
  604 + XposedBridge.log("[WeChatHook] f9 bytes probe scan failed: " + t);
  605 + }
  606 +
  607 + XposedBridge.log("[WeChatHook] f9 setter map: " + result);
  608 + return result;
  609 + }
  610 +
  611 + // ── Hook w11.r0.H(String) — CDN upload entry-point trace ─────────────────
  612 + // Logs every r0.H() call: dumps all String+File fields on r0 so we can identify
  613 + // which field contains the audio file path that H() uploads to CDN.
  614 + // Hook ALL methods on pt0.e0 (voice-send coroutine class found in stack trace).
  615 + // Goal: find which method triggers CDN upload AFTER f9.convertTo() returns.
  616 + // pt0.e0.k returns f9 objects and fires in multiple threads — CDN upload entry point.
  617 + private void hookPt0E0(ClassLoader cl, String procName) {
  618 + try {
  619 + Class<?> cls = XposedHelpers.findClass("pt0.e0", cl);
  620 + java.lang.reflect.Method[] methods = cls.getDeclaredMethods();
  621 + StringBuilder sig = new StringBuilder("[WeChatHook] pt0.e0 methods(" + methods.length + "):");
  622 + for (java.lang.reflect.Method m : methods) sig.append(" ").append(m.getName()).append("(").append(m.getParameterTypes().length).append(")");
  623 + XposedBridge.log(sig.toString());
  624 + for (java.lang.reflect.Method m : methods) {
  625 + final String mName = m.getName();
  626 + m.setAccessible(true);
  627 + XposedBridge.hookMethod(m, new XC_MethodHook() {
  628 + @Override protected void beforeHookedMethod(MethodHookParam p) {
  629 + // Capture singleton from ANY method (not just r()), so it's
  630 + // available even when no real voice send has happened this session.
  631 + if (sPt0E0Instance == null && p.thisObject != null) {
  632 + sPt0E0Instance = p.thisObject;
  633 + XposedBridge.log("[WeChatHook] pt0.e0 singleton captured via " + mName + ": " + p.thisObject);
  634 + }
  635 + if ("k".equals(mName)) {
  636 + // k(2): confirmed signature k(String talker, Long msgLocalId)
  637 + // CDN worker calls this to dequeue next upload task.
  638 + // Only log first call per send to avoid spam.
  639 + Object a0 = p.args != null && p.args.length > 0 ? p.args[0] : null;
  640 + Object a1 = p.args != null && p.args.length > 1 ? p.args[1] : null;
  641 + XposedBridge.log("[WeChatHook] pt0.e0.k ENTER talker=" + a0
  642 + + " msgLocalId=" + (a1 instanceof Long ? ((Long)a1).longValue() : a1));
  643 + } else if ("r".equals(mName)) {
  644 + // Save pt0.e0 singleton for later use in sendVoiceViaAPI.
  645 + if (sPt0E0Instance == null && p.thisObject != null) {
  646 + sPt0E0Instance = p.thisObject;
  647 + XposedBridge.log("[WeChatHook] pt0.e0 singleton captured: " + p.thisObject);
  648 + }
  649 + XposedBridge.log("[WeChatHook] pt0.e0.r ENTER, dumping thisObject fields:");
  650 + if (p.thisObject != null) {
  651 + Class<?> c = p.thisObject.getClass();
  652 + while (c != null && !c.equals(Object.class)) {
  653 + for (java.lang.reflect.Field f : c.getDeclaredFields()) {
  654 + f.setAccessible(true);
  655 + try {
  656 + Object v = f.get(p.thisObject);
  657 + XposedBridge.log("[WeChatHook] " + c.getSimpleName()
  658 + + "." + f.getName() + "=" + (v == null ? "null"
  659 + : (v instanceof String || v instanceof Number || v instanceof Boolean)
  660 + ? v.toString() : v.getClass().getName() + "@" + System.identityHashCode(v)));
  661 + } catch (Throwable ignored) {}
  662 + }
  663 + c = c.getSuperclass();
  664 + }
  665 + }
  666 + } else if ("s".equals(mName)) {
  667 + // s(3): CDN upload trigger. Log args + full f9 hierarchy for diff analysis.
  668 + StringBuilder sb = new StringBuilder("[WeChatHook] pt0.e0.s ENTER args:");
  669 + if (p.args != null) for (int i = 0; i < p.args.length; i++) {
  670 + Object a = p.args[i];
  671 + if (a == null) { sb.append(" [").append(i).append("]=null"); }
  672 + else if (a instanceof String) { sb.append(" [").append(i).append("]=String(\"").append(a).append("\")"); }
  673 + else if (a instanceof Number) { sb.append(" [").append(i).append("]=").append(a); }
  674 + else { sb.append(" [").append(i).append("]=").append(a.getClass().getName()).append("@").append(System.identityHashCode(a)); }
  675 + }
  676 + XposedBridge.log(sb.toString());
  677 + // Dump ALL fields of f9 (args[2]) across full parent hierarchy
  678 + if (p.args != null && p.args.length > 2 && p.args[2] != null) {
  679 + Object f9 = p.args[2];
  680 + StringBuilder fb = new StringBuilder("[WeChatHook] pt0.e0.s f9 DUMP:");
  681 + Class<?> c = f9.getClass();
  682 + while (c != null && !c.equals(Object.class)) {
  683 + for (java.lang.reflect.Field f : c.getDeclaredFields()) {
  684 + f.setAccessible(true);
  685 + try {
  686 + Object v = f.get(f9);
  687 + String vs;
  688 + if (v == null) vs = "null";
  689 + else if (v instanceof byte[]) vs = "byte[" + ((byte[])v).length + "]";
  690 + else if (v instanceof String || v instanceof Number || v instanceof Boolean) vs = v.toString();
  691 + else vs = v.getClass().getSimpleName() + "@" + System.identityHashCode(v);
  692 + fb.append("\n ").append(c.getSimpleName()).append(".").append(f.getName()).append("=").append(vs);
  693 + } catch (Throwable ignored) {}
  694 + }
  695 + c = c.getSuperclass();
  696 + }
  697 + XposedBridge.log(fb.toString());
  698 + }
  699 + } else if (p.args != null && p.args.length == 2
  700 + && ("a".equals(mName) || "b".equals(mName) || "l".equals(mName)
  701 + || "n".equals(mName) || "q".equals(mName))) {
  702 + // Log 2-arg entry methods — one of these is likely the
  703 + // "enqueue voice for send" entry point called by WeChat UI
  704 + StringBuilder sb2 = new StringBuilder(
  705 + "[WeChatHook] pt0.e0." + mName + "(2) ENTER");
  706 + if (p.args != null) for (int i = 0; i < p.args.length; i++) {
  707 + Object a = p.args[i];
  708 + if (a == null) sb2.append(" arg").append(i).append("=null");
  709 + else if (a instanceof String) sb2.append(" arg").append(i).append("=\"").append(a).append("\"");
  710 + else if (a instanceof Number) sb2.append(" arg").append(i).append("=").append(a);
  711 + else sb2.append(" arg").append(i).append("=").append(a.getClass().getName()).append("@").append(System.identityHashCode(a));
  712 + }
  713 + XposedBridge.log(sb2.toString());
  714 + } else {
  715 + XposedBridge.log("[WeChatHook] pt0.e0." + mName + " ENTER");
  716 + }
  717 + }
  718 + @Override protected void afterHookedMethod(MethodHookParam p) {
  719 + if (p.hasThrowable()) {
  720 + XposedBridge.log("[WeChatHook] pt0.e0." + mName + " THREW " + p.getThrowable());
  721 + } else if ("k".equals(mName)) {
  722 + Object ret = p.getResult();
  723 + if (ret != null) {
  724 + // Dump ALL declared fields on f9 (first call only, to learn field names)
  725 + StringBuilder fb = new StringBuilder("[WeChatHook] pt0.e0.k OK f9=").append(ret.getClass().getSimpleName());
  726 + java.lang.reflect.Field[] fields = ret.getClass().getDeclaredFields();
  727 + for (java.lang.reflect.Field f : fields) {
  728 + f.setAccessible(true);
  729 + try {
  730 + Object v = f.get(ret);
  731 + fb.append(" ").append(f.getName()).append("=").append(
  732 + v == null ? "null" : (v instanceof String || v instanceof Number || v instanceof Boolean)
  733 + ? v.toString() : v.getClass().getSimpleName() + "@" + System.identityHashCode(v));
  734 + } catch (Throwable ignored) {}
  735 + }
  736 + XposedBridge.log(fb.toString());
  737 + } else {
  738 + XposedBridge.log("[WeChatHook] pt0.e0.k OK ret=null");
  739 + }
  740 + } else {
  741 + XposedBridge.log("[WeChatHook] pt0.e0." + mName + " OK ret=" + p.getResult());
  742 + }
  743 + }
  744 + });
  745 + }
  746 + XposedBridge.log("[WeChatHook] hookPt0E0: hooked " + methods.length + " methods in " + procName);
  747 + } catch (Throwable t) {
  748 + XposedBridge.log("[WeChatHook] hookPt0E0 failed in " + procName + ": " + t);
  749 + }
  750 + }
  751 +
  752 + // ── Surgical voice-send entry probe ──────────────────────────────────────
  753 + // SAFE version: hooks ONLY the voice-send-specific classes (jg0.x coordinator
  754 + // + qi3.f0/g0 voice-message objects), NOT generic coroutine classes, so it
  755 + // won't add anti-tamper risk to the live Pad session. Goal: find the entry
  756 + // method that receives (talker, silk file/bytes, durationMs) in plain form,
  757 + // which we can then call synthetically to get a real, delivered voice send.
  758 + private static String fmtArg(Object a) {
  759 + if (a == null) return "null";
  760 + if (a instanceof byte[]) return "byte[" + ((byte[]) a).length + "]";
  761 + if (a instanceof String) return "\"" + a + "\"";
  762 + if (a instanceof Number || a instanceof Boolean) return a.toString();
  763 + return a.getClass().getName() + "@" + System.identityHashCode(a);
  764 + }
  765 +
  766 + // Recursively dump an object's non-static fields, bounded by depth, to find
  767 + // where scalar values (talker string / silk path / duration) are captured.
  768 + private static void dumpDeep(Object o, String prefix, int depth, StringBuilder sb) {
  769 + if (o == null || depth < 0) return;
  770 + for (Class<?> c = o.getClass(); c != null && !c.equals(Object.class); c = c.getSuperclass()) {
  771 + for (java.lang.reflect.Field f : c.getDeclaredFields()) {
  772 + if (java.lang.reflect.Modifier.isStatic(f.getModifiers())) continue;
  773 + f.setAccessible(true);
  774 + Object v;
  775 + try { v = f.get(o); } catch (Throwable t) { continue; }
  776 + sb.append("\n").append(prefix).append(f.getName()).append("=").append(fmtArg(v));
  777 + // Recurse into non-scalar, non-array WeChat/kotlin objects.
  778 + if (v != null && depth > 0
  779 + && !(v instanceof String) && !(v instanceof Number)
  780 + && !(v instanceof Boolean) && !(v instanceof byte[])
  781 + && !v.getClass().isArray()
  782 + && !v.getClass().getName().startsWith("java.")
  783 + && !v.getClass().getName().startsWith("android.")) {
  784 + dumpDeep(v, prefix + " ", depth - 1, sb);
  785 + }
  786 + }
  787 + }
  788 + }
  789 +
  790 + private void hookVoiceProbe(ClassLoader cl, String procName) {
  791 + // jg0.x — voice send coordinator; hook ALL methods to find the entry.
  792 + try {
  793 + Class<?> xClass = XposedHelpers.findClass("jg0.x", cl);
  794 + int n = 0;
  795 + for (java.lang.reflect.Method m : xClass.getDeclaredMethods()) {
  796 + final String mn = m.getName();
  797 + m.setAccessible(true);
  798 + XposedBridge.hookMethod(m, new XC_MethodHook() {
  799 + @Override protected void beforeHookedMethod(MethodHookParam p) {
  800 + // ── Voice hot-swap (the route that actually delivers) ──────────
  801 + // jg0.x.w(jg0.x, qi3.d0, w21.w0, int type, int durMs, w21.t silk, Cont)
  802 + // is the CDN uploadAttach step. On the REAL (non-resume) call, arg5
  803 + // (w21.t) holds the recorded SILK in its single byte[] field. When
  804 + // armed, replace it with our TTS SILK so WeChat uploads our audio.
  805 + // (This lives in the probe hook because this fork won't stack a 2nd
  806 + // hook on an already-hooked method — see hookVoiceSwap note.)
  807 + if ("w".equals(mn) && sSwapArmed && sSwapSilk != null
  808 + && System.currentTimeMillis() < sSwapExpiresAt
  809 + && p.args != null && p.args.length == 7 && p.args[5] != null) {
  810 + try {
  811 + Object tHolder = p.args[5];
  812 + java.lang.reflect.Field byteF = null;
  813 + for (java.lang.reflect.Field f : tHolder.getClass().getDeclaredFields())
  814 + if (f.getType() == byte[].class) { byteF = f; break; }
  815 + if (byteF != null) {
  816 + byteF.setAccessible(true);
  817 + byte[] orig = (byte[]) byteF.get(tHolder);
  818 + byteF.set(tHolder, sSwapSilk);
  819 + if (orig != null) for (java.lang.reflect.Field f : tHolder.getClass().getDeclaredFields()) {
  820 + if (f.getType() != int.class) continue;
  821 + f.setAccessible(true);
  822 + if (f.getInt(tHolder) == orig.length) f.setInt(tHolder, sSwapSilk.length);
  823 + }
  824 + if (sSwapDuration > 0) p.args[4] = sSwapDuration;
  825 + XposedBridge.log("[WeChatHook] VOICE SWAP DONE: "
  826 + + (orig == null ? "?" : orig.length) + "B -> " + sSwapSilk.length
  827 + + "B dur -> " + p.args[4]);
  828 + sSwapArmed = false; sSwapSilk = null; // one-shot
  829 + }
  830 + } catch (Throwable t) {
  831 + XposedBridge.log("[WeChatHook] VOICE SWAP failed: " + t);
  832 + }
  833 + }
  834 + StringBuilder sb = new StringBuilder("[WeChatHook] jg0.x." + mn + "(");
  835 + if (p.args != null) for (int i = 0; i < p.args.length; i++) {
  836 + if (i > 0) sb.append(", ");
  837 + sb.append(fmtArg(p.args[i]));
  838 + }
  839 + sb.append(")");
  840 + // Deep-dump the send-carrying methods: D's lambda (arg0) and
  841 + // w's descriptor args — to locate talker/silk/duration fields.
  842 + if ("D".equals(mn) && p.args != null && p.args.length > 0) {
  843 + sb.append("\n [D arg0 pu.m0 deep]:");
  844 + dumpDeep(p.args[0], " ", 3, sb);
  845 + } else if ("w".equals(mn) && p.args != null) {
  846 + for (int i = 0; i < p.args.length; i++) {
  847 + if (p.args[i] != null && !(p.args[i] instanceof Number)) {
  848 + sb.append("\n [w arg").append(i).append(" deep]:");
  849 + dumpDeep(p.args[i], " ", 2, sb);
  850 + }
  851 + }
  852 + }
  853 + XposedBridge.log(sb.toString());
  854 + }
  855 + });
  856 + n++;
  857 + }
  858 + XposedBridge.log("[WeChatHook] hookVoiceProbe: jg0.x " + n + " methods in " + procName);
  859 + } catch (Throwable t) {
  860 + XposedBridge.log("[WeChatHook] hookVoiceProbe jg0.x failed: " + t);
  861 + }
  862 + // qi3.f0 / qi3.g0 — voice-message domain objects; dump ctor args + fields.
  863 + for (String cn : new String[]{"qi3.f0", "qi3.g0"}) {
  864 + try {
  865 + Class<?> c = XposedHelpers.findClass(cn, cl);
  866 + for (java.lang.reflect.Constructor<?> ctor : c.getDeclaredConstructors()) {
  867 + ctor.setAccessible(true);
  868 + final String fcn = cn;
  869 + XposedBridge.hookMethod(ctor, new XC_MethodHook() {
  870 + @Override protected void afterHookedMethod(MethodHookParam p) {
  871 + StringBuilder sb = new StringBuilder("[WeChatHook] " + fcn + ".<init>(");
  872 + if (p.args != null) for (int i = 0; i < p.args.length; i++) {
  873 + if (i > 0) sb.append(", ");
  874 + sb.append(fmtArg(p.args[i]));
  875 + }
  876 + sb.append(") fields:");
  877 + for (Class<?> cc = p.thisObject.getClass();
  878 + cc != null && !cc.equals(Object.class); cc = cc.getSuperclass()) {
  879 + for (java.lang.reflect.Field f : cc.getDeclaredFields()) {
  880 + if (java.lang.reflect.Modifier.isStatic(f.getModifiers())) continue;
  881 + f.setAccessible(true);
  882 + try {
  883 + sb.append("\n ").append(f.getName()).append("=").append(fmtArg(f.get(p.thisObject)));
  884 + } catch (Throwable ignored) {}
  885 + }
  886 + }
  887 + XposedBridge.log(sb.toString());
  888 + }
  889 + });
  890 + }
  891 + XposedBridge.log("[WeChatHook] hookVoiceProbe: " + cn + " ctor hooked in " + procName);
  892 + } catch (Throwable t) {
  893 + XposedBridge.log("[WeChatHook] hookVoiceProbe " + cn + " failed: " + t);
  894 + }
  895 + }
  896 + }
  897 +
  898 + // ── Find the voice-send entry point ──────────────────────────────────────
  899 + // pu.o0 is the outer coroutine, launched by the real entry point (async, so
  900 + // it doesn't appear in the jg0.x.D stack). Hooking pu.o0's CONSTRUCTOR gives
  901 + // a synchronous stack trace revealing the method that starts a voice send.
  902 + // Also dumps qi3.f0/g0 constructors (the voice-message domain objects that
  903 + // carry talker/silk/duration).
  904 + private void hookVoiceEntry(ClassLoader cl, String procName) {
  905 + // pu.o0 constructor — stack trace = the real send entry point.
  906 + for (String cn : new String[]{"pu.o0", "pu.m0"}) {
  907 + try {
  908 + Class<?> c = XposedHelpers.findClass(cn, cl);
  909 + for (java.lang.reflect.Constructor<?> ctor : c.getDeclaredConstructors()) {
  910 + ctor.setAccessible(true);
  911 + final String fcn = cn;
  912 + final int np = ctor.getParameterTypes().length;
  913 + XposedBridge.hookMethod(ctor, new XC_MethodHook() {
  914 + private volatile boolean logged = false;
  915 + @Override protected void afterHookedMethod(MethodHookParam p) {
  916 + if (logged) return;
  917 + logged = true;
  918 + StringBuilder sb = new StringBuilder(
  919 + "[WeChatHook] " + fcn + ".<init>(" + np + ") args:");
  920 + if (p.args != null) for (int i = 0; i < p.args.length; i++) {
  921 + Object a = p.args[i];
  922 + sb.append("\n arg[").append(i).append("]=")
  923 + .append(a == null ? "null" : a.getClass().getName());
  924 + }
  925 + sb.append("\n").append(android.util.Log.getStackTraceString(new Exception()));
  926 + XposedBridge.log(sb.toString());
  927 + }
  928 + });
  929 + }
  930 + XposedBridge.log("[WeChatHook] hookVoiceEntry: " + cn + " ctor hooked in " + procName);
  931 + } catch (Throwable t) {
  932 + XposedBridge.log("[WeChatHook] hookVoiceEntry " + cn + " failed: " + t);
  933 + }
  934 + }
  935 + // qi3.f0 / qi3.g0 constructors — dump their args (talker/silk/duration).
  936 + for (String cn : new String[]{"qi3.f0", "qi3.g0"}) {
  937 + try {
  938 + Class<?> c = XposedHelpers.findClass(cn, cl);
  939 + StringBuilder info = new StringBuilder("[WeChatHook] " + cn
  940 + + " super=" + c.getSuperclass().getName() + " fields:");
  941 + for (java.lang.reflect.Field f : c.getDeclaredFields())
  942 + info.append(" ").append(f.getName()).append("(").append(f.getType().getSimpleName()).append(")");
  943 + XposedBridge.log(info.toString());
  944 + for (java.lang.reflect.Constructor<?> ctor : c.getDeclaredConstructors()) {
  945 + ctor.setAccessible(true);
  946 + final String fcn = cn;
  947 + XposedBridge.hookMethod(ctor, new XC_MethodHook() {
  948 + private volatile boolean logged = false;
  949 + @Override protected void afterHookedMethod(MethodHookParam p) {
  950 + if (logged) return;
  951 + logged = true;
  952 + StringBuilder sb = new StringBuilder(
  953 + "[WeChatHook] " + fcn + ".<init> args:");
  954 + if (p.args != null) for (int i = 0; i < p.args.length; i++) {
  955 + Object a = p.args[i];
  956 + String vs;
  957 + if (a == null) vs = "null";
  958 + else if (a instanceof byte[]) vs = "byte[" + ((byte[])a).length + "]";
  959 + else if (a instanceof String || a instanceof Number || a instanceof Boolean)
  960 + vs = a.getClass().getSimpleName() + "(" + a + ")";
  961 + else vs = a.getClass().getName();
  962 + sb.append("\n arg[").append(i).append("]=").append(vs);
  963 + }
  964 + // Dump the constructed object's fields too
  965 + for (Class<?> cc = p.thisObject.getClass();
  966 + cc != null && !cc.equals(Object.class); cc = cc.getSuperclass()) {
  967 + for (java.lang.reflect.Field f : cc.getDeclaredFields()) {
  968 + if (java.lang.reflect.Modifier.isStatic(f.getModifiers())) continue;
  969 + f.setAccessible(true);
  970 + try {
  971 + Object v = f.get(p.thisObject);
  972 + String vs;
  973 + if (v == null) vs = "null";
  974 + else if (v instanceof byte[]) vs = "byte[" + ((byte[])v).length + "]";
  975 + else if (v instanceof String || v instanceof Number || v instanceof Boolean) vs = v.toString();
  976 + else vs = v.getClass().getSimpleName();
  977 + sb.append("\n this.").append(f.getName()).append("=").append(vs);
  978 + } catch (Throwable ignored) {}
  979 + }
  980 + }
  981 + XposedBridge.log(sb.toString());
  982 + }
  983 + });
  984 + }
  985 + XposedBridge.log("[WeChatHook] hookVoiceEntry: " + cn + " ctor hooked in " + procName);
  986 + } catch (Throwable t) {
  987 + XposedBridge.log("[WeChatHook] hookVoiceEntry " + cn + " failed: " + t);
  988 + }
  989 + }
  990 + }
  991 +
  992 + // ── Hook jg0.j / jg0.x / g9 ─────────────────────────────────────────────
  993 + // Reveals the internal structure needed to call pt0.e0.r() synthetically.
  994 + // jg0.j captures the g9 (voice message / f9 subclass) as a field.
  995 + // jg0.x.D sets up jg0.j and starts the coroutine.
  996 + // g9 extends f9 (or is f9) with M9/N9 DB-insert methods.
  997 + private void hookJg0(ClassLoader cl, String procName) {
  998 + // ── jg0.j (the inner coroutine whose invokeSuspend calls pt0.e0.r) ────
  999 + try {
  1000 + Class<?> jClass = XposedHelpers.findClass("jg0.j", cl);
  1001 + StringBuilder jInfo = new StringBuilder("[WeChatHook] jg0.j class=" + jClass.getName()
  1002 + + " super=" + jClass.getSuperclass().getName() + " ownFields:");
  1003 + for (java.lang.reflect.Field f : jClass.getDeclaredFields())
  1004 + jInfo.append(" ").append(f.getName()).append("(").append(f.getType().getSimpleName()).append(")");
  1005 + jInfo.append(" | superFields:");
  1006 + for (java.lang.reflect.Field f : jClass.getSuperclass().getDeclaredFields())
  1007 + jInfo.append(" ").append(f.getName()).append("(").append(f.getType().getSimpleName()).append(")");
  1008 + XposedBridge.log(jInfo.toString());
  1009 +
  1010 + // Hook invokeSuspend — fires every time a jg0.j coroutine step runs.
  1011 + // We only care about the FIRST call (state=0, label=0) to see captured fields.
  1012 + try {
  1013 + XposedHelpers.findAndHookMethod(jClass, "invokeSuspend", Object.class,
  1014 + new XC_MethodHook() {
  1015 + private volatile boolean sLogged = false;
  1016 + @Override protected void beforeHookedMethod(MethodHookParam p) {
  1017 + if (sLogged) return;
  1018 + sLogged = true;
  1019 + StringBuilder sb = new StringBuilder(
  1020 + "[WeChatHook] jg0.j.invokeSuspend FIRST fields:");
  1021 + for (Class<?> c = p.thisObject.getClass();
  1022 + c != null && !c.equals(Object.class); c = c.getSuperclass()) {
  1023 + for (java.lang.reflect.Field f : c.getDeclaredFields()) {
  1024 + if (java.lang.reflect.Modifier.isStatic(f.getModifiers())) continue;
  1025 + f.setAccessible(true);
  1026 + try {
  1027 + Object v = f.get(p.thisObject);
  1028 + sb.append("\n ").append(c.getSimpleName())
  1029 + .append(".").append(f.getName()).append("=")
  1030 + .append(v == null ? "null"
  1031 + : v.getClass().getName() + "@" + System.identityHashCode(v));
  1032 + } catch (Throwable ignored) {}
  1033 + }
  1034 + }
  1035 + XposedBridge.log(sb.toString());
  1036 + }
  1037 + });
  1038 + } catch (Throwable t) {
  1039 + XposedBridge.log("[WeChatHook] hookJg0 jg0.j.invokeSuspend hook failed: " + t);
  1040 + }
  1041 + XposedBridge.log("[WeChatHook] hookJg0: jg0.j hooked in " + procName);
  1042 + } catch (Throwable t) {
  1043 + XposedBridge.log("[WeChatHook] hookJg0 jg0.j failed: " + t);
  1044 + }
  1045 +
  1046 + // ── jg0.x (coordinator that creates jg0.j and calls D to enqueue send) ──
  1047 + try {
  1048 + Class<?> xClass = XposedHelpers.findClass("jg0.x", cl);
  1049 + StringBuilder xInfo = new StringBuilder("[WeChatHook] jg0.x methods:");
  1050 + for (java.lang.reflect.Method m : xClass.getDeclaredMethods())
  1051 + xInfo.append(" ").append(m.getName()).append("(").append(m.getParameterTypes().length).append(")");
  1052 + xInfo.append(" | ownFields:");
  1053 + for (java.lang.reflect.Field f : xClass.getDeclaredFields())
  1054 + xInfo.append(" ").append(f.getName()).append("(").append(f.getType().getSimpleName()).append(")");
  1055 + XposedBridge.log(xInfo.toString());
  1056 +
  1057 + // Hook D() — the method called from pu.o0.invokeSuspend(84) that enqueues the send
  1058 + for (java.lang.reflect.Method m : xClass.getDeclaredMethods()) {
  1059 + if (!"D".equals(m.getName())) continue;
  1060 + m.setAccessible(true);
  1061 + final String sig = m.toGenericString();
  1062 + XposedBridge.hookMethod(m, new XC_MethodHook() {
  1063 + @Override protected void beforeHookedMethod(MethodHookParam p) {
  1064 + StringBuilder sb = new StringBuilder(
  1065 + "[WeChatHook] jg0.x.D ENTER sig=" + sig);
  1066 + // args
  1067 + if (p.args != null) for (int i = 0; i < p.args.length; i++) {
  1068 + Object a = p.args[i];
  1069 + sb.append("\n arg[").append(i).append("]=")
  1070 + .append(a == null ? "null" : a.getClass().getName()
  1071 + + "@" + System.identityHashCode(a));
  1072 + // If it looks like a voice-msg / f9 subclass, dump its fields
  1073 + if (a != null) {
  1074 + for (Class<?> c2 = a.getClass();
  1075 + c2 != null && !c2.equals(Object.class); c2 = c2.getSuperclass()) {
  1076 + for (java.lang.reflect.Field f2 : c2.getDeclaredFields()) {
  1077 + if (java.lang.reflect.Modifier.isStatic(f2.getModifiers())) continue;
  1078 + f2.setAccessible(true);
  1079 + try {
  1080 + Object v2 = f2.get(a);
  1081 + String vs;
  1082 + if (v2 == null) vs = "null";
  1083 + else if (v2 instanceof byte[]) vs = "byte[" + ((byte[])v2).length + "]";
  1084 + else if (v2 instanceof String || v2 instanceof Number
  1085 + || v2 instanceof Boolean) vs = v2.toString();
  1086 + else vs = v2.getClass().getSimpleName();
  1087 + sb.append("\n ").append(c2.getSimpleName())
  1088 + .append(".").append(f2.getName()).append("=").append(vs);
  1089 + } catch (Throwable ignored2) {}
  1090 + }
  1091 + }
  1092 + }
  1093 + }
  1094 + // thisObject fields
  1095 + for (Class<?> c = p.thisObject.getClass();
  1096 + c != null && !c.equals(Object.class); c = c.getSuperclass()) {
  1097 + for (java.lang.reflect.Field f : c.getDeclaredFields()) {
  1098 + if (java.lang.reflect.Modifier.isStatic(f.getModifiers())) continue;
  1099 + f.setAccessible(true);
  1100 + try {
  1101 + Object v = f.get(p.thisObject);
  1102 + sb.append("\n this.").append(c.getSimpleName())
  1103 + .append(".").append(f.getName()).append("=")
  1104 + .append(v == null ? "null" : v.getClass().getName());
  1105 + } catch (Throwable ignored) {}
  1106 + }
  1107 + }
  1108 + XposedBridge.log(sb.toString());
  1109 + }
  1110 + });
  1111 + }
  1112 + XposedBridge.log("[WeChatHook] hookJg0: jg0.x hooked in " + procName);
  1113 + } catch (Throwable t) {
  1114 + XposedBridge.log("[WeChatHook] hookJg0 jg0.x failed: " + t);
  1115 + }
  1116 +
  1117 + // ── g9 (likely a subclass of f9; M9/N9 are the DB-insert methods) ─────
  1118 + try {
  1119 + Class<?> g9Class = XposedHelpers.findClass("com.tencent.mm.storage.g9", cl);
  1120 + StringBuilder g9Info = new StringBuilder("[WeChatHook] g9 super="
  1121 + + g9Class.getSuperclass().getName() + " methods:");
  1122 + for (java.lang.reflect.Method m : g9Class.getDeclaredMethods())
  1123 + g9Info.append(" ").append(m.getName()).append("(").append(m.getParameterTypes().length).append(")");
  1124 + g9Info.append(" | ownFields:");
  1125 + for (java.lang.reflect.Field f : g9Class.getDeclaredFields())
  1126 + g9Info.append(" ").append(f.getName()).append("(").append(f.getType().getSimpleName()).append(")");
  1127 + XposedBridge.log(g9Info.toString());
  1128 +
  1129 + for (java.lang.reflect.Method m : g9Class.getDeclaredMethods()) {
  1130 + if (!"M9".equals(m.getName()) && !"N9".equals(m.getName())) continue;
  1131 + m.setAccessible(true);
  1132 + final String mName2 = m.getName();
  1133 + final String mSig2 = m.toGenericString();
  1134 + XposedBridge.hookMethod(m, new XC_MethodHook() {
  1135 + @Override protected void beforeHookedMethod(MethodHookParam p) {
  1136 + StringBuilder sb = new StringBuilder(
  1137 + "[WeChatHook] g9." + mName2 + " ENTER sig=" + mSig2
  1138 + + " thisClass=" + p.thisObject.getClass().getName());
  1139 + if (p.args != null) for (int i = 0; i < p.args.length; i++)
  1140 + sb.append(" arg[").append(i).append("]=")
  1141 + .append(p.args[i] == null ? "null" : p.args[i].getClass().getName());
  1142 + XposedBridge.log(sb.toString());
  1143 + }
  1144 + @Override protected void afterHookedMethod(MethodHookParam p) {
  1145 + if (p.hasThrowable())
  1146 + XposedBridge.log("[WeChatHook] g9." + mName2 + " THREW: " + p.getThrowable());
  1147 + else
  1148 + XposedBridge.log("[WeChatHook] g9." + mName2 + " OK ret=" + p.getResult());
  1149 + }
  1150 + });
  1151 + }
  1152 + XposedBridge.log("[WeChatHook] hookJg0: g9 hooked in " + procName);
  1153 + } catch (Throwable t) {
  1154 + XposedBridge.log("[WeChatHook] hookJg0 g9 failed: " + t);
  1155 + }
  1156 +
  1157 + // ── pu.o0 (outer coroutine that calls jg0.x.D) ───────────────────────
  1158 + // Hook invokeSuspend to see what it captures (especially the g9/voice data).
  1159 + try {
  1160 + Class<?> puClass = XposedHelpers.findClass("pu.o0", cl);
  1161 + StringBuilder puInfo = new StringBuilder("[WeChatHook] pu.o0 super="
  1162 + + puClass.getSuperclass().getName() + " | ownFields:");
  1163 + for (java.lang.reflect.Field f : puClass.getDeclaredFields())
  1164 + puInfo.append(" ").append(f.getName()).append("(").append(f.getType().getSimpleName()).append(")");
  1165 + XposedBridge.log(puInfo.toString());
  1166 +
  1167 + XposedHelpers.findAndHookMethod(puClass, "invokeSuspend", Object.class,
  1168 + new XC_MethodHook() {
  1169 + private volatile boolean sLogged2 = false;
  1170 + @Override protected void beforeHookedMethod(MethodHookParam p) {
  1171 + if (sLogged2) return;
  1172 + sLogged2 = true;
  1173 + StringBuilder sb = new StringBuilder(
  1174 + "[WeChatHook] pu.o0.invokeSuspend FIRST fields:");
  1175 + for (Class<?> c = p.thisObject.getClass();
  1176 + c != null && !c.equals(Object.class); c = c.getSuperclass()) {
  1177 + for (java.lang.reflect.Field f : c.getDeclaredFields()) {
  1178 + if (java.lang.reflect.Modifier.isStatic(f.getModifiers())) continue;
  1179 + f.setAccessible(true);
  1180 + try {
  1181 + Object v = f.get(p.thisObject);
  1182 + sb.append("\n ").append(c.getSimpleName())
  1183 + .append(".").append(f.getName()).append("=")
  1184 + .append(v == null ? "null"
  1185 + : v.getClass().getName() + "@" + System.identityHashCode(v));
  1186 + } catch (Throwable ignored) {}
  1187 + }
  1188 + }
  1189 + XposedBridge.log(sb.toString());
  1190 + }
  1191 + });
  1192 + XposedBridge.log("[WeChatHook] hookJg0: pu.o0 hooked in " + procName);
  1193 + } catch (Throwable t) {
  1194 + XposedBridge.log("[WeChatHook] hookJg0 pu.o0 failed: " + t);
  1195 + }
  1196 + }
  1197 +
  1198 + private void hookR0H(ClassLoader cl, String procName) {
  1199 + try {
  1200 + Class<?> r0Class = XposedHelpers.findClass("w11.r0", cl);
  1201 + int hooked = 0;
  1202 + // Hook ALL methods named H on r0 — real voice sends may use H() or H(int), not just H(String).
  1203 + for (java.lang.reflect.Method m : r0Class.getDeclaredMethods()) {
  1204 + if (!m.getName().equals("H")) continue;
  1205 + final String sig = m.toGenericString();
  1206 + final boolean isHString = m.getParameterTypes().length == 1
  1207 + && m.getParameterTypes()[0] == String.class;
  1208 + m.setAccessible(true);
  1209 + XposedBridge.hookMethod(m, new XC_MethodHook() {
  1210 + @Override
  1211 + protected void beforeHookedMethod(MethodHookParam p) throws Throwable {
  1212 + String by = sCalledByUs ? "US" : "WeChat";
  1213 + XposedBridge.log("[WeChatHook] r0." + sig + " ENTER by=" + by + " proc=" + procName);
  1214 + // Capture real dispatcher from any real WeChat r0 H() call.
  1215 + if (!sCalledByUs) {
  1216 + try {
  1217 + Object disp = XposedHelpers.getObjectField(p.thisObject, "dispatcher");
  1218 + if (disp != null && !(disp instanceof java.lang.reflect.Proxy)) {
  1219 + sCapturedDispatcher = disp;
  1220 + XposedBridge.log("[WeChatHook] hookR0H: REAL dispatcher=" + disp.getClass().getName() + " from " + sig);
  1221 + }
  1222 + } catch (Throwable ignored) {}
  1223 + // Also dump r0 fields on first real send to capture full state.
  1224 + dumpR0Fields(p.thisObject, "r0.H-WeChat by=" + by + " proc=" + procName);
  1225 + } else if (isHString) {
  1226 + dumpR0Fields(p.thisObject, "r0.H-ENTER by=US proc=" + procName);
  1227 + }
  1228 + }
  1229 + @Override
  1230 + protected void afterHookedMethod(MethodHookParam p) throws Throwable {
  1231 + String by = sCalledByUs ? "US" : "WeChat";
  1232 + XposedBridge.log("[WeChatHook] r0.H() DONE by=" + by + " proc=" + procName
  1233 + + (p.hasThrowable() ? " THREW=" + p.getThrowable() : " OK"));
  1234 + }
  1235 + });
  1236 + hooked++;
  1237 + }
  1238 + XposedBridge.log("[WeChatHook] hookR0H: hooked " + hooked + " H() overloads in " + procName);
  1239 + } catch (Throwable t) {
  1240 + XposedBridge.log("[WeChatHook] hookR0H failed in " + procName + ": " + t);
  1241 + }
  1242 + }
  1243 +
  1244 + // ── Capture live network dispatcher (com.tencent.mm.modelbase.m2) ────────────
  1245 + // m2 = MicroMsg.RDispatcher, the com.tencent.mm.network.s the send scene needs.
  1246 + // We grab the instance at construction (network init, before any synthetic send)
  1247 + // into sCapturedDispatcher, so sendVoiceViaAPI can hand r0 the REAL dispatcher.
  1248 + private void hookDispatcher(ClassLoader cl, String procName) {
  1249 + try {
  1250 + Class<?> m2 = XposedHelpers.findClass("com.tencent.mm.modelbase.m2", cl);
  1251 + XC_MethodHook grab = new XC_MethodHook() {
  1252 + @Override protected void beforeHookedMethod(MethodHookParam p) {
  1253 + if (sCapturedDispatcher == null && p.thisObject != null
  1254 + && !(p.thisObject instanceof java.lang.reflect.Proxy)) {
  1255 + sCapturedDispatcher = p.thisObject;
  1256 + XposedBridge.log("[WeChatHook] hookDispatcher: captured REAL m2="
  1257 + + p.thisObject + " in " + procName);
  1258 + }
  1259 + }
  1260 + };
  1261 + int n = 0;
  1262 + // Ctor: catches m2 constructed AFTER we install (network re-init).
  1263 + for (java.lang.reflect.Constructor<?> c : m2.getDeclaredConstructors()) {
  1264 + c.setAccessible(true);
  1265 + XposedBridge.hookMethod(c, new XC_MethodHook() {
  1266 + @Override protected void afterHookedMethod(MethodHookParam p) {
  1267 + sCapturedDispatcher = p.thisObject;
  1268 + XposedBridge.log("[WeChatHook] hookDispatcher: captured REAL m2 (ctor)="
  1269 + + p.thisObject + " in " + procName);
  1270 + }
  1271 + });
  1272 + n++;
  1273 + }
  1274 + // Instance methods: catches an ALREADY-existing m2 (constructed before our
  1275 + // hook / persistent connection) on its next network call. After capture the
  1276 + // callback is a single null check — negligible overhead.
  1277 + int mh = 0;
  1278 + for (java.lang.reflect.Method m : m2.getDeclaredMethods()) {
  1279 + if (java.lang.reflect.Modifier.isStatic(m.getModifiers())) continue;
  1280 + if (java.lang.reflect.Modifier.isAbstract(m.getModifiers())) continue;
  1281 + try { m.setAccessible(true); XposedBridge.hookMethod(m, grab); mh++; }
  1282 + catch (Throwable ignored) {}
  1283 + }
  1284 + XposedBridge.log("[WeChatHook] hookDispatcher: hooked " + n + " ctor(s) + "
  1285 + + mh + " method(s) on m2 in " + procName);
  1286 + } catch (Throwable t) {
  1287 + XposedBridge.log("[WeChatHook] hookDispatcher failed in " + procName + ": " + t);
  1288 + }
  1289 + }
  1290 +
  1291 + // ── Instrument voice-upload service w21.g1 (voiceinfo table) ─────────────────
  1292 + // On a REAL voice send, WeChat builds a w21.w0 upload-task and calls g1.L0(w0)
  1293 + // (insert) / g1.P0(file, w0) (upload). Dump every w0 field on those calls so we
  1294 + // learn the exact template (FileName/ClientId/MsgLocalId/VoiceLength/MsgTalker/
  1295 + // Status correlation) needed to synthesize the upload for hook-sent voice.
  1296 + // ── Voice hot-swap: replace recorded SILK with our TTS at the CDN-upload step ─
  1297 + // jg0.x.w(jg0.x self, qi3.d0, w21.w0, int type, int durationMs, w21.t silk, Cont)
  1298 + // is WeChat's uploadAttach step (confirmed by real-recording capture + tinker
  1299 + // decompile). w21.t has exactly one byte[] field (f443506a) = the SILK audio
  1300 + // about to be sent to CDN. When armed, we overwrite that byte[] with our TTS
  1301 + // SILK and the duration int (arg4). WeChat then uploads + delivers OUR audio,
  1302 + // reusing the entire real send pipeline we cannot rebuild.
  1303 + // Hook runs in the process where recording happens (main). Verified swap target,
  1304 + // but does its own field dump on every fire so a first real test confirms layout.
  1305 + private void hookVoiceSwap(ClassLoader cl, String procName) {
  1306 + try {
  1307 + Class<?> xClass = XposedHelpers.findClass("jg0.x", cl);
  1308 + int hooked = 0;
  1309 + for (java.lang.reflect.Method m : xClass.getDeclaredMethods()) {
  1310 + if (!"w".equals(m.getName())) continue; // hook EVERY 'w' overload
  1311 + m.setAccessible(true);
  1312 + XposedBridge.hookMethod(m, new XC_MethodHook() {
  1313 + @Override protected void beforeHookedMethod(MethodHookParam p) {
  1314 + // Absolute-first, arg-safe entry log so we KNOW the hook runs.
  1315 + int n = (p.args == null) ? 0 : p.args.length;
  1316 + XposedBridge.log("[WeChatHook] SWAPHOOK ENTER w nargs=" + n + " armed=" + sSwapArmed);
  1317 + try {
  1318 + // Real uploadAttach call: (jg0.x, qi3.d0, w21.w0, int, int, w21.t, Cont).
  1319 + // Coroutine resumptions re-call w with nulls — skip those.
  1320 + if (n != 7 || p.args[5] == null) return;
  1321 + Object tHolder = p.args[5]; // w21.t (SILK holder)
  1322 + java.lang.reflect.Field byteF = null;
  1323 + for (java.lang.reflect.Field f : tHolder.getClass().getDeclaredFields()) {
  1324 + if (f.getType() == byte[].class) { byteF = f; break; }
  1325 + }
  1326 + if (byteF == null) return;
  1327 + byteF.setAccessible(true);
  1328 + byte[] orig = (byte[]) byteF.get(tHolder);
  1329 + XposedBridge.log("[WeChatHook] SWAPHOOK real w: silk="
  1330 + + (orig == null ? "null" : orig.length + "B") + " durArg=" + p.args[4]
  1331 + + " holder=" + tHolder.getClass().getName());
  1332 + if (!sSwapArmed || sSwapSilk == null) return;
  1333 +
  1334 + byteF.set(tHolder, sSwapSilk);
  1335 + if (orig != null) {
  1336 + for (java.lang.reflect.Field f : tHolder.getClass().getDeclaredFields()) {
  1337 + if (f.getType() != int.class) continue;
  1338 + f.setAccessible(true);
  1339 + if (f.getInt(tHolder) == orig.length) f.setInt(tHolder, sSwapSilk.length);
  1340 + }
  1341 + }
  1342 + if (sSwapDuration > 0) p.args[4] = sSwapDuration;
  1343 + XposedBridge.log("[WeChatHook] VOICE SWAP DONE: "
  1344 + + (orig == null ? "?" : orig.length) + "B -> " + sSwapSilk.length
  1345 + + "B, dur -> " + p.args[4]);
  1346 + sSwapArmed = false; // one-shot
  1347 + sSwapSilk = null;
  1348 + } catch (Throwable t) {
  1349 + XposedBridge.log("[WeChatHook] VOICE SWAP failed: " + t
  1350 + + "\n" + android.util.Log.getStackTraceString(t));
  1351 + }
  1352 + }
  1353 + });
  1354 + hooked++;
  1355 + }
  1356 + XposedBridge.log("[WeChatHook] hookVoiceSwap: hooked jg0.x.w x" + hooked + " in " + procName);
  1357 + } catch (Throwable t) {
  1358 + XposedBridge.log("[WeChatHook] hookVoiceSwap failed in " + procName + ": " + t);
  1359 + }
  1360 + }
  1361 +
  1362 + // ── Full field dump across the whole class hierarchy (for RE capture) ────────
  1363 + private static void dumpFieldsDeep(Object o, String tag) {
  1364 + if (o == null) { XposedBridge.log("[WeChatHook] " + tag + " = null"); return; }
  1365 + try {
  1366 + StringBuilder sb = new StringBuilder("[WeChatHook] " + tag + " (" + o.getClass().getName() + "):");
  1367 + for (Class<?> c = o.getClass(); c != null && !c.equals(Object.class); c = c.getSuperclass()) {
  1368 + for (java.lang.reflect.Field f : c.getDeclaredFields()) {
  1369 + if (java.lang.reflect.Modifier.isStatic(f.getModifiers())) continue;
  1370 + f.setAccessible(true);
  1371 + Object v; try { v = f.get(o); } catch (Throwable t) { continue; }
  1372 + String vs = v == null ? "null"
  1373 + : (v instanceof byte[] ? "byte[" + ((byte[]) v).length + "]"
  1374 + : (v instanceof String || v instanceof Number || v instanceof Boolean ? v.toString()
  1375 + : v.getClass().getName() + "@" + System.identityHashCode(v)));
  1376 + if (vs.length() > 200) vs = vs.substring(0, 200) + "…";
  1377 + sb.append("\n ").append(f.getName()).append(" (").append(f.getType().getSimpleName()).append(") = ").append(vs);
  1378 + }
  1379 + }
  1380 + XposedBridge.log(sb.toString());
  1381 + } catch (Throwable t) { XposedBridge.log("[WeChatHook] dumpFieldsDeep err: " + t); }
  1382 + }
  1383 +
  1384 + // ── Trace the CDN upload submission for voice (the missing full-synthesis layer) ─
  1385 + // Real voice send: jg0.x.u builds a dn.m task (field_fileType=15, field_fullpath=
  1386 + // voice2 amr, field_mediaId="VideoData"+id, aesKey/fileId empty) and drives the CDN
  1387 + // engine (h2.d=addSendTask → l1.u → native CdnManager.startC2CUpload). The native
  1388 + // side ASSIGNS aeskey+fileId, returned in dn.h to l1.keep_onUploadSuccessed, then
  1389 + // jg0.x.u writes them back to the voiceinfo protobuf + newsendmsg. We OBSERVE only
  1390 + // (no modification) so a real recording still delivers, and we capture the exact
  1391 + // dn.m template + assigned aeskey/fileId to replicate CDN upload for synthetic voice.
  1392 + private void hookCdnTrace(ClassLoader cl, String procName) {
  1393 + // 1) h2.d(dn.m) = addSendTask — dump the full task struct on submit.
  1394 + try {
  1395 + Class<?> h2 = XposedHelpers.findClass("com.tencent.mm.modelcdntran.h2", cl);
  1396 + Class<?> dnm = XposedHelpers.findClass("dn.m", cl);
  1397 + XposedBridge.hookMethod(h2.getDeclaredMethod("d", dnm), new XC_MethodHook() {
  1398 + @Override protected void beforeHookedMethod(MethodHookParam p) {
  1399 + XposedBridge.log("[WeChatHook] CDNTRACE h2.d(addSendTask) ENTER");
  1400 + if (p.args != null && p.args.length > 0) dumpFieldsDeep(p.args[0], "CDNTRACE addSendTask dn.m");
  1401 + }
  1402 + @Override protected void afterHookedMethod(MethodHookParam p) {
  1403 + XposedBridge.log("[WeChatHook] CDNTRACE h2.d ret=" + p.getResult());
  1404 + }
  1405 + });
  1406 + XposedBridge.log("[WeChatHook] hookCdnTrace: hooked h2.d(addSendTask) in " + procName);
  1407 + } catch (Throwable t) { XposedBridge.log("[WeChatHook] hookCdnTrace h2.d failed in " + procName + ": " + t); }
  1408 +
  1409 + // 2) l1.keep_onUpload* — the native CDN callback carrying assigned aeskey/fileId (dn.h).
  1410 + try {
  1411 + Class<?> l1 = XposedHelpers.findClass("com.tencent.mm.modelcdntran.l1", cl);
  1412 + int n = 0;
  1413 + for (java.lang.reflect.Method m : l1.getDeclaredMethods()) {
  1414 + if (!m.getName().startsWith("keep_onUpload")) continue;
  1415 + m.setAccessible(true);
  1416 + final String mn = m.getName();
  1417 + XposedBridge.hookMethod(m, new XC_MethodHook() {
  1418 + @Override protected void afterHookedMethod(MethodHookParam p) {
  1419 + XposedBridge.log("[WeChatHook] CDNTRACE l1." + mn + " nargs=" + (p.args == null ? 0 : p.args.length));
  1420 + if (p.args != null) for (Object a : p.args) {
  1421 + if (a != null && a.getClass().getName().equals("dn.h")) dumpFieldsDeep(a, "CDNTRACE " + mn + " dn.h");
  1422 + }
  1423 + }
  1424 + });
  1425 + n++;
  1426 + }
  1427 + XposedBridge.log("[WeChatHook] hookCdnTrace: hooked l1.keep_onUpload* x" + n + " in " + procName);
  1428 + } catch (Throwable t) { XposedBridge.log("[WeChatHook] hookCdnTrace l1 failed in " + procName + ": " + t); }
  1429 +
  1430 + // 3) jg0.x.u — the orchestrator (builds dn.m, writes aeskey back). Log entry to
  1431 + // confirm it fires + timing vs the CDN calls.
  1432 + try {
  1433 + Class<?> x = XposedHelpers.findClass("jg0.x", cl);
  1434 + int n = 0;
  1435 + for (java.lang.reflect.Method m : x.getDeclaredMethods()) {
  1436 + if (!"u".equals(m.getName())) continue;
  1437 + m.setAccessible(true);
  1438 + XposedBridge.hookMethod(m, new XC_MethodHook() {
  1439 + @Override protected void beforeHookedMethod(MethodHookParam p) {
  1440 + XposedBridge.log("[WeChatHook] CDNTRACE jg0.x.u ENTER nargs=" + (p.args == null ? 0 : p.args.length));
  1441 + if (p.args != null && p.args.length > 1 && p.args[1] != null)
  1442 + dumpFieldsDeep(p.args[1], "CDNTRACE jg0.x.u w21.w0");
  1443 + }
  1444 + });
  1445 + n++;
  1446 + }
  1447 + XposedBridge.log("[WeChatHook] hookCdnTrace: hooked jg0.x.u x" + n + " in " + procName);
  1448 + } catch (Throwable t) { XposedBridge.log("[WeChatHook] hookCdnTrace jg0.x.u failed in " + procName + ": " + t); }
  1449 + }
  1450 +
  1451 + // ── Capture the real uploadvoice cgi request (this device's actual voice path) ──
  1452 + // This device uses the INLINE-cgi branch of jg0.x.w (not CDN): it builds a
  1453 + // com.tencent.mm.modelbase.l reqresp with url /cgi-bin/micromsg-bin/uploadvoice,
  1454 + // request pb r45.cv6 carrying the SILK inline in field 7. The scene
  1455 + // (modelbase.i.f70699d, a NetScene = m1 subclass) can be submitted via z2.b — the
  1456 + // SAME queue our text send uses. Hook modelbase.l.a() (the reqresp builder, fires
  1457 + // mid-jg0.x.w) filtered to the uploadvoice url, and dump every cv6 field index so
  1458 + // we can replicate the exact wire request for fully-synthetic voice.
  1459 + // Diagnostic: hook modelbase.i.k(errType,errCode,errMsg,respPb,scene) = scene-end
  1460 + // callback. Logs the result of any uploadvoice send (resp pb = r45.dv6), so we can
  1461 + // tell if our synthetic z2.b send was dispatched + accepted (errCode 0) or rejected.
  1462 + private void hookVoiceCgiResult(ClassLoader cl, String procName) {
  1463 + try {
  1464 + Class<?> iCls = XposedHelpers.findClass("com.tencent.mm.modelbase.i", cl);
  1465 + Class<?> pbCls = XposedHelpers.findClass("com.tencent.mm.protobuf.f", cl);
  1466 + Class<?> m1Cls = XposedHelpers.findClass("com.tencent.mm.modelbase.m1", cl);
  1467 + int n = 0;
  1468 + for (java.lang.reflect.Method m : iCls.getDeclaredMethods()) {
  1469 + Class<?>[] pt = m.getParameterTypes();
  1470 + // onSceneEnd: (int, int, String, protobuf.f, m1)
  1471 + if (pt.length == 5 && pt[0] == int.class && pt[1] == int.class && pt[2] == String.class
  1472 + && pbCls.isAssignableFrom(pt[3]) && m1Cls.isAssignableFrom(pt[4])) {
  1473 + m.setAccessible(true);
  1474 + XposedBridge.hookMethod(m, new XC_MethodHook() {
  1475 + @Override protected void beforeHookedMethod(MethodHookParam p) {
  1476 + try {
  1477 + Object resp = p.args[3];
  1478 + if (resp == null || !resp.getClass().getName().equals("r45.dv6")) return;
  1479 + long svr = 0; try { Object v = XposedHelpers.callMethod(resp, "getLong", 11); if (v != null) svr = (Long) v; } catch (Throwable t) {}
  1480 + XposedBridge.log("[WeChatHook] VOICECGI-RESULT errType=" + p.args[0]
  1481 + + " errCode=" + p.args[1] + " errMsg=" + p.args[2]
  1482 + + " respClass=" + resp.getClass().getName() + " svrMsgId(11)=" + svr);
  1483 + } catch (Throwable t) { XposedBridge.log("[WeChatHook] VOICECGI-RESULT err: " + t); }
  1484 + }
  1485 + });
  1486 + n++;
  1487 + }
  1488 + }
  1489 + XposedBridge.log("[WeChatHook] hookVoiceCgiResult: hooked i.onSceneEnd x" + n + " in " + procName);
  1490 + } catch (Throwable t) { XposedBridge.log("[WeChatHook] hookVoiceCgiResult failed in " + procName + ": " + t); }
  1491 + }
  1492 +
  1493 + private void hookVoiceCgiCapture(ClassLoader cl, String procName) {
  1494 + try {
  1495 + Class<?> lCls = XposedHelpers.findClass("com.tencent.mm.modelbase.l", cl);
  1496 + final Class<?> pbCls = XposedHelpers.findClass("com.tencent.mm.protobuf.f", cl);
  1497 + XposedBridge.hookMethod(lCls.getDeclaredMethod("a"), new XC_MethodHook() {
  1498 + @Override protected void beforeHookedMethod(MethodHookParam p) {
  1499 + try {
  1500 + // Field names differ base-vs-tinker, so locate by TYPE: the url String
  1501 + // (contains cgi-bin) + the request/response protobufs (protobuf.f).
  1502 + Object self = p.thisObject;
  1503 + String url = null;
  1504 + java.util.List<Object> pbs = new java.util.ArrayList<>();
  1505 + for (Class<?> c = self.getClass(); c != null && !c.equals(Object.class); c = c.getSuperclass()) {
  1506 + for (java.lang.reflect.Field f : c.getDeclaredFields()) {
  1507 + if (java.lang.reflect.Modifier.isStatic(f.getModifiers())) continue;
  1508 + f.setAccessible(true);
  1509 + Object v; try { v = f.get(self); } catch (Throwable t) { continue; }
  1510 + if (v instanceof String && ((String) v).contains("cgi-bin")) url = (String) v;
  1511 + else if (v != null && pbCls.isInstance(v)) pbs.add(v);
  1512 + }
  1513 + }
  1514 + if (url == null || !url.contains("uploadvoice")) return; // gate: voice cgi only
  1515 + StringBuilder sb = new StringBuilder("[WeChatHook] VOICECGI url=" + url + " pbCount=" + pbs.size());
  1516 + int idx = 0;
  1517 + for (Object req : pbs) {
  1518 + sb.append("\n -- pb#").append(idx++).append(" ").append(req.getClass().getName()).append(" --");
  1519 + for (int i = 0; i <= 25; i++) {
  1520 + Object val = null; String kind = "";
  1521 + try { Object c = XposedHelpers.callMethod(req, "getCustom", i);
  1522 + if (c != null) { val = "custom:" + c.getClass().getName(); kind = "C"; } } catch (Throwable t) {}
  1523 + if (val == null) { try { Object s = XposedHelpers.callMethod(req, "getString", i); if (s != null) { val = s; kind = "S"; } } catch (Throwable t) {} }
  1524 + if (val == null) { try { Object iv = XposedHelpers.callMethod(req, "getInteger", i); if (iv != null && ((Integer) iv) != 0) { val = iv; kind = "I"; } } catch (Throwable t) {} }
  1525 + if (val == null) { try { Object lv = XposedHelpers.callMethod(req, "getLong", i); if (lv != null && ((Long) lv) != 0L) { val = lv; kind = "L"; } } catch (Throwable t) {} }
  1526 + if (val != null) {
  1527 + String vs = String.valueOf(val);
  1528 + if (vs.length() > 140) vs = vs.substring(0, 140) + "…";
  1529 + sb.append("\n [").append(i).append("](").append(kind).append(")=").append(vs);
  1530 + }
  1531 + }
  1532 + }
  1533 + XposedBridge.log(sb.toString());
  1534 + } catch (Throwable t) { XposedBridge.log("[WeChatHook] VOICECGI err: " + t); }
  1535 + }
  1536 + });
  1537 + XposedBridge.log("[WeChatHook] hookVoiceCgiCapture: hooked modelbase.l.a() in " + procName);
  1538 + } catch (Throwable t) { XposedBridge.log("[WeChatHook] hookVoiceCgiCapture failed in " + procName + ": " + t); }
  1539 + }
  1540 +
  1541 + private void hookVoiceUpload(ClassLoader cl, String procName) {
  1542 + try {
  1543 + Class<?> g1 = XposedHelpers.findClass("w21.g1", cl);
  1544 + int mh = 0;
  1545 + for (java.lang.reflect.Method m : g1.getDeclaredMethods()) {
  1546 + final String mName = m.getName();
  1547 + // L0(w0)=insert, P0(file,w0)=upload, D0/J0/y0/z0=lookups. Dump w0 on all.
  1548 + if (!("L0".equals(mName) || "P0".equals(mName))) continue;
  1549 + m.setAccessible(true);
  1550 + XposedBridge.hookMethod(m, new XC_MethodHook() {
  1551 + @Override protected void beforeHookedMethod(MethodHookParam p) {
  1552 + try {
  1553 + // find the w0 arg (w21.w0) among args
  1554 + Object w0 = null;
  1555 + if (p.args != null) for (Object a : p.args)
  1556 + if (a != null && a.getClass().getName().equals("w21.w0")) { w0 = a; break; }
  1557 + StringBuilder sb = new StringBuilder("[WeChatHook] g1." + mName
  1558 + + " by=" + (sCalledByUs ? "US" : "REAL") + " args=[");
  1559 + if (p.args != null) for (int i = 0; i < p.args.length; i++) {
  1560 + Object a = p.args[i];
  1561 + sb.append(i > 0 ? ", " : "").append(a == null ? "null"
  1562 + : (a instanceof String ? "\"" + a + "\"" : a.getClass().getSimpleName()));
  1563 + }
  1564 + sb.append("]");
  1565 + if (w0 != null) {
  1566 + sb.append("\n w21.w0 DUMP:");
  1567 + for (java.lang.reflect.Field f : w0.getClass().getDeclaredFields()) {
  1568 + if (java.lang.reflect.Modifier.isStatic(f.getModifiers())) continue;
  1569 + f.setAccessible(true);
  1570 + Object v = f.get(w0);
  1571 + String vs = v == null ? "null"
  1572 + : (v instanceof byte[] ? "byte[" + ((byte[]) v).length + "]"
  1573 + : (v instanceof String || v instanceof Number || v instanceof Boolean ? v.toString()
  1574 + : v.getClass().getSimpleName()));
  1575 + sb.append("\n ").append(f.getName()).append("=").append(vs);
  1576 + }
  1577 + }
  1578 + XposedBridge.log(sb.toString());
  1579 + } catch (Throwable ignored) {}
  1580 + }
  1581 + });
  1582 + mh++;
  1583 + }
  1584 + XposedBridge.log("[WeChatHook] hookVoiceUpload: hooked " + mh + " g1 method(s) in " + procName);
  1585 + } catch (Throwable t) {
  1586 + XposedBridge.log("[WeChatHook] hookVoiceUpload failed in " + procName + ": " + t);
  1587 + }
  1588 + }
  1589 +
  1590 + // ── Image send: hook b80.u.pj/Bi (the real non-suspend send entry) ───────────
  1591 + // b80.u (implements o70.e, = n0.c(o70.e.class)) is the image plugin. The send
  1592 + // coroutine b80.s calls b80.u.Bi(o70.h,String) then b80.u.pj(o70.h). We hook both
  1593 + // to (1) capture the live b80.u instance and (2) on a REAL image send, dump the
  1594 + // full o70.h (PreBuildParams) field-by-field — that's the exact recipe to replicate.
  1595 + private static void dumpO70h(Object h, String tag) {
  1596 + try {
  1597 + StringBuilder sb = new StringBuilder("[WeChatHook] " + tag + " o70.h DUMP:");
  1598 + for (java.lang.reflect.Field f : h.getClass().getDeclaredFields()) {
  1599 + if (java.lang.reflect.Modifier.isStatic(f.getModifiers())) continue;
  1600 + f.setAccessible(true);
  1601 + Object v = f.get(h);
  1602 + String vs = v == null ? "null"
  1603 + : (v instanceof byte[] ? "byte[" + ((byte[]) v).length + "]"
  1604 + : (v instanceof String || v instanceof Number || v instanceof Boolean || v instanceof android.net.Uri
  1605 + ? v.toString() : v.getClass().getName() + "@" + System.identityHashCode(v)));
  1606 + sb.append("\n ").append(f.getName()).append(" (").append(f.getType().getSimpleName())
  1607 + .append(") = ").append(vs);
  1608 + }
  1609 + XposedBridge.log(sb.toString());
  1610 + } catch (Throwable t) { XposedBridge.log("[WeChatHook] dumpO70h err: " + t); }
  1611 + }
  1612 +
  1613 + // Hook SendImgProxyUI.onCreate → dump the launch Intent extras. Real gallery image
  1614 + // sends run through this proxy Activity ($$a.run → b80.s coroutine → send). Capturing
  1615 + // its Intent lets us replay the WHOLE real flow via `am start` with the same extras.
  1616 + private void hookSendImgProxyUI(ClassLoader cl, String procName) {
  1617 + try {
  1618 + XposedHelpers.findAndHookMethod(
  1619 + "com.tencent.mm.ui.chatting.SendImgProxyUI", cl, "onCreate",
  1620 + android.os.Bundle.class, new XC_MethodHook() {
  1621 + @Override protected void afterHookedMethod(MethodHookParam p) {
  1622 + try {
  1623 + android.content.Intent it = (android.content.Intent)
  1624 + XposedHelpers.callMethod(p.thisObject, "getIntent");
  1625 + if (it == null) { XposedBridge.log("[WeChatHook] SendImgProxyUI: intent null"); return; }
  1626 + android.os.Bundle ex = it.getExtras();
  1627 + StringBuilder sb = new StringBuilder("[WeChatHook] SendImgProxyUI INTENT:");
  1628 + sb.append("\n action=").append(it.getAction());
  1629 + sb.append("\n data=").append(it.getDataString());
  1630 + if (ex != null) for (String key : ex.keySet()) {
  1631 + Object v = ex.get(key);
  1632 + String vs = v == null ? "null"
  1633 + : (v instanceof java.util.ArrayList ? "ArrayList" + v
  1634 + : (v.getClass().isArray() ? v.getClass().getSimpleName() + java.util.Arrays.deepToString(new Object[]{v})
  1635 + : v.toString()));
  1636 + if (vs.length() > 300) vs = vs.substring(0, 300) + "…";
  1637 + sb.append("\n [").append(key).append("] (")
  1638 + .append(v == null ? "?" : v.getClass().getName()).append(") = ").append(vs);
  1639 + }
  1640 + XposedBridge.log(sb.toString());
  1641 + } catch (Throwable t) { XposedBridge.log("[WeChatHook] SendImgProxyUI dump err: " + t); }
  1642 + }
  1643 + });
  1644 + XposedBridge.log("[WeChatHook] hookSendImgProxyUI OK in " + procName);
  1645 + } catch (Throwable t) {
  1646 + XposedBridge.log("[WeChatHook] hookSendImgProxyUI failed in " + procName + ": " + t);
  1647 + }
  1648 + }
  1649 +
  1650 + private void hookImageSend(ClassLoader cl, String procName) {
  1651 + try {
  1652 + Class<?> u = XposedHelpers.findClass("b80.u", cl);
  1653 + int n = 0;
  1654 + for (java.lang.reflect.Method m : u.getDeclaredMethods()) {
  1655 + final String mn = m.getName();
  1656 + if (!("pj".equals(mn) || "Bi".equals(mn) || "oj".equals(mn))) continue;
  1657 + Class<?>[] pts = m.getParameterTypes();
  1658 + if (pts.length < 1) continue;
  1659 + final boolean isOj = "oj".equals(mn); // oj(o70.k) = the insert/send step
  1660 + if (!isOj && !pts[0].getName().equals("o70.h")) continue;
  1661 + m.setAccessible(true);
  1662 + XposedBridge.hookMethod(m, new XC_MethodHook() {
  1663 + @Override protected void beforeHookedMethod(MethodHookParam p) {
  1664 + if (sImgPlugin == null && p.thisObject != null) {
  1665 + sImgPlugin = p.thisObject;
  1666 + XposedBridge.log("[WeChatHook] hookImageSend: captured b80.u=" + p.thisObject);
  1667 + }
  1668 + if (!sCalledByUs && p.args != null && p.args.length > 0 && p.args[0] != null) {
  1669 + if (isOj) {
  1670 + // o70.k — the insert object. Dump its full field tree.
  1671 + Object k = p.args[0];
  1672 + sRealImgK = k;
  1673 + XposedBridge.log("[WeChatHook] b80.u.oj REAL o70.k class=" + k.getClass().getName());
  1674 + dumpO70h(k, "b80.u.oj REAL o70.k");
  1675 + } else {
  1676 + sRealImgParams = p.args[0];
  1677 + dumpO70h(p.args[0], "b80.u." + mn + " REAL");
  1678 + }
  1679 + }
  1680 + }
  1681 + });
  1682 + n++;
  1683 + }
  1684 + XposedBridge.log("[WeChatHook] hookImageSend: hooked " + n + " b80.u method(s) in " + procName);
  1685 + } catch (Throwable t) {
  1686 + XposedBridge.log("[WeChatHook] hookImageSend failed in " + procName + ": " + t);
  1687 + }
  1688 + }
  1689 +
  1690 + // ── Voice send via internal API ────────────────────────────────────────────
  1691 + // Protocol (confirmed by hooking f9.convertTo() on real user send):
  1692 + // • content XML: <msg><voicemsg voicelength="{ms}" fromusername="{wxid}" isPlayed="false"></voicemsg></msg>
  1693 + // • imgPath : 26-char hex voice file ID (f9 field, determines file location)
  1694 + // • voice2 dir : voice2/md5(voiceId)[0:2]/md5(voiceId)[2:4]/msg_{voiceId}.amr (confirmed formula)
  1695 + //
  1696 + // Two modes (mutually exclusive extras):
  1697 + // (a) voice_id — caller pre-placed the SILK file in voice2 already (no file I/O here)
  1698 + // (b) src_path — WeChat-readable path (e.g. /data/data/com.tencent.mm/cache/…);
  1699 + // hook generates voice_id, copies src_path → voice2/{dir}/msg_{id}.amr internally
  1700 + // (WeChat process has full access to its own data dir, unlike root which is SELinux-blocked)
  1701 + //
  1702 + // Typical flow for TTS voice:
  1703 + // root: cp tts.amr /data/data/com.tencent.mm/cache/hook_voice_src.amr && chown u0_a330 ...
  1704 + // broadcast: --es to filehelper --es src_path /data/data/com.tencent.mm/cache/hook_voice_src.amr --ei duration 3000
  1705 + // ── Fully-synthetic voice via the uploadvoice cgi (this device's real path) ──
  1706 + // Captured from a real send (VOICECGI): voice audio uploads INLINE via
  1707 + // /cgi-bin/micromsg-bin/uploadvoice (cmdid 127, req pb r45.cv6), NOT the CDN engine.
  1708 + // The scene (modelbase.g extends m1) submits via z2.b — same queue as our text send.
  1709 + // SILK is chunked at 6000 bytes; each chunk is one cgi with the slice in field 7.
  1710 + // cv6 fields (from capture): 0=self 1=talker 2=netOffset 3=chunkLen
  1711 + // 4="newSendVoice_"+voiceId 6=durMs 7=cu5(silk slice) 8=endFlag 11=msgsource
  1712 + // 12=4 15=long(createId). Last chunk (8=1) response dv6.getLong(11)>0 = delivered.
  1713 + // Builds modelbase.o via its 13-arg constructor (signature-stable) to sidestep the
  1714 + // base-vs-tinker field-name mismatch on modelbase.l.
  1715 + private static void sendVoiceViaCgi(String talker, String srcPath, int durationMs, String fromWxId) throws Throwable {
  1716 + ClassLoader cl = sTinkerCL != null ? sTinkerCL : sWeChatCL;
  1717 + if (cl == null) throw new IllegalStateException("classloader null");
  1718 + if (srcPath == null || srcPath.isEmpty()) throw new IllegalArgumentException("need src_path (SILK)");
  1719 +
  1720 + byte[] silk;
  1721 + try (java.io.FileInputStream in = new java.io.FileInputStream(srcPath)) {
  1722 + java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
  1723 + byte[] buf = new byte[8192]; int n;
  1724 + while ((n = in.read(buf)) != -1) bos.write(buf, 0, n);
  1725 + silk = bos.toByteArray();
  1726 + }
  1727 + if (silk.length == 0) throw new IllegalStateException("empty SILK file: " + srcPath);
  1728 +
  1729 + // voiceId (26 hex) + clientmsgid link the chunks to one message.
  1730 + byte[] idBytes = new byte[13];
  1731 + new java.util.Random().nextBytes(idBytes);
  1732 + StringBuilder vsb = new StringBuilder(26);
  1733 + for (byte b : idBytes) vsb.append(String.format("%02x", b & 0xff));
  1734 + String voiceId = vsb.toString();
  1735 + String clientMsgId = "newSendVoice_" + voiceId;
  1736 + String self = (fromWxId != null && !fromWxId.isEmpty()) ? fromWxId
  1737 + : (sMyWxid != null ? sMyWxid : "wxid_51ap3m6p9xs722");
  1738 +
  1739 + Class<?> cv6C = XposedHelpers.findClass("r45.cv6", cl);
  1740 + Class<?> dv6C = XposedHelpers.findClass("r45.dv6", cl);
  1741 + Class<?> cu5C = XposedHelpers.findClass("r45.cu5", cl);
  1742 + Class<?> oCls = XposedHelpers.findClass("com.tencent.mm.modelbase.o", cl);
  1743 + Class<?> iCls = XposedHelpers.findClass("com.tencent.mm.modelbase.i", cl);
  1744 + Class<?> m1Cls = XposedHelpers.findClass("com.tencent.mm.modelbase.m1", cl);
  1745 + Class<?> pq5g = XposedHelpers.findClass("pq5.g", cl);
  1746 + Class<?> km5d = XposedHelpers.findClass("km5.d", cl);
  1747 + // i.l() (no-arg → pq5.g) registers the response consumer + returns the deferred;
  1748 + // pq5.g.l(long) (long → km5.d) is the terminal subscribe that fires the cgi.
  1749 + java.lang.reflect.Method runM = null;
  1750 + for (java.lang.reflect.Method m : iCls.getDeclaredMethods())
  1751 + if (m.getParameterCount() == 0 && m.getReturnType() == pq5g) { runM = m; runM.setAccessible(true); break; }
  1752 + java.lang.reflect.Method subM = null;
  1753 + for (java.lang.reflect.Method m : pq5g.getDeclaredMethods()) {
  1754 + Class<?>[] pt = m.getParameterTypes();
  1755 + if (pt.length == 1 && pt[0] == long.class && m.getReturnType() == km5d) { subM = m; subM.setAccessible(true); break; }
  1756 + }
  1757 + if (runM == null || subM == null) throw new IllegalStateException("i.l()/pq5.g.l(long) not found: run=" + runM + " sub=" + subM);
  1758 +
  1759 + // modelbase.o(req, resp, url, cmdid, 0, 0, true, 0, 0, false, 0, false, null) — find by arg count.
  1760 + java.lang.reflect.Constructor<?> oCtor = null;
  1761 + for (java.lang.reflect.Constructor<?> c : oCls.getDeclaredConstructors())
  1762 + if (c.getParameterTypes().length == 13) { oCtor = c; break; }
  1763 + if (oCtor == null) throw new IllegalStateException("modelbase.o 13-arg ctor not found");
  1764 + oCtor.setAccessible(true);
  1765 + // modelbase.i.p(o) — locate by signature (one param assignable from modelbase.o).
  1766 + java.lang.reflect.Method pM = null;
  1767 + for (java.lang.reflect.Method m : iCls.getDeclaredMethods()) {
  1768 + Class<?>[] pt = m.getParameterTypes();
  1769 + if (m.getReturnType() == void.class && pt.length == 1 && pt[0].isAssignableFrom(oCls)) { pM = m; break; }
  1770 + }
  1771 + if (pM == null) throw new IllegalStateException("modelbase.i.p(o) not found");
  1772 + pM.setAccessible(true);
  1773 + // i's scene field (type modelbase.g / m1 subclass).
  1774 + java.lang.reflect.Field sceneF = null;
  1775 + for (java.lang.reflect.Field f : iCls.getDeclaredFields()) {
  1776 + if (java.lang.reflect.Modifier.isStatic(f.getModifiers())) continue;
  1777 + if (m1Cls.isAssignableFrom(f.getType())) { sceneF = f; sceneF.setAccessible(true); break; }
  1778 + }
  1779 + if (sceneF == null) throw new IllegalStateException("modelbase.i scene field not found");
  1780 +
  1781 + final String URL = "/cgi-bin/micromsg-bin/uploadvoice";
  1782 + final int CHUNK = 6000;
  1783 + int total = silk.length, chunks = 0;
  1784 + Object lastDv6 = null;
  1785 + sCalledByUs = true;
  1786 + try {
  1787 + for (int off = 0; off < total; off += CHUNK) {
  1788 + int len = Math.min(CHUNK, total - off);
  1789 + boolean last = (off + len >= total);
  1790 + byte[] slice = java.util.Arrays.copyOfRange(silk, off, off + len);
  1791 +
  1792 + Object cv6 = XposedHelpers.newInstance(cv6C);
  1793 + XposedHelpers.callMethod(cv6, "set", 0, self);
  1794 + XposedHelpers.callMethod(cv6, "set", 1, talker);
  1795 + XposedHelpers.callMethod(cv6, "set", 2, Integer.valueOf(off));
  1796 + XposedHelpers.callMethod(cv6, "set", 3, Integer.valueOf(len));
  1797 + XposedHelpers.callMethod(cv6, "set", 4, clientMsgId);
  1798 + XposedHelpers.callMethod(cv6, "set", 6, Integer.valueOf(durationMs));
  1799 + Object cu5 = XposedHelpers.newInstance(cu5C);
  1800 + XposedHelpers.callMethod(cu5, "e", slice, 0, len); // cu5.e(byte[],off,len)
  1801 + XposedHelpers.callMethod(cv6, "set", 7, cu5);
  1802 + XposedHelpers.callMethod(cv6, "set", 8, Integer.valueOf(last ? 1 : 0));
  1803 + XposedHelpers.callMethod(cv6, "set", 11, ""); // msgsource (empty for filehelper)
  1804 + XposedHelpers.callMethod(cv6, "set", 12, Integer.valueOf(4));
  1805 + // [15] = per-message create id (long). Real sends carry it; derive a
  1806 + // large positive nonce from the voiceId so the server has a stable value.
  1807 + long createId = (System.currentTimeMillis() << 20) ^ (voiceId.hashCode() & 0xffffffffL);
  1808 + if (createId < 0) createId = -createId;
  1809 + XposedHelpers.callMethod(cv6, "set", 15, Long.valueOf(createId));
  1810 +
  1811 + Object dv6 = XposedHelpers.newInstance(dv6C);
  1812 + lastDv6 = dv6;
  1813 + Object o = oCtor.newInstance(cv6, dv6, URL, 127, 0, 0, Boolean.TRUE, 0, 0, Boolean.FALSE, 0, Boolean.FALSE, null);
  1814 + Object iInst = XposedHelpers.newInstance(iCls);
  1815 + pM.invoke(iInst, o);
  1816 + Object scene = sceneF.get(iInst);
  1817 + // Dispatch: i.l() registers the response consumer + returns the deferred,
  1818 + // then pq5.g.l(timeout) subscribes → the cgi actually runs. Bare z2.b(g)
  1819 + // doesn't wire the callback, so the scene never completes.
  1820 + Object deferred = runM.invoke(iInst);
  1821 + sVoiceCgiKeepAlive.add(iInst); // deferred holds i weakly
  1822 + if (deferred != null) { sVoiceCgiKeepAlive.add(deferred); subM.invoke(deferred, 30000L); }
  1823 + chunks++;
  1824 + XposedBridge.log("[WeChatHook] sendVoiceViaCgi: chunk off=" + off + " len=" + len
  1825 + + " last=" + last + " scene=" + (scene == null ? "null" : scene.getClass().getName())
  1826 + + " deferred=" + (deferred == null ? "null" : deferred.getClass().getName()));
  1827 + }
  1828 + } finally { sCalledByUs = false; }
  1829 + XposedBridge.log("[WeChatHook] sendVoiceViaCgi: submitted " + chunks + " chunk(s) to=" + talker
  1830 + + " voiceId=" + voiceId + " silk=" + total + "B dur=" + durationMs + " self=" + self);
  1831 +
  1832 + // Read the server response off the SAME dv6 we passed (WeChat parses the cgi
  1833 + // reply into it). getLong(11) = assigned server msgId; >0 means the server
  1834 + // accepted the voice = delivered. Poll a few times since z2.b is async.
  1835 + final Object fDv6 = lastDv6;
  1836 + final String fVoice = voiceId;
  1837 + if (fDv6 != null) {
  1838 + final Handler h = new Handler(Looper.getMainLooper());
  1839 + final int[] tries = {0};
  1840 + Runnable poll = new Runnable() {
  1841 + @Override public void run() {
  1842 + tries[0]++;
  1843 + try {
  1844 + long svrMsgId = 0; try { Object v = XposedHelpers.callMethod(fDv6, "getLong", 11); if (v != null) svrMsgId = (Long) v; } catch (Throwable t) {}
  1845 + int netOff = 0; try { Object v = XposedHelpers.callMethod(fDv6, "getInteger", 2); if (v != null) netOff = (Integer) v; } catch (Throwable t) {}
  1846 + if (svrMsgId != 0 || netOff != 0 || tries[0] >= 6) {
  1847 + StringBuilder sb = new StringBuilder("[WeChatHook] sendVoiceViaCgi RESP try=" + tries[0]
  1848 + + " voiceId=" + fVoice + " svrMsgId(11)=" + svrMsgId + " netOffset(2)=" + netOff + " dv6:");
  1849 + for (int i = 0; i <= 15; i++) {
  1850 + Object val = null;
  1851 + try { Object s = XposedHelpers.callMethod(fDv6, "getString", i); if (s != null && !"".equals(s)) val = "S:" + s; } catch (Throwable t) {}
  1852 + if (val == null) { try { Object iv = XposedHelpers.callMethod(fDv6, "getInteger", i); if (iv != null && ((Integer) iv) != 0) val = "I:" + iv; } catch (Throwable t) {} }
  1853 + if (val == null) { try { Object lv = XposedHelpers.callMethod(fDv6, "getLong", i); if (lv != null && ((Long) lv) != 0L) val = "L:" + lv; } catch (Throwable t) {} }
  1854 + if (val != null) sb.append("\n [").append(i).append("]=").append(val);
  1855 + }
  1856 + XposedBridge.log(sb.toString());
  1857 + } else {
  1858 + h.postDelayed(this, 1500);
  1859 + }
  1860 + } catch (Throwable t) { XposedBridge.log("[WeChatHook] sendVoiceViaCgi RESP err: " + t); }
  1861 + }
  1862 + };
  1863 + h.postDelayed(poll, 1500);
  1864 + }
  1865 + }
  1866 +
  1867 + private static void sendVoiceViaAPI(String talker, String voiceId, String srcPath,
  1868 + int durationMs, String fromWxId) throws Throwable {
  1869 + ClassLoader cl = sTinkerCL != null ? sTinkerCL : sWeChatCL;
  1870 + if (cl == null) throw new IllegalStateException("classloader null");
  1871 +
  1872 + // ── File placement ───────────────────────────────────────────────────
  1873 + if (voiceId == null || voiceId.isEmpty()) {
  1874 + // Mode (b): generate voice_id and copy SILK from srcPath
  1875 + if (srcPath == null || srcPath.isEmpty())
  1876 + throw new IllegalArgumentException("need either voice_id or src_path");
  1877 + byte[] idBytes = new byte[13];
  1878 + new java.util.Random().nextBytes(idBytes);
  1879 + StringBuilder sb = new StringBuilder(26);
  1880 + for (byte b : idBytes) sb.append(String.format("%02x", b & 0xff));
  1881 + voiceId = sb.toString();
  1882 +
  1883 + java.security.MessageDigest md5 = java.security.MessageDigest.getInstance("MD5");
  1884 + byte[] mdBytes = md5.digest(voiceId.getBytes("UTF-8"));
  1885 + String dir1 = String.format("%02x", mdBytes[0] & 0xff);
  1886 + String dir2 = String.format("%02x", mdBytes[1] & 0xff);
  1887 +
  1888 + String mmDir = "/data/data/com.tencent.mm/MicroMsg/653cdc2320abb089e149a3f7a7683fcf";
  1889 + String destDir = mmDir + "/voice2/" + dir1 + "/" + dir2;
  1890 + String destPath = destDir + "/msg_" + voiceId + ".amr";
  1891 + new java.io.File(destDir).mkdirs();
  1892 + try (java.io.FileInputStream in = new java.io.FileInputStream(srcPath);
  1893 + java.io.FileOutputStream out = new java.io.FileOutputStream(destPath)) {
  1894 + byte[] buf = new byte[8192]; int n;
  1895 + while ((n = in.read(buf)) != -1) out.write(buf, 0, n);
  1896 + }
  1897 + new java.io.File(destPath).setReadable(true, false);
  1898 + XposedBridge.log("[WeChatHook] sendVoiceViaAPI: " + srcPath + " -> " + destPath);
  1899 + } else if (voiceId.length() != 26) {
  1900 + throw new IllegalArgumentException("voice_id must be 26 hex chars, got: " + voiceId);
  1901 + }
  1902 +
  1903 + // ── Build voice XML ──────────────────────────────────────────────────
  1904 + // fromusername is the sender's wxid. sMyWxid is auto-discovered from the first
  1905 + // real UI voice send; fall back to the known wxid for this device.
  1906 + String safeFrom = (fromWxId != null && !fromWxId.isEmpty())
  1907 + ? fromWxId
  1908 + : (sMyWxid != null ? sMyWxid : "wxid_51ap3m6p9xs722");
  1909 + String voiceXml = "<msg><voicemsg voicelength=\"" + durationMs
  1910 + + "\" fromusername=\"" + safeFrom + "\" isPlayed=\"false\"></voicemsg></msg>";
  1911 +
  1912 + // ── Probe f9 setter map BEFORE setting sPendingVoiceId ───────────────
  1913 + Class<?> f9Class = XposedHelpers.findClass("com.tencent.mm.storage.f9", cl);
  1914 + if (sF9SetterMap == null) sF9SetterMap = probeAllF9Setters(f9Class);
  1915 + if (!sF9SetterMap.containsKey("imgPath"))
  1916 + throw new IllegalStateException("imgPath setter not found in map: " + sF9SetterMap);
  1917 +
  1918 + // ── Synthetic lvbuffer (waveform visualization, NOT the SILK audio) ────
  1919 + // Real WeChat always stores exactly 74 bytes regardless of duration:
  1920 + // 4-byte header (0x7b 0x00 0x00 0x00) + 70 zero bytes. The size is fixed.
  1921 + byte[] syntheticLv = new byte[74];
  1922 + syntheticLv[0] = 0x7b;
  1923 + // bytes 1..73 default to 0x00
  1924 + XposedBridge.log("[WeChatHook] sendVoiceViaAPI: synthetic lvbuffer 74 bytes for " + durationMs + "ms");
  1925 +
  1926 + // ── Create r0: try Object-param ctor first (real WeChat voice path) ─────
  1927 + // WeChat has two 5-param r0 ctors:
  1928 + // (String, String, int, int, long) — timestamp variant
  1929 + // (String, String, int, int, Object) — audio-path variant (used by real voice sends)
  1930 + // The Object ctor stores the audio file reference that H() reads for CDN upload.
  1931 + // If it works, r0 sets imgPath internally and H() can find the SILK for upload.
  1932 + // Fall back to long ctor if the Object ctor throws.
  1933 + Class<?> r0Class = XposedHelpers.findClass("w11.r0", cl);
  1934 + sPendingVoiceId.set(voiceId);
  1935 + sPendingLvBuffer.set(syntheticLv);
  1936 + sCalledByUs = true;
  1937 + Object r0;
  1938 + try {
  1939 + try {
  1940 + // Pass the voice2 path (where we placed the SILK) as the Object arg.
  1941 + // Real WeChat passes the temp recording file; we pass our already-placed file.
  1942 + String voiceFilePath = srcPath != null ? srcPath
  1943 + : "/data/data/com.tencent.mm/MicroMsg/653cdc2320abb089e149a3f7a7683fcf/voice2/"
  1944 + + String.format("%02x", java.security.MessageDigest.getInstance("MD5")
  1945 + .digest(voiceId.getBytes("UTF-8"))[0] & 0xff)
  1946 + + "/" + String.format("%02x", java.security.MessageDigest.getInstance("MD5")
  1947 + .digest(voiceId.getBytes("UTF-8"))[1] & 0xff)
  1948 + + "/msg_" + voiceId + ".amr";
  1949 + r0 = XposedHelpers.newInstance(r0Class,
  1950 + new Class<?>[]{String.class, String.class, int.class, int.class, Object.class},
  1951 + talker, voiceXml, 34, 0, voiceFilePath);
  1952 + XposedBridge.log("[WeChatHook] sendVoiceViaAPI: used Object-ctor with path=" + voiceFilePath);
  1953 + } catch (Throwable e1) {
  1954 + XposedBridge.log("[WeChatHook] sendVoiceViaAPI: Object-ctor failed (" + e1 + "), falling back to long-ctor");
  1955 + long ts = System.currentTimeMillis();
  1956 + r0 = XposedHelpers.newInstance(r0Class,
  1957 + new Class<?>[]{String.class, String.class, int.class, int.class, long.class},
  1958 + talker, voiceXml, 34, 0, ts);
  1959 + }
  1960 + } finally {
  1961 + sCalledByUs = false;
  1962 + sPendingVoiceId.remove();
  1963 + sPendingLvBuffer.remove();
  1964 + }
  1965 + // Dump r0 fields so we can see which field holds the audio path.
  1966 + dumpR0Fields(r0, "r0-after-ctor by=US");
  1967 +
  1968 + // ── Leave r0.p == null: take the AUTHENTIC new-send path ──────────────────
  1969 + // The r0 Object-ctor already inserted a proper f9 (content=voiceXml, imgPath
  1970 + // injected by hookF9ImgPathInjector, status=1) via cj().N9(). With p==null,
  1971 + // NetSceneSendMsg.doScene() reloads that f9 fresh from the DB (cj().c6()) —
  1972 + // content/msgsource intact — and assembles + dispatches it, exactly like a
  1973 + // real new send.
  1974 + //
  1975 + // Previously we forced r0.p = sDatabaseF9. That sends doScene down the *resend*
  1976 + // branch (which expects status=5 and logs "should not be resend"), handing the
  1977 + // MsgSource assembler a stale in-memory f9 whose content reads null →
  1978 + // e14.k.fromXml(null) NPE. That was the root-cause blocker; fixed by NOT setting p.
  1979 + sDatabaseF9.remove();
  1980 +
  1981 + // ── Set dispatcher on r0 (required for CDN upload via H()) ─────────────
  1982 + // r0.dispatcher (type com.tencent.mm.network.s) is null in our synthetic r0.
  1983 + // H() NPEs on `dispatcher.J(z0, o0, int)` if null.
  1984 + // We capture dispatcher from the first real WeChat r0 that enters H() (hookR0H).
  1985 + if (sCapturedDispatcher != null && !(sCapturedDispatcher instanceof java.lang.reflect.Proxy)) {
  1986 + // Real dispatcher captured from a genuine WeChat send — use it directly.
  1987 + try {
  1988 + XposedHelpers.setObjectField(r0, "dispatcher", sCapturedDispatcher);
  1989 + XposedBridge.log("[WeChatHook] sendVoiceViaAPI: set r0.dispatcher REAL class="
  1990 + + sCapturedDispatcher.getClass().getName());
  1991 + } catch (Throwable ed) {
  1992 + XposedBridge.log("[WeChatHook] sendVoiceViaAPI: r0.dispatcher set failed: " + ed);
  1993 + }
  1994 + } else {
  1995 + // No real dispatcher yet — fall through to proxy creation below.
  1996 + // (Cached proxy is reused if already created; fresh one made otherwise.)
  1997 + // Dispatcher not yet captured — search WeChat singletons for it.
  1998 + // gm0.j1.i() returns the message manager which likely holds a dispatcher reference.
  1999 + XposedBridge.log("[WeChatHook] sendVoiceViaAPI: dispatcher null, searching singletons...");
  2000 + outer:
  2001 + for (String[] candidate : new String[][]{
  2002 + {"gm0.j1", "i"}, // message manager singleton
  2003 + {"tg3.t1", "a"}, // service locator
  2004 + }) {
  2005 + try {
  2006 + Class<?> mgr = XposedHelpers.findClass(candidate[0], cl);
  2007 + Object inst = XposedHelpers.callStaticMethod(mgr, candidate[1]);
  2008 + if (inst == null) continue;
  2009 + // Walk inst's fields recursively (depth 2) looking for dispatcher
  2010 + for (java.lang.reflect.Field f1 : inst.getClass().getDeclaredFields()) {
  2011 + if (java.lang.reflect.Modifier.isStatic(f1.getModifiers())) continue;
  2012 + f1.setAccessible(true);
  2013 + Object v1 = f1.get(inst);
  2014 + if (v1 == null) continue;
  2015 + // Level 1: try r0.dispatcher field name on v1 directly
  2016 + try {
  2017 + Object d = XposedHelpers.getObjectField(v1, "dispatcher");
  2018 + if (d != null) {
  2019 + sCapturedDispatcher = d;
  2020 + XposedBridge.log("[WeChatHook] dispatcher found: "
  2021 + + candidate[0] + "." + candidate[1] + "()." + f1.getName()
  2022 + + ".dispatcher=" + d.getClass().getName());
  2023 + XposedHelpers.setObjectField(r0, "dispatcher", d);
  2024 + break outer;
  2025 + }
  2026 + } catch (Throwable ignored1) {}
  2027 + // Level 2: walk v1's fields
  2028 + for (java.lang.reflect.Field f2 : v1.getClass().getDeclaredFields()) {
  2029 + if (java.lang.reflect.Modifier.isStatic(f2.getModifiers())) continue;
  2030 + f2.setAccessible(true);
  2031 + Object v2 = f2.get(v1);
  2032 + if (v2 == null) continue;
  2033 + try {
  2034 + Object d = XposedHelpers.getObjectField(v2, "dispatcher");
  2035 + if (d != null) {
  2036 + sCapturedDispatcher = d;
  2037 + XposedBridge.log("[WeChatHook] dispatcher found (L2): "
  2038 + + candidate[0] + "." + candidate[1] + "()."
  2039 + + f1.getName() + "." + f2.getName()
  2040 + + ".dispatcher=" + d.getClass().getName());
  2041 + XposedHelpers.setObjectField(r0, "dispatcher", d);
  2042 + break outer;
  2043 + }
  2044 + } catch (Throwable ignored2) {}
  2045 + }
  2046 + }
  2047 + } catch (Throwable t2) {
  2048 + XposedBridge.log("[WeChatHook] dispatcher search " + candidate[0] + ": " + t2);
  2049 + }
  2050 + }
  2051 + if (sCapturedDispatcher instanceof java.lang.reflect.Proxy) {
  2052 + // Already have a proxy from a previous voice send — reuse it on this r0.
  2053 + try {
  2054 + XposedHelpers.setObjectField(r0, "dispatcher", sCapturedDispatcher);
  2055 + XposedBridge.log("[WeChatHook] sendVoiceViaAPI: reusing proxy dispatcher on r0");
  2056 + } catch (Throwable ed2) {
  2057 + XposedBridge.log("[WeChatHook] sendVoiceViaAPI: proxy reuse failed: " + ed2);
  2058 + }
  2059 + } else if (sCapturedDispatcher == null) {
  2060 + // Still not found — create a minimal proxy for s that logs calls.
  2061 + // This lets H() proceed past the NPE; CDN upload may work via callback.
  2062 + try {
  2063 + Class<?> sInterface = XposedHelpers.findClass("com.tencent.mm.network.s", cl);
  2064 + java.lang.reflect.Method[] sMethods = sInterface.getDeclaredMethods();
  2065 + StringBuilder sb = new StringBuilder("[WeChatHook] s interface methods:\n");
  2066 + for (java.lang.reflect.Method m : sMethods) sb.append(" ").append(m.toGenericString()).append("\n");
  2067 + XposedBridge.log(sb.toString());
  2068 + Object dispProxy = java.lang.reflect.Proxy.newProxyInstance(cl,
  2069 + new Class<?>[]{sInterface},
  2070 + (proxy, method, args) -> {
  2071 + XposedBridge.log("[WeChatHook] dispatcher.proxy: " + method.getName()
  2072 + + " ret=" + method.getReturnType().getSimpleName());
  2073 + if ("J".equals(method.getName()) && args != null && args.length >= 2) {
  2074 + // ── Attempt 1: forward J() via l0 method on m05.j ──────────────
  2075 + // method.declaringClass = s (s has own J, NOT inherited from l0).
  2076 + // m05.j implements l0 (not s). Solution: get J() from l0 interface
  2077 + // and invoke THAT on m05.j — valid since m05.j implements l0.
  2078 + try {
  2079 + Object q2arg = args[1];
  2080 + Object mj = XposedHelpers.getObjectField(q2arg, "e");
  2081 + if (mj != null) {
  2082 + Class<?> l0Iface = XposedHelpers.findClass("com.tencent.mm.network.l0", cl);
  2083 + // Dump l0 methods for diagnosis
  2084 + StringBuilder l0log = new StringBuilder("[WeChatHook] l0 methods:");
  2085 + java.lang.reflect.Method foundL0J = null;
  2086 + for (java.lang.reflect.Method l0m : l0Iface.getDeclaredMethods()) {
  2087 + l0log.append(" ").append(l0m.getName()).append("(").append(l0m.getParameterTypes().length).append(")");
  2088 + if (l0m.getName().equals(method.getName())
  2089 + && l0m.getParameterTypes().length == method.getParameterTypes().length) {
  2090 + foundL0J = l0m;
  2091 + }
  2092 + }
  2093 + XposedBridge.log(l0log.toString());
  2094 + if (foundL0J != null) {
  2095 + foundL0J.setAccessible(true);
  2096 + XposedBridge.log("[WeChatHook] J→m05.j via l0.J()");
  2097 + try {
  2098 + Object result = foundL0J.invoke(mj, args);
  2099 + XposedBridge.log("[WeChatHook] J→m05.j l0 OK result=" + result);
  2100 + return result;
  2101 + } catch (java.lang.reflect.InvocationTargetException ite) {
  2102 + XposedBridge.log("[WeChatHook] J→m05.j l0 threw: " + ite.getCause());
  2103 + }
  2104 + } else {
  2105 + XposedBridge.log("[WeChatHook] J not found in l0 by name+paramcount");
  2106 + }
  2107 + }
  2108 + } catch (Throwable jt0) {
  2109 + XposedBridge.log("[WeChatHook] J→m05.j err: " + jt0);
  2110 + }
  2111 + // ── Attempt 2: find s implementor in J() args (skip l0-only classes) ──
  2112 + try {
  2113 + Class<?> sIface = XposedHelpers.findClass("com.tencent.mm.network.s", cl);
  2114 + for (Object searchRoot : new Object[]{args[0], args[1]}) {
  2115 + if (searchRoot == null) continue;
  2116 + for (Class<?> cls2 = searchRoot.getClass(); cls2 != null && !cls2.equals(Object.class); cls2 = cls2.getSuperclass()) {
  2117 + for (java.lang.reflect.Field sf1 : cls2.getDeclaredFields()) {
  2118 + if (java.lang.reflect.Modifier.isStatic(sf1.getModifiers())) continue;
  2119 + sf1.setAccessible(true);
  2120 + Object sv1 = sf1.get(searchRoot);
  2121 + if (sv1 == null || sv1 == proxy) continue;
  2122 + if (sIface.isInstance(sv1)) {
  2123 + sCapturedDispatcher = sv1;
  2124 + XposedBridge.log("[WeChatHook] J: REAL s L1 " + sv1.getClass().getName());
  2125 + try { return method.invoke(sv1, args); } catch (java.lang.reflect.InvocationTargetException ite) { throw ite.getCause(); }
  2126 + }
  2127 + // L2 sub-fields
  2128 + try {
  2129 + for (Class<?> cls3 = sv1.getClass(); cls3 != null && !cls3.equals(Object.class); cls3 = cls3.getSuperclass()) {
  2130 + for (java.lang.reflect.Field sf2 : cls3.getDeclaredFields()) {
  2131 + if (java.lang.reflect.Modifier.isStatic(sf2.getModifiers())) continue;
  2132 + sf2.setAccessible(true);
  2133 + Object sv2 = sf2.get(sv1);
  2134 + if (sv2 == null || sv2 == proxy) continue;
  2135 + if (sIface.isInstance(sv2)) {
  2136 + sCapturedDispatcher = sv2;
  2137 + XposedBridge.log("[WeChatHook] J: REAL s L2 " + sf1.getName() + "." + sf2.getName() + " " + sv2.getClass().getName());
  2138 + try { return method.invoke(sv2, args); } catch (java.lang.reflect.InvocationTargetException ite) { throw ite.getCause(); }
  2139 + }
  2140 + }
  2141 + }
  2142 + } catch (Throwable ignored4) {}
  2143 + }
  2144 + }
  2145 + }
  2146 + XposedBridge.log("[WeChatHook] J: no s implementor in args");
  2147 + } catch (Throwable jse) {
  2148 + XposedBridge.log("[WeChatHook] J: search err: " + jse);
  2149 + }
  2150 + // ── Deep-dump v2 (CDN request) sub-fields ───────────────────
  2151 + try {
  2152 + Object v2arg = args[0];
  2153 + StringBuilder cdnDump = new StringBuilder("[WeChatHook] J v2-deep:\n");
  2154 + // Walk class hierarchy (getDeclaredFields only finds own fields)
  2155 + for (Class<?> cls2 = v2arg.getClass(); cls2 != null && !cls2.equals(Object.class); cls2 = cls2.getSuperclass()) {
  2156 + for (java.lang.reflect.Field sf1 : cls2.getDeclaredFields()) {
  2157 + if (java.lang.reflect.Modifier.isStatic(sf1.getModifiers())) continue;
  2158 + sf1.setAccessible(true);
  2159 + Object sv1 = sf1.get(v2arg);
  2160 + cdnDump.append(" ").append(sf1.getName()).append("=")
  2161 + .append(sv1 == null ? "null" : sv1.getClass().getSimpleName()).append("\n");
  2162 + if (sv1 == null) continue;
  2163 + for (java.lang.reflect.Field sf2 : sv1.getClass().getDeclaredFields()) {
  2164 + if (java.lang.reflect.Modifier.isStatic(sf2.getModifiers())) continue;
  2165 + sf2.setAccessible(true);
  2166 + Object sv2 = sf2.get(sv1);
  2167 + String sv2s;
  2168 + if (sv2 == null) { sv2s = "null"; }
  2169 + else if (sv2 instanceof byte[]) {
  2170 + byte[] ba = (byte[]) sv2;
  2171 + StringBuilder hex = new StringBuilder();
  2172 + for (int xi = 0; xi < Math.min(ba.length, 20); xi++) hex.append(String.format("%02x", ba[xi] & 0xff));
  2173 + sv2s = "byte[" + ba.length + "]=" + hex;
  2174 + } else {
  2175 + sv2s = sv2.toString();
  2176 + if (sv2s.length() > 100) sv2s = sv2s.substring(0, 100);
  2177 + }
  2178 + cdnDump.append(" ").append(sf1.getName()).append(".").append(sf2.getName()).append("=").append(sv2s).append("\n");
  2179 + }
  2180 + }
  2181 + }
  2182 + XposedBridge.log(cdnDump.toString());
  2183 + } catch (Throwable jde) {
  2184 + XposedBridge.log("[WeChatHook] J v2-dump err: " + jde);
  2185 + }
  2186 + }
  2187 + if (method.getReturnType() == int.class || method.getReturnType() == Integer.class)
  2188 + return 0;
  2189 + if (method.getReturnType() == boolean.class || method.getReturnType() == Boolean.class)
  2190 + return false;
  2191 + return null;
  2192 + });
  2193 + sCapturedDispatcher = dispProxy;
  2194 + XposedHelpers.setObjectField(r0, "dispatcher", dispProxy);
  2195 + XposedBridge.log("[WeChatHook] sendVoiceViaAPI: dispatcher proxy set on r0");
  2196 + } catch (Throwable ep) {
  2197 + XposedBridge.log("[WeChatHook] sendVoiceViaAPI: dispatcher proxy failed: " + ep);
  2198 + }
  2199 + }
  2200 + }
  2201 +
  2202 + // ── u0 callback stub (same pattern as sendViaR0) ─────────────────────
  2203 + // r0.d (type com.tencent.mm.modelbase.u0) is null unless we set it;
  2204 + // H() calls u0.onSceneEnd which NPEs otherwise.
  2205 + // hStarted gates the u0 stub: ignore premature onSceneEnd (fires synchronously
  2206 + // when we set r0.d, BEFORE H() is called) and only act on H()'s async CDN callback.
  2207 + // Root cause: setting r0.d triggers an immediate "local save done" callback.
  2208 + // If we call K(0) there, WeChat marks the message as "completed" → H() skips CDN.
  2209 + final java.util.concurrent.atomic.AtomicBoolean hStarted =
  2210 + new java.util.concurrent.atomic.AtomicBoolean(false);
  2211 + try {
  2212 + Class<?> u0 = XposedHelpers.findClass("com.tencent.mm.modelbase.u0", cl);
  2213 + Object stub = Proxy.newProxyInstance(cl, new Class<?>[]{u0},
  2214 + (proxy, method, args) -> {
  2215 + StringBuilder params = new StringBuilder();
  2216 + if (args != null) {
  2217 + for (int i = 0; i < args.length; i++) {
  2218 + if (i > 0) params.append(", ");
  2219 + params.append(args[i]);
  2220 + }
  2221 + }
  2222 + XposedBridge.log("[WeChatHook] voice-cb: " + method.getName()
  2223 + + "(" + params + ") hStarted=" + hStarted.get());
  2224 + // onSceneEnd(int code, int errCode, String msg, m1 scene)
  2225 + // Real m2 dispatch: r0.onGYNetEnd handles the network result itself
  2226 + // (status/msgSvrId update, SendMsgSuccessEvent, K/I). This u0 only needs
  2227 + // to be non-null so that internal onSceneEnd call doesn't NPE — do NOT
  2228 + // call K/I here or success/fail events double-fire.
  2229 + if ("onSceneEnd".equals(method.getName()) && args != null && args.length >= 2) {
  2230 + XposedBridge.log("[WeChatHook] voice onSceneEnd code=" + args[0] + " err=" + args[1]);
  2231 + }
  2232 + return null;
  2233 + });
  2234 + XposedHelpers.setObjectField(r0, "d", stub);
  2235 + // Premature onSceneEnd fires synchronously during setObjectField above and is suppressed.
  2236 + } catch (Throwable t) {
  2237 + XposedBridge.log("[WeChatHook] u0 stub failed (non-fatal): " + t);
  2238 + }
  2239 +
  2240 + // ── Dispatch via WeChat's REAL NetSceneQueue ─────────────────────────────
  2241 + // Exactly the path the (now-working) internal text send uses. n1.a() does:
  2242 + // ((gm0.n) com.tencent.mm.modelbase.z2.f88087b).f290500a.f290528b.h(scene, 0)
  2243 + // The queue supplies the real network dispatcher and runs doScene properly:
  2244 + // p==null → it reloads our just-inserted voice f9 from the DB, assembles the
  2245 + // MsgSource, uploads the SILK to CDN, and transports to the server.
  2246 + //
  2247 + // This replaces the old manual r0.H()+fake-$Proxy dispatcher, which never
  2248 + // reached the network — real transport is the queue's job (routed via IPC to
  2249 + // the :push connection), NOT a hand-set main-process m2 (which is never even
  2250 + // exercised, so it can't be captured).
  2251 + hStarted.set(true);
  2252 + sCalledByUs = true;
  2253 + try {
  2254 + // z2.b(m1) = WeChat's own "run cgi" helper (IGetNetSceneQueue): enqueues the
  2255 + // scene into the real NetSceneQueue, which supplies the live dispatcher and
  2256 + // runs doScene. Using the static helper avoids hardcoding the queue's field
  2257 + // chain, whose obfuscated names differ between base.apk and the Tinker patch
  2258 + // (the running code). r0 extends m1, so this resolves b(m1) by assignability.
  2259 + Class<?> z2c = XposedHelpers.findClass("com.tencent.mm.modelbase.z2", cl);
  2260 + XposedHelpers.callStaticMethod(z2c, "b", r0);
  2261 + XposedBridge.log("[WeChatHook] sendVoiceViaAPI: enqueued via z2.b(NetSceneQueue) to=" + talker
  2262 + + " voiceId=" + voiceId + " durationMs=" + durationMs);
  2263 + } catch (Throwable t) {
  2264 + XposedBridge.log("[WeChatHook] sendVoiceViaAPI: enqueue threw: " + t
  2265 + + "\n" + android.util.Log.getStackTraceString(t));
  2266 + } finally {
  2267 + sCalledByUs = false;
  2268 + }
  2269 +
  2270 + // ── Trigger REAL delivery via ResendVoiceMsgEvent{f9} ──────────────────
  2271 + // Decompiling WeChat 8.0.74 revealed the real voice send path:
  2272 + // cg0.d(talker,file) → jg0.x(cg0.d) → sendCgi(m)+uploadAttach(w).
  2273 + // ResendVoiceMsgEvent (com.tencent.mm.autogen.events) carries a single f9
  2274 + // (field g = am.wr, wr.a = f9). Publishing it makes WeChat's voice-resend
  2275 + // handler run the FULL sendCgi + CDN upload for our already-inserted f9 —
  2276 + // i.e. the same machinery a real send uses. This replaces the dead
  2277 + // r0.H()/msgSvrId-poll path (delivery never happened → msgSvrId stayed 0).
  2278 + final Long msgLocalId = sPendingMsgLocalId.get();
  2279 + sPendingMsgLocalId.remove();
  2280 + sDatabaseF9.remove();
  2281 + final Object fPt0e0 = sPt0E0Instance;
  2282 + final String fTalker = talker;
  2283 + final ClassLoader fCl = cl;
  2284 + // ResendVoiceMsgEvent path CONFIRMED DEAD (2026-07-06): even after marking the
  2285 + // properly-inserted voice msg failed (status=5) and firing the event, WeChat's
  2286 + // resend handler does NOT respond — the message just shows red ! (failed), no
  2287 + // CDN upload. So this force-fails sends for nothing. Disabled. The remaining
  2288 + // real path is to build a voiceinfo/w0 upload task and drive w21.g1.P0() (or
  2289 + // reconstruct jg0.x). Kept for reference.
  2290 + if (false && msgLocalId != null) {
  2291 + new Thread(() -> {
  2292 + try {
  2293 + Thread.sleep(1500); // let the z2.b send settle first
  2294 + // Re-fetch the DB-bound f9 via pt0.e0.k(talker, msgLocalId).
  2295 + Object f9 = null;
  2296 + if (fPt0e0 != null) {
  2297 + try {
  2298 + java.lang.reflect.Method kM = null;
  2299 + for (java.lang.reflect.Method m : fPt0e0.getClass().getDeclaredMethods())
  2300 + if ("k".equals(m.getName()) && m.getParameterTypes().length == 2) { kM = m; break; }
  2301 + if (kM != null) { kM.setAccessible(true); f9 = kM.invoke(fPt0e0, fTalker, msgLocalId); }
  2302 + } catch (Throwable t) {
  2303 + XposedBridge.log("[WeChatHook] resend: k() failed: " + t);
  2304 + }
  2305 + }
  2306 + if (f9 == null) {
  2307 + XposedBridge.log("[WeChatHook] resend: f9 null for msgLocalId=" + msgLocalId + ", abort");
  2308 + return;
  2309 + }
  2310 + // Mark the message failed (status=5) + persist, so the resend handler
  2311 + // treats it as a resendable failed voice. f9.r1(int)=status setter;
  2312 + // pt0.e0.s(talker,msgId,f9) persists via cj().lb().
  2313 + try {
  2314 + XposedHelpers.callMethod(f9, "r1", 5);
  2315 + long mid = ((Number) XposedHelpers.callMethod(f9, "getMsgId")).longValue();
  2316 + if (fPt0e0 != null) {
  2317 + java.lang.reflect.Method sM = null;
  2318 + for (java.lang.reflect.Method m : fPt0e0.getClass().getDeclaredMethods())
  2319 + if ("s".equals(m.getName()) && m.getParameterTypes().length == 3) { sM = m; break; }
  2320 + if (sM != null) { sM.setAccessible(true); sM.invoke(fPt0e0, fTalker, mid, f9); }
  2321 + }
  2322 + XposedBridge.log("[WeChatHook] resend: marked f9 status=5 + persisted msgId=" + mid);
  2323 + } catch (Throwable t) {
  2324 + XposedBridge.log("[WeChatHook] resend: status=5 failed: " + t);
  2325 + }
  2326 + // Build ResendVoiceMsgEvent, set its f9 (field g -> wr.a), publish.
  2327 + Class<?> evCls = XposedHelpers.findClass(
  2328 + "com.tencent.mm.autogen.events.ResendVoiceMsgEvent", fCl);
  2329 + Object ev = evCls.newInstance();
  2330 + Object wr = XposedHelpers.getObjectField(ev, "g"); // am.wr
  2331 + XposedHelpers.setObjectField(wr, "a", f9);
  2332 + XposedHelpers.callMethod(ev, "b", Looper.getMainLooper());
  2333 + XposedBridge.log("[WeChatHook] resend: ResendVoiceMsgEvent published msgLocalId="
  2334 + + msgLocalId + " talker=" + fTalker + " f9=" + f9.getClass().getName());
  2335 + } catch (Throwable t) {
  2336 + XposedBridge.log("[WeChatHook] resend: failed: " + t);
  2337 + }
  2338 + }, "WCHook-resend-" + msgLocalId).start();
  2339 + } else {
  2340 + XposedBridge.log("[WeChatHook] resend: msgLocalId null, skip");
  2341 + }
  2342 + }
  2343 +
  2344 + // ── Factory method discovery ───────────────────────────────────────────────
  2345 + // Hooks ALL static methods on w11.s1 and logs their signatures + call args.
  2346 + // When WeChat UI sends image/voice, we'll see which s1 method is called and
  2347 + // what parameters it receives, revealing the builder API for each msgtype.
  2348 + private void hookFactoryMethods(ClassLoader cl, String procName) {
  2349 + try {
  2350 + Class<?> s1 = XposedHelpers.findClass("w11.s1", cl);
  2351 + java.lang.reflect.Method[] methods = s1.getDeclaredMethods();
  2352 +
  2353 + // Dump all method signatures immediately
  2354 + StringBuilder sb = new StringBuilder();
  2355 + sb.append("[WeChatHook] w11.s1 ALL METHODS (").append(methods.length).append("):\n");
  2356 + for (java.lang.reflect.Method m : methods) {
  2357 + sb.append(" ").append(m.toGenericString()).append("\n");
  2358 + }
  2359 + XposedBridge.log(sb.toString());
  2360 +
  2361 + // Hook each static method to intercept calls from WeChat UI
  2362 + for (java.lang.reflect.Method m : methods) {
  2363 + if (!java.lang.reflect.Modifier.isStatic(m.getModifiers())) continue;
  2364 + final String mName = m.getName();
  2365 + final String mSig = m.toGenericString();
  2366 + m.setAccessible(true);
  2367 + XposedBridge.hookMethod(m, new XC_MethodHook() {
  2368 + @Override
  2369 + protected void afterHookedMethod(MethodHookParam param) throws Throwable {
  2370 + StringBuilder log = new StringBuilder();
  2371 + log.append("[WeChatHook] s1.").append(mName).append("(");
  2372 + if (param.args != null) {
  2373 + for (int i = 0; i < param.args.length; i++) {
  2374 + if (i > 0) log.append(", ");
  2375 + Object a = param.args[i];
  2376 + log.append(a == null ? "null" : a.getClass().getSimpleName() + "=" + a);
  2377 + }
  2378 + }
  2379 + log.append(") -> ");
  2380 + Object ret = param.getResult();
  2381 + if (ret == null) {
  2382 + log.append("null");
  2383 + } else {
  2384 + log.append(ret.getClass().getName());
  2385 + dumpBuilderMethods(ret, "s1." + mName);
  2386 + // Capture dispatcher from the r0 inside r1 (set by factory, null in direct ctor)
  2387 + try {
  2388 + StringBuilder r1Fields = new StringBuilder("[WeChatHook] r1 fields:\n");
  2389 + for (Class<?> rc = ret.getClass(); rc != null && !rc.equals(Object.class); rc = rc.getSuperclass()) {
  2390 + for (java.lang.reflect.Field rf : rc.getDeclaredFields()) {
  2391 + if (java.lang.reflect.Modifier.isStatic(rf.getModifiers())) continue;
  2392 + rf.setAccessible(true);
  2393 + Object rv = rf.get(ret);
  2394 + String typeName = rv != null ? rv.getClass().getName() : rf.getType().getName();
  2395 + r1Fields.append(" ").append(rf.getName()).append(" (").append(typeName).append(")");
  2396 + if (sCapturedDispatcher == null && rv != null) {
  2397 + // Try to get dispatcher from any field, whether it's r0 or a container
  2398 + try {
  2399 + Object disp = XposedHelpers.getObjectField(rv, "dispatcher");
  2400 + if (disp != null) {
  2401 + sCapturedDispatcher = disp;
  2402 + r1Fields.append(" [dispatcher captured!]");
  2403 + }
  2404 + } catch (Throwable ignored2) {}
  2405 + }
  2406 + r1Fields.append("\n");
  2407 + }
  2408 + }
  2409 + XposedBridge.log(r1Fields.toString());
  2410 + } catch (Throwable r1e) {
  2411 + XposedBridge.log("[WeChatHook] r1 field dump error: " + r1e);
  2412 + }
  2413 + }
  2414 + if (param.hasThrowable())
  2415 + log.append(" THREW: ").append(param.getThrowable());
  2416 + XposedBridge.log(log.toString());
  2417 + }
  2418 + });
  2419 + }
  2420 + XposedBridge.log("[WeChatHook] hookFactoryMethods: hooked " + methods.length
  2421 + + " methods on w11.s1 in " + procName);
  2422 + } catch (Throwable t) {
  2423 + XposedBridge.log("[WeChatHook] hookFactoryMethods failed in " + procName + ": " + t);
  2424 + }
  2425 + }
  2426 +
  2427 + // Dump ALL instance methods on a builder object returned by the factory.
  2428 + // Each unique builder class is only dumped once to avoid logcat spam.
  2429 + private static final java.util.Set<String> sDumpedClasses =
  2430 + java.util.Collections.synchronizedSet(new java.util.HashSet<>());
  2431 +
  2432 + private static void dumpBuilderMethods(Object builder, String fromFactory) {
  2433 + if (builder == null) return;
  2434 + String clsName = builder.getClass().getName();
  2435 + if (!sDumpedClasses.add(clsName)) return; // already dumped
  2436 + try {
  2437 + java.lang.reflect.Method[] ms = builder.getClass().getDeclaredMethods();
  2438 + StringBuilder sb = new StringBuilder();
  2439 + sb.append("[WeChatHook] BUILDER from ").append(fromFactory)
  2440 + .append(" class=").append(clsName)
  2441 + .append(" methods(").append(ms.length).append("):\n");
  2442 + for (java.lang.reflect.Method m : ms) {
  2443 + sb.append(" ").append(m.toGenericString()).append("\n");
  2444 + }
  2445 + XposedBridge.log(sb.toString());
  2446 + } catch (Throwable t) {
  2447 + XposedBridge.log("[WeChatHook] dumpBuilderMethods " + clsName + ": " + t);
  2448 + }
  2449 + }
  2450 +
  2451 + // Dump all instance fields of w11.r0 to logcat.
  2452 + // Used to discover which field holds the SILK audio data for CDN upload.
  2453 + // Logs each field name, type, and a brief value summary.
  2454 + private static void dumpR0Fields(Object r0, String tag) {
  2455 + if (r0 == null) return;
  2456 + try {
  2457 + Class<?> cls = r0.getClass();
  2458 + StringBuilder sb = new StringBuilder();
  2459 + sb.append("[WeChatHook] ").append(tag).append(" class=").append(cls.getName()).append("\n");
  2460 + // Walk the class hierarchy to capture inherited fields
  2461 + for (Class<?> c = cls; c != null && !c.equals(Object.class); c = c.getSuperclass()) {
  2462 + for (java.lang.reflect.Field f : c.getDeclaredFields()) {
  2463 + if (java.lang.reflect.Modifier.isStatic(f.getModifiers())) continue;
  2464 + f.setAccessible(true);
  2465 + try {
  2466 + Object val = f.get(r0);
  2467 + if (val == null) {
  2468 + sb.append(" ").append(f.getName()).append(" (").append(f.getType().getSimpleName()).append(") = null\n");
  2469 + } else if (val instanceof byte[]) {
  2470 + byte[] ba = (byte[]) val;
  2471 + StringBuilder hex = new StringBuilder();
  2472 + int show = Math.min(ba.length, 16);
  2473 + for (int i = 0; i < show; i++) hex.append(String.format("%02x", ba[i] & 0xff));
  2474 + sb.append(" ").append(f.getName()).append(" (byte[]) len=").append(ba.length).append(" hex=").append(hex).append("\n");
  2475 + } else if (val instanceof String) {
  2476 + String s = (String) val;
  2477 + sb.append(" ").append(f.getName()).append(" (String) = \"").append(s.length() > 80 ? s.substring(0, 80) + "…" : s).append("\"\n");
  2478 + } else {
  2479 + String vs = val.toString();
  2480 + sb.append(" ").append(f.getName()).append(" (").append(val.getClass().getSimpleName()).append(") = ").append(vs.length() > 80 ? vs.substring(0, 80) + "…" : vs).append("\n");
  2481 + }
  2482 + } catch (Throwable e2) {
  2483 + sb.append(" ").append(f.getName()).append(" ERROR: ").append(e2).append("\n");
  2484 + }
  2485 + }
  2486 + }
  2487 + XposedBridge.log(sb.toString());
  2488 + } catch (Throwable t) {
  2489 + XposedBridge.log("[WeChatHook] dumpR0Fields failed: " + t);
  2490 + }
  2491 + }
  2492 +
  2493 + // ── On-demand API dump broadcast ──────────────────────────────────────────
  2494 + // am broadcast -a com.hermes.wechat.DUMP_WECHAT_API
  2495 + // Optional extra: --es class "w11.s1" (defaults to w11.s1 if omitted)
  2496 + private static void handleDumpApi(Intent intent) {
  2497 + ClassLoader cl = sTinkerCL != null ? sTinkerCL : sWeChatCL;
  2498 + if (cl == null) { XposedBridge.log("[WeChatHook] DUMP_API: classloader null"); return; }
  2499 +
  2500 + String className = intent.getStringExtra("class");
  2501 + if (className == null || className.isEmpty()) className = "w11.s1";
  2502 +
  2503 + try {
  2504 + Class<?> cls = XposedHelpers.findClass(className, cl);
  2505 + java.lang.reflect.Method[] ms = cls.getDeclaredMethods();
  2506 + java.lang.reflect.Constructor[] cs = cls.getDeclaredConstructors();
  2507 + java.lang.reflect.Field[] fs = cls.getDeclaredFields();
  2508 +
  2509 + StringBuilder sb = new StringBuilder();
  2510 + sb.append("[WeChatHook] DUMP_API class=").append(cls.getName()).append("\n");
  2511 +
  2512 + // For enum classes, print each constant with its ordinal and any int fields
  2513 + if (cls.isEnum()) {
  2514 + sb.append(" ENUM CONSTANTS:\n");
  2515 + try {
  2516 + Object[] constants = (Object[]) cls.getMethod("values").invoke(null);
  2517 + java.lang.reflect.Method nameM = Enum.class.getMethod("name");
  2518 + java.lang.reflect.Method ordinalM = Enum.class.getMethod("ordinal");
  2519 + for (Object c : constants) {
  2520 + String cName = (String) nameM.invoke(c);
  2521 + int cOrd = (int) ordinalM.invoke(c);
  2522 + sb.append(" ").append(cName).append(" ordinal=").append(cOrd);
  2523 + // Also print any int/String fields on the enum instance
  2524 + for (java.lang.reflect.Field f2 : fs) {
  2525 + if (java.lang.reflect.Modifier.isStatic(f2.getModifiers())) continue;
  2526 + f2.setAccessible(true);
  2527 + try {
  2528 + Object fv = f2.get(c);
  2529 + sb.append(" ").append(f2.getName()).append("=").append(fv);
  2530 + } catch (Throwable ignored) {}
  2531 + }
  2532 + sb.append("\n");
  2533 + }
  2534 + } catch (Throwable e2) {
  2535 + sb.append(" (enum values() failed: ").append(e2).append(")\n");
  2536 + }
  2537 + }
  2538 +
  2539 + sb.append(" FIELDS (").append(fs.length).append("):\n");
  2540 + for (java.lang.reflect.Field f : fs) {
  2541 + sb.append(" ").append(f.toGenericString());
  2542 + // Read static field values (helpful for non-enum static constants)
  2543 + if (java.lang.reflect.Modifier.isStatic(f.getModifiers()) && !cls.isEnum()) {
  2544 + f.setAccessible(true);
  2545 + try { sb.append(" = ").append(f.get(null)); } catch (Throwable ignored) {}
  2546 + }
  2547 + sb.append("\n");
  2548 + }
  2549 + sb.append(" CONSTRUCTORS (").append(cs.length).append("):\n");
  2550 + for (java.lang.reflect.Constructor<?> c : cs) sb.append(" ").append(c.toGenericString()).append("\n");
  2551 + sb.append(" METHODS (").append(ms.length).append("):\n");
  2552 + for (java.lang.reflect.Method m : ms) sb.append(" ").append(m.toGenericString()).append("\n");
  2553 + XposedBridge.log(sb.toString());
  2554 + } catch (Throwable t) {
  2555 + XposedBridge.log("[WeChatHook] DUMP_API failed for " + className + ": " + t);
  2556 + }
  2557 + }
  2558 +
  2559 + // PRIMARY FIX: WeChat's own methods (LoginPasswordUI.onCreate etc.) are AOT-compiled
  2560 + // in a way that bypasses ArtMethod entry point replacement. But framework-dispatched
  2561 + // base class methods like Activity.onResume() always go through the entry point.
  2562 + // We hook onResume, filter for the login screens, and force the tablet button visible.
  2563 + // By onResume time, all views are initialized (onCreate + initView have run).
  2564 + private void hookProbe(ClassLoader cl) {
  2565 + try {
  2566 + XposedHelpers.findAndHookMethod(
  2567 + "android.app.Activity", null,
  2568 + "onResume", new XC_MethodHook() {
  2569 + @Override
  2570 + protected void afterHookedMethod(MethodHookParam param) throws Throwable {
  2571 + String cls = param.thisObject.getClass().getName();
  2572 + if (!cls.equals("com.tencent.mm.plugin.account.ui.LoginPasswordUI")
  2573 + && !cls.equals("com.tencent.mm.plugin.account.ui.LoginHistoryUI")) {
  2574 + return;
  2575 + }
  2576 + Object obj = param.thisObject;
  2577 + View tabletBtn = null;
  2578 + try {
  2579 + tabletBtn = (View) XposedHelpers.getObjectField(obj, "N");
  2580 + } catch (Throwable e) {
  2581 + XposedBridge.log("[WeChatHook] onResume getField N failed: " + e);
  2582 + }
  2583 + if (tabletBtn == null) {
  2584 + XposedBridge.log("[WeChatHook] onResume: N is null for " + cls);
  2585 + return;
  2586 + }
  2587 + tabletBtn.setVisibility(View.VISIBLE);
  2588 + // CRITICAL: resolve m4 from the Activity's OWN classloader. The login
  2589 + // Activities run under the Tinker CL, but hookProbe was installed with
  2590 + // the pre-Tinker CL. m4's ctor param LoginHistoryUI and the running
  2591 + // Activity are the SAME FQN but from DIFFERENT classloaders, so a
  2592 + // captured-CL m4 fails with "type LoginHistoryUI, got LoginHistoryUI".
  2593 + // Looking up m4 via obj's CL makes the types line up.
  2594 + boolean attached = false;
  2595 + try {
  2596 + ClassLoader runtimeCl = obj.getClass().getClassLoader();
  2597 + Class<?> m4Class = XposedHelpers.findClass(
  2598 + "com.tencent.mm.plugin.account.ui.m4", runtimeCl);
  2599 + java.lang.reflect.Constructor<?> chosen = null;
  2600 + for (java.lang.reflect.Constructor<?> c : m4Class.getDeclaredConstructors()) {
  2601 + Class<?>[] pt = c.getParameterTypes();
  2602 + if (pt.length == 1 && pt[0].isAssignableFrom(obj.getClass())) {
  2603 + chosen = c; break;
  2604 + }
  2605 + }
  2606 + if (chosen != null && View.OnClickListener.class.isAssignableFrom(m4Class)) {
  2607 + chosen.setAccessible(true);
  2608 + tabletBtn.setOnClickListener(
  2609 + (View.OnClickListener) chosen.newInstance(obj));
  2610 + attached = true;
  2611 + XposedBridge.log("[WeChatHook] onResume: m4 listener attached via "
  2612 + + chosen.getParameterTypes()[0].getName() + " for " + cls);
  2613 + } else {
  2614 + XposedBridge.log("[WeChatHook] onResume: no assignable m4 ctor for "
  2615 + + cls + " (obj CL=" + runtimeCl + ")");
  2616 + }
  2617 + } catch (Throwable e) {
  2618 + XposedBridge.log("[WeChatHook] onResume setListener failed: " + e);
  2619 + }
  2620 + if (!attached) {
  2621 + XposedBridge.log("[WeChatHook] onResume: N VISIBLE but NO listener for " + cls);
  2622 + }
  2623 + }
  2624 + });
  2625 + XposedBridge.log("[WeChatHook] Hooked Activity.onResume for tablet button");
  2626 + } catch (Throwable t) {
  2627 + XposedBridge.log("[WeChatHook] hookProbe/onResume failed: " + t);
  2628 + }
  2629 + }
  2630 +
  2631 + private void hookInTabletEnv(ClassLoader cl) {
  2632 + try {
  2633 + Class<?> bkClass = XposedHelpers.findClass("com.tencent.mm.ui.bk", cl);
  2634 + Class<?> x0Class = XposedHelpers.findClass("bm5.x0", cl);
  2635 + XposedHelpers.findAndHookMethod(bkClass, "B", x0Class, new XC_MethodHook() {
  2636 + @Override
  2637 + protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
  2638 + param.setResult(Boolean.TRUE);
  2639 + }
  2640 + });
  2641 + XposedHelpers.findAndHookMethod(bkClass, "A", new XC_MethodHook() {
  2642 + @Override
  2643 + protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
  2644 + XposedBridge.log("[WeChatHook] bk.A() called -> TRUE");
  2645 + param.setResult(Boolean.TRUE);
  2646 + }
  2647 + });
  2648 + XposedBridge.log("[WeChatHook] Hooked bk.B(x0) + bk.A()");
  2649 + } catch (Throwable t) {
  2650 + XposedBridge.log("[WeChatHook] hookInTabletEnv failed: " + t);
  2651 + }
  2652 + }
  2653 +
  2654 + // PRIMARY FIX: Hook LoginPasswordUI.onCreate(Bundle) afterHookedMethod.
  2655 + //
  2656 + // Previous attempts to hook initView() and LoginHistoryUI.initView() both failed
  2657 + // because ART AOT devirtualizes the call to this.initView() inside
  2658 + // LoginHistoryUI.onCreate() — the compiled native code jumps directly past the
  2659 + // Xposed entry point replacement.
  2660 + //
  2661 + // onCreate() itself is called by the Android framework via the ArtMethod pointer
  2662 + // directly (no vtable devirtualization possible), so this hook fires reliably.
  2663 + // By the time afterHookedMethod runs, super.onCreate() has completed which means
  2664 + // LoginHistoryUI.initView() has already run and this.N is assigned.
  2665 + private void hookLoginHistoryUIInitView(ClassLoader cl) {
  2666 + final Class<?> m4Class;
  2667 + try {
  2668 + m4Class = XposedHelpers.findClass("com.tencent.mm.plugin.account.ui.m4", cl);
  2669 + } catch (Throwable t) {
  2670 + XposedBridge.log("[WeChatHook] m4 class not found: " + t);
  2671 + return;
  2672 + }
  2673 +
  2674 + try {
  2675 + XposedHelpers.findAndHookMethod(
  2676 + "com.tencent.mm.plugin.account.ui.LoginPasswordUI", cl,
  2677 + "onCreate", Bundle.class, new XC_MethodHook() {
  2678 + @Override
  2679 + protected void afterHookedMethod(MethodHookParam param) throws Throwable {
  2680 + Object obj = param.thisObject;
  2681 + View tabletBtn = (View) XposedHelpers.getObjectField(obj, "N");
  2682 + if (tabletBtn == null) {
  2683 + XposedBridge.log("[WeChatHook] LoginPasswordUI.onCreate: N is null");
  2684 + return;
  2685 + }
  2686 + tabletBtn.setVisibility(View.VISIBLE);
  2687 + tabletBtn.setOnClickListener(
  2688 + (View.OnClickListener) XposedHelpers.newInstance(m4Class, obj));
  2689 + XposedBridge.log("[WeChatHook] LoginPasswordUI.onCreate() -> N VISIBLE + m4 attached");
  2690 + }
  2691 + });
  2692 + XposedBridge.log("[WeChatHook] Hooked LoginPasswordUI.onCreate()");
  2693 + } catch (Throwable t) {
  2694 + XposedBridge.log("[WeChatHook] hookLoginPasswordUI.onCreate failed: " + t);
  2695 + }
  2696 +
  2697 + // Belt-and-suspenders: also hook LoginHistoryUI.onCreate() for any subclass
  2698 + // that doesn't override onCreate but does have the N button.
  2699 + try {
  2700 + XposedHelpers.findAndHookMethod(
  2701 + "com.tencent.mm.plugin.account.ui.LoginHistoryUI", cl,
  2702 + "onCreate", Bundle.class, new XC_MethodHook() {
  2703 + @Override
  2704 + protected void afterHookedMethod(MethodHookParam param) throws Throwable {
  2705 + Object obj = param.thisObject;
  2706 + if (obj.getClass().getName().equals(
  2707 + "com.tencent.mm.plugin.account.ui.LoginPasswordUI")) return;
  2708 + View tabletBtn = (View) XposedHelpers.getObjectField(obj, "N");
  2709 + if (tabletBtn == null) {
  2710 + XposedBridge.log("[WeChatHook] LoginHistoryUI.onCreate: N is null");
  2711 + return;
  2712 + }
  2713 + tabletBtn.setVisibility(View.VISIBLE);
  2714 + tabletBtn.setOnClickListener(
  2715 + (View.OnClickListener) XposedHelpers.newInstance(m4Class, obj));
  2716 + XposedBridge.log("[WeChatHook] LoginHistoryUI.onCreate() -> N VISIBLE + m4 attached");
  2717 + }
  2718 + });
  2719 + XposedBridge.log("[WeChatHook] Hooked LoginHistoryUI.onCreate()");
  2720 + } catch (Throwable t) {
  2721 + XposedBridge.log("[WeChatHook] hookLoginHistoryUI.onCreate failed: " + t);
  2722 + }
  2723 + }
  2724 +
  2725 + private void hookLoginUIInitView(ClassLoader cl) {
  2726 + try {
  2727 + final Class<?> wbClass = XposedHelpers.findClass(
  2728 + "com.tencent.mm.plugin.account.ui.wb", cl);
  2729 + XposedHelpers.findAndHookMethod(
  2730 + "com.tencent.mm.plugin.account.ui.MobileInputUI", cl,
  2731 + "initView", new XC_MethodHook() {
  2732 + @Override
  2733 + protected void afterHookedMethod(MethodHookParam param) throws Throwable {
  2734 + Object mobileInputUI = param.thisObject;
  2735 + View tabletBtn = (View) XposedHelpers.getObjectField(mobileInputUI, "w");
  2736 + if (tabletBtn == null) {
  2737 + XposedBridge.log("[WeChatHook] MobileInputUI.w is null");
  2738 + return;
  2739 + }
  2740 + tabletBtn.setVisibility(View.VISIBLE);
  2741 + tabletBtn.setOnClickListener(
  2742 + (View.OnClickListener) XposedHelpers.newInstance(wbClass, mobileInputUI));
  2743 + XposedBridge.log("[WeChatHook] MobileInputUI.initView() -> w VISIBLE + wb attached");
  2744 + }
  2745 + });
  2746 + XposedBridge.log("[WeChatHook] Hooked MobileInputUI.initView()");
  2747 + } catch (Throwable t) {
  2748 + XposedBridge.log("[WeChatHook] hookLoginUIInitView(MobileInputUI) failed: " + t);
  2749 + }
  2750 + try {
  2751 + final Class<?> g7Class = XposedHelpers.findClass(
  2752 + "com.tencent.mm.plugin.account.ui.g7", cl);
  2753 + XposedHelpers.findAndHookMethod(
  2754 + "com.tencent.mm.plugin.account.ui.LoginUI", cl,
  2755 + "initView", new XC_MethodHook() {
  2756 + @Override
  2757 + protected void afterHookedMethod(MethodHookParam param) throws Throwable {
  2758 + Object loginUI = param.thisObject;
  2759 + View tabletBtn = (View) XposedHelpers.getObjectField(loginUI, "f992u");
  2760 + if (tabletBtn == null) return;
  2761 + tabletBtn.setVisibility(View.VISIBLE);
  2762 + tabletBtn.setOnClickListener(
  2763 + (View.OnClickListener) XposedHelpers.newInstance(g7Class, loginUI));
  2764 + XposedBridge.log("[WeChatHook] LoginUI.initView() -> f992u VISIBLE + g7 attached");
  2765 + }
  2766 + });
  2767 + XposedBridge.log("[WeChatHook] Hooked LoginUI.initView()");
  2768 + } catch (Throwable t) {
  2769 + XposedBridge.log("[WeChatHook] hookLoginUIInitView(LoginUI) failed: " + t);
  2770 + }
  2771 + }
  2772 +
  2773 + private void hookLoginSelectUICheck(ClassLoader cl) {
  2774 + try {
  2775 + Class<?> callbackClass = XposedHelpers.findClass(
  2776 + "com.tencent.mm.plugin.account.ui.LoginSelectUI$a", cl);
  2777 + XposedHelpers.findAndHookMethod(callbackClass, "a", boolean.class, new XC_MethodHook() {
  2778 + @Override
  2779 + protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
  2780 + XposedBridge.log("[WeChatHook] LoginSelectUI$a.a(" + param.args[0] + ") -> false");
  2781 + param.args[0] = false;
  2782 + }
  2783 + });
  2784 + XposedBridge.log("[WeChatHook] Hooked LoginSelectUI$a.a()");
  2785 + } catch (Throwable t) {
  2786 + XposedBridge.log("[WeChatHook] hookLoginSelectUICheck failed: " + t);
  2787 + }
  2788 + }
  2789 +
  2790 + private void hookLoginButtonClick(ClassLoader cl) {
  2791 + try {
  2792 + Class<?> ljClass = XposedHelpers.findClass(
  2793 + "com.tencent.mm.plugin.account.ui.lj", cl);
  2794 + final Class<?> loginSelectUIClass = XposedHelpers.findClass(
  2795 + "com.tencent.mm.plugin.account.ui.LoginSelectUI", cl);
  2796 + XposedHelpers.findAndHookMethod(ljClass, "onClick", View.class, new XC_MethodHook() {
  2797 + @Override
  2798 + protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
  2799 + XposedBridge.log("[WeChatHook] lj.onClick() -> forcing LoginSelectUI");
  2800 + Activity welcomeActivity = (Activity) XposedHelpers.getObjectField(
  2801 + param.thisObject, "d");
  2802 + Intent intent = new Intent(welcomeActivity, loginSelectUIClass);
  2803 + intent.putExtra("mobile_input_purpose", 1);
  2804 + welcomeActivity.startActivity(intent);
  2805 + param.setResult(null);
  2806 + }
  2807 + });
  2808 + XposedBridge.log("[WeChatHook] Hooked lj.onClick() -> LoginSelectUI");
  2809 + } catch (Throwable t) {
  2810 + XposedBridge.log("[WeChatHook] hookLoginButtonClick failed: " + t);
  2811 + }
  2812 + }
  2813 +
  2814 + // ── Send message via internal API ────────────────────────────────────────
  2815 + //
  2816 + // Registered in ALL WeChat processes. We don't yet know which process has gm0.j1
  2817 + // initialized — the first process where the receiver fires and succeeds wins.
  2818 + //
  2819 + // Trigger from ADB (must run as root — RECEIVER_NOT_EXPORTED):
  2820 + // adb shell su -c 'am broadcast -a com.hermes.wechat.SEND_MSG_INTERNAL \
  2821 + // --es to "filehelper" --es text "hello"'
  2822 + private void hookSendMessage(ClassLoader cl, String procName) {
  2823 + try {
  2824 + XposedHelpers.findAndHookMethod(
  2825 + "android.app.Application", null, "onCreate",
  2826 + new XC_MethodHook() {
  2827 + @Override
  2828 + protected void afterHookedMethod(MethodHookParam param) throws Throwable {
  2829 + Context ctx = (Context) param.thisObject;
  2830 + if (!"com.tencent.mm".equals(ctx.getPackageName())) return;
  2831 + sAppContext = ctx;
  2832 + // Capture Tinker-patched classloader (Tinker installs in attachBaseContext,
  2833 + // so by App.onCreate this loader has the patch DEX classes).
  2834 + sTinkerCL = ctx.getClassLoader();
  2835 + XposedBridge.log("[WeChatHook] App.onCreate proc=" + procName
  2836 + + " pid=" + android.os.Process.myPid()
  2837 + + " tinkerCL=" + (sTinkerCL != null ? sTinkerCL.getClass().getSimpleName() : "null"));
  2838 + // Re-hook with Tinker CL — w11.s1 and f9 may live in a Tinker DEX.
  2839 + // This ensures our factory and convertTo hooks fire on actual WeChat UI sends.
  2840 + if (sTinkerCL != sWeChatCL) {
  2841 + hookFactoryMethods(sTinkerCL, procName + "/tinker");
  2842 + hookF9ConvertTo(sTinkerCL, procName + "/tinker");
  2843 + hookF9ImgPathInjector(sTinkerCL, procName + "/tinker");
  2844 + hookR0H(sTinkerCL, procName + "/tinker");
  2845 + // Hook pt0.e0 in Tinker CL — real voice sends run in Tinker CL.
  2846 + hookPt0E0(sTinkerCL, procName + "/tinker");
  2847 + // NOTE: hookJg0 / hookVoiceEntry disabled — they hook WeChat's
  2848 + // generic coroutine classes (pu.o0/pu.m0) and every message
  2849 + // DB insert (g9.M9/N9), which adds anti-tamper risk and
  2850 + // destabilizes the fragile Pad login. Re-enable only for a
  2851 + // targeted investigation session, never during normal use.
  2852 + // hookJg0(sTinkerCL, procName + "/tinker");
  2853 + // hookVoiceEntry(sTinkerCL, procName + "/tinker");
  2854 + // Surgical probe: jg0.x + qi3.f0/g0 only (safe).
  2855 + hookVoiceProbe(sTinkerCL, procName + "/tinker");
  2856 + // Image send runs in Tinker CL — hook b80.u.pj/Bi there.
  2857 + hookImageSend(sTinkerCL, procName + "/tinker");
  2858 + // CDN upload trace runs in Tinker CL (real voice send path).
  2859 + hookCdnTrace(sTinkerCL, procName + "/tinker");
  2860 + // Capture the real uploadvoice cgi request in Tinker CL.
  2861 + hookVoiceCgiCapture(sTinkerCL, procName + "/tinker");
  2862 + hookVoiceCgiResult(sTinkerCL, procName + "/tinker");
  2863 + }
  2864 + hookF9ConvertTo(sWeChatCL, procName);
  2865 + hookF9ImgPathInjector(sWeChatCL, procName);
  2866 + registerSendReceiver(ctx, procName);
  2867 + }
  2868 + });
  2869 + XposedBridge.log("[WeChatHook] Send hook registered in " + procName);
  2870 + } catch (Throwable t) {
  2871 + XposedBridge.log("[WeChatHook] hookSendMessage failed in " + procName + ": " + t);
  2872 + }
  2873 +
  2874 + // ── w11.r0 constructor hooks ───────────────────────────────────────────
  2875 + // Log "by=US" vs "by=WeChat" to tell if WeChat's own UI send uses this ctor.
  2876 + XC_MethodHook r0Hook = new XC_MethodHook() {
  2877 + @Override
  2878 + protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
  2879 + String by = sCalledByUs ? "US" : "WeChat";
  2880 + XposedBridge.log("[WeChatHook] w11.r0 ctor by=" + by
  2881 + + " args=" + param.args.length + " proc=" + procName
  2882 + + " pid=" + android.os.Process.myPid());
  2883 + if (sCalledByUs) {
  2884 + forceInitDI();
  2885 + diagMCoreStorage("before-r0-ctor");
  2886 + }
  2887 + }
  2888 + @Override
  2889 + protected void afterHookedMethod(MethodHookParam param) throws Throwable {
  2890 + String by = sCalledByUs ? "US" : "WeChat";
  2891 + if (param.hasThrowable()) {
  2892 + Throwable t = param.getThrowable();
  2893 + XposedBridge.log("[WeChatHook] w11.r0 ctor THREW by=" + by
  2894 + + " proc=" + procName + ": " + t);
  2895 + if (sCalledByUs)
  2896 + XposedBridge.log("[WeChatHook] r0-ctor-stack: "
  2897 + + android.util.Log.getStackTraceString(t));
  2898 + return;
  2899 + }
  2900 + sFsGReady = true;
  2901 + XposedBridge.log("[WeChatHook] w11.r0 ctor OK by=" + by + " proc=" + procName);
  2902 + }
  2903 + };
  2904 + for (Class<?>[] sig : new Class<?>[][]{
  2905 + {String.class, String.class, int.class, int.class, long.class},
  2906 + {String.class, String.class, int.class, int.class, Object.class},
  2907 + {long.class, int.class, String.class},
  2908 + {}}) {
  2909 + try {
  2910 + XposedHelpers.findAndHookConstructor("w11.r0", cl,
  2911 + appendHook(sig, r0Hook));
  2912 + XposedBridge.log("[WeChatHook] Hooked w11.r0(" + sig.length + " params)");
  2913 + } catch (Throwable t) {
  2914 + XposedBridge.log("[WeChatHook] w11.r0(" + sig.length + "p) hook failed: " + t);
  2915 + }
  2916 + }
  2917 +
  2918 + // ── w11.r0.H(String) — the actual dispatch method ─────────────────────
  2919 + // Fires for EVERY send (ours AND WeChat UI sends). Shows if WeChat uses r0.
  2920 + // For real WeChat voice sends (type=34, by=WeChat), dumps ALL r0 fields so
  2921 + // we can find which field holds the SILK audio data (root cause of spinner).
  2922 + try {
  2923 + XposedHelpers.findAndHookMethod("w11.r0", cl, "H", String.class,
  2924 + new XC_MethodHook() {
  2925 + @Override
  2926 + protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
  2927 + String by = sCalledByUs ? "US" : "WeChat";
  2928 + XposedBridge.log("[WeChatHook] w11.r0.H() called by=" + by
  2929 + + " proc=" + procName + " pid=" + android.os.Process.myPid());
  2930 + // Dump all r0 fields for real WeChat voice sends only.
  2931 + // This reveals which field holds the SILK audio data that H() uses for CDN upload.
  2932 + if (!sCalledByUs) {
  2933 + dumpR0Fields(param.thisObject, "r0.H-before");
  2934 + }
  2935 + }
  2936 + @Override
  2937 + protected void afterHookedMethod(MethodHookParam param) throws Throwable {
  2938 + if (param.hasThrowable())
  2939 + XposedBridge.log("[WeChatHook] w11.r0.H() threw: " + param.getThrowable());
  2940 + else
  2941 + XposedBridge.log("[WeChatHook] w11.r0.H() OK proc=" + procName);
  2942 + }
  2943 + });
  2944 + XposedBridge.log("[WeChatHook] Hooked w11.r0.H(String) in " + procName);
  2945 + } catch (Throwable t) {
  2946 + XposedBridge.log("[WeChatHook] w11.r0.H hook failed in " + procName + ": " + t);
  2947 + }
  2948 +
  2949 + // ── r0.I(int) and r0.K(int) — delivery completion hooks ──────────────────
  2950 + // Log when WeChat calls these so we understand their role in the send flow.
  2951 + // Our u0 stub now calls r0.I(0) after onSceneEnd — this confirms whether I()
  2952 + // is the right trigger for delivery completion and spinner removal.
  2953 + try {
  2954 + XposedHelpers.findAndHookMethod("w11.r0", cl, "I", int.class,
  2955 + new XC_MethodHook() {
  2956 + @Override protected void beforeHookedMethod(MethodHookParam p) throws Throwable {
  2957 + String by = sCalledByUs ? "US" : "WeChat";
  2958 + XposedBridge.log("[WeChatHook] r0.I(" + p.args[0] + ") by=" + by + " proc=" + procName);
  2959 + }
  2960 + });
  2961 + XposedBridge.log("[WeChatHook] Hooked w11.r0.I(int) in " + procName);
  2962 + } catch (Throwable t) {
  2963 + XposedBridge.log("[WeChatHook] r0.I hook failed in " + procName + ": " + t);
  2964 + }
  2965 + try {
  2966 + XposedHelpers.findAndHookMethod("w11.r0", cl, "K", int.class,
  2967 + new XC_MethodHook() {
  2968 + @Override protected void beforeHookedMethod(MethodHookParam p) throws Throwable {
  2969 + String by = sCalledByUs ? "US" : "WeChat";
  2970 + XposedBridge.log("[WeChatHook] r0.K(" + p.args[0] + ") by=" + by + " proc=" + procName);
  2971 + }
  2972 + });
  2973 + XposedBridge.log("[WeChatHook] Hooked w11.r0.K(int) in " + procName);
  2974 + } catch (Throwable t) {
  2975 + XposedBridge.log("[WeChatHook] r0.K hook failed in " + procName + ": " + t);
  2976 + }
  2977 +
  2978 + // ── Diagnostic probes on the constructor call chain ───────────────────
  2979 + // Each probe fires when the method is called from inside the r0 constructor
  2980 + // (by WeChat OR by us). They trace which methods succeed before the NPE.
  2981 + hookProbeMethod(cl, "gm0.j1", "u", "gm0.j1.u");
  2982 + hookProbeMethod(cl, "c01.z1", "r", "c01.z1.r");
  2983 + // gm0.b0.c() is a virtual method — probe it too
  2984 + try {
  2985 + XposedHelpers.findAndHookMethod("gm0.b0", cl, "c",
  2986 + new XC_MethodHook() {
  2987 + @Override protected void beforeHookedMethod(MethodHookParam p) {
  2988 + XposedBridge.log("[WeChatHook] PROBE gm0.b0.c() called");
  2989 + }
  2990 + @Override protected void afterHookedMethod(MethodHookParam p) {
  2991 + if (p.hasThrowable()) XposedBridge.log("[WeChatHook] PROBE gm0.b0.c() THREW: " + p.getThrowable());
  2992 + else XposedBridge.log("[WeChatHook] PROBE gm0.b0.c() → " + p.getResult());
  2993 + }
  2994 + });
  2995 + } catch (Throwable t) {
  2996 + XposedBridge.log("[WeChatHook] gm0.b0.c probe failed: " + t);
  2997 + }
  2998 + }
  2999 +
  3000 + private static Object[] appendHook(Class<?>[] params, XC_MethodHook hook) {
  3001 + Object[] result = new Object[params.length + 1];
  3002 + System.arraycopy(params, 0, result, 0, params.length);
  3003 + result[params.length] = hook;
  3004 + return result;
  3005 + }
  3006 +
  3007 + private void hookProbeMethod(ClassLoader cl, String cls, String method, String tag) {
  3008 + try {
  3009 + XposedHelpers.findAndHookMethod(cls, cl, method,
  3010 + new XC_MethodHook() {
  3011 + @Override protected void beforeHookedMethod(MethodHookParam p) {
  3012 + XposedBridge.log("[WeChatHook] PROBE " + tag + "() called");
  3013 + }
  3014 + @Override protected void afterHookedMethod(MethodHookParam p) {
  3015 + if (p.hasThrowable()) XposedBridge.log("[WeChatHook] PROBE " + tag + "() THREW: " + p.getThrowable());
  3016 + else XposedBridge.log("[WeChatHook] PROBE " + tag + "() → " + p.getResult());
  3017 + }
  3018 + });
  3019 + XposedBridge.log("[WeChatHook] Probe hooked: " + tag);
  3020 + } catch (Throwable t) {
  3021 + XposedBridge.log("[WeChatHook] Probe " + tag + " failed: " + t);
  3022 + }
  3023 + }
  3024 +
  3025 + private static boolean isDIReady() {
  3026 + if (sWeChatCL == null) return false;
  3027 + try {
  3028 + XposedHelpers.callStaticMethod(XposedHelpers.findClass("gm0.j1", sWeChatCL), "i");
  3029 + return true;
  3030 + } catch (Throwable e) { return false; }
  3031 + }
  3032 +
  3033 + // Hook gm0.j1.g(km0.c) to detect when WeChat DI kernel is initialized.
  3034 + // gm0.j1.g() sets gm0.j1.m (the singleton) and is called lazily — not during
  3035 + // Application.onCreate, so our broadcast often arrives first. After g() fires,
  3036 + // gm0.j1.i() will succeed and w11.r0 can be constructed.
  3037 + private static void hookDIInit(ClassLoader cl, String procName) {
  3038 + try {
  3039 + Class<?> km0cCls = XposedHelpers.findClass("km0.c", cl);
  3040 + XposedHelpers.findAndHookMethod("gm0.j1", cl, "g", km0cCls,
  3041 + new XC_MethodHook() {
  3042 + @Override
  3043 + protected void afterHookedMethod(MethodHookParam p) throws Throwable {
  3044 + XposedBridge.log("[WeChatHook] gm0.j1.g() fired — DI ready in " + procName);
  3045 + String t = sPendingTalker, x = sPendingText, pr = sPendingProc;
  3046 + if (t != null && x != null && procName.equals(pr)) {
  3047 + sPendingTalker = null; sPendingText = null; sPendingProc = null;
  3048 + XposedBridge.log("[WeChatHook] resuming pending send to=" + t + " proc=" + procName);
  3049 + new Handler(Looper.getMainLooper()).postDelayed(
  3050 + () -> trySendWithRetry(t, x, 0, procName), 50);
  3051 + }
  3052 + }
  3053 + });
  3054 + XposedBridge.log("[WeChatHook] gm0.j1.g hook OK in " + procName);
  3055 + } catch (Throwable t) {
  3056 + XposedBridge.log("[WeChatHook] gm0.j1.g hook failed in " + procName + ": " + t);
  3057 + }
  3058 + }
  3059 +
  3060 + private static void diagMCoreStorage(String where) {
  3061 + if (sWeChatCL == null) return;
  3062 + try {
  3063 + Class<?> j1Cls = XposedHelpers.findClass("gm0.j1", sWeChatCL);
  3064 + Object j1 = XposedHelpers.callStaticMethod(j1Cls, "i");
  3065 + Object mCS = (j1 != null) ? XposedHelpers.getObjectField(j1, "d") : null;
  3066 + XposedBridge.log("[WeChatHook] " + where + " mCoreStorage=" + mCS);
  3067 + } catch (Throwable e) {
  3068 + XposedBridge.log("[WeChatHook] " + where + " mCoreStorage-check: " + e);
  3069 + }
  3070 + }
  3071 +
  3072 + private static void forceInitDI() {
  3073 + if (sWeChatCL == null) return;
  3074 + try {
  3075 + Class<?> fsgCls = XposedHelpers.findClass("fs.g", sWeChatCL);
  3076 + java.lang.reflect.Field faFld = fsgCls.getDeclaredField("a");
  3077 + faFld.setAccessible(true);
  3078 + Object[] arr = (Object[]) faFld.get(null);
  3079 +
  3080 + if (arr == null || arr.length == 0 || arr[0] == null) {
  3081 + Class<?> k2Cls = XposedHelpers.findClass("fs.k2", sWeChatCL);
  3082 + java.lang.reflect.Field k2eFld = k2Cls.getDeclaredField("e");
  3083 + k2eFld.setAccessible(true);
  3084 + Object k2e = k2eFld.get(null);
  3085 + if (k2e == null) {
  3086 + XposedBridge.log("[WeChatHook] forceInitDI: fs.k2.e null");
  3087 + return;
  3088 + }
  3089 + if (arr == null || arr.length == 0) {
  3090 + arr = new Object[1];
  3091 + faFld.set(null, arr);
  3092 + }
  3093 + arr[0] = k2e;
  3094 + XposedBridge.log("[WeChatHook] forceInitDI: fs.g.a[0]=" + k2e.getClass().getName());
  3095 + }
  3096 + } catch (Throwable e) {
  3097 + XposedBridge.log("[WeChatHook] forceInitDI: " + e);
  3098 + }
  3099 + }
  3100 +
  3101 + private static void trySendWithRetry(String talker, String text, int attempt, String procName) {
  3102 + // Non-main WeChat processes (:push, :tools, etc.) lack storage init — fail immediately.
  3103 + if (procName != null && procName.contains(":")) {
  3104 + if (attempt == 0) XposedBridge.log("[WeChatHook] Skip send in non-main proc=" + procName);
  3105 + return;
  3106 + }
  3107 + // Route A2: tg3.t1 high-level service locator
  3108 + try {
  3109 + sendViaHighLevel(talker, text);
  3110 + XposedBridge.log("[WeChatHook] HighLevel send OK to=" + talker + " proc=" + procName);
  3111 + return;
  3112 + } catch (Throwable t) {
  3113 + if (attempt == 0)
  3114 + XposedBridge.log("[WeChatHook] HighLevel FAILED proc=" + procName + ": " + t);
  3115 + }
  3116 +
  3117 + // Route A1b: w11.s1 factory (mid-level)
  3118 + try {
  3119 + sendViaFactory(talker, text);
  3120 + XposedBridge.log("[WeChatHook] Factory send OK to=" + talker + " proc=" + procName);
  3121 + return;
  3122 + } catch (Throwable t) {
  3123 + // Log every 5 attempts to track what's changing
  3124 + if (attempt % 5 == 0)
  3125 + XposedBridge.log("[WeChatHook] Factory FAILED attempt=" + attempt
  3126 + + " proc=" + procName + ": " + t);
  3127 + }
  3128 +
  3129 + // Route A1: w11.r0 direct (requires gm0.j1 DI ready)
  3130 + if (isDIReady()) {
  3131 + try {
  3132 + sendViaR0(talker, text);
  3133 + XposedBridge.log("[WeChatHook] R0 send OK to=" + talker + " proc=" + procName);
  3134 + return;
  3135 + } catch (Throwable t) {
  3136 + if (attempt == 0)
  3137 + XposedBridge.log("[WeChatHook] R0 FAILED proc=" + procName + ": " + t);
  3138 + }
  3139 + }
  3140 +
  3141 + // All paths failed — poll every 1s up to 60 attempts waiting for WeChat DI init
  3142 + if (attempt < 60) {
  3143 + if (attempt == 0)
  3144 + XposedBridge.log("[WeChatHook] All paths not ready, polling proc=" + procName
  3145 + + " to=" + talker);
  3146 + new Handler(Looper.getMainLooper()).postDelayed(
  3147 + () -> trySendWithRetry(talker, text, attempt + 1, procName), 1000);
  3148 + } else {
  3149 + XposedBridge.log("[WeChatHook] GIVE UP after 60s proc=" + procName + " to=" + talker);
  3150 + }
  3151 + }
  3152 +
  3153 + // Route A1b: w11.s1 factory — SendMsgCgiFactory.a(talker) → w11.r1.e(content).b()
  3154 + private static void sendViaFactory(String talker, String text) throws Throwable {
  3155 + ClassLoader cl = sTinkerCL != null ? sTinkerCL : sWeChatCL;
  3156 + if (cl == null) throw new IllegalStateException("classloader null");
  3157 + Class<?> s1 = XposedHelpers.findClass("w11.s1", cl);
  3158 + Object r1 = XposedHelpers.callStaticMethod(s1, "a", talker);
  3159 + if (r1 == null) throw new IllegalStateException("w11.s1.a() returned null");
  3160 + try {
  3161 + XposedHelpers.callMethod(r1, "e", text);
  3162 + } catch (Throwable t) {
  3163 + throw new RuntimeException("r1.e() failed: " + t, t);
  3164 + }
  3165 + try {
  3166 + XposedHelpers.callMethod(r1, "b");
  3167 + } catch (Throwable t) {
  3168 + throw new RuntimeException("r1.b() failed: " + t, t);
  3169 + }
  3170 + }
  3171 +
  3172 + // Route A2: high-level API via tg3.t1 service locator → dk5.s5.Ni().
  3173 + // This path is what WeChat UI uses — internally handles DI, account context, etc.
  3174 + private static void sendViaHighLevel(String talker, String text) throws Throwable {
  3175 + ClassLoader cl = sTinkerCL != null ? sTinkerCL : sWeChatCL;
  3176 + if (cl == null) throw new IllegalStateException("classloader null");
  3177 + // Text = same PROVEN path as voice sendVoiceViaAPI: w11.r0 ctor (type=1) inserts
  3178 + // the f9 into the DB, then z2.b(NetSceneQueue) dispatches over the real network.
  3179 + // Text carries no CDN attachment, so unlike voice it completes fully. (The s1.a /
  3180 + // s1.b / dk5.s5.Ni builder paths either produced name-cards or silently failed to
  3181 + // persist — they need hidden r1 fields + MsgRetransmitUI.P6 that we can't set robustly.)
  3182 + Class<?> r0Class = XposedHelpers.findClass("w11.r0", cl);
  3183 + Object r0;
  3184 + sCalledByUs = true;
  3185 + try {
  3186 + // Object-ctor is the one that actually inserts the f9 (confirmed by
  3187 + // sendVoiceViaAPI). obj=null for text (no audio/msgsource extras).
  3188 + r0 = XposedHelpers.newInstance(r0Class,
  3189 + new Class<?>[]{String.class, String.class, int.class, int.class, Object.class},
  3190 + talker, text, 1, 0, null); // (talker, content, type=1 TEXT, flag=0, null)
  3191 + } finally { sCalledByUs = false; }
  3192 + Class<?> z2c = XposedHelpers.findClass("com.tencent.mm.modelbase.z2", cl);
  3193 + XposedHelpers.callStaticMethod(z2c, "b", r0); // enqueue → doScene → newsendmsg
  3194 + XposedBridge.log("[WeChatHook] sendViaHighLevel(TEXT via r0-obj+z2.b): OK to=" + talker);
  3195 + }
  3196 +
  3197 + private static void registerSendReceiver(Context ctx, String procName) {
  3198 + // SEND_MSG_INTERNAL: send a text message
  3199 + BroadcastReceiver sendRecv = new BroadcastReceiver() {
  3200 + @Override
  3201 + public void onReceive(Context context, Intent intent) {
  3202 + String talker = intent.getStringExtra("to");
  3203 + String rawText = intent.getStringExtra("text");
  3204 + // Non-ASCII (Chinese) via `am broadcast --es text` gets mangled by the
  3205 + // shell/am → server rejects → stuck "sending". Prefer base64: send with
  3206 + // --es text_b64 <base64(utf-8)> and we decode it here intact.
  3207 + String textB64 = intent.getStringExtra("text_b64");
  3208 + if (textB64 != null && !textB64.isEmpty()) {
  3209 + try {
  3210 + rawText = new String(android.util.Base64.decode(textB64, android.util.Base64.DEFAULT), "UTF-8");
  3211 + } catch (Throwable t) {
  3212 + XposedBridge.log("[WeChatHook] SEND_MSG_INTERNAL: bad text_b64: " + t);
  3213 + }
  3214 + }
  3215 + final String text = rawText;
  3216 + if (talker == null || talker.isEmpty() || text == null || text.isEmpty()) {
  3217 + XposedBridge.log("[WeChatHook] SEND_MSG_INTERNAL: missing 'to' or 'text'/'text_b64'");
  3218 + return;
  3219 + }
  3220 + XposedBridge.log("[WeChatHook] SEND_MSG_INTERNAL proc=" + procName
  3221 + + " pid=" + android.os.Process.myPid()
  3222 + + " to=" + talker + " len=" + text.length());
  3223 + new Handler(Looper.getMainLooper()).post(() -> trySendWithRetry(talker, text, 0, procName));
  3224 + }
  3225 + };
  3226 + ctx.registerReceiver(sendRecv, new IntentFilter(ACTION_SEND), Context.RECEIVER_NOT_EXPORTED);
  3227 +
  3228 + // SEND_IMAGE_INTERNAL: send an image via w11.s1.b internal API
  3229 + // Usage: adb shell su -c 'am broadcast -a com.hermes.wechat.SEND_IMAGE_INTERNAL \
  3230 + // --es to "filehelper" --es path "/sdcard/test.jpg"'
  3231 + BroadcastReceiver imgRecv = new BroadcastReceiver() {
  3232 + @Override
  3233 + public void onReceive(Context context, Intent intent) {
  3234 + // Only handle in main WeChat process (sub-processes lack storage init)
  3235 + if (procName.contains(":")) return;
  3236 + String talker = intent.getStringExtra("to");
  3237 + String path = intent.getStringExtra("path");
  3238 + if (talker == null || talker.isEmpty() || path == null || path.isEmpty()) {
  3239 + XposedBridge.log("[WeChatHook] SEND_IMAGE_INTERNAL: missing 'to' or 'path'");
  3240 + return;
  3241 + }
  3242 + XposedBridge.log("[WeChatHook] SEND_IMAGE_INTERNAL proc=" + procName
  3243 + + " to=" + talker + " path=" + path);
  3244 + new Handler(Looper.getMainLooper()).post(() -> {
  3245 + try {
  3246 + sendImageViaAPI(talker, path);
  3247 + } catch (Throwable t) {
  3248 + XposedBridge.log("[WeChatHook] SEND_IMAGE_INTERNAL failed: " + t
  3249 + + "\n" + android.util.Log.getStackTraceString(t));
  3250 + }
  3251 + });
  3252 + }
  3253 + };
  3254 + ctx.registerReceiver(imgRecv, new IntentFilter(ACTION_SEND_IMAGE), Context.RECEIVER_NOT_EXPORTED);
  3255 +
  3256 + // SEND_VOICE_INTERNAL: send a voice message via w11.r0 + f9 internal API.
  3257 + // The caller (root, Python helper) must pre-place the SILK file at:
  3258 + // /data/data/com.tencent.mm/MicroMsg/{hash}/voice2/{md5(id)[0:2]}/{md5(id)[2:4]}/msg_{id}.amr
  3259 + // Usage: adb shell su -c 'am broadcast -a com.hermes.wechat.SEND_VOICE_INTERNAL \
  3260 + // --es to "filehelper" --es voice_id "26hexchars" --ei duration 3000 [--es from_wxid "wxid_..."]'
  3261 + BroadcastReceiver voiceRecv = new BroadcastReceiver() {
  3262 + @Override
  3263 + public void onReceive(Context context, Intent intent) {
  3264 + if (procName.contains(":")) return;
  3265 + String talker = intent.getStringExtra("to");
  3266 + String voiceId = intent.getStringExtra("voice_id"); // pre-placed file
  3267 + String srcPath = intent.getStringExtra("src_path"); // hook copies from here
  3268 + int duration = intent.getIntExtra("duration", 0);
  3269 + String fromWxId = intent.getStringExtra("from_wxid");
  3270 + if (talker == null || talker.isEmpty()
  3271 + || (voiceId == null && srcPath == null)) {
  3272 + XposedBridge.log("[WeChatHook] SEND_VOICE_INTERNAL: need 'to' + 'voice_id' or 'src_path'");
  3273 + return;
  3274 + }
  3275 + if (duration <= 0) {
  3276 + XposedBridge.log("[WeChatHook] SEND_VOICE_INTERNAL: missing 'duration'");
  3277 + return;
  3278 + }
  3279 + XposedBridge.log("[WeChatHook] SEND_VOICE_INTERNAL proc=" + procName
  3280 + + " to=" + talker + " voice_id=" + voiceId + " src=" + srcPath + " dur=" + duration);
  3281 + final String fVoiceId = voiceId, fSrcPath = srcPath;
  3282 + new Handler(Looper.getMainLooper()).post(() -> {
  3283 + try {
  3284 + sendVoiceViaAPI(talker, fVoiceId, fSrcPath, duration, fromWxId);
  3285 + } catch (Throwable t) {
  3286 + XposedBridge.log("[WeChatHook] SEND_VOICE_INTERNAL failed: " + t
  3287 + + "\n" + android.util.Log.getStackTraceString(t));
  3288 + }
  3289 + });
  3290 + }
  3291 + };
  3292 + ctx.registerReceiver(voiceRecv, new IntentFilter(ACTION_SEND_VOICE), Context.RECEIVER_NOT_EXPORTED);
  3293 +
  3294 + // SEND_VOICE_CGI: fully-synthetic voice via the uploadvoice cgi (this device's
  3295 + // real path). No recording, no hot-swap — chunk the SILK and submit uploadvoice
  3296 + // scenes via z2.b. Usage: am broadcast -a com.hermes.wechat.SEND_VOICE_CGI \
  3297 + // --es to filehelper --es src_path /path/to.silk --ei duration 3000 [--es from_wxid ..]
  3298 + BroadcastReceiver voiceCgiRecv = new BroadcastReceiver() {
  3299 + @Override
  3300 + public void onReceive(Context context, Intent intent) {
  3301 + if (procName.contains(":")) return; // main process only
  3302 + String talker = intent.getStringExtra("to");
  3303 + String srcPath = intent.getStringExtra("src_path");
  3304 + int duration = intent.getIntExtra("duration", 0);
  3305 + String fromWxId = intent.getStringExtra("from_wxid");
  3306 + if (talker == null || talker.isEmpty() || srcPath == null || srcPath.isEmpty()) {
  3307 + XposedBridge.log("[WeChatHook] SEND_VOICE_CGI: need 'to' + 'src_path'"); return;
  3308 + }
  3309 + if (duration <= 0) { XposedBridge.log("[WeChatHook] SEND_VOICE_CGI: missing 'duration'"); return; }
  3310 + XposedBridge.log("[WeChatHook] SEND_VOICE_CGI proc=" + procName + " to=" + talker
  3311 + + " src=" + srcPath + " dur=" + duration);
  3312 + new Handler(Looper.getMainLooper()).post(() -> {
  3313 + try {
  3314 + sendVoiceViaCgi(talker, srcPath, duration, fromWxId);
  3315 + } catch (Throwable t) {
  3316 + XposedBridge.log("[WeChatHook] SEND_VOICE_CGI failed: " + t
  3317 + + "\n" + android.util.Log.getStackTraceString(t));
  3318 + }
  3319 + });
  3320 + }
  3321 + };
  3322 + ctx.registerReceiver(voiceCgiRecv, new IntentFilter(ACTION_SEND_VOICE_CGI), Context.RECEIVER_NOT_EXPORTED);
  3323 +
  3324 + // ARM_VOICE_SWAP: load our TTS SILK into memory and arm the jg0.x.w swap.
  3325 + // After arming, trigger a REAL recording (hold "按住说话") to the target chat —
  3326 + // WeChat records, but jg0.x.w uploads our TTS bytes instead → delivered.
  3327 + // Usage: am broadcast -a com.hermes.wechat.ARM_VOICE_SWAP \
  3328 + // --es src_path /data/data/com.tencent.mm/cache/hook_voice_src.amr --ei duration 3200
  3329 + BroadcastReceiver armRecv = new BroadcastReceiver() {
  3330 + @Override
  3331 + public void onReceive(Context context, Intent intent) {
  3332 + if (procName.contains(":")) return; // main process only (where recording runs)
  3333 + String srcPath = intent.getStringExtra("src_path");
  3334 + int duration = intent.getIntExtra("duration", 0);
  3335 + if (srcPath == null || srcPath.isEmpty()) {
  3336 + XposedBridge.log("[WeChatHook] ARM_VOICE_SWAP: missing 'src_path'");
  3337 + return;
  3338 + }
  3339 + try {
  3340 + java.io.File f = new java.io.File(srcPath);
  3341 + byte[] bytes = new byte[(int) f.length()];
  3342 + try (java.io.FileInputStream in = new java.io.FileInputStream(f)) {
  3343 + int off = 0, n;
  3344 + while (off < bytes.length && (n = in.read(bytes, off, bytes.length - off)) > 0) off += n;
  3345 + }
  3346 + sSwapSilk = bytes;
  3347 + sSwapDuration = duration;
  3348 + sSwapExpiresAt = System.currentTimeMillis() + Math.max(duration, 0) + 10000;
  3349 + sSwapArmed = true;
  3350 + XposedBridge.log("[WeChatHook] ARM_VOICE_SWAP: armed " + bytes.length
  3351 + + "B dur=" + duration + "ms from " + srcPath
  3352 + + " (expires in " + ((sSwapExpiresAt - System.currentTimeMillis()) / 1000)
  3353 + + "s — trigger a real recording now)");
  3354 + } catch (Throwable t) {
  3355 + XposedBridge.log("[WeChatHook] ARM_VOICE_SWAP failed: " + t);
  3356 + }
  3357 + }
  3358 + };
  3359 + ctx.registerReceiver(armRecv, new IntentFilter(ACTION_ARM_SWAP), Context.RECEIVER_NOT_EXPORTED);
  3360 +
  3361 + // DUMP_WECHAT_API: on-demand class introspection (main process only)
  3362 + // Usage: adb shell su -c 'am broadcast -a com.hermes.wechat.DUMP_WECHAT_API [--es class "w11.s1"]'
  3363 + BroadcastReceiver dumpRecv = new BroadcastReceiver() {
  3364 + @Override
  3365 + public void onReceive(Context context, Intent intent) {
  3366 + XposedBridge.log("[WeChatHook] DUMP_WECHAT_API received in " + procName);
  3367 + new Handler(Looper.getMainLooper()).post(() -> handleDumpApi(intent));
  3368 + }
  3369 + };
  3370 + ctx.registerReceiver(dumpRecv, new IntentFilter(ACTION_DUMP_API), Context.RECEIVER_NOT_EXPORTED);
  3371 +
  3372 + XposedBridge.log("[WeChatHook] BroadcastReceivers registered in " + procName);
  3373 + }
  3374 +
  3375 + private static void sendViaR0(String talker, String text) throws Throwable {
  3376 + ClassLoader cl = sTinkerCL != null ? sTinkerCL : sWeChatCL;
  3377 + if (cl == null) throw new IllegalStateException("classloader null");
  3378 + Class<?> r0Class = XposedHelpers.findClass("w11.r0", cl);
  3379 + long ts = System.currentTimeMillis();
  3380 + Object msg;
  3381 + sCalledByUs = true;
  3382 + try {
  3383 + try {
  3384 + msg = XposedHelpers.newInstance(r0Class,
  3385 + new Class<?>[]{String.class, String.class, int.class, int.class, long.class},
  3386 + talker, text, 1, 0, ts);
  3387 + } catch (Throwable t) {
  3388 + msg = XposedHelpers.newInstance(r0Class,
  3389 + new Class<?>[]{String.class, String.class, int.class, int.class, Object.class},
  3390 + talker, text, 1, 0, (Object) ts);
  3391 + }
  3392 + } finally {
  3393 + sCalledByUs = false;
  3394 + }
  3395 +
  3396 + try {
  3397 + Class<?> u0 = XposedHelpers.findClass("com.tencent.mm.modelbase.u0", cl);
  3398 + Object stub = Proxy.newProxyInstance(cl, new Class<?>[]{u0},
  3399 + (proxy, method, args) -> {
  3400 + XposedBridge.log("[WeChatHook] send-cb: " + method.getName());
  3401 + return null;
  3402 + });
  3403 + XposedHelpers.setObjectField(msg, "d", stub);
  3404 + } catch (Throwable ignored) {}
  3405 +
  3406 + sCalledByUs = true;
  3407 + try {
  3408 + XposedHelpers.callMethod(msg, "H", "");
  3409 + } finally {
  3410 + sCalledByUs = false;
  3411 + }
  3412 + }
  3413 +}
xhs_lsposed_a16_fix/wechathook_src/WeChatHook.java
@@ -56,6 +56,9 @@ public class WeChatHook implements IXposedHookLoadPackage { @@ -56,6 +56,9 @@ public class WeChatHook implements IXposedHookLoadPackage {
56 // Network dispatcher captured from a real WeChat r0 at H()-entry; needed by CDN upload 56 // Network dispatcher captured from a real WeChat r0 at H()-entry; needed by CDN upload
57 private static volatile Object sCapturedDispatcher = null; 57 private static volatile Object sCapturedDispatcher = null;
58 private static volatile Object sPt0E0Instance = null; // pt0.e0 singleton, captured from r() hook 58 private static volatile Object sPt0E0Instance = null; // pt0.e0 singleton, captured from r() hook
  59 + // Keeps synthetic-voice-cgi i/deferred objects strongly referenced (the deferred
  60 + // holds the CgiLifecycleObserver weakly, so without this GC kills the in-flight send).
  61 + private static final java.util.List<Object> sVoiceCgiKeepAlive = new java.util.concurrent.CopyOnWriteArrayList<>();
59 private static volatile Object sImgPlugin = null; // b80.u instance, captured from pj/Bi hook 62 private static volatile Object sImgPlugin = null; // b80.u instance, captured from pj/Bi hook
60 private static volatile Object sRealImgParams = null; // last real o70.h, captured for replication 63 private static volatile Object sRealImgParams = null; // last real o70.h, captured for replication
61 private static volatile Object sRealImgK = null; // last real o70.k (oj insert object) 64 private static volatile Object sRealImgK = null; // last real o70.k (oj insert object)
@@ -149,6 +152,7 @@ public class WeChatHook implements IXposedHookLoadPackage { @@ -149,6 +152,7 @@ public class WeChatHook implements IXposedHookLoadPackage {
149 hookCdnTrace(cl, lpparam.processName); 152 hookCdnTrace(cl, lpparam.processName);
150 // Capture the real uploadvoice cgi request (this device uses inline-cgi, not CDN). 153 // Capture the real uploadvoice cgi request (this device uses inline-cgi, not CDN).
151 hookVoiceCgiCapture(cl, lpparam.processName); 154 hookVoiceCgiCapture(cl, lpparam.processName);
  155 + hookVoiceCgiResult(cl, lpparam.processName);
152 } 156 }
153 157
154 // ── WCDB hook ────────────────────────────────────────────────────────────── 158 // ── WCDB hook ──────────────────────────────────────────────────────────────
@@ -1452,6 +1456,40 @@ public class WeChatHook implements IXposedHookLoadPackage { @@ -1452,6 +1456,40 @@ public class WeChatHook implements IXposedHookLoadPackage {
1452 // SAME queue our text send uses. Hook modelbase.l.a() (the reqresp builder, fires 1456 // SAME queue our text send uses. Hook modelbase.l.a() (the reqresp builder, fires
1453 // mid-jg0.x.w) filtered to the uploadvoice url, and dump every cv6 field index so 1457 // mid-jg0.x.w) filtered to the uploadvoice url, and dump every cv6 field index so
1454 // we can replicate the exact wire request for fully-synthetic voice. 1458 // we can replicate the exact wire request for fully-synthetic voice.
  1459 + // Diagnostic: hook modelbase.i.k(errType,errCode,errMsg,respPb,scene) = scene-end
  1460 + // callback. Logs the result of any uploadvoice send (resp pb = r45.dv6), so we can
  1461 + // tell if our synthetic z2.b send was dispatched + accepted (errCode 0) or rejected.
  1462 + private void hookVoiceCgiResult(ClassLoader cl, String procName) {
  1463 + try {
  1464 + Class<?> iCls = XposedHelpers.findClass("com.tencent.mm.modelbase.i", cl);
  1465 + Class<?> pbCls = XposedHelpers.findClass("com.tencent.mm.protobuf.f", cl);
  1466 + Class<?> m1Cls = XposedHelpers.findClass("com.tencent.mm.modelbase.m1", cl);
  1467 + int n = 0;
  1468 + for (java.lang.reflect.Method m : iCls.getDeclaredMethods()) {
  1469 + Class<?>[] pt = m.getParameterTypes();
  1470 + // onSceneEnd: (int, int, String, protobuf.f, m1)
  1471 + if (pt.length == 5 && pt[0] == int.class && pt[1] == int.class && pt[2] == String.class
  1472 + && pbCls.isAssignableFrom(pt[3]) && m1Cls.isAssignableFrom(pt[4])) {
  1473 + m.setAccessible(true);
  1474 + XposedBridge.hookMethod(m, new XC_MethodHook() {
  1475 + @Override protected void beforeHookedMethod(MethodHookParam p) {
  1476 + try {
  1477 + Object resp = p.args[3];
  1478 + if (resp == null || !resp.getClass().getName().equals("r45.dv6")) return;
  1479 + long svr = 0; try { Object v = XposedHelpers.callMethod(resp, "getLong", 11); if (v != null) svr = (Long) v; } catch (Throwable t) {}
  1480 + XposedBridge.log("[WeChatHook] VOICECGI-RESULT errType=" + p.args[0]
  1481 + + " errCode=" + p.args[1] + " errMsg=" + p.args[2]
  1482 + + " respClass=" + resp.getClass().getName() + " svrMsgId(11)=" + svr);
  1483 + } catch (Throwable t) { XposedBridge.log("[WeChatHook] VOICECGI-RESULT err: " + t); }
  1484 + }
  1485 + });
  1486 + n++;
  1487 + }
  1488 + }
  1489 + XposedBridge.log("[WeChatHook] hookVoiceCgiResult: hooked i.onSceneEnd x" + n + " in " + procName);
  1490 + } catch (Throwable t) { XposedBridge.log("[WeChatHook] hookVoiceCgiResult failed in " + procName + ": " + t); }
  1491 + }
  1492 +
1455 private void hookVoiceCgiCapture(ClassLoader cl, String procName) { 1493 private void hookVoiceCgiCapture(ClassLoader cl, String procName) {
1456 try { 1494 try {
1457 Class<?> lCls = XposedHelpers.findClass("com.tencent.mm.modelbase.l", cl); 1495 Class<?> lCls = XposedHelpers.findClass("com.tencent.mm.modelbase.l", cl);
@@ -1698,13 +1736,25 @@ public class WeChatHook implements IXposedHookLoadPackage { @@ -1698,13 +1736,25 @@ public class WeChatHook implements IXposedHookLoadPackage {
1698 String self = (fromWxId != null && !fromWxId.isEmpty()) ? fromWxId 1736 String self = (fromWxId != null && !fromWxId.isEmpty()) ? fromWxId
1699 : (sMyWxid != null ? sMyWxid : "wxid_51ap3m6p9xs722"); 1737 : (sMyWxid != null ? sMyWxid : "wxid_51ap3m6p9xs722");
1700 1738
1701 - Class<?> z2c = XposedHelpers.findClass("com.tencent.mm.modelbase.z2", cl);  
1702 Class<?> cv6C = XposedHelpers.findClass("r45.cv6", cl); 1739 Class<?> cv6C = XposedHelpers.findClass("r45.cv6", cl);
1703 Class<?> dv6C = XposedHelpers.findClass("r45.dv6", cl); 1740 Class<?> dv6C = XposedHelpers.findClass("r45.dv6", cl);
1704 Class<?> cu5C = XposedHelpers.findClass("r45.cu5", cl); 1741 Class<?> cu5C = XposedHelpers.findClass("r45.cu5", cl);
1705 Class<?> oCls = XposedHelpers.findClass("com.tencent.mm.modelbase.o", cl); 1742 Class<?> oCls = XposedHelpers.findClass("com.tencent.mm.modelbase.o", cl);
1706 Class<?> iCls = XposedHelpers.findClass("com.tencent.mm.modelbase.i", cl); 1743 Class<?> iCls = XposedHelpers.findClass("com.tencent.mm.modelbase.i", cl);
1707 Class<?> m1Cls = XposedHelpers.findClass("com.tencent.mm.modelbase.m1", cl); 1744 Class<?> m1Cls = XposedHelpers.findClass("com.tencent.mm.modelbase.m1", cl);
  1745 + Class<?> pq5g = XposedHelpers.findClass("pq5.g", cl);
  1746 + Class<?> km5d = XposedHelpers.findClass("km5.d", cl);
  1747 + // i.l() (no-arg → pq5.g) registers the response consumer + returns the deferred;
  1748 + // pq5.g.l(long) (long → km5.d) is the terminal subscribe that fires the cgi.
  1749 + java.lang.reflect.Method runM = null;
  1750 + for (java.lang.reflect.Method m : iCls.getDeclaredMethods())
  1751 + if (m.getParameterCount() == 0 && m.getReturnType() == pq5g) { runM = m; runM.setAccessible(true); break; }
  1752 + java.lang.reflect.Method subM = null;
  1753 + for (java.lang.reflect.Method m : pq5g.getDeclaredMethods()) {
  1754 + Class<?>[] pt = m.getParameterTypes();
  1755 + if (pt.length == 1 && pt[0] == long.class && m.getReturnType() == km5d) { subM = m; subM.setAccessible(true); break; }
  1756 + }
  1757 + if (runM == null || subM == null) throw new IllegalStateException("i.l()/pq5.g.l(long) not found: run=" + runM + " sub=" + subM);
1708 1758
1709 // modelbase.o(req, resp, url, cmdid, 0, 0, true, 0, 0, false, 0, false, null) — find by arg count. 1759 // modelbase.o(req, resp, url, cmdid, 0, 0, true, 0, 0, false, 0, false, null) — find by arg count.
1710 java.lang.reflect.Constructor<?> oCtor = null; 1760 java.lang.reflect.Constructor<?> oCtor = null;
@@ -1731,6 +1781,7 @@ public class WeChatHook implements IXposedHookLoadPackage { @@ -1731,6 +1781,7 @@ public class WeChatHook implements IXposedHookLoadPackage {
1731 final String URL = "/cgi-bin/micromsg-bin/uploadvoice"; 1781 final String URL = "/cgi-bin/micromsg-bin/uploadvoice";
1732 final int CHUNK = 6000; 1782 final int CHUNK = 6000;
1733 int total = silk.length, chunks = 0; 1783 int total = silk.length, chunks = 0;
  1784 + Object lastDv6 = null;
1734 sCalledByUs = true; 1785 sCalledByUs = true;
1735 try { 1786 try {
1736 for (int off = 0; off < total; off += CHUNK) { 1787 for (int off = 0; off < total; off += CHUNK) {
@@ -1751,20 +1802,66 @@ public class WeChatHook implements IXposedHookLoadPackage { @@ -1751,20 +1802,66 @@ public class WeChatHook implements IXposedHookLoadPackage {
1751 XposedHelpers.callMethod(cv6, "set", 8, Integer.valueOf(last ? 1 : 0)); 1802 XposedHelpers.callMethod(cv6, "set", 8, Integer.valueOf(last ? 1 : 0));
1752 XposedHelpers.callMethod(cv6, "set", 11, ""); // msgsource (empty for filehelper) 1803 XposedHelpers.callMethod(cv6, "set", 11, ""); // msgsource (empty for filehelper)
1753 XposedHelpers.callMethod(cv6, "set", 12, Integer.valueOf(4)); 1804 XposedHelpers.callMethod(cv6, "set", 12, Integer.valueOf(4));
  1805 + // [15] = per-message create id (long). Real sends carry it; derive a
  1806 + // large positive nonce from the voiceId so the server has a stable value.
  1807 + long createId = (System.currentTimeMillis() << 20) ^ (voiceId.hashCode() & 0xffffffffL);
  1808 + if (createId < 0) createId = -createId;
  1809 + XposedHelpers.callMethod(cv6, "set", 15, Long.valueOf(createId));
1754 1810
1755 Object dv6 = XposedHelpers.newInstance(dv6C); 1811 Object dv6 = XposedHelpers.newInstance(dv6C);
  1812 + lastDv6 = dv6;
1756 Object o = oCtor.newInstance(cv6, dv6, URL, 127, 0, 0, Boolean.TRUE, 0, 0, Boolean.FALSE, 0, Boolean.FALSE, null); 1813 Object o = oCtor.newInstance(cv6, dv6, URL, 127, 0, 0, Boolean.TRUE, 0, 0, Boolean.FALSE, 0, Boolean.FALSE, null);
1757 Object iInst = XposedHelpers.newInstance(iCls); 1814 Object iInst = XposedHelpers.newInstance(iCls);
1758 pM.invoke(iInst, o); 1815 pM.invoke(iInst, o);
1759 Object scene = sceneF.get(iInst); 1816 Object scene = sceneF.get(iInst);
1760 - XposedHelpers.callStaticMethod(z2c, "b", scene); // enqueue like text send 1817 + // Dispatch: i.l() registers the response consumer + returns the deferred,
  1818 + // then pq5.g.l(timeout) subscribes → the cgi actually runs. Bare z2.b(g)
  1819 + // doesn't wire the callback, so the scene never completes.
  1820 + Object deferred = runM.invoke(iInst);
  1821 + sVoiceCgiKeepAlive.add(iInst); // deferred holds i weakly
  1822 + if (deferred != null) { sVoiceCgiKeepAlive.add(deferred); subM.invoke(deferred, 30000L); }
1761 chunks++; 1823 chunks++;
1762 XposedBridge.log("[WeChatHook] sendVoiceViaCgi: chunk off=" + off + " len=" + len 1824 XposedBridge.log("[WeChatHook] sendVoiceViaCgi: chunk off=" + off + " len=" + len
1763 - + " last=" + last + " scene=" + (scene == null ? "null" : scene.getClass().getName())); 1825 + + " last=" + last + " scene=" + (scene == null ? "null" : scene.getClass().getName())
  1826 + + " deferred=" + (deferred == null ? "null" : deferred.getClass().getName()));
1764 } 1827 }
1765 } finally { sCalledByUs = false; } 1828 } finally { sCalledByUs = false; }
1766 XposedBridge.log("[WeChatHook] sendVoiceViaCgi: submitted " + chunks + " chunk(s) to=" + talker 1829 XposedBridge.log("[WeChatHook] sendVoiceViaCgi: submitted " + chunks + " chunk(s) to=" + talker
1767 + " voiceId=" + voiceId + " silk=" + total + "B dur=" + durationMs + " self=" + self); 1830 + " voiceId=" + voiceId + " silk=" + total + "B dur=" + durationMs + " self=" + self);
  1831 +
  1832 + // Read the server response off the SAME dv6 we passed (WeChat parses the cgi
  1833 + // reply into it). getLong(11) = assigned server msgId; >0 means the server
  1834 + // accepted the voice = delivered. Poll a few times since z2.b is async.
  1835 + final Object fDv6 = lastDv6;
  1836 + final String fVoice = voiceId;
  1837 + if (fDv6 != null) {
  1838 + final Handler h = new Handler(Looper.getMainLooper());
  1839 + final int[] tries = {0};
  1840 + Runnable poll = new Runnable() {
  1841 + @Override public void run() {
  1842 + tries[0]++;
  1843 + try {
  1844 + long svrMsgId = 0; try { Object v = XposedHelpers.callMethod(fDv6, "getLong", 11); if (v != null) svrMsgId = (Long) v; } catch (Throwable t) {}
  1845 + int netOff = 0; try { Object v = XposedHelpers.callMethod(fDv6, "getInteger", 2); if (v != null) netOff = (Integer) v; } catch (Throwable t) {}
  1846 + if (svrMsgId != 0 || netOff != 0 || tries[0] >= 6) {
  1847 + StringBuilder sb = new StringBuilder("[WeChatHook] sendVoiceViaCgi RESP try=" + tries[0]
  1848 + + " voiceId=" + fVoice + " svrMsgId(11)=" + svrMsgId + " netOffset(2)=" + netOff + " dv6:");
  1849 + for (int i = 0; i <= 15; i++) {
  1850 + Object val = null;
  1851 + try { Object s = XposedHelpers.callMethod(fDv6, "getString", i); if (s != null && !"".equals(s)) val = "S:" + s; } catch (Throwable t) {}
  1852 + if (val == null) { try { Object iv = XposedHelpers.callMethod(fDv6, "getInteger", i); if (iv != null && ((Integer) iv) != 0) val = "I:" + iv; } catch (Throwable t) {} }
  1853 + if (val == null) { try { Object lv = XposedHelpers.callMethod(fDv6, "getLong", i); if (lv != null && ((Long) lv) != 0L) val = "L:" + lv; } catch (Throwable t) {} }
  1854 + if (val != null) sb.append("\n [").append(i).append("]=").append(val);
  1855 + }
  1856 + XposedBridge.log(sb.toString());
  1857 + } else {
  1858 + h.postDelayed(this, 1500);
  1859 + }
  1860 + } catch (Throwable t) { XposedBridge.log("[WeChatHook] sendVoiceViaCgi RESP err: " + t); }
  1861 + }
  1862 + };
  1863 + h.postDelayed(poll, 1500);
  1864 + }
1768 } 1865 }
1769 1866
1770 private static void sendVoiceViaAPI(String talker, String voiceId, String srcPath, 1867 private static void sendVoiceViaAPI(String talker, String voiceId, String srcPath,
@@ -2762,6 +2859,7 @@ public class WeChatHook implements IXposedHookLoadPackage { @@ -2762,6 +2859,7 @@ public class WeChatHook implements IXposedHookLoadPackage {
2762 hookCdnTrace(sTinkerCL, procName + "/tinker"); 2859 hookCdnTrace(sTinkerCL, procName + "/tinker");
2763 // Capture the real uploadvoice cgi request in Tinker CL. 2860 // Capture the real uploadvoice cgi request in Tinker CL.
2764 hookVoiceCgiCapture(sTinkerCL, procName + "/tinker"); 2861 hookVoiceCgiCapture(sTinkerCL, procName + "/tinker");
  2862 + hookVoiceCgiResult(sTinkerCL, procName + "/tinker");
2765 } 2863 }
2766 hookF9ConvertTo(sWeChatCL, procName); 2864 hookF9ConvertTo(sWeChatCL, procName);
2767 hookF9ImgPathInjector(sWeChatCL, procName); 2865 hookF9ImgPathInjector(sWeChatCL, procName);