dump-guest-memory.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. """
  2. This python script adds a new gdb command, "dump-guest-memory". It
  3. should be loaded with "source dump-guest-memory.py" at the (gdb)
  4. prompt.
  5. Copyright (C) 2013, Red Hat, Inc.
  6. Authors:
  7. Laszlo Ersek <lersek@redhat.com>
  8. Janosch Frank <frankja@linux.vnet.ibm.com>
  9. This work is licensed under the terms of the GNU GPL, version 2 or later. See
  10. the COPYING file in the top-level directory.
  11. """
  12. import ctypes
  13. UINTPTR_T = gdb.lookup_type("uintptr_t")
  14. TARGET_PAGE_SIZE = 0x1000
  15. TARGET_PAGE_MASK = 0xFFFFFFFFFFFFF000
  16. # Special value for e_phnum. This indicates that the real number of
  17. # program headers is too large to fit into e_phnum. Instead the real
  18. # value is in the field sh_info of section 0.
  19. PN_XNUM = 0xFFFF
  20. EV_CURRENT = 1
  21. ELFCLASS32 = 1
  22. ELFCLASS64 = 2
  23. ELFDATA2LSB = 1
  24. ELFDATA2MSB = 2
  25. ET_CORE = 4
  26. PT_LOAD = 1
  27. PT_NOTE = 4
  28. EM_386 = 3
  29. EM_PPC = 20
  30. EM_PPC64 = 21
  31. EM_S390 = 22
  32. EM_AARCH = 183
  33. EM_X86_64 = 62
  34. class ELF(object):
  35. """Representation of a ELF file."""
  36. def __init__(self, arch):
  37. self.ehdr = None
  38. self.notes = []
  39. self.segments = []
  40. self.notes_size = 0
  41. self.endianess = None
  42. self.elfclass = ELFCLASS64
  43. if arch == 'aarch64-le':
  44. self.endianess = ELFDATA2LSB
  45. self.elfclass = ELFCLASS64
  46. self.ehdr = get_arch_ehdr(self.endianess, self.elfclass)
  47. self.ehdr.e_machine = EM_AARCH
  48. elif arch == 'aarch64-be':
  49. self.endianess = ELFDATA2MSB
  50. self.ehdr = get_arch_ehdr(self.endianess, self.elfclass)
  51. self.ehdr.e_machine = EM_AARCH
  52. elif arch == 'X86_64':
  53. self.endianess = ELFDATA2LSB
  54. self.ehdr = get_arch_ehdr(self.endianess, self.elfclass)
  55. self.ehdr.e_machine = EM_X86_64
  56. elif arch == '386':
  57. self.endianess = ELFDATA2LSB
  58. self.elfclass = ELFCLASS32
  59. self.ehdr = get_arch_ehdr(self.endianess, self.elfclass)
  60. self.ehdr.e_machine = EM_386
  61. elif arch == 's390':
  62. self.endianess = ELFDATA2MSB
  63. self.ehdr = get_arch_ehdr(self.endianess, self.elfclass)
  64. self.ehdr.e_machine = EM_S390
  65. elif arch == 'ppc64-le':
  66. self.endianess = ELFDATA2LSB
  67. self.ehdr = get_arch_ehdr(self.endianess, self.elfclass)
  68. self.ehdr.e_machine = EM_PPC64
  69. elif arch == 'ppc64-be':
  70. self.endianess = ELFDATA2MSB
  71. self.ehdr = get_arch_ehdr(self.endianess, self.elfclass)
  72. self.ehdr.e_machine = EM_PPC64
  73. else:
  74. raise gdb.GdbError("No valid arch type specified.\n"
  75. "Currently supported types:\n"
  76. "aarch64-be, aarch64-le, X86_64, 386, s390, "
  77. "ppc64-be, ppc64-le")
  78. self.add_segment(PT_NOTE, 0, 0)
  79. def add_note(self, n_name, n_desc, n_type):
  80. """Adds a note to the ELF."""
  81. note = get_arch_note(self.endianess, len(n_name), len(n_desc))
  82. note.n_namesz = len(n_name) + 1
  83. note.n_descsz = len(n_desc)
  84. note.n_name = n_name.encode()
  85. note.n_type = n_type
  86. # Desc needs to be 4 byte aligned (although the 64bit spec
  87. # specifies 8 byte). When defining n_desc as uint32 it will be
  88. # automatically aligned but we need the memmove to copy the
  89. # string into it.
  90. ctypes.memmove(note.n_desc, n_desc.encode(), len(n_desc))
  91. self.notes.append(note)
  92. self.segments[0].p_filesz += ctypes.sizeof(note)
  93. self.segments[0].p_memsz += ctypes.sizeof(note)
  94. def add_segment(self, p_type, p_paddr, p_size):
  95. """Adds a segment to the elf."""
  96. phdr = get_arch_phdr(self.endianess, self.elfclass)
  97. phdr.p_type = p_type
  98. phdr.p_paddr = p_paddr
  99. phdr.p_filesz = p_size
  100. phdr.p_memsz = p_size
  101. self.segments.append(phdr)
  102. self.ehdr.e_phnum += 1
  103. def to_file(self, elf_file):
  104. """Writes all ELF structures to the the passed file.
  105. Structure:
  106. Ehdr
  107. Segment 0:PT_NOTE
  108. Segment 1:PT_LOAD
  109. Segment N:PT_LOAD
  110. Note 0..N
  111. Dump contents
  112. """
  113. elf_file.write(self.ehdr)
  114. off = ctypes.sizeof(self.ehdr) + \
  115. len(self.segments) * ctypes.sizeof(self.segments[0])
  116. for phdr in self.segments:
  117. phdr.p_offset = off
  118. elf_file.write(phdr)
  119. off += phdr.p_filesz
  120. for note in self.notes:
  121. elf_file.write(note)
  122. def get_arch_note(endianess, len_name, len_desc):
  123. """Returns a Note class with the specified endianess."""
  124. if endianess == ELFDATA2LSB:
  125. superclass = ctypes.LittleEndianStructure
  126. else:
  127. superclass = ctypes.BigEndianStructure
  128. len_name = len_name + 1
  129. class Note(superclass):
  130. """Represents an ELF note, includes the content."""
  131. _fields_ = [("n_namesz", ctypes.c_uint32),
  132. ("n_descsz", ctypes.c_uint32),
  133. ("n_type", ctypes.c_uint32),
  134. ("n_name", ctypes.c_char * len_name),
  135. ("n_desc", ctypes.c_uint32 * ((len_desc + 3) // 4))]
  136. return Note()
  137. class Ident(ctypes.Structure):
  138. """Represents the ELF ident array in the ehdr structure."""
  139. _fields_ = [('ei_mag0', ctypes.c_ubyte),
  140. ('ei_mag1', ctypes.c_ubyte),
  141. ('ei_mag2', ctypes.c_ubyte),
  142. ('ei_mag3', ctypes.c_ubyte),
  143. ('ei_class', ctypes.c_ubyte),
  144. ('ei_data', ctypes.c_ubyte),
  145. ('ei_version', ctypes.c_ubyte),
  146. ('ei_osabi', ctypes.c_ubyte),
  147. ('ei_abiversion', ctypes.c_ubyte),
  148. ('ei_pad', ctypes.c_ubyte * 7)]
  149. def __init__(self, endianess, elfclass):
  150. self.ei_mag0 = 0x7F
  151. self.ei_mag1 = ord('E')
  152. self.ei_mag2 = ord('L')
  153. self.ei_mag3 = ord('F')
  154. self.ei_class = elfclass
  155. self.ei_data = endianess
  156. self.ei_version = EV_CURRENT
  157. def get_arch_ehdr(endianess, elfclass):
  158. """Returns a EHDR64 class with the specified endianess."""
  159. if endianess == ELFDATA2LSB:
  160. superclass = ctypes.LittleEndianStructure
  161. else:
  162. superclass = ctypes.BigEndianStructure
  163. class EHDR64(superclass):
  164. """Represents the 64 bit ELF header struct."""
  165. _fields_ = [('e_ident', Ident),
  166. ('e_type', ctypes.c_uint16),
  167. ('e_machine', ctypes.c_uint16),
  168. ('e_version', ctypes.c_uint32),
  169. ('e_entry', ctypes.c_uint64),
  170. ('e_phoff', ctypes.c_uint64),
  171. ('e_shoff', ctypes.c_uint64),
  172. ('e_flags', ctypes.c_uint32),
  173. ('e_ehsize', ctypes.c_uint16),
  174. ('e_phentsize', ctypes.c_uint16),
  175. ('e_phnum', ctypes.c_uint16),
  176. ('e_shentsize', ctypes.c_uint16),
  177. ('e_shnum', ctypes.c_uint16),
  178. ('e_shstrndx', ctypes.c_uint16)]
  179. def __init__(self):
  180. super(superclass, self).__init__()
  181. self.e_ident = Ident(endianess, elfclass)
  182. self.e_type = ET_CORE
  183. self.e_version = EV_CURRENT
  184. self.e_ehsize = ctypes.sizeof(self)
  185. self.e_phoff = ctypes.sizeof(self)
  186. self.e_phentsize = ctypes.sizeof(get_arch_phdr(endianess, elfclass))
  187. self.e_phnum = 0
  188. class EHDR32(superclass):
  189. """Represents the 32 bit ELF header struct."""
  190. _fields_ = [('e_ident', Ident),
  191. ('e_type', ctypes.c_uint16),
  192. ('e_machine', ctypes.c_uint16),
  193. ('e_version', ctypes.c_uint32),
  194. ('e_entry', ctypes.c_uint32),
  195. ('e_phoff', ctypes.c_uint32),
  196. ('e_shoff', ctypes.c_uint32),
  197. ('e_flags', ctypes.c_uint32),
  198. ('e_ehsize', ctypes.c_uint16),
  199. ('e_phentsize', ctypes.c_uint16),
  200. ('e_phnum', ctypes.c_uint16),
  201. ('e_shentsize', ctypes.c_uint16),
  202. ('e_shnum', ctypes.c_uint16),
  203. ('e_shstrndx', ctypes.c_uint16)]
  204. def __init__(self):
  205. super(superclass, self).__init__()
  206. self.e_ident = Ident(endianess, elfclass)
  207. self.e_type = ET_CORE
  208. self.e_version = EV_CURRENT
  209. self.e_ehsize = ctypes.sizeof(self)
  210. self.e_phoff = ctypes.sizeof(self)
  211. self.e_phentsize = ctypes.sizeof(get_arch_phdr(endianess, elfclass))
  212. self.e_phnum = 0
  213. # End get_arch_ehdr
  214. if elfclass == ELFCLASS64:
  215. return EHDR64()
  216. else:
  217. return EHDR32()
  218. def get_arch_phdr(endianess, elfclass):
  219. """Returns a 32 or 64 bit PHDR class with the specified endianess."""
  220. if endianess == ELFDATA2LSB:
  221. superclass = ctypes.LittleEndianStructure
  222. else:
  223. superclass = ctypes.BigEndianStructure
  224. class PHDR64(superclass):
  225. """Represents the 64 bit ELF program header struct."""
  226. _fields_ = [('p_type', ctypes.c_uint32),
  227. ('p_flags', ctypes.c_uint32),
  228. ('p_offset', ctypes.c_uint64),
  229. ('p_vaddr', ctypes.c_uint64),
  230. ('p_paddr', ctypes.c_uint64),
  231. ('p_filesz', ctypes.c_uint64),
  232. ('p_memsz', ctypes.c_uint64),
  233. ('p_align', ctypes.c_uint64)]
  234. class PHDR32(superclass):
  235. """Represents the 32 bit ELF program header struct."""
  236. _fields_ = [('p_type', ctypes.c_uint32),
  237. ('p_offset', ctypes.c_uint32),
  238. ('p_vaddr', ctypes.c_uint32),
  239. ('p_paddr', ctypes.c_uint32),
  240. ('p_filesz', ctypes.c_uint32),
  241. ('p_memsz', ctypes.c_uint32),
  242. ('p_flags', ctypes.c_uint32),
  243. ('p_align', ctypes.c_uint32)]
  244. # End get_arch_phdr
  245. if elfclass == ELFCLASS64:
  246. return PHDR64()
  247. else:
  248. return PHDR32()
  249. def int128_get64(val):
  250. """Returns low 64bit part of Int128 struct."""
  251. assert val["hi"] == 0
  252. return val["lo"]
  253. def qlist_foreach(head, field_str):
  254. """Generator for qlists."""
  255. var_p = head["lh_first"]
  256. while var_p != 0:
  257. var = var_p.dereference()
  258. var_p = var[field_str]["le_next"]
  259. yield var
  260. def qemu_get_ram_block(ram_addr):
  261. """Returns the RAMBlock struct to which the given address belongs."""
  262. ram_blocks = gdb.parse_and_eval("ram_list.blocks")
  263. for block in qlist_foreach(ram_blocks, "next"):
  264. if (ram_addr - block["offset"]) < block["used_length"]:
  265. return block
  266. raise gdb.GdbError("Bad ram offset %x" % ram_addr)
  267. def qemu_get_ram_ptr(ram_addr):
  268. """Returns qemu vaddr for given guest physical address."""
  269. block = qemu_get_ram_block(ram_addr)
  270. return block["host"] + (ram_addr - block["offset"])
  271. def memory_region_get_ram_ptr(memory_region):
  272. if memory_region["alias"] != 0:
  273. return (memory_region_get_ram_ptr(memory_region["alias"].dereference())
  274. + memory_region["alias_offset"])
  275. return qemu_get_ram_ptr(memory_region["ram_block"]["offset"])
  276. def get_guest_phys_blocks():
  277. """Returns a list of ram blocks.
  278. Each block entry contains:
  279. 'target_start': guest block phys start address
  280. 'target_end': guest block phys end address
  281. 'host_addr': qemu vaddr of the block's start
  282. """
  283. guest_phys_blocks = []
  284. print("guest RAM blocks:")
  285. print("target_start target_end host_addr message "
  286. "count")
  287. print("---------------- ---------------- ---------------- ------- "
  288. "-----")
  289. current_map_p = gdb.parse_and_eval("address_space_memory.current_map")
  290. current_map = current_map_p.dereference()
  291. # Conversion to int is needed for python 3
  292. # compatibility. Otherwise range doesn't cast the value itself and
  293. # breaks.
  294. for cur in range(int(current_map["nr"])):
  295. flat_range = (current_map["ranges"] + cur).dereference()
  296. memory_region = flat_range["mr"].dereference()
  297. # we only care about RAM
  298. if not memory_region["ram"]:
  299. continue
  300. section_size = int128_get64(flat_range["addr"]["size"])
  301. target_start = int128_get64(flat_range["addr"]["start"])
  302. target_end = target_start + section_size
  303. host_addr = (memory_region_get_ram_ptr(memory_region)
  304. + flat_range["offset_in_region"])
  305. predecessor = None
  306. # find continuity in guest physical address space
  307. if len(guest_phys_blocks) > 0:
  308. predecessor = guest_phys_blocks[-1]
  309. predecessor_size = (predecessor["target_end"] -
  310. predecessor["target_start"])
  311. # the memory API guarantees monotonically increasing
  312. # traversal
  313. assert predecessor["target_end"] <= target_start
  314. # we want continuity in both guest-physical and
  315. # host-virtual memory
  316. if (predecessor["target_end"] < target_start or
  317. predecessor["host_addr"] + predecessor_size != host_addr):
  318. predecessor = None
  319. if predecessor is None:
  320. # isolated mapping, add it to the list
  321. guest_phys_blocks.append({"target_start": target_start,
  322. "target_end": target_end,
  323. "host_addr": host_addr})
  324. message = "added"
  325. else:
  326. # expand predecessor until @target_end; predecessor's
  327. # start doesn't change
  328. predecessor["target_end"] = target_end
  329. message = "joined"
  330. print("%016x %016x %016x %-7s %5u" %
  331. (target_start, target_end, host_addr.cast(UINTPTR_T),
  332. message, len(guest_phys_blocks)))
  333. return guest_phys_blocks
  334. # The leading docstring doesn't have idiomatic Python formatting. It is
  335. # printed by gdb's "help" command (the first line is printed in the
  336. # "help data" summary), and it should match how other help texts look in
  337. # gdb.
  338. class DumpGuestMemory(gdb.Command):
  339. """Extract guest vmcore from qemu process coredump.
  340. The two required arguments are FILE and ARCH:
  341. FILE identifies the target file to write the guest vmcore to.
  342. ARCH specifies the architecture for which the core will be generated.
  343. This GDB command reimplements the dump-guest-memory QMP command in
  344. python, using the representation of guest memory as captured in the qemu
  345. coredump. The qemu process that has been dumped must have had the
  346. command line option "-machine dump-guest-core=on" which is the default.
  347. For simplicity, the "paging", "begin" and "end" parameters of the QMP
  348. command are not supported -- no attempt is made to get the guest's
  349. internal paging structures (ie. paging=false is hard-wired), and guest
  350. memory is always fully dumped.
  351. Currently aarch64-be, aarch64-le, X86_64, 386, s390, ppc64-be,
  352. ppc64-le guests are supported.
  353. The CORE/NT_PRSTATUS and QEMU notes (that is, the VCPUs' statuses) are
  354. not written to the vmcore. Preparing these would require context that is
  355. only present in the KVM host kernel module when the guest is alive. A
  356. fake ELF note is written instead, only to keep the ELF parser of "crash"
  357. happy.
  358. Dependent on how busted the qemu process was at the time of the
  359. coredump, this command might produce unpredictable results. If qemu
  360. deliberately called abort(), or it was dumped in response to a signal at
  361. a halfway fortunate point, then its coredump should be in reasonable
  362. shape and this command should mostly work."""
  363. def __init__(self):
  364. super(DumpGuestMemory, self).__init__("dump-guest-memory",
  365. gdb.COMMAND_DATA,
  366. gdb.COMPLETE_FILENAME)
  367. self.elf = None
  368. self.guest_phys_blocks = None
  369. def dump_init(self, vmcore):
  370. """Prepares and writes ELF structures to core file."""
  371. # Needed to make crash happy, data for more useful notes is
  372. # not available in a qemu core.
  373. self.elf.add_note("NONE", "EMPTY", 0)
  374. # We should never reach PN_XNUM for paging=false dumps,
  375. # there's just a handful of discontiguous ranges after
  376. # merging.
  377. # The constant is needed to account for the PT_NOTE segment.
  378. phdr_num = len(self.guest_phys_blocks) + 1
  379. assert phdr_num < PN_XNUM
  380. for block in self.guest_phys_blocks:
  381. block_size = block["target_end"] - block["target_start"]
  382. self.elf.add_segment(PT_LOAD, block["target_start"], block_size)
  383. self.elf.to_file(vmcore)
  384. def dump_iterate(self, vmcore):
  385. """Writes guest core to file."""
  386. qemu_core = gdb.inferiors()[0]
  387. for block in self.guest_phys_blocks:
  388. cur = block["host_addr"]
  389. left = block["target_end"] - block["target_start"]
  390. print("dumping range at %016x for length %016x" %
  391. (cur.cast(UINTPTR_T), left))
  392. while left > 0:
  393. chunk_size = min(TARGET_PAGE_SIZE, left)
  394. chunk = qemu_core.read_memory(cur, chunk_size)
  395. vmcore.write(chunk)
  396. cur += chunk_size
  397. left -= chunk_size
  398. def invoke(self, args, from_tty):
  399. """Handles command invocation from gdb."""
  400. # Unwittingly pressing the Enter key after the command should
  401. # not dump the same multi-gig coredump to the same file.
  402. self.dont_repeat()
  403. argv = gdb.string_to_argv(args)
  404. if len(argv) != 2:
  405. raise gdb.GdbError("usage: dump-guest-memory FILE ARCH")
  406. self.elf = ELF(argv[1])
  407. self.guest_phys_blocks = get_guest_phys_blocks()
  408. with open(argv[0], "wb") as vmcore:
  409. self.dump_init(vmcore)
  410. self.dump_iterate(vmcore)
  411. DumpGuestMemory()