一、脱壳

脱壳这里没细看,看到有壳就直接用脱壳网站解了

二、反调试绕过方法说明

2.0 检测发现方法

最初现象是:Frida spawn 后应用会弹出“检测到该应用在 hook 环境中运行”的风险提示,随后原进程被终止/重启。早期如果只观察线程存活时间,会被自动重启误导;真正关键是原始 PID 在进入 Home/主界面附近被检测链替换或杀死。

诊断过程采用了几类证据交叉确认:

  1. 运行时日志:观察 Frida attach/spawn 后哪个 so 加载、哪个线程创建、哪个分支触发风险提示。
  2. pthread_create 入口跟踪:定位 libnesec.solibnllvm*.so 创建的检测线程。
  3. linker 加载时机跟踪:hook do_dlopen / call_constructors,确保在目标 so 构造阶段或刚加载完成时安装 patch。
  4. maps 读取跟踪:确认 libnesec.so 会读取 /proc/self/maps 并匹配 Frida 痕迹。
  5. Crash/ANR 现象对比:排除单纯 exit/kill,发现部分链路是 native 状态机制造崩溃或卡死。

2.1 linker 加载时机控制

目标 so 的检测逻辑启动很早,如果等 Java 层稳定后再 hook,检测线程可能已经跑过。因此脚本先 hook linker:

1
2
3
4
// 关键思路:目标 so 加载或构造阶段就安装 patch
hook linker64/linker:
- do_dlopen
- call_constructors

do_dlopen / call_constructors 中识别以下模块:

1
2
3
4
libnesec.so
libmsaoaidsec.so
libnllvm*.so
libgtcore.so

命中后分别调用:

1
2
3
4
installNesecCode4Edges(...)
installMsaoaid(...)
installNllvm(...)
installGtcore(...)

这样能保证 patch 足够早,但又不是盲目 hook 所有 constructor。


2.2 libnesec.so 第一条检测线程:hook 环境检测

libnesec.so 加载后会创建多条 native 工作线程,其中最早触发风险提示的是第一条检测线程。运行时通过 hook pthread_create 记录第三个参数 start_routine,再用 Process.findModuleByAddress(start_routine) 计算所属 so 和模块内偏移,确认该检测线程入口为:

1
libnesec.so + 0x110ed8

这里的 pthread_create 思路不是泛泛地“hook 线程创建”,而是利用 pthread_create 的函数签名定位 native 线程入口:

1
2
3
4
5
6
int pthread_create(
pthread_t *thread,
const pthread_attr_t *attr,
void *(*start_routine)(void *), // 第三个参数就是新线程入口
void *arg
);

因此只要在 pthread_create 入口读取 start_routine,就能知道 native so 实际创建了哪个线程。当前样本中,libnesec.so + 0x110ed8 对应的线程不是普通业务线程,而是 hook 环境检测线程。

运行时观测到的线程创建关系可以抽象为:

1
2
3
4
5
6
// libnesec.so 内部初始化/调度逻辑,伪代码
void nesec_start_workers() {
pthread_create(&tid0, NULL, (void *(*)(void *))(base + 0x110ed8), arg0); // hook 环境检测线程
pthread_create(&tid1, NULL, other_worker_1, arg1); // 其它解密/业务线程
pthread_create(&tid2, NULL, other_worker_2, arg2); // 其它辅助线程
}

base + 0x110ed8 线程的核心检测行为可以概括为:

  1. 等待 native 初始化或运行环境稳定。

  2. 扫描进程运行环境,重点包括 /proc/self/maps、线程/模块/内存段等痕迹。

  3. 匹配 Frida/Gum/注入器相关字符串。

  4. 命中后进入风险码上报链,表现为:

    1
    检测到该应用在 hook 环境中运行
  5. 风险成立后,后续链路会触发进程终止、替换或重启。

对应伪代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// libnesec.so + 0x110ed8,伪代码
void* hook_env_detect_thread(void* arg) {
sleep_or_wait_runtime_ready();

int suspicious = 0;

// maps 中查找 Frida/Gum/注入器痕迹
suspicious |= scan_proc_maps_for_keywords(
"/proc/self/maps",
"frida",
"gum-js",
"gadget",
"linjector",
"substrate",
"xposed",
"memfd:frida"
);

// 其它运行时环境检查:线程名、模块名、内存段名等
suspicious |= scan_runtime_threads_or_modules();

if (suspicious) {
report_risk_code(4); // 后续在 libnesec code=4 分支继续处理
notify_java_risk_ui(); // 表现为 hook 环境 Toast/弹窗
trigger_restart_or_exit(); // 进程被终止、替换或重启
return NULL;
}

return NULL;
}

绕过点选择在线程入口层,而不是全局屏蔽 pthread_create。Frida 侧逻辑如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Interceptor.attach(pthread_create, {
onEnter(args) {
const start = args[2];
const m = Process.findModuleByAddress(start);
if (!m) return;

const off = start.sub(m.base);
if (m.name.indexOf("libnesec.so") >= 0 && off.equals(ptr("0x110ed8"))) {
// 只替换这一条确认的 hook 环境检测线程
Interceptor.replace(start, new NativeCallback(function (arg) {
return ptr(0);
}, "pointer", ["pointer"]));
}
}
});

pthread_create 定点替换后,该线程逻辑等价于:

1
2
3
void* hook_env_detect_thread_stub(void* arg) {
return NULL;
}

绕过效果:

  • 阻断 libnesec.so + 0x110ed8 这条早期 hook 环境检测线程。
  • 不替换其它 libnesec.so 线程,避免影响解密、初始化和后续业务逻辑。
  • 该线程不会再触发 hook 环境风险提示,但仍需要配合 2.3 的 code=4 分支 patch 和 2.4 的 maps 定向清洗,防止其它路径再次上报风险。

2.3 libnesec.so code=4 风险分支:风险码上报检测

替换 libnesec.so + 0x110ed8 检测线程后,仍然需要处理 libnesec.so 内部的风险码上报分支。运行时表现是:即使检测线程被压住,某些初始化路径仍会把 hook 环境写成风险码 4,然后交给风险 dispatcher,最终仍可能弹出 hook 环境提示。

当前确认的三个关键地址如下:

1
2
3
libnesec.so + 0x1041bc    // code=4 edge A
libnesec.so + 0x1042cc // code=4 edge B
libnesec.so + 0x101764 // MyJni.load 早期 hook-risk 上报点

这几个位置不是普通变量,而是 native 状态机中的控制流边。原始逻辑可以概括为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// libnesec.so 风险码分支,伪代码
void nesec_risk_state_machine(Context* ctx) {
int risk = 0;

if (check_hook_env_edge_A(ctx)) { // 对应 +0x1041bc 附近
risk = 4;
goto report;
}

if (check_hook_env_edge_B(ctx)) { // 对应 +0x1042cc 附近
risk = 4;
goto report;
}

if (myjni_load_hook_risk(ctx)) { // 对应 +0x101764 附近
risk = 4;
goto report;
}

continue_normal_init(ctx);
return;

report:
report_risk_code(risk); // risk == 4
notify_java_risk_ui();
trigger_restart_or_exit();
}

三个地址的具体含义:

地址 检测/分支含义 原始风险
libnesec.so + 0x1041bc 早期 code=4 分支边 条件命中后进入风险码 4 写入/上报路径
libnesec.so + 0x1042cc 后续 code=4 分支边 条件命中后跳到 code=4 异常分支
libnesec.so + 0x101764 MyJni.load 附近 hook-risk 上报点 早期 native load 阶段直接上报 hook 风险

绕过方式是只改这三个确认边,不改全局风险变量:

1
2
3
libnesec.so +0x1041bc -> 0x14000009    // b normal_continue
libnesec.so +0x1042cc -> 0xd503201f // nop
libnesec.so +0x101764 -> 0x14000010 // skip report

Frida 侧逻辑抽象如下:

1
2
3
4
5
6
7
8
9
10
function patch_nesec_code4_edges(base) {
// A:强制早期 code=4 edge 进入正常 continue
patchU32(base.add(0x1041bc), 0x14000009);

// B:抹掉后续 code=4 异常跳转
patchU32(base.add(0x1042cc), 0xd503201f);

// C:跳过 MyJni.load 附近的风险上报调用
patchU32(base.add(0x101764), 0x14000010);
}

注意点:

  • libnesec.so 文本段会异步解码,所以脚本会等待原始特征指令出现后再 patch。
  • 这里不是把所有风险结果都改成正常,而是只修改已经确认会把 hook 环境上报成 code=4 的控制流边。
  • 2.2 阻断检测线程,2.3 阻断残留风险码上报。

2.4 libnesec.so /proc/self/maps 检测:Frida 注入痕迹扫描

除线程入口和 code=4 分支外,libnesec.so 还会读取 /proc/self/maps/proc/<pid>/maps,扫描当前进程内存映射中的注入痕迹。该检测点的代码实现分散在 libnesec.so 的 maps 扫描路径中,运行时通过 returnAddress 归属确认调用来源为 libnesec.so,并且读取目标是 maps 文件。

检测对象:

1
2
/proc/self/maps
/proc/<pid>/maps

检测关键词:

1
2
3
4
5
6
7
8
9
10
frida
gum-js
gadget
linjector
substrate
xposed
memfd:frida
frida-agent
pool-frida
re.frida

libnesec.so 中该检测逻辑可抽象为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// libnesec.so maps 检测逻辑,伪代码
int scan_maps_for_hook_env() {
int fd = openat(AT_FDCWD, "/proc/self/maps", O_RDONLY);
char line[512];

while (read_one_line(fd, line, sizeof(line))) {
if (strcasestr(line, "frida") ||
strcasestr(line, "gum-js") ||
strcasestr(line, "gadget") ||
strcasestr(line, "linjector") ||
strcasestr(line, "substrate") ||
strcasestr(line, "xposed") ||
strcasestr(line, "memfd:frida")) {
return 1; // hook environment detected
}
}

return 0;
}

如果返回检测命中,后续会进入 2.3 中的风险码上报路径:

1
2
3
4
5
if (scan_maps_for_hook_env()) {
report_risk_code(4);
notify_java_risk_ui();
trigger_restart_or_exit();
}

绕过方式不是全局替换 maps,而是只对 libnesec.so 调用来源做定向清洗。脚本同时覆盖 libc 的两类读取方式:

1
2
3
fopen / fgets
open / openat / read
close / fclose

Frida 侧伪代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function is_from_nesec(ctx) {
const m = Process.findModuleByAddress(ctx.returnAddress);
return m && m.name.indexOf("libnesec.so") >= 0;
}

function sanitize_maps_line(line) {
if (contains(line, "frida") ||
contains(line, "gum-js") ||
contains(line, "gadget") ||
contains(line, "linjector") ||
contains(line, "memfd:frida")) {
return ""; // 丢掉可疑行
}
return line;
}

open/openat/fopen(path):
if is_from_nesec(this) && path matches "/proc/*/maps":
mark fd/FILE as tracked

read/fgets(fd_or_FILE):
if tracked:
return sanitize_maps_line(original_data)

绕过效果:

  • libnesec.so 看到的 maps 中没有 Frida 注入痕迹。
  • 其它模块读取 maps 不受影响。
  • 这一步是 2.2/2.3 的补充:即使检测线程或风险边被压住,也避免 maps 扫描路径再次制造风险输入。

2.5 libnllvm*.so 状态机 / watchdog:后续 native 检测与崩溃链

libnllvm*.so 是第二阶段检测链。它不一定直接调用 exit/kill,而是通过 native 状态机、watchdog 线程和毒化指针路径制造崩溃、卡死或 ANR-like 状态。因此这里不能简单 hook 终止函数,而要处理具体检测点。

当前确认的关键地址:

1
2
3
4
5
6
libnllvm*.so + 0x65e44    // watchdog 线程入口
libnllvm*.so + 0x3ebec // anti-check callsite
libnllvm*.so + 0x725d8 // poisoned string callsite
libnllvm*.so + 0x725e8 // paired poisoned string callsite
libnllvm*.so + 0x72dec // poisoned link pointer read
libnllvm*.so + 0x72edc // paired canary/expected-value read

2.5.1 watchdog 线程检测

运行时通过 pthread_create 确认 libnllvm*.so + 0x65e44 是 watchdog 线程入口。其行为可以抽象为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// libnllvm*.so + 0x65e44,伪代码
void* nllvm_watchdog_thread(void* arg) {
while (1) {
int detected = 0;

detected |= check_runtime_hook_state();
detected |= check_native_state_machine();
detected |= check_poisoned_string_or_object();

if (detected) {
poison_state_machine();
trigger_native_crash_or_anr();
return NULL;
}

sleep_or_wait_next_round();
}
}

绕过方式同样利用 pthread_create 的第三个参数,但只替换确认的 +0x65e44

1
2
3
4
pthread_create(start_routine):
module = Process.findModuleByAddress(start_routine)
if module.name startsWith "libnllvm" and offset == 0x65e44:
args[2] = empty_callback_return_NULL

代码等价于

1
2
3
void* nllvm_watchdog_stub(void* arg) {
return NULL;
}

2.5.2 状态机 callsite 检测

仅替换 watchdog 线程还不够,libnllvm*.so 内部还有多个状态机 callsite 会把检测结果转成异常对象或毒化指针。对应伪代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// libnllvm*.so 状态机,伪代码
void nllvm_state_machine(State* st) {
Obj* obj = get_runtime_object();

if (anti_check_callsite_at_0x3ebec(obj)) {
st->risk = 1;
}

char* s1 = poisoned_string_callsite_at_0x725d8(obj);
char* s2 = paired_string_callsite_at_0x725e8(obj);
if (is_bad_string(s1) || is_bad_string(s2)) {
st->risk = 1;
}

Link* link = *(Link**)((char*)obj + poisoned_offset); // +0x72dec 附近
if (link == invalid_pointer) {
crash_at_native_state(); // 不是普通 exit,而是 native 崩溃链
}

check_canary_or_expected_value(); // +0x72edc 附近
}

对应 patch:

地址 检测/异常点 绕过方式
libnllvm*.so +0x3ebec anti-check callsite 返回 null/no-match
libnllvm*.so +0x725d8 poisoned string callsite 返回 null/no-match
libnllvm*.so +0x725e8 paired poisoned string callsite 返回 null/no-match
libnllvm*.so +0x72dec poisoned link pointer read 改成 null
libnllvm*.so +0x72edc paired canary/expected-value read 改读有效字段

Frida 侧 patch 逻辑抽象:

1
2
3
4
5
patchU32(base.add(0x3ebec), 0xd2800000); // anti_check_ret_null
patchU32(base.add(0x725d8), 0xd2800000); // poisoned_string_ret_null
patchU32(base.add(0x725e8), 0xd2800000); // paired_string_ret_null
patchU32(base.add(0x72dec), 0xaa1f03e8); // poisoned_linkptr_to_null
patchU32(base.add(0x72edc), 0xf9406ec8); // canary_load_from_valid_field

绕过效果:

  • watchdog 线程不再运行。
  • 状态机中已确认的检测 callsite 返回 no-match。
  • 毒化指针路径不再制造 native crash。
  • 不 patch 整个底层检测函数,保留 LuAsset / NetSec 需要的其它调用路径。

2.6 libmsaoaidsec.so 初始化/环境辅助检测

libmsaoaidsec.so 不是最主要的 hook 环境弹窗来源,但它参与 native 初始化和环境辅助检测。如果不处理,后续 NetSec / LuAsset 初始化会不稳定,甚至把前面的反调试绕过结果重新带入异常路径。

当前确认的关键地址:

1
2
3
4
libmsaoaidsec.so + 0x234e0
libmsaoaidsec.so + 0x26334
libmsaoaidsec.so + 0x1bfac
libmsaoaidsec.so + 0x11f38 // handle/object 获取桥

原始逻辑可以抽象为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// libmsaoaidsec.so 初始化辅助逻辑,伪代码
void msaoaid_init_or_check() {
if (check_env_at_0x234e0()) {
enter_abnormal_path();
return;
}

if (check_env_at_0x26334()) {
enter_abnormal_path();
return;
}

int r = check_or_prepare_at_0x1bfac();
if (r != 0) {
enter_abnormal_path();
return;
}

void* handle = get_handle_or_object_at_0x11f38();
if (handle == NULL) {
enter_abnormal_path();
return;
}

continue_native_init();
}

其中 +0x11f38 的作用更像是获取库 handle 或 native object。如果这里返回空或异常对象,后续初始化会进入失败路径。给它安装 bridge,跳过异常检测,让程序正常初始化。

1
2
3
4
5
6
7
8
9
// libmsaoaidsec.so +0x11f38 绕过后逻辑,伪代码
void* msaoaid_handle_bridge() {
void* handle = dlopen("libmsaoaidsec.so", RTLD_NOW | RTLD_NOLOAD);
if (handle != NULL) {
return handle;
}

return fake_msaoaid_object;
}

对应 patch:

1
2
3
4
libmsaoaidsec.so +0x234e0 -> ret
libmsaoaidsec.so +0x26334 -> ret
libmsaoaidsec.so +0x1bfac -> mov x0,#0; ret
libmsaoaidsec.so +0x11f38 -> bridge callback

Frida 侧逻辑抽象:

1
2
3
4
5
6
7
8
patchRet(base.add(0x234e0));
patchRet(base.add(0x26334));
patchRet0(base.add(0x1bfac));

Interceptor.replace(base.add(0x11f38), new NativeCallback(function () {
const h = dlopen_no_load("libmsaoaidsec.so");
return h || fakeMsObject;
}, "pointer", []));

绕过效果:

  • 跳过 libmsaoaidsec.so 中几个确认的异常检测/初始化失败点。
  • +0x11f38 始终返回可用 handle 或 fake object。
  • 后续 NetSec / LuAsset 初始化可以继续,不会因为该库返回异常而破坏业务流程。

2.7 libgtcore.so JDWP / ART 调试探测

libgtcore.so 中存在 JDWP / ART 调试探测点。该检测不是 Java 层的 Debug.isDebuggerConnected(),而是 native 侧探测 ART/JDWP 状态。当前确认地址:

1
libgtcore.so + 0x48fa4

原始逻辑可以抽象为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// libgtcore.so +0x48fa4,伪代码
int jdwp_art_probe() {
int detected = 0;

detected |= check_art_debugger_state();
detected |= check_jdwp_thread_or_socket();
detected |= check_runtime_debug_flags();

if (detected) {
return 1; // debugger / JDWP environment detected
}

return 0;
}

如果该 probe 返回 true,后续 native 环境链可能把它合并进风险状态:

1
2
3
4
if (jdwp_art_probe()) {
mark_debug_env();
enter_risk_path();
}

绕过方式是只让该 probe 返回 false:

1
libgtcore.so +0x48fa4 -> mov x0,#0; ret

Frida 侧逻辑抽象:

1
patchRet0(gtcore_base.add(0x48fa4));

绕过效果:

  • libgtcore.so 认为当前没有 JDWP / ART 调试环境。
  • 不修改 Java 全局 Debug 状态。
  • 不影响其它 libgtcore.so 初始化逻辑。

2.8 为什么不 hook exit/kill/restart

曾经观察过 abort/exit/_exit/kill/tgkill 等入口,但最终稳定方案没有把它们作为绕过核心,原因是:

  1. 风险弹窗出现时,检测已经成立;只拦截 kill/restart 是治标不治本。
  2. 部分失败不是普通 exit_group,而是 native 状态机触发崩溃/卡死。
  3. 拦截重启会导致“程序不重启但卡死/ANR”,这个现象已经在实测中验证过。

因此最终做法是:

1
阻断检测成立条件 > 阻断风险码上报 > 避免 native 崩溃链

而不是:

1
hook kill/exit/restart

2.9 稳定绕过流程总结

启动脚本后,反调试相关流程如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1. Frida spawn 应用
2. hook linker do_dlopen / call_constructors
3. hook pthread_create
4. libnesec.so 加载:
- 等待文本段解码
- patch code=4 三个风险边
- 替换第一条检测线程 +0x110ed8
- 安装 maps 定向清洗
5. libnllvm*.so 加载:
- fake object / payload 修正
- patch 确认 callsite
- 替换 watchdog +0x65e44
6. libmsaoaidsec.so 加载:
- 三处定点 patch
- 安装 +0x11f38 bridge
7. libgtcore.so 加载:
- patch JDWP/ART probe 返回 false
8. NetSec / LuAsset 后续兼容初始化
9. 应用正常进入业务流程

2.10 检测点与绕过表

