05bba0
From 11d85a217f6b3b15710bbc786adebd943774be09 Mon Sep 17 00:00:00 2001
05bba0
From: Laszlo Ersek <lersek@redhat.com>
05bba0
Date: Fri, 20 Feb 2015 09:53:20 +0100
05bba0
Subject: [PATCH 14/16] Python-lang gdb script to extract x86_64 guest vmcore
05bba0
 from qemu coredump
05bba0
05bba0
Message-id: <1424426001-3543-2-git-send-email-lersek@redhat.com>
05bba0
Patchwork-id: 63908
05bba0
O-Subject: [RHEL-7.2 qemu-kvm PATCH v2 1/2] Python-lang gdb script to extract x86_64 guest vmcore from qemu coredump
05bba0
Bugzilla: 828493
05bba0
RH-Acked-by: Vitaly Kuznetsov <vkuznets@redhat.com>
05bba0
RH-Acked-by: Jeff Nelson <jenelson@redhat.com>
05bba0
RH-Acked-by: Miroslav Rezanina <mrezanin@redhat.com>
05bba0
05bba0
When qemu dies unexpectedly, for example in response to an explicit
05bba0
abort() call, or (more importantly) when an external signal is delivered
05bba0
to it that results in a coredump, sometimes it is useful to extract the
05bba0
guest vmcore from the qemu process' memory image. The guest vmcore might
05bba0
help understand an emulation problem in qemu, or help debug the guest.
05bba0
05bba0
This script reimplements (and cuts many features of) the
05bba0
qmp_dump_guest_memory() command in gdb/Python,
05bba0
05bba0
  https://sourceware.org/gdb/current/onlinedocs/gdb/Python-API.html
05bba0
05bba0
working off the saved memory image of the qemu process. The docstring in
05bba0
the patch (serving as gdb help text) describes the limitations relative to
05bba0
the QMP command.
05bba0
05bba0
Dependencies of qmp_dump_guest_memory() have been reimplemented as needed.
05bba0
I sought to follow the general structure, sticking to original function
05bba0
names where possible. However, keeping it simple prevailed in some places.
05bba0
05bba0
The patch has been tested with a 4 VCPU, 768 MB, RHEL-6.4
05bba0
(2.6.32-358.el6.x86_64) guest:
05bba0
05bba0
- The script printed
05bba0
05bba0
> guest RAM blocks:
05bba0
> target_start     target_end       host_addr        message count
05bba0
> ---------------- ---------------- ---------------- ------- -----
05bba0
> 0000000000000000 00000000000a0000 00007f95d0000000 added       1
05bba0
> 00000000000a0000 00000000000b0000 00007f960ac00000 added       2
05bba0
> 00000000000c0000 00000000000ca000 00007f95d00c0000 added       3
05bba0
> 00000000000ca000 00000000000cd000 00007f95d00ca000 joined      3
05bba0
> 00000000000cd000 00000000000d0000 00007f95d00cd000 joined      3
05bba0
> 00000000000d0000 00000000000f0000 00007f95d00d0000 joined      3
05bba0
> 00000000000f0000 0000000000100000 00007f95d00f0000 joined      3
05bba0
> 0000000000100000 0000000030000000 00007f95d0100000 joined      3
05bba0
> 00000000fc000000 00000000fc800000 00007f960ac00000 added       4
05bba0
> 00000000fffe0000 0000000100000000 00007f9618800000 added       5
05bba0
> dumping range at 00007f95d0000000 for length 00000000000a0000
05bba0
> dumping range at 00007f960ac00000 for length 0000000000010000
05bba0
> dumping range at 00007f95d00c0000 for length 000000002ff40000
05bba0
> dumping range at 00007f960ac00000 for length 0000000000800000
05bba0
> dumping range at 00007f9618800000 for length 0000000000020000
05bba0
05bba0
- The vmcore was checked with "readelf", comparing the results against a
05bba0
  vmcore written by qmp_dump_guest_memory():
05bba0
05bba0
> --- theirs      2013-09-12 17:38:59.797289404 +0200
05bba0
> +++ mine        2013-09-12 17:39:03.820289404 +0200
05bba0
> @@ -27,16 +27,16 @@
05bba0
>    Type           Offset             VirtAddr           PhysAddr
05bba0
>                   FileSiz            MemSiz              Flags  Align
05bba0
>    NOTE           0x0000000000000190 0x0000000000000000 0x0000000000000000
05bba0
> -                 0x0000000000000ca0 0x0000000000000ca0         0
05bba0
> -  LOAD           0x0000000000000e30 0x0000000000000000 0x0000000000000000
05bba0
> +                 0x000000000000001c 0x000000000000001c         0
05bba0
> +  LOAD           0x00000000000001ac 0x0000000000000000 0x0000000000000000
05bba0
>                   0x00000000000a0000 0x00000000000a0000         0
05bba0
> -  LOAD           0x00000000000a0e30 0x0000000000000000 0x00000000000a0000
05bba0
> +  LOAD           0x00000000000a01ac 0x0000000000000000 0x00000000000a0000
05bba0
>                   0x0000000000010000 0x0000000000010000         0
05bba0
> -  LOAD           0x00000000000b0e30 0x0000000000000000 0x00000000000c0000
05bba0
> +  LOAD           0x00000000000b01ac 0x0000000000000000 0x00000000000c0000
05bba0
>                   0x000000002ff40000 0x000000002ff40000         0
05bba0
> -  LOAD           0x000000002fff0e30 0x0000000000000000 0x00000000fc000000
05bba0
> +  LOAD           0x000000002fff01ac 0x0000000000000000 0x00000000fc000000
05bba0
>                   0x0000000000800000 0x0000000000800000         0
05bba0
> -  LOAD           0x00000000307f0e30 0x0000000000000000 0x00000000fffe0000
05bba0
> +  LOAD           0x00000000307f01ac 0x0000000000000000 0x00000000fffe0000
05bba0
>                   0x0000000000020000 0x0000000000020000         0
05bba0
>
05bba0
>  There is no dynamic section in this file.
05bba0
> @@ -47,13 +47,6 @@
05bba0
>
05bba0
>  No version information found in this file.
05bba0
>
05bba0
> -Notes at offset 0x00000190 with length 0x00000ca0:
05bba0
> +Notes at offset 0x00000190 with length 0x0000001c:
05bba0
>    Owner                Data size       Description
05bba0
> -  CORE         0x00000150      NT_PRSTATUS (prstatus structure)
05bba0
> -  CORE         0x00000150      NT_PRSTATUS (prstatus structure)
05bba0
> -  CORE         0x00000150      NT_PRSTATUS (prstatus structure)
05bba0
> -  CORE         0x00000150      NT_PRSTATUS (prstatus structure)
05bba0
> -  QEMU         0x000001b0      Unknown note type: (0x00000000)
05bba0
> -  QEMU         0x000001b0      Unknown note type: (0x00000000)
05bba0
> -  QEMU         0x000001b0      Unknown note type: (0x00000000)
05bba0
> -  QEMU         0x000001b0      Unknown note type: (0x00000000)
05bba0
> +  NONE         0x00000005      Unknown note type: (0x00000000)
05bba0
05bba0
- The vmcore was checked with "crash" too, again comparing the results
05bba0
  against a vmcore written by qmp_dump_guest_memory():
