Skip to content

Limits and hostile input

If you parse pages you didn’t write, some of them will be built to hurt you, and some will hurt you by accident. This page covers the three limits Parsec gives you, which inputs it handles in linear time and why, and where it doesn’t yet.

The HTML Standard’s tree builder does real work per tag. Asking whether a <p> is “in button scope” means walking the stack of open elements; the adoption agency algorithm, which repairs misnested formatting like <b><i></b></i>, walks the list of active formatting elements and the stack; reconstructing formatting after a block can clone a whole list of elements. Each of those is cheap on a normal page and costs time proportional to depth or list length on a page made of nothing but nesting. Multiply that by the number of tags and you get a parser whose time grows with the square of the input.

Here’s the arithmetic. Say a page is $n$ nested tags, and the $k$-th tag costs a walk down a stack $k$ elements deep. The whole parse then costs

$$1 + 2 + \cdots + n = \frac{n(n+1)}{2},$$

which is quadratic: double $n$ and the time goes up four times. If each tag costs a constant $c$ instead, however deep the stack, the parse costs $cn$, and doubling the page only doubles the time. The rest of this page is about keeping Parsec on the $cn$ side.

Lexbor shows what that looks like. In lexbor#340, <b>×n <i>×n x</b>×n takes 29 seconds at n = 4,000 (82 KB), and at n = 10,000 (208 KB) it ran a 32 GB machine out of memory after about ten minutes; 40,000 nested <div>s (200 KB) take 1.7 seconds, from an unbounded walk in lxb_html_tree_element_in_scope(). The same thread notes that Gumbo caps nesting at 400 and that Chromium caps it too. Lexbor has no limit option of any kind.

parse_with takes an Options::budget. When it runs out, you get ParseError::Timeout { budget, parsed } and no document. Parsing has the details: the clock is checked every 4,096 steps of the tokenizer, so the limit is approximate, and the partial tree is thrown away.

Pick it from what a page is worth to you, not from what parsing usually takes; a normal page finishes far inside any budget you’d choose, so the budget only ever fires on the pages you’d want to drop anyway.

use parsec::{Options, ParseError, parse_with};
use std::time::Duration;
fn parse_untrusted(html: &str) -> Option<parsec::Document> {
let options = Options {
budget: Some(Duration::from_secs(1)),
..Options::default()
};
match parse_with(html, options) {
Ok(doc) => Some(doc),
Err(ParseError::Timeout { parsed, .. }) => {
eprintln!("dropped a page after {parsed} bytes");
None
}
Err(ParseError::TooLarge { len }) => {
eprintln!("dropped a {len}-byte page");
None
}
}
}
fn main() {
assert!(parse_untrusted("<p>hello").is_some());
}

parse and parse_fragment have no budget. For a fragment, use parse_fragment_with, which takes the same Options (Parsing).

MAX_INPUT is 536,870,912 bytes (512 MiB). Over that, parse_with and parse_fragment_with return ParseError::TooLarge, and parse and parse_fragment panic. It exists because strings are stored as 32-bit offsets with flag bits on top (Architecture), not as a memory policy. If you want a smaller cap, check html.len() yourself before parsing.

There’s no memory limit. Memory grows with the input: the document reserves space in proportion to the input’s length up front (about one node per 24 bytes, plus buffers), then grows as needed.

Options::max_depth caps how deep the tree gets. Once more than max_depth elements are open, counting <html>, the next node goes beside the current element instead of inside it. That’s the rule Chromium follows at a depth of 512 (its AttachLater).

Only where nodes go changes. The parse itself carries on exactly as before: the stack of open elements is untouched, end tags close what they always closed, and every element and every piece of text is still in the document, just flatter. Two places keep their own rules: foster-parented content still goes before its table, and a template’s contents still go into its contents.

use parsec::{Options, parse_with};
let html = "<div><div><div><p>x</p></div></div></div>";
let options = Options { max_depth: Some(4), ..Options::default() };
let doc = parse_with(html, options).unwrap();
// <html>, <body> and two <div>s are open, so the third <div> is the last
// to go inside. The <p> and its text go beside it.
assert_eq!(
doc.inner_html(doc.root()),
"<html><head></head><body><div><div><div></div><p></p>x</div></div></body></html>"
);

The default is None, no limit, which builds the tree the HTML Standard describes. Set one when your own code walks the tree recursively, so a page can’t decide how deep that recursion goes. It works the same way in parse_fragment_with.

crates/parsec/examples/hostile.rs builds eight inputs designed to be slow and times each one.

The eight hostile inputs, with their sizes
Name Input Size
unclosed divs <div> × 80,000 390 KB
unclosed tables <table> × 40,000 273 KB
nested inline <span> × 80,000 468 KB
formatting then paragraphs 300 distinct <b class=cN> tags, then <p>x × 3,000 15 KB
distinct formatting per p <p><b><i><u><s><em><strong><tt><code><big><small><strike> × 5,000 278 KB
misnested a <a><p><a>x</p> × 20,000 273 KB
adoption <b><div><b><div> × 10,000 156 KB
table foster <table> then x<td>y × 50,000 292 KB

