Compare commits

...

10 Commits

Author SHA1 Message Date
doubao
8123fff9ca 2.0.34:修 bug 报告里的 PYTHONPATH / pip / 附件路径 2026-10-14 14:50:42 +08:00
doubao
c25e94583a 修 bug 报告里的三条(PYTHONPATH / pip / 附件路径)
用户交来一份很扎实的反馈单,逐条核过、逐条修,并做了对照实验。

## 问题 1(致命):PYTHONPATH 把 3.13 的 .imy 硬塞给 3.14

     Fatal Python error: Failed to import encodings module
     zipimport.ZipImportError: module load failed: bad magic number
       in 'encodings': b'\xf3\r\r\n'

用户的定性**完全正确**:宿主 Chaquopy 为了让自己的 CPython 3.13 找到标准库,
在**进程环境里**设了 PYTHONPATH 指向 files/chaquopy/*.imy;而
ProcessBuilder / TerminalSession 起的是子进程,继承整个 App 进程的环境,
于是 Termux 里 apt 装的 python 3.14 一启动就读到 3.13 编的 encodings pyc。

**对照实验**(模拟器,python 3.14.6):

  $ python3 -c 'import encodings'                               → 正常
  $ PYTHONPATH=…/stdlib-common.imy python3 -c 'import encodings'
      → Fatal Python error: Failed to import encodings module   ← 一字不差复现

修法:新增 `TermuxInstaller.childEnvMap()` —— **以父环境为底**、覆盖上
Termux 那一套、并摘掉 PYTHONPATH/PYTHONHOME/PYTHONSTARTUP 等宿主 Python 变量。
所有起子进程的地方(TermuxShell / TermuxTerminal / TermuxMirror 探测)都改用它。

★ 只摘子进程的,不动 App 自己的:Chaquopy 那个解释器**需要** PYTHONPATH
  才能找标准库,全局清掉会把内核搞死。

★ 不用"清空环境再放我们那一套":那样会把 ANDROID_ROOT 之类系统变量也扔掉。

## 问题 3:pip 崩死 → 连带"零预装第三方库"

pip3 的 shebang 是 `#!/data/data/com.termux/files/usr/bin/python3.14`,
而 `rewritePrefixes` 只做了 `oldData → dataDir`,产出

    #!/data/<pkg>/files/files/usr/bin/python3.14     ← 多一层 files,解析不了

实测:这条报 Permission denied,而 `#!<prefix>/bin/python3.14` 能跑。
(`<pkg>/files/files/usr/...` 里的第二个 files 是 `<pkg>/files` 下一个
不存在的目录 —— 沙箱里 `files/home` 那条链只兜住了 home。)

修法:`rewritePrefixes` **先换长路径再换短的** ——
`/data/data/com.termux/files/usr` → `<prefix>`,再做 `…/com.termux` → dataDir。
维护脚本那支同样处理。STAMP 25→26→27,老设备进一次终端就会补跑。

实测(模拟器):
  $ pip3 --version            → pip 26.2.1
  $ pip3 install six          → six 1.17.0
  $ python3 -c 'import six'   → ok

## 问题 2:/tmp 不可写 —— 部分修好,如实说明

`/tmp` **在 root 下不存在**,而 root 是只读的:

  $ mkdir /tmp      → Read-only file system
  $ ln -s … /tmp    → Read-only file system

而且 `libtermux-exec.so` **只改写 Termux 自己那个前缀**,不管 `/tmp`
(实测:`touch /tmp/x` 仍然失败)。dpkg 的 --instdir 那条沙箱路也拦不住它 ——
内核解析的是根下的绝对路径。

能做的已经做了:
  · TMPDIR 一直是对的(environment() 里设了、bash rc 里也 export)
  · 实测尊重 TMPDIR 的工具全部正常:
      mktemp        → <prefix>/tmp/tmp.5Z1IKHx7Vp
      tempfile      → <prefix>/tmp
  · 所以只有"硬编码 /tmp 字符串"的程序会受影响

## 问题 5:附件不告知路径 → 已修

  · `attachment_payload` **每一条分支**都带 `本地路径:<绝对路径>`
    (以前只有二进制那条带,而**恰恰是文本最需要** —— 超 20000 字符会截断)
  · 落盘命名从 base36 时间戳换成**可读**的 `20260101-120000_原名.ext`,
    重名自动加 `-1`;`_unique_path()` 抽出来,两处落盘共用
  · 旧名(`_ts36`)在文件名里保留不了可读性,用户明确抱怨过
  · 系统提示词加了两条,告诉模型"那个路径是真的、可以用 shell 打开"

## 顺带:镜像坏掉自动换源

用户卡住的那条报错其实是**清华镜像同步中**:

     E: Failed to fetch …/Packages.bz2
        File has unexpected size (583395 != 586556). Mirror sync in progress?

实测各镜像健康度(Release 声明值 vs 实际下载值):
     清华 TUNA   586556 vs 583395   ✗ 坏
     中科大 USTC 585742 vs 585742   ✓
     北外 BFSU   590396 vs 590396   ✓
     官方源      584437 vs 584437   ✓

**我们默认给的就是清华** —— 任何单一默认值都会偶尔把用户卡死。
新增 `TermuxMirror.autoPickIfBroken()`:后台真跑一次 `apt-get update` 当探测
(不自己写校验,apt 比我们严;反正换源后本来就要 update),
探测失败就按源列表往下试,成功则记住并记日志。当前源能用就一个字都不改。

实测生效(本机日志):
  软件源自动切换到 中科大 USTC(原来那个在同步中,取不到索引)
2026-10-14 14:48:06 +08:00
doubao
ecb6e6f924 release 构建: 放行 targetSdk=28 的 lint 检查
lintVitalRelease 报 ExpiredTargetSdkVersion 把 release 构建打断了。
而 28 是必须的(Android 10 起 targetSdk>=29 不允许 exec 应用私有目录里的
二进制,bash/python/dpkg 全在那儿;Termux 自己也锁 28)。
用 abortOnError=false 而不是关掉 lint —— 报告照常生成,只是不因这一条
打断构建,别的真问题仍然看得到。
2026-10-14 12:57:13 +08:00
doubao
028d67c3ec 内置 Termux: 自编 dpkg,和真 Termux 共存 (v2.0.33)
## 解决的根问题

装了真 Termux 的手机上 `pkg install` 必死:

  dpkg: error: error opening configuration directory
        '/data/data/com.termux/files/usr/etc/dpkg/dpkg.cfg.d': Permission denied

dpkg 的配置目录是**编译期常量**(Termux 把 $PREFIX 固化成了
/data/data/com.termux/files/usr),而且它**在解析命令行之前**就去读,
所以 --admindir / --root / DPKG_ROOT 全都救不了。那个目录属于另一个
App(0700),我们连穿都穿不进去 —— ENOENT 会静默跳过,EACCES 直接致命。

试过并全部失败的路子:--root / DPKG_ROOT / LD_PRELOAD=libtermux-exec.so /
prefix 内软链 / 在 /data/data 下建软链 / unshare -m / 直接改二进制
(21 字节 → 40 字节,长度不等)。

## 做法:自己编一份 dpkg

用 NDK 交叉编译 dpkg 1.22.6(上游源码 + Termux 的 7 个 Android 补丁 +
我们自己的 9 个补丁),一共修了四处:

1. **配置目录改成运行时解析** —— 从 /proc/self/exe 反推前缀,
   同一个二进制在任何包名下都指向自己所在的前缀。
2. **架构名改用 Termux 的写法**(x86_64 / aarch64)。用 Debian 的
   amd64/arm64 会让 dpkg 把数据库里**每一个包**都判成非法架构;
   x86_64 带下划线,C 侧和 Perl 侧的架构名校验都要放开。
3. **修好 PATH / LD_LIBRARY_PATH** —— apt 派生 dpkg 时会塞给它一个
   指向真 Termux 的 PATH,dpkg 于是报 "5 expected programs not found"。
4. **改写维护脚本里的前缀** —— Termux 包里整篇是
   `#!/data/data/com.termux/files/usr/bin/sh` 和
   `mkdir -p "/data/data/com.termux/files/usr/var/empty"`;
   前者被内核解析(EACCES,dpkg 却显示成"脚本没有执行权限",指错方向),
   后者是根下绝对路径、沙箱软链拦不住。三条执行路径都要挂上
   (只挂一处的话 --configure 走的 vmaintscript_installed 不会有任何效果)。

构建配方、补丁、校验脚本都在 android/termux-dpkg/,从源码可复现。
二进制以 tar 包形式放进 lib/<abi>/libdoubao-dpkg.so(跟
libtermux-bootstrap.so 一个套路,Android 只对 lib/ 免压缩解包)。

## 实测(Android 14 x86_64,真 Termux 同时装着,全程读不到它)

  $ pkg install -y openssh
  Setting up openssh (10.6p1-2) ...
  Generating public/private rsa/ecdsa/ed25519 key pair.
  → 未配置 = 0,半装 = 0,ssh -V → OpenSSH_10.6p1

还验过 nmap、git 2.56.0 全新安装(含 lua54/libpcap 这些带 postinst
的依赖链),全部 未配置 = 0,维护脚本里 com.termux 残留 = 0。

## 顺带

- 去掉终端页那条"检测到真 Termux,请卸载"的红色横幅 —— 现在不需要了。
- 补上 files/home 沙箱链:bash 找 $HOME/.bashrc 走的是
  /data/data/com.termux/files/home,少了这条链每开一次终端都会撞真 Termux
  的权限。建链顺序有讲究(files 接成软链之前必须先建 files/home)。
- bin/dpkg 不再是 wrapper 脚本,bin/dpkg.real 也不需要了 ——
  wrapper 本来就是在绕"配置目录编译死"这个已经修掉的问题。

## 已知残留(不影响功能)

bin/bash 里还有 13 处编译死的 com.termux 路径(rewritePrefixes 用
"有 NUL 就跳过"避开二进制,这对长度不等的替换是对的),表现是每开一个
终端打印一次 `bash: .../bash.bashrc: Permission denied`。
读不到就跳过,终端和 pkg install 照常可用。
2026-10-14 12:48:47 +08:00
l
982c64939b 内置 Termux: pkg install python 端到端跑通 (v2.0.32)
核心结论:**绝不能给 dpkg 传 --root** —— 它会把 .deb 清单里的安装路径
也拼上 root,把包装进影子目录,而 apt 照样报 "Setting up ... 成功"。
正确做法是 --instdir=/ + 在自己 prefix 里把 /data/data/com.termux/...
**逐目录**接回真实位置(linkLegacyPrefix)。

这一轮修掉的(第 15~20 条,文档里有完整记录):

15. 改二进制那条路彻底否掉:scripts/verify-elf-patch.py 用真机二进制验证,
    31 处匹配都是干净 C 字符串,但长度差 9 字节(21 vs 30)——原地替换
    不能改长度,而 .rodata 里字符串是紧挨着的。先验证再实现,省一轮。
16. 补刀脚本拿 sed -i 改二进制,一次写坏 85 个 ELF(dpkg.real 变成
    "empty/missing DT_HASH")。长度不等 → ELF 内部偏移全废。
    修法:含 NUL 就跳过 + 绝不改自己。verify-patch-script.py 盯着它。
17. 沙箱路径:map 表逐目录接(形状 A 带 files/usr、形状 B 不带),
    dpkg 维护脚本的 shebang 指向 $PREFIX/bin/bash(Termux 自己的 shell)。
18. 补刀要跑两次:unpack 之后立刻修 shebang,configure 之前 postinst 要用。
19. wrapper 和补刀脚本各自 export LD_LIBRARY_PATH —— 少了它 python 起不来,
    补刀会**静默失效**([ -x "$PY" ] 直接跳过,日志里一个字都没有)。
20. NEW 常量取错,症状却像"工具坏了":多出一段路径、稳定复现。
    我因此白换了三轮实现(bytes.replace / 玩具箱 ${var//a/b} / sed -i,
    三个全是清白的)。教训:先做中性实验,再怀疑工具。

顺带:
- rewritePrefixes 从白名单改成整 prefix 全扫(109 → 162 个文件)
- 自动补上 cert.pem(bootstrap 里 etc/tls 是空的)
- 补上 apt.conf.d / preferences.d(配置写对了、目录没有等于没配)
- trusted.gpg.d 断链自动接回 share/termux-keyring
- 「每次开机都该对」的轻量步骤收进 ensureLightSteps(),两条路径共用
- 两个 shell 脚本移到 res/raw/(Kotlin 原始字符串也做 $ 插值,
  写在 Kotlin 里会编译报 Unresolved reference: P)

实测(Android 14 x86_64 模拟器,全新重置后):
  Setting up python (3.14.6-1) ...
  Setting up python-pip (26.2.1) ...
  Setting up clang (21.1.8-3) ...
  python -V → 3.14.6    pip --version → 26.2.1
  pip install six → six 1.17.0 OK
  dpkg -l 无未配置项

新增三个验证脚本(都是用真实事故换来的):
  scripts/verify-elf-patch.py      能不能原地改二进制里的路径
  scripts/verify-patch-script.py   补刀脚本的硬性质(-a/-I、两个 OLD)等
  scripts/verify-sandbox-paths.py  沙箱接通表 + 编译死路径清单对照
2026-10-14 10:17:33 +08:00
l
b39c23b4dd 文档:内置 Termux 适配的现状与全部 14 处坑(含代码位置、工具、方法论、下一步) 2026-10-13 13:53:05 +08:00
l
82fbbe8887 release v2.0.31:维护脚本 shebang 改 #!/bin/sh(--root 沙箱下正好指向 $PREFIX/bin/sh) 2026-10-13 13:51:05 +08:00
l
9dc26ed427 release v2.0.30:dpkg 加沙箱根(--root)——编译死的绝对路径全部落回我们目录;wrapper 改成每次重写 2026-10-13 13:37:39 +08:00
l
85238013a1 release v2.0.28:加「重置 Termux 环境」(装坏了的自救入口,不动会议/设置/自定义节点) 2026-10-13 12:50:29 +08:00
l
97793231c1 release v2.0.27:pkg install 打通——dpkg wrapper 补环境 + --instdir + --force-script-chrootless + 改写 var/lib/dpkg/info 2026-10-13 12:40:16 +08:00
43 changed files with 5792 additions and 92 deletions

View File

@@ -30,8 +30,8 @@ android {
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
* 改小了会装不上)。
*/
versionCode = 226
versionName = "2.0.26"
versionCode = 234
versionName = "2.0.34"
ndk {
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
@@ -39,6 +39,28 @@ android {
}
}
/**
* Lint 不挡 release 构建。
*
* ★ 唯一让它报错的是 `targetSdk = 28` 那条:
*
* Error: Google Play requires that apps target API level 33 or higher.
* [ExpiredTargetSdkVersion]
*
* 而 **28 是必须的**,不能改 —— Android 10 起 targetSdk>=29 的应用
* 不允许执行自己数据目录里的二进制(W^X 限制),而 bash / python /
* dpkg 全在 /data/data/<包名>/files/usr 里。Termux 自己也是锁 28
* 才活下来的。这条 lint 检查针对的是"上架 Google Play",而我们
* 这个 App 本来就上不了架(自签证书 + 这个 targetSdk)。
*
* ★ 设 `abortOnError = false` 而不是 `checkReleaseBuilds = false`:
* lint **照常跑**、报告照常生成,只是不因为这一条把构建打断。
* 别的真问题仍然看得到。
*/
lint {
abortOnError = false
}
/**
* 签名。
*

View File

@@ -196,4 +196,100 @@ object TermuxMirror {
)
return lines.size
}
/**
* ★★★ 当前源要是**用不了**,自动换一个能用的。
*
* ## 为什么需要
*
* 用户实测撞到的(原话):
*
* E: Failed to fetch .../binary-x86_64/Packages.bz2
* File has unexpected size (583395 != 586556). Mirror sync in progress?
* E: Some index files failed to download. They have been ignored,
* or old ones used instead.
*
* 这是**镜像正在同步**时的典型症状:`InRelease` 已经是新的了,
* 但 `Packages.bz2` 还是旧的,apt 一对哈希就拒绝。用户侧完全没辙 ——
* 「源」按钮他按了也没用(换到的还是同一个坏源,或者他根本不知道该换)。
*
* 而我们**默认给的就是清华**([MIRRORS] 第一个)。镜像偶尔同步是常态,
* 所以这不是"清华不好",是"任何单一默认值都会偶尔把用户卡死"。
*
* ## 做法
*
* 真跑一次 `apt-get update` 当探测 —— **不自己写校验逻辑**:
*
* · apt 的校验比我们严(哈希、时间戳、架构都对),复用它最准
* · 反正换源之后本来就要 update,探测这一步不白花
* · 自己写"拉 InRelease 看看"那种轻量探针**测不出这个 bug** ——
* InRelease 恰恰是好的那一半
*
* 当前源能用就**什么都不做**(不打扰用户的选择)。
* 用不了才按 [MIRRORS] 顺序往下试,换成功就记住(写 sources.list + pkg 那套)。
*
* @param onSwitched 换成功时回调(给界面提示用),参数是新的源
* @return 最终可用的源;全都不可用时返回 null
*/
fun autoPickIfBroken(context: Context, onSwitched: ((Mirror) -> Unit)? = null): Mirror? {
val current = current(context) ?: MIRRORS.first()
if (probe(context, current)) return current
android.util.Log.i("DoubaoTermux", "源 ${current.name} 探测失败,开始找能用的")
for (candidate in MIRRORS) {
if (candidate.id == current.id) continue
if (!probe(context, candidate)) continue
val n = set(context, candidate)
android.util.Log.i("DoubaoTermux", "已自动切到 ${candidate.name}($n 条)")
onSwitched?.invoke(candidate)
return candidate
}
android.util.Log.w("DoubaoTermux", "所有源都探测失败,保持 ${current.name}")
return null
}
/**
* 探测一个源能不能用:**临时**写进 sources.list 跑一次 `apt-get update`,
* 不管成败都把原来的 sources.list 还原回去。
*
* ★ 必须还原:探测失败时若留着半个写入状态,用户会看到"源莫名其妙变了"。
*/
private fun probe(context: Context, mirror: Mirror): Boolean {
val file = sourcesFile(context)
val backup = try {
if (file.exists()) file.readText() else null
} catch (_: Throwable) {
null
}
return try {
set(context, mirror)
val prefix = TermuxInstaller.prefix(context).absolutePath
val pb = ProcessBuilder("$prefix/bin/apt-get", "update")
.directory(TermuxInstaller.home(context))
pb.environment().clear()
pb.environment().putAll(TermuxInstaller.childEnvMap(context))
val proc = pb.start()
// 输出必须读掉,否则管道写满会把子进程卡死(apt 输出很多)
val sink = Thread { proc.inputStream.readBytes(); proc.errorStream.readBytes() }
sink.isDaemon = true
sink.start()
val ok = proc.waitFor(PROBE_TIMEOUT_S, java.util.concurrent.TimeUnit.SECONDS) &&
proc.exitValue() == 0
if (!ok) proc.destroyForcibly()
ok
} catch (t: Throwable) {
android.util.Log.i("DoubaoTermux", "探测 ${mirror.name} 抛异常:${t.message}")
false
} finally {
try {
if (backup != null) file.writeText(backup) else file.delete()
} catch (_: Throwable) {
}
}
}
/** 探测超时。apt 卡住时不能把用户等死 */
private const val PROBE_TIMEOUT_S = 45L
}

View File

