Open History to see the last commit
1#!/usr/bin/env node
2
3import { createHash } from "node:crypto";
4import { execFileSync } from "node:child_process";
5import { existsSync, readFileSync, writeFileSync } from "node:fs";
6import { createRequire } from "node:module";
7import path from "node:path";
8import { fileURLToPath } from "node:url";
9
10const VERSION_NAMESPACES = ["GLIBC", "GLIBCXX", "CXXABI"];
11
12export function compareNumericVersion(left, right) {
13 const a = String(left)
14 .split(".")
15 .map((part) => Number.parseInt(part, 10));
16 const b = String(right)
17 .split(".")
18 .map((part) => Number.parseInt(part, 10));
19 const length = Math.max(a.length, b.length);
20 for (let index = 0; index < length; index += 1) {
21 const av = a[index] ?? 0;
22 const bv = b[index] ?? 0;
23 if (av !== bv) return av < bv ? -1 : 1;
24 }
25 return 0;
26}
27
28export function maxNumericVersion(versions) {
29 if (versions.length === 0) return "none";
30 return [...versions].sort(compareNumericVersion).at(-1);
31}
32
33export function parseRequiredSymbolVersions(readelfVersionInfo) {
34 const marker = "Version needs section";
35 const start = readelfVersionInfo.indexOf(marker);
36 const needsText = start >= 0 ? readelfVersionInfo.slice(start) : "";
37 const result = Object.fromEntries(VERSION_NAMESPACES.map((namespace) => [namespace, []]));
38 const pattern = /\b(GLIBCXX|GLIBC|CXXABI)_([0-9]+(?:\.[0-9]+)*)\b/g;
39 for (const match of needsText.matchAll(pattern)) {
40 result[match[1]].push(match[2]);
41 }
42 for (const namespace of VERSION_NAMESPACES) {
43 result[namespace] = [...new Set(result[namespace])].sort(compareNumericVersion);
44 }
45 return result;
46}
47
48export function parseProvidedSymbolVersions(readelfVersionInfo) {
49 const result = Object.fromEntries(VERSION_NAMESPACES.map((namespace) => [namespace, []]));
50 const pattern = /\b(GLIBCXX|GLIBC|CXXABI)_([0-9]+(?:\.[0-9]+)*)\b/g;
51 for (const match of readelfVersionInfo.matchAll(pattern)) {
52 result[match[1]].push(match[2]);
53 }
54 for (const namespace of VERSION_NAMESPACES) {
55 result[namespace] = [...new Set(result[namespace])].sort(compareNumericVersion);
56 }
57 return result;
58}
59
60export function parseNeededLibraries(readelfDynamic) {
61 return [...readelfDynamic.matchAll(/Shared library: \[([^\]]+)\]/g)].map((match) => match[1]);
62}
63
64export function parseElfHeader(readelfHeader) {
65 const classMatch = readelfHeader.match(/^\s*Class:\s*(.+)$/m);
66 const machineMatch = readelfHeader.match(/^\s*Machine:\s*(.+)$/m);
67 return {
68 elfClass: classMatch?.[1]?.trim() ?? "unknown",
69 machine: machineMatch?.[1]?.trim() ?? "unknown",
70 };
71}
72
73export function assertVersionWithinLimit(namespace, required, limit, artifactName) {
74 if (required === "none") return;
75 if (compareNumericVersion(required, limit) > 0) {
76 throw new Error(
77 `${artifactName} requires ${namespace}_${required}, exceeding the declared WSL baseline ceiling ${namespace}_${limit}.`,
78 );
79 }
80}
81
82function run(command, args) {
83 try {
84 return execFileSync(command, args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
85 } catch (error) {
86 const stdout = error?.stdout?.toString?.() ?? "";
87 const stderr = error?.stderr?.toString?.() ?? "";
88 throw new Error(`Command failed: ${command} ${args.join(" ")}\n${stdout}${stderr}`.trim(), {
89 cause: error,
90 });
91 }
92}
93
94function sha256File(filePath) {
95 return createHash("sha256").update(readFileSync(filePath)).digest("hex");
96}
97
98function resolveWslNativeArtifacts(serverRoot, arch, nodePtyPath, nodeRuntimePath) {
99 const serverRequire = createRequire(path.join(path.resolve(serverRoot), "package.json"));
100 const fffNodeEntry = serverRequire.resolve("@ff-labs/fff-node");
101 const fffRequire = createRequire(fffNodeEntry);
102 const fffPath = fffRequire.resolve(`@ff-labs/fff-bin-linux-${arch}-gnu`);
103 const ffiEntry = fffRequire.resolve("ffi-rs");
104 const ffiRequire = createRequire(ffiEntry);
105 const ffiPath = ffiRequire.resolve(`@yuuang/ffi-rs-linux-${arch}-gnu`);
106 return [
107 { name: "node-runtime", path: path.resolve(nodeRuntimePath) },
108 { name: "node-pty", path: path.resolve(nodePtyPath) },
109 { name: "fff", path: fffPath },
110 { name: "ffi-rs", path: ffiPath },
111 ];
112}
113
114function expectedMachineForArch(arch) {
115 if (arch === "x64") return /X86-64|Advanced Micro Devices X86-64/i;
116 if (arch === "arm64") return /AArch64/i;
117 throw new Error(`Unsupported WSL ABI architecture: ${arch}`);
118}
119
120function auditArtifact(artifact, { arch, limits }) {
121 if (!existsSync(artifact.path)) {
122 throw new Error(`WSL native artifact not found: ${artifact.name} (${artifact.path})`);
123 }
124
125 const headerText = run("readelf", ["-h", artifact.path]);
126 const dynamicText = run("readelf", ["-d", artifact.path]);
127 const versionText = run("readelf", ["--version-info", artifact.path]);
128 const neededLibraries = parseNeededLibraries(dynamicText);
129 // `ldd` returns non-zero for a valid fully-static ELF. Only invoke it when
130 // DT_NEEDED entries exist; static native helpers are compatible by
131 // construction with respect to runtime shared-library resolution.
132 const lddText = neededLibraries.length > 0 ? run("ldd", [artifact.path]) : "";
133 const header = parseElfHeader(headerText);
134 const expectedMachine = expectedMachineForArch(arch);
135 if (header.elfClass !== "ELF64") {
136 throw new Error(`${artifact.name} must be ELF64 for WSL ${arch}; found ${header.elfClass}.`);
137 }
138 if (!expectedMachine.test(header.machine)) {
139 throw new Error(`${artifact.name} has the wrong ELF machine for WSL ${arch}: ${header.machine}.`);
140 }
141 if (/\bnot found\b/i.test(lddText)) {
142 throw new Error(`${artifact.name} has unresolved dynamic dependencies:\n${lddText}`);
143 }
144
145 const required = parseRequiredSymbolVersions(versionText);
146 const maxRequired = {
147 GLIBC: maxNumericVersion(required.GLIBC),
148 GLIBCXX: maxNumericVersion(required.GLIBCXX),
149 CXXABI: maxNumericVersion(required.CXXABI),
150 };
151
152 assertVersionWithinLimit("GLIBC", maxRequired.GLIBC, limits.GLIBC, artifact.name);
153 assertVersionWithinLimit("GLIBCXX", maxRequired.GLIBCXX, limits.GLIBCXX, artifact.name);
154 assertVersionWithinLimit("CXXABI", maxRequired.CXXABI, limits.CXXABI, artifact.name);
155
156 return {
157 name: artifact.name,
158 path: path.basename(artifact.path),
159 sha256: sha256File(artifact.path),
160 elfClass: header.elfClass,
161 machine: header.machine,
162 neededLibraries,
163 requiredVersions: required,
164 maxRequired,
165 };
166}
167
168function parseArgs(argv) {
169 const options = { artifacts: [] };
170 for (let index = 0; index < argv.length; index += 1) {
171 const arg = argv[index];
172 const value = argv[index + 1];
173 if (arg === "--baseline") options.baseline = value;
174 else if (arg === "--arch") options.arch = value;
175 else if (arg === "--max-glibc") options.maxGlibc = value;
176 else if (arg === "--libstdcxx") options.libstdcxx = value;
177 else if (arg === "--server-root") options.serverRoot = value;
178 else if (arg === "--node-pty") options.nodePty = value;
179 else if (arg === "--node-runtime") options.nodeRuntime = value;
180 else if (arg === "--output") options.output = value;
181 else throw new Error(`Unknown argument: ${arg}`);
182 index += 1;
183 }
184 for (const key of ["baseline", "arch", "maxGlibc", "libstdcxx", "serverRoot", "nodePty", "nodeRuntime", "output"]) {
185 if (!options[key]) throw new Error(`Missing required argument --${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`);
186 }
187 return options;
188}
189
190export function buildAbiReport(options) {
191 const libstdcxxVersionText = run("readelf", ["--version-info", path.resolve(options.libstdcxx)]);
192 const provided = parseProvidedSymbolVersions(libstdcxxVersionText);
193 const limits = {
194 GLIBC: options.maxGlibc,
195 GLIBCXX: maxNumericVersion(provided.GLIBCXX),
196 CXXABI: maxNumericVersion(provided.CXXABI),
197 };
198 if (limits.GLIBCXX === "none" || limits.CXXABI === "none") {
199 throw new Error(`Could not derive GLIBCXX/CXXABI ceilings from ${options.libstdcxx}.`);
200 }
201
202 const glibcRuntime = run("getconf", ["GNU_LIBC_VERSION"]).trim();
203 const glibcMatch = glibcRuntime.match(/glibc\s+([0-9]+(?:\.[0-9]+)+)/i);
204 if (!glibcMatch) throw new Error(`Could not parse baseline glibc version from: ${glibcRuntime}`);
205 if (compareNumericVersion(glibcMatch[1], options.maxGlibc) > 0) {
206 throw new Error(
207 `ABI audit host glibc ${glibcMatch[1]} is newer than declared WSL baseline ${options.maxGlibc}; run this audit on the compatibility-floor image.`,
208 );
209 }
210
211 const nodeRuntimeVersion = run(path.resolve(options.nodeRuntime), ["-p", "process.versions.node"]).trim();
212 if (!/^\d+(?:\.\d+){2}(?:[-+].+)?$/.test(nodeRuntimeVersion)) {
213 throw new Error(`Could not read bundled Node runtime version from ${options.nodeRuntime}: ${nodeRuntimeVersion}`);
214 }
215
216 const artifacts = resolveWslNativeArtifacts(
217 options.serverRoot,
218 options.arch,
219 options.nodePty,
220 options.nodeRuntime,
221 ).map((artifact) => auditArtifact(artifact, { arch: options.arch, limits }));
222
223 return {
224 schemaVersion: 2,
225 nodeRuntime: {
226 version: nodeRuntimeVersion,
227 },
228 baseline: {
229 id: options.baseline,
230 arch: options.arch,
231 glibcRuntime: glibcMatch[1],
232 limits: {
233 glibc: limits.GLIBC,
234 glibcxx: limits.GLIBCXX,
235 cxxabi: limits.CXXABI,
236 },
237 libstdcxx: path.basename(path.resolve(options.libstdcxx)),
238 },
239 artifacts,
240 };
241}
242
243function main() {
244 const options = parseArgs(process.argv.slice(2));
245 const report = buildAbiReport(options);
246 writeFileSync(path.resolve(options.output), `${JSON.stringify(report, null, 2)}\n`);
247 console.log(
248 `[wsl-abi] PASS ${report.baseline.id}/${report.baseline.arch}: GLIBC<=${report.baseline.limits.glibc}, GLIBCXX<=${report.baseline.limits.glibcxx}, CXXABI<=${report.baseline.limits.cxxabi}`,
249 );
250 for (const artifact of report.artifacts) {
251 console.log(
252 `[wsl-abi] ${artifact.name}: ${artifact.machine}; max GLIBC=${artifact.maxRequired.GLIBC}, GLIBCXX=${artifact.maxRequired.GLIBCXX}, CXXABI=${artifact.maxRequired.CXXABI}; sha256=${artifact.sha256}`,
253 );
254 }
255}
256
257if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
258 main();
259}