blob: bd3aee0c2fcf456c04978351a24ff5c0aa021501 [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
77 serial - enable a serial console on /dev/ttyS0
78 slirp - enable user networking, no root privileges is required
79 kvm - enable KVM when running x86/x86_64 (VT-capable CPU required)
80 kvm-vhost - enable KVM with vhost when running x86/x86_64 (VT-capable CPU required)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050081 publicvnc - enable a VNC server open to all hosts
Patrick Williamsc0f7c042017-02-23 20:41:17 -060082 audio - enable audio
Brad Bishop6e60e8b2018-02-01 10:27:11 -050083 [*/]ovmf* - OVMF firmware file or base name for booting with UEFI
Patrick Williamsc0f7c042017-02-23 20:41:17 -060084 tcpserial=<port> - specify tcp serial port number
85 biosdir=<dir> - specify custom bios dir
86 biosfilename=<filename> - specify bios filename
87 qemuparams=<xyz> - specify custom parameters to QEMU
88 bootparams=<xyz> - specify custom kernel parameters during boot
Brad Bishop6e60e8b2018-02-01 10:27:11 -050089 help, -h, --help: print this text
Brad Bishopd7bf8c12018-02-25 22:55:05 -050090 -d, --debug: Enable debug output
91 -q, --quite: Hide most output except error messages
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050092
93Examples:
Brad Bishop6e60e8b2018-02-01 10:27:11 -050094 runqemu
Patrick Williamsc0f7c042017-02-23 20:41:17 -060095 runqemu qemuarm
96 runqemu tmp/deploy/images/qemuarm
Brad Bishop6e60e8b2018-02-01 10:27:11 -050097 runqemu tmp/deploy/images/qemux86/<qemuboot.conf>
Patrick Williamsc0f7c042017-02-23 20:41:17 -060098 runqemu qemux86-64 core-image-sato ext4
99 runqemu qemux86-64 wic-image-minimal wic
100 runqemu path/to/bzImage-qemux86.bin path/to/nfsrootdir/ serial
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500101 runqemu qemux86 iso/hddimg/wic.vmdk/wic.qcow2/wic.vdi/ramfs/cpio.gz...
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600102 runqemu qemux86 qemuparams="-m 256"
103 runqemu qemux86 bootparams="psplash=false"
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600104 runqemu path/to/<image>-<machine>.wic
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500105 runqemu path/to/<image>-<machine>.wic.vmdk
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600106""")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500107
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600108def check_tun():
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500109 """Check /dev/net/tun"""
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600110 dev_tun = '/dev/net/tun'
111 if not os.path.exists(dev_tun):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500112 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 -0500113
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600114 if not os.access(dev_tun, os.W_OK):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500115 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 -0500116
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600117def check_libgl(qemu_bin):
118 cmd = 'ldd %s' % qemu_bin
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500119 logger.debug('Running %s...' % cmd)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600120 need_gl = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
121 if re.search('libGLU', need_gl):
122 # We can't run without a libGL.so
123 libgl = False
124 check_files = (('/usr/lib/libGL.so', '/usr/lib/libGLU.so'), \
125 ('/usr/lib64/libGL.so', '/usr/lib64/libGLU.so'), \
126 ('/usr/lib/*-linux-gnu/libGL.so', '/usr/lib/*-linux-gnu/libGLU.so'))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500127
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600128 for (f1, f2) in check_files:
129 if re.search('\*', f1):
130 for g1 in glob.glob(f1):
131 if libgl:
132 break
133 if os.path.exists(g1):
134 for g2 in glob.glob(f2):
135 if os.path.exists(g2):
136 libgl = True
137 break
138 if libgl:
139 break
140 else:
141 if os.path.exists(f1) and os.path.exists(f2):
142 libgl = True
143 break
144 if not libgl:
145 logger.error("You need libGL.so and libGLU.so to exist in your library path to run the QEMU emulator.")
146 logger.error("Ubuntu package names are: libgl1-mesa-dev and libglu1-mesa-dev.")
147 logger.error("Fedora package names are: mesa-libGL-devel mesa-libGLU-devel.")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500148 raise RunQemuError('%s requires libGLU, but not found' % qemu_bin)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500149
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600150def get_first_file(cmds):
151 """Return first file found in wildcard cmds"""
152 for cmd in cmds:
153 all_files = glob.glob(cmd)
154 if all_files:
155 for f in all_files:
156 if not os.path.isdir(f):
157 return f
158 return ''
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500159
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500160def check_free_port(host, port):
161 """ Check whether the port is free or not """
162 import socket
163 from contextlib import closing
164
165 with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
166 if sock.connect_ex((host, port)) == 0:
167 # Port is open, so not free
168 return False
169 else:
170 # Port is not open, so free
171 return True
172
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600173class BaseConfig(object):
174 def __init__(self):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500175 # The self.d saved vars from self.set(), part of them are from qemuboot.conf
176 self.d = {'QB_KERNEL_ROOT': '/dev/vda'}
177
178 # Supported env vars, add it here if a var can be got from env,
179 # and don't use os.getenv in the code.
180 self.env_vars = ('MACHINE',
181 'ROOTFS',
182 'KERNEL',
Brad Bishop316dfdd2018-06-25 12:45:53 -0400183 'DEVICE_TREE',
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500184 'DEPLOY_DIR_IMAGE',
185 'OE_TMPDIR',
186 'OECORE_NATIVE_SYSROOT',
187 )
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500188
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600189 self.qemu_opt = ''
190 self.qemu_opt_script = ''
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600191 self.clean_nfs_dir = False
192 self.nfs_server = ''
193 self.rootfs = ''
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500194 # File name(s) of a OVMF firmware file or variable store,
195 # to be added with -drive if=pflash.
196 # Found in the same places as the rootfs, with or without one of
197 # these suffices: qcow2, bin.
198 # Setting one also adds "-vga std" because that is all that
199 # OVMF supports.
200 self.ovmf_bios = []
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600201 self.qemuboot = ''
202 self.qbconfload = False
203 self.kernel = ''
204 self.kernel_cmdline = ''
205 self.kernel_cmdline_script = ''
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500206 self.bootparams = ''
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600207 self.dtb = ''
208 self.fstype = ''
209 self.kvm_enabled = False
210 self.vhost_enabled = False
211 self.slirp_enabled = False
212 self.nfs_instance = 0
213 self.nfs_running = False
214 self.serialstdio = False
215 self.cleantap = False
216 self.saved_stty = ''
217 self.audio_enabled = False
218 self.tcpserial_portnum = ''
219 self.custombiosdir = ''
220 self.lock = ''
221 self.lock_descriptor = ''
222 self.bitbake_e = ''
223 self.snapshot = False
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500224 self.fstypes = ('ext2', 'ext3', 'ext4', 'jffs2', 'nfs', 'btrfs',
225 'cpio.gz', 'cpio', 'ramfs', 'tar.bz2', 'tar.gz')
226 self.vmtypes = ('hddimg', 'hdddirect', 'wic', 'wic.vmdk',
227 'wic.qcow2', 'wic.vdi', 'iso')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500228 self.network_device = "-device e1000,netdev=net0,mac=@MAC@"
229 # Use different mac section for tap and slirp to avoid
230 # conflicts, e.g., when one is running with tap, the other is
231 # running with slirp.
232 # The last section is dynamic, which is for avoiding conflicts,
233 # when multiple qemus are running, e.g., when multiple tap or
234 # slirp qemus are running.
235 self.mac_tap = "52:54:00:12:34:"
236 self.mac_slirp = "52:54:00:12:35:"
Brad Bishop004d4992018-10-02 23:54:45 +0200237 # pid of the actual qemu process
238 self.qemupid = None
239 # avoid cleanup twice
240 self.cleaned = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500241
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500242 def acquire_lock(self, error=True):
243 logger.debug("Acquiring lockfile %s..." % self.lock)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600244 try:
245 self.lock_descriptor = open(self.lock, 'w')
246 fcntl.flock(self.lock_descriptor, fcntl.LOCK_EX|fcntl.LOCK_NB)
247 except Exception as e:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500248 msg = "Acquiring lockfile %s failed: %s" % (self.lock, e)
249 if error:
250 logger.error(msg)
251 else:
252 logger.info(msg)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600253 if self.lock_descriptor:
254 self.lock_descriptor.close()
255 return False
256 return True
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500257
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600258 def release_lock(self):
259 fcntl.flock(self.lock_descriptor, fcntl.LOCK_UN)
260 self.lock_descriptor.close()
261 os.remove(self.lock)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500262
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600263 def get(self, key):
264 if key in self.d:
265 return self.d.get(key)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500266 elif os.getenv(key):
267 return os.getenv(key)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600268 else:
269 return ''
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500270
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600271 def set(self, key, value):
272 self.d[key] = value
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500273
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600274 def is_deploy_dir_image(self, p):
275 if os.path.isdir(p):
276 if not re.search('.qemuboot.conf$', '\n'.join(os.listdir(p)), re.M):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500277 logger.debug("Can't find required *.qemuboot.conf in %s" % p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600278 return False
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500279 if not any(map(lambda name: '-image-' in name, os.listdir(p))):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500280 logger.debug("Can't find *-image-* in %s" % p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600281 return False
282 return True
283 else:
284 return False
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500285
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600286 def check_arg_fstype(self, fst):
287 """Check and set FSTYPE"""
288 if fst not in self.fstypes + self.vmtypes:
289 logger.warn("Maybe unsupported FSTYPE: %s" % fst)
290 if not self.fstype or self.fstype == fst:
291 if fst == 'ramfs':
292 fst = 'cpio.gz'
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500293 if fst in ('tar.bz2', 'tar.gz'):
294 fst = 'nfs'
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600295 self.fstype = fst
296 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500297 raise RunQemuError("Conflicting: FSTYPE %s and %s" % (self.fstype, fst))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500298
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600299 def set_machine_deploy_dir(self, machine, deploy_dir_image):
300 """Set MACHINE and DEPLOY_DIR_IMAGE"""
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500301 logger.debug('MACHINE: %s' % machine)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600302 self.set("MACHINE", machine)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500303 logger.debug('DEPLOY_DIR_IMAGE: %s' % deploy_dir_image)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600304 self.set("DEPLOY_DIR_IMAGE", deploy_dir_image)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500305
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600306 def check_arg_nfs(self, p):
307 if os.path.isdir(p):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500308 self.rootfs = p
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600309 else:
310 m = re.match('(.*):(.*)', p)
311 self.nfs_server = m.group(1)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500312 self.rootfs = m.group(2)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600313 self.check_arg_fstype('nfs')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500314
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600315 def check_arg_path(self, p):
316 """
317 - Check whether it is <image>.qemuboot.conf or contains <image>.qemuboot.conf
318 - Check whether is a kernel file
319 - Check whether is a image file
320 - Check whether it is a nfs dir
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500321 - Check whether it is a OVMF flash file
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600322 """
323 if p.endswith('.qemuboot.conf'):
324 self.qemuboot = p
325 self.qbconfload = True
326 elif re.search('\.bin$', p) or re.search('bzImage', p) or \
327 re.search('zImage', p) or re.search('vmlinux', p) or \
328 re.search('fitImage', p) or re.search('uImage', p):
329 self.kernel = p
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500330 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 -0600331 self.rootfs = p
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500332 # Check filename against self.fstypes can hanlde <file>.cpio.gz,
333 # otherwise, its type would be "gz", which is incorrect.
334 fst = ""
335 for t in self.fstypes:
336 if p.endswith(t):
337 fst = t
338 break
339 if not fst:
340 m = re.search('.*\.(.*)$', self.rootfs)
341 if m:
342 fst = m.group(1)
343 if fst:
344 self.check_arg_fstype(fst)
345 qb = re.sub('\.' + fst + "$", '', self.rootfs)
346 qb = '%s%s' % (re.sub('\.rootfs$', '', qb), '.qemuboot.conf')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600347 if os.path.exists(qb):
348 self.qemuboot = qb
349 self.qbconfload = True
350 else:
351 logger.warn("%s doesn't exist" % qb)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600352 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500353 raise RunQemuError("Can't find FSTYPE from: %s" % p)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500354
355 elif os.path.isdir(p) or re.search(':', p) and re.search('/', p):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600356 if self.is_deploy_dir_image(p):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500357 logger.debug('DEPLOY_DIR_IMAGE: %s' % p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600358 self.set("DEPLOY_DIR_IMAGE", p)
359 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500360 logger.debug("Assuming %s is an nfs rootfs" % p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600361 self.check_arg_nfs(p)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500362 elif os.path.basename(p).startswith('ovmf'):
363 self.ovmf_bios.append(p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600364 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500365 raise RunQemuError("Unknown path arg %s" % p)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500366
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600367 def check_arg_machine(self, arg):
368 """Check whether it is a machine"""
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500369 if self.get('MACHINE') == arg:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600370 return
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500371 elif self.get('MACHINE') and self.get('MACHINE') != arg:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500372 raise RunQemuError("Maybe conflicted MACHINE: %s vs %s" % (self.get('MACHINE'), arg))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500373 elif re.search('/', arg):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500374 raise RunQemuError("Unknown arg: %s" % arg)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500375
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500376 logger.debug('Assuming MACHINE = %s' % arg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500377
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600378 # if we're running under testimage, or similarly as a child
379 # of an existing bitbake invocation, we can't invoke bitbake
380 # to validate the MACHINE setting and must assume it's correct...
381 # FIXME: testimage.bbclass exports these two variables into env,
382 # are there other scenarios in which we need to support being
383 # invoked by bitbake?
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500384 deploy = self.get('DEPLOY_DIR_IMAGE')
385 bbchild = deploy and self.get('OE_TMPDIR')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600386 if bbchild:
387 self.set_machine_deploy_dir(arg, deploy)
388 return
389 # also check whether we're running under a sourced toolchain
390 # environment file
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500391 if self.get('OECORE_NATIVE_SYSROOT'):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600392 self.set("MACHINE", arg)
393 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500394
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600395 cmd = 'MACHINE=%s bitbake -e' % arg
396 logger.info('Running %s...' % cmd)
397 self.bitbake_e = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
398 # bitbake -e doesn't report invalid MACHINE as an error, so
399 # let's check DEPLOY_DIR_IMAGE to make sure that it is a valid
400 # MACHINE.
401 s = re.search('^DEPLOY_DIR_IMAGE="(.*)"', self.bitbake_e, re.M)
402 if s:
403 deploy_dir_image = s.group(1)
404 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500405 raise RunQemuError("bitbake -e %s" % self.bitbake_e)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600406 if self.is_deploy_dir_image(deploy_dir_image):
407 self.set_machine_deploy_dir(arg, deploy_dir_image)
408 else:
409 logger.error("%s not a directory valid DEPLOY_DIR_IMAGE" % deploy_dir_image)
410 self.set("MACHINE", arg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500411
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600412 def check_args(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500413 for debug in ("-d", "--debug"):
414 if debug in sys.argv:
415 logger.setLevel(logging.DEBUG)
416 sys.argv.remove(debug)
417
418 for quiet in ("-q", "--quiet"):
419 if quiet in sys.argv:
420 logger.setLevel(logging.ERROR)
421 sys.argv.remove(quiet)
422
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600423 unknown_arg = ""
424 for arg in sys.argv[1:]:
425 if arg in self.fstypes + self.vmtypes:
426 self.check_arg_fstype(arg)
427 elif arg == 'nographic':
428 self.qemu_opt_script += ' -nographic'
429 self.kernel_cmdline_script += ' console=ttyS0'
430 elif arg == 'serial':
431 self.kernel_cmdline_script += ' console=ttyS0'
432 self.serialstdio = True
433 elif arg == 'audio':
434 logger.info("Enabling audio in qemu")
435 logger.info("Please install sound drivers in linux host")
436 self.audio_enabled = True
437 elif arg == 'kvm':
438 self.kvm_enabled = True
439 elif arg == 'kvm-vhost':
440 self.vhost_enabled = True
441 elif arg == 'slirp':
442 self.slirp_enabled = True
443 elif arg == 'snapshot':
444 self.snapshot = True
445 elif arg == 'publicvnc':
446 self.qemu_opt_script += ' -vnc :0'
447 elif arg.startswith('tcpserial='):
448 self.tcpserial_portnum = arg[len('tcpserial='):]
449 elif arg.startswith('biosdir='):
450 self.custombiosdir = arg[len('biosdir='):]
451 elif arg.startswith('biosfilename='):
452 self.qemu_opt_script += ' -bios %s' % arg[len('biosfilename='):]
453 elif arg.startswith('qemuparams='):
454 self.qemu_opt_script += ' %s' % arg[len('qemuparams='):]
455 elif arg.startswith('bootparams='):
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500456 self.bootparams = arg[len('bootparams='):]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600457 elif os.path.exists(arg) or (re.search(':', arg) and re.search('/', arg)):
458 self.check_arg_path(os.path.abspath(arg))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500459 elif re.search(r'-image-|-image$', arg):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600460 # Lazy rootfs
461 self.rootfs = arg
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500462 elif arg.startswith('ovmf'):
463 self.ovmf_bios.append(arg)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600464 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500465 # At last, assume it is the MACHINE
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600466 if (not unknown_arg) or unknown_arg == arg:
467 unknown_arg = arg
468 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500469 raise RunQemuError("Can't handle two unknown args: %s %s\n"
470 "Try 'runqemu help' on how to use it" % \
471 (unknown_arg, arg))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600472 # Check to make sure it is a valid machine
473 if unknown_arg:
474 if self.get('MACHINE') == unknown_arg:
475 return
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500476 if self.get('DEPLOY_DIR_IMAGE'):
477 machine = os.path.basename(self.get('DEPLOY_DIR_IMAGE'))
478 if unknown_arg == machine:
479 self.set("MACHINE", machine)
480 return
481
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):
664 s = re.search('-m +([0-9]+)', self.qemu_opt_script)
665 if s:
666 self.set('QB_MEM', '-m %s' % s.group(1))
667 elif not self.get('QB_MEM'):
668 logger.info('QB_MEM is not set, use 512M by default')
669 self.set('QB_MEM', '-m 512')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500670
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600671 self.kernel_cmdline_script += ' mem=%s' % self.get('QB_MEM').replace('-m','').strip() + 'M'
672 self.qemu_opt_script += ' %s' % self.get('QB_MEM')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500673
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600674 def check_tcpserial(self):
675 if self.tcpserial_portnum:
676 if self.get('QB_TCPSERIAL_OPT'):
677 self.qemu_opt_script += ' ' + self.get('QB_TCPSERIAL_OPT').replace('@PORT@', self.tcpserial_portnum)
678 else:
679 self.qemu_opt_script += ' -serial tcp:127.0.0.1:%s' % self.tcpserial_portnum
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500680
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600681 def check_and_set(self):
682 """Check configs sanity and set when needed"""
683 self.validate_paths()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500684 if not self.slirp_enabled:
685 check_tun()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600686 # Check audio
687 if self.audio_enabled:
688 if not self.get('QB_AUDIO_DRV'):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500689 raise RunQemuError("QB_AUDIO_DRV is NULL, this board doesn't support audio")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600690 if not self.get('QB_AUDIO_OPT'):
691 logger.warn('QB_AUDIO_OPT is NULL, you may need define it to make audio work')
692 else:
693 self.qemu_opt_script += ' %s' % self.get('QB_AUDIO_OPT')
694 os.putenv('QEMU_AUDIO_DRV', self.get('QB_AUDIO_DRV'))
695 else:
696 os.putenv('QEMU_AUDIO_DRV', 'none')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500697
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600698 self.check_kvm()
699 self.check_fstype()
700 self.check_rootfs()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500701 self.check_ovmf()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600702 self.check_kernel()
Brad Bishop316dfdd2018-06-25 12:45:53 -0400703 self.check_dtb()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600704 self.check_biosdir()
705 self.check_mem()
706 self.check_tcpserial()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500707
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600708 def read_qemuboot(self):
709 if not self.qemuboot:
710 if self.get('DEPLOY_DIR_IMAGE'):
711 deploy_dir_image = self.get('DEPLOY_DIR_IMAGE')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600712 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500713 logger.warn("Can't find qemuboot conf file, DEPLOY_DIR_IMAGE is NULL!")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600714 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500715
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600716 if self.rootfs and not os.path.exists(self.rootfs):
717 # Lazy rootfs
718 machine = self.get('MACHINE')
719 if not machine:
720 machine = os.path.basename(deploy_dir_image)
721 self.qemuboot = "%s/%s-%s.qemuboot.conf" % (deploy_dir_image,
722 self.rootfs, machine)
723 else:
724 cmd = 'ls -t %s/*.qemuboot.conf' % deploy_dir_image
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500725 logger.debug('Running %s...' % cmd)
726 try:
727 qbs = subprocess.check_output(cmd, shell=True).decode('utf-8')
728 except subprocess.CalledProcessError as err:
729 raise RunQemuError(err)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600730 if qbs:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500731 for qb in qbs.split():
732 # Don't use initramfs when other choices unless fstype is ramfs
733 if '-initramfs-' in os.path.basename(qb) and self.fstype != 'cpio.gz':
734 continue
735 self.qemuboot = qb
736 break
737 if not self.qemuboot:
738 # Use the first one when no choice
739 self.qemuboot = qbs.split()[0]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600740 self.qbconfload = True
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500741
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600742 if not self.qemuboot:
743 # If we haven't found a .qemuboot.conf at this point it probably
744 # doesn't exist, continue without
745 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500746
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600747 if not os.path.exists(self.qemuboot):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500748 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 -0500749
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500750 logger.debug('CONFFILE: %s' % self.qemuboot)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500751
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600752 cf = configparser.ConfigParser()
753 cf.read(self.qemuboot)
754 for k, v in cf.items('config_bsp'):
755 k_upper = k.upper()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500756 if v.startswith("../"):
757 v = os.path.abspath(os.path.dirname(self.qemuboot) + "/" + v)
758 elif v == ".":
759 v = os.path.dirname(self.qemuboot)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600760 self.set(k_upper, v)
761
762 def validate_paths(self):
763 """Ensure all relevant path variables are set"""
764 # When we're started with a *.qemuboot.conf arg assume that image
765 # artefacts are relative to that file, rather than in whatever
766 # directory DEPLOY_DIR_IMAGE in the conf file points to.
767 if self.qbconfload:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500768 imgdir = os.path.realpath(os.path.dirname(self.qemuboot))
769 if imgdir != os.path.realpath(self.get('DEPLOY_DIR_IMAGE')):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600770 logger.info('Setting DEPLOY_DIR_IMAGE to folder containing %s (%s)' % (self.qemuboot, imgdir))
771 self.set('DEPLOY_DIR_IMAGE', imgdir)
772
773 # If the STAGING_*_NATIVE directories from the config file don't exist
774 # and we're in a sourced OE build directory try to extract the paths
775 # from `bitbake -e`
776 havenative = os.path.exists(self.get('STAGING_DIR_NATIVE')) and \
777 os.path.exists(self.get('STAGING_BINDIR_NATIVE'))
778
779 if not havenative:
780 if not self.bitbake_e:
781 self.load_bitbake_env()
782
783 if self.bitbake_e:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500784 native_vars = ['STAGING_DIR_NATIVE']
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600785 for nv in native_vars:
786 s = re.search('^%s="(.*)"' % nv, self.bitbake_e, re.M)
787 if s and s.group(1) != self.get(nv):
788 logger.info('Overriding conf file setting of %s to %s from Bitbake environment' % (nv, s.group(1)))
789 self.set(nv, s.group(1))
790 else:
791 # when we're invoked from a running bitbake instance we won't
792 # be able to call `bitbake -e`, then try:
793 # - get OE_TMPDIR from environment and guess paths based on it
794 # - get OECORE_NATIVE_SYSROOT from environment (for sdk)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500795 tmpdir = self.get('OE_TMPDIR')
796 oecore_native_sysroot = self.get('OECORE_NATIVE_SYSROOT')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600797 if tmpdir:
798 logger.info('Setting STAGING_DIR_NATIVE and STAGING_BINDIR_NATIVE relative to OE_TMPDIR (%s)' % tmpdir)
799 hostos, _, _, _, machine = os.uname()
800 buildsys = '%s-%s' % (machine, hostos.lower())
801 staging_dir_native = '%s/sysroots/%s' % (tmpdir, buildsys)
802 self.set('STAGING_DIR_NATIVE', staging_dir_native)
803 elif oecore_native_sysroot:
804 logger.info('Setting STAGING_DIR_NATIVE to OECORE_NATIVE_SYSROOT (%s)' % oecore_native_sysroot)
805 self.set('STAGING_DIR_NATIVE', oecore_native_sysroot)
806 if self.get('STAGING_DIR_NATIVE'):
807 # we have to assume that STAGING_BINDIR_NATIVE is at usr/bin
808 staging_bindir_native = '%s/usr/bin' % self.get('STAGING_DIR_NATIVE')
809 logger.info('Setting STAGING_BINDIR_NATIVE to %s' % staging_bindir_native)
810 self.set('STAGING_BINDIR_NATIVE', '%s/usr/bin' % self.get('STAGING_DIR_NATIVE'))
811
812 def print_config(self):
813 logger.info('Continuing with the following parameters:\n')
814 if not self.fstype in self.vmtypes:
815 print('KERNEL: [%s]' % self.kernel)
816 if self.dtb:
817 print('DTB: [%s]' % self.dtb)
818 print('MACHINE: [%s]' % self.get('MACHINE'))
819 print('FSTYPE: [%s]' % self.fstype)
820 if self.fstype == 'nfs':
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500821 print('NFS_DIR: [%s]' % self.rootfs)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600822 else:
823 print('ROOTFS: [%s]' % self.rootfs)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500824 if self.ovmf_bios:
825 print('OVMF: %s' % self.ovmf_bios)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600826 print('CONFFILE: [%s]' % self.qemuboot)
827 print('')
828
829 def setup_nfs(self):
830 if not self.nfs_server:
831 if self.slirp_enabled:
832 self.nfs_server = '10.0.2.2'
833 else:
834 self.nfs_server = '192.168.7.1'
835
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500836 # Figure out a new nfs_instance to allow multiple qemus running.
837 # CentOS 7.1's ps doesn't print full command line without "ww"
838 # when invoke by subprocess.Popen().
839 cmd = "ps auxww"
840 ps = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
841 pattern = '/bin/unfsd .* -i .*\.pid -e .*/exports([0-9]+) '
842 all_instances = re.findall(pattern, ps, re.M)
843 if all_instances:
844 all_instances.sort(key=int)
845 self.nfs_instance = int(all_instances.pop()) + 1
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600846
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500847 nfsd_port = 3049 + 2 * self.nfs_instance
848 mountd_port = 3048 + 2 * self.nfs_instance
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600849
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500850 # Export vars for runqemu-export-rootfs
851 export_dict = {
852 'NFS_INSTANCE': self.nfs_instance,
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500853 'NFSD_PORT': nfsd_port,
854 'MOUNTD_PORT': mountd_port,
855 }
856 for k, v in export_dict.items():
857 # Use '%s' since they are integers
858 os.putenv(k, '%s' % v)
859
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500860 self.unfs_opts="nfsvers=3,port=%s,udp,mountport=%s" % (nfsd_port, mountd_port)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600861
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500862 # Extract .tar.bz2 or .tar.bz if no nfs dir
863 if not (self.rootfs and os.path.isdir(self.rootfs)):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600864 src_prefix = '%s/%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_LINK_NAME'))
865 dest = "%s-nfsroot" % src_prefix
866 if os.path.exists('%s.pseudo_state' % dest):
867 logger.info('Use %s as NFS_DIR' % dest)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500868 self.rootfs = dest
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600869 else:
870 src = ""
871 src1 = '%s.tar.bz2' % src_prefix
872 src2 = '%s.tar.gz' % src_prefix
873 if os.path.exists(src1):
874 src = src1
875 elif os.path.exists(src2):
876 src = src2
877 if not src:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500878 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 -0600879 logger.info('NFS_DIR not found, extracting %s to %s' % (src, dest))
880 cmd = 'runqemu-extract-sdk %s %s' % (src, dest)
881 logger.info('Running %s...' % cmd)
882 if subprocess.call(cmd, shell=True) != 0:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500883 raise RunQemuError('Failed to run %s' % cmd)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600884 self.clean_nfs_dir = True
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500885 self.rootfs = dest
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600886
887 # Start the userspace NFS server
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500888 cmd = 'runqemu-export-rootfs start %s' % self.rootfs
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600889 logger.info('Running %s...' % cmd)
890 if subprocess.call(cmd, shell=True) != 0:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500891 raise RunQemuError('Failed to run %s' % cmd)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600892
893 self.nfs_running = True
894
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600895 def setup_slirp(self):
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500896 """Setup user networking"""
897
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600898 if self.fstype == 'nfs':
899 self.setup_nfs()
900 self.kernel_cmdline_script += ' ip=dhcp'
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500901 # Port mapping
902 hostfwd = ",hostfwd=tcp::2222-:22,hostfwd=tcp::2323-:23"
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500903 qb_slirp_opt_default = "-netdev user,id=net0%s,tftp=%s" % (hostfwd, self.get('DEPLOY_DIR_IMAGE'))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500904 qb_slirp_opt = self.get('QB_SLIRP_OPT') or qb_slirp_opt_default
905 # Figure out the port
906 ports = re.findall('hostfwd=[^-]*:([0-9]+)-[^,-]*', qb_slirp_opt)
907 ports = [int(i) for i in ports]
908 mac = 2
909 # Find a free port to avoid conflicts
910 for p in ports[:]:
911 p_new = p
912 while not check_free_port('localhost', p_new):
913 p_new += 1
914 mac += 1
915 while p_new in ports:
916 p_new += 1
917 mac += 1
918 if p != p_new:
919 ports.append(p_new)
920 qb_slirp_opt = re.sub(':%s-' % p, ':%s-' % p_new, qb_slirp_opt)
921 logger.info("Port forward changed: %s -> %s" % (p, p_new))
922 mac = "%s%02x" % (self.mac_slirp, mac)
923 self.set('NETWORK_CMD', '%s %s' % (self.network_device.replace('@MAC@', mac), qb_slirp_opt))
924 # Print out port foward
925 hostfwd = re.findall('(hostfwd=[^,]*)', qb_slirp_opt)
926 if hostfwd:
927 logger.info('Port forward: %s' % ' '.join(hostfwd))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600928
929 def setup_tap(self):
930 """Setup tap"""
931
932 # This file is created when runqemu-gen-tapdevs creates a bank of tap
933 # devices, indicating that the user should not bring up new ones using
934 # sudo.
935 nosudo_flag = '/etc/runqemu-nosudo'
936 self.qemuifup = shutil.which('runqemu-ifup')
937 self.qemuifdown = shutil.which('runqemu-ifdown')
938 ip = shutil.which('ip')
939 lockdir = "/tmp/qemu-tap-locks"
940
941 if not (self.qemuifup and self.qemuifdown and ip):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500942 logger.error("runqemu-ifup: %s" % self.qemuifup)
943 logger.error("runqemu-ifdown: %s" % self.qemuifdown)
944 logger.error("ip: %s" % ip)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600945 raise OEPathError("runqemu-ifup, runqemu-ifdown or ip not found")
946
947 if not os.path.exists(lockdir):
948 # There might be a race issue when multi runqemu processess are
949 # running at the same time.
950 try:
951 os.mkdir(lockdir)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500952 os.chmod(lockdir, 0o777)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600953 except FileExistsError:
954 pass
955
956 cmd = '%s link' % ip
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500957 logger.debug('Running %s...' % cmd)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600958 ip_link = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
959 # Matches line like: 6: tap0: <foo>
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500960 possibles = re.findall('^[0-9]+: +(tap[0-9]+): <.*', ip_link, re.M)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600961 tap = ""
962 for p in possibles:
963 lockfile = os.path.join(lockdir, p)
964 if os.path.exists('%s.skip' % lockfile):
965 logger.info('Found %s.skip, skipping %s' % (lockfile, p))
966 continue
967 self.lock = lockfile + '.lock'
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500968 if self.acquire_lock(error=False):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600969 tap = p
970 logger.info("Using preconfigured tap device %s" % tap)
971 logger.info("If this is not intended, touch %s.skip to make runqemu skip %s." %(lockfile, tap))
972 break
973
974 if not tap:
975 if os.path.exists(nosudo_flag):
976 logger.error("Error: There are no available tap devices to use for networking,")
977 logger.error("and I see %s exists, so I am not going to try creating" % nosudo_flag)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500978 raise RunQemuError("a new one with sudo.")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600979
980 gid = os.getgid()
981 uid = os.getuid()
982 logger.info("Setting up tap interface under sudo")
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500983 cmd = 'sudo %s %s %s %s' % (self.qemuifup, uid, gid, self.bindir_native)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600984 tap = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8').rstrip('\n')
985 lockfile = os.path.join(lockdir, tap)
986 self.lock = lockfile + '.lock'
987 self.acquire_lock()
988 self.cleantap = True
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500989 logger.debug('Created tap: %s' % tap)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600990
991 if not tap:
992 logger.error("Failed to setup tap device. Run runqemu-gen-tapdevs to manually create.")
993 return 1
994 self.tap = tap
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500995 tapnum = int(tap[3:])
996 gateway = tapnum * 2 + 1
997 client = gateway + 1
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600998 if self.fstype == 'nfs':
999 self.setup_nfs()
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001000 netconf = "192.168.7.%s::192.168.7.%s:255.255.255.0" % (client, gateway)
1001 logger.info("Network configuration: %s", netconf)
1002 self.kernel_cmdline_script += " ip=%s" % netconf
1003 mac = "%s%02x" % (self.mac_tap, client)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001004 qb_tap_opt = self.get('QB_TAP_OPT')
1005 if qb_tap_opt:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001006 qemu_tap_opt = qb_tap_opt.replace('@TAP@', tap)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001007 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001008 qemu_tap_opt = "-netdev tap,id=net0,ifname=%s,script=no,downscript=no" % (self.tap)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001009
1010 if self.vhost_enabled:
1011 qemu_tap_opt += ',vhost=on'
1012
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001013 self.set('NETWORK_CMD', '%s %s' % (self.network_device.replace('@MAC@', mac), qemu_tap_opt))
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001014
1015 def setup_network(self):
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001016 if self.get('QB_NET') == 'none':
1017 return
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001018 if sys.stdin.isatty():
1019 self.saved_stty = subprocess.check_output("stty -g", shell=True).decode('utf-8')
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001020 self.network_device = self.get('QB_NETWORK_DEVICE') or self.network_device
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001021 if self.slirp_enabled:
1022 self.setup_slirp()
1023 else:
1024 self.setup_tap()
1025
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001026 def setup_rootfs(self):
1027 if self.get('QB_ROOTFS') == 'none':
1028 return
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001029 if 'wic.' in self.fstype:
1030 self.fstype = self.fstype[4:]
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001031 rootfs_format = self.fstype if self.fstype in ('vmdk', 'qcow2', 'vdi') else 'raw'
1032
1033 qb_rootfs_opt = self.get('QB_ROOTFS_OPT')
1034 if qb_rootfs_opt:
1035 self.rootfs_options = qb_rootfs_opt.replace('@ROOTFS@', self.rootfs)
1036 else:
1037 self.rootfs_options = '-drive file=%s,if=virtio,format=%s' % (self.rootfs, rootfs_format)
1038
1039 if self.fstype in ('cpio.gz', 'cpio'):
1040 self.kernel_cmdline = 'root=/dev/ram0 rw debugshell'
1041 self.rootfs_options = '-initrd %s' % self.rootfs
1042 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001043 vm_drive = ''
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001044 if self.fstype in self.vmtypes:
1045 if self.fstype == 'iso':
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001046 vm_drive = '-drive file=%s,if=virtio,media=cdrom' % self.rootfs
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001047 elif self.get('QB_DRIVE_TYPE'):
1048 drive_type = self.get('QB_DRIVE_TYPE')
1049 if drive_type.startswith("/dev/sd"):
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001050 logger.info('Using scsi drive')
1051 vm_drive = '-drive if=none,id=hd,file=%s,format=%s -device virtio-scsi-pci,id=scsi -device scsi-hd,drive=hd' \
1052 % (self.rootfs, rootfs_format)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001053 elif drive_type.startswith("/dev/hd"):
Brad Bishop37a0e4d2017-12-04 01:01:44 -05001054 logger.info('Using ide drive')
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001055 vm_drive = "-drive file=%s,format=%s" % (self.rootfs, rootfs_format)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001056 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001057 # virtio might have been selected explicitly (just use it), or
1058 # is used as fallback (then warn about that).
1059 if not drive_type.startswith("/dev/vd"):
1060 logger.warn("Unknown QB_DRIVE_TYPE: %s" % drive_type)
1061 logger.warn("Failed to figure out drive type, consider define or fix QB_DRIVE_TYPE")
1062 logger.warn('Trying to use virtio block drive')
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001063 vm_drive = '-drive if=virtio,file=%s,format=%s' % (self.rootfs, rootfs_format)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001064
1065 # All branches above set vm_drive.
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001066 self.rootfs_options = '%s -no-reboot' % vm_drive
1067 self.kernel_cmdline = 'root=%s rw highres=off' % (self.get('QB_KERNEL_ROOT'))
1068
1069 if self.fstype == 'nfs':
1070 self.rootfs_options = ''
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001071 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 -06001072 self.kernel_cmdline = 'root=%s rw highres=off' % k_root
1073
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001074 if self.fstype == 'none':
1075 self.rootfs_options = ''
1076
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001077 self.set('ROOTFS_OPTIONS', self.rootfs_options)
1078
1079 def guess_qb_system(self):
1080 """attempt to determine the appropriate qemu-system binary"""
1081 mach = self.get('MACHINE')
1082 if not mach:
1083 search = '.*(qemux86-64|qemux86|qemuarm64|qemuarm|qemumips64|qemumips64el|qemumipsel|qemumips|qemuppc).*'
1084 if self.rootfs:
1085 match = re.match(search, self.rootfs)
1086 if match:
1087 mach = match.group(1)
1088 elif self.kernel:
1089 match = re.match(search, self.kernel)
1090 if match:
1091 mach = match.group(1)
1092
1093 if not mach:
1094 return None
1095
1096 if mach == 'qemuarm':
1097 qbsys = 'arm'
1098 elif mach == 'qemuarm64':
1099 qbsys = 'aarch64'
1100 elif mach == 'qemux86':
1101 qbsys = 'i386'
1102 elif mach == 'qemux86-64':
1103 qbsys = 'x86_64'
1104 elif mach == 'qemuppc':
1105 qbsys = 'ppc'
1106 elif mach == 'qemumips':
1107 qbsys = 'mips'
1108 elif mach == 'qemumips64':
1109 qbsys = 'mips64'
1110 elif mach == 'qemumipsel':
1111 qbsys = 'mipsel'
1112 elif mach == 'qemumips64el':
1113 qbsys = 'mips64el'
Brad Bishop316dfdd2018-06-25 12:45:53 -04001114 elif mach == 'qemuriscv64':
1115 qbsys = 'riscv64'
1116 elif mach == 'qemuriscv32':
1117 qbsys = 'riscv32'
Brad Bishop004d4992018-10-02 23:54:45 +02001118 else:
1119 logger.error("Unable to determine QEMU PC System emulator for %s machine." % mach)
1120 logger.error("As %s is not among valid QEMU machines such as," % mach)
1121 logger.error("qemux86-64, qemux86, qemuarm64, qemuarm, qemumips64, qemumips64el, qemumipsel, qemumips, qemuppc")
1122 raise RunQemuError("Set qb_system_name with suitable QEMU PC System emulator in .*qemuboot.conf.")
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001123
1124 return 'qemu-system-%s' % qbsys
1125
1126 def setup_final(self):
1127 qemu_system = self.get('QB_SYSTEM_NAME')
1128 if not qemu_system:
1129 qemu_system = self.guess_qb_system()
1130 if not qemu_system:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001131 raise RunQemuError("Failed to boot, QB_SYSTEM_NAME is NULL!")
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001132
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001133 qemu_bin = '%s/%s' % (self.bindir_native, qemu_system)
1134
1135 # It is possible to have qemu-native in ASSUME_PROVIDED, and it won't
1136 # find QEMU in sysroot, it needs to use host's qemu.
1137 if not os.path.exists(qemu_bin):
1138 logger.info("QEMU binary not found in %s, trying host's QEMU" % qemu_bin)
1139 for path in (os.environ['PATH'] or '').split(':'):
1140 qemu_bin_tmp = os.path.join(path, qemu_system)
1141 logger.info("Trying: %s" % qemu_bin_tmp)
1142 if os.path.exists(qemu_bin_tmp):
1143 qemu_bin = qemu_bin_tmp
1144 if not os.path.isabs(qemu_bin):
1145 qemu_bin = os.path.abspath(qemu_bin)
1146 logger.info("Using host's QEMU: %s" % qemu_bin)
1147 break
1148
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001149 if not os.access(qemu_bin, os.X_OK):
1150 raise OEPathError("No QEMU binary '%s' could be found" % qemu_bin)
1151
1152 check_libgl(qemu_bin)
1153
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001154 self.qemu_opt = "%s %s %s %s" % (qemu_bin, self.get('NETWORK_CMD'), self.get('ROOTFS_OPTIONS'), self.get('QB_OPT_APPEND'))
1155
1156 for ovmf in self.ovmf_bios:
1157 format = ovmf.rsplit('.', 1)[-1]
1158 self.qemu_opt += ' -drive if=pflash,format=%s,file=%s' % (format, ovmf)
1159 if self.ovmf_bios:
1160 # OVMF only supports normal VGA, i.e. we need to override a -vga vmware
1161 # that gets added for example for normal qemux86.
1162 self.qemu_opt += ' -vga std'
1163
1164 self.qemu_opt += ' ' + self.qemu_opt_script
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001165
1166 if self.snapshot:
1167 self.qemu_opt += " -snapshot"
1168
1169 if self.serialstdio:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001170 if sys.stdin.isatty():
1171 subprocess.check_call("stty intr ^]", shell=True)
1172 logger.info("Interrupt character is '^]'")
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001173
1174 first_serial = ""
1175 if not re.search("-nographic", self.qemu_opt):
1176 first_serial = "-serial mon:vc"
1177 # We always want a ttyS1. Since qemu by default adds a serial
1178 # port when nodefaults is not specified, it seems that all that
1179 # would be needed is to make sure a "-serial" is there. However,
1180 # it appears that when "-serial" is specified, it ignores the
1181 # default serial port that is normally added. So here we make
1182 # sure to add two -serial if there are none. And only one if
1183 # there is one -serial already.
1184 serial_num = len(re.findall("-serial", self.qemu_opt))
1185 if serial_num == 0:
1186 self.qemu_opt += " %s %s" % (first_serial, self.get("QB_SERIAL_OPT"))
1187 elif serial_num == 1:
1188 self.qemu_opt += " %s" % self.get("QB_SERIAL_OPT")
1189
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001190 # We always wants ttyS0 and ttyS1 in qemu machines (see SERIAL_CONSOLES),
1191 # if not serial or serialtcp options was specified only ttyS0 is created
1192 # and sysvinit shows an error trying to enable ttyS1:
1193 # INIT: Id "S1" respawning too fast: disabled for 5 minutes
1194 serial_num = len(re.findall("-serial", self.qemu_opt))
1195 if serial_num == 0:
1196 if re.search("-nographic", self.qemu_opt):
1197 self.qemu_opt += " -serial mon:stdio -serial null"
1198 else:
1199 self.qemu_opt += " -serial mon:vc -serial null"
1200
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001201 def start_qemu(self):
Brad Bishop004d4992018-10-02 23:54:45 +02001202 import shlex
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001203 if self.kernel:
Brad Bishop37a0e4d2017-12-04 01:01:44 -05001204 kernel_opts = "-kernel %s -append '%s %s %s %s'" % (self.kernel, self.kernel_cmdline,
1205 self.kernel_cmdline_script, self.get('QB_KERNEL_CMDLINE_APPEND'),
1206 self.bootparams)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001207 if self.dtb:
1208 kernel_opts += " -dtb %s" % self.dtb
1209 else:
1210 kernel_opts = ""
1211 cmd = "%s %s" % (self.qemu_opt, kernel_opts)
Brad Bishop004d4992018-10-02 23:54:45 +02001212 cmds = shlex.split(cmd)
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001213 logger.info('Running %s\n' % cmd)
Brad Bishop004d4992018-10-02 23:54:45 +02001214 process = subprocess.Popen(cmds, stderr=subprocess.PIPE)
1215 self.qemupid = process.pid
1216 retcode = process.wait()
1217 if retcode:
1218 if retcode == -signal.SIGTERM:
1219 logger.info("Qemu terminated by SIGTERM")
1220 else:
1221 logger.error("Failed to run qemu: %s", process.stderr.read().decode())
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001222
1223 def cleanup(self):
Brad Bishop004d4992018-10-02 23:54:45 +02001224 if self.cleaned:
1225 return
1226
1227 # avoid dealing with SIGTERM when cleanup function is running
1228 signal.signal(signal.SIGTERM, signal.SIG_IGN)
1229
1230 logger.info("Cleaning up")
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001231 if self.cleantap:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001232 cmd = 'sudo %s %s %s' % (self.qemuifdown, self.tap, self.bindir_native)
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001233 logger.debug('Running %s' % cmd)
1234 subprocess.check_call(cmd, shell=True)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001235 if self.lock_descriptor:
1236 logger.info("Releasing lockfile for tap device '%s'" % self.tap)
1237 self.release_lock()
1238
1239 if self.nfs_running:
1240 logger.info("Shutting down the userspace NFS server...")
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001241 cmd = "runqemu-export-rootfs stop %s" % self.rootfs
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001242 logger.debug('Running %s' % cmd)
1243 subprocess.check_call(cmd, shell=True)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001244
1245 if self.saved_stty:
1246 cmd = "stty %s" % self.saved_stty
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001247 subprocess.check_call(cmd, shell=True)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001248
1249 if self.clean_nfs_dir:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001250 logger.info('Removing %s' % self.rootfs)
1251 shutil.rmtree(self.rootfs)
1252 shutil.rmtree('%s.pseudo_state' % self.rootfs)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001253
Brad Bishop004d4992018-10-02 23:54:45 +02001254 self.cleaned = True
1255
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001256 def load_bitbake_env(self, mach=None):
1257 if self.bitbake_e:
1258 return
1259
1260 bitbake = shutil.which('bitbake')
1261 if not bitbake:
1262 return
1263
1264 if not mach:
1265 mach = self.get('MACHINE')
1266
1267 if mach:
1268 cmd = 'MACHINE=%s bitbake -e' % mach
1269 else:
1270 cmd = 'bitbake -e'
1271
1272 logger.info('Running %s...' % cmd)
1273 try:
1274 self.bitbake_e = subprocess.check_output(cmd, shell=True).decode('utf-8')
1275 except subprocess.CalledProcessError as err:
1276 self.bitbake_e = ''
1277 logger.warn("Couldn't run 'bitbake -e' to gather environment information:\n%s" % err.output.decode('utf-8'))
1278
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001279 def validate_combos(self):
1280 if (self.fstype in self.vmtypes) and self.kernel:
1281 raise RunQemuError("%s doesn't need kernel %s!" % (self.fstype, self.kernel))
1282
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001283 @property
1284 def bindir_native(self):
1285 result = self.get('STAGING_BINDIR_NATIVE')
1286 if result and os.path.exists(result):
1287 return result
1288
1289 cmd = 'bitbake qemu-helper-native -e'
1290 logger.info('Running %s...' % cmd)
1291 out = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
1292 out = out.stdout.read().decode('utf-8')
1293
1294 match = re.search('^STAGING_BINDIR_NATIVE="(.*)"', out, re.M)
1295 if match:
1296 result = match.group(1)
1297 if os.path.exists(result):
1298 self.set('STAGING_BINDIR_NATIVE', result)
1299 return result
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001300 raise RunQemuError("Native sysroot directory %s doesn't exist" % result)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001301 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001302 raise RunQemuError("Can't find STAGING_BINDIR_NATIVE in '%s' output" % cmd)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001303
1304
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001305def main():
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001306 if "help" in sys.argv or '-h' in sys.argv or '--help' in sys.argv:
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001307 print_usage()
1308 return 0
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001309 try:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001310 config = BaseConfig()
Brad Bishop004d4992018-10-02 23:54:45 +02001311
1312 def sigterm_handler(signum, frame):
1313 logger.info("SIGTERM received")
1314 os.kill(config.qemupid, signal.SIGTERM)
1315 config.cleanup()
1316 subprocess.run(["tput", "smam"])
1317 signal.signal(signal.SIGTERM, sigterm_handler)
1318
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001319 config.check_args()
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001320 config.read_qemuboot()
1321 config.check_and_set()
1322 # Check whether the combos is valid or not
1323 config.validate_combos()
1324 config.print_config()
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001325 config.setup_network()
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001326 config.setup_rootfs()
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001327 config.setup_final()
1328 config.start_qemu()
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001329 except RunQemuError as err:
1330 logger.error(err)
1331 return 1
1332 except Exception as err:
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001333 import traceback
1334 traceback.print_exc()
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001335 return 1
1336 finally:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001337 config.cleanup()
Brad Bishop004d4992018-10-02 23:54:45 +02001338 subprocess.run(["tput", "smam"])
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001339
1340if __name__ == "__main__":
1341 sys.exit(main())