blob: 39bed038d5aadcb2da0c1e44166a9f93cf89504f [file] [log] [blame]
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001#!/usr/bin/env python3
2
Patrick Williamsc124f4f2015-09-15 14:41:29 -05003# Handle running OE images standalone with QEMU
4#
5# Copyright (C) 2006-2011 Linux Foundation
Patrick Williamsc0f7c042017-02-23 20:41:17 -06006# Copyright (c) 2016 Wind River Systems, Inc.
Patrick Williamsc124f4f2015-09-15 14:41:29 -05007#
Brad Bishopc342db32019-05-15 21:57:59 -04008# SPDX-License-Identifier: GPL-2.0-only
Patrick Williamsc124f4f2015-09-15 14:41:29 -05009#
Patrick Williamsc124f4f2015-09-15 14:41:29 -050010
Patrick Williamsc0f7c042017-02-23 20:41:17 -060011import os
12import sys
13import logging
14import subprocess
15import re
16import fcntl
17import shutil
18import glob
19import configparser
Brad Bishop004d4992018-10-02 23:54:45 +020020import signal
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050021
Brad Bishopd7bf8c12018-02-25 22:55:05 -050022class RunQemuError(Exception):
23 """Custom exception to raise on known errors."""
24 pass
25
26class OEPathError(RunQemuError):
Patrick Williamsc0f7c042017-02-23 20:41:17 -060027 """Custom Exception to give better guidance on missing binaries"""
28 def __init__(self, message):
Brad Bishopd7bf8c12018-02-25 22:55:05 -050029 super().__init__("In order for this script to dynamically infer paths\n \
Patrick Williamsc0f7c042017-02-23 20:41:17 -060030kernels or filesystem images, you either need bitbake in your PATH\n \
31or to source oe-init-build-env before running this script.\n\n \
32Dynamic path inference can be avoided by passing a *.qemuboot.conf to\n \
Brad Bishopd7bf8c12018-02-25 22:55:05 -050033runqemu, i.e. `runqemu /path/to/my-image-name.qemuboot.conf`\n\n %s" % message)
Patrick Williamsc0f7c042017-02-23 20:41:17 -060034
35
36def create_logger():
37 logger = logging.getLogger('runqemu')
38 logger.setLevel(logging.INFO)
39
40 # create console handler and set level to debug
41 ch = logging.StreamHandler()
Brad Bishopd7bf8c12018-02-25 22:55:05 -050042 ch.setLevel(logging.DEBUG)
Patrick Williamsc0f7c042017-02-23 20:41:17 -060043
44 # create formatter
45 formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
46
47 # add formatter to ch
48 ch.setFormatter(formatter)
49
50 # add ch to logger
51 logger.addHandler(ch)
52
53 return logger
54
55logger = create_logger()
56
57def print_usage():
58 print("""
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050059Usage: you can run this script with any valid combination
60of the following environment variables (in any order):
61 KERNEL - the kernel image file to use
62 ROOTFS - the rootfs image file or nfsroot directory to use
Brad Bishop316dfdd2018-06-25 12:45:53 -040063 DEVICE_TREE - the device tree blob to use
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050064 MACHINE - the machine name (optional, autodetected from KERNEL filename if unspecified)
65 Simplified QEMU command-line options can be passed with:
Patrick Williamsc0f7c042017-02-23 20:41:17 -060066 nographic - disable video console
Brad Bishop19323692019-04-05 15:28:33 -040067 sdl - choose the SDL frontend instead of the Gtk+ default
68 gtk-gl - enable virgl-based GL acceleration using Gtk+ frontend
69 gtk-gl-es - enable virgl-based GL acceleration, using OpenGL ES and Gtk+ frontend
70 egl-headless - enable headless EGL output; use vnc or spice to see it
Patrick Williamsc0f7c042017-02-23 20:41:17 -060071 serial - enable a serial console on /dev/ttyS0
Brad Bishop19323692019-04-05 15:28:33 -040072 serialstdio - enable a serial console on the console (regardless of graphics mode)
Patrick Williamsc0f7c042017-02-23 20:41:17 -060073 slirp - enable user networking, no root privileges is required
74 kvm - enable KVM when running x86/x86_64 (VT-capable CPU required)
75 kvm-vhost - enable KVM with vhost when running x86/x86_64 (VT-capable CPU required)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050076 publicvnc - enable a VNC server open to all hosts
Patrick Williamsc0f7c042017-02-23 20:41:17 -060077 audio - enable audio
Brad Bishop6e60e8b2018-02-01 10:27:11 -050078 [*/]ovmf* - OVMF firmware file or base name for booting with UEFI
Patrick Williamsc0f7c042017-02-23 20:41:17 -060079 tcpserial=<port> - specify tcp serial port number
80 biosdir=<dir> - specify custom bios dir
81 biosfilename=<filename> - specify bios filename
82 qemuparams=<xyz> - specify custom parameters to QEMU
83 bootparams=<xyz> - specify custom kernel parameters during boot
Brad Bishop6e60e8b2018-02-01 10:27:11 -050084 help, -h, --help: print this text
Brad Bishopd7bf8c12018-02-25 22:55:05 -050085 -d, --debug: Enable debug output
86 -q, --quite: Hide most output except error messages
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050087
88Examples:
Brad Bishop6e60e8b2018-02-01 10:27:11 -050089 runqemu
Patrick Williamsc0f7c042017-02-23 20:41:17 -060090 runqemu qemuarm
91 runqemu tmp/deploy/images/qemuarm
Brad Bishop6e60e8b2018-02-01 10:27:11 -050092 runqemu tmp/deploy/images/qemux86/<qemuboot.conf>
Patrick Williamsc0f7c042017-02-23 20:41:17 -060093 runqemu qemux86-64 core-image-sato ext4
94 runqemu qemux86-64 wic-image-minimal wic
95 runqemu path/to/bzImage-qemux86.bin path/to/nfsrootdir/ serial
Brad Bishopd7bf8c12018-02-25 22:55:05 -050096 runqemu qemux86 iso/hddimg/wic.vmdk/wic.qcow2/wic.vdi/ramfs/cpio.gz...
Patrick Williamsc0f7c042017-02-23 20:41:17 -060097 runqemu qemux86 qemuparams="-m 256"
98 runqemu qemux86 bootparams="psplash=false"
Patrick Williamsc0f7c042017-02-23 20:41:17 -060099 runqemu path/to/<image>-<machine>.wic
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500100 runqemu path/to/<image>-<machine>.wic.vmdk
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600101""")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500102
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600103def check_tun():
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500104 """Check /dev/net/tun"""
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600105 dev_tun = '/dev/net/tun'
106 if not os.path.exists(dev_tun):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500107 raise RunQemuError("TUN control device %s is unavailable; you may need to enable TUN (e.g. sudo modprobe tun)" % dev_tun)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500108
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600109 if not os.access(dev_tun, os.W_OK):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500110 raise RunQemuError("TUN control device %s is not writable, please fix (e.g. sudo chmod 666 %s)" % (dev_tun, dev_tun))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500111
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600112def get_first_file(cmds):
113 """Return first file found in wildcard cmds"""
114 for cmd in cmds:
115 all_files = glob.glob(cmd)
116 if all_files:
117 for f in all_files:
118 if not os.path.isdir(f):
119 return f
120 return ''
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500121
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500122def check_free_port(host, port):
123 """ Check whether the port is free or not """
124 import socket
125 from contextlib import closing
126
127 with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
128 if sock.connect_ex((host, port)) == 0:
129 # Port is open, so not free
130 return False
131 else:
132 # Port is not open, so free
133 return True
134
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600135class BaseConfig(object):
136 def __init__(self):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500137 # The self.d saved vars from self.set(), part of them are from qemuboot.conf
138 self.d = {'QB_KERNEL_ROOT': '/dev/vda'}
139
140 # Supported env vars, add it here if a var can be got from env,
141 # and don't use os.getenv in the code.
142 self.env_vars = ('MACHINE',
143 'ROOTFS',
144 'KERNEL',
Brad Bishop316dfdd2018-06-25 12:45:53 -0400145 'DEVICE_TREE',
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500146 'DEPLOY_DIR_IMAGE',
147 'OE_TMPDIR',
148 'OECORE_NATIVE_SYSROOT',
149 )
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500150
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600151 self.qemu_opt = ''
152 self.qemu_opt_script = ''
Andrew Geissler99467da2019-02-25 18:54:23 -0600153 self.qemuparams = ''
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600154 self.clean_nfs_dir = False
155 self.nfs_server = ''
156 self.rootfs = ''
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500157 # File name(s) of a OVMF firmware file or variable store,
158 # to be added with -drive if=pflash.
159 # Found in the same places as the rootfs, with or without one of
160 # these suffices: qcow2, bin.
161 # Setting one also adds "-vga std" because that is all that
162 # OVMF supports.
163 self.ovmf_bios = []
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600164 self.qemuboot = ''
165 self.qbconfload = False
166 self.kernel = ''
167 self.kernel_cmdline = ''
168 self.kernel_cmdline_script = ''
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500169 self.bootparams = ''
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600170 self.dtb = ''
171 self.fstype = ''
172 self.kvm_enabled = False
173 self.vhost_enabled = False
174 self.slirp_enabled = False
175 self.nfs_instance = 0
176 self.nfs_running = False
Brad Bishop19323692019-04-05 15:28:33 -0400177 self.serialconsole = False
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600178 self.serialstdio = False
179 self.cleantap = False
180 self.saved_stty = ''
181 self.audio_enabled = False
182 self.tcpserial_portnum = ''
183 self.custombiosdir = ''
184 self.lock = ''
Brad Bishopf86d0552018-12-04 14:18:15 -0800185 self.lock_descriptor = None
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600186 self.bitbake_e = ''
187 self.snapshot = False
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500188 self.fstypes = ('ext2', 'ext3', 'ext4', 'jffs2', 'nfs', 'btrfs',
189 'cpio.gz', 'cpio', 'ramfs', 'tar.bz2', 'tar.gz')
190 self.vmtypes = ('hddimg', 'hdddirect', 'wic', 'wic.vmdk',
191 'wic.qcow2', 'wic.vdi', 'iso')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500192 self.network_device = "-device e1000,netdev=net0,mac=@MAC@"
193 # Use different mac section for tap and slirp to avoid
194 # conflicts, e.g., when one is running with tap, the other is
195 # running with slirp.
196 # The last section is dynamic, which is for avoiding conflicts,
197 # when multiple qemus are running, e.g., when multiple tap or
198 # slirp qemus are running.
199 self.mac_tap = "52:54:00:12:34:"
200 self.mac_slirp = "52:54:00:12:35:"
Brad Bishop004d4992018-10-02 23:54:45 +0200201 # pid of the actual qemu process
202 self.qemupid = None
203 # avoid cleanup twice
204 self.cleaned = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500205
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500206 def acquire_lock(self, error=True):
207 logger.debug("Acquiring lockfile %s..." % self.lock)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600208 try:
209 self.lock_descriptor = open(self.lock, 'w')
210 fcntl.flock(self.lock_descriptor, fcntl.LOCK_EX|fcntl.LOCK_NB)
211 except Exception as e:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500212 msg = "Acquiring lockfile %s failed: %s" % (self.lock, e)
213 if error:
214 logger.error(msg)
215 else:
216 logger.info(msg)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600217 if self.lock_descriptor:
218 self.lock_descriptor.close()
Brad Bishopf86d0552018-12-04 14:18:15 -0800219 self.lock_descriptor = None
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600220 return False
221 return True
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500222
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600223 def release_lock(self):
Brad Bishopf86d0552018-12-04 14:18:15 -0800224 if self.lock_descriptor:
225 logger.debug("Releasing lockfile for tap device '%s'" % self.tap)
226 fcntl.flock(self.lock_descriptor, fcntl.LOCK_UN)
227 self.lock_descriptor.close()
228 os.remove(self.lock)
229 self.lock_descriptor = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500230
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600231 def get(self, key):
232 if key in self.d:
233 return self.d.get(key)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500234 elif os.getenv(key):
235 return os.getenv(key)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600236 else:
237 return ''
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500238
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600239 def set(self, key, value):
240 self.d[key] = value
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500241
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600242 def is_deploy_dir_image(self, p):
243 if os.path.isdir(p):
244 if not re.search('.qemuboot.conf$', '\n'.join(os.listdir(p)), re.M):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500245 logger.debug("Can't find required *.qemuboot.conf in %s" % p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600246 return False
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500247 if not any(map(lambda name: '-image-' in name, os.listdir(p))):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500248 logger.debug("Can't find *-image-* in %s" % p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600249 return False
250 return True
251 else:
252 return False
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500253
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600254 def check_arg_fstype(self, fst):
255 """Check and set FSTYPE"""
256 if fst not in self.fstypes + self.vmtypes:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800257 logger.warning("Maybe unsupported FSTYPE: %s" % fst)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600258 if not self.fstype or self.fstype == fst:
259 if fst == 'ramfs':
260 fst = 'cpio.gz'
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500261 if fst in ('tar.bz2', 'tar.gz'):
262 fst = 'nfs'
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600263 self.fstype = fst
264 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500265 raise RunQemuError("Conflicting: FSTYPE %s and %s" % (self.fstype, fst))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500266
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600267 def set_machine_deploy_dir(self, machine, deploy_dir_image):
268 """Set MACHINE and DEPLOY_DIR_IMAGE"""
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500269 logger.debug('MACHINE: %s' % machine)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600270 self.set("MACHINE", machine)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500271 logger.debug('DEPLOY_DIR_IMAGE: %s' % deploy_dir_image)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600272 self.set("DEPLOY_DIR_IMAGE", deploy_dir_image)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500273
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600274 def check_arg_nfs(self, p):
275 if os.path.isdir(p):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500276 self.rootfs = p
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600277 else:
278 m = re.match('(.*):(.*)', p)
279 self.nfs_server = m.group(1)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500280 self.rootfs = m.group(2)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600281 self.check_arg_fstype('nfs')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500282
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600283 def check_arg_path(self, p):
284 """
285 - Check whether it is <image>.qemuboot.conf or contains <image>.qemuboot.conf
286 - Check whether is a kernel file
287 - Check whether is a image file
288 - Check whether it is a nfs dir
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500289 - Check whether it is a OVMF flash file
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600290 """
291 if p.endswith('.qemuboot.conf'):
292 self.qemuboot = p
293 self.qbconfload = True
294 elif re.search('\.bin$', p) or re.search('bzImage', p) or \
295 re.search('zImage', p) or re.search('vmlinux', p) or \
296 re.search('fitImage', p) or re.search('uImage', p):
297 self.kernel = p
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500298 elif os.path.exists(p) and (not os.path.isdir(p)) and '-image-' in os.path.basename(p):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600299 self.rootfs = p
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500300 # Check filename against self.fstypes can hanlde <file>.cpio.gz,
301 # otherwise, its type would be "gz", which is incorrect.
302 fst = ""
303 for t in self.fstypes:
304 if p.endswith(t):
305 fst = t
306 break
307 if not fst:
308 m = re.search('.*\.(.*)$', self.rootfs)
309 if m:
310 fst = m.group(1)
311 if fst:
312 self.check_arg_fstype(fst)
313 qb = re.sub('\.' + fst + "$", '', self.rootfs)
314 qb = '%s%s' % (re.sub('\.rootfs$', '', qb), '.qemuboot.conf')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600315 if os.path.exists(qb):
316 self.qemuboot = qb
317 self.qbconfload = True
318 else:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800319 logger.warning("%s doesn't exist" % qb)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600320 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500321 raise RunQemuError("Can't find FSTYPE from: %s" % p)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500322
323 elif os.path.isdir(p) or re.search(':', p) and re.search('/', p):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600324 if self.is_deploy_dir_image(p):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500325 logger.debug('DEPLOY_DIR_IMAGE: %s' % p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600326 self.set("DEPLOY_DIR_IMAGE", p)
327 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500328 logger.debug("Assuming %s is an nfs rootfs" % p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600329 self.check_arg_nfs(p)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500330 elif os.path.basename(p).startswith('ovmf'):
331 self.ovmf_bios.append(p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600332 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500333 raise RunQemuError("Unknown path arg %s" % p)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500334
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600335 def check_arg_machine(self, arg):
336 """Check whether it is a machine"""
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500337 if self.get('MACHINE') == arg:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600338 return
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500339 elif self.get('MACHINE') and self.get('MACHINE') != arg:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500340 raise RunQemuError("Maybe conflicted MACHINE: %s vs %s" % (self.get('MACHINE'), arg))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500341 elif re.search('/', arg):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500342 raise RunQemuError("Unknown arg: %s" % arg)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500343
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500344 logger.debug('Assuming MACHINE = %s' % arg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500345
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600346 # if we're running under testimage, or similarly as a child
347 # of an existing bitbake invocation, we can't invoke bitbake
348 # to validate the MACHINE setting and must assume it's correct...
349 # FIXME: testimage.bbclass exports these two variables into env,
350 # are there other scenarios in which we need to support being
351 # invoked by bitbake?
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500352 deploy = self.get('DEPLOY_DIR_IMAGE')
353 bbchild = deploy and self.get('OE_TMPDIR')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600354 if bbchild:
355 self.set_machine_deploy_dir(arg, deploy)
356 return
357 # also check whether we're running under a sourced toolchain
358 # environment file
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500359 if self.get('OECORE_NATIVE_SYSROOT'):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600360 self.set("MACHINE", arg)
361 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500362
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600363 cmd = 'MACHINE=%s bitbake -e' % arg
364 logger.info('Running %s...' % cmd)
Brad Bishop977dc1a2019-02-06 16:01:43 -0500365 self.bitbake_e = subprocess.check_output(cmd, shell=True).decode('utf-8')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600366 # bitbake -e doesn't report invalid MACHINE as an error, so
367 # let's check DEPLOY_DIR_IMAGE to make sure that it is a valid
368 # MACHINE.
369 s = re.search('^DEPLOY_DIR_IMAGE="(.*)"', self.bitbake_e, re.M)
370 if s:
371 deploy_dir_image = s.group(1)
372 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500373 raise RunQemuError("bitbake -e %s" % self.bitbake_e)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600374 if self.is_deploy_dir_image(deploy_dir_image):
375 self.set_machine_deploy_dir(arg, deploy_dir_image)
376 else:
377 logger.error("%s not a directory valid DEPLOY_DIR_IMAGE" % deploy_dir_image)
378 self.set("MACHINE", arg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500379
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600380 def check_args(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500381 for debug in ("-d", "--debug"):
382 if debug in sys.argv:
383 logger.setLevel(logging.DEBUG)
384 sys.argv.remove(debug)
385
386 for quiet in ("-q", "--quiet"):
387 if quiet in sys.argv:
388 logger.setLevel(logging.ERROR)
389 sys.argv.remove(quiet)
390
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600391 unknown_arg = ""
392 for arg in sys.argv[1:]:
393 if arg in self.fstypes + self.vmtypes:
394 self.check_arg_fstype(arg)
395 elif arg == 'nographic':
396 self.qemu_opt_script += ' -nographic'
397 self.kernel_cmdline_script += ' console=ttyS0'
Brad Bishop19323692019-04-05 15:28:33 -0400398 elif arg == 'sdl':
399 self.qemu_opt_script += ' -display sdl'
400 elif arg == 'gtk-gl':
401 self.qemu_opt_script += ' -vga virtio -display gtk,gl=on'
402 elif arg == 'gtk-gl-es':
403 self.qemu_opt_script += ' -vga virtio -display gtk,gl=es'
404 elif arg == 'egl-headless':
405 self.qemu_opt_script += ' -vga virtio -display egl-headless'
406 # As runqemu can be run within bitbake (when using testimage, for example),
407 # we need to ensure that we run host pkg-config, and that it does not
408 # get mis-directed to native build paths set by bitbake.
409 try:
410 del os.environ['PKG_CONFIG_PATH']
411 del os.environ['PKG_CONFIG_DIR']
412 del os.environ['PKG_CONFIG_LIBDIR']
413 except KeyError:
414 pass
415 try:
416 dripath = subprocess.check_output("PATH=/bin:/usr/bin:$PATH pkg-config --variable=dridriverdir dri", shell=True)
417 except subprocess.CalledProcessError as e:
418 raise RunQemuError("Could not determine the path to dri drivers on the host via pkg-config.\nPlease install Mesa development files (particularly, dri.pc) on the host machine.")
419 os.environ['LIBGL_DRIVERS_PATH'] = dripath.decode('utf-8').strip()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600420 elif arg == 'serial':
421 self.kernel_cmdline_script += ' console=ttyS0'
Brad Bishop19323692019-04-05 15:28:33 -0400422 self.serialconsole = True
423 elif arg == "serialstdio":
424 self.kernel_cmdline_script += ' console=ttyS0'
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600425 self.serialstdio = True
426 elif arg == 'audio':
427 logger.info("Enabling audio in qemu")
428 logger.info("Please install sound drivers in linux host")
429 self.audio_enabled = True
430 elif arg == 'kvm':
431 self.kvm_enabled = True
432 elif arg == 'kvm-vhost':
433 self.vhost_enabled = True
434 elif arg == 'slirp':
435 self.slirp_enabled = True
436 elif arg == 'snapshot':
437 self.snapshot = True
438 elif arg == 'publicvnc':
439 self.qemu_opt_script += ' -vnc :0'
440 elif arg.startswith('tcpserial='):
441 self.tcpserial_portnum = arg[len('tcpserial='):]
442 elif arg.startswith('biosdir='):
443 self.custombiosdir = arg[len('biosdir='):]
444 elif arg.startswith('biosfilename='):
445 self.qemu_opt_script += ' -bios %s' % arg[len('biosfilename='):]
446 elif arg.startswith('qemuparams='):
Andrew Geissler99467da2019-02-25 18:54:23 -0600447 self.qemuparams = ' %s' % arg[len('qemuparams='):]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600448 elif arg.startswith('bootparams='):
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500449 self.bootparams = arg[len('bootparams='):]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600450 elif os.path.exists(arg) or (re.search(':', arg) and re.search('/', arg)):
451 self.check_arg_path(os.path.abspath(arg))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500452 elif re.search(r'-image-|-image$', arg):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600453 # Lazy rootfs
454 self.rootfs = arg
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500455 elif arg.startswith('ovmf'):
456 self.ovmf_bios.append(arg)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600457 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500458 # At last, assume it is the MACHINE
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600459 if (not unknown_arg) or unknown_arg == arg:
460 unknown_arg = arg
461 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500462 raise RunQemuError("Can't handle two unknown args: %s %s\n"
463 "Try 'runqemu help' on how to use it" % \
464 (unknown_arg, arg))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600465 # Check to make sure it is a valid machine
Brad Bishopa5c52ff2018-11-23 10:55:50 +1300466 if unknown_arg and self.get('MACHINE') != unknown_arg:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500467 if self.get('DEPLOY_DIR_IMAGE'):
468 machine = os.path.basename(self.get('DEPLOY_DIR_IMAGE'))
469 if unknown_arg == machine:
470 self.set("MACHINE", machine)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500471
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600472 self.check_arg_machine(unknown_arg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500473
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500474 if not (self.get('DEPLOY_DIR_IMAGE') or self.qbconfload):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500475 self.load_bitbake_env()
476 s = re.search('^DEPLOY_DIR_IMAGE="(.*)"', self.bitbake_e, re.M)
477 if s:
478 self.set("DEPLOY_DIR_IMAGE", s.group(1))
479
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600480 def check_kvm(self):
481 """Check kvm and kvm-host"""
482 if not (self.kvm_enabled or self.vhost_enabled):
483 self.qemu_opt_script += ' %s %s' % (self.get('QB_MACHINE'), self.get('QB_CPU'))
484 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500485
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600486 if not self.get('QB_CPU_KVM'):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500487 raise RunQemuError("QB_CPU_KVM is NULL, this board doesn't support kvm")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500488
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600489 self.qemu_opt_script += ' %s %s' % (self.get('QB_MACHINE'), self.get('QB_CPU_KVM'))
490 yocto_kvm_wiki = "https://wiki.yoctoproject.org/wiki/How_to_enable_KVM_for_Poky_qemu"
491 yocto_paravirt_kvm_wiki = "https://wiki.yoctoproject.org/wiki/Running_an_x86_Yocto_Linux_image_under_QEMU_KVM"
492 dev_kvm = '/dev/kvm'
493 dev_vhost = '/dev/vhost-net'
494 with open('/proc/cpuinfo', 'r') as f:
495 kvm_cap = re.search('vmx|svm', "".join(f.readlines()))
496 if not kvm_cap:
497 logger.error("You are trying to enable KVM on a cpu without VT support.")
498 logger.error("Remove kvm from the command-line, or refer:")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500499 raise RunQemuError(yocto_kvm_wiki)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500500
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600501 if not os.path.exists(dev_kvm):
502 logger.error("Missing KVM device. Have you inserted kvm modules?")
503 logger.error("For further help see:")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500504 raise RunQemuError(yocto_kvm_wiki)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500505
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600506 if os.access(dev_kvm, os.W_OK|os.R_OK):
507 self.qemu_opt_script += ' -enable-kvm'
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500508 if self.get('MACHINE') == "qemux86":
509 # Workaround for broken APIC window on pre 4.15 host kernels which causes boot hangs
510 # See YOCTO #12301
511 # On 64 bit we use x2apic
512 self.kernel_cmdline_script += " clocksource=kvm-clock hpet=disable noapic nolapic"
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600513 else:
514 logger.error("You have no read or write permission on /dev/kvm.")
515 logger.error("Please change the ownership of this file as described at:")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500516 raise RunQemuError(yocto_kvm_wiki)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500517
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600518 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:")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500522 raise RunQemuError(yocto_paravirt_kvm_wiki)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500523
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600524 if not os.access(dev_kvm, os.W_OK|os.R_OK):
525 logger.error("You have no read or write permission on /dev/vhost-net.")
526 logger.error("Please change the ownership of this file as described at:")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500527 raise RunQemuError(yocto_kvm_wiki)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500528
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600529 def check_fstype(self):
530 """Check and setup FSTYPE"""
531 if not self.fstype:
532 fstype = self.get('QB_DEFAULT_FSTYPE')
533 if fstype:
534 self.fstype = fstype
535 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500536 raise RunQemuError("FSTYPE is NULL!")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500537
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600538 def check_rootfs(self):
539 """Check and set rootfs"""
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500540
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500541 if self.fstype == "none":
542 return
543
544 if self.get('ROOTFS'):
545 if not self.rootfs:
546 self.rootfs = self.get('ROOTFS')
547 elif self.get('ROOTFS') != self.rootfs:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500548 raise RunQemuError("Maybe conflicted ROOTFS: %s vs %s" % (self.get('ROOTFS'), self.rootfs))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500549
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600550 if self.fstype == 'nfs':
551 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500552
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600553 if self.rootfs and not os.path.exists(self.rootfs):
554 # Lazy rootfs
555 self.rootfs = "%s/%s-%s.%s" % (self.get('DEPLOY_DIR_IMAGE'),
556 self.rootfs, self.get('MACHINE'),
557 self.fstype)
558 elif not self.rootfs:
559 cmd_name = '%s/%s*.%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_NAME'), self.fstype)
560 cmd_link = '%s/%s*.%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_LINK_NAME'), self.fstype)
561 cmds = (cmd_name, cmd_link)
562 self.rootfs = get_first_file(cmds)
563 if not self.rootfs:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500564 raise RunQemuError("Failed to find rootfs: %s or %s" % cmds)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500565
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600566 if not os.path.exists(self.rootfs):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500567 raise RunQemuError("Can't find rootfs: %s" % self.rootfs)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500568
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500569 def check_ovmf(self):
570 """Check and set full path for OVMF firmware and variable file(s)."""
571
572 for index, ovmf in enumerate(self.ovmf_bios):
573 if os.path.exists(ovmf):
574 continue
575 for suffix in ('qcow2', 'bin'):
576 path = '%s/%s.%s' % (self.get('DEPLOY_DIR_IMAGE'), ovmf, suffix)
577 if os.path.exists(path):
578 self.ovmf_bios[index] = path
579 break
580 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500581 raise RunQemuError("Can't find OVMF firmware: %s" % ovmf)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500582
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600583 def check_kernel(self):
Brad Bishop316dfdd2018-06-25 12:45:53 -0400584 """Check and set kernel"""
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600585 # The vm image doesn't need a kernel
586 if self.fstype in self.vmtypes:
587 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500588
Brad Bishop316dfdd2018-06-25 12:45:53 -0400589 # See if the user supplied a KERNEL option
590 if self.get('KERNEL'):
591 self.kernel = self.get('KERNEL')
592
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500593 # QB_DEFAULT_KERNEL is always a full file path
594 kernel_name = os.path.basename(self.get('QB_DEFAULT_KERNEL'))
595
596 # The user didn't want a kernel to be loaded
Brad Bishop316dfdd2018-06-25 12:45:53 -0400597 if kernel_name == "none" and not self.kernel:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500598 return
599
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600600 deploy_dir_image = self.get('DEPLOY_DIR_IMAGE')
601 if not self.kernel:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500602 kernel_match_name = "%s/%s" % (deploy_dir_image, kernel_name)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600603 kernel_match_link = "%s/%s" % (deploy_dir_image, self.get('KERNEL_IMAGETYPE'))
604 kernel_startswith = "%s/%s*" % (deploy_dir_image, self.get('KERNEL_IMAGETYPE'))
605 cmds = (kernel_match_name, kernel_match_link, kernel_startswith)
606 self.kernel = get_first_file(cmds)
607 if not self.kernel:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500608 raise RunQemuError('KERNEL not found: %s, %s or %s' % cmds)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500609
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600610 if not os.path.exists(self.kernel):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500611 raise RunQemuError("KERNEL %s not found" % self.kernel)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500612
Brad Bishop316dfdd2018-06-25 12:45:53 -0400613 def check_dtb(self):
614 """Check and set dtb"""
615 # Did the user specify a device tree?
616 if self.get('DEVICE_TREE'):
617 self.dtb = self.get('DEVICE_TREE')
618 if not os.path.exists(self.dtb):
619 raise RunQemuError('Specified DTB not found: %s' % self.dtb)
620 return
621
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600622 dtb = self.get('QB_DTB')
623 if dtb:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400624 deploy_dir_image = self.get('DEPLOY_DIR_IMAGE')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600625 cmd_match = "%s/%s" % (deploy_dir_image, dtb)
626 cmd_startswith = "%s/%s*" % (deploy_dir_image, dtb)
627 cmd_wild = "%s/*.dtb" % deploy_dir_image
628 cmds = (cmd_match, cmd_startswith, cmd_wild)
629 self.dtb = get_first_file(cmds)
630 if not os.path.exists(self.dtb):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500631 raise RunQemuError('DTB not found: %s, %s or %s' % cmds)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500632
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600633 def check_biosdir(self):
634 """Check custombiosdir"""
635 if not self.custombiosdir:
636 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500637
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600638 biosdir = ""
639 biosdir_native = "%s/%s" % (self.get('STAGING_DIR_NATIVE'), self.custombiosdir)
640 biosdir_host = "%s/%s" % (self.get('STAGING_DIR_HOST'), self.custombiosdir)
641 for i in (self.custombiosdir, biosdir_native, biosdir_host):
642 if os.path.isdir(i):
643 biosdir = i
644 break
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500645
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600646 if biosdir:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500647 logger.debug("Assuming biosdir is: %s" % biosdir)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600648 self.qemu_opt_script += ' -L %s' % biosdir
649 else:
650 logger.error("Custom BIOS directory not found. Tried: %s, %s, and %s" % (self.custombiosdir, biosdir_native, biosdir_host))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500651 raise RunQemuError("Invalid custombiosdir: %s" % self.custombiosdir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500652
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600653 def check_mem(self):
Andrew Geissler99467da2019-02-25 18:54:23 -0600654 """
655 Both qemu and kernel needs memory settings, so check QB_MEM and set it
656 for both.
657 """
658 s = re.search('-m +([0-9]+)', self.qemuparams)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600659 if s:
660 self.set('QB_MEM', '-m %s' % s.group(1))
661 elif not self.get('QB_MEM'):
662 logger.info('QB_MEM is not set, use 512M by default')
663 self.set('QB_MEM', '-m 512')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500664
Andrew Geissler99467da2019-02-25 18:54:23 -0600665 # Check and remove M or m suffix
666 qb_mem = self.get('QB_MEM')
667 if qb_mem.endswith('M') or qb_mem.endswith('m'):
668 qb_mem = qb_mem[:-1]
669
670 # Add -m prefix it not present
671 if not qb_mem.startswith('-m'):
672 qb_mem = '-m %s' % qb_mem
673
674 self.set('QB_MEM', qb_mem)
675
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800676 mach = self.get('MACHINE')
677 if not mach.startswith('qemumips'):
678 self.kernel_cmdline_script += ' mem=%s' % self.get('QB_MEM').replace('-m','').strip() + 'M'
679
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600680 self.qemu_opt_script += ' %s' % self.get('QB_MEM')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500681
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600682 def check_tcpserial(self):
683 if self.tcpserial_portnum:
684 if self.get('QB_TCPSERIAL_OPT'):
685 self.qemu_opt_script += ' ' + self.get('QB_TCPSERIAL_OPT').replace('@PORT@', self.tcpserial_portnum)
686 else:
687 self.qemu_opt_script += ' -serial tcp:127.0.0.1:%s' % self.tcpserial_portnum
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500688
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600689 def check_and_set(self):
690 """Check configs sanity and set when needed"""
691 self.validate_paths()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500692 if not self.slirp_enabled:
693 check_tun()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600694 # Check audio
695 if self.audio_enabled:
696 if not self.get('QB_AUDIO_DRV'):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500697 raise RunQemuError("QB_AUDIO_DRV is NULL, this board doesn't support audio")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600698 if not self.get('QB_AUDIO_OPT'):
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800699 logger.warning('QB_AUDIO_OPT is NULL, you may need define it to make audio work')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600700 else:
701 self.qemu_opt_script += ' %s' % self.get('QB_AUDIO_OPT')
702 os.putenv('QEMU_AUDIO_DRV', self.get('QB_AUDIO_DRV'))
703 else:
704 os.putenv('QEMU_AUDIO_DRV', 'none')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500705
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600706 self.check_kvm()
707 self.check_fstype()
708 self.check_rootfs()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500709 self.check_ovmf()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600710 self.check_kernel()
Brad Bishop316dfdd2018-06-25 12:45:53 -0400711 self.check_dtb()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600712 self.check_biosdir()
713 self.check_mem()
714 self.check_tcpserial()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500715
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600716 def read_qemuboot(self):
717 if not self.qemuboot:
718 if self.get('DEPLOY_DIR_IMAGE'):
719 deploy_dir_image = self.get('DEPLOY_DIR_IMAGE')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600720 else:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800721 logger.warning("Can't find qemuboot conf file, DEPLOY_DIR_IMAGE is NULL!")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600722 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500723
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600724 if self.rootfs and not os.path.exists(self.rootfs):
725 # Lazy rootfs
726 machine = self.get('MACHINE')
727 if not machine:
728 machine = os.path.basename(deploy_dir_image)
729 self.qemuboot = "%s/%s-%s.qemuboot.conf" % (deploy_dir_image,
730 self.rootfs, machine)
731 else:
732 cmd = 'ls -t %s/*.qemuboot.conf' % deploy_dir_image
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500733 logger.debug('Running %s...' % cmd)
734 try:
735 qbs = subprocess.check_output(cmd, shell=True).decode('utf-8')
736 except subprocess.CalledProcessError as err:
737 raise RunQemuError(err)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600738 if qbs:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500739 for qb in qbs.split():
740 # Don't use initramfs when other choices unless fstype is ramfs
741 if '-initramfs-' in os.path.basename(qb) and self.fstype != 'cpio.gz':
742 continue
743 self.qemuboot = qb
744 break
745 if not self.qemuboot:
746 # Use the first one when no choice
747 self.qemuboot = qbs.split()[0]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600748 self.qbconfload = True
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500749
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600750 if not self.qemuboot:
751 # If we haven't found a .qemuboot.conf at this point it probably
752 # doesn't exist, continue without
753 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500754
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600755 if not os.path.exists(self.qemuboot):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500756 raise RunQemuError("Failed to find %s (wrong image name or BSP does not support running under qemu?)." % self.qemuboot)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500757
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500758 logger.debug('CONFFILE: %s' % self.qemuboot)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500759
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600760 cf = configparser.ConfigParser()
761 cf.read(self.qemuboot)
762 for k, v in cf.items('config_bsp'):
763 k_upper = k.upper()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500764 if v.startswith("../"):
765 v = os.path.abspath(os.path.dirname(self.qemuboot) + "/" + v)
766 elif v == ".":
767 v = os.path.dirname(self.qemuboot)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600768 self.set(k_upper, v)
769
770 def validate_paths(self):
771 """Ensure all relevant path variables are set"""
772 # When we're started with a *.qemuboot.conf arg assume that image
773 # artefacts are relative to that file, rather than in whatever
774 # directory DEPLOY_DIR_IMAGE in the conf file points to.
775 if self.qbconfload:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500776 imgdir = os.path.realpath(os.path.dirname(self.qemuboot))
777 if imgdir != os.path.realpath(self.get('DEPLOY_DIR_IMAGE')):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600778 logger.info('Setting DEPLOY_DIR_IMAGE to folder containing %s (%s)' % (self.qemuboot, imgdir))
779 self.set('DEPLOY_DIR_IMAGE', imgdir)
780
781 # If the STAGING_*_NATIVE directories from the config file don't exist
782 # and we're in a sourced OE build directory try to extract the paths
783 # from `bitbake -e`
784 havenative = os.path.exists(self.get('STAGING_DIR_NATIVE')) and \
785 os.path.exists(self.get('STAGING_BINDIR_NATIVE'))
786
787 if not havenative:
788 if not self.bitbake_e:
789 self.load_bitbake_env()
790
791 if self.bitbake_e:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500792 native_vars = ['STAGING_DIR_NATIVE']
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600793 for nv in native_vars:
794 s = re.search('^%s="(.*)"' % nv, self.bitbake_e, re.M)
795 if s and s.group(1) != self.get(nv):
796 logger.info('Overriding conf file setting of %s to %s from Bitbake environment' % (nv, s.group(1)))
797 self.set(nv, s.group(1))
798 else:
799 # when we're invoked from a running bitbake instance we won't
800 # be able to call `bitbake -e`, then try:
801 # - get OE_TMPDIR from environment and guess paths based on it
802 # - get OECORE_NATIVE_SYSROOT from environment (for sdk)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500803 tmpdir = self.get('OE_TMPDIR')
804 oecore_native_sysroot = self.get('OECORE_NATIVE_SYSROOT')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600805 if tmpdir:
806 logger.info('Setting STAGING_DIR_NATIVE and STAGING_BINDIR_NATIVE relative to OE_TMPDIR (%s)' % tmpdir)
807 hostos, _, _, _, machine = os.uname()
808 buildsys = '%s-%s' % (machine, hostos.lower())
809 staging_dir_native = '%s/sysroots/%s' % (tmpdir, buildsys)
810 self.set('STAGING_DIR_NATIVE', staging_dir_native)
811 elif oecore_native_sysroot:
812 logger.info('Setting STAGING_DIR_NATIVE to OECORE_NATIVE_SYSROOT (%s)' % oecore_native_sysroot)
813 self.set('STAGING_DIR_NATIVE', oecore_native_sysroot)
814 if self.get('STAGING_DIR_NATIVE'):
815 # we have to assume that STAGING_BINDIR_NATIVE is at usr/bin
816 staging_bindir_native = '%s/usr/bin' % self.get('STAGING_DIR_NATIVE')
817 logger.info('Setting STAGING_BINDIR_NATIVE to %s' % staging_bindir_native)
818 self.set('STAGING_BINDIR_NATIVE', '%s/usr/bin' % self.get('STAGING_DIR_NATIVE'))
819
820 def print_config(self):
821 logger.info('Continuing with the following parameters:\n')
822 if not self.fstype in self.vmtypes:
823 print('KERNEL: [%s]' % self.kernel)
824 if self.dtb:
825 print('DTB: [%s]' % self.dtb)
826 print('MACHINE: [%s]' % self.get('MACHINE'))
827 print('FSTYPE: [%s]' % self.fstype)
828 if self.fstype == 'nfs':
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500829 print('NFS_DIR: [%s]' % self.rootfs)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600830 else:
831 print('ROOTFS: [%s]' % self.rootfs)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500832 if self.ovmf_bios:
833 print('OVMF: %s' % self.ovmf_bios)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600834 print('CONFFILE: [%s]' % self.qemuboot)
835 print('')
836
837 def setup_nfs(self):
838 if not self.nfs_server:
839 if self.slirp_enabled:
840 self.nfs_server = '10.0.2.2'
841 else:
842 self.nfs_server = '192.168.7.1'
843
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500844 # Figure out a new nfs_instance to allow multiple qemus running.
Brad Bishop977dc1a2019-02-06 16:01:43 -0500845 ps = subprocess.check_output(("ps", "auxww")).decode('utf-8')
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500846 pattern = '/bin/unfsd .* -i .*\.pid -e .*/exports([0-9]+) '
847 all_instances = re.findall(pattern, ps, re.M)
848 if all_instances:
849 all_instances.sort(key=int)
850 self.nfs_instance = int(all_instances.pop()) + 1
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600851
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500852 nfsd_port = 3049 + 2 * self.nfs_instance
853 mountd_port = 3048 + 2 * self.nfs_instance
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600854
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500855 # Export vars for runqemu-export-rootfs
856 export_dict = {
857 'NFS_INSTANCE': self.nfs_instance,
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500858 'NFSD_PORT': nfsd_port,
859 'MOUNTD_PORT': mountd_port,
860 }
861 for k, v in export_dict.items():
862 # Use '%s' since they are integers
863 os.putenv(k, '%s' % v)
864
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500865 self.unfs_opts="nfsvers=3,port=%s,udp,mountport=%s" % (nfsd_port, mountd_port)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600866
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500867 # Extract .tar.bz2 or .tar.bz if no nfs dir
868 if not (self.rootfs and os.path.isdir(self.rootfs)):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600869 src_prefix = '%s/%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_LINK_NAME'))
870 dest = "%s-nfsroot" % src_prefix
871 if os.path.exists('%s.pseudo_state' % dest):
872 logger.info('Use %s as NFS_DIR' % dest)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500873 self.rootfs = dest
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600874 else:
875 src = ""
876 src1 = '%s.tar.bz2' % src_prefix
877 src2 = '%s.tar.gz' % src_prefix
878 if os.path.exists(src1):
879 src = src1
880 elif os.path.exists(src2):
881 src = src2
882 if not src:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500883 raise RunQemuError("No NFS_DIR is set, and can't find %s or %s to extract" % (src1, src2))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600884 logger.info('NFS_DIR not found, extracting %s to %s' % (src, dest))
Brad Bishop977dc1a2019-02-06 16:01:43 -0500885 cmd = ('runqemu-extract-sdk', src, dest)
886 logger.info('Running %s...' % str(cmd))
887 if subprocess.call(cmd) != 0:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500888 raise RunQemuError('Failed to run %s' % cmd)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600889 self.clean_nfs_dir = True
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500890 self.rootfs = dest
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600891
892 # Start the userspace NFS server
Brad Bishop977dc1a2019-02-06 16:01:43 -0500893 cmd = ('runqemu-export-rootfs', 'start', self.rootfs)
894 logger.info('Running %s...' % str(cmd))
895 if subprocess.call(cmd) != 0:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500896 raise RunQemuError('Failed to run %s' % cmd)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600897
898 self.nfs_running = True
899
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600900 def setup_slirp(self):
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500901 """Setup user networking"""
902
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600903 if self.fstype == 'nfs':
904 self.setup_nfs()
905 self.kernel_cmdline_script += ' ip=dhcp'
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500906 # Port mapping
907 hostfwd = ",hostfwd=tcp::2222-:22,hostfwd=tcp::2323-:23"
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500908 qb_slirp_opt_default = "-netdev user,id=net0%s,tftp=%s" % (hostfwd, self.get('DEPLOY_DIR_IMAGE'))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500909 qb_slirp_opt = self.get('QB_SLIRP_OPT') or qb_slirp_opt_default
910 # Figure out the port
911 ports = re.findall('hostfwd=[^-]*:([0-9]+)-[^,-]*', qb_slirp_opt)
912 ports = [int(i) for i in ports]
913 mac = 2
914 # Find a free port to avoid conflicts
915 for p in ports[:]:
916 p_new = p
917 while not check_free_port('localhost', p_new):
918 p_new += 1
919 mac += 1
920 while p_new in ports:
921 p_new += 1
922 mac += 1
923 if p != p_new:
924 ports.append(p_new)
925 qb_slirp_opt = re.sub(':%s-' % p, ':%s-' % p_new, qb_slirp_opt)
926 logger.info("Port forward changed: %s -> %s" % (p, p_new))
927 mac = "%s%02x" % (self.mac_slirp, mac)
928 self.set('NETWORK_CMD', '%s %s' % (self.network_device.replace('@MAC@', mac), qb_slirp_opt))
929 # Print out port foward
930 hostfwd = re.findall('(hostfwd=[^,]*)', qb_slirp_opt)
931 if hostfwd:
932 logger.info('Port forward: %s' % ' '.join(hostfwd))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600933
934 def setup_tap(self):
935 """Setup tap"""
936
937 # This file is created when runqemu-gen-tapdevs creates a bank of tap
938 # devices, indicating that the user should not bring up new ones using
939 # sudo.
940 nosudo_flag = '/etc/runqemu-nosudo'
941 self.qemuifup = shutil.which('runqemu-ifup')
942 self.qemuifdown = shutil.which('runqemu-ifdown')
943 ip = shutil.which('ip')
944 lockdir = "/tmp/qemu-tap-locks"
945
946 if not (self.qemuifup and self.qemuifdown and ip):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500947 logger.error("runqemu-ifup: %s" % self.qemuifup)
948 logger.error("runqemu-ifdown: %s" % self.qemuifdown)
949 logger.error("ip: %s" % ip)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600950 raise OEPathError("runqemu-ifup, runqemu-ifdown or ip not found")
951
952 if not os.path.exists(lockdir):
953 # There might be a race issue when multi runqemu processess are
954 # running at the same time.
955 try:
956 os.mkdir(lockdir)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500957 os.chmod(lockdir, 0o777)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600958 except FileExistsError:
959 pass
960
Brad Bishop977dc1a2019-02-06 16:01:43 -0500961 cmd = (ip, 'link')
962 logger.debug('Running %s...' % str(cmd))
963 ip_link = subprocess.check_output(cmd).decode('utf-8')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600964 # Matches line like: 6: tap0: <foo>
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500965 possibles = re.findall('^[0-9]+: +(tap[0-9]+): <.*', ip_link, re.M)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600966 tap = ""
967 for p in possibles:
968 lockfile = os.path.join(lockdir, p)
969 if os.path.exists('%s.skip' % lockfile):
970 logger.info('Found %s.skip, skipping %s' % (lockfile, p))
971 continue
972 self.lock = lockfile + '.lock'
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500973 if self.acquire_lock(error=False):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600974 tap = p
975 logger.info("Using preconfigured tap device %s" % tap)
976 logger.info("If this is not intended, touch %s.skip to make runqemu skip %s." %(lockfile, tap))
977 break
978
979 if not tap:
980 if os.path.exists(nosudo_flag):
981 logger.error("Error: There are no available tap devices to use for networking,")
982 logger.error("and I see %s exists, so I am not going to try creating" % nosudo_flag)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500983 raise RunQemuError("a new one with sudo.")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600984
985 gid = os.getgid()
986 uid = os.getuid()
987 logger.info("Setting up tap interface under sudo")
Brad Bishop977dc1a2019-02-06 16:01:43 -0500988 cmd = ('sudo', self.qemuifup, str(uid), str(gid), self.bindir_native)
989 tap = subprocess.check_output(cmd).decode('utf-8').strip()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600990 lockfile = os.path.join(lockdir, tap)
991 self.lock = lockfile + '.lock'
992 self.acquire_lock()
993 self.cleantap = True
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500994 logger.debug('Created tap: %s' % tap)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600995
996 if not tap:
997 logger.error("Failed to setup tap device. Run runqemu-gen-tapdevs to manually create.")
998 return 1
999 self.tap = tap
Brad Bishop37a0e4d2017-12-04 01:01:44 -05001000 tapnum = int(tap[3:])
1001 gateway = tapnum * 2 + 1
1002 client = gateway + 1
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001003 if self.fstype == 'nfs':
1004 self.setup_nfs()
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001005 netconf = "192.168.7.%s::192.168.7.%s:255.255.255.0" % (client, gateway)
1006 logger.info("Network configuration: %s", netconf)
1007 self.kernel_cmdline_script += " ip=%s" % netconf
1008 mac = "%s%02x" % (self.mac_tap, client)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001009 qb_tap_opt = self.get('QB_TAP_OPT')
1010 if qb_tap_opt:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001011 qemu_tap_opt = qb_tap_opt.replace('@TAP@', tap)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001012 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001013 qemu_tap_opt = "-netdev tap,id=net0,ifname=%s,script=no,downscript=no" % (self.tap)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001014
1015 if self.vhost_enabled:
1016 qemu_tap_opt += ',vhost=on'
1017
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001018 self.set('NETWORK_CMD', '%s %s' % (self.network_device.replace('@MAC@', mac), qemu_tap_opt))
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001019
1020 def setup_network(self):
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001021 if self.get('QB_NET') == 'none':
1022 return
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001023 if sys.stdin.isatty():
Brad Bishop977dc1a2019-02-06 16:01:43 -05001024 self.saved_stty = subprocess.check_output(("stty", "-g")).decode('utf-8').strip()
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001025 self.network_device = self.get('QB_NETWORK_DEVICE') or self.network_device
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001026 if self.slirp_enabled:
1027 self.setup_slirp()
1028 else:
1029 self.setup_tap()
1030
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001031 def setup_rootfs(self):
1032 if self.get('QB_ROOTFS') == 'none':
1033 return
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001034 if 'wic.' in self.fstype:
1035 self.fstype = self.fstype[4:]
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001036 rootfs_format = self.fstype if self.fstype in ('vmdk', 'qcow2', 'vdi') else 'raw'
1037
1038 qb_rootfs_opt = self.get('QB_ROOTFS_OPT')
1039 if qb_rootfs_opt:
1040 self.rootfs_options = qb_rootfs_opt.replace('@ROOTFS@', self.rootfs)
1041 else:
1042 self.rootfs_options = '-drive file=%s,if=virtio,format=%s' % (self.rootfs, rootfs_format)
1043
1044 if self.fstype in ('cpio.gz', 'cpio'):
1045 self.kernel_cmdline = 'root=/dev/ram0 rw debugshell'
1046 self.rootfs_options = '-initrd %s' % self.rootfs
1047 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001048 vm_drive = ''
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001049 if self.fstype in self.vmtypes:
1050 if self.fstype == 'iso':
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001051 vm_drive = '-drive file=%s,if=virtio,media=cdrom' % self.rootfs
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001052 elif self.get('QB_DRIVE_TYPE'):
1053 drive_type = self.get('QB_DRIVE_TYPE')
1054 if drive_type.startswith("/dev/sd"):
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001055 logger.info('Using scsi drive')
1056 vm_drive = '-drive if=none,id=hd,file=%s,format=%s -device virtio-scsi-pci,id=scsi -device scsi-hd,drive=hd' \
1057 % (self.rootfs, rootfs_format)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001058 elif drive_type.startswith("/dev/hd"):
Brad Bishop37a0e4d2017-12-04 01:01:44 -05001059 logger.info('Using ide drive')
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001060 vm_drive = "-drive file=%s,format=%s" % (self.rootfs, rootfs_format)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001061 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001062 # virtio might have been selected explicitly (just use it), or
1063 # is used as fallback (then warn about that).
1064 if not drive_type.startswith("/dev/vd"):
Brad Bishop1a4b7ee2018-12-16 17:11:34 -08001065 logger.warning("Unknown QB_DRIVE_TYPE: %s" % drive_type)
1066 logger.warning("Failed to figure out drive type, consider define or fix QB_DRIVE_TYPE")
1067 logger.warning('Trying to use virtio block drive')
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001068 vm_drive = '-drive if=virtio,file=%s,format=%s' % (self.rootfs, rootfs_format)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001069
1070 # All branches above set vm_drive.
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001071 self.rootfs_options = '%s -no-reboot' % vm_drive
1072 self.kernel_cmdline = 'root=%s rw highres=off' % (self.get('QB_KERNEL_ROOT'))
1073
1074 if self.fstype == 'nfs':
1075 self.rootfs_options = ''
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001076 k_root = '/dev/nfs nfsroot=%s:%s,%s' % (self.nfs_server, os.path.abspath(self.rootfs), self.unfs_opts)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001077 self.kernel_cmdline = 'root=%s rw highres=off' % k_root
1078
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001079 if self.fstype == 'none':
1080 self.rootfs_options = ''
1081
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001082 self.set('ROOTFS_OPTIONS', self.rootfs_options)
1083
1084 def guess_qb_system(self):
1085 """attempt to determine the appropriate qemu-system binary"""
1086 mach = self.get('MACHINE')
1087 if not mach:
1088 search = '.*(qemux86-64|qemux86|qemuarm64|qemuarm|qemumips64|qemumips64el|qemumipsel|qemumips|qemuppc).*'
1089 if self.rootfs:
1090 match = re.match(search, self.rootfs)
1091 if match:
1092 mach = match.group(1)
1093 elif self.kernel:
1094 match = re.match(search, self.kernel)
1095 if match:
1096 mach = match.group(1)
1097
1098 if not mach:
1099 return None
1100
1101 if mach == 'qemuarm':
1102 qbsys = 'arm'
1103 elif mach == 'qemuarm64':
1104 qbsys = 'aarch64'
1105 elif mach == 'qemux86':
1106 qbsys = 'i386'
1107 elif mach == 'qemux86-64':
1108 qbsys = 'x86_64'
1109 elif mach == 'qemuppc':
1110 qbsys = 'ppc'
1111 elif mach == 'qemumips':
1112 qbsys = 'mips'
1113 elif mach == 'qemumips64':
1114 qbsys = 'mips64'
1115 elif mach == 'qemumipsel':
1116 qbsys = 'mipsel'
1117 elif mach == 'qemumips64el':
1118 qbsys = 'mips64el'
Brad Bishop316dfdd2018-06-25 12:45:53 -04001119 elif mach == 'qemuriscv64':
1120 qbsys = 'riscv64'
1121 elif mach == 'qemuriscv32':
1122 qbsys = 'riscv32'
Brad Bishop004d4992018-10-02 23:54:45 +02001123 else:
1124 logger.error("Unable to determine QEMU PC System emulator for %s machine." % mach)
1125 logger.error("As %s is not among valid QEMU machines such as," % mach)
1126 logger.error("qemux86-64, qemux86, qemuarm64, qemuarm, qemumips64, qemumips64el, qemumipsel, qemumips, qemuppc")
1127 raise RunQemuError("Set qb_system_name with suitable QEMU PC System emulator in .*qemuboot.conf.")
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001128
1129 return 'qemu-system-%s' % qbsys
1130
1131 def setup_final(self):
1132 qemu_system = self.get('QB_SYSTEM_NAME')
1133 if not qemu_system:
1134 qemu_system = self.guess_qb_system()
1135 if not qemu_system:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001136 raise RunQemuError("Failed to boot, QB_SYSTEM_NAME is NULL!")
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001137
Brad Bishop977dc1a2019-02-06 16:01:43 -05001138 qemu_bin = os.path.join(self.bindir_native, qemu_system)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001139
1140 # It is possible to have qemu-native in ASSUME_PROVIDED, and it won't
1141 # find QEMU in sysroot, it needs to use host's qemu.
1142 if not os.path.exists(qemu_bin):
1143 logger.info("QEMU binary not found in %s, trying host's QEMU" % qemu_bin)
1144 for path in (os.environ['PATH'] or '').split(':'):
1145 qemu_bin_tmp = os.path.join(path, qemu_system)
1146 logger.info("Trying: %s" % qemu_bin_tmp)
1147 if os.path.exists(qemu_bin_tmp):
1148 qemu_bin = qemu_bin_tmp
1149 if not os.path.isabs(qemu_bin):
1150 qemu_bin = os.path.abspath(qemu_bin)
1151 logger.info("Using host's QEMU: %s" % qemu_bin)
1152 break
1153
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001154 if not os.access(qemu_bin, os.X_OK):
1155 raise OEPathError("No QEMU binary '%s' could be found" % qemu_bin)
1156
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001157 self.qemu_opt = "%s %s %s %s" % (qemu_bin, self.get('NETWORK_CMD'), self.get('ROOTFS_OPTIONS'), self.get('QB_OPT_APPEND'))
1158
1159 for ovmf in self.ovmf_bios:
1160 format = ovmf.rsplit('.', 1)[-1]
1161 self.qemu_opt += ' -drive if=pflash,format=%s,file=%s' % (format, ovmf)
1162 if self.ovmf_bios:
1163 # OVMF only supports normal VGA, i.e. we need to override a -vga vmware
1164 # that gets added for example for normal qemux86.
1165 self.qemu_opt += ' -vga std'
1166
1167 self.qemu_opt += ' ' + self.qemu_opt_script
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001168
Andrew Geissler99467da2019-02-25 18:54:23 -06001169 # Append qemuparams to override previous settings
1170 if self.qemuparams:
1171 self.qemu_opt += ' ' + self.qemuparams
1172
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001173 if self.snapshot:
1174 self.qemu_opt += " -snapshot"
1175
Brad Bishop19323692019-04-05 15:28:33 -04001176 if self.serialconsole:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001177 if sys.stdin.isatty():
Brad Bishop977dc1a2019-02-06 16:01:43 -05001178 subprocess.check_call(("stty", "intr", "^]"))
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001179 logger.info("Interrupt character is '^]'")
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001180
1181 first_serial = ""
1182 if not re.search("-nographic", self.qemu_opt):
1183 first_serial = "-serial mon:vc"
1184 # We always want a ttyS1. Since qemu by default adds a serial
1185 # port when nodefaults is not specified, it seems that all that
1186 # would be needed is to make sure a "-serial" is there. However,
1187 # it appears that when "-serial" is specified, it ignores the
1188 # default serial port that is normally added. So here we make
1189 # sure to add two -serial if there are none. And only one if
1190 # there is one -serial already.
1191 serial_num = len(re.findall("-serial", self.qemu_opt))
1192 if serial_num == 0:
1193 self.qemu_opt += " %s %s" % (first_serial, self.get("QB_SERIAL_OPT"))
1194 elif serial_num == 1:
1195 self.qemu_opt += " %s" % self.get("QB_SERIAL_OPT")
1196
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001197 # We always wants ttyS0 and ttyS1 in qemu machines (see SERIAL_CONSOLES),
1198 # if not serial or serialtcp options was specified only ttyS0 is created
1199 # and sysvinit shows an error trying to enable ttyS1:
1200 # INIT: Id "S1" respawning too fast: disabled for 5 minutes
1201 serial_num = len(re.findall("-serial", self.qemu_opt))
1202 if serial_num == 0:
Brad Bishop19323692019-04-05 15:28:33 -04001203 if re.search("-nographic", self.qemu_opt) or self.serialstdio:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001204 self.qemu_opt += " -serial mon:stdio -serial null"
1205 else:
1206 self.qemu_opt += " -serial mon:vc -serial null"
1207
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001208 def start_qemu(self):
Brad Bishop004d4992018-10-02 23:54:45 +02001209 import shlex
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001210 if self.kernel:
Brad Bishop37a0e4d2017-12-04 01:01:44 -05001211 kernel_opts = "-kernel %s -append '%s %s %s %s'" % (self.kernel, self.kernel_cmdline,
1212 self.kernel_cmdline_script, self.get('QB_KERNEL_CMDLINE_APPEND'),
1213 self.bootparams)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001214 if self.dtb:
1215 kernel_opts += " -dtb %s" % self.dtb
1216 else:
1217 kernel_opts = ""
1218 cmd = "%s %s" % (self.qemu_opt, kernel_opts)
Brad Bishop004d4992018-10-02 23:54:45 +02001219 cmds = shlex.split(cmd)
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001220 logger.info('Running %s\n' % cmd)
Brad Bishopf86d0552018-12-04 14:18:15 -08001221 pass_fds = []
1222 if self.lock_descriptor:
1223 pass_fds = [self.lock_descriptor.fileno()]
1224 process = subprocess.Popen(cmds, stderr=subprocess.PIPE, pass_fds=pass_fds)
Brad Bishop004d4992018-10-02 23:54:45 +02001225 self.qemupid = process.pid
1226 retcode = process.wait()
1227 if retcode:
1228 if retcode == -signal.SIGTERM:
1229 logger.info("Qemu terminated by SIGTERM")
1230 else:
1231 logger.error("Failed to run qemu: %s", process.stderr.read().decode())
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001232
1233 def cleanup(self):
Brad Bishop004d4992018-10-02 23:54:45 +02001234 if self.cleaned:
1235 return
1236
1237 # avoid dealing with SIGTERM when cleanup function is running
1238 signal.signal(signal.SIGTERM, signal.SIG_IGN)
1239
1240 logger.info("Cleaning up")
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001241 if self.cleantap:
Brad Bishop977dc1a2019-02-06 16:01:43 -05001242 cmd = ('sudo', self.qemuifdown, self.tap, self.bindir_native)
1243 logger.debug('Running %s' % str(cmd))
1244 subprocess.check_call(cmd)
Brad Bishopf86d0552018-12-04 14:18:15 -08001245 self.release_lock()
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001246
1247 if self.nfs_running:
1248 logger.info("Shutting down the userspace NFS server...")
Brad Bishop977dc1a2019-02-06 16:01:43 -05001249 cmd = ("runqemu-export-rootfs", "stop", self.rootfs)
1250 logger.debug('Running %s' % str(cmd))
1251 subprocess.check_call(cmd)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001252
1253 if self.saved_stty:
Brad Bishop977dc1a2019-02-06 16:01:43 -05001254 subprocess.check_call(("stty", self.saved_stty))
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001255
1256 if self.clean_nfs_dir:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001257 logger.info('Removing %s' % self.rootfs)
1258 shutil.rmtree(self.rootfs)
1259 shutil.rmtree('%s.pseudo_state' % self.rootfs)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001260
Brad Bishop004d4992018-10-02 23:54:45 +02001261 self.cleaned = True
1262
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001263 def load_bitbake_env(self, mach=None):
1264 if self.bitbake_e:
1265 return
1266
1267 bitbake = shutil.which('bitbake')
1268 if not bitbake:
1269 return
1270
1271 if not mach:
1272 mach = self.get('MACHINE')
1273
1274 if mach:
1275 cmd = 'MACHINE=%s bitbake -e' % mach
1276 else:
1277 cmd = 'bitbake -e'
1278
1279 logger.info('Running %s...' % cmd)
1280 try:
1281 self.bitbake_e = subprocess.check_output(cmd, shell=True).decode('utf-8')
1282 except subprocess.CalledProcessError as err:
1283 self.bitbake_e = ''
Brad Bishop1a4b7ee2018-12-16 17:11:34 -08001284 logger.warning("Couldn't run 'bitbake -e' to gather environment information:\n%s" % err.output.decode('utf-8'))
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001285
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001286 def validate_combos(self):
1287 if (self.fstype in self.vmtypes) and self.kernel:
1288 raise RunQemuError("%s doesn't need kernel %s!" % (self.fstype, self.kernel))
1289
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001290 @property
1291 def bindir_native(self):
1292 result = self.get('STAGING_BINDIR_NATIVE')
1293 if result and os.path.exists(result):
1294 return result
1295
Brad Bishop977dc1a2019-02-06 16:01:43 -05001296 cmd = ('bitbake', 'qemu-helper-native', '-e')
1297 logger.info('Running %s...' % str(cmd))
1298 out = subprocess.check_output(cmd).decode('utf-8')
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001299
1300 match = re.search('^STAGING_BINDIR_NATIVE="(.*)"', out, re.M)
1301 if match:
1302 result = match.group(1)
1303 if os.path.exists(result):
1304 self.set('STAGING_BINDIR_NATIVE', result)
1305 return result
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001306 raise RunQemuError("Native sysroot directory %s doesn't exist" % result)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001307 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001308 raise RunQemuError("Can't find STAGING_BINDIR_NATIVE in '%s' output" % cmd)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001309
1310
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001311def main():
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001312 if "help" in sys.argv or '-h' in sys.argv or '--help' in sys.argv:
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001313 print_usage()
1314 return 0
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001315 try:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001316 config = BaseConfig()
Brad Bishop004d4992018-10-02 23:54:45 +02001317
1318 def sigterm_handler(signum, frame):
1319 logger.info("SIGTERM received")
1320 os.kill(config.qemupid, signal.SIGTERM)
1321 config.cleanup()
Brad Bishopc342db32019-05-15 21:57:59 -04001322 # Deliberately ignore the return code of 'tput smam'.
1323 subprocess.call(["tput", "smam"])
Brad Bishop004d4992018-10-02 23:54:45 +02001324 signal.signal(signal.SIGTERM, sigterm_handler)
1325
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001326 config.check_args()
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001327 config.read_qemuboot()
1328 config.check_and_set()
1329 # Check whether the combos is valid or not
1330 config.validate_combos()
1331 config.print_config()
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001332 config.setup_network()
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001333 config.setup_rootfs()
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001334 config.setup_final()
1335 config.start_qemu()
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001336 except RunQemuError as err:
1337 logger.error(err)
1338 return 1
1339 except Exception as err:
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001340 import traceback
1341 traceback.print_exc()
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001342 return 1
1343 finally:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001344 config.cleanup()
Brad Bishopc342db32019-05-15 21:57:59 -04001345 # Deliberately ignore the return code of 'tput smam'.
1346 subprocess.call(["tput", "smam"])
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001347
1348if __name__ == "__main__":
1349 sys.exit(main())