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/>.
35 class MigrationFile(object):
36 def __init__(self
, filename
):
37 self
.filename
= filename
38 self
.file = open(self
.filename
, "rb")
41 return int.from_bytes(self
.file.read(8), byteorder
='big', signed
=True)
44 return int.from_bytes(self
.file.read(4), byteorder
='big', signed
=True)
47 return int.from_bytes(self
.file.read(2), byteorder
='big', signed
=True)
50 return int.from_bytes(self
.file.read(1), byteorder
='big', signed
=True)
52 def readstr(self
, len = None):
53 return self
.readvar(len).decode('utf-8')
55 def readvar(self
, size
= None):
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()))
66 return self
.file.tell()
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
73 # Remember the offset in the file when we started
74 entrypos
= self
.file.tell()
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")
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
)
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")
95 jsonlen
= self
.read32()
97 # Seek back to where we were at the beginning
98 self
.file.seek(entrypos
, 0)
100 return data
[jsonpos
:jsonpos
+ jsonlen
]
105 class 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
114 def __init__(self
, file, version_id
, ramargs
, section_key
):
116 raise Exception("Unknown RAM version %d" % version_id
)
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
127 if self
.write_memory
:
130 self
.memory
= collections
.OrderedDict()
131 self
.data
['memory'] = self
.memory
134 return self
.data
.__repr
__()
137 return self
.data
.__str
__()
143 # Read all RAM sections
145 addr
= self
.file.read64()
146 flags
= addr
& (self
.TARGET_PAGE_SIZE
- 1)
147 addr
&= ~
(self
.TARGET_PAGE_SIZE
- 1)
149 if flags
& self
.RAM_SAVE_FLAG_MEM_SIZE
:
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.
157 self
.file.file.seek(-1, 1)
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
:
164 mkdir_p('./' + os
.path
.dirname(self
.name
))
165 f
= open('./' + self
.name
, "wb")
168 self
.files
[self
.name
] = f
169 flags
&= ~self
.RAM_SAVE_FLAG_MEM_SIZE
171 if flags
& self
.RAM_SAVE_FLAG_COMPRESS
:
172 if flags
& self
.RAM_SAVE_FLAG_CONTINUE
:
173 flags
&= ~self
.RAM_SAVE_FLAG_CONTINUE
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
)
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
188 self
.name
= self
.file.readstr()
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)
195 if self
.write_memory
:
196 self
.files
[self
.name
].seek(addr
, os
.SEEK_SET
)
197 self
.files
[self
.name
].write(data
)
199 hexdata
= " ".join("{0:02x}".format(ord(c
)) for c
in data
)
200 self
.memory
['%s (0x%016x)' % (self
.name
, addr
)] = hexdata
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")
209 if flags
& self
.RAM_SAVE_FLAG_EOS
:
213 raise Exception("Unknown RAM flags: %x" % flags
)
216 if self
.write_memory
:
217 for key
in self
.files
:
218 self
.files
[key
].close()
221 class HTABSection(object):
222 HASH_PTE_SIZE_64
= 16
224 def __init__(self
, file, version_id
, device
, section_key
):
226 raise Exception("Unknown HTAB version %d" % version_id
)
229 self
.section_key
= section_key
233 header
= self
.file.read32()
240 # First section, just the hash shift
243 # Read until end marker
245 index
= self
.file.read32()
246 n_valid
= self
.file.read16()
247 n_invalid
= self
.file.read16()
249 if index
== 0 and n_valid
== 0 and n_invalid
== 0:
252 self
.file.readvar(n_valid
* self
.HASH_PTE_SIZE_64
)
258 class ConfigurationSection(object):
259 def __init__(self
, file):
263 name_len
= self
.file.read32()
264 name
= self
.file.readstr(len = name_len
)
266 class VMSDFieldGeneric(object):
267 def __init__(self
, desc
, file):
273 return str(self
.__str
__())
276 return " ".join("{0:02x}".format(c
) for c
in self
.data
)
279 return self
.__str
__()
282 size
= int(self
.desc
['size'])
283 self
.data
= self
.file.readvar(size
)
286 class 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
296 return ('%s (%d)' % ((self
.format
% self
.udata
), self
.data
))
298 return self
.format
% self
.data
301 return self
.__repr
__()
304 return self
.__str
__()
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
313 class VMSDFieldUInt(VMSDFieldInt
):
314 def __init__(self
, desc
, file):
315 super(VMSDFieldUInt
, self
).__init
__(desc
, file)
318 super(VMSDFieldUInt
, self
).read()
319 self
.data
= self
.udata
322 class VMSDFieldIntLE(VMSDFieldInt
):
323 def __init__(self
, desc
, file):
324 super(VMSDFieldIntLE
, self
).__init
__(desc
, file)
325 self
.dtype
= '<i%d' % self
.size
327 class VMSDFieldBool(VMSDFieldGeneric
):
328 def __init__(self
, desc
, file):
329 super(VMSDFieldBool
, self
).__init
__(desc
, file)
332 return self
.data
.__repr
__()
335 return self
.data
.__str
__()
341 super(VMSDFieldBool
, self
).read()
342 if self
.data
[0] == 0:
348 class VMSDFieldStruct(VMSDFieldGeneric
):
349 QEMU_VM_SUBSECTION
= 0x05
351 def __init__(self
, desc
, file):
352 super(VMSDFieldStruct
, self
).__init
__(desc
, file)
353 self
.data
= collections
.OrderedDict()
355 # When we see compressed array elements, unfold them here
357 for field
in self
.desc
['struct']['fields']:
358 if not 'array_len' in field
:
359 new_fields
.append(field
)
361 array_len
= field
.pop('array_len')
363 new_fields
.append(field
)
364 for i
in range(1, array_len
):
369 self
.desc
['struct']['fields'] = new_fields
372 return self
.data
.__repr
__()
375 return self
.data
.__str
__()
378 for field
in self
.desc
['struct']['fields']:
380 reader
= vmsd_field_readers
[field
['type']]
382 reader
= VMSDFieldGeneric
384 field
['data'] = reader(field
, self
.file)
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'])
395 self
.data
[field
['name']] = field
['data']
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()
406 def getDictItem(self
, value
):
407 # Strings would fall into the array category, treat
409 if value
.__class
__ is ''.__class
__:
413 return self
.getDictOrderedDict(value
)
416 return self
.getDictArray(value
)
419 return value
.getDict()
423 def getDictArray(self
, array
):
426 r
.append(self
.getDictItem(value
))
429 def getDictOrderedDict(self
, dict):
430 r
= collections
.OrderedDict()
431 for (key
, value
) in dict.items():
432 r
[key
] = self
.getDictItem(value
)
436 return self
.getDictOrderedDict(self
.data
)
438 vmsd_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
,
463 class VMSDSection(VMSDFieldStruct
):
464 def __init__(self
, file, version_id
, device
, section_key
):
468 self
.section_key
= section_key
470 if 'vmsd_name' in device
:
471 self
.vmsd_name
= device
['vmsd_name']
473 # A section really is nothing but a FieldStruct :)
474 super(VMSDSection
, self
).__init
__({ 'struct' : desc
}, file)
476 ###############################################################################
478 class MigrationDump(object):
479 QEMU_VM_FILE_MAGIC
= 0x5145564d
480 QEMU_VM_FILE_VERSION
= 0x00000003
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
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
497 def read(self
, desc_only
= False, dump_memory
= False, write_memory
= False):
498 # Read in the whole file
499 file = MigrationFile(self
.filename
)
503 if data
!= self
.QEMU_VM_FILE_MAGIC
:
504 raise Exception("Invalid file magic %x" % data
)
506 # Version (has to be v3)
508 if data
!= self
.QEMU_VM_FILE_VERSION
:
509 raise Exception("Invalid version number %d" % data
)
511 self
.load_vmsd_json(file)
514 self
.sections
= collections
.OrderedDict()
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
526 section_type
= file.read8()
527 if section_type
== self
.QEMU_VM_EOF
:
529 elif section_type
== self
.QEMU_VM_CONFIGURATION
:
530 section
= ConfigurationSection(file)
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
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
))
550 raise Exception("Unknown section type: %d" % section_type
)
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
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()
568 ###############################################################################
570 class JSONEncoder(json
.JSONEncoder
):
571 def default(self
, o
):
572 if isinstance(o
, VMSDFieldGeneric
):
574 return json
.JSONEncoder
.default(self
, o
)
576 parser
= argparse
.ArgumentParser()
577 parser
.add_argument("-f", "--file", help='migration dump to read from', required
=True)
578 parser
.add_argument("-m", "--memory", help='dump RAM contents as well', action
='store_true')
579 parser
.add_argument("-d", "--dump", help='what to dump ("state" or "desc")', default
='state')
580 parser
.add_argument("-x", "--extract", help='extract contents into individual files', action
='store_true')
581 args
= parser
.parse_args()
583 jsonenc
= JSONEncoder(indent
=4, separators
=(',', ': '))
586 dump
= MigrationDump(args
.file)
588 dump
.read(desc_only
= True)
590 f
= open("desc.json", "wb")
592 f
.write(jsonenc
.encode(dump
.vmsd_desc
))
595 dump
.read(write_memory
= True)
596 dict = dump
.getDict()
598 f
= open("state.json", "wb")
600 f
.write(jsonenc
.encode(dict))
602 elif args
.dump
== "state":
603 dump
= MigrationDump(args
.file)
604 dump
.read(dump_memory
= args
.memory
)
605 dict = dump
.getDict()
606 print(jsonenc
.encode(dict))
607 elif args
.dump
== "desc":
608 dump
= MigrationDump(args
.file)
609 dump
.read(desc_only
= True)
610 print(jsonenc
.encode(dump
.vmsd_desc
))
612 raise Exception("Please specify either -x, -d state or -d dump")