-
Notifications
You must be signed in to change notification settings - Fork 5k
build(linux-musl): statically link Bun's C++ runtime #38152
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
vladislav-miroshnikov
wants to merge
2
commits into
oven-sh:main
Choose a base branch
from
vladislav-miroshnikov:vmiroshnikov/static-musl-runtime-successor
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
42 changes: 42 additions & 0 deletions
42
test/internal/source-lints/musl-static-cxx-runtime.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| import { expect, test } from "bun:test"; | ||
| import type { Config } from "../../../scripts/build/config.ts"; | ||
| import { computeFlags } from "../../../scripts/build/flags.ts"; | ||
|
|
||
| const config = (arm64: boolean) => | ||
| ({ | ||
| os: "linux", | ||
| arch: arm64 ? "aarch64" : "x64", | ||
| linux: true, | ||
| unix: true, | ||
| darwin: false, | ||
| windows: false, | ||
| freebsd: false, | ||
| abi: "musl", | ||
| x64: !arm64, | ||
| arm64, | ||
| release: true, | ||
| debug: false, | ||
| asan: false, | ||
| valgrind: false, | ||
| fuzzilli: false, | ||
| lto: false, | ||
| canary: true, | ||
| ci: true, | ||
| buildkite: false, | ||
| cwd: "/repo", | ||
| buildDir: "/repo/build/release", | ||
| ld: "/usr/bin/ld.lld", | ||
| crossTarget: undefined, | ||
| }) as Config; | ||
|
|
||
| test.each([ | ||
| ["x64", false], | ||
| ["aarch64", true], | ||
| ] as const)("linux-musl-%s embeds the C++ runtime", (_, arm64) => { | ||
| const flags = computeFlags(config(arm64)).ldflags; | ||
|
coderabbitai[bot] marked this conversation as resolved.
Outdated
|
||
|
|
||
| expect(flags).toContain("-static-libstdc++"); | ||
| expect(flags).toContain("-static-libgcc"); | ||
| expect(flags).not.toContain("-lstdc++"); | ||
| expect(flags).not.toContain("-lgcc"); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| #include "node_api.h" | ||
|
|
||
| struct ValidationException { | ||
| int value; | ||
| }; | ||
|
|
||
| static volatile int validation_seed = 41; | ||
|
|
||
| static int throw_and_catch() { | ||
| try { | ||
| throw ValidationException{validation_seed}; | ||
| } catch (const ValidationException &exception) { | ||
| return exception.value + 1; | ||
| } | ||
| } | ||
|
|
||
| NAPI_MODULE_INIT() { | ||
| napi_value caught; | ||
| if (napi_create_int32(env, throw_and_catch(), &caught) != napi_ok) | ||
| return nullptr; | ||
| if (napi_set_named_property(env, exports, "caught", caught) != napi_ok) | ||
| return nullptr; | ||
| return exports; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| #include "node_api.h" | ||
|
|
||
| /* | ||
| * Model a legacy native addon which expects the host process to provide the | ||
| * C++ runtime. The final link intentionally omits libstdc++, leaving these | ||
| * relocations for process.dlopen() to resolve from the global loader scope. | ||
| */ | ||
| extern void *cxx_operator_new(size_t size) __asm__("_Znwm"); | ||
| extern void cxx_operator_delete(void *ptr) __asm__("_ZdlPv"); | ||
|
|
||
| static void *(*volatile cxx_operator_new_ptr)(size_t) = cxx_operator_new; | ||
| static void (*volatile cxx_operator_delete_ptr)(void *) = cxx_operator_delete; | ||
|
|
||
| NAPI_MODULE_INIT() { | ||
| void *allocation = cxx_operator_new_ptr(32); | ||
| cxx_operator_delete_ptr(allocation); | ||
|
|
||
| napi_value loaded; | ||
| if (napi_get_boolean(env, true, &loaded) != napi_ok) | ||
| return NULL; | ||
| if (napi_set_named_property(env, exports, "loaded", loaded) != napi_ok) | ||
| return NULL; | ||
| return exports; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,150 @@ | ||
| import { expect, test } from "bun:test"; | ||
| import { bunEnv, bunExe, isMusl, tempDir } from "harness"; | ||
| import { join } from "node:path"; | ||
|
|
||
| const cc = process.env.CC || Bun.which("cc") || Bun.which("clang") || Bun.which("gcc"); | ||
| const cxx = process.env.CXX || Bun.which("c++") || Bun.which("clang++") || Bun.which("g++"); | ||
| const readelf = Bun.which("readelf"); | ||
|
|
||
| function hasOptionalCxxRuntimeProvider(): boolean { | ||
| if (!isMusl) return false; | ||
|
|
||
| try { | ||
| const probe = Bun.spawnSync({ | ||
| cmd: [ | ||
| bunExe(), | ||
| "-e", | ||
| `import { dlopen } from "bun:ffi"; const library = dlopen("libstdc++.so.6", { _Znwm: { args: ["usize"], returns: "ptr" } }); library.close();`, | ||
| ], | ||
| env: bunEnv, | ||
| stdout: "ignore", | ||
| stderr: "ignore", | ||
| }); | ||
| return probe.exitCode === 0; | ||
| } catch { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| const hasCxxRuntimeProvider = hasOptionalCxxRuntimeProvider(); | ||
|
|
||
| interface AddonFixture { | ||
| compiler: string; | ||
| compilerFlags?: string[]; | ||
| expectedResult: boolean | number; | ||
| expectedSymbols: string[]; | ||
| resultProperty: string; | ||
| source: string; | ||
| } | ||
|
|
||
| async function compileAndLoadAddon(fixture: AddonFixture) { | ||
| using dir = tempDir("issue-29681", { | ||
| "load.js": ` | ||
| const { readFileSync } = require("node:fs"); | ||
| const runtimeMaps = () => readFileSync("/proc/self/maps", "utf8") | ||
| .split("\\n") | ||
| .filter(line => line.includes("libstdc++.so.6") || line.includes("libgcc_s.so.1")); | ||
|
|
||
| const before = runtimeMaps(); | ||
| const addon = require("./addon.node"); | ||
| const result = addon[${JSON.stringify(fixture.resultProperty)}]; | ||
| const after = runtimeMaps(); | ||
| console.log(JSON.stringify({ before, result, after })); | ||
| `, | ||
| }); | ||
| const dirPath = String(dir); | ||
| const addonPath = join(dirPath, "addon.node"); | ||
| const fixturePath = join(import.meta.dir, fixture.source); | ||
| const napiInclude = join(import.meta.dir, "..", "..", "..", "src", "runtime", "napi"); | ||
|
|
||
| await using compile = Bun.spawn({ | ||
| cmd: [ | ||
| fixture.compiler, | ||
| ...(fixture.compilerFlags ?? []), | ||
| "-shared", | ||
| "-fPIC", | ||
| "-nostdlib", | ||
| "-Wl,-z,now", | ||
| "-I", | ||
| napiInclude, | ||
| "-o", | ||
| addonPath, | ||
| fixturePath, | ||
| ], | ||
| env: bunEnv, | ||
| stderr: "pipe", | ||
| stdout: "pipe", | ||
| }); | ||
| const [compileStdout, compileStderr, compileExitCode] = await Promise.all([ | ||
| compile.stdout.text(), | ||
| compile.stderr.text(), | ||
| compile.exited, | ||
| ]); | ||
| expect({ stdout: compileStdout, stderr: compileStderr, exitCode: compileExitCode }).toEqual({ | ||
| stdout: "", | ||
| stderr: "", | ||
| exitCode: 0, | ||
| }); | ||
|
|
||
| const dynamic = Bun.spawnSync([readelf!, "-d", addonPath]); | ||
| const symbols = Bun.spawnSync([readelf!, "-Ws", addonPath]); | ||
| expect({ stderr: dynamic.stderr.toString(), exitCode: dynamic.exitCode }).toEqual({ stderr: "", exitCode: 0 }); | ||
| expect({ stderr: symbols.stderr.toString(), exitCode: symbols.exitCode }).toEqual({ stderr: "", exitCode: 0 }); | ||
| expect(dynamic.stdout.toString()).not.toContain("NEEDED"); | ||
| for (const symbol of fixture.expectedSymbols) { | ||
| expect(symbols.stdout.toString()).toContain(`UND ${symbol}`); | ||
| } | ||
|
|
||
| await using run = Bun.spawn({ | ||
| cmd: [bunExe(), join(dirPath, "load.js")], | ||
| cwd: dirPath, | ||
| env: { ...bunEnv, LD_PRELOAD: undefined }, | ||
| stderr: "pipe", | ||
| stdout: "pipe", | ||
| }); | ||
| const [stdout, stderr, exitCode] = await Promise.all([run.stdout.text(), run.stderr.text(), run.exited]); | ||
| expect(stderr).toBe(""); | ||
| expect(JSON.parse(stdout)).toEqual({ | ||
| before: [], | ||
| result: fixture.expectedResult, | ||
| after: expect.arrayContaining([ | ||
| expect.stringContaining("libstdc++.so.6"), | ||
| expect.stringContaining("libgcc_s.so.1"), | ||
| ]), | ||
| }); | ||
| expect(exitCode).toBe(0); | ||
| } | ||
|
|
||
| // The compatibility provider is optional, so clean musl developer images may not have it. | ||
| test.skipIf(!isMusl || !cc || !readelf || !hasCxxRuntimeProvider)( | ||
| "a legacy new/delete addon can use the optional host C++ runtime", | ||
| () => | ||
| compileAndLoadAddon({ | ||
| compiler: cc!, | ||
| expectedResult: true, | ||
| expectedSymbols: ["_Znwm", "_ZdlPv"], | ||
| resultProperty: "loaded", | ||
| source: "29681-cxx-runtime-addon.c", | ||
| }), | ||
| ); | ||
|
|
||
| test.skipIf(!isMusl || !cxx || !readelf || !hasCxxRuntimeProvider)( | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| "a legacy exception addon can use the optional host C++ runtime", | ||
| () => | ||
| compileAndLoadAddon({ | ||
| compiler: cxx!, | ||
| compilerFlags: ["-O0", "-fexceptions"], | ||
| expectedResult: 42, | ||
| expectedSymbols: [ | ||
| "__cxa_allocate_exception", | ||
| "__cxa_throw", | ||
| "__cxa_begin_catch", | ||
| "__cxa_end_catch", | ||
| "__gxx_personality_v0", | ||
| "_Unwind_Resume", | ||
| "_ZTVN10__cxxabiv117__class_type_infoE", | ||
| ], | ||
| resultProperty: "caught", | ||
| source: "29681-cxx-exception-addon.cpp", | ||
| }), | ||
| ); | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.