2
0

coroutine.py 6.0 KB

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