Run it with:

Terminal window
cargo run --release --example hostile

It prints each input’s size, the time and the node count. Doubling or quadrupling any of these doubles or quadruples the time, give or take noise: the cost is linear in the input.

The spec’s algorithms are the same in every parser; what differs is how much each step costs. Parsec’s tree builder (crates/parsec/src/tree.rs) keeps a little extra state so that the common worst cases are constant-time per tag:

  • Counts of open elements by tag. The builder keeps, for each of its 124 known tags, how many HTML elements of that tag are open. “Is there a <p> in button scope?” is answered at once when no <p> is open at all, however deep the stack, which is what makes 80,000 unclosed <div>s cheap. (counts, and in_scope.)
  • A flag per node for “on the stack of open elements”. Reconstructing active formatting elements and the adoption agency both ask whether an element is still open. That’s one lookup instead of a walk down the stack. (on_stack, and open_contains.)
  • The spec’s own bounds, kept. The adoption agency’s outer loop runs at most 8 times and its inner loop drops formatting elements after the third, as the spec says, and the “Noah’s Ark” clause keeps at most three identical formatting elements after the last marker. These are what stop <b> repeated thousands of times from rebuilding thousands of elements at every paragraph.
  • A signature per formatting element. The Noah’s Ark check compares each new formatting element with every entry in the list since the last marker. Each element gets a hash of its namespace, name and attributes (in any order), worked out once and handed on to the copies reconstruction makes, so the check compares one number per entry and does the full comparison only when two agree. With 300 different <b class=cN> open, that turned 45,000 attribute-by-attribute comparisons into 45,000 number comparisons. (signature, and push_active.)
  • Text that doesn’t get copied again and again. When text is added to a text node whose string isn’t at the end of the parse buffer, the string moves to an allocation of its own once, rather than being copied to the end on every append. Without that, <body x> repeated between runs of text made memory grow with the square of the input; there’s a test for it in tree.rs’s hostile module. (Document::append_text in dom.rs.)

And outside the tree builder:

  • No recursion where depth comes from the page. Serialization, text and select walk the tree with their own stack or with the tree’s links, so a tree tens of thousands of levels deep doesn’t overflow a thread’s stack. A test serializes 20,000 nested <div>s on a 256 KB stack.
  • A nesting limit on selectors. Selector parsing and matching do recurse, so functional pseudo-classes nest at most 32 deep (see Selectors).

And in CSS, where a stylesheet can nest and multiply itself:

  • A nesting limit on stylesheets. The CSS parser doesn’t recurse, but plenty of what reads its output does, a derived clone() and the cascade among them. So functions, blocks and rules nest at most 256 deep, counted together (parsec_css::MAX_NESTING). Anything that would open deeper is skipped whole as it’s read, and a rule dropped that way is an InvalidRule error. The cascade then looks at most 128 rules deep.
  • A byte cap on var(). Each custom property can refer to the one before it twice, and the value doubles at every step. A substituted value may copy in 1 MiB of the stylesheet at most; past that it’s invalid at computed-value time, as the spec lets a browser decide.
  • A cap on nested selectors. A nested rule writes its parent’s selectors into its own, and & & doubles them per level. A nested rule’s selectors stop at 64 KiB with their parents written in; past that, the rule and everything in it is ignored. A lone parent goes in as it is, div p, rather than as :is(div) p: the two match the same elements with the same specificity, and nested :is()s cost twice as much to match at every level.
  • Cascade layers in a map, and names 64 parts long at most, so @layer a.a.a… doesn’t scan every name for every part.
  • Declarations given up on early. In a block, a{}a{}… used to be read to the end of the input for every a, looking for the ; that would make it a declaration. The parser now stops as soon as what it has read can’t be one.

Not every input is. Some patterns still make the tree builder walk the stack of open elements, or an element’s ancestors, for every tag, as the spec describes those steps: certain kinds of end tags under very deep nesting are the main ones. On those, time grows with depth multiplied by the number of tags, as it does in Lexbor and in any parser that follows the algorithm step by step.

The time budget is what protects you there: it turns a slow page into an error, and the size cap bounds how long the input can be. The depth limit keeps the tree shallow, but it doesn’t make those walks shorter, because the stack of open elements is as deep as it would be without it. New inputs that turn out slow go into hostile.rs with the fix that makes them linear.

A fuzz target (crates/parsec/fuzz/fuzz_targets/parse.rs) parses arbitrary bytes, lossily decoded, as a document and as a fragment in one of 13 contexts, with scripting on or off, and checks that every node is reached from the root exactly once and that every child’s parent link agrees. CI runs it nightly for five minutes on inputs of up to 4,096 bytes. Contributing shows how to run it yourself.