Function to mangle/demangle functions

后端 未结 3 1289
野性不改
野性不改 2020-12-14 10:06

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

相关标签:
3条回答
  • 2020-12-14 10:24

    This is a slight variation on Dave's version above. This is a unique_ptr version with a little bit of checking on the return type, though it looks like you could just ignore that, but somehow that just seems unclean.

    auto cppDemangle (const char *abiName)
    {
        //
        // This function allocates and returns storage in ret
        //
        int status;
        char *ret = abi::__cxa_demangle(abiName, 0 /* output buffer */, 0 /* length */, &status);
    
        auto deallocator = ( [](char *mem) { if (mem) free((void*)mem); } );
    
        if (status) {
            // 0: The demangling operation succeeded.
            // -1: A memory allocation failure occurred.
            // -2: mangled_name is not a valid name under the C++ ABI mangling rules.
            // -3: One of the arguments is invalid.
            std::unique_ptr<char, decltype(deallocator) > retval(nullptr, deallocator);
        }
    
        //
        // Create a unique pointer to take ownership of the returned string so it
        // is freed when that pointers goes out of scope
        //
        std::unique_ptr<char, decltype(deallocator) > retval(ret, deallocator);
        return retval;
    }
    
    0 讨论(0)
  • 2020-12-14 10:29

    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));
    
    0 讨论(0)
  • 2020-12-14 10:43

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

    0 讨论(0)
提交回复
热议问题