dump-guest-memory.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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.endianness = None
  42. self.elfclass = ELFCLASS64
  43. if arch == 'aarch64-le':
  44. self.endianness = ELFDATA2LSB
  45. self.elfclass = ELFCLASS64
  46. self.ehdr = get_arch_ehdr(self.endianness, self.elfclass)
  47. self.ehdr.e_machine = EM_AARCH
  48. elif arch == 'aarch64-be':
  49. self.endianness = ELFDATA2MSB
  50. self.ehdr = get_arch_ehdr(self.endianness, self.elfclass)
  51. self.ehdr.e_machine = EM_AARCH
  52. elif arch == 'X86_64':
  53. self.endianness = ELFDATA2LSB
  54. self.ehdr = get_arch_ehdr(self.endianness, self.elfclass)
  55. self.ehdr.e_machine = EM_X86_64
  56. elif arch == '386':
  57. self.endianness = ELFDATA2LSB
  58. self.elfclass = ELFCLASS32
  59. self.ehdr = get_arch_ehdr(self.endianness, self.elfclass)
  60. self.ehdr.e_machine = EM_386
  61. elif arch == 's390':
  62. self.endianness = ELFDATA2MSB
  63. self.ehdr = get_arch_ehdr(self.endianness, self.elfclass)
  64. self.ehdr.e_machine = EM_S390
  65. elif arch == 'ppc64-le':
  66. self.endianness = ELFDATA2LSB
  67. self.ehdr = get_arch_ehdr(self.endianness, self.elfclass)
  68. self.ehdr.e_machine = EM_PPC64
  69. elif arch == 'ppc64-be':
  70. self.endianness = ELFDATA2MSB
  71. self.ehdr = get_arch_ehdr(self.endianness, 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.endianness, 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.endianness, 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(endianness, len_name, len_desc):
  123. """Returns a Note class with the specified endianness."""
  124. if endianness == 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, endianness, 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 = endianness
  156. self.ei_version = EV_CURRENT
  157. def get_arch_ehdr(endianness, elfclass):
  158. """Returns a EHDR64 class with the specified endianness."""
  159. if endianness == 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(endianness, 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(endianness, 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(endianness, 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(endianness, 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(endianness, elfclass):
  219. """Returns a 32 or 64 bit PHDR class with the specified endianness."""
  220. if endianness == 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_map_ram_ptr(block, offset):
  261. """Returns qemu vaddr for given guest physical address."""
  262. return block["host"] + offset
  263. def memory_region_get_ram_ptr(memory_region):
  264. if memory_region["alias"] != 0:
  265. return (memory_region_get_ram_ptr(memory_region["alias"].dereference())
  266. + memory_region["alias_offset"])
  267. return qemu_map_ram_ptr(memory_region["ram_block"], 0)
  268. def get_guest_phys_blocks():
  269. """Returns a list of ram blocks.
  270. Each block entry contains:
  271. 'target_start': guest block phys start address
  272. 'target_end': guest block phys end address
  273. 'host_addr': qemu vaddr of the block's start
  274. """
  275. guest_phys_blocks = []
  276. print("guest RAM blocks:")
  277. print("target_start target_end host_addr message "
  278. "count")
  279. print("---------------- ---------------- ---------------- ------- "
  280. "-----")
  281. current_map_p = gdb.parse_and_eval("address_space_memory.current_map")
  282. current_map = current_map_p.dereference()
  283. # Conversion to int is needed for python 3
  284. # compatibility. Otherwise range doesn't cast the value itself and
  285. # breaks.
  286. for cur in range(int(current_map["nr"])):
  287. flat_range = (current_map["ranges"] + cur).dereference()
  288. memory_region = flat_range["mr"].dereference()
  289. # we only care about RAM
  290. if not memory_region["ram"]:
  291. continue
  292. section_size = int128_get64(flat_range["addr"]["size"])
  293. target_start = int128_get64(flat_range["addr"]["start"])
  294. target_end = target_start + section_size
  295. host_addr = (memory_region_get_ram_ptr(memory_region)
  296. + flat_range["offset_in_region"])
  297. predecessor = None
  298. # find continuity in guest physical address space
  299. if len(guest_phys_blocks) > 0:
  300. predecessor = guest_phys_blocks[-1]
  301. predecessor_size = (predecessor["target_end"] -
  302. predecessor["target_start"])
  303. # the memory API guarantees monotonically increasing
  304. # traversal
  305. assert predecessor["target_end"] <= target_start
  306. # we want continuity in both guest-physical and
  307. # host-virtual memory
  308. if (predecessor["target_end"] < target_start or
  309. predecessor["host_addr"] + predecessor_size != host_addr):
  310. predecessor = None
  311. if predecessor is None:
  312. # isolated mapping, add it to the list
  313. guest_phys_blocks.append({"target_start": target_start,
  314. "target_end": target_end,
  315. "host_addr": host_addr})
  316. message = "added"
  317. else:
  318. # expand predecessor until @target_end; predecessor's
  319. # start doesn't change
  320. predecessor["target_end"] = target_end
  321. message = "joined"
  322. print("%016x %016x %016x %-7s %5u" %
  323. (target_start, target_end, host_addr.cast(UINTPTR_T),
  324. message, len(guest_phys_blocks)))
  325. return guest_phys_blocks
  326. # The leading docstring doesn't have idiomatic Python formatting. It is
  327. # printed by gdb's "help" command (the first line is printed in the
  328. # "help data" summary), and it should match how other help texts look in
  329. # gdb.
  330. class DumpGuestMemory(gdb.Command):
  331. """Extract guest vmcore from qemu process coredump.
  332. The two required arguments are FILE and ARCH:
  333. FILE identifies the target file to write the guest vmcore to.
  334. ARCH specifies the architecture for which the core will be generated.
  335. This GDB command reimplements the dump-guest-memory QMP command in
  336. python, using the representation of guest memory as captured in the qemu
  337. coredump. The qemu process that has been dumped must have had the
  338. command line option "-machine dump-guest-core=on" which is the default.
  339. For simplicity, the "paging", "begin" and "end" parameters of the QMP
  340. command are not supported -- no attempt is made to get the guest's
  341. internal paging structures (ie. paging=false is hard-wired), and guest
  342. memory is always fully dumped.
  343. Currently aarch64-be, aarch64-le, X86_64, 386, s390, ppc64-be,
  344. ppc64-le guests are supported.
  345. The CORE/NT_PRSTATUS and QEMU notes (that is, the VCPUs' statuses) are
  346. not written to the vmcore. Preparing these would require context that is
  347. only present in the KVM host kernel module when the guest is alive. A
  348. fake ELF note is written instead, only to keep the ELF parser of "crash"
  349. happy.
  350. Dependent on how busted the qemu process was at the time of the
  351. coredump, this command might produce unpredictable results. If qemu
  352. deliberately called abort(), or it was dumped in response to a signal at
  353. a halfway fortunate point, then its coredump should be in reasonable
  354. shape and this command should mostly work."""
  355. def __init__(self):
  356. super(DumpGuestMemory, self).__init__("dump-guest-memory",
  357. gdb.COMMAND_DATA,
  358. gdb.COMPLETE_FILENAME)
  359. self.elf = None
  360. self.guest_phys_blocks = None
  361. def dump_init(self, vmcore):
  362. """Prepares and writes ELF structures to core file."""
  363. # Needed to make crash happy, data for more useful notes is
  364. # not available in a qemu core.
  365. self.elf.add_note("NONE", "EMPTY", 0)
  366. # We should never reach PN_XNUM for paging=false dumps,
  367. # there's just a handful of discontiguous ranges after
  368. # merging.
  369. # The constant is needed to account for the PT_NOTE segment.
  370. phdr_num = len(self.guest_phys_blocks) + 1
  371. assert phdr_num < PN_XNUM
  372. for block in self.guest_phys_blocks:
  373. block_size = block["target_end"] - block["target_start"]
  374. self.elf.add_segment(PT_LOAD, block["target_start"], block_size)
  375. self.elf.to_file(vmcore)
  376. def dump_iterate(self, vmcore):
  377. """Writes guest core to file."""
  378. qemu_core = gdb.inferiors()[0]
  379. for block in self.guest_phys_blocks:
  380. cur = block["host_addr"]
  381. left = block["target_end"] - block["target_start"]
  382. print("dumping range at %016x for length %016x" %
  383. (cur.cast(UINTPTR_T), left))
  384. while left > 0:
  385. chunk_size = min(TARGET_PAGE_SIZE, left)
  386. chunk = qemu_core.read_memory(cur, chunk_size)
  387. vmcore.write(chunk)
  388. cur += chunk_size
  389. left -= chunk_size
  390. def invoke(self, args, from_tty):
  391. """Handles command invocation from gdb."""
  392. # Unwittingly pressing the Enter key after the command should
  393. # not dump the same multi-gig coredump to the same file.
  394. self.dont_repeat()
  395. argv = gdb.string_to_argv(args)
  396. if len(argv) != 2:
  397. raise gdb.GdbError("usage: dump-guest-memory FILE ARCH")
  398. self.elf = ELF(argv[1])
  399. self.guest_phys_blocks = get_guest_phys_blocks()
  400. with open(argv[0], "wb") as vmcore:
  401. self.dump_init(vmcore)
  402. self.dump_iterate(vmcore)
  403. DumpGuestMemory()