Commit Graph
22329 Commits
Author SHA1 Message Date
Behdad EsfahbodandClaude Opus 4.8 f2fdcdcd4e [hb-info] Fix two --list-* crashes/garbage on unusual fonts (#6517)
* [hb-info] Skip unresolvable variation sequences in --list-unicodes

_list_unicodes() asserted that every codepoint returned by
hb_face_collect_variation_unicodes() also resolves via
hb_font_get_variation_glyph(), but the library never guarantees
that: collection reads only the cmap format 14 subtable, while
lookup additionally requires a nominal cmap mapping for Default UVS
ranges and a non-zero glyph for Non-Default UVS mappings. A
structurally valid, sanitizer-clean font that lists an unmapped
codepoint in a Default UVS range, or glyph 0 in a Non-Default UVS
entry, therefore aborted hb-info --list-unicodes/--list-all/--all in
any assertion-enabled build (the meson debugoptimized default).

Treat a failed lookup as data and skip the sequence instead of
asserting. Both library calls behave as documented, and the
subsetter relies on collect_variation_unicodes() returning every
listed entry, so the fix belongs in the tool.

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

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

* [hb-info] Skip dangling LangSys feature indices in --list-features

The script-sensitive path of _list_features() printed a local
hb_tag_t that hb_ot_layout_table_get_feature_tags() only writes when
the requested index exists. LangSys::sanitize bounds-checks the
feature-index array but not its values, so a featureIndex past the
end of the FeatureList left the tag uninitialised and hb-info printed
stack garbage (NUL bytes under -O2, the previous tag under ASan).

Initialise the tag, resolve it at the top of the per-feature loop,
and honour the returned count by skipping the entry when it is zero,
matching how the shaper ignores such indices. This is a tool-only
defect: the library already returns zero tags for the dangling index.

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

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 22:53:55 -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 04d6d3912e [vector] Fix six OSS-scanner findings in the vector paint backends and gvar instancer (#6498)
* [instancer] Treat a zero-size pool allocation as success in gvar instancing

hb_alloc_pool_t::alloc(0) legitimately returns nullptr while no shared
chunk is open, but hb_vector_t::allocate_from_pool() took any nullptr as
an allocation failure and flagged the (empty) vector with set_error().
The next allocate_from_pool() on it then tripped
assert(!length && !allocated), aborting hb-subset during partial
instancing of a crafted ~1 KB variable font whose retained glyph has
more than 16,376 points (so no small request ever opens the shared
chunk) and whose tuple is split by the requested axis range.

Fix the root cause where the vector already special-cases zero-size
requests on the heap path: a null result is a failure only when bytes
were requested (size && !arrayZ).

tuple_delta_t::copy_from() also discarded the results of its seven
duplicate_vector_from_pool() calls, so a genuine pool failure during a
tuple clone would reach the same assert (or silently drop gvar under
NDEBUG); it now returns bool, change_tuple_var_axis_limit() marks out in
error, and change_tuple_variations_axis_limits() fails instead of
continuing.

A regression test for the zero-size pool allocation is added to
src/test-vector.cc. The attack font now instances to the same output as
the control; test-vector and the subset suite pass.

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

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

* [vector] Refuse PDF indexed-PNG soft masks larger than the document cap

hb_pdf_build_indexed_smask() allocated and filled (width+1)*height and
width*height bytes straight from the attacker-controlled PNG IHDR, while
HB_VECTOR_MAX_DOCUMENT_SIZE was only consulted when the finished mask was
appended to the PDF object.  A ~1 MB sbix/CBDT font could thus make the
PDF backend inflate and un-filter up to a 4 GiB mask per painted glyph,
only to drop it afterwards.

The mask is emitted uncompressed into a document-capped hb_vector_buf_t,
so a mask larger than the cap can never be appended: reject it alongside
the existing 32-bit overflow guards in the builder (the same pattern as
the raster PNG decoder's HB_RASTER_MAX_BUFFER_SIZE check), which bounds
both allocations (raw_len = mask_len + height) before any work is done.

add_xobject_png_image() additionally skips registering and referencing
the SMask object when its buffer tripped the cap, so the output no longer
contains a dangling empty-stream object for an edge-case mask that fits
the builder but not the object with its header.  Masks that fit today are
unaffected.

A regression test in test/vector/test-vector-budget.c hand-rolls a zlib
stream for a 4097x4096 indexed PNG with tRNS, paints it to PDF, and
asserts the render succeeds without an /SMask.

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

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

* [vector] Reduce linear-gradient P2 anchor in the PDF backend

The PDF paint backend drew COLRv1 linear gradients along the raw P0->P1
segment and marked the rotation anchor P2 as HB_UNUSED, writing the
axial shading's /Coords straight from P0 and P1.  For any gradient whose
P2 - P0 is not perpendicular to P1 - P0 (how a font rotates or skews a
gradient), the PDF put the colour stops in the wrong places, unlike the
SVG, raster, GPU and cairo backends, which all call
hb_paint_reduce_linear_anchors() first.

Reduce the three COLR anchors to the two-point axis the same way and
derive the gradient coordinates from the reduced axis.  One change covers
both the colour shading and the soft-mask shading, since both use the
same gx0..gy1.

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

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

* [vector] Size PDF gradient soft masks to cover the painted area

For a linear or radial COLRv1 gradient with a translucent stop, the PDF
backend painted the alpha ramp through a luminosity soft mask whose Form
XObject /BBox was the rectangle spanned by the gradient axis (linear) or
the enclosing square of the outer circle (radial).  An axial shading is
not confined to its axis rectangle, and a radial shading with /Extend
extends beyond its circles; the RGB fill relies on that.  A form's /BBox
clips everything it paints and the luminosity backdrop is black (mask 0)
outside it, so the translucent gradient was masked out entirely for a
horizontal or vertical axis (zero-area box) and cropped otherwise.

Give both soft-mask forms a large box covering the whole painted area,
as hb_pdf_paint_sweep_gradient() already does, instead of the axis or
circle box.

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

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

* [vector] Decline color_glyph in the SVG paint backend

The SVG backend's color_glyph callback re-entered hb_font_paint_glyph()
for every COLRv1 PaintColrGlyph, and each re-entry built a fresh COLR
paint context whose HB_MAX_GRAPH_EDGE_COUNT and HB_MAX_NESTING_LEVEL
counters started over.  The limits therefore applied per nested glyph
instead of per top-level glyph, so a DAG in which each level references
the next one f times was walked f^levels times, letting a sub-2 KB font
spin indefinitely; the same per-re-entry depth reset let a crafted font
overflow a small thread stack.

Return false, as hb-raster and the PDF backend do (and as the COLR and
FreeType walkers expect), so the walker paints the nested glyph inline
in the same context, where the existing decycler, nesting limit and edge
limit bound the whole graph.  The color_glyph_depth counter and
active_color_glyphs set existed only to guard the re-entry, so they are
dropped from hb_vector_paint_t and from create, destroy and clear.

A regression test building a 30-level, 3-reference COLR chain in memory
is added to test/vector/test-vector-budget.c for both SVG and PDF.

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

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

* [vector] Make the document-size cap per document, not per buffer

HB_VECTOR_MAX_DOCUMENT_SIZE was enforced in hb_vector_buf_t against the
length of the one buffer being appended to, but both backends spread one
document across many buffers, so the cap bounded each buffer and not the
document.  A few-KB COLRv1 font could exceed it by a large multiple:

- SVG starts a fresh buffer per open paint group, so a chain of nested
  PaintComposite records keeps dozens of near-cap backdrop buffers alive
  at once (about 1 GB from a 1.3 KB font).  An open group now inherits
  the bytes already held by the buffers it will be appended to, via a
  base member folded into would_overflow(), so base + length of every
  open group stays within the cap.

- PDF keeps every object (functions, shadings, ExtGStates, images) in a
  buffer of its own with no running total, so one large gradient painted
  thousands of times produces millions of objects (gigabytes) that are
  only summed at render.  add_object() now charges a running total
  against the same cap with a sticky overflow flag; the image and
  gradient callbacks stop when res->in_error(), and render returns NULL
  in that state because the content stream would refer to dropped
  objects.

hb_vector_buf_t and hb_pdf_resources_t are internal, so there is no API
or ABI change; documents that fit under the cap are unchanged.
Regression tests are added to test/vector/test-vector-budget.c.

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

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 17:16:03 -06:00
Behdad Esfahbod b1316bce52 [uniscribe] Read font directories from the sanitized original (#6488)
* [uniscribe] Read font directories from the sanitized original

Renaming a face's name table record can change another face's
header when TTC directories overlap. Parsing the edited copy then
uses table counts and offsets that were never sanitized. Find each
record in the original blob and edit the copy at that byte offset,
keeping both directory reads and record writes within validated data.

Add a bounded overlapping-collection regression and a non-overlapping
control, gated on Uniscribe support. The original renamer fails under
ASan; the patched public-API test passes with Windows stand-ins.
Ordinary TTF, TTC, and dfont outputs remain byte-identical. MinGW
builds the 64-bit Windows executable and the 32-bit backend, including
HB_NO_OT_FONT. Windows execution was unavailable. The full native
Meson suite passes (274 tests).

Reported by Anthropic's OSS Scanner as ANT-2026-2VV35K9M.

Assisted-by: OpenAI Codex

* [uniscribe] Don't create font data without face data

When face-data creation fails -- eg. AddFontMemResourceEx() rejects a
malformed font and returns NULL -- face->data.uniscribe is left NULL.
populate_log_font() then dereferences it
(font->face->data.uniscribe->face_name) and crashes.  This is reachable
from the public hb_uniscribe_font_get_hfont() and from shaping with any
font GDI declines, not just the overlapping-TTC case.

Bail out of _hb_uniscribe_shaper_font_data_create() when face data is
NULL, matching _hb_coretext_shaper_font_data_create().

This is what made the new test-uniscribe regression crash on the
Windows CI jobs: Wine reported "page fault on read access to
0x0000000000000010", ie. a NULL + offsetof(face_name) read.  Verified
by cross-compiling with MinGW and running the test under Wine: it hits
the same 0x10 page fault without this change and exits cleanly with it.

Assisted-by: Claude Opus 4.8 <noreply@anthropic.com>

* [directwrite] Don't create font data without face data

Same NULL face-data dereference as the uniscribe backend: when
_hb_directwrite_shaper_face_data_create() fails (dw_face_create()
returns NULL for a font DirectWrite rejects), face->data.directwrite is
left NULL.  _hb_directwrite_shaper_font_data_create() then calls
fontFace->QueryInterface() through that NULL pointer and crashes.

Bail out when face data is NULL, matching the uniscribe and coretext
backends.

Assisted-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 17:15:02 -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 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
Behdad EsfahbodandClaude Opus 4.8 d52c540c7a [face-builder] Keep table tags sorted at add_table() time
_hb_face_builder_get_table_tags() copied every key out of the hash map
and qsort()ed it on each call, so a caller paging through the list (the
subsetter uses 32-entry pages in hb_subset_plan_execute_or_fail() and
_is_table_present()) paid N/32 sorts of N tags per enumeration.  With
the 65535-table face that hb_subset_preprocess() hands back this was
~25 s of CPU per hb_subset_or_fail() call.

Keep an hb_vector_t<hb_tag_t> next to the map and maintain it in
hb_face_builder_add_table(), the only place keys are inserted: a binary
search finds the slot, the vector is pre-allocated before the map is
touched so an allocation failure leaves both structures unchanged, and
the slot is opened with the same resize+memmove idiom hb-bit-set.hh
uses.  The getter becomes a sub_array() copy, so enumeration is O(page)
and the returned order is unchanged.  _hb_face_builder_data_reference_blob()
keeps its own sort, which orders by blob size, not by tag.

A regression test adds tags out of order, one of them twice, and checks
that paging with a 4-entry array returns each tag once in ascending
order.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 15:30:37 -06:00
Behdad EsfahbodandClaude Opus 4.8 dae0a46b4d [face-builder] Bound the summed table length before allocating the blob
Table records of a font file may overlap, so the sum of the passed
-through table lengths is not bounded by the size of the font: with
HB_SUBSET_FLAGS_PASSTHROUGH_UNRECOGNIZED a 262 KB font of aliased
records made _hb_face_builder_data_reference_blob() allocate and fill a
~4 GiB buffer, only for hb_blob_create() to refuse it.

Accumulate face_length with hb_unsigned_add_overflows() and return
nullptr as soon as the total reaches 1u<<31, the length
hb_blob_create_or_fail() refuses, so the 2-4 GiB allocate-fill-free
cycle no longer happens; the serializer's own bounds already prevented
any overrun once the sum wrapped.  Output for every input that succeeded
before is unchanged.

The endless retry that turned this into a hang is fixed in the
companion commit (hb_face_reference_blob() no longer recurses into
itself on the fallback builder).

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 15:28:07 -06:00
Behdad EsfahbodandClaude Opus 4.8 8f09a11184 [face-builder] Limit builder faces to 65535 tables
A builder face must always be serializable into an sfnt, but
hb_face_builder_add_table() accepted any number of tables while the
table directory's numTables is 16-bit.  Serializing a 65536th table hit
the assert in BinSearchHeader::operator= (or, with NDEBUG, truncated the
count and then looped forever through hb_face_reference_blob()'s retry).
The subsetter reaches this with HB_SUBSET_FLAGS_PASSTHROUGH_UNRECOGNIZED
because glyf::subset() always adds a 'loca' the source need not have.

Enforce the limit where tables are added, so the subsetter fails cleanly
at plan->add_table() and a builder face can always be written out;
replacing an existing tag is still allowed.  Also stop
hb_face_reference_blob() from recursing into itself on the fallback
builder it just built (serialize it directly with reference_table()):
otherwise a builder that cannot produce a blob is retried without end.

A regression test in test/api/test-get-table-tags.c adds 65535 tags,
checks the 65536th is refused, that replacement still works, and that
the serialized blob has the expected size.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 15:27:31 -06:00
Behdad EsfahbodandClaude Opus 4.8 db0231fc12 [subset] Free the replaced override string in override_name_table()
name_table_overrides stores hb_malloc()ed strings as plain hb_bytes_t
values, so the invariant that every stored string is freed exactly once
in ~hb_subset_input_t broke when set() silently overwrote an existing
key: overriding the same name record more than once on one input leaked
the previous copy, and so did a NULL (remove) after a non-empty
override.

hb_subset_input_override_name_table() is the only place that allocates
these strings, so fix it there: look the record up with has(&old) and
fini() it in place before set() (fini nulls the pair, so no path frees
twice, and the lookup happens before set() can reallocate the table).
Also free the fresh copy and return false when set() cannot store it,
instead of leaking it and returning true.  hb_subset_plan_t copies the
map and frees its own copies, so it is unaffected.  No public API/ABI
change.

A regression line in test_subset_name_overrides overrides one record
twice; only the last string survives and the first must not leak.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 15:26:52 -06:00
Behdad EsfahbodandClaude Opus 4.8 9c093444ef [subset] Honour len in hb_subset_axis_range_from_string()
The function documents len as the length of str, but located the ':'
separators with strpbrk() and matched "drop" with strcmp(), both of
which scan to the next NUL byte.  A caller passing an exact-length,
non-NUL-terminated slice therefore got an out-of-bounds read, and bytes
beyond len could change or reject the parsed range.

Bound every scan by str+len: each strpbrk() becomes memchr() bounded by
end, the strcmp() becomes a len==4 && hb_memcmp() check, and the empty
-piece test !*str becomes str == end.  This is the same discipline the
sibling parsers hb_feature_from_string()/hb_variation_from_string()
already follow.  For len == -1 (the only in-tree caller) len becomes
strlen() first, so behaviour is unchanged.  No public API/ABI change.

A regression test in test/api/test-subset.c passes prefixes of longer
literals with an explicit len and checks the NUL-terminated cases still
parse as before.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* [cairo] Charge compositing operations to the glyph budget

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

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

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

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

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

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

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 15:26:28 -06:00
Behdad EsfahbodandClaude Opus 4.8 379e2b0b7a [CBDT] Index records by glyph instead of walking them per query
IndexSubtableArray::find_table() finds a glyph's bitmap by walking
the strike's whole IndexSubtableRecord array.  The record count is a
32-bit field bounded only by the table length, and the walk is
charged to no work limit, so two callers run it once per glyph and
turn font size times text/glyph count into CPU time:

 - hb-ot-font, on every extents/PNG/paint query, which stalls
   hb_shape() (vertical text without VORG/vmtx measures each glyph by
   its extents) and the extents/paint/PNG getters;
 - the subsetter, for every output glyph of every strike in
   IndexSubtableArray::build_lookup().

With a ~320 KB font one vertical hb_shape() of 2000 letters took ~31 s
against ~0.25 s for the same font with the record count set to 1, and
a ~303 KB font kept hb-subset --gids='*' busy for ~100 s.

build_lookup() now maps each retained glyph to the first record that
covers it in one pass over the records (a copy of the glyphset with
del_range() after each record keeps the first-covering-record rule),
instead of searching the array per glyph.  Output is byte-identical.

The accelerator builds a bounded per-face index: for the first strike
of each ppem it records the disjoint (ppem, glyph range) -> record
index spans in a sorted vector that find_table() binary searches,
preserving the first-covering-record rule exactly.  The index is
capped at HB_CBDT_MAX_INDEX_ENTRIES (a new limit in hb-limits.hh): a
strike whose records would overflow it, or that hits an allocation
failure, falls back to the original linear walk via walk_ppems, so
the index never exceeds the cap no matter how many records the
sanitizer accepted.  BitmapSizeTable::find_table() is kept as that
fallback.

Known limitation: the cap is one shared budget, filled in sizeTables
order.  A single ~512 KB filler strike of ~65535 one-glyph records
exhausts it, so every strike after it in the array keeps the full
per-glyph walk; a font under 3x the reproducer's size can still force
that walk for those later strikes.  This is acceptable for a
non-security performance bug and keeps lookup results exact for every
font.  Per-strike lazy indexing (build a strike's index on first use,
under its own cap) is the real follow-up and is left out here to keep
the change small.

Lookups are unchanged.  The reproducer drops from ~31 s to ~0.39 s
with identical shaped output; the 303 KB subsetter case drops to
~0.07 s; the 197 MiB worst case (255 strikes at distinct ppems
sharing one 65535-record array) now peaks at ~18 MiB.  Adds
test_hb_ot_color_png_cbdt_records (pins the first-covering-record
rule through the index) and test_subset_cbdt_many_records (a
65535-glyph, 64-strike, keep-everything subset that must finish
quickly).  The full test suite passes; ASan/UBSan clean.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 15:10:33 -06:00
Behdad Esfahbod 7768296945 [gpu] Skip paint layers with empty clip outlines (#6483)
The draw encoder returns the empty blob for outlines without curves.
Treating it as a clip sub-blob leaves a layer referring to the next
payload or the end of the encoded data. Cache empty glyph and path
clips separately and skip their consuming layers. Preserve the
paint encoder's no-ink contract when only group operations remain,
returning an empty blob with zero extents.

Use fallible blob creation for gradient payloads so allocation failure
cannot produce the same zero-length sub-blob references.

Add an API regression using an ordinary font and paint callbacks,
covering solid and gradient layers, empty paths, groups, and clip slot
reuse. Validate the surviving layer's outline and band references.
The regression fails on the original encoder; the full Meson suite
passes (274 tests).

Reported by Anthropic's OSS Scanner as ANT-2026-5Z1FLVCW.

Assisted-by: OpenAI Codex
2026-10-30 15:07:23 -06:00
Behdad Esfahbod 041e5a311b [ot-layout] Collect glyph alternates without dangling references (#6482)
hb_pair() preserves references to lvalue arguments. The alternate
collection callbacks returned pairs referencing their own by-value
parameters, so the next iterator stage read them after the call ended.

Pass each AlternateSubst glyph directly to the collector helper, which
already encodes its alternate index. This also keeps alternate_count
keyed by the original glyph. Return a value pair for SingleSubst format
1, as the subsetting path already does.

Cross-check collected maps against the per-glyph getter for four
SourceSansPro lookups. The alternate and both SingleSubst format 1
cases fail on the previous code; the format 2 control passes.

Testing: meson test -C build (292 passed; check-symbols skipped on
macOS). All five alternate API tests also pass under ASan and UBSan,
with stack-use-after-return detection enabled.

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

Assisted-by: OpenAI Codex
2026-10-30 15:04:54 -06:00
Behdad Esfahbod 6f6ed4cd5c [vector] Share recycling metadata across renderers (#6480)
Use one hidden user-data key for vector blob metadata. A static key in
its header gives each renderer a different address, so a blob recycled
between renderers can retain a user-data entry for released metadata.

Clear in_replace after replace_buffer() returns, including when the
buffer stays at the same address and its destroy callback is skipped.
Otherwise the final destruction keeps the metadata allocation alive.

Exercise cross-renderer and in-place recycling in all four SVG/PDF draw
and paint paths. The cross-renderer case fails under ASan before the
fix. With the fix the sanitizer check and all 293 Meson tests pass, and
macOS leaks reports no leaks (five metadata allocations before clearing
the in_replace flag).

Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-HAG1BPA1
and ordinary bug ANT-2026-YE77VHKY.

Assisted-by: OpenAI Codex
2026-10-30 15:03:23 -06:00
Behdad Esfahbod 4971496028 [subset/CBDT] Check append lengths before reserving and copying data (#6485)
Check the combined image-data length for unsigned overflow and ensure
it fits the vector's signed length argument. Resize the output only
after those checks, then copy at the saved old length. Both callers
already propagate failure to the serializer.

Extend the allocation-failure test with small simulated boundary cases
for an unrepresentable total and a wrapping sum. Each starts with a
fresh vector, and the allocator refuses large requests as a backstop.
The new regression fails before the fix without allocating large
buffers. All 293 tests pass, and test-cbdt-cache passes under ASan and
UBSan, including the existing required-allocation failure checks.

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

Assisted-by: OpenAI Codex
2026-10-30 15:01:41 -06:00
Behdad Esfahbod 2134638033 [ft] Copy color bitmaps while the face is locked (#6486)
The glyph slot belongs to the shared FreeType face. Copy its bitmap
and dimensions before releasing the face lock, then query extents
and invoke the image callback without the lock. Fail if the bitmap
copy cannot be allocated.

Add a bounded shared-font paint regression using the existing emoji
fixture. Check BGRA blob dimensions and reenter the font from the
image callback. The test crashes before the fix and passes after it.
The full Meson suite passes (274 tests).

Reported by Anthropic's OSS Scanner as ANT-2026-ANVKHBVD.

Assisted-by: OpenAI Codex
2026-10-30 15:01:04 -06:00
Behdad EsfahbodandClaude Opus 4.8 b76754924e [vector] Make the document-size cap per document, not per buffer
HB_VECTOR_MAX_DOCUMENT_SIZE was enforced in hb_vector_buf_t against the
length of the one buffer being appended to, but both backends spread one
document across many buffers, so the cap bounded each buffer and not the
document.  A few-KB COLRv1 font could exceed it by a large multiple:

- SVG starts a fresh buffer per open paint group, so a chain of nested
  PaintComposite records keeps dozens of near-cap backdrop buffers alive
  at once (about 1 GB from a 1.3 KB font).  An open group now inherits
  the bytes already held by the buffers it will be appended to, via a
  base member folded into would_overflow(), so base + length of every
  open group stays within the cap.

- PDF keeps every object (functions, shadings, ExtGStates, images) in a
  buffer of its own with no running total, so one large gradient painted
  thousands of times produces millions of objects (gigabytes) that are
  only summed at render.  add_object() now charges a running total
  against the same cap with a sticky overflow flag; the image and
  gradient callbacks stop when res->in_error(), and render returns NULL
  in that state because the content stream would refer to dropped
  objects.

hb_vector_buf_t and hb_pdf_resources_t are internal, so there is no API
or ABI change; documents that fit under the cap are unchanged.
Regression tests are added to test/vector/test-vector-budget.c.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 14:57:14 -06:00
Behdad EsfahbodandClaude Opus 4.8 14e1f86467 [vector] Decline color_glyph in the SVG paint backend
The SVG backend's color_glyph callback re-entered hb_font_paint_glyph()
for every COLRv1 PaintColrGlyph, and each re-entry built a fresh COLR
paint context whose HB_MAX_GRAPH_EDGE_COUNT and HB_MAX_NESTING_LEVEL
counters started over.  The limits therefore applied per nested glyph
instead of per top-level glyph, so a DAG in which each level references
the next one f times was walked f^levels times, letting a sub-2 KB font
spin indefinitely; the same per-re-entry depth reset let a crafted font
overflow a small thread stack.

Return false, as hb-raster and the PDF backend do (and as the COLR and
FreeType walkers expect), so the walker paints the nested glyph inline
in the same context, where the existing decycler, nesting limit and edge
limit bound the whole graph.  The color_glyph_depth counter and
active_color_glyphs set existed only to guard the re-entry, so they are
dropped from hb_vector_paint_t and from create, destroy and clear.

A regression test building a 30-level, 3-reference COLR chain in memory
is added to test/vector/test-vector-budget.c for both SVG and PDF.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 14:55:57 -06:00
Behdad Esfahbod 02b4af88a6 [sanitize] Drop unused writable flag from the context (#6496)
hb_sanitize_context_t::writable is only ever written (in the
constructor and init()) and never read.  The edit/neuter code that
consulted it was removed in 665afc08f6 ("[sanitize] Remove
table-altering code parts") and 83dc4d1d35 ("[sanitize] Don't do
edit-sanitize cycle"); the flag was left behind as dead state.

Remove it.  No functional change; the full Meson suite passes
(274 tests).

Assisted-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 14:55:14 -06:00
Behdad EsfahbodandClaude Opus 4.8 21fc7db92d [vector] Size PDF gradient soft masks to cover the painted area
For a linear or radial COLRv1 gradient with a translucent stop, the PDF
backend painted the alpha ramp through a luminosity soft mask whose Form
XObject /BBox was the rectangle spanned by the gradient axis (linear) or
the enclosing square of the outer circle (radial).  An axial shading is
not confined to its axis rectangle, and a radial shading with /Extend
extends beyond its circles; the RGB fill relies on that.  A form's /BBox
clips everything it paints and the luminosity backdrop is black (mask 0)
outside it, so the translucent gradient was masked out entirely for a
horizontal or vertical axis (zero-area box) and cropped otherwise.

Give both soft-mask forms a large box covering the whole painted area,
as hb_pdf_paint_sweep_gradient() already does, instead of the axis or
circle box.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 14:55:13 -06:00
Behdad EsfahbodandClaude Opus 4.8 105fb37749 [vector] Reduce linear-gradient P2 anchor in the PDF backend
The PDF paint backend drew COLRv1 linear gradients along the raw P0->P1
segment and marked the rotation anchor P2 as HB_UNUSED, writing the
axial shading's /Coords straight from P0 and P1.  For any gradient whose
P2 - P0 is not perpendicular to P1 - P0 (how a font rotates or skews a
gradient), the PDF put the colour stops in the wrong places, unlike the
SVG, raster, GPU and cairo backends, which all call
hb_paint_reduce_linear_anchors() first.

Reduce the three COLR anchors to the two-point axis the same way and
derive the gradient coordinates from the reduced axis.  One change covers
both the colour shading and the soft-mask shading, since both use the
same gx0..gy1.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 14:54:53 -06:00
Behdad Esfahbod a763a612d1 [aat] Reject zero-sized lookup format 10 values (#6487)
Require each format 10 value to occupy at least one byte. Otherwise a
lookup can declare covered glyphs without backing data for those values,
bypassing the sanitizer work charged for checking the array.

Add a compact lookup sanitizer regression covering sizes zero through
five, existing supported sizes, and truncated payloads. The regression
rejects the original zero-sized case and accepts the supported controls.
All 294 Meson tests pass, including the shape suite, and the new test
passes under ASan and UBSan.

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

Assisted-by: OpenAI Codex
2026-10-30 14:54:49 -06:00
Behdad EsfahbodandClaude Opus 4.8 a14c095e3f [vector] Refuse PDF indexed-PNG soft masks larger than the document cap
hb_pdf_build_indexed_smask() allocated and filled (width+1)*height and
width*height bytes straight from the attacker-controlled PNG IHDR, while
HB_VECTOR_MAX_DOCUMENT_SIZE was only consulted when the finished mask was
appended to the PDF object.  A ~1 MB sbix/CBDT font could thus make the
PDF backend inflate and un-filter up to a 4 GiB mask per painted glyph,
only to drop it afterwards.

The mask is emitted uncompressed into a document-capped hb_vector_buf_t,
so a mask larger than the cap can never be appended: reject it alongside
the existing 32-bit overflow guards in the builder (the same pattern as
the raster PNG decoder's HB_RASTER_MAX_BUFFER_SIZE check), which bounds
both allocations (raw_len = mask_len + height) before any work is done.

add_xobject_png_image() additionally skips registering and referencing
the SMask object when its buffer tripped the cap, so the output no longer
contains a dangling empty-stream object for an edge-case mask that fits
the builder but not the object with its header.  Masks that fit today are
unaffected.

A regression test in test/vector/test-vector-budget.c hand-rolls a zlib
stream for a 4097x4096 indexed PNG with tRNS, paints it to PDF, and
asserts the render succeeds without an /SMask.

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 14:53:31 -06:00
Behdad EsfahbodandClaude Opus 4.8 d73f4eea07 [instancer] Treat a zero-size pool allocation as success in gvar instancing
hb_alloc_pool_t::alloc(0) legitimately returns nullptr while no shared
chunk is open, but hb_vector_t::allocate_from_pool() took any nullptr as
an allocation failure and flagged the (empty) vector with set_error().
The next allocate_from_pool() on it then tripped
assert(!length && !allocated), aborting hb-subset during partial
instancing of a crafted ~1 KB variable font whose retained glyph has
more than 16,376 points (so no small request ever opens the shared
chunk) and whose tuple is split by the requested axis range.

Fix the root cause where the vector already special-cases zero-size
requests on the heap path: a null result is a failure only when bytes
were requested (size && !arrayZ).

tuple_delta_t::copy_from() also discarded the results of its seven
duplicate_vector_from_pool() calls, so a genuine pool failure during a
tuple clone would reach the same assert (or silently drop gvar under
NDEBUG); it now returns bool, change_tuple_var_axis_limit() marks out in
error, and change_tuple_variations_axis_limits() fails instead of
continuing.

A regression test for the zero-size pool allocation is added to
src/test-vector.cc. The attack font now instances to the same output as
the control; test-vector and the subset suite pass.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 14:53:31 -06:00
Behdad Esfahbod c34cf564b1 [ft] Allow font queries from color paint callbacks (#6490)
Release the face lock around solid, gradient, and custom palette
callbacks. Keep lazy FreeType color-stop reads locked and give each
getter call its own iterator, so callbacks can query the same font
without deadlocking or disturbing another stop query.

Snapshot the selected palette once per COLRv1 traversal, shared by
the bounds and paint passes. Nested paints can select a different
palette on the face; they must not change the outer paint's colors.
Return failure if the palette copy cannot be allocated. Stops remain
lazy and no cache policy or limits change.

Add a bounded callback regression with the existing COLRv1 fixture.
It queries font extents, performs nested paints with another palette,
and checks repeated and paged stop reads against the OT backend.
The original code times out; unlocking without copying the palette
fails the color comparison. The full Meson suite passes: 274 tests, no failures.

Reported by Anthropic's OSS Scanner as ANT-2026-YPLDSFHA.

Assisted-by: OpenAI Codex
2026-10-30 14:52:35 -06:00
Behdad Esfahbod f9fcba7272 [repacker] Prevent matrix vertex size checks from wrapping (#6491)
AnchorMatrix's offset array size was multiplied in unsigned arithmetic.
A small vertex with 46341 rows could therefore be accepted as a
46341-column matrix, leading to excessive work and allocation during
subtable splitting. PairPosFormat2 had the same problem on 32-bit
platforms.

Use the existing size_t saturating multiply helper and compare against
the payload length after checking the header. This preserves the width
of PairPosFormat2's size computation and avoids overflow in the header
addition as well.

Add bounded internal vertex tests for wrapping dimensions, exact valid
sizes, truncated payloads and headers, and empty matrices. The anchor
regression fails against the unchanged code without large allocations.

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

Testing: meson compile -C build -j4; meson test -C build
(all 274 tests passed).

Assisted-by: OpenAI Codex
2026-10-30 14:51:09 -06:00
Behdad EsfahbodandClaude Opus 4.8 51fae4098a [subset/CBDT] Bound image bytes copied out of the source table
IndexSubtableRecord::add_new_subtable() bounds-checks each retained
glyph's image block against the source CBDT table, but nothing
requires the blocks of different glyphs (or strikes) to be distinct
and nothing limits the total copied.  A format 3 offsetArray of
0, 65535, 0, 65535, ... makes every even glyph copy the same 64 KB,
so a ~186 KB font makes one hb_subset_or_fail() peak at ~3.8 GB and
emit a ~1.97 GB font.  The existing source_blob->length * 256 cap
covers only the serializer buffer holding the new CBLC, not the CBDT
side buffers.

Charge every block copied out of the source CBDT to a byte budget
that is proportional to the source table and shared across strikes,
and fail the strike when it runs out; the existing subset_size_table()
path then reverts that strike and continues.  The budget lives in
cbdt_dedup_context_t, which CBLC::subset already shares across every
strike, and is set to cbdt_length * HB_SUBSET_CBDT_MAX_COPY_FACTOR, a
new limit (64) in hb-limits.hh.  The charge is taken before the copy
into the per-strike buffer, so strikes that end up sharing data are
bounded as well, and it covers index formats 1/2/3 and overlapping
records, not only non-monotonic format 3 arrays.  The budget defaults
to unlimited, so the direct users of the struct (test-cbdt-cache) are
unaffected; a well-formed font copies each byte at most once per
strike, so only a font whose strikes reference the table more than 64
times over loses bitmaps.

This is distinct from the integer-overflow hardening of
_copy_data_to_cbdt() in PR #6485: that bounds the final append to
cbdt_prime, this bounds the overlap amplification before the copy.

Adds test_subset_cbdt_overlapping_images, which builds the format 3
shape above and asserts the output CBDT stays within the factor
(524292 > 65536 on the unpatched tree).  The api and subset suites
pass and the reproducer drops from 3767 MiB to 17 MiB.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 14:50:11 -06:00
Behdad Esfahbod ca538ba0d1 [ft] Preserve face and blob ownership through loader lifetimes (#6475)
Keep the memory-backed FT_Face blob on the hb_face_t even when the
OpenType sanitizer discards its copy. Otherwise the destroy callback
can release the FT_Face while the face or font still uses it. Return
the empty object on allocation failure before accessing that pointer.

Keep a blob loader's input bytes on the FT_Face rather than the
hb_face_t, since retained table blobs can outlive the latter. Keep the
library reference on the input blob and release it outside the static
FreeType mutex. Initialize file-loader ownership before transferring
references as well.

Add regressions for destroy-callback timing, referenced font lifetime,
and table blobs retained past the source face. All 293 tests pass,
including all eight FreeType subtests under ASan and UBSan. A separate
sanitized ownership probe passes 154 allocation-failure cases.

Discovered by Anthropic's OSS Scanner, as vulnerabilities
ANT-2026-FC0F75Y2 and ANT-2026-O2E5WAA5.

Assisted-by: OpenAI Codex
2026-10-30 14:49:21 -06:00
Behdad EsfahbodandClaude Opus 4.8 703509a9d9 [GPOS] Bound cross-offset resolution by the glyph count (#6492)
Cursive lookups with different flags can create an attachment cycle.
The const cross-offset walker then follows it forever when attaching
a mark. An acyclic chain over len glyphs has at most len - 1 links;
stop at that bound while retaining every valid forward and backward
chain and the existing offset accumulation behavior.

Add an in-house shaping regression instead of a bespoke unit test:
a tiny payload font whose two cursive lookups (one RightToLeft, one
IgnoreMarks) close an A -> B -> C -> A cycle, with a MarkBasePos that
attaches a mark onto C. Shaping ABCD looped forever before the fix and
now terminates. The original hang is reproduced on the unpatched tree;
the patched build shapes it identically under the ot and ft font-funcs.
The full Meson suite passes (274 tests), including shaping.

Reported by Anthropic's OSS Scanner as ANT-2026-PRD7EFA6.

Assisted-by: OpenAI Codex

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 14:48:18 -06:00
Behdad EsfahbodandClaude Opus 4.8 d5471c112c [set] Keep the set well-formed when growing it fails after compaction (#6495)
process_() moves the kept page_map entries to the front and renumbers
their pages with compact() before calling resize(count), which can fail
when the operation grows the set (passthru_right without passthru_left:
union with an inverted set, intersect of an inverted set, subtract of two
inverted sets). On failure the set kept its old page_map/pages length with
a duplicated, unsorted map; hb_bit_set_t::set() copied that state into a
fresh set that reported success, and a later del_range()/add() then indexed
pages out of bounds.

compact() already knows the kept length, so truncate page_map and pages to
it with shrink(length, false), which cannot fail. The set is now consistent
before any fallible growth, and del_pages() no longer needs its own resize()
after compact().

Only host programs doing mixed inverted/normal hb_set_t arithmetic under a
failing allocation reach this; HarfBuzz itself never runs the operation on a
non-empty left set, so it is an ordinary bug, not a security issue.

A regression test in src/test-set.cc simulates the allocation failure for
both process() and del_range() and checks the resulting lengths and map.

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

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 14:46:10 -06:00
Behdad EsfahbodandClaude Opus 4.8 8986600d59 [sbix,CBDT] Index strikes by ppem in the accelerator
sbix::accelerator_t::choose_strike() and CBLC::choose_strike()
walked the whole strike array on every extents/PNG/paint query, and
nothing bounds the strike count beyond the sanitizer byte budget, so
a font with a very large strike array made each per-glyph query cost
one iteration per strike.  With a ~300 KB sbix font holding 75000
strike offsets, one hb_shape() over a long mark run took tens of
seconds.

The chosen strike depends only on the table and the requested ppem
(smallest strike ppem >= requested, else the largest; the first index
among equal ppems), so the accelerator constructor now records the
first strike index per distinct ppem in an hb_set_t/hb_map_t (ppem is
at most 16 bits, so both stay tiny whatever the strike count is), and
choose_strike() becomes a set next()/get_max() plus a map lookup.
CBLC::choose_strike() is moved into CBDT::accelerator_t, its only
caller, to hold the same index.  On allocation failure the set stays
empty or the map returns HB_MAP_VALUE_INVALID, which the existing
bounds-checked array access turns into the Null strike, i.e. no
bitmap rather than corruption.

Strike choice is unchanged.  The reproducer drops from ~40 s to
0.08 s of CPU with identical output; the shape and api suites pass.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 14:45:16 -06:00
Behdad EsfahbodandClaude Opus 4.8 f69c05ea38 [cairo] Map non-monotone buffer clusters to one cairo cluster
hb_cairo_glyphs_from_buffer() asserted that buffer clusters are monotone
in the buffer direction, but hb_shape() does not guarantee that:
HB_BUFFER_CLUSTER_LEVEL_CHARACTERS, shaping that hits the ops limit
mid-lookup, and Indic reordering corner cases can all produce
non-monotone clusters.  The function runs from HarfBuzz's own cairo
text_to_glyphs callback on attacker-controlled text and fonts, so the
assertion was an input-dependent abort (and, with NDEBUG, an unchecked
backward walk off the ends of the utf8 buffer).

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

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

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 14:45:15 -06:00
Behdad EsfahbodandClaude Opus 4.8 4e215a7ec8 [cairo] Don't leak the hb_font_t created per scaled font
hb_cairo_init_scaled_font() must hand exactly one reference of the
hb_font_t to the cairo_scaled_font_t.  For a face-based font face
(hb_cairo_font_face_create_for_face()) it creates the font with a
reference count of 1, but then still called hb_font_reference() before
attaching it, so the creating reference was never released.  Every
finalized scaled font therefore leaked an hb_font_t, pinning its
hb_face_t, the font blob and the accelerators until the process exits.
Cairo finalizes scaled fonts during normal operation once its cache
fills, so the leak accumulates as content selects distinct sizes,
transforms or font options.

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

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

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

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 14:44:32 -06:00
Behdad EsfahbodandClaude Opus 4.8 fd8c9209b6 [cairo] Paint nested color glyphs inline to bound recursion
hb_cairo_paint_color_glyph() accepted the color_glyph paint callback
and drew the nested glyph with cairo_show_glyphs(), which re-enters
hb_font_paint_glyph() through a new cairo scaled font with a fresh
hb_paint_context_t.  The glyph decycler, HB_MAX_NESTING_LEVEL and the
edge budget therefore start over at every level, so two glyphs that
paint each other with PaintColrGlyph recurse until the stack is
exhausted.  The per-scaled-font hb_cairo_budget_t cannot bound this
either: the nested glyph is shown through a different scaled font, so
each level gets its own budget.

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

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

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-30 14:43:49 -06:00
Behdad Esfahbod 88e5077a80 [aat] Read kerx format 2 class values as byte offsets (#6494)
Format 2 class values are byte offsets, but ExtendedTypes::offsetToIndex
leaves them unchanged. Use byteOffsetToIndex to convert their sum to an
FWORD index. ObsoleteTypes retains the existing kern format 2 behavior.

Add a synthetic font and shaping regressions covering negative and
positive kerning, the final array entry, zero classes, missing lookup
entries, and disabled kerning.

The shaping regression fails without the fix. The full Meson test suite
passes, and Helvetica Light's LY, AY, Hi, and HH kerning matches CoreText.

Fixes: https://github.com/harfbuzz/harfbuzz/issues/6461
Assisted-by: OpenAI Codex
2026-10-30 12:49:31 -06:00
Behdad Esfahbod 6156c7b4a7 [subset] Validate custom glyph mappings before assigning output ids (#6479)
Glyph zero is always reserved for .notdef. Reject mappings that assign
another retained glyph to it, so the output list has one entry per id.

Also bound the resulting glyph count by the widest supported count
field, MAXP's HBUINT24. Account for the unmapped glyphs and the initial
slot before assigning ids, avoiding wraparound and oversized counts in
table subsetters. The limit applies to the count, not the highest id.

Document these constraints and test valid renumbering, gaps, ignored
remapping of .notdef, reserved-id collisions, and out-of-range counts.
The regression and stock hb-subset both reproduce the issue under ASan
before the fix. All 293 tests pass after it, including the subset suite;
the API subset tests and command-line checks also pass ASan and UBSan.

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

Assisted-by: OpenAI Codex
2026-10-29 21:01:05 -06:00
Behdad Esfahbod d8347f079e [repacker] Count null offsets when splitting ligatures (#6476)
Ligature split points skipped null offsets while the ranges used to
clone and shrink subtables counted every slot. Advance the split index
for null offsets too, so both stages refer to the same ligatures.

Also reject an inverted range after narrowing it to the remaining
links, before calculating the number of ligatures to allocate.

Add a regression that compares the split graph with the expected
subtables when one ligature set has trailing null offsets.

Testing: meson test -C build (292 passed; check-symbols skipped on
macOS), plus the repacker test and shared-ligature font check with
ASan and UBSan.

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

Assisted-by: OpenAI Codex
2026-10-29 21:00:03 -06:00
Behdad Esfahbod 8f115ee233 [vector] Keep allocation capacity representable as an int (#6484)
Reject allocation requests above INT_MAX before growing the capacity,
and cap geometric growth at that limit. Otherwise the unsigned growth
loop can wrap, or a successful allocation can store a negative value
in the signed capacity field. Normalize exact requests before checking
the limit so the existing length is included.

Test both normal and exact oversized requests, preservation of existing
contents on failure, and saturation of geometric growth. Intercept the
allocator in the unit test to avoid allocating large buffers. The new
regression fails before the fix. All 293 tests pass, and test-vector
passes under ASan and UBSan.

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

Assisted-by: OpenAI Codex
2026-10-29 20:58:54 -06:00
Behdad Esfahbod 4aebec5702 [subset/cff1] Bound preprocessing map lookups for output gaps (#6481)
A custom glyph mapping can leave unassigned output glyph IDs beyond
the source glyph count. The preprocessing glyph-to-SID map only covers
source glyphs, so use the existing charset lookup for those gaps and
skip the map-based range shortcut there.

Compare plain and preprocessed subsets of existing name-keyed and
CID-keyed fonts with output gaps. The new regression fails under ASan
before the fix. The complete ASan/UBSan Meson suite passes afterward
(293 tests, including 23 CFF1 API subtests).

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

Assisted-by: OpenAI Codex
2026-10-29 20:57:13 -06:00
Behdad Esfahbod 21a2f7c43e [repacker] Reject output sizes that cannot fit a blob (#6478)
The graph total is size_t, while the output vector allocation takes an
unsigned int. Check the total against the blob length limit before that
conversion, so the allocation and serialization context use the same
size. Totals above INT_MAX cannot produce a valid output blob anyway.

Add a public-API regression whose objects share their backing storage,
keeping its memory use small while exercising a large graph total.

Testing: meson test -C build (292 passed; check-symbols skipped on
macOS), plus test-subset-repacker with ASan and UBSan. The regression
reproduces the invalid write without the check and fails cleanly with it.

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

Assisted-by: OpenAI Codex
2026-10-29 20:56:03 -06:00
Behdad Esfahbod fdd29aa9a9 [subset] Check the VARC axis-index allocation size before narrowing (#6477)
The saturating size helper returns size_t, so assigning its product to
unsigned can truncate it before the UINT_MAX check. Check multiplication
at unsigned width before resizing the buffer used by compile_unsafe().

Validated the reported high-count case under ASan/UBSan: it fails cleanly
after this change. A small control produces byte-identical output. The
ASan/UBSan Meson suite passes; check-symbols also passes after generating
its symbol manifests.
The large input remains a manual regression because it requires several
GB of memory.

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

Assisted-by: OpenAI Codex
2026-10-29 20:55:45 -06:00
Behdad Esfahbod d0b38a793b [arabic-fallback] Count components only for matched ligatures (#6474)
A missing component skipped a fallback ligature but left its partial
component list counted. Later ligatures then used the wrong letters.
Write tentative components at the current offset and advance the
count only after every component has matched.

Add a generated GSUB-less font and two shaping regressions, covering
both the wrong ligature and the valid ligature it displaced, with ot
and ft font functions. All four cases fail before the fix. The full
Meson suite passes (293 tests, 6227 in-house shaping subtests).

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

Assisted-by: OpenAI Codex
2026-10-29 19:31:29 -06:00
Behdad Esfahbod ecf0bc81aa [subset] Keep ClassDef range traversal in sync for class zero (#6473)
The class-zero intersection loop skipped ranges starting at glyph 0
without advancing the last glyph, and consulted a separate iterator
instead of the range being visited. Probe only actual gaps and always
advance past each range, so unlisted glyphs retain class-zero rules.

Check all 256 glyph sets over eight glyphs against per-glyph class
lookup for empty, contiguous, gapped, and explicit class-zero ranges.
The regression fails on the old source. The full Meson suite passes
(293 tests), including shape and subset.

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

Assisted-by: OpenAI Codex
2026-10-29 19:30:56 -06:00