Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions src/jsc/bindings/ZigGlobalObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -284,11 +284,20 @@ extern "C" long Bun__crashHandlerFromJSCFrame(void*, void*, void*, void*);
// bun_icu_default_locale.cpp
extern "C" void Bun__ensureICUDefaultLocale();

extern "C" void JSCInitialize(const char* envp[], size_t envc, void (*onCrash)(const char* ptr, size_t length), bool evalMode, bool oneShotStartup, bool shortLivedGlobals)
// The assertOptionsAreCoherent() rule that BUN_JSC_* variables can reach; notifyOptionsChanged() repairs the others.
static ASCIILiteral incoherentJSCOptions()
{
using JSC::Options;
if (Options::useWasm() && !Options::useWasmIPInt() && !(Options::useBBQJIT() && Options::useJIT()))
return "useWasmIPInt and useBBQJIT are both off, so nothing can run WebAssembly (useJIT=0 also turns useBBQJIT off). Enable one of them, or set BUN_JSC_useWasm=0"_s;
return {};
}

extern "C" void JSCInitialize(const char* envp[], size_t envc, void (*onInvalidOption)(const char* ptr, size_t length), void (*onIncoherentOptions)(const char* reason, size_t length), bool evalMode, bool oneShotStartup, bool shortLivedGlobals)
{
static std::once_flag jsc_init_flag;
// NOLINTBEGIN
std::call_once(jsc_init_flag, [evalMode, oneShotStartup, shortLivedGlobals, envp, envc, onCrash]() {
std::call_once(jsc_init_flag, [evalMode, oneShotStartup, shortLivedGlobals, envp, envc, onInvalidOption, onIncoherentOptions]() {
Bun__ensureICUDefaultLocale();
JSC::Config::enableRestrictedOptions();
// JSC options come from BUN_JSC_* (applied in the callback below), not JSC_*.
Expand Down Expand Up @@ -377,14 +386,17 @@ extern "C" void JSCInitialize(const char* envp[], size_t envc, void (*onCrash)(c
}

if (!JSC::Options::setOption(env + 8)) [[unlikely]] {
onCrash(env, strlen(env));
onInvalidOption(env, strlen(env));
}
}
}
// $vm, which an engine built with assertions has, evaluates strings and makes global objects
// that are not Bun's, where eval is on. After the loop: BUN_JSC_useDollarVM does not bring it back.
if (Bun::codeGenerationFromStrings() != Bun::CodeGenerationFromStrings::Allowed) [[unlikely]]
JSC::Options::useDollarVM() = false;
if (auto reason = incoherentJSCOptions(); !reason.isNull()) [[unlikely]] {
onIncoherentOptions(reason.characters(), reason.length());
}
JSC::Options::assertOptionsAreCoherent();
}); // end JSC::initialize lambda

Expand Down
50 changes: 39 additions & 11 deletions src/jsc/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -499,14 +499,13 @@ pub fn initialize(options: InitializeOptions) {
// `bun_analytics`.
bun_core::analytics::Features::jsc_inc();
let env = bun_sys::environ();
// SAFETY: `env` borrows the libc `environ` global for the duration of the
// call; `on_jsc_invalid_env_var` is `extern "C"` and only reads the (ptr,len)
// it is handed. JSCInitialize is called exactly once at startup.
// SAFETY: runs once at startup; `env` borrows `environ` for the call; callbacks only read it.
unsafe {
JSCInitialize(
env.as_ptr(),
env.len(),
on_jsc_invalid_env_var,
on_jsc_incoherent_options,
options.eval_mode,
options.one_shot,
options.short_lived_globals,
Expand Down Expand Up @@ -540,18 +539,46 @@ pub fn is_one_shot_eval_invocation() -> bool {
false
}

/// Shared tail of the `BUN_JSC_*` startup errors below.
fn exit_with_jsc_env_var_help() -> ! {
bun_core::pretty_errorln!(
"\nFor a list of options, see this file:\n\n \
https://github.com/oven-sh/webkit/blob/main/Source/JavaScriptCore/runtime/OptionsList.h\n\n\
Environment variables must be prefixed with \"BUN_JSC_\". This code runs before .env files are loaded, so those won't work here.\n\n\
Warning: options change between releases of Bun and WebKit without notice. This is not a stable API, you should not rely on it beyond debugging something, and it may be removed entirely in a future version of Bun."
);
bun_core::exit(1);
}

extern "C" fn on_jsc_invalid_env_var(name: *const u8, len: usize) {
// SAFETY: C++ guarantees `name[..len]` is valid for the call.
let name = unsafe { bun_core::ffi::slice(name, len) };
bun_core::err_generic!(
"invalid JSC environment variable\n\n <b>{}<r>\n\n\
For a list of options, see this file:\n\n \
https://github.com/oven-sh/webkit/blob/main/Source/JavaScriptCore/runtime/OptionsList.h\n\n\
Environment variables must be prefixed with \"BUN_JSC_\". This code runs before .env files are loaded, so those won't work here.\n\n\
Warning: options change between releases of Bun and WebKit without notice. This is not a stable API, you should not rely on it beyond debugging something, and it may be removed entirely in a future version of Bun.",
bstr::BStr::new(name),
"invalid JSC environment variable\n\n <b>{}<r>",
bstr::BStr::new(name)
);
bun_core::exit(1);
exit_with_jsc_env_var_help();
}

/// A `BUN_JSC_*` combination JSC cannot run with: name the variables and exit(1) before JSC aborts.
extern "C" fn on_jsc_incoherent_options(reason: *const u8, len: usize) {
// SAFETY: C++ guarantees `reason[..len]` is valid for the call.
let reason = unsafe { bun_core::ffi::slice(reason, len) };
let mut vars = Vec::<u8>::new();
for &entry in bun_sys::environ() {
// SAFETY: `environ` entries are NUL-terminated C strings that live for the process.
let entry = unsafe { bun_core::ffi::cstr(entry) }.to_bytes();
if entry.starts_with(b"BUN_JSC_") {
vars.extend_from_slice(b"\n ");
vars.extend_from_slice(entry);
}
}
bun_core::err_generic!(
"incoherent JSC options: {}\n<b>{}<r>",
bstr::BStr::new(reason),
bstr::BStr::new(&vars),
);
exit_with_jsc_env_var_help();
}

/// `bun.JSError` — the canonical Bun JS error union (`error{Thrown, OutOfMemory, Terminated}`),
Expand Down Expand Up @@ -1564,7 +1591,8 @@ unsafe extern "C" {
fn JSCInitialize(
env: *const *const c_char,
count: usize,
cb: extern "C" fn(name: *const u8, len: usize),
on_invalid_option: extern "C" fn(name: *const u8, len: usize),
on_incoherent_options: extern "C" fn(reason: *const u8, len: usize),
eval_mode: bool,
one_shot_startup: bool,
short_lived_globals: bool,
Expand Down
47 changes: 40 additions & 7 deletions test/cli/run/env.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1477,19 +1477,19 @@ describe("node shim (argv0=node) does not auto-load .env files", () => {
// JSC options come from BUN_JSC_<option>; JSC's own JSC_<option> environment
// pass is disabled (JSC::Config::disableEnvironmentOptions in JSCInitialize).
describe("JSC option environment variables", () => {
async function dumpOptions(env: Record<string, string>) {
async function run(env: Record<string, string>) {
await using proc = Bun.spawn({
cmd: [bunExe(), "-e", "1"],
cmd: [bunExe(), "-e", "process.stdout.write('ran')"],
env: { ...bunEnv, ...env },
stdout: "ignore",
stdout: "pipe",
stderr: "pipe",
});
const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]);
return { stderr, exitCode };
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
return { stdout, stderr, exitCode, signalCode: proc.signalCode };
}
test.concurrent("BUN_JSC_<option> applies", async () => {
// level 1 lists overridden options only
const { stderr, exitCode } = await dumpOptions({
const { stderr, exitCode } = await run({
BUN_JSC_dumpOptions: "1",
BUN_JSC_thresholdForJITAfterWarmUp: "77",
});
Expand All @@ -1498,9 +1498,42 @@ describe("JSC option environment variables", () => {
});
test.concurrent("JSC_<option> is ignored", async () => {
// level 2 lists every option with its current value, however it was set
const { stderr, exitCode } = await dumpOptions({ BUN_JSC_dumpOptions: "2", JSC_thresholdForJITAfterWarmUp: "77" });
const { stderr, exitCode } = await run({ BUN_JSC_dumpOptions: "2", JSC_thresholdForJITAfterWarmUp: "77" });
expect(stderr).toContain("thresholdForJITAfterWarmUp=");
expect(stderr).not.toContain("thresholdForJITAfterWarmUp=77");
expect(exitCode).toBe(0);
});

// A bad set of BUN_JSC_* variables is a configuration error: a message on
// stderr and exit code 1, never a crash report.
test.concurrent("an unknown option is rejected with exit code 1", async () => {
const { stdout, stderr, exitCode, signalCode } = await run({ BUN_JSC_noSuchOption: "1" });
expect(stderr).toContain("invalid JSC environment variable");
expect(stderr).toContain("BUN_JSC_noSuchOption=1");
expect({ stdout, exitCode, signalCode }).toEqual({ stdout: "", exitCode: 1, signalCode: null });
});
// JSC::Options::assertOptionsAreCoherent() aborts on these combinations.
for (const env of [
// useJIT=0 turns every JIT tier off, including the wasm BBQ JIT, so with the
// wasm interpreter also off there is nothing left to run WebAssembly with.
{ BUN_JSC_useJIT: "0", BUN_JSC_useWasmIPInt: "0" },
{ BUN_JSC_useBBQJIT: "0", BUN_JSC_useWasmIPInt: "0" },
]) {
test.concurrent(`incoherent options are a configuration error: ${Object.keys(env).join(" + ")}`, async () => {
const { stdout, stderr, exitCode, signalCode } = await run(env);
expect(stderr).toContain("error: incoherent JSC options: useWasmIPInt and useBBQJIT are both off");
for (const [key, value] of Object.entries(env)) {
expect(stderr).toContain(`${key}=${value}`);
}
expect({ stdout, exitCode, signalCode }).toEqual({ stdout: "", exitCode: 1, signalCode: null });
});
}
test.concurrent("the same options with useWasm=0 are coherent and run", async () => {
const { stdout, exitCode, signalCode } = await run({
BUN_JSC_useJIT: "0",
BUN_JSC_useWasmIPInt: "0",
BUN_JSC_useWasm: "0",
});
expect({ stdout, exitCode, signalCode }).toEqual({ stdout: "ran", exitCode: 0, signalCode: null });
});
});
Loading