Function to mangle/demangle functions

15,227

Solution 1

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

Solution 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));
Share:
15,227
Syntax_Error
Author by

Syntax_Error

Updated on July 18, 2022

Comments

  • Syntax_Error
    Syntax_Error almost 2 years

    I have previously, here, been shown that C++ functions aren't easily represented in assembly. Now I am interested in reading them one 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.
    

    Has anyone ever tried something like that? I want to demangle/mangle in C.

    My compiler is gcc 4.x.