You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Harden PDF/A and PDF/X conformance, memory safety, and Rust bounds checks - #295
Applies ISO 19005 (PDF/A), ISO 15930 (PDF/X), C++ memory-safety, and Rust bounds-checking fixes across the native bridge and Java pipeline. Fixes /CIDSet bitmask generation on re-subsetted CID/SFNT/CFF fonts per ISO 19005-2 §6.2.11.4.2, leaves XMP Metadata uncompressed for PDF/A-1, enforces integer/iterator bounds in C++ and Rust, and cleans up test formatting.
Changed:
Compute /CIDSet directly from retained PostScript/CFF/SFNT subset glyphs via reloaded FreeType sub-faces in jpdfium_font_normalizer.cpp, jpdfium_qpdf_fonts_embed.cpp, and jpdfium_qpdf_fonts_subset.cpp.
Enforce uncompressed XMP Metadata streams, preserve output intents and PDF/X color invariants across jpdfium_color.cpp, jpdfium_pdfx.cpp, jpdfium_qpdf_sanitize.cpp, PdfCompressor.java, and PdfXConverter.java.
Harden lifetime/bounds checks across jpdfium_internal.h, jpdfium_qpdf_internal.h, jpdfium_advanced.cpp, jpdfium_pattern.cpp, jpdfium_qpdf_pages.cpp, jpdfium_redact.cpp, jpdfium_render.cpp, jpdfium_sanitize.cpp, jpdfium_signature.cpp, and native/rust/jpdfium-impl/src/lib.rs.
PDF repair can recover more malformed or truncated documents, preserve clean signed PDFs, and report when a usable repair isn’t possible.
Font tools can identify damaged embedded fonts and improve font replacement and normalization.
Bug Fixes
PDF/A and PDF/X processing better respects format requirements, including object-stream settings and page-box boundaries.
Compression, sanitization, redaction, and PDF conversion handle more edge cases and malformed data reliably.
Text and pattern matching results are serialized more reliably, while PDF metadata and font mappings are handled more safely.
Invalid or missing output buffers are handled more safely across PDF operations.
The pull request updates PDF font processing, repair, PDF/A and PDF/X conversion, compression, sanitization, pattern APIs, and native API checks. It also adds PDF byte-comparison helpers and updates related tests and security scanner configuration.
Changes: Font processing
Layer / File(s)
Summary
Font inspection and embedding jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontAuditor.java, jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java, native/bridge/src/jpdfium_qpdf_fonts_embed.cpp, native/bridge/src/jpdfium_qpdf_fonts_subset.cpp, jpdfium/src/test/java/stirling/software/jpdfium/doc/PdfFontEmbedderTest.java
Font auditing and embedding use visible text, codepoint coverage, configured font paths, and embedded-program validity. Native embedding preserves inherited mappings and derives CID sets from embedded font programs. Tests cover invisible text and non-renderable codepoints.
Font normalization and cmap repair native/bridge/include/jpdfium_font_internal.h, native/bridge/include/jpdfium_qpdf_internal.h, native/bridge/src/jpdfium_font_normalizer.cpp, native/bridge/src/jpdfium_font_shared.cpp, jpdfium/src/test/java/stirling/software/jpdfium/fonts/FontNormalizerTest.java
Native normalization repairs font widths, encodings, Type 1 lengths, CID metadata, cmap tables, and CID sets. Tests update CIDSet expectations to exclude CID 0.
PDF repair
Layer / File(s)
Summary
Repair input checks and result selection jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfRepair.java, native/bridge/src/jpdfium_repair.cpp, jpdfium/src/test/java/stirling/software/jpdfium/doc/PdfRepairTest.java
The repair flow handles signed and password-blocked documents, prepares input, validates repair stages, and accepts or compacts output only when it meets page checks. Tests cover malformed nesting and salvage cases.
PDF token and page-tree reconstruction jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfRepair.java
Repair helpers normalize malformed tokens, rebuild page trees from page dictionaries, and restore trailer references during truncated-file salvage.
PDF/A and PDF/X output
Layer / File(s)
Summary
PDF/A recognition and page boxes jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfCompressor.java, jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfXConverter.java
PDF/A detection recognizes single-quoted claims and applies PDF/A-1 object-stream settings. Java page-box handling clamps boxes to the MediaBox.
PDF/X writer and metadata configuration native/bridge/src/jpdfium_color.cpp, native/bridge/src/jpdfium_qpdf_pages.cpp
PDF/X writer settings select output versions and object-stream behavior. Metadata parsing, date conversion, catalog version handling, and changed-page tracking are also updated.
PDF/X resource conversion and audit native/bridge/src/jpdfium_pdfx.cpp
PDF/X processing converts additional color spaces and shading, checks resource and annotation structures, removes selected actions and files, and clamps page boxes.
Rust PDF compression and conversion
Layer / File(s)
Summary
Stream compression and input validation native/rust/jpdfium-impl/src/lib.rs
Compression handles additional Flate stream forms, skips metadata streams, and retains filtered data when recompression does not reduce its size. C-ABI pointer checks and pixel-buffer validation are updated, with tests for stream integrity.
Pattern API JSON handling
Layer / File(s)
Summary
Pattern JSON parsing and output native/bridge/src/jpdfium_pattern.cpp
PCRE2 and FlashText results use JSON string escaping. FlashText parsing handles quoted content and object bounds, and result pointers are initialized and checked.
PDF sanitization and byte comparisons
Layer / File(s)
Summary
Sanitization and output handling native/bridge/src/jpdfium_sanitize.cpp, native/bridge/src/jpdfium_qpdf_sanitize.cpp
Sanitization updates CMap and document-structure handling, validates PDF values, and checks output buffers. File output uses scoped stream ownership.
Serialized PDF comparison tests jpdfium/src/test/java/stirling/software/jpdfium/PdfTestAssertions.java, jpdfium/src/test/java/stirling/software/jpdfium/SaveTransportTest.java, jpdfium/src/test/java/stirling/software/jpdfium/redact/RedactionSessionTest.java
Test helpers compare PDF bytes outside validated trailer ID ranges. Save and redaction tests use these helpers.
Native API and resource checks
Layer / File(s)
Summary
Native ownership and API validation native/bridge/include/jpdfium_internal.h, native/bridge/src/jpdfium_advanced.cpp, native/bridge/src/jpdfium_redact.cpp, native/bridge/src/jpdfium_render.cpp, native/bridge/src/jpdfium_signature.cpp, native/bridge/src/jpdfium_qpdf_pages.cpp
Native document ownership is explicit. Buffer, signature, and version-forcing paths validate or configure their output handling.
The security workflow passes the scanner configuration file. The configuration lists RUSTSEC-2026-0543 as ignored with a tracking explanation.
Possibly related issues
Stirling-Tools/JPDFium#191: The changes address parts of the issue’s PDF/A and PDF/X metadata and conformance concerns, but do not cover the full operation matrix.
Possibly related PRs
Stirling-Tools/JPDFium#297: The PRs overlap on PDF/A conformance and CIDSet generation from embedded font data.
Change: Bug fix
Merge Risk: Moderate · up to 097a8
The change broadens PDF/A, PDF/X, repair and font normalization behavior. Several open edge cases can silently alter output, such as tiling-pattern spacing, repaired page trees, font mappings and ToUnicode maps. Resolve or consciously accept these before merging.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title names PDF/A and PDF/X conformance, memory safety, and Rust bounds checks. The changeset covers all three areas: CIDSet and XMP metadata changes for PDF/A, PDF/X box and color changes, C++ li…
Description check
The description follows the template structure: it has the Description of Changes section and the Checklist with General, Library, Native/FFM, and Testing subsections. It explains the main changes (CI…
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Full details: Title check
Explanation
The title names PDF/A and PDF/X conformance, memory safety, and Rust bounds checks. The changeset covers all three areas: CIDSet and XMP metadata changes for PDF/A, PDF/X box and color changes, C++ lifetime and bounds hardening, and Rust bounds checks in lib.rs. The title is slightly broad and long (73 characters), but it names the main changes accurately.
Full details: Description check
Explanation
The description follows the template structure: it has the Description of Changes section and the Checklist with General, Library, Native/FFM, and Testing subsections. It explains the main changes (CIDSet computation, XMP metadata, bounds hardening, moved PR #297 changes) and lists the test updates. The changelog item under [Unreleased] is unchecked, and the description does not mention a Closes #issue reference. The description also marks the integrationTest run as passing while the template's ./gradlew test item is not checked.
Resolution
Record the user-facing changes under ## [Unreleased] in CHANGELOG.md and check that item, or state why no entry is needed. Add a Closes #(issue number) line if an issue exists. Confirm whether ./gradlew test passes, since the description only reports :jpdfium:integrationTest.
Finishing Touches
Generate unit tests (beta)
Commit to this branch
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.
Review details
Context from checks skipped due to timeout: 1
GitHub Check: CodeRabbit
Additional context used
Code guidelines: 1
.github/CODERABBIT_REVIEW.md — configured
Path-based instructions: 4
Apply the native ownership, C ABI, C++23, engine integration, memory, and SIMD rules from .github/CODERABBIT_REVIEW.md.
Learnt from: CR
Repo: Stirling-Tools/JPDFium PR: 0
File: .github/CODERABBIT_REVIEW.md:0-0
Timestamp: 2026-10-20T15:53:18.441Z
Learning: Source excerpt:
# JPDFium review standards
## Comments and documentation
- Keep ordinary inline comments to one or two concise sentences. Longer public contracts and subtle ABI/lifetime explanations are justified; do not shorten them until ambiguity remains.
[warning] 1184-1184: Use a randomly-generated IV
Context: byte[] tail = (trailer + "%%EOF\n").getBytes(StandardCharsets.ISO_8859_1);
Note: [CWE-329] Generation of Predictable IV with CBC Mode.
(random-iv)
Clippy (1.99.1)
native/rust/jpdfium-impl/src/lib.rs
[warning] 67-67: manual implementation of .is_multiple_of()
(warning)
Additional comments: 2
native/bridge/src/jpdfium_font_shared.cpp: 1
397-398: Data Integrity & Integration
The arithmetic concern is real but its reachability is not established. ensureSfntCmapSubtable narrows the cumulative output offset to uint32_t at native/bridge/src/jpdfium_font_shared.cpp:397 without checking the total. Its per-entry bounds check at line 355 allows duplicated or overlapping directory ranges. When the total exceeds UINT32_MAX, the offsets wrap and later table copies can overwrite earlier output.
Whether a PDF font can trigger this depends on whether the pinned FreeType loader accepts such a directory. The repair callers in native/bridge/src/jpdfium_font_normalizer.cpp:1092-1136 pass the same buffer that backs the loaded face, so an accepted directory would reach this helper. The FreeType sfnt loader is not in the checkout, so that premise cannot be decided here.
Public scan can race document close without admission.
visibleFontKeys obtains the native page segment through rawHandleForRead(), which retains no admission. The page and document close paths do not wait for in-flight raw-handle use. A concurrent PdfDocument.close() can free native state between line 587 and the invokeExact calls. Whether this is a defect depends on the documented threading contract for PdfDocument, which is not established in the inspected source. The same unguarded pattern already exists in other public methods, so this change does not introduce it.
The reason will be displayed to describe this comment to others. Learn more.
Minor · Data Integrity & Integration · Quick win
Resolve the PDF/A part after a conformance-only match.
If compressed catalog XMP claims part 1, an Info string containing pdfaid:conformance='B' now makes rawPdfa true. With no raw part-1 or GTS_PDFA1 marker, this skips metadata decoding and returns 2 instead of the previous 1. Compression then selects object-stream generation and can retain that output when smaller. (raw.githubusercontent.com)
When the raw match does not establish the part, inspect the catalog metadata before selecting the structural policy. Add a regression with this combination.
The reason will be displayed to describe this comment to others. Learn more.
Major · Functional Correctness · Quick win
Discard incomplete visibility results.
If page 0 contributes font A and enumeration of page 1 fails, this returns {A}. embedMissing then treats page 1's font B as invisible and skips it. Child-scan failures have the same effect because collectVisibleFonts keeps partial results.
Return an explicit incomplete result, or disable suppression for the whole document after any scan failure. Keep suppression enabled only after a complete scan.
The reason will be displayed to describe this comment to others. Learn more.
Major · Functional Correctness · Quick win
Do not classify an unobserved resource as invisible-only.
A page can contain visible font A and an unused font B in /Resources. Inventory gives B a nonempty pages set, so B is not resourceOnly. This condition skips B even when a matching donor exists. Before this change, B reached embedding.
This also affects fonts outside the text/form walk. Suppress a font only when inspection establishes that every use is in rendering mode 3. Preserve the documented embedding of unused resources.
The reason will be displayed to describe this comment to others. Learn more.
Major · Data Integrity & Integration · Heavy lift
Verify CID mappings before automatic corrupt-font replacement.
For a corrupt Identity-H font whose CID 1 means A, a donor can contain A at GID 36. The coverage check passes, but replacement mode skips prepareMissingCidMapping because the descriptor already has a program. The native path retains /CIDToGIDMap /Identity, so CID 1 renders the donor's GID 1 instead of A.
Use a verified CID-to-donor-GID mapping for corrupt fonts. If the mapping cannot be preserved, leave the font unresolved rather than reporting successful embedding.
The reason will be displayed to describe this comment to others. Learn more.
Major · Data Integrity & Integration · Quick win
Decode JSON escapes before registering keywords.
For [{"keyword": "caf\u00e9","label":"PERSON"}], this loop registers cafu00e9, not café. Searches for café then return no match. Likewise, \n becomes n instead of a newline.
Decode JSON escapes, including Unicode escapes, before calling addKeyword. Add regressions that verify the resulting matches, while preserving plain strings and escaped quotes.
As per coding guidelines, “Preserve stable public behavior.”
The reason will be displayed to describe this comment to others. Learn more.
Major · Data Integrity & Integration · Heavy lift
Preserve the DeviceN process-channel contract.
For /Process << /ColorSpace /DeviceRGB /Components [/Red /Green /Blue] >>, this changes /ColorSpace to /DeviceCMYK but retains three component names and the original DeviceN channels. /Components must match the process colour space in count and order. The resulting dictionary violates that contract. (udp.adobe.io)
Preserve the process mapping when supported. Otherwise, reject the conversion until the complete channel model can be converted. Add a regression that checks /ColorSpace, /Components, and rendered output.
As per coding guidelines, “Preserve stable public behavior.”
The reason will be displayed to describe this comment to others. Learn more.
Major · Functional Correctness · Heavy lift
Do not convert a shading by transforming only its endpoints.
This newly routes RGB shadings through the Type 2 endpoint rewrite in ConvertFunction. Type 2 functions interpolate between their endpoints. (udp.adobe.io)
For a linear black-to-red gradient without a LUT, the rewritten midpoint is CMYK [0,0.5,0.5,0.5]. Converting the original RGB midpoint with ConvertComponents gives [0,1,1,0.5]. The endpoints agree, but intermediate colours do not.
Compose the original function with the colour transformation, or use a sufficiently sampled replacement. Add a midpoint regression, not only endpoint assertions.
As per coding guidelines, “Preserve public pixel semantics.”
Source: Coding guidelines
Major · Data Integrity & Integration · Heavy lift
Keep failed shading conversion atomic.
For an X1a Lab shading, use a Type 3 function with a Type 2 subfunction followed by a Type 4 subfunction. Stitching functions can combine these function types. (udp.adobe.io)
ConvertFunction changes the first subfunction to four CMYK outputs. It then rejects the Lab Type 4 subfunction. This return leaves the shading's /ColorSpace as Lab while retaining the modified four-output subfunction. Preparation can then publish the inconsistent shading.
Stage the complete function graph and commit only after conversion succeeds. On failure, preserve the original graph or reject preparation. Add a regression that fails after the first subfunction converts.
As per coding guidelines, “Every early return and exception must preserve the documented state and cleanup contract.”
The reason will be displayed to describe this comment to others. Learn more.
Major · Functional Correctness · Quick win
Do not change valid tiling-pattern spacing.
Pattern steps use pattern-space coordinates and need not have magnitude at least one. They must be nonzero. (udp.adobe.io)
For XStep=YStep=0.5, BBox=[0,0,0.5,0.5], and Matrix=[20,0,0,20,0,0], this new call changes both steps to 1. It leaves the cell and matrix unchanged, doubling the repetition distance and introducing gaps.
Preserve valid finite steps. If a renderer cannot support a pattern, reject it instead of silently changing its geometry. Add a rendering regression for fractional steps with a scaling matrix.
As per coding guidelines, “Preserve stable public behavior.”
The reason will be displayed to describe this comment to others. Learn more.
Major · Data Integrity & Integration · Quick win
Accept valid CFF header variants before scheduling replacement.
A valid CFF program can start with 01 00 04 01; offSize permits values 1 through 4. This predicate rejects that program and emits programValid=false. embedMissing then replaces a valid embedded font or reports it unresolved. Adobe's CFF specification defines these bytes as header fields, not a fixed four-byte magic. (adobe-type-tools.github.io)
Validate the CFF header fields instead. Apply the same correction to PdfFontAuditor.looksLikeFontProgram, and add a regression that preserves a valid CFF with offSize != 4.
The reason will be displayed to describe this comment to others. Learn more.
Minor · Functional Correctness · Quick win
Compare the bytes between the two ID strings.
/ID[<AA> <BB>] and /ID[<AA>X<BB>] pass this assertion. All hex validations succeed, but the excluded range also contains the separator and inner delimiters. This lets the transport test accept changes outside the ID digits.
Exclude the two digit ranges separately. Compare the intervening bytes exactly. Add a regression that rejects the changed separator but accepts changed ID digits.
The reason will be displayed to describe this comment to others. Learn more.
Minor · Functional Correctness · Quick win
Match the actual trailer /ID key.
The reverse scan also matches /IDBackup. With /ID[<00><11>] /IDBackup[<AA><BB>], changing the final <BB> to <CC> passes both public assertions. The scanner selects /IDBackup, so the helpers exempt unrelated bytes instead of the trailer ID.
Locate the exact /ID key in the trailer dictionary and validate its array boundaries. Add a regression with an unchanged real ID and a changed /IDBackup value.
The reason will be displayed to describe this comment to others. Learn more.
Major · Functional Correctness · Heavy lift
Supported by static analysis
Script executed:
sed -n '1386,1495p' native/bridge/src/jpdfium_font_normalizer.cpp
rg -n 'fixCidSystemInfo|repairFontToUnicode|/Ordering' native/bridge/src/jpdfium_font_normalizer.cpp
Repository: Stirling-Tools/JPDFium
Length of output: 5857
Script executed:
sed -n '90,135p' native/bridge/src/jpdfium_font_normalizer.cpp | cat -n
echo ---
sed -n '1596,1616p' native/bridge/src/jpdfium_font_normalizer.cpp | cat -n
Repository: Stirling-Tools/JPDFium
Length of output: 4256
Keep the existing collection for Identity-H and Identity-V descendants.
The Identity branch of fixCidSystemInfo overwrites /Registry, /Ordering, and /Supplement unconditionally. For a descendant that already has an Adobe Japan1 collection, /Ordering changes to Identity before repairFontToUnicode runs. adobeOrderingForCidFont then reads Identity, so the Adobe collection ToUnicode fallback can no longer select the Japan1 table for fonts that lack usable ToUnicode mappings.
The overwrite must not discard a valid existing collection. Resolve the required CIDSystemInfo for Identity CMaps against ISO 19005-2 6.2.11.3.1 before changing the Identity branch, because the current Adobe/Identity/0 values appear to satisfy that clause. Read the descendant collection before this branch changes it, or keep it for the ToUnicode fallback.
The reason will be displayed to describe this comment to others. Learn more.
Minor · Data Integrity & Integration · Quick win
Preserve codespaces for every retained source width.
With mappings <41> and <8140> and content <00418140>, the existing width heuristic retains both mappings. This new declaration permits only two-byte codes, but Line 331 still emits <41>. The resulting ToUnicode CMap has a mapping outside its declared codespace. Codespace matching requires the same source-code length. (opensource.adobe.com)
Preserve the original encoding-consistent codespace ranges when filtering mappings. Add a mixed-width regression that checks both mappings and their codespaces.
As per coding guidelines, “Preserve stable public behavior,” including output-format semantics.
The reason will be displayed to describe this comment to others. Learn more.
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
⚠️ Outside diff range comments (11)
Major · Keep the last successful output when a pass makes no changes. · PdfFontEmbedder.java:408-411
jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java:408-411 Major · Functional Correctness · Quick win
Keep the last successful output when a pass makes no changes.
QpdfLib.embedFonts returns null on native rc 1. If the missing-font pass returns null, this code skips corrupt-font replacement. If the missing-font pass succeeds but replacement returns null, this code discards the successful rewrite and returns the original PDF. Start each pass with the last successful PDF and replace it only when the pass returns new bytes. Test both orders of success and no change.
Major · Aggregate codepoints page by page instead of materializing the whole… · PdfFontEmbedder.java:769
jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java:769 Major · Performance & Scalability · Quick win
Aggregate codepoints page by page instead of materializing the whole document.
usedCodepoints calls PdfTextExtractor.extractAll(doc), which builds every PageText before the loop starts. Each page keeps its TextLine and TextChar lists alive for the whole document, so peak memory grows with the document's total text. The loop only needs the unique codepoints for each font name.
Change the loop so each page's PageText can be released before the next page is extracted. Use a per-page extraction entry point, if one is accessible from this package. Keep extractAll unchanged for callers that need the complete list.
Major · Keep a valid /Encoding when a font name contains… · jpdfium_font_normalizer.cpp:1145-1148
native/bridge/src/jpdfium_font_normalizer.cpp:1145-1148 Major · Data Integrity & Integration · Heavy lift
Keep a valid /Encoding when a font name contains symbol.
isSymbolicFamilyName matches any font name that contains symbol, so /ExampleSymbolText matches. normalizeSimpleTrueTypeEncoding removes /Encoding at lines 1145-1151 before it checks the cmap. For a font with a (3,1) cmap and no (3,0) cmap, lines 1159-1162 then clear the symbolic flag, but the removed /Encoding is not restored. A valid Differences entry that maps code 65 to /B is lost, so code 65 can render a different glyph.
The whole-document TrueType pass at lines 1806-1811 removes /Encoding the same way, before any cmap check.
Decide the symbolic flag and encoding removal from the effective cmap and the existing /Encoding together. Use one shared decision in both passes. Keep the symbolic repair for fonts whose mappings need it. Add a regression test that code 65 still selects /B after normalization and after reopening the output.
Minor · Do not classify an oversized font program as corrupt. · PdfFontAuditor.java:684
jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontAuditor.java:684 Minor · Functional Correctness · Quick win
Do not classify an oversized font program as corrupt.
If PDFium reports a valid 65 MiB program, getFontProgram returns null without inspecting it. collectCorruptFonts then reports the font as corrupt. Keep the allocation limit, but distinguish an uninspected program from an invalid one. Add a regression that verifies the size limit does not add the font to the result.
Minor · Apply control cleanup only to complete single-scalar… · jpdfium_font_normalizer.cpp:1234-1235
native/bridge/src/jpdfium_font_normalizer.cpp:1234-1235 Minor · Functional Correctness · Quick win
Apply control cleanup only to complete single-scalar names.
For /uni000D0041, the check reads only 000D. It changes the name to /.notdef, then drops the Differences entry, even if the font has a glyph with that exact name. Parse the complete name before classifying it as a control. Keep multi-scalar names intact and continue to clean up single-scalar control names.
Minor · Check cmap reads against each subtable's declared length. · jpdfium_font_normalizer.cpp:851
native/bridge/src/jpdfium_font_normalizer.cpp:851 Minor · Data Integrity & Integration · Quick win
Check cmap reads against each subtable's declared length.
A Format 4 idRangeOffset can leave its subtable and still pass the enclosing cmap check. The validator then interprets bytes from the next subtable as a glyph ID, which can change the CIDSet decision. Format 6 entries and Format 12 groups use the same enclosing bound. Validate each declared subtable length against the enclosing cmap, then reject lookups and arrays that leave that subtable. Keep the corrected Format 12 field offsets.
Based on learnings, offset-based font lookups must stay within the subtable's declared length, not just the enclosing table.
Also applies to: 862-862, 874-874
Source: Learnings
Minor · Publish the corrected /W when every corrected width equals… · jpdfium_font_normalizer.cpp:538
native/bridge/src/jpdfium_font_normalizer.cpp:538 Minor · Data Integrity & Integration · Quick win
Publish the corrected /W when every corrected width equals /DW.
repairCidFontWidths rewrites every existing /W entry in full mode, including unused CIDs. When a corrected width equals /DW, buildCidWidthsArray omits it and returns an empty array. The guard at line 567 then skips the write, so the old /W entry survives. For example, /DW 1000 with /W [7 [500]] and an unused CID 7 whose program width is 1000 keeps the width 500. The stored width then contradicts the embedded program, which the comment at lines 532-534 says must not happen.
Publish the corrected state in this case. Removing /W makes every CID use /DW, which matches the corrected widths. Entries that differ from /DW still produce a nonempty array and keep the current replacement.
Minor · Keep width-only repair from changing fonts it skips. · jpdfium_font_normalizer.cpp:1834-1836
native/bridge/src/jpdfium_font_normalizer.cpp:1834-1836 Minor · Data Integrity & Integration · Quick win
Keep width-only repair from changing fonts it skips.
FontNormalizer.repairWidths documents that fonts without a readable embedded program are skipped. repairWidthsAll calls the same native operation with page index -1. In that whole-document pass, the Type0 loop at jpdfium_font_normalizer.cpp:1823-1838 removes /CIDSet from every Type0 font that processFont did not inspect, including fonts whose program fails to load. The reload at line 1857 publishes the change. PdfRedactor calls repairWidthsAll by default, so an unrelated optional descriptor key can be removed from a skipped font during redaction.
The width-only path must leave skipped fonts unchanged. If the whole-document CIDSet cleanup is required for another mode, restrict it to that mode. If the cleanup must also apply to width-only calls, the repairWidths javadoc must state the change.
native/bridge/src/jpdfium_font_normalizer.cpp:1268-1273 Minor · Functional Correctness · Quick win
Reject uni-prefixed Differences names whose code units are not hexadecimal.
A name such as /uniZZZZ fails the hex check at lines 1219-1233. Lines 1268-1273 still accept it, because algorithmicName checks only the uni prefix and the length. The override is then stored at line 1276, and the base encoding for that code does not apply. A uni name must contain one or more groups of four hexadecimal digits after uni. A name that does not match this form must not set validGlyph. Valid multi-scalar names, such as /uni00410042, must still be kept.
Minor · Do not derive CIDSet from the original face when the… · jpdfium_font_normalizer.cpp:1650-1656
native/bridge/src/jpdfium_font_normalizer.cpp:1650-1656 Minor · Data Integrity & Integration · Quick win
Do not derive CIDSet from the original face when the replacement program cannot be read.
After a successful resubset, the embedded program is the replacement stream. If reading that stream throws, or reloading it returns null, cidSetFace keeps the original face. The cmapFitsProgram guard is skipped because didResubset is true, and the /CIDFontType0 removal does not cover /CIDFontType2. The writer then publishes a CIDSet for the original program on the replaced stream.
The required behavior is that CIDSet must describe the embedded program that is actually written. When the replacement cannot be inspected, the code must not publish coverage derived from the original face. Choose between removing the key and another behavior that the applicable profile permits.
Trivial · Remove the unreachable bundled fallback. · PdfFontEmbedder.java:354-359
restrictedName returns null or a face with embeddable() == false. This branch requires the opposite, so it cannot select an alternate. Remove it, or use a lookup that can return a distinct embeddable candidate. As per coding guidelines, “Remove unused imports, raw types, dead branches, redundant casts, unnecessary wrappers, and duplicated helpers.”
Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.
Learnt from: CR
Repo: Stirling-Tools/JPDFium PR: 0
File: .github/CODERABBIT_REVIEW.md:0-0
Timestamp: 2026-10-31T10:47:27.879Z
Learning: Source excerpt:
# JPDFium review standards
## Java 25 style
- Do not catch `Throwable` merely to swallow or log it. Catch broadly only at a justified boundary or cleanup guard, preserving fatal-error policy and cleanup ordering.
734-735: Do not return a partial visibility set after an object walk fails.
If the walk records font A and the render-mode query for visible font B throws, this catch leaves {A} intact. The caller then skips B as invisible. Rethrow fatal errors and propagate nonfatal scan failures to the page-level handler, which already returns null.
325-325: Require positive evidence before skipping a font as invisible.
If a page draws font A and lists unused font B in /Resources, B has a nonempty page set but is absent from visibleFonts. This branch skips B before donor lookup, contrary to the contract to embed every non-embedded resource. Skip only fonts whose observed uses are all in rendering mode 3 and whose visibility scan is complete.
411-411: Data Integrity & Integration
The concern that an existing /FontFile* makes the native loop skip a corrupt font is not supported. For a donor whose name matches, the loop with onlyMissing false replaces the existing program stream with the donor stream.
native/bridge/src/jpdfium_font_normalizer.cpp: 3
845-845: The supplied prior review already covers the Format 4 scan budget, symbolic identity mapping, ligature component mapping, PFB lengths, Identity collection overwrite, face destruction order, PDF/A-1 CIDSet removal, and stale program snapshot.
Also applies to: 1107-1107, 1124-1126, 1333-1338, 1432-1434, 1638-1639, 1659-1659, 1706-1706
773-774: Data Integrity & Integration
The loop sets a CIDSet bit for any CID whose /CIDToGIDMap entry is GID 0, and only CID 0 is removed afterward. Whether that bit is a conformance defect depends on whether a CID mapped to .notdef counts as "present in the font program" under ISO 19005-2 §6.2.11.4.2. The available sources conflict on this point, and the ISO text was not retrieved. The claimed defect is therefore not decided.
1781-1781: Data Integrity & Integration
The retry-and-double-count mechanism is real in the inspected code. A font that throws after the counter increments is not marked, and the whole-document passes re-run it. Its counted total can then be inflated, and the Type0 pass can remove its /CIDSet if the retry also throws.
The claim depends on a throw that occurs after the first state change. The inspected lines do not establish one. The helpers listed in the evidence could throw from unguarded QPDF calls, and their bodies were not inspected. The review comment's effect is therefore conditional on those helper bodies, and this review cannot decide it from the inspected source.
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 27
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
⚠️ Outside diff range comments (10)
Major · Do not let an incompatible replacement donor discard successful… · PdfFontEmbedder.java:421
jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java:421 Major · Data Integrity & Integration · Heavy lift
Do not let an incompatible replacement donor discard successful embedding.
If the first pass embeds Helvetica and the second pass supplies a Type 1 donor for a corrupt CID font, native code rejects the replacement batch with -4. QpdfLib throws, so the caller loses the successfully rewritten PDF. Before this change, the same missing Helvetica could be embedded without attempting that replacement. Reject the incompatible donor before the replacement pass and leave that CID font unresolved. Keep password and signature failures visible. (raw.githubusercontent.com)
Major · Try the next donor when coverage rejects the preferred face. · PdfFontEmbedder.java:396-402
jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java:396-402 Major · Functional Correctness · Heavy lift
Try the next donor when coverage rejects the preferred face.
If SimSun resolves first to PingFangSC and that face lacks a required ideograph, this branch abandons the font. It never tries an installed NotoSansSC face that covers the text. Validate candidates in preference order and stop at the first eligible face with sufficient coverage. Keep the first choice when it already covers the text.
Major · Keep predefined-CMap substitution when the glyph mapping is… · jpdfium_qpdf_fonts_embed.cpp:570
native/bridge/src/jpdfium_qpdf_fonts_embed.cpp:570 Major · Functional Correctness · Quick win
Keep predefined-CMap substitution when the glyph mapping is independent of /ToUnicode.
A supported 90msp-RKSJ-H font with an inherited /ToUnicode stream now returns false before the native code scans the used CIDs. The caller skips the font. The predefined branch derives glyph mappings from the Adobe collection tables, not from the local /ToUnicode stream. Keep the inherited stream, but limit this refusal to paths that cannot otherwise establish a complete glyph mapping.
Major · Do not mark zero-filled CID map gaps as present glyphs. · jpdfium_qpdf_fonts_embed.cpp:793
native/bridge/src/jpdfium_qpdf_fonts_embed.cpp:793 Major · Data Integrity & Integration · Quick win
Do not mark zero-filled CID map gaps as present glyphs.
If a subset retains CID 3 but not CIDs 1 and 2, the generated /CIDToGIDMap fills those gaps with GID 0. cidsPresentInProgram accepts those entries because zero is below the glyph count. The bitmap writer clears CID 0, not CIDs 1 and 2. Exclude GID 0 entries from the membership scan and apply the same rule in the normalizer. Verify that the reopened bitmap marks CID 3 but not either gap. (raw.githubusercontent.com)
Major · Validate the full algorithmic glyph name before keeping… · jpdfium_font_normalizer.cpp:1332-1337
native/bridge/src/jpdfium_font_normalizer.cpp:1332-1337 Major · Data Integrity & Integration · Quick win
Validate the full algorithmic glyph name before keeping a Differences entry.
/u110000 and /uni41Z1 pass this prefix check. Neither names a valid Unicode scalar or sequence. Both can survive normalization in /Differences. Use the full glyph-name parser for algorithmic names, and retain valid entries such as /u0042 and /uni0041.
Major · Do not reclassify fonts after the normalizer has… · jpdfium_font_normalizer.cpp:1792-1802
native/bridge/src/jpdfium_font_normalizer.cpp:1792-1802 Major · Data Integrity & Integration · Quick win
Do not reclassify fonts after the normalizer has processed them.
In the supplemental TrueType sweep, the processedFonts check follows the symbolic flag update. A font named SymbolExample with (3,1) and (3,10) cmap records but no (3,0) can first be classified as nonsymbolic by normalizeSimpleTrueTypeEncoding, then be marked symbolic by this sweep. The output then fails the symbolic cmap rule. Check processedFonts before changing the descriptor, and apply the same classification logic to unprocessed fonts. This range uses the pinned source because the supplemental sweep was omitted from the annotated excerpt. (raw.githubusercontent.com)
Major · Do not edit a shared /CIDSystemInfo dictionary in place. · jpdfium_font_normalizer.cpp:1470
native/bridge/src/jpdfium_font_normalizer.cpp:1470 Major · Data Integrity & Integration · Quick win
Do not edit a shared /CIDSystemInfo dictionary in place.
If an Identity-H descendant and a Japan1 descendant reference the same indirect dictionary, each repair writes its values into that shared object. Whichever runs last leaves the other descendant with the wrong collection. Install a private dictionary on the target when its values must change. Leave the original reference in place when the values already match.
Major · Read /CIDSystemInfo from the stream dictionary, not the… · jpdfium_font_normalizer.cpp:1482
native/bridge/src/jpdfium_font_normalizer.cpp:1482 Major · Data Integrity & Integration · Quick win
Read /CIDSystemInfo from the stream dictionary, not the stream object.
enc is a stream here (line 1481). QPDFObjectHandle::getKey on a stream handle does not reach the stream dictionary. qpdf returns null with a type warning. As a result, src.isDictionary() is false, the target's Registry, Ordering, and Supplement are not synchronized, and the function returns at line 1491. If the target had no dictionary /CIDSystemInfo, the empty dictionary created at line 1456 stays without its required keys.
Major · Decode original Flate bytes before document-wide decompression. · lib.rs:175
native/rust/jpdfium-impl/src/lib.rs:175 Major · Data Integrity & Integration · Heavy lift
Decode original Flate bytes before document-wide decompression.
The new raw-DEFLATE recovery is bypassed for a /FlateDecode stream containing 01 03 00 FC FF 71 20 51 (q Q). In lopdf 0.47.0, failed zlib and header-skipped decoding can still publish empty content and remove /Filter. The empty-stream guard then skips the object, so compression saves an empty stream without calling the new fallback. (raw.githubusercontent.com)
Decode each original Flate stream before destructive decompression, while preserving /DecodeParms semantics. Add an end-to-end raw-DEFLATE fixture and assert its decoded content after reopening. The helper-only test cannot detect this integration failure.
Severity: major. Confidence: high for the declared dependency version.
Minor · The stale-width test cannot show that CID 0 was repaired. · FontNormalizerTest.java:777
jpdfium/src/test/java/stirling/software/jpdfium/fonts/FontNormalizerTest.java:777 Minor · Functional Correctness · Quick win
The stale-width test cannot show that CID 0 was repaired.
withCidWidth replaces the whole /W array with one entry for CID 0. The width repair counts any other used CID that has a GID but no width as a change. The assertion widthsRepaired == 1 can therefore pass without correcting the CID 0 width.
CID 0 can also be excluded before the comparison. buildCidToGidTable drops entries whose GID is 0. If the embedded map sends CID 0 to GID 0, the injected width is never checked.
Use a stale width on a used CID whose GID is nonzero. After normalization, assert that the saved /W value for that CID equals the font program advance. Keep the CID 0 case only with its own assertion on the saved value.
Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.
Review details
Context from checks skipped due to timeout: 42
GitHub Check: CodeRabbit
GitHub Check: Native bridge libFuzzer (ASan/UBSan, real PDFium)
GitHub Check: Natural System Libvips & Downstream Integration (Linux x64)
GitHub Check: Samples E2E Suite (All 88 Feature Samples)
GitHub Check: README Quick Start Example (Linux x64)
Learnt from: CR
Repo: Stirling-Tools/JPDFium PR: 0
File: .github/CODERABBIT_REVIEW.md:0-0
Timestamp: 2026-10-20T15:53:18.441Z
Learning: Source excerpt:
# JPDFium review standards
## Tests, profiling, and delivery
- Every defect fix needs a focused regression with an observable expected result. No `assertTrue(true)`, swallowed failures, or tests that silently pass when fixtures/tools/source roots are missing.
[warning] 1341-1341: Use a randomly-generated IV
Context: byte[] tail = (trailer + "%%EOF\n").getBytes(StandardCharsets.ISO_8859_1);
Note: [CWE-329] Generation of Predictable IV with CBC Mode.
[warning] 480-481: Use a randomly-generated IV
Context: byte[] deepNesting = ("%PDF-1.4\n" + "<<".repeat(100) + "/Im1 5 0 R")
.getBytes(StandardCharsets.ISO_8859_1);
Note: [CWE-329] Generation of Predictable IV with CBC Mode.
(random-iv)
[warning] 491-492: Use a randomly-generated IV
Context: byte[] headerless = ("<<".repeat(70) + "/Type /Page")
.getBytes(StandardCharsets.ISO_8859_1);
Note: [CWE-329] Generation of Predictable IV with CBC Mode.
(random-iv)
[warning] 557-557: Use a randomly-generated IV
Context: byte[] pdf = sb.toString().getBytes(StandardCharsets.ISO_8859_1);
Note: [CWE-329] Generation of Predictable IV with CBC Mode.
(random-iv)
[warning] 608-608: Use a randomly-generated IV
Context: byte[] pdf = sb.toString().getBytes(StandardCharsets.ISO_8859_1);
Note: [CWE-329] Generation of Predictable IV with CBC Mode.
[warning] 706-706: Use a randomly-generated IV
Context: byte[] staleCidSet = new byte[] {(byte) 0x80, 0, 0, 0, 0x08, 0, 0x20};
Note: [CWE-329] Generation of Predictable IV with CBC Mode.
(random-iv)
Clippy (1.99.1)
native/rust/jpdfium-impl/src/lib.rs
[warning] 69-69: manual implementation of .is_multiple_of()
421-421: Automatic corrupt-CID replacement still needs mapping validation. If CID 1 means A but the donor places A at GID 36, Unicode coverage can pass while the preserved /Identity map selects GID 1.
334-336: The visibility check can still skip an unused page font. A font listed in a page’s resources has a page in the inventory even when no text uses it. Its absence from visibleFonts does not establish Tr 3 use. The auditor can also return a partial set when an object walk fails. (raw.githubusercontent.com)
native/bridge/src/jpdfium_font_normalizer.cpp: 4
1702-1703: cidSetOwned is still destroyed before cidSetGuard retires the face that borrows its bytes. (freetype.org)
1188-1190: The ligature-name loop still installs a multi-scalar glyph such as f_i as the nominal glyph for each component.
1547-1547: The unconditional /CIDSet removal still affects PDF/A-1 CIDFont subsets, where the entry is required. (github-wiki-see.page)
1139-1141: Functional Correctness
The reload at lines 1139-1141 has no evidence of skipping a valid re-subsetted face. The resubset path validates subset.bytes with the same faceIndex before storing it (lines 674-676), and the cmap repair then reloads those same bytes with that index (lines 1139-1140). If the first check succeeds, the second should too.
The review comment poses a question about the generated map. Its premise is a runtime-generated artifact. The inspected source shows that a zero-filled hole is possible when mapping keys are sparse. The source that decides whether this fixture produces such a hole was not inspected: the population of remappedGlyph or job.cidGlyph for issue20065, and the cids set that the normalizer passes to buildCidSetBits (jpdfium_font_normalizer.cpp lines 900-925). Without those, the assertion at FontNormalizerTest.java:804-807 cannot be shown to demand a bit for a glyphless CID. No defect is established, and no correction is proposed.
The reason will be displayed to describe this comment to others. Learn more.
Minor · Functional Correctness · Quick win
Describe invisible-font embedding as strict API policy.
PDF/A-2 clause 6.2.11.5 concerns font metrics. Its embedding rule exempts fonts used only in rendering mode 3. Keep the stricter API behavior if intended, but remove the claim that PDF/A-2 requires it. Update the matching comments in the best-effort branch and integration test. (github.com)
The reason will be displayed to describe this comment to others. Learn more.
Major · Functional Correctness · Quick win
Supported by static analysis
Script executed:
# Locate the key() definition and its call sites in PdfFontEmbedder.java.
rg -n -F -e 'key(' -e 'computeIfAbsent' -- jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java ||test"$?" -eq 1
# Read the coverage collection window around line 798.
cat -n jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java | sed -n '776,812p'# Read the donor validation window around line 380.
cat -n jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java | sed -n '362,416p'
Repository: Stirling-Tools/JPDFium
Length of output: 5849
Script executed:
# Read key() definition and its normalization.
cat -n jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java | sed -n '718,740p'# Read the loop header that binds key for the coverage lookup at line 380.
cat -n jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java | sed -n '338,352p'
Repository: Stirling-Tools/JPDFium
Length of output: 1821
Scope the coverage check to the missing font's own codepoints.
key() strips the subset prefix, so usedCodepoints merges every subset of one base family into one set. The donor check at lines 380-402 then requires codepoints drawn by other subsets. For example, a missing GHIJKL+Acme that uses only A is rejected by a donor that covers A but not Ω, because ABCDEF+Acme draws Ω. The missing font is then not embedded.
Build the coverage requirement from codepoints drawn with the missing font itself. Keep the base-family key for font resolution at lines 346, 703, and 1218.
The reason will be displayed to describe this comment to others. Learn more.
Major · Functional Correctness · Quick win
Do not report successful sanitization without sanitizing.
If an openable signed PDF contains an embedded file, sanitize(true) returns CLEAN and the original bytes before it reaches sanitization. Preserving the signature is correct, but the caller cannot tell that the requested sanitization did not happen. Return an explicit conflict when sanitization is requested. Keep signed pass-through when it is not requested. Test both options on the same signed fixture.
The reason will be displayed to describe this comment to others. Learn more.
Minor · Functional Correctness · Quick win
Supported by static analysis
Script executed:
# Cascade guards and fallback calls
cat -n jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfRepair.java | sed -n '296,362p'# Where pageTree and salvagedResult are bound
rg -n -F -e 'pageTree' -e 'salvagedResult' -- jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfRepair.java ||test"$?" -eq 1
# hasPages and isUsable definitions
rg -n -F -e 'hasPages' -e 'isUsable' -- jpdfium/src/main/java/stirling/software/jpdfium/doc/ ||test"$?" -eq 1
Repository: Stirling-Tools/JPDFium
Length of output: 7697
Run the enabled fallbacks until a page-bearing result is found.
The fallback guards at lines 308 and 311 check only isUsable(). The adoption check at line 314 also requires hasPages(...). A usable RepairLib.repair(pageTree, flags) result with no pages therefore skips both fallbacks and is rejected. The same mismatch exists at lines 325 and 328 for the truncated-file salvage.
Both fallbacks operate on pageTree, the same bytes the core repair received. A page-bearing fallback result can therefore recover the document that the core repair left without pages. Gate each fallback on the negation of the adoption condition, !(salvagedResult.isUsable() && hasPages(salvagedResult.repairedPdf())), at lines 308, 311, and 325. A usable page-bearing core result should still stop the cascade.
The reason will be displayed to describe this comment to others. Learn more.
Minor · Data Integrity & Integration · Quick win
Build fatal diagnostics independently of partial success output.
If warnings_to_json() throws and allocation then recovers, the widened catch appends fatal fields after the existing "issues": prefix. RepairLib.inspect() returns the malformed JSON. Start the fatal response in a clean buffer and publish only a complete response. Inject a failure during warning serialization and check that Java receives parseable fatal JSON.
Major · Stability & Availability · Heavy lift
Translate diagnostic allocation failures at the C boundary.
If inspection throws std::bad_alloc and memory remains exhausted, the new catch allocates msg and escaped. A second allocation failure escapes the exported function. Final string materialization is also outside the try block. Initialize the output pointer to null and return a checked error code if a diagnostic cannot be built or copied. Update RepairLib.inspect() to handle that result before reading the pointer. Verify with allocation failure injection.
As per coding guidelines, “Exported boundaries translate exceptions; noexcept alone does not translate them.”
The reason will be displayed to describe this comment to others. Learn more.
Minor · Data Integrity & Integration · Quick win
Preserve valid surrogate pairs in consecutive ranges.
Minor; high confidence. For <0002> <0003> <D83DDE00>, this check rejects the valid UTF-16BE pair before adding either mapping. Adobe explicitly permits surrogate-pair destinations in bfrange. (pdfa.org)
If another mapping parses successfully, the sanitizer replaces /ToUnicode without these surviving mappings. Validate surrogate pairing instead of rejecting every surrogate unit. Add a saved-text regression with BMP and supplementary characters. (raw.githubusercontent.com)
As per coding guidelines, “Preserve stable public behavior,” including output-format semantics.
The reason will be displayed to describe this comment to others. Learn more.
Major · Stability & Availability · Quick win
Dispatch EOF cleanup to the active CMap section.
Major; high confidence. An unterminated bfrange array with 100,000 short destination strings reaches flushBfChar() here. That helper repeatedly erases two elements from the vector front. This causes roughly 2.5 billion string-element moves and treats range operands as bfchar mappings. The output-entry cap does not prevent this work. (raw.githubusercontent.com)
Flush only the active section and reject incomplete arrays. Add a truncated-array regression with an observable rejection result and bounded completion time.
As per coding guidelines, “Every defect fix needs a focused regression with an observable expected result.”
The reason will be displayed to describe this comment to others. Learn more.
Minor · Maintainability & Code Quality · Quick win
Exercise the still-filtered branch in the regression test.
lopdf 0.47.0 already recovers this corrupt-Adler fixture during doc.decompress(). It removes /Filter before the loop, so this test also passes with the old defective replacement branch. (raw.githubusercontent.com)
Add a zlib stream containing q Q with /DecodeParms << /Predictor 12 /Columns 1 >>. lopdf rejects its predictor data, leaving the stream filtered. Assert that the original compressed bytes and filter remain unchanged when zopfli cannot shrink the content. This distinguishes the fixed branch from the old implementation. (raw.githubusercontent.com)
Severity: minor. Confidence: high. As per coding guidelines, “Every defect fix needs a focused regression with an observable expected result.”
Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.
Review details
Additional context used
Code guidelines: 1
.github/CODERABBIT_REVIEW.md — configured
Path-based instructions: 3
Apply the native ownership, C ABI, C++23, engine integration, memory, and SIMD rules from .github/CODERABBIT_REVIEW.md.
CodeRabbit configuration file
Files:
native/bridge/src/jpdfium_font_normalizer.cpp
native/bridge/src/jpdfium_sanitize.cpp
Apply the Java 25 and FFM rules from .github/CODERABBIT_REVIEW.md.
The concern that compaction skipping makes repaired output "much larger" is not supported. The native repair writer sets setCompressStreams(true), so the core output keeps compressed streams, and no decoded-QDF output path appeared in the inspected source. The compaction guard skips compaction when either format flag is set, not only when both are set. That skip is deliberate. Compaction would conflict with the classic xref and PDF 1.4 settings the flags require.
The reason will be displayed to describe this comment to others. Learn more.
Major · Data Integrity & Integration · Heavy lift
Supported by static analysis
Script executed:
rg -n -i 'XStep|YStep|applyDocumentOptions|clamp' native/bridge/src/jpdfium_qpdf.cpp
sed -n 425,475p jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfCompressor.java
Repository: Stirling-Tools/JPDFium
Length of output: 4477
Keep tiling-pattern steps unchanged in the PDF/A-1 stream pass.
The stream pass calls PdfOptimizer.optimize with RECOMPRESS_FLATE | COMPRESS_STREAMS. Native applyDocumentOptions runs clampPatternSteps before it checks any flag. That clamp replaces a tiling-pattern /XStep or /YStep with an absolute value below 1.0 by 1.0. A pattern with /XStep 0.5 therefore renders with different tile spacing after this pass.
The Java code adopts the output whenever it is smaller (opt.length < resultBytes.length). It does not compare rendering, so the changed pattern is accepted without a check.
This pass must leave tiling-pattern steps unchanged, or reject its output when they change. Keep the overflow clamp for non-finite and out-of-range steps, because the native source documents that protection.
Add a regression. Render a PDF/A-1 page that contains a /XStep 0.5 tiling pattern before and after this pass, and assert that the rendering matches.
The reason will be displayed to describe this comment to others. Learn more.
Minor · Data Integrity & Integration · Quick win
Do not publish a partial CMap after a resource limit.
If an earlier mapping succeeds, this return discards the range but leaves parseToUnicode() successful. Lines 799-807 then replace /ToUnicode with incomplete mappings.
For example, place <0001> <0041> before range <0002> <FFFF> with a 258-byte destination containing repeated <0042> units. This check rejects the range. Surviving content <00010002> loses the mapping for 0002, which the previous implementation retained.
Propagate limit exhaustion separately. Skip the replacement or fail sanitization instead of publishing a partial CMap. Add a regression that checks the surviving mapping and the limit result.
As per coding guidelines, “Preserve stable public behavior,” including output-format semantics.
Source: Coding guidelines
This branch has not been deployed
No deployments
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
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.
Description of Changes
Applies ISO 19005 (PDF/A), ISO 15930 (PDF/X), C++ memory-safety, and Rust bounds-checking fixes across the native bridge and Java pipeline. Fixes
/CIDSetbitmask generation on re-subsetted CID/SFNT/CFF fonts per ISO 19005-2 §6.2.11.4.2, leaves XMPMetadatauncompressed for PDF/A-1, enforces integer/iterator bounds in C++ and Rust, and cleans up test formatting.Changed:
/CIDSetdirectly from retained PostScript/CFF/SFNT subset glyphs via reloaded FreeType sub-faces injpdfium_font_normalizer.cpp,jpdfium_qpdf_fonts_embed.cpp, andjpdfium_qpdf_fonts_subset.cpp.Metadatastreams, preserve output intents and PDF/X color invariants acrossjpdfium_color.cpp,jpdfium_pdfx.cpp,jpdfium_qpdf_sanitize.cpp,PdfCompressor.java, andPdfXConverter.java.jpdfium_internal.h,jpdfium_qpdf_internal.h,jpdfium_advanced.cpp,jpdfium_pattern.cpp,jpdfium_qpdf_pages.cpp,jpdfium_redact.cpp,jpdfium_render.cpp,jpdfium_sanitize.cpp,jpdfium_signature.cpp, andnative/rust/jpdfium-impl/src/lib.rs.PdfRepair,PdfFontEmbedder,PdfFontAuditor, font normalizer/shared/subset/embed, and repair tokenization.PdfTestAssertions.java,SaveTransportTest.java,FontNormalizerTest.java(ISO 19005-2/CIDSet), andRedactionSessionTest.java.Checklist
General
## [Unreleased]inCHANGELOG.mdLibrary changes
.github/workflows/compatibility.ymlexcludes the break with a reasondocs/installation.md, and the POMsNative or FFM changes
bash native/build-real.sh)./gradlew :jpdfium:integrationTestnative/bridge/include/jpdfium.hand the ABI notes for any ABI changeTesting
./gradlew :jpdfium:integrationTestpasses