Home
Code
Contact

GDB Stack Script


Simple script to print Stack layout

Usage and Installation

Installation

place the script show_stack.py somewhere you have your other gdb scripts. (eg ~/.gdb/scripts/)

add

source ~/.gdb/scripts/show-stack.py

to your ~/.gdbinit for autoloading it, or just call the command everytime you want to use it.

Usage

Just call show-stack command anytime after the executable is running.

break main
run
show-stack

Code

import gdb

class ShowStack(gdb.Command):
    def __init__(self):
        super (ShowStack, self).__init__("show-stack", gdb.COMMAND_OBSCURE)

    def invoke(self, args, from_tty):
        rbp = gdb.parse_and_eval('$rbp')
        rsp = gdb.parse_and_eval('$rsp')
        canary = self.defer_long_from_addr(rbp - 8)
        saved_rip = self.defer_long_from_addr(rbp + 8)
        tmp = rsp
        print "Stack"
        print "------------------------"
        while tmp < rbp - 8:
            v = self.defer_long_from_addr(tmp)
            print '0x%016x: 0x%016x' % (tmp, v)
            tmp = tmp + 8
        print '0x%016x: 0x%016x (CANARY)' % ((rbp - 8), canary)
        print '0x%016x: 0x%016x (Saved RBP)' % ((rbp), self.defer_long_from_addr(rbp))
        print '0x%016x: 0x%016x (Saved RIP)' % ((rbp + 8), saved_rip)
        print "------------------------"
        print "Stack Pointer: 0x%016x" % rsp
        print "Stack Base:    0x%016x" % rbp
        print "Canary:        0x%016x" % canary
        print "saved RIP:     0x%016x" % saved_rip

    def defer_long_from_addr(self, addr):
        p_long = gdb.lookup_type('long').pointer()
        val = gdb.Value(addr).cast(p_long).dereference()
        return long(val) & 0xffffffffffffffff

ShowStack()