dsh-plugin-mesh 0.0.0-stage → 0.3.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1183 -2
  3. package/client/client.js +958 -0
  4. package/cordis.patch.yml +80 -0
  5. package/install.sh +142 -0
  6. package/lib/_rehearsal-peer.mjs +229 -0
  7. package/lib/_selftest-capabilities.mjs +631 -0
  8. package/lib/_selftest-client.mjs +249 -0
  9. package/lib/_selftest-discovery.mjs +51 -0
  10. package/lib/_selftest-newsession.mjs +124 -0
  11. package/lib/_selftest-prompt.mjs +97 -0
  12. package/lib/_selftest-tsnet-live.mjs +169 -0
  13. package/lib/_selftest-tsnet-tailnet.mjs +418 -0
  14. package/lib/_selftest-tsnet.mjs +647 -0
  15. package/lib/capabilities.js +786 -0
  16. package/lib/conversation.js +59 -0
  17. package/lib/discovery.js +744 -0
  18. package/lib/identity.js +136 -0
  19. package/lib/index.js +2079 -0
  20. package/lib/prompt.js +50 -0
  21. package/lib/scan.js +118 -0
  22. package/lib/tsnet/bridge.js +71 -0
  23. package/lib/tsnet/checksums.js +19 -0
  24. package/lib/tsnet/download.js +384 -0
  25. package/lib/tsnet/manager.js +655 -0
  26. package/package.json +118 -4
  27. package/scripts/__pycache__/mesh-tsnet-merge.cpython-312.pyc +0 -0
  28. package/scripts/_selftest-tsnet-merge.py +168 -0
  29. package/scripts/build-sidecar.sh +372 -0
  30. package/scripts/check-loadable.mjs +154 -0
  31. package/scripts/check-tarball.mjs +106 -0
  32. package/scripts/check-tdz.mjs +78 -0
  33. package/scripts/check-version.mjs +32 -0
  34. package/scripts/fix-android-tls-align.py +87 -0
  35. package/scripts/mesh-tsnet-merge.py +345 -0
  36. package/scripts/mesh-tsnet-onboarding.md +98 -0
  37. package/scripts/publish-assets.py +213 -0
  38. package/scripts/push-via-api.py +262 -0
  39. package/scripts/release-plugin.sh +129 -0
  40. package/scripts/restart-dsh.sh +308 -0
  41. package/scripts/submit-to-awesome.py +212 -0
  42. package/scripts/verify-lan-mirror.mjs +57 -0
  43. package/sidecar/androidbin_linux.go +39 -0
  44. package/sidecar/androidnet_linux.go +414 -0
  45. package/sidecar/androidnet_other.go +15 -0
  46. package/sidecar/go.mod +51 -0
  47. package/sidecar/go.sum +239 -0
  48. package/sidecar/main.go +850 -0
