device-crash-test 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. #!/usr/bin/env python2.7
  2. #
  3. # Copyright (c) 2017 Red Hat Inc
  4. #
  5. # Author:
  6. # Eduardo Habkost <ehabkost@redhat.com>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 2 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License along
  19. # with this program; if not, write to the Free Software Foundation, Inc.,
  20. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. """
  22. Run QEMU with all combinations of -machine and -device types,
  23. check for crashes and unexpected errors.
  24. """
  25. import sys
  26. import os
  27. import glob
  28. import logging
  29. import traceback
  30. import re
  31. import random
  32. import argparse
  33. from itertools import chain
  34. sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'scripts'))
  35. from qemu import QEMUMachine
  36. logger = logging.getLogger('device-crash-test')
  37. dbg = logger.debug
  38. # Purposes of the following whitelist:
  39. # * Avoiding verbose log messages when we find known non-fatal
  40. # (exitcode=1) errors
  41. # * Avoiding fatal errors when we find known crashes
  42. # * Skipping machines/devices that are known not to work out of
  43. # the box, when running in --quick mode
  44. #
  45. # Keeping the whitelist updated is desirable, but not required,
  46. # because unexpected cases where QEMU exits with exitcode=1 will
  47. # just trigger a INFO message.
  48. # Valid whitelist entry keys:
  49. # * accel: regexp, full match only
  50. # * machine: regexp, full match only
  51. # * device: regexp, full match only
  52. # * log: regexp, partial match allowed
  53. # * exitcode: if not present, defaults to 1. If None, matches any exitcode
  54. # * warn: if True, matching failures will be logged as warnings
  55. # * expected: if True, QEMU is expected to always fail every time
  56. # when testing the corresponding test case
  57. # * loglevel: log level of log output when there's a match.
  58. ERROR_WHITELIST = [
  59. # Machines that won't work out of the box:
  60. # MACHINE | ERROR MESSAGE
  61. {'machine':'niagara', 'expected':True}, # Unable to load a firmware for -M niagara
  62. {'machine':'boston', 'expected':True}, # Please provide either a -kernel or -bios argument
  63. {'machine':'leon3_generic', 'expected':True}, # Can't read bios image (null)
  64. # devices that don't work out of the box because they require extra options to "-device DEV":
  65. # DEVICE | ERROR MESSAGE
  66. {'device':'.*-(i386|x86_64)-cpu', 'expected':True}, # CPU socket-id is not set
  67. {'device':'ARM,bitband-memory', 'expected':True}, # source-memory property not set
  68. {'device':'arm.cortex-a9-global-timer', 'expected':True}, # a9_gtimer_realize: num-cpu must be between 1 and 4
  69. {'device':'arm_mptimer', 'expected':True}, # num-cpu must be between 1 and 4
  70. {'device':'armv7m', 'expected':True}, # memory property was not set
  71. {'device':'aspeed.scu', 'expected':True}, # Unknown silicon revision: 0x0
  72. {'device':'aspeed.sdmc', 'expected':True}, # Unknown silicon revision: 0x0
  73. {'device':'bcm2835-dma', 'expected':True}, # bcm2835_dma_realize: required dma-mr link not found: Property '.dma-mr' not found
  74. {'device':'bcm2835-fb', 'expected':True}, # bcm2835_fb_realize: required vcram-base property not set
  75. {'device':'bcm2835-mbox', 'expected':True}, # bcm2835_mbox_realize: required mbox-mr link not found: Property '.mbox-mr' not found
  76. {'device':'bcm2835-peripherals', 'expected':True}, # bcm2835_peripherals_realize: required ram link not found: Property '.ram' not found
  77. {'device':'bcm2835-property', 'expected':True}, # bcm2835_property_realize: required fb link not found: Property '.fb' not found
  78. {'device':'bcm2835_gpio', 'expected':True}, # bcm2835_gpio_realize: required sdhci link not found: Property '.sdbus-sdhci' not found
  79. {'device':'bcm2836', 'expected':True}, # bcm2836_realize: required ram link not found: Property '.ram' not found
  80. {'device':'cfi.pflash01', 'expected':True}, # attribute "sector-length" not specified or zero.
  81. {'device':'cfi.pflash02', 'expected':True}, # attribute "sector-length" not specified or zero.
  82. {'device':'icp', 'expected':True}, # icp_realize: required link 'xics' not found: Property '.xics' not found
  83. {'device':'ics', 'expected':True}, # ics_base_realize: required link 'xics' not found: Property '.xics' not found
  84. # "-device ide-cd" does work on more recent QEMU versions, so it doesn't have expected=True
  85. {'device':'ide-cd'}, # No drive specified
  86. {'device':'ide-drive', 'expected':True}, # No drive specified
  87. {'device':'ide-hd', 'expected':True}, # No drive specified
  88. {'device':'ipmi-bmc-extern', 'expected':True}, # IPMI external bmc requires chardev attribute
  89. {'device':'isa-debugcon', 'expected':True}, # Can't create serial device, empty char device
  90. {'device':'isa-ipmi-bt', 'expected':True}, # IPMI device requires a bmc attribute to be set
  91. {'device':'isa-ipmi-kcs', 'expected':True}, # IPMI device requires a bmc attribute to be set
  92. {'device':'isa-parallel', 'expected':True}, # Can't create serial device, empty char device
  93. {'device':'isa-serial', 'expected':True}, # Can't create serial device, empty char device
  94. {'device':'ivshmem', 'expected':True}, # You must specify either 'shm' or 'chardev'
  95. {'device':'ivshmem-doorbell', 'expected':True}, # You must specify a 'chardev'
  96. {'device':'ivshmem-plain', 'expected':True}, # You must specify a 'memdev'
  97. {'device':'loader', 'expected':True}, # please include valid arguments
  98. {'device':'nand', 'expected':True}, # Unsupported NAND block size 0x1
  99. {'device':'nvdimm', 'expected':True}, # 'memdev' property is not set
  100. {'device':'nvme', 'expected':True}, # Device initialization failed
  101. {'device':'pc-dimm', 'expected':True}, # 'memdev' property is not set
  102. {'device':'pci-bridge', 'expected':True}, # Bridge chassis not specified. Each bridge is required to be assigned a unique chassis id > 0.
  103. {'device':'pci-bridge-seat', 'expected':True}, # Bridge chassis not specified. Each bridge is required to be assigned a unique chassis id > 0.
  104. {'device':'pci-serial', 'expected':True}, # Can't create serial device, empty char device
  105. {'device':'pci-serial-2x', 'expected':True}, # Can't create serial device, empty char device
  106. {'device':'pci-serial-4x', 'expected':True}, # Can't create serial device, empty char device
  107. {'device':'pxa2xx-dma', 'expected':True}, # channels value invalid
  108. {'device':'pxb', 'expected':True}, # Bridge chassis not specified. Each bridge is required to be assigned a unique chassis id > 0.
  109. {'device':'scsi-block', 'expected':True}, # drive property not set
  110. {'device':'scsi-disk', 'expected':True}, # drive property not set
  111. {'device':'scsi-generic', 'expected':True}, # drive property not set
  112. {'device':'scsi-hd', 'expected':True}, # drive property not set
  113. {'device':'spapr-pci-host-bridge', 'expected':True}, # BUID not specified for PHB
  114. {'device':'spapr-pci-vfio-host-bridge', 'expected':True}, # BUID not specified for PHB
  115. {'device':'spapr-rng', 'expected':True}, # spapr-rng needs an RNG backend!
  116. {'device':'spapr-vty', 'expected':True}, # chardev property not set
  117. {'device':'tpm-tis', 'expected':True}, # tpm_tis: backend driver with id (null) could not be found
  118. {'device':'unimplemented-device', 'expected':True}, # property 'size' not specified or zero
  119. {'device':'usb-braille', 'expected':True}, # Property chardev is required
  120. {'device':'usb-mtp', 'expected':True}, # x-root property must be configured
  121. {'device':'usb-redir', 'expected':True}, # Parameter 'chardev' is missing
  122. {'device':'usb-serial', 'expected':True}, # Property chardev is required
  123. {'device':'usb-storage', 'expected':True}, # drive property not set
  124. {'device':'vfio-amd-xgbe', 'expected':True}, # -device vfio-amd-xgbe: vfio error: wrong host device name
  125. {'device':'vfio-calxeda-xgmac', 'expected':True}, # -device vfio-calxeda-xgmac: vfio error: wrong host device name
  126. {'device':'vfio-pci', 'expected':True}, # No provided host device
  127. {'device':'vfio-pci-igd-lpc-bridge', 'expected':True}, # VFIO dummy ISA/LPC bridge must have address 1f.0
  128. {'device':'vhost-scsi.*', 'expected':True}, # vhost-scsi: missing wwpn
  129. {'device':'vhost-vsock-device', 'expected':True}, # guest-cid property must be greater than 2
  130. {'device':'vhost-vsock-pci', 'expected':True}, # guest-cid property must be greater than 2
  131. {'device':'virtio-9p-ccw', 'expected':True}, # 9pfs device couldn't find fsdev with the id = NULL
  132. {'device':'virtio-9p-device', 'expected':True}, # 9pfs device couldn't find fsdev with the id = NULL
  133. {'device':'virtio-9p-pci', 'expected':True}, # 9pfs device couldn't find fsdev with the id = NULL
  134. {'device':'virtio-blk-ccw', 'expected':True}, # drive property not set
  135. {'device':'virtio-blk-device', 'expected':True}, # drive property not set
  136. {'device':'virtio-blk-device', 'expected':True}, # drive property not set
  137. {'device':'virtio-blk-pci', 'expected':True}, # drive property not set
  138. {'device':'virtio-crypto-ccw', 'expected':True}, # 'cryptodev' parameter expects a valid object
  139. {'device':'virtio-crypto-device', 'expected':True}, # 'cryptodev' parameter expects a valid object
  140. {'device':'virtio-crypto-pci', 'expected':True}, # 'cryptodev' parameter expects a valid object
  141. {'device':'virtio-input-host-device', 'expected':True}, # evdev property is required
  142. {'device':'virtio-input-host-pci', 'expected':True}, # evdev property is required
  143. {'device':'xen-pvdevice', 'expected':True}, # Device ID invalid, it must always be supplied
  144. {'device':'vhost-vsock-ccw', 'expected':True}, # guest-cid property must be greater than 2
  145. {'device':'ALTR.timer', 'expected':True}, # "clock-frequency" property must be provided
  146. {'device':'zpci', 'expected':True}, # target must be defined
  147. {'device':'pnv-(occ|icp|lpc)', 'expected':True}, # required link 'xics' not found: Property '.xics' not found
  148. {'device':'powernv-cpu-.*', 'expected':True}, # pnv_core_realize: required link 'xics' not found: Property '.xics' not found
  149. # ioapic devices are already created by pc and will fail:
  150. {'machine':'q35|pc.*', 'device':'kvm-ioapic', 'expected':True}, # Only 1 ioapics allowed
  151. {'machine':'q35|pc.*', 'device':'ioapic', 'expected':True}, # Only 1 ioapics allowed
  152. # "spapr-cpu-core needs a pseries machine"
  153. {'machine':'(?!pseries).*', 'device':'.*-spapr-cpu-core', 'expected':True},
  154. # KVM-specific devices shouldn't be tried without accel=kvm:
  155. {'accel':'(?!kvm).*', 'device':'kvmclock', 'expected':True},
  156. # xen-specific machines and devices:
  157. {'accel':'(?!xen).*', 'machine':'xen.*', 'expected':True},
  158. {'accel':'(?!xen).*', 'device':'xen-.*', 'expected':True},
  159. # this fails on some machine-types, but not all, so they don't have expected=True:
  160. {'device':'vmgenid'}, # vmgenid requires DMA write support in fw_cfg, which this machine type does not provide
  161. # Silence INFO messages for errors that are common on multiple
  162. # devices/machines:
  163. {'log':r"No '[\w-]+' bus found for device '[\w-]+'"},
  164. {'log':r"images* must be given with the 'pflash' parameter"},
  165. {'log':r"(Guest|ROM|Flash|Kernel) image must be specified"},
  166. {'log':r"[cC]ould not load [\w ]+ (BIOS|bios) '[\w-]+\.bin'"},
  167. {'log':r"Couldn't find rom image '[\w-]+\.bin'"},
  168. {'log':r"speed mismatch trying to attach usb device"},
  169. {'log':r"Can't create a second ISA bus"},
  170. {'log':r"duplicate fw_cfg file name"},
  171. # sysbus-related error messages: most machines reject most dynamic sysbus devices:
  172. {'log':r"Option '-device [\w.,-]+' cannot be handled by this machine"},
  173. {'log':r"Device [\w.,-]+ is not supported by this machine yet"},
  174. {'log':r"Device [\w.,-]+ can not be dynamically instantiated"},
  175. {'log':r"Platform Bus: Can not fit MMIO region of size "},
  176. # other more specific errors we will ignore:
  177. {'device':'.*-spapr-cpu-core', 'log':r"CPU core type should be"},
  178. {'log':r"MSI(-X)? is not supported by interrupt controller"},
  179. {'log':r"pxb-pcie? devices cannot reside on a PCIe? bus"},
  180. {'log':r"Ignoring smp_cpus value"},
  181. {'log':r"sd_init failed: Drive 'sd0' is already in use because it has been automatically connected to another device"},
  182. {'log':r"This CPU requires a smaller page size than the system is using"},
  183. {'log':r"MSI-X support is mandatory in the S390 architecture"},
  184. {'log':r"rom check and register reset failed"},
  185. {'log':r"Unable to initialize GIC, CPUState for CPU#0 not valid"},
  186. {'log':r"Multiple VT220 operator consoles are not supported"},
  187. {'log':r"core 0 already populated"},
  188. {'log':r"could not find stage1 bootloader"},
  189. # other exitcode=1 failures not listed above will just generate INFO messages:
  190. {'exitcode':1, 'loglevel':logging.INFO},
  191. # KNOWN CRASHES:
  192. # Known crashes will generate error messages, but won't be fatal.
  193. # Those entries must be removed once we fix the crashes.
  194. {'exitcode':-6, 'log':r"Device 'serial0' is in use", 'loglevel':logging.ERROR},
  195. {'exitcode':-6, 'log':r"spapr_rtas_register: Assertion .*rtas_table\[token\]\.name.* failed", 'loglevel':logging.ERROR},
  196. {'exitcode':-6, 'log':r"qemu_net_client_setup: Assertion `!peer->peer' failed", 'loglevel':logging.ERROR},
  197. {'exitcode':-6, 'log':r'RAMBlock "[\w.-]+" already registered', 'loglevel':logging.ERROR},
  198. {'exitcode':-6, 'log':r"find_ram_offset: Assertion `size != 0' failed.", 'loglevel':logging.ERROR},
  199. {'exitcode':-6, 'log':r"puv3_load_kernel: Assertion `kernel_filename != NULL' failed", 'loglevel':logging.ERROR},
  200. {'exitcode':-6, 'log':r"add_cpreg_to_hashtable: code should not be reached", 'loglevel':logging.ERROR},
  201. {'exitcode':-6, 'log':r"qemu_alloc_display: Assertion `surface->image != NULL' failed", 'loglevel':logging.ERROR},
  202. {'exitcode':-6, 'log':r"Unexpected error in error_set_from_qdev_prop_error", 'loglevel':logging.ERROR},
  203. {'exitcode':-6, 'log':r"Object .* is not an instance of type spapr-machine", 'loglevel':logging.ERROR},
  204. {'exitcode':-6, 'log':r"Object .* is not an instance of type generic-pc-machine", 'loglevel':logging.ERROR},
  205. {'exitcode':-6, 'log':r"Object .* is not an instance of type e500-ccsr", 'loglevel':logging.ERROR},
  206. {'exitcode':-6, 'log':r"vmstate_register_with_alias_id: Assertion `!se->compat \|\| se->instance_id == 0' failed", 'loglevel':logging.ERROR},
  207. {'exitcode':-11, 'device':'stm32f205-soc', 'loglevel':logging.ERROR, 'expected':True},
  208. {'exitcode':-11, 'device':'xlnx,zynqmp', 'loglevel':logging.ERROR, 'expected':True},
  209. {'exitcode':-11, 'device':'mips-cps', 'loglevel':logging.ERROR, 'expected':True},
  210. {'exitcode':-11, 'device':'gus', 'loglevel':logging.ERROR, 'expected':True},
  211. {'exitcode':-11, 'device':'a9mpcore_priv', 'loglevel':logging.ERROR, 'expected':True},
  212. {'exitcode':-11, 'device':'a15mpcore_priv', 'loglevel':logging.ERROR, 'expected':True},
  213. {'exitcode':-11, 'device':'isa-serial', 'loglevel':logging.ERROR, 'expected':True},
  214. {'exitcode':-11, 'device':'sb16', 'loglevel':logging.ERROR, 'expected':True},
  215. {'exitcode':-11, 'device':'cs4231a', 'loglevel':logging.ERROR, 'expected':True},
  216. {'exitcode':-11, 'device':'arm-gicv3', 'loglevel':logging.ERROR, 'expected':True},
  217. {'exitcode':-11, 'machine':'isapc', 'device':'.*-iommu', 'loglevel':logging.ERROR, 'expected':True},
  218. # everything else (including SIGABRT and SIGSEGV) will be a fatal error:
  219. {'exitcode':None, 'fatal':True, 'loglevel':logging.FATAL},
  220. ]
  221. def whitelistTestCaseMatch(wl, t):
  222. """Check if a test case specification can match a whitelist entry
  223. This only checks if a whitelist entry is a candidate match
  224. for a given test case, it won't check if the test case
  225. results/output match the entry. See whitelistResultMatch().
  226. """
  227. return (('machine' not in wl or
  228. 'machine' not in t or
  229. re.match(wl['machine'] + '$', t['machine'])) and
  230. ('accel' not in wl or
  231. 'accel' not in t or
  232. re.match(wl['accel'] + '$', t['accel'])) and
  233. ('device' not in wl or
  234. 'device' not in t or
  235. re.match(wl['device'] + '$', t['device'])))
  236. def whitelistCandidates(t):
  237. """Generate the list of candidates that can match a test case"""
  238. for i, wl in enumerate(ERROR_WHITELIST):
  239. if whitelistTestCaseMatch(wl, t):
  240. yield (i, wl)
  241. def findExpectedResult(t):
  242. """Check if there's an expected=True whitelist entry for a test case
  243. Returns (i, wl) tuple, where i is the index in
  244. ERROR_WHITELIST and wl is the whitelist entry itself.
  245. """
  246. for i, wl in whitelistCandidates(t):
  247. if wl.get('expected'):
  248. return (i, wl)
  249. def whitelistResultMatch(wl, r):
  250. """Check if test case results/output match a whitelist entry
  251. It is valid to call this function only if
  252. whitelistTestCaseMatch() is True for the entry (e.g. on
  253. entries returned by whitelistCandidates())
  254. """
  255. assert whitelistTestCaseMatch(wl, r['testcase'])
  256. return ((wl.get('exitcode', 1) is None or
  257. r['exitcode'] == wl.get('exitcode', 1)) and
  258. ('log' not in wl or
  259. re.search(wl['log'], r['log'], re.MULTILINE)))
  260. def checkResultWhitelist(r):
  261. """Look up whitelist entry for a given test case result
  262. Returns (i, wl) tuple, where i is the index in
  263. ERROR_WHITELIST and wl is the whitelist entry itself.
  264. """
  265. for i, wl in whitelistCandidates(r['testcase']):
  266. if whitelistResultMatch(wl, r):
  267. return i, wl
  268. raise Exception("this should never happen")
  269. def qemuOptsEscape(s):
  270. """Escape option value QemuOpts"""
  271. return s.replace(",", ",,")
  272. def formatTestCase(t):
  273. """Format test case info as "key=value key=value" for prettier logging output"""
  274. return ' '.join('%s=%s' % (k, v) for k, v in t.items())
  275. def qomListTypeNames(vm, **kwargs):
  276. """Run qom-list-types QMP command, return type names"""
  277. types = vm.command('qom-list-types', **kwargs)
  278. return [t['name'] for t in types]
  279. def infoQDM(vm):
  280. """Parse 'info qdm' output"""
  281. args = {'command-line': 'info qdm'}
  282. devhelp = vm.command('human-monitor-command', **args)
  283. for l in devhelp.split('\n'):
  284. l = l.strip()
  285. if l == '' or l.endswith(':'):
  286. continue
  287. d = {'name': re.search(r'name "([^"]+)"', l).group(1),
  288. 'no-user': (re.search(', no-user', l) is not None)}
  289. yield d
  290. class QemuBinaryInfo(object):
  291. def __init__(self, binary, devtype):
  292. if devtype is None:
  293. devtype = 'device'
  294. self.binary = binary
  295. self._machine_info = {}
  296. dbg("devtype: %r", devtype)
  297. args = ['-S', '-machine', 'none,accel=kvm:tcg']
  298. dbg("querying info for QEMU binary: %s", binary)
  299. vm = QEMUMachine(binary=binary, args=args)
  300. vm.launch()
  301. try:
  302. self.alldevs = set(qomListTypeNames(vm, implements=devtype, abstract=False))
  303. # there's no way to query DeviceClass::user_creatable using QMP,
  304. # so use 'info qdm':
  305. self.no_user_devs = set([d['name'] for d in infoQDM(vm, ) if d['no-user']])
  306. self.machines = list(m['name'] for m in vm.command('query-machines'))
  307. self.user_devs = self.alldevs.difference(self.no_user_devs)
  308. self.kvm_available = vm.command('query-kvm')['enabled']
  309. finally:
  310. vm.shutdown()
  311. def machineInfo(self, machine):
  312. """Query for information on a specific machine-type
  313. Results are cached internally, in case the same machine-
  314. type is queried multiple times.
  315. """
  316. if machine in self._machine_info:
  317. return self._machine_info[machine]
  318. mi = {}
  319. args = ['-S', '-machine', '%s' % (machine)]
  320. dbg("querying machine info for binary=%s machine=%s", self.binary, machine)
  321. vm = QEMUMachine(binary=self.binary, args=args)
  322. try:
  323. vm.launch()
  324. mi['runnable'] = True
  325. except KeyboardInterrupt:
  326. raise
  327. except:
  328. dbg("exception trying to run binary=%s machine=%s", self.binary, machine, exc_info=sys.exc_info())
  329. dbg("log: %r", vm.get_log())
  330. mi['runnable'] = False
  331. vm.shutdown()
  332. self._machine_info[machine] = mi
  333. return mi
  334. BINARY_INFO = {}
  335. def getBinaryInfo(args, binary):
  336. if binary not in BINARY_INFO:
  337. BINARY_INFO[binary] = QemuBinaryInfo(binary, args.devtype)
  338. return BINARY_INFO[binary]
  339. def checkOneCase(args, testcase):
  340. """Check one specific case
  341. Returns a dictionary containing failure information on error,
  342. or None on success
  343. """
  344. binary = testcase['binary']
  345. accel = testcase['accel']
  346. machine = testcase['machine']
  347. device = testcase['device']
  348. dbg("will test: %r", testcase)
  349. args = ['-S', '-machine', '%s,accel=%s' % (machine, accel),
  350. '-device', qemuOptsEscape(device)]
  351. cmdline = ' '.join([binary] + args)
  352. dbg("will launch QEMU: %s", cmdline)
  353. vm = QEMUMachine(binary=binary, args=args)
  354. exc_traceback = None
  355. try:
  356. vm.launch()
  357. except KeyboardInterrupt:
  358. raise
  359. except:
  360. exc_traceback = traceback.format_exc()
  361. dbg("Exception while running test case")
  362. finally:
  363. vm.shutdown()
  364. ec = vm.exitcode()
  365. log = vm.get_log()
  366. if exc_traceback is not None or ec != 0:
  367. return {'exc_traceback':exc_traceback,
  368. 'exitcode':ec,
  369. 'log':log,
  370. 'testcase':testcase,
  371. 'cmdline':cmdline}
  372. def binariesToTest(args, testcase):
  373. if args.qemu:
  374. r = args.qemu
  375. else:
  376. r = glob.glob('./*-softmmu/qemu-system-*')
  377. return r
  378. def accelsToTest(args, testcase):
  379. if getBinaryInfo(args, testcase['binary']).kvm_available:
  380. yield 'kvm'
  381. yield 'tcg'
  382. def machinesToTest(args, testcase):
  383. return getBinaryInfo(args, testcase['binary']).machines
  384. def devicesToTest(args, testcase):
  385. return getBinaryInfo(args, testcase['binary']).user_devs
  386. TESTCASE_VARIABLES = [
  387. ('binary', binariesToTest),
  388. ('accel', accelsToTest),
  389. ('machine', machinesToTest),
  390. ('device', devicesToTest),
  391. ]
  392. def genCases1(args, testcases, var, fn):
  393. """Generate new testcases for one variable
  394. If an existing item already has a variable set, don't
  395. generate new items and just return it directly. This
  396. allows the "-t" command-line option to be used to choose
  397. a specific test case.
  398. """
  399. for testcase in testcases:
  400. if var in testcase:
  401. yield testcase.copy()
  402. else:
  403. for i in fn(args, testcase):
  404. t = testcase.copy()
  405. t[var] = i
  406. yield t
  407. def genCases(args, testcase):
  408. """Generate test cases for all variables
  409. """
  410. cases = [testcase.copy()]
  411. for var, fn in TESTCASE_VARIABLES:
  412. dbg("var: %r, fn: %r", var, fn)
  413. cases = genCases1(args, cases, var, fn)
  414. return cases
  415. def casesToTest(args, testcase):
  416. cases = genCases(args, testcase)
  417. if args.random:
  418. cases = list(cases)
  419. cases = random.sample(cases, min(args.random, len(cases)))
  420. if args.debug:
  421. cases = list(cases)
  422. dbg("%d test cases to test", len(cases))
  423. if args.shuffle:
  424. cases = list(cases)
  425. random.shuffle(cases)
  426. return cases
  427. def logFailure(f, level):
  428. t = f['testcase']
  429. logger.log(level, "failed: %s", formatTestCase(t))
  430. logger.log(level, "cmdline: %s", f['cmdline'])
  431. for l in f['log'].strip().split('\n'):
  432. logger.log(level, "log: %s", l)
  433. logger.log(level, "exit code: %r", f['exitcode'])
  434. if f['exc_traceback']:
  435. logger.log(level, "exception:")
  436. for l in f['exc_traceback'].split('\n'):
  437. logger.log(level, " %s", l.rstrip('\n'))
  438. def main():
  439. parser = argparse.ArgumentParser(description="QEMU -device crash test")
  440. parser.add_argument('-t', metavar='KEY=VALUE', nargs='*',
  441. help="Limit test cases to KEY=VALUE",
  442. action='append', dest='testcases', default=[])
  443. parser.add_argument('-d', '--debug', action='store_true',
  444. help='debug output')
  445. parser.add_argument('-v', '--verbose', action='store_true', default=True,
  446. help='verbose output')
  447. parser.add_argument('-q', '--quiet', dest='verbose', action='store_false',
  448. help='non-verbose output')
  449. parser.add_argument('-r', '--random', type=int, metavar='COUNT',
  450. help='run a random sample of COUNT test cases',
  451. default=0)
  452. parser.add_argument('--shuffle', action='store_true',
  453. help='Run test cases in random order')
  454. parser.add_argument('--dry-run', action='store_true',
  455. help="Don't run any tests, just generate list")
  456. parser.add_argument('-D', '--devtype', metavar='TYPE',
  457. help="Test only device types that implement TYPE")
  458. parser.add_argument('-Q', '--quick', action='store_true', default=True,
  459. help="Quick mode: skip test cases that are expected to fail")
  460. parser.add_argument('-F', '--full', action='store_false', dest='quick',
  461. help="Full mode: test cases that are expected to fail")
  462. parser.add_argument('--strict', action='store_true', dest='strict',
  463. help="Treat all warnings as fatal")
  464. parser.add_argument('qemu', nargs='*', metavar='QEMU',
  465. help='QEMU binary to run')
  466. args = parser.parse_args()
  467. if args.debug:
  468. lvl = logging.DEBUG
  469. elif args.verbose:
  470. lvl = logging.INFO
  471. else:
  472. lvl = logging.WARN
  473. logging.basicConfig(stream=sys.stdout, level=lvl, format='%(levelname)s: %(message)s')
  474. fatal_failures = []
  475. wl_stats = {}
  476. skipped = 0
  477. total = 0
  478. tc = {}
  479. dbg("testcases: %r", args.testcases)
  480. if args.testcases:
  481. for t in chain(*args.testcases):
  482. for kv in t.split():
  483. k, v = kv.split('=', 1)
  484. tc[k] = v
  485. if len(binariesToTest(args, tc)) == 0:
  486. print >>sys.stderr, "No QEMU binary found"
  487. parser.print_usage(sys.stderr)
  488. return 1
  489. for t in casesToTest(args, tc):
  490. logger.info("running test case: %s", formatTestCase(t))
  491. total += 1
  492. expected_match = findExpectedResult(t)
  493. if (args.quick and
  494. (expected_match or
  495. not getBinaryInfo(args, t['binary']).machineInfo(t['machine'])['runnable'])):
  496. dbg("skipped: %s", formatTestCase(t))
  497. skipped += 1
  498. continue
  499. if args.dry_run:
  500. continue
  501. try:
  502. f = checkOneCase(args, t)
  503. except KeyboardInterrupt:
  504. break
  505. if f:
  506. i, wl = checkResultWhitelist(f)
  507. dbg("testcase: %r, whitelist match: %r", t, wl)
  508. wl_stats.setdefault(i, []).append(f)
  509. level = wl.get('loglevel', logging.DEBUG)
  510. logFailure(f, level)
  511. if wl.get('fatal') or (args.strict and level >= logging.WARN):
  512. fatal_failures.append(f)
  513. else:
  514. dbg("success: %s", formatTestCase(t))
  515. if expected_match:
  516. logger.warn("Didn't fail as expected: %s", formatTestCase(t))
  517. logger.info("Total: %d test cases", total)
  518. if skipped:
  519. logger.info("Skipped %d test cases", skipped)
  520. if args.debug:
  521. stats = sorted([(len(wl_stats.get(i, [])), wl) for i, wl in enumerate(ERROR_WHITELIST)])
  522. for count, wl in stats:
  523. dbg("whitelist entry stats: %d: %r", count, wl)
  524. if fatal_failures:
  525. for f in fatal_failures:
  526. t = f['testcase']
  527. logger.error("Fatal failure: %s", formatTestCase(t))
  528. logger.error("Fatal failures on some machine/device combinations")
  529. return 1
  530. if __name__ == '__main__':
  531. sys.exit(main())