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