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>
The quiet option currently exits immediately after compiling the
dependency graph, making it impossible to measure public API retrieval
separately from formatting and output.
Make -q/--quiet retrieve all selected edges without printing them, and
add --compile for construction-only runs. Avoid creating a font in
quiet mode since glyph names are not needed.
On Noto Nastaliq, compilation takes 362ms and retrieving every edge adds
about 1.4ms, showing that formatting rather than public API retrieval is
the remaining tool-side cost.
Tested with the full Meson test suite (272/272 passed).
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>
The Noto Nastaliq fixtures dominate the runtime of a 64-font dependency
closure-parity chunk, obscuring both their cost and the runtime of the
remaining fixtures.
Run each Noto Nastaliq font as its own named test while retaining the
same seed and per-font test count. Keep all other fonts in the normal
chunking flow.
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>
Add -q/--quiet to build and validate a dependency graph without spending
time formatting or printing it. This makes graph-construction profiling
and performance measurements straightforward.
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>
The thread-safety test shaped entire books and a twelve-thousand-line word
list in every worker. That made it behave like a benchmark even though
the races it targets are exercised when threads concurrently initialize
and use a shared font.
Use the existing substantial paragraph corpora instead. They retain
Latin and Arabic-script coverage across every font backend and both
variable-font modes while reducing standalone runtime from about 1.09s
to 0.16s.
Also reset the worker start gate for every backend so each combination
actually begins concurrently instead of only synchronizing the first.
The full 270-test Meson suite passes, as does an 8-thread, 5-repetition
stress run.
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>
The vector and raster output APIs generate a single glyph asset for
embedding by their caller, but their fuzzers accumulated the first 16
glyphs into one output document. Select one of those glyphs from the
fuzz input instead, retaining coverage across the original range
without multiplying per-glyph work in one invocation.
Tested with the fuzzing suite and the full Meson test suite.
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>
The explicit 120-second timeouts were added after raster-fuzzer chunks
exceeded Meson's 30-second default under MALLOC_PERTURB_. The dominant
cost was an oversized temporary PNG decode buffer, which is now rejected
before allocation.
Restore the default timeout so future runaway fuzz inputs fail promptly
instead of being hidden by extra headroom.
This reverts commit fbdac41be3.
Testing: meson test -C build
Assisted-by: OpenAI Codex <noreply@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>
The raster-fuzzer chunks occasionally hit meson's default 30s test
timeout on CI (e.g. raster-fuzzer-chunk-5 at 30.8s on linux main).
The dominant cost is not the fuzzer inputs themselves: meson runs
tests with MALLOC_PERTURB_ set, which makes glibc scribble over
every allocation on free. Fuzz inputs that acquire large raster
surfaces (up to 4096^2, 64MB) normally leave most pages untouched,
but the perturbation forces a full memset and page-in on free, so a
chunk that runs in ~1.1s bare takes ~7.7s under meson locally
(~6s of it system time), and brushes 30s on slower shared CI
runners. Which chunk is affected varies by machine because the
fonts glob is not sorted, so chunk membership differs.
Keep the perturbation (it catches real bugs) and raise the timeout
of the chunked fuzzing tests to 120s instead, in line with other
suites (subset: 500, threads: 300, perf: 100).
Fuzzing suite passes.
Assisted-by: Claude Fable 5 <noreply@anthropic.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 seed's COLR paint walk fills glyphs whose gvar-varied cubics have
astronomically large control points; each curve recursed to the full
depth-16 subdivision cap while emitting no edges, invisible to the
edge-based paint budget. Timed out on ClusterFuzz before the two
preceding commits.
https://oss-fuzz.com/testcase-detail/4912367159541760
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>
The seed's COLR paint walk emits a full 16MB vector-paint work
budget of path text from a single large gvar-varied glyf glyph;
before the preceding commit the snprintf-based number formatting
made that blow the 60s ClusterFuzz timeout on i386 ASAN builds.
https://oss-fuzz.com/testcase-detail/4700345193005056
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>