Skip to content

Harden Layout and Kernel inputs and the save lifecycle (v2.3.4, v2.3.5); read JBIG2 file headers; keep narrow no-break spaces - #571

Merged
Tim81 merged 108 commits into
mainfrom
claude/open-pr-test-failures-7ueb5n
Nov 20, 2026
Merged

Tim81 merged 108 commits into
mainfrom
claude/open-pr-test-failures-7ueb5n

Conversation

@Tim81

@Tim81 Tim81 commented Nov 2, 2026 •

Copy link
Copy Markdown
Owner

Closes #502
Closes #508
Closes #509
Closes #519
Closes #520
Closes #521
Closes #523
Closes #530
Closes #531
Closes #532
Closes #544
Closes #546
Closes #547
Closes #548
Closes #555
Closes #556
Closes #557
Closes #562
Part of #570 (Annex D files are refused as in 2.3.3; loading them moves to v2.5)

What this PR does

Hardens Kernel and Layout against inputs that produced invalid files, runtime faults or silent data loss. Apart from the deliberate output changes below, an input that saved a valid file on 2.3.3 saves the same file. The CHANGELOG has one entry per issue, and the XML docs say, per member, what is refused, which call throws and what not to pass.

Rules followed:

  • A refusal keeps 2.3.3's exception type, unless 2.3.3 threw a runtime fault. Those become ArgumentNullException, ArgumentException, ArgumentOutOfRangeException or InvalidDataException. A subclass of the old type is allowed, and an object cycle that overflowed the stack becomes InvalidOperationException.
  • A call with two or more defects is still refused, but the exception reported may be a different defect's than on 2.3.3. A save precondition is reported before a layout defect, and an already cancelled token before both. The path checks of SaveAsync(string) are the exception: they run at the open, before the token is looked at.
  • A refusal raised before the layout runs leaves the document usable, and a retry saves it once. This covers the Kernel PdfDocument as well as Document.
  • New refusals are added only where 2.3.3 wrote an invalid file or already threw.
  • Input that saved a valid file keeps saving and gets a "Do not pass ... 3.0 refuses it" paragraph in the XML doc.

Deliberate output changes

Attention

Refusals a caller can now hit:

JBIG2

