runqemu 64 KB

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