dump-guest-memory.py 20 KB

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