Skip to content

Commit 14ac462

Browse files
committed
Handle image size overflow
1 parent 9fedfcc commit 14ac462

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

src/PngImg.cc

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,10 +60,20 @@ void PngImg::ReadInfo_(PngReadStruct& rs) {
6060
///
6161
void PngImg::InitStorage_() {
6262
rowPtrs_.resize(info_.height, nullptr);
63-
data_ = new png_byte[info_.height * info_.rowbytes];
63+
// Extend height and rowbytes from uint32_t to size_t to avoid multiplication overflow when size_t is larger
64+
size_t h = info_.height;
65+
size_t rb = info_.rowbytes;
66+
// We need to make sure that info_.height * info_.rowbytes will not overflow size_t
67+
// Unfotunately, there's no simple and portable way to do this in C++
68+
// For integer division of positive numbers a * b > c <==> a > c / b holds
69+
if (h > std::numeric_limits<size_t>::max() / rb) {
70+
// TODO Propagate this exception to JS, and test it
71+
throw std::runtime_error("Image is too large to allocate single buffer");
72+
}
73+
data_ = new png_byte[h * rb];
6474

6575
for(size_t i = 0; i < info_.height; ++i) {
66-
rowPtrs_[i] = data_ + i * info_.rowbytes;
76+
rowPtrs_[i] = data_ + i * rb;
6777
}
6878
}
6979

0 commit comments

Comments
 (0)