From b16cdae53eec72c27357cb869043f150c222ecd2 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 29 Jun 2026 13:48:51 +0000 Subject: [PATCH 1/7] markdown: harden the parser's remaining 32-bit limits Follow-ups to #32752, requested in review after it merged. The first fix only guarded the input length read by Parser::init; three sibling limits in the same path were still fatal in release builds: - block_bytes growth: every block offset is a u32 (Container.block_byte_off, the casts in push_container and enter_child_containers), but nothing bounded the buffer, so a few hundred MB of nested blockquotes or headings panicked on 'int cast' in push_container. Reject the document at the two sites that grow the buffer (push_container_bytes, start_new_block) with a new ParserError::TooManyBlocks, reported to JS as a RangeError. - lookahead margin: input_size accepted lengths up to u32::MAX, but the parser probes up to 9 bytes past an offset (the AnsiRenderer<'a> { last_was_newline: true, blank_emitted: false, }; - r.out.list.reserve(src_text.len() + src_text.len() / 2); + // The output is usually ~1.5x the input; this is only a throughput + // hint, so on failure fall back to the incremental `try_reserve`s in + // `write` instead of aborting. + let _ = r.out.list.try_reserve(src_text.len() + src_text.len() / 2); r } diff --git a/src/md/blocks.rs b/src/md/blocks.rs index 7f9dcccd1fe4..0806e563e841 100644 --- a/src/md/blocks.rs +++ b/src/md/blocks.rs @@ -48,7 +48,7 @@ impl Parser<'_> { p_end: &mut OFF, pivot_line: &Line, line: &mut Line, - ) -> Result<(), bun_alloc::AllocError> { + ) -> Result<(), parser::Error> { let mut off = off_start; let mut total_indent: u32 = 0; let mut n_parents: u32 = 0; @@ -692,7 +692,7 @@ impl Parser<'_> { cur_line_idx: usize, line_buf: &mut [Line; 2], line_idx: &mut usize, - ) -> Result<(), bun_alloc::AllocError> { + ) -> Result<(), parser::Error> { // Index into line_buf via cur_line_idx instead of taking a `&mut Line` // parameter, which would alias line_buf. let line = &mut line_buf[cur_line_idx]; @@ -832,7 +832,7 @@ impl Parser<'_> { Ok(()) } - pub fn start_new_block(&mut self, line: &Line) -> Result<(), bun_alloc::AllocError> { + pub fn start_new_block(&mut self, line: &Line) -> Result<(), parser::Error> { let block_type: BlockType = match line.r#type { LineType::Hr => BlockType::Hr, LineType::Atxheader => BlockType::H, @@ -847,6 +847,11 @@ impl Parser<'_> { let cur_len = self.block_bytes.len(); let aligned = (cur_len + align_mask) & !align_mask; let needed = aligned + size_of::(); + // See `push_container_bytes`: block offsets are u32, so reject a + // document whose headers outgrow them at the site that grows them. + if needed > parser::MAX_BLOCK_BYTES { + return Err(parser::Error::TooManyBlocks); + } self.block_bytes.ensure_total_capacity(needed); // Zero-fill to `needed`; bytes in [aligned, needed) are immediately // overwritten by the BlockHeader write below. diff --git a/src/md/containers.rs b/src/md/containers.rs index c38ec8e2b43f..8cb18fb66745 100644 --- a/src/md/containers.rs +++ b/src/md/containers.rs @@ -27,11 +27,18 @@ impl Parser<'_> { block_type: BlockType, data: u32, flags: u32, - ) -> Result<(), AllocError> { + ) -> Result<(), parser::Error> { let align_mask: usize = align_of::() - 1; let cur_len = self.block_bytes.len(); let aligned = (cur_len + align_mask) & !align_mask; let needed = aligned + size_of::(); + // Block offsets are u32 (`block_byte_off`, the casts in + // `push_container` and `enter_child_containers`); a document needing + // more header bytes than they can address must be rejected here, at + // the only places `block_bytes` grows, not cast. + if needed > parser::MAX_BLOCK_BYTES { + return Err(parser::Error::TooManyBlocks); + } self.block_bytes .reserve(needed.saturating_sub(self.block_bytes.len())); // Zero-fill to `needed`; bytes in [aligned, needed) are immediately @@ -49,7 +56,7 @@ impl Parser<'_> { Ok(()) } - pub fn enter_child_containers(&mut self, count: u32) -> Result<(), AllocError> { + pub fn enter_child_containers(&mut self, count: u32) -> Result<(), parser::Error> { let mut i: u32 = self.n_containers - count; while i < self.n_containers { // Capture the container fields before calling &mut self methods. @@ -100,7 +107,7 @@ impl Parser<'_> { Ok(()) } - pub fn leave_child_containers(&mut self, keep: u32) -> Result<(), AllocError> { + pub fn leave_child_containers(&mut self, keep: u32) -> Result<(), parser::Error> { while self.n_containers > keep { self.n_containers -= 1; // Capture the container fields before calling &mut self methods. diff --git a/src/md/parser.rs b/src/md/parser.rs index a9ddceb87a15..0df54c1b21d5 100644 --- a/src/md/parser.rs +++ b/src/md/parser.rs @@ -130,7 +130,7 @@ impl Default for BlockHeader { } /// `Parser`'s error type: the union of `{ OutOfMemory, JSError, JSTerminated }` -/// with the parser-specific `{ StackOverflow, InputTooLarge }`. +/// with the parser-specific `{ StackOverflow, InputTooLarge, TooManyBlocks }`. // (`bun_jsc::JsError` covers the first three, but the md crate sits below // `bun_jsc` in the layering, so the variants stay flat here.) pub type Error = ParserError; @@ -141,9 +141,12 @@ pub enum ParserError { JSError, JSTerminated, StackOverflow, - /// The input is longer than `OFF::MAX` bytes, so its offsets cannot be - /// represented by the parser's `u32` offset type. + /// The input is longer than [`MAX_INPUT_LEN`], so the parser's `u32` + /// offset arithmetic cannot address it. InputTooLarge, + /// The document needs more than [`MAX_BLOCK_BYTES`] of block headers, so + /// the parser's `u32` block offsets cannot address them. + TooManyBlocks, } bun_core::oom_from_alloc!(ParserError); @@ -154,12 +157,33 @@ impl From for bun_core::Error { } } -/// Every offset, mark and span boundary in the parser is an `OFF` (u32), so an -/// input of 2^32 bytes or more cannot be indexed. Callers that size anything -/// from the input length must reject it with this before allocating. +/// The longest fixed lookahead the parser performs from an in-bounds offset: +/// the 9-byte `() + align_of::()); + +/// Callers that size anything from the input length must reject oversized +/// inputs with this before allocating. #[inline] pub(crate) fn input_size(text: &[u8]) -> Result { - OFF::try_from(text.len()).map_err(|_| ParserError::InputTooLarge) + if text.len() > MAX_INPUT_LEN { + return Err(ParserError::InputTooLarge); + } + Ok(text.len() as OFF) } impl<'a> Parser<'a> { diff --git a/src/runtime/api/MarkdownObject.rs b/src/runtime/api/MarkdownObject.rs index 089dba2210c9..58d461932ae0 100644 --- a/src/runtime/api/MarkdownObject.rs +++ b/src/runtime/api/MarkdownObject.rs @@ -9,7 +9,7 @@ use bun_jsc::{ // thin mod-decl shim, so alias the `root` module (which re-exports BlockType, // SpanType, TextType, SpanDetail, Renderer, helpers, types, ansi, …) as `md`. use crate::node::StringOrBuffer; -use bun_md::parser::ParserError; +use bun_md::parser::{MAX_INPUT_LEN, ParserError}; use bun_md::root as md; // `bun_core::String::create_utf8_for_js` lives in `bun_jsc::bun_string_jsc` @@ -54,11 +54,21 @@ fn parser_err_to_js( ParserError::InputTooLarge => global_this.throw_range_error( input_len as i64, RangeErrorOptions { - max: md::types::OFF::MAX as i64, + max: MAX_INPUT_LEN as i64, field_name: b"input.byteLength", ..Default::default() }, ), + // The document, not the input length, overflowed the parser's u32 + // block offsets, so an `input.byteLength` bound would be misleading. + ParserError::TooManyBlocks => global_this + .err( + bun_jsc::ErrCode::OUT_OF_RANGE, + format_args!( + "markdown input requires more block metadata than the parser can address (4 GiB)" + ), + ) + .throw(), } } diff --git a/test/js/bun/md/md-edge-cases.test.ts b/test/js/bun/md/md-edge-cases.test.ts index 221d716ab5d5..ce4ff635bcb2 100644 --- a/test/js/bun/md/md-edge-cases.test.ts +++ b/test/js/bun/md/md-edge-cases.test.ts @@ -1190,21 +1190,24 @@ describe("pathological autolink opener inputs", () => { }, 90_000); }); -describe("inputs of 2^32 bytes or more", () => { - // The parser addresses its input with u32 offsets, so a 2^32-byte input - // cannot be represented and must be rejected with a catchable RangeError by - // every entry point. One subprocess covers all four: a crash must not take - // down the test runner, and one 4 GiB reservation (virtual only, never - // written) keeps this cheap. The SKIP branch covers runners that cannot - // reserve 4 GiB; under ASAN the allocator must be allowed to return null - // for that to surface as a catchable error rather than an abort. The - // explicit timeout is for the debug+ASAN lanes, where a spawned child is - // slow under load (same as the linear-time test above). - test("html, ansi, render and react reject a 2^32-byte input", async () => { +describe("inputs the parser cannot address", () => { + // The parser addresses its input with u32 offsets and probes up to 9 bytes + // past an offset (the ` { const script = ` - let big; + let big, boundary; try { big = new Uint8Array(2 ** 32); + boundary = new Uint8Array(2 ** 32 - 1); } catch { console.log(JSON.stringify("SKIP")); process.exit(0); @@ -1214,6 +1217,9 @@ describe("inputs of 2^32 bytes or more", () => { () => Bun.markdown.ansi(big), () => Bun.markdown.render(big, {}), () => Bun.markdown.react(big, undefined, { reactVersion: 18 }), + // One past the accepted maximum of 4294967286 from the other side: + // the largest allocatable length that must still be rejected. + () => Bun.markdown.html(boundary), ]; const results = []; for (const run of runs) { @@ -1234,13 +1240,18 @@ describe("inputs of 2^32 bytes or more", () => { }, stdout: "pipe", stderr: "inherit", + // An accepted 4 GiB input would take minutes to scan; if a regression + // accepts one of these lengths again, kill the child instead. + timeout: 20_000, + killSignal: "SIGKILL", }); const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); - const rangeError = - 'RangeError | ERR_OUT_OF_RANGE | The value of "input.byteLength" is out of range. It must be <= 4294967295. Received 4294967296'; - expect(["SKIP", [rangeError, rangeError, rangeError, rangeError]]).toContainEqual( - JSON.parse(stdout.trim() || '"NO_OUTPUT"'), - ); + const message = (received: number) => + `RangeError | ERR_OUT_OF_RANGE | The value of "input.byteLength" is out of range. It must be <= 4294967286. Received ${received}`; + expect([ + "SKIP", + [message(2 ** 32), message(2 ** 32), message(2 ** 32), message(2 ** 32), message(2 ** 32 - 1)], + ]).toContainEqual(JSON.parse(stdout.trim() || '"NO_OUTPUT"')); expect(exitCode).toBe(0); }, 30_000); }); From 6d256b9975853f89fb24dc0973c16916fea819da Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 29 Jun 2026 14:14:45 +0000 Subject: [PATCH 2/7] markdown: cover the third block_bytes growth site and share the cap Review follow-ups: end_current_block flushes 12 bytes of VerbatimLine per accumulated line into block_bytes, so a few hundred MB of two-byte lines still overflowed the u32 block offsets through a growth site the first commit missed (and its comment wrongly called the other two the only ones). Move the cap into one parser::check_block_bytes_len helper used by all three growth sites, and name the actual function holding the 9-byte lookahead in the MAX_LOOKAHEAD comment. --- src/md/blocks.rs | 11 +++++------ src/md/containers.rs | 8 +------- src/md/parser.rs | 14 +++++++++++++- 3 files changed, 19 insertions(+), 14 deletions(-) diff --git a/src/md/blocks.rs b/src/md/blocks.rs index 0806e563e841..1b540e931699 100644 --- a/src/md/blocks.rs +++ b/src/md/blocks.rs @@ -847,11 +847,7 @@ impl Parser<'_> { let cur_len = self.block_bytes.len(); let aligned = (cur_len + align_mask) & !align_mask; let needed = aligned + size_of::(); - // See `push_container_bytes`: block offsets are u32, so reject a - // document whose headers outgrow them at the site that grows them. - if needed > parser::MAX_BLOCK_BYTES { - return Err(parser::Error::TooManyBlocks); - } + parser::check_block_bytes_len(needed)?; self.block_bytes.ensure_total_capacity(needed); // Zero-fill to `needed`; bytes in [aligned, needed) are immediately // overwritten by the BlockHeader write below. @@ -884,7 +880,7 @@ impl Parser<'_> { Ok(()) } - pub fn end_current_block(&mut self) -> Result<(), bun_alloc::AllocError> { + pub fn end_current_block(&mut self) -> Result<(), parser::Error> { if let Some(cb_off) = self.current_block { // Capture the header fields, drop the &mut borrow, then access // other &self fields. @@ -931,6 +927,9 @@ impl Parser<'_> { self.current_block_lines.len() * size_of::(), ) }; + // The block's lines land in `block_bytes` too (12 bytes per + // line), not just its header, so this growth needs the same cap. + parser::check_block_bytes_len(self.block_bytes.len() + line_bytes.len())?; self.block_bytes.extend_from_slice(line_bytes); self.current_block = None; } diff --git a/src/md/containers.rs b/src/md/containers.rs index 8cb18fb66745..5a8e97a10371 100644 --- a/src/md/containers.rs +++ b/src/md/containers.rs @@ -32,13 +32,7 @@ impl Parser<'_> { let cur_len = self.block_bytes.len(); let aligned = (cur_len + align_mask) & !align_mask; let needed = aligned + size_of::(); - // Block offsets are u32 (`block_byte_off`, the casts in - // `push_container` and `enter_child_containers`); a document needing - // more header bytes than they can address must be rejected here, at - // the only places `block_bytes` grows, not cast. - if needed > parser::MAX_BLOCK_BYTES { - return Err(parser::Error::TooManyBlocks); - } + parser::check_block_bytes_len(needed)?; self.block_bytes .reserve(needed.saturating_sub(self.block_bytes.len())); // Zero-fill to `needed`; bytes in [aligned, needed) are immediately diff --git a/src/md/parser.rs b/src/md/parser.rs index 0df54c1b21d5..b990080196c6 100644 --- a/src/md/parser.rs +++ b/src/md/parser.rs @@ -158,7 +158,7 @@ impl From for bun_core::Error { } /// The longest fixed lookahead the parser performs from an in-bounds offset: -/// the 9-byte `() + align_of::()); +/// Rejects growing `block_bytes` to `needed` bytes once the parser's u32 +/// block offsets could no longer address it. Every site that grows the +/// buffer (`start_new_block`, `push_container_bytes`, `end_current_block`) +/// checks this before appending. +#[inline] +pub(crate) fn check_block_bytes_len(needed: usize) -> Result<(), ParserError> { + if needed > MAX_BLOCK_BYTES { + return Err(ParserError::TooManyBlocks); + } + Ok(()) +} + /// Callers that size anything from the input length must reject oversized /// inputs with this before allocating. #[inline] From 6561c6ad301f2332432e5fd185ac936132fd76fb Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 29 Jun 2026 14:43:56 +0000 Subject: [PATCH 3/7] markdown: describe MAX_BLOCK_BYTES as the whole block_bytes cap The constant bounds headers and the per-line VerbatimLine data since the end_current_block guard, not just headers. --- src/md/parser.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/md/parser.rs b/src/md/parser.rs index b990080196c6..0001af851a32 100644 --- a/src/md/parser.rs +++ b/src/md/parser.rs @@ -144,8 +144,8 @@ pub enum ParserError { /// The input is longer than [`MAX_INPUT_LEN`], so the parser's `u32` /// offset arithmetic cannot address it. InputTooLarge, - /// The document needs more than [`MAX_BLOCK_BYTES`] of block headers, so - /// the parser's `u32` block offsets cannot address them. + /// The document needs more than [`MAX_BLOCK_BYTES`] of block metadata, + /// so the parser's `u32` block offsets cannot address it. TooManyBlocks, } @@ -168,7 +168,7 @@ const MAX_LOOKAHEAD: OFF = 9; /// never to wrap. pub const MAX_INPUT_LEN: usize = (OFF::MAX - MAX_LOOKAHEAD) as usize; -/// The most block-header bytes a document may allocate: block offsets are +/// The most bytes `block_bytes` may hold: block offsets are /// stored as `u32`s (`BlockHeader.data` links, `Container.block_byte_off`), /// and each new header is written at the end of `block_bytes` rounded up to /// its alignment, so the buffer must stop one aligned header short of From a42545d2bd2a07211ed804d639a705aca066a15b Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 30 Jun 2026 01:01:07 +0000 Subject: [PATCH 4/7] test: give the reference-definition perf child a budget a loaded runner can meet The 'documents with many reference definitions and references render in linear time' test spawns a debug+ASAN child over a 220k-line document with a 30s kill timer. On a loaded runner that child needs 24-45s (observed: SIGKILLed at 30.1s), which made it the flakiest test in this file. Raise the child's hard stop to 75s, still under the test's own 90s timeout; the workload and every assertion are unchanged. --- test/js/bun/md/md-edge-cases.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/js/bun/md/md-edge-cases.test.ts b/test/js/bun/md/md-edge-cases.test.ts index ce4ff635bcb2..cc18a78e9d6e 100644 --- a/test/js/bun/md/md-edge-cases.test.ts +++ b/test/js/bun/md/md-edge-cases.test.ts @@ -1093,7 +1093,10 @@ describe("pathological reference definition inputs", () => { env: bunEnv, stdout: "pipe", stderr: "pipe", - timeout: 30_000, + // 220k lines through a debug+ASAN child run close to 30s on a loaded + // runner, which made this the flakiest test in the file; the hard stop + // only has to stay under the test's own 90s timeout. + timeout: 75_000, killSignal: "SIGKILL", }); const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); From 240c35a68da49fa4056b31aaf7abe1b2655fcc1e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 30 Jun 2026 09:27:12 +0000 Subject: [PATCH 5/7] markdown: share OutputBuffer between the renderers and guard the ANSI staging buffers The HTML and ANSI renderers each carried a byte-identical OutputBuffer; hoist it (plus try_extend/try_push helpers) into src/md/output.rs. The ANSI renderer routed code-block, heading, image-alt, and table-cell bytes through staging Vecs that still aborted on allocation failure one branch above the guarded output sink; those sites (and the table_rows/table_cells pushes) now record the failure on the same oom flag that render_to_ansi already checks, matching how the HTML renderer guards its heading buffer. resolve_href can no longer fail, so it returns Box<[u8]> directly. --- src/md/ansi_renderer.rs | 82 +++++++++++++++-------------------------- src/md/html_renderer.rs | 49 ++---------------------- src/md/lib.rs | 1 + src/md/output.rs | 60 ++++++++++++++++++++++++++++++ 4 files changed, 95 insertions(+), 97 deletions(-) create mode 100644 src/md/output.rs diff --git a/src/md/ansi_renderer.rs b/src/md/ansi_renderer.rs index 9c9a63774678..5181c2b6e313 100644 --- a/src/md/ansi_renderer.rs +++ b/src/md/ansi_renderer.rs @@ -10,6 +10,7 @@ use bun_core::output::ansi_b; use bun_core::strings; use crate::helpers; +use crate::output::{OutputBuffer, try_extend, try_push}; use crate::root; use crate::types::{ self, Align, BlockType, JsResult, Renderer, RendererImpl, SpanDetail, SpanType, TextType, @@ -259,35 +260,6 @@ impl InlineStyle { } } -pub struct OutputBuffer { - pub list: Vec, - pub oom: bool, -} - -impl OutputBuffer { - fn write(&mut self, data: &[u8]) { - if self.oom { - return; - } - if self.list.try_reserve(data.len()).is_err() { - self.oom = true; - return; - } - self.list.extend_from_slice(data); - } - - fn write_byte(&mut self, b: u8) { - if self.oom { - return; - } - if self.list.try_reserve(1).is_err() { - self.oom = true; - return; - } - self.list.push(b); - } -} - impl<'a> AnsiRenderer<'a> { pub fn init(src_text: &'a [u8], theme: Theme<'a>) -> AnsiRenderer<'a> { let mut r = AnsiRenderer { @@ -557,19 +529,27 @@ impl<'a> AnsiRenderer<'a> { // normalized once the table finishes. let cells: Box<[TableCell]> = core::mem::take(&mut self.table_cells).into_boxed_slice(); - self.table_rows.push(TableRow { - cells, - is_header: self.in_thead, - }); + try_push( + &mut self.out.oom, + &mut self.table_rows, + TableRow { + cells, + is_header: self.in_thead, + }, + ); self.table_cells.clear(); } BlockType::Th | BlockType::Td => { self.in_cell = false; let owned = Box::<[u8]>::from(self.table_cell_buf.as_slice()); - self.table_cells.push(TableCell { - content: owned, - alignment: self.cell_align, - }); + try_push( + &mut self.out.oom, + &mut self.table_cells, + TableCell { + content: owned, + alignment: self.cell_align, + }, + ); } } } @@ -593,10 +573,8 @@ impl<'a> AnsiRenderer<'a> { SpanType::A => { self.link_depth += 1; if self.link_depth == 1 { - // Resolve final href (prefixes for autolinks). On OOM - // we leave link_href null so leaveSpan doesn't try to - // free a literal. - self.link_href = resolve_href(&detail).ok(); + // Resolve final href (prefixes for autolinks). + self.link_href = Some(resolve_href(&detail)); if self.theme.colors && self.theme.hyperlinks { if let Some(href) = &self.link_href { // OSC 8 hyperlink start @@ -758,19 +736,19 @@ impl<'a> AnsiRenderer<'a> { /// heading buffer, table cell, image alt, or directly to output). fn write_content(&mut self, data: &[u8]) { if self.image_depth > 0 { - self.image_alt.extend_from_slice(data); + try_extend(&mut self.out.oom, &mut self.image_alt, data); return; } if self.in_code_block { - self.code_buf.extend_from_slice(data); + try_extend(&mut self.out.oom, &mut self.code_buf, data); return; } if self.heading_level > 0 { - self.heading_buf.extend_from_slice(data); + try_extend(&mut self.out.oom, &mut self.heading_buf, data); return; } if self.in_cell { - self.table_cell_buf.extend_from_slice(data); + try_extend(&mut self.out.oom, &mut self.table_cell_buf, data); return; } // Normal paragraph flow: respect wrapping + indent. @@ -952,16 +930,16 @@ impl<'a> AnsiRenderer<'a> { while i < bytes.len() && bytes[i] != 0x1b { i += 1; } - self.image_alt.extend_from_slice(&bytes[start..i]); + try_extend(&mut self.out.oom, &mut self.image_alt, &bytes[start..i]); } return; } if self.in_cell { - self.table_cell_buf.extend_from_slice(bytes); + try_extend(&mut self.out.oom, &mut self.table_cell_buf, bytes); return; } if self.heading_level > 0 { - self.heading_buf.extend_from_slice(bytes); + try_extend(&mut self.out.oom, &mut self.heading_buf, bytes); return; } self.out.write(bytes); @@ -1126,11 +1104,11 @@ impl<'a> AnsiRenderer<'a> { return; } if self.in_cell { - self.table_cell_buf.extend_from_slice(data); + try_extend(&mut self.out.oom, &mut self.table_cell_buf, data); return; } if self.heading_level > 0 { - self.heading_buf.extend_from_slice(data); + try_extend(&mut self.out.oom, &mut self.heading_buf, data); return; } self.out.write(data); @@ -2448,7 +2426,7 @@ fn extract_language(src_text: &[u8], info_beg: u32) -> &[u8] { /// Build the final href string with autolink prefixes (mailto:, http://). /// Caller owns the returned memory. -fn resolve_href(detail: &SpanDetail) -> Result, bun_alloc::AllocError> { +fn resolve_href(detail: &SpanDetail) -> Box<[u8]> { let mut buf: Vec = Vec::new(); if detail.autolink_email { buf.extend_from_slice(b"mailto:"); @@ -2458,7 +2436,7 @@ fn resolve_href(detail: &SpanDetail) -> Result, bun_alloc::AllocError> } let mut scratch: Vec = Vec::new(); buf.extend_from_slice(sanitize_source_text(detail.href, &mut scratch)); - Ok(buf.into_boxed_slice()) + buf.into_boxed_slice() } // ======================================== diff --git a/src/md/html_renderer.rs b/src/md/html_renderer.rs index 6a5f1c99911e..8fb7cea1edd0 100644 --- a/src/md/html_renderer.rs +++ b/src/md/html_renderer.rs @@ -4,6 +4,7 @@ use bun_core::strings; use crate::RenderOptions; use crate::helpers; +use crate::output::{OutputBuffer, try_extend, try_push}; use crate::types; use crate::types::{BlockType, JsResult, Renderer, RendererImpl, SpanDetail, SpanType, TextType}; @@ -21,36 +22,6 @@ pub(crate) struct HtmlRenderer<'src> { pub heading_tracker: helpers::HeadingIdTracker, } -pub struct OutputBuffer { - pub list: Vec, - // allocator dropped — non-AST crate uses global mimalloc - pub oom: bool, -} - -impl OutputBuffer { - fn write(&mut self, data: &[u8]) { - if self.oom { - return; - } - if self.list.try_reserve(data.len()).is_err() { - self.oom = true; - return; - } - self.list.extend_from_slice(data); - } - - fn write_byte(&mut self, b: u8) { - if self.oom { - return; - } - if self.list.try_reserve(1).is_err() { - self.oom = true; - return; - } - self.list.push(b); - } -} - impl<'src> HtmlRenderer<'src> { pub(crate) fn init(src_text: &'src [u8], render_opts: RenderOptions) -> HtmlRenderer<'src> { HtmlRenderer { @@ -426,11 +397,7 @@ impl<'src> HtmlRenderer<'src> { pub(crate) fn write(&mut self, data: &[u8]) { if self.heading_tracker.in_heading { - if self.heading_buf.try_reserve(data.len()).is_err() { - self.out.oom = true; - return; - } - self.heading_buf.extend_from_slice(data); + try_extend(&mut self.out.oom, &mut self.heading_buf, data); } else { self.out.write(data); } @@ -438,11 +405,7 @@ impl<'src> HtmlRenderer<'src> { fn write_byte(&mut self, b: u8) { if self.heading_tracker.in_heading { - if self.heading_buf.try_reserve(1).is_err() { - self.out.oom = true; - return; - } - self.heading_buf.push(b); + try_push(&mut self.out.oom, &mut self.heading_buf, b); } else { self.out.write_byte(b); } @@ -473,11 +436,7 @@ impl<'src> HtmlRenderer<'src> { if self.heading_tracker.in_heading { let items = self.heading_buf.as_slice(); if !items.is_empty() && items[items.len() - 1] != b'\n' { - if self.heading_buf.try_reserve(1).is_err() { - self.out.oom = true; - return; - } - self.heading_buf.push(b'\n'); + try_push(&mut self.out.oom, &mut self.heading_buf, b'\n'); } } else { let items = self.out.list.as_slice(); diff --git a/src/md/lib.rs b/src/md/lib.rs index 861b7657c470..df97e17a8dce 100644 --- a/src/md/lib.rs +++ b/src/md/lib.rs @@ -11,6 +11,7 @@ pub mod html_renderer; pub mod inlines; pub mod line_analysis; pub mod links; +pub mod output; pub mod parser; pub mod ref_defs; pub mod render_blocks; diff --git a/src/md/output.rs b/src/md/output.rs new file mode 100644 index 000000000000..4b517f30ada5 --- /dev/null +++ b/src/md/output.rs @@ -0,0 +1,60 @@ +//! The renderers' shared output sink. Allocation failure while rendering is +//! recorded in [`OutputBuffer::oom`] instead of aborting; the render entry +//! points (`render_to_html`, `render_to_ansi`) turn the flag into +//! `ParserError::OutOfMemory`. Staging buffers that hold output-sized data +//! before it reaches the sink must grow through [`try_extend`] / [`try_push`] +//! so their failures land on the same flag. + +pub struct OutputBuffer { + pub list: Vec, + pub oom: bool, +} + +impl OutputBuffer { + pub(crate) fn write(&mut self, data: &[u8]) { + if self.oom { + return; + } + if self.list.try_reserve(data.len()).is_err() { + self.oom = true; + return; + } + self.list.extend_from_slice(data); + } + + pub(crate) fn write_byte(&mut self, b: u8) { + if self.oom { + return; + } + if self.list.try_reserve(1).is_err() { + self.oom = true; + return; + } + self.list.push(b); + } +} + +/// Grow `buf` by `data` without aborting on allocation failure; the failure +/// is recorded in `oom` and further writes become no-ops. +pub(crate) fn try_extend(oom: &mut bool, buf: &mut Vec, data: &[u8]) { + if *oom { + return; + } + if buf.try_reserve(data.len()).is_err() { + *oom = true; + return; + } + buf.extend_from_slice(data); +} + +/// [`try_extend`] for a single element. +pub(crate) fn try_push(oom: &mut bool, vec: &mut Vec, value: T) { + if *oom { + return; + } + if vec.try_reserve(1).is_err() { + *oom = true; + return; + } + vec.push(value); +} From b5b7ffc22569e07153c73eb9245f4d9aa0287772 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 30 Jun 2026 09:27:22 +0000 Subject: [PATCH 6/7] markdown: prove the block-metadata cap and make it testable MAX_LOOKAHEAD is now derived from the CDATA probe it exists for (line_analysis::CDATA_OPEN), and its doc states the real invariant: the longest OFF-typed fixed addition, not the longest lookahead. A const assert next to MAX_BLOCK_BYTES encodes the headroom proof so a larger BlockHeader fails to compile instead of silently shrinking the margin. The align/check/grow/write-header sequence that start_new_block and push_container_bytes duplicated moves into Parser::append_block_header, so a new header site cannot skip check_block_bytes_len; the remaining u32 casts of block_bytes.len() are annotated with the invariant that makes them safe. check_block_bytes_len now reads an AtomicUsize initialized to MAX_BLOCK_BYTES and lowerable (never raisable) through setMaxMarkdownBlockBytesForTesting in bun:internal-for-testing. The new test shrinks the cap to ~1 KB and proves the exact boundary: a document whose metadata lands on the cap renders, one more block (and a nested blockquote's container headers) throws the catchable ERR_OUT_OF_RANGE, and restoring the cap makes both render again. Also drops the redundant inner timeout/SIGKILL from the addressable limit test; the outer test timeout already bounds and reaps the child. --- src/codegen/generate-js2native.ts | 1 + src/js/internal-for-testing.ts | 10 +++++ src/md/blocks.rs | 17 +------- src/md/containers.rs | 23 ++++------- src/md/line_analysis.rs | 15 +++++-- src/md/parser.rs | 57 ++++++++++++++++++++++--- src/runtime/api/MarkdownObject.rs | 20 +++++++++ test/js/bun/md/md-edge-cases.test.ts | 62 ++++++++++++++++++++++++++-- 8 files changed, 162 insertions(+), 43 deletions(-) diff --git a/src/codegen/generate-js2native.ts b/src/codegen/generate-js2native.ts index e32f5c4e0c8e..e7662b3d474c 100644 --- a/src/codegen/generate-js2native.ts +++ b/src/codegen/generate-js2native.ts @@ -48,6 +48,7 @@ const rustIdentifierPaths: Record = { "Counters.rs": "jsc/Counters.rs", "FrameworkRouter.rs": "runtime/bake/FrameworkRouter.rs", "Listener.rs": "runtime/socket/Listener.rs", + "MarkdownObject.rs": "runtime/api/MarkdownObject.rs", "SecureContext.rs": "runtime/api/bun/SecureContext.rs", "Stat.rs": "runtime/node/Stat.rs", "bindgen_test.rs": "jsc/bindgen_test.rs", diff --git a/src/js/internal-for-testing.ts b/src/js/internal-for-testing.ts index d04d7b9a7325..e0d3d9252a85 100644 --- a/src/js/internal-for-testing.ts +++ b/src/js/internal-for-testing.ts @@ -144,6 +144,16 @@ export const setSyntheticAllocationLimitForTesting: (limit: number) => number = 1, ); +// Shrink the markdown parser's block-metadata cap (in bytes) so its +// `TooManyBlocks` error is reachable without 4 GiB of input. The cap can only +// be lowered, never raised past the real limit. Returns the previous value so +// a test can restore it. +export const setMaxMarkdownBlockBytesForTesting: (limit: number) => number = $newRustFunction( + "MarkdownObject.rs", + "setMaxMarkdownBlockBytesForTesting", + 1, +); + export const npm_manifest_test_helpers = $rust("npm.rs", "PackageManifest.bindings.generate") as { /** * Returns the parsed manifest file. Currently only returns an array of available versions. diff --git a/src/md/blocks.rs b/src/md/blocks.rs index 1b540e931699..9fa9f50279a0 100644 --- a/src/md/blocks.rs +++ b/src/md/blocks.rs @@ -3,7 +3,6 @@ use crate::helpers; use crate::parser::{self, Parser}; use crate::types::{self, BlockType, Container, Line, OFF, VerbatimLine}; -use bun_collections::VecExt as _; use core::mem::{align_of, size_of}; type BlockHeader = parser::BlockHeader; @@ -842,25 +841,13 @@ impl Parser<'_> { _ => BlockType::P, }; - // Align block_bytes for Block alignment - let align_mask: usize = align_of::() - 1; - let cur_len = self.block_bytes.len(); - let aligned = (cur_len + align_mask) & !align_mask; - let needed = aligned + size_of::(); - parser::check_block_bytes_len(needed)?; - self.block_bytes.ensure_total_capacity(needed); - // Zero-fill to `needed`; bytes in [aligned, needed) are immediately - // overwritten by the BlockHeader write below. - self.block_bytes.resize(needed, 0); - - let hdr = self.get_block_header_at(aligned); - *hdr = BlockHeader { + let aligned = self.append_block_header(BlockHeader { block_type, _pad: [0; 3], flags: 0, data: line.data, n_lines: 0, - }; + })?; self.current_block = Some(aligned); self.current_block_lines.clear(); diff --git a/src/md/containers.rs b/src/md/containers.rs index 5a8e97a10371..527a30d0cbcc 100644 --- a/src/md/containers.rs +++ b/src/md/containers.rs @@ -14,7 +14,8 @@ impl Parser<'_> { self.containers[self.n_containers as usize] = *c; } - // Record block_byte offset in the container + // Record block_byte offset in the container. + // In range: every `block_bytes` grower enforces `check_block_bytes_len`. let block_off: u32 = u32::try_from(self.block_bytes.len()).expect("int cast"); self.containers[self.n_containers as usize].block_byte_off = block_off; @@ -28,25 +29,13 @@ impl Parser<'_> { data: u32, flags: u32, ) -> Result<(), parser::Error> { - let align_mask: usize = align_of::() - 1; - let cur_len = self.block_bytes.len(); - let aligned = (cur_len + align_mask) & !align_mask; - let needed = aligned + size_of::(); - parser::check_block_bytes_len(needed)?; - self.block_bytes - .reserve(needed.saturating_sub(self.block_bytes.len())); - // Zero-fill to `needed`; bytes in [aligned, needed) are immediately - // overwritten by the BlockHeader assignment below. - self.block_bytes.resize(needed, 0); - - let hdr = self.get_block_header_at(aligned); - *hdr = BlockHeader { + self.append_block_header(BlockHeader { block_type, _pad: [0; 3], flags, data, n_lines: 0, - }; + })?; Ok(()) } @@ -66,6 +55,8 @@ impl Parser<'_> { } else if ch == b'-' || ch == b'+' || ch == b'*' { // Save opener position for later loose-list patching let align_mask_: usize = align_of::() - 1; + // In range: every `block_bytes` grower enforces + // `check_block_bytes_len`, which leaves alignment headroom. self.containers[idx].block_byte_off = u32::try_from((self.block_bytes.len() + align_mask_) & !align_mask_).unwrap(); // Unordered list + list item @@ -82,6 +73,8 @@ impl Parser<'_> { } else if ch == b'.' || ch == b')' { // Save opener position for later loose-list patching let align_mask_: usize = align_of::() - 1; + // In range: every `block_bytes` grower enforces + // `check_block_bytes_len`, which leaves alignment headroom. self.containers[idx].block_byte_off = u32::try_from((self.block_bytes.len() + align_mask_) & !align_mask_).unwrap(); // Ordered list + list item diff --git a/src/md/line_analysis.rs b/src/md/line_analysis.rs index 9dc466c0e6cb..30f7c1fb3960 100644 --- a/src/md/line_analysis.rs +++ b/src/md/line_analysis.rs @@ -1,8 +1,13 @@ use super::helpers; -use super::parser::Parser; +use super::parser::{self, Parser}; use super::types; use super::types::{Align, Container, OFF}; +/// ` { return 4; } - // Type 5: for bun_core::Error { } } -/// The longest fixed lookahead the parser performs from an in-bounds offset: -/// the 9-byte `() + align_of::()); +// The headroom proof: a buffer filled to the cap can still be aligned up and +// take one more header without leaving `OFF` range. +const _: () = assert!( + ((MAX_BLOCK_BYTES + (align_of::() - 1)) & !(align_of::() - 1)) + + size_of::() + <= OFF::MAX as usize +); + +/// The runtime block-metadata cap checked by [`check_block_bytes_len`]: +/// always [`MAX_BLOCK_BYTES`] outside of tests, shrinkable only through +/// [`set_max_block_bytes_for_testing`]. +static BLOCK_BYTES_LIMIT: AtomicUsize = AtomicUsize::new(MAX_BLOCK_BYTES); + +/// `bun:internal-for-testing` (`setMaxMarkdownBlockBytesForTesting`): shrink +/// the block-metadata cap so the `TooManyBlocks` path is reachable without +/// allocating 4 GiB of headers. The cap can only be lowered, never raised +/// past [`MAX_BLOCK_BYTES`]. Returns the previous value so callers can +/// restore it. +pub fn set_max_block_bytes_for_testing(limit: usize) -> usize { + BLOCK_BYTES_LIMIT.swap(limit.min(MAX_BLOCK_BYTES), Ordering::Relaxed) +} + /// Rejects growing `block_bytes` to `needed` bytes once the parser's u32 /// block offsets could no longer address it. Every site that grows the -/// buffer (`start_new_block`, `push_container_bytes`, `end_current_block`) -/// checks this before appending. +/// buffer (`append_block_header`, `end_current_block`) checks this before +/// appending. #[inline] pub(crate) fn check_block_bytes_len(needed: usize) -> Result<(), ParserError> { - if needed > MAX_BLOCK_BYTES { + if needed > BLOCK_BYTES_LIMIT.load(Ordering::Relaxed) { return Err(ParserError::TooManyBlocks); } Ok(()) @@ -221,6 +246,26 @@ impl<'a> Parser<'a> { self.get_block_header_at(off) } + /// Appends one aligned `BlockHeader` to `block_bytes` and returns its + /// byte offset. This is the only way a header is added, so the + /// block-metadata cap cannot be forgotten by a new caller. + pub(crate) fn append_block_header( + &mut self, + header: BlockHeader, + ) -> Result { + let align_mask: usize = align_of::() - 1; + let aligned = (self.block_bytes.len() + align_mask) & !align_mask; + let needed = aligned + size_of::(); + check_block_bytes_len(needed)?; + self.block_bytes + .reserve(needed.saturating_sub(self.block_bytes.len())); + // Zero-fill to `needed`; bytes in [aligned, needed) are immediately + // overwritten by the header write below. + self.block_bytes.resize(needed, 0); + *self.get_block_header_at(aligned) = header; + Ok(aligned) + } + fn init(text: &'a [u8], flags: Flags, rend: Renderer<'a>) -> Result, ParserError> { let size = input_size(text)?; let mut p = Parser { diff --git a/src/runtime/api/MarkdownObject.rs b/src/runtime/api/MarkdownObject.rs index 58d461932ae0..22855563fbd5 100644 --- a/src/runtime/api/MarkdownObject.rs +++ b/src/runtime/api/MarkdownObject.rs @@ -109,6 +109,26 @@ pub(crate) fn create(global_this: &JSGlobalObject) -> JSValue { ) } +/// `bun:internal-for-testing`'s `setMaxMarkdownBlockBytesForTesting(limit)`: +/// shrink the parser's block-metadata cap so its `TooManyBlocks` error is +/// testable without 4 GiB of input. Returns the previous limit. +#[bun_jsc::host_fn] +pub(crate) fn set_max_markdown_block_bytes_for_testing( + global_this: &JSGlobalObject, + callframe: &CallFrame, +) -> JsResult { + let [limit_value] = callframe.arguments_as_array::<1>(); + if !limit_value.is_number() { + return Err(global_this.throw_invalid_arguments(format_args!( + "setMaxMarkdownBlockBytesForTesting expects a number" + ))); + } + let limit = usize::try_from(limit_value.coerce_to_int64(global_this)?.max(0)) + .expect("non-negative i64 fits usize"); + let prev = bun_md::parser::set_max_block_bytes_for_testing(limit); + Ok(JSValue::js_number(prev as f64)) +} + /// `Bun.markdown.ansi(text, theme?)` — render markdown to an ANSI-colored /// terminal string. `theme` is an optional object: `{ colors?, hyperlinks?, /// light?, columns? }`. By default colors are enabled, hyperlinks are diff --git a/test/js/bun/md/md-edge-cases.test.ts b/test/js/bun/md/md-edge-cases.test.ts index cc18a78e9d6e..1361551514d3 100644 --- a/test/js/bun/md/md-edge-cases.test.ts +++ b/test/js/bun/md/md-edge-cases.test.ts @@ -1243,10 +1243,6 @@ describe("inputs the parser cannot address", () => { }, stdout: "pipe", stderr: "inherit", - // An accepted 4 GiB input would take minutes to scan; if a regression - // accepts one of these lengths again, kill the child instead. - timeout: 20_000, - killSignal: "SIGKILL", }); const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); const message = (received: number) => @@ -1258,3 +1254,61 @@ describe("inputs the parser cannot address", () => { expect(exitCode).toBe(0); }, 30_000); }); + +describe("documents whose block metadata the parser cannot address", () => { + // Block offsets are u32s too, so `block_bytes` (the flat buffer of block + // headers and verbatim-line records) is capped independently of the input + // length. Filling the real ~4 GiB cap needs ~256M blocks, so the child + // shrinks it through `setMaxMarkdownBlockBytesForTesting` + // (bun:internal-for-testing) and proves the exact boundary: a document + // whose metadata lands exactly on the cap renders, and one more block (or + // the container openers of a nested blockquote) raises the catchable + // RangeError that replaced the release-build integer-cast panic. + test("a document needing more block metadata than the cap throws a RangeError", async () => { + const script = ` + import { setMaxMarkdownBlockBytesForTesting } from "bun:internal-for-testing"; + // One single-line paragraph costs exactly one 16-byte BlockHeader plus + // one 12-byte VerbatimLine in block_bytes, with no alignment padding. + const PARAGRAPH_BYTES = 16 + 12; + const AT_LIMIT = 40; + const paragraphs = n => Array.from({ length: n }, (_, i) => "p" + i).join("\\n\\n"); + const nestedQuotes = Buffer.alloc(128, "> ").toString() + "deep"; + const render = input => { + try { + return typeof Bun.markdown.html(input); + } catch (e) { + return [e.constructor.name, e.code, e.message].join(" | "); + } + }; + const results = []; + const previous = setMaxMarkdownBlockBytesForTesting(AT_LIMIT * PARAGRAPH_BYTES); + try { + results.push(render(paragraphs(AT_LIMIT))); + results.push(render(paragraphs(AT_LIMIT + 1))); + results.push(render(nestedQuotes)); + } finally { + setMaxMarkdownBlockBytesForTesting(previous); + } + // The restore took: the same over-limit documents render again. + results.push(render(paragraphs(AT_LIMIT + 1)), render(nestedQuotes)); + console.log(JSON.stringify(results)); + `; + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", script], + env: bunEnv, + stdout: "pipe", + stderr: "inherit", + }); + const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); + const tooManyBlocks = + "RangeError | ERR_OUT_OF_RANGE | markdown input requires more block metadata than the parser can address (4 GiB)"; + expect(JSON.parse(stdout.trim() || '"NO_OUTPUT"')).toEqual([ + "string", + tooManyBlocks, + tooManyBlocks, + "string", + "string", + ]); + expect(exitCode).toBe(0); + }, 30_000); +}); From fc66f1ff1d1e4883f5a91b00a67a13e0453a6f41 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 30 Jun 2026 09:29:42 +0000 Subject: [PATCH 7/7] markdown: only Container.block_byte_off stores a block offset as u32 BlockHeader.data carries block-type payloads (heading level, list start, fenced-code info offset into the source text), never an offset into block_bytes, so it does not justify the cap. --- src/md/parser.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/md/parser.rs b/src/md/parser.rs index 63d95d5140e9..40d651918e1b 100644 --- a/src/md/parser.rs +++ b/src/md/parser.rs @@ -171,10 +171,10 @@ pub(crate) const MAX_LOOKAHEAD: OFF = 1 + crate::line_analysis::CDATA_OPEN.len() /// never to wrap. pub const MAX_INPUT_LEN: usize = (OFF::MAX - MAX_LOOKAHEAD) as usize; -/// The most bytes `block_bytes` may hold: block offsets are -/// stored as `u32`s (`BlockHeader.data` links, `Container.block_byte_off`), -/// and each new header is written at the end of `block_bytes` rounded up to -/// its alignment, so the buffer must stop one aligned header short of +/// The most bytes `block_bytes` may hold: a block's offset into the buffer +/// is stored as a `u32` (`Container.block_byte_off` and the casts that feed +/// it), and each new header is written at the end of `block_bytes` rounded +/// up to its alignment, so the buffer must stop one aligned header short of /// `OFF::MAX`. pub(crate) const MAX_BLOCK_BYTES: usize = OFF::MAX as usize - (size_of::() + align_of::());