runqemu 67 KB

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