1# 2# GDB debugging support 3# 4# Copyright 2012 Red Hat, Inc. and/or its affiliates 5# 6# Authors: 7# Avi Kivity <avi@redhat.com> 8# 9# This work is licensed under the terms of the GNU GPL, version 2 10# or later. See the COPYING file in the top-level directory. 11 12import gdb 13 14VOID_PTR = gdb.lookup_type('void').pointer() 15 16def pthread_self(): 17 '''Fetch the base address of TLS.''' 18 return gdb.parse_and_eval("$fs_base") 19 20def get_glibc_pointer_guard(): 21 '''Fetch glibc pointer guard value''' 22 fs_base = pthread_self() 23 return gdb.parse_and_eval('*(uint64_t*)((uint64_t)%s + 0x30)' % fs_base) 24 25def glibc_ptr_demangle(val, pointer_guard): 26 '''Undo effect of glibc's PTR_MANGLE()''' 27 return gdb.parse_and_eval('(((uint64_t)%s >> 0x11) | ((uint64_t)%s << (64 - 0x11))) ^ (uint64_t)%s' % (val, val, pointer_guard)) 28 29def get_jmpbuf_regs(jmpbuf): 30 JB_RBX = 0 31 JB_RBP = 1 32 JB_R12 = 2 33 JB_R13 = 3 34 JB_R14 = 4 35 JB_R15 = 5 36 JB_RSP = 6 37 JB_PC = 7 38 39 pointer_guard = get_glibc_pointer_guard() 40 return {'rbx': jmpbuf[JB_RBX], 41 'rbp': glibc_ptr_demangle(jmpbuf[JB_RBP], pointer_guard), 42 'rsp': glibc_ptr_demangle(jmpbuf[JB_RSP], pointer_guard), 43 'r12': jmpbuf[JB_R12], 44 'r13': jmpbuf[JB_R13], 45 'r14': jmpbuf[JB_R14], 46 'r15': jmpbuf[JB_R15], 47 'rip': glibc_ptr_demangle(jmpbuf[JB_PC], pointer_guard) } 48 49def symbol_lookup(addr): 50 # Example: "__clone3 + 44 in section .text of /lib64/libc.so.6" 51 result = gdb.execute(f"info symbol {hex(addr)}", to_string=True).strip() 52 try: 53 if "+" in result: 54 (func, result) = result.split(" + ") 55 (offset, result) = result.split(" in ") 56 else: 57 offset = "0" 58 (func, result) = result.split(" in ") 59 func_str = f"{func}<+{offset}> ()" 60 except: 61 return f"??? ({result})" 62 63 # Example: Line 321 of "../util/coroutine-ucontext.c" starts at address 64 # 0x55cf3894d993 <qemu_coroutine_switch+99> and ends at 0x55cf3894d9ab 65 # <qemu_coroutine_switch+123>. 66 result = gdb.execute(f"info line *{hex(addr)}", to_string=True).strip() 67 if not result.startswith("Line "): 68 return func_str 69 result = result[5:] 70 71 try: 72 result = result.split(" starts ")[0] 73 (line, path) = result.split(" of ") 74 path = path.replace("\"", "") 75 except: 76 return func_str 77 78 return f"{func_str} at {path}:{line}" 79 80def dump_backtrace(regs): 81 ''' 82 Backtrace dump with raw registers, mimic GDB command 'bt'. 83 ''' 84 # Here only rbp and rip that matter.. 85 rbp = regs['rbp'] 86 rip = regs['rip'] 87 i = 0 88 89 while rbp: 90 # For all return addresses on stack, we want to look up symbol/line 91 # on the CALL command, because the return address is the next 92 # instruction instead of the CALL. Here -1 would work for any 93 # sized CALL instruction. 94 print(f"#{i} {hex(rip)} in {symbol_lookup(rip if i == 0 else rip-1)}") 95 rip = gdb.parse_and_eval(f"*(uint64_t *)(uint64_t)({hex(rbp)} + 8)") 96 rbp = gdb.parse_and_eval(f"*(uint64_t *)(uint64_t)({hex(rbp)})") 97 i += 1 98 99def dump_backtrace_live(regs): 100 ''' 101 Backtrace dump with gdb's 'bt' command, only usable in a live session. 102 ''' 103 old = dict() 104 105 # remember current stack frame and select the topmost 106 # so that register modifications don't wreck it 107 selected_frame = gdb.selected_frame() 108 gdb.newest_frame().select() 109 110 for i in regs: 111 old[i] = gdb.parse_and_eval('(uint64_t)$%s' % i) 112 113 for i in regs: 114 gdb.execute('set $%s = %s' % (i, regs[i])) 115 116 gdb.execute('bt') 117 118 for i in regs: 119 gdb.execute('set $%s = %s' % (i, old[i])) 120 121 selected_frame.select() 122 123def bt_jmpbuf(jmpbuf): 124 '''Backtrace a jmpbuf''' 125 regs = get_jmpbuf_regs(jmpbuf) 126 try: 127 # This reuses gdb's "bt" command, which can be slightly prettier 128 # but only works with live sessions. 129 dump_backtrace_live(regs) 130 except: 131 # If above doesn't work, fallback to poor man's unwind 132 dump_backtrace(regs) 133 134def co_cast(co): 135 return co.cast(gdb.lookup_type('CoroutineUContext').pointer()) 136 137def coroutine_to_jmpbuf(co): 138 coroutine_pointer = co_cast(co) 139 return coroutine_pointer['env']['__jmpbuf'] 140 141 142class CoroutineCommand(gdb.Command): 143 '''Display coroutine backtrace''' 144 def __init__(self): 145 gdb.Command.__init__(self, 'qemu coroutine', gdb.COMMAND_DATA, 146 gdb.COMPLETE_NONE) 147 148 def invoke(self, arg, from_tty): 149 argv = gdb.string_to_argv(arg) 150 if len(argv) != 1: 151 gdb.write('usage: qemu coroutine <coroutine-pointer>\n') 152 return 153 154 bt_jmpbuf(coroutine_to_jmpbuf(gdb.parse_and_eval(argv[0]))) 155 156class CoroutineBt(gdb.Command): 157 '''Display backtrace including coroutine switches''' 158 def __init__(self): 159 gdb.Command.__init__(self, 'qemu bt', gdb.COMMAND_STACK, 160 gdb.COMPLETE_NONE) 161 162 def invoke(self, arg, from_tty): 163 164 gdb.execute("bt") 165 166 try: 167 # This only works with a live session 168 co_ptr = gdb.parse_and_eval("qemu_coroutine_self()") 169 except: 170 # Fallback to use hard-coded ucontext vars if it's coredump 171 co_ptr = gdb.parse_and_eval("co_tls_current") 172 173 if co_ptr == False: 174 return 175 176 while True: 177 co = co_cast(co_ptr) 178 co_ptr = co["base"]["caller"] 179 if co_ptr == 0: 180 break 181 gdb.write("Coroutine at " + str(co_ptr) + ":\n") 182 bt_jmpbuf(coroutine_to_jmpbuf(co_ptr)) 183 184class CoroutineSPFunction(gdb.Function): 185 def __init__(self): 186 gdb.Function.__init__(self, 'qemu_coroutine_sp') 187 188 def invoke(self, addr): 189 return get_jmpbuf_regs(coroutine_to_jmpbuf(addr))['rsp'].cast(VOID_PTR) 190 191class CoroutinePCFunction(gdb.Function): 192 def __init__(self): 193 gdb.Function.__init__(self, 'qemu_coroutine_pc') 194 195 def invoke(self, addr): 196 return get_jmpbuf_regs(coroutine_to_jmpbuf(addr))['rip'].cast(VOID_PTR) 197