C ++ RTTI without libstdC ++. Is it possible?

I want to explore how to link a C ++ program without libstdC ++, but with rtti support. I tried to compile it as described below. Any necessary but missing character that I can define as the strcmp function in the example, but is it possible to define characters like info without explicit magic / sorcery? And if possible, how?

cd /tmp && cat << 'eof' >rtti.cpp && g++ -nodefaultlibs -lc rtti.cpp

 extern "C" int strcmp(const char *s1, const char *s2) { return 0; }; #include "typeinfo" int main(){ return typeid(int) == typeid(char); } 

Linker says:

/tmp/cc6rBAef.o: In the `main 'function:

 rtti.cpp:(.text+0x18): undefined reference to `typeinfo for char' rtti.cpp:(.text+0x1d): undefined reference to `typeinfo for int' collect2: error: ld returned 1 exit status 

So, how can I define 'typeinfo from char' (_ ZTIc @@ CXXABI_1.3) in the source file using g ++ or clang ++?

PS. Do not ask me why I need this. Just curiosity.

+4
source share
2 answers

Thanks to gcc community for the tip.

Answer:

"gcc use some magic to replace the __fundamental_type_info destructor with a character set of type info

The replacement code is placed in the file: gcc-4.7.2 / gcc / cp / rtti.c, void emit_support_tinfos(void);

rtti.cc:

 #include <typeinfo> namespace __cxxabiv1 { class __fundamental_type_info:public std::type_info{ public: explicit __fundamental_type_info(const char* __n) : std::type_info(_n) { } virtual ~__fundamental_type_info(){}; }; } int main(){ return typeid(int) == typeid(char); } 

All major file types are entered into the object file at compile time.

$g++ -c ./rtti.cc;readelf -sW ./rtti.o |c++filt|grep typeinfo|wc -l

$153

So the answer to the question.

+2
source

Since the characters needed for RTTI seem to be in the libstdc++ , you cannot do this without it. Please note that I found this by running

 readelf -Ws `g++ -print-file-name=libstdc++.so` | awk '{print $8}' | c++filt | grep 'typeinfo for' 

However, you can statically refer to libstdc++ :

 g++ -static-libstdc++ rtti.cpp 

Thus, you will not have any dynamic dependencies on libstdc++ , and only the characters you need will be pulled into your executable file. (Well, all the characters from the object file that contains the necessary characters, fundamental_type_info.o in your example, I suppose.)

+4
source

Source: https://habr.com/ru/post/1486549/


All Articles