Repository navigation
fix(reader): honour object generation numbers on resolve - #192
Conversation
|
Blocked — adversarial review found a regression that breaks valid documents. Not ready to merge despite green CI. The parser discards the generation, so the new check rejects conforming files
var objNum = ParseObjectNumber(firstIntToken.Raw, "indirect reference object number");
return new PdfIndirectReference(objNum); // peekTok — the generation — thrown awayEvery reference parsed from a real document therefore carries Reproduced independently, twice:
Why the suite is green. Every generation-bearing reference in Three more, all confirmed
Verified sound — not re-litigating these
Fixes are in progress. A second review pass is still running. |
PdfIndirectReference carried only an object number and hardcoded " 0 R" on write, and the xref table was keyed on object number alone, so 10 2 R resolved to whatever object 10 held at generation 0. Store the generation on XrefEntry and validate it on resolve; a mismatch (including one against an object a later revision freed) now resolves to nothing instead of the wrong object. Classic-table 'f' entries were also silently skipped rather than recorded, which let an older revision's stale entry resurface through a freed object number. Prerequisite for decryption (#97): R2-R4 per-object key derivation consumes the generation.
freed was shared between a revision's classic table and that same revision's /XRefStm, but a hybrid-reference file marks an object 'f' in the classic table precisely because its live definition is in the accompanying stream (ISO 32000-2 §7.5.8.4) — the object is free only to a reader that cannot see the stream. The shared set made the classic 'f' entry block the stream's own live entry for the same object in the same revision, making it unresolvable. Scope the free set per revision: classic table and /XRefStm each record into a local set, suppressing only against frees carried in from a newer revision, and the local set is folded into the cross-revision set only after both halves of the revision have had a chance to add the object back. Classic-wins precedence between the two halves is unchanged. Also restores the cache-first fast path in Resolve/ResolveStream for the generation-agnostic case, so a lookup with no generation to check still costs one dictionary lookup on a hit.
ParseIntegerOrReference parsed the middle "G" token of "N G R" only to peek past it and throw it away, so every reference read from a real document looked like generation 0 no matter what the file said. The enforcement added in the previous two commits then rejected any object legitimately at a nonzero generation, including a catalog referenced as "1 1 R" — PdfReader.Open threw "/Root does not resolve to a dictionary" outright, and a canonical incremental update that reuses a freed object number at a higher generation resolved to nothing. Carry the generation through, validated by the same helper the "N G obj" header already uses. Two more gaps surfaced alongside it: - A cache entry populated by a generation-agnostic Resolve(int) call carried no record of what generation it was actually parsed at, so a later generation-bearing call for the same object could pass the xref check, hit the warm cache, and return a value nothing had ever verified against the requested generation. Cache the parsed generation alongside the value and re-check it on a hit. - PreflightContext.ResolveStream unwrapped a reference to its object number before calling Reader.ResolveStream, bypassing the new generation check entirely — the same reference could resolve to a live dictionary through Resolve and to null through ResolveStream. Route it through the generation-aware overload instead. Also: the classic-table and xref-stream generation fields are now parsed leniently (space-padded, or a value overflowing int in an 8-byte xref-stream row, falls back to generation 0) rather than aborting a document that used to open fine — this field was never read before this change. GetHashCode uses a deterministic combination instead of HashCode.Combine, which salts with a per-process seed; this type shipped Stable in 2.0.0. Left two round-trip normalizers (PdfObjectRemapper and LinearizedCrossReferenceBuilder) hardcoding generation 0, with a comment at each explaining why that is still safe today — fixing them is v3.0 read-modify-write territory (#101).
446d8ca to
7f517b0
Compare
The read path was fixed; the write path was not, and it broke the AppendRevision case DssBuilder and ArchiveTimestampBuilder both use for LTV and archive-timestamp signing. Given a catalog at generation 1, AppendRevision wrote its re-emitted object header as "N 0 obj" and its xref entry as "... 00000 n" (both hardcoded), while the trailer's /Root now carried the real generation 1 from the parsed reference. Reopening the result threw "/Root does not resolve to a dictionary". Rewriting any other existing object at the wrong generation failed the same way but silently — Resolve returned null, no exception, and a page or font just vanished. PdfIndirectObject gains a Generation property and a three-argument constructor; IncrementalCrossReferenceBuilder writes the real generation into both the object header and the xref entry; AppendRevision's parameter and IncrementalCrossReferenceBuilder's writtenObjects both become (ObjectNumber, Generation, Value) triples, and AppendRevision now checks that a rewritten /Root's generation agrees with the trailer before writing anything, rather than producing an inconsistent file. DssBuilder and ArchiveTimestampBuilder thread the real generation through for every object they rewrite (catalog in both; first page in ArchiveTimestampBuilder) while new objects stay at generation 0. The PdfObjectRemapper and LinearizedCrossReferenceBuilder comments justifying their own hardcoded generation 0 no longer claim a read-then-rewrite path doesn't exist — AppendRevision is one and ships today; those two specifically are just never reached by it. Also in this pass: - Nine call sites still unwrapped a reference to its object number before calling Resolve/ResolveStream, bypassing the generation check the previous commit added elsewhere. SeparationConsistencyRule tried the number-only path first and returned on success, so enforcement was fully bypassed there rather than merely inconsistent. All nine now go through the reference-aware overload. - An xref generation field that is genuinely unparseable (not merely sloppy) is recorded as unknown rather than guessed at 0: with xref and header disagreeing, guessing 0 made a legitimately reachable object unresolvable at every generation. XrefEntry.UnknownGeneration marks it, and the object's own header becomes the sole authority for that one entry instead. - A reference's own generation token that overflows int no longer aborts the parse. It saturates to int.MaxValue, which cannot match any real xref entry — the same outcome an ordinary mismatch already produces, not a document-wide failure. - Given the above, the xref is now the single authority for an object's generation whenever it parses cleanly, instead of also requiring the object's own header to agree. Requiring both made a disagreement (however it arose) unresolvable at any generation rather than resolvable at the one the xref actually recorded. - PdfIndirectReference's two-argument constructor now rejects a negative generation. - Resolve/ResolveStream fold the entry's authoritative generation into the cache tuple, so a warm hit costs one dictionary lookup instead of an xref lookup followed by a cache lookup. CHANGELOG documents the three behaviour changes this leaves on PdfIndirectReference, a Stable type since 2.0.0: WriteTo emits the real generation, Equals narrowed, GetHashCode differs.
) The freed-entry tracking added earlier removes a recovery behaviour some producers may have relied on: a tool that writes a full "0 N" subsection on every incremental update, marking every untouched object 'f' instead of only the ones it actually freed, used to have those spurious frees silently overridden by xref.TryAdd resurrecting the older-revision entry. Under the current tracking they are treated as genuine deletions instead. No real-world fixture exhibiting this has turned up; note it near the freed set so the interaction with PR #193's xref-rebuild fallback is visible if one does.
PrepareForSigning_withPins_isByteIdentical pinned Timestamp and DocumentId but passed a default SignaturePlaceholderOptions with no SigningTime, so PdfDocument.PrepareForSigning fell back to the live clock (options.SigningTime ?? DateTimeOffset.UtcNow). The two Build() calls the test compares straddling a wall-clock second produced one differing byte inside /M, an intermittent failure unrelated to whatever the test happened to be exercising. Not caused by #121 or any change in this branch — reproduces on an unmodified checkout. A determinism test that reads the clock is not testing determinism.
…121) ParseGenerationLenient's out-of-range fallback saturated at int.MaxValue on the theory that no real xref entry could ever hold that value. XrefParser only routed a field to XrefEntry.UnknownGeneration when it exceeded int range, so a /W field wide enough to hold int.MaxValue recorded it as an ordinary generation — and a reference whose own token overflowed int (or even long) collapsed onto that exact saturated value and resolved. The object-number half of the same parser is careful to avoid precisely this shape of aliasing; the generation half reintroduced it. ISO 32000-2 §7.5.4 bounds a generation number at 65535, not int.MaxValue. Both XrefParser paths (classic table, xref-stream type-1) now route anything above 65535 to UnknownGeneration, and ParseGenerationLenient saturates at the same ceiling instead of only on true overflow — an xref entry can never legitimately hold more than 65535 either way, so nothing above it can be a real match, and nothing above it is safe to let a header-authority fallback pass through uncapped once the xref stops having an opinion on that entry. This also closes the write side: DssBuilder and ArchiveTimestampBuilder only ever thread a PdfIndirectReference.Generation parsed off the source document into AppendRevision, and that value is now guaranteed to fit the 5-digit xref field IncrementalCrossReferenceBuilder writes — a document whose /Root named a larger generation fails to open at all, so neither signing entry point can ever reach the field-width guard with a document-supplied value. The guard itself is untouched: it still protects a caller that builds an out-of-range generation by hand. CHANGELOG: moved the four Stable/Shipped member changes (PdfIndirectReference .WriteTo/Equals/GetHashCode, PdfIndirectObject.Reference) from Fixed to Changed — Equals narrowing is a genuine break for anyone keying a collection on the type, not merely a fix.
The single Fixed bullet ran 34 lines and packed five distinct changes into one paragraph — nearly four times the longest bullet anywhere else in the file, where 2.0.0 established a 2-9 line convention with 5 the norm. Nobody scanning the changelog for what moved would find it. Split into four bullets, one per change, each with its own bold lead-in: the core read/write generation fix, the AppendRevision/signing round-trip fix (its own bullet, since a rewritten non-catalog object silently resolving to nothing is the failure most likely to bite someone), the freed-object tracking, and generation-field leniency. Every fact that was in the original bullet is still here, just distributed. Ran the avoid-ai-writing skill over the result per CLAUDE.md and tightened one over-compressed closing sentence that chained a semicolon onto an em-dash parenthetical.
Rebasing onto #192 left the reconstruction scanner calling the old one-argument XrefEntry.Uncompressed. The scanner already parses the generation out of each "N G obj" header and was discarding it, so the obvious repair — passing 0 — would have recorded every recovered object at generation 0 and made a legitimately nonzero-generation object unresolvable at every generation. Reconstruction runs precisely when the cross-reference table is unusable, so the object header is the only authority left for a generation. Carry it through, and record anything outside the ISO 32000-2 §7.5.4 range of 0-65535 as unknown, matching how the xref-side generation fields already handle a value they cannot trust.
The reader dropped PDF object generation numbers: PdfIndirectReference carried only an object number and hardcoded " 0 R" on write, the parser discarded the middle field of a parsed N G R, and the cross-reference table was keyed on object number alone, so 10 2 R resolved to whatever object 10 held at generation 0. The generation is now stored on XrefEntry and validated on resolve, with the cross-reference table as the single authority for a generation it actually records. Where it has no opinion — a garbled field, or one above the ISO 32000-2 §7.5.4 ceiling of 65535 — the entry is marked unknown and the object's own header takes over, rather than guessing 0 and making a reachable object silently unresolvable. PdfIndirectObject gains a matching Generation, because an incremental update preserves an object's generation (§7.5.4/§7.5.6). Without it AppendRevision wrote a trailer whose /Root disagreed with the object header beside it, and the long-term-validation and archive-timestamp signing paths produced files that could not be reopened. Prerequisite for decryption (#97): R2-R4 per-object key derivation consumes the generation. Closes #121.
The reader dropped PDF object generation numbers: PdfIndirectReference carried only an object number and hardcoded " 0 R" on write, the parser discarded the middle field of a parsed N G R, and the cross-reference table was keyed on object number alone, so 10 2 R resolved to whatever object 10 held at generation 0. The generation is now stored on XrefEntry and validated on resolve, with the cross-reference table as the single authority for a generation it actually records. Where it has no opinion — a garbled field, or one above the ISO 32000-2 §7.5.4 ceiling of 65535 — the entry is marked unknown and the object's own header takes over, rather than guessing 0 and making a reachable object silently unresolvable. PdfIndirectObject gains a matching Generation, because an incremental update preserves an object's generation (§7.5.4/§7.5.6). Without it AppendRevision wrote a trailer whose /Root disagreed with the object header beside it, and the long-term-validation and archive-timestamp signing paths produced files that could not be reopened. Prerequisite for decryption (#97): R2-R4 per-object key derivation consumes the generation. Closes #121.
Closes #121.
PdfIndirectReferencecarried only an object number and hardcoded" 0 R"on write; the parser droppedthe middle field of a parsed
N G R; and the cross-reference table was keyed on object number alone. So10 2 Rresolved to whatever object 10 held at generation 0.This also unblocks #97: per-object key derivation for security handler revisions R2-R4 is
MD5(fileKey ‖ objNum[0..3] ‖ gen[0..2]), so decrypting V1/V2/V4 files is impossible without the generation.Approach
The generation is stored on
XrefEntryand validated on resolve, rather than re-keying the dictionary on(objNum, gen)— a compound key would have brokenObjectNumbers,NextFreeObjectNumber, andUncompressedObjectOffset(int), all consumed byPreflightContext.Resolve(int)keeps itsgeneration-agnostic behaviour for callers with no reference in hand;
Resolve(PdfIndirectReference)enforces.The cache stores
(Value, Generation)so a generation-bearing lookup cannot be answered from an entry ageneration-agnostic call warmed first.
The cross-reference table is the single authority for a generation it actually records. Where it does not — a
garbled field, or one above the ISO 32000-2 §7.5.4 ceiling of 65535 — the entry is marked unknown and the
object's own header takes over, rather than guessing 0 and making a reachable object silently unresolvable.
Public API
Four additive members, all in
PublicAPI.Unshipped.txt;PublicAPI.Shipped.txtis byte-untouched in alleight packages.
PdfIndirectReference.Generation+ a two-argument constructor.PdfIndirectObject.Generation+ a three-argument constructor.The second pair is what fixes the write path. An incremental update preserves an object's generation — it
advances only when a freed number is reused for a different object (§7.5.4/§7.5.6) — so re-emitting an object
must write the generation the reference to it carries. The considered alternative, normalising the trailer to
generation 0, was rejected: it is spec-wrong, it fixes only
/Rootwhile every other reference in the basefile still names the old generation, and doing it properly would mean rewriting the whole file, invalidating
the very signatures the DSS and archive-timestamp paths exist to preserve.
Four members change behaviour on surfaces Stable since 2.0.0 —
WriteTo,Equals(narrowed),GetHashCode(now deterministic;HashCode.Combineis salted per process), andPdfIndirectObject.Reference.All four are documented under
### Changed.What review caught
Four defects, each of which survived a fully green 4,500-test suite:
own
/XRefStm, but per §7.5.8.4 the classic table marks an object free because the stream defines it.The existing hybrid test could not see it — its table omits the object rather than marking it free.
became unresolvable; a catalog at nonzero generation made
Openthrow. The tests hand-constructedreferences instead of parsing them.
AppendRevisionemitted files it could not reopen — the PAdES LTV path.WriteTobegan emitting thereal generation while the object header and incremental xref still wrote 0.
int.MaxValuesaturation aliased. A/W [1 4 4]field records0x7FFFFFFFlegitimately, so everyout-of-range reference token collapsed onto it and resolved — the exact risk the neighbouring comment
claimed to have eliminated.
Each is now pinned by a regression test that fails against the commit before its fix.
Verification
REQUIRE_VERAPDF=1, qpdf on PATH).Conformance runs 1237/1237 in ~4m30s; the same suite finishes in 2s with 277 skipped when the oracles are
off, which is how we know they ran.
main— 1237/0/0 both sides. No conformance verdict moved.inside the noise floor —
main's own ratio wanders 0.976-1.011 on identical code. End-to-endPdfPreflight.Validateis 0.785 ms vsmain's 0.787 ms. Zero allocation across 300M ops.OracleCorpus.csfor the tuple widening makes thembyte-identical to
main, across ~340 migrated call sites.dotnet format --verify-no-changesclean, clean-room passed, no golden snapshot moved.Known and disclosed
A non-
/Rootobject rewritten at the wrong generation is still silent — the object resolves to nothing,with no exception.
AppendRevisionguards/Rootspecifically because that one fails loudly at reopen. TheAPI is
internal, both in-repo callers now pass real generations, and the XML doc states this explicitly.9eddcd5is unrelated to #121: it pinsSigningTimein a determinism test that was reading the live clock.Kept as a separate commit; see #194.