Skip to content

Instantly share code, notes, and snippets.

@charles-l
Last active February 22, 2021 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charles-l/3648f91da44f4b96989af54bd32f5ee2 to your computer and use it in GitHub Desktop.
Save charles-l/3648f91da44f4b96989af54bd32f5ee2 to your computer and use it in GitHub Desktop.
GDB command to visualize the raw memory for the current stack frame
class RawFrame(gdb.Command):
"""Dump the raw memory for the stack while visualizing a stack frame"""
def __init__ (self):
super().__init__('raw-frame', gdb.COMMAND_USER)
def invoke(self, arg, from_tty):
sp = gdb.selected_frame().read_register('rsp').cast(gdb.lookup_type('unsigned char').pointer())
bp = gdb.selected_frame().read_register('rbp').cast(gdb.lookup_type('unsigned char').pointer())
def hex_word(addr, length=8):
return f"{hex(int(addr))}: {' '.join('{:02x}'.format(int(addr[i])) for i in range(length))}"
frame_size = bp - sp + 8
labels = [(bp+8, 'return address'),
(bp, 'saved rbp'),
(sp, 'rsp')]
for sym in gdb.selected_frame().block():
labels.append((sym.value(gdb.selected_frame()).address, sym.name + ':' + str(sym.type)))
labels.sort()
for i in range(-8, frame_size, 8):
s = hex_word(bp-i, length=min(8, frame_size - i))
for addr, label in labels:
if bp-i <= addr < bp-i + 8:
s += f' [{label}]'
print(s)
RawFrame()

Given the following function:

double f(int x, int y, int z) {
   int xx = x + y + z;
   int yy = y * z;
   double zz = pow(xx, yy);
   return zz; // we'll dump the frame at this point
}

// ... f is called in main()

Lets debug it in gdb:

> break f # breakpoint on calling f
> next 3 # fast forward to breakpoint
> raw-frame

  0x7fffffffe718: e4 51 55 55 55 55 00 00 [return address]
  0x7fffffffe710: 20 e7 ff ff ff 7f 00 00 [saved rbp]
  0x7fffffffe708: 04 00 00 00 08 00 00 00 [yy:int] [xx:int]
  0x7fffffffe700: 00 00 00 00 00 00 b0 40 [zz:double]
  0x7fffffffe6f8: 01 00 00 00 03 00 00 00 [y:int] [x:int]
  0x7fffffffe6f0: 00 00 00 00 04 00 00 00 [rsp] [z:int]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment