Commit Graph
22491 Commits
Author SHA1 Message Date
Behdad EsfahbodandClaude Opus 5.5 46f738b7af [subset] Document that the avar2 range budget fallback is safe
Running out of HB_BUDGET_SUBSET_AVAR2_RANGES returns early from
_compute_avar2_reachable_ranges() and records nothing for the
remaining axes.  That does not produce a wrongly instanced font:
avar2_reachable_ranges is only used to cull variation data that
cannot be reached, and an axis without a range is never culled
(_hb_avar2_region_is_dead() skips it, the same as the VARC path that
resets the map).  A pinned axis that is not detected as
self-contained stays in fvar as a hidden pin, which is what CFF2
fonts always get.  The output is correct, only larger.  Likewise the
exact-grid fallback uses interval bounds, which are conservative.

Say so in the comments instead of "left unconstrained".

Tested: meson test -C build (278/278); hb-subset --instance
wght=400 and wght=300:700 on GoogleSansFlex, NotoSansKR and
SourceSerif4 variable fonts, all glyphs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 17:37:31 -06:00
Behdad EsfahbodandClaude Opus 4.8 10fa66cdd4 [subset] Guard against null glyf blob in contour-point budget
get_instance_glyphs_contour_points() sizes its op budget from the
source glyf table length.  When head.glyphDataFormat (or
indexToLocFormat) is out of range the glyf accelerator is disabled and
reference_glyf_table() returns no blob, so hb_blob_get_length() then
dereferenced a null pointer and crashed during partial instancing.

Take the length only when the blob is non-null.  Add a regression test
that builds a variable font with an invalid glyphDataFormat and plans a
partial instance.

Reported by Anthropic's OSS Scanner.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 16:36:35 -06:00
Behdad EsfahbodandClaude Opus 4.8 69680c7b4c [subset] Budget the avar2 reachable-range computation
_compute_avar2_reachable_ranges() bounded only the breakpoint grid
(MAX_GRID = 16384 vertices), while its real work is
axes x vertices x active row columns x tents. A delta-set row may list
the same region tens of thousands of times, and a clamped
DeltaSetIndexMap lets every fvar axis share that one row, so a 50 KB
font cost about two minutes of CPU per hb_subset_plan_create_or_fail().

Charge one shared allowance per plan, HB_BUDGET_SUBSET_AVAR2_RANGES, at
the three places the work is created: scanning the row's columns into
the active set, collecting each active region's tents, and the exact
grid enumeration (charged up front as grid_size x (active + tents)).
Degradation reuses states the surrounding code already handles: an axis
whose exact enumeration does not fit takes the existing
interval-arithmetic bounds (still conservative, so the instance stays
correct), and once the allowance is gone the remaining axes are left
unconstrained. The hostile fonts now finish in well under a second;
real avar2 fonts use a small fraction of the budget and their
output is unchanged.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 16:36:35 -06:00
Behdad EsfahbodandClaude Opus 4.8 d1e8c1079d [subset] Budget the glyf points a plan keeps for partial instancing
For partial instancing the subset plan decodes every retained glyph
through Glyph::get_all_points_without_var() and keeps all the points in
plan->new_gid_contour_points_map until the plan is destroyed. That
caller passed no work budget, and nothing capped the total. A simple
glyph of repeated flags declares ~65536 points in ~526 bytes, and a
loca whose offsets alias one another lets many glyph ids share those
bytes, so a 25 KB font drove plan creation to 2.2 GB.

PR #6256 added a charge-before-allocate budget to
SimpleGlyph::get_contour_points() and passed it from the draw/extents
path, but left this subsetter caller unbudgeted. Give the loop one
plan-wide budget, the larger of HB_BUDGET_SUBSET_CONTOUR_POINTS and the
source glyf length, and charge each glyph's decoded points after it is
decoded. One glyph's decode is bounded by the format (about 786 KB),
so the transient is proportional to the input; the budget bounds what
the plan retains. Exhausting it fails plan creation, the same outcome
as any other decode failure in this loop. Ordinary glyph data carries
at least one byte per point, so the size-derived bound does not
constrain well-formed fonts.

