runqemu 57 KB

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