Commit Graph
22500 Commits
Author SHA1 Message Date
Behdad EsfahbodandClaude Opus 4.8 76655660b3 [layout] Charge the skip, skipped-record and ligature walks
The per-pass `len / 16` charge does not bound per-position inner work:
the skipping iterator's rescans over default-ignorables, apply_lookup's
walk over a rule's skipped LookupRecords, and match_input /
ligate_input's walk over a ligature's components and marks. Each is a
CPU-DoS a crafted font triggers under the default max_ops.

Charge each on its work path only, so honest shaping is unaffected:
skipping_iterator_t::next/prev charge one op per skip (a first-try
match charges nothing); apply_lookup charges each skipped record;
match_input charges the ligbase backward walk and ligate_input the
mark re-adjust walk, once each.

Reproducers drop from 20 s / 6.8 s / 3.8 s to 0.05 s / 0.003 s /
0.02 s; in-house and aots shaping tests pass with no output change
(the pre-existing text-rendering-tests failures are unchanged).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 21:45:46 -06:00
Behdad EsfahbodandClaude Opus 4.8 bbdde752f6 [test] Force the ot shaper in the layout budget tests
test_ot_layout_gpos_mark_base_rescan_budget calls hb_shape() with no
shaper forced, then asserts an OT-specific max_ops trip via
hb_buffer_allocation_successful().  Under the HarfRust shaper
(HB_SHAPER_LIST=harfrust, as the rust CI job re-runs the api suite)
it aborts, because harfrust shapes independently and never reaches
the C-side max_ops paths it tests.

Shape with hb_shape_full(..., {"ot", NULL}) so it exercises the OT
shaper regardless of the configured shaper list, as
test_shape_lookup_budget already does.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 19:23:24 -06:00
Behdad EsfahbodandClaude Opus 4.8 9af27609af [depend] Bound lookup recursion depth and whole-table path count
hb_depend_context_t::recurse() only refused to re-enter a lookup already
on the call stack, so a chain of distinct Context lookups recursed once
per lookup (stack overflow around 8600 lookups on an 8 MB stack) and
lookups invoking each other in every order were walked once per ordering
(a factorial number of interned paths, gigabytes of memory).

recurse() is where every sibling context (closure, closure-lookups,
apply) enforces HB_MAX_NESTING_LEVEL, so add the same nesting_level_left
guard here; shaping never applies lookups nested deeper, so no edge the
closure can reach is lost (a chain's final edge drops at exactly the
depth the closure stops, 65->66).  Bound the number of distinct
recursion paths with a counter kept over the whole table (not cleared by
reset_recurse_cache, which runs per top-level lookup) against a new
HB_MAX_DEPEND_RECURSE_PATHS limit in hb-limits.hh, so it can be tuned
on its own; exceeding it fails the build so
hb_subset_depend_from_face_or_fail() returns nullptr instead of emitting
a truncated graph.  The largest whole-table path count among the test
fonts is 744 (NotoNastaliqUrdu-Bold), so 35000 leaves ample headroom.

Builds only with experimental_api.  Adds a small permutation-font fuzz
seed and a test-ot-depend test; test-ot-depend, the depend fuzzer and
the depend-closure-parity tests pass.  Related to PR #6185.

Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-N28924W8.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 19:23:24 -06:00
Behdad EsfahbodandClaude Opus 4.8 06e9e32980 [depend] Release oversized recursion maps in reset_recurse_cache()
reset_recurse_cache() runs once per top-level lookup and cleared
completed_recursions and recurse_path_to_index with hb_hashmap_t::clear(),
which walks the whole table and keeps its allocated capacity.  A single
lookup that grew these maps large therefore made every later top-level
lookup pay to walk that full capacity, however little it recursed,
giving a font with one busy lookup followed by many trivial ones a CPU
DoS in hb_subset_depend_from_face_or_fail().

Add clear_or_release(): when a map is large but was left mostly empty by
the lookup that just finished, swap in fresh storage before clearing, so
later lookups start from a small table.  Adds a fuzzer regression font.

Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-PNJPHF76.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 19:23:24 -06:00
Behdad EsfahbodandClaude Opus 4.8 d6d66b9422 [GPOS] Charge propagate_attachment_offsets() base-to-mark walk to max_ops
propagate_attachment_offsets() turns a mark's stored attachment into an
offset by summing the advances of every glyph between the mark and its
base.  That distance can be up to 32767 glyphs (the range of
attach_chain), and position_finish_offsets() runs the pass once per
attached glyph, so the total work is the sum of all mark-to-base
distances and is not bounded by the font; it was never charged to
buffer->max_ops.  Attacker-chosen text over a cooperating font (or the
kerx path) could thus make hb_shape() spend several times the budgeted
CPU.

Thread the buffer into propagate_attachment_offsets() and charge the
base-to-mark distance to buffer->max_ops before the summation loops,
failing the shape when the budget runs out (the same budget the
unsafe_to_break walk over this range already uses).  Normal text, whose
marks sit next to their base, pays a negligible amount.

Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-4JGOSACZ.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 19:23:24 -06:00
Behdad EsfahbodandClaude Opus 4.8 efe5821d7a [GPOS] Charge out-of-order MarkBasePos/MarkLigPos base rescans to max_ops
MarkBasePosFormat1 and MarkLigPosFormat1 find a mark's base with a
cache (c->last_base / last_base_until) that is only amortized while
buffer->idx moves forward.  A (Chain)Context lookup that recurses into
the mark lookup at input positions out of order resets the cache, so
each application rescans the glyphs from last_base_until to idx from
scratch; on a long run of marks with no base this is quadratic and was
uncharged.

