runqemu 66 KB

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