This commit is contained in:
LZX committed 2026-09-13 18:05:41 +08:00
1 parent e932c60dbd
commit 55f35673df
21 files changed
+1430 -3

No files matched your search

+22
View File
@@ -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`。
+64
View File
@@ -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/`)。
+260
View File
@@ -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/<abi>/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)漏了
# <string.h>,老 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 <unistd.h>", "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\<abi>\libproot.so" -ForegroundColor Cyan
+91
View File
@@ -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="<app cache>/" ── 上游引用 bionic 未定义的 _PATH_TMP,
# 它是命名 shm key 的 symlink 存放位置
# -Wno-implicit-function-declaration ── 上游漏了 <fcntl.h>(老 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
+8 -1
View File
@@ -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
+168
View File
@@ -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 */
+144
View File
@@ -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 (;;) {}
}
@@ -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 <dlfcn.h>
+
+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()
+397
View File
@@ -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 <errno.h>
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+#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 },