A file with the T.88 Annex D file header that the ID-string-plus-segments reading cannot read is refused with InvalidDataException in both Passthrough and DecodeToRaster, as on 2.3.3. Only the 8-byte ID string is stripped, as on 2.3.3. Loading Annex D files correctly moves to v2.5 (#570, #434).

A PDF image is one page, so the loader embeds the page the first page-information segment names, plus the segments of no page. On 2.3.3, Passthrough embedded every page's segments and DecodeToRaster composited every page into one raster. Other behaviour kept from 2.3.3: a segment of unknown length is dropped under Passthrough and ends what is read of the stream, and DecodeToRaster stores the decoded bits unchanged as /DeviceGray, so its raster renders as a negative (T.88 5.6, NOTE 1 gives 1 as black). Jbig2ImageLoader.Load(bytes, null) throws ArgumentNullException (options) where it threw NullReferenceException.

Differential run against 2.3.3

Every input was run against 2.3.3 and against this branch at ada6cb6. Commit b60e949 changed only prose since then: the CHANGELOG, XML-doc comments, inline comments and one test's doc comment. git diff ada6cb6 b60e949 over src and tests shows no changed code line.

The first run compared 28,631 rows and the second, a run of 1,500 random documents, compared 1,500. Both report 0 violations and no pending rulings.

First run:

Result Rows
Both threw the same exception type 12,873
Identical result 12,097
2.3.3 wrote an invalid file, now refused 2,003
Multi-page JBIG2 file, only the first page is kept (deliberate) 1,050
2.3.3 failed with a runtime fault, now a documented argument or data exception 264
Output differs, listed as a deliberate change 154
A save precondition and a layout defect, the precondition is reported 86
Both threw; this branch's type is a subclass of 2.3.3's 35
Two or more defects, the documented exception of one of them is reported 27
A precondition refusal leaves the document usable and the retry writes it once 25
Random document, only the U+202F and U+2007 change (#562) 9
2.3.3 overflowed the stack on an object cycle, now InvalidOperationException 6
Random document, only list lines that 2.3.3 dropped (#556) 1
Random document, only the justified word spacing change (#548) 1
Total 28,631

Second run (random documents):

Result Rows
Both threw the same exception type 439
Identical result 328
2.3.3 failed with a runtime fault, now a documented argument or data exception 268
A save precondition and a layout defect, the precondition is reported 172
2.3.3 wrote an invalid file, now refused 150
Both threw; this branch's type is a subclass of 2.3.3's 68
Two or more defects, the documented exception of one of them is reported 37
Random document, only the U+202F and U+2007 change (#562) 32
Random document, only list lines that 2.3.3 dropped (#556) 3
Random document, only the justified word spacing change (#548) 3
Total 1,500

Deliberate output changes the run recognised, each in the CHANGELOG:

Change Issue
Justified standard-14 text divides the slack by the spaces the line draws #548, #555
U+202F and U+2007 are kept as no-break spaces instead of drawing ? #562
The last item a list draws on a page keeps all its lines #556
Glyphs used through a foreign font handle are merged into the subset #544
A pie start angle of magnitude 1e12 or more is reduced modulo a turn #546
A document that threw once layout had started cannot be saved again; a refusal before layout leaves a retry that saves once #530
The JBIG2 loader keeps the first page of a multi-page file #570
A cancelled SaveAsync(path) leaves an existing file intact #508
An exception message carries the invariant-culture text of the value #519
A null is refused by the call that took it, with ArgumentNullException #523, #531, #547

Rulings applied, in plain words:

  • A refusal keeps 2.3.3's exception type. The exceptions are a runtime fault (null reference, index, overflow, invalid cast, key not found, stack overflow, out of memory, hang), which becomes the documented argument or data exception; a subclass of the old type; and an object cycle, which becomes InvalidOperationException naming the cycle.
  • A call with a save precondition defect (null destination, disposed document, unwritable or closed stream, option conflict) and a layout defect reports the precondition, so the document stays retryable.
  • An already cancelled token wins over any defect, as on 2.3.3.
  • A call with two or more defects is refused as on 2.3.3, but the documented exception of any one of them may be reported. For random documents this was applied only where the plan text provably holds two or more defects.
  • After a refusal before anything is written, a Document or PdfDocument stays usable and the retry writes it once. After a save that threw once layout had started, a second save throws "cannot be saved again".
  • This branch may refuse an input only where 2.3.3 wrote an invalid file (a NaN or Infinity token, a negative line width, an undefined resource) or already threw.
  • A file with the Annex D header that the older reading cannot read is refused with InvalidDataException, as on 2.3.3.

What the run covers: the generated inputs and random documents of those two runs, compared outcome by outcome between 2.3.3 and this branch. It does not cover inputs outside them. It judges a kept input by comparing its output with 2.3.3's, and a refused input by exception type, so it does not check the wording of messages.

Mutation checks

Each mutation changes one line of the code this PR adds and is run against the test written to catch it. The first table repeats counts from runs at an earlier head of this branch; each of these tests is still in the test projects at b60e949, and the runs were not repeated. Every mutation fails its test. Five pass the earlier test project, so the new tests are what catch them. Two, shrinking explicit table widths and reordering the pie sweep expression, also fail an earlier test.

Mutation Failures in its new test Failures in the earlier test project
Explicit table width shrunk 1 4
Bottom inset left unchecked 6 0
Pie sweep expression reordered 1 1
Deferred canvas refusal keeps the last instead of the first 1 0
The layout-failed check made before the stream check 1 0
Array container leave not in a finally 1 0
Embedder fallback recorded for every glyph 1 0

Measured on the tree this round, in Debug on net10.0, against SaveGuardTests, SaveLifecycleTests and OverflowInputTests (with the Jbig2 and layout classes beside them):

  • Restoring the up-front destination check on a synchronous linearized save fails 8 tests: 7 in SaveGuardTests and 1 in SaveLifecycleTests. The unmutated baseline fails none.
  • Scaling the auto column's width in the table grid fails 1 test, Table_explicitWidthsThatOverflowToInfinity_withAnAutoColumn_keepTheAutoColumnsContentWidth.
  • Removing the reset of the deferred canvas refusal fails ARenderReusedAfterACanvasRefusal_doesNotRaiseTheFirstRefusal.
  • Removing the null check on ImageLoadOptions fails Load_NullOptions_ThrowsArgumentNullExceptionNamingOptions.
  • Putting back !CanRead && !CanSeek as the closed-stream test fails SaveAsync_toAnUnwritableUnreadableSeekableStream_throwsObjectDisposedException in SaveGuardTests and its SaveLifecycleTests twin.

Not measured / limits

  • The first table's counts were not re-run at b60e949, and the mutation runs above were Debug on net10.0 only, not Release or net11.0.
  • The differential run covers two seeds. A third seed or a larger corpus could turn up a class these did not.
  • Annex D files are refused, not read, so nothing here measures how they would render.

Tim81 added 16 commits November 2, 2026 15:35
PdfCanvas.N copied PdfReal's format string and left its check behind, so 24
content-stream operators wrote NaN or Infinity as a token. Route all 31 call
sites through one check that throws PdfReal's ArgumentException, and format the
size in SetFont and SetFontByName before writing the font name.

Refs #519
A NaN or infinite channel on a text style, running band, table cell, table
border, line separator or pie chart reached the stream as NaN 0 0 rg. Refuse
it from Save, naming the element and the channel. A finite channel outside 0
to 1 still renders, so it is documented on ColorRgb and ColorCmyk and left to
the next major (#484).

Refs #509
A NaN or negative-infinity margin passed the sum check and surfaced as a
message about an element. A footer height of negative infinity saved a file
with NaN in a text matrix. Check every inset and both band heights up front,
naming the edge or the band, and rewrite the documentation that described the
old routes.

Refs #502, #520
A nested child marker and a flat item with a word too wide for its gutter take
the indent directly, so negative infinity wrote -Infinity into a text matrix.
Refuse NaN and negative infinity up front. Positive infinity and finite
negatives are unchanged.

Refs #532
Sweep of the 24 Math.Max, Math.Min and Math.Clamp sites in Layout: element
Margins on Paragraph, Heading, ListElement, TableElement, LayoutImage and
PieChart were the remaining unchecked caller input. Refuse a non-finite edge
before layout, naming the element. Paragraphs a list builds from its own
indent opt out, since the list has already checked it.

Refs #519
ISO 32000-2, 8.4.3.2 requires a non-negative line width, and LineSeparator
and TableElement wrote a negative one as -3 w. Refuse it in
ValidateLineWidth with the non-finite refusal's shape, naming the clause.
Zero stays accepted.

Refs #557
Refuse a pie slice total that overflows to infinity and a set of explicit
column widths that does. Reduce the pie start angle to a turn with an exact
remainder before sweeps are added; angles within a turn are unchanged. One
dominant finite width still renders and is documented.

Refs #546
Tw applies once per space character, but the divisor counted both neighbours
of every space token, so half the slack was distributed. Divide by the number
of spaces the line draws, and advance each fragment by its drawn width so a
multi-style line does not overprint. A link rectangle on that line follows the
drawn position.

Refs #548, #555
Draw re-lays each item out in Bottom - y, which for the last item on a page
could be one rounding step short of the height Layout tracked, so a
paragraph's floor of the line count dropped a line that Layout had reserved
space for. Record the height offered per item and reuse it.

Refs #556
Null was stored without a check by the Kernel array and dictionary, the Layout
elements, the Document.Add overloads and the renderer constructors, and failed
as NullReferenceException from a later Save. Throw ArgumentNullException from
the call that took it, naming the parameter, and rewrite the documentation that
described the old behaviour.

Refs #523, #531, #547
A handle's resource name is a counter local to the document that issued it,
and usage was recorded by that name without asking which document embedded
the font. Record the owning document on each handle and refuse any other in
RegisterEmbeddedFontUsage, so the save fails where the text is drawn.

Refs #544
A structure element added to itself, or an array or dictionary holding itself,
recursed until the process died, which cannot be caught. Refuse the cycle in
PdfStructElem.AddChild, and keep an active path in PdfWriter and the three
structure-tree walks for a graph built any other way. No depth cap.

Refs #521
A layout that threw left its pages behind and the retry appended a second
layout; refusals that need no layout came after it; an unwritable stream burned
the document. Run those checks before layout, refuse every save after a layout
that threw once pages were added, and check the destination up front in the
kernel's SaveAsync.

Save(string) and SaveAsync(string) opened the path with FileMode.Create before
laying out, so a layout failure left a zero-byte file. Write a temporary file
beside the target and move it over the path only when the whole file is written.

Refs #530, #508
Jbig2ImageLoader skipped only the 8-byte ID string, so the flags byte and page
count were read as the start of the first segment and every standard file
failed. Read the header per ITU-T T.88 Annex D.4, parse the random-access
organisation (headers first, ending with the end-of-file segment, then the data
parts), and rejoin each header to its data when writing the embedded form. The
bare ID-string form and the embedded form still load.

Refs #570
NormaliseWhitespace kept only U+00A0, so a paragraph could wrap at the narrow
no-break space French puts before ; ? ! and at the figure space. Treat all
three white-space characters in UAX #14 class GL as part of a word, in the
paragraph wrap and in ListRenderer's indent bound, from one definition.

Keeping them meant deciding how a font draws them. The Standard-14 encoder and
metrics now treat U+202F and U+2007 as U+00A0 instead of '?', and an embedded
font without the glyph falls back to U+00A0's, then a space's, instead of
.notdef.

Refs #562
@Tim81 Tim81 changed the title Harden Layout and Kernel inputs and the save lifecycle (v2.3.4, v2.3.5); read JBIG2 file headers Harden Layout and Kernel inputs and the save lifecycle (v2.3.4, v2.3.5); read JBIG2 file headers; keep narrow no-break spaces Nov 2, 2026
Tim81 added 13 commits November 2, 2026 19:17
Save(string) and SaveAsync(string) open the file before the layout
without truncating it, build the PDF in memory and copy it in at the
end, so the old file keeps its identity and survives every failure
before the copy. A step after the layout that throws, a cancellation
included, now stops the Document being laid out twice. Signing refuses
encryption before the layout.
A null cell text drew empty in a table with explicit column widths and
threw at save in an auto-sized one. Both now draw an empty cell. The
changelog no longer claims no null could have rendered.
The per-item height array added for #556 turned the documented
ArgumentOutOfRangeException into IndexOutOfRangeException. The start is
now checked before it indexes anything.
A multi-page JBIG2 file put every page's segments in one image stream.
Passthrough and DecodeToRaster now use only the page of the first
page-information segment, plus segments that belong to no page.
Passthrough used to skip a segment of unknown length and embed a blank
image; it now throws InvalidDataException naming the segment.
When U+202F or U+2007 falls back to the glyph of U+00A0 or a space, the
ToUnicode CMap listed the stand-in for that glyph, so copying a normal
space gave a narrow no-break space. The stand-in is now listed only
when no code point that owns the glyph is in use.
Assert the right edge of the two-style justified line, say that
PdfCanvas shares PdfReal's message text but not its ParamName, drop a
wrong claim about every font having a space glyph, and note the
exception types the up-front stream check changes.
Save(string) no longer second-guesses the operating system about
read-only files and directories, follows a symbolic link to the file it
creates or deletes, deletes a created file even if Dispose throws, and
cancels with TaskCanceledException. Signing refuses options no page
count could make valid before laying out. Docs and tests follow.
DecodeToRaster refuses an unknown-length segment of the first page with
the passthrough message, and a first page-information segment with page
association 0 is refused instead of giving a blank image.
Save(string) opens the path as given instead of resolving links by
string rules, which broke /dev/stdout and relative .. targets, and a
link at the path now counts as something that exists. The signing size
check uses the real placeholder bound, a document with no pages is
reported before options, and the unreachable cancel checkpoint is gone.
A first page-information segment with page association 0 selects no
page and keeps every segment, as before pages were chosen.
DecodeToRaster refuses an unknown length only on a generic region, with
the clearer message; every other segment type behaves as it did.
Test saving through a link to /proc/self/fd/N, which the string-rule
link resolver could not open. SomethingExistsAt treats a not-found link
read as nothing there. An empty Document signed with bad options still
reports no pages. The FIFO test is bounded by timeouts.
A page-0 segment of unknown length, such as a trailing tables or
extension segment, and everything in a file that selects no page, is
skipped as before instead of refused.
DocumentRenderer.Render refuses an unwritable destination or bad
options before the layout, so a retry cannot write every page twice.
A Document with no content and a PdfDocument with no pages report no
pages before the destination and options, as before. Justified Symbol
and ZapfDingbats lines keep the pre-#548 divisor (#548).
DecodeToRaster is called from one place, under DecodeMode == DecodeToRaster,
after Load has refused every file with the Annex D header in that mode. The
guard argument was dataStart <= FileHeader.Length, and a file that reaches the
call has no Annex D header, so it was always true and neither skip could fire.
The canvas-refusal test said 2.3.3 threw at the first NaN operand; measured on
2.3.3+1c61fa6 it saved the document with it, so there is no 2.3.3 exception to
keep. The burned-document test said 2.3.3 reported the unwritable stream; it
laid out first and reported the layout defect, so the test now cites the
two-defect ruling instead.
SaveAsync to a stream that cannot be written to or is closed throws
NotSupportedException and ObjectDisposedException, so the tags and the
changelog say so. The already-cancelled-token ordering names the path
overload's open as its exception, AppendArc's skip set excludes a negative
radius, and ParamName is null, not empty, where PdfReal reports it.
The asynchronous save reported ObjectDisposedException only for a stream
that is neither readable nor seekable. An unwritable stream that answers
CanSeek but not CanRead is still how a closed one reports, and it gets
that exception again.
Every other copy repeated a Draw-time or call-time refusal and a
same-font-program condition the code does not have. The check runs at
Save, SaveAsync and PrepareForSigning, and only when the saving
document defines no font under the handle's resource name.
SaveAsync and PrepareForSigning refuse a foreign font handle with
ArgumentException, and PrepareForSigning also throws for a document with
no pages, one already written, and a structure-element cycle. The
Sign and SignAsync overloads point to it.
Tim81 added 13 commits November 20, 2026 06:37
…g cannot read

Only the ID string is stripped, so such a file throws InvalidDataException
in both modes. The gate, the random-access and flags-byte readings and the
rule checks behind them are removed; first-page embedding, headerless
streams and the polarity note stay.
A renderer reused for a second Render raised the first call's refusal
even when the second layout drew cleanly.
…eption

The decode mode is read from the options, so a null reached a
NullReferenceException once the data parsed.
…e stream

The up-front destination check threw ArgumentException for a linearized
PdfDocument.Save, where the stream's own Write decided the type. A write
of no bytes asks the stream the same question before anything is written.
…in the written values

An explicit-width table whose sum is infinity writes every column at width 0
with the text overprinted at the left edge, not an empty table. The two
overflow tests now pin the written rectangles and text positions.
A synchronous linearized save serialises in memory and writes once, so the
stream's own Write decides what an unwritable destination does. The up-front
check made that ArgumentException, and a write of no bytes is not the same
question as a real one. The check is skipped for a linearized document, in
PdfDocument.Save and DocumentRenderer.Render; SaveAsync keeps its check.
…ce the empty-document caveat

An explicit-width table whose sum is infinity writes only its explicit columns
at width 0; an auto column keeps its content width. The empty-document caveat
now sits where it holds: preconditions follow the geometry, a cancelled token
does not.
…rized-save wording

Explicit columns of an infinite-sum table are written at width 0, so cells
that start at the same x overprint; an auto column keeps its width, which
does not by itself prevent it. A Layout Document with nothing added throws
'no pages' before the destination check, so those tags say so.
@Tim81
Tim81 merged commit ea88e67 into main Nov 20, 2026
4 checks passed
Tim81 added a commit that referenced this pull request Nov 20, 2026
PdfStructureTree's six walks recursed, and #571 gave one of them an extra
parameter, so a tagged chain of about 6,500 elements that 2.3.3 saved
ended the process with a stack overflow on the default stack. Five walks
now share one explicit-stack pre-order walk that keeps the same visit
order, path set and cycle message; the sixth, the first-leaf page lookup,
is one post-order pass per Build instead of a walk of every element's
subtree. Depth no longer depends on the calling thread's stack: a chain
of 100,000 elements saves on every path, and 2.3.3 died there too.

Where each element has one parent the walks are linear in the number of
elements; an element added under two parents is walked once per path and
is refused by Save. A duplicate MCID, an MCID over the cap, a non-standard
type and a shared element without an MCID are refused with the same
exception and message as on 2.3.3; the cycle and null-child refusals stay
as #521 introduced them. A tree that saved before saves to the same bytes.
@Tim81
Tim81 deleted the claude/open-pr-test-failures-7ueb5n branch November 21, 2026 06:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment