analyze-migration.py 20 KB

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