master
py 827 lines 27.8 KB
Raw
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.1 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
20 import json
21 import os
22 import math
23 import argparse
24 import collections
25 import struct
26 import sys
27
28
29 def mkdir_p(path):
30 try:
31 os.makedirs(path)
32 except OSError:
33 pass
34
35
36 class MigrationFile(object):
37 def __init__(self, filename):
38 self.filename = filename
39 self.file = open(self.filename, "rb")
40
41 def read64(self):
42 return int.from_bytes(self.file.read(8), byteorder='big', signed=False)
43
44 def read32(self):
45 return int.from_bytes(self.file.read(4), byteorder='big', signed=False)
46
47 def read16(self):
48 return int.from_bytes(self.file.read(2), byteorder='big', signed=False)
49
50 def read8(self):
51 return int.from_bytes(self.file.read(1), byteorder='big', signed=True)
52
53 def readstr(self, len = None):
54 return self.readvar(len).decode('utf-8')
55
56 def readvar(self, size = None):
57 if size is None:
58 size = self.read8()
59 if size == 0:
60 return ""
61 value = self.file.read(size)
62 if len(value) != size:
63 raise Exception("Unexpected end of %s at 0x%x" % (self.filename, self.file.tell()))
64 return value
65
66 def tell(self):
67 return self.file.tell()
68
69 def seek(self, a, b):
70 return self.file.seek(a, b)
71
72 # The VMSD description is at the end of the file, after EOF. Look for
73 # the last NULL byte, then for the beginning brace of JSON.
74 def read_migration_debug_json(self):
75 QEMU_VM_VMDESCRIPTION = 0x06
76
77 # Remember the offset in the file when we started
78 entrypos = self.file.tell()
79
80 # Read the last 10MB
81 self.file.seek(0, os.SEEK_END)
82 endpos = self.file.tell()
83 self.file.seek(max(-endpos, -10 * 1024 * 1024), os.SEEK_END)
84 datapos = self.file.tell()
85 data = self.file.read()
86 # The full file read closed the file as well, reopen it
87 self.file = open(self.filename, "rb")
88
89 # Find the last NULL byte, then the first brace after that. This should
90 # be the beginning of our JSON data.
91 nulpos = data.rfind(b'\0')
92 jsonpos = data.find(b'{', nulpos)
93
94 # Check backwards from there and see whether we guessed right
95 self.file.seek(datapos + jsonpos - 5, 0)
96 if self.read8() != QEMU_VM_VMDESCRIPTION:
97 raise Exception("No Debug Migration device found")
98
99 jsonlen = self.read32()
100
101 # Seek back to where we were at the beginning
102 self.file.seek(entrypos, 0)
103
104 # explicit decode() needed for Python 3.5 compatibility
105 return data[jsonpos:jsonpos + jsonlen].decode("utf-8")
106
107 def close(self):
108 self.file.close()
109
110 class RamSection(object):
111 RAM_SAVE_FLAG_ZERO = 0x02
112 RAM_SAVE_FLAG_MEM_SIZE = 0x04
113 RAM_SAVE_FLAG_PAGE = 0x08
114 RAM_SAVE_FLAG_EOS = 0x10
115 RAM_SAVE_FLAG_CONTINUE = 0x20
116 RAM_SAVE_FLAG_XBZRLE = 0x40
117 RAM_SAVE_FLAG_HOOK = 0x80
118 RAM_SAVE_FLAG_COMPRESS_PAGE = 0x100
119 RAM_SAVE_FLAG_MULTIFD_FLUSH = 0x200
120
121 def __init__(self, file, version_id, ramargs, section_key):
122 if version_id != 4:
123 raise Exception("Unknown RAM version %d" % version_id)
124
125 self.file = file
126 self.section_key = section_key
127 self.TARGET_PAGE_SIZE = ramargs['page_size']
128 self.dump_memory = ramargs['dump_memory']
129 self.write_memory = ramargs['write_memory']
130 self.ignore_shared = ramargs['ignore_shared']
131 self.mapped_ram = ramargs['mapped_ram']
132 self.sizeinfo = collections.OrderedDict()
133 self.data = collections.OrderedDict()
134 self.data['section sizes'] = self.sizeinfo
135 self.name = ''
136 if self.write_memory:
137 self.files = { }
138 if self.dump_memory:
139 self.memory = collections.OrderedDict()
140 self.data['memory'] = self.memory
141
142 def __repr__(self):
143 return self.data.__repr__()
144
145 def __str__(self):
146 return self.data.__str__()
147
148 def getDict(self):
149 return self.data
150
151 def parseMappedRamBlob(self, len):
152 version = self.file.read32()
153 if version != 1:
154 raise Exception("Unsupported MappedRamHeader version %s" % version)
155
156 page_size = self.file.read64()
157 if page_size != self.TARGET_PAGE_SIZE:
158 raise Exception("Page size mismatch in MappedRamHeader")
159
160 bitmap_offset = self.file.read64()
161 pages_offset = self.file.read64()
162
163 if self.ignore_shared and bitmap_offset == 0 and pages_offset == 0:
164 # This is a shared ramblock, x-ignore-share must have been
165 # enabled, and mapped-ram didn't allocate bitmap or page blob
166 # for it.
167 return
168
169 if self.dump_memory or self.write_memory:
170 num_pages = len // page_size
171
172 self.file.seek(bitmap_offset, os.SEEK_SET)
173 bitmap_len = int(math.ceil(num_pages / 8))
174 bitmap = self.file.readvar(size=bitmap_len)
175
176 self.file.seek(pages_offset, os.SEEK_SET)
177 for page_num in range(num_pages):
178 page_addr = page_num * page_size
179
180 is_filled = (bitmap[page_num // 8] >> page_num % 8) & 1
181 if is_filled:
182 data = self.file.readvar(size=self.TARGET_PAGE_SIZE)
183 if self.write_memory:
184 self.files[self.name].seek(page_addr, os.SEEK_SET)
185 self.files[self.name].write(data)
186 if self.dump_memory:
187 hexdata = " ".join("{0:02x}".format(c) for c in data)
188 self.memory['%s (0x%016x)' %
189 (self.name, page_addr)] = hexdata
190 else:
191 self.file.seek(self.TARGET_PAGE_SIZE, os.SEEK_CUR)
192 if self.write_memory:
193 self.files[self.name].seek(page_addr, os.SEEK_SET)
194 self.files[self.name].write(
195 b'\x00' * self.TARGET_PAGE_SIZE)
196 if self.dump_memory:
197 self.memory['%s (0x%016x)' %
198 (self.name, page_addr)] = 'Filled with 0x00'
199
200 self.file.seek(pages_offset + len, os.SEEK_SET)
201
202 def read(self):
203 # Read all RAM sections
204 while True:
205 addr = self.file.read64()
206 flags = addr & (self.TARGET_PAGE_SIZE - 1)
207 addr &= ~(self.TARGET_PAGE_SIZE - 1)
208
209 if flags & self.RAM_SAVE_FLAG_MEM_SIZE:
210 total_length = addr
211 while total_length > 0:
212 namelen = self.file.read8()
213 self.name = self.file.readstr(len = namelen)
214 len = self.file.read64()
215 total_length -= len
216 self.sizeinfo[self.name] = '0x%016x' % len
217 if self.write_memory:
218 print(self.name)
219 mkdir_p('./' + os.path.dirname(self.name))
220 f = open('./' + self.name, "wb")
221 f.truncate(0)
222 f.truncate(len)
223 self.files[self.name] = f
224 if self.ignore_shared:
225 mr_addr = self.file.read64()
226 if self.mapped_ram:
227 self.parseMappedRamBlob(len)
228 flags &= ~self.RAM_SAVE_FLAG_MEM_SIZE
229
230 if flags & self.RAM_SAVE_FLAG_ZERO:
231 if flags & self.RAM_SAVE_FLAG_CONTINUE:
232 flags &= ~self.RAM_SAVE_FLAG_CONTINUE
233 else:
234 self.name = self.file.readstr()
235 _fill_char = self.file.read8()
236 if self.dump_memory:
237 self.memory['%s (0x%016x)' %
238 (self.name, addr)] = 'Filled with 0x00'
239 flags &= ~self.RAM_SAVE_FLAG_ZERO
240 elif flags & self.RAM_SAVE_FLAG_PAGE:
241 if flags & self.RAM_SAVE_FLAG_CONTINUE:
242 flags &= ~self.RAM_SAVE_FLAG_CONTINUE
243 else:
244 self.name = self.file.readstr()
245
246 if self.write_memory or self.dump_memory:
247 data = self.file.readvar(size = self.TARGET_PAGE_SIZE)
248 else: # Just skip RAM data
249 self.file.file.seek(self.TARGET_PAGE_SIZE, 1)
250
251 if self.write_memory:
252 self.files[self.name].seek(addr, os.SEEK_SET)
253 self.files[self.name].write(data)
254 if self.dump_memory:
255 hexdata = " ".join("{0:02x}".format(ord(c)) for c in data)
256 self.memory['%s (0x%016x)' % (self.name, addr)] = hexdata
257
258 flags &= ~self.RAM_SAVE_FLAG_PAGE
259 elif flags & self.RAM_SAVE_FLAG_XBZRLE:
260 raise Exception("XBZRLE RAM compression is not supported yet")
261 elif flags & self.RAM_SAVE_FLAG_HOOK:
262 raise Exception("RAM hooks don't make sense with files")
263 if flags & self.RAM_SAVE_FLAG_MULTIFD_FLUSH:
264 continue
265
266 # End of RAM section
267 if flags & self.RAM_SAVE_FLAG_EOS:
268 break
269
270 if flags != 0:
271 raise Exception("Unknown RAM flags: %x" % flags)
272
273 def __del__(self):
274 if self.write_memory:
275 for key in self.files:
276 self.files[key].close()
277
278
279 class HTABSection(object):
280 HASH_PTE_SIZE_64 = 16
281
282 def __init__(self, file, version_id, device, section_key):
283 if version_id != 1:
284 raise Exception("Unknown HTAB version %d" % version_id)
285
286 self.file = file
287 self.section_key = section_key
288
289 def read(self):
290
291 header = self.file.read32()
292
293 if (header == -1):
294 # "no HPT" encoding
295 return
296
297 if (header > 0):
298 # First section, just the hash shift
299 return
300
301 # Read until end marker
302 while True:
303 index = self.file.read32()
304 n_valid = self.file.read16()
305 n_invalid = self.file.read16()
306
307 if index == 0 and n_valid == 0 and n_invalid == 0:
308 break
309
310 self.file.readvar(n_valid * self.HASH_PTE_SIZE_64)
311
312 def getDict(self):
313 return ""
314
315
316 class S390StorageAttributes(object):
317 STATTR_FLAG_EOS = 0x01
318 STATTR_FLAG_MORE = 0x02
319 STATTR_FLAG_ERROR = 0x04
320 STATTR_FLAG_DONE = 0x08
321
322 def __init__(self, file, version_id, device, section_key):
323 if version_id != 0:
324 raise Exception("Unknown storage_attributes version %d" % version_id)
325
326 self.file = file
327 self.section_key = section_key
328
329 def read(self):
330 pos = 0
331 while True:
332 addr_flags = self.file.read64()
333 flags = addr_flags & 0xfff
334
335 if flags & self.STATTR_FLAG_DONE:
336 pos = self.file.tell()
337 continue
338 elif flags & self.STATTR_FLAG_EOS:
339 return
340 else:
341 # No EOS came after DONE, that's OK, but rewind the
342 # stream because this is not our data.
343 if pos:
344 self.file.seek(pos, os.SEEK_SET)
345 return
346 raise Exception("Unknown flags %x", flags)
347
348 if (flags & self.STATTR_FLAG_ERROR):
349 raise Exception("Error in migration stream")
350 count = self.file.read64()
351 self.file.readvar(count)
352
353 def getDict(self):
354 return ""
355
356
357 class ConfigurationSection(object):
358 def __init__(self, file, desc):
359 self.file = file
360 self.desc = desc
361 self.caps = []
362
363 def parse_capabilities(self, vmsd_caps):
364 if not vmsd_caps:
365 return
366
367 ncaps = vmsd_caps.data['caps_count'].data
368 self.caps = vmsd_caps.data['capabilities']
369
370 if type(self.caps) != list:
371 self.caps = [self.caps]
372
373 if len(self.caps) != ncaps:
374 raise Exception("Number of capabilities doesn't match "
375 "caps_count field")
376
377 def has_capability(self, cap):
378 return any([str(c) == cap for c in self.caps])
379
380 def read(self):
381 if self.desc:
382 version_id = self.desc['version']
383 section = VMSDSection(self.file, version_id, self.desc,
384 'configuration')
385 section.read()
386 self.parse_capabilities(
387 section.data.get("configuration/capabilities"))
388 else:
389 # backward compatibility for older streams that don't have
390 # the configuration section in the json
391 name_len = self.file.read32()
392 name = self.file.readstr(len = name_len)
393
394 class VMSDFieldGeneric(object):
395 def __init__(self, desc, file):
396 self.file = file
397 self.desc = desc
398 self.data = ""
399
400 def __repr__(self):
401 return str(self.__str__())
402
403 def __str__(self):
404 return " ".join("{0:02x}".format(c) for c in self.data)
405
406 def getDict(self):
407 return self.__str__()
408
409 def read(self):
410 size = int(self.desc['size'])
411 self.data = self.file.readvar(size)
412 return self.data
413
414 class VMSDFieldCap(object):
415 def __init__(self, desc, file):
416 self.file = file
417 self.desc = desc
418 self.data = ""
419
420 def __repr__(self):
421 return self.data
422
423 def __str__(self):
424 return self.data
425
426 def read(self):
427 len = self.file.read8()
428 self.data = self.file.readstr(len)
429
430
431 class VMSDFieldInt(VMSDFieldGeneric):
432 def __init__(self, desc, file):
433 super(VMSDFieldInt, self).__init__(desc, file)
434 self.size = int(desc['size'])
435 self.format = '0x%%0%dx' % (self.size * 2)
436 self.sdtype = '>i%d' % self.size
437 self.udtype = '>u%d' % self.size
438
439 def __repr__(self):
440 if self.data < 0:
441 return ('%s (%d)' % ((self.format % self.udata), self.data))
442 else:
443 return self.format % self.data
444
445 def __str__(self):
446 return self.__repr__()
447
448 def getDict(self):
449 return self.__str__()
450
451 def read(self):
452 super(VMSDFieldInt, self).read()
453 self.sdata = int.from_bytes(self.data, byteorder='big', signed=True)
454 self.udata = int.from_bytes(self.data, byteorder='big', signed=False)
455 self.data = self.sdata
456 return self.data
457
458 class VMSDFieldUInt(VMSDFieldInt):
459 def __init__(self, desc, file):
460 super(VMSDFieldUInt, self).__init__(desc, file)
461
462 def read(self):
463 super(VMSDFieldUInt, self).read()
464 self.data = self.udata
465 return self.data
466
467 class VMSDFieldIntLE(VMSDFieldInt):
468 def __init__(self, desc, file):
469 super(VMSDFieldIntLE, self).__init__(desc, file)
470 self.dtype = '<i%d' % self.size
471
472 class VMSDFieldPtrMarker(VMSDFieldGeneric):
473 NULL_PTR_MARKER = b'0'
474 VALID_PTR_MARKER = b'1'
475
476 def __init__(self, desc, file):
477 super(VMSDFieldPtrMarker, self).__init__(desc, file)
478
479 def __repr__(self):
480 # A NULL / non-NULL pointer may be encoded in the stream as a
481 # '0'/'1' to represent the status of the pointer. Displaying '0',
482 # 0x30 or 0x0 when analyzing the JSON debug stream could become
483 # confusing, so use an explicit term instead.
484 return "null-ptr" if self.data == self.NULL_PTR_MARKER else "valid-ptr"
485
486 def __str__(self):
487 return self.__repr__()
488
489 def read(self):
490 super(VMSDFieldPtrMarker, self).read()
491 assert(self.data in [self.NULL_PTR_MARKER, self.VALID_PTR_MARKER])
492 return self.data
493
494 class VMSDFieldBool(VMSDFieldGeneric):
495 def __init__(self, desc, file):
496 super(VMSDFieldBool, self).__init__(desc, file)
497
498 def __repr__(self):
499 return self.data.__repr__()
500
501 def __str__(self):
502 return self.data.__str__()
503
504 def getDict(self):
505 return self.data
506
507 def read(self):
508 super(VMSDFieldBool, self).read()
509 if self.data[0] == 0:
510 self.data = False
511 else:
512 self.data = True
513 return self.data
514
515 class VMSDFieldStruct(VMSDFieldGeneric):
516 QEMU_VM_SUBSECTION = 0x05
517
518 def __init__(self, desc, file):
519 super(VMSDFieldStruct, self).__init__(desc, file)
520 self.data = collections.OrderedDict()
521
522 if 'fields' not in self.desc['struct']:
523 raise Exception("No fields in struct. VMSD:\n%s" % self.desc)
524
525 # When we see compressed array elements, unfold them here
526 new_fields = []
527 for field in self.desc['struct']['fields']:
528 if not 'array_len' in field:
529 new_fields.append(field)
530 continue
531 array_len = field.pop('array_len')
532 field['index'] = 0
533 new_fields.append(field)
534 for i in range(1, array_len):
535 c = field.copy()
536 c['index'] = i
537 new_fields.append(c)
538
539 self.desc['struct']['fields'] = new_fields
540
541 def __repr__(self):
542 return self.data.__repr__()
543
544 def __str__(self):
545 return self.data.__str__()
546
547 def read(self):
548 for field in self.desc['struct']['fields']:
549 try:
550 reader = vmsd_field_readers[field['type']]
551 except:
552 reader = VMSDFieldGeneric
553
554 field['data'] = reader(field, self.file)
555 field['data'].read()
556
557 fname = field['name']
558 fdata = field['data']
559
560 # The field could be:
561 # i) a single data entry, e.g. uint64
562 # ii) an array, indicated by it containing the 'index' key
563 #
564 # However, the overall data after parsing the whole
565 # stream, could be a mix of arrays and single data fields,
566 # all sharing the same field name due to how QEMU breaks
567 # up arrays with NULL pointers into multiple compressed
568 # array segments.
569 if fname not in self.data:
570 self.data[fname] = fdata
571 elif type(self.data[fname]) == list:
572 self.data[fname].append(fdata)
573 else:
574 tmp = self.data[fname]
575 self.data[fname] = [tmp, fdata]
576
577 if 'subsections' in self.desc['struct']:
578 for subsection in self.desc['struct']['subsections']:
579 if self.file.read8() != self.QEMU_VM_SUBSECTION:
580 raise Exception("Subsection %s not found at offset %x" % ( subsection['vmsd_name'], self.file.tell()))
581 name = self.file.readstr()
582 version_id = self.file.read32()
583
584 if not subsection:
585 raise Exception("Empty description for subsection: %s" % name)
586
587 self.data[name] = VMSDSection(self.file, version_id, subsection, (name, 0))
588 self.data[name].read()
589
590 def getDictItem(self, value):
591 # Strings would fall into the array category, treat
592 # them specially
593 if value.__class__ is ''.__class__:
594 return value
595
596 try:
597 return self.getDictOrderedDict(value)
598 except:
599 try:
600 return self.getDictArray(value)
601 except:
602 try:
603 return value.getDict()
604 except:
605 return value
606
607 def getDictArray(self, array):
608 r = []
609 for value in array:
610 r.append(self.getDictItem(value))
611 return r
612
613 def getDictOrderedDict(self, dict):
614 r = collections.OrderedDict()
615 for (key, value) in dict.items():
616 r[key] = self.getDictItem(value)
617 return r
618
619 def getDict(self):
620 return self.getDictOrderedDict(self.data)
621
622 vmsd_field_readers = {
623 "bool" : VMSDFieldBool,
624 "int8" : VMSDFieldInt,
625 "int16" : VMSDFieldInt,
626 "int32" : VMSDFieldInt,
627 "int32 equal" : VMSDFieldInt,
628 "int32 le" : VMSDFieldIntLE,
629 "int64" : VMSDFieldInt,
630 "uint8" : VMSDFieldUInt,
631 "uint16" : VMSDFieldUInt,
632 "uint32" : VMSDFieldUInt,
633 "uint32 equal" : VMSDFieldUInt,
634 "uint64" : VMSDFieldUInt,
635 "int64 equal" : VMSDFieldInt,
636 "uint8 equal" : VMSDFieldInt,
637 "uint16 equal" : VMSDFieldInt,
638 "float64" : VMSDFieldGeneric,
639 "timer" : VMSDFieldGeneric,
640 "buffer" : VMSDFieldGeneric,
641 "unused_buffer" : VMSDFieldGeneric,
642 "bitmap" : VMSDFieldGeneric,
643 "struct" : VMSDFieldStruct,
644 "capability": VMSDFieldCap,
645 # Keep the old nullptr for old binaries
646 "nullptr": VMSDFieldPtrMarker,
647 "ptr-marker": VMSDFieldPtrMarker,
648 "unknown" : VMSDFieldGeneric,
649 }
650
651 class VMSDSection(VMSDFieldStruct):
652 def __init__(self, file, version_id, device, section_key):
653 self.file = file
654 self.data = ""
655 self.vmsd_name = ""
656 self.section_key = section_key
657 desc = device
658 if 'vmsd_name' in device:
659 self.vmsd_name = device['vmsd_name']
660
661 # A section really is nothing but a FieldStruct :)
662 super(VMSDSection, self).__init__({ 'struct' : desc }, file)
663
664 ###############################################################################
665
666 class MigrationDump(object):
667 QEMU_VM_FILE_MAGIC = 0x5145564d
668 QEMU_VM_FILE_VERSION = 0x00000003
669 QEMU_VM_EOF = 0x00
670 QEMU_VM_SECTION_START = 0x01
671 QEMU_VM_SECTION_PART = 0x02
672 QEMU_VM_SECTION_END = 0x03
673 QEMU_VM_SECTION_FULL = 0x04
674 QEMU_VM_SUBSECTION = 0x05
675 QEMU_VM_VMDESCRIPTION = 0x06
676 QEMU_VM_CONFIGURATION = 0x07
677 QEMU_VM_COMMAND = 0x08
678 QEMU_VM_SECTION_FOOTER= 0x7e
679 QEMU_MIG_CMD_SWITCHOVER_START = 0x0b
680
681 def __init__(self, filename):
682 self.section_classes = {
683 ( 'ram', 0 ) : [ RamSection, None ],
684 ( 's390-storage_attributes', 0 ) : [ S390StorageAttributes, None],
685 ( 'spapr/htab', 0) : ( HTABSection, None )
686 }
687 self.filename = filename
688 self.vmsd_desc = None
689 self.vmsd_json = ""
690
691 def read(self, desc_only = False, dump_memory = False,
692 write_memory = False):
693 # Read in the whole file
694 file = MigrationFile(self.filename)
695 self.vmsd_json = file.read_migration_debug_json()
696
697 # File magic
698 data = file.read32()
699 if data != self.QEMU_VM_FILE_MAGIC:
700 raise Exception("Invalid file magic %x" % data)
701
702 # Version (has to be v3)
703 data = file.read32()
704 if data != self.QEMU_VM_FILE_VERSION:
705 raise Exception("Invalid version number %d" % data)
706
707 self.load_vmsd_json(file)
708
709 # Read sections
710 self.sections = collections.OrderedDict()
711
712 if desc_only:
713 return
714
715 ramargs = {}
716 ramargs['page_size'] = self.vmsd_desc['page_size']
717 ramargs['dump_memory'] = dump_memory
718 ramargs['write_memory'] = write_memory
719 ramargs['ignore_shared'] = False
720 ramargs['mapped_ram'] = False
721 self.section_classes[('ram',0)][1] = ramargs
722
723 while True:
724 section_type = file.read8()
725 if section_type == self.QEMU_VM_EOF:
726 break
727 elif section_type == self.QEMU_VM_CONFIGURATION:
728 config_desc = self.vmsd_desc.get('configuration')
729 section = ConfigurationSection(file, config_desc)
730 section.read()
731 ramargs['ignore_shared'] = section.has_capability('x-ignore-shared')
732 ramargs['mapped_ram'] = section.has_capability('mapped-ram')
733 elif section_type == self.QEMU_VM_SECTION_START or section_type == self.QEMU_VM_SECTION_FULL:
734 section_id = file.read32()
735 name = file.readstr()
736 instance_id = file.read32()
737 version_id = file.read32()
738 section_key = (name, instance_id)
739 classdesc = self.section_classes[section_key]
740 section = classdesc[0](file, version_id, classdesc[1], section_key)
741 self.sections[section_id] = section
742 section.read()
743 elif section_type == self.QEMU_VM_SECTION_PART or section_type == self.QEMU_VM_SECTION_END:
744 section_id = file.read32()
745 self.sections[section_id].read()
746 elif section_type == self.QEMU_VM_COMMAND:
747 command_type = file.read16()
748 command_data_len = file.read16()
749 if command_type != self.QEMU_MIG_CMD_SWITCHOVER_START:
750 raise Exception("Unknown QEMU_VM_COMMAND: %x" %
751 (command_type))
752 if command_data_len != 0:
753 raise Exception("Invalid SWITCHOVER_START length: %x" %
754 (command_data_len))
755 elif section_type == self.QEMU_VM_SECTION_FOOTER:
756 read_section_id = file.read32()
757 if read_section_id != section_id:
758 raise Exception("Mismatched section footer: %x vs %x" % (read_section_id, section_id))
759 else:
760 raise Exception("Unknown section type: %d" % section_type)
761 file.close()
762
763 def load_vmsd_json(self, file):
764 self.vmsd_desc = json.loads(self.vmsd_json,
765 object_pairs_hook=collections.OrderedDict)
766 for device in self.vmsd_desc['devices']:
767 if 'fields' not in device:
768 raise Exception("vmstate for device %s has no fields" % device['name'])
769 key = (device['name'], device['instance_id'])
770 value = ( VMSDSection, device )
771 self.section_classes[key] = value
772
773 def getDict(self):
774 r = collections.OrderedDict()
775 for (key, value) in self.sections.items():
776 key = "%s (%d)" % ( value.section_key[0], key )
777 r[key] = value.getDict()
778 return r
779
780 ###############################################################################
781
782 class JSONEncoder(json.JSONEncoder):
783 def default(self, o):
784 if isinstance(o, VMSDFieldGeneric):
785 return str(o)
786 return json.JSONEncoder.default(self, o)
787
788 parser = argparse.ArgumentParser()
789 parser.add_argument("-f", "--file", help='migration dump to read from', required=True)
790 parser.add_argument("-m", "--memory", help='dump RAM contents as well', action='store_true')
791 parser.add_argument("-d", "--dump", help='what to dump ("state" or "desc")', default='state')
792 parser.add_argument("-x", "--extract", help='extract contents into individual files', action='store_true')
793 args = parser.parse_args()
794
795 jsonenc = JSONEncoder(indent=4, separators=(',', ': '))
796
797 if not any([args.extract, args.dump == "state", args.dump == "desc"]):
798 raise Exception("Please specify either -x, -d state or -d desc")
799
800 try:
801 dump = MigrationDump(args.file)
802
803 if args.extract:
804 dump.read(desc_only = True)
805
806 print("desc.json")
807 f = open("desc.json", "w")
808 f.truncate()
809 f.write(jsonenc.encode(dump.vmsd_desc))
810 f.close()
811
812 dump.read(write_memory = True)
813 dict = dump.getDict()
814 print("state.json")
815 f = open("state.json", "w")
816 f.truncate()
817 f.write(jsonenc.encode(dict))
818 f.close()
819 elif args.dump == "state":
820 dump.read(dump_memory = args.memory)
821 dict = dump.getDict()
822 print(jsonenc.encode(dict))
823 elif args.dump == "desc":
824 dump.read(desc_only = True)
825 print(jsonenc.encode(dump.vmsd_desc))
826 except Exception:
827 raise Exception("Full JSON dump:\n%s", dump.vmsd_json)