From a965a25a3c2dd0d638f615b1e86743937cdddbf4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20Sz=C3=BCcs?= Date: Sun, 15 Nov 2026 12:33:05 +0100 Subject: [PATCH] Repair CIDSet, widths, and CFF/PDF/X font handling in native bridge MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Balázs Szücs --- .../software/jpdfium/panama/QpdfLib.java | 2 +- native/bridge/src/jpdfium_advanced.cpp | 278 ++++++---- native/bridge/src/jpdfium_pdfx.cpp | 22 + native/bridge/src/jpdfium_qpdf.cpp | 487 +++++++++++++----- 4 files changed, 560 insertions(+), 229 deletions(-) diff --git a/jpdfium/src/main/java/stirling/software/jpdfium/panama/QpdfLib.java b/jpdfium/src/main/java/stirling/software/jpdfium/panama/QpdfLib.java index 67461fac0..74a382973 100644 --- a/jpdfium/src/main/java/stirling/software/jpdfium/panama/QpdfLib.java +++ b/jpdfium/src/main/java/stirling/software/jpdfium/panama/QpdfLib.java @@ -145,7 +145,7 @@ public record FontSubsetResult(byte[] pdf, int fontsSubset) {} /** True when this native build can subset already-embedded fonts. */ public static boolean isSubsetFontsSupported() { - return SUBSET_FONTS_HANDLE != null; + return SUBSET_FONTS_HANDLE != null && isFontReplacementSupported(); } /** diff --git a/native/bridge/src/jpdfium_advanced.cpp b/native/bridge/src/jpdfium_advanced.cpp index 9f12d5081..9766a0748 100644 --- a/native/bridge/src/jpdfium_advanced.cpp +++ b/native/bridge/src/jpdfium_advanced.cpp @@ -1204,6 +1204,11 @@ static FT_Face load_font_face(FT_Library lib, std::string const& bytes, FT_Long // Minimal content-stream scanner: track the selected font across Tf/q/Q and // collect the character codes or CIDs drawn by text operators. +static bool fn_is_pdf_delimiter(unsigned char c) { + return c == '(' || c == ')' || c == '<' || c == '>' || c == '[' || c == ']' || c == '{' || + c == '}' || c == '/' || c == '%'; +} + struct FnContentOperand { enum class Kind { Name, String, Array, Other }; Kind kind = Kind::Other; @@ -1483,19 +1488,22 @@ struct FnContentLexer { } void skipInlineImage() { + // Image data may abut EI with no separating whitespace, and EI may be + // followed by a delimiter instead of whitespace, so validate only the + // trailing boundary. FnContentToken token; while (next(token)) { if (token.word && token.text == "ID") { if (pos < data.size() && std::isspace(static_cast(data[pos]))) ++pos; while (pos + 1 < data.size()) { - if (std::isspace(static_cast(data[pos])) && - data[pos + 1] == 'E' && pos + 2 < data.size() && data[pos + 2] == 'I' && - (pos + 3 >= data.size() || - std::isspace(static_cast(data[pos + 3])) || - data[pos + 3] == '/' || data[pos + 3] == '(' || data[pos + 3] == '<' || - data[pos + 3] == '[' || data[pos + 3] == '{' || data[pos + 3] == '%')) { - pos += 3; - return; + if (data[pos] == 'E' && data[pos + 1] == 'I') { + const size_t after = pos + 2; + if (after >= data.size() || + std::isspace(static_cast(data[after])) || + fn_is_pdf_delimiter(static_cast(data[after]))) { + pos = after; + return; + } } ++pos; } @@ -2113,84 +2121,139 @@ static void repair_simple_font_widths(QPDFObjectHandle& target, FT_Face face, } // Synthesize a missing /W array on a horizontal CIDFont from FreeType glyph advances. -static void repair_cid_font_widths(QPDFObjectHandle& font, QPDFObjectHandle& target, FT_Face face, - QPDFObjectHandle& cid_to_gid, bool cid_identity, +static std::map parse_cid_widths(QPDFObjectHandle const& w) { + std::map widths; + if (!w.isArray()) return widths; + const auto items = w.getArrayAsVector(); + size_t i = 0; + while (i < items.size()) { + if (!items[i].isInteger()) break; + const uint32_t first = static_cast(items[i].getIntValueAsInt()); + ++i; + if (i >= items.size()) break; + if (items[i].isArray()) { + const auto run = items[i].getArrayAsVector(); + ++i; + for (size_t j = 0; j < run.size() && first + j <= kFontMaxCid; ++j) { + if (run[j].isNumber()) + widths[first + static_cast(j)] = + static_cast(std::lround(run[j].getNumericValue())); + } + continue; + } + if (i + 1 >= items.size() || !items[i].isInteger() || !items[i + 1].isNumber()) break; + const uint32_t last = static_cast(items[i].getIntValueAsInt()); + const int width = static_cast(std::lround(items[i + 1].getNumericValue())); + i += 2; + if (last < first || last > kFontMaxCid) continue; + for (uint32_t cid = first; cid <= last; ++cid) widths[cid] = width; + } + return widths; +} + +static QPDFObjectHandle build_cid_widths_array(std::map const& widths) { + QPDFObjectHandle array = QPDFObjectHandle::newArray(); + auto it = widths.begin(); + while (it != widths.end()) { + const uint32_t start = it->first; + std::vector run; + uint32_t expected = start; + while (it != widths.end() && it->first == expected) { + run.push_back(it->second); + ++it; + ++expected; + } + const bool same = std::ranges::all_of(run, [&](int value) { return value == run.front(); }); + array.appendItem(QPDFObjectHandle::newInteger(start)); + if (run.size() >= 2 && same) { + array.appendItem(QPDFObjectHandle::newInteger(expected - 1)); + array.appendItem(QPDFObjectHandle::newInteger(run.front())); + } else { + QPDFObjectHandle values = QPDFObjectHandle::newArray(); + for (int value : run) values.appendItem(QPDFObjectHandle::newInteger(value)); + array.appendItem(values); + } + } + return array; +} + +static void repair_cid_font_widths(QPDF& pdf, QPDFObjectHandle& font, QPDFObjectHandle& target, + FT_Face face, QPDFObjectHandle& cid_to_gid, bool cid_identity, std::map const& gid_to_cid, FontNormalizeState& state) { // Vertical writing uses /DW2 and /W2, not horizontal /W. if (font.getKey("/Encoding").isNameAndEquals("/Identity-V")) return; - QPDFObjectHandle existing_w = target.getKey("/W"); - if (existing_w.isArray() && existing_w.getArrayNItems() > 0) return; - QPDFObjectHandle dw = target.getKey("/DW"); - const int default_dw = - dw.isNumber() ? static_cast(std::lround(dw.getNumericValue())) : 1000; // /W is keyed by CID, not GID. - std::map cid_to_width; + std::map cid_gid; if (cid_to_gid.isStream()) { try { std::shared_ptr map = cid_to_gid.getStreamData(qpdf_dl_generalized); if (map) { const auto* bytes = static_cast(map->getBuffer()); const size_t entries = map->getSize() / 2; - for (size_t c = 1; c < entries && c <= 0xFFFF; ++c) { + for (size_t c = 0; c < entries && c <= kFontMaxCid; ++c) { const uint32_t gid = (static_cast(bytes[2 * c]) << 8) | bytes[2 * c + 1]; - if (gid == 0) continue; - int width = 0; - if (pdf_width_from_glyph(face, gid, width) && width >= 0 && width != default_dw) - cid_to_width[static_cast(c)] = width; + if (gid != 0) cid_gid[static_cast(c)] = gid; } } } catch (...) { - cid_to_width.clear(); + cid_gid.clear(); } } else if (cid_identity) { if (FT_IS_CID_KEYED(face)) { - for (auto const& entry : gid_to_cid) { - int width = 0; - if (pdf_width_from_glyph(face, (FT_UInt)entry.first, width) && width >= 0 && - width != default_dw) - cid_to_width[entry.second] = width; - } + for (auto const& [gid, cid] : gid_to_cid) cid_gid[cid] = gid; } else { const int max_gid = static_cast( - std::min(face->num_glyphs - 1, static_cast(65535))); - for (int gid = 1; gid <= max_gid; ++gid) { - int width = 0; - if (pdf_width_from_glyph(face, (FT_UInt)gid, width) && width >= 0 && - width != default_dw) - cid_to_width[static_cast(gid)] = width; + std::min(face->num_glyphs - 1, static_cast(kFontMaxCid))); + for (int gid = 1; gid <= max_gid; ++gid) + cid_gid[static_cast(gid)] = static_cast(gid); + } + } + if (cid_gid.empty()) return; + + QPDFObjectHandle existing_w = target.getKey("/W"); + std::map widths = parse_cid_widths(existing_w); + + // With no /W at all, synthesize every mapped CID. With an existing array, + // repair only the CIDs the content draws: unused entries may be deliberate + // producer metadata and are not checked by the validator. + std::set check; + if (widths.empty()) { + for (auto const& [cid, gid] : cid_gid) { + (void)gid; + check.insert(cid); + } + } else { + FnCidScan scan = fn_used_cids_for_font(pdf, font, true, &state); + if (!scan.complete) return; + check = scan.cids; + if (check.empty()) { + for (auto const& [cid, gid] : cid_gid) { + (void)gid; + check.insert(cid); } } } - if (cid_to_width.empty()) return; - std::vector> entries(cid_to_width.begin(), cid_to_width.end()); - QPDFObjectHandle widths = QPDFObjectHandle::newArray(); - size_t i = 0; - while (i < entries.size()) { - size_t j = i + 1; - bool same_width = true; - while (j < entries.size() && entries[j].first == entries[j - 1].first + 1) { - if (entries[j].second != entries[i].second) same_width = false; - ++j; - } - if (j - i >= 2 && same_width) { - widths.appendItem(QPDFObjectHandle::newInteger(entries[i].first)); - widths.appendItem(QPDFObjectHandle::newInteger(entries[j - 1].first)); - widths.appendItem(QPDFObjectHandle::newInteger(entries[i].second)); - } else { - widths.appendItem(QPDFObjectHandle::newInteger(entries[i].first)); - QPDFObjectHandle run = QPDFObjectHandle::newArray(); - for (size_t k = i; k < j; ++k) - run.appendItem(QPDFObjectHandle::newInteger(entries[k].second)); - widths.appendItem(run); + bool changed = false; + for (uint32_t cid : check) { + auto glyph = cid_gid.find(cid); + if (glyph == cid_gid.end()) continue; + int width = 0; + if (!pdf_width_from_glyph(face, glyph->second, width)) continue; + auto existing = widths.find(cid); + if (existing == widths.end() || existing->second != width) { + widths[cid] = width; + changed = true; } - i = j; } - if (widths.getArrayNItems() > 0) { - target.replaceKey("/W", widths); + if (!changed) return; + + QPDFObjectHandle array = build_cid_widths_array(widths); + if (array.getArrayNItems() > 0) { + target.replaceKey("/W", array); ++state.w_fixed; state.changed = true; } @@ -2286,8 +2349,6 @@ static void convert_cff_in_sfnt(QPDF& pdf, QPDFObjectHandle& target, QPDFObjectH * @param cid_identity True if /CIDToGIDMap is /Identity. * @param simple_glyphs Character-code-to-GID mapping array for simple fonts. * @param usage Shared reference counts for descriptors and font streams. - * @param active_cids Output set receiving retained CIDs for CIDSet synchronization. - * @param have_active_cids Output flag set to true when active_cids is populated. * @param state Normalization statistics and scan cache. * @return True if the font program was successfully subsetted and replaced; false otherwise. */ @@ -2297,8 +2358,7 @@ static bool resubset_embedded_sfnt(QPDF& pdf, QPDFObjectHandle& font, QPDFObject std::unique_ptr& face, bool cid, QPDFObjectHandle& cid_to_gid, bool cid_identity, std::vector const& simple_glyphs, - FontUsageCounts const& usage, std::set& active_cids, - bool& have_active_cids, FontNormalizeState& state) { + FontUsageCounts const& usage, FontNormalizeState& state) { if (face->num_glyphs <= 1 || !FT_IS_SFNT(face.get()) || font_has_sfnt_table(face.get(), FT_MAKE_TAG('C', 'F', 'F', '2')) || font_forbids_subsetting(face.get())) @@ -2326,7 +2386,6 @@ static bool resubset_embedded_sfnt(QPDF& pdf, QPDFObjectHandle& font, QPDFObject if ((!is_ttc && tagged) || shared || base_name.empty()) return false; std::set target_glyphs{0}; - std::set used_active{0}; if (cid) { FnCidScan scan = fn_used_cids_for_font(pdf, font, true, &state); if (!scan.complete || scan.cids.empty()) return false; @@ -2351,7 +2410,6 @@ static bool resubset_embedded_sfnt(QPDF& pdf, QPDFObjectHandle& font, QPDFObject } if (gid >= static_cast(face->num_glyphs)) return false; target_glyphs.insert(static_cast(gid)); - used_active.insert(c); } } else { if (simple_glyphs.size() < 256) return false; @@ -2417,33 +2475,53 @@ static bool resubset_embedded_sfnt(QPDF& pdf, QPDFObjectHandle& font, QPDFObject } ++state.resubset; state.changed = true; - if (cid) { - active_cids = used_active; - have_active_cids = true; - } return true; } -// Repair or synthesize /CIDSet on a CIDFont descriptor so its bitset matches the embedded program. -// Per ISO 19005-1 §6.3.3.3 and ISO 19005-2 §6.2.11.3.3, /CIDSet must identify all CIDs present -// in the embedded font program. If re-subsetting just ran (did_resubset), active_cids contains -// the exact CIDs retained in the new font program. If no re-subset ran, we do not overwrite -// an existing /CIDSet with only drawn CIDs (which would falsely mark unreferenced glyphs as -// absent). -static void repair_cidset_stream(QPDF& pdf, QPDFObjectHandle& font, QPDFObjectHandle& descriptor, - bool did_resubset, bool have_active_cids, - std::set const& active_cids, FontNormalizeState& state) { - if (!did_resubset && !have_active_cids) return; - std::set cids{0}; - bool complete = true; - if (have_active_cids) { - cids.insert(active_cids.begin(), active_cids.end()); - } else { - FnCidScan scan = fn_used_cids_for_font(pdf, font, true, &state); - complete = scan.complete; - cids.insert(scan.cids.begin(), scan.cids.end()); +// CIDs that exist in the embedded CID font program. PDF/A-2 6.2.11.4 test 4 +// requires every mapped CID, including CIDs mapped to GID 0; a bitmap built +// only from drawn CIDs is too short. +static std::set cids_present_in_program(FT_Face face, QPDFObjectHandle& cid_to_gid, + bool cid_identity, + std::map const& gid_to_cid) { + std::set cids; + if (cid_to_gid.isStream()) { + try { + std::shared_ptr data = cid_to_gid.getStreamData(qpdf_dl_generalized); + if (data) { + const size_t entries = data->getSize() / 2; + for (size_t i = 0; i < entries && i <= kFontMaxCid; ++i) + cids.insert(static_cast(i)); + } + } catch (...) { + cids.clear(); + } + return cids; + } + if (face && FT_IS_CID_KEYED(face)) { + for (auto const& [gid, cid] : gid_to_cid) { + (void)gid; + if (cid <= kFontMaxCid) cids.insert(cid); + } + return cids; } - if (!complete) return; + if (face && cid_identity && face->num_glyphs > 0) { + const long max_gid = std::min(face->num_glyphs - 1, kFontMaxCid); + for (long gid = 0; gid <= max_gid; ++gid) cids.insert(static_cast(gid)); + } + return cids; +} + +// Repair or synthesize /CIDSet so its bitset matches the embedded program. +// ISO 19005-2 6.2.11.4 test 4 counts every CID present in the program, +// regardless of whether content draws it. +static void repair_cidset_stream(QPDF& pdf, QPDFObjectHandle& descriptor, FT_Face face, + QPDFObjectHandle& cid_to_gid, bool cid_identity, + std::map const& gid_to_cid, + FontNormalizeState& state) { + std::set cids = cids_present_in_program(face, cid_to_gid, cid_identity, gid_to_cid); + if (cids.empty()) return; + cids.insert(0); const std::string bits = build_cid_set_bits(cids); bool differs = true; @@ -2458,7 +2536,7 @@ static void repair_cidset_stream(QPDF& pdf, QPDFObjectHandle& font, QPDFObjectHa differs = true; } } - if (differs || did_resubset) { + if (differs) { descriptor.replaceKey("/CIDSet", QPDFObjectHandle::newStream(&pdf, bits)); state.changed = true; } @@ -2617,8 +2695,8 @@ static void process_font(QPDF& pdf, QPDFObjectHandle font, bool do_fix_tounicode repair_simple_font_widths(target, face.get(), simple_encoding, simple_any_gid, simple_glyphs, state); } else { - repair_cid_font_widths(font, target, face.get(), cid_to_gid, cid_identity, gid_to_cid, - state); + repair_cid_font_widths(pdf, font, target, face.get(), cid_to_gid, cid_identity, + gid_to_cid, state); } } @@ -2629,15 +2707,12 @@ static void process_font(QPDF& pdf, QPDFObjectHandle font, bool do_fix_tounicode convert_cff_in_sfnt(pdf, target, descriptor, face, cid, subtype_name, state); did_convert = state.type1_converted != converted_before; } - std::set active_cids{0}; - bool have_active_cids = false; - const bool did_resubset = - full && !did_convert && + if (full && !did_convert) { resubset_embedded_sfnt(pdf, font, target, descriptor, stream, data, face_index, face, cid, - cid_to_gid, cid_identity, simple_glyphs, usage, active_cids, - have_active_cids, state); + cid_to_gid, cid_identity, simple_glyphs, usage, state); + } if (cid && full) { - repair_cidset_stream(pdf, font, descriptor, did_resubset, have_active_cids, active_cids, + repair_cidset_stream(pdf, descriptor, face.get(), cid_to_gid, cid_identity, gid_to_cid, state); } } @@ -2875,10 +2950,11 @@ int32_t jpdfium_font_subset(const uint8_t* font_data, int64_t font_len, const ui hb_set_add(unicode_set, codepoints[i]); } - // Set flags - if (retain_gids) { - hb_subset_input_set_flags(input, HB_SUBSET_FLAGS_RETAIN_GIDS); - } + // Keep glyph names and the .notdef outline so Java AWT and PDFBox can + // parse and render the subset (PDFBOX-490). + unsigned int flags = HB_SUBSET_FLAGS_GLYPH_NAMES | HB_SUBSET_FLAGS_NOTDEF_OUTLINE; + if (retain_gids) flags |= HB_SUBSET_FLAGS_RETAIN_GIDS; + hb_subset_input_set_flags(input, flags); // Perform subsetting hb_face_t* subset_face = hb_subset_or_fail(face, input); diff --git a/native/bridge/src/jpdfium_pdfx.cpp b/native/bridge/src/jpdfium_pdfx.cpp index fd43f2582..677ca1402 100644 --- a/native/bridge/src/jpdfium_pdfx.cpp +++ b/native/bridge/src/jpdfium_pdfx.cpp @@ -241,6 +241,27 @@ std::string Name(QPDFObjectHandle h) { return h.isName() ? h.getName() : std::string(); } +// Chromium 445740322: a non-finite or unbounded tiling-pattern step overflows +// the renderer's tile raster dimensions. Clamp to the positive range that PDF +// rasterisers accept. +void ClampPatternSteps(QPDFObjectHandle pattern) { + if (!pattern.isDictionary()) return; + QPDFObjectHandle type = pattern.getKey("/PatternType"); + if (!type.isInteger() || type.getIntValueAsInt() != 1) return; + for (const char* key : {"/XStep", "/YStep"}) { + QPDFObjectHandle value = pattern.getKey(key); + double step = value.isNumber() ? value.getNumericValue() : 1.0; + if (!std::isfinite(step) || step <= 0.0) { + step = 1.0; + } else if (step > 32767.0) { + step = 32767.0; + } + if (!value.isNumber() || value.getNumericValue() != step) { + pattern.replaceKey(key, QPDFObjectHandle::newReal(step, 4)); + } + } +} + ColourSpaceInfo Replaced(Kind kind, const char* device) { ColourSpaceInfo info; info.kind = kind; @@ -1293,6 +1314,7 @@ void Converter::ProcessResources(Resources& res, int depth) { if (patterns.isDictionary()) { for (const std::string& key : patterns.getKeys()) { QPDFObjectHandle pat = patterns.getKey(key); + ClampPatternSteps(pat); if (pat.isStream()) ProcessContentHolder(pat, res.dict, depth + 1); } } diff --git a/native/bridge/src/jpdfium_qpdf.cpp b/native/bridge/src/jpdfium_qpdf.cpp index 82d4771fe..5e06eb5d0 100644 --- a/native/bridge/src/jpdfium_qpdf.cpp +++ b/native/bridge/src/jpdfium_qpdf.cpp @@ -5,6 +5,7 @@ #include #include +#include #include #include #include @@ -62,6 +63,7 @@ using namespace jpdfium_font_encoding; #include "jpdfium_qpdf_writer_lock.h" #include FT_FREETYPE_H +#include FT_CID_H #include FT_ADVANCES_H #include FT_FONT_FORMATS_H #include FT_TRUETYPE_TABLES_H @@ -518,8 +520,100 @@ int32_t encodeBilevelImages(QPDF& pdf) { }); } +// Chromium 445740322: a non-finite or unbounded tiling-pattern step overflows +// the renderer's tile raster dimensions. Clamp to the positive range that PDF +// rasterisers accept. +void clampTilingPatternStep(QPDFObjectHandle pattern) { + if (!pattern.isDictionary()) return; + QPDFObjectHandle type = pattern.getKey("/PatternType"); + if (!type.isInteger() || type.getIntValueAsInt() != 1) return; + for (char const* key : {"/XStep", "/YStep"}) { + QPDFObjectHandle value = pattern.getKey(key); + double step = value.isNumber() ? value.getNumericValue() : 1.0; + if (!std::isfinite(step) || step <= 0.0) { + step = 1.0; + } else if (step > 32767.0) { + step = 32767.0; + } + if (!value.isNumber() || value.getNumericValue() != step) { + pattern.replaceKey(key, QPDFObjectHandle::newReal(step, 4)); + } + } +} + +void clampPatternsInResources(QPDFObjectHandle const& resources, std::set& seen, + int depth) { + if (!resources.isDictionary() || depth > 32) return; + if (resources.isIndirect() && !seen.insert(resources.getObjGen()).second) return; + try { + QPDFObjectHandle patterns = resources.getKey("/Pattern"); + if (patterns.isDictionary()) { + for (auto const& entry : patterns.getDictAsMap()) { + QPDFObjectHandle pattern = entry.second; + clampTilingPatternStep(pattern); + if (pattern.isStream()) + clampPatternsInResources(pattern.getDict().getKey("/Resources"), seen, + depth + 1); + } + } + QPDFObjectHandle xobjects = resources.getKey("/XObject"); + if (xobjects.isDictionary()) { + for (auto const& entry : xobjects.getDictAsMap()) { + QPDFObjectHandle xobject = entry.second; + if (!xobject.isStream()) continue; + if (xobject.isIndirect() && !seen.insert(xobject.getObjGen()).second) continue; + clampPatternsInResources(xobject.getDict().getKey("/Resources"), seen, depth + 1); + } + } + QPDFObjectHandle fonts = resources.getKey("/Font"); + if (fonts.isDictionary()) { + for (auto const& entry : fonts.getDictAsMap()) { + QPDFObjectHandle font = entry.second; + if (!font.isDictionary() || !font.getKey("/Subtype").isNameAndEquals("/Type3")) + continue; + clampPatternsInResources(font.getKey("/Resources"), seen, depth + 1); + } + } + } catch (...) { + // A malformed resource tree must not abort optimization. + } +} + +void clampPatternSteps(QPDF& pdf) { + std::set seen; + try { + QPDFPageDocumentHelper helper{pdf}; + for (auto& page : helper.getAllPages()) { + clampPatternsInResources(page.getAttribute("/Resources", false), seen, 0); + QPDFObjectHandle annots = page.getObjectHandle().getKey("/Annots"); + if (!annots.isArray()) continue; + for (auto& annot : annots.getArrayAsVector()) { + if (!annot.isDictionary()) continue; + QPDFObjectHandle ap = annot.getKey("/AP"); + if (!ap.isDictionary()) continue; + for (char const* key : {"/N", "/R", "/D"}) { + QPDFObjectHandle appearance = ap.getKey(key); + if (appearance.isStream()) { + clampPatternsInResources(appearance.getDict().getKey("/Resources"), seen, + 0); + } else if (appearance.isDictionary()) { + for (auto const& state : appearance.getDictAsMap()) { + if (state.second.isStream()) + clampPatternsInResources( + state.second.getDict().getKey("/Resources"), seen, 0); + } + } + } + } + } + } catch (...) { + // Pattern repair is best-effort; the writer still emits the document. + } +} + int subsetEmbeddedFonts(QPDF& qpdf); int32_t applyDocumentOptions(QPDF& pdf, const OptimizeOptions& options) { + clampPatternSteps(pdf); if (options.flags & JPDFIUM_QPDF_QDF) { if (options.flags & JPDFIUM_QPDF_LINEARIZE) { throw std::runtime_error("QDF mode cannot be combined with linearization"); @@ -1792,11 +1886,14 @@ void ensureMicrosoftUnicodeCmap(std::string& sfnt) { } } - if (!cmapEntryOff || cmapOffset + 4 > sfnt.size() || cmapOffset + cmapLength > sfnt.size()) + // Compare against remaining size instead of adding the (attacker-controlled) + // offsets, which would wrap around before the bounds check. + if (!cmapEntryOff || cmapOffset > sfnt.size() || sfnt.size() - cmapOffset < 4 || + cmapLength > sfnt.size() - cmapOffset) return; - uint16_t numSubtables = read16(cmapOffset + 2); - if (cmapOffset + 4 + static_cast(numSubtables) * 8 > sfnt.size()) return; + uint16_t numSubtables = read16(static_cast(cmapOffset) + 2); + if (cmapLength < 4 || static_cast(numSubtables) * 8 > cmapLength - 4) return; bool hasMsUnicode = false; size_t unicodeSubtableOff = 0; @@ -1810,7 +1907,10 @@ void ensureMicrosoftUnicodeCmap(std::string& sfnt) { break; } if (plat == 0 && (enc == 3 || enc == 4 || enc == 0)) { - unicodeSubtableOff = subOff; + uint32_t subtableDataOffset = read32(subOff + 4); + if (static_cast(cmapOffset) + subtableDataOffset + 2 <= sfnt.size() && + read16(static_cast(cmapOffset) + subtableDataOffset) == 4) + unicodeSubtableOff = subOff; } } @@ -1835,7 +1935,7 @@ void ensureMicrosoftUnicodeCmap(std::string& sfnt) { write32(cmapEntryOff + 4, cmapSum); // Recalculate head checkSumAdjustment if head table is present - if (headOffset && headOffset + 12 <= sfnt.size()) { + if (headOffset && headOffset <= sfnt.size() && sfnt.size() - headOffset >= 12) { write32(headOffset + 8, 0); uint32_t fontSum = 0; for (size_t i = 0; i < sfnt.size(); i += 4) { @@ -1934,18 +2034,26 @@ FT_UInt glyphForCode(FT_Face face, int code, bool symbolic, SimpleEncoding const return 0; } -void addWidths(QPDFObjectHandle font, FT_Face face, bool symbolic) { +bool addWidths(QPDFObjectHandle font, FT_Face face, bool symbolic) { auto enc = parseEncoding(font); auto widths = QPDFObjectHandle::newArray(); + bool any_positive = false; for (int code = 0; code < 256; ++code) { - FT_Fixed advance = 0; - FT_Get_Advance(face, glyphForCode(face, code, symbolic, enc), FT_LOAD_NO_SCALE, &advance); - widths.appendItem(QPDFObjectHandle::newInteger( - advance * 1000 / (face->units_per_EM ? face->units_per_EM : 1000))); + const FT_UInt gid = glyphForCode(face, code, symbolic, enc); + long w = 0; + if (gid != 0 && face->units_per_EM != 0) { + FT_Fixed advance = 0; + FT_Get_Advance(face, gid, FT_LOAD_NO_SCALE, &advance); + w = advance * 1000 / face->units_per_EM; + } + if (w > 0) any_positive = true; + widths.appendItem(QPDFObjectHandle::newInteger(w)); } + if (!any_positive) return false; font.replaceKey("/FirstChar", QPDFObjectHandle::newInteger(0)); font.replaceKey("/LastChar", QPDFObjectHandle::newInteger(255)); font.replaceKey("/Widths", widths); + return true; } bool reachesSameGlyphs(FT_Library lib, std::string const& subset, FT_Face original, @@ -2015,28 +2123,39 @@ std::map unicodeByGlyph(FT_Face face, bool symbolic) { void setToUnicode(QPDF& qpdf, QPDFObjectHandle font, std::map const& codes, bool twoByte) { if (codes.empty() || font.hasKey("/ToUnicode")) return; + std::vector> valid; + valid.reserve(codes.size()); + for (auto [code, u] : codes) { + if (u == 0 || u == 0xFEFF || u == 0xFFFE || (u >= 0xD800 && u <= 0xDFFF) || u > 0x10FFFF) + continue; + valid.emplace_back(code, u); + } + if (valid.empty()) return; + std::string cmap = std::string( "/CIDInit /ProcSet findresource begin 12 dict begin begincmap\n" "/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> " "def\n/CMapName /Adobe-Identity-UCS def /CMapType 2 def\n") + (twoByte ? "1 begincodespacerange <0000> endcodespacerange\n" : "1 begincodespacerange <00> endcodespacerange\n"); - std::string entries; - size_t count = 0; - for (auto [code, u] : codes) { - char entry[40]; - int n = std::snprintf(entry, sizeof entry, twoByte ? "<%04X> " : "<%02X> ", code); - if (u > 0xFFFF) - std::snprintf(entry + n, sizeof entry - n, "<%04lX%04lX>\n", - 0xD800 + ((u - 0x10000) >> 10), 0xDC00 + ((u - 0x10000) & 0x3FF)); - else - std::snprintf(entry + n, sizeof entry - n, "<%04lX>\n", u); - entries += entry; - if (++count % 100 == 0 || count == codes.size()) { - cmap += - std::to_string((count - 1) % 100 + 1) + " beginbfchar\n" + entries + "endbfchar\n"; - entries.clear(); - } + size_t remaining = valid.size(); + auto it = valid.begin(); + while (remaining > 0) { + size_t chunk = remaining > 100 ? 100 : remaining; + cmap += std::to_string(chunk) + " beginbfchar\n"; + for (size_t i = 0; i < chunk; ++i, ++it) { + char entry[40]; + int n = std::snprintf(entry, sizeof entry, twoByte ? "<%04X> " : "<%02X> ", it->first); + FT_ULong u = it->second; + if (u > 0xFFFF) + std::snprintf(entry + n, sizeof entry - n, "<%04lX%04lX>\n", + 0xD800 + ((u - 0x10000) >> 10), 0xDC00 + ((u - 0x10000) & 0x3FF)); + else + std::snprintf(entry + n, sizeof entry - n, "<%04lX>\n", u); + cmap += entry; + } + cmap += "endbfchar\n"; + remaining -= chunk; } cmap += "endcmap CMapName currentdict /CMap defineresource pop end end\n"; font.replaceKey("/ToUnicode", QPDFObjectHandle::newStream(&qpdf, cmap)); @@ -2294,7 +2413,7 @@ inline bool isPdfDelimiter(unsigned char c) { } struct ContentLexer { - std::string const& data; + std::string_view data; size_t pos = 0; bool malformed = false; int array_depth = 0; @@ -2371,18 +2490,31 @@ struct ContentLexer { bool hex(std::string& out) { if (pos >= data.size() || data[pos] != '<') return false; ++pos; - std::string digits; + int first_nibble = -1; while (pos < data.size() && data[pos] != '>') { unsigned char c = static_cast(data[pos++]); if (isPdfWhitespace(c)) continue; - if (!std::isxdigit(c)) return false; - digits += static_cast(c); + int val = -1; + if (c >= '0' && c <= '9') { + val = c - '0'; + } else if (c >= 'a' && c <= 'f') { + val = c - 'a' + 10; + } else if (c >= 'A' && c <= 'F') { + val = c - 'A' + 10; + } else { + return false; + } + if (first_nibble < 0) { + first_nibble = val; + } else { + out += static_cast((first_nibble << 4) | val); + first_nibble = -1; + } } if (pos >= data.size()) return false; ++pos; - if (digits.size() % 2) digits += '0'; - for (size_t i = 0; i < digits.size(); i += 2) { - out += static_cast(std::strtoul(digits.substr(i, 2).c_str(), nullptr, 16)); + if (first_nibble >= 0) { + out += static_cast(first_nibble << 4); } return true; } @@ -2390,15 +2522,21 @@ struct ContentLexer { bool name(std::string& out) { if (pos >= data.size() || data[pos] != '/') return false; ++pos; + auto hex_val = [](char ch) -> int { + if (ch >= '0' && ch <= '9') return ch - '0'; + if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10; + if (ch >= 'A' && ch <= 'F') return ch - 'A' + 10; + return 0; + }; while (pos < data.size()) { unsigned char c = static_cast(data[pos]); if (isPdfWhitespace(c) || isPdfDelimiter(c)) { break; } - if (c == '#' && pos + 2 < data.size() && std::isxdigit(data[pos + 1]) && - std::isxdigit(data[pos + 2])) { - out += - static_cast(std::strtoul(data.substr(pos + 1, 2).c_str(), nullptr, 16)); + if (c == '#' && pos + 2 < data.size() && + std::isxdigit(static_cast(data[pos + 1])) && + std::isxdigit(static_cast(data[pos + 2]))) { + out += static_cast((hex_val(data[pos + 1]) << 4) | hex_val(data[pos + 2])); pos += 3; } else { out += static_cast(c); @@ -2524,7 +2662,7 @@ struct ContentLexer { ++pos; } if (pos == start) return false; - std::string value = data.substr(start, pos - start); + std::string value(data.substr(start, pos - start)); bool numeric = value.find_first_not_of("0123456789+-.") == std::string::npos; if (numeric) { out.word = false; @@ -2538,22 +2676,23 @@ struct ContentLexer { } void skipInlineImage() { - // BI ... ID EI + // BI ... ID EI. Image data may abut EI with no separating + // whitespace, and EI may be followed by a delimiter instead of + // whitespace, so validate only the trailing boundary. ContentToken token; while (next(token)) { if (token.word && token.text == "ID") { if (pos < data.size() && isPdfWhitespace(static_cast(data[pos]))) ++pos; - while (pos + 2 < data.size()) { - // The EI marker is a token of its own: whitespace on both sides. - // Accepting \" EI[\" would end the image at bytes that are still - // image data and desynchronize the rest of the stream. - if (isPdfWhitespace(static_cast(data[pos])) && - data[pos + 1] == 'E' && data[pos + 2] == 'I' && - (pos + 3 >= data.size() || - isPdfWhitespace(static_cast(data[pos + 3])))) { - pos += 3; - return; + while (pos + 1 < data.size()) { + if (data[pos] == 'E' && data[pos + 1] == 'I') { + const size_t after = pos + 2; + if (after >= data.size() || + isPdfWhitespace(static_cast(data[after])) || + isPdfDelimiter(static_cast(data[after]))) { + pos = after; + return; + } } ++pos; } @@ -2599,7 +2738,7 @@ void scanResourceStreams(QPDFObjectHandle const& resources, QPDFObjectHandle con std::set>& seenStreams, int& budget, bool& complete, bool twoByte = true); -void scanContentStream(std::string const& data, QPDFObjectHandle const& resources, +void scanContentStream(std::string_view data, QPDFObjectHandle const& resources, QPDFObjectHandle const& target, std::set& cids, int depth, std::set>& seenStreams, int& budget, bool& complete, bool twoByte = true, bool initialSelected = false) { @@ -2637,6 +2776,22 @@ void scanContentStream(std::string const& data, QPDFObjectHandle const& resource selected = sameFont(font, target); } } + } else if (op == "gs" && !operands.empty() && + operands.back().kind == ContentOperand::Kind::Name) { + if (resources.isDictionary()) { + auto extgstate = resources.getKey("/ExtGState"); + if (extgstate.isDictionary()) { + auto gsDict = extgstate.getKey("/" + operands.back().text); + if (gsDict.isDictionary() && gsDict.hasKey("/Font")) { + auto fontEntry = gsDict.getKey("/Font"); + if (fontEntry.isArray() && fontEntry.getArrayNItems() > 0) { + selected = sameFont(fontEntry.getArrayItem(0), target); + } else { + complete = false; + } + } + } + } } else if (op == "Tj" && !operands.empty() && operands.back().kind == ContentOperand::Kind::String) { if (selected) collectStringCids(operands.back().text, cids, complete, twoByte); @@ -2668,7 +2823,7 @@ void scanContentStream(std::string const& data, QPDFObjectHandle const& resource try { auto streamData = form.getStreamData(qpdf_dl_generalized); if (streamData && streamData->getSize()) { - std::string content( + std::string_view content( reinterpret_cast(streamData->getBuffer()), streamData->getSize()); scanContentStream(content, formResources, target, cids, @@ -2792,8 +2947,8 @@ CidScanResult usedCidsForFont(QPDF& qpdf, QPDFObjectHandle const& target, bool t try { auto data = stream.getStreamData(qpdf_dl_generalized); if (!data || !data->getSize()) return; - std::string content(reinterpret_cast(data->getBuffer()), - data->getSize()); + std::string_view content(reinterpret_cast(data->getBuffer()), + data->getSize()); scanContentStream(content, streamResources, target, result.cids, 0, seenStreams, budget, result.complete, twoByte); scanResourceStreams(streamResources, target, result.cids, 0, seenStreams, @@ -2969,16 +3124,14 @@ void pinTrueTypeMapping(QPDF& qpdf, QPDFObjectHandle font, FT_Face face, bool sy if ((code >= 0x20 || differs) && (differs || (u != 0 && u != baseEncodingUnicode(BaseEncoding::WinAnsi, code)))) { char name[64] = ""; - if (differs) { - if (const char* agl = adobeGlyphNameForUnicode(static_cast(u))) { - std::snprintf(name, sizeof name, "%s", agl); - } else if (unicodeForGlyphName(enc.differences.at(code))) { - std::snprintf(name, sizeof name, "%s", enc.differences.at(code).c_str()); - } else { - std::snprintf(name, sizeof name, ".notdef"); - } - } else if (const char* agl = adobeGlyphNameForUnicode(static_cast(u))) { + if (const char* agl = adobeGlyphNameForUnicode(static_cast(u))) { std::snprintf(name, sizeof name, "%s", agl); + } else if (differs && unicodeForGlyphName(enc.differences.at(code))) { + std::snprintf(name, sizeof name, "%s", enc.differences.at(code).c_str()); + } else if (u > 0 && u <= 0xFFFF) { + std::snprintf(name, sizeof name, "uni%04lX", u); + } else if (differs) { + std::snprintf(name, sizeof name, ".notdef"); } if (name[0]) { if (code != lastCode + 1) { @@ -3016,6 +3169,40 @@ void updateCidSet(QPDF& qpdf, QPDFObjectHandle descriptor, std::set co descriptor.replaceKey("/CIDSet", QPDFObjectHandle::newStream(&qpdf, bits)); } +// CIDs that exist in the embedded CID font program. PDF/A-2 6.2.11.4 test 4 +// requires the CIDSet to describe every one, including CIDs mapped to GID 0; +// describing only the CIDs drawn by content leaves the bitmap too short. +std::set cidsPresentInProgram(QPDFObjectHandle const& target, FT_Face face) { + std::set cids; + auto map = target.getKey("/CIDToGIDMap"); + if (map.isStream()) { + try { + std::shared_ptr data = map.getStreamData(qpdf_dl_generalized); + if (data) { + const size_t entries = data->getSize() / 2; + for (size_t i = 0; i < entries && i <= kMaxCid; ++i) + cids.insert(static_cast(i)); + } + } catch (...) { + cids.clear(); + } + return cids; + } + if (face && FT_IS_CID_KEYED(face)) { + for (FT_UInt gid = 0; gid < static_cast(face->num_glyphs); ++gid) { + FT_UInt cid = 0; + if (FT_Get_CID_From_Glyph_Index(face, gid, &cid) == 0 && cid <= kMaxCid) + cids.insert(static_cast(cid)); + } + return cids; + } + if (face && face->num_glyphs > 0) { + const long max_gid = std::min(face->num_glyphs - 1, kMaxCid); + for (long gid = 0; gid <= max_gid; ++gid) cids.insert(static_cast(gid)); + } + return cids; +} + bool hasSubsetTag(std::string const& name) { if (name.size() <= 7 || name[6] != '+') return false; return std::all_of(name.begin(), name.begin() + 6, @@ -3172,6 +3359,18 @@ bool subsetEmbeddedSimpleFont(QPDF& qpdf, FT_Library lib, QPDFObjectHandle& font for (char const* key : {"/FontFile", "/FontFile2", "/FontFile3"}) descriptor.removeKey(key); descriptor.replaceKey(program.kind == ProgramKind::TrueType ? "/FontFile2" : "/FontFile3", makeProgramStream(qpdf, program, program.kind, false, subset)); + std::string charsetStr; + char glyphName[256]; + for (FT_UInt gid : targetGlyphs) { + if (FT_HAS_GLYPH_NAMES(program.face) && + FT_Get_Glyph_Name(program.face, gid, glyphName, sizeof(glyphName)) == 0) { + charsetStr += "/"; + charsetStr += glyphName; + } + } + if (!charsetStr.empty()) { + descriptor.replaceKey("/CharSet", QPDFObjectHandle::newString(charsetStr)); + } return true; } @@ -3284,13 +3483,48 @@ int subsetEmbeddedFonts(QPDF& qpdf) { for (auto& child : children.getArrayAsVector()) pendingFields.push_back(child); } } - if (acroForm.isDictionary()) collectFromResources(acroForm.getKey("/DR")); + // Fonts reachable from /AcroForm /DR may be used for interactive text entry + // in form fields that never reference them from a page /Resources. They are + // never subset candidates: collect them separately so their descriptors and + // programs can be marked as shared (see below) and excluded from uniqueFonts. + std::vector formFonts; + std::set visitedFormResources; + std::vector pendingFormResources{ + acroForm.isDictionary() ? acroForm.getKey("/DR") : QPDFObjectHandle()}; + while (!pendingFormResources.empty()) { + QPDFObjectHandle res = pendingFormResources.back(); + pendingFormResources.pop_back(); + if (!res.isDictionary()) continue; + if (res.isIndirect() && !visitedFormResources.insert(res.getObjGen()).second) continue; + auto fontDict = res.getKey("/Font"); + if (fontDict.isDictionary()) { + for (auto const& [name, font] : fontDict.getDictAsMap()) { + if (!font.isDictionary()) continue; + formFonts.push_back(font); + auto descendants = font.getKey("/DescendantFonts"); + if (!descendants.isArray()) continue; + for (auto& descendant : descendants.getArrayAsVector()) + if (descendant.isDictionary()) formFonts.push_back(descendant); + } + } + auto xobjects = res.getKey("/XObject"); + if (xobjects.isDictionary()) { + for (auto const& [name, xobject] : xobjects.getDictAsMap()) { + if (!xobject.isStream()) continue; + pendingFormResources.push_back(xobject.getDict().getKey("/Resources")); + } + } + } + std::set formFontObjects; + for (auto const& font : formFonts) + if (font.isIndirect()) formFontObjects.insert(font.getObjGen()); // Deduplicate indirect font dictionaries and count shared descriptors/streams. std::set seenFonts; std::vector uniqueFonts; for (auto const& font : fonts) { if (font.isIndirect() && !seenFonts.insert(font.getObjGen()).second) continue; + if (font.isIndirect() && formFontObjects.contains(font.getObjGen())) continue; uniqueFonts.push_back(font); } @@ -3312,6 +3546,20 @@ int subsetEmbeddedFonts(QPDF& qpdf) { if (stream.isIndirect()) ++streamUseCount[stream.getObjGen()]; } + // Sentinel counts keep AcroForm /DR fonts, descriptors and programs out of + // subsetting even when a page /Resources also references them. Subsetting + // form fonts would break interactive entry for characters not yet drawn. + for (auto const& font : formFonts) { + auto descriptor = font.getKey("/FontDescriptor"); + if (!descriptor.isDictionary()) continue; + if (descriptor.isIndirect()) descriptorUseCount[descriptor.getObjGen()] = 999999; + for (char const* key : {"/FontFile", "/FontFile2", "/FontFile3"}) { + auto stream = descriptor.getKey(key); + if (stream.isStream() && stream.isIndirect()) + streamUseCount[stream.getObjGen()] = 999999; + } + } + FT_Library lib = nullptr; struct LibraryGuard { FT_Library& library; @@ -3323,8 +3571,12 @@ int subsetEmbeddedFonts(QPDF& qpdf) { int subsetCount = 0; for (auto& font : uniqueFonts) { - if (subsetEmbeddedFontResource(qpdf, lib, font, descriptorUseCount, streamUseCount)) - ++subsetCount; + try { + if (subsetEmbeddedFontResource(qpdf, lib, font, descriptorUseCount, streamUseCount)) + ++subsetCount; + } catch (...) { + // Isolate failure to this specific font and continue + } } return subsetCount; } @@ -3527,6 +3779,10 @@ EmbedFontsResult embedFonts(std::function const& load, targetName.find("Dingbats") != std::string::npos); bool symbolic = !hasEncoding && (isSymbolName || (flags.isInteger() && (flags.getIntValue() & 4) != 0)); + if (!cid && !target.getKey("/Widths").isArray() && + !addWidths(target, program.face, symbolic)) { + continue; + } target.replaceKey("/Type", QPDFObjectHandle::newName("/Font")); if (cid) font.replaceKey("/Type", QPDFObjectHandle::newName("/Font")); if (!descriptor.isDictionary()) { @@ -3580,24 +3836,27 @@ EmbedFontsResult embedFonts(std::function const& load, target.replaceKey("/CIDToGIDMap", QPDFObjectHandle::newName("/Identity")); if (!cid && glyf) pinTrueTypeMapping(*qpdf, target, program.face, symbolic); } - if (!cid && !target.getKey("/Widths").isArray()) - addWidths(target, program.face, symbolic); // OTTO/CFF can be carried by a pre-1.6 PDF as /FontFile3 - // /Subtype /Type1C instead of requiring /Subtype /OpenType and a - // PDF 1.6 bump. - if (kind == ProgramKind::OpenType && !cid && !wrapped && - qpdf->getPDFVersion() < std::string("1.6") && FT_HAS_GLYPH_NAMES(program.face)) { + // /Subtype /Type1C or /CIDFontType0C instead of requiring /Subtype /OpenType + // and a PDF 1.6 bump (which would violate PDF/A-1). + if (kind == ProgramKind::OpenType && !wrapped && + qpdf->getPDFVersion() < std::string("1.6")) { std::string cff = extractCffTable(lib, subset.empty() ? program.bytes : subset); if (cff.empty() && !subset.empty()) { cff = extractCffTable(lib, program.bytes); if (!cff.empty()) glyphs.clear(); } if (!cff.empty()) { - auto enc = parseEncoding(target); - if (reachesSameGlyphs(lib, cff, program.face, enc, symbolic)) { + if (cid) { kind = ProgramKind::BareCff; subset = std::move(cff); - pinTrueTypeMapping(*qpdf, target, program.face, symbolic); + } else { + auto enc = parseEncoding(target); + if (reachesSameGlyphs(lib, cff, program.face, enc, symbolic)) { + kind = ProgramKind::BareCff; + subset = std::move(cff); + pinTrueTypeMapping(*qpdf, target, program.face, symbolic); + } } } } @@ -3673,54 +3932,36 @@ EmbedFontsResult embedFonts(std::function const& load, : "/FontFile3", stream); if (cid) { - std::set activeCids{0}; - bool cidSetComplete = true; - if (!remappedGlyph.empty()) { - for (auto const& [c, gid] : remappedGlyph) { - (void)gid; - activeCids.insert(c); - } - } else if (!cidGlyph.empty()) { - for (auto const& [c, gid] : cidGlyph) { - (void)gid; - activeCids.insert(c); - } - } else if (identityCidMap) { - long maxGlyph = std::min(program.face->num_glyphs - 1, kMaxCid); - for (long g = 0; g <= maxGlyph; ++g) - activeCids.insert(static_cast(g)); - } else { - // A non-Identity /CIDToGIDMap names CIDs directly. Glyph - // indices are not CIDs, so enumerate the retained map. - cidSetComplete = false; - auto retained = target.getKey("/CIDToGIDMap"); - if (retained.isStream()) { - try { - auto map = retained.getStreamData(qpdf_dl_generalized); - if (map && (map->getSize() % 2) == 0) { - auto const* bytes = - reinterpret_cast(map->getBuffer()); - for (size_t candidate = 0; - candidate < map->getSize() / 2 && candidate <= kMaxCid; - ++candidate) { - uint32_t gid = (uint32_t(bytes[2 * candidate]) << 8) | - bytes[2 * candidate + 1]; - if (gid < static_cast(program.face->num_glyphs)) - activeCids.insert(static_cast(candidate)); - } - cidSetComplete = true; - } - } catch (...) { + std::set activeCids = cidsPresentInProgram(target, program.face); + if (activeCids.empty()) { + // The installed map could not be read back. Derive the bitmap + // from the mapping this rewrite actually wrote, or leave the + // CIDSet absent when the mapping is unknown. + activeCids.insert(0); + bool cidSetComplete = true; + if (!remappedGlyph.empty()) { + for (auto const& [c, gid] : remappedGlyph) { + (void)gid; + activeCids.insert(c); + } + } else if (!cidGlyph.empty()) { + for (auto const& [c, gid] : cidGlyph) { + (void)gid; + activeCids.insert(c); } + } else if (identityCidMap) { + long maxGlyph = std::min(program.face->num_glyphs - 1, kMaxCid); + for (long g = 0; g <= maxGlyph; ++g) + activeCids.insert(static_cast(g)); + } else { + cidSetComplete = false; + } + if (!cidSetComplete) { + activeCids.clear(); + descriptor.removeKey("/CIDSet"); } } - if (cidSetComplete) { - updateCidSet(*qpdf, descriptor, activeCids); - } else { - // A wrong CIDSet is worse than a missing one: validators - // would see a bitmap that contradicts the installed program. - descriptor.removeKey("/CIDSet"); - } + if (!activeCids.empty()) updateCidSet(*qpdf, descriptor, activeCids); } openType |= kind == ProgramKind::OpenType; ++embedded; @@ -5020,14 +5261,6 @@ JPDFIUM_EXPORT int32_t jpdfium_qpdf_copy_encryption_file(const char*, const char return -1; } -JPDFIUM_EXPORT int32_t jpdfium_qpdf_subset_fonts(const uint8_t*, int64_t, uint8_t** output, - int64_t* outputLen, int32_t* fontsSubset) { - if (output) *output = nullptr; - if (outputLen) *outputLen = 0; - if (fontsSubset) *fontsSubset = 0; - return -1; -} - } // extern "C" #endif // JPDFIUM_HAS_QPDF