[cairo] Charge compositing operations to the glyph budget

hb-cairo's per-glyph work budget was spent only on emitted path segments,
so a COLRv1 font could pay once for a clip outline (push_clip_glyph) and
then have cairo re-rasterize it for every PaintSolid/gradient/group
composite under it, up to the COLR edge limit.  That is the
multiplication of limits the shared budget in hb-limits.hh exists to
prevent: a 2 KB font kept hb-view busy for over a minute on one glyph.

Charge every composite in the cairo backend, where the cost is incurred
and where the sibling backends already charge per operation (hb-raster
charges pixel area per paint).  hb_cairo_context_t now counts the
segments of the current path and keeps a stack of the clip paths in
force, maintained by the push_clip_* callbacks and pop_clip; spend_paint()
charges every fill, paint, group and gradient with (1 + segments) times a
per-source weight, squared when more than one path is in force since
cairo then intersects the paths per operation.  These segment and clip
counts are inputs to the existing budget_remaining counter; they are not
a separate per-callback limit.  The weights (HB_BUDGET_512 for
solid/group, 1024 for linear/radial gradients, a new HB_BUDGET_8192 for
the sweep mesh pattern) follow per-composite timings measured on
cairo 1.18.

Nested color glyphs are already painted inline by the color_glyph
callback, so their composites are charged against the clips in force at
that point; no change is needed there.

Behaviour change: a glyph whose composites exceed the budget (about 32k
segment-composites, roughly a second of cairo time at hb-view's default
size) is truncated best-effort, as outline work already is.  All glyphs
of the COLRv1 glyf (static and variable) and CFF2 test fonts render
byte-identically through hb-view with and without this change.

A regression test with a generated 3 KB font is added to
test/api/test-cairo.c alongside its fontTools generator; it finishes in
about a second once the paints are charged and guards against
reintroduction through the meson test timeout rather than a
discriminating assertion.

Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-38OVH0N4.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Behdad EsfahbodandClaude Opus 4.8 committed 2026-10-30 14:53:31 -06:00
1 parent f69c05ea38
commit 022a9e475a
6 files changed
+178 -6

No files matched your search

