Skip to content

Commit 304bc9c

Browse files
committed
avoid integer overflow in new ImageData
1 parent ac355ba commit 304bc9c

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

src/ImageData.cc

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ ImageData::ImageData(const Napi::CallbackInfo& info) : Napi::ObjectWrap<ImageDat
3030
Napi::TypedArray dataArray;
3131
uint32_t width;
3232
uint32_t height;
33-
int length;
33+
uint32_t length;
3434

3535
if (info[0].IsNumber() && info[1].IsNumber()) {
3636
width = info[0].As<Napi::Number>().Uint32Value();
@@ -43,6 +43,12 @@ ImageData::ImageData(const Napi::CallbackInfo& info) : Napi::ObjectWrap<ImageDat
4343
Napi::RangeError::New(env, "The source height is zero.").ThrowAsJavaScriptException();
4444
return;
4545
}
46+
if ((uint64_t)width * height > INT32_MAX / 4) {
47+
// INT32_MAX is what Firefox limits ImageData to
48+
std::string msg = "buffer exceeds " + std::to_string(INT32_MAX) + " bytes";
49+
Napi::Error::New(env, msg).ThrowAsJavaScriptException();
50+
return;
51+
}
4652
length = width * height * 4; // ImageData(w, h) constructor assumes 4 BPP; documented.
4753

4854
dataArray = Napi::Uint8Array::New(env, length, napi_uint8_clamped_array);

test/canvas.test.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@ const {
1616
loadImage,
1717
registerFont,
1818
Canvas,
19-
deregisterAllFonts
19+
deregisterAllFonts,
20+
ImageData
2021
} = require('../')
2122

2223
function assertApprox(actual, expected, tol) {
@@ -999,6 +1000,12 @@ describe('Canvas', function () {
9991000
})
10001001
})
10011002

1003+
describe('ImageData', function () {
1004+
it('checks for overflow', function () {
1005+
assert.throws(() => new ImageData(0x80000001, 0x80000001))
1006+
})
1007+
})
1008+
10021009
describe('Context2d#measureText()', function () {
10031010
it('Context2d#measureText().width', function () {
10041011
const canvas = createCanvas(20, 20)

0 commit comments

Comments
 (0)