• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
3 // found in the LICENSE file.
4 
5 #ifndef BASE_NUMERICS_SAFE_MATH_H_
6 #define BASE_NUMERICS_SAFE_MATH_H_
7 
8 #include <stddef.h>
9 
10 #include <limits>
11 #include <type_traits>
12 
13 #include "base/logging.h"
14 #include "base/numerics/safe_math_impl.h"
15 
16 namespace base {
17 
18 namespace internal {
19 
20 // CheckedNumeric implements all the logic and operators for detecting integer
21 // boundary conditions such as overflow, underflow, and invalid conversions.
22 // The CheckedNumeric type implicitly converts from floating point and integer
23 // data types, and contains overloads for basic arithmetic operations (i.e.: +,
24 // -, *, /, %).
25 //
26 // The following methods convert from CheckedNumeric to standard numeric values:
27 // IsValid() - Returns true if the underlying numeric value is valid (i.e. has
28 //             has not wrapped and is not the result of an invalid conversion).
29 // ValueOrDie() - Returns the underlying value. If the state is not valid this
30 //                call will crash on a CHECK.
31 // ValueOrDefault() - Returns the current value, or the supplied default if the
32 //                    state is not valid.
33 // ValueFloating() - Returns the underlying floating point value (valid only
34 //                   only for floating point CheckedNumeric types).
35 //
36 // Bitwise operations are explicitly not supported, because correct
37 // handling of some cases (e.g. sign manipulation) is ambiguous. Comparison
38 // operations are explicitly not supported because they could result in a crash
39 // on a CHECK condition. You should use patterns like the following for these
40 // operations:
41 // Bitwise operation:
42 //     CheckedNumeric<int> checked_int = untrusted_input_value;
43 //     int x = checked_int.ValueOrDefault(0) | kFlagValues;
44 // Comparison:
45 //   CheckedNumeric<size_t> checked_size = untrusted_input_value;
46 //   checked_size += HEADER LENGTH;
47 //   if (checked_size.IsValid() && checked_size.ValueOrDie() < buffer_size)
48 //     Do stuff...
49 template <typename T>
50 class CheckedNumeric {
51   static_assert(std::is_arithmetic<T>::value,
52                 "CheckedNumeric<T>: T must be a numeric type.");
53 
54  public:
55   typedef T type;
56 
CheckedNumeric()57   CheckedNumeric() {}
58 
59   // Copy constructor.
60   template <typename Src>
CheckedNumeric(const CheckedNumeric<Src> & rhs)61   CheckedNumeric(const CheckedNumeric<Src>& rhs)
62       : state_(rhs.ValueUnsafe(), rhs.validity()) {}
63 
64   template <typename Src>
CheckedNumeric(Src value,RangeConstraint validity)65   CheckedNumeric(Src value, RangeConstraint validity)
66       : state_(value, validity) {}
67 
68   // This is not an explicit constructor because we implicitly upgrade regular
69   // numerics to CheckedNumerics to make them easier to use.
70   template <typename Src>
CheckedNumeric(Src value)71   CheckedNumeric(Src value)  // NOLINT(runtime/explicit)
72       : state_(value) {
73     static_assert(std::numeric_limits<Src>::is_specialized,
74                   "Argument must be numeric.");
75   }
76 
77   // This is not an explicit constructor because we want a seamless conversion
78   // from StrictNumeric types.
79   template <typename Src>
CheckedNumeric(StrictNumeric<Src> value)80   CheckedNumeric(StrictNumeric<Src> value)  // NOLINT(runtime/explicit)
81       : state_(static_cast<Src>(value)) {
82   }
83 
84   // IsValid() is the public API to test if a CheckedNumeric is currently valid.
IsValid()85   bool IsValid() const { return validity() == RANGE_VALID; }
86 
87   // ValueOrDie() The primary accessor for the underlying value. If the current
88   // state is not valid it will CHECK and crash.
ValueOrDie()89   T ValueOrDie() const {
90     CHECK(IsValid());
91     return state_.value();
92   }
93 
94   // ValueOrDefault(T default_value) A convenience method that returns the
95   // current value if the state is valid, and the supplied default_value for
96   // any other state.
ValueOrDefault(T default_value)97   T ValueOrDefault(T default_value) const {
98     return IsValid() ? state_.value() : default_value;
99   }
100 
101   // ValueFloating() - Since floating point values include their validity state,
102   // we provide an easy method for extracting them directly, without a risk of
103   // crashing on a CHECK.
ValueFloating()104   T ValueFloating() const {
105     static_assert(std::numeric_limits<T>::is_iec559, "Argument must be float.");
106     return CheckedNumeric<T>::cast(*this).ValueUnsafe();
107   }
108 
109   // validity() - DO NOT USE THIS IN EXTERNAL CODE - It is public right now for
110   // tests and to avoid a big matrix of friend operator overloads. But the
111   // values it returns are likely to change in the future.
112   // Returns: current validity state (i.e. valid, overflow, underflow, nan).
113   // TODO(jschuh): crbug.com/332611 Figure out and implement semantics for
114   // saturation/wrapping so we can expose this state consistently and implement
115   // saturated arithmetic.
validity()116   RangeConstraint validity() const { return state_.validity(); }
117 
118   // ValueUnsafe() - DO NOT USE THIS IN EXTERNAL CODE - It is public right now
119   // for tests and to avoid a big matrix of friend operator overloads. But the
120   // values it returns are likely to change in the future.
121   // Returns: the raw numeric value, regardless of the current state.
122   // TODO(jschuh): crbug.com/332611 Figure out and implement semantics for
123   // saturation/wrapping so we can expose this state consistently and implement
124   // saturated arithmetic.
ValueUnsafe()125   T ValueUnsafe() const { return state_.value(); }
126 
127   // Prototypes for the supported arithmetic operator overloads.
128   template <typename Src> CheckedNumeric& operator+=(Src rhs);
129   template <typename Src> CheckedNumeric& operator-=(Src rhs);
130   template <typename Src> CheckedNumeric& operator*=(Src rhs);
131   template <typename Src> CheckedNumeric& operator/=(Src rhs);
132   template <typename Src> CheckedNumeric& operator%=(Src rhs);
133 
134   CheckedNumeric operator-() const {
135     RangeConstraint validity;
136     T value = CheckedNeg(state_.value(), &validity);
137     // Negation is always valid for floating point.
138     if (std::numeric_limits<T>::is_iec559)
139       return CheckedNumeric<T>(value);
140 
141     validity = GetRangeConstraint(state_.validity() | validity);
142     return CheckedNumeric<T>(value, validity);
143   }
144 
Abs()145   CheckedNumeric Abs() const {
146     RangeConstraint validity;
147     T value = CheckedAbs(state_.value(), &validity);
148     // Absolute value is always valid for floating point.
149     if (std::numeric_limits<T>::is_iec559)
150       return CheckedNumeric<T>(value);
151 
152     validity = GetRangeConstraint(state_.validity() | validity);
153     return CheckedNumeric<T>(value, validity);
154   }
155 
156   // This function is available only for integral types. It returns an unsigned
157   // integer of the same width as the source type, containing the absolute value
158   // of the source, and properly handling signed min.
UnsignedAbs()159   CheckedNumeric<typename UnsignedOrFloatForSize<T>::type> UnsignedAbs() const {
160     return CheckedNumeric<typename UnsignedOrFloatForSize<T>::type>(
161         CheckedUnsignedAbs(state_.value()), state_.validity());
162   }
163 
164   CheckedNumeric& operator++() {
165     *this += 1;
166     return *this;
167   }
168 
169   CheckedNumeric operator++(int) {
170     CheckedNumeric value = *this;
171     *this += 1;
172     return value;
173   }
174 
175   CheckedNumeric& operator--() {
176     *this -= 1;
177     return *this;
178   }
179 
180   CheckedNumeric operator--(int) {
181     CheckedNumeric value = *this;
182     *this -= 1;
183     return value;
184   }
185 
186   // These static methods behave like a convenience cast operator targeting
187   // the desired CheckedNumeric type. As an optimization, a reference is
188   // returned when Src is the same type as T.
189   template <typename Src>
190   static CheckedNumeric<T> cast(
191       Src u,
192       typename std::enable_if<std::numeric_limits<Src>::is_specialized,
193                               int>::type = 0) {
194     return u;
195   }
196 
197   template <typename Src>
198   static CheckedNumeric<T> cast(
199       const CheckedNumeric<Src>& u,
200       typename std::enable_if<!std::is_same<Src, T>::value, int>::type = 0) {
201     return u;
202   }
203 
cast(const CheckedNumeric<T> & u)204   static const CheckedNumeric<T>& cast(const CheckedNumeric<T>& u) { return u; }
205 
206  private:
207   template <typename NumericType>
208   struct UnderlyingType {
209     using type = NumericType;
210   };
211 
212   template <typename NumericType>
213   struct UnderlyingType<CheckedNumeric<NumericType>> {
214     using type = NumericType;
215   };
216 
217   CheckedNumericState<T> state_;
218 };
219 
220 // This is the boilerplate for the standard arithmetic operator overloads. A
221 // macro isn't the prettiest solution, but it beats rewriting these five times.
222 // Some details worth noting are:
223 //  * We apply the standard arithmetic promotions.
224 //  * We skip range checks for floating points.
225 //  * We skip range checks for destination integers with sufficient range.
226 // TODO(jschuh): extract these out into templates.
227 #define BASE_NUMERIC_ARITHMETIC_OPERATORS(NAME, OP, COMPOUND_OP)              \
228   /* Binary arithmetic operator for CheckedNumerics of the same type. */      \
229   template <typename T>                                                       \
230   CheckedNumeric<typename ArithmeticPromotion<T>::type> operator OP(          \
231       const CheckedNumeric<T>& lhs, const CheckedNumeric<T>& rhs) {           \
232     typedef typename ArithmeticPromotion<T>::type Promotion;                  \
233     /* Floating point always takes the fast path */                           \
234     if (std::numeric_limits<T>::is_iec559)                                    \
235       return CheckedNumeric<T>(lhs.ValueUnsafe() OP rhs.ValueUnsafe());       \
236     if (IsIntegerArithmeticSafe<Promotion, T, T>::value)                      \
237       return CheckedNumeric<Promotion>(                                       \
238           lhs.ValueUnsafe() OP rhs.ValueUnsafe(),                             \
239           GetRangeConstraint(rhs.validity() | lhs.validity()));               \
240     RangeConstraint validity = RANGE_VALID;                                   \
241     T result = static_cast<T>(                                                \
242         Checked##NAME(static_cast<Promotion>(lhs.ValueUnsafe()),              \
243                       static_cast<Promotion>(rhs.ValueUnsafe()), &validity)); \
244     return CheckedNumeric<Promotion>(                                         \
245         result,                                                               \
246         GetRangeConstraint(validity | lhs.validity() | rhs.validity()));      \
247   }                                                                           \
248   /* Assignment arithmetic operator implementation from CheckedNumeric. */    \
249   template <typename T>                                                       \
250   template <typename Src>                                                     \
251   CheckedNumeric<T>& CheckedNumeric<T>::operator COMPOUND_OP(Src rhs) {       \
252     *this = CheckedNumeric<T>::cast(*this)                                    \
253         OP CheckedNumeric<typename UnderlyingType<Src>::type>::cast(rhs);     \
254     return *this;                                                             \
255   }                                                                           \
256   /* Binary arithmetic operator for CheckedNumeric of different type. */      \
257   template <typename T, typename Src>                                         \
258   CheckedNumeric<typename ArithmeticPromotion<T, Src>::type> operator OP(     \
259       const CheckedNumeric<Src>& lhs, const CheckedNumeric<T>& rhs) {         \
260     typedef typename ArithmeticPromotion<T, Src>::type Promotion;             \
261     if (IsIntegerArithmeticSafe<Promotion, T, Src>::value)                    \
262       return CheckedNumeric<Promotion>(                                       \
263           lhs.ValueUnsafe() OP rhs.ValueUnsafe(),                             \
264           GetRangeConstraint(rhs.validity() | lhs.validity()));               \
265     return CheckedNumeric<Promotion>::cast(lhs)                               \
266         OP CheckedNumeric<Promotion>::cast(rhs);                              \
267   }                                                                           \
268   /* Binary arithmetic operator for left CheckedNumeric and right numeric. */ \
269   template <typename T, typename Src,                                         \
270             typename std::enable_if<std::is_arithmetic<Src>::value>::type* =  \
271                 nullptr>                                                      \
272   CheckedNumeric<typename ArithmeticPromotion<T, Src>::type> operator OP(     \
273       const CheckedNumeric<T>& lhs, Src rhs) {                                \
274     typedef typename ArithmeticPromotion<T, Src>::type Promotion;             \
275     if (IsIntegerArithmeticSafe<Promotion, T, Src>::value)                    \
276       return CheckedNumeric<Promotion>(lhs.ValueUnsafe() OP rhs,              \
277                                        lhs.validity());                       \
278     return CheckedNumeric<Promotion>::cast(lhs)                               \
279         OP CheckedNumeric<Promotion>::cast(rhs);                              \
280   }                                                                           \
281   /* Binary arithmetic operator for left numeric and right CheckedNumeric. */ \
282   template <typename T, typename Src,                                         \
283             typename std::enable_if<std::is_arithmetic<Src>::value>::type* =  \
284                 nullptr>                                                      \
285   CheckedNumeric<typename ArithmeticPromotion<T, Src>::type> operator OP(     \
286       Src lhs, const CheckedNumeric<T>& rhs) {                                \
287     typedef typename ArithmeticPromotion<T, Src>::type Promotion;             \
288     if (IsIntegerArithmeticSafe<Promotion, T, Src>::value)                    \
289       return CheckedNumeric<Promotion>(lhs OP rhs.ValueUnsafe(),              \
290                                        rhs.validity());                       \
291     return CheckedNumeric<Promotion>::cast(lhs)                               \
292         OP CheckedNumeric<Promotion>::cast(rhs);                              \
293   }
294 
295 BASE_NUMERIC_ARITHMETIC_OPERATORS(Add, +, += )
296 BASE_NUMERIC_ARITHMETIC_OPERATORS(Sub, -, -= )
297 BASE_NUMERIC_ARITHMETIC_OPERATORS(Mul, *, *= )
298 BASE_NUMERIC_ARITHMETIC_OPERATORS(Div, /, /= )
299 BASE_NUMERIC_ARITHMETIC_OPERATORS(Mod, %, %= )
300 
301 #undef BASE_NUMERIC_ARITHMETIC_OPERATORS
302 
303 }  // namespace internal
304 
305 using internal::CheckedNumeric;
306 
307 }  // namespace base
308 
309 #endif  // BASE_NUMERICS_SAFE_MATH_H_
310