Use a non-overwriting hashmap insertion to detect duplicate dependency
edges. This avoids hashing and probing every newly inserted edge twice,
while still distinguishing duplicates from allocation failures through
the hashmap error state.
The NotoNastaliqUrdu compile-only dependency workload saves about 2.2M
instructions. Its wall-time change is below measurement noise.
Tested with: meson test -C build
Assisted-by: OpenAI Codex <codex@openai.com>
Root and singleton active-glyph sets dominate dependency recursion memo
keys. Avoid copying and interning the root set, and encode singleton glyph
IDs directly in the key.
Add an internal singleton query that can recognize uncached sparse sets in
one pass while preserving the population cache.
On NotoNastaliqUrdu-Regular.ttf this reduces the compile-only dependency
run from about 3.18B to 3.05B instructions and from about 245ms to 238ms.
Dependency graphs match the previous output across the focused font
corpus.
Tested with: meson test -C build
Assisted-by: OpenAI Codex <codex@openai.com>
Memoization previously interned the full set of in-progress lookups for
every recursive dispatch. Hashing, comparing, and copying those sets
became visible after the larger dependency-analysis speedups.
Assign stable IDs to ordered recursion paths instead. The path identity
is conservatively more specific than lookup-set identity, while the
separate bit set continues to provide exact cycle detection.
This reduces Noto Nastaliq dependency construction by about 4% in
instructions while preserving byte-identical graphs across the tested
font corpus.
Tested with: meson test -C build
Assisted-by: OpenAI Codex <codex@openai.com>
Walk tag sets and sorted glyph-map keys through their native iterators
instead of repeatedly calling the public scalar set API.
Tests: meson test -C build (272/272)
Assisted-by: OpenAI Codex <codex@openai.com>
Fetch one nonempty 64-bit bitmap word at a time and consume its bits
locally in hb_set_t iterators. This avoids searching the sparse page
map once per codepoint while preserving inverted-set iteration and
bidirectional iterator behavior.
Mutating a set now explicitly invalidates its iterators.
Noto Nastaliq dependency construction is about 1-2% faster in an A/B
comparison, with 3.33B instructions reduced to 3.31B.
Tests: meson test -C build (272/272)
Tests: Noto dependency graph byte-identical to the pre-change oracle
Tests: full-Unicode subset output byte-identical for Noto Nastaliq,
Amiri, Source Serif Variable, and Noto COLRv1
Assisted-by: OpenAI Codex <codex@openai.com>
The per-lookup nested feature vectors introduced a leak in the sanitizer
job: their inner allocations were lost when the temporary dependency
builder was destroyed on GitHub's Clang 18 build.
Pack lookup index and feature tag into a single flat uint64_t vector, then
sort and deduplicate it and build per-lookup offsets. This preserves the
compact sequential traversal and its performance while giving the builder
only flat owning containers.
Tests: meson test -C build (272/272)
Tests: Clang 18 ASan/UBSan depend-fuzzer chunks (9/9)
Assisted-by: OpenAI Codex <codex@openai.com>
Lookup feature tags are collected once, then only iterated while dependency
edges are emitted. Sparse sets make each of those tiny iterations pay bit-page
lookup costs in a major graph-construction hot path.
Append tags to per-lookup vectors, then sort and deduplicate each vector once
after collection. This preserves the set's sorted iteration order while
avoiding quadratic insertion behavior for pathological feature lists.
On Noto Nastaliq this reduces dependency compilation from about 275ms to
259ms, with instructions falling from 3.50 billion to 3.32 billion. Output
is byte-identical.
Tests: meson test -C build (272/272)
Assisted-by: OpenAI Codex <codex@openai.com>
Pass reusable intersection workspace as an optional pointer through the set
layers. Existing callers keep the ordinary local-workspace behavior, while
hot paths can opt into retaining the temporary allocation.
This also lets dependency position collection supply workspace only for the
class/parent intersection that can actually require compaction.
Tests: meson test -C build (272/272)
Assisted-by: OpenAI Codex <codex@openai.com>
Removing pages during a bit-set operation needs a temporary index vector.
The normal set API allocates this vector locally so arbitrary callers do not
carry extra storage, but dependency traversal performs the same class-set
intersection hundreds of thousands of times.
Add an internal intersection overload that accepts caller-owned workspace,
and retain that workspace in the contextual recursion scratch pool. The
ordinary intersection path and its exact-sized temporary remain unchanged.
On Noto Nastaliq this removes 271 thousand allocation calls, reducing the
post-stack-reuse total from 371 thousand to 100 thousand. Compilation time
improves slightly from about 277ms to 275ms, and output is byte-identical.
Tests: meson test -C build (272/272)
Assisted-by: OpenAI Codex <codex@openai.com>
Dependency recursion moves each position glyph set onto the active stack.
Popping the stack then destroys the set and its backing pages, so the next
edge has to allocate them again.
Keep constructed stack slots and track the active depth separately. Reused
slots are cleared before use, preserving the previous empty-set semantics
while retaining their allocations across sibling traversals.
After contextual scratch pooling, this reduces Noto Nastaliq dependency
compilation from about 294ms to 277ms. Allocation calls fall from 1.19
million to 371 thousand, and cumulative allocated bytes fall from 163MB
to 80MB. Serialized output remains byte-identical.
Tests: meson test -C build (272/272)
Assisted-by: OpenAI Codex <codex@openai.com>
Contextual dependency traversal repeatedly constructs temporary glyph sets
and pointer vectors. On Noto Nastaliq this causes over five million
allocation or reallocation calls even after recursion memoization.
Keep one scratch bundle per active contextual recursion level and recycle it
across sibling traversals. This retains backing capacity while preserving
the independent state needed by nested lookups.
For NotoNastaliqUrdu-Regular.ttf, dependency compilation drops from about
374ms to 294ms. Allocation calls drop from 5.26 million to 1.19 million,
and cumulative allocated bytes drop from 480MB to 163MB. Output is
byte-identical.
Tests: meson test -C build (272/272)
Assisted-by: OpenAI Codex <codex@openai.com>
Contextual dependency traversal uses a set to track sequence positions
already covered by earlier lookup records. Those positions are bounded
by HB_MAX_CONTEXT_LENGTH, but the general sparse set allocates its first
bit page on every contextual rule.
Use one inline hb_bit_page_t for dependency traversal. Its 512 bits are
well above the configured 64-position context limit. This reduces quiet
Noto Nastaliq graph construction from 385ms to 363ms.
Tested with the full Meson test suite (272/272 passed).
Assisted-by: OpenAI Codex <codex@openai.com>
Dependency graph extraction repeatedly expands identical class
definitions and coverages into temporary sets while traversing
contextual rules. It also repeatedly interns those same sets when
recording context requirements.
Cache immutable position sets by source identity, reuse their context
set indices, and pass pointers through the short-lived position vectors
instead of copying their contents. This reduces quiet Noto Nastaliq
graph construction from 685ms to 385ms on the profiling machine while
preserving the graph byte-for-byte.
Tested with the full Meson test suite (272/272 passed).
Assisted-by: OpenAI Codex <codex@openai.com>
Expose the exact set-intersection query so callers can test whether two
sets have any elements in common without copying and mutating a set.
The implementation handles inverted sets through the internal helper.
Document the new API with its release placeholder, add it to the docs
section index, and cover regular and inverted set combinations.
Tested with the full Meson test suite (270/270 passed).
Assisted-by: OpenAI Codex <codex@openai.com>
Set-to-set intersection currently only has a conservative may_intersect
helper because sets can be inverted. Callers that know their sets are
not inverted must otherwise reach through two implementation layers.
Add an exact intersects overload that handles all inversion combinations
without allocating. Use it for contextual dependency collection and add
unit coverage for normal, mixed, and inverted pairs.
Tested with the full Meson test suite (270/270 passed).
Assisted-by: OpenAI Codex <codex@openai.com>
Contextual GSUB dependency collection revisits completed lookup states
through each parent path. Complex Nastaliq lookup graphs therefore spend
minutes repeatedly expanding identical subgraphs.
Intern the recursion inputs and cache completed states per top-level
lookup. Remove unused contextual stack bookkeeping and avoid temporary
set allocation for exact intersection checks. Re-enable the Nastaliq
closure-parity fixtures now that they complete quickly.
Tested with the full Meson test suite (270/270 passed).
Assisted-by: OpenAI Codex <codex@openai.com>
SEAC dependency discovery interpreted every CFF1 charstring to inspect
the operand stack at endchar. Most glyphs instead end in a path operator
that has already cleared the stack, making full interpretation needless.
Recognize every Type 2 number encoding that could end immediately before
endchar and retain the full interpreter for those ambiguous cases. Also
retain it for subroutine calls, which can leave operands on the shared
stack. Reject other suffixes without interpreting the charstring.
This reduces 100 dependency scans of the SourceHan test font from 1.38s
to 0.36s and 50 full subsets from 2.56s to 2.05s. The pathological
dependency-fuzzer chunk drops from 1.31s to 0.04s. The full 270-test Meson
suite passes.
Assisted-by: OpenAI Codex <codex@openai.com>
Ligature dependency extraction built a set of component glyphs, but then
walked the original component array and allocated a distinct copy of the
set for every ligature record. Repeated components and equivalent
ligature rules consequently generated millions of redundant edge lookups
and set objects on malformed fonts.
Walk the already-deduplicated component set and intern ligature sets using
the existing content-based dependency-set map. Preserve the unused-set
reuse path by discarding only newly interned sets.
The slow dependency-fuzzer seed improves from about 0.91s and 292MB peak
RSS to 0.24s and 80MB. The full 270-test Meson suite passes.
Assisted-by: OpenAI Codex <codex@openai.com>
VARC's traversal budget still allowed one glyph to amplify into large
serialized paths or millions of raster edges. Vector paint also
charged outline bytes only after a whole glyph, allowing an unbounded
single-operation overshoot.
Charge complete SVG/PDF path commands against cumulative draw and
paint context budgets, reset on clear. Cap each raster draw session's
stored edges and stop processing outline callbacks after exhaustion.
The pathological VARC seed now keeps raster chunk 7 below 0.8 seconds
and vector chunk 7 below 1 second in the full suite. SVG and PDF
outputs remain syntactically valid at the budget boundary.
Tested with the vector, raster, fuzzing, and full Meson test suites.
Assisted-by: OpenAI Codex <noreply@openai.com>
Update the draw and paint examples for the current three-argument
glyph APIs. Document that cached images must be positioned using the
raster image origins instead of reconstructed glyph bearings.
Testing: meson compile -C build harfbuzz-raster docs/harfbuzz-doc:custom
Assisted-by: Codex <codex@openai.com>
* Guard against underflow in calculating val.last_arg_offset in top dict processing.
* [cff] Calculate last argument offset only for ROS
last_arg_offset is consumed only when serializing ROS. Calculate it
after ROS's three arguments have been successfully popped, where the
offset invariant holds, instead of guarding the calculation for every
DICT token.
Tested with: meson test -C build (270 passed)
Assisted-by: Codex <codex@openai.com>
---------
Co-authored-by: Behdad Esfahbod <behdad@behdad.org>
The PNG decoder allocated its temporary RGBA buffer before the final
raster image enforced HB_RASTER_MAX_BUFFER_SIZE. A malformed
65536-by-65536 image therefore requested and, with MALLOC_PERTURB_,
touched 16 GiB before the final image was rejected.
Apply the existing raster buffer limit before allocating the temporary
decode buffer. Images over the limit already failed configuration, so
this only rejects them earlier.
Testing: meson test -C build
Assisted-by: OpenAI Codex <noreply@openai.com>
Detect when the underlying iterator cannot move backwards and restore the
last matching position. This avoids looping forever when the first array
items do not pass the filter.
Add a regression test that exercises the decrement which previously hung.
Fixes: https://github.com/harfbuzz/harfbuzz/issues/6178
Assisted-by: Codex <codex@openai.com>
- Limit max population size of map to prevent size from overflowing.
- Fix possibly overflow population * 8
- Correctly handle copying a map that's in error.
The RTL-safe offset is intentionally double precision, while the font
scale is a float. Cast the scale explicitly before multiplying so GCC's
-Wdouble-promotion does not warn about the intended conversion.
Testing: MinGW DirectWrite build with -Wdouble-promotion
Testing: meson test -C build --print-errorlogs
Assisted-by: Codex <codex@openai.com>
Three refinements to the clip/budget checks the two previous commits
added to the Bézier flatteners, so well-behaved fonts pay almost
nothing for them:
- Subdivided control points are convex combinations of their
parent's, so once a node's bounding box is entirely inside the
clip box no descendant can leave it. Track that per node and skip
the bounding-box test for such subtrees; a typical fully-visible
curve now tests once at the root instead of at every node. Only
curves straddling the box boundary keep testing, and those are the
ones where the test prunes real work.
- Resolve the effective clip box (internal clip box, else fixed
extents; expanded by one pixel) once when it changes, cached in
hb_raster_draw_t, instead of re-deriving it on every curve.
- Keep the work-budget counter in a local and write it back once per
flattener call rather than decrementing through a pointer per
subdivision.
Measured with hb-raster-all (all glyphs, pinned CPU, perf stat -r 10)
against the pre-guard baseline: cubic-heavy SourceSansPro at 1024px
is back to baseline parity (was +0.8% with the naive per-node check);
quad-heavy Amiri at 256px goes from +3.2% to ~+2.6% (residual is the
per-curve root test and budget setup on very short curves; the
workload is a flattening-heavy microbenchmark).
All-glyph renders of Bungee, Bitcount (COLR), Amiri, and AktivGrotesk
VF stay byte-identical; the timeout seed stays at 0.05s; full test
suite passes.
Assisted-by: Claude Fable 5 <noreply@anthropic.com>
The paint-session budget charged outlines only after a whole glyph
had been emitted, by counting accumulated edges. That accounting
misses two things: flattening work that emits no edges at all
(degenerate curves whose subdivided segments collapse or clamp away),
and the single-glyph overshoot before the post-hoc charge lands.
Charge one budget unit per Bézier subdivision inside the flatteners
instead, degrading to the chord once the budget is spent. When
driven by raster-paint, the charge goes to the paint session budget
(threaded in via hb_raster_draw_set_external_work), so per-glyph
work cannot multiply with the paint traversal. Standalone
hb-raster-draw sessions get their own HB_RASTER_MAX_DRAW_WORK
budget, re-armed by hb_raster_draw_clear().
This is belt-and-suspenders on top of the previous commit: the
visibility clip already collapses the degenerate out-of-box curves,
and the budget bounds whatever in-box work remains.
Full test suite passes; rendering all glyphs of Bungee, Bitcount
(COLR), Amiri, and AktivGrotesk VF at size 256 stays byte-identical.
https://oss-fuzz.com/testcase-detail/4912367159541760
Assisted-by: Claude Fable 5 <noreply@anthropic.com>
A malicious font can present Bézier curves with astronomically large
control points. The flatness test never passes on such curves, so
each one recurses to the full depth-16 subdivision cap, spinning
through up to 65536 iterations while emitting nothing: the resulting
segments all saturate to the same clamped coordinates and are skipped
as horizontal. Because the paint-session budget charges outlines by
their accumulated edges, this work was invisible to it, and a COLR
font driving many such fills timed out on ClusterFuzz (61s on the
x86_64 UBSAN bot; 0.6s locally, 90% inside flatten_cubic_recursive).
Give hb_raster_draw_t a visibility clip box (set internally by
raster-paint to the target surface, or derived from fixed extents
when set) and replace any curve whose control-point bounding box
falls entirely outside it with its single chord. The replacement is
exact for rendering: a curve's net winding contribution per scanline
depends only on its endpoints (intermediate crossings cancel in
pairs), crossings right of the box never reach visible pixels, and
the renderer already folds left-of-surface edges into the first
column's cover. Subdivision still prunes invisible halves of
partially visible curves at the first level where their bounding box
exits the box.
The timeout input drops from 0.6s to 0.05s locally. Rendering all
glyphs of Bungee, Bitcount (COLR), Amiri, and AktivGrotesk VF at
size 256 produces byte-identical images; full test suite passes.
https://oss-fuzz.com/testcase-detail/4912367159541760
Assisted-by: Claude Fable 5 <noreply@anthropic.com>
hb_vector_buf_t::append_num() formatted every coordinate with two
snprintf calls (one just to build the "%.Nf" format string) plus
strstr/strchr/strlen for the locale decimal-point fix-up and the
trailing-zero strip. On oss-fuzz's i386 ASAN builds those
intercepted libc calls run ~60-100x slower than native, so a COLR
paint session that emits its full 16MB work budget of path text
(~2M numbers) blew the 60s fuzzer timeout; locally the same input
spent 75% of its time inside glibc __printf_fp.
Replace the common case with fixed-point integer formatting: scale
by 10^p, round half-to-even, and print the digits with integer
math. A float has a 24-bit significand and 5^12 adds 28 more bits,
so v*10^p is exact in a double for p <= 12; the result therefore
matches snprintf "%.pf" digit-for-digit, verified against the old
code on 40M random and targeted inputs (ties, denormals, FLT_MAX,
NaN/Inf, negative zero, all precisions). Magnitudes that do not
fit int64 fall back to the old snprintf path.
The timeout input drops from 0.84s to 0.17s locally, and the
remaining profile is HarfBuzz code rather than intercepted libc.
check-symbols, the vector suite, and the full test suite pass with
byte-identical outputs.
https://oss-fuzz.com/testcase-detail/4700345193005056
Assisted-by: Claude Fable 5 <noreply@anthropic.com>
Share the forward and inverse instantiated-mapping evaluator. Reuse the
grid scratch containers, remove redundant axis bookkeeping and box
lookups, and use the preferred odometer loop form.
Make the grid-size cutoff overflow-safe so a crafted many-axis store
cannot wrap the product and bypass the conservative fallback.
Tests: meson test -C build
Tests: meson test -C build --suite subset
Tests: GCC/Clang C++11 and reduced-feature amalgamation builds
Assisted-by: OpenAI Codex
An avar version 2 table with a NULL varStore offset is legal and maps
like plain v1 — but partial-instancing it used to fail outright, because
the planner errored against the missing store. Rather than falling back
to the v1 instancing path (which rescales every variation store and is
not always bit-exact), keep such fonts on the avar2 path: mapping
entries that don't resolve to a real store row are normalized to
NO_VARIATIONS_INDEX, mirroring runtime get_delta semantics, and offset
compensation creates the needed delta rows on demand in an empty store.
The instance stays version 2 and bit-exact, and consumers that ignore
the v2 tail still see the renormalized v1 segment maps.
Adds a subset test with a null-VarStore variant of the RobotoDelta test
font; the instancing test fails outright without the fix.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The per-axis reachable-range bound used per-region interval arithmetic,
which ignores correlations between regions: sound, but loose enough
that culling rarely fires on real parametric fonts. The delta is
piecewise multilinear in the axis coordinates, so its exact extremes
are attained at vertices of the grid of per-axis tent breakpoints.
Enumerate that grid when it is small (real fonts: exact answer,
microseconds) and keep the interval bound as the conservative fallback
when a crafted many-axis row would make the grid explode. Ports
fontTools' VarStore.getExtremes rewrite from the avar2-instancing
branch (fonttools/fonttools#4045).
Also resolve delta rows with runtime semantics: a varidx (or the
implicit identity mapping) that doesn't point at a real store row
contributes no variation, instead of failing the plan.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The support scalar is 1 (not 0) at v == peak, so a tent whose peak sits
exactly on the reachable-range boundary is live there. The ranges'
one-unit padding at their producer already prevented wrong culling in
practice; strictness makes the predicate correct on its own terms.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The estimator that picks between offset-compensation knot sets (and
decides whether to warn) sampled a uniform 257-point grid only, which
can miss the worst kink in precisely the steep-segment regime it
targets. Augment the sample set with the user-space preimages of every
kink of the residual: old and new avar v1 breakpoints and the offset(z)
knots, pulled back through the inverse of the instantiated mapping.
The pointwise F2Dot14 rounding keeps this an estimate, but every
piecewise-linear extremum is now visited.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The subset planner rejected out-of-range avar2 delta-set indices even
though runtime evaluation treats them as zero. The avar2 rewrite also
carried those invalid indices into its output mapping.
Validate delta-set indices centrally and normalize invalid mappings to
NO_VARIATION_INDEX during planning and rewriting. Add coverage for an
empty non-NULL VarStore with an implicit index map.
Tests: meson test -C build
Assisted-by: OpenAI Codex