Skip to content

Commit 14a7447

Browse files
Merge pull request #896 from sharadboni:fix-tensor-ppm-overflow
PiperOrigin-RevId: 901370544
2 parents 221d8df + c4d14db commit 14a7447

2 files changed

Lines changed: 19 additions & 3 deletions

File tree

paligemma/image.cc

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,11 @@ const char* ParseUnsigned(const char* pos, const char* end, size_t& num) {
8383
}
8484
num = 0;
8585
for (; pos < end && std::isdigit(*pos); ++pos) {
86-
num *= 10;
87-
num += *pos - '0';
86+
const size_t digit = *pos - '0';
87+
if (num > (SIZE_MAX - digit) / 10) {
88+
return nullptr; // overflow
89+
}
90+
num = num * 10 + digit;
8891
}
8992
return pos;
9093
}
@@ -136,6 +139,14 @@ bool Image::ReadPPM(const hwy::Span<const char>& buf) {
136139
return false;
137140
}
138141
++pos;
142+
if (width == 0 || height == 0) {
143+
HWY_ABORT("Invalid zero dimension\n");
144+
return false;
145+
}
146+
if (width > SIZE_MAX / 3 || width * 3 > SIZE_MAX / height) {
147+
HWY_ABORT("Image dimensions overflow\n");
148+
return false;
149+
}
139150
const size_t data_size = width * height * 3;
140151
if (buf.cend() - pos < static_cast<ptrdiff_t>(data_size)) {
141152
std::cerr << "Insufficient data remaining\n";

util/basics.h

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,12 @@ struct Extents2D {
9797
constexpr Extents2D() : rows(0), cols(0) {}
9898
constexpr Extents2D(size_t rows, size_t cols) : rows(rows), cols(cols) {}
9999

100-
size_t Area() const { return rows * cols; }
100+
size_t Area() const {
101+
if (rows != 0 && cols > SIZE_MAX / rows) {
102+
HWY_ABORT("Tensor dimension overflow: rows=%zu cols=%zu", rows, cols);
103+
}
104+
return rows * cols;
105+
}
101106

102107
size_t rows;
103108
size_t cols;

0 commit comments

Comments
 (0)