Commit Graph
22501 Commits
Author SHA1 Message Date
Behdad EsfahbodandClaude Opus 4.8 95c3d1a80b [subset] Detect CFF charstring budget exhaustion at zero, not below
The shared CFF charstring budget is only ever spent through the
cs_interpreter_t interpret() cap, which clamps each glyph's operator
count to the remaining budget and charges back exactly what it
consumed.  By construction it never overshoots, so an exhausted
budget lands at exactly 0 rather than going negative.

The exhaustion checks therefore compare budget <= 0 (cff1 depend()'s
seac walk) and budget > 0 (the subset planner's seac-closure and CFF2
get_extents verdicts), not < 0 / >= 0, which that path can never
reach.  With < 0, cff1 depend() never failed, so
hb_subset_depend_from_face_or_fail() returned a result for an
adversarial font that exhausts the budget even though the equivalent
subset fails; that is the test-subset-cff1 shared-subrs case on CI
builds with -Dexperimental_api=true.  Document this at each check.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 19:25:04 -06:00
Behdad EsfahbodandClaude Opus 5.5 8d112d5b99 [subset] Share one CFF charstring budget across a whole subset
Each CFF / CFF2 charstring pass of the subsetter (seac closure, CFF2
extents for instancing, CFF2 usage and instancing passes, subroutine
subsetting with hint dropping, and flattening) created its own budget
with CFF::get_subset_budget(), so one subset could spend that budget
several times over, and the two CFF2 instancing passes reset it
between them.

Keep the budget on hb_subset_plan_t instead: cff_budget() sizes it on
first use from the table, as before, and every pass draws on the same
counter, so the total work of one subset is bounded once.  Retries of
a table with a larger serialize buffer draw on it too.  cff1 depend()
is not part of a subset plan and keeps its own budget per call.

Real fonts use about 1.5 operations per table byte per pass, against
a budget of 32 per byte (at least 2^24).  Tested: full meson test and
the subset suite; hb-subset on SourceSerif4Variable-Roman.otf (CFF2),
Roboto-Regular.otf (CFF), NotoSansCJKhk-VF.otf (30 MB CFF2) with
--gids='*' and --unicodes='*', with and without --no-hinting,
--desubroutinize and partial / full instancing, and on every .otf in
/Library/Fonts with --gids='*', all succeed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 19:25:04 -06:00
Behdad EsfahbodandClaude Opus 5.5 2f641844f2 [subset] Stop CFF subr walks at the call-depth limit instead of failing
The hint-dropping and subr-closure walks enforce kMaxCallLimit
themselves, because the recorded call graph can nest deeper than the
interpreter allows or be cyclic.  Hitting the limit failed the whole
subset, and the hint-dropping walk signalled it by writing -1 into the
shared work budget, conflating "too deep" with "out of budget" and
clobbering the budget for later passes.

Make both walks best-effort at the limit: the closure walk keeps the
subr it reached but does not walk into it, and the hint-dropping walk
does not walk into the subr and keeps the call and its hints.  Only
running out of the work budget fails the subset now, so
drop_hints_param_t no longer needs set_error() and the budget is only
ever touched by hb_budget_spend().  Walks that follow the
interpreter's path never reach the limit, so real fonts are
unaffected; for fonts whose records diverge the output may keep a few
hints or call a subr whose callees were not retained, but no longer
fails.

test_subset_cff1_subr_loop now also asserts that the subset succeeds;
it failed before this change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 19:25:04 -06:00
Behdad EsfahbodandClaude Opus 4.8 d473ca7030 [subset] Bound the CFF hint-dropping and closure walks
drop_hints_in_str()/drop_hints_in_subr() and the closure walk
(collect_subr_refs_in_str/_in_subr) recursively walk the subroutine
calls recorded for each glyph with no depth limit and no work budget.
The records need not match what the interpreter executed: a string is
parsed on its first run only, global subr records are shared across
Font DICTs whose local subrs differ, and endchar does not end a walk.
So the recorded call graph can nest deeper than kMaxCallLimit or be
cyclic, and a binary-tree subr structure makes the hint-dropping walk
expand exponentially.  A 360-byte CID font crashed the subsetter with
a stack overflow under --no-hinting (or hb_subset_preprocess), and a
~1 KB font ran unboundedly.  PR #6428 rejected stack-supplied call
operands but added no depth, cycle or work limit to these walks, so
these fonts were still affected.

