Skip to content

Instantly share code, notes, and snippets.

@nick0ve
Created September 8, 2021 19:10
Show Gist options
  • Save nick0ve/1a114c698c313090abb97c37b9fd7adc to your computer and use it in GitHub Desktop.
Save nick0ve/1a114c698c313090abb97c37b9fd7adc to your computer and use it in GitHub Desktop.
GDB Gotchas

Load symbol file in gdb (without malding)

https://stackoverflow.com/questions/20380204/how-to-load-multiple-symbol-files-in-gdb

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 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)
        print (f"{gdb_cmd = }")
        gdb.execute(gdb_cmd, from_tty)

    def get_text_offset(self, solibpath):
        import subprocess
        elfres = subprocess.check_output([READELF_BINARY, "-WS", solibpath]).decode()
        for line in elfres.splitlines():
            if "] .text " in line:
                return "0x" + line.split()[4]
        raise Exception("Offset to .text not found :(   ")
        #return ""  # TODO: Raise error when offset is not found?

    def complete(self, text, word):
        return gdb.COMPLETE_FILENAME

AddSymbolFileAuto()
end

Example with ubuntu's libc, what you need:

  • libc-2.27.so <- the stripped library used normally by the system
  • libc-2.27.so.debug <- the separate elf containing only debug informations
  • eu-unstrip libc-2.27.so libc-2.27.so.debug says gibberish

Solution: gdb binary.elf -ex "add-symbol-file-auto libc-2.27.so.debug"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment