dump-guest-memory.py 20 KB

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