diff --git a/engine/src/flutter/ci/licenses.sh b/engine/src/flutter/ci/licenses.sh index 48988f30a8..4a139c5d9c 100755 --- a/engine/src/flutter/ci/licenses.sh +++ b/engine/src/flutter/ci/licenses.sh @@ -122,7 +122,7 @@ function verify_licenses() ( local actualLicenseCount actualLicenseCount="$(tail -n 1 flutter/ci/licenses_golden/licenses_flutter | tr -dc '0-9')" - local expectedLicenseCount=15 # When changing this number: Update the error message below as well describing all expected license types. + local expectedLicenseCount=17 # When changing this number: Update the error message below as well describing all expected license types. if [[ $actualLicenseCount -ne $expectedLicenseCount ]]; then echo "=============================== ERROR ===============================" diff --git a/engine/src/flutter/ci/licenses_golden/licenses_flutter b/engine/src/flutter/ci/licenses_golden/licenses_flutter index 7c23ce8073..177517471d 100755 --- a/engine/src/flutter/ci/licenses_golden/licenses_flutter +++ b/engine/src/flutter/ci/licenses_golden/licenses_flutter @@ -22,6 +22,10 @@ FILE: ../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_ma FILE: ../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_mac.mm FILE: ../../../flutter/third_party/accessibility/ax/tree_generator.cc FILE: ../../../flutter/third_party/accessibility/ax/tree_generator.h +FILE: ../../../flutter/third_party/accessibility/base/numerics/safe_conversions.h +FILE: ../../../flutter/third_party/accessibility/base/numerics/safe_conversions_impl.h +FILE: ../../../flutter/third_party/accessibility/gfx/mac/coordinate_conversion.h +FILE: ../../../flutter/third_party/accessibility/gfx/mac/coordinate_conversion.mm ---------------------------------------------------------------------------------------------------- Copyright 2014 The Chromium Authors. All rights reserved. @@ -152,6 +156,17 @@ FILE: ../../../flutter/third_party/accessibility/ax/platform/ax_system_caret_win FILE: ../../../flutter/third_party/accessibility/ax/platform/ax_system_caret_win.h FILE: ../../../flutter/third_party/accessibility/ax/platform/ax_unique_id.cc FILE: ../../../flutter/third_party/accessibility/ax/platform/ax_unique_id.h +FILE: ../../../flutter/third_party/accessibility/base/numerics/checked_math.h +FILE: ../../../flutter/third_party/accessibility/base/numerics/checked_math_impl.h +FILE: ../../../flutter/third_party/accessibility/base/numerics/clamped_math.h +FILE: ../../../flutter/third_party/accessibility/base/numerics/clamped_math_impl.h +FILE: ../../../flutter/third_party/accessibility/base/numerics/math_constants.h +FILE: ../../../flutter/third_party/accessibility/base/numerics/ranges.h +FILE: ../../../flutter/third_party/accessibility/base/numerics/safe_conversions_arm_impl.h +FILE: ../../../flutter/third_party/accessibility/base/numerics/safe_math.h +FILE: ../../../flutter/third_party/accessibility/base/numerics/safe_math_arm_impl.h +FILE: ../../../flutter/third_party/accessibility/base/numerics/safe_math_clang_gcc_impl.h +FILE: ../../../flutter/third_party/accessibility/base/numerics/safe_math_shared_impl.h ---------------------------------------------------------------------------------------------------- Copyright 2017 The Chromium Authors. All rights reserved. @@ -283,6 +298,7 @@ LIBRARY: accessibility ORIGIN: ../../../flutter/third_party/accessibility/ax/ax_text_utils.cc + ../../../LICENSE TYPE: LicenseType.bsd FILE: ../../../flutter/third_party/accessibility/ax/ax_text_utils.cc +FILE: ../../../flutter/third_party/accessibility/base/auto_reset.h ---------------------------------------------------------------------------------------------------- Copyright (c) 2011 The Chromium Authors. All rights reserved. @@ -319,6 +335,40 @@ ORIGIN: ../../../flutter/third_party/accessibility/ax/ax_text_utils.h + ../../.. TYPE: LicenseType.bsd FILE: ../../../flutter/third_party/accessibility/ax/ax_text_utils.h FILE: ../../../flutter/third_party/accessibility/ax_build/build_config.h +FILE: ../../../flutter/third_party/accessibility/base/compiler_specific.h +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/insets.h +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/insets_f.cc +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/insets_f.h +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/point.cc +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/point.h +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/point_conversions.cc +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/point_conversions.h +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/point_f.cc +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/point_f.h +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/point_unittest.cc +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/rect.cc +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/rect.h +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/rect_conversions.cc +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/rect_conversions.h +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/rect_f.cc +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/rect_f.h +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/size.cc +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/size.h +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/size_conversions.cc +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/size_conversions.h +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/size_f.cc +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/size_f.h +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/size_unittest.cc +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/vector2d.cc +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/vector2d.h +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/vector2d_conversions.cc +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/vector2d_conversions.h +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/vector2d_f.cc +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/vector2d_f.h +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/vector2d_unittest.cc +FILE: ../../../flutter/third_party/accessibility/gfx/native_widget_types.h +FILE: ../../../flutter/third_party/accessibility/gfx/transform.cc +FILE: ../../../flutter/third_party/accessibility/gfx/transform.h ---------------------------------------------------------------------------------------------------- Copyright (c) 2012 The Chromium Authors. All rights reserved. @@ -411,6 +461,7 @@ FILE: ../../../flutter/third_party/accessibility/ax/platform/ax_platform_node_te FILE: ../../../flutter/third_party/accessibility/ax/platform/compute_attributes.cc FILE: ../../../flutter/third_party/accessibility/ax/platform/compute_attributes.h FILE: ../../../flutter/third_party/accessibility/ax/run_all_unittests.cc +FILE: ../../../flutter/third_party/accessibility/base/no_destructor.h ---------------------------------------------------------------------------------------------------- Copyright 2018 The Chromium Authors. All rights reserved. @@ -606,6 +657,78 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ==================================================================================================== +==================================================================================================== +LIBRARY: accessibility +ORIGIN: ../../../flutter/third_party/accessibility/gfx/geometry/insets.cc + ../../../LICENSE +TYPE: LicenseType.bsd +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/insets.cc +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/insets_unittest.cc +---------------------------------------------------------------------------------------------------- +Copyright (c) 2009 The Chromium Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +==================================================================================================== + +==================================================================================================== +LIBRARY: accessibility +ORIGIN: ../../../flutter/third_party/accessibility/gfx/geometry/rect_unittest.cc + ../../../LICENSE +TYPE: LicenseType.bsd +FILE: ../../../flutter/third_party/accessibility/gfx/geometry/rect_unittest.cc +FILE: ../../../flutter/third_party/accessibility/gfx/gfx_export.h +---------------------------------------------------------------------------------------------------- +Copyright (c) 2013 The Chromium Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +==================================================================================================== + ==================================================================================================== LIBRARY: accessibility ORIGIN: ../../../third_party/icu/scripts/LICENSE @@ -2549,4 +2672,4 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================================================== -Total license count: 15 +Total license count: 17 diff --git a/engine/src/flutter/third_party/accessibility/base/auto_reset.h b/engine/src/flutter/third_party/accessibility/base/auto_reset.h new file mode 100644 index 0000000000..d8ce87b600 --- /dev/null +++ b/engine/src/flutter/third_party/accessibility/base/auto_reset.h @@ -0,0 +1,52 @@ +// Copyright (c) 2011 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_AUTO_RESET_H_ +#define BASE_AUTO_RESET_H_ + +#include + +// base::AutoReset<> is useful for setting a variable to a new value only within +// a particular scope. An base::AutoReset<> object resets a variable to its +// original value upon destruction, making it an alternative to writing +// "var = false;" or "var = old_val;" at all of a block's exit points. +// +// This should be obvious, but note that an base::AutoReset<> instance should +// have a shorter lifetime than its scoped_variable, to prevent invalid memory +// writes when the base::AutoReset<> object is destroyed. + +namespace base { + +template +class AutoReset { + public: + template + AutoReset(T* scoped_variable, U&& new_value) + : scoped_variable_(scoped_variable), + original_value_( + std::exchange(*scoped_variable_, std::forward(new_value))) {} + + AutoReset(AutoReset&& other) + : scoped_variable_(std::exchange(other.scoped_variable_, nullptr)), + original_value_(std::move(other.original_value_)) {} + + AutoReset& operator=(AutoReset&& rhs) { + scoped_variable_ = std::exchange(rhs.scoped_variable_, nullptr); + original_value_ = std::move(rhs.original_value_); + return *this; + } + + ~AutoReset() { + if (scoped_variable_) + *scoped_variable_ = std::move(original_value_); + } + + private: + T* scoped_variable_; + T original_value_; +}; + +} // namespace base + +#endif // BASE_AUTO_RESET_H_ diff --git a/engine/src/flutter/third_party/accessibility/base/compiler_specific.h b/engine/src/flutter/third_party/accessibility/base/compiler_specific.h new file mode 100644 index 0000000000..6943b0c780 --- /dev/null +++ b/engine/src/flutter/third_party/accessibility/base/compiler_specific.h @@ -0,0 +1,308 @@ +// Copyright (c) 2012 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_COMPILER_SPECIFIC_H_ +#define BASE_COMPILER_SPECIFIC_H_ + +#include "build/build_config.h" + +#if defined(COMPILER_MSVC) && !defined(__clang__) +#error "Only clang-cl is supported on Windows, see https://crbug.com/988071" +#endif + +// Annotate a variable indicating it's ok if the variable is not used. +// (Typically used to silence a compiler warning when the assignment +// is important for some other reason.) +// Use like: +// int x = ...; +// ALLOW_UNUSED_LOCAL(x); +#define ALLOW_UNUSED_LOCAL(x) (void)x + +// Annotate a typedef or function indicating it's ok if it's not used. +// Use like: +// typedef Foo Bar ALLOW_UNUSED_TYPE; +#if defined(COMPILER_GCC) || defined(__clang__) +#define ALLOW_UNUSED_TYPE __attribute__((unused)) +#else +#define ALLOW_UNUSED_TYPE +#endif + +// Annotate a function indicating it should not be inlined. +// Use like: +// NOINLINE void DoStuff() { ... } +#if defined(COMPILER_GCC) +#define NOINLINE __attribute__((noinline)) +#elif defined(COMPILER_MSVC) +#define NOINLINE __declspec(noinline) +#else +#define NOINLINE +#endif + +#if defined(COMPILER_GCC) && defined(NDEBUG) +#define ALWAYS_INLINE inline __attribute__((__always_inline__)) +#elif defined(COMPILER_MSVC) && defined(NDEBUG) +#define ALWAYS_INLINE __forceinline +#else +#define ALWAYS_INLINE inline +#endif + +// Annotate a function indicating it should never be tail called. Useful to make +// sure callers of the annotated function are never omitted from call-stacks. +// To provide the complementary behavior (prevent the annotated function from +// being omitted) look at NOINLINE. Also note that this doesn't prevent code +// folding of multiple identical caller functions into a single signature. To +// prevent code folding, see base::debug::Alias. +// Use like: +// void NOT_TAIL_CALLED FooBar(); +#if defined(__clang__) && __has_attribute(not_tail_called) +#define NOT_TAIL_CALLED __attribute__((not_tail_called)) +#else +#define NOT_TAIL_CALLED +#endif + +// Specify memory alignment for structs, classes, etc. +// Use like: +// class ALIGNAS(16) MyClass { ... } +// ALIGNAS(16) int array[4]; +// +// In most places you can use the C++11 keyword "alignas", which is preferred. +// +// But compilers have trouble mixing __attribute__((...)) syntax with +// alignas(...) syntax. +// +// Doesn't work in clang or gcc: +// struct alignas(16) __attribute__((packed)) S { char c; }; +// Works in clang but not gcc: +// struct __attribute__((packed)) alignas(16) S2 { char c; }; +// Works in clang and gcc: +// struct alignas(16) S3 { char c; } __attribute__((packed)); +// +// There are also some attributes that must be specified *before* a class +// definition: visibility (used for exporting functions/classes) is one of +// these attributes. This means that it is not possible to use alignas() with a +// class that is marked as exported. +#if defined(COMPILER_MSVC) +#define ALIGNAS(byte_alignment) __declspec(align(byte_alignment)) +#elif defined(COMPILER_GCC) +#define ALIGNAS(byte_alignment) __attribute__((aligned(byte_alignment))) +#endif + +// Annotate a function indicating the caller must examine the return value. +// Use like: +// int foo() WARN_UNUSED_RESULT; +// To explicitly ignore a result, see |ignore_result()| in base/macros.h. +#undef WARN_UNUSED_RESULT +#if defined(COMPILER_GCC) || defined(__clang__) +#define WARN_UNUSED_RESULT __attribute__((warn_unused_result)) +#else +#define WARN_UNUSED_RESULT +#endif + +// Tell the compiler a function is using a printf-style format string. +// |format_param| is the one-based index of the format string parameter; +// |dots_param| is the one-based index of the "..." parameter. +// For v*printf functions (which take a va_list), pass 0 for dots_param. +// (This is undocumented but matches what the system C headers do.) +// For member functions, the implicit this parameter counts as index 1. +#if defined(COMPILER_GCC) || defined(__clang__) +#define PRINTF_FORMAT(format_param, dots_param) \ + __attribute__((format(printf, format_param, dots_param))) +#else +#define PRINTF_FORMAT(format_param, dots_param) +#endif + +// WPRINTF_FORMAT is the same, but for wide format strings. +// This doesn't appear to yet be implemented in any compiler. +// See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=38308 . +#define WPRINTF_FORMAT(format_param, dots_param) +// If available, it would look like: +// __attribute__((format(wprintf, format_param, dots_param))) + +// Sanitizers annotations. +#if defined(__has_attribute) +#if __has_attribute(no_sanitize) +#define NO_SANITIZE(what) __attribute__((no_sanitize(what))) +#endif +#endif +#if !defined(NO_SANITIZE) +#define NO_SANITIZE(what) +#endif + +// MemorySanitizer annotations. +#if defined(MEMORY_SANITIZER) && !defined(OS_NACL) +#include + +// Mark a memory region fully initialized. +// Use this to annotate code that deliberately reads uninitialized data, for +// example a GC scavenging root set pointers from the stack. +#define MSAN_UNPOISON(p, size) __msan_unpoison(p, size) + +// Check a memory region for initializedness, as if it was being used here. +// If any bits are uninitialized, crash with an MSan report. +// Use this to sanitize data which MSan won't be able to track, e.g. before +// passing data to another process via shared memory. +#define MSAN_CHECK_MEM_IS_INITIALIZED(p, size) \ + __msan_check_mem_is_initialized(p, size) +#else // MEMORY_SANITIZER +#define MSAN_UNPOISON(p, size) +#define MSAN_CHECK_MEM_IS_INITIALIZED(p, size) +#endif // MEMORY_SANITIZER + +// DISABLE_CFI_PERF -- Disable Control Flow Integrity for perf reasons. +#if !defined(DISABLE_CFI_PERF) +#if defined(__clang__) && defined(OFFICIAL_BUILD) +#define DISABLE_CFI_PERF __attribute__((no_sanitize("cfi"))) +#else +#define DISABLE_CFI_PERF +#endif +#endif + +// DISABLE_CFI_ICALL -- Disable Control Flow Integrity indirect call checks. +#if !defined(DISABLE_CFI_ICALL) +#if defined(OS_WIN) +// Windows also needs __declspec(guard(nocf)). +#define DISABLE_CFI_ICALL NO_SANITIZE("cfi-icall") __declspec(guard(nocf)) +#else +#define DISABLE_CFI_ICALL NO_SANITIZE("cfi-icall") +#endif +#endif +#if !defined(DISABLE_CFI_ICALL) +#define DISABLE_CFI_ICALL +#endif + +// Macro useful for writing cross-platform function pointers. +#if !defined(CDECL) +#if defined(OS_WIN) +#define CDECL __cdecl +#else // defined(OS_WIN) +#define CDECL +#endif // defined(OS_WIN) +#endif // !defined(CDECL) + +// Macro for hinting that an expression is likely to be false. +#if !defined(UNLIKELY) +#if defined(COMPILER_GCC) || defined(__clang__) +#define UNLIKELY(x) __builtin_expect(!!(x), 0) +#else +#define UNLIKELY(x) (x) +#endif // defined(COMPILER_GCC) +#endif // !defined(UNLIKELY) + +#if !defined(LIKELY) +#if defined(COMPILER_GCC) || defined(__clang__) +#define LIKELY(x) __builtin_expect(!!(x), 1) +#else +#define LIKELY(x) (x) +#endif // defined(COMPILER_GCC) +#endif // !defined(LIKELY) + +// Compiler feature-detection. +// clang.llvm.org/docs/LanguageExtensions.html#has-feature-and-has-extension +#if defined(__has_feature) +#define HAS_FEATURE(FEATURE) __has_feature(FEATURE) +#else +#define HAS_FEATURE(FEATURE) 0 +#endif + +// Macro for telling -Wimplicit-fallthrough that a fallthrough is intentional. +#if defined(__clang__) +#define FALLTHROUGH [[clang::fallthrough]] +#else +#define FALLTHROUGH +#endif + +#if defined(COMPILER_GCC) +#define PRETTY_FUNCTION __PRETTY_FUNCTION__ +#elif defined(COMPILER_MSVC) +#define PRETTY_FUNCTION __FUNCSIG__ +#else +// See https://en.cppreference.com/w/c/language/function_definition#func +#define PRETTY_FUNCTION __func__ +#endif + +#if !defined(CPU_ARM_NEON) +#if defined(__arm__) +#if !defined(__ARMEB__) && !defined(__ARM_EABI__) && !defined(__EABI__) && \ + !defined(__VFP_FP__) && !defined(_WIN32_WCE) && !defined(ANDROID) +#error Chromium does not support middle endian architecture +#endif +#if defined(__ARM_NEON__) +#define CPU_ARM_NEON 1 +#endif +#endif // defined(__arm__) +#endif // !defined(CPU_ARM_NEON) + +#if !defined(HAVE_MIPS_MSA_INTRINSICS) +#if defined(__mips_msa) && defined(__mips_isa_rev) && (__mips_isa_rev >= 5) +#define HAVE_MIPS_MSA_INTRINSICS 1 +#endif +#endif + +#if defined(__clang__) && __has_attribute(uninitialized) +// Attribute "uninitialized" disables -ftrivial-auto-var-init=pattern for +// the specified variable. +// Library-wide alternative is +// 'configs -= [ "//build/config/compiler:default_init_stack_vars" ]' in .gn +// file. +// +// See "init_stack_vars" in build/config/compiler/BUILD.gn and +// http://crbug.com/977230 +// "init_stack_vars" is enabled for non-official builds and we hope to enable it +// in official build in 2020 as well. The flag writes fixed pattern into +// uninitialized parts of all local variables. In rare cases such initialization +// is undesirable and attribute can be used: +// 1. Degraded performance +// In most cases compiler is able to remove additional stores. E.g. if memory is +// never accessed or properly initialized later. Preserved stores mostly will +// not affect program performance. However if compiler failed on some +// performance critical code we can get a visible regression in a benchmark. +// 2. memset, memcpy calls +// Compiler may replaces some memory writes with memset or memcpy calls. This is +// not -ftrivial-auto-var-init specific, but it can happen more likely with the +// flag. It can be a problem if code is not linked with C run-time library. +// +// Note: The flag is security risk mitigation feature. So in future the +// attribute uses should be avoided when possible. However to enable this +// mitigation on the most of the code we need to be less strict now and minimize +// number of exceptions later. So if in doubt feel free to use attribute, but +// please document the problem for someone who is going to cleanup it later. +// E.g. platform, bot, benchmark or test name in patch description or next to +// the attribute. +#define STACK_UNINITIALIZED __attribute__((uninitialized)) +#else +#define STACK_UNINITIALIZED +#endif + +// The ANALYZER_ASSUME_TRUE(bool arg) macro adds compiler-specific hints +// to Clang which control what code paths are statically analyzed, +// and is meant to be used in conjunction with assert & assert-like functions. +// The expression is passed straight through if analysis isn't enabled. +// +// ANALYZER_SKIP_THIS_PATH() suppresses static analysis for the current +// codepath and any other branching codepaths that might follow. +#if defined(__clang_analyzer__) + +inline constexpr bool AnalyzerNoReturn() __attribute__((analyzer_noreturn)) { + return false; +} + +inline constexpr bool AnalyzerAssumeTrue(bool arg) { + // AnalyzerNoReturn() is invoked and analysis is terminated if |arg| is + // false. + return arg || AnalyzerNoReturn(); +} + +#define ANALYZER_ASSUME_TRUE(arg) ::AnalyzerAssumeTrue(!!(arg)) +#define ANALYZER_SKIP_THIS_PATH() static_cast(::AnalyzerNoReturn()) +#define ANALYZER_ALLOW_UNUSED(var) static_cast(var); + +#else // !defined(__clang_analyzer__) + +#define ANALYZER_ASSUME_TRUE(arg) (arg) +#define ANALYZER_SKIP_THIS_PATH() +#define ANALYZER_ALLOW_UNUSED(var) static_cast(var); + +#endif // defined(__clang_analyzer__) + +#endif // BASE_COMPILER_SPECIFIC_H_ diff --git a/engine/src/flutter/third_party/accessibility/base/no_destructor.h b/engine/src/flutter/third_party/accessibility/base/no_destructor.h new file mode 100644 index 0000000000..21cfef8565 --- /dev/null +++ b/engine/src/flutter/third_party/accessibility/base/no_destructor.h @@ -0,0 +1,98 @@ +// Copyright 2018 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_NO_DESTRUCTOR_H_ +#define BASE_NO_DESTRUCTOR_H_ + +#include +#include + +namespace base { + +// A wrapper that makes it easy to create an object of type T with static +// storage duration that: +// - is only constructed on first access +// - never invokes the destructor +// in order to satisfy the styleguide ban on global constructors and +// destructors. +// +// Runtime constant example: +// const std::string& GetLineSeparator() { +// // Forwards to std::string(size_t, char, const Allocator&) constructor. +// static const base::NoDestructor s(5, '-'); +// return *s; +// } +// +// More complex initialization with a lambda: +// const std::string& GetSessionNonce() { +// static const base::NoDestructor nonce([] { +// std::string s(16); +// crypto::RandString(s.data(), s.size()); +// return s; +// }()); +// return *nonce; +// } +// +// NoDestructor stores the object inline, so it also avoids a pointer +// indirection and a malloc. Also note that since C++11 static local variable +// initialization is thread-safe and so is this pattern. Code should prefer to +// use NoDestructor over: +// - A function scoped static T* or T& that is dynamically initialized. +// - A global base::LazyInstance. +// +// Note that since the destructor is never run, this *will* leak memory if used +// as a stack or member variable. Furthermore, a NoDestructor should never +// have global scope as that may require a static initializer. +template +class NoDestructor { + public: + // Not constexpr; just write static constexpr T x = ...; if the value should + // be a constexpr. + template + explicit NoDestructor(Args&&... args) { + new (storage_) T(std::forward(args)...); + } + + // Allows copy and move construction of the contained type, to allow + // construction from an initializer list, e.g. for std::vector. + explicit NoDestructor(const T& x) { new (storage_) T(x); } + explicit NoDestructor(T&& x) { new (storage_) T(std::move(x)); } + + NoDestructor(const NoDestructor&) = delete; + NoDestructor& operator=(const NoDestructor&) = delete; + + ~NoDestructor() = default; + + const T& operator*() const { return *get(); } + T& operator*() { return *get(); } + + const T* operator->() const { return get(); } + T* operator->() { return get(); } + + const T* get() const { return reinterpret_cast(storage_); } + T* get() { return reinterpret_cast(storage_); } + + private: + alignas(T) char storage_[sizeof(T)]; + +#if defined(LEAK_SANITIZER) + // TODO(https://crbug.com/812277): This is a hack to work around the fact + // that LSan doesn't seem to treat NoDestructor as a root for reachability + // analysis. This means that code like this: + // static base::NoDestructor> v({1, 2, 3}); + // is considered a leak. Using the standard leak sanitizer annotations to + // suppress leaks doesn't work: std::vector is implicitly constructed before + // calling the base::NoDestructor constructor. + // + // Unfortunately, I haven't been able to demonstrate this issue in simpler + // reproductions: until that's resolved, hold an explicit pointer to the + // placement-new'd object in leak sanitizer mode to help LSan realize that + // objects allocated by the contained type are still reachable. + T* storage_ptr_ = reinterpret_cast(storage_); +#endif // defined(LEAK_SANITIZER) +}; + +} // namespace base + +#endif // BASE_NO_DESTRUCTOR_H_ diff --git a/engine/src/flutter/third_party/accessibility/base/numerics/BUILD.gn b/engine/src/flutter/third_party/accessibility/base/numerics/BUILD.gn new file mode 100644 index 0000000000..0bb8dd1036 --- /dev/null +++ b/engine/src/flutter/third_party/accessibility/base/numerics/BUILD.gn @@ -0,0 +1,28 @@ +# Copyright (c) 2017 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. + +# This is a dependency-free, header-only, library, and it needs to stay that +# way to facilitate pulling it into various third-party projects. So, this +# file is here to protect against accidentally introducing external +# dependencies or depending on internal implementation details. +source_set("base_numerics") { + visibility = [ "//base/*" ] + sources = [ + "checked_math_impl.h", + "clamped_math_impl.h", + "safe_conversions_arm_impl.h", + "safe_conversions_impl.h", + "safe_math_arm_impl.h", + "safe_math_clang_gcc_impl.h", + "safe_math_shared_impl.h", + ] + public = [ + "checked_math.h", + "clamped_math.h", + "math_constants.h", + "ranges.h", + "safe_conversions.h", + "safe_math.h", + ] +} diff --git a/engine/src/flutter/third_party/accessibility/base/numerics/README.md b/engine/src/flutter/third_party/accessibility/base/numerics/README.md new file mode 100644 index 0000000000..7e25f131fe --- /dev/null +++ b/engine/src/flutter/third_party/accessibility/base/numerics/README.md @@ -0,0 +1,451 @@ +# `base/numerics` + +This directory contains a dependency-free, header-only library of templates +providing well-defined semantics for safely and performantly handling a variety +of numeric operations, including most common arithmetic operations and +conversions. + +The public API is broken out into the following header files: + +* `checked_math.h` contains the `CheckedNumeric` template class and helper + functions for performing arithmetic and conversion operations that detect + errors and boundary conditions (e.g. overflow, truncation, etc.). +* `clamped_math.h` contains the `ClampedNumeric` template class and + helper functions for performing fast, clamped (i.e. [non-sticky](#notsticky) + saturating) arithmetic operations and conversions. +* `safe_conversions.h` contains the `StrictNumeric` template class and + a collection of custom casting templates and helper functions for safely + converting between a range of numeric types. +* `safe_math.h` includes all of the previously mentioned headers. + +*** aside +**Note:** The `Numeric` template types implicitly convert from C numeric types +and `Numeric` templates that are convertable to an underlying C numeric type. +The conversion priority for `Numeric` type coercions is: + +* `StrictNumeric` coerces to `ClampedNumeric` and `CheckedNumeric` +* `ClampedNumeric` coerces to `CheckedNumeric` +*** + +[TOC] + +## Common patterns and use-cases + +The following covers the preferred style for the most common uses of this +library. Please don't cargo-cult from anywhere else. 😉 + +### Performing checked arithmetic type conversions + +The `checked_cast` template converts between arbitrary arithmetic types, and is +used for cases where a conversion failure should result in program termination: + +```cpp +// Crash if signed_value is out of range for buff_size. +size_t buff_size = checked_cast(signed_value); +``` + +### Performing saturated (clamped) arithmetic type conversions + +The `saturated_cast` template converts between arbitrary arithmetic types, and +is used in cases where an out-of-bounds source value should be saturated to the +corresponding maximum or minimum of the destination type: + +```cpp +// Cast to a smaller type, saturating as needed. +int8_t eight_bit_value = saturated_cast(int_value); + +// Convert from float with saturation to INT_MAX, INT_MIN, or 0 for NaN. +int int_value = saturated_cast(floating_point_value); +``` + +`ClampCeil`, `ClampFloor`, and `ClampRound` provide similar functionality to the +versions in `std::`, but saturate and return an integral type. An optional +template parameter specifies the desired destination type (`int` if +unspecified). These should be used for most floating-to-integral conversions. + +```cpp +// Basically saturated_cast(std::round(floating_point_value)). +int int_value = ClampRound(floating_point_value); + +// A destination type can be explicitly specified. +uint8_t byte_value = ClampFloor(floating_point_value); +``` + +### Enforcing arithmetic type conversions at compile-time + +The `strict_cast` emits code that is identical to `static_cast`. However, +provides static checks that will cause a compilation failure if the +destination type cannot represent the full range of the source type: + +```cpp +// Throw a compiler error if byte_value is changed to an out-of-range-type. +int int_value = strict_cast(byte_value); +``` + +You can also enforce these compile-time restrictions on function parameters by +using the `StrictNumeric` template: + +```cpp +// Throw a compiler error if the size argument cannot be represented by a +// size_t (e.g. passing an int will fail to compile). +bool AllocateBuffer(void** buffer, StrictCast size); +``` + +### Comparing values between arbitrary arithmetic types + +Both the `StrictNumeric` and `ClampedNumeric` types provide well defined +comparisons between arbitrary arithmetic types. This allows you to perform +comparisons that are not legal or would trigger compiler warnings or errors +under the normal arithmetic promotion rules: + +```cpp +bool foo(unsigned value, int upper_bound) { + // Converting to StrictNumeric allows this comparison to work correctly. + if (MakeStrictNum(value) >= upper_bound) + return false; +``` + +*** note +**Warning:** Do not perform manual conversions using the comparison operators. +Instead, use the cast templates described in the previous sections, or the +constexpr template functions `IsValueInRangeForNumericType` and +`IsTypeInRangeForNumericType`, as these templates properly handle the full range +of corner cases and employ various optimizations. +*** + +### Calculating a buffer size (checked arithmetic) + +When making exact calculations—such as for buffer lengths—it's often necessary +to know when those calculations trigger an overflow, undefined behavior, or +other boundary conditions. The `CheckedNumeric` template does this by storing +a bit determining whether or not some arithmetic operation has occured that +would put the variable in an "invalid" state. Attempting to extract the value +from a variable in an invalid state will trigger a check/trap condition, that +by default will result in process termination. + +Here's an example of a buffer calculation using a `CheckedNumeric` type (note: +the AssignIfValid method will trigger a compile error if the result is ignored). + +```cpp +// Calculate the buffer size and detect if an overflow occurs. +size_t size; +if (!CheckAdd(kHeaderSize, CheckMul(count, kItemSize)).AssignIfValid(&size)) { + // Handle an overflow error... +} +``` + +### Calculating clamped coordinates (non-sticky saturating arithmetic) + +Certain classes of calculations—such as coordinate calculations—require +well-defined semantics that always produce a valid result on boundary +conditions. The `ClampedNumeric` template addresses this by providing +performant, non-sticky saturating arithmetic operations. + +Here's an example of using a `ClampedNumeric` to calculate an operation +insetting a rectangle. + +```cpp +// Use clamped arithmetic since inset calculations might overflow. +void Rect::Inset(int left, int top, int right, int bottom) { + origin_ += Vector2d(left, top); + set_width(ClampSub(width(), ClampAdd(left, right))); + set_height(ClampSub(height(), ClampAdd(top, bottom))); +} +``` + +*** note + +The `ClampedNumeric` type is not "sticky", which means the saturation is not +retained across individual operations. As such, one arithmetic operation may +result in a saturated value, while the next operation may then "desaturate" +the value. Here's an example: + +```cpp +ClampedNumeric value = INT_MAX; +++value; // value is still INT_MAX, due to saturation. +--value; // value is now (INT_MAX - 1), because saturation is not sticky. +``` + +*** + +## Conversion functions and StrictNumeric<> in safe_conversions.h + +This header includes a collection of helper `constexpr` templates for safely +performing a range of conversions, assignments, and tests. + +### Safe casting templates + +* `as_signed()` - Returns the supplied integral value as a signed type of + the same width. +* `as_unsigned()` - Returns the supplied integral value as an unsigned type + of the same width. +* `checked_cast<>()` - Analogous to `static_cast<>` for numeric types, except + that by default it will trigger a crash on an out-of-bounds conversion (e.g. + overflow, underflow, NaN to integral) or a compile error if the conversion + error can be detected at compile time. The crash handler can be overridden + to perform a behavior other than crashing. +* `saturated_cast<>()` - Analogous to `static_cast` for numeric types, except + that it returns a saturated result when the specified numeric conversion + would otherwise overflow or underflow. An NaN source returns 0 by + default, but can be overridden to return a different result. +* `strict_cast<>()` - Analogous to `static_cast` for numeric types, except + this causes a compile failure if the destination type is not large + enough to contain any value in the source type. It performs no runtime + checking and thus introduces no runtime overhead. + +### Other helper and conversion functions + +* `ClampCeil<>()` - A convenience function that computes the ceil of its floating- + point arg, then saturates to the destination type (template parameter, + defaults to `int`). +* `ClampFloor<>()` - A convenience function that computes the floor of its + floating-point arg, then saturates to the destination type (template + parameter, defaults to `int`). +* `IsTypeInRangeForNumericType<>()` - A convenience function that evaluates + entirely at compile-time and returns true if the destination type (first + template parameter) can represent the full range of the source type + (second template parameter). +* `IsValueInRangeForNumericType<>()` - A convenience function that returns + true if the type supplied as the template parameter can represent the value + passed as an argument to the function. +* `IsValueNegative()` - A convenience function that will accept any + arithmetic type as an argument and will return whether the value is less + than zero. Unsigned types always return false. +* `ClampRound<>()` - A convenience function that rounds its floating-point arg, + then saturates to the destination type (template parameter, defaults to + `int`). +* `SafeUnsignedAbs()` - Returns the absolute value of the supplied integer + parameter as an unsigned result (thus avoiding an overflow if the value + is the signed, two's complement minimum). + +### StrictNumeric<> + +`StrictNumeric<>` is a wrapper type that performs assignments and copies via +the `strict_cast` template, and can perform valid arithmetic comparisons +across any range of arithmetic types. `StrictNumeric` is the return type for +values extracted from a `CheckedNumeric` class instance. The raw numeric value +is extracted via `static_cast` to the underlying type or any type with +sufficient range to represent the underlying type. + +* `MakeStrictNum()` - Creates a new `StrictNumeric` from the underlying type + of the supplied arithmetic or StrictNumeric type. +* `SizeT` - Alias for `StrictNumeric`. + +## CheckedNumeric<> in checked_math.h + +`CheckedNumeric<>` implements all the logic and operators for detecting integer +boundary conditions such as overflow, underflow, and invalid conversions. +The `CheckedNumeric` type implicitly converts from floating point and integer +data types, and contains overloads for basic arithmetic operations (i.e.: `+`, +`-`, `*`, `/` for all types and `%`, `<<`, `>>`, `&`, `|`, `^` for integers). +However, *the [variadic template functions +](#CheckedNumeric_in-checked_math_h-Non_member-helper-functions) +are the prefered API,* as they remove type ambiguities and help prevent a number +of common errors. The variadic functions can also be more performant, as they +eliminate redundant expressions that are unavoidable with the with the operator +overloads. (Ideally the compiler should optimize those away, but better to avoid +them in the first place.) + +Type promotions are a slightly modified version of the [standard C/C++ numeric +promotions +](http://en.cppreference.com/w/cpp/language/implicit_conversion#Numeric_promotions) +with the two differences being that *there is no default promotion to int* +and *bitwise logical operations always return an unsigned of the wider type.* + +### Example + +``` +#include "base/numerics/checked_math.h" +... +CheckedNumeric variable = 0; +variable++; +variable--; +if (variable.ValueOrDie() == 0) + // Fine, |variable| still within valid range. + +variable--; +variable++; +if (variable.ValueOrDie() == 0) // Breakpoint or configured CheckHandler + // Does not happen as variable underflowed. +``` + +### Members + +The unary negation, increment, and decrement operators are supported, along +with the following unary arithmetic methods, which return a new +`CheckedNumeric` as a result of the operation: + +* `Abs()` - Absolute value. +* `UnsignedAbs()` - Absolute value as an equal-width unsigned underlying type + (valid for only integral types). +* `Max()` - Returns whichever is greater of the current instance or argument. + The underlying return type is whichever has the greatest magnitude. +* `Min()` - Returns whichever is lowest of the current instance or argument. + The underlying return type is whichever has can represent the lowest + number in the smallest width (e.g. int8_t over unsigned, int over + int8_t, and float over int). + +The following are for converting `CheckedNumeric` instances: + +* `type` - The underlying numeric type. +* `AssignIfValid()` - Assigns the underlying value to the supplied + destination pointer if the value is currently valid and within the + range supported by the destination type. Returns true on success. +* `Cast<>()` - Instance method returning a `CheckedNumeric` derived from + casting the current instance to a `CheckedNumeric` of the supplied + destination type. + +*** aside +The following member functions return a `StrictNumeric`, which is valid for +comparison and assignment operations, but will trigger a compile failure on +attempts to assign to a type of insufficient range. The underlying value can +be extracted by an explicit `static_cast` to the underlying type or any type +with sufficient range to represent the underlying type. +*** + +* `IsValid()` - Returns true if the underlying numeric value is valid (i.e. + has not wrapped or saturated and is not the result of an invalid + conversion). +* `ValueOrDie()` - Returns the underlying value. If the state is not valid + this call will trigger a crash by default (but may be overridden by + supplying an alternate handler to the template). +* `ValueOrDefault()` - Returns the current value, or the supplied default if + the state is not valid (but will not crash). + +**Comparison operators are explicitly not provided** for `CheckedNumeric` +types because they could result in a crash if the type is not in a valid state. +Patterns like the following should be used instead: + +```cpp +// Either input or padding (or both) may be arbitrary sizes. +size_t buff_size; +if (!CheckAdd(input, padding, kHeaderLength).AssignIfValid(&buff_size) || + buff_size >= kMaxBuffer) { + // Handle an error... +} else { + // Do stuff on success... +} +``` + +### Non-member helper functions + +The following variadic convenience functions, which accept standard arithmetic +or `CheckedNumeric` types, perform arithmetic operations, and return a +`CheckedNumeric` result. The supported functions are: + +* `CheckAdd()` - Addition. +* `CheckSub()` - Subtraction. +* `CheckMul()` - Multiplication. +* `CheckDiv()` - Division. +* `CheckMod()` - Modulus (integer only). +* `CheckLsh()` - Left integer shift (integer only). +* `CheckRsh()` - Right integer shift (integer only). +* `CheckAnd()` - Bitwise AND (integer only with unsigned result). +* `CheckOr()` - Bitwise OR (integer only with unsigned result). +* `CheckXor()` - Bitwise XOR (integer only with unsigned result). +* `CheckMax()` - Maximum of supplied arguments. +* `CheckMin()` - Minimum of supplied arguments. + +The following wrapper functions can be used to avoid the template +disambiguator syntax when converting a destination type. + +* `IsValidForType<>()` in place of: `a.template IsValid<>()` +* `ValueOrDieForType<>()` in place of: `a.template ValueOrDie<>()` +* `ValueOrDefaultForType<>()` in place of: `a.template ValueOrDefault<>()` + +The following general utility methods is are useful for converting from +arithmetic types to `CheckedNumeric` types: + +* `MakeCheckedNum()` - Creates a new `CheckedNumeric` from the underlying type + of the supplied arithmetic or directly convertible type. + +## ClampedNumeric<> in clamped_math.h + +`ClampedNumeric<>` implements all the logic and operators for clamped +(non-sticky saturating) arithmetic operations and conversions. The +`ClampedNumeric` type implicitly converts back and forth between floating point +and integer data types, saturating on assignment as appropriate. It contains +overloads for basic arithmetic operations (i.e.: `+`, `-`, `*`, `/` for +all types and `%`, `<<`, `>>`, `&`, `|`, `^` for integers) along with comparison +operators for arithmetic types of any size. However, *the [variadic template +functions +](#ClampedNumeric_in-clamped_math_h-Non_member-helper-functions) +are the prefered API,* as they remove type ambiguities and help prevent +a number of common errors. The variadic functions can also be more performant, +as they eliminate redundant expressions that are unavoidable with the operator +overloads. (Ideally the compiler should optimize those away, but better to avoid +them in the first place.) + +Type promotions are a slightly modified version of the [standard C/C++ numeric +promotions +](http://en.cppreference.com/w/cpp/language/implicit_conversion#Numeric_promotions) +with the two differences being that *there is no default promotion to int* +and *bitwise logical operations always return an unsigned of the wider type.* + +*** aside +Most arithmetic operations saturate normally, to the numeric limit in the +direction of the sign. The potentially unusual cases are: + +* **Division:** Division by zero returns the saturated limit in the direction + of sign of the dividend (first argument). The one exception is 0/0, which + returns zero (although logically is NaN). +* **Modulus:** Division by zero returns the dividend (first argument). +* **Left shift:** Non-zero values saturate in the direction of the signed + limit (max/min), even for shifts larger than the bit width. 0 shifted any + amount results in 0. +* **Right shift:** Negative values saturate to -1. Positive or 0 saturates + to 0. (Effectively just an unbounded arithmetic-right-shift.) +* **Bitwise operations:** No saturation; bit pattern is identical to + non-saturated bitwise operations. +*** + +### Members + +The unary negation, increment, and decrement operators are supported, along +with the following unary arithmetic methods, which return a new +`ClampedNumeric` as a result of the operation: + +* `Abs()` - Absolute value. +* `UnsignedAbs()` - Absolute value as an equal-width unsigned underlying type + (valid for only integral types). +* `Max()` - Returns whichever is greater of the current instance or argument. + The underlying return type is whichever has the greatest magnitude. +* `Min()` - Returns whichever is lowest of the current instance or argument. + The underlying return type is whichever has can represent the lowest + number in the smallest width (e.g. int8_t over unsigned, int over + int8_t, and float over int). + +The following are for converting `ClampedNumeric` instances: + +* `type` - The underlying numeric type. +* `RawValue()` - Returns the raw value as the underlying arithmetic type. This + is useful when e.g. assigning to an auto type or passing as a deduced + template parameter. +* `Cast<>()` - Instance method returning a `ClampedNumeric` derived from + casting the current instance to a `ClampedNumeric` of the supplied + destination type. + +### Non-member helper functions + +The following variadic convenience functions, which accept standard arithmetic +or `ClampedNumeric` types, perform arithmetic operations, and return a +`ClampedNumeric` result. The supported functions are: + +* `ClampAdd()` - Addition. +* `ClampSub()` - Subtraction. +* `ClampMul()` - Multiplication. +* `ClampDiv()` - Division. +* `ClampMod()` - Modulus (integer only). +* `ClampLsh()` - Left integer shift (integer only). +* `ClampRsh()` - Right integer shift (integer only). +* `ClampAnd()` - Bitwise AND (integer only with unsigned result). +* `ClampOr()` - Bitwise OR (integer only with unsigned result). +* `ClampXor()` - Bitwise XOR (integer only with unsigned result). +* `ClampMax()` - Maximum of supplied arguments. +* `ClampMin()` - Minimum of supplied arguments. + +The following is a general utility method that is useful for converting +to a `ClampedNumeric` type: + +* `MakeClampedNum()` - Creates a new `ClampedNumeric` from the underlying type + of the supplied arithmetic or directly convertible type. diff --git a/engine/src/flutter/third_party/accessibility/base/numerics/checked_math.h b/engine/src/flutter/third_party/accessibility/base/numerics/checked_math.h new file mode 100644 index 0000000000..50be2f0ea2 --- /dev/null +++ b/engine/src/flutter/third_party/accessibility/base/numerics/checked_math.h @@ -0,0 +1,393 @@ +// Copyright 2017 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_CHECKED_MATH_H_ +#define BASE_NUMERICS_CHECKED_MATH_H_ + +#include + +#include +#include + +#include "base/numerics/checked_math_impl.h" + +namespace base { +namespace internal { + +template +class CheckedNumeric { + static_assert(std::is_arithmetic::value, + "CheckedNumeric: T must be a numeric type."); + + public: + using type = T; + + constexpr CheckedNumeric() = default; + + // Copy constructor. + template + constexpr CheckedNumeric(const CheckedNumeric& rhs) + : state_(rhs.state_.value(), rhs.IsValid()) {} + + template + friend class CheckedNumeric; + + // This is not an explicit constructor because we implicitly upgrade regular + // numerics to CheckedNumerics to make them easier to use. + template + constexpr CheckedNumeric(Src value) // NOLINT(runtime/explicit) + : state_(value) { + static_assert(std::is_arithmetic::value, "Argument must be numeric."); + } + + // This is not an explicit constructor because we want a seamless conversion + // from StrictNumeric types. + template + constexpr CheckedNumeric( + StrictNumeric value) // NOLINT(runtime/explicit) + : state_(static_cast(value)) {} + + // IsValid() - The public API to test if a CheckedNumeric is currently valid. + // A range checked destination type can be supplied using the Dst template + // parameter. + template + constexpr bool IsValid() const { + return state_.is_valid() && + IsValueInRangeForNumericType(state_.value()); + } + + // AssignIfValid(Dst) - Assigns the underlying value if it is currently valid + // and is within the range supported by the destination type. Returns true if + // successful and false otherwise. + template +#if defined(__clang__) || defined(__GNUC__) + __attribute__((warn_unused_result)) +#elif defined(_MSC_VER) + _Check_return_ +#endif + constexpr bool + AssignIfValid(Dst* result) const { + return BASE_NUMERICS_LIKELY(IsValid()) + ? ((*result = static_cast(state_.value())), true) + : false; + } + + // ValueOrDie() - The primary accessor for the underlying value. If the + // current state is not valid it will CHECK and crash. + // A range checked destination type can be supplied using the Dst template + // parameter, which will trigger a CHECK if the value is not in bounds for + // the destination. + // The CHECK behavior can be overridden by supplying a handler as a + // template parameter, for test code, etc. However, the handler cannot access + // the underlying value, and it is not available through other means. + template + constexpr StrictNumeric ValueOrDie() const { + return BASE_NUMERICS_LIKELY(IsValid()) + ? static_cast(state_.value()) + : CheckHandler::template HandleFailure(); + } + + // ValueOrDefault(T default_value) - A convenience method that returns the + // current value if the state is valid, and the supplied default_value for + // any other state. + // A range checked destination type can be supplied using the Dst template + // parameter. WARNING: This function may fail to compile or CHECK at runtime + // if the supplied default_value is not within range of the destination type. + template + constexpr StrictNumeric ValueOrDefault(const Src default_value) const { + return BASE_NUMERICS_LIKELY(IsValid()) + ? static_cast(state_.value()) + : checked_cast(default_value); + } + + // Returns a checked numeric of the specified type, cast from the current + // CheckedNumeric. If the current state is invalid or the destination cannot + // represent the result then the returned CheckedNumeric will be invalid. + template + constexpr CheckedNumeric::type> Cast() const { + return *this; + } + + // This friend method is available solely for providing more detailed logging + // in the tests. Do not implement it in production code, because the + // underlying values may change at any time. + template + friend U GetNumericValueForTest(const CheckedNumeric& src); + + // Prototypes for the supported arithmetic operator overloads. + template + constexpr CheckedNumeric& operator+=(const Src rhs); + template + constexpr CheckedNumeric& operator-=(const Src rhs); + template + constexpr CheckedNumeric& operator*=(const Src rhs); + template + constexpr CheckedNumeric& operator/=(const Src rhs); + template + constexpr CheckedNumeric& operator%=(const Src rhs); + template + constexpr CheckedNumeric& operator<<=(const Src rhs); + template + constexpr CheckedNumeric& operator>>=(const Src rhs); + template + constexpr CheckedNumeric& operator&=(const Src rhs); + template + constexpr CheckedNumeric& operator|=(const Src rhs); + template + constexpr CheckedNumeric& operator^=(const Src rhs); + + constexpr CheckedNumeric operator-() const { + // The negation of two's complement int min is int min, so we simply + // check for that in the constexpr case. + // We use an optimized code path for a known run-time variable. + return MustTreatAsConstexpr(state_.value()) || !std::is_signed::value || + std::is_floating_point::value + ? CheckedNumeric( + NegateWrapper(state_.value()), + IsValid() && (!std::is_signed::value || + std::is_floating_point::value || + NegateWrapper(state_.value()) != + std::numeric_limits::lowest())) + : FastRuntimeNegate(); + } + + constexpr CheckedNumeric operator~() const { + return CheckedNumeric( + InvertWrapper(state_.value()), IsValid()); + } + + constexpr CheckedNumeric Abs() const { + return !IsValueNegative(state_.value()) ? *this : -*this; + } + + template + constexpr CheckedNumeric::type> Max( + const U rhs) const { + using R = typename UnderlyingType::type; + using result_type = typename MathWrapper::type; + // TODO(jschuh): This can be converted to the MathOp version and remain + // constexpr once we have C++14 support. + return CheckedNumeric( + static_cast( + IsGreater::Test(state_.value(), Wrapper::value(rhs)) + ? state_.value() + : Wrapper::value(rhs)), + state_.is_valid() && Wrapper::is_valid(rhs)); + } + + template + constexpr CheckedNumeric::type> Min( + const U rhs) const { + using R = typename UnderlyingType::type; + using result_type = typename MathWrapper::type; + // TODO(jschuh): This can be converted to the MathOp version and remain + // constexpr once we have C++14 support. + return CheckedNumeric( + static_cast( + IsLess::Test(state_.value(), Wrapper::value(rhs)) + ? state_.value() + : Wrapper::value(rhs)), + state_.is_valid() && Wrapper::is_valid(rhs)); + } + + // This function is available only for integral types. It returns an unsigned + // integer of the same width as the source type, containing the absolute value + // of the source, and properly handling signed min. + constexpr CheckedNumeric::type> + UnsignedAbs() const { + return CheckedNumeric::type>( + SafeUnsignedAbs(state_.value()), state_.is_valid()); + } + + constexpr CheckedNumeric& operator++() { + *this += 1; + return *this; + } + + constexpr CheckedNumeric operator++(int) { + CheckedNumeric value = *this; + *this += 1; + return value; + } + + constexpr CheckedNumeric& operator--() { + *this -= 1; + return *this; + } + + constexpr CheckedNumeric operator--(int) { + CheckedNumeric value = *this; + *this -= 1; + return value; + } + + // These perform the actual math operations on the CheckedNumerics. + // Binary arithmetic operations. + template