Charge the rescanned span (idx - j) to buffer->max_ops after the
backward search in both lookups, failing the shape when the budget runs
out.  A real mark-heavy font pays a negligible amount.  Adds a
regression test shaping a Context lookup that recurses to MarkBasePos
at positions 1,0,1,0,...

Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-FJEXEDJ4.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 19:23:24 -06:00
Behdad EsfahbodandClaude Opus 4.8 89fd1403da [layout] Charge each GSUB/GPOS lookup pass to max_ops
Lookups can share subtables, features can share lookups, and each
shaping stage applies its lookups anew, so the number of passes over
the buffer is not bounded by the font size.  An earlier lookup can
also grow the buffer far beyond the text the budget was sized from:
a font that grows one character into a long buffer and then walks it
with thousands of lookups (as in harfbuzz/harfrust#571) made hb_shape()
spend CPU out of proportion to the text, and none of it was charged
to buffer->max_ops.

Charge each pass in apply_string() len / 16 for walking the buffer,
even if it applies at no glyph (skipping a glyph is cheap, hence the
division; applying at one is charged only through the buffer
operations and nested lookups it does), and stop the stage loop in
hb_ot_map_t::apply() once the buffer has failed.  Nothing is charged
in the matching hot loops (skipping iterator, RuleSet, ChainRuleSet,
LigatureSet): charging there cost real fonts most of the budget in
HarfRust (Gulzar spent about half of max_ops on ordinary Urdu prose,
Noto Sans Duployan ran out on its own sample text).  Aliased rules and
ligatures stay bounded by the sanitizer, including the ChainRule array
charge.  Matches harfbuzz/harfrust#601.

test_shape_lookup_budget grows one 'a' to 65025 glyphs before applying
aliased lookups, and checks that the pass charge stops the shape.

With the font from harfbuzz/harfrust#571 (one 'A' grown to 30,000
glyphs, then 2,000 lookups), hb_shape() takes about 10 ms instead of
0.6 s, stopping after about 35 passes with the glyphs kept.  Gulzar
and Noto Nastaliq Urdu spend under 0.5% of max_ops on Urdu and Persian
prose.  Noto Sans Duployan spends up to 45% on its sample text, as on
main: nearly all of it is the _infos_set_glyph_flags() charge from
#5522; the per-pass charge adds about 5%.

Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-6A9E6OEX.
Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-K2T2LOJH.
Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-DVG5XAU0.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 19:23:24 -06:00
Behdad EsfahbodandClaude Opus 4.8 25bf796716 [GPOS] Charge zero-size ValueRecord arrays to the sanitizer op budget
When a ValueFormat is empty its records take no bytes, so
ValueFormat::sanitize_values() and PairPosFormat2::sanitize() pass
check_range() without charging max_ops for the records, while later
code (the subsetter, variation-index collection) still walks count
records.  A tiny table can thus declare a huge valueCount / class
matrix and cost the subsetter CPU out of proportion to its size.

Charge count ops when the record size / stride is zero, following the
918193ebf precedent.  Adds two fuzzer regression fonts.

Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-HFGOLC64.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 19:23:24 -06:00
Behdad EsfahbodandClaude Opus 4.8 1a3a6d2446 [sanitize] Charge ChainRule backtrack/input/lookahead arrays to max_ops
ChainRule::sanitize() checks the length of each of its three arrays but
only sanitizes the trailing LookupRecord array, so it never charges
max_ops for the bytes it skipped over.  A table with many ChainRuleSet
offsets all pointing at one large ChainRule could therefore be
sanitized in time proportional to offsets x rule size, escaping the
sanitizer's work bound (restoring the accounting removed by 385896ff6).

Charge the skipped span (from this to the LookupRecord array) to
check_ops before sanitizing the records.  Adds a fuzzer regression
font.

Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-EFNNHRHV.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 19:23:24 -06:00
Behdad Esfahbod 0a3f84c495 Merge pull request #6559 from harfbuzz/scanner/layout-opt
[layout] Algorithmic fast-paths for GSUB/GPOS/GDEF closure, subset and shaping
2026-11-10 19:23:20 -06:00
Behdad EsfahbodandClaude Opus 4.8 8b0e9da51f [layout] Collect intersected ClassDef classes once per ContextFormat2 visit
The class-based (Chain)Context closure and depend paths called
ClassDef::intersects_class() for every rule-set index / class, and each
call walks the whole ClassDef, so a subtable with many classes sharing
one large ClassDef was quadratic per closure visit (and thus in
subsetting).

Collect ClassDef::intersected_classes() of the glyph set into a set
once per visit and answer the per-class query from that set.  All eight
call sites across ContextFormat2 and ChainContextFormat2 (closure and
depend) use the precomputed set; results are identical.  Adds a fuzzer
regression font.

Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-ZCMLEQFJ.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 19:15:42 -06:00
Behdad EsfahbodandClaude Opus 4.8 0cf5addc3e [GSUB] Add small-active-set closure/depend fast path to Coverage-keyed lookups
SingleSubstFormat2 already picks, per closure visit, between walking its
whole Coverage and iterating the (usually small) active glyph set.  The
Multiple/Alternate/Ligature/ReverseChain closure and depend paths, the
format-1 (Chain)Context closure, and Coverage::intersect_set lacked that
choice, so a nested lookup visited many times over a small active set
re-walked a large Coverage every time, giving quadratic GSUB closure
(and thus subsetting) time.

Add the same get_population()-based fast path to those paths and to
CoverageFormat1/2::intersect_set.  Output is byte-identical; only the
per-visit work is bounded.

Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-KNHDK379.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 19:15:42 -06:00
Behdad EsfahbodandClaude Opus 4.8 fb350edda9 [ot] Collect class-based contextual rule classes once per ClassDef in collect_glyphs
Rule::collect_second_glyphs() resolved the second input glyph of a
class-based contextual rule by scanning the whole input ClassDef once
per rule, so a RuleSet with many rules sharing one large ClassDef was
quadratic in collect_glyphs() (and thus in subsetting).

