Add support for analyzing C++ dynamic_cast calls
The GCC analyzer now understands C++ `dynamic_cast` to detect bugs like dereferencing null pointers after failed casts.
The GCC static analyzer has been enhanced to understand C++ dynamic_cast operations, resolving a limitation where results of failed casts were treated as opaque. This new functionality allows the analyzer to statically evaluate dynamic_cast calls, similar to the frontend’s cxx_eval_dynamic_cast, enabling it to detect bugs such as dereferencing a null pointer resulting from a failed cast. It works by traversing BINFOs and calculating offsets without directly using frontend trees.
In Details
A new known_function for __dynamic_cast is introduced in kf-lang-cp.cc, enabling the analyzer to statically evaluate cast results. The implementation, evaluate_dyncast, mimics cxx_eval_dynamic_cast but operates without frontend trees. It leverages helper functions like get_type_from_tinfo_arg and lookup_subobject_matches to traverse BINFOs and determine the target object and its offset. Additionally, region_model::get_vtable_from_obj is factored out to support vtable derivation from objects with virtual functions.
- dynamic_cast
- A C++ runtime cast operator used for safe, polymorphic downcasting or crosscasting of object pointers and references. It performs a runtime check to ensure the cast is valid.
- Static Analyzer
- A tool that examines source code to find potential bugs, security vulnerabilities, or style violations without actually executing the code. The GCC analyzer is part of the GCC compiler.
- BINFO
- Likely refers to 'Base Class Information,' a data structure used internally by the compiler to represent information about base classes and their layout within a derived class, crucial for RTTI and dynamic casting.
- vtable
- Virtual Table. A lookup table used by C++ compilers to implement virtual function calls. It contains pointers to the virtual functions of a class.
- RTTI
- Run-Time Type Information. A C++ feature that allows a program to determine the type of an object at runtime, essential for
dynamic_castandtypeid.