set prompt \033[31m(gdb) \033[0m
set disassembly-flavor intel

python
import os
gdb.execute('file ' + os.environ['BUILDROOT'] + 'sysroot/kernel')
end

target remote :1234

set height 0
set width 0

# The PANIC() macro - defined in src/kernel/include/debug.h - creates
# a label of the form panic_breakpoint_xxx, where xxx is a number.
# Unfortunately, gdb can set breakpoints on FUNCTIONS based on regex, but
# not on LABELS.
# The following piece of python code runs objdump to extract all panic_breakpoint
# labels, and set breakpoints for each.
python
import subprocess
import os
dump = subprocess.Popen(("objdump", "-t", os.environ['BUILDROOT'] + "sysroot/kernel"), stdout=subprocess.PIPE)
lines = subprocess.check_output(('grep', 'panic_breakpoint'), stdin=dump.stdout)
dump.wait()
for line in lines.split('\n'):
  name = line.split(' ')[-1]
  if name:
    gdb.execute('b ' + name, to_string=True)
end

define q
monitor quit
end

define reset
monitor system_reset
end

define mmap
monitor info mem
end

python

import re

class Reg(gdb.Command):

  def __init__(self):
    super(Reg, self).__init__("reg", gdb.COMMAND_USER)

  def invoke(self, arg, from_tty):
    regs = gdb.execute('monitor info registers', False, True)

    if not arg:
    # If no argument was given, print the output from qemu
      print regs
      return

    if arg.upper() in ['CS', 'DS', 'ES', 'FS', 'GS', 'SS', 'LDT', 'TR']:
    # Code selectors may contain equals signs
      for l in regs.splitlines():
        if l.startswith(arg.upper()):
          print l
    elif arg.upper() in ['EFL', 'RFL']:
    # The xFLAGS registers contains equals signs
      for l in regs.splitlines():
        if arg.upper() in l:
          print ' '.join(l.split()[1:])
          # The xFLAGS register is the second one on the line
    else:
    # Split at any word followed by and equals sign
    # Clean up both sides of the split and put into a dictionary
    # then print the requested register value
      regex = re.compile("[A-Z0-9]+\s?=")
      names = [v[:-1].strip() for v in regex.findall(regs)]
      values = [v.strip() for v in regex.split(regs)][1:]
      regs = dict(zip(names, values))
      print "%s=%s" % (arg.upper(), regs[arg.upper()])


Reg()

end

define restore_env
set $name = $arg0
python

registers = {r: gdb.parse_and_eval('$name->' + r) for r in
['rax', 'rbx', 'rcx', 'rdx', 'rsi', 'rdi', 'rbp', 'rsp', 'r8', 'r9', 'r10',
'r11', 'r12', 'r13', 'r14', 'r15', 'rip']}

for r in registers.items():
  gdb.parse_and_eval('$%s=%s' % r)
gdb.execute('frame 0')
end
end
