runqemu 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776
  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_dri_path(self):
  433. drivers_path = os.path.join(self.bindir_native, '../lib/dri')
  434. if not os.path.exists(drivers_path) or not os.listdir(drivers_path):
  435. raise RunQemuError("""
  436. qemu has been built without opengl support and accelerated graphics support is not available.
  437. To enable it, add:
  438. DISTRO_FEATURES_NATIVE:append = " opengl"
  439. DISTRO_FEATURES_NATIVESDK:append = " opengl"
  440. to your build configuration.
  441. """)
  442. self.qemu_environ['LIBGL_DRIVERS_PATH'] = drivers_path
  443. def check_args(self):
  444. for debug in ("-d", "--debug"):
  445. if debug in sys.argv:
  446. logger.setLevel(logging.DEBUG)
  447. sys.argv.remove(debug)
  448. for quiet in ("-q", "--quiet"):
  449. if quiet in sys.argv:
  450. logger.setLevel(logging.ERROR)
  451. sys.argv.remove(quiet)
  452. if 'gl' not in sys.argv[1:] and 'gl-es' not in sys.argv[1:]:
  453. self.qemu_environ['SDL_RENDER_DRIVER'] = 'software'
  454. self.qemu_environ['SDL_FRAMEBUFFER_ACCELERATION'] = 'false'
  455. unknown_arg = ""
  456. for arg in sys.argv[1:]:
  457. if arg in self.fstypes + self.vmtypes + self.wictypes:
  458. self.check_arg_fstype(arg)
  459. elif arg == 'nographic':
  460. self.nographic = True
  461. elif arg == "nonetwork":
  462. self.nonetwork = True
  463. elif arg == 'sdl':
  464. self.sdl = True
  465. elif arg == 'gtk':
  466. self.gtk = True
  467. elif arg == 'gl':
  468. self.gl = True
  469. elif arg == 'gl-es':
  470. self.gl_es = True
  471. elif arg == 'egl-headless':
  472. self.egl_headless = True
  473. elif arg == 'novga':
  474. self.novga = True
  475. elif arg == 'serial':
  476. self.serialconsole = True
  477. elif arg == "serialstdio":
  478. self.serialstdio = True
  479. elif arg == 'audio':
  480. logger.info("Enabling audio in qemu")
  481. logger.info("Please install sound drivers in linux host")
  482. self.audio_enabled = True
  483. elif arg == 'kvm':
  484. self.kvm_enabled = True
  485. elif arg == 'kvm-vhost':
  486. self.vhost_enabled = True
  487. elif arg == 'slirp':
  488. self.slirp_enabled = True
  489. elif arg.startswith('bridge='):
  490. self.net_bridge = '%s' % arg[len('bridge='):]
  491. elif arg == 'snapshot':
  492. self.snapshot = True
  493. elif arg == 'publicvnc':
  494. self.publicvnc = True
  495. self.qemu_opt_script += ' -vnc :0'
  496. elif arg == 'guestagent':
  497. self.guest_agent = True
  498. elif arg == "qmp":
  499. self.qmp = "unix:qmp.sock"
  500. elif arg.startswith("qmp="):
  501. self.qmp = arg[len('qmp='):]
  502. elif arg.startswith('guestagent-sockpath='):
  503. self.guest_agent_sockpath = '%s' % arg[len('guestagent-sockpath='):]
  504. elif arg.startswith('tcpserial='):
  505. self.tcpserial_portnum = '%s' % arg[len('tcpserial='):]
  506. elif arg.startswith('qemuparams='):
  507. self.qemuparams = ' %s' % arg[len('qemuparams='):]
  508. elif arg.startswith('bootparams='):
  509. self.bootparams = arg[len('bootparams='):]
  510. elif os.path.exists(arg) or (re.search(':', arg) and re.search('/', arg)):
  511. self.check_arg_path(os.path.abspath(arg))
  512. elif re.search(r'-image-|-image$', arg):
  513. # Lazy rootfs
  514. self.rootfs = arg
  515. elif arg.startswith('ovmf'):
  516. self.ovmf_bios.append(arg)
  517. else:
  518. # At last, assume it is the MACHINE
  519. if (not unknown_arg) or unknown_arg == arg:
  520. unknown_arg = arg
  521. else:
  522. raise RunQemuError("Can't handle two unknown args: %s %s\n"
  523. "Try 'runqemu help' on how to use it" % \
  524. (unknown_arg, arg))
  525. # Check to make sure it is a valid machine
  526. if unknown_arg and self.get('MACHINE') != unknown_arg:
  527. if self.get('DEPLOY_DIR_IMAGE'):
  528. machine = os.path.basename(self.get('DEPLOY_DIR_IMAGE'))
  529. if unknown_arg == machine:
  530. self.set("MACHINE", machine)
  531. self.check_arg_machine(unknown_arg)
  532. if not (self.get('DEPLOY_DIR_IMAGE') or self.qbconfload):
  533. self.load_bitbake_env(target=self.rootfs)
  534. s = re.search('^DEPLOY_DIR_IMAGE="(.*)"', self.bitbake_e, re.M)
  535. if s:
  536. self.set("DEPLOY_DIR_IMAGE", s.group(1))
  537. if not self.get('IMAGE_LINK_NAME') and self.rootfs:
  538. s = re.search('^IMAGE_LINK_NAME="(.*)"', self.bitbake_e, re.M)
  539. if s:
  540. image_link_name = s.group(1)
  541. self.set("IMAGE_LINK_NAME", image_link_name)
  542. logger.debug('Using IMAGE_LINK_NAME = "%s"' % image_link_name)
  543. def check_kvm(self):
  544. """Check kvm and kvm-host"""
  545. if not (self.kvm_enabled or self.vhost_enabled):
  546. self.qemu_opt_script += ' %s %s %s' % (self.get('QB_MACHINE'), self.get('QB_CPU'), self.get('QB_SMP'))
  547. return
  548. if not self.get('QB_CPU_KVM'):
  549. raise RunQemuError("QB_CPU_KVM is NULL, this board doesn't support kvm")
  550. self.qemu_opt_script += ' %s %s %s' % (self.get('QB_MACHINE'), self.get('QB_CPU_KVM'), self.get('QB_SMP'))
  551. yocto_kvm_wiki = "https://wiki.yoctoproject.org/wiki/How_to_enable_KVM_for_Poky_qemu"
  552. yocto_paravirt_kvm_wiki = "https://wiki.yoctoproject.org/wiki/Running_an_x86_Yocto_Linux_image_under_QEMU_KVM"
  553. dev_kvm = '/dev/kvm'
  554. dev_vhost = '/dev/vhost-net'
  555. if self.qemu_system.endswith(('i386', 'x86_64')):
  556. with open('/proc/cpuinfo', 'r') as f:
  557. kvm_cap = re.search('vmx|svm', "".join(f.readlines()))
  558. if not kvm_cap:
  559. logger.error("You are trying to enable KVM on a cpu without VT support.")
  560. logger.error("Remove kvm from the command-line, or refer:")
  561. raise RunQemuError(yocto_kvm_wiki)
  562. if not os.path.exists(dev_kvm):
  563. logger.error("Missing KVM device. Have you inserted kvm modules?")
  564. logger.error("For further help see:")
  565. raise RunQemuError(yocto_kvm_wiki)
  566. if os.access(dev_kvm, os.W_OK|os.R_OK):
  567. self.qemu_opt_script += ' -enable-kvm'
  568. else:
  569. logger.error("You have no read or write permission on /dev/kvm.")
  570. logger.error("Please change the ownership of this file as described at:")
  571. raise RunQemuError(yocto_kvm_wiki)
  572. if self.vhost_enabled:
  573. if not os.path.exists(dev_vhost):
  574. logger.error("Missing virtio net device. Have you inserted vhost-net module?")
  575. logger.error("For further help see:")
  576. raise RunQemuError(yocto_paravirt_kvm_wiki)
  577. if not os.access(dev_vhost, os.W_OK|os.R_OK):
  578. logger.error("You have no read or write permission on /dev/vhost-net.")
  579. logger.error("Please change the ownership of this file as described at:")
  580. raise RunQemuError(yocto_paravirt_kvm_wiki)
  581. def check_fstype(self):
  582. """Check and setup FSTYPE"""
  583. if not self.fstype:
  584. fstype = self.get('QB_DEFAULT_FSTYPE')
  585. if fstype:
  586. self.fstype = fstype
  587. else:
  588. raise RunQemuError("FSTYPE is NULL!")
  589. # parse QB_FSINFO into dict, e.g. { 'wic': ['no-kernel-in-fs', 'a-flag'], 'ext4': ['another-flag']}
  590. wic_fs = False
  591. qb_fsinfo = self.get('QB_FSINFO')
  592. if qb_fsinfo:
  593. qb_fsinfo = qb_fsinfo.split()
  594. for fsinfo in qb_fsinfo:
  595. try:
  596. fstype, fsflag = fsinfo.split(':')
  597. if fstype == 'wic':
  598. if fsflag == 'no-kernel-in-fs':
  599. wic_fs = True
  600. elif fsflag == 'kernel-in-fs':
  601. wic_fs = False
  602. else:
  603. logger.warning('Unknown flag "%s:%s" in QB_FSINFO', fstype, fsflag)
  604. continue
  605. else:
  606. logger.warning('QB_FSINFO is not supported for image type "%s"', fstype)
  607. continue
  608. if fstype in self.fsinfo:
  609. self.fsinfo[fstype].append(fsflag)
  610. else:
  611. self.fsinfo[fstype] = [fsflag]
  612. except Exception:
  613. logger.error('Invalid parameter "%s" in QB_FSINFO', fsinfo)
  614. # treat wic images as vmimages (with kernel) or as fsimages (rootfs only)
  615. if wic_fs:
  616. self.fstypes = self.fstypes + self.wictypes
  617. else:
  618. self.vmtypes = self.vmtypes + self.wictypes
  619. def check_rootfs(self):
  620. """Check and set rootfs"""
  621. if self.fstype == "none":
  622. return
  623. if self.get('ROOTFS'):
  624. if not self.rootfs:
  625. self.rootfs = self.get('ROOTFS')
  626. elif self.get('ROOTFS') != self.rootfs:
  627. raise RunQemuError("Maybe conflicted ROOTFS: %s vs %s" % (self.get('ROOTFS'), self.rootfs))
  628. if self.fstype == 'nfs':
  629. return
  630. if self.rootfs and not os.path.exists(self.rootfs):
  631. # Lazy rootfs
  632. self.rootfs = "%s/%s.%s" % (self.get('DEPLOY_DIR_IMAGE'),
  633. self.get('IMAGE_LINK_NAME'),
  634. self.fstype)
  635. elif not self.rootfs:
  636. glob_name = '%s/%s*.%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_NAME'), self.fstype)
  637. glob_link = '%s/%s*.%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_LINK_NAME'), self.fstype)
  638. globs = (glob_name, glob_link)
  639. self.rootfs = get_first_file(globs)
  640. if not self.rootfs:
  641. raise RunQemuError("Failed to find rootfs: %s or %s" % globs)
  642. if not os.path.exists(self.rootfs):
  643. raise RunQemuError("Can't find rootfs: %s" % self.rootfs)
  644. def setup_pkkek1(self):
  645. """
  646. Extract from PEM certificate the Platform Key and first Key
  647. Exchange Key certificate string. The hypervisor needs to provide
  648. it in the Type 11 SMBIOS table
  649. """
  650. pemcert = '%s/%s' % (self.get('DEPLOY_DIR_IMAGE'), 'OvmfPkKek1.pem')
  651. try:
  652. with open(pemcert, 'r') as pemfile:
  653. key = pemfile.read().replace('\n', ''). \
  654. replace('-----BEGIN CERTIFICATE-----', ''). \
  655. replace('-----END CERTIFICATE-----', '')
  656. self.ovmf_secboot_pkkek1 = key
  657. except FileNotFoundError:
  658. raise RunQemuError("Can't open PEM certificate %s " % pemcert)
  659. def check_ovmf(self):
  660. """Check and set full path for OVMF firmware and variable file(s)."""
  661. for index, ovmf in enumerate(self.ovmf_bios):
  662. if os.path.exists(ovmf):
  663. continue
  664. for suffix in ('qcow2', 'bin'):
  665. path = '%s/%s.%s' % (self.get('DEPLOY_DIR_IMAGE'), ovmf, suffix)
  666. if os.path.exists(path):
  667. self.ovmf_bios[index] = path
  668. if ovmf.endswith('secboot'):
  669. self.setup_pkkek1()
  670. break
  671. else:
  672. raise RunQemuError("Can't find OVMF firmware: %s" % ovmf)
  673. def check_kernel(self):
  674. """Check and set kernel"""
  675. # The vm image doesn't need a kernel
  676. if self.fstype in self.vmtypes:
  677. return
  678. # See if the user supplied a KERNEL option
  679. if self.get('KERNEL'):
  680. self.kernel = self.get('KERNEL')
  681. # QB_DEFAULT_KERNEL is always a full file path
  682. kernel_name = os.path.basename(self.get('QB_DEFAULT_KERNEL'))
  683. # The user didn't want a kernel to be loaded
  684. if kernel_name == "none" and not self.kernel:
  685. return
  686. deploy_dir_image = self.get('DEPLOY_DIR_IMAGE')
  687. if not self.kernel:
  688. kernel_match_name = "%s/%s" % (deploy_dir_image, kernel_name)
  689. kernel_match_link = "%s/%s" % (deploy_dir_image, self.get('KERNEL_IMAGETYPE'))
  690. kernel_startswith = "%s/%s*" % (deploy_dir_image, self.get('KERNEL_IMAGETYPE'))
  691. globs = (kernel_match_name, kernel_match_link, kernel_startswith)
  692. self.kernel = get_first_file(globs)
  693. if not self.kernel:
  694. raise RunQemuError('KERNEL not found: %s, %s or %s' % globs)
  695. if not os.path.exists(self.kernel):
  696. raise RunQemuError("KERNEL %s not found" % self.kernel)
  697. def check_dtb(self):
  698. """Check and set dtb"""
  699. # Did the user specify a device tree?
  700. if self.get('DEVICE_TREE'):
  701. self.dtb = self.get('DEVICE_TREE')
  702. if not os.path.exists(self.dtb):
  703. raise RunQemuError('Specified DTB not found: %s' % self.dtb)
  704. return
  705. dtb = self.get('QB_DTB')
  706. if dtb:
  707. deploy_dir_image = self.get('DEPLOY_DIR_IMAGE')
  708. glob_match = "%s/%s" % (deploy_dir_image, dtb)
  709. glob_startswith = "%s/%s*" % (deploy_dir_image, dtb)
  710. glob_wild = "%s/*.dtb" % deploy_dir_image
  711. globs = (glob_match, glob_startswith, glob_wild)
  712. self.dtb = get_first_file(globs)
  713. if not os.path.exists(self.dtb):
  714. raise RunQemuError('DTB not found: %s, %s or %s' % globs)
  715. def check_bios(self):
  716. """Check and set bios"""
  717. # See if the user supplied a BIOS option
  718. if self.get('BIOS'):
  719. self.bios = self.get('BIOS')
  720. # QB_DEFAULT_BIOS is always a full file path
  721. bios_name = os.path.basename(self.get('QB_DEFAULT_BIOS'))
  722. # The user didn't want a bios to be loaded
  723. if (bios_name == "" or bios_name == "none") and not self.bios:
  724. return
  725. if not self.bios:
  726. deploy_dir_image = self.get('DEPLOY_DIR_IMAGE')
  727. self.bios = "%s/%s" % (deploy_dir_image, bios_name)
  728. if not self.bios:
  729. raise RunQemuError('BIOS not found: %s' % bios_match_name)
  730. if not os.path.exists(self.bios):
  731. raise RunQemuError("BIOS %s not found" % self.bios)
  732. def check_mem(self):
  733. """
  734. Both qemu and kernel needs memory settings, so check QB_MEM and set it
  735. for both.
  736. """
  737. s = re.search('-m +([0-9]+)', self.qemuparams)
  738. if s:
  739. self.set('QB_MEM', '-m %s' % s.group(1))
  740. elif not self.get('QB_MEM'):
  741. logger.info('QB_MEM is not set, use 256M by default')
  742. self.set('QB_MEM', '-m 256')
  743. # Check and remove M or m suffix
  744. qb_mem = self.get('QB_MEM')
  745. if qb_mem.endswith('M') or qb_mem.endswith('m'):
  746. qb_mem = qb_mem[:-1]
  747. # Add -m prefix it not present
  748. if not qb_mem.startswith('-m'):
  749. qb_mem = '-m %s' % qb_mem
  750. self.set('QB_MEM', qb_mem)
  751. mach = self.get('MACHINE')
  752. if not mach.startswith(('qemumips', 'qemux86', 'qemuloongarch64')):
  753. self.kernel_cmdline_script += ' mem=%s' % self.get('QB_MEM').replace('-m','').strip() + 'M'
  754. self.qemu_opt_script += ' %s' % self.get('QB_MEM')
  755. def check_tcpserial(self):
  756. if self.tcpserial_portnum:
  757. ports = self.tcpserial_portnum.split(':')
  758. port = ports[0]
  759. if self.get('QB_TCPSERIAL_OPT'):
  760. self.qemu_opt_script += ' ' + self.get('QB_TCPSERIAL_OPT').replace('@PORT@', port)
  761. else:
  762. self.qemu_opt_script += ' -serial tcp:127.0.0.1:%s,nodelay=on' % port
  763. if len(ports) > 1:
  764. for port in ports[1:]:
  765. self.qemu_opt_script += ' -serial tcp:127.0.0.1:%s,nodelay=on' % port
  766. def check_and_set(self):
  767. """Check configs sanity and set when needed"""
  768. self.validate_paths()
  769. if not self.slirp_enabled and not self.net_bridge:
  770. check_tun()
  771. # Check audio
  772. if self.audio_enabled:
  773. if not self.get('QB_AUDIO_DRV'):
  774. raise RunQemuError("QB_AUDIO_DRV is NULL, this board doesn't support audio")
  775. if not self.get('QB_AUDIO_OPT'):
  776. logger.warning('QB_AUDIO_OPT is NULL, you may need define it to make audio work')
  777. else:
  778. self.qemu_opt_script += ' %s' % self.get('QB_AUDIO_OPT')
  779. os.putenv('QEMU_AUDIO_DRV', self.get('QB_AUDIO_DRV'))
  780. else:
  781. os.putenv('QEMU_AUDIO_DRV', 'none')
  782. self.check_qemu_system()
  783. self.check_kvm()
  784. self.check_fstype()
  785. self.check_rootfs()
  786. self.check_ovmf()
  787. self.check_kernel()
  788. self.check_dtb()
  789. self.check_bios()
  790. self.check_mem()
  791. self.check_tcpserial()
  792. def read_qemuboot(self):
  793. if not self.qemuboot:
  794. if self.get('DEPLOY_DIR_IMAGE'):
  795. deploy_dir_image = self.get('DEPLOY_DIR_IMAGE')
  796. else:
  797. logger.warning("Can't find qemuboot conf file, DEPLOY_DIR_IMAGE is NULL!")
  798. return
  799. if self.rootfs and not os.path.exists(self.rootfs):
  800. # Lazy rootfs
  801. machine = self.get('MACHINE')
  802. if not machine:
  803. machine = os.path.basename(deploy_dir_image)
  804. if not self.get('IMAGE_LINK_NAME'):
  805. raise RunQemuError("IMAGE_LINK_NAME wasn't set to find corresponding .qemuboot.conf file")
  806. self.qemuboot = "%s/%s.qemuboot.conf" % (deploy_dir_image,
  807. self.get('IMAGE_LINK_NAME'))
  808. else:
  809. cmd = 'ls -t %s/*.qemuboot.conf' % deploy_dir_image
  810. logger.debug('Running %s...' % cmd)
  811. try:
  812. qbs = subprocess.check_output(cmd, shell=True).decode('utf-8')
  813. except subprocess.CalledProcessError as err:
  814. raise RunQemuError(err)
  815. if qbs:
  816. for qb in qbs.split():
  817. # Don't use initramfs when other choices unless fstype is ramfs
  818. if '-initramfs-' in os.path.basename(qb) and self.fstype != 'cpio.gz':
  819. continue
  820. self.qemuboot = qb
  821. break
  822. if not self.qemuboot:
  823. # Use the first one when no choice
  824. self.qemuboot = qbs.split()[0]
  825. self.qbconfload = True
  826. if not self.qemuboot:
  827. # If we haven't found a .qemuboot.conf at this point it probably
  828. # doesn't exist, continue without
  829. return
  830. if not os.path.exists(self.qemuboot):
  831. raise RunQemuError("Failed to find %s (wrong image name or BSP does not support running under qemu?)." % self.qemuboot)
  832. logger.debug('CONFFILE: %s' % self.qemuboot)
  833. cf = configparser.ConfigParser()
  834. cf.read(self.qemuboot)
  835. for k, v in cf.items('config_bsp'):
  836. k_upper = k.upper()
  837. if v.startswith("../"):
  838. v = os.path.abspath(os.path.dirname(self.qemuboot) + "/" + v)
  839. elif v == ".":
  840. v = os.path.dirname(self.qemuboot)
  841. self.set(k_upper, v)
  842. def validate_paths(self):
  843. """Ensure all relevant path variables are set"""
  844. # When we're started with a *.qemuboot.conf arg assume that image
  845. # artefacts are relative to that file, rather than in whatever
  846. # directory DEPLOY_DIR_IMAGE in the conf file points to.
  847. if self.qbconfload:
  848. imgdir = os.path.realpath(os.path.dirname(self.qemuboot))
  849. if imgdir != os.path.realpath(self.get('DEPLOY_DIR_IMAGE')):
  850. logger.info('Setting DEPLOY_DIR_IMAGE to folder containing %s (%s)' % (self.qemuboot, imgdir))
  851. self.set('DEPLOY_DIR_IMAGE', imgdir)
  852. # If the STAGING_*_NATIVE directories from the config file don't exist
  853. # and we're in a sourced OE build directory try to extract the paths
  854. # from `bitbake -e`
  855. havenative = os.path.exists(self.get('STAGING_DIR_NATIVE')) and \
  856. os.path.exists(self.get('STAGING_BINDIR_NATIVE'))
  857. if not havenative:
  858. if not self.bitbake_e:
  859. self.load_bitbake_env()
  860. if self.bitbake_e:
  861. native_vars = ['STAGING_DIR_NATIVE']
  862. for nv in native_vars:
  863. s = re.search('^%s="(.*)"' % nv, self.bitbake_e, re.M)
  864. if s and s.group(1) != self.get(nv):
  865. logger.info('Overriding conf file setting of %s to %s from Bitbake environment' % (nv, s.group(1)))
  866. self.set(nv, s.group(1))
  867. else:
  868. # when we're invoked from a running bitbake instance we won't
  869. # be able to call `bitbake -e`, then try:
  870. # - get OE_TMPDIR from environment and guess paths based on it
  871. # - get OECORE_NATIVE_SYSROOT from environment (for sdk)
  872. tmpdir = self.get('OE_TMPDIR')
  873. oecore_native_sysroot = self.get('OECORE_NATIVE_SYSROOT')
  874. if tmpdir:
  875. logger.info('Setting STAGING_DIR_NATIVE and STAGING_BINDIR_NATIVE relative to OE_TMPDIR (%s)' % tmpdir)
  876. hostos, _, _, _, machine = os.uname()
  877. buildsys = '%s-%s' % (machine, hostos.lower())
  878. staging_dir_native = '%s/sysroots/%s' % (tmpdir, buildsys)
  879. self.set('STAGING_DIR_NATIVE', staging_dir_native)
  880. elif oecore_native_sysroot:
  881. logger.info('Setting STAGING_DIR_NATIVE to OECORE_NATIVE_SYSROOT (%s)' % oecore_native_sysroot)
  882. self.set('STAGING_DIR_NATIVE', oecore_native_sysroot)
  883. if self.get('STAGING_DIR_NATIVE'):
  884. # we have to assume that STAGING_BINDIR_NATIVE is at usr/bin
  885. staging_bindir_native = '%s/usr/bin' % self.get('STAGING_DIR_NATIVE')
  886. logger.info('Setting STAGING_BINDIR_NATIVE to %s' % staging_bindir_native)
  887. self.set('STAGING_BINDIR_NATIVE', '%s/usr/bin' % self.get('STAGING_DIR_NATIVE'))
  888. def print_config(self):
  889. logoutput = ['Continuing with the following parameters:']
  890. if not self.fstype in self.vmtypes:
  891. logoutput.append('KERNEL: [%s]' % self.kernel)
  892. if self.bios:
  893. logoutput.append('BIOS: [%s]' % self.bios)
  894. if self.dtb:
  895. logoutput.append('DTB: [%s]' % self.dtb)
  896. logoutput.append('MACHINE: [%s]' % self.get('MACHINE'))
  897. try:
  898. fstype_flags = ' (' + ', '.join(self.fsinfo[self.fstype]) + ')'
  899. except KeyError:
  900. fstype_flags = ''
  901. logoutput.append('FSTYPE: [%s%s]' % (self.fstype, fstype_flags))
  902. if self.fstype == 'nfs':
  903. logoutput.append('NFS_DIR: [%s]' % self.rootfs)
  904. else:
  905. logoutput.append('ROOTFS: [%s]' % self.rootfs)
  906. if self.ovmf_bios:
  907. logoutput.append('OVMF: %s' % self.ovmf_bios)
  908. if (self.ovmf_secboot_pkkek1):
  909. logoutput.append('SECBOOT PKKEK1: [%s...]' % self.ovmf_secboot_pkkek1[0:100])
  910. logoutput.append('CONFFILE: [%s]' % self.qemuboot)
  911. logoutput.append('')
  912. logger.info('\n'.join(logoutput))
  913. def setup_nfs(self):
  914. if not self.nfs_server:
  915. if self.slirp_enabled:
  916. self.nfs_server = '10.0.2.2'
  917. else:
  918. self.nfs_server = '192.168.7.@GATEWAY@'
  919. nfsd_port = 3048 + self.nfs_instance
  920. lockdir = "/tmp/qemu-port-locks"
  921. self.make_lock_dir(lockdir)
  922. while not self.check_free_port('localhost', nfsd_port, lockdir):
  923. self.nfs_instance += 1
  924. nfsd_port += 1
  925. mountd_port = nfsd_port
  926. # Export vars for runqemu-export-rootfs
  927. export_dict = {
  928. 'NFS_INSTANCE': self.nfs_instance,
  929. 'NFSD_PORT': nfsd_port,
  930. 'MOUNTD_PORT': mountd_port,
  931. }
  932. for k, v in export_dict.items():
  933. # Use '%s' since they are integers
  934. os.putenv(k, '%s' % v)
  935. qb_nfsrootfs_extra_opt = self.get("QB_NFSROOTFS_EXTRA_OPT")
  936. if qb_nfsrootfs_extra_opt and not qb_nfsrootfs_extra_opt.startswith(","):
  937. qb_nfsrootfs_extra_opt = "," + qb_nfsrootfs_extra_opt
  938. self.unfs_opts="nfsvers=3,port=%s,tcp,mountport=%s%s" % (nfsd_port, mountd_port, qb_nfsrootfs_extra_opt)
  939. # Extract .tar.bz2 or .tar.bz if no nfs dir
  940. if not (self.rootfs and os.path.isdir(self.rootfs)):
  941. src_prefix = '%s/%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_LINK_NAME'))
  942. dest = "%s-nfsroot" % src_prefix
  943. if os.path.exists('%s.pseudo_state' % dest):
  944. logger.info('Use %s as NFS_DIR' % dest)
  945. self.rootfs = dest
  946. else:
  947. src = ""
  948. src1 = '%s.tar.bz2' % src_prefix
  949. src2 = '%s.tar.gz' % src_prefix
  950. if os.path.exists(src1):
  951. src = src1
  952. elif os.path.exists(src2):
  953. src = src2
  954. if not src:
  955. raise RunQemuError("No NFS_DIR is set, and can't find %s or %s to extract" % (src1, src2))
  956. logger.info('NFS_DIR not found, extracting %s to %s' % (src, dest))
  957. cmd = ('runqemu-extract-sdk', src, dest)
  958. logger.info('Running %s...' % str(cmd))
  959. if subprocess.call(cmd) != 0:
  960. raise RunQemuError('Failed to run %s' % str(cmd))
  961. self.rootfs = dest
  962. self.cleanup_files.append(self.rootfs)
  963. self.cleanup_files.append('%s.pseudo_state' % self.rootfs)
  964. # Start the userspace NFS server
  965. cmd = ('runqemu-export-rootfs', 'start', self.rootfs)
  966. logger.info('Running %s...' % str(cmd))
  967. if subprocess.call(cmd) != 0:
  968. raise RunQemuError('Failed to run %s' % str(cmd))
  969. self.nfs_running = True
  970. def setup_cmd(self):
  971. cmd = self.get('QB_SETUP_CMD')
  972. if cmd != '':
  973. logger.info('Running setup command %s' % str(cmd))
  974. if subprocess.call(cmd, shell=True) != 0:
  975. raise RunQemuError('Failed to run %s' % str(cmd))
  976. def setup_net_bridge(self):
  977. self.set('NETWORK_CMD', '-netdev bridge,br=%s,id=net0,helper=%s -device virtio-net-pci,netdev=net0 ' % (
  978. self.net_bridge, os.path.join(self.bindir_native, 'qemu-oe-bridge-helper')))
  979. def make_lock_dir(self, lockdir):
  980. if not os.path.exists(lockdir):
  981. # There might be a race issue when multi runqemu processess are
  982. # running at the same time.
  983. try:
  984. os.mkdir(lockdir)
  985. os.chmod(lockdir, 0o777)
  986. except FileExistsError:
  987. pass
  988. return
  989. def setup_slirp(self):
  990. """Setup user networking"""
  991. if self.fstype == 'nfs':
  992. self.setup_nfs()
  993. netconf = " " + self.cmdline_ip_slirp
  994. logger.info("Network configuration:%s", netconf)
  995. self.kernel_cmdline_script += netconf
  996. # Port mapping
  997. hostfwd = ",hostfwd=tcp:127.0.0.1:2222-:22,hostfwd=tcp:127.0.0.1:2323-:23"
  998. qb_slirp_opt_default = "-netdev user,id=net0%s,tftp=%s" % (hostfwd, self.get('DEPLOY_DIR_IMAGE'))
  999. qb_slirp_opt = self.get('QB_SLIRP_OPT') or qb_slirp_opt_default
  1000. # Figure out the port
  1001. ports = re.findall('hostfwd=[^-]*:([0-9]+)-[^,-]*', qb_slirp_opt)
  1002. ports = [int(i) for i in ports]
  1003. mac = 2
  1004. lockdir = "/tmp/qemu-port-locks"
  1005. self.make_lock_dir(lockdir)
  1006. # Find a free port to avoid conflicts
  1007. for p in ports[:]:
  1008. p_new = p
  1009. while not self.check_free_port('localhost', p_new, lockdir):
  1010. p_new += 1
  1011. mac += 1
  1012. while p_new in ports:
  1013. p_new += 1
  1014. mac += 1
  1015. if p != p_new:
  1016. ports.append(p_new)
  1017. qb_slirp_opt = re.sub(':%s-' % p, ':%s-' % p_new, qb_slirp_opt)
  1018. logger.info("Port forward changed: %s -> %s" % (p, p_new))
  1019. mac = "%s%02x" % (self.mac_slirp, mac)
  1020. self.set('NETWORK_CMD', '%s %s' % (self.network_device.replace('@MAC@', mac), qb_slirp_opt))
  1021. # Print out port foward
  1022. hostfwd = re.findall('(hostfwd=[^,]*)', qb_slirp_opt)
  1023. if hostfwd:
  1024. logger.info('Port forward: %s' % ' '.join(hostfwd))
  1025. def setup_tap(self):
  1026. """Setup tap"""
  1027. # This file is created when runqemu-gen-tapdevs creates a bank of tap
  1028. # devices, indicating that the user should not bring up new ones using
  1029. # sudo.
  1030. nosudo_flag = '/etc/runqemu-nosudo'
  1031. self.qemuifup = shutil.which('runqemu-ifup')
  1032. self.qemuifdown = shutil.which('runqemu-ifdown')
  1033. ip = shutil.which('ip')
  1034. lockdir = "/tmp/qemu-tap-locks"
  1035. if not (self.qemuifup and self.qemuifdown and ip):
  1036. logger.error("runqemu-ifup: %s" % self.qemuifup)
  1037. logger.error("runqemu-ifdown: %s" % self.qemuifdown)
  1038. logger.error("ip: %s" % ip)
  1039. raise OEPathError("runqemu-ifup, runqemu-ifdown or ip not found")
  1040. self.make_lock_dir(lockdir)
  1041. cmd = (ip, 'link')
  1042. logger.debug('Running %s...' % str(cmd))
  1043. ip_link = subprocess.check_output(cmd).decode('utf-8')
  1044. # Matches line like: 6: tap0: <foo>
  1045. oe_tap_name = 'tap'
  1046. if 'OE_TAP_NAME' in os.environ:
  1047. oe_tap_name = os.environ['OE_TAP_NAME']
  1048. tap_re = '^[0-9]+: +(' + oe_tap_name + '[0-9]+): <.*'
  1049. possibles = re.findall(tap_re, ip_link, re.M)
  1050. tap = ""
  1051. for p in possibles:
  1052. lockfile = os.path.join(lockdir, p)
  1053. if os.path.exists('%s.skip' % lockfile):
  1054. logger.info('Found %s.skip, skipping %s' % (lockfile, p))
  1055. continue
  1056. self.taplock = lockfile + '.lock'
  1057. if self.acquire_taplock(error=False):
  1058. tap = p
  1059. logger.info("Using preconfigured tap device %s" % tap)
  1060. logger.info("If this is not intended, touch %s.skip to make runqemu skip %s." %(lockfile, tap))
  1061. break
  1062. if not tap:
  1063. if os.path.exists(nosudo_flag):
  1064. logger.error("Error: There are no available tap devices to use for networking,")
  1065. logger.error("and I see %s exists, so I am not going to try creating" % nosudo_flag)
  1066. raise RunQemuError("a new one with sudo.")
  1067. gid = os.getgid()
  1068. uid = os.getuid()
  1069. logger.info("Setting up tap interface under sudo")
  1070. cmd = ('sudo', self.qemuifup, str(gid))
  1071. for _ in range(5):
  1072. try:
  1073. tap = subprocess.check_output(cmd).decode('utf-8').strip()
  1074. except subprocess.CalledProcessError as e:
  1075. logger.error('Setting up tap device failed:\n%s\nRun runqemu-gen-tapdevs to manually create one.' % str(e))
  1076. sys.exit(1)
  1077. lockfile = os.path.join(lockdir, tap)
  1078. self.taplock = lockfile + '.lock'
  1079. if self.acquire_taplock():
  1080. self.cleantap = True
  1081. logger.debug('Created tap: %s' % tap)
  1082. break
  1083. else:
  1084. tap = None
  1085. if not tap:
  1086. logger.error("Failed to setup tap device. Run runqemu-gen-tapdevs to manually create.")
  1087. sys.exit(1)
  1088. self.tap = tap
  1089. tapnum = int(tap[len(oe_tap_name):])
  1090. gateway = tapnum * 2 + 1
  1091. client = gateway + 1
  1092. if self.fstype == 'nfs':
  1093. self.setup_nfs()
  1094. netconf = " " + self.cmdline_ip_tap
  1095. netconf = netconf.replace('@CLIENT@', str(client))
  1096. netconf = netconf.replace('@GATEWAY@', str(gateway))
  1097. self.nfs_server = self.nfs_server.replace('@GATEWAY@', str(gateway))
  1098. logger.info("Network configuration:%s", netconf)
  1099. self.kernel_cmdline_script += netconf
  1100. mac = "%s%02x" % (self.mac_tap, client)
  1101. qb_tap_opt = self.get('QB_TAP_OPT')
  1102. if qb_tap_opt:
  1103. qemu_tap_opt = qb_tap_opt.replace('@TAP@', tap)
  1104. else:
  1105. qemu_tap_opt = "-netdev tap,id=net0,ifname=%s,script=no,downscript=no" % (self.tap)
  1106. if self.vhost_enabled:
  1107. qemu_tap_opt += ',vhost=on'
  1108. self.set('NETWORK_CMD', '%s %s' % (self.network_device.replace('@MAC@', mac), qemu_tap_opt))
  1109. def setup_network(self):
  1110. if self.nonetwork or self.get('QB_NET') == 'none':
  1111. self.set('NETWORK_CMD', '-nic none')
  1112. return
  1113. if sys.stdin.isatty():
  1114. self.saved_stty = subprocess.check_output(("stty", "-g")).decode('utf-8').strip()
  1115. self.network_device = self.get('QB_NETWORK_DEVICE') or self.network_device
  1116. if self.net_bridge:
  1117. self.setup_net_bridge()
  1118. elif self.slirp_enabled:
  1119. self.cmdline_ip_slirp = self.get('QB_CMDLINE_IP_SLIRP') or self.cmdline_ip_slirp
  1120. self.setup_slirp()
  1121. else:
  1122. self.cmdline_ip_tap = self.get('QB_CMDLINE_IP_TAP') or self.cmdline_ip_tap
  1123. self.setup_tap()
  1124. def setup_rootfs(self):
  1125. if self.get('QB_ROOTFS') == 'none':
  1126. return
  1127. if 'wic.' in self.fstype:
  1128. self.fstype = self.fstype[4:]
  1129. rootfs_format = self.fstype if self.fstype in ('vmdk', 'vhd', 'vhdx', 'qcow2', 'vdi') else 'raw'
  1130. tmpfsdir = os.environ.get("RUNQEMU_TMPFS_DIR", None)
  1131. if self.snapshot and tmpfsdir:
  1132. newrootfs = os.path.join(tmpfsdir, os.path.basename(self.rootfs)) + "." + str(os.getpid())
  1133. logger.info("Copying rootfs to %s" % newrootfs)
  1134. copy_start = time.time()
  1135. shutil.copyfile(self.rootfs, newrootfs)
  1136. logger.info("Copy done in %s seconds" % (time.time() - copy_start))
  1137. self.rootfs = newrootfs
  1138. # Don't need a second copy now!
  1139. self.snapshot = False
  1140. self.cleanup_files.append(newrootfs)
  1141. qb_rootfs_opt = self.get('QB_ROOTFS_OPT')
  1142. if qb_rootfs_opt:
  1143. self.rootfs_options = qb_rootfs_opt.replace('@ROOTFS@', self.rootfs)
  1144. else:
  1145. self.rootfs_options = '-drive file=%s,if=virtio,format=%s' % (self.rootfs, rootfs_format)
  1146. qb_rootfs_extra_opt = self.get("QB_ROOTFS_EXTRA_OPT")
  1147. if qb_rootfs_extra_opt and not qb_rootfs_extra_opt.startswith(","):
  1148. qb_rootfs_extra_opt = "," + qb_rootfs_extra_opt
  1149. if self.fstype in ('cpio.gz', 'cpio'):
  1150. self.kernel_cmdline = 'root=/dev/ram0 rw debugshell'
  1151. self.rootfs_options = '-initrd %s' % self.rootfs
  1152. else:
  1153. vm_drive = ''
  1154. if self.fstype in self.vmtypes:
  1155. if self.fstype == 'iso':
  1156. vm_drive = '-drive file=%s,if=virtio,media=cdrom' % self.rootfs
  1157. elif self.get('QB_DRIVE_TYPE'):
  1158. drive_type = self.get('QB_DRIVE_TYPE')
  1159. if drive_type.startswith("/dev/sd"):
  1160. logger.info('Using scsi drive')
  1161. vm_drive = '-drive if=none,id=hd,file=%s,format=%s -device virtio-scsi-pci,id=scsi -device scsi-hd,drive=hd%s' \
  1162. % (self.rootfs, rootfs_format, qb_rootfs_extra_opt)
  1163. elif drive_type.startswith("/dev/hd"):
  1164. logger.info('Using ide drive')
  1165. vm_drive = "-drive file=%s,format=%s" % (self.rootfs, rootfs_format)
  1166. elif drive_type.startswith("/dev/vdb"):
  1167. logger.info('Using block virtio drive');
  1168. vm_drive = '-drive id=disk0,file=%s,if=none,format=%s -device virtio-blk-device,drive=disk0%s' \
  1169. % (self.rootfs, rootfs_format,qb_rootfs_extra_opt)
  1170. else:
  1171. # virtio might have been selected explicitly (just use it), or
  1172. # is used as fallback (then warn about that).
  1173. if not drive_type.startswith("/dev/vd"):
  1174. logger.warning("Unknown QB_DRIVE_TYPE: %s" % drive_type)
  1175. logger.warning("Failed to figure out drive type, consider define or fix QB_DRIVE_TYPE")
  1176. logger.warning('Trying to use virtio block drive')
  1177. vm_drive = '-drive if=virtio,file=%s,format=%s' % (self.rootfs, rootfs_format)
  1178. # All branches above set vm_drive.
  1179. self.rootfs_options = vm_drive
  1180. if not self.fstype in self.vmtypes:
  1181. self.rootfs_options += ' -no-reboot'
  1182. # By default, ' rw' is appended to QB_KERNEL_ROOT unless either ro or rw is explicitly passed.
  1183. qb_kernel_root = self.get('QB_KERNEL_ROOT')
  1184. qb_kernel_root_l = qb_kernel_root.split()
  1185. if not ('ro' in qb_kernel_root_l or 'rw' in qb_kernel_root_l):
  1186. qb_kernel_root += ' rw'
  1187. self.kernel_cmdline = 'root=%s' % qb_kernel_root
  1188. if self.fstype == 'nfs':
  1189. self.rootfs_options = ''
  1190. k_root = '/dev/nfs nfsroot=%s:%s,%s' % (self.nfs_server, os.path.abspath(self.rootfs), self.unfs_opts)
  1191. self.kernel_cmdline = 'root=%s rw' % k_root
  1192. if self.fstype == 'none':
  1193. self.rootfs_options = ''
  1194. self.set('ROOTFS_OPTIONS', self.rootfs_options)
  1195. def guess_qb_system(self):
  1196. """attempt to determine the appropriate qemu-system binary"""
  1197. mach = self.get('MACHINE')
  1198. if not mach:
  1199. search = '.*(qemux86-64|qemux86|qemuarm64|qemuarm|qemuloongarch64|qemumips64|qemumips64el|qemumipsel|qemumips|qemuppc).*'
  1200. if self.rootfs:
  1201. match = re.match(search, self.rootfs)
  1202. if match:
  1203. mach = match.group(1)
  1204. elif self.kernel:
  1205. match = re.match(search, self.kernel)
  1206. if match:
  1207. mach = match.group(1)
  1208. if not mach:
  1209. return None
  1210. if mach == 'qemuarm':
  1211. qbsys = 'arm'
  1212. elif mach == 'qemuarm64':
  1213. qbsys = 'aarch64'
  1214. elif mach == 'qemux86':
  1215. qbsys = 'i386'
  1216. elif mach == 'qemux86-64':
  1217. qbsys = 'x86_64'
  1218. elif mach == 'qemuppc':
  1219. qbsys = 'ppc'
  1220. elif mach == 'qemuloongarch64':
  1221. qbsys = 'loongarch64'
  1222. elif mach == 'qemumips':
  1223. qbsys = 'mips'
  1224. elif mach == 'qemumips64':
  1225. qbsys = 'mips64'
  1226. elif mach == 'qemumipsel':
  1227. qbsys = 'mipsel'
  1228. elif mach == 'qemumips64el':
  1229. qbsys = 'mips64el'
  1230. elif mach == 'qemuriscv64':
  1231. qbsys = 'riscv64'
  1232. elif mach == 'qemuriscv32':
  1233. qbsys = 'riscv32'
  1234. else:
  1235. logger.error("Unable to determine QEMU PC System emulator for %s machine." % mach)
  1236. logger.error("As %s is not among valid QEMU machines such as," % mach)
  1237. logger.error("qemux86-64, qemux86, qemuarm64, qemuarm, qemumips64, qemumips64el, qemumipsel, qemumips, qemuppc")
  1238. raise RunQemuError("Set qb_system_name with suitable QEMU PC System emulator in .*qemuboot.conf.")
  1239. return 'qemu-system-%s' % qbsys
  1240. def check_qemu_system(self):
  1241. qemu_system = self.get('QB_SYSTEM_NAME')
  1242. if not qemu_system:
  1243. qemu_system = self.guess_qb_system()
  1244. if not qemu_system:
  1245. raise RunQemuError("Failed to boot, QB_SYSTEM_NAME is NULL!")
  1246. self.qemu_system = qemu_system
  1247. def check_render_nodes(self):
  1248. 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."""
  1249. try:
  1250. content = os.listdir("/dev/dri")
  1251. nodes = [i for i in content if i.startswith('renderD')]
  1252. if len(nodes) == 0:
  1253. raise RunQemuError("No render nodes found in /dev/dri/: %s. %s" %(content, render_hint))
  1254. for n in nodes:
  1255. try:
  1256. with open(os.path.join("/dev/dri", n), "w") as f:
  1257. f.close()
  1258. break
  1259. except IOError:
  1260. pass
  1261. else:
  1262. 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))
  1263. except FileNotFoundError:
  1264. raise RunQemuError("/dev/dri directory does not exist; no render nodes available on this machine. %s" %(render_hint))
  1265. def setup_guest_agent(self):
  1266. if self.guest_agent == True:
  1267. self.qemu_opt += ' -chardev socket,path=' + self.guest_agent_sockpath + ',server,nowait,id=qga0 '
  1268. self.qemu_opt += ' -device virtio-serial '
  1269. self.qemu_opt += ' -device virtserialport,chardev=qga0,name=org.qemu.guest_agent.0 '
  1270. def setup_qmp(self):
  1271. if self.qmp:
  1272. self.qemu_opt += " -qmp %s,server,nowait" % self.qmp
  1273. def setup_vga(self):
  1274. if self.nographic == True:
  1275. if self.sdl == True:
  1276. raise RunQemuError('Option nographic makes no sense alongside the sdl option.')
  1277. if self.gtk == True:
  1278. raise RunQemuError('Option nographic makes no sense alongside the gtk option.')
  1279. self.qemu_opt += ' -nographic'
  1280. if self.novga == True:
  1281. self.qemu_opt += ' -vga none'
  1282. return
  1283. if (self.gl_es == True or self.gl == True) and (self.sdl == False and self.gtk == False):
  1284. raise RunQemuError('Option gl/gl-es needs gtk or sdl option.')
  1285. # If we have no display option, we autodetect based upon what qemu supports. We
  1286. # need our font setup and show-cusor below so we need to see what qemu --help says
  1287. # is supported so we can pass our correct config in.
  1288. if not self.nographic and not self.sdl and not self.gtk and not self.publicvnc and not self.egl_headless == True:
  1289. output = subprocess.check_output([self.qemu_bin, "--help"], universal_newlines=True, env=self.qemu_environ)
  1290. if "-display gtk" in output:
  1291. self.gtk = True
  1292. elif "-display sdl" in output:
  1293. self.sdl = True
  1294. else:
  1295. self.qemu_opt += ' -display none'
  1296. if self.sdl == True or self.gtk == True or self.egl_headless == True:
  1297. if self.qemu_system.endswith(('i386', 'x86_64')):
  1298. if self.gl or self.gl_es or self.egl_headless:
  1299. self.qemu_opt += ' -device virtio-vga-gl '
  1300. else:
  1301. self.qemu_opt += ' -device virtio-vga '
  1302. self.qemu_opt += ' -display '
  1303. if self.egl_headless == True:
  1304. self.check_render_nodes()
  1305. self.set_dri_path()
  1306. self.qemu_opt += 'egl-headless,'
  1307. else:
  1308. if self.sdl == True:
  1309. self.qemu_opt += 'sdl,'
  1310. elif self.gtk == True:
  1311. self.qemu_environ['FONTCONFIG_PATH'] = '/etc/fonts'
  1312. self.qemu_opt += 'gtk,'
  1313. if self.gl == True:
  1314. self.set_dri_path()
  1315. self.qemu_opt += 'gl=on,'
  1316. elif self.gl_es == True:
  1317. self.set_dri_path()
  1318. self.qemu_opt += 'gl=es,'
  1319. self.qemu_opt += 'show-cursor=on'
  1320. self.qemu_opt += ' %s' %self.get('QB_GRAPHICS')
  1321. def setup_serial(self):
  1322. # Setup correct kernel command line for serial
  1323. if self.get('SERIAL_CONSOLES') and (self.serialstdio == True or self.serialconsole == True or self.nographic == True or self.tcpserial_portnum):
  1324. for entry in self.get('SERIAL_CONSOLES').split(' '):
  1325. self.kernel_cmdline_script += ' console=%s' %entry.split(';')[1]
  1326. # We always wants ttyS0 and ttyS1 in qemu machines (see SERIAL_CONSOLES).
  1327. # If no serial or serialtcp options were specified, only ttyS0 is created
  1328. # and sysvinit shows an error trying to enable ttyS1:
  1329. # INIT: Id "S1" respawning too fast: disabled for 5 minutes
  1330. serial_num = len(re.findall("(^| )-serial ", self.qemu_opt))
  1331. # Assume if the user passed serial options, they know what they want
  1332. # and pad to two devices
  1333. if serial_num == 1:
  1334. self.qemu_opt += " -serial null"
  1335. elif serial_num >= 2:
  1336. return
  1337. if self.serialstdio == True or self.nographic == True:
  1338. self.qemu_opt += " -serial mon:stdio"
  1339. else:
  1340. self.qemu_opt += " -serial mon:vc"
  1341. if self.serialconsole:
  1342. if sys.stdin.isatty():
  1343. subprocess.check_call(("stty", "intr", "^]"))
  1344. logger.info("Interrupt character is '^]'")
  1345. self.qemu_opt += " %s" % self.get("QB_SERIAL_OPT")
  1346. serial_num = len(re.findall("(^| )-serial ", self.qemu_opt))
  1347. if serial_num < 2:
  1348. self.qemu_opt += " -serial null"
  1349. def find_qemu(self):
  1350. qemu_bin = os.path.join(self.bindir_native, self.qemu_system)
  1351. # It is possible to have qemu-native in ASSUME_PROVIDED, and it won't
  1352. # find QEMU in sysroot, it needs to use host's qemu.
  1353. if not os.path.exists(qemu_bin):
  1354. logger.info("QEMU binary not found in %s, trying host's QEMU" % qemu_bin)
  1355. for path in (os.environ['PATH'] or '').split(':'):
  1356. qemu_bin_tmp = os.path.join(path, self.qemu_system)
  1357. logger.info("Trying: %s" % qemu_bin_tmp)
  1358. if os.path.exists(qemu_bin_tmp):
  1359. qemu_bin = qemu_bin_tmp
  1360. if not os.path.isabs(qemu_bin):
  1361. qemu_bin = os.path.abspath(qemu_bin)
  1362. logger.info("Using host's QEMU: %s" % qemu_bin)
  1363. break
  1364. if not os.access(qemu_bin, os.X_OK):
  1365. raise OEPathError("No QEMU binary '%s' could be found" % qemu_bin)
  1366. self.qemu_bin = qemu_bin
  1367. def setup_final(self):
  1368. self.find_qemu()
  1369. 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')))
  1370. for ovmf in self.ovmf_bios:
  1371. format = ovmf.rsplit('.', 1)[-1]
  1372. if format == "bin":
  1373. format = "raw"
  1374. self.qemu_opt += ' -drive if=pflash,format=%s,file=%s' % (format, ovmf)
  1375. self.qemu_opt += ' ' + self.qemu_opt_script
  1376. if self.ovmf_secboot_pkkek1:
  1377. # Provide the Platform Key and first Key Exchange Key certificate as an
  1378. # OEM string in the SMBIOS Type 11 table. Prepend the certificate string
  1379. # with "application prefix" of the EnrollDefaultKeys.efi application
  1380. self.qemu_opt += ' -smbios type=11,value=4e32566d-8e9e-4f52-81d3-5bb9715f9727:' \
  1381. + self.ovmf_secboot_pkkek1
  1382. # Append qemuparams to override previous settings
  1383. if self.qemuparams:
  1384. self.qemu_opt += ' ' + self.qemuparams
  1385. if self.snapshot:
  1386. self.qemu_opt += " -snapshot"
  1387. self.setup_guest_agent()
  1388. self.setup_qmp()
  1389. self.setup_serial()
  1390. self.setup_vga()
  1391. def start_qemu(self):
  1392. import shlex
  1393. if self.kernel:
  1394. kernel_opts = "-kernel %s" % (self.kernel)
  1395. if self.get('QB_KERNEL_CMDLINE') == "none":
  1396. if self.bootparams:
  1397. kernel_opts += " -append '%s'" % (self.bootparams)
  1398. else:
  1399. kernel_opts += " -append '%s %s %s %s'" % (self.kernel_cmdline,
  1400. self.kernel_cmdline_script, self.get('QB_KERNEL_CMDLINE_APPEND'),
  1401. self.bootparams)
  1402. if self.dtb:
  1403. kernel_opts += " -dtb %s" % self.dtb
  1404. else:
  1405. kernel_opts = ""
  1406. if self.bios:
  1407. self.qemu_opt += " -bios %s" % self.bios
  1408. cmd = "%s %s" % (self.qemu_opt, kernel_opts)
  1409. cmds = shlex.split(cmd)
  1410. logger.info('Running %s\n' % cmd)
  1411. with open('/proc/uptime', 'r') as f:
  1412. uptime_seconds = f.readline().split()[0]
  1413. logger.info('Host uptime: %s\n' % uptime_seconds)
  1414. pass_fds = []
  1415. if self.taplock_descriptor:
  1416. pass_fds = [self.taplock_descriptor.fileno()]
  1417. if len(self.portlocks):
  1418. for descriptor in self.portlocks.values():
  1419. pass_fds.append(descriptor.fileno())
  1420. process = subprocess.Popen(cmds, stderr=subprocess.PIPE, pass_fds=pass_fds, env=self.qemu_environ)
  1421. self.qemuprocess = process
  1422. retcode = process.wait()
  1423. if retcode:
  1424. if retcode == -signal.SIGTERM:
  1425. logger.info("Qemu terminated by SIGTERM")
  1426. else:
  1427. logger.error("Failed to run qemu: %s", process.stderr.read().decode())
  1428. def cleanup_cmd(self):
  1429. cmd = self.get('QB_CLEANUP_CMD')
  1430. if cmd != '':
  1431. logger.info('Running cleanup command %s' % str(cmd))
  1432. if subprocess.call(cmd, shell=True) != 0:
  1433. raise RunQemuError('Failed to run %s' % str(cmd))
  1434. def cleanup(self):
  1435. if self.cleaned:
  1436. return
  1437. # avoid dealing with SIGTERM when cleanup function is running
  1438. signal.signal(signal.SIGTERM, signal.SIG_IGN)
  1439. logger.info("Cleaning up")
  1440. if self.qemuprocess:
  1441. try:
  1442. # give it some time to shut down, ignore return values and output
  1443. self.qemuprocess.send_signal(signal.SIGTERM)
  1444. self.qemuprocess.communicate(timeout=5)
  1445. except subprocess.TimeoutExpired:
  1446. self.qemuprocess.kill()
  1447. with open('/proc/uptime', 'r') as f:
  1448. uptime_seconds = f.readline().split()[0]
  1449. logger.info('Host uptime: %s\n' % uptime_seconds)
  1450. if self.cleantap:
  1451. cmd = ('sudo', self.qemuifdown, self.tap)
  1452. logger.debug('Running %s' % str(cmd))
  1453. subprocess.check_call(cmd)
  1454. self.release_taplock()
  1455. if self.nfs_running:
  1456. logger.info("Shutting down the userspace NFS server...")
  1457. cmd = ("runqemu-export-rootfs", "stop", self.rootfs)
  1458. logger.debug('Running %s' % str(cmd))
  1459. subprocess.check_call(cmd)
  1460. self.release_portlock()
  1461. if self.saved_stty:
  1462. subprocess.check_call(("stty", self.saved_stty))
  1463. if self.cleanup_files:
  1464. for ent in self.cleanup_files:
  1465. logger.info('Removing %s' % ent)
  1466. if os.path.isfile(ent):
  1467. os.remove(ent)
  1468. else:
  1469. shutil.rmtree(ent)
  1470. # Deliberately ignore the return code of 'tput smam'.
  1471. subprocess.call(["tput", "smam"])
  1472. self.cleaned = True
  1473. def run_bitbake_env(self, mach=None, target=''):
  1474. bitbake = shutil.which('bitbake')
  1475. if not bitbake:
  1476. return
  1477. if not mach:
  1478. mach = self.get('MACHINE')
  1479. multiconfig = self.get('MULTICONFIG')
  1480. if multiconfig:
  1481. multiconfig = "mc:%s" % multiconfig
  1482. if mach:
  1483. cmd = 'MACHINE=%s bitbake -e %s %s' % (mach, multiconfig, target)
  1484. else:
  1485. cmd = 'bitbake -e %s %s' % (multiconfig, target)
  1486. logger.info('Running %s...' % cmd)
  1487. try:
  1488. return subprocess.check_output(cmd, shell=True).decode('utf-8')
  1489. except subprocess.CalledProcessError as err:
  1490. 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')))
  1491. # need something with IMAGE_NAME_SUFFIX/IMAGE_LINK_NAME defined (kernel also inherits image-artifact-names.bbclass)
  1492. target = 'virtual/kernel'
  1493. if mach:
  1494. cmd = 'MACHINE=%s bitbake -e %s %s' % (mach, multiconfig, target)
  1495. else:
  1496. cmd = 'bitbake -e %s %s' % (multiconfig, target)
  1497. try:
  1498. return subprocess.check_output(cmd, shell=True).decode('utf-8')
  1499. except subprocess.CalledProcessError as err:
  1500. logger.warning("Couldn't run '%s' to gather environment information, giving up with 'bitbake -e':\n%s" % (cmd, err.output.decode('utf-8')))
  1501. return ''
  1502. def load_bitbake_env(self, mach=None, target=None):
  1503. if self.bitbake_e:
  1504. return
  1505. self.bitbake_e = self.run_bitbake_env(mach=mach, target=target)
  1506. def validate_combos(self):
  1507. if (self.fstype in self.vmtypes) and self.kernel:
  1508. raise RunQemuError("%s doesn't need kernel %s!" % (self.fstype, self.kernel))
  1509. @property
  1510. def bindir_native(self):
  1511. result = self.get('STAGING_BINDIR_NATIVE')
  1512. if result and os.path.exists(result):
  1513. return result
  1514. cmd = ['bitbake', '-e']
  1515. multiconfig = self.get('MULTICONFIG')
  1516. if multiconfig:
  1517. cmd.append('mc:%s:qemu-helper-native' % multiconfig)
  1518. else:
  1519. cmd.append('qemu-helper-native')
  1520. logger.info('Running %s...' % str(cmd))
  1521. out = subprocess.check_output(cmd).decode('utf-8')
  1522. match = re.search('^STAGING_BINDIR_NATIVE="(.*)"', out, re.M)
  1523. if match:
  1524. result = match.group(1)
  1525. if os.path.exists(result):
  1526. self.set('STAGING_BINDIR_NATIVE', result)
  1527. return result
  1528. raise RunQemuError("Native sysroot directory %s doesn't exist" % result)
  1529. else:
  1530. raise RunQemuError("Can't find STAGING_BINDIR_NATIVE in '%s' output" % str(cmd))
  1531. def main():
  1532. if "help" in sys.argv or '-h' in sys.argv or '--help' in sys.argv:
  1533. print_usage()
  1534. return 0
  1535. try:
  1536. config = BaseConfig()
  1537. renice = os.path.expanduser("~/bin/runqemu-renice")
  1538. if os.path.exists(renice):
  1539. logger.info('Using %s to renice' % renice)
  1540. subprocess.check_call([renice, str(os.getpid())])
  1541. def sigterm_handler(signum, frame):
  1542. logger.info("Received signal: %s" % (signum))
  1543. config.cleanup()
  1544. signal.signal(signal.SIGTERM, sigterm_handler)
  1545. config.check_args()
  1546. config.read_qemuboot()
  1547. config.check_and_set()
  1548. # Check whether the combos is valid or not
  1549. config.validate_combos()
  1550. config.print_config()
  1551. config.setup_network()
  1552. config.setup_rootfs()
  1553. config.setup_final()
  1554. config.setup_cmd()
  1555. config.start_qemu()
  1556. except RunQemuError as err:
  1557. logger.error(err)
  1558. return 1
  1559. except Exception as err:
  1560. import traceback
  1561. traceback.print_exc()
  1562. return 1
  1563. finally:
  1564. config.cleanup_cmd()
  1565. config.cleanup()
  1566. if __name__ == "__main__":
  1567. sys.exit(main())