Adds an API regression test (test_subset_gvar_shared_glyph_data) with
an aliased loca over a 65536-point simple and composite glyph.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 16:36:35 -06:00
Behdad EsfahbodandClaude Opus 4.8 224fca316c [subset] Budget the dense per-point expansion of gvar/cvar tuples
create_from_tuple_var_data() expands every tuple to arrays with one
entry per point of its glyph (per cvt value), however few points the
tuple actually names, and keeps them until the table is serialized. The
tuple count (12-bit) and point count (16-bit) are each bounded per
glyph, but their product and its sum over the table are not, and neither
factor costs many font bytes: 15 bytes of gvar can expand to ~590 KB,
and a 31 KB font reached 2.1 GiB.

Give the decode a per-table points budget,
HB_BUDGET_SUBSET_TUPLE_POINTS_FACTOR per byte of the source table
floored at HB_BUDGET_SUBSET_TUPLE_POINTS_MIN, owned by
glyph_variations_t for gvar and a local in cvar::subset(), and charge
point_count per decoded tuple before expanding it. Exhausting it
returns false exactly like the function's existing allocation-failure
paths (the table is dropped from the subset). Real gvar tables
expand to only a small multiple of their byte size, so the factor
leaves ample headroom. The extra copies made when a range limit splits
a tuple are already bounded by the instancer split budget in
optimize_scratch_t, so they are not charged here again.

Adds a unit test (test_tuple_points_budget) covering the decode charge.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 16:36:35 -06:00
Behdad EsfahbodandClaude Opus 4.8 171a4fa59f [instancer] Budget tuple splitting when narrowing axes
Narrowing an axis makes change_tuple_variations_axis_limits() replace
every tuple whose region uses that axis with up to six tuples
(rebase_tent solutions), axis after axis with no merging, so one region
spanning N narrowed axes becomes up to 6^N tuples, each with its own
copy of the axis map and deltas. A 364-byte font with a region on 8
narrowed axes drove one hb_subset_or_fail() call to 9 s of CPU and
1.7 GB. The only existing limit, the subset output buffer cap, is
checked after the whole instantiation has run.

Charge the copies to a cumulative budget held in optimize_scratch_t,
which every caller (gvar, cvar, CFF2, and item_variations_t for
GDEF/HVAR/MVAR/BASE/COLR) already keeps for one whole table. The budget
starts at HB_BUDGET_INSTANCER_MIN and earns HB_BUDGET_INSTANCER_FACTOR
times the cost of each source tuple; each split spends
out[0].get_cost() x (out.length - 1) through the existing
hb_budget_spend() helper, and the function returns false when the
budget is spent, which all callers already treat as failure. The cost
(32 + 8 per axis + 1 per row/point) scales with what a copy allocates
for both ItemVariationStore and gvar tuples, so the budget also bounds
a store with many VarData and a gvar with many glyphs.

An instancing request whose splits exceed the budget (roughly more than
64 copies per source tuple beyond a 4M-unit floor) now fails instead of
producing a store that could not be serialized anyway. Normal fonts
stay far below the floor, so the subset suite's partial-instance
tests are byte-identical.

Adds a unit test (test_tuple_split_budget) with a tent on 16 axes.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 16:36:35 -06:00
Behdad EsfahbodandClaude Opus 4.8 52152cbf97 [subset] Bound the dense delta matrix when rebuilding a VarStore
item_variations_t::as_item_varstore() allocates one int per
(row, region) pair for the whole rebuilt ItemVariationStore, every row
as wide as the full region list. In the font a row only pays for the
regions of its own VarData (possibly none, and several dataSets offsets
may share one VarData), so the row count and the region count are
independent and their product is unbounded: a ~120 KB font drove the
allocation to 2.4 GB, and a 972-byte font with region-less rows to
~800 MB.

Bound the matrix before allocating it, at the single site all
instancing callers (MVAR, HVAR/VVAR, GDEF, BASE, COLR, avar) pass
through: HB_SUBSET_MAX_VARSTORE_ROWS (1<<21, which also bounds the
per-row hb_vector_t overhead and catches the zero-width-row variant)
and HB_SUBSET_MAX_VARSTORE_DELTAS (1<<26 cells, 256 MB of int),
computed in 64-bit. These are flat ceilings on this one allocation
rather than a bound proportional to the source size: optimizer output
routinely has several VarData over disjoint region subsets, so the
dense matrix is legitimately much wider than any single VarData and a
proportional bound would reject it. No store in the test fonts comes
near the cell cap. Returning
false is the path a failed resize() already takes, and every caller
drops the table on it. Rows are fixed-width, so they are now allocated
with resize_exact(), removing the ~19% growth slack per row.

