qemu/scripts/analyze-migration.py
<<
>>
Prefs
   1#!/usr/bin/env python3
   2#
   3#  Migration Stream Analyzer
   4#
   5#  Copyright (c) 2015 Alexander Graf <agraf@suse.de>
   6#
   7# This library is free software; you can redistribute it and/or
   8# modify it under the terms of the GNU Lesser General Public
   9# License as published by the Free Software Foundation; either
  10# version 2 of the License, or (at your option) any later version.
  11#
  12# This library is distributed in the hope that it will be useful,
  13# but WITHOUT ANY WARRANTY; without even the implied warranty of
  14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  15# Lesser General Public License for more details.
  16#
  17# You should have received a copy of the GNU Lesser General Public
  18# License along with this library; if not, see <http://www.gnu.org/licenses/>.
  19
  20import json
  21import os
  22import argparse
  23import collections
  24import struct
  25import sys
  26
  27
  28def mkdir_p(path):
  29    try:
  30        os.makedirs(path)
  31    except OSError:
  32        pass
  33
  34
  35class MigrationFile(object):
  36    def __init__(self, filename):
  37        self.filename = filename
  38        self.file = open(self.filename, "rb")
  39
  40    def read64(self):
  41        return int.from_bytes(self.file.read(8), byteorder='big', signed=True)
  42
  43    def read32(self):
  44        return int.from_bytes(self.file.read(4), byteorder='big', signed=True)
  45
  46    def read16(self):
  47        return int.from_bytes(self.file.read(2), byteorder='big', signed=True)
  48
  49    def read8(self):
  50        return int.from_bytes(self.file.read(1), byteorder='big', signed=True)
  51
  52    def readstr(self, len = None):
  53        return self.readvar(len).decode('utf-8')
  54
  55    def readvar(self, size = None):
  56        if size is None:
  57            size = self.read8()
  58        if size == 0:
  59            return ""
  60        value = self.file.read(size)
  61        if len(value) != size:
  62            raise Exception("Unexpected end of %s at 0x%x" % (self.filename, self.file.tell()))
  63        return value
  64
  65    def tell(self):
  66        return self.file.tell()
  67
  68    # The VMSD description is at the end of the file, after EOF. Look for
  69    # the last NULL byte, then for the beginning brace of JSON.
  70    def read_migration_debug_json(self):
  71        QEMU_VM_VMDESCRIPTION = 0x06
  72
  73        # Remember the offset in the file when we started
  74        entrypos = self.file.tell()
  75
  76        # Read the last 10MB
  77        self.file.seek(0, os.SEEK_END)
  78        endpos = self.file.tell()
  79        self.file.seek(max(-endpos, -10 * 1024 * 1024), os.SEEK_END)
  80        datapos = self.file.tell()
  81        data = self.file.read()
  82        # The full file read closed the file as well, reopen it
  83        self.file = open(self.filename, "rb")
  84
  85        # Find the last NULL byte, then the first brace after that. This should
  86        # be the beginning of our JSON data.
  87        nulpos = data.rfind(b'\0')
  88        jsonpos = data.find(b'{', nulpos)
  89
  90        # Check backwards from there and see whether we guessed right
  91        self.file.seek(datapos + jsonpos - 5, 0)
  92        if self.read8() != QEMU_VM_VMDESCRIPTION:
  93            raise Exception("No Debug Migration device found")
  94
  95        jsonlen = self.read32()
  96
  97        # Seek back to where we were at the beginning
  98        self.file.seek(entrypos, 0)
  99
 100        return data[jsonpos:jsonpos + jsonlen]
 101
 102    def close(self):
 103        self.file.close()
 104
 105class RamSection(object):
 106    RAM_SAVE_FLAG_COMPRESS = 0x02
 107    RAM_SAVE_FLAG_MEM_SIZE = 0x04
 108    RAM_SAVE_FLAG_PAGE     = 0x08
 109    RAM_SAVE_FLAG_EOS      = 0x10
 110    RAM_SAVE_FLAG_CONTINUE = 0x20
 111    RAM_SAVE_FLAG_XBZRLE   = 0x40
 112    RAM_SAVE_FLAG_HOOK     = 0x80
 113
 114    def __init__(self, file, version_id, ramargs, section_key):
 115        if version_id != 4:
 116            raise Exception("Unknown RAM version %d" % version_id)
 117
 118        self.file = file
 119        self.section_key = section_key
 120        self.TARGET_PAGE_SIZE = ramargs['page_size']
 121        self.dump_memory = ramargs['dump_memory']
 122        self.write_memory = ramargs['write_memory']
 123        self.sizeinfo = collections.OrderedDict()
 124        self.data = collections.OrderedDict()
 125        self.data['section sizes'] = self.sizeinfo
 126        self.name = ''
 127        if self.write_memory:
 128            self.files = { }
 129        if self.dump_memory:
 130            self.memory = collections.OrderedDict()
 131            self.data['memory'] = self.memory
 132
 133    def __repr__(self):
 134        return self.data.__repr__()
 135
 136    def __str__(self):
 137        return self.data.__str__()
 138
 139    def getDict(self):
 140        return self.data
 141
 142    def read(self):
 143        # Read all RAM sections
 144        while True:
 145            addr = self.file.read64()
 146            flags = addr & (self.TARGET_PAGE_SIZE - 1)
 147            addr &= ~(self.TARGET_PAGE_SIZE - 1)
 148
 149            if flags & self.RAM_SAVE_FLAG_MEM_SIZE:
 150                while True:
 151                    namelen = self.file.read8()
 152                    # We assume that no RAM chunk is big enough to ever
 153                    # hit the first byte of the address, so when we see
 154                    # a zero here we know it has to be an address, not the
 155                    # length of the next block.
 156                    if namelen == 0:
 157                        self.file.file.seek(-1, 1)
 158                        break
 159                    self.name = self.file.readstr(len = namelen)
 160                    len = self.file.read64()
 161                    self.sizeinfo[self.name] = '0x%016x' % len
 162                    if self.write_memory:
 163                        print(self.name)
 164                        mkdir_p('./' + os.path.dirname(self.name))
 165                        f = open('./' + self.name, "wb")
 166                        f.truncate(0)
 167                        f.truncate(len)
 168                        self.files[self.name] = f
 169                flags &= ~self.RAM_SAVE_FLAG_MEM_SIZE
 170
 171            if flags & self.RAM_SAVE_FLAG_COMPRESS:
 172                if flags & self.RAM_SAVE_FLAG_CONTINUE:
 173                    flags &= ~self.RAM_SAVE_FLAG_CONTINUE
 174                else:
 175                    self.name = self.file.readstr()
 176                fill_char = self.file.read8()
 177                # The page in question is filled with fill_char now
 178                if self.write_memory and fill_char != 0:
 179                    self.files[self.name].seek(addr, os.SEEK_SET)
 180                    self.files[self.name].write(chr(fill_char) * self.TARGET_PAGE_SIZE)
 181                if self.dump_memory:
 182                    self.memory['%s (0x%016x)' % (self.name, addr)] = 'Filled with 0x%02x' % fill_char
 183                flags &= ~self.RAM_SAVE_FLAG_COMPRESS
 184            elif flags & self.RAM_SAVE_FLAG_PAGE:
 185                if flags & self.RAM_SAVE_FLAG_CONTINUE:
 186                    flags &= ~self.RAM_SAVE_FLAG_CONTINUE
 187                else:
 188                    self.name = self.file.readstr()
 189
 190                if self.write_memory or self.dump_memory:
 191                    data = self.file.readvar(size = self.TARGET_PAGE_SIZE)
 192                else: # Just skip RAM data
 193                    self.file.file.seek(self.TARGET_PAGE_SIZE, 1)
 194
 195                if self.write_memory:
 196                    self.files[self.name].seek(addr, os.SEEK_SET)
 197                    self.files[self.name].write(data)
 198                if self.dump_memory:
 199                    hexdata = " ".join("{0:02x}".format(ord(c)) for c in data)
 200                    self.memory['%s (0x%016x)' % (self.name, addr)] = hexdata
 201
 202                flags &= ~self.RAM_SAVE_FLAG_PAGE
 203            elif flags & self.RAM_SAVE_FLAG_XBZRLE:
 204                raise Exception("XBZRLE RAM compression is not supported yet")
 205            elif flags & self.RAM_SAVE_FLAG_HOOK:
 206                raise Exception("RAM hooks don't make sense with files")
 207
 208            # End of RAM section
 209            if flags & self.RAM_SAVE_FLAG_EOS:
 210                break
 211
 212            if flags != 0:
 213                raise Exception("Unknown RAM flags: %x" % flags)
 214
 215    def __del__(self):
 216        if self.write_memory:
 217            for key in self.files:
 218                self.files[key].close()
 219
 220
 221class HTABSection(object):
 222    HASH_PTE_SIZE_64       = 16
 223
 224    def __init__(self, file, version_id, device, section_key):
 225        if version_id != 1:
 226            raise Exception("Unknown HTAB version %d" % version_id)
 227
 228        self.file = file
 229        self.section_key = section_key
 230
 231    def read(self):
 232
 233        header = self.file.read32()
 234
 235        if (header == -1):
 236            # "no HPT" encoding
 237            return
 238
 239        if (header > 0):
 240            # First section, just the hash shift
 241            return
 242
 243        # Read until end marker
 244        while True:
 245            index = self.file.read32()
 246            n_valid = self.file.read16()
 247            n_invalid = self.file.read16()
 248
 249            if index == 0 and n_valid == 0 and n_invalid == 0:
 250                break
 251
 252            self.file.readvar(n_valid * self.HASH_PTE_SIZE_64)
 253
 254    def getDict(self):
 255        return ""
 256
 257
 258class ConfigurationSection(object):
 259    def __init__(self, file):
 260        self.file = file
 261
 262    def read(self):
 263        name_len = self.file.read32()
 264        name = self.file.readstr(len = name_len)
 265
 266class VMSDFieldGeneric(object):
 267    def __init__(self, desc, file):
 268        self.file = file
 269        self.desc = desc
 270        self.data = ""
 271
 272    def __repr__(self):
 273        return str(self.__str__())
 274
 275    def __str__(self):
 276        return " ".join("{0:02x}".format(c) for c in self.data)
 277
 278    def getDict(self):
 279        return self.__str__()
 280
 281    def read(self):
 282        size = int(self.desc['size'])
 283        self.data = self.file.readvar(size)
 284        return self.data
 285
 286class VMSDFieldInt(VMSDFieldGeneric):
 287    def __init__(self, desc, file):
 288        super(VMSDFieldInt, self).__init__(desc, file)
 289        self.size = int(desc['size'])
 290        self.format = '0x%%0%dx' % (self.size * 2)
 291        self.sdtype = '>i%d' % self.size
 292        self.udtype = '>u%d' % self.size
 293
 294    def __repr__(self):
 295        if self.data < 0:
 296            return ('%s (%d)' % ((self.format % self.udata), self.data))
 297        else:
 298            return self.format % self.data
 299
 300    def __str__(self):
 301        return self.__repr__()
 302
 303    def getDict(self):
 304        return self.__str__()
 305
 306    def read(self):
 307        super(VMSDFieldInt, self).read()
 308        self.sdata = int.from_bytes(self.data, byteorder='big', signed=True)
 309        self.udata = int.from_bytes(self.data, byteorder='big', signed=False)
 310        self.data = self.sdata
 311        return self.data
 312
 313class VMSDFieldUInt(VMSDFieldInt):
 314    def __init__(self, desc, file):
 315        super(VMSDFieldUInt, self).__init__(desc, file)
 316
 317    def read(self):
 318        super(VMSDFieldUInt, self).read()
 319        self.data = self.udata
 320        return self.data
 321
 322class VMSDFieldIntLE(VMSDFieldInt):
 323    def __init__(self, desc, file):
 324        super(VMSDFieldIntLE, self).__init__(desc, file)
 325        self.dtype = '<i%d' % self.size
 326
 327class VMSDFieldBool(VMSDFieldGeneric):
 328    def __init__(self, desc, file):
 329        super(VMSDFieldBool, self).__init__(desc, file)
 330
 331    def __repr__(self):
 332        return self.data.__repr__()
 333
 334    def __str__(self):
 335        return self.data.__str__()
 336
 337    def getDict(self):
 338        return self.data
 339
 340    def read(self):
 341        super(VMSDFieldBool, self).read()
 342        if self.data[0] == 0:
 343            self.data = False
 344        else:
 345            self.data = True
 346        return self.data
 347
 348class VMSDFieldStruct(VMSDFieldGeneric):
 349    QEMU_VM_SUBSECTION    = 0x05
 350
 351    def __init__(self, desc, file):
 352        super(VMSDFieldStruct, self).__init__(desc, file)
 353        self.data = collections.OrderedDict()
 354
 355        # When we see compressed array elements, unfold them here
 356        new_fields = []
 357        for field in self.desc['struct']['fields']:
 358            if not 'array_len' in field:
 359                new_fields.append(field)
 360                continue
 361            array_len = field.pop('array_len')
 362            field['index'] = 0
 363            new_fields.append(field)
 364            for i in range(1, array_len):
 365                c = field.copy()
 366                c['index'] = i
 367                new_fields.append(c)
 368
 369        self.desc['struct']['fields'] = new_fields
 370
 371    def __repr__(self):
 372        return self.data.__repr__()
 373
 374    def __str__(self):
 375        return self.data.__str__()
 376
 377    def read(self):
 378        for field in self.desc['struct']['fields']:
 379            try:
 380                reader = vmsd_field_readers[field['type']]
 381            except:
 382                reader = VMSDFieldGeneric
 383
 384            field['data'] = reader(field, self.file)
 385            field['data'].read()
 386
 387            if 'index' in field:
 388                if field['name'] not in self.data:
 389                    self.data[field['name']] = []
 390                a = self.data[field['name']]
 391                if len(a) != int(field['index']):
 392                    raise Exception("internal index of data field unmatched (%d/%d)" % (len(a), int(field['index'])))
 393                a.append(field['data'])
 394            else:
 395                self.data[field['name']] = field['data']
 396
 397        if 'subsections' in self.desc['struct']:
 398            for subsection in self.desc['struct']['subsections']:
 399                if self.file.read8() != self.QEMU_VM_SUBSECTION:
 400                    raise Exception("Subsection %s not found at offset %x" % ( subsection['vmsd_name'], self.file.tell()))
 401                name = self.file.readstr()
 402                version_id = self.file.read32()
 403                self.data[name] = VMSDSection(self.file, version_id, subsection, (name, 0))
 404                self.data[name].read()
 405
 406    def getDictItem(self, value):
 407       # Strings would fall into the array category, treat
 408       # them specially
 409       if value.__class__ is ''.__class__:
 410           return value
 411
 412       try:
 413           return self.getDictOrderedDict(value)
 414       except:
 415           try:
 416               return self.getDictArray(value)
 417           except:
 418               try:
 419                   return value.getDict()
 420               except:
 421                   return value
 422
 423    def getDictArray(self, array):
 424        r = []
 425        for value in array:
 426           r.append(self.getDictItem(value))
 427        return r
 428
 429    def getDictOrderedDict(self, dict):
 430        r = collections.OrderedDict()
 431        for (key, value) in dict.items():
 432            r[key] = self.getDictItem(value)
 433        return r
 434
 435    def getDict(self):
 436        return self.getDictOrderedDict(self.data)
 437
 438vmsd_field_readers = {
 439    "bool" : VMSDFieldBool,
 440    "int8" : VMSDFieldInt,
 441    "int16" : VMSDFieldInt,
 442    "int32" : VMSDFieldInt,
 443    "int32 equal" : VMSDFieldInt,
 444    "int32 le" : VMSDFieldIntLE,
 445    "int64" : VMSDFieldInt,
 446    "uint8" : VMSDFieldUInt,
 447    "uint16" : VMSDFieldUInt,
 448    "uint32" : VMSDFieldUInt,
 449    "uint32 equal" : VMSDFieldUInt,
 450    "uint64" : VMSDFieldUInt,
 451    "int64 equal" : VMSDFieldInt,
 452    "uint8 equal" : VMSDFieldInt,
 453    "uint16 equal" : VMSDFieldInt,
 454    "float64" : VMSDFieldGeneric,
 455    "timer" : VMSDFieldGeneric,
 456    "buffer" : VMSDFieldGeneric,
 457    "unused_buffer" : VMSDFieldGeneric,
 458    "bitmap" : VMSDFieldGeneric,
 459    "struct" : VMSDFieldStruct,
 460    "unknown" : VMSDFieldGeneric,
 461}
 462
 463class VMSDSection(VMSDFieldStruct):
 464    def __init__(self, file, version_id, device, section_key):
 465        self.file = file
 466        self.data = ""
 467        self.vmsd_name = ""
 468        self.section_key = section_key
 469        desc = device
 470        if 'vmsd_name' in device:
 471            self.vmsd_name = device['vmsd_name']
 472
 473        # A section really is nothing but a FieldStruct :)
 474        super(VMSDSection, self).__init__({ 'struct' : desc }, file)
 475
 476###############################################################################
 477
 478class MigrationDump(object):
 479    QEMU_VM_FILE_MAGIC    = 0x5145564d
 480    QEMU_VM_FILE_VERSION  = 0x00000003
 481    QEMU_VM_EOF           = 0x00
 482    QEMU_VM_SECTION_START = 0x01
 483    QEMU_VM_SECTION_PART  = 0x02
 484    QEMU_VM_SECTION_END   = 0x03
 485    QEMU_VM_SECTION_FULL  = 0x04
 486    QEMU_VM_SUBSECTION    = 0x05
 487    QEMU_VM_VMDESCRIPTION = 0x06
 488    QEMU_VM_CONFIGURATION = 0x07
 489    QEMU_VM_SECTION_FOOTER= 0x7e
 490
 491    def __init__(self, filename):
 492        self.section_classes = { ( 'ram', 0 ) : [ RamSection, None ],
 493                                 ( 'spapr/htab', 0) : ( HTABSection, None ) }
 494        self.filename = filename
 495        self.vmsd_desc = None
 496
 497    def read(self, desc_only = False, dump_memory = False, write_memory = False):
 498        # Read in the whole file
 499        file = MigrationFile(self.filename)
 500
 501        # File magic
 502        data = file.read32()
 503        if data != self.QEMU_VM_FILE_MAGIC:
 504            raise Exception("Invalid file magic %x" % data)
 505
 506        # Version (has to be v3)
 507        data = file.read32()
 508        if data != self.QEMU_VM_FILE_VERSION:
 509            raise Exception("Invalid version number %d" % data)
 510
 511        self.load_vmsd_json(file)
 512
 513        # Read sections
 514        self.sections = collections.OrderedDict()
 515
 516        if desc_only:
 517            return
 518
 519        ramargs = {}
 520        ramargs['page_size'] = self.vmsd_desc['page_size']
 521        ramargs['dump_memory'] = dump_memory
 522        ramargs['write_memory'] = write_memory
 523        self.section_classes[('ram',0)][1] = ramargs
 524
 525        while True:
 526            section_type = file.read8()
 527            if section_type == self.QEMU_VM_EOF:
 528                break
 529            elif section_type == self.QEMU_VM_CONFIGURATION:
 530                section = ConfigurationSection(file)
 531                section.read()
 532            elif section_type == self.QEMU_VM_SECTION_START or section_type == self.QEMU_VM_SECTION_FULL:
 533                section_id = file.read32()
 534                name = file.readstr()
 535                instance_id = file.read32()
 536                version_id = file.read32()
 537                section_key = (name, instance_id)
 538                classdesc = self.section_classes[section_key]
 539                section = classdesc[0](file, version_id, classdesc[1], section_key)
 540                self.sections[section_id] = section
 541                section.read()
 542            elif section_type == self.QEMU_VM_SECTION_PART or section_type == self.QEMU_VM_SECTION_END:
 543                section_id = file.read32()
 544                self.sections[section_id].read()
 545            elif section_type == self.QEMU_VM_SECTION_FOOTER:
 546                read_section_id = file.read32()
 547                if read_section_id != section_id:
 548                    raise Exception("Mismatched section footer: %x vs %x" % (read_section_id, section_id))
 549            else:
 550                raise Exception("Unknown section type: %d" % section_type)
 551        file.close()
 552
 553    def load_vmsd_json(self, file):
 554        vmsd_json = file.read_migration_debug_json()
 555        self.vmsd_desc = json.loads(vmsd_json, object_pairs_hook=collections.OrderedDict)
 556        for device in self.vmsd_desc['devices']:
 557            key = (device['name'], device['instance_id'])
 558            value = ( VMSDSection, device )
 559            self.section_classes[key] = value
 560
 561    def getDict(self):
 562        r = collections.OrderedDict()
 563        for (key, value) in self.sections.items():
 564           key = "%s (%d)" % ( value.section_key[0], key )
 565           r[key] = value.getDict()
 566        return r
 567
 568###############################################################################
 569
 570class JSONEncoder(json.JSONEncoder):
 571    def default(self, o):
 572        if isinstance(o, VMSDFieldGeneric):
 573            return str(o)
 574        return json.JSONEncoder.default(self, o)
 575
 576parser = argparse.ArgumentParser()
 577parser.add_argument("-f", "--file", help='migration dump to read from', required=True)
 578parser.add_argument("-m", "--memory", help='dump RAM contents as well', action='store_true')
 579parser.add_argument("-d", "--dump", help='what to dump ("state" or "desc")', default='state')
 580parser.add_argument("-x", "--extract", help='extract contents into individual files', action='store_true')
 581args = parser.parse_args()
 582
 583jsonenc = JSONEncoder(indent=4, separators=(',', ': '))
 584
 585if args.extract:
 586    dump = MigrationDump(args.file)
 587
 588    dump.read(desc_only = True)
 589    print("desc.json")
 590    f = open("desc.json", "wb")
 591    f.truncate()
 592    f.write(jsonenc.encode(dump.vmsd_desc))
 593    f.close()
 594
 595    dump.read(write_memory = True)
 596    dict = dump.getDict()
 597    print("state.json")
 598    f = open("state.json", "wb")
 599    f.truncate()
 600    f.write(jsonenc.encode(dict))
 601    f.close()
 602elif args.dump == "state":
 603    dump = MigrationDump(args.file)
 604    dump.read(dump_memory = args.memory)
 605    dict = dump.getDict()
 606    print(jsonenc.encode(dict))
 607elif args.dump == "desc":
 608    dump = MigrationDump(args.file)
 609    dump.read(desc_only = True)
 610    print(jsonenc.encode(dump.vmsd_desc))
 611else:
 612    raise Exception("Please specify either -x, -d state or -d dump")
 613