Hold both walks to the interpreter's call-depth limit (kMaxCallLimit),
which stops the cycle and the long chain before the stack runs out, and
charge the hint-dropping walk to the subsetting pass budget introduced
for the shared-subroutine work, so the exponential expansion is capped
too.  A walk that follows the interpreter's path stays within both, so
only fonts whose records diverge from their execution are affected;
over either limit the subset fails, as other CFF planning failures do.

Adds test_subset_cff1_subr_loop, which subsets the 360-byte cycle font
with --no-hinting and only requires that hb_subset_or_fail() returns.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 19:25:04 -06:00
Behdad EsfahbodandClaude Opus 4.8 f4968616bb [CFF2] Charge the blend default values to the work budget
cff2_cs_opset_t::process_blend() walks all (k+1)*n values of a blend
(n default values plus k deltas each) but charged only the k*n deltas,
total - n.  With a VarData of regionIndexCount 0 (or no variation
store) k is 0, so `n blend` charges nothing, pops nothing, and the same
operands can be blended again and again for the price of two tokens.

Charge `total` = (k+1)*n, exactly what the loop touches.  spend_budget()
is a no-op without a caller budget, so only budgeted callers (draw,
extents, paint, shape, and the subsetter passes that now pass a budget)
are affected, and a well-formed charstring pays one extra unit per
blended value.

Adds test_hb_draw_cff2_blend_budget: a charstring that pushes 100
numbers and blends them 100 times over a region-less VarData must
consume at least 100 x 100 units and fail under a 5000-unit budget.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 19:25:04 -06:00
Behdad EsfahbodandClaude Opus 4.8 d4b4538e25 [CFF2] Charge blend region-scalar evaluation to the work budget
cff2_cs_interp_env_t::process_blend() evaluates one VarRegionList scalar
per entry of the VarData's region indices (up to 65535, each walking up
to axisCount axes) the first time a charstring hits `blend`, but the
only budget charge for blend is the operand-proportional one in
cff2_cs_opset_t::process_blend(), which runs afterwards and is skipped
when the operand check fails.  So `1 blend` did regionIndexCount x
axisCount scalar evaluations for one budget unit, and a VARC fan-out
re-ran it tens of thousands of times within 2% of HB_BUDGET_GLYPH.

Charge region_count x max(1, axisCount) through the env's existing
spend_budget() right before resizing and filling the scalars vector,
matching how VARC charges values x coords for its own
ItemVariationStore evaluations; a failed charge errors the interpreter
exactly as a failed resize does.  spend_budget() is a no-op without a
budget, so the subsetter and instancer paths are unchanged, and
seen_blend gates the work to once per charstring run.

Adds test_hb_draw_cff2_blend_region_budget: a CFF2 charstring blending
one value over 256 region indices of a 16-axis region list must consume
at least 256 x 16 units and fail under a 2048-unit budget.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 19:25:04 -06:00
Behdad EsfahbodandClaude Opus 4.8 f57127cfcb [subset] Share one CFF charstring work budget across a subsetting pass
Every per-glyph charstring loop in the subsetter (subr_subsetter_t::
subset, subr_flattener_t::flatten, the two CFF2 partial-instancing
passes, the CFF2 instance-metrics loop, and the CFF1 seac closure in
the plan and in the depend builder) created a fresh interpreter bounded
only by HB_CFF_MAX_OPS per charstring.  Glyphs can share subroutines,
so a font where every glyph makes one cheap call into a deeply nested
shared subr cost num_glyphs x ~200,000 ops: a 121 KB, 30,000-glyph font
took 33 s to subset (control 0.05 s).

