Skip to content

Commit 79aefee

Browse files
committed
count bitmap glyphs before decoding them and bound their scaled size in renderText
1 parent 568a279 commit 79aefee

8 files changed

Lines changed: 77 additions & 18 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ Upgrading from 3.x? Upgrade to the latest 3.x release first, fix the deprecation
137137
### Fixes
138138

139139
- `renderSVG()` bounds the points paths are made of: an arc between far-apart ends is drawn with at most 64 curves a turn (a 139-byte path, `M 1e25 100 A 40 30 20 1 1 160 100`, stroked, ran the process out of memory), and the curves of arcs and the points of all paths, also of each copy drawn through `<use>`, count against 2^25 points plus 4 per pixel of the output in one render and 2^21 in one path. Reading path data and placing text along a `<textPath>` count, too, and SVGs embedded as images share the budget of the render they are in. More throw a `LimitError` (which a text's layout no longer takes for a damaged font). A path drawn through `<use>` is read once a render instead of once a copy.
140-
- SVG text: the glyph outlines of all texts count against the render's points before they are made, 16 points a command (20 texts of 1,000 characters of a complex font ran the process out of memory), so very long texts need a larger output; many `<tspan>`s in one `<text>` take linear time (10,000 took 20 s); a `<textPath>` on a long path renders at a normal size; bitmap emoji (CBDT, sbix) are decoded once a render instead of once a draw (copies through `<use>` took minutes), at most 2048x2048 pixels each (larger ones aren't drawn, also in `renderText()`: one that said 16383x16383 ran the process out of memory).
140+
- SVG text: the glyph outlines of all texts count against the render's points before they are made, 16 points a command (20 texts of 1,000 characters of a complex font ran the process out of memory), so very long texts need a larger output; many `<tspan>`s in one `<text>` take linear time (10,000 took 20 s); a `<textPath>` on a long path renders at a normal size; bitmap emoji (CBDT, sbix) are decoded once a render instead of once a draw (copies through `<use>` took minutes), at most 2048x2048 pixels each (larger ones aren't drawn, also in `renderText()`: one that said 16383x16383 ran the process out of memory), and counted before they are decoded, also damaged ones. `renderText()` counts its bitmap glyphs' decoding and scaling against 2^28 pixels plus 64 per pixel of the image (a `LimitError`), and doesn't draw a glyph scaled to more than 4 times the image (a strike at ppem 1 made a 32768x32768 copy for a 10x10 image).
141141
- `renderText()` takes linear time for many combining marks and lines (400,000 lines took minutes).
142142
- Very long text (50,000 characters in SVG, 200,000 combining marks or lines in `renderText()`) no longer overflows the call stack or says the font is damaged.
143143
- Binary data and dates of other realms (iframes, `node:vm`, Jest) are accepted; objects that only claim to be one by `Symbol.toStringTag` aren't, and a detached buffer throws a `TypeError` that says so.

‎src/render/color.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,19 @@ export interface ColorLayer {
99
}
1010

1111
/** a glyph's PNG and where it goes, in pixels of its strike */
12+
/** the most pixels a bitmap glyph may have: emoji fonts have strikes of 160 at most, one that said 16383x16383 took 1 GB */
13+
export const MAX_BITMAP_GLYPH_PIXELS = 2048 * 2048;
14+
15+
/**
16+
* The pixels a bitmap glyph's PNG says it has (its header), what decoding it costs whether it succeeds or not; NaN if it
17+
* isn't a PNG
18+
*/
19+
export function bitmapPixels(png: Uint8Array): number {
20+
if (png.length < 24 || png[12] !== 0x49 || png[13] !== 0x48 || png[14] !== 0x44 || png[15] !== 0x52) return NaN;
21+
const view = new DataView(png.buffer, png.byteOffset, png.length);
22+
return view.getUint32(16) * view.getUint32(20);
23+
}
24+
1225
export interface BitmapGlyph {
1326
png: Uint8Array;
1427
/** pixels per em of the strike */

‎src/render/svg.ts‎

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import { FontFace, FontStyle, fontFace, givenFontFace, damaged, layOutText, pars
2323
import { rasterizeGlyph } from './text.ts';
2424
import { renderPaintGlyph } from './colr.ts';
2525
import { decodeSync as decodePNG } from '../codecs/png.ts';
26+
import { bitmapPixels, MAX_BITMAP_GLYPH_PIXELS } from './color.ts';
2627
import { MAX_PIXELS, LimitError } from '../util/limits.ts';
2728

2829
const UNSUPPORTED = new Set(['filter', 'pattern', 'marker', 'foreignObject', 'script', 'style', 'title', 'desc', 'metadata',
@@ -3412,25 +3413,26 @@ const glyphPaths = new WeakSet<PathCommand[]>();
34123413
// the bitmap glyphs decoded in the render that runs, by the font data they are in and their offset there (a strike's
34133414
// glyphs are looked up for each size), and their pixels
34143415
let decodedBitmaps: WeakMap<ArrayBufferLike, Map<number, RasterImage | null>> | null = null, decodedBitmapPixels = 0;
3415-
// the most pixels a bitmap glyph may have (emoji fonts have strikes of 160 at most; one that said 16383x16383 took 1 GB),
3416-
// and the pixels of the bitmap glyphs kept in a render (decoded once, an emoji drawn through <use> was decoded for each
3416+
// the pixels of the bitmap glyphs kept in a render (decoded once, an emoji drawn through <use> was decoded for each
34173417
// copy; with its premultiplied floats a pixel takes 20 bytes, so some 80 MB)
3418-
const MAX_BITMAP_GLYPH_PIXELS = 2048 * 2048, MAX_KEPT_BITMAP_PIXELS = 2 ** 22;
3418+
const MAX_KEPT_BITMAP_PIXELS = 2 ** 22;
34193419

34203420
/** a bitmap glyph's PNG decoded, or null if it can't be (damaged or too large) */
34213421
function decodedBitmap(png: Uint8Array): RasterImage | null {
34223422
let kept = decodedBitmaps?.get(png.buffer);
34233423
const key = png.byteOffset * 2 ** 21 + Math.min(png.length, 2 ** 21 - 1);
34243424
const cached = kept?.get(key);
34253425
if (cached !== undefined) return cached;
3426-
let decoded: RasterImage | null;
3427-
try {
3428-
decoded = decodePNG(png, MAX_BITMAP_GLYPH_PIXELS);
3429-
// (decoding takes about the time of painting its pixels 4 times)
3430-
charge(4 * decoded.width * decoded.height);
3431-
} catch (err) {
3432-
if (err instanceof LimitError && paintLeft < 0) throw err;
3433-
decoded = null;
3426+
let decoded: RasterImage | null = null;
3427+
// (decoding takes about the time of painting its pixels 4 times, counted before it, as damaged ones take it too)
3428+
const declared = bitmapPixels(png);
3429+
if (declared <= MAX_BITMAP_GLYPH_PIXELS) {
3430+
charge(4 * Math.max(declared, 1));
3431+
try {
3432+
decoded = decodePNG(png, MAX_BITMAP_GLYPH_PIXELS);
3433+
} catch {
3434+
decoded = null;
3435+
}
34343436
}
34353437
const pixels = decoded ? decoded.width * decoded.height : 0;
34363438
if (decodedBitmaps && decodedBitmapPixels + pixels <= MAX_KEPT_BITMAP_PIXELS) {

‎src/render/text.ts‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
import { Font, PathCommand } from './font.ts';
77
import { Hinter } from './hinting.ts';
8-
import { ColorLayer, BitmapGlyph, parseColorLayers, parseBitmaps } from './color.ts';
8+
import { ColorLayer, BitmapGlyph, parseColorLayers, parseBitmaps, bitmapPixels, MAX_BITMAP_GLYPH_PIXELS } from './color.ts';
99
import { Direction } from './buffer.ts';
1010
import { ShapeFont, shapeFont, shapeRun, isDefaultIgnorableCodepoint, Features } from './shape.ts';
1111
import { shown } from '../util/options.ts';
@@ -248,7 +248,9 @@ async function layOut(fonts: Uint8Array[], size: number, text: string, layout: L
248248
}
249249

250250
// the box's size, else the text's: text without ink (empty, spaces) still makes an image, a transparent pixel wide
251-
const width = layout.width ?? Math.max(1, Math.ceil(Math.max(0, ...visible.map(line => line.extent))));
251+
let extent = 0;
252+
for (const line of visible) extent = Math.max(extent, line.extent);
253+
const width = layout.width ?? Math.max(1, Math.ceil(extent));
252254
const height = layout.height ?? visible.length * lineHeight;
253255
// the lines placed vertically in the box (a line taller than the box is cut off as the alignment says)
254256
const free = height - visible.length * lineHeight;
@@ -257,6 +259,9 @@ async function layOut(fonts: Uint8Array[], size: number, text: string, layout: L
257259
throw new LimitError(`Text too large to render: ${width + 2 * pad}x${height + 2 * pad} pixels exceed the limit of ${maxPixels} (the render options' maxPixels)`);
258260
const coverage = new Uint8Array(width * height);
259261
let color: Uint8ClampedArray | null = null;
262+
// the pixels bitmap glyphs may be decoded and scaled to: 2^28 and 64 per pixel of the image, like the paint of an
263+
// SVG (1000 glyphs of 2048x2048 without advance took 39 s for a 32x1 image)
264+
const budget = { left: 2 ** 28 + 64 * width * height, image: width * height };
260265

261266
for (const [n, line] of visible.entries()) {
262267
const align = layout.horizontalAlign ?? (line.rtl ? 'right' : 'left');
@@ -279,7 +284,7 @@ async function layOut(fonts: Uint8Array[], size: number, text: string, layout: L
279284
const key = 'bitmap' in g.color ? '0' : `${subpixel}:${foreground}`;
280285
let bitmap = g.colors.get(key);
281286
if (bitmap === undefined) g.colors.set(key, bitmap = 'bitmap' in g.color
282-
? await scaledBitmap(g.color.bitmap, size / g.color.bitmap.ppem)
287+
? await scaledBitmap(g.color.bitmap, size / g.color.bitmap.ppem, budget)
283288
: 'layers' in g.color ? layeredGlyph(g, g.color.layers, subpixel / SUBPIXELS, foreground)
284289
: paintedGlyph(g, subpixel / SUBPIXELS, foreground));
285290
if (bitmap) blitColor(color ??= new Uint8ClampedArray(width * height * 4), width, height, bitmap, pixel + bitmap.left, y - bitmap.top);
@@ -497,15 +502,25 @@ function layOutParagraph(p: Paragraph, layout: Layout, font: (i: number) => Size
497502
}
498503

499504
// a bitmap glyph's PNG decoded and scaled from its strike to the font size, premultiplied
500-
async function scaledBitmap(glyph: BitmapGlyph, scale: number): Promise<ColorBitmap | null> {
505+
async function scaledBitmap(glyph: BitmapGlyph, scale: number, budget: { left: number, image: number }): Promise<ColorBitmap | null> {
506+
const spend = (pixels: number): void => {
507+
if ((budget.left -= pixels) < 0) throw new LimitError('Text too complex: its bitmap glyphs take more pixels to decode and scale than an image of this size allows (2^28 and 64 per pixel)');
508+
};
509+
// (decoding takes about the time of 4 pixels a pixel, counted before it, as damaged ones take it too)
510+
const declared = bitmapPixels(glyph.png);
511+
if (!(declared <= MAX_BITMAP_GLYPH_PIXELS)) return null;
512+
spend(4 * Math.max(declared, 1));
501513
let decoded;
502514
try {
503-
// (at most 2048x2048: emoji fonts have strikes of 160 at most, and one that said 16383x16383 took 1 GB)
504-
decoded = await decodePNG(glyph.png, 2048 * 2048);
515+
decoded = await decodePNG(glyph.png, MAX_BITMAP_GLYPH_PIXELS);
505516
} catch {
506517
return null;
507518
}
508519
const width = Math.max(1, Math.round(decoded.width * scale)), height = Math.max(1, Math.round(decoded.height * scale));
520+
// (scaled from its strike to the size: from a strike at ppem 1, a 2048x2048 bitmap became 32768x32768 at size 16. A
521+
// glyph larger than 4 times the image, and than the largest bitmap glyph, isn't drawn)
522+
if (width * height > Math.max(MAX_BITMAP_GLYPH_PIXELS, 4 * budget.image)) return null;
523+
spend(width * height);
509524
const data = new Uint8ClampedArray(width * height * 4);
510525
resample(new Uint8ClampedArray(decoded.pixels.buffer, decoded.pixels.byteOffset, decoded.pixels.length), decoded.width, decoded.height, width, height, TRIANGLE, data, true);
511526
premultiply(data);

‎tests/bitmap-glyph-limits.js‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
const fs = require('fs');
2+
const {Image, LimitError} = require('..');
3+
4+
// bitmap glyphs (sbix, CBDT) are bounded like the rest of a render: their PNGs count before they are decoded (also those
5+
// that turn out damaged), and a glyph scaled from a tiny strike to the font size isn't allocated past the output
6+
const panic = message => {
7+
console.error(message);
8+
process.exit(1);
9+
};
10+
const font = name => fs.readFileSync(`${__dirname}/fonts/bitmap-limits/${name}.ttf`);
11+
const text = n => Array.from({length: n}, (_, i) => String.fromCodePoint(0xe000 + i)).join('');
12+
const NS = 'xmlns="http://www.w3.org/2000/svg"';
13+
14+
(async () => {
15+
for (const [name, run] of [
16+
// a strike at ppem 1 of a 2048x2048 PNG, drawn at size 16: a 32768x32768 copy (4 GB) for a 10x10 image
17+
['a glyph from a strike at ppem 1', () => Image.renderText('\ue000', {font: font('p1'), size: 16, width: 10, height: 10, maxPixels: 100})],
18+
// 1000 glyphs of valid 2048x2048 PNGs without advance, in a 32x1 image: 39 s of decoding
19+
['1000 large glyphs without advance', () => Image.renderText(text(1000), {font: font('z-ok-1000'), size: 1, maxPixels: 100})],
20+
// 1000 records of one damaged PNG with different ends: each was decoded, and never counted, as it failed
21+
['1000 damaged glyphs in an SVG', () => Image.renderSVG(`<svg ${NS} width="10" height="10"><style>@font-face{font-family:f;src:url(data:font/ttf;base64,${font('sh-bad-1000').toString('base64')})}</style><text y="8" font-family="f" font-size="1">${text(2000)}</text></svg>`, {maxPixels: 100})],
22+
]) {
23+
const begin = Date.now(), before = process.memoryUsage().rss;
24+
const result = await run().then(() => 'ok', err => err);
25+
if (result !== 'ok' && !(result instanceof LimitError)) panic(`${name}: ${result}`);
26+
if (Date.now() - begin > 10000) panic(`${name}: took ${Date.now() - begin} ms`);
27+
if (process.memoryUsage().rss - before > 768 * 2 ** 20) panic(`${name}: took ${(process.memoryUsage().rss - before) >> 20} MB`);
28+
}
29+
})();

‎tests/fonts/bitmap-limits/p1.ttf‎

19.9 KB
Binary file not shown.
53 KB
Binary file not shown.
53 KB
Binary file not shown.

0 commit comments

Comments
 (0)