Skip to content

Commit

Permalink
Handle image size overflow
Browse files Browse the repository at this point in the history
  • Loading branch information
mcheshkov committed Oct 6, 2020
1 parent 9fedfcc commit 14ac462
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/PngImg.cc
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,20 @@ void PngImg::ReadInfo_(PngReadStruct& rs) {
///
void PngImg::InitStorage_() {
rowPtrs_.resize(info_.height, nullptr);
data_ = new png_byte[info_.height * info_.rowbytes];
// Extend height and rowbytes from uint32_t to size_t to avoid multiplication overflow when size_t is larger
size_t h = info_.height;
size_t rb = info_.rowbytes;
// We need to make sure that info_.height * info_.rowbytes will not overflow size_t
// Unfotunately, there's no simple and portable way to do this in C++
// For integer division of positive numbers a * b > c <==> a > c / b holds
if (h > std::numeric_limits<size_t>::max() / rb) {
// TODO Propagate this exception to JS, and test it
throw std::runtime_error("Image is too large to allocate single buffer");
}
data_ = new png_byte[h * rb];

for(size_t i = 0; i < info_.height; ++i) {
rowPtrs_[i] = data_ + i * info_.rowbytes;
rowPtrs_[i] = data_ + i * rb;
}
}

Expand Down

0 comments on commit 14ac462

Please sign in to comment.