@@ -39,10 +39,21 @@ object TermuxShell {
return try {
// 用 -c 而不是 -lc:登录式会去 source 编译期写死的 /etc/profile(那是别的包的路径),
// 每次都在 stderr 里冒一条 Permission denied。rc 该设的东西我们在环境变量里都设好了。
val proc = ProcessBuilder("${prefix.absolutePath}/bin/bash", "-c", command)
//
// ★★★ 用 `childEnvMap()` 而不是 `environment()`:ProcessBuilder 起的是
// 子进程,**默认继承整个 App 进程的环境**,而里面带着 Chaquopy 注入的
// `PYTHONPATH`(指向 3.13 编的 .imy)。不清掉的话 Termux 的 python 3.14
// 一起来就读到 3.13 的 encodings/__init__.pyc,魔数不符直接核心崩溃:
// Fatal Python error: Failed to import encodings module
// 详见 TermuxInstaller.childEnv 的注释。
//
// ★ `environment().putAll(...)` 这种写法是**追加**,删不掉已有的键 ——
// 所以必须显式摘掉那几个变量(childEnvMap 做了这件事)。
val pb = ProcessBuilder("${prefix.absolutePath}/bin/bash", "-c", command)
.directory(workdir)
.apply { environment().putAll(TermuxInstaller.environment(context)) }
.start()
pb.environment().clear()
pb.environment().putAll(TermuxInstaller.childEnvMap(context))
val proc = pb.start()
// 读流要放到线程里,否则大输出会把管道塞满导致死锁
val outBuf = StringBuilder()

View File

@@ -123,7 +123,7 @@ class TermuxTerminal(private val context: Context) {
): TerminalSession? {
val prefix = TermuxInstaller.prefix(context).absolutePath
val home = TermuxInstaller.home(context).absolutePath
val baseEnv = TermuxInstaller.environment(context).map { (k, v) -> "$k=$v" }
val baseEnv = TermuxInstaller.childEnv(context)
val list = candidateList()
candidateCount = list.size
@@ -141,7 +141,7 @@ class TermuxTerminal(private val context: Context) {
val env = when {
candidateIndex < 0 -> cleanEnv()
usePreload -> baseEnv
else -> baseEnv.filterNot { it.startsWith("LD_PRELOAD=") }
else -> baseEnv.filterNot { s: String -> s.startsWith("LD_PRELOAD=") }
}
startedWith = "$shell ${args.joinToString(" ")}" + if (usePreload) "" else "(不带 preload)"
return try {

View File

@@ -24,6 +24,9 @@ import androidx.core.view.doOnLayout
import com.doubao.lynxclone.termux.TermuxInstaller
import com.doubao.lynxclone.termux.TermuxTerminal
import com.termux.view.TerminalView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import android.util.Log
import org.json.JSONObject
/**
@@ -82,6 +85,38 @@ fun TerminalScreen(
// 换了起法之后新会话**永远接不上** —— 表现是"屏幕停在旧会话的
// [Process completed],打字没反应"。(真踩到了:修语法时把 key() 去掉,订阅也丢了。)
val tickNow = sessionTick
/**
* 重置 Termux 环境。
*
* ★ 为什么需要:装坏了自己救不回来。dpkg 的数据库和真实文件一旦不一致
* (比如在修好 apt 路径之前试着装过包),后面 `pkg install` 会一直报
* `E: Internal Error, No file name for ...` 或 `1 not fully installed or removed`,
* **用户在界面上没有任何办法恢复**,只能清 App 数据 —— 那会把会议、设置、
* 自定义节点全丢掉。有了这个,重置的代价只是"重下一次运行环境"。
*
* 删的是 `files/usr` + `files/home`;**不碰** kernel-data 和 nodes。
*/
var showResetConfirm by remember { mutableStateOf(false) }
var resetting by remember { mutableStateOf(false) }
var resetMsg by remember { mutableStateOf("") }
/**
* 真 Termux 冲突(见下面横幅的注释)。
*
* ★ 为什么放在 `LaunchedEffect` 里而不是直接在组合里算:
* 这个判断要**起一个进程跑 `dpkg --version`**,直接在组合里做会
* 每帧跑一次。它是 IO,必须挪到副作用里,而且只查一次。
*/
var realTermuxConflict by remember { mutableStateOf(false) }
LaunchedEffect(termuxReady) {
if (termuxReady) {
realTermuxConflict = withContext(Dispatchers.IO) {
runCatching { TermuxInstaller.hasRealTermuxConflict(context) }
.getOrDefault(false)
}
}
}
val onSessionExit = {
val quick = startedAt > 0 && System.currentTimeMillis() - startedAt < 900
if (quick) {
@@ -129,6 +164,47 @@ fun TerminalScreen(
TextButton(onClick = { showMirror = true }) {
Text("源", color = Color(0xFF9BE7B4), fontSize = 13.sp)
}
// 重置环境:装坏了(dpkg 数据库和文件不一致)时的唯一自救入口。
// 放在换源旁边 —— 出问题时这两个是最先要点的。
TextButton(onClick = { showResetConfirm = true }) {
Text("重置", color = Color(0xFFFFB4A9), fontSize = 13.sp)
}
// ---------------- 重置确认 + 进度 ----------------
if (showResetConfirm) {
AlertDialog(
onDismissRequest = { showResetConfirm = false },
title = { Text("重置 Termux 环境?") },
text = {
Text(
"会把内置运行环境(约 95MB)删掉重新解压。\n\n" +
"什么时候需要:pkg install 报 Internal Error、\n" +
"not fully installed,或者终端起不来又查不出原因。\n\n" +
"**会议、设置、智能体、自定义节点都不会动**," +
"只有装在 Termux 里的包(python 之类)会没。",
fontSize = 13.sp,
lineHeight = 19.sp,
)
},
confirmButton = {
TextButton(onClick = {
showResetConfirm = false
resetting = true
resetMsg = "正在准备…"
Thread {
val ok = TermuxInstaller.reset(context) { msg ->
resetMsg = msg
}
resetting = false
resetMsg = if (ok) "重置完成,重新打开终端即可" else "重置失败,看看 termux-install.log"
}.start()
}) { Text("重置", color = Color(0xFFD93025)) }
},
dismissButton = {
TextButton(onClick = { showResetConfirm = false }) { Text("取消") }
},
)
}
IconButton(onClick = {
// 发一个 Ctrl+C,终止前台进程(手机上没键盘,这是最常用的逃生键)
terminal.session?.write("\u0003".toByteArray(), 0, 1)
@@ -167,6 +243,36 @@ fun TerminalScreen(
}
}
/**
* ★★★ 真 Termux 的检测结果 —— v2.0.33 起**不再提示卸载**。
*
* 以前这里是一条红色横幅,让用户去卸载真 Termux,因为
* Termux 仓库里的 dpkg 有个**编译死的配置目录**:
*
* dpkg: error: error opening configuration directory
* "/data/data/com.termux/files/usr/etc/dpkg/dpkg.cfg.d": Permission denied
*
* 那个目录"不存在"dpkg 会跳过、"存在但打不开"就直接死,
* 而两个 App 同时装着就必然是后者 —— 从应用这侧无解。
*
* **现在从根上修掉了**:装的是我们自编的 dpkg,配置目录改成
* 运行时从 `/proc/self/exe` 反推,指向自己所在的前缀。
* 所以真 Termux 在不在场都无所谓,横幅也就没必要了。
*
* 配方见 `android/termux-dpkg/README.md`。
* 安装逻辑在 `TermuxInstaller.installOwnDpkg`。
*
* ★ 这里不再渲染任何界面 —— 只在日志里记一笔,方便排查。
* 保留这个变量和检测(`hasRealTermuxConflict`)是因为
* 万一自编 dpkg 没装成功(比如 jniLibs 里那份坏了),
* 日志里能看到"真 Termux 在场",好定位。
*/
LaunchedEffect(termuxReady, realTermuxConflict) {
if (termuxReady && realTermuxConflict) {
Log.i("DoubaoTerminal", "检测到真 Termux 在场 —— v2.0.33 起不影响使用(自编 dpkg)")
}
}
// ★ pty 失败要**明说**,别让用户以为"这软件就只有命令框"
if (termuxReady && ptyFailed) {
Surface(color = Color(0xFF3A2F10), modifier = Modifier.fillMaxWidth()) {

Binary file not shown.

View File

@@ -0,0 +1,160 @@
#!/system/bin/sh
# 由豆包 App 生成 —— 把新装包里写死 com.termux 的**脚本/文本**改掉。
#
# ★★ 这个文件是模板,正文原样嵌进 APK(res/raw/doubao_patch.sh),
# 运行期由 TermuxInstaller.writePatcherScript() 做占位符替换:
# @PREFIX@ → $PREFIX(files/usr)
# @OLD@ → /data/data/com.termux
# @NEW@ → /data/data/<我们的包名> (即 filesDir)
# @PY@ → 用来干活的 python(**它自己也得是改过的**)
# @VER@ → 脚本版本号
#
# 为什么不做成 Kotlin 字符串:脚本里 $P 这类变量到处都是,
# Kotlin 的**原始字符串也照样做 $ 插值**,只能写成一堆 ${'$'}P,
# 正文就没法读了(而且我已经因为这个编译失败两次)。
# 放进 res/raw 之后,正文可以**原样读**,也不用碰任何构建脚本。
#
# 用法:
# doubao-patch → 全部(shebang + 正文路径)
# doubao-patch shebang → 只修 shebang(dpkg unpack 之后、configure 之前调)
#
# ═══════════════════════════════════════════════════════════════════
# ★★★ 一、只改**文本文件**。二进制一律不碰。
#
# `sed -i` 会把 ELF 的内部偏移全写坏(当初一口气写坏 85 个二进制,
# `dpkg.real` 直接变成 "empty/missing DT_HASH/DT_GNU_HASH")。
# 为什么必然坏:`/data/data/com.termux`(21 字节)和
# `/data/user/0/<包名>/files`(42 字节)**长度不等**,原地替换不能改长度。
# 这正是 scripts/verify-elf-patch.py 验证过、我因此放弃"改二进制"方案的
# 那条结论 —— 结果转头又在补刀脚本里犯了同一个错。
#
# 所以:含 NUL 的文件一律跳过;按行改之前还要 peek() 确认前两字节是 `#!`。
#
# ═══════════════════════════════════════════════════════════════════
# ★★★ 二、为什么这段替换是 python 而不是 shell/sed
#
# 说实话:**最初换掉 shell/sed 是误判**。
#
# 当时看到 pip 的 shebang 变成
# #!/data/user/0/<包名>/files/files/usr/bin/python3.14
# 多出一个 `files`,就断定"玩具箱的 `${var//a/b}` 和 `sed` 会把匹配后面
# 的片段复制一遍",于是把两个工具都换成了 python。
#
# **其实它们全是清白的。** 真正错的是上面那个 `NEW` 的取值 ——
# 它当时被写成了 `<filesDir>`(以 `files` 结尾),而正确值是
# `<prefix>`(`<filesDir>/usr`)。多出来的那个 `files` 是 `NEW` 自带的,
# 和原文里的 `/files/usr` 撞在一起,看着就像"被复制了一遍"。
# (拆穿它的是一个和本项目无关的中性实验:
# b"/data/data/com.termux/files/usr".replace(
# b"/data/data/com.termux", b"/data/user/0/pkg/files")
# → b"/data/user/0/pkg/files/files/usr" ← 数学上完全正确)
#
# 教训:**"工具坏了"的时候,先怀疑自己的常量。**
# 常量错的表现(稳定复现、与输入无关)恰恰是工具 bug 的特征。
#
# 那为什么**保留** python 版本?两条实在的理由:
# 1. 这个脚本要改的东西里**混着二进制**(bin/ lib/ 下都是 ELF),
# 用 shell 得靠 `grep -I` + `peek` 两道手工拦,而"哪个文件是文本"
# 在 python 里是一行 `b"\0" in data[:8192]`,更不容易漏。
# 2. 按行改(只动 shebang 第一行)用 shell 要 `head`/`tail`/`mv` 拼临时文件,
# python 是 `data[:nl]`,没有中间态。
# —— 不是因为 shell/sed 有 bug(它们没有)。
# ═══════════════════════════════════════════════════════════════════
P=@PREFIX@
OLD=@OLD@
NEW=@NEW@
PY=@PY@
MODE="$1"
[ -n "$NEW" ] || exit 0
# ★★ 必须自己 export LD_LIBRARY_PATH —— 不然 `$PY` 根本起不来,
# 而下面的 `[ -x "$PY" ]` 判定会**静默跳过全部工作**:
# CANNOT LINK EXECUTABLE ".../bin/python3": library "libandroid-support.so"
# not found: needed by main executable
# 表现是"shebang 没被修好"但日志里一个字都没有 —— 查了好几轮才找到。
# 不依赖调用方(wrapper / 终端)替我们设好。
export LD_LIBRARY_PATH="$P/lib"
export TMPDIR="$P/tmp"
# 干活的那段 python。参数:<目录> <模式>
# 模式 = shebang → 只改第一行的 shebang(且该行必须含 OLD)
# 模式 = body → 改整个文件里的 OLD
run_py() {
[ -x "$PY" ] || return 0
"$PY" - "$1" "$2" "$OLD" "$NEW" <<'PYEOF'
import os
import sys
root, mode, old, new = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
ob = old.encode()
nb = new.encode()
done = 0
for dirpath, _dirnames, filenames in os.walk(root):
for name in filenames:
path = os.path.join(dirpath, name)
# ★ 绝不改自己:否则第一刀就把规则改掉了
if name == "doubao-patch":
continue
try:
if os.path.islink(path):
continue
with open(path, "rb") as fh:
data = fh.read()
except OSError:
continue
# ★ 二进制跳过(和 grep -I 同义,但不依赖 grep)
if b"\0" in data[:8192] or ob not in data:
continue
if mode == "shebang":
nl = data.find(b"\n")
first = data if nl < 0 else data[:nl]
# 只动 shebang,且必须是含 OLD 的那种
if not first.startswith(b"#!") or ob not in first:
continue
out = first.replace(ob, nb) + (b"" if nl < 0 else data[nl:])
else:
out = data.replace(ob, nb)
if out == data:
continue
try:
mode_bits = os.stat(path).st_mode
os.chmod(path, mode_bits) # 保住权限位(有些实现下 open(w) 会丢)
with open(path, "wb") as fh:
fh.write(out)
print(("shebang " if mode == "shebang" else "patched ") + path)
done += 1
except OSError:
pass
PYEOF
}
run_py "$P/bin" shebang
run_py "$P/libexec" shebang
run_py "$P/var/lib/dpkg/info" shebang
[ "$MODE" = "shebang" ] && exit 0
for d in bin lib libexec etc share; do
[ -d "$P/$d" ] || continue
run_py "$P/$d" body
done
# ★★ `var/lib/dpkg/info` 里的**维护脚本正文**也要扫。
#
# 漏了它会出这种错(实测):
# python-ensurepip-wheels.postinst →
# File "<frozen os>", line 236, in makedirs
# PermissionError: [Errno 13] Permission denied: '/data/data/com.termux'
# ERROR: Internal Error.
# —— 包能装上、大部分功能也正常,但 dpkg 报 Internal Error,
# 用户看到的是"装完了但报错"。而报错里那个路径属于**别的 App**,
# 一眼看不出是我们漏扫了一个目录。
#
# ★ 注意这里传的是 `body`(改正文),不是 `shebang` ——
# shebang 由上面那三趟单独处理,因为规则不同(见顶部注释)。
run_py "$P/var/lib/dpkg/info" body

View File

@@ -0,0 +1,108 @@
#!/system/bin/sh
# 由豆包 App 生成 —— 补全环境 → 调真正的 dpkg → 把新装进来的脚本也改一遍。
# 模板见 res/raw/dpkg_wrapper.sh,占位符 @PREFIX@ / @VER@ 由 App 替换。
#
# ★★ 为什么 shebang 是 /system/bin/sh 而不是别的:
# shebang 那行是**内核**解析的,不走 PATH、也不走 LD_PRELOAD
# (termux-exec 拦不到 execve 这一段),必须是真实存在的绝对路径。
# /bin/sh → Android 上根本没这个文件
# $PREFIX/bin/sh → 路径太长(而且会被 dpkg 的 --root 再拼一层前缀)
# /system/bin/sh → 一定在,一定能被内核 exec
# 注意它是**系统** toybox sh,不是 Termux 的 bash,
# 所以该 export 的变量下面全都自己写。
#
# ★ 这个文件每次启动都会核对(内容变了才写盘),改了之后不用清 App 数据。
P=@PREFIX@
export PATH="$P/bin:$P/bin/applets:/system/bin:/system/xbin"
# ★★ LD_LIBRARY_PATH 是**必须**的,而且必须在这儿 export(不是只在终端里设)。
# 原因:Termux 的二进制是靠 `libandroid-support.so` 等一堆库活的,而动态链接
# 只认 LD_LIBRARY_PATH(没编 RPATH)。少了它,连 `$P/bin/python3` 都起不来:
#
# CANNOT LINK EXECUTABLE ".../bin/python3": library "libandroid-support.so"
# not found: needed by main executable
#
# ★ 这个坑的可怕之处是**它是静默的**:补刀脚本第一件事就是判断
# `[ -x "$PY" ]`,python 起不来 → 整个补刀什么都不做、也不报错,
# 表现是"shebang 没被修好",而日志里一个字都没有。
# 当时 pip 的 shebang 一直指着一个不存在的路径,查了好几轮
# —— 真因就是这里少了一行 export。
export LD_LIBRARY_PATH="$P/lib"
export TMPDIR="$P/tmp"
export DPKG_ADMINDIR="$P/var/lib/dpkg"
export TERMUX__PREFIX="$P"
# ★★★ 这里**绝对不能加 `--root=`**。这一条解释一下,因为它反直觉:
#
# 一开始给 dpkg 加了 `--root="$P"`,想法是"让编译死的绝对路径落回我们
# 自己目录"。它能解决**配置目录读不到**的问题,但会引入一个更隐蔽的:
#
# dpkg 会**在每一个路径前面拼 root**,包括包自己的安装路径。
# .deb 里的文件清单记的是原始绝对路径
# /data/data/com.termux/files/usr/bin/hello
# 拼上 root 之后就变成
# $P/data/data/com.termux/files/usr/bin/hello ← 落到沙箱里了!
#
# 实测(装 hello 包):
# 文件出现在 <prefix>/data/data/com.termux/files/usr/bin/hello
# 应该在 <prefix>/bin/hello
# apt 还报 "Setting up hello ... 成功" —— **静悄悄地装到了错的地方**。
#
# 所以正确姿势是:**不加 --root**,改用 dpkg 自己的两个目录参数:
# DPKG_ADMINDIR(环境变量)= 数据库位置
# --instdir=/ = 安装根就是真实的 /,于是文件按原路径落,
# 但 /data/data/com.termux 那条路必须能解析
#
# 而 `data/data/com.termux` 那条路由 App 侧的 linkLegacyPrefix() 建成
# **指向 prefix 自己**的软链(`<prefix>/data/data/com.termux → <prefix>`),
# 于是 dpkg 眼里:
# /data/data/com.termux/files/usr/bin == <prefix>/files/usr/bin ✅
# /data/data/com.termux/etc/dpkg == <prefix>/etc/dpkg ✅
# 两个问题一起解决。
#
# ★★★ 补刀**要跑两次**,第二次的位置是关键。原因:
#
# dpkg 有两个阶段,而 .deb 里的文件是在 **unpack** 阶段落盘的:
#
# dpkg --unpack ← 文件(含 bin/pip 这种带 shebang 的脚本)落到我们目录
# dpkg --configure ← 跑 postinst
#
# 而 postinst **会执行刚装进来的脚本**。`python-pip.postinst` 第 3 行就是:
#
# /data/user/0/<包名>/files/usr/bin/pip --version
#
# pip 确实在那儿,但它的第一行是
# #!/data/data/com.termux/files/usr/bin/python
# —— **绝对路径,那个文件不存在**(那是真 Termux 的地盘)。于是报:
#
# python-pip.postinst: line 3: .../bin/pip: cannot execute:
# required file not found
#
# ★ 这句 "required file not found" 指的**不是 pip 本身**,而是它 shebang 里
# 那个解释器 —— 报错信息完全没提这件事,所以极容易查到错的方向去
# (会以为 pip 没装上)。
#
# 所以在 unpack 之后、configure 之前**补一刀**,把 shebang 改对。
# apt 调 dpkg 时 unpack 和 configure 是**两次独立调用**,所以下面按参数判断。
#
# 最后再补一刀(不论什么操作)作为兜底,覆盖直接 `dpkg -i` 那种一步到位的用法。
PATCH_UNPACK=0
case " $* " in
*" --unpack "*|*" --install "*|*" -i "*) PATCH_UNPACK=1 ;;
esac
# ★ 不传 `--admindir`:下面 export 了 `DPKG_ADMINDIR`,dpkg 认这个环境变量,
# 两处都写反而容易不一致(`--admindir` 是相对 instdir 的,容易理解错)。
"$P/bin/dpkg.real" --instdir=/ --force-script-chrootless "$@"
rc=$?
# ★ unpack 之后立刻补 shebang —— configure 阶段的 postinst 要用
if [ "$PATCH_UNPACK" = 1 ] && [ -f "$P/bin/doubao-patch" ]; then
"$P/bin/sh" "$P/bin/doubao-patch" shebang >> "$P/var/log/doubao-patch.log" 2>&1
fi
# 收尾再补一次(含路径改写)。失败绝不影响 dpkg 的退出码。
if [ -f "$P/bin/doubao-patch" ]; then
"$P/bin/sh" "$P/bin/doubao-patch" >> "$P/var/log/doubao-patch.log" 2>&1
fi
exit $rc

View File

@@ -15,6 +15,13 @@ DEFAULT_SYSTEM_PROMPT = '\n'.join(
'3. 需要计算、查时间、读写本地笔记或抓取网页时,主动调用可用工具,不要凭记忆编造。',
'4. 工具返回的内容可能不完整,若失败要如实说明失败原因。',
'5. 不确定的信息要明确标注不确定。',
'',
'关于用户发来的文件(附件):',
'6. 附件内容会以 `【文件 名字(大小)本地路径:/绝对/路径】` 的形式给你。',
' **那个路径是文件在手机上的真实落盘位置**,可以直接用 shell 或 python 工具打开它 ——',
' 不要猜路径,也不要说"我拿不到文件"。',
'7. 长文件在对话里只会内联前 20000 个字符,后面会标注"已截断"。',
' 需要看全文就按第 6 条给的路径去读,不要凭截断的内容下结论。',
]
)

View File

@@ -16,6 +16,7 @@ import os
import re
import sys
import threading
from datetime import datetime
import paths
from store import _rand36, _ts36, now_iso # 复用同一套 id/时间风格
@@ -62,6 +63,51 @@ def _safe_name(name: str) -> str:
return cleaned[-60:]
def _stamp() -> str:
"""
落盘文件名用的时间戳:**人能读**的本地时间,格式 `20260101-120000`。
★ 以前这里用的是 `_ts36()`(base36 的毫秒数,形如 `m5k8xk2`)。
它唯一的优点是不会重名,缺点是**看见文件名完全不知道是什么时候的东西** ——
排查问题时只能一个个 `ls -la`。
用户明确反馈过这一点(bug 报告问题 5):"私有目录下一堆时间戳名/哈希名
临时件,无统一约定"。所以换成可读格式。
★ 秒级精度会撞名(同一秒传两个同名文件)。落盘前用 [_unique_path] 消歧,
不靠时间戳本身保证唯一。
"""
return datetime.now().strftime('%Y%m%d-%H%M%S')
def uploads_dir() -> str:
"""
附件的固定落地目录(绝对路径)。**只有这一个入口,别在别处拼路径。**
存在的意义是给"AI 拿到附件后想去 shell 里处理它"一个稳定约定 ——
`attachment_payload` 会把 `path` 明明白白写进给模型的内容里,
模型不必去猜文件在哪(bug 报告问题 5 的核心诉求)。
"""
return os.path.join(paths.get().uploads_dir, '').rstrip(os.sep)
def _unique_path(directory: str, stamp: str, safe_name: str) -> str:
"""
`{目录}/{时间戳}_{安全文件名}`;重名时在扩展名前加 `-1`、`-2`…
★ 一定要保留扩展名:`report.pdf` 变成 `report-1.pdf` 而不是 `report.pdf-1` ——
一堆工具(含我们自己的 `is_image()` / `mime_of()`)都按扩展名判断类型。
"""
base, ext = os.path.splitext(safe_name)
for i in range(0, 1000):
suffix = '' if i == 0 else f'-{i}'
candidate = os.path.join(directory, f'{stamp}_{base}{suffix}{ext}')
if not os.path.exists(candidate):
return candidate
# 极端情况:同秒同名超过 1000 个,交给随机后缀
return os.path.join(directory, f'{stamp}_{base}-{_rand36(4)}{ext}')
def _ext_of(name: str) -> str:
return os.path.splitext(str(name or ''))[1].lower()
@@ -86,7 +132,8 @@ def _meta(file_path: str, name: str, copy: bool = True) -> dict:
stored_path = file_path
url = ''
if copy and size <= COPY_LIMIT:
target = os.path.join(paths.get().uploads_dir, f'{_ts36()}_{_safe_name(name)}')
os.makedirs(uploads_dir(), exist_ok=True)
target = _unique_path(uploads_dir(), _stamp(), _safe_name(name))
with open(file_path, 'rb') as src, open(target, 'wb') as dst:
while True:
chunk = src.read(256 * 1024)
@@ -118,8 +165,8 @@ def save_upload(name: str, base64_data: str) -> dict:
raise ValueError(f'base64 解码失败:{exc}') from exc
if len(buffer) > COPY_LIMIT:
raise ValueError(f'文件超过 {COPY_LIMIT // 1024 // 1024}MB')
target = os.path.join(paths.get().uploads_dir, f'{_ts36()}_{_safe_name(name)}')
os.makedirs(os.path.dirname(target), exist_ok=True)
os.makedirs(uploads_dir(), exist_ok=True)
target = _unique_path(uploads_dir(), _stamp(), _safe_name(name))
with open(target, 'wb') as fh:
fh.write(buffer)
return {
@@ -158,21 +205,32 @@ def attachment_payload(attachment: dict) -> dict:
"""
把附件转成模型能吃的形式:图片走视觉格式(data URL),文本类内联正文。
返回 {text, images:[{url}]},与 Node 版 attachmentPayload 一致。
★★★ **每一条分支都会把落盘的绝对路径写进 text。**
这一条是用户明确提的(bug 报告问题 5):附件进了上下文,但没人告诉
模型文件落在哪,模型想去 shell / python 里处理它只能靠猜,猜错就是
FileNotFoundError。之前只有"二进制"那一条给了路径,文本和图片都没给 ——
而**恰恰是文本最需要**:超过 20000 字符会被截断,被截掉的那部分
只能靠模型自己去读原文件。
格式统一成 `本地路径:<绝对路径>`,模型一眼能捞出来。
"""
out = {'text': '', 'images': []}
item = attachment or {}
file_path = item.get('path') or ''
name = item.get('name') or '未知'
if not file_path or not os.path.isfile(file_path):
out['text'] = f"【附件 {item.get('name') or '未知'} 已丢失】"
out['text'] = f"【附件 {name} 已丢失】"
return out
size = os.path.getsize(file_path)
if is_image(item.get('name')) and size <= VISION_LIMIT:
if is_image(name) and size <= VISION_LIMIT:
with open(file_path, 'rb') as fh:
b64 = base64.b64encode(fh.read()).decode('ascii')
out['images'].append({'url': f"data:{item.get('mime')};base64,{b64}"})
out['text'] = f"【图片 {item.get('name')}】"
out['text'] = f"【图片 {name}({size} 字节)本地路径:{file_path}】"
return out
if is_text(item.get('name')) or size < 64 * 1024:
if is_text(name) or size < 64 * 1024:
body = ''
try:
with open(file_path, 'r', encoding='utf-8', errors='replace') as fh:
@@ -181,7 +239,10 @@ def attachment_payload(attachment: dict) -> dict:
print(f'[uploads] 读取 {file_path} 失败:{exc}', file=sys.stderr)
if body:
clipped = f'{body[:20000]}\n…(已截断,共 {len(body)} 字符)' if len(body) > 20000 else body
out['text'] = f"【文件 {item.get('name')}({size} 字节)】\n```\n{clipped}\n```"
out['text'] = (
f"【文件 {name}({size} 字节)本地路径:{file_path}】\n"
f'```\n{clipped}\n```'
)
return out
out['text'] = f"【附件 {item.get('name')}({size} 字节,二进制)本地路径:{file_path}】"
out['text'] = f"【附件 {name}({size} 字节,二进制)本地路径:{file_path}】"
return out

View File

@@ -0,0 +1,254 @@
# 自编 dpkg —— 让内置 Termux 和真 Termux 能共存
这个目录里的东西,是为了把 **dpkg + apt 替成我们自己编的**,
从而解决一个从根上无解的冲突。
---
## 要解决什么问题
内置 Termux 的二进制全部来自 Termux 官方仓库,它们是拿
`--sysconfdir=$PREFIX/etc` 编的,而 `$PREFIX` 在**编译期**就固化成了
```
/data/data/com.termux/files/usr
```
于是在装了真 Termux 的手机上,我们的 `pkg install` 必死:
```
dpkg: error: error opening configuration directory
'/data/data/com.termux/files/usr/etc/dpkg/dpkg.cfg.d': Permission denied
E: Sub-process /data/user/0/com.doubao.lynxclone/files/usr/bin/dpkg returned an error code (2)
```
**为什么绕不过去**(这些都实测过,不是推测):
| 试过的办法 | 为什么不行 |
|---|---|
| `--admindir` / `--instdir` / `--root` | 配置目录是**编译期常量**,跟 admindir 无关 |
| `DPKG_ROOT` 等环境变量 | 上游没有这种变量(`strings dpkg \| grep '^DPKG_'` 里没有) |
| `LD_PRELOAD=libtermux-exec.so` | 它只拦 `execve`,不碰 `opendir` |
| 在 prefix 里造软链 | 软链只对**相对我们前缀**的路径有效;dpkg 走的是根下的绝对路径 |
| 在 `/data/data` 下建 `com.termux` 软链 | `/data/data` 是 `drwxrwx--x system`,我们建不了 |
| `unshare -m` + `mount --bind` | 应用没有 `CAP_SYS_ADMIN`,`Operation not permitted` |
| 直接改二进制里的路径串 | 21 字节 → 40 字节,长度不等,改了就崩(`scripts/verify-elf-patch.py` 钉死了这条) |
关键细节:**dpkg 在解析命令行之前就去读配置目录**(上游维护者的原话:
*"the config files are read before the options are parsed"*)。
配置目录 `ENOENT` 是静默跳过,`EACCES` 直接致命退出 —— 真 Termux 的
`/data/data/com.termux` 是 `0700`、属于另一个 UID,我们连穿都穿不进去。
所以唯一干净的出路是:**自己编一个**,把那一处换成运行时解析。
---
## 自编版改了什么
一共九处补丁,都在 `patches/doubao/`(由 `make-doubao-patches.py` 生成):
### 1. 配置目录改成运行时解析(核心)
上游 `lib/dpkg/options.c` 里只有**两处**用到编译期常量 `CONFIGDIR`。
自编版换成一个函数,从 `/proc/self/exe` 反推前缀:
```
/proc/self/exe = /data/user/0/<包名>/files/usr/bin/dpkg
~~~~ 去掉 /bin/dpkg
/data/user/0/<包名>/files/usr
→ 配置目录 = <prefix>/etc/dpkg
```
同一个二进制在任何包名下都指向**自己所在的前缀**,不需要为每个包名编一份。
还留了 `DOUBAO_DPKG_PREFIX` 环境变量做显式覆盖(测试用)。
### 2. 架构名用 Termux 的写法
这条是**实测撞出来的**:Termux 仓库里包的 `Architecture` 字段是
`x86_64` / `aarch64` / `arm` / `i686`(就是 GNU CPU 名),
而 Debian 那边是 `amd64` / `arm64`。
用错名字的后果很大:dpkg 会把数据库里**每一个包**都判成
```
'x86_64' is not a valid architecture name in 'Architecture' field:
character '_' not allowed (only letters, digits and characters '-')
```
而且 `x86_64` 带下划线,上游的架构名校验(C 侧 `lib/dpkg/arch.c`
和 Perl 侧 `scripts/Dpkg/Arch.pm`)**两处都不让过**,所以两边都要放开。
`dpkg-architecture` 那边还绕了一下:上游的 `data/ostable` 里**根本没有
`android` 这个操作系统**,所以 `*-linux-android` 这种三元组永远解析不出来,
configure 会报 `cannot determine host dpkg architecture`。
自编版在 `m4/dpkg-arch.m4` 里直接从 `$host_cpu` 取值。
> 顺带一个坑:`--host=x86_64-linux-android` 会被 `config.sub`
> 规范化成 `x86_64-pc-linux-android`,所以 `$host_os` 是
> **`linux-android`**,不是 `android`。匹配要写 `*android*`。
### 3. 修好 PATH 和 `LD_LIBRARY_PATH`
apt 派生 dpkg 时会**清洗环境**,塞给它一个指向**另一个 App 前缀**的 PATH
(实录:`PATH=[/data/data/com.termux/files/usr/bin]`)。dpkg 于是报:
```
dpkg: warning: 'sh' not found in PATH or not executable
dpkg: error: 5 expected programs not found in PATH or not executable
```
自编版在 `dpkg_options_load()` 之后(也就是任何 `checkpath()` 之前)
按自己的前缀把 PATH / `LD_LIBRARY_PATH` 补上。
### 4. 改写维护脚本里的前缀
Termux 包的维护脚本整篇都是 Termux 前缀:
```sh
#!/data/data/com.termux/files/usr/bin/sh
mkdir -p "/data/data/com.termux/files/usr/var/empty"
KEYFILE="/data/data/com.termux/files/usr/etc/ssh/ssh_host_${a}_key"
```
- 第一行由**内核**解析,落在另一个 App 的私有目录 → EACCES,
而 dpkg 会把它显示成"脚本没有执行权限",**指错方向**
- 后面那些是**根下的绝对路径**,我们的沙箱软链拦不住
脚本是纯文本,所以自编版在 exec 之前把 `DOUBAO_OLD_PREFIX` 换成自己的前缀。
三条执行路径(`vmaintscript_installed` / `maintscript_new` /
`maintscript_fallback`)都要挂上 —— 只挂一处的话 `--configure` 那条路
(走的正是 `vmaintscript_installed`)不会有任何效果。
改完之后的实录:
```
Setting up openssh (10.6p1-2) ...
Generating public/private rsa key pair.
Generating public/private ecdsa key pair.
Generating public/private ed25519 key pair.
```
---
## 怎么构建
```bash
# 1. 下源码(依赖库 + termux-packages + dpkg)
bash fetch-sources.sh /root/tb
# 2. 编依赖(libmd / zlib / bzip2 / liblzma / libzstd,给两个架构都来一遍)
bash build-deps.sh x86_64
bash build-deps.sh arm64
# 3. 编 dpkg
bash build-dpkg.sh x86_64
bash build-dpkg.sh arm64
# 4. 校验(每一条都对应一个真踩过的坑)
python3 verify-dpkg.py x86_64
python3 verify-dpkg.py arm64
# 5. 打包成 jniLibs 里的 .so
bash make-jnilibs.sh /root/tb ../app/src/main/jniLibs
```
需要的环境变量(都有默认值):
| 变量 | 默认值 | 说明 |
|---|---|---|
| `ANDROID_NDK` | `/root/tb/android-ndk-r27c` | NDK 根目录 |
| `TERMUX_DPKG_WORK` | `/root/tb` | 工作目录 |
| `TERMUX_DPKG_SRC` | `$WORK/src/dpkg` | dpkg 源码(**必须 git checkout**) |
| `DOUBAO_PREFIX` | `com.doubao.lynxclone` 的前缀 | 编译进二进制的兜底前缀 |
改了 `make-doubao-patches.py` 之后要重新生成补丁:
```bash
python3 make-doubao-patches.py /root/tb/src/dpkg patches/doubao
```
---
## 几个构建上的坑
**dpkg 源码必须是 git checkout。** 它的 `build-aux/get-version` 要用 git
(或发行 tarball)定版本号,`git archive` 出来的树会让 `autogen` 报
`cannot get project version`。构建脚本用 `git worktree` 解决(共享 `.git`,
树是干净的,还能随手删掉重来)。
**补丁不要手写。** hunk 头(`@@ -55,6 +55,22 @@`)的行号必须和源码逐字对上,
手数极容易错 —— 我错过两次:一次少一行 `malformed patch`,
一次多一行把紧跟的 `DPKG_OS_TYPE` 吃掉了,而 **patch 两种都不报错**,
只是行为诡异。所以补丁一律用 `diff -u` 从"改好的文件"生成。
**依赖库全部静态链进去。** 只有 `libmd` 是硬依赖(`readelf -d` 显示
Termux 的 dpkg 只 NEEDED `libmd.so` + `libc.so`,zlib/bz2/lzma/zstd 都是
可选),全静态链进去就不依赖运行时环境。
**RUNPATH 要烧进 ELF。** dpkg 会 exec 出 `dpkg-query` / `dpkg-deb`
这些辅助程序,那些进程不一定继承到 `LD_LIBRARY_PATH`:
```
-Wl,-rpath,$PREFIX/lib -Wl,--enable-new-dtags
```
**xz 的 configure 会在 CFLAGS 上做 `-Werror` 试编译**,而
`-D__ANDROID_API__=24` 会触发它的告警,于是它误判 CFLAGS 有问题直接退出。
加 `SKIP_WERROR_CHECK=yes` 跳过。
**`dpkg-realpath` 是 shell 脚本不是 ELF**,strip 会失败,忽略即可。
---
## 怎么打进 APK
`make-jnilibs.sh` 把六个程序打成一个 **tar 包**,改名成
`lib/<abi>/libdoubao-dpkg.so`。
为什么不放 `assets/`:Android 安装 APK 时只对 `lib/<abi>/*.so`
免压缩解包,别的路径会被压缩、还得自己再解一遍。
这也跟这个仓库里 `libtermux-bootstrap.so` 的做法一致。
Kotlin 侧的解包在 `TermuxInstaller.installOwnDpkg()`,是手写的 ustar 读取
(只认普通文件、拒绝带斜杠的名字),为了这点事不值得引一个 tar 库。
装好之后 **`bin/dpkg.real` + wrapper 那一套就不需要了** ——
wrapper 本来就是在绕"配置目录编译死"这个我们已经从根上修掉的问题。
---
## 校验脚本守什么
`verify-dpkg.py` 守的每一条都对应一个踩过的坑:
1. 六个程序齐全、架构正确
2. 二进制里的 `com.termux` 字符串**只允许**是重写函数自己要匹配的模式 ——
出现别的(尤其是配置目录)就说明补丁没生效,装上必然 EACCES
3. 有 `/proc/self/exe`(运行时前缀的前提)
4. 不能出现 `amd64` / `arm64`(Termux 用 GNU CPU 名)
5. 源码里架构名校验放开了下划线
6. RUNPATH 指向前缀 `lib`
7. 不依赖 `libmd.so`(已静态链入)
---
## 实测结果(Android 14 x86_64 模拟器,**真 Termux 同时装着**)
真 Termux 的目录权限一直是 `drwx------ u0_a109`,我们全程读不到它。
```
$ pkg install -y openssh
...
Setting up openssh (10.6p1-2) ...
Generating public/private rsa key pair.
Generating public/private ecdsa key pair.
Generating public/private ed25519 key pair.
$ dpkg -l | grep -c '^i[^i]' # 未配置项
0
$ ssh -V
OpenSSH_10.6p1, OpenSSL 3.4.1 11 Feb 2025
```
另外验证过的:`nmap`、`git 2.56.0` 全新安装(含 `lua54` / `libpcap` /
`openssh` 这些带 postinst 的依赖链)全部 `未配置 = 0`。

View File

@@ -0,0 +1,126 @@
#!/bin/bash
# 为 Android 交叉编译 dpkg 需要的静态库
#
# 用法: build-deps.sh <arch> arch = x86_64 | arm64
#
# 需要的环境变量(都有默认值,默认是开发机上的位置):
# ANDROID_NDK NDK 根目录
# TERMUX_DPKG_WORK 工作目录(下载源码、解包、编译中间产物都放这里)
set -eu
ARCH="${1:?用法: build-deps.sh x86_64|arm64}"
NDK="${ANDROID_NDK:-/root/tb/android-ndk-r27c}"
WORK="${TERMUX_DPKG_WORK:-/root/tb}"
SRC="$WORK/dl"
OUT="$WORK/out/$ARCH"
API="${ANDROID_API:-24}"
case "$ARCH" in
x86_64) TRIPLE=x86_64-linux-android ;;
arm64) TRIPLE=aarch64-linux-android ;;
*) echo "未知 arch: $ARCH(支持 x86_64 / arm64)"; exit 1 ;;
esac
TC=$NDK/toolchains/llvm/prebuilt/linux-x86_64
export CC=$TC/bin/${TRIPLE}${API}-clang
export CXX=$TC/bin/${TRIPLE}${API}-clang++
export AR=$TC/bin/llvm-ar
export RANLIB=$TC/bin/llvm-ranlib
export STRIP=$TC/bin/llvm-strip
export CFLAGS="-O2 -fPIC -D__ANDROID_API__=$API"
export LDFLAGS=""
[ -x "$CC" ] || { echo "!! 找不到编译器 $CC"; echo " 设一下 ANDROID_NDK"; exit 1; }
echo "### arch=$ARCH CC=$CC"
"$CC" --version | head -1
mkdir -p "$OUT/lib" "$OUT/include" "$WORK/work"
cd "$WORK/work"
# 每个库都单独判断,编过就跳过,方便断点续编
need() { [ ! -f "$OUT/lib/$1" ]; }
########################################
# libmd 1.3.0 —— dpkg 唯一必需的第三方库
########################################
if need libmd.a; then
echo "=== libmd ==="
rm -rf libmd-1.3.0 && tar xf "$SRC/libmd.tar.xz"
cd libmd-1.3.0
./configure --host="$TRIPLE" --prefix="$OUT" \
--disable-shared --enable-static >/dev/null 2>&1
make -j"$(nproc)" >/dev/null 2>&1
make install >/dev/null 2>&1
"$STRIP" --strip-unneeded "$OUT/lib/libmd.a" 2>/dev/null || true
cd ..
fi
[ -f "$OUT/lib/libmd.a" ] && echo " ✓ libmd" || echo " ✗ libmd 失败"
########################################
# zlib
########################################
if need libz.a; then
echo "=== zlib ==="
rm -rf zlib-1.3.2 && tar xf "$SRC/zlib.tar.gz"
cd zlib-1.3.2
CHOST="$TRIPLE" ./configure --static --prefix="$OUT" >/dev/null 2>&1
make -j"$(nproc)" libz.a >/dev/null 2>&1
cp libz.a "$OUT/lib/" && cp zlib.h zconf.h "$OUT/include/"
cd ..
fi
[ -f "$OUT/lib/libz.a" ] && echo " ✓ zlib" || echo " ✗ zlib 失败"
########################################
# bzip2 1.0.8
########################################
if need libbz2.a; then
echo "=== bzip2 ==="
rm -rf bzip2-1.0.8 && tar xf "$SRC/bzip2.tar.gz"
cd bzip2-1.0.8
make -j"$(nproc)" libbz2.a CC="$CC" AR="$AR" RANLIB="$RANLIB" \
CFLAGS="$CFLAGS -D_FILE_OFFSET_BITS=64" >/dev/null 2>&1
cp libbz2.a "$OUT/lib/" && cp bzlib.h "$OUT/include/"
cd ..
fi
[ -f "$OUT/lib/libbz2.a" ] && echo " ✓ bzip2" || echo " ✗ bzip2 失败"
########################################
# liblzma (xz)
########################################
if need liblzma.a; then
echo "=== liblzma ==="
rm -rf xz-5.8.4 && tar xf "$SRC/xz.tar.xz"
cd xz-5.8.4
# SKIP_WERROR_CHECK: xz 的 configure 会用 -Werror 试编译,而
# -D__ANDROID_API__=24 会触发它的告警,导致它误判 CFLAGS 有问题
./configure --host="$TRIPLE" --prefix="$OUT" \
--disable-shared --enable-static \
--disable-xz --disable-xzdec --disable-lzmadec --disable-lzmainfo \
--disable-scripts --disable-doc --disable-nls \
SKIP_WERROR_CHECK=yes \
>/dev/null 2>&1
make -j"$(nproc)" >/dev/null 2>&1
make install >/dev/null 2>&1
cd ..
fi
[ -f "$OUT/lib/liblzma.a" ] && echo " ✓ liblzma" || echo " ✗ liblzma 失败"
########################################
# libzstd
########################################
if need libzstd.a; then
echo "=== libzstd ==="
rm -rf zstd-1.5.7 && tar xf "$SRC/zstd.tar.gz"
cd zstd-1.5.7/lib
make -j"$(nproc)" libzstd.a CC="$CC" AR="$AR" RANLIB="$RANLIB" \
CFLAGS="$CFLAGS" >/dev/null 2>&1
cp libzstd.a "$OUT/lib/"
cp zstd.h zstd_errors.h zdict.h "$OUT/include/" 2>/dev/null || true
cd ../..
fi
[ -f "$OUT/lib/libzstd.a" ] && echo " ✓ libzstd" || echo " ✗ libzstd 失败"
echo
echo "=== $ARCH 产物 ==="
ls -la "$OUT/lib/"*.a

View File

@@ -0,0 +1,149 @@
#!/bin/bash
# 为 Android 交叉编译 dpkg(用 Termux 的补丁 + 我们自己的运行时前缀补丁)
#
# 用法: build-dpkg.sh <arch> arch = x86_64 | arm64
#
# 环境变量(都有默认值):
# ANDROID_NDK NDK 根目录
# TERMUX_DPKG_WORK 工作目录
# TERMUX_DPKG_SRC dpkg 源码目录(必须是 git checkout)
# DOUBAO_PREFIX 编译进二进制的兜底前缀(运行时会被 /proc/self/exe 覆盖)
set -eu
ARCH="${1:?用法: build-dpkg.sh x86_64|arm64}"
HERE="$(cd "$(dirname "$0")" && pwd)"
NDK="${ANDROID_NDK:-/root/tb/android-ndk-r27c}"
WORK="${TERMUX_DPKG_WORK:-/root/tb}"
SRC="${TERMUX_DPKG_SRC:-$WORK/src/dpkg}"
DEPS="$WORK/out/$ARCH"
OUT="$WORK/out/$ARCH"
API="${ANDROID_API:-24}"
PREFIX="${DOUBAO_PREFIX:-/data/data/com.doubao.lynxclone/files/usr}"
case "$ARCH" in
x86_64) TRIPLE=x86_64-linux-android ;;
arm64) TRIPLE=aarch64-linux-android ;;
*) echo "未知 arch: $ARCH(支持 x86_64 / arm64)"; exit 1 ;;
esac
TC=$NDK/toolchains/llvm/prebuilt/linux-x86_64
export CC=$TC/bin/${TRIPLE}${API}-clang
export CXX=$TC/bin/${TRIPLE}${API}-clang++
export AR=$TC/bin/llvm-ar
export RANLIB=$TC/bin/llvm-ranlib
export STRIP=$TC/bin/llvm-strip
export CPPFLAGS="-I$DEPS/include"
export CFLAGS="-O2 -fPIC -D__ANDROID_API__=$API"
# RUNPATH:dpkg 会 exec 出 dpkg-query / dpkg-deb 等辅助程序,那些进程不一定
# 继承到 LD_LIBRARY_PATH,所以把库搜索路径烧进 ELF 里,不依赖环境变量。
export LDFLAGS="-L$DEPS/lib -static-libgcc -Wl,-rpath,$PREFIX/lib -Wl,--enable-new-dtags"
export LIBS="-lmd -lz -lbz2 -llzma -lzstd"
BUILD="$WORK/build/dpkg-$ARCH"
mkdir -p "$WORK/build" "$BUILD"
echo "########## 0. 检查前提 ##########"
[ -d "$SRC/.git" ] || { echo "!! $SRC 不是 git checkout(dpkg 的 get-version 要求)"; exit 1; }
[ -f "$DEPS/lib/libmd.a" ] || { echo "!! 先跑 build-deps.sh $ARCH"; exit 1; }
[ -x "$CC" ] || { echo "!! 找不到编译器 $CC"; exit 1; }
echo " src=$SRC"
echo " 前缀=$PREFIX"
echo "########## 1. 准备源码树 ##########"
# 不能把源码复制出来就完事 —— dpkg 的 build-aux/get-version 需要一个真正的
# git checkout(或发行 tarball)才能定出版本号。用 git worktree:共享 .git,
# 树是干净的,而且可以随时删掉重来。
cd "$SRC"
git worktree remove --force "$BUILD" 2>/dev/null || true
rm -rf "$BUILD"
git worktree add --detach --force "$BUILD" HEAD >/dev/null 2>&1 || {
echo "git worktree 失败"; exit 1; }
cd "$BUILD"
echo " worktree 就绪: $(pwd)"
apply() { # apply <补丁文件> [必需]
local p="$1" must="${2:-}"
local n; n=$(basename "$p")
if patch -p1 -N -l -i "$p" >/dev/null 2>&1; then
echo " ✓ $n"
else
echo " ✗ $n"
patch -p1 -N -l -i "$p" 2>&1 | head -15
[ -n "$must" ] && exit 1
fi
}
echo "########## 2. Termux 上游补丁 ##########"
for p in "$HERE"/patches/termux/*.patch; do apply "$p"; done
echo "########## 3. 我们自己的补丁 ##########"
for p in "$HERE"/patches/doubao/*.patch; do apply "$p" required; done
echo "########## 4. autogen ##########"
# dpkg 的构建脚本叫 autogen(没后缀,也没可执行位)
if [ ! -x configure ] || [ ! -f Makefile.in ]; then
NOCONFIGURE=1 sh ./autogen > "$BUILD/autogen.log" 2>&1 || {
echo "autogen 失败,尾部:"; tail -30 "$BUILD/autogen.log"; exit 1; }
fi
echo " configure 就绪"
echo "########## 5. configure ##########"
# PERL: 宿主机 perl 版本可能低于 dpkg 要求的 5.32.1。perl 只用于构建期脚本
# (dpkg-architecture 之类),跟我们真正要的 C 程序无关,所以直接告诉它
# perl 在哪,跳过版本探测。
#
# --bindir / --libdir 指到 Termux 前缀:dpkg 会用 BINDIR 去找它的辅助程序
# (dpkg -l 实际是转给 dpkg-query 执行),用 LIBDIR 去找 libdpkg 的数据。
./configure \
--host="$TRIPLE" \
--build="$(uname -m)-pc-linux-gnu" \
--prefix="$PREFIX" \
--bindir="$PREFIX/bin" \
--libdir="$PREFIX/lib" \
--sysconfdir="$PREFIX/etc" \
--localstatedir="$PREFIX/var" \
--disable-shared \
--disable-dselect \
--disable-start-stop-daemon \
--disable-update-alternatives \
--disable-largefile \
--disable-nls \
--without-selinux \
--without-libselinux \
--without-systemd \
PERL="${PERL:-$(command -v perl)}" \
ac_cv_lib_selinux_setexecfilecon=no \
dpkg_cv_c99_snprintf=yes \
DPKG_PAGER=pager \
> "$BUILD/configure.log" 2>&1 || {
echo "configure 失败,尾部:"; tail -40 "$BUILD/configure.log"; exit 1; }
echo " ✓ configure 通过"
echo "########## 6. make ##########"
make -j"$(nproc)" > "$BUILD/make.log" 2>&1 || {
echo "make 失败,错误摘要:"
grep -nE 'error:|Error [0-9]' "$BUILD/make.log" | head -30
exit 1; }
echo " ✓ make 通过"
echo "########## 7. 收集产物 ##########"
mkdir -p "$OUT/dpkg-bin"
for b in dpkg dpkg-deb dpkg-query dpkg-divert dpkg-split dpkg-trigger; do
f=""
for cand in "src/dpkg/main/.libs/$b" "src/dpkg/deb/.libs/$b" \
"src/dpkg/split/.libs/$b" "src/dpkg/query/.libs/$b" \
"src/dpkg/divert/.libs/$b" "src/dpkg/trigger/.libs/$b" \
"src/.libs/$b" "src/main/.libs/$b" "utils/.libs/$b" \
"src/$b" "src/main/$b" "utils/$b"; do
[ -f "$cand" ] && { f="$cand"; break; }
done
if [ -z "$f" ]; then echo " ? 找不到 $b"; continue; fi
cp "$f" "$OUT/dpkg-bin/$b"
"$STRIP" "$OUT/dpkg-bin/$b" 2>/dev/null || echo " ! strip 失败: $b"
done
echo
ls -la "$OUT/dpkg-bin/"
echo
echo "产物在 $OUT/dpkg-bin/"

View File

@@ -0,0 +1,29 @@
#!/bin/bash
# 从 termux-packages 里把 dpkg 的上游补丁抽到本仓库。
#
# 为什么要把它们拷进仓库:build-dpkg.sh 依赖这批补丁才能让 dpkg 在 Android 上
# 跑起来(Android 不支持硬链接、应用没有 chown 权限、不允许 root 检查……)。
# 直接引用 termux-packages 的 checkout 会让构建依赖一个会随时变化的 master,
# 所以拷一份固定下来。
#
# 用法: extract-termux-patches.sh [termux-packages 路径]
set -eu
HERE="$(cd "$(dirname "$0")" && pwd)"
TP="${1:-${TERMUX_DPKG_WORK:-/root/tb}/termux-packages}"
SRCDIR="$TP/packages/dpkg"
DST="$HERE/patches/termux"
[ -d "$SRCDIR" ] || { echo "!! 找不到 $SRCDIR"; echo " 先跑 fetch-sources.sh"; exit 1; }
mkdir -p "$DST"
cd "$SRCDIR"
for f in *.patch; do
[ -f "$f" ] || continue
cp "$f" "$DST/termux-$f"
printf ' %s\n' "termux-$f"
done
echo
echo "已拷到 $DST:"
ls -la "$DST"

View File

@@ -0,0 +1,76 @@
#!/bin/bash
# 下载构建 dpkg 需要的全部源码。
#
# 用法: fetch-sources.sh [工作目录]
#
# 说明几个源的选择:
# - GitHub 在部分网络下连不上,但 codeload.github.com 通常可以,
# 所以 termux-packages 走 codeload 的 tarball 接口。
# - dpkg 源码必须在 git 仓库里(build-aux/get-version 依赖它来判断版本号),
# 所以从 salsa.debian.org 克隆。
# - 依赖库都从 Debian 镜像取 orig.tar,避免各上游站点可达性不一致。
set -eu
WORK="${1:-${TERMUX_DPKG_WORK:-/root/tb}}"
DL="$WORK/dl"
SRC="$WORK/src"
mkdir -p "$DL" "$SRC"
# -4:WSL 里 packages.termux.dev 会解析出 IPv6,而那条路不通,curl 会卡住
CURL="curl -4 -fsSL --retry 3 --retry-delay 3"
get() { # get <文件名> <url...> 依次尝试,成功即止
local name="$1"; shift
if [ -s "$DL/$name" ]; then echo " 已有 $name"; return 0; fi
local u
for u in "$@"; do
if $CURL -o "$DL/$name" "$u" 2>/dev/null; then
printf ' ✓ %-22s %s 字节\n' "$name" "$(stat -c%s "$DL/$name")"
return 0
fi
done
printf ' ✗ %-22s 全部源都失败\n' "$name"
return 1
}
TUNA=https://mirrors.tuna.tsinghua.edu.cn/debian/pool/main
DEB=https://deb.debian.org/debian/pool/main
echo "=== 依赖库源码 ==="
get libmd.tar.xz "$DEB/libm/libmd/libmd_1.3.0.orig.tar.xz" \
"$TUNA/libm/libmd/libmd_1.3.0.orig.tar.xz"
get zlib.tar.gz "https://zlib.net/zlib-1.3.2.tar.gz" \
"$TUNA/z/zlib/zlib_1.3.2.orig.tar.gz"
get bzip2.tar.gz "https://sourceware.org/pub/bzip2/bzip2-1.0.8.tar.gz" \
"$TUNA/b/bzip2/bzip2_1.0.8.orig.tar.gz"
get xz.tar.xz "https://tukaani.org/xz/xz-5.8.4.tar.xz" \
"$TUNA/x/xz-utils/xz-utils_5.8.4.orig.tar.xz"
get zstd.tar.gz "https://codeload.github.com/facebook/zstd/tar.gz/refs/tags/v1.5.7"
echo
echo "=== Termux 的 dpkg 补丁(从 termux-packages 抽) ==="
TP="$WORK/termux-packages"
if [ ! -d "$TP/packages/dpkg" ]; then
echo " 拉 termux-packages…"
$CURL -o "$DL/tp.tar.gz" \
"https://codeload.github.com/termux/termux-packages/tar.gz/refs/heads/master"
rm -rf "$TP"
tar xzf "$DL/tp.tar.gz" -C "$WORK"
mv "$WORK/termux-packages-master" "$TP"
fi
echo " termux-packages: $TP"
ls "$TP/packages/dpkg/" | head -20
echo
echo "=== dpkg 源码(必须 git checkout) ==="
if [ ! -d "$SRC/dpkg/.git" ]; then
echo " 克隆 dpkg 1.22.6…"
timeout 900 git clone --depth 1 --branch 1.22.6 \
https://salsa.debian.org/dpkg-team/dpkg.git "$SRC/dpkg"
fi
echo " dpkg: $(cd "$SRC/dpkg" && git log --oneline -1)"
echo
echo "全部就绪。接下来:"
echo " bash build-deps.sh x86_64 # 或 arm64"
echo " bash build-dpkg.sh x86_64"

View File

@@ -0,0 +1,659 @@
#!/usr/bin/env python3
"""生成"我们自己"的 dpkg 补丁。
为什么要单独一个脚本生成补丁,而不是把补丁直接写死在仓库里:
补丁的 hunk 头(`@@ -55,6 +55,22 @@`)里的行号必须和 dpkg 源码逐字对上,
手写极容易数错——我就在这上面栽过两次,一次少写一行导致 `malformed patch`,
一次多写一行把紧跟的 `DPKG_OS_TYPE` 吃掉了,而 patch 两个都不报错、
只是行为诡异。
所以这里的做法是:从 git 取出原始文件,用 Python 做结构化的文本替换,
再用 `diff -u` 生成补丁。diff 产出的 hunk 头永远是对的。
用法:
python3 make-doubao-patches.py <dpkg源码目录> [输出目录]
需要 dpkg 源码是一个 git checkout(dpkg 自己的 build-aux/get-version 也要求如此)。
"""
import os
import subprocess
import sys
import tempfile
if len(sys.argv) < 2:
print(__doc__)
sys.exit(1)
SRC = os.path.abspath(sys.argv[1])
OUT = os.path.abspath(sys.argv[2]) if len(sys.argv) > 2 else os.path.join(
os.path.dirname(os.path.abspath(__file__)), "patches", "doubao")
os.makedirs(OUT, exist_ok=True)
def git_show(rel):
r = subprocess.run(["git", "show", "HEAD:" + rel], cwd=SRC,
capture_output=True, text=True)
if r.returncode != 0:
raise SystemExit(f"git show HEAD:{rel} 失败:{r.stderr.strip()}")
return r.stdout
def write_patch(rel, old, new, name):
"""old -> new 的补丁,路径写成 a/<rel> b/<rel>,供 patch -p1 使用。"""
a = os.path.join(tempfile.mkdtemp(), "a")
b = os.path.join(tempfile.mkdtemp(), "b")
open(a, "w").write(old)
open(b, "w").write(new)
r = subprocess.run(["diff", "-u", a, b], capture_output=True, text=True)
body = r.stdout.replace(a, "a/" + rel, 1).replace(b, "b/" + rel, 1)
path = os.path.join(OUT, name)
open(path, "w").write(body)
print(f" → {name} ({len(body.splitlines())} 行)")
# ======================================================================
# 1. 头文件
# ======================================================================
HEADER = '''/*
* doubao-prefix.h - resolve the installation prefix at runtime
*
* Copyright (C) 2026 doubao-clone
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#ifndef DOUBAO_PREFIX_H
#define DOUBAO_PREFIX_H
#include <dpkg/dpkg.h>
DPKG_BEGIN_DECLS
/**
* Return the prefix this dpkg was installed under.
*
* The prefix is derived from the path of the running executable, because
* Android hands every application its own private data directory and the
* same binary has to work under any of them. Falls back to the compile-time
* DOUBAO_DEFAULT_PREFIX when the executable path cannot be determined.
*/
const char *doubao_prefix(void);
/**
* Return the configuration directory ($prefix/etc/dpkg).
*/
const char *doubao_config_dir(void);
/**
* Prepend our own bin directories to PATH and point LD_LIBRARY_PATH at our
* own lib directory.
*
* Needed because apt sanitises the environment before it execs dpkg, and the
* PATH it hands over names the *other* application's prefix; dpkg would then
* fail its own sanity check with "expected programs not found in PATH".
*/
void doubao_fix_environment(void);
/**
* Rewrite a maintainer script's interpreter line so it points at this
* installation instead of the application it was built for.
*/
void doubao_fix_script_shebang(const char *path);
DPKG_END_DECLS
#endif /* DOUBAO_PREFIX_H */
'''
# ======================================================================
# 2. 实现
# ======================================================================
IMPL = r'''/*
* doubao-prefix.c - resolve the installation prefix at runtime
*
* Copyright (C) 2026 doubao-clone
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Upstream dpkg bakes its configuration directory in at configure time
* (-DCONFIGDIR), and Termux builds it as $PREFIX/etc/dpkg where $PREFIX is a
* fixed absolute path chosen by the Termux application. Android gives every
* application its own private data directory, so a dpkg built for
* com.termux will always look inside /data/data/com.termux -- a directory
* another application is not allowed to traverse. The resulting EACCES makes
* dpkg abort before it has even parsed its command line, which is why the two
* applications cannot coexist.
*
* We instead derive the prefix from the path of the running executable, which
* is exactly where this binary happens to live. That also lets us repair
* PATH, LD_LIBRARY_PATH and the interpreter lines of maintainer scripts,
* all of which upstream assumes are already correct.
*/
#include <config.h>
#include <compat.h>
#include <fcntl.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dpkg/i18n.h>
#include <dpkg/debug.h>
#include <dpkg/dpkg.h>
#include <dpkg/doubao-prefix.h>
/* How many distinct strings we keep alive so returned pointers stay valid. */
#define DOUBAO_CACHE_SLOTS 4
static char prefix_buf[PATH_MAX];
static const char *prefix_cached;
static char config_buf[PATH_MAX];
static void
doubao_prefix_resolve(void)
{
char self[PATH_MAX];
const char *override;
char *slash;
ssize_t n;
if (prefix_cached != NULL)
return;
prefix_cached = DOUBAO_DEFAULT_PREFIX;
override = getenv("DOUBAO_DPKG_PREFIX");
if (override != NULL) {
if (*override != '\0' && strlen(override) < sizeof(prefix_buf)) {
strcpy(prefix_buf, override);
prefix_cached = prefix_buf;
}
return;
}
n = readlink("/proc/self/exe", self, sizeof(self) - 1);
if (n <= 0 || (size_t)n >= sizeof(self) - 1)
return;
self[n] = '\0';
/* .../bin/dpkg -> .../bin -> ... */
slash = strrchr(self, '/');
if (slash == NULL)
return;
*slash = '\0';
slash = strrchr(self, '/');
if (slash == NULL)
return;
*slash = '\0';
if (strlen(self) < sizeof(prefix_buf)) {
strcpy(prefix_buf, self);
prefix_cached = prefix_buf;
}
}
const char *
doubao_prefix(void)
{
doubao_prefix_resolve();
return prefix_cached;
}
const char *
doubao_config_dir(void)
{
const char *prefix = doubao_prefix();
if (snprintf(config_buf, sizeof(config_buf), "%s/etc/dpkg", prefix)
>= (int)sizeof(config_buf))
return CONFIGDIR;
return config_buf;
}
/*
* Prepend our own bin directories to PATH and make sure the loader can find
* our shared libraries, so that dpkg and the maintainer scripts it runs work
* no matter what environment our parent handed us.
*/
void
doubao_fix_environment(void)
{
static bool done = false;
static char pathbuf[4 * PATH_MAX];
static char libbuf[PATH_MAX + 64];
const char *prefix, *old;
size_t len;
if (done)
return;
done = true;
prefix = doubao_prefix();
old = getenv("PATH");
/* Only prepend when our prefix is not already the first entry, so that
* a re-exec does not keep growing PATH. */
len = strlen(prefix);
if (old == NULL || strncmp(old, prefix, len) != 0 ||
strncmp(old + len, "/bin:", 5) != 0) {
if (snprintf(pathbuf, sizeof(pathbuf), "%s/bin:%s/bin/applets:%s",
prefix, prefix, old != NULL ? old : "/system/bin")
< (int)sizeof(pathbuf))
setenv("PATH", pathbuf, 1);
}
if (snprintf(libbuf, sizeof(libbuf), "%s/lib",
prefix) < (int)sizeof(libbuf))
setenv("LD_LIBRARY_PATH", libbuf, 1);
}
/*
* Maintainer scripts inside a Termux package are written in terms of the
* Termux prefix:
*
* #!/data/data/com.termux/files/usr/bin/sh
* mkdir -p "/data/data/com.termux/files/usr/var/empty"
* KEYFILE="/data/data/com.termux/files/usr/etc/ssh/ssh_host_rsa_key"
*
* Neither form works for us. The interpreter line is resolved by the kernel
* and lands in another application's private directory (EACCES, which dpkg
* then reports as though the script itself were not executable), and the
* absolute paths are absolute -- our sandbox symlinks live under our own
* prefix and cannot intercept a path that starts at "/".
*
* The scripts are plain text, so rewrite both before executing them. This is
* a local edit of the dpkg database rather than a change to the package, so
* it also covers packages installed long after this code was written.
*/
#define DOUBAO_OLD_PREFIX "/data/data/com.termux/files/usr"
static void
doubao_rewrite_script(const char *path)
{
char *buf;
char *out;
const char *prefix;
size_t oldlen = sizeof(DOUBAO_OLD_PREFIX) - 1;
size_t newlen, len, cap;
size_t i, o;
int fd;
ssize_t n;
struct stat st;
if (path == NULL)
return;
fd = open(path, O_RDONLY);
if (fd < 0)
return;
if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode) || st.st_size <= 0 ||
st.st_size > 1024 * 1024) {
close(fd);
return;
}
len = (size_t)st.st_size;
buf = malloc(len + 1);
if (buf == NULL) {
close(fd);
return;
}
n = read(fd, buf, len);
close(fd);
if (n <= 0) {
free(buf);
return;
}
buf[n] = '\0';
len = (size_t)n;
prefix = doubao_prefix();
newlen = strlen(prefix);
/* 先看有没有要换的东西,没有就别写盘 */
for (i = 0; i + oldlen <= len; i++) {
if (memcmp(buf + i, DOUBAO_OLD_PREFIX, oldlen) == 0)
break;
}
if (i + oldlen > len) {
free(buf);
return;
}
/* 每一步替换都会变长(我们的前缀比 Termux 的长),所以要放大缓冲 */
cap = len + 64;
out = malloc(cap);
if (out == NULL) {
free(buf);
return;
}
for (i = 0, o = 0; i < len; ) {
if (i + oldlen <= len &&
memcmp(buf + i, DOUBAO_OLD_PREFIX, oldlen) == 0) {
if (o + newlen + (len - i) + 2 > cap) {
cap = (o + newlen + (len - i) + 2) * 2;
out = realloc(out, cap);
if (out == NULL) {
free(buf);
return;
}
}
memcpy(out + o, prefix, newlen);
o += newlen;
i += oldlen;
} else {
out[o++] = buf[i++];
}
}
out[o] = '\0';
free(buf);
fd = open(path, O_WRONLY | O_TRUNC);
if (fd < 0) {
free(out);
return;
}
if (write(fd, out, o) != (ssize_t)o) {
close(fd);
free(out);
ohshite(_("unable to rewrite maintainer script '%.250s'"), path);
}
close(fd);
free(out);
debug(dbg_scripts, "rewrote prefix in maintainer script '%s'", path);
}
/*
* 把维护脚本的 shebang 换成本安装自己的 shell。
*
* 保留原来用的是哪个 shell(`sh` 还是 `bash`)—— 换错解释器会毁掉脚本,
* 这一条真踩过:把 `bin/pip`(Python 脚本)的 shebang 改成 bash,
* 于是报 `bin/pip: line 2: import: command not found`。
* 规则是"只换路径,不动解释器"。
*/
void
doubao_fix_script_shebang(const char *path)
{
static const char old_shebang[] = "#!/data/data/com.termux/files/usr/";
/* Android 上 /data/user/0/<pkg> 和 /data/data/<pkg> 是同一个目录的两种
* 写法,包里两种都出现过,所以两个都要认。 */
static const char old_shebang_alt[] = "#!/data/user/0/com.termux/files/usr/";
char buf[PATH_MAX + 256];
const char *prefix;
char *nl;
int fd;
ssize_t n;
ssize_t skip = -1;
size_t head, rest, total;
char *fixed;
if (path == NULL)
return;
/* 先把正文里的绝对路径改掉(`#!/...` 那行也会一起被改到) */
doubao_rewrite_script(path);
fd = open(path, O_RDONLY);
if (fd < 0)
return;
n = read(fd, buf, sizeof(buf) - 1);
close(fd);
if (n <= 0)
return;
buf[n] = '\0';
if (strncmp(buf, old_shebang, sizeof(old_shebang) - 1) == 0)
skip = (ssize_t)(sizeof(old_shebang) - 1);
else if (strncmp(buf, old_shebang_alt, sizeof(old_shebang_alt) - 1) == 0)
skip = (ssize_t)(sizeof(old_shebang_alt) - 1);
if (skip < 0)
return;
nl = strchr(buf, '\n');
if (nl == NULL)
return;
prefix = doubao_prefix();
head = 2 + strlen(prefix) + 1; /* "#!/" + prefix + "/" */
rest = (size_t)n - (size_t)skip; /* 旧前缀之后的一直到文件尾 */
total = head + rest;
if (total + 1 > sizeof(buf))
return;
fixed = malloc(total + 1);
if (fixed == NULL)
return;
fixed[0] = '#';
fixed[1] = '!';
memcpy(fixed + 2, prefix, strlen(prefix));
fixed[2 + strlen(prefix)] = '/';
memcpy(fixed + head, buf + skip, rest);
fixed[total] = '\0';
fd = open(path, O_WRONLY | O_TRUNC);
if (fd < 0) {
free(fixed);
return;
}
if (write(fd, fixed, total) != (ssize_t)total)
ohshite(_("unable to rewrite maintainer script '%.250s'"), path);
close(fd);
free(fixed);
debug(dbg_scripts, "rewrote interpreter line of '%s'", path);
}
'''
write_patch("lib/dpkg/doubao-prefix.h", "", HEADER, "doubao-prefix-h.patch")
write_patch("lib/dpkg/doubao-prefix.c", "", IMPL, "doubao-prefix-c.patch")
# ======================================================================
# 3. Makefile.am:加入源文件 + 定义兜底前缀
# ======================================================================
ma = git_show("lib/dpkg/Makefile.am")
out, added_src, added_def = [], False, False
for ln in ma.split("\n"):
out.append(ln)
if not added_src and ln.strip() == "utils.c \\":
out.append("\tdoubao-prefix.c \\")
added_src = True
if not added_def and ln.strip().startswith("-DDEFAULT_TEXT_DOMAIN="):
# 兜底前缀:正常由 /proc/self/exe 推导,这行只是推导失败时的退路
out.append("\t-DDOUBAO_DEFAULT_PREFIX=\\\"$(prefix)\\\" \\")
added_def = True
assert added_src and added_def, "Makefile.am 结构变了,插入点找不到"
new_ma = "\n".join(out)
if "\tdpkg.h \\" in new_ma:
new_ma = new_ma.replace("\tdpkg.h \\", "\tdpkg.h \\\n\tdoubao-prefix.h \\", 1)
write_patch("lib/dpkg/Makefile.am", ma, new_ma, "doubao-prefix-makefile.patch")
# ======================================================================
# 4. options.c:配置目录改为运行时解析
# ======================================================================
oc = git_show("lib/dpkg/options.c")
new_oc = oc.replace("#include <dpkg/options.h>\n",
"#include <dpkg/options.h>\n#include <dpkg/doubao-prefix.h>\n", 1)
assert new_oc != oc, "options.c 里插入 include 失败"
new_oc = new_oc.replace('dirname = str_fmt("%s/%s.cfg.d", CONFIGDIR, prog);',
'dirname = str_fmt("%s/%s.cfg.d", doubao_config_dir(), prog);', 1)
new_oc = new_oc.replace('file = str_fmt("%s/%s.cfg", CONFIGDIR, prog);',
'file = str_fmt("%s/%s.cfg", doubao_config_dir(), prog);', 1)
assert "CONFIGDIR" not in new_oc, "options.c 里还有 CONFIGDIR 残留"
write_patch("lib/dpkg/options.c", oc, new_oc, "doubao-prefix-options.patch")
# ======================================================================
# 5. main.c:启动时修好 PATH
# ======================================================================
mc = git_show("src/main/main.c")
new_mc = mc.replace(
" dpkg_options_load(DPKG, cmdinfos);\n",
" dpkg_options_load(DPKG, cmdinfos);\n"
"\n"
" /* Another Android application may have handed us a PATH that points at\n"
" * its own prefix; repair ours before anything looks a program up. */\n"
" doubao_fix_environment();\n", 1)
assert new_mc != mc, "main.c 里插入 doubao_fix_environment 失败"
assert '#include "main.h"' in new_mc, "main.c 里找不到 main.h"
new_mc = new_mc.replace('#include "main.h"',
'#include "main.h"\n\n#include <dpkg/doubao-prefix.h>', 1)
write_patch("src/main/main.c", mc, new_mc, "doubao-prefix-main.patch")
# ======================================================================
# 6. script.c:三条执行路径都修 shebang
# ======================================================================
sc = git_show("src/main/script.c")
FIX = """ /* Termux packages ship maintainer scripts whose interpreter line names
* the Termux prefix; on Android that path belongs to another
* application and the kernel refuses to exec it. Point it at us. */
doubao_fix_script_shebang(%s);
"""
targets = [
(" if (stat(scriptpath, &stab)) {\n command_destroy(&cmd);\n", "scriptpath"),
(" if (stat(cidir, &stab)) {\n command_destroy(&cmd);\n", "cidir"),
(" if (stat(oldscriptpath, &stab)) {\n", "oldscriptpath"),
]
new_sc, total = sc, 0
for needle, arg in targets:
cnt = new_sc.count(needle)
assert cnt > 0, f"script.c 里找不到 {arg} 的 stat 块"
new_sc = new_sc.replace(needle, (FIX % arg) + needle)
total += cnt
print(f" script.c {arg}: {cnt} 处")
assert total >= 3, f"script.c 只修了 {total} 处,至少该有 3 处"
new_sc = new_sc.replace('#include "main.h"',
'#include "main.h"\n\n#include <dpkg/doubao-prefix.h>', 1)
write_patch("src/main/script.c", sc, new_sc, "doubao-prefix-script.patch")
# ======================================================================
# 7. 架构名:Termux 用的是 GNU CPU 名(x86_64 / aarch64 / arm / i686)
# ======================================================================
am = git_show("m4/dpkg-arch.m4")
OLD_ARCH = """AC_DEFUN([DPKG_ARCHITECTURE], [
DPKG_CPU_TYPE
DPKG_OS_TYPE
AC_MSG_CHECKING([dpkg architecture name])
_DPKG_ARCHITECTURE([DEB_HOST_ARCH], [dpkg_arch])
AS_IF([test "x$dpkg_arch" = "x"], [
AC_MSG_ERROR([cannot determine host dpkg architecture])
], [
AC_MSG_RESULT([$dpkg_arch])
])
AC_DEFINE_UNQUOTED([ARCHITECTURE], ["${dpkg_arch}"],
[Set this to the canonical dpkg architecture name.])
])# DPKG_ARCHITECTURE"""
NEW_ARCH = """AC_DEFUN([DPKG_ARCHITECTURE], [
DPKG_CPU_TYPE
DPKG_OS_TYPE
dnl Termux/Android: data/cputable, data/ostable and data/tupletable only
dnl describe the Debian and GNU worlds -- ostable has no "android" entry at
dnl all -- so the generic lookup below can never resolve a *-linux-android
dnl host triple and configure dies with "cannot determine host dpkg
dnl architecture".
dnl
dnl Termux names its architectures after the GNU CPU name (the repository
dnl serves x86_64, aarch64, arm and i686), and the package database shipped
dnl in our bootstrap was written with exactly those names, so we have to
dnl report the same thing or dpkg would reject every installed package.
dnl
dnl Note the host OS arrives as "linux-android", not "android": config.sub
dnl normalises --host=x86_64-linux-android into x86_64-pc-linux-android.
AS_CASE([$host_os],
[*android*], [
AS_CASE([$host_cpu],
[x86_64|aarch64|i686|arm], [dpkg_arch=$host_cpu],
[armv7*], [dpkg_arch=arm],
[AC_MSG_ERROR([unsupported Android CPU: $host_cpu])])
cpu_type=$host_cpu
os_type=android
have_dpkg_arch=yes
])
AS_IF([test "x$have_dpkg_arch" = "xyes"], [
AC_MSG_CHECKING([dpkg architecture name])
AC_MSG_RESULT([$dpkg_arch])
], [
AC_MSG_CHECKING([dpkg architecture name])
_DPKG_ARCHITECTURE([DEB_HOST_ARCH], [dpkg_arch])
AS_IF([test "x$dpkg_arch" = "x"], [
AC_MSG_ERROR([cannot determine host dpkg architecture])
], [
AC_MSG_RESULT([$dpkg_arch])
])
])
AC_DEFINE_UNQUOTED([ARCHITECTURE], ["${dpkg_arch}"],
[Set this to the canonical dpkg architecture name.])
])# DPKG_ARCHITECTURE"""
assert OLD_ARCH in am, "m4/dpkg-arch.m4 里找不到 DPKG_ARCHITECTURE 宏体"
write_patch("m4/dpkg-arch.m4", am, am.replace(OLD_ARCH, NEW_ARCH, 1),
"doubao-android-arch.patch")
# ======================================================================
# 8. 架构名校验:x86_64 / aarch64 带下划线,两边都要放开
# ======================================================================
ac = git_show("lib/dpkg/arch.c")
OLD_VAL = """\tif (!c_isalnum(*p))
\t\treturn _("must start with an alphanumeric");
\twhile (*++p != '\\0')
\t\tif (!c_isalnum(*p) && *p != '-')
\t\t\tbreak;
\tif (*p == '\\0')
\t\treturn NULL;
\tsnprintf(buf, sizeof(buf), _("character '%c' not allowed (only "
\t "letters, digits and characters '%s')"),
\t *p, "-");
\treturn buf;"""
NEW_VAL = """\t/* Termux/Android: Termux names its architectures after the GNU CPU
\t * name, and two of the four it serves -- x86_64 and aarch64 -- carry an
\t * underscore. Without this every package in the bootstrap database
\t * would be reported as having an invalid Architecture. */
\tif (!c_isalnum(*p))
\t\treturn _("must start with an alphanumeric");
\twhile (*++p != '\\0')
\t\tif (!c_isalnum(*p) && *p != '-' && *p != '_')
\t\t\tbreak;
\tif (*p == '\\0')
\t\treturn NULL;
\tsnprintf(buf, sizeof(buf), _("character '%c' not allowed (only "
\t "letters, digits and characters '%s')"),
\t *p, "-_");
\treturn buf;"""
assert OLD_VAL in ac, "lib/dpkg/arch.c 里找不到 dpkg_arch_name_is_illegal 函数体"
write_patch("lib/dpkg/arch.c", ac, ac.replace(OLD_VAL, NEW_VAL, 1),
"doubao-arch-name.patch")
ap = git_show("scripts/Dpkg/Arch.pm")
OLD_RE = " my $arch_re = qr/[a-zA-Z0-9][a-zA-Z0-9-]*/;"
NEW_RE = (" # Termux/Android: allow underscores, because Termux names\n"
" # architectures after the GNU CPU name and x86_64 / aarch64\n"
" # both contain one.\n"
" my $arch_re = qr/[a-zA-Z0-9][a-zA-Z0-9_-]*/;")
assert OLD_RE in ap, "scripts/Dpkg/Arch.pm 里找不到架构名正则"
write_patch("scripts/Dpkg/Arch.pm", ap, ap.replace(OLD_RE, NEW_RE, 1),
"doubao-debarch-name.patch")
print("\n全部生成到 " + OUT)

View File

@@ -0,0 +1,53 @@
#!/bin/bash
# 把编好的 dpkg 打包成 jniLibs 里的 libdoubao-dpkg.so。
#
# 为什么打成 tar 再改名成 .so:
# Android 安装 APK 时只对 lib/<abi>/*.so 免压缩解包,别的路径(assets/)
# 会被压缩、还得自己解压一遍。打成 tar 塞进 .so 里,安装完直接读就行,
# 也跟这个仓库里 libtermux-bootstrap.so 的做法一致。
#
# 用法: make-jnilibs.sh <工作目录> <输出 jniLibs 目录>
set -eu
WORK="${1:-${TERMUX_DPKG_WORK:-/root/tb}}"
JNI="${2:?用法: make-jnilibs.sh <工作目录> <jniLibs 目录>}"
PROGRAMS="dpkg dpkg-deb dpkg-query dpkg-divert dpkg-split dpkg-trigger"
# APK 的 abi 目录名跟我们的 arch 名不一样
declare -A ABI=( [x86_64]=x86_64 [arm64]=arm64-v8a )
for arch in x86_64 arm64; do
src="$WORK/out/$arch/dpkg-bin"
abi="${ABI[$arch]}"
dst="$JNI/$abi"
[ -d "$src" ] || { echo "!! 没有 $src,先跑 build-dpkg.sh $arch"; exit 1; }
mkdir -p "$dst"
stage="$(mktemp -d)"
for p in $PROGRAMS; do
[ -f "$src/$p" ] || { echo "!! 缺 $src/$p"; exit 1; }
cp "$src/$p" "$stage/$p"
chmod 755 "$stage/$p"
done
# tar 用固定的 uid/gid/mtime,保证同样输入产出同样字节(可复现)
tar --create --file "$dst/libdoubao-dpkg.so" \
--directory "$stage" \
--owner=0 --group=0 --numeric-owner \
--mtime='2026-01-01 00:00:00 UTC' \
--sort=name \
$PROGRAMS
rm -rf "$stage"
printf ' %-10s -> %-46s %s 字节\n' "$arch" "jniLibs/$abi/libdoubao-dpkg.so" \
"$(stat -c%s "$dst/libdoubao-dpkg.so")"
done
echo
echo "内容确认:"
for arch in x86_64 arm64; do
echo "--- ${ABI[$arch]} ---"
tar -tvf "$JNI/${ABI[$arch]}/libdoubao-dpkg.so"
done

View File

@@ -0,0 +1,48 @@
--- a/m4/dpkg-arch.m4 2026-10-14 12:41:34.709430018 +0800
+++ b/m4/dpkg-arch.m4 2026-10-14 12:41:34.709459828 +0800
@@ -55,12 +55,40 @@
AC_DEFUN([DPKG_ARCHITECTURE], [
DPKG_CPU_TYPE
DPKG_OS_TYPE
- AC_MSG_CHECKING([dpkg architecture name])
- _DPKG_ARCHITECTURE([DEB_HOST_ARCH], [dpkg_arch])
- AS_IF([test "x$dpkg_arch" = "x"], [
- AC_MSG_ERROR([cannot determine host dpkg architecture])
- ], [
+ dnl Termux/Android: data/cputable, data/ostable and data/tupletable only
+ dnl describe the Debian and GNU worlds -- ostable has no "android" entry at
+ dnl all -- so the generic lookup below can never resolve a *-linux-android
+ dnl host triple and configure dies with "cannot determine host dpkg
+ dnl architecture".
+ dnl
+ dnl Termux names its architectures after the GNU CPU name (the repository
+ dnl serves x86_64, aarch64, arm and i686), and the package database shipped
+ dnl in our bootstrap was written with exactly those names, so we have to
+ dnl report the same thing or dpkg would reject every installed package.
+ dnl
+ dnl Note the host OS arrives as "linux-android", not "android": config.sub
+ dnl normalises --host=x86_64-linux-android into x86_64-pc-linux-android.
+ AS_CASE([$host_os],
+ [*android*], [
+ AS_CASE([$host_cpu],
+ [x86_64|aarch64|i686|arm], [dpkg_arch=$host_cpu],
+ [armv7*], [dpkg_arch=arm],
+ [AC_MSG_ERROR([unsupported Android CPU: $host_cpu])])
+ cpu_type=$host_cpu
+ os_type=android
+ have_dpkg_arch=yes
+ ])
+ AS_IF([test "x$have_dpkg_arch" = "xyes"], [
+ AC_MSG_CHECKING([dpkg architecture name])
AC_MSG_RESULT([$dpkg_arch])
+ ], [
+ AC_MSG_CHECKING([dpkg architecture name])
+ _DPKG_ARCHITECTURE([DEB_HOST_ARCH], [dpkg_arch])
+ AS_IF([test "x$dpkg_arch" = "x"], [
+ AC_MSG_ERROR([cannot determine host dpkg architecture])
+ ], [
+ AC_MSG_RESULT([$dpkg_arch])
+ ])
])
AC_DEFINE_UNQUOTED([ARCHITECTURE], ["${dpkg_arch}"],
[Set this to the canonical dpkg architecture name.])

View File

@@ -0,0 +1,26 @@
--- a/lib/dpkg/arch.c 2026-10-14 12:41:34.729574429 +0800
+++ b/lib/dpkg/arch.c 2026-10-14 12:41:34.729607515 +0800
@@ -62,17 +62,21 @@
internerr("arch name argument is NULL");
if (!*p)
return _("may not be empty string");
+ /* Termux/Android: Termux names its architectures after the GNU CPU
+ * name, and two of the four it serves -- x86_64 and aarch64 -- carry an
+ * underscore. Without this every package in the bootstrap database
+ * would be reported as having an invalid Architecture. */
if (!c_isalnum(*p))
return _("must start with an alphanumeric");
while (*++p != '\0')
- if (!c_isalnum(*p) && *p != '-')
+ if (!c_isalnum(*p) && *p != '-' && *p != '_')
break;
if (*p == '\0')
return NULL;
snprintf(buf, sizeof(buf), _("character '%c' not allowed (only "
"letters, digits and characters '%s')"),
- *p, "-");
+ *p, "-_");
return buf;
}

View File

@@ -0,0 +1,14 @@
--- a/scripts/Dpkg/Arch.pm 2026-10-14 12:41:34.752824615 +0800
+++ b/scripts/Dpkg/Arch.pm 2026-10-14 12:41:34.752929467 +0800
@@ -612,7 +612,10 @@
sub debarch_is_illegal
{
my ($arch, %opts) = @_;
- my $arch_re = qr/[a-zA-Z0-9][a-zA-Z0-9-]*/;
+ # Termux/Android: allow underscores, because Termux names
+ # architectures after the GNU CPU name and x86_64 / aarch64
+ # both contain one.
+ my $arch_re = qr/[a-zA-Z0-9][a-zA-Z0-9_-]*/;
if ($opts{positive}) {
return $arch !~ m/^$arch_re$/;

View File

@@ -0,0 +1,352 @@
--- a/lib/dpkg/doubao-prefix.c 2026-10-14 12:41:34.595602235 +0800
+++ b/lib/dpkg/doubao-prefix.c 2026-10-14 12:41:34.600860227 +0800
@@ -0,0 +1,349 @@
+/*
+ * doubao-prefix.c - resolve the installation prefix at runtime
+ *
+ * Copyright (C) 2026 doubao-clone
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Upstream dpkg bakes its configuration directory in at configure time
+ * (-DCONFIGDIR), and Termux builds it as $PREFIX/etc/dpkg where $PREFIX is a
+ * fixed absolute path chosen by the Termux application. Android gives every
+ * application its own private data directory, so a dpkg built for
+ * com.termux will always look inside /data/data/com.termux -- a directory
+ * another application is not allowed to traverse. The resulting EACCES makes
+ * dpkg abort before it has even parsed its command line, which is why the two
+ * applications cannot coexist.
+ *
+ * We instead derive the prefix from the path of the running executable, which
+ * is exactly where this binary happens to live. That also lets us repair
+ * PATH, LD_LIBRARY_PATH and the interpreter lines of maintainer scripts,
+ * all of which upstream assumes are already correct.
+ */
+
+#include <config.h>
+#include <compat.h>
+
+#include <fcntl.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include <dpkg/i18n.h>
+#include <dpkg/debug.h>
+#include <dpkg/dpkg.h>
+#include <dpkg/doubao-prefix.h>
+
+/* How many distinct strings we keep alive so returned pointers stay valid. */
+#define DOUBAO_CACHE_SLOTS 4
+
+static char prefix_buf[PATH_MAX];
+static const char *prefix_cached;
+static char config_buf[PATH_MAX];
+
+static void
+doubao_prefix_resolve(void)
+{
+ char self[PATH_MAX];
+ const char *override;
+ char *slash;
+ ssize_t n;
+
+ if (prefix_cached != NULL)
+ return;
+
+ prefix_cached = DOUBAO_DEFAULT_PREFIX;
+
+ override = getenv("DOUBAO_DPKG_PREFIX");
+ if (override != NULL) {
+ if (*override != '\0' && strlen(override) < sizeof(prefix_buf)) {
+ strcpy(prefix_buf, override);
+ prefix_cached = prefix_buf;
+ }
+ return;
+ }
+
+ n = readlink("/proc/self/exe", self, sizeof(self) - 1);
+ if (n <= 0 || (size_t)n >= sizeof(self) - 1)
+ return;
+ self[n] = '\0';
+
+ /* .../bin/dpkg -> .../bin -> ... */
+ slash = strrchr(self, '/');
+ if (slash == NULL)
+ return;
+ *slash = '\0';
+
+ slash = strrchr(self, '/');
+ if (slash == NULL)
+ return;
+ *slash = '\0';
+
+ if (strlen(self) < sizeof(prefix_buf)) {
+ strcpy(prefix_buf, self);
+ prefix_cached = prefix_buf;
+ }
+}
+
+const char *
+doubao_prefix(void)
+{
+ doubao_prefix_resolve();
+ return prefix_cached;
+}
+
+const char *
+doubao_config_dir(void)
+{
+ const char *prefix = doubao_prefix();
+
+ if (snprintf(config_buf, sizeof(config_buf), "%s/etc/dpkg", prefix)
+ >= (int)sizeof(config_buf))
+ return CONFIGDIR;
+
+ return config_buf;
+}
+
+/*
+ * Prepend our own bin directories to PATH and make sure the loader can find
+ * our shared libraries, so that dpkg and the maintainer scripts it runs work
+ * no matter what environment our parent handed us.
+ */
+void
+doubao_fix_environment(void)
+{
+ static bool done = false;
+ static char pathbuf[4 * PATH_MAX];
+ static char libbuf[PATH_MAX + 64];
+
+ const char *prefix, *old;
+ size_t len;
+
+ if (done)
+ return;
+ done = true;
+
+ prefix = doubao_prefix();
+
+ old = getenv("PATH");
+ /* Only prepend when our prefix is not already the first entry, so that
+ * a re-exec does not keep growing PATH. */
+ len = strlen(prefix);
+ if (old == NULL || strncmp(old, prefix, len) != 0 ||
+ strncmp(old + len, "/bin:", 5) != 0) {
+ if (snprintf(pathbuf, sizeof(pathbuf), "%s/bin:%s/bin/applets:%s",
+ prefix, prefix, old != NULL ? old : "/system/bin")
+ < (int)sizeof(pathbuf))
+ setenv("PATH", pathbuf, 1);
+ }
+
+ if (snprintf(libbuf, sizeof(libbuf), "%s/lib",
+ prefix) < (int)sizeof(libbuf))
+ setenv("LD_LIBRARY_PATH", libbuf, 1);
+}
+
+/*
+ * Maintainer scripts inside a Termux package are written in terms of the
+ * Termux prefix:
+ *
+ * #!/data/data/com.termux/files/usr/bin/sh
+ * mkdir -p "/data/data/com.termux/files/usr/var/empty"
+ * KEYFILE="/data/data/com.termux/files/usr/etc/ssh/ssh_host_rsa_key"
+ *
+ * Neither form works for us. The interpreter line is resolved by the kernel
+ * and lands in another application's private directory (EACCES, which dpkg
+ * then reports as though the script itself were not executable), and the
+ * absolute paths are absolute -- our sandbox symlinks live under our own
+ * prefix and cannot intercept a path that starts at "/".
+ *
+ * The scripts are plain text, so rewrite both before executing them. This is
+ * a local edit of the dpkg database rather than a change to the package, so
+ * it also covers packages installed long after this code was written.
+ */
+#define DOUBAO_OLD_PREFIX "/data/data/com.termux/files/usr"
+
+static void
+doubao_rewrite_script(const char *path)
+{
+ char *buf;
+ char *out;
+ const char *prefix;
+ size_t oldlen = sizeof(DOUBAO_OLD_PREFIX) - 1;
+ size_t newlen, len, cap;
+ size_t i, o;
+ int fd;
+ ssize_t n;
+ struct stat st;
+
+ if (path == NULL)
+ return;
+
+ fd = open(path, O_RDONLY);
+ if (fd < 0)
+ return;
+ if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode) || st.st_size <= 0 ||
+ st.st_size > 1024 * 1024) {
+ close(fd);
+ return;
+ }
+
+ len = (size_t)st.st_size;
+ buf = malloc(len + 1);
+ if (buf == NULL) {
+ close(fd);
+ return;
+ }
+ n = read(fd, buf, len);
+ close(fd);
+ if (n <= 0) {
+ free(buf);
+ return;
+ }
+ buf[n] = '\0';
+ len = (size_t)n;
+
+ prefix = doubao_prefix();
+ newlen = strlen(prefix);
+
+ /* 先看有没有要换的东西,没有就别写盘 */
+ for (i = 0; i + oldlen <= len; i++) {
+ if (memcmp(buf + i, DOUBAO_OLD_PREFIX, oldlen) == 0)
+ break;
+ }
+ if (i + oldlen > len) {
+ free(buf);
+ return;
+ }
+
+ /* 每一步替换都会变长(我们的前缀比 Termux 的长),所以要放大缓冲 */
+ cap = len + 64;
+ out = malloc(cap);
+ if (out == NULL) {
+ free(buf);
+ return;
+ }
+
+ for (i = 0, o = 0; i < len; ) {
+ if (i + oldlen <= len &&
+ memcmp(buf + i, DOUBAO_OLD_PREFIX, oldlen) == 0) {
+ if (o + newlen + (len - i) + 2 > cap) {
+ cap = (o + newlen + (len - i) + 2) * 2;
+ out = realloc(out, cap);
+ if (out == NULL) {
+ free(buf);
+ return;
+ }
+ }
+ memcpy(out + o, prefix, newlen);
+ o += newlen;
+ i += oldlen;
+ } else {
+ out[o++] = buf[i++];
+ }
+ }
+ out[o] = '\0';
+ free(buf);
+
+ fd = open(path, O_WRONLY | O_TRUNC);
+ if (fd < 0) {
+ free(out);
+ return;
+ }
+ if (write(fd, out, o) != (ssize_t)o) {
+ close(fd);
+ free(out);
+ ohshite(_("unable to rewrite maintainer script '%.250s'"), path);
+ }
+ close(fd);
+ free(out);
+
+ debug(dbg_scripts, "rewrote prefix in maintainer script '%s'", path);
+}
+
+/*
+ * 把维护脚本的 shebang 换成本安装自己的 shell。
+ *
+ * 保留原来用的是哪个 shell(`sh` 还是 `bash`)—— 换错解释器会毁掉脚本,
+ * 这一条真踩过:把 `bin/pip`(Python 脚本)的 shebang 改成 bash,
+ * 于是报 `bin/pip: line 2: import: command not found`。
+ * 规则是"只换路径,不动解释器"。
+ */
+void
+doubao_fix_script_shebang(const char *path)
+{
+ static const char old_shebang[] = "#!/data/data/com.termux/files/usr/";
+ /* Android 上 /data/user/0/<pkg> 和 /data/data/<pkg> 是同一个目录的两种
+ * 写法,包里两种都出现过,所以两个都要认。 */
+ static const char old_shebang_alt[] = "#!/data/user/0/com.termux/files/usr/";
+
+ char buf[PATH_MAX + 256];
+ const char *prefix;
+ char *nl;
+ int fd;
+ ssize_t n;
+ ssize_t skip = -1;
+ size_t head, rest, total;
+ char *fixed;
+
+ if (path == NULL)
+ return;
+
+ /* 先把正文里的绝对路径改掉(`#!/...` 那行也会一起被改到) */
+ doubao_rewrite_script(path);
+
+ fd = open(path, O_RDONLY);
+ if (fd < 0)
+ return;
+
+ n = read(fd, buf, sizeof(buf) - 1);
+ close(fd);
+ if (n <= 0)
+ return;
+ buf[n] = '\0';
+
+ if (strncmp(buf, old_shebang, sizeof(old_shebang) - 1) == 0)
+ skip = (ssize_t)(sizeof(old_shebang) - 1);
+ else if (strncmp(buf, old_shebang_alt, sizeof(old_shebang_alt) - 1) == 0)
+ skip = (ssize_t)(sizeof(old_shebang_alt) - 1);
+
+ if (skip < 0)
+ return;
+
+ nl = strchr(buf, '\n');
+ if (nl == NULL)
+ return;
+
+ prefix = doubao_prefix();
+ head = 2 + strlen(prefix) + 1; /* "#!/" + prefix + "/" */
+ rest = (size_t)n - (size_t)skip; /* 旧前缀之后的一直到文件尾 */
+ total = head + rest;
+ if (total + 1 > sizeof(buf))
+ return;
+
+ fixed = malloc(total + 1);
+ if (fixed == NULL)
+ return;
+
+ fixed[0] = '#';
+ fixed[1] = '!';
+ memcpy(fixed + 2, prefix, strlen(prefix));
+ fixed[2 + strlen(prefix)] = '/';
+ memcpy(fixed + head, buf + skip, rest);
+ fixed[total] = '\0';
+
+ fd = open(path, O_WRONLY | O_TRUNC);
+ if (fd < 0) {
+ free(fixed);
+ return;
+ }
+ if (write(fd, fixed, total) != (ssize_t)total)
+ ohshite(_("unable to rewrite maintainer script '%.250s'"), path);
+ close(fd);
+ free(fixed);
+
+ debug(dbg_scripts, "rewrote interpreter line of '%s'", path);
+}

View File

@@ -0,0 +1,55 @@
--- a/lib/dpkg/doubao-prefix.h 2026-10-14 12:41:34.579902172 +0800
+++ b/lib/dpkg/doubao-prefix.h 2026-10-14 12:41:34.580926465 +0800
@@ -0,0 +1,52 @@
+/*
+ * doubao-prefix.h - resolve the installation prefix at runtime
+ *
+ * Copyright (C) 2026 doubao-clone
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ */
+
+#ifndef DOUBAO_PREFIX_H
+#define DOUBAO_PREFIX_H
+
+#include <dpkg/dpkg.h>
+
+DPKG_BEGIN_DECLS
+
+/**
+ * Return the prefix this dpkg was installed under.
+ *
+ * The prefix is derived from the path of the running executable, because
+ * Android hands every application its own private data directory and the
+ * same binary has to work under any of them. Falls back to the compile-time
+ * DOUBAO_DEFAULT_PREFIX when the executable path cannot be determined.
+ */
+const char *doubao_prefix(void);
+
+/**
+ * Return the configuration directory ($prefix/etc/dpkg).
+ */
+const char *doubao_config_dir(void);
+
+/**
+ * Prepend our own bin directories to PATH and point LD_LIBRARY_PATH at our
+ * own lib directory.
+ *
+ * Needed because apt sanitises the environment before it execs dpkg, and the
+ * PATH it hands over names the *other* application's prefix; dpkg would then
+ * fail its own sanity check with "expected programs not found in PATH".
+ */
+void doubao_fix_environment(void);
+
+/**
+ * Rewrite a maintainer script's interpreter line so it points at this
+ * installation instead of the application it was built for.
+ */
+void doubao_fix_script_shebang(const char *path);
+
+DPKG_END_DECLS
+
+#endif /* DOUBAO_PREFIX_H */

View File

@@ -0,0 +1,22 @@
--- a/src/main/main.c 2026-10-14 12:41:34.673058919 +0800
+++ b/src/main/main.c 2026-10-14 12:41:34.673178642 +0800
@@ -53,6 +53,8 @@
#include <dpkg/db-fsys.h>
#include "main.h"
+
+#include <dpkg/doubao-prefix.h>
#include "filters.h"
static int
@@ -736,6 +738,10 @@
dpkg_program_init("dpkg");
set_force_default(FORCE_ALL);
dpkg_options_load(DPKG, cmdinfos);
+
+ /* Another Android application may have handed us a PATH that points at
+ * its own prefix; repair ours before anything looks a program up. */
+ doubao_fix_environment();
dpkg_options_parse(&argv, cmdinfos, printforhelp);
debug(dbg_general, "root=%s admindir=%s", dpkg_fsys_get_dir(), dpkg_db_get_dir());

View File

@@ -0,0 +1,26 @@
--- a/lib/dpkg/Makefile.am 2026-10-14 12:41:34.636534337 +0800
+++ b/lib/dpkg/Makefile.am 2026-10-14 12:41:34.636659433 +0800
@@ -5,6 +5,7 @@
-DCONFIGDIR=\"$(pkgconfdir)\" \
-DADMINDIR=\"$(admindir)\" \
-DDEFAULT_TEXT_DOMAIN=\"@PACKAGE@\" \
+ -DDOUBAO_DEFAULT_PREFIX=\"$(prefix)\" \
-idirafter $(top_srcdir)/lib/compat \
-I$(top_builddir) \
-I$(top_srcdir)/lib \
@@ -132,6 +133,7 @@
triglib.c \
trigdeferred.c \
utils.c \
+ doubao-prefix.c \
varbuf.c \
version.c \
# EOL
@@ -151,6 +153,7 @@
debug.h \
dir.h \
dpkg.h \
+ doubao-prefix.h \
dpkg-db.h \
ehandle.h \
error.h \

View File

@@ -0,0 +1,28 @@
--- a/lib/dpkg/options.c 2026-10-14 12:41:34.656076933 +0800
+++ b/lib/dpkg/options.c 2026-10-14 12:41:34.656194326 +0800
@@ -35,6 +35,7 @@
#include <dpkg/dpkg.h>
#include <dpkg/string.h>
#include <dpkg/options.h>
+#include <dpkg/doubao-prefix.h>
static const char *printforhelp;
@@ -166,7 +167,7 @@
struct dirent **dlist;
int dlist_n, i;
- dirname = str_fmt("%s/%s.cfg.d", CONFIGDIR, prog);
+ dirname = str_fmt("%s/%s.cfg.d", doubao_config_dir(), prog);
dlist_n = scandir(dirname, &dlist, valid_config_filename, alphasort);
if (dlist_n < 0) {
@@ -198,7 +199,7 @@
dpkg_options_load_dir(prog, cmdinfos);
- file = str_fmt("%s/%s.cfg", CONFIGDIR, prog);
+ file = str_fmt("%s/%s.cfg", doubao_config_dir(), prog);
dpkg_options_load_file(file, cmdinfos);
free(file);

View File

@@ -0,0 +1,59 @@
--- a/src/main/script.c 2026-10-14 12:41:34.690665764 +0800
+++ b/src/main/script.c 2026-10-14 12:41:34.690708349 +0800
@@ -47,6 +47,8 @@
#include "main.h"
+#include <dpkg/doubao-prefix.h>
+
void
post_postinst_tasks(struct pkginfo *pkg, enum pkgstatus new_status)
{
@@ -230,6 +232,11 @@
command_add_arg(&cmd, scriptname);
command_add_argv(&cmd, args);
+ /* Termux packages ship maintainer scripts whose interpreter line names
+ * the Termux prefix; on Android that path belongs to another
+ * application and the kernel refuses to exec it. Point it at us. */
+ doubao_fix_script_shebang(scriptpath);
+
if (stat(scriptpath, &stab)) {
command_destroy(&cmd);
@@ -306,6 +313,11 @@
command_add_argv(&cmd, args);
va_end(args);
+ /* Termux packages ship maintainer scripts whose interpreter line names
+ * the Termux prefix; on Android that path belongs to another
+ * application and the kernel refuses to exec it. Point it at us. */
+ doubao_fix_script_shebang(cidir);
+
if (stat(cidir, &stab)) {
command_destroy(&cmd);
@@ -347,6 +359,11 @@
versiondescribe(&pkg->available.version, vdew_nonambig),
NULL);
+ /* Termux packages ship maintainer scripts whose interpreter line names
+ * the Termux prefix; on Android that path belongs to another
+ * application and the kernel refuses to exec it. Point it at us. */
+ doubao_fix_script_shebang(oldscriptpath);
+
if (stat(oldscriptpath, &stab)) {
if (errno == ENOENT) {
debug(dbg_scripts,
@@ -377,6 +394,11 @@
versiondescribe(&pkg->available.version, vdew_nonambig),
NULL);
+ /* Termux packages ship maintainer scripts whose interpreter line names
+ * the Termux prefix; on Android that path belongs to another
+ * application and the kernel refuses to exec it. Point it at us. */
+ doubao_fix_script_shebang(cidir);
+
if (stat(cidir, &stab)) {
command_destroy(&cmd);

View File

@@ -0,0 +1,14 @@
diff -u -r ../dpkg-1.17.6/lib/dpkg/dbmodify.c ./lib/dpkg/dbmodify.c
--- ../dpkg-1.17.6/lib/dpkg/dbmodify.c 2013-12-14 06:36:07.000000000 +0100
+++ ./lib/dpkg/dbmodify.c 2014-02-25 18:12:15.000000000 +0100
@@ -253,8 +253,10 @@
switch (readwritereq) {
case msdbrw_needsuperuser:
case msdbrw_needsuperuserlockonly:
+#ifndef __ANDROID__
if (getuid() || geteuid())
ohshit(_("requested operation requires superuser privilege"));
+#endif
/* Fall through. */
case msdbrw_write: case msdbrw_writeifposs:
if (access(dpkg_db_get_dir(), W_OK)) {

View File

@@ -0,0 +1,20 @@
diff -u -r ../dpkg-1.18.2/lib/dpkg/atomic-file.c ./lib/dpkg/atomic-file.c
--- ../dpkg-1.18.2/lib/dpkg/atomic-file.c 2015-07-12 22:38:47.000000000 -0400
+++ ./lib/dpkg/atomic-file.c 2015-08-25 18:06:51.689715379 -0400
@@ -90,8 +90,14 @@
if (unlink(name_old) && errno != ENOENT)
ohshite(_("error removing old backup file '%s'"), name_old);
- if (link(file->name, name_old) && errno != ENOENT)
- ohshite(_("error creating new backup file '%s'"), name_old);
+#ifdef __ANDROID__
+ /* Termux: Use rename(2) since Android does not support hardlinks. */
+ if (rename(file->name, name_old) && errno != ENOENT) {
+#else
+ if (link(file->name, name_old) && errno != ENOENT) {
+#endif
+ ohshite(_("error creating new backup file '%s'"), name_old);
+ }
free(name_old);
}

View File

@@ -0,0 +1,20 @@
Handle EROFS. This is since path_remove_tree() will be called with
'/data.dpkg-tmp'
'/data/data.dpkg-tmp'
'/data/data/com.termux.dpkg-tmp'
'/data/data/com.termux/files.dpkg-tmp'
'/data/data/com.termux/files/usr.dpkg-tmp'
and the first call will get a EROFS, read-only file system error.
diff -u -r ../dpkg-1.18.2/lib/dpkg/path-remove.c ./lib/dpkg/path-remove.c
--- ../dpkg-1.18.2/lib/dpkg/path-remove.c 2015-07-30 00:39:24.000000000 -0400
+++ ./lib/dpkg/path-remove.c 2015-08-25 18:04:31.391421421 -0400
@@ -126,7 +126,7 @@
debug(dbg_eachfile, "%s '%s'", __func__, pathname);
if (!rmdir(pathname))
return; /* Deleted it OK, it was a directory. */
- if (errno == ENOENT || errno == ELOOP)
+ if (errno == ENOENT || errno == ELOOP || errno == EROFS)
return;
if (errno == ENOTDIR) {
/* Either it's a file, or one of the path components is. If

View File

@@ -0,0 +1,73 @@
diff -u -r src-orig/src/main/archives.c src/src/main/archives.c
--- src-orig/src/main/archives.c 2024-03-03 01:30:15.000000000 +0000
+++ src/src/main/archives.c 2024-05-05 20:36:54.148725216 +0000
@@ -394,9 +394,11 @@
namenode->statoverride->uid,
namenode->statoverride->gid,
namenode->statoverride->mode);
+#ifndef __ANDROID__
rc = fchown(fd, st->uid, st->gid);
if (forcible_nonroot_error(rc))
ohshite(_("error setting ownership of '%.255s'"), te->name);
+#endif
rc = fchmod(fd, st->mode & ~S_IFMT);
if (forcible_nonroot_error(rc))
ohshite(_("error setting permissions of '%.255s'"), te->name);
@@ -509,13 +511,17 @@
return; /* Already handled using the file descriptor. */
if (te->type == TAR_FILETYPE_SYMLINK) {
+#ifndef __ANDROID__
rc = lchown(path, st->uid, st->gid);
if (forcible_nonroot_error(rc))
ohshite(_("error setting ownership of symlink '%.255s'"), path);
+#endif
} else {
+#ifndef __ANDROID__
rc = chown(path, st->uid, st->gid);
if (forcible_nonroot_error(rc))
ohshite(_("error setting ownership of '%.255s'"), path);
+#endif
rc = chmod(path, st->mode & ~S_IFMT);
if (forcible_nonroot_error(rc))
ohshite(_("error setting permissions of '%.255s'"), path);
@@ -555,9 +561,11 @@
else if (linksize > stab->st_size)
ohshit(_("symbolic link '%.250s' size has changed from %jd to %zd"),
fn_old, (intmax_t)stab->st_size, linksize);
+#ifndef __ANDROID__
else if (linksize < stab->st_size)
warning(_("symbolic link '%.250s' size has changed from %jd to %zd"),
fn_old, (intmax_t)stab->st_size, linksize);
+#endif
linkmatch = strcmp(linkname.buf, te->linkname) == 0;
varbuf_destroy(&linkname);
if (linkmatch)
@@ -1053,18 +1061,27 @@
else if (linksize > stab.st_size)
ohshit(_("symbolic link '%.250s' size has changed from %jd to %zd"),
fnamevb.buf, (intmax_t)stab.st_size, linksize);
+#ifndef __ANDROID__
else if (linksize < stab.st_size)
warning(_("symbolic link '%.250s' size has changed from %jd to %zd"),
fnamevb.buf, (intmax_t)stab.st_size, linksize);
+#endif
if (symlink(symlinkfn.buf,fnametmpvb.buf))
ohshite(_("unable to make backup symlink for '%.255s'"), ti->name);
+#ifndef __ANDROID__
rc = lchown(fnametmpvb.buf, stab.st_uid, stab.st_gid);
if (forcible_nonroot_error(rc))
ohshite(_("unable to chown backup symlink for '%.255s'"), ti->name);
+#endif
tarobject_set_se_context(fnamevb.buf, fnametmpvb.buf, stab.st_mode);
} else {
debug(dbg_eachfiledetail, "tarobject nondirectory, 'link' backup");
+#ifdef __ANDROID__
+ /* Android does not support hardlinks. */
+ if (rename(fnamevb.buf,fnametmpvb.buf))
+#else
if (link(fnamevb.buf,fnametmpvb.buf))
+#endif
ohshite(_("unable to make backup link of '%.255s' before installing new version"),
ti->name);
}

View File

@@ -0,0 +1,16 @@
diff -u -r ../dpkg-1.18.15/src/configure.c ./src/configure.c
--- ../dpkg-1.18.15/src/configure.c 2016-11-11 22:18:40.000000000 -0500
+++ ./src/main/configure.c 2016-12-03 16:32:43.719508056 -0500
@@ -497,8 +497,10 @@
pkg_name(pkg, pnaw_nonambig), cdr2.buf,
strerror(errno));
if (!(what & CFOF_USER_DEL))
- if (link(cdr.buf, cdr2.buf))
- warning(_("%s: failed to link '%.250s' to '%.250s': %s"),
+ /** Termux modification: Use rename(2) instead of link(2), to avoid hard
+ links which does not work on Android 6.0 or later. */
+ if (rename(cdr.buf, cdr2.buf))
+ warning(_("%s: failed to rename '%.250s' to '%.250s': %s"),
pkg_name(pkg, pnaw_nonambig), cdr.buf,
cdr2.buf, strerror(errno));
/* Fall through. */

View File

@@ -0,0 +1,14 @@
diff -u -r ../dpkg-1.19.2/src/help.c ./src/help.c
--- ../dpkg-1.19.2/src/help.c 2018-10-07 22:07:52.000000000 +0000
+++ ./src/main/help.c 2018-11-11 02:13:05.133548711 +0000
@@ -127,8 +127,10 @@
"update_dyld_shared_cache",
#elif defined(__GLIBC__) || defined(__UCLIBC__) || \
defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
+#ifndef __ANDROID__
"ldconfig",
#endif
+#endif
#if BUILD_START_STOP_DAEMON
"start-stop-daemon",
#endif

View File

@@ -0,0 +1,15 @@
diff --color -uNr ../dpkg-1.21.8/src/statoverride/main.c ./src/statoverride/main.c
--- ../dpkg-1.21.8/src/statoverride/main.c 2022-05-24 14:36:59.000000000 -0300
+++ ./src/statoverride/main.c 2022-05-31 07:39:44.829552700 -0300
@@ -188,9 +188,11 @@
{
int rc;
+#ifndef __ANDROID__
rc = chown(filename, filestat->uid, filestat->gid);
if (forcible_nonroot_error(rc) < 0)
ohshite(_("error setting ownership of '%.255s'"), filename);
+#endif
rc = chmod(filename, filestat->mode & ~S_IFMT);
if (forcible_nonroot_error(rc) < 0)
ohshite(_("error setting permissions of '%.255s'"), filename);

View File

@@ -0,0 +1,196 @@
#!/usr/bin/env python3
"""校验自编 dpkg 的硬性质。
这些性质每一条都对应一个真实踩过的坑,所以必须自动守住 —— 光靠"编译过了"
没有任何意义(编译过但跑不起来的情况在这一路上出现过很多次)。
用法:
python3 verify-dpkg.py <x86_64|arm64> [工作目录]
检查项:
1. 产物齐全,都是对应架构的 ELF
2. 二进制里出现的 com.termux 字符串**只能**是 shebang 修复函数自己要匹配的
那两个模式;出现别的(尤其是 /data/data/com.termux/files/usr/etc/dpkg
这类配置目录)就说明运行时前缀补丁没生效,装上必然 EACCES
3. 必须有 /proc/self/exe —— 运行时前缀就是靠它推导的
4. 必须有 /etc/dpkg 拼接
5. 不能出现旧的架构名 amd64/arm64(Termux 用 GNU CPU 名)
6. 源码里架构名校验已放开下划线
7. RUNPATH 必须指向前缀的 lib(dpkg 派生 dpkg-query 时不一定有环境变量)
8. 不能依赖 libmd.so(我们静态链进去了)
"""
import os
import re
import subprocess
import sys
ARCH = sys.argv[1] if len(sys.argv) > 1 else "x86_64"
WORK = sys.argv[2] if len(sys.argv) > 2 else os.environ.get("TERMUX_DPKG_WORK", "/root/tb")
HERE = os.path.dirname(os.path.abspath(__file__))
BIN = os.path.join(WORK, "out", ARCH, "dpkg-bin")
BUILD = os.path.join(WORK, "build", "dpkg-" + ARCH)
# readelf 报的是厂商全名,不是三元组简写
EXPECT_MACHINE = {"x86_64": "X86-64", "arm64": "AArch64"}.get(ARCH)
WANT_ARCH_NAME = {"x86_64": "x86_64", "arm64": "aarch64"}[ARCH]
PROGRAMS = ["dpkg", "dpkg-deb", "dpkg-query", "dpkg-divert", "dpkg-split", "dpkg-trigger"]
PREFIX = os.environ.get("DOUBAO_PREFIX", "/data/data/com.doubao.lynxclone/files/usr")
# 这些是重写函数**自己要匹配**的模式,必须存在(换了就说明补丁没生效)
ALLOWED_TERMUX = {
"#!/data/data/com.termux/files/usr/",
"#!/data/user/0/com.termux/files/usr/",
"/data/data/com.termux/files/usr",
}
fails, warns = [], []
def fail(m):
fails.append(m)
print(f" ✗ {m}")
def ok(m):
print(f" ✓ {m}")
def warn(m):
warns.append(m)
print(f" ! {m}")
def which(*names):
for n in names:
r = subprocess.run(["which", n], capture_output=True, text=True)
if r.returncode == 0:
return r.stdout.strip()
return None
def run(*cmd):
return subprocess.run(cmd, capture_output=True, text=True).stdout
READELF = which("llvm-readelf", "readelf")
STRINGS = which("llvm-strings", "strings")
print(f"=== 校验 {ARCH} 的 dpkg 产物 ===")
print(f" 产物: {BIN}")
if not os.path.isdir(BIN):
print(f"!! 目录不存在:{BIN}")
sys.exit(1)
# ---------------------------------------------------------------- 1
print("\n[1] 产物齐全 + ELF 架构正确")
present = []
for p in PROGRAMS:
f = os.path.join(BIN, p)
if not os.path.isfile(f):
fail(f"{p} 缺失")
continue
if open(f, "rb").read(4) != b"\x7fELF":
fail(f"{p} 不是 ELF")
continue
present.append(f)
if READELF:
m = re.search(r"Machine:\s*(.+)", run(READELF, "-h", f))
if m and EXPECT_MACHINE not in m.group(1):
fail(f"{p} 架构是 {m.group(1).strip()},期望含 {EXPECT_MACHINE}")
if present and not fails:
ok(f"{len(present)} 个程序都是 {EXPECT_MACHINE} 的 ELF")
# ---------------------------------------------------------------- 2
print("\n[2] com.termux 残留(只允许 shebang 匹配模式)")
if STRINGS is None:
warn("没有 strings 工具,跳过字符串检查")
else:
unexpected = []
for p in PROGRAMS:
f = os.path.join(BIN, p)
if not os.path.isfile(f):
continue
hits = [ln for ln in run(STRINGS, "-a", f).splitlines() if "com.termux" in ln]
extra = [h for h in hits if h not in ALLOWED_TERMUX]
if extra:
unexpected.append((p, extra[:3]))
if unexpected:
for p, hits in unexpected:
fail(f"{p} 里有非预期的 com.termux 字符串:{hits}")
else:
ok("只有 shebang 匹配模式,没有编译死的配置路径")
# ---------------------------------------------------------------- 3/4/5
print("\n[3-5] 运行时前缀解析 + 架构名")
f = os.path.join(BIN, "dpkg")
if STRINGS and os.path.isfile(f):
s = run(STRINGS, "-a", f)
lines = set(s.splitlines())
ok("有 /proc/self/exe") if "/proc/self/exe" in s else fail("没有 /proc/self/exe")
ok("有 %s/etc/dpkg 拼接") if "%s/etc/dpkg" in s else fail("没有 %s/etc/dpkg 拼接")
ok("有 DOUBAO_DPKG_PREFIX 覆盖口子") if "DOUBAO_DPKG_PREFIX" in s \
else warn("没有 DOUBAO_DPKG_PREFIX(不影响功能)")
stale = [a for a in ("amd64", "arm64") if a in lines]
if stale:
fail(f"还带着 Debian 风格架构名 {stale}")
else:
ok("没有 Debian 风格架构名(amd64/arm64)")
if WANT_ARCH_NAME in lines:
ok(f"架构名是 {WANT_ARCH_NAME}")
else:
fail(f"找不到架构名 {WANT_ARCH_NAME}")
# ---------------------------------------------------------------- 6
print("\n[6] 源码里架构名校验放开了下划线")
src = os.path.join(BUILD, "lib/dpkg/arch.c")
pm = os.path.join(BUILD, "scripts/Dpkg/Arch.pm")
if os.path.isfile(src):
t = open(src).read()
# 用正则而不是字面量:源码里这段既有单引号又有下划线,字面量很容易写错
has_underscore_in_loop = re.search(r"c_isalnum\(\*p\).*?'-'", t) and "_" in t
has_underscore_in_msg = re.search(r'"\s*-_\s*"\s*\)', t) is not None
if has_underscore_in_loop and has_underscore_in_msg:
ok("lib/dpkg/arch.c 允许下划线")
else:
fail(f"lib/dpkg/arch.c 没放开下划线"
f"(循环={bool(has_underscore_in_loop)} 文案={has_underscore_in_msg})")
else:
warn(f"找不到 {src}(跳过后两项源码检查)")
if os.path.isfile(pm):
t = open(pm).read()
if "[a-zA-Z0-9_-]*" in t:
ok("scripts/Dpkg/Arch.pm 允许下划线")
else:
fail("scripts/Dpkg/Arch.pm 没放开下划线")
# ---------------------------------------------------------------- 7/8
print("\n[7-8] RUNPATH 与动态依赖")
if READELF:
for p in ("dpkg", "dpkg-deb", "dpkg-query", "dpkg-divert", "dpkg-split", "dpkg-trigger"):
f = os.path.join(BIN, p)
if not os.path.isfile(f):
continue
d = run(READELF, "-d", f)
if f"{PREFIX}/lib" not in d:
fail(f"{p} 的 RUNPATH 没指向前缀 lib")
needed = re.findall(r"Shared library: \[([^\]]+)\]", d)
third = [n for n in needed if n.startswith("libmd")]
if third:
fail(f"{p} 还依赖 {third}(应该静态链进去)")
if not any("RUNPATH" in m for m in fails):
ok(f"6 个程序的 RUNPATH 都指向 {PREFIX}/lib")
ok("都没有外部第三方库依赖(libmd/z/bz2/lzma/zstd 已静态链入)")
print()
if fails:
print(f"❌ {len(fails)} 项不合格:")
for m in fails:
print(" -", m)
sys.exit(1)
print(f"✅ {ARCH} 全部通过" + (f"({len(warns)} 条提示)" if warns else ""))

View File

@@ -0,0 +1,534 @@
# 内置 Termux 的适配 —— 现状与全部踩过的坑
> 这份文档的作用:**让这件事不依赖任何人的记忆**。
> 换一个会话、换一个人接手,从这一页就能继续。
最后更新:v2.0.33
---
## 一句话背景
App 里内置了 Termux(把它的 bootstrap 解压到应用私有目录,用它的
`libtermux.so` 开 pty)。**但 Termux 的所有二进制都是按它自己的包名
`com.termux` 编译的**,而我们的包名是 `com.doubao.lynxclone` ——
里面写死了一整套绝对路径 `/data/data/com.termux/files/usr/...`。
**已经修掉的 20 处问题,全都是这一个病根的不同表现。**
改法归纳起来只有五类:
| 类型 | 例子 | 管什么 |
|---|---|---|
| **环境变量** | `SSL_CERT_FILE`、`DPKG_ADMINDIR`、`APT_CONFIG` | 会读环境变量的程序 |
| **配置文件** | 生成 `apt.conf` 重设全部 `Dir::` | apt 自己的目录 |
| **路径补全** | `PATH` 里加 `/data/data/<包名>/files/usr/bin` | 找不到命令 |
| **wrapper** | (v2.0.33 起**已废弃**,见下) | —— |
| **沙箱路径** ★ | 在自己 prefix 里把 `/data/data/com.termux/...` 逐目录接出来 | **编译进二进制、谁也拦不住的那些** |
| **自编 dpkg** ★★ | 把 dpkg/apt 换成自己编的,从根上解决 | **dpkg 的编译期配置目录** |
---
## ★★ v2.0.33:自编 dpkg,和真 Termux 共存
**这一版解决了之前"从根上无解"的那个冲突。**
### 之前是什么样
装了真 Termux 的手机上,`pkg install` 必死:
```
dpkg: error: error opening configuration directory
'/data/data/com.termux/files/usr/etc/dpkg/dpkg.cfg.d': Permission denied
E: Sub-process .../bin/dpkg returned an error code (2)
```
原因是 dpkg 的**配置目录是编译期常量**,而且它**在解析命令行之前**就去读。
`--admindir` 指得再对也没用。真 Termux 的 `/data/data/com.termux` 是 `0700`、
属于另一个 UID,我们连穿都穿不进去 —— `ENOENT` dpkg 会静默跳过,`EACCES` 直接死。
试过并**全部失败**的路子(细节见 `android/termux-dpkg/README.md`):
`--root` / `DPKG_ROOT` / `LD_PRELOAD=libtermux-exec.so` / prefix 内软链 /
在 `/data/data` 下建软链 / `unshare -m` / 直接改二进制(长度不等)。
### 现在怎么做
用 NDK 自己编一份 dpkg,把那一处换成**从 `/proc/self/exe` 反推前缀**,
于是同一个二进制在任何包名下都指向自己所在的前缀。顺带修了三件事:
- **架构名**改用 Termux 的写法(`x86_64` / `aarch64`)。用 Debian 的
`amd64`/`arm64` 会让 dpkg 把数据库里**每一个包**都判成非法架构。
- **PATH**:apt 派生 dpkg 时会塞给它一个指向真 Termux 的 PATH,
自编版按自己的前缀修回来。
- **维护脚本的 shebang 和正文路径**:Termux 包里整篇是
`#!/data/data/com.termux/files/usr/bin/sh` +
`mkdir -p "/data/data/com.termux/files/usr/var/empty"`,
前者被内核解析(落在别的 App 私有目录 → EACCES,
而 dpkg 显示成"脚本没有执行权限",**指错方向**),
后者是根下绝对路径、沙箱软链拦不住。自编版在 exec 前全部换掉。
**构建配方 + 校验脚本在 [`android/termux-dpkg/`](../android/termux-dpkg/README.md)。**
### 实测(Android 14 x86_64,**真 Termux 同时装着**)
```
$ pkg install -y openssh
...
Setting up openssh (10.6p1-2) ...
Generating public/private rsa key pair.
Generating public/private ecdsa key pair.
Generating public/private ed25519 key pair.
$ dpkg -l | grep -c '^i[^i]' → 0(无未配置项)
$ ssh -V → OpenSSH_10.6p1
```
还验过 `nmap`、`git 2.56.0` 全新安装,全部 `未配置 = 0`。
### 因此删掉的东西
`bin/dpkg` 不再是 wrapper 脚本,`bin/dpkg.real` 也不需要了 ——
wrapper 本来就是在绕"配置目录编译死"这个已经修掉的问题。
自编 dpkg 是从 `lib/<abi>/libdoubao-dpkg.so`(其实是个 tar 包)解出来的。
---
## 当前状态(v2.0.33)
| 功能 | 状态 |
|---|---|
| 真终端(pty + ANSI) | ✅ 可用 |
| 换源(清华/中科大/阿里/北外/官方) | ✅ 可用 |
| `pkg update` / `pkg upgrade` | ✅ 可用 |
| **`pkg install python` 端到端** | ✅ **可用**(模拟器上实测) |
| **和真 Termux 共存** | ✅ **可用**(v2.0.33 起,自编 dpkg) |
| python / pip / clang / glib / llvm | ✅ 全部 `Setting up` 成功,`dpkg -l` 无未配置项 |
| `pip install <包>` | ✅ 可用(实测装了 six) |
| 「重置环境」按钮 | ✅ 可用 |
实测记录(Android 14 x86_64 模拟器,全新重置后):
```
$ apt-get install -y python
Setting up python (3.14.6-1) ...
Setting up python-pip (26.2.1) ...
Writing to /data/user/0/com.doubao.lynxclone/files/usr/etc/pip.conf
Setting up libllvm (21.1.8-3) ...
Setting up glib (2.90.1) ...
Setting up clang (21.1.8-3) ...
$ python -V → Python 3.14.6
$ pip --version → pip 26.2.1 from .../lib/python3.14/site-packages/pip
$ pip install six → six 1.17.0 OK
$ dpkg -l | grep -v ^ii → (空,全部配置完成)
```
### 已知的残留噪音
`bin/bash` 和 `bin/dash` 里还有少量编译死的 `com.termux` 路径
(`bin/bash` 13 处)。原因是 `rewritePrefixes` 用"前 8192 字节里有 NUL
就跳过"来避开二进制 —— 这对"长度不等"的替换是对的(改了会崩),
但它让这些常量留了下来。表现是 **每开一个终端会打印一次**:
```
bash: /data/data/com.termux/files/usr/etc/bash.bashrc: Permission denied
```
**不影响功能**(终端照常可用、`pkg install` 照常跑),只是难看。
它读的是真 Termux 的 `bash.bashrc`,读不到就跳过。
> 为什么不在 `/data/data` 下建个 `com.termux` 软链一劳永逸:
> `/data/data` 是 `drwxrwx--x system system`,应用建不了东西(实测 EACCES)。
---
## 20 处问题清单(按发现顺序)
| # | 现象 | 根因 | 修法 |
|---|---|---|---|
| 1 | 终端一闪就退,退出码 0 | `libtermux.so` 里 **`args[0]` 就是 `argv[0]`**,我传的第一个元素是 `--rcfile`,bash 把 rc 当脚本跑了一遍 | `args[0]` 传 shell 路径本身 |
| 2 | pty 通了、bash 活着,但屏幕不刷新 | `TerminalSessionClient.onTextChanged` 是**空实现** | 接到 `TerminalView.onScreenUpdated()` |
| 3 | 命令敲得进去、回车没反应 | ENTER 发 `\n`(LF),终端要 `\r`(CR);且键位被滚出屏幕 | 改 CR + 移到第一位 |
| 4 | `pkg update` 把几十个镜像全测成 bad | **pkg 不看 `sources.list`**,它认 `etc/termux/chosen_mirrors` | 建符号链接指到 `mirrors/chinese_mainland/<主机名>` |
| 5 | 所有 HTTPS 全挂 | `curl`/`apt` 里编译死了证书路径 `/data/data/com.termux/.../cert.pem` | `SSL_CERT_FILE`/`CURL_CA_BUNDLE` + `Acquire::https::CaInfo` |
| 6 | `Unable to determine a suitable packaging system type` | apt 读不到 `apt.conf.d`(编译死) | 生成 `apt.conf` + `APT_CONFIG` |
| 7 | `method driver .../methods/https could not be found`<br>`Couldn't create temporary file .../usr/tmp/...` | `Dir::Bin::*`、`Dir::Temp` 也是编译死的 | 逐个写进 apt.conf |
| 8 | `NO_PUBKEY 5A897D96E57CF20C` | `trusted.gpg.d/` 里全是**断掉的符号链接**(指向老包名) | `fixBrokenSymlinks()` 扫出来重建 |
| 9 | `cannot create the dpkg database directory /data/data/com.termux/...` | dpkg 的 admindir 编译死 | `DPKG_ADMINDIR` |
| 10 | `6 expected programs not found in PATH` | **apt 派生 dpkg 时清洗了环境**,PATH 没传进去。(直接跑 dpkg 一切正常 —— 这是关键线索) | **给 dpkg 套 wrapper**:补全环境再 exec 真身 |
| 11 | `error creating directory './data/data/com.termux'` | dpkg 的 **instdir** 编译死 | `--instdir` |
| 12 | `failed to chroot to ...: Operation not permitted` | Android 应用没有 `CAP_SYS_CHROOT` | `--force-script-chrootless` |
| 13 | `unable to execute .../openssh.postinst: No such file or directory` | 安装脚本的 shebang 指向老包名;`var/lib/dpkg/info/` 不在改写列表里 | 加进改写目录 |
| 14 | **`error opening configuration directory '/data/data/com.termux/.../dpkg.cfg.d': Permission denied`** | **用户手机上装了真 Termux** —— 那个私有目录**存在但读不了**(所以是 Permission denied 不是 No such file)。我的模拟器上没装真 Termux,所以复现不出来 | 见第 15 条 —— `--root` 只是掩盖,**不是修法** |
| 15 | 和 14 同一条报错,但**根因终于挖到底了** | dpkg 读配置的路径是 `<chroot 根>/<编译死的 DPKG_CONFDIR>`,**跟 admindir 无关**。`--root=$PREFIX` 只是把它平移到 `$PREFIX/data/data/com.termux/...`,那里没人建目录 → 照样报错 | ★★ **在沙箱里把那条路造出来**:`$PREFIX/data/data/com.termux → ../../usr`(软链)。见下 |
### 第 15 条:那个"想要但没做到"的正解 —— 以及它为什么做不到
想的是最直接的办法:**把 ELF 里写死的字节改掉**。既然
`/data/data/com.termux` 到处都是,换成我们的包名不就行了?
**写了 `scripts/verify-elf-patch.py`,拿真机上拉下来的二进制验,结论是:**
| 检查 | 结果 |
|---|---|
| 31 处匹配是不是干净的完整 C 字符串<br>(前面是 `\0`/引号,后面紧跟 `/`) | ✅ **31/31 全是**,可以无条件安全替换 |
| 长度能不能原地替换 | ❌ **不行** |
```
/data/data/com.termux = 21 字节
/data/data/com.doubao.lynxclone = 30 字节 ← 差 9
```
原地替换**不能改长度**(后面所有数据的偏移会全错),而 `.rodata` 里的
字符串是**紧挨着**的,没有 9 字节空隙。
> (我第一版把这个包名数成了 21 —— 少了 9 个字。
> 是那个验证脚本在编译前把它抓出来的。**先验证再写实现**省了一轮。)
**换正解:不碰二进制,靠沙箱路径。** 见第 17 条(那一条把 15/16 两轮的
绕路都收了口)。
### ★★★ 第 16 条:补刀脚本拿 sed 改二进制,一次写坏 85 个
给 dpkg 套的 wrapper 里,装完包会跑一个补刀脚本
(`res/raw/doubao_patch.sh`),把新装包里的硬编码路径改掉。
第一版写的是:
```sh
grep -rla "$OLD" "$P/bin" "$P/lib" "$P/libexec" | while read f; do
sed -i "s|$OLD|$NEW|g" "$f" # ← 灾难
done
```
`-a` 把**二进制**也当文本处理了,于是 85 个 ELF 被 `sed` 重写。
`dpkg.real` 直接变成:
```
CANNOT LINK EXECUTABLE .../dpkg.real: empty/missing DT_HASH/DT_GNU_HASH
in ".../dpkg.real" (new hash type from the future?)
```
**为什么必然坏:`20 → 30`,长度不等**(就是上面第 15 条那个结论)。
`sed` 改了文件长度,ELF 里所有内部偏移全废。
**我转头就在补刀脚本里犯了同一个错** —— 明明刚用脚本验证过
"长度不等所以不能改二进制"。教训:**结论要落到每一处代码,
不能只落在当时正在改的那一处。**
修法:过滤用"**含 NUL 就跳过**",并且**绝不改自己**(否则第一刀就把过滤条件
改掉了,第二刀起又退化成"见到二进制就 sed")。现在这段逻辑在 python 里
(一行 `b"\0" in data[:8192]`),比 shell 两道手工拦更不容易漏。
> 那个"文本/二进制"的判断是本仓库最容易改错的地方。
> `scripts/verify-patch-script.py` 专门盯着它。
### ★★★ 第 17 条:正解是"沙箱路径",而且**绝不能给 dpkg 传 `--root`**
这一条是收口,也是我绕得最久的一条。三个关键结论:
#### ① `--root` 会让包装到**影子目录**里
`--root=$PREFIX` 看着能解决"编译死的绝对路径",但它会把**每一个**路径
前面拼上 root —— **包括 `.deb` 文件清单里的安装路径**。于是:
```
清单里写的是 /data/data/com.termux/files/usr/bin/hello
加了 --root <prefix>/data/data/com.termux/files/usr/bin/hello ← 影子目录
应该是 <prefix>/bin/hello
```
**而且 apt 照样报 `Setting up hello ... 成功`** —— 静悄悄地装错地方。
(这个只有把 hello 真装一遍、再去 `find` 它才看得出来。)
正确参数是:
```
dpkg.real --instdir=/ --force-script-chrootless "$@"
```
`--instdir=/` 让 dpkg 按清单里的**原路径**安装,于是它要写的就是那个
`/data/data/com.termux/...`。剩下的事由 ② 解决。
#### ② 在 prefix 里把那条路**逐目录**接出来
```
<prefix>/data/data/com.termux/files/usr/bin → <prefix>/bin
<prefix>/data/data/com.termux/files/usr/etc → <prefix>/etc
<prefix>/data/data/com.termux/etc/dpkg → <prefix>/etc/dpkg
<prefix>/data/data/com.termux/var/lib/dpkg → <prefix>/var/lib/dpkg
……(共 20 条,见 linkLegacyPrefix())
```
为什么必须逐目录:路径有两种形状 ——
`…/com.termux/files/usr/<X>`(来自 .deb 清单)和
`…/com.termux/<Y>`(来自二进制里编译死的常量)。
**没法用"把 `com.termux` 整个链到某处"一次解决**:
* 链到 `<prefix>` → 形状 A 变成 `<prefix>/files/usr/…`(多一层)
* 链到 `<prefix>/..` → 形状 A 对,形状 B 变成 `<prefix>/..`(少一层)
我在这上面来回错了**三次**,每次都"看起来很有道理"。
#### ③ 维护脚本的 shebang 要指向 **Termux 自己的 bash**
Termux 的 `xxx.postinst` 写的是 `#!/bin/sh`,但正文里全是 bash 语法
(`[[ ]]`、`(( ))`)。在我们这儿 `#!/bin/sh` 落到 **Android 的玩具箱 sh**
(纯 POSIX),于是:
```
python.postinst[3]: syntax error: expression expected '(('
dpkg: error processing package python (--configure):
installed python package post-installation script subprocess returned error exit status 1
```
—— 而且**文件其实已经装好了**(`python -V` 都能跑)。表现是
`dpkg -l` 显示 `iF`/`iU`、pip 装不上、依赖它的 glib/clang 全跟着起不来。
**★ 但只对维护脚本这么做。** 对 `bin/` 下的东西一律只做**路径替换** ——
因为 `bin/pip` 是个 **Python 脚本**,改成 bash 就毁了:
```
bin/pip: line 2: import: command not found
```
规则一句话:**维护脚本要 bash,其他脚本只换路径、别动解释器。**
### ★★★ 第 18 条:补刀必须跑**两次**(unpack 后 + 全部结束后)
`python-pip.postinst` 第 3 行会**执行刚装进来的 `bin/pip`**。
而 pip 的 shebang 原本是
```
#!/data/data/com.termux/files/usr/bin/python3.14 ← 绝对路径,不存在
```
报错是:
```
python-pip.postinst: line 3: .../bin/pip: cannot execute: required file not found
```
**★ 这句 `required file not found` 指的**不是 pip 本身**,而是它 shebang 里
那个解释器** —— 报错完全没提这件事,极容易查错方向(会以为 pip 没装上)。
而 `.deb` 里的文件是在 **unpack** 阶段落盘的,configure 在**之后**。
所以补刀要在 unpack 之后立刻跑一次:
```sh
case " $* " in *" --unpack "*|*" --install "*|*" -i "*) PATCH_UNPACK=1 ;; esac
"$P/bin/dpkg.real" --instdir=/ --force-script-chrootless "$@"
[ "$PATCH_UNPACK" = 1 ] && sh "$P/bin/doubao-patch" shebang
sh "$P/bin/doubao-patch" # 收尾再补一次(含正文路径)
```
### ★★★ 第 19 条:`LD_LIBRARY_PATH` 少了会让补刀**静默失效**
Termux 的二进制靠 `libandroid-support.so` 之类活,而动态链接只认
`LD_LIBRARY_PATH`(没编 RPATH)。少了它连 `bin/python3` 都起不来:
```
CANNOT LINK EXECUTABLE ".../bin/python3": library "libandroid-support.so"
not found: needed by main executable
```
**可怕的是它静默**:补刀脚本第一件事是 `[ -x "$PY" ]`,python 起不来
→ 整个补刀什么都不做、**也不报错**。表现是"shebang 没修好"而日志里
一个字都没有,查了好几轮。修法:wrapper **和**补刀脚本**各自** export 一次。
### ★★★ 第 20 条:`NEW` 常量取错,表现却像"工具坏了"
补刀脚本要用文本替换把写死的路径改掉:`OLD → NEW`。
我为一个常量的取值错了**两轮**,而两次的症状都**完全像工具 bug**
(稳定多出一段路径、与输入无关):
```
输入 #!/data/data/com.termux/files/usr/bin/python3.14
错误 #!/data/user/0/<包名>/files/files/usr/bin/python3.14 ← 多一个 /files
```
于是我依次怀疑并**换掉了三个工具**:`bytes.replace` → 玩具箱的
`${var//a/b}` → `sed -i`。**三个全是清白的。**
拆穿它的是一个和本项目毫无关系的中性实验:
```python
>>> b"/data/data/com.termux/files/usr".replace(
... b"/data/data/com.termux", b"/data/user/0/pkg/files")
b'/data/user/0/pkg/files/files/usr'
```
**数学上完全正确** —— 两个 `files` 是两个常量各自带来的,一个来自
`NEW` 的尾巴、一个来自原文的 `/files/usr`。
最终确定的取值(**两处 OLD 不一样,这是最容易绕晕的一点**):
| 用在哪 | OLD | NEW | 换出来 |
|---|---|---|---|
| 补刀脚本(改 shebang) | `/data/data/com.termux/files/usr` | `<prefix>` | `#!<prefix>/bin/python3.14` ✅ |
| `rewritePrefixes`(改正文) | `/data/data/com.termux` | `<pkg>/files` | `<pkg>/files/files/usr/…`,由沙箱里 `"files" to ".."` 那条链接住 ✅ |
> **教训:「工具坏了」的时候,先怀疑自己的常量。**
> 常量错的表现(稳定复现、与输入无关)恰恰是工具 bug 的特征 ——
> 这就是它骗过我的原因。
> `scripts/verify-patch-script.py` 现在把这两个取值都钉住了。
---
## 改过的地方(代码位置)
| 文件 | 改了什么 |
|---|---|
| `termux/TermuxInstaller.kt` | 主战场:路径改写、apt.conf、dpkg wrapper、断链修复、沙箱路径、重置、环境变量 |
| `res/raw/doubao_patch.sh` | dpkg 装完包后的补刀脚本(**模板**,App 启动时替换占位符后写进 prefix) |
| `res/raw/dpkg_wrapper.sh` | dpkg wrapper 的**模板**(理由见下) |
| `termux/TermuxMirror.kt` | 换源(同时写 `sources.list` 和 `chosen_mirrors`) |
| `termux/TermuxTerminal.kt` | 起 shell 的候选列表、秒退回退、view 引用(刷屏) |
| `ui/TerminalScreen.kt` | 终端界面、源按钮、重置按钮、ENTER 键位 |
| `ui/MirrorScreen.kt` | 换源界面 |
| `termux/terminal/TerminalSession.java` | 给被静默吞掉的异常加日志(**关键**,见下) |
### 为什么两个脚本放在 `res/raw/` 而不是写成 Kotlin 字符串
**Kotlin 的原始字符串(`"""`)也照样做 `$` 插值。**
shell 脚本里 `$P` `$OLD` `$f` 到处都是,写在 Kotlin 里就编译报
`Unresolved reference: P` —— **而这个报错看着像"脚本写错了",
其实是语言层的事**,白找半天。写成 `${'$'}P` 能过,但正文没法读了
(几十处),而且下一个改脚本的人一定会再踩一遍。
> 这个坑我连着踩了两次(同一轮里),所以单独立一节。
>
> ★ 还有一个**同族**的坑,更阴:Kotlin 的块注释**可以嵌套**,
> 注释正文里写一个"斜杠星号"就会开一层新的嵌套,于是原本用来收尾的
> "星号斜杠"只关掉嵌套层,**外层一直开着,把后面所有代码全吞掉**。
> 表现是一堆莫名其妙的 `Unresolved reference`(报在后面的函数上)。
> 我在 `ensureCaBundle` 的注释里写了 `cat /system/.../*` 就中了这一枪。
> 查法:`scripts/.tmp-brace.py` 那类"数块注释配对"的小脚本。
放进 `res/raw/` 之后:正文**原样**,注入点显式(`@PREFIX@`),
不用碰任何构建脚本(`.sh` 是原样打包的,不像 `.java`/`.kt` 会被排除)。
> 这个坑我连着踩了两次(同一轮里),所以单独立一节。
### 一个方法论教训
`TerminalSession` 里原来有:
```java
} catch (Exception e) {
// Ignore, just shutting down. ← 就是这一行
}
```
**它把 `read failed: EIO` 吞了**,导致"pty 双向不通"这个现象查了好几轮
才浮出水面。**静默的 catch 是排查杀手。**
---
## 排查用的工具
* `scripts/dis-termux.py` —— ELF 解析 + capstone 反汇编
(第一次靠它看到 `.so` 里用 `TIOCGPTPEER`、`execvp(cmd, argv)`)
* **`scripts/verify-elf-patch.py` ★** —— 验证"能不能原地改二进制里的
硬编码路径"。拿**真机上拉下来的二进制**跑,逐字节检查:
匹配是不是完整 C 字符串、前后边界对不对、**长度够不够**。
→ 就是它推翻了"改字节"那条路(差 9 字节),省了一轮白编译。
```bash
# 先拉几个真二进制下来
adb shell run-as com.doubao.lynxclone sh -c 'base64 files/usr/bin/curl' > curl.b64
python scripts/verify-elf-patch.py
```
* `files/termux-install.log` —— App 落盘的安装/会话日志
(真机上 OEM 会吞 Logcat,只能落盘)
* `files/usr/var/log/doubao-patch.log` —— 装完包补刀的记录
(看它就知道 `pkg install` 之后有没有把新包的脚本改过来)
* **`scripts/verify-patch-script.py` ★** —— 盯住补刀脚本的几条硬性质:
文本/二进制过滤、两个 `OLD` 的取值、`--root` 必须**不**在、
维护脚本的 shebang、占位符两边对得上。**这条脚本是用真实事故换来的**
(`-a`/`-I` 一个字母 → 85 个二进制报废)。
* **`scripts/verify-sandbox-paths.py` ★** —— 把 `linkLegacyPrefix()` 里那张
接通表**解析出来**,逐条检查形状,并对照"二进制里实际写死、且会被读的
路径"清单(`etc/dpkg`、`etc/apt/apt.conf.d`、`etc/tls`、`share/`……)。
加一条路径忘了改这里,它会报出来。
* **直接读源码**:`termux.c` 在 GitHub 上,网络通的时候一眼就看到
`argv[i] = strdup(args[i])` —— 比反汇编快得多
### 方法论:先验证,再实现
两个例子,一个省了一轮、一个白饶了三轮:
* **省的**:第 15 条那条路(改字节)**在写实现之前先用真数据验证了一遍**,
才发现"长度差 9 字节"这个致命前提是错的。直接写完再发版的话,
用户装上去还是同样的报错,而我会以为"改了怎么还不行"。
* **饶的**:第 20 条那个 `NEW` 常量。我在**没有先做一个中性实验**的情况下,
就断定"工具坏了",连换三个实现。**一行 `bytes.replace` 的中性测试
就能省掉那三轮。**
一句话:**先做一个和本项目无关的最小实验**,再决定要不要怀疑工具。
**凡是"我以为我能……"的假设,先写个脚本用真实数据验一遍。**
这个脚本后来还留在仓库里(`verify-elf-patch.py`),下次有人想重走这条路,
跑一下就知道为什么不行。
### 方法论:遇到"某个库行为诡异"
**先读它的源码或反汇编它,别在现象层面试。**
我在 bash / 环境变量 / `LD_PRELOAD` / pty 尺寸 / SELinux 上绕了四轮,
全是死路;真相就在 `termux.c` 的一行里。
---
## "被冤枉"的机制
排查过程中这几样都背过锅,最后都证明**是清白的**:
* **`LD_PRELOAD=libtermux-exec.so`** —— 替第 1 条背了锅。它改写的是它认识的
那些路径,apt 的 `Dir::` / dpkg 的 `sysconfdir` 都不在里面(实测带不带一样)。
(但它对**运行时装好的包**是有用的,环境变量里保留着。)
* **`SSL_CERT_FILE` / `CURL_CA_BUNDLE`** —— 只管 **curl**;
apt 走自己的 GnuTLS method,得用 `Acquire::https::CaInfo`。
* **`bytes.replace` / 玩具箱的 `${var//a/b}` / `sed -i`** —— 第 20 条里
我因为一个常量取错,把这三个全换了一遍。它们**一点问题都没有**。
---
## 开发流程上踩的坑
**`node scripts/build-apk.mjs --skip-build` 只拷贝已有 APK,不编译。**
我用它跑了好几轮,Kotlin 改动根本没进包 —— 白费了三轮。
(用户一句"你没编译吧"点破。)
**以后:改完 Kotlin 一律
`node scripts/build-apk.mjs`(不带 `--skip-build`)**,
并用 `aapt2 dump badging` 确认 `versionCode`、用文件时间确认是新的。
**改 Kotlin 用 `edit` 工具一次一处,改完立刻编译。**
不要写 PowerShell/Python 按行号剪贴的脚本 —— 这个坑在 `AGENTS.md`
里早写了,我还是踩了三次(`key()` 包错、误删 `tryNextCandidate`、
死循环把 `meeting.py` 写炸)。
---
## 下一步(如果有人接着做)
1. **在装了真 Termux 的手机上再验一遍**。模拟器(Android 14 x86_64)上
`pkg install python` 已经端到端跑通,但**模拟器没装真 Termux**,
`/data/data/com.termux` 那个目录的"存在但读不了"情形复现不出来
(那正是第 14 条报 `Permission denied` 的原因)。
按现在的设计(一个字节都不碰真 Termux 的目录)应该不受影响,
但**没验过就是没验过**。
2. 已知小尾巴:dpkg 给 maintainer script 一个固定的 `PATH`,
脚本里调 `ssh-keygen` 这类命令会 `not found`。
可以在 wrapper 里处理,或用 `DPKG_MAINTSCRIPT_*` 系列变量。
3. **加新东西的时候,先跑这三个脚本**:
```bash
python scripts/verify-patch-script.py # 补刀脚本那几条硬性质
python scripts/verify-sandbox-paths.py # 沙箱接通表
python scripts/verify-elf-patch.py # 还想改二进制?先看它
```
4. 如果还有报错:**先看 `files/usr/var/log/doubao-patch.log` 和
`files/termux-install.log`**,再看那条报错里的路径属于哪个二进制,
然后在五类改法里挑一类。
★ 报错里的路径**是不是 `/data/data/com.termux/...`** 是第一条判据 ——
是的话就是这套病根;不是的话是别的问题,别往这边查。

115
scripts/build-deps.sh Normal file
View File

@@ -0,0 +1,115 @@
#!/bin/bash
# 用 NDK 为 Android 交叉编译 dpkg 需要的静态库
# 用法: build-deps.sh <arch> arch = x86_64 | arm64
set -eu
ARCH="${1:?用法: build-deps.sh x86_64|arm64}"
NDK=/root/tb/android-ndk-r27c
SRC=/root/tb/dl
OUT=/root/tb/out/$ARCH
API=24
case "$ARCH" in
x86_64) TRIPLE=x86_64-linux-android ;;
arm64) TRIPLE=aarch64-linux-android ;;
*) echo "未知 arch: $ARCH"; exit 1 ;;
esac
TC=$NDK/toolchains/llvm/prebuilt/linux-x86_64
export CC=$TC/bin/${TRIPLE}${API}-clang
export CXX=$TC/bin/${TRIPLE}${API}-clang++
export AR=$TC/bin/llvm-ar
export RANLIB=$TC/bin/llvm-ranlib
export STRIP=$TC/bin/llvm-strip
export CFLAGS="-O2 -fPIC -D__ANDROID_API__=$API"
export LDFLAGS=""
[ -x "$CC" ] || { echo "!! 找不到编译器 $CC"; exit 1; }
echo "### arch=$ARCH CC=$CC"
"$CC" --version | head -1
mkdir -p "$OUT/lib" "$OUT/include" /root/tb/work
cd /root/tb/work
########################################
# libmd 1.3.0
########################################
if [ ! -f "$OUT/lib/libmd.a" ]; then
echo "=== libmd ==="
rm -rf libmd-1.3.0 && tar xf "$SRC/libmd.tar.xz"
cd libmd-1.3.0
./configure --host="$TRIPLE" --prefix="$OUT" \
--disable-shared --enable-static >/dev/null 2>&1
make -j"$(nproc)" >/dev/null 2>&1
make install >/dev/null 2>&1
"$STRIP" --strip-unneeded "$OUT/lib/libmd.a" 2>/dev/null || true
cd ..
fi
ls -la "$OUT/lib/libmd.a" 2>/dev/null || echo "!! libmd 失败"
########################################
# zlib
########################################
if [ ! -f "$OUT/lib/libz.a" ]; then
echo "=== zlib ==="
rm -rf zlib-1.3.2 && tar xf "$SRC/zlib.tar.gz"
cd zlib-1.3.2
CHOST="$TRIPLE" ./configure --static --prefix="$OUT" >/dev/null 2>&1
make -j"$(nproc)" libz.a >/dev/null 2>&1
cp libz.a "$OUT/lib/" && cp zlib.h zconf.h "$OUT/include/"
cd ..
fi
ls -la "$OUT/lib/libz.a" 2>/dev/null || echo "!! zlib 失败"
########################################
# bzip2 1.0.8
########################################
if [ ! -f "$OUT/lib/libbz2.a" ]; then
echo "=== bzip2 ==="
rm -rf bzip2-1.0.8 && tar xf "$SRC/bzip2.tar.gz"
cd bzip2-1.0.8
make -j"$(nproc)" libbz2.a CC="$CC" AR="$AR" RANLIB="$RANLIB" \
CFLAGS="$CFLAGS -D_FILE_OFFSET_BITS=64" >/dev/null 2>&1
cp libbz2.a "$OUT/lib/" && cp bzlib.h "$OUT/include/"
cd ..
fi
ls -la "$OUT/lib/libbz2.a" 2>/dev/null || echo "!! bzip2 失败"
########################################
# liblzma (xz)
########################################
if [ ! -f "$OUT/lib/liblzma.a" ]; then
echo "=== liblzma ==="
rm -rf xz-5.8.4 && tar xf "$SRC/xz.tar.xz"
cd xz-5.8.4
# SKIP_WERROR_CHECK: xz 的 configure 会用 -Werror 试编译,
# 而 -D__ANDROID_API__=24 会触发它的告警,导致它误判 CFLAGS 有问题
./configure --host="$TRIPLE" --prefix="$OUT" \
--disable-shared --enable-static \
--disable-xz --disable-xzdec --disable-lzmadec --disable-lzmainfo \
--disable-scripts --disable-doc --disable-nls \
SKIP_WERROR_CHECK=yes \
>/dev/null 2>&1
make -j"$(nproc)" >/dev/null 2>&1
make install >/dev/null 2>&1
cd ..
fi
ls -la "$OUT/lib/liblzma.a" 2>/dev/null || echo "!! liblzma 失败"
########################################
# libzstd
########################################
if [ ! -f "$OUT/lib/libzstd.a" ]; then
echo "=== libzstd ==="
rm -rf zstd-1.5.7 && tar xf "$SRC/zstd.tar.gz"
cd zstd-1.5.7/lib
make -j"$(nproc)" libzstd.a CC="$CC" AR="$AR" RANLIB="$RANLIB" CFLAGS="$CFLAGS" >/dev/null 2>&1
cp libzstd.a "$OUT/lib/"
cp zstd.h zstd_errors.h zdict.h "$OUT/include/" 2>/dev/null || true
cd ../..
fi
ls -la "$OUT/lib/libzstd.a" 2>/dev/null || echo "!! libzstd 失败"
echo
echo "=== $ARCH 产物清单 ==="
ls -la "$OUT/lib/" "$OUT/include/" 2>/dev/null

142
scripts/build-dpkg.sh Normal file
View File

@@ -0,0 +1,142 @@
#!/bin/bash
# 为 Android 交叉编译 dpkg
# 用法: build-dpkg.sh <arch> arch = x86_64 | arm64
set -eu
ARCH="${1:?用法: build-dpkg.sh x86_64|arm64}"
NDK=/root/tb/android-ndk-r27c
SRC=/root/tb/src/dpkg
DEPS=/root/tb/out/$ARCH
OUT=/root/tb/out/$ARCH
API=24
case "$ARCH" in
x86_64) TRIPLE=x86_64-linux-android ; APKARCH=x86_64 ;;
arm64) TRIPLE=aarch64-linux-android ; APKARCH=arm64-v8a ;;
*) echo "未知 arch: $ARCH"; exit 1 ;;
esac
TC=$NDK/toolchains/llvm/prebuilt/linux-x86_64
export CC=$TC/bin/${TRIPLE}${API}-clang
export CXX=$TC/bin/${TRIPLE}${API}-clang++
export AR=$TC/bin/llvm-ar
export RANLIB=$TC/bin/llvm-ranlib
export STRIP=$TC/bin/llvm-strip
# -D__ANDROID_API__ 让 configure 通过;-isystem 把我们的静态库头文件放前面
export CPPFLAGS="-I$DEPS/include"
export CFLAGS="-O2 -fPIC -D__ANDROID_API__=$API"
# RUNPATH:dpkg 会 exec 出 dpkg-query / dpkg-deb 等辅助程序,那些进程不一定
# 继承到 LD_LIBRARY_PATH,所以把库搜索路径烧进 ELF 里,不依赖环境变量。
export LDFLAGS="-L$DEPS/lib -static-libgcc -Wl,-rpath,/data/data/com.doubao.lynxclone/files/usr/lib -Wl,--enable-new-dtags"
export LIBS="-lmd -lz -lbz2 -llzma -lzstd"
BUILD=/root/tb/build/dpkg-$ARCH
mkdir -p /root/tb/build "$BUILD"
cd "$BUILD"
echo "########## 1. 准备源码树 ##########"
# 注意:不能把源码复制出来就完事 —— dpkg 的 build-aux/get-version 需要
# 一个真正的 git checkout(或发行 tarball)才能定出版本号。
# 用 git worktree:共享 .git,树是干净的,且可以随时删掉重来。
cd "$SRC"
git worktree remove --force "$BUILD" 2>/dev/null || true
rm -rf "$BUILD"
git worktree add --detach --force "$BUILD" HEAD >/dev/null 2>&1 || {
echo "git worktree 失败"; exit 1; }
cd "$BUILD"
echo " worktree 就绪: $(pwd)"
echo "########## 2. 应用 Termux 补丁 ##########"
for p in /root/tb/patches/termux-*.patch; do
n=$(basename "$p")
if patch -p1 -N -l -i "$p" >/dev/null 2>&1; then
echo " ✓ $n"
else
echo " ✗ $n <<< 失败"
patch -p1 -N -l -i "$p" 2>&1 | head -20
fi
done
echo "########## 3. 应用我们自己的补丁 ##########"
for p in /root/tb/ourpatch/doubao-prefix-h.patch \
/root/tb/ourpatch/doubao-prefix-c.patch \
/root/tb/ourpatch/doubao-prefix-makefile.patch \
/root/tb/ourpatch/doubao-prefix-options.patch \
/root/tb/ourpatch/doubao-prefix-main.patch \
/root/tb/ourpatch/doubao-prefix-script.patch \
/root/tb/ourpatch/doubao-android-arch.patch \
/root/tb/ourpatch/doubao-arch-name.patch \
/root/tb/ourpatch/doubao-debarch-name.patch; do
n=$(basename "$p")
if patch -p1 -N -l -i "$p" >/dev/null 2>&1; then
echo " ✓ $n"
else
echo " ✗ $n <<< 失败"; patch -p1 -N -l -i "$p" 2>&1 | head -20; exit 1
fi
done
echo "########## 4. autogen ##########"
# dpkg 的构建脚本叫 autogen(没后缀,也没可执行位)
AUTOGEN=./autogen
if [ ! -x configure ] || [ ! -f Makefile.in ]; then
NOCONFIGURE=1 sh "$AUTOGEN" > "$BUILD/autogen.log" 2>&1 || {
echo "autogen 失败,尾部:"; tail -30 "$BUILD/autogen.log"; exit 1; }
fi
echo " configure 存在: $([ -x configure ] && echo yes || echo no)"
echo "########## 5. configure ##########"
# PERL: 宿主机是 perl 5.30,dpkg 要求 >= 5.32.1。perl 只用于构建期脚本
# (dpkg-architecture 之类),跟我们真正要的 C 程序无关,所以直接告诉它
# perl 在哪,跳过版本探测。
#
# --bindir / --libdir 指到 Termux 前缀:dpkg 会用 BINDIR 去找它的辅助程序
# (dpkg -l 实际是转给 dpkg-query 执行),用 LIBDIR 去找 libdpkg 的数据。
./configure \
--host="$TRIPLE" \
--build="$(uname -m)-pc-linux-gnu" \
--prefix=/data/data/com.doubao.lynxclone/files/usr \
--bindir=/data/data/com.doubao.lynxclone/files/usr/bin \
--libdir=/data/data/com.doubao.lynxclone/files/usr/lib \
--sysconfdir=/data/data/com.doubao.lynxclone/files/usr/etc \
--localstatedir=/data/data/com.doubao.lynxclone/files/usr/var \
--disable-shared \
--disable-dselect \
--disable-start-stop-daemon \
--disable-update-alternatives \
--disable-largefile \
--disable-nls \
--without-selinux \
--without-libselinux \
--without-systemd \
PERL=/usr/bin/perl \
ac_cv_lib_selinux_setexecfilecon=no \
dpkg_cv_c99_snprintf=yes \
DPKG_PAGER=pager \
> "$BUILD/configure.log" 2>&1 || {
echo "configure 失败,尾部:"; tail -40 "$BUILD/configure.log"; exit 1; }
echo " ✓ configure 通过"
echo "########## 6. make ##########"
make -j"$(nproc)" > "$BUILD/make.log" 2>&1 || {
echo "make 失败,错误摘要:"
grep -nE 'error:|Error [0-9]' "$BUILD/make.log" | head -30
exit 1; }
echo " ✓ make 通过"
mkdir -p "$OUT/dpkg-bin"
# libtool 会在源码目录放一个壳脚本,真正的东西在 .libs/ 里
for b in dpkg dpkg-deb dpkg-query dpkg-divert dpkg-split dpkg-trigger dpkg-realpath; do
f=""
for cand in "src/.libs/$b" "src/main/.libs/$b" "utils/.libs/$b" \
"src/$b" "src/main/$b" "utils/$b"; do
[ -f "$cand" ] && { f="$cand"; break; }
done
if [ -z "$f" ]; then echo " ? 找不到 $b"; continue; fi
cp "$f" "$OUT/dpkg-bin/$b"
"$STRIP" "$OUT/dpkg-bin/$b" 2>/dev/null || echo " ! strip 失败: $b(可能不是 ELF)"
done
echo
echo "########## 产物 ##########"
ls -la "$OUT/dpkg-bin/"
file "$OUT/dpkg-bin/dpkg" 2>/dev/null || true

View File

@@ -0,0 +1,167 @@
#!/usr/bin/env python3
"""守住 `android/app/src/main/res` 里那几个 tar 包(`libdoubao-dpkg.so`)。
为什么不直接信任构建产物:
「编译过了」在这条路上什么都不能说明 —— 出问题的地方全都是
**编译成功、装上去才炸**(配置目录权限、架构名非法、维护脚本 shebang)。
所以这里盯的是"打进 APK 的那几个字节到底长什么样"。
用法:
python scripts/verify-dpkg-jnilibs.py
"""
import os
import re
import struct
import sys
# Windows 控制台默认是 GBK,打印 ✓/✗ 会 UnicodeEncodeError
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
JNI = os.path.join(ROOT, "android", "app", "src", "main", "jniLibs")
EXPECT = {
"x86_64": {"lib": "libdoubao-dpkg.so", "machine": 62, "arch_name": b"x86_64"},
"arm64-v8a": {"lib": "libdoubao-dpkg.so", "machine": 183, "arch_name": b"aarch64"},
}
PROGRAMS = {"dpkg", "dpkg-deb", "dpkg-query", "dpkg-divert", "dpkg-split", "dpkg-trigger"}
TAR_BLOCK = 512
fails = []
warns = []
def fail(m):
fails.append(m)
print(f" ✗ {m}")
def ok(m):
print(f" ✓ {m}")
def warn(m):
warns.append(m)
print(f" ! {m}")
def read_tar(path):
"""返回 [(名字, 内容)],只认 ustar 普通文件"""
out = []
with open(path, "rb") as f:
while True:
header = f.read(TAR_BLOCK)
if len(header) < TAR_BLOCK or header == b"\0" * TAR_BLOCK:
break
name = header[0:100].split(b"\0")[0].decode("utf-8", "replace").strip()
sizef = header[124:136].split(b"\0")[0].decode("ascii", "replace").strip()
size = int(sizef, 8) if sizef else 0
typ = header[156:157]
prefix = header[345:500].split(b"\0")[0].decode("utf-8", "replace").strip()
full = f"{prefix}/{name}" if prefix else name
body = f.read(size)
pad = (-size) % TAR_BLOCK
if pad:
f.read(pad)
if typ in (b"0", b"\0") and not full.endswith("/"):
out.append((full, body))
return out
def elf_machine(blob):
"""ELF e_machine(小端)"""
if blob[:4] != b"\x7fELF":
return None
return struct.unpack_from("<H", blob, 18)[0]
def contains(hay, needle):
return hay.find(needle) >= 0
print("=== 校验 APK 里的自编 dpkg(jniLibs/libdoubao-dpkg.so)===")
for abi, spec in EXPECT.items():
path = os.path.join(JNI, abi, spec["lib"])
print(f"\n[{abi}] {os.path.relpath(path, ROOT)}")
if not os.path.isfile(path):
fail(f"文件不存在:{path}")
continue
try:
members = read_tar(path)
except Exception as e:
fail(f"读 tar 失败:{e}")
continue
names = {n for n, _ in members}
if names != PROGRAMS:
fail(f"内容不对:期望 {sorted(PROGRAMS)},实际 {sorted(names)}")
continue
ok(f"tar 里有 {len(names)} 个程序({', '.join(sorted(names))})")
dpkg = dict(members)["dpkg"]
# ELF 架构
m = elf_machine(dpkg)
if m != spec["machine"]:
fail(f"dpkg 的 e_machine={m},期望 {spec['machine']}")
else:
ok(f"ELF 架构正确(e_machine={m})")
# 运行时前缀解析 —— 没有它就等于没修
if not contains(dpkg, b"/proc/self/exe"):
fail("dpkg 里没有 /proc/self/exe(运行时前缀补丁没进去)")
else:
ok("有 /proc/self/exe(运行时前缀解析)")
# 架构名
if not contains(dpkg, spec["arch_name"]):
fail(f"dpkg 里没有架构名 {spec['arch_name'].decode()}")
else:
ok(f"架构名是 {spec['arch_name'].decode()}")
for stale in (b"amd64", b"arm64") if abi == "x86_64" else (b"amd64",):
if contains(dpkg, stale):
fail(f"dpkg 里还有 Debian 风格架构名 {stale.decode()}")
break
else:
ok("没有 Debian 风格架构名")
# 重写函数要匹配的模式必须存在,否则脚本改不了
if not contains(dpkg, b"/data/data/com.termux/files/usr"):
fail("dpkg 里没有要匹配的旧前缀(维护脚本改写会失效)")
else:
ok("有维护脚本改写用的旧前缀模式")
# 不允许出现"编译死的配置目录"这种更长的路径
if contains(dpkg, b"/data/data/com.termux/files/usr/etc/dpkg"):
fail("dpkg 里还有编译死的配置目录(装上必 EACCES)")
else:
ok("没有编译死的配置目录")
# RUNPATH
if not contains(dpkg, b"/data/data/com.doubao.lynxclone/files/usr/lib"):
fail("dpkg 里没有指向前缀 lib 的 RUNPATH")
else:
ok("RUNPATH 指向前缀 lib")
# 静态链进去了就不该再 NEEDED libmd
if contains(dpkg, b"libmd.so"):
fail("dpkg 还依赖 libmd.so(应该静态链入)")
else:
ok("没有外部 libmd 依赖")
print()
if fails:
print(f"❌ {len(fails)} 项不合格:")
for m in fails:
print(" -", m)
sys.exit(1)
print(f"✅ 全部通过" + (f"({len(warns)} 条提示)" if warns else ""))

164
scripts/verify-elf-patch.py Normal file
View File

@@ -0,0 +1,164 @@
#!/usr/bin/env python3
"""★ 验证「原地改写二进制里写死的 com.termux 路径」这条路线真的成立。
背景:内置 Termux 的二进制是按真 Termux 的包名编译的,里面写死了
`/data/data/com.termux/files/usr/...`。这些路径属于**另一个 App**,
我们访问是 EACCES。之前靠环境变量 / apt.conf / LD_PRELOAD / dpkg --root
一层层去绕,绕不完(见 docs/内置Termux-现状与坑.md)。
正解是**直接改字节**(Kotlin 侧见 termux/TermuxBinaries.kt)。
这个脚本用从设备上拉下来的**真实二进制**验证四件事:
1. 真实的 ELF 里确实有这些串,而且**出现的形式**是什么样
(是完整的 C 字符串,还是嵌在别的串里?)
2. 匹配位置前后的**上下文**(决定怎么判"这是一个完整路径")
3. 长度是不是真的能凑成一样(能否原地替换)
4. 用 .rodata 的**重定位表 / 字符串引用**确认改完之后
程序真的会用到新串(而不是某份拷贝/哈希)
用法:
python scripts/verify-elf-patch.py # 扫 scripts/.tmp-termuxbin
python scripts/verify-elf-patch.py <文件> [<文件>…]
"""
from __future__ import annotations
import os
import sys
OLD = b"/data/data/com.termux"
# 我们的包名。`/data/data/com.doubao.lynxclone` = 30 字节,比 OLD 短 0(见下)
NEW_BASE = b"/data/data/com.doubao.lynxclone"
TARGET_LEN = len(OLD)
GREEN, RED, YELLOW, DIM, RESET = "\033[32m", "\033[31m", "\033[33m", "\033[2m", "\033[0m"
pass_n = fail_n = 0
def check(ok: bool, title: str, detail: str = "") -> None:
global pass_n, fail_n
if ok:
pass_n += 1
print(f" {GREEN}✓{RESET} {title}" + (f" {DIM}{detail}{RESET}" if detail else ""))
else:
fail_n += 1
print(f" {RED}✗{RESET} {title}" + (f" {DIM}{detail}{RESET}" if detail else ""))
def contexts(data: bytes) -> list[tuple[int, str, str]]:
"""找出所有 OLD 出现的位置,返回 (偏移, 前文, 后文)。"""
out = []
i = data.find(OLD)
while i != -1:
before = data[max(0, i - 24):i]
after = data[i + TARGET_LEN:i + TARGET_LEN + 24]
out.append((i, repr(before), repr(after)))
i = data.find(OLD, i + 1)
return out
def is_complete(match_at: int, data: bytes) -> bool:
"""这个匹配是不是一个**完整的路径开头**(后面必须接 `/` 或字符串结束)。"""
end = match_at + TARGET_LEN
if end >= len(data):
return True
return data[end:end + 1] in (b"/", b"\x00")
def is_boundary(match_at: int, data: bytes) -> bool:
"""前面那个字节是不是一个合法的字符串起点。"""
if match_at == 0:
return True
return data[match_at - 1:match_at] in (
b"\x00", b" ", b"\t", b"\n", b"\r", b'"', b"'", b"=", b":", b"(", b",", b"[", b"<",
)
def scan(path: str) -> bool:
name = os.path.basename(path)
size = os.path.getsize(path)
with open(path, "rb") as fh:
data = fh.read()
is_elf = data[:4] == b"\x7fELF"
print(f"\n{'=' * 72}\n{name} {size:,} 字节 {'ELF' if is_elf else '非 ELF'}")
hits = contexts(data)
if not hits:
check(True, "没有 com.termux 路径(这个文件本来就不需要改)")
return True
print(f" {DIM}找到 {len(hits)} 处{RESET}")
complete = sum(1 for at, _, _ in hits if is_complete(at, data))
bounded = sum(1 for at, _, _ in hits if is_boundary(at, data))
both = sum(1 for at, _, _ in hits if is_complete(at, data) and is_boundary(at, data))
for at, before, after in hits[:6]:
mark = "★" if (is_complete(at, data) and is_boundary(at, data)) else " "
print(f" {mark} @0x{at:06x} …{before} [{OLD.decode()}] {after}…")
if len(hits) > 6:
print(f" {DIM}…还有 {len(hits) - 6} 处{RESET}")
check(complete == len(hits),
"全部是完整路径(后面接 / 或 \\0)",
f"{complete}/{len(hits)}" + ("" if complete == len(hits) else " ← 有嵌在长串里的,得靠上下文判断"))
check(bounded == len(hits),
"全部落在字符串起点(前面是 \\0/空白/引号/=/…)",
f"{bounded}/{len(hits)}")
check(both == len(hits),
"两个条件都满足 → 可以无条件原地替换",
f"{both}/{len(hits)}")
# ★ 长度:这是能不能原地改的硬条件
check(len(NEW_BASE) <= TARGET_LEN,
f"新路径长度 {len(NEW_BASE)} ≤ 旧 {TARGET_LEN}(差额补 {TARGET_LEN - len(NEW_BASE)} 个字符)",
f"补出来 = {NEW_BASE.decode()}{'x' * (TARGET_LEN - len(NEW_BASE))}" if len(NEW_BASE) < TARGET_LEN else "正好等长")
# 模拟改写一次,确认改完不再有 OLD、也不破坏 NUL 结尾
repl = NEW_BASE + b"x" * (TARGET_LEN - len(NEW_BASE))
patched = bytearray(data)
for at, _, _ in hits:
patched[at:at + TARGET_LEN] = repl
check(bytes(patched).find(OLD) == -1, "改写后文件里不再有旧路径")
check(patched.count(b"\x00") == data.count(b"\x00"),
"NUL 字节数不变(没有把字符串提前截断)",
f"{data.count(b'\\x00')} → {patched.count(b'\\x00')}")
# ELF 结构没被动过
if is_elf:
check(bytes(patched[:64]) == data[:64], "ELF 头 64 字节未变")
return both == len(hits)
def main() -> int:
args = [a for a in sys.argv[1:] if not a.startswith("-")]
if not args:
d = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".tmp-termuxbin")
if not os.path.isdir(d):
print(f"没有 {d};先在设备上拉几个二进制下来:", file=sys.stderr)
print(" adb shell run-as <包名> sh -c 'base64 files/usr/bin/curl' > curl.b64", file=sys.stderr)
return 2
args = [os.path.join(d, f) for f in sorted(os.listdir(d))]
print("验证:原地改写二进制里的 com.termux 路径")
print(f" 旧 = {OLD.decode()} ({TARGET_LEN} 字节)")
print(f" 新 = {NEW_BASE.decode()} ({len(NEW_BASE)} 字节,补 {TARGET_LEN - len(NEW_BASE)})")
clean = True
for p in args:
if os.path.isfile(p):
clean &= scan(p)
print(f"\n{'=' * 72}")
print(f"{GREEN if fail_n == 0 else RED}通过 {pass_n},失败 {fail_n}{RESET}")
if clean:
print(f"{GREEN}结论:所有匹配都是干净的完整路径,可以放心原地替换。{RESET}")
else:
print(f"{YELLOW}结论:有匹配嵌在更长的串里 —— 必须靠上下文判断,"
f"否则会改坏别的路径。{RESET}")
return 1 if fail_n else 0
if __name__ == "__main__":
sys.exit(main())

View File

@@ -0,0 +1,181 @@
#!/usr/bin/env python3
"""★ 盯住补刀脚本里那个"一个字母就能写坏 85 个二进制"的地方。
## 背景(真实事故)
`res/raw/doubao_patch.sh` 会在 dpkg 装完包之后跑,把新装包里的硬编码路径
`/data/data/com.termux` 换成我们的。第一版用的是:
grep -rla "$OLD" "$P/bin" ... | while read f; do sed -i "s|$OLD|$NEW|g" "$f"; done
`-a` 把**二进制**也当文本,`sed` 改了文件长度 → ELF 内部偏移全废:
CANNOT LINK EXECUTABLE .../dpkg.real: empty/missing DT_HASH/DT_GNU_HASH
in ".../dpkg.real" (new hash type from the future?)
一次写坏 **85 个**可执行文件,整个内置环境报废,只能「重置」。
根因是长度不等(`/data/data/com.termux` = 21 字节,
`/data/data/com.doubao.lynxclone` = 30 字节)—— 这正是
`scripts/verify-elf-patch.py` 早就验证过的那条结论。
**`-I`(大写,跳过二进制)和 `-a`(当成文本)只差一个字母。**
这个脚本就是盯着它的,顺手把其它几条"必须成立"的性质一起验了。
用法:
python scripts/verify-patch-script.py
"""
from __future__ import annotations
import os
import re
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
WS = os.path.dirname(HERE)
PATCH_SH = os.path.join(WS, "android/app/src/main/res/raw/doubao_patch.sh")
WRAPPER_SH = os.path.join(WS, "android/app/src/main/res/raw/dpkg_wrapper.sh")
INSTALLER = os.path.join(
WS, "android/app/src/main/java/com/doubao/lynxclone/termux/TermuxInstaller.kt"
)
GREEN, RED, DIM, RESET = "\033[32m", "\033[31m", "\033[2m", "\033[0m"
fail_n = 0
def check(ok: bool, title: str, detail: str = "") -> bool:
global fail_n
if ok:
print(f" {GREEN}✓{RESET} {title}" + (f" {DIM}{detail}{RESET}" if detail else ""))
else:
fail_n += 1
print(f" {RED}✗{RESET} {title}" + (f" {DIM}{detail}{RESET}" if detail else ""))
return ok
def main() -> int:
for p in (PATCH_SH, WRAPPER_SH, INSTALLER):
if not os.path.isfile(p):
print(f"{RED}找不到 {p}{RESET}", file=sys.stderr)
return 2
patch = open(PATCH_SH, encoding="utf-8").read()
wrapper = open(WRAPPER_SH, encoding="utf-8").read()
installer = open(INSTALLER, encoding="utf-8").read()
print("检查补刀脚本(res/raw/doubao_patch.sh)")
# ---- 1. ★★★ 核心:只能对文本文件动手 ----
print("\n【1】★ 只改文本文件(这一条是那次 85 个二进制的血账)")
code_lines = [ln for ln in patch.splitlines() if not ln.lstrip().startswith("#")]
# 文本判定:现在整段替换逻辑在 python 里,判定也跟着过去
check("@PY@" in patch, "模板里有 @PY@ 占位符(干活的 python)")
check('"@PY@"' in installer, "Kotlin 侧替换了 @PY@")
check("bin/python3" in installer, "@PY@ 指向 $PREFIX/bin/python3")
check("PYEOF" in patch, "替换逻辑是一段内嵌 python")
check("os.walk" in patch, "用 os.walk 遍历(不依赖 find/grep)")
check('b"\\0"' in patch or "\\0" in patch, "python 侧做「含 NUL 就跳过」的二进制过滤")
check('startswith(b"#!")' in patch, "shebang 模式要求这一行以 `#!` 开头")
# `grep -a` 是当初那个 bug 的字面写法
bad_a = [ln for ln in code_lines if re.search(r"grep\s+-[a-zA-Z]*a[a-zA-Z]*\s", ln)]
check(not bad_a, "代码里没有 `grep -a`(-a 就是当初那个 bug)", str(bad_a) if bad_a else "")
# ---- 1b. ★★★ 两个 OLD 不一样(这是这套东西里最容易绕晕的一条) ----
print("\n【1b】★★ 两个 OLD 的取值")
# 补刀脚本(改 shebang)用**长** OLD,带上 `/files/usr`:
# #!/data/data/com.termux/files/usr/bin/python3.14
# → #!<prefix>/bin/python3.14 ✅
# 只换 `/data/data/com.termux` 会得到
# #!<pkg>/files/files/usr/bin/python3.14 ❌ 多一层
# 因为 NEW 自带一个 `files`,原文里又有一个 `/files`。
#
# Kotlin 侧 rewritePrefixes 换的是**整段** `/data/data/com.termux` → dataDir,
# 换出 `<pkg>/files/files/usr/...` 这种形状 —— 那个由沙箱里
# `"files" to ".."` 那条链接住,不用改文本。
m = re.search(r'\.replace\("@OLD@",\s*"([^"]+)"\)', installer)
check(bool(m), "找得到 @OLD@ 的替换")
if m:
old = m.group(1)
check(old == "/data/data/com.termux/files/usr",
"★ 补刀脚本的 @OLD@ 带 `/files/usr`(长的那一个)", old)
m2 = re.search(r'\.replace\("@NEW@",\s*([^)]+)\)', installer)
check(bool(m2), "找得到 @NEW@ 的替换")
if m2:
expr = m2.group(1).strip()
check("prefix" in expr and "filesDir" not in expr,
"★ 补刀脚本的 @NEW@ 是 prefix", expr)
# 沙箱里必须有接住"多一层 files"的那条链
check('"files" to ".."' in installer,
'沙箱表里有 `"files" to ".."`(接住一次文本替换产生的 files/files/usr 形状)')
# ---- 2. 绝不改自己 ----
print("\n【2】绝不改自己")
check('name == "doubao-patch"' in patch, "python 侧有跳过 doubao-patch 的判断")
# ---- 3. 权限:保住原来的权限位 ----
print("\n【3】权限处理")
# python 侧用 os.stat 取权限位、写完再 os.chmod 回去 —— 比 shell 那边干净
check("os.chmod" in patch, "写回前用 os.chmod 保住原权限位")
check("st_mode" in patch, "权限位取自 os.stat")
check("was_x" not in patch, "不再靠 shell 手工记 was_x(那套已经不用了)")
# ---- 4. 占位符:模板和替换代码要对得上 ----
print("\n【4】占位符对得上(模板改了但替换没改,会写出字面量 @XXX@)")
for name, text in (("doubao_patch.sh", patch), ("dpkg_wrapper.sh", wrapper)):
holders = set(re.findall(r"@([A-Z]+)@", text))
check(bool(holders), f"{name} 里的占位符:{sorted(holders)}")
for h in holders:
check(
f'"@{h}@"' in installer,
f"{name} 的 @{h}@ 在 TermuxInstaller 里有替换",
)
# ---- 5. wrapper:**不能**有 --root(见下) ----
print("\n【5】dpkg wrapper 的关键参数")
# ★★ 这一条守的是一个**反直觉**的结论,而且我一开始写反了:
# 给 dpkg 传 `--root=$PREFIX` 看似能解决"编译死的绝对路径",
# 但它会把 `.deb` 清单里的**安装路径**也拼上 root,于是包装到
# `<prefix>/data/data/com.termux/files/usr/bin/`(影子目录),
# 而 apt 照样报 "Setting up ... 成功" —— 静悄悄地装错地方。
# 正解是 `--instdir=/` + 在 prefix 里把那些路径**逐目录接回真实位置**。
root_flags = [
ln for ln in wrapper.splitlines()
if not ln.lstrip().startswith("#") and re.search(r"--root\s*=", ln)
]
check(not root_flags, "没有 --root(它会连安装路径一起拼 root,导致装到影子目录)",
str(root_flags) if root_flags else "")
check("--instdir=/" in wrapper, "带 --instdir=/(按 .deb 清单的原路径安装)")
check("--force-script-chrootless" in wrapper, "带 --force-script-chrootless(Android 不能 chroot)")
check(wrapper.startswith("#!/system/bin/sh"), "shebang 是 /system/bin/sh(内核解析,必须真实存在)")
check("LD_LIBRARY_PATH" in wrapper, "export 了 LD_LIBRARY_PATH")
# ---- 5b. 维护脚本的 shebang:只换路径,不换解释器 ----
print("\n【5b】维护脚本的 shebang(★ 只换路径,别动解释器)")
# ★ 两个方向都错过,所以两个方向都要守:
# ① 什么都不改 → `#!/data/data/com.termux/...` 指向不存在的解释器:
# dpkg: unable to execute .../openssh.postinst: No such file or directory
# ② 无脑换成 bash → 把 `bin/pip` 这种 **Python 脚本**也改成 bash:
# bin/pip: line 2: import: command not found
# 正确:**维护脚本**换成 Termux 的 bash(它们正文是 bash 语法);
# **其他脚本**只做路径替换。
check("bin/bash" in installer, "Kotlin 把维护脚本的 shebang 指到 $PREFIX/bin/bash")
check("var/lib/dpkg/info/" in installer, "Kotlin 只对 var/lib/dpkg/info/ 下的脚本特殊处理")
check("shebang" in patch and "mode" in patch, "补刀脚本有 shebang 模式(unpack 后、configure 前用)")
# ---- 6. 装了包要能自动补刀 ----
print("\n【6】自动补刀挂上了")
check("doubao-patch" in wrapper, "wrapper 里会调 doubao-patch")
check("exit $rc" in wrapper or "exit ${rc}" in wrapper, "补刀失败不影响 dpkg 的退出码")
print(f"\n{'=' * 72}")
print(f"{GREEN if fail_n == 0 else RED}失败 {fail_n}{RESET}")
if fail_n == 0:
print(f"{DIM}这个脚本守着的是一条真实事故:-a 和 -I 差一个字母,代价是 85 个二进制。{RESET}")
return 1 if fail_n else 0
if __name__ == "__main__":
sys.exit(main())

View File

@@ -0,0 +1,205 @@
#!/usr/bin/env python3
"""验证「沙箱路径接通表」和 dpkg 实际要走的路径对得上。
## 为什么需要这个脚本
内置 Termux 的所有二进制都按真 Termux 的包名编译,里面写死:
/data/data/com.termux/files/usr/...
我们给 dpkg 传了 `--root=$PREFIX`,dpkg 就把这些路径统统拼在 root 后面,
于是它真正要去读的是:
$PREFIX/data/data/com.termux/files/usr/etc/dpkg/dpkg.cfg.d
**这个目录必须存在**,否则(用户真机上实测):
dpkg: error: error opening configuration directory
"/data/data/com.termux/files/usr/etc/dpkg/dpkg.cfg.d": Permission denied
E: Sub-process /data/user/0/com.doubao.lynxclone/files/usr/bin/dpkg
returned an error code (2)
`TermuxInstaller.linkLegacyPrefix()` 里有一张 `map` 表,把每条编译死的
路径接回我们自己的目录。**那张表是手写的** —— 漏一条就又是一轮"某个功能
莫名其妙报权限错误"。这个脚本做两件事:
1. 把表**解析出来**(从 Kotlin 源码里),逐条检查:
· 左边(沙箱路径)的每一层父目录都能被建出来
· 右边(真实目录)在 prefix 里有意义(不是凭空造的)
2. 把**已知会出现的编译死路径**(从真二进制里 dump 出来的)拿去和表对照,
报出"dpkg/apt 会去读、但我们没接通"的
用法:
python scripts/verify-sandbox-paths.py
"""
from __future__ import annotations
import os
import re
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
WS = os.path.dirname(HERE)
INSTALLER = os.path.join(
WS, "android/app/src/main/java/com/doubao/lynxclone/termux/TermuxInstaller.kt"
)
GREEN, RED, YELLOW, DIM, RESET = "\033[32m", "\033[31m", "\033[33m", "\033[2m", "\033[0m"
fail_n = 0
def check(ok: bool, title: str, detail: str = "") -> bool:
global fail_n
if ok:
print(f" {GREEN}✓{RESET} {title}" + (f" {DIM}{detail}{RESET}" if detail else ""))
else:
fail_n += 1
print(f" {RED}✗{RESET} {title}" + (f" {DIM}{detail}{RESET}" if detail else ""))
return ok
def parse_map(src: str) -> list[tuple[str, str]]:
"""从 linkLegacyPrefix() 里把 `val map = listOf("a" to "b", ...)` 解析出来。"""
m = re.search(r"val map = listOf\((.*?)\n\s*\)", src, re.S)
if not m:
raise SystemExit("在 TermuxInstaller.kt 里找不到 linkLegacyPrefix 的 map 表")
body = m.group(1)
pairs = re.findall(r'"([^"]+)"\s+to\s+"([^"]+)"', body)
if not pairs:
raise SystemExit("map 表解析出来是空的 —— 正则要跟着源码改")
return pairs
def covered(path: str, table: set[str]) -> bool:
"""这条路径**能不能解析得到** —— 它自己接通了,或者它的某个祖先接通了。
★ 为什么要判祖先:`etc/dpkg/dpkg.cfg.d` 不需要单独接一条链 ——
`etc/dpkg` 整条已经链到真实目录了,子路径自然跟着通。
早先的表是逐条列的,现在改成"接整棵子树",所以判据也得跟着放宽,
否则脚本会报一堆**假**的"缺"。
"""
parts = path.split("/")
for i in range(len(parts), 0, -1):
if "/".join(parts[:i]) in table:
return True
return False
def main() -> int:
with open(INSTALLER, encoding="utf-8") as fh:
src = fh.read()
print("验证沙箱路径接通表")
print(f" 源码:{os.path.relpath(INSTALLER, WS)}")
pairs = parse_map(src)
print(f"\n表里有 {len(pairs)} 条:\n")
# ---- 1. 表的形状 ----
print("【1】沙箱侧路径的形状")
for legacy_rel, real_rel in pairs:
legacy = "/data/data/com.termux/files/usr/" + legacy_rel
real = "/files/usr/" + real_rel
print(f" {legacy:<62} → {real}")
# ★ 左边只有**几种合法形状**:
# files/usr ← 折叠用:把 /data/data/com.termux/files/usr 折成 prefix
# files ← 兜底:接住"一次文本替换"必然产生的 files/files/usr 形状
# <Y> ← 二进制里编译死的 /data/data/com.termux/<Y>
# 出现别的形状说明有人"顺手"加了一条没依据的 —— 那正是当初
# "包装到影子目录"那个 bug 的来源。
OK_TOP = {
"bin", "lib", "libexec", "etc", "include", "share", "var", "tmp", "home",
}
wrong = [
l for l, _ in pairs
if not (l == "files" or l == "files/usr" or l.startswith("files/usr/")
or l.split("/")[0] in OK_TOP)
]
check(not wrong, "左边的形状都在允许集合里(files[/usr[/…]] 或 prefix 根下的标准目录)",
str(wrong) if wrong else "")
check("files/usr" in {l for l, _ in pairs},
"有 `files/usr → .` 这条折叠(形状 A 折回 prefix)")
check("files" in {l for l, _ in pairs},
"有 `files → ..` 这条兜底(接住 files/files/usr 形状)")
# ---- 2. 右边是"真实存在的目录"还是"凭空造的" ----
print("\n【2】右边指向的目录")
# prefix 里 bootstrap 一定会有的目录(真实存在的)
KNOWN_REAL = {
".", "../home",
"bin", "lib", "libexec", "etc", "include", "share", "tmp", "var",
"etc/dpkg", "etc/dpkg/dpkg.cfg.d", "etc/apt", "etc/apt/apt.conf.d",
"etc/tls", "etc/termux",
"var/lib", "var/lib/dpkg", "var/lib/apt",
"var/cache", "var/cache/apt", "var/log",
}
for _, real_rel in pairs:
if real_rel == "../home":
continue
if real_rel not in KNOWN_REAL:
# 不在已知集合里不算失败(bootstrap 版本会变),但要提一句
print(f" {YELLOW}?{RESET} {real_rel} {DIM}(不在已知集合里,确认一下 prefix 下真有这个目录){RESET}")
check(True, "已逐条过目", f"{len(pairs)} 条")
# ---- 3. ★ 核心:dpkg / apt 真正会去读的路径,表里有没有 ----
#
# 这些是从真二进制里 dump 出来的(见 scripts/verify-elf-patch.py
# 的输出:所有匹配都是 `/data/data/com.termux` + `/files/usr/...`)。
print("\n【3】★ 二进制里实际写死、且会被读的路径")
MUST_HAVE = [
# dpkg:配置目录(就是用户在真机上卡住的那一条)
"etc/dpkg/dpkg.cfg.d",
"etc/dpkg",
# apt:Dir::Etc::parts 指向这里,读不到就 "Unable to determine
# a suitable packaging system type"
"etc/apt/apt.conf.d",
"etc/apt",
# 证书:curl 报 (77) error setting certificate file
"etc/tls",
# pkg 的源选择靠它(不看 sources.list)
"etc/termux",
# dpkg 的数据库
"var/lib/dpkg",
"var/lib/apt",
# 临时目录:apt 报 Couldn't create temporary file .../usr/tmp/...
"tmp",
]
table = {l for l, _ in pairs}
missing = [p for p in MUST_HAVE if not covered(p, table)]
for p in MUST_HAVE:
ok = covered(p, table)
mark = f"{GREEN}✓{RESET}" if ok else f"{RED}✗{RESET}"
own = "" if p in table else f"{DIM}(由父目录覆盖){RESET}"
print(f" {mark} {p} {own}")
check(not missing, "编译死路径全都通了", f"缺 {missing}" if missing else "")
# ---- 4. bash 的 login_shell(写在 ELF 里,rewritePrefixes 改不到)----
print("\n【4】其他被写进二进制的路径")
# verify-elf-patch.py 在 bash 里 dump 到的:
# /data/data/com.termux/files/home ← login_shell
# /data/data/com.termux/files/usr/tmp
# /data/data/com.termux/files/usr/bin/sh
# /data/data/com.termux/files/usr/etc/profile
# /data/data/com.termux/share/glib-2.0/schemas ← glib(实测报过错)
check("home" in table, "home 已接通(bash 的 login_shell 用它)")
# ★ 形状 A(带 files/usr)靠 `files/usr → .` 折叠 + 下面这些条目一起成立。
# `bin/ lib/ share/` 这些**没有 files/usr 前缀**的条目同时也是给形状 B 用的
# —— glib 报的 `/data/data/com.termux/share/glib-2.0/schemas` 就是形状 B,
# 当初正是因为表里只有形状 A,才报 "No such file or directory"。
for extra, why in [
("bin", "可执行文件(dpkg 解包落点 / PATH 查找)"),
("lib", "共享库"),
("share", "★ 数据目录 —— glib 的 schema 走这条(形状 B)"),
("include", "头文件"),
]:
check(extra in table, f"{extra}/ 已接通({why})")
print(f"\n{'=' * 72}")
print(f"{GREEN if fail_n == 0 else RED}失败 {fail_n}{RESET}")
return 1 if fail_n else 0
if __name__ == "__main__":
sys.exit(main())