dump-guest-memory.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. class DumpGuestMemory(gdb.Command):
  19. """Extract guest vmcore from qemu process coredump.
  20. The sole argument is FILE, identifying the target file to write the
  21. guest vmcore to.
  22. This GDB command reimplements the dump-guest-memory QMP command in
  23. python, using the representation of guest memory as captured in the qemu
  24. coredump. The qemu process that has been dumped must have had the
  25. command line option "-machine dump-guest-core=on".
  26. For simplicity, the "paging", "begin" and "end" parameters of the QMP
  27. command are not supported -- no attempt is made to get the guest's
  28. internal paging structures (ie. paging=false is hard-wired), and guest
  29. memory is always fully dumped.
  30. Only x86_64 guests are supported.
  31. The CORE/NT_PRSTATUS and QEMU notes (that is, the VCPUs' statuses) are
  32. not written to the vmcore. Preparing these would require context that is
  33. only present in the KVM host kernel module when the guest is alive. A
  34. fake ELF note is written instead, only to keep the ELF parser of "crash"
  35. happy.
  36. Dependent on how busted the qemu process was at the time of the
  37. coredump, this command might produce unpredictable results. If qemu
  38. deliberately called abort(), or it was dumped in response to a signal at
  39. a halfway fortunate point, then its coredump should be in reasonable
  40. shape and this command should mostly work."""
  41. TARGET_PAGE_SIZE = 0x1000
  42. TARGET_PAGE_MASK = 0xFFFFFFFFFFFFF000
  43. # Various ELF constants
  44. EM_X86_64 = 62 # AMD x86-64 target machine
  45. ELFDATA2LSB = 1 # little endian
  46. ELFCLASS64 = 2
  47. ELFMAG = "\x7FELF"
  48. EV_CURRENT = 1
  49. ET_CORE = 4
  50. PT_LOAD = 1
  51. PT_NOTE = 4
  52. # Special value for e_phnum. This indicates that the real number of
  53. # program headers is too large to fit into e_phnum. Instead the real
  54. # value is in the field sh_info of section 0.
  55. PN_XNUM = 0xFFFF
  56. # Format strings for packing and header size calculation.
  57. ELF64_EHDR = ("4s" # e_ident/magic
  58. "B" # e_ident/class
  59. "B" # e_ident/data
  60. "B" # e_ident/version
  61. "B" # e_ident/osabi
  62. "8s" # e_ident/pad
  63. "H" # e_type
  64. "H" # e_machine
  65. "I" # e_version
  66. "Q" # e_entry
  67. "Q" # e_phoff
  68. "Q" # e_shoff
  69. "I" # e_flags
  70. "H" # e_ehsize
  71. "H" # e_phentsize
  72. "H" # e_phnum
  73. "H" # e_shentsize
  74. "H" # e_shnum
  75. "H" # e_shstrndx
  76. )
  77. ELF64_PHDR = ("I" # p_type
  78. "I" # p_flags
  79. "Q" # p_offset
  80. "Q" # p_vaddr
  81. "Q" # p_paddr
  82. "Q" # p_filesz
  83. "Q" # p_memsz
  84. "Q" # p_align
  85. )
  86. def __init__(self):
  87. super(DumpGuestMemory, self).__init__("dump-guest-memory",
  88. gdb.COMMAND_DATA,
  89. gdb.COMPLETE_FILENAME)
  90. self.uintptr_t = gdb.lookup_type("uintptr_t")
  91. self.elf64_ehdr_le = struct.Struct("<%s" % self.ELF64_EHDR)
  92. self.elf64_phdr_le = struct.Struct("<%s" % self.ELF64_PHDR)
  93. def int128_get64(self, val):
  94. assert (val["hi"] == 0)
  95. return val["lo"]
  96. def qtailq_foreach(self, head, field_str):
  97. var_p = head["tqh_first"]
  98. while (var_p != 0):
  99. var = var_p.dereference()
  100. yield var
  101. var_p = var[field_str]["tqe_next"]
  102. def qemu_get_ram_block(self, ram_addr):
  103. ram_blocks = gdb.parse_and_eval("ram_list.blocks")
  104. for block in self.qtailq_foreach(ram_blocks, "next"):
  105. if (ram_addr - block["offset"] < block["length"]):
  106. return block
  107. raise gdb.GdbError("Bad ram offset %x" % ram_addr)
  108. def qemu_get_ram_ptr(self, ram_addr):
  109. block = self.qemu_get_ram_block(ram_addr)
  110. return block["host"] + (ram_addr - block["offset"])
  111. def memory_region_get_ram_ptr(self, mr):
  112. if (mr["alias"] != 0):
  113. return (self.memory_region_get_ram_ptr(mr["alias"].dereference()) +
  114. mr["alias_offset"])
  115. return self.qemu_get_ram_ptr(mr["ram_addr"] & self.TARGET_PAGE_MASK)
  116. def guest_phys_blocks_init(self):
  117. self.guest_phys_blocks = []
  118. def guest_phys_blocks_append(self):
  119. print "guest RAM blocks:"
  120. print ("target_start target_end host_addr message "
  121. "count")
  122. print ("---------------- ---------------- ---------------- ------- "
  123. "-----")
  124. current_map_p = gdb.parse_and_eval("address_space_memory.current_map")
  125. current_map = current_map_p.dereference()
  126. for cur in range(current_map["nr"]):
  127. flat_range = (current_map["ranges"] + cur).dereference()
  128. mr = flat_range["mr"].dereference()
  129. # we only care about RAM
  130. if (not mr["ram"]):
  131. continue
  132. section_size = self.int128_get64(flat_range["addr"]["size"])
  133. target_start = self.int128_get64(flat_range["addr"]["start"])
  134. target_end = target_start + section_size
  135. host_addr = (self.memory_region_get_ram_ptr(mr) +
  136. flat_range["offset_in_region"])
  137. predecessor = None
  138. # find continuity in guest physical address space
  139. if (len(self.guest_phys_blocks) > 0):
  140. predecessor = self.guest_phys_blocks[-1]
  141. predecessor_size = (predecessor["target_end"] -
  142. predecessor["target_start"])
  143. # the memory API guarantees monotonically increasing
  144. # traversal
  145. assert (predecessor["target_end"] <= target_start)
  146. # we want continuity in both guest-physical and
  147. # host-virtual memory
  148. if (predecessor["target_end"] < target_start or
  149. predecessor["host_addr"] + predecessor_size != host_addr):
  150. predecessor = None
  151. if (predecessor is None):
  152. # isolated mapping, add it to the list
  153. self.guest_phys_blocks.append({"target_start": target_start,
  154. "target_end" : target_end,
  155. "host_addr" : host_addr})
  156. message = "added"
  157. else:
  158. # expand predecessor until @target_end; predecessor's
  159. # start doesn't change
  160. predecessor["target_end"] = target_end
  161. message = "joined"
  162. print ("%016x %016x %016x %-7s %5u" %
  163. (target_start, target_end, host_addr.cast(self.uintptr_t),
  164. message, len(self.guest_phys_blocks)))
  165. def cpu_get_dump_info(self):
  166. # We can't synchronize the registers with KVM post-mortem, and
  167. # the bits in (first_x86_cpu->env.hflags) seem to be stale; they
  168. # may not reflect long mode for example. Hence just assume the
  169. # most common values. This also means that instruction pointer
  170. # etc. will be bogus in the dump, but at least the RAM contents
  171. # should be valid.
  172. self.dump_info = {"d_machine": self.EM_X86_64,
  173. "d_endian" : self.ELFDATA2LSB,
  174. "d_class" : self.ELFCLASS64}
  175. def encode_elf64_ehdr_le(self):
  176. return self.elf64_ehdr_le.pack(
  177. self.ELFMAG, # e_ident/magic
  178. self.dump_info["d_class"], # e_ident/class
  179. self.dump_info["d_endian"], # e_ident/data
  180. self.EV_CURRENT, # e_ident/version
  181. 0, # e_ident/osabi
  182. "", # e_ident/pad
  183. self.ET_CORE, # e_type
  184. self.dump_info["d_machine"], # e_machine
  185. self.EV_CURRENT, # e_version
  186. 0, # e_entry
  187. self.elf64_ehdr_le.size, # e_phoff
  188. 0, # e_shoff
  189. 0, # e_flags
  190. self.elf64_ehdr_le.size, # e_ehsize
  191. self.elf64_phdr_le.size, # e_phentsize
  192. self.phdr_num, # e_phnum
  193. 0, # e_shentsize
  194. 0, # e_shnum
  195. 0 # e_shstrndx
  196. )
  197. def encode_elf64_note_le(self):
  198. return self.elf64_phdr_le.pack(self.PT_NOTE, # p_type
  199. 0, # p_flags
  200. (self.memory_offset -
  201. len(self.note)), # p_offset
  202. 0, # p_vaddr
  203. 0, # p_paddr
  204. len(self.note), # p_filesz
  205. len(self.note), # p_memsz
  206. 0 # p_align
  207. )
  208. def encode_elf64_load_le(self, offset, start_hwaddr, range_size):
  209. return self.elf64_phdr_le.pack(self.PT_LOAD, # p_type
  210. 0, # p_flags
  211. offset, # p_offset
  212. 0, # p_vaddr
  213. start_hwaddr, # p_paddr
  214. range_size, # p_filesz
  215. range_size, # p_memsz
  216. 0 # p_align
  217. )
  218. def note_init(self, name, desc, type):
  219. # name must include a trailing NUL
  220. namesz = (len(name) + 1 + 3) / 4 * 4
  221. descsz = (len(desc) + 3) / 4 * 4
  222. fmt = ("<" # little endian
  223. "I" # n_namesz
  224. "I" # n_descsz
  225. "I" # n_type
  226. "%us" # name
  227. "%us" # desc
  228. % (namesz, descsz))
  229. self.note = struct.pack(fmt,
  230. len(name) + 1, len(desc), type, name, desc)
  231. def dump_init(self):
  232. self.guest_phys_blocks_init()
  233. self.guest_phys_blocks_append()
  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 < self.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(self.uintptr_t), left))
  275. while (left > 0):
  276. chunk_size = min(self.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()