Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 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
1 change: 1 addition & 0 deletions src/codegen/generate-js2native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ const sourceFiles = readdirRecursiveWithExclusionsAndExtensionsSync(
// requires adding its entry below.
const rustIdentifierPaths: Record<string, string> = {
"bun.rs": "bun.rs",
"ConsoleObject.rs": "jsc/ConsoleObject.rs",
"Counters.rs": "jsc/Counters.rs",
"FrameworkRouter.rs": "runtime/bake/FrameworkRouter.rs",
"Listener.rs": "runtime/socket/Listener.rs",
Expand Down
8 changes: 5 additions & 3 deletions src/js/node/worker_threads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -469,10 +469,12 @@
enumerable: true,
});
// node routes console.log through process.stdout/stderr; Bun's global console
// writes the fd directly, so rebind it to the captured streams when present.
// writes the fd directly. Rebind its output sink to the port-backed streams
// so console output is captured by worker.stdout/stderr, while keeping Bun's
// formatter and the Bun-specific console surface (console.write,
// Symbol.asyncIterator) intact.
if (stdout || stderr) {
const { Console } = require("node:console");
globalThis.console = new Console(process.stdout, process.stderr);
$newRustFunction("ConsoleObject.rs", "setOutputStreams", 2)(process.stdout, process.stderr);

Check warning on line 477 in src/js/node/worker_threads.ts

View check run for this annotation

Claude / Claude Code Review

Restored Bun console APIs (console.write, Symbol.asyncIterator) bypass port-backed worker stdio

🟡 The restored Bun-specific console APIs bypass the port-backed worker stdio: `console.write` (ConsoleObject.ts:124) writes via `Bun.stdout.writer()` to fd 1 and never consults `stdout_override`, so its output escapes `worker.stdout` capture; and `console[Symbol.asyncIterator]` (ConsoleObject.ts:3) reads `Bun.stdin.stream()` (fd 0) directly — exactly what the `process.stdin` replacement at :456-458 exists to prevent ("would race the main thread (and hang on a TTY)"). Not a regression (both were
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}

Expand Down
182 changes: 157 additions & 25 deletions src/jsc/ConsoleObject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
use core::ffi::c_void;

use crate as jsc;
use crate::strong::Optional as StrongOptional;
use crate::virtual_machine::VirtualMachine;
use crate::{EventType, JSGlobalObject, JSPromise, JSValue, JsResult, ZigString};
use crate::{CallFrame, EventType, JSGlobalObject, JSPromise, JSValue, JsResult, ZigString};
use bun_collections::HashMap;
use bun_core::{Output, StackCheck};
use bun_core::{OwnedString, String as BunString, strings};
Expand Down Expand Up @@ -98,6 +99,14 @@

counts: Counter,

/// When set, formatted console output is written to this JS Writable's
/// `.write()` instead of the fd-backed `writer_backing`. Used by
/// `node:worker_threads` so console output flows through the worker's
/// port-backed `process.stdout`/`stderr` without replacing the global
/// console object.
stdout_override: StrongOptional,
stderr_override: StrongOptional,

// The writer adapters above hold raw pointers into `{stderr,stdout}_buffer`;
// moving the struct would dangle them. `PhantomPinned` opts out of `Unpin`
// so `Pin<Box<Self>>` (returned by `init`) actually enforces that.
Expand Down Expand Up @@ -138,6 +147,8 @@
writer_backing: Output::QuietWriterAdapter::uninit(),
default_indent: 0,
counts: Counter::default(),
stdout_override: StrongOptional::empty(),
stderr_override: StrongOptional::empty(),
_pin: core::marker::PhantomPinned,
});
let p: *mut ConsoleObject = &raw mut *out;
Expand Down Expand Up @@ -173,6 +184,8 @@
writer_backing: Output::QuietWriterAdapter::uninit(),
default_indent: 0,
counts: Counter::default(),
stdout_override: StrongOptional::empty(),
stderr_override: StrongOptional::empty(),
_pin: core::marker::PhantomPinned,
});
let p: *mut ConsoleObject = out;
Expand Down Expand Up @@ -202,6 +215,63 @@
pub fn writer(&mut self) -> &mut bun_core::io::Writer {
self.writer_backing.new_interface()
}

#[inline]
fn override_for(&self, use_stderr: bool) -> Option<JSValue> {
if use_stderr {
self.stderr_override.get()
} else {
self.stdout_override.get()
}
}

/// Release the JS stream overrides. Must run while the JSC VM is still
/// alive; the `StrongOptional` Drop path would otherwise touch a freed
/// `HandleSet` when the `ConsoleObject` box is destroyed after VM teardown.
pub fn clear_output_streams(&mut self) {
self.stdout_override.deinit();
self.stderr_override.deinit();
}
}

