diff --git a/.gitignore b/.gitignore index 342ee1e..385d9b6 100644 --- a/.gitignore +++ b/.gitignore @@ -45,3 +45,8 @@ app.*.map.json /android/app/release # Widget Preview related .widget_preview/ + +# proot 源码/依赖/构建产物(用 tool/build-proot.ps1 重新获取与生成;成品已提交在 jniLibs 与 assets) +proot-source/ +build_proot_deps/ +build_proot_out/ diff --git a/CONTAINER_FIX_SUMMARY.md b/CONTAINER_FIX_SUMMARY.md index 766dbdd..852f674 100644 --- a/CONTAINER_FIX_SUMMARY.md +++ b/CONTAINER_FIX_SUMMARY.md @@ -118,4 +118,146 @@ arm64 上的 `poll/select/pipe/dup2`(该架构无这些 syscall)。 - **验收基准用 arm64 真机**;模拟器只用于 UI 迭代。 - **MIUI 设备**(如 Redmi K60)`adb install` 会被拦(`INSTALL_FAILED_USER_RESTRICTED`),需手动安装或开启开发者选项里的「USB 安装」;OnePlus / 原生 Android 无此限制。 -- 若将来需要 `--sysvipc`/完整 uname 伪装,必须改用 Termux 的 proot fork(`github.com/termux/proot`,带 `PROOT_WITH_LIBANDROID_SHMEM`)重新编译。 +- `/data/local/tmp` 下**不能执行**二进制(SELinux `execute` denied)——测试用的 proot/shim 必须放到应用数据目录。 + +--- + +## 八、proot 重建(2026-09-13:App 已内置新 proot) + +### 为什么重建 + +原来的 `jniLibs/*/libproot.so` 是 **termux/proot fork @ `dcc74e9b`(2018-12-05,UserLAnd 那条线)**, +NDK clang 7.0.2 构建、loader 内嵌、未编 libandroid-shmem(无 `--sysvipc`)。 +相对当前上游 tag **`v5.1.107.92` 落后 166 个提交且已分叉**(缺 f2fs、l2s、SIGSYS、seccomp 等一批 Android 修复)。 + +### 怎么重建(本机无 make/sh/awk ⇒ PowerShell 复刻 GNUmakefile) + +| 项目 | 内容 | +|---|---| +| 源码 | `git clone --depth 1 --branch v5.1.107.92 https://github.com/termux/proot.git proot-source` | +| talloc | 头文件取自稀疏克隆的 samba(`build_proot_deps/samba/lib/talloc/talloc.h`);`libtalloc.so` 沿用仓库现有(SONAME 匹配) | +| 脚本 | `tools/build/build-proot.ps1`:架构宏探测(clang -E -dM)→ `build.h` → 66 个目标文件 → loader 编译 + `objcopy` 内嵌 → POKEDATA `loader-info.c` → 链接单个 `.so` | +| 关键参数 | `-DARG_MAX=131072`;**不设** `PROOT_UNBUNDLE_LOADER`(loader 内嵌);API 24(`getifaddrs`);**关闭 `HAVE_PROCESS_VM`**(与旧二进制一致,走 POKEDATA 路径,规避 Android 策略风险) | +| 产物 | `jniLibs/arm64-v8a/libproot.so` **257712 B**、`jniLibs/x86_64/libproot.so` **272672 B**(旧文件备份在 `build_proot_out/backup/`) | +| 新增能力 | `--sysvipc`(需配 libandroid-shmem 才能真正使用,暂未启用)、`--change-id`、f2fs-bug 修复 | + +### 必须配套的 shim 改动(实测得出) + +新版把 `link2symlink.c` **重写(+838 行)**、`fake_id0/helper_functions.c` **删掉 84 行**,于是 apk 的 +`fchownat(dirfd, ".apk.", 0, 0, 0)` 也会解析 l2s 隐藏替身 → `Failed to set ownership`。 +⇒ shim 新增 **`fchownat` 的 `AT_SYMLINK_NOFOLLOW` 重试**(与 `utimensat` 同套路;musl 的 `chown/lchown/fchownat` 都走 `SYS_fchownat`)。 + +对照矩阵(真机 arm64,`apk add tzdata`): + +| 组合 | 结果 | +|---|---| +| 旧 proot + 旧 shim | ✅ rc=0(基线) | +| 旧 proot 无 shim | ❌ `Failed to preserve modification time` | +| 新 proot + 旧 shim | ❌ **`Failed to set ownership`** | +| **新 proot + 新 shim(含 fchownat)** | ✅ **rc=0,无 broken 标记** | +| 新 proot 不加 `--link2symlink` | ❌ `failed to rename .apk.`(**l2s 仍必须保留**) | + +shim 体积:arm64 2936 → **3088 B**;x86_64 11112 → **11168 B**。 + +### 验证状态 + +| 项目 | 状态 | +|---|---| +| 双架构编译 | ✅ | +| arm64 真机(容器 + `apk update/add tzdata/tree` 全流程) | ✅ | +| x86_64 运行时 | ⏳ 待模拟器在线(产物已就绪,源码/参数与 arm64 同源) | +| 回滚方式 | 用 `build_proot_out/backup/*` 覆盖回 `jniLibs/*/libproot.so`(或 `git checkout` 对应文件) | + +--- + +## 九、启用 SysV IPC(`--sysvipc`,2026-09-13) + +### 它是什么 + +**System V IPC**:共享内存 `shmget/shmat`、信号量 `semget/semop`、消息队列 `msgget/msgsnd` +(`ipcs` 命令列的就是它们)。数据库(PostgreSQL 等)、部分老工具与科学计算依赖它。 +**Android 的 app seccomp 策略把这套调用全部返回 ENOSYS**,因此 PRoot 提供 `--sysvipc` +在容器内用用户态模拟(共享内存靠 ashmem/memfd 支撑)。 + +### 实测(真机 arm64,probe6 裸 syscall) + +| 探针项 | 不开 `--sysvipc` | 开 `--sysvipc` | +|---|---|---| +| `shmget(IPC_PRIVATE)` / `shmat` / `shmctl` | ENOSYS | ✅ 成功 | +| `shmget(key=0x1234)`(命名 key)/ 同 key 复用 | ENOSYS | ✅ 同一段(跨进程共享语义正确) | +| `semget` / `msgget` | ENOSYS | ✅ 成功 | +| 容器基本 / `apk update` / `apk add tzdata` / broken 标记 | ✅ 正常 | ✅ **依然正常(0/0/0)** | +| `/dev/shm` 读写、`whoami/ls/pipe/apk info/ps` | ✅ | ✅ | + +⇒ **不开时与旧行为逐项一致(证明重编中立),开了无负面影响。** + +### 构建(`tools/build/build-shmem.ps1`) + +| 项目 | 内容 | +|---|---| +| 源码 | `git clone --depth 1 https://github.com/termux/libandroid-shmem.git` | +| 本地补丁 | `tools/patches/libandroid-shmem-runtime-ashmem.patch`:把上游的**编译期**后端选择(`__ANDROID_API__ >= 26`)改成**运行时** `dlopen("libandroid.so")` + `dlsym(ASharedMemory_*)`,拿不到再回退 `/dev/ashmem` | +| 为什么需要补丁 | 实测 Android 16 上 `open("/dev/ashmem", O_RDWR)` = **EACCES**(应用进程被拒),而 `ASharedMemory_create()` = 4 ✅(memfd 支撑)。不补丁则 `shmget` 返回 EACCES;改成 API 26 编译又会要求设备 ≥26 | +| 其他参数 | `-D_PATH_TMP="/data/data//cache/"`(上游引用了 bionic 未定义的 `_PATH_TMP`,它是命名 key 的 symlink 存放处;applicationId 由脚本从 `build.gradle.kts` 读取);`-Wno-implicit-function-declaration`(上游漏 ``) | +| 产物 | `jniLibs/{arm64-v8a,x86_64}/libandroid-shmem.so`(21976 / 21128 B) | + +### 启用后的依赖关系(重要) + +`jniLibs/*/libproot.so` 现在是 **shmem 版**(258432 / 273424 B),其 `NEEDED` 含 +`libandroid-shmem.so` ⇒ **必须一起打包**,否则 proot 无法启动。启动参数在 +`lib/services/distro_manager.dart` 中新增了 `--sysvipc`。 + +回滚:`build_proot_out/backup/*preshmem-*` 是本次之前的非 shmem 版 proot;去掉 +`--sysvipc` 一行即可退回旧行为(此时 libandroid-shmem.so 仍会被打包但不被使用)。 + +--- + +## 十、本轮最终形态(2026-09-13 收尾总结) + +### 1. 仓库里现在是什么 + +| 产物 | 说明 | +|---|---| +| `jniLibs/arm64-v8a/libproot.so` **259696 B** / `x86_64` **274800 B** | `termux/proot` **v5.1.107.92** + 本地补丁,**loader 内嵌**(单个自包含 .so) | +| `jniLibs/*/libandroid-shmem.so` | `--sysvipc` 的共享内存后端(运行时 ashmem/ASharedMemory 双路径) | +| `jniLibs/*/libtalloc.so` | proot 依赖(沿用原有) | +| `assets/shims/arm64-v8a` **3088 B** / `x86_64` **11488 B** | freestanding shim:`utimensat`/`fchownat`(l2s 硬链接兜底);x86_64 另含 `poll/select/pipe/dup2/fork/vfork` 与 `getaddrinfo` | +| `tools/build/build-proot.ps1`、`tools/build/build-shmem.ps1`、`tools/patches/*` | 可复现构建链(用法见 `tools/build/README.md`) | +| `tools/container-selfcheck/` | 探针 `probe3/4/5/6/8` + 一键验收 + adb 跑手 + README | +| `lib/services/distro_manager.dart` | 启动参数含 `--sysvipc` | + +构建中间目录(`proot-source/`、`build_proot_deps/`、`build_proot_out/`)**已删除**,可按 `tools/build/README.md` 随时重建; +旧版 proot 二进制都在 git 历史里,可回滚。 + +### 2. proot 层"传统 syscall 现代化"(本轮核心) + +Android 的 app seccomp 策略在 **x86_64** 上拒绝下列调用(arm64 的系统调用表里根本没有它们,所以只有 x86_64 中招): + +| 被拒调用 | proot 层改写 | 状态 | +|---|---|---| +| `poll` / `select` / `epoll_wait` | `ppoll` / `pselect6` / `epoll_pwait`(timespec 写进 tracee 栈) | ✅ **实测生效**(静态探针 = 0,shim 影响不到) | +| `pipe` / `dup2` | `pipe2` / `dup3` | ✅ | +| `vfork`(`clone` 带 `CLONE_VM\|CLONE_VFORK`) | 去掉这两位(vfork 降级为 fork,POSIX 允许) | ✅ | +| `fork`(57) / `clone3`(435) | → `clone(SIGCHLD)` / 结构体→寄存器参数转换 | ⚠️ **改写未生效**(见下) | + +**已知限制(实测定位)**:`fork` 与 `clone3` 确实被平台拒(`ENOSYS`),但它们属于**创建进程**的调用, +**PRoot 走自己的子进程跟踪路径(ptrace 的 CLONE/FORK 事件),不经过 `translate_syscall_enter`**, +所以补丁里对这两条的改写不会被执行。 + +- 影响面:**仅静态链接程序**(Go/Rust 静态二进制)在 x86_64 上 `fork` 会失败; +- 动态程序不受影响:shim 替换了 libc 的 `fork`/`vfork` ⇒ guest 永远不会发出 `clone3`(这是当前可用的保证); +- 彻底的修法:在 PRoot 的 clone/子进程跟踪路径里挂钩(更深、更侵入的改动)。 + +### 3. 验收记录 + +| 平台 | 项目 | 结果 | +|---|---|---| +| **arm64 真机**(OnePlus PLC110 / Android 16 / 非 root) | 全新导入、`apk update`(3 s / 24059 包)、`apk add tzdata`(`Africa/Accra` nlink=14)、`apk add tree`(busybox 触发器)、broken=0、`unshare`=0、`chroot("/")`=0、SysV IPC 跨进程 `verify=OK` | ✅ 全绿 | +| **x86_64 模拟器**(Android 14 / SDK 34) | 真实 app 过滤器(`Seccomp_filters: 2`)下:静态探针 `poll/select/epoll_wait`=0、子 shell/后台任务/管道、`apk` 0/0/0、SysV IPC 跨进程 `verify=OK`、`/dev/shm` 读写、`profile_sha` 与官方一致 | ✅ 全绿(清空 `LD_PRELOAD` 时 `fork` 受限,见 2 的已知限制) | + +### 4. 复现方式(三步) + +1. `git clone --depth 1 --branch v5.1.107.92 https://github.com/termux/proot.git proot-source` +2. `git -C proot-source apply tools/patches/proot-legacy-syscalls.patch`(另需 talloc 头文件,见 `tools/build/README.md`) +3. `pwsh tools/build/build-proot.ps1 -TallocInclude -ShmemLib build_proot_out/shmem -Install` + (shmem 库用 `pwsh tools/build/build-shmem.ps1` 生成;shim 直接用 NDK clang 编,见 README) diff --git a/android/app/src/main/assets/shims/arm64-v8a/libfix_seccomp.so b/android/app/src/main/assets/shims/arm64-v8a/libfix_seccomp.so index 437bb37..855067a 100644 Binary files a/android/app/src/main/assets/shims/arm64-v8a/libfix_seccomp.so and b/android/app/src/main/assets/shims/arm64-v8a/libfix_seccomp.so differ diff --git a/android/app/src/main/assets/shims/x86_64/libfix_seccomp.so b/android/app/src/main/assets/shims/x86_64/libfix_seccomp.so index 5130ad0..a5374c3 100644 Binary files a/android/app/src/main/assets/shims/x86_64/libfix_seccomp.so and b/android/app/src/main/assets/shims/x86_64/libfix_seccomp.so differ diff --git a/android/app/src/main/cpp/libfix_seccomp.c b/android/app/src/main/cpp/libfix_seccomp.c index 588e46d..a7dffc4 100644 --- a/android/app/src/main/cpp/libfix_seccomp.c +++ b/android/app/src/main/cpp/libfix_seccomp.c @@ -120,9 +120,12 @@ static inline long my_syscall6(long n, long a1, long a2, long a3, long a4, long } #define SYS_utimensat 280 +#define SYS_fchownat 260 #define SYS_ppoll 271 #define SYS_pipe2 293 #define SYS_dup3 292 +#define SYS_clone 56 +#define SIGCHLD_ 17 #elif defined(__aarch64__) @@ -157,6 +160,7 @@ static inline long my_syscall6(long n, long a1, long a2, long a3, long a4, long } #define SYS_utimensat 88 +#define SYS_fchownat 54 #define SYS_ppoll 73 #endif @@ -175,7 +179,13 @@ static inline int set_errno_and_return(long ret) { } /* ------------------------------------------------------------------------- - * utimensat(): survive PRoot's --link2symlink hardlink stand-ins. + * utimensat() / fchownat(): survive PRoot's --link2symlink hardlink stand-ins. + * + * apk 在装完文件后会对 /.apk. 做两件"跟随符号链接"语义的操作: + * utimensat(dirfd, name, times, 0) 保 mtime → 维护老的 proot 需要它 + * fchownat(dirfd, name, 0, 0, 0) 设 owner → 新版 proot(link2symlink 重写后)需要它 + * 二者都会解析进 l2s 的隐藏替身(guest 不可解析)→ ENOENT。 + * 带 AT_SYMLINK_NOFOLLOW 重试即可作用于替身自身(最接近硬链接语义)。 * ------------------------------------------------------------------------- */ __attribute__((visibility("default"))) int utimensat(int dirfd, const char *path, const void *times, int flags) { @@ -193,6 +203,22 @@ int utimensat(int dirfd, const char *path, const void *times, int flags) { return set_errno_and_return(ret); } +__attribute__((visibility("default"))) +int fchownat(int dirfd, const char *path, int owner, int group, int flags) { + long ret = my_syscall6(SYS_fchownat, (long)dirfd, (long)path, + (long)owner, (long)group, (long)flags, 0); + if (ret == -ENOENT && path != 0 && path[0] != '\0' && + (flags & AT_SYMLINK_NOFOLLOW) == 0) { + long retry = my_syscall6(SYS_fchownat, (long)dirfd, (long)path, + (long)owner, (long)group, + (long)(flags | AT_SYMLINK_NOFOLLOW), 0); + if (retry >= 0) { + return 0; + } + } + return set_errno_and_return(ret); +} + #if defined(__x86_64__) /* ------------------------------------------------------------------------- @@ -303,6 +329,27 @@ int pipe(int pipefd[2]) { return set_errno_and_return(ret); } +/* + * fork()/vfork(): Android 的 app seccomp 策略在 x86_64 上拒绝传统 fork/vfork 路径。 + * 实测(App 会话内、无 shim):busybox ash 报 + * /etc/profile.d/xxx.sh: can't fork: Function not implemented (ENOSYS) + * 于是子 shell `( ... ) &`、后台任务、管道等全部失败。 + * 二者统一改为 clone(SIGCHLD):与 fork 语义相同;用 fork 语义实现 vfork 是允许的 + * (POSIX 允许 vfork 退化为 fork,只是少了共享地址空间的优化)。 + * 注意:这条覆盖在"无过滤器的 adb/run-as 环境"里看不出必要性,必须在 App 会话里验证。 + */ +__attribute__((visibility("default"))) +pid_t fork(void) { + long ret = my_syscall6(SYS_clone, SIGCHLD_, 0, 0, 0, 0, 0); + return set_errno_and_return(ret); +} + +__attribute__((visibility("default"))) +pid_t vfork(void) { + long ret = my_syscall6(SYS_clone, SIGCHLD_, 0, 0, 0, 0, 0); + return set_errno_and_return(ret); +} + __attribute__((visibility("default"))) int dup2(int oldfd, int newfd) { if (oldfd == newfd) { diff --git a/android/app/src/main/jniLibs/arm64-v8a/libandroid-shmem.so b/android/app/src/main/jniLibs/arm64-v8a/libandroid-shmem.so new file mode 100644 index 0000000..cd8bdbb Binary files /dev/null and b/android/app/src/main/jniLibs/arm64-v8a/libandroid-shmem.so differ diff --git a/android/app/src/main/jniLibs/arm64-v8a/libproot.so b/android/app/src/main/jniLibs/arm64-v8a/libproot.so index 841554c..5bd6ae3 100644 Binary files a/android/app/src/main/jniLibs/arm64-v8a/libproot.so and b/android/app/src/main/jniLibs/arm64-v8a/libproot.so differ diff --git a/android/app/src/main/jniLibs/x86_64/libandroid-shmem.so b/android/app/src/main/jniLibs/x86_64/libandroid-shmem.so new file mode 100644 index 0000000..21a8c54 Binary files /dev/null and b/android/app/src/main/jniLibs/x86_64/libandroid-shmem.so differ diff --git a/android/app/src/main/jniLibs/x86_64/libproot.so b/android/app/src/main/jniLibs/x86_64/libproot.so index 3e5e390..1bd2e48 100644 Binary files a/android/app/src/main/jniLibs/x86_64/libproot.so and b/android/app/src/main/jniLibs/x86_64/libproot.so differ diff --git a/assets/shims/arm64-v8a/libfix_seccomp.so b/assets/shims/arm64-v8a/libfix_seccomp.so index 437bb37..855067a 100644 Binary files a/assets/shims/arm64-v8a/libfix_seccomp.so and b/assets/shims/arm64-v8a/libfix_seccomp.so differ diff --git a/assets/shims/x86_64/libfix_seccomp.so b/assets/shims/x86_64/libfix_seccomp.so index 5130ad0..a5374c3 100644 Binary files a/assets/shims/x86_64/libfix_seccomp.so and b/assets/shims/x86_64/libfix_seccomp.so differ diff --git a/lib/services/distro_manager.dart b/lib/services/distro_manager.dart index b8b1ae4..8e29c1f 100644 --- a/lib/services/distro_manager.dart +++ b/lib/services/distro_manager.dart @@ -300,6 +300,10 @@ class DistroManager { final args = [ '--kill-on-exit', '--link2symlink', + // SysV IPC(共享内存/信号量/消息队列)用户态模拟:Android 的 app seccomp 策略把 + // shmget/semget/msgget 全部返回 ENOSYS,PRoot 用 libandroid-shmem 在容器内模拟这一套。 + // 需要 jniLibs 里同时提供 libandroid-shmem.so(proot 的 NEEDED 依赖)。 + '--sysvipc', '-0', // 模拟 root 权限 (uid 0) '-k', '5.4.0-proot', // 伪装内核版本(解决 musl libc 调用 clone3/ppoll 时的 Function not implemented) '-L', // 修复 lstat 符号链接大小属性 diff --git a/tools/README.md b/tools/README.md new file mode 100644 index 0000000..ce1bbe5 --- /dev/null +++ b/tools/README.md @@ -0,0 +1,22 @@ +# tools/ —— 构建与自检工具 + +``` +tools/ +├── build/ 构建 proot / libandroid-shmem(用法见 build/README.md) +│ ├── build-proot.ps1 +│ └── build-shmem.ps1 +├── patches/ 构建时应用的本地补丁 +│ ├── proot-legacy-syscalls.patch proot 层"传统 syscall 现代化" +│ └── libandroid-shmem-runtime-ashmem.patch shmem 后端改成运行时选择 +└── container-selfcheck/ 容器自检(用法见 container-selfcheck/README.md) + ├── probe3/4/5/6/8.c 裸 syscall 探针(策略、apk 安装序列、空路径 stat、SysV IPC、fork 变体) + ├── selfcheck.sh 一键验收 + └── guest-run.sh adb 跑手(免重装 APK 在容器里跑命令) +``` + +**日常开发不需要它们**:proot / shmem / shim 的成品都已提交在 +`android/app/src/main/jniLibs/` 与 `assets/shims/`。只有在升级 proot、修改补丁、或换 ABI 时才需要重新构建。 + +⚠️ 自检里的 `guest-run.sh` 经 `run-as` 启动,**没有** Android 的 app seccomp 过滤器 +(容器里看到的 `Seccomp:2` 是 proot 自己的加速过滤器)。涉及平台策略的结论必须在 +**App 自己的会话**里验证 —— 详见 `container-selfcheck/README.md`。 diff --git a/tools/build/README.md b/tools/build/README.md new file mode 100644 index 0000000..aaabe2f --- /dev/null +++ b/tools/build/README.md @@ -0,0 +1,64 @@ +# tool/ —— proot / shmem 的构建与补丁 + +这里的产物**已经编译好并提交在仓库里**(`android/app/src/main/jniLibs/*/lib*.so` 与 `assets/shims/*/`), +正常开发**不需要**重新构建。只有在升级 proot、改补丁、或换 ABI 时才需要。 + +构建所需的中间目录(`proot-source/`、`build_proot_deps/`、`build_proot_out/`)都在 `.gitignore` 里, +可随时删除、按下面步骤重建。 + +--- + +## 一、重建 proot(含本地补丁) + +```powershell +# 1) 取源码(必须是 termux 的 fork —— 我们需要它的 --link2symlink/--kill-on-exit/l2s) +git clone --depth 1 --branch v5.1.107.92 https://github.com/termux/proot.git proot-source + +# 2) 应用本地补丁(proot 层"传统 syscall 现代化",见补丁头部注释) +git -C proot-source apply tools\patches\proot-legacy-syscalls.patch + +# 3) 取 talloc 头文件(编译期需要;libtalloc.so 用仓库里现成的) +# 任一 talloc 2.x 版本即可: +git clone --depth 1 --filter=blob:none --sparse https://github.com/samba-team/samba.git build_proot_deps\samba +git -C build_proot_deps\samba sparse-checkout set lib/talloc +# 之后 -TallocInclude 指向 build_proot_deps\samba\lib\talloc + +# 4) 编译(双架构,loader 内嵌,链接仓库里的 libtalloc.so / libandroid-shmem.so) +pwsh tools\build\build-proot.ps1 -TallocInclude build_proot_deps\samba\lib\talloc ` + -ShmemLib build_proot_out\shmem ` + -Install +``` + +## 二、重建 libandroid-shmem(仅当要改 `--sysvipc` 后端时) + +```powershell +pwsh tools\build\build-shmem.ps1 # 自动克隆 termux/libandroid-shmem 并应用 tools\patches\libandroid-shmem-runtime-ashmem.patch +``` + +## 三、重建 shim + +shim 是 freestanding C(无 libc),直接用 NDK clang 编: + +```powershell +$ndk = "D:\Android\SDK\ndk\28.2.13676358\toolchains\llvm\prebuilt\windows-x86_64\bin" +$src = "android\app\src\main\cpp" +foreach ($t in @(@("x86_64","x86_64-linux-android24"), @("arm64-v8a","aarch64-linux-android24"))) { + & "$ndk\clang.exe" --target=$($t[1]) -shared -fPIC -nostdlib -ffreestanding ` + -fno-builtin -fno-stack-protector -O2 -o "assets\shims\$($t[0])\libfix_seccomp.so" ` + "$src\libfix_seccomp.c" "$src\libfix_dns.c" + Copy-Item "assets\shims\$($t[0])\libfix_seccomp.so" "android\app\src\main\assets\shims\$($t[0])\libfix_seccomp.so" -Force +} +``` + +## 四、补丁清单 + +| 补丁 | 作用 | +|---|---| +| `patches/proot-legacy-syscalls.patch` | proot 层把 Android 在 x86_64 上拒绝的传统 syscall 改写成现代等价形式(`poll→ppoll`、`select→pselect6`、`epoll_wait→epoll_pwait`、`pipe→pipe2`、`dup2→dup3`、`fork/vfork→clone(SIGCHLD)`、`clone` 去掉 `CLONE_VM\|CLONE_VFORK`、`clone3→clone`)。新增 `src/syscall/legacy.c`,并在 `src/syscall/seccomp.c` 的过滤表里登记这些调用 | +| `patches/libandroid-shmem-runtime-ashmem.patch` | `libandroid-shmem` 的后端选择从**编译期**(`__ANDROID_API__ >= 26`)改成**运行时** `dlsym(ASharedMemory_*)`,拿不到再回退 `/dev/ashmem`。原因:Android 11+ 对应用进程已拒绝 `/dev/ashmem`(实测 EACCES),而 API 26 编译又会把设备门槛抬到 8.0 | + +## 五、注意 + +- **不要用 proot-me 上游**:`--link2symlink`(本环境禁止 `link(2)`,必须用 l2s 模拟)与 `--kill-on-exit` 都来自 termux fork。 +- **不要原地覆盖运行中的 shim**:必须「写临时文件 → `mv`」,否则正在映射它的进程会 SIGSEGV。 +- 构建产物请用 `-Install` 安装(会自动把旧文件备份到 `build_proot_out/backup/`)。 diff --git a/tools/build/build-proot.ps1 b/tools/build/build-proot.ps1 new file mode 100644 index 0000000..7ce2689 --- /dev/null +++ b/tools/build/build-proot.ps1 @@ -0,0 +1,260 @@ +# build-proot.ps1 —— 从 termux/proot 源码为 Android 双架构构建 proot +# +# 为什么需要这个脚本:proot 的构建入口是 src/GNUmakefile,它依赖 make/sh/awk/grep; +# 而本机没有这些工具(只有 NDK + git)。本脚本用 PowerShell 复刻 GNUmakefile 的全部 +# 关键步骤,产物与「make -C src」一致: +# 1) 用 clang -E -dM 从 arch.h 提取 LOADER_ADDRESS / HAS_LOADER_32BIT / HAS_POKEDATA_WORKAROUND +# 2) 编译 .check_seccomp_filter / .check_process_vm 生成 build.h 的 HAVE_* 定义 +# 3) 编译 65 个目标文件 +# 4) 构建 loader(可执行体)→ strip → objcopy 成二进制块 → 链进 proot(loader 内嵌) +# 5) 若架构需要,生成并编译 loader-info.c(POKEDATA workaround 的符号偏移) +# 6) 链接成单个 libproot.so(ELF PIE 可执行体,NEEDED libtalloc.so) +# +# 用法: +# pwsh tools\build\build-proot.ps1 -TallocInclude <含 talloc.h 的目录> [-Install] +# +# 说明: +# - 不设 PROOT_UNBUNDLE_LOADER ⇒ loader 内嵌,产物是单个 .so(APK 无需额外文件) +# - talloc:链接仓库里现成的 jniLibs//libtalloc.so,只需要一个 talloc.h +# - 32 位 loader(loader-m32)在我们的 64 位 rootfs 下用不到;源码头文件里它声明为 +# WEAK 符号,缺失不会导致链接失败。需要时用 -AlsoM32Loader 打开。 + +param( + [string]$ProotSrc = "proot-source", + [Parameter(Mandatory = $true)][string]$TallocInclude, + [string]$TallocLibRoot = "android\app\src\main\jniLibs", + [string]$OutDir = "build_proot_out", + [string[]]$Abis = @("arm64-v8a", "x86_64"), + # 可选:启用 SysV IPC 的共享内存后端(需要 libandroid-shmem) + # -ShmemLib build_proot_out\shmem ← 该目录下每个 ABI 一个子目录,内含 libandroid-shmem.so + # 打开后 proot 会 NEEDED libandroid-shmem.so;运行时是否真的启用由 --sysvipc 参数决定。 + [string]$ShmemLib, + [switch]$AlsoM32Loader, + [switch]$EnableProcessVm, + [switch]$Install +) + +$ErrorActionPreference = "Stop" +$root = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path) +Set-Location $root + +# --- 工具链 --------------------------------------------------------------- +$ndkBin = Get-ChildItem "D:\Android\SDK\ndk" -Directory | + Sort-Object Name -Descending | + ForEach-Object { Join-Path $_.FullName "toolchains\llvm\prebuilt\windows-x86_64\bin" } | + Where-Object { Test-Path (Join-Path $_ "clang.exe") } | + Select-Object -First 1 +if (-not $ndkBin) { throw "找不到 NDK clang(期望 D:\Android\SDK\ndk\*\toolchains\llvm\prebuilt\windows-x86_64\bin)" } + +$clang = Join-Path $ndkBin "clang.exe" +$strip = Join-Path $ndkBin "llvm-strip.exe" +$objcopy = Join-Path $ndkBin "llvm-objcopy.exe" +$objdump = Join-Path $ndkBin "llvm-objdump.exe" +$readelf = Join-Path $ndkBin "llvm-readelf.exe" +$nm = Join-Path $ndkBin "llvm-nm.exe" +foreach ($t in @($clang, $strip, $objcopy, $objdump, $readelf)) { + if (-not (Test-Path $t)) { throw "缺少工具: $t" } +} + +$srcDir = Join-Path $ProotSrc "src" +if (-not (Test-Path (Join-Path $srcDir "GNUmakefile"))) { throw "找不到 $srcDir\GNUmakefile" } +if (-not (Test-Path (Join-Path $TallocInclude "talloc.h"))) { throw "在 $TallocInclude 里找不到 talloc.h" } + +# ABI → 目标三元组(64 位 / 32 位 loader 用) +$triples = @{ + "arm64-v8a" = @{ t64 = "aarch64-linux-android24"; t32 = "armv7a-linux-androideabi24" } + "x86_64" = @{ t64 = "x86_64-linux-android24"; t32 = "i686-linux-android24" } +} + +# --- 从 GNUmakefile 解析目标文件列表(保持与上游同步)-------------------- +function Get-ObjectList([string]$mkPath) { + # 逐行解析 OBJECTS += 块(不依赖换行符风格,Windows 检出的 CRLF 也适用) + $objs = @() + $inBlock = $false + foreach ($line in Get-Content $mkPath) { + if ($line -match '^\s*OBJECTS \+=') { $inBlock = $true; continue } + if ($inBlock -and $line -match '^\S') { break } # 缩进结束 => 块结束 + if ($inBlock -and ($line -match '([A-Za-z0-9_/-]+)\.o')) { $objs += $Matches[1] } + } + if ($objs.Count -eq 0) { throw "无法从 GNUmakefile 解析 OBJECTS 列表($mkPath)" } + $objs | Sort-Object -Unique +} + +# --- 从 arch.h 提取宏(等价于 GNUmakefile 的 define_from_arch.h)---------- +function Get-ArchMacro([string]$target, [string]$name) { + $out = & $clang "--target=$target" -E -dM -DNO_LIBC_HEADER (Join-Path $srcDir "arch.h") 2>$null + $line = $out | Select-String -Pattern "\b$name\b" | Select-Object -First 1 + if (-not $line) { return $null } + # 形如: #define LOADER_ADDRESS 0x600000000000 + $parts = ($line.ToString() -split '\s+') + if ($parts.Count -ge 3) { return ($parts[2..($parts.Count - 1)] -join ' ') } else { return $null } +} + +function Invoke-Compile([string]$target, [string]$source, [string]$output, [string[]]$extra) { + # -Wno-implicit-function-declaration:上游个别文件(如 extension/ashmem_memfd)漏了 + # ,老 clang 只是警告,现代 clang 默认按错误处理;降级以保持与上游行为一致。 + $args = @("--target=$target", "-D_FILE_OFFSET_BITS=64", "-D_GNU_SOURCE", "-I.", "-I$srcDir", + "-Wall", "-Wextra", "-O2", "-DARG_MAX=131072", + "-Wno-implicit-function-declaration", "-I$TallocInclude") + $extra + + @("-c", $source, "-o", $output) + $out = & $clang @args 2>&1 + if ($LASTEXITCODE -ne 0) { throw "编译失败: $source`n$($out -join "`n")" } +} + +# --- 主流程 --------------------------------------------------------------- +New-Item -ItemType Directory -Force -Path $OutDir | Out-Null +$objectList = Get-ObjectList (Join-Path $srcDir "GNUmakefile") +Write-Host "从 GNUmakefile 解析到 $($objectList.Count) 个目标文件" -ForegroundColor Cyan + +$version = (& git -C $ProotSrc describe --tags --dirty --abbrev=8 --always 2>$null) +if (-not $version) { $version = "unknown" } + +foreach ($abi in $Abis) { + if (-not $triples.ContainsKey($abi)) { throw "不支持的 ABI: $abi" } + $t64 = $triples[$abi].t64 + $objDir = Join-Path $OutDir $abi + New-Item -ItemType Directory -Force -Path $objDir | Out-Null + Write-Host "`n===== 构建 $abi ($t64) =====" -ForegroundColor Green + + # 1) 架构宏 + $loaderAddr = Get-ArchMacro $t64 "LOADER_ADDRESS" + $loaderCflags = Get-ArchMacro $t64 "LOADER_ARCH_CFLAGS" + $hasM32 = Get-ArchMacro $t64 "HAS_LOADER_32BIT" + $hasPokedata = Get-ArchMacro $t64 "HAS_POKEDATA_WORKAROUND" + Write-Host " LOADER_ADDRESS=$loaderAddr LOADER_ARCH_CFLAGS='$loaderCflags' 32bit=$hasM32 pokedata=$hasPokedata" + + # 2) build.h(VERSION + HAVE_*,HAVE_ 由链接探测决定) + $checkDir = Join-Path $objDir "check" + New-Item -ItemType Directory -Force -Path $checkDir | Out-Null + $defines = @() + # HAVE_PROCESS_VM 默认**不开启**:PRoot 用它读写 tracee 内存,而 Android 应用进程策略 + # 可能拒绝 process_vm_readv/writev;现有可用的 2018 二进制也是 process_vm=no + # (走 POKEDATA 兼容路径)。需要试验时加 -EnableProcessVm。 + $checks = @([pscustomobject]@{ file = "seccomp_filter"; define = "HAVE_SECCOMP_FILTER" }) + if ($EnableProcessVm) { $checks += [pscustomobject]@{ file = "process_vm"; define = "HAVE_PROCESS_VM" } } + foreach ($c in $checks) { + $exe = Join-Path $checkDir $c.file + $null = & $clang "--target=$t64" "-o" $exe (Join-Path $srcDir ".check_$($c.file).c") 2>&1 + if ($LASTEXITCODE -eq 0) { $defines += "#define $($c.define) 1" ; Write-Host " $($c.define) = 有" } + else { Write-Host " $($c.define) = 无(走兼容路径,符合预期)" } + } + if (-not $EnableProcessVm) { Write-Host " HAVE_PROCESS_VM = 强制关闭(与现有可用二进制一致,走 POKEDATA 路径)" } + $buildH = Join-Path $srcDir "build.h" + @("#undef VERSION", "#define VERSION `"$version`"") + $defines | Set-Content -Path $buildH -Encoding ASCII + Write-Host " 已生成 build.h (VERSION=$version)" + + # 3) 编译目标文件 + # -ShmemLib 时给所有目标文件加 WITH_LIBANDROID_SHMEM(sysvipc 的 shm 后端改用 + # libandroid-shmem 的 shmget/shmat 实现;不传 --sysvipc 时该扩展不激活) + $objDefs = @() + if ($ShmemLib) { $objDefs += "-DWITH_LIBANDROID_SHMEM" } + $objects = @() + $i = 0 + foreach ($o in $objectList) { + $i++ + $cFile = Join-Path $srcDir "$o.c" + $oFile = Join-Path $objDir ("{0}.o" -f ($o -replace '/', '_')) + Invoke-Compile $t64 $cFile $oFile $objDefs + $objects += $oFile + } + Write-Host " 已编译 $i 个目标文件" + + # 4) loader(内嵌形态):编 → 链 → (保留未 strip 副本供 readelf)→ strip → objcopy 成二进制块 + $loaderObjDir = Join-Path $objDir "loader" + New-Item -ItemType Directory -Force -Path $loaderObjDir | Out-Null + $loaderC = Join-Path $srcDir "loader\loader.c" + $loaderAsm = Join-Path $srcDir "loader\assembly.S" + $loaderLo = Join-Path $loaderObjDir "loader.o" + $loaderSo = Join-Path $loaderObjDir "assembly.o" + $loaderRaw = Join-Path $loaderObjDir "loader" # 未 strip(上游 .INTERMEDIATE) + $loaderBin = Join-Path $loaderObjDir "loader.exe" # strip 后(用于 objcopy 包装) + $loaderWrap = Join-Path $loaderObjDir "loader-wrapped.o" + $extraL = @("-fPIC", "-ffreestanding") + if ($loaderCflags) { $extraL += ($loaderCflags -split '\s+') } + Invoke-Compile $t64 $loaderC $loaderLo $extraL + $null = & $clang "--target=$t64" "-fPIC" "-c" $loaderAsm "-o" $loaderSo 2>&1 + if ($LASTEXITCODE -ne 0) { throw "loader/assembly.S 编译失败" } + $ldArgs = @("--target=$t64", "-static", "-nostdlib", + "-Wl,--build-id=none", "-Wl,-Ttext=$loaderAddr", "-Wl,-z,noexecstack", + "-o", $loaderRaw, $loaderLo, $loaderSo) + $null = & $clang @ldArgs 2>&1 + if ($LASTEXITCODE -ne 0) { throw "loader 链接失败" } + Copy-Item $loaderRaw $loaderBin -Force + & $strip $loaderBin 2>&1 | Out-Null + # 由 objdump -f 推 objcopy 需要的 --output-target / --binary-architecture + $f = (& $objdump -f $loaderSo 2>&1 | Select-String -Pattern "file format|architecture" | Select-Object -First 2) + $fmt = ($f[0].ToString() -replace '.*file format\s+', '').Trim() + $arch = ($f[1].ToString() -replace '.*architecture:\s+', '').Trim() + if (-not $fmt) { $fmt = if ($abi -eq "arm64-v8a") { "elf64-littleaarch64" } else { "elf64-x86-64" } } + if (-not $arch) { $arch = if ($abi -eq "arm64-v8a") { "aarch64" } else { "i386:x86-64" } } + # objcopy 生成的符号名由**传入的文件名**决定(须为裸文件名,否则会变成 + # _binary_<路径>_start,与 enter.c 期望的 _binary_loader_exe_start 不符)⇒ 在 loader 目录内执行 + Push-Location $loaderObjDir + $null = & $objcopy --input-target=binary "--output-target=$fmt" "--binary-architecture=$arch" "loader.exe" "loader-wrapped.o" 2>&1 + $objcopyRc = $LASTEXITCODE + Pop-Location + if ($objcopyRc -ne 0) { throw "objcopy 包装 loader 失败 (fmt=$fmt arch=$arch)" } + $objects += $loaderWrap + Write-Host " loader 内嵌就绪($((Get-Item $loaderBin).Length) 字节,objcopy fmt=$fmt arch=$arch)" + + # 5) POKEDATA workaround:由 **未 strip 的** loader 符号表生成 loader-info.c(复刻 loader-info.awk) + if ($hasPokedata -eq "true") { + $syms = & $readelf -s $loaderRaw 2>&1 + $pw = $null; $st = $null + foreach ($line in $syms) { + $t = ($line.ToString().Trim() -split '\s+') + if ($t.Count -lt 3) { continue } + $name = $t[-1] + $val = $t[1] + if ($val -notmatch '^[0-9a-fA-F]+$') { continue } + if ($name -eq 'pokedata_workaround') { $pw = [Convert]::ToInt64($val, 16) } + elseif ($name -eq '_start') { $st = [Convert]::ToInt64($val, 16) } + } + if ($null -eq $pw -or $null -eq $st) { throw "无法从未 strip 的 loader 提取 pokedata_workaround / _start" } + $infoC = Join-Path $srcDir "loader\loader-info.c" + @("#include ", "const ssize_t offset_to_pokedata_workaround=$($pw - $st);") | + Set-Content -Path $infoC -Encoding ASCII + $infoO = Join-Path $loaderObjDir "loader-info.o" + Invoke-Compile $t64 $infoC $infoO @() + $objects += $infoO + Write-Host " loader-info.c 已生成 (offset=$($pw - $st))" + } + + # 6) 链接 proot(单个自包含 .so;NEEDED libtalloc.so[+ libandroid-shmem.so]) + $tallocDir = Join-Path $TallocLibRoot $abi + if (-not (Test-Path (Join-Path $tallocDir "libtalloc.so"))) { + throw "找不到 $tallocDir\libtalloc.so(用于链接)" + } + $libArgs = @("-L$tallocDir", "-ltalloc") + if ($ShmemLib) { + $shmemDir = Join-Path $ShmemLib $abi + if (-not (Test-Path (Join-Path $shmemDir "libandroid-shmem.so"))) { + throw "找不到 $shmemDir\libandroid-shmem.so(-ShmemLib 需要每个 ABI 一个子目录)" + } + $libArgs += @("-L$shmemDir", "-landroid-shmem") + } + $outSo = Join-Path $objDir "libproot.so" + $linkArgs = @("--target=$t64", "-o", $outSo) + $objects + $libArgs + @("-Wl,-z,noexecstack") + $out = & $clang @linkArgs 2>&1 + if ($LASTEXITCODE -ne 0) { throw "链接 libproot.so 失败`n$($out -join "`n")" } + $null = & $strip $outSo 2>&1 + $size = (Get-Item $outSo).Length + $needed = & $readelf -d $outSo 2>&1 | Select-String -Pattern "NEEDED|SONAME" + Write-Host " ✅ 产出 $outSo ($size 字节)$(if ($ShmemLib) { ' [含 libandroid-shmem 后端]' })" -ForegroundColor Green + Write-Host " $(($needed | ForEach-Object { $_.ToString().Trim() }) -join ' | ')" +} + +# --- 可选:安装到 jniLibs(覆盖前备份)----------------------------------- +if ($Install) { + $stamp = Get-Date -Format "yyyyMMdd-HHmmss" + foreach ($abi in $Abis) { + $built = Join-Path (Join-Path $OutDir $abi) "libproot.so" + if (-not (Test-Path $built)) { continue } + $target = Join-Path (Join-Path $TallocLibRoot $abi) "libproot.so" + if (Test-Path $target) { Copy-Item $target "$target.bak-$stamp" -Force } + Copy-Item $built $target -Force + Write-Host "已安装 $target(旧文件备份为 libproot.so.bak-$stamp)" -ForegroundColor Yellow + } +} + +Write-Host "`n完成。产物在 $OutDir\\libproot.so" -ForegroundColor Cyan diff --git a/tools/build/build-shmem.ps1 b/tools/build/build-shmem.ps1 new file mode 100644 index 0000000..1d8e8ab --- /dev/null +++ b/tools/build/build-shmem.ps1 @@ -0,0 +1,91 @@ +# build-shmem.ps1 —— 为 Android 双架构构建 libandroid-shmem(SysV IPC 共享内存后端) +# +# 为什么需要: +# proot 的 --sysvipc 在 Android 上用 libandroid-shmem 支撑 shmget/shmat。 +# 该库上游用 __ANDROID_API__ >= 26 静态选择后端,但实测 Android 11+ 已不允许应用 +# 进程打开 /dev/ashmem(EACCES),而 libandroid 的 ASharedMemory_*(memfd 支撑)可用。 +# tools/patches/libandroid-shmem-runtime-ashmem.patch 把选择改为运行时 dlsym: +# 现代设备走 ASharedMemory,老设备(API 24/25)回退 /dev/ashmem。 +# +# 另外两个构建参数: +# -D_PATH_TMP="/" ── 上游引用 bionic 未定义的 _PATH_TMP, +# 它是命名 shm key 的 symlink 存放位置 +# -Wno-implicit-function-declaration ── 上游漏了 (老 clang 只是警告) +# +# 用法: +# pwsh tools\build\build-shmem.ps1 [-AppId com.example.code_editor] [-OutDir build_proot_out\shmem] + +param( + [string]$SrcDir = "build_proot_deps\libandroid-shmem", + [string]$OutDir = "build_proot_out\shmem", + [string]$AppId, + [string[]]$Abis = @("arm64-v8a", "x86_64"), + [string]$ApiLevel = "24" +) + +$ErrorActionPreference = "Stop" +$root = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path) +Set-Location $root + +$ndkBin = Get-ChildItem "D:\Android\SDK\ndk" -Directory | + Sort-Object Name -Descending | + ForEach-Object { Join-Path $_.FullName "toolchains\llvm\prebuilt\windows-x86_64\bin" } | + Where-Object { Test-Path (Join-Path $_ "clang.exe") } | + Select-Object -First 1 +if (-not $ndkBin) { throw "找不到 NDK clang" } +$clang = Join-Path $ndkBin "clang.exe" +$readelf = Join-Path $ndkBin "llvm-readelf.exe" + +# --- 源码与补丁 ----------------------------------------------------------- +if (-not (Test-Path (Join-Path $SrcDir "shmem.c"))) { + Write-Host "克隆 libandroid-shmem..." -ForegroundColor Cyan + & git clone --depth 1 https://github.com/termux/libandroid-shmem.git $SrcDir +} +$patch = "tools\patches\libandroid-shmem-runtime-ashmem.patch" +if ((Test-Path $patch) -and -not (Select-String -Path (Join-Path $SrcDir "shmem.c") -Pattern "choose the ashmem backend at RUNTIME" -Quiet)) { + Write-Host "应用运行时后端补丁..." -ForegroundColor Cyan + & git -C $SrcDir apply (Resolve-Path $patch).Path + if ($LASTEXITCODE -ne 0) { throw "补丁应用失败: $patch" } +} + +# --- app id(决定 _PATH_TMP:命名 shm key 的 symlink 存放位置)------------- +if (-not $AppId) { + $m = Select-String -Path "android\app\build.gradle.kts" -Pattern 'applicationId\s*=\s*"([^"]+)"' | Select-Object -First 1 + $AppId = if ($m) { $m.Matches.Groups[1].Value } else { "com.example.code_editor" } +} +$tmpDef = "-D_PATH_TMP=`"/data/data/$AppId/cache/`"" +Write-Host "applicationId=$AppId _PATH_TMP=/data/data/$AppId/cache/" -ForegroundColor Cyan + +$triples = @{ "arm64-v8a" = "aarch64-linux-android$ApiLevel"; "x86_64" = "x86_64-linux-android$ApiLevel" } +$srcAbs = (Resolve-Path $SrcDir).Path +$outAbs = Join-Path $root $OutDir + +foreach ($abi in $Abis) { + if (-not $triples.ContainsKey($abi)) { throw "不支持的 ABI: $abi" } + $target = $triples[$abi] + $abiDir = Join-Path $outAbs $abi + New-Item -ItemType Directory -Force -Path $abiDir | Out-Null + $obj = Join-Path $abiDir "shmem.o" + $so = Join-Path $abiDir "libandroid-shmem.so" + Write-Host "`n===== $abi ($target) =====" -ForegroundColor Green + + Push-Location $srcAbs + $w = & $clang --target=$target -fpic -std=c11 -Wall -Wextra -Wno-implicit-function-declaration $tmpDef -c shmem.c -o $obj 2>&1 + $rc = $LASTEXITCODE + Pop-Location + if ($rc -ne 0) { throw "编译失败: $($w -join "`n")" } + $warnings = $w | Select-String -Pattern "implicitly|undeclared" + if ($warnings) { Write-Host " (上游漏 include 的告警): $(($warnings | Measure-Object).Count) 条" -ForegroundColor DarkYellow } + + Push-Location $srcAbs + $linkOut = & $clang --target=$target "-Wl,--version-script=exports.txt" -shared $obj -o $so -llog 2>&1 + $rc = $LASTEXITCODE + Pop-Location + if ($rc -ne 0) { throw "链接失败: $($linkOut -join "`n")" } + + $needed = (& $readelf -d $so 2>&1 | Select-String -Pattern "NEEDED") | + ForEach-Object { ($_.ToString() -split '\[|\]')[1] } + Write-Host " ✅ $so ($((Get-Item $so).Length) 字节) NEEDED: $($needed -join ', ')" -ForegroundColor Green +} + +Write-Host "`n完成。proot 构建时用:-ShmemLib $OutDir" -ForegroundColor Cyan diff --git a/tools/container-selfcheck/guest-run.sh b/tools/container-selfcheck/guest-run.sh index 643ce9a..6afb086 100644 --- a/tools/container-selfcheck/guest-run.sh +++ b/tools/container-selfcheck/guest-run.sh @@ -1,9 +1,16 @@ #!/system/bin/sh # run an arbitrary guest binary inside the PRoot container (adb harness) +# 注意:这条路径经 run-as 启动,**没有** Android 的 app seccomp 过滤器 +#(容器里看到的 Seccomp:2 是 proot 自己的加速过滤器)。因此涉及 +# poll/select 等平台策略的结论必须在 App 自己的会话里验证。 PKG=com.example.code_editor BASE=/data/data/$PKG/files/distros/alpine ROOT=$BASE/rootfs -LIBDIR=$(pm path $PKG 2>/dev/null | head -1 | sed 's|package:||; s|/base.apk$||')/lib/arm64 +# 按设备 ABI 选择(arm64-v8a / x86_64),避免写死导致换架构失效 +ABI=$(getprop ro.product.cpu.abi) +[ -z "$ABI" ] && ABI=arm64-v8a +LIBDIR=$(pm path $PKG 2>/dev/null | head -1 | sed 's|package:||; s|/base.apk$||')/lib/$ABI +[ -d "$LIBDIR" ] || LIBDIR=$(pm path $PKG 2>/dev/null | head -1 | sed 's|package:||; s|/base.apk$||')/lib/arm64 export LD_LIBRARY_PATH=$LIBDIR export PROOT_TMP_DIR=/data/data/$PKG/cache export PROOT_L2S_DIR=$BASE/.l2s diff --git a/tools/container-selfcheck/probe6.c b/tools/container-selfcheck/probe6.c new file mode 100644 index 0000000..148e96a --- /dev/null +++ b/tools/container-selfcheck/probe6.c @@ -0,0 +1,168 @@ +/* probe6.c - SysV IPC 可用性探针(shmget/semget/msgget + shmat) + * Build: clang --target=aarch64-linux-android24 -nostdlib -static -O1 -o probe6 probe6.c + */ +typedef long i64; + +#if defined(__x86_64__) +static inline i64 sc6(i64 n, i64 a1, i64 a2, i64 a3, i64 a4, i64 a5, i64 a6) +{ + i64 ret; + register i64 r10 __asm__("r10") = a4; + register i64 r8 __asm__("r8") = a5; + register i64 r9 __asm__("r9") = a6; + __asm__ __volatile__("syscall" : "=a"(ret) + : "a"(n), "D"(a1), "S"(a2), "d"(a3), "r"(r10), "r"(r8), "r"(r9) + : "rcx", "r11", "memory"); + return ret; +} +#define SYS_write 1 +#define SYS_nanosleep 35 +#define SYS_exit 60 +#define SYS_shmget 29 +#define SYS_shmat 30 +#define SYS_shmctl 31 +#define SYS_semget 64 +#define SYS_msgget 68 +#elif defined(__aarch64__) +static inline i64 sc6(i64 n, i64 a1, i64 a2, i64 a3, i64 a4, i64 a5, i64 a6) +{ + register i64 x8 __asm__("x8") = n; + register i64 x0 __asm__("x0") = a1; + register i64 x1 __asm__("x1") = a2; + register i64 x2 __asm__("x2") = a3; + register i64 x3 __asm__("x3") = a4; + register i64 x4 __asm__("x4") = a5; + register i64 x5 __asm__("x5") = a6; + __asm__ __volatile__("svc #0" : "+r"(x0) + : "r"(x8), "r"(x1), "r"(x2), "r"(x3), "r"(x4), "r"(x5) : "memory"); + return x0; +} +#define SYS_write 64 +#define SYS_nanosleep 101 +#define SYS_exit 93 +#define SYS_shmget 194 +#define SYS_shmat 196 +#define SYS_shmctl 195 +#define SYS_semget 190 +#define SYS_msgget 186 +#endif + +static i64 sc1(i64 n, i64 a) { return sc6(n, a, 0, 0, 0, 0, 0); } +static i64 sc3(i64 n, i64 a, i64 b, i64 c) { return sc6(n, a, b, c, 0, 0, 0); } + +static void put(const char *s) { i64 n = 0; while (s[n]) n++; sc3(SYS_write, 1, (i64)s, n); } +static void putnum(i64 v) +{ + char b[24]; int i = 24, neg = v < 0; + unsigned long u = neg ? (unsigned long)(-v) : (unsigned long)v; + if (v == 0) { put("0"); return; } + b[--i] = 0; + while (u) { b[--i] = '0' + (u % 10); u /= 10; } + if (neg) b[--i] = '-'; + put(&b[i]); +} +static void show(const char *n, i64 r) +{ + put(" "); put(n); put(" = "); putnum(r); + if (r == -38) put(" [ENOSYS: 被 seccomp 拦]"); + else if (r == -1) put(" [EPERM]"); + else if (r == -13) put(" [EACCES]"); + else if (r >= 0) put(" [OK]"); + put("\n"); +} + +void prog_main(void); +#if defined(__x86_64__) +__asm__(".globl _start\n_start:\n andq $-16, %rsp\n call prog_main\n" + " movl $60, %eax\n xorl %edi, %edi\n syscall\n"); +#else +__asm__(".globl _start\n_start:\n bl prog_main\n mov x0, #0\n mov x8, #93\n svc #0\n"); +#endif + +#define IPC_CREAT 01000 +#define IPC_RMID 0 + +#if defined(PROBE6_WRITE) || defined(PROBE6_READ) +/* 跨进程共享内存测试:writer 建段写数据,reader 另起进程附着读取 */ +#define TEST_KEY 0x4321 +#define MAGIC "SYSVIPC-SHARED!" +void prog_main(void) +{ + i64 shmid, addr; + const char *tag = +#ifdef PROBE6_WRITE + "writer"; +#else + "reader"; +#endif + put("=== probe6 "); put(tag); put(" ===\n"); + shmid = sc3(SYS_shmget, TEST_KEY, 4096, IPC_CREAT | 0600); + show("shmget(key=0x4321)", shmid); + if (shmid < 0) { sc1(SYS_exit, 1); for (;;) {} } + addr = sc3(SYS_shmat, shmid, 0, 0); + show("shmat", addr); + if (addr < 0) { sc1(SYS_exit, 1); for (;;) {} } + +#ifdef PROBE6_WRITE + { + char *p = (char *)addr; + const char *m = MAGIC; + int i = 0; + while (m[i]) { p[i] = m[i]; i++; } + put(" wrote: "); put(MAGIC); put("\n"); + /* 保持在世:真实场景里创建者(如 postmaster)会常驻,别人才能附着 */ + { + struct ts2 { long s; long ns; } ts = { 60, 0 }; + put(" (keepalive 60s)\n"); + sc6(SYS_nanosleep, (i64)&ts, 0, 0, 0, 0, 0); + } + } +#else + { + char *p = (char *)addr; + const char *m = MAGIC; + int i = 0, ok = 1; + while (m[i]) { if (p[i] != m[i]) { ok = 0; break; } i++; } + put(" read : "); + for (i = 0; i < 16; i++) put((const char[]){p[i], 0}); + put("\n cross-process verify = "); put(ok ? "OK" : "MISMATCH"); put("\n"); + show("shmctl(RMID)", sc3(SYS_shmctl, shmid, IPC_RMID, 0)); + } +#endif + put("=== done ===\n"); + sc1(SYS_exit, 0); + for (;;) {} +} +#else +void prog_main(void) +{ + i64 shmid, semid, msgid, addr, shmid2; + put("=== probe6: SysV IPC ===\n"); + + shmid = sc3(SYS_shmget, 0 /*IPC_PRIVATE*/, 4096, IPC_CREAT | 0600); + show("shmget(IPC_PRIVATE,4096)", shmid); + if (shmid >= 0) { + addr = sc3(SYS_shmat, shmid, 0, 0); + show("shmat", addr); + show("shmctl(RMID)", sc3(SYS_shmctl, shmid, IPC_RMID, 0)); + } + + /* 命名 key:会走 libandroid-shmem 的 symlink 协调路径(_PATH_TMP) */ + shmid2 = sc3(SYS_shmget, 0x1234, 4096, IPC_CREAT | 0600); + show("shmget(key=0x1234)", shmid2); + if (shmid2 >= 0) { + show("shmget(same key again)", sc3(SYS_shmget, 0x1234, 4096, IPC_CREAT | 0600)); + show("shmctl(RMID)", sc3(SYS_shmctl, shmid2, IPC_RMID, 0)); + } + + semid = sc3(SYS_semget, 0, 1, IPC_CREAT | 0600); + show("semget(1)", semid); + + msgid = sc3(SYS_msgget, 0, IPC_CREAT | 0600, 0); + show("msgget", msgid); + + put("=== done ===\n"); + sc1(SYS_exit, 0); + for (;;) {} +} +#endif /* PROBE6_WRITE / PROBE6_READ */ diff --git a/tools/container-selfcheck/probe8.c b/tools/container-selfcheck/probe8.c new file mode 100644 index 0000000..5a5e117 --- /dev/null +++ b/tools/container-selfcheck/probe8.c @@ -0,0 +1,144 @@ +/* probe8.c - fork 路径各变体的 errno 定位(静态、裸 syscall) + * Build: clang --target=x86_64-linux-android24 -nostdlib -static -O1 -o probe8 probe8.c + */ +typedef long i64; +typedef unsigned long u64; + +#if defined(__x86_64__) +static inline i64 sc6(i64 n, i64 a1, i64 a2, i64 a3, i64 a4, i64 a5, i64 a6) +{ + i64 ret; + register i64 r10 __asm__("r10") = a4; + register i64 r8 __asm__("r8") = a5; + register i64 r9 __asm__("r9") = a6; + __asm__ __volatile__("syscall" : "=a"(ret) + : "a"(n), "D"(a1), "S"(a2), "d"(a3), "r"(r10), "r"(r8), "r"(r9) + : "rcx", "r11", "memory"); + return ret; +} +#define SYS_write 1 +#define SYS_exit 60 +#define SYS_wait4 61 +#define SYS_clone 56 +#define SYS_fork 57 +#define SYS_vfork 58 +#define SYS_clone3 435 +#elif defined(__aarch64__) +static inline i64 sc6(i64 n, i64 a1, i64 a2, i64 a3, i64 a4, i64 a5, i64 a6) +{ + register i64 x8 __asm__("x8") = n; + register i64 x0 __asm__("x0") = a1; + register i64 x1 __asm__("x1") = a2; + register i64 x2 __asm__("x2") = a3; + register i64 x3 __asm__("x3") = a4; + register i64 x4 __asm__("x4") = a5; + register i64 x5 __asm__("x5") = a6; + __asm__ __volatile__("svc #0" : "+r"(x0) + : "r"(x8), "r"(x1), "r"(x2), "r"(x3), "r"(x4), "r"(x5) : "memory"); + return x0; +} +#define SYS_write 64 +#define SYS_exit 93 +#define SYS_wait4 260 +#define SYS_clone 220 +#define SYS_clone3 435 +#define SYS_fork 0 /* 不存在 */ +#endif + +static i64 sc1(i64 n, i64 a) { return sc6(n, a, 0, 0, 0, 0, 0); } +static i64 sc2(i64 n, i64 a, i64 b) { return sc6(n, a, b, 0, 0, 0, 0); } +static i64 sc4(i64 n, i64 a, i64 b, i64 c, i64 d) { return sc6(n, a, b, c, d, 0, 0); } +static i64 sc0(i64 n) { return sc6(n, 0, 0, 0, 0, 0, 0); } + +static i64 sc3w(const char *s, i64 n) { return sc6(SYS_write, 1, (i64)s, n, 0, 0, 0); } +static void put(const char *s) { i64 n = 0; while (s[n]) n++; sc3w(s, n); } +static void putnum(i64 v) +{ + char b[24]; int i = 24, neg = v < 0; + unsigned long u = neg ? (unsigned long)(-v) : (unsigned long)v; + if (v == 0) { put("0"); return; } + b[--i] = 0; + while (u) { b[--i] = '0' + (u % 10); u /= 10; } + if (neg) b[--i] = '-'; + put(&b[i]); +} +static void show(const char *n, i64 r) +{ + put(" "); put(n); put(" = "); putnum(r); + if (r == -38) put(" [ENOSYS 被平台拒绝]"); + else if (r == -1) put(" [EPERM]"); + else if (r > 0) put(" [成功]"); + put("\n"); +} + +void prog_main(void); +#if defined(__x86_64__) +__asm__(".globl _start\n_start:\n andq $-16, %rsp\n call prog_main\n" + " movl $60, %eax\n xorl %edi, %edi\n syscall\n"); +#else +__asm__(".globl _start\n_start:\n bl prog_main\n mov x0, #0\n mov x8, #93\n svc #0\n"); +#endif + +#define SIGCHLD_ 17 +#define CLONE_VM_ 0x00000100 +#define CLONE_VFORK_ 0x00004000 + +struct clone_args { + u64 flags, pidfd, child_tid, parent_tid, exit_signal, + stack, stack_size, tls, set_tid, set_tid_size, cgroup; +}; + +void prog_main(void) +{ + i64 r; + struct clone_args ca; + + put("=== probe8: fork 路径变体(静态探针,量 proot 改写后的裸行为)===\n"); + + /* 1. classic clone(SIGCHLD) —— 最标准的 fork 实现 */ + r = sc6(SYS_clone, SIGCHLD_, 0, 0, 0, 0, 0); + if (r == 0) { sc1(SYS_exit, 0); for (;;) {} } + show("clone(SIGCHLD)", r); + if (r > 0) sc4(SYS_wait4, r, 0, 0, 0); + + /* 2. vfork 语义:CLONE_VM|CLONE_VFORK */ + r = sc6(SYS_clone, CLONE_VM_ | CLONE_VFORK_ | SIGCHLD_, 0, 0, 0, 0, 0); + if (r == 0) { sc1(SYS_exit, 0); for (;;) {} } + show("clone(VM|VFORK|SIGCHLD)", r); + if (r > 0) sc4(SYS_wait4, r, 0, 0, 0); + + /* 3. clone3(flags=SIGCHLD) */ + { + int i; char *p = (char *)&ca; + for (i = 0; i < (int)sizeof(ca); i++) p[i] = 0; + } + ca.flags = SIGCHLD_; + r = sc2(SYS_clone3, (i64)&ca, sizeof(ca)); + if (r == 0) { sc1(SYS_exit, 0); for (;;) {} } + show("clone3(flags=SIGCHLD)", r); + if (r > 0) sc4(SYS_wait4, r, 0, 0, 0); + + /* 4. clone3(flags=CLONE_VM|CLONE_VFORK|SIGCHLD) */ + ca.flags = CLONE_VM_ | CLONE_VFORK_ | SIGCHLD_; + r = sc2(SYS_clone3, (i64)&ca, sizeof(ca)); + if (r == 0) { sc1(SYS_exit, 0); for (;;) {} } + show("clone3(VM|VFORK|SIGCHLD)", r); + if (r > 0) sc4(SYS_wait4, r, 0, 0, 0); + +#if defined(__x86_64__) + /* 5. 传统 fork / vfork 系统调用号 */ + r = sc0(SYS_fork); + if (r == 0) { sc1(SYS_exit, 0); for (;;) {} } + show("fork(57)", r); + if (r > 0) sc4(SYS_wait4, r, 0, 0, 0); + + r = sc0(SYS_vfork); + if (r == 0) { sc1(SYS_exit, 0); for (;;) {} } + show("vfork(58)", r); + if (r > 0) sc4(SYS_wait4, r, 0, 0, 0); +#endif + + put("=== done ===\n"); + sc1(SYS_exit, 0); + for (;;) {} +} diff --git a/tools/patches/libandroid-shmem-runtime-ashmem.patch b/tools/patches/libandroid-shmem-runtime-ashmem.patch new file mode 100644 index 0000000..790eaf4 --- /dev/null +++ b/tools/patches/libandroid-shmem-runtime-ashmem.patch @@ -0,0 +1,76 @@ +diff --git a/shmem.c b/shmem.c +index f95fc07..28c8415 100644 +--- a/shmem.c ++++ b/shmem.c +@@ -111,13 +111,45 @@ static int ancil_recv_fd(int sock) + return ((int*) CMSG_DATA(cmsg))[0]; + } + ++/* --- local patch (code_editor): choose the ashmem backend at RUNTIME ------ ++ * Android 11+ denies /dev/ashmem to app processes (measured on Android 16: ++ * open("/dev/ashmem", O_RDWR) -> EACCES), while libandroid's ASharedMemory_* ++ * (memfd-backed) works. Upstream picks the backend at compile time with ++ * __ANDROID_API__ >= 26, which would force API 26+ on every user of this ++ * library; resolving it via dlopen/dlsym keeps API 24 devices working (there ++ * the /dev/ashmem path is the permitted one). ++ */ ++#include ++ ++static int (*p_ASharedMemory_create)(const char *, size_t); ++static int (*p_ASharedMemory_getSize)(int); ++static int ashmem_backend_checked; ++static int ashmem_backend_ok; ++ ++static void ashmem_backend_init(void) ++{ ++ void *h; ++ ++ if (ashmem_backend_checked) ++ return; ++ ashmem_backend_checked = 1; ++ ++ h = dlopen("libandroid.so", RTLD_NOW | RTLD_LOCAL); ++ if (h == NULL) ++ return; ++ ++ p_ASharedMemory_create = (int (*)(const char *, size_t))dlsym(h, "ASharedMemory_create"); ++ p_ASharedMemory_getSize = (int (*)(int))dlsym(h, "ASharedMemory_getSize"); ++ if (p_ASharedMemory_create != NULL && p_ASharedMemory_getSize != NULL) ++ ashmem_backend_ok = 1; ++} ++ + static int ashmem_get_size_region(int fd) + { +-#if __ANDROID_API__ >= 26 +- return ASharedMemory_getSize(fd); +-#else ++ ashmem_backend_init(); ++ if (ashmem_backend_ok) ++ return p_ASharedMemory_getSize(fd); + return TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_GET_SIZE, NULL)); +-#endif + } + + /* +@@ -129,9 +161,10 @@ static int ashmem_get_size_region(int fd) + */ + static int ashmem_create_region(char const* name, size_t size) + { +-#if __ANDROID_API__ >= 26 +- return ASharedMemory_create(name, size); +-#else ++ ashmem_backend_init(); ++ if (ashmem_backend_ok) ++ return p_ASharedMemory_create(name, size); ++ + // From https://android.googlesource.com/platform/system/core/+/master/libcutils/ashmem-dev.c + int fd = open("/dev/ashmem", O_RDWR); + if (fd < 0) return fd; +@@ -150,7 +183,6 @@ static int ashmem_create_region(char const* name, size_t size) + error: + close(fd); + return ret; +-#endif + } + + static void ashv_check_pid() diff --git a/tools/patches/proot-legacy-syscalls.patch b/tools/patches/proot-legacy-syscalls.patch new file mode 100644 index 0000000..1f15026 --- /dev/null +++ b/tools/patches/proot-legacy-syscalls.patch @@ -0,0 +1,397 @@ +warning: in the working copy of 'src/syscall/seccomp.c', LF will be replaced by CRLF the next time Git touches it +warning: in the working copy of 'src/syscall/legacy.c', LF will be replaced by CRLF the next time Git touches it +diff --git a/src/GNUmakefile b/src/GNUmakefile +index 5ade279..4a85331 100644 +--- a/src/GNUmakefile ++++ b/src/GNUmakefile +@@ -46,6 +46,7 @@ OBJECTS += \ + syscall/enter.o \ + syscall/exit.o \ + syscall/sysnum.o \ ++ syscall/legacy.o \ + syscall/socket.o \ + syscall/heap.o \ + syscall/rlimit.o \ +@@ -280,4 +281,4 @@ ifdef PROOT_UNBUNDLE_LOADER + ifdef HAS_LOADER_32BIT + $(INSTALL) -D loader/loader-m32 $(PROOT_UNBUNDLE_LOADER)/loader32 + endif +-endif ++endif +\ No newline at end of file +diff --git a/src/syscall/enter.c b/src/syscall/enter.c +index 93f4306..0f72da3 100644 +--- a/src/syscall/enter.c ++++ b/src/syscall/enter.c +@@ -79,6 +79,7 @@ + #include "path/binding.h" + #include "path/temp.h" + #include "arch.h" ++#include "syscall/legacy.h" + + /* Older kernel headers may lack these. */ + #ifndef CLONE_NEWTIME +@@ -1837,6 +1838,9 @@ int translate_syscall_enter(Tracee *tracee) + if (status > 0) + return 0; + ++ /* Modernize legacy syscalls that Android's app seccomp policy denies. */ ++ translate_legacy_syscall(tracee); ++ + /* Translate input arguments. */ + syscall_number = get_sysnum(tracee, ORIGINAL); + switch (syscall_number) { +@@ -2869,4 +2873,4 @@ end: + status = status2; + + return status; +-} ++} +\ No newline at end of file +diff --git a/src/syscall/legacy.c b/src/syscall/legacy.c +new file mode 100644 +index 0000000..1e6dcf1 +--- /dev/null ++++ b/src/syscall/legacy.c +@@ -0,0 +1,298 @@ ++/* -*- c-set-style: "K&R"; c-basic-offset: 8 -*- */ ++/* ++ * Legacy SysV-era syscall modernization for Android app processes. ++ * ++ * WHY THIS FILE EXISTS ++ * -------------------- ++ * Android installs a seccomp filter into every application process that denies ++ * the legacy spelling of several syscalls (they are not used by bionic): ++ * ++ * poll(2) -> ENOSYS ++ * select(2) -> ENOSYS ++ * epoll_wait(2) -> ENOSYS ++ * pipe(2), dup2(2) ++ * clone(CLONE_VM|CLONE_VFORK|...) (vfork semantics) ++ * ++ * arm64 guests never notice: the (asm-generic) syscall table has no poll/ ++ * select/epoll_wait at all, so musl/glibc there issue ppoll/pselect6/ ++ * epoll_pwait/pipe2/dup3 and fork() via clone(SIGCHLD). ++ * ++ * x86_64 keeps those entries in its syscall table, and libc prefers them ++ * whenever the architecture defines them - musl does so with plain ++ * "#ifdef SYS_poll" style checks - so an x86_64 guest inside an app process ++ * gets ENOSYS for calls that work perfectly on arm64. Worst case, the stub ++ * resolver calls poll() from *inside libc*, where neither LD_PRELOAD nor any ++ * guest-side shim can reach it: DNS then fails and apk reports the famously ++ * misleading "temporary error (try again later)". ++ * ++ * Rewriting the calls here, in the tracer and before the kernel executes them, ++ * fixes all of that for *every* guest program - static or dynamic, musl or ++ * glibc, and including calls issued from inside libc - which is exactly the ++ * "make x86_64 behave like arm64" property we want. ++ * ++ * The replacements are semantically equivalent: ++ * poll(fds,n,ms) -> ppoll(fds,n,&ts,NULL) ++ * select(n,r,w,e,tv) -> pselect6(n,r,w,e,&ts,NULL) ++ * epoll_wait(e,ev,m,ms) -> epoll_pwait(e,ev,m,ms,NULL,0) ++ * pipe(fds) -> pipe2(fds,0) ++ * dup2(o,n) -> dup3(o,n,0) [o != n; dup2(o,o) is left alone] ++ * fork()/vfork() -> clone(SIGCHLD) ++ * clone(VM|VFORK|...) -> clone(... & ~(CLONE_VM|CLONE_VFORK)) ++ * ++ * Not handled on purpose: dup2(o,o) would need a return-value fixup at syscall ++ * exit; such a call is a no-op and programs normally guard it with "o != n". ++ */ ++ ++#include ++#include ++#include ++#include ++ ++#include "syscall/legacy.h" ++#include "syscall/sysnum.h" ++#include "tracee/mem.h" ++#include "tracee/reg.h" ++#include "tracee/tracee.h" ++ ++#ifndef CLONE_VM ++#define CLONE_VM 0x00000100 ++#endif ++#ifndef CLONE_VFORK ++#define CLONE_VFORK 0x00004000 ++#endif ++#ifndef SIGCHLD ++#define SIGCHLD 17 ++#endif ++#ifndef CLONE_PIDFD ++#define CLONE_PIDFD 0x00001000 ++#endif ++ ++struct legacy_timeval { ++ int64_t tv_sec; ++ int64_t tv_usec; ++}; ++ ++struct legacy_timespec { ++ int64_t tv_sec; ++ int64_t tv_nsec; ++}; ++ ++/** ++ * Write a timespec into the tracee's stack and return its address (0 on error). ++ */ ++static word_t write_timespec(Tracee *tracee, int64_t sec, int64_t nsec) ++{ ++ struct legacy_timespec ts; ++ word_t address; ++ ++ ts.tv_sec = sec; ++ ts.tv_nsec = nsec; ++ ++ address = alloc_mem(tracee, sizeof(ts)); ++ if (address == 0) ++ return 0; ++ ++ if (write_data(tracee, address, &ts, sizeof(ts)) < 0) ++ return 0; ++ ++ return address; ++} ++ ++/** ++ * poll(fds, nfds, timeout_ms) -> ppoll(fds, nfds, &ts, NULL, 0) ++ */ ++static void rewrite_poll(Tracee *tracee) ++{ ++ int timeout_ms = (int) peek_reg(tracee, CURRENT, SYSARG_3); ++ word_t address = 0; ++ ++ if (timeout_ms >= 0) { ++ address = write_timespec(tracee, ++ timeout_ms / 1000, ++ (int64_t)(timeout_ms % 1000) * 1000000); ++ if (address == 0) ++ return; /* give up: let the original syscall fail */ ++ } ++ ++ poke_reg(tracee, SYSARG_3, address); /* NULL == wait forever */ ++ poke_reg(tracee, SYSARG_4, 0); /* sigmask */ ++ poke_reg(tracee, SYSARG_5, 0); /* sigsetsize */ ++ ++ set_sysnum(tracee, PR_ppoll); ++} ++ ++/** ++ * select(nfds, r, w, e, timeval) -> pselect6(nfds, r, w, e, &ts, NULL) ++ */ ++static void rewrite_select(Tracee *tracee) ++{ ++ word_t timeval_ptr = peek_reg(tracee, CURRENT, SYSARG_5); ++ word_t address = 0; ++ ++ if (timeval_ptr != 0) { ++ struct legacy_timeval tv; ++ ++ if (read_data(tracee, &tv, timeval_ptr, sizeof(tv)) < 0) ++ return; ++ if (tv.tv_sec < 0 || tv.tv_usec < 0 || tv.tv_usec >= 1000000) ++ return; /* invalid: let the kernel reject it */ ++ ++ address = write_timespec(tracee, tv.tv_sec, tv.tv_usec * 1000); ++ if (address == 0) ++ return; ++ } ++ ++ poke_reg(tracee, SYSARG_5, address); ++ poke_reg(tracee, SYSARG_6, 0); /* sigmask == NULL */ ++ ++ set_sysnum(tracee, PR_pselect6); ++} ++ ++/** ++ * epoll_wait(epfd, events, maxevents, timeout_ms) ++ * -> epoll_pwait(epfd, events, maxevents, timeout_ms, NULL, 0) ++ */ ++static void rewrite_epoll_wait(Tracee *tracee) ++{ ++ poke_reg(tracee, SYSARG_5, 0); /* sigmask */ ++ poke_reg(tracee, SYSARG_6, 0); /* sigsetsize */ ++ ++ set_sysnum(tracee, PR_epoll_pwait); ++} ++ ++/** ++ * Drop vfork shared-memory semantics (clone(CLONE_VM|CLONE_VFORK)) down to a ++ * plain clone(SIGCHLD). POSIX allows vfork to behave like fork; the ++ * CLONE_VM|CLONE_VFORK pair is what the app filter rejects, which is how ++ * busybox ash ends up reporting "can't fork: Function not implemented" for ++ * every subshell and background job. ++ */ ++static void sanitize_clone_flags(Tracee *tracee) ++{ ++ word_t flags; ++ ++ flags = peek_reg(tracee, CURRENT, SYSARG_1); ++ if ((flags & (CLONE_VM | CLONE_VFORK)) == (CLONE_VM | CLONE_VFORK)) ++ poke_reg(tracee, SYSARG_1, ++ flags & ~(word_t)(CLONE_VM | CLONE_VFORK)); ++} ++ ++/** ++ * clone3() -> clone(). Android's app seccomp policy rejects clone3() outright ++ * (its flexible argument struct cannot be filtered), so sanitizing the flags is ++ * not enough: the call must become the classic clone() with the same ++ * semantics. This is what lets fork() work for a guest whose libc prefers ++ * clone3 (musl), which otherwise gets a plain ENOSYS errno and reports ++ * "can't fork: Function not implemented". ++ */ ++struct legacy_clone_args { ++ uint64_t flags; ++ uint64_t pidfd; ++ uint64_t child_tid; ++ uint64_t parent_tid; ++ uint64_t exit_signal; ++ uint64_t stack; ++ uint64_t stack_size; ++ uint64_t tls; ++}; ++ ++static void rewrite_clone3(Tracee *tracee) ++{ ++ word_t args_ptr = peek_reg(tracee, CURRENT, SYSARG_1); ++ struct legacy_clone_args a; ++ uint64_t flags; ++ word_t parent_tid; ++ ++ if (args_ptr == 0) ++ return; ++ if (read_data(tracee, &a, args_ptr, sizeof(a)) < 0) ++ return; ++ ++ flags = a.flags; ++ if ((flags & (CLONE_VM | CLONE_VFORK)) == (CLONE_VM | CLONE_VFORK)) ++ flags &= ~(uint64_t)(CLONE_VM | CLONE_VFORK); ++ ++ /* The classic ABI carries the exit signal in the low byte of flags. */ ++ flags = (flags & ~(uint64_t)0xff) | (a.exit_signal & 0xff); ++ ++ /* With CLONE_PIDFD the pidfd is written through the parent_tid slot. */ ++ parent_tid = (flags & CLONE_PIDFD) != 0 ? (word_t) a.pidfd +warning: in the working copy of 'src/syscall/legacy.h', LF will be replaced by CRLF the next time Git touches it ++ : (word_t) a.parent_tid; ++ ++ poke_reg(tracee, SYSARG_1, (word_t) flags); ++ /* classic clone() wants the *top* of the child stack */ ++ poke_reg(tracee, SYSARG_2, (word_t)(a.stack + a.stack_size)); ++ poke_reg(tracee, SYSARG_3, parent_tid); ++ poke_reg(tracee, SYSARG_4, (word_t) a.child_tid); ++ poke_reg(tracee, SYSARG_5, (word_t) a.tls); ++ ++ set_sysnum(tracee, PR_clone); ++} ++ ++/** ++ * fork()/vfork() themselves -> clone(SIGCHLD). ++ */ ++static void rewrite_fork(Tracee *tracee) ++{ ++ poke_reg(tracee, SYSARG_1, SIGCHLD); ++ poke_reg(tracee, SYSARG_2, 0); ++ poke_reg(tracee, SYSARG_3, 0); ++ poke_reg(tracee, SYSARG_4, 0); ++ poke_reg(tracee, SYSARG_5, 0); ++ ++ set_sysnum(tracee, PR_clone); ++} ++ ++/** ++ * Entry point, called from translate_syscall_enter() before the regular ++ * argument translation: only the syscall number and its raw arguments change. ++ */ ++void translate_legacy_syscall(Tracee *tracee) ++{ ++ switch (get_sysnum(tracee, CURRENT)) { ++ case PR_poll: ++ rewrite_poll(tracee); ++ break; ++ ++ case PR_select: ++ rewrite_select(tracee); ++ break; ++ ++ case PR_epoll_wait: ++ rewrite_epoll_wait(tracee); ++ break; ++ ++ case PR_pipe: ++ poke_reg(tracee, SYSARG_2, 0); ++ set_sysnum(tracee, PR_pipe2); ++ break; ++ ++ case PR_dup2: { ++ word_t oldfd = peek_reg(tracee, CURRENT, SYSARG_1); ++ word_t newfd = peek_reg(tracee, CURRENT, SYSARG_2); ++ ++ if (oldfd == newfd) ++ break; /* see the note at the top of this file */ ++ ++ poke_reg(tracee, SYSARG_3, 0); ++ set_sysnum(tracee, PR_dup3); ++ break; ++ } ++ ++ case PR_fork: ++ case PR_vfork: ++ rewrite_fork(tracee); ++ break; ++ ++ case PR_clone: ++ sanitize_clone_flags(tracee); ++ break; ++ ++ case PR_clone3: ++ rewrite_clone3(tracee); ++ break; ++ ++ default: ++ break; ++ } ++} +diff --git a/src/syscall/legacy.h b/src/syscall/legacy.h +new file mode 100644 +index 0000000..7da22ac +--- /dev/null ++++ b/src/syscall/legacy.h +@@ -0,0 +1,15 @@ ++/* -*- c-set-style: "K&R"; c-basic-offset: 8 -*- */ ++/* ++ * Modernize legacy syscalls that Android's app seccomp policy denies on ++ * x86_64 (poll/select/epoll_wait/pipe/dup2 and vfork-style clone). ++ * See syscall/legacy.c for the rationale. ++ */ ++ ++#ifndef LEGACY_H ++#define LEGACY_H ++ ++#include "tracee/tracee.h" ++ ++extern void translate_legacy_syscall(Tracee *tracee); ++ ++#endif /* LEGACY_H */ +diff --git a/src/syscall/seccomp.c b/src/syscall/seccomp.c +index 2f8930e..ed3f661 100644 +--- a/src/syscall/seccomp.c ++++ b/src/syscall/seccomp.c +@@ -342,6 +342,16 @@ static FilteredSysnum proot_sysnums[] = { + { PR_chroot, 0 }, + { PR_clone, 0 }, + { PR_clone3, 0 }, ++ /* Legacy syscalls modernized in syscall/legacy.c. They must be listed ++ * here, otherwise the seccomp accelerator lets them run natively and ++ * translate_legacy_syscall() never sees them. */ ++ { PR_poll, 0 }, ++ { PR_select, 0 }, ++ { PR_epoll_wait, 0 }, ++ { PR_pipe, 0 }, ++ { PR_dup2, 0 }, ++ { PR_fork, 0 }, ++ { PR_vfork, 0 }, + { PR_close, 0 }, + { PR_connect, 0 }, + { PR_creat, 0 },