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