From 8b4e4a8e900d1d95137f350cce540cd4536e84e6 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 8 Oct 2026 03:32:20 +0000 Subject: [PATCH] refactor: deny unwrap, expect and panic in library and binary code The library and the binary now deny clippy's unwrap_used, expect_used, panic, unimplemented, todo and unreachable lints outside unit tests, and forbid unsafe code. Malformed input must give an error or a warning, never a panic. The 36 offending calls are replaced without changing behaviour: - Byte reads that converted a slice of checked length to an array now use the `Encoding::*_at` decoders, `first_chunk`, or a `Cursor` helper that returns `Result`; the fallbacks are the existing results for data of the wrong length (`Value::Other`, a skipped value, a short-data error). - The fixed-offset readers of the header and the master pages build the array with `array::from_fn`; they index as before. - `Node::set` returns the node it set, so `TextFramePreference` insets no longer look it up again with `expect`. - The embedded value files fall back to no values if one fails to parse, and a block with a version bound that is not a number does not apply. A new unit test checks that every committed file parses and that every bound is a number. - `Xml::end` without an open element fails a debug assertion and writes nothing in a release build. diff_outputs.py over the corpus (without own/): 0 differing outputs, 0 changed failures, 0 changed warnings. Idea from storytold/designcraft#98. --- src/container.rs | 7 ++-- src/database.rs | 16 +++++---- src/header.rs | 10 ++++-- src/idml/styles.rs | 9 ++--- src/idml/values.rs | 82 ++++++++++++++++++++++++++----------------- src/idml/xml.rs | 10 +++++- src/lib.rs | 16 +++++++++ src/main.rs | 14 ++++++++ src/model/attrs.rs | 53 +++++++++++++++------------- src/model/story.rs | 3 +- src/model/variable.rs | 3 +- src/object.rs | 23 ++++++++---- 12 files changed, 162 insertions(+), 84 deletions(-) diff --git a/src/container.rs b/src/container.rs index e0efe23..7dbe151 100644 --- a/src/container.rs +++ b/src/container.rs @@ -21,12 +21,15 @@ const SEQUENCE_OFFSET: usize = 0x108; const DB_PAGES_OFFSET: usize = 0x118; const XMP_START: &[u8] = b" u32 { - u32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap()) + u32::from_le_bytes(std::array::from_fn(|i| bytes[offset + i])) } +/// The little-endian u64 at `offset`; see [`le_u32`]. fn le_u64(bytes: &[u8], offset: usize) -> u64 { - u64::from_le_bytes(bytes[offset..offset + 8].try_into().unwrap()) + u64::from_le_bytes(std::array::from_fn(|i| bytes[offset + i])) } /// One of the two master pages at the start of the file. diff --git a/src/database.rs b/src/database.rs index b4367d4..ccc918e 100644 --- a/src/database.rs +++ b/src/database.rs @@ -131,15 +131,17 @@ impl<'a> Database<'a> { fn u16(&self, offset: usize) -> Result { self.bytes - .get(offset..offset + 2) - .map(|b| u16::from_le_bytes(b.try_into().unwrap())) + .get(offset..) + .and_then(<[u8]>::first_chunk) + .map(|&b| u16::from_le_bytes(b)) .ok_or_else(|| corrupt(format!("read past end of file at {offset:#x}"))) } fn u32(&self, offset: usize) -> Result { self.bytes - .get(offset..offset + 4) - .map(|b| u32::from_le_bytes(b.try_into().unwrap())) + .get(offset..) + .and_then(<[u8]>::first_chunk) + .map(|&b| u32::from_le_bytes(b)) .ok_or_else(|| corrupt(format!("read past end of file at {offset:#x}"))) } @@ -283,8 +285,10 @@ impl<'a> Database<'a> { "continued record at {offset:#x} is too short" ))); } - let next = u32::from_le_bytes(record[..4].try_into().unwrap()); - let next_page = u32::from_le_bytes(record[4..8].try_into().unwrap()); + // `record` starts at `offset + 4` and is at least 8 bytes long. + let next = self.u32(offset + 4)?; + let next_page = self.u32(offset + 8)?; + let here = &record[8..]; if here.is_empty() || here.len() >= len || next & 0xFFFF != 0 { return Err(corrupt(format!("bad continuation at {offset:#x}"))); diff --git a/src/header.rs b/src/header.rs index 3d022c0..fb2d779 100644 --- a/src/header.rs +++ b/src/header.rs @@ -28,8 +28,13 @@ pub enum ByteOrder { } impl ByteOrder { + /// The u32 at `offset` in this byte order. + /// + /// # Panics + /// + /// If `bytes` is shorter than `offset + 4`. pub fn read_u32(self, bytes: &[u8], offset: usize) -> u32 { - let b: [u8; 4] = bytes[offset..offset + 4].try_into().unwrap(); + let b: [u8; 4] = std::array::from_fn(|i| bytes[offset + i]); match self { ByteOrder::Little => u32::from_le_bytes(b), ByteOrder::Big => u32::from_be_bytes(b), @@ -78,7 +83,8 @@ impl Header { other => return Err(Error::UnknownByteOrder(other)), }; Ok(Header { - kind: bytes[KIND_OFFSET..KIND_OFFSET + 8].try_into().unwrap(), + kind: std::array::from_fn(|i| bytes[KIND_OFFSET + i]), + byte_order, version: Version { major: byte_order.read_u32(bytes, MAJOR_OFFSET), diff --git a/src/idml/styles.rs b/src/idml/styles.rs index fd1bf98..cc5d7a8 100644 --- a/src/idml/styles.rs +++ b/src/idml/styles.rs @@ -563,13 +563,8 @@ impl Writer<'_> { && b == c && c == e { - node.set(&["TextFramePreference", "Properties"], Vec::new()); - let props = node - .children - .iter_mut() - .find(|c| c.tag == "TextFramePreference") - .and_then(|t| t.children.iter_mut().find(|c| c.tag == "Properties")) - .expect("set above"); + let props = node.set(&["TextFramePreference", "Properties"], Vec::new()); + props.children.retain(|c| c.tag != "InsetSpacing"); props.children.push(Node { tag: "InsetSpacing".into(), diff --git a/src/idml/values.rs b/src/idml/values.rs index 23f29e0..d599b51 100644 --- a/src/idml/values.rs +++ b/src/idml/values.rs @@ -30,8 +30,9 @@ impl Node { /// Set the attributes of the descendant at `path`, creating missing /// elements (`Properties` as the first child), replacing values - /// already there in place and adding the others at the end. - pub fn set(&mut self, path: &[&str], attrs: Vec<(&str, String)>) { + /// already there in place and adding the others at the end. Returns + /// the descendant. + pub fn set(&mut self, path: &[&str], attrs: Vec<(&str, String)>) -> &mut Node { let mut node = self; for tag in path { let i = match node.children.iter().position(|c| c.tag == *tag) { @@ -58,6 +59,7 @@ impl Node { None => node.attrs.push((k.to_string(), v)), } } + node } /// Add the attributes and children of `other` that `self` lacks. @@ -97,6 +99,25 @@ impl Node { } } +/// An embedded values file, parsed. The files are generated and committed, +/// and the test `embedded_files_parse` checks that each one parses and +/// that every version bound in it is a number. A file that did not parse +/// would give no observed values instead of stopping every conversion. +fn embedded(text: &str) -> Node { + parse(text).unwrap_or_default() +} + +/// Whether a block of a values file applies to InDesign version `major`: +/// its `MinimumVersion` and `MaximumVersion`, where present, include +/// `major`. A bound that is not a number excludes the block (see +/// [`embedded`]). +fn applies(block: &Node, major: u32) -> bool { + // `None`: no bound; `Some(None)`: a bound that is not a number. + let bound = |name: &str| block.attr(name).map(|v| v.parse::().ok()); + bound("MinimumVersion").is_none_or(|v| v.is_some_and(|v| v <= major)) + && bound("MaximumVersion").is_none_or(|v| v.is_some_and(|v| major <= v)) +} + const ROOT_VALUES: &str = include_str!("root_values.xml"); /// The observed values of root style element `tag` (`ParagraphStyle`, @@ -106,12 +127,9 @@ pub fn root_style(tag: &str, major: u32) -> Node { tag: tag.to_string(), ..Node::default() }; - let root = parse(ROOT_VALUES).expect("root_values.xml is well-formed"); + let root = embedded(ROOT_VALUES); for block in &root.children { - let since = block - .attr("MinimumVersion") - .map_or(0, |v| v.parse().expect("MinimumVersion is a number")); - if since <= major + if applies(block, major) && let Some(n) = block.child(tag) { out.merge(n); @@ -131,14 +149,9 @@ pub fn object_style(major: u32) -> Node { }; // Parsed once: the converter asks for these values for every page item. static PARSED: std::sync::OnceLock = std::sync::OnceLock::new(); - let root = PARSED.get_or_init(|| { - parse(OBJECT_STYLE_VALUES).expect("object_style_values.xml is well-formed") - }); + let root = PARSED.get_or_init(|| embedded(OBJECT_STYLE_VALUES)); for block in &root.children { - let since = block - .attr("MinimumVersion") - .map_or(0, |v| v.parse().expect("MinimumVersion is a number")); - if since <= major + if applies(block, major) && let Some(n) = block.child("ObjectStyle") { out.merge(n); @@ -152,13 +165,10 @@ const PREFERENCE_VALUES: &str = include_str!("preference_values.xml"); /// The observed preference elements (`TextDefault`, ...) for a document of /// InDesign version `major`, in the order the IDML files list them. pub fn preferences(major: u32) -> Vec { - let root = parse(PREFERENCE_VALUES).expect("preference_values.xml is well-formed"); + let root = embedded(PREFERENCE_VALUES); let mut out: Vec = Vec::new(); for block in &root.children { - let since = block - .attr("MinimumVersion") - .map_or(0, |v| v.parse().expect("MinimumVersion is a number")); - if since > major { + if !applies(block, major) { continue; } for n in &block.children { @@ -175,19 +185,7 @@ const ELEMENT_VALUES: &str = include_str!("element_values.xml"); fn element_values() -> &'static Node { static PARSED: std::sync::OnceLock = std::sync::OnceLock::new(); - PARSED.get_or_init(|| parse(ELEMENT_VALUES).expect("element_values.xml is well-formed")) -} - -/// Whether a block of `element_values.xml` applies to InDesign version -/// `major`. -fn applies(block: &Node, major: u32) -> bool { - let bound = |name: &str| { - block - .attr(name) - .map(|v| v.parse::().expect("version bounds are numbers")) - }; - bound("MinimumVersion").is_none_or(|v| v <= major) - && bound("MaximumVersion").is_none_or(|v| major <= v) + PARSED.get_or_init(|| embedded(ELEMENT_VALUES)) } /// The observed values of the elements on `path` (a tag, or a tag and a @@ -390,6 +388,26 @@ fn parse(s: &str) -> Option { mod tests { use super::*; + #[test] + fn embedded_files_parse() { + for (name, text) in [ + ("root_values.xml", ROOT_VALUES), + ("object_style_values.xml", OBJECT_STYLE_VALUES), + ("preference_values.xml", PREFERENCE_VALUES), + ("element_values.xml", ELEMENT_VALUES), + ] { + let root = parse(text).unwrap_or_else(|| panic!("{name} does not parse")); + assert!(!root.children.is_empty(), "{name} has no blocks"); + for block in &root.children { + for bound in ["MinimumVersion", "MaximumVersion"] { + if let Some(v) = block.attr(bound) { + assert!(v.parse::().is_ok(), "{name}: {bound}=\"{v}\""); + } + } + } + } + } + #[test] fn unescapes_numeric_references() { assert_eq!(unescape("a b &lt;&x"), "a\tb\u{3000}<&x"); diff --git a/src/idml/xml.rs b/src/idml/xml.rs index 5dc112b..4dc95e0 100644 --- a/src/idml/xml.rs +++ b/src/idml/xml.rs @@ -186,8 +186,16 @@ impl Xml { self } + /// Close the current element. Every `end` follows its `start` in the + /// writer's code, whatever the input; an `end` with no open element + /// is a writer bug, fails a debug assertion, and writes nothing in a + /// release build. pub fn end(&mut self) -> &mut Self { - let name = self.stack.pop().expect("end without start"); + debug_assert!(!self.stack.is_empty(), "end without start"); + let Some(name) = self.stack.pop() else { + return self; + }; + if self.open { self.flush_attrs(); self.out.push_str(" />"); diff --git a/src/lib.rs b/src/lib.rs index 6fb1a8c..91cfc96 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -29,7 +29,23 @@ //! that inspect files: [`Header`], [`Container`], [`Database`], [`Object`] //! and the [`model`]. +#![forbid(unsafe_code)] +// Malformed input gives an error or a warning, never a panic. Unit tests +// may unwrap and panic. +#![cfg_attr( + not(test), + deny( + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::unimplemented, + clippy::todo, + clippy::unreachable + ) +)] + pub mod audit; + pub mod container; pub mod database; pub mod header; diff --git a/src/main.rs b/src/main.rs index 07b0e2d..6b2f611 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,7 +2,21 @@ //! inside an INDD file (header, objects, chunks, XMP, audit). Run it //! without arguments for the list of subcommands. +#![forbid(unsafe_code)] +#![cfg_attr( + not(test), + deny( + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::unimplemented, + clippy::todo, + clippy::unreachable + ) +)] + use std::io::Write; + use std::process::ExitCode; const USAGE: &str = "usage: diff --git a/src/model/attrs.rs b/src/model/attrs.rs index fa5b7dd..34cf48a 100644 --- a/src/model/attrs.rs +++ b/src/model/attrs.rs @@ -270,8 +270,9 @@ impl Attrs { match (i, &first) { (0, _) => first = Some(decode(enc, id, t, data)), (1, Some(Value::Ref(r))) if t == ty::CODE && len == 4 => { - let code = enc.u32_from(data.try_into().unwrap()); - first = Some(Value::RefOrCode(*r, code)); + if let Some(code) = enc.u32_at(data, 0) { + first = Some(Value::RefOrCode(*r, code)); + } } _ => {} } @@ -333,12 +334,13 @@ fn text_layout(id: u32) -> Option { /// fit it); the others are numbers of 8, 4 or 2 bytes. fn decode_text(enc: Encoding, id: u32, t: u32, data: &[u8]) -> Value { let Some(layout) = text_layout(id) else { - return match data.len() { - 8 => Value::Double(enc.f64_from(data.try_into().unwrap())), - 4 => Value::Ref(enc.u32_from(data.try_into().unwrap())), - 2 => Value::Enum(enc.u16_from(data.try_into().unwrap())), - _ => Value::Other(t, data.to_vec()), + let number = match data.len() { + 8 => enc.f64_at(data, 0).map(Value::Double), + 4 => enc.u32_at(data, 0).map(Value::Ref), + 2 => enc.u16_at(data, 0).map(Value::Enum), + _ => None, }; + return number.unwrap_or_else(|| Value::Other(t, data.to_vec())); }; let mut c = enc.cursor(data); let value = match layout { @@ -432,31 +434,32 @@ fn nested_styles(c: &mut Cursor) -> Option> { pub const OPACITY_STOPS: [u32; 3] = [0x1EB8C, 0x1EB95, 0x1EB9E]; fn decode(enc: Encoding, id: u32, t: u32, data: &[u8]) -> Value { - let f = |o: usize| enc.f64_from(data[o..o + 8].try_into().unwrap()); + let f = |o: usize| enc.f64_at(data, o); if OPACITY_STOPS.contains(&id) - && let Some(n) = data - .get(..4) - .map(|b| enc.u32_from(b.try_into().unwrap()) as usize) + && let Some(n) = enc.u32_at(data, 0).map(|n| n as usize) && n > 0 && data.len() == 4 + n * 24 + && let Some(stops) = (0..n) + .map(|i| { + let at = |k: usize| f(4 + (3 * i + k) * 8); + Some([at(0)?, at(1)?, at(2)?]) + }) + .collect::>>() { - return Value::Stops( - (0..n) - .map(|i| [0, 1, 2].map(|k| f(4 + (3 * i + k) * 8))) - .collect(), - ); + return Value::Stops(stops); } - match (t, data.len()) { - (ty::DOUBLE, 8) => Value::Double(f(0)), - (ty::INT, 4) => Value::Int(enc.i32_from(data.try_into().unwrap())), - (ty::ENUM, 2) => Value::Enum(enc.u16_from(data.try_into().unwrap())), - (ty::REF, 4) => Value::Ref(enc.u32_from(data.try_into().unwrap())), - (ty::POINT, 16) => Value::Point(f(0), f(8)), + let value = match (t, data.len()) { + (ty::DOUBLE, 8) => f(0).map(Value::Double), + (ty::INT, 4) => enc.i32_at(data, 0).map(Value::Int), + (ty::ENUM, 2) => enc.u16_at(data, 0).map(Value::Enum), + (ty::REF, 4) => enc.u32_at(data, 0).map(Value::Ref), + (ty::POINT, 16) => f(0).zip(f(8)).map(|(x, y)| Value::Point(x, y)), // Other 4-byte types are references or codes (for example a // corner effect ID); keep the number. - (_, 4) => Value::Ref(enc.u32_from(data.try_into().unwrap())), - _ => Value::Other(t, data.to_vec()), - } + (_, 4) => enc.u32_at(data, 0).map(Value::Ref), + _ => None, + }; + value.unwrap_or_else(|| Value::Other(t, data.to_vec())) } #[cfg(test)] diff --git a/src/model/story.rs b/src/model/story.rs index b5b5bbc..944ba25 100644 --- a/src/model/story.rs +++ b/src/model/story.rs @@ -279,9 +279,8 @@ impl<'a> Reader<'a> { } if self.class(strand) == Some(hyperlink::class::RANGE_STRAND) && let Some(tree) = self.chunk(strand, hyperlink::chunk::RANGE_TREE)? - && tree.len() >= 4 + && let Some(first) = self.enc().u32_at(&tree, 0) { - let first = self.enc().u32_from(tree[..4].try_into().unwrap()); let pages = |uid| self.chunk(uid, hyperlink::chunk::RANGE_PAGE); match hyperlink::source_ranges(self.enc(), first, pages) { Ok(r) => sources.extend(r), diff --git a/src/model/variable.rs b/src/model/variable.rs index a9dec41..afda501 100644 --- a/src/model/variable.rs +++ b/src/model/variable.rs @@ -80,7 +80,8 @@ fn parse(enc: Encoding, uid: u32, data: &[u8]) -> Result { } 0xCAC0 => enc.u32_at(rest, 0) == Some(0x8C64) && zero(&rest[4..]), 0xCAAA => { - style = Some(enc.u32_from(rest[4..8].try_into().unwrap())); + style = enc.u32_at(rest, 4); + zero(&rest[..4]) && zero(&rest[8..]) } _ => zero(rest) && text.is_empty(), diff --git a/src/object.rs b/src/object.rs index e54240c..b260b59 100644 --- a/src/object.rs +++ b/src/object.rs @@ -94,8 +94,8 @@ impl Encoding { let mut pos = 0; while pos < bytes.len() { let head = bytes.get(pos..pos + 8)?; - let id = self.u32_from(head[..4].try_into().unwrap()); - let len = self.u32_from(head[4..].try_into().unwrap()) as usize; + let id = self.u32_at(head, 0)?; + let len = self.u32_at(head, 4)? as usize; let data = bytes.get(pos + 8..(pos + 8).checked_add(len)?)?; out.push(Chunk { id, data }); pos += 8 + len; @@ -214,6 +214,17 @@ impl<'a> Cursor<'a> { Ok(out) } + /// The next `N` bytes, as an array. + fn array(&mut self) -> Result<[u8; N], Error> { + let out = *self + .data + .get(self.pos..) + .and_then(<[u8]>::first_chunk) + .ok_or_else(|| short("bytes", self.pos))?; + self.pos += N; + Ok(out) + } + pub fn skip(&mut self, n: usize) -> Result<(), Error> { self.bytes(n).map(|_| ()) } @@ -223,19 +234,19 @@ impl<'a> Cursor<'a> { } pub fn u16(&mut self) -> Result { - Ok(self.enc.u16_from(self.bytes(2)?.try_into().unwrap())) + Ok(self.enc.u16_from(self.array()?)) } pub fn u32(&mut self) -> Result { - Ok(self.enc.u32_from(self.bytes(4)?.try_into().unwrap())) + Ok(self.enc.u32_from(self.array()?)) } pub fn i32(&mut self) -> Result { - Ok(self.enc.i32_from(self.bytes(4)?.try_into().unwrap())) + Ok(self.enc.i32_from(self.array()?)) } pub fn f64(&mut self) -> Result { - Ok(self.enc.f64_from(self.bytes(8)?.try_into().unwrap())) + Ok(self.enc.f64_from(self.array()?)) } /// A u32 count followed by that many u32 values.