PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
fix(fonts): decode each candidate font program once, within its size
aiongg05df6ee4b722
diff --git a/crates/fonts/src/embedding.rs b/crates/fonts/src/embedding.rsindex a5bb011e0..23f34dbb3 100644--- a/crates/fonts/src/embedding.rs+++ b/crates/fonts/src/embedding.rs@@ -1,9 +1,10 @@//! Unicode embedding of an explicitly supplied, embeddable TrueType face. Font files are//! document inputs or the optional craft-fonts build input, never system-interface fallbacks.+use std::collections::HashMap;use std::fmt::Write as _;-use pdfcraft_cos::{Dict, Document, Object, PdfString, Stream};+use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString, Stream};use skrifa::{FontRef, MetadataProvider,instance::{LocationRef, Size},@@ -173,7 +174,8 @@ pub fn embed_mapping(return Err("the font family name is invalid".into());}let glyph_map = if cff { cid_encoding.as_bytes() } else { gids.as_slice() };- if let Some(resource) = same_resource(doc, fonts, &name, bytes, glyph_map, cmap.as_bytes()) {+ let mut programs = ProgramMatch::new(bytes);+ if let Some(resource) = same_resource(doc, fonts, &name, &mut programs, glyph_map, cmap.as_bytes()) {return Ok(resource);}let mut descriptor = Dict::new();@@ -193,12 +195,7 @@ pub fn embed_mapping();// Reuse the program another resource of this page already has, else one registered on another// page; source subset programs stay untouched.- let existing = written(doc, fonts).find(|w| w.has_program(doc, bytes)).map(|w| w.program).or_else(|| {- doc.scan_objects().take(8192).find_map(|(r, o)| match o.as_ref() {- Object::Stream(s) if is_program(doc, s, bytes) => Some(Object::Ref(r)),- _ => None,- })- });+ let existing = existing_program(doc, fonts, &mut programs);let program = existing.unwrap_or_else(|| {let mut d = Dict::new();d.set(b"Length1".to_vec(), Object::Int(bytes.len() as i64));@@ -246,14 +243,66 @@ pub fn embed_mapping(Ok(resource)}-/// The decoded data of the stream `object` refers to.-fn stream_data(doc: &Document, object: Option<&Object>) -> Option<Vec<u8>> {- match doc.resolve(object?).as_ref() {- Object::Stream(s) => s.decoded_within(17 << 20).ok(),- _ => None,+/// Whether the stream `object` refers to decodes to `expected`.+fn stream_is(doc: &Document, object: Option<&Object>, expected: &[u8]) -> bool {+ object.is_some_and(|o| match doc.resolve(o).as_ref() {+ Object::Stream(s) => s.decoded_within(expected.len()).is_ok_and(|d| d == expected),+ _ => false,+ })+}++/// Full programs one embedding decodes at most while looking for its own. A real match passes+/// the cheap checks and decodes once; many candidates that pass them come from a hostile file.+const MAX_PROGRAM_DECODES: usize = 16;++/// Recognises the full program written for `bytes`: each candidate stream decodes at most once+/// and within `bytes.len()`, and at most [`MAX_PROGRAM_DECODES`] decode in all.+struct ProgramMatch<'a> {+ bytes: &'a [u8],+ known: HashMap<ObjRef, bool>,+ decodes: usize,+}++impl<'a> ProgramMatch<'a> {+ fn new(bytes: &'a [u8]) -> Self {+ Self { bytes, known: HashMap::new(), decodes: 0 }+ }++ /// Whether `r`, holding `object`, is the program.+ fn is(&mut self, doc: &Document, r: ObjRef, object: &Object) -> bool {+ if let Some(&known) = self.known.get(&r) {+ return known;+ }+ let found = match object {+ Object::Stream(s)+ if s.dict.get(b"PCFullFont").is_some()+ && s.dict.get(b"Length1").and_then(|l| doc.resolve(l).as_int()) == i64::try_from(self.bytes.len()).ok()+ && self.decodes < MAX_PROGRAM_DECODES =>+ {+ self.decodes = self.decodes.saturating_add(1);+ s.decoded_within(self.bytes.len()).is_ok_and(|data| data == self.bytes)+ }+ _ => false,+ };+ self.known.insert(r, found);+ found+ }++ /// Whether the resource's program is this one.+ fn written(&mut self, doc: &Document, w: &Written) -> bool {+ w.program.as_ref().is_some_and(|r| self.is(doc, r, &*doc.get(r)))}}+/// The program for `programs.bytes` that this page's `PCFull` resources, or else the first+/// objects of the document, already have.+fn existing_program(doc: &Document, fonts: &Dict, programs: &mut ProgramMatch) -> Option<Object> {+ written(doc, fonts)+ .find(|w| programs.written(doc, w))+ .map(|w| w.program)+ .or_else(|| doc.scan_objects().take(8192).find_map(|(r, o)| programs.is(doc, r, &*o).then_some(Object::Ref(r))))+}+/// A `PCFull` resource that [`embed_mapping`] wrote.struct Written {resource: String,@@ -263,21 +312,6 @@ struct Written {program: Object,}-impl Written {- /// Whether its program is `bytes`.- fn has_program(&self, doc: &Document, bytes: &[u8]) -> bool {- matches!(doc.resolve(&self.program).as_ref(), Object::Stream(s) if is_program(doc, s, bytes))- }-}--/// Whether `s` is a full program written for `bytes`, compressed or not. The length it was-/// written with is compared before decoding.-fn is_program(doc: &Document, s: &Stream, bytes: &[u8]) -> bool {- s.dict.get(b"PCFullFont").is_some()- && s.dict.get(b"Length1").and_then(|l| doc.resolve(l).as_int()) == i64::try_from(bytes.len()).ok()- && s.decoded_within(17 << 20).is_ok_and(|data| data == bytes)-}-/// The `PCFull` resources in `fonts`, in order.fn written<'a>(doc: &'a Document, fonts: &'a Dict) -> impl Iterator<Item = Written> + 'a {fonts.iter().filter(|(key, _)| key.starts_with(b"PCFull")).take(256).filter_map(move |(key, value)| {@@ -291,14 +325,14 @@ fn written<'a>(doc: &'a Document, fonts: &'a Dict) -> impl Iterator<Item = Writt/// A resource in `fonts` that already is this embedding: the same font name, program, glyph map/// and Unicode map. Editing the same text again reuses it instead of adding another copy.-fn same_resource(doc: &Document, fonts: &Dict, name: &str, bytes: &[u8], glyph_map: &[u8], unicode: &[u8]) -> Option<String> {+fn same_resource(doc: &Document, fonts: &Dict, name: &str, programs: &mut ProgramMatch, glyph_map: &[u8], unicode: &[u8]) -> Option<String> {written(doc, fonts).find(|w| {let glyphs = w.cid.get(b"CIDToGIDMap").or_else(|| w.top.get(b"Encoding"));w.top.name(b"BaseFont") == Some(name.as_bytes())- && stream_data(doc, w.top.get(b"ToUnicode")).is_some_and(|d| d == unicode)- && stream_data(doc, glyphs).is_some_and(|d| d == glyph_map)- && w.has_program(doc, bytes)+ && stream_is(doc, w.top.get(b"ToUnicode"), unicode)+ && stream_is(doc, glyphs, glyph_map)+ && programs.written(doc, w)}).map(|w| w.resource)}@@ -385,6 +419,48 @@ mod tests {assert_eq!(programs(&doc), 2);}+ #[test]+ fn the_program_search_decodes_each_candidate_once_and_few_in_all() {+ let bytes = b"the program".as_slice();+ let decoy = |doc: &mut Document| {+ let mut d = Dict::new();+ d.set(b"PCFullFont".to_vec(), Object::Bool(true));+ d.set(b"Length1".to_vec(), Object::Int(bytes.len() as i64));+ doc.add(Object::Stream(Stream::flate(d, &[0; 4096])))+ };+ let resource = |doc: &mut Document, program: ObjRef| {+ let mut descriptor = Dict::new();+ descriptor.set(b"FontFile2".to_vec(), Object::Ref(program));+ let mut cid = Dict::new();+ cid.set(b"FontDescriptor".to_vec(), Object::Dict(descriptor));+ let mut top = Dict::new();+ top.set(b"DescendantFonts".to_vec(), Object::Array(vec![Object::Dict(cid)]));+ doc.add(Object::Dict(top))+ };+ // 200 resources sharing one decoy program decode it once.+ let mut doc = Document::new_empty();+ let shared = decoy(&mut doc);+ let mut fonts = Dict::new();+ for i in 0..200 {+ let r = resource(&mut doc, shared);+ fonts.set(format!("PCFull{i}").into_bytes(), Object::Ref(r));+ }+ let mut programs = ProgramMatch::new(bytes);+ assert_eq!(existing_program(&doc, &fonts, &mut programs), None);+ assert_eq!(programs.decodes, 1);+ // 100 distinct decoys decode a bounded number of times.+ let mut doc = Document::new_empty();+ let mut fonts = Dict::new();+ for i in 0..100 {+ let program = decoy(&mut doc);+ let r = resource(&mut doc, program);+ fonts.set(format!("PCFull{i}").into_bytes(), Object::Ref(r));+ }+ let mut programs = ProgramMatch::new(bytes);+ assert_eq!(existing_program(&doc, &fonts, &mut programs), None);+ assert_eq!(programs.decodes, MAX_PROGRAM_DECODES);+ }+#[test]fn the_full_program_is_written_compressed_and_another_page_reuses_it() {let bytes = include_bytes!("../../../assets/fonts/Inter-Regular.ttf");