Commit Graph
225 Commits
Author SHA1 Message Date
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 Esfahbod a01588aad7 Merge branch 'main' into scanner/instancer-fix 2026-11-09 13:06:22 -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 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 Esfahbod eb9dc91893 [subset] Bound CFF1 encoding lookups by the glyph count (#6543)
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
2026-11-01 14:14:09 -07:00
Behdad EsfahbodandClaude Opus 4.8 a3ad47c776 [ft] Report zero color stops when skipping to start fails
hb_color_line_get_color_stops() defines *count as in/out: capacity on
entry, number of stops written on exit.  The skip-to-start early return
added in #6121 (to avoid an infinite loop when FT_Get_Colorline_Stops()
refuses a stop) writes no stops but left *count untouched, so an embedder
paging a malformed ColorLine with start > 0 reads uninitialized
hb_color_stop_t entries and draws the gradient from its own buffer.

Set *count = 0 on that exit, matching the start >= num_color_stops exit
a few lines above and the hb-ot ColorLine::get_color_stops().  Well-formed
fonts are unaffected; no API/ABI change.

Adds test_color_stops_short_ft with a generated 392-byte font whose
ColorLine declares one more stop than it holds.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-31 22:45:12 -06:00
Behdad EsfahbodandClaude Opus 4.8 820032a852 [test] Move the USE_MY_METRICS advance regression to an ot-funcs metrics test
The ANT-2026-DQGMHCLX regression was added as a line in
test/shape/data/in-house/tests/variations.tests, but that suite is also
run with --font-funcs=fontations appended by the test runner (which a
.tests line cannot override).  Under fontations funcs this multi-
USE_MY_METRICS composite font's advances differ from HarfBuzz's own, so
the line failed CI.  The divergence is a real HarfBuzz-vs-fontations
difference in how multiple USE_MY_METRICS components are resolved, not a
HarfBuzz bug: HarfBuzz takes the metrics of the last such component.