Give each pass one cumulative counter, max(HB_BUDGET_SUBSET_CFF = 2^24,
32 ops per table byte), threaded through cs_interpreter_t::interpret()'s
existing budget argument exactly as the outline and extents paths do.
When it runs out, interpret() fails as it does for a single over-limit
charstring, so the CFF/CFF2 table fails to subset (the subset fails, as
any CFF planning failure has since dde7da182e); the seac closure fails
the plan and the depend builder fails.  The 32-ops-per-byte allowance
was measured against the in-tree corpus, where real fonts interpret at
most a few operations per CFF byte, so they stay far below it and
produce byte-identical output; the attacker font now fails in 0.17 s.

Adds test_subset_cff1_shared_subrs: four shared-subr glyphs subset
fine, while a hundred of them exhaust the budget and the subset (and
the dependency builder) fail.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 19:25:04 -06:00
Behdad EsfahbodandClaude Opus 4.8 24bf835d78 [subset/cff] Bound parsed subroutines by the table size before allocating
subr_subsetter_t::subset() resizes one parsed_cs_str_vec_t per Font DICT
to that DICT's localSubrs->count, assuming the sum is bounded by the
table.  It is not: any number of Font DICTs may point at the same
Private DICT and Subrs INDEX, so a 500 KB font with 16 Font DICTs all
sharing one 1000-subr INDEX cost about 1.6 GiB (measured: control 10
MiB, shared 1651 MiB; 2.8 GiB with hb_subset_preprocess).

Sum the global plus per-Font-DICT local subroutine counts in 64-bit
before any per-Font-DICT allocation, and fail the subset when the
records would exceed 256 bytes per byte of the source table, the same
ratio _hb_subset_table_try() uses to stop growing the output buffer.
A font whose Font DICTs do not share their Subrs needs at least one
table byte per subroutine, so it stays far below the limit; every
CFF/CFF2 font in the test corpus is at most a couple of bytes per table
byte.  Over the limit the subset fails, as any CFF planning failure has
since dde7da182e; the shared font now peaks at 7 MiB instead of 1.6 GiB.

The check sits before the allocations in the non-accelerator branch, so
it also covers the hb_subset_preprocess path and both CFF1 and CFF2
instantiations of the template; the --desubroutinize flattener path
does not allocate per subroutine and is unaffected.

Adds test_subset_cff1_shared_local_subrs: a 16-Font-DICT CID font with
1000 local subrs subsets when the subrs are unshared and fails when
every Font DICT shares them.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 19:25:04 -06:00
Behdad EsfahbodandClaude Opus 4.8 d8ca8b132d [subset/cff2] Budget the region transforms built for partial instancing
cff2_instancing_plan_t::create() builds k identity tuples of k cells
(then keeps a k-float column per surviving solver tuple) for every
entry of the CFF2 ItemVariationStore's VarData offset array, and
nothing bounded k (a 16-bit region count), the number of entries, or
their aliasing of one VarData.  The work is therefore quadratic in a
font field, so a 12 KB font cost 2.2 GB.

Charge those cells, before they are allocated, to a per-table budget
HB_BUDGET_SUBSET_CFF2_CELLS (2^24 cells) via the existing
hb_budget_spend helper, at both allocation sites (the k*k identity
tuples and the surviving solver columns).  Exhausting it fails create()
like any other planning failure, so the partial instance fails safely
(bounded at ~175 MB worst case) instead of exhausting memory.

Adds test_instance_cff2_vardata_budget: a 6.8 KB font with 40 offsets
aliasing one unused 800-region VarData must fail to partially instance
rather than build a region transform for each; it succeeds (keeping
CFF2 at hundreds of MB) before this change.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 19:25:04 -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 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