mirror of
https://github.com/storytold/harfbuzz.git
synced 2026-11-29 09:34:05 +01:00
cd570b6f544c498d02515ef2d5f3d4b2c31f86ee
17224
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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> |
||
|
|
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>
|
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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 |
||
|
|
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> |
||
|
|
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> |
||
|
|
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 |
||
|
|
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 |
||
|
|
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> |
||
|
|
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> |
||
|
|
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 |
||
|
|
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> |
||
|
|
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 |
||
|
|
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 |
||
|
|
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 |
||
|
|
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 |
||
|
|
29577aa640 |
Merge pull request #6499 from harfbuzz/scanner/ft
[ft] Fix color-stop count, immutable set_funcs crash, and cache vertical metrics |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
436f067b20 |
Merge pull request #6537 from harfbuzz/issue-6535
[aat] Apply kerx format 4 cross-direction mark offsets immediately |
||
|
|
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> |
||
|
|
a3ad47c776 |
[ft] Report zero color stops when skipping to start fails
hb_color_line_get_color_stops() defines *count as in/out: capacity on entry, number of stops written on exit. The skip-to-start early return added in #6121 (to avoid an infinite loop when FT_Get_Colorline_Stops() refuses a stop) writes no stops but left *count untouched, so an embedder paging a malformed ColorLine with start > 0 reads uninitialized hb_color_stop_t entries and draws the gradient from its own buffer. Set *count = 0 on that exit, matching the start >= num_color_stops exit a few lines above and the hb-ot ColorLine::get_color_stops(). Well-formed fonts are unaffected; no API/ABI change. Adds test_color_stops_short_ft with a generated 392-byte font whose ColorLine declares one more stop than it holds. Reported by Anthropic's OSS Scanner as ordinary bug ANT-2026-O5RJ72EZ. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
b05c7266d6 |
Merge pull request #6504 from harfbuzz/scanner/glyf
[glyf] Fix phantom-only advance bugs and bound glyf memory/subsetting work |
||
|
|
7939d2f295 |
Merge pull request #6511 from harfbuzz/scanner/misc
[core] Fix four OSS-scanner findings: map UAF, NULL out-params, qsort DoS, shape-plan limits |
||
|
|
7b7e4ef3d1 |
[glyf] Guard phantom-shift subarray against OOM underflow
In phantom_only mode the horizontal shift walks all_points.sub_array (all_points.length - PHANTOM_COUNT). If the preceding extend (phantoms) failed under memory pressure, all_points can be shorter than PHANTOM_COUNT, so the subtraction wraps and the code forms an out-of-range pointer (UB flagged by UBSan under the failing-malloc fuzzers) even though sub_array clamps the count to 0 and the in-error result is discarded. Fall back to offset 0 when the phantoms are not present. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
fc302bdfe5 |
[subset] Share one work budget across all glyphs when instancing glyf
hb-limits.hh states that a session which drives another subsystem carries one cumulative budget, initialized once per top-level entry and only ever decremented. When instancing, glyf::subset() drives Glyph::get_points() once per retained glyph to recompute bounds and metrics, but passed no budget, so each glyph restarted from a fresh HB_BUDGET_GLYPH and the table as a whole was bounded only by 2^24 times the glyph count. A 59 KB font of 2,000 nested composites over a shared 64-level chain made one hb_subset_or_fail() instancing call spend 34 s of CPU, since the shared chain was re-walked (and re-charged only against a fresh budget) for every top-level glyph. Add HB_BUDGET_SUBSET_GLYF and keep the live counter in hb_subset_context_t, which is constructed once and reused across the ran-out-of-room retries in _hb_subset_table_try(), so a retry does not reset it. Thread it through _populate_subset_glyphs() and both compile_bytes_with_deltas() into get_points(). Exhausting it fails get_points(), which the existing loop already turns into dropping glyf from the instance -- the same outcome as any other glyph-load failure there. This is one cumulative counter, not a per-glyph budget multiplied by the glyph count. It is sized at 2^28; measured consumption of the largest glyf variable font under test/ (MPLUS1-Variable) is ~1.2M units, about 220x below the cap, and even a font at the 65,535-glyph maximum stays well under, so real fonts instance unchanged (outputs byte-identical). One behaviour change: a single glyph is now bounded by what is left of the table budget rather than by HB_BUDGET_GLYPH, so one glyph may spend between 2^24 and 2^28 units; the session total is still bounded. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-5BY15VDS. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
be8103f334 |
[subset] Bound the glyf bytes a plan may retain through an aliasing loca
glyf::subset() trims (and, with --no-hinting, walks the components of) every retained glyph on every serializer retry. The only thing bounding that work was the implicit assumption that loca is monotonic, so the retained ranges sum to at most the table. loca need not be monotonic, so any number of glyph IDs can alias the same bytes, and the work grows as glyph count times glyph size times retries: a 328 KB font with loca = 0, L, 0, L, ... makes hb-subset spend ~22 s of CPU and then fail, where a same-sized monotonic font takes 0.02 s. The glyph closure in _populate_gids_to_retain() already fetches each retained glyph exactly once, before any table is subset, so charge the untrimmed length there (before the composite operation count can bail out, so every glyph added to the set is paid for) against a budget of HB_SUBSET_GLYF_MAX_BYTES_FACTOR (16) times the glyf length, and fail the plan when it is exceeded. This also makes hb_subset_preprocess() fall back to the source face cheaply. Fonts with a monotonic loca never exceed a factor of one, so their output is unchanged; the one behaviour change is that a specification-violating loca that aliases large glyph bytes more than sixteen tables' worth is now rejected instead of subsetting slowly. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-S5U7MYJ7. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
220ef2ca34 |
[glyf] Restore scratch length when gvar fails in get_points; clear comp_points at entry
Glyph::get_points() uses scratch.comp_points as a stack shared by all recursion levels: it appends one point per component plus four phantoms, and every exit restores points.length to old_length -- except the exit taken when gvar->apply_deltas_to_points() returns false (for example on a tuple whose variationDataSize overruns its data). Because the hb_glyf_scratch_t is cached on the glyf (and VARC) accelerator for the life of the face, every failed depth-0 load grows the vector permanently, until it reaches its allocation ceiling; a VARC font can drive hundreds of thousands of such failing leaf loads within one glyph budget, leaving tens of megabytes behind per extents or draw call. Balance the missing exit the way every sibling exit (and #6410) already does. Also clear comp_points next to the existing all_points.clear() at the depth-0 entry in glyf_accelerator_t::get_points(), the only entry into the cached scratch (the subsetter's call uses a local scratch), so the cached vector can never carry stale points across loads even if a future exit forgets the discipline. No behaviour change for well-formed fonts: the resize only runs on the failure path and comp_points is empty at entry when exits are balanced. Adds a minimized VARC+gvar font to test/fuzzing/fonts exercising the failing path through the shape/draw/raster/vector/subset fuzzers. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-NM4GCMBX. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
c5d3fdda16 |
[glyf] In phantom-only get_points, descend only into the last USE_MY_METRICS component
Glyph::get_points(phantom_only=true) is the path hb-ot-font uses for advances and vertical origins of a gvar font without HVAR/VVAR. It recursed into every USE_MY_METRICS component although each one overwrites the phantoms copied from the previous one, so only the last surviving one can influence the result; a composite that sets the flag on many components could thus cost nearly a whole HB_BUDGET_GLYPH per advance lookup, and a small font could reach the same per-character cost that previously needed a megabyte-sized one. Add a cheap pre-pass over the component records (bounded by the same count the offset-collecting loop already charges) that picks the last flagged component the decycler would accept, and descend only into it. Components that are not descended into now continue before the post-child bookkeeping; this also removes a latent wrong-advance bug where the unconditional all_points.resize (length - PHANTOM_COUNT) for a skipped component ate entries pushed by earlier siblings, making the parent's phantom copy read out of range and return advance 0. Non-phantom-only traversal (drawing, extents, subsetting) is unchanged: copy_metrics reduces to the old condition and the new continue is never taken. The one behavioural difference in phantom-only mode is that a traversal failure (nesting, edge count, budget) inside a flagged subtree that is no longer visited no longer fails the whole lookup. Reported by Anthropic's OSS Scanner as ordinary bug ANT-2026-DQGMHCLX. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
0155687e9a |
[glyf] Don't transform/keep unloaded component points in phantom_only get_points
In phantom_only mode SimpleGlyph::get_contour_points() reserves a glyph's
declared point count (gvar needs the count to locate the phantoms) but never
loads the points. The composite branch of Glyph::get_points() wrongly assumed
the component's point array is then empty ("Empty in case of phantom_only"):
for a USE_MY_METRICS child it transformed all the reserved points and, after
removing only the four phantoms, left them in all_points to be transformed
again at each enclosing level (up to 64 deep) and counted against
HB_GLYF_MAX_POINTS.
Once the child's phantoms have been copied, skip the transform and shrink
all_points back to old_count in phantom_only mode; the top-level lsb shift
likewise only touches the phantoms in that mode so a simple glyph's reserved
points are not walked either. Output is unchanged (phantoms are copied before
the transform in both modes). The one behavioural change is that advance
lookups no longer fail spuriously when components' unloaded point counts exceed
HB_GLYF_MAX_POINTS (four USE_MY_METRICS copies of a 65536-point glyph now give
the hmtx advance 600 rather than the upem/2 fallback).
Reported by Anthropic's OSS Scanner as ordinary bug ANT-2026-0NDQUVPX.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
5e84cf30bb |
[COLR] Harden COLR subsetting, instancing and paint against DoS findings (#6508)
* [subset] Clamp PaintColrLayers layer range to LayerList in COLRv1 closure PaintColrLayers::closurev1() recorded firstLayerIndex .. firstLayerIndex + numLayers - 1 as retained layers without checking the range against LayerList.len (PaintColrLayers::sanitize is a plain check_struct), and _colr_closure() then creates one colrv1_layers map entry per retained index. A crafted font whose leaf paints point past the end of the LayerList could therefore add up to 255 entries each for layers that do not exist, driving subset-plan memory to roughly 1200x the font size (585 MiB for a 512 KB font). Clamp the range to the LayerList at the one place the retained-layer set is built, before add_layer_indices() and for the dispatch loop alike; this also removes the firstLayerIndex + numLayers wrap-around in the loop bound. Readers (paint_glyph, dependv1) never record indices and already tolerate out-of-range ones via LayerList::get_paint() returning Null, so they are left alone. A PaintColrLayers whose range lies past the source LayerList now has no mapping and subset writes 0xFFFFFFFF; both that and a renumbered index past the new LayerList are out of range and draw nothing. Adds a regression test that builds such a font inline and pins the output; it fails without the fix. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-ROQFK0RA. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * [subset] Bound shared COLRv0 layer expansion and make V0 closures linear COLR::subset() gives every retained COLRv0 base glyph a private copy of its layer range, so N base glyphs sharing L layers cost N x L layer copies with two hash lookups each, and nothing checked the total against the 16-bit numLayers header field. serialize_V0() walks the lazy iterator twice and _hb_subset_table_try() retries while doubling the buffer, so a ~200 KB font with all records naming the same range kept hb-subset busy for about two minutes before failing. Cap the summed layer count with a cheap walk over base_it before layer_it is built, and drop COLR (return_trace (false)) when the total exceeds 0xFFFF, the same way this function already handles V0 records it cannot subset; this also removes the 16-bit wrap in serialize_V0(). Any total above 65535 could only have produced a failed subset or a wrapped, invalid numLayers, so no valid output is lost. The two V0 closure helpers had the same N x L shape during planning; collect the layer indices of all retained base glyphs into one set first and visit each layer once. closure_glyphs() now takes the glyph set in one call (the accelerator wrapper changes signature with it; no public API change), and _colr_closure() passes the whole set instead of looping. Adds test_subset_colr_shared_layers (256 base glyphs all claiming the same 256 layers): retaining 255 gives a 65280-layer table, retaining all 256 gives an empty COLR. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-4T7NHCTK. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * [subset] Look up each retained glyph's ClipRecord by bsearch in ClipList::subset ClipList::subset() walked startGlyphID..endGlyphID of every ClipRecord, which is only O(num_glyphs) overall when the records are sorted and disjoint. ClipList::sanitize() checks neither, so R overlapping records each spanning all glyphs cost R x 65535 iterations: a 332 KB font with 10000 whole-range records took about 20 s of CPU in hb-subset whatever glyphs or text the request asked for. Invert the loop: iterate the retained glyph set once and find each glyph's record with clips.as_array ().bsearch (gid), exactly how ClipList::get_extents() resolves a glyph's clip box when rendering, and the same shape as the COLRv0 path in COLR::subset(). Cost is now O(|glyphset| log R) regardless of record overlap. For well-formed (sorted, disjoint) lists the output is unchanged; for malformed overlapping/unsorted lists the chosen record can differ (bsearch instead of last-record-wins), which makes the subset agree with the clip box HarfBuzz itself renders from the source font. Adds an extended-format hb-subset-fuzzer input (5000 records covering all 65535 glyphs) that the subset-fuzzer tests pick up. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-MRSCGMJ7. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * [subset] Compute COLR constant_after_pinning once per plan PaintRadialGradient::constant_after_pinning() answers a question about the source ItemVariationStore and the subset plan only, yet it rescanned every variation region (building a hashmap per region, up to 32767) on every paint visit. Shared paints are visited once per reference by OffsetTo::serialize_subset(), so during partial instancing the cost grew as visits x regionCount: 40 s to 6 minutes for a 192 KB font with a PaintComposite chain and many regions. Cache the answer in a tri-state plan field (-1 until computed, like the lazily-set has_gdef_varstore flag) so the scan runs at most once per plan; the plan is valid for one source face and one set of axis locations, so this is sound. Move the cheap varIdxBase != NO_VARIATION test ahead of the scan so non-variable format 6 gradients never trigger it. The allocation-failure path of get_var_region() still sets the serializer error and returns uncached, as before. Output is byte-identical; the attack font drops from ~41 s to ~0.03 s. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-910I4C0Y. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * [COLR] Charge gradient color stops to the paint session work budget The COLRv1 paint walk bounds paint-table visits (HB_MAX_NESTING_LEVEL, HB_MAX_GRAPH_EDGE_COUNT) but handed out ColorLine stops uncharged, so a single 65535-stop ColorLine shared across up to 16384 gradient edges could deliver ~10^9 stops from one hb_font_paint_glyph() call, keeping the rendering thread busy for minutes per glyph in every backend. Give hb_paint_context_t the session's live budget via funcs->get_budget_remaining_ptr(), with the same local HB_BUDGET_GLYPH fallback hb_draw_session_t uses, charge HB_BUDGET_16 per stop delivered in ColorLine::get_color_stops() (the one place every consumer fetches stops, so vector, raster, cairo and client paint functions are all covered), and make recurse() skip further paints once the budget is negative, as it already does for an oversized graph. The backend's one budget is only spent, never re-armed, so this does not reintroduce the cross-subsystem budget multiplication removed in #6147. hb-ft-colr.hh has the same shape and gets the identical change. With the default 2^24 budget about a million stops per session are delivered before the rest of the walk is skipped best-effort. A separate quadratic cost inside cairo's own gradient pattern building is not addressed here. Adds a regression test that fails without the fix. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-F2NWHRVP. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * [paint] Clip sweep-gradient tiles to 0..2π in hb_paint_sweep_gradient_tiles hb_paint_sweep_gradient_tiles() documents that it iterates the 0..2π sweep, and all three consumers (hb-cairo mesh patches, the SVG and PDF writers) size their per-tile loops by tile width on that assumption. Several emit sites (the start==end PAD case, the first PAD stop past 0, and repeat/reflect segments straddling 0 or 2π) passed the angles straight through, and COLRv1 variation deltas can place them hundreds of thousands of radians outside the circle, so one tile could expand to millions of patches: a 504-byte variable font drawn off its default allocated ~1.6 GiB through hb-cairo. #6157 bounded the number of sweep tiles; this bounds the width of each one. Route every emit through a small clipping lambda inside the tiler that clamps the tile to [0, 2π], lerps the end colours at the clip points, and drops tiles entirely outside, so the contract holds at the single place it is established rather than in each backend. HB_PAINT_MAX_SWEEP_TILES and the repeat-loop bounds are untouched; external callers need no change. Adds a regression test calling the public function with far-out angles for PAD/REPEAT/REFLECT; it fails without the fix. Follow-up to #6157. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-GCNW3SND. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * [depend] Bound COLR dependency extraction with a shared op budget COLR::depend() walked the COLRv1 paint graph from scratch for every BaseGlyphPaintRecord (clearing the visited set each time) with no total work limit, so N base glyphs sharing one paint graph cost N times the graph, quadratic in table size (204 s for a 200 KB font); the COLRv0 loop has the same base-glyphs x layers shape. The API is built only with -Dexperimental_api=true. hb_colrv1_depend_context_t, which already owns the per-walk depth and visited-set guards, now also carries max_ops sized like the sanitizer's (table length x HB_SANITIZE_MAX_OPS_FACTOR, clamped to the MIN/MAX), charged one unit per Paint::dispatch(), per COLRv0 layer record, and per PaintColrLayers layer run. Charging the layer run in dependv1() matters because a layer resolving to the null or an unknown-format paint is dropped by Paint::dispatch() before it reaches the context, so without it a PaintColrLayers could still spin its 255-iteration loop uncharged. Exhausting the budget calls depend_data->fail() (the existing error idiom) so hb_subset_depend_from_face_or_fail() returns NULL rather than a graph with silently missing edges, and the base-glyph loop stops once the builder has failed. The reproducer font is now rejected in a fraction of a second; the control still succeeds, and legitimate fonts keep 64 ops per table byte of headroom. Adds test_depend_colr_budget. Follow-up to #6113. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-TO8ND880. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * [ft] Drop the dead color-stop iterator resets Since the color line is copied locally ("Keep iteration local"), the iteration advances cl->color_stop_iterator on that local copy, which is discarded when the function returns. The two "reset the iterator for next time" writes (cl->color_stop_iterator = iter) therefore have no effect: there is no persistent iterator state to restore, and positioning across calls is driven entirely by the start argument. Remove both dead writes and the now-unused saved iterator. No behavior change; the return value (num_color_stops) is unaffected by iteration. Full test suite passes (277/277). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
e8a578bf07 |
[build] Avoid libstdc++ assertions in unoptimized builds (#6534)
* [build] Avoid libstdc++ assertions in unoptimized builds Recent libstdc++ headers enable assertions at -O0. Atomic operations then reference std::__glibcxx_assert_fail, which is unavailable when HarfBuzz uses the C linker without libstdc++. Define _GLIBCXX_NO_ASSERTIONS in Meson and CMake builds. Undefine _GLIBCXX_ASSERTIONS in Meson as well, since Meson enables it for debug builds. Verified Clang 21.1.8 with libstdc++ 15.3.1 debug shared-library builds in both build systems, using --no-undefined with CMake. Confirmed that harfbuzz and harfbuzz-gpu have no assertion reference or libstdc++ dependency. The full Meson suite passed: 295 tests, one skipped. Fixes: https://github.com/harfbuzz/harfbuzz/issues/6528 Assisted-by: Codex * [build] Configure libstdc++ assertions in hb.hh Move the assertion settings from Meson and CMake to the internal header so custom builds and amalgamations also avoid the runtime dependency. The settings must precede the first C++ standard header. hb-atomic.hh is included after other standard headers, so set them at the top of hb.hh instead. Verified Clang debug shared-library builds with Meson and CMake, plus a direct -O0 build of harfbuzz.cc with pthread mutexes and assertions explicitly enabled on the command line. All link without libstdc++ and have no assertion reference. The GCC atomic repro also passes. The full Meson suite passed: 295 tests, one skipped. Assisted-by: Codex * [test] Keep vector string operations instrumented under MSan Including hb.hh first disables libstdc++ assertions and restores its extern template declarations for std::string. The vector test then calls the uninstrumented copy constructor from libstdc++, and MSan reports uninitialized state when moving the temporary copy. Include string before hb.hh so the test retains the inline string implementations that MSan can instrument. Reproduced with Clang 18 and libstdc++ 14 using CI's assertion flags. The original test fails and the updated test passes under MSan. The full regular Meson suite passed: 295 tests, one skipped. Assisted-by: Codex |
||
|
|
4d2b4125b4 |
[ft] Drop the dead color-stop iterator resets
Since the color line is copied locally ("Keep iteration local"), the
iteration advances cl->color_stop_iterator on that local copy, which is
discarded when the function returns. The two "reset the iterator for next
time" writes (cl->color_stop_iterator = iter) therefore have no effect:
there is no persistent iterator state to restore, and positioning across
calls is driven entirely by the start argument.
Remove both dead writes and the now-unused saved iterator. No behavior
change; the return value (num_color_stops) is unaffected by iteration.
Full test suite passes (277/277).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
0ba555a3d4 |
[cairo] Clear the path before the rectangle clip (#6530)
hb_cairo_push_clip_rectangle() appended its rectangle to whatever path was already on the cairo_t, where the sibling clip callbacks (hb_cairo_push_clip_glyph, hb_cairo_push_clip_path_start) all start with cairo_new_path(). This became reachable once compositing operations were gated on the work budget: hb_cairo_fill_glyph() now only runs cairo_fill() when spend_paint() succeeds, so a budget-skipped fill leaves the glyph outline on the context unconsumed. cairo's current path is not part of the graphics state, so the enclosing cairo_save()/cairo_restore() does not clear it; the leftover outline survives into the next push_clip_rectangle(), and cairo_rectangle() then adds the clip box to that outline instead of to an empty path, clipping to their union. Call cairo_new_path() first, matching the other clip callbacks, so the rectangle clip is always exactly the requested box. Full test suite passes (277/277). Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
7fde83a7e0 |
[number] Fix two more edge cases (#6529)
* [number] Minor rename * [number] Make zero mantissa with large exponent to return 0, not nan * [number] More percise keeping track of fraction |
||
|
|
07bc8effbb |
Merge pull request #6515 from harfbuzz/scanner/gpu
[gpu] Fix clip-pop imbalance and bound cu2qu / per-layer shader work |
||
|
|
799f1cd721 |
Merge pull request #6516 from harfbuzz/scanner/graphite
[graphite2/shaper] Fix uninitialized mask, missing positions, and repeated failed-face loads |
||
|
|
44b64b061a |
Merge pull request #6501 from harfbuzz/scanner/shaper
[buffer/layout] Fix empty-buffer mutation and two shaping-time CPU DoS findings |
||
|
|
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> |
||
|
|
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>
|
||
|
|
786fddc088 |
Merge pull request #6503 from harfbuzz/scanner/subsetmisc
[subset/face-builder] Fix parser, leak, and DoS issues found by OSS Scanner |
||
|
|
8896ade249 |
Merge pull request #6500 from harfbuzz/scanner/cbdt-sbix
[sbix,CBDT] Bound per-glyph strike/record scans and CBDT subset image copies |
||
|
|
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> |
||
|
|
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> |