/// Hand the buffered bytes to a JS Writable stream's `.write()`. A stream
/// whose `write` is not callable is a programmer error in the binding, not a
/// user-visible condition, so fall through silently rather than throw.
fn write_to_js_stream(global: &JSGlobalObject, stream: JSValue, buf: &[u8]) -> JsResult<()> {
if buf.is_empty() {
return Ok(());
}
let Some(write_fn) = stream.get(global, b"write")? else {
return Ok(());
};
if !write_fn.is_callable() {
return Ok(());
}
let str = crate::bun_string_jsc::create_utf8_for_js(global, buf)?;
let _ = write_fn.call(global, stream, core::slice::from_ref(&str))?;
Ok(())
}

/// `$newRustFunction("ConsoleObject.rs", "setOutputStreams", 2)`.
/// Rebinds this VM's native console output sink to a pair of JS Writable
/// streams so formatting and the Bun-specific console surface are preserved
/// while output still flows through `process.stdout`/`stderr`.
pub fn set_output_streams(global: &JSGlobalObject, callframe: &CallFrame) -> JsResult<JSValue> {
let [stdout, stderr] = callframe.arguments_as_array::<2>();
// SAFETY: top-level JS-thread host call ⇒ exclusive access to the
// set-once `VirtualMachine.console` box.
let this = unsafe { vm_console_mut(global) };
if stdout.is_object() {
this.stdout_override.set(global, stdout);
} else {
this.stdout_override.deinit();
}
if stderr.is_object() {
this.stderr_override.set(global, stderr);
} else {
this.stderr_override.deinit();
}
Ok(JSValue::UNDEFINED)
}

#[repr(u32)]
Expand Down Expand Up @@ -455,6 +525,42 @@
// time. We do this the slightly annoying way to avoid assigning a pointer.
let use_stderr = matches!(level, MessageLevel::Warning | MessageLevel::Error)
|| message_type == MessageType::Assert;

// Snapshot before borrowing the writer; `default_indent` is not mutated
// again until the deferred `_indent_guard` runs on scope exit, so the two
// later reads (FormatOptions / TablePrinter) can use this cached copy
// instead of re-dereferencing the raw `console` pointer.
// SAFETY: see [`vm_console`] — single-JS-thread; no other `&mut` is live.
let (default_indent, override_stream) = {
let c = unsafe { vm_console_mut(global) };

Check failure on line 535 in src/jsc/ConsoleObject.rs

View workflow job for this annotation

GitHub Actions / cargo clippy

unsafe block missing a safety comment
(c.default_indent, c.override_for(use_stderr))
};
Comment thread
robobun marked this conversation as resolved.
Resolved

if let Some(stream) = override_stream {
// The override sink is a JS Writable (port-backed `process.stdout` in a
// `node:worker_threads` worker). It is not a shared fd, so the stream
// lock is unnecessary; and it is never a TTY, so colors are off.
if message_type == MessageType::Clear {
return Ok(());
}
let mut buf: Vec<u8> = Vec::new();
if message_type == MessageType::Assert && len == 0 {
buf.extend_from_slice(b"Assertion failed\n");
} else {
write_message_body(
&mut buf,
message_type,
level,
global,
vals,
len,
false,
default_indent,
)?;
}
return write_to_js_stream(global, stream, &buf);

Check warning on line 561 in src/jsc/ConsoleObject.rs

View check run for this annotation

Claude / Claude Code Review

console.trace() override path leaks ANSI codes into captured worker output

`console.trace()` in the override path can still emit ANSI escape codes into the captured buffer: `write_message_body` calls `write_trace(writer, global)` (line 719), and `write_trace` hardcodes `Output::enable_ansi_colors_stderr()` (line 1355) instead of honoring the `enable_colors=false` passed here. When the parent process's fd 2 is a TTY, a worker's `console.trace()` writes raw escape sequences into `worker.stdout`/`stderr`. Threading `enable_colors` into `write_trace` would fix it alongside
Comment thread
robobun marked this conversation as resolved.
Resolved
}

let _stream_lock = ConsoleStreamLock::acquire(use_stderr);

if message_type == MessageType::Clear {
Expand Down Expand Up @@ -483,13 +589,6 @@
Output::enable_ansi_colors_stdout()
};

// Snapshot before borrowing the writer; `default_indent` is not mutated
// again until the deferred `_indent_guard` runs on scope exit, so the two
// later reads (FormatOptions / TablePrinter) can use this cached copy
// instead of re-dereferencing the raw `console` pointer.
// SAFETY: see [`vm_console`] — single-JS-thread; no other `&mut` is live.
let default_indent = unsafe { vm_console_mut(global) }.default_indent;

// SAFETY: see [`vm_console`] — `console` points at the live boxed
// `ConsoleObject` for this VM; JS-thread-only. Kept as a raw deref (not
// `vm_console_mut`) so the resulting `writer` borrow does not pin a
Expand All @@ -513,6 +612,29 @@
(hooks.console_on_before_print)();
}

write_message_body(
writer,
message_type,
level,
global,
vals,
len,
enable_colors,
default_indent,
)
}

