Skip to content
2 changes: 1 addition & 1 deletion src/runtime/server/server_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2325,7 +2325,7 @@ where
}

if let Some(body__) = opts.fast_get(ctx, jsc::BuiltinName::Body)? {
match Blob::get::<true, false>(ctx, body__) {
match Blob::get::<false>(ctx, body__) {
Ok(new_blob) => body = BodyValue::Blob(new_blob),
Err(err) => {
return Ok(JSPromise::rejected_promise_with_caught_exception(
Expand Down
108 changes: 18 additions & 90 deletions src/runtime/webcore/Blob.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,9 @@
//! operations like writing `Store::File` to another `Store::File` knows to use a
//! basic file copy instead of a naive read write loop.

use core::cell::Cell;
use core::ffi::{c_char, c_void};
use core::ptr::NonNull;

use bun_jsc::JsCell;

use crate::webcore::jsc::{
self as jsc, CallFrame, JSGlobalObject, JSPromise, JSValue, JsResult, VirtualMachine,
};
Expand Down Expand Up @@ -334,22 +331,11 @@ pub(crate) trait BlobExt {
lifetime: Lifetime,
) -> JsResult<JSValue>;
fn to_form_data(&self, cx: &bun_jsc::JsThread<'_>, _lifetime: Lifetime) -> JsResult<JSValue>;
fn get<const MOVE: bool, const REQUIRE_ARRAY: bool>(
global: &JSGlobalObject,
arg: JSValue,
) -> JsResult<Blob>
where
Self: Sized;
fn from_js_move(global: &JSGlobalObject, arg: JSValue) -> JsResult<Blob>
where
Self: Sized;
fn from_js_clone(global: &JSGlobalObject, arg: JSValue) -> JsResult<Blob>
/// `new Blob(parts)` from `arg`. With `REQUIRE_ARRAY = false` a bare part is accepted too.
fn get<const REQUIRE_ARRAY: bool>(global: &JSGlobalObject, arg: JSValue) -> JsResult<Blob>
where
Self: Sized;
fn from_js_clone_optional_array(global: &JSGlobalObject, arg: JSValue) -> JsResult<Blob>
where
Self: Sized;
fn from_js_without_defer_gc<const MOVE: bool, const REQUIRE_ARRAY: bool>(
fn from_js_without_defer_gc<const REQUIRE_ARRAY: bool>(
global: &JSGlobalObject,
arg: JSValue,
) -> JsResult<Blob>
Expand Down Expand Up @@ -2191,7 +2177,7 @@ impl BlobExt for Blob {
blob = Blob::init(Vec::new(), global_this);
}
_ => {
blob = Blob::get::<false, true>(global_this, args[0])?;
blob = Blob::get::<true>(global_this, args[0])?;

if args.len() > 1 {
let options = args[1];
Expand Down Expand Up @@ -2364,13 +2350,18 @@ impl BlobExt for Blob {
}

fn set_is_ascii_flag(&self, is_all_ascii: bool) {
// The callers scanned the bytes after a stripped UTF-8 BOM, which is itself non-ASCII.
let is_all_ascii =
is_all_ascii && !self.shared_view().starts_with(&strings::BOM::UTF8_BYTES);
Comment thread
robobun marked this conversation as resolved.
Resolved
self.charset
.set(strings::AsciiStatus::from_bool(Some(is_all_ascii)));
// if this Blob represents the entire binary data
// we can update the store's is_all_ascii flag
if self.size.get() > 0 && self.offset.get() == 0 {
if let Some(store) = self.store() {
if matches!(store.data, store::Data::Bytes(_)) {
if let store::Data::Bytes(bytes) = &store.data
&& self.size.get() >= bytes.len()
{
store.is_all_ascii.set(is_all_ascii);
}
}
Expand Down Expand Up @@ -2761,7 +2752,6 @@ impl BlobExt for Blob {
if TYPED_ARRAY_VIEW != jsc::JSType::ArrayBuffer {
// ArrayBuffer doesn't have this limit.
if buf_len > jsc::virtual_machine::synthetic_allocation_limit() {
self.detach();
return Err(global.throw_out_of_memory());
}
}
Expand Down Expand Up @@ -2974,33 +2964,11 @@ impl BlobExt for Blob {
})
}
#[inline]
fn get<const MOVE: bool, const REQUIRE_ARRAY: bool>(
global: &JSGlobalObject,
arg: JSValue,
) -> JsResult<Blob> {
match (MOVE, REQUIRE_ARRAY) {
(true, false) => Self::from_js_move(global, arg),
(false, false) => Self::from_js_clone_optional_array(global, arg),
(_, true) => Self::from_js_clone(global, arg),
}
}

#[inline]
fn from_js_move(global: &JSGlobalObject, arg: JSValue) -> JsResult<Blob> {
Self::from_js_without_defer_gc::<true, false>(global, arg)
}

#[inline]
fn from_js_clone(global: &JSGlobalObject, arg: JSValue) -> JsResult<Blob> {
Self::from_js_without_defer_gc::<false, true>(global, arg)
fn get<const REQUIRE_ARRAY: bool>(global: &JSGlobalObject, arg: JSValue) -> JsResult<Blob> {
Self::from_js_without_defer_gc::<REQUIRE_ARRAY>(global, arg)
}

#[inline]
fn from_js_clone_optional_array(global: &JSGlobalObject, arg: JSValue) -> JsResult<Blob> {
Self::from_js_without_defer_gc::<false, false>(global, arg)
}

fn from_js_without_defer_gc<const MOVE: bool, const REQUIRE_ARRAY: bool>(
fn from_js_without_defer_gc<const REQUIRE_ARRAY: bool>(
global: &JSGlobalObject,
arg: JSValue,
) -> JsResult<Blob> {
Expand Down Expand Up @@ -3033,7 +3001,7 @@ impl BlobExt for Blob {
}
}

if might_only_be_one_thing || !MOVE {
if might_only_be_one_thing {
// Fast path: one item, we don't need to join
match top_value.js_type_loose() {
jsc::JSType::Cell
Expand All @@ -3060,47 +3028,11 @@ impl BlobExt for Blob {

jsc::JSType::DOMWrapper => {
if !fail_if_top_value_is_not_typed_array_like {
if let Some(blob_ptr) = top_value.as_::<Blob>() {
// SAFETY: live JS heap pointer; single-threaded JS execution.
// Shared access only — Blob state is Cell/JsCell-based.
let blob = unsafe { &*blob_ptr };
if MOVE {
// Move the store without bumping its refcount, but take
// independent ownership of name/content_type so the
// source's eventual finalize() doesn't double-free them.
// *Take* the RefPtr<Store> out of `blob`
// (no clone, no into_raw leak) and field-copy the
// rest, deep-owning `name`/`content_type` — net 0 on
// the store refcount.
let _blob = Blob {
reported_estimated_size: Cell::new(
blob.reported_estimated_size.get(),
),
size: Cell::new(blob.size.get()),
offset: Cell::new(blob.offset.get()),
store: JsCell::new(blob.take_store()), // ← the move
content_type: JsCell::new(blob.content_type.get().clone()),
content_type_was_set: Cell::new(
blob.content_type_was_set.get(),
),
charset: Cell::new(blob.charset.get()),
is_jsdom_file: Cell::new(blob.is_jsdom_file.get()),
ref_count: bun_ptr::RawRefCount::init(0), // setNotHeapAllocated
global_this: Cell::new(blob.global_this.get()),
last_modified: Cell::new(blob.last_modified.get()),
name: blob.name.clone(),
};
return Ok(_blob);
} else {
return Ok(blob.dupe());
}
if let Some(blob) = top_value.as_class_ref::<Blob>() {
return Ok(blob.dupe());
} else if let Some(artifact) =
top_value.as_class_ref::<crate::api::BuildArtifact>()
{
// The previous "move" path here only nulled the store on a
// local copy and left `build.blob` fully intact, so it was
// never a real move. Share the store and deep-copy owned
// buffers instead — regardless of `MOVE`.
return Ok(artifact.blob.dupe());
} else {
let view = current.to_js_string_view(global)?;
Expand Down Expand Up @@ -5002,7 +4934,7 @@ pub(crate) fn write_file_internal(
return destination_blob.pipe_readable_stream_to_blob(cx, readable, &options);
}

break 'brk Blob::get::<false, false>(cx.global(), data)?;
break 'brk Blob::get::<false>(cx.global(), data)?;
};
// Detach the source blob on scope exit.
let mut source_blob = scopeguard::guard(source_blob, |b| b.detach());
Expand Down Expand Up @@ -5331,7 +5263,7 @@ pub(crate) fn jsdom_file_construct(
)));
}
let name = BunString::from_js(args[1], global_this)?;
let blob = Blob::get::<false, true>(global_this, args[0])?;
let blob = Blob::get::<true>(global_this, args[0])?;
// The store may be shared with the source blob (`dupe()`); never rename it.
blob.name.set(name);

Expand Down Expand Up @@ -5929,10 +5861,6 @@ impl read_file::ReadFileToJs for ToFormDataWithBytesFn {
}
}

// ──────────────────────────────────────────────────────────────────────────
// get / fromJSMove / fromJSClone / fromJSWithoutDeferGC
// ──────────────────────────────────────────────────────────────────────────

// ──────────────────────────────────────────────────────────────────────────
// Core constructors / JS bridging (init_with_store / to_js /
// find_or_create_file_from_path). These are referenced by `Bun.file` /
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/webcore/Body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1047,7 +1047,7 @@ impl Value {
));
}

Ok(Value::Blob(Blob::get::<true, false>(global_this, value)?))
Ok(Value::Blob(Blob::get::<false>(global_this, value)?))
Comment thread
robobun marked this conversation as resolved.
Resolved
}

pub(crate) fn from_readable_stream_without_lock_check(
Expand Down
140 changes: 140 additions & 0 deletions test/js/web/fetch/blob.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,146 @@ for (const info of [
});
}

// text()/json() cache whether the bytes they decoded were all ASCII, and Blobs
// sharing one backing store read each other's cache. The cache must only ever
// describe bytes the reader is actually going to decode.
describe("Blob text()/json() decoding does not depend on what was read before", () => {
const utf8 = "héllo wörld ✓";
const bom = new Uint8Array([0xef, 0xbb, 0xbf]);

test("parent after an ASCII prefix slice", async () => {
const blob = new Blob(["abc", utf8]);
expect(await blob.slice(0, 3).text()).toBe("abc");
expect(await blob.text()).toBe("abc" + utf8);
});

test("sibling slice after an ASCII prefix slice", async () => {
const blob = new Blob(["abc", utf8]);
const rest = blob.slice(3);
expect(await blob.slice(0, 3).text()).toBe("abc");
expect(await rest.text()).toBe(utf8);
});

test("Response wrapping the Blob after an ASCII prefix slice", async () => {
const blob = new Blob(["abc", utf8]);
expect(await blob.slice(0, 3).text()).toBe("abc");
expect(await new Response(blob).text()).toBe("abc" + utf8);
});

test("parent after a Response body made from an ASCII prefix slice", async () => {
const blob = new Blob(["abc", utf8]);
expect(await new Response(blob.slice(0, 3)).text()).toBe("abc");
expect(await blob.text()).toBe("abc" + utf8);
});

test("parent after a Response body made from an ASCII prefix slice was read as json()", async () => {
const blob = new Blob(["123", utf8]);
expect(await new Response(blob.slice(0, 3)).json()).toBe(123);
expect(await blob.text()).toBe("123" + utf8);
});

test("parent json() after an ASCII prefix slice text()", async () => {
const blob = new Blob(['"', utf8, '"']);
expect(await blob.slice(0, 1).text()).toBe('"');
expect(await blob.json()).toBe(utf8);
});

test("parent text() after an ASCII prefix slice json()", async () => {
const blob = new Blob(["123", utf8]);
expect(await blob.slice(0, 3).json()).toBe(123);
expect(await blob.text()).toBe("123" + utf8);
});

test("parent after an ASCII prefix slice was read through its stream", async () => {
const blob = new Blob(["abc", utf8]);
expect(await Bun.readableStreamToText(blob.slice(0, 3).stream())).toBe("abc");
expect(await blob.text()).toBe("abc" + utf8);
});

// A Blob made from one string knows its own charset, a stream made from it does not.
test("stream of a Blob made from one string after an ASCII prefix slice", async () => {
const blob = new Blob(["abc" + utf8]);
expect(await blob.slice(0, 3).text()).toBe("abc");
expect(await Bun.readableStreamToText(blob.stream())).toBe("abc" + utf8);
});

test("File from a parsed FormData after an ASCII prefix slice", async () => {
const form = new FormData();
form.append("file", new File([JSON.stringify({ name: utf8 })], "user.json", { type: "application/json" }));
const file = (await new Response(form).formData()).get("file") as File;
expect(await file.slice(0, 1).text()).toBe("{");
expect(await file.json()).toEqual({ name: utf8 });
});

test("slice(0) spans the whole Blob and decodes the same as the parent", async () => {
const blob = new Blob(["abc", utf8]);
expect(await blob.slice(0).text()).toBe("abc" + utf8);
expect(await blob.text()).toBe("abc" + utf8);
expect(await blob.slice(0, 3).text()).toBe("abc");
expect(await blob.slice(3).text()).toBe(utf8);
});

test("slice into a UTF-8 BOM after the parent's text() stripped it", async () => {
const blob = new Blob([bom, "abc"]);
const sliceMadeBefore = blob.slice(1);
expect(await blob.text()).toBe("abc");
expect(await blob.text()).toBe("abc");
expect(await sliceMadeBefore.text()).toBe("\ufffd\ufffdabc");
expect(await blob.slice(1).text()).toBe("\ufffd\ufffdabc");
});

test("slice into a UTF-8 BOM after the parent's json() stripped it", async () => {
const blob = new Blob([bom, '{"a":1}']);
const sliceMadeBefore = blob.slice(1);
expect(await blob.json()).toEqual({ a: 1 });
expect(await sliceMadeBefore.text()).toBe('\ufffd\ufffd{"a":1}');
expect(await blob.slice(1).text()).toBe('\ufffd\ufffd{"a":1}');
});

test("Blob built from a BOM-prefixed Blob part that was already read", async () => {
const part = new Blob([bom, "abc"]);
expect(await part.text()).toBe("abc");
// The BOM is no longer at the start, so it decodes as U+FEFF.
expect(await new Blob(["x", part]).text()).toBe("x\ufeffabc");
expect(await new Blob([part]).text()).toBe("abc");
});
});

// bytes() rejects a Blob that is larger than one Uint8Array may be. The read
// that was refused must leave the caller's Blob as it was.
test("a Blob keeps its bytes after bytes() rejected it for its size", async () => {
const script = `
const blob = new Blob([new Uint8Array(500_000).fill(65)]);
const refused = await blob.bytes().then(
() => "resolved",
e => e.name + ": " + e.message,
);
console.log(
JSON.stringify({
refused,
size: blob.size,
head: await blob.slice(0, 5).text(),
arrayBuffer: (await blob.arrayBuffer()).byteLength,
}),
);
`;
await using proc = Bun.spawn({
cmd: [bunExe(), "-e", script],
env: { ...bunEnv, BUN_FEATURE_FLAG_SYNTHETIC_MEMORY_LIMIT: "100000" },
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stderr).toBe("");
expect(JSON.parse(stdout)).toEqual({
refused: "RangeError: Out of memory",
size: 500_000,
head: "AAAAA",
arrayBuffer: 500_000,
});
expect(exitCode).toBe(0);
});

test("new Blob", () => {
var blob = new Blob(["Bun", "Foo"], { type: "text/foo" });
expect(blob.size).toBe(6);
Expand Down
Loading
Loading