fix: 适配安卓 16KB 内存页并在启动轮询校验版本号

- Prisma 引擎按单机版 minSdk 26 编译,传入 -Wl,-z,max-page-size=16384 并校验 LOAD 段对齐
- 打包运行时解析 ELF,所有内置 .so 的 LOAD 段不满足 16KB 时构建失败
- 启动轮询只在 /api/health 返回当前目标 version 时判定就绪,避免误连旧服务端
Refs: https://github.com/margrop/wrong-notebook/issues/122
This commit is contained in:
margrop
2026-12-04 21:03:35 +08:00
parent 2978133467
commit 0664cf8f3c
9 changed files with 127 additions and 7 deletions

View File

@@ -234,7 +234,7 @@ npm install -g wrong-notebook
wrong-notebook --port 3000
```
The npm package needs Node.js 22.15 or later and stores data in `~/.wrong-notebook` by default. The desktop app listens on `127.0.0.1` only; the fnOS package needs Node.js v24 from the fnOS app center and is served on port 39300. The standalone Android app includes the server and works right after installation. Data stays on the device (uninstalling the app deletes it, and it is excluded from Android system backup because it contains API keys, so export a backup in Settings before uninstalling or switching phones); on first launch it opens the one-time setup page where you create the admin account. It needs a 64-bit ARM device with Android 8.0 or later. Both Android editions render the interface with the system Android System WebView, which must be version 111 or later; when it is outdated a notice at the top of the page asks you to update it (on phones without Google Play, update it from the phone's own app store). The Android client does not include the server: on first launch, enter the address of a deployed server (for example `http://192.168.1.10:3000`); you can change the server under Settings → About. It needs Android 7.0 or later. Both apps support taking photos for upload, saving exported files and system printing, and can be installed side by side.
The npm package needs Node.js 22.15 or later and stores data in `~/.wrong-notebook` by default. The desktop app listens on `127.0.0.1` only; the fnOS package needs Node.js v24 from the fnOS app center and is served on port 39300. The standalone Android app includes the server and works right after installation. Data stays on the device (uninstalling the app deletes it, and it is excluded from Android system backup because it contains API keys, so export a backup in Settings before uninstalling or switching phones); on first launch it opens the one-time setup page where you create the admin account. It needs a 64-bit ARM device with Android 8.0 or later and supports Android 15+ devices with 16 KB memory pages. Both Android editions render the interface with the system Android System WebView, which must be version 111 or later; when it is outdated a notice at the top of the page asks you to update it (on phones without Google Play, update it from the phone's own app store). The Android client does not include the server: on first launch, enter the address of a deployed server (for example `http://192.168.1.10:3000`); you can change the server under Settings → About. It needs Android 7.0 or later. Both apps support taking photos for upload, saving exported files and system printing, and can be installed side by side.
Data directories, default accounts and local builds are described in [INSTALL_PACKAGES.md](doc/INSTALL_PACKAGES.md) (Chinese).

View File

@@ -90,7 +90,7 @@ wrong-notebook --port 3000 --host 0.0.0.0 --data-dir ~/.wrong-notebook
| 服务端 | 内置,在手机上运行 | 需先用 Docker 或其他安装包部署 |
| 数据 | 保存在本机,卸载 App 时删除 | 保存在服务器 |
| 安装包大小 | 约 75MB | 约 2MB |
| 系统要求 | Android 8.0 及以上,64 位 ARM(arm64-v8a) | Android 7.0 及以上 |
| 系统要求 | Android 8.0 及以上,64 位 ARM(arm64-v8a),已适配 Android 15+ 的 16KB 内存页设备 | Android 7.0 及以上 |
| 系统 WebView | Android System WebView 111 及以上,过旧时页面顶部提示升级 | 同左 |
| 包名 | `com.margrop.wrongnotebook.standalone` | `com.margrop.wrongnotebook` |
@@ -152,7 +152,7 @@ PDF 导入的浏览器端解析需要 pdfjs-dist 的 CMap 与标准字体数据
安卓 APK 构建需要 JDK 17、Android SDK(`ANDROID_HOME`,compileSdk 35、build-tools 35.0.0)和 Gradle 8.11(PATH 中的 `gradle`,或用环境变量 `GRADLE` 指定)。客户端版不依赖 `bundle`;单机版还需要:
- `dist/bundle`:与其他安装包相同的服务端。
- 安卓 Prisma 引擎:Prisma 不提供安卓版本,`build-android-prisma-engines.sh` 按项目安装的 Prisma 版本下载对应提交的 prisma-engines 源码,用 Android NDK(`ANDROID_NDK_HOME`)和 rustup 交叉编译查询引擎与迁移引擎,约需 15–30 分钟。输出目录默认 `dist/android-prisma-engines`,可用 `ANDROID_PRISMA_ENGINES_DIR` 指定。
- 安卓 Prisma 引擎:Prisma 不提供安卓版本,`build-android-prisma-engines.sh` 按项目安装的 Prisma 版本下载对应提交的 prisma-engines 源码,用 Android NDK(`ANDROID_NDK_HOME`)和 rustup 交叉编译查询引擎与迁移引擎,约需 15–30 分钟。编译按单机版 `minSdk 26` 使用 api 26 工具链,并传入 `-Wl,-z,max-page-size=16384` 让 ELF LOAD 段满足 Android 15+ 的 16KB 页要求;`scripts/package/android-runtime.mjs` 组装运行时时会解析 ELF 并校验所有内置 `.so` 的 LOAD 段对齐,不满足时构建失败。输出目录默认 `dist/android-prisma-engines`,可用 `ANDROID_PRISMA_ENGINES_DIR` 指定。
- `patchelf`(可用 `PATCHELF` 指定路径)和 `zip`。
单机版内置的 Node.js 取自 [Termux](https://termux.dev) 软件源的 `nodejs`(当前 26.x,依赖 libicu 79;`nodejs-lts` 24.22 仍依赖 libicu 78,与软件源已更新的 libicu 79.1 不兼容)及其依赖库(构建时按软件源索引校验 SHA256,可用 `TERMUX_MIRROR` 指定镜像)。安卓只允许执行 `nativeLibraryDir` 中的程序,因此 Node.js、依赖库和引擎都以 `lib*.so` 的形式放进 `jniLibs/arm64-v8a`,由 `scripts/package/android-runtime.mjs` 改名并用 patchelf 改写依赖;服务端打包为 `assets/server.zip`,首次启动时解压。各组件的许可证随 APK 放在 `assets/licenses/`。网页端按需加载的 HEIC/HEIF 转换组件(heic-to 及其包含的 libheif、libde265)的第三方说明与许可证位于 `public/third-party-licenses/heic-to/`,随服务端 `public/` 目录进入 Docker 镜像、npm 包、桌面版、飞牛OS 安装包和单机版的 `server.zip`。

View File

@@ -250,4 +250,4 @@ xattr -cr /Applications/WrongNotebook.app
codesign --force --deep --sign - /Applications/WrongNotebook.app
```
安卓单机版在手机上运行服务端,无需另行部署,需要 Android 8.0 及以上的 64 位 ARM 设备;两个安卓版本都需要 Android System WebView 111 及以上;安卓客户端版只是连接服务器的外壳,需要先用上面任一方式部署服务端。详细说明见 [INSTALL_PACKAGES.md](https://github.com/margrop/wrong-notebook/blob/main/doc/INSTALL_PACKAGES.md)。
安卓单机版在手机上运行服务端,无需另行部署,需要 Android 8.0 及以上的 64 位 ARM 设备,已适配 Android 15+ 的 16KB 内存页;两个安卓版本都需要 Android System WebView 111 及以上;安卓客户端版只是连接服务器的外壳,需要先用上面任一方式部署服务端。详细说明见 [INSTALL_PACKAGES.md](https://github.com/margrop/wrong-notebook/blob/main/doc/INSTALL_PACKAGES.md)。

View File

@@ -250,4 +250,4 @@ xattr -cr /Applications/WrongNotebook.app
codesign --force --deep --sign - /Applications/WrongNotebook.app
```
The Android standalone edition runs the server on the phone with no separate deployment and needs a 64-bit ARM device on Android 8.0 or later; both Android editions need Android System WebView 111 or later; the Android client edition is only a shell that connects to a server, which must first be deployed with one of the methods above. See [INSTALL_PACKAGES.md](https://github.com/margrop/wrong-notebook/blob/main/doc/INSTALL_PACKAGES.md) for details.
The Android standalone edition runs the server on the phone with no separate deployment and needs a 64-bit ARM device on Android 8.0 or later and supports Android 15+ devices with 16 KB memory pages; both Android editions need Android System WebView 111 or later; the Android client edition is only a shell that connects to a server, which must first be deployed with one of the methods above. See [INSTALL_PACKAGES.md](https://github.com/margrop/wrong-notebook/blob/main/doc/INSTALL_PACKAGES.md) for details.

View File

@@ -107,7 +107,8 @@ final class LocalServer {
if (!isAlive(process)) {
throw new IOException("Server exited (" + process.exitValue() + ")\n" + tail(log));
}
if (healthyVersion() != null) return;
// 升级重启时旧进程可能仍在响应;只认当前目标版本的 /api/health
if (version.equals(healthyVersion())) return;
try {
Thread.sleep(300);
} catch (InterruptedException e) {

View File

@@ -14,6 +14,7 @@ export function parseTermuxPackages(text: string): Map<string, TermuxPackage>;
export function resolveTermuxDependencies(index: Map<string, TermuxPackage>, name: string): TermuxPackage[];
export function compareDebianVersions(left: string, right: string): number;
export function androidLibraryName(soname: string): string;
export function loadSegmentAlignments(buffer: Buffer): number[];
export function extractDebData(buffer: Buffer): { name: string; data: Buffer };
export function buildAndroidRuntime(options: {
bundleDir: string;

View File

@@ -113,6 +113,28 @@ export function androidLibraryName(soname) {
return `${m[1]}${m[2].replace(/\./g, '_')}.so`;
}
/**
* 读取 ELF64 小端文件中 PT_LOAD 段的 p_align,用于校验 Android 15+ 的 16KB 页对齐。
* 仅支持 arm64 的 ELF64;返回各 LOAD 段的对齐值。
*/
export function loadSegmentAlignments(buffer) {
if (buffer.length < 64 || buffer[0] !== 0x7f || buffer[1] !== 0x45 || buffer[2] !== 0x4c || buffer[3] !== 0x46) {
throw new Error('不是有效的 ELF 文件');
}
if (buffer[4] !== 2 || buffer[5] !== 1) throw new Error('仅支持 ELF64 小端文件');
const phoff = Number(buffer.readBigUInt64LE(32));
const phentsize = buffer.readUInt16LE(54);
const phnum = buffer.readUInt16LE(56);
if (phentsize < 56) throw new Error(`程序头尺寸异常:${phentsize}`);
const alignments = [];
for (let i = 0; i < phnum; i++) {
const offset = phoff + i * phentsize;
if (offset + 56 > buffer.length) throw new Error('程序头超出文件范围');
if (buffer.readUInt32LE(offset) === 1) alignments.push(Number(buffer.readBigUInt64LE(offset + 48)));
}
return alignments;
}
/** 解析 deb(ar 归档),返回其中 data.tar.* 的文件名和内容 */
export function extractDebData(buffer) {
if (buffer.subarray(0, 8).toString('latin1') !== '!<arch>\n') throw new Error('不是有效的 deb 文件');
@@ -236,6 +258,20 @@ export async function buildAndroidRuntime({ bundleDir, enginesDir, outDir, workD
fs.copyFileSync(path.join(enginesDir, 'libquery_engine.so'), path.join(jniDir, 'libquery_engine.so'));
fs.copyFileSync(path.join(enginesDir, 'schema-engine'), path.join(jniDir, 'libschema_engine.so'));
// Android 15+ 的 16KB 页设备要求所有 LOAD 段 p_align ≥ 0x4000;
// Prisma 引擎由本脚本的链接参数保证,Termux 依赖库也一并校验
const MIN_LOAD_ALIGN = 16384;
for (const name of fs.readdirSync(jniDir)) {
if (!name.endsWith('.so')) continue;
const alignments = loadSegmentAlignments(fs.readFileSync(path.join(jniDir, name)));
const smallest = Math.min(...alignments);
if (!alignments.length || smallest < MIN_LOAD_ALIGN) {
throw new Error(`${name} 的 ELF LOAD 段对齐 ${`0x${smallest.toString(16)}`} 小于 16KB,`
+ 'Android 15+ 的 16KB 页设备无法加载');
}
}
log('jniLibs 中的 ELF LOAD 段均满足 16KB(0x4000)对齐');
for (const pkg of Object.keys(versions)) {
const docDir = path.join(prefix, 'share', 'doc', pkg);
if (!fs.existsSync(docDir)) continue;

View File

@@ -21,7 +21,8 @@ if [ -z "$ndk" ] || [ ! -d "$ndk/toolchains/llvm/prebuilt" ]; then
fi
commit="$(node -p "require('$root/node_modules/@prisma/engines-version/package.json').prisma.enginesVersion")"
target=aarch64-linux-android
api=24
# 与单机版 minSdk 26 对齐;Android 15+ 的 16KB 页设备要求 LOAD 段按 16KB 对齐
api=26
work="${PRISMA_ENGINES_WORK_DIR:-$(mktemp -d "${TMPDIR:-/tmp}/prisma-engines.XXXXXX")}"
mkdir -p "$work" "$out"
@@ -50,6 +51,8 @@ export RANLIB="$bin/llvm-ranlib"
export CARGO_TARGET_AARCH64_LINUX_ANDROID_LINKER="$bin/$target$api-clang"
export GIT_HASH="$commit"
export CARGO_TARGET_DIR="$work/target"
# Android 15+ 的 16KB 页设备要求 ELF LOAD 段 p_align ≥ 0x4000,否则加载 .so 直接失败
export RUSTFLAGS="${RUSTFLAGS:+$RUSTFLAGS }-C link-arg=-Wl,-z,max-page-size=16384"
cd "$src"
echo "[engines] 编译查询引擎和迁移引擎(Rust ${toolchain},${target})"
@@ -60,4 +63,14 @@ cp "$CARGO_TARGET_DIR/$target/release/libquery_engine.so" "$out/libquery_engine.
cp "$CARGO_TARGET_DIR/$target/release/schema-engine" "$out/schema-engine"
cp "$src/LICENSE" "$out/LICENSE"
echo "$commit" > "$out/COMMIT"
# 打包前先确认 LOAD 段对齐,避免在 16KB 页设备上启动时才暴露
for file in "$out/libquery_engine.so" "$out/schema-engine"; do
for value in "$("$bin/llvm-readelf" -lW "$file" | awk '$1 == "LOAD" { print $NF }')"; do
if (( value < 0x4000 )); then
echo "[engines] $(basename "$file") 的 LOAD 段对齐 $value 小于 16KB(0x4000)" >&2
exit 1
fi
done
done
echo "[engines] 已输出到 $out"

View File

@@ -0,0 +1,69 @@
// @vitest-environment node
/**
* 安卓单机版 16KB 页对齐:Prisma 引擎交叉编译必须按 api 26 链接并传入
* -Wl,-z,max-page-size=16384;打包阶段解析 ELF LOAD 段确认 p_align ≥ 0x4000。
* 启动轮询只认当前目标版本的 /api/health。
*/
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { loadSegmentAlignments } from "../../../scripts/package/android-runtime.mjs";
const root = process.cwd();
const buildScript = readFileSync(join(root, "scripts/package/build-android-prisma-engines.sh"), "utf8");
const runtimeScript = readFileSync(join(root, "scripts/package/android-runtime.mjs"), "utf8");
const localServer = readFileSync(
join(root, "packaging/android/app/src/main/java/com/margrop/wrongnotebook/LocalServer.java"),
"utf8",
);
/** 构造最小的 ELF64 小端文件,每个 LOAD 段使用给定 p_align */
function elfWithLoadAlignments(alignments: number[]): Buffer {
const phoff = 64;
const phentsize = 56;
const buffer = Buffer.alloc(phoff + phentsize * alignments.length);
buffer[0] = 0x7f;
buffer[1] = 0x45;
buffer[2] = 0x4c;
buffer[3] = 0x46;
buffer[4] = 2;
buffer[5] = 1;
buffer.writeBigUInt64LE(BigInt(phoff), 32);
buffer.writeUInt16LE(phentsize, 54);
buffer.writeUInt16LE(alignments.length, 56);
alignments.forEach((alignment, index) => {
const offset = phoff + index * phentsize;
buffer.writeUInt32LE(1, offset);
buffer.writeBigUInt64LE(BigInt(alignment), offset + 48);
});
return buffer;
}
describe("安卓 Prisma 引擎 16KB 页对齐", () => {
it("交叉编译按单机版 minSdk 26 并传入 16KB 链接参数", () => {
expect(buildScript).toContain("api=26");
expect(buildScript).toContain("max-page-size=16384");
expect(buildScript).toContain("llvm-readelf");
});
it("解析 ELF64 LOAD 段对齐值", () => {
expect(loadSegmentAlignments(elfWithLoadAlignments([0x4000, 0x4000]))).toEqual([0x4000, 0x4000]);
expect(loadSegmentAlignments(elfWithLoadAlignments([0x1000, 0x10000]))).toEqual([0x1000, 0x10000]);
});
it("打包阶段校验所有内置 .so 的 LOAD 段不小于 0x4000", () => {
expect(runtimeScript).toContain("MIN_LOAD_ALIGN = 16384");
expect(runtimeScript).toContain("smallest < MIN_LOAD_ALIGN");
expect(runtimeScript).toContain("16KB 页设备无法加载");
});
});
describe("安卓启动轮询版本校验", () => {
it("只在 /api/health 返回当前目标 version 时判定就绪", () => {
const start = localServer.indexOf("static synchronized void ensureRunning(");
expect(start).toBeGreaterThanOrEqual(0);
const body = localServer.slice(start, localServer.indexOf("\n }", start));
expect(body).toContain("if (version.equals(healthyVersion())) return;");
expect(body).not.toContain("if (healthyVersion() != null) return;");
});
});