diff options
author | Caolán McNamara <caolanm@redhat.com> | 2017-03-21 11:23:09 +0000 |
---|---|---|
committer | Caolán McNamara <caolanm@redhat.com> | 2017-03-22 11:23:46 +0000 |
commit | 4f0b226600fdad4e5aef9313fe8754c765cfee42 (patch) | |
tree | 18fce6798d07c39dbf6d33d1d309497d3a60235c /tools | |
parent | b7abbc07f21dc1e318b1acab44de8144d8ab34eb (diff) |
check for overflow in multiply
gcc >= 5 and clang have builtins for this
msvc has safeint.h and functions in the msl::utilties namespace
otherwise fall back to certs demo implementations
Change-Id: I6001a278c24b0be4b381d933d256f01f91ead55d
Reviewed-on: https://gerrit.libreoffice.org/35505
Tested-by: Jenkins <ci@libreoffice.org>
Reviewed-by: Caolán McNamara <caolanm@redhat.com>
Tested-by: Caolán McNamara <caolanm@redhat.com>
Diffstat (limited to 'tools')
-rw-r--r-- | tools/source/generic/fract.cxx | 14 |
1 files changed, 9 insertions, 5 deletions
diff --git a/tools/source/generic/fract.cxx b/tools/source/generic/fract.cxx index 068a2b6429a8..bc9bef467e86 100644 --- a/tools/source/generic/fract.cxx +++ b/tools/source/generic/fract.cxx @@ -21,6 +21,7 @@ #include <tools/debug.hxx> #include <tools/lineend.hxx> #include <tools/stream.hxx> +#include <o3tl/safeint.hxx> #include <rtl/ustring.hxx> #include <sal/log.hxx> #include <osl/diagnose.h> @@ -172,7 +173,7 @@ Fraction& Fraction::operator -= ( const Fraction& rVal ) namespace { - template<typename T> void multiply_by(boost::rational<T>& i, const boost::rational<T>& r) + template<typename T> bool checked_multiply_by(boost::rational<T>& i, const boost::rational<T>& r) { // Protect against self-modification T num = r.numerator(); @@ -181,10 +182,13 @@ namespace // Avoid overflow and preserve normalization T gcd1 = boost::integer::gcd(i.numerator(), den); T gcd2 = boost::integer::gcd(num, i.denominator()); - num = (i.numerator() / gcd1) * (num / gcd2); - den = (i.denominator() / gcd2) * (den / gcd1); + bool fail = false; + fail |= o3tl::checked_multiply(i.numerator() / gcd1, num / gcd2, num); + fail |= o3tl::checked_multiply(i.denominator() / gcd2, den / gcd1, den); i.assign(num, den); + + return fail; } } @@ -199,9 +203,9 @@ Fraction& Fraction::operator *= ( const Fraction& rVal ) return *this; } - multiply_by(mpImpl->value, rVal.mpImpl->value); + bool bFail = checked_multiply_by(mpImpl->value, rVal.mpImpl->value); - if (HasOverflowValue()) + if (bFail || HasOverflowValue()) { mpImpl->valid = false; } |