dump-guest-memory.py 20 KB

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