createImageData() with negative width and height aborts the process

Open Beginner friendly
#2,633 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
76/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
javascript, node.js
Domain
backend, web-dev

Research direction

Start by reading Context2d::CreateImageData, named in the issue, and trace how it converts width and height before allocating the buffer. Compare the behavior with the cited Canvas specification and reproduce the two negative-size cases from the provided script. Done means both return positive dimensions without throwing or aborting; add or run focused tests for those cases.

Written by the indexing model from the issue text.

Description

Version of node-canvas

v3.2.3, v4.0.0-rc3 (master 6cc138b)

Version of node

v26.13.0

What operating system does the problem occur on?

Linux

Steps to reproduce

ctx.createImageData(sw, sh) should use the absolute values of sw and sh. In node-canvas a negative size is read as a huge unsigned number: one negative argument throws, and two negative arguments abort Node with a fatal out-of-memory error that cannot be caught.

const { createCanvas } = require('canvas');
const ctx = createCanvas(10, 10).getContext('2d');
try { const d = ctx.createImageData(-3, 2); console.log(d.width, d.height); } catch (e) { console.log('threw:', e.message); }
const d = ctx.createImageData(-3, -2);
console.log(d.width, d.height);

Run node repro.js; echo $?:

Actual:

threw: buffer exceeds 2147483647 bytes
FATAL ERROR: v8::ArrayBuffer::New Allocation failed - process out of memory
...
134

Expected (matches Chrome 153):

3 2
3 2
Additional information/comments

Per https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createimagedata, createImageData(sw, sh) must initialize the ImageData object with the absolute magnitude of sw and sh. In Context2d::CreateImageData, the arguments are converted with Uint32Value(), turning -3 into 4294967293; with two negative values Bpp * width * height overflows int64_t, bypasses the nBytes > INT32_MAX check, and passes a negative nBytes to Napi::ArrayBuffer::New.

Credit: https://ucsbplse.github.io/

Dominant language
JavaScript
Stars
10.7k
Forks
1.2k
PR merge metrics
No merged PRs in 30d

Getting set up

  • No Dockerfile or Docker Compose file
  • Has a pull request template
  • No contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from Automattic/node-canvas

All issues in Automattic/node-canvas

Similar issues

More JavaScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.