#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>
#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>
#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>
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>
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>
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>
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
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>
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>
* [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
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>
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>
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>
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>
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>
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
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
* [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
* [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
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>
* [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
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
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
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>
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>
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>
The per-subtable glyph sets built by the morx/kerx chain accelerator
assume LookupFormat2 segments are sorted and disjoint, but the
sanitizer does not check that, so a malformed table can repeat a
segment spanning the whole glyph range tens of thousands of times,
and every subtable pointing at it pays a full bit-set pass per
segment -- 300 subtables sharing one 65000-segment lookup stalled
shaping two letters for over 20 seconds.
Make LookupFormat2::collect_glyphs{,_filtered} track the end of the
last range added and, at the first segment that is out of order, fold
every remaining matching segment into a single add_range. For
well-formed fonts the result is identical; for malformed ones it is a
superset, which is safe because the set is only an intersects()
pre-filter. collect_glyphs() now shares the filtered implementation
with an always-true filter. Formats 4/6/8/10 cannot amplify this way
and are untouched.
Adds a morx font with unsorted format-2 segments to the in-house
aat-morx shape tests, checking the subtable still applies.
Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-A0RYWLIT.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A kerx format-4 control-point action asks the font for two glyph
contour points, which the font functions may satisfy by loading the
whole glyph outline (two full FT_Load_Glyph calls with hb-ft). The
state-machine driver charges a non-advancing transition only one op,
so a looping entry turned the whole work budget into glyph loads:
two letters and a 680-byte font stalled hb_shape() for seconds.
Charge 2 * HB_BUDGET_256 to buffer->max_ops at the action, before the
callbacks, using the same decrement-and-return idiom morx insertion
uses; once the budget is spent the action is skipped and the driver's
existing max_ops check forces the machine forward.
The sibling GPOS AnchorFormat2 contour-point path has the same
uncharged callback but lives in the layout subsystem and is left for
a separate change. GDEF CaretValueFormat2 also calls it but only
from hb_ot_layout_get_ligature_carets, bounded per API call.
Regression test in test/api/test-shape.c uses a counting
glyph_contour_point callback on a builder-made looping kerx font
(131074 calls before, <= 256 after).
Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-EE451WE1.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The kern/kerx accelerator keeps two hb_bit_set_t per subtable and
mort/morx keeps one per subtable, all built eagerly when the shape
plan is compiled and held for the life of the face. A 14-byte kern
format-3 subtable fills both sets with every glyph, so heap use was
about 2100x the font size with nothing bounding the subtable count;
morx is worse because overlapping chains can claim each other's
subtables. A ~560 KB kern font drove shaping one letter to 1.1 GiB.
Add HB_AAT_MAX_SUBTABLES (1024) to hb-limits.hh and enforce it in
sanitize, the way GSUB/GPOS already bound their subtables via
visit_subtables (whose 0x4000 limit is too loose here -- 16383 kern
subtables still peak at hundreds of MiB). KerxTable::sanitize()
(shared by kerx, OpenType kern and Apple kern) fails when tableCount
exceeds the limit, and mortmorx::sanitize() fails once the chains'
subtable counts add up past it. Over-limit tables are dropped
entirely (the font shapes without kerning/morx); real fonts under
test/ declare at most three kern/kerx subtables and one morx chain.
Regression test in test/api/test-aat-layout.c builds kern and morx
faces with hb_face_builder and checks both sides of the limit.
Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-5N52Y0UN.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
hb_accelerate_subtables_context_t::dispatch() filled accelerator
entries with a counter that advanced only for the subtable types
ChainSubtable::dispatch() knows, while Chain::apply() reads entries by
subtable position. A subtable of a reserved type (3, or 6 and up),
which the sanitizer accepts and apply() steps over, shifts every later
entry down by one, so each later subtable is gated by the wrong glyph
set and the last one gets a zeroed entry and is never applied. Output
then depends on where the unknown subtable sits in the chain.
Add Chain::accelerate(), the same walk Chain::dispatch() does but
setting the context's index to the subtable position before each
dispatch, and stop the context's dispatch() from advancing the index
itself; create() calls accelerate() instead of dispatch(). Unknown-
type subtables keep a zeroed entry, which is what the calloc in
create() already relies on, and apply() does nothing for them anyway.
mort shares Chain/ChainSubtable so it is fixed too; the kerx
accelerator already fills one entry per subtable and is untouched.
Adds a regression font with subtables [reserved, 1->2, 3->1] to the
in-house aat-morx shape tests.
Reported by Anthropic's OSS Scanner as ordinary bug ANT-2026-OIN1GIHX.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
tables with a non-first initial state are accepted
AAT::StateTable numbers the rows before the initial 'kern'/'mort'
row negatively (the Apple stateArray quirk the code documents), but
the negative branch of sanitize() passed the negative int min_state
to hb_unsigned_mul_overflows() and used it in unsigned index
arithmetic, so the overflow check always fired and such tables were
always rejected and silently dropped. get_entry() indexed the state
array the same unsigned way and would read far past it had sanitize()
let those tables through, so the two functions have to be fixed
together.
sanitize() now works with the magnitude of min_state
(num_neg_states = -min_state) for the overflow check, the
check_range() and the sweep pointer, and get_entry() computes its row
index in signed int so negative states address the rows before the
initial one. Negative states only arise for ObsoleteTypes, where
nClasses and offsets are 16-bit so the products fit; for ExtendedTypes
states are never negative and sanitize() already bounds
(max_state+1)*nClasses by the blob size, so the (int) casts cannot
change any sanitized index.
Fonts whose 'kern' format 1 / 'mort' state tables use a non-first
initial state now sanitize and apply instead of being dropped. Adds
a regression test (kern-format1.tests plus its font) to
test/shape/data/in-house.
Reported by Anthropic's OSS Scanner as ordinary bug ANT-2026-FM7UTB3Y.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
tuple_variations_t::_cmp_axis_tag() subtracted two axis tags as int.
The tags come from the font, so tags far apart in signed range, such
as one with the high bit set, overflow the subtraction during partial
instancing. UBSan reports signed-integer-overflow from
change_tuple_variations_axis_limits(). The wrapped result also makes
the comparator inconsistent, for a sort that exists to keep the
result deterministic.
Use _hb_cmp_operator<hb_tag_t, hb_tag_t>, as other sorts in the tree
do, and drop the local comparator. Printable ASCII tags keep their
order, so valid fonts are unaffected.
Testing: added a 1074-byte fuzzer seed that fails under UBSan without
the fix. meson test -C build-asan passes 100/100 with
-Db_sanitize=address,undefined -Dexperimental_api=true. The build had
no glib, so test/api did not run.
Assisted-by: Claude
A shifted default can leave fractional contour coordinates that round to
identical positions in glyf. Selecting IUP references against those
fractions can omit deltas that no longer interpolate correctly after
serialization. The reported four-point case loses 499 units.
Round the real contour points after merging default deltas and before
selecting IUP references. The gvar caller already uses a private point
copy, so the plan's coordinates and metric calculations stay intact.
Leave the four phantom points unrounded.
Add a tuple-store regression covering both axes and signs, and regenerate
six affected subset expectations. The reported fixture now reconstructs
exactly. All nine checked optimized fixtures stay within the existing
0.5-unit tolerance against optimization-disabled output, with unchanged
non-gvar tables apart from the head checksum.
Testing: meson test -C build (276 passed).
Fixes: https://github.com/harfbuzz/harfbuzz/issues/6462
Reported-by: olsklcode
Assisted-by: OpenAI Codex
Honk paints an empty outline as one of its COLR layers. Transforming its
void bounding box orders the sentinel corners into a real rectangle at
(-1,-1)-(0,0), even with the identity transform. That rectangle expands
the accent's ink bounds toward the origin and shifts fallback marks by
hundreds of units.
Keep void extents void when applying a transform. Add shaping regressions
for normal and double scale and vertical layout using a default-instance
Honk subset, with its OFL embedded in the name table.
Current read-fonts already computes the correct COLR bounds. Removing
only the empty layer also makes unpatched HarfBuzz match HarfRust,
confirming the cause of harfrust#553.
Update the existing vertical-origin overflow fixture to use an explicit
COLR clip box. Assert that its height still clamps to INT_MIN so the
original negation-overflow regression stays covered after void bounds
stop producing artificial ink.
Testing: meson test -C build (276 passed).
Fixes: https://github.com/harfbuzz/harfrust/issues/553
Assisted-by: OpenAI Codex
* [subset] Bound CFF2 blend values and serialization fields
Clamp fully pinned Private DICT blend sums before converting to int.
Reject CFF2 Top DICT sizes, variation-store counts, and region indexes
that cannot fit their serialized fields. Check VarRegionList counts
and byte-size multiplication before writing or allocating output.
Keep the CFF2 API regressions and move variation-region serialization
coverage into test-item-varstore. Use hb_always_assert and compact
boundary cases instead of custom macros, command-line selectors,
duplicate controls, and constant-condition checks. Verify that valid
region lists survive serialization and remapping unchanged.
The new CFF2 API regressions fail against unpatched main and pass with
these fixes. All 277 Meson tests pass, including all 133 subset tests.
The item-varstore tests also compile with HB_NO_VAR.
Based on the hardening patch in PR #6532.
Co-Authored-By: Nathan Keys <professor.moody@pm.me>
Assisted-by: OpenAI Codex
* [meson] Link the IUP optimizer into the CFF2 serialization test
The CFF2 serialization test instantiates tuple variations. Its object can
therefore reference iup_delta_optimize even though CFF2 does not enable
IUP optimization. Some compilers retain that reference and fail to link
the test; the local optimized build had eliminated it.
Include the IUP implementation in the test target, as the other tuple
and item varstore tests already do.
Reproduced the undefined reference by compiling the CFF2 test object at
-O0. It links and passes after adding the dependency. All 277 tests pass
with meson test -C build.
Assisted-by: OpenAI Codex
---------
Co-authored-by: Nathan Keys <professor.moody@pm.me>
HarfRust signals a shaping failure -- a max_ops / preprocessing-budget trip, an allocation failure, or an internal error -- by returning false from its shape function, whereas the ot shaper always returns true and reports such failures through the buffer's success flag.
Because hb_shape() returns void, hb_buffer_allocation_successful() is the only failure signal its callers have. The HarfRust shim returned false without touching the C hb_buffer_t, so after a HarfRust budget trip hb_buffer_allocation_successful() still reported success while the buffer was left unshaped.
Mirror the ot shaper in hb-harfrust.cc: always return true and, on failure, mark the buffer unsuccessful. As with the ot shaper after a budget trip, the buffer is then labelled GLYPHS but its contents must not be trusted; the caller must check hb_buffer_allocation_successful().
Add a test-shape regression test that drives the HarfRust shaper with many ranged features (overrunning setup_masks()'s op budget) and asserts the failure now reaches hb_buffer_allocation_successful(). It runs in the test-shape-harfrust CI job and skips when HarfRust is not built.
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
* [indic] Include Unicode 18 Devanagari and Bengali additions
The block filter discarded U+11B0A even though the Unicode 18 data
classifies it as a consonant. Following marks therefore formed broken
syllables and received unwanted dotted circles. The same omission
excluded Bengali Supplement's U+11DF0 and U+11DF1.
Include both blocks and regenerate the Indic table. These three code
points are the only effective classification changes. Add nine shaping
cases using the existing Adobe Blank font, including a valid-syllable
control and an isolated anusvara that needs a dotted circle.
Eight new cases fail before the fix. All 275 Meson tests pass after it,
including the full shaping suite.
Fixes: https://github.com/harfbuzz/harfbuzz/issues/6452
Assisted-by: OpenAI Codex
* [gen] Preserve current Rust vowel-constraint buffer access
The shared generator still emitted direct field access through
buffer.cur(), which now returns Option in HarfRust. Regenerating the
file also lost its checked access to output glyph information.
Emit the cur_glyph helper and guarded output lookup already used by
the checked-in Rust implementation. The regenerated Rust functions
match HarfRust after its import adaptations, and the C++ output is
byte-for-byte unchanged.
All 275 Meson tests pass. HarfRust's default and all-feature workspace
tests pass with the regenerated functions.
Assisted-by: OpenAI Codex
* [test] Keep Unicode 18 Indic cases in a dedicated shaping file
Group the new cases in indic-unicode18.tests so HarfRust can import
these generated tests without replacing existing Indic regressions.
Register the file in the in-house shaping suite.
All 275 Meson tests pass.
Assisted-by: OpenAI Codex
* [gen] Emit HarfRust names directly from the shared generators
Generate the Rust module paths, type names, and table symbol prefixes
used by HarfRust at their source. This removes the need for text
rewrites in HarfRust's Unicode-table makefile.
All eight Rust outputs are byte-for-byte identical to the previous
postprocessed outputs. All seven C/C++ generator outputs are
byte-for-byte unchanged, and all 275 Meson tests pass.
Assisted-by: OpenAI Codex
* [varc/colr] Bound tuple decoding and guard variation-index overflow
Preflight packed tuple runs before allocating decoded vectors, reject
truncated runs, and stop failed iterators at the end of their input.
Charge VARC axis expansion to the draw budget before resizing scratch
vectors. Guard variation-index addition and clip-box closure, using
checked 32-bit arithmetic for COLR ranges and preserving valid prefixes
below the reserved sentinel.
Run VARC draw tests under their actual feature guard instead of the
stale experimental-API guard. Keep tests compatible with GCC ASan,
older GLib, and builds with variations disabled.
Based on the hardening work in PR #6533.
Testing: all 275 default Meson tests and 294 experimental-API tests pass.
The machinery, VARC draw, color, and COLR subset tests pass under Clang
ASan/UBSan with the default APIs; the VARC draw suite runs all 11 cases.
GCC/Clang ASan syntax checks, GLib 2.66 API-availability checks, and the
HB_NO_VAR machinery test pass.
Co-authored-by: Nathan Keys <professor.moody@pm.me>
Assisted-by: OpenAI Codex
* [test] Put tuple and COLR regressions with their subsystems
Restore test-machinery to its original purpose. Put packed-tuple
regressions in test-tuple-varstore and the instancer regression in
test-item-varstore. Give the COLR closure checks their own test-colr
unit target. Use the local hb_always_assert convention and remove the
ad-hoc check macro, method-detection templates, and test-mode dispatcher.
Testing: all 276 default Meson tests pass. The tuple/item varstore,
COLR, VARC draw, color, and COLR subset tests pass under ASan/UBSan.
Assisted-by: OpenAI Codex
* [ot] Use an unsigned result for checked variation-index addition
The ARM EABI toolchain defines uint32_t as unsigned long, while
hb_unsigned_add_overflows accepts unsigned*. Store the checked sum in
an unsigned temporary and assign it back, preserving the overflow and
NO_VARIATION checks without depending on typedef identity.
Testing: all 276 Meson tests pass. A distinct-unsigned-long compile check
covers normal, sentinel, and overflow inputs.
Assisted-by: OpenAI Codex
* [test] Remove allocator-specific VARC test instrumentation
Drop the heap-accounting regression and its sanitizer and libc hooks.
Keep the ordinary VARC budget and truncated-axis regression tests.
All 276 Meson tests pass. The tuple/item varstore, COLR, VARC draw,
color, and COLR subset tests also pass under Clang ASan/UBSan.
Assisted-by: OpenAI Codex
---------
Co-authored-by: Nathan Keys <professor.moody@pm.me>
An explicit glyph map can create empty output glyphs beyond the source
font's glyph count. When preserving codes for gaps in the mapping, the
subsetter queries those nonexistent source glyphs. Excess entries in a
malformed custom encoding can then give the new empty glyphs codes.
Return CFF_UNDEF_CODE for glyphs outside the source font before reading
the encoding. Add format 0 and format 1 regression cases comparing
ordinary and explicitly remapped subsets against bounded encodings,
with a generator for the small synthetic fonts.
Both new cases fail before the fix. All 275 tests pass with
meson test -C build --print-errorlogs --num-processes 12.
Related: https://github.com/googlefonts/fontations/pull/2398
Assisted-by: Codex
* [test] Probe CoreText kerx stack behavior
Add native CoreText probes for list reuse, excess values, zero values,
duplicate pushes, repeated actions, resets, and long lists. Run them on
macOS 15 and macOS latest to establish the compatibility behavior before
changing the kerx driver.
The local baseline Meson suite passes all 275 tests. Native execution
is intentionally checked by the new macOS probe jobs.
Related: https://github.com/harfbuzz/harfbuzz/pull/6538#issuecomment-6561986849
Assisted-by: OpenAI Codex
* [test] Probe retained kerx history past eight pushes
Add an end-of-text action after twenty repeated push/action entries to
distinguish retained history from an eight-entry rolling window.
The local Meson suite passes all 275 tests.
Assisted-by: OpenAI Codex
* [test] Probe kerx history wraparound and reset reuse
Add native cases around the eight-slot boundary, actions before the
first push, a first push after ignored glyphs, and history reuse after
reset. These distinguish partial-history initialization and cursor
wraparound for the CoreText compatibility implementation.
Testing: all 275 Meson tests pass with the implementation in progress.
Assisted-by: OpenAI Codex
* [test] Verify kerx reset anchors and Arabic examples in CoreText
Measure a reset followed by another action without a push, and include
both versions of the reported Arabic font. Use mapped glyphs for ignored
prefixes so font fallback cannot affect the native position comparison.
Testing: all 275 Meson tests pass with the implementation in progress.
Assisted-by: OpenAI Codex
* [test] Probe long kerx lists after resetting history
Distinguish how reset initializes unused history slots by applying a
long list after a reset with and without a push, and after every push.
Testing: all 275 Meson tests pass with the implementation in progress.
Assisted-by: OpenAI Codex
* [aat] Match CoreText kerx format 1 history
The written kerx rules describe destructive stack pops and a reset flag.
Native CoreText retains an eight-slot circular history, initializes its
unused slots to the first glyph, and ignores reset. Each action list
walks the history independently and wraps after eight values.
Use that behavior for extended kerx while retaining legacy kern rules.
Bound the longer action-list walks by the buffer operation budget and
keep fixed-size history storage. Document the spec discrepancy and add
regressions for reuse, wraparound, initial slots, reset, and both Arabic
examples, plus terminated and unterminated over-budget lists.
Testing: all 275 Meson tests pass. HB and HR match glyph identities,
character indices, positions, and final extents for all 35 native cases
on macOS 15.8.2 and 26.6.2. Both Arabic examples match their GPOS reference.
Fixes: https://github.com/harfbuzz/harfbuzz/issues/6536
Assisted-by: OpenAI Codex
* [ci] Remove exploratory CoreText kerx probe jobs
The native measurements established the compatibility behavior, which
is now covered by the normal shaping regressions in HB and HR. Keep the
manual probe, recorded results, and discrepancy documentation without
adding two native macOS jobs to every pull request.
CI and documentation only; no code or test inputs changed.
Assisted-by: OpenAI Codex
* [test] Run kerx CoreText comparisons with shaping tests
Move the native helper and reference data from .ci into test/shape.
Run the native comparison as a normal CoreText-enabled macOS Meson
shaping test, using the existing macOS CI job. Keep the discrepancy
explanation beside the regression cases and drop the standalone Markdown.
Testing: all 275 Linux Meson tests pass. The comparison runner passes
all 35 recorded cases and rejects an injected position mismatch. The
native helper is unchanged from the macOS 15.8.2 and 26.6.2 measurements.
Assisted-by: OpenAI Codex
* [test] Keep kerx regressions in the shaping suite
Remove the API C budget test, native CoreText C helper, comparison
runner, reference JSON files, and extra Meson test target. Retain the
library fix and normal shaping regressions, with a short explanation of
the native behavior in the shaping test file.
Testing: all 275 Meson tests pass.
Assisted-by: OpenAI Codex
kerx format 1 entries contain value-array indices and terminate lists
with a separate 0xFFFF word. The shared kern/kerx driver instead treated
the indices as byte offsets and used the legacy kern low-bit terminator.
Keep the legacy kern behavior, but read kerx indices directly and stop
before popping a glyph for 0xFFFF. Validate kerx values as they are read
so a short list can terminate while glyphs remain on the stack. Mark
the dependencies of adjustments to earlier stacked glyphs unsafe to break.
Add regressions for positive and negative odd values, nonzero indices,
short lists, retained stack entries, and glyph flags. All 275 Meson
tests pass, including the shaping suite and both font callback backends.
Related: https://github.com/harfbuzz/harfbuzz/issues/6536
Assisted-by: OpenAI Codex
hb-ft's vertical-origin callback cached a full origin -- x, y, and a
load-failure flag -- in a bespoke 256-entry direct-mapped cache, because
hb_cache_t holds only a single non-negative integer.
Do what hb-ot does instead. The vertical origin's x is half the glyph's
horizontal advance, already cached for horizontal advances, so only y
needs a cache of its own, and y fits hb_cache_t once its sign is
normalized the way hb-ot normalizes the origin. v_origins now fills x
from hb_ft_get_glyph_h_advances() before taking the lock and caches only
y; the custom cache and its origin struct are removed.
This changes the origin's x for fonts whose FreeType vertical bearing
does not center the glyph (eg. a proportional font laid out vertically):
x was horiBearingX - vertBearingX and is now advance/2, which matches
hb-ot. For CJK and other centered glyphs it is unchanged.
A FreeType load failure is no longer turned into a failed origin that
sent the whole run to the caller's fallback. The glyph will not render,
so its y origin is cached as 0 and the rest of the run keeps its real
origins.
Reported by Anthropic's OSS Scanner as ordinary bug ANT-2026-Y24FNCOQ.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
For vertical text hb_ot_position_default() fetches one advance and one
origin per glyph in the buffer. hb-ft registered only single-glyph
callbacks for these, each going to FreeType with no cache, so a glyph
that is expensive for FreeType to load (eg. a deeply nested CFF
charstring) was loaded again for every occurrence in the text: shaping
time grew linearly with text length. Horizontal advances in hb-ft and
both vertical values in hb-ot are already batched and cached.
Register batched callbacks, hb_ft_get_glyph_v_advances() and
hb_ft_get_glyph_v_origins(), mirroring the horizontal advance callback,
and put a per-font cache in front of FreeType in each.
Vertical advances reuse the same hb_cache_t that horizontal advances
use. A vertical advance is non-positive when y_scale is positive (as in
hb-ot, which scales -advance), while hb_cache_t stores only non-negative
values, so the cache holds the advance's magnitude and the sign is
restored on read -- the same trick hb-ot's vertical-advance cache uses.
An origin is two values plus a failure flag, which hb_cache_t cannot
hold, so origins keep a small direct-mapped cache, hb_ft_glyph_cache_t
(256 entries); failed loads are cached too. The batched origins
callback returns false if any glyph failed to load, reproducing the
all-or-nothing result the single-glyph adapter produced for a run.
Both callbacks consult their cache under the ft_font->lock they already
hold. clear_caches() clears all caches wherever the horizontal cache
was cleared, including from hb_ft_font_set_load_flags(), since the load
flags feed both FreeType calls -- which also fixes the horizontal
advance_cache going stale there.
A cache removes the repetition, not the cost of a first load of each
distinct glyph, which is FreeType's own.
Adds test_native_ft_v_metrics_cache and test_native_ft_v_metrics_batched,
checking that repeated and batched queries agree with the single-glyph
API and a fresh font, that scale and load-flag changes are not served
from the cache, and that the advance sign is right at negative y_scale.
Reported by Anthropic's OSS Scanner as ordinary bug ANT-2026-Y24FNCOQ.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>