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
11 changes: 11 additions & 0 deletions src/runtime/node/node_fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4432,6 +4432,17 @@ impl Default for NodeFS {
}
}

impl NodeFS {
/// A fresh `NodeFS` on the heap. `sync_error_buf` makes the struct
/// `MAX_PATH_BYTES` large (96 KB on Windows), so a stack local of it costs
/// that much frame in every caller, taken or not.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) fn new_boxed() -> Box<Self> {
// SAFETY: all-zero bytes are a valid `NodeFS`: `sync_error_buf` is a
// `u8` array and a null `Option<NonNull<_>>` is `None`.
unsafe { Box::<Self>::new_zeroed().assume_init() }
}
}

/// Encode a path returned by the OS (`mkdtemp`/`readlink`/`realpath`) using the
/// caller's `encoding` option, matching Node.js: `"buffer"` yields a `Buffer`
/// of the raw bytes, any other encoding is `Buffer.from(bytes).toString(enc)`.
Expand Down
21 changes: 8 additions & 13 deletions src/runtime/webcore/fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ use bun_http::{self as http, FetchRedirect, Headers, HeadersExt as _, MimeType};
use bun_http_jsc::method_jsc;
use bun_http_types::Method::Method;
use bun_jsc::{HTTPHeaderName, StringJsc as _, SysErrorJsc as _, URLJsc as _};
use bun_paths::{self, PathBuffer};
use bun_sys::FdExt as _;
// `FromJsEnum for FetchRedirect` lives in bun_http_jsc; importing the impl crate
// brings the trait impl into scope for `JSValue::get_optional_enum::<FetchRedirect>`.
Expand Down Expand Up @@ -1267,8 +1266,8 @@ fn fetch_impl<const ALLOW_GET_BODY: bool>(
// We don't pass along headers, we ignore method, we ignore status code...
// But it's better than status quo.
if url_type != URLType::Remote {
let mut path_buf = PathBuffer::uninit();
let mut path_buf2 = PathBuffer::uninit();
let mut path_buf = bun_paths::path_buffer_pool::get();
let mut path_buf2 = bun_paths::path_buffer_pool::get();
let decoded_len = match PercentEncoding::decode_into(
&mut path_buf2[..],
match url_type {
Expand Down Expand Up @@ -1347,11 +1346,11 @@ fn fetch_impl<const ALLOW_GET_BODY: bool>(
}

#[cfg(windows)]
let mut cwd_buf = PathBuffer::uninit();
let mut cwd_buf = bun_paths::path_buffer_pool::get();
#[cfg(windows)]
// `bun_sys::getcwd` returns the byte length written into
// `cwd_buf`; slice it here.
let cwd: &[u8] = match bun_sys::getcwd(&mut cwd_buf) {
let cwd: &[u8] = match bun_sys::getcwd(&mut cwd_buf[..]) {
Ok(len) => &cwd_buf[..len],
Err(err) => {
return Err(global_this.throw_error(err, "Failed to resolve file url"));
Expand Down Expand Up @@ -1517,10 +1516,7 @@ fn fetch_impl<const ALLOW_GET_BODY: bool>(
}
if body.needs_to_read_file() {
'prepare_body: {
// A local `PathBuffer` serves as NUL-termination scratch for
// `path.slice_z()` (the `vm.node_fs()` accessor is gated behind a
// jsc↔runtime cycle).
let mut open_path_buf = PathBuffer::uninit();
let mut open_path_buf = bun_paths::path_buffer_pool::get();
let opened_fd_res: bun_sys::Result<bun_sys::Fd> = {
let store = body.store().expect("needs_to_read_file implies store");
match &store.data.as_file().pathlike {
Expand Down Expand Up @@ -1617,10 +1613,9 @@ fn fetch_impl<const ALLOW_GET_BODY: bool>(
// TODO: make this async + lazy
let blob_offset = body.any_blob().blob().offset.get();
let blob_size = body.any_blob().blob().size.get();
// The `vm.node_fs()` accessor is a jsc↔runtime cycle. `read_file`
// with an `Fd` path only touches `self.sync_error_buf` for
// path-variant inputs, so a fresh `NodeFS` is sufficient here.
let mut node_fs = node::fs::NodeFS::default();
// `read_file` with an `Fd` path only touches `self.sync_error_buf`
// for path-variant inputs, so a fresh `NodeFS` is sufficient here.
Comment thread
robobun marked this conversation as resolved.
Resolved
let mut node_fs = node::fs::NodeFS::new_boxed();
Comment thread
robobun marked this conversation as resolved.
Resolved
// `ReadFile` has `Drop`; can't use FRU `..Default::default()`.
let mut rf_args = node::fs::args::ReadFile::default();
rf_args.encoding = Encoding::Buffer;
Expand Down
35 changes: 35 additions & 0 deletions test/js/web/fetch/body-async-iterator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,41 @@ test("Response.bytes() with async iterable body does not crash with null deref",
expect(exitCode).toBe(0);
});

// Each level of this recursion holds one native fetch() frame on the stack.
// Windows used to reach 16 levels before the RangeError because that frame
// carried three 96 KB path buffers (Linux: 387 levels with the same script).
// A debug build of the fix reaches 96 on Windows; stock 1.4.1 reaches 16.
test("fetch() called from a body's Symbol.asyncIterator getter recurses deeply before the stack limit", async () => {
await using proc = Bun.spawn({
cmd: [
bunExe(),
"-e",
`
let depth = 0;
const signal = AbortSignal.abort();
const body = {
get [Symbol.asyncIterator]() {
depth++;
fetch("http://localhost/", { method: "POST", body, signal }).catch(() => {});
return undefined;
},
};
fetch("http://localhost/", { method: "POST", body, signal }).catch(() => {});
console.log(depth);
`,
],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});

const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);

expect(stderr).toBe("");
expect(Number(stdout.trim())).toBeGreaterThanOrEqual(32);
expect(exitCode).toBe(0);
});

test("Response.arrayBuffer() with async iterable body does not crash with null deref", async () => {
await using proc = Bun.spawn({
cmd: [
Expand Down
Loading