runqemu 65 KB

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