Consider this simple hierarchy:
class Base { public: virtual ~Base() { } };
class Derived : public Base { };
Trying to downcast Base*
Magic.
Just kidding. If you really want to research this in detail, the code that implements it for GCC is in libsupc++, a part of libstdc++.
https://github.com/mirrors/gcc/tree/master/libstdc%2B%2B-v3/libsupc%2B%2B
Specifically, look for all files with tinfo or type_info in their name.
Or read the description here, that's probably a lot more accessible:
https://itanium-cxx-abi.github.io/cxx-abi/abi.html#rtti
This details the format of the type information the compiler generates and should give you clues how the runtime support then finds the right casting path.