Skip to content

Commit 9d89215

Browse files
committed
bound the curves of arcs and the points paths are made of in renderSVG
1 parent 980f094 commit 9d89215

4 files changed

Lines changed: 108 additions & 5 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
# Changelog
22

3+
## 3.20.5
4+
5+
### Fixes
6+
7+
- **`Image.renderSVG()`** bounds the points paths are made of. An arc between far-apart ends gets a radius of half their distance and was drawn with as many curves as that radius took: a 139-byte path (`M 1e25 100 A 40 30 20 1 1 160 100`, stroked) ran the process out of memory. An arc now gets at most 64 curves a turn (from a radius of about 6e9, more than any output resolves), and the points of all paths (path data read, curves flattened, also of each copy drawn through `<use>`) count against 2^25 plus 4 per pixel of the output in one render, and 2^21 in one path (a text's glyphs excepted). More throw a `RangeError` ("SVG too complex").
8+
39
## 3.20.4
410

511
### Deprecated

‎src/render/svg.ts‎

Lines changed: 44 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -186,10 +186,17 @@ export function render(source: string | Uint8Array, mode: 'scale' | 'width' | 'h
186186
outWidth = Math.max(1, outWidth);
187187
outHeight = Math.max(1, outHeight);
188188

189-
const canvas = new Layer(outWidth, outHeight);
190-
// (a transform on the root element (SVG 2) applies before the viewBox mapping)
191-
doc.renderRoot([outWidth / width, 0, 0, outHeight / height, 0, 0], canvas, 0);
192-
return { width: outWidth, height: outHeight, pixels: canvas.toRGBA() };
189+
// (a nested render, of an SVG embedded as an image, takes its points from the render it is in)
190+
const outermost = pointsLeft === Infinity;
191+
if (outermost) pointsLeft = MAX_POINTS + POINTS_PER_PIXEL * outWidth * outHeight;
192+
try {
193+
const canvas = new Layer(outWidth, outHeight);
194+
// (a transform on the root element (SVG 2) applies before the viewBox mapping)
195+
doc.renderRoot([outWidth / width, 0, 0, outHeight / height, 0, 0], canvas, 0);
196+
return { width: outWidth, height: outHeight, pixels: canvas.toRGBA() };
197+
} finally {
198+
if (outermost) pointsLeft = Infinity;
199+
}
193200
}
194201

195202
/** a decoded image, RGBA */
@@ -1027,6 +1034,7 @@ class Document {
10271034
if (!(err instanceof RangeError)) throw err;
10281035
}
10291036
}
1037+
if (layout) for (const span of layout.spans) glyphPaths.add(span.glyphs);
10301038
this.texts.set(node, { style, width: viewport.width, height: viewport.height, scale, layout });
10311039
return layout;
10321040
}
@@ -1372,6 +1380,7 @@ class Document {
13721380
if (!layout) return null;
13731381
const path: PathCommand[] = [];
13741382
for (const span of layout.spans) if (span.visible) for (const part of [...span.before, { path: span.glyphs }, ...span.after]) path.push(...part.path);
1383+
glyphPaths.add(path);
13751384
return path.length ? path : null;
13761385
}
13771386

@@ -3105,6 +3114,20 @@ function shapePath(node: XNode, viewport: Viewport, fontSize: number): PathComma
31053114
return null;
31063115
}
31073116