Collect the needed classes into a set and walk each ClassDef once for
all of them: add ClassDef::collect_classes(), and have
collect_second_glyphs() accumulate the classes and resolve them in a
single pass.  The collected sets are identical; only the work is
reduced.

Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-5FCXNOQF.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 19:15:42 -06:00
Behdad EsfahbodandClaude Opus 4.8 fd57025171 [syllabic] Record HB_MAX_SYLLABLE_LENGTH cuts so every pass sees the same pieces (#6558)
Since 12b686dad, _hb_next_syllable() cuts syllables longer than
HB_MAX_SYLLABLE_LENGTH at whatever glyph index the walk reaches, and
nothing records that cut.  The Indic shaper's initial and final
reordering (with GSUB features shortening the buffer in between) then
walk different pieces, the deferred pre-base-matra cluster merge never
happens, and hb_shape() returns non-monotone clusters at the default
MONOTONE_GRAPHEMES level for an over-long Indic syllable.

Add hb_syllabic_record_cut(), next to the other shared syllabic
helpers, and call it on each piece from the foreach_syllable() loops
that already exist where syllables are set up in all four syllabic
shapers (Indic, Khmer, Myanmar, USE), and once more in Indic initial
reordering since dotted-circle insertion can push a piece back over
the limit.  Its inline fast path is a single length compare, so it
costs nothing unless a piece reaches the limit.  Only a piece of
HB_MAX_SYLLABLE_LENGTH glyphs that is followed by more of the same
syllable takes the slow path: it cuts the rest of the syllable into
the pieces foreach_syllable() would make, gives every piece but the
last one of two serials that differ from the preceding syllable and
from the last piece (which keeps the ragel serial), so substituted
glyphs inherit it and all later walks see identical pieces, and
merges the whole oversized syllable into one cluster
(merge_clusters at monotone cluster levels, unsafe-to-break
otherwise) so the cut cannot become a line-break opportunity
mid-syllable.  Serials of all other syllables are untouched, so
numbering and wraparound are exactly what the ragel machines
produce.  The cut in _hb_next_syllable() stays as the backstop.

Behaviour change: syllables longer than HB_MAX_SYLLABLE_LENGTH become
a single cluster, where previously each piece got its own clusters.

A regression test with a 68-codepoint Devanagari input is added to
indic-syllable.tests; it fails (non-monotone clusters) on the
unpatched tree.

Tested: meson test (all pass).  hb-shape on hi-words / a 175KB
Devanagari paragraph shows no measurable slowdown.

Reported by Anthropic's OSS Scanner as ordinary bug ANT-2026-W15T9EXZ.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 19:15:38 -06:00
Behdad Esfahbod edca03eadb [bit-vector] Use bounded bitvectors in GDEF and the repacker (#6630)
Use hb_bit_vector_t and hb_min_max_t as Coverage sinks for the GDEF
mark-set cache. Preserve the exact-cache span limit and fall back to
the digest and table when allocation fails. Pack the repacker's
Dijkstra visited flags into one bit per vertex.

Fix singleton ranges and compute bit masks relative to the vector's
minimum. Avoid overflow when sizing inclusive ranges, expose allocation
failure, and add the Coverage sink methods needed by GDEF.

Add regression tests for biased ranges, singleton and allocation
boundaries, failing allocation, moves, and GDEF cache/table parity.

Testing: full meson test suite (303 passed, 1 skipped); bitvector tests
with AddressSanitizer and UndefinedBehaviorSanitizer; HB_TINY
amalgamation syntax check.

Assisted-by: OpenAI Codex
2026-11-10 17:12:12 -06:00
Behdad EsfahbodandClaude Opus 5.5 df02261eca [subset] Charge Coverage and ClassDef glyph walks to a work budget (#6628)
* [subset] Charge Coverage and ClassDef glyph walks to a work budget

Coverage::subset() expands a format 2 Coverage glyph by glyph, up to
numGlyphs, every time an offset to it is subset, and nothing bounded
that work.  A 10-byte range Coverage referenced by 30,000 two-byte
offsets in a subtable listed 8 times costs 1.6e10 iterator steps,
while the sanitizer only bounds work by table bytes; a 60 KB font
keeps hb-subset busy ~50 s.  GDEF's MarkGlyphSets reaches the same
walk with no feature or lookup needing to survive planning.

Give hb_subset_context_t a per-table work budget
(HB_BUDGET_SUBSET_TABLE, in the hb_budget_spend() idiom of
hb-limits.hh) with a check_ops() helper that fails the serializer once
exhausted, and charge Coverage::subset() its capped population before
the walk.  Charging inside Coverage::subset() covers every caller
(ReverseChainSingleSubst, (Chain)ContextFormat3, GDEF MarkGlyphSets,
...) without touching them.  The same unbounded per-reference pattern
in ClassDefFormat1_3 / ClassDefFormat2_4::subset() (the range or
glyphset walk and the glyph_filter count) is charged the same way.

A hostile table that exceeds the budget now fails the subset cleanly
(hb_subset_or_fail returns NULL) in a fraction of a second instead of
succeeding slowly; valid-font output is byte-identical and the
heaviest local table spends a small fraction of the budget.
test_subset_shared_coverage_budget builds the reverse-chaining GSUB in
memory and asserts 256 shared references subset while 2048 fail.

Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-LLIWV9UK.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* [subset] Charge layout glyph walks to the existing subset budget

Drop the separate HB_BUDGET_SUBSET_TABLE budget and the second
hb_subset_context_t field it needed; check_ops() now charges
budget_remaining (HB_BUDGET_SUBSET_GLYF, 1 << 28), the per-table
budget glyf instancing already uses.  Both are per-table and shared
across buffer-size retries, and no table spends both.

The larger budget still bounds the attack (fails after 2^28 glyph
steps, ~3 s), so test_subset_shared_coverage_budget now expects the
failure at 8192 shared offsets instead of 2048.

Subsetting all glyphs with --layout-features='*' of Gulzar,
NotoSansKR-VF and GoogleSansFlex-VF keeps GSUB/GPOS/GDEF with output
byte-identical to before; the heaviest table (Gulzar GPOS) spends
~98K units, under 0.04% of the budget.  Full meson test: 278 OK.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 16:50:50 -06:00
Behdad EsfahbodandClaude Opus 4.8 7f65c5d820 [ot-map] Resolve a feature once in add_lookups() instead of once per 32 lookups (#6626)
hb_ot_map_builder_t::add_lookups() paged through a feature's lookup
indices 32 at a time with hb_ot_layout_feature_with_variations_get_lookups(),
which re-resolves the feature on every call.  Under a FeatureVariations
record that resolution is a linear search of the substitution records,
so a feature with many lookups and many variation records cost time
quadratic in the number of lookups, stalling hb_shape()'s plan build.

Add _hb_ot_layout_feature_with_variations_get_lookups(), which resolves
the feature once and returns its whole lookup-index array, and have
add_lookups() iterate that array directly.  The public API is
unchanged; the resulting map is identical.

Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-M3XZD80O.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 16:29:56 -06:00
Behdad EsfahbodandClaude Opus 4.8 26a6729680 [instancer] Merge repeated VarData region indices into one tuple (#6625)
create_from_item_var_data() deep-copied a region's axis hash map once
per entry of VarData.regionIndexes, so memory grew with
regionIndexCount x axisCount while the font pays only their sum, and
region indices may repeat freely. A 100 KB font (2000 axes, one region,
16000 copies of region index 0) made one hb-subset call allocate about
2 GB.

A region a VarData names again now adds its delta column to the tuple
it already owns, exactly what merge_tuple_variations() computes later,
so the instanced output is byte-identical. To also bound the sibling
case of many dataSets offsets each pointing at one VarData, the region
axes copied while converting one ItemVariationStore are summed across
its VarData subtables and capped at a new HB_VARSTORE_MAX_TUPLE_AXES
(1<<20); stores in the test fonts stay far below the
cap. Exceeding the cap fails instancing of that store, the same
path a failed allocation already takes.

Adds a unit test (test_repeated_region_index) covering the merge and
the cap.

Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-1CGIYCMY.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 16:24:19 -06:00
Behdad Esfahbod ca50d4ad91 Merge pull request #6624 from harfbuzz/split/gsubgpos-header
[layout] Write GSUB/GPOS subsets with a header that matches their layout
2026-11-10 16:21:48 -06:00
Behdad EsfahbodandClaude Opus 4.8 8aa3f2a887 [gpos] Skip non-increasing Coverage indices in PairPosFormat1::intersects fast path (#6623)
* [gpos] Skip non-increasing Coverage indices in PairPosFormat1::intersects fast path

The slow-population fast path of PairPosFormat1_3::intersects() walked
the glyph set and indexed pairSet by the Coverage index of each glyph.
In a well-formed font those indices increase with glyph id, but a
broken Coverage can repeat an index, so one PairSet could be scanned
once per glyph, giving quadratic time.

Track the last index used and skip any that does not increase (and any
NOT_COVERED), following the existing "Broken table. Skip." convention,
so each PairSet is scanned at most once.  Well-formed fonts are
unchanged.  Adds a fuzzer regression font.

Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-6GSU471N.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* [subset] Skip PairPosFormat2 classes outside the class matrix when collecting variation indices

collect_pair_variation_indices() added every class returned by the two
ClassDefs to class1_set / class2_set without bounding them by
class1Count / class2Count.  A ClassDef can map glyphs to classes far
outside the value matrix, so the collected sets could be enormous and
the subsequent nested loop quadratic, although apply() and the
serialization loops only ever touch classes inside the matrix.

Bound the collected classes by class1Count / class2Count, the same
bound the rest of the code already uses.  Output is byte-identical;
adds a fuzzer regression font.

Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-C60AYSA3.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 16:20:27 -06:00
Behdad EsfahbodandClaude Opus 4.8 7f1440eac1 [GDEF] Fill the mark-glyph-set cache straight from each Coverage (#6622)
The GDEF accelerator built its per-mark-set bit-page/digest cache by
materializing an hb_set_t for every mark glyph set and walking it glyph
by glyph.  A mark set's Coverage can name an enormous glyph range in a
few bytes, and several sets can alias one all-glyphs Coverage, so a
256 KiB font with 65535 such sets cost about 1 GiB and billions of
iterations in the accelerator constructor.

Fill each entry directly from its Coverage table via
collect_coverage() into lightweight sinks (gid extents, then a biased
bit-page or a digest), so the work is proportional to the coverage
records the sanitizer already budgeted for, not to the glyphs they
span.  Replace MarkGlyphSets::collect_coverage() with get_count() /
get_coverage() accessors.  Answers are identical.  Adds a fuzzer
regression font.

Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-OM3ZVHGK.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 16:15:17 -06:00
Behdad EsfahbodandClaude Opus 4.8 40d215957a [depend] Collect GSUB feature tags, substitutes and lookup variations in one pass (#6621)
GSUB_accelerator_t::depend() resolved each feature tag separately: it
ran hb_ot_layout_collect_features() once per tag and, for every tag,
walked the whole FeatureVariations table looking for substitute
features.  Tables with many features and many FeatureVariations records
were therefore quadratic, work that sanitize() bounds only for a single
pass.

Query all tags at once, then visit each feature once and each
FeatureVariations substitute once (via new visit_substitutes()
helpers), mapping every lookup to the tag of the feature it belongs to.
The emitted dependency graphs are unchanged.

Adds a regression test building a FeatureVariations GSUB whose features
have no direct lookups.

Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-5C2QXX5N.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 16:11:44 -06:00
Behdad EsfahbodandClaude Opus 4.8 c569b7fede [gsubgpos] Read contextual rule input glyphs through glyph_data_t in closure/depend (#6620)
context_closure_recurse_lookups() and context_depend_recurse_lookups()
already hold the rule's input sequence as a width-erased glyph_data_t
view, but for glyph-based rules (ContextFormat::SimpleContext) they
unwrapped the raw pointer and let intersected_glyph() index it as
HBUINT16.  That is wrong for the HBUINT24 arrays of
SequenceContextFormat4 / ChainedSequenceContextFormat4: every input
position after the first was read at the wrong bytes, so the nested
lookup was closed over the wrong glyph and its real output never
entered the closure (other glyph ids keep glyphs that can never
appear).  Only experimental / beyond-64k builds are affected.

Resolve the glyph via input[seqIndex - 1] for every format and make
intersected_glyph() a plain insert of the value, mirroring its sibling
intersects_glyph() which already takes the resolved glyph and ignores
data.  These two call sites were the only users of the
pointer-plus-index convention; 16-bit formats are unchanged, and there
is no API/ABI change.

Adds a regression test under HB_NO_BEYOND_64K: a SequenceContextFormat4
rule "1 2" invoking a SingleSubst 2->3 must close {1, 2} to {1, 2, 3}.
It fails on the unpatched library and passes with the fix.

Reported by Anthropic's OSS Scanner as ordinary bug ANT-2026-IU58QGNT.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 16:10:13 -06:00
Behdad EsfahbodandClaude Opus 4.8 f2390b0a2e [subset] Merge CFF charstring commands in place, not by erasing (#6619)
Passes 2 and 3 of CFF::specialize_commands() called
hb_vector_t::remove_ordered() once per merged command, and each call
shifts every command behind it, so a charstring of A mergeable line
segments followed by T unmergeable commands cost A*T element moves,
bounded only by HB_CFF_MAX_OPS: 32 s of CPU for one glyph of a 1.6 KB
font with --downgrade-cff2, paid again on every serializer-buffer
retry.

Replace both loops with one helper, combine_commands(), that walks
backwards exactly as before (each command absorbs its already-merged
successor chunk while the predicate allows, matching fontTools order)
but keeps finished commands packed at the tail and compacts the vector
once at the end, so the work is linear.  The two merge conditions
(operator pair, args-length parity, combined args < maxstack) become
the predicates verbatim and the merge order is unchanged.

Adds test_specialized_many_commands() to src/test-cff.cc (100,000 unit
rlineto followed by 100,000 empty hhcurveto must come back as 2,128
line commands plus the untouched hhcurveto commands); it takes 0.08 s
with this change versus tens of seconds before.

Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-7TEMF5SE.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 16:08:49 -06:00
ebraminio e4802120b6 [subset] Keep hinting for fonts that require it (#6588)
* [subset] Keep hinting for fonts that require it

Some legacy fonts have hinting programs that must be run for correct
rendering; dropping them changes glyph advances and outlines.  FreeType
refuses to load these fonts without hinting, so do the same in the
subsetter by ignoring HB_SUBSET_FLAGS_NO_HINTING for them.

Only TrueType-outline fonts qualify.  Identify them by family name, and
by the length and checksum of their cvt, fpgm, and prep tables.  The
lists and the name-to-ASCII semantics are ported from FreeType's
src/truetype/ttobjs.c; fontations has the same logic in
read-fonts/src/tables/glyf/hint_reliant.rs.  Keep the detection in
hb-subset-hinting.hh rather than the subsetter, and add tests for both
paths.

Assisted-by: DeepSeek

* [subset] Refine hint-dependent font detection

- Store family names in a fixed-size table to avoid relocations.
- Read the name table directly instead of building the name
  accelerator, and select the record with FreeType's platform and
  language priority.
- Use hb_vector_t::set_storage() for the name buffer; treat an
  allocation failure as a non-match.
- Pick the family name the way FreeType does: honor the OS/2 WWS bit,
  and do not fall through to a lower-priority family name when the
  preferred one exists but does not match.
- Add equality operators and use CheckSum::set_for_data() for table
  checksums, rejecting unaligned data and handling the trailing bytes.
- Use face->table.glyf and drop the beyond-64K guard.
- Use ISALPHA/TOUPPER for the PDF randomization tag check.
- Add a regression test for the OS/2 WWS family selection.

Assisted-by: DeepSeek

* [perf] Add NO_HINTING subset benchmarks

Add a per-test NO_HINTING flag and enable it for the static TrueType
font benchmarks, so subsetting through the hint-dependent-font
detection path is measured. Benchmark names get a /nohinting suffix.

Assisted-by: DeepSeek

* [subset] Allow unaligned and unpadded checksum data

CalcTableChecksum() can add a trailing partial word.  Use that so
_table_checksum() can pass arbitrary table data directly to
CheckSum::set_for_data() instead of rejecting unaligned data and
splitting off the padded prefix.

Add unit coverage for padded, unpadded, and unaligned data.

Assisted-by: DeepSeek

* [subset] Rename and cache the hint-dependent face check

Prefix the entry point with _hb_subset, and cache the answer in face
user data so repeated subsetting of the same face does not repeat the
name and table scans.

Assisted-by: DeepSeek

* [subset] Avoid allocating for the hint-dependent cache

Store the hint_dependent_cache_t value in the face user-data pointer
instead of allocating a bool.  UNCACHED is zero, CACHED_FALSE is one,
and CACHED_TRUE is two.

Assisted-by: DeepSeek

* [test] Validate checksums against Python-generated vectors

Generate deterministic buffers and expected OpenType checksums with an
independent Python implementation, covering unaligned offsets and
lengths that are not multiples of four.  The generator is committed as
src/generate-checksum-vectors.py and rewrites the marked block in the
unit test.

Assisted-by: DeepSeek

* [test] Drop the checksum vector generator

Keep the Python-generated vectors embedded in test-checksum.cc, but
remove the generator script and its markers.  The comment records that
the values were generated independently with Python.

Assisted-by: DeepSeek

* [subset] Use CheckSum::CalcTableChecksum directly

Drop the trivial _table_checksum() wrapper and call
CheckSum::CalcTableChecksum() from the table-ID builder.

Assisted-by: DeepSeek

* [subset] Release the sanitized name table

hb_blob_ptr_t does not destroy its blob in its destructor, so add a
scope guard to release it on every return path.

Assisted-by: DeepSeek

* [subset] Limit cache enum scope

* [subset] Use dagger iteration for hint lists

Replace the family-name and font-ID membership loops with
hb_iter/hb_map/hb_any, and name the family-name capacity used by the
table and its iterator.

Assisted-by: DeepSeek
2026-11-10 11:26:23 -06:00
Behdad EsfahbodandClaude Opus 4.8 5aeb5ec60d [ft] Reselect the COLR palette instead of copying it per paint (#6617)
* [ft] Reselect the COLR palette instead of copying it per paint

#6490 lets paint callbacks run with the FT face unlocked, so a
callback can paint another glyph that selects a different palette on
the same FT_Face, changing the colors FreeType's palette buffer holds.
It guarded against that by heap-copying the whole palette on every
COLRv1 glyph paint.

Instead, remember on the hb_ft_font_t which palette hb-ft last
selected, and when a palette color is about to be read (with the lock
held) and another palette has been selected since, select ours again.
The common case costs one compare and no allocation.

Testing: meson test -C build passes.  test-paint's
ft_reentrant_paint, which paints with palette 1 from inside the
custom-palette callback, fails with the reselect disabled and passes
with it.

Follow-up to #6490

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* [ft] Drop palette bookkeeping; rely on FT_Palette_Select's no-op

FT_Palette_Select already skips its work when the requested palette is
the one already selected on the face, and returns the palette pointer
either way (freetype src/base/ftcolor.c).  So the selected_palette
member added to track it, and the guard around the re-select, are
unnecessary: _hb_ft_get_solid_color re-selects our palette
unconditionally after a callback may have changed it, and FreeType
no-ops the common case where it is already current.

Removes hb_ft_font_t::selected_palette and both of its assignments.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 11:22:15 -06:00
Behdad EsfahbodandClaude Opus 4.8 82bef10c5f [subset] Skip PairPosFormat2 classes outside the class matrix when collecting variation indices
collect_pair_variation_indices() added every class returned by the two
ClassDefs to class1_set / class2_set without bounding them by
class1Count / class2Count.  A ClassDef can map glyphs to classes far
outside the value matrix, so the collected sets could be enormous and
the subsequent nested loop quadratic, although apply() and the
serialization loops only ever touch classes inside the matrix.

Bound the collected classes by class1Count / class2Count, the same
bound the rest of the code already uses.  Output is byte-identical;
adds a fuzzer regression font.

Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-C60AYSA3.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-09 21:29:32 -06:00
Behdad EsfahbodandClaude Opus 4.8 63c31a9e6c [gpos] Skip non-increasing Coverage indices in PairPosFormat1::intersects fast path
The slow-population fast path of PairPosFormat1_3::intersects() walked
the glyph set and indexed pairSet by the Coverage index of each glyph.
In a well-formed font those indices increase with glyph id, but a
broken Coverage can repeat an index, so one PairSet could be scanned
once per glyph, giving quadratic time.

Track the last index used and skip any that does not increase (and any
NOT_COVERED), following the existing "Broken table. Skip." convention,
so each PairSet is scanned at most once.  Well-formed fonts are
unchanged.  Adds a fuzzer regression font.

Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-6GSU471N.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-09 21:29:32 -06:00
Behdad EsfahbodandClaude Opus 5.5 488e98dd8c [aat] Share hb_language_from_string()'s canonicalization with ltag (#6610)
* [aat] Share hb_language_from_string()'s canonicalization with ltag

ltag::matches_language() avoids interning the font's tag, but did so
by re-implementing hb_language_from_string()'s canonicalization
(63-byte cap, lowercasing, '_' to '-', stop at other characters) with
its own code, which could drift from canon_map.

Add an internal hb_language_matches_string() in hb-common.cc that
compares a raw string against an hb_language_t through canon_map and
the same length cap, and computes exactly
hb_language_matches (hb_language_from_string (str, len), specific)
without interning str.  matches_language() now calls it.  The length
cap is named once and used by hb_language_from_string() too.

The only edge-case differences from the previous copy are where it
diverged from hb_language_matches(): an empty tag now matches
HB_LANGUAGE_INVALID, and a tag with no canonical characters matches a
language that is empty or starts with '-'.

Testing: meson test -C build (all passing).

Follow-up to #6513

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* [aat] Move language matching declaration to hb-algs.hh

Declare hb_language_matches_string() with the internal helpers instead
of in hb.hh. Keep its implementation in hb-common.cc alongside the
shared language canonicalization table.

Validation: meson compile -C build; meson test -C build (278 passed).

Assisted-by: OpenAI Codex

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 20:30:13 -06:00
Behdad EsfahbodandClaude Opus 5.5 d17c0dbe97 [raster] Fail hb_raster_draw_render() when over the pixel budget (#6616)
#6521 made hb_raster_draw_render() skip the scanline sweep when the
estimated pixel work exceeds the budget, but it still returned a
cleared image, so callers could not tell a budget failure from an
outline that legitimately covers nothing.

Check the budget before allocating the image and return NULL, the
same way render already reports allocation and configuration
failures.  The accumulated edges are still cleared by the existing
scope guard.  All in-tree callers (raster paint masks, hb-raster
utilities) already handle a NULL result.

test_budget_sweep now expects NULL for the over-budget case.  Full
meson test passes.

Follow-up to #6521

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 20:29:35 -06:00
Behdad EsfahbodandClaude Opus 5.5 9fe4897e97 [face-builder] Drop the parallel sorted_tags; sort once on demand (#6609)
* [face-builder] Sort table tags in get_table_tags() again

Follow-up to #6503.  d52c540c7 kept a sorted copy of the table tags
next to the hash map and maintained it on every
hb_face_builder_add_table() insert (binary search, pre-allocation,
memmove), only so that _hb_face_builder_get_table_tags() would not
have to sort.  That is a second structure to keep in sync with the
map on the hot insertion path for every subset.

Drop the parallel vector and sort the keys in get_table_tags(), as
before.  Serialization (_hb_face_builder_data_reference_blob()) never
used the vector; it sorts its own entries by order and size.  The
65535-table limit goes back to its original tables.has() form; the
other #6503 fixes (axis-range parser, name-override leak, length
bound, reference_blob() recursion) are untouched, and the paging
regression test from d52c540c7 is kept and still passes.

Note that a caller paging through get_table_tags() again pays one
sort per page, which is what ANT-2026-VENZFNXH reported for the
65535-table faces hb_subset_preprocess() can produce.

Tested: meson test -C build (278/278 pass).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* [face-builder] Sort table tags once and remember the order

Sorting in every get_table_tags() call brings back the slowdown that
#6503 fixed (ANT-2026-VENZFNXH).  The subsetter pages through a
builder face's tags 32 at a time, so a face with 65535 tables paid
for thousands of full sorts.

Instead of keeping a sorted vector up to date on every insert, build
the sorted tag array the first time it is needed.  Keep it until the
next hb_face_builder_add_table().  The array is published with a
compare-and-swap, so concurrent readers stay safe.  If two readers
race, the loser frees its copy.

Testing: meson test -C build: 278 OK.  Paging through 65535 tags 32
at a time takes 5 ms and returns them sorted.  A table added after a
listing shows up in the next one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 20:28:45 -06:00
Behdad EsfahbodandClaude Opus 5.5 5e0b0dbb2f [gpu] Trim empty-clip comments (#6608)
The comments added for the empty-clip handling were long-winded
for what the code does.  Shorten them to one line each.

The extents check in hb_gpu_paint_encode() is kept as is: layer
ops are the only ones that accumulate extents, so unset extents
already mean no layer was emitted; a separate flag would only add
state to keep in sync.

No behavior change.  Tested with meson test.

Follow-up to #6483

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 20:27:12 -06:00
Behdad EsfahbodandClaude Opus 5.5 07cabf6e5b [aat] Drop the per-subtable buffer-pass charge to max_ops (#6605)
charge_buffer_pass() debited buffer->len from max_ops before every
kerx/kern/morx subtable that applies.  It mostly duplicates the
HB_AAT_MAX_SUBTABLES (1024) sanitize cap, which already bounds the
number of passes per table, and it charged the length of a buffer that
morx may have grown against an allowance sized from the input length.

Remove it and its two call sites.  The kerx loop still stops once the
buffer is no longer successful.  The subtable-limit API tests are kept;
they test the sanitize cap, not the charge.

Testing: meson test -C build (all passing).

Follow-up to #6513

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 20:26:42 -06:00
Behdad EsfahbodandClaude Opus 5.5 5ac43f0a80 [buffer] Restore plain enter() limits; inject the graphite2 fault in the test (#6614)
Follow-up to #6511.  Moving enter()/leave() into HB_SHAPER_EXECUTE
(so hb_shape_plan_execute() gets per-text max_len/max_ops, the
ANT-2026-SUMXXLXH fix) made enter() overwrite the max_len that
test-graphite2-buffer narrows to inject an output-growth failure.
#6511 worked around that in the library: enter() kept any limit
already below the idle default.  That is extra logic in every shape
for the sake of one test.

Restore enter() to simply compute the per-text limits, and have the
test call the plan's shaper_func directly in the failing iteration,
so the max_len it sets is not replaced.  enter()/leave() stay in
HB_SHAPER_EXECUTE, so hb_shape_plan_execute() remains bounded.

The verify path in hb_shape_full() now runs after leave(); that is
fine: verify only reads the shaped buffer's info/pos and shapes
fresh buffers through hb_shape_full(), each of which gets its own
enter()/leave().  It uses no buffer vars or work limits of the
outer buffer.

Tested: meson test -C build (278/278 pass), and a second build with
-Dgraphite2=enabled (280/280 pass, incl. test-graphite2-buffer).

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 20:25:53 -06:00
Behdad EsfahbodandClaude Opus 5.5 73e9d5f054 Revert "[shape-plan] Cache the last shape plan looked up per face (#6550)" (#6618)
This reverts commit 708d59a50.

The one-entry per-face cache doesn't help the common case: with a
single plan per face, the plan is already the first node of the list.
When shaping alternates between keys on one face (LTR and RTL, two
scripts, different features), every call misses the slot.  That costs
an extra key.equal() before the list walk, then a write to the slot.
From several threads, that write bounces the face's cache line
between them on almost every call.  This is the same problem as the
hb_language_from_string() cache from #6549, which is also being
reverted.

A long-lived face with many plans walks the uncapped plan list by
design.  If that becomes a real problem, it should be fixed in the
list itself, not with a slot in front of it.

hb_atomic_t<T *>::set_release(), added in #6549 for these caches,
stays.

Testing: meson test -C build: 278 OK.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 18:36:35 -06:00
Behdad EsfahbodandClaude Opus 5.5 0c910506de [buffer] Restore simple loops in merge_clusters_impl() (#6615)
#6501 charged the neighboring-cluster walks in merge_clusters_impl()
and merge_out_clusters_impl() to max_ops by wrapping the extension
and cross-buffer continuation loops in an if (successful) block with
their own charges.  These are hot shaping paths, and the restructure
made them harder to follow.

Keep the original loop structure instead: return early once the
buffer has failed (callers such as the Thai shaper keep merging after
that, which is what made the walks quadratic), and move the existing
max_ops charge after the extension loops so that it covers the
extended range plus the cross-buffer continuation.  The cluster !=
guards #6501 added to merge_out_clusters_impl(), matching
merge_clusters_impl(), are kept; without them the Thai SARA AM case
walks the merged run on every call.  delete_glyph() and
delete_glyphs_inplace() are left as they are.

Testing: U+0E01 + 130000 x U+0E33 shapes in 0.04 s LTR / 0.56 s RTL,
same as current main (3.8 s / 5 s without the guards / early return).
test_shape_overlong_cluster_remerge passes; full meson test passes.

Follow-up to #6501

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 18:33:28 -06:00
Behdad EsfahbodandClaude Opus 5.5 d6d32a9c61 [aat] Fix author line in test-aat.cc header (#6611)
The license header was copied from another file and kept its
"Google Author(s): Garret Rieger" line.  Credit the actual author.

Header-only change; test-aat builds and passes.

Follow-up to #6487

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 18:32:43 -06:00
Behdad EsfahbodandClaude Opus 5.5 9c2a315301 [vector] Check the INT_MAX bound only after the fast path (#6604)
Follow-up to #6484.  The new `size > INT_MAX` check in
hb_vector_t::alloc() ran before the `size <= allocated` early
return, so every push/resize, including on the shaping hot path,
paid an extra compare and branch.

Do the early returns first and check the bound only when we are
about to reallocate.  The early returns only succeed when size is
at most allocated, which is itself at most INT_MAX, so behavior is
unchanged; the check still precedes the growth loop.  The `exact`
path still clamps size to length before both the shrink check and
the bound check.

Tested: meson test -C build (278/278 pass, incl. test-vector).

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 18:32:12 -06:00
Behdad EsfahbodandClaude Opus 5.5 fc1ad85522 [ft] Take vertical origins from FreeType's bearings again (#6613)
#6499 added caches for the vertical advance and origin, but also
changed what the origin is: its x became half the horizontal
advance (as hb-ot does) instead of FreeType's
horiBearingX - vertBearingX, and a glyph FreeType fails to load got
a cached origin of 0 instead of the callback returning false.  That
changed shaping output for fonts whose vertical bearings are not
centered (e.g. bitmap-only fonts), and stopped the fallback to
h_origins on load failure.

Keep the caches, but cache both the x and y FreeType computes, the
same way as before #6499, and return false on load failure without
caching anything.  Values that don't fit the unsigned cache after
sign normalization are simply not cached.

Testing: meson test -C build passes.  test-ft now checks the
batched origins against FreeType's bearings and that a failed load
returns false on repeat queries.  hb-shape --font-funcs=ft
--direction=ttb output over NotoSansKR plus 80 shape/api test fonts,
at several sizes, a variation, and negative scale (810 runs) is
identical to the commit before #6499; on main 30 of those differed
(aat-feat, chromacheck-cbdt, chromacheck-sbix).

Follow-up to #6499

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 18:28:24 -06:00
Behdad EsfahbodandClaude Opus 5.5 9e65a95d62 [aat] Share the segment-collection guard between Lookup formats 2 and 4 (#6612)
#6513 made LookupFormat2::collect_glyphs_filtered() stop adding
segments one by one once they are out of order, folding the rest into
a single range.  It did so with an inline copy of the segment logic
instead of the segment's own methods, and LookupFormat4 kept the old
loop, so repeated full-range format-4 segments each still cost a full
pass (bounded only by sanitize's per-byte max_ops on the value arrays).

Move the loop into collect_segments_glyphs_filtered(), shared by both
formats.  It asks each segment type whether it may contribute
(may_match()) and collects through the segment's own
collect_glyphs_filtered().  Format-2 segments check their value against
the filter.  Format-4 segments only check their range, so out-of-order
format-4 segments are folded into a superset without reading their
values.  Format 4's collect_glyphs() now uses the filtered path with an
always-true filter, as format 2's already does.  Sorted tables produce
the same sets as before.

Testing: meson test -C build (all passing).

Follow-up to #6513

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 18:03:08 -06:00
Behdad EsfahbodandClaude Opus 5.5 6df7f66f94 [CBDT] Cap strikes considered instead of indexing them (#6606)
#6500 made the CBDT accelerator build a per-face (ppem, glyph range)
-> record index at load time, with a strike set/map, a sorted vector,
a walk_ppems fallback and an HB_CBDT_MAX_INDEX_ENTRIES cap, to avoid
walking a huge strike array on every glyph query.  Real fonts have a
handful of strikes, so that machinery costs every CBDT face memory and
load time for the benefit of pathological fonts only.

Remove it and restore the simple CBLC::choose_strike() and
BitmapSizeTable::find_table() lookup path, but only consider the first
HB_CBLC_MAX_STRIKES (256) strikes when choosing one; later ones are
ignored.  ppem is 8-bit, so this never drops a distinct size a real
font could need.  The sbix strike index, the CBDT subsetter's record
map and its image-copy budget from #6500 are kept unchanged.

Adds test_hb_ot_color_png_cbdt_max_strikes, which places the only
usable strike at index 255 / 256 and checks it is found / ignored; it
fails with the cap removed.  Full meson test passes.

Follow-up to #6500

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 17:54:20 -06:00
Behdad Esfahbod 85c9526477 Merge pull request #6603 from harfbuzz/scanner/kerx4-overflow
[kerx] Guard kerx format-4 attach-chain against i16 overflow
2026-11-09 17:36:04 -06:00
Behdad Esfahbod 539a034cf2 Merge pull request #6607 from harfbuzz/fix/revert-language-cache
Revert "[common] Cache the last hb_language_from_string() result"
2026-11-09 17:35:04 -06:00
Behdad Esfahbod a40bb748d1 Merge pull request #6512 from harfbuzz/scanner/varc
[VARC] Bound CPU work in VARC shaping and subsetting
2026-11-09 13:57:59 -06:00
Behdad Esfahbod b457e5d2a1 Merge pull request #6514 from harfbuzz/scanner/cmap
[subset] Bound adversarial cmap work in format 4, per-record collection, and DMAP closure
2026-11-09 13:52:51 -06:00
Behdad Esfahbod 100717c015 Merge pull request #6561 from harfbuzz/scanner/cff-fix
[subset/cff] FDSelect and Encoding-supplement subset correctness fixes
2026-11-09 13:35:10 -06:00
Behdad EsfahbodandClaude Opus 4.8 051a12a37a [cff] Return the sentinel as the end of the last FDSelect range
FDSelect::get_fd_range() is documented to return "one after last glyph
in range", but for the last format-3/4 range FDSelect3_4::get_fd_range()
returned the range's first glyph (62f5ed461 changed it from 0 to that
value to stop an infinite loop, but it is still below every glyph in
the range).  hb_plan_subset_cff_fdselect() assigns that end to its loop
counter, so with a custom old-to-new glyph map the loop re-walks the
last range once per mapped glyph, making CFF1/CFF2 subsetting
quadratic.

The correct end is the FDSelect sentinel: sanitize() guarantees
sentinel > ranges[last].first and sentinel >= num_glyphs (== num_glyphs
for CFF1, >= CharStrings count for CFF2), and the caller only queries
old_glyph < src_num_glyphs and clamps the end to src_num_glyphs, so the
counter now only ever moves forward.  Fixing the accessor (rather than
guarding the loop) keeps the one place that establishes the documented
contract; FDSelect0::get_fd_range() already returns glyph + 1, and the
format-4 instantiation is covered by the same template.

Adds an assertion to the existing test_fd_select_sentinel() in
src/test-cff.cc; it fails before this change.

Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-CGK397GA.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-09 13:18:05 -06:00
Behdad EsfahbodandClaude Opus 4.8 fb58fbe259 [subset/cff2] Plan FDSelect from the real CFF2FDSelect type
cff2_subset_plan::create() cast acc.fdSelect (a CFF2FDSelect) to the
CFF1 FDSelect type for hb_plan_subset_cff_fdselect(), whose
get_fd_range() dispatch knows only formats 0 and 3.  A CFF2-only
format-4 FDSelect therefore reported FD 0 for every glyph, so the
planner kept only Font DICT 0: every retained glyph belonging to
another Font DICT lost that DICT's Private DICT and local subrs, and
when it called a local subr it either lost its outline or drew through
FD 0's subrs with the wrong shape.  The call still succeeded, writing a
single-Font-DICT font.  Format 4 is the only FDSelect format with a
16-bit FD index, so every CFF2 font with more than 256 Font DICTs is
affected.

The planner only needs get_fd_range() and format, so give CFF2FDSelect
its own get_fd_range() dispatching formats 0, 3 and 4, make
hb_plan_subset_cff_fdselect a template over the FDSelect type with
explicit instantiations for CFF1FDSelect and CFF2FDSelect (same pattern
as other explicitly instantiated subset helpers), and drop the cast.
The existing format-4 writer in hb_serialize_cff_fdselect is now
reachable.  Because a CFF2 font with >256 retained FDs can now
legitimately plan format 4, serialize_cff2_to_cff1() rejects that case
(CFF1 has no format 4) instead of emitting an invalid CFF table; with
fewer FDs the downgrade is unchanged.

Adds test_subset_cff2_fdselect_format4, which subsets the format-3 and
format-4 variants of a two-Font-DICT font and requires identical CFF2
output and glyph 2's extents; it fails before this change.

Reported by Anthropic's OSS Scanner as ordinary bug ANT-2026-7RSDR0F0.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-09 13:18:05 -06:00
Behdad EsfahbodandClaude Opus 4.8 a61e59716f [subset/cff1] Remap Encoding supplement SIDs through sidmap
cff1_subset_plan renumbers every custom SID it emits through sidmap
(charset via plan_subset_charset, Top DICT names via reassignSIDs, FD
names via sidmap[]), and the output String INDEX is serialized from
that map.  plan_subset_encoding was the one emitter that pushed the
source font's SID unchanged into subset_enc_supp_codes, so once an
earlier custom-named glyph was dropped a supplement code named the
wrong glyph, or a string past the end of the renumbered String INDEX.

Look the SID up in sidmap where the supplement entry is recorded.  The
source SID is still used for get_supplement_codes(), which searches the
source Encoding.  This is safe on every path that reaches it:
subset_encoding implies a non-CID font, so plan_subset_charset has
already added each visited glyph's name (sidmap.add is idempotent), and
when the charset is predefined and plan_subset_charset is skipped all
glyph SIDs are standard strings, which sidmap[] returns unchanged.

Adds test_subset_cff1_encoding_supplement with a generated CFF font
(custom names, format-0 Encoding with supplement 98 -> 'second') and
its expected B,C subset; the test fails before this change.

Reported by Anthropic's OSS Scanner as ordinary bug ANT-2026-JORVXUQZ.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-09 13:18:05 -06:00
Behdad EsfahbodandClaude Opus 4.8 9c84021391 [VARC] Charge VARC component condition evaluation to the work budget
VarComponent::get_path_at() paid a flat HB_BUDGET_4 per component and
then evaluated the component's Condition tree for free.  ConditionAnd
and ConditionOr children are offsets that may all point at the same
subtree, so the evaluated size of a tree is not tied to its encoded
size: a 1.4 KB ConditionList expands to 51,001 leaf visits per
component, and a 143-byte chain of two-child ConditionAnd nodes to
65,535 node visits, while the glyph budget still admits hundreds of
thousands of such components.  A sub-20 KB font could keep one glyph
extents or draw call busy for minutes, reachable from hb_shape() on
vertical text or combining marks.

Condition::evaluate() is a template shared with FeatureVariations in
GSUB/GPOS, which is evaluated once while building a shape or subset plan
and has no rendering budget, so route the charge through the instancer:
MultiItemVarStoreInstancer::charge_condition() spends HB_BUDGET_1 from
the live budget threaded in for the delta lookups, while
ItemVarStoreInstancer::charge_condition() is a no-op.  Condition::
evaluate() charges one unit per node visited, so every node is counted
even when an And/Or's children share one subtree, and returns false once
the charge fails; the VARC caller already bails when c.budget goes
negative right after the evaluation.  The instancer && guard keeps the
null-instancer callers (e.g. src/test-serialize.cc) safe.

A font whose conditional components do pathological amounts of condition
work now exhausts the glyph budget and renders incomplete output instead
of running for minutes; ordinary fonts spend a few extra units per
conditional component, and GSUB/GPOS condition evaluation is unchanged.
A unit test in src/test-item-varstore.cc pins the per-node charge,
including shared subtrees, and the bail-out once the budget is negative.

Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-U1J54XX5.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-09 13:17:50 -06:00