blob: c0e569c44cb46923fa43dba113d3cd0de8b975c5 [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#
8# This program is free software; you can redistribute it and/or modify
9# it under the terms of the GNU General Public License version 2 as
10# published by the Free Software Foundation.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License along
18# with this program; if not, write to the Free Software Foundation, Inc.,
19# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
Patrick Williamsc0f7c042017-02-23 20:41:17 -060021import os
22import sys
23import logging
24import subprocess
25import re
26import fcntl
27import shutil
28import glob
29import configparser
Brad Bishop004d4992018-10-02 23:54:45 +020030import signal
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050031
Brad Bishopd7bf8c12018-02-25 22:55:05 -050032class RunQemuError(Exception):
33 """Custom exception to raise on known errors."""
34 pass
35
36class OEPathError(RunQemuError):
Patrick Williamsc0f7c042017-02-23 20:41:17 -060037 """Custom Exception to give better guidance on missing binaries"""
38 def __init__(self, message):
Brad Bishopd7bf8c12018-02-25 22:55:05 -050039 super().__init__("In order for this script to dynamically infer paths\n \
Patrick Williamsc0f7c042017-02-23 20:41:17 -060040kernels or filesystem images, you either need bitbake in your PATH\n \
41or to source oe-init-build-env before running this script.\n\n \
42Dynamic path inference can be avoided by passing a *.qemuboot.conf to\n \
Brad Bishopd7bf8c12018-02-25 22:55:05 -050043runqemu, i.e. `runqemu /path/to/my-image-name.qemuboot.conf`\n\n %s" % message)
Patrick Williamsc0f7c042017-02-23 20:41:17 -060044
45
46def create_logger():
47 logger = logging.getLogger('runqemu')
48 logger.setLevel(logging.INFO)
49
50 # create console handler and set level to debug
51 ch = logging.StreamHandler()
Brad Bishopd7bf8c12018-02-25 22:55:05 -050052 ch.setLevel(logging.DEBUG)
Patrick Williamsc0f7c042017-02-23 20:41:17 -060053
54 # create formatter
55 formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
56
57 # add formatter to ch
58 ch.setFormatter(formatter)
59
60 # add ch to logger
61 logger.addHandler(ch)
62
63 return logger
64
65logger = create_logger()
66
67def print_usage():
68 print("""
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050069Usage: you can run this script with any valid combination
70of the following environment variables (in any order):
71 KERNEL - the kernel image file to use
72 ROOTFS - the rootfs image file or nfsroot directory to use
Brad Bishop316dfdd2018-06-25 12:45:53 -040073 DEVICE_TREE - the device tree blob to use
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050074 MACHINE - the machine name (optional, autodetected from KERNEL filename if unspecified)
75 Simplified QEMU command-line options can be passed with:
Patrick Williamsc0f7c042017-02-23 20:41:17 -060076 nographic - disable video console
Brad Bishop19323692019-04-05 15:28:33 -040077 sdl - choose the SDL frontend instead of the Gtk+ default
78 gtk-gl - enable virgl-based GL acceleration using Gtk+ frontend
79 gtk-gl-es - enable virgl-based GL acceleration, using OpenGL ES and Gtk+ frontend
80 egl-headless - enable headless EGL output; use vnc or spice to see it
Patrick Williamsc0f7c042017-02-23 20:41:17 -060081 serial - enable a serial console on /dev/ttyS0
Brad Bishop19323692019-04-05 15:28:33 -040082 serialstdio - enable a serial console on the console (regardless of graphics mode)
Patrick Williamsc0f7c042017-02-23 20:41:17 -060083 slirp - enable user networking, no root privileges is required
84 kvm - enable KVM when running x86/x86_64 (VT-capable CPU required)
85 kvm-vhost - enable KVM with vhost when running x86/x86_64 (VT-capable CPU required)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050086 publicvnc - enable a VNC server open to all hosts
Patrick Williamsc0f7c042017-02-23 20:41:17 -060087 audio - enable audio
Brad Bishop6e60e8b2018-02-01 10:27:11 -050088 [*/]ovmf* - OVMF firmware file or base name for booting with UEFI
Patrick Williamsc0f7c042017-02-23 20:41:17 -060089 tcpserial=<port> - specify tcp serial port number
90 biosdir=<dir> - specify custom bios dir
91 biosfilename=<filename> - specify bios filename
92 qemuparams=<xyz> - specify custom parameters to QEMU
93 bootparams=<xyz> - specify custom kernel parameters during boot
Brad Bishop6e60e8b2018-02-01 10:27:11 -050094 help, -h, --help: print this text
Brad Bishopd7bf8c12018-02-25 22:55:05 -050095 -d, --debug: Enable debug output
96 -q, --quite: Hide most output except error messages
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050097
98Examples:
Brad Bishop6e60e8b2018-02-01 10:27:11 -050099 runqemu
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600100 runqemu qemuarm
101 runqemu tmp/deploy/images/qemuarm
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500102 runqemu tmp/deploy/images/qemux86/<qemuboot.conf>
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600103 runqemu qemux86-64 core-image-sato ext4
104 runqemu qemux86-64 wic-image-minimal wic
105 runqemu path/to/bzImage-qemux86.bin path/to/nfsrootdir/ serial
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500106 runqemu qemux86 iso/hddimg/wic.vmdk/wic.qcow2/wic.vdi/ramfs/cpio.gz...
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600107 runqemu qemux86 qemuparams="-m 256"
108 runqemu qemux86 bootparams="psplash=false"
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600109 runqemu path/to/<image>-<machine>.wic
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500110 runqemu path/to/<image>-<machine>.wic.vmdk
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600111""")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500112
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600113def check_tun():
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500114 """Check /dev/net/tun"""
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600115 dev_tun = '/dev/net/tun'
116 if not os.path.exists(dev_tun):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500117 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 -0500118
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600119 if not os.access(dev_tun, os.W_OK):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500120 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 -0500121
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600122def get_first_file(cmds):
123 """Return first file found in wildcard cmds"""
124 for cmd in cmds:
125 all_files = glob.glob(cmd)
126 if all_files:
127 for f in all_files:
128 if not os.path.isdir(f):
129 return f
130 return ''
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500131
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500132def check_free_port(host, port):
133 """ Check whether the port is free or not """
134 import socket
135 from contextlib import closing
136
137 with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
138 if sock.connect_ex((host, port)) == 0:
139 # Port is open, so not free
140 return False
141 else:
142 # Port is not open, so free
143 return True
144
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600145class BaseConfig(object):
146 def __init__(self):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500147 # The self.d saved vars from self.set(), part of them are from qemuboot.conf
148 self.d = {'QB_KERNEL_ROOT': '/dev/vda'}
149
150 # Supported env vars, add it here if a var can be got from env,
151 # and don't use os.getenv in the code.
152 self.env_vars = ('MACHINE',
153 'ROOTFS',
154 'KERNEL',
Brad Bishop316dfdd2018-06-25 12:45:53 -0400155 'DEVICE_TREE',
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500156 'DEPLOY_DIR_IMAGE',
157 'OE_TMPDIR',
158 'OECORE_NATIVE_SYSROOT',
159 )
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500160
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600161 self.qemu_opt = ''
162 self.qemu_opt_script = ''
Andrew Geissler99467da2019-02-25 18:54:23 -0600163 self.qemuparams = ''
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600164 self.clean_nfs_dir = False
165 self.nfs_server = ''
166 self.rootfs = ''
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500167 # File name(s) of a OVMF firmware file or variable store,
168 # to be added with -drive if=pflash.
169 # Found in the same places as the rootfs, with or without one of
170 # these suffices: qcow2, bin.
171 # Setting one also adds "-vga std" because that is all that
172 # OVMF supports.
173 self.ovmf_bios = []
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600174 self.qemuboot = ''
175 self.qbconfload = False
176 self.kernel = ''
177 self.kernel_cmdline = ''
178 self.kernel_cmdline_script = ''
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500179 self.bootparams = ''
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600180 self.dtb = ''
181 self.fstype = ''
182 self.kvm_enabled = False
183 self.vhost_enabled = False
184 self.slirp_enabled = False
185 self.nfs_instance = 0
186 self.nfs_running = False
Brad Bishop19323692019-04-05 15:28:33 -0400187 self.serialconsole = False
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600188 self.serialstdio = False
189 self.cleantap = False
190 self.saved_stty = ''
191 self.audio_enabled = False
192 self.tcpserial_portnum = ''
193 self.custombiosdir = ''
194 self.lock = ''
Brad Bishopf86d0552018-12-04 14:18:15 -0800195 self.lock_descriptor = None
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600196 self.bitbake_e = ''
197 self.snapshot = False
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500198 self.fstypes = ('ext2', 'ext3', 'ext4', 'jffs2', 'nfs', 'btrfs',
199 'cpio.gz', 'cpio', 'ramfs', 'tar.bz2', 'tar.gz')
200 self.vmtypes = ('hddimg', 'hdddirect', 'wic', 'wic.vmdk',
201 'wic.qcow2', 'wic.vdi', 'iso')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500202 self.network_device = "-device e1000,netdev=net0,mac=@MAC@"
203 # Use different mac section for tap and slirp to avoid
204 # conflicts, e.g., when one is running with tap, the other is
205 # running with slirp.
206 # The last section is dynamic, which is for avoiding conflicts,
207 # when multiple qemus are running, e.g., when multiple tap or
208 # slirp qemus are running.
209 self.mac_tap = "52:54:00:12:34:"
210 self.mac_slirp = "52:54:00:12:35:"
Brad Bishop004d4992018-10-02 23:54:45 +0200211 # pid of the actual qemu process
212 self.qemupid = None
213 # avoid cleanup twice
214 self.cleaned = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500215
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500216 def acquire_lock(self, error=True):
217 logger.debug("Acquiring lockfile %s..." % self.lock)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600218 try:
219 self.lock_descriptor = open(self.lock, 'w')
220 fcntl.flock(self.lock_descriptor, fcntl.LOCK_EX|fcntl.LOCK_NB)
221 except Exception as e:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500222 msg = "Acquiring lockfile %s failed: %s" % (self.lock, e)
223 if error:
224 logger.error(msg)
225 else:
226 logger.info(msg)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600227 if self.lock_descriptor:
228 self.lock_descriptor.close()
Brad Bishopf86d0552018-12-04 14:18:15 -0800229 self.lock_descriptor = None
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600230 return False
231 return True
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500232
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600233 def release_lock(self):
Brad Bishopf86d0552018-12-04 14:18:15 -0800234 if self.lock_descriptor:
235 logger.debug("Releasing lockfile for tap device '%s'" % self.tap)
236 fcntl.flock(self.lock_descriptor, fcntl.LOCK_UN)
237 self.lock_descriptor.close()
238 os.remove(self.lock)
239 self.lock_descriptor = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500240
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600241 def get(self, key):
242 if key in self.d:
243 return self.d.get(key)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500244 elif os.getenv(key):
245 return os.getenv(key)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600246 else:
247 return ''
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500248
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600249 def set(self, key, value):
250 self.d[key] = value
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500251
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600252 def is_deploy_dir_image(self, p):
253 if os.path.isdir(p):
254 if not re.search('.qemuboot.conf$', '\n'.join(os.listdir(p)), re.M):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500255 logger.debug("Can't find required *.qemuboot.conf in %s" % p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600256 return False
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500257 if not any(map(lambda name: '-image-' in name, os.listdir(p))):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500258 logger.debug("Can't find *-image-* in %s" % p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600259 return False
260 return True
261 else:
262 return False
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500263
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600264 def check_arg_fstype(self, fst):
265 """Check and set FSTYPE"""
266 if fst not in self.fstypes + self.vmtypes:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800267 logger.warning("Maybe unsupported FSTYPE: %s" % fst)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600268 if not self.fstype or self.fstype == fst:
269 if fst == 'ramfs':
270 fst = 'cpio.gz'
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500271 if fst in ('tar.bz2', 'tar.gz'):
272 fst = 'nfs'
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600273 self.fstype = fst
274 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500275 raise RunQemuError("Conflicting: FSTYPE %s and %s" % (self.fstype, fst))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500276
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600277 def set_machine_deploy_dir(self, machine, deploy_dir_image):
278 """Set MACHINE and DEPLOY_DIR_IMAGE"""
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500279 logger.debug('MACHINE: %s' % machine)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600280 self.set("MACHINE", machine)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500281 logger.debug('DEPLOY_DIR_IMAGE: %s' % deploy_dir_image)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600282 self.set("DEPLOY_DIR_IMAGE", deploy_dir_image)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500283
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600284 def check_arg_nfs(self, p):
285 if os.path.isdir(p):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500286 self.rootfs = p
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600287 else:
288 m = re.match('(.*):(.*)', p)
289 self.nfs_server = m.group(1)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500290 self.rootfs = m.group(2)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600291 self.check_arg_fstype('nfs')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500292
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600293 def check_arg_path(self, p):
294 """
295 - Check whether it is <image>.qemuboot.conf or contains <image>.qemuboot.conf
296 - Check whether is a kernel file
297 - Check whether is a image file
298 - Check whether it is a nfs dir
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500299 - Check whether it is a OVMF flash file
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600300 """
301 if p.endswith('.qemuboot.conf'):
302 self.qemuboot = p
303 self.qbconfload = True
304 elif re.search('\.bin$', p) or re.search('bzImage', p) or \
305 re.search('zImage', p) or re.search('vmlinux', p) or \
306 re.search('fitImage', p) or re.search('uImage', p):
307 self.kernel = p
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500308 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 -0600309 self.rootfs = p
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500310 # Check filename against self.fstypes can hanlde <file>.cpio.gz,
311 # otherwise, its type would be "gz", which is incorrect.
312 fst = ""
313 for t in self.fstypes:
314 if p.endswith(t):
315 fst = t
316 break
317 if not fst:
318 m = re.search('.*\.(.*)$', self.rootfs)
319 if m:
320 fst = m.group(1)
321 if fst:
322 self.check_arg_fstype(fst)
323 qb = re.sub('\.' + fst + "$", '', self.rootfs)
324 qb = '%s%s' % (re.sub('\.rootfs$', '', qb), '.qemuboot.conf')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600325 if os.path.exists(qb):
326 self.qemuboot = qb
327 self.qbconfload = True
328 else:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800329 logger.warning("%s doesn't exist" % qb)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600330 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500331 raise RunQemuError("Can't find FSTYPE from: %s" % p)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500332
333 elif os.path.isdir(p) or re.search(':', p) and re.search('/', p):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600334 if self.is_deploy_dir_image(p):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500335 logger.debug('DEPLOY_DIR_IMAGE: %s' % p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600336 self.set("DEPLOY_DIR_IMAGE", p)
337 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500338 logger.debug("Assuming %s is an nfs rootfs" % p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600339 self.check_arg_nfs(p)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500340 elif os.path.basename(p).startswith('ovmf'):
341 self.ovmf_bios.append(p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600342 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500343 raise RunQemuError("Unknown path arg %s" % p)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500344
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600345 def check_arg_machine(self, arg):
346 """Check whether it is a machine"""
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500347 if self.get('MACHINE') == arg:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600348 return
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500349 elif self.get('MACHINE') and self.get('MACHINE') != arg:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500350 raise RunQemuError("Maybe conflicted MACHINE: %s vs %s" % (self.get('MACHINE'), arg))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500351 elif re.search('/', arg):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500352 raise RunQemuError("Unknown arg: %s" % arg)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500353
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500354 logger.debug('Assuming MACHINE = %s' % arg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500355
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600356 # if we're running under testimage, or similarly as a child
357 # of an existing bitbake invocation, we can't invoke bitbake
358 # to validate the MACHINE setting and must assume it's correct...
359 # FIXME: testimage.bbclass exports these two variables into env,
360 # are there other scenarios in which we need to support being
361 # invoked by bitbake?
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500362 deploy = self.get('DEPLOY_DIR_IMAGE')
363 bbchild = deploy and self.get('OE_TMPDIR')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600364 if bbchild:
365 self.set_machine_deploy_dir(arg, deploy)
366 return
367 # also check whether we're running under a sourced toolchain
368 # environment file
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500369 if self.get('OECORE_NATIVE_SYSROOT'):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600370 self.set("MACHINE", arg)
371 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500372
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600373 cmd = 'MACHINE=%s bitbake -e' % arg
374 logger.info('Running %s...' % cmd)
Brad Bishop977dc1a2019-02-06 16:01:43 -0500375 self.bitbake_e = subprocess.check_output(cmd, shell=True).decode('utf-8')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600376 # bitbake -e doesn't report invalid MACHINE as an error, so
377 # let's check DEPLOY_DIR_IMAGE to make sure that it is a valid
378 # MACHINE.
379 s = re.search('^DEPLOY_DIR_IMAGE="(.*)"', self.bitbake_e, re.M)
380 if s:
381 deploy_dir_image = s.group(1)
382 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500383 raise RunQemuError("bitbake -e %s" % self.bitbake_e)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600384 if self.is_deploy_dir_image(deploy_dir_image):
385 self.set_machine_deploy_dir(arg, deploy_dir_image)
386 else:
387 logger.error("%s not a directory valid DEPLOY_DIR_IMAGE" % deploy_dir_image)
388 self.set("MACHINE", arg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500389
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600390 def check_args(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500391 for debug in ("-d", "--debug"):
392 if debug in sys.argv:
393 logger.setLevel(logging.DEBUG)
394 sys.argv.remove(debug)
395
396 for quiet in ("-q", "--quiet"):
397 if quiet in sys.argv:
398 logger.setLevel(logging.ERROR)
399 sys.argv.remove(quiet)
400
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600401 unknown_arg = ""
402 for arg in sys.argv[1:]:
403 if arg in self.fstypes + self.vmtypes:
404 self.check_arg_fstype(arg)
405 elif arg == 'nographic':
406 self.qemu_opt_script += ' -nographic'
407 self.kernel_cmdline_script += ' console=ttyS0'
Brad Bishop19323692019-04-05 15:28:33 -0400408 elif arg == 'sdl':
409 self.qemu_opt_script += ' -display sdl'
410 elif arg == 'gtk-gl':
411 self.qemu_opt_script += ' -vga virtio -display gtk,gl=on'
412 elif arg == 'gtk-gl-es':
413 self.qemu_opt_script += ' -vga virtio -display gtk,gl=es'
414 elif arg == 'egl-headless':
415 self.qemu_opt_script += ' -vga virtio -display egl-headless'
416 # As runqemu can be run within bitbake (when using testimage, for example),
417 # we need to ensure that we run host pkg-config, and that it does not
418 # get mis-directed to native build paths set by bitbake.
419 try:
420 del os.environ['PKG_CONFIG_PATH']
421 del os.environ['PKG_CONFIG_DIR']
422 del os.environ['PKG_CONFIG_LIBDIR']
423 except KeyError:
424 pass
425 try:
426 dripath = subprocess.check_output("PATH=/bin:/usr/bin:$PATH pkg-config --variable=dridriverdir dri", shell=True)
427 except subprocess.CalledProcessError as e:
428 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.")
429 os.environ['LIBGL_DRIVERS_PATH'] = dripath.decode('utf-8').strip()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600430 elif arg == 'serial':
431 self.kernel_cmdline_script += ' console=ttyS0'
Brad Bishop19323692019-04-05 15:28:33 -0400432 self.serialconsole = True
433 elif arg == "serialstdio":
434 self.kernel_cmdline_script += ' console=ttyS0'
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600435 self.serialstdio = True
436 elif arg == 'audio':
437 logger.info("Enabling audio in qemu")
438 logger.info("Please install sound drivers in linux host")
439 self.audio_enabled = True
440 elif arg == 'kvm':
441 self.kvm_enabled = True
442 elif arg == 'kvm-vhost':
443 self.vhost_enabled = True
444 elif arg == 'slirp':
445 self.slirp_enabled = True
446 elif arg == 'snapshot':
447 self.snapshot = True
448 elif arg == 'publicvnc':
449 self.qemu_opt_script += ' -vnc :0'
450 elif arg.startswith('tcpserial='):
451 self.tcpserial_portnum = arg[len('tcpserial='):]
452 elif arg.startswith('biosdir='):
453 self.custombiosdir = arg[len('biosdir='):]
454 elif arg.startswith('biosfilename='):
455 self.qemu_opt_script += ' -bios %s' % arg[len('biosfilename='):]
456 elif arg.startswith('qemuparams='):
Andrew Geissler99467da2019-02-25 18:54:23 -0600457 self.qemuparams = ' %s' % arg[len('qemuparams='):]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600458 elif arg.startswith('bootparams='):
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500459 self.bootparams = arg[len('bootparams='):]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600460 elif os.path.exists(arg) or (re.search(':', arg) and re.search('/', arg)):
461 self.check_arg_path(os.path.abspath(arg))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500462 elif re.search(r'-image-|-image$', arg):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600463 # Lazy rootfs
464 self.rootfs = arg
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500465 elif arg.startswith('ovmf'):
466 self.ovmf_bios.append(arg)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600467 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500468 # At last, assume it is the MACHINE
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600469 if (not unknown_arg) or unknown_arg == arg:
470 unknown_arg = arg
471 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500472 raise RunQemuError("Can't handle two unknown args: %s %s\n"
473 "Try 'runqemu help' on how to use it" % \
474 (unknown_arg, arg))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600475 # Check to make sure it is a valid machine
Brad Bishopa5c52ff2018-11-23 10:55:50 +1300476 if unknown_arg and self.get('MACHINE') != unknown_arg:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500477 if self.get('DEPLOY_DIR_IMAGE'):
478 machine = os.path.basename(self.get('DEPLOY_DIR_IMAGE'))
479 if unknown_arg == machine:
480 self.set("MACHINE", machine)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500481
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600482 self.check_arg_machine(unknown_arg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500483
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500484 if not (self.get('DEPLOY_DIR_IMAGE') or self.qbconfload):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500485 self.load_bitbake_env()
486 s = re.search('^DEPLOY_DIR_IMAGE="(.*)"', self.bitbake_e, re.M)
487 if s:
488 self.set("DEPLOY_DIR_IMAGE", s.group(1))
489
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600490 def check_kvm(self):
491 """Check kvm and kvm-host"""
492 if not (self.kvm_enabled or self.vhost_enabled):
493 self.qemu_opt_script += ' %s %s' % (self.get('QB_MACHINE'), self.get('QB_CPU'))
494 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500495
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600496 if not self.get('QB_CPU_KVM'):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500497 raise RunQemuError("QB_CPU_KVM is NULL, this board doesn't support kvm")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500498
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600499 self.qemu_opt_script += ' %s %s' % (self.get('QB_MACHINE'), self.get('QB_CPU_KVM'))
500 yocto_kvm_wiki = "https://wiki.yoctoproject.org/wiki/How_to_enable_KVM_for_Poky_qemu"
501 yocto_paravirt_kvm_wiki = "https://wiki.yoctoproject.org/wiki/Running_an_x86_Yocto_Linux_image_under_QEMU_KVM"
502 dev_kvm = '/dev/kvm'
503 dev_vhost = '/dev/vhost-net'
504 with open('/proc/cpuinfo', 'r') as f:
505 kvm_cap = re.search('vmx|svm', "".join(f.readlines()))
506 if not kvm_cap:
507 logger.error("You are trying to enable KVM on a cpu without VT support.")
508 logger.error("Remove kvm from the command-line, or refer:")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500509 raise RunQemuError(yocto_kvm_wiki)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500510
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600511 if not os.path.exists(dev_kvm):
512 logger.error("Missing KVM device. Have you inserted kvm modules?")
513 logger.error("For further help see:")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500514 raise RunQemuError(yocto_kvm_wiki)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500515
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600516 if os.access(dev_kvm, os.W_OK|os.R_OK):
517 self.qemu_opt_script += ' -enable-kvm'
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500518 if self.get('MACHINE') == "qemux86":
519 # Workaround for broken APIC window on pre 4.15 host kernels which causes boot hangs
520 # See YOCTO #12301
521 # On 64 bit we use x2apic
522 self.kernel_cmdline_script += " clocksource=kvm-clock hpet=disable noapic nolapic"
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600523 else:
524 logger.error("You have no read or write permission on /dev/kvm.")
525 logger.error("Please change the ownership of this file as described at:")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500526 raise RunQemuError(yocto_kvm_wiki)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500527
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600528 if self.vhost_enabled:
529 if not os.path.exists(dev_vhost):
530 logger.error("Missing virtio net device. Have you inserted vhost-net module?")
531 logger.error("For further help see:")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500532 raise RunQemuError(yocto_paravirt_kvm_wiki)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500533
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600534 if not os.access(dev_kvm, os.W_OK|os.R_OK):
535 logger.error("You have no read or write permission on /dev/vhost-net.")
536 logger.error("Please change the ownership of this file as described at:")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500537 raise RunQemuError(yocto_kvm_wiki)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500538
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600539 def check_fstype(self):
540 """Check and setup FSTYPE"""
541 if not self.fstype:
542 fstype = self.get('QB_DEFAULT_FSTYPE')
543 if fstype:
544 self.fstype = fstype
545 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500546 raise RunQemuError("FSTYPE is NULL!")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500547
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600548 def check_rootfs(self):
549 """Check and set rootfs"""
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500550
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500551 if self.fstype == "none":
552 return
553
554 if self.get('ROOTFS'):
555 if not self.rootfs:
556 self.rootfs = self.get('ROOTFS')
557 elif self.get('ROOTFS') != self.rootfs:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500558 raise RunQemuError("Maybe conflicted ROOTFS: %s vs %s" % (self.get('ROOTFS'), self.rootfs))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500559
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600560 if self.fstype == 'nfs':
561 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500562
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600563 if self.rootfs and not os.path.exists(self.rootfs):
564 # Lazy rootfs
565 self.rootfs = "%s/%s-%s.%s" % (self.get('DEPLOY_DIR_IMAGE'),
566 self.rootfs, self.get('MACHINE'),
567 self.fstype)
568 elif not self.rootfs:
569 cmd_name = '%s/%s*.%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_NAME'), self.fstype)
570 cmd_link = '%s/%s*.%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_LINK_NAME'), self.fstype)
571 cmds = (cmd_name, cmd_link)
572 self.rootfs = get_first_file(cmds)
573 if not self.rootfs:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500574 raise RunQemuError("Failed to find rootfs: %s or %s" % cmds)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500575
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600576 if not os.path.exists(self.rootfs):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500577 raise RunQemuError("Can't find rootfs: %s" % self.rootfs)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500578
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500579 def check_ovmf(self):
580 """Check and set full path for OVMF firmware and variable file(s)."""
581
582 for index, ovmf in enumerate(self.ovmf_bios):
583 if os.path.exists(ovmf):
584 continue
585 for suffix in ('qcow2', 'bin'):
586 path = '%s/%s.%s' % (self.get('DEPLOY_DIR_IMAGE'), ovmf, suffix)
587 if os.path.exists(path):
588 self.ovmf_bios[index] = path
589 break
590 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500591 raise RunQemuError("Can't find OVMF firmware: %s" % ovmf)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500592
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600593 def check_kernel(self):
Brad Bishop316dfdd2018-06-25 12:45:53 -0400594 """Check and set kernel"""
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600595 # The vm image doesn't need a kernel
596 if self.fstype in self.vmtypes:
597 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500598
Brad Bishop316dfdd2018-06-25 12:45:53 -0400599 # See if the user supplied a KERNEL option
600 if self.get('KERNEL'):
601 self.kernel = self.get('KERNEL')
602
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500603 # QB_DEFAULT_KERNEL is always a full file path
604 kernel_name = os.path.basename(self.get('QB_DEFAULT_KERNEL'))
605
606 # The user didn't want a kernel to be loaded
Brad Bishop316dfdd2018-06-25 12:45:53 -0400607 if kernel_name == "none" and not self.kernel:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500608 return
609
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600610 deploy_dir_image = self.get('DEPLOY_DIR_IMAGE')
611 if not self.kernel:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500612 kernel_match_name = "%s/%s" % (deploy_dir_image, kernel_name)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600613 kernel_match_link = "%s/%s" % (deploy_dir_image, self.get('KERNEL_IMAGETYPE'))
614 kernel_startswith = "%s/%s*" % (deploy_dir_image, self.get('KERNEL_IMAGETYPE'))
615 cmds = (kernel_match_name, kernel_match_link, kernel_startswith)
616 self.kernel = get_first_file(cmds)
617 if not self.kernel:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500618 raise RunQemuError('KERNEL not found: %s, %s or %s' % cmds)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500619
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600620 if not os.path.exists(self.kernel):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500621 raise RunQemuError("KERNEL %s not found" % self.kernel)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500622
Brad Bishop316dfdd2018-06-25 12:45:53 -0400623 def check_dtb(self):
624 """Check and set dtb"""
625 # Did the user specify a device tree?
626 if self.get('DEVICE_TREE'):
627 self.dtb = self.get('DEVICE_TREE')
628 if not os.path.exists(self.dtb):
629 raise RunQemuError('Specified DTB not found: %s' % self.dtb)
630 return
631
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600632 dtb = self.get('QB_DTB')
633 if dtb:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400634 deploy_dir_image = self.get('DEPLOY_DIR_IMAGE')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600635 cmd_match = "%s/%s" % (deploy_dir_image, dtb)
636 cmd_startswith = "%s/%s*" % (deploy_dir_image, dtb)
637 cmd_wild = "%s/*.dtb" % deploy_dir_image
638 cmds = (cmd_match, cmd_startswith, cmd_wild)
639 self.dtb = get_first_file(cmds)
640 if not os.path.exists(self.dtb):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500641 raise RunQemuError('DTB not found: %s, %s or %s' % cmds)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500642
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600643 def check_biosdir(self):
644 """Check custombiosdir"""
645 if not self.custombiosdir:
646 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500647
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600648 biosdir = ""
649 biosdir_native = "%s/%s" % (self.get('STAGING_DIR_NATIVE'), self.custombiosdir)
650 biosdir_host = "%s/%s" % (self.get('STAGING_DIR_HOST'), self.custombiosdir)
651 for i in (self.custombiosdir, biosdir_native, biosdir_host):
652 if os.path.isdir(i):
653 biosdir = i
654 break
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500655
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600656 if biosdir:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500657 logger.debug("Assuming biosdir is: %s" % biosdir)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600658 self.qemu_opt_script += ' -L %s' % biosdir
659 else:
660 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 -0500661 raise RunQemuError("Invalid custombiosdir: %s" % self.custombiosdir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500662
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600663 def check_mem(self):
Andrew Geissler99467da2019-02-25 18:54:23 -0600664 """
665 Both qemu and kernel needs memory settings, so check QB_MEM and set it
666 for both.
667 """
668 s = re.search('-m +([0-9]+)', self.qemuparams)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600669 if s:
670 self.set('QB_MEM', '-m %s' % s.group(1))
671 elif not self.get('QB_MEM'):
672 logger.info('QB_MEM is not set, use 512M by default')
673 self.set('QB_MEM', '-m 512')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500674
Andrew Geissler99467da2019-02-25 18:54:23 -0600675 # Check and remove M or m suffix
676 qb_mem = self.get('QB_MEM')
677 if qb_mem.endswith('M') or qb_mem.endswith('m'):
678 qb_mem = qb_mem[:-1]
679
680 # Add -m prefix it not present
681 if not qb_mem.startswith('-m'):
682 qb_mem = '-m %s' % qb_mem
683
684 self.set('QB_MEM', qb_mem)
685
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800686 mach = self.get('MACHINE')
687 if not mach.startswith('qemumips'):
688 self.kernel_cmdline_script += ' mem=%s' % self.get('QB_MEM').replace('-m','').strip() + 'M'
689
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600690 self.qemu_opt_script += ' %s' % self.get('QB_MEM')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500691
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600692 def check_tcpserial(self):
693 if self.tcpserial_portnum:
694 if self.get('QB_TCPSERIAL_OPT'):
695 self.qemu_opt_script += ' ' + self.get('QB_TCPSERIAL_OPT').replace('@PORT@', self.tcpserial_portnum)
696 else:
697 self.qemu_opt_script += ' -serial tcp:127.0.0.1:%s' % self.tcpserial_portnum
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500698
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600699 def check_and_set(self):
700 """Check configs sanity and set when needed"""
701 self.validate_paths()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500702 if not self.slirp_enabled:
703 check_tun()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600704 # Check audio
705 if self.audio_enabled:
706 if not self.get('QB_AUDIO_DRV'):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500707 raise RunQemuError("QB_AUDIO_DRV is NULL, this board doesn't support audio")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600708 if not self.get('QB_AUDIO_OPT'):
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800709 logger.warning('QB_AUDIO_OPT is NULL, you may need define it to make audio work')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600710 else:
711 self.qemu_opt_script += ' %s' % self.get('QB_AUDIO_OPT')
712 os.putenv('QEMU_AUDIO_DRV', self.get('QB_AUDIO_DRV'))
713 else:
714 os.putenv('QEMU_AUDIO_DRV', 'none')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500715
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600716 self.check_kvm()
717 self.check_fstype()
718 self.check_rootfs()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500719 self.check_ovmf()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600720 self.check_kernel()
Brad Bishop316dfdd2018-06-25 12:45:53 -0400721 self.check_dtb()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600722 self.check_biosdir()
723 self.check_mem()
724 self.check_tcpserial()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500725
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600726 def read_qemuboot(self):
727 if not self.qemuboot:
728 if self.get('DEPLOY_DIR_IMAGE'):
729 deploy_dir_image = self.get('DEPLOY_DIR_IMAGE')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600730 else:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800731 logger.warning("Can't find qemuboot conf file, DEPLOY_DIR_IMAGE is NULL!")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600732 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500733
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600734 if self.rootfs and not os.path.exists(self.rootfs):
735 # Lazy rootfs
736 machine = self.get('MACHINE')
737 if not machine:
738 machine = os.path.basename(deploy_dir_image)
739 self.qemuboot = "%s/%s-%s.qemuboot.conf" % (deploy_dir_image,
740 self.rootfs, machine)
741 else:
742 cmd = 'ls -t %s/*.qemuboot.conf' % deploy_dir_image
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500743 logger.debug('Running %s...' % cmd)
744 try:
745 qbs = subprocess.check_output(cmd, shell=True).decode('utf-8')
746 except subprocess.CalledProcessError as err:
747 raise RunQemuError(err)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600748 if qbs:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500749 for qb in qbs.split():
750 # Don't use initramfs when other choices unless fstype is ramfs
751 if '-initramfs-' in os.path.basename(qb) and self.fstype != 'cpio.gz':
752 continue
753 self.qemuboot = qb
754 break
755 if not self.qemuboot:
756 # Use the first one when no choice
757 self.qemuboot = qbs.split()[0]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600758 self.qbconfload = True
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500759
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600760 if not self.qemuboot:
761 # If we haven't found a .qemuboot.conf at this point it probably
762 # doesn't exist, continue without
763 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500764
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600765 if not os.path.exists(self.qemuboot):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500766 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 -0500767
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500768 logger.debug('CONFFILE: %s' % self.qemuboot)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500769
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600770 cf = configparser.ConfigParser()
771 cf.read(self.qemuboot)
772 for k, v in cf.items('config_bsp'):
773 k_upper = k.upper()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500774 if v.startswith("../"):
775 v = os.path.abspath(os.path.dirname(self.qemuboot) + "/" + v)
776 elif v == ".":
777 v = os.path.dirname(self.qemuboot)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600778 self.set(k_upper, v)
779
780 def validate_paths(self):
781 """Ensure all relevant path variables are set"""
782 # When we're started with a *.qemuboot.conf arg assume that image
783 # artefacts are relative to that file, rather than in whatever
784 # directory DEPLOY_DIR_IMAGE in the conf file points to.
785 if self.qbconfload:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500786 imgdir = os.path.realpath(os.path.dirname(self.qemuboot))
787 if imgdir != os.path.realpath(self.get('DEPLOY_DIR_IMAGE')):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600788 logger.info('Setting DEPLOY_DIR_IMAGE to folder containing %s (%s)' % (self.qemuboot, imgdir))
789 self.set('DEPLOY_DIR_IMAGE', imgdir)
790
791 # If the STAGING_*_NATIVE directories from the config file don't exist
792 # and we're in a sourced OE build directory try to extract the paths
793 # from `bitbake -e`
794 havenative = os.path.exists(self.get('STAGING_DIR_NATIVE')) and \
795 os.path.exists(self.get('STAGING_BINDIR_NATIVE'))
796
797 if not havenative:
798 if not self.bitbake_e:
799 self.load_bitbake_env()
800
801 if self.bitbake_e:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500802 native_vars = ['STAGING_DIR_NATIVE']
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600803 for nv in native_vars:
804 s = re.search('^%s="(.*)"' % nv, self.bitbake_e, re.M)
805 if s and s.group(1) != self.get(nv):
806 logger.info('Overriding conf file setting of %s to %s from Bitbake environment' % (nv, s.group(1)))
807 self.set(nv, s.group(1))
808 else:
809 # when we're invoked from a running bitbake instance we won't
810 # be able to call `bitbake -e`, then try:
811 # - get OE_TMPDIR from environment and guess paths based on it
812 # - get OECORE_NATIVE_SYSROOT from environment (for sdk)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500813 tmpdir = self.get('OE_TMPDIR')
814 oecore_native_sysroot = self.get('OECORE_NATIVE_SYSROOT')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600815 if tmpdir:
816 logger.info('Setting STAGING_DIR_NATIVE and STAGING_BINDIR_NATIVE relative to OE_TMPDIR (%s)' % tmpdir)
817 hostos, _, _, _, machine = os.uname()
818 buildsys = '%s-%s' % (machine, hostos.lower())
819 staging_dir_native = '%s/sysroots/%s' % (tmpdir, buildsys)
820 self.set('STAGING_DIR_NATIVE', staging_dir_native)
821 elif oecore_native_sysroot:
822 logger.info('Setting STAGING_DIR_NATIVE to OECORE_NATIVE_SYSROOT (%s)' % oecore_native_sysroot)
823 self.set('STAGING_DIR_NATIVE', oecore_native_sysroot)
824 if self.get('STAGING_DIR_NATIVE'):
825 # we have to assume that STAGING_BINDIR_NATIVE is at usr/bin
826 staging_bindir_native = '%s/usr/bin' % self.get('STAGING_DIR_NATIVE')
827 logger.info('Setting STAGING_BINDIR_NATIVE to %s' % staging_bindir_native)
828 self.set('STAGING_BINDIR_NATIVE', '%s/usr/bin' % self.get('STAGING_DIR_NATIVE'))
829
830 def print_config(self):
831 logger.info('Continuing with the following parameters:\n')
832 if not self.fstype in self.vmtypes:
833 print('KERNEL: [%s]' % self.kernel)
834 if self.dtb:
835 print('DTB: [%s]' % self.dtb)
836 print('MACHINE: [%s]' % self.get('MACHINE'))
837 print('FSTYPE: [%s]' % self.fstype)
838 if self.fstype == 'nfs':
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500839 print('NFS_DIR: [%s]' % self.rootfs)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600840 else:
841 print('ROOTFS: [%s]' % self.rootfs)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500842 if self.ovmf_bios:
843 print('OVMF: %s' % self.ovmf_bios)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600844 print('CONFFILE: [%s]' % self.qemuboot)
845 print('')
846
847 def setup_nfs(self):
848 if not self.nfs_server:
849 if self.slirp_enabled:
850 self.nfs_server = '10.0.2.2'
851 else:
852 self.nfs_server = '192.168.7.1'
853
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500854 # Figure out a new nfs_instance to allow multiple qemus running.
Brad Bishop977dc1a2019-02-06 16:01:43 -0500855 ps = subprocess.check_output(("ps", "auxww")).decode('utf-8')
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500856 pattern = '/bin/unfsd .* -i .*\.pid -e .*/exports([0-9]+) '
857 all_instances = re.findall(pattern, ps, re.M)
858 if all_instances:
859 all_instances.sort(key=int)
860 self.nfs_instance = int(all_instances.pop()) + 1
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600861
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500862 nfsd_port = 3049 + 2 * self.nfs_instance
863 mountd_port = 3048 + 2 * self.nfs_instance
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600864
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500865 # Export vars for runqemu-export-rootfs
866 export_dict = {
867 'NFS_INSTANCE': self.nfs_instance,
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500868 'NFSD_PORT': nfsd_port,
869 'MOUNTD_PORT': mountd_port,
870 }
871 for k, v in export_dict.items():
872 # Use '%s' since they are integers
873 os.putenv(k, '%s' % v)
874
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500875 self.unfs_opts="nfsvers=3,port=%s,udp,mountport=%s" % (nfsd_port, mountd_port)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600876
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500877 # Extract .tar.bz2 or .tar.bz if no nfs dir
878 if not (self.rootfs and os.path.isdir(self.rootfs)):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600879 src_prefix = '%s/%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_LINK_NAME'))
880 dest = "%s-nfsroot" % src_prefix
881 if os.path.exists('%s.pseudo_state' % dest):
882 logger.info('Use %s as NFS_DIR' % dest)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500883 self.rootfs = dest
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600884 else:
885 src = ""
886 src1 = '%s.tar.bz2' % src_prefix
887 src2 = '%s.tar.gz' % src_prefix
888 if os.path.exists(src1):
889 src = src1
890 elif os.path.exists(src2):
891 src = src2
892 if not src:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500893 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 -0600894 logger.info('NFS_DIR not found, extracting %s to %s' % (src, dest))
Brad Bishop977dc1a2019-02-06 16:01:43 -0500895 cmd = ('runqemu-extract-sdk', src, dest)
896 logger.info('Running %s...' % str(cmd))
897 if subprocess.call(cmd) != 0:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500898 raise RunQemuError('Failed to run %s' % cmd)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600899 self.clean_nfs_dir = True
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500900 self.rootfs = dest
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600901
902 # Start the userspace NFS server
Brad Bishop977dc1a2019-02-06 16:01:43 -0500903 cmd = ('runqemu-export-rootfs', 'start', self.rootfs)
904 logger.info('Running %s...' % str(cmd))
905 if subprocess.call(cmd) != 0:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500906 raise RunQemuError('Failed to run %s' % cmd)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600907
908 self.nfs_running = True
909
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600910 def setup_slirp(self):
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500911 """Setup user networking"""
912
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600913 if self.fstype == 'nfs':
914 self.setup_nfs()
915 self.kernel_cmdline_script += ' ip=dhcp'
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500916 # Port mapping
917 hostfwd = ",hostfwd=tcp::2222-:22,hostfwd=tcp::2323-:23"
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500918 qb_slirp_opt_default = "-netdev user,id=net0%s,tftp=%s" % (hostfwd, self.get('DEPLOY_DIR_IMAGE'))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500919 qb_slirp_opt = self.get('QB_SLIRP_OPT') or qb_slirp_opt_default
920 # Figure out the port
921 ports = re.findall('hostfwd=[^-]*:([0-9]+)-[^,-]*', qb_slirp_opt)
922 ports = [int(i) for i in ports]
923 mac = 2
924 # Find a free port to avoid conflicts
925 for p in ports[:]:
926 p_new = p
927 while not check_free_port('localhost', p_new):
928 p_new += 1
929 mac += 1
930 while p_new in ports:
931 p_new += 1
932 mac += 1
933 if p != p_new:
934 ports.append(p_new)
935 qb_slirp_opt = re.sub(':%s-' % p, ':%s-' % p_new, qb_slirp_opt)
936 logger.info("Port forward changed: %s -> %s" % (p, p_new))
937 mac = "%s%02x" % (self.mac_slirp, mac)
938 self.set('NETWORK_CMD', '%s %s' % (self.network_device.replace('@MAC@', mac), qb_slirp_opt))
939 # Print out port foward
940 hostfwd = re.findall('(hostfwd=[^,]*)', qb_slirp_opt)
941 if hostfwd:
942 logger.info('Port forward: %s' % ' '.join(hostfwd))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600943
944 def setup_tap(self):
945 """Setup tap"""
946
947 # This file is created when runqemu-gen-tapdevs creates a bank of tap
948 # devices, indicating that the user should not bring up new ones using
949 # sudo.
950 nosudo_flag = '/etc/runqemu-nosudo'
951 self.qemuifup = shutil.which('runqemu-ifup')
952 self.qemuifdown = shutil.which('runqemu-ifdown')
953 ip = shutil.which('ip')
954 lockdir = "/tmp/qemu-tap-locks"
955
956 if not (self.qemuifup and self.qemuifdown and ip):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500957 logger.error("runqemu-ifup: %s" % self.qemuifup)
958 logger.error("runqemu-ifdown: %s" % self.qemuifdown)
959 logger.error("ip: %s" % ip)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600960 raise OEPathError("runqemu-ifup, runqemu-ifdown or ip not found")
961
962 if not os.path.exists(lockdir):
963 # There might be a race issue when multi runqemu processess are
964 # running at the same time.
965 try:
966 os.mkdir(lockdir)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500967 os.chmod(lockdir, 0o777)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600968 except FileExistsError:
969 pass
970
Brad Bishop977dc1a2019-02-06 16:01:43 -0500971 cmd = (ip, 'link')
972 logger.debug('Running %s...' % str(cmd))
973 ip_link = subprocess.check_output(cmd).decode('utf-8')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600974 # Matches line like: 6: tap0: <foo>
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500975 possibles = re.findall('^[0-9]+: +(tap[0-9]+): <.*', ip_link, re.M)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600976 tap = ""
977 for p in possibles:
978 lockfile = os.path.join(lockdir, p)
979 if os.path.exists('%s.skip' % lockfile):
980 logger.info('Found %s.skip, skipping %s' % (lockfile, p))
981 continue
982 self.lock = lockfile + '.lock'
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500983 if self.acquire_lock(error=False):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600984 tap = p
985 logger.info("Using preconfigured tap device %s" % tap)
986 logger.info("If this is not intended, touch %s.skip to make runqemu skip %s." %(lockfile, tap))
987 break
988
989 if not tap:
990 if os.path.exists(nosudo_flag):
991 logger.error("Error: There are no available tap devices to use for networking,")
992 logger.error("and I see %s exists, so I am not going to try creating" % nosudo_flag)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500993 raise RunQemuError("a new one with sudo.")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600994
995 gid = os.getgid()
996 uid = os.getuid()
997 logger.info("Setting up tap interface under sudo")
Brad Bishop977dc1a2019-02-06 16:01:43 -0500998 cmd = ('sudo', self.qemuifup, str(uid), str(gid), self.bindir_native)
999 tap = subprocess.check_output(cmd).decode('utf-8').strip()
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001000 lockfile = os.path.join(lockdir, tap)
1001 self.lock = lockfile + '.lock'
1002 self.acquire_lock()
1003 self.cleantap = True
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001004 logger.debug('Created tap: %s' % tap)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001005
1006 if not tap:
1007 logger.error("Failed to setup tap device. Run runqemu-gen-tapdevs to manually create.")
1008 return 1
1009 self.tap = tap
Brad Bishop37a0e4d2017-12-04 01:01:44 -05001010 tapnum = int(tap[3:])
1011 gateway = tapnum * 2 + 1
1012 client = gateway + 1
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001013 if self.fstype == 'nfs':
1014 self.setup_nfs()
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001015 netconf = "192.168.7.%s::192.168.7.%s:255.255.255.0" % (client, gateway)
1016 logger.info("Network configuration: %s", netconf)
1017 self.kernel_cmdline_script += " ip=%s" % netconf
1018 mac = "%s%02x" % (self.mac_tap, client)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001019 qb_tap_opt = self.get('QB_TAP_OPT')
1020 if qb_tap_opt:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001021 qemu_tap_opt = qb_tap_opt.replace('@TAP@', tap)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001022 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001023 qemu_tap_opt = "-netdev tap,id=net0,ifname=%s,script=no,downscript=no" % (self.tap)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001024
1025 if self.vhost_enabled:
1026 qemu_tap_opt += ',vhost=on'
1027
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001028 self.set('NETWORK_CMD', '%s %s' % (self.network_device.replace('@MAC@', mac), qemu_tap_opt))
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001029
1030 def setup_network(self):
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001031 if self.get('QB_NET') == 'none':
1032 return
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001033 if sys.stdin.isatty():
Brad Bishop977dc1a2019-02-06 16:01:43 -05001034 self.saved_stty = subprocess.check_output(("stty", "-g")).decode('utf-8').strip()
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001035 self.network_device = self.get('QB_NETWORK_DEVICE') or self.network_device
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001036 if self.slirp_enabled:
1037 self.setup_slirp()
1038 else:
1039 self.setup_tap()
1040
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001041 def setup_rootfs(self):
1042 if self.get('QB_ROOTFS') == 'none':
1043 return
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001044 if 'wic.' in self.fstype:
1045 self.fstype = self.fstype[4:]
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001046 rootfs_format = self.fstype if self.fstype in ('vmdk', 'qcow2', 'vdi') else 'raw'
1047
1048 qb_rootfs_opt = self.get('QB_ROOTFS_OPT')
1049 if qb_rootfs_opt:
1050 self.rootfs_options = qb_rootfs_opt.replace('@ROOTFS@', self.rootfs)
1051 else:
1052 self.rootfs_options = '-drive file=%s,if=virtio,format=%s' % (self.rootfs, rootfs_format)
1053
1054 if self.fstype in ('cpio.gz', 'cpio'):
1055 self.kernel_cmdline = 'root=/dev/ram0 rw debugshell'
1056 self.rootfs_options = '-initrd %s' % self.rootfs
1057 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001058 vm_drive = ''
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001059 if self.fstype in self.vmtypes:
1060 if self.fstype == 'iso':
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001061 vm_drive = '-drive file=%s,if=virtio,media=cdrom' % self.rootfs
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001062 elif self.get('QB_DRIVE_TYPE'):
1063 drive_type = self.get('QB_DRIVE_TYPE')
1064 if drive_type.startswith("/dev/sd"):
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001065 logger.info('Using scsi drive')
1066 vm_drive = '-drive if=none,id=hd,file=%s,format=%s -device virtio-scsi-pci,id=scsi -device scsi-hd,drive=hd' \
1067 % (self.rootfs, rootfs_format)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001068 elif drive_type.startswith("/dev/hd"):
Brad Bishop37a0e4d2017-12-04 01:01:44 -05001069 logger.info('Using ide drive')
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001070 vm_drive = "-drive file=%s,format=%s" % (self.rootfs, rootfs_format)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001071 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001072 # virtio might have been selected explicitly (just use it), or
1073 # is used as fallback (then warn about that).
1074 if not drive_type.startswith("/dev/vd"):
Brad Bishop1a4b7ee2018-12-16 17:11:34 -08001075 logger.warning("Unknown QB_DRIVE_TYPE: %s" % drive_type)
1076 logger.warning("Failed to figure out drive type, consider define or fix QB_DRIVE_TYPE")
1077 logger.warning('Trying to use virtio block drive')
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001078 vm_drive = '-drive if=virtio,file=%s,format=%s' % (self.rootfs, rootfs_format)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001079
1080 # All branches above set vm_drive.
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001081 self.rootfs_options = '%s -no-reboot' % vm_drive
1082 self.kernel_cmdline = 'root=%s rw highres=off' % (self.get('QB_KERNEL_ROOT'))
1083
1084 if self.fstype == 'nfs':
1085 self.rootfs_options = ''
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001086 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 -06001087 self.kernel_cmdline = 'root=%s rw highres=off' % k_root
1088
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001089 if self.fstype == 'none':
1090 self.rootfs_options = ''
1091
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001092 self.set('ROOTFS_OPTIONS', self.rootfs_options)
1093
1094 def guess_qb_system(self):
1095 """attempt to determine the appropriate qemu-system binary"""
1096 mach = self.get('MACHINE')
1097 if not mach:
1098 search = '.*(qemux86-64|qemux86|qemuarm64|qemuarm|qemumips64|qemumips64el|qemumipsel|qemumips|qemuppc).*'
1099 if self.rootfs:
1100 match = re.match(search, self.rootfs)
1101 if match:
1102 mach = match.group(1)
1103 elif self.kernel:
1104 match = re.match(search, self.kernel)
1105 if match:
1106 mach = match.group(1)
1107
1108 if not mach:
1109 return None
1110
1111 if mach == 'qemuarm':
1112 qbsys = 'arm'
1113 elif mach == 'qemuarm64':
1114 qbsys = 'aarch64'
1115 elif mach == 'qemux86':
1116 qbsys = 'i386'
1117 elif mach == 'qemux86-64':
1118 qbsys = 'x86_64'
1119 elif mach == 'qemuppc':
1120 qbsys = 'ppc'
1121 elif mach == 'qemumips':
1122 qbsys = 'mips'
1123 elif mach == 'qemumips64':
1124 qbsys = 'mips64'
1125 elif mach == 'qemumipsel':
1126 qbsys = 'mipsel'
1127 elif mach == 'qemumips64el':
1128 qbsys = 'mips64el'
Brad Bishop316dfdd2018-06-25 12:45:53 -04001129 elif mach == 'qemuriscv64':
1130 qbsys = 'riscv64'
1131 elif mach == 'qemuriscv32':
1132 qbsys = 'riscv32'
Brad Bishop004d4992018-10-02 23:54:45 +02001133 else:
1134 logger.error("Unable to determine QEMU PC System emulator for %s machine." % mach)
1135 logger.error("As %s is not among valid QEMU machines such as," % mach)
1136 logger.error("qemux86-64, qemux86, qemuarm64, qemuarm, qemumips64, qemumips64el, qemumipsel, qemumips, qemuppc")
1137 raise RunQemuError("Set qb_system_name with suitable QEMU PC System emulator in .*qemuboot.conf.")
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001138
1139 return 'qemu-system-%s' % qbsys
1140
1141 def setup_final(self):
1142 qemu_system = self.get('QB_SYSTEM_NAME')
1143 if not qemu_system:
1144 qemu_system = self.guess_qb_system()
1145 if not qemu_system:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001146 raise RunQemuError("Failed to boot, QB_SYSTEM_NAME is NULL!")
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001147
Brad Bishop977dc1a2019-02-06 16:01:43 -05001148 qemu_bin = os.path.join(self.bindir_native, qemu_system)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001149
1150 # It is possible to have qemu-native in ASSUME_PROVIDED, and it won't
1151 # find QEMU in sysroot, it needs to use host's qemu.
1152 if not os.path.exists(qemu_bin):
1153 logger.info("QEMU binary not found in %s, trying host's QEMU" % qemu_bin)
1154 for path in (os.environ['PATH'] or '').split(':'):
1155 qemu_bin_tmp = os.path.join(path, qemu_system)
1156 logger.info("Trying: %s" % qemu_bin_tmp)
1157 if os.path.exists(qemu_bin_tmp):
1158 qemu_bin = qemu_bin_tmp
1159 if not os.path.isabs(qemu_bin):
1160 qemu_bin = os.path.abspath(qemu_bin)
1161 logger.info("Using host's QEMU: %s" % qemu_bin)
1162 break
1163
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001164 if not os.access(qemu_bin, os.X_OK):
1165 raise OEPathError("No QEMU binary '%s' could be found" % qemu_bin)
1166
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001167 self.qemu_opt = "%s %s %s %s" % (qemu_bin, self.get('NETWORK_CMD'), self.get('ROOTFS_OPTIONS'), self.get('QB_OPT_APPEND'))
1168
1169 for ovmf in self.ovmf_bios:
1170 format = ovmf.rsplit('.', 1)[-1]
1171 self.qemu_opt += ' -drive if=pflash,format=%s,file=%s' % (format, ovmf)
1172 if self.ovmf_bios:
1173 # OVMF only supports normal VGA, i.e. we need to override a -vga vmware
1174 # that gets added for example for normal qemux86.
1175 self.qemu_opt += ' -vga std'
1176
1177 self.qemu_opt += ' ' + self.qemu_opt_script
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001178
Andrew Geissler99467da2019-02-25 18:54:23 -06001179 # Append qemuparams to override previous settings
1180 if self.qemuparams:
1181 self.qemu_opt += ' ' + self.qemuparams
1182
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001183 if self.snapshot:
1184 self.qemu_opt += " -snapshot"
1185
Brad Bishop19323692019-04-05 15:28:33 -04001186 if self.serialconsole:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001187 if sys.stdin.isatty():
Brad Bishop977dc1a2019-02-06 16:01:43 -05001188 subprocess.check_call(("stty", "intr", "^]"))
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001189 logger.info("Interrupt character is '^]'")
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001190
1191 first_serial = ""
1192 if not re.search("-nographic", self.qemu_opt):
1193 first_serial = "-serial mon:vc"
1194 # We always want a ttyS1. Since qemu by default adds a serial
1195 # port when nodefaults is not specified, it seems that all that
1196 # would be needed is to make sure a "-serial" is there. However,
1197 # it appears that when "-serial" is specified, it ignores the
1198 # default serial port that is normally added. So here we make
1199 # sure to add two -serial if there are none. And only one if
1200 # there is one -serial already.
1201 serial_num = len(re.findall("-serial", self.qemu_opt))
1202 if serial_num == 0:
1203 self.qemu_opt += " %s %s" % (first_serial, self.get("QB_SERIAL_OPT"))
1204 elif serial_num == 1:
1205 self.qemu_opt += " %s" % self.get("QB_SERIAL_OPT")
1206
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001207 # We always wants ttyS0 and ttyS1 in qemu machines (see SERIAL_CONSOLES),
1208 # if not serial or serialtcp options was specified only ttyS0 is created
1209 # and sysvinit shows an error trying to enable ttyS1:
1210 # INIT: Id "S1" respawning too fast: disabled for 5 minutes
1211 serial_num = len(re.findall("-serial", self.qemu_opt))
1212 if serial_num == 0:
Brad Bishop19323692019-04-05 15:28:33 -04001213 if re.search("-nographic", self.qemu_opt) or self.serialstdio:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001214 self.qemu_opt += " -serial mon:stdio -serial null"
1215 else:
1216 self.qemu_opt += " -serial mon:vc -serial null"
1217
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001218 def start_qemu(self):
Brad Bishop004d4992018-10-02 23:54:45 +02001219 import shlex
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001220 if self.kernel:
Brad Bishop37a0e4d2017-12-04 01:01:44 -05001221 kernel_opts = "-kernel %s -append '%s %s %s %s'" % (self.kernel, self.kernel_cmdline,
1222 self.kernel_cmdline_script, self.get('QB_KERNEL_CMDLINE_APPEND'),
1223 self.bootparams)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001224 if self.dtb:
1225 kernel_opts += " -dtb %s" % self.dtb
1226 else:
1227 kernel_opts = ""
1228 cmd = "%s %s" % (self.qemu_opt, kernel_opts)
Brad Bishop004d4992018-10-02 23:54:45 +02001229 cmds = shlex.split(cmd)
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001230 logger.info('Running %s\n' % cmd)
Brad Bishopf86d0552018-12-04 14:18:15 -08001231 pass_fds = []
1232 if self.lock_descriptor:
1233 pass_fds = [self.lock_descriptor.fileno()]
1234 process = subprocess.Popen(cmds, stderr=subprocess.PIPE, pass_fds=pass_fds)
Brad Bishop004d4992018-10-02 23:54:45 +02001235 self.qemupid = process.pid
1236 retcode = process.wait()
1237 if retcode:
1238 if retcode == -signal.SIGTERM:
1239 logger.info("Qemu terminated by SIGTERM")
1240 else:
1241 logger.error("Failed to run qemu: %s", process.stderr.read().decode())
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001242
1243 def cleanup(self):
Brad Bishop004d4992018-10-02 23:54:45 +02001244 if self.cleaned:
1245 return
1246
1247 # avoid dealing with SIGTERM when cleanup function is running
1248 signal.signal(signal.SIGTERM, signal.SIG_IGN)
1249
1250 logger.info("Cleaning up")
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001251 if self.cleantap:
Brad Bishop977dc1a2019-02-06 16:01:43 -05001252 cmd = ('sudo', self.qemuifdown, self.tap, self.bindir_native)
1253 logger.debug('Running %s' % str(cmd))
1254 subprocess.check_call(cmd)
Brad Bishopf86d0552018-12-04 14:18:15 -08001255 self.release_lock()
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001256
1257 if self.nfs_running:
1258 logger.info("Shutting down the userspace NFS server...")
Brad Bishop977dc1a2019-02-06 16:01:43 -05001259 cmd = ("runqemu-export-rootfs", "stop", self.rootfs)
1260 logger.debug('Running %s' % str(cmd))
1261 subprocess.check_call(cmd)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001262
1263 if self.saved_stty:
Brad Bishop977dc1a2019-02-06 16:01:43 -05001264 subprocess.check_call(("stty", self.saved_stty))
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001265
1266 if self.clean_nfs_dir:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001267 logger.info('Removing %s' % self.rootfs)
1268 shutil.rmtree(self.rootfs)
1269 shutil.rmtree('%s.pseudo_state' % self.rootfs)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001270
Brad Bishop004d4992018-10-02 23:54:45 +02001271 self.cleaned = True
1272
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001273 def load_bitbake_env(self, mach=None):
1274 if self.bitbake_e:
1275 return
1276
1277 bitbake = shutil.which('bitbake')
1278 if not bitbake:
1279 return
1280
1281 if not mach:
1282 mach = self.get('MACHINE')
1283
1284 if mach:
1285 cmd = 'MACHINE=%s bitbake -e' % mach
1286 else:
1287 cmd = 'bitbake -e'
1288
1289 logger.info('Running %s...' % cmd)
1290 try:
1291 self.bitbake_e = subprocess.check_output(cmd, shell=True).decode('utf-8')
1292 except subprocess.CalledProcessError as err:
1293 self.bitbake_e = ''
Brad Bishop1a4b7ee2018-12-16 17:11:34 -08001294 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 -06001295
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001296 def validate_combos(self):
1297 if (self.fstype in self.vmtypes) and self.kernel:
1298 raise RunQemuError("%s doesn't need kernel %s!" % (self.fstype, self.kernel))
1299
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001300 @property
1301 def bindir_native(self):
1302 result = self.get('STAGING_BINDIR_NATIVE')
1303 if result and os.path.exists(result):
1304 return result
1305
Brad Bishop977dc1a2019-02-06 16:01:43 -05001306 cmd = ('bitbake', 'qemu-helper-native', '-e')
1307 logger.info('Running %s...' % str(cmd))
1308 out = subprocess.check_output(cmd).decode('utf-8')
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001309
1310 match = re.search('^STAGING_BINDIR_NATIVE="(.*)"', out, re.M)
1311 if match:
1312 result = match.group(1)
1313 if os.path.exists(result):
1314 self.set('STAGING_BINDIR_NATIVE', result)
1315 return result
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001316 raise RunQemuError("Native sysroot directory %s doesn't exist" % result)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001317 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001318 raise RunQemuError("Can't find STAGING_BINDIR_NATIVE in '%s' output" % cmd)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001319
1320
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001321def main():
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001322 if "help" in sys.argv or '-h' in sys.argv or '--help' in sys.argv:
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001323 print_usage()
1324 return 0
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001325 try:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001326 config = BaseConfig()
Brad Bishop004d4992018-10-02 23:54:45 +02001327
1328 def sigterm_handler(signum, frame):
1329 logger.info("SIGTERM received")
1330 os.kill(config.qemupid, signal.SIGTERM)
1331 config.cleanup()
Brad Bishopf86d0552018-12-04 14:18:15 -08001332 subprocess.check_call(["tput", "smam"])
Brad Bishop004d4992018-10-02 23:54:45 +02001333 signal.signal(signal.SIGTERM, sigterm_handler)
1334
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001335 config.check_args()
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001336 config.read_qemuboot()
1337 config.check_and_set()
1338 # Check whether the combos is valid or not
1339 config.validate_combos()
1340 config.print_config()
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001341 config.setup_network()
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001342 config.setup_rootfs()
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001343 config.setup_final()
1344 config.start_qemu()
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001345 except RunQemuError as err:
1346 logger.error(err)
1347 return 1
1348 except Exception as err:
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001349 import traceback
1350 traceback.print_exc()
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001351 return 1
1352 finally:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001353 config.cleanup()
Brad Bishopf86d0552018-12-04 14:18:15 -08001354 subprocess.check_call(["tput", "smam"])
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001355
1356if __name__ == "__main__":
1357 sys.exit(main())