Commit Graph
22505 Commits
Author SHA1 Message Date
Behdad EsfahbodandClaude Opus 4.8 339aa688fa [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-11 12:43:10 -06:00
Behdad EsfahbodandClaude Opus 4.8 8f93b6d21b [layout] Charge GSUB/GPOS sanitize-time arrays to max_ops (#6631)
* [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>

* [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>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-11 12:43:06 -06:00
Behdad Esfahbod c67232c237 Merge pull request #6647 from harfbuzz/test/indic-zero-context
[test] Cover Indic zero-context feature detection
2026-11-11 12:34:33 -06:00
Behdad Esfahbod 83a47049a3 Merge pull request #6519 from harfbuzz/scanner/depend
[depend] Bound dependency-graph edge count and dedup probe walk
2026-11-10 22:44:19 -06:00
Behdad EsfahbodandClaude Opus 4.8 0601dd774e [limits] depend build budget + GSUB closure budget (#6526)
* [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>

* [depend] Clip context glyph sets to the face and charge a build budget

While extracting GSUB dependencies, find_or_create_glyph_set() turned
every Coverage (format 3 contexts) and class (format 2 contexts) that
a contextual rule mentions into an hb_set_t holding every glyph id the
table lists, whether the face has it or not, with no budget on the
expansion or on the second copy kept in the returned graph.  In
experimental builds, where the depend API and 24-bit Coverage formats
live together, a 6.5 KB font with 400 backtrack Coverage format 4
tables each covering [0, 0xFFFFFF] drives a build to ~2 GB.

Clip the cached sets to the face in find_or_create_glyph_set(), the
one place every context position goes through (the first input
Coverage and ReverseChainSingleSubst already clip this way), so the
copies kept in the graph shrink with them.  For real fonts this
changes nothing; only broken fonts stop carrying glyph ids past the
face.

Clipping alone is not enough: the temporary is still expanded in full,
and the glyph count itself is cheap to inflate with a MAXP table.  So
add a work budget for the whole build in the existing hb_budget_spend()
style: HB_BUDGET_DEPEND, budget_remaining on hb_depend_data_builder_t,
and charge_set(), which spends HB_BUDGET_4 per page while expanding a
temporary and HB_BUDGET_32 per page for every set the graph or context
keeps (new_set(), find_or_create_glyph_set(), find_or_create_recurse_set()).
Running out fails the build and hb_subset_depend_from_face_or_fail()
returns NULL, as it already does on allocation failure.  A
get_page_count() accessor is added to the bit-set types so the charge
does not reach into set internals; no public API change.

The 400-position font now peaks at ~11 MB instead of ~2 GB, the 64 KB
/ 4000-position font is refused, and hb-subset-depend output is
unchanged for real fonts.  Regression tests build the face with
hb_face_builder_create(): one asserts no glyph above the face count is
kept, the other that a 600-range face is refused.

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

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

* [layout] Charge GSUB glyph closure to a per-session work budget

hb_closure_context_t bounded GSUB glyph closure only by counting lookup
visits (HB_MAX_LOOKUP_VISIT_COUNT per round), and forgets which lookups
are done whenever the glyph set grows, so what one visit walks -- through
aliased offsets, many times the table size -- was charged to nothing.  A
LigatureSubst with 9000 ligatureSet offsets aliased onto one 64-component
Ligature, re-walked after every one of 1700 Context triggers that each
add a glyph, makes hb-subset --unicodes='*' of an 86 KB font spend ~110 s
of CPU.  A ReverseChain/ChainContextFormat3 with aliased backtrack
Coverages is a second way in.

Give the context an int64_t budget (HB_BUDGET_LAYOUT_CLOSURE records, in
the hb_budget_spend() idiom) spent as each closure() implementation walks
its arrays: dispatch() charges a visit its coverage record count;
ligature sets / ligatures / components, sequences, alternates,
single-subst intersections, rule sets and rules, context Coverages (via a
spend_coverages() helper) and the per-rule-set ClassDef walks are each
charged.  Coverage and ClassDef gain a get_record_count() helper because
intersects()/intersect_set() are linear in records, not population.  Once
the budget is spent, should_visit_lookup()/lookup_limit_exceeded() stop
the closure early, exactly as they do at the visit limit.

The budget lives in the context, so both public closure entry points (also
reached from hb_ot_shape_glyphs_closure() and the subset plan) are covered
with no API/ABI change.  Both attack shapes drop to ~1 s and the control
font's closure output is byte-identical; the heaviest real font in the
corpora uses about 1% of the budget.  A hostile GSUB now gets a truncated
closure, as one hitting the visit limit already does.
test_ot_layout_lookups_substitute_closure_budget builds the hostile table
in C and drives hb_ot_layout_lookups_substitute_closure() over it.

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

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 22:29:59 -06:00
Behdad Esfahbod 0eaceda537 [limits] Resolve work-budget conflicts with main
Merge main's active-glyph fast paths and precomputed ClassDef caches
with the dependency and GSUB closure budgets. Charge the fast paths
for the glyphs they visit and the class caches for their ClassDef
scans, preserving both the optimizations and the work limits.

The full Meson suite passes with experimental APIs enabled (300 tests)
and with the default configuration (281 tests). Also syntax-checked
hb-ot-layout.cc with HB_NO_BEYOND_64K.

Assisted-by: Codex
2026-11-10 19:31:06 -06:00
Behdad EsfahbodandClaude Opus 5.5 86c1bbb3b4 [cff1] Cache std_code_to_glyph() for seac component lookups (#6562)
std_code_to_glyph() resolves a seac component (bchar/achar) with
Charset::get_glyph(), a linear scan of the whole charset, and every
load of a seac charstring does it twice.  The scan is not charged to
the glyph work budget, so a COLRv0 glyph whose layers all name one
seac glyph costs seconds of CPU while the budget stays almost
untouched (the attacker font: 32 s).

Charging the scan is not a good fit here: Charset::get_glyph() does
not report how far it scanned, so there is no exact cost to charge,
and a flat per-lookup charge against the shared subset budget would
make large fonts with many accented seac glyphs fail to subset.
Instead remove the redundant work: the key space is the 256
StandardEncoding codes, so on first use build a 256-entry
code-to-glyph table in one pass over the charset, recording the
first glyph carrying each StandardEncoding SID, as get_glyph() does.
This fixes all three callers (path, extents and the subsetter's seac
closure) with byte-identical output.

The table is allocated lazily and installed with cmpexch, like the
accelerator's glyph_names, and freed in _fini(): the accelerator
grows by one pointer, HB_NULL_POOL_SIZE is unchanged, and nothing is
allocated for fonts without seac.  On allocation failure the lookup
falls back to the scan.

Tested by checking the table against get_glyph() on every lookup
across the full test suite (temporary assert), and the existing seac
tests (draw, extents, subset).

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 19:25:00 -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 70df3ff279 [layout] Charge GSUB glyph closure to a per-session work budget
hb_closure_context_t bounded GSUB glyph closure only by counting lookup
visits (HB_MAX_LOOKUP_VISIT_COUNT per round), and forgets which lookups
are done whenever the glyph set grows, so what one visit walks -- through
aliased offsets, many times the table size -- was charged to nothing.  A
LigatureSubst with 9000 ligatureSet offsets aliased onto one 64-component
Ligature, re-walked after every one of 1700 Context triggers that each
add a glyph, makes hb-subset --unicodes='*' of an 86 KB font spend ~110 s
of CPU.  A ReverseChain/ChainContextFormat3 with aliased backtrack
Coverages is a second way in.

Give the context an int64_t budget (HB_BUDGET_LAYOUT_CLOSURE records, in
the hb_budget_spend() idiom) spent as each closure() implementation walks
its arrays: dispatch() charges a visit its coverage record count;
ligature sets / ligatures / components, sequences, alternates,
single-subst intersections, rule sets and rules, context Coverages (via a
spend_coverages() helper) and the per-rule-set ClassDef walks are each
charged.  Coverage and ClassDef gain a get_record_count() helper because
intersects()/intersect_set() are linear in records, not population.  Once
the budget is spent, should_visit_lookup()/lookup_limit_exceeded() stop
the closure early, exactly as they do at the visit limit.

The budget lives in the context, so both public closure entry points (also
reached from hb_ot_shape_glyphs_closure() and the subset plan) are covered
with no API/ABI change.  Both attack shapes drop to ~1 s and the control
font's closure output is byte-identical; the heaviest real font in the
corpora uses about 1% of the budget.  A hostile GSUB now gets a truncated
closure, as one hitting the visit limit already does.
test_ot_layout_lookups_substitute_closure_budget builds the hostile table
in C and drives hb_ot_layout_lookups_substitute_closure() over it.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 16:42:16 -06:00
Behdad EsfahbodandClaude Opus 4.8 9b4e3df364 [depend] Clip context glyph sets to the face and charge a build budget
While extracting GSUB dependencies, find_or_create_glyph_set() turned
every Coverage (format 3 contexts) and class (format 2 contexts) that
a contextual rule mentions into an hb_set_t holding every glyph id the
table lists, whether the face has it or not, with no budget on the
expansion or on the second copy kept in the returned graph.  In
experimental builds, where the depend API and 24-bit Coverage formats
live together, a 6.5 KB font with 400 backtrack Coverage format 4
tables each covering [0, 0xFFFFFF] drives a build to ~2 GB.

Clip the cached sets to the face in find_or_create_glyph_set(), the
one place every context position goes through (the first input
Coverage and ReverseChainSingleSubst already clip this way), so the
copies kept in the graph shrink with them.  For real fonts this
changes nothing; only broken fonts stop carrying glyph ids past the
face.

Clipping alone is not enough: the temporary is still expanded in full,
and the glyph count itself is cheap to inflate with a MAXP table.  So
add a work budget for the whole build in the existing hb_budget_spend()
style: HB_BUDGET_DEPEND, budget_remaining on hb_depend_data_builder_t,
and charge_set(), which spends HB_BUDGET_4 per page while expanding a
temporary and HB_BUDGET_32 per page for every set the graph or context
keeps (new_set(), find_or_create_glyph_set(), find_or_create_recurse_set()).
Running out fails the build and hb_subset_depend_from_face_or_fail()
returns NULL, as it already does on allocation failure.  A
get_page_count() accessor is added to the bit-set types so the charge
does not reach into set internals; no public API change.

The 400-position font now peaks at ~11 MB instead of ~2 GB, the 64 KB
/ 4000-position font is refused, and hb-subset-depend output is
unchanged for real fonts.  Regression tests build the face with
hb_face_builder_create(): one asserts no glyph above the face count is
kept, the other that a 600-range face is refused.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 16:42:16 -06:00
Behdad EsfahbodandClaude Opus 5.5 3b517b36f5 [depend] Drop the edge probe budget and raise the edge cap
With edge keys hashed by fasthash32 over all fields, a font can no
longer steer its edges onto one slot, so probing is bounded by the
table's load factor; remove HB_DEPEND_MAX_EDGE_PROBES and its
per-probe charge.

HB_DEPEND_MAX_EDGES at 1<<22 was too close to real fonts: macOS's
DecoType Nastaleeq Urdu builds a graph of 1,198,826 edges, 3.5x below
it.  Raise the cap to 1<<25, 28x above that.  Other large fonts
measured: Noto Nastaliq 234,098; Hiragino Kaku Gothic 120,851; Gulzar
30,377; NotoSans-merged 29,968; NotoSansKR 7,797.

Reaching the raised cap takes 3.7 s and 1.7 GB, too much for a test,
so test_depend_edge_limit now only checks that a modest fan-out is
recorded in full.  test_depend_gsub_high_bit_tags still covers the
hash.

Tested: meson test -C build-exp (experimental API, 296/296 OK).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:38:50 -06:00
Behdad EsfahbodandClaude Opus 4.8 0f9c31a671 [depend] Hash edge keys with fasthash32 and bound the dedup probe walk
The dependency-graph edge dedup table in
hb_depend_data_builder_t::add_edge() was indexed by the low bits of
an FNV-style hash whose chain of XORs and odd-constant multiplies
only ever carries upwards, so bit j of the result depended only on
bits 0..j of each field.  A font controls feature tags (free 32-bit
values) and substitute glyph IDs, so it can pick values that differ
only in their high bits and pile every edge of a lookup onto one
slot.  The open-addressed probe loop then does about N^2/2 work and
each resize_edge_slots() repeats it, so a 15 KB font with 680k
colliding edges spent ~10 min of CPU while an ordinary font with the
same edges takes 0.1 s.

hb_depend_edge_key_t::hash() now runs fasthash32() over all identity
fields, so every bit of every field reaches the index; equality and
the probe sequence are unchanged, so real fonts produce the same
graph at about two probes per edge.  The now-unused
hb_depend_edge_t::hash() is removed.

A mixed hash alone is not enough: it is unkeyed, so colliding edges
can still be found offline (each one then costs font bytes instead
of coming free from a product of tags and pairs, but the walk stays
quadratic in them).  Every occupied slot stepped over in add_edge()
and resize_edge_slots() is therefore charged to a new per-build
counter edge_probes_remaining, seeded from HB_DEPEND_MAX_EDGE_PROBES
(1<<26, in hb-limits.hh and overridable like the other HB_*_MAX_*
limits, following the HB_RASTER_MAX_DRAW_EDGES precedent); exceeding
it fails the build the way an allocation failure does, so
hb_subset_depend_from_face_or_fail() returns NULL.  At about two
probes per edge the cap leaves more than 100x headroom over the
largest test font.  Honest fonts are already bounded well below it
by the HB_DEPEND_MAX_EDGES cap added in the previous commit; the
probe budget is what stops a crafted all-colliding chain from doing
quadratic work before that cap is reached.

A regression test builds a GSUB with 2048 features whose tags differ
only in bits 20 and up and checks that all 2048 edges are recorded.
test-ot-depend, the api suite and the depend fuzzing/closure-parity
tests pass on the ASan experimental build, and the finding's
reproducer now builds the hostile font in well under a second.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 16:38:50 -06:00
Behdad EsfahbodandClaude Opus 4.8 d377bc81f2 [depend] Cap the number of stored dependency-graph edges
hb_depend_data_builder_t::add_edge() stored one record per
(source, target, feature tag) with no bound.  In GSUB a lookup
reached by F feature tags multiplies its N*M substitutions by F, so
a lookup whose covered glyphs all share one AlternateSet, selected
by many feature tags, produces N*M*F edges from a font that grows
only with N+M+F.  A 5 KB font yields 33M edges and ~1.4 GB of
builder memory; COLRv0 overlapping layer slices reach the same sink
without any GSUB.  The builder also kept walking after fail(), so an
allocation failure still cost the full N*M*F iterations.

This adds HB_DEPEND_MAX_EDGES (1<<22, about 4M, next to
HB_MAX_GRAPH_EDGE_COUNT in hb-limits.hh and overridable the same
way; 16x the largest graph in the test corpus) and enforces it in
add_edge(), the single choke point every table's extractor stores
through, so hb_subset_depend_from_face_or_fail() returns NULL
instead of building an unbounded graph.  add_edge() and
add_gsub_lookup() return early once the builder has failed, and
GSUB_accelerator_t::depend()'s lookup loop stops as well, matching
the existing !successful checks in the context walkers, so a failed
build does bounded work.

A regression test builds the fan-out font in memory with
hb_face_builder (no binary test font needed) and checks that a
16x16x4 fan-out is recorded in full and that the 256x256x512 one is
refused.  test-ot-depend and the api suite pass on the ASan
experimental build, and the finding's reproducer now returns NULL
in ~1 s.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 16:38: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 5.5 1af279ed98 [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>
2026-11-09 22:23:09 -06:00
Behdad EsfahbodandClaude Opus 4.8 c5b920a0f9 [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>
2026-11-09 21:29:33 -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