#!/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 源码是一个 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/ b/,供 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_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 #include #include #include #include #include #include #include #include #include #include #include /* 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/ 和 /data/data/ 是同一个目录的两种 * 写法,包里两种都出现过,所以两个都要认。 */ 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 \n", "#include \n#include \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 ', 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 ', 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)