Commit Graph
3207 Commits
Author SHA1 Message Date
Behdad EsfahbodandClaude Opus 4.8 bbdde752f6 [test] Force the ot shaper in the layout budget tests
test_ot_layout_gpos_mark_base_rescan_budget calls hb_shape() with no
shaper forced, then asserts an OT-specific max_ops trip via
hb_buffer_allocation_successful().  Under the HarfRust shaper
(HB_SHAPER_LIST=harfrust, as the rust CI job re-runs the api suite)
it aborts, because harfrust shapes independently and never reaches
the C-side max_ops paths it tests.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-10 19:23:24 -06:00
Behdad 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 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 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
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 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 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 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 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 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 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 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 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
Wei-Lun Li 24ded4335b [font] Saturate synthetic bold and glyph origin arithmetic (#6585)
* [font] Saturate synthetic bold and glyph origin arithmetic

#6154 made hb_position_t arithmetic saturate and #6296 did the same
for synthetic_glyph_extents(), but the rest of hb_font_t still used
plain signed arithmetic:

- changed() computed the embolden strength with abs (x_scale), which
  overflows for INT32_MIN, and converted the float product to int
  without a range check. A strength of INT32_MIN could also not be
  negated later on, for negative scales.
- get_font_[hv]_extents(), the advance, origin and contour point
  getters added the strength with += and could overflow.
- add_offset(), subtract_offset() and apply_offset() overflow when
  they apply a large origin, and so do the origin fallbacks in
  apply_glyph_[hv]_origins_with_fallback().
- em_multf() converted its float result to hb_position_t without a
  range check, which is undefined for a value such as an ascender
  above the em at a scale close to INT32_MAX.

Use hb_saturate_add(), hb_saturate_sub() and hb_clamp_to() in these
places, and keep the strength away from INT32_MIN so that negating it
stays defined. Results that fit do not change.

The shift variables that were int are now hb_position_t, since the
saturating helpers deduce one type and int32_t is not int everywhere.

Tested with test-font under UBSan: the new tests fail on the base
commit at hb-font.hh:365, :848, :1154 and :1167, and pass here.

Assisted-by: Claude

* [test] Cover plural origins and synthetic slant saturation

Review feedback: the plural origin getters and the slant
clamp in get_glyph_contour_point were not covered by the
tests, so removing their saturation would still pass.

test_synthetic_bold_saturates now also calls
hb_font_get_glyph_h_origins and hb_font_get_glyph_v_origins
once each and checks both coordinates for INT32_MAX. A new
test_synthetic_slant_saturates sets a slant of 1 on a contour
point one short of INT32_MAX in both axes and checks that x
saturates to INT32_MAX.

Verified by mutation: replacing the plural hb_saturate_add
calls with plain addition makes the first test fail (the
value wraps), and dropping the hb_clamp_to in the slant path
makes the second fail (x comes out as -2). Full
meson test -C build: 270 ok, 0 fail, 7 skipped
(subset+repack, missing repacker dependency; same as the
baseline run for this PR).

Assisted-by: Claude

* [font] Apply the synthetic slant shift before clamping

get_glyph_contour_point clamped the slant shift to
hb_position_t before adding it to x. When x and the shift
have opposite signs and partly cancel, clamping first
changes the result: a contour point at x = -2000000000,
y = 2000000000 with a slant of 2 should land at
x = 2000000000, but came out as 147483647, because the
shift was clamped to INT32_MAX before the addition.

Add the shift first and clamp the sum instead. The
existing saturation case is unchanged: hb_clamp_to
widens to double to do the clamp, so an out-of-range sum
still saturates instead of hitting an undefined
float-to-int conversion.

The new test_synthetic_slant_cancelling covers the
cancelling case. Verified by mutation: restoring the
clamp-first order makes it fail with 147483647, the
reported value. Full meson test -C build: 270 ok,
0 fail, 7 skipped, same as baseline.

Assisted-by: Claude
2026-11-09 11:47:15 -06:00
Behdad EsfahbodandClaude Opus 4.8 c3fb304549 [subset] Only visit non-default UVS mappings in the DMAP cmap closure
cmap_accelerator_t::closure_glyphs() in the DMAP path expanded, for
every retained variation selector, all of the selector's Default UVS
ranges and resolved each code point with get_variation_glyph(). Any
number of 11-byte selector records may share one Default UVS table and
a 4-byte range covers 256 code points, so the work was bounded by
selectors x covered code points rather than by the table size: a 223 KB
font with 20000 selectors on one 168-range table drove ~860M lookups
and ~49 s of CPU in hb_subset_plan_create_or_fail().

A default mapping can only ever resolve to the nominal glyph, which the
subset plan already retains with the unicode itself, so the closure only
needs the code points that carry a Non-Default UVS mapping in cmap or
DMAP; get_variation_glyph() still decides which table wins for each.
This is exactly what the non-DMAP path (NonDefaultUVS::closure_glyphs)
already does. A collect_variation_non_default_unicodes() accessor is
added alongside the existing collect_variation_unicodes() chain
(VariationSelectorRecord, CmapSubtableFormat14_15, CmapSubtable,
cmap::accelerator_t) and used from the DMAP closure, so the work is one
lookup per 5-byte mapping visited.

No public API or ABI change; hb_face_collect_variation_unicodes() keeps
expanding Default UVS ranges as before, and fonts without DMAP take the
unchanged first branch. The reproducer's plan drops from ~49 s to 0.01 s
with the same 257-glyph result. The separate, older per-record
DefaultUVS::copy() serialization cost (~5.2 s for this font, independent
of DMAP) is left in place.

Adds test_subset_DMAP_shared_default_uvs to test/api/test-subset-cmap.c.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-08 14:36:19 -06:00
Behdad EsfahbodandClaude Opus 4.8 60bd82dcb4 [subset] Bound cmap per-record unicode set collection
When rewriting cmap, the subsetter built one hb_set_t of covered code
points per encoding record. SubtableUnicodesCache keyed those sets by
the record's own offset and collected each with num_glyphs = UINT_MAX,
so a font with many records sharing one full-range format 12 subtable
built one ~1.1M-code-point set per record: ~41 s of CPU, or ~2.1 GB of
memory for a 96 KB input, with nothing but the record count (bounded
only by the sanitizer) limiting the work.

Three changes bound it, all matching how nearby cmap code already works:

 1. Key cached_unicodes by record->subtable, so records sharing a
    subtable share one set (both set_for overloads).
 2. Give the cache a num_glyphs member and collect with it instead of
    UINT_MAX, as the cmap accelerator already does for
    hb_face_collect_unicodes; cmap::serialize fills it from
    plan->source->get_num_glyphs() and create_filled_cache() takes it
    as a parameter, passed as face->get_num_glyphs() for
    hb_subset_preprocess.
 3. Process only the first encoding record of each (platformID,
    encodingID) pair in both cmap::serialize and create_filled_cache
    (variation-selector records exempt). Lookup already sees one record
    per pair and EncodingRecord::copy links later records of a format to
    the first serialized subtable, so this bounds both the number of
    sets built and the _can_drop walk regardless of how many records a
    malformed font repeats, independent of whether they share a subtable.

No public API or ABI change. Output is unchanged for well-formed fonts:
the plan's unicodes are already restricted to gids below num_glyphs, and
valid fonts never repeat a (platformID, encodingID) pair. The attached
reproducer's hostile fonts drop from ~41 s / 2.1 GB to ~0 s / 12 MiB
with byte-identical output.

Adds test_subset_cmap_shared_subtable_many_records and
test_subset_cmap_repeated_encoding_records to
test/api/test-subset-cmap.c.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-08 14:36:19 -06:00
Behdad EsfahbodandClaude Opus 4.8 acdd1707a3 [cmap] Bound format 4 collect_unicodes/collect_mapping over overlapping segments
CmapSubtableFormat4::accelerator_t::collect_unicodes() and
collect_mapping() trusted the format's invariant that segments are
sorted and disjoint, so a subtable whose 32766 segments all cover
U+0000..U+FFFE was walked once per segment: ~2.1 billion insertions
(about 30 s of CPU) for a single hb_subset() or
hb_face_collect_nominal_glyph_mapping() call on a 262 KB font.

Both walkers now keep a cursor `next` past the last collected code
point and clamp each segment's start to it, skipping segments that end
before the cursor. Total work per subtable is therefore at most 65536
code points plus one step per segment, mirroring the ordering guard
CmapSubtableLongSegmented::collect_mapping() already has for formats
12/13. The glyphIdArray index is still computed from the raw
startCount[i], so range-offset segments map exactly as before, and
get_glyph() is untouched. Behaviour changes only for malformed
subtables: where sorted segments overlap the earlier segment now wins
the shared code points, and a segment lying wholly inside an earlier
one is ignored.

Adds test_collect_unicodes_format4_overlapping_segments to
test/api/test-collect-unicodes.c.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-08 14:36:19 -06:00
Behdad EsfahbodandClaude Opus 4.8 edf8de90d6 [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>
2026-11-08 14:34:15 -06:00
Behdad EsfahbodandClaude Opus 4.8 aad69a017b [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>
2026-11-08 14:33:10 -06:00
Wei-Lun Li d1520e8007 [GPOS] Clamp anchor coordinates when converting them from float (#6587)
Anchor coordinates are scaled as float, and apply_cursive_attachment()
and the mark attachment code converted them to hb_position_t with a
plain cast or an implicit conversion. A value out of range for the
target type makes that conversion undefined; on x86 it gives INT32_MIN.
#6154 made the additions around these conversions saturate, but not
the conversions themselves.

With NotoNastaliqUrdu-Regular.ttf at a scale of INT32_MAX, a cursive
anchor scales to 2.23e9, and the glyph ended up with an x_advance of
-2147483648.

Convert with hb_clamp_to(), and negate the cursive cross-direction
offsets with hb_saturate_neg(), since they can now be INT32_MIN.
Results that fit do not change.

Tested with test-shape under UBSan: the new test fails on the base
commit at CursivePosFormat1.hh:141 and passes here. No test reaches
the two conversions in MarkArray.hh; they are changed to match.

Assisted-by: Claude
2026-11-08 12:33:39 -06:00
Muhammad Abdullah Butt 9644ff2a0f [cmap] Don't clamp format 13 groups to num_glyphs in collect_unicodes (#6597)
CmapSubtableLongSegmented::collect_unicodes() and collect_mapping()
clamp the end of a group so that its glyph ids stay below num_glyphs.
That only makes sense for format 12, where the glyph id increases
across the group. In format 13 every code point of a group maps to the
same glyph, so the clamp cut each group down to a couple of code
points (Adobe Blank 2: 38 code points collected instead of 1,111,998).

Only clamp when the glyph id increases, and fix the clamp itself: it
kept one code point too many, mapping it to glyph num_glyphs.

Fixes https://github.com/harfbuzz/harfbuzz/issues/6591

Assisted-by: Claude
2026-11-07 17:06:07 -06:00
ebraminio 2f489784c8 [subset] Support longintdict encoding (#6584)
* [test] Expand CFF number font parsing to subsetter encoding roundtrip

* [subset] Support longintdict encoding

It was a TODO for the encoder and this implements it.

* [test] Move roundtrip parse encode to its own function

* [cff] Extract nibble_buffer_t to avoid heap allocated hb_vector_t

* [cff] Use '(size + 1) / 2' buffer size instead of asserting evenness

Address review

* [cff] Minor touches

* [cff] Use idempotent ensure_error instead of set_error

As review
2026-11-07 16:29:39 -06:00
Behdad Esfahbod 2823aad36c [subset] Reuse sanitized tables cached on the face (#6579)
* [subset] Reuse sanitized tables cached on the face

Use the face table list and SFINAE to borrow sanitized tables from
the source face. Add borrow_sanitized_table() to suitable accelerators
and reuse the COLR accelerator during closure. Keep fallback tables
in the subset cache without taking references for each access.

Cache full GSUB/GPOS sanitization separately from shaping's lazy
sanitization. Inline their no-op blocklist hooks so the subset library
can instantiate the accelerators.

Add regressions for repeated subsets and GPOS data that passes lazy
sanitization but fails full validation.

Tested with meson test -C build: 299 passed, 1 skipped. Also ran
reduced-feature syntax checks and ASan/UBSan with failing malloc.

Assisted-by: Codex

* [ot-layout] Remove unused GSUB/GPOS blocklist hooks

Both hooks always return false. Remove the hooks and their dead
conditional from accelerator initialization.

Tested with meson test -C build: 299 passed, 1 skipped.

Assisted-by: Codex

* [subset] Borrow GDEF before shaping's blocklist

Keep ownership of the unfiltered sanitized GDEF table in the face
accelerator, alongside the potentially blocklisted shaping view.
Subsetting can borrow it without repeating sanitization or taking
references for each access.

Allow static borrowing accessors to initialize accelerators inside
libharfbuzz. GDEF uses this to keep its hidden blocklist implementation
out of the subset library's initialization path. Other accelerators
retain their instance accessors.

Add a synthetic blocklisted-font regression checking that shaping
still ignores GDEF while repeated subsets preserve its glyph classes
without rereading it.

Tested with meson test -C build: 299 passed, 1 skipped. Also ran GCC
and reduced-feature syntax checks, plus ASan/UBSan with failing malloc.

Assisted-by: Codex
2026-11-04 17:05:57 -06:00
Garret RiegerandGemini a913b14e2c [cairo] Bound cluster walks in hb_cairo_glyphs_from_buffer() (#6578)
hb_utf_offset_to_pointer() walked `start` using `while (offset-- > 0)`
and `while (offset++ < 0)` without checking whether `start` had
reached `text + text_len` or `text`.  In addition, post-decrementing
`offset` in the first loop's condition left `offset == -1` after any
non-negative walk, causing the backward loop to execute one extra
`utf_t::prev()` step.  In hb_cairo_glyphs_from_buffer(), cluster
deltas in the `utf8_clusters` path could also advance `start` past
`utf8 + utf8_len`, or overflow `signed` when cast for
hb_utf_offset_to_pointer().

Check `start < text + text_len` and `start > text` in
hb_utf_offset_to_pointer() while adjusting `offset` inside the loop
bodies, and clamp each cluster delta in hb_cairo_glyphs_from_buffer()
to the remaining bytes in `utf8`.

Extend test_hb_cairo_glyphs_from_buffer_clusters in
test/api/test-cairo.c to cover multi-byte UTF-8 inputs on exact-sized
heap buffers and cluster deltas that exceed the string length or
overflow signed 32-bit integers.

Co-authored-by: Gemini <noreply@google.com>
2026-11-04 15:11:48 -06:00
Eugenio Depalo 2db1b3ab9d [buffer] Add deserializers with byte offsets (#6552)
* [buffer] Add deserializers with byte offsets

Buffer deserializers return a pointer into caller-owned input. GIR
describes it as an owned UTF-8 string, so bindings can free an
interior pointer or read beyond explicitly sized input.

Add _with_offset variants with bounded byte-array inputs and optional
byte counts. Preserve the existing return values and partial buffer
contents, including on failure. Cross-check both variants against the
existing deserializers in the buffer API tests.

Testing: full Meson suite, buffer tests under Valgrind, and GIR and
PyGObject checks.

Fixes: #6446
Assisted-by: OpenAI Codex

* [buffer] Rename new deserializers to use 2 suffix

Use the established 2 suffix for the new buffer deserializers,
following hb_shape_plan_create2(). Update API docs, NEWS, and tests.

Testing: full Meson suite, generated GIR, and PyGObject checks.

Assisted-by: OpenAI Codex
2026-11-04 12:05:35 -06:00
m00dy db1a1e9a36 [gvar] Reject glyph data offsets that wrap past 2^32 (#6556)
Slice the blob at dataZ, then slice the remaining bytes at the glyph
start offset. Chaining sub_array avoids a wrapping unsigned addition
and lets each slice clamp against the remaining length.

Keep test_subset_gvar_valid_data_offsets_control and
test_subset_gvar_data_offset_overflow_rejected unchanged.

Assisted-by: an AI coding assistant
2026-11-04 12:04:23 -06:00
Khaled Hosny bd306afedb [face] Ignore named-instance bits in hb_face_create_or_fail() (#6571)
Fixes: https://github.com/harfbuzz/harfbuzz/issues/6567
2026-11-04 12:02:49 -06:00
m00dy b269f9e1ad [font] Copy the default font-functions environment value (#6563)
The default cache borrows HB_FONT_FUNCS storage from the environment.
Copy its initial value with the existing lazy-loader conventions so
later changes to caller-owned storage do not change the default.

Preserve environment selection under HB_NO_ATEXIT. In that build the
copy has process lifetime; HB_NO_GETENV still uses the normal default.

Strengthen the coverage so an ignored environment value can no longer
hide behind the first backend: the environment test also checks that the
FreeType face is not selected when the default is ot, and a new
subprocess test selects ft, a non-first entry, before any font is
created.

The snapshot test fails before the library fix and passes afterward.
All 17 font API cases pass. The full suite has 276 passes and no
failures. A throwaway variant with the environment lookup stubbed out
fails the new nonfirst test, so the assertion does bite.

Assisted-by: an AI coding assistant
2026-11-03 15:18:24 -06:00
Behdad EsfahbodandClaude Opus 4.8 bcdf9c02a1 [test] Force the ot shaper in the AAT subtable-limit tests
CI re-runs the api suite under HarfRust (HB_SHAPER_LIST=harfrust),
which does not implement AAT, so test-aat-layout's new tests would
shape with no kern/morx applied and their subtable-count and
substitution assertions would fail.  The tests are inherently about
the OT/AAT shaper, so pin it via hb_shape_full (font, buffer, ...,
{"ot", NULL}), as the AAT additions to test-shape.c already do.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-02 10:52:07 -06:00
Behdad EsfahbodandClaude Opus 4.8 370a0da5a1 [aat] Merge equal-flag feature ranges per chain and budget AAT map compilation
hb_aat_map_t stored one range_flags_t per morx/mort chain for every
feature range, so memory and time were the product of a font-
controlled count (chains) and a caller-controlled count (ranges),
with no limit on either: a 304 KB font with 19000 chains and 5000
feature ranges peaked at 1.4 GiB.

mortmorx::compile_flags() now extends a chain's previous range entry
when the new range compiles to the same flags.  Ranges arrive in
order and contiguous and the consumers only look at flags per cluster,
so this is output-equivalent; it collapses every chain that does not
react to the features (and most do not) to a single entry.

A chain that does react still gets one entry per range, so also add
HB_BUDGET_AAT_MAP (in the existing hb_budget_spend() style) to
hb_aat_map_builder_t, charged per chain, per chain feature record
visited, and more heavily per stored range; hb_aat_map_builder_t::
compile() stops after the range that exhausts it and the existing
fix-up extends the last compiled ranges to the end of the text
(best-effort degradation, as other budgets do).  Only inputs whose
chains x ranges x features exceed ~16M, far beyond any real
font/document, lose their trailing ranges.  The budget member is
mutable because Chain::compile_flags receives the builder as const.

Adds two regression tests to test/api/test-aat-layout.c with a
hand-built feat+morx face.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-02 10:52:07 -06:00