2
0

analyze-migration.py 20 KB

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