内置 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 照常可用。
This commit is contained in:
doubao
2026-10-14 12:48:47 +08:00
parent 982c64939b
commit 028d67c3ec
33 changed files with 3241 additions and 8 deletions

View File

@@ -30,8 +30,8 @@ android {
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
* 改小了会装不上)。
*/
versionCode = 232
versionName = "2.0.32"
versionCode = 233
versionName = "2.0.33"
ndk {
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份

View File

@@ -28,6 +28,18 @@ object TermuxInstaller {
private const val BOOTSTRAP_LIB = "libtermux-bootstrap.so"
private const val ARROW = "\u2190" // SYMLINKS.txt 里的分隔符
/** 自编 dpkg 的 tar 包(伪装成 .so,见 [installOwnDpkg]) */
private const val DPKG_LIB = "libdoubao-dpkg.so"
/**
* 自编 dpkg 的版本戳。换了 dpkg 二进制就 +1 ——
* 不然老设备上标记文件还在,新二进制不会被解出来。
*
* v1 → v2:维护脚本里**绝对路径**的改写(之前只改了 shebang,
* 于是 `mkdir -p "/data/data/com.termux/..."` 这类照样撞权限)。
*/
private const val DPKG_VALUE = 2
fun prefix(context: Context): File = File(context.filesDir, "usr")
fun home(context: Context): File = File(context.filesDir, "home")
fun bashPath(context: Context): String = File(prefix(context), "bin/bash").absolutePath
@@ -48,8 +60,11 @@ object TermuxInstaller {
*
* 把戳的值带上版本号,**对不上就只重跑修正式步骤**(不重新解压,
* 解压要几十秒)。以后再加这类"装完之后要修一下"的逻辑,把这里 +1。
*
* v25:装上自编 dpkg(见 [installOwnDpkg])。
* v26:补 `files/home` 那条沙箱链(bash 读 `$HOME/.bashrc` 用)。
*/
private const val STAMP_VALUE = "ok:24"
private const val STAMP_VALUE = "ok:26"
/**
* wrapper / 补丁脚本的版本号。
@@ -278,11 +293,228 @@ object TermuxInstaller {
ensureSources(context)
ensureCaBundle(context)
fixBrokenSymlinks(context).let { trace(context, "修了 $it 个断链") }
installDpkgWrapper(context)
installOwnDpkg(context)
writePatcherScript(context)
linkLegacyPrefix(context)
}
/**
* ★★★ 装上**我们自编的 dpkg**。
*
* ## 为什么要自编
*
* Termux 仓库里的 dpkg 是拿 `--sysconfdir=$PREFIX/etc` 编的,
* 而 `$PREFIX` 在编译期就固化成了 `/data/data/com.termux/files/usr`。
* 上游把配置目录当**编译期常量**烤进二进制,而且 dpkg 在**解析命令行之前**
* 就去读它 —— 于是 `--admindir` 指得再对也没用:
*
* dpkg: error opening configuration directory
* '/data/data/com.termux/files/usr/etc/dpkg/dpkg.cfg.d': Permission denied
*
* `/data/data/com.termux` 是 **0700、属于真 Termux 的 UID**,我们的应用
* 连穿都穿不进去,`scandir` 拿 EACCES;dpkg 对配置目录 ENOENT 是静默跳过、
* 对 EACCES 直接致命退出。所以只要真 Termux 装着,Termux 的 dpkg 就必死。
*
* 自编版把这一处换成了**运行时解析**(从 `/proc/self/exe` 反推前缀),
* 于是同一个二进制在任何包名下都指向自己所在的前缀。顺带还修了两件事:
*
* · **架构名**用 Termux 的写法(`x86_64` / `aarch64`)。Debian 那边叫
* `amd64` / `arm64`,用错了 dpkg 会把数据库里**每一个包**都判成
* `'x86_64' is not a valid architecture name`。
* · 维护脚本的 **shebang**。Termux 的包里写的是
* `#!/data/data/com.termux/files/usr/bin/sh`,内核对这条读不到的路径
* 报 EACCES,而 dpkg 会把它显示成"脚本没有执行权限",指错方向。
* 自编版在 exec 之前把这一行改成我们自己的前缀。
*
* 完整配方(补丁 + 构建脚本 + 校验脚本)在仓库的 `android/termux-dpkg/`。
*
* ## 二进制怎么来的
*
* `lib/<abi>/libdoubao-dpkg.so` 其实是个 **tar 包**(改名的原因见
* [makeJniLibs],跟 `libtermux-bootstrap.so` 一个套路)。
* 解出来直接覆盖 `bin/` 下的同名程序 —— 因为自编版是**完全替代**,
* 不再需要 `dpkg.real` + wrapper 那一套(wrapper 本来就是在绕
* "编译死的配置目录"这个我们已经从根上修掉的问题)。
*/
private fun installOwnDpkg(context: Context) {
val prefix = prefix(context)
val marker = File(prefix, "bin/dpkg")
val stamp = File(context.filesDir, ".dpkg-own-$DPKG_VALUE")
// 已经装过这一版就不重复解包(解包 + chmod 有成本)
if (stamp.exists() && marker.isFile) {
if (looksLikeOurDpkg(marker)) return
trace(context, "bin/dpkg 不像自编版,重新解一份")
}
val dir = File(context.applicationInfo.nativeLibraryDir)
val tar = File(dir, DPKG_LIB)
if (!tar.isFile) {
trace(context, "找不到 $DPKG_LIB($dir),只能用仓库里的 dpkg")
return
}
try {
val names = readTarNames(tar)
if (names.isEmpty()) {
trace(context, "$DPKG_LIB 里没解出文件名,跳过")
return
}
extractTar(tar, prefix, "bin")
var n = 0
for (name in names) {
val f = File(prefix, "bin/$name")
if (f.isFile) {
f.setExecutable(true, false)
n++
}
}
trace(context, "已装自编 dpkg(v$DPKG_VALUE):$n 个程序 $names")
// 旧方案留下的东西清掉,免得以后有人看到 bin/dpkg.real 以为还在用
File(prefix, "bin/dpkg.real").delete()
stamp.writeText("ok")
} catch (t: Throwable) {
trace(context, "装自编 dpkg 失败:${t.javaClass.simpleName}: ${t.message}")
}
}
/**
* 粗判一个文件是不是我们自编的 dpkg。
*
* 判据是 `/proc/self/exe` 这个字符串 —— 自编版的运行时前缀解析全靠它,
* 而 Termux 仓库里的那份**没有**(它是编译期写死的路径)。
* 只读前 512 KB 就够了,字符串在只读数据段靠前的位置。
*/
private fun looksLikeOurDpkg(f: File): Boolean = try {
val buf = ByteArray(512 * 1024)
val n = FileInputStream(f).use { it.read(buf) }
var found = false
if (n > 0) {
val needle = "/proc/self/exe".toByteArray(Charsets.US_ASCII)
outer@ for (i in 0..(n - needle.size)) {
for (j in needle.indices) {
if (buf[i + j] != needle[j]) continue@outer
}
found = true
break
}
}
found
} catch (_: Throwable) {
false
}
/* ------------------------------------------------------------------
* 极简 tar 读取
*
* 只要 ustar 格式、只要普通文件、不要长名/PAX —— 我们自己打的包
* (见 android/termux-dpkg/make-jnilibs.sh)全是短名的普通文件。
* 为了这点事去引一个 tar 库不值得,所以手写。
* ------------------------------------------------------------------ */
private const val TAR_BLOCK = 512
/** 读出 tar 里所有普通文件的名字(跳过目录等元数据项) */
private fun readTarNames(tar: File): List<String> {
val out = mutableListOf<String>()
FileInputStream(tar).use { input ->
val header = ByteArray(TAR_BLOCK)
while (true) {
if (!readFully(input, header)) break
if (header.all { it == 0.toByte() }) break
val name = cString(header, 0, 100)
val size = cString(header, 124, 12).toLongOrNull(8) ?: 0L
val type = header[156].toInt().toChar()
val prefix = cString(header, 345, 155)
val full = if (prefix.isEmpty()) name else "$prefix/$name"
if (type == '0' || type == '\u0000') {
if (!full.endsWith("/")) out.add(full)
}
val skip = ((size + TAR_BLOCK - 1) / TAR_BLOCK) * TAR_BLOCK
if (!skipFully(input, skip)) break
}
}
return out
}
/**
* 把 tar 里的普通文件解到 [destRoot]/[subdir] 下。
*
* 只接受**纯文件名**(没有斜杠)—— 我们只放几个 bin 程序,
* 拒绝路径能让损坏或恶意的 tar 没法写到别处去。
*/
private fun extractTar(tar: File, destRoot: File, subdir: String) {
val dest = File(destRoot, subdir)
dest.mkdirs()
FileInputStream(tar).use { input ->
val header = ByteArray(TAR_BLOCK)
while (true) {
if (!readFully(input, header)) break
if (header.all { it == 0.toByte() }) break
val name = cString(header, 0, 100)
val size = cString(header, 124, 12).toLongOrNull(8) ?: 0L
val type = header[156].toInt().toChar()
val prefix = cString(header, 345, 155)
val full = if (prefix.isEmpty()) name else "$prefix/$name"
val padded = ((size + TAR_BLOCK - 1) / TAR_BLOCK) * TAR_BLOCK
val plain = (type == '0' || type == '\u0000') &&
!full.endsWith("/") && !full.contains('/') &&
full != "." && full != ".."
if (plain) {
FileOutputStream(File(dest, full)).use { fos ->
var left = size
val buf = ByteArray(64 * 1024)
while (left > 0) {
val want = minOf(left, buf.size.toLong()).toInt()
val got = input.read(buf, 0, want)
if (got <= 0) throw IllegalStateException("tar 提前结束:$full")
fos.write(buf, 0, got)
left -= got
}
}
if (!skipFully(input, padded - size)) break
} else if (!skipFully(input, padded)) {
break
}
}
}
}
private fun readFully(input: FileInputStream, buf: ByteArray): Boolean {
var off = 0
while (off < buf.size) {
val n = input.read(buf, off, buf.size - off)
if (n <= 0) return off == 0
off += n
}
return true
}
private fun skipFully(input: FileInputStream, count: Long): Boolean {
var left = count
val buf = ByteArray(8 * 1024)
while (left > 0) {
val n = input.read(buf, 0, minOf(left, buf.size.toLong()).toInt())
if (n <= 0) return false
left -= n
}
return true
}
/** 读 tar 头里的定长字符串(以 NUL 结尾) */
private fun cString(buf: ByteArray, offset: Int, len: Int): String {
var end = offset
val limit = minOf(offset + len, buf.size)
while (end < limit && buf[end] != 0.toByte()) end++
return String(buf, offset, end - offset, Charsets.UTF_8).trim()
}
/**
* ★★ 保证 `etc/tls/cert.pem` **真的存在**。
*
@@ -1377,9 +1609,21 @@ object TermuxInstaller {
// `filesDir` 本身就带一个 `files`。有这条链,那种"看着别扭但
// 确实是这么来的"路径也能解析到正确位置。
val map = listOf(
// ★★★ 顺序有讲究,**必须 `files/home` 排在最前面**:
//
// `files` 这条会被接成软链(下一条),一旦它成了软链,
// 再想往里建 `files/home` 就会被解析到**目标目录**去
// (也就是真实 home),链接根本建不到 we 想要的位置。
// 所以凡是"建在 `files` 里面"的条目,都得排在 `files` 前面。
//
// `files/home` 为什么需要:bash 找 `$HOME/.bashrc` 用的是
// `/data/data/com.termux/files/home`(形状 A,多一层 files)。
// 少了这条链它会掉进**真 Termux 的 home**,每开一个终端就报
// bash: /data/data/com.termux/files/usr/etc/bash.bashrc: Permission denied
"files/home" to "../home",
// 形状 A:把 `files/usr` 折回 prefix 自己
"files/usr" to ".",
// ★ 第二条兜底:一次文本替换会产生的 `files/files/usr` 形状
// ★ 第三条兜底:一次文本替换会产生的 `files/files/usr` 形状
"files" to "..",
// prefix 根下的标准目录(形状 B)
"bin" to "bin",
@@ -1441,6 +1685,9 @@ object TermuxInstaller {
// ★ 每种形状都要有代表:
// `files/usr/bin` 走形状 A(dpkg 解包的落点)
// `share` 走形状 B(glib 读 schema 的地方)
// `files/home` bash 读 `$HOME/.bashrc` 的地方 ——
// 这条少了不会报错,只是**每开一次终端**
// 都往真 Termux 的 home 里撞权限
val probes = listOf(
"files/usr/bin" to "bin",
"files/usr/lib" to "lib",
@@ -1453,6 +1700,7 @@ object TermuxInstaller {
"var/lib/dpkg" to "var/lib/dpkg",
"tmp" to "tmp",
"home" to "../home",
"files/home" to "../home",
)
val wrong = probes.filterNot { (l, r) ->
val a = runCatching { File(File(legacyRoot, l).absolutePath).canonicalPath }.getOrNull()
@@ -1489,6 +1737,89 @@ object TermuxInstaller {
return dir.isDirectory
}
/**
* ★★★ 检测"真 Termux 冲突" —— 这是一个**无解的硬冲突**,得让用户知道。
*
* ## 现象
*
* 装了真 Termux(`com.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 <prefix>/bin/dpkg returned an error code (2)
*
* ★ 而**没装真 Termux 的设备上一切正常** —— 这就是为什么模拟器
* (我们一开始没装 Termux)一直是好的,只在用户手机上炸。
*
* ## 为什么绕不过去(这些我都实测过,不是推测)
*
* dpkg 找配置目录用的是**编译死的绝对路径**
* (Termux 构建 dpkg 时 `$PREFIX/etc/dpkg` = `/data/data/com.termux/files/usr/etc/dpkg`),
* 而它对"那个目录打不开"的处理分两种:
*
* 目录不存在(ENOENT)→ **静默跳过**,用默认值继续 ← 只有我们时
* 存在但打不开(EACCES)→ **致命报错** ← 装了真 Termux 时
*
* (Termux 自己会建这个目录,所以只要真 Termux 跑过一次就存在了。)
*
* 试过并**全部失败**的办法:
*
* · `--root=` / `DPKG_ROOT` / `--instdir=` —— dpkg **在解析命令行之前**
* 就读配置了(dpkg 维护者原话:*"the config files are read before
* the options are parsed"*),所以这些参数一律管不到配置目录。
* · 环境变量指定配置目录 —— dpkg **根本没有**这个变量
* (`strings dpkg.real | grep '^DPKG_'` 里没有 CONFDIR 之类)。
* · `LD_PRELOAD=libtermux-exec.so` —— 它**只拦 `execve`**
* (它自己的字符串是 `TERMUX_EXEC__EXECVE_CALL__INTERCEPT`),
* 不碰 `opendir`,所以救不了。
* · 在自己 prefix 里造一条 `/data/data/com.termux/...` ——
* 那是**绝对路径**,内核永远走不到我们的目录里。
* (沙箱路径对"带 `--root` / 拼前缀"的访问有效,对这个无效。)
* · `unshare -m` + `mount --bind` 把那条路遮掉 ——
* Android 应用没有 `CAP_SYS_ADMIN`,`unshare: Operation not permitted`。
* · 改 dpkg 二进制里的字节 —— 长度不等(21 → 30 字节),
* 原地替换会废掉 ELF 内部偏移(`scripts/verify-elf-patch.py` 验过)。
* · 从 apt 源装新版 dpkg —— 同一个 `$PREFIX` 构建,路径一模一样。
*
* ## 所以能做的只有"说清楚 + 给一条出路"
*
* 界面上明确告诉用户:**内置的 Termux 和真 Termux App 不能同时用**。
* 这不是我们的 bug,是 Android 的沙箱规则。
* (内置的那套是自包含的,卸载真 Termux 不会丢任何东西。)
*
* @return true = 检测到真 Termux 而且它挡住了 dpkg
*/
fun hasRealTermuxConflict(context: Context): Boolean {
val real = File("/data/data/com.termux")
// ① 真 Termux 得装着。
// ★ 判断"这个绝对路径存不存在"**不能用 `File.exists()`** ——
// 中间某一层没权限遍历时它返回 **false**(不是抛异常),
// 于是"存在但我们读不了"会被误判成"不存在"。
// 这正是我第一次写错的地方(分支永远进不去,横幅不出现)。
// 用 NIO 的 `notExists` 才是准的:只有 **ENOENT** 才算不存在,
// EACCES 会抛出来 —— 那恰好是我们要的信号。
val exists = try {
!java.nio.file.Files.notExists(real.toPath())
} catch (_: Throwable) {
true // 抛异常 = 权限不足 = 它确实在那儿
}
if (!exists) return false
// ② 它得**挡着我们**:真实表现是 dpkg 连 `--version` 都跑不动(rc != 0)。
// ★ 不再去 list() 那个配置目录 —— 上面的 exists 陷阱已经踩过一次,
// 「能不能列出来」在多层没权限时同样不可靠。
// 直接看**最终后果**:dpkg 能不能跑。这个判据不会骗人。
return try {
val p = ProcessBuilder(
File(prefix(context), "bin/dpkg").absolutePath, "--version",
).redirectErrorStream(true).start()
p.inputStream.bufferedReader().readText()
p.waitFor() != 0
} catch (_: Throwable) {
false
}
}
/**
* 内容一样就不写盘。
*

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
/**
@@ -97,6 +100,23 @@ fun TerminalScreen(
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) {
@@ -223,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,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 ""))