add-symbol-file-auto
from Jaakko's answer relies on writing to an external file. This can cause issues if the file cannot be read or written. Here is an implementation that offers the same functionality, using a GDB command defined in Python. Add this to your .gdbinit
:
python
# Note: Replace "readelf" with path to binary if it is not in your PATH.
READELF_BINARY = 'readelf'
class AddSymbolFileAuto (gdb.Command):
"""Load symbols from FILE, assuming FILE has been dynamically loaded (auto-address).
Usage: add-symbol-file-auto FILE [-readnow | -readnever]
The necessary starting address of the file's text is resolved by 'readelf'."""
def __init__(self):
super(AddSymbolFileAuto, self).__init__("add-symbol-file-auto", gdb.COMMAND_FILES)
def invoke(self, solibpath, from_tty):
from os import path
self.dont_repeat()
if os.path.exists(solibpath) == False:
print ("{0}: No such file or directory." .format(solibpath))
return
offset = self.get_text_offset(solibpath)
gdb_cmd = "add-symbol-file %s %s" % (solibpath, offset)
gdb.execute(gdb_cmd, from_tty)
def get_text_offset(self, solibpath):
import subprocess
elfres = subprocess.check_output([READELF_BINARY, "-WS", solibpath])
for line in elfres.splitlines():
if "] .text " in line:
return "0x" + line.split()[4]
return "" # TODO: Raise error when offset is not found?
def complete(self, text, word):
return gdb.COMPLETE_FILENAME
AddSymbolFileAuto()
end
Usage example:
add-symbol-file-auto foo.symbol
Note that merely loading the symbols with add-symbol-file
can allow you to set breakpoints, but this does not automatically mean that you can do something useful with it, such as actually triggering the breakpoint. Use info sharedlibrary
(or info shared
) to verify that the symbols are actually relevant to the debugging target (optionally with a pattern to show specific results instead of all). It should look like this:
(gdb) gdb-symbol-file-auto path/to/library.symbols
(gdb) info shared symbol-file
From To Syms Read Shared Object Library
0x0000abc0 0x0000def0 Yes path/to/library
The following is shown when the loaded symbols are not used:
From To Syms Read Shared Object Library
0x0000abc0 0x0000def0 Yes (*) path/to/library
(*): Shared library is missing debugging information.
The following is shown when GDB is unable to load the library at all (e.g. if GDB has a bug):
From To Syms Read Shared Object Library
0x0000abc0 0x0000def0 No path/to/library