05bba0
05bba0
> --- guest.vmcore.log2   2013-09-12 17:52:27.074289201 +0200
05bba0
> +++ example.dump.log2   2013-09-12 17:52:15.904289203 +0200
05bba0
> @@ -22,11 +22,11 @@
05bba0
>  This GDB was configured as "x86_64-unknown-linux-gnu"...
05bba0
>
05bba0
>       KERNEL: /usr/lib/debug/lib/modules/2.6.32-358.el6.x86_64/vmlinux
05bba0
> -    DUMPFILE: /home/lacos/tmp/guest.vmcore
05bba0
> +    DUMPFILE: /home/lacos/tmp/example.dump
05bba0
>          CPUS: 4
05bba0
> -        DATE: Thu Sep 12 17:16:11 2013
05bba0
> -      UPTIME: 00:01:09
05bba0
> -LOAD AVERAGE: 0.07, 0.03, 0.00
05bba0
> +        DATE: Thu Sep 12 17:17:41 2013
05bba0
> +      UPTIME: 00:00:38
05bba0
> +LOAD AVERAGE: 0.18, 0.05, 0.01
05bba0
>         TASKS: 130
05bba0
>      NODENAME: localhost.localdomain
05bba0
>       RELEASE: 2.6.32-358.el6.x86_64
05bba0
> @@ -38,12 +38,12 @@
05bba0
>       COMMAND: "swapper"
05bba0
>          TASK: ffffffff81a8d020  (1 of 4)  [THREAD_INFO: ffffffff81a00000]
05bba0
>           CPU: 0
05bba0
> -       STATE: TASK_RUNNING (PANIC)
05bba0
> +       STATE: TASK_RUNNING (ACTIVE)
05bba0
> +     WARNING: panic task not found
05bba0
>
05bba0
>  crash> bt
05bba0
>  PID: 0      TASK: ffffffff81a8d020  CPU: 0   COMMAND: "swapper"
05bba0
> - #0 [ffffffff81a01ed0] default_idle at ffffffff8101495d
05bba0
> - #1 [ffffffff81a01ef0] cpu_idle at ffffffff81009fc6
05bba0
> + #0 [ffffffff81a01ef0] cpu_idle at ffffffff81009fc6
05bba0
>  crash> task ffffffff81a8d020
05bba0
>  PID: 0      TASK: ffffffff81a8d020  CPU: 0   COMMAND: "swapper"
05bba0
>  struct task_struct {
05bba0
> @@ -75,7 +75,7 @@
05bba0
>        prev = 0xffffffff81a8d080
05bba0
>      },
05bba0
>      on_rq = 0,
05bba0
> -    exec_start = 8618466836,
05bba0
> +    exec_start = 7469214014,
05bba0
>      sum_exec_runtime = 0,
05bba0
>      vruntime = 0,
05bba0
>      prev_sum_exec_runtime = 0,
05bba0
> @@ -149,7 +149,7 @@
05bba0
>    },
05bba0
>    tasks = {
05bba0
>      next = 0xffff88002d621948,
05bba0
> -    prev = 0xffff880029618f28
05bba0
> +    prev = 0xffff880023b74488
05bba0
>    },
05bba0
>    pushable_tasks = {
05bba0
>      prio = 140,
05bba0
> @@ -165,7 +165,7 @@
05bba0
>      }
05bba0
>    },
05bba0
>    mm = 0x0,
05bba0
> -  active_mm = 0xffff88002929b780,
05bba0
> +  active_mm = 0xffff8800297eb980,
05bba0
>    exit_state = 0,
05bba0
>    exit_code = 0,
05bba0
>    exit_signal = 0,
05bba0
> @@ -177,7 +177,7 @@
05bba0
>    sched_reset_on_fork = 0,
05bba0
>    pid = 0,
05bba0
>    tgid = 0,
05bba0
> -  stack_canary = 2483693585637059287,
05bba0
> +  stack_canary = 7266362296181431986,
05bba0
>    real_parent = 0xffffffff81a8d020,
05bba0
>    parent = 0xffffffff81a8d020,
05bba0
>    children = {
05bba0
> @@ -224,14 +224,14 @@
05bba0
>    set_child_tid = 0x0,
05bba0
>    clear_child_tid = 0x0,
05bba0
>    utime = 0,
05bba0
> -  stime = 3,
05bba0
> +  stime = 2,
05bba0
>    utimescaled = 0,
05bba0
> -  stimescaled = 3,
05bba0
> +  stimescaled = 2,
05bba0
>    gtime = 0,
05bba0
>    prev_utime = 0,
05bba0
>    prev_stime = 0,
05bba0
>    nvcsw = 0,
05bba0
> -  nivcsw = 1000,
05bba0
> +  nivcsw = 1764,
05bba0
>    start_time = {
05bba0
>      tv_sec = 0,
05bba0
>      tv_nsec = 0
05bba0
05bba0
- <name_dropping>I asked for Dave Anderson's help with verifying the
05bba0
  extracted vmcore, and his comments make me think I should post
05bba0
  this.</name_dropping>
05bba0
05bba0
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
05bba0
Signed-off-by: Michael S. Tsirkin <mst@redhat.com>
05bba0
(cherry picked from commit 3e16d14fd93ca6059134ba6b4f65c1c3e4cd3a18)
05bba0
Signed-off-by: Miroslav Rezanina <mrezanin@redhat.com>
05bba0
---
05bba0
 scripts/dump-guest-memory.py | 339 +++++++++++++++++++++++++++++++++++++++++++
05bba0
 1 file changed, 339 insertions(+)
05bba0
 create mode 100644 scripts/dump-guest-memory.py
05bba0
05bba0
diff --git a/scripts/dump-guest-memory.py b/scripts/dump-guest-memory.py
05bba0
new file mode 100644
05bba0
index 0000000..1ed8b67
05bba0
--- /dev/null
05bba0
+++ b/scripts/dump-guest-memory.py
05bba0
@@ -0,0 +1,339 @@
05bba0
+# This python script adds a new gdb command, "dump-guest-memory". It
05bba0
+# should be loaded with "source dump-guest-memory.py" at the (gdb)
05bba0
+# prompt.
05bba0
+#
05bba0
+# Copyright (C) 2013, Red Hat, Inc.
05bba0
+#
05bba0
+# Authors:
05bba0
+#   Laszlo Ersek <lersek@redhat.com>
05bba0
+#
05bba0
+# This work is licensed under the terms of the GNU GPL, version 2 or later. See
05bba0
+# the COPYING file in the top-level directory.
05bba0
+#
05bba0
+# The leading docstring doesn't have idiomatic Python formatting. It is
05bba0
+# printed by gdb's "help" command (the first line is printed in the
05bba0
+# "help data" summary), and it should match how other help texts look in
05bba0
+# gdb.
05bba0
+
05bba0
+import struct
05bba0
+
05bba0
+class DumpGuestMemory(gdb.Command):
05bba0
+    """Extract guest vmcore from qemu process coredump.
05bba0
+
05bba0
+The sole argument is FILE, identifying the target file to write the
05bba0
+guest vmcore to.
05bba0
+
05bba0
+This GDB command reimplements the dump-guest-memory QMP command in
05bba0
+python, using the representation of guest memory as captured in the qemu
05bba0
+coredump. The qemu process that has been dumped must have had the
05bba0
+command line option "-machine dump-guest-core=on".
05bba0
+
05bba0
+For simplicity, the "paging", "begin" and "end" parameters of the QMP
05bba0
+command are not supported -- no attempt is made to get the guest's
05bba0
+internal paging structures (ie. paging=false is hard-wired), and guest
05bba0
+memory is always fully dumped.
05bba0
+
05bba0
+Only x86_64 guests are supported.
05bba0
+
05bba0
+The CORE/NT_PRSTATUS and QEMU notes (that is, the VCPUs' statuses) are
05bba0
+not written to the vmcore. Preparing these would require context that is
05bba0
+only present in the KVM host kernel module when the guest is alive. A
05bba0
+fake ELF note is written instead, only to keep the ELF parser of "crash"
05bba0
+happy.
05bba0
+
05bba0
+Dependent on how busted the qemu process was at the time of the
05bba0
+coredump, this command might produce unpredictable results. If qemu
05bba0
+deliberately called abort(), or it was dumped in response to a signal at
05bba0
+a halfway fortunate point, then its coredump should be in reasonable
05bba0
+shape and this command should mostly work."""
05bba0
+
05bba0
+    TARGET_PAGE_SIZE = 0x1000
05bba0
+    TARGET_PAGE_MASK = 0xFFFFFFFFFFFFF000
05bba0
+
05bba0
+    # Various ELF constants
05bba0
+    EM_X86_64   = 62        # AMD x86-64 target machine
05bba0
+    ELFDATA2LSB = 1         # little endian
05bba0
+    ELFCLASS64  = 2
05bba0
+    ELFMAG      = "\x7FELF"
05bba0
+    EV_CURRENT  = 1
05bba0
+    ET_CORE     = 4
05bba0
+    PT_LOAD     = 1
05bba0
+    PT_NOTE     = 4
05bba0
+
05bba0
+    # Special value for e_phnum. This indicates that the real number of
05bba0
+    # program headers is too large to fit into e_phnum. Instead the real
05bba0
+    # value is in the field sh_info of section 0.
05bba0
+    PN_XNUM = 0xFFFF
05bba0
+
05bba0
+    # Format strings for packing and header size calculation.
05bba0
+    ELF64_EHDR = ("4s" # e_ident/magic
05bba0
+                  "B"  # e_ident/class
05bba0
+                  "B"  # e_ident/data
05bba0
+                  "B"  # e_ident/version
05bba0
+                  "B"  # e_ident/osabi
05bba0
+                  "8s" # e_ident/pad
05bba0
+                  "H"  # e_type
05bba0
+                  "H"  # e_machine
05bba0
+                  "I"  # e_version
05bba0
+                  "Q"  # e_entry
05bba0
+                  "Q"  # e_phoff
05bba0
+                  "Q"  # e_shoff
05bba0
+                  "I"  # e_flags
05bba0
+                  "H"  # e_ehsize
05bba0
+                  "H"  # e_phentsize
05bba0
+                  "H"  # e_phnum
05bba0
+                  "H"  # e_shentsize
05bba0
+                  "H"  # e_shnum
05bba0
+                  "H"  # e_shstrndx
05bba0
+                 )
05bba0
+    ELF64_PHDR = ("I"  # p_type
05bba0
+                  "I"  # p_flags
05bba0
+                  "Q"  # p_offset
05bba0
+                  "Q"  # p_vaddr
05bba0
+                  "Q"  # p_paddr
05bba0
+                  "Q"  # p_filesz
05bba0
+                  "Q"  # p_memsz
05bba0
+                  "Q"  # p_align
05bba0
+                 )
05bba0
+
05bba0
+    def __init__(self):
05bba0
+        super(DumpGuestMemory, self).__init__("dump-guest-memory",
05bba0
+                                              gdb.COMMAND_DATA,
05bba0
+                                              gdb.COMPLETE_FILENAME)
05bba0
+        self.uintptr_t     = gdb.lookup_type("uintptr_t")
05bba0
+        self.elf64_ehdr_le = struct.Struct("<%s" % self.ELF64_EHDR)
05bba0
+        self.elf64_phdr_le = struct.Struct("<%s" % self.ELF64_PHDR)
05bba0
+
05bba0
+    def int128_get64(self, val):
05bba0
+        assert (val["hi"] == 0)
05bba0
+        return val["lo"]
05bba0
+
05bba0
+    def qtailq_foreach(self, head, field_str):
05bba0
+        var_p = head["tqh_first"]
05bba0
+        while (var_p != 0):
05bba0
+            var = var_p.dereference()
05bba0
+            yield var
05bba0
+            var_p = var[field_str]["tqe_next"]
05bba0
+
05bba0
+    def qemu_get_ram_block(self, ram_addr):
05bba0
+        ram_blocks = gdb.parse_and_eval("ram_list.blocks")
05bba0
+        for block in self.qtailq_foreach(ram_blocks, "next"):
05bba0
+            if (ram_addr - block["offset"] < block["length"]):
05bba0
+                return block
05bba0
+        raise gdb.GdbError("Bad ram offset %x" % ram_addr)
05bba0
+
05bba0
+    def qemu_get_ram_ptr(self, ram_addr):
05bba0
+        block = self.qemu_get_ram_block(ram_addr)
05bba0
+        return block["host"] + (ram_addr - block["offset"])
05bba0
+
05bba0
+    def memory_region_get_ram_ptr(self, mr):
05bba0
+        if (mr["alias"] != 0):
05bba0
+            return (self.memory_region_get_ram_ptr(mr["alias"].dereference()) +
05bba0
+                    mr["alias_offset"])
05bba0
+        return self.qemu_get_ram_ptr(mr["ram_addr"] & self.TARGET_PAGE_MASK)
05bba0
+
05bba0
+    def guest_phys_blocks_init(self):
05bba0
+        self.guest_phys_blocks = []
05bba0
+
05bba0
+    def guest_phys_blocks_append(self):
05bba0
+        print "guest RAM blocks:"
05bba0
+        print ("target_start     target_end       host_addr        message "
05bba0
+               "count")
05bba0
+        print ("---------------- ---------------- ---------------- ------- "
05bba0
+               "-----")
05bba0
+
05bba0
+        current_map_p = gdb.parse_and_eval("address_space_memory.current_map")
05bba0
+        current_map = current_map_p.dereference()
05bba0
+        for cur in range(current_map["nr"]):
05bba0
+            flat_range   = (current_map["ranges"] + cur).dereference()
05bba0
+            mr           = flat_range["mr"].dereference()
05bba0
+
05bba0
+            # we only care about RAM
05bba0
+            if (not mr["ram"]):
05bba0
+                continue
05bba0
+
05bba0
+            section_size = self.int128_get64(flat_range["addr"]["size"])
05bba0
+            target_start = self.int128_get64(flat_range["addr"]["start"])
05bba0
+            target_end   = target_start + section_size
05bba0
+            host_addr    = (self.memory_region_get_ram_ptr(mr) +
05bba0
+                            flat_range["offset_in_region"])
05bba0
+            predecessor = None
05bba0
+
05bba0
+            # find continuity in guest physical address space
05bba0
+            if (len(self.guest_phys_blocks) > 0):
05bba0
+                predecessor = self.guest_phys_blocks[-1]
05bba0
+                predecessor_size = (predecessor["target_end"] -
05bba0
+                                    predecessor["target_start"])
05bba0
+
05bba0
+                # the memory API guarantees monotonically increasing
05bba0
+                # traversal
05bba0
+                assert (predecessor["target_end"] <= target_start)
05bba0
+
05bba0
+                # we want continuity in both guest-physical and
05bba0
+                # host-virtual memory
05bba0
+                if (predecessor["target_end"] < target_start or
05bba0
+                    predecessor["host_addr"] + predecessor_size != host_addr):
05bba0
+                    predecessor = None
05bba0
+
05bba0
+            if (predecessor is None):
05bba0
+                # isolated mapping, add it to the list
05bba0
+                self.guest_phys_blocks.append({"target_start": target_start,
05bba0
+                                               "target_end"  : target_end,
05bba0
+                                               "host_addr"   : host_addr})
05bba0
+                message = "added"
05bba0
+            else:
05bba0
+                # expand predecessor until @target_end; predecessor's
05bba0
+                # start doesn't change
05bba0
+                predecessor["target_end"] = target_end
05bba0
+                message = "joined"
05bba0
+
05bba0
+            print ("%016x %016x %016x %-7s %5u" %
05bba0
+                   (target_start, target_end, host_addr.cast(self.uintptr_t),
05bba0
+                    message, len(self.guest_phys_blocks)))
05bba0
+
05bba0
+    def cpu_get_dump_info(self):
05bba0
+        # We can't synchronize the registers with KVM post-mortem, and
05bba0
+        # the bits in (first_x86_cpu->env.hflags) seem to be stale; they
05bba0
+        # may not reflect long mode for example. Hence just assume the
05bba0
+        # most common values. This also means that instruction pointer
05bba0
+        # etc. will be bogus in the dump, but at least the RAM contents
05bba0
+        # should be valid.
05bba0
+        self.dump_info = {"d_machine": self.EM_X86_64,
05bba0
+                          "d_endian" : self.ELFDATA2LSB,
05bba0
+                          "d_class"  : self.ELFCLASS64}
05bba0
+
05bba0
+    def encode_elf64_ehdr_le(self):
05bba0
+        return self.elf64_ehdr_le.pack(
05bba0
+                                 self.ELFMAG,                 # e_ident/magic
05bba0
+                                 self.dump_info["d_class"],   # e_ident/class
05bba0
+                                 self.dump_info["d_endian"],  # e_ident/data
05bba0
+                                 self.EV_CURRENT,             # e_ident/version
05bba0
+                                 0,                           # e_ident/osabi
05bba0
+                                 "",                          # e_ident/pad
05bba0
+                                 self.ET_CORE,                # e_type
05bba0
+                                 self.dump_info["d_machine"], # e_machine
05bba0
+                                 self.EV_CURRENT,             # e_version
05bba0
+                                 0,                           # e_entry
05bba0
+                                 self.elf64_ehdr_le.size,     # e_phoff
05bba0
+                                 0,                           # e_shoff
05bba0
+                                 0,                           # e_flags
05bba0
+                                 self.elf64_ehdr_le.size,     # e_ehsize
05bba0
+                                 self.elf64_phdr_le.size,     # e_phentsize
05bba0
+                                 self.phdr_num,               # e_phnum
05bba0
+                                 0,                           # e_shentsize
05bba0
+                                 0,                           # e_shnum
05bba0
+                                 0                            # e_shstrndx
05bba0
+                                )
05bba0
+
05bba0
+    def encode_elf64_note_le(self):
05bba0
+        return self.elf64_phdr_le.pack(self.PT_NOTE,         # p_type
05bba0
+                                       0,                    # p_flags
05bba0
+                                       (self.memory_offset -
05bba0
+                                        len(self.note)),     # p_offset
05bba0
+                                       0,                    # p_vaddr
05bba0
+                                       0,                    # p_paddr
05bba0
+                                       len(self.note),       # p_filesz
05bba0
+                                       len(self.note),       # p_memsz
05bba0
+                                       0                     # p_align
05bba0
+                                      )
05bba0
+
05bba0
+    def encode_elf64_load_le(self, offset, start_hwaddr, range_size):
05bba0
+        return self.elf64_phdr_le.pack(self.PT_LOAD, # p_type
05bba0
+                                       0,            # p_flags
05bba0
+                                       offset,       # p_offset
05bba0
+                                       0,            # p_vaddr
05bba0
+                                       start_hwaddr, # p_paddr
05bba0
+                                       range_size,   # p_filesz
05bba0
+                                       range_size,   # p_memsz
05bba0
+                                       0             # p_align
05bba0
+                                      )
05bba0
+
05bba0
+    def note_init(self, name, desc, type):
05bba0
+        # name must include a trailing NUL
05bba0
+        namesz = (len(name) + 1 + 3) / 4 * 4
05bba0
+        descsz = (len(desc)     + 3) / 4 * 4
05bba0
+        fmt = ("<"   # little endian
05bba0
+               "I"   # n_namesz
05bba0
+               "I"   # n_descsz
05bba0
+               "I"   # n_type
05bba0
+               "%us" # name
05bba0
+               "%us" # desc
05bba0
+               % (namesz, descsz))
05bba0
+        self.note = struct.pack(fmt,
05bba0
+                                len(name) + 1, len(desc), type, name, desc)
05bba0
+
05bba0
+    def dump_init(self):
05bba0
+        self.guest_phys_blocks_init()
05bba0
+        self.guest_phys_blocks_append()
05bba0
+        self.cpu_get_dump_info()
05bba0
+        # we have no way to retrieve the VCPU status from KVM
05bba0
+        # post-mortem
05bba0
+        self.note_init("NONE", "EMPTY", 0)
05bba0
+
05bba0
+        # Account for PT_NOTE.
05bba0
+        self.phdr_num = 1
05bba0
+
05bba0
+        # We should never reach PN_XNUM for paging=false dumps: there's
05bba0
+        # just a handful of discontiguous ranges after merging.
05bba0
+        self.phdr_num += len(self.guest_phys_blocks)
05bba0
+        assert (self.phdr_num < self.PN_XNUM)
05bba0
+
05bba0
+        # Calculate the ELF file offset where the memory dump commences:
05bba0
+        #
05bba0
+        #   ELF header
05bba0
+        #   PT_NOTE
05bba0
+        #   PT_LOAD: 1
05bba0
+        #   PT_LOAD: 2
05bba0
+        #   ...
05bba0
+        #   PT_LOAD: len(self.guest_phys_blocks)
05bba0
+        #   ELF note
05bba0
+        #   memory dump
05bba0
+        self.memory_offset = (self.elf64_ehdr_le.size +
05bba0
+                              self.elf64_phdr_le.size * self.phdr_num +
05bba0
+                              len(self.note))
05bba0
+
05bba0
+    def dump_begin(self, vmcore):
05bba0
+        vmcore.write(self.encode_elf64_ehdr_le())
05bba0
+        vmcore.write(self.encode_elf64_note_le())
05bba0
+        running = self.memory_offset
05bba0
+        for block in self.guest_phys_blocks:
05bba0
+            range_size = block["target_end"] - block["target_start"]
05bba0
+            vmcore.write(self.encode_elf64_load_le(running,
05bba0
+                                                   block["target_start"],
05bba0
+                                                   range_size))
05bba0
+            running += range_size
05bba0
+        vmcore.write(self.note)
05bba0
+
05bba0
+    def dump_iterate(self, vmcore):
05bba0
+        qemu_core = gdb.inferiors()[0]
05bba0
+        for block in self.guest_phys_blocks:
05bba0
+            cur  = block["host_addr"]
05bba0
+            left = block["target_end"] - block["target_start"]
05bba0
+            print ("dumping range at %016x for length %016x" %
05bba0
+                   (cur.cast(self.uintptr_t), left))
05bba0
+            while (left > 0):
05bba0
+                chunk_size = min(self.TARGET_PAGE_SIZE, left)
05bba0
+                chunk = qemu_core.read_memory(cur, chunk_size)
05bba0
+                vmcore.write(chunk)
05bba0
+                cur  += chunk_size
05bba0
+                left -= chunk_size
05bba0
+
05bba0
+    def create_vmcore(self, filename):
05bba0
+        vmcore = open(filename, "wb")
05bba0
+        self.dump_begin(vmcore)
05bba0
+        self.dump_iterate(vmcore)
05bba0
+        vmcore.close()
05bba0
+
05bba0
+    def invoke(self, args, from_tty):
05bba0
+        # Unwittingly pressing the Enter key after the command should
05bba0
+        # not dump the same multi-gig coredump to the same file.
05bba0
+        self.dont_repeat()
05bba0
+
05bba0
+        argv = gdb.string_to_argv(args)
05bba0
+        if (len(argv) != 1):
05bba0
+            raise gdb.GdbError("usage: dump-guest-memory FILE")
05bba0
+
05bba0
+        self.dump_init()
05bba0
+        self.create_vmcore(argv[0])
05bba0
+
05bba0
+DumpGuestMemory()
05bba0
-- 
05bba0
1.8.3.1
05bba0