The cap bounds the amplification rather than removing it (a ~75 KB
font just under the cell cap still peaks around 265 MB); the
structural follow-up is to stop making every row as wide as the whole
region list.

Adds a unit test (test_delta_matrix_limits) covering both caps and an
under-cap case.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Assisted-by: DeepSeek

* [subset] Refine hint-dependent font detection

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

Assisted-by: DeepSeek

* [perf] Add NO_HINTING subset benchmarks

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

Assisted-by: DeepSeek

* [subset] Allow unaligned and unpadded checksum data

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

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

Assisted-by: DeepSeek

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

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

Assisted-by: DeepSeek

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

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

Assisted-by: DeepSeek

* [test] Validate checksums against Python-generated vectors

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

Assisted-by: DeepSeek

* [test] Drop the checksum vector generator

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

Assisted-by: DeepSeek

* [subset] Use CheckSum::CalcTableChecksum directly

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

Assisted-by: DeepSeek

* [subset] Release the sanitized name table

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

Assisted-by: DeepSeek

* [subset] Limit cache enum scope

* [subset] Use dagger iteration for hint lists

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

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

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

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

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

Follow-up to #6490

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

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

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

Removes hb_ft_font_t::selected_palette and both of its assignments.

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

---------

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

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

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

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

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

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

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

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

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

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

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

Follow-up to #6513

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

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

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

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

Assisted-by: OpenAI Codex

---------

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

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

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

Follow-up to #6521

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

No behavior change.  Tested with meson test.

Follow-up to #6483

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

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

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

Follow-up to #6513

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

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

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

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

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

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

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

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

Testing: meson test -C build: 278 OK.

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

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

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

Follow-up to #6501

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

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

Follow-up to #6487

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

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

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

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

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

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

Follow-up to #6499

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

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

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

Follow-up to #6513

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

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

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

Follow-up to #6500

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-09 13:17:50 -06:00
Behdad EsfahbodandClaude Opus 4.8 9f9055ee97 [VARC] Charge MultiItemVariationStore delta lookups per region walked
VarComponent::get_path_at() precharged axisValues.length x coords.length
before MultiItemVariationStore::get_delta(), but the work that call does
is one iteration per entry of the selected MultiVarData's regionIndices
(up to 65535) plus, for each region not yet in the scalar cache, one
evaluation per axis record (up to 65535).  With no variation coordinates
the precharge is zero, so a 148 KB font could drain the 2^24 glyph
budget 65535 times too slowly: about 20 minutes of CPU for a single
extents or draw call, reachable from plain hb_shape() on vertical text
or fallback mark positioning.

Thread the session budget (the same c.budget every other VARC charge
site spends) through the three MultiItemVariationStore::get_delta()
overloads into MultiVarData::get_delta(), which charges (1 + out.length)
per listed region before the walk, and into
SparseVariationRegion::evaluate(), which charges one unit per axis
record before an uncached region is evaluated.  This is the code that
knows the real cost, so the charge is exact rather than an estimate.
The three VARC call sites (axis-value deltas, transform deltas, and the
MultiItemVarStoreInstancer used for component conditions) pass &c.budget
and bail out once it goes negative, replacing the old values x coords
estimates.

All new parameters default to nullptr, so the instancing and subsetting
callers are unaffected; no public API or ABI changes.  A unit test in
src/test-item-varstore.cc pins the exact per-region and per-axis charge
and the bail-out once the budget is negative.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-09 13:17:50 -06:00
Behdad EsfahbodandClaude Opus 4.8 9ddb3d0f24 [VARC] Bound the glyph records walked during subsetting to the INDEX size
closure_glyphs(), depend() and varc_subset_plan_t::collect_glyphs()
each decode the full glyph record of every glyph id they reach,
assuming every glyph has its own record.  Nothing enforces that:
CFFIndex::sanitize() accepts overlapping glyphRecords offsets, and a
Coverage table may map many glyph ids to the same INDEX entry, so N
glyph ids can resolve to one large record and the walk does N times
that record's work -- quadratic in the font size (44 s for a 245 KB
font), charged to no budget.

In a well-formed table the records are disjoint and each glyph is
visited once, so the bytes of all records walked cannot exceed the
glyphRecords INDEX.  Enforce exactly that invariant where the records
are fetched, in all three walks, failing through each site's existing
idiom.  The remaining work is linear: a component decodes only if its
record holds at least one byte per 64 counted axis values.

