Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
50644fb
SVG import: shapes whose coordinates overflow to infinity or NaN are …
mbolling Nov 5, 2026
44b0399
LISP: a step's list walking and callback steps count against the slic…
mbolling Nov 5, 2026
f13a1f2
MTEXT: a relative height code grows no further than the largest absol…
mbolling Nov 5, 2026
16e0fa5
SVG import: an ellipse's major axis is relative to its centre, not a …
mbolling Nov 5, 2026
348d767
LISP: each synchronous callback's cap counts only its own steps
mbolling Nov 5, 2026
51f38b4
SVG import: a shape left out for overflowing coordinates still counts…
mbolling Nov 5, 2026
063cbef
SVG import: a shape whose extents overflow is left out too, not only …
mbolling Nov 5, 2026
f903621
LISP: the long-list slice test measures the walk's charge, not the ti…
mbolling Nov 5, 2026
6a240a7
SVG import: the finiteness check names every entity kind, so a new on…
mbolling Nov 5, 2026
f24da7a
SVG import: shapes too large to represent are noted as invalid, apart…
mbolling Nov 5, 2026
b1a34dc
SVG import: a rotated or sheared ellipse keeps the orientation of its…
mbolling Nov 5, 2026
6f862d7
SVG import: a tiny sheared ellipse keeps the axes of its image
mbolling Nov 5, 2026
ed85558
LISP: a routine is charged the work its slices did
mbolling Nov 5, 2026
31866fc
Merge remote-tracking branch 'origin/main' into parsers-hostile
mbolling Nov 10, 2026
797c5df
Merge remote-tracking branch 'origin/main' into parsers-hostile
mbolling Nov 11, 2026
a39d637
Merge remote-tracking branch 'origin/main' into parsers-hostile
mbolling Nov 18, 2026
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
43 changes: 29 additions & 14 deletions crates/engine/src/lisp/eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,30 +175,40 @@ pub struct Machine {
stack: Vec<Frame>,
state: State,
need: Option<Need>,
/// Steps the last [`Machine::run`] took, with the work done inside them.
pub(crate) used: u64,
}

