diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 73c1ecc..a47a88d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -30,6 +30,13 @@ jobs: with: go-version: '1.24' + # Zygisk 模块 (C++) 需要 NDK 交叉编译; 该 action 会设置 ANDROID_NDK_HOME, + # dev/lib/ndk.mjs 据此定位工具链 + - name: Setup Android NDK + uses: nttld/setup-ndk@v1 + with: + ndk-version: r27c + # 根依赖提供打包所需的 zip 库 (@zip.js/zip.js), # 打包脚本不再依赖 zip / unzip 命令, 故无需系统级安装 - name: Install root dependencies @@ -41,7 +48,8 @@ jobs: - name: Build WebUI run: pnpm -C web build - # 打包内部会交叉编译 fontmm-wght 并生成两版产物与 .sha256 校验文件 + # 打包内部会编译 fontmm-wght (Go) 与 Zygisk 模块 (C++), + # 并生成两版产物与 .sha256 校验文件 # 注意: 必须写 `pnpm run pack`, 不可省略 run —— `pnpm pack` 是 pnpm 内置的 # 打包命令 (生成 npm tarball), 会与我们定义的 pack 脚本冲突 - name: Pack module (preplace / template) diff --git a/.github/workflows/native.yml b/.github/workflows/native.yml new file mode 100644 index 0000000..5ad9278 --- /dev/null +++ b/.github/workflows/native.yml @@ -0,0 +1,42 @@ +name: Native (Zygisk) + +on: + push: + paths: + - 'native/**' + - 'dev/build-zygisk.mjs' + - 'dev/lib/ndk.mjs' + pull_request: + paths: + - 'native/**' + - 'dev/build-zygisk.mjs' + - 'dev/lib/ndk.mjs' + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: 22 + + - name: Setup Android NDK + uses: nttld/setup-ndk@v1 + with: + ndk-version: r27c + + # 构建脚本自身会校验导出符号与动态依赖 (不得依赖 libc++_shared 等 + # 不在 Zygisk 加载器搜索路径中的库), 校验失败即退出非 0 + - name: Build Zygisk module (arm64-v8a) + run: node dev/build-zygisk.mjs + + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: fontmm-zygisk-arm64-v8a + path: src/zygisk/arm64-v8a.so diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9687a4a..100366c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -32,6 +32,13 @@ jobs: with: go-version: '1.24' + # Zygisk 模块 (C++) 需要 NDK 交叉编译; 该 action 会设置 ANDROID_NDK_HOME, + # dev/lib/ndk.mjs 据此定位工具链 + - name: Setup Android NDK + uses: nttld/setup-ndk@v1 + with: + ndk-version: r27c + # 根依赖提供打包所需的 zip 库 (@zip.js/zip.js), # 打包脚本不再依赖 zip / unzip 命令, 故无需系统级安装 - name: Install root dependencies @@ -43,7 +50,8 @@ jobs: - name: Build WebUI run: pnpm -C web build - # 打包内部会交叉编译 fontmm-wght 并生成两版产物与 .sha256 校验文件 + # 打包内部会编译 fontmm-wght (Go) 与 Zygisk 模块 (C++), + # 并生成两版产物与 .sha256 校验文件 # 注意: 必须写 `pnpm run pack`, 不可省略 run —— `pnpm pack` 是 pnpm 内置的 # 打包命令 (生成 npm tarball), 会与我们定义的 pack 脚本冲突 - name: Pack module (preplace / template) diff --git a/.gitignore b/.gitignore index e55350e..a197b32 100644 --- a/.gitignore +++ b/.gitignore @@ -17,3 +17,10 @@ src/system/etc/fonts_base.xml src/system/etc/fonts_ule.xml src/system/etc/font_fallback.xml src/system/system_ext/ + +# Zygisk 模块产物 (由 dev/build-zygisk.mjs 生成) +src/zygisk/ +native/build/ + +# 编辑器 C++ 索引数据 (由 dev/build-zygisk.mjs 生成) +compile_commands.json diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json new file mode 100644 index 0000000..87224c2 --- /dev/null +++ b/.vscode/c_cpp_properties.json @@ -0,0 +1,20 @@ +{ + // C/C++ 智能提示配置。 + // + // native/ 下的 Zygisk 模块用 Android NDK 交叉编译, 头文件 (jni.h / android/log.h 等) + // 不在系统路径中, 因此交给 compile_commands.json 提供真实构建参数 —— 该文件由 + // `pnpm zygisk:build` (或 pnpm build) 生成, 首次克隆后需先构建一次。 + // + // clangd 扩展会自动发现仓库根的 compile_commands.json, 无需此文件; + // 这里是为 Microsoft C/C++ 扩展 (ms-vscode.cpptools) 提供同等配置。 + "configurations": [ + { + "name": "Android arm64-v8a", + "compileCommands": "${workspaceFolder}/compile_commands.json", + "cStandard": "c17", + "cppStandard": "c++20", + "intelliSenseMode": "linux-clang-arm64" + } + ], + "version": 4 +} diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 99e2f7d..3e8946d 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -1,3 +1,7 @@ { - "recommendations": ["oxc.oxc-vscode"] + "recommendations": [ + "oxc.oxc-vscode", + "llvm-vs-code-extensions.vscode-clangd", + "ms-vscode.cpptools" + ] } diff --git a/dev/build-zygisk.mjs b/dev/build-zygisk.mjs new file mode 100644 index 0000000..eaf1fd6 --- /dev/null +++ b/dev/build-zygisk.mjs @@ -0,0 +1,39 @@ +#!/usr/bin/env node +// dev/build-zygisk.mjs — 交叉编译 Zygisk 模块 (C++ -> arm64-v8a.so) +// +// 产物输出到 src/zygisk/.so, 随模块 zip 打包。Zygisk 加载器按约定路径 +// /data/adb/modules/<模块名>/zygisk/.so 查找模块, 因此文件名必须精确匹配 +// (Magisk 与 ReZygisk 等实现均使用 ABI 全名, 如 arm64-v8a.so)。 +// +// 需要 Android NDK。设置 ANDROID_NDK_HOME 指定, 或放到常见位置 (见 dev/lib/ndk.mjs)。 +// +// 用法: node dev/build-zygisk.mjs +import fsp from 'node:fs/promises'; +import path from 'node:path'; +import { log, die } from './lib/log.mjs'; +import { ROOT, SRC_DIR } from './lib/paths.mjs'; +import { findNdk, buildZygiskModule, TARGET_ABI } from './lib/ndk.mjs'; + +const ndkRoot = await findNdk(); +if (!ndkRoot) { + die( + '未找到 Android NDK。请设置 ANDROID_NDK_HOME, 或下载到 ~/opt/android-ndk-r27c\n' + + ' 下载: https://developer.android.com/ndk/downloads', + ); +} +log.info(`NDK: ${ndkRoot}`); + +log.step(`交叉编译 Zygisk 模块 (android/${TARGET_ABI})...`); +const { outFile, size } = await buildZygiskModule(ndkRoot, { + onLog: (m) => log.info(m), +}); + +// 复制到模块目录 (打包时按此路径收录) +const destDir = path.join(SRC_DIR, 'zygisk'); +const dest = path.join(destDir, `${TARGET_ABI}.so`); +await fsp.mkdir(destDir, { recursive: true }); +await fsp.copyFile(outFile, dest); +// 库文件不需要执行位, 但需要可读 +await fsp.chmod(dest, 0o644); + +log.ok(`产物: ${path.relative(ROOT, dest)} (${size} 字节)`); diff --git a/dev/ci.mjs b/dev/ci.mjs index 7468915..2ab1ae7 100644 --- a/dev/ci.mjs +++ b/dev/ci.mjs @@ -16,7 +16,7 @@ import fsp from 'node:fs/promises'; import path from 'node:path'; import { spawnSync } from 'node:child_process'; import { log, die } from './lib/log.mjs'; -import { ROOT, SRC_DIR, WEB_DIR, MODULE_PROP, FONTS_XML, DERIVED_XML_RELS } from './lib/paths.mjs'; +import { ROOT, SRC_DIR, WEB_DIR, MODULE_PROP, FONTS_XML, DERIVED_XML_RELS, NATIVE_DIR } from './lib/paths.mjs'; import { run, hasCommand } from './lib/exec.mjs'; const strict = process.argv.includes('--strict'); @@ -158,6 +158,43 @@ await check('apply.sh 占位映射与占位清单一致', async () => { } }); +// Zygisk 预加载的字体清单必须覆盖 apply.sh 会替换的全部字体文件。 +// 两者若不一致, 缺失的字体在 DenyList 应用里会静默渲染失败, 问题极难定位。 +await check('Zygisk 预热字体清单与 apply.sh 一致', async () => { + const applySh = await fsp.readFile(path.join(SRC_DIR, 'apply.sh'), 'utf8'); + + // apply.sh 会写入 system/fonts/ 的全部文件名: + // 1. 占位字体 (hans/hant/en 三组多行列表) + // 2. 直接替换的系统字体 (DroidSansMono / NotoColorEmoji, 单行) + const expected = new Set(); + for (const m of applySh.matchAll(/'([^']*)'/g)) { + const value = m[1]; + const lines = value.includes('\n') ? value.split('\n') : [value]; + for (const line of lines) { + const name = line.trim(); + // 只看形如 xxx.ttf 的纯文件名 (排除含路径或变量的内容) + if (/^[A-Za-z0-9_-]+\.ttf$/.test(name)) expected.add(name); + } + } + if (expected.size === 0) throw new Error('未从 apply.sh 解析到字体文件名 (解析逻辑可能已失效)'); + + const cpp = await fsp.readFile(path.join(NATIVE_DIR, 'src', 'fontmm.cpp'), 'utf8'); + const block = cpp.match(/kFontFiles\[\]\s*=\s*\{([\s\S]*?)\};/); + if (!block) throw new Error('fontmm.cpp 中未找到 kFontFiles 列表'); + const actual = new Set( + [...block[1].matchAll(/"\/system\/fonts\/([A-Za-z0-9_-]+\.ttf)"/g)].map((m) => m[1]), + ); + + const missing = [...expected].filter((n) => !actual.has(n)); + const extra = [...actual].filter((n) => !expected.has(n)); + if (missing.length) { + throw new Error(`fontmm.cpp 缺少以下字体的预热 (apply.sh 会替换它们): ${missing.join(', ')}`); + } + if (extra.length) { + throw new Error(`fontmm.cpp 预热了 apply.sh 不会替换的字体: ${extra.join(', ')}`); + } +}); + // 前端脚本引用的 dev 入口必须存在 (避免重命名后 package.json 指向不存在的文件) await check('package.json 中引用的 dev 脚本存在', async () => { const pkg = JSON.parse(await fsp.readFile(path.join(ROOT, 'package.json'), 'utf8')); diff --git a/dev/gen-sha256.mjs b/dev/gen-sha256.mjs index d10d20e..661449e 100644 --- a/dev/gen-sha256.mjs +++ b/dev/gen-sha256.mjs @@ -20,10 +20,11 @@ import { hashFile } from './lib/zip.mjs'; const noDist = process.argv.includes('--no-dist'); -/** 模块内需要校验的文件: shell 脚本 + 模块二进制 + Magisk 安装脚本 */ +/** 模块内需要校验的文件: shell 脚本 + 模块二进制 + Zygisk 库 + Magisk 安装脚本 */ const SUM_PATTERNS = [ (name) => name.endsWith('.sh'), (name) => name === 'fontmm-wght', + (name) => name.endsWith('.so'), // Zygisk 模块 (zygisk/arm64-v8a.so) (name) => name === 'update-binary', (name) => name === 'updater-script', ]; diff --git a/dev/lib/ndk.mjs b/dev/lib/ndk.mjs new file mode 100644 index 0000000..fd112b5 --- /dev/null +++ b/dev/lib/ndk.mjs @@ -0,0 +1,194 @@ +// dev/lib/ndk.mjs — Android NDK 工具链定位与 C++ 交叉编译 +// +// Zygisk 模块必须编译成 aarch64 的 ELF 共享库, 因此需要 Android NDK。 +// NDK 体积很大 (约 600MB) 且不进仓库, 通过环境变量或常见安装位置查找。 +import fsp from 'node:fs/promises'; +import path from 'node:path'; +import os from 'node:os'; +import { ROOT, NATIVE_DIR } from './paths.mjs'; +import { run } from './exec.mjs'; + +/** 目标 ABI: ColorOS 16 设备均为 arm64 */ +export const TARGET_ABI = 'arm64-v8a'; +/** 最低 API 级别: 与 nativeWarmUpCache 的引入版本一致 (Android 12) */ +export const MIN_API = 31; + +/** NDK 常见安装位置 (按优先级) */ +const NDK_CANDIDATES = [ + process.env.ANDROID_NDK_HOME, + process.env.ANDROID_NDK_ROOT, + process.env.NDK_HOME, + path.join(os.homedir(), 'opt', 'android-ndk-r27c'), + path.join(os.homedir(), 'Android', 'Sdk', 'ndk'), + '/opt/android-ndk', + '/usr/lib/android-ndk', +]; + +/** + * 定位 NDK 根目录。 + * @returns {Promise} NDK 根目录, 未找到返回 null + */ +export async function findNdk() { + for (const candidate of NDK_CANDIDATES) { + if (!candidate) continue; + // 直接指向 NDK 根 + const sourceProps = path.join(candidate, 'source.properties'); + try { + await fsp.access(sourceProps); + return candidate; + } catch { + // 不是 NDK 根, 继续; 也可能是 ndk/<版本>/ 形式 (Android SDK 布局) + } + // Android SDK 的 ndk/ 目录: 取版本号最大的一个 + try { + const entries = (await fsp.readdir(candidate, { withFileTypes: true })) + .filter((e) => e.isDirectory()) + .map((e) => e.name) + .sort() + .reverse(); + for (const name of entries) { + const dir = path.join(candidate, name); + try { + await fsp.access(path.join(dir, 'source.properties')); + return dir; + } catch { + // 继续找下一个 + } + } + } catch { + // 目录不存在, 继续 + } + } + return null; +} + +/** 由 NDK 根目录推导出 prebuilt 工具链的 bin 目录 */ +export function toolchainBin(ndkRoot) { + return path.join(ndkRoot, 'toolchains', 'llvm', 'prebuilt', 'linux-x86_64', 'bin'); +} + +/** + * 生成 compile_commands.json, 让编辑器 (clangd / VSCode C/C++ 扩展) 用与真实构建 + * 完全相同的参数解析源码, 从而正确找到 NDK 的头文件 (jni.h / android/log.h 等), + * 否则编辑器会满屏 "无法打开源文件" 的 IntelliSense 报错。 + * + * 不依赖 CMake: 我们只有单个源文件, 直接按 clang 的 JSON Compilation Database 格式 + * 写一条记录即可。写入仓库根, 便于编辑器自动发现; 该文件是构建产物, 已被 .gitignore 忽略。 + * + * @param {string} cxx 编译器绝对路径 + * @param {string[]} args 构建参数 + */ +async function writeCompileCommands(cxx, args) { + const sourceRel = path.join('native', 'src', 'fontmm.cpp'); + const sourceAbs = path.join(ROOT, sourceRel); + + const entry = { + directory: ROOT, + arguments: [cxx, ...args.map((a) => (a === sourceRel ? sourceAbs : a))], + file: sourceAbs, + }; + + await fsp.writeFile( + path.join(ROOT, 'compile_commands.json'), + JSON.stringify([entry], null, 2), + 'utf8', + ); +} + +/** + * 编译 Zygisk 模块。 + * + * 编译选项说明 (每一项都影响产物能否被 Zygisk 加载器正确加载): + * -fPIC / -shared 共享库基础 + * -fvisibility=hidden 只导出显式标记的符号 (zygisk_module_entry) + * -ffixed-x18 ARM64 平台寄存器约定, Android 要求 + * -fno-exceptions -fno-rtti 减小体积, 且异常跨 .so 边界无意义 + * -fno-threadsafe-statics 取消静态局部变量的线程安全 guard。 + * 否则会引入 __cxa_guard_acquire/release, 这两个符号 + * 不在 bionic libc 的导出表里 (仅 libc++ 提供), 而 + * Zygisk 的自研加载器只解析系统库, 会导致加载失败。 + * -nostdlib++ 不链接 libc++ (我们的代码不需要), 产物从 464KB 降到 10KB, + * 同时避免依赖 libc++_shared.so (它不在加载器的搜索路径中)。 + * 静态初始化改由 C++ 编译器直接发射, 无需运行时支持。 + * + * @param {string} ndkRoot NDK 根目录 + * @param {{onLog?: (msg: string) => void}} [opts] + * @returns {Promise<{ outFile: string, size: number }>} + */ +export async function buildZygiskModule(ndkRoot, opts = {}) { + const bin = toolchainBin(ndkRoot); + const cxx = path.join(bin, `aarch64-linux-android${MIN_API}-clang++`); + const nm = path.join(bin, 'llvm-nm'); + const strip = path.join(bin, 'llvm-strip'); + + const outDir = path.join(NATIVE_DIR, 'build'); + const outFile = path.join(outDir, `${TARGET_ABI}.so`); + await fsp.mkdir(outDir, { recursive: true }); + + const args = [ + '-std=c++20', + '-O2', + '-fPIC', + '-shared', + '-Wall', + '-Wextra', + '-fvisibility=hidden', + '-fvisibility-inlines-hidden', + '-ffixed-x18', + '-fno-exceptions', + '-fno-rtti', + '-fno-threadsafe-statics', + '-nostdlib++', + // 可复现构建: 去掉源码绝对路径 + '-ffile-prefix-map=' + NATIVE_DIR + '=.', + '-o', + outFile, + path.join(NATIVE_DIR, 'src', 'fontmm.cpp'), + '-llog', + ]; + + run(cxx, args, { cwd: ROOT }); + // 去掉调试符号与本地符号 (6.8KB vs 10.4KB), 动态符号表不受影响 + run(strip, ['--strip-unneeded', outFile], { cwd: ROOT }); + opts.onLog?.(`编译完成: ${path.relative(ROOT, outFile)}`); + + // 生成 compile_commands.json: 供 clangd / VSCode C/C++ 扩展解析本文件, + // 使其能定位 NDK 的头文件 (jni.h / android/log.h 等), 否则编辑器会满屏 + // "无法打开源文件" 的 IntelliSense 报错。 + await writeCompileCommands(cxx, args); + + // 校验导出符号: Zygisk 只认 zygisk_module_entry, 多导出会污染宿主进程符号表 + const symbols = (run(nm, ['-D', '--defined-only', outFile], { quiet: true }).stdout ?? '') + .split('\n') + .map((l) => l.trim().split(/\s+/).pop()) + .filter(Boolean); + const expected = 'zygisk_module_entry'; + const unexpected = symbols.filter((s) => s !== expected); + if (!symbols.includes(expected)) { + throw new Error(`产物缺少 ${expected} 导出符号 (Zygisk 无法识别该模块)`); + } + if (unexpected.length > 0) { + throw new Error(`产物导出了预期外的符号: ${unexpected.join(', ')}`); + } + + // 校验没有链接 libc++_shared: 它不在 Zygisk 加载器的库搜索路径中 + const needed = (run( + path.join(bin, 'llvm-readelf'), + ['-d', outFile], + { quiet: true }, + ).stdout ?? '') + .split('\n') + .filter((l) => l.includes('NEEDED')) + .map((l) => l.match(/\[(.*)\]/)?.[1]) + .filter(Boolean); + const libcxx = needed.find((l) => l.includes('libc++')); + if (libcxx) { + throw new Error( + `产物依赖 ${libcxx}, 该库不在 Zygisk 加载器的搜索路径中, 会导致模块加载失败`, + ); + } + opts.onLog?.(`动态依赖: ${needed.join(', ')}`); + + const { size } = await fsp.stat(outFile); + return { outFile, size }; +} diff --git a/dev/lib/paths.mjs b/dev/lib/paths.mjs index d5f5fd1..9598b66 100644 --- a/dev/lib/paths.mjs +++ b/dev/lib/paths.mjs @@ -11,10 +11,15 @@ export const SRC_DIR = path.join(ROOT, 'src'); export const WEB_DIR = path.join(ROOT, 'web'); export const DIST_DIR = path.join(ROOT, 'dist'); export const GOLANG_DIR = path.join(ROOT, 'golang'); +/** Zygisk 原生模块 (C++) 源码目录 */ +export const NATIVE_DIR = path.join(ROOT, 'native'); export const WEBROOT_DIR = path.join(SRC_DIR, 'webroot'); export const MODULE_PROP = path.join(SRC_DIR, 'module.prop'); export const FONTS_XML = path.join(SRC_DIR, 'system', 'etc', 'fonts.xml'); +/** 模块内 Zygisk 库目录 (相对模块根): 加载器约定读 zygisk/.so */ +export const ZYGISK_DIR_REL = 'zygisk'; + /** 派生字体配置 (不打包, 由设备端 customize.sh 生成; 开发期用 sync-fonts-xml 本地生成) */ export const DERIVED_XML_RELS = [ 'system/etc/fonts_base.xml', diff --git a/dev/pack.mjs b/dev/pack.mjs index 2544fb4..eaacb43 100644 --- a/dev/pack.mjs +++ b/dev/pack.mjs @@ -5,10 +5,12 @@ // _preplace: 含 FONTS/hans.ttf, 适合全新安装 // _template: FONTS/ 为空目录, 适合更新已有模块 (customize.sh 从旧模块继承字体) // -// 流程: 交叉编译 fontmm-wght -> 生成 SHA256SUMS -> 打包两版 -> 校验产物 -> 生成发布校验文件 +// 流程: 编译 fontmm-wght (Go) 与 Zygisk 模块 (C++) -> 生成 SHA256SUMS +// -> 打包两版 -> 校验产物 -> 生成发布校验文件 // -// 用法: node dev/pack.mjs [--skip-go] -// --skip-go: 跳过 Go 交叉编译 (CI 中已单独构建时使用) +// 用法: node dev/pack.mjs [--skip-go] [--skip-zygisk] +// --skip-go: 跳过 Go 交叉编译 (CI 中已单独构建时使用) +// --skip-zygisk: 跳过 Zygisk 模块编译 (无 NDK 或已构建好时使用) import fsp from 'node:fs/promises'; import path from 'node:path'; import { log, die, stopwatch } from './lib/log.mjs'; @@ -16,8 +18,10 @@ import { ROOT, SRC_DIR, DIST_DIR, DERIVED_XML_RELS, readVersion, safeFileVersion import { packDir, listEntries, indexZip, hashFile } from './lib/zip.mjs'; import { run, hasCommand } from './lib/exec.mjs'; import { buildWght, wghtBinRel, WGHT_BIN } from './lib/go.mjs'; +import { findNdk, buildZygiskModule, TARGET_ABI } from './lib/ndk.mjs'; const skipGo = process.argv.includes('--skip-go'); +const skipZygisk = process.argv.includes('--skip-zygisk'); const elapsed = stopwatch(); // 可复现打包: 设置 SOURCE_DATE_EPOCH 时, 所有 zip 条目使用该固定时间戳, @@ -55,11 +59,37 @@ if (skipGo) { log.ok(`产物: ${wghtBinRel()} (${size} 字节)`); } -// ---------- 2. 生成模块内可执行文件校验表 (src/SHA256SUMS) ---------- +// ---------- 2. 交叉编译 Zygisk 模块 (字体预加载用的 C++ 程序) ---------- +const zygiskBin = path.join(SRC_DIR, 'zygisk', `${TARGET_ABI}.so`); +if (skipZygisk) { + log.info('已跳过 Zygisk 模块编译 (--skip-zygisk)'); + try { + await fsp.access(zygiskBin); + } catch { + die(`缺少 ${path.relative(ROOT, zygiskBin)}, 请先运行 pnpm zygisk:build`); + } +} else { + const ndkRoot = await findNdk(); + if (!ndkRoot) { + die( + '未找到 Android NDK, 无法编译 Zygisk 模块。\n' + + ' 请设置 ANDROID_NDK_HOME, 或下载到 ~/opt/android-ndk-r27c\n' + + ' 仅打包现有产物: node dev/pack.mjs --skip-zygisk', + ); + } + log.step(`交叉编译 Zygisk 模块 (android/${TARGET_ABI})...`); + const { size } = await buildZygiskModule(ndkRoot, { onLog: (m) => log.detail(m) }); + await fsp.mkdir(path.dirname(zygiskBin), { recursive: true }); + await fsp.copyFile(path.join(ROOT, 'native', 'build', `${TARGET_ABI}.so`), zygiskBin); + await fsp.chmod(zygiskBin, 0o644); + log.ok(`产物: ${path.relative(ROOT, zygiskBin)} (${size} 字节)`); +} + +// ---------- 3. 生成模块内可执行文件校验表 (src/SHA256SUMS) ---------- log.step('生成 SHA256 校验文件...'); run(process.execPath, [path.join(ROOT, 'dev', 'gen-sha256.mjs'), '--no-dist'], { cwd: ROOT }); -// ---------- 3. 打包 ---------- +// ---------- 4. 打包 ---------- // 派生字体配置 (fonts_base/ule/font_fallback) 由设备端 customize.sh 扫描生成, // 不随包分发; 这里一律排除, 避免与设备端生成结果冲突。 const exclude = ['*.git*', '*.DS_Store', '*.swp', '*~', '*.bak', ...DERIVED_XML_RELS]; diff --git a/native/src/fontmm.cpp b/native/src/fontmm.cpp new file mode 100644 index 0000000..c7c111a --- /dev/null +++ b/native/src/fontmm.cpp @@ -0,0 +1,162 @@ +// FontMM Zygisk 模块 — 字体预加载 +// SPDX-License-Identifier: GPL-3.0 +// +// 背景: Android 12 起字体不再由 zygote 预加载, 而是各 app 进程按需读取。 +// 当 Root 管理器对某个 app 执行「卸载模块」(DenyList / App Profile), 该 app 的 +// 挂载视图里就没有模块的字体了; 但 app 启动早期仍会去读这些字体, 结果读不到, +// 表现为字体显示异常甚至闪退。 +// +// 解法: 在 app specialize *之前* (此时进程仍是 zygote 的挂载视图) 让 ART 把字体 +// 数据读进 Skia 的全局缓存。缓存的 key 是字体路径, 且进程生命周期内不清除, 因此 +// specialize 之后即使路径已不可访问, 仍能命中缓存正常渲染。 +// +// 与参考实现 (JingMatrix/FontLoader) 的差异: +// 1. 只预热 FontMM 自己的字体 —— 字体清单在编译期已知, 无需 root companion +// 进程扫描 /data/adb/modules/*/system/fonts 再通过 socket 传回。 +// 这样省掉了整个 companion 与 IPC, 代码量与攻击面都大幅缩小。 +// 2. 不包含 HideFromMaps (把字体从 /proc/self/maps 摘除的反检测逻辑)。 +// 参考实现里该函数是死代码, 从未被调用; 且它对字体正常渲染并非必需。 +// +// 目标架构: arm64 (ColorOS 16 设备), 产物 zygisk/arm64-v8a.so +// +// 加载约束 (编译选项据此确定, 见 dev/lib/ndk.mjs): +// Zygisk 提供者 (Magisk / Zygisk Next / ReZygisk 等) 用自己的 ELF 加载器装载本库, +// 不使用系统 dlopen。该加载器只从系统库目录解析依赖, 因此本库不得依赖 +// libc++_shared.so, 也不得引用其提供的 __cxa_guard_* (故禁用线程安全静态初始化)。 + +#include +#include +#include + +#include + +#include "zygisk.hpp" + +using zygisk::Api; +using zygisk::AppSpecializeArgs; +using zygisk::ServerSpecializeArgs; + +#define LOG_TAG "FontMM" +#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) +#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__) +#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) + +// 需要预热的字体 (系统路径)。 +// +// 这些正是 apply.sh 会写入 system/fonts/ 的文件, 也是在 fonts.xml 中被 +// sans-serif / sys-sans-en / zh-Hans / zh-Hant 等家族引用的文件。缺一个都可能 +// 让某个家族在 DenyList 应用里渲染失败。 +// +// 注意: 仅列出 FontMM 确实会替换的文件 (与 src/apply.sh 的映射表保持一致); +// 未设置的槽位不会产生对应文件, 此时该项会被 prepare 阶段跳过。 +static const char *const kFontFiles[] = { + // 中文简体槽位 + "/system/fonts/SysSans-Hans-Regular.ttf", + "/system/fonts/SysFont-Static-Regular.ttf", + "/system/fonts/SysFont-Myanmar.ttf", + "/system/fonts/SysFont-Hans-Regular.ttf", + // 中文繁体槽位 + "/system/fonts/SysSans-Hant-Regular.ttf", + "/system/fonts/SysFont-Hant-Regular.ttf", + // 英文 & 数字槽位 + "/system/fonts/SysSans-En-Regular.ttf", + "/system/fonts/SysFont-Regular.ttf", + // 等宽槽位 + "/system/fonts/DroidSansMono.ttf", + // Emoji 槽位 + "/system/fonts/NotoColorEmoji.ttf", +}; + +/** + * 预热单个字体: 调用 Typeface.nativeWarmUpCache(String)。 + * + * 该方法在 AOSP 中是 private static native (Typeface.java), 签名 "(Ljava/lang/String;)V", + * 从 Android 12 到 16 均存在。其原生实现为 Typeface_warmUpCache -> makeSkDataCached, + * 把字体文件 mmap 进 Skia 的静态数据缓存 (以路径字符串为 key, 进程内不清除)。 + * + * 这里通过 GetStaticMethodID 直接获取, 不做权限检查 —— 在 preAppSpecialize + * 阶段进程仍具备 zygote 权限, 可以正常拿到该私有方法。 + */ +static bool WarmUpFont(JNIEnv *env, jclass typefaceCls, jmethodID methodId, const char *path) { + // 只预热确实存在的文件: 未设置的槽位不会有对应文件 + if (access(path, F_OK) != 0) return false; + + jstring jPath = env->NewStringUTF(path); + if (jPath == nullptr) { + env->ExceptionClear(); + return false; + } + + env->CallStaticVoidMethod(typefaceCls, methodId, jPath); + env->DeleteLocalRef(jPath); + + if (env->ExceptionCheck()) { + LOGW("预热失败: %s", path); + // 打印并清除异常, 避免影响 zygote 后续的 specialize 流程 + env->ExceptionDescribe(); + env->ExceptionClear(); + return false; + } + + LOGD("已预热: %s", path); + return true; +} + +class FontMMModule : public zygisk::ModuleBase { +public: + void onLoad(Api *api, JNIEnv *env) override { + this->api = api; + this->env = env; + } + + void preAppSpecialize([[maybe_unused]] AppSpecializeArgs *args) override { + // 对所有 app 进程都预热, 不按 uid 过滤。 + // + // 这里刻意不做「跳过系统进程」的优化: ColorOS 有大量以 android.uid.system + // (uid 1000) 运行的系统应用, 它们同样会被加入 DenyList 而失去字体访问权, + // 正是最需要预热的对象。按 uid 过滤会恰好漏掉这类进程, 导致系统应用字体异常。 + // + // 每个 app 进程只预热一次, 且只读已挂载的字体文件, 开销可接受。 + PreloadFonts(); + + // 本模块只做一次性预热, 不留任何 hook, 可以安全卸载 + api->setOption(zygisk::Option::DLCLOSE_MODULE_LIBRARY); + } + + void preServerSpecialize([[maybe_unused]] ServerSpecializeArgs *args) override { + api->setOption(zygisk::Option::DLCLOSE_MODULE_LIBRARY); + } + +private: + Api *api{}; + JNIEnv *env{}; + + void PreloadFonts() { + jclass typefaceCls = env->FindClass("android/graphics/Typeface"); + if (typefaceCls == nullptr) { + env->ExceptionClear(); + LOGE("找不到 android.graphics.Typeface"); + return; + } + + jmethodID methodId = env->GetStaticMethodID(typefaceCls, "nativeWarmUpCache", + "(Ljava/lang/String;)V"); + if (methodId == nullptr) { + env->ExceptionClear(); + LOGE("找不到 Typeface.nativeWarmUpCache (系统版本不兼容?)"); + env->DeleteLocalRef(typefaceCls); + return; + } + + int ok = 0; + for (const char *path : kFontFiles) { + if (WarmUpFont(env, typefaceCls, methodId, path)) ok++; + } + + LOGD("字体预热完成: %d/%zu", ok, sizeof(kFontFiles) / sizeof(kFontFiles[0])); + + env->DeleteLocalRef(typefaceCls); + } +}; + +REGISTER_ZYGISK_MODULE(FontMMModule) diff --git a/native/src/zygisk.hpp b/native/src/zygisk.hpp new file mode 100644 index 0000000..9749755 --- /dev/null +++ b/native/src/zygisk.hpp @@ -0,0 +1,395 @@ +/* Copyright 2022-2023 John "topjohnwu" Wu + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ + +// This is the public API for Zygisk modules. +// DO NOT MODIFY ANY CODE IN THIS HEADER. + +#pragma once + +#include + +#define ZYGISK_API_VERSION 5 + +/* + +*************** +* Introduction +*************** + +On Android, all app processes are forked from a special daemon called "Zygote". +For each new app process, zygote will fork a new process and perform "specialization". +This specialization operation enforces the Android security sandbox on the newly forked +process to make sure that 3rd party application code is only loaded after it is being +restricted within a sandbox. + +On Android, there is also this special process called "system_server". This single +process hosts a significant portion of system services, which controls how the +Android operating system and apps interact with each other. + +The Zygisk framework provides a way to allow developers to build modules and run custom +code before and after system_server and any app processes' specialization. +This enable developers to inject code and alter the behavior of system_server and app processes. + +Please note that modules will only be loaded after zygote has forked the child process. +THIS MEANS ALL OF YOUR CODE RUNS IN THE APP/SYSTEM_SERVER PROCESS, NOT THE ZYGOTE DAEMON! + +********************* +* Development Guide +********************* + +Define a class and inherit zygisk::ModuleBase to implement the functionality of your module. +Use the macro REGISTER_ZYGISK_MODULE(className) to register that class to Zygisk. + +Example code: + +static jint (*orig_logger_entry_max)(JNIEnv *env); +static jint my_logger_entry_max(JNIEnv *env) { return orig_logger_entry_max(env); } + +class ExampleModule : public zygisk::ModuleBase { +public: + void onLoad(zygisk::Api *api, JNIEnv *env) override { + this->api = api; + this->env = env; + } + void preAppSpecialize(zygisk::AppSpecializeArgs *args) override { + JNINativeMethod methods[] = { + { "logger_entry_max_payload_native", "()I", (void*) my_logger_entry_max }, + }; + api->hookJniNativeMethods(env, "android/util/Log", methods, 1); + *(void **) &orig_logger_entry_max = methods[0].fnPtr; + } +private: + zygisk::Api *api; + JNIEnv *env; +}; + +REGISTER_ZYGISK_MODULE(ExampleModule) + +----------------------------------------------------------------------------------------- + +Since your module class's code runs with either Zygote's privilege in pre[XXX]Specialize, +or runs in the sandbox of the target process in post[XXX]Specialize, the code in your class +never runs in a true superuser environment. + +If your module require access to superuser permissions, you can create and register +a root companion handler function. This function runs in a separate root companion +daemon process, and an Unix domain socket is provided to allow you to perform IPC between +your target process and the root companion process. + +Example code: + +static void example_handler(int socket) { ... } + +REGISTER_ZYGISK_COMPANION(example_handler) + +*/ + +namespace zygisk { + +struct Api; +struct AppSpecializeArgs; +struct ServerSpecializeArgs; + +class ModuleBase { +public: + + // This method is called as soon as the module is loaded into the target process. + // A Zygisk API handle will be passed as an argument. + virtual void onLoad([[maybe_unused]] Api *api, [[maybe_unused]] JNIEnv *env) {} + + // This method is called before the app process is specialized. + // At this point, the process just got forked from zygote, but no app specific specialization + // is applied. This means that the process does not have any sandbox restrictions and + // still runs with the same privilege of zygote. + // + // All the arguments that will be sent and used for app specialization is passed as a single + // AppSpecializeArgs object. You can read and overwrite these arguments to change how the app + // process will be specialized. + // + // If you need to run some operations as superuser, you can call Api::connectCompanion() to + // get a socket to do IPC calls with a root companion process. + // See Api::connectCompanion() for more info. + virtual void preAppSpecialize([[maybe_unused]] AppSpecializeArgs *args) {} + + // This method is called after the app process is specialized. + // At this point, the process has all sandbox restrictions enabled for this application. + // This means that this method runs with the same privilege of the app's own code. + virtual void postAppSpecialize([[maybe_unused]] const AppSpecializeArgs *args) {} + + // This method is called before the system server process is specialized. + // See preAppSpecialize(args) for more info. + virtual void preServerSpecialize([[maybe_unused]] ServerSpecializeArgs *args) {} + + // This method is called after the system server process is specialized. + // At this point, the process runs with the privilege of system_server. + virtual void postServerSpecialize([[maybe_unused]] const ServerSpecializeArgs *args) {} +}; + +struct AppSpecializeArgs { + // Required arguments. These arguments are guaranteed to exist on all Android versions. + jint &uid; + jint &gid; + jintArray &gids; + jint &runtime_flags; + jobjectArray &rlimits; + jint &mount_external; + jstring &se_info; + jstring &nice_name; + jstring &instruction_set; + jstring &app_data_dir; + + // Optional arguments. Please check whether the pointer is null before de-referencing + jintArray *const fds_to_ignore; + jboolean *const is_child_zygote; + jboolean *const is_top_app; + jobjectArray *const pkg_data_info_list; + jobjectArray *const whitelisted_data_info_list; + jboolean *const mount_data_dirs; + jboolean *const mount_storage_dirs; + jboolean *const mount_sysprop_overrides; + + AppSpecializeArgs() = delete; +}; + +struct ServerSpecializeArgs { + jint &uid; + jint &gid; + jintArray &gids; + jint &runtime_flags; + jlong &permitted_capabilities; + jlong &effective_capabilities; + + ServerSpecializeArgs() = delete; +}; + +namespace internal { +struct api_table; +template void entry_impl(api_table *, JNIEnv *); +} + +// These values are used in Api::setOption(Option) +enum Option : int { + // Force Magisk's denylist unmount routines to run on this process. + // + // Setting this option only makes sense in preAppSpecialize. + // The actual unmounting happens during app process specialization. + // + // Set this option to force all Magisk and modules' files to be unmounted from the + // mount namespace of the process, regardless of the denylist enforcement status. + FORCE_DENYLIST_UNMOUNT = 0, + + // When this option is set, your module's library will be dlclose-ed after post[XXX]Specialize. + // Be aware that after dlclose-ing your module, all of your code will be unmapped from memory. + // YOU MUST NOT ENABLE THIS OPTION AFTER HOOKING ANY FUNCTIONS IN THE PROCESS. + DLCLOSE_MODULE_LIBRARY = 1, +}; + +// Bit masks of the return value of Api::getFlags() +enum StateFlag : uint32_t { + // The user has granted root access to the current process + PROCESS_GRANTED_ROOT = (1u << 0), + + // The current process was added on the denylist + PROCESS_ON_DENYLIST = (1u << 1), +}; + +// All API methods will stop working after post[XXX]Specialize as Zygisk will be unloaded +// from the specialized process afterwards. +struct Api { + + // Connect to a root companion process and get a Unix domain socket for IPC. + // + // This API only works in the pre[XXX]Specialize methods due to SELinux restrictions. + // + // The pre[XXX]Specialize methods run with the same privilege of zygote. + // If you would like to do some operations with superuser permissions, register a handler + // function that would be called in the root process with REGISTER_ZYGISK_COMPANION(func). + // Another good use case for a companion process is that if you want to share some resources + // across multiple processes, hold the resources in the companion process and pass it over. + // + // The root companion process is ABI aware; that is, when calling this method from a 32-bit + // process, you will be connected to a 32-bit companion process, and vice versa for 64-bit. + // + // Returns a file descriptor to a socket that is connected to the socket passed to your + // module's companion request handler. Returns -1 if the connection attempt failed. + int connectCompanion(); + + // Get the file descriptor of the root folder of the current module. + // + // This API only works in the pre[XXX]Specialize methods. + // Accessing the directory returned is only possible in the pre[XXX]Specialize methods + // or in the root companion process (assuming that you sent the fd over the socket). + // Both restrictions are due to SELinux and UID. + // + // Module should also make sure zygote is allowed to read module dir (e.g. module dir has + // system_file context) due to SELinux restrictions on socket messages. + // + // Returns -1 if errors occurred. + int getModuleDir(); + + // Set various options for your module. + // Please note that this method accepts one single option at a time. + // Check zygisk::Option for the full list of options available. + void setOption(Option opt); + + // Get information about the current process. + // Returns bitwise-or'd zygisk::StateFlag values. + uint32_t getFlags(); + + // Exempt the provided file descriptor from being automatically closed. + // + // This API only make sense in preAppSpecialize; calling this method in any other situation + // is either a no-op (returns true) or an error (returns false). + // + // When false is returned, the provided file descriptor will eventually be closed by zygote. + bool exemptFd(int fd); + + // Hook JNI native methods for a class + // + // Lookup all registered JNI native methods and replace it with your own methods. + // The original function pointer will be saved in each JNINativeMethod's fnPtr. + // If no matching class, method name, or signature is found, that specific JNINativeMethod.fnPtr + // will be set to nullptr. + void hookJniNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *methods, int numMethods); + + // Hook functions in the PLT (Procedure Linkage Table) of ELFs loaded in memory. + // + // Parsing /proc/[PID]/maps will give you the memory map of a process. As an example: + // + //
+ // 56b4346000-56b4347000 r-xp 00002000 fe:00 235 /system/bin/app_process64 + // (More details: https://man7.org/linux/man-pages/man5/proc.5.html) + // + // The `dev` and `inode` pair uniquely identifies a file being mapped into memory. + // For matching ELFs loaded in memory, replace function `symbol` with `newFunc`. + // If `oldFunc` is not nullptr, the original function pointer will be saved to `oldFunc`. + void pltHookRegister(dev_t dev, ino_t inode, const char *symbol, void *newFunc, void **oldFunc); + + // Commit all the hooks that was previously registered. + // Returns false if an error occurred. + bool pltHookCommit(); + +private: + internal::api_table *tbl; + template friend void internal::entry_impl(internal::api_table *, JNIEnv *); +}; + +// Register a class as a Zygisk module + +#define REGISTER_ZYGISK_MODULE(clazz) \ +void zygisk_module_entry(zygisk::internal::api_table *table, JNIEnv *env) { \ + zygisk::internal::entry_impl(table, env); \ +} + +// Register a root companion request handler function for your module +// +// The function runs in a superuser daemon process and handles a root companion request from +// your module running in a target process. The function has to accept an integer value, +// which is a Unix domain socket that is connected to the target process. +// See Api::connectCompanion() for more info. +// +// NOTE: the function can run concurrently on multiple threads. +// Be aware of race conditions if you have globally shared resources. + +#define REGISTER_ZYGISK_COMPANION(func) \ +void zygisk_companion_entry(int client) { func(client); } + +/********************************************************* + * The following is internal ABI implementation detail. + * You do not have to understand what it is doing. + *********************************************************/ + +namespace internal { + +struct module_abi { + long api_version; + ModuleBase *impl; + + void (*preAppSpecialize)(ModuleBase *, AppSpecializeArgs *); + void (*postAppSpecialize)(ModuleBase *, const AppSpecializeArgs *); + void (*preServerSpecialize)(ModuleBase *, ServerSpecializeArgs *); + void (*postServerSpecialize)(ModuleBase *, const ServerSpecializeArgs *); + + module_abi(ModuleBase *module) : api_version(ZYGISK_API_VERSION), impl(module) { + preAppSpecialize = [](auto m, auto args) { m->preAppSpecialize(args); }; + postAppSpecialize = [](auto m, auto args) { m->postAppSpecialize(args); }; + preServerSpecialize = [](auto m, auto args) { m->preServerSpecialize(args); }; + postServerSpecialize = [](auto m, auto args) { m->postServerSpecialize(args); }; + } +}; + +struct api_table { + // Base + void *impl; + bool (*registerModule)(api_table *, module_abi *); + + void (*hookJniNativeMethods)(JNIEnv *, const char *, JNINativeMethod *, int); + void (*pltHookRegister)(dev_t, ino_t, const char *, void *, void **); + bool (*exemptFd)(int); + bool (*pltHookCommit)(); + int (*connectCompanion)(void * /* impl */); + void (*setOption)(void * /* impl */, Option); + int (*getModuleDir)(void * /* impl */); + uint32_t (*getFlags)(void * /* impl */); +}; + +template +void entry_impl(api_table *table, JNIEnv *env) { + static Api api; + api.tbl = table; + static T module; + ModuleBase *m = &module; + static module_abi abi(m); + if (!table->registerModule(table, &abi)) return; + m->onLoad(&api, env); +} + +} // namespace internal + +inline int Api::connectCompanion() { + return tbl->connectCompanion ? tbl->connectCompanion(tbl->impl) : -1; +} +inline int Api::getModuleDir() { + return tbl->getModuleDir ? tbl->getModuleDir(tbl->impl) : -1; +} +inline void Api::setOption(Option opt) { + if (tbl->setOption) tbl->setOption(tbl->impl, opt); +} +inline uint32_t Api::getFlags() { + return tbl->getFlags ? tbl->getFlags(tbl->impl) : 0; +} +inline bool Api::exemptFd(int fd) { + return tbl->exemptFd != nullptr && tbl->exemptFd(fd); +} +inline void Api::hookJniNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *methods, int numMethods) { + if (tbl->hookJniNativeMethods) tbl->hookJniNativeMethods(env, className, methods, numMethods); +} +inline void Api::pltHookRegister(dev_t dev, ino_t inode, const char *symbol, void *newFunc, void **oldFunc) { + if (tbl->pltHookRegister) tbl->pltHookRegister(dev, inode, symbol, newFunc, oldFunc); +} +inline bool Api::pltHookCommit() { + return tbl->pltHookCommit != nullptr && tbl->pltHookCommit(); +} + +} // namespace zygisk + +extern "C" { + +[[gnu::visibility("default"), maybe_unused]] +void zygisk_module_entry(zygisk::internal::api_table *, JNIEnv *); + +[[gnu::visibility("default"), maybe_unused]] +void zygisk_companion_entry(int); + +} // extern "C" diff --git a/package.json b/package.json index 28db9b4..7ea6c69 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,7 @@ "go:test": "cd golang && go vet ./... && go test ./...", "go:build": "node dev/build-wght.mjs", "go:build:local": "cd golang && go build -o /tmp/fontmm-wght ./cmd/fontmm-wght", + "zygisk:build": "node dev/build-zygisk.mjs", "sha256": "node dev/gen-sha256.mjs", "sync:fonts-xml": "node dev/sync-fonts-xml.mjs", "empty-font": "node dev/empty-font.mjs" diff --git a/src/customize.sh b/src/customize.sh index 7fe926a..883edf4 100644 --- a/src/customize.sh +++ b/src/customize.sh @@ -173,49 +173,60 @@ CONFIRM_RISK() { fi } -CONFIRM_FONTLOADER_RISK() { - local reason="$1" - echo - log "警告: $reason" - log "未安装或版本过低的 FontLoader 可能导致开机卡死、字体渲染错误或系统异常。" - log "请按音量上键确认继续安装, 按音量下键取消安装。" - if [ "$(btn)" = "1" ]; then - log_err "用户取消安装" - fi -} +# ---------- 判断 Zygisk 环境 ---------- +# 模块自带字体预加载 (zygisk/arm64-v8a.so), 但 Zygisk 框架本身需要由 Root 管理器 +# 或独立的 Zygisk 提供者 (Magisk 内置 Zygisk / Zygisk Next / ReZygisk 等) 提供。 +# 缺少时模块仍可安装, 只是被 DenyList 的应用可能字体异常, 故仅提示不阻断。 +CHECK_ZYGISK_ENV() { + local ok=0 -# ---------- 判断 FontLoader ---------- -CHECK_FONTLOADER() { - local fontloader_moddir="/data/adb/modules/fontloader" - local fontloader_github="https://github.com/KernelSU-Modules-Repo/fontloader/releases" - - if [ ! -d "$fontloader_moddir" ]; then - log "注意: 你还没安装 FontLoader" - log "前往 $fontloader_github 安装 FontLoader" - CONFIRM_FONTLOADER_RISK "当前设备未安装 FontLoader。" - return 0 + # Magisk 内置 Zygisk: 以是否开启 Zygisk 为准 (magisk --sqlite 查询数据库开关) + if [ -f /data/adb/magisk/magisk ]; then + local zg="" + zg="$(/data/adb/magisk/magisk --sqlite "SELECT value FROM settings WHERE key='zygisk';" 2>/dev/null | tr -d '\r')" + if [ "$zg" = "1" ]; then + log_succ "Magisk 内置 Zygisk 已启用" + ok=1 + fi fi - local prop_file="$fontloader_moddir/module.prop" - local version_code="" - if [ -f "$prop_file" ]; then - version_code="$(sed -n 's/^versionCode=//p' "$prop_file")" - fi - version_code="$(printf '%s' "$version_code" | tr -cd '0-9')" + # 独立 Zygisk 提供者模块。各实现的内部布局不同, 逐一识别 (任一命中即算可用): + # - Zygisk Next / Magisk 兼容第三方: 自带 zygisk/ 目录 + # - ReZygisk: lib64/libzygisk.so + bin/zygisk-ptrace64 (无 zygisk/ 目录) + # - Zygisk Next 早期版本: bin/zygiskd64 + if [ "$ok" -eq 0 ]; then + local dir="" name="" f="" + for dir in /data/adb/modules/*; do + [ -d "$dir" ] || continue + name="$(basename "$dir")" + [ "$name" = "FontMM" ] && continue + [ -f "$dir/disable" ] && continue - if [ -z "$version_code" ]; then - log "注意: 无法读取 FontLoader 版本号, 建议更新到最新版" - log "前往 $fontloader_github 更新 FontLoader" - CONFIRM_FONTLOADER_RISK "无法确认 FontLoader 版本。" - return 0 + local hit="" + if [ -d "$dir/zygisk" ]; then + hit="zygisk/" + else + for f in "$dir"/lib64/libzygisk.so "$dir"/lib/libzygisk.so \ + "$dir"/bin/zygisk-ptrace64 "$dir"/bin/zygiskd64; do + if [ -f "$f" ]; then + hit="${f#"$dir"/}" + break + fi + done + fi + + [ -z "$hit" ] && continue + log_succ "检测到 Zygisk 提供者: $name ($hit)" + ok=1 + break + done fi - if [ "$version_code" -lt 33 ] 2>/dev/null; then - log "注意: 你的 FontLoader 版本过低, 建议更新到 v1.2.3+" - log "前往 $fontloader_github 更新 FontLoader" - CONFIRM_FONTLOADER_RISK "当前 FontLoader 版本低于 v1.2.3。" - else - log_succ "FontLoader 版本正常" + if [ "$ok" -eq 0 ]; then + log_warn "未检测到可用的 Zygisk 环境" + log "模块的字体预加载依赖 Zygisk, 缺少时被卸载模块的应用可能字体异常" + log "请启用 Magisk 内置 Zygisk, 或安装 Zygisk Next / ReZygisk" + CONFIRM_RISK "未检测到 Zygisk 环境" "字体预加载不会生效, 被 DenyList 的应用可能字体显示异常" fi } @@ -255,13 +266,72 @@ system/system_ext/etc/fonts_ule.xml" fi } +# ---------- 判断 FontLoader ---------- +# 本模块已内置字体预加载 (zygisk/arm64-v8a.so), 与外部 FontLoader 模块功能重叠。 +# 两者同时启用会重复预热、并可能互相干扰, 因此检测到旧 FontLoader 时建议禁用它。 +# 禁用方式: 在其模块目录放置 disable 文件 (模块的通用停用约定, 重启后生效), +# 不删除其数据, 用户可随时移除该文件恢复。 +DISABLE_OLD_FONTLOADER() { + local found="" + local hit="" + + # 按目录名候选 + 内容特征双重识别: + # - RikkaW/FontLoader 原版: 模块目录名多为 fontloader + # - JingMatrix/FontLoader: build.gradle 中 moduleId = 'font-loader' + # - 兜底: 扫描各模块 module.prop 描述中明确含 FontLoader 字样者 + local names="fontloader font-loader font_loader" + + local name="" dir="" + for name in $names; do + dir="/data/adb/modules/$name" + if [ -d "$dir" ]; then + hit="$name" + break + fi + done + + # 目录名未命中时, 扫描其它模块的 module.prop 描述 + if [ -z "$hit" ]; then + local d="" prop="" + for d in /data/adb/modules/*; do + [ -d "$d" ] || continue + [ "$(basename "$d")" = "FontMM" ] && continue + prop="$d/module.prop" + [ -f "$prop" ] || continue + # 只认明确声明为 FontLoader 的模块, 避免误伤其他模块 + if grep -qiE '^description=.*font.?loader' "$prop" 2>/dev/null; then + hit="$(basename "$d")" + break + fi + done + fi + + if [ -n "$hit" ]; then + dir="/data/adb/modules/$hit" + if [ -f "$dir/disable" ]; then + log "外部 FontLoader ($hit) 已处于停用状态" + elif touch "$dir/disable" 2>/dev/null; then + log_succ "已停用外部 FontLoader 模块: $hit" + found="$hit" + else + log_warn "检测到外部 FontLoader ($hit) 但无法停用, 建议手动在管理器中关闭" + found="$hit" + fi + fi + + if [ -n "$found" ]; then + log "本模块已内置字体预加载, 无需外部 FontLoader; 重启后以本模块为准" + fi +} + # ---------- 主流程 ---------- MAIN() { CHECK_COLOROS if ! CHECK_META_MODULE; then log_err "元模块检查不通过" fi - CHECK_FONTLOADER + CHECK_ZYGISK_ENV + DISABLE_OLD_FONTLOADER echo && log "开始准备字体..." DETECT_UPDATE_MODE @@ -270,6 +340,11 @@ MAIN() { # 同步派生字体配置 (设备 XML 扫描 + fontmm-wght -sync) SYNC_FONT_XMLS + # 校验内置的 Zygisk 字体预加载模块存在 (缺失则 DenyList 应用可能字体异常) + if [ ! -f "$MODPATH/zygisk/arm64-v8a.so" ]; then + log_warn "缺少 zygisk/arm64-v8a.so, 字体预加载不可用 (DenyList 应用可能字体异常)" + fi + # 备份模块内嵌的补充字库 Emoji 字体, 供用户清除 emoji 槽位时恢复 if [ -f "$MODPATH/system/fonts/NotoColorEmoji.ttf" ] && [ ! -f "$MODPATH/backup/NotoColorEmoji.ttf" ]; then mkdir -p "$MODPATH/backup"