mirror of
https://github.com/storytold/harfbuzz.git
synced 2026-11-19 05:51:05 +01:00
main
1238
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
e563058688 |
[font] Add hb_font_create_without_funcs_or_fail() (#6651)
Let clients install their own font funcs without initializing and immediately discarding the default backend. Return NULL if the font object or its initial variation coordinates cannot be allocated. Keep hb_font_create()'s initialization order and behavior. Use the new constructor in hb-ft, Fontconfig, explicit tool backend selection, and the font benchmarks. This avoids loading a second FT_Face when FreeType is the default while preserving the caller's face. Document the custom-client use case and add API and stream-read regressions. Testing: full Meson suite (302 passed, one skipped), generated docs, reduced-feature builds, allocator failures, and tool/benchmark checks. Supersedes: https://github.com/harfbuzz/harfbuzz/pull/6648 Assisted-by: OpenAI Codex Co-authored-by: Mattias Eriksson <me@axentia.se> |
||
|
|
136b04439b |
Merge pull request #6656 from harfbuzz/fix/raster-bgra-endianness-6655
[raster] Preserve BGRA byte order on big-endian systems |
||
|
|
f87e9d774c |
[gvar] Charge tuple region eval and point-number decoding to work budget (#6654)
apply_deltas_to_points() only charged the glyph work budget (HB_BUDGET_GLYPH) for tuple variations that actually applied, and only by the glyph's point count, after calculate_scalar() had already walked gvar.axisCount axes for every tuple header. A ~35 KB font with axisCount 8192 and 4095 non-applying tuples on a composite-multiplied glyph could hold one hb_font_get_glyph_extents() call for over a minute while using ~3% of the budget. Two further pieces of work were also uncharged: the shared point-number list is decoded on every glyph load, and an applied tuple decodes/applies indices.length deltas, which can exceed the point count charged. Following the project's "charge before doing the work" idiom (#6256, #6410), charge 1 + axisCount per tuple before its region is evaluated (bounding calculate_scalar() regardless of the scalar cache or outcome), shared_indices.length once per load after the shared point numbers are decoded, and indices.length per applied tuple before its deltas are decoded. A font whose tuple work exceeds the budget now fails the glyph load (outline/extents return false) instead of finishing slowly; real fonts (a dozen axes, tens of tuples) pay a few hundred units per load. Adds test_hb_draw_gvar_budget to test/api/test-draw.c covering both the unapplied-tuple region charge and the point-number charges. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-S2OJWJHX. Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
aa7a824cc4 |
[JSTF] Expose extender glyphs via hb_ot_layout_get_extender_glyphs (#6568)
* [JSTF] Expose extender glyphs via hb_ot_layout_get_extender_glyphs The JSTF table is already parsed but never exposed to clients. Extender glyphs are the most widely populated part of it and are useful for cursive-script justification implementations that want to prefer a font-provided extender over the plain U+0640 TATWEEL fallback. Adds hb_ot_layout_get_extender_glyphs(face, script, language, start_offset, &count, glyphs) following the standard iterator idiom used by hb_ot_layout_get_attach_points and friends: NULL for size probing, inout count for pagination. Only the script tag is consulted: per the OT spec, extender glyphs live directly on JstfScript and do not vary by language. JstfLangSys carries per-language justification priorities, but exposing those is both harder and less common among fonts than the (already rare) JSTF table itself; that can be a separate accessor later. Co-authored-by: Helmut Januschka <helmut@januschka.com> * [JSTF] Minor simplification by refactoring exposed methods --------- Co-authored-by: Helmut Januschka <helmut@januschka.com> Co-authored-by: Behdad Esfahbod <behdad@behdad.org> |
||
|
|
5ee557a991 |
[subset] Bound avar2 offset-compensation (binary search instead of quadratic) (#6642)
* [subset] Bound avar2 offset-compensation's quadratic breakpoint work avar::_subset_avar2() builds the offset-compensation knots and runs _avar2_estimate_offset_error() twice per narrowed axis; every breakpoint and every estimator sample is looked up in the old segment map, the instantiated mapping and the knots by linear search, so the cost is quadratic in the axis's avar breakpoints and nothing bounded it (42 s of CPU for a 131 KB font, re-run on each serializer out-of-room retry). Add HB_BUDGET_SUBSET_TABLE to hb-limits.hh (same hb_budget_spend() idiom as the rendering budgets) and, right before the knot loop and the estimator, charge (256 + breakpoints) * 8 * breakpoints from a budget shared by all axes of the table. Charging at the point where the quadratic work starts covers the O(n^2) knot-collection loop and its map_float() calls too. On exhaustion the table fails through c->serializer->check_success(), so the whole subset fails (hb_subset_or_fail() returns NULL) rather than avar being silently dropped from an avar2-instanced font. The budget is 1<<30: a 5,000-breakpoint axis narrowed to -900:900 is still admitted (0.6 s), while 16,385 and 32,769 breakpoints are rejected in 0.01 s (the 42 s DoS). A reviewer may tighten it; real avar maps have a handful of breakpoints, far below the cap. Adds test_avar2_restrict_many_breakpoints to test/api/test-subset-avar2.c. This caps the cost; it does not remove the quadratic algorithm. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-CWJXX1BL. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * [subset] Bound avar2 offset-compensation tuple memory to the table size avar::_subset_avar2() adds one item_variations_t tuple per retained avar v1 breakpoint and per biased axis, and add_tuple() stores each as a dense column with one bool and one float per row of the VarData it joins. VarData.itemCount can be 65535 with zero-width rows (a 6-byte VarData with no regions passes sanitize), so breakpoints x rows x 5 bytes is not bounded by the font: a 20 KB font drove hb-subset to 2.8 GB, and add_tuple() silently dropped the failed allocation so the result still exited 0. Charge each tuple's item_count deltas to a budget before the add_tuple() call, at all three avar2 sites (empty-region bias, knot tents, free-axis bias), with the existing hb_budget_spend() idiom. The budget is max(HB_AVAR2_MAX_DELTAS_MIN, HB_AVAR2_MAX_DELTAS_FACTOR x table length) -- 128 deltas per byte, floor 65536, new macros in hb-limits.hh next to the other table-derived limits. Exhaustion fails the subset through c->serializer->check_success(false) rather than dropping avar. The attack font is now rejected with a 19 MB peak instead of 2.8 GB; valid fonts (a few deltas per byte) stay far below the budget. Adds test_avar2_empty_rows to test/api/test-subset-avar2.c: 513 breakpoints (which clear the quadratic estimate budget) with a 65535-row region-less VarData, so the delta budget is what rejects it. The charge is placed in the caller; the sibling improvement of making add_tuple() return failure instead of swallowing the dropped allocation lives in hb-ot-var-common.hh and is left for that file's own change. The as_item_varstore() rows x regions allocation and duplicate_row() remain uncovered, as in the report. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-3HO8JDDV. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * [subset] Binary-search avar2 offset compensation instead of budgeting it Offset compensation looked every breakpoint and estimator sample up in the old segment map, the instantiated mapping and the knots by linear search, and inserted each breakpoint knot by shifting, so its cost was quadratic in the axis's breakpoints. The previous commit capped that with HB_BUDGET_SUBSET_TABLE; remove the quadratic work instead: - SegmentMaps::map_float() takes a sorted flag; for maps whose fromCoords ascend it finds the exact-match run and the segment by binary search, which lands where the linear scans do. - The instantiated mapping is sorted by fromCoord, and the knots by z, so _avar2_map_new_mapping() and _avar2_eval_offset() binary-search. - The estimator pulls the ascending knots back through the mapping with one forward scan over its toCoords. - Breakpoint knots are pushed and then sorted, keeping the first of equal z as _avar2_add_knot() did. An old segment map with fromCoords out of order, which the spec forbids, would still need a linear scan per lookup; for such an axis keep the {-1, 0, +1, z_old} anchors and skip the estimate. Remove HB_BUDGET_SUBSET_TABLE, now unused. test_avar2_restrict_many_breakpoints now expects the 32,769-breakpoint axis to instance, and to match, rather than fail; the whole test runs in 0.2 s. 65,000-breakpoint maps instance in under 0.25 s. Outputs are byte-identical to before for every test-subset-avar2 instance and for 317 random avar2 maps (sorted, with duplicate fromCoords, and with non-monotone toCoords) on random ranges; only maps with unsorted fromCoords differ. Tested: meson test -C build (277/277 OK). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * [subset] Reuse the one bsearch loop for avar2 instead of a new one The avar2 offset-compensation searches went through a hand-rolled _avar_partition_point loop -- a second binary search living next to hb_bsearch_impl. Route them through hb_bsearch_impl instead, with comparators that never return 0 so it reports the insertion position (a lower or upper bound, per the comparator) rather than a match. No behavior change: the full test suite passes and the CWJXX1BL and 3HO8JDDV reproducers stay bounded (0.13 s CPU and 21 MB peak, the table failing cleanly), same as before. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
420bb6d0ba |
[subset/cff] Bound hint-drop/closure walks and share the budget across the whole subset (#6638)
* [subset] Bound the CFF hint-dropping and closure walks drop_hints_in_str()/drop_hints_in_subr() and the closure walk (collect_subr_refs_in_str/_in_subr) recursively walk the subroutine calls recorded for each glyph with no depth limit and no work budget. The records need not match what the interpreter executed: a string is parsed on its first run only, global subr records are shared across Font DICTs whose local subrs differ, and endchar does not end a walk. So the recorded call graph can nest deeper than kMaxCallLimit or be cyclic, and a binary-tree subr structure makes the hint-dropping walk expand exponentially. A 360-byte CID font crashed the subsetter with a stack overflow under --no-hinting (or hb_subset_preprocess), and a ~1 KB font ran unboundedly. PR #6428 rejected stack-supplied call operands but added no depth, cycle or work limit to these walks, so these fonts were still affected. Hold both walks to the interpreter's call-depth limit (kMaxCallLimit), which stops the cycle and the long chain before the stack runs out, and charge the hint-dropping walk to the subsetting pass budget introduced for the shared-subroutine work, so the exponential expansion is capped too. A walk that follows the interpreter's path stays within both, so only fonts whose records diverge from their execution are affected; over either limit the subset fails, as other CFF planning failures do. Adds test_subset_cff1_subr_loop, which subsets the 360-byte cycle font with --no-hinting and only requires that hb_subset_or_fail() returns. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-BCC7WHCA. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * [subset] Stop CFF subr walks at the call-depth limit instead of failing The hint-dropping and subr-closure walks enforce kMaxCallLimit themselves, because the recorded call graph can nest deeper than the interpreter allows or be cyclic. Hitting the limit failed the whole subset, and the hint-dropping walk signalled it by writing -1 into the shared work budget, conflating "too deep" with "out of budget" and clobbering the budget for later passes. Make both walks best-effort at the limit: the closure walk keeps the subr it reached but does not walk into it, and the hint-dropping walk does not walk into the subr and keeps the call and its hints. Only running out of the work budget fails the subset now, so drop_hints_param_t no longer needs set_error() and the budget is only ever touched by hb_budget_spend(). Walks that follow the interpreter's path never reach the limit, so real fonts are unaffected; for fonts whose records diverge the output may keep a few hints or call a subr whose callees were not retained, but no longer fails. test_subset_cff1_subr_loop now also asserts that the subset succeeds; it failed before this change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * [subset] Share one CFF charstring budget across a whole subset Each CFF / CFF2 charstring pass of the subsetter (seac closure, CFF2 extents for instancing, CFF2 usage and instancing passes, subroutine subsetting with hint dropping, and flattening) created its own budget with CFF::get_subset_budget(), so one subset could spend that budget several times over, and the two CFF2 instancing passes reset it between them. Keep the budget on hb_subset_plan_t instead: cff_budget() sizes it on first use from the table, as before, and every pass draws on the same counter, so the total work of one subset is bounded once. Retries of a table with a larger serialize buffer draw on it too. cff1 depend() is not part of a subset plan and keeps its own budget per call. Real fonts use about 1.5 operations per table byte per pass, against a budget of 32 per byte (at least 2^24). Tested: full meson test and the subset suite; hb-subset on SourceSerif4Variable-Roman.otf (CFF2), Roboto-Regular.otf (CFF), NotoSansCJKhk-VF.otf (30 MB CFF2) with --gids='*' and --unicodes='*', with and without --no-hinting, --desubroutinize and partial / full instancing, and on every .otf in /Library/Fonts with --gids='*', all succeed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * [subset] Detect CFF charstring budget exhaustion at zero, not below The shared CFF charstring budget is only ever spent through the cs_interpreter_t interpret() cap, which clamps each glyph's operator count to the remaining budget and charges back exactly what it consumed. By construction it never overshoots, so an exhausted budget lands at exactly 0 rather than going negative. The exhaustion checks therefore compare budget <= 0 (cff1 depend()'s seac walk) and budget > 0 (the subset planner's seac-closure and CFF2 get_extents verdicts), not < 0 / >= 0, which that path can never reach. With < 0, cff1 depend() never failed, so hb_subset_depend_from_face_or_fail() returned a result for an adversarial font that exhausts the budget even though the equivalent subset fails; that is the test-subset-cff1 shared-subrs case on CI builds with -Dexperimental_api=true. Document this at each check. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
41a2880106 |
[CFF2] Charge blend region-scalar and default-value evaluation to the budget (#6637)
* [CFF2] Charge blend region-scalar evaluation to the work budget cff2_cs_interp_env_t::process_blend() evaluates one VarRegionList scalar per entry of the VarData's region indices (up to 65535, each walking up to axisCount axes) the first time a charstring hits `blend`, but the only budget charge for blend is the operand-proportional one in cff2_cs_opset_t::process_blend(), which runs afterwards and is skipped when the operand check fails. So `1 blend` did regionIndexCount x axisCount scalar evaluations for one budget unit, and a VARC fan-out re-ran it tens of thousands of times within 2% of HB_BUDGET_GLYPH. Charge region_count x max(1, axisCount) through the env's existing spend_budget() right before resizing and filling the scalars vector, matching how VARC charges values x coords for its own ItemVariationStore evaluations; a failed charge errors the interpreter exactly as a failed resize does. spend_budget() is a no-op without a budget, so the subsetter and instancer paths are unchanged, and seen_blend gates the work to once per charstring run. Adds test_hb_draw_cff2_blend_region_budget: a CFF2 charstring blending one value over 256 region indices of a 16-axis region list must consume at least 256 x 16 units and fail under a 2048-unit budget. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-WSM91D3G. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * [CFF2] Charge the blend default values to the work budget cff2_cs_opset_t::process_blend() walks all (k+1)*n values of a blend (n default values plus k deltas each) but charged only the k*n deltas, total - n. With a VarData of regionIndexCount 0 (or no variation store) k is 0, so `n blend` charges nothing, pops nothing, and the same operands can be blended again and again for the price of two tokens. Charge `total` = (k+1)*n, exactly what the loop touches. spend_budget() is a no-op without a caller budget, so only budgeted callers (draw, extents, paint, shape, and the subsetter passes that now pass a budget) are affected, and a well-formed charstring pays one extra unit per blended value. Adds test_hb_draw_cff2_blend_budget: a charstring that pushes 100 numbers and blends them 100 times over a region-less VarData must consume at least 100 x 100 units and fail under a 5000-unit budget. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-0DAQUESS. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
6aa278829e |
[subset] Charge gvar avar2 culling pass to the source table size (#6641)
In a well-formed gvar the per-glyph data ranges [offset[i], offset[i+1]) are disjoint, so the retained glyphs' data add up to at most the table. gvar::subset()'s avar2 culling pass used the offsets as they are, so malformed offsets (0, D, 0, D, ...) could point thousands of glyphs at one 128 KB block; the pass parsed, rewrote and kept a heap copy of it once per glyph, repeated on each of the serializer's buffer-doubling retries (26 s and 1.3 GiB from a 251 KB font before it was rejected). Restore the invariant where the pass is driven: charge each retained glyph's byte length to a budget equal to the source blob length with hb_budget_spend(), and on exhaustion raise HB_SERIALIZE_ERROR_OTHER so _hb_subset_table_try() does not retry. A spec-conforming table can never reach the limit, so there is no tuning constant and valid fonts subset byte-identically; a font whose retained glyphs' gvar ranges overlap by more than the table length now fails avar2 partial instancing. Adds test_avar2_culling_aliased_gvar_data to test/api/test-subset-avar2.c. The non-avar2 instantiate() branch trusts the same offsets and is not touched here. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-NJZQ4XFP. Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
a1134fa3ea |
[subset] Budget kept glyf points and the avar2 reachable-range computation (#6640)
* [subset] Budget the glyf points a plan keeps for partial instancing For partial instancing the subset plan decodes every retained glyph through Glyph::get_all_points_without_var() and keeps all the points in plan->new_gid_contour_points_map until the plan is destroyed. That caller passed no work budget, and nothing capped the total. A simple glyph of repeated flags declares ~65536 points in ~526 bytes, and a loca whose offsets alias one another lets many glyph ids share those bytes, so a 25 KB font drove plan creation to 2.2 GB. PR #6256 added a charge-before-allocate budget to SimpleGlyph::get_contour_points() and passed it from the draw/extents path, but left this subsetter caller unbudgeted. Give the loop one plan-wide budget, the larger of HB_BUDGET_SUBSET_CONTOUR_POINTS and the source glyf length, and charge each glyph's decoded points after it is decoded. One glyph's decode is bounded by the format (about 786 KB), so the transient is proportional to the input; the budget bounds what the plan retains. Exhausting it fails plan creation, the same outcome as any other decode failure in this loop. Ordinary glyph data carries at least one byte per point, so the size-derived bound does not constrain well-formed fonts. Adds an API regression test (test_subset_gvar_shared_glyph_data) with an aliased loca over a 65536-point simple and composite glyph. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-O2ZFVVUI. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * [subset] Budget the avar2 reachable-range computation _compute_avar2_reachable_ranges() bounded only the breakpoint grid (MAX_GRID = 16384 vertices), while its real work is axes x vertices x active row columns x tents. A delta-set row may list the same region tens of thousands of times, and a clamped DeltaSetIndexMap lets every fvar axis share that one row, so a 50 KB font cost about two minutes of CPU per hb_subset_plan_create_or_fail(). Charge one shared allowance per plan, HB_BUDGET_SUBSET_AVAR2_RANGES, at the three places the work is created: scanning the row's columns into the active set, collecting each active region's tents, and the exact grid enumeration (charged up front as grid_size x (active + tents)). Degradation reuses states the surrounding code already handles: an axis whose exact enumeration does not fit takes the existing interval-arithmetic bounds (still conservative, so the instance stays correct), and once the allowance is gone the remaining axes are left unconstrained. The hostile fonts now finish in well under a second; real avar2 fonts use a small fraction of the budget and their output is unchanged. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-3VDGZ019. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * [subset] Guard against null glyf blob in contour-point budget get_instance_glyphs_contour_points() sizes its op budget from the source glyf table length. When head.glyphDataFormat (or indexToLocFormat) is out of range the glyf accelerator is disabled and reference_glyf_table() returns no blob, so hb_blob_get_length() then dereferenced a null pointer and crashed during partial instancing. Take the length only when the blob is non-null. Add a regression test that builds a variable font with an invalid glyphDataFormat and plans a partial instance. Reported by Anthropic's OSS Scanner. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * [subset] Document that the avar2 range budget fallback is safe Running out of HB_BUDGET_SUBSET_AVAR2_RANGES returns early from _compute_avar2_reachable_ranges() and records nothing for the remaining axes. That does not produce a wrongly instanced font: avar2_reachable_ranges is only used to cull variation data that cannot be reached, and an axis without a range is never culled (_hb_avar2_region_is_dead() skips it, the same as the VARC path that resets the map). A pinned axis that is not detected as self-contained stays in fvar as a hidden pin, which is what CFF2 fonts always get. The output is correct, only larger. Likewise the exact-grid fallback uses interval bounds, which are conservative. Say so in the comments instead of "left unconstrained". Tested: meson test -C build (278/278); hb-subset --instance wght=400 and wght=300:700 on GoogleSansFlex, NotoSansKR and SourceSerif4 variable fonts, all glyphs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
a6beb11493 |
[subset/cff] Bound parsed subrs and share one charstring budget per pass (#6636)
* [subset/cff] Bound parsed subroutines by the table size before allocating
subr_subsetter_t::subset() resizes one parsed_cs_str_vec_t per Font DICT
to that DICT's localSubrs->count, assuming the sum is bounded by the
table. It is not: any number of Font DICTs may point at the same
Private DICT and Subrs INDEX, so a 500 KB font with 16 Font DICTs all
sharing one 1000-subr INDEX cost about 1.6 GiB (measured: control 10
MiB, shared 1651 MiB; 2.8 GiB with hb_subset_preprocess).
Sum the global plus per-Font-DICT local subroutine counts in 64-bit
before any per-Font-DICT allocation, and fail the subset when the
records would exceed 256 bytes per byte of the source table, the same
ratio _hb_subset_table_try() uses to stop growing the output buffer.
A font whose Font DICTs do not share their Subrs needs at least one
table byte per subroutine, so it stays far below the limit; every
CFF/CFF2 font in the test corpus is at most a couple of bytes per table
byte. Over the limit the subset fails, as any CFF planning failure has
since dde7da182e; the shared font now peaks at 7 MiB instead of 1.6 GiB.
The check sits before the allocations in the non-accelerator branch, so
it also covers the hb_subset_preprocess path and both CFF1 and CFF2
instantiations of the template; the --desubroutinize flattener path
does not allocate per subroutine and is unaffected.
Adds test_subset_cff1_shared_local_subrs: a 16-Font-DICT CID font with
1000 local subrs subsets when the subrs are unshared and fails when
every Font DICT shares them.
Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-HPFG1IAV.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* [subset] Share one CFF charstring work budget across a subsetting pass
Every per-glyph charstring loop in the subsetter (subr_subsetter_t::
subset, subr_flattener_t::flatten, the two CFF2 partial-instancing
passes, the CFF2 instance-metrics loop, and the CFF1 seac closure in
the plan and in the depend builder) created a fresh interpreter bounded
only by HB_CFF_MAX_OPS per charstring. Glyphs can share subroutines,
so a font where every glyph makes one cheap call into a deeply nested
shared subr cost num_glyphs x ~200,000 ops: a 121 KB, 30,000-glyph font
took 33 s to subset (control 0.05 s).
Give each pass one cumulative counter, max(HB_BUDGET_SUBSET_CFF = 2^24,
32 ops per table byte), threaded through cs_interpreter_t::interpret()'s
existing budget argument exactly as the outline and extents paths do.
When it runs out, interpret() fails as it does for a single over-limit
charstring, so the CFF/CFF2 table fails to subset (the subset fails, as
any CFF planning failure has since
|
||
|
|
db38d0c7e0 |
[layout] Charge the skip, skipped-record and ligature walks to max_ops (#6634)
* [test] Force the ot shaper in the layout budget tests
test_ot_layout_gpos_mark_base_rescan_budget calls hb_shape() with no
shaper forced, then asserts an OT-specific max_ops trip via
hb_buffer_allocation_successful(). Under the HarfRust shaper
(HB_SHAPER_LIST=harfrust, as the rust CI job re-runs the api suite)
it aborts, because harfrust shapes independently and never reaches
the C-side max_ops paths it tests.
Shape with hb_shape_full(..., {"ot", NULL}) so it exercises the OT
shaper regardless of the configured shaper list, as
test_shape_lookup_budget already does.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* [layout] Charge the skip, skipped-record and ligature walks
The per-pass `len / 16` charge does not bound per-position inner work:
the skipping iterator's rescans over default-ignorables, apply_lookup's
walk over a rule's skipped LookupRecords, and match_input /
ligate_input's walk over a ligature's components and marks. Each is a
CPU-DoS a crafted font triggers under the default max_ops.
Charge each on its work path only, so honest shaping is unaffected:
skipping_iterator_t::next/prev charge one op per skip (a first-try
match charges nothing); apply_lookup charges each skipped record;
match_input charges the ligbase backward walk and ligate_input the
mark re-adjust walk, once each.
Reproducers drop from 20 s / 6.8 s / 3.8 s to 0.05 s / 0.003 s /
0.02 s; in-house and aots shaping tests pass with no output change
(the pre-existing text-rendering-tests failures are unchanged).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* [layout] Stop matching once the skip/walk budget is spent
The previous commit charged the walks, but the skipping iterator's skip
arm only decremented max_ops; within one pass a tiny aliased font could
still re-run a walk per candidate, per rule or per subtable without bound
(dfrg's harfrust #604 review found the same gaps here).
Flag the buffer unsuccessful when the skip arm spends the budget -- it
still never early-returns, so *unsafe_to stays set for the kern machine --
and stop the loops that repeat walks once it clears: apply_backward,
Ligature::apply, the reverse-chain and mark-base/lig subtable applies,
and context_apply_lookup / chain_context_apply_lookup. apply_forward
already checks successful.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* [layout] Enforce the budget in the shared subtable loop
dfrg's re-review (harfrust #604): the per-kind entry guards miss paths
that scan before reaching them -- context format 3, the context/ligature
pre-match scans, cursive and mark-to-mark -- so a lookup aliasing thousands
of subtables restarts a buffer scan at each one. Guard the shared
accelerator apply instead (hb_applicable_t::apply), and drop the
now-redundant reverse-chain and mark-base/lig entry guards it subsumes.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
8d01a1b148 |
[subset/cff2] Budget the region transforms built for partial instancing (#6635)
cff2_instancing_plan_t::create() builds k identity tuples of k cells (then keeps a k-float column per surviving solver tuple) for every entry of the CFF2 ItemVariationStore's VarData offset array, and nothing bounded k (a 16-bit region count), the number of entries, or their aliasing of one VarData. The work is therefore quadratic in a font field, so a 12 KB font cost 2.2 GB. Charge those cells, before they are allocated, to a per-table budget HB_BUDGET_SUBSET_CFF2_CELLS (2^24 cells) via the existing hb_budget_spend helper, at both allocation sites (the k*k identity tuples and the surviving solver columns). Exhausting it fails create() like any other planning failure, so the partial instance fails safely (bounded at ~175 MB worst case) instead of exhausting memory. Adds test_instance_cff2_vardata_budget: a 6.8 KB font with 40 offsets aliasing one unused 800-region VarData must fail to partially instance rather than build a region transform for each; it succeeds (keeping CFF2 at hundreds of MB) before this change. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-I7KWU2X6. Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
79146f902e |
[depend] Bound lookup recursion depth and whole-table path count
hb_depend_context_t::recurse() only refused to re-enter a lookup already on the call stack, so a chain of distinct Context lookups recursed once per lookup (stack overflow around 8600 lookups on an 8 MB stack) and lookups invoking each other in every order were walked once per ordering (a factorial number of interned paths, gigabytes of memory). recurse() is where every sibling context (closure, closure-lookups, apply) enforces HB_MAX_NESTING_LEVEL, so add the same nesting_level_left guard here; shaping never applies lookups nested deeper, so no edge the closure can reach is lost (a chain's final edge drops at exactly the depth the closure stops, 65->66). Bound the number of distinct recursion paths with a counter kept over the whole table (not cleared by reset_recurse_cache, which runs per top-level lookup) against a new HB_MAX_DEPEND_RECURSE_PATHS limit in hb-limits.hh, so it can be tuned on its own; exceeding it fails the build so hb_subset_depend_from_face_or_fail() returns nullptr instead of emitting a truncated graph. The largest whole-table path count among the test fonts is 744 (NotoNastaliqUrdu-Bold), so 35000 leaves ample headroom. Builds only with experimental_api. Adds a small permutation-font fuzz seed and a test-ot-depend test; test-ot-depend, the depend fuzzer and the depend-closure-parity tests pass. Related to PR #6185. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-N28924W8. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
0aa7da1772 |
[GPOS] Charge out-of-order MarkBasePos/MarkLigPos base rescans to max_ops
MarkBasePosFormat1 and MarkLigPosFormat1 find a mark's base with a cache (c->last_base / last_base_until) that is only amortized while buffer->idx moves forward. A (Chain)Context lookup that recurses into the mark lookup at input positions out of order resets the cache, so each application rescans the glyphs from last_base_until to idx from scratch; on a long run of marks with no base this is quadratic and was uncharged. Charge the rescanned span (idx - j) to buffer->max_ops after the backward search in both lookups, failing the shape when the budget runs out. A real mark-heavy font pays a negligible amount. Adds a regression test shaping a Context lookup that recurses to MarkBasePos at positions 1,0,1,0,... Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-FJEXEDJ4. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
339aa688fa |
[layout] Charge each GSUB/GPOS lookup pass to max_ops
Lookups can share subtables, features can share lookups, and each shaping stage applies its lookups anew, so the number of passes over the buffer is not bounded by the font size. An earlier lookup can also grow the buffer far beyond the text the budget was sized from: a font that grows one character into a long buffer and then walks it with thousands of lookups (as in harfbuzz/harfrust#571) made hb_shape() spend CPU out of proportion to the text, and none of it was charged to buffer->max_ops. Charge each pass in apply_string() len / 16 for walking the buffer, even if it applies at no glyph (skipping a glyph is cheap, hence the division; applying at one is charged only through the buffer operations and nested lookups it does), and stop the stage loop in hb_ot_map_t::apply() once the buffer has failed. Nothing is charged in the matching hot loops (skipping iterator, RuleSet, ChainRuleSet, LigatureSet): charging there cost real fonts most of the budget in HarfRust (Gulzar spent about half of max_ops on ordinary Urdu prose, Noto Sans Duployan ran out on its own sample text). Aliased rules and ligatures stay bounded by the sanitizer, including the ChainRule array charge. Matches harfbuzz/harfrust#601. test_shape_lookup_budget grows one 'a' to 65025 glyphs before applying aliased lookups, and checks that the pass charge stops the shape. With the font from harfbuzz/harfrust#571 (one 'A' grown to 30,000 glyphs, then 2,000 lookups), hb_shape() takes about 10 ms instead of 0.6 s, stopping after about 35 passes with the glyphs kept. Gulzar and Noto Nastaliq Urdu spend under 0.5% of max_ops on Urdu and Persian prose. Noto Sans Duployan spends up to 45% on its sample text, as on main: nearly all of it is the _infos_set_glyph_flags() charge from #5522; the per-pass charge adds about 5%. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-6A9E6OEX. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-K2T2LOJH. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-DVG5XAU0. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
83a47049a3 |
Merge pull request #6519 from harfbuzz/scanner/depend
[depend] Bound dependency-graph edge count and dedup probe walk |
||
|
|
0eaceda537 |
[limits] Resolve work-budget conflicts with main
Merge main's active-glyph fast paths and precomputed ClassDef caches with the dependency and GSUB closure budgets. Charge the fast paths for the glyphs they visit and the class caches for their ClassDef scans, preserving both the optimizations and the work limits. The full Meson suite passes with experimental APIs enabled (300 tests) and with the default configuration (281 tests). Also syntax-checked hb-ot-layout.cc with HB_NO_BEYOND_64K. Assisted-by: Codex |
||
|
|
0cf5addc3e |
[GSUB] Add small-active-set closure/depend fast path to Coverage-keyed lookups
SingleSubstFormat2 already picks, per closure visit, between walking its whole Coverage and iterating the (usually small) active glyph set. The Multiple/Alternate/Ligature/ReverseChain closure and depend paths, the format-1 (Chain)Context closure, and Coverage::intersect_set lacked that choice, so a nested lookup visited many times over a small active set re-walked a large Coverage every time, giving quadratic GSUB closure (and thus subsetting) time. Add the same get_population()-based fast path to those paths and to CoverageFormat1/2::intersect_set. Output is byte-identical; only the per-visit work is bounded. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-KNHDK379. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
fb350edda9 |
[ot] Collect class-based contextual rule classes once per ClassDef in collect_glyphs
Rule::collect_second_glyphs() resolved the second input glyph of a class-based contextual rule by scanning the whole input ClassDef once per rule, so a RuleSet with many rules sharing one large ClassDef was quadratic in collect_glyphs() (and thus in subsetting). Collect the needed classes into a set and walk each ClassDef once for all of them: add ClassDef::collect_classes(), and have collect_second_glyphs() accumulate the classes and resolve them in a single pass. The collected sets are identical; only the work is reduced. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-5FCXNOQF. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
df02261eca |
[subset] Charge Coverage and ClassDef glyph walks to a work budget (#6628)
* [subset] Charge Coverage and ClassDef glyph walks to a work budget Coverage::subset() expands a format 2 Coverage glyph by glyph, up to numGlyphs, every time an offset to it is subset, and nothing bounded that work. A 10-byte range Coverage referenced by 30,000 two-byte offsets in a subtable listed 8 times costs 1.6e10 iterator steps, while the sanitizer only bounds work by table bytes; a 60 KB font keeps hb-subset busy ~50 s. GDEF's MarkGlyphSets reaches the same walk with no feature or lookup needing to survive planning. Give hb_subset_context_t a per-table work budget (HB_BUDGET_SUBSET_TABLE, in the hb_budget_spend() idiom of hb-limits.hh) with a check_ops() helper that fails the serializer once exhausted, and charge Coverage::subset() its capped population before the walk. Charging inside Coverage::subset() covers every caller (ReverseChainSingleSubst, (Chain)ContextFormat3, GDEF MarkGlyphSets, ...) without touching them. The same unbounded per-reference pattern in ClassDefFormat1_3 / ClassDefFormat2_4::subset() (the range or glyphset walk and the glyph_filter count) is charged the same way. A hostile table that exceeds the budget now fails the subset cleanly (hb_subset_or_fail returns NULL) in a fraction of a second instead of succeeding slowly; valid-font output is byte-identical and the heaviest local table spends a small fraction of the budget. test_subset_shared_coverage_budget builds the reverse-chaining GSUB in memory and asserts 256 shared references subset while 2048 fail. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-LLIWV9UK. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * [subset] Charge layout glyph walks to the existing subset budget Drop the separate HB_BUDGET_SUBSET_TABLE budget and the second hb_subset_context_t field it needed; check_ops() now charges budget_remaining (HB_BUDGET_SUBSET_GLYF, 1 << 28), the per-table budget glyf instancing already uses. Both are per-table and shared across buffer-size retries, and no table spends both. The larger budget still bounds the attack (fails after 2^28 glyph steps, ~3 s), so test_subset_shared_coverage_budget now expects the failure at 8192 shared offsets instead of 2048. Subsetting all glyphs with --layout-features='*' of Gulzar, NotoSansKR-VF and GoogleSansFlex-VF keeps GSUB/GPOS/GDEF with output byte-identical to before; the heaviest table (Gulzar GPOS) spends ~98K units, under 0.04% of the budget. Full meson test: 278 OK. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
70df3ff279 |
[layout] Charge GSUB glyph closure to a per-session work budget
hb_closure_context_t bounded GSUB glyph closure only by counting lookup visits (HB_MAX_LOOKUP_VISIT_COUNT per round), and forgets which lookups are done whenever the glyph set grows, so what one visit walks -- through aliased offsets, many times the table size -- was charged to nothing. A LigatureSubst with 9000 ligatureSet offsets aliased onto one 64-component Ligature, re-walked after every one of 1700 Context triggers that each add a glyph, makes hb-subset --unicodes='*' of an 86 KB font spend ~110 s of CPU. A ReverseChain/ChainContextFormat3 with aliased backtrack Coverages is a second way in. Give the context an int64_t budget (HB_BUDGET_LAYOUT_CLOSURE records, in the hb_budget_spend() idiom) spent as each closure() implementation walks its arrays: dispatch() charges a visit its coverage record count; ligature sets / ligatures / components, sequences, alternates, single-subst intersections, rule sets and rules, context Coverages (via a spend_coverages() helper) and the per-rule-set ClassDef walks are each charged. Coverage and ClassDef gain a get_record_count() helper because intersects()/intersect_set() are linear in records, not population. Once the budget is spent, should_visit_lookup()/lookup_limit_exceeded() stop the closure early, exactly as they do at the visit limit. The budget lives in the context, so both public closure entry points (also reached from hb_ot_shape_glyphs_closure() and the subset plan) are covered with no API/ABI change. Both attack shapes drop to ~1 s and the control font's closure output is byte-identical; the heaviest real font in the corpora uses about 1% of the budget. A hostile GSUB now gets a truncated closure, as one hitting the visit limit already does. test_ot_layout_lookups_substitute_closure_budget builds the hostile table in C and drives hb_ot_layout_lookups_substitute_closure() over it. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-J9K92HA9. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
9b4e3df364 |
[depend] Clip context glyph sets to the face and charge a build budget
While extracting GSUB dependencies, find_or_create_glyph_set() turned every Coverage (format 3 contexts) and class (format 2 contexts) that a contextual rule mentions into an hb_set_t holding every glyph id the table lists, whether the face has it or not, with no budget on the expansion or on the second copy kept in the returned graph. In experimental builds, where the depend API and 24-bit Coverage formats live together, a 6.5 KB font with 400 backtrack Coverage format 4 tables each covering [0, 0xFFFFFF] drives a build to ~2 GB. Clip the cached sets to the face in find_or_create_glyph_set(), the one place every context position goes through (the first input Coverage and ReverseChainSingleSubst already clip this way), so the copies kept in the graph shrink with them. For real fonts this changes nothing; only broken fonts stop carrying glyph ids past the face. Clipping alone is not enough: the temporary is still expanded in full, and the glyph count itself is cheap to inflate with a MAXP table. So add a work budget for the whole build in the existing hb_budget_spend() style: HB_BUDGET_DEPEND, budget_remaining on hb_depend_data_builder_t, and charge_set(), which spends HB_BUDGET_4 per page while expanding a temporary and HB_BUDGET_32 per page for every set the graph or context keeps (new_set(), find_or_create_glyph_set(), find_or_create_recurse_set()). Running out fails the build and hb_subset_depend_from_face_or_fail() returns NULL, as it already does on allocation failure. A get_page_count() accessor is added to the bit-set types so the charge does not reach into set internals; no public API change. The 400-position font now peaks at ~11 MB instead of ~2 GB, the 64 KB / 4000-position font is refused, and hb-subset-depend output is unchanged for real fonts. Regression tests build the face with hb_face_builder_create(): one asserts no glyph above the face count is kept, the other that a 600-range face is refused. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-856K54QG. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
3b517b36f5 |
[depend] Drop the edge probe budget and raise the edge cap
With edge keys hashed by fasthash32 over all fields, a font can no longer steer its edges onto one slot, so probing is bounded by the table's load factor; remove HB_DEPEND_MAX_EDGE_PROBES and its per-probe charge. HB_DEPEND_MAX_EDGES at 1<<22 was too close to real fonts: macOS's DecoType Nastaleeq Urdu builds a graph of 1,198,826 edges, 3.5x below it. Raise the cap to 1<<25, 28x above that. Other large fonts measured: Noto Nastaliq 234,098; Hiragino Kaku Gothic 120,851; Gulzar 30,377; NotoSans-merged 29,968; NotoSansKR 7,797. Reaching the raised cap takes 3.7 s and 1.7 GB, too much for a test, so test_depend_edge_limit now only checks that a modest fan-out is recorded in full. test_depend_gsub_high_bit_tags still covers the hash. Tested: meson test -C build-exp (experimental API, 296/296 OK). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
0f9c31a671 |
[depend] Hash edge keys with fasthash32 and bound the dedup probe walk
The dependency-graph edge dedup table in hb_depend_data_builder_t::add_edge() was indexed by the low bits of an FNV-style hash whose chain of XORs and odd-constant multiplies only ever carries upwards, so bit j of the result depended only on bits 0..j of each field. A font controls feature tags (free 32-bit values) and substitute glyph IDs, so it can pick values that differ only in their high bits and pile every edge of a lookup onto one slot. The open-addressed probe loop then does about N^2/2 work and each resize_edge_slots() repeats it, so a 15 KB font with 680k colliding edges spent ~10 min of CPU while an ordinary font with the same edges takes 0.1 s. hb_depend_edge_key_t::hash() now runs fasthash32() over all identity fields, so every bit of every field reaches the index; equality and the probe sequence are unchanged, so real fonts produce the same graph at about two probes per edge. The now-unused hb_depend_edge_t::hash() is removed. A mixed hash alone is not enough: it is unkeyed, so colliding edges can still be found offline (each one then costs font bytes instead of coming free from a product of tags and pairs, but the walk stays quadratic in them). Every occupied slot stepped over in add_edge() and resize_edge_slots() is therefore charged to a new per-build counter edge_probes_remaining, seeded from HB_DEPEND_MAX_EDGE_PROBES (1<<26, in hb-limits.hh and overridable like the other HB_*_MAX_* limits, following the HB_RASTER_MAX_DRAW_EDGES precedent); exceeding it fails the build the way an allocation failure does, so hb_subset_depend_from_face_or_fail() returns NULL. At about two probes per edge the cap leaves more than 100x headroom over the largest test font. Honest fonts are already bounded well below it by the HB_DEPEND_MAX_EDGES cap added in the previous commit; the probe budget is what stops a crafted all-colliding chain from doing quadratic work before that cap is reached. A regression test builds a GSUB with 2048 features whose tags differ only in bits 20 and up and checks that all 2048 edges are recorded. test-ot-depend, the api suite and the depend fuzzing/closure-parity tests pass on the ASan experimental build, and the finding's reproducer now builds the hostile font in well under a second. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-4XW1PGV5. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
d377bc81f2 |
[depend] Cap the number of stored dependency-graph edges
hb_depend_data_builder_t::add_edge() stored one record per (source, target, feature tag) with no bound. In GSUB a lookup reached by F feature tags multiplies its N*M substitutions by F, so a lookup whose covered glyphs all share one AlternateSet, selected by many feature tags, produces N*M*F edges from a font that grows only with N+M+F. A 5 KB font yields 33M edges and ~1.4 GB of builder memory; COLRv0 overlapping layer slices reach the same sink without any GSUB. The builder also kept walking after fail(), so an allocation failure still cost the full N*M*F iterations. This adds HB_DEPEND_MAX_EDGES (1<<22, about 4M, next to HB_MAX_GRAPH_EDGE_COUNT in hb-limits.hh and overridable the same way; 16x the largest graph in the test corpus) and enforces it in add_edge(), the single choke point every table's extractor stores through, so hb_subset_depend_from_face_or_fail() returns NULL instead of building an unbounded graph. add_edge() and add_gsub_lookup() return early once the builder has failed, and GSUB_accelerator_t::depend()'s lookup loop stops as well, matching the existing !successful checks in the context walkers, so a failed build does bounded work. A regression test builds the fan-out font in memory with hb_face_builder (no binary test font needed) and checks that a 16x16x4 fan-out is recorded in full and that the 256x256x512 one is refused. test-ot-depend and the api suite pass on the ASan experimental build, and the finding's reproducer now returns NULL in ~1 s. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-9IOHFFER. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
ca50d4ad91 |
Merge pull request #6624 from harfbuzz/split/gsubgpos-header
[layout] Write GSUB/GPOS subsets with a header that matches their layout |
||
|
|
40d215957a |
[depend] Collect GSUB feature tags, substitutes and lookup variations in one pass (#6621)
GSUB_accelerator_t::depend() resolved each feature tag separately: it ran hb_ot_layout_collect_features() once per tag and, for every tag, walked the whole FeatureVariations table looking for substitute features. Tables with many features and many FeatureVariations records were therefore quadratic, work that sanitize() bounds only for a single pass. Query all tags at once, then visit each feature once and each FeatureVariations substitute once (via new visit_substitutes() helpers), mapping every lookup to the tag of the feature it belongs to. The emitted dependency graphs are unchanged. Adds a regression test building a FeatureVariations GSUB whose features have no direct lookups. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-5C2QXX5N. Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
c569b7fede |
[gsubgpos] Read contextual rule input glyphs through glyph_data_t in closure/depend (#6620)
context_closure_recurse_lookups() and context_depend_recurse_lookups()
already hold the rule's input sequence as a width-erased glyph_data_t
view, but for glyph-based rules (ContextFormat::SimpleContext) they
unwrapped the raw pointer and let intersected_glyph() index it as
HBUINT16. That is wrong for the HBUINT24 arrays of
SequenceContextFormat4 / ChainedSequenceContextFormat4: every input
position after the first was read at the wrong bytes, so the nested
lookup was closed over the wrong glyph and its real output never
entered the closure (other glyph ids keep glyphs that can never
appear). Only experimental / beyond-64k builds are affected.
Resolve the glyph via input[seqIndex - 1] for every format and make
intersected_glyph() a plain insert of the value, mirroring its sibling
intersects_glyph() which already takes the resolved glyph and ignores
data. These two call sites were the only users of the
pointer-plus-index convention; 16-bit formats are unchanged, and there
is no API/ABI change.
Adds a regression test under HB_NO_BEYOND_64K: a SequenceContextFormat4
rule "1 2" invoking a SingleSubst 2->3 must close {1, 2} to {1, 2, 3}.
It fails on the unpatched library and passes with the fix.
Reported by Anthropic's OSS Scanner as ordinary bug ANT-2026-IU58QGNT.
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
e4802120b6 |
[subset] Keep hinting for fonts that require it (#6588)
* [subset] Keep hinting for fonts that require it Some legacy fonts have hinting programs that must be run for correct rendering; dropping them changes glyph advances and outlines. FreeType refuses to load these fonts without hinting, so do the same in the subsetter by ignoring HB_SUBSET_FLAGS_NO_HINTING for them. Only TrueType-outline fonts qualify. Identify them by family name, and by the length and checksum of their cvt, fpgm, and prep tables. The lists and the name-to-ASCII semantics are ported from FreeType's src/truetype/ttobjs.c; fontations has the same logic in read-fonts/src/tables/glyf/hint_reliant.rs. Keep the detection in hb-subset-hinting.hh rather than the subsetter, and add tests for both paths. Assisted-by: DeepSeek * [subset] Refine hint-dependent font detection - Store family names in a fixed-size table to avoid relocations. - Read the name table directly instead of building the name accelerator, and select the record with FreeType's platform and language priority. - Use hb_vector_t::set_storage() for the name buffer; treat an allocation failure as a non-match. - Pick the family name the way FreeType does: honor the OS/2 WWS bit, and do not fall through to a lower-priority family name when the preferred one exists but does not match. - Add equality operators and use CheckSum::set_for_data() for table checksums, rejecting unaligned data and handling the trailing bytes. - Use face->table.glyf and drop the beyond-64K guard. - Use ISALPHA/TOUPPER for the PDF randomization tag check. - Add a regression test for the OS/2 WWS family selection. Assisted-by: DeepSeek * [perf] Add NO_HINTING subset benchmarks Add a per-test NO_HINTING flag and enable it for the static TrueType font benchmarks, so subsetting through the hint-dependent-font detection path is measured. Benchmark names get a /nohinting suffix. Assisted-by: DeepSeek * [subset] Allow unaligned and unpadded checksum data CalcTableChecksum() can add a trailing partial word. Use that so _table_checksum() can pass arbitrary table data directly to CheckSum::set_for_data() instead of rejecting unaligned data and splitting off the padded prefix. Add unit coverage for padded, unpadded, and unaligned data. Assisted-by: DeepSeek * [subset] Rename and cache the hint-dependent face check Prefix the entry point with _hb_subset, and cache the answer in face user data so repeated subsetting of the same face does not repeat the name and table scans. Assisted-by: DeepSeek * [subset] Avoid allocating for the hint-dependent cache Store the hint_dependent_cache_t value in the face user-data pointer instead of allocating a bool. UNCACHED is zero, CACHED_FALSE is one, and CACHED_TRUE is two. Assisted-by: DeepSeek * [test] Validate checksums against Python-generated vectors Generate deterministic buffers and expected OpenType checksums with an independent Python implementation, covering unaligned offsets and lengths that are not multiples of four. The generator is committed as src/generate-checksum-vectors.py and rewrites the marked block in the unit test. Assisted-by: DeepSeek * [test] Drop the checksum vector generator Keep the Python-generated vectors embedded in test-checksum.cc, but remove the generator script and its markers. The comment records that the values were generated independently with Python. Assisted-by: DeepSeek * [subset] Use CheckSum::CalcTableChecksum directly Drop the trivial _table_checksum() wrapper and call CheckSum::CalcTableChecksum() from the table-ID builder. Assisted-by: DeepSeek * [subset] Release the sanitized name table hb_blob_ptr_t does not destroy its blob in its destructor, so add a scope guard to release it on every return path. Assisted-by: DeepSeek * [subset] Limit cache enum scope * [subset] Use dagger iteration for hint lists Replace the family-name and font-ID membership loops with hb_iter/hb_map/hb_any, and name the family-name capacity used by the table and its iterator. Assisted-by: DeepSeek |
||
|
|
1af279ed98 |
[subset] Charge layout glyph walks to the existing subset budget
Drop the separate HB_BUDGET_SUBSET_TABLE budget and the second hb_subset_context_t field it needed; check_ops() now charges budget_remaining (HB_BUDGET_SUBSET_GLYF, 1 << 28), the per-table budget glyf instancing already uses. Both are per-table and shared across buffer-size retries, and no table spends both. The larger budget still bounds the attack (fails after 2^28 glyph steps, ~3 s), so test_subset_shared_coverage_budget now expects the failure at 8192 shared offsets instead of 2048. Subsetting all glyphs with --layout-features='*' of Gulzar, NotoSansKR-VF and GoogleSansFlex-VF keeps GSUB/GPOS/GDEF with output byte-identical to before; the heaviest table (Gulzar GPOS) spends ~98K units, under 0.04% of the budget. Full meson test: 278 OK. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
c5b920a0f9 |
[subset] Charge Coverage and ClassDef glyph walks to a work budget
Coverage::subset() expands a format 2 Coverage glyph by glyph, up to numGlyphs, every time an offset to it is subset, and nothing bounded that work. A 10-byte range Coverage referenced by 30,000 two-byte offsets in a subtable listed 8 times costs 1.6e10 iterator steps, while the sanitizer only bounds work by table bytes; a 60 KB font keeps hb-subset busy ~50 s. GDEF's MarkGlyphSets reaches the same walk with no feature or lookup needing to survive planning. Give hb_subset_context_t a per-table work budget (HB_BUDGET_SUBSET_TABLE, in the hb_budget_spend() idiom of hb-limits.hh) with a check_ops() helper that fails the serializer once exhausted, and charge Coverage::subset() its capped population before the walk. Charging inside Coverage::subset() covers every caller (ReverseChainSingleSubst, (Chain)ContextFormat3, GDEF MarkGlyphSets, ...) without touching them. The same unbounded per-reference pattern in ClassDefFormat1_3 / ClassDefFormat2_4::subset() (the range or glyphset walk and the glyph_filter count) is charged the same way. A hostile table that exceeds the budget now fails the subset cleanly (hb_subset_or_fail returns NULL) in a fraction of a second instead of succeeding slowly; valid-font output is byte-identical and the heaviest local table spends a small fraction of the budget. test_subset_shared_coverage_budget builds the reverse-chaining GSUB in memory and asserts 256 shared references subset while 2048 fail. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-LLIWV9UK. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
d17c0dbe97 |
[raster] Fail hb_raster_draw_render() when over the pixel budget (#6616)
#6521 made hb_raster_draw_render() skip the scanline sweep when the estimated pixel work exceeds the budget, but it still returned a cleared image, so callers could not tell a budget failure from an outline that legitimately covers nothing. Check the budget before allocating the image and return NULL, the same way render already reports allocation and configuration failures. The accumulated edges are still cleared by the existing scope guard. All in-tree callers (raster paint masks, hb-raster utilities) already handle a NULL result. test_budget_sweep now expects NULL for the over-budget case. Full meson test passes. Follow-up to #6521 Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
fc1ad85522 |
[ft] Take vertical origins from FreeType's bearings again (#6613)
#6499 added caches for the vertical advance and origin, but also changed what the origin is: its x became half the horizontal advance (as hb-ot does) instead of FreeType's horiBearingX - vertBearingX, and a glyph FreeType fails to load got a cached origin of 0 instead of the callback returning false. That changed shaping output for fonts whose vertical bearings are not centered (e.g. bitmap-only fonts), and stopped the fallback to h_origins on load failure. Keep the caches, but cache both the x and y FreeType computes, the same way as before #6499, and return false on load failure without caching anything. Values that don't fit the unsigned cache after sign normalization are simply not cached. Testing: meson test -C build passes. test-ft now checks the batched origins against FreeType's bearings and that a failed load returns false on repeat queries. hb-shape --font-funcs=ft --direction=ttb output over NotoSansKR plus 80 shape/api test fonts, at several sizes, a variation, and negative scale (810 runs) is identical to the commit before #6499; on main 30 of those differed (aat-feat, chromacheck-cbdt, chromacheck-sbix). Follow-up to #6499 Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
6df7f66f94 |
[CBDT] Cap strikes considered instead of indexing them (#6606)
#6500 made the CBDT accelerator build a per-face (ppem, glyph range) -> record index at load time, with a strike set/map, a sorted vector, a walk_ppems fallback and an HB_CBDT_MAX_INDEX_ENTRIES cap, to avoid walking a huge strike array on every glyph query. Real fonts have a handful of strikes, so that machinery costs every CBDT face memory and load time for the benefit of pathological fonts only. Remove it and restore the simple CBLC::choose_strike() and BitmapSizeTable::find_table() lookup path, but only consider the first HB_CBLC_MAX_STRIKES (256) strikes when choosing one; later ones are ignored. ppem is 8-bit, so this never drops a distinct size a real font could need. The sbix strike index, the CBDT subsetter's record map and its image-copy budget from #6500 are kept unchanged. Adds test_hb_ot_color_png_cbdt_max_strikes, which places the only usable strike at index 255 / 256 and checks it is found / ignored; it fails with the cap removed. Full meson test passes. Follow-up to #6500 Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
a40bb748d1 |
Merge pull request #6512 from harfbuzz/scanner/varc
[VARC] Bound CPU work in VARC shaping and subsetting |
||
|
|
b457e5d2a1 |
Merge pull request #6514 from harfbuzz/scanner/cmap
[subset] Bound adversarial cmap work in format 4, per-record collection, and DMAP closure |
||
|
|
fb58fbe259 |
[subset/cff2] Plan FDSelect from the real CFF2FDSelect type
cff2_subset_plan::create() cast acc.fdSelect (a CFF2FDSelect) to the CFF1 FDSelect type for hb_plan_subset_cff_fdselect(), whose get_fd_range() dispatch knows only formats 0 and 3. A CFF2-only format-4 FDSelect therefore reported FD 0 for every glyph, so the planner kept only Font DICT 0: every retained glyph belonging to another Font DICT lost that DICT's Private DICT and local subrs, and when it called a local subr it either lost its outline or drew through FD 0's subrs with the wrong shape. The call still succeeded, writing a single-Font-DICT font. Format 4 is the only FDSelect format with a 16-bit FD index, so every CFF2 font with more than 256 Font DICTs is affected. The planner only needs get_fd_range() and format, so give CFF2FDSelect its own get_fd_range() dispatching formats 0, 3 and 4, make hb_plan_subset_cff_fdselect a template over the FDSelect type with explicit instantiations for CFF1FDSelect and CFF2FDSelect (same pattern as other explicitly instantiated subset helpers), and drop the cast. The existing format-4 writer in hb_serialize_cff_fdselect is now reachable. Because a CFF2 font with >256 retained FDs can now legitimately plan format 4, serialize_cff2_to_cff1() rejects that case (CFF1 has no format 4) instead of emitting an invalid CFF table; with fewer FDs the downgrade is unchanged. Adds test_subset_cff2_fdselect_format4, which subsets the format-3 and format-4 variants of a two-Font-DICT font and requires identical CFF2 output and glyph 2's extents; it fails before this change. Reported by Anthropic's OSS Scanner as ordinary bug ANT-2026-7RSDR0F0. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
a61e59716f |
[subset/cff1] Remap Encoding supplement SIDs through sidmap
cff1_subset_plan renumbers every custom SID it emits through sidmap (charset via plan_subset_charset, Top DICT names via reassignSIDs, FD names via sidmap[]), and the output String INDEX is serialized from that map. plan_subset_encoding was the one emitter that pushed the source font's SID unchanged into subset_enc_supp_codes, so once an earlier custom-named glyph was dropped a supplement code named the wrong glyph, or a string past the end of the renumbered String INDEX. Look the SID up in sidmap where the supplement entry is recorded. The source SID is still used for get_supplement_codes(), which searches the source Encoding. This is safe on every path that reaches it: subset_encoding implies a non-CID font, so plan_subset_charset has already added each visited glyph's name (sidmap.add is idempotent), and when the charset is predefined and plan_subset_charset is skipped all glyph SIDs are standard strings, which sidmap[] returns unchanged. Adds test_subset_cff1_encoding_supplement with a generated CFF font (custom names, format-0 Encoding with supplement 98 -> 'second') and its expected B,C subset; the test fails before this change. Reported by Anthropic's OSS Scanner as ordinary bug ANT-2026-JORVXUQZ. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
9ddb3d0f24 |
[VARC] Bound the glyph records walked during subsetting to the INDEX size
closure_glyphs(), depend() and varc_subset_plan_t::collect_glyphs() each decode the full glyph record of every glyph id they reach, assuming every glyph has its own record. Nothing enforces that: CFFIndex::sanitize() accepts overlapping glyphRecords offsets, and a Coverage table may map many glyph ids to the same INDEX entry, so N glyph ids can resolve to one large record and the walk does N times that record's work -- quadratic in the font size (44 s for a 245 KB font), charged to no budget. In a well-formed table the records are disjoint and each glyph is visited once, so the bytes of all records walked cannot exceed the glyphRecords INDEX. Enforce exactly that invariant where the records are fetched, in all three walks, failing through each site's existing idiom. The remaining work is linear: a component decodes only if its record holds at least one byte per 64 counted axis values. In collect_glyphs() this also replaces the saturating sum and the post-loop data_size != UINT_MAX test, which a 64-bit build bypasses because hb_unsigned_add_saturate() returns size_t and the sum truncates into the unsigned data_size (a near-4 GiB total stored as a small value); the running total is now checked after every addition. Overlapping VARC records, already malformed per the CFF INDEX spec, now fail subsetting instead of being accepted; shaping and drawing are unaffected and valid VARC fonts subset to byte-identical output. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-71PGEDL2. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
a01588aad7 | Merge branch 'main' into scanner/instancer-fix | ||
|
|
f33d54ecf9 |
[subset] Preserve glyph ids for retained glyph-bearing tables (#6586)
The subsetter cannot rewrite tables that refer to glyphs. That includes legacy kern, AAT (ankr, bsln, just, kern, kerx, lcar, mort, morx, opbd, prop), Graphite (Glat, Gloc, Silf), JSTF, SVG, LTSH, EBDT/EBLC, and Apple's Zapf, bdat/bloc, gcid, and hvgl/hvpm tables. When one of these is retained it is passed through unchanged, so renumbering glyphs makes its glyph ids stale. Implicitly enable retain-gids in that case. Make the plan use its own flags after this adjustment so every consumer sees the effective retain-gids state, and add regression tests covering AAT, Graphite, and the other unsubsettable glyph tables. Assisted-by: DeepSeek |
||
|
|
a86ba5f203 |
[cairo] Remove work-budget accounting (#6602)
hb-cairo hands the actual rendering to cairo, so the work done per paint operation (clip, gradient, compositing) is cairo's, not ours. Any count we keep is a guess. The guesses we had were not good: |
||
|
|
970e231199 |
[subset] Merge main and resolve COLR regression test conflict
Both branches appended independent regressions to test-subset-colr.c. Keep the phantom variation-row checks alongside main's overlapping CPAL palette checks, and register both tests. Validation: meson compile -C build; meson test -C build. Assisted-by: OpenAI Codex |
||
|
|
f9b16b40e0 |
[subset/CPAL] Bound retained color records before copying (#6518)
CPAL::subset() copies the retained colors once per distinct
colorRecordIndices start and later writes distinct-blocks x
retained-colors into the 16-bit numColorRecords, but nothing bounded
that product. CPAL palettes may overlap in the color-record array, so
a well-formed 280 KB font with 20000 palettes of 20000 colors made a
single hb_subset_or_fail() hold ~1.5 GiB of copies and burn ~29 s of
CPU (rebuilt on each out-of-room retry) before failing; smaller
products silently wrapped numColorRecords and the per-palette start
indices in the emitted table. This is a regression from
|
||
|
|
24ded4335b |
[font] Saturate synthetic bold and glyph origin arithmetic (#6585)
* [font] Saturate synthetic bold and glyph origin arithmetic #6154 made hb_position_t arithmetic saturate and #6296 did the same for synthetic_glyph_extents(), but the rest of hb_font_t still used plain signed arithmetic: - changed() computed the embolden strength with abs (x_scale), which overflows for INT32_MIN, and converted the float product to int without a range check. A strength of INT32_MIN could also not be negated later on, for negative scales. - get_font_[hv]_extents(), the advance, origin and contour point getters added the strength with += and could overflow. - add_offset(), subtract_offset() and apply_offset() overflow when they apply a large origin, and so do the origin fallbacks in apply_glyph_[hv]_origins_with_fallback(). - em_multf() converted its float result to hb_position_t without a range check, which is undefined for a value such as an ascender above the em at a scale close to INT32_MAX. Use hb_saturate_add(), hb_saturate_sub() and hb_clamp_to() in these places, and keep the strength away from INT32_MIN so that negating it stays defined. Results that fit do not change. The shift variables that were int are now hb_position_t, since the saturating helpers deduce one type and int32_t is not int everywhere. Tested with test-font under UBSan: the new tests fail on the base commit at hb-font.hh:365, :848, :1154 and :1167, and pass here. Assisted-by: Claude * [test] Cover plural origins and synthetic slant saturation Review feedback: the plural origin getters and the slant clamp in get_glyph_contour_point were not covered by the tests, so removing their saturation would still pass. test_synthetic_bold_saturates now also calls hb_font_get_glyph_h_origins and hb_font_get_glyph_v_origins once each and checks both coordinates for INT32_MAX. A new test_synthetic_slant_saturates sets a slant of 1 on a contour point one short of INT32_MAX in both axes and checks that x saturates to INT32_MAX. Verified by mutation: replacing the plural hb_saturate_add calls with plain addition makes the first test fail (the value wraps), and dropping the hb_clamp_to in the slant path makes the second fail (x comes out as -2). Full meson test -C build: 270 ok, 0 fail, 7 skipped (subset+repack, missing repacker dependency; same as the baseline run for this PR). Assisted-by: Claude * [font] Apply the synthetic slant shift before clamping get_glyph_contour_point clamped the slant shift to hb_position_t before adding it to x. When x and the shift have opposite signs and partly cancel, clamping first changes the result: a contour point at x = -2000000000, y = 2000000000 with a slant of 2 should land at x = 2000000000, but came out as 147483647, because the shift was clamped to INT32_MAX before the addition. Add the shift first and clamp the sum instead. The existing saturation case is unchanged: hb_clamp_to widens to double to do the clamp, so an out-of-range sum still saturates instead of hitting an undefined float-to-int conversion. The new test_synthetic_slant_cancelling covers the cancelling case. Verified by mutation: restoring the clamp-first order makes it fail with 147483647, the reported value. Full meson test -C build: 270 ok, 0 fail, 7 skipped, same as baseline. Assisted-by: Claude |
||
|
|
c3fb304549 |
[subset] Only visit non-default UVS mappings in the DMAP cmap closure
cmap_accelerator_t::closure_glyphs() in the DMAP path expanded, for every retained variation selector, all of the selector's Default UVS ranges and resolved each code point with get_variation_glyph(). Any number of 11-byte selector records may share one Default UVS table and a 4-byte range covers 256 code points, so the work was bounded by selectors x covered code points rather than by the table size: a 223 KB font with 20000 selectors on one 168-range table drove ~860M lookups and ~49 s of CPU in hb_subset_plan_create_or_fail(). A default mapping can only ever resolve to the nominal glyph, which the subset plan already retains with the unicode itself, so the closure only needs the code points that carry a Non-Default UVS mapping in cmap or DMAP; get_variation_glyph() still decides which table wins for each. This is exactly what the non-DMAP path (NonDefaultUVS::closure_glyphs) already does. A collect_variation_non_default_unicodes() accessor is added alongside the existing collect_variation_unicodes() chain (VariationSelectorRecord, CmapSubtableFormat14_15, CmapSubtable, cmap::accelerator_t) and used from the DMAP closure, so the work is one lookup per 5-byte mapping visited. No public API or ABI change; hb_face_collect_variation_unicodes() keeps expanding Default UVS ranges as before, and fonts without DMAP take the unchanged first branch. The reproducer's plan drops from ~49 s to 0.01 s with the same 257-glyph result. The separate, older per-record DefaultUVS::copy() serialization cost (~5.2 s for this font, independent of DMAP) is left in place. Adds test_subset_DMAP_shared_default_uvs to test/api/test-subset-cmap.c. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-8RP452C0. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
60bd82dcb4 |
[subset] Bound cmap per-record unicode set collection
When rewriting cmap, the subsetter built one hb_set_t of covered code
points per encoding record. SubtableUnicodesCache keyed those sets by
the record's own offset and collected each with num_glyphs = UINT_MAX,
so a font with many records sharing one full-range format 12 subtable
built one ~1.1M-code-point set per record: ~41 s of CPU, or ~2.1 GB of
memory for a 96 KB input, with nothing but the record count (bounded
only by the sanitizer) limiting the work.
Three changes bound it, all matching how nearby cmap code already works:
1. Key cached_unicodes by record->subtable, so records sharing a
subtable share one set (both set_for overloads).
2. Give the cache a num_glyphs member and collect with it instead of
UINT_MAX, as the cmap accelerator already does for
hb_face_collect_unicodes; cmap::serialize fills it from
plan->source->get_num_glyphs() and create_filled_cache() takes it
as a parameter, passed as face->get_num_glyphs() for
hb_subset_preprocess.
3. Process only the first encoding record of each (platformID,
encodingID) pair in both cmap::serialize and create_filled_cache
(variation-selector records exempt). Lookup already sees one record
per pair and EncodingRecord::copy links later records of a format to
the first serialized subtable, so this bounds both the number of
sets built and the _can_drop walk regardless of how many records a
malformed font repeats, independent of whether they share a subtable.
No public API or ABI change. Output is unchanged for well-formed fonts:
the plan's unicodes are already restricted to gids below num_glyphs, and
valid fonts never repeat a (platformID, encodingID) pair. The attached
reproducer's hostile fonts drop from ~41 s / 2.1 GB to ~0 s / 12 MiB
with byte-identical output.
Adds test_subset_cmap_shared_subtable_many_records and
test_subset_cmap_repeated_encoding_records to
test/api/test-subset-cmap.c.
Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-FSXRDPBT.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
acdd1707a3 |
[cmap] Bound format 4 collect_unicodes/collect_mapping over overlapping segments
CmapSubtableFormat4::accelerator_t::collect_unicodes() and collect_mapping() trusted the format's invariant that segments are sorted and disjoint, so a subtable whose 32766 segments all cover U+0000..U+FFFE was walked once per segment: ~2.1 billion insertions (about 30 s of CPU) for a single hb_subset() or hb_face_collect_nominal_glyph_mapping() call on a 262 KB font. Both walkers now keep a cursor `next` past the last collected code point and clamp each segment's start to it, skipping segments that end before the cursor. Total work per subtable is therefore at most 65536 code points plus one step per segment, mirroring the ordering guard CmapSubtableLongSegmented::collect_mapping() already has for formats 12/13. The glyphIdArray index is still computed from the raw startCount[i], so range-offset segments map exactly as before, and get_glyph() is untouched. Behaviour changes only for malformed subtables: where sorted segments overlap the earlier segment now wins the shared code points, and a segment lying wholly inside an earlier one is ignored. Adds test_collect_unicodes_format4_overlapping_segments to test/api/test-collect-unicodes.c. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-GV7L48CF. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
edf8de90d6 |
[subset] Don't retain ItemVariationStore rows the source lacks
The subset plan turned every variation index collected by the COLR, GDEF and BASE closures into a row to keep, checking only the outer index against the subtable count and never the inner index against VarData::itemCount. A font could therefore name tens of thousands of rows in a VarData whose itemCount is 2, and partial instancing then sized its work from that inflated row count, allocating regionIndexCount x rows x 5 bytes (3.2 GB from a 240 KB COLRv1 font). generate_varstore_inner_maps() now takes the store and keeps only rows that ItemVariationStore::has_delta_set() confirms exist, and remap_variation_indices() maps such an index to HB_OT_LAYOUT_NO_VARIATIONS_INDEX without consuming a new row. That preserves the runtime meaning of an out-of-range index (delta 0) and keeps the two functions in step; all consumers already handle the sentinel. This covers the COLR, GDEF and BASE callers. Well-formed fonts are byte-identical. The HVAR/VVAR route noted in the report (its planner builds row maps itself, one per retained glyph) is left for a follow-up: folding the missing rows into a shared zero row changes the output form of a map-less HVAR whose glyph count exceeds the store's itemCount, which is better landed on its own. Adds an API regression test (test_subset_colr_phantom_rows) that fails on the unpatched tree. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-0TLE41I0. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
d1520e8007 |
[GPOS] Clamp anchor coordinates when converting them from float (#6587)
Anchor coordinates are scaled as float, and apply_cursive_attachment() and the mark attachment code converted them to hb_position_t with a plain cast or an implicit conversion. A value out of range for the target type makes that conversion undefined; on x86 it gives INT32_MIN. #6154 made the additions around these conversions saturate, but not the conversions themselves. With NotoNastaliqUrdu-Regular.ttf at a scale of INT32_MAX, a cursive anchor scales to 2.23e9, and the glyph ended up with an x_advance of -2147483648. Convert with hb_clamp_to(), and negate the cursive cross-direction offsets with hb_saturate_neg(), since they can now be INT32_MIN. Results that fit do not change. Tested with test-shape under UBSan: the new test fails on the base commit at CursivePosFormat1.hh:141 and passes here. No test reaches the two conversions in MarkArray.hh; they are changed to match. Assisted-by: Claude |