In collect_glyphs() this also replaces the saturating sum and the
post-loop data_size != UINT_MAX test, which a 64-bit build bypasses
because hb_unsigned_add_saturate() returns size_t and the sum truncates
into the unsigned data_size (a near-4 GiB total stored as a small
value); the running total is now checked after every addition.

Overlapping VARC records, already malformed per the CFF INDEX spec, now
fail subsetting instead of being accepted; shaping and drawing are
unaffected and valid VARC fonts subset to byte-identical output.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-09 13:17:50 -06:00
Behdad EsfahbodandClaude Opus 4.8 ace1c824d4 [VARC] Use a work stack in closure_glyphs() instead of an hb_set_t (#6566)
closure_glyphs() used an hb_set_t as its work queue, popping the
minimum with get_min() and removing it with del().  del() clears the
bit but keeps the emptied page in the set, and both get_min() and the
while-loop condition rescan from the first page every time, so each pop
rechecks every page emptied by earlier pops.

Components flagged GID_IS_24BIT carry 3-byte glyph ids, and the closure
queues them without checking the face's glyph count (invalid ids are
only dropped afterwards), so a font can spread the queue over all 32768
pages and make each pop cost up to 65536 page checks.  A 400 KB font
whose .notdef composite references one gid per page burns ~6.5 s of CPU
for any subset request, growing ~21 s per further MB.

