Created
July 6, 2011 19:02
-
-
Save bnoordhuis/1068052 to your computer and use it in GitHub Desktop.
trace function calls with gdb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import re | |
import sys | |
import subprocess | |
import tempfile | |
nm = 'nm' | |
gdb = 'gdb' | |
backtrace = 1 | |
ours, theirs = [], [] | |
i = 0 | |
for arg in sys.argv[1:]: | |
if arg == '--': | |
i = 1 | |
elif i == 0 and arg.startswith('--backtrace='): | |
backtrace = int(arg[12:]) | |
else: | |
(theirs if i else ours).append(arg) | |
regex = re.compile('|'.join('(%s)' % s for s in ours)) | |
if not theirs: | |
print "Usage: %s regex [...] -- program [args]" % sys.argv[0] | |
sys.exit(1) | |
program, args = theirs[0], theirs[1:] | |
# not very memory efficient | |
stdout, stderr = subprocess.Popen([nm, '-C', program], stdout=subprocess.PIPE).communicate() | |
if stderr: | |
print stderr | |
sys.exit(1) | |
f = tempfile.NamedTemporaryFile() | |
f.write("set height 0\n") # disable gdb's pager | |
f.write("set breakpoint pending on\n") | |
template = """ | |
break %(name)s | |
commands | |
silent | |
backtrace %(backtrace)d | |
continue | |
end | |
""" | |
for line in stdout.split("\n"): | |
fields = line.split(None, 2) # address, type, name | |
if len(fields) == 3 and fields[1] in 'TUVWtuvw' and regex.search(fields[2]): | |
f.write(template % dict(name=fields[2], backtrace=backtrace)) | |
f.flush() | |
retcode = subprocess.call( | |
[gdb, '-x', f.name, '--args', program] + args) | |
sys.exit(retcode) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment