From f2f108254546136b476af5dcfe77fa8120adc5bc Mon Sep 17 00:00:00 2001 From: Matthew Bentham Date: Wed, 30 Jun 2021 12:00:05 +0100 Subject: Fix undefined behaviour in PolymorphicDowncast In the assertion part of PolymorphicDowncast (and PolymorphicPointerDowncast) there was an unnecessary static_cast of the source pointer to the destination type. This is unnecessary because the implicit conversion of the result pointer back to the base type is sufficient to check for correctness of the downcast, and potentially harmful because if the downcast is actually incorrect the behaviour of static_cast is undefined (not actually known to be a problem in any tested implementation). Fixes warnings detected by ubsan. Signed-off-by: Matthew Bentham Change-Id: I9126288cbb06564009f94e57f6ca4688fc3b53c4 --- include/armnn/utility/PolymorphicDowncast.hpp | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/include/armnn/utility/PolymorphicDowncast.hpp b/include/armnn/utility/PolymorphicDowncast.hpp index 8f052370e5..76b00fa888 100644 --- a/include/armnn/utility/PolymorphicDowncast.hpp +++ b/include/armnn/utility/PolymorphicDowncast.hpp @@ -48,14 +48,14 @@ std::shared_ptr DynamicPointerCast (const std::shared_ptr& sp) // static_pointer_cast overload for raw pointers template -inline T1* StaticPointerCast(T2 *ptr) +inline T1* StaticPointerCast(T2* ptr) { return static_cast(ptr); } // dynamic_pointer_cast overload for raw pointers template -inline T1* DynamicPointerCast(T2 *ptr) +inline T1* DynamicPointerCast(T2* ptr) { return dynamic_cast(ptr); } @@ -71,13 +71,12 @@ inline T1* DynamicPointerCast(T2 *ptr) /// \param value Pointer to the source object /// \return Pointer of type DestType (Pointer of type child) template -DestType PolymorphicDowncast(SourceType value) +DestType PolymorphicDowncast(SourceType* value) { - static_assert(std::is_pointer::value && - std::is_pointer::value, + static_assert(std::is_pointer::value, "PolymorphicDowncast only works with pointer types."); - ARMNN_POLYMORPHIC_CAST_CHECK(dynamic_cast(value) == static_cast(value)); + ARMNN_POLYMORPHIC_CAST_CHECK(dynamic_cast(value) == value); return static_cast(value); } @@ -94,8 +93,8 @@ template auto PolymorphicPointerDowncast(const SourceType& value) { ARMNN_POLYMORPHIC_CAST_CHECK(utility::DynamicPointerCast(value) - == utility::StaticPointerCast(value)); + == value); return utility::StaticPointerCast(value); } -} //namespace armnn \ No newline at end of file +} //namespace armnn -- cgit v1.2.1