Skip to content

Commit

Permalink
Make sure that fraction addition and subtraction stays in valid range…
Browse files Browse the repository at this point in the history
… (Clusterfuzz Issue 59453)
  • Loading branch information
farindk committed Oct 13, 2023
1 parent 7e4aacb commit c2d2c6b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
22 changes: 18 additions & 4 deletions libheif/box.cc
Original file line number Diff line number Diff line change
Expand Up @@ -70,14 +70,27 @@ Fraction::Fraction(uint32_t num, uint32_t den)
*this = Fraction(int32_t(num), int32_t(den));
}

Fraction::Fraction(int64_t num, int64_t den)
{
while (num < std::numeric_limits<int32_t>::min() || num > std::numeric_limits<int32_t>::max() ||
den < std::numeric_limits<int32_t>::min() || den > std::numeric_limits<int32_t>::max()) {
num = (num + (num>=0 ? 1 : -1)) / 2;
den = (den + (den>=0 ? 1 : -1)) / 2;
}

numerator = static_cast<int32_t>(num);
denominator = static_cast<int32_t>(den);
}

Fraction Fraction::operator+(const Fraction& b) const
{
if (denominator == b.denominator) {
return Fraction{numerator + b.numerator, denominator};
}
else {
return Fraction{numerator * b.denominator + b.numerator * denominator,
denominator * b.denominator};
int64_t n = int64_t{numerator} * b.denominator + int64_t{b.numerator} * denominator;
int64_t d = int64_t{denominator} * b.denominator;
return Fraction{n,d};
}
}

Expand All @@ -87,8 +100,9 @@ Fraction Fraction::operator-(const Fraction& b) const
return Fraction{numerator - b.numerator, denominator};
}
else {
return Fraction{numerator * b.denominator - b.numerator * denominator,
denominator * b.denominator};
int64_t n = int64_t{numerator} * b.denominator - int64_t{b.numerator} * denominator;
int64_t d = int64_t{denominator} * b.denominator;
return Fraction{n,d};
}
}

Expand Down
3 changes: 3 additions & 0 deletions libheif/box.h
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ class Fraction
// may only use values up to int32_t maximum
Fraction(uint32_t num, uint32_t den);

// Values will be reduced until they fit into int32_t.
Fraction(int64_t num, int64_t den);

Fraction operator+(const Fraction&) const;

Fraction operator-(const Fraction&) const;
Expand Down

0 comments on commit c2d2c6b

Please sign in to comment.