From 7b51909d40deb15397ec90695dc611bde5d13e34 Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Sun, 15 Nov 2026 10:28:08 -0500 Subject: [PATCH 1/6] shx: preserve CADCraft shape compiler and errors Original source by Francesco BV in cadcraft52c1e6de, copied from main7064a685. App font lookup, text layout and glyph interpretation are not moved. --- crates/shx/src/compile.rs | 313 ++++++++++++++++++++++++++++++++++++++ crates/shx/src/error.rs | 29 ++++ 2 files changed, 342 insertions(+) create mode 100644 crates/shx/src/compile.rs create mode 100644 crates/shx/src/error.rs diff --git a/crates/shx/src/compile.rs b/crates/shx/src/compile.rs new file mode 100644 index 000000000..2e8cb3c25 --- /dev/null +++ b/crates/shx/src/compile.rs @@ -0,0 +1,313 @@ +//! Shape source (`.shp`) to a compiled SHX file, as COMPILE does. +//! +//! A source is a list of definitions: a header line `*number,defbytes,NAME` followed by its +//! specification bytes (on as many lines as needed, ending with 0). Numbers are decimal, or +//! hexadecimal after a leading `0` (`012`, `08cfb`); parentheses only group; `;` starts a +//! comment. A big font starts with `*BIGFONT nchars,nranges,first,last,…` and a Unicode font +//! with `*UNIFONT,6,name` followed by `above,below,modes,encoding,type,0`. Shape 0 is a text +//! font's record (`above,below,modes,0`). +//! +//! Operands are encoded by what they are: a subshape number takes two bytes in a Unicode font +//! (and after `7,0` in a big font), displacements and bulges are two's complement, and an arc's +//! direction byte (`-043`) keeps its sign in the high bit. `defbytes` is not checked: the +//! program's own length is written. + +use super::ShxError; +use super::parse::{BIGFONT, SHAPES_10, UNIFONT}; + +/// Largest source compiled. +const MAX_SOURCE: usize = 8 << 20; + +#[derive(Clone, Copy, PartialEq)] +enum Kind { + Shapes, + Big, + Uni, +} + +struct Shape { + number: u16, + name: String, + program: Vec, +} + +/// A number token: value (sign included). +fn number(tok: &str, line: usize) -> Result { + let t: String = tok.chars().filter(|c| !matches!(c, '(' | ')') && !c.is_whitespace()).collect(); + let (neg, digits) = match t.strip_prefix('-') { + Some(d) => (true, d), + None => (false, t.strip_prefix('+').unwrap_or(&t)), + }; + let err = || ShxError::Source(line, format!("not a number: {tok:?}")); + let v = if digits.len() > 1 && digits.starts_with('0') { + i64::from_str_radix(digits.get(1..).unwrap_or_default(), 16).map_err(|_| err())? + } else { + digits.parse::().map_err(|_| err())? + }; + if v > 0xFFFF { + return Err(err()); + } + Ok(if neg { -v } else { v }) +} + +/// The comma-separated numbers of a line (comment removed, blank fields skipped). +fn numbers(text: &str, line: usize) -> Result, ShxError> { + text.split(',').map(str::trim).filter(|t| !t.is_empty() && *t != "(" && *t != ")").map(|t| number(t, line)).collect() +} + +/// The spec-byte encoder: walks the tokens as the reader walks the bytes. +struct Enc<'a> { + toks: &'a [i64], + i: usize, + out: Vec, + kind: Kind, + line: usize, +} + +impl Enc<'_> { + fn next(&mut self) -> Result { + let v = self.toks.get(self.i).copied().ok_or_else(|| ShxError::Source(self.line, "the shape ends inside a command".into()))?; + self.i += 1; + Ok(v) + } + fn byte(&mut self) -> Result<(), ShxError> { + let v = self.next()?; + let b = u8::try_from(v).map_err(|_| ShxError::Source(self.line, format!("{v} is not a byte")))?; + self.out.push(b); + Ok(()) + } + /// Two's complement −128..127. + fn signed(&mut self) -> Result { + let v = self.next()?; + let b = i8::try_from(v).map_err(|_| ShxError::Source(self.line, format!("{v} is not −128..127")))?; + self.out.extend(b.to_le_bytes()); + Ok(v) + } + /// Sign in the high bit (an arc's direction byte). + fn sign_magnitude(&mut self) -> Result<(), ShxError> { + let v = self.next()?; + let m = u8::try_from(v.unsigned_abs()) + .ok() + .filter(|m| *m < 0x80) + .ok_or_else(|| ShxError::Source(self.line, format!("{v} is not an octant byte")))?; + self.out.push(if v < 0 { m | 0x80 } else { m }); + Ok(()) + } + fn word(&mut self) -> Result<(), ShxError> { + let v = self.next()?; + let w = u16::try_from(v).map_err(|_| ShxError::Source(self.line, format!("{v} is not a shape number")))?; + self.out.extend(w.to_be_bytes()); + Ok(()) + } + + fn program(mut self) -> Result, ShxError> { + while self.i < self.toks.len() { + let code = self.next()?; + let c = u8::try_from(code).map_err(|_| ShxError::Source(self.line, format!("{code} is not a code")))?; + self.out.push(c); + match c { + 0 => break, + 3 | 4 => self.byte()?, + 7 => match self.kind { + Kind::Uni => self.word()?, + Kind::Big => { + let first = self.toks.get(self.i).copied().unwrap_or(0); + if first == 0 { + self.byte()?; + self.word()?; + for _ in 0..4 { + self.byte()?; + } + } else { + self.byte()?; + } + } + Kind::Shapes => self.byte()?, + }, + 8 => { + self.signed()?; + self.signed()?; + } + 9 => loop { + let (x, y) = (self.signed()?, self.signed()?); + if x == 0 && y == 0 { + break; + } + }, + 10 => { + self.byte()?; + self.sign_magnitude()?; + } + 11 => { + for _ in 0..4 { + self.byte()?; + } + self.sign_magnitude()?; + } + 12 => { + for _ in 0..3 { + self.signed()?; + } + } + 13 => loop { + let (x, y) = (self.signed()?, self.signed()?); + if x == 0 && y == 0 { + break; + } + self.signed()?; + }, + _ => {} + } + } + if self.out.last() != Some(&0) { + self.out.push(0); + } + Ok(self.out) + } +} + +/// Compile shape source into an SHX file (a shape file or text font, a big font, or a Unicode +/// font, as its first definition says). +pub fn compile(source: &str) -> Result, ShxError> { + if source.len() > MAX_SOURCE { + return Err(ShxError::TooLarge); + } + let mut kind = Kind::Shapes; + let mut ranges: Vec<(u16, u16)> = Vec::new(); + let mut uni_info: Option<(String, Vec)> = None; + // Definitions: header (number, name, line) and the numbers that follow it. + let mut defs: Vec<(i64, String, usize, Vec)> = Vec::new(); + let mut uni_header_pending = false; + for (no, raw) in source.lines().enumerate() { + let line = no + 1; + let text = raw.split(';').next().unwrap_or_default().trim(); + if text.is_empty() { + continue; + } + if let Some(head) = text.strip_prefix('*') { + let upper = head.trim_start().to_ascii_uppercase(); + if let Some(rest) = upper.strip_prefix("BIGFONT") { + kind = Kind::Big; + let v = numbers(rest, line)?; + let n = usize::try_from(v.get(1).copied().unwrap_or(0)).unwrap_or(0); + for k in 0..n { + let lo = v.get(2 + 2 * k).copied().unwrap_or(0); + let hi = v.get(3 + 2 * k).copied().unwrap_or(lo); + let to = |x: i64| u16::try_from(x).map_err(|_| ShxError::Source(line, "bad escape range".into())); + ranges.push((to(lo)?, to(hi)?)); + } + continue; + } + if upper.starts_with("UNIFONT") { + kind = Kind::Uni; + let name = head.splitn(3, ',').nth(2).unwrap_or_default().trim().to_string(); + uni_info = Some((name, Vec::new())); + uni_header_pending = true; + continue; + } + uni_header_pending = false; + let mut parts = head.splitn(3, ','); + let num = number(parts.next().unwrap_or_default().trim(), line)?; + let _defbytes = parts.next(); + let name = parts.next().unwrap_or_default().trim().to_string(); + defs.push((num, name, line, Vec::new())); + continue; + } + let v = numbers(text, line)?; + if uni_header_pending { + if let Some((_, info)) = uni_info.as_mut() { + for x in v { + info.push(u8::try_from(x).map_err(|_| ShxError::Source(line, "bad font record".into()))?); + } + } + continue; + } + match defs.last_mut() { + Some(d) => d.3.extend(v), + None => return Err(ShxError::Source(line, "specification bytes before any *number,defbytes,NAME line".into())), + } + } + let mut shapes: Vec = Vec::new(); + for (num, name, line, toks) in defs { + let number = u16::try_from(num).map_err(|_| ShxError::Source(line, format!("shape number {num} out of range")))?; + let program = if number == 0 { + // The font record: plain bytes. + toks.iter().map(|x| u8::try_from(*x).map_err(|_| ShxError::Source(line, "bad font record".into()))).collect::, _>>()? + } else { + Enc { toks: &toks, i: 0, out: Vec::new(), kind, line }.program()? + }; + if shapes.iter().any(|s| s.number == number) { + return Err(ShxError::Source(line, format!("shape {number} is defined twice"))); + } + shapes.push(Shape { number, name, program }); + } + if shapes.is_empty() { + return Err(ShxError::Empty); + } + shapes.sort_by_key(|s| s.number); + let record = |s: &Shape| -> Result, ShxError> { + let mut r: Vec = s.name.bytes().filter(|b| *b != 0).collect(); + r.push(0); + r.extend(&s.program); + if r.len() > usize::from(u16::MAX) { Err(ShxError::TooLarge) } else { Ok(r) } + }; + let count = u16::try_from(shapes.len()).map_err(|_| ShxError::TooLarge)?; + let len16 = |r: &[u8]| u16::try_from(r.len()).unwrap_or(u16::MAX); + let mut out = Vec::new(); + match kind { + Kind::Shapes => { + out.extend(SHAPES_10); + out.extend(shapes.first().map_or(0, |s| s.number).to_le_bytes()); + out.extend(shapes.last().map_or(0, |s| s.number).to_le_bytes()); + out.extend(count.to_le_bytes()); + let recs: Vec> = shapes.iter().map(record).collect::>()?; + for (s, r) in shapes.iter().zip(&recs) { + out.extend(s.number.to_le_bytes()); + out.extend(len16(r).to_le_bytes()); + } + for r in &recs { + out.extend(r); + } + out.extend(b"EOF"); + } + Kind::Big => { + out.extend(BIGFONT); + let nranges = u16::try_from(ranges.len()).map_err(|_| ShxError::TooLarge)?; + out.extend(count.to_le_bytes()); + out.extend(count.to_le_bytes()); + out.extend(nranges.to_le_bytes()); + for (lo, hi) in &ranges { + out.extend(lo.to_le_bytes()); + out.extend(hi.to_le_bytes()); + } + let recs: Vec> = shapes.iter().map(record).collect::>()?; + let mut off = out.len() + 8 * recs.len(); + for (s, r) in shapes.iter().zip(&recs) { + out.extend(s.number.to_le_bytes()); + out.extend(len16(r).to_le_bytes()); + out.extend(u32::try_from(off).map_err(|_| ShxError::TooLarge)?.to_le_bytes()); + off += r.len(); + } + for r in &recs { + out.extend(r); + } + } + Kind::Uni => { + out.extend(UNIFONT); + let (name, info) = uni_info.unwrap_or_default(); + out.extend((u32::from(count) + 1).to_le_bytes()); + let mut rec: Vec = name.bytes().filter(|b| *b != 0).collect(); + rec.push(0); + rec.extend(&info); + out.extend(len16(&rec).to_le_bytes()); + out.extend(&rec); + for s in &shapes { + let r = record(s)?; + out.extend(s.number.to_le_bytes()); + out.extend(len16(&r).to_le_bytes()); + out.extend(r); + } + } + } + Ok(out) +} diff --git a/crates/shx/src/error.rs b/crates/shx/src/error.rs new file mode 100644 index 000000000..0addd1c98 --- /dev/null +++ b/crates/shx/src/error.rs @@ -0,0 +1,29 @@ +/// Why a font file can't be read or a shape source can't be compiled. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ShxError { + /// Not an SHX file (unknown signature). + NotShx, + /// The file ends inside its header or index. + Truncated, + /// The file is larger, or has more of something, than CADCraft reads. + TooLarge, + /// The file is well-formed but holds no shape. + Empty, + /// Shape source error: line and message. + Source(usize, String), +} + +impl std::fmt::Display for ShxError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ShxError::NotShx => f.write_str("not an SHX shape or font file"), + ShxError::Truncated => f.write_str("the SHX file is truncated"), + ShxError::TooLarge => f.write_str("the SHX file is too large"), + ShxError::Empty => f.write_str("the SHX file has no shapes"), + ShxError::Source(line, msg) => write!(f, "line {line}: {msg}"), + } + } +} + +impl std::error::Error for ShxError {} + From b3307f7814629961841b80ab907116252e41b34d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 10:30:48 -0500 Subject: [PATCH 2/6] shx: expose shared bounded shape compiler with hostile-source tests --- Cargo.lock | 4 ++++ Cargo.toml | 1 + crates/shx/Cargo.toml | 11 +++++++++++ crates/shx/README.md | 8 ++++++++ crates/shx/src/compile.rs | 20 +++++++++++++++++--- crates/shx/src/error.rs | 1 - crates/shx/src/lib.rs | 8 ++++++++ crates/shx/tests/compiler.rs | 30 ++++++++++++++++++++++++++++++ 8 files changed, 79 insertions(+), 4 deletions(-) create mode 100644 crates/shx/Cargo.toml create mode 100644 crates/shx/README.md create mode 100644 crates/shx/src/lib.rs create mode 100644 crates/shx/tests/compiler.rs diff --git a/Cargo.lock b/Cargo.lock index add90f8c2..3e9aeba59 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2610,6 +2610,10 @@ dependencies = [ name = "craft-sheet" version = "0.1.0" +[[package]] +name = "craft-shx" +version = "0.1.0" + [[package]] name = "craft-silhouette-studio" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index eae758e17..b68880781 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/craft-libs" [workspace.dependencies] +craft-shx = { path = "crates/shx" } craft-smime = { path = "crates/smime" } craft-ber = { path = "crates/ber" } craft-proto = { path = "crates/proto" } diff --git a/crates/shx/Cargo.toml b/crates/shx/Cargo.toml new file mode 100644 index 000000000..012f9d2f9 --- /dev/null +++ b/crates/shx/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "craft-shx" +description = "Bounded SHP shape-source compiler for SHX shape, big-font and Unicode containers" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true diff --git a/crates/shx/README.md b/crates/shx/README.md new file mode 100644 index 000000000..691890447 --- /dev/null +++ b/crates/shx/README.md @@ -0,0 +1,8 @@ +# craft-shx + +Compiles SHP shape source into SHX shapes, big-font and Unicode containers. +Extracted from CADCraft by Francesco BV (cadcraft52c1e6de); no font assets are bundled. +App font discovery, text layout and glyph interpretation are not part of this crate. +The original 8 MiB source and u16 record bounds remain; malformed double signs, +excess escape ranges and oversized Unicode font records are refused. Duplicate +shape detection is linear rather than a repeated whole-list scan. diff --git a/crates/shx/src/compile.rs b/crates/shx/src/compile.rs index 2e8cb3c25..0d91a9545 100644 --- a/crates/shx/src/compile.rs +++ b/crates/shx/src/compile.rs @@ -13,7 +13,9 @@ //! program's own length is written. use super::ShxError; -use super::parse::{BIGFONT, SHAPES_10, UNIFONT}; +const SHAPES_10: &[u8] = b"AutoCAD-86 shapes 1.0\r\n\x1a"; +const BIGFONT: &[u8] = b"AutoCAD-86 bigfont 1.0\r\n\x1a"; +const UNIFONT: &[u8] = b"AutoCAD-86 unifont 1.0\r\n\x1a"; /// Largest source compiled. const MAX_SOURCE: usize = 8 << 20; @@ -44,7 +46,7 @@ fn number(tok: &str, line: usize) -> Result { } else { digits.parse::().map_err(|_| err())? }; - if v > 0xFFFF { + if !(0..=0xFFFF).contains(&v) { return Err(err()); } Ok(if neg { -v } else { v }) @@ -190,6 +192,11 @@ pub fn compile(source: &str) -> Result, ShxError> { kind = Kind::Big; let v = numbers(rest, line)?; let n = usize::try_from(v.get(1).copied().unwrap_or(0)).unwrap_or(0); + // A big font has byte-valued lead ranges. Bound repeated headers too, + // so a tiny declaration cannot amplify into millions of ranges. + if n > 256 || ranges.len().saturating_add(n) > 256 { + return Err(ShxError::TooLarge); + } for k in 0..n { let lo = v.get(2 + 2 * k).copied().unwrap_or(0); let hi = v.get(3 + 2 * k).copied().unwrap_or(lo); @@ -210,6 +217,9 @@ pub fn compile(source: &str) -> Result, ShxError> { let num = number(parts.next().unwrap_or_default().trim(), line)?; let _defbytes = parts.next(); let name = parts.next().unwrap_or_default().trim().to_string(); + if defs.len() >= usize::from(u16::MAX) { + return Err(ShxError::TooLarge); + } defs.push((num, name, line, Vec::new())); continue; } @@ -228,6 +238,7 @@ pub fn compile(source: &str) -> Result, ShxError> { } } let mut shapes: Vec = Vec::new(); + let mut seen = std::collections::HashSet::new(); for (num, name, line, toks) in defs { let number = u16::try_from(num).map_err(|_| ShxError::Source(line, format!("shape number {num} out of range")))?; let program = if number == 0 { @@ -236,7 +247,7 @@ pub fn compile(source: &str) -> Result, ShxError> { } else { Enc { toks: &toks, i: 0, out: Vec::new(), kind, line }.program()? }; - if shapes.iter().any(|s| s.number == number) { + if !seen.insert(number) { return Err(ShxError::Source(line, format!("shape {number} is defined twice"))); } shapes.push(Shape { number, name, program }); @@ -296,6 +307,9 @@ pub fn compile(source: &str) -> Result, ShxError> { out.extend(UNIFONT); let (name, info) = uni_info.unwrap_or_default(); out.extend((u32::from(count) + 1).to_le_bytes()); + if name.len().saturating_add(1).saturating_add(info.len()) > usize::from(u16::MAX) { + return Err(ShxError::TooLarge); + } let mut rec: Vec = name.bytes().filter(|b| *b != 0).collect(); rec.push(0); rec.extend(&info); diff --git a/crates/shx/src/error.rs b/crates/shx/src/error.rs index 0addd1c98..135214f54 100644 --- a/crates/shx/src/error.rs +++ b/crates/shx/src/error.rs @@ -26,4 +26,3 @@ impl std::fmt::Display for ShxError { } impl std::error::Error for ShxError {} - diff --git a/crates/shx/src/lib.rs b/crates/shx/src/lib.rs new file mode 100644 index 000000000..e595e90f5 --- /dev/null +++ b/crates/shx/src/lib.rs @@ -0,0 +1,8 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] +//! SHP source compilation to SHX containers, extracted from CADCraft. +//! Font discovery, glyph execution and text layout remain consumer responsibilities. +mod compile; +mod error; +pub use compile::compile; +pub use error::ShxError; diff --git a/crates/shx/tests/compiler.rs b/crates/shx/tests/compiler.rs new file mode 100644 index 000000000..f558e185a --- /dev/null +++ b/crates/shx/tests/compiler.rs @@ -0,0 +1,30 @@ +use craft_shx::{ShxError, compile}; + +#[test] +fn fixed_shape_bytes() { + let b = compile("*65,2,A\n010,0\n").unwrap(); + let mut expected = b"AutoCAD-86 shapes 1.0\r\n\x1a".to_vec(); + expected.extend([65, 0, 65, 0, 1, 0, 65, 0, 4, 0, b'A', 0, 0x10, 0]); + expected.extend(b"EOF"); + assert_eq!(b, expected); +} +#[test] +fn hostile_sources_are_refused() { + for src in [ + "*1,2,X\n7\n", + "*1,2,X\n9,(1,1)\n", + "*99999,1,X\n0\n", + "*1,1,X\n300,0\n", + "010,0\n", + "*1,1,X\n1,0zz,0\n", + "*1,1,X\n0\n*1,1,Y\n0\n", + "*--9223372036854775808,1,X\n0", + "*BIGFONT 1,65535\n*1,1,X\n0", + ] { + assert!(compile(src).is_err(), "{src:?}"); + } + assert_eq!(compile(""), Err(ShxError::Empty)); + assert_eq!(compile(&" ".repeat((8 << 20) + 1)), Err(ShxError::TooLarge)); + let oversized_header = format!("*UNIFONT,6,{}\n10,2,0,0,0,0\n*65,1,A\n0", "n".repeat(65536)); + assert_eq!(compile(&oversized_header), Err(ShxError::TooLarge)); +} From 3c5007339754def577b3c5274f523d96384a35c4 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 15:48:41 +0000 Subject: [PATCH 3/6] Share bounded SHX container reader --- crates/shx/src/lib.rs | 2 + crates/shx/src/parse.rs | 281 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 283 insertions(+) create mode 100644 crates/shx/src/parse.rs diff --git a/crates/shx/src/lib.rs b/crates/shx/src/lib.rs index e595e90f5..ce330450c 100644 --- a/crates/shx/src/lib.rs +++ b/crates/shx/src/lib.rs @@ -4,5 +4,7 @@ //! Font discovery, glyph execution and text layout remain consumer responsibilities. mod compile; mod error; +pub mod parse; pub use compile::compile; pub use error::ShxError; +pub use parse::{ParsedFont, Record, ShxKind}; diff --git a/crates/shx/src/parse.rs b/crates/shx/src/parse.rs new file mode 100644 index 000000000..9cd4a35ad --- /dev/null +++ b/crates/shx/src/parse.rs @@ -0,0 +1,281 @@ +//! Reading the compiled SHX containers (layouts in the module documentation). Every count and +//! offset comes from the file, so each is checked against its length; records that run past +//! the end are dropped and the rest kept. + +use super::ShxError; +use std::collections::HashMap; + +/// The SHX container kind. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ShxKind { + Shapes, + BigFont, + Unifont, +} +/// Byte ranges of one shape name and pen program in [`ParsedFont::data`]. +#[derive(Clone, Copy, Debug)] +pub struct Record { + pub name: (usize, usize), + pub program: (usize, usize), +} +/// Decoded container records and metrics; glyph execution remains a caller concern. +pub struct ParsedFont { + pub kind: ShxKind, + pub name: String, + pub header: bool, + pub above: f64, + pub below: f64, + pub dual: bool, + pub encoding: u8, + pub char_width: f64, + pub ranges: Vec<(u16, u16)>, + pub data: Vec, + pub records: HashMap, +} + +pub const SHAPES_10: &[u8] = b"AutoCAD-86 shapes 1.0\r\n\x1a"; +pub const SHAPES_11: &[u8] = b"AutoCAD-86 shapes 1.1\r\n\x1a"; +pub const BIGFONT: &[u8] = b"AutoCAD-86 bigfont 1.0\r\n\x1a"; +pub const UNIFONT: &[u8] = b"AutoCAD-86 unifont 1.0\r\n\x1a"; + +/// Largest file read (the largest big fonts are a few megabytes). +pub const MAX_FILE_BYTES: usize = 32 << 20; +/// Most escape ranges in a big font (lead bytes: at most 256). +const MAX_RANGES: usize = 256; + +/// A checked little-endian reader. +struct Rd<'a> { + b: &'a [u8], + pos: usize, +} + +impl<'a> Rd<'a> { + fn take(&mut self, n: usize) -> Result<&'a [u8], ShxError> { + let end = self.pos.checked_add(n).ok_or(ShxError::Truncated)?; + let s = self.b.get(self.pos..end).ok_or(ShxError::Truncated)?; + self.pos = end; + Ok(s) + } + fn u16(&mut self) -> Result { + match self.take(2)? { + [a, b] => Ok(u16::from_le_bytes([*a, *b])), + _ => Err(ShxError::Truncated), + } + } + fn u32(&mut self) -> Result { + match self.take(4)? { + [a, b, c, d] => Ok(u32::from_le_bytes([*a, *b, *c, *d])), + _ => Err(ShxError::Truncated), + } + } +} + +/// A font being read. +struct Font { + kind: ShxKind, + name: String, + header: bool, + above: f64, + below: f64, + dual: bool, + encoding: u8, + char_width: f64, + ranges: Vec<(u16, u16)>, + records: HashMap, +} + +impl Font { + fn new(kind: ShxKind) -> Font { + Font { + kind, + name: String::new(), + header: false, + above: 0.0, + below: 0.0, + dual: false, + encoding: 0, + char_width: 0.0, + ranges: Vec::new(), + records: HashMap::new(), + } + } + + /// Add the record of shape `number` at `start..end` of `data`: a NUL-terminated name, then + /// the program. Shape 0 is the font record. A record without a name terminator is dropped; + /// the first record of a number wins. + fn record(&mut self, data: &[u8], number: u16, start: usize, end: usize) { + let Some(bytes) = data.get(start..end) else { return }; + let Some(nul) = bytes.iter().position(|b| *b == 0) else { return }; + let name = (start, start + nul); + let program = (start + nul + 1, end); + if number == 0 { + if !self.header { + self.font_record(data.get(program.0..program.1).unwrap_or_default(), data.get(name.0..name.1).unwrap_or_default()); + } + return; + } + self.records.entry(number).or_insert(Record { name, program }); + } + + /// The font record: above, below, modes (and for a unifont encoding and embedding); an + /// extended big font's is character height, 0, modes, character width. + fn font_record(&mut self, info: &[u8], name: &[u8]) { + self.header = true; + self.name = name.iter().take(255).map(|c| char::from(*c)).collect(); + let byte = |i: usize| info.get(i).copied().unwrap_or(0); + self.above = f64::from(byte(0)); + self.below = f64::from(byte(1)); + self.dual = byte(2) == 2; + if self.kind == ShxKind::Unifont { + self.encoding = byte(3); + } + if self.kind == ShxKind::BigFont && info.len() >= 5 && byte(1) == 0 { + // Extended: height, 0, modes, width, 0. + self.below = 0.0; + self.char_width = f64::from(byte(3)); + } + } + + fn finish(self, data: Vec) -> Result { + if self.records.is_empty() { + return Err(ShxError::Empty); + } + Ok(ParsedFont { + kind: self.kind, + name: self.name, + header: self.header, + above: self.above, + below: self.below, + dual: self.dual, + encoding: self.encoding, + char_width: if self.char_width > 0.0 { self.char_width } else { self.above }, + ranges: self.ranges, + data, + records: self.records, + }) + } +} + +pub fn parse(bytes: &[u8]) -> Result { + if bytes.len() > MAX_FILE_BYTES { + return Err(ShxError::TooLarge); + } + if bytes.starts_with(SHAPES_10) || bytes.starts_with(SHAPES_11) { + shapes(bytes) + } else if bytes.starts_with(BIGFONT) { + bigfont(bytes) + } else if bytes.starts_with(UNIFONT) { + unifont(bytes) + } else { + Err(ShxError::NotShx) + } +} + +fn shapes(bytes: &[u8]) -> Result { + let mut r = Rd { b: bytes, pos: SHAPES_10.len() }; + let _first = r.u16()?; + let _last = r.u16()?; + let count = usize::from(r.u16()?); + // The whole index must be there before anything is read from it. + let index = r.take(count.checked_mul(4).ok_or(ShxError::TooLarge)?)?; + let mut f = Font::new(ShxKind::Shapes); + let mut pos = r.pos; + for [a, b, c, d] in index.as_chunks::<4>().0 { + let (number, len) = (u16::from_le_bytes([*a, *b]), usize::from(u16::from_le_bytes([*c, *d]))); + let Some(end) = pos.checked_add(len).filter(|e| *e <= bytes.len()) else { break }; + f.record(bytes, number, pos, end); + pos = end; + } + f.finish(bytes.to_vec()) +} + +fn bigfont(bytes: &[u8]) -> Result { + let mut r = Rd { b: bytes, pos: BIGFONT.len() }; + let index_size = usize::from(r.u16()?); + let count = usize::from(r.u16()?); + let nranges = usize::from(r.u16()?); + if nranges > MAX_RANGES { + return Err(ShxError::TooLarge); + } + let mut f = Font::new(ShxKind::BigFont); + for _ in 0..nranges { + let (lo, hi) = (r.u16()?, r.u16()?); + f.ranges.push((lo.min(hi), lo.max(hi))); + } + // The index has `count` entries of 8 bytes; a file whose count doesn't fit but whose index + // size does is read by that. + let fits = |n: usize| n.checked_mul(8).and_then(|l| r.pos.checked_add(l)).is_some_and(|e| e <= bytes.len()); + let n = if fits(count) { + count + } else if fits(index_size) { + index_size + } else { + return Err(ShxError::Truncated); + }; + let index = r.take(n.checked_mul(8).ok_or(ShxError::TooLarge)?)?; + for [a, b, c, d, o0, o1, o2, o3] in index.as_chunks::<8>().0 { + let number = u16::from_le_bytes([*a, *b]); + let len = usize::from(u16::from_le_bytes([*c, *d])); + let Ok(off) = usize::try_from(u32::from_le_bytes([*o0, *o1, *o2, *o3])) else { continue }; + if len == 0 { + continue; + } + let Some(end) = off.checked_add(len).filter(|e| *e <= bytes.len()) else { continue }; + f.record(bytes, number, off, end); + } + f.finish(bytes.to_vec()) +} + +fn unifont(bytes: &[u8]) -> Result { + let mut r = Rd { b: bytes, pos: UNIFONT.len() }; + let count = r.u32()?; + let info_len = usize::from(r.u16()?); + let info = r.take(info_len)?; + let mut f = Font::new(ShxKind::Unifont); + let nul = info.iter().position(|b| *b == 0).unwrap_or(info.len()); + f.font_record(info.get(nul.saturating_add(1)..).unwrap_or_default(), info.get(..nul).unwrap_or_default()); + // `count` includes the font record; never trusted beyond the data that is there. + let mut left = count.saturating_sub(1); + while left > 0 { + left -= 1; + let Ok(number) = r.u16() else { break }; + let Ok(len) = r.u16().map(usize::from) else { break }; + let start = r.pos; + let Some(end) = start.checked_add(len).filter(|e| *e <= bytes.len()) else { break }; + r.pos = end; + f.record(bytes, number, start, end); + } + f.finish(bytes.to_vec()) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + #[test] + fn reads_shapes_bigfont_and_unifont_records() { + for (source, kind, shape) in [ + ("*0,4,font\n6,2,2,0\n*65,4,A\n1,064,0\n", ShxKind::Shapes, 65), + ("*BIGFONT 2,1,081,09F\n*0,4,big\n8,0,0,0\n*082A0,4,square\n1,080,0\n", ShxKind::BigFont, 0x82a0), + ("*UNIFONT,6,uni\n6,2,0,0,0,0\n*00041,4,a\n1,064,0\n", ShxKind::Unifont, 65), + ] { + let bytes = crate::compile(source).unwrap(); + let font = parse(&bytes).unwrap(); + assert_eq!(font.kind, kind); + assert!(font.header); + let record = font.records.get(&shape).unwrap(); + assert_eq!(font.data.get(record.program.1 - 1), Some(&0)); + } + } + #[test] + fn truncation_limits_and_unknown_signatures_are_errors() { + assert!(matches!(parse(b"not a font"), Err(ShxError::NotShx))); + assert!(matches!(parse(&vec![0; MAX_FILE_BYTES + 1]), Err(ShxError::TooLarge))); + let mut shapes = SHAPES_10.to_vec(); + shapes.extend([1, 0, 255, 255, 255, 255]); + assert!(matches!(parse(&shapes), Err(ShxError::Truncated))); + let mut big = BIGFONT.to_vec(); + big.extend([255, 255, 255, 255, 255, 255]); + assert!(matches!(parse(&big), Err(ShxError::TooLarge))); + } +} From 2f2d1d84e3a36b3f93e81507aeff3f0da97a7162 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 15:51:27 +0000 Subject: [PATCH 4/6] Share bounded SHX glyph program interpreter --- crates/shx/src/lib.rs | 1 + crates/shx/src/program.rs | 443 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 444 insertions(+) create mode 100644 crates/shx/src/program.rs diff --git a/crates/shx/src/lib.rs b/crates/shx/src/lib.rs index ce330450c..e330e59fd 100644 --- a/crates/shx/src/lib.rs +++ b/crates/shx/src/lib.rs @@ -5,6 +5,7 @@ mod compile; mod error; pub mod parse; +pub mod program; pub use compile::compile; pub use error::ShxError; pub use parse::{ParsedFont, Record, ShxKind}; diff --git a/crates/shx/src/program.rs b/crates/shx/src/program.rs new file mode 100644 index 000000000..9115d1c6d --- /dev/null +++ b/crates/shx/src/program.rs @@ -0,0 +1,443 @@ +//! The shape pen program: vector length/direction bytes and special codes 0–14, run into +//! polylines. Bounded everywhere: subshape depth, location stack, steps, points, coordinates. +//! +//! - A byte with a non-zero high nibble is a vector: length (high nibble) in one of 16 +//! directions (low nibble, counter-clockwise from east in 22.5° steps; the off-axis ones +//! are half-unit or unit steps on the minor axis). +//! - 0 end, 1 pen down, 2 pen up, 3/4 divide/multiply vector lengths by the next byte, +//! 5/6 push/pop the location, 7 subshape (one byte; two bytes high first in a Unicode font; +//! `0`, a two-byte number, base point, width and height in an extended big font), +//! 8 one X-Y displacement, 9 displacements up to (0,0), 10 octant arc (radius, +//! ±0SC: sign = clockwise, S start octant, C octants, 0 = 8), 11 fractional arc (start +//! offset, end offset, high and low radius, ±0SC; offsets in 1/256 of 45° from the octant +//! boundaries), 12 bulge arc (dx, dy, bulge: ±127 = semicircle), 13 bulge arcs up to (0,0), +//! 14 the next command is for vertical text only (dual-orientation fonts). +//! - Displacements and bulges are two's complement bytes; the arc direction byte keeps its +//! sign in the high bit. + +use std::f64::consts::{FRAC_PI_4, TAU}; + +use super::ShxKind; +use std::ops::{Add, Mul, Neg, Sub}; + +/// A point in SHX font units. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Point { + pub x: f64, + pub y: f64, +} +impl Point { + pub const ZERO: Self = Self { x: 0.0, y: 0.0 }; + pub const fn new(x: f64, y: f64) -> Self { + Self { x, y } + } + fn is_finite(self) -> bool { + self.x.is_finite() && self.y.is_finite() + } + fn len(self) -> f64 { + self.x.hypot(self.y) + } + fn len2(self) -> f64 { + self.x * self.x + self.y * self.y + } +} +impl Add for Point { + type Output = Self; + fn add(self, rhs: Self) -> Self { + Self::new(self.x + rhs.x, self.y + rhs.y) + } +} +impl Sub for Point { + type Output = Self; + fn sub(self, rhs: Self) -> Self { + Self::new(self.x - rhs.x, self.y - rhs.y) + } +} +impl Mul for Point { + type Output = Self; + fn mul(self, rhs: f64) -> Self { + Self::new(self.x * rhs, self.y * rhs) + } +} +impl Neg for Point { + type Output = Self; + fn neg(self) -> Self { + Self::new(-self.x, -self.y) + } +} + +/// Font records and metrics the bounded shape interpreter needs. +pub trait Font { + fn kind(&self) -> ShxKind; + fn dual(&self) -> bool; + fn above(&self) -> f64; + fn char_width(&self) -> f64; + fn program(&self, number: u16) -> Option<&[u8]>; +} +/// Pen-down strokes and advance in font units. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Glyph { + pub strokes: Vec>, + pub advance: Point, +} + +/// Subshape nesting (a cycle ends here). +const MAX_DEPTH: usize = 16; +/// Location stack (the format promises four). +const MAX_STACK: usize = 64; +/// Bytes run per glyph, subshapes included. +const MAX_STEPS: usize = 200_000; +/// Points per glyph. +const MAX_POINTS: usize = 50_000; +/// Coordinates in font units. +const MAX_COORD: f64 = 1.0e7; +/// Arc segments per full turn. +const ARC_STEPS: f64 = 64.0; + +/// Why a program stops early: the glyph is then not drawn. +#[derive(Debug)] +pub struct Broken; + +type Res = Result<(), Broken>; + +struct Pen<'a> { + font: &'a dyn Font, + vertical: bool, + pos: Point, + down: bool, + /// Vector length factor (codes 3 and 4). + scale: f64, + /// Per-axis factor of an extended big font subshape. + axes: Point, + stack: Vec, + strokes: Vec>, + active: Vec, + steps: usize, + points: usize, +} + +pub fn outline(font: &dyn Font, number: u16, vertical: bool) -> Result { + let mut pen = Pen { + font, + vertical, + pos: Point::ZERO, + down: true, + scale: 1.0, + axes: Point::new(1.0, 1.0), + stack: Vec::new(), + strokes: Vec::new(), + active: Vec::new(), + steps: 0, + points: 0, + }; + pen.run(number, 0)?; + pen.flush(); + Ok(Glyph { strokes: pen.strokes, advance: pen.pos }) +} + +/// The 16 vector directions (unit length on the major axis). +fn direction(d: u8) -> Point { + let (x, y) = match d & 15 { + 0 => (1.0, 0.0), + 1 => (1.0, 0.5), + 2 => (1.0, 1.0), + 3 => (0.5, 1.0), + 4 => (0.0, 1.0), + 5 => (-0.5, 1.0), + 6 => (-1.0, 1.0), + 7 => (-1.0, 0.5), + 8 => (-1.0, 0.0), + 9 => (-1.0, -0.5), + 10 => (-1.0, -1.0), + 11 => (-0.5, -1.0), + 12 => (0.0, -1.0), + 13 => (0.5, -1.0), + 14 => (1.0, -1.0), + _ => (1.0, -0.5), + }; + Point::new(x, y) +} + +/// A two's complement operand byte. +fn signed(b: u8) -> f64 { + f64::from(i8::from_le_bytes([b])) +} + +/// A program being read: its bytes and position. +struct Cur<'p> { + b: &'p [u8], + pos: usize, +} + +impl Cur<'_> { + fn byte(&mut self) -> Result { + let v = self.b.get(self.pos).copied().ok_or(Broken)?; + self.pos += 1; + Ok(v) + } +} + +impl Pen<'_> { + fn step(&mut self) -> Res { + self.steps += 1; + if self.steps > MAX_STEPS { Err(Broken) } else { Ok(()) } + } + + fn flush(&mut self) { + if self.active.len() >= 2 { + self.strokes.push(std::mem::take(&mut self.active)); + } else { + self.active.clear(); + } + } + + /// Move the pen by `d` font units (already scaled), drawing when the pen is down. + fn to(&mut self, target: Point) -> Res { + if !target.is_finite() || target.x.abs().max(target.y.abs()) > MAX_COORD { + return Err(Broken); + } + if self.down { + if self.active.is_empty() { + self.active.push(self.pos); + self.points += 1; + } + self.active.push(target); + self.points += 1; + if self.points > MAX_POINTS { + return Err(Broken); + } + } else { + self.flush(); + } + self.pos = target; + Ok(()) + } + + /// A displacement in vector units (times the length factor and the subshape axes). + fn by(&mut self, d: Point) -> Res { + let k = d * self.scale; + self.to(self.pos + Point::new(k.x * self.axes.x, k.y * self.axes.y)) + } + + /// An arc of `radius` vector units from the pen, starting at angle `start` on its circle + /// and turning `sweep` radians (positive counter-clockwise). + fn arc(&mut self, radius: f64, start: f64, sweep: f64) -> Res { + let r = radius * self.scale; + if !(r.is_finite() && r > 0.0 && sweep.is_finite()) { + return Ok(()); + } + let n = if self.down { (sweep.abs() / TAU * ARC_STEPS).ceil().clamp(1.0, ARC_STEPS) as usize } else { 1 }; + let from = self.pos; + let s0 = Point::new(start.cos(), start.sin()); + for i in 1..=n { + let a = start + sweep * i as f64 / n as f64; + let d = (Point::new(a.cos(), a.sin()) - s0) * r; + self.to(from + Point::new(d.x * self.axes.x, d.y * self.axes.y))?; + } + Ok(()) + } + + /// An arc to the displacement `d` with `bulge` (−127..127, ±127 a semicircle). + fn bulge(&mut self, d: Point, bulge: f64) -> Res { + let b = bulge.clamp(-127.0, 127.0) / 127.0; + if b == 0.0 || !self.down || d.len2() == 0.0 { + return self.by(d); + } + // Centre from the chord midpoint along its left normal; sweep 4·atan(b). + let centre = d * 0.5 + Point::new(-d.y, d.x) * ((1.0 - b * b) / (4.0 * b)); + let rel = -centre; + self.arc(rel.len(), rel.y.atan2(rel.x), 4.0 * b.atan()) + } + + /// The octant byte `±0SC`: (clockwise, start octant, octants with 0 = 8). + fn octants(spec: u8) -> (f64, f64, f64) { + let sign = if spec & 0x80 != 0 { -1.0 } else { 1.0 }; + let s = f64::from((spec >> 4) & 7); + let c = match spec & 7 { + 0 => 8.0, + c => f64::from(c), + }; + (sign, s, c) + } + + /// The vector unit size of an extended big font's subshape cell. + fn cell(&self) -> Point { + let h = if self.font.above() > 0.0 { self.font.above() } else { 1.0 }; + let w = if self.font.char_width() > 0.0 { self.font.char_width() } else { h }; + Point::new(w, h) + } + + fn run(&mut self, number: u16, depth: usize) -> Res { + if depth >= MAX_DEPTH { + return Err(Broken); + } + let program = self.font.program(number).ok_or(Broken)?; + let mut r = Cur { b: program, pos: 0 }; + let mut skip = false; + while r.pos < r.b.len() { + self.step()?; + let code = r.byte()?; + // Code 14: in a dual-orientation font the next command is for vertical text only. + let exec = !skip; + skip = false; + match code { + 0 => return Ok(()), + 1 if exec => self.down = true, + 2 if exec => { + self.down = false; + self.flush(); + } + 3 | 4 => { + let k = f64::from(r.byte()?); + if exec && k > 0.0 { + let s = if code == 3 { self.scale / k } else { self.scale * k }; + if !(1e-9..=MAX_COORD).contains(&s) { + return Err(Broken); + } + self.scale = s; + } + } + 5 if exec => { + if self.stack.len() >= MAX_STACK { + return Err(Broken); + } + self.stack.push(self.pos); + } + 6 if exec => { + self.flush(); + if let Some(p) = self.stack.pop() { + self.pos = p; + } + } + 7 => self.subshape(&mut r, exec, depth)?, + 8 | 9 | 12 | 13 => loop { + self.step()?; + let d = Point::new(signed(r.byte()?), signed(r.byte()?)); + if matches!(code, 9 | 13) && d == Point::ZERO { + break; + } + let bulge = if matches!(code, 12 | 13) { signed(r.byte()?) } else { 0.0 }; + if exec { + self.bulge(d, bulge)?; + } + if matches!(code, 8 | 12) { + break; + } + }, + 10 => { + let radius = f64::from(r.byte()?); + let (sign, s, c) = Self::octants(r.byte()?); + if exec { + self.arc(radius, s * FRAC_PI_4, sign * c * FRAC_PI_4)?; + } + } + 11 => { + let start = f64::from(r.byte()?) / 256.0; + let end = match r.byte()? { + 0 => 1.0, + e => f64::from(e) / 256.0, + }; + let radius = f64::from(u16::from_be_bytes([r.byte()?, r.byte()?])); + let (sign, s, c) = Self::octants(r.byte()?); + if exec { + // From `start` past the first octant boundary to `end` past the last + // octant's. + self.arc(radius, (s + sign * start) * FRAC_PI_4, sign * (c - 1.0 + end - start) * FRAC_PI_4)?; + } + } + 14 => skip = self.font.dual() && !self.vertical && exec, + 1..=15 => {} + v => { + if exec { + self.by(direction(v) * f64::from(v >> 4))?; + } + } + } + } + Ok(()) + } + + /// Code 7 and its operands. + fn subshape(&mut self, r: &mut Cur, exec: bool, depth: usize) -> Res { + match self.font.kind() { + ShxKind::Unifont => { + let n = u16::from_be_bytes([r.byte()?, r.byte()?]); + if exec { + self.run(n, depth + 1)?; + } + } + ShxKind::BigFont => { + let first = r.byte()?; + if first != 0 { + if exec { + self.run(u16::from(first), depth + 1)?; + } + return Ok(()); + } + // Extended: the primitive drawn in the box (x, y, width, height) of the cell. + let n = u16::from_be_bytes([r.byte()?, r.byte()?]); + let (x, y, w, h) = (f64::from(r.byte()?), f64::from(r.byte()?), f64::from(r.byte()?), f64::from(r.byte()?)); + if !exec { + return Ok(()); + } + let (pos, axes, down) = (self.pos, self.axes, self.down); + let cell = self.cell(); + self.flush(); + self.pos = pos + Point::new(x * axes.x, y * axes.y) * self.scale; + self.axes = Point::new(axes.x * w / cell.x, axes.y * h / cell.y); + let res = self.run(n, depth + 1); + self.flush(); + self.axes = axes; + self.pos = pos; + self.down = down; + res?; + } + ShxKind::Shapes => { + let n = u16::from(r.byte()?); + if exec { + self.run(n, depth + 1)?; + } + } + } + Ok(()) + } +} + +impl Font for crate::ParsedFont { + fn kind(&self) -> ShxKind { + self.kind + } + fn dual(&self) -> bool { + self.dual + } + fn above(&self) -> f64 { + self.above + } + fn char_width(&self) -> f64 { + self.char_width + } + fn program(&self, number: u16) -> Option<&[u8]> { + let r = self.records.get(&number)?; + self.data.get(r.program.0..r.program.1) + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + #[test] + fn executes_shape_vectors_without_app_geometry_types() { + let bytes = crate::compile("*1,3,A\n1,010,0\n").unwrap(); + let font = crate::parse::parse(&bytes).unwrap(); + let glyph = outline(&font, 1, false).unwrap(); + assert_eq!(glyph.strokes, vec![vec![Point::new(0.0, 0.0), Point::new(1.0, 0.0)]]); + assert_eq!(glyph.advance, Point::new(1.0, 0.0)); + } + #[test] + fn recursive_shapes_stop_at_the_depth_bound() { + let bytes = crate::compile("*1,3,A\n7,1,0\n").unwrap(); + let font = crate::parse::parse(&bytes).unwrap(); + assert!(outline(&font, 1, false).is_err()); + } +} From 3a1943322b391c771fc9bce9889f6210f1a1b0b2 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 17:19:27 +0000 Subject: [PATCH 5/6] Cover SHX compiler wire variants and typed operand errors --- crates/shx/tests/compiler.rs | 79 ++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/crates/shx/tests/compiler.rs b/crates/shx/tests/compiler.rs index f558e185a..c68670218 100644 --- a/crates/shx/tests/compiler.rs +++ b/crates/shx/tests/compiler.rs @@ -28,3 +28,82 @@ fn hostile_sources_are_refused() { let oversized_header = format!("*UNIFONT,6,{}\n10,2,0,0,0,0\n*65,1,A\n0", "n".repeat(65536)); assert_eq!(compile(&oversized_header), Err(ShxError::TooLarge)); } + +#[test] +fn displacement_arc_and_subshape_operands_have_exact_bytes() { + let source = "; comment\n*+65,99,A\n3,2,4,3,7,66,8,-128,127,9,(1,-2),(0,0),\n10,12,-043,11,1,2,3,4,043,12,-1,2,-3,13,1,2,-3,0,0,0\n"; + let bytes = compile(source).unwrap(); + let program = [3, 2, 4, 3, 7, 66, 8, 128, 127, 9, 1, 254, 0, 0, 10, 12, 0xc3, 11, 1, 2, 3, 4, 0x43, 12, 255, 2, 253, 13, 1, 2, 253, 0, 0, 0]; + let mut record = vec![b'A', 0]; + record.extend(program); + record.extend(b"EOF"); + assert!(bytes.ends_with(&record)); +} + +#[test] +fn bigfont_ranges_index_offsets_and_extended_calls_are_encoded() { + let bytes = compile("*BIGFONT 1,2,128,129,140,141\n*65,1,A\n7,66,7,0,01234,1,2,3,4,0\n").unwrap(); + let signature = b"AutoCAD-86 bigfont 1.0\r\n\x1a"; + let mut expected = signature.to_vec(); + expected.extend([1, 0, 1, 0, 2, 0, 128, 0, 129, 0, 140, 0, 141, 0]); + let record = [b'A', 0, 7, 66, 7, 0, 0x12, 0x34, 1, 2, 3, 4, 0]; + let offset = (expected.len() + 8) as u32; + expected.extend([65, 0, record.len() as u8, 0]); + expected.extend(offset.to_le_bytes()); + expected.extend(record); + assert_eq!(bytes, expected); +} + +#[test] +fn unicode_font_records_and_subshape_numbers_are_encoded() { + let bytes = compile("*UNIFONT,6,Example\n10,2,0\n0,0,0\n*65,9,A\n7,01234\n").unwrap(); + let mut expected = b"AutoCAD-86 unifont 1.0\r\n\x1a".to_vec(); + expected.extend(2u32.to_le_bytes()); + expected.extend(14u16.to_le_bytes()); + expected.extend(b"Example\0"); + expected.extend([10, 2, 0, 0, 0, 0]); + expected.extend([65, 0, 6, 0, b'A', 0, 7, 0x12, 0x34, 0]); + assert_eq!(bytes, expected); +} + +#[test] +fn font_records_sorting_names_and_implicit_end_are_preserved() { + let bytes = compile("*66,1,B\0name\n1\n*0,4,Font\n10,2,0,0\n*65,1,A\n2,0\n").unwrap(); + let mut expected = b"AutoCAD-86 shapes 1.0\r\n\x1a".to_vec(); + expected.extend([0, 0, 66, 0, 3, 0]); + let records: [(u16, &[u8]); 3] = [(0, b"Font\0\x0a\x02\0\0"), (65, b"A\0\x02\0"), (66, b"Bname\0\x01\0")]; + for (number, record) in records { + expected.extend(number.to_le_bytes()); + expected.extend((record.len() as u16).to_le_bytes()); + } + for (_, record) in records { + expected.extend(record); + } + expected.extend(b"EOF"); + assert_eq!(bytes, expected); +} + +#[test] +fn invalid_typed_operands_report_source_lines() { + for body in ["8,128,0", "10,1,128", "11,1,2,3,4,-128", "7,-1", "3,-1", "256", "7,256"] { + assert!(matches!(compile(&format!("*65,1,A\n{body}")), Err(ShxError::Source(1, _))), "{body}"); + } + for source in ["*UNIFONT,6,X\n256\n*65,1,A\n0", "*BIGFONT 1,1,-1,2\n*65,1,A\n0", "*0,1,F\n256", "*-1,1,A\n0"] { + assert!(matches!(compile(source), Err(ShxError::Source(_, _))), "{source}"); + } + let large_record = format!("*65,1,{}\n0", "x".repeat(65535)); + assert_eq!(compile(&large_record), Err(ShxError::TooLarge)); +} + +#[test] +fn errors_have_useful_display_messages() { + for (error, expected) in [ + (ShxError::NotShx, "not an SHX shape or font file"), + (ShxError::Truncated, "the SHX file is truncated"), + (ShxError::TooLarge, "the SHX file is too large"), + (ShxError::Empty, "the SHX file has no shapes"), + (ShxError::Source(7, "bad operand".into()), "line 7: bad operand"), + ] { + assert_eq!(error.to_string(), expected); + } +} From e1c90a267dbf50ef2632a574f7daab8e74439ab7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:41:17 +0000 Subject: [PATCH 6/6] Exercise bounded SHX interpreter instructions and malformed inputs --- crates/shx/src/program.rs | 93 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) diff --git a/crates/shx/src/program.rs b/crates/shx/src/program.rs index 9115d1c6d..eba6fd796 100644 --- a/crates/shx/src/program.rs +++ b/crates/shx/src/program.rs @@ -441,3 +441,96 @@ mod tests { assert!(outline(&font, 1, false).is_err()); } } + +#[cfg(test)] +mod instruction_tests { + #![allow(clippy::unwrap_used)] + use super::*; + + struct Fixture { + kind: ShxKind, + programs: Vec>, + } + impl Font for Fixture { + fn kind(&self) -> ShxKind { + self.kind + } + fn dual(&self) -> bool { + true + } + fn above(&self) -> f64 { + 10.0 + } + fn char_width(&self) -> f64 { + 10.0 + } + fn program(&self, number: u16) -> Option<&[u8]> { + self.programs.get(usize::from(number)).map(Vec::as_slice) + } + } + fn fixture(program: Vec) -> Fixture { + Fixture { kind: ShxKind::Shapes, programs: vec![program] } + } + + #[test] + fn pen_state_scaling_and_location_stack_keep_separate_strokes() { + let font = fixture(vec![4, 4, 0x10, 5, 2, 8, 2, 3, 6, 1, 3, 2, 0x14, 0]); + let g = outline(&font, 0, false).unwrap(); + assert_eq!(g.strokes, vec![vec![Point::ZERO, Point::new(4.0, 0.0)], vec![Point::new(4.0, 0.0), Point::new(4.0, 2.0)]]); + assert_eq!(g.advance, Point::new(4.0, 2.0)); + } + + #[test] + fn vertical_only_commands_consume_operands_without_affecting_horizontal_text() { + let font = fixture(vec![14, 8, 10, 20, 0x10, 0]); + assert_eq!(outline(&font, 0, false).unwrap().advance, Point::new(1.0, 0.0)); + assert_eq!(outline(&font, 0, true).unwrap().advance, Point::new(11.0, 20.0)); + } + + #[test] + fn displacement_and_bulge_sequences_end_at_their_chord_endpoint() { + for (program, end_x) in + [(vec![9, 3, 4, 253, 252, 0, 0, 0], 0.0), (vec![12, 10, 0, 127, 0], 10.0), (vec![13, 10, 0, 129, 246, 0, 0, 0, 0, 0], 0.0)] + { + let g = outline(&fixture(program), 0, false).unwrap(); + assert!(g.advance.y.abs() < 1e-10); + assert!((g.advance.x - end_x).abs() < 1e-10); + } + } + + #[test] + fn full_octant_arcs_close_and_fractional_arcs_keep_radius() { + for program in [vec![10, 10, 0, 0], vec![10, 10, 128, 0], vec![11, 0, 0, 0, 10, 0, 0]] { + let g = outline(&fixture(program), 0, false).unwrap(); + assert!(g.advance.len() < 1e-10); + assert_eq!(g.strokes[0].len(), 65); + } + } + + #[test] + fn subshape_operands_follow_font_kind_and_bigfont_restores_parent_position() { + for kind in [ShxKind::Shapes, ShxKind::Unifont, ShxKind::BigFont] { + let call = match kind { + ShxKind::Unifont => vec![7, 0, 1, 0], + ShxKind::BigFont => vec![7, 0, 0, 1, 2, 3, 20, 30, 0], + _ => vec![7, 1, 0], + }; + let font = Fixture { kind, programs: vec![call, vec![0x10, 0]] }; + let g = outline(&font, 0, false).unwrap(); + if kind == ShxKind::BigFont { + assert_eq!(g.advance, Point::ZERO); + assert_eq!(g.strokes[0], vec![Point::new(2.0, 3.0), Point::new(4.0, 3.0)]); + } else { + assert_eq!(g.advance, Point::new(1.0, 0.0)); + } + } + } + + #[test] + fn malformed_operands_and_resource_exhaustion_return_errors() { + for program in [vec![8, 1], vec![7, 99], vec![5; MAX_STACK + 1], vec![0x10; MAX_POINTS + 1], vec![4, 255, 4, 255, 4, 255]] { + assert!(outline(&fixture(program), 0, false).is_err()); + } + assert!(outline(&fixture(vec![0]), 1, false).is_err()); + } +}