Skip to content

Instantly share code, notes, and snippets.

@cr7pt0gr4ph7
Last active August 29, 2015 14:10
Show Gist options
  • Save cr7pt0gr4ph7/75f6ee4363ec17ec1671 to your computer and use it in GitHub Desktop.
Save cr7pt0gr4ph7/75f6ee4363ec17ec1671 to your computer and use it in GitHub Desktop.
Utilities for working with C++ ELF files
#!/bin/bash
# usage: demangle_ld_trace.bash [filename|STDIN]
#
# Demangle C++ symbol names inside a ld.so trace file
# (obtained by setting LD_DEBUG=symbols and LD_DEBUG_OUTPUT=somefile.trace)
# by feeding them to name demangler c++filt.
#
# The idea to use perl for the replacement is based upon:
# http://stackoverflow.com/a/6355941/
# (Q: "using command substitution inside a sed script, with arguments")
#
# This is combined with the information from below to actually call c++filt:
# http://perlmeme.org/faqs/system/system.html (for calling shell commands using backticks)
# http://www.perlmeme.org/howtos/perlfunc/chomp_function.html (for removing the last newline character from the command output)
#
cat ${1:-} | perl -pe 'sub demangle {
$raw = @_[0];
$text = `c++filt $raw`;
chomp($text);
$eq = ($text eq $raw);
$text = ($eq) ? $text : "$text ($raw)";
return "symbol=$text ($raw);"; }; s/symbol=([^;]+);/demangle($1)/e'
#!/bin/bash
# C++ name mangler based upon:
# http://stackoverflow.com/questions/12400105/getting-mangled-name-from-demangled-name
IFS='::' read -a array <<< "$1"
indexes=("${!array[@]}")
prefix=""
middle=""
suffix=""
rettype=""
if [ -z "$2" ]; then
rettype="void"
fi
for index in "${indexes[@]}"
do
#echo "$index ${array[index]}"
if [ $index == ${indexes[-1]} ]; then
#echo "last"
middle="$rettype ${array[index]};"
elif [ -n "${array[index]}" ]; then
#echo "not empty"
prefix="${prefix}struct ${array[index]}{"
suffix="${suffix}};"
fi
done
#echo "$prefix$middle$suffix $rettype $1{}"
echo "$prefix$middle$suffix $rettype $1{}" | g++ -x c++ -S - -o- | grep "^_.*:$"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment