Commit Graph
22426 Commits
Author SHA1 Message Date
Michael Nosthoff 09aff9962a meson: order GPU compilation after shader header generation (#6590)
The shader header custom targets are built by default, but their outputs
are not included in the sources of libharfbuzz-gpu. This allows Ninja to
compile the GPU sources concurrently with shader header generation.

The generator also copies each generated header into the source directory.
The GPU sources use quoted includes, which find these source-tree copies
first. Since the copy truncates its destination before writing, a compiler
running concurrently can read an empty header and report undeclared shader
symbols.

Collect the shader header targets and add them to the GPU library sources.
Meson then orders compilation after those targets have completed, including
their copies back into the source tree.

Keep the existing build-by-default behavior unchanged.

Fixes: b1ad797e5 ("[gpu] Commit stringized shader headers; auto-regenerate like ragel")


Assisted-by: Copilot <223556219+Copilot@users.noreply.github.com>

Signed-off-by: Michael Nosthoff <buildroot@heine.tech>
2026-11-07 16:37:48 -06:00
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
Reilly Brogan 24439d01be [check-libstdc++] Only inspect direct DT_NEEDED entries (#6592)
ldd prints the full transitive dependency closure, so the check fails when a
dependency of a dependency links C++ (for example cairo -> fontconfig ->
libxml2 -> ICU), even though HarfBuzz itself has no libstdc++/libc++ NEEDED
entry. When readelf (or llvm-readelf) is available, inspect the library's own
(NEEDED) entries and check every exported library, including harfbuzz-cairo
and harfbuzz-icu. Without either tool, keep the ldd/otool closure check but
skip those two, whose closure is known to contain libstdc++.
2026-11-07 13:26:37 -06:00
Reilly Brogan 5a53654525 [tests] Fall back to llvm-objdump and llvm-nm (#6593)
Toolchains that ship only the LLVM binutils have no GNU objdump or nm, so
check-static-inits and check-symbols are skipped. Try llvm-objdump and
llvm-nm as fallbacks; their output is compatible with the parsing in these
checks. Also correct the check-static-inits skip message, which named ldd
instead of objdump.
2026-11-07 12:51:23 -06:00
Qunxin Liu 316e802222 [subset] Check context rule input glyphs against the GSUB glyph set (#6589)
Rule::subset (glyph-based Context format 1 rules) checked and mapped
input glyphs with plan->glyph_map, which also contains glyphs that are
only retained by later closures, e.g. glyf composite components. Rules
whose input glyphs can never be in the glyph run were therefore kept.

ChainRule::subset already checks against the GSUB glyph set. Use
plan->glyph_map_gsub, which maps exactly the GSUB glyph set to the same
new glyph ids, so both are consistent.
2026-11-05 12:33:46 -06:00
Behdad Esfahbod fcebeeba60 [util] Include serialization in hb-subset iterations (#6580)
hb-subset serialized only the final face, leaving serialization out of
the repeated work measured by --num-iterations.

Reference each subset face's blob inside the loop, releasing the
previous blob on the next iteration and writing the final blob once.

Tested with meson test -C build: 299 passed, 1 skipped. Also checked
identical output for one and three iterations with and without
preprocessing, plus zero iterations and invalid-font handling.

Assisted-by: Codex
2026-11-04 17:32:09 -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
Khaled Hosny 3df40d9b98 15.1.0 15.1.0 2026-11-04 23:03:36 +02:00
ebraminio e1db1b215a [CFF] Fix trailing-zero exponent in BCD encoder (#6577)
Block 3 assumed exactly 3 trailing zeros (matching its "000" guard) and
then walked backward from len - 4, incrementing exponent on each step.
The two roles on one variable — start position AND final count — only
coincided when the mantissa had 3 leading digits, so any "X...0000"
with 4+ zeros was off by 10x or more:

  123000    -> "123E3"   (correct)
  1230000   -> "123E5"   (should be E4)
  12340000  -> "1234E6"  (should be E4)
  1000000   -> "1E7"     (should be E6)

Real fonts only produce fractional BCD values (0.001, 0.039625), so
this is latent, but it silently corrupts the output when triggered.

Fix: count trailing zeros from s + len - 1.  s[0] is guaranteed
non-'0' by blocks 1-2 ("0.xxx"/"-0.xxx"), so the backward scan
terminates before reaching s.

Also moves encode_byte(OpCode_BCD) past the nibble-buffer allocation
so OOM bails cleanly instead of emitting a marker with no digits.

Tests: 12340000.0, 1000000.0 (block 3 with 4+ zeros); 0.0012
(block 1->6); 1.23e-5 (block 4, negative exp); 123456780.0 (block 5,
newExponent==1); 0.000123, -0.000123 (block 1/2 -> 6 chain).
2026-11-04 14:59:07 -06:00
Koi 613f59727a [subset] Keep the format byte when serializing DeltaSetIndexMap format 1 (#6573)
* [subset] Keep the format byte when serializing DeltaSetIndexMap format 1

DeltaSetIndexMap::serialize() set u.format before calling the
format serializer, and DeltaSetIndexMapFormat01::serialize() then
calls extend_min(), which zero-fills the header. Format 0 survived
because its format value is 0, but a format 1 map (more than 65535
entries) came out with format 0, so readers took the upper half of
the 32-bit mapCount as a 16-bit count and lost the HVAR advance
deltas of the subset font.

Set the format inside DeltaSetIndexMapFormat01::serialize() after
extend_min(). Add a test-serialize case that checks both formats.

Fixes: https://github.com/harfbuzz/harfbuzz/issues/6440
Assisted-by: OpenCode

* [subset] Test DeltaSetIndexMap at the format boundary

Run the DeltaSetIndexMap serialize check with 65535, 65536 and 65537
entries so the <= 0xFFFF switch between format 0 and format 1 is
covered, and give the last entry a value no other entry has so a read
of the wrong entry is caught.

Assisted-by: OpenCode
2026-11-04 13:09:53 -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
Roshan Ramani 1a6008afb8 [docs] Drop HB_SUBSET_DEPEND_API from the depend API guide (#6570)
df5ce0d58 removed the macro, so the depend API is now only built with
experimental_api. The basic example also needs hb-subset.h, not hb.h.

Assisted-by: Claude
2026-11-04 12:03:10 -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
ebraminio df9e6d1514 [number] Make _pow10 more accurate (#6555)
Replace the 9-constant composition (up to 6 multiplies, ~3 ULP) with
two precomputed tables: 10^0..10^15 exact, 10^16..10^304 rounded.
One multiply on the large side, ~2 ULP, no loop.

Prior to the two-table _pow10, these were computed by composing 10^n
from nine powers-of-10 constants.  Every constant above 10^22 carries
its own rounding error, and the six multiplications that build up a
typical exponent accumulated 2-3 ULP.  The two-table version reduces
this to a single multiply of two correctly-rounded constants and
lands within ~1 ULP of strtod.

Each case decomposes n = 16*q + r for a different (q, r), exercising
the (n >> 4, n & 15) split at different offsets in the tables.
Inputs are the simplest form that produces the same (q, r) as the
fuzzer-discovered failing inputs.
2026-11-02 13:06:07 -06:00
m00dy b8d093e607 Merge pull request #6557 from professor-moody/fix-cff1-glyph-to-sid-map-error-state-leak
[subset/cff1] Free a failed glyph-to-SID map created during subsetting
2026-11-02 13:00:26 -06:00
Behdad Esfahbod 5cb6cac5f7 Merge pull request #6505 from harfbuzz/scanner/repacker
[repacker] Fix an OOB write, an overflow-error crash, and six repacker DoS issues
2026-11-02 11:48:40 -06:00
Behdad Esfahbod 653467a9bc Merge pull request #6513 from harfbuzz/scanner/aat
[aat] Fix kern/kerx/mort/morx correctness bugs, a leak, and DoS hardenings
2026-11-02 11:42:21 -06:00
Behdad Esfahbod f34d3fbf87 [algs] Make ARRAY_LENGTH a constant expression for array references (#6553)
Use hb_array_length as an array trait deriving from integral_constant,
with an incomplete primary template to keep rejecting pointers. Have
ARRAY_LENGTH remove references and extract the trait's value without
evaluating the array expression.

This lets Arabic fallback use ARRAY_LENGTH directly for its ligature
table dimensions. Update the reference-parameter checks and verify that
side effects in the array expression are not evaluated.

Validated with a warning-free full Meson build and meson test -C build
(298 passed, 1 skipped). GCC and Clang C++11 checks cover the algorithms
test, Arabic shaper, HB_TINY amalgamation, cv-qualified and rvalue arrays,
debug linking, and rejection of pointer arguments.

Assisted-by: OpenAI Codex
2026-11-02 10:15:49 -07: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 cd570b6f54 [aat] Match morx language-tag features against ltag without interning the font's tags
Chain::compile_flags() resolved every type-39 (language tag) feature
record by interning the font's ltag string with
hb_language_from_string(), whose process-wide language list is a
linear, never-freed linked list meant for the handful of languages an
application passes in.  A font controls both the number of records and
the number of distinct tags, so shape-plan creation became quadratic
(about a minute for a 125 KB font) and the tags stayed in the list for
the life of the process.

Add ltag::matches_language(i, specific), which compares the tag bytes
directly against the buffer language, applying the same
canonicalization hb_language_from_string() does (at most 63 bytes,
lowercase, '_' to '-', stop at the first other non-alphanumeric) and
the same prefix rule as hb_language_matches(); each record now costs
at most the length of the buffer's language and nothing is added to
the global list.  get_language() is kept for the name table, which
genuinely needs an hb_language_t.  Behaviour is unchanged for every
real tag; only a degenerate tag with no valid leading byte, which used
to become the empty/invalid language, now matches nothing.

Adds a regression font to the in-house aat-morx tests whose type-39
features gate substitutions by tags 'sr' and 'Zh_Hant', exercising
case folding, '_' canonicalization, subtag prefix matching and
non-matches.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-02 10:52:07 -06:00
Behdad EsfahbodandClaude Opus 4.8 77be62a733 [aat] Collect LookupFormat2 glyphs in one pass over the segments
The per-subtable glyph sets built by the morx/kerx chain accelerator
assume LookupFormat2 segments are sorted and disjoint, but the
sanitizer does not check that, so a malformed table can repeat a
segment spanning the whole glyph range tens of thousands of times,
and every subtable pointing at it pays a full bit-set pass per
segment -- 300 subtables sharing one 65000-segment lookup stalled
shaping two letters for over 20 seconds.

Make LookupFormat2::collect_glyphs{,_filtered} track the end of the
last range added and, at the first segment that is out of order, fold
every remaining matching segment into a single add_range.  For
well-formed fonts the result is identical; for malformed ones it is a
superset, which is safe because the set is only an intersects()
pre-filter.  collect_glyphs() now shares the filtered implementation
with an always-true filter.  Formats 4/6/8/10 cannot amplify this way
and are untouched.

Adds a morx font with unsorted format-2 segments to the in-house
aat-morx shape tests, checking the subtable still applies.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
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 663a004d7c [aat] Charge each applied kerx/kern/morx subtable pass to max_ops
KerxTable::apply() (shared by kerx and both kern flavours) and morx
Chain::apply() run one full pass over the buffer per subtable, but a
pass that changes nothing never touched buffer->max_ops, so a font
could ask for an unbounded number of passes -- and morx may first
grow the buffer up to 256x, so each pass is over a much larger buffer
than the input.  The kerx loop also ignored buffer->successful.

Add hb_aat_apply_context_t::charge_buffer_pass(), which debits
buffer->len from max_ops using the same decrement/check/
successful=false idiom as morx glyph insertion and hb_buffer_t, and
call it in both subtable loops right before a subtable is applied;
skipped subtables (wrong direction, no glyph intersection) stay free.
Placing the charge in the shared apply context covers kerx, OT kern,
Apple kern and morx with one helper.  Also stop the kerx loop once the
buffer is no longer successful, as the morx loop already does.

This complements the subtable-count cap: that bounds the per-face
accelerator memory, while this bounds the per-shape pass work,
including passes over a buffer that morx has grown.  Real fonts apply
a few subtables over a buffer far shorter than the budget, so they are
unaffected.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-02 10:51:40 -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 EsfahbodandClaude Opus 4.8 843b32d48c [aat] Destroy the losing morx chain accelerator before freeing it
hb_aat_layout_chain_accelerator_t owns one hb_bit_set_t (pages and
page_map heap vectors) per subtable, filled by create() and released
only by destroy().  mortmorx::accelerator_t::get_accel() builds a copy
lazily and, when another thread already installed one, discarded its
own copy with a bare hb_free(), leaking every subtable's glyph set.
The lost-race branch is the only place the object was released without
destroy() -- ~accelerator_t() calls destroy() first, and the sibling
lazy-install patterns (the GSUB/GPOS accelerator and
destroy_buffer_glyph_set()) already fini() before free -- so add
accel->destroy() there to restore the invariant.  mort and morx share
the template, so one line covers both tables.

No regression test: the leak is timing-dependent and none of the
in-tree AAT fonts reaches the race window dependably in the threads
suite.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-02 10:51:40 -06:00
Behdad EsfahbodandClaude Opus 4.8 5afb887342 [aat] Index morx chain accelerator entries by subtable position
hb_accelerate_subtables_context_t::dispatch() filled accelerator
entries with a counter that advanced only for the subtable types
ChainSubtable::dispatch() knows, while Chain::apply() reads entries by
subtable position.  A subtable of a reserved type (3, or 6 and up),
which the sanitizer accepts and apply() steps over, shifts every later
entry down by one, so each later subtable is gated by the wrong glyph
set and the last one gets a zeroed entry and is never applied.  Output
then depends on where the unknown subtable sits in the chain.

Add Chain::accelerate(), the same walk Chain::dispatch() does but
setting the context's index to the subtable position before each
dispatch, and stop the context's dispatch() from advancing the index
itself; create() calls accelerate() instead of dispatch().  Unknown-
type subtables keep a zeroed entry, which is what the calloc in
create() already relies on, and apply() does nothing for them anyway.
mort shares Chain/ChainSubtable so it is fixed too; the kerx
accelerator already fills one entry per subtable and is untouched.

Adds a regression font with subtables [reserved, 1->2, 3->1] to the
in-house aat-morx shape tests.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-02 10:51:40 -06:00
Behdad EsfahbodandClaude Opus 4.8 ec4a38c4ab [aat] Fix negative-state arithmetic in StateTable so 'kern'/'mort'
tables with a non-first initial state are accepted

AAT::StateTable numbers the rows before the initial 'kern'/'mort'
row negatively (the Apple stateArray quirk the code documents), but
the negative branch of sanitize() passed the negative int min_state
to hb_unsigned_mul_overflows() and used it in unsigned index
arithmetic, so the overflow check always fired and such tables were
always rejected and silently dropped.  get_entry() indexed the state
array the same unsigned way and would read far past it had sanitize()
let those tables through, so the two functions have to be fixed
together.

sanitize() now works with the magnitude of min_state
(num_neg_states = -min_state) for the overflow check, the
check_range() and the sweep pointer, and get_entry() computes its row
index in signed int so negative states address the rows before the
initial one.  Negative states only arise for ObsoleteTypes, where
nClasses and offsets are 16-bit so the products fit; for ExtendedTypes
states are never negative and sanitize() already bounds
(max_state+1)*nClasses by the blob size, so the (int) casts cannot
change any sanitized index.

Fonts whose 'kern' format 1 / 'mort' state tables use a non-first
initial state now sanitize and apply instead of being dropped.  Adds
a regression test (kern-format1.tests plus its font) to
test/shape/data/in-house.

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-02 10:51:40 -06:00
nussaibah shaikh c89c0c4aa5 Fix signed overflow sorting axis tags (#6551)
tuple_variations_t::_cmp_axis_tag() subtracted two axis tags as int.
The tags come from the font, so tags far apart in signed range, such
as one with the high bit set, overflow the subtraction during partial
instancing. UBSan reports signed-integer-overflow from
change_tuple_variations_axis_limits(). The wrapped result also makes
the comparator inconsistent, for a sort that exists to keep the
result deterministic.

Use _hb_cmp_operator<hb_tag_t, hb_tag_t>, as other sorts in the tree
do, and drop the local comparator. Printable ASCII tags keep their
order, so valid fonts are unaffected.

Testing: added a 1074-byte fuzzer seed that fails under UBSan without
the fix. meson test -C build-asan passes 100/100 with
-Db_sanitize=address,undefined -Dexperimental_api=true. The build had
no glib, so test/api did not run.

Assisted-by: Claude
2026-11-02 09:13:37 -07:00
Behdad EsfahbodandClaude Opus 4.8 708d59a507 [shape-plan] Cache the last shape plan looked up per face (#6550)
hb_shape_plan_create_cached2() walks the face's plan list on every call. The
list is never capped (by design, like the rest of the cache), so on a
long-lived face that has accumulated many plans, repeatedly reshaping with a
plan that sits deep in the list re-walks it each time.

Add a one-entry per-face "last plan" cache: an atomic pointer to the most
recently matched node, checked before the list walk and updated on hit and on
insert. Plan nodes are never freed before the face, so a cached pointer stays
valid; a stale or raced read just fails the key compare and falls through to
the walk. The common single-plan case already hit on the first node (the list
is front-prepended); this bounds the lookup for the many-plan case too.

Uses hb_atomic_t<T*>::set_release(), added in #6549.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-01 21:54:17 -07:00
Behdad EsfahbodandClaude Opus 4.8 31083b1f24 [common] Cache the last hb_language_from_string() result (#6549)
hb_language_from_string() walks the whole intern list on every call. A
process that looks up the same tag repeatedly -- the common case, since a
mostly-one-language document resolves its language once per run -- pays that
linear scan each time, and the list is never freed, so the cost grows with
every distinct tag ever seen.

Add a one-entry "last found" cache: an atomic pointer to the most recently
returned language item, checked before the scan and updated on hit/insert.
Interned languages are never freed, so a cached pointer stays valid; a stale
or raced read just falls through to the list scan, and the cache is cleared
in free_langs(). Repeated same-tag lookups become O(tag length) instead of
O(list length). (The adversarial flood of *distinct* tags is still linear --
that is the by-design never-freed list.)

Adds the missing set_release() to hb_atomic_t<T*> so the cache store
publishes a freshly-inserted item's fields to a concurrent reader.

Prompted by harfrust OSS-scanner finding ANT-2026-IA4M34ES, which notes that
HarfBuzz's hb_language_from_string() has a comparable linear scan (its
getters, unlike the port's, already avoid re-searching).

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-01 21:19:20 -07:00
Behdad Esfahbod 2b1e11ee50 [subset] Use serialized contour coordinates for IUP optimization (#6547)
A shifted default can leave fractional contour coordinates that round to
identical positions in glyf. Selecting IUP references against those
fractions can omit deltas that no longer interpolate correctly after
serialization. The reported four-point case loses 499 units.

Round the real contour points after merging default deltas and before
selecting IUP references. The gvar caller already uses a private point
copy, so the plan's coordinates and metric calculations stay intact.
Leave the four phantom points unrounded.

Add a tuple-store regression covering both axes and signs, and regenerate
six affected subset expectations. The reported fixture now reconstructs
exactly. All nine checked optimized fixtures stay within the existing
0.5-unit tolerance against optimization-disabled output, with unchanged
non-gvar tables apart from the head checksum.

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

Fixes: https://github.com/harfbuzz/harfbuzz/issues/6462
Reported-by: olsklcode
Assisted-by: OpenAI Codex
2026-11-01 19:29:45 -07: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 Esfahbod 0e6a9c81f0 [indic] Fix Unicode 18 shaping and Rust table generation (#6544)
* [indic] Include Unicode 18 Devanagari and Bengali additions

The block filter discarded U+11B0A even though the Unicode 18 data
classifies it as a consonant. Following marks therefore formed broken
syllables and received unwanted dotted circles. The same omission
excluded Bengali Supplement's U+11DF0 and U+11DF1.

Include both blocks and regenerate the Indic table. These three code
points are the only effective classification changes. Add nine shaping
cases using the existing Adobe Blank font, including a valid-syllable
control and an isolated anusvara that needs a dotted circle.

Eight new cases fail before the fix. All 275 Meson tests pass after it,
including the full shaping suite.

Fixes: https://github.com/harfbuzz/harfbuzz/issues/6452
Assisted-by: OpenAI Codex

* [gen] Preserve current Rust vowel-constraint buffer access

The shared generator still emitted direct field access through
buffer.cur(), which now returns Option in HarfRust. Regenerating the
file also lost its checked access to output glyph information.

Emit the cur_glyph helper and guarded output lookup already used by
the checked-in Rust implementation. The regenerated Rust functions
match HarfRust after its import adaptations, and the C++ output is
byte-for-byte unchanged.

All 275 Meson tests pass. HarfRust's default and all-feature workspace
tests pass with the regenerated functions.

Assisted-by: OpenAI Codex

* [test] Keep Unicode 18 Indic cases in a dedicated shaping file

Group the new cases in indic-unicode18.tests so HarfRust can import
these generated tests without replacing existing Indic regressions.
Register the file in the in-house shaping suite.

All 275 Meson tests pass.

Assisted-by: OpenAI Codex

* [gen] Emit HarfRust names directly from the shared generators

Generate the Rust module paths, type names, and table symbol prefixes
used by HarfRust at their source. This removes the need for text
rewrites in HarfRust's Unicode-table makefile.

All eight Rust outputs are byte-for-byte identical to the previous
postprocessed outputs. All seven C/C++ generator outputs are
byte-for-byte unchanged, and all 275 Meson tests pass.

Assisted-by: OpenAI Codex
2026-11-01 19:14:23 -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 Esfahbod 07c411aff4 [repacker] Check visited vector resize result (#6541)
update_distances() checked the vector's error state after resize(), but
left the return value unchecked, triggering Coverity CID 506917.

Check resize() directly and return ALLOCATION_FAILURE on failure. This
preserves the existing allocation failure behavior.

Tested with meson compile -C build -j 6 and meson test -C build
(275 tests passed).

Assisted-by: OpenAI Codex
2026-11-01 13:52:56 -07:00
Behdad Esfahbod 90417543fd [aat] Match CoreText kerx format 1 history (#6540)
* [test] Probe CoreText kerx stack behavior

Add native CoreText probes for list reuse, excess values, zero values,
duplicate pushes, repeated actions, resets, and long lists. Run them on
macOS 15 and macOS latest to establish the compatibility behavior before
changing the kerx driver.

The local baseline Meson suite passes all 275 tests. Native execution
is intentionally checked by the new macOS probe jobs.

Related: https://github.com/harfbuzz/harfbuzz/pull/6538#issuecomment-6561986849
Assisted-by: OpenAI Codex

* [test] Probe retained kerx history past eight pushes

Add an end-of-text action after twenty repeated push/action entries to
distinguish retained history from an eight-entry rolling window.

The local Meson suite passes all 275 tests.

Assisted-by: OpenAI Codex

* [test] Probe kerx history wraparound and reset reuse

Add native cases around the eight-slot boundary, actions before the
first push, a first push after ignored glyphs, and history reuse after
reset. These distinguish partial-history initialization and cursor
wraparound for the CoreText compatibility implementation.

Testing: all 275 Meson tests pass with the implementation in progress.

Assisted-by: OpenAI Codex

* [test] Verify kerx reset anchors and Arabic examples in CoreText

Measure a reset followed by another action without a push, and include
both versions of the reported Arabic font. Use mapped glyphs for ignored
prefixes so font fallback cannot affect the native position comparison.

Testing: all 275 Meson tests pass with the implementation in progress.

Assisted-by: OpenAI Codex

* [test] Probe long kerx lists after resetting history

Distinguish how reset initializes unused history slots by applying a
long list after a reset with and without a push, and after every push.

Testing: all 275 Meson tests pass with the implementation in progress.

Assisted-by: OpenAI Codex

* [aat] Match CoreText kerx format 1 history

The written kerx rules describe destructive stack pops and a reset flag.
Native CoreText retains an eight-slot circular history, initializes its
unused slots to the first glyph, and ignores reset. Each action list
walks the history independently and wraps after eight values.

Use that behavior for extended kerx while retaining legacy kern rules.
Bound the longer action-list walks by the buffer operation budget and
keep fixed-size history storage. Document the spec discrepancy and add
regressions for reuse, wraparound, initial slots, reset, and both Arabic
examples, plus terminated and unterminated over-budget lists.

Testing: all 275 Meson tests pass. HB and HR match glyph identities,
character indices, positions, and final extents for all 35 native cases
on macOS 15.8.2 and 26.6.2. Both Arabic examples match their GPOS reference.

Fixes: https://github.com/harfbuzz/harfbuzz/issues/6536
Assisted-by: OpenAI Codex

* [ci] Remove exploratory CoreText kerx probe jobs

The native measurements established the compatibility behavior, which
is now covered by the normal shaping regressions in HB and HR. Keep the
manual probe, recorded results, and discrepancy documentation without
adding two native macOS jobs to every pull request.

CI and documentation only; no code or test inputs changed.

Assisted-by: OpenAI Codex

* [test] Run kerx CoreText comparisons with shaping tests

Move the native helper and reference data from .ci into test/shape.
Run the native comparison as a normal CoreText-enabled macOS Meson
shaping test, using the existing macOS CI job. Keep the discrepancy
explanation beside the regression cases and drop the standalone Markdown.

Testing: all 275 Linux Meson tests pass. The comparison runner passes
all 35 recorded cases and rejects an injected position mismatch. The
native helper is unchanged from the macOS 15.8.2 and 26.6.2 measurements.

Assisted-by: OpenAI Codex

* [test] Keep kerx regressions in the shaping suite

Remove the API C budget test, native CoreText C helper, comparison
runner, reference JSON files, and extra Meson test target. Retain the
library fix and normal shaping regressions, with a short explanation of
the native behavior in the shaping test file.

Testing: all 275 Meson tests pass.

Assisted-by: OpenAI Codex
2026-11-01 13:35:37 -07:00
Behdad Esfahbod a92e0996dc [aat] Read kerx format 1 value indices and terminators (#6538)
kerx format 1 entries contain value-array indices and terminate lists
with a separate 0xFFFF word. The shared kern/kerx driver instead treated
the indices as byte offsets and used the legacy kern low-bit terminator.

Keep the legacy kern behavior, but read kerx indices directly and stop
before popping a glyph for 0xFFFF. Validate kerx values as they are read
so a short list can terminate while glyphs remain on the stack. Mark
the dependencies of adjustments to earlier stacked glyphs unsafe to break.

Add regressions for positive and negative odd values, nonzero indices,
short lists, retained stack entries, and glyph flags. All 275 Meson
tests pass, including the shaping suite and both font callback backends.

Related: https://github.com/harfbuzz/harfbuzz/issues/6536
Assisted-by: OpenAI Codex
2026-11-01 11:52:56 -07:00
Behdad Esfahbod 29577aa640 Merge pull request #6499 from harfbuzz/scanner/ft
[ft] Fix color-stop count, immutable set_funcs crash, and cache vertical metrics
2026-11-01 10:44:17 -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 EsfahbodandEbrahim c956a11cc7 [algs] Unify ARRAY_LENGTH with compile-time type information (#6539)
* [algs] Declare ARRAY_LENGTH also constexpr so can be used in static contexts

* [algs] Remove more use of ARRAY_LENGTH_CONST

And rename it to ARRAY_LENGTH_UNCHECKED so it will be more obvious
this is the last resort.

* [bit] Avoid use of ARRAY_LENGTH_UNCHECKED

* [algs] Move ARRAY_LENGTH_UNCHECKED to its only caller

* [algs] Return size_t from ARRAY_LENGTH

* [algs] Remove last use of ARRAY_LENGTH_UNCHECKED

* [algs] Use std::extent to get template parameter array length

It makes more sense I think.

* [algs] Make ARRAY_LENGTH usable through template reference parameters

Evaluating ARRAY_LENGTH on a reference parameter is not a constant
expression in C++11. Return std::integral_constant from a function
object so callers can extract the length from the return type without
evaluating the array expression. Ordinary calls still convert to size_t.

Use this form for all three Arabic fallback ligature table dimensions,
replacing std::extent. Document both forms and add compile-time checks
for ordinary calls, string literals, and nested template array arguments.

Validated with GCC and Clang C++11 syntax checks, a full Meson build,
and meson test -C build (296 passed, 1 skipped).

Assisted-by: OpenAI Codex

---------

Co-authored-by: Ebrahim <ebrahim@gnu.org>
2026-11-01 09:48:25 -07:00
Khaled Hosny 436f067b20 Merge pull request #6537 from harfbuzz/issue-6535
[aat] Apply kerx format 4 cross-direction mark offsets immediately
2026-11-01 09:28:05 -07: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