If you're using g++
on x86
or ARM
then you can try this one(ish)-liner:
echo "<your-type> <your-name>(<your-parameters>) {}" \
| g++ -x c++ - -o - -S -w \
| grep '^_' \
| sed 's/:$//'
g++
invokes the front-end for the cc1plusplus
compiler.
g++ -x c++
says to interpret the input language as C++.
g++ -x c++ -
says to get the input from the stdin
(the piped echo
).
g++ -x c++ - -o -
says to output to the stdout
(your display).
g++ -x c++ - -o - -S
says to output assembler/assembly language.
g++ -x c++ - -o - -S -w
says to silence all warnings from cc1plusplus
.
This gives us the raw assembly code output.
For x86(_64)
or ARM(v7/v8)
machines, the mangled name in the assembly output will start at the beginning of a line, prefixed by an underscore (_
) (typically _Z
).
Notably, no other lines will begin this way, so lines beginning with an underscore are guaranteed to be a code object name.
grep '^_'
says to filter the output down to only lines beginning with an underscore (_
).
Now we have the mangled names (one on each line--depending on how many you echo
ed into g++
).
However, all the names in the assembly are suffixed by a colon (:
) character. We can remove it with the Stream-EDitor, sed
.
sed 's/:$//'
says to remove the colon (:
) character at the end of each line.
Lastly, a couple of concrete examples, showing mangling and then demangling for you to use as reference (output from an x86
machine):
Example 1:
echo "int MyFunction(int x, char y) {}" \
| g++ -x c++ - -o - -S -w \
| grep '^_' \
| sed 's/:$//'
_Z10MyFunctionic # This is the output from the command pipeline
c++filt _Z10MyFunctionic
MyFunction(int, char) # This is the output from c++filt
Example 2:
echo \
"\
namespace YourSpace { int YourFunction(int, char); }
int YourSpace::YourFunction(int x, char y) {}
"\
| g++ -x c++ - -o - -S -w \
| grep '^_' \
| sed 's/:$//'
_ZN9YourSpace12YourFunctionEic # This is the output from the command pipeline
c++filt _ZN9YourSpace12YourFunctionEic
YourSpace::YourFunction(int, char) # This is the output from c++filt
I originally saw how to apply g++
to stdin
in Romain Picard's article:
How To Mangle And Demangle A C++ Method Name
I think it's a good read.
Hope this helped you.
Additional Info:
Primary source: GNU <libstdc++> Manual: Chapter 28 Part 3: Demangling
ldsym
? – Heeltap