From 6a9475e931cad80061db7703595740c798b29a31 Mon Sep 17 00:00:00 2001 From: Malte Ubl Date: Sun, 11 Oct 2026 07:05:29 -0700 Subject: [PATCH 1/2] Free the address space after process.exit off the critical path (--detached-exit) `scriptc build|run --detached-exit` opts an executable into handing the address-space teardown after process.exit to a helper process on Linux. The helper shares the address space (CLONE_VM), blocks signals, closes every descriptor but the read end of a pipe and waits for EOF on it. The kernel releases an exiting process's memory (exit_mm) before its files (exit_files), so EOF means the helper holds the last reference; it then exits and the kernel frees the pages there instead of before the parent sees the exit (30-40 ms per GB of 4 KiB pages; tsc-ts 20-110 ms). The same latency mold hides with --fork. It is a build-time choice, not a run-time knob, because the helper keeps the executable mapped (overwriting the binary right after it exits can fail with ETXTBSY) and the memory charged to the cgroup for up to ~100 ms, and the teardown CPU time leaves the parent's rusage. The program object defines `scr_detached_exit = 1`, overriding the runtime's weak default of 0, so no runtime flavor or linker flag is added. The option is part of the early executable cache and route keys; executables only, no effect on other platforms. --- docs/content/docs/cli.mdx | 3 ++ packages/cli/src/bootstrap.ts | 2 + packages/cli/test/output-options.test.ts | 2 + .../compiler/src/backend/llvm/emitter.test.ts | 10 ++++ packages/compiler/src/backend/llvm/emitter.ts | 10 ++++ packages/compiler/src/cli/command.ts | 9 +++- packages/compiler/src/cli/output-options.ts | 4 ++ packages/compiler/src/cli/usage.ts | 6 +++ packages/compiler/src/compile-types.ts | 5 ++ .../src/executable/executable-cache.test.ts | 1 + .../src/executable/executable-cache.ts | 4 ++ packages/compiler/src/index.ts | 15 ++++++ packages/compiler/src/native/prepare.ts | 1 + packages/compiler/test/source-output.test.ts | 13 +++++ packages/runtime/src/scr_lib.c | 53 +++++++++++++++++++ 15 files changed, 137 insertions(+), 1 deletion(-) diff --git a/docs/content/docs/cli.mdx b/docs/content/docs/cli.mdx index 169f838a44..f08ec558a9 100644 --- a/docs/content/docs/cli.mdx +++ b/docs/content/docs/cli.mdx @@ -108,6 +108,9 @@ Verifies and reads the installed precompiled runtime objects and vendor archives
--windows-subsystem <console|gui>
Select the subsystem of a Windows executable. console is the default; gui prevents Windows from opening a console window for the app. Valid only for executable builds targeting Windows.
+
--detached-exit
+
On Linux, when the program calls process.exit(), hand the release of its memory to a helper process so the parent sees the exit sooner. The kernel otherwise frees the whole address space before the exit is reported, which takes tens of milliseconds per gigabyte. Opt in only where the trade-offs are acceptable: for up to about 100 ms after the exit, the helper keeps the executable mapped (overwriting the binary in place fails with "text file busy"), its memory stays charged to the cgroup, and the teardown CPU time no longer appears in the parent's resource usage. Valid only for executable builds; it has no effect on other platforms.
+
--npm-static <pkg[,pkg…]|auto>
EXPERIMENTAL. Compile the named npm packages' shipped JS statically as program modules instead of embedding them for the engine (repeatable; auto opts in every eligible direct import). A package the preflight refuses falls back to the island with a coverage-report note. See npm Dependencies for maturity notes.
diff --git a/packages/cli/src/bootstrap.ts b/packages/cli/src/bootstrap.ts index 9bd04eed76..7aba1e6749 100644 --- a/packages/cli/src/bootstrap.ts +++ b/packages/cli/src/bootstrap.ts @@ -126,6 +126,7 @@ async function tryFastPath(): Promise { backend: "llvm", ...(optimization === "dev" || optimization === "speed" ? { optimization } : {}), ...(values.strip ? { strip: true as const } : {}), + ...(values["detached-exit"] ? { detachedExit: true as const } : {}), npmStatic, ffiProfile: ffiPath === null ? null : { path: ffiPath, bytes: ffiBytes! }, target: `${process.env["SCRIPTC_TARGET"] ?? "native"}:${buildPlatform}:${process.arch}:${ @@ -183,6 +184,7 @@ async function coverageFastPath( (failOn !== undefined && failOn !== "blockers" && failOn !== "divergences") || values.emit !== undefined || values.strip || + values["detached-exit"] || values.lib || values.profile !== undefined || values.ffi !== undefined || diff --git a/packages/cli/test/output-options.test.ts b/packages/cli/test/output-options.test.ts index 81d8343ef7..ead3280c06 100644 --- a/packages/cli/test/output-options.test.ts +++ b/packages/cli/test/output-options.test.ts @@ -46,6 +46,8 @@ describe("output option compatibility", () => { [{ emit: "llvm", windowsSubsystem: "gui" }, /windows-subsystem/], [{ emit: "obj", strip: true }, /strip/], [{ emit: "llvm", strip: true }, /strip/], + [{ emit: "obj", detachedExit: true }, /detached-exit/], + [{ emit: "llvm", detachedExit: true }, /detached-exit/], ] as const)("rejects %j", (override, message) => { const result = resolveOutputOptions("build", { ...BASE, ...override }); expect(result).toEqual({ ok: false, message: expect.stringMatching(message) }); diff --git a/packages/compiler/src/backend/llvm/emitter.test.ts b/packages/compiler/src/backend/llvm/emitter.test.ts index d78c74f713..d74552eb2c 100644 --- a/packages/compiler/src/backend/llvm/emitter.test.ts +++ b/packages/compiler/src/backend/llvm/emitter.test.ts @@ -109,6 +109,16 @@ test("throwing-call count does not multiply identical scope cleanup", () => { } }); +test("detached exit defines the runtime opt-in symbol only when requested", () => { + const module = moduleFor([call()]); + const plain = emitLlvmModule(module); + expect(emitLlvmModule(module, { detachedExit: false })).toBe(plain); + expect(plain).not.toContain("@scr_detached_exit"); + const detached = emitLlvmModule(module, { detachedExit: true }); + expect(detached.match(/^@scr_detached_exit = constant i8 1$/gm)).toHaveLength(1); + expect(detached.replace("@scr_detached_exit = constant i8 1\n", "")).toBe(plain); +}); + test("inline RC is a speed-only emission mode and leaves release IR unchanged", () => { for (const boxed of [false, true]) { const module = moduleFor(Array.from({ length: 4 }, call), { boxed }); diff --git a/packages/compiler/src/backend/llvm/emitter.ts b/packages/compiler/src/backend/llvm/emitter.ts index e7ae6a9345..84005a48c4 100644 --- a/packages/compiler/src/backend/llvm/emitter.ts +++ b/packages/compiler/src/backend/llvm/emitter.ts @@ -397,6 +397,10 @@ export interface LlvmTargetOptions { /** Emit retain/release fast paths inline (the `speed` posture). Off, every * retain and release is a runtime call. */ inlineRc?: boolean; + /** Define `scr_detached_exit` so the Linux runtime hands the address-space + * teardown after `process.exit` to a helper process (`--detached-exit`). + * Executables only; the runtime's weak default keeps it off. */ + detachedExit?: boolean; } export function emitLlvmModule(mod: IrModule, options: LlvmTargetOptions = {}): string { @@ -520,6 +524,7 @@ export class LlEmitter { private readonly executableTls: boolean; private readonly emitLibraryIdentity: boolean; private readonly runtimeAbiMarker: boolean; + private readonly detachedExit: boolean; /** Interned string literals: UTF-8 text → { symbol, byte length } — * first-use order, the runtime ABI’s determinism discipline. */ private readonly literals = new Map(); @@ -814,6 +819,7 @@ export class LlEmitter { !/apple|darwin|windows|mingw|cygwin|win32/.test(options.targetTriple || process.platform); this.emitLibraryIdentity = options.emitLibraryIdentity !== false; this.runtimeAbiMarker = options.runtimeAbiMarker === true; + this.detachedExit = options.detachedExit === true; this.rcHelpers = options.inlineRc === true ? new Set() : null; // ScrCycHdr.color stays 12 bytes behind a wasm32 object and 16 bytes // behind a 64-bit object. The wasm32 header pads before color so its @@ -1900,6 +1906,10 @@ export class LlEmitter { ...(this.runtimeAbiMarker && this.mod.lib === undefined ? [`declare void @${RUNTIME_ABI_MARKER}()`] : []), + // Overrides the runtime's weak default (scr_lib.c). + ...(this.detachedExit && this.mod.lib === undefined + ? [`@scr_detached_exit = constant i8 1`] + : []), ); for (const d of this.decls) out.push(d); out.push(``); diff --git a/packages/compiler/src/cli/command.ts b/packages/compiler/src/cli/command.ts index 1eea9b32e3..8dd8a9f28a 100644 --- a/packages/compiler/src/cli/command.ts +++ b/packages/compiler/src/cli/command.ts @@ -86,6 +86,7 @@ async function main(args: string[], host: CliHost): Promise { values.profile !== undefined || values.strip || values["windows-subsystem"] !== undefined || + values["detached-exit"] || (values["npm-static"] ?? []).length > 0 || values["provenance-sources"] || externalTypeArgs.length > 0 || @@ -151,11 +152,12 @@ async function main(args: string[], host: CliHost): Promise { values.strip || values.ffi !== undefined || values["windows-subsystem"] !== undefined || + values["detached-exit"] || (values["npm-static"] ?? []).length > 0 || externalTypeArgs.length > 0 ) { fail( - "scriptc build --lib takes no --dynamic/--backend/--emit/--print/--optimization/--strip/--windows-subsystem/--npm-static/--ffi/--external-types: the profile pins the emission and optimization, npm imports are judged automatically, outbound FFI belongs to executable builds, and external type mappings belong to coverage", + "scriptc build --lib takes no --dynamic/--backend/--emit/--print/--optimization/--strip/--windows-subsystem/--detached-exit/--npm-static/--ffi/--external-types: the profile pins the emission and optimization, npm imports are judged automatically, outbound FFI belongs to executable builds, and external type mappings belong to coverage", ); } const profilePath = resolve(profileArg); @@ -198,6 +200,9 @@ async function main(args: string[], host: CliHost): Promise { if (command === "coverage" && values.strip) { fail(`--strip is a build/run option\n\n${USAGE}`); } + if (command === "coverage" && values["detached-exit"]) { + fail(`--detached-exit is a build/run option\n\n${USAGE}`); + } if ( values.print !== undefined && values.print !== "native-link-info" && @@ -292,6 +297,7 @@ async function main(args: string[], host: CliHost): Promise { sanitize: values.sanitize, ...(values.optimization === undefined ? {} : { optimization: values.optimization }), strip: values.strip, + detachedExit: values["detached-exit"], ...(windowsSubsystem === undefined ? {} : { windowsSubsystem }), ...(values.ffi === undefined ? {} : { ffi: values.ffi }), }); @@ -380,6 +386,7 @@ async function main(args: string[], host: CliHost): Promise { ...(optimization !== undefined ? { optimization } : {}), ...(values.strip ? { strip: true } : {}), ...(windowsSubsystem !== undefined ? { windowsSubsystem } : {}), + ...(values["detached-exit"] ? { detachedExit: true } : {}), ...(npmStatic !== undefined ? { npmStatic } : {}), ...(ffiProfilePath !== undefined ? { ffiProfilePath } : {}), ...(printNativeLinkInfo ? { nativeLinkInfo: true } : {}), diff --git a/packages/compiler/src/cli/output-options.ts b/packages/compiler/src/cli/output-options.ts index 85513abde1..9387775265 100644 --- a/packages/compiler/src/cli/output-options.ts +++ b/packages/compiler/src/cli/output-options.ts @@ -10,6 +10,7 @@ export interface OutputOptionValues { optimization?: string; strip?: boolean; windowsSubsystem?: string; + detachedExit?: boolean; ffi?: string; } @@ -69,6 +70,9 @@ export function resolveOutputOptions( if (values.strip && emit !== "exe") { return { ok: false, message: `--strip is only supported with --emit=exe` }; } + if (values.detachedExit && emit !== "exe") { + return { ok: false, message: `--detached-exit is only supported with --emit=exe` }; + } if (emit === "ir" && backend !== undefined) { return { ok: false, diff --git a/packages/compiler/src/cli/usage.ts b/packages/compiler/src/cli/usage.ts index b707f2fdb3..0a24477f2f 100644 --- a/packages/compiler/src/cli/usage.ts +++ b/packages/compiler/src/cli/usage.ts @@ -42,6 +42,11 @@ Options: --windows-subsystem Windows executable subsystem (default: console). gui prevents Windows from opening a console window + --detached-exit + Linux: after process.exit, free the program's memory in + a helper process so the parent sees the exit sooner. The + helper keeps the executable mapped and its memory charged + for up to ~100 ms after exit (opt in; --emit=exe only) --keep-llvm keep generated LLVM IR beside the executable (default) --no-keep-llvm delete generated LLVM IR after compiling --emit-ir also write IR beside an executable or library archive; @@ -81,6 +86,7 @@ export const CLI_OPTIONS = { optimization: { type: "string" }, strip: { type: "boolean", default: false }, "windows-subsystem": { type: "string" }, + "detached-exit": { type: "boolean", default: false }, "keep-llvm": { type: "boolean", default: true }, "emit-ir": { type: "boolean", default: false }, sanitize: { type: "boolean", default: false }, diff --git a/packages/compiler/src/compile-types.ts b/packages/compiler/src/compile-types.ts index d48b551f64..db0d57966f 100644 --- a/packages/compiler/src/compile-types.ts +++ b/packages/compiler/src/compile-types.ts @@ -34,6 +34,11 @@ export interface CompileBaseOptions { /** Windows PE executable subsystem. Console is the default; GUI suppresses * automatic console-window creation. Only valid for Windows executables. */ windowsSubsystem?: WindowsSubsystem; + /** On Linux, hand the address-space teardown after `process.exit` to a + * helper process so the parent sees the exit sooner. The helper keeps the + * executable mapped and the memory charged for up to ~100 ms after exit. + * Executables only; no effect on other platforms. */ + detachedExit?: boolean; /** --npm-static: package names whose shipped, unminified JS compiles * STATICALLY as program modules (inference types the bodies; statements * the lowering cannot prove become runtime fences). "auto" opts in every diff --git a/packages/compiler/src/executable/executable-cache.test.ts b/packages/compiler/src/executable/executable-cache.test.ts index 6b4ca73ae0..a287a7c5a7 100644 --- a/packages/compiler/src/executable/executable-cache.test.ts +++ b/packages/compiler/src/executable/executable-cache.test.ts @@ -217,6 +217,7 @@ test("early executable keys isolate compile modes, paths, implementation, and FF { ...f.options, dynamic: true }, { ...f.options, optimization: "dev" }, { ...f.options, optimization: "speed" }, + { ...f.options, detachedExit: true }, { ...f.options, npmStatic: "auto" }, { ...f.options, npmStatic: ["commander"] }, { ...f.options, outPath: join(f.options.outDir, "other") }, diff --git a/packages/compiler/src/executable/executable-cache.ts b/packages/compiler/src/executable/executable-cache.ts index 876904a259..9542e6fa53 100644 --- a/packages/compiler/src/executable/executable-cache.ts +++ b/packages/compiler/src/executable/executable-cache.ts @@ -110,6 +110,8 @@ export interface EarlyExecutableCacheOptions { strip?: true; /** Omitted for the default Windows console subsystem. */ windowsSubsystem?: "gui"; + /** Omitted unless --detached-exit is set. */ + detachedExit?: true; npmStatic: readonly string[] | "auto" | null; /** Raw manifest identity: path and bytes. Native archives remain under the * stricter native cache's independent dependency validation. */ @@ -220,6 +222,7 @@ function cacheKey(options: EarlyExecutableCacheOptions): string { ...optimizationKeyParts(options.optimization), ...(options.strip ? ["strip"] : []), ...(options.windowsSubsystem === "gui" ? ["windows-subsystem-gui"] : []), + ...(options.detachedExit ? ["detached-exit"] : []), options.npmStatic === null ? "" : options.npmStatic === "auto" @@ -258,6 +261,7 @@ function routeKey(options: Omit { + const { entry, outDir } = await fixture(); + const outPath = join(outDir, "main.ll"); + const result = await compile(entry, { outDir, outPath, outputKind: "llvm", detachedExit: true }); + expect(result).toMatchObject({ + ok: false, + diagnostics: [ + { code: "SC3002", message: expect.stringContaining("only supported for executable output") }, + ], + }); + await expect(readFile(outPath)).rejects.toMatchObject({ code: "ENOENT" }); +}); + test("LLVM is the exact primary artifact and never creates an executable", async () => { const { entry, outDir } = await fixture(); const llvmPath = join(outDir, "exact.llvm-output"); diff --git a/packages/runtime/src/scr_lib.c b/packages/runtime/src/scr_lib.c index e259f6f7e1..80558c1ecf 100644 --- a/packages/runtime/src/scr_lib.c +++ b/packages/runtime/src/scr_lib.c @@ -1806,6 +1806,56 @@ double scr_process_exit_code_or_zero(void) { return (double)scr_exit_code_hint_get(); } +#if defined(__linux__) +#include +#include +#include +#ifndef SYS_close_range +#define SYS_close_range 436 /* the generic syscall table: x86_64 and aarch64 */ +#endif + +/* Detached teardown (`scriptc build --detached-exit`): the kernel frees an + * exiting process's memory on its critical path, 30-40 ms per GB of 4 KiB + * pages, before its parent sees it exit. A helper process that shares the + * address space (CLONE_VM) and holds no descriptor but the read end of a + * pipe keeps the memory alive past the exit, then exits itself and frees it + * off the parent's critical path (the latency mold's --fork hides). The + * kernel releases an exiting process's memory (exit_mm) before its files + * (exit_files), so EOF on the pipe means the helper holds the last + * reference. The helper keeps the executable mapped and the memory charged + * to the cgroup until then, so a program opts in at build time: the program + * object then defines scr_detached_exit = 1, overriding this weak default. */ +__attribute__((weak)) const unsigned char scr_detached_exit = 0; +static char scr_teardown_stack[16384] __attribute__((aligned(64))); + +static int scr_teardown_main(void *arg) { + int fd = (int)(intptr_t)arg; + /* Raw syscalls only: the helper runs on the exiting thread's TLS. */ + if (fd > 0) (void)syscall(SYS_close_range, 0u, (unsigned)fd - 1u, 0u); + (void)syscall(SYS_close_range, (unsigned)fd + 1u, ~0u, 0u); + char c; + while (syscall(SYS_read, fd, &c, 1) != 0) { + } + syscall(SYS_exit, 0); + return 0; +} + +static void scr_detach_teardown(void) { + if (!scr_detached_exit) return; + int fds[2]; + if (pipe2(fds, O_CLOEXEC) != 0) return; + sigset_t all, old; + sigfillset(&all); + pthread_sigmask(SIG_SETMASK, &all, &old); + pid_t pid = clone(scr_teardown_main, scr_teardown_stack + sizeof scr_teardown_stack, CLONE_VM | SIGCHLD, + (void *)(intptr_t)fds[0]); + pthread_sigmask(SIG_SETMASK, &old, NULL); + (void)close(fds[0]); + if (pid < 0) (void)close(fds[1]); + /* fds[1] stays open until the process's files are released. */ +} +#endif + void scr_process_exit(double code) { /* Node runs 'exit' listeners on explicit process.exit() too — they run * HERE, synchronously, before the teardown-free exit below. The hook is @@ -1823,6 +1873,9 @@ void scr_process_exit(double code) { * Node), and the RC audit is meaningless mid-program (live values are * expected). scr_init's flush-at-exit is also skipped — flush here. */ fflush(stdout); +#if defined(__linux__) + scr_detach_teardown(); +#endif _Exit((int)code); } From 3e83a7b38c613a66e527333a579f31a3f168bfe4 Mon Sep 17 00:00:00 2001 From: Malte Ubl Date: Sun, 11 Oct 2026 08:13:26 -0700 Subject: [PATCH 2/2] Declare scr_detached_exit in scr_runtime.h The emitter defines @scr_detached_exit for --detached-exit executables, and the runtime ABI test requires every scr_* symbol the backend can emit to have a prototype or extern data declaration in the header. --- packages/runtime/src/scr_runtime.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/runtime/src/scr_runtime.h b/packages/runtime/src/scr_runtime.h index 363f892452..426b0d5370 100644 --- a/packages/runtime/src/scr_runtime.h +++ b/packages/runtime/src/scr_runtime.h @@ -3128,6 +3128,10 @@ bool scr_process_kill_named(double pid, const ScrStr *signal); /* fflush stdout, then _Exit((int)code): no atexit handlers run — the RC * audit is deliberately skipped (exiting mid-program leaves live values). */ void scr_process_exit(double code); +/* Nonzero hands the address-space teardown after scr_process_exit to a + * helper process (Linux, `--detached-exit`). scr_lib.c defines a weak 0; + * the program object of such an executable defines it as 1. */ +extern const unsigned char scr_detached_exit; void scr_process_set_exit_code(double code); double scr_process_exit_code_or_zero(void); /* process._exiting: true once the exit sequence began (process.exit or