# 检测点 模块 触发方式 当前绕过
1 hook 环境首检线程 libnesec.so pthread_create 创建 +0x110ed8 仅替换该线程入口为空返回
2 风险码 code=4 上报 libnesec.so native 分支写入/上报风险码 patch +0x1041bc/+0x1042cc/+0x101764
3 Frida maps 痕迹 libnesec.so 读取 /proc/self/maps 仅对 libnesec 调用来源过滤 Frida 行
4 native anti-check 状态机 libnllvm*.so 多个 callsite 返回异常/毒化对象 patch +0x3ebec/+0x725d8/+0x725e8/+0x72dec/+0x72edc
5 watchdog 线程 libnllvm*.so pthread_create 创建 +0x65e44 替换该线程入口为空返回
6 初始化/环境辅助检测 libmsaoaidsec.so native 初始化分支 patch 三处偏移 + handle bridge
7 JDWP / ART 探测 libgtcore.so native probe +0x48fa4 返回 false
8 进程终止 libc exit/kill/tgkill/abort 仅诊断,不作为最终绕过

三、outdoor_run 刷数据实现方法说明

3.0 业务链路发现方法

反调试稳定后,进入室外跑流程,通过 Frida Java hook 逐步观察以下行为:

  1. 点击“开始运动”后,OutdoorRunViewModel.startRun() 被调用。
  2. 跑步中 UI 状态由 RunUiState.copy() 持续刷新。
  3. 点击结束时,先进入 requestFinish() / isSportComplete() / finishRun() 等本地校验。
  4. 上传前生成 UploadFormatEntityRunDataEntity
  5. 轨迹数据会经过 RunUploadHelper.buildUploadData()uploadObs()uploadToServer()
  6. 服务端请求前会调用 HttpUtil.signRunRecord() 做签名或加密参数生成。
  7. 上传成功后进入 RunHistoryDetailActivity,详情页会读取 RunHistoryDetailBean / RunHistoryDetailPImpl 中的数据。

最终确认:如果只改 UI 显示距离,结束时会出现“里程太短无法上传”;如果只改上传实体,不补轨迹/步频/速度 JSON,会出现服务器错误或详情页黑屏。因此需要多点一致 patch。


3.1 数据配置:统一 fake profile

脚本集中使用 OUTDOOR_FAKE 作为数据源,避免各 hook 点写出互相矛盾的值。

当前配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const OUTDOOR_FAKE = {
enabled: true,
onlyWhenAppRunning: true,
speedMps: 2.80,
timeScale: 1.0,
stepFreq: 172,
gpsLevel: 4,
kcalPerKm: 62,
minUploadDistanceM: 1200,
minUploadTimeSec: 600,
minUploadSteps: 1600,
baseLat: 38.9140,
baseLng: 121.6147,
trackPoints: 21,
coorType: "gcj02",
forceEndFalse: false
};

核心计算函数:

1
2
3
4
5
6
7
8
function outdoorFakeTotalsForSubmit(now) {
fake = outdoorFakeStateFromNow(now);
meters = max(1200, round(fake.distanceKm * 1000));
seconds = max(600, round(fake.elapsedSec));
kcal = max(1, round((meters / 1000) * 62));
steps = max(1600, round(seconds * 172 / 60));
return { meters, seconds, kcal, steps };
}

实现策略:

  • 所有 UI、结束校验、上传实体、详情页数据都从同一组 totals 派生。
  • 默认成绩为 1200m / 600s / 1720步 / 74kcal 附近,避免低于本地和服务端阈值。
  • onlyWhenAppRunning=true,不从 idle 状态强行伪造 running,必须等 app 自己进入真实跑步状态。
  • forceEndFalse=false,结束动作由用户和 app 自身流程触发,不伪造异常结束态。

3.2 RunUiState.copy():跑步中 UI 状态刷新

目标类:

1
com.zjwh.android_wh_physicalfitness.mvi.sport.outdoor.RunUiState

目标方法:

1
RunUiState.copy(...)

跑步页面的距离、时间、配速、步频、GPS、卡路里等状态会通过 RunUiState.copy() 反复生成新状态。原始逻辑可以抽象为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Kotlin data class copy,伪代码
RunUiState copy(
distance,
totalTime,
pace,
stepFreq,
gpsLevel,
kcal,
running,
pause,
end,
...
) {
return new RunUiState(...);
}

如果只改这个点,页面显示会变化,但上传前的 ViewModel totals 和轨迹文件仍可能为空,所以它只能作为“跑步中显示层”。

Frida 侧伪代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
RunUiState.copy.implementation = function (...) {
original = read_state_from_args(arguments);

if (!OUTDOOR_FAKE.enabled) {
return original_copy(...);
}

if (OUTDOOR_FAKE.onlyWhenAppRunning && !original.running) {
return original_copy(...);
}

fake = outdoorFakeStateFromNow(Date.now());

args.distance = fake.distanceKm;
args.time = fake.timeText;
args.pace = fake.paceText;
args.stepFreq = OUTDOOR_FAKE.stepFreq;
args.gpsLevel = OUTDOOR_FAKE.gpsLevel;
args.kcal = fake.kcal;

return original_copy(args);
}

实现策略:

  • 只在 app 已经处于 running 状态时改 UI state。
  • 不主动把 idle 改成 running,避免破坏业务状态机。
  • UI 层只负责显示自然增长的数据,最终上传仍以后续 UploadFormatEntity 和轨迹数据为准。

3.3 OutdoorRunViewModel:结束校验与上传入口

目标类:

1
com.zjwh.android_wh_physicalfitness.mvi.sport.outdoor.OutdoorRunViewModel

目标方法:

1
2
3
4
5
startRun()
requestFinish()
finishRun()
isSportComplete()
uploadRecord(entity)

点击结束后,本地会检查距离、时间、步数等字段。早期只改 UI 时,这里仍然读到真实距离很短,所以会提示:

1
里程太短无法上传

原始流程可抽象为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void requestFinish() {
if (!isSportComplete()) {
show_too_short_dialog();
return;
}
finishRun();
}

bool isSportComplete() {
return mTotalDis >= minDistance &&
mTotalTime >= minTime &&
gpsValid &&
trackValid;
}

void uploadRecord(UploadFormatEntity entity) {
send_to_upload_helper(entity);
}

可以在这些入口统一调用 outdoorForceVmTotals()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function outdoorForceVmTotals(vm, why) {
totals = outdoorFakeTotalsForSubmit(Date.now());

vm.mTotalDis = totals.meters;
vm.mTotalTime = totals.seconds;
vm.mCalorie = totals.kcal;
vm.mTotalSteps = totals.steps;

// 同步可能存在的字段名/类型,避免 Kotlin/Java 字段和 getter 不一致
set_field_or_call_setter(vm, "totalDis", totals.meters);
set_field_or_call_setter(vm, "totalTime", totals.seconds);
set_field_or_call_setter(vm, "calorie", totals.kcal);
set_field_or_call_setter(vm, "totalSteps", totals.steps);
}

各 hook 点:

1
2
3
4
5
requestFinish():    outdoorForceVmTotals(this, "requestFinish")
finishRun(): outdoorForceVmTotals(this, "finishRun")
isSportComplete(): outdoorForceVmTotals(this, "isSportComplete")
uploadRecord(ent): outdoorForceVmTotals(this, "uploadRecord")
outdoorPatchUploadEntity(ent, "uploadRecord")

实现策略:

  • 在结束校验前写入 ViewModel totals,解决“里程太短无法上传”。
  • uploadRecord(entity) 前同步 patch 上传实体,避免 ViewModel 与 entity 不一致。
  • 不直接改 isSportComplete() 返回值为 true,而是先补齐它依赖的数据,再让原逻辑自然返回。

3.4 UploadFormatEntity:上传主实体补全

核心实体:

1
UploadFormatEntity

该实体是服务端签名和上传的主要数据源,里面包含:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
uuid
totalDis
validDis
totalTime
validTime
speed
startTime
stopTime
calorie
totalSteps
avgStepFreq
latitude
longitude
allLocJson
fivePointJson
segmentJson

原始上传逻辑可抽象为:

1
2
3
4
5
6
7
UploadFormatEntity buildUploadData(RunDataEntity runData) {
entity.totalDis = runData.totalDis;
entity.totalTime = runData.totalTime;
entity.allLocJson = runData.run_data;
entity.speed = calculate_speed(...);
return entity;
}

如果这里字段不完整,会出现几类问题:

  • totalDis/totalTime 不够:本地或服务端认为成绩无效。
  • startTime/stopTimetotalTime 不一致:签名参数异常。
  • allLocJson/fivePointJson 为空:OBS/详情页无法读取轨迹。
  • speed/latitude/longitude 不合理:服务端校验失败。

当前 patch 函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function outdoorPatchUploadEntity(entity, why) {
totals = outdoorFakeTotalsForSubmit(Date.now());
artifacts = outdoorArtifactsForEntity(entity, why);

entity.totalDis = totals.meters;
entity.validDis = totals.meters;
entity.totalTime = totals.seconds;
entity.validTime = totals.seconds;
entity.calorie = totals.kcal;
entity.totalSteps = totals.steps;
entity.avgStepFreq = OUTDOOR_FAKE.stepFreq;
entity.speed = round(OUTDOOR_FAKE.speedMps * 1000);
entity.latitude = OUTDOOR_FAKE.baseLat;
entity.longitude = OUTDOOR_FAKE.baseLng;

normalize_start_stop_time(entity, totals.seconds);

entity.allLocJson = artifacts.locEntityJson;
entity.fivePointJson = artifacts.pointEntityJson;
entity.segmentJson = "[]";
}

安装位置:

1
2
3
4
OutdoorRunViewModel.uploadRecord(entity)
RunUploadHelper.buildUploadData(...)
RunUploadHelper.uploadToServer(entity)
HttpUtil.signRunRecord(entity)

实现策略:

  • 在上传链多个入口重复 patch,防止中间流程重新生成 entity 覆盖字段。
  • 统一 startTime/stopTime/totalTime,保证时间跨度等于 fake 秒数。
  • 将总距离、有效距离、总时间、有效时间同时写入,避免只改一个字段导致校验不一致。
  • 同步轨迹 JSON、五点 JSON、步频/速度 JSON,保证服务端和详情页读取的数据一致。

3.5 轨迹数据构造:allLocJson / fivePointJson / stepJson / speedJson

上传不能只有距离和时间,还要有轨迹点、步频序列、速度序列等结构化数据。可以用 outdoorBuildFakeTrackArtifacts() 统一生成这些 artifacts。

生成内容:

1
2
3
4
5
6
7
8
locListJson      // 21 个 MyLocation 点
locEntityJson // { useZip:false, allLocJson: locListJson }
pointEntityJson // { useZip:false, fivePointJson: ..., runAreaId:-1, ... }
stepJson // 每 10 秒一个步频片段
speedJson // 每 10 秒一个速度/距离片段
lapsJson // 单圈汇总
segmentJson // []
altitudeJson // []

轨迹点生成逻辑:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 伪代码
points = [];
lat0 = 38.9140;
lng0 = 121.6147;
lngDelta = meters / meters_per_lng_degree(lat0);

for i in 0 .. trackPoints-1:
ratio = i / (trackPoints - 1);
lat = lat0 + 0.00003 * sin(ratio * 2π);
lng = lng0 + lngDelta * ratio;
sec = round(totalSeconds * ratio);
dis = totalMeters * ratio;

points.push({
lat, lng, gLat: lat, gLng: lng,
totalTime: sec,
validTime: sec,
totalDis: dis,
validDis: dis,
speed: 2.8,
avgSpeed: 2.8,
locType: 61,
radius: 8.0,
bdG: 4,
state: 1,
coorType: "gcj02"
});

步频/速度序列生成逻辑:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
for each 10s slot:
stepJson.push({
stepsNum: round(stepFreq * slotSeconds / 60),
beginTime,
endTime,
state: 1
});

speedJson.push({
distance: meters_per_slot,
beginTime,
endTime,
state: 1
});

实现策略:

  • 使用固定起点和确定性轨迹,避免每个 hook 点生成不同路线。
  • 点数控制为 21 个,既能满足轨迹结构,又不制造过大 JSON。
  • allLocJsonfivePointJsonstepJsonspeedJsonlapsJson 全部由同一个 totals 派生。
  • 轨迹作为上传实体、OBS 文件和详情页 fallback 的共同数据源。

3.6 RunUploadHelper:上传链路补丁

目标类:

1
com.zjwh.android_wh_physicalfitness.mvi.sport.helper.RunUploadHelper

目标方法:

1
2
3
buildUploadData(...)
uploadObs(...)
uploadToServer(...)

原始上传链路:

1
2
3
4
RunDataEntity runData = collect_local_run_data();
UploadFormatEntity entity = buildUploadData(runData);
uploadObs(runData);
uploadToServer(entity);

当前 hook:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
buildUploadData(...):
entity = original(...)
artifacts = outdoorPatchUploadEntity(entity)
outdoorPatchRunDataEntity(runData, artifacts)
return entity

uploadObs(runData):
artifacts = outdoorBuildFakeTrackArtifacts(...)
outdoorPatchRunDataEntity(runData, artifacts)
return original(runData)

uploadToServer(entity):
outdoorPatchUploadEntity(entity)
return original(entity)

实现策略:

  • buildUploadData() 后 patch entity,确保刚生成的上传对象立即被修正。
  • uploadObs() 前 patch RunDataEntity,保证上传到 OBS 的轨迹文件也是 fake 数据。
  • uploadToServer() 前再次 patch entity,防止前面流程被覆盖或重建。
  • 让 OBS 轨迹、服务端请求、详情页读取三者使用同一套 artifacts。

3.7 RunDataEntity 与 OBS:轨迹文件补全

核心实体:

1
RunDataEntity

相关上传管理:

1
2
3
com.zjwh.android_wh_physicalfitness.utils.rundata.RunDataUploadManger.uploadUUID(...)
com.zjwh.android_wh_physicalfitness.utils.rundata.RunDataUploadManger.queryUUID(...)
com.zjwh.android_wh_physicalfitness.manager.ObsClient.downloadTimeJsonSync(...)

OBS 链路负责上传/下载轨迹详情。如果 RunDataEntity 中的轨迹字段为空,服务端虽然可能返回成功,但详情页读取时会出现空数据、等待下载或黑屏。

原始逻辑可抽象为:

1
2
3
4
5
6
7
8
9
10
11
12
uploadObs(runData) {
bytes = GZipHelper.runDataToByte(runData);
uuid = RunDataUploadManger.uploadUUID(bytes);
entity.recordUrl = uuid;
}

detail(uuid) {
json = RunDataUploadManger.queryUUID(uuid);
if empty:
json = ObsClient.downloadTimeJsonSync(uuid);
render_detail(json);
}

当前 patch:

1
2
3
4
5
6
7
8
9
10
function outdoorPatchRunDataEntity(runData, artifacts, why) {
runData.run_data = artifacts.locEntityJson;
runData.fixedPointJson = artifacts.pointEntityJson;
runData.step_freq_json = artifacts.stepJson;
runData.speed_json = artifacts.speedJson;
runData.segment_json = "[]";
runData.laps_json = artifacts.lapsJson;
runData.total_dis = totals.meters;
runData.total_time = totals.seconds;
}

实现策略:

  • uploadObs() 前补齐 RunDataEntity,让上传到 OBS 的内容不是空轨迹。
  • 在本地文件存在时同步覆盖 runData 文件,避免压缩函数读旧文件。
  • hook queryUUID() / downloadTimeJsonSync() 相关路径,用于详情页缺数据时回填 fake artifacts。
  • 不直接伪造上传成功回调,而是让原上传流程继续走完。

3.8 GZipHelper:压缩兜底

目标类:

1
com.zjwh.android_wh_physicalfitness.utils.GZipHelper

目标方法:

1
2
runDataToByte(...)
runDataToByte2(...)

原始逻辑:

1
2
3
4
byte[] runDataToByte(RunDataEntity entity) {
json = serialize(entity.run_data, entity.fixed_point_json, ...);
return gzip(json);
}

问题点:某些情况下原始压缩函数读到的是旧文件或空字段,导致 OBS 上传数据为空。脚本保留原函数优先,只在原始函数失败或返回异常时走 fallback。

兜底逻辑:

1
2
3
4
5
6
7
try {
bytes = original_runDataToByte(entity);
if (bytes valid) return bytes;
} catch (_) {}

json = build_json_from_fake_artifacts(entity);
return gzip(json);

实现策略:

  • 原始压缩逻辑可用时优先使用原函数,减少格式偏差。
  • 原始逻辑失败或返回空时,使用 fake artifacts 重新组装 JSON 并 gzip。
  • fallback 与 UploadFormatEntity 使用同一套轨迹、五点、步频、速度数据。

3.9 HttpUtil.signRunRecord():签名前一致性检查

目标类:

1
com.zjwh.android_wh_physicalfitness.utils.HttpUtil

目标方法:

1
signRunRecord(entity)

该方法是服务端请求前的关键点。签名时如果 entity 内字段不一致,后面即使再改网络参数也来不及。

原始逻辑:

1
2
3
4
5
String signRunRecord(UploadFormatEntity entity) {
json = serialize(entity);
sign = netease_or_native_sign(json);
return signed_json;
}

当前 hook 主要用于最终校验和补丁:

1
2
3
signRunRecord(entity):
outdoorPatchUploadEntity(entity, "signRunRecord")
return original(entity)

关键一致性字段:

1
2
3
4
5
6
stopTime - startTime == totalTime * 1000
totalDis == validDis == 1200
totalTime == validTime == 600
speed == 2800
latitude/longitude == fake 起点
allLocJson/fivePointJson 非空

实现策略:

  • 在签名前最后一次 patch UploadFormatEntity
  • 不改签名算法本身,继续使用 app 原始 signRunRecord()
  • 让服务端接收到的是 app 自己签出来的、字段一致的 fake run record。

3.10 上传成功回调:记录 uuid / rrid

目标回调:

1
2
RunUploadHelper$uploadToServer$1.onSuccess(...)
RunUploadHelper$uploadToServer$1.onError(...)

上传成功后,服务端返回类似:

1
GetDrawChanceBean{uuid='...', rrid=..., completed=true}

脚本记录:

1
2
3
4
outdoorLastSuccessUuid
outdoorCurrentUploadUuid
outdoorLastSuccessRrid
outdoorFakeRunUuids[uuid] = true

伪代码:

1
2
3
4
5
6
7
onSuccess(bean):
uuid = extract_uuid(bean)
rrid = extract_rrid(bean)
outdoorLastSuccessUuid = uuid
outdoorLastSuccessRrid = rrid
outdoorFakeRunUuids[uuid] = true
return original(bean)

实现策略:

  • 不伪造 onSuccess(),只在原始成功回调发生后记录 uuid / rrid。
  • 用 uuid 标记后续详情页数据是否属于本次 fake run。
  • 详情页 patch 只针对当前 fake uuid 或最近成功 uuid,避免污染其它历史记录。

3.11 详情页数据回填:RunHistoryDetailBean / RunHistoryDetailPImpl

目标类:

1
2
com.zjwh.android_wh_physicalfitness.entity.sport.RunHistoryDetailBean
com.zjwh.android_wh_physicalfitness.mvi.run.mode.RunHistoryDetailPImpl

目标方法:

1
2
3
4
5
6
RunHistoryDetailBean.getAllLocJson()
RunHistoryDetailBean.getFivePointJson()
RunHistoryDetailBean.getSegmentJson()
RunHistoryDetailBean.getJsonFromObs()
RunHistoryDetailPImpl.getNetData()
RunHistoryDetailPImpl.getObsData()

详情页原始逻辑:

1
2
3
4
5
6
7
8
9
10
detailBean = getNetData(uuid);

if (detailBean.jsonFromObs == 1) {
json = download_from_obs(uuid);
} else {
json = detailBean.allLocJson;
}

showData(...);
setMapCenter(points, stepJson, speedJson, segmentJson, ...);

如果服务端返回的详情字段为空,Activity 可能等待 OBS 下载或传空数据给 native 地图,最终出现黑屏。

当前 patch:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
RunHistoryDetailBean.getAllLocJson():
if empty and is_target_fake_uuid:
return artifacts.locEntityJson

RunHistoryDetailBean.getFivePointJson():
if empty and is_target_fake_uuid:
return artifacts.pointEntityJson

RunHistoryDetailBean.getSegmentJson():
if empty:
return "[]"

RunHistoryDetailBean.getJsonFromObs():
if fake artifacts ready:
setJsonFromObs(0)
return 0

RunHistoryDetailPImpl.getNetData/getObsData():
patch mStepsPerTenSec
patch mSpeedPerTenSec
patch mSegmentJson
patch mLapsJson

