Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

linux-arm64-sea.ts

127 lines4.8 KB

1// TEMPORARY one-time workaround for a Node --build-sea bug on Linux arm64.
2// It breaks kernels with 16 KiB or 64 KiB pages. Revert when Node ships a fix.
3// Node issue: https://github.com/nodejs/node/issues/67048
4// Workaround PR: https://github.com/pingdotgg/t3code/pull/25825
5import * as NodeModule from "node:module";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Path from "effect/Path";
9import * as Schema from "effect/Schema";
10import { ChildProcess, ChildProcessSpawner } from "effect/process";
11​
12import { cliAssets } from "./cli-assets.ts";
13​
14class LinuxArm64SeaError extends Schema.TaggedError<LinuxArm64SeaError>()("LinuxArm64SeaError", {
15 message: Schema.String,
16}) {}
17​
18const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
19​
20const run = Effect.fn("LinuxArm64Sea.run")(function* (args: Array<string>, verbose: boolean) {
21 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
22 const child = yield* spawner.spawn(
23 ChildProcess.make(process.execPath, args, {
24 stdout: verbose ? "inherit" : "ignore",
25 stderr: "inherit",
26 }),
27 );
28 const exitCode = yield* child.exitCode;
29 if (exitCode !== 0) {
30 return yield* new LinuxArm64SeaError({ message: `${args[0]} exited with code ${exitCode}.` });
31 }
32});
33​
34// Builds the SEA blob with this Node and injects it into a copy of this Node with postject.
35export const injectLinuxArm64Sea = Effect.fn("LinuxArm64Sea.inject")(function* (input: {
36 bundlePath: string;
37 cliAssetDir: string;
38 outputPath: string;
39 nodeVersion: string;
40 verbose: boolean;
41}) {
42 // The copied execPath is the shipped runtime; vp pack only checks its own Node.
43 if (process.versions.node !== input.nodeVersion) {
44 return yield* new LinuxArm64SeaError({
45 message: `Linux ARM64 executables must be built with Node ${input.nodeVersion}; running ${process.versions.node}.`,
46 });
47 }
48 const fs = yield* FileSystem.FileSystem;
49 const path = yield* Path.Path;
50 const temp = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sea-" });
51 const blobPath = path.join(temp, "sea.blob");
52 const configPath = path.join(temp, "sea.json");
53 yield* fs.writeFileString(
54 configPath,
55 yield* encodeJson({
56 main: input.bundlePath,
57 assets: cliAssets(input.cliAssetDir),
58 output: blobPath,
59 mainFormat: "module",
60 disableExperimentalSEAWarning: true,
61 // Node SEA useCodeCache breaks import(), which the server needs.
62 useCodeCache: false,
63 // The bootstrap loads the embedded CLI with require(esm).
64 execArgv: ["--require-module"],
65 }),
66 );
67 yield* run(["--experimental-sea-config", configPath], input.verbose);
68 yield* fs.copyFile(process.execPath, input.outputPath);
69 yield* fs.chmod(input.outputPath, 0o755);
70 const require = NodeModule.createRequire(import.meta.url);
71 yield* run(
72 [
73 require.resolve("postject/dist/cli.js"),
74 input.outputPath,
75 "NODE_SEA_BLOB",
76 blobPath,
77 "--sentinel-fuse",
78 "NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2",
79 ],
80 input.verbose,
81 );
82}, Effect.scoped);
83​
84// Kernels map LOAD segments in whole pages. Checking at 64 KiB covers 4, 16, and 64 KiB kernels.
85export function assertLinuxArm64PageCompatibility(bytes: Uint8Array) {
86 const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
87 if (
88 bytes.length < 64 ||
89 view.getUint32(0, false) !== 0x7f454c46 ||
90 bytes[4] !== 2 ||
91 bytes[5] !== 1 ||
92 view.getUint16(18, true) !== 183
93 ) {
94 throw new Error("Expected a little-endian ELF64 ARM64 executable.");
95 }
96 const tableOffset = Number(view.getBigUint64(32, true));
97 const entrySize = view.getUint16(54, true);
98 const count = view.getUint16(56, true);
99 if (
100 !Number.isSafeInteger(tableOffset) ||
101 entrySize < 56 ||
102 count === 0 ||
103 tableOffset + entrySize * count > bytes.length
104 ) {
105 throw new Error("Invalid ELF program header table.");
106 }
107 const pageSize = 0x10000n;
108 const ranges: Array<{ start: bigint; end: bigint }> = [];
109 for (let index = 0; index < count; index++) {
110 const header = tableOffset + index * entrySize;
111 if (view.getUint32(header, true) !== 1) continue;
112 const offset = view.getBigUint64(header + 8, true);
113 const address = view.getBigUint64(header + 16, true);
114 const size = view.getBigUint64(header + 40, true);
115 if (offset % pageSize !== address % pageSize) {
116 throw new Error(`ARM64 LOAD segment ${index} is incompatible with 64 KiB pages.`);
117 }
118 if (size === 0n) continue;
119 const start = address / pageSize;
120 const end = (address + size + pageSize - 1n) / pageSize;
121 if (ranges.some((range) => start < range.end && range.start < end)) {
122 throw new Error(`ARM64 LOAD segments overlap on a 64 KiB page (segment ${index}).`);
123 }
124 ranges.push({ start, end });
125 }
126 if (ranges.length === 0) throw new Error("ELF executable has no LOAD segments.");