function to mangle/demangle functions

五迷三道 提交于 2019-11-27 14:00:06

问题


I have previously ,here, been shown that C++ functions aren't easily represented in assembly. Now I am interested in reading 1 way or another because callgrind, part of valgrind, show them demangled while in assembly they are shown mangled, so i would like to either mangle the valgrind function output or demangle the assembly names of functions. Anyone ever tried something like that? I was looking at a website and found out the following:

 Code to implement demangling is part of the GNU Binutils package; 
see libiberty/cplus-dem.c and include/demangle.h.

anyone ever tried something like that, I want to demangle/mangle in C? my compiler is gcc 4.x


回答1:


Use the c++filt command line tool to demangle the name.




回答2:


Here is my C++11 implementation, derived from the following page: http://gcc.gnu.org/onlinedocs/libstdc++/manual/ext_demangling.html

#include <cxxabi.h>  // needed for abi::__cxa_demangle

std::shared_ptr<char> cppDemangle(const char *abiName)
{
  int status;    
  char *ret = abi::__cxa_demangle(abiName, 0, 0, &status);  

  /* NOTE: must free() the returned char when done with it! */
  std::shared_ptr<char> retval;
  retval.reset( (char *)ret, [](char *mem) { if (mem) free((void*)mem); } );
  return retval;
}

To make the memory management easy on the returned (char *), I'm using a std::shared_ptr with a custom lambda 'deleter' function that calls free() on the returned memory. Because of this, I don't ever have to worry about deleting the memory on my own, I just use it as needed, and when the shared_ptr goes out of scope, the memory will be free'd.

Here's the macro I use to access the demangled type name as a (const char *). Note that you must have RTTI turned on to have access to 'typeid'

#define CLASS_NAME(somePointer) ((const char *) cppDemangle(typeid(*somePointer).name()).get() )

So, from within a C++ class I can say:

printf("I am inside of a %s\n",CLASS_NAME(this));


来源:https://stackoverflow.com/questions/4939636/function-to-mangle-demangle-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!