实现策略:

  • 只对当前 fake uuid 或最近成功 uuid 的详情数据做回填。
  • 如果详情页缺轨迹 JSON,则用上传阶段保存的 artifacts 补齐。
  • jsonFromObs 改为 0,避免 Activity 等待不存在或为空的 OBS 下载。
  • 同步 PImpl 内部缓存字段,避免 Bean 和 Presenter 数据不一致。

3.12 详情页黑屏处理:跳过 native 地图渲染,使用 placeholder(后面经过确认发现不是脚本问题,而是测试机的问题,换了一个测试机就能正常打开,不会黑屏)

目标 Activity:

1
com.zjwh.android_wh_physicalfitness.mvi.run.RunHistoryDetailActivity

关键控件:

1
2
run_history_map               0x7f0a0ce7
fl_run_map_hidden_placeholder 0x7f0a03e1

早期版本上传成功后会黑屏。最终定位不是上传失败,而是详情页 native 地图/Surface 渲染不稳定:数据已经成功上传,showData()setMapCenter() 等也会进入,但地图 Surface 可能导致全黑。

原始渲染链路:

1
2
3
4
5
6
7
showData(...)
setMapCenter(points, stepJson, speedJson, segmentJson, ...)
addLine(...)
setFivePoint(...)
setStartPoint(...)
setEndPoint(...)
drawGeoFence(...)

当前稳定策略:

1
2
3
4
5
if current_activity is RunHistoryDetailActivity:
show fl_run_map_hidden_placeholder
hide run_history_map
skip setMapCenter native
skip addLine / setFivePoint / setStartPoint / setEndPoint / drawGeoFence

作用域控制:

1
2
3
4
function outdoorIsDetailMapView(v) {
return currentActivity is RunHistoryDetailActivity &&
v.getId() == 0x7f0a0ce7;
}

实现策略:

  • 只在 RunHistoryDetailActivity 中启用 placeholder。
  • 只隐藏详情页的 run_history_map,不影响 OutdoorRunActivity 的运动中地图。
  • onStop/onDestroy 时清理 placeholder 状态,防止返回后污染下一次开始运动。
  • 放弃详情页路径显示,优先保证多次上传后详情页不黑屏、运动页地图正常。

3.13 完整刷数据流程总结

完整链路如下:

1
2
3
4
5
6
7
8
9
10
11
12
1. 用户正常点击“开始运动”
2. RunUiState.copy() 只在 running=true 后刷新 UI 显示
3. 用户点击结束
4. requestFinish/isSportComplete/finishRun 前写入 ViewModel totals
5. uploadRecord/buildUploadData 生成上传实体
6. outdoorPatchUploadEntity() 写入距离、时间、步数、卡路里、速度、经纬度
7. outdoorBuildFakeTrackArtifacts() 生成 allLocJson/fivePointJson/stepJson/speedJson
8. uploadObs 前 patch RunDataEntity,必要时 gzip fallback
9. uploadToServer/signRunRecord 前再次 patch entity,并使用 app 原签名逻辑
10. 服务端返回成功后记录 uuid / rrid
11. 详情页读取当前 uuid 时回填 fake artifacts
12. 详情页跳过 native 地图渲染,使用 placeholder 防黑屏

关键目标不是“只改 UI 距离”,而是让以下数据保持一致:

1
2
3
4
5
6
7
8
UI state
ViewModel totals
UploadFormatEntity
RunDataEntity
OBS gzip bytes
signRunRecord 输入
RunHistoryDetailBean
RunHistoryDetailPImpl

3.14 hook 点与实现表

# 位置 类/方法 目的 实现策略
1 跑步中 UI RunUiState.copy() 显示距离/时间/配速增长 running=true 后按 fake profile 改 copy 参数
2 开始运动 OutdoorRunViewModel.startRun() 标记 fake 起点时间 记录 startRun,初始化计时基准
3 结束校验 requestFinish() / finishRun() / isSportComplete() 通过本地距离/时间校验 先写 ViewModel totals,再走原逻辑
4 上传入口 uploadRecord(entity) 修正上传实体 patch UploadFormatEntity
5 数据构造 RunUploadHelper.buildUploadData() 防止 entity 被重新生成覆盖 original 后再次 patch entity/runData
6 OBS 上传 RunUploadHelper.uploadObs() 补齐轨迹文件 patch RunDataEntity 和本地文件
7 服务端上传 RunUploadHelper.uploadToServer() 最后修正上传对象 发送前 patch entity
8 签名 HttpUtil.signRunRecord() 保证签名前字段一致 patch entity 后调用原签名
9 压缩 GZipHelper.runDataToByte*() OBS bytes 兜底 原函数失败时用 fake artifacts gzip
10 上传成功 uploadToServer.onSuccess() 记录 uuid/rrid 只记录真实成功结果,不伪造成功
11 详情数据 RunHistoryDetailBean/PImpl 回填缺失轨迹 当前 fake uuid 才补数据
12 详情渲染 RunHistoryDetailActivity 防止黑屏 跳过 native 地图,显示 placeholder

final

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
'use strict';


const OFF = {
nesecWorker: ptr('0x110ed8'),
nesecGeneratedEntry: ptr('0x110f2c'),
ms234e0: ptr('0x234e0'),
ms26334: ptr('0x26334'),
ms1bfac: ptr('0x1bfac'),
ms11f38: ptr('0x11f38'),
nnInlineObj: ptr('0x72428'),
nnPayloadCall: ptr('0x7809c')
};

const NNLLVM_WORKERS = ['0x65e44'];
const TRY_LUASSET_NATIVE_FIRST = true;
const RTLD_NOW_NOLOAD = 2 | 4;

const keepAlive = [];
const installed = Object.create(null);
let fakeMsBacking = null;
let fakeMsObject = ptr(0);
let fakeNnBacking = null;
let fakeNnObject = ptr(0);
let javaPrimed = false;
let luAssetInstalled = false;
let luAssetNativeOk = false;
let neteaseTraceInstalled = false;
let neteaseInitSeen = false;
let neteaseReady = false;
let neteaseTraceRound = 0;
let jniTargetRegistrations = 0;
let verdictScheduled = false;
let myJniLoadWrapped = false;

const CLEAN_LOG_MODE = true;
function shouldDropCleanLog(s) {
if (!CLEAN_LOG_MODE) return false;
s = String(s);
const noisyPrefixes = [
'[STATUS]',
'[OUTDOOR-VIEW]',
'[OUTDOOR-RENDER]',
'[OUTDOOR-MAP-REPLAY]',
'[OUTDOOR-DETAIL-NATIVE]'
];
for (let i = 0; i < noisyPrefixes.length; i++) {
if (s.indexOf(noisyPrefixes[i]) === 0) return true;
}
if (s.indexOf('[OUTDOOR-PLACEHOLDER] apply') === 0) return true;
if (s.indexOf('[OUTDOOR-PLACEHOLDER] scheduled') === 0) return true;
if (s.indexOf('[OUTDOOR-PLACEHOLDER] schedule') === 0) return true;
if (s.indexOf('[OUTDOOR-PLACEHOLDER] WHMapView.') === 0) return true;
if (s.indexOf('[OUTDOOR-PLACEHOLDER] skip detail WHMapView.') === 0) return true;
if (s.indexOf('[OUTDOOR-DETAIL] Activity.setMapCenter') === 0) return true;
if (s.indexOf(' hooked overloads=') >= 0) return true;
if (s.indexOf('[PATCH] ') === 0) return true;
if (s.indexOf('[OUTDOOR-DETAIL] patched ') === 0) return true;
if (s.indexOf('[OUTDOOR-DETAIL] getSegmentJson') === 0) return true;
if (s.indexOf('[OUTDOOR-TRACK] built ') === 0) return true;
if (s.indexOf('[OUTDOOR-TRACK] patch RunDataEntity') === 0) return true;
if (s.indexOf('[OUTDOOR-TRACK] patched RunDataEntity') === 0) return true;
if (s.indexOf('[OUTDOOR-SUBMIT] patch UploadFormatEntity') === 0) return true;
if (s.indexOf('[OUTDOOR-SUBMIT] patched UploadFormatEntity') === 0) return true;
if (s.indexOf('[OUTDOOR-SUBMIT] normalize time') === 0) return true;
if (s.indexOf('[OUTDOOR-SUBMIT] force VM totals') === 0) return true;
if (s.indexOf('[OUTDOOR-SUBMIT] isSportComplete') === 0) return true;
if (s.indexOf('[OUTDOOR-GZIP] runDataToByte') === 0) return true;
if (s.indexOf('[OUTDOOR-GZIP] fallback mode=') === 0) return true;
return false;
}

function log(s) {
if (shouldDropCleanLog(s)) return;
console.log(s);
}

function installRegisterNativesTrace() {
const art = moduleByName('libart.so');
if (!art) {
log('[JNI-TRACE] libart missing');
return;
}

let target = null;
const symbols = art.enumerateSymbols();
for (let i = 0; i < symbols.length; i++) {
const name = symbols[i].name;
if (name.indexOf('RegisterNatives') !== -1 &&
name.indexOf('CheckJNI') === -1 &&
name.indexOf('JNI') !== -1) {
target = symbols[i];
break;
}
}
if (!target) {
log('[JNI-TRACE] RegisterNatives symbol missing');
return;
}

Interceptor.attach(target.address, {
onEnter(args) {
const methods = args[2];
let count = 0;
try { count = args[3].toInt32(); } catch (e) { return; }
if (count <= 0 || count > 512 || methods.isNull()) return;

let className = '<unknown>';
try { className = Java.vm.getEnv().getClassName(args[1]); } catch (e) {}
const rows = [];
for (let i = 0; i < count; i++) {
try {
const row = methods.add(i * Process.pointerSize * 3);
const name = row.readPointer().readCString();
const sig = row.add(Process.pointerSize).readPointer().readCString();
const fn = row.add(Process.pointerSize * 2).readPointer();
const mod = moduleByAddress(fn);
const owner = mod ? mod.name + '+' + fn.sub(mod.base) : fn.toString();
if (!myJniLoadWrapped && mod && isNesec(mod.name) && name === 'load' &&
sig.indexOf('Landroid/app/Application;Ljava/lang/String;)Z') !== -1) {
try {
const originalPtr = fn;
const originalLoad = new NativeFunction(originalPtr, 'int', ['pointer', 'pointer', 'pointer', 'pointer']);
const cb = new NativeCallback(function (env, clazz, app, str) {
const mm = moduleByAddress(originalPtr) || findLoaded(isNesec);
log('[MYJNI-WRAP] enter original=' + originalPtr + ' owner=' + owner + ' module=' + (mm ? mm.base : '<none>'));
if (mm) installNesecCode4Edges(mm, 'myjni-load-wrapper-before-original');
const r = originalLoad(env, clazz, app, str);
log('[MYJNI-WRAP] leave ret=' + r);
return r;
}, 'int', ['pointer', 'pointer', 'pointer', 'pointer']);
keepAlive.push(cb, originalLoad);
row.add(Process.pointerSize * 2).writePointer(cb);
myJniLoadWrapped = true;
log('[MYJNI-WRAP] RegisterNatives rewrote MyJni.load ' + sig + ' original=' + originalPtr + ' ' + owner);
} catch (eWrap) {
log('[MYJNI-WRAP-FAIL] ' + eWrap.message + ' fn=' + fn + ' ' + owner);
}
}
if ((mod && isNllvm(mod.name)) ||
className.indexOf('lufunds') !== -1 ||
name.indexOf('initAsset') !== -1) {
rows.push(name + sig + ' -> ' + owner);
}
} catch (e) {}
}
if (rows.length > 0) {
jniTargetRegistrations += rows.length;
log('[JNI-REGISTER] class=' + className +
' count=' + count + ' methods=' + rows.join(' | '));
}
}
});
log('[JNI-TRACE] RegisterNatives installed symbol=' + target.name);
}

function moduleByName(name) {
try { return Process.findModuleByName(name); } catch (e) { return null; }
}

function moduleByAddress(address) {
try { return Process.findModuleByAddress(address); } catch (e) { return null; }
}

function findExport(moduleName, symbolName) {
try {
if (typeof Module.findExportByName === 'function') {
const p = Module.findExportByName(moduleName, symbolName);
if (p) return p;
}
} catch (e0) {}
try {
if (moduleName) {
const m = moduleByName(moduleName);
if (m) {
const p = m.findExportByName(symbolName);
if (p) return p;
}
}
} catch (e1) {}
try {
if (typeof Module.findGlobalExportByName === 'function') {
return Module.findGlobalExportByName(symbolName);
}
} catch (e2) {}
return null;
}

function readCString(p) {
try { return p && !p.isNull() ? p.readCString() : ''; }
catch (e) { return ''; }
}

function isNesec(name) {
name = String(name || '').toLowerCase();
return name.indexOf('libnesec.so') !== -1 || name.indexOf('libsecexe.so') !== -1;
}

function isMsaoaid(name) {
return String(name || '').toLowerCase().indexOf('libmsaoaidsec.so') !== -1;
}

function isNllvm(name) {
return String(name || '').toLowerCase().indexOf('libnllvm') !== -1;
}

function isGtcore(name) {
return String(name || '').toLowerCase().indexOf('libgtcore.so') !== -1;
}

function findLoaded(predicate) {
try {
const modules = Process.enumerateModules();
for (let i = 0; i < modules.length; i++) {
if (predicate(modules[i].name) || predicate(modules[i].path)) return modules[i];
}
} catch (e) {}
return null;
}

function patchRet(moduleObj, offset, tag) {
const address = moduleObj.base.add(offset);
Memory.patchCode(address, 4, function (code) {
code.writeU32(0xd65f03c0); // ret
});
log('[PATCH] ' + tag + ' addr=' + address + ' insn=0x' + address.readU32().toString(16));
}

function patchRet0(moduleObj, offset, tag) {
const address = moduleObj.base.add(offset);
Memory.patchCode(address, 8, function (code) {
code.writeU32(0xd2800000); // mov x0, #0
code.add(4).writeU32(0xd65f03c0); // ret
});
log('[PATCH] ' + tag + ' addr=' + address +
' insn=0x' + address.readU32().toString(16) + ',0x' + address.add(4).readU32().toString(16));
}

function getFakeMsObject() {
if (!fakeMsObject.isNull()) return fakeMsObject;
fakeMsBacking = Memory.alloc(0x4000);
try { Memory.writeByteArray(fakeMsBacking, new Uint8Array(0x4000).buffer); } catch (e) {}
fakeMsObject = fakeMsBacking.add(0x100);
keepAlive.push(fakeMsBacking, fakeMsObject);
log('[MSAOAID] fake object=' + fakeMsObject);
return fakeMsObject;
}

function installMs11f38Bridge(moduleObj) {
const address = moduleObj.base.add(OFF.ms11f38);
const dlopenPtr = findExport(null, 'dlopen') || findExport('libdl.so', 'dlopen');
const androidDlopenExtPtr = findExport(null, 'android_dlopen_ext') || findExport('libdl.so', 'android_dlopen_ext');
const dlopenFn = dlopenPtr ? new NativeFunction(dlopenPtr, 'pointer', ['pointer', 'int']) : null;
const androidDlopenExtFn = androidDlopenExtPtr ?
new NativeFunction(androidDlopenExtPtr, 'pointer', ['pointer', 'int', 'pointer']) : null;
const soname = Memory.allocUtf8String('libmsaoaidsec.so');
const fullPath = Memory.allocUtf8String(moduleObj.path);
keepAlive.push(soname, fullPath);

const callback = new NativeCallback(function () {
let handle = ptr(0);
let source = 'fake';
try { if (dlopenFn) handle = dlopenFn(soname, RTLD_NOW_NOLOAD); } catch (e0) {}
try { if (handle.isNull() && dlopenFn) handle = dlopenFn(fullPath, RTLD_NOW_NOLOAD); } catch (e1) {}
try { if (handle.isNull() && androidDlopenExtFn) handle = androidDlopenExtFn(soname, RTLD_NOW_NOLOAD, ptr(0)); } catch (e2) {}
try { if (handle.isNull() && androidDlopenExtFn) handle = androidDlopenExtFn(fullPath, RTLD_NOW_NOLOAD, ptr(0)); } catch (e3) {}
if (handle.isNull()) handle = getFakeMsObject();
else source = 'NOLOAD';
log('[MSAOAID-11F38] ret=' + handle + ' source=' + source);
return handle;
}, 'pointer', []);
keepAlive.push(callback);
Interceptor.replace(address, callback);
log('[MSAOAID] +0x11f38 bridge installed');
}

function installMsaoaid(moduleObj, reason) {
if (!moduleObj) return;
const key = 'ms:' + moduleObj.base;
if (installed[key]) return;
installed[key] = true;
try {
patchRet(moduleObj, OFF.ms234e0, 'msaoaid+0x234e0');
patchRet(moduleObj, OFF.ms26334, 'msaoaid+0x26334');
patchRet0(moduleObj, OFF.ms1bfac, 'msaoaid+0x1bfac');
installMs11f38Bridge(moduleObj);
log('[MSAOAID] ready base=' + moduleObj.base + ' reason=' + reason);
} catch (e) {
log('[MSAOAID-FAIL] ' + e.message);
}
}

function getFakeNnObject() {
if (!fakeNnObject.isNull()) return fakeNnObject;
fakeNnBacking = Memory.alloc(0x4000);
try { Memory.writeByteArray(fakeNnBacking, new Uint8Array(0x4000).buffer); } catch (e) {}
fakeNnObject = fakeNnBacking.add(0x100);
const child = fakeNnObject.add(0x300);
fakeNnObject.add(0x198).writePointer(child);
fakeNnObject.add(0x1a0).writeU8(0);
child.writePointer(child);
keepAlive.push(fakeNnBacking, fakeNnObject);
log('[NNLLVM] fake object=' + fakeNnObject + ' child=' + child);
return fakeNnObject;
}

function movWide(base, halfWord, imm16, reg) {
return (base | ((halfWord & 3) << 21) | ((imm16 & 0xffff) << 5) | (reg & 31)) >>> 0;
}

function installNllvm(moduleObj, reason) {
if (!moduleObj) return;
const key = 'nn:' + moduleObj.base;
if (installed[key]) return;
installed[key] = true;

try {
const fake = getFakeNnObject();
let hex = fake.toString().toLowerCase().replace('0x', '');
while (hex.length < 16) hex = '0' + hex;
const parts = [
parseInt(hex.slice(12, 16), 16),
parseInt(hex.slice(8, 12), 16),
parseInt(hex.slice(4, 8), 16),
parseInt(hex.slice(0, 4), 16)
];
const words = [
movWide(0xd2800000, 0, parts[0], 8),
movWide(0xf2800000, 1, parts[1], 8),
movWide(0xf2800000, 2, parts[2], 8),
movWide(0xf2800000, 3, parts[3], 8),
0x91068100, // add x0, x8, #0x1a0
0xf9000ec8 // str x8, [x22, #0x18]
];
const inlineAddress = moduleObj.base.add(OFF.nnInlineObj);
Memory.patchCode(inlineAddress, 24, function (code) {
for (let i = 0; i < words.length; i++) code.add(i * 4).writeU32(words[i]);
});

const payloadAddress = moduleObj.base.add(OFF.nnPayloadCall);
const before = payloadAddress.readU32();
if (before === 0xd63f0100 || before === 0x52800000) {
Memory.patchCode(payloadAddress, 4, function (code) {
code.writeU32(0x52800000); // mov w0, #0
});
}

// v56: after v55 fixed the native crash callsite, the original PID no
// longer crashed but became undeliverable/ANR-like. Older v11/v12
// diagnostics proved this exact callsite enters sub_71F74 and does not
// return on the non-registration anti-check path. Force only this
// branch's result to NULL/no-match; keep the other sub_71F74 callers
// intact because LuAsset registration depends on them.
patchU32(moduleObj, '0x3ebec', 0xd2800000, 'nllvm+0x3ebec sub_71F74_anti_check_ret_null');

// v55: v54 CrashSDK proved the post-popup crash is not exit/kill; it is
// SIGSEGV at libnllvm+0x45960 with LR=libnllvm+0x725dc. The direct
// caller is the state-machine slot at +0x725d8, which passes a poisoned
// string-like pointer into sub_457B4/sub_45960. Patch only this slot to
// produce a NULL/no-match result; do not patch sub_45960 globally.
patchU32(moduleObj, '0x725d8', 0xd2800000, 'nllvm+0x725d8 poisoned_string_callsite_ret_null');
patchU32(moduleObj, '0x725e8', 0xd2800000, 'nllvm+0x725e8 paired_string_callsite_ret_null');

// v57: v56 CrashSDK moved the crash to +0x72dec (ldr x8,[x8,#0x28])
// with the same poisoned pointer pattern. Keep the state-machine slot
// alive but make the poisoned link read produce NULL, and make the
// paired canary/expected-value read use the valid object field.
patchU32(moduleObj, '0x72dec', 0xaa1f03e8, 'nllvm+0x72dec poisoned_linkptr_to_null');
patchU32(moduleObj, '0x72edc', 0xf9406ec8, 'nllvm+0x72edc paired_canary_load_from_x22_d8');
log('[NNLLVM] ready base=' + moduleObj.base +
' inline=0x' + inlineAddress.readU32().toString(16) +
' payload=0x' + payloadAddress.readU32().toString(16) +
' reason=' + reason);
scheduleLuAssetBridge('nllvm-ready/' + reason);
} catch (e) {
log('[NNLLVM-FAIL] ' + e.message);
}
}

