pdfcer_model/recover.rs
1//! # Cross-reference recovery — rebuild-by-scan (decision 013 Pass B)
2//!
3//! When a file's stored cross-reference machinery cannot be parsed
4//! ([`crate::xref::load_xref_chain`] returns `Err`, or the `%PDF-` header
5//! probe fails), this module reconstructs a usable cross-reference table
6//! and trailer by **scanning the whole buffer for `N G obj` headers** and
7//! walking any recovered object streams. It is the single highest-leverage
8//! real-world robustness fix in pdfcer: a swept 1,109-file real-world
9//! corpus showed 605 of 712 load failures (85%) were this one missing
10//! capability, and every mature reader (pdfium, qpdf, poppler, mupdf,
11//! pdf.js) closes the gap the same way. See
12//! `docs/decisions/013-xref-recovery.md`.
13//!
14//! ## Recovery is a FALLBACK, never the default (the load-bearing rule)
15//!
16//! Recovery runs **only after the strict path has already failed**. A file
17//! that returns `Ok(LoadedXref)` from `load_xref_chain` takes the normal
18//! path unchanged, with zero recovery code in its control flow — so the
19//! round-trip/minimal-diff invariant (`ARCHITECTURE.md` §5) for cleanly
20//! loading files is preserved **by construction**, not by policy. The
21//! trigger lives in [`crate::document::Document::from_bytes`], gated by
22//! [`recovery_reason_for`]; this module is only ever entered on the error
23//! path.
24//!
25//! ## What is reconstructed vs. what is spec
26//!
27//! §7.5.4 (classic table), §7.5.5 (the load algorithm, `startxref`,
28//! `%%EOF`), §7.5.7 (object streams), §7.5.8 (cross-reference streams) and
29//! Annex H.7 define the **well-formed structure** this module rebuilds a
30//! valid instance of. **No ISO clause defines a recovery *procedure*** —
31//! rebuild-by-scan is a deliberate reader-robustness **policy** grounded
32//! in universal reader behaviour (the same outcome-over-method pattern the
33//! xref layer already uses, e.g. tolerating a missing `/Type` on an xref
34//! stream). Where recovery cannot succeed it fails clean (R27); it never
35//! returns a partial or guessed [`crate::document::Document`].
36//!
37//! ## The algorithm (two phases + trailer, mirroring the normal loader)
38//!
39//! **Phase 1 — file-level scan.** A single linear pass locates every
40//! `N G obj` header. Each candidate is then **confirmed** by actually
41//! parsing it with the ordinary [`Parser::parse_indirect_object`] (rule
42//! 13: no new tokenizer, no new dependency) — a candidate that does not
43//! parse, or whose parsed identity disagrees with its scanned header, is a
44//! binary-data false positive and is dropped. Confirmed objects are keyed
45//! by number **last-valid-wins by file order** (the reader convention:
46//! incremental updates append, so a later definition supersedes an
47//! earlier one). Each becomes a synthetic [`XrefEntry::InUse`].
48//!
49//! Confirmation runs under [`StreamLengthPolicy::RecoverFromEndstream`],
50//! **not** under the parser's default strictness. That one word is what
51//! makes the scan's object count match the file's real object count on
52//! damaged input. A `/Length` that does not land on `endstream` is
53//! §7.3.8.2 "an error" on the clean path, but here it is the single most
54//! common surviving symptom of the very damage that broke the
55//! cross-reference table in the first place: the dominant real-world shape
56//! is a file whose `/Length` values were computed with LF line endings and
57//! which was later converted to CRLF, growing every stream by one byte per
58//! line and shifting every stored offset (which is *why* `startxref` no
59//! longer points at `xref`). Confirming strictly would silently drop
60//! exactly the content streams the page tree then demands, turning a
61//! recoverable file into an unopenable one. Repairs are counted into
62//! [`RecoveryReport::stream_lengths_recovered`] and disclosed.
63//!
64//! The same policy must be used by [`crate::document`]'s re-parse of the
65//! recovered table — an object accepted here and rejected there would fail
66//! the whole load — which is why the policy is a parameter of
67//! [`parse_object_at`] rather than a local choice.
68//!
69//! **Phase 2 — object streams.** *After* phase 1 (the same forced order as
70//! [`crate::document`]'s normal two-phase load), every confirmed
71//! `/Type /ObjStm` container is decoded and its `/N` pair table read; each
72//! compressed member becomes a synthetic [`XrefEntry::InStream`] (type-2).
73//! Compressed members are **not** at file-level `N G obj` offsets, so the
74//! scan cannot find them directly — the container's pair table is the
75//! authority, exactly as a type-2 xref entry normally is. A file-level
76//! (scanned) definition **wins** over an object-stream member of the same
77//! number (a documented limitation: true newest-wins needs the revision
78//! ordering the scan discards). For a normal xref-stream file most objects
79//! arrive via this phase — the design handles "few file-level objects,
80//! bulk from ObjStm".
81//!
82//! **Trailer.** In priority order: (1) the **last `trailer` keyword**'s
83//! dictionary (classic files — the dominant offset-shift case); (2) a
84//! recovered cross-reference **stream** object's own Table 17 dictionary
85//! (§7.5.8.1: it "carries what a trailer would carry" — its *data* was
86//! unreadable, which is *why* strict failed, but its dictionary with
87//! `/Root`/`/Size`/`/Info`/`/Encrypt`/`/ID` parsed fine as an ordinary
88//! file-level object); (3) **synthesize** from a scanned `/Type /Catalog`
89//! object. The trailer is normalized to just the semantic keys — §5.6's
90//! "never normalize" governs *clean passthrough*, and a recovered file's
91//! base was invalid, so emitting a fresh classic form is correct, not a
92//! violation (decision 013 §3.3.4). If `/Encrypt` is present recovery
93//! refuses ([`RecoverError::Encrypted`]) — the same §7.6 capability gap
94//! the clean path enforces, re-checked here so a broken-xref-**and**-
95//! encrypted file still fails for the right reason. If no `/Catalog` can
96//! be found by any route, recovery fails clean ([`RecoverError::NoCatalog`]).
97//!
98//! ## Absolute offsets subsume the offset-start case
99//!
100//! The scan records `N G obj` at **absolute** byte positions and never
101//! trusts a stored offset, so it is header-independent: it also handles a
102//! file with leading bytes before `%PDF-` (the "offset start" case,
103//! decision 007 §10 item 6) with no rebasing — spans are absolute from
104//! byte 0 (`crate::span`). The [`RecoveryReport::offset_start`] flag simply
105//! records that the marker was not at byte 0.
106//!
107//! ## Resource guards (R25, `ARCHITECTURE.md` §10)
108//!
109//! The scan is O(n) single-pass. Total synthesized entries are capped by
110//! [`crate::xref::MAX_XREF_ENTRIES`] — an `obj`-token-dense adversarial
111//! file stops at the cap and fails clean rather than allocating without
112//! bound. Object-stream decoding in phase 2 runs through the same
113//! `crate::filters` / [`ObjectStream`] machinery as the normal path, so
114//! the §10.1 decompression-bomb ceilings apply. There is no recursion
115//! (§7.5.7's two-level guarantee holds for recovered containers too), and
116//! the "no catalog → refuse" terminal together with the entry cap bound
117//! worst-case work: recovery always terminates and never hangs.
118
119use std::collections::HashMap;
120use std::collections::hash_map::Entry;
121
122use crate::PdfVersion;
123use crate::document::parse_object_at;
124use crate::lexer::{is_delimiter, is_regular, is_whitespace};
125use crate::object::{Dict, Name, ObjId, Object};
126use crate::objstm::ObjectStream;
127use crate::parser::{Parser, StreamLengthPolicy, TerminatorPolicy};
128use crate::xref::{MAX_XREF_ENTRIES, XrefEntry, XrefErrorKind, XrefTable};
129
130/// Why the strict load failed, carried into the [`RecoveryReport`] so the
131/// disclosure (R20) can name the originating cause.
132///
133/// This is a self-contained enum rather than a borrow of
134/// [`XrefErrorKind`] so a recovered [`crate::document::Document`] does not
135/// pin the xref error's payloads for its whole lifetime. The mapping from
136/// an `XrefErrorKind` (and the header-probe failure) lives in
137/// [`recovery_reason_for`].
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139#[non_exhaustive]
140pub enum RecoveryReason {
141 /// No `startxref` keyword in the trailing scan window.
142 StartxrefNotFound,
143 /// `startxref` present but its offset was unusable / out of range.
144 BadStartxrefOffset,
145 /// The `startxref` target was neither an `xref` keyword nor an
146 /// `N G obj` stream header — the classic offset-shift signature.
147 NotAnXrefSection,
148 /// A classic 20-byte entry deviated from §7.5.4.
149 BadEntry,
150 /// A subsection header line was not `first count`.
151 BadSubsectionHeader,
152 /// The `trailer` dictionary was missing or malformed, or a `/Prev`
153 /// offset was out of range.
154 BadTrailer,
155 /// The `/Prev` chain was cyclic or exceeded the section cap.
156 PrevChainCycle,
157 /// The strict path hit the entry cap; recovery re-attempts under it.
158 TooManyEntries,
159 /// A cross-reference stream's dictionary/`W`/`Index`/data was
160 /// malformed — unrecoverable in place, so the file-level objects are
161 /// scanned instead.
162 BadXrefStream,
163 /// A cross-reference stream's filter chain failed to decode.
164 XrefStreamDecode,
165 /// A structural parse error inside the trailer dictionary.
166 TrailerParse,
167 /// The `%PDF-` header probe failed (offset-start / leading-junk /
168 /// headerless); recovery is header-independent and attempts a rebuild
169 /// anyway, succeeding only if it finds objects **and** a `/Catalog`.
170 MissingHeader,
171}
172
173/// Where the recovered trailer's keys came from — disclosed and counted
174/// (R20), because the operator should be able to tell a parsed trailer
175/// from a synthesized one.
176#[derive(Debug, Clone, Copy, PartialEq, Eq)]
177#[non_exhaustive]
178pub enum TrailerSource {
179 /// Parsed from the last `trailer` keyword's dictionary (§7.5.5) — the
180 /// classic-table case, which is the dominant offset-shift shape.
181 TrailerKeyword,
182 /// Lifted from a recovered cross-reference **stream** object's own
183 /// Table 17 dictionary (§7.5.8.1). The stream's *data* was unreadable
184 /// (that is why strict failed), but its dictionary — carrying `/Root`,
185 /// `/Size`, `/Info`, `/Encrypt`, `/ID` — parsed as an ordinary
186 /// file-level object.
187 XrefStreamDict,
188 /// Synthesized: `/Root` set to a scanned `/Type /Catalog` object,
189 /// `/Size` from the highest recovered number, `/ID`/`/Encrypt`/`/Info`
190 /// lifted from any recovered cross-reference-stream dictionary found.
191 SynthesizedFromCatalog,
192}
193
194/// One object the scan found and recovery could not keep.
195///
196/// Reachable only through [`RecoveryReport::objects_dropped`]; see that
197/// field for why the reason travels with the number.
198#[derive(Debug, Clone, PartialEq, Eq)]
199#[non_exhaustive]
200pub struct DroppedObject {
201 /// The object number from the `N G obj` header the scan matched.
202 pub number: u32,
203 /// Why it could not be kept.
204 pub reason: DropReason,
205}
206
207/// Why a scanned object was not kept.
208///
209/// Deliberately an enum rather than a string: a shell must be able to tell a
210/// **false positive** (bytes that merely looked like a header — routine, not
211/// a loss) from a **real object that would not parse** (a loss the operator
212/// may need to act on). A single prose sentence reads the same for both and
213/// makes the routine case as alarming as the serious one.
214#[derive(Debug, Clone, Copy, PartialEq, Eq)]
215#[non_exhaustive]
216pub enum DropReason {
217 /// The bytes at that offset did not parse as an object under any of
218 /// recovery's lenient policies. Usually binary data inside a stream that
219 /// happens to spell `N G obj`; occasionally a genuinely corrupt object,
220 /// which is the case worth surfacing.
221 Unparseable,
222 /// It parsed, but the object number in the body disagreed with the one
223 /// the scan matched — the definition cannot be trusted to be what the
224 /// offset claimed.
225 IdMismatch,
226}
227
228/// The counted, disclosed record of a recovery (fuzzy-never-sneaky, R20).
229///
230/// Stored on the recovered [`crate::document::Document`]; surfaced by the
231/// CLI (a diagnostic line + a distinct exit status) and the GUI (a
232/// non-blocking banner). Every field is a fact an operator can act on, so
233/// none is rounded away.
234#[derive(Debug, Clone, PartialEq, Eq)]
235#[non_exhaustive]
236pub struct RecoveryReport {
237 /// Why the strict load failed (the originating cause).
238 pub reason: RecoveryReason,
239 /// Objects recovered by the file-level `N G obj` scan (type-1).
240 pub file_level_objects: usize,
241 /// Objects recovered from `/Type /ObjStm` containers (type-2).
242 pub objstm_objects: usize,
243 /// Duplicate object numbers resolved last-valid-wins among file-level
244 /// definitions (how many times a number had more than one valid
245 /// definition).
246 pub last_wins_collisions: usize,
247 /// Recovered objects whose stream extent had to be re-derived from the
248 /// `endstream` keyword because the stored `/Length` was unusable
249 /// (absent, unresolvable, or simply not landing on `endstream` —
250 /// §7.3.8.2 defines `/Length` in terms of that keyword, so the two are
251 /// halves of one statement and this counts how often they disagreed).
252 ///
253 /// Counted over the objects actually **kept**, not over every candidate
254 /// examined, so the number matches what the loaded document contains.
255 /// A non-zero value means some stream's byte extent is pdfcer's reading
256 /// of the file rather than the file's own claim — the operator is told
257 /// (R20) because the two can differ, most visibly for a stream whose
258 /// binary data happens to contain the bytes `endstream`.
259 pub stream_lengths_recovered: usize,
260 /// How many definitions were accepted with **no `endobj` keyword**
261 /// (§7.3.10 requires one).
262 ///
263 /// Non-zero means the file omitted a required terminator and pdfcer
264 /// bounded the object at the next `N G obj` header instead of dropping
265 /// it. Dropping is what pdfcer used to do, and it is how a document
266 /// whose catalog named an absent `/Pages` object got written — see
267 /// [`crate::parser::TerminatorPolicy`]. Disclosed, never silent (R20).
268 pub missing_endobj_recovered: usize,
269 /// Objects the scan FOUND — a well-formed `N G obj` header at a byte
270 /// offset — and recovery could not keep, with the reason for each.
271 ///
272 /// # Why this is a list and not a count (`decision 145`, owed item 18)
273 ///
274 /// `decision 145` obliges pdfcer to disclose what it dropped rather than
275 /// return a shorter document and no explanation. It closed that gap at
276 /// the **loader**; the recovery path had the same gap and was measured
277 /// having it on a real file: `Annotations_output.pdf`, whose `startxref`
278 /// points 134 bytes short of its own `xref` (a PDFsharp writer bug),
279 /// recovers **10 of 11** objects and drops object 5 — the page's content
280 /// stream — with nothing recorded anywhere.
281 ///
282 /// Losing that object is the CORRECT outcome: its Flate data is genuinely
283 /// corrupt and keeping it would hand a caller bytes that cannot be
284 /// decoded. **Losing it silently is not**, and the difference is the whole
285 /// of rule 4 — an inference pdfcer made (this candidate is not usable) is
286 /// disclosed, never silent.
287 ///
288 /// A COUNT would not have been enough, and that is why this carries the
289 /// object number and the reason. The complaint that produced this item was
290 /// not "the number was wrong" — it was that a human holding a file with a
291 /// missing page could not find out WHICH object went or WHY. A bare
292 /// `dropped: 1` answers neither.
293 pub objects_dropped: Vec<DroppedObject>,
294 /// Where the recovered trailer's keys came from.
295 pub trailer_source: TrailerSource,
296 /// Whether the `%PDF-` marker was not at byte 0 (offset-start /
297 /// leading-junk / headerless) — recovery handled it via absolute
298 /// offsets with no rebasing.
299 pub offset_start: bool,
300}
301
302/// A reconstructed cross-reference table + trailer, ready for the document
303/// layer to eager-parse exactly as if [`crate::xref::load_xref_chain`] had
304/// produced it.
305#[derive(Debug, Clone)]
306#[non_exhaustive]
307pub struct RecoveredXref {
308 /// The synthesized merged table (type-1 file-level + type-2 ObjStm).
309 pub table: XrefTable,
310 /// The recovered trailer, normalized to `/Root`/`/Size`/`/Info`/
311 /// `/Encrypt`/`/ID`.
312 pub trailer: Dict,
313 /// Highest recovered object number (the number a writer allocates
314 /// above); also the basis for the synthesized `/Size`.
315 pub highest_object_number: u32,
316 /// PDF version detected by scanning for `%PDF-` (whole-buffer, so it
317 /// survives the offset-start case); a conservative default when the
318 /// file carries no marker at all.
319 pub version: PdfVersion,
320 /// The counted disclosure record.
321 pub report: RecoveryReport,
322}
323
324/// Why a recovery attempt could not produce a document — every case a
325/// **named, fail-clean refusal** (R27), never a partial/garbage document.
326#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
327#[non_exhaustive]
328pub enum RecoverError {
329 /// The scan found no confirmable `N G obj` objects at all — this is
330 /// not a recoverable PDF (the "not a PDF" outcome on the header path).
331 #[error("cross-reference recovery found no parseable objects")]
332 NoObjects,
333 /// Objects were recovered but no `/Type /Catalog` could be found by
334 /// any route — a document root is required (§7.7.2), so recovery
335 /// refuses rather than return a rootless document.
336 #[error("cross-reference recovery found no document catalog (/Type /Catalog)")]
337 NoCatalog,
338 /// The recovered trailer carries `/Encrypt` (§7.6). pdfcer has no
339 /// security handler, so a broken-xref-**and**-encrypted file is
340 /// refused post-rebuild for the same reason the clean path refuses it.
341 #[error("recovered document is encrypted (\u{a7}7.6); recovery cannot proceed")]
342 Encrypted,
343 /// The synthesized entries exceeded [`MAX_XREF_ENTRIES`] (R25 guard) —
344 /// an `obj`-token-dense adversarial file stops here rather than
345 /// allocating without bound.
346 #[error("recovered cross-reference entries exceed MAX_XREF_ENTRIES")]
347 TooManyEntries,
348}
349
350/// Map a strict-load [`XrefErrorKind`] to the recovery it should trigger,
351/// or `None` when recovery **must not** fire.
352///
353/// This one function is the load-bearing trigger gate (decision 013
354/// §3.3.1): it simultaneously decides *whether* to recover and *why*.
355///
356/// - `EncryptionUnsupported` returns `None`: encryption is a deliberate
357/// **named capability gap**, not damage. Scanning would still surface
358/// ciphertext, and recovery re-checks `/Encrypt` after rebuilding the
359/// trailer anyway — so refusing up front here is both correct and
360/// cheaper.
361/// - `XrefErrorKind` is `#[non_exhaustive]`, but this match lives in the
362/// same crate, so it is **exhaustive without a wildcard**: adding a
363/// cross-reference error kind in a future Pass forces the author to
364/// classify it here (recover or refuse) rather than silently defaulting.
365///
366/// Object-level failures *after* a clean xref (`DocError::BadObject`,
367/// `ObjectIdMismatch`, `ObjectStream*`) are **not** reachable here — they
368/// arise in the document layer after `load_xref_chain` already returned
369/// `Ok`, so recovery never sees them. That scoping (xref-parse failure
370/// only) is a documented limitation, not an oversight.
371#[must_use]
372pub(crate) fn recovery_reason_for(kind: &XrefErrorKind) -> Option<RecoveryReason> {
373 match kind {
374 XrefErrorKind::StartxrefNotFound => Some(RecoveryReason::StartxrefNotFound),
375 XrefErrorKind::BadStartxrefOffset => Some(RecoveryReason::BadStartxrefOffset),
376 XrefErrorKind::NotAnXrefSection => Some(RecoveryReason::NotAnXrefSection),
377 XrefErrorKind::BadEntry => Some(RecoveryReason::BadEntry),
378 XrefErrorKind::BadSubsectionHeader => Some(RecoveryReason::BadSubsectionHeader),
379 XrefErrorKind::BadTrailer(_) => Some(RecoveryReason::BadTrailer),
380 XrefErrorKind::PrevChainCycle => Some(RecoveryReason::PrevChainCycle),
381 XrefErrorKind::TooManyEntries => Some(RecoveryReason::TooManyEntries),
382 XrefErrorKind::BadXrefStream(_) => Some(RecoveryReason::BadXrefStream),
383 XrefErrorKind::XrefStreamDecode(_) => Some(RecoveryReason::XrefStreamDecode),
384 XrefErrorKind::Parse(_) => Some(RecoveryReason::TrailerParse),
385 // §7.6: a NAMED capability gap, not damage — do not recover.
386 XrefErrorKind::EncryptionUnsupported => None,
387 }
388}
389
390/// One confirmed file-level object: its identity, the offset of its
391/// `N G obj` header, and its parsed value (kept so phase 2 and the
392/// catalog/trailer search need not re-parse it).
393struct Confirmed {
394 id: ObjId,
395 offset: usize,
396 value: Object,
397 /// Stream extents re-derived from `endstream` while parsing THIS
398 /// object (0 or 1 in practice — one object holds at most one stream).
399 /// Carried per-object so the report can sum over the objects actually
400 /// kept, rather than over superseded duplicates the document never sees.
401 lengths_recovered: usize,
402 /// Whether THIS object was accepted with no `endobj` keyword (0 or 1).
403 /// Same per-object carriage, same reason.
404 missing_endobj: usize,
405}
406
407/// Reconstruct a cross-reference table + trailer from a full-buffer scan.
408///
409/// See the module docs for the algorithm. This is the recovery entry point
410/// [`crate::document::Document::from_bytes`] calls on the strict-load error
411/// path.
412///
413/// # Errors
414///
415/// [`RecoverError`] — every case a named fail-clean refusal (no objects, no
416/// catalog, encrypted, or the entry cap). A recovered document is returned
417/// only when a `/Catalog` is reachable and the file is not encrypted.
418pub fn recover(buf: &[u8], reason: RecoveryReason) -> Result<RecoveredXref, RecoverError> {
419 // Phase 1: locate + confirm every file-level `N G obj` object.
420 let candidates = scan_object_headers(buf);
421 let (confirmed, last_wins_collisions, objects_dropped) = confirm_candidates(buf, &candidates)?;
422 if confirmed.is_empty() {
423 return Err(RecoverError::NoObjects);
424 }
425
426 // Build the type-1 (file-level) entries.
427 let mut entries: HashMap<u32, XrefEntry> = HashMap::with_capacity(confirmed.len());
428 for c in confirmed.values() {
429 entries.insert(
430 c.id.num,
431 XrefEntry::InUse {
432 offset: c.offset as u64,
433 generation: c.id.generation,
434 },
435 );
436 }
437
438 // Phase 2: walk recovered `/Type /ObjStm` containers for compressed
439 // members (type-2 entries).
440 let objstm_objects = recover_object_streams(buf, &confirmed, &mut entries)?;
441
442 let highest_object_number = entries.keys().copied().max().unwrap_or(0);
443
444 // Trailer recovery + the §7.6 encryption re-check.
445 let (mut trailer, trailer_source) = recover_trailer(buf, &confirmed)?;
446 if trailer.contains_key(b"Encrypt") {
447 return Err(RecoverError::Encrypted);
448 }
449 // Ensure `/Size` covers every recovered object. The document layer does
450 // not re-run the §7.5.5 `/Size` filter on a synthesized table, but a
451 // stale-low `/Size` would still mislead `next_object_number`/the
452 // writer; setting it correctly is right for a rebuilt file (its base
453 // was invalid, so §5.6 does not bind).
454 set_size_at_least(&mut trailer, highest_object_number);
455
456 let version = detect_version(buf);
457 let offset_start = find_bytes(buf, 0, b"%PDF-") != Some(0);
458 // Sum over the objects actually KEPT (superseded duplicates are not in
459 // the loaded document, so counting them would overstate the repair).
460 let stream_lengths_recovered = confirmed.values().map(|c| c.lengths_recovered).sum();
461 let missing_endobj_recovered = confirmed.values().map(|c| c.missing_endobj).sum();
462
463 Ok(RecoveredXref {
464 table: XrefTable::from_entries(entries),
465 trailer,
466 highest_object_number,
467 version,
468 report: RecoveryReport {
469 reason,
470 file_level_objects: confirmed.len(),
471 objstm_objects,
472 last_wins_collisions,
473 trailer_source,
474 offset_start,
475 stream_lengths_recovered,
476 missing_endobj_recovered,
477 objects_dropped,
478 },
479 })
480}
481
482/// A scanned `N G obj` candidate: its identity and the byte offset of the
483/// object number (the start of the full `N G obj … endobj` definition).
484struct Candidate {
485 id: ObjId,
486 offset: usize,
487}
488
489/// Phase 1 scan: one linear forward pass locating every `N G obj` header.
490///
491/// Reader-robust by construction: it searches for the literal `obj`
492/// keyword (byte-level), then walks **backward** over the whitespace and
493/// two integer runs that must precede it. It does not fully tokenize the
494/// buffer, so binary stream data cannot abort the scan the way a strict
495/// lex would. Candidates are validated (parsed) separately in
496/// [`confirm_candidates`]; this pass only proposes.
497fn scan_object_headers(buf: &[u8]) -> Vec<Candidate> {
498 let mut out: Vec<Candidate> = Vec::new();
499 let mut from = 0usize;
500 while let Some(obj_start) = find_bytes(buf, from, b"obj") {
501 let obj_end = obj_start + 3;
502 // Always advance so the scan is strictly forward (O(n) total).
503 from = obj_end;
504
505 // Token boundary AFTER `obj`: EOF or a non-regular byte, so `object`
506 // / `objx` do not match.
507 if buf.get(obj_end).is_some_and(|&b| is_regular(b)) {
508 continue;
509 }
510 if let Some(c) = parse_header_backward(buf, obj_start) {
511 out.push(c);
512 }
513 }
514 out
515}
516
517/// Given the offset of the `o` in an `obj` keyword, recover the preceding
518/// `N G` header by walking backward, or `None` if the bytes before it are
519/// not a well-formed `N SP+ G` (e.g. `endobj`, where `d` precedes `obj`).
520fn parse_header_backward(buf: &[u8], obj_start: usize) -> Option<Candidate> {
521 let mut p = obj_start;
522 // At least one whitespace byte between the generation and `obj`. This
523 // is also what rejects `endobj` (`...d obj`? no — `endobj` has `d`
524 // immediately before `obj`, no whitespace, so this fails cleanly).
525 if !skip_ws_back(buf, &mut p) {
526 return None;
527 }
528 let gen_end = p;
529 skip_digits_back(buf, &mut p);
530 let gen_start = p;
531 if gen_start == gen_end {
532 return None; // no generation digits
533 }
534 // At least one whitespace byte between the object number and generation.
535 if !skip_ws_back(buf, &mut p) {
536 return None;
537 }
538 let num_end = p;
539 skip_digits_back(buf, &mut p);
540 let num_start = p;
541 if num_start == num_end {
542 return None; // no object-number digits
543 }
544 // Boundary before the object number: start-of-buffer or a non-regular
545 // byte, so a number is never sliced out of the middle of a longer run
546 // (binary junk like `x12 0 obj`).
547 if num_start > 0 && buf.get(num_start - 1).is_some_and(|&b| is_regular(b)) {
548 return None;
549 }
550
551 let num = u32::try_from(parse_uint(buf.get(num_start..num_end)?)?).ok()?;
552 let generation = u16::try_from(parse_uint(buf.get(gen_start..gen_end)?)?).ok()?;
553 // Object 0 is permanently the free-list head (§7.5.4); it never names a
554 // real object.
555 if num == 0 {
556 return None;
557 }
558 Some(Candidate {
559 id: ObjId::new(num, generation),
560 offset: num_start,
561 })
562}
563
564/// Confirm each scanned candidate by actually parsing it, keeping the
565/// **last valid** definition per object number (file order).
566///
567/// Confirmation is what makes the scan safe to hand to the strict document
568/// loader: a candidate whose offset does not parse as a well-formed
569/// `N G obj … endobj`, or whose parsed identity disagrees with the scanned
570/// header, is a binary-data false positive and is dropped rather than
571/// poisoning the table. Indirect stream `/Length` values are resolved
572/// against a provisional table built from all candidate offsets (the same
573/// §7.3.10 EXAMPLE 3 pattern the normal loader uses).
574///
575/// Returns the confirmed objects keyed by number and the count of
576/// last-valid-wins collisions.
577/// What phase 1 hands on: the objects it kept, how many later definitions
578/// superseded earlier ones, and — since owed item 18 — the ones it could not
579/// keep, with the reason for each.
580///
581/// A named type rather than a bare tuple because clippy's `type_complexity`
582/// is right here: a three-element tuple of two collections and a count is a
583/// thing a reader has to decode at every call site, and adding the third
584/// element is what pushed it over.
585type ConfirmedCandidates = (HashMap<u32, Confirmed>, usize, Vec<DroppedObject>);
586
587fn confirm_candidates(
588 buf: &[u8],
589 candidates: &[Candidate],
590) -> Result<ConfirmedCandidates, RecoverError> {
591 // Provisional last-wins offset table for indirect `/Length` resolution.
592 // Candidates are in ascending file order, so a later insert supersedes.
593 // Built ONCE (not per candidate — that would be O(n^2)).
594 let mut provisional: HashMap<u32, XrefEntry> = HashMap::with_capacity(candidates.len());
595 for c in candidates {
596 provisional.insert(
597 c.id.num,
598 XrefEntry::InUse {
599 offset: c.offset as u64,
600 generation: c.id.generation,
601 },
602 );
603 }
604 let length_table = XrefTable::from_entries(provisional);
605
606 let mut confirmed: HashMap<u32, Confirmed> = HashMap::new();
607 let mut collisions = 0usize;
608 let mut dropped: Vec<DroppedObject> = Vec::new();
609 for c in candidates {
610 // RecoverFromEndstream, and ONLY here (plus the matching re-parse in
611 // `document::assemble`): this is the single highest-yield leniency
612 // in the whole recovery path. A corpus census over 4,012 real PDFs
613 // found 341 files unopenable with "page /Contents is neither a
614 // stream nor an array of streams"; in 337 of them the missing
615 // content stream's `N G obj` header was physically present and had
616 // been dropped **here**, overwhelmingly because the file's
617 // `/Length` values were computed for LF line endings and the file
618 // was later converted to CRLF, so every stream is one byte per line
619 // longer than it claims. Confirming such an object under the strict
620 // policy discards a perfectly readable content stream.
621 let (io, repairs) = match parse_object_at(
622 buf,
623 &length_table,
624 c.offset as u64,
625 StreamLengthPolicy::RecoverFromEndstream,
626 // A definition whose `endobj` is missing but whose body parsed
627 // cleanly is kept. Dropping it costs the whole object, and when
628 // that object is the `/Pages` node the catalog is left naming
629 // nothing — the defect the veraPDF gate found on qpdf's
630 // `bad6.pdf`. See `TerminatorPolicy`.
631 TerminatorPolicy::RecoverAtNextHeader,
632 // Recovery confirms candidate objects found by scanning; a
633 // duplicate key must not disqualify one, for the same reason the
634 // two policies above are lenient here — an object this step
635 // rejects is an object the document loses.
636 crate::parser::DuplicateKeyPolicy::KeepLast,
637 ) {
638 Ok(pair) => pair,
639 Err(_) => {
640 // Dropped, and SAID SO (owed item 18). Overwhelmingly a
641 // binary-data false positive; occasionally a real object
642 // whose loss the operator needs to know about, and from the
643 // outside those two are the same event until the reason is
644 // carried out with the number.
645 dropped.push(DroppedObject {
646 number: c.id.num,
647 reason: DropReason::Unparseable,
648 });
649 continue;
650 }
651 };
652 if io.id != c.id {
653 dropped.push(DroppedObject {
654 number: c.id.num,
655 reason: DropReason::IdMismatch,
656 });
657 continue; // scan/parse disagreement — drop
658 }
659 // Last-valid-wins: a later valid definition supersedes an earlier
660 // one (reader convention for appended incremental updates).
661 if confirmed
662 .insert(
663 c.id.num,
664 Confirmed {
665 id: c.id,
666 offset: c.offset,
667 value: io.value,
668 lengths_recovered: repairs.stream_lengths,
669 missing_endobj: repairs.missing_endobj,
670 },
671 )
672 .is_some()
673 {
674 collisions += 1;
675 }
676 if confirmed.len() > MAX_XREF_ENTRIES {
677 return Err(RecoverError::TooManyEntries);
678 }
679 }
680 Ok((confirmed, collisions, dropped))
681}
682
683/// Phase 2: for every confirmed `/Type /ObjStm` container, synthesize a
684/// type-2 entry for each compressed member the container's pair table
685/// names, and return the count added.
686///
687/// A file-level (scanned) definition wins over an object-stream member of
688/// the same number (documented limitation B-W4); among object streams the
689/// first by container number wins (deterministic; true newest-wins needs
690/// revision ordering the scan discards).
691fn recover_object_streams(
692 buf: &[u8],
693 confirmed: &HashMap<u32, Confirmed>,
694 entries: &mut HashMap<u32, XrefEntry>,
695) -> Result<usize, RecoverError> {
696 // Deterministic order: container object number ascending.
697 let mut containers: Vec<&Confirmed> = confirmed
698 .values()
699 .filter(|c| is_object_stream(&c.value))
700 .collect();
701 containers.sort_by_key(|c| c.id.num);
702
703 let mut added = 0usize;
704 for container in containers {
705 let Object::Stream(stream) = &container.value else {
706 continue;
707 };
708 let Some(raw) = stream.data_span.slice(buf) else {
709 continue;
710 };
711 // Reuse the ordinary object-stream machinery (its own §10.1
712 // decompression-bomb + `/N` guards apply). A container that fails
713 // to decode is skipped, not fatal — recovery is best-effort here.
714 let Ok(objstm) = ObjectStream::parse(&stream.dict, raw) else {
715 continue;
716 };
717 for (index, member_num) in objstm.member_numbers().enumerate() {
718 // A file-level definition of this number wins.
719 if confirmed.contains_key(&member_num) {
720 continue;
721 }
722 // First object stream to claim the number wins.
723 if let Entry::Vacant(slot) = entries.entry(member_num) {
724 slot.insert(XrefEntry::InStream {
725 stream_num: container.id.num,
726 index: u32::try_from(index).unwrap_or(u32::MAX),
727 });
728 added += 1;
729 if entries.len() > MAX_XREF_ENTRIES {
730 return Err(RecoverError::TooManyEntries);
731 }
732 }
733 }
734 }
735 Ok(added)
736}
737
738/// Recover the trailer dictionary and record where it came from.
739///
740/// Priority: the last `trailer` keyword → a recovered cross-reference
741/// stream's own dictionary → synthesis from a scanned `/Type /Catalog`.
742/// The result is normalized to the trailer-semantic keys only.
743///
744/// # Errors
745///
746/// [`RecoverError::NoCatalog`] if no `/Root`/`/Catalog` is reachable by any
747/// route.
748fn recover_trailer(
749 buf: &[u8],
750 confirmed: &HashMap<u32, Confirmed>,
751) -> Result<(Dict, TrailerSource), RecoverError> {
752 // 1. The last `trailer` keyword's dictionary (classic files).
753 if let Some(dict) = last_trailer_dict(buf)
754 && dict.get(b"Root").and_then(Object::as_reference).is_some()
755 {
756 return Ok((normalize_trailer(&dict), TrailerSource::TrailerKeyword));
757 }
758
759 // 2. A recovered cross-reference stream's own dictionary carries the
760 // trailer keys (§7.5.8.1). Prefer one that actually has `/Root`.
761 if let Some(dict) = xref_stream_trailer_dict(confirmed) {
762 return Ok((normalize_trailer(dict), TrailerSource::XrefStreamDict));
763 }
764
765 // 3. Synthesize from a scanned catalog (file-level or compressed).
766 if let Some(root) = find_catalog_ref(buf, confirmed) {
767 let mut trailer = Dict::new();
768 trailer.insert(Name::from(b"Root"), Object::Reference(root));
769 // Preserve `/ID` and (for the refusal) `/Encrypt`, plus `/Info`,
770 // from any recovered xref-stream dictionary — needed for §7.6 key
771 // derivation continuity (R39) and honest metadata.
772 if let Some(src) = any_xref_or_trailer_dict(buf, confirmed) {
773 for key in [&b"ID"[..], b"Info", b"Encrypt"] {
774 if let Some(v) = src.get(key) {
775 trailer.insert(Name::from(key), v.clone());
776 }
777 }
778 }
779 return Ok((trailer, TrailerSource::SynthesizedFromCatalog));
780 }
781
782 Err(RecoverError::NoCatalog)
783}
784
785/// Copy a source dictionary down to just the trailer-semantic keys
786/// (`/Root`, `/Size`, `/Info`, `/Encrypt`, `/ID`), dropping the physical
787/// cross-reference-stream keys (`/Type`, `/W`, `/Index`, `/Filter`,
788/// `/DecodeParms`, `/Length`, `/Prev`, `/XRefStm`).
789///
790/// A recovered file's base cross-reference was invalid, so §5.6's
791/// "never normalize" does not bind it — emitting a clean trailer is the
792/// correct, honest output (decision 013 §3.3.4).
793fn normalize_trailer(src: &Dict) -> Dict {
794 let mut out = Dict::new();
795 for key in [&b"Root"[..], b"Size", b"Info", b"Encrypt", b"ID"] {
796 if let Some(v) = src.get(key) {
797 out.insert(Name::from(key), v.clone());
798 }
799 }
800 out
801}
802
803/// Find the last `trailer` keyword at a token boundary and parse the
804/// dictionary that follows it.
805fn last_trailer_dict(buf: &[u8]) -> Option<Dict> {
806 const KW: &[u8] = b"trailer";
807 let mut found = None;
808 let mut from = 0usize;
809 while let Some(p) = find_bytes(buf, from, KW) {
810 from = p + KW.len();
811 let before_ok = p == 0
812 || buf
813 .get(p - 1)
814 .is_some_and(|&b| is_whitespace(b) || is_delimiter(b));
815 let after_ok = !buf.get(p + KW.len()).is_some_and(|&b| is_regular(b));
816 if before_ok && after_ok {
817 found = Some(p + KW.len());
818 }
819 }
820 match Parser::at(buf, found?).parse_object() {
821 Ok(Object::Dict(d)) => Some(d),
822 _ => None,
823 }
824}
825
826/// A recovered cross-reference **stream** object's own dictionary, if one
827/// carries `/Root` — the trailer for a pure xref-stream file whose stream
828/// data was unreadable but whose Table 17 dictionary parsed.
829fn xref_stream_trailer_dict(confirmed: &HashMap<u32, Confirmed>) -> Option<&Dict> {
830 // Deterministic: highest object number wins (the newest xref stream).
831 let mut candidates: Vec<&Confirmed> = confirmed
832 .values()
833 .filter(|c| {
834 dict_of(&c.value).is_some_and(|d| {
835 d.get(b"Type").and_then(Object::as_name).map(Name::as_bytes) == Some(b"XRef")
836 && d.get(b"Root").and_then(Object::as_reference).is_some()
837 })
838 })
839 .collect();
840 candidates.sort_by_key(|c| c.id.num);
841 candidates.last().and_then(|c| dict_of(&c.value))
842}
843
844/// Any recovered cross-reference-stream (or the parsed trailer) dictionary,
845/// as a donor for `/ID`/`/Info`/`/Encrypt` during synthesis.
846fn any_xref_or_trailer_dict<'a>(
847 buf: &'a [u8],
848 confirmed: &'a HashMap<u32, Confirmed>,
849) -> Option<Dict> {
850 if let Some(d) = confirmed.values().find_map(|c| {
851 dict_of(&c.value).filter(|d| {
852 d.get(b"Type").and_then(Object::as_name).map(Name::as_bytes) == Some(b"XRef")
853 })
854 }) {
855 return Some(d.clone());
856 }
857 last_trailer_dict(buf)
858}
859
860/// Find a document catalog by any route: a scanned file-level object, else
861/// a compressed member of a recovered object stream.
862fn find_catalog_ref(buf: &[u8], confirmed: &HashMap<u32, Confirmed>) -> Option<ObjId> {
863 // File-level: highest object number wins (deterministic).
864 let mut file_level: Vec<&Confirmed> = confirmed
865 .values()
866 .filter(|c| is_catalog(&c.value))
867 .collect();
868 file_level.sort_by_key(|c| c.id.num);
869 if let Some(c) = file_level.last() {
870 return Some(c.id);
871 }
872
873 // Compressed: scan object-stream members (§7.5.7 permits the catalog in
874 // an object stream except in linearized files).
875 let mut containers: Vec<&Confirmed> = confirmed
876 .values()
877 .filter(|c| is_object_stream(&c.value))
878 .collect();
879 containers.sort_by_key(|c| c.id.num);
880 for container in containers {
881 let Object::Stream(stream) = &container.value else {
882 continue;
883 };
884 let Some(raw) = stream.data_span.slice(buf) else {
885 continue;
886 };
887 let Ok(objstm) = ObjectStream::parse(&stream.dict, raw) else {
888 continue;
889 };
890 for index in 0..objstm.len() {
891 if let Ok((num, value)) = objstm.object_at(index)
892 && is_catalog(&value)
893 {
894 // Compressed objects are generation 0 (§7.5.7).
895 return Some(ObjId::new(num, 0));
896 }
897 }
898 }
899 None
900}
901
902/// Raise `/Size` to at least `highest + 1`, never lowering it (Table 15:
903/// `/Size` is one greater than the highest object number defined).
904fn set_size_at_least(trailer: &mut Dict, highest: u32) {
905 let needed = i64::from(highest) + 1;
906 let current = trailer.get(b"Size").and_then(Object::as_int).unwrap_or(0);
907 trailer.insert(Name::from(b"Size"), Object::Integer(current.max(needed)));
908}
909
910/// Detect the PDF version by scanning the whole buffer for `%PDF-M.N`
911/// (whole-buffer so it survives the offset-start case); a conservative
912/// `1.7` default when the file carries no marker at all.
913fn detect_version(buf: &[u8]) -> PdfVersion {
914 const DEFAULT: PdfVersion = PdfVersion { major: 1, minor: 7 };
915 let Some(pos) = find_bytes(buf, 0, b"%PDF-") else {
916 return DEFAULT;
917 };
918 let after = pos + 5;
919 let (Some(major), maj_len) = take_u8(buf.get(after..).unwrap_or(&[])) else {
920 return DEFAULT;
921 };
922 if buf.get(after + maj_len) != Some(&b'.') {
923 return DEFAULT;
924 }
925 let (Some(minor), _) = take_u8(buf.get(after + maj_len + 1..).unwrap_or(&[])) else {
926 return DEFAULT;
927 };
928 PdfVersion { major, minor }
929}
930
931// --- small byte helpers (checked-slicing per the crate panic-free policy) --
932
933/// Index of the first occurrence of `needle` in `buf` at or after `from`,
934/// or `None`. Cumulatively O(n) across a forward scan because callers
935/// advance `from` past each hit.
936fn find_bytes(buf: &[u8], from: usize, needle: &[u8]) -> Option<usize> {
937 let hay = buf.get(from..)?;
938 if needle.is_empty() || needle.len() > hay.len() {
939 return None;
940 }
941 hay.windows(needle.len())
942 .position(|w| w == needle)
943 .map(|p| from + p)
944}
945
946/// Walk `*p` backward over whitespace bytes; return whether at least one
947/// was consumed.
948fn skip_ws_back(buf: &[u8], p: &mut usize) -> bool {
949 let start = *p;
950 while *p > 0 && buf.get(*p - 1).is_some_and(|&b| is_whitespace(b)) {
951 *p -= 1;
952 }
953 *p < start
954}
955
956/// Walk `*p` backward over ASCII digits.
957fn skip_digits_back(buf: &[u8], p: &mut usize) {
958 while *p > 0 && buf.get(*p - 1).is_some_and(|&b| b.is_ascii_digit()) {
959 *p -= 1;
960 }
961}
962
963/// Parse a run of ASCII digits into `u64`, `None` on a non-digit or
964/// overflow.
965fn parse_uint(bytes: &[u8]) -> Option<u64> {
966 if bytes.is_empty() {
967 return None;
968 }
969 let mut v: u64 = 0;
970 for &b in bytes {
971 let d = b.checked_sub(b'0')?;
972 if d > 9 {
973 return None;
974 }
975 v = v.checked_mul(10)?.checked_add(u64::from(d))?;
976 }
977 Some(v)
978}
979
980/// Consume a leading run of ASCII digits as a `u8`, returning the value and
981/// bytes consumed (mirrors the header probe's `take_u8`; a version
982/// component never exceeds a single digit legitimately).
983fn take_u8(bytes: &[u8]) -> (Option<u8>, usize) {
984 let mut value: u32 = 0;
985 let mut consumed = 0usize;
986 for &b in bytes {
987 if b.is_ascii_digit() {
988 value = value.saturating_mul(10).saturating_add(u32::from(b - b'0'));
989 consumed += 1;
990 } else {
991 break;
992 }
993 }
994 if consumed == 0 {
995 (None, 0)
996 } else {
997 (u8::try_from(value).ok(), consumed)
998 }
999}
1000
1001/// A dictionary view of an object (plain dict or a stream's dict).
1002fn dict_of(value: &Object) -> Option<&Dict> {
1003 value.as_dict()
1004}
1005
1006/// Whether an object is a `/Type /Catalog` dictionary (§7.7.2).
1007fn is_catalog(value: &Object) -> bool {
1008 dict_of(value)
1009 .and_then(|d| d.get(b"Type"))
1010 .and_then(Object::as_name)
1011 .map(Name::as_bytes)
1012 == Some(b"Catalog")
1013}
1014
1015/// Whether an object is a `/Type /ObjStm` stream (§7.5.7). A container
1016/// without an explicit `/Type` is tolerated by [`ObjectStream::parse`] but
1017/// the scan needs a positive signal to enumerate it, so recovery requires
1018/// the explicit tag here (a scanned object with `/N`+`/First` but no
1019/// `/Type` is not treated as a container — a conservative choice that
1020/// avoids mis-enumerating an ordinary stream).
1021fn is_object_stream(value: &Object) -> bool {
1022 matches!(value, Object::Stream(_))
1023 && dict_of(value)
1024 .and_then(|d| d.get(b"Type"))
1025 .and_then(Object::as_name)
1026 .map(Name::as_bytes)
1027 == Some(b"ObjStm")
1028}
1029
1030#[cfg(test)]
1031#[allow(
1032 clippy::unwrap_used,
1033 clippy::expect_used,
1034 clippy::panic,
1035 clippy::indexing_slicing
1036)]
1037mod tests {
1038 use super::*;
1039 use crate::graph::ObjectGraph as _;
1040
1041 /// The trigger gate: encryption is a named capability gap (no recovery);
1042 /// every unparseable-xref kind recovers.
1043 #[test]
1044 fn recovery_reason_for_gates_encryption_out() {
1045 assert_eq!(
1046 recovery_reason_for(&XrefErrorKind::EncryptionUnsupported),
1047 None
1048 );
1049 assert_eq!(
1050 recovery_reason_for(&XrefErrorKind::NotAnXrefSection),
1051 Some(RecoveryReason::NotAnXrefSection)
1052 );
1053 assert_eq!(
1054 recovery_reason_for(&XrefErrorKind::StartxrefNotFound),
1055 Some(RecoveryReason::StartxrefNotFound)
1056 );
1057 assert_eq!(
1058 recovery_reason_for(&XrefErrorKind::BadXrefStream("x")),
1059 Some(RecoveryReason::BadXrefStream)
1060 );
1061 }
1062
1063 /// The backward header walk locates `N G obj` and rejects `endobj`
1064 /// (whose `obj` has no preceding whitespace-then-digits).
1065 #[test]
1066 fn scan_finds_headers_and_rejects_endobj() {
1067 let buf = b"%PDF-1.7\n12 0 obj\n<< >>\nendobj\n34 5 obj null endobj\n";
1068 let headers = scan_object_headers(buf);
1069 let ids: Vec<(u32, u16)> = headers
1070 .iter()
1071 .map(|c| (c.id.num, c.id.generation))
1072 .collect();
1073 // Only the two real headers; the `obj` inside `endobj` is rejected.
1074 assert_eq!(ids, vec![(12, 0), (34, 5)]);
1075 }
1076
1077 /// A false-positive `N G obj` sitting inside a byte run (no boundary
1078 /// before the number) is not proposed.
1079 #[test]
1080 fn scan_rejects_number_without_leading_boundary() {
1081 // `x12 0 obj` — the `12` is glued to a regular byte, so it is not a
1082 // valid object-number token start.
1083 let buf = b"x12 0 obj\n";
1084 assert!(scan_object_headers(buf).is_empty());
1085 }
1086
1087 /// Object number 0 (the free-list head) is never proposed as an object.
1088 #[test]
1089 fn scan_rejects_object_zero() {
1090 let buf = b" 0 0 obj\n";
1091 assert!(scan_object_headers(buf).is_empty());
1092 }
1093
1094 /// Version detection scans the whole buffer, so it survives leading junk
1095 /// (the offset-start case); a headerless buffer defaults conservatively.
1096 #[test]
1097 fn detect_version_scans_whole_buffer() {
1098 assert_eq!(
1099 detect_version(b"junk...%PDF-2.0\nrest"),
1100 PdfVersion { major: 2, minor: 0 }
1101 );
1102 assert_eq!(
1103 detect_version(b"no header here"),
1104 PdfVersion { major: 1, minor: 7 }
1105 );
1106 }
1107
1108 /// A SCANNED OBJECT THAT CANNOT BE KEPT IS NAMED (owed item 18).
1109 ///
1110 /// `decision 145` obliges pdfcer to disclose what it dropped. It closed
1111 /// that at the LOADER; recovery had the same gap, measured on a real
1112 /// file: `Annotations_output.pdf` recovers 10 of 11 objects and dropped
1113 /// object 5 — the page's content stream — with **nothing recorded
1114 /// anywhere**. Losing it was right; losing it in silence was not.
1115 ///
1116 /// Here object 3's body is `<< /Type` and stops — a header the scan
1117 /// matches and the parser cannot finish, which is the `Unparseable` arm.
1118 /// The document still loads on objects 1 and 2.
1119 ///
1120 /// The assertion is on the NUMBER and the REASON, not on a count. The
1121 /// complaint this item came from was not that a tally was wrong — it was
1122 /// that a human holding a file with a missing page could not find out
1123 /// WHICH object went or WHY, and `dropped: 1` answers neither.
1124 #[test]
1125 fn an_object_the_scan_found_and_could_not_parse_is_named_not_dropped_silently() {
1126 let buf = b"%PDF-1.7\n\
11271 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n\
11282 0 obj\n<< /Type /Pages /Count 0 /Kids [] >>\nendobj\n\
11293 0 obj\n<< /Type \n";
1130 let out = recover(buf, RecoveryReason::StartxrefNotFound)
1131 .expect("objects 1 and 2 are enough to recover a document");
1132
1133 assert_eq!(
1134 out.report.objects_dropped.len(),
1135 1,
1136 "object 3 was found by the scan and could not be parsed; it must \
1137 appear in the disclosure, not vanish"
1138 );
1139 let d = &out.report.objects_dropped[0];
1140 assert_eq!(d.number, 3, "the disclosure must name WHICH object");
1141 assert_eq!(
1142 d.reason,
1143 DropReason::Unparseable,
1144 "and WHY — a false positive and a corrupt object are the same \
1145 event from outside until the reason is carried with the number"
1146 );
1147
1148 // The kept objects are unaffected: this discloses a loss, it does not
1149 // cause one.
1150 assert_eq!(out.report.file_level_objects, 2);
1151 }
1152
1153 /// A clean recovery discloses NOTHING dropped — so the field above is a
1154 /// signal rather than noise every recovery emits.
1155 #[test]
1156 fn a_recovery_that_keeps_everything_reports_no_drops() {
1157 let buf = b"%PDF-1.7\n\
11581 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n\
11592 0 obj\n<< /Type /Pages /Count 0 /Kids [] >>\nendobj\n";
1160 let out = recover(buf, RecoveryReason::StartxrefNotFound).expect("recovers");
1161 assert!(
1162 out.report.objects_dropped.is_empty(),
1163 "nothing was dropped, so nothing may be reported as dropped"
1164 );
1165 }
1166
1167 /// A buffer with no confirmable objects fails clean with `NoObjects`
1168 /// (the header-path "not a PDF" outcome).
1169 #[test]
1170 fn recover_on_empty_input_is_no_objects() {
1171 let err = recover(b"not a pdf at all", RecoveryReason::MissingHeader).unwrap_err();
1172 assert_eq!(err, RecoverError::NoObjects);
1173 }
1174
1175 /// Objects present but no `/Catalog` fails clean with `NoCatalog`, never
1176 /// a garbage document.
1177 #[test]
1178 fn recover_without_catalog_is_no_catalog() {
1179 let buf = b"%PDF-1.7\n1 0 obj\n<< /Type /Pages /Count 0 /Kids [] >>\nendobj\n";
1180 let err = recover(buf, RecoveryReason::StartxrefNotFound).unwrap_err();
1181 assert_eq!(err, RecoverError::NoCatalog);
1182 }
1183
1184 /// The corpus's dominant damage shape, in miniature: a classic file
1185 /// whose `/Length` values were computed for LF line endings and which
1186 /// was then converted to CRLF. Every stream is now one byte per line
1187 /// longer than it claims, and every stored offset is stale — which is
1188 /// why `startxref` no longer lands on `xref` and recovery fires.
1189 ///
1190 /// Before the `StreamLengthPolicy::RecoverFromEndstream` confirmation,
1191 /// object 4 failed to parse and was silently dropped, so the scan
1192 /// reported one object fewer than the file contains and the page's
1193 /// `/Contents` resolved to null. This asserts the object is now KEPT,
1194 /// with the right bytes, and that the repair is disclosed.
1195 #[test]
1196 fn recover_keeps_streams_whose_length_predates_crlf_conversion() {
1197 // Written LF-first, then converted — exactly how the real files
1198 // were damaged — so the /Length values are honestly stale rather
1199 // than hand-picked to make the test pass.
1200 let lf = "%PDF-1.4\n\
1201 1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n\
1202 2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 \
1203 /MediaBox [0 0 10 10] /Resources << >> >>\nendobj\n\
1204 3 0 obj\n<< /Type /Page /Parent 2 0 R /Contents 4 0 R >>\nendobj\n\
1205 4 0 obj\n<< /Length 14 >>\nstream\nBT\n(hi) Tj\nET\nendstream\nendobj\n\
1206 trailer\n<< /Root 1 0 R /Size 5 >>\nstartxref\n9\n%%EOF\n";
1207 // `/Length 14` is what the LF form measures: "BT\n(hi) Tj\nET\n".
1208 // (13 would also be legal — §7.3.8.1's trailing EOL is optional in
1209 // the count — and either value parses strictly BEFORE conversion,
1210 // which is the point: the file was VALID until the line endings
1211 // changed underneath it.)
1212 assert_eq!("BT\n(hi) Tj\nET\n".len(), 14);
1213 let buf = lf.replace('\n', "\r\n").into_bytes();
1214
1215 let rec = recover(&buf, RecoveryReason::NotAnXrefSection).expect("recovery");
1216 assert_eq!(
1217 rec.report.file_level_objects, 4,
1218 "all four objects survive confirmation — the stream is no longer dropped"
1219 );
1220 assert_eq!(
1221 rec.report.stream_lengths_recovered, 1,
1222 "the one repaired extent is counted for disclosure"
1223 );
1224
1225 // And the recovered stream holds the real content, not a truncation.
1226 let doc = crate::document::Document::from_bytes(buf).expect("load");
1227 let pages = crate::page_tree::pages(&doc).expect("page tree");
1228 assert_eq!(pages.len(), 1);
1229 assert_eq!(pages[0].contents.len(), 1, "the content stream is present");
1230 assert_eq!(
1231 pages[0].contents_unresolved, 0,
1232 "nothing had to be degraded — the object was actually recovered"
1233 );
1234 let Some(Object::Stream(s)) = doc.value(pages[0].contents[0]) else {
1235 panic!("content stream missing");
1236 };
1237 assert_eq!(
1238 s.data_span.slice(doc.bytes()).unwrap(),
1239 b"BT\r\n(hi) Tj\r\nET",
1240 "the extent is re-derived to the real CRLF payload, EOL backed off"
1241 );
1242 }
1243
1244 /// A recovered `/Encrypt` trailer refuses post-rebuild (the §7.6
1245 /// capability gap re-checked after recovery).
1246 #[test]
1247 fn recover_encrypted_refuses() {
1248 let mut buf: Vec<u8> = b"%PDF-1.7\n".to_vec();
1249 buf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
1250 buf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [] /Count 0 >>\nendobj\n");
1251 // A `trailer` keyword carrying /Root AND /Encrypt.
1252 buf.extend_from_slice(b"trailer\n<< /Root 1 0 R /Encrypt 9 0 R /Size 3 >>\n");
1253 let err = recover(&buf, RecoveryReason::StartxrefNotFound).unwrap_err();
1254 assert_eq!(err, RecoverError::Encrypted);
1255 }
1256}