Commit Graph
1187 Commits
Author SHA1 Message Date
ebraminio 2f489784c8 [subset] Support longintdict encoding (#6584)
* [test] Expand CFF number font parsing to subsetter encoding roundtrip

* [subset] Support longintdict encoding

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

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

* [cff] Extract nibble_buffer_t to avoid heap allocated hb_vector_t

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

Address review

* [cff] Minor touches

* [cff] Use idempotent ensure_error instead of set_error

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

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

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

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

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

Assisted-by: Codex

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

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

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

Assisted-by: Codex

* [subset] Borrow GDEF before shaping's blocklist

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

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

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

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

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

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

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

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

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

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

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

Fixes: #6446
Assisted-by: OpenAI Codex

* [buffer] Rename new deserializers to use 2 suffix

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

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

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

Keep test_subset_gvar_valid_data_offsets_control and
test_subset_gvar_data_offset_overflow_rejected unchanged.

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-02 10:52:07 -06:00
Behdad EsfahbodandClaude Opus 4.8 5ef8ef9281 [kerx] Charge format-4 control-point actions' contour-point lookups to max_ops
A kerx format-4 control-point action asks the font for two glyph
contour points, which the font functions may satisfy by loading the
whole glyph outline (two full FT_Load_Glyph calls with hb-ft).  The
state-machine driver charges a non-advancing transition only one op,
so a looping entry turned the whole work budget into glyph loads:
two letters and a 680-byte font stalled hb_shape() for seconds.

Charge 2 * HB_BUDGET_256 to buffer->max_ops at the action, before the
callbacks, using the same decrement-and-return idiom morx insertion
uses; once the budget is spent the action is skipped and the driver's
existing max_ops check forces the machine forward.

The sibling GPOS AnchorFormat2 contour-point path has the same
uncharged callback but lives in the layout subsystem and is left for
a separate change.  GDEF CaretValueFormat2 also calls it but only
from hb_ot_layout_get_ligature_carets, bounded per API call.

Regression test in test/api/test-shape.c uses a counting
glyph_contour_point callback on a builder-made looping kerx font
(131074 calls before, <= 256 after).

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-02 10:52:07 -06:00
Behdad EsfahbodandClaude Opus 4.8 cf9889b73f [aat] Reject kern/kerx/mort/morx tables declaring too many subtables
The kern/kerx accelerator keeps two hb_bit_set_t per subtable and
mort/morx keeps one per subtable, all built eagerly when the shape
plan is compiled and held for the life of the face.  A 14-byte kern
format-3 subtable fills both sets with every glyph, so heap use was
about 2100x the font size with nothing bounding the subtable count;
morx is worse because overlapping chains can claim each other's
subtables.  A ~560 KB kern font drove shaping one letter to 1.1 GiB.

Add HB_AAT_MAX_SUBTABLES (1024) to hb-limits.hh and enforce it in
sanitize, the way GSUB/GPOS already bound their subtables via
visit_subtables (whose 0x4000 limit is too loose here -- 16383 kern
subtables still peak at hundreds of MiB).  KerxTable::sanitize()
(shared by kerx, OpenType kern and Apple kern) fails when tableCount
exceeds the limit, and mortmorx::sanitize() fails once the chains'
subtable counts add up past it.  Over-limit tables are dropped
entirely (the font shapes without kerning/morx); real fonts under
test/ declare at most three kern/kerx subtables and one morx chain.

Regression test in test/api/test-aat-layout.c builds kern and morx
faces with hb_face_builder and checks both sides of the limit.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-02 10:51:40 -06:00
Behdad Esfahbod e8a7f183fe [paint] Preserve void extents through transformations (#6548)
Honk paints an empty outline as one of its COLR layers. Transforming its
void bounding box orders the sentinel corners into a real rectangle at
(-1,-1)-(0,0), even with the identity transform. That rectangle expands
the accent's ink bounds toward the origin and shifts fallback marks by
hundreds of units.

Keep void extents void when applying a transform. Add shaping regressions
for normal and double scale and vertical layout using a default-instance
Honk subset, with its OFL embedded in the name table.

Current read-fonts already computes the correct COLR bounds. Removing
only the empty layer also makes unpatched HarfBuzz match HarfRust,
confirming the cause of harfrust#553.

Update the existing vertical-origin overflow fixture to use an explicit
COLR clip box. Assert that its height still clamps to INT_MIN so the
original negation-overflow regression stays covered after void bounds
stop producing artificial ink.

Testing: meson test -C build (276 passed).

Fixes: https://github.com/harfbuzz/harfrust/issues/553
Assisted-by: OpenAI Codex
2026-11-01 19:26:02 -07:00
Behdad EsfahbodandNathan Keys a945625923 [subset] Bound CFF2 blends and serialization fields (#6546)
* [subset] Bound CFF2 blend values and serialization fields

Clamp fully pinned Private DICT blend sums before converting to int.
Reject CFF2 Top DICT sizes, variation-store counts, and region indexes
that cannot fit their serialized fields. Check VarRegionList counts
and byte-size multiplication before writing or allocating output.

Keep the CFF2 API regressions and move variation-region serialization
coverage into test-item-varstore. Use hb_always_assert and compact
boundary cases instead of custom macros, command-line selectors,
duplicate controls, and constant-condition checks. Verify that valid
region lists survive serialization and remapping unchanged.

The new CFF2 API regressions fail against unpatched main and pass with
these fixes. All 277 Meson tests pass, including all 133 subset tests.
The item-varstore tests also compile with HB_NO_VAR.

Based on the hardening patch in PR #6532.

Co-Authored-By: Nathan Keys <professor.moody@pm.me>
Assisted-by: OpenAI Codex

* [meson] Link the IUP optimizer into the CFF2 serialization test

The CFF2 serialization test instantiates tuple variations. Its object can
therefore reference iup_delta_optimize even though CFF2 does not enable
IUP optimization. Some compilers retain that reference and fail to link
the test; the local optimized build had eliminated it.

Include the IUP implementation in the test target, as the other tuple
and item varstore tests already do.

Reproduced the undefined reference by compiling the CFF2 test object at
-O0. It links and passes after adding the dependency. All 277 tests pass
with meson test -C build.

Assisted-by: OpenAI Codex

---------

Co-authored-by: Nathan Keys <professor.moody@pm.me>
2026-11-01 19:15:30 -07:00
Behdad EsfahbodandClaude Opus 4.8 e95283e73e [harfrust] Report shaping failures via hb_buffer_allocation_successful() (#6545)
HarfRust signals a shaping failure -- a max_ops / preprocessing-budget trip, an allocation failure, or an internal error -- by returning false from its shape function, whereas the ot shaper always returns true and reports such failures through the buffer's success flag.

Because hb_shape() returns void, hb_buffer_allocation_successful() is the only failure signal its callers have. The HarfRust shim returned false without touching the C hb_buffer_t, so after a HarfRust budget trip hb_buffer_allocation_successful() still reported success while the buffer was left unshaped.

Mirror the ot shaper in hb-harfrust.cc: always return true and, on failure, mark the buffer unsuccessful. As with the ot shaper after a budget trip, the buffer is then labelled GLYPHS but its contents must not be trusted; the caller must check hb_buffer_allocation_successful().

Add a test-shape regression test that drives the HarfRust shaper with many ranged features (overrunning setup_masks()'s op budget) and asserts the failure now reaches hb_buffer_allocation_successful(). It runs in the test-shape-harfrust CI job and skips when HarfRust is not built.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-01 19:14:38 -07:00
Behdad EsfahbodandNathan Keys 5f7ed584f6 [varc/colr] Bound tuple decoding and guard variation-index overflow (#6542)
* [varc/colr] Bound tuple decoding and guard variation-index overflow

Preflight packed tuple runs before allocating decoded vectors, reject
truncated runs, and stop failed iterators at the end of their input.
Charge VARC axis expansion to the draw budget before resizing scratch
vectors. Guard variation-index addition and clip-box closure, using
checked 32-bit arithmetic for COLR ranges and preserving valid prefixes
below the reserved sentinel.

Run VARC draw tests under their actual feature guard instead of the
stale experimental-API guard. Keep tests compatible with GCC ASan,
older GLib, and builds with variations disabled.

Based on the hardening work in PR #6533.

Testing: all 275 default Meson tests and 294 experimental-API tests pass.
The machinery, VARC draw, color, and COLR subset tests pass under Clang
ASan/UBSan with the default APIs; the VARC draw suite runs all 11 cases.
GCC/Clang ASan syntax checks, GLib 2.66 API-availability checks, and the
HB_NO_VAR machinery test pass.

Co-authored-by: Nathan Keys <professor.moody@pm.me>
Assisted-by: OpenAI Codex

* [test] Put tuple and COLR regressions with their subsystems

Restore test-machinery to its original purpose. Put packed-tuple
regressions in test-tuple-varstore and the instancer regression in
test-item-varstore. Give the COLR closure checks their own test-colr
unit target. Use the local hb_always_assert convention and remove the
ad-hoc check macro, method-detection templates, and test-mode dispatcher.

Testing: all 276 default Meson tests pass. The tuple/item varstore,
COLR, VARC draw, color, and COLR subset tests pass under ASan/UBSan.

Assisted-by: OpenAI Codex

* [ot] Use an unsigned result for checked variation-index addition

The ARM EABI toolchain defines uint32_t as unsigned long, while
hb_unsigned_add_overflows accepts unsigned*. Store the checked sum in
an unsigned temporary and assign it back, preserving the overflow and
NO_VARIATION checks without depending on typedef identity.

Testing: all 276 Meson tests pass. A distinct-unsigned-long compile check
covers normal, sentinel, and overflow inputs.

Assisted-by: OpenAI Codex

* [test] Remove allocator-specific VARC test instrumentation

Drop the heap-accounting regression and its sanitizer and libc hooks.
Keep the ordinary VARC budget and truncated-axis regression tests.

All 276 Meson tests pass. The tuple/item varstore, COLR, VARC draw,
color, and COLR subset tests also pass under Clang ASan/UBSan.

Assisted-by: OpenAI Codex

---------

Co-authored-by: Nathan Keys <professor.moody@pm.me>
2026-11-01 14:22:23 -07: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 3cd312379c [ft] Drop the custom vertical-origin cache; use hb_cache_t
hb-ft's vertical-origin callback cached a full origin -- x, y, and a
load-failure flag -- in a bespoke 256-entry direct-mapped cache, because
hb_cache_t holds only a single non-negative integer.

Do what hb-ot does instead.  The vertical origin's x is half the glyph's
horizontal advance, already cached for horizontal advances, so only y
needs a cache of its own, and y fits hb_cache_t once its sign is
normalized the way hb-ot normalizes the origin.  v_origins now fills x
from hb_ft_get_glyph_h_advances() before taking the lock and caches only
y; the custom cache and its origin struct are removed.

This changes the origin's x for fonts whose FreeType vertical bearing
does not center the glyph (eg. a proportional font laid out vertically):
x was horiBearingX - vertBearingX and is now advance/2, which matches
hb-ot.  For CJK and other centered glyphs it is unchanged.

A FreeType load failure is no longer turned into a failed origin that
sent the whole run to the caller's fallback.  The glyph will not render,
so its y origin is cached as 0 and the rest of the run keeps its real
origins.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-01 11:06:28 -06:00
Behdad EsfahbodandClaude Opus 4.8 5cb4f458a1 [ft] Batch and cache vertical advances and origins
For vertical text hb_ot_position_default() fetches one advance and one
origin per glyph in the buffer.  hb-ft registered only single-glyph
callbacks for these, each going to FreeType with no cache, so a glyph
that is expensive for FreeType to load (eg. a deeply nested CFF
charstring) was loaded again for every occurrence in the text: shaping
time grew linearly with text length.  Horizontal advances in hb-ft and
both vertical values in hb-ot are already batched and cached.

Register batched callbacks, hb_ft_get_glyph_v_advances() and
hb_ft_get_glyph_v_origins(), mirroring the horizontal advance callback,
and put a per-font cache in front of FreeType in each.

Vertical advances reuse the same hb_cache_t that horizontal advances
use.  A vertical advance is non-positive when y_scale is positive (as in
hb-ot, which scales -advance), while hb_cache_t stores only non-negative
values, so the cache holds the advance's magnitude and the sign is
restored on read -- the same trick hb-ot's vertical-advance cache uses.

An origin is two values plus a failure flag, which hb_cache_t cannot
hold, so origins keep a small direct-mapped cache, hb_ft_glyph_cache_t
(256 entries); failed loads are cached too.  The batched origins
callback returns false if any glyph failed to load, reproducing the
all-or-nothing result the single-glyph adapter produced for a run.

Both callbacks consult their cache under the ft_font->lock they already
hold.  clear_caches() clears all caches wherever the horizontal cache
was cleared, including from hb_ft_font_set_load_flags(), since the load
flags feed both FreeType calls -- which also fixes the horizontal
advance_cache going stale there.

A cache removes the repetition, not the cost of a first load of each
distinct glyph, which is FreeType's own.

Adds test_native_ft_v_metrics_cache and test_native_ft_v_metrics_batched,
checking that repeated and batched queries agree with the single-glyph
API and a fresh font, that scale and load-flag changes are not served
from the cache, and that the advance sign is right at negative y_scale.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-01 10:49:08 -06:00
Behdad EsfahbodandClaude Opus 4.8 fd1877fa8b [ft] Make hb_ft_font_set_funcs() a no-op on immutable fonts
hb_ft_font_set_funcs() assumed the FT_Face it creates is adopted by
hb_font_set_funcs(), but on an immutable font that call only runs the
destroy callback, which FT_Done_Face()s the face.  The trailing
_hb_ft_hb_font_changed() then called FT_Set_Char_Size()/FT_Set_Transform()
on freed memory, crashing an application that merely called the setter on
a frozen hb-ft font (e.g. one already passed to
hb_cairo_font_face_create_for_font()).

Add the same early hb_object_is_immutable() return that the sibling setter
hb_ft_font_set_load_flags() and hb_font_set_funcs_using() already have, so
the call fails silently as the object model documents and no
FT_Face/FT_Library reference is created at all.  No change for mutable
fonts; no API/ABI change.

Adds test_native_ft_set_funcs_immutable, which reports the
heap-use-after-free under ASan without the fix and passes with it.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-31 22:45:12 -06: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 Esfahbod b05c7266d6 Merge pull request #6504 from harfbuzz/scanner/glyf
[glyf] Fix phantom-only advance bugs and bound glyf memory/subsetting work
2026-10-31 22:33:06 -06:00
Behdad Esfahbod 7939d2f295 Merge pull request #6511 from harfbuzz/scanner/misc
[core] Fix four OSS-scanner findings: map UAF, NULL out-params, qsort DoS, shape-plan limits
2026-10-31 22:32:48 -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 fc302bdfe5 [subset] Share one work budget across all glyphs when instancing glyf
hb-limits.hh states that a session which drives another subsystem
carries one cumulative budget, initialized once per top-level entry and
only ever decremented.  When instancing, glyf::subset() drives
Glyph::get_points() once per retained glyph to recompute bounds and
metrics, but passed no budget, so each glyph restarted from a fresh
HB_BUDGET_GLYPH and the table as a whole was bounded only by 2^24 times
the glyph count.  A 59 KB font of 2,000 nested composites over a shared
64-level chain made one hb_subset_or_fail() instancing call spend 34 s
of CPU, since the shared chain was re-walked (and re-charged only
against a fresh budget) for every top-level glyph.

Add HB_BUDGET_SUBSET_GLYF and keep the live counter in
hb_subset_context_t, which is constructed once and reused across the
ran-out-of-room retries in _hb_subset_table_try(), so a retry does not
reset it.  Thread it through _populate_subset_glyphs() and both
compile_bytes_with_deltas() into get_points().  Exhausting it fails
get_points(), which the existing loop already turns into dropping glyf
from the instance -- the same outcome as any other glyph-load failure
there.

This is one cumulative counter, not a per-glyph budget multiplied by
the glyph count.  It is sized at 2^28; measured consumption of the
largest glyf variable font under test/ (MPLUS1-Variable) is ~1.2M
units, about 220x below the cap, and even a font at the 65,535-glyph
maximum stays well under, so real fonts instance unchanged (outputs
byte-identical).  One behaviour change: a single glyph is now bounded
by what is left of the table budget rather than by HB_BUDGET_GLYPH, so
one glyph may spend between 2^24 and 2^28 units; the session total is
still bounded.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-31 22:00:12 -06:00
Behdad EsfahbodandClaude Opus 4.8 be8103f334 [subset] Bound the glyf bytes a plan may retain through an aliasing loca
glyf::subset() trims (and, with --no-hinting, walks the components of) every
retained glyph on every serializer retry.  The only thing bounding that work
was the implicit assumption that loca is monotonic, so the retained ranges sum
to at most the table.  loca need not be monotonic, so any number of glyph IDs
can alias the same bytes, and the work grows as glyph count times glyph size
times retries: a 328 KB font with loca = 0, L, 0, L, ... makes hb-subset spend
~22 s of CPU and then fail, where a same-sized monotonic font takes 0.02 s.

The glyph closure in _populate_gids_to_retain() already fetches each retained
glyph exactly once, before any table is subset, so charge the untrimmed length
there (before the composite operation count can bail out, so every glyph added
to the set is paid for) against a budget of HB_SUBSET_GLYF_MAX_BYTES_FACTOR (16)
times the glyf length, and fail the plan when it is exceeded.  This also makes
hb_subset_preprocess() fall back to the source face cheaply.

Fonts with a monotonic loca never exceed a factor of one, so their output is
unchanged; the one behaviour change is that a specification-violating loca that
aliases large glyph bytes more than sixteen tables' worth is now rejected
instead of subsetting slowly.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-31 21:59:50 -06:00
Behdad EsfahbodandClaude Opus 4.8 0155687e9a [glyf] Don't transform/keep unloaded component points in phantom_only get_points
In phantom_only mode SimpleGlyph::get_contour_points() reserves a glyph's
declared point count (gvar needs the count to locate the phantoms) but never
loads the points.  The composite branch of Glyph::get_points() wrongly assumed
the component's point array is then empty ("Empty in case of phantom_only"):
for a USE_MY_METRICS child it transformed all the reserved points and, after
removing only the four phantoms, left them in all_points to be transformed
again at each enclosing level (up to 64 deep) and counted against
HB_GLYF_MAX_POINTS.

Once the child's phantoms have been copied, skip the transform and shrink
all_points back to old_count in phantom_only mode; the top-level lsb shift
likewise only touches the phantoms in that mode so a simple glyph's reserved
points are not walked either.  Output is unchanged (phantoms are copied before
the transform in both modes).  The one behavioural change is that advance
lookups no longer fail spuriously when components' unloaded point counts exceed
HB_GLYF_MAX_POINTS (four USE_MY_METRICS copies of a 65536-point glyph now give
the hmtx advance 600 rather than the upem/2 fallback).

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

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 Esfahbod 07bc8effbb Merge pull request #6515 from harfbuzz/scanner/gpu
[gpu] Fix clip-pop imbalance and bound cu2qu / per-layer shader work
2026-10-30 23:10:13 -06:00
Behdad Esfahbod 799f1cd721 Merge pull request #6516 from harfbuzz/scanner/graphite
[graphite2/shaper] Fix uninitialized mask, missing positions, and repeated failed-face loads
2026-10-30 23:05:24 -06:00
Behdad Esfahbod 44b64b061a Merge pull request #6501 from harfbuzz/scanner/shaper
[buffer/layout] Fix empty-buffer mutation and two shaping-time CPU DoS findings
2026-10-30 22:55:58 -06:00
Behdad EsfahbodandClaude Opus 4.8 8b5d290611 [raster] Bound embedded PNG size and charge the scanline sweep (#6521)
* [raster] Bound embedded PNG dimensions before decoding

hb_raster_paint_image() handed a font's embedded sbix/CBDT PNG to
deserialize_from_png(), which allocated and filled the whole image at
whatever size the PNG's IHDR declared (up to two buffers at the 1 GiB
HB_RASTER_MAX_BUFFER_SIZE cap each), and only charged src_width *
src_height against the pixel budget after the decode had finished.  A
33 KB sbix font with a blank 16384x16384 1-bit PNG therefore made the
raster backend allocate and touch ~2 GiB of memory per painted glyph,
independent of the requested output size.

Surfaces whose size comes from font data are already clamped to
HB_RASTER_MAX_AUTO_DIMENSION (4096 per side); the PNG decoder was not.
deserialize_from_png() gains a max_dimension parameter checked right
after png_get_IHDR(), before any allocation, and the paint callback
passes HB_RASTER_MAX_AUTO_DIMENSION.  The public
hb_raster_image_deserialize_from_png_or_fail() keeps its INT_MAX
behaviour through the default argument, matching the limit's documented
intent that explicitly requested sizes are not bounded.  With the cap a
decode is at most 16M pixels, whose cost fits the 2^26 pixel budget, so
the later charge_work() is adequate.

Behaviour change: sbix/CBDT PNG glyphs wider or taller than 4096 pixels
are no longer painted by the raster backend (the callback returns false,
as for any undecodable image).  The cairo backend has the same weakness
on a different code path and was already fixed separately (#6497).

test_image_png_size() in test/api/test-raster.cc paints a 4096- and a
4097-pixel-wide PNG and checks that only the former lands; it fails on
the unpatched library.

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

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

* [raster] Charge the scanline sweep to the pixel budget

hb_raster_draw_render() walks every active edge once per pixel row it
spans, a product (edges times rows) that neither HB_RASTER_MAX_DRAW_EDGES
(2^20) nor HB_RASTER_MAX_AUTO_DIMENSION (4096 rows) bounds, and that
nothing charged: the outline budget only sees traversal and curve
flattening.  A 10 KB glyf font of 199,800 full-height straight edges
therefore cost tens of seconds of CPU for a single render.

PR #6244 added the precharge for the paint path but sized it by the paint
*surface*, which comes from the font's declared glyph extents, while the
mask rasterizer auto-sizes the mask from the outline itself; a 1x1
ClipBox or empty bounding box slipped the full-height sweep past it.  The
direct draw path had no check at all.

This charges the sweep inside hb_raster_draw_render(), where the extents
really rendered are known, estimating it with the existing
hb_raster_draw_get_pixel_work() helper, now clamped to those extents (the
fixed ones, else the 4096 auto cap) rather than taking them as arguments.
The sweep is skipped when the estimate exceeds the per-session pixel
allowance raster-paint already uses, max(HB_BUDGET_RASTER_PIXELS,
HB_BUDGET_RASTER_PAINT_PASSES * width * height).  The two paint callers
now use the mask-relative estimate, and hb_raster_paint_attach_clip_rdr()
seeds HB_BUDGET_UNLIMITED into the mask rasterizer when the paint policy
is unlimited, so opting out of limits still disables the check.
hb_raster_draw_get_pixel_work() is HB_INTERNAL, so dropping its two
arguments changes no public API/ABI.

Behaviour change: an over-budget render returns a blank image of the
computed size (documented in the API comment) rather than NULL.  Letting
HB_BUDGET_UNLIMITED switch the check off matches the paint pixel budget's
semantics and keeps the edge and dimension caps active; whether this
bound should instead be an unconditional structural cap is a maintainer's
choice.

Testing: the finding's reproducer flips from BUG to OK, its attack render
dropping from ~39 s to 0.05 s of CPU while the control is unchanged; the
api suite passes under both the optimized and the ASan/UBSan build.
test_budget_sweep in test/api/test-raster.cc covers the direct draw path
with auto and fixed extents and the small-surface paint-clip path.

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

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 22:52:47 -06:00
Behdad Esfahbod fcb6557402 [face] Duplicate the loader environment value instead of borrowing it (#6502)
get_default_loader_name() cached the pointer returned by
getenv("HB_FACE_LOADER") for the process lifetime.  That storage is
owned by the C runtime or the caller and may change or be freed after
the lookup, leaving the cached pointer dangling.

Duplicate the value on first use and hold onto the copy, rather than
caching the borrowed pointer or calling getenv() on every face load.
Use the existing hb_lazy_loader_t pattern (as static_face_loader_list
does): an unset or empty value, or an allocation failure, caches the
empty-string default; a non-empty value is copied with hb_malloc and
freed via hb_atexit.

Add an api smoke test that loads the fixture through the file and blob
default-loader entry points (loader == NULL) with HB_FACE_LOADER set,
then restores the caller's environment.  Its value is LSan coverage of
the copy-and-free path in the asan-ubsan job; glibc's setenv() does not
free replaced strings, so the borrowed-pointer bug is not observable on
Linux.  Verified: full meson test suite (275 tests) and test-face under
ASan/UBSan with leak detection enabled both pass.

Alternative to #6493, following review feedback there.

Assisted-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 17:47:06 -06:00
Behdad Esfahbod 786fddc088 Merge pull request #6503 from harfbuzz/scanner/subsetmisc
[subset/face-builder] Fix parser, leak, and DoS issues found by OSS Scanner
2026-10-30 17:45:06 -06:00
Behdad Esfahbod 8896ade249 Merge pull request #6500 from harfbuzz/scanner/cbdt-sbix
[sbix,CBDT] Bound per-glyph strike/record scans and CBDT subset image copies
2026-10-30 17:21:13 -06:00
Behdad EsfahbodandClaude Opus 4.8 f5ab3f4ca2 [test] Force the ot shaper in the cluster re-merge budget test
test_shape_overlong_cluster_remerge checks the native cluster re-merge op
budget added in hb-buffer.cc, which only the "ot" shaper exercises. Under
HB_SHAPER_LIST=harfrust the harfrust shaper handles clusters itself and
never trips that budget, so the buffer stayed allocation-successful and the
test aborted in the rust CI job. Pin the test to hb_shape_full() with an
"ot" shaper list.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 17:05:41 -06:00
Behdad EsfahbodandClaude Opus 4.8 757cd85427 [shaper] Cache a failed face/font data create() so it is not retried
The per-shaper lazy loaders (hb_shaper_lazy_loader_t) declare nullptr
as their null object, so hb_lazy_loader_t::get_stored() cannot tell
"create() failed" from "not created yet" and re-runs create() on
every access.  hb_shape_plan_key_t::init() tests face->data.graphite2
before the plan cache is consulted, so a font whose Silf table
Graphite2 rejects paid a full gr_make_face_with_ops() on every
hb_shape() call for the life of the face -- CPU cost unbounded by
max_ops/max_len, which apply only once the buffer is processed.

The loader already has the mechanism for this: tag_null stores a
failed create() as get_null() with bit 0 set, and get_stored()/
operator bool()/do_destroy() mask or recognize it by that bit.
Opt the shaper loaders into tag_null, fixing every shaper's face and
font data at once, as the table and accelerator loaders already do.
HB_SHAPER_DATA_SUCCEEDED moves from (void *) +1 to (void *) +2 so the
success sentinel no longer collides with the tagged null (nullptr | 1
== (void *) 1); its no-op destroy functions never dereference it.

hb_font_t's data.fini() on font changes still resets the font-data
loaders, so a retry happens there.  A font with no Silf table is now
also asked for it once per face instead of once per call.

Adds test_graphite2_failed_face_load_is_remembered, which counts Silf
table requests across three hb_shape() calls; it fails on the
unpatched tree (8 != 4) and passes with the fix.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 17:00:07 -06:00
Behdad EsfahbodandClaude Opus 4.8 fca5fc4e6b [graphite2] Clear positions when the segment has no slots
Every shaper that returns true must leave the buffer with
have_positions set; the OpenType and fallback shapers call
clear_positions() unconditionally.  _hb_graphite2_shape() borrows
pos[] as scratch via get_scratch_buffer(), which clears
have_positions, and the normal path restores it through
hb_buffer_get_glyph_positions().  But when Graphite deletes every
glyph of the run, the zero-slot early-out set buffer->len = 0 and
returned true without restoring the flag, so a later
hb_buffer_normalize_glyphs() (hb-shape --normalize-glyphs) hit
assert (buffer->have_positions) and aborted.

Restore the invariant where it is broken, by calling
buffer->clear_positions() in the empty-segment return.

Adds test_graphite2_all_glyphs_deleted, with an embedded 500-byte
font whose Silf rule deletes 'a'; shaping "aaa" must now succeed with
length 0 and positions, while the "aba" control is unchanged.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 16:59:32 -06:00
Behdad EsfahbodandClaude Opus 4.8 b32bfc243d [graphite2] Initialize mask of glyphs the shaper adds
_hb_graphite2_shape() grows buffer->info with ensure() (a plain
realloc) and then fills each output glyph field by field, but never
assigned hb_glyph_info_t::mask.  Entries beyond the original text
length therefore kept uninitialised heap bytes (or, in a reused
buffer, the mask from a previous shaping run); clear_glyph_flags()
only rewrites the low three bits, so hb_buffer_get_glyph_infos()
handed the stale bits 3-31 to the caller.  Shaping output is correct
(every in-tree reader masks down to HB_GLYPH_FLAG_DEFINED), but
valgrind/MSan flag the uninitialised bytes and code reading the
private field sees values that vary run to run.

Set info->mask = 0 in the fill loop, next to the other fields.  That
matches what hb_buffer_t::add() starts from and what the OpenType
shaper returns after hb_propagate_flags(), so the subsequent
clear_glyph_flags()/unsafe_to_break() operate on a defined value and
shaping output is unchanged.  No other shaper needs the change.

Adds test_graphite2_inserted_glyph_masks, which first runs the
OpenType shaper so a removed default-ignorable leaves a non-zero mask
in the buffer storage, then checks that every glyph the Graphite
shaper adds for U+0622 comes back with nothing but glyph-flag bits.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 16:58:47 -06:00
Behdad EsfahbodandClaude Opus 4.8 4a8f1cd542 [gpu] Charge layer clip-outline references to the paint budget
The paint encoder memoizes a clip glyph's sub-blob, so layers painted
under the same clip stack cost it only a cached index and 24 bytes of
op stream each.  The fragment shader, however, walks every curve of
every clip outline again for every layer in every fragment.  Ops, clips
per layer and outline size each had a cap, but nothing bounded their
product: a small COLRv1 font nesting a few PaintGlyph clips of a dense
outline under tens of thousands of PaintSolid layers made the shader do
hundreds of millions of curve-loop iterations per fragment, a denial of
service on the GPU (or the CPU under a software rasterizer).

Charge each layer's reference to each clip sub-blob -- cached or freshly
encoded, glyph or path clip -- to the existing session work budget, in
encoded RGBA16I texels, which is what the shader's band walk scales
with.  This lives in emit_all_clip_sub_blobs(), the one path all four
layer emitters go through; exhausting the budget marks the paint
unsupported like the other encoder limits, so hb_gpu_paint_encode()
returns NULL.  It adds no new tunable: the budget defaults to
HB_BUDGET_GLYPH and hb_paint_set_budget(), including
HB_BUDGET_UNLIMITED, governs it as it does the outline work.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 16:55:57 -06:00
Behdad EsfahbodandClaude Opus 4.8 462a554921 [gpu] Charge each cu2qu subdivision node to the work budget
hb_gpu_cubic_to_quadratics() split a cubic up to 10 levels deep
(2,047 nodes, each with a fit test) without charging that work to the
per-glyph budget and without checking whether the accumulator still
accepted output.  Once the budget was spent, acc_emit() dropped every
curve but left g->success set, so each further cubic was fully
subdivided for nothing.  A VARC composite of CFF glyphs that shares one
budget across many cubic-producing components could make a single
hb_gpu_draw_glyph() (or hb_gpu_paint_glyph() clip) call spend seconds
of CPU, far past the budget, as a CPU denial of service from a small
crafted font.

Charge one unit per node and return at the top of the recursion once
g->success is false or the budget is exhausted, the same approach the
raster flattener already takes.  Returning is equivalent to emitting
here because acc_emit() discards everything once the budget is
negative, so the encoded outline is unchanged for any glyph that stays
within budget; the only cost is one extra unit per node, negligible
against HB_BUDGET_GLYPH.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 16:55:11 -06:00
Behdad EsfahbodandClaude Opus 4.8 f97d6bbb0d [gpu] Count ignored rectangle clips so their pop does not pop a real clip
The GPU paint encoder left push_clip_rectangle at the no-op default
while pop_clip unconditionally decremented clip_depth.  COLR emits a
rectangle push/pop pair around every PaintColrGlyph that has a ClipBox,
so that pop removed whatever glyph/path clip sat below it on the stack.
When such a PaintColrGlyph is nested inside a PaintGlyph, the sibling
layers encoded afterwards carried one clip outline too few, painting
ink outside the enclosing outline, or were dropped entirely when they
reached an emitter with clip_depth == 0.

Register a push_clip_rectangle callback that records the push in a
small per-depth counter (rect_clips[d] = rectangles pushed while
clip_depth was d).  pop_clip consumes a non-zero count at the current
depth first and only otherwise pops a real clip.  Rectangle clips are
still left unencoded, exactly as the v1 design notes state; the counter
only keeps the glyph/path clip depth balanced across the ignored pair.
This is correct for any LIFO push/pop order without allocation, and
changes nothing for paint trees without rectangle clips (the top-level
ClipBox in COLR::paint_glyph is already balanced).

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 16:54:46 -06:00
Behdad EsfahbodandClaude Opus 4.8 02b4120e34 [shape-plan] Install buffer work limits in hb_shape_plan_execute()
The per-text limits max_len/max_ops are set by hb_buffer_t::enter() and
reset by leave(), but since e246723f0 only hb_shape_full() called them,
so the public hb_shape_plan_execute() ran the shapers with the idle
defaults (0x3FFFFFFF glyphs / 0x1FFFFFFF ops).  A client that executes a
plan itself could be made to allocate gigabytes or spend seconds of CPU
on a single character.  A reused buffer also kept its spent op budget
across executions, silently skipping nested lookups afterwards.

Move the enter()/leave() pair from hb_shape_full() into the
HB_SHAPER_EXECUTE step of _hb_shape_plan_execute_internal(), the single
point every public path reaches the shapers through, so each call gets a
fresh allowance.  It runs after the empty-buffer early return, so the
immutable empty buffer is never written.

enter() now runs on every shape, so guard against discarding a limit
that internal code narrowed below the idle default before shaping (the
output-growth fault injection in src/test-graphite2-buffer.cc sets
max_len that way): compute the per-text limit as before, but keep the
stricter value when the current limit is already below the default.
Public paths always arrive at the idle defaults (from hb_buffer_create()
or leave()), so they get exactly the computed per-text limit as today;
reused buffers are refilled because leave() restores the defaults first.

hb_shape_full()'s VERIFY pass now runs after leave(), which is harmless:
it reshapes fragment copies via hb_shape_full() (which install their own
limits) and does not read max_len/max_ops.  No API/ABI change.

A regression test in test/api/test-shape-plan.c asserts that
hb_shape_plan_execute() yields the same buffer length as hb_shape().

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 16:49:35 -06:00
Behdad EsfahbodandClaude Opus 4.8 507575fd82 [metrics][layout] Accept NULL out-pointer where the docs allow it
hb_ot_metrics_get_position_with_fallback() and
hb_ot_layout_get_font_extents() / ...2() document their result pointer
as optional ((out) (optional) / (out) (nullable)), and one path in each
honours that, but the others dereference it: the metrics fallback reads
*position for the strikeout/underline zero check and writes it in every
synthesized arm, and the layout miss path hands the pointer unchecked to
hb_font_get_extents_for_direction(), which memsets it.

Substitute a stack local at function entry with the existing
`if (!p) p = &local;` idiom (cf. hb-paint.cc), so every path below is
unchanged, and drop the now-redundant `if (extents)` guard.  ...2() is
covered through its callee.  The prototype comment becomes
`/* OUT.  May be NULL. */` to match hb_ot_metrics_get_position().  No
API/ABI change.

Regression cases are added to test/api/test-ot-metrics.c and
test/api/test-base-minmax.c.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 16:35:27 -06:00
Behdad EsfahbodandClaude Opus 4.8 2f8fb68973 [map] Fix use-after-free when updating a map from itself
hb_hashmap_t::update() iterates other's items array while inserting
each pair into *this with set().  When other is *this and occupancy
sits on a growth threshold (5 of 8, 10 of 16, ...), the first set()
calls alloc(), which frees the items array the iterator is still
walking, so the rest of the loop reads freed memory.  The existing
in_storage() guard only protects set()'s own key/value references,
not this iterator.

Merging a map into itself cannot change it, so make update() a no-op
in that case with an early &other == this return, mirroring the
self-check in hb_vector_t.  hb_map_update() is the only caller.

Regression tests are added in src/test-map.cc (including the tombstone
case at 42 used / 10 live slots) and test/api/test-map.c; both fail
under ASan without the fix.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 16:35:27 -06:00
Behdad EsfahbodandClaude Opus 4.8 b83dcdbcde [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>
2026-10-30 16:22:37 -06:00
Behdad EsfahbodandClaude Opus 4.8 b732218126 [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>
2026-10-30 16:15:07 -06:00
Behdad EsfahbodandClaude Opus 4.8 292942ceca [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>
2026-10-30 16:14:51 -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 f840e4d018 [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>
2026-10-30 16:00:28 -06:00