function describeCallback(callback, tag) {
let name = '<null>';
try { if (callback) name = callback.getClass().getName().toString(); } catch (e) {}
log('[LUASSET] ' + tag + ' callback=' + name);
}

function installLuAssetWithFactory(factory, reason) {
const className = 'com.lufunds.sdk.asset.LuAssetServer';
const LuAssetServer = factory.use(className);
log('[LUASSET] class ready reason=' + reason);

const initAsset = LuAssetServer.initAsset.overload(
'android.content.Context',
'com.lufunds.sdk.asset.LuConfigInfo',
'com.lufunds.sdk.asset.impl.AuthorizeEncryptDataCallBack');
initAsset.implementation = function (context, config, callback) {
log('[LUASSET] initAsset context=' + context + ' config=' + config);
describeCallback(callback, 'initAsset');
if (TRY_LUASSET_NATIVE_FIRST) {
try {
const result = initAsset.call(this, context, config, callback);
luAssetNativeOk = true;
log('[LUASSET-NATIVE-OK] initAsset');
return result;
} catch (e) {
log('[LUASSET-NATIVE-FALLBACK] initAsset err=' + e);
log('[STABLE] anti-debug chain completed; LuAsset JNI registration is the remaining compatibility gap');
if (!verdictScheduled) {
verdictScheduled = true;
setTimeout(function () {
log('[VERDICT] antiDebug=stable nextNativeCrash=none' +
' NetSecReady=' + neteaseReady +
' LuNative=' + luAssetNativeOk +
' JniTargetRegs=' + jniTargetRegistrations);
}, 3000);
}
}
}
};

const exitLogin = LuAssetServer.exitLogin.overload();
exitLogin.implementation = function () {
if (TRY_LUASSET_NATIVE_FIRST) {
try { return exitLogin.call(this); }
catch (e) { log('[LUASSET-NATIVE-FALLBACK] exitLogin err=' + e); }
}
};

const goH5 = LuAssetServer.goH5Controller.overload('java.lang.Object', 'java.lang.String');
goH5.implementation = function (owner, url) {
if (TRY_LUASSET_NATIVE_FIRST) {
try { return goH5.call(this, owner, url); }
catch (e) { log('[LUASSET-NATIVE-FALLBACK] goH5Controller err=' + e); }
}
};

const loadView = LuAssetServer.loadAssetView.overload(
'java.lang.Object',
'android.view.ViewGroup',
'java.lang.String',
'com.lufunds.sdk.asset.impl.AuthorizeCallBack');
loadView.implementation = function (owner, container, route, callback) {
describeCallback(callback, 'loadAssetView');
if (TRY_LUASSET_NATIVE_FIRST) {
try { return loadView.call(this, owner, container, route, callback); }
catch (e) { log('[LUASSET-NATIVE-FALLBACK] loadAssetView err=' + e); }
}
};

luAssetInstalled = true;
log('[LUASSET] bridge installed nativeFirst=' + TRY_LUASSET_NATIVE_FIRST);
return true;
}

function installLuAssetBridge(reason) {
if (luAssetInstalled || typeof Java === 'undefined' || !Java.available) return;
log('[LUASSET] install begin reason=' + reason + ' javaPrimed=' + javaPrimed);

const runner = function () {
if (luAssetInstalled) return;
try {
if (installLuAssetWithFactory(Java.classFactory, reason)) return;
} catch (e0) {
log('[LUASSET] default loader miss=' + e0);
}
try {
const loaders = Java.enumerateClassLoadersSync();
for (let i = 0; i < loaders.length; i++) {
try {
if (installLuAssetWithFactory(Java.ClassFactory.get(loaders[i]), reason + '/loader#' + i)) return;
} catch (e1) {}
}
} catch (e2) {}
log('[LUASSET-FAIL] class/method bridge not installed');
};

try {
if (javaPrimed && typeof Java.performNow === 'function') Java.performNow(runner);
else Java.perform(runner);
} catch (e) {
log('[LUASSET-FAIL] install err=' + e.message);
}
}

function scheduleLuAssetBridge(reason) {
if (installed['lu-sched:' + reason] || luAssetInstalled) return;
installed['lu-sched:' + reason] = true;
let tries = 0;
const timer = setInterval(function () {
tries++;
if (luAssetInstalled || tries > 60) {
clearInterval(timer);
if (!luAssetInstalled) log('[LUASSET] schedule exhausted reason=' + reason + ' tries=' + tries);
return;
}
installLuAssetBridge(reason + '/try' + tries);
}, 100);
keepAlive.push(timer);
}

function primeJavaRuntime() {
try {
if (typeof Java === 'undefined' || !Java.available) return;
Java.perform(function () {
javaPrimed = true;
log('[JAVA] runtime primed');
installJavaCompatibility();
installNeteaseStateTrace();
});
} catch (e) {
log('[JAVA] prime failed=' + e.message);
}
}

function installNeteaseStateTrace() {
if (neteaseTraceInstalled) return;
const className = 'com.zjwh.android_wh_physicalfitness.secruity.NeteaseManager';
try {
let factory = null;
try {
Java.use(className);
factory = Java.classFactory;
} catch (e0) {
const loaders = Java.enumerateClassLoadersSync();
for (let i = 0; i < loaders.length; i++) {
try {
loaders[i].loadClass(className);
factory = Java.ClassFactory.get(loaders[i]);
break;
} catch (e) {}
}
}
if (factory === null) throw new Error('class loader pending');

const Manager = factory.use(className);
const init = Manager.init.overload('android.content.Context');
init.implementation = function (context) {
neteaseInitSeen = true;
log('[NETEASE-INIT] enter context=' + context);
const result = init.call(this, context);
try { neteaseReady = this.secruityInfo.value !== null; } catch (e) {}
log('[NETEASE-INIT] leave ready=' + neteaseReady);
return result;
};

const encrypt = Manager.encryptStringToServer.overload('java.lang.String');
encrypt.implementation = function (plainText) {
let ready = false;
try { ready = this.secruityInfo.value !== null; } catch (e) {}
if (!ready) {
log('[NETEASE-LAZY-INIT] SecruityInfo=null; retry init before encrypt');
try {
const ActivityThread = Java.use('android.app.ActivityThread');
const app = ActivityThread.currentApplication();
if (app !== null) init.call(this, app.getApplicationContext());
ready = this.secruityInfo.value !== null;
} catch (e) {
log('[NETEASE-LAZY-INIT] err=' + e);
}
neteaseReady = ready;
log('[NETEASE-LAZY-INIT] ready=' + ready);
}
return encrypt.call(this, plainText);
};

neteaseTraceInstalled = true;
log('[NETEASE-TRACE] init/encrypt compatibility installed');
} catch (e) {
neteaseTraceRound++;
if (neteaseTraceRound === 1 || neteaseTraceRound % 10 === 0)
log('[NETEASE-TRACE] waiting round=' + neteaseTraceRound);
if (neteaseTraceRound < 80) {
setTimeout(function () {
try { Java.perform(installNeteaseStateTrace); } catch (ignored) {}
}, 100);
}
}
}

function installJavaCompatibility() {
// Keep Java runtime available only for lazy init and compatibility patches.
log('[JAVA] compatibility hooks disabled');
}

const nllvmThreadCallbacks = Object.create(null);
NNLLVM_WORKERS.forEach(function (offset) {
const callback = new NativeCallback(function (arg) {
log('[NNLLVM-THREAD-BYPASS] entry=+' + offset + ' arg=' + arg + ' -> 0');
return ptr(0);
}, 'pointer', ['pointer']);
nllvmThreadCallbacks[offset] = callback;
keepAlive.push(callback);
});

function hookPthreadCreate() {
const address = findExport('libc.so', 'pthread_create') || findExport(null, 'pthread_create');
if (!address) throw new Error('pthread_create export missing');
Interceptor.attach(address, {
onEnter(args) {
this.replaced = '';
const start = args[2];
const moduleObj = moduleByAddress(start);
if (!moduleObj) return;
const offset = start.sub(moduleObj.base).toString().toLowerCase();
if (isNesec(moduleObj.name) && offset === OFF.nesecWorker.toString()) {
// Current target: user-confirmed stable path. Replace only the first libnesec worker entry.
// This prevents the early hook-environment Toast path without touching NEDialog/exit/restart.
if (!installed['nesec-first-thread']) {
installed['nesec-first-thread'] = true;
const cb = new NativeCallback(function(arg) {
log('[NESEC-FIRST-THREAD] stub hit entry=+0x110ed8 arg=' + arg + ' -> 0');
return ptr(0);
}, 'pointer', ['pointer']);
keepAlive.push(cb);
Interceptor.replace(start, cb);
log('[NESEC-FIRST-THREAD] replaced entry=' + start + ' base=' + moduleObj.base);
}
return;
}
if (isNllvm(moduleObj.name) && nllvmThreadCallbacks[offset]) {
args[2] = nllvmThreadCallbacks[offset];
this.replaced = moduleObj.name + '+' + offset;
}
},
onLeave(retval) {
if (this.replaced) log('[PTHREAD-REPLACED] ret=' + retval.toInt32() + ' reason=' + this.replaced);
}
});
}



function patchU32(moduleObj, off, word, tag) {
const address = moduleObj.base.add(ptr(off));
const before = address.readU32();
Memory.patchCode(address, 4, function (code) { code.writeU32(word >>> 0); });
log('[PATCH] ' + tag + ' addr=' + address + ' before=0x' + before.toString(16) + ' after=0x' + address.readU32().toString(16));
}

function installNesecCode4Edges(moduleObj, reason) {
if (!moduleObj) return false;
const key = 'nesec-code4:' + moduleObj.base;
if (installed[key]) return true;
try {
const pA = moduleObj.base.add(ptr('0x1041bc')); // cbnz w22 -> skip code=4; false path writes risk code 4
const pB = moduleObj.base.add(ptr('0x1042cc')); // cbnz x27 -> code=4 branch at +0x10436c
const pC = moduleObj.base.add(ptr('0x101764')); // mov w1,#4; bl +0x13783c; exact early hook-risk code path
const a = pA.readU32();
const b = pB.readU32();
const c = pC.readU32();
// Runtime text is decoded asynchronously. Only patch after exact decoded bytes appear.
if (a !== 0x35000136 || b !== 0xb500051b || c !== 0x52800081) {
if (!installed[key + ':poll']) {
installed[key + ':poll'] = true;
let tries = 0;
const timer = setInterval(function () {
tries++;
if (installNesecCode4Edges(moduleObj, reason + '/poll' + tries) || tries > 300) clearInterval(timer);
}, 5);
}
if (reason.indexOf('/poll') < 0 || /\/poll(50|100|150|200|250|300)$/.test(reason)) {
log('[NESEC-CODE4] wait decoded reason=' + reason + ' base=' + moduleObj.base +
' pA=0x' + a.toString(16) + ' pB=0x' + b.toString(16) + ' pC=0x' + c.toString(16));
}
return false;
}
installed[key] = true;
// A: force the earlier exact code=4 edge to continue at +0x1041e0 instead of executing the code=4 store.
patchU32(moduleObj, '0x1041bc', 0x14000009, 'nesec+0x1041bc code4_edge_A force_continue');
// B: neutralize the later exact code=4 edge; fall through to normal scan continuation.
patchU32(moduleObj, '0x1042cc', 0xd503201f, 'nesec+0x1042cc code4_edge_B nop');
// C: exact MyJni.load early hook-risk edge: do not report code=4 into libnesec risk dispatcher.
patchU32(moduleObj, '0x101764', 0x14000010, 'nesec+0x101764 code4_edge_C skip_report');
log('[NESEC-CODE4] installed reason=' + reason + ' base=' + moduleObj.base);
return true;
} catch (e) {
log('[NESEC-CODE4-FAIL] ' + e.message + ' reason=' + reason);
return false;
}
}

function installGtcore(moduleObj, reason) {
if (!moduleObj) return;
const key = 'gt:' + moduleObj.base;
if (installed[key]) return;
installed[key] = true;
try {
patchRet0(moduleObj, ptr('0x48fa4'), 'gtcore+0x48fa4 jdwp_art_probe_false');
log('[GTCORE] ready base=' + moduleObj.base + ' reason=' + reason);
} catch (e) {
log('[GTCORE-FAIL] ' + e.message);
}
}

function installLoadedTargets(reason) {
installNesecCode4Edges(findLoaded(isNesec), reason);
installMsaoaid(findLoaded(isMsaoaid), reason);
installNllvm(findLoaded(isNllvm), reason);
installGtcore(findLoaded(isGtcore), reason);
}

function hookLinker() {
const linker = moduleByName('linker64') || moduleByName('linker');
if (!linker) throw new Error('linker module missing');

let doDlopen = null;
let callConstructors = null;
const symbols = linker.enumerateSymbols();
for (let i = 0; i < symbols.length; i++) {
const name = symbols[i].name;
if (!doDlopen && name.indexOf('do_dlopen') !== -1) doDlopen = symbols[i].address;
if (!callConstructors && name.indexOf('call_constructors') !== -1) callConstructors = symbols[i].address;
}

if (callConstructors) {
Interceptor.attach(callConstructors, {
onEnter() {
installLoadedTargets('call_constructors');
}
});
}

if (!doDlopen) throw new Error('do_dlopen symbol missing');
Interceptor.attach(doDlopen, {
onEnter(args) {
this.path = readCString(args[0]);
this.nn = isNllvm(this.path);
this.ms = isMsaoaid(this.path);
this.gt = isGtcore(this.path);
this.ne = isNesec(this.path);
if (this.nn || this.ms || isGtcore(this.path) || isNesec(this.path) || this.path.toLowerCase().indexOf('libcrashsdk.so') !== -1) {
log('[DLOPEN] path=' + this.path);
}
},
onLeave(retval) {
if (this.ne) {
installNesecCode4Edges(findLoaded(isNesec), 'nesec-dlopen-ret');
log('[DLOPEN] nesec ret=' + retval);
}
if (this.ms) {
installMsaoaid(findLoaded(isMsaoaid), 'msaoaid-dlopen-ret');
log('[DLOPEN] msaoaid ret=' + retval);
}
if (this.gt) {
installGtcore(findLoaded(isGtcore), 'gtcore-dlopen-ret');
log('[DLOPEN] gtcore ret=' + retval);
}
if (this.nn) {
installNllvm(findLoaded(isNllvm), 'nllvm-dlopen-ret');
log('[DLOPEN] nllvm ret=' + retval);
installLuAssetBridge('nllvm-dlopen-ret');
log('[DLOPEN] nllvm post-bridge installed=' + luAssetInstalled);
}
}
});
log('[INIT] linker hooks ready base=' + linker.base);
}


const procMapFds = Object.create(null);
const procMapFiles = Object.create(null);
let mapsHideCount = 0;
function isFromNesecContext(ctx) {
try { const m = moduleByAddress(ctx.returnAddress); return !!(m && isNesec(m.name)); } catch (e) { return false; }
}
function isMapsPath(p) { return !!p && (p === '/proc/self/maps' || /\/proc\/\d+\/maps$/.test(p)); }
function badMapLine(s) { return /frida|gum-js|gadget|linjector|substrate|xposed|memfd:frida|frida-agent|pool-frida|re\.frida/i.test(s); }
function sanitizeMapsText(raw) {
if (!raw || !badMapLine(raw)) return raw;
const parts = raw.split('\n');
const out = [];
for (let i = 0; i < parts.length; i++) {
const line = parts[i];
if (badMapLine(line)) continue;
out.push(line);
}
let clean = out.join('\n');
if (raw.endsWith('\n') && !clean.endsWith('\n')) clean += '\n';
if (clean.length === 0) clean = '\n';
return clean;
}
function installNesecMapsSanitize() {
const fopenPtr = findExport('libc.so', 'fopen') || findExport(null, 'fopen');
const fgetsPtr = findExport('libc.so', 'fgets') || findExport(null, 'fgets');
const openPtr = findExport('libc.so', 'open') || findExport(null, 'open');
const openatPtr = findExport('libc.so', 'openat') || findExport(null, 'openat');
const readPtr = findExport('libc.so', 'read') || findExport(null, 'read');
const closePtr = findExport('libc.so', 'close') || findExport(null, 'close');
const fclosePtr = findExport('libc.so', 'fclose') || findExport(null, 'fclose');
if (fopenPtr) Interceptor.attach(fopenPtr, {
onEnter(args) { this.path = readCString(args[0]); this.track = isMapsPath(this.path) && isFromNesecContext(this); },
onLeave(retval) { if (this.track && !retval.isNull()) { procMapFiles[retval.toString()] = true; if (!installed['maps-track-log']) { installed['maps-track-log'] = true; log('[MAPS-SAN] tracking libnesec maps FILE reads'); } } }
});
if (fgetsPtr) Interceptor.attach(fgetsPtr, {
onEnter(args) { this.buf = args[0]; this.size = args[1].toInt32(); this.file = args[2]; this.track = !!procMapFiles[this.file.toString()]; },
onLeave(retval) {
if (!this.track || retval.isNull()) return;
try {
const raw = this.buf.readCString();
if (badMapLine(raw)) {
const clean = sanitizeMapsText(raw);
const max = Math.max(1, this.size - 1);
this.buf.writeUtf8String(clean.slice(0, max));
mapsHideCount++; if (mapsHideCount <= 4 || mapsHideCount % 50 === 0) log('[MAPS-SAN] hidden maps lines count=' + mapsHideCount);
}
} catch (e) { log('[MAPS-SAN] fgets err=' + e.message); }
}
});
if (openPtr) Interceptor.attach(openPtr, {
onEnter(args) { this.path = readCString(args[0]); this.track = isMapsPath(this.path) && isFromNesecContext(this); },
onLeave(retval) { if (this.track) { const fd=retval.toInt32(); if (fd>=0) { procMapFds[fd]=true; if (!installed['maps-fd-log']) { installed['maps-fd-log'] = true; log('[MAPS-SAN] tracking libnesec maps fd reads'); } } } }
});
if (openatPtr) Interceptor.attach(openatPtr, {
onEnter(args) { this.path = readCString(args[1]); this.track = isMapsPath(this.path) && isFromNesecContext(this); },
onLeave(retval) { if (this.track) { const fd=retval.toInt32(); if (fd>=0) { procMapFds[fd]=true; if (!installed['maps-fd-log']) { installed['maps-fd-log'] = true; log('[MAPS-SAN] tracking libnesec maps fd reads'); } } } }
});
if (readPtr) Interceptor.attach(readPtr, {
onEnter(args) { const fd=args[0].toInt32(); this.track=!!procMapFds[fd]; this.buf=args[1]; this.fd=fd; },
onLeave(retval) {
if (!this.track) return;
const n=retval.toInt32(); if (n<=0) return;
try {
const raw=this.buf.readCString(n);
if (badMapLine(raw)) {
const clean=sanitizeMapsText(raw);
const bytes=Memory.allocUtf8String(clean);
const len=Math.min(clean.length, n-1);
this.buf.writeByteArray(bytes.readByteArray(len));
retval.replace(ptr(len));
mapsHideCount++; if (mapsHideCount <= 4 || mapsHideCount % 50 === 0) log('[MAPS-SAN] hidden maps chunks/lines count=' + mapsHideCount);
}
} catch(e) { log('[MAPS-SAN] read err=' + e.message); }
}
});
if (closePtr) Interceptor.attach(closePtr, { onEnter(args){ delete procMapFds[args[0].toInt32()]; } });
if (fclosePtr) Interceptor.attach(fclosePtr, { onEnter(args){ delete procMapFiles[args[0].toString()]; } });
log('[MAPS-SAN] installed targeted libnesec /proc/maps sanitizer');
}


// ---- Outdoor run lightweight hooks (merged from hook_outdoor_run.js, sanitized) ----
const OUTDOOR_CFG = {
printIntervalMs: 3000,
pollIntervalMs: 1000,
maxPolls: 180,
target: 'com.zjwh.android_wh_physicalfitness.mvi.sport.outdoor.RunUiState',
vm: 'com.zjwh.android_wh_physicalfitness.mvi.sport.outdoor.OutdoorRunViewModel',
record: 'com.zjwh.android_wh_physicalfitness.utils.sport.SportRecordManager'
};

