Malformed reflected gradients can produce very large finite
gradient parameters. The raster backend normalized reflect
mode by casting floorf(t) to int, which can overflow and
drive LUT lookups past the fixed-size stack buffer.
Fold reflected coordinates with fmodf(), clamp LUT inputs
defensively, and add the minimized oss-fuzz raster
testcase to the corpus.
Fixes: https://oss-fuzz.com/testcase-detail/6597066439852032
Tested: meson test -C build
Co-Authored-By: OpenAI Codex <codex@openai.com>
hb_gpu_draw_encode() could allocate a fresh output buffer and then
return NULL before transferring ownership to a blob, leaking that
temporary buffer on late encode failures.
The recycled-blob growth path also tried hb_realloc() first and fell
back to hb_malloc() when that failed. Once the new buffer was committed
to the recycled blob, the old recycled buffer could be orphaned.
Free temporary buffers on the remaining late-failure exits and keep
the old recycled buffer alive until a replacement has been committed.
Tighten the GPU API recycle test to encode a larger second outline so
that reused-buffer growth stays covered.
Tested:
- meson test -C build
Assisted-by: OpenAI Codex <codex@openai.com>
edge_sweep_row() computed the clipped endpoint x coordinates with
int32_t subtractions before casting to int64_t. If an edge started at
INT32_MIN and the scanline clipped endpoint was near zero, ey - yL
overflowed before the slope multiply and UBSan flagged the raster
fuzzer path.
Keep the endpoint interpolation and follow-on dx math in 64-bit until
clamping back to int32_t. This preserves the existing rasterizer logic
while avoiding signed overflow for extreme edge coordinates.
Tested:
- meson test -C build
Assisted-by: OpenAI Codex <codex@openai.com>
libpng aborts via longjmp. Our PNG read/write helpers kept scratch
hb_vector_t objects as automatic locals after setjmp and then tried
to free them from the longjmp handler. Once longjmp fires, those
modified locals have indeterminate state, so the cleanup path can
miss live allocations and leak under the raster fuzzer.
Move the PNG scratch buffers and write accumulator into explicit
heap-backed state allocated before setjmp and cleaned up on every
exit path. This keeps both decode and encode cleanup deterministic
across libpng errors.
Tested:
- env LD_LIBRARY_PATH=/home/behdad/harfbuzz/build/src valgrind --leak-check=full --show-leak-kinds=all --error-exitcode=1 ./build/test/fuzzing/hb-raster-fuzzer test/fuzzing/fonts/clusterfuzz-testcase-minimized-hb-subset-fuzzer-5684014636859392
- meson test -C build raster-fuzzer-chunk-0 raster-fuzzer-chunk-1 raster-fuzzer-chunk-2 raster-fuzzer-chunk-3 raster-fuzzer-chunk-4 raster-fuzzer-chunk-5 raster-fuzzer-chunk-6 raster-fuzzer-chunk-7 --wrap='valgrind --leak-check=full --show-leak-kinds=all --error-exitcode=1' --print-errorlogs
- meson test -C build
Assisted-by: OpenAI Codex <codex@openai.com>
Transformed clip rectangles kept their intersection math in unsigned
loop bounds after clamping only the lower edge to zero. When the
transformed upper edge stayed negative, the signed-to-unsigned cast
wrapped and raster clip reuse read past the previous alpha mask.
The same path also reused emitter-generated clip buffers without
clearing bytes outside the rows it rewrote, which let Valgrind see
uninitialized alpha values on later clip intersections.
Keep the clip intersection in signed ints until after the empty-range
check, and zero newly sized emitter clip buffers before partial writes.
Testing:
- env LD_LIBRARY_PATH=/home/behdad/harfbuzz/build/src valgrind --leak-check=full --error-exitcode=1 ./build/test/fuzzing/hb-raster-fuzzer test/fuzzing/fonts/clusterfuzz-testcase-minimized-hb-raster-fuzzer-4872362293264384
- meson test -C build raster-fuzzer-chunk-0 --wrap='valgrind --leak-check=full --error-exitcode=1' --print-errorlogs
- meson test -C build
Assisted-by: OpenAI Codex <codex@openai.com>
The raster paint clip code indexed non-rect clip alpha rows directly,
assuming the clip metadata always matched a full stride*height backing
buffer. Fuzzing showed that reused clip objects can reach those reads
with stale scalar state, which turns the row access in
push_clip_rectangle() into a heap-buffer-overflow.
Reset cached clip geometry on acquire, add a validity check for
non-rect alpha masks, and refuse to build new clip intersections from
an invalid mask. The fallback is an empty clip, which keeps the paint
path safe without affecting well-formed clips.
Testing:
- meson test -C build --suite fuzzing --print-errorlogs
- meson test -C build
Co-authored-by: OpenAI Codex <codex@openai.com>
The raster SVG renderer asserted that each element restored the paint
transform, clip, and surface stacks to their entry depths. Fuzzing
found malformed documents that violate that assumption and abort the
process in svg_render_element().
Replace the assertions with explicit stack restoration, discard any
extra group surfaces, and mark the render as failed if the renderer
cannot get back to the saved baseline. The top-level SVG entry point
now checks that failure bit and stops rendering cleanly instead of
crashing.
Testing:
- meson test -C build --suite fuzzing --print-errorlogs
- meson test -C build
Co-authored-by: OpenAI Codex <codex@openai.com>
MemorySanitizer reported use of uninitialized data while building the
SVG document cache used by vector painting. The parser keeps small
aggregate structs on the stack, and their padding could stay poisoned
as they were copied through the open-element stack.
Zero-initialize the parser stack and the temporary span / element
records before filling their fields. That keeps later copies and
container insertions from carrying undefined padding into the MSan
instrumented path.
Testing:
- meson test -C build --suite fuzzing --print-errorlogs
- meson test -C build
Co-authored-by: OpenAI Codex <codex@openai.com>
The GPU fuzzer can build outline data large enough to stress the size
math inside hb_gpu_draw_encode(). Several totals and byte counts were
computed with unchecked unsigned arithmetic before the existing bounds
checks ran.
Use HarfBuzz's overflow helpers for band-index totals, encoded blob
lengths, byte sizes, and recycled-buffer growth. Also rewrite the
uint16-offset limit check so it does not rely on subtracting from an
already-overflowed total.
Testing:
- meson test -C build --suite fuzzing --print-errorlogs
- meson test -C build
Fixes: https://oss-fuzz.com/testcase-detail/6336503637934080
Co-authored-by: OpenAI Codex <codex@openai.com>
Failing-malloc fuzzing exposed two holes in the GPU draw path.
Accumulation ignored push failures, and encode reused scratch vectors
that could remain poisoned after a previous allocation failure.
Poison the draw object on accumulator OOM, bail out of the remaining
path-building callbacks, and have hb_gpu_draw_encode() return NULL once
the object has failed. Also check the encode scratch resizes and reset
poisoned vectors before reuse. Resetting the draw now fully resets the
curve vector as well, so callers can recover after an OOM by calling
hb_gpu_draw_reset().
Testing:
- meson test -C build --suite fuzzing --print-errorlogs
- meson test -C build
Co-authored-by: OpenAI Codex <codex@openai.com>
Encode used adjacent endpoint equality to infer contour breaks, which
fails when two contours touch at the same point. Track contour starts
explicitly during accumulation instead, and use that flag when packing
shared endpoints.
Encode also rounded blob bounds to the nearest quarter unit. That can
shrink the encoded extents and clip coverage at glyph edges. Quantize
mins downward and maxes upward so the blob header always encloses the
actual geometry.
Add focused API tests for both regressions.
Testing:
- meson test -C build
Co-authored-by: OpenAI Codex <codex@openai.com>
Compute pixelsPerEm once in hb_gpu_render and pass it down,
so MSAA samples share one fwidth call instead of each
computing their own. Required for WGSL (fwidth must be
called from uniform control flow) and a minor win for all
backends.
Assisted-by: Claude <noreply@anthropic.com>
Add hb_gpu_draw_set_scale() API and store x/y scale in the
glyph blob header (buf[1].b/a). hb_gpu_draw_glyph() sets it
automatically from the font.
hb_gpu_render() now reads the scale, computes ppem via fwidth,
and automatically blends 4 corner samples at ±1/3 pixel when
ppem < 16 to reduce moiré at small sizes. Define
HB_GPU_NO_MSAA to disable.
Add hb_gpu_ppem() public shader helper so clients can get
ppem without touching internal functions (e.g. for
hb_gpu_darken).
Remove hb_gpu_render_aaa(), u_upem uniform, and set_upem
plumbing from the demo — no longer needed.
GLSL only for now.
Assisted-by: Claude <noreply@anthropic.com>
Replace the two-program MSAA toggle with hb_gpu_render_aaa()
that takes ppem from the caller and auto-selects single-sample
(ppem >= 16) or 4-corner MSAA (ppem < 16). This keeps
hb_gpu_render() lean for the fast path while letting the
adaptive function handle small sizes.
The previous approach had the ppem calculation inside the
library shader using 1/fwidth(texcoord), which was wrong by
a factor of upem — MSAA fired at all sizes. Now the demo
passes correct ppem via a u_upem uniform.
Remove the 'm' key toggle, two-program compilation, and
set_msaa plumbing — no longer needed.
GLSL only for now.
Assisted-by: Claude <noreply@anthropic.com>
Use 4 samples at ±1/3 pixel corners instead of the full 3x3
grid. Diagonal placement provides good moiré reduction at
half the cost.
Assisted-by: Claude <noreply@anthropic.com>
Add hb_gpu_render_msaa() that evaluates 9 samples (3x3 grid
at ±1/3 pixel) to reduce moiré at small sizes. GLSL only.
The demo compiles two shader programs and toggles between them
with the 'm' key, so the MSAA program's register pressure
does not affect the fast single-sample path.
Assisted-by: Claude <noreply@anthropic.com>
At ppem < 16, blend in 4 extra samples at ±1/3 pixel offsets
to reduce moiré patterns and aliasing at small sizes. The
blend factor transitions smoothly from full MSAA at ppem 8
to single-sample at ppem 16.
GLSL only for now; MSL, WGSL, and HLSL still use single-sample.
Assisted-by: Claude <noreply@anthropic.com>
The HB_NO_DRAW closure must run before the HB_NO_CFF closure
so that HB_NO_DRAW → HB_NO_CFF → HB_NO_OT_FONT_CFF propagates
correctly in a single pass.
Assisted-by: Claude <noreply@anthropic.com>
CFF parsing requires the draw infrastructure, so it belongs
in the HB_NO_DRAW closure rather than being unconditionally
disabled by HB_LEAN. This allows HB_LEAN and HB_TINY builds
that re-enable draw (via config-override.h) to also get CFF
support without explicitly undefining HB_NO_CFF.
Assisted-by: Claude <noreply@anthropic.com>
Library function for stem darkening: pow(2, brightness-0.5)
scaled by ppem. Added to GLSL, MSL, WGSL, HLSL with consistent
brief docs. Demo shaders now call the library function.
Section docs in hb-gpu.cc updated with usage example.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Bring WGSL shader in line with GLSL/MSL/HLSL by extracting the
header decode + band index computation into a shared helper.
Enables future debug heatmap support in the WebGPU demo.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Make hb_gpu_fetch public (no underscore prefix) in all shaders.
Internal functions use _hb_gpu_* consistently, including WGSL
(single leading underscore is legal per gpuweb/gpuweb#2298).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Explain why font scale should be left at default, how dilation
works and what jac means, and provide a simpler static dilation
alternative for 2D rendering at known sizes.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Port fragment and vertex shaders to HLSL (Shader Model 5.0+).
Uses asuint for bit reinterpretation, StructuredBuffer<int4> for
atlas, and mul() for matrix multiply. Verified with DXC on Linux.
Adds HB_GPU_SHADER_LANG_HLSL to the enum. Reorders enum to:
GLSL, WGSL, MSL, HLSL. Updates doc strings for consistency.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Replace separate .glsl files and generated .hh headers with C++11
raw string literals (R"glsl(...)glsl") directly in demo-shader.cc.
Matches the pattern already used by demo-metal.mm and the WebGPU
demo. Removes demo shader generation from meson and the generator
script.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
WGSL reserves identifiers starting with underscore. Use hb_gpu_fetch
(no prefix) for the atlas fetch helper, and hb_gpu__* (double
underscore mid-identifier) for truly internal functions. Reverts the
decode_glyph/curve_counts refactor from the WGSL shader since it
was causing compilation failures.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
WGSL reserves identifiers starting with underscore. Rename all
_hb_gpu_* functions and _hb_gpu_glyph_info struct to use hbgpu_*
and HbGpuGlyphInfo prefixes.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Refactor library fragment shaders (GLSL, MSL, WGSL) to extract
_hb_gpu_decode_glyph and _hb_gpu_curve_counts helpers, used by
both hb_gpu_render and the debug visualization.
Debug mode (d key) shows per-pixel curve counts as a heatmap:
R = horizontal band curves, G = vertical band curves, B = text
coverage. Scale 0-8 curves maps to 0-1 intensity.
Also auto-generates demo shader headers via meson, and adds
set_debug to the renderer interface.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add a WebGPU variant of the web demo using Emscripten's
emdawnwebgpu port. Uses the WGSL shaders from the library API,
a storage buffer for the atlas (i16→i32 expansion on upload),
and Emscripten HTML5 APIs for input (no GLFW).
Also moves demo_shader_add_glyph_vertices to demo-shader.h as
static inline so demo-buffer.cc can be compiled without GL.
Build: bash util/gpu/web/build-webgpu.sh → out/webgpu.html
The existing WebGL build continues to work unchanged.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Port fragment and vertex shaders to WGSL. Key differences from
GLSL/MSL: no preprocessor (constants instead of #define), bitcast
instead of floatBitsToUint, storage buffer pointer parameter for
atlas, and emsPerPixel passed explicitly since fwidth() is only
available in the caller's fragment entry point.
Adds HB_GPU_SHADER_LANG_WGSL to the shader language enum.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add MSL shader translations of the Slug GPU text rasterizer, and a
Metal rendering backend for hb-gpu-demo selectable via --metal flag.
Library changes:
- Add HB_GPU_SHADER_LANG_MSL enum value
- Add hb-gpu-vertex.msl and hb-gpu-fragment.msl
- Extend gen-gpu-shader-artifacts.py for MSL
Demo changes:
- Add demo-metal.h/mm with CAMetalLayer rendering
- Add external atlas backend for non-GL paths
- Add demo_buffer_get_vertices for Metal draw path
- Skip GL init when using Metal (GLFW_NO_API)
- Add --metal command-line flag
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Compute a and b from unshifted (raw int16 × power-of-2) coordinates
so they are exact, then pass renderCoord-shifted p1 separately as
the constant term. This eliminates float rounding residuals that
made a non-zero for true lines, removing the need for an epsilon
threshold in the linear fallback.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Use 1.0/16384.0 instead of 1.0/65536.0 for detecting
near-degenerate quadratics in both horizontal and vertical
poly solvers, fixing rendering artifacts (thin white gaps)
at curve junctions caused by float rounding residuals in
the second-order coefficient.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>