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
Clang rejects explicit destruction of polymorphic classes with
non-virtual destructors unless the exact type is known to be final.
Mark the two internal DirectWrite COM helper implementations final.
This keeps their manual HarfBuzz allocation lifecycle C++11-safe
without reintroducing operator delete references.
Tested with Clang and GCC MinGW cross-compiles and the full Meson test
suite.
Assisted-by: OpenAI Codex <codex@openai.com>
DirectWrite used scalar and array new/delete for its COM helpers and
shaping buffers. This left operator new/delete references in MinGW
static and amalgamated builds, forcing C consumers to link libstdc++.
Use HarfBuzz allocators and containers instead, propagate allocation
failures from text analysis, and let Meson use the normal C linker.
Tested with MinGW Meson and CMake DirectWrite builds, a C-linked
amalgamation, and the full Meson test suite.
Fixes: https://github.com/harfbuzz/harfbuzz/issues/6160
Assisted-by: OpenAI Codex <codex@openai.com>
ensure_initialized() lazily acquires the session's root surface on
the first paint callback. When one of its stack pushes fails under
OOM, the hb_vector_t goes into its sticky error state and the push
can never succeed again -- but every subsequent paint callback
re-ran the whole initialization: acquire_surface(), configure, and
a full-surface clear, then failed the push and released the surface
again. Nothing along that path charges the session work budget, so
a COLR paint graph with thousands of callbacks re-paid a 4096x4096
(64MB) memset each time: the ClusterFuzz font drives ~2240 fill
callbacks, ~140GB of memset, and a libFuzzer timeout. Simulating
the failed push locally (forcing the stack's error state in gdb)
reproduces it: 15664 full-surface clears, 70s.
Bail out of initialization if either stack is in error, and charge
the root surface's area to the session budget before acquiring it,
mirroring the push_group() pattern, so any other repeated-
initialization path drains the budget instead of spinning.
Successful initialization re-arms the budget right after, so the
charge is a no-op for normal sessions.
Also drop a stray transform_stack.pop() from the clip-push failure
path: ensure_initialized() never pushes a transform, so the pop
could strip a transform legitimately pushed by an earlier callback.
With the error state forced, the reproducer now performs 2 clears
and finishes instantly; full test suite passes.
https://oss-fuzz.com/testcase-detail/4604877465255936
Assisted-by: Claude Fable 5 <noreply@anthropic.com>
The SVG and PDF vector paint backends charge glyph-outline bytes to
the session work budget, but sweep-gradient patch emission appended
mesh/path bytes with no charge. Even with the per-call tile cap
from the previous commit, a COLR paint graph can invoke many sweep
gradients, multiplying the per-gradient patch data by the
paint-graph traversal limits.
Charge the bytes appended by each emitted patch to the session
budget and skip patch generation once the budget is spent, matching
the existing outline-extraction pattern.
Sweep glyphs of test_glyphs-glyf_colr_1.ttf and its variable
version render byte-identically in both SVG and PDF; full test
suite passes.
Assisted-by: Claude Fable 5 <noreply@anthropic.com>
hb_paint_sweep_gradient_tiles() walked to the first repeat that can
reach angle 0 by subtracting the color-line span one repeat at a
time, and bounded the repeat loop only by an absolute repeat index
of 1000. A repeat/reflect color line whose stops span a tiny angle
then emits repeats-times-stops patches: the ClusterFuzz font drives
27648 stops over ~0.0008 rad, producing ~140M emit_patch callbacks
and gigabytes of Coons-patch mesh in the PDF vector backend, and a
libFuzzer timeout. The one-span-at-a-time walk could also fail to
terminate outright for angle values reachable through variation
deltas, once the span drops below the float ulp of the angle.
Cap emitted tiles at the new HB_PAINT_MAX_SWEEP_TILES (4096); its
inverse doubles as the angular resolution of the tiling, 2π/4096.
A color line whose period is below that resolution repeats faster
than the tiles can resolve, so instead of tiling it, fill the whole
circle flat with the width-weighted average color of one period --
the band-limit of the pattern. Compute the starting repeat directly
by division, bailing out on non-finite angles, and guard the inner
loop against clipped-segment spins that unsorted (contract-violating)
stop arrays could otherwise drive. The absolute-index 1000 cap is
gone: repeat gradients that legitimately need more repeats to cover
the full circle now render completely instead of being silently
truncated. The helper is also used by the hb-cairo glue, which
picks up the same bounds.
The ClusterFuzz reproducer drops from 27s / 7.8GB RSS locally to
under 0.01s / 8MB, each degenerate gradient collapsing to one flat
patch. All 96 sweep glyphs of test_glyphs-glyf_colr_1.ttf and 98
sweep glyphs of its variable version at three variation settings
render byte-identically in both SVG and PDF; full test suite passes.
https://oss-fuzz.com/testcase-detail/6490910482038784
Assisted-by: Claude Fable 5 <noreply@anthropic.com>
Individual mark and cursive anchors stay within four ems and cannot
approach the hb_position_t limits. Convert those directly, while keeping
saturation where they are combined with offsets accumulated through an
attachment chain.
Testing: meson test -C build --print-errorlogs
Assisted-by: OpenAI Codex
Font-space metrics stay within four ems and font scales within 131072,
so scaled advances and vertical origins cannot approach the
hb_position_t limits. Keep these common operations direct instead of
clamping or saturating each one.
Testing: meson test -C build --print-errorlogs
Assisted-by: OpenAI Codex
Font-space geometry stays within four ems and font scales within 131072,
so scaled extents, synthetic adjustments, origins, and parent-child
conversions cannot approach the hb_position_t limits. Keep these common
operations direct instead of saturating each one.
Testing: meson test -C build --print-errorlogs
Assisted-by: OpenAI Codex
Font-space values stay within four ems and font scales within 131072,
so the fixed-point result cannot approach the hb_position_t limits.
Accept int32_t directly instead of clamping every result or branching to
the floating-point scaler for wider inputs.
Testing: meson test -C build --print-errorlogs
Assisted-by: OpenAI Codex
Integrate the remote main update before publishing the DirectWrite CI fix.
Testing: meson test -C build --print-errorlogs
Assisted-by: Codex <codex@openai.com>
The hb_in_range helper intentionally accepts unsigned types only. Using it
with DirectWrite's widened signed metrics therefore failed both MinGW and
Clang MSYS2 builds at its static assertion. Check the int16 bounds directly
before selecting the narrow scaling path.
Testing: meson test -C build --print-errorlogs
Testing: MinGW64 cross-build of the harfbuzz target
Assisted-by: Codex <codex@openai.com>
Variable clip-box endpoints can span the full coordinate range after
applying variation deltas. Saturate their differences when producing
glyph extents.
Tested with: meson test -C build --print-errorlogs
Assisted-by: OpenAI Codex
Variable COLR clip boxes add rounded variation deltas to integer
coordinates. Clamp each floating-point delta and saturate its addition
so extreme variation data cannot overflow the runtime clip box.
Tested with: meson test -C build --print-errorlogs
Assisted-by: OpenAI Codex
DirectWrite outline coordinates negate scaled vertical positions before
passing them to the float draw API. Convert to that float domain first
so INT_MIN does not overflow during negation.
Tested with: meson test -C build --print-errorlogs
Assisted-by: OpenAI Codex
Synthetic slant translates outlines by the negated glyph origin.
Convert the full-range position to the float coordinate domain before
negating it, avoiding signed integer overflow at INT_MIN.
Tested with: meson test -C build --print-errorlogs
Assisted-by: OpenAI Codex
Building the fixed-point font multipliers negated INT_MIN and shifted
negative values. Replace both paths with a widened multiplication,
which is defined across the full font-scale range.
Tested with: meson test -C build --print-errorlogs
Assisted-by: OpenAI Codex
DirectWrite returns vertical design advances as INT32. Scale their
full range, then saturate the sign reversal required by HarfBuzz's
vertical advance convention.
Tested with: meson test -C build --print-errorlogs
Assisted-by: OpenAI Codex
DirectWrite returns design advances as INT32. Use the full-range
scaling helper instead of narrowing them to the int16 fast-path input.
Tested with: meson test -C build --print-errorlogs
Assisted-by: OpenAI Codex
MathValueRecord adds a device or variation delta to an already scaled
coordinate. Saturate that addition at full-range font scales and
deltas.
Tested with: meson test -C build --print-errorlogs
Assisted-by: OpenAI Codex
Format-3 baseline coordinates add a device or variation delta to an
already scaled coordinate. Saturate that addition at full-range font
scales and deltas.
Tested with: meson test -C build --print-errorlogs
Assisted-by: OpenAI Codex
Format-3 caret values add a device or variation delta to an already
scaled coordinate. Saturate the result for full-range font scales and
deltas.
Tested with: meson test -C build --print-errorlogs
Assisted-by: OpenAI Codex
Synthetic caret metrics multiply scaled positions and add a slant
adjustment. Widen the multiplication, clamp the floating-point delta,
and saturate its addition.
Tested with: meson test -C build --print-errorlogs
Assisted-by: OpenAI Codex
Baseline fallback combines full-range BASE coordinates and font scales.
Widen proportional formulas and saturate additions and subtractions so
the synthesized coordinates remain defined at extreme scales.
Tested with: meson test -C build --print-errorlogs
Assisted-by: OpenAI Codex
Synthetic slant and emboldening add adjustments to full-range contour
coordinates. Keep the slant calculation in float, clamp its rounded
delta, and saturate both additions.
Tested with: meson test -C build --print-errorlogs
Assisted-by: OpenAI Codex
Fallback space advances negate, round, and multiply the font scale.
Perform those operations in 64-bit arithmetic so full-range scales do
not overflow before the final, bounded division.
Tested with: meson test -C build --print-errorlogs
Assisted-by: OpenAI Codex