Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions paligemma/image.cc
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,11 @@ const char* ParseUnsigned(const char* pos, const char* end, size_t& num) {
}
num = 0;
for (; pos < end && std::isdigit(*pos); ++pos) {
num *= 10;
num += *pos - '0';
const size_t digit = *pos - '0';
if (num > (SIZE_MAX - digit) / 10) {
return nullptr; // overflow
}
num = num * 10 + digit;
}
return pos;
}
Expand Down Expand Up @@ -136,6 +139,14 @@ bool Image::ReadPPM(const hwy::Span<const char>& buf) {
return false;
}
++pos;
if (width == 0 || height == 0) {
HWY_ABORT("Invalid zero dimension\n");
return false;
}
if (width > SIZE_MAX / 3 || width * 3 > SIZE_MAX / height) {
HWY_ABORT("Image dimensions overflow\n");
return false;
}
const size_t data_size = width * height * 3;
if (buf.cend() - pos < static_cast<ptrdiff_t>(data_size)) {
std::cerr << "Insufficient data remaining\n";
Expand Down
7 changes: 6 additions & 1 deletion util/basics.h
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,12 @@ struct Extents2D {
constexpr Extents2D() : rows(0), cols(0) {}
constexpr Extents2D(size_t rows, size_t cols) : rows(rows), cols(cols) {}

size_t Area() const { return rows * cols; }
size_t Area() const {
if (rows != 0 && cols > SIZE_MAX / rows) {
HWY_ABORT("Tensor dimension overflow: rows=%zu cols=%zu", rows, cols);
}
return rows * cols;
}

size_t rows;
size_t cols;
Expand Down
Loading