impl Machine {
/// A machine evaluating `forms` in turn.
pub fn forms(forms: Vec<Value>) -> Machine {
Machine { stack: vec![Frame::Forms { rest: forms.into_iter().rev().collect() }], state: State::Ret(Value::Nil), need: None }
Machine { stack: vec![Frame::Forms { rest: forms.into_iter().rev().collect() }], state: State::Ret(Value::Nil), need: None, used: 0 }
}

/// A machine calling `f` with `args`.
pub fn calling(f: Value, args: Vec<Value>) -> Machine {
Machine { stack: Vec::new(), state: State::Call(f, args), need: None }
Machine { stack: Vec::new(), state: State::Call(f, args), need: None, used: 0 }
}

/// Give the value a [`Need`] waited for, and carry on.
pub fn resume(&mut self, v: Value) {
self.state = State::Ret(v);
}

/// Run until done, waiting, or `budget` steps.
/// Run until done, waiting, or `budget` steps. A step that walks a long list (`length`) or
/// runs a synchronous callback counts that work too, so one slice stays short.
pub fn run(&mut self, ctx: &mut Ctx<'_>, budget: u64) -> Outcome {
let mut n = 0u64;
let outcome = self.run_counted(ctx, budget, &mut n);
// The last step's work too, so nothing is left for the next run.
self.used = n.saturating_add(super::value::take_work());
outcome
}

fn run_counted(&mut self, ctx: &mut Ctx<'_>, budget: u64, n: &mut u64) -> Outcome {
loop {
n += 1;
if n > budget {
*n = n.saturating_add(1).saturating_add(super::value::take_work());
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if *n > budget {
return Outcome::Wait(Need::Yield);
}
let r = match std::mem::replace(&mut self.state, State::Ret(Value::Nil)) {
Expand Down Expand Up @@ -654,23 +664,28 @@ impl Ctx<'_> {
// loop inside a comparator or predicate terminates with an error rather than hanging the
// thread and bypassing the blocking execution cap (CWE-400).
let mut spent: u64 = 0;
loop {
let result = loop {
let remaining = cap.saturating_sub(spent);
if remaining == 0 {
return Err(LispError::new(format!("callback stopped after {cap} steps")));
break Err(LispError::new(format!("callback stopped after {cap} steps")));
}
let slice = remaining.min(SYNC_SLICE);
match m.run(&mut sub, slice) {
Outcome::Done(v) => return Ok(v),
Outcome::Error(e) => return Err(e),
let outcome = m.run(&mut sub, slice);
spent = spent.saturating_add(m.used);
match outcome {
Outcome::Done(v) => break Ok(v),
Outcome::Error(e) => break Err(e),
Outcome::Wait(Need::Yield) => {
spent = spent.saturating_add(slice);
if spent >= cap {
return Err(LispError::new(format!("callback stopped after {cap} steps")));
break Err(LispError::new(format!("callback stopped after {cap} steps")));
}
}
Outcome::Wait(_) => return Err(LispError::new("this function can't ask for input here")),
Outcome::Wait(_) => break Err(LispError::new("this function can't ask for input here")),
}
}
};
// Its steps, nested callbacks' included, are work done inside the caller's one step: they
// count against every enclosing callback's cap and slice.
super::value::charge_work(spent);
result
}
}
57 changes: 57 additions & 0 deletions crates/engine/src/lisp/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,63 @@ fn synchronous_callback_loop_is_an_error_not_a_hang() {
assert_eq!(ok(&mut s, "(vl-sort '(3 1 2) '<)"), "(1 2 3)");
}

/// A step that walks a long list counts its work: an endless loop over one gives frames.
#[test]
fn walking_a_long_list_counts_against_the_slice() {
let _heavy = super::value::HEAVY_CELLS.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
// Each `length` is one step walking 131072 cells: a 400000-step slice was 5e10 cells, no frame.
let r = s.lisp_eval("(setq l '(1)) (repeat 17 (setq l (append l l))) (while t (length l))", false, false, Vec::new()).unwrap();
assert!(r.is_none(), "the routine gave the interface a frame");
for _ in 0..20 {
assert!(s.lisp_busy());
s.lisp_tick();
}
s.lisp_abort("Function cancelled");
assert!(!s.lisp_running());
assert_eq!(ok(&mut s, "(setq l nil) (+ 1 2)"), "3");
}

/// A run's last step walking a long list is charged to that run, not left for the next one: here
/// it fails after the walk (a list of numbers isn't a list of strings), so no step follows it.
#[test]
fn the_last_steps_list_walk_is_charged_to_its_run() {
let _heavy = super::value::HEAVY_CELLS.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
let mut env = super::Env::default();
env.globals.insert(super::value::Sym::new("L"), Value::list(vec![Value::Int(1); 100_000]));
let mut m = super::eval::Machine::forms(super::read::read_all("(acad_strlsort l)").unwrap());
let mut ctx = super::eval::Ctx { s: &mut s, env: &mut env, depth: 0 };
assert!(matches!(m.run(&mut ctx, u64::MAX), super::eval::Outcome::Error(_)));
assert!(m.used > 100_000, "{}", m.used);
assert_eq!(super::value::take_work(), 0, "nothing is left for the next run");
}

/// Nested callbacks share one cap: an inner endless callback retried by an outer one stops.
#[test]
fn nested_callback_steps_count_against_the_outer_callback() {
let mut s = session();
s.lisp.limits.callback_steps = 10_000;
// Each level retried the endless level inside it with a fresh cap: 10000^3 steps, a hang.
let code = "(defun g (a b) (while t)) \
(defun f (a b) (while t (vl-catch-all-apply 'vl-sort (list '(1 2) 'g)))) \
(defun h (a b) (while t (vl-catch-all-apply 'vl-sort (list '(1 2) 'f)))) \
(vl-sort '(1 2) 'h)";
assert_eq!(eval(&mut s, code), Err("callback stopped after 10000 steps".into()));
// A callback's own steps count once, however many slices it runs in: three slices do three
// times the work of one.
let counts: Vec<u64> = [400_000, 1_200_000]
.into_iter()
.map(|cap| {
s.lisp.limits.callback_steps = cap;
ok(&mut s, "(setq n 0)");
assert!(eval(&mut s, "(vl-remove-if '(lambda (x) (while t (setq n (1+ n)))) '(1))").is_err());
ok(&mut s, "n").parse().unwrap()
})
.collect();
assert!(counts[1] * 10 >= counts[0] * 29, "{counts:?}");
}

/// A zero-step callback limit prevents even the first callback side effect.
#[test]
fn a_zero_callback_budget_does_not_run_the_callback() {
Expand Down
18 changes: 17 additions & 1 deletion crates/engine/src/lisp/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ thread_local! {
static STRING_BYTES: Cell<(u64, u64)> = const { Cell::new((0, STRING_BUDGET)) };
/// The running slice's cap on live cons cells.
static CELL_LIMIT: Cell<usize> = const { Cell::new(MAX_CELLS) };
/// Work done inside the current machine step: list cells walked, steps of synchronous callbacks.
static WORK: Cell<u64> = const { Cell::new(0) };
}

/// Start a slice of a run on this thread: it fails when more than `limit` cells are alive.
Expand All @@ -76,6 +78,16 @@ pub fn check_cells() -> Result<(), LispError> {
if live_cells() > CELL_LIMIT.with(Cell::get) { Err(LispError::quit("out of memory: too many list cells")) } else { Ok(()) }
}

/// Count `n` units of work done inside one machine step ([`super::eval::Machine::run`] charges them as steps).
pub fn charge_work(n: u64) {
WORK.with(|c| c.set(c.get().saturating_add(n)));
}

/// The work counted since the last call.
pub fn take_work() -> u64 {
WORK.with(|c| c.replace(0))
}

/// Start a slice of a run on this thread: it has made `used` bytes of its `budget`.
pub fn set_string_budget(used: u64, budget: u64) {
STRING_BYTES.with(|c| c.set((used, budget)));
Expand Down Expand Up @@ -262,7 +274,10 @@ impl Value {
loop {
match v {
Value::Nil => return true,
Value::Cons(c) => v = c.cdr.clone(),
Value::Cons(c) => {
charge_work(1);
v = c.cdr.clone();
}
_ => return false,
}
}
Expand Down Expand Up @@ -318,6 +333,7 @@ impl Iterator for ListIter {
fn next(&mut self) -> Option<Value> {
match std::mem::take(&mut self.next) {
Value::Cons(c) => {
charge_work(1);
self.next = c.cdr.clone();
Some(c.car.clone())
}
Expand Down
17 changes: 15 additions & 2 deletions crates/fonts/src/mtext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,8 @@ enum Atom {

/// Upper bound on parsed atoms (hostile contents).
const MAX_ATOMS: usize = 200_000;
/// Largest height `\H` sets; a relative one (`\H1000x;` again and again) grows no further.
const MAX_HEIGHT: f64 = 1e6;
/// Scale of stacked text relative to the surrounding text.
const STACK_SCALE: f64 = 0.7;

Expand Down Expand Up @@ -341,8 +343,8 @@ fn parse(contents: &str, base: Fmt) -> (Vec<Atom>, Vec<Fmt>) {
Some(r) => (true, num(r)),
None => (false, num(&a)),
};
if let Some(v) = v.filter(|v| *v > 0.0 && *v < 1e6) {
derive(&mut fmts, &mut cur, &|f| f.height = if rel { f.height * v } else { v });
if let Some(v) = v.filter(|v| *v > 0.0 && *v < MAX_HEIGHT) {
derive(&mut fmts, &mut cur, &|f| f.height = if rel { (f.height * v).min(MAX_HEIGHT.max(f.height)) } else { v });
}
}
'W' => {
Expand Down Expand Up @@ -976,6 +978,17 @@ mod tests {
assert_eq!(lay(&"ภาษาไทย".repeat(20_000), 3.0).lines.len(), 1);
}

#[test]
fn compounding_relative_heights_stay_finite() {
// Each `\H1000x;` multiplied the height again: 1000^200 is infinite, and so was the layout.
let grow = "\\H1000x;".repeat(200);
for s in [format!("{grow}ab cd\\Pef"), format!("\\pxi1,t2;{grow}ab\tcd\\Pef")] {
let l = lay(&s, 10.0);
assert!(l.strokes.iter().flatten().all(|p| p.x.is_finite() && p.y.is_finite()), "{s}");
assert!(l.bounds.min.is_finite() && l.bounds.max.is_finite(), "{s}");
}
}

/// Thai writes no spaces between words: a long line wraps between words, in the plain and the
/// paragraph layout, without fonts installed (the line breaks don't depend on glyph widths).
#[test]
Expand Down
21 changes: 20 additions & 1 deletion crates/io/src/svg_read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ enum LeftOut {
Use,
Style,
RoundedCorners,
TooLarge,
}

impl LeftOut {
Expand All @@ -166,6 +167,7 @@ impl LeftOut {
Self::Use => ("`<use>` copy", "`<use>` copies"),
Self::Style => ("`<style>` sheet (its class rules aren't applied)", "`<style>` sheets (their class rules aren't applied)"),
Self::RoundedCorners => ("rectangle with rounded corners (drawn square)", "rectangles with rounded corners (drawn square)"),
Self::TooLarge => ("shape with coordinates too large to represent", "shapes with coordinates too large to represent"),
};
format!("{n} {}", if n == 1 { one } else { many })
}
Expand Down Expand Up @@ -354,6 +356,11 @@ impl Parser {
if self.elements > MAX_ELEMENTS {
return Err(IoError::Format(format!("SVG: more than {MAX_ELEMENTS} elements")));
}
// Finite numbers can still overflow through transforms and relative steps (`l1e308 0` twice).
if !finite(&kind) {
self.left_out(LeftOut::TooLarge);
return Ok(());
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
// Charge the vertices this entity retains against the shared document budget, so repeated
// flattened arcs/curves cannot amplify a compact path into unbounded geometry (CWE-400).
let verts = match &kind {
Expand Down Expand Up @@ -435,7 +442,7 @@ impl Parser {
v / l
};
let ratio = (l_min.max(0.0).sqrt() / s_max).clamp(1e-9, 1.0);
let major = center + axis * s_max;
let major = axis * s_max;
self.add(EntityKind::Ellipse(Ellipse { center: v3(center), major: v3(major), ratio, start: 0.0, end: std::f64::consts::TAU }))
}

Expand Down Expand Up @@ -581,6 +588,18 @@ impl Parser {
}
}

/// Every coordinate of an entity the reader makes is finite.
fn finite(kind: &EntityKind) -> bool {
match kind {
EntityKind::Line(l) => l.a.is_finite() && l.b.is_finite(),
EntityKind::Circle(c) => c.center.is_finite() && c.radius.is_finite(),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
EntityKind::Ellipse(e) => e.center.is_finite() && e.major.is_finite() && e.ratio.is_finite(),
EntityKind::LwPolyline(p) => p.vertices.iter().all(|v| v.p.is_finite() && v.bulge.is_finite()),
EntityKind::Spline(s) => s.control.iter().all(|p| p.is_finite()),
_ => true,
}
}

/// The element is not rendered (`display="none"`, or a style that says so).
fn hidden(e: &BytesStart) -> bool {
if attr(e, b"display").as_deref() == Some("none") {
Expand Down
30 changes: 29 additions & 1 deletion crates/io/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2328,12 +2328,26 @@ fn svg_shapes_become_entities_in_millimetres() {
let c = first(&d, |k| if let EntityKind::Circle(c) = k { Some(c.clone()) } else { None });
assert!((c.radius - 2.0).abs() < 1e-9 && (c.center.x - 10.0).abs() < 1e-9 && (c.center.y - 5.0).abs() < 1e-9, "{c:?}");
let e = first(&d, |k| if let EntityKind::Ellipse(e) = k { Some(e.clone()) } else { None });
let major = Vec2::new(e.major.x - e.center.x, e.major.y - e.center.y);
let major = Vec2::new(e.major.x, e.major.y);
assert!((major.len() - 4.0).abs() < 1e-9 && (e.ratio - 0.5).abs() < 1e-9, "{e:?}");
let l = first(&d, |k| if let EntityKind::Line(l) = k { Some(l.clone()) } else { None });
assert!((l.a.y - 10.0).abs() < 1e-9 && (l.b.y).abs() < 1e-9, "{l:?}");
}

#[test]
fn svg_ellipse_major_axis_is_relative_to_its_centre() {
// Away from the origin: the major axis was stored as the absolute point centre + axis.
let svg = format!("{SVG_PAGE}<ellipse cx=\"15\" cy=\"2\" rx=\"2\" ry=\"1\"/><circle cx=\"15\" cy=\"2\" r=\"1\"/></svg>");
let d = read(svg.as_bytes(), "ellipse.svg").unwrap();
assert_eq!(kinds(&d), ["Ellipse", "Circle"]);
let e = first(&d, |k| if let EntityKind::Ellipse(e) = k { Some(e.clone()) } else { None });
assert!((e.center - Vec3::new(15.0, 8.0, 0.0)).len() < 1e-9, "{e:?}");
assert!((e.major.x.abs() - 2.0).abs() < 1e-9 && e.major.y.abs() < 1e-9 && e.major.z == 0.0, "{e:?}");
assert!((e.ratio - 0.5).abs() < 1e-9, "{e:?}");
let c = first(&d, |k| if let EntityKind::Circle(c) = k { Some(c.clone()) } else { None });
assert!((c.center - Vec3::new(15.0, 8.0, 0.0)).len() < 1e-9 && (c.radius - 1.0).abs() < 1e-9, "{c:?}");
}

#[test]
fn svg_path_lines_curves_and_arcs() {
let svg = format!("{SVG_PAGE}<path d=\"M1 1 L5 1 C6 1 7 2 8 3\"/><path d=\"M0 0 A5 5 0 0 1 10 0 Z\"/></svg>");
Expand Down Expand Up @@ -2514,6 +2528,20 @@ fn svg_hostile_input_errors_without_panicking() {
assert!(deep.is_err(), "200 nested groups are refused, not walked");
}

#[test]
fn svg_coordinates_that_overflow_are_left_out() {
// Every number is finite; relative steps and transforms overflow them to infinity or NaN.
let svg = format!(
"{SVG_PAGE}<path d=\"M1e308 0 l1e308 0\"/><rect x=\"1e308\" width=\"1e308\" height=\"1\"/>\
<g transform=\"scale(1e308)\"><line x1=\"1e308\" y1=\"0\" x2=\"1\" y2=\"1\"/><circle r=\"1e308\"/></g>\
<g transform=\"scale(1e308,1)\"><ellipse rx=\"1e308\" ry=\"1\"/><path d=\"M0 0 C1e308 0 1 1 2 2\"/></g>\
<line x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\"/></svg>"
);
let d = read(svg.as_bytes(), "huge.svg").unwrap();
assert_eq!(kinds(&d), ["Line"]);
assert_eq!(d.read_notes, ["SVG: CADCraft doesn't read these yet, so they were left out: 6 shapes with coordinates too large to represent"]);
}

#[test]
fn svg_no_geometry_yields_an_empty_drawing() {
let svg = format!("{SVG_PAGE}</svg>");
Expand Down
Loading