Commit 700a802c42c14eba8446ba28b19d1dfd62be3802

Authored by yibo
1 parent 3f6b3266

feat(wechathook): 语音全合成 sendVoiceViaCgi — uploadvoice cgi + z2.b(提交跑通)

按捕获的 wire 协议实现全合成语音(无录音、无 hot-swap):
- 读 SILK → 按 6000 字节分块 → 每块建 r45.cv6 请求 pb([0]self [1]talker
  [2]offset [3]len [4]"newSendVoice_"+voiceId [6]dur [7]cu5(SILK切片) [8]end
  [11]msgsource [12]=4)→ 经 modelbase.o 13参构造器(绕过 modelbase.l 字段名
  base≠tinker 不匹配) → modelbase.i.p(o)(按签名定位) → scene modelbase.g(m1)
  → z2.b(scene) 入队(同文字发送)。
- 广播 SEND_VOICE_CGI --es to --es src_path <SILK> --ei duration。

真机 filehelper 测试:反射全部解析成功,scene=com.tencent.mm.modelbase.g,
z2.b 提交 1 块无异常(silk=2593B dur=2000)。投递确认待(设备屏幕 doze +
需第二账号);已知待补:[15] long 字段省略、本地 f9 气泡未插、cgi 响应
getLong(11) 未校。

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