Search code examples
c++symbolsname-mangling

Mangling names for templated functions in runtime - possible?


Suppose I've written a foo<T> function (I have a full signature with namespaces), but never mind that right now); and suppose there is no other function overloading it (in the relevant namespace it's in). Now let's place ourselves at runtime. Suppose I have the string "foo", and for some type MyType, I have typeid(MyType) (from the <memory> header).

Can I somehow obtain the symbol name for foo<MyType>?

Second version of this question: Now suppose I have the full signature of foo as a string, instead of just the name; and drop the assumption about no overloads.

Notes:

  • No, I'm not asking about the symbol itself, just the name. That would be an interesting question for another time.
  • Answers which depend on foo<T> coming from a shared library are relevant, although I don't think it should matter just for the symbol name.
  • I don't care about performance here, I'll do whatever it takes. Help me Obi Wan, you're my last hope etc. So, RTTI, compiling with weird flags, whatever.
  • Platform-dependent answers are also relevant: GNU/Linux with kernel version >= 3.x , an x86_64 CPU , gcc >= 4.8 .

Solution

  • No, you can't.

    To get the mangled name of an instantiated function template, you need in the simplest case the following information:

    • The fully qualified name of the function (you said you only have "foo", what if the function is in a namespace?)
    • The types of all template type arguments (the mangled name of the type may suffice, if the mangling scheme for the function name embeds the type name directly; otherwise you'd need the full type name, potentially recursively into all template arguments of the type).
    • The types of all function arguments (same caveat applies).

    This is assuming that you don't have template template parameters, or non-type parameters. It gets a lot more complicated when you have those, since it may require mangled forms of entire expression trees. It also assumes that you're not dealing with partial or full explicit specialization, which is even more complicated. And it is finally assuming that your function doesn't have any special decoration due to compiler-specific extensions (e.g. __stdcall in 32-bit Windows environments). Oh, and some ABIs may encode the return type of the function as well.

    Since according to your premise you only have the function name (not clear on whether it is fully qualified) and the type_id objects of the template arguments (which may work as a source of the mangled type name, but do not on all platforms), you have insufficient information to recreate the mangled name.

    This leaves the option of obtaining a list of all compiled symbols from your binary (if such is available) and searching for a most likely candidate, which is of course error-prone.