let outdoorInstalled = false;
let outdoorPollCount = 0;
let outdoorLastPrintTime = 0;
let outdoorStarted = false;
let outdoorLast = { d: '', t: '', p: '', s: 0, k: 0, g: -1 };


// Fake-data profile. Keep this scoped to Outdoor Run UI state only.
// distance/time/pace are generated after the app enters real running state.
const OUTDOOR_FAKE = {
enabled: true,
// Do not force the app into running state from idle; wait until its own startRun/copy says running=true.
onlyWhenAppRunning: true,
// Simulation speed. 2.80 m/s ~= 10.08 km/h ~= 5'57" / km.
speedMps: 2.80,
// If you want faster/slower virtual progress than wall clock, change this.
timeScale: 1.0,
stepFreq: 172,
gpsLevel: 4,
kcalPerKm: 62,
// Upload/local-finish validator uses OutdoorRunViewModel.mTotalDis in meters.
minUploadDistanceM: 1200,
minUploadTimeSec: 600,
minUploadSteps: 1600,
minDistanceKm: 0.00,
// Fallback outdoor track. Used only when the app/server detail data is empty.
// Keep it small and deterministic: enough points for the detail map, not a broad DB rewrite.
baseLat: 38.9140,
baseLng: 121.6147,
trackPoints: 21,
coorType: 'gcj02',
// End protection: do not forge end=true. Let app/user end naturally.
forceEndFalse: false,
verboseEveryMs: 3000
};

let outdoorFakeStartMs = 0;
let outdoorFakeLastLogMs = 0;
let outdoorStartRunSeen = false;


function outdoorFakeTotalsForSubmit(now) {
const fake = outdoorFakeStateFromNow(now || Date.now());
const meters = Math.max(OUTDOOR_FAKE.minUploadDistanceM, Math.round(Number(fake.d) * 1000));
const seconds = Math.max(OUTDOOR_FAKE.minUploadTimeSec, Math.round(fake.elapsedSec || 0));
const kcal = Math.max(1, Math.round((meters / 1000.0) * OUTDOOR_FAKE.kcalPerKm));
const steps = Math.max(OUTDOOR_FAKE.minUploadSteps, Math.round(seconds * OUTDOOR_FAKE.stepFreq / 60.0));
return { meters: meters, seconds: seconds, kcal: kcal, steps: steps };
}

let outdoorLastArtifacts = null;
let outdoorFakeRunUuids = {};
let outdoorLastSuccessUuid = '';
let outdoorCurrentUploadUuid = '';
let outdoorLastSuccessRrid = 0;
let outdoorDetailActiveUntilMs = 0;
let outdoorDetailPatchDepth = 0;
let outdoorDetailCurrentActivity = null;
let outdoorDetailViewDiagUntilMs = 0;
let outdoorDetailRenderSessionKey = '';
let outdoorDetailRenderResetCount = 0;
let outdoorUploadSuccessUnique = {};
let outdoorUploadSuccessUniqueCount = 0;
let outdoorDetailSecondPlaceholderActive = false;
let outdoorDetailPlaceholderApplyCount = 0;
let outdoorWHMapViewPlaceholderHooksInstalled = false;

function outdoorDetailClassName(obj) {
try { return obj && obj.getClass ? obj.getClass().getName().toString() : String(obj); } catch (e) { return '<class-err:' + e.message + '>'; }
}

function outdoorDetailIsDetailActivity(obj) {
try { return outdoorDetailClassName(obj).indexOf('RunHistoryDetailActivity') >= 0; } catch (e) { return false; }
}

function outdoorDetailActivityKey(activity) {
try {
if (!activity) return '';
return outdoorDetailClassName(activity) + '#' + activity.hashCode();
} catch (e) { return '<act-key-err>'; }
}

function outdoorDetailResetRenderState(activity, why, force) {
try {
const key = activity ? outdoorDetailActivityKey(activity) : ('global#' + why);
if (!force && key && key === outdoorDetailRenderSessionKey) return false;
outdoorDetailRenderSessionKey = key;
outdoorDetailSecondPlaceholderActive = activity ? outdoorDetailIsDetailActivity(activity) : false;
outdoorDetailPlaceholderApplyCount = 0;
outdoorDetailViewDiagUntilMs = Date.now() + 45000;
outdoorDetailRenderResetCount++;
log('[OUTDOOR-RENDER] reset session#' + outdoorDetailRenderResetCount + ' why=' + why + ' key=' + key + ' placeholder=' + outdoorDetailSecondPlaceholderActive);
return true;
} catch (e) {
log('[OUTDOOR-RENDER] reset err why=' + why + ' err=' + e.message);
return false;
}
}


function outdoorExtractUuidFromText(x) {
try {
const t = outdoorS(x);
const m = /uuid='([^']+)'/.exec(t) || /uuid=([0-9a-fA-F-]{20,})/.exec(t) || /"uuid"\s*:\s*"([^"]+)"/.exec(t);
if (m && m[1] && m[1] !== 'null') return m[1];
} catch (e) {}
return '';
}

function outdoorRememberCurrentUuid(uuid, why) {
try {
uuid = outdoorS(uuid);
if (!uuid || uuid === 'null') return false;
outdoorCurrentUploadUuid = uuid;
outdoorLastSuccessUuid = uuid;
outdoorFakeRunUuids[uuid] = true;
if (why && why.indexOf('uploadSuccess') === 0 && !outdoorUploadSuccessUnique[uuid]) {
outdoorUploadSuccessUnique[uuid] = true;
outdoorUploadSuccessUniqueCount++;
log('[OUTDOOR-NET] unique upload count=' + outdoorUploadSuccessUniqueCount + ' uuid=' + uuid);
}
log('[OUTDOOR-NET] current uuid set why=' + why + ' uuid=' + uuid);
return true;
} catch (e) { log('[OUTDOOR-NET] current uuid set err why=' + why + ' err=' + e.message); return false; }
}

const OUTDOOR_ID_RUN_HISTORY_MAP = 0x7f0a0ce7;
const OUTDOOR_ID_RUN_HISTORY_MAP_DATA = 0x7f0a0ce8;
const OUTDOOR_ID_RUN_MAP_PLACEHOLDER = 0x7f0a03e1;
const OUTDOOR_ID_RUN_HIS_SCROLL = 0x7f0a0ce6;
const OUTDOOR_ID_BOTTOM_LAYOUT = 0x7f0a01a4;
const OUTDOOR_ID_HISTORY_TITLE = 0x7f0a0483;

function outdoorJavaCall(obj, name, args, defv) { try { return obj && typeof obj[name] === 'function' ? obj[name].apply(obj, args || []) : defv; } catch (e) { return defv; } }

function outdoorJavaSet(obj, name, args) {
outdoorJavaCall(obj, name, args || [], null);
}

function outdoorDetailClearPlaceholderState(why) { outdoorDetailSecondPlaceholderActive = false; outdoorDetailCurrentActivity = null; outdoorDetailViewDiagUntilMs = 0; outdoorDetailRenderSessionKey = ''; }

function outdoorIsDetailMapView(v) {
try {
if (!v || !outdoorDetailCurrentActivity) return false;
if (!outdoorDetailIsDetailActivity(outdoorDetailCurrentActivity)) return false;
const vid = outdoorJavaCall(v, 'getId', [], -1);
if (vid === OUTDOOR_ID_RUN_HISTORY_MAP) return true;
const win = outdoorJavaCall(outdoorDetailCurrentActivity, 'getWindow', [], null);
const decor = win ? outdoorJavaCall(win, 'getDecorView', [], null) : null;
const root = outdoorJavaCall(v, 'getRootView', [], null);
if (!decor || !root) return false;
try { if (root.equals && root.equals(decor)) return true; } catch (eEq) {}
try { return root.hashCode && decor.hashCode && root.hashCode() === decor.hashCode(); } catch (eHash) {}
return false;
} catch (e) {
return false;
}
}

function outdoorDetailApplyPlaceholder(factory, activity, why) {
try {
if (!outdoorDetailSecondPlaceholderActive || !activity || !outdoorDetailIsDetailActivity(activity)) return false;
outdoorDetailPlaceholderApplyCount++;
const win = outdoorJavaCall(activity, 'getWindow', [], null);
const decor = win ? outdoorJavaCall(win, 'getDecorView', [], null) : null;
try { if (win) outdoorJavaSet(win, 'setBackgroundDrawable', [factory.use('android.graphics.drawable.ColorDrawable').$new(-1)]); } catch (eBgWin) {}
if (decor) {
outdoorJavaSet(decor, 'setBackgroundColor', [-1]);
outdoorJavaSet(decor, 'setAlpha', [1.0]);
outdoorJavaSet(decor, 'bringToFront', []);
outdoorJavaSet(decor, 'invalidate', []);
outdoorJavaSet(decor, 'postInvalidate', []);
}
function byId(id) {
return outdoorJavaCall(activity, 'findViewById', [id], null);
}
const map = byId(OUTDOOR_ID_RUN_HISTORY_MAP);
const mapData = byId(OUTDOOR_ID_RUN_HISTORY_MAP_DATA);
const ph = byId(OUTDOOR_ID_RUN_MAP_PLACEHOLDER);
const scroll = byId(OUTDOOR_ID_RUN_HIS_SCROLL);
const bottom = byId(OUTDOOR_ID_BOTTOM_LAYOUT);
const title = byId(OUTDOOR_ID_HISTORY_TITLE);
try {
if (map) {
outdoorJavaSet(map, 'onPause', []);
outdoorJavaSet(map, 'setVisibility', [8]);
outdoorJavaSet(map, 'setAlpha', [0.0]);
outdoorJavaSet(map, 'setBackgroundColor', [-1]);
outdoorJavaSet(map, 'invalidate', []);
}
if (ph) {
outdoorJavaSet(ph, 'setVisibility', [0]);
outdoorJavaSet(ph, 'setAlpha', [1.0]);
outdoorJavaSet(ph, 'setBackgroundColor', [-1]);
outdoorJavaSet(ph, 'bringToFront', []);
outdoorJavaSet(ph, 'invalidate', []);
outdoorJavaSet(ph, 'postInvalidate', []);
}
if (mapData) {
outdoorJavaSet(mapData, 'setVisibility', [0]);
outdoorJavaSet(mapData, 'setAlpha', [1.0]);
outdoorJavaSet(mapData, 'setBackgroundColor', [-1]);
outdoorJavaSet(mapData, 'invalidate', []);
outdoorJavaSet(mapData, 'postInvalidate', []);
}
[scroll, bottom, title].forEach(function (v) {
try {
if (!v) return;
outdoorJavaSet(v, 'setVisibility', [0]);
outdoorJavaSet(v, 'setAlpha', [1.0]);
outdoorJavaSet(v, 'setBackgroundColor', [-1]);
outdoorJavaSet(v, 'bringToFront', []);
outdoorJavaSet(v, 'invalidate', []);
outdoorJavaSet(v, 'postInvalidate', []);
} catch (eEach) {}
});
} catch (eSet) {}
if (outdoorDetailPlaceholderApplyCount <= 16) {
log('[OUTDOOR-PLACEHOLDER] apply#' + outdoorDetailPlaceholderApplyCount + ' why=' + why +
' map=' + (map ? outdoorDetailClassName(map) : 'null') +
' mapVis=' + outdoorJavaCall(map, 'getVisibility', [], -1) +
' phVis=' + outdoorJavaCall(ph, 'getVisibility', [], -1) +
' mapData=' + (mapData ? (outdoorJavaCall(mapData, 'getWidth', [], -1) + 'x' + outdoorJavaCall(mapData, 'getHeight', [], -1)) : 'null'));
}
return true;
} catch (e) {
log('[OUTDOOR-PLACEHOLDER] apply err why=' + why + ' err=' + e.message);
return false;
}
}

function outdoorDetailSchedulePlaceholder(factory, activity, why, delayMs) {
try {
if (!outdoorDetailSecondPlaceholderActive || !activity || !outdoorDetailIsDetailActivity(activity)) return;
const held = Java.retain(activity);
setTimeout(function () {
Java.perform(function () {
try {
const run = function () { outdoorDetailApplyPlaceholder(factory || Java.classFactory, held, why + '+' + delayMs + 'ms'); };
if (Java.scheduleOnMainThread) Java.scheduleOnMainThread(run); else run();
} catch (e) { log('[OUTDOOR-PLACEHOLDER] scheduled err why=' + why + ' err=' + e.message); }
});
}, Math.max(0, delayMs || 0));
} catch (e) {
log('[OUTDOOR-PLACEHOLDER] schedule err why=' + why + ' err=' + e.message);
}
}

function outdoorInstallWHMapViewPlaceholderHooks(factory) {
if (outdoorWHMapViewPlaceholderHooksInstalled) return;
outdoorWHMapViewPlaceholderHooksInstalled = true;
try {
const WHMapView = factory.use('com.zjwh.android_wh_physicalfitness.utils.map.WHMapView');
['onCreate', 'onStart', 'onResume', 'onPause', 'onStop', 'onDestroy'].forEach(function (mn) {
try {
if (!WHMapView[mn] || !WHMapView[mn].overloads) return;
WHMapView[mn].overloads.forEach(function (ol, idx) {
ol.implementation = function () {
try {
if (outdoorDetailSecondPlaceholderActive && outdoorIsDetailMapView(this)) {
outdoorJavaSet(this, 'setVisibility', [8]);
outdoorJavaSet(this, 'setAlpha', [0.0]);
if (outdoorDetailPlaceholderApplyCount <= 20) {
log('[OUTDOOR-PLACEHOLDER] skip detail WHMapView.' + mn + '#' + idx +
' id=' + outdoorJavaCall(this, 'getId', [], -1) + ' argc=' + arguments.length);
}
return;
}
} catch (eSkip) {}
return ol.apply(this, arguments);
};
});
log('[OUTDOOR-PLACEHOLDER] WHMapView.' + mn + ' hooked overloads=' + WHMapView[mn].overloads.length);
} catch (eMn) { log('[OUTDOOR-PLACEHOLDER] WHMapView hook miss ' + mn + ' err=' + eMn.message); }
});
} catch (e) {
log('[OUTDOOR-PLACEHOLDER] WHMapView hook miss=' + e.message);
}
}

function outdoorDetailRememberActivity(factory, activity, why) {
try {
if (!activity || !outdoorDetailIsDetailActivity(activity)) return;
if (why.indexOf('onCreate') >= 0 && why.indexOf('.enter') >= 0) {
outdoorDetailResetRenderState(activity, why, true);
} else {
outdoorDetailResetRenderState(activity, why, false);
}
outdoorDetailCurrentActivity = Java.retain(activity);
outdoorDetailViewDiagUntilMs = Date.now() + 45000;
try {
if (outdoorDetailSecondPlaceholderActive) {
outdoorDetailSchedulePlaceholder(factory, activity, why, 30);
outdoorDetailSchedulePlaceholder(factory, activity, why, 220);
}
} catch (ePhRemember) {}
} catch (e) { log('[OUTDOOR-VIEW] remember err why=' + why + ' err=' + e.message); }
}

function outdoorIsEmptyJsonLike(s) {
const v = outdoorS(s).trim();
return v.length === 0 || v === 'null' || v === '[]' || v === '{}';
}

function outdoorTryCall(obj, methodName) {
try {
if (obj && obj[methodName]) return obj[methodName]();
} catch (e) {}
return null;
}


function outdoorBuildDetailSeriesJsons(startMs, totals) {
totals = totals || outdoorFakeTotalsForSubmit(Date.now());
startMs = Number(startMs || (Date.now() - totals.seconds * 1000));
const seconds = Math.max(1, Number(totals.seconds || OUTDOOR_FAKE.minUploadTimeSec));
const meters = Math.max(1, Number(totals.meters || OUTDOOR_FAKE.minUploadDistanceM));
const stepsTotal = Math.max(1, Number(totals.steps || OUTDOOR_FAKE.minUploadSteps));
const slots = Math.max(1, Math.ceil(seconds / 10));
const steps = [];
const speed = [];
let usedSteps = 0;
let usedDist = 0;
for (let i = 0; i < slots; i++) {
const beginSec = i * 10;
const endSec = Math.min(seconds, (i + 1) * 10);
const span = Math.max(1, endSec - beginSec);
const begin = startMs + beginSec * 1000;
const end = startMs + endSec * 1000;
let sn = Math.round(OUTDOOR_FAKE.stepFreq * span / 60.0);
if (i === slots - 1) sn = Math.max(1, stepsTotal - usedSteps);
usedSteps += sn;
const dist = (i === slots - 1) ? Math.max(0, meters - usedDist) : Math.round((meters / seconds * span) * 100) / 100;
usedDist += dist;
steps.push({
stepsNum: sn,
beginTime: begin,
endTime: end,
flag: begin,
maxDiff: 0.0,
minDiff: 0.0,
avgDiff: 0.0,
state: 1,
queueNum: i,
id: i + 1
});
speed.push({
distance: dist,
beginTime: begin,
endTime: end,
flag: begin,
state: 1,
queueNum: i,
id: i + 1
});
}
const laps = [{
avgCadence: OUTDOOR_FAKE.stepFreq,
avgPace: Math.round(seconds * 1000.0 / meters) / 1000.0,
avgStride: Math.round((meters / stepsTotal) * 1000.0) / 1000.0,
cumulativeDuration: seconds,
distance: meters,
duration: seconds,
elevationGain: 0.0,
endAltAbs: 0.0,
endAltRel: 0.0,
flag: startMs,
id: 1,
isFullLap: true,
lapIndex: 1,
step: stepsTotal
}];
return {
stepJson: JSON.stringify(steps),
speedJson: JSON.stringify(speed),
segmentJson: '[]',
lapsJson: JSON.stringify(laps),
altitudeJson: '[]'
};
}

function outdoorBuildFakeFivePointJson(lat0, lng0, lngDelta, startMs, totals) {
try {
const pts = [];
for (let i = 0; i < 5; i++) {
const ratio = i / 4.0;
const lat = lat0 + 0.00003 * Math.sin(ratio * Math.PI * 2);
const lng = lng0 + lngDelta * ratio;
pts.push({
id: i + 1,
position: i + 1,
pointName: 'P' + (i + 1),
lat: lat,
lon: lng,
glat: lat,
glon: lng,
flag: startMs + Math.round((totals.seconds || OUTDOOR_FAKE.minUploadTimeSec) * ratio) * 1000,
isFixed: 1,
isPass: true,
state: 1
});
}
return JSON.stringify(pts);
} catch (e) {
return '[]';
}
}

function outdoorMaybeFakeUuid(uuid) {
uuid = outdoorS(uuid);
if (uuid.length === 0 || uuid === 'null') return false;
return !!outdoorFakeRunUuids[uuid] || (outdoorCurrentUploadUuid.length > 0 && uuid === outdoorCurrentUploadUuid) || (outdoorLastSuccessUuid.length > 0 && uuid === outdoorLastSuccessUuid);
}

function outdoorIsTargetDetailBean(bean) {
if (!bean) return false;
let uuid = '';
try { uuid = outdoorEntityString(bean, 'getUuid', ''); } catch (e0) {}
if (outdoorMaybeFakeUuid(uuid)) return true;
if (outdoorLastSuccessUuid.length > 0) {
try {
const all = bean.getAllLocJson ? bean.getAllLocJson() : '';
if (outdoorIsEmptyJsonLike(all)) return true;
} catch (e1) { return true; }
}
return false;
}