3117+
// the most points paths may be made of and flattened to in one render: 2^25 and 4 per pixel of the output (a curve
3118+
// gets up to 512, and an arc between far-apart ends, with a radius of half their distance, got as many curves as it
3119+
// took: a 139-byte path ran the process out of memory). What is left of it in the render that runs
3120+
// and 2^21 in one path (its points are in memory at once; a text's glyphs excepted)
3121+
const MAX_POINTS = 2 ** 25, POINTS_PER_PIXEL = 4, MAX_PATH_POINTS = 2 ** 21;
3122+
let pointsLeft = Infinity;
3123+
const glyphPaths = new WeakSet<PathCommand[]>();
3124+
3125+
/** counts points against the render's budget */
3126+
function chargePoints(points: number): void {
3127+
if ((pointsLeft -= points) < 0)
3128+
throw new RangeError(`SVG too complex: its paths are made of more points than a render of this size allows (${MAX_POINTS} and ${POINTS_PER_PIXEL} per output pixel)`);
3129+
}
3130+
31083131
function parsePath(d: string): PathCommand[] {
31093132
const path: PathCommand[] = [];
31103133
// numbers stay strings so compact arc flags can be split later
@@ -3116,6 +3139,8 @@ function parsePath(d: string): PathCommand[] {
31163139
end = m.index + m[0].length;
31173140
items.push(m[1] ? { command: m[1] } : m[2]);
31183141
}
3142+
// (reading takes about the time of flattening 2 points a number or command)
3143+
chargePoints(2 * items.length);
31193144

31203145
let i = 0;
31213146
let command: string | null = null;
@@ -3267,8 +3292,12 @@ function arcToCubics(path: PathCommand[], x1: number, y1: number, rx: number, ry
32673292
else if (sweep && delta < 0) delta += 2 * Math.PI;
32683293

32693294
// as many cubics as kurbo makes for usvg (at a tolerance of 0.1), which places mid markers at their ends
3270-
const perTurn = Math.max(Math.pow(1.1163 * Math.max(rx, ry) / 0.1, 1 / 6), 3.999999);
3295+
// (at most 64 a turn, from a radius of about 6e9, more than any output resolves: the count grew with the radius
3296+
// without a limit)
3297+
const perTurn = Math.min(Math.max(Math.pow(1.1163 * Math.max(rx, ry) / 0.1, 1 / 6), 3.999999), 64);
32713298
const segments = Math.max(1, Math.ceil(perTurn * Math.abs(delta) / (2 * Math.PI)));
3299+
// (a curve's command takes the memory of about 4 points)
3300+
chargePoints(4 * segments);
32723301
const step = delta / segments;
32733302
const k = 4 / 3 * Math.tan(step / 4);
32743303

@@ -3287,6 +3316,13 @@ function arcToCubics(path: PathCommand[], x1: number, y1: number, rx: number, ry
32873316

32883317
// flattens path commands into polylines: [{points: [x, y, ...], closed}]
32893318
function flatten(path: PathCommand[], tolerance: number): Subpath[] {
3319+
let pathPoints = 0;
3320+
const limited = !glyphPaths.has(path);
3321+
const count = (points: number): void => {
3322+
chargePoints(points);
3323+
if (limited && (pathPoints += points) > MAX_PATH_POINTS)
3324+
throw new RangeError(`SVG too complex: a path is made of more than ${MAX_PATH_POINTS} points`);
3325+
};
32903326
const subpaths: Subpath[] = [];
32913327
let current: Subpath | null = null;
32923328
let x = 0, y = 0, sx = 0, sy = 0;
@@ -3302,9 +3338,11 @@ function flatten(path: PathCommand[], tolerance: number): Subpath[] {
33023338
case 'M':
33033339
x = sx = command[1];
33043340
y = sy = command[2];
3341+
count(1);
33053342
current = start(x, y);
33063343
break;
33073344
case 'L':
3345+
count(1);
33083346
if (!current) current = start(x, y);
33093347
x = command[1];
33103348
y = command[2];
@@ -3316,6 +3354,7 @@ function flatten(path: PathCommand[], tolerance: number): Subpath[] {
33163354
const ddx = Math.max(Math.abs(x - 2 * c1x + c2x), Math.abs(c1x - 2 * c2x + ex));
33173355
const ddy = Math.max(Math.abs(y - 2 * c1y + c2y), Math.abs(c1y - 2 * c2y + ey));
33183356
const n = Math.min(512, Math.max(1, Math.ceil(Math.sqrt(0.75 * Math.hypot(ddx, ddy) / tolerance))));
3357+
count(n);
33193358
for (let i = 1; i <= n; i++) {
33203359
const t = i / n, mt = 1 - t;
33213360
current.points.push(

‎tests/svg-arcs.js‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
const fs = require('fs');
2+
const os = require('os');
3+
const path = require('path');
4+
const child_process = require('child_process');
5+
6+
// arcs between far-apart ends get a radius of half their distance, and were drawn with as many curves as it takes, and
7+
// flattened to as many points: a 139-byte path ran the process out of memory. Each case runs in its own process with 1
8+
// GB of heap, so that a failure can't take the test runner with it
9+
const NS = 'xmlns="http://www.w3.org/2000/svg"';
10+
const svg = body => `<svg viewBox="0 0 200 200" width="200" height="200" ${NS}>${body}</svg>`;
11+
const cases = {
12+
'stroked arc from 1e25': svg('<path d="M 1e25 100 A 40 30 20 1 1 160 100" fill="none" stroke="red"/>'),
13+
'stroked arc from 301e30': svg('<path d="M 301e30 100 A 40 30 20 1 1 160 100" fill="none" stroke="red"/>'),
14+
'1000 arcs between 1e12 and -1e12': svg(`<path d="M -1e12 100${Array.from({length: 1000}, (_, i) => i & 1 ? 'A1 1 0 1 1-1e12 100' : 'A1 1 0 1 1 1e12 100').join('')}" fill="none" stroke="red"/>`),
15+
'20000 arcs between 1e30 and -1e30': svg(`<path d="M -1e30 100${Array.from({length: 20000}, (_, i) => i & 1 ? 'A1 1 0 1 1-1e30 100' : 'A1 1 0 1 1 1e30 100').join('')}"/>`),
16+
'circle of radius 1e30': svg('<circle cx="100" cy="100" r="1e30" fill="none" stroke="red"/>'),
17+
};
18+
19+
const panic = message => {
20+
console.error(message);
21+
process.exit(1);
22+
};
23+
24+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'svg-arcs-'));
25+
const [command, ...flags] = typeof Deno !== 'undefined' ? [process.execPath, 'run', '-A', '--v8-flags=--max-old-space-size=1024'] : [process.execPath, ...(process.versions.bun ? [] : ['--max-old-space-size=1024'])];
26+
try {
27+
for (const [name, document] of Object.entries(cases)) {
28+
const file = path.join(dir, 'case.svg');
29+
fs.writeFileSync(file, document);
30+
const begin = Date.now();
31+
let output;
32+
try {
33+
output = JSON.parse(child_process.execFileSync(command, [...flags, './tests/util/render-svg.js', file], {timeout: 60000, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe']}).trim());
34+
} catch (err) {
35+
panic(`${name}: crashed (${err.signal || err.status})`);
36+
}
37+
if (output.result !== 'ok' && !/too complex/.test(output.result)) panic(`${name}: ${output.result}`);
38+
if (output.mb > 768) panic(`${name}: took ${output.mb} MB`);
39+
if (Date.now() - begin > 20000) panic(`${name}: took ${Date.now() - begin} ms`);
40+
console.log(name, output.result.slice(0, 60), Date.now() - begin, 'ms', output.mb, 'MB');
41+
}
42+
} finally {
43+
fs.rmSync(dir, {recursive: true, force: true});
44+
}

‎tests/util/render-svg.js‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// renders the SVG in the file given and prints the result and the peak memory as JSON (run by tests/svg-arcs.js)
2+
const fs = require('fs');
3+
const {Image} = require('../..');
4+
5+
(async () => {
6+
const svg = fs.readFileSync(process.argv[2], 'utf8');
7+
let result = 'ok';
8+
try {
9+
await Image.renderSVG(svg, {width: 50});
10+
} catch (err) {
11+
result = `${err.constructor.name}: ${err.message}`;
12+
}
13+
console.log(JSON.stringify({result, mb: Math.round(process.memoryUsage().rss / 2 ** 20)}));
14+
})();

0 commit comments

Comments
 (0)