@@ -0,0 +1,154 @@
1
+ /**
2
+ * 校验一份**已落盘**的插件副本"真的能被加载",而不只是"文件都对得上"。
3
+ *
4
+ * ── 为什么单独做这一步 ──────────────────────────────────────────────
5
+ * 升级是"先落盘、后重启"两段式的,中间存在一个**半态窗口**:磁盘已经是新版本,
6
+ * 进程还是旧版本(VERSION 是进程启动时读入的常量,不会跟着磁盘变)。这个窗口
7
+ * 里如果新代码新增了一个 import,而落盘**漏了**那个文件,重启就会**当场崩**
8
+ * —— DSH 加载插件时才会去解析 import,之前一切正常。
9
+ *
10
+ * 两种常规自检都兜不住这个失败模式:
11
+ * · `find lib -type f` + 逐字节 cmp:**被漏掉的文件根本不在磁盘上**,
12
+ * 没有"不一致"可比对,cmp 只会报"全部一致"。
13
+ * · `node --check <file>`:只做**单文件语法**解析,不解析 import 图,
14
+ * 缺文件照样通过。
15
+ * 唯一能精确复现"重启即崩"的,是**从安装路径实际 import 一次入口**。
16
+ *
17
+ * 踩过:0.3.28 新增了 `lib/prompt.js`(index.js 顶层 import 它)。当时磁盘
18
+ * 一度处于"新 index.js + 缺 prompt.js"的半态,cmp 全绿、--check 全绿,
19
+ * 差点带着它重启。对端 hos 复现并给出这条做法,实测有效。
20
+ *
21
+ * ── 跑法 ────────────────────────────────────────────────────────────
22
+ * # 校验本仓库(默认)
23
+ * node scripts/check-loadable.mjs
24
+ *
25
+ * # 校验某个**安装路径**(升级脚本里应校验这个,而不是仓库)
26
+ * node scripts/check-loadable.mjs ~/.dsh/profiles/desktop/node_modules/dsh-plugin-mesh
27
+ *
28
+ * 退出码 0 = 可加载;非 0 = 不可加载(升级脚本应当据此**回滚**)。
29
+ *
30
+ * ⚠️ 必须在**装了运行时的位置**跑。index.js 顶层 import 了 DSH 运行时提供的
31
+ * `@deepseek-ai/dsh-brand`;在仓库里直接跑会因为解析不到它而报
32
+ * ERR_MODULE_NOT_FOUND —— 那是"仓库缺 node_modules",**不是**半态,别误判。
33
+ * 校验仓库时用 `--allow-missing-runtime-dep` 把这一类错误降级为警告。
34
+ *
35
+ * ✅ 这一步是**安全**的:`import` 只求值顶层代码,而 index.js 把起服务、绑端口、
36
+ * 建 udp socket 全都放在 `apply()` 里,顶层没有副作用。实测连跑 3 次:
37
+ * 不写 state.json / threads.json,也不抢 sidecar 的 45917(仍归运行中的进程)。
38
+ * 所以可以放心放进发布门禁和升级脚本 —— 它不会干扰正在跑的实例。
39
+ */
40
+ import { existsSync, readFileSync } from "node:fs";
41
+ import { dirname, isAbsolute, join, resolve } from "node:path";
42
+ import { fileURLToPath, pathToFileURL } from "node:url";
43
+
44
+ const ENTRY = "lib/index.js";
45
+
46
+ /** 报错里出现这些包名,说明缺的是 DSH 运行时提供的依赖,不是磁盘半态。 */
47
+ const RUNTIME_PROVIDED = ["@deepseek-ai/"];
48
+ /** 预期的入口导出 —— 少一个都说明这份代码和当前协议不匹配。 */
49
+ const EXPECTED_EXPORTS = ["Config", "MESH_DEFAULT_PORT", "apply", "inject", "name"];
50
+
51
+ function parseArgs(argv) {
52
+ const args = { target: null, allowMissingRuntimeDep: false, quiet: false };
53
+ for (const a of argv) {
54
+ if (a === "--allow-missing-runtime-dep") args.allowMissingRuntimeDep = true;
55
+ else if (a === "--quiet") args.quiet = true;
56
+ else if (!a.startsWith("-")) args.target = a;
57
+ else {
58
+ console.error(`✗ 未知参数:${a}`);
59
+ process.exit(2);
60
+ }
61
+ }
62
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
63
+ args.dir = args.target
64
+ ? resolve(isAbsolute(args.target) ? args.target : join(process.cwd(), args.target))
65
+ : root;
66
+ return args;
67
+ }
68
+
69
+ const args = parseArgs(process.argv.slice(2));
70
+ const say = (...m) => {
71
+ if (!args.quiet) console.log(...m);
72
+ };
73
+
74
+ const entryPath = join(args.dir, ENTRY);
75
+ if (!existsSync(entryPath)) {
76
+ console.error(`✗ 找不到入口:${entryPath}`);
77
+ console.error(" 这份副本不完整(连 lib/index.js 都没有),**不要重启**。");
78
+ process.exit(1);
79
+ }
80
+
81
+ /** 读 package.json 的版本,仅用于打印;读不到不算失败。 */
82
+ function versionOf(dir) {
83
+ try {
84
+ const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
85
+ return pkg.version ?? "?";
86
+ } catch {
87
+ return "?";
88
+ }
89
+ }
90
+
91
+ /**
92
+ * 读 lib/index.js 里的 `const VERSION = "x.y.z";` —— 这是**进程自述**的版本。
93
+ * 不用 mod.version:index.js 并不导出 VERSION(导出只有 Config/apply/inject/name…),
94
+ * 一开始就是这么写错的,别再踩。
95
+ */
96
+ function declaredVersion(dir) {
97
+ try {
98
+ const src = readFileSync(join(dir, ENTRY), "utf8");
99
+ return /^const VERSION = "([^"]+)";/m.exec(src)?.[1] ?? null;
100
+ } catch {
101
+ return null;
102
+ }
103
+ }
104
+
105
+ say(`▶ 校验可加载性: ${args.dir}`);
106
+ say(` 版本(磁盘): ${versionOf(args.dir)}`);
107
+ say(` 入口: ${entryPath}`);
108
+
109
+ const started = Date.now();
110
+ let mod;
111
+ try {
112
+ mod = await import(pathToFileURL(entryPath).href);
113
+ } catch (err) {
114
+ const code = err?.code ?? "";
115
+ const msg = String(err?.message ?? err);
116
+ const missingRuntimeDep =
117
+ code === "ERR_MODULE_NOT_FOUND" && RUNTIME_PROVIDED.some((p) => msg.includes(p));
118
+
119
+ if (missingRuntimeDep && args.allowMissingRuntimeDep) {
120
+ console.warn(`⚠ 跳过:缺的是 DSH 运行时依赖,不是磁盘半态。`);
121
+ console.warn(` ${msg.split("\n")[0]}`);
122
+ process.exit(0);
123
+ }
124
+
125
+ console.error(`✗ 加载失败(${Date.now() - started}ms):${code || "Error"}`);
126
+ console.error(` ${msg.split("\n")[0]}`);
127
+ if (code === "ERR_MODULE_NOT_FOUND") {
128
+ console.error("");
129
+ console.error(" 这是**半态**特征:入口 import 了磁盘上不存在的文件。");
130
+ console.error(" 带着这份磁盘去重启,DSH 会在加载插件时当场崩 —— 请先补齐文件或回滚。");
131
+ }
132
+ process.exit(1);
133
+ }
134
+
135
+ const exports = Object.keys(mod).sort();
136
+ const missing = EXPECTED_EXPORTS.filter((k) => !(k in mod));
137
+ if (missing.length) {
138
+ console.error(`✗ 加载成功但导出不全,缺: ${missing.join(", ")}`);
139
+ console.error(` 实际导出: ${exports.join(", ") || "(空)"}`);
140
+ process.exit(1);
141
+ }
142
+
143
+ // 自述版本应当和 package.json 一致(两者不一致会让"装没装上"没法从界面判断)。
144
+ const diskVersion = versionOf(args.dir);
145
+ const selfVersion = declaredVersion(args.dir);
146
+
147
+ say(`✓ 可加载(${Date.now() - started}ms):exports = ${exports.join(", ")}`);
148
+ if (selfVersion && diskVersion !== "?" && selfVersion !== diskVersion) {
149
+ console.warn(`⚠ 自述 VERSION(${selfVersion}) ≠ package.json(${diskVersion})`);
150
+ say(" (VERSION 是启动时冻结的常量,这通常说明**进程**还没重启 —— 磁盘已是新版本)");
151
+ } else if (selfVersion) {
152
+ say(` 自述 VERSION: ${selfVersion}(与 package.json 一致)`);
153
+ }
154
+ process.exit(0);
@@ -0,0 +1,106 @@
1
+ /**
2
+ * 发布门禁:校验**打出来的包**,而不是源码树。
3
+ *
4
+ * 为什么不能只跑 check-loadable 就完事:那个查的是仓库目录,而真正发出去的是
5
+ * `npm pack` 按 `files` 白名单挑出来的 tar。两者可以不一致 —— `files` 里漏写一个
6
+ * 目录,源码树完好、发布件残缺,装到别人机器上才炸。
7
+ * 本项目已经栽过好几次"看着接上了、其实没接"(cordis.patch.yml 钉死默认值、
8
+ * install.sh 漏拷 scripts/、门禁只被注释提到),所以这里刻意校验**产物本身**。
9
+ *
10
+ * 做四件事:
11
+ * 1. 真打一个 tgz(--ignore-scripts,避免递归触发 pre* 脚本)
12
+ * 2. 解到临时目录,检查运行必需的条目一个不少
13
+ * 3. 对**解出来的那棵树**跑 check-loadable:它能抓出"入口 import 了包内不存在
14
+ * 的文件"这种半态(缺 @deepseek-ai/* 运行时依赖不算错,那是宿主提供的)
15
+ * 4. 打印体积与文件数
16
+ *
17
+ * node scripts/check-tarball.mjs
18
+ */
19
+ import { execFileSync } from "node:child_process";
20
+ import { mkdtempSync, rmSync, existsSync, statSync, readdirSync } from "node:fs";
21
+ import { tmpdir } from "node:os";
22
+ import { join, dirname } from "node:path";
23
+ import { fileURLToPath } from "node:url";
24
+
25
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
26
+
27
+ /** 发布件里**必须**存在的条目。缺任何一个,装到别人机器上就是坏的。 */
28
+ const REQUIRED = [
29
+ "package.json",
30
+ "cordis.patch.yml", // dsh.bundle.patch 指向它,没有它插件根本挂不上
31
+ "lib/index.js", // 入口
32
+ "lib/capabilities.js",
33
+ "lib/prompt.js",
34
+ "lib/discovery.js",
35
+ "lib/conversation.js",
36
+ "lib/identity.js",
37
+ "lib/tsnet/manager.js",
38
+ "client/client.js", // dsh.client 指向它
39
+ "scripts/check-loadable.mjs",
40
+ "README.md",
41
+ "LICENSE",
42
+ ];
43
+
44
+ let failed = 0;
45
+ const bad = (m) => {
46
+ failed += 1;
47
+ console.error(`✗ ${m}`);
48
+ };
49
+
50
+ const tmp = mkdtempSync(join(tmpdir(), "mesh-pack-"));
51
+ try {
52
+ console.log("▶ 打包(npm pack --ignore-scripts)");
53
+ const out = execFileSync("npm", ["pack", "--ignore-scripts", "--pack-destination", tmp, "--silent"], {
54
+ cwd: ROOT,
55
+ encoding: "utf8",
56
+ }).trim();
57
+ const tgz = join(tmp, out.split("\n").pop().trim());
58
+ if (!existsSync(tgz)) {
59
+ bad(`没生成 tgz(npm pack 输出:${out})`);
60
+ process.exit(1);
61
+ }
62
+ const sizeKb = Math.round(statSync(tgz).size / 1024);
63
+ console.log(` 产物 ${out}(${sizeKb} KB)`);
64
+
65
+ // 解包:tar 在各平台上都有(macOS / Linux 自带,Windows 10+ 自带 bsdtar)
66
+ const dest = join(tmp, "unpacked");
67
+ execFileSync("mkdir", ["-p", dest]);
68
+ execFileSync("tar", ["-xzf", tgz, "-C", dest]);
69
+
70
+ // npm 打出来的包固定多一层 package/
71
+ const pkgRoot = join(dest, "package");
72
+ if (!existsSync(pkgRoot)) {
73
+ bad("解出来没有 package/ 目录,包结构不对");
74
+ process.exit(1);
75
+ }
76
+
77
+ console.log("▶ 必需条目");
78
+ for (const rel of REQUIRED) {
79
+ if (existsSync(join(pkgRoot, rel))) console.log(` ✓ ${rel}`);
80
+ else bad(`缺文件:${rel}`);
81
+ }
82
+
83
+ const count = (d) => readdirSync(d, { withFileTypes: true }).reduce((n, e) => n + (e.isDirectory() ? count(join(d, e.name)) : 1), 0);
84
+ console.log(` 文件总数:${count(pkgRoot)}`);
85
+
86
+ console.log("▶ 对**发布件**跑可加载性门禁");
87
+ try {
88
+ const r = execFileSync("node", [join(pkgRoot, "scripts", "check-loadable.mjs"), pkgRoot, "--allow-missing-runtime-dep"], {
89
+ encoding: "utf8",
90
+ cwd: pkgRoot,
91
+ });
92
+ process.stdout.write(r.split("\n").map((l) => (l ? ` ${l}` : l)).join("\n"));
93
+ } catch (e) {
94
+ bad("发布件不可加载");
95
+ process.stdout.write(String(e.stdout ?? ""));
96
+ process.stderr.write(String(e.stderr ?? ""));
97
+ }
98
+ } finally {
99
+ rmSync(tmp, { recursive: true, force: true });
100
+ }
101
+
102
+ if (failed > 0) {
103
+ console.error(`\n✗ 发布门禁未通过(${failed} 项)—— 不要发布`);
104
+ process.exit(1);
105
+ }
106
+ console.log("\n✓ 发布门禁通过:打出来的包完整且可加载");
@@ -0,0 +1,78 @@
1
+ /**
2
+ * 静态检查 `const` 的"声明前使用"(TDZ)。
3
+ *
4
+ * 为什么需要:这类错误**语法完全合法**,`node --check` 抓不到,只在运行时抛
5
+ * ReferenceError。而插件里入站任务处理被 try/catch 包着,异常会被吞掉、任务
6
+ * 停在 accepted —— **静默失败**,发送方看不出异常。
7
+ *
8
+ * 实测连续踩了两次:先把 canInject 判断插到闸门之前,但 `key` / `liveSession`
9
+ * 的声明还留在后面。
10
+ *
11
+ * 判定用**花括号深度**界定作用域(这才是 TDZ 的真实语义):
12
+ * 从声明处往上扫,遇到深度降到声明深度以下就停(说明已经出了这个块);
13
+ * 只对**深度恰好等于声明深度**的行报错 —— 更深的是内层块、更浅的是外层,
14
+ * 都不属于同一作用域。用缩进判定会误报(类的各个方法缩进相同)。
15
+ *
16
+ * 排除点号前缀:`st.secret` / `msg.host` 这类属性访问会被误判成变量引用
17
+ * (实测 3 处假阳性全是这一类)。
18
+ *
19
+ * 跑法:node scripts/check-tdz.mjs (挂在 npm run check 里)
20
+ */
21
+ import { readFileSync } from "node:fs";
22
+ import { fileURLToPath } from "node:url";
23
+ import { dirname, join } from "node:path";
24
+
25
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
26
+ const files = ["lib/index.js", "lib/discovery.js", "lib/conversation.js", "lib/identity.js"];
27
+ let problems = 0;
28
+
29
+ /** 逐行计算花括号深度(粗略:不解析字符串/模板串,够用) */
30
+ function depths(lines) {
31
+ const out = [];
32
+ let d = 0;
33
+ for (const line of lines) {
34
+ out.push(d);
35
+ const code = line.replace(/\/\/.*$/, "");
36
+ for (const ch of code) {
37
+ if (ch === "{") d += 1;
38
+ else if (ch === "}") d -= 1;
39
+ }
40
+ }
41
+ return out;
42
+ }
43
+
44
+ for (const rel of files) {
45
+ const lines = readFileSync(join(root, rel), "utf8").split("\n");
46
+ const depth = depths(lines);
47
+ const seen = new Set();
48
+
49
+ lines.forEach((l, i) => {
50
+ const m = /^(\s*)const ([A-Za-z_$][\w$]*) =/.exec(l);
51
+ if (!m) return;
52
+ const name = m[2];
53
+ const key = `${name}@${depth[i]}`;
54
+ if (seen.has(key)) return; // 同一作用域同名只查一次
55
+ seen.add(key);
56
+
57
+ const D = depth[i];
58
+ // 前面不能是 `.` —— `st.secret` / `msg.host` 这类属性访问不是变量引用
59
+ const re = new RegExp(`(?<![.\\w$])${name.replace(/\$/g, "\\$")}\\b`);
60
+ for (let j = i - 1; j >= 0; j -= 1) {
61
+ if (depth[j] < D) break; // 出了这个块
62
+ if (depth[j] > D) continue; // 内层块,不同作用域
63
+ const text = lines[j];
64
+ if (/^\s*(\/\/|\*|\/\*)/.test(text)) continue;
65
+ if (re.test(text)) {
66
+ console.error(`✗ ${rel}:${j + 1} 在声明前使用了 '${name}'(声明在 ${i + 1} 行,同属深度 ${D} 的块)`);
67
+ problems += 1;
68
+ break;
69
+ }
70
+ }
71
+ });
72
+ }
73
+
74
+ if (problems > 0) {
75
+ console.error(`\n发现 ${problems} 处 TDZ 风险:语法合法,但运行时必抛 ReferenceError。`);
76
+ process.exit(1);
77
+ }
78
+ console.log("✓ 无声明前使用(TDZ)");
@@ -0,0 +1,32 @@
1
+ /**
2
+ * 校验 lib/index.js 里的 VERSION 常量与 package.json 的 version 一致。
3
+ *
4
+ * 为什么单独做这一步:版本号写在两个地方,发版时很容易只改一个 —— 实测就漏过
5
+ * 一次(package.json 升到 0.3.0,插件自报还是 0.2.0),而 UI 和日志都用这个常量,
6
+ * 于是"装没装上"变得没法从界面上判断。
7
+ *
8
+ * 跑法:node scripts/check-version.mjs (已挂在 npm run check 里)
9
+ */
10
+ import { readFileSync } from "node:fs";
11
+ import { dirname, join } from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+
14
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
15
+ const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
16
+ const src = readFileSync(join(root, "lib/index.js"), "utf8");
17
+
18
+ const m = /^const VERSION = "([^"]+)";/m.exec(src);
19
+ if (!m) {
20
+ console.error("✗ lib/index.js 里找不到 `const VERSION = \"...\";`");
21
+ process.exit(1);
22
+ }
23
+
24
+ if (m[1] !== pkg.version) {
25
+ console.error(`✗ 版本号不一致:`);
26
+ console.error(` package.json : ${pkg.version}`);
27
+ console.error(` lib/index.js : ${m[1]}`);
28
+ console.error(` 两处必须相同,否则界面和日志会报错的版本号。`);
29
+ process.exit(1);
30
+ }
31
+
32
+ console.log(`✓ 版本号一致:${pkg.version}`);
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env python3
2
+ """把 PT_TLS 的 p_align 抬到 bionic 能接受的值(原地改写 ELF 文件)。
3
+
4
+ 为什么需要这一步(真机实测 2026-10,Android 5.10.43 aarch64):
5
+
6
+ error: "…/dsh-mesh-tsnet": executable's TLS segment is underaligned:
7
+ alignment is 8, needs to be at least 64 for ARM64 Bionic
8
+
9
+ Go 的**内部链接器**在产 PIE 时把 PT_TLS 的 p_align 硬编码成寄存器宽度:
10
+
11
+ cmd/link/internal/ld/elf.go: ph.Align = uint64(ctxt.Arch.RegSize) // arm64 上是 8
12
+
13
+ 而 ARM64 bionic 要求 ≥64(x86_64 bionic 要求 ≥16)。外部链接器(NDK 的 lld)
14
+ 会按符号对齐算这个值,所以 Go 自己不管 —— 用内部链接器就得自己补。
15
+
16
+ 安全性:ELF 的 TLS 块按 variant II 布局,**块尾贴着线程指针 TP,符号地址 =
17
+ TP - (tls_size - sym_offset)**。p_align 只影响块**起点**(更低地址)留多少填充,
18
+ 不改变任何符号相对块尾的偏移,所以把 8 改成 64 只是多留 48 字节填充,
19
+ Go 运行时算出来的 TLS 地址不变(真机上改完 p_align 进程即可正常加载运行)。
20
+
21
+ 用法:
22
+ scripts/fix-android-tls-align.py <elf-file> [更多文件…]
23
+ """
24
+ import struct
25
+ import sys
26
+
27
+ EM_X86_64 = 62
28
+ EM_AARCH64 = 183
29
+ PT_TLS = 7
30
+
31
+ # bionic 对主可执行文件 TLS 段对齐的最低要求(linker/linker.cpp)。
32
+ MIN_ALIGN = {
33
+ EM_AARCH64: 64,
34
+ EM_X86_64: 16,
35
+ }
36
+
37
+
38
+ def fix(path):
39
+ with open(path, "rb") as fh:
40
+ data = bytearray(fh.read())
41
+
42
+ if data[:4] != b"\x7fELF" or data[4] != 2:
43
+ sys.exit(f"{path}: 不是 64 位 ELF,拒绝改写")
44
+
45
+ e_machine = struct.unpack_from("<H", data, 18)[0]
46
+ e_phoff = struct.unpack_from("<Q", data, 32)[0]
47
+ e_phentsize = struct.unpack_from("<H", data, 54)[0]
48
+ e_phnum = struct.unpack_from("<H", data, 56)[0]
49
+
50
+ want = MIN_ALIGN.get(e_machine)
51
+ if want is None:
52
+ print(f" · {path}: e_machine={e_machine} 不在已知 bionic 目标里,跳过")
53
+ return
54
+
55
+ patched = []
56
+ for i in range(e_phnum):
57
+ off = e_phoff + i * e_phentsize
58
+ if struct.unpack_from("<I", data, off)[0] != PT_TLS:
59
+ continue
60
+ # Elf64_Phdr: p_type(4) p_flags(4) p_offset(8) p_vaddr(8) p_paddr(8)
61
+ # p_filesz(8) p_memsz(8) p_align(8) → p_align 在 +48
62
+ cur = struct.unpack_from("<Q", data, off + 48)[0]
63
+ if cur >= want:
64
+ patched.append(f"p_align={cur} 已达标")
65
+ continue
66
+ struct.pack_into("<Q", data, off + 48, want)
67
+ patched.append(f"p_align {cur} → {want}")
68
+
69
+ if not patched:
70
+ # 没有 TLS 段就没什么可修的:Go 只在有 TLS 符号时才发 PT_TLS。
71
+ print(f" · {path}: 没有 PT_TLS,跳过")
72
+ return
73
+
74
+ with open(path, "wb") as fh:
75
+ fh.write(data)
76
+ print(f" ✓ {path}: {'; '.join(patched)}")
77
+
78
+
79
+ def main():
80
+ if len(sys.argv) < 2:
81
+ sys.exit(__doc__.strip().splitlines()[-1].strip())
82
+ for path in sys.argv[1:]:
83
+ fix(path)
84
+
85
+
86
+ if __name__ == "__main__":
87
+ main()