dump-guest-memory.py 20 KB

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