Replace the set with an hb_vector_t used as a LIFO stack: glyphset
already records which gids have been seen, so nothing is queued twice,
and push()/pop() are O(1) with no page rescans.  The hostile font now
subsets in the same ~0.02 s as a benign font of the same size.

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

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-09 13:17:46 -06:00
Behdad EsfahbodandClaude Opus 4.8 59f4f1a55a [subset] Variable-font instancing subset-output correctness fixes (#6564)
* [instancer] Walk MVAR value records at the source valueRecordSize

MVAR::subset() copied the source valueRecordSize into the output
header but then walked the source array with a typed
VariationValueRecord pointer (8-byte stride) and embedded 8 bytes per
record. For a font whose MVAR uses value records longer than 8 bytes
(valueRecordSize > 8, which the spec and MVAR::sanitize() allow), every
record after the first was read from the wrong offset and the emitted
header described a record array that overlaps the table's own
ItemVariationStore, silently losing metric variations on partial
instancing.

Step through the source records with StructAtOffset at the table's own
valueRecordSize stride, the same way sanitize() and get_var() do, and
declare VariationValueRecord::static_size in the emitted header so it
always matches the 8-byte records that are written. Output for the
usual 8-byte fonts is byte-identical.

Adds a subset regression test (mvar_partial_instance_record_size) built
from NotoSans-VF.abc with its MVAR records re-padded to 12 bytes; its
expected instanced output is byte-identical to the 8-byte
mvar_partial_instance wght=300:600 file and it fails on the unpatched
tree.

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

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

* [subset] Don't retain ItemVariationStore rows the source lacks

The subset plan turned every variation index collected by the COLR,
GDEF and BASE closures into a row to keep, checking only the outer
index against the subtable count and never the inner index against
VarData::itemCount. A font could therefore name tens of thousands of
rows in a VarData whose itemCount is 2, and partial instancing then
sized its work from that inflated row count, allocating
regionIndexCount x rows x 5 bytes (3.2 GB from a 240 KB COLRv1 font).

generate_varstore_inner_maps() now takes the store and keeps only rows
that ItemVariationStore::has_delta_set() confirms exist, and
remap_variation_indices() maps such an index to
HB_OT_LAYOUT_NO_VARIATIONS_INDEX without consuming a new row. That
preserves the runtime meaning of an out-of-range index (delta 0) and
keeps the two functions in step; all consumers already handle the
sentinel. This covers the COLR, GDEF and BASE callers. Well-formed
fonts are byte-identical.

The HVAR/VVAR route noted in the report (its planner builds row maps
itself, one per retained glyph) is left for a follow-up: folding the
missing rows into a shared zero row changes the output form of a
map-less HVAR whose glyph count exceeds the store's itemCount, which
is better landed on its own.

Adds an API regression test (test_subset_colr_phantom_rows) that fails
on the unpatched tree.

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

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-09 13:08:56 -06:00
Behdad Esfahbod a01588aad7 Merge branch 'main' into scanner/instancer-fix 2026-11-09 13:06:22 -06:00
ebraminio f33d54ecf9 [subset] Preserve glyph ids for retained glyph-bearing tables (#6586)
The subsetter cannot rewrite tables that refer to glyphs. That includes
legacy kern, AAT (ankr, bsln, just, kern, kerx, lcar, mort, morx, opbd,
prop), Graphite (Glat, Gloc, Silf), JSTF, SVG, LTSH, EBDT/EBLC, and
Apple's Zapf, bdat/bloc, gcid, and hvgl/hvpm tables. When one of these
is retained it is passed through unchanged, so renumbering glyphs makes
its glyph ids stale. Implicitly enable retain-gids in that case.

Make the plan use its own flags after this adjustment so every consumer
sees the effective retain-gids state, and add regression tests covering
AAT, Graphite, and the other unsubsettable glyph tables.

Assisted-by: DeepSeek
2026-11-09 13:04:53 -06:00
Behdad EsfahbodandClaude Opus 5.5 a86ba5f203 [cairo] Remove work-budget accounting (#6602)
hb-cairo hands the actual rendering to cairo, so the work done per
paint operation (clip, gradient, compositing) is cairo's, not ours.
Any count we keep is a guess.  The guesses we had were not good:
022a9e475 charged each paint
(1 + clip + path segments) x max(weight, segments), with a weight of
up to 8192, against HB_BUDGET_GLYPH.  Real fonts blow through that.
For example, hb-view renders the Spain flag in Noto-COLRv1 (U+1F1EA
U+1F1F8) as a blank image, and about ten glyphs in that font go over.

Remove the budget accounting from hb-cairo:

  - Revert 022a9e475 "[cairo] Charge compositing operations to the
    glyph budget", with its test font and generator.
  - Revert 8f3ab5ab8 "[cairo] Share work across nested glyph
    rendering": the per-scaled-font hb_cairo_budget_t, the segment
    charges in the draw callbacks, and the set/get budget callbacks
    on the cairo draw and paint funcs.

Keep paint_color_glyph declining (fd8c9209b), so COLR paints nested
glyphs inline under the decycler and nesting limits of the walk in
progress.  Going through cairo_show_glyphs() again would bring back
the PaintColrGlyph cycle crash, which test_hb_cairo_color_glyph_cycle
covers.  Only the code comment loses its mention of work limits.

Testing: meson test -C build: 299 OK, 1 skipped.  The Spain flag
renders again, and the PaintColrGlyph cycle glyphs in
test_glyphs-glyf_colr_1.ttf render without crashing.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 13:00:15 -06:00
Behdad Esfahbod 970e231199 [subset] Merge main and resolve COLR regression test conflict
Both branches appended independent regressions to test-subset-colr.c.
Keep the phantom variation-row checks alongside main's overlapping
CPAL palette checks, and register both tests.

Validation: meson compile -C build; meson test -C build.

Assisted-by: OpenAI Codex
2026-11-09 12:52:43 -06:00
Behdad EsfahbodandClaude Opus 4.8 f9b16b40e0 [subset/CPAL] Bound retained color records before copying (#6518)
CPAL::subset() copies the retained colors once per distinct
colorRecordIndices start and later writes distinct-blocks x
retained-colors into the 16-bit numColorRecords, but nothing bounded
that product. CPAL palettes may overlap in the color-record array, so
a well-formed 280 KB font with 20000 palettes of 20000 colors made a
single hb_subset_or_fail() hold ~1.5 GiB of copies and burn ~29 s of
CPU (rebuilt on each out-of-room retry) before failing; smaller
products silently wrapped numColorRecords and the per-palette start
indices in the emitted table. This is a regression from 95ba91721
(#6285, "Share color record blocks between identical palettes").

Fail before copying, at the top of the per-start loop, once one more
block of retained colors could no longer be counted in the 16-bit
numColorRecords, via check_assign() with HB_SERIALIZE_ERROR_INT_
OVERFLOW. This caps the copy-and-hash work, the heap and the
serialized size at 65535 records, and makes the two 16-bit
assignments provably safe, which resolves and removes the
"limit total final size" TODO in serialize(). Palettes that do not
overlap can never reach the limit, since their distinct starts times
numColors already fit in the source numColorRecords.

Trade-off: the bound counts distinct starts, not distinct dedup
blocks, so a font whose many overlapping palettes would all collapse
into a few shared blocks is also rejected past the limit. Pre-#6285
code wrapped on those inputs anyway.

Adds test_subset_cpal_overlapping_palettes asserting the 218-vs-219
palette boundary (65400 records accepted, next rejected).

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

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-09 12:43:27 -06:00