Commit Graph
319 Commits
Author SHA1 Message Date
nussaibah shaikh c89c0c4aa5 Fix signed overflow sorting axis tags (#6551)
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
2026-11-02 09:13:37 -07:00
Behdad EsfahbodandClaude Opus 4.8 220ef2ca34 [glyf] Restore scratch length when gvar fails in get_points; clear comp_points at entry
Glyph::get_points() uses scratch.comp_points as a stack shared by all
recursion levels: it appends one point per component plus four phantoms, and
every exit restores points.length to old_length -- except the exit taken when
gvar->apply_deltas_to_points() returns false (for example on a tuple whose
variationDataSize overruns its data).  Because the hb_glyf_scratch_t is cached
on the glyf (and VARC) accelerator for the life of the face, every failed
depth-0 load grows the vector permanently, until it reaches its allocation
ceiling; a VARC font can drive hundreds of thousands of such failing leaf
loads within one glyph budget, leaving tens of megabytes behind per extents or
draw call.

Balance the missing exit the way every sibling exit (and #6410) already does.
Also clear comp_points next to the existing all_points.clear() at the depth-0
entry in glyf_accelerator_t::get_points(), the only entry into the cached
scratch (the subsetter's call uses a local scratch), so the cached vector can
never carry stale points across loads even if a future exit forgets the
discipline.  No behaviour change for well-formed fonts: the resize only runs on
the failure path and comp_points is empty at entry when exits are balanced.

Adds a minimized VARC+gvar font to test/fuzzing/fonts exercising the failing
path through the shape/draw/raster/vector/subset fuzzers.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-31 21:59:50 -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 EsfahbodandClaude Opus 4.8 f2b79d995c [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>
2026-10-30 16:10:42 -06:00
Behdad EsfahbodandClaude Opus 4.8 a5235968bb [subset] Collect lookup-variation feature indices once in dedup
_GSUBGPOS_find_duplicate_features() compared every pair of same-tag
retained features and, for each pair, called
FeatureVariations::has_lookup_variations() twice -- a linear walk of the
FeatureVariations 1.1 LookupVariationRecord array -- so a font cost
features^2 x records with no work limit (31 s for a 144 KB font).

The FeatureVariationRecord half of the same question is already answered
once up front via collect_feature_indices() into the variable_features
set, so do the same for the LookupVariationRecord half:
has_lookup_variations() becomes collect_lookup_variation_feature_indices(),
called once before the loop, and the per-pair test only consults the
set.  It is collected regardless of all_axes_pinned because the old code
consulted the records in both cases, so dedup decisions are unchanged
for fonts with sorted records; the only behavioural difference is that a
record sitting after one with a larger featureIndex (which the old early
break skipped) now also keeps its feature distinct, which is the
conservative direction.  has_lookup_variations() had no other callers.

The remaining F^2/2 same-tag pair loop is pre-existing and not part of
this finding.

A timing-only regression font is added under test/fuzzing/fonts/.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 15:35:53 -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 0bfc7a9b16 [glyf] Charge composite offsets to the work budget (#6410)
* [glyf] Charge composite offsets to the work budget

Composite glyphs prepare component offsets before descending into
children. This work was not charged to the shared rendering budget,
including offsets for children later skipped by cycle detection.
Repeated preparation through COLR extents could time out the shaper.

Charge each offset before loading it and restore the scratch length
on failure. Add a cyclic-composite budget regression and the minimized
fuzzer testcase.

The full Meson suite passes (292 passed, one skipped). The reproducer
completes under ASan/UBSan in 17 seconds instead of timing out after
60 seconds. A failing-allocation variant passes 100 runs.

Fixes: https://oss-fuzz.com/testcase-detail/6193853460447232
Assisted-by: OpenAI Codex

* [glyf] Charge component preparation as traversal work

Component preparation parses records and updates scratch vectors, but
charging one unit per record still allows excessive work within the
shared budget. Use the existing 16-unit glyph traversal charge for
preparing a component, including children skipped by cycle detection.

Increase the cyclic-composite regression's budget so it also catches
the undercharged preparation path. The reproducer now takes about
1.1 seconds under ASan/UBSan and 0.03 seconds in the normal build.

Tested with the full Meson suite (292 passed, one skipped), 100
sanitizer reproducer runs, and 100 failing-allocation variant runs.

Assisted-by: OpenAI Codex
2026-10-18 19:54:45 -06:00
Behdad Esfahbod 8abfd0d16e [subset] Reject failed glyph sets before allocating flat maps (#6409)
An allocation failure can leave out-of-range glyph IDs in the GSUB
set because subsequent range deletions are skipped. Building the flat
glyph map from that set can then request several gigabytes before the
set's error state is checked.

Reject an errored GSUB glyph set before sizing the flat map, and add
the minimized fuzzer testcase to the regression corpus.

Tested with the full Meson suite (292 passed, one skipped) and 100
reproducer runs under ASan/UBSan with failing allocations enabled.

Fixes: https://oss-fuzz.com/testcase-detail/5574495277219840
Assisted-by: OpenAI Codex
2026-10-18 18:01:11 -06:00
Behdad Esfahbod a52249ff62 Merge pull request #6326 from harfbuzz/fix/cff2-fdselect-varc
[subset] Bound CFF2 FDSelect lookups by the CharStrings count
2026-10-06 19:34:36 -06:00
Behdad EsfahbodandClaude Sonnet 5.5 e6d5454350 [paint] Clamp hb_color_lerp() channels to [0,255] (#6305)
Sweep-gradient color-stop angles come from the font, so the
interpolation fraction t can fall outside [0,1] (or be NaN).  The
interpolated channel was then cast float -> unsigned directly; a
negative value (e.g. -387.671) is UB (UBSan float-cast-overflow) and
yields meaningless colors on release builds.

Clamp the interpolated channel to [0,255], mapping NaN to 0, before
the cast.  In-range behavior is unchanged.  Add the reported fuzzer
input as a seed.

Reported by iceray-Li.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-09-30 18:22:41 -06:00
Behdad EsfahbodandClaude Sonnet 5.5 b7fca823a0 [avar] Clamp instantiated axis-value maps to F2DOT14 range (#6303)
AxisValueMap::instantiate() renormalizes the from/to coordinates and
stores them with set_float() without clamping.  With malformed input
the result can fall outside [-1,1] (e.g. 2.192 -> 35923), overflowing
the int16 F2DOT14 storage: UB under UBSan's float-cast-overflow, and a
silently truncated avar table otherwise.

Clamp both coordinates to [-1,1] before storing.  Add the reported
fuzzer input as a seed.

Reported by iceray-Li.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-09-30 18:03:28 -06:00
Behdad Esfahbod b3bab62307 [VARC] Clamp component axis coordinates (#6274)
Axis-value variation deltas can push a rounded component coordinate
outside the range of int. Assigning that float to coord_setter then
triggers undefined behavior in the conversion.

Use hb_clamp_to<int>() after rounding, preserving in-range behavior
while saturating extreme values. Add the minimized raster-fuzzer input.

Tested with meson test -C build and the ASan/UBSan raster fuzzer.

Assisted-by: OpenAI Codex
2026-09-21 12:15:48 -06:00
Behdad EsfahbodandClaude Fable 5.1 64e2b53235 [glyf] Charge point loading to the work budget before doing the work (#6256)
The glyf outline budget was only charged after a glyph loaded
successfully: Glyph::get_points() spent 16 units per node up front, and
glyf_accelerator_t::get_points() charged one unit per point only after
the whole tree came back.  A glyph that loaded ~175K points and then
tripped a structural cap (HB_GLYF_MAX_POINTS, edge count) paid for the
nodes but not the points.  Driven from a COLR paint walk through
hb_font_get_glyph_extents(), one such glyph was loaded and thrown away
over 8000 times per session within the budget, ~1.4G point loads.

Charge at the point where the work is attempted instead:

- SimpleGlyph::get_contour_points() takes the budget and charges
  num_points before allocating, clearing, and reading, so truncated or
  later-rejected glyphs pay for the points they allocate.

- Composite levels charge the component subtree size before
  transform_points(), since each nesting level transforms every point
  below it and that multiplication was previously invisible to the
  budget.

The terminal per-point charge for path emission is unchanged.

Local hb-vector-fuzzer run on the testcase: 4.3s -> 0.12s.  Full test
suite passes.  The testcase is added as a fuzz seed.

Fixes: https://oss-fuzz.com/testcase-detail/5714817420427264


Claude-Session: https://claude.ai/code/session_013ksLGe7wUVwbuANqR56YaN

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 22:19:47 -06:00
Behdad Esfahbod 3baafbcb3d [raster] Clip the edge sweep's column walk to the surface (#6251)
* [raster] Clip the edge sweep's column walk to the surface

edge_sweep_row() walked every fixed-point pixel column an edge spans,
even though columns right of the surface contribute nothing and
columns left of it only contribute a cover delta that telescopes into
column 0.  A near-horizontal edge with extreme coordinates could span
~2^24 columns per row, making sweep cost proportional to coordinate
range instead of surface width: the ClusterFuzz testcase took 114s in
a plain release build.

Fold the left-of-surface portion of the walk into a single column-0
cover update, skip the right-of-surface portion, and enter/exit the
per-column loop at the visible window.  Jumping the incremental fy
accumulator by k*delta_fy is exact, since the increment is constant
and the running sums are bounded, so output is bit-identical; verified
by comparing 178 hb-raster renders (draw and paint paths, several
fonts, sizes, and negative-margin crops that clip edges off-surface)
byte-for-byte against the previous code.  The testcase now runs in
0.17s.  Also add it as a fuzz seed.

Fixes https://oss-fuzz.com/testcase-detail/5267980968329216

Assisted-by: Claude Fable 5 <noreply@anthropic.com>

* [raster] Keep an unclipped fast path in the edge sweep

The window clipping added in the previous commit made every
multi-column edge-row pay for the clip setup, measurable as ~1% more
instructions rasterizing all glyphs of NotoSansCJKsc/SourceHanSans-VF
at 256px with hb-raster-all.  Guard it with a two-compare
fully-inside-the-surface check and walk such edges with the original
unclipped code, which is also the everyday case: auto-sized surfaces
always contain their edges.

Interleaved perf-stat A/B (5 rounds, all glyphs at 256px): instruction
overhead drops to +0.24% (CJK) / +0.9% (AwamiNastaliq, tiny workload);
cycles flat to -1.3%, within noise.  Output remains bit-identical on
the 178-render comparison matrix, and the oss-fuzz 5267980968329216
testcase stays at 0.19s.

Assisted-by: Claude Fable 5 <noreply@anthropic.com>

* [raster] Charge column spans in the pixel-work estimate

hb_raster_draw_get_pixel_work() charged each edge only its scanline
span, so a nearly-horizontal edge crossing one pixel row but sweeping
the full surface width cost up to `width` cells while being charged 2
units — the paint path's pixel-budget precharge could undercharge the
sweep by a factor of the surface width.  This is the same blind spot
that let the previous commits' column-walk timeout through the paint
path's precharge.

Charge each edge its column span too, clipped to the surface width the
same way the row span is clipped to its height.  Since an edge is a
straight segment, row span plus clipped column span is a true upper
bound on the post-clipping sweep work.  Normal outlines are barely
affected: flattening yields short segments whose column spans are
commensurate with their row spans, far below the 2^26 budget.

No rendering change: the 178-render comparison matrix remains
bit-identical and the full test suite passes.

Assisted-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-10 14:30:09 -06:00
Behdad Esfahbod 46ea946ab4 Merge pull request #6214 from harfbuzz/rendering-work-budgets
[limits] Add rendering work budgets
2026-09-06 16:36:58 -06:00
Behdad Esfahbod 037aa79451 [fuzzing] Add rendering budget timeout seeds
Add the minimized vector, raster, and GPU testcases that exercise the
aggregate outline-expansion timeout.  Keeping the OSS-Fuzz testcase IDs
in their filenames makes each regression directly traceable.

The current leaf-level limits allow all three inputs to complete in the
optimized test build; later aggregate accounting will reduce their work
further.

Tests: meson test -C build

Assisted-by: OpenAI Codex <codex@openai.com>
2026-08-26 16:41:49 -06:00
Garret Rieger 5f16f4ba68 In pair pos format 2 splitting only recompute coverage size when the included glyph set changes.
Assisted by Gemini
2026-08-26 14:24:53 -06:00
nussaibah shaikh 64dab85712 [depend] avoid inputCount underflow in context depend loops (#6211)
context_depend_lookup and chain_context_depend_lookup build the
input-position glyph sets with for (i = 0; i < inputCount - 1; i++),
so a Rule with inputCount 0 (what a null rule offset resolves to)
underflows the bound to UINT_MAX and reads past the object into the
Null pool. Rewrite both loops as i + 1 < inputCount, matching the
guarded inputCount handling used everywhere else in the file. Reached
from hb_subset_depend_from_face_or_fail on a crafted GSUB context
rule; seed added under test/fuzzing/fonts.
2026-08-26 08:52:19 -06:00
nussaiba shaikh 66ef3397ea [depend] Bound context inputCount to HB_MAX_CONTEXT_LENGTH
context_depend_recurse_lookups tracks covered sequence positions in
a fixed hb_bit_page_t, but the dependency-graph path never bounded
inputCount the way the shaping apply path does. A crafted GSUB
contextual rule with glyphCount past the page (e.g. 512) and a
SubstLookupRecord whose sequenceIndex lands in a higher page element
than endIndex makes hb_bit_page_t::add_range compute its memset
length as (char*)lb - (char*)la, which is negative and wraps to a
huge size_t, writing past the stack-allocated page. Reachable from
hb_subset_depend_from_face_or_fail on a crafted face.

Cap inputCount at HB_MAX_CONTEXT_LENGTH before the page is used,
matching the apply path; rules longer than that never apply during
shaping, so no real dependency edges are lost. Adds a regression
seed exercised by the depend fuzzer.
2026-08-24 14:57:59 +05:30
Garret Rieger 6c2107ace7 Fix arithmetic overflows in IUP handling.
Fixes https://oss-fuzz.com/testcase-detail/4688270404157440.
2026-08-17 19:09:43 -06:00
Behdad Esfahbod d54151cf08 Merge pull request #6169 from harfbuzz/raster-flatten-clip
[raster] Clip and budget Bézier flattening
2026-08-17 17:10:07 -06:00
Behdad Esfahbod c1b4afecfa [test] Add fuzz seed for raster flattening timeout
The seed's COLR paint walk fills glyphs whose gvar-varied cubics have
astronomically large control points; each curve recursed to the full
depth-16 subdivision cap while emitting no edges, invisible to the
edge-based paint budget.  Timed out on ClusterFuzz before the two
preceding commits.

https://oss-fuzz.com/testcase-detail/4912367159541760

Assisted-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-17 14:38:00 -06:00
Behdad Esfahbod beae23d0a7 [test] Add fuzz seed for vector number-formatting timeout
The seed's COLR paint walk emits a full 16MB vector-paint work
budget of path text from a single large gvar-varied glyf glyph;
before the preceding commit the snprintf-based number formatting
made that blow the 60s ClusterFuzz timeout on i386 ASAN builds.

https://oss-fuzz.com/testcase-detail/4700345193005056

Assisted-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-17 14:14:28 -06:00
Behdad Esfahbod dfdc088c4d Merge pull request #6158 from harfbuzz/fix-raster-surface-clear
[raster] Stop re-clearing the root surface after failed initialization
2026-08-13 12:48:03 -06:00
Behdad Esfahbod 7244b5da86 [test] Add fuzz seed for raster surface re-clear timeout
Under the fuzzer's failing-malloc allocator, the font drives a COLR
paint graph whose session initialization fails its stack push and
then re-cleared a 4096x4096 root surface on every one of ~2240
paint callbacks, timing out on ClusterFuzz before the previous
commit.

https://oss-fuzz.com/testcase-detail/4604877465255936

Assisted-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 12:09:54 -06:00
Behdad Esfahbod 738e09b075 [test] Add fuzz seed for sweep-gradient tile timeout
The font drives two sweep gradients with 27648 color stops over an
angular span of ~0.0008 rad with a repeat extend, previously
emitting ~140M Coons patches in the PDF vector backend and timing
out on ClusterFuzz before the preceding two commits.

https://oss-fuzz.com/testcase-detail/6490910482038784

Assisted-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 11:48:04 -06:00
Behdad Esfahbod 1f30c6d4cc [raster] Widen edge-span subtraction (#6153)
The edge-work estimator cast the result of the y-coordinate
subtraction to int64_t, after the subtraction had already happened in
int32_t. An edge spanning the clamped coordinate range could therefore
overflow before the work was capped to the surface height.

Widen both operands before subtracting, matching the existing edge
slope calculation, and add the minimized OSS-Fuzz reproducer to the
fuzz corpus.

Fixes: https://oss-fuzz.com/testcase-detail/5773854015029248

Assisted-by: OpenAI Codex <noreply@openai.com>
2026-08-12 18:27:36 -06:00
Behdad Esfahbod 3344283d4a [test] Add fuzz seeds for budget-multiplication timeouts
The raster seed drives ~2048 COLR PaintComposite nodes each costing
a full-surface composite; the gpu seed drives a VARC composite glyph
whose components each load a large glyf leaf glyph.  Both timed out
on ClusterFuzz before the preceding work-budget commits.

Assisted-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-10 14:27:56 -06:00
Behdad EsfahbodandClaude Sonnet 5 bbfe29975d [raster] Cap font-derived surface dimensions at 4096 pixels per side
When no extents are set explicitly, the paint and draw contexts
derive the surface size from font data: glyph extents (which the
auto path in hb_raster_paint_glyph_impl () feeds through
set_glyph_extents ()) or the accumulated outline bounds in
hb_raster_draw_render ().  A malicious font with a tiny upem and
huge glyph coordinates turns that into arbitrarily large
allocations: a 49 KB fuzz font produced several ~885 MB BGRA
surfaces live at once (root surface plus one per PaintComposite
push_group), nearly 4 GB total.

Add HB_RASTER_MAX_AUTO_DIMENSION (4096) to hb-limits.hh and clamp
width/height at the three font-derived sizing points: both
set_glyph_extents () implementations and draw render's
auto-size-from-edges path.  Since push_group and clip surfaces
inherit fixed_extents, the cap bounds those too.  Extents set
explicitly via hb_raster_{draw,paint}_set_extents () are not
limited.

Fixes an hb-raster-fuzzer out-of-memory finding (testcase
6344015149858816): peak RSS 3.47 GB before, 350 MB after.
Testcase added as a fuzz seed.  Full meson test suite passes.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-10 13:14:53 -06:00
Behdad EsfahbodandClaude Sonnet 5 c2b6b09ed2 [raster] Fix signed overflow computing row bottom at coordinate limit
edge_sweep_row () computed y_bot = y_top + ONE_PIXEL in int32.  The
scanline loop clamps y_top itself to INT32_MAX, but when the surface
sits at the extreme of the 24.8 fixed-point coordinate space y_top
can be within ONE_PIXEL of INT32_MAX (0x7FFFFF00), and the addition
overflows: UBSan "2147483392 + 256 cannot be represented in type
'int'".

Saturate the addition at INT32_MAX using the same 64-bit-then-clamp
idiom already used for y_top and the x interpolation.  Edges are
int32-clamped too, so no coverage exists beyond INT32_MAX and the
clipped bottom band loses nothing real.

Fixes ClusterFuzz issue 541858526 (testcase 5513551012495360).
Reproduced with a -Db_sanitize=undefined build: one UBSan report
before, clean after.  Testcase added as a fuzz seed.  Full meson
test suite passes.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-10 12:55:45 -06:00
Behdad EsfahbodandClaude Sonnet 5 d94c18b6a6 [subset] Clamp variable advances to UFWORD range in plan
When instancing, the hmtx/vmtx advance is computed by adding the
HVAR/VVAR delta to the base advance.  The delta is attacker-
controlled and unbounded, so the sum can go negative or exceed
65535.  The negative case, cast to unsigned, produced advances
near 4 billion in hmtx_map; CFF::optimize_widths () then looped
over the full [min_w, max_w] width range, taking minutes (the
oversized cumsum resize fails cleanly, so this was a pure hang,
no memory unsafety).

Clamp the computed advance to [0, 0xFFFF], matching the UFWORD
range that hmtx/vmtx serialization stores and the hb_max (0.f, …)
clamp already used by the runtime metrics path.

Fixes a ClusterFuzz timeout in hb-subset-fuzzer (testcase
4846730722738176, minimized from timeout-fd8f4bd2a650).  The
testcase went from >60s to 5ms; added as a fuzz seed.  Full
meson test suite passes.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-10 12:47:41 -06:00
Nussu06 1737bce456 [subset] bound cvar tuple data length in calculate_cvt_deltas 2026-07-18 07:25:19 -06:00
Behdad EsfahbodandClaude Opus 4.8 9072836ef5 [vector-pdf] Fix indexed-PNG tRNS soft-mask dimension overflow
hb_pdf_build_indexed_smask() computed its buffer sizes with unchecked
32-bit arithmetic:

    unsigned raw_len = (width + 1) * height;
    ...
    out->resize (width * height);

width/height come straight from the attacker-controlled PNG IHDR (the
vector-PDF path re-parses IHDR itself and does not clamp dimensions,
unlike sbix).  For width = height = 65536, (width + 1) * height wraps to
65536 and width * height wraps to 0.  A crafted IDAT inflating to the
wrapped raw_len passes the length check, the mask buffer is resized to
zero, and the per-pixel loop then writes through out->arrayZ[y*width+x]
and reads past raw -- an out-of-bounds write / NULL-page store and crash.

Reject zero/degenerate dimensions and use hb_unsigned_mul_overflows()
for both (width + 1) * height and width * height before allocating,
sizing the inflate, and indexing.  This bounds every subsequent
raw + y*(width+1) and out->arrayZ[y*width+x] access.

Add a CBDT regression seed embedding a 65536x65536 indexed PNG with a
tRNS chunk; it reaches the soft-mask builder through
hb_font_paint_glyph -> CBDT::paint_glyph -> hb_pdf_paint_image and
crashed pre-fix under ASAN/UBSan at hb-vector-paint-pdf.cc:617.

Fixes: GHSA-gmjm-qc3c-qfp8
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 00:16:00 -06:00
Behdad EsfahbodandClaude Opus 4.8 9a55008395 [vector-pdf] Fix PLTE chunk-length wrapping OOB read in PNG parser
The PNG chunk-bounds check in hb_pdf_paint_image() used wrapping
32-bit unsigned arithmetic:

    if (pos + 12 + chunk_len > len)
      break;

A large attacker-controlled chunk_len (e.g. 0xFFFFFF30) wraps
pos + 12 + chunk_len below len, so a truncated PLTE chunk passes the
check.  The oversized plte_len is then trusted during palette
serialization in add_xobject_png_image(), reading far past the input
buffer -- an out-of-bounds read and deterministic crash.

Rewrite the bounds checks to be non-wrapping, relying on the invariant
pos <= len (len >= 8 is checked earlier): gate the loop on
len - pos >= 12 and reject a chunk with chunk_len > len - pos - 12.
This keeps pos <= len across pos += 12 + chunk_len and makes every
in-loop read (chunk header and chunk payload) provably in bounds.

Add a regression seed font that embeds a malformed indexed PNG with an
oversized PLTE length via sbix.  It reaches the vector-PDF paint path
through hb_font_paint_glyph -> sbix::paint_glyph -> hb_pdf_paint_image
and crashed pre-fix under ASAN at hb-vector-paint-pdf.cc:222; it now
renders cleanly.

Fixes: GHSA-9m78-3jcg-57f2
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 00:08:05 -06:00
Behdad Esfahbod 760470e91e [raster] Avoid clip mask origin overflow (#6044)
Clip mask extents can have extreme signed origins after malformed
or heavily transformed outlines. Subtracting the surface origin in
int overflowed for cases such as 0 - INT_MIN.

Keep the mask-to-surface coordinate conversion in int64_t until
after intersecting with the finite clip and surface bounds, then
convert to unsigned only for proven in-range pixels.

Add the minimized OSS-Fuzz seed to the raster fuzzer corpus.

Testing: meson test -C build
Fixes: https://oss-fuzz.com/testcase-detail/4621471331450880
Assisted-by: OpenAI Codex <codex@openai.com>
2026-06-29 15:26:24 -06:00
Qunxin Liu 209a7237b9 [repacker] fuzzer fix: duplicate shared liga_sets before splitting (#5972)
fix for: https://oss-fuzz.com/testcase-detail/5291844211900416
2026-05-01 14:50:05 -06:00
Behdad Esfahbod e4d1127676 [test] Add one more fuzzer font 2026-04-17 16:23:42 -06:00
Behdad Esfahbod 0f9e0ba2a5 [gpu] Fix signed integer overflow in extents computation
Glyph extents from malicious fonts can have extreme values
that overflow when computing x_bearing + width or the
width/height deltas in hb_gpu_paint_encode.  Widen to int64_t
before the arithmetic.

Fixes: https://oss-fuzz.com/testcase-detail/crash-8a9ba2164fd1e6a6fd7a8ed566cf4d0350c1357e

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-17 16:20:14 -06:00
Behdad Esfahbod 82cba44644 [gpu] Fix out-of-bounds read in emit_all_clip_sub_blobs
When clip nesting exceeds HB_GPU_PAINT_MAX_CLIP_DEPTH (3),
push_clip_glyph sets unsupported=true but still increments
clip_depth.  emit_all_clip_sub_blobs then iterated clip_depth
without capping, reading past the fixed-size clip_stack array.

Cap the iteration at HB_GPU_PAINT_MAX_CLIP_DEPTH.

Fixes: https://oss-fuzz.com/testcase-detail/6573156621156352

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-17 16:17:42 -06:00
Behdad Esfahbod df4be0cec8 [gpu] Use vector.reset() not resize(0) in hb_gpu_paint_clear
Three accumulator vectors -- ops, sub_blobs, transform_stack --
can enter error state via failed push_or_fail() under
failing-malloc.  Once in error state, resize(0) short-circuits
at the in_error() guard in alloc() and leaves length unchanged.

In hb_gpu_paint_clear that means the next iteration's clear
walks the stale entries again.  For sub_blobs this is a
double-destroy: the blob pointers were already freed in the
previous clear, and hb_blob_destroy reads the dead ref_count
field -- heap-use-after-free.

Fix by calling vector.reset(), which clears the error state
before resizing to 0.  Matches the pattern hb_gpu_draw_clear
already uses for draw->curves.

Found by oss-fuzz/CIFuzz on hb-gpu-fuzzer; minimized testcase
added to the fuzz corpus.

Assisted-by: Claude <noreply@anthropic.com>
2026-04-14 21:49:12 -06:00
Behdad Esfahbod 25bfb5adc3 [vector-paint/pdf] Check color-stops vector resize under failing-malloc
Two sites queried color-stop count, resized the scratch vector to
match, then called hb_color_line_get_color_stops() passing the
requested count as the write capacity.  If the resize() failed
(OOM), the vector stayed at its previous (smaller) length while
the callee still wrote the full requested count -- heap-buffer-
overflow.

Fixed by checking resize() and bailing: build_gradient_function
returns 0, paint_sweep_gradient returns.  Matches the pattern
already used in hb-raster-paint.cc and hb-vector-paint.cc.

Found by oss-fuzz/CIFuzz on hb-vector-fuzzer against a sweep-
gradient COLRv1 glyph under failing-malloc.

Assisted-by: Claude <noreply@anthropic.com>
2026-04-14 21:36:18 -06:00
Behdad Esfahbod 6c2afd1e0e [geometry] Clamp glyph extents conversion
hb_extents_t::to_glyph_extents() rounded bounds to hb_position_t
before subtracting them. Extreme extents from fuzzed VARC and
raster paths could therefore overflow signed int arithmetic while
forming glyph widths or heights.

Compute the rounded endpoints in double, clamp the exported values
to hb_position_t, and reject non-finite results. Also avoid the
same overflow in the reverse hb_glyph_extents_t constructor, add
an internal regression for the shared helper, and include the
minimized raster testcase.

Fixes: https://oss-fuzz.com/testcase-detail/4826864710647808
Not-tested: Skipped by request.
Assisted-by: OpenAI Codex
2026-04-09 23:21:05 -06:00
Behdad Esfahbod b5287cb3fb [gpu] Clamp exported draw extents
hb_gpu_draw_get_extents() cast rounded bounds to hb_position_t
before subtracting them. A fuzzed glyph outline with an extreme
negative bound could therefore overflow signed int arithmetic while
forming width or height.

Compute the rounded bounds in double, reject non-finite values, and
clamp the exported extents to hb_position_t before returning them.
Add an API regression that covers the OSS-Fuzz testcase through the
public GPU draw API.

Fixes: https://oss-fuzz.com/testcase-detail/5918954634936320
Tested: meson test -C build --print-errorlogs
Assisted-by: OpenAI Codex
2026-04-09 23:15:34 -06:00
Behdad EsfahbodandOpenAI Codex 03c262d1eb [raster] Clamp reflected gradient LUT coordinates
Malformed reflected gradients can produce very large finite
gradient parameters. The raster backend normalized reflect
mode by casting floorf(t) to int, which can overflow and
drive LUT lookups past the fixed-size stack buffer.

Fold reflected coordinates with fmodf(), clamp LUT inputs
defensively, and add the minimized oss-fuzz raster
testcase to the corpus.

Fixes: https://oss-fuzz.com/testcase-detail/6597066439852032
Tested: meson test -C build
Co-Authored-By: OpenAI Codex <codex@openai.com>
2026-04-06 17:13:58 -06:00
Behdad Esfahbod e8c5bb452d [raster] Widen edge row interpolation arithmetic
edge_sweep_row() computed the clipped endpoint x coordinates with
int32_t subtractions before casting to int64_t. If an edge started at
INT32_MIN and the scanline clipped endpoint was near zero, ey - yL
overflowed before the slope multiply and UBSan flagged the raster
fuzzer path.

Keep the endpoint interpolation and follow-on dx math in 64-bit until
clamping back to int32_t. This preserves the existing rasterizer logic
while avoiding signed overflow for extreme edge coordinates.

Tested:
- meson test -C build

Assisted-by: OpenAI Codex <codex@openai.com>
2026-04-03 18:07:28 -06:00
Behdad EsfahbodandOpenAI Codex 19e4bf2597 [raster] Validate non-rect clip masks before reuse
The raster paint clip code indexed non-rect clip alpha rows directly,
assuming the clip metadata always matched a full stride*height backing
buffer. Fuzzing showed that reused clip objects can reach those reads
with stale scalar state, which turns the row access in
push_clip_rectangle() into a heap-buffer-overflow.

Reset cached clip geometry on acquire, add a validity check for
non-rect alpha masks, and refuse to build new clip intersections from
an invalid mask. The fallback is an empty clip, which keeps the paint
path safe without affecting well-formed clips.

Testing:
- meson test -C build --suite fuzzing --print-errorlogs
- meson test -C build

Co-authored-by: OpenAI Codex <codex@openai.com>
2026-04-03 17:17:49 -06:00
Behdad EsfahbodandOpenAI Codex 98866c9fef [svg] Zero-initialize doc cache parser structs
MemorySanitizer reported use of uninitialized data while building the
SVG document cache used by vector painting. The parser keeps small
aggregate structs on the stack, and their padding could stay poisoned
as they were copied through the open-element stack.

Zero-initialize the parser stack and the temporary span / element
records before filling their fields. That keeps later copies and
container insertions from carrying undefined padding into the MSan
instrumented path.

Testing:
- meson test -C build --suite fuzzing --print-errorlogs
- meson test -C build

Co-authored-by: OpenAI Codex <codex@openai.com>
2026-04-03 16:49:48 -06:00
Behdad EsfahbodandOpenAI Codex bfafd9d648 [gpu] Check draw encode size arithmetic
The GPU fuzzer can build outline data large enough to stress the size
math inside hb_gpu_draw_encode(). Several totals and byte counts were
computed with unchecked unsigned arithmetic before the existing bounds
checks ran.

Use HarfBuzz's overflow helpers for band-index totals, encoded blob
lengths, byte sizes, and recycled-buffer growth. Also rewrite the
uint16-offset limit check so it does not rely on subtracting from an
already-overflowed total.

Testing:
- meson test -C build --suite fuzzing --print-errorlogs
- meson test -C build

Fixes: https://oss-fuzz.com/testcase-detail/6336503637934080
Co-authored-by: OpenAI Codex <codex@openai.com>
2026-04-03 16:44:50 -06:00
Behdad EsfahbodandOpenAI Codex 92b9b1ed82 [docs] Clarify OOM policy for experimental libraries
Document that raster, vector, and gpu still must not crash,
access out of bounds, or corrupt memory under failing-malloc,
but best-effort early failure is acceptable and complex rollback
logic is not required after OOM.

Co-authored-by: OpenAI Codex <codex@openai.com>
2026-04-03 16:24:31 -06:00
Behdad EsfahbodandClaude Opus 4.6 f0c127fc62 [fuzzing] Remove _fuzzing_skip_leading_comment
The leading-comment mechanism corrupted fuzzer font files by
prepending non-font data.  Remove the function, its callers,
and strip the one seed file that had a leading comment.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-28 00:14:36 -06:00