3 # Migration Stream Analyzer
5 # Copyright (c) 2015 Alexander Graf <agraf@suse.de>
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.
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.
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/>.
20 from __future__
import print_function
34 class MigrationFile(object):
35 def __init__(self
, filename
):
36 self
.filename
= filename
37 self
.file = open(self
.filename
, "rb")
40 return np
.asscalar(np
.fromfile(self
.file, count
=1, dtype
='>i8')[0])
43 return np
.asscalar(np
.fromfile(self
.file, count
=1, dtype
='>i4')[0])
46 return np
.asscalar(np
.fromfile(self
.file, count
=1, dtype
='>i2')[0])
49 return np
.asscalar(np
.fromfile(self
.file, count
=1, dtype
='>i1')[0])
51 def readstr(self
, len = None):
56 return np
.fromfile(self
.file, count
=1, dtype
=('S%d' % len))[0]
58 def readvar(self
, size
= None):
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()))
69 return self
.file.tell()
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
76 # Remember the offset in the file when we started
77 entrypos
= self
.file.tell()
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")
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
)
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")
98 jsonlen
= self
.read32()
100 # Seek back to where we were at the beginning
101 self
.file.seek(entrypos
, 0)
103 return data
[jsonpos
:jsonpos
+ jsonlen
]
108 class 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
117 def __init__(self
, file, version_id
, ramargs
, section_key
):
119 raise Exception("Unknown RAM version %d" % version_id
)
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
130 if self
.write_memory
:
133 self
.memory
= collections
.OrderedDict()
134 self
.data
['memory'] = self
.memory
137 return self
.data
.__repr
__()
140 return self
.data
.__str
__()
146 # Read all RAM sections
148 addr
= self
.file.read64()
149 flags
= addr
& (self
.TARGET_PAGE_SIZE
- 1)
150 addr
&= ~
(self
.TARGET_PAGE_SIZE
- 1)
152 if flags
& self
.RAM_SAVE_FLAG_MEM_SIZE
:
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.
160 self
.file.file.seek(-1, 1)
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
:
167 mkdir_p('./' + os
.path
.dirname(self
.name
))
168 f
= open('./' + self
.name
, "wb")
171 self
.files
[self
.name
] = f
172 flags
&= ~self
.RAM_SAVE_FLAG_MEM_SIZE
174 if flags
& self
.RAM_SAVE_FLAG_COMPRESS
:
175 if flags
& self
.RAM_SAVE_FLAG_CONTINUE
:
176 flags
&= ~self
.RAM_SAVE_FLAG_CONTINUE
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
)
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
191 self
.name
= self
.file.readstr()
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)
198 if self
.write_memory
:
199 self
.files
[self
.name
].seek(addr
, os
.SEEK_SET
)
200 self
.files
[self
.name
].write(data
)
202 hexdata
= " ".join("{0:02x}".format(ord(c
)) for c
in data
)
203 self
.memory
['%s (0x%016x)' % (self
.name
, addr
)] = hexdata
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")
212 if flags
& self
.RAM_SAVE_FLAG_EOS
:
216 raise Exception("Unknown RAM flags: %x" % flags
)
219 if self
.write_memory
:
220 for key
in self
.files
:
221 self
.files
[key
].close()
224 class HTABSection(object):
225 HASH_PTE_SIZE_64
= 16
227 def __init__(self
, file, version_id
, device
, section_key
):
229 raise Exception("Unknown HTAB version %d" % version_id
)
232 self
.section_key
= section_key
236 header
= self
.file.read32()
243 # First section, just the hash shift
246 # Read until end marker
248 index
= self
.file.read32()
249 n_valid
= self
.file.read16()
250 n_invalid
= self
.file.read16()
252 if index
== 0 and n_valid
== 0 and n_invalid
== 0:
255 self
.file.readvar(n_valid
* self
.HASH_PTE_SIZE_64
)
261 class ConfigurationSection(object):
262 def __init__(self
, file):
266 name_len
= self
.file.read32()
267 name
= self
.file.readstr(len = name_len
)
269 class VMSDFieldGeneric(object):
270 def __init__(self
, desc
, file):
276 return str(self
.__str
__())
279 return " ".join("{0:02x}".format(ord(c
)) for c
in self
.data
)
282 return self
.__str
__()
285 size
= int(self
.desc
['size'])
286 self
.data
= self
.file.readvar(size
)
289 class 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
299 return ('%s (%d)' % ((self
.format
% self
.udata
), self
.data
))
301 return self
.format
% self
.data
304 return self
.__repr
__()
307 return self
.__str
__()
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
316 class VMSDFieldUInt(VMSDFieldInt
):
317 def __init__(self
, desc
, file):
318 super(VMSDFieldUInt
, self
).__init
__(desc
, file)
321 super(VMSDFieldUInt
, self
).read()
322 self
.data
= self
.udata
325 class VMSDFieldIntLE(VMSDFieldInt
):
326 def __init__(self
, desc
, file):
327 super(VMSDFieldIntLE
, self
).__init
__(desc
, file)
328 self
.dtype
= '<i%d' % self
.size
330 class VMSDFieldBool(VMSDFieldGeneric
):
331 def __init__(self
, desc
, file):
332 super(VMSDFieldBool
, self
).__init
__(desc
, file)
335 return self
.data
.__repr
__()
338 return self
.data
.__str
__()
344 super(VMSDFieldBool
, self
).read()
345 if self
.data
[0] == 0:
351 class VMSDFieldStruct(VMSDFieldGeneric
):
352 QEMU_VM_SUBSECTION
= 0x05
354 def __init__(self
, desc
, file):
355 super(VMSDFieldStruct
, self
).__init
__(desc
, file)
356 self
.data
= collections
.OrderedDict()
358 # When we see compressed array elements, unfold them here
360 for field
in self
.desc
['struct']['fields']:
361 if not 'array_len' in field
:
362 new_fields
.append(field
)
364 array_len
= field
.pop('array_len')
366 new_fields
.append(field
)
367 for i
in xrange(1, array_len
):
372 self
.desc
['struct']['fields'] = new_fields
375 return self
.data
.__repr
__()
378 return self
.data
.__str
__()
381 for field
in self
.desc
['struct']['fields']:
383 reader
= vmsd_field_readers
[field
['type']]
385 reader
= VMSDFieldGeneric
387 field
['data'] = reader(field
, self
.file)
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'])
398 self
.data
[field
['name']] = field
['data']
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()
409 def getDictItem(self
, value
):
410 # Strings would fall into the array category, treat
412 if value
.__class
__ is ''.__class
__:
416 return self
.getDictOrderedDict(value
)
419 return self
.getDictArray(value
)
422 return value
.getDict()
426 def getDictArray(self
, array
):
429 r
.append(self
.getDictItem(value
))
432 def getDictOrderedDict(self
, dict):
433 r
= collections
.OrderedDict()
434 for (key
, value
) in dict.items():
435 r
[key
] = self
.getDictItem(value
)
439 return self
.getDictOrderedDict(self
.data
)
441 vmsd_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
,
466 class VMSDSection(VMSDFieldStruct
):
467 def __init__(self
, file, version_id
, device
, section_key
):
471 self
.section_key
= section_key
473 if 'vmsd_name' in device
:
474 self
.vmsd_name
= device
['vmsd_name']
476 # A section really is nothing but a FieldStruct :)
477 super(VMSDSection
, self
).__init
__({ 'struct' : desc
}, file)
479 ###############################################################################
481 class MigrationDump(object):
482 QEMU_VM_FILE_MAGIC
= 0x5145564d
483 QEMU_VM_FILE_VERSION
= 0x00000003
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
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
500 def read(self
, desc_only
= False, dump_memory
= False, write_memory
= False):
501 # Read in the whole file
502 file = MigrationFile(self
.filename
)
506 if data
!= self
.QEMU_VM_FILE_MAGIC
:
507 raise Exception("Invalid file magic %x" % data
)
509 # Version (has to be v3)
511 if data
!= self
.QEMU_VM_FILE_VERSION
:
512 raise Exception("Invalid version number %d" % data
)
514 self
.load_vmsd_json(file)
517 self
.sections
= collections
.OrderedDict()
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
529 section_type
= file.read8()
530 if section_type
== self
.QEMU_VM_EOF
:
532 elif section_type
== self
.QEMU_VM_CONFIGURATION
:
533 section
= ConfigurationSection(file)
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
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
))
553 raise Exception("Unknown section type: %d" % section_type
)
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
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()
571 ###############################################################################
573 class JSONEncoder(json
.JSONEncoder
):
574 def default(self
, o
):
575 if isinstance(o
, VMSDFieldGeneric
):
577 return json
.JSONEncoder
.default(self
, o
)
579 parser
= argparse
.ArgumentParser()
580 parser
.add_argument("-f", "--file", help='migration dump to read from', required
=True)
581 parser
.add_argument("-m", "--memory", help='dump RAM contents as well', action
='store_true')
582 parser
.add_argument("-d", "--dump", help='what to dump ("state" or "desc")', default
='state')
583 parser
.add_argument("-x", "--extract", help='extract contents into individual files', action
='store_true')
584 args
= parser
.parse_args()
586 jsonenc
= JSONEncoder(indent
=4, separators
=(',', ': '))
589 dump
= MigrationDump(args
.file)
591 dump
.read(desc_only
= True)
593 f
= open("desc.json", "wb")
595 f
.write(jsonenc
.encode(dump
.vmsd_desc
))
598 dump
.read(write_memory
= True)
599 dict = dump
.getDict()
601 f
= open("state.json", "wb")
603 f
.write(jsonenc
.encode(dict))
605 elif args
.dump
== "state":
606 dump
= MigrationDump(args
.file)
607 dump
.read(dump_memory
= args
.memory
)
608 dict = dump
.getDict()
609 print(jsonenc
.encode(dict))
610 elif args
.dump
== "desc":
611 dump
= MigrationDump(args
.file)
612 dump
.read(desc_only
= True)
613 print(jsonenc
.encode(dump
.vmsd_desc
))
615 raise Exception("Please specify either -x, -d state or -d dump")