Remove the .tests line and pin the same regression in
test/api/test-ot-metrics-tt-var.c instead, using hb_font_get_glyph_h_advance,
so it exercises HarfBuzz's own glyph metrics and the fontations CI run does
not touch it.  The font moves to test/api/fonts/ where that test loads it.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-31 22:00:12 -06:00
Behdad EsfahbodandClaude Opus 4.8 5e84cf30bb [COLR] Harden COLR subsetting, instancing and paint against DoS findings (#6508)
* [subset] Clamp PaintColrLayers layer range to LayerList in COLRv1 closure

PaintColrLayers::closurev1() recorded firstLayerIndex ..
firstLayerIndex + numLayers - 1 as retained layers without checking
the range against LayerList.len (PaintColrLayers::sanitize is a plain
check_struct), and _colr_closure() then creates one colrv1_layers map
entry per retained index.  A crafted font whose leaf paints point past
the end of the LayerList could therefore add up to 255 entries each for
layers that do not exist, driving subset-plan memory to roughly 1200x
the font size (585 MiB for a 512 KB font).

Clamp the range to the LayerList at the one place the retained-layer set
is built, before add_layer_indices() and for the dispatch loop alike;
this also removes the firstLayerIndex + numLayers wrap-around in the loop
bound.  Readers (paint_glyph, dependv1) never record indices and already
tolerate out-of-range ones via LayerList::get_paint() returning Null, so
they are left alone.  A PaintColrLayers whose range lies past the source
LayerList now has no mapping and subset writes 0xFFFFFFFF; both that and
a renumbered index past the new LayerList are out of range and draw
nothing.

Adds a regression test that builds such a font inline and pins the
output; it fails without the fix.

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

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

* [subset] Bound shared COLRv0 layer expansion and make V0 closures linear

COLR::subset() gives every retained COLRv0 base glyph a private copy of
its layer range, so N base glyphs sharing L layers cost N x L layer
copies with two hash lookups each, and nothing checked the total against
the 16-bit numLayers header field.  serialize_V0() walks the lazy
iterator twice and _hb_subset_table_try() retries while doubling the
buffer, so a ~200 KB font with all records naming the same range kept
hb-subset busy for about two minutes before failing.

Cap the summed layer count with a cheap walk over base_it before layer_it
is built, and drop COLR (return_trace (false)) when the total exceeds
0xFFFF, the same way this function already handles V0 records it cannot
subset; this also removes the 16-bit wrap in serialize_V0().  Any total
above 65535 could only have produced a failed subset or a wrapped,
invalid numLayers, so no valid output is lost.

The two V0 closure helpers had the same N x L shape during planning;
collect the layer indices of all retained base glyphs into one set first
and visit each layer once.  closure_glyphs() now takes the glyph set in
one call (the accelerator wrapper changes signature with it; no public
API change), and _colr_closure() passes the whole set instead of looping.

Adds test_subset_colr_shared_layers (256 base glyphs all claiming the
same 256 layers): retaining 255 gives a 65280-layer table, retaining all
256 gives an empty COLR.

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

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

* [subset] Look up each retained glyph's ClipRecord by bsearch in ClipList::subset

ClipList::subset() walked startGlyphID..endGlyphID of every ClipRecord,
which is only O(num_glyphs) overall when the records are sorted and
disjoint.  ClipList::sanitize() checks neither, so R overlapping records
each spanning all glyphs cost R x 65535 iterations: a 332 KB font with
10000 whole-range records took about 20 s of CPU in hb-subset whatever
glyphs or text the request asked for.

Invert the loop: iterate the retained glyph set once and find each
glyph's record with clips.as_array ().bsearch (gid), exactly how
ClipList::get_extents() resolves a glyph's clip box when rendering, and
the same shape as the COLRv0 path in COLR::subset().  Cost is now
O(|glyphset| log R) regardless of record overlap.  For well-formed
(sorted, disjoint) lists the output is unchanged; for malformed
overlapping/unsorted lists the chosen record can differ (bsearch instead
of last-record-wins), which makes the subset agree with the clip box
HarfBuzz itself renders from the source font.

Adds an extended-format hb-subset-fuzzer input (5000 records covering
all 65535 glyphs) that the subset-fuzzer tests pick up.

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

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

* [subset] Compute COLR constant_after_pinning once per plan

PaintRadialGradient::constant_after_pinning() answers a question about
the source ItemVariationStore and the subset plan only, yet it rescanned
every variation region (building a hashmap per region, up to 32767) on
every paint visit.  Shared paints are visited once per reference by
OffsetTo::serialize_subset(), so during partial instancing the cost grew
as visits x regionCount: 40 s to 6 minutes for a 192 KB font with a
PaintComposite chain and many regions.

Cache the answer in a tri-state plan field (-1 until computed, like the
lazily-set has_gdef_varstore flag) so the scan runs at most once per
plan; the plan is valid for one source face and one set of axis
locations, so this is sound.  Move the cheap varIdxBase != NO_VARIATION
test ahead of the scan so non-variable format 6 gradients never trigger
it.  The allocation-failure path of get_var_region() still sets the
serializer error and returns uncached, as before.

Output is byte-identical; the attack font drops from ~41 s to ~0.03 s.

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

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

* [COLR] Charge gradient color stops to the paint session work budget

The COLRv1 paint walk bounds paint-table visits (HB_MAX_NESTING_LEVEL,
HB_MAX_GRAPH_EDGE_COUNT) but handed out ColorLine stops uncharged, so a
single 65535-stop ColorLine shared across up to 16384 gradient edges
could deliver ~10^9 stops from one hb_font_paint_glyph() call, keeping
the rendering thread busy for minutes per glyph in every backend.

Give hb_paint_context_t the session's live budget via
funcs->get_budget_remaining_ptr(), with the same local HB_BUDGET_GLYPH
fallback hb_draw_session_t uses, charge HB_BUDGET_16 per stop delivered
in ColorLine::get_color_stops() (the one place every consumer fetches
stops, so vector, raster, cairo and client paint functions are all
covered), and make recurse() skip further paints once the budget is
negative, as it already does for an oversized graph.  The backend's one
budget is only spent, never re-armed, so this does not reintroduce the
cross-subsystem budget multiplication removed in #6147.  hb-ft-colr.hh
has the same shape and gets the identical change.

With the default 2^24 budget about a million stops per session are
delivered before the rest of the walk is skipped best-effort.  A
separate quadratic cost inside cairo's own gradient pattern building is
not addressed here.  Adds a regression test that fails without the fix.

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

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

* [paint] Clip sweep-gradient tiles to 0..2π in hb_paint_sweep_gradient_tiles

hb_paint_sweep_gradient_tiles() documents that it iterates the 0..2π
sweep, and all three consumers (hb-cairo mesh patches, the SVG and PDF
writers) size their per-tile loops by tile width on that assumption.
Several emit sites (the start==end PAD case, the first PAD stop past 0,
and repeat/reflect segments straddling 0 or 2π) passed the angles
straight through, and COLRv1 variation deltas can place them hundreds of
thousands of radians outside the circle, so one tile could expand to
millions of patches: a 504-byte variable font drawn off its default
allocated ~1.6 GiB through hb-cairo.

#6157 bounded the number of sweep tiles; this bounds the width of each
one.  Route every emit through a small clipping lambda inside the tiler
that clamps the tile to [0, 2π], lerps the end colours at the clip
points, and drops tiles entirely outside, so the contract holds at the
single place it is established rather than in each backend.
HB_PAINT_MAX_SWEEP_TILES and the repeat-loop bounds are untouched;
external callers need no change.

Adds a regression test calling the public function with far-out angles
for PAD/REPEAT/REFLECT; it fails without the fix.

Follow-up to #6157.

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

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

* [depend] Bound COLR dependency extraction with a shared op budget

COLR::depend() walked the COLRv1 paint graph from scratch for every
BaseGlyphPaintRecord (clearing the visited set each time) with no total
work limit, so N base glyphs sharing one paint graph cost N times the
graph, quadratic in table size (204 s for a 200 KB font); the COLRv0
loop has the same base-glyphs x layers shape.  The API is built only
with -Dexperimental_api=true.

hb_colrv1_depend_context_t, which already owns the per-walk depth and
visited-set guards, now also carries max_ops sized like the sanitizer's
(table length x HB_SANITIZE_MAX_OPS_FACTOR, clamped to the MIN/MAX),
charged one unit per Paint::dispatch(), per COLRv0 layer record, and per
PaintColrLayers layer run.  Charging the layer run in dependv1() matters
because a layer resolving to the null or an unknown-format paint is
dropped by Paint::dispatch() before it reaches the context, so without
it a PaintColrLayers could still spin its 255-iteration loop uncharged.
Exhausting the budget calls depend_data->fail() (the existing error
idiom) so hb_subset_depend_from_face_or_fail() returns NULL rather than
a graph with silently missing edges, and the base-glyph loop stops once
the builder has failed.

The reproducer font is now rejected in a fraction of a second; the
control still succeeds, and legitimate fonts keep 64 ops per table byte
of headroom.  Adds test_depend_colr_budget.

Follow-up to #6113.

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

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

* [ft] Drop the dead color-stop iterator resets

Since the color line is copied locally ("Keep iteration local"), the
iteration advances cl->color_stop_iterator on that local copy, which is
discarded when the function returns.  The two "reset the iterator for next
time" writes (cl->color_stop_iterator = iter) therefore have no effect:
there is no persistent iterator state to restore, and positioning across
calls is driven entirely by the start argument.

Remove both dead writes and the now-unused saved iterator.  No behavior
change; the return value (num_color_stops) is unaffected by iteration.

Full test suite passes (277/277).

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-31 21:56:50 -06:00
Behdad Esfahbod e8f8ee612f [subset] Ignore seac component lookups in CID-keyed CFF fonts (#6506)
CID-keyed CFF charsets contain CIDs, not the standard SIDs needed by seac.
Interpreting the invalid operator can therefore retain unrelated glyphs
when their CIDs collide with the component SIDs from StandardEncoding.

Reject CID-keyed fonts in get_seac_components so both subset closure and
dependency collection skip these invalid lookups. Add a synthetic CID
font with colliding CIDs and check that only .notdef and the requested
glyph enter the subset plan.

The regression fails before the fix with four retained glyphs instead of
two. All 294 Meson tests pass, including the subset and API suites.

Assisted-by: OpenAI Codex
2026-10-30 16:10:52 -06:00
Behdad EsfahbodandClaude Opus 4.8 c5dedbef33 [subset] Bound shared COLRv0 layer expansion and make V0 closures linear
COLR::subset() gives every retained COLRv0 base glyph a private copy of
its layer range, so N base glyphs sharing L layers cost N x L layer
copies with two hash lookups each, and nothing checked the total against
the 16-bit numLayers header field.  serialize_V0() walks the lazy
iterator twice and _hb_subset_table_try() retries while doubling the
buffer, so a ~200 KB font with all records naming the same range kept
hb-subset busy for about two minutes before failing.

Cap the summed layer count with a cheap walk over base_it before layer_it
is built, and drop COLR (return_trace (false)) when the total exceeds
0xFFFF, the same way this function already handles V0 records it cannot
subset; this also removes the 16-bit wrap in serialize_V0().  Any total
above 65535 could only have produced a failed subset or a wrapped,
invalid numLayers, so no valid output is lost.

The two V0 closure helpers had the same N x L shape during planning;
collect the layer indices of all retained base glyphs into one set first
and visit each layer once.  closure_glyphs() now takes the glyph set in
one call (the accelerator wrapper changes signature with it; no public
API change), and _colr_closure() passes the whole set instead of looping.

Adds test_subset_colr_shared_layers (256 base glyphs all claiming the
same 256 layers): retaining 255 gives a 65280-layer table, retaining all
256 gives an empty COLR.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 16:04:35 -06:00
Behdad EsfahbodandClaude Opus 4.8 969dbf7931 [cairo] Fix recursion, leak, cluster abort and COLR paint DoS in hb-cairo (#6497)
* [cairo] Paint nested color glyphs inline to bound recursion

hb_cairo_paint_color_glyph() accepted the color_glyph paint callback
and drew the nested glyph with cairo_show_glyphs(), which re-enters
hb_font_paint_glyph() through a new cairo scaled font with a fresh
hb_paint_context_t.  The glyph decycler, HB_MAX_NESTING_LEVEL and the
edge budget therefore start over at every level, so two glyphs that
paint each other with PaintColrGlyph recurse until the stack is
exhausted.  The per-scaled-font hb_cairo_budget_t cannot bound this
either: the nested glyph is shown through a different scaled font, so
each level gets its own budget.

Decline the callback, returning false exactly as hb-raster's does, so
the COLR (and hb-ft-colr) walk paints the nested glyph inline under the
decycler and depth limits of the walk already in progress.

A regression test with two PaintColrGlyph glyphs that paint each other
is added to test/api/test-cairo.c; it aborts on the unpatched library
and passes with the fix.

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

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

* [cairo] Don't leak the hb_font_t created per scaled font

hb_cairo_init_scaled_font() must hand exactly one reference of the
hb_font_t to the cairo_scaled_font_t.  For a face-based font face
(hb_cairo_font_face_create_for_face()) it creates the font with a
reference count of 1, but then still called hb_font_reference() before
attaching it, so the creating reference was never released.  Every
finalized scaled font therefore leaked an hb_font_t, pinning its
hb_face_t, the font blob and the accelerators until the process exits.
Cairo finalizes scaled fonts during normal operation once its cache
fills, so the leak accumulates as content selects distinct sizes,
transforms or font options.

Take the extra reference only in the branch where the font is the
shared one owned by the cairo font face (the font-based constructor),
and transfer the freshly created font as-is.  The set_user_data result
is now checked and the font released on failure, matching the
budget/color-cache idiom a few lines below and the font-face
constructors in the same file.

A callback installed with hb_cairo_font_face_set_font_init_func() that
returns a different font keeps its historical behavior: the returned
font is referenced rather than assumed to transfer ownership, so no
in-tree contract changes and no caller can turn into a use-after-free.
hb-view uses the font-based constructor and was unaffected.

A regression test in test/api/test-cairo.c registers a face destroy
notifier, draws through a face-based font face, flushes cairo's
scaled-font cache and asserts the face was destroyed; it fails on the
unpatched library and passes with the fix.

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

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

* [cairo] Map non-monotone buffer clusters to one cairo cluster

hb_cairo_glyphs_from_buffer() asserted that buffer clusters are monotone
in the buffer direction, but hb_shape() does not guarantee that:
HB_BUFFER_CLUSTER_LEVEL_CHARACTERS, shaping that hits the ops limit
mid-lookup, and Indic reordering corner cases can all produce
non-monotone clusters.  The function runs from HarfBuzz's own cairo
text_to_glyphs callback on attacker-controlled text and fonts, so the
assertion was an input-dependent abort (and, with NDEBUG, an unchecked
backward walk off the ends of the utf8 buffer).

The cluster-counting loop that already walks the buffer now detects a
step against the buffer's direction and falls back to a single cairo
cluster mapping all of the utf8 to all of the glyphs, which cairo
accepts.  The monotonicity assertions in the fill step then hold by
construction and glyph output is unchanged for monotone buffers.

A regression test in test/api/test-cairo.c feeds monotone and
non-monotone LTR/RTL buffers through both cluster modes and checks the
cluster counts and byte/glyph totals; it aborts on the pristine tree.

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

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

* [cairo] Charge compositing operations to the glyph budget

hb-cairo's per-glyph work budget was spent only on emitted path segments,
so a COLRv1 font could pay once for a clip outline (push_clip_glyph) and
then have cairo re-rasterize it for every PaintSolid/gradient/group
composite under it, up to the COLR edge limit.  That is the
multiplication of limits the shared budget in hb-limits.hh exists to
prevent: a 2 KB font kept hb-view busy for over a minute on one glyph.

Charge every composite in the cairo backend, where the cost is incurred
and where the sibling backends already charge per operation (hb-raster
charges pixel area per paint).  hb_cairo_context_t now counts the
segments of the current path and keeps a stack of the clip paths in
force, maintained by the push_clip_* callbacks and pop_clip; spend_paint()
charges every fill, paint, group and gradient with (1 + segments) times a
per-source weight, squared when more than one path is in force since
cairo then intersects the paths per operation.  These segment and clip
counts are inputs to the existing budget_remaining counter; they are not
a separate per-callback limit.  The weights (HB_BUDGET_512 for
solid/group, 1024 for linear/radial gradients, a new HB_BUDGET_8192 for
the sweep mesh pattern) follow per-composite timings measured on
cairo 1.18.

Nested color glyphs are already painted inline by the color_glyph
callback, so their composites are charged against the clips in force at
that point; no change is needed there.

Behaviour change: a glyph whose composites exceed the budget (about 32k
segment-composites, roughly a second of cairo time at hb-view's default
size) is truncated best-effort, as outline work already is.  All glyphs
of the COLRv1 glyf (static and variable) and CFF2 test fonts render
byte-identically through hb-view with and without this change.

A regression test with a generated 3 KB font is added to
test/api/test-cairo.c alongside its fontTools generator; it finishes in
about a second once the paints are charged and guards against
reintroduction through the meson test timeout rather than a
discriminating assertion.

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

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 15:26:28 -06:00
Behdad Esfahbod 68ee3a923e [graphite2] Stop shaping when output buffer growth fails (#6489)
Check ensure(glyph_count) before writing Graphite output. Release the
feature values and segment and return failure when buffer growth fails.

Add a small synthetic font and a bounded regression that refuses buffer
growth via max_len. The normal path produces 164 glyphs; the failure path
retains the original input length and reports allocation failure. Include
the font generator, whose output matches the checked-in fixture.

The new regression fails before the fix under ASan and passes afterward.
All 276 tests pass with Graphite2 enabled; the regression also passes under
ASan and UBSan.

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

Assisted-by: OpenAI Codex
2026-10-30 14:53:51 -06:00
Behdad EsfahbodandClaude Opus 4.8 022a9e475a [cairo] Charge compositing operations to the glyph budget
hb-cairo's per-glyph work budget was spent only on emitted path segments,
so a COLRv1 font could pay once for a clip outline (push_clip_glyph) and
then have cairo re-rasterize it for every PaintSolid/gradient/group
composite under it, up to the COLR edge limit.  That is the
multiplication of limits the shared budget in hb-limits.hh exists to
prevent: a 2 KB font kept hb-view busy for over a minute on one glyph.

Charge every composite in the cairo backend, where the cost is incurred
and where the sibling backends already charge per operation (hb-raster
charges pixel area per paint).  hb_cairo_context_t now counts the
segments of the current path and keeps a stack of the clip paths in
force, maintained by the push_clip_* callbacks and pop_clip; spend_paint()
charges every fill, paint, group and gradient with (1 + segments) times a
per-source weight, squared when more than one path is in force since
cairo then intersects the paths per operation.  These segment and clip
counts are inputs to the existing budget_remaining counter; they are not
a separate per-callback limit.  The weights (HB_BUDGET_512 for
solid/group, 1024 for linear/radial gradients, a new HB_BUDGET_8192 for
the sweep mesh pattern) follow per-composite timings measured on
cairo 1.18.

Nested color glyphs are already painted inline by the color_glyph
callback, so their composites are charged against the clips in force at
that point; no change is needed there.

Behaviour change: a glyph whose composites exceed the budget (about 32k
segment-composites, roughly a second of cairo time at hb-view's default
size) is truncated best-effort, as outline work already is.  All glyphs
of the COLRv1 glyf (static and variable) and CFF2 test fonts render
byte-identically through hb-view with and without this change.

A regression test with a generated 3 KB font is added to
test/api/test-cairo.c alongside its fontTools generator; it finishes in
about a second once the paints are charged and guards against
reintroduction through the meson test timeout rather than a
discriminating assertion.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 14:53:31 -06:00
Beleniuc Ilie 4868fd314f [subset] Use CFF1 Encoding format 1 for more than 255 codes (#6460)
A format 1 Encoding can give codes to more than 255 glyphs, since
codes may repeat across ranges. When the subset keeps more than 255
of those glyphs, as with retain-gids, plan_subset_encoding() hit
assert (subset_enc_num_codes <= 0xFF).

Choose format 0 only when it can hold the codes, and fail cleanly in
the format 1 serializer instead of truncating nRanges past 255.

Add a test font whose format 1 Encoding covers 768 glyphs, and the
reporter's font to the fuzzing corpus.

Fixes: https://github.com/harfbuzz/harfbuzz/issues/6031
Assisted-by: Claude
Assisted-by: OpenAI Codex
2026-10-29 16:35:22 -06:00
Behdad Esfahbod c305720f01 [subset] Handle seac operands returned by a subroutine (#6463)
A subroutine can push all four seac operands, return, and leave the
glyph's own endchar to consume them. Treat callsubr and callgsubr
immediately before endchar as possible seac suffixes even when no
subroutine contains endchar.

Add a synthetic CFF1 regression font for the operand-only subroutine
case.

Assisted-by: OpenAI Codex
2026-10-29 16:25:35 -06:00
Behdad Esfahbod 2c0df50ce1 [subset] Make CFF1 seac precheck conservative (#6458)
A subroutine can terminate a glyph with endchar, and dotsection preserves
live operands. Account for both cases when deciding whether a CFF1
charstring can form a seac composite.

Cache whether any subroutine may contain endchar so ordinary fonts keep
the fast trailing-byte check. Skip component closure when all glyphs are
already retained, except when computing reusable accelerator metadata.

Add regressions for endchar in a local subroutine and operands preserved
across dotsection.

Assisted-by: OpenAI Codex
2026-10-27 18:05:47 -06:00
Behdad Esfahbod f306676520 [subset] Tighten CFF2 absolute rounding (#6443)
Clear flex-depth deltas when they all round to zero and reject unexpected
operators in the absolute-rounding pass. Cover static fractional operands
in a charstring that also contains blends.

Remove command-capture branches made redundant by the full-instancing
control flow.

Testing: meson test -C build (295 passed, one skipped).

Assisted-by: OpenAI Codex
2026-10-27 15:42:35 -06:00
nussaiba shaikh d2202126e2 Read 24-bit coverage offsets in ContextFormat3_6::depend
ContextFormat3_6<MediumTypes> (context format 6) stores its input
Coverage offsets as Offset24, but depend() passed them to
context_depend_lookup() cast to HBUINT16, so every input position
after the first decoded the wrong bytes as its offset.
intersects_coverage() then followed that value to a Coverage table
sanitize never checked.

With small offsets the misread value is 0, which points at the
subtable header, and the nested lookup's dependencies are silently
dropped.  A crafted rule can instead point the misread offset at bytes
shaped like a large Coverage, and CoverageFormat1_3::intersects() reads
past the end of the GSUB blob (ASan heap-buffer-overflow via
hb_subset_depend_from_face_or_fail).

The other ContextFormat3_6 methods pass coverageZ.arrayZ + 1 as is and
let glyph_data_t pick the width.  Do the same here.
ChainContextFormat3 has the same cast but only has a 16-bit
instantiation.

Add a format 6 font and test to test-ot-depend.c; it fails without
the fix.  Tested with meson test under ASan+UBSan with
-Dexperimental_api=true.

Assisted-by: Claude
2026-10-28 00:03:22 +05:30
Behdad Esfahbod 75d8ac5d23 [subset] Reject unsupported symbolic CFF2 delta products (#6434)
Without coordinates, blend_arg_t stores only a flat delta vector.
A blend used as a later blend's delta loses its own deltas, changing
outlines during partial instancing or desubroutinization.

Reject that case in the usage and flatten passes. Retained subroutine
collection needs only blend identity, and full instancing evaluates
blends numerically, so keep both paths working. Mark CFF2 planning
failures as serialization errors so the subset API returns failure
instead of a face missing its outline table.

Add a generated two-axis font and exercise retained subsetting, full
instancing, rejected partial/desubroutinized products, and supported
nested defaults. The regression fails before the fix. Full Meson suite:
272 passed, one skipped.

Assisted-by: OpenAI Codex
2026-10-22 13:04:52 -06:00
Behdad Esfahbod 51c6d7676c [subset] Recompute glyph headers when instancing at default (#6436)
A partial TrueType instance can round a child's points and its
component offset independently. A later full instance at the remaining
axes' defaults recalculates bounds but leaves the source glyph header
unchanged, so it can disagree with the stored component geometry and
with the updated global bounds.

Compile glyphs through the owned-byte path for default pins as well,
and free those buffers on both serialization and failure paths.

Add a generated regression where partial instancing stores child xMax
11 and component offset 1, then default instancing must write xMax 12.
The assertion fails before the fix. The full Meson suite passes with
272 tests successful and one skipped; OTS accepts the source fixture.

Assisted-by: OpenAI Codex <codex@openai.com>
2026-10-22 12:55:36 -06:00
Behdad Esfahbod dde7da182e [subset] Reject CFF calls without an immediate subroutine number
Retained subroutine remapping assumes the number preceding a call is
in the same program. Caller-supplied targets violate that assumption
and can silently change glyph outlines when unused subroutines are
removed. Enforce the existing support boundary in CFF1 and CFF2.

Report plan failures as serialization errors, rather than silently
dropping the CFF table. Explicit desubroutinization still handles the
regression fonts and preserves both outlines.

Validation: full Meson suite, 272 passed and one skipped.

Assisted-by: OpenAI Codex
2026-10-22 17:06:10 +03:00
Behdad Esfahbod 4fc369ca36 [subset] Preserve long CFF DICT byte spans
Private DICT entries can accumulate several CFF2 blends before their
final operator. An eight-bit byte count truncated these spans modulo
256 during serialization, producing malformed output.

Use a full-width count and cover a 579-byte Private DICT with forty
variation regions and fourteen blended BlueValues.

Validation: full Meson suite, 272 passed and one skipped.

Assisted-by: OpenAI Codex
2026-10-22 17:06:10 +03:00
Behdad Esfahbod de3011962e [subset] Round CFF2 instances on absolute coordinates (#6427)
Rounding relative charstring operands independently accumulates errors,
opening contours and displacing stem hints after instancing. Track
absolute outline coordinates and stem edges, round their defaults and
surviving variation deltas, then emit relative operands again.

Preserve compact path operators. Conservatively retain relative rounding
for every glyph containing flex1, avoiding variation-dependent direction
analysis. Leave charstrings without blends unchanged.

Add a generated regression font covering closed contours, compact curves,
flexes, masks, and fractional static operands. Check full and partial
instances, contour closure, point accuracy, and the flex1 fallback. Refresh
the existing serialized CFF expectations.

Testing: the complete Meson suite passes (294 passed, one skipped), as do
the CFF2 API tests under ASan and UBSan.

See-also: https://github.com/fonttools/fonttools/pull/4338
Assisted-by: OpenAI Codex
2026-10-22 07:01:35 -06:00
Behdad Esfahbod 3272df037c [subset] Allow CFF2 VariationStores larger than 65535 bytes (#6432)
OFF 2026 section 5.3.3.11.2 permits larger ItemVariationStores and
specifies a saturated length field of 65535. Partial CFF2 instancing
currently rejects these stores while serializing them.

Saturate the field while retaining the 32-bit offset size check.
Add a font with 200 referenced regions over 60 axes and exercise
partial instancing and extents at three locations. The test fails
before the fix because the output loses its CFF2 table.

Validation: full Meson suite, 272 passed and one skipped.

Assisted-by: OpenAI Codex
2026-10-21 19:59:08 -06:00
Behdad Esfahbod 2b6ffde1e5 [cff] Discard ignored Private DICT blend operands while loading CFF2 (#6431)
The ordinary CFF2 Private DICT parser ignores hint blend operators but
leaves their raw operands on its stack. Multiple valid blend groups can
therefore overflow the stack during font loading, making glyph extents
and drawing fail. The subset parser already discards these operands.

Clear ignored operands after each hint blend in the ordinary parser too.
Add a synthetic font with two seven-result groups over 40 regions and
check its glyph extents at default and non-default locations. Each group
fits the stack, but their raw operands together exceed its capacity.

The regression fails before the fix and passes after. The complete
Meson suite passes: 272 tests passed, one skipped.

Assisted-by: Codex <noreply@openai.com>
2026-10-21 19:58:41 -06:00
Behdad Esfahbod cb56bae961 [subset] Zero CFF2 instance bounds when no glyph contributes extents (#6430)
Instancing a CFF2 font with only empty outlines leaves the head bounds
accumulator at its inverted initialization sentinels. These are then
serialized as xMin=yMin=32767 and xMax=yMax=-32767.

Reset an empty accumulator to zero after collecting CFF2 extents. This
also provides a valid FontBBox if the instance is downgraded to CFF1.

Add a reproducible synthetic font and an API regression that fails before
the fix. The regression also checks preservation of the empty glyph's
advance and bearing. The complete Meson suite passes: 272 tests passed,
one skipped.

Assisted-by: Codex <noreply@openai.com>
2026-10-21 18:13:19 -06:00
Behdad Esfahbod 54d71be605 [subset] Clamp overflowing COLRv1 variation values (#6408)
Unbounded variation deltas can overflow integer conversions while
instancing COLRv1 paints and clip boxes. Clamp coordinates, radii,
affine coefficients, and fixed-point values before narrowing them.
Keep affine base precision and existing alpha and clip rounding.

Add a generated font and regression checks for positive and negative
overflow in full and composed instances. Parenthesize the fixed-point
roundf argument so its template comma is safe for macro expansion.

Validation: meson compile -C build and meson test -C build pass
(292 tests passed, one skipped). The font regenerates identically.

Assisted-by: OpenAI Codex
2026-10-18 15:26:44 -06:00
nussaibah shaikh fe407340d5 Clamp transformed CFF2 blend deltas before int conversion (#6397)
When partially instancing a CFF2 font, the blend rewriters in
hb-subset-cff2.cc pass each old delta row through the region transform
and store the result with (int) round (transform_delta (...)).
transform_delta accumulates in double with no bound. Private DICT
operands can be BCD reals of any magnitude, so a StdVW blend delta of
1e12 yields about 3.7e11 at wght=300:600, and the double-to-int
conversion is undefined behavior (UBSan float-cast-overflow in
cff2_private_dict_blend_opset_t::rewrite_blends).

Saturate with hb_clamp_to<int>, as number_t::to_int already does.
The charstring blend rewriter uses the same expression and gets the
same clamp. Charstring operands are bounded by the 16.16 range, so
that site is not known to overflow in practice. Results that fit in
int are unchanged.

Add a regression test to test-instance-cff2 with a fixture generated
from AdobeVFPrototype.abc.otf. Under UBSAN_OPTIONS=halt_on_error=1 it
fails before the fix and passes after. The full Meson suite passes
under ASan+UBSan (290 ok).

Assisted-by: Claude
2026-10-15 11:16:49 -06:00
nussaibah shaikh 3fff90528d clamp variable advance before unsigned conversion (#6395)
get_advance_with_var_unscaled adds the HVAR/VVAR advance delta to the
base advance and returns the sum as unsigned. The delta from
ItemVariationStore::get_delta is an unbounded float, so an HVAR whose
item-variation store uses long-word (int32) deltas across several
regions that all peak at the axis extreme can make advance + roundf
(delta) exceed the unsigned range; converting that float to unsigned is
then undefined behavior (UBSan float-cast-overflow), and hb_max (0.0f,
NaN) would likewise pass NaN to the conversion. Reached from the public
hb_font_get_glyph_h_advance / v_advance on a variable font.

Clamp the accumulated value into the unsigned range with hb_clamp_to
before returning, matching the saturation already used for the
variation-derived glyph-extents arithmetic. Valid advances are
unchanged. The template is shared by hmtx/HVAR and vmtx/VVAR, so all
three advance sites are covered.

Add a regression test under test/api driving a crafted long-word HVAR;
it reports float-cast-overflow under the sanitizers job without the fix
and passes with it. The full meson test suite passes.
2026-10-14 10:51:09 -06:00
Behdad Esfahbod 2329384670 [subset] Preserve COLR sentinel-only variation maps (#6389)
COLR closure returned before planning delta-set index mappings when
there was no store or no live variation index. Variable paint and stop
serialization then failed to find their remapped bases, dropping COLR.

Remap explicit delta-set indices even when every entry is the
NO_VARIATION_INDEX sentinel. Keep variation-row planning conditional on
live rows. Cover NULL and empty stores with ordinary subsetting,
partial instancing of either axis, and full instancing.

Testing: meson test -C build passed 271 targets, with one skip.

Assisted-by: OpenAI Codex
2026-10-12 17:50:56 -06:00
Behdad Esfahbod e8ed626526 [subset] Preserve Fixed base precision in COLR affine values (#6384)
Instancing PaintVarTransform loses low Fixed bits when the stored base
is converted to float before adding its delta. This occurs at ordinary
translation values and even when the delta is zero.

Add the float delta to the precise stored integer in double precision,
then round to the target Fixed integer. Preserve the existing default
coordinate fast path.

Cover all six coefficients, signed and zero deltas, and direct and
composed instances in both axis orders at ordinary magnitudes. The
pre-fix library fails the translation regression. All 256 configured
Meson tests pass, and all 28 matrices match FontTools exactly in each
instancing order.

Assisted-by: Codex
2026-10-11 14:41:09 -06:00
Behdad Esfahbod 534f82e726 [subset] Preserve negative derived COLR radial gradients (#6387)
Reparameterize circles and color stops together when a derived radius
is negative. Preserve pad, repeat, reflect, and stable stop ordering.
Normalize constant gradients after a partial pin without creating
constant variation regions at the new default.

Allow fractional parameter shifts on the common lattice of the circle
coordinates and F2Dot14 stops. This preserves odd stop bits in ordinary
coordinate ranges that integer-only shifts incorrectly rejected.

Assisted-by: Codex
2026-10-11 14:37:21 -06:00
Behdad Esfahbod d5e4f22a13 [COLR] Round variable clip edges outwards (#6388)
Round minimum clip edges down and maximum edges up in font units.
Nearest rounding can shrink bounds and cut painted pixels.

Cover signed fractional deltas, default coordinates, rendering, and
full/composed instances in both axis orders at ordinary values.
All 256 configured Meson tests passed.

Assisted-by: Codex
2026-10-11 14:32:47 -06:00
Behdad Esfahbod fac913b1de [math] Preserve and apply shared GDEF variation indices (#6385)
MATH devices were evaluated against an empty variation store, and the
subsetter dropped them without folding deltas into the base values.
MATH users were also omitted when pruning GDEF's shared store.

Evaluate MATH VariationIndex devices with GDEF's store. Collect indices
from retained constants, glyph information, and assemblies, then fold
pinned deltas and remap residual devices during subsetting. Preserve
ordinary ppem device corrections and reject unrepresentable values.

Add a reproducible two-axis fixture covering every MathValueRecord
location, axis orders, full and partial instances, and glyph pruning.
All 255 configured tests pass; reduced-feature syntax checks pass.

Assisted-by: Codex
2026-10-11 00:41:07 -06:00
Behdad Esfahbod 5c5172fcd2 [subset] Preserve zero-contour glyph instructions when instancing (#6369)
Zero-contour glyphs can contain instructions for phantom-point metrics.
Non-default instancing discarded them, while the empty-glyph branch
also bypassed ordinary hint removal.

Copy these instructions into owned compiled storage, and remove them
when hinting is dropped. Keep discarded .notdef outlines empty.

Add generated data and regressions for ordinary subsets, default pins,
partial and full instances, hint removal, and phantom-point advances.
The configured Meson suite passes: 253 tests and one skipped.

Assisted-by: Codex
2026-10-11 00:38:02 -06:00
Behdad Esfahbod 3b39c74c3a [subset] Preserve overflowing static COLRv1 scales (#6370)
Assisted-by: Codex
2026-10-11 00:37:22 -06:00
Behdad Esfahbodandartemkulyk bc1e757db1 [subset/CBDT] Share strike data without losing bitmaps on OOM (#6368)
Identical CBLC subtables can share exact image blocks instead of
copying the same CBDT bytes for every strike. Carry forward the sharing
implementation and expected font outputs from #6287.

A cache allocation failure previously discarded a strike without
setting a serializer error, so subsetting could succeed with no bitmap
strikes. Treat cache insertion as best-effort and stop further insertions
after a cache error. Propagate failures in the required temporary image
and offset buffers to the serializer instead of silently dropping data.

Add a regression that fails all three cache allocations in turn and
compares both strikes and every image byte with uncached output. It also
checks required allocation failures cannot silently discard a strike.
The cache regression fails against the original PR and passes here.

The full configured Meson suite passed: 289 tests, including all 224
CBDT subset cases. MSVC and native 32-bit builds were not run locally.


Assisted-by: OpenAI Codex

Co-authored-by: artemkulyk <artem.kulyk@gmail.com>
2026-10-11 00:36:18 -06:00
Behdad Esfahbod 1bf17d7295 [subset] Allow instancing axes unrelated to VARC (#6265)
Replace the blanket VARC instancing rejection with validation of the
axes referenced by retained components, variation regions, and nested
conditions. Remap those indices when unrelated axes are removed, while
keeping passthrough VARC incompatible with instancing.

Preserve component-internal variation data during avar2 instancing by
avoiding culling based on font-level reachable ranges. Add drawing
comparisons and rejection tests with reproducible fixtures, including
hidden component axes and non-default unrelated-axis pins.

Serialize sparse-region axis references using the revised VARC format.
Regenerate the fixtures without changing their logical VARC contents or
other table bytes, apart from the head checksum adjustment.

Validation: meson test -C build (283 passed); subset suite (130 passed);
C++11 compile checks with HB_NO_VAR and HB_NO_VAR_COMPOSITES.

Assisted-by: Codex
2026-10-10 04:04:32 -06:00
Behdad Esfahbod 9af58580c6 [subset] Merge main into the condition precision branch
Resolve condition-evaluation conflicts while preserving the layout
instancing fixes and main's double-precision and static VARC support.

Tests: full Meson suite (279 passed), and C++11 syntax checks with
HB_NO_VAR, HB_NO_SUBSET_LAYOUT, and HB_OPTIMIZE_SIZE.

Assisted-by: OpenAI Codex <codex@openai.com>
2026-10-05 18:51:15 -06:00
Behdad Esfahbod 366065c366 [subset] Preserve large condition biases and delta residuals
Adding a fractional pinned delta to a large condition default in float
loses its low bits. A scaled 32-bit bias also loses bits when stored in
float tuples, and float variation-store accumulation can erase small
residuals when large deltas cancel.

Use double accumulation for layout condition evaluation and instancing,
keeping ordinary positioning and region-scalar arithmetic unchanged.
Split large biases into float-exact parts, which integer row assembly
combines before serializing a single neutral-region delta.

Add large-default fractional fixtures for GSUB and GPOS, with both
legacy and additive feature variations. Test a positive 1/12288 residual
at cancellation, partial and repeated instancing, and direct evaluation
of 32-bit variation deltas outside float's exact integer range.

Tests: full Meson suite (279 passed), sanitized item-varstore tests,
C++11 reduced-feature checks, and sanitized allocation sweeps over the
new fixtures (2334 full-font attempts and 21 row-encoder attempts).

Assisted-by: OpenAI Codex <codex@openai.com>
2026-10-05 18:11:53 -06:00
Behdad Esfahbod 726f2266e6 [subset] Wait for GDEF before instancing GSUB conditions
GSUB conditions need GDEF's remapped indices and precise condition
values, just as GPOS does. With avar2, GDEF waits for avar, allowing
GSUB to run first unless its dependency is explicit.

Add GSUB to the GDEF dependency and generate identity-avar2 fixtures
for legacy and additive feature variations in both layout tables.
The regressions compare shaping after partial and repeated instancing.

Tests: full Meson suite (279 passed).

Assisted-by: OpenAI Codex <codex@openai.com>
2026-10-05 18:04:51 -06:00
Behdad Esfahbod 8a9b58c30f [subset] Scan later PairPos rows when instancing device values
Instancing can add base fields absent from the source value format.
Matching the original format after an early PairSet or class row is
therefore no longer an upper bound on the effective output format.

Disable the early exit when a variation-delta map is supplied. Add
regressions for both PairPos formats and both value records, with a
zero pinned delta in the first row and a nonzero delta in a later row.

Tests: full Meson suite (279 passed), including the new regressions.

Assisted-by: OpenAI Codex <codex@openai.com>
2026-10-05 18:04:26 -06:00
Behdad Esfahbod 152313c8cc [VARC] Apply constant deltas in static fonts (#6315)
* [VARC] Apply constant deltas in static fonts

Static VARC fonts have no fvar coordinates, but sparse regions without
active axes still contribute constant deltas. Empty coordinate guards
were skipping those deltas in conditions, transforms, and axis values.

Supply an implicit zero coordinate for VARC variation-store evaluation
and remove its coordinate-presence guards. Keep inherited component
coordinates and the shared variation-store evaluators unchanged.

Add a generated static font and drawing/extents regression covering all
three consumers, with both constant and default-inactive regions.

Tests: meson test -C build (281 passed, 1 skipped); C++11 syntax checks
with default, HB_NO_VAR, and HB_OPTIMIZE_SIZE configurations.

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

* [VARC] Allow empty coordinates in the multi-item instancer

The region evaluators already treat missing coordinates as zero.
MultiItemVarStoreInstancer is used only by VARC, so remove its
coordinate-presence checks instead of supplying a dummy coordinate
from the VARC caller.

Document why empty coordinates must allow constant VARC deltas, and
the ordinary instancer's existing empty-coordinate shortcut. Leave
ordinary instancer behavior unchanged.

Tests: meson test -C build (281 passed, 1 skipped); C++11 syntax checks
with default, HB_NO_VAR, and HB_OPTIMIZE_SIZE configurations.

Assisted-by: OpenAI Codex <codex@openai.com>
2026-10-02 18:01:26 -06:00
Behdad Esfahbod c042c00839 [VARC] Preserve precision when accumulating 32-bit deltas (#6314)
Packed VARC deltas can use the full signed 32-bit range. Converting
them to float before scaling and accumulation loses small residuals
when large contributions cancel, affecting conditions, transforms,
and component axis values.

Accumulate MultiItemVariationStore deltas in double and keep condition
and axis values at that precision until comparison or rounding. Leave
region scalars, drawing transforms, and ordinary variation stores
unchanged.

Add a generated regression font covering all three consumers.

Tests: meson test -C build (281 passed, 1 skipped); C++11 syntax checks
with default, HB_NO_VAR, and HB_OPTIMIZE_SIZE configurations.

Assisted-by: OpenAI Codex <codex@openai.com>
2026-10-02 17:17:10 -06:00
Behdad Esfahbod 49d6ba3fa4 [subset] Preserve precision in variable layout conditions
Partial instancing rounds the default and surviving deltas of format-2
layout conditions independently, moving their Boolean boundary and
changing GSUB or GPOS lookup selection.

Rescale variable conditions into private variation-store rows before
integer encoding, leaving shared positioning values unchanged. Prefer
exact integers; otherwise use the available signed 32-bit precision.
Carry defaults outside int16 in a neutral variation region.

Keep source values separate from output mappings so serialization retries
start with the original condition, and make private-row order independent
of source addresses. Propagate store-instancing failures to the serializer.

Add legacy and additive feature-variation fixtures covering nested
conditions, fractional coefficients, large defaults, shared positioning
rows, and a second instancing pass.

Tested: full Meson suite with and without experimental API (279 passed;
261 passed and 1 skipped respectively), C++11 reduced-feature syntax
checks, and C++11 sanitizer builds with failing allocation checks.

Assisted-by: OpenAI Codex <codex@openai.com>
2026-10-02 14:14:29 -06:00
Behdad Esfahbod 1c06f05453 Merge pull request #5655 from harfbuzz/beyond-64k
[beyond-64k] Update to final ISO Open Font Format 5th edition standard
2026-10-02 13:07:46 -06:00
Behdad Esfahbod bd079077d2 [VARC] Update the variation-store binary format (#6312)
Use a uint32 sparse-region count, region-relative Offset32 axis
references, and an Offset32 reference to the delta-set INDEX. Update
evaluation, sanitization, and subset serialization together.

Migrate all seven affected fixtures. Their logical VARC contents and
non-VARC table bytes are unchanged apart from head checksum adjustment.

Tests: full Meson suite (277 passed), C++11 amalgamation compilation,
and compilation with HB_NO_VAR and HB_NO_BORING_EXPANSION.

Spec: https://github.com/harfbuzz/boring-expansion-spec/pull/175
Offset-base erratum: https://github.com/harfbuzz/boring-expansion-spec/issues/177
Assisted-by: OpenAI Codex
2026-10-02 12:58:52 -06:00
Behdad Esfahbod e5ce527941 [cff2] Support VARC glyphs beyond the CharStrings INDEX
OFF permits CFF2 CharStrings to omit a tail of glyphs provided by
VARC. Accept this count mismatch only when VARC is present, and
validate FDSelect against both the CharStrings and font glyph counts.
Reject malformed explicit FDSelect tables instead of using FD zero.

Add draw and count-mismatch regressions, plus FDSelect format 3 and 4
sentinel checks. The full Meson suite passes: 281 passed, 1 skipped.
C++11 syntax checks pass with extended and reduced features.

Assisted-by: OpenAI Codex <noreply@openai.com>
2026-10-02 06:43:14 -06:00
Behdad Esfahbod 955770eaa8 [subset] Preserve universal first-match records after axis pinning
A satisfied condition set becomes universal when all its conditions are
dropped, even if no remaining condition requested retention. Mark that
record universal and retain it while other axes remain, preventing
later records and an obsolete default catch-all from changing behavior.

Serialize reduced unconditional records with a null ConditionSet.
Regress GSUB and GPOS together, with an earlier conditional record and
LookupVariationRecord ADD_DEFAULT_LOOKUPS interaction. Regenerate the
existing instance goldens for the unconditional-record representation.

Testing: full Meson suite, 281 passed and one expected skip.

Assisted-by: OpenAI Codex <noreply@openai.com>
2026-10-02 06:20:51 -06:00
Behdad Esfahbod 81b68595b1 [subset] Instance FeatureVariationRecord condition formats 2-5
Legacy FeatureVariationRecords forced non-axis conditions to false when
choosing the new default features. Their empty range maps also compared
equal, discarding distinct conditional records during partial instancing.

Evaluate value and boolean conditions against the original GDEF store
at the new default, classify their surviving ranges conservatively, and
avoid range-only deduplication for complex conditions. Reuse the lookup
condition serializer to fold pinned axes and remap variation indices.
Materialize a false condition rather than emitting a null (true) offset.
Remove the unused condition-subset TODO stubs.

Add GSUB/GPOS coverage with 75 full/partial-instancing comparisons of
glyph selection and advances, covering formats 2-5 and null children.

Testing: meson test -C build (281 passed, 1 skipped); C++11 reduced-
feature syntax checks with HB_NO_VAR, HB_NO_BEYOND_64K, HB_NO_CUBIC_GLYF.

Assisted-by: OpenAI Codex <noreply@openai.com>
2026-10-02 04:49:46 -06:00