Home > Back-end >  Print bounds of function using GDB
Print bounds of function using GDB

Time:11-27

How can I get the bounds of a function using GDB? I would like to know the starting and ending addresses so that I can dump/restore the machine code.

CodePudding user response:

Without Python:

(gdb) pipe disas main | sed -n '2p;x;$p'
0x0000555555555155 < 0>:     push   %rbp
0x00005555555551b4 < 95>:    ret    

(assuming ret only takes up one byte)

With Python:

Create bounds.py.

class Bounds(gdb.Command):
  """print lower and upper pc values for function"""

  def __init__(self):
    super (Bounds, self).__init__ ('info bounds', gdb.COMMAND_USER, gdb.COMPLETE_SYMBOL)

  def invoke(self, argstr, from_tty):
    try:
      (sym, _) = gdb.lookup_symbol(argstr)
    except gdb.error:
      raise gdb.GdbError(f'{argstr} not found. Start the program and try again.')
    if sym == None:
      raise gdb.GdbError(f'{argstr} not found')
    pc = int(sym.value().address)
    block = gdb.block_for_pc(pc)
    print(hex(block.start), hex(block.end-1))

Bounds()

Then use it in GDB like this:

(gdb) source bounds.py
(gdb) info bounds main
0x555555555155 0x5555555551b4

CodePudding user response:

You can use the "info line" command. For example:

(gdb) info line main
Line 115 of "source/main.cpp" starts at address 0x55555555819b <main()> and ends at 0x5555555581a4 <main() 9>.
  • Related