function outdoorPatchRunHistoryDetailBean(factory, bean, why) {
if (!bean || !OUTDOOR_FAKE.enabled) return null;
if (outdoorDetailPatchDepth > 0) return outdoorLastArtifacts;
if (!outdoorIsTargetDetailBean(bean)) return null;
outdoorDetailPatchDepth++;
let st = outdoorReadEntityNumber(bean, 'getStartTime', 'startTime');
const artifacts = outdoorLastArtifacts || outdoorBuildFakeTrackArtifacts(factory || Java.classFactory, st, why + '.artifacts');
if (!artifacts) { outdoorDetailPatchDepth--; return null; }
try {
const uuid = outdoorEntityString(bean, 'getUuid', '');
if (uuid && uuid !== 'null') outdoorFakeRunUuids[uuid] = true;
} catch (eMark) {}
outdoorCallNoThrow(bean, 'setAllLocJson', ['java.lang.String'], [artifacts.locEntityJson]);
outdoorCallNoThrow(bean, 'setFivePointJson', ['java.lang.String'], [artifacts.pointEntityJson]);
outdoorCallNoThrow(bean, 'setSegmentJson', ['java.lang.String'], [artifacts.segmentJson]);
outdoorCallNoThrow(bean, 'setJsonFromObs', ['int'], [0]);
outdoorCallNoThrow(bean, 'setIsUpload', ['boolean'], [true]);
outdoorCallNoThrow(bean, 'setTotalSteps', ['int'], [artifacts.totals.steps]);
outdoorCallNoThrow(bean, 'setAvgStepFreq', ['int'], [OUTDOOR_FAKE.stepFreq]);
outdoorCallNoThrow(bean, 'setCalorie', ['int'], [artifacts.totals.kcal]);
outdoorCallNoThrow(bean, 'setTotalDis', ['int'], [artifacts.totals.meters]);
outdoorCallNoThrow(bean, 'setTotalTime', ['long'], [artifacts.totals.seconds]);
outdoorCallNoThrow(bean, 'setValidDis', ['int'], [artifacts.totals.meters]);
outdoorCallNoThrow(bean, 'setValidTime', ['long'], [artifacts.totals.seconds]);
outdoorSetField(bean, 'allLocJson', 'object', artifacts.locEntityJson);
outdoorSetField(bean, 'fivePointJson', 'object', artifacts.pointEntityJson);
outdoorSetField(bean, 'segmentJson', 'object', artifacts.segmentJson);
outdoorSetField(bean, 'jsonFromObs', 'int', 0);
outdoorSetField(bean, 'totalSteps', 'int', artifacts.totals.steps);
outdoorSetField(bean, 'avgStepFreq', 'int', OUTDOOR_FAKE.stepFreq);
outdoorSetField(bean, 'calorie', 'int', artifacts.totals.kcal);
outdoorDetailActiveUntilMs = Date.now() + 120000;
log('[OUTDOOR-DETAIL] patched bean why=' + why +
' uuid=' + outdoorEntityString(bean, 'getUuid', '') +
' all=' + artifacts.locEntityJson.length +
' step=' + artifacts.stepJson.length +
' speed=' + artifacts.speedJson.length +
' laps=' + artifacts.lapsJson.length);
outdoorDetailPatchDepth--;
return artifacts;
}

function outdoorPatchRunHistoryDetailPImpl(factory, pimpl, why) {
if (!pimpl || !OUTDOOR_FAKE.enabled) return null;
let bean = null;
try { if (pimpl.getRunHistoryDetailBean) bean = pimpl.getRunHistoryDetailBean(); } catch (e0) {}
if (!bean) {
try { bean = outdoorReadField(pimpl, 'mRunHistoryDetailBean'); } catch (e1) {}
}
const artifacts = outdoorPatchRunHistoryDetailBean(factory, bean, why + '.bean') || outdoorLastArtifacts;
if (!artifacts) return null;
outdoorSetField(pimpl, 'mStepsPerTenSec', 'object', artifacts.stepJson);
outdoorSetField(pimpl, 'mSpeedPerTenSec', 'object', artifacts.speedJson);
outdoorSetField(pimpl, 'mSegmentJson', 'object', artifacts.segmentJson);
outdoorSetField(pimpl, 'mRunFaceCheck', 'object', '');
outdoorSetField(pimpl, 'mLapsJson', 'object', artifacts.lapsJson);
outdoorSetField(pimpl, 'isUncompress', 'boolean', true);
outdoorSetField(pimpl, 'mTotalSteps', 'int', artifacts.totals.steps);
outdoorSetField(pimpl, 'mAvgStepFreq', 'int', OUTDOOR_FAKE.stepFreq);
outdoorDetailActiveUntilMs = Date.now() + 120000;
log('[OUTDOOR-DETAIL] patched PImpl why=' + why +
' stepsLen=' + artifacts.stepJson.length +
' speedLen=' + artifacts.speedJson.length +
' lapsLen=' + artifacts.lapsJson.length);
return artifacts;
}

function outdoorBuildSWLatLngList(factory, artifacts, why) {
try {
if (!artifacts) artifacts = outdoorLastArtifacts || outdoorBuildFakeTrackArtifacts(factory || Java.classFactory, 0, why + '.sw');
const ArrayList = factory.use('java.util.ArrayList');
const SWLatLng = factory.use('com.zjwh.sw.map.entity.SWLatLng');
const list = ArrayList.$new();
const arr = JSON.parse(artifacts.locListJson || '[]');
for (let i = 0; i < arr.length; i++) {
const x = arr[i];
list.add(SWLatLng.$new(Number(x.gLat || x.lat || 0), Number(x.gLng || x.lng || 0), Number(x.lat || x.gLat || 0), Number(x.lng || x.gLng || 0)));
}
return list;
} catch (e) {
log('[OUTDOOR-DETAIL] build SWLatLng list err why=' + why + ' err=' + e.message);
return null;
}
}

function outdoorBuildManualTrackArtifacts(startMs, why, cause) {
const totals = outdoorFakeTotalsForSubmit(Date.now());
startMs = Number(startMs || 0);
if (!startMs || isNaN(startMs) || startMs < 1000000000000) startMs = Date.now() - totals.seconds * 1000;
const n = Math.max(2, OUTDOOR_FAKE.trackPoints | 0);
const lat0 = OUTDOOR_FAKE.baseLat;
const lng0 = OUTDOOR_FAKE.baseLng;
const metersPerLngDeg = 111320.0 * Math.cos(lat0 * Math.PI / 180.0);
const lngDelta = totals.meters / metersPerLngDeg;
const arr = [];
for (let i = 0; i < n; i++) {
const ratio = i / (n - 1);
const lat = lat0 + 0.00003 * Math.sin(ratio * Math.PI * 2);
const lng = lng0 + lngDelta * ratio;
const sec = Math.round(totals.seconds * ratio);
const dis = totals.meters * ratio;
const ts = startMs + sec * 1000;
arr.push({
id: i + 1,
lng: lng,
lat: lat,
gLng: lng,
gLat: lat,
gainTime: outdoorFmtDateTimeMs(ts),
type: 0,
avgSpeed: OUTDOOR_FAKE.speedMps,
speed: OUTDOOR_FAKE.speedMps,
locType: 61,
radius: 8.0,
totalTime: sec,
totalDis: dis,
flag: ts,
count: i + 1,
validDis: dis,
validTime: sec,
bdG: OUTDOOR_FAKE.gpsLevel,
state: 1,
stepDistance: i === 0 ? 0 : totals.meters / (n - 1),
coorType: OUTDOOR_FAKE.coorType
});
}
const locListJson = JSON.stringify(arr);
const fivePointListJson = outdoorBuildFakeFivePointJson(lat0, lng0, lngDelta, startMs, totals);
const pointEntityJson = JSON.stringify({ useZip: false, fivePointJson: fivePointListJson, runAreaId: -1, geoFencesJson: '', freedomShowFence: false });
const series = outdoorBuildDetailSeriesJsons(startMs, totals);
const ret = {
locList: null,
locListJson: locListJson,
locEntityJson: JSON.stringify({ useZip: false, allLocJson: locListJson }),
pointEntityJson: pointEntityJson,
segmentJson: series.segmentJson,
lapsJson: series.lapsJson,
stepJson: series.stepJson,
speedJson: series.speedJson,
altitudeJson: series.altitudeJson,
startMs: startMs,
stopMs: startMs + totals.seconds * 1000,
lat: lat0,
lng: lng0,
totals: totals
};
outdoorLastArtifacts = ret;
log('[OUTDOOR-TRACK] built manual fake track why=' + why +
(cause ? ' cause=' + cause : '') +
' points=' + n + ' dis=' + totals.meters + ' time=' + totals.seconds +
' locJsonLen=' + ret.locEntityJson.length);
return ret;
}

function outdoorBuildFakeTrackArtifacts(factory, startMs, why) {
const totals = outdoorFakeTotalsForSubmit(Date.now());
startMs = Number(startMs || 0);
if (!startMs || isNaN(startMs) || startMs < 1000000000000) startMs = Date.now() - totals.seconds * 1000;

try {
const ArrayList = factory.use('java.util.ArrayList');
const MyLocation = factory.use('com.zjwh.android_wh_physicalfitness.entity.database.MyLocation');
const GsonUtil = factory.use('com.zjwh.android_wh_physicalfitness.utils.GsonUtil');
const LocJsonEntity = factory.use('com.zjwh.android_wh_physicalfitness.entity.LocJsonEntity');
const PointJsonEntity = factory.use('com.zjwh.android_wh_physicalfitness.entity.PointJsonEntity');
const Integer = factory.use('java.lang.Integer');

const n = Math.max(2, OUTDOOR_FAKE.trackPoints | 0);
const lat0 = OUTDOOR_FAKE.baseLat;
const lng0 = OUTDOOR_FAKE.baseLng;
// Approx longitude delta for target distance at this latitude.
const metersPerLngDeg = 111320.0 * Math.cos(lat0 * Math.PI / 180.0);
const lngDelta = totals.meters / metersPerLngDeg;
const list = ArrayList.$new();

for (let i = 0; i < n; i++) {
const ratio = i / (n - 1);
const loc = MyLocation.$new();
const lat = lat0 + 0.00003 * Math.sin(ratio * Math.PI * 2);
const lng = lng0 + lngDelta * ratio;
const sec = Math.round(totals.seconds * ratio);
const dis = totals.meters * ratio;
const ts = startMs + sec * 1000;
outdoorCallNoThrow(loc, 'setId', ['int'], [i + 1]);
outdoorCallNoThrow(loc, 'setCount', ['int'], [i + 1]);
outdoorCallNoThrow(loc, 'setLat', ['double'], [lat]);
outdoorCallNoThrow(loc, 'setLng', ['double'], [lng]);
outdoorCallNoThrow(loc, 'setgLat', ['double'], [lat]);
outdoorCallNoThrow(loc, 'setgLng', ['double'], [lng]);
outdoorCallNoThrow(loc, 'setCoorType', ['java.lang.String'], [OUTDOOR_FAKE.coorType]);
outdoorCallNoThrow(loc, 'setGainTime', ['java.lang.String'], [outdoorFmtDateTimeMs(ts)]);
outdoorCallNoThrow(loc, 'setTotalTime', ['long'], [sec]);
outdoorCallNoThrow(loc, 'setValidTime', ['long'], [sec]);
outdoorCallNoThrow(loc, 'setTotalDis', ['double'], [dis]);
outdoorCallNoThrow(loc, 'setValidDis', ['double'], [dis]);
outdoorCallNoThrow(loc, 'setSpeed', ['double'], [OUTDOOR_FAKE.speedMps]);
outdoorCallNoThrow(loc, 'setAvgSpeed', ['double'], [OUTDOOR_FAKE.speedMps]);
outdoorCallNoThrow(loc, 'setStepDistance', ['double'], [i === 0 ? 0 : totals.meters / (n - 1)]);
outdoorCallNoThrow(loc, 'setBdG', ['int'], [OUTDOOR_FAKE.gpsLevel]);
outdoorCallNoThrow(loc, 'setLocType', ['int'], [61]);
outdoorCallNoThrow(loc, 'setRadius', ['float'], [8.0]);
outdoorCallNoThrow(loc, 'setState', ['int'], [1]);
outdoorCallNoThrow(loc, 'setType', ['int'], [0]);
outdoorCallNoThrow(loc, 'setFlag', ['long'], [ts]);
list.add(loc);
}

const gson = GsonUtil.getInstance();
const locListJson = outdoorS(gson.toJson(list));
const locEntity = LocJsonEntity.$new(false, locListJson);
const locEntityJson = outdoorS(gson.toJson(locEntity));
const fivePointListJson = outdoorBuildFakeFivePointJson(lat0, lng0, lngDelta, startMs, totals);
const pointEntity = PointJsonEntity.$new(false, fivePointListJson, Integer.valueOf(-1), '', false);
const pointEntityJson = outdoorS(gson.toJson(pointEntity));
const series = outdoorBuildDetailSeriesJsons(startMs, totals);
const ret = {
locList: list,
locListJson: locListJson,
locEntityJson: locEntityJson,
pointEntityJson: pointEntityJson,
segmentJson: series.segmentJson,
lapsJson: series.lapsJson,
stepJson: series.stepJson,
speedJson: series.speedJson,
altitudeJson: series.altitudeJson,
startMs: startMs,
stopMs: startMs + totals.seconds * 1000,
lat: lat0,
lng: lng0,
totals: totals
};
outdoorLastArtifacts = ret;
log('[OUTDOOR-TRACK] built fake track why=' + why + ' points=' + n +
' dis=' + totals.meters + ' time=' + totals.seconds +
' locJsonLen=' + locEntityJson.length);
return ret;
} catch (e) {
log('[OUTDOOR-TRACK] build err why=' + why + ' err=' + e.message);
return outdoorBuildManualTrackArtifacts(startMs, why, e.message);
}
}

function outdoorArtifactsForEntity(factory, entity, why) {
let st = outdoorReadEntityNumber(entity, 'getStartTime', 'startTime');
return outdoorBuildFakeTrackArtifacts(factory || Java.classFactory, st, why);
}

function outdoorReadEntityNumber(obj, getter, field) {
let v = 0;
try {
if (obj && getter && obj[getter]) v = Number(obj[getter]());
} catch (e0) {}
if (!v || isNaN(v)) {
try {
const fv = outdoorReadField(obj, field);
v = Number(fv && fv.value !== undefined ? fv.value : fv);
} catch (e1) {}
}
return (!v || isNaN(v)) ? 0 : v;
}

function outdoorNormalizeUploadWindow(entity, totals, why) {
const seconds = Math.max(1, Number(totals.seconds || OUTDOOR_FAKE.minUploadTimeSec));
let stop = outdoorReadEntityNumber(entity, 'getStopTime', 'stopTime');
let start = outdoorReadEntityNumber(entity, 'getStartTime', 'startTime');
const oldStart = start;
const oldStop = stop;
// Keep stopTime close to the real end/upload time; backdate startTime to match totalTime.
// v60 left start/stop only ~67s apart while totalTime=600, which is a likely server-side reject.
if (!stop || stop < 1000000000000) stop = Date.now();
start = stop - seconds * 1000;
outdoorCallNoThrow(entity, 'setStartTime', ['long'], [start]);
outdoorCallNoThrow(entity, 'setStopTime', ['long'], [stop]);
outdoorSetField(entity, 'startTime', 'long', start);
outdoorSetField(entity, 'stopTime', 'long', stop);
log('[OUTDOOR-SUBMIT] normalize time why=' + why +
' start=' + start + ' stop=' + stop + ' span=' + Math.round((stop - start) / 1000) +
' oldStart=' + outdoorS(oldStart) + ' oldStop=' + outdoorS(oldStop));
return { startMs: start, stopMs: stop, seconds: seconds };
}

function outdoorFmtDateTimeMs(ms) {
// Avoid java.text.SimpleDateFormat here: Frida may expose only the inherited
// Format.format(Date, StringBuffer, FieldPosition) overloads, which caused
// the v59 track builder to fail before any JSON was generated.
const d = new Date(Number(ms || Date.now()));
const y = d.getFullYear();
const mo = outdoorPad2(d.getMonth() + 1);
const da = outdoorPad2(d.getDate());
const h = outdoorPad2(d.getHours());
const mi = outdoorPad2(d.getMinutes());
const se = outdoorPad2(d.getSeconds());
return y + '-' + mo + '-' + da + ' ' + h + ':' + mi + ':' + se;
}

function outdoorOverwriteRunDataFile(runData, content, why) {
try {
if (!runData || !runData.getFile) return false;
const path = outdoorS(runData.getFile());
if (path.length === 0 || path === 'null') return false;
const FileOutputStream = Java.use('java.io.FileOutputStream');
const JString = Java.use('java.lang.String');
const fos = FileOutputStream.$new(path, false);
try {
fos.write(JString.$new(content).getBytes('UTF-8'));
} finally {
fos.close();
}
log('[OUTDOOR-TRACK] overwrite runData file why=' + why + ' path=' + path + ' bytes=' + content.length);
return true;
} catch (e) {
log('[OUTDOOR-TRACK] overwrite file err why=' + why + ' err=' + e.message);
return false;
}
}

function outdoorPatchRunDataEntity(runData, artifacts, why) {
if (!runData || !artifacts) return;
try {
const fakeUuid = outdoorEntityString(runData, 'getUuid', '');
if (fakeUuid && fakeUuid !== 'null') outdoorFakeRunUuids[fakeUuid] = true;
} catch (eMark) {}
if (!CLEAN_LOG_MODE) { try { log('[OUTDOOR-TRACK] patch RunDataEntity why=' + why + ' before=' + outdoorS(runData)); } catch (e0) {} }
outdoorCallNoThrow(runData, 'setRun_data', ['java.lang.String'], [artifacts.locEntityJson]);
outdoorCallNoThrow(runData, 'setStep_freq_json', ['java.lang.String'], [artifacts.stepJson]);
outdoorCallNoThrow(runData, 'setSpeed_json', ['java.lang.String'], [artifacts.speedJson]);
outdoorCallNoThrow(runData, 'setFixed_point_json', ['java.lang.String'], [artifacts.pointEntityJson]);
outdoorCallNoThrow(runData, 'setSegment_json', ['java.lang.String'], [artifacts.segmentJson]);
outdoorCallNoThrow(runData, 'setLaps_json', ['java.lang.String'], [artifacts.lapsJson]);
outdoorCallNoThrow(runData, 'setTimestamp', ['long'], [artifacts.startMs]);
outdoorSetField(runData, 'run_data', 'object', artifacts.locEntityJson);
outdoorSetField(runData, 'step_freq_json', 'object', artifacts.stepJson);
outdoorSetField(runData, 'speed_json', 'object', artifacts.speedJson);
outdoorSetField(runData, 'fixed_point_json', 'object', artifacts.pointEntityJson);
outdoorSetField(runData, 'segment_json', 'object', artifacts.segmentJson);
outdoorSetField(runData, 'laps_json', 'object', artifacts.lapsJson);
outdoorSetField(runData, 'timestamp', 'long', artifacts.startMs);
outdoorOverwriteRunDataFile(runData, artifacts.locEntityJson, why);
if (!CLEAN_LOG_MODE) { try { log('[OUTDOOR-TRACK] patched RunDataEntity after=' + outdoorS(runData)); } catch (e1) {} }
}

function outdoorSetFieldDirect(obj, name, value) {
try {
if (obj && obj[name] !== undefined && obj[name].value !== undefined) {
obj[name].value = value;
return true;
}
} catch (e) {}
return false;
}

function outdoorSetFieldReflect(obj, name, kind, value) {
try {
let cls = obj.getClass();
let lastErr = null;
while (cls) {
try {
const f = cls.getDeclaredField(name);
f.setAccessible(true);
if (kind === 'double') f.setDouble(obj, value);
else if (kind === 'long') f.setLong(obj, value);
else if (kind === 'int') f.setInt(obj, value);
else if (kind === 'boolean') f.setBoolean(obj, value);
else f.set(obj, value);
return true;
} catch (eInner) {
lastErr = eInner;
try { cls = cls.getSuperclass(); } catch (eSuper) { cls = null; }
}
}
log('[OUTDOOR-SUBMIT] set field miss ' + name + ' err=' + (lastErr ? lastErr.message : 'no class'));
return false;
} catch (e) {
log('[OUTDOOR-SUBMIT] set field miss ' + name + ' err=' + e.message);
return false;
}
}

function outdoorSetField(obj, name, kind, value) {
if (outdoorSetFieldDirect(obj, name, value)) return true;
return outdoorSetFieldReflect(obj, name, kind, value);
}

function outdoorReadField(obj, name) {
try {
if (obj && obj[name] !== undefined && obj[name].value !== undefined) return obj[name].value;
} catch (e0) {}
try {
const f = obj.getClass().getDeclaredField(name);
f.setAccessible(true);
return f.get(obj);
} catch (e1) {}
return '<na>';
}

function outdoorForceVmTotals(vm, why) {
if (!OUTDOOR_FAKE.enabled) return;
const totals = outdoorFakeTotalsForSubmit(Date.now());
const beforeDis = outdoorReadField(vm, 'mTotalDis');
const beforeTime = outdoorReadField(vm, 'mTotalTime');
outdoorSetField(vm, 'mTotalDis', 'double', totals.meters);
outdoorSetField(vm, 'mTotalTime', 'long', totals.seconds);
outdoorSetField(vm, 'totalConsumptionKcal', 'double', totals.kcal);
log('[OUTDOOR-SUBMIT] force VM totals why=' + why +
' dis ' + beforeDis + '->' + totals.meters +
' time ' + beforeTime + '->' + totals.seconds +
' kcal=' + totals.kcal +
' steps=' + totals.steps);
}

