Skip to content
44 changes: 43 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,49 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).

## [Unreleased]

Nothing yet.
### Changed

- **`PdfIndirectReference` and `PdfIndirectObject` honour generation, which changes four members
on surfaces Stable/Shipped since 2.0.0.** `PdfIndirectReference.WriteTo` now emits the real
generation instead of a hardcoded `0`; `Equals` narrowed, so `new PdfIndirectReference(5)` no
longer equals a parsed `5 1 R` — a genuine break for anything keying a collection on this type;
`GetHashCode` returns different (now deterministic, unlike `HashCode.Combine`'s per-process
salt) values than in 2.0.0; and `PdfIndirectObject.Reference` returns `new(ObjectNumber,
Generation)` rather than `new(ObjectNumber)`, unobservable unless the object was built through
the new three-argument constructor. See Fixed, below, for why. (#121)

### Fixed

- **A reference's generation number is honoured instead of discarded.** `PdfIndirectReference`
carried only an object number, and the parser dropped a parsed `N G R`'s middle field too, so
every reference read from a document looked like generation 0. With an xref table keyed on
object number alone, `10 2 R` resolved to whatever object 10 held at generation 0 instead of
nothing, and a document with a legitimately nonzero generation anywhere — including its own
`/Root` — either resolved the wrong object or failed to open. (#121)

- **A rewritten object at a nonzero generation now round-trips through `AppendRevision`.** The
incremental-update writer hardcoded every re-emitted object, including the catalog, to
generation 0. Long-term-validation and archive-timestamp signing both rewrite the catalog, so
a base document whose catalog sat at a nonzero generation got a trailer `/Root` that disagreed
with the object header and xref entry next to it and failed to reopen; rewriting any other
object at the wrong generation failed the same way but silently, resolving to nothing with no
exception. `PdfIndirectObject` gains a matching `Generation` and a three-argument constructor
to carry the real value through. (#121)

- **A freed object number no longer resurfaces from an older revision.** Classic-table `f`
entries and xref-stream type-0 rows were discarded instead of recorded, so an object deleted
in the newest revision could still resolve from a stale entry in an older one. Both are now
tracked, scoped per revision so a hybrid file's own `/XRefStm` still resolves an object its
classic table marks free — the convention such a file uses to hide that object from a
classic-table-only reader. (#121)

- **A malformed generation field no longer takes down the document, or aliases onto the wrong
object.** A sloppy but unambiguous field (space-padded rather than zero-padded) still parses.
One that is genuinely unparseable, or exceeds the ISO 32000-2 §7.5.4 ceiling of 65535, is
recorded as unknown rather than guessed at 0, so the object's header takes over instead of the
object going unresolvable at every generation. A reference whose own token is unparseable,
negative, or exceeds 65535 no longer aborts the document either; it simply matches no real
xref entry, the same outcome an ordinary mismatch already produces. (#121)

## [2.0.0] - 2026-08-17

Expand Down
2 changes: 1 addition & 1 deletion src/VellumPdf.Conformance/PdfPreflight.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ private static IReadOnlyList<PdfConformance> DetectClaimedProfiles(PdfDocumentRe
if (metaRef is not PdfIndirectReference r)
return [];

var parsedStream = reader.ResolveStream(r.ObjectNumber);
var parsedStream = reader.ResolveStream(r);
if (parsedStream is null)
return [];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -522,7 +522,7 @@ private static bool TryResolve(
// from plain objects in the reader).
try
{
stream = context.Reader.ResolveStream(r.ObjectNumber);
stream = context.Reader.ResolveStream(r);
if (stream is not null)
return true; // resolved stays null; stream is set.
}
Expand Down
6 changes: 4 additions & 2 deletions src/VellumPdf.Conformance/Rules/PreflightContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -415,10 +415,12 @@ public IEnumerable<PdfDictionary> EnumerateAnnotations()

/// <summary>
/// Resolves <paramref name="obj"/> to a stream object, or <see langword="null"/> when it is
/// not an indirect reference to a stream.
/// not an indirect reference to a stream. Honours the reference's generation the same way
/// <see cref="Resolve"/> does — a stream reference at the wrong generation resolves to
/// nothing, matching <c>Resolve</c> rather than the object number alone (ISO 32000-2 §7.3.10).
/// </summary>
public ParsedStream? ResolveStream(PdfObject? obj)
=> obj is PdfIndirectReference r ? Reader.ResolveStream(r.ObjectNumber) : null;
=> obj is PdfIndirectReference r ? Reader.ResolveStream(r) : null;

/// <summary>The number of indirect objects in the cross-reference table.</summary>
public int IndirectObjectCount => Reader.ObjectNumbers.Count;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ private static (EmbeddedPdfAKind Kind, PdfConformance? Level) ReadEmbeddedPdfAIn

if (metadataObj is not PdfIndirectReference metaRef)
return (EmbeddedPdfAKind.NoPdfAId, null);
var stream = reader.ResolveStream(metaRef.ObjectNumber);
var stream = reader.ResolveStream(metaRef);
if (stream is null)
return (EmbeddedPdfAKind.NoPdfAId, null);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ private static void TryRecordFormInvocation(
return; // direct objects cannot be shared — always unique, skip

// Resolve to the stream dictionary. ResolveStream returns null for non-streams.
var stream = context.Reader.ResolveStream(iref.ObjectNumber);
var stream = context.Reader.ResolveStream(iref);
if (stream is null)
return;

Expand Down
39 changes: 33 additions & 6 deletions src/VellumPdf.Kernel/Core/PdfIndirectObject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,31 +6,58 @@
namespace VellumPdf.Core;

/// <summary>
/// An indirect object wrapper: writes N 0 obj … endobj (ISO 32000-2 §7.3.10).
/// Generation is always 0 for fresh documents.
/// An indirect object wrapper: writes N G obj … endobj (ISO 32000-2 §7.3.10).
/// Generation is 0 unless constructed otherwise — every object a fresh document mints is
/// generation 0; a nonzero generation only matters when re-emitting an object that already
/// exists in a document being incrementally updated (see <see cref="Generation"/>).
/// </summary>
public sealed class PdfIndirectObject : PdfObject
{
/// <summary>The object number assigned to this indirect object.</summary>
public int ObjectNumber { get; }

/// <summary>The generation this object is written at (the <c>G</c> in <c>N G obj</c>).</summary>
public int Generation { get; }

/// <summary>The wrapped object value.</summary>
public PdfObject Value { get; }

/// <summary>Creates an indirect object with the given <paramref name="objectNumber"/> wrapping <paramref name="value"/>.</summary>
/// <summary>
/// Creates an indirect object with the given <paramref name="objectNumber"/>, at generation 0,
/// wrapping <paramref name="value"/>.
/// </summary>
public PdfIndirectObject(int objectNumber, PdfObject value)
{
ObjectNumber = objectNumber;
Value = value;
}

/// <summary>An indirect reference (N 0 R) pointing at this object.</summary>
public PdfIndirectReference Reference => new(ObjectNumber);
/// <summary>
/// Creates an indirect object with the given <paramref name="objectNumber"/> and
/// <paramref name="generation"/>, wrapping <paramref name="value"/>. Re-emitting an object that
/// already exists in a document — an incremental update's job — must keep that object's
/// existing generation; only a freed number being reused for a different object advances it
/// (ISO 32000-2 §7.5.4).
/// </summary>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="generation"/> is negative.</exception>
public PdfIndirectObject(int objectNumber, int generation, PdfObject value)
{
ArgumentOutOfRangeException.ThrowIfNegative(generation);
ObjectNumber = objectNumber;
Generation = generation;
Value = value;
}

/// <summary>An indirect reference (N G R) pointing at this object.</summary>
public PdfIndirectReference Reference => new(ObjectNumber, Generation);

/// <summary>Writes the serialised PDF representation to <paramref name="writer"/>.</summary>
public override void WriteTo(PdfWriter writer)
{
WriteInt(writer, ObjectNumber);
writer.WriteAscii(" 0 obj\n"u8);
writer.WriteAscii(" "u8);
WriteInt(writer, Generation);
writer.WriteAscii(" obj\n"u8);
Value.WriteTo(writer);
writer.WriteAscii("\nendobj"u8);
}
Expand Down
46 changes: 36 additions & 10 deletions src/VellumPdf.Kernel/Core/PdfIndirectReference.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,53 @@

namespace VellumPdf.Core;

/// <summary>PDF indirect reference: N 0 R (ISO 32000-2 §7.3.10).</summary>
/// <summary>PDF indirect reference: N G R (ISO 32000-2 §7.3.10).</summary>
public sealed class PdfIndirectReference : PdfObject, IEquatable<PdfIndirectReference>
{
/// <summary>The referenced object's number (the <c>N</c> in <c>N 0 R</c>).</summary>
/// <summary>The referenced object's number (the <c>N</c> in <c>N G R</c>).</summary>
public int ObjectNumber { get; }
/// <summary>Creates an indirect reference to the object with the given number.</summary>

/// <summary>The referenced object's generation (the <c>G</c> in <c>N G R</c>).</summary>
public int Generation { get; }

/// <summary>Creates an indirect reference to the object with the given number, at generation 0.</summary>
public PdfIndirectReference(int objectNumber) => ObjectNumber = objectNumber;

/// <summary>Writes the reference as <c>N 0 R</c> (generation is always 0).</summary>
/// <summary>
/// Creates an indirect reference to the object with the given number and generation.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="generation"/> is negative —
/// ISO 32000-2 §7.3.10 does not permit one, and <see cref="WriteTo"/> would otherwise emit
/// text (e.g. <c>5 -1 R</c>) that this library's own reader rejects as malformed.</exception>
public PdfIndirectReference(int objectNumber, int generation)
{
ArgumentOutOfRangeException.ThrowIfNegative(generation);
ObjectNumber = objectNumber;
Generation = generation;
}

/// <summary>Writes the reference as <c>N G R</c>.</summary>
public override void WriteTo(PdfWriter writer)
{
Span<byte> buf = stackalloc byte[12];
Utf8Formatter.TryFormat(ObjectNumber, buf, out var len);
writer.WriteAscii(buf[..len]);
writer.WriteAscii(" 0 R"u8);
writer.WriteAscii(" "u8);
Utf8Formatter.TryFormat(Generation, buf, out len);
writer.WriteAscii(buf[..len]);
writer.WriteAscii(" R"u8);
}

/// <summary>Two references are equal when they target the same object number.</summary>
public bool Equals(PdfIndirectReference? other) => other is not null && ObjectNumber == other.ObjectNumber;
/// <summary>Determines whether <paramref name="obj"/> is a reference to the same object number.</summary>
/// <summary>Two references are equal when they target the same object number and generation.</summary>
public bool Equals(PdfIndirectReference? other) =>
other is not null && ObjectNumber == other.ObjectNumber && Generation == other.Generation;
/// <summary>Determines whether <paramref name="obj"/> is a reference to the same object number and generation.</summary>
public override bool Equals(object? obj) => obj is PdfIndirectReference r && Equals(r);
/// <summary>Returns a hash code derived from the object number.</summary>
public override int GetHashCode() => ObjectNumber;
/// <summary>
/// Returns a hash code derived from the object number and generation. Deterministic across runs
/// — unlike <see cref="HashCode.Combine{T1, T2}(T1, T2)"/>, which salts with a per-process random
/// seed — because this type shipped Stable in 2.0.0 and a process-randomized hash is a footgun
/// for any consumer outside this repository that persists or compares one across runs.
/// </summary>
public override int GetHashCode() => unchecked((ObjectNumber * 397) ^ Generation);
}
6 changes: 6 additions & 0 deletions src/VellumPdf.Kernel/Core/PdfObjectRemapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ public static PdfObject Remap(PdfObject obj, IReadOnlyDictionary<int, int> oldTo
{
return obj switch
{
// The one-arg ctor drops r.Generation, silently rewriting a remapped reference to
// generation 0. Harmless here specifically: LinearizedLayoutPlanner, this method's only
// caller, only ever remaps freshly-registered objects from PdfObjectRegistry, which are
// always generation 0 — a read → remap → write path already exists (AppendRevision,
// fixed for exactly this in #121), but linearization is not it, and never has been handed
// a reference parsed from a source document. It stops being harmless the day that changes.
PdfIndirectReference r => oldToNew.TryGetValue(r.ObjectNumber, out var n)
? new PdfIndirectReference(n)
: r,
Expand Down
62 changes: 50 additions & 12 deletions src/VellumPdf.Kernel/IO/IncrementalCrossReferenceBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,22 +24,32 @@ internal static class IncrementalCrossReferenceBuilder
/// </summary>
/// <param name="writer">PDF writer positioned immediately after the last appended object.</param>
/// <param name="writtenObjects">
/// Pairs of (objectNumber, absoluteByteOffset) for every object written in this revision.
/// May be supplied in any order (sorted internally for the xref). Must not be empty.
/// Triples of (objectNumber, generation, absoluteByteOffset) for every object written in
/// this revision. Rewriting an existing object number keeps that object's existing
/// generation — generation only advances when a freed number is reused for a different
/// object (ISO 32000-2 §7.5.4); this builder trusts the caller to have gotten that right
/// and just records whatever it is given. May be supplied in any order (sorted internally
/// for the xref). Must not be empty.
/// </param>
/// <param name="baseSize">
/// The /Size value from the base document's trailer. The new /Size is
/// max(<paramref name="baseSize"/>, maxObjectNumber + 1).
/// </param>
/// <param name="catalogRef">Carried /Root reference from the base trailer.</param>
/// <param name="catalogRef">
/// Carried /Root reference from the base trailer. Its generation must match whatever
/// <paramref name="writtenObjects"/> records for that same object number — or, if /Root
/// was not itself rewritten in this revision, the generation the base document already has
/// on file for it — or the appended trailer disagrees with the xref entry and object
/// header it sits next to.
/// </param>
/// <param name="prevXrefOffset">The base document's startxref value, written as /Prev.</param>
/// <param name="documentId">
/// The base document's /ID array entries (first and second). Written verbatim — never
/// modified in incremental updates (ISO 32000-2 §14.4).
/// </param>
internal static long WriteIncrementalXrefAndTrailer(
PdfWriter writer,
IReadOnlyList<(int ObjectNumber, long ByteOffset)> writtenObjects,
IReadOnlyList<(int ObjectNumber, int Generation, long ByteOffset)> writtenObjects,
int baseSize,
PdfIndirectReference catalogRef,
long prevXrefOffset,
Expand Down Expand Up @@ -75,10 +85,12 @@ internal static long WriteIncrementalXrefAndTrailer(
WriteInt(writer, entries.Count);
writer.WriteByte((byte)'\n');

foreach (var (_, offset) in entries)
foreach (var (_, generation, offset) in entries)
{
Write10Digits(writer, offset);
writer.WriteAscii(" 00000 n\r\n"u8);
writer.WriteByte((byte)' ');
Write5Digits(writer, generation);
writer.WriteAscii(" n\r\n"u8);
}
}

Expand All @@ -104,21 +116,21 @@ internal static long WriteIncrementalXrefAndTrailer(
return xrefOffset;
}

private static List<(int FirstObjNum, List<(int ObjectNumber, long ByteOffset)> Entries)> GroupIntoRuns(
IReadOnlyList<(int ObjectNumber, long ByteOffset)> items)
private static List<(int FirstObjNum, List<(int ObjectNumber, int Generation, long ByteOffset)> Entries)> GroupIntoRuns(
IReadOnlyList<(int ObjectNumber, int Generation, long ByteOffset)> items)
{
var runs = new List<(int, List<(int, long)>)>();
List<(int, long)>? current = null;
var runs = new List<(int, List<(int, int, long)>)>();
List<(int, int, long)>? current = null;
int prevNum = -2;

foreach (var (objNum, offset) in items)
foreach (var (objNum, generation, offset) in items)
{
if (objNum != prevNum + 1 || current is null)
{
current = [];
runs.Add((objNum, current));
}
current.Add((objNum, offset));
current.Add((objNum, generation, offset));
prevNum = objNum;
}

Expand Down Expand Up @@ -148,4 +160,30 @@ private static void Write10Digits(PdfWriter w, long n)
}
w.WriteAscii(buf);
}

private static void Write5Digits(PdfWriter w, int n)
{
// Unreachable through DssBuilder/ArchiveTimestampBuilder as things stand: both thread only
// a PdfIndirectReference.Generation parsed off the source document, and the parser caps
// that at the ISO 32000-2 §7.5.4 ceiling of 65535 (PdfObjectParser.ParseGenerationLenient) —
// well inside the 5-digit field's own 99999 ceiling checked below. A document whose /Root
// reference names a larger generation fails to open at all (PdfDocumentReader's constructor
// requires /Root to resolve), so no caller ever reaches AppendRevision with one. Kept as a
// guard rather than an assertion: AppendRevision's parameter is a public-facing (int, int,
// PdfObject) triple, so a caller that builds one by hand — not through a parsed reference —
// can still ask for a generation this field cannot hold, and a clear exception naming the
// field's own limit beats a truncated or wrapped write.
if (n is < 0 or > 99_999)
throw new NotSupportedException(
$"Generation {n} does not fit the 5-digit xref field (0–99999).");
Span<byte> buf = stackalloc byte[5];
buf.Fill((byte)'0');
var tmp = n;
for (var i = 4; i >= 0 && tmp > 0; i--)
{
buf[i] = (byte)('0' + tmp % 10);
tmp /= 10;
}
w.WriteAscii(buf);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,12 @@ private static void WriteHexId(PdfWriter w, ReadOnlySpan<byte> id)

private static void WriteRef(PdfWriter w, PdfIndirectReference r)
{
// Hardcodes generation 0 rather than r.Generation. Harmless here specifically: both callers
// (catalogRef, infoRef below) come from a freshly-built PdfDocument, which mints everything
// at generation 0 — a read → remap → write path already exists (AppendRevision, fixed for
// exactly this in #121), but linearization is a distinct one-shot save path that has never
// been given a reference parsed from a source document. If that changes, this must become
// r.WriteTo(w) or otherwise carry the real generation through.
WriteInt(w, r.ObjectNumber);
w.WriteAscii(" 0 R"u8);
}
Expand Down
4 changes: 4 additions & 0 deletions src/VellumPdf.Kernel/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
#nullable enable
VellumPdf.Core.PdfIndirectReference.Generation.get -> int
VellumPdf.Core.PdfIndirectReference.PdfIndirectReference(int objectNumber, int generation) -> void
VellumPdf.Core.PdfIndirectObject.Generation.get -> int
VellumPdf.Core.PdfIndirectObject.PdfIndirectObject(int objectNumber, int generation, VellumPdf.Core.PdfObject! value) -> void
Loading