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

target remote emul:1234

define q
monitor quit
quit
end

define reset
monitor system_reset
end

define mmap
monitor info mem
end

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

# Inspect registers with `reg RAX` or just `reg`
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:
            print(regs)
            return

        if arg.upper() in ['CS', 'DS', 'ES', 'FS', 'GS', 'SS']:
            for l in regs.splitlines():
                if l.startswith(arg.upper()):
                    print(l)
        elif arg.upper() in ['EFL', 'RFL']:
            for l in regs.splitlines():
                if arg.upper() in l:
                    print(' '.join(l.split()[1:]))
        else:
            regex = f"\\b{arg.upper()}\\s?=[a-zA-Z0-9]*\\b"
            matches = re.findall(regex, regs)
            if matches:
                print(matches[0])
            else:
                print(f"Register {arg.upper()} unknown")
Reg()
end

# Break on any label called panic_breakpoint_X which is defined by the PANIC() macro
python
import re
syms = gdb.execute('maintenance print msymbols', False, True)
for l in syms.splitlines():
    matches = re.findall("panic_breakpoint_.*\\b", l)
    if matches:
        name = matches[0].split()[0]
        gdb.execute(f"break {name}", to_string=True)

end

define restore_env
set $name = $arg0
python
regs = ['rax', 'rbx', 'rcx', 'rdx', 'rsi', 'rdi', 'rbp', 'rsp', 'r8', 'r9', 'r10', 'r11', 'r12', 'r13', 'r14', 'r15', 'rip']
stored = {r: gdb.parse_and_eval('$name->'+r) for r in regs}
for r in regs:
    gdb.parse_and_eval(f"${r}={stored[r]}")
gdb.execute("frame 0")
end