function outdoorCallNoThrow(obj, methodName, sig, args) {
try {
if (obj && obj[methodName]) {
const m = sig ? obj[methodName].overload.apply(obj[methodName], sig) : obj[methodName];
return m.apply(obj, args || []);
}
} catch (e) {
log('[OUTDOOR-SUBMIT] call ' + methodName + ' err=' + e.message);
}
return null;
}

function outdoorPatchUploadEntity(entity, why) {
if (!entity || !OUTDOOR_FAKE.enabled) return;
const totals = outdoorFakeTotalsForSubmit(Date.now());
if (!CLEAN_LOG_MODE) { try { log('[OUTDOOR-SUBMIT] patch UploadFormatEntity why=' + why + ' before=' + outdoorS(entity)); } catch (e0) {} }
const win = outdoorNormalizeUploadWindow(entity, totals, why);
const artifacts = outdoorBuildFakeTrackArtifacts(Java.classFactory, win.startMs, why);
try {
let upUuid = outdoorEntityString(entity, 'getUuid', '');
if (!upUuid || upUuid === 'null') upUuid = outdoorExtractUuidFromText(entity);
if (upUuid && upUuid !== 'null') {
outdoorRememberCurrentUuid(upUuid, why + '.entity');
outdoorDetailResetRenderState(null, 'uploadPrepared:' + upUuid, true);
}
} catch (eUuidPrep) { log('[OUTDOOR-NET] upload uuid prep err why=' + why + ' err=' + eUuidPrep.message); }
outdoorCallNoThrow(entity, 'setTotalDis', ['int'], [totals.meters]);
outdoorCallNoThrow(entity, 'setValidDis', ['int'], [totals.meters]);
outdoorCallNoThrow(entity, 'setTotalTime', ['long'], [totals.seconds]);
outdoorCallNoThrow(entity, 'setValidTime', ['long'], [totals.seconds]);
outdoorCallNoThrow(entity, 'setComplete', ['boolean'], [true]);
outdoorCallNoThrow(entity, 'setUnCompleteReason', ['int'], [0]);
outdoorCallNoThrow(entity, 'setAvgStepFreq', ['int'], [OUTDOOR_FAKE.stepFreq]);
outdoorCallNoThrow(entity, 'setTotalSteps', ['int'], [totals.steps]);
try { outdoorCallNoThrow(entity, 'setSpeed', ['double'], [OUTDOOR_FAKE.speedMps]); } catch (e1) {}
// Method calls are preferred, but this object is exactly the upload DTO,
// so direct field fallback is still scoped and avoids silent overload quirks.
outdoorSetField(entity, 'totalDis', 'int', totals.meters);
outdoorSetField(entity, 'validDis', 'int', totals.meters);
outdoorSetField(entity, 'totalTime', 'long', totals.seconds);
outdoorSetField(entity, 'validTime', 'long', totals.seconds);
outdoorSetField(entity, 'complete', 'boolean', true);
outdoorSetField(entity, 'unCompleteReason', 'int', 0);
outdoorSetField(entity, 'avgStepFreq', 'int', OUTDOOR_FAKE.stepFreq);
outdoorSetField(entity, 'totalSteps', 'int', totals.steps);
outdoorSetField(entity, 'calorie', 'int', totals.kcal);
outdoorSetField(entity, 'speed', 'long', Math.round(OUTDOOR_FAKE.speedMps * 1000));
if (artifacts) {
// These are the fields the post-upload detail page parses. Previously they were empty/null,
// so RunHistoryDetailActivity could enter a blank rendering state.
outdoorCallNoThrow(entity, 'setAllLocJson', ['java.lang.String'], [artifacts.locEntityJson]);
outdoorCallNoThrow(entity, 'setFivePointJson', ['java.lang.String'], [artifacts.pointEntityJson]);
outdoorCallNoThrow(entity, 'setSegmentJson', ['java.lang.String'], [artifacts.segmentJson]);
outdoorCallNoThrow(entity, 'setLatitude', ['double'], [artifacts.lat]);
outdoorCallNoThrow(entity, 'setLongitude', ['double'], [artifacts.lng]);
outdoorCallNoThrow(entity, 'setCalorie', ['int'], [totals.kcal]);
outdoorSetField(entity, 'allLocJson', 'object', artifacts.locEntityJson);
outdoorSetField(entity, 'fivePointJson', 'object', artifacts.pointEntityJson);
outdoorSetField(entity, 'segmentJson', 'object', artifacts.segmentJson);
outdoorSetField(entity, 'latitude', 'double', artifacts.lat);
outdoorSetField(entity, 'longitude', 'double', artifacts.lng);
}
if (!CLEAN_LOG_MODE) { try { log('[OUTDOOR-SUBMIT] patched UploadFormatEntity after=' + outdoorS(entity)); } catch (e3) {} }
return artifacts;
}

function outdoorPad2(n) {
n = Math.max(0, Math.floor(n));
return n < 10 ? '0' + n : String(n);
}

function outdoorFmtTime(sec) {
sec = Math.max(0, Math.floor(sec));
const h = Math.floor(sec / 3600);
const m = Math.floor((sec % 3600) / 60);
const s = sec % 60;
if (h > 0) return String(h) + ':' + outdoorPad2(m) + ':' + outdoorPad2(s);
return outdoorPad2(m) + ':' + outdoorPad2(s);
}

function outdoorFmtPace(speedMps) {
if (!speedMps || speedMps <= 0) return "0'00\"";
const paceSec = Math.round(1000 / speedMps);
const m = Math.floor(paceSec / 60);
const s = paceSec % 60;
return String(m) + "'" + outdoorPad2(s) + '"';
}

function outdoorFakeStateFromNow(now) {
if (outdoorFakeStartMs === 0) outdoorFakeStartMs = now;
const elapsedRealSec = Math.max(0, (now - outdoorFakeStartMs) / 1000.0);
const elapsedSec = elapsedRealSec * OUTDOOR_FAKE.timeScale;
const km = Math.max(OUTDOOR_FAKE.minDistanceKm, (elapsedSec * OUTDOOR_FAKE.speedMps) / 1000.0);
return {
d: km.toFixed(2),
t: outdoorFmtTime(elapsedSec),
p: outdoorFmtPace(OUTDOOR_FAKE.speedMps),
s: OUTDOOR_FAKE.stepFreq,
g: OUTDOOR_FAKE.gpsLevel,
k: Math.round(km * OUTDOOR_FAKE.kcalPerKm),
elapsedSec: elapsedSec
};
}

function outdoorReadStateFromArgs(args, o) {
return {
d: outdoorS(args[o + 0]),
t: outdoorS(args[o + 1]),
p: outdoorS(args[o + 2]),
s: outdoorN(args[o + 3]),
g: outdoorN(args[o + 6]),
run: outdoorB(args[o + 8]),
pause: outdoorB(args[o + 9]),
end: outdoorB(args[o + 10]),
k: outdoorN(args[o + 18])
};
}

function outdoorApplyFakeArgs(args, o, original, now) {
if (!OUTDOOR_FAKE.enabled) return original;
if (OUTDOOR_FAKE.onlyWhenAppRunning && !original.run) return original;
if (original.pause) return original;

const fake = outdoorFakeStateFromNow(now);
args[o + 0] = fake.d;
args[o + 1] = fake.t;
args[o + 2] = fake.p;
args[o + 3] = fake.s;
args[o + 6] = fake.g;
args[o + 18] = fake.k;
if (OUTDOOR_FAKE.forceEndFalse) args[o + 10] = false;

return {
d: fake.d,
t: fake.t,
p: fake.p,
s: fake.s,
g: fake.g,
run: original.run,
pause: original.pause,
end: OUTDOOR_FAKE.forceEndFalse ? false : original.end,
k: fake.k
};
}

function outdoorS(v) {
try {
if (v === null || v === undefined) return '';
return String(v);
} catch (e) {
return '<toString-error>';
}
}

function outdoorN(v) {
const n = Number(outdoorS(v));
return isNaN(n) ? 0 : n;
}

function outdoorB(v) {
if (v === true) return true;
if (v === false || v === null || v === undefined) return false;
const s = outdoorS(v).toLowerCase();
return s === 'true' || s === '1';
}

function outdoorShortArgs(args) {
const out = [];
const max = Math.min(args.length, 6);
for (let i = 0; i < max; i++) out.push(outdoorS(args[i]).slice(0, 80));
if (args.length > max) out.push('...+' + (args.length - max));
return out.join(' | ');
}

function outdoorPrintState(tag, st) {
log('[OUTDOOR] ' + tag +
' distance=' + st.d +
' time=' + st.t +
' pace=' + st.p +
' stepFreq=' + st.s +
' gps=' + st.g +
' kcal=' + st.k +
' running=' + st.run +
' pause=' + st.pause +
' end=' + st.end);
}

function hookOutdoorRunUiState(factory) {
const C = factory.use(OUTDOOR_CFG.target);
if (!C.copy || !C.copy.overloads || C.copy.overloads.length === 0) {
throw new Error('RunUiState.copy overloads missing');
}

C.copy.overloads.forEach(function (ol, idx) {
ol.implementation = function () {
const args = [];
for (let i = 0; i < arguments.length; i++) args.push(arguments[i]);

let st = null;
try {
// Kotlin data-class copy may have receiver/default-mask variants in some call paths.
const o = (args.length > 20) ? 1 : 0;
const original = outdoorReadStateFromArgs(args, o);
const now = Date.now();
st = outdoorApplyFakeArgs(args, o, original, now);

if (original.run && !outdoorStarted) {
outdoorStarted = true;
if (outdoorFakeStartMs === 0) outdoorFakeStartMs = now;
outdoorPrintState('started original', original);
outdoorPrintState('started fake', st);
}

if (st.end && outdoorStarted) {
outdoorPrintState('finished fake', st);
outdoorStarted = false;
outdoorFakeStartMs = 0;
outdoorLast = { d: '', t: '', p: '', s: 0, k: 0, g: -1 };
} else if (st.run && !st.pause && now - outdoorLastPrintTime >= OUTDOOR_CFG.printIntervalMs) {
if (st.d !== outdoorLast.d || st.t !== outdoorLast.t || st.p !== outdoorLast.p ||
st.s !== outdoorLast.s || st.k !== outdoorLast.k || st.g !== outdoorLast.g) {
outdoorPrintState('fake-state', st);
outdoorLastPrintTime = now;
outdoorLast = { d: st.d, t: st.t, p: st.p, s: st.s, k: st.k, g: st.g };
}
}
} catch (e) {
log('[OUTDOOR-FAKE] copy#' + idx + ' prepare/log err=' + e.message);
}

return ol.apply(this, args);
};
});
log('[OUTDOOR-FAKE] RunUiState.copy hooked overloads=' + C.copy.overloads.length +
' enabled=' + OUTDOOR_FAKE.enabled +
' speedMps=' + OUTDOOR_FAKE.speedMps +
' timeScale=' + OUTDOOR_FAKE.timeScale);
}



function outdoorEntityString(entity, getter, defValue) {
try {
if (entity && entity[getter]) {
const v = entity[getter]();
if (v !== null && v !== undefined && outdoorS(v) !== 'null') return outdoorS(v);
}
} catch (e) {}
return defValue === undefined ? '' : defValue;
}

function outdoorIsFakeRunDataEntity(entity) {
try {
const uuid = outdoorEntityString(entity, 'getUuid', '');
return !!(uuid && outdoorFakeRunUuids[uuid]);
} catch (e) {
return false;
}
}

function outdoorJavaUtf8Bytes(str) {
const JString = Java.use('java.lang.String');
return JString.$new(outdoorS(str)).getBytes('UTF-8');
}

function outdoorByteArrayLen(arr) {
try {
if (arr === null || arr === undefined) return -1;
return Number(arr.length);
} catch (e) {
return -2;
}
}

function outdoorGzipCompressField(gzipInst, value) {
try {
return outdoorS(gzipInst.compress(outdoorJavaUtf8Bytes(value === null || value === undefined ? '' : value)));
} catch (e) {
log('[OUTDOOR-GZIP] compress fallback field err=' + e.message);
return '';
}
}

function outdoorBuildRunDataBytesFallback(gzipInst, entity, mode) {
const uid = outdoorEntityString(entity, 'getUid', '');
const uuid = outdoorEntityString(entity, 'getUuid', '');
const step = outdoorEntityString(entity, 'getStep_freq_json', '[]');
let obj;
if (mode === 2) {
obj = {
uid: outdoorGzipCompressField(gzipInst, uid),
uuid: outdoorGzipCompressField(gzipInst, uuid),
step_json: outdoorGzipCompressField(gzipInst, step)
};
} else {
const rrid = outdoorEntityString(entity, 'getRrid', '0');
const runData = outdoorEntityString(entity, 'getRun_data', outdoorLastArtifacts ? outdoorLastArtifacts.locEntityJson : '{}');
const speed = outdoorEntityString(entity, 'getSpeed_json', '[]');
const segment = outdoorEntityString(entity, 'getSegment_json', '');
const fixed = outdoorEntityString(entity, 'getFixed_point_json', outdoorLastArtifacts ? outdoorLastArtifacts.pointEntityJson : '{}');
const face = outdoorEntityString(entity, 'getRunFaceCheck', '');
const laps = outdoorEntityString(entity, 'getLaps_json', '');
obj = {
rrid: outdoorGzipCompressField(gzipInst, rrid),
uid: outdoorGzipCompressField(gzipInst, uid),
uuid: outdoorGzipCompressField(gzipInst, uuid),
run_data: outdoorGzipCompressField(gzipInst, runData),
step_freq_json: outdoorGzipCompressField(gzipInst, step),
speed_json: outdoorGzipCompressField(gzipInst, speed),
segment_json: outdoorGzipCompressField(gzipInst, segment),
fixed_point_json: outdoorGzipCompressField(gzipInst, fixed),
runFaceCheck: outdoorGzipCompressField(gzipInst, face),
laps_json: outdoorGzipCompressField(gzipInst, laps)
};
}
const json = JSON.stringify(obj);
const bytes = outdoorJavaUtf8Bytes(json);
log('[OUTDOOR-GZIP] fallback mode=' + mode + ' uuid=' + uuid + ' jsonLen=' + json.length + ' bytes=' + outdoorByteArrayLen(bytes));
return bytes;
}

function outdoorInstallGZipRunDataFix(factory) {
try {
const GZ = factory.use('com.zjwh.android_wh_physicalfitness.utils.GZipHelper');
if (GZ.runDataToByte && GZ.runDataToByte.overloads) {
GZ.runDataToByte.overloads.forEach(function (ol, idx) {
ol.implementation = function (entity) {
const fake = outdoorIsFakeRunDataEntity(entity);
try {
const r = ol.call(this, entity);
const len = outdoorByteArrayLen(r);
if (fake) log('[OUTDOOR-GZIP] runDataToByte#' + idx + ' uuid=' + outdoorEntityString(entity, 'getUuid', '') + ' retLen=' + len);
if (fake && (r === null || r === undefined || len <= 0)) return outdoorBuildRunDataBytesFallback(this, entity, 1);
return r;
} catch (e) {
if (fake) {
log('[OUTDOOR-GZIP] runDataToByte#' + idx + ' original err=' + e.message + ' -> fallback');
return outdoorBuildRunDataBytesFallback(this, entity, 1);
}
throw e;
}
};
});
log('[OUTDOOR-GZIP] GZipHelper.runDataToByte hooked overloads=' + GZ.runDataToByte.overloads.length);
}
if (GZ.runDataToByte2 && GZ.runDataToByte2.overloads) {
GZ.runDataToByte2.overloads.forEach(function (ol, idx) {
ol.implementation = function (entity) {
const fake = outdoorIsFakeRunDataEntity(entity);
try {
const r = ol.call(this, entity);
const len = outdoorByteArrayLen(r);
if (fake) log('[OUTDOOR-GZIP] runDataToByte2#' + idx + ' uuid=' + outdoorEntityString(entity, 'getUuid', '') + ' retLen=' + len);
if (fake && (r === null || r === undefined || len <= 0)) return outdoorBuildRunDataBytesFallback(this, entity, 2);
return r;
} catch (e) {
if (fake) {
log('[OUTDOOR-GZIP] runDataToByte2#' + idx + ' original err=' + e.message + ' -> fallback');
return outdoorBuildRunDataBytesFallback(this, entity, 2);
}
throw e;
}
};
});
log('[OUTDOOR-GZIP] GZipHelper.runDataToByte2 hooked overloads=' + GZ.runDataToByte2.overloads.length);
}
} catch (e) {
log('[OUTDOOR-GZIP] GZipHelper hook pending/miss=' + e.message);
}
}

function outdoorInstallUploadObsDiag(factory) {
outdoorInstallGZipRunDataFix(factory);
try {
const Cb = factory.use('com.zjwh.android_wh_physicalfitness.mvi.sport.helper.RunUploadHelper$uploadToServer$1');
if (Cb.onSuccess && Cb.onSuccess.overloads) {
Cb.onSuccess.overloads.forEach(function (ol, idx) {
ol.implementation = function () {
try {
const okBean = arguments.length > 0 ? arguments[0] : null;
try {
let u = outdoorEntityString(okBean, 'getUuid', '');
if (!u || u === 'null') u = outdoorExtractUuidFromText(okBean);
if (u && u !== 'null') outdoorRememberCurrentUuid(u, 'uploadSuccess#' + idx);
const rr = outdoorReadEntityNumber(okBean, 'getRrid', 'rrid');
if (rr) outdoorLastSuccessRrid = rr;
try { outdoorDetailResetRenderState(null, 'uploadSuccess#' + idx + ':' + (u || outdoorCurrentUploadUuid || outdoorLastSuccessUuid), true); } catch (eRstNet) {}
} catch (eRec) {}
} catch (e1) {}
return ol.apply(this, arguments);
};
});
log('[OUTDOOR-NET] uploadToServer success hook installed');
}
} catch (eCb) {
log('[OUTDOOR-NET] RunUploadHelper.uploadToServer callback hook pending/miss=' + eCb.message);
}
}

