analyze-migration.py 20 KB

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