pdfcer_model/objstm.rs
1//! # Object streams (ISO 32000-1 §7.5.7) — compressed indirect objects
2//!
3//! A PDF 1.5 **object stream** is an ordinary stream object whose
4//! decoded data holds a sequence of *other* indirect objects, so that
5//! non-stream objects can be compressed by a stream filter. A type-2
6//! cross-reference entry (§7.5.8.3 Table 18; [`XrefEntry::InStream`])
7//! names the container and the index within it; this module turns that
8//! pair into a parsed [`Object`].
9//!
10//! Spec source: `iso32000__s__7.5.7.md` (Table 16, the decoded layout,
11//! the `Extends` collection model) in the PDF-spec RAG, plus
12//! `iso32000__s__7.3.10.md` for the generation rule. Clause numbers are
13//! ISO 32000-1:2008.
14//!
15//! [`XrefEntry::InStream`]: crate::xref::XrefEntry::InStream
16//!
17//! ## The decoded layout
18//!
19//! ```text
20//! ┌──────────────────────────────────────────────┐
21//! │ N pairs of integers: objnum offset … │ ← the "pair table"
22//! │ │
23//! ├──────────────────────────────────────────────┤ ← byte `First`
24//! │ object 0's value │
25//! │ object 1's value │
26//! │ … │
27//! └──────────────────────────────────────────────┘
28//! ```
29//!
30//! Three rules from §7.5.7 that a naïve implementation gets wrong:
31//!
32//! 1. **Each pair's offset is relative to `First`**, not to the start
33//! of the decoded data. Absolute position = `First + offset`.
34//! 2. **Offsets are increasing, object numbers are NOT.** NOTE 6:
35//! "there is no restriction on the order of objects in the object
36//! stream; in particular, the objects need not be stored in
37//! object-number order." So the pair table must never be
38//! binary-searched by object number — index into it positionally,
39//! which is exactly what the type-2 entry's field 3 gives.
40//! 3. **No `obj`/`endobj` framing.** "Only the object values are
41//! stored in the stream; the `obj` and `endobj` keywords shall not
42//! be used." Each object is parsed as a bare direct value, and its
43//! identity comes from the pair table, not from the bytes.
44//!
45//! A conforming writer places the first object immediately after the
46//! pair table, but "a conforming reader **shall rely on the `First`
47//! entry**" — so `First` is authoritative here and the pair table's
48//! extent is never used to locate object data.
49//!
50//! ## What cannot be in an object stream (and why that bounds us)
51//!
52//! §7.5.7 forbids: stream objects, objects with a non-zero generation,
53//! the encryption dictionary, the object that is the value of an object
54//! stream's own `/Length`, and (in linearized files) the catalog, the
55//! linearization dictionary and page objects.
56//!
57//! Two of those are load-bearing for this module's guarantees:
58//!
59//! - **No streams inside** means a parsed compressed object can never
60//! carry a [`ByteSpan`](crate::span::ByteSpan) — [`Object`] holds
61//! spans only inside [`Object::Stream`]. So the decoded buffer can be
62//! dropped after parsing without leaving dangling coordinates, and
63//! the object's provenance is honestly
64//! [`Provenance::ObjectStream`](crate::object::Provenance::ObjectStream)
65//! with no file span at all.
66//! - **The `/Length` object cannot itself be compressed**, which bounds
67//! the resolution recursion: fetching a container's `/Length` can
68//! never require fetching another container.
69//!
70//! ## `Extends` is not followed at read time
71//!
72//! Table 16's `Extends` links object streams into a collection ("a
73//! directed acyclic graph") so an update can add objects to a
74//! collection without rewriting the original stream. It is
75//! **informational for a reader**: a type-2 entry names the specific
76//! container and index directly, so resolution never walks the chain.
77//! pdfcer therefore does not follow it — which also means the "damaged
78//! file cycles through `Extends`" hazard cannot arise here at all,
79//! rather than being defended against with a depth counter. A future
80//! *writer* doing collection updates is where `Extends` becomes live,
81//! and that is where its cycle guard belongs.
82//!
83//! ## Guards (ARCHITECTURE.md §10 — pdfcer policy, not spec)
84//!
85//! - [`MAX_OBJSTM_OBJECTS`] bounds `/N` before any allocation, so a
86//! hostile `/N 4000000000` cannot make the pair-table `Vec` reserve
87//! gigabytes.
88//! - The pair table is read strictly **within** the first `First`
89//! bytes; a pair claiming to live past `First` is malformed rather
90//! than an excuse to read into object data.
91//! - Filter decoding runs through `crate::filters`, which enforces
92//! `MAX_DECODED_LEN` incrementally (decompression-bomb ceiling).
93//!
94//! ## Failure posture
95//!
96//! Every failure is a structured [`ObjStmError`], never a panic and
97//! never a partially-decoded object presented as complete — the same
98//! fail-clean contract the filter and parser layers hold.
99
100use crate::filters::{self, FilterError};
101use crate::lexer::{Lexer, TokenKind};
102use crate::object::{Dict, Name, Object};
103use crate::parser::{ParseError, Parser};
104
105/// Maximum number of objects (`/N`) accepted in a single object stream.
106///
107/// pdfcer policy (ARCHITECTURE.md §10.1): ISO 32000-1 sets no limit —
108/// NOTE 4 merely *advises* writers to keep object streams small so a
109/// reader need not decompress a large stream to reach one object. One
110/// million objects in a single container is orders of magnitude beyond
111/// any real producer while bounding the pair-table allocation.
112pub const MAX_OBJSTM_OBJECTS: usize = 1_000_000;
113
114/// Something went wrong reading an object stream (§7.5.7).
115///
116/// C-GOOD-ERR via `thiserror`; every variant is `Send + Sync +
117/// 'static`. Variants name the specific spec rule violated so a
118/// diagnostic can point at the producer's actual mistake.
119#[derive(Debug, Clone, PartialEq, thiserror::Error)]
120#[non_exhaustive]
121pub enum ObjStmError {
122 /// The object a type-2 entry named as its container is not a stream
123 /// object at all (§7.5.7: an object stream is a stream).
124 #[error("the container object is not a stream")]
125 NotAStream,
126 /// The container's `/Type` is present but is not `/ObjStm`
127 /// (Table 16, Required).
128 #[error("container /Type is present but is not /ObjStm")]
129 WrongType,
130 /// `/N` (Table 16, Required) is missing or not a direct
131 /// non-negative integer.
132 ///
133 /// Table 16 does not mark `/N` direct-only, but resolving an
134 /// indirect `/N` would require a document-level resolve *inside*
135 /// the loader that is building the document — pdfcer refuses rather
136 /// than reordering the load for a case no real producer emits.
137 #[error("/N missing or not a direct non-negative integer")]
138 BadObjectCount,
139 /// `/First` (Table 16, Required) is missing, not a direct
140 /// non-negative integer, or points past the end of the decoded
141 /// data.
142 #[error("/First missing, invalid, or past the end of the decoded data")]
143 BadFirst,
144 /// `/N` exceeded [`MAX_OBJSTM_OBJECTS`] (pdfcer guard).
145 #[error("object count {0} exceeds MAX_OBJSTM_OBJECTS ({MAX_OBJSTM_OBJECTS})")]
146 TooManyObjects(usize),
147 /// The `N` `objnum offset` integer pairs could not be read from the
148 /// region before `/First` — too few numbers, a non-integer token, a
149 /// negative value, or a pair extending past `/First`.
150 #[error("malformed object-stream pair table")]
151 BadPairTable,
152 /// The container's raw data span did not lie inside the retained
153 /// buffer (a loader-side coordinate bug, surfaced rather than
154 /// panicked).
155 #[error("container stream data lies outside the source buffer")]
156 DataOutOfRange,
157 /// A type-2 entry's index is past the last pair in the table.
158 #[error("index {index} is out of range for an object stream holding {count} object(s)")]
159 IndexOutOfRange {
160 /// The requested 0-based index.
161 index: usize,
162 /// How many objects the pair table actually describes.
163 count: usize,
164 },
165 /// `First + offset` for the requested object falls outside the
166 /// decoded data.
167 #[error("object offset is outside the decoded object-stream data")]
168 OffsetOutOfRange,
169 /// The container's `/Filter` chain failed to decode.
170 #[error("object-stream data could not be decoded: {0}")]
171 Decode(#[from] FilterError),
172 /// The bytes at the object's position are not a well-formed COS
173 /// object.
174 #[error("compressed object does not parse: {0}")]
175 Parse(#[from] ParseError),
176 /// The stored object consists solely of an indirect reference —
177 /// §7.5.7 states an object in an object stream "shall not consist
178 /// solely of an object reference" (its EXAMPLE 2 of the forbidden
179 /// form is `3 0 R`). The prohibition exists to prevent an aliasing
180 /// ambiguity; the spec does not define reader behaviour, so pdfcer
181 /// treats it as malformed.
182 #[error("compressed object consists solely of an indirect reference")]
183 SoleReference,
184}
185
186/// A decoded object stream, ready for positional object lookup.
187///
188/// Constructed once per container by [`ObjectStream::parse`] and cached
189/// by the document loader — decoding is the expensive part and a
190/// container typically holds dozens to hundreds of objects, each of
191/// which would otherwise re-inflate the whole thing.
192#[derive(Debug, Clone, PartialEq, Eq)]
193pub struct ObjectStream {
194 /// The fully decoded stream data (pair table + object values).
195 data: Vec<u8>,
196 /// `/First`: byte offset in `data` of the first object value.
197 first: usize,
198 /// The pair table, in stored order: `(object number, offset
199 /// relative to `first`)`. Index into this positionally — see the
200 /// module docs on why object-number search is wrong.
201 pairs: Vec<(u32, usize)>,
202}
203
204impl ObjectStream {
205 /// Decode `raw` through `dict`'s filter chain and read its Table 16
206 /// header and pair table.
207 ///
208 /// `dict` is the container's stream dictionary and `raw` its
209 /// still-encoded `data_span` bytes.
210 ///
211 /// # Errors
212 ///
213 /// [`ObjStmError`] — see the variants; each names the §7.5.7 rule
214 /// that was violated.
215 pub fn parse(dict: &Dict, raw: &[u8]) -> Result<Self, ObjStmError> {
216 // Table 16: `/Type` shall be `/ObjStm`. As with cross-reference
217 // streams, a *wrong* type is refused (the xref pointed at
218 // something else entirely) while an *absent* type is tolerated:
219 // `/N` and `/First` are what actually drive decoding.
220 if let Some(ty) = dict.get(b"Type")
221 && ty.as_name().map(Name::as_bytes) != Some(b"ObjStm")
222 {
223 return Err(ObjStmError::WrongType);
224 }
225
226 let count = dict
227 .get(b"N")
228 .and_then(Object::as_int)
229 .and_then(|v| usize::try_from(v).ok())
230 .ok_or(ObjStmError::BadObjectCount)?;
231 if count > MAX_OBJSTM_OBJECTS {
232 return Err(ObjStmError::TooManyObjects(count));
233 }
234 let first = dict
235 .get(b"First")
236 .and_then(Object::as_int)
237 .and_then(|v| usize::try_from(v).ok())
238 .ok_or(ObjStmError::BadFirst)?;
239
240 let data = filters::decode_stream(dict, raw)?;
241 if first > data.len() {
242 return Err(ObjStmError::BadFirst);
243 }
244
245 let pairs = read_pair_table(&data, first, count)?;
246 Ok(Self { data, first, pairs })
247 }
248
249 /// How many objects the pair table describes (`/N`, as actually
250 /// read).
251 #[must_use]
252 pub fn len(&self) -> usize {
253 self.pairs.len()
254 }
255
256 /// The object numbers this container holds, in stored (index) order.
257 ///
258 /// Cheap: it reads the already-parsed pair table without decoding any
259 /// object *value* (unlike [`ObjectStream::object_at`]). It exists for
260 /// the cross-reference **recovery** path (`crate::recover`), which
261 /// rebuilds the type-2 (`InStream`) entries a lost xref would
262 /// otherwise have named — recovery needs only *which numbers* live in
263 /// *which container at what index*, exactly the type-2 entry's fields
264 /// (§7.5.8.3 Table 18), and the pair table is the authority for that
265 /// (module docs). The index of each yielded number is its position in
266 /// the iterator, i.e. the type-2 entry's field 3.
267 pub fn member_numbers(&self) -> impl Iterator<Item = u32> + '_ {
268 self.pairs.iter().map(|&(num, _)| num)
269 }
270
271 /// Decoded byte length of each member, in stored (index) order.
272 ///
273 /// A member runs from its pair-table offset to the next larger offset, the
274 /// last to the end of the decoded data. The pair table and its separators,
275 /// which sit before `/First`, are not attributed to any member. Offsets
276 /// out of order or out of range yield 0 for that member rather than an
277 /// error: this answers "how much space", a measurement, not a parse.
278 #[must_use]
279 pub fn member_lengths(&self) -> Vec<usize> {
280 let body = self.data.len().saturating_sub(self.first);
281 let mut starts: Vec<usize> = self.pairs.iter().map(|&(_, rel)| rel.min(body)).collect();
282 starts.sort_unstable();
283 self.pairs
284 .iter()
285 .map(|&(_, rel)| {
286 let rel = rel.min(body);
287 let end = starts.iter().copied().find(|&s| s > rel).unwrap_or(body);
288 end - rel
289 })
290 .collect()
291 }
292
293 /// Whether the container holds no objects.
294 #[must_use]
295 pub fn is_empty(&self) -> bool {
296 self.pairs.is_empty()
297 }
298
299 /// Parse the object stored at 0-based `index`, returning its
300 /// declared object number (from the pair table) and its value.
301 ///
302 /// The object number is returned rather than assumed so the caller
303 /// can cross-check it against the object number the type-2
304 /// cross-reference entry promised — a mismatch means the xref and
305 /// the container disagree, which the strict loader refuses instead
306 /// of silently trusting one of them.
307 ///
308 /// # Errors
309 ///
310 /// [`ObjStmError::IndexOutOfRange`], [`ObjStmError::OffsetOutOfRange`],
311 /// [`ObjStmError::Parse`], or [`ObjStmError::SoleReference`].
312 pub fn object_at(&self, index: usize) -> Result<(u32, Object), ObjStmError> {
313 let &(num, rel) = self.pairs.get(index).ok_or(ObjStmError::IndexOutOfRange {
314 index,
315 count: self.pairs.len(),
316 })?;
317 // Absolute position = First + offset (module docs rule 1).
318 let start = self
319 .first
320 .checked_add(rel)
321 .ok_or(ObjStmError::OffsetOutOfRange)?;
322 if start > self.data.len() {
323 return Err(ObjStmError::OffsetOutOfRange);
324 }
325 // No `obj`/`endobj` framing (module docs rule 3): a bare value.
326 let value = Parser::at(&self.data, start).parse_object()?;
327 if matches!(value, Object::Reference(_)) {
328 return Err(ObjStmError::SoleReference);
329 }
330 Ok((num, value))
331 }
332}
333
334/// Read `count` `objnum offset` integer pairs from the region of `data`
335/// before `first`.
336///
337/// Tokenizing (rather than hand-scanning digits) is deliberate: §7.5.7
338/// specifies only "N pairs of integers separated by white space", and
339/// the lexer already implements §7.2's white-space and comment rules.
340/// Every consumed token is bounds-checked against `first` so the pair
341/// table can never run into object data.
342fn read_pair_table(
343 data: &[u8],
344 first: usize,
345 count: usize,
346) -> Result<Vec<(u32, usize)>, ObjStmError> {
347 let mut lexer = Lexer::at(data, 0);
348 let mut pairs = Vec::with_capacity(count);
349 for _ in 0..count {
350 let num = next_pair_int(&mut lexer, first)?;
351 let offset = next_pair_int(&mut lexer, first)?;
352 let num = u32::try_from(num).map_err(|_| ObjStmError::BadPairTable)?;
353 let offset = usize::try_from(offset).map_err(|_| ObjStmError::BadPairTable)?;
354 pairs.push((num, offset));
355 }
356 Ok(pairs)
357}
358
359/// Read one non-negative integer token from the pair table, refusing
360/// anything that ends at or past `first` (i.e. that would be reading
361/// object data, not header).
362fn next_pair_int(lexer: &mut Lexer<'_>, first: usize) -> Result<i64, ObjStmError> {
363 let token = lexer
364 .next_token()
365 .map_err(|_| ObjStmError::BadPairTable)?
366 .ok_or(ObjStmError::BadPairTable)?;
367 if token.span.end() > first {
368 return Err(ObjStmError::BadPairTable);
369 }
370 match token.kind {
371 TokenKind::Integer(v) if v >= 0 => Ok(v),
372 _ => Err(ObjStmError::BadPairTable),
373 }
374}
375
376#[cfg(test)]
377#[allow(
378 clippy::unwrap_used,
379 clippy::expect_used,
380 clippy::panic,
381 clippy::indexing_slicing
382)]
383mod tests {
384 use super::*;
385 use crate::object::ObjId;
386
387 /// Build an object-stream dictionary + uncompressed data for the
388 /// given `(objnum, value-text)` list, laid out exactly per §7.5.7.
389 fn build(objects: &[(u32, &str)]) -> (Dict, Vec<u8>) {
390 let mut body = String::new();
391 let mut header = String::new();
392 for (num, text) in objects {
393 header.push_str(&format!("{num} {} ", body.len()));
394 body.push_str(text);
395 body.push(' ');
396 }
397 let first = header.len();
398 let data = format!("{header}{body}").into_bytes();
399
400 let mut dict = Dict::new();
401 dict.insert(Name::from(b"Type"), Object::Name(Name::from(b"ObjStm")));
402 dict.insert(
403 Name::from(b"N"),
404 Object::Integer(i64::try_from(objects.len()).unwrap()),
405 );
406 dict.insert(
407 Name::from(b"First"),
408 Object::Integer(i64::try_from(first).unwrap()),
409 );
410 dict.insert(
411 Name::from(b"Length"),
412 Object::Integer(i64::try_from(data.len()).unwrap()),
413 );
414 (dict, data)
415 }
416
417 #[test]
418 fn reads_pair_table_and_objects_in_stored_order() {
419 // NOTE 6: object numbers need NOT ascend — offsets must.
420 let (dict, data) = build(&[
421 (7, "<< /Type /Catalog /Pages 2 0 R >>"),
422 (2, "<< /Type /Pages /Kids [] /Count 0 >>"),
423 (9, "42"),
424 ]);
425 let objstm = ObjectStream::parse(&dict, &data).unwrap();
426 assert_eq!(objstm.len(), 3);
427
428 let (num, value) = objstm.object_at(0).unwrap();
429 assert_eq!(num, 7);
430 assert_eq!(
431 value
432 .as_dict()
433 .unwrap()
434 .get(b"Pages")
435 .unwrap()
436 .as_reference(),
437 Some(ObjId::new(2, 0))
438 );
439
440 let (num, value) = objstm.object_at(2).unwrap();
441 assert_eq!(num, 9);
442 assert_eq!(value.as_int(), Some(42));
443 }
444
445 #[test]
446 fn member_lengths_run_to_the_next_offset() {
447 let (dict, data) = build(&[(7, "<< /A 1 >>"), (2, "[1 2 3]"), (9, "42")]);
448 let objstm = ObjectStream::parse(&dict, &data).unwrap();
449 // Each body is followed by one separator space in `build`.
450 assert_eq!(objstm.member_lengths(), [11, 8, 3]);
451 }
452
453 #[test]
454 fn index_past_the_end_is_an_error_not_a_panic() {
455 let (dict, data) = build(&[(1, "null")]);
456 let objstm = ObjectStream::parse(&dict, &data).unwrap();
457 assert_eq!(
458 objstm.object_at(5).unwrap_err(),
459 ObjStmError::IndexOutOfRange { index: 5, count: 1 }
460 );
461 }
462
463 #[test]
464 fn sole_reference_is_refused() {
465 // §7.5.7: "An object in an object stream shall not consist
466 // solely of an object reference." Spec EXAMPLE 2: `3 0 R`.
467 let (dict, data) = build(&[(1, "3 0 R")]);
468 let objstm = ObjectStream::parse(&dict, &data).unwrap();
469 assert_eq!(objstm.object_at(0).unwrap_err(), ObjStmError::SoleReference);
470 }
471
472 #[test]
473 fn wrong_type_is_refused_missing_type_is_tolerated() {
474 let (mut dict, data) = build(&[(1, "null")]);
475 dict.insert(Name::from(b"Type"), Object::Name(Name::from(b"XRef")));
476 assert_eq!(
477 ObjectStream::parse(&dict, &data).unwrap_err(),
478 ObjStmError::WrongType
479 );
480
481 let (mut dict, data) = build(&[(1, "null")]);
482 dict.0.retain(|(k, _)| k.as_bytes() != b"Type");
483 assert!(ObjectStream::parse(&dict, &data).is_ok());
484 }
485
486 #[test]
487 fn first_past_end_of_data_is_refused() {
488 let (mut dict, data) = build(&[(1, "null")]);
489 dict.insert(Name::from(b"First"), Object::Integer(9999));
490 assert_eq!(
491 ObjectStream::parse(&dict, &data).unwrap_err(),
492 ObjStmError::BadFirst
493 );
494 }
495
496 #[test]
497 fn pair_table_running_past_first_is_refused() {
498 // `/N` claims more pairs than fit before `/First`: the extra
499 // reads would consume object data, so the table is malformed.
500 let (mut dict, data) = build(&[(1, "null")]);
501 dict.insert(Name::from(b"N"), Object::Integer(4));
502 assert_eq!(
503 ObjectStream::parse(&dict, &data).unwrap_err(),
504 ObjStmError::BadPairTable
505 );
506 }
507
508 #[test]
509 fn hostile_object_count_is_bounded_before_allocation() {
510 let (mut dict, data) = build(&[(1, "null")]);
511 let hostile = i64::try_from(MAX_OBJSTM_OBJECTS).unwrap() + 1;
512 dict.insert(Name::from(b"N"), Object::Integer(hostile));
513 assert!(matches!(
514 ObjectStream::parse(&dict, &data).unwrap_err(),
515 ObjStmError::TooManyObjects(_)
516 ));
517 }
518
519 #[test]
520 fn flate_encoded_container_decodes() {
521 use flate2::Compression;
522 use flate2::write::ZlibEncoder;
523 use std::io::Write as _;
524
525 let (mut dict, data) = build(&[(4, "(hello)")]);
526 let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
527 enc.write_all(&data).unwrap();
528 let compressed = enc.finish().unwrap();
529 dict.insert(
530 Name::from(b"Filter"),
531 Object::Name(Name::from(b"FlateDecode")),
532 );
533
534 let objstm = ObjectStream::parse(&dict, &compressed).unwrap();
535 let (num, value) = objstm.object_at(0).unwrap();
536 assert_eq!(num, 4);
537 assert_eq!(value, Object::String(b"hello".to_vec()));
538 }
539}