runqemu 74 KB

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