dump-guest-memory.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. # This python script adds a new gdb command, "dump-guest-memory". It
  2. # should be loaded with "source dump-guest-memory.py" at the (gdb)
  3. # prompt.
  4. #
  5. # Copyright (C) 2013, Red Hat, Inc.
  6. #
  7. # Authors:
  8. # Laszlo Ersek <lersek@redhat.com>
  9. #
  10. # This work is licensed under the terms of the GNU GPL, version 2 or later. See
  11. # the COPYING file in the top-level directory.
  12. #
  13. # The leading docstring doesn't have idiomatic Python formatting. It is
  14. # printed by gdb's "help" command (the first line is printed in the
  15. # "help data" summary), and it should match how other help texts look in
  16. # gdb.
  17. import struct
  18. UINTPTR_T = gdb.lookup_type("uintptr_t")
  19. TARGET_PAGE_SIZE = 0x1000
  20. TARGET_PAGE_MASK = 0xFFFFFFFFFFFFF000
  21. # Various ELF constants
  22. EM_X86_64 = 62 # AMD x86-64 target machine
  23. ELFDATA2LSB = 1 # little endian
  24. ELFCLASS64 = 2
  25. ELFMAG = "\x7FELF"
  26. EV_CURRENT = 1
  27. ET_CORE = 4
  28. PT_LOAD = 1
  29. PT_NOTE = 4
  30. # Special value for e_phnum. This indicates that the real number of
  31. # program headers is too large to fit into e_phnum. Instead the real
  32. # value is in the field sh_info of section 0.
  33. PN_XNUM = 0xFFFF
  34. # Format strings for packing and header size calculation.
  35. ELF64_EHDR = ("4s" # e_ident/magic
  36. "B" # e_ident/class
  37. "B" # e_ident/data
  38. "B" # e_ident/version
  39. "B" # e_ident/osabi
  40. "8s" # e_ident/pad
  41. "H" # e_type
  42. "H" # e_machine
  43. "I" # e_version
  44. "Q" # e_entry
  45. "Q" # e_phoff
  46. "Q" # e_shoff
  47. "I" # e_flags
  48. "H" # e_ehsize
  49. "H" # e_phentsize
  50. "H" # e_phnum
  51. "H" # e_shentsize
  52. "H" # e_shnum
  53. "H" # e_shstrndx
  54. )
  55. ELF64_PHDR = ("I" # p_type
  56. "I" # p_flags
  57. "Q" # p_offset
  58. "Q" # p_vaddr
  59. "Q" # p_paddr
  60. "Q" # p_filesz
  61. "Q" # p_memsz
  62. "Q" # p_align
  63. )
  64. def int128_get64(val):
  65. assert (val["hi"] == 0)
  66. return val["lo"]
  67. def qlist_foreach(head, field_str):
  68. var_p = head["lh_first"]
  69. while (var_p != 0):
  70. var = var_p.dereference()
  71. yield var
  72. var_p = var[field_str]["le_next"]
  73. def qemu_get_ram_block(ram_addr):
  74. ram_blocks = gdb.parse_and_eval("ram_list.blocks")
  75. for block in qlist_foreach(ram_blocks, "next"):
  76. if (ram_addr - block["offset"] < block["used_length"]):
  77. return block
  78. raise gdb.GdbError("Bad ram offset %x" % ram_addr)
  79. def qemu_get_ram_ptr(ram_addr):
  80. block = qemu_get_ram_block(ram_addr)
  81. return block["host"] + (ram_addr - block["offset"])
  82. def memory_region_get_ram_ptr(mr):
  83. if (mr["alias"] != 0):
  84. return (memory_region_get_ram_ptr(mr["alias"].dereference()) +
  85. mr["alias_offset"])
  86. return qemu_get_ram_ptr(mr["ram_addr"] & TARGET_PAGE_MASK)
  87. def get_guest_phys_blocks():
  88. guest_phys_blocks = []
  89. print "guest RAM blocks:"
  90. print ("target_start target_end host_addr message "
  91. "count")
  92. print ("---------------- ---------------- ---------------- ------- "
  93. "-----")
  94. current_map_p = gdb.parse_and_eval("address_space_memory.current_map")
  95. current_map = current_map_p.dereference()
  96. for cur in range(current_map["nr"]):
  97. flat_range = (current_map["ranges"] + cur).dereference()
  98. mr = flat_range["mr"].dereference()
  99. # we only care about RAM
  100. if (not mr["ram"]):
  101. continue
  102. section_size = int128_get64(flat_range["addr"]["size"])
  103. target_start = int128_get64(flat_range["addr"]["start"])
  104. target_end = target_start + section_size
  105. host_addr = (memory_region_get_ram_ptr(mr) +
  106. flat_range["offset_in_region"])
  107. predecessor = None
  108. # find continuity in guest physical address space
  109. if (len(guest_phys_blocks) > 0):
  110. predecessor = guest_phys_blocks[-1]
  111. predecessor_size = (predecessor["target_end"] -
  112. predecessor["target_start"])
  113. # the memory API guarantees monotonically increasing
  114. # traversal
  115. assert (predecessor["target_end"] <= target_start)
  116. # we want continuity in both guest-physical and
  117. # host-virtual memory
  118. if (predecessor["target_end"] < target_start or
  119. predecessor["host_addr"] + predecessor_size != host_addr):
  120. predecessor = None
  121. if (predecessor is None):
  122. # isolated mapping, add it to the list
  123. guest_phys_blocks.append({"target_start": target_start,
  124. "target_end" : target_end,
  125. "host_addr" : host_addr})
  126. message = "added"
  127. else:
  128. # expand predecessor until @target_end; predecessor's
  129. # start doesn't change
  130. predecessor["target_end"] = target_end
  131. message = "joined"
  132. print ("%016x %016x %016x %-7s %5u" %
  133. (target_start, target_end, host_addr.cast(UINTPTR_T),
  134. message, len(guest_phys_blocks)))
  135. return guest_phys_blocks
  136. class DumpGuestMemory(gdb.Command):
  137. """Extract guest vmcore from qemu process coredump.
  138. The sole argument is FILE, identifying the target file to write the
  139. guest vmcore to.
  140. This GDB command reimplements the dump-guest-memory QMP command in
  141. python, using the representation of guest memory as captured in the qemu
  142. coredump. The qemu process that has been dumped must have had the
  143. command line option "-machine dump-guest-core=on".
  144. For simplicity, the "paging", "begin" and "end" parameters of the QMP
  145. command are not supported -- no attempt is made to get the guest's
  146. internal paging structures (ie. paging=false is hard-wired), and guest
  147. memory is always fully dumped.
  148. Only x86_64 guests are supported.
  149. The CORE/NT_PRSTATUS and QEMU notes (that is, the VCPUs' statuses) are
  150. not written to the vmcore. Preparing these would require context that is
  151. only present in the KVM host kernel module when the guest is alive. A
  152. fake ELF note is written instead, only to keep the ELF parser of "crash"
  153. happy.
  154. Dependent on how busted the qemu process was at the time of the
  155. coredump, this command might produce unpredictable results. If qemu
  156. deliberately called abort(), or it was dumped in response to a signal at
  157. a halfway fortunate point, then its coredump should be in reasonable
  158. shape and this command should mostly work."""
  159. def __init__(self):
  160. super(DumpGuestMemory, self).__init__("dump-guest-memory",
  161. gdb.COMMAND_DATA,
  162. gdb.COMPLETE_FILENAME)
  163. self.elf64_ehdr_le = struct.Struct("<%s" % ELF64_EHDR)
  164. self.elf64_phdr_le = struct.Struct("<%s" % ELF64_PHDR)
  165. self.guest_phys_blocks = None
  166. def cpu_get_dump_info(self):
  167. # We can't synchronize the registers with KVM post-mortem, and
  168. # the bits in (first_x86_cpu->env.hflags) seem to be stale; they
  169. # may not reflect long mode for example. Hence just assume the
  170. # most common values. This also means that instruction pointer
  171. # etc. will be bogus in the dump, but at least the RAM contents
  172. # should be valid.
  173. self.dump_info = {"d_machine": EM_X86_64,
  174. "d_endian" : ELFDATA2LSB,
  175. "d_class" : ELFCLASS64}
  176. def encode_elf64_ehdr_le(self):
  177. return self.elf64_ehdr_le.pack(
  178. ELFMAG, # e_ident/magic
  179. self.dump_info["d_class"], # e_ident/class
  180. self.dump_info["d_endian"], # e_ident/data
  181. EV_CURRENT, # e_ident/version
  182. 0, # e_ident/osabi
  183. "", # e_ident/pad
  184. ET_CORE, # e_type
  185. self.dump_info["d_machine"], # e_machine
  186. EV_CURRENT, # e_version
  187. 0, # e_entry
  188. self.elf64_ehdr_le.size, # e_phoff
  189. 0, # e_shoff
  190. 0, # e_flags
  191. self.elf64_ehdr_le.size, # e_ehsize
  192. self.elf64_phdr_le.size, # e_phentsize
  193. self.phdr_num, # e_phnum
  194. 0, # e_shentsize
  195. 0, # e_shnum
  196. 0 # e_shstrndx
  197. )
  198. def encode_elf64_note_le(self):
  199. return self.elf64_phdr_le.pack(PT_NOTE, # p_type
  200. 0, # p_flags
  201. (self.memory_offset -
  202. len(self.note)), # p_offset
  203. 0, # p_vaddr
  204. 0, # p_paddr
  205. len(self.note), # p_filesz
  206. len(self.note), # p_memsz
  207. 0 # p_align
  208. )
  209. def encode_elf64_load_le(self, offset, start_hwaddr, range_size):
  210. return self.elf64_phdr_le.pack(PT_LOAD, # p_type
  211. 0, # p_flags
  212. offset, # p_offset
  213. 0, # p_vaddr
  214. start_hwaddr, # p_paddr
  215. range_size, # p_filesz
  216. range_size, # p_memsz
  217. 0 # p_align
  218. )
  219. def note_init(self, name, desc, type):
  220. # name must include a trailing NUL
  221. namesz = (len(name) + 1 + 3) / 4 * 4
  222. descsz = (len(desc) + 3) / 4 * 4
  223. fmt = ("<" # little endian
  224. "I" # n_namesz
  225. "I" # n_descsz
  226. "I" # n_type
  227. "%us" # name
  228. "%us" # desc
  229. % (namesz, descsz))
  230. self.note = struct.pack(fmt,
  231. len(name) + 1, len(desc), type, name, desc)
  232. def dump_init(self):
  233. self.guest_phys_blocks = get_guest_phys_blocks()
  234. self.cpu_get_dump_info()
  235. # we have no way to retrieve the VCPU status from KVM
  236. # post-mortem
  237. self.note_init("NONE", "EMPTY", 0)
  238. # Account for PT_NOTE.
  239. self.phdr_num = 1
  240. # We should never reach PN_XNUM for paging=false dumps: there's
  241. # just a handful of discontiguous ranges after merging.
  242. self.phdr_num += len(self.guest_phys_blocks)
  243. assert (self.phdr_num < PN_XNUM)
  244. # Calculate the ELF file offset where the memory dump commences:
  245. #
  246. # ELF header
  247. # PT_NOTE
  248. # PT_LOAD: 1
  249. # PT_LOAD: 2
  250. # ...
  251. # PT_LOAD: len(self.guest_phys_blocks)
  252. # ELF note
  253. # memory dump
  254. self.memory_offset = (self.elf64_ehdr_le.size +
  255. self.elf64_phdr_le.size * self.phdr_num +
  256. len(self.note))
  257. def dump_begin(self, vmcore):
  258. vmcore.write(self.encode_elf64_ehdr_le())
  259. vmcore.write(self.encode_elf64_note_le())
  260. running = self.memory_offset
  261. for block in self.guest_phys_blocks:
  262. range_size = block["target_end"] - block["target_start"]
  263. vmcore.write(self.encode_elf64_load_le(running,
  264. block["target_start"],
  265. range_size))
  266. running += range_size
  267. vmcore.write(self.note)
  268. def dump_iterate(self, vmcore):
  269. qemu_core = gdb.inferiors()[0]
  270. for block in self.guest_phys_blocks:
  271. cur = block["host_addr"]
  272. left = block["target_end"] - block["target_start"]
  273. print ("dumping range at %016x for length %016x" %
  274. (cur.cast(UINTPTR_T), left))
  275. while (left > 0):
  276. chunk_size = min(TARGET_PAGE_SIZE, left)
  277. chunk = qemu_core.read_memory(cur, chunk_size)
  278. vmcore.write(chunk)
  279. cur += chunk_size
  280. left -= chunk_size
  281. def create_vmcore(self, filename):
  282. vmcore = open(filename, "wb")
  283. self.dump_begin(vmcore)
  284. self.dump_iterate(vmcore)
  285. vmcore.close()
  286. def invoke(self, args, from_tty):
  287. # Unwittingly pressing the Enter key after the command should
  288. # not dump the same multi-gig coredump to the same file.
  289. self.dont_repeat()
  290. argv = gdb.string_to_argv(args)
  291. if (len(argv) != 1):
  292. raise gdb.GdbError("usage: dump-guest-memory FILE")
  293. self.dump_init()
  294. self.create_vmcore(argv[0])
  295. DumpGuestMemory()