Commit Graph
17281 Commits
Author SHA1 Message Date
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 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 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 Esfahbod 9baef4fc09 [aat] Place nodiscard before noinline on kerx action helper (#6600)
* [aat] Remove nodiscard from kerx perform_action

Clang rejects [[nodiscard]] after __declspec(noinline), which is
used by HB_NEVER_INLINE on Windows. Remove HB_NODISCARD from the
kerx format 4 action helper to fix Chromium's Windows build.

Reproduced the failure with Clang 21 and the Windows noinline
spelling; the same syntax check passes after the change.
meson compile -C build and meson test -C build pass (298 passed,
one skipped).

Assisted-by: OpenAI Codex <noreply@openai.com>

* [aat] Restore nodiscard before noinline

Place HB_NODISCARD before HB_NEVER_INLINE so [[nodiscard]] precedes
__declspec(noinline) on Windows. This preserves the return-value
check while avoiding Clang's attribute-ordering error.

Check all six action helpers; only kerx format 4 returns a value.
Keep the other five helpers' void signatures unchanged.

Clang and GCC syntax checks pass in C++11 and C++17. Clang checks
using the Windows noinline spelling also pass in C++17 and C++23.
The full Meson build passes, with 298 tests passed and one skipped.

Assisted-by: OpenAI Codex <noreply@openai.com>
2026-11-08 23:12:49 -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
Behdad Esfahbod 71d5df6158 [subset] Fix build after standard trait migration (#6599)
978afca2a removed hb_integral_constant, but four subset table-cache
tag-dispatch sites still used it. Both ordinary and amalgamated
builds fail as a result.

Use std::integral_constant at all four sites to complete the
migration and preserve the existing tag dispatch.

Validation: full Meson build and suite (298 passed, 1 skipped);
GCC and Clang C++11 world amalgamation builds with -Werror; GCC
C++11 HB_TINY core and subset compilation checks.

Fixes: 978afca2a ([meta] Use C++11 standard traits and numeric limits)
Assisted-by: Codex
2026-11-08 14:24:02 -06:00
Behdad Esfahbod 978afca2a9 [meta] Use C++11 standard traits and numeric limits (#6554)
* [meta] Use C++11 standard traits for constants and SFINAE

Replace the duplicated integral constants, boolean tags, enable_if,
and is_same with their C++11 standard counterparts. Use std:: types
at call sites and keep the convenience macros backed by standard traits.

Define hb_match_*::type directly to avoid ambiguity with the type
member inherited from std::integral_constant.

Validation: full Meson suite (298 passed, 1 skipped); six focused GCC
C++11 tests; Clang C++11 compilation checks.

Assisted-by: Codex

* [meta] Use standard type transformations and numeric limits

Keep the short hb_remove_const and hb_remove_reference aliases while
backing them with C++11 standard traits. Remove their unused matching
specializations.

Implement hb_int_min/max using std::numeric_limits. Require integral
types and retain the pointer-minimum specialization returning nullptr.
Parenthesize min/max calls for compatibility with platform macros.

Validation: standard Meson suite (298 passed, 1 skipped); GCC, Clang,
and 32/64-bit MinGW C++11 integer-bound probes with both char signs.
Native probes also link without the C++ runtime at -O0.

The isolated GCC C++11 debug suite passed 276 tests; check-symbols
exposed an existing ARRAY_LENGTH integral_constant value export,
reproduced with the previous commit's hb-meta.hh.

Assisted-by: Codex

* [meta] Remove unused pointer and rvalue reference helpers

Remove hb_add_pointer and hb_add_rvalue_reference along with their
overload helpers. They have no uses in tracked sources.

Validation: meson test -C build (298 passed, 1 skipped).

Assisted-by: Codex
2026-11-08 14:17:24 -06:00
Behdad Esfahbod b70acb123f [aat] Outline state-machine action handlers (#6598)
Keep per-transition bookkeeping in small always-inlined wrappers and
move the larger action bodies into never-inlined perform_action helpers
for all six morx/kerx state-machine contexts. Preserve mark-update order
and early exits when an action fails.

Adding a glyph-set update to ligature deletion enlarged the inlined
driver substantially. Outlining actions avoids duplicating those paths
inside the driver while keeping ordinary transitions cheap. Use the
standard inline attributes directly, including size-optimized builds.

Clang 21 Linux/x86-64 measurements improve the sampled Helvetica Neue,
Menlo, Lucida Grande, and Devanagari Sangam cases by about 1-3% at -O3
and 3-8% at -Oz. The action-heavy Geeza word-list case is a small
tradeoff at -O2.

The full default Meson suite passes: 298 tests passed and one skipped.
Separate -Oz shaping tests and GCC reduced-feature syntax checks pass.

Assisted-by: OpenAI Codex <noreply@openai.com>
2026-11-08 14:06:34 -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
ebraminio 4ed682d5ce Remove extra inline from static methods (#6582)
* Remove extra `inline` from static methods

Just being defined inside a struct is enough to make them inline.

* Add `inline` to hb-cff-specializer.hh functions

Discovered while writing a custom code having the header included.
2026-11-08 12:16:33 -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 ed2e62fa95 [algs] Share pow10 lookup between number parser and SVG serializer (#6596) 2026-11-07 17:03:05 -06:00
Michael Nosthoff 09aff9962a meson: order GPU compilation after shader header generation (#6590)
The shader header custom targets are built by default, but their outputs
are not included in the sources of libharfbuzz-gpu. This allows Ninja to
compile the GPU sources concurrently with shader header generation.

The generator also copies each generated header into the source directory.
The GPU sources use quoted includes, which find these source-tree copies
first. Since the copy truncates its destination before writing, a compiler
running concurrently can read an empty header and report undeclared shader
symbols.

Collect the shader header targets and add them to the GPU library sources.
Meson then orders compilation after those targets have completed, including
their copies back into the source tree.

Keep the existing build-by-default behavior unchanged.

Fixes: b1ad797e5 ("[gpu] Commit stringized shader headers; auto-regenerate like ragel")


Assisted-by: Copilot <223556219+Copilot@users.noreply.github.com>

Signed-off-by: Michael Nosthoff <buildroot@heine.tech>
2026-11-07 16:37:48 -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
Reilly Brogan 24439d01be [check-libstdc++] Only inspect direct DT_NEEDED entries (#6592)
ldd prints the full transitive dependency closure, so the check fails when a
dependency of a dependency links C++ (for example cairo -> fontconfig ->
libxml2 -> ICU), even though HarfBuzz itself has no libstdc++/libc++ NEEDED
entry. When readelf (or llvm-readelf) is available, inspect the library's own
(NEEDED) entries and check every exported library, including harfbuzz-cairo
and harfbuzz-icu. Without either tool, keep the ldd/otool closure check but
skip those two, whose closure is known to contain libstdc++.
2026-11-07 13:26:37 -06:00
Reilly Brogan 5a53654525 [tests] Fall back to llvm-objdump and llvm-nm (#6593)
Toolchains that ship only the LLVM binutils have no GNU objdump or nm, so
check-static-inits and check-symbols are skipped. Try llvm-objdump and
llvm-nm as fallbacks; their output is compatible with the parsing in these
checks. Also correct the check-static-inits skip message, which named ldd
instead of objdump.
2026-11-07 12:51:23 -06:00
Qunxin Liu 316e802222 [subset] Check context rule input glyphs against the GSUB glyph set (#6589)
Rule::subset (glyph-based Context format 1 rules) checked and mapped
input glyphs with plan->glyph_map, which also contains glyphs that are
only retained by later closures, e.g. glyf composite components. Rules
whose input glyphs can never be in the glyph run were therefore kept.

ChainRule::subset already checks against the GSUB glyph set. Use
plan->glyph_map_gsub, which maps exactly the GSUB glyph set to the same
new glyph ids, so both are consistent.
2026-11-05 12:33:46 -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
Khaled Hosny 3df40d9b98 15.1.0 2026-11-04 23:03:36 +02:00
ebraminio e1db1b215a [CFF] Fix trailing-zero exponent in BCD encoder (#6577)
Block 3 assumed exactly 3 trailing zeros (matching its "000" guard) and
then walked backward from len - 4, incrementing exponent on each step.
The two roles on one variable — start position AND final count — only
coincided when the mantissa had 3 leading digits, so any "X...0000"
with 4+ zeros was off by 10x or more:

  123000    -> "123E3"   (correct)
  1230000   -> "123E5"   (should be E4)
  12340000  -> "1234E6"  (should be E4)
  1000000   -> "1E7"     (should be E6)

Real fonts only produce fractional BCD values (0.001, 0.039625), so
this is latent, but it silently corrupts the output when triggered.

Fix: count trailing zeros from s + len - 1.  s[0] is guaranteed
non-'0' by blocks 1-2 ("0.xxx"/"-0.xxx"), so the backward scan
terminates before reaching s.

Also moves encode_byte(OpCode_BCD) past the nibble-buffer allocation
so OOM bails cleanly instead of emitting a marker with no digits.

Tests: 12340000.0, 1000000.0 (block 3 with 4+ zeros); 0.0012
(block 1->6); 1.23e-5 (block 4, negative exp); 123456780.0 (block 5,
newExponent==1); 0.000123, -0.000123 (block 1/2 -> 6 chain).
2026-11-04 14:59:07 -06:00
Koi 613f59727a [subset] Keep the format byte when serializing DeltaSetIndexMap format 1 (#6573)
* [subset] Keep the format byte when serializing DeltaSetIndexMap format 1

DeltaSetIndexMap::serialize() set u.format before calling the
format serializer, and DeltaSetIndexMapFormat01::serialize() then
calls extend_min(), which zero-fills the header. Format 0 survived
because its format value is 0, but a format 1 map (more than 65535
entries) came out with format 0, so readers took the upper half of
the 32-bit mapCount as a 16-bit count and lost the HVAR advance
deltas of the subset font.

Set the format inside DeltaSetIndexMapFormat01::serialize() after
extend_min(). Add a test-serialize case that checks both formats.

Fixes: https://github.com/harfbuzz/harfbuzz/issues/6440
Assisted-by: OpenCode

* [subset] Test DeltaSetIndexMap at the format boundary

Run the DeltaSetIndexMap serialize check with 65535, 65536 and 65537
entries so the <= 0xFFFF switch between format 0 and format 1 is
covered, and give the last entry a value no other entry has so a read
of the wrong entry is caught.

Assisted-by: OpenCode
2026-11-04 13:09:53 -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
ebraminio df9e6d1514 [number] Make _pow10 more accurate (#6555)
Replace the 9-constant composition (up to 6 multiplies, ~3 ULP) with
two precomputed tables: 10^0..10^15 exact, 10^16..10^304 rounded.
One multiply on the large side, ~2 ULP, no loop.

Prior to the two-table _pow10, these were computed by composing 10^n
from nine powers-of-10 constants.  Every constant above 10^22 carries
its own rounding error, and the six multiplications that build up a
typical exponent accumulated 2-3 ULP.  The two-table version reduces
this to a single multiply of two correctly-rounded constants and
lands within ~1 ULP of strtod.

Each case decomposes n = 16*q + r for a different (q, r), exercising
the (n >> 4, n & 15) split at different offsets in the tables.
Inputs are the simplest form that produces the same (q, r) as the
fuzzer-discovered failing inputs.
2026-11-02 13:06:07 -06:00
m00dy b8d093e607 Merge pull request #6557 from professor-moody/fix-cff1-glyph-to-sid-map-error-state-leak
[subset/cff1] Free a failed glyph-to-SID map created during subsetting
2026-11-02 13:00:26 -06:00
Behdad Esfahbod 5cb6cac5f7 Merge pull request #6505 from harfbuzz/scanner/repacker
[repacker] Fix an OOB write, an overflow-error crash, and six repacker DoS issues
2026-11-02 11:48:40 -06:00
Behdad Esfahbod 653467a9bc Merge pull request #6513 from harfbuzz/scanner/aat
[aat] Fix kern/kerx/mort/morx correctness bugs, a leak, and DoS hardenings
2026-11-02 11:42:21 -06:00
Behdad Esfahbod f34d3fbf87 [algs] Make ARRAY_LENGTH a constant expression for array references (#6553)
Use hb_array_length as an array trait deriving from integral_constant,
with an incomplete primary template to keep rejecting pointers. Have
ARRAY_LENGTH remove references and extract the trait's value without
evaluating the array expression.

This lets Arabic fallback use ARRAY_LENGTH directly for its ligature
table dimensions. Update the reference-parameter checks and verify that
side effects in the array expression are not evaluated.

Validated with a warning-free full Meson build and meson test -C build
(298 passed, 1 skipped). GCC and Clang C++11 checks cover the algorithms
test, Arabic shaper, HB_TINY amalgamation, cv-qualified and rvalue arrays,
debug linking, and rejection of pointer arguments.

Assisted-by: OpenAI Codex
2026-11-02 10:15:49 -07: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
Behdad EsfahbodandClaude Opus 4.8 cd570b6f54 [aat] Match morx language-tag features against ltag without interning the font's tags
Chain::compile_flags() resolved every type-39 (language tag) feature
record by interning the font's ltag string with
hb_language_from_string(), whose process-wide language list is a
linear, never-freed linked list meant for the handful of languages an
application passes in.  A font controls both the number of records and
the number of distinct tags, so shape-plan creation became quadratic
(about a minute for a 125 KB font) and the tags stayed in the list for
the life of the process.

Add ltag::matches_language(i, specific), which compares the tag bytes
directly against the buffer language, applying the same
canonicalization hb_language_from_string() does (at most 63 bytes,
lowercase, '_' to '-', stop at the first other non-alphanumeric) and
the same prefix rule as hb_language_matches(); each record now costs
at most the length of the buffer's language and nothing is added to
the global list.  get_language() is kept for the name table, which
genuinely needs an hb_language_t.  Behaviour is unchanged for every
real tag; only a degenerate tag with no valid leading byte, which used
to become the empty/invalid language, now matches nothing.

Adds a regression font to the in-house aat-morx tests whose type-39
features gate substitutions by tags 'sr' and 'Zh_Hant', exercising
case folding, '_' canonicalization, subtag prefix matching and
non-matches.

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

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