#[allow(clippy::too_many_arguments)]
fn write_message_body(
writer: &mut dyn bun_io::Write,
message_type: MessageType,
level: MessageLevel,
global: &JSGlobalObject,
vals: *const JSValue,
len: usize,
enable_colors: bool,
default_indent: u16,
) -> JsResult<()> {
let mut print_length = len;
// Get console depth from CLI options or bunfig, fallback to default.
let console_depth = bun_options_types::context::try_get()
Expand Down Expand Up @@ -587,12 +709,8 @@
print_options,
)?;
} else if message_type == MessageType::Log {
// SAFETY: see [`vm_console`]. `writer` (above) is dead in this arm —
// the only later uses are in the mutually-exclusive `Trace` block, and
// `message_type == Log` here.
let w = unsafe { (*console).writer() };
let _ = w.write_all(b"\n");
let _ = w.flush();
let _ = writer.write_all(b"\n");
let _ = writer.flush();
} else if message_type != MessageType::Trace {
let _ = writer.write_all(b"undefined\n");
}
Expand Down Expand Up @@ -5863,21 +5981,35 @@
ptr: *const u8,
len: usize,
) {
// SAFETY: top-level JS-thread host call ⇒ exclusive access to the
// set-once `VirtualMachine.console` box.
let this = unsafe { vm_console_mut(global_this) };
// SAFETY: caller passes a valid (ptr, len) pair.
let slice = unsafe { bun_core::ffi::slice(ptr, len) };
let hash = bun_wyhash::hash(slice);
// we don't want to store these strings, it will take too much memory
let counter = this.counts.get_or_put(hash).expect("unreachable");
let current: u32 = if counter.found_existing {
*counter.value_ptr
} else {
0
} + 1;
*counter.value_ptr = current;
// SAFETY: top-level JS-thread host call ⇒ exclusive access to the
// set-once `VirtualMachine.console` box. The borrow is scoped so it ends
// before the override path calls back into JS (which may re-enter here).
let (current, override_stream) = {
let this = unsafe { vm_console_mut(global_this) };

Check failure on line 5991 in src/jsc/ConsoleObject.rs

View workflow job for this annotation

GitHub Actions / cargo clippy

unsafe block missing a safety comment
// we don't want to store these strings, it will take too much memory
let counter = this.counts.get_or_put(hash).expect("unreachable");
let current: u32 = if counter.found_existing {
*counter.value_ptr
} else {
0
} + 1;
*counter.value_ptr = current;
(current, this.stdout_override.get())
};

if let Some(stream) = override_stream {
let mut buf: Vec<u8> = Vec::new();
let w: &mut dyn bun_io::Write = &mut buf;
let _ = writeln!(w, "{}: {}", bstr::BStr::new(slice), current);
let _ = write_to_js_stream(global_this, stream, &buf);
return;
}
Comment thread
robobun marked this conversation as resolved.
Resolved

// SAFETY: fd path; no JS re-entry below.
let this = unsafe { vm_console_mut(global_this) };
let writer = this.writer();
if Output::enable_ansi_colors_stdout() {
let _ = writeln!(
Expand Down
7 changes: 7 additions & 0 deletions src/jsc/web_worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1297,6 +1297,13 @@ impl WebWorker {
// worker VM is dealloc'd-without-Drop so anything still in
// self.tasks leaks. Mirrors the global_exit() ordering.
vm.event_loop_mut().release_queued_tasks_for_shutdown();
// The console's JS stream overrides hold Strong handles into this
// VM's heap; release them while JSC is still alive so the
// ConsoleObject box (freed in step 5) doesn't touch a dead HandleSet.
if !vm.console.is_null() {
// SAFETY: set-once per-VM box; sole owner.
unsafe { (*vm.console).clear_output_streams() };
}
exit_code = i32::from(vm.exit_handler.exit_code);
global_object = Some(vm.global);
}
Expand Down
1 change: 1 addition & 0 deletions src/runtime/dispatch_js2native.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ pub use bun_install_jsc::ini_jsc::ini_testing_load_npmrc_from_js as ini_ini_ini_
pub use bun_install_jsc::ini_jsc::ini_testing_parse as ini_ini_ini_testing_ap_is_parse;

pub use bun_jsc::bindgen_test::get_bindgen_test_functions as jsc_bindgen_test_get_bindgen_test_functions;
pub use bun_jsc::console_object::set_output_streams as jsc_console_object_set_output_streams;
pub use bun_jsc::counters::create_counters_object as jsc_counters_create_counters_object;
pub use bun_jsc::event_loop::get_active_tasks as jsc_event_loop_get_active_tasks;
pub use bun_jsc::virtual_machine_exports::Bun__setSyntheticAllocationLimitForTesting as jsc_virtual_machine_exports_bun__set_synthetic_allocation_limit_for_testing;
Expand Down
Loading
Loading