OLD | NEW |
1 // Copyright 2014 The Chromium Authors. All rights reserved. | 1 // Copyright 2014 The Chromium Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 #ifndef PDFIUM_THIRD_PARTY_BASE_SAFE_MATH_H_ | 5 #ifndef PDFIUM_THIRD_PARTY_BASE_NUMERICS_SAFE_MATH_H_ |
6 #define PDFIUM_THIRD_PARTY_BASE_SAFE_MATH_H_ | 6 #define PDFIUM_THIRD_PARTY_BASE_NUMERICS_SAFE_MATH_H_ |
7 | 7 |
8 #include "safe_math_impl.h" | 8 #include <stddef.h> |
| 9 |
| 10 #include <limits> |
| 11 #include <type_traits> |
| 12 |
| 13 #include "third_party/base/numerics/safe_math_impl.h" |
9 | 14 |
10 namespace pdfium { | 15 namespace pdfium { |
11 namespace base { | 16 namespace base { |
12 namespace internal { | 17 namespace internal { |
13 | 18 |
14 // CheckedNumeric implements all the logic and operators for detecting integer | 19 // CheckedNumeric<> implements all the logic and operators for detecting integer |
15 // boundary conditions such as overflow, underflow, and invalid conversions. | 20 // boundary conditions such as overflow, underflow, and invalid conversions. |
16 // The CheckedNumeric type implicitly converts from floating point and integer | 21 // The CheckedNumeric type implicitly converts from floating point and integer |
17 // data types, and contains overloads for basic arithmetic operations (i.e.: +, | 22 // data types, and contains overloads for basic arithmetic operations (i.e.: +, |
18 // -, *, /, %). | 23 // -, *, / for all types and %, <<, >>, &, |, ^ for integers). Type promotions |
| 24 // are a slightly modified version of the standard C arithmetic rules with the |
| 25 // two differences being that there is no default promotion to int and bitwise |
| 26 // logical operations always return an unsigned of the wider type. |
| 27 // |
| 28 // You may also use one of the variadic convenience functions, which accept |
| 29 // standard arithmetic or CheckedNumeric types, perform arithmetic operations, |
| 30 // and return a CheckedNumeric result. The supported functions are: |
| 31 // CheckAdd() - Addition. |
| 32 // CheckSub() - Subtraction. |
| 33 // CheckMul() - Multiplication. |
| 34 // CheckDiv() - Division. |
| 35 // CheckMod() - Modulous (integer only). |
| 36 // CheckLsh() - Left integer shift (integer only). |
| 37 // CheckRsh() - Right integer shift (integer only). |
| 38 // CheckAnd() - Bitwise AND (integer only with unsigned result). |
| 39 // CheckOr() - Bitwise OR (integer only with unsigned result). |
| 40 // CheckXor() - Bitwise XOR (integer only with unsigned result). |
| 41 // CheckMax() - Maximum of supplied arguments. |
| 42 // CheckMin() - Minimum of supplied arguments. |
| 43 // |
| 44 // The unary negation, increment, and decrement operators are supported, along |
| 45 // with the following unary arithmetic methods, which return a new |
| 46 // CheckedNumeric as a result of the operation: |
| 47 // Abs() - Absolute value. |
| 48 // UnsignedAbs() - Absolute value as an equal-width unsigned underlying type |
| 49 // (valid for only integral types). |
| 50 // Max() - Returns whichever is greater of the current instance or argument. |
| 51 // The underlying return type is whichever has the greatest magnitude. |
| 52 // Min() - Returns whichever is lowest of the current instance or argument. |
| 53 // The underlying return type is whichever has can represent the lowest |
| 54 // number in the smallest width (e.g. int8_t over unsigned, int over |
| 55 // int8_t, and float over int). |
19 // | 56 // |
20 // The following methods convert from CheckedNumeric to standard numeric values: | 57 // The following methods convert from CheckedNumeric to standard numeric values: |
21 // IsValid() - Returns true if the underlying numeric value is valid (i.e. has | 58 // AssignIfValid() - Assigns the underlying value to the supplied destination |
22 // has not wrapped and is not the result of an invalid conversion). | 59 // pointer if the value is currently valid and within the range |
23 // ValueOrDie() - Returns the underlying value. If the state is not valid this | 60 // supported by the destination type. Returns true on success. |
24 // call will crash on a CHECK. | 61 // **************************************************************************** |
25 // ValueOrDefault() - Returns the current value, or the supplied default if the | 62 // * WARNING: All of the following functions return a StrictNumeric, which * |
26 // state is not valid. | 63 // * is valid for comparison and assignment operations, but will trigger a * |
27 // ValueFloating() - Returns the underlying floating point value (valid only | 64 // * compile failure on attempts to assign to a type of insufficient range. * |
28 // only for floating point CheckedNumeric types). | 65 // **************************************************************************** |
29 // | 66 // IsValid() - Returns true if the underlying numeric value is valid (i.e. has |
30 // Bitwise operations are explicitly not supported, because correct | 67 // has not wrapped and is not the result of an invalid conversion). |
31 // handling of some cases (e.g. sign manipulation) is ambiguous. Comparison | 68 // ValueOrDie() - Returns the underlying value. If the state is not valid this |
32 // operations are explicitly not supported because they could result in a crash | 69 // call will crash on a CHECK. |
33 // on a CHECK condition. You should use patterns like the following for these | 70 // ValueOrDefault() - Returns the current value, or the supplied default if the |
34 // operations: | 71 // state is not valid (will not trigger a CHECK). |
35 // Bitwise operation: | 72 // |
36 // CheckedNumeric<int> checked_int = untrusted_input_value; | 73 // The following wrapper functions can be used to avoid the template |
37 // int x = checked_int.ValueOrDefault(0) | kFlagValues; | 74 // disambiguator syntax when converting a destination type. |
38 // Comparison: | 75 // IsValidForType<>() in place of: a.template IsValid<Dst>() |
39 // CheckedNumeric<size_t> checked_size; | 76 // ValueOrDieForType<>() in place of: a.template ValueOrDie() |
40 // CheckedNumeric<int> checked_size = untrusted_input_value; | 77 // ValueOrDefaultForType<>() in place of: a.template ValueOrDefault(default) |
41 // checked_size = checked_size + HEADER LENGTH; | 78 // |
| 79 // The following are general utility methods that are useful for converting |
| 80 // between arithmetic types and CheckedNumeric types: |
| 81 // CheckedNumeric::Cast<Dst>() - Instance method returning a CheckedNumeric |
| 82 // derived from casting the current instance to a CheckedNumeric of |
| 83 // the supplied destination type. |
| 84 // MakeCheckedNum() - Creates a new CheckedNumeric from the underlying type of |
| 85 // the supplied arithmetic, CheckedNumeric, or StrictNumeric type. |
| 86 // |
| 87 // Comparison operations are explicitly not supported because they could result |
| 88 // in a crash on an unexpected CHECK condition. You should use patterns like the |
| 89 // following for comparisons: |
| 90 // CheckedNumeric<size_t> checked_size = untrusted_input_value; |
| 91 // checked_size += HEADER LENGTH; |
42 // if (checked_size.IsValid() && checked_size.ValueOrDie() < buffer_size) | 92 // if (checked_size.IsValid() && checked_size.ValueOrDie() < buffer_size) |
43 // Do stuff... | 93 // Do stuff... |
| 94 |
44 template <typename T> | 95 template <typename T> |
45 class CheckedNumeric { | 96 class CheckedNumeric { |
| 97 static_assert(std::is_arithmetic<T>::value, |
| 98 "CheckedNumeric<T>: T must be a numeric type."); |
| 99 |
46 public: | 100 public: |
47 typedef T type; | 101 using type = T; |
48 | 102 |
49 CheckedNumeric() {} | 103 constexpr CheckedNumeric() {} |
50 | 104 |
51 // Copy constructor. | 105 // Copy constructor. |
52 template <typename Src> | 106 template <typename Src> |
53 CheckedNumeric(const CheckedNumeric<Src>& rhs) | 107 constexpr CheckedNumeric(const CheckedNumeric<Src>& rhs) |
54 : state_(rhs.ValueUnsafe(), rhs.validity()) {} | 108 : state_(rhs.state_.value(), rhs.IsValid()) {} |
55 | 109 |
56 template <typename Src> | 110 template <typename Src> |
57 CheckedNumeric(Src value, RangeConstraint validity) | 111 friend class CheckedNumeric; |
58 : state_(value, validity) {} | |
59 | 112 |
60 // This is not an explicit constructor because we implicitly upgrade regular | 113 // This is not an explicit constructor because we implicitly upgrade regular |
61 // numerics to CheckedNumerics to make them easier to use. | 114 // numerics to CheckedNumerics to make them easier to use. |
62 template <typename Src> | 115 template <typename Src> |
63 CheckedNumeric(Src value) | 116 constexpr CheckedNumeric(Src value) // NOLINT(runtime/explicit) |
64 : state_(value) { | 117 : state_(value) { |
65 COMPILE_ASSERT(std::numeric_limits<Src>::is_specialized, | 118 static_assert(std::is_arithmetic<Src>::value, "Argument must be numeric."); |
66 argument_must_be_numeric); | 119 } |
67 } | 120 |
68 | 121 // This is not an explicit constructor because we want a seamless conversion |
69 // IsValid() is the public API to test if a CheckedNumeric is currently valid. | 122 // from StrictNumeric types. |
70 bool IsValid() const { return validity() == RANGE_VALID; } | 123 template <typename Src> |
71 | 124 constexpr CheckedNumeric( |
72 // ValueOrDie() The primary accessor for the underlying value. If the current | 125 StrictNumeric<Src> value) // NOLINT(runtime/explicit) |
73 // state is not valid it will CHECK and crash. | 126 : state_(static_cast<Src>(value)) {} |
74 T ValueOrDie() const { | 127 |
75 CHECK(IsValid()); | 128 // IsValid() - The public API to test if a CheckedNumeric is currently valid. |
76 return state_.value(); | 129 // A range checked destination type can be supplied using the Dst template |
77 } | 130 // parameter. |
78 | 131 template <typename Dst = T> |
79 // ValueOrDefault(T default_value) A convenience method that returns the | 132 constexpr bool IsValid() const { |
| 133 return state_.is_valid() && |
| 134 IsValueInRangeForNumericType<Dst>(state_.value()); |
| 135 } |
| 136 |
| 137 // AssignIfValid(Dst) - Assigns the underlying value if it is currently valid |
| 138 // and is within the range supported by the destination type. Returns true if |
| 139 // successful and false otherwise. |
| 140 template <typename Dst> |
| 141 constexpr bool AssignIfValid(Dst* result) const { |
| 142 return IsValid<Dst>() ? ((*result = static_cast<Dst>(state_.value())), true) |
| 143 : false; |
| 144 } |
| 145 |
| 146 // ValueOrDie() - The primary accessor for the underlying value. If the |
| 147 // current state is not valid it will CHECK and crash. |
| 148 // A range checked destination type can be supplied using the Dst template |
| 149 // parameter, which will trigger a CHECK if the value is not in bounds for |
| 150 // the destination. |
| 151 // The CHECK behavior can be overridden by supplying a handler as a |
| 152 // template parameter, for test code, etc. However, the handler cannot access |
| 153 // the underlying value, and it is not available through other means. |
| 154 template <typename Dst = T, class CheckHandler = CheckOnFailure> |
| 155 constexpr StrictNumeric<Dst> ValueOrDie() const { |
| 156 return IsValid<Dst>() ? static_cast<Dst>(state_.value()) |
| 157 : CheckHandler::template HandleFailure<Dst>(); |
| 158 } |
| 159 |
| 160 // ValueOrDefault(T default_value) - A convenience method that returns the |
80 // current value if the state is valid, and the supplied default_value for | 161 // current value if the state is valid, and the supplied default_value for |
81 // any other state. | 162 // any other state. |
82 T ValueOrDefault(T default_value) const { | 163 // A range checked destination type can be supplied using the Dst template |
83 return IsValid() ? state_.value() : default_value; | 164 // parameter. WARNING: This function may fail to compile or CHECK at runtime |
84 } | 165 // if the supplied default_value is not within range of the destination type. |
85 | 166 template <typename Dst = T, typename Src> |
86 // ValueFloating() - Since floating point values include their validity state, | 167 constexpr StrictNumeric<Dst> ValueOrDefault(const Src default_value) const { |
87 // we provide an easy method for extracting them directly, without a risk of | 168 return IsValid<Dst>() ? static_cast<Dst>(state_.value()) |
88 // crashing on a CHECK. | 169 : checked_cast<Dst>(default_value); |
89 T ValueFloating() const { | 170 } |
90 COMPILE_ASSERT(std::numeric_limits<T>::is_iec559, argument_must_be_float); | 171 |
91 return CheckedNumeric<T>::cast(*this).ValueUnsafe(); | 172 // Returns a checked numeric of the specified type, cast from the current |
92 } | 173 // CheckedNumeric. If the current state is invalid or the destination cannot |
93 | 174 // represent the result then the returned CheckedNumeric will be invalid. |
94 // validity() - DO NOT USE THIS IN EXTERNAL CODE - It is public right now for | 175 template <typename Dst> |
95 // tests and to avoid a big matrix of friend operator overloads. But the | 176 constexpr CheckedNumeric<typename UnderlyingType<Dst>::type> Cast() const { |
96 // values it returns are likely to change in the future. | 177 return *this; |
97 // Returns: current validity state (i.e. valid, overflow, underflow, nan). | 178 } |
98 // TODO(jschuh): crbug.com/332611 Figure out and implement semantics for | 179 |
99 // saturation/wrapping so we can expose this state consistently and implement | 180 // This friend method is available solely for providing more detailed logging |
100 // saturated arithmetic. | 181 // in the the tests. Do not implement it in production code, because the |
101 RangeConstraint validity() const { return state_.validity(); } | 182 // underlying values may change at any time. |
102 | 183 template <typename U> |
103 // ValueUnsafe() - DO NOT USE THIS IN EXTERNAL CODE - It is public right now | 184 friend U GetNumericValueForTest(const CheckedNumeric<U>& src); |
104 // for tests and to avoid a big matrix of friend operator overloads. But the | |
105 // values it returns are likely to change in the future. | |
106 // Returns: the raw numeric value, regardless of the current state. | |
107 // TODO(jschuh): crbug.com/332611 Figure out and implement semantics for | |
108 // saturation/wrapping so we can expose this state consistently and implement | |
109 // saturated arithmetic. | |
110 T ValueUnsafe() const { return state_.value(); } | |
111 | 185 |
112 // Prototypes for the supported arithmetic operator overloads. | 186 // Prototypes for the supported arithmetic operator overloads. |
113 template <typename Src> CheckedNumeric& operator+=(Src rhs); | 187 template <typename Src> |
114 template <typename Src> CheckedNumeric& operator-=(Src rhs); | 188 CheckedNumeric& operator+=(const Src rhs); |
115 template <typename Src> CheckedNumeric& operator*=(Src rhs); | 189 template <typename Src> |
116 template <typename Src> CheckedNumeric& operator/=(Src rhs); | 190 CheckedNumeric& operator-=(const Src rhs); |
117 template <typename Src> CheckedNumeric& operator%=(Src rhs); | 191 template <typename Src> |
118 | 192 CheckedNumeric& operator*=(const Src rhs); |
119 CheckedNumeric operator-() const { | 193 template <typename Src> |
120 RangeConstraint validity; | 194 CheckedNumeric& operator/=(const Src rhs); |
121 T value = CheckedNeg(state_.value(), &validity); | 195 template <typename Src> |
122 // Negation is always valid for floating point. | 196 CheckedNumeric& operator%=(const Src rhs); |
123 if (std::numeric_limits<T>::is_iec559) | 197 template <typename Src> |
124 return CheckedNumeric<T>(value); | 198 CheckedNumeric& operator<<=(const Src rhs); |
125 | 199 template <typename Src> |
126 validity = GetRangeConstraint(state_.validity() | validity); | 200 CheckedNumeric& operator>>=(const Src rhs); |
127 return CheckedNumeric<T>(value, validity); | 201 template <typename Src> |
128 } | 202 CheckedNumeric& operator&=(const Src rhs); |
129 | 203 template <typename Src> |
130 CheckedNumeric Abs() const { | 204 CheckedNumeric& operator|=(const Src rhs); |
131 RangeConstraint validity; | 205 template <typename Src> |
132 T value = CheckedAbs(state_.value(), &validity); | 206 CheckedNumeric& operator^=(const Src rhs); |
133 // Absolute value is always valid for floating point. | 207 |
134 if (std::numeric_limits<T>::is_iec559) | 208 constexpr CheckedNumeric operator-() const { |
135 return CheckedNumeric<T>(value); | 209 return CheckedNumeric<T>( |
136 | 210 NegateWrapper(state_.value()), |
137 validity = GetRangeConstraint(state_.validity() | validity); | 211 IsValid() && |
138 return CheckedNumeric<T>(value, validity); | 212 (!std::is_signed<T>::value || std::is_floating_point<T>::value || |
| 213 NegateWrapper(state_.value()) != |
| 214 std::numeric_limits<T>::lowest())); |
| 215 } |
| 216 |
| 217 constexpr CheckedNumeric operator~() const { |
| 218 return CheckedNumeric<decltype(InvertWrapper(T()))>( |
| 219 InvertWrapper(state_.value()), IsValid()); |
| 220 } |
| 221 |
| 222 constexpr CheckedNumeric Abs() const { |
| 223 return CheckedNumeric<T>( |
| 224 AbsWrapper(state_.value()), |
| 225 IsValid() && |
| 226 (!std::is_signed<T>::value || std::is_floating_point<T>::value || |
| 227 AbsWrapper(state_.value()) != std::numeric_limits<T>::lowest())); |
| 228 } |
| 229 |
| 230 template <typename U> |
| 231 constexpr CheckedNumeric<typename MathWrapper<CheckedMaxOp, T, U>::type> Max( |
| 232 const U rhs) const { |
| 233 using R = typename UnderlyingType<U>::type; |
| 234 using result_type = typename MathWrapper<CheckedMaxOp, T, U>::type; |
| 235 // TODO(jschuh): This can be converted to the MathOp version and remain |
| 236 // constexpr once we have C++14 support. |
| 237 return CheckedNumeric<result_type>( |
| 238 static_cast<result_type>( |
| 239 IsGreater<T, R>::Test(state_.value(), Wrapper<U>::value(rhs)) |
| 240 ? state_.value() |
| 241 : Wrapper<U>::value(rhs)), |
| 242 state_.is_valid() && Wrapper<U>::is_valid(rhs)); |
| 243 } |
| 244 |
| 245 template <typename U> |
| 246 constexpr CheckedNumeric<typename MathWrapper<CheckedMinOp, T, U>::type> Min( |
| 247 const U rhs) const { |
| 248 using R = typename UnderlyingType<U>::type; |
| 249 using result_type = typename MathWrapper<CheckedMinOp, T, U>::type; |
| 250 // TODO(jschuh): This can be converted to the MathOp version and remain |
| 251 // constexpr once we have C++14 support. |
| 252 return CheckedNumeric<result_type>( |
| 253 static_cast<result_type>( |
| 254 IsLess<T, R>::Test(state_.value(), Wrapper<U>::value(rhs)) |
| 255 ? state_.value() |
| 256 : Wrapper<U>::value(rhs)), |
| 257 state_.is_valid() && Wrapper<U>::is_valid(rhs)); |
| 258 } |
| 259 |
| 260 // This function is available only for integral types. It returns an unsigned |
| 261 // integer of the same width as the source type, containing the absolute value |
| 262 // of the source, and properly handling signed min. |
| 263 constexpr CheckedNumeric<typename UnsignedOrFloatForSize<T>::type> |
| 264 UnsignedAbs() const { |
| 265 return CheckedNumeric<typename UnsignedOrFloatForSize<T>::type>( |
| 266 SafeUnsignedAbs(state_.value()), state_.is_valid()); |
139 } | 267 } |
140 | 268 |
141 CheckedNumeric& operator++() { | 269 CheckedNumeric& operator++() { |
142 *this += 1; | 270 *this += 1; |
143 return *this; | 271 return *this; |
144 } | 272 } |
145 | 273 |
146 CheckedNumeric operator++(int) { | 274 CheckedNumeric operator++(int) { |
147 CheckedNumeric value = *this; | 275 CheckedNumeric value = *this; |
148 *this += 1; | 276 *this += 1; |
149 return value; | 277 return value; |
150 } | 278 } |
151 | 279 |
152 CheckedNumeric& operator--() { | 280 CheckedNumeric& operator--() { |
153 *this -= 1; | 281 *this -= 1; |
154 return *this; | 282 return *this; |
155 } | 283 } |
156 | 284 |
157 CheckedNumeric operator--(int) { | 285 CheckedNumeric operator--(int) { |
158 CheckedNumeric value = *this; | 286 CheckedNumeric value = *this; |
159 *this -= 1; | 287 *this -= 1; |
160 return value; | 288 return value; |
161 } | 289 } |
162 | 290 |
163 // These static methods behave like a convenience cast operator targeting | 291 // These perform the actual math operations on the CheckedNumerics. |
164 // the desired CheckedNumeric type. As an optimization, a reference is | 292 // Binary arithmetic operations. |
165 // returned when Src is the same type as T. | 293 template <template <typename, typename, typename> class M, |
166 template <typename Src> | 294 typename L, |
167 static CheckedNumeric<T> cast( | 295 typename R> |
168 Src u, | 296 static CheckedNumeric MathOp(const L lhs, const R rhs) { |
169 typename std::enable_if<std::numeric_limits<Src>::is_specialized, | 297 using Math = typename MathWrapper<M, L, R>::math; |
170 int>::type = 0) { | 298 T result = 0; |
171 return u; | 299 bool is_valid = |
172 } | 300 Wrapper<L>::is_valid(lhs) && Wrapper<R>::is_valid(rhs) && |
173 | 301 Math::Do(Wrapper<L>::value(lhs), Wrapper<R>::value(rhs), &result); |
174 template <typename Src> | 302 return CheckedNumeric<T>(result, is_valid); |
175 static CheckedNumeric<T> cast( | 303 }; |
176 const CheckedNumeric<Src>& u, | 304 |
177 typename std::enable_if<!std::is_same<Src, T>::value, int>::type = 0) { | 305 // Assignment arithmetic operations. |
178 return u; | 306 template <template <typename, typename, typename> class M, typename R> |
179 } | 307 CheckedNumeric& MathOp(const R rhs) { |
180 | 308 using Math = typename MathWrapper<M, T, R>::math; |
181 static const CheckedNumeric<T>& cast(const CheckedNumeric<T>& u) { return u; } | 309 T result = 0; // Using T as the destination saves a range check. |
| 310 bool is_valid = state_.is_valid() && Wrapper<R>::is_valid(rhs) && |
| 311 Math::Do(state_.value(), Wrapper<R>::value(rhs), &result); |
| 312 *this = CheckedNumeric<T>(result, is_valid); |
| 313 return *this; |
| 314 }; |
182 | 315 |
183 private: | 316 private: |
184 CheckedNumericState<T> state_; | 317 CheckedNumericState<T> state_; |
185 }; | 318 |
186 | 319 template <typename Src> |
187 // This is the boilerplate for the standard arithmetic operator overloads. A | 320 constexpr CheckedNumeric(Src value, bool is_valid) |
188 // macro isn't the prettiest solution, but it beats rewriting these five times. | 321 : state_(value, is_valid) {} |
189 // Some details worth noting are: | 322 |
190 // * We apply the standard arithmetic promotions. | 323 // These wrappers allow us to handle state the same way for both |
191 // * We skip range checks for floating points. | 324 // CheckedNumeric and POD arithmetic types. |
192 // * We skip range checks for destination integers with sufficient range. | 325 template <typename Src> |
193 // TODO(jschuh): extract these out into templates. | 326 struct Wrapper { |
194 #define BASE_NUMERIC_ARITHMETIC_OPERATORS(NAME, OP, COMPOUND_OP) \ | 327 static constexpr bool is_valid(Src) { return true; } |
195 /* Binary arithmetic operator for CheckedNumerics of the same type. */ \ | 328 static constexpr Src value(Src value) { return value; } |
196 template <typename T> \ | 329 }; |
197 CheckedNumeric<typename ArithmeticPromotion<T>::type> operator OP( \ | 330 |
198 const CheckedNumeric<T>& lhs, const CheckedNumeric<T>& rhs) { \ | 331 template <typename Src> |
199 typedef typename ArithmeticPromotion<T>::type Promotion; \ | 332 struct Wrapper<CheckedNumeric<Src>> { |
200 /* Floating point always takes the fast path */ \ | 333 static constexpr bool is_valid(const CheckedNumeric<Src> v) { |
201 if (std::numeric_limits<T>::is_iec559) \ | 334 return v.IsValid(); |
202 return CheckedNumeric<T>(lhs.ValueUnsafe() OP rhs.ValueUnsafe()); \ | 335 } |
203 if (IsIntegerArithmeticSafe<Promotion, T, T>::value) \ | 336 static constexpr Src value(const CheckedNumeric<Src> v) { |
204 return CheckedNumeric<Promotion>( \ | 337 return v.state_.value(); |
205 lhs.ValueUnsafe() OP rhs.ValueUnsafe(), \ | 338 } |
206 GetRangeConstraint(rhs.validity() | lhs.validity())); \ | 339 }; |
207 RangeConstraint validity = RANGE_VALID; \ | 340 |
208 T result = Checked##NAME(static_cast<Promotion>(lhs.ValueUnsafe()), \ | 341 template <typename Src> |
209 static_cast<Promotion>(rhs.ValueUnsafe()), \ | 342 struct Wrapper<StrictNumeric<Src>> { |
210 &validity); \ | 343 static constexpr bool is_valid(const StrictNumeric<Src>) { return true; } |
211 return CheckedNumeric<Promotion>( \ | 344 static constexpr Src value(const StrictNumeric<Src> v) { |
212 result, \ | 345 return static_cast<Src>(v); |
213 GetRangeConstraint(validity | lhs.validity() | rhs.validity())); \ | 346 } |
214 } \ | 347 }; |
215 /* Assignment arithmetic operator implementation from CheckedNumeric. */ \ | 348 }; |
216 template <typename T> \ | 349 |
217 template <typename Src> \ | 350 // Convenience functions to avoid the ugly template disambiguator syntax. |
218 CheckedNumeric<T>& CheckedNumeric<T>::operator COMPOUND_OP(Src rhs) { \ | 351 template <typename Dst, typename Src> |
219 *this = CheckedNumeric<T>::cast(*this) OP CheckedNumeric<Src>::cast(rhs); \ | 352 constexpr bool IsValidForType(const CheckedNumeric<Src> value) { |
220 return *this; \ | 353 return value.template IsValid<Dst>(); |
221 } \ | 354 } |
222 /* Binary arithmetic operator for CheckedNumeric of different type. */ \ | 355 |
223 template <typename T, typename Src> \ | 356 template <typename Dst, typename Src> |
224 CheckedNumeric<typename ArithmeticPromotion<T, Src>::type> operator OP( \ | 357 constexpr StrictNumeric<Dst> ValueOrDieForType( |
225 const CheckedNumeric<Src>& lhs, const CheckedNumeric<T>& rhs) { \ | 358 const CheckedNumeric<Src> value) { |
226 typedef typename ArithmeticPromotion<T, Src>::type Promotion; \ | 359 return value.template ValueOrDie<Dst>(); |
227 if (IsIntegerArithmeticSafe<Promotion, T, Src>::value) \ | 360 } |
228 return CheckedNumeric<Promotion>( \ | 361 |
229 lhs.ValueUnsafe() OP rhs.ValueUnsafe(), \ | 362 template <typename Dst, typename Src, typename Default> |
230 GetRangeConstraint(rhs.validity() | lhs.validity())); \ | 363 constexpr StrictNumeric<Dst> ValueOrDefaultForType( |
231 return CheckedNumeric<Promotion>::cast(lhs) \ | 364 const CheckedNumeric<Src> value, |
232 OP CheckedNumeric<Promotion>::cast(rhs); \ | 365 const Default default_value) { |
233 } \ | 366 return value.template ValueOrDefault<Dst>(default_value); |
234 /* Binary arithmetic operator for left CheckedNumeric and right numeric. */ \ | 367 } |
235 template <typename T, typename Src> \ | 368 |
236 CheckedNumeric<typename ArithmeticPromotion<T, Src>::type> operator OP( \ | 369 // These variadic templates work out the return types. |
237 const CheckedNumeric<T>& lhs, Src rhs) { \ | 370 // TODO(jschuh): Rip all this out once we have C++14 non-trailing auto support. |
238 typedef typename ArithmeticPromotion<T, Src>::type Promotion; \ | 371 template <template <typename, typename, typename> class M, |
239 if (IsIntegerArithmeticSafe<Promotion, T, Src>::value) \ | 372 typename L, |
240 return CheckedNumeric<Promotion>(lhs.ValueUnsafe() OP rhs, \ | 373 typename R, |
241 lhs.validity()); \ | 374 typename... Args> |
242 return CheckedNumeric<Promotion>::cast(lhs) \ | 375 struct ResultType; |
243 OP CheckedNumeric<Promotion>::cast(rhs); \ | 376 |
244 } \ | 377 template <template <typename, typename, typename> class M, |
245 /* Binary arithmetic operator for right numeric and left CheckedNumeric. */ \ | 378 typename L, |
246 template <typename T, typename Src> \ | 379 typename R> |
247 CheckedNumeric<typename ArithmeticPromotion<T, Src>::type> operator OP( \ | 380 struct ResultType<M, L, R> { |
248 Src lhs, const CheckedNumeric<T>& rhs) { \ | 381 using type = typename MathWrapper<M, L, R>::type; |
249 typedef typename ArithmeticPromotion<T, Src>::type Promotion; \ | 382 }; |
250 if (IsIntegerArithmeticSafe<Promotion, T, Src>::value) \ | 383 |
251 return CheckedNumeric<Promotion>(lhs OP rhs.ValueUnsafe(), \ | 384 template <template <typename, typename, typename> class M, |
252 rhs.validity()); \ | 385 typename L, |
253 return CheckedNumeric<Promotion>::cast(lhs) \ | 386 typename R, |
254 OP CheckedNumeric<Promotion>::cast(rhs); \ | 387 typename... Args> |
| 388 struct ResultType { |
| 389 using type = |
| 390 typename ResultType<M, typename ResultType<M, L, R>::type, Args...>::type; |
| 391 }; |
| 392 |
| 393 // Convience wrapper to return a new CheckedNumeric from the provided arithmetic |
| 394 // or CheckedNumericType. |
| 395 template <typename T> |
| 396 constexpr CheckedNumeric<typename UnderlyingType<T>::type> MakeCheckedNum( |
| 397 const T value) { |
| 398 return value; |
| 399 } |
| 400 |
| 401 // These implement the variadic wrapper for the math operations. |
| 402 template <template <typename, typename, typename> class M, |
| 403 typename L, |
| 404 typename R> |
| 405 CheckedNumeric<typename MathWrapper<M, L, R>::type> ChkMathOp(const L lhs, |
| 406 const R rhs) { |
| 407 using Math = typename MathWrapper<M, L, R>::math; |
| 408 return CheckedNumeric<typename Math::result_type>::template MathOp<M>(lhs, |
| 409 rhs); |
| 410 } |
| 411 |
| 412 // General purpose wrapper template for arithmetic operations. |
| 413 template <template <typename, typename, typename> class M, |
| 414 typename L, |
| 415 typename R, |
| 416 typename... Args> |
| 417 CheckedNumeric<typename ResultType<M, L, R, Args...>::type> |
| 418 ChkMathOp(const L lhs, const R rhs, const Args... args) { |
| 419 auto tmp = ChkMathOp<M>(lhs, rhs); |
| 420 return tmp.IsValid() ? ChkMathOp<M>(tmp, args...) |
| 421 : decltype(ChkMathOp<M>(tmp, args...))(tmp); |
| 422 }; |
| 423 |
| 424 // The following macros are just boilerplate for the standard arithmetic |
| 425 // operator overloads and variadic function templates. A macro isn't the nicest |
| 426 // solution, but it beats rewriting these over and over again. |
| 427 #define BASE_NUMERIC_ARITHMETIC_VARIADIC(NAME) \ |
| 428 template <typename L, typename R, typename... Args> \ |
| 429 CheckedNumeric<typename ResultType<Checked##NAME##Op, L, R, Args...>::type> \ |
| 430 Check##NAME(const L lhs, const R rhs, const Args... args) { \ |
| 431 return ChkMathOp<Checked##NAME##Op, L, R, Args...>(lhs, rhs, args...); \ |
255 } | 432 } |
256 | 433 |
257 BASE_NUMERIC_ARITHMETIC_OPERATORS(Add, +, += ) | 434 #define BASE_NUMERIC_ARITHMETIC_OPERATORS(NAME, OP, COMPOUND_OP) \ |
258 BASE_NUMERIC_ARITHMETIC_OPERATORS(Sub, -, -= ) | 435 /* Binary arithmetic operator for all CheckedNumeric operations. */ \ |
259 BASE_NUMERIC_ARITHMETIC_OPERATORS(Mul, *, *= ) | 436 template <typename L, typename R, \ |
260 BASE_NUMERIC_ARITHMETIC_OPERATORS(Div, /, /= ) | 437 typename std::enable_if<IsCheckedOp<L, R>::value>::type* = \ |
261 BASE_NUMERIC_ARITHMETIC_OPERATORS(Mod, %, %= ) | 438 nullptr> \ |
262 | 439 CheckedNumeric<typename MathWrapper<Checked##NAME##Op, L, R>::type> \ |
| 440 operator OP(const L lhs, const R rhs) { \ |
| 441 return decltype(lhs OP rhs)::template MathOp<Checked##NAME##Op>(lhs, rhs); \ |
| 442 } \ |
| 443 /* Assignment arithmetic operator implementation from CheckedNumeric. */ \ |
| 444 template <typename L> \ |
| 445 template <typename R> \ |
| 446 CheckedNumeric<L>& CheckedNumeric<L>::operator COMPOUND_OP(const R rhs) { \ |
| 447 return MathOp<Checked##NAME##Op>(rhs); \ |
| 448 } \ |
| 449 /* Variadic arithmetic functions that return CheckedNumeric. */ \ |
| 450 BASE_NUMERIC_ARITHMETIC_VARIADIC(NAME) |
| 451 |
| 452 BASE_NUMERIC_ARITHMETIC_OPERATORS(Add, +, +=) |
| 453 BASE_NUMERIC_ARITHMETIC_OPERATORS(Sub, -, -=) |
| 454 BASE_NUMERIC_ARITHMETIC_OPERATORS(Mul, *, *=) |
| 455 BASE_NUMERIC_ARITHMETIC_OPERATORS(Div, /, /=) |
| 456 BASE_NUMERIC_ARITHMETIC_OPERATORS(Mod, %, %=) |
| 457 BASE_NUMERIC_ARITHMETIC_OPERATORS(Lsh, <<, <<=) |
| 458 BASE_NUMERIC_ARITHMETIC_OPERATORS(Rsh, >>, >>=) |
| 459 BASE_NUMERIC_ARITHMETIC_OPERATORS(And, &, &=) |
| 460 BASE_NUMERIC_ARITHMETIC_OPERATORS(Or, |, |=) |
| 461 BASE_NUMERIC_ARITHMETIC_OPERATORS(Xor, ^, ^=) |
| 462 BASE_NUMERIC_ARITHMETIC_VARIADIC(Max) |
| 463 BASE_NUMERIC_ARITHMETIC_VARIADIC(Min) |
| 464 |
| 465 #undef BASE_NUMERIC_ARITHMETIC_VARIADIC |
263 #undef BASE_NUMERIC_ARITHMETIC_OPERATORS | 466 #undef BASE_NUMERIC_ARITHMETIC_OPERATORS |
264 | 467 |
| 468 // These are some extra StrictNumeric operators to support simple pointer |
| 469 // arithmetic with our result types. Since wrapping on a pointer is always |
| 470 // bad, we trigger the CHECK condition here. |
| 471 template <typename L, typename R> |
| 472 L* operator+(L* lhs, const StrictNumeric<R> rhs) { |
| 473 uintptr_t result = CheckAdd(reinterpret_cast<uintptr_t>(lhs), |
| 474 CheckMul(sizeof(L), static_cast<R>(rhs))) |
| 475 .template ValueOrDie<uintptr_t>(); |
| 476 return reinterpret_cast<L*>(result); |
| 477 } |
| 478 |
| 479 template <typename L, typename R> |
| 480 L* operator-(L* lhs, const StrictNumeric<R> rhs) { |
| 481 uintptr_t result = CheckSub(reinterpret_cast<uintptr_t>(lhs), |
| 482 CheckMul(sizeof(L), static_cast<R>(rhs))) |
| 483 .template ValueOrDie<uintptr_t>(); |
| 484 return reinterpret_cast<L*>(result); |
| 485 } |
| 486 |
265 } // namespace internal | 487 } // namespace internal |
266 | 488 |
267 using internal::CheckedNumeric; | 489 using internal::CheckedNumeric; |
| 490 using internal::IsValidForType; |
| 491 using internal::ValueOrDieForType; |
| 492 using internal::ValueOrDefaultForType; |
| 493 using internal::MakeCheckedNum; |
| 494 using internal::CheckMax; |
| 495 using internal::CheckMin; |
| 496 using internal::CheckAdd; |
| 497 using internal::CheckSub; |
| 498 using internal::CheckMul; |
| 499 using internal::CheckDiv; |
| 500 using internal::CheckMod; |
| 501 using internal::CheckLsh; |
| 502 using internal::CheckRsh; |
| 503 using internal::CheckAnd; |
| 504 using internal::CheckOr; |
| 505 using internal::CheckXor; |
268 | 506 |
269 } // namespace base | 507 } // namespace base |
270 } // namespace pdfium | 508 } // namespace pdfium |
271 | 509 |
272 #endif // PDFIUM_THIRD_PARTY_BASE_SAFE_MATH_H_ | 510 #endif // PDFIUM_THIRD_PARTY_BASE_NUMERICS_SAFE_MATH_H_ |
OLD | NEW |