From 43a97878ce14b72f0981164f87f2e35e14151312 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 7 Apr 2024 11:22:09 +0200 Subject: Adding upstream version 110.0.1. Signed-off-by: Daniel Baumann --- .../chromium/base/numerics/safe_conversions.h | 358 +++++++++++++++++++++ 1 file changed, 358 insertions(+) create mode 100644 security/sandbox/chromium/base/numerics/safe_conversions.h (limited to 'security/sandbox/chromium/base/numerics/safe_conversions.h') diff --git a/security/sandbox/chromium/base/numerics/safe_conversions.h b/security/sandbox/chromium/base/numerics/safe_conversions.h new file mode 100644 index 0000000000..b9636fec42 --- /dev/null +++ b/security/sandbox/chromium/base/numerics/safe_conversions.h @@ -0,0 +1,358 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef BASE_NUMERICS_SAFE_CONVERSIONS_H_ +#define BASE_NUMERICS_SAFE_CONVERSIONS_H_ + +#include + +#include +#include + +#include "base/numerics/safe_conversions_impl.h" + +#if !defined(__native_client__) && (defined(__ARMEL__) || defined(__arch64__)) +#include "base/numerics/safe_conversions_arm_impl.h" +#define BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS (1) +#else +#define BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS (0) +#endif + +#if !BASE_NUMERICS_DISABLE_OSTREAM_OPERATORS +#include +#endif + +namespace base { +namespace internal { + +#if !BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS +template +struct SaturateFastAsmOp { + static const bool is_supported = false; + static constexpr Dst Do(Src) { + // Force a compile failure if instantiated. + return CheckOnFailure::template HandleFailure(); + } +}; +#endif // BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS +#undef BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS + +// The following special case a few specific integer conversions where we can +// eke out better performance than range checking. +template +struct IsValueInRangeFastOp { + static const bool is_supported = false; + static constexpr bool Do(Src value) { + // Force a compile failure if instantiated. + return CheckOnFailure::template HandleFailure(); + } +}; + +// Signed to signed range comparison. +template +struct IsValueInRangeFastOp< + Dst, + Src, + typename std::enable_if< + std::is_integral::value && std::is_integral::value && + std::is_signed::value && std::is_signed::value && + !IsTypeInRangeForNumericType::value>::type> { + static const bool is_supported = true; + + static constexpr bool Do(Src value) { + // Just downcast to the smaller type, sign extend it back to the original + // type, and then see if it matches the original value. + return value == static_cast(value); + } +}; + +// Signed to unsigned range comparison. +template +struct IsValueInRangeFastOp< + Dst, + Src, + typename std::enable_if< + std::is_integral::value && std::is_integral::value && + !std::is_signed::value && std::is_signed::value && + !IsTypeInRangeForNumericType::value>::type> { + static const bool is_supported = true; + + static constexpr bool Do(Src value) { + // We cast a signed as unsigned to overflow negative values to the top, + // then compare against whichever maximum is smaller, as our upper bound. + return as_unsigned(value) <= as_unsigned(CommonMax()); + } +}; + +// Convenience function that returns true if the supplied value is in range +// for the destination type. +template +constexpr bool IsValueInRangeForNumericType(Src value) { + using SrcType = typename internal::UnderlyingType::type; + return internal::IsValueInRangeFastOp::is_supported + ? internal::IsValueInRangeFastOp::Do( + static_cast(value)) + : internal::DstRangeRelationToSrcRange( + static_cast(value)) + .IsValid(); +} + +// checked_cast<> is analogous to static_cast<> for numeric types, +// except that it CHECKs that the specified numeric conversion will not +// overflow or underflow. NaN source will always trigger a CHECK. +template +constexpr Dst checked_cast(Src value) { + // This throws a compile-time error on evaluating the constexpr if it can be + // determined at compile-time as failing, otherwise it will CHECK at runtime. + using SrcType = typename internal::UnderlyingType::type; + return BASE_NUMERICS_LIKELY((IsValueInRangeForNumericType(value))) + ? static_cast(static_cast(value)) + : CheckHandler::template HandleFailure(); +} + +// Default boundaries for integral/float: max/infinity, lowest/-infinity, 0/NaN. +// You may provide your own limits (e.g. to saturated_cast) so long as you +// implement all of the static constexpr member functions in the class below. +template +struct SaturationDefaultLimits : public std::numeric_limits { + static constexpr T NaN() { + return std::numeric_limits::has_quiet_NaN + ? std::numeric_limits::quiet_NaN() + : T(); + } + using std::numeric_limits::max; + static constexpr T Overflow() { + return std::numeric_limits::has_infinity + ? std::numeric_limits::infinity() + : std::numeric_limits::max(); + } + using std::numeric_limits::lowest; + static constexpr T Underflow() { + return std::numeric_limits::has_infinity + ? std::numeric_limits::infinity() * -1 + : std::numeric_limits::lowest(); + } +}; + +template class S, typename Src> +constexpr Dst saturated_cast_impl(Src value, RangeCheck constraint) { + // For some reason clang generates much better code when the branch is + // structured exactly this way, rather than a sequence of checks. + return !constraint.IsOverflowFlagSet() + ? (!constraint.IsUnderflowFlagSet() ? static_cast(value) + : S::Underflow()) + // Skip this check for integral Src, which cannot be NaN. + : (std::is_integral::value || !constraint.IsUnderflowFlagSet() + ? S::Overflow() + : S::NaN()); +} + +// We can reduce the number of conditions and get slightly better performance +// for normal signed and unsigned integer ranges. And in the specific case of +// Arm, we can use the optimized saturation instructions. +template +struct SaturateFastOp { + static const bool is_supported = false; + static constexpr Dst Do(Src value) { + // Force a compile failure if instantiated. + return CheckOnFailure::template HandleFailure(); + } +}; + +template +struct SaturateFastOp< + Dst, + Src, + typename std::enable_if::value && + std::is_integral::value && + SaturateFastAsmOp::is_supported>::type> { + static const bool is_supported = true; + static Dst Do(Src value) { return SaturateFastAsmOp::Do(value); } +}; + +template +struct SaturateFastOp< + Dst, + Src, + typename std::enable_if::value && + std::is_integral::value && + !SaturateFastAsmOp::is_supported>::type> { + static const bool is_supported = true; + static Dst Do(Src value) { + // The exact order of the following is structured to hit the correct + // optimization heuristics across compilers. Do not change without + // checking the emitted code. + Dst saturated = CommonMaxOrMin( + IsMaxInRangeForNumericType() || + (!IsMinInRangeForNumericType() && IsValueNegative(value))); + return BASE_NUMERICS_LIKELY(IsValueInRangeForNumericType(value)) + ? static_cast(value) + : saturated; + } +}; + +// saturated_cast<> is analogous to static_cast<> for numeric types, except +// that the specified numeric conversion will saturate by default rather than +// overflow or underflow, and NaN assignment to an integral will return 0. +// All boundary condition behaviors can be overriden with a custom handler. +template class SaturationHandler = SaturationDefaultLimits, + typename Src> +constexpr Dst saturated_cast(Src value) { + using SrcType = typename UnderlyingType::type; + return !IsCompileTimeConstant(value) && + SaturateFastOp::is_supported && + std::is_same, + SaturationDefaultLimits>::value + ? SaturateFastOp::Do(static_cast(value)) + : saturated_cast_impl( + static_cast(value), + DstRangeRelationToSrcRange( + static_cast(value))); +} + +// strict_cast<> is analogous to static_cast<> for numeric types, except that +// it will cause a compile failure if the destination type is not large enough +// to contain any value in the source type. It performs no runtime checking. +template +constexpr Dst strict_cast(Src value) { + using SrcType = typename UnderlyingType::type; + static_assert(UnderlyingType::is_numeric, "Argument must be numeric."); + static_assert(std::is_arithmetic::value, "Result must be numeric."); + + // If you got here from a compiler error, it's because you tried to assign + // from a source type to a destination type that has insufficient range. + // The solution may be to change the destination type you're assigning to, + // and use one large enough to represent the source. + // Alternatively, you may be better served with the checked_cast<> or + // saturated_cast<> template functions for your particular use case. + static_assert(StaticDstRangeRelationToSrcRange::value == + NUMERIC_RANGE_CONTAINED, + "The source type is out of range for the destination type. " + "Please see strict_cast<> comments for more information."); + + return static_cast(static_cast(value)); +} + +// Some wrappers to statically check that a type is in range. +template +struct IsNumericRangeContained { + static const bool value = false; +}; + +template +struct IsNumericRangeContained< + Dst, + Src, + typename std::enable_if::value && + ArithmeticOrUnderlyingEnum::value>::type> { + static const bool value = StaticDstRangeRelationToSrcRange::value == + NUMERIC_RANGE_CONTAINED; +}; + +// StrictNumeric implements compile time range checking between numeric types by +// wrapping assignment operations in a strict_cast. This class is intended to be +// used for function arguments and return types, to ensure the destination type +// can always contain the source type. This is essentially the same as enforcing +// -Wconversion in gcc and C4302 warnings on MSVC, but it can be applied +// incrementally at API boundaries, making it easier to convert code so that it +// compiles cleanly with truncation warnings enabled. +// This template should introduce no runtime overhead, but it also provides no +// runtime checking of any of the associated mathematical operations. Use +// CheckedNumeric for runtime range checks of the actual value being assigned. +template +class StrictNumeric { + public: + using type = T; + + constexpr StrictNumeric() : value_(0) {} + + // Copy constructor. + template + constexpr StrictNumeric(const StrictNumeric& rhs) + : value_(strict_cast(rhs.value_)) {} + + // This is not an explicit constructor because we implicitly upgrade regular + // numerics to StrictNumerics to make them easier to use. + template + constexpr StrictNumeric(Src value) // NOLINT(runtime/explicit) + : value_(strict_cast(value)) {} + + // If you got here from a compiler error, it's because you tried to assign + // from a source type to a destination type that has insufficient range. + // The solution may be to change the destination type you're assigning to, + // and use one large enough to represent the source. + // If you're assigning from a CheckedNumeric<> class, you may be able to use + // the AssignIfValid() member function, specify a narrower destination type to + // the member value functions (e.g. val.template ValueOrDie()), use one + // of the value helper functions (e.g. ValueOrDieForType(val)). + // If you've encountered an _ambiguous overload_ you can use a static_cast<> + // to explicitly cast the result to the destination type. + // If none of that works, you may be better served with the checked_cast<> or + // saturated_cast<> template functions for your particular use case. + template ::value>::type* = nullptr> + constexpr operator Dst() const { + return static_cast::type>(value_); + } + + private: + const T value_; +}; + +// Convience wrapper returns a StrictNumeric from the provided arithmetic type. +template +constexpr StrictNumeric::type> MakeStrictNum( + const T value) { + return value; +} + +#if !BASE_NUMERICS_DISABLE_OSTREAM_OPERATORS +// Overload the ostream output operator to make logging work nicely. +template +std::ostream& operator<<(std::ostream& os, const StrictNumeric& value) { + os << static_cast(value); + return os; +} +#endif + +#define BASE_NUMERIC_COMPARISON_OPERATORS(CLASS, NAME, OP) \ + template ::value>::type* = nullptr> \ + constexpr bool operator OP(const L lhs, const R rhs) { \ + return SafeCompare::type, \ + typename UnderlyingType::type>(lhs, rhs); \ + } + +BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsLess, <) +BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsLessOrEqual, <=) +BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsGreater, >) +BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsGreaterOrEqual, >=) +BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsEqual, ==) +BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsNotEqual, !=) + +} // namespace internal + +using internal::as_signed; +using internal::as_unsigned; +using internal::checked_cast; +using internal::strict_cast; +using internal::saturated_cast; +using internal::SafeUnsignedAbs; +using internal::StrictNumeric; +using internal::MakeStrictNum; +using internal::IsValueInRangeForNumericType; +using internal::IsTypeInRangeForNumericType; +using internal::IsValueNegative; + +// Explicitly make a shorter size_t alias for convenience. +using SizeT = StrictNumeric; + +} // namespace base + +#endif // BASE_NUMERICS_SAFE_CONVERSIONS_H_ -- cgit v1.2.3