function hookOutdoorOptional(factory) {
let O = null;
try {
O = factory.use(OUTDOOR_CFG.vm);
if (O.startRun && O.startRun.overloads) {
O.startRun.overloads.forEach(function (ol, idx) {
ol.implementation = function () {
outdoorStartRunSeen = true;
outdoorFakeStartMs = 0;
outdoorFakeLastLogMs = 0;
log('[OUTDOOR-FAKE] OutdoorRunViewModel.startRun#' + idx + ' args=' + outdoorShortArgs(arguments));
return ol.apply(this, arguments);
};
});
log('[OUTDOOR] OutdoorRunViewModel.startRun hooked overloads=' + O.startRun.overloads.length);
}
} catch (e0) {
log('[OUTDOOR] startRun pending/miss=' + e0.message);
}

if (O !== null) try {
if (O.requestFinish && O.requestFinish.overloads) {
O.requestFinish.overloads.forEach(function (ol, idx) {
ol.implementation = function () {
outdoorForceVmTotals(this, 'requestFinish#' + idx);
return ol.apply(this, arguments);
};
});
log('[OUTDOOR-SUBMIT] OutdoorRunViewModel.requestFinish hooked overloads=' + O.requestFinish.overloads.length);
}
} catch (eReq) {
log('[OUTDOOR-SUBMIT] requestFinish hook miss=' + eReq.message);
}

if (O !== null) try {
if (O.finishRun && O.finishRun.overloads) {
O.finishRun.overloads.forEach(function (ol, idx) {
ol.implementation = function () {
outdoorForceVmTotals(this, 'finishRun#' + idx);
return ol.apply(this, arguments);
};
});
log('[OUTDOOR-SUBMIT] OutdoorRunViewModel.finishRun hooked overloads=' + O.finishRun.overloads.length);
}
} catch (eFin) {
log('[OUTDOOR-SUBMIT] finishRun hook miss=' + eFin.message);
}

if (O !== null) try {
if (O.isSportComplete && O.isSportComplete.overloads) {
O.isSportComplete.overloads.forEach(function (ol, idx) {
ol.implementation = function () {
outdoorForceVmTotals(this, 'isSportComplete#' + idx);
const r = ol.apply(this, arguments);
log('[OUTDOOR-SUBMIT] isSportComplete#' + idx + ' ret=' + r);
return r;
};
});
log('[OUTDOOR-SUBMIT] OutdoorRunViewModel.isSportComplete hooked overloads=' + O.isSportComplete.overloads.length);
}
} catch (eComp) {
log('[OUTDOOR-SUBMIT] isSportComplete hook miss=' + eComp.message);
}

if (O !== null) try {
if (O.uploadRecord && O.uploadRecord.overloads) {
O.uploadRecord.overloads.forEach(function (ol, idx) {
ol.implementation = function (entity) {
outdoorForceVmTotals(this, 'uploadRecord#' + idx);
outdoorPatchUploadEntity(entity, 'OutdoorRunViewModel.uploadRecord#' + idx);
return ol.apply(this, arguments);
};
});
log('[OUTDOOR-SUBMIT] OutdoorRunViewModel.uploadRecord hooked overloads=' + O.uploadRecord.overloads.length);
}
} catch (eUp) {
log('[OUTDOOR-SUBMIT] uploadRecord hook miss=' + eUp.message);
}

try {
const S = factory.use(OUTDOOR_CFG.record);
if (S.init && S.init.overloads) {
S.init.overloads.forEach(function (ol, idx) {
ol.implementation = function () {
const r = ol.apply(this, arguments);
log('[OUTDOOR] SportRecordManager.init#' + idx + ' ret=' + outdoorS(r));
return r;
};
});
log('[OUTDOOR] SportRecordManager.init hooked overloads=' + S.init.overloads.length);
}
} catch (e1) {
log('[OUTDOOR] SportRecordManager.init pending/miss=' + e1.message);
}

try {
const H = factory.use('com.zjwh.android_wh_physicalfitness.mvi.sport.helper.RunUploadHelper');
if (H.buildUploadData && H.buildUploadData.overloads) {
H.buildUploadData.overloads.forEach(function (ol, idx) {
ol.implementation = function () {
const pair = ol.apply(this, arguments);
try {
if (pair) {
const entity = pair.getFirst ? pair.getFirst() : (pair.component1 ? pair.component1() : null);
const runData = pair.getSecond ? pair.getSecond() : (pair.component2 ? pair.component2() : null);
const artifacts = outdoorPatchUploadEntity(entity, 'RunUploadHelper.buildUploadData#' + idx) ||
outdoorArtifactsForEntity(factory, entity, 'RunUploadHelper.buildUploadData#' + idx);
outdoorPatchRunDataEntity(runData, artifacts, 'RunUploadHelper.buildUploadData#' + idx);
} else {
log('[OUTDOOR-TRACK] buildUploadData#' + idx + ' returned null');
}
} catch (eBuild) {
log('[OUTDOOR-TRACK] buildUploadData#' + idx + ' patch err=' + eBuild.message);
}
return pair;
};
});
log('[OUTDOOR-TRACK] RunUploadHelper.buildUploadData hooked overloads=' + H.buildUploadData.overloads.length);
}
if (H.uploadObs && H.uploadObs.overloads) {
H.uploadObs.overloads.forEach(function (ol, idx) {
ol.implementation = function () {
try {
const runData = arguments.length > 1 ? arguments[1] : null;
const artifacts = outdoorLastArtifacts ||
outdoorBuildFakeTrackArtifacts(factory, outdoorReadEntityNumber(runData, 'getTimestamp', 'timestamp'), 'RunUploadHelper.uploadObs#' + idx);
outdoorPatchRunDataEntity(runData, artifacts, 'RunUploadHelper.uploadObs#' + idx);
} catch (eObs) {
log('[OUTDOOR-TRACK] uploadObs#' + idx + ' patch err=' + eObs.message);
}
return ol.apply(this, arguments);
};
});
log('[OUTDOOR-TRACK] RunUploadHelper.uploadObs hooked overloads=' + H.uploadObs.overloads.length);
}
if (H.uploadToServer && H.uploadToServer.overloads) {
H.uploadToServer.overloads.forEach(function (ol, idx) {
ol.implementation = function () {
if (arguments.length > 0) outdoorPatchUploadEntity(arguments[0], 'RunUploadHelper.uploadToServer#' + idx);
return ol.apply(this, arguments);
};
});
log('[OUTDOOR-SUBMIT] RunUploadHelper.uploadToServer hooked overloads=' + H.uploadToServer.overloads.length);
}
} catch (eH) {
log('[OUTDOOR-SUBMIT] RunUploadHelper hook pending/miss=' + eH.message);
}

try {
const HU = factory.use('com.zjwh.android_wh_physicalfitness.utils.HttpUtil');
if (HU.signRunRecord && HU.signRunRecord.overloads) {
HU.signRunRecord.overloads.forEach(function (ol, idx) {
ol.implementation = function () {
try {
if (arguments.length > 0) {
const ent = arguments[0];
const span = outdoorReadEntityNumber(ent, 'getStopTime', 'stopTime') -
outdoorReadEntityNumber(ent, 'getStartTime', 'startTime');
log('[OUTDOOR-NET] signRunRecord#' + idx +
' spanSec=' + Math.round(span / 1000) +
' dis=' + outdoorReadEntityNumber(ent, 'getTotalDis', 'totalDis') +
' time=' + outdoorReadEntityNumber(ent, 'getTotalTime', 'totalTime') +
' speed=' + outdoorReadEntityNumber(ent, 'getSpeed', 'speed') +
' lat=' + outdoorReadEntityNumber(ent, 'getLatitude', 'latitude') +
' lng=' + outdoorReadEntityNumber(ent, 'getLongitude', 'longitude'));
}
} catch (eSig0) {
log('[OUTDOOR-NET] signRunRecord pre err=' + eSig0.message);
}
const r = ol.apply(this, arguments);
try { log('[OUTDOOR-NET] signRunRecord#' + idx + ' jsonLen=' + outdoorS(r).length); } catch (eSig1) {}
return r;
};
});
log('[OUTDOOR-NET] HttpUtil.signRunRecord hooked overloads=' + HU.signRunRecord.overloads.length);
}
} catch (eNet) {
log('[OUTDOOR-NET] HttpUtil.signRunRecord hook pending/miss=' + eNet.message);
}

outdoorInstallUploadObsDiag(factory);

try {
const D = factory.use('com.zjwh.android_wh_physicalfitness.entity.sport.RunHistoryDetailBean');
const patchStringGetter = function (name, replacementFn) {
if (!D[name] || !D[name].overloads) return;
D[name].overloads.forEach(function (ol, idx) {
ol.implementation = function () {
const r = ol.apply(this, arguments);
if (!outdoorIsEmptyJsonLike(r)) return r;
try {
const artifacts = outdoorBuildFakeTrackArtifacts(factory, 0, 'RunHistoryDetailBean.' + name + '#' + idx);
const nr = replacementFn(artifacts);
try {
if (name === 'getAllLocJson') outdoorCallNoThrow(this, 'setAllLocJson', ['java.lang.String'], [nr]);
else if (name === 'getFivePointJson') outdoorCallNoThrow(this, 'setFivePointJson', ['java.lang.String'], [nr]);
else if (name === 'getSegmentJson') outdoorCallNoThrow(this, 'setSegmentJson', ['java.lang.String'], [nr]);
outdoorCallNoThrow(this, 'setJsonFromObs', ['int'], [0]);
} catch (eSetInline) {}
log('[OUTDOOR-DETAIL] ' + name + '#' + idx + ' empty -> fake len=' + outdoorS(nr).length);
return nr;
} catch (eD) {
log('[OUTDOOR-DETAIL] ' + name + '#' + idx + ' fake err=' + eD.message);
return r;
}
};
});
};
patchStringGetter('getAllLocJson', function (a) { return a ? a.locEntityJson : ''; });
patchStringGetter('getFivePointJson', function (a) { return a ? a.pointEntityJson : ''; });
patchStringGetter('getSegmentJson', function (a) { return a ? a.segmentJson : '[]'; });
// v65: do NOT hook the setters here. v64 recursively patched inside
// setAllLocJson/setFivePointJson/setSegmentJson and caused StackOverflow/black screen.
if (D.getJsonFromObs && D.getJsonFromObs.overloads) {
D.getJsonFromObs.overloads.forEach(function (ol, idx) {
ol.implementation = function () {
const r = ol.apply(this, arguments);
try {
// If server says "read from OBS" but the local/server detail payload has no url/data,
// the Activity may wait on an impossible download and show black. Fall back to inline fake data.
const artifacts = outdoorPatchRunHistoryDetailBean(factory, this, 'RunHistoryDetailBean.getJsonFromObs#' + idx);
const all = this.getAllLocJson ? this.getAllLocJson() : '';
if (artifacts || (Number(r) === 1 && !outdoorIsEmptyJsonLike(all))) {
try { outdoorCallNoThrow(this, 'setJsonFromObs', ['int'], [0]); } catch (eSetObs) {}
return 0;
}
} catch (eJsonObs) {}
return r;
};
});
log('[OUTDOOR-DETAIL] RunHistoryDetailBean.getJsonFromObs guarded');
}
log('[OUTDOOR-DETAIL] RunHistoryDetailBean empty-json getters hooked');
} catch (eD0) {
log('[OUTDOOR-DETAIL] RunHistoryDetailBean hook pending/miss=' + eD0.message);
}

try {
const P = factory.use('com.zjwh.android_wh_physicalfitness.mvi.run.mode.RunHistoryDetailPImpl');
if (P.getNetData && P.getNetData.overloads) {
P.getNetData.overloads.forEach(function (ol, idx) {
ol.implementation = function () {
try { outdoorPatchRunHistoryDetailPImpl(factory, this, 'RunHistoryDetailPImpl.getNetData#' + idx); } catch (eP) { log('[OUTDOOR-DETAIL] PImpl.getNetData pre err=' + eP.message); }
return ol.apply(this, arguments);
};
});
log('[OUTDOOR-DETAIL] RunHistoryDetailPImpl.getNetData hooked overloads=' + P.getNetData.overloads.length);
}
if (P.getObsData && P.getObsData.overloads) {
P.getObsData.overloads.forEach(function (ol, idx) {
ol.implementation = function () {
try { outdoorPatchRunHistoryDetailPImpl(factory, this, 'RunHistoryDetailPImpl.getObsData#' + idx); } catch (eP) {}
return ol.apply(this, arguments);
};
});
log('[OUTDOOR-DETAIL] RunHistoryDetailPImpl.getObsData hooked overloads=' + P.getObsData.overloads.length);
}
} catch (eP0) {
log('[OUTDOOR-DETAIL] RunHistoryDetailPImpl hook pending/miss=' + eP0.message);
}

try {
const A = factory.use('com.zjwh.android_wh_physicalfitness.mvi.run.RunHistoryDetailActivity');
// clean 版不再安装 View/WindowManager 诊断钩子;placeholder 已经足够稳定。
outdoorInstallWHMapViewPlaceholderHooks(factory);
['initView', 'initData', 'onCreate', 'onResume', 'onPostResume', 'onWindowFocusChanged', 'showData', 'showLoadingDialog', 'showRunCompleteDialog', 'uploadSuccess', 'showUploading', 'uploadRecordFail', 'showUploadError', 'showExtraError', 'showHandleNetworkTime', 'refreshRunOverviewMetrics', 'addLine', 'setStartPoint', 'setEndPoint', 'setFivePoint', 'drawGeoFence', 'onPause', 'onStop', 'onDestroy'].forEach(function (mn) {
try {
if (!A[mn] || !A[mn].overloads) return;
A[mn].overloads.forEach(function (ol2, idx2) {
ol2.implementation = function () {
const t0 = Date.now();
try { outdoorDetailRememberActivity(factory, this, mn + '#' + idx2 + '.enter'); } catch (eN0) {}
try {
if (outdoorDetailSecondPlaceholderActive && (mn === 'addLine' || mn === 'setFivePoint' || mn === 'setStartPoint' || mn === 'setEndPoint' || mn === 'drawGeoFence')) {
outdoorDetailApplyPlaceholder(factory, this, mn + '#' + idx2 + '.skip-enter');
outdoorDetailSchedulePlaceholder(factory, this, mn + '#' + idx2 + '.skip', 80);
log('[OUTDOOR-PLACEHOLDER] skip map native ' + mn + '#' + idx2);
return;
}
} catch (eSkipMapNative) {}
const r = ol2.apply(this, arguments);
try {
if (outdoorDetailSecondPlaceholderActive && (mn === 'initView' || mn === 'onCreate' || mn === 'onResume' || mn === 'onPostResume' || mn === 'showData' || mn === 'refreshRunOverviewMetrics')) {
outdoorDetailApplyPlaceholder(factory, this, mn + '#' + idx2 + '.leave');
outdoorDetailSchedulePlaceholder(factory, this, mn + '#' + idx2 + '.leave', 120);
outdoorDetailSchedulePlaceholder(factory, this, mn + '#' + idx2 + '.leave', 600);
}
} catch (ePhAfter) {}
try { outdoorDetailRememberActivity(factory, this, mn + '#' + idx2 + '.leave'); } catch (eN1) {}
try {
if (mn === 'onStop' || mn === 'onDestroy') {
outdoorDetailClearPlaceholderState(mn + '#' + idx2 + '.leave');
}
} catch (eClr) {}
return r;
};
});
log('[OUTDOOR-DETAIL-NATIVE] hooked ' + mn + ' overloads=' + A[mn].overloads.length);
} catch (eN) { log('[OUTDOOR-DETAIL-NATIVE] hook miss ' + mn + ' err=' + eN.message); }
});
if (A.setMapCenter && A.setMapCenter.overloads) {
A.setMapCenter.overloads.forEach(function (ol, idx) {
ol.implementation = function () {
try {
const list = arguments.length > 0 ? arguments[0] : null;
let size = -1;
try { if (list) size = list.size(); } catch (eSize) {}
const stepLen = outdoorS(arguments.length > 1 ? arguments[1] : '').length;
const speedLen = outdoorS(arguments.length > 2 ? arguments[2] : '').length;
const segLen = outdoorS(arguments.length > 3 ? arguments[3] : '').length;
const lapsLen = outdoorS(arguments.length > 7 ? arguments[7] : '').length;
const pointsLen = outdoorS(arguments.length > 9 ? arguments[9] : '').length;
log('[OUTDOOR-DETAIL] Activity.setMapCenter#' + idx + ' listSize=' + size + ' step=' + stepLen + ' speed=' + speedLen + ' seg=' + segLen + ' laps=' + lapsLen + ' pointsJson=' + pointsLen);
outdoorDetailRememberActivity(factory, this, 'setMapCenter#' + idx + '.enter');
if (Date.now() < outdoorDetailActiveUntilMs && outdoorLastArtifacts) {
const args = [];
for (let i = 0; i < arguments.length; i++) args.push(arguments[i]);
if (args.length >= 10) {
if (!args[0] || size <= 0) args[0] = outdoorBuildSWLatLngList(factory, outdoorLastArtifacts, 'Activity.setMapCenter#' + idx) || args[0];
if (outdoorIsEmptyJsonLike(args[1])) args[1] = outdoorLastArtifacts.stepJson;
if (outdoorIsEmptyJsonLike(args[2])) args[2] = outdoorLastArtifacts.speedJson;
if (outdoorIsEmptyJsonLike(args[3])) args[3] = outdoorLastArtifacts.segmentJson;
if (outdoorIsEmptyJsonLike(args[5])) args[5] = '';
if (outdoorIsEmptyJsonLike(args[6])) args[6] = outdoorLastArtifacts.altitudeJson || '[]';
if (outdoorIsEmptyJsonLike(args[7])) args[7] = outdoorLastArtifacts.lapsJson;
if (outdoorIsEmptyJsonLike(args[8])) args[8] = '';
if (outdoorIsEmptyJsonLike(args[9])) args[9] = outdoorLastArtifacts.locListJson;
// v68: keep v67 minimal native map call, then dump detail Activity view tree.
// Keep the point list, but remove heavy/possibly schema-sensitive chart/fence/lap JSON.
args[1] = '[]'; // stepsPerTenSec
args[2] = '[]'; // speedPerTenSec
args[3] = '[]'; // segmentJson
args[5] = ''; // runFaceCheck
args[6] = '[]'; // altitudeJson
args[7] = ''; // lapsJson
args[8] = '';
args[9] = '';
log('[OUTDOOR-DETAIL] Activity.setMapCenter#' + idx + ' v101 clean-placeholder native call listSize=' + (args[0] ? args[0].size() : -1));
if (outdoorDetailSecondPlaceholderActive) {
outdoorDetailApplyPlaceholder(factory, this, 'setMapCenter#' + idx + '.skip-native');
outdoorDetailSchedulePlaceholder(factory, this, 'setMapCenter#' + idx + '.skip-native', 120);
outdoorDetailSchedulePlaceholder(factory, this, 'setMapCenter#' + idx + '.skip-native', 700);
log('[OUTDOOR-PLACEHOLDER] skip setMapCenter native listSize=' + (args[0] ? args[0].size() : -1));
outdoorDetailRememberActivity(factory, this, 'setMapCenter#' + idx + '.leave.skip');
return;
}
const tNative = Date.now();
const rr = ol.apply(this, args);
log('[OUTDOOR-DETAIL] Activity.setMapCenter#' + idx + ' v101 clean-placeholder native returned ms=' + (Date.now() - tNative));
outdoorDetailRememberActivity(factory, this, 'setMapCenter#' + idx + '.leave');
return rr;
}
}
} catch (eMap) {
log('[OUTDOOR-DETAIL] Activity.setMapCenter pre err=' + eMap.message);
}
return ol.apply(this, arguments);
};
});
log('[OUTDOOR-DETAIL] RunHistoryDetailActivity.setMapCenter hooked overloads=' + A.setMapCenter.overloads.length);
}
} catch (eA0) {
log('[OUTDOOR-DETAIL] RunHistoryDetailActivity.setMapCenter hook pending/miss=' + eA0.message);
}
}

function installOutdoorRunHooksWithFactory(factory, reason) {
if (outdoorInstalled) return true;
try {
hookOutdoorRunUiState(factory);
hookOutdoorOptional(factory);
outdoorInstalled = true;
log('[OUTDOOR-FAKE] hook installed reason=' + reason);
return true;
} catch (e) {
return false;
}
}

function findOutdoorFactoryLowFreq(reason) {
try {
if (installOutdoorRunHooksWithFactory(Java.classFactory, reason + '/default')) return true;
} catch (e0) {}

// Low-frequency loader scan only. No ClassLoader.loadClass global hook, no loaded-class full scan.
try {
const loaders = Java.enumerateClassLoadersSync();
for (let i = 0; i < loaders.length; i++) {
try {
loaders[i].loadClass(OUTDOOR_CFG.target);
const factory = Java.ClassFactory.get(loaders[i]);
if (installOutdoorRunHooksWithFactory(factory, reason + '/loader#' + i)) return true;
} catch (e1) {}
}
} catch (e2) {
log('[OUTDOOR] loader scan err=' + e2.message);
}
return false;
}

function scheduleOutdoorRunHooks(reason) {
if (installed['outdoor-sched'] || outdoorInstalled) return;
installed['outdoor-sched'] = true;
log('[OUTDOOR] scheduler started reason=' + reason + ' poll=' + OUTDOOR_CFG.pollIntervalMs + 'ms');

const runner = function () {
if (outdoorInstalled) return;
try {
const job = function () {
if (outdoorInstalled) return;
outdoorPollCount++;
const doLoaderScan = outdoorPollCount === 1 || (outdoorPollCount % 10) === 0;

try {
if (installOutdoorRunHooksWithFactory(Java.classFactory, 'poll#' + outdoorPollCount + '/default')) return;
} catch (e0) {}

if (doLoaderScan) {
if (findOutdoorFactoryLowFreq('poll#' + outdoorPollCount)) return;
log('[OUTDOOR] waiting target class; elapsed=' + Math.floor(outdoorPollCount * OUTDOOR_CFG.pollIntervalMs / 1000) + 's');
}

if (outdoorPollCount >= OUTDOOR_CFG.maxPolls) {
log('[OUTDOOR] scheduler exhausted; open outdoor run page then reload/attach this script if needed');
return;
}
setTimeout(runner, OUTDOOR_CFG.pollIntervalMs);
};

if (javaPrimed && typeof Java.performNow === 'function') Java.performNow(job);
else Java.perform(job);
} catch (e) {
log('[OUTDOOR] scheduler err=' + e.message);
if (outdoorPollCount < OUTDOOR_CFG.maxPolls) setTimeout(runner, OUTDOOR_CFG.pollIntervalMs);
}
};

setTimeout(runner, 2000);
}

function main() {
log('[START] v101 clean placeholder + anti-debug stable');
log('[CFG] nesec=first-thread-replace nllvm=worker65e44+state msaoaid=targeted gtcore=probe0 NetEase=lazy-init LuAsset=native-first detail=placeholder');
primeJavaRuntime();
scheduleLuAssetBridge('startup');
installRegisterNativesTrace();
installNesecMapsSanitize();
hookPthreadCreate();
hookLinker();
installLoadedTargets('startup');
scheduleOutdoorRunHooks('main');
log('[START] loaded v101-clean-placeholder-optimized');
}

main();