Repository navigation
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
Conversation
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
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.
…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.
…ts for what they pin
…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.
This was referenced Nov 20, 2026
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
ArgumentNullException,ArgumentException,ArgumentOutOfRangeExceptionorInvalidDataException. A subclass of the old type is allowed, and an object cycle that overflowed the stack becomesInvalidOperationException.SaveAsync(string)are the exception: they run at the open, before the token is looked at.PdfDocumentas well asDocument.Deliberate output changes
Save(string)orSaveAsync(string)leaves the file that was already there. Only a failure or cancellation during the final copy can truncate it (Layout: a failed Save(string) destroys the file that was already there #508).?, and an embedded font that lacks the U+202F glyph uses the glyph of U+00A0 instead of glyph 0 (Layout: NormaliseWhitespace turns U+202F NARROW NO-BREAK SPACE and U+2007 FIGURE SPACE into break points #562).Jbig2ImageLoaderembeds only the first page of a multi-page stream (Images: Jbig2ImageLoader reads only the 8-byte ID string, so a standard sequential JBIG2 file (flags + page count) fails to load #570).Attention
Refusals a caller can now hit:
ArgumentNullExceptionfrom the call that took it, where 2.3.3 threwNullReferenceExceptionlater (Six Add methods accept null and defer the failure to Save as a NullReferenceException #523, Layout: a null RunningBand template throws NullReferenceException from Save, not ArgumentNullException #531, Layout: null arguments are stored and throw NullReferenceException from Save #547).new Paragraph((IEnumerable<TextRun>)null)reportsParamNamerunswhere it reportedsource.PdfCanvasandPdfRealthrowArgumentExceptionforNaNor infinity (Layout: every clamp is a comparison, so NaN passes all of them and reaches the content stream #519, Layout: a non-finite colour channel reaches the content stream as an invalid token #509, Layout: a non-finite Document.Margins inset reports the wrong cause, two ways out of three #502, Layout: a footer with a negative-infinity height saves and writes NaN into the text matrix #520, Layout: a negative-infinity list indent writes -Infinity into a nested item's text matrix #532). Where the layout checks the value, it throwsInvalidOperationExceptionnaming the element, so acatchofArgumentExceptionaround a save does not see those. Most non-finite values are not checked before the layout; the CHANGELOG entry on non-finite numbers lists which are.PdfCanvas.AppendArcskips aNaNor positive-infinite radius and throwsArgumentOutOfRangeExceptionfor a negative one, negative infinity included.LineSeparator.LineWidthorTableElement.BorderWidththrowsInvalidOperationException(Layout: a negative line width is written as-3 w, which ISO 32000-2 8.4.3.2 forbids #557).Save,SaveAsyncandPrepareForSigningthrowArgumentException(parameterhandle) before anything is written (Layout: an embedded font handle from another Document saves a page with an undefined font #544).InvalidOperationException. On 2.3.3 it ended the process with a stack overflow (Kernel: a self-referencing array, dictionary or struct element overflows the stack from a normal Save #521).DocumentthrowsInvalidOperationException. Build a newDocument(Layout: a Document that threw during layout silently appends a second layout on the next save #530).EstimatedSignatureSizeBytesthrowsArgumentOutOfRangeExceptionwithParamNameoptionsbefore any page is added. 2.3.3 usedcount, or threwOutOfMemoryExceptionfor sizes up to 2^30 - 1.Saveto a stream that cannot be written to reportsdestinationwhere it reportedstream.PdfDocument.SaveorDocumentRenderer.Renderdoes not check the destination up front, as on 2.3.3. Whatever the stream's ownWritethrows, for exampleObjectDisposedExceptionfor a closedMemoryStreamorNotSupportedExceptionfor a read-only one, comes after serialisation. The document then counts as written and a retry throwsInvalidOperationException.Save(string)is not atomic, and the PDF is held in memory until it is copied. The file is held open withFileShare.Noneuntil the save returns.JBIG2
A file with the T.88 Annex D file header that the ID-string-plus-segments reading cannot read is refused with
InvalidDataExceptionin bothPassthroughandDecodeToRaster, 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,
Passthroughembedded every page's segments andDecodeToRastercomposited every page into one raster. Other behaviour kept from 2.3.3: a segment of unknown length is dropped underPassthroughand ends what is read of the stream, andDecodeToRasterstores 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)throwsArgumentNullException(options) where it threwNullReferenceException.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 b60e949oversrcandtestsshows 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:
InvalidOperationExceptionSecond run (random documents):
Deliberate output changes the run recognised, each in the CHANGELOG:
?SaveAsync(path)leaves an existing file intactArgumentNullExceptionRulings applied, in plain words:
InvalidOperationExceptionnaming the cycle.DocumentorPdfDocumentstays usable and the retry writes it once. After a save that threw once layout had started, a second save throws "cannot be saved again".NaNorInfinitytoken, a negative line width, an undefined resource) or already threw.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.
finallyMeasured on the tree this round, in Debug on net10.0, against
SaveGuardTests,SaveLifecycleTestsandOverflowInputTests(with the Jbig2 and layout classes beside them):SaveGuardTestsand 1 inSaveLifecycleTests. The unmutated baseline fails none.Table_explicitWidthsThatOverflowToInfinity_withAnAutoColumn_keepTheAutoColumnsContentWidth.ARenderReusedAfterACanvasRefusal_doesNotRaiseTheFirstRefusal.ImageLoadOptionsfailsLoad_NullOptions_ThrowsArgumentNullExceptionNamingOptions.!CanRead && !CanSeekas the closed-stream test failsSaveAsync_toAnUnwritableUnreadableSeekableStream_throwsObjectDisposedExceptioninSaveGuardTestsand itsSaveLifecycleTeststwin.Not measured / limits