runqemu 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489
  1. #!/usr/bin/env python3
  2. # Handle running OE images standalone with QEMU
  3. #
  4. # Copyright (C) 2006-2011 Linux Foundation
  5. # Copyright (c) 2016 Wind River Systems, Inc.
  6. #
  7. # SPDX-License-Identifier: GPL-2.0-only
  8. #
  9. import os
  10. import sys
  11. import logging
  12. import subprocess
  13. import re
  14. import fcntl
  15. import shutil
  16. import glob
  17. import configparser
  18. import signal
  19. class RunQemuError(Exception):
  20. """Custom exception to raise on known errors."""
  21. pass
  22. class OEPathError(RunQemuError):
  23. """Custom Exception to give better guidance on missing binaries"""
  24. def __init__(self, message):
  25. super().__init__("In order for this script to dynamically infer paths\n \
  26. kernels or filesystem images, you either need bitbake in your PATH\n \
  27. or to source oe-init-build-env before running this script.\n\n \
  28. Dynamic path inference can be avoided by passing a *.qemuboot.conf to\n \
  29. runqemu, i.e. `runqemu /path/to/my-image-name.qemuboot.conf`\n\n %s" % message)
  30. def create_logger():
  31. logger = logging.getLogger('runqemu')
  32. logger.setLevel(logging.INFO)
  33. # create console handler and set level to debug
  34. ch = logging.StreamHandler()
  35. ch.setLevel(logging.DEBUG)
  36. # create formatter
  37. formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
  38. # add formatter to ch
  39. ch.setFormatter(formatter)
  40. # add ch to logger
  41. logger.addHandler(ch)
  42. return logger
  43. logger = create_logger()
  44. def print_usage():
  45. print("""
  46. Usage: you can run this script with any valid combination
  47. of the following environment variables (in any order):
  48. KERNEL - the kernel image file to use
  49. BIOS - the bios image file to use
  50. ROOTFS - the rootfs image file or nfsroot directory to use
  51. DEVICE_TREE - the device tree blob to use
  52. MACHINE - the machine name (optional, autodetected from KERNEL filename if unspecified)
  53. Simplified QEMU command-line options can be passed with:
  54. nographic - disable video console
  55. sdl - choose the SDL UI frontend
  56. gtk - choose the Gtk UI frontend
  57. gl - enable virgl-based GL acceleration (also needs gtk option)
  58. gl-es - enable virgl-based GL acceleration, using OpenGL ES (also needs gtk option)
  59. egl-headless - enable headless EGL output; use vnc or spice to see it
  60. serial - enable a serial console on /dev/ttyS0
  61. serialstdio - enable a serial console on the console (regardless of graphics mode)
  62. slirp - enable user networking, no root privileges is required
  63. snapshot - don't write changes to back to images
  64. kvm - enable KVM when running x86/x86_64 (VT-capable CPU required)
  65. kvm-vhost - enable KVM with vhost when running x86/x86_64 (VT-capable CPU required)
  66. publicvnc - enable a VNC server open to all hosts
  67. audio - enable audio
  68. [*/]ovmf* - OVMF firmware file or base name for booting with UEFI
  69. tcpserial=<port> - specify tcp serial port number
  70. qemuparams=<xyz> - specify custom parameters to QEMU
  71. bootparams=<xyz> - specify custom kernel parameters during boot
  72. help, -h, --help: print this text
  73. -d, --debug: Enable debug output
  74. -q, --quiet: Hide most output except error messages
  75. Examples:
  76. runqemu
  77. runqemu qemuarm
  78. runqemu tmp/deploy/images/qemuarm
  79. runqemu tmp/deploy/images/qemux86/<qemuboot.conf>
  80. runqemu qemux86-64 core-image-sato ext4
  81. runqemu qemux86-64 wic-image-minimal wic
  82. runqemu path/to/bzImage-qemux86.bin path/to/nfsrootdir/ serial
  83. runqemu qemux86 iso/hddimg/wic.vmdk/wic.qcow2/wic.vdi/ramfs/cpio.gz...
  84. runqemu qemux86 qemuparams="-m 256"
  85. runqemu qemux86 bootparams="psplash=false"
  86. runqemu path/to/<image>-<machine>.wic
  87. runqemu path/to/<image>-<machine>.wic.vmdk
  88. """)
  89. def check_tun():
  90. """Check /dev/net/tun"""
  91. dev_tun = '/dev/net/tun'
  92. if not os.path.exists(dev_tun):
  93. raise RunQemuError("TUN control device %s is unavailable; you may need to enable TUN (e.g. sudo modprobe tun)" % dev_tun)
  94. if not os.access(dev_tun, os.W_OK):
  95. raise RunQemuError("TUN control device %s is not writable, please fix (e.g. sudo chmod 666 %s)" % (dev_tun, dev_tun))
  96. def get_first_file(cmds):
  97. """Return first file found in wildcard cmds"""
  98. for cmd in cmds:
  99. all_files = glob.glob(cmd)
  100. if all_files:
  101. for f in all_files:
  102. if not os.path.isdir(f):
  103. return f
  104. return ''
  105. class BaseConfig(object):
  106. def __init__(self):
  107. # The self.d saved vars from self.set(), part of them are from qemuboot.conf
  108. self.d = {'QB_KERNEL_ROOT': '/dev/vda'}
  109. # Supported env vars, add it here if a var can be got from env,
  110. # and don't use os.getenv in the code.
  111. self.env_vars = ('MACHINE',
  112. 'ROOTFS',
  113. 'KERNEL',
  114. 'BIOS',
  115. 'DEVICE_TREE',
  116. 'DEPLOY_DIR_IMAGE',
  117. 'OE_TMPDIR',
  118. 'OECORE_NATIVE_SYSROOT',
  119. )
  120. self.qemu_opt = ''
  121. self.qemu_opt_script = ''
  122. self.qemuparams = ''
  123. self.clean_nfs_dir = False
  124. self.nfs_server = ''
  125. self.rootfs = ''
  126. # File name(s) of a OVMF firmware file or variable store,
  127. # to be added with -drive if=pflash.
  128. # Found in the same places as the rootfs, with or without one of
  129. # these suffices: qcow2, bin.
  130. self.ovmf_bios = []
  131. # When enrolling default Secure Boot keys, the hypervisor
  132. # must provide the Platform Key and the first Key Exchange Key
  133. # certificate in the Type 11 SMBIOS table.
  134. self.ovmf_secboot_pkkek1 = ''
  135. self.qemuboot = ''
  136. self.qbconfload = False
  137. self.kernel = ''
  138. self.bios = ''
  139. self.kernel_cmdline = ''
  140. self.kernel_cmdline_script = ''
  141. self.bootparams = ''
  142. self.dtb = ''
  143. self.fstype = ''
  144. self.kvm_enabled = False
  145. self.vhost_enabled = False
  146. self.slirp_enabled = False
  147. self.nfs_instance = 0
  148. self.nfs_running = False
  149. self.serialconsole = False
  150. self.serialstdio = False
  151. self.cleantap = False
  152. self.saved_stty = ''
  153. self.audio_enabled = False
  154. self.tcpserial_portnum = ''
  155. self.taplock = ''
  156. self.taplock_descriptor = None
  157. self.portlocks = {}
  158. self.bitbake_e = ''
  159. self.snapshot = False
  160. self.wictypes = ('wic', 'wic.vmdk', 'wic.qcow2', 'wic.vdi')
  161. self.fstypes = ('ext2', 'ext3', 'ext4', 'jffs2', 'nfs', 'btrfs',
  162. 'cpio.gz', 'cpio', 'ramfs', 'tar.bz2', 'tar.gz')
  163. self.vmtypes = ('hddimg', 'iso')
  164. self.fsinfo = {}
  165. self.network_device = "-device e1000,netdev=net0,mac=@MAC@"
  166. # Use different mac section for tap and slirp to avoid
  167. # conflicts, e.g., when one is running with tap, the other is
  168. # running with slirp.
  169. # The last section is dynamic, which is for avoiding conflicts,
  170. # when multiple qemus are running, e.g., when multiple tap or
  171. # slirp qemus are running.
  172. self.mac_tap = "52:54:00:12:34:"
  173. self.mac_slirp = "52:54:00:12:35:"
  174. # pid of the actual qemu process
  175. self.qemupid = None
  176. # avoid cleanup twice
  177. self.cleaned = False
  178. def acquire_taplock(self, error=True):
  179. logger.debug("Acquiring lockfile %s..." % self.taplock)
  180. try:
  181. self.taplock_descriptor = open(self.taplock, 'w')
  182. fcntl.flock(self.taplock_descriptor, fcntl.LOCK_EX|fcntl.LOCK_NB)
  183. except Exception as e:
  184. msg = "Acquiring lockfile %s failed: %s" % (self.taplock, e)
  185. if error:
  186. logger.error(msg)
  187. else:
  188. logger.info(msg)
  189. if self.taplock_descriptor:
  190. self.taplock_descriptor.close()
  191. self.taplock_descriptor = None
  192. return False
  193. return True
  194. def release_taplock(self):
  195. if self.taplock_descriptor:
  196. logger.debug("Releasing lockfile for tap device '%s'" % self.tap)
  197. fcntl.flock(self.taplock_descriptor, fcntl.LOCK_UN)
  198. self.taplock_descriptor.close()
  199. os.remove(self.taplock)
  200. self.taplock_descriptor = None
  201. def check_free_port(self, host, port, lockdir):
  202. """ Check whether the port is free or not """
  203. import socket
  204. from contextlib import closing
  205. lockfile = os.path.join(lockdir, str(port) + '.lock')
  206. if self.acquire_portlock(lockfile):
  207. with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
  208. if sock.connect_ex((host, port)) == 0:
  209. # Port is open, so not free
  210. self.release_portlock(lockfile)
  211. return False
  212. else:
  213. # Port is not open, so free
  214. return True
  215. else:
  216. return False
  217. def acquire_portlock(self, lockfile):
  218. logger.debug("Acquiring lockfile %s..." % lockfile)
  219. try:
  220. portlock_descriptor = open(lockfile, 'w')
  221. self.portlocks.update({lockfile: portlock_descriptor})
  222. fcntl.flock(self.portlocks[lockfile], fcntl.LOCK_EX|fcntl.LOCK_NB)
  223. except Exception as e:
  224. msg = "Acquiring lockfile %s failed: %s" % (lockfile, e)
  225. logger.info(msg)
  226. if lockfile in self.portlocks.keys() and self.portlocks[lockfile]:
  227. self.portlocks[lockfile].close()
  228. del self.portlocks[lockfile]
  229. return False
  230. return True
  231. def release_portlock(self, lockfile=None):
  232. if lockfile != None:
  233. logger.debug("Releasing lockfile '%s'" % lockfile)
  234. fcntl.flock(self.portlocks[lockfile], fcntl.LOCK_UN)
  235. self.portlocks[lockfile].close()
  236. os.remove(lockfile)
  237. del self.portlocks[lockfile]
  238. elif len(self.portlocks):
  239. for lockfile, descriptor in self.portlocks.items():
  240. logger.debug("Releasing lockfile '%s'" % lockfile)
  241. fcntl.flock(descriptor, fcntl.LOCK_UN)
  242. descriptor.close()
  243. os.remove(lockfile)
  244. self.portlocks = {}
  245. def get(self, key):
  246. if key in self.d:
  247. return self.d.get(key)
  248. elif os.getenv(key):
  249. return os.getenv(key)
  250. else:
  251. return ''
  252. def set(self, key, value):
  253. self.d[key] = value
  254. def is_deploy_dir_image(self, p):
  255. if os.path.isdir(p):
  256. if not re.search('.qemuboot.conf$', '\n'.join(os.listdir(p)), re.M):
  257. logger.debug("Can't find required *.qemuboot.conf in %s" % p)
  258. return False
  259. if not any(map(lambda name: '-image-' in name, os.listdir(p))):
  260. logger.debug("Can't find *-image-* in %s" % p)
  261. return False
  262. return True
  263. else:
  264. return False
  265. def check_arg_fstype(self, fst):
  266. """Check and set FSTYPE"""
  267. if fst not in self.fstypes + self.vmtypes + self.wictypes:
  268. logger.warning("Maybe unsupported FSTYPE: %s" % fst)
  269. if not self.fstype or self.fstype == fst:
  270. if fst == 'ramfs':
  271. fst = 'cpio.gz'
  272. if fst in ('tar.bz2', 'tar.gz'):
  273. fst = 'nfs'
  274. self.fstype = fst
  275. else:
  276. raise RunQemuError("Conflicting: FSTYPE %s and %s" % (self.fstype, fst))
  277. def set_machine_deploy_dir(self, machine, deploy_dir_image):
  278. """Set MACHINE and DEPLOY_DIR_IMAGE"""
  279. logger.debug('MACHINE: %s' % machine)
  280. self.set("MACHINE", machine)
  281. logger.debug('DEPLOY_DIR_IMAGE: %s' % deploy_dir_image)
  282. self.set("DEPLOY_DIR_IMAGE", deploy_dir_image)
  283. def check_arg_nfs(self, p):
  284. if os.path.isdir(p):
  285. self.rootfs = p
  286. else:
  287. m = re.match('(.*):(.*)', p)
  288. self.nfs_server = m.group(1)
  289. self.rootfs = m.group(2)
  290. self.check_arg_fstype('nfs')
  291. def check_arg_path(self, p):
  292. """
  293. - Check whether it is <image>.qemuboot.conf or contains <image>.qemuboot.conf
  294. - Check whether is a kernel file
  295. - Check whether is a image file
  296. - Check whether it is a nfs dir
  297. - Check whether it is a OVMF flash file
  298. """
  299. if p.endswith('.qemuboot.conf'):
  300. self.qemuboot = p
  301. self.qbconfload = True
  302. elif re.search('\.bin$', p) or re.search('bzImage', p) or \
  303. re.search('zImage', p) or re.search('vmlinux', p) or \
  304. re.search('fitImage', p) or re.search('uImage', p):
  305. self.kernel = p
  306. elif os.path.exists(p) and (not os.path.isdir(p)) and '-image-' in os.path.basename(p):
  307. self.rootfs = p
  308. # Check filename against self.fstypes can hanlde <file>.cpio.gz,
  309. # otherwise, its type would be "gz", which is incorrect.
  310. fst = ""
  311. for t in self.fstypes:
  312. if p.endswith(t):
  313. fst = t
  314. break
  315. if not fst:
  316. m = re.search('.*\.(.*)$', self.rootfs)
  317. if m:
  318. fst = m.group(1)
  319. if fst:
  320. self.check_arg_fstype(fst)
  321. qb = re.sub('\.' + fst + "$", '', self.rootfs)
  322. qb = '%s%s' % (re.sub('\.rootfs$', '', qb), '.qemuboot.conf')
  323. if os.path.exists(qb):
  324. self.qemuboot = qb
  325. self.qbconfload = True
  326. else:
  327. logger.warning("%s doesn't exist" % qb)
  328. else:
  329. raise RunQemuError("Can't find FSTYPE from: %s" % p)
  330. elif os.path.isdir(p) or re.search(':', p) and re.search('/', p):
  331. if self.is_deploy_dir_image(p):
  332. logger.debug('DEPLOY_DIR_IMAGE: %s' % p)
  333. self.set("DEPLOY_DIR_IMAGE", p)
  334. else:
  335. logger.debug("Assuming %s is an nfs rootfs" % p)
  336. self.check_arg_nfs(p)
  337. elif os.path.basename(p).startswith('ovmf'):
  338. self.ovmf_bios.append(p)
  339. else:
  340. raise RunQemuError("Unknown path arg %s" % p)
  341. def check_arg_machine(self, arg):
  342. """Check whether it is a machine"""
  343. if self.get('MACHINE') == arg:
  344. return
  345. elif self.get('MACHINE') and self.get('MACHINE') != arg:
  346. raise RunQemuError("Maybe conflicted MACHINE: %s vs %s" % (self.get('MACHINE'), arg))
  347. elif re.search('/', arg):
  348. raise RunQemuError("Unknown arg: %s" % arg)
  349. logger.debug('Assuming MACHINE = %s' % arg)
  350. # if we're running under testimage, or similarly as a child
  351. # of an existing bitbake invocation, we can't invoke bitbake
  352. # to validate the MACHINE setting and must assume it's correct...
  353. # FIXME: testimage.bbclass exports these two variables into env,
  354. # are there other scenarios in which we need to support being
  355. # invoked by bitbake?
  356. deploy = self.get('DEPLOY_DIR_IMAGE')
  357. bbchild = deploy and self.get('OE_TMPDIR')
  358. if bbchild:
  359. self.set_machine_deploy_dir(arg, deploy)
  360. return
  361. # also check whether we're running under a sourced toolchain
  362. # environment file
  363. if self.get('OECORE_NATIVE_SYSROOT'):
  364. self.set("MACHINE", arg)
  365. return
  366. cmd = 'MACHINE=%s bitbake -e' % arg
  367. logger.info('Running %s...' % cmd)
  368. self.bitbake_e = subprocess.check_output(cmd, shell=True).decode('utf-8')
  369. # bitbake -e doesn't report invalid MACHINE as an error, so
  370. # let's check DEPLOY_DIR_IMAGE to make sure that it is a valid
  371. # MACHINE.
  372. s = re.search('^DEPLOY_DIR_IMAGE="(.*)"', self.bitbake_e, re.M)
  373. if s:
  374. deploy_dir_image = s.group(1)
  375. else:
  376. raise RunQemuError("bitbake -e %s" % self.bitbake_e)
  377. if self.is_deploy_dir_image(deploy_dir_image):
  378. self.set_machine_deploy_dir(arg, deploy_dir_image)
  379. else:
  380. logger.error("%s not a directory valid DEPLOY_DIR_IMAGE" % deploy_dir_image)
  381. self.set("MACHINE", arg)
  382. def check_args(self):
  383. for debug in ("-d", "--debug"):
  384. if debug in sys.argv:
  385. logger.setLevel(logging.DEBUG)
  386. sys.argv.remove(debug)
  387. for quiet in ("-q", "--quiet"):
  388. if quiet in sys.argv:
  389. logger.setLevel(logging.ERROR)
  390. sys.argv.remove(quiet)
  391. unknown_arg = ""
  392. for arg in sys.argv[1:]:
  393. if arg in self.fstypes + self.vmtypes + self.wictypes:
  394. self.check_arg_fstype(arg)
  395. elif arg == 'nographic':
  396. self.qemu_opt_script += ' -nographic'
  397. self.kernel_cmdline_script += ' console=ttyS0'
  398. elif arg == 'sdl':
  399. self.qemu_opt_script += ' -display sdl'
  400. elif arg == 'gtk':
  401. if 'gl' in sys.argv[1:]:
  402. self.qemu_opt_script += ' -vga virtio -display gtk,gl=on'
  403. elif 'gl-es' in sys.argv[1:]:
  404. self.qemu_opt_script += ' -vga virtio -display gtk,gl=es'
  405. else:
  406. self.qemu_opt_script += ' -display gtk'
  407. elif arg == 'gl' or arg == 'gl-es':
  408. # These args are handled inside sdl or gtk blocks above
  409. pass
  410. elif arg == 'egl-headless':
  411. self.qemu_opt_script += ' -vga virtio -display egl-headless'
  412. # As runqemu can be run within bitbake (when using testimage, for example),
  413. # we need to ensure that we run host pkg-config, and that it does not
  414. # get mis-directed to native build paths set by bitbake.
  415. try:
  416. del os.environ['PKG_CONFIG_PATH']
  417. del os.environ['PKG_CONFIG_DIR']
  418. del os.environ['PKG_CONFIG_LIBDIR']
  419. del os.environ['PKG_CONFIG_SYSROOT_DIR']
  420. except KeyError:
  421. pass
  422. try:
  423. dripath = subprocess.check_output("PATH=/bin:/usr/bin:$PATH pkg-config --variable=dridriverdir dri", shell=True)
  424. except subprocess.CalledProcessError as e:
  425. raise RunQemuError("Could not determine the path to dri drivers on the host via pkg-config.\nPlease install Mesa development files (particularly, dri.pc) on the host machine.")
  426. os.environ['LIBGL_DRIVERS_PATH'] = dripath.decode('utf-8').strip()
  427. elif arg == 'serial':
  428. self.kernel_cmdline_script += ' console=ttyS0'
  429. self.serialconsole = True
  430. elif arg == "serialstdio":
  431. self.kernel_cmdline_script += ' console=ttyS0'
  432. self.serialstdio = True
  433. elif arg == 'audio':
  434. logger.info("Enabling audio in qemu")
  435. logger.info("Please install sound drivers in linux host")
  436. self.audio_enabled = True
  437. elif arg == 'kvm':
  438. self.kvm_enabled = True
  439. elif arg == 'kvm-vhost':
  440. self.vhost_enabled = True
  441. elif arg == 'slirp':
  442. self.slirp_enabled = True
  443. elif arg == 'snapshot':
  444. self.snapshot = True
  445. elif arg == 'publicvnc':
  446. self.qemu_opt_script += ' -vnc :0'
  447. elif arg.startswith('tcpserial='):
  448. self.tcpserial_portnum = '%s' % arg[len('tcpserial='):]
  449. elif arg.startswith('qemuparams='):
  450. self.qemuparams = ' %s' % arg[len('qemuparams='):]
  451. elif arg.startswith('bootparams='):
  452. self.bootparams = arg[len('bootparams='):]
  453. elif os.path.exists(arg) or (re.search(':', arg) and re.search('/', arg)):
  454. self.check_arg_path(os.path.abspath(arg))
  455. elif re.search(r'-image-|-image$', arg):
  456. # Lazy rootfs
  457. self.rootfs = arg
  458. elif arg.startswith('ovmf'):
  459. self.ovmf_bios.append(arg)
  460. else:
  461. # At last, assume it is the MACHINE
  462. if (not unknown_arg) or unknown_arg == arg:
  463. unknown_arg = arg
  464. else:
  465. raise RunQemuError("Can't handle two unknown args: %s %s\n"
  466. "Try 'runqemu help' on how to use it" % \
  467. (unknown_arg, arg))
  468. # Check to make sure it is a valid machine
  469. if unknown_arg and self.get('MACHINE') != unknown_arg:
  470. if self.get('DEPLOY_DIR_IMAGE'):
  471. machine = os.path.basename(self.get('DEPLOY_DIR_IMAGE'))
  472. if unknown_arg == machine:
  473. self.set("MACHINE", machine)
  474. self.check_arg_machine(unknown_arg)
  475. if not (self.get('DEPLOY_DIR_IMAGE') or self.qbconfload):
  476. self.load_bitbake_env()
  477. s = re.search('^DEPLOY_DIR_IMAGE="(.*)"', self.bitbake_e, re.M)
  478. if s:
  479. self.set("DEPLOY_DIR_IMAGE", s.group(1))
  480. def check_kvm(self):
  481. """Check kvm and kvm-host"""
  482. if not (self.kvm_enabled or self.vhost_enabled):
  483. self.qemu_opt_script += ' %s %s' % (self.get('QB_MACHINE'), self.get('QB_CPU'))
  484. return
  485. if not self.get('QB_CPU_KVM'):
  486. raise RunQemuError("QB_CPU_KVM is NULL, this board doesn't support kvm")
  487. self.qemu_opt_script += ' %s %s' % (self.get('QB_MACHINE'), self.get('QB_CPU_KVM'))
  488. yocto_kvm_wiki = "https://wiki.yoctoproject.org/wiki/How_to_enable_KVM_for_Poky_qemu"
  489. yocto_paravirt_kvm_wiki = "https://wiki.yoctoproject.org/wiki/Running_an_x86_Yocto_Linux_image_under_QEMU_KVM"
  490. dev_kvm = '/dev/kvm'
  491. dev_vhost = '/dev/vhost-net'
  492. if self.qemu_system.endswith(('i386', 'x86_64')):
  493. with open('/proc/cpuinfo', 'r') as f:
  494. kvm_cap = re.search('vmx|svm', "".join(f.readlines()))
  495. if not kvm_cap:
  496. logger.error("You are trying to enable KVM on a cpu without VT support.")
  497. logger.error("Remove kvm from the command-line, or refer:")
  498. raise RunQemuError(yocto_kvm_wiki)
  499. if not os.path.exists(dev_kvm):
  500. logger.error("Missing KVM device. Have you inserted kvm modules?")
  501. logger.error("For further help see:")
  502. raise RunQemuError(yocto_kvm_wiki)
  503. if os.access(dev_kvm, os.W_OK|os.R_OK):
  504. self.qemu_opt_script += ' -enable-kvm'
  505. if self.get('MACHINE') == "qemux86":
  506. # Workaround for broken APIC window on pre 4.15 host kernels which causes boot hangs
  507. # See YOCTO #12301
  508. # On 64 bit we use x2apic
  509. self.kernel_cmdline_script += " clocksource=kvm-clock hpet=disable noapic nolapic"
  510. else:
  511. logger.error("You have no read or write permission on /dev/kvm.")
  512. logger.error("Please change the ownership of this file as described at:")
  513. raise RunQemuError(yocto_kvm_wiki)
  514. if self.vhost_enabled:
  515. if not os.path.exists(dev_vhost):
  516. logger.error("Missing virtio net device. Have you inserted vhost-net module?")
  517. logger.error("For further help see:")
  518. raise RunQemuError(yocto_paravirt_kvm_wiki)
  519. if not os.access(dev_kvm, os.W_OK|os.R_OK):
  520. logger.error("You have no read or write permission on /dev/vhost-net.")
  521. logger.error("Please change the ownership of this file as described at:")
  522. raise RunQemuError(yocto_kvm_wiki)
  523. def check_fstype(self):
  524. """Check and setup FSTYPE"""
  525. if not self.fstype:
  526. fstype = self.get('QB_DEFAULT_FSTYPE')
  527. if fstype:
  528. self.fstype = fstype
  529. else:
  530. raise RunQemuError("FSTYPE is NULL!")
  531. # parse QB_FSINFO into dict, e.g. { 'wic': ['no-kernel-in-fs', 'a-flag'], 'ext4': ['another-flag']}
  532. wic_fs = False
  533. qb_fsinfo = self.get('QB_FSINFO')
  534. if qb_fsinfo:
  535. qb_fsinfo = qb_fsinfo.split()
  536. for fsinfo in qb_fsinfo:
  537. try:
  538. fstype, fsflag = fsinfo.split(':')
  539. if fstype == 'wic':
  540. if fsflag == 'no-kernel-in-fs':
  541. wic_fs = True
  542. elif fsflag == 'kernel-in-fs':
  543. wic_fs = False
  544. else:
  545. logger.warn('Unknown flag "%s:%s" in QB_FSINFO', fstype, fsflag)
  546. continue
  547. else:
  548. logger.warn('QB_FSINFO is not supported for image type "%s"', fstype)
  549. continue
  550. if fstype in self.fsinfo:
  551. self.fsinfo[fstype].append(fsflag)
  552. else:
  553. self.fsinfo[fstype] = [fsflag]
  554. except Exception:
  555. logger.error('Invalid parameter "%s" in QB_FSINFO', fsinfo)
  556. # treat wic images as vmimages (with kernel) or as fsimages (rootfs only)
  557. if wic_fs:
  558. self.fstypes = self.fstypes + self.wictypes
  559. else:
  560. self.vmtypes = self.vmtypes + self.wictypes
  561. def check_rootfs(self):
  562. """Check and set rootfs"""
  563. if self.fstype == "none":
  564. return
  565. if self.get('ROOTFS'):
  566. if not self.rootfs:
  567. self.rootfs = self.get('ROOTFS')
  568. elif self.get('ROOTFS') != self.rootfs:
  569. raise RunQemuError("Maybe conflicted ROOTFS: %s vs %s" % (self.get('ROOTFS'), self.rootfs))
  570. if self.fstype == 'nfs':
  571. return
  572. if self.rootfs and not os.path.exists(self.rootfs):
  573. # Lazy rootfs
  574. self.rootfs = "%s/%s-%s.%s" % (self.get('DEPLOY_DIR_IMAGE'),
  575. self.rootfs, self.get('MACHINE'),
  576. self.fstype)
  577. elif not self.rootfs:
  578. cmd_name = '%s/%s*.%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_NAME'), self.fstype)
  579. cmd_link = '%s/%s*.%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_LINK_NAME'), self.fstype)
  580. cmds = (cmd_name, cmd_link)
  581. self.rootfs = get_first_file(cmds)
  582. if not self.rootfs:
  583. raise RunQemuError("Failed to find rootfs: %s or %s" % cmds)
  584. if not os.path.exists(self.rootfs):
  585. raise RunQemuError("Can't find rootfs: %s" % self.rootfs)
  586. def setup_pkkek1(self):
  587. """
  588. Extract from PEM certificate the Platform Key and first Key
  589. Exchange Key certificate string. The hypervisor needs to provide
  590. it in the Type 11 SMBIOS table
  591. """
  592. pemcert = '%s/%s' % (self.get('DEPLOY_DIR_IMAGE'), 'OvmfPkKek1.pem')
  593. try:
  594. with open(pemcert, 'r') as pemfile:
  595. key = pemfile.read().replace('\n', ''). \
  596. replace('-----BEGIN CERTIFICATE-----', ''). \
  597. replace('-----END CERTIFICATE-----', '')
  598. self.ovmf_secboot_pkkek1 = key
  599. except FileNotFoundError:
  600. raise RunQemuError("Can't open PEM certificate %s " % pemcert)
  601. def check_ovmf(self):
  602. """Check and set full path for OVMF firmware and variable file(s)."""
  603. for index, ovmf in enumerate(self.ovmf_bios):
  604. if os.path.exists(ovmf):
  605. continue
  606. for suffix in ('qcow2', 'bin'):
  607. path = '%s/%s.%s' % (self.get('DEPLOY_DIR_IMAGE'), ovmf, suffix)
  608. if os.path.exists(path):
  609. self.ovmf_bios[index] = path
  610. if ovmf.endswith('secboot'):
  611. self.setup_pkkek1()
  612. break
  613. else:
  614. raise RunQemuError("Can't find OVMF firmware: %s" % ovmf)
  615. def check_kernel(self):
  616. """Check and set kernel"""
  617. # The vm image doesn't need a kernel
  618. if self.fstype in self.vmtypes:
  619. return
  620. # See if the user supplied a KERNEL option
  621. if self.get('KERNEL'):
  622. self.kernel = self.get('KERNEL')
  623. # QB_DEFAULT_KERNEL is always a full file path
  624. kernel_name = os.path.basename(self.get('QB_DEFAULT_KERNEL'))
  625. # The user didn't want a kernel to be loaded
  626. if kernel_name == "none" and not self.kernel:
  627. return
  628. deploy_dir_image = self.get('DEPLOY_DIR_IMAGE')
  629. if not self.kernel:
  630. kernel_match_name = "%s/%s" % (deploy_dir_image, kernel_name)
  631. kernel_match_link = "%s/%s" % (deploy_dir_image, self.get('KERNEL_IMAGETYPE'))
  632. kernel_startswith = "%s/%s*" % (deploy_dir_image, self.get('KERNEL_IMAGETYPE'))
  633. cmds = (kernel_match_name, kernel_match_link, kernel_startswith)
  634. self.kernel = get_first_file(cmds)
  635. if not self.kernel:
  636. raise RunQemuError('KERNEL not found: %s, %s or %s' % cmds)
  637. if not os.path.exists(self.kernel):
  638. raise RunQemuError("KERNEL %s not found" % self.kernel)
  639. def check_dtb(self):
  640. """Check and set dtb"""
  641. # Did the user specify a device tree?
  642. if self.get('DEVICE_TREE'):
  643. self.dtb = self.get('DEVICE_TREE')
  644. if not os.path.exists(self.dtb):
  645. raise RunQemuError('Specified DTB not found: %s' % self.dtb)
  646. return
  647. dtb = self.get('QB_DTB')
  648. if dtb:
  649. deploy_dir_image = self.get('DEPLOY_DIR_IMAGE')
  650. cmd_match = "%s/%s" % (deploy_dir_image, dtb)
  651. cmd_startswith = "%s/%s*" % (deploy_dir_image, dtb)
  652. cmd_wild = "%s/*.dtb" % deploy_dir_image
  653. cmds = (cmd_match, cmd_startswith, cmd_wild)
  654. self.dtb = get_first_file(cmds)
  655. if not os.path.exists(self.dtb):
  656. raise RunQemuError('DTB not found: %s, %s or %s' % cmds)
  657. def check_bios(self):
  658. """Check and set bios"""
  659. # See if the user supplied a BIOS option
  660. if self.get('BIOS'):
  661. self.bios = self.get('BIOS')
  662. # QB_DEFAULT_BIOS is always a full file path
  663. bios_name = os.path.basename(self.get('QB_DEFAULT_BIOS'))
  664. # The user didn't want a bios to be loaded
  665. if (bios_name == "" or bios_name == "none") and not self.bios:
  666. return
  667. if not self.bios:
  668. deploy_dir_image = self.get('DEPLOY_DIR_IMAGE')
  669. self.bios = "%s/%s" % (deploy_dir_image, bios_name)
  670. if not self.bios:
  671. raise RunQemuError('BIOS not found: %s' % bios_match_name)
  672. if not os.path.exists(self.bios):
  673. raise RunQemuError("KERNEL %s not found" % self.bios)
  674. def check_mem(self):
  675. """
  676. Both qemu and kernel needs memory settings, so check QB_MEM and set it
  677. for both.
  678. """
  679. s = re.search('-m +([0-9]+)', self.qemuparams)
  680. if s:
  681. self.set('QB_MEM', '-m %s' % s.group(1))
  682. elif not self.get('QB_MEM'):
  683. logger.info('QB_MEM is not set, use 256M by default')
  684. self.set('QB_MEM', '-m 256')
  685. # Check and remove M or m suffix
  686. qb_mem = self.get('QB_MEM')
  687. if qb_mem.endswith('M') or qb_mem.endswith('m'):
  688. qb_mem = qb_mem[:-1]
  689. # Add -m prefix it not present
  690. if not qb_mem.startswith('-m'):
  691. qb_mem = '-m %s' % qb_mem
  692. self.set('QB_MEM', qb_mem)
  693. mach = self.get('MACHINE')
  694. if not mach.startswith('qemumips'):
  695. self.kernel_cmdline_script += ' mem=%s' % self.get('QB_MEM').replace('-m','').strip() + 'M'
  696. self.qemu_opt_script += ' %s' % self.get('QB_MEM')
  697. def check_tcpserial(self):
  698. if self.tcpserial_portnum:
  699. ports = self.tcpserial_portnum.split(':')
  700. port = ports[0]
  701. if self.get('QB_TCPSERIAL_OPT'):
  702. self.qemu_opt_script += ' ' + self.get('QB_TCPSERIAL_OPT').replace('@PORT@', port)
  703. else:
  704. self.qemu_opt_script += ' -serial tcp:127.0.0.1:%s' % port
  705. if len(ports) > 1:
  706. for port in ports[1:]:
  707. self.qemu_opt_script += ' -serial tcp:127.0.0.1:%s' % port
  708. def check_and_set(self):
  709. """Check configs sanity and set when needed"""
  710. self.validate_paths()
  711. if not self.slirp_enabled:
  712. check_tun()
  713. # Check audio
  714. if self.audio_enabled:
  715. if not self.get('QB_AUDIO_DRV'):
  716. raise RunQemuError("QB_AUDIO_DRV is NULL, this board doesn't support audio")
  717. if not self.get('QB_AUDIO_OPT'):
  718. logger.warning('QB_AUDIO_OPT is NULL, you may need define it to make audio work')
  719. else:
  720. self.qemu_opt_script += ' %s' % self.get('QB_AUDIO_OPT')
  721. os.putenv('QEMU_AUDIO_DRV', self.get('QB_AUDIO_DRV'))
  722. else:
  723. os.putenv('QEMU_AUDIO_DRV', 'none')
  724. self.check_qemu_system()
  725. self.check_kvm()
  726. self.check_fstype()
  727. self.check_rootfs()
  728. self.check_ovmf()
  729. self.check_kernel()
  730. self.check_dtb()
  731. self.check_bios()
  732. self.check_mem()
  733. self.check_tcpserial()
  734. def read_qemuboot(self):
  735. if not self.qemuboot:
  736. if self.get('DEPLOY_DIR_IMAGE'):
  737. deploy_dir_image = self.get('DEPLOY_DIR_IMAGE')
  738. else:
  739. logger.warning("Can't find qemuboot conf file, DEPLOY_DIR_IMAGE is NULL!")
  740. return
  741. if self.rootfs and not os.path.exists(self.rootfs):
  742. # Lazy rootfs
  743. machine = self.get('MACHINE')
  744. if not machine:
  745. machine = os.path.basename(deploy_dir_image)
  746. self.qemuboot = "%s/%s-%s.qemuboot.conf" % (deploy_dir_image,
  747. self.rootfs, machine)
  748. else:
  749. cmd = 'ls -t %s/*.qemuboot.conf' % deploy_dir_image
  750. logger.debug('Running %s...' % cmd)
  751. try:
  752. qbs = subprocess.check_output(cmd, shell=True).decode('utf-8')
  753. except subprocess.CalledProcessError as err:
  754. raise RunQemuError(err)
  755. if qbs:
  756. for qb in qbs.split():
  757. # Don't use initramfs when other choices unless fstype is ramfs
  758. if '-initramfs-' in os.path.basename(qb) and self.fstype != 'cpio.gz':
  759. continue
  760. self.qemuboot = qb
  761. break
  762. if not self.qemuboot:
  763. # Use the first one when no choice
  764. self.qemuboot = qbs.split()[0]
  765. self.qbconfload = True
  766. if not self.qemuboot:
  767. # If we haven't found a .qemuboot.conf at this point it probably
  768. # doesn't exist, continue without
  769. return
  770. if not os.path.exists(self.qemuboot):
  771. raise RunQemuError("Failed to find %s (wrong image name or BSP does not support running under qemu?)." % self.qemuboot)
  772. logger.debug('CONFFILE: %s' % self.qemuboot)
  773. cf = configparser.ConfigParser()
  774. cf.read(self.qemuboot)
  775. for k, v in cf.items('config_bsp'):
  776. k_upper = k.upper()
  777. if v.startswith("../"):
  778. v = os.path.abspath(os.path.dirname(self.qemuboot) + "/" + v)
  779. elif v == ".":
  780. v = os.path.dirname(self.qemuboot)
  781. self.set(k_upper, v)
  782. def validate_paths(self):
  783. """Ensure all relevant path variables are set"""
  784. # When we're started with a *.qemuboot.conf arg assume that image
  785. # artefacts are relative to that file, rather than in whatever
  786. # directory DEPLOY_DIR_IMAGE in the conf file points to.
  787. if self.qbconfload:
  788. imgdir = os.path.realpath(os.path.dirname(self.qemuboot))
  789. if imgdir != os.path.realpath(self.get('DEPLOY_DIR_IMAGE')):
  790. logger.info('Setting DEPLOY_DIR_IMAGE to folder containing %s (%s)' % (self.qemuboot, imgdir))
  791. self.set('DEPLOY_DIR_IMAGE', imgdir)
  792. # If the STAGING_*_NATIVE directories from the config file don't exist
  793. # and we're in a sourced OE build directory try to extract the paths
  794. # from `bitbake -e`
  795. havenative = os.path.exists(self.get('STAGING_DIR_NATIVE')) and \
  796. os.path.exists(self.get('STAGING_BINDIR_NATIVE'))
  797. if not havenative:
  798. if not self.bitbake_e:
  799. self.load_bitbake_env()
  800. if self.bitbake_e:
  801. native_vars = ['STAGING_DIR_NATIVE']
  802. for nv in native_vars:
  803. s = re.search('^%s="(.*)"' % nv, self.bitbake_e, re.M)
  804. if s and s.group(1) != self.get(nv):
  805. logger.info('Overriding conf file setting of %s to %s from Bitbake environment' % (nv, s.group(1)))
  806. self.set(nv, s.group(1))
  807. else:
  808. # when we're invoked from a running bitbake instance we won't
  809. # be able to call `bitbake -e`, then try:
  810. # - get OE_TMPDIR from environment and guess paths based on it
  811. # - get OECORE_NATIVE_SYSROOT from environment (for sdk)
  812. tmpdir = self.get('OE_TMPDIR')
  813. oecore_native_sysroot = self.get('OECORE_NATIVE_SYSROOT')
  814. if tmpdir:
  815. logger.info('Setting STAGING_DIR_NATIVE and STAGING_BINDIR_NATIVE relative to OE_TMPDIR (%s)' % tmpdir)
  816. hostos, _, _, _, machine = os.uname()
  817. buildsys = '%s-%s' % (machine, hostos.lower())
  818. staging_dir_native = '%s/sysroots/%s' % (tmpdir, buildsys)
  819. self.set('STAGING_DIR_NATIVE', staging_dir_native)
  820. elif oecore_native_sysroot:
  821. logger.info('Setting STAGING_DIR_NATIVE to OECORE_NATIVE_SYSROOT (%s)' % oecore_native_sysroot)
  822. self.set('STAGING_DIR_NATIVE', oecore_native_sysroot)
  823. if self.get('STAGING_DIR_NATIVE'):
  824. # we have to assume that STAGING_BINDIR_NATIVE is at usr/bin
  825. staging_bindir_native = '%s/usr/bin' % self.get('STAGING_DIR_NATIVE')
  826. logger.info('Setting STAGING_BINDIR_NATIVE to %s' % staging_bindir_native)
  827. self.set('STAGING_BINDIR_NATIVE', '%s/usr/bin' % self.get('STAGING_DIR_NATIVE'))
  828. def print_config(self):
  829. logger.info('Continuing with the following parameters:\n')
  830. if not self.fstype in self.vmtypes:
  831. print('KERNEL: [%s]' % self.kernel)
  832. if self.bios:
  833. print('BIOS: [%s]' % self.bios)
  834. if self.dtb:
  835. print('DTB: [%s]' % self.dtb)
  836. print('MACHINE: [%s]' % self.get('MACHINE'))
  837. try:
  838. fstype_flags = ' (' + ', '.join(self.fsinfo[self.fstype]) + ')'
  839. except KeyError:
  840. fstype_flags = ''
  841. print('FSTYPE: [%s%s]' % (self.fstype, fstype_flags))
  842. if self.fstype == 'nfs':
  843. print('NFS_DIR: [%s]' % self.rootfs)
  844. else:
  845. print('ROOTFS: [%s]' % self.rootfs)
  846. if self.ovmf_bios:
  847. print('OVMF: %s' % self.ovmf_bios)
  848. if (self.ovmf_secboot_pkkek1):
  849. print('SECBOOT PKKEK1: [%s...]' % self.ovmf_secboot_pkkek1[0:100])
  850. print('CONFFILE: [%s]' % self.qemuboot)
  851. print('')
  852. def setup_nfs(self):
  853. if not self.nfs_server:
  854. if self.slirp_enabled:
  855. self.nfs_server = '10.0.2.2'
  856. else:
  857. self.nfs_server = '192.168.7.1'
  858. # Figure out a new nfs_instance to allow multiple qemus running.
  859. ps = subprocess.check_output(("ps", "auxww")).decode('utf-8')
  860. pattern = '/bin/unfsd .* -i .*\.pid -e .*/exports([0-9]+) '
  861. all_instances = re.findall(pattern, ps, re.M)
  862. if all_instances:
  863. all_instances.sort(key=int)
  864. self.nfs_instance = int(all_instances.pop()) + 1
  865. nfsd_port = 3049 + 2 * self.nfs_instance
  866. mountd_port = 3048 + 2 * self.nfs_instance
  867. # Export vars for runqemu-export-rootfs
  868. export_dict = {
  869. 'NFS_INSTANCE': self.nfs_instance,
  870. 'NFSD_PORT': nfsd_port,
  871. 'MOUNTD_PORT': mountd_port,
  872. }
  873. for k, v in export_dict.items():
  874. # Use '%s' since they are integers
  875. os.putenv(k, '%s' % v)
  876. self.unfs_opts="nfsvers=3,port=%s,udp,mountport=%s" % (nfsd_port, mountd_port)
  877. # Extract .tar.bz2 or .tar.bz if no nfs dir
  878. if not (self.rootfs and os.path.isdir(self.rootfs)):
  879. src_prefix = '%s/%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_LINK_NAME'))
  880. dest = "%s-nfsroot" % src_prefix
  881. if os.path.exists('%s.pseudo_state' % dest):
  882. logger.info('Use %s as NFS_DIR' % dest)
  883. self.rootfs = dest
  884. else:
  885. src = ""
  886. src1 = '%s.tar.bz2' % src_prefix
  887. src2 = '%s.tar.gz' % src_prefix
  888. if os.path.exists(src1):
  889. src = src1
  890. elif os.path.exists(src2):
  891. src = src2
  892. if not src:
  893. raise RunQemuError("No NFS_DIR is set, and can't find %s or %s to extract" % (src1, src2))
  894. logger.info('NFS_DIR not found, extracting %s to %s' % (src, dest))
  895. cmd = ('runqemu-extract-sdk', src, dest)
  896. logger.info('Running %s...' % str(cmd))
  897. if subprocess.call(cmd) != 0:
  898. raise RunQemuError('Failed to run %s' % cmd)
  899. self.clean_nfs_dir = True
  900. self.rootfs = dest
  901. # Start the userspace NFS server
  902. cmd = ('runqemu-export-rootfs', 'start', self.rootfs)
  903. logger.info('Running %s...' % str(cmd))
  904. if subprocess.call(cmd) != 0:
  905. raise RunQemuError('Failed to run %s' % cmd)
  906. self.nfs_running = True
  907. def setup_slirp(self):
  908. """Setup user networking"""
  909. if self.fstype == 'nfs':
  910. self.setup_nfs()
  911. self.kernel_cmdline_script += ' ip=dhcp'
  912. # Port mapping
  913. hostfwd = ",hostfwd=tcp::2222-:22,hostfwd=tcp::2323-:23"
  914. qb_slirp_opt_default = "-netdev user,id=net0%s,tftp=%s" % (hostfwd, self.get('DEPLOY_DIR_IMAGE'))
  915. qb_slirp_opt = self.get('QB_SLIRP_OPT') or qb_slirp_opt_default
  916. # Figure out the port
  917. ports = re.findall('hostfwd=[^-]*:([0-9]+)-[^,-]*', qb_slirp_opt)
  918. ports = [int(i) for i in ports]
  919. mac = 2
  920. lockdir = "/tmp/qemu-port-locks"
  921. if not os.path.exists(lockdir):
  922. # There might be a race issue when multi runqemu processess are
  923. # running at the same time.
  924. try:
  925. os.mkdir(lockdir)
  926. os.chmod(lockdir, 0o777)
  927. except FileExistsError:
  928. pass
  929. # Find a free port to avoid conflicts
  930. for p in ports[:]:
  931. p_new = p
  932. while not self.check_free_port('localhost', p_new, lockdir):
  933. p_new += 1
  934. mac += 1
  935. while p_new in ports:
  936. p_new += 1
  937. mac += 1
  938. if p != p_new:
  939. ports.append(p_new)
  940. qb_slirp_opt = re.sub(':%s-' % p, ':%s-' % p_new, qb_slirp_opt)
  941. logger.info("Port forward changed: %s -> %s" % (p, p_new))
  942. mac = "%s%02x" % (self.mac_slirp, mac)
  943. self.set('NETWORK_CMD', '%s %s' % (self.network_device.replace('@MAC@', mac), qb_slirp_opt))
  944. # Print out port foward
  945. hostfwd = re.findall('(hostfwd=[^,]*)', qb_slirp_opt)
  946. if hostfwd:
  947. logger.info('Port forward: %s' % ' '.join(hostfwd))
  948. def setup_tap(self):
  949. """Setup tap"""
  950. # This file is created when runqemu-gen-tapdevs creates a bank of tap
  951. # devices, indicating that the user should not bring up new ones using
  952. # sudo.
  953. nosudo_flag = '/etc/runqemu-nosudo'
  954. self.qemuifup = shutil.which('runqemu-ifup')
  955. self.qemuifdown = shutil.which('runqemu-ifdown')
  956. ip = shutil.which('ip')
  957. lockdir = "/tmp/qemu-tap-locks"
  958. if not (self.qemuifup and self.qemuifdown and ip):
  959. logger.error("runqemu-ifup: %s" % self.qemuifup)
  960. logger.error("runqemu-ifdown: %s" % self.qemuifdown)
  961. logger.error("ip: %s" % ip)
  962. raise OEPathError("runqemu-ifup, runqemu-ifdown or ip not found")
  963. if not os.path.exists(lockdir):
  964. # There might be a race issue when multi runqemu processess are
  965. # running at the same time.
  966. try:
  967. os.mkdir(lockdir)
  968. os.chmod(lockdir, 0o777)
  969. except FileExistsError:
  970. pass
  971. cmd = (ip, 'link')
  972. logger.debug('Running %s...' % str(cmd))
  973. ip_link = subprocess.check_output(cmd).decode('utf-8')
  974. # Matches line like: 6: tap0: <foo>
  975. possibles = re.findall('^[0-9]+: +(tap[0-9]+): <.*', ip_link, re.M)
  976. tap = ""
  977. for p in possibles:
  978. lockfile = os.path.join(lockdir, p)
  979. if os.path.exists('%s.skip' % lockfile):
  980. logger.info('Found %s.skip, skipping %s' % (lockfile, p))
  981. continue
  982. self.taplock = lockfile + '.lock'
  983. if self.acquire_taplock(error=False):
  984. tap = p
  985. logger.info("Using preconfigured tap device %s" % tap)
  986. logger.info("If this is not intended, touch %s.skip to make runqemu skip %s." %(lockfile, tap))
  987. break
  988. if not tap:
  989. if os.path.exists(nosudo_flag):
  990. logger.error("Error: There are no available tap devices to use for networking,")
  991. logger.error("and I see %s exists, so I am not going to try creating" % nosudo_flag)
  992. raise RunQemuError("a new one with sudo.")
  993. gid = os.getgid()
  994. uid = os.getuid()
  995. logger.info("Setting up tap interface under sudo")
  996. cmd = ('sudo', self.qemuifup, str(uid), str(gid), self.bindir_native)
  997. tap = subprocess.check_output(cmd).decode('utf-8').strip()
  998. lockfile = os.path.join(lockdir, tap)
  999. self.taplock = lockfile + '.lock'
  1000. self.acquire_taplock()
  1001. self.cleantap = True
  1002. logger.debug('Created tap: %s' % tap)
  1003. if not tap:
  1004. logger.error("Failed to setup tap device. Run runqemu-gen-tapdevs to manually create.")
  1005. return 1
  1006. self.tap = tap
  1007. tapnum = int(tap[3:])
  1008. gateway = tapnum * 2 + 1
  1009. client = gateway + 1
  1010. if self.fstype == 'nfs':
  1011. self.setup_nfs()
  1012. netconf = "192.168.7.%s::192.168.7.%s:255.255.255.0" % (client, gateway)
  1013. logger.info("Network configuration: %s", netconf)
  1014. self.kernel_cmdline_script += " ip=%s" % netconf
  1015. mac = "%s%02x" % (self.mac_tap, client)
  1016. qb_tap_opt = self.get('QB_TAP_OPT')
  1017. if qb_tap_opt:
  1018. qemu_tap_opt = qb_tap_opt.replace('@TAP@', tap)
  1019. else:
  1020. qemu_tap_opt = "-netdev tap,id=net0,ifname=%s,script=no,downscript=no" % (self.tap)
  1021. if self.vhost_enabled:
  1022. qemu_tap_opt += ',vhost=on'
  1023. self.set('NETWORK_CMD', '%s %s' % (self.network_device.replace('@MAC@', mac), qemu_tap_opt))
  1024. def setup_network(self):
  1025. if self.get('QB_NET') == 'none':
  1026. return
  1027. if sys.stdin.isatty():
  1028. self.saved_stty = subprocess.check_output(("stty", "-g")).decode('utf-8').strip()
  1029. self.network_device = self.get('QB_NETWORK_DEVICE') or self.network_device
  1030. if self.slirp_enabled:
  1031. self.setup_slirp()
  1032. else:
  1033. self.setup_tap()
  1034. def setup_rootfs(self):
  1035. if self.get('QB_ROOTFS') == 'none':
  1036. return
  1037. if 'wic.' in self.fstype:
  1038. self.fstype = self.fstype[4:]
  1039. rootfs_format = self.fstype if self.fstype in ('vmdk', 'qcow2', 'vdi') else 'raw'
  1040. qb_rootfs_opt = self.get('QB_ROOTFS_OPT')
  1041. if qb_rootfs_opt:
  1042. self.rootfs_options = qb_rootfs_opt.replace('@ROOTFS@', self.rootfs)
  1043. else:
  1044. self.rootfs_options = '-drive file=%s,if=virtio,format=%s' % (self.rootfs, rootfs_format)
  1045. if self.fstype in ('cpio.gz', 'cpio'):
  1046. self.kernel_cmdline = 'root=/dev/ram0 rw debugshell'
  1047. self.rootfs_options = '-initrd %s' % self.rootfs
  1048. else:
  1049. vm_drive = ''
  1050. if self.fstype in self.vmtypes:
  1051. if self.fstype == 'iso':
  1052. vm_drive = '-drive file=%s,if=virtio,media=cdrom' % self.rootfs
  1053. elif self.get('QB_DRIVE_TYPE'):
  1054. drive_type = self.get('QB_DRIVE_TYPE')
  1055. if drive_type.startswith("/dev/sd"):
  1056. logger.info('Using scsi drive')
  1057. vm_drive = '-drive if=none,id=hd,file=%s,format=%s -device virtio-scsi-pci,id=scsi -device scsi-hd,drive=hd' \
  1058. % (self.rootfs, rootfs_format)
  1059. elif drive_type.startswith("/dev/hd"):
  1060. logger.info('Using ide drive')
  1061. vm_drive = "-drive file=%s,format=%s" % (self.rootfs, rootfs_format)
  1062. else:
  1063. # virtio might have been selected explicitly (just use it), or
  1064. # is used as fallback (then warn about that).
  1065. if not drive_type.startswith("/dev/vd"):
  1066. logger.warning("Unknown QB_DRIVE_TYPE: %s" % drive_type)
  1067. logger.warning("Failed to figure out drive type, consider define or fix QB_DRIVE_TYPE")
  1068. logger.warning('Trying to use virtio block drive')
  1069. vm_drive = '-drive if=virtio,file=%s,format=%s' % (self.rootfs, rootfs_format)
  1070. # All branches above set vm_drive.
  1071. self.rootfs_options = '%s -no-reboot' % vm_drive
  1072. self.kernel_cmdline = 'root=%s rw' % (self.get('QB_KERNEL_ROOT'))
  1073. if self.fstype == 'nfs':
  1074. self.rootfs_options = ''
  1075. k_root = '/dev/nfs nfsroot=%s:%s,%s' % (self.nfs_server, os.path.abspath(self.rootfs), self.unfs_opts)
  1076. self.kernel_cmdline = 'root=%s rw' % k_root
  1077. if self.fstype == 'none':
  1078. self.rootfs_options = ''
  1079. self.set('ROOTFS_OPTIONS', self.rootfs_options)
  1080. def guess_qb_system(self):
  1081. """attempt to determine the appropriate qemu-system binary"""
  1082. mach = self.get('MACHINE')
  1083. if not mach:
  1084. search = '.*(qemux86-64|qemux86|qemuarm64|qemuarm|qemumips64|qemumips64el|qemumipsel|qemumips|qemuppc).*'
  1085. if self.rootfs:
  1086. match = re.match(search, self.rootfs)
  1087. if match:
  1088. mach = match.group(1)
  1089. elif self.kernel:
  1090. match = re.match(search, self.kernel)
  1091. if match:
  1092. mach = match.group(1)
  1093. if not mach:
  1094. return None
  1095. if mach == 'qemuarm':
  1096. qbsys = 'arm'
  1097. elif mach == 'qemuarm64':
  1098. qbsys = 'aarch64'
  1099. elif mach == 'qemux86':
  1100. qbsys = 'i386'
  1101. elif mach == 'qemux86-64':
  1102. qbsys = 'x86_64'
  1103. elif mach == 'qemuppc':
  1104. qbsys = 'ppc'
  1105. elif mach == 'qemumips':
  1106. qbsys = 'mips'
  1107. elif mach == 'qemumips64':
  1108. qbsys = 'mips64'
  1109. elif mach == 'qemumipsel':
  1110. qbsys = 'mipsel'
  1111. elif mach == 'qemumips64el':
  1112. qbsys = 'mips64el'
  1113. elif mach == 'qemuriscv64':
  1114. qbsys = 'riscv64'
  1115. elif mach == 'qemuriscv32':
  1116. qbsys = 'riscv32'
  1117. else:
  1118. logger.error("Unable to determine QEMU PC System emulator for %s machine." % mach)
  1119. logger.error("As %s is not among valid QEMU machines such as," % mach)
  1120. logger.error("qemux86-64, qemux86, qemuarm64, qemuarm, qemumips64, qemumips64el, qemumipsel, qemumips, qemuppc")
  1121. raise RunQemuError("Set qb_system_name with suitable QEMU PC System emulator in .*qemuboot.conf.")
  1122. return 'qemu-system-%s' % qbsys
  1123. def check_qemu_system(self):
  1124. qemu_system = self.get('QB_SYSTEM_NAME')
  1125. if not qemu_system:
  1126. qemu_system = self.guess_qb_system()
  1127. if not qemu_system:
  1128. raise RunQemuError("Failed to boot, QB_SYSTEM_NAME is NULL!")
  1129. self.qemu_system = qemu_system
  1130. def setup_final(self):
  1131. qemu_bin = os.path.join(self.bindir_native, self.qemu_system)
  1132. # It is possible to have qemu-native in ASSUME_PROVIDED, and it won't
  1133. # find QEMU in sysroot, it needs to use host's qemu.
  1134. if not os.path.exists(qemu_bin):
  1135. logger.info("QEMU binary not found in %s, trying host's QEMU" % qemu_bin)
  1136. for path in (os.environ['PATH'] or '').split(':'):
  1137. qemu_bin_tmp = os.path.join(path, self.qemu_system)
  1138. logger.info("Trying: %s" % qemu_bin_tmp)
  1139. if os.path.exists(qemu_bin_tmp):
  1140. qemu_bin = qemu_bin_tmp
  1141. if not os.path.isabs(qemu_bin):
  1142. qemu_bin = os.path.abspath(qemu_bin)
  1143. logger.info("Using host's QEMU: %s" % qemu_bin)
  1144. break
  1145. if not os.access(qemu_bin, os.X_OK):
  1146. raise OEPathError("No QEMU binary '%s' could be found" % qemu_bin)
  1147. self.qemu_opt = "%s %s %s %s" % (qemu_bin, self.get('NETWORK_CMD'), self.get('ROOTFS_OPTIONS'), self.get('QB_OPT_APPEND'))
  1148. for ovmf in self.ovmf_bios:
  1149. format = ovmf.rsplit('.', 1)[-1]
  1150. self.qemu_opt += ' -drive if=pflash,format=%s,file=%s' % (format, ovmf)
  1151. self.qemu_opt += ' ' + self.qemu_opt_script
  1152. if self.ovmf_secboot_pkkek1:
  1153. # Provide the Platform Key and first Key Exchange Key certificate as an
  1154. # OEM string in the SMBIOS Type 11 table. Prepend the certificate string
  1155. # with "application prefix" of the EnrollDefaultKeys.efi application
  1156. self.qemu_opt += ' -smbios type=11,value=4e32566d-8e9e-4f52-81d3-5bb9715f9727:' \
  1157. + self.ovmf_secboot_pkkek1
  1158. # Append qemuparams to override previous settings
  1159. if self.qemuparams:
  1160. self.qemu_opt += ' ' + self.qemuparams
  1161. if self.snapshot:
  1162. self.qemu_opt += " -snapshot"
  1163. if self.serialconsole:
  1164. if sys.stdin.isatty():
  1165. subprocess.check_call(("stty", "intr", "^]"))
  1166. logger.info("Interrupt character is '^]'")
  1167. first_serial = ""
  1168. if not re.search("-nographic", self.qemu_opt):
  1169. first_serial = "-serial mon:vc"
  1170. # We always want a ttyS1. Since qemu by default adds a serial
  1171. # port when nodefaults is not specified, it seems that all that
  1172. # would be needed is to make sure a "-serial" is there. However,
  1173. # it appears that when "-serial" is specified, it ignores the
  1174. # default serial port that is normally added. So here we make
  1175. # sure to add two -serial if there are none. And only one if
  1176. # there is one -serial already.
  1177. serial_num = len(re.findall("-serial", self.qemu_opt))
  1178. if serial_num == 0:
  1179. self.qemu_opt += " %s %s" % (first_serial, self.get("QB_SERIAL_OPT"))
  1180. elif serial_num == 1:
  1181. self.qemu_opt += " %s" % self.get("QB_SERIAL_OPT")
  1182. # We always wants ttyS0 and ttyS1 in qemu machines (see SERIAL_CONSOLES),
  1183. # if not serial or serialtcp options was specified only ttyS0 is created
  1184. # and sysvinit shows an error trying to enable ttyS1:
  1185. # INIT: Id "S1" respawning too fast: disabled for 5 minutes
  1186. serial_num = len(re.findall("-serial", self.qemu_opt))
  1187. if serial_num == 0:
  1188. if re.search("-nographic", self.qemu_opt) or self.serialstdio:
  1189. self.qemu_opt += " -serial mon:stdio -serial null"
  1190. else:
  1191. self.qemu_opt += " -serial mon:vc -serial null"
  1192. def start_qemu(self):
  1193. import shlex
  1194. if self.kernel:
  1195. kernel_opts = "-kernel %s -append '%s %s %s %s'" % (self.kernel, self.kernel_cmdline,
  1196. self.kernel_cmdline_script, self.get('QB_KERNEL_CMDLINE_APPEND'),
  1197. self.bootparams)
  1198. if self.bios:
  1199. kernel_opts += " -bios %s" % self.bios
  1200. if self.dtb:
  1201. kernel_opts += " -dtb %s" % self.dtb
  1202. else:
  1203. kernel_opts = ""
  1204. cmd = "%s %s" % (self.qemu_opt, kernel_opts)
  1205. cmds = shlex.split(cmd)
  1206. logger.info('Running %s\n' % cmd)
  1207. pass_fds = []
  1208. if self.taplock_descriptor:
  1209. pass_fds = [self.taplock_descriptor.fileno()]
  1210. if len(self.portlocks):
  1211. for descriptor in self.portlocks.values():
  1212. pass_fds.append(descriptor.fileno())
  1213. process = subprocess.Popen(cmds, stderr=subprocess.PIPE, pass_fds=pass_fds)
  1214. self.qemupid = process.pid
  1215. retcode = process.wait()
  1216. if retcode:
  1217. if retcode == -signal.SIGTERM:
  1218. logger.info("Qemu terminated by SIGTERM")
  1219. else:
  1220. logger.error("Failed to run qemu: %s", process.stderr.read().decode())
  1221. def cleanup(self):
  1222. if self.cleaned:
  1223. return
  1224. # avoid dealing with SIGTERM when cleanup function is running
  1225. signal.signal(signal.SIGTERM, signal.SIG_IGN)
  1226. logger.info("Cleaning up")
  1227. if self.cleantap:
  1228. cmd = ('sudo', self.qemuifdown, self.tap, self.bindir_native)
  1229. logger.debug('Running %s' % str(cmd))
  1230. subprocess.check_call(cmd)
  1231. self.release_taplock()
  1232. self.release_portlock()
  1233. if self.nfs_running:
  1234. logger.info("Shutting down the userspace NFS server...")
  1235. cmd = ("runqemu-export-rootfs", "stop", self.rootfs)
  1236. logger.debug('Running %s' % str(cmd))
  1237. subprocess.check_call(cmd)
  1238. if self.saved_stty:
  1239. subprocess.check_call(("stty", self.saved_stty))
  1240. if self.clean_nfs_dir:
  1241. logger.info('Removing %s' % self.rootfs)
  1242. shutil.rmtree(self.rootfs)
  1243. shutil.rmtree('%s.pseudo_state' % self.rootfs)
  1244. self.cleaned = True
  1245. def load_bitbake_env(self, mach=None):
  1246. if self.bitbake_e:
  1247. return
  1248. bitbake = shutil.which('bitbake')
  1249. if not bitbake:
  1250. return
  1251. if not mach:
  1252. mach = self.get('MACHINE')
  1253. if mach:
  1254. cmd = 'MACHINE=%s bitbake -e' % mach
  1255. else:
  1256. cmd = 'bitbake -e'
  1257. logger.info('Running %s...' % cmd)
  1258. try:
  1259. self.bitbake_e = subprocess.check_output(cmd, shell=True).decode('utf-8')
  1260. except subprocess.CalledProcessError as err:
  1261. self.bitbake_e = ''
  1262. logger.warning("Couldn't run 'bitbake -e' to gather environment information:\n%s" % err.output.decode('utf-8'))
  1263. def validate_combos(self):
  1264. if (self.fstype in self.vmtypes) and self.kernel:
  1265. raise RunQemuError("%s doesn't need kernel %s!" % (self.fstype, self.kernel))
  1266. @property
  1267. def bindir_native(self):
  1268. result = self.get('STAGING_BINDIR_NATIVE')
  1269. if result and os.path.exists(result):
  1270. return result
  1271. cmd = ('bitbake', 'qemu-helper-native', '-e')
  1272. logger.info('Running %s...' % str(cmd))
  1273. out = subprocess.check_output(cmd).decode('utf-8')
  1274. match = re.search('^STAGING_BINDIR_NATIVE="(.*)"', out, re.M)
  1275. if match:
  1276. result = match.group(1)
  1277. if os.path.exists(result):
  1278. self.set('STAGING_BINDIR_NATIVE', result)
  1279. return result
  1280. raise RunQemuError("Native sysroot directory %s doesn't exist" % result)
  1281. else:
  1282. raise RunQemuError("Can't find STAGING_BINDIR_NATIVE in '%s' output" % cmd)
  1283. def main():
  1284. if "help" in sys.argv or '-h' in sys.argv or '--help' in sys.argv:
  1285. print_usage()
  1286. return 0
  1287. try:
  1288. config = BaseConfig()
  1289. def sigterm_handler(signum, frame):
  1290. logger.info("SIGTERM received")
  1291. os.kill(config.qemupid, signal.SIGTERM)
  1292. config.cleanup()
  1293. # Deliberately ignore the return code of 'tput smam'.
  1294. subprocess.call(["tput", "smam"])
  1295. signal.signal(signal.SIGTERM, sigterm_handler)
  1296. config.check_args()
  1297. config.read_qemuboot()
  1298. config.check_and_set()
  1299. # Check whether the combos is valid or not
  1300. config.validate_combos()
  1301. config.print_config()
  1302. config.setup_network()
  1303. config.setup_rootfs()
  1304. config.setup_final()
  1305. config.start_qemu()
  1306. except RunQemuError as err:
  1307. logger.error(err)
  1308. return 1
  1309. except Exception as err:
  1310. import traceback
  1311. traceback.print_exc()
  1312. return 1
  1313. finally:
  1314. config.cleanup()
  1315. # Deliberately ignore the return code of 'tput smam'.
  1316. subprocess.call(["tput", "smam"])
  1317. if __name__ == "__main__":
  1318. sys.exit(main())