1 // Copyright 2014 The Chromium Authors
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 PARTITION_ALLOC_PARTITION_ALLOC_BASE_NUMERICS_SAFE_CONVERSIONS_H_
6 #define PARTITION_ALLOC_PARTITION_ALLOC_BASE_NUMERICS_SAFE_CONVERSIONS_H_
7 
8 #include <cmath>
9 #include <cstddef>
10 #include <limits>
11 #include <type_traits>
12 
13 #include "partition_alloc/partition_alloc_base/numerics/safe_conversions_impl.h"
14 
15 #if defined(__ARMEL__) && !defined(__native_client__)
16 #include "partition_alloc/partition_alloc_base/numerics/safe_conversions_arm_impl.h"
17 #define PA_BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS (1)
18 #else
19 #define PA_BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS (0)
20 #endif
21 
22 #if !PA_BASE_NUMERICS_DISABLE_OSTREAM_OPERATORS
23 #include <ostream>
24 #endif
25 
26 namespace partition_alloc::internal::base {
27 namespace internal {
28 
29 #if !PA_BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS
30 template <typename Dst, typename Src>
31 struct SaturateFastAsmOp {
32   static constexpr bool is_supported = false;
DoSaturateFastAsmOp33   static constexpr Dst Do(Src) {
34     // Force a compile failure if instantiated.
35     return CheckOnFailure::template HandleFailure<Dst>();
36   }
37 };
38 #endif  // PA_BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS
39 #undef PA_BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS
40 
41 // The following special case a few specific integer conversions where we can
42 // eke out better performance than range checking.
43 template <typename Dst, typename Src, typename Enable = void>
44 struct IsValueInRangeFastOp {
45   static constexpr bool is_supported = false;
DoIsValueInRangeFastOp46   static constexpr bool Do(Src value) {
47     // Force a compile failure if instantiated.
48     return CheckOnFailure::template HandleFailure<bool>();
49   }
50 };
51 
52 // Signed to signed range comparison.
53 template <typename Dst, typename Src>
54 struct IsValueInRangeFastOp<
55     Dst,
56     Src,
57     typename std::enable_if<
58         std::is_integral_v<Dst> && std::is_integral_v<Src> &&
59         std::is_signed_v<Dst> && std::is_signed_v<Src> &&
60         !IsTypeInRangeForNumericType<Dst, Src>::value>::type> {
61   static constexpr bool is_supported = true;
62 
63   static constexpr bool Do(Src value) {
64     // Just downcast to the smaller type, sign extend it back to the original
65     // type, and then see if it matches the original value.
66     return value == static_cast<Dst>(value);
67   }
68 };
69 
70 // Signed to unsigned range comparison.
71 template <typename Dst, typename Src>
72 struct IsValueInRangeFastOp<
73     Dst,
74     Src,
75     typename std::enable_if<
76         std::is_integral_v<Dst> && std::is_integral_v<Src> &&
77         !std::is_signed_v<Dst> && std::is_signed_v<Src> &&
78         !IsTypeInRangeForNumericType<Dst, Src>::value>::type> {
79   static constexpr bool is_supported = true;
80 
81   static constexpr bool Do(Src value) {
82     // We cast a signed as unsigned to overflow negative values to the top,
83     // then compare against whichever maximum is smaller, as our upper bound.
84     return as_unsigned(value) <= as_unsigned(CommonMax<Src, Dst>());
85   }
86 };
87 
88 // Convenience function that returns true if the supplied value is in range
89 // for the destination type.
90 template <typename Dst, typename Src>
91 constexpr bool IsValueInRangeForNumericType(Src value) {
92   using SrcType = typename internal::UnderlyingType<Src>::type;
93   return internal::IsValueInRangeFastOp<Dst, SrcType>::is_supported
94              ? internal::IsValueInRangeFastOp<Dst, SrcType>::Do(
95                    static_cast<SrcType>(value))
96              : internal::DstRangeRelationToSrcRange<Dst>(
97                    static_cast<SrcType>(value))
98                    .IsValid();
99 }
100 
101 // checked_cast<> is analogous to static_cast<> for numeric types,
102 // except that it CHECKs that the specified numeric conversion will not
103 // overflow or underflow. NaN source will always trigger a CHECK.
104 template <typename Dst,
105           class CheckHandler = internal::CheckOnFailure,
106           typename Src>
107 constexpr Dst checked_cast(Src value) {
108   // This throws a compile-time error on evaluating the constexpr if it can be
109   // determined at compile-time as failing, otherwise it will CHECK at runtime.
110   using SrcType = typename internal::UnderlyingType<Src>::type;
111   return PA_BASE_NUMERICS_LIKELY((IsValueInRangeForNumericType<Dst>(value)))
112              ? static_cast<Dst>(static_cast<SrcType>(value))
113              : CheckHandler::template HandleFailure<Dst>();
114 }
115 
116 // Default boundaries for integral/float: max/infinity, lowest/-infinity, 0/NaN.
117 // You may provide your own limits (e.g. to saturated_cast) so long as you
118 // implement all of the static constexpr member functions in the class below.
119 template <typename T>
120 struct SaturationDefaultLimits : public std::numeric_limits<T> {
121   static constexpr T NaN() {
122     return std::numeric_limits<T>::has_quiet_NaN
123                ? std::numeric_limits<T>::quiet_NaN()
124                : T();
125   }
126   using std::numeric_limits<T>::max;
127   static constexpr T Overflow() {
128     return std::numeric_limits<T>::has_infinity
129                ? std::numeric_limits<T>::infinity()
130                : std::numeric_limits<T>::max();
131   }
132   using std::numeric_limits<T>::lowest;
133   static constexpr T Underflow() {
134     return std::numeric_limits<T>::has_infinity
135                ? std::numeric_limits<T>::infinity() * -1
136                : std::numeric_limits<T>::lowest();
137   }
138 };
139 
140 template <typename Dst, template <typename> class S, typename Src>
141 constexpr Dst saturated_cast_impl(Src value, RangeCheck constraint) {
142   // For some reason clang generates much better code when the branch is
143   // structured exactly this way, rather than a sequence of checks.
144   return !constraint.IsOverflowFlagSet()
145              ? (!constraint.IsUnderflowFlagSet() ? static_cast<Dst>(value)
146                                                  : S<Dst>::Underflow())
147              // Skip this check for integral Src, which cannot be NaN.
148              : (std::is_integral_v<Src> || !constraint.IsUnderflowFlagSet()
149                     ? S<Dst>::Overflow()
150                     : S<Dst>::NaN());
151 }
152 
153 // We can reduce the number of conditions and get slightly better performance
154 // for normal signed and unsigned integer ranges. And in the specific case of
155 // Arm, we can use the optimized saturation instructions.
156 template <typename Dst, typename Src, typename Enable = void>
157 struct SaturateFastOp {
158   static constexpr bool is_supported = false;
159   static constexpr Dst Do(Src value) {
160     // Force a compile failure if instantiated.
161     return CheckOnFailure::template HandleFailure<Dst>();
162   }
163 };
164 
165 template <typename Dst, typename Src>
166 struct SaturateFastOp<Dst,
167                       Src,
168                       typename std::enable_if<
169                           std::is_integral_v<Src> && std::is_integral_v<Dst> &&
170                           SaturateFastAsmOp<Dst, Src>::is_supported>::type> {
171   static constexpr bool is_supported = true;
172   static constexpr Dst Do(Src value) {
173     return SaturateFastAsmOp<Dst, Src>::Do(value);
174   }
175 };
176 
177 template <typename Dst, typename Src>
178 struct SaturateFastOp<Dst,
179                       Src,
180                       typename std::enable_if<
181                           std::is_integral_v<Src> && std::is_integral_v<Dst> &&
182                           !SaturateFastAsmOp<Dst, Src>::is_supported>::type> {
183   static constexpr bool is_supported = true;
184   static constexpr Dst Do(Src value) {
185     // The exact order of the following is structured to hit the correct
186     // optimization heuristics across compilers. Do not change without
187     // checking the emitted code.
188     const Dst saturated = CommonMaxOrMin<Dst, Src>(
189         IsMaxInRangeForNumericType<Dst, Src>() ||
190         (!IsMinInRangeForNumericType<Dst, Src>() && IsValueNegative(value)));
191     return PA_BASE_NUMERICS_LIKELY(IsValueInRangeForNumericType<Dst>(value))
192                ? static_cast<Dst>(value)
193                : saturated;
194   }
195 };
196 
197 // saturated_cast<> is analogous to static_cast<> for numeric types, except
198 // that the specified numeric conversion will saturate by default rather than
199 // overflow or underflow, and NaN assignment to an integral will return 0.
200 // All boundary condition behaviors can be overridden with a custom handler.
201 template <typename Dst,
202           template <typename> class SaturationHandler = SaturationDefaultLimits,
203           typename Src>
204 constexpr Dst saturated_cast(Src value) {
205   using SrcType = typename UnderlyingType<Src>::type;
206   return !PA_IsConstantEvaluated() &&
207                  SaturateFastOp<Dst, SrcType>::is_supported &&
208                  std::is_same_v<SaturationHandler<Dst>,
209                                 SaturationDefaultLimits<Dst>>
210              ? SaturateFastOp<Dst, SrcType>::Do(static_cast<SrcType>(value))
211              : saturated_cast_impl<Dst, SaturationHandler, SrcType>(
212                    static_cast<SrcType>(value),
213                    DstRangeRelationToSrcRange<Dst, SaturationHandler, SrcType>(
214                        static_cast<SrcType>(value)));
215 }
216 
217 // strict_cast<> is analogous to static_cast<> for numeric types, except that
218 // it will cause a compile failure if the destination type is not large enough
219 // to contain any value in the source type. It performs no runtime checking.
220 template <typename Dst, typename Src>
221 constexpr Dst strict_cast(Src value) {
222   using SrcType = typename UnderlyingType<Src>::type;
223   static_assert(UnderlyingType<Src>::is_numeric, "Argument must be numeric.");
224   static_assert(std::is_arithmetic_v<Dst>, "Result must be numeric.");
225 
226   // If you got here from a compiler error, it's because you tried to assign
227   // from a source type to a destination type that has insufficient range.
228   // The solution may be to change the destination type you're assigning to,
229   // and use one large enough to represent the source.
230   // Alternatively, you may be better served with the checked_cast<> or
231   // saturated_cast<> template functions for your particular use case.
232   static_assert(StaticDstRangeRelationToSrcRange<Dst, SrcType>::value ==
233                     NUMERIC_RANGE_CONTAINED,
234                 "The source type is out of range for the destination type. "
235                 "Please see strict_cast<> comments for more information.");
236 
237   return static_cast<Dst>(static_cast<SrcType>(value));
238 }
239 
240 // Some wrappers to statically check that a type is in range.
241 template <typename Dst, typename Src, class Enable = void>
242 struct IsNumericRangeContained {
243   static constexpr bool value = false;
244 };
245 
246 template <typename Dst, typename Src>
247 struct IsNumericRangeContained<
248     Dst,
249     Src,
250     typename std::enable_if<ArithmeticOrUnderlyingEnum<Dst>::value &&
251                             ArithmeticOrUnderlyingEnum<Src>::value>::type> {
252   static constexpr bool value =
253       StaticDstRangeRelationToSrcRange<Dst, Src>::value ==
254       NUMERIC_RANGE_CONTAINED;
255 };
256 
257 // StrictNumeric implements compile time range checking between numeric types by
258 // wrapping assignment operations in a strict_cast. This class is intended to be
259 // used for function arguments and return types, to ensure the destination type
260 // can always contain the source type. This is essentially the same as enforcing
261 // -Wconversion in gcc and C4302 warnings on MSVC, but it can be applied
262 // incrementally at API boundaries, making it easier to convert code so that it
263 // compiles cleanly with truncation warnings enabled.
264 // This template should introduce no runtime overhead, but it also provides no
265 // runtime checking of any of the associated mathematical operations. Use
266 // CheckedNumeric for runtime range checks of the actual value being assigned.
267 template <typename T>
268 class StrictNumeric {
269  public:
270   using type = T;
271 
272   constexpr StrictNumeric() : value_(0) {}
273 
274   // Copy constructor.
275   template <typename Src>
276   constexpr StrictNumeric(const StrictNumeric<Src>& rhs)
277       : value_(strict_cast<T>(rhs.value_)) {}
278 
279   // This is not an explicit constructor because we implicitly upgrade regular
280   // numerics to StrictNumerics to make them easier to use.
281   template <typename Src>
282   constexpr StrictNumeric(Src value)  // NOLINT(runtime/explicit)
283       : value_(strict_cast<T>(value)) {}
284 
285   // If you got here from a compiler error, it's because you tried to assign
286   // from a source type to a destination type that has insufficient range.
287   // The solution may be to change the destination type you're assigning to,
288   // and use one large enough to represent the source.
289   // If you're assigning from a CheckedNumeric<> class, you may be able to use
290   // the AssignIfValid() member function, specify a narrower destination type to
291   // the member value functions (e.g. val.template ValueOrDie<Dst>()), use one
292   // of the value helper functions (e.g. ValueOrDieForType<Dst>(val)).
293   // If you've encountered an _ambiguous overload_ you can use a static_cast<>
294   // to explicitly cast the result to the destination type.
295   // If none of that works, you may be better served with the checked_cast<> or
296   // saturated_cast<> template functions for your particular use case.
297   template <typename Dst,
298             typename std::enable_if<
299                 IsNumericRangeContained<Dst, T>::value>::type* = nullptr>
300   constexpr operator Dst() const {
301     return static_cast<typename ArithmeticOrUnderlyingEnum<Dst>::type>(value_);
302   }
303 
304  private:
305   const T value_;
306 };
307 
308 // Convenience wrapper returns a StrictNumeric from the provided arithmetic
309 // type.
310 template <typename T>
311 constexpr StrictNumeric<typename UnderlyingType<T>::type> MakeStrictNum(
312     const T value) {
313   return value;
314 }
315 
316 #define PA_BASE_NUMERIC_COMPARISON_OPERATORS(CLASS, NAME, OP)           \
317   template <typename L, typename R,                                     \
318             typename std::enable_if<                                    \
319                 internal::Is##CLASS##Op<L, R>::value>::type* = nullptr> \
320   constexpr bool operator OP(const L lhs, const R rhs) {                \
321     return SafeCompare<NAME, typename UnderlyingType<L>::type,          \
322                        typename UnderlyingType<R>::type>(lhs, rhs);     \
323   }
324 
325 PA_BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsLess, <)
326 PA_BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsLessOrEqual, <=)
327 PA_BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsGreater, >)
328 PA_BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsGreaterOrEqual, >=)
329 PA_BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsEqual, ==)
330 PA_BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsNotEqual, !=)
331 
332 }  // namespace internal
333 
334 using internal::as_signed;
335 using internal::as_unsigned;
336 using internal::checked_cast;
337 using internal::IsTypeInRangeForNumericType;
338 using internal::IsValueInRangeForNumericType;
339 using internal::IsValueNegative;
340 using internal::MakeStrictNum;
341 using internal::SafeUnsignedAbs;
342 using internal::saturated_cast;
343 using internal::strict_cast;
344 using internal::StrictNumeric;
345 
346 // Explicitly make a shorter size_t alias for convenience.
347 using SizeT = StrictNumeric<size_t>;
348 
349 // floating -> integral conversions that saturate and thus can actually return
350 // an integral type.  In most cases, these should be preferred over the std::
351 // versions.
352 template <typename Dst = int,
353           typename Src,
354           typename = std::enable_if_t<std::is_integral_v<Dst> &&
355                                       std::is_floating_point_v<Src>>>
356 Dst ClampFloor(Src value) {
357   return saturated_cast<Dst>(std::floor(value));
358 }
359 template <typename Dst = int,
360           typename Src,
361           typename = std::enable_if_t<std::is_integral_v<Dst> &&
362                                       std::is_floating_point_v<Src>>>
363 Dst ClampCeil(Src value) {
364   return saturated_cast<Dst>(std::ceil(value));
365 }
366 template <typename Dst = int,
367           typename Src,
368           typename = std::enable_if_t<std::is_integral_v<Dst> &&
369                                       std::is_floating_point_v<Src>>>
370 Dst ClampRound(Src value) {
371   const Src rounded =
372       (value >= 0.0f) ? std::floor(value + 0.5f) : std::ceil(value - 0.5f);
373   return saturated_cast<Dst>(rounded);
374 }
375 
376 }  // namespace partition_alloc::internal::base
377 
378 #endif  // PARTITION_ALLOC_PARTITION_ALLOC_BASE_NUMERICS_SAFE_CONVERSIONS_H_
379