1 /* Copyright (C) 2022-2023 Free Software Foundation, Inc. 2 3 This file is part of GDB. 4 5 This program is free software; you can redistribute it and/or modify 6 it under the terms of the GNU General Public License as published by 7 the Free Software Foundation; either version 3 of the License, or 8 (at your option) any later version. 9 10 This program is distributed in the hope that it will be useful, 11 but WITHOUT ANY WARRANTY; without even the implied warranty of 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 GNU General Public License for more details. 14 15 You should have received a copy of the GNU General Public License 16 along with this program. If not, see <http://www.gnu.org/licenses/>. */ 17 18 #ifndef COMMON_GDB_CHECKED_DYNAMIC_CAST_H 19 #define COMMON_GDB_CHECKED_DYNAMIC_CAST_H 20 21 #include "gdbsupport/traits.h" 22 23 namespace gdb 24 { 25 26 /* This function can be used in place of static_cast when casting between 27 pointers of polymorphic types. The benefit of using this call is that, 28 when compiling in developer mode, dynamic_cast will be used to validate 29 the cast. This use of dynamic_cast is why this function will only 30 work for polymorphic types. 31 32 In non-developer (i.e. production) builds, the dynamic_cast is replaced 33 with a static_cast which is usually significantly faster. */ 34 35 template<typename T, typename V> 36 T 37 checked_static_cast (V *v) 38 { 39 /* We only support casting to pointer types. */ 40 static_assert (std::is_pointer<T>::value, "target must be a pointer type"); 41 42 /* Check for polymorphic types explicitly in case we're in release mode. */ 43 static_assert (std::is_polymorphic<V>::value, "types must be polymorphic"); 44 45 /* Figure out the type that T points to. */ 46 using T_no_P = typename std::remove_pointer<T>::type; 47 48 /* In developer mode this cast uses dynamic_cast to confirm at run-time 49 that the cast from V* to T is valid. However, we can catch some 50 mistakes at compile time, this assert prevents anything other than 51 downcasts, or casts to same type. */ 52 static_assert (std::is_base_of<V, T_no_P>::value 53 || std::is_base_of<T_no_P, V>::value, 54 "types must be related"); 55 56 #ifdef DEVELOPMENT 57 T result = dynamic_cast<T> (v); 58 gdb_assert (result != nullptr); 59 #else 60 T result = static_cast<T> (v); 61 #endif 62 63 return result; 64 } 65 66 } 67 68 #endif /* COMMON_GDB_CHECKED_DYNAMIC_CAST_H */ 69