+53
View File
@@ -29,6 +29,7 @@
#include "hb.hh"
#include "hb-cairo.h"
#include "hb-vector.hh"
struct hb_cairo_budget_t
@@ -88,10 +89,62 @@ struct hb_cairo_context_t
bool spend (unsigned int cost, unsigned int mult = 1)
{ return hb_budget_spend (budget->budget_remaining, cost, mult); }
/* One emitted path segment. Also counted, so that the compositing
* operations that cairo later performs with the path can be charged. */
bool spend_segment ()
{
if (unlikely (!spend (HB_BUDGET_1)))
return false;
path_segments++;
return true;
}
/* One compositing operation: a fill, a paint, or a composited group.
* Cairo rasterizes the path being filled and every clip path in force
* anew for each of them, walking every segment through the scanlines it
* crosses; with more than one path it first intersects them, which is
* quadratic in their segments. Charge accordingly, so that a font
* cannot pay for a clip outline once and reuse it for thousands of
* paints. WEIGHT is the relative cost of a span of the source being
* composited. These counters feed the existing budget_remaining; they
* are not a separate per-callback limit. */
bool spend_paint (unsigned int weight = HB_BUDGET_512)
{
unsigned paths = clip.paths + !!path_segments;
unsigned segments = clip.segments + path_segments;
path_segments = 0;
return spend (1 + segments, hb_max (weight, paths > 1 ? segments : 0u));
}
/* The current path becomes a clip, in force until the matching pop_clip. */
void push_clip ()
{
if (unlikely (!clip_stack.push_or_fail (clip)))
budget->budget_remaining = -1;
clip.paths += !!path_segments;
clip.segments += path_segments;
path_segments = 0;
}
void pop_clip ()
{
if (likely (clip_stack.length))
clip = clip_stack.pop ();
}
cairo_scaled_font_t *scaled_font;
cairo_t *cr;
hb_map_t *color_cache;
hb_cairo_budget_t *budget;
/* Segments of the current path, and of the clip paths in force. */
unsigned path_segments = 0;
struct clip_t
{
unsigned paths = 0;
unsigned segments = 0;
} clip;
hb_vector_t<clip_t> clip_stack;
};
static inline cairo_operator_t
+31 -6
View File
@@ -55,7 +55,7 @@ hb_cairo_move_to (hb_draw_funcs_t *dfuncs HB_UNUSED,
void *user_data HB_UNUSED)
{
hb_cairo_context_t *c = (hb_cairo_context_t *) draw_data;
if (unlikely (!c->spend (HB_BUDGET_1)))
if (unlikely (!c->spend_segment ()))
return;
cairo_move_to (c->cr, (double) to_x, (double) to_y);
@@ -69,7 +69,7 @@ hb_cairo_line_to (hb_draw_funcs_t *dfuncs HB_UNUSED,
void *user_data HB_UNUSED)
{
hb_cairo_context_t *c = (hb_cairo_context_t *) draw_data;
if (unlikely (!c->spend (HB_BUDGET_1)))
if (unlikely (!c->spend_segment ()))
return;
cairo_line_to (c->cr, (double) to_x, (double) to_y);
@@ -85,7 +85,7 @@ hb_cairo_cubic_to (hb_draw_funcs_t *dfuncs HB_UNUSED,
void *user_data HB_UNUSED)
{
hb_cairo_context_t *c = (hb_cairo_context_t *) draw_data;
if (unlikely (!c->spend (HB_BUDGET_1)))
if (unlikely (!c->spend_segment ()))
return;
cairo_curve_to (c->cr,
@@ -101,7 +101,7 @@ hb_cairo_close_path (hb_draw_funcs_t *dfuncs HB_UNUSED,
void *user_data HB_UNUSED)
{
hb_cairo_context_t *c = (hb_cairo_context_t *) draw_data;
if (unlikely (!c->spend (HB_BUDGET_1)))
if (unlikely (!c->spend_segment ()))
return;
cairo_close_path (c->cr);
@@ -220,7 +220,8 @@ hb_cairo_fill_glyph (hb_paint_funcs_t *pfuncs HB_UNUSED,
hb_font_draw_glyph (font, glyph, hb_cairo_draw_get_funcs (), c);
cairo_close_path (cr);
_hb_cairo_set_source_color (c, use_foreground, color);
cairo_fill (cr);
if (likely (c->spend_paint ()))
cairo_fill (cr);
cairo_restore (cr);
}
@@ -258,6 +259,7 @@ hb_cairo_push_clip_glyph (hb_paint_funcs_t *pfuncs HB_UNUSED,
cairo_close_path (cr);
cairo_clip (cr);
c->push_clip ();
}
static void
@@ -274,6 +276,13 @@ hb_cairo_push_clip_rectangle (hb_paint_funcs_t *pfuncs HB_UNUSED,
(double) xmin, (double) ymin,
(double) (xmax - xmin), (double) (ymax - ymin));
cairo_clip (cr);
/* Cairo keeps an axis-aligned rectangle as a box, not as a path. */
cairo_matrix_t m;
cairo_get_matrix (cr, &m);
if (m.xy || m.yx)
c->path_segments += 4;
c->push_clip ();
}
static hb_draw_funcs_t *
@@ -301,6 +310,7 @@ hb_cairo_push_clip_path_end (hb_paint_funcs_t *pfuncs HB_UNUSED,
cairo_close_path (cr);
cairo_clip (cr);
c->push_clip ();
}
static void
@@ -312,6 +322,7 @@ hb_cairo_pop_clip (hb_paint_funcs_t *pfuncs HB_UNUSED,
cairo_t *cr = c->cr;
cairo_restore (cr);
c->pop_clip ();
}
static void
@@ -337,7 +348,8 @@ hb_cairo_pop_group (hb_paint_funcs_t *pfuncs HB_UNUSED,
cairo_pop_group_to_source (cr);
cairo_set_operator (cr, _hb_paint_composite_mode_to_cairo (mode));
cairo_paint (cr);
if (likely (c->spend_paint ()))
cairo_paint (cr);
cairo_restore (cr);
}
@@ -352,6 +364,9 @@ hb_cairo_paint_color (hb_paint_funcs_t *pfuncs HB_UNUSED,
hb_cairo_context_t *c = (hb_cairo_context_t *) paint_data;
cairo_t *cr = c->cr;
if (unlikely (!c->spend_paint ()))
return;
_hb_cairo_set_source_color (c, use_foreground, color);
cairo_paint (cr);
}
@@ -383,6 +398,9 @@ hb_cairo_paint_linear_gradient (hb_paint_funcs_t *pfuncs HB_UNUSED,
{
hb_cairo_context_t *c = (hb_cairo_context_t *) paint_data;
if (unlikely (!c->spend_paint (HB_BUDGET_1024)))
return;
_hb_cairo_paint_linear_gradient (c, color_line, x0, y0, x1, y1, x2, y2);
}
@@ -396,6 +414,9 @@ hb_cairo_paint_radial_gradient (hb_paint_funcs_t *pfuncs HB_UNUSED,
{
hb_cairo_context_t *c = (hb_cairo_context_t *) paint_data;
if (unlikely (!c->spend_paint (HB_BUDGET_1024)))
return;
_hb_cairo_paint_radial_gradient (c, color_line, x0, y0, r0, x1, y1, r1);
}
@@ -409,6 +430,10 @@ hb_cairo_paint_sweep_gradient (hb_paint_funcs_t *pfuncs HB_UNUSED,
{
hb_cairo_context_t *c = (hb_cairo_context_t *) paint_data;
/* The sweep is a mesh pattern, which cairo rasterizes per paint. */
if (unlikely (!c->spend_paint (HB_BUDGET_8192)))
return;
_hb_cairo_paint_sweep_gradient (c, color_line, x0, y0, start_angle, end_angle);
}
+1
View File
@@ -188,6 +188,7 @@
#define HB_BUDGET_256 256u
#define HB_BUDGET_512 512u
#define HB_BUDGET_1024 1024u
#define HB_BUDGET_8192 8192u
/* The common finite default for one top-level glyph rendering session.
* Nested outline and paint work shares the same live counter. */
Binary file not shown.
@@ -0,0 +1,44 @@
"""Generate a COLRv1 glyph that paints thousands of layers under one clip glyph."""
from pathlib import Path
from fontTools.fontBuilder import FontBuilder
from fontTools.colorLib.builder import buildCOLR, buildCPAL
from fontTools.pens.ttGlyphPen import TTGlyphPen
def build(num_points, num_layers, filename):
fb = FontBuilder(1000, isTTF=True)
names = [".notdef", "A", "clip"]
fb.setupGlyphOrder(names)
fb.setupCharacterMap({0x41: "A"})
# A sawtooth contour: every edge crosses every scanline of the glyph.
pen = TTGlyphPen(None)
pen.moveTo((0, 0))
for i in range(1, num_points):
pen.lineTo((i * 1000 // num_points, 1000 if i % 2 else 0))
pen.closePath()
fb.setupGlyf({".notdef": TTGlyphPen(None).glyph(), "A": TTGlyphPen(None).glyph(), "clip": pen.glyph()})
fb.setupHorizontalMetrics({name: (1000, 0) for name in names})
fb.setupHorizontalHeader(ascent=800, descent=-200)
fb.setupNameTable({"familyName": "COLR Clip Paint Budget", "styleName": "Regular"})
fb.setupOS2(
sTypoAscender=800, sTypoDescender=-200, usWinAscent=800, usWinDescent=200
)
fb.setupPost()
# PaintColrLayers nests as 255-wide lists; identical lists share one
# LayerList range, so the glyph stays small however many layers it paints.
solid = dict(Format=2, PaletteIndex=0, Alpha=1)
layers = [dict(Format=1, Layers=[solid] * 255)] * (num_layers // 255)
paints = {
"A": dict(Format=10, Glyph="clip", Paint=dict(Format=1, Layers=layers)),
}
fb.font["COLR"] = buildCOLR(
paints,
version=1,
glyphMap=fb.font.getReverseGlyphMap(),
)
fb.font["CPAL"] = buildCPAL([[(1.0, 0.0, 0.0, 1.0)]])
fb.save(filename)
build(300, 63 * 255, Path(__file__).with_name("colr-clip-paint-budget.ttf"))
+49
View File
@@ -213,6 +213,54 @@ test_hb_cairo_glyphs_from_buffer_clusters (void)
}
}
/* One clip glyph of 300 points with 15830 solid paints under it. Cairo
* rasterizes the clip path anew for every paint, so the paints must be
* charged to the glyph budget or this takes over a minute. The test has
* no discriminating assertion; it guards against reintroduction through
* the meson test timeout, finishing in about a second once the paints
* are charged. */
static void
test_hb_cairo_paint_budget (void)
{
#ifdef HB_TEST_CAIRO_TSAN
g_test_skip ("Cairo user-font rendering has a pre-existing lock-order inversion under TSan");
return;
#endif
hb_face_t *face = hb_test_open_font_file ("fonts/colr-clip-paint-budget.ttf");
cairo_font_face_t *cairo_face = hb_cairo_font_face_create_for_face (face);
cairo_surface_t *surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, 256, 256);
cairo_t *cr = cairo_create (surface);
cairo_set_font_face (cr, cairo_face);
cairo_set_font_size (cr, 256);
cairo_glyph_t glyph = {1, 0, 256};
cairo_show_glyphs (cr, &glyph, 1);
cairo_surface_flush (surface);
g_assert_cmpint (cairo_status (cr), ==, CAIRO_STATUS_SUCCESS);
g_assert_cmpint (cairo_surface_status (surface), ==, CAIRO_STATUS_SUCCESS);
/* The budget truncates the repeated paints but keeps the first ones. */
const unsigned char *data = cairo_image_surface_get_data (surface);
int stride = cairo_image_surface_get_stride (surface);
gboolean painted = FALSE;
for (int y = 0; y < 256 && !painted; y++)
for (int x = 0; x < 256; x++)
if (data[y * stride + x * 4 + 3])
{
painted = TRUE;
break;
}
g_assert_true (painted);
cairo_destroy (cr);
cairo_surface_destroy (surface);
cairo_font_face_destroy (cairo_face);
hb_face_destroy (face);
}
int
main (int argc, char **argv)
{
@@ -221,6 +269,7 @@ main (int argc, char **argv)
hb_test_add (test_hb_cairo_color_glyph_cycle);
hb_test_add (test_hb_cairo_face_lifecycle);
hb_test_add (test_hb_cairo_glyphs_from_buffer_clusters);
hb_test_add (test_hb_cairo_paint_budget);
return hb_test_run ();
}