blob: d998494063a28bb3029804b2ff42e3a631a178fe [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
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050030
Brad Bishopd7bf8c12018-02-25 22:55:05 -050031class RunQemuError(Exception):
32 """Custom exception to raise on known errors."""
33 pass
34
35class OEPathError(RunQemuError):
Patrick Williamsc0f7c042017-02-23 20:41:17 -060036 """Custom Exception to give better guidance on missing binaries"""
37 def __init__(self, message):
Brad Bishopd7bf8c12018-02-25 22:55:05 -050038 super().__init__("In order for this script to dynamically infer paths\n \
Patrick Williamsc0f7c042017-02-23 20:41:17 -060039kernels or filesystem images, you either need bitbake in your PATH\n \
40or to source oe-init-build-env before running this script.\n\n \
41Dynamic path inference can be avoided by passing a *.qemuboot.conf to\n \
Brad Bishopd7bf8c12018-02-25 22:55:05 -050042runqemu, i.e. `runqemu /path/to/my-image-name.qemuboot.conf`\n\n %s" % message)
Patrick Williamsc0f7c042017-02-23 20:41:17 -060043
44
45def create_logger():
46 logger = logging.getLogger('runqemu')
47 logger.setLevel(logging.INFO)
48
49 # create console handler and set level to debug
50 ch = logging.StreamHandler()
Brad Bishopd7bf8c12018-02-25 22:55:05 -050051 ch.setLevel(logging.DEBUG)
Patrick Williamsc0f7c042017-02-23 20:41:17 -060052
53 # create formatter
54 formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
55
56 # add formatter to ch
57 ch.setFormatter(formatter)
58
59 # add ch to logger
60 logger.addHandler(ch)
61
62 return logger
63
64logger = create_logger()
65
66def print_usage():
67 print("""
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050068Usage: you can run this script with any valid combination
69of the following environment variables (in any order):
70 KERNEL - the kernel image file to use
71 ROOTFS - the rootfs image file or nfsroot directory to use
Brad Bishop316dfdd2018-06-25 12:45:53 -040072 DEVICE_TREE - the device tree blob to use
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050073 MACHINE - the machine name (optional, autodetected from KERNEL filename if unspecified)
74 Simplified QEMU command-line options can be passed with:
Patrick Williamsc0f7c042017-02-23 20:41:17 -060075 nographic - disable video console
76 serial - enable a serial console on /dev/ttyS0
77 slirp - enable user networking, no root privileges is required
78 kvm - enable KVM when running x86/x86_64 (VT-capable CPU required)
79 kvm-vhost - enable KVM with vhost when running x86/x86_64 (VT-capable CPU required)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050080 publicvnc - enable a VNC server open to all hosts
Patrick Williamsc0f7c042017-02-23 20:41:17 -060081 audio - enable audio
Brad Bishop6e60e8b2018-02-01 10:27:11 -050082 [*/]ovmf* - OVMF firmware file or base name for booting with UEFI
Patrick Williamsc0f7c042017-02-23 20:41:17 -060083 tcpserial=<port> - specify tcp serial port number
84 biosdir=<dir> - specify custom bios dir
85 biosfilename=<filename> - specify bios filename
86 qemuparams=<xyz> - specify custom parameters to QEMU
87 bootparams=<xyz> - specify custom kernel parameters during boot
Brad Bishop6e60e8b2018-02-01 10:27:11 -050088 help, -h, --help: print this text
Brad Bishopd7bf8c12018-02-25 22:55:05 -050089 -d, --debug: Enable debug output
90 -q, --quite: Hide most output except error messages
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050091
92Examples:
Brad Bishop6e60e8b2018-02-01 10:27:11 -050093 runqemu
Patrick Williamsc0f7c042017-02-23 20:41:17 -060094 runqemu qemuarm
95 runqemu tmp/deploy/images/qemuarm
Brad Bishop6e60e8b2018-02-01 10:27:11 -050096 runqemu tmp/deploy/images/qemux86/<qemuboot.conf>
Patrick Williamsc0f7c042017-02-23 20:41:17 -060097 runqemu qemux86-64 core-image-sato ext4
98 runqemu qemux86-64 wic-image-minimal wic
99 runqemu path/to/bzImage-qemux86.bin path/to/nfsrootdir/ serial
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500100 runqemu qemux86 iso/hddimg/wic.vmdk/wic.qcow2/wic.vdi/ramfs/cpio.gz...
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600101 runqemu qemux86 qemuparams="-m 256"
102 runqemu qemux86 bootparams="psplash=false"
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600103 runqemu path/to/<image>-<machine>.wic
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500104 runqemu path/to/<image>-<machine>.wic.vmdk
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600105""")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500106
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600107def check_tun():
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500108 """Check /dev/net/tun"""
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600109 dev_tun = '/dev/net/tun'
110 if not os.path.exists(dev_tun):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500111 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 -0500112
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600113 if not os.access(dev_tun, os.W_OK):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500114 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 -0500115
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600116def check_libgl(qemu_bin):
117 cmd = 'ldd %s' % qemu_bin
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500118 logger.debug('Running %s...' % cmd)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600119 need_gl = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
120 if re.search('libGLU', need_gl):
121 # We can't run without a libGL.so
122 libgl = False
123 check_files = (('/usr/lib/libGL.so', '/usr/lib/libGLU.so'), \
124 ('/usr/lib64/libGL.so', '/usr/lib64/libGLU.so'), \
125 ('/usr/lib/*-linux-gnu/libGL.so', '/usr/lib/*-linux-gnu/libGLU.so'))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500126
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600127 for (f1, f2) in check_files:
128 if re.search('\*', f1):
129 for g1 in glob.glob(f1):
130 if libgl:
131 break
132 if os.path.exists(g1):
133 for g2 in glob.glob(f2):
134 if os.path.exists(g2):
135 libgl = True
136 break
137 if libgl:
138 break
139 else:
140 if os.path.exists(f1) and os.path.exists(f2):
141 libgl = True
142 break
143 if not libgl:
144 logger.error("You need libGL.so and libGLU.so to exist in your library path to run the QEMU emulator.")
145 logger.error("Ubuntu package names are: libgl1-mesa-dev and libglu1-mesa-dev.")
146 logger.error("Fedora package names are: mesa-libGL-devel mesa-libGLU-devel.")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500147 raise RunQemuError('%s requires libGLU, but not found' % qemu_bin)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500148
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600149def get_first_file(cmds):
150 """Return first file found in wildcard cmds"""
151 for cmd in cmds:
152 all_files = glob.glob(cmd)
153 if all_files:
154 for f in all_files:
155 if not os.path.isdir(f):
156 return f
157 return ''
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500158
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500159def check_free_port(host, port):
160 """ Check whether the port is free or not """
161 import socket
162 from contextlib import closing
163
164 with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
165 if sock.connect_ex((host, port)) == 0:
166 # Port is open, so not free
167 return False
168 else:
169 # Port is not open, so free
170 return True
171
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600172class BaseConfig(object):
173 def __init__(self):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500174 # The self.d saved vars from self.set(), part of them are from qemuboot.conf
175 self.d = {'QB_KERNEL_ROOT': '/dev/vda'}
176
177 # Supported env vars, add it here if a var can be got from env,
178 # and don't use os.getenv in the code.
179 self.env_vars = ('MACHINE',
180 'ROOTFS',
181 'KERNEL',
Brad Bishop316dfdd2018-06-25 12:45:53 -0400182 'DEVICE_TREE',
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500183 'DEPLOY_DIR_IMAGE',
184 'OE_TMPDIR',
185 'OECORE_NATIVE_SYSROOT',
186 )
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500187
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600188 self.qemu_opt = ''
189 self.qemu_opt_script = ''
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600190 self.clean_nfs_dir = False
191 self.nfs_server = ''
192 self.rootfs = ''
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500193 # File name(s) of a OVMF firmware file or variable store,
194 # to be added with -drive if=pflash.
195 # Found in the same places as the rootfs, with or without one of
196 # these suffices: qcow2, bin.
197 # Setting one also adds "-vga std" because that is all that
198 # OVMF supports.
199 self.ovmf_bios = []
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600200 self.qemuboot = ''
201 self.qbconfload = False
202 self.kernel = ''
203 self.kernel_cmdline = ''
204 self.kernel_cmdline_script = ''
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500205 self.bootparams = ''
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600206 self.dtb = ''
207 self.fstype = ''
208 self.kvm_enabled = False
209 self.vhost_enabled = False
210 self.slirp_enabled = False
211 self.nfs_instance = 0
212 self.nfs_running = False
213 self.serialstdio = False
214 self.cleantap = False
215 self.saved_stty = ''
216 self.audio_enabled = False
217 self.tcpserial_portnum = ''
218 self.custombiosdir = ''
219 self.lock = ''
220 self.lock_descriptor = ''
221 self.bitbake_e = ''
222 self.snapshot = False
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500223 self.fstypes = ('ext2', 'ext3', 'ext4', 'jffs2', 'nfs', 'btrfs',
224 'cpio.gz', 'cpio', 'ramfs', 'tar.bz2', 'tar.gz')
225 self.vmtypes = ('hddimg', 'hdddirect', 'wic', 'wic.vmdk',
226 'wic.qcow2', 'wic.vdi', 'iso')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500227 self.network_device = "-device e1000,netdev=net0,mac=@MAC@"
228 # Use different mac section for tap and slirp to avoid
229 # conflicts, e.g., when one is running with tap, the other is
230 # running with slirp.
231 # The last section is dynamic, which is for avoiding conflicts,
232 # when multiple qemus are running, e.g., when multiple tap or
233 # slirp qemus are running.
234 self.mac_tap = "52:54:00:12:34:"
235 self.mac_slirp = "52:54:00:12:35:"
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500236
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500237 def acquire_lock(self, error=True):
238 logger.debug("Acquiring lockfile %s..." % self.lock)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600239 try:
240 self.lock_descriptor = open(self.lock, 'w')
241 fcntl.flock(self.lock_descriptor, fcntl.LOCK_EX|fcntl.LOCK_NB)
242 except Exception as e:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500243 msg = "Acquiring lockfile %s failed: %s" % (self.lock, e)
244 if error:
245 logger.error(msg)
246 else:
247 logger.info(msg)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600248 if self.lock_descriptor:
249 self.lock_descriptor.close()
250 return False
251 return True
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500252
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600253 def release_lock(self):
254 fcntl.flock(self.lock_descriptor, fcntl.LOCK_UN)
255 self.lock_descriptor.close()
256 os.remove(self.lock)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500257
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600258 def get(self, key):
259 if key in self.d:
260 return self.d.get(key)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500261 elif os.getenv(key):
262 return os.getenv(key)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600263 else:
264 return ''
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500265
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600266 def set(self, key, value):
267 self.d[key] = value
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500268
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600269 def is_deploy_dir_image(self, p):
270 if os.path.isdir(p):
271 if not re.search('.qemuboot.conf$', '\n'.join(os.listdir(p)), re.M):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500272 logger.debug("Can't find required *.qemuboot.conf in %s" % p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600273 return False
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500274 if not any(map(lambda name: '-image-' in name, os.listdir(p))):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500275 logger.debug("Can't find *-image-* in %s" % p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600276 return False
277 return True
278 else:
279 return False
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500280
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600281 def check_arg_fstype(self, fst):
282 """Check and set FSTYPE"""
283 if fst not in self.fstypes + self.vmtypes:
284 logger.warn("Maybe unsupported FSTYPE: %s" % fst)
285 if not self.fstype or self.fstype == fst:
286 if fst == 'ramfs':
287 fst = 'cpio.gz'
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500288 if fst in ('tar.bz2', 'tar.gz'):
289 fst = 'nfs'
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600290 self.fstype = fst
291 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500292 raise RunQemuError("Conflicting: FSTYPE %s and %s" % (self.fstype, fst))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500293
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600294 def set_machine_deploy_dir(self, machine, deploy_dir_image):
295 """Set MACHINE and DEPLOY_DIR_IMAGE"""
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500296 logger.debug('MACHINE: %s' % machine)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600297 self.set("MACHINE", machine)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500298 logger.debug('DEPLOY_DIR_IMAGE: %s' % deploy_dir_image)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600299 self.set("DEPLOY_DIR_IMAGE", deploy_dir_image)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500300
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600301 def check_arg_nfs(self, p):
302 if os.path.isdir(p):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500303 self.rootfs = p
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600304 else:
305 m = re.match('(.*):(.*)', p)
306 self.nfs_server = m.group(1)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500307 self.rootfs = m.group(2)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600308 self.check_arg_fstype('nfs')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500309
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600310 def check_arg_path(self, p):
311 """
312 - Check whether it is <image>.qemuboot.conf or contains <image>.qemuboot.conf
313 - Check whether is a kernel file
314 - Check whether is a image file
315 - Check whether it is a nfs dir
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500316 - Check whether it is a OVMF flash file
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600317 """
318 if p.endswith('.qemuboot.conf'):
319 self.qemuboot = p
320 self.qbconfload = True
321 elif re.search('\.bin$', p) or re.search('bzImage', p) or \
322 re.search('zImage', p) or re.search('vmlinux', p) or \
323 re.search('fitImage', p) or re.search('uImage', p):
324 self.kernel = p
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500325 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 -0600326 self.rootfs = p
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500327 # Check filename against self.fstypes can hanlde <file>.cpio.gz,
328 # otherwise, its type would be "gz", which is incorrect.
329 fst = ""
330 for t in self.fstypes:
331 if p.endswith(t):
332 fst = t
333 break
334 if not fst:
335 m = re.search('.*\.(.*)$', self.rootfs)
336 if m:
337 fst = m.group(1)
338 if fst:
339 self.check_arg_fstype(fst)
340 qb = re.sub('\.' + fst + "$", '', self.rootfs)
341 qb = '%s%s' % (re.sub('\.rootfs$', '', qb), '.qemuboot.conf')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600342 if os.path.exists(qb):
343 self.qemuboot = qb
344 self.qbconfload = True
345 else:
346 logger.warn("%s doesn't exist" % qb)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600347 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500348 raise RunQemuError("Can't find FSTYPE from: %s" % p)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500349
350 elif os.path.isdir(p) or re.search(':', p) and re.search('/', p):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600351 if self.is_deploy_dir_image(p):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500352 logger.debug('DEPLOY_DIR_IMAGE: %s' % p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600353 self.set("DEPLOY_DIR_IMAGE", p)
354 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500355 logger.debug("Assuming %s is an nfs rootfs" % p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600356 self.check_arg_nfs(p)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500357 elif os.path.basename(p).startswith('ovmf'):
358 self.ovmf_bios.append(p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600359 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500360 raise RunQemuError("Unknown path arg %s" % p)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500361
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600362 def check_arg_machine(self, arg):
363 """Check whether it is a machine"""
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500364 if self.get('MACHINE') == arg:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600365 return
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500366 elif self.get('MACHINE') and self.get('MACHINE') != arg:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500367 raise RunQemuError("Maybe conflicted MACHINE: %s vs %s" % (self.get('MACHINE'), arg))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500368 elif re.search('/', arg):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500369 raise RunQemuError("Unknown arg: %s" % arg)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500370
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500371 logger.debug('Assuming MACHINE = %s' % arg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500372
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600373 # if we're running under testimage, or similarly as a child
374 # of an existing bitbake invocation, we can't invoke bitbake
375 # to validate the MACHINE setting and must assume it's correct...
376 # FIXME: testimage.bbclass exports these two variables into env,
377 # are there other scenarios in which we need to support being
378 # invoked by bitbake?
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500379 deploy = self.get('DEPLOY_DIR_IMAGE')
380 bbchild = deploy and self.get('OE_TMPDIR')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600381 if bbchild:
382 self.set_machine_deploy_dir(arg, deploy)
383 return
384 # also check whether we're running under a sourced toolchain
385 # environment file
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500386 if self.get('OECORE_NATIVE_SYSROOT'):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600387 self.set("MACHINE", arg)
388 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500389
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600390 cmd = 'MACHINE=%s bitbake -e' % arg
391 logger.info('Running %s...' % cmd)
392 self.bitbake_e = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
393 # bitbake -e doesn't report invalid MACHINE as an error, so
394 # let's check DEPLOY_DIR_IMAGE to make sure that it is a valid
395 # MACHINE.
396 s = re.search('^DEPLOY_DIR_IMAGE="(.*)"', self.bitbake_e, re.M)
397 if s:
398 deploy_dir_image = s.group(1)
399 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500400 raise RunQemuError("bitbake -e %s" % self.bitbake_e)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600401 if self.is_deploy_dir_image(deploy_dir_image):
402 self.set_machine_deploy_dir(arg, deploy_dir_image)
403 else:
404 logger.error("%s not a directory valid DEPLOY_DIR_IMAGE" % deploy_dir_image)
405 self.set("MACHINE", arg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500406
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600407 def check_args(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500408 for debug in ("-d", "--debug"):
409 if debug in sys.argv:
410 logger.setLevel(logging.DEBUG)
411 sys.argv.remove(debug)
412
413 for quiet in ("-q", "--quiet"):
414 if quiet in sys.argv:
415 logger.setLevel(logging.ERROR)
416 sys.argv.remove(quiet)
417
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600418 unknown_arg = ""
419 for arg in sys.argv[1:]:
420 if arg in self.fstypes + self.vmtypes:
421 self.check_arg_fstype(arg)
422 elif arg == 'nographic':
423 self.qemu_opt_script += ' -nographic'
424 self.kernel_cmdline_script += ' console=ttyS0'
425 elif arg == 'serial':
426 self.kernel_cmdline_script += ' console=ttyS0'
427 self.serialstdio = True
428 elif arg == 'audio':
429 logger.info("Enabling audio in qemu")
430 logger.info("Please install sound drivers in linux host")
431 self.audio_enabled = True
432 elif arg == 'kvm':
433 self.kvm_enabled = True
434 elif arg == 'kvm-vhost':
435 self.vhost_enabled = True
436 elif arg == 'slirp':
437 self.slirp_enabled = True
438 elif arg == 'snapshot':
439 self.snapshot = True
440 elif arg == 'publicvnc':
441 self.qemu_opt_script += ' -vnc :0'
442 elif arg.startswith('tcpserial='):
443 self.tcpserial_portnum = arg[len('tcpserial='):]
444 elif arg.startswith('biosdir='):
445 self.custombiosdir = arg[len('biosdir='):]
446 elif arg.startswith('biosfilename='):
447 self.qemu_opt_script += ' -bios %s' % arg[len('biosfilename='):]
448 elif arg.startswith('qemuparams='):
449 self.qemu_opt_script += ' %s' % arg[len('qemuparams='):]
450 elif arg.startswith('bootparams='):
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500451 self.bootparams = arg[len('bootparams='):]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600452 elif os.path.exists(arg) or (re.search(':', arg) and re.search('/', arg)):
453 self.check_arg_path(os.path.abspath(arg))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500454 elif re.search(r'-image-|-image$', arg):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600455 # Lazy rootfs
456 self.rootfs = arg
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500457 elif arg.startswith('ovmf'):
458 self.ovmf_bios.append(arg)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600459 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500460 # At last, assume it is the MACHINE
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600461 if (not unknown_arg) or unknown_arg == arg:
462 unknown_arg = arg
463 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500464 raise RunQemuError("Can't handle two unknown args: %s %s\n"
465 "Try 'runqemu help' on how to use it" % \
466 (unknown_arg, arg))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600467 # Check to make sure it is a valid machine
468 if unknown_arg:
469 if self.get('MACHINE') == unknown_arg:
470 return
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500471 if self.get('DEPLOY_DIR_IMAGE'):
472 machine = os.path.basename(self.get('DEPLOY_DIR_IMAGE'))
473 if unknown_arg == machine:
474 self.set("MACHINE", machine)
475 return
476
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600477 self.check_arg_machine(unknown_arg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500478
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500479 if not (self.get('DEPLOY_DIR_IMAGE') or self.qbconfload):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500480 self.load_bitbake_env()
481 s = re.search('^DEPLOY_DIR_IMAGE="(.*)"', self.bitbake_e, re.M)
482 if s:
483 self.set("DEPLOY_DIR_IMAGE", s.group(1))
484
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600485 def check_kvm(self):
486 """Check kvm and kvm-host"""
487 if not (self.kvm_enabled or self.vhost_enabled):
488 self.qemu_opt_script += ' %s %s' % (self.get('QB_MACHINE'), self.get('QB_CPU'))
489 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500490
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600491 if not self.get('QB_CPU_KVM'):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500492 raise RunQemuError("QB_CPU_KVM is NULL, this board doesn't support kvm")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500493
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600494 self.qemu_opt_script += ' %s %s' % (self.get('QB_MACHINE'), self.get('QB_CPU_KVM'))
495 yocto_kvm_wiki = "https://wiki.yoctoproject.org/wiki/How_to_enable_KVM_for_Poky_qemu"
496 yocto_paravirt_kvm_wiki = "https://wiki.yoctoproject.org/wiki/Running_an_x86_Yocto_Linux_image_under_QEMU_KVM"
497 dev_kvm = '/dev/kvm'
498 dev_vhost = '/dev/vhost-net'
499 with open('/proc/cpuinfo', 'r') as f:
500 kvm_cap = re.search('vmx|svm', "".join(f.readlines()))
501 if not kvm_cap:
502 logger.error("You are trying to enable KVM on a cpu without VT support.")
503 logger.error("Remove kvm from the command-line, or refer:")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500504 raise RunQemuError(yocto_kvm_wiki)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500505
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600506 if not os.path.exists(dev_kvm):
507 logger.error("Missing KVM device. Have you inserted kvm modules?")
508 logger.error("For further help see:")
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 os.access(dev_kvm, os.W_OK|os.R_OK):
512 self.qemu_opt_script += ' -enable-kvm'
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500513 if self.get('MACHINE') == "qemux86":
514 # Workaround for broken APIC window on pre 4.15 host kernels which causes boot hangs
515 # See YOCTO #12301
516 # On 64 bit we use x2apic
517 self.kernel_cmdline_script += " clocksource=kvm-clock hpet=disable noapic nolapic"
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600518 else:
519 logger.error("You have no read or write permission on /dev/kvm.")
520 logger.error("Please change the ownership of this file as described at:")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500521 raise RunQemuError(yocto_kvm_wiki)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500522
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600523 if self.vhost_enabled:
524 if not os.path.exists(dev_vhost):
525 logger.error("Missing virtio net device. Have you inserted vhost-net module?")
526 logger.error("For further help see:")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500527 raise RunQemuError(yocto_paravirt_kvm_wiki)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500528
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600529 if not os.access(dev_kvm, os.W_OK|os.R_OK):
530 logger.error("You have no read or write permission on /dev/vhost-net.")
531 logger.error("Please change the ownership of this file as described at:")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500532 raise RunQemuError(yocto_kvm_wiki)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500533
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600534 def check_fstype(self):
535 """Check and setup FSTYPE"""
536 if not self.fstype:
537 fstype = self.get('QB_DEFAULT_FSTYPE')
538 if fstype:
539 self.fstype = fstype
540 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500541 raise RunQemuError("FSTYPE is NULL!")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500542
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600543 def check_rootfs(self):
544 """Check and set rootfs"""
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500545
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500546 if self.fstype == "none":
547 return
548
549 if self.get('ROOTFS'):
550 if not self.rootfs:
551 self.rootfs = self.get('ROOTFS')
552 elif self.get('ROOTFS') != self.rootfs:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500553 raise RunQemuError("Maybe conflicted ROOTFS: %s vs %s" % (self.get('ROOTFS'), self.rootfs))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500554
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600555 if self.fstype == 'nfs':
556 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500557
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600558 if self.rootfs and not os.path.exists(self.rootfs):
559 # Lazy rootfs
560 self.rootfs = "%s/%s-%s.%s" % (self.get('DEPLOY_DIR_IMAGE'),
561 self.rootfs, self.get('MACHINE'),
562 self.fstype)
563 elif not self.rootfs:
564 cmd_name = '%s/%s*.%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_NAME'), self.fstype)
565 cmd_link = '%s/%s*.%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_LINK_NAME'), self.fstype)
566 cmds = (cmd_name, cmd_link)
567 self.rootfs = get_first_file(cmds)
568 if not self.rootfs:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500569 raise RunQemuError("Failed to find rootfs: %s or %s" % cmds)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500570
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600571 if not os.path.exists(self.rootfs):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500572 raise RunQemuError("Can't find rootfs: %s" % self.rootfs)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500573
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500574 def check_ovmf(self):
575 """Check and set full path for OVMF firmware and variable file(s)."""
576
577 for index, ovmf in enumerate(self.ovmf_bios):
578 if os.path.exists(ovmf):
579 continue
580 for suffix in ('qcow2', 'bin'):
581 path = '%s/%s.%s' % (self.get('DEPLOY_DIR_IMAGE'), ovmf, suffix)
582 if os.path.exists(path):
583 self.ovmf_bios[index] = path
584 break
585 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500586 raise RunQemuError("Can't find OVMF firmware: %s" % ovmf)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500587
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600588 def check_kernel(self):
Brad Bishop316dfdd2018-06-25 12:45:53 -0400589 """Check and set kernel"""
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600590 # The vm image doesn't need a kernel
591 if self.fstype in self.vmtypes:
592 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500593
Brad Bishop316dfdd2018-06-25 12:45:53 -0400594 # See if the user supplied a KERNEL option
595 if self.get('KERNEL'):
596 self.kernel = self.get('KERNEL')
597
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500598 # QB_DEFAULT_KERNEL is always a full file path
599 kernel_name = os.path.basename(self.get('QB_DEFAULT_KERNEL'))
600
601 # The user didn't want a kernel to be loaded
Brad Bishop316dfdd2018-06-25 12:45:53 -0400602 if kernel_name == "none" and not self.kernel:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500603 return
604
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600605 deploy_dir_image = self.get('DEPLOY_DIR_IMAGE')
606 if not self.kernel:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500607 kernel_match_name = "%s/%s" % (deploy_dir_image, kernel_name)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600608 kernel_match_link = "%s/%s" % (deploy_dir_image, self.get('KERNEL_IMAGETYPE'))
609 kernel_startswith = "%s/%s*" % (deploy_dir_image, self.get('KERNEL_IMAGETYPE'))
610 cmds = (kernel_match_name, kernel_match_link, kernel_startswith)
611 self.kernel = get_first_file(cmds)
612 if not self.kernel:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500613 raise RunQemuError('KERNEL not found: %s, %s or %s' % cmds)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500614
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600615 if not os.path.exists(self.kernel):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500616 raise RunQemuError("KERNEL %s not found" % self.kernel)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500617
Brad Bishop316dfdd2018-06-25 12:45:53 -0400618 def check_dtb(self):
619 """Check and set dtb"""
620 # Did the user specify a device tree?
621 if self.get('DEVICE_TREE'):
622 self.dtb = self.get('DEVICE_TREE')
623 if not os.path.exists(self.dtb):
624 raise RunQemuError('Specified DTB not found: %s' % self.dtb)
625 return
626
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600627 dtb = self.get('QB_DTB')
628 if dtb:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400629 deploy_dir_image = self.get('DEPLOY_DIR_IMAGE')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600630 cmd_match = "%s/%s" % (deploy_dir_image, dtb)
631 cmd_startswith = "%s/%s*" % (deploy_dir_image, dtb)
632 cmd_wild = "%s/*.dtb" % deploy_dir_image
633 cmds = (cmd_match, cmd_startswith, cmd_wild)
634 self.dtb = get_first_file(cmds)
635 if not os.path.exists(self.dtb):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500636 raise RunQemuError('DTB not found: %s, %s or %s' % cmds)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500637
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600638 def check_biosdir(self):
639 """Check custombiosdir"""
640 if not self.custombiosdir:
641 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500642
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600643 biosdir = ""
644 biosdir_native = "%s/%s" % (self.get('STAGING_DIR_NATIVE'), self.custombiosdir)
645 biosdir_host = "%s/%s" % (self.get('STAGING_DIR_HOST'), self.custombiosdir)
646 for i in (self.custombiosdir, biosdir_native, biosdir_host):
647 if os.path.isdir(i):
648 biosdir = i
649 break
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500650
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600651 if biosdir:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500652 logger.debug("Assuming biosdir is: %s" % biosdir)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600653 self.qemu_opt_script += ' -L %s' % biosdir
654 else:
655 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 -0500656 raise RunQemuError("Invalid custombiosdir: %s" % self.custombiosdir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500657
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600658 def check_mem(self):
659 s = re.search('-m +([0-9]+)', self.qemu_opt_script)
660 if s:
661 self.set('QB_MEM', '-m %s' % s.group(1))
662 elif not self.get('QB_MEM'):
663 logger.info('QB_MEM is not set, use 512M by default')
664 self.set('QB_MEM', '-m 512')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500665
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600666 self.kernel_cmdline_script += ' mem=%s' % self.get('QB_MEM').replace('-m','').strip() + 'M'
667 self.qemu_opt_script += ' %s' % self.get('QB_MEM')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500668
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600669 def check_tcpserial(self):
670 if self.tcpserial_portnum:
671 if self.get('QB_TCPSERIAL_OPT'):
672 self.qemu_opt_script += ' ' + self.get('QB_TCPSERIAL_OPT').replace('@PORT@', self.tcpserial_portnum)
673 else:
674 self.qemu_opt_script += ' -serial tcp:127.0.0.1:%s' % self.tcpserial_portnum
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500675
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600676 def check_and_set(self):
677 """Check configs sanity and set when needed"""
678 self.validate_paths()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500679 if not self.slirp_enabled:
680 check_tun()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600681 # Check audio
682 if self.audio_enabled:
683 if not self.get('QB_AUDIO_DRV'):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500684 raise RunQemuError("QB_AUDIO_DRV is NULL, this board doesn't support audio")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600685 if not self.get('QB_AUDIO_OPT'):
686 logger.warn('QB_AUDIO_OPT is NULL, you may need define it to make audio work')
687 else:
688 self.qemu_opt_script += ' %s' % self.get('QB_AUDIO_OPT')
689 os.putenv('QEMU_AUDIO_DRV', self.get('QB_AUDIO_DRV'))
690 else:
691 os.putenv('QEMU_AUDIO_DRV', 'none')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500692
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600693 self.check_kvm()
694 self.check_fstype()
695 self.check_rootfs()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500696 self.check_ovmf()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600697 self.check_kernel()
Brad Bishop316dfdd2018-06-25 12:45:53 -0400698 self.check_dtb()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600699 self.check_biosdir()
700 self.check_mem()
701 self.check_tcpserial()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500702
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600703 def read_qemuboot(self):
704 if not self.qemuboot:
705 if self.get('DEPLOY_DIR_IMAGE'):
706 deploy_dir_image = self.get('DEPLOY_DIR_IMAGE')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600707 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500708 logger.warn("Can't find qemuboot conf file, DEPLOY_DIR_IMAGE is NULL!")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600709 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500710
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600711 if self.rootfs and not os.path.exists(self.rootfs):
712 # Lazy rootfs
713 machine = self.get('MACHINE')
714 if not machine:
715 machine = os.path.basename(deploy_dir_image)
716 self.qemuboot = "%s/%s-%s.qemuboot.conf" % (deploy_dir_image,
717 self.rootfs, machine)
718 else:
719 cmd = 'ls -t %s/*.qemuboot.conf' % deploy_dir_image
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500720 logger.debug('Running %s...' % cmd)
721 try:
722 qbs = subprocess.check_output(cmd, shell=True).decode('utf-8')
723 except subprocess.CalledProcessError as err:
724 raise RunQemuError(err)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600725 if qbs:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500726 for qb in qbs.split():
727 # Don't use initramfs when other choices unless fstype is ramfs
728 if '-initramfs-' in os.path.basename(qb) and self.fstype != 'cpio.gz':
729 continue
730 self.qemuboot = qb
731 break
732 if not self.qemuboot:
733 # Use the first one when no choice
734 self.qemuboot = qbs.split()[0]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600735 self.qbconfload = True
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500736
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600737 if not self.qemuboot:
738 # If we haven't found a .qemuboot.conf at this point it probably
739 # doesn't exist, continue without
740 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500741
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600742 if not os.path.exists(self.qemuboot):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500743 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 -0500744
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500745 logger.debug('CONFFILE: %s' % self.qemuboot)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500746
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600747 cf = configparser.ConfigParser()
748 cf.read(self.qemuboot)
749 for k, v in cf.items('config_bsp'):
750 k_upper = k.upper()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500751 if v.startswith("../"):
752 v = os.path.abspath(os.path.dirname(self.qemuboot) + "/" + v)
753 elif v == ".":
754 v = os.path.dirname(self.qemuboot)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600755 self.set(k_upper, v)
756
757 def validate_paths(self):
758 """Ensure all relevant path variables are set"""
759 # When we're started with a *.qemuboot.conf arg assume that image
760 # artefacts are relative to that file, rather than in whatever
761 # directory DEPLOY_DIR_IMAGE in the conf file points to.
762 if self.qbconfload:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500763 imgdir = os.path.realpath(os.path.dirname(self.qemuboot))
764 if imgdir != os.path.realpath(self.get('DEPLOY_DIR_IMAGE')):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600765 logger.info('Setting DEPLOY_DIR_IMAGE to folder containing %s (%s)' % (self.qemuboot, imgdir))
766 self.set('DEPLOY_DIR_IMAGE', imgdir)
767
768 # If the STAGING_*_NATIVE directories from the config file don't exist
769 # and we're in a sourced OE build directory try to extract the paths
770 # from `bitbake -e`
771 havenative = os.path.exists(self.get('STAGING_DIR_NATIVE')) and \
772 os.path.exists(self.get('STAGING_BINDIR_NATIVE'))
773
774 if not havenative:
775 if not self.bitbake_e:
776 self.load_bitbake_env()
777
778 if self.bitbake_e:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500779 native_vars = ['STAGING_DIR_NATIVE']
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600780 for nv in native_vars:
781 s = re.search('^%s="(.*)"' % nv, self.bitbake_e, re.M)
782 if s and s.group(1) != self.get(nv):
783 logger.info('Overriding conf file setting of %s to %s from Bitbake environment' % (nv, s.group(1)))
784 self.set(nv, s.group(1))
785 else:
786 # when we're invoked from a running bitbake instance we won't
787 # be able to call `bitbake -e`, then try:
788 # - get OE_TMPDIR from environment and guess paths based on it
789 # - get OECORE_NATIVE_SYSROOT from environment (for sdk)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500790 tmpdir = self.get('OE_TMPDIR')
791 oecore_native_sysroot = self.get('OECORE_NATIVE_SYSROOT')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600792 if tmpdir:
793 logger.info('Setting STAGING_DIR_NATIVE and STAGING_BINDIR_NATIVE relative to OE_TMPDIR (%s)' % tmpdir)
794 hostos, _, _, _, machine = os.uname()
795 buildsys = '%s-%s' % (machine, hostos.lower())
796 staging_dir_native = '%s/sysroots/%s' % (tmpdir, buildsys)
797 self.set('STAGING_DIR_NATIVE', staging_dir_native)
798 elif oecore_native_sysroot:
799 logger.info('Setting STAGING_DIR_NATIVE to OECORE_NATIVE_SYSROOT (%s)' % oecore_native_sysroot)
800 self.set('STAGING_DIR_NATIVE', oecore_native_sysroot)
801 if self.get('STAGING_DIR_NATIVE'):
802 # we have to assume that STAGING_BINDIR_NATIVE is at usr/bin
803 staging_bindir_native = '%s/usr/bin' % self.get('STAGING_DIR_NATIVE')
804 logger.info('Setting STAGING_BINDIR_NATIVE to %s' % staging_bindir_native)
805 self.set('STAGING_BINDIR_NATIVE', '%s/usr/bin' % self.get('STAGING_DIR_NATIVE'))
806
807 def print_config(self):
808 logger.info('Continuing with the following parameters:\n')
809 if not self.fstype in self.vmtypes:
810 print('KERNEL: [%s]' % self.kernel)
811 if self.dtb:
812 print('DTB: [%s]' % self.dtb)
813 print('MACHINE: [%s]' % self.get('MACHINE'))
814 print('FSTYPE: [%s]' % self.fstype)
815 if self.fstype == 'nfs':
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500816 print('NFS_DIR: [%s]' % self.rootfs)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600817 else:
818 print('ROOTFS: [%s]' % self.rootfs)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500819 if self.ovmf_bios:
820 print('OVMF: %s' % self.ovmf_bios)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600821 print('CONFFILE: [%s]' % self.qemuboot)
822 print('')
823
824 def setup_nfs(self):
825 if not self.nfs_server:
826 if self.slirp_enabled:
827 self.nfs_server = '10.0.2.2'
828 else:
829 self.nfs_server = '192.168.7.1'
830
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500831 # Figure out a new nfs_instance to allow multiple qemus running.
832 # CentOS 7.1's ps doesn't print full command line without "ww"
833 # when invoke by subprocess.Popen().
834 cmd = "ps auxww"
835 ps = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
836 pattern = '/bin/unfsd .* -i .*\.pid -e .*/exports([0-9]+) '
837 all_instances = re.findall(pattern, ps, re.M)
838 if all_instances:
839 all_instances.sort(key=int)
840 self.nfs_instance = int(all_instances.pop()) + 1
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600841
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500842 nfsd_port = 3049 + 2 * self.nfs_instance
843 mountd_port = 3048 + 2 * self.nfs_instance
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600844
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500845 # Export vars for runqemu-export-rootfs
846 export_dict = {
847 'NFS_INSTANCE': self.nfs_instance,
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500848 'NFSD_PORT': nfsd_port,
849 'MOUNTD_PORT': mountd_port,
850 }
851 for k, v in export_dict.items():
852 # Use '%s' since they are integers
853 os.putenv(k, '%s' % v)
854
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500855 self.unfs_opts="nfsvers=3,port=%s,udp,mountport=%s" % (nfsd_port, mountd_port)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600856
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500857 # Extract .tar.bz2 or .tar.bz if no nfs dir
858 if not (self.rootfs and os.path.isdir(self.rootfs)):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600859 src_prefix = '%s/%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_LINK_NAME'))
860 dest = "%s-nfsroot" % src_prefix
861 if os.path.exists('%s.pseudo_state' % dest):
862 logger.info('Use %s as NFS_DIR' % dest)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500863 self.rootfs = dest
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600864 else:
865 src = ""
866 src1 = '%s.tar.bz2' % src_prefix
867 src2 = '%s.tar.gz' % src_prefix
868 if os.path.exists(src1):
869 src = src1
870 elif os.path.exists(src2):
871 src = src2
872 if not src:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500873 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 -0600874 logger.info('NFS_DIR not found, extracting %s to %s' % (src, dest))
875 cmd = 'runqemu-extract-sdk %s %s' % (src, dest)
876 logger.info('Running %s...' % cmd)
877 if subprocess.call(cmd, shell=True) != 0:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500878 raise RunQemuError('Failed to run %s' % cmd)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600879 self.clean_nfs_dir = True
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500880 self.rootfs = dest
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600881
882 # Start the userspace NFS server
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500883 cmd = 'runqemu-export-rootfs start %s' % self.rootfs
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600884 logger.info('Running %s...' % cmd)
885 if subprocess.call(cmd, shell=True) != 0:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500886 raise RunQemuError('Failed to run %s' % cmd)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600887
888 self.nfs_running = True
889
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600890 def setup_slirp(self):
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500891 """Setup user networking"""
892
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600893 if self.fstype == 'nfs':
894 self.setup_nfs()
895 self.kernel_cmdline_script += ' ip=dhcp'
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500896 # Port mapping
897 hostfwd = ",hostfwd=tcp::2222-:22,hostfwd=tcp::2323-:23"
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500898 qb_slirp_opt_default = "-netdev user,id=net0%s,tftp=%s" % (hostfwd, self.get('DEPLOY_DIR_IMAGE'))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500899 qb_slirp_opt = self.get('QB_SLIRP_OPT') or qb_slirp_opt_default
900 # Figure out the port
901 ports = re.findall('hostfwd=[^-]*:([0-9]+)-[^,-]*', qb_slirp_opt)
902 ports = [int(i) for i in ports]
903 mac = 2
904 # Find a free port to avoid conflicts
905 for p in ports[:]:
906 p_new = p
907 while not check_free_port('localhost', p_new):
908 p_new += 1
909 mac += 1
910 while p_new in ports:
911 p_new += 1
912 mac += 1
913 if p != p_new:
914 ports.append(p_new)
915 qb_slirp_opt = re.sub(':%s-' % p, ':%s-' % p_new, qb_slirp_opt)
916 logger.info("Port forward changed: %s -> %s" % (p, p_new))
917 mac = "%s%02x" % (self.mac_slirp, mac)
918 self.set('NETWORK_CMD', '%s %s' % (self.network_device.replace('@MAC@', mac), qb_slirp_opt))
919 # Print out port foward
920 hostfwd = re.findall('(hostfwd=[^,]*)', qb_slirp_opt)
921 if hostfwd:
922 logger.info('Port forward: %s' % ' '.join(hostfwd))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600923
924 def setup_tap(self):
925 """Setup tap"""
926
927 # This file is created when runqemu-gen-tapdevs creates a bank of tap
928 # devices, indicating that the user should not bring up new ones using
929 # sudo.
930 nosudo_flag = '/etc/runqemu-nosudo'
931 self.qemuifup = shutil.which('runqemu-ifup')
932 self.qemuifdown = shutil.which('runqemu-ifdown')
933 ip = shutil.which('ip')
934 lockdir = "/tmp/qemu-tap-locks"
935
936 if not (self.qemuifup and self.qemuifdown and ip):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500937 logger.error("runqemu-ifup: %s" % self.qemuifup)
938 logger.error("runqemu-ifdown: %s" % self.qemuifdown)
939 logger.error("ip: %s" % ip)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600940 raise OEPathError("runqemu-ifup, runqemu-ifdown or ip not found")
941
942 if not os.path.exists(lockdir):
943 # There might be a race issue when multi runqemu processess are
944 # running at the same time.
945 try:
946 os.mkdir(lockdir)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500947 os.chmod(lockdir, 0o777)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600948 except FileExistsError:
949 pass
950
951 cmd = '%s link' % ip
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500952 logger.debug('Running %s...' % cmd)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600953 ip_link = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
954 # Matches line like: 6: tap0: <foo>
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500955 possibles = re.findall('^[0-9]+: +(tap[0-9]+): <.*', ip_link, re.M)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600956 tap = ""
957 for p in possibles:
958 lockfile = os.path.join(lockdir, p)
959 if os.path.exists('%s.skip' % lockfile):
960 logger.info('Found %s.skip, skipping %s' % (lockfile, p))
961 continue
962 self.lock = lockfile + '.lock'
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500963 if self.acquire_lock(error=False):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600964 tap = p
965 logger.info("Using preconfigured tap device %s" % tap)
966 logger.info("If this is not intended, touch %s.skip to make runqemu skip %s." %(lockfile, tap))
967 break
968
969 if not tap:
970 if os.path.exists(nosudo_flag):
971 logger.error("Error: There are no available tap devices to use for networking,")
972 logger.error("and I see %s exists, so I am not going to try creating" % nosudo_flag)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500973 raise RunQemuError("a new one with sudo.")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600974
975 gid = os.getgid()
976 uid = os.getuid()
977 logger.info("Setting up tap interface under sudo")
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500978 cmd = 'sudo %s %s %s %s' % (self.qemuifup, uid, gid, self.bindir_native)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600979 tap = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8').rstrip('\n')
980 lockfile = os.path.join(lockdir, tap)
981 self.lock = lockfile + '.lock'
982 self.acquire_lock()
983 self.cleantap = True
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500984 logger.debug('Created tap: %s' % tap)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600985
986 if not tap:
987 logger.error("Failed to setup tap device. Run runqemu-gen-tapdevs to manually create.")
988 return 1
989 self.tap = tap
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500990 tapnum = int(tap[3:])
991 gateway = tapnum * 2 + 1
992 client = gateway + 1
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600993 if self.fstype == 'nfs':
994 self.setup_nfs()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500995 netconf = "192.168.7.%s::192.168.7.%s:255.255.255.0" % (client, gateway)
996 logger.info("Network configuration: %s", netconf)
997 self.kernel_cmdline_script += " ip=%s" % netconf
998 mac = "%s%02x" % (self.mac_tap, client)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600999 qb_tap_opt = self.get('QB_TAP_OPT')
1000 if qb_tap_opt:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001001 qemu_tap_opt = qb_tap_opt.replace('@TAP@', tap)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001002 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001003 qemu_tap_opt = "-netdev tap,id=net0,ifname=%s,script=no,downscript=no" % (self.tap)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001004
1005 if self.vhost_enabled:
1006 qemu_tap_opt += ',vhost=on'
1007
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001008 self.set('NETWORK_CMD', '%s %s' % (self.network_device.replace('@MAC@', mac), qemu_tap_opt))
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001009
1010 def setup_network(self):
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001011 if self.get('QB_NET') == 'none':
1012 return
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001013 if sys.stdin.isatty():
1014 self.saved_stty = subprocess.check_output("stty -g", shell=True).decode('utf-8')
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001015 self.network_device = self.get('QB_NETWORK_DEVICE') or self.network_device
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001016 if self.slirp_enabled:
1017 self.setup_slirp()
1018 else:
1019 self.setup_tap()
1020
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001021 def setup_rootfs(self):
1022 if self.get('QB_ROOTFS') == 'none':
1023 return
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001024 if 'wic.' in self.fstype:
1025 self.fstype = self.fstype[4:]
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001026 rootfs_format = self.fstype if self.fstype in ('vmdk', 'qcow2', 'vdi') else 'raw'
1027
1028 qb_rootfs_opt = self.get('QB_ROOTFS_OPT')
1029 if qb_rootfs_opt:
1030 self.rootfs_options = qb_rootfs_opt.replace('@ROOTFS@', self.rootfs)
1031 else:
1032 self.rootfs_options = '-drive file=%s,if=virtio,format=%s' % (self.rootfs, rootfs_format)
1033
1034 if self.fstype in ('cpio.gz', 'cpio'):
1035 self.kernel_cmdline = 'root=/dev/ram0 rw debugshell'
1036 self.rootfs_options = '-initrd %s' % self.rootfs
1037 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001038 vm_drive = ''
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001039 if self.fstype in self.vmtypes:
1040 if self.fstype == 'iso':
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001041 vm_drive = '-drive file=%s,if=virtio,media=cdrom' % self.rootfs
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001042 elif self.get('QB_DRIVE_TYPE'):
1043 drive_type = self.get('QB_DRIVE_TYPE')
1044 if drive_type.startswith("/dev/sd"):
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001045 logger.info('Using scsi drive')
1046 vm_drive = '-drive if=none,id=hd,file=%s,format=%s -device virtio-scsi-pci,id=scsi -device scsi-hd,drive=hd' \
1047 % (self.rootfs, rootfs_format)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001048 elif drive_type.startswith("/dev/hd"):
Brad Bishop37a0e4d2017-12-04 01:01:44 -05001049 logger.info('Using ide drive')
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001050 vm_drive = "-drive file=%s,format=%s" % (self.rootfs, rootfs_format)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001051 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001052 # virtio might have been selected explicitly (just use it), or
1053 # is used as fallback (then warn about that).
1054 if not drive_type.startswith("/dev/vd"):
1055 logger.warn("Unknown QB_DRIVE_TYPE: %s" % drive_type)
1056 logger.warn("Failed to figure out drive type, consider define or fix QB_DRIVE_TYPE")
1057 logger.warn('Trying to use virtio block drive')
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001058 vm_drive = '-drive if=virtio,file=%s,format=%s' % (self.rootfs, rootfs_format)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001059
1060 # All branches above set vm_drive.
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001061 self.rootfs_options = '%s -no-reboot' % vm_drive
1062 self.kernel_cmdline = 'root=%s rw highres=off' % (self.get('QB_KERNEL_ROOT'))
1063
1064 if self.fstype == 'nfs':
1065 self.rootfs_options = ''
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001066 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 -06001067 self.kernel_cmdline = 'root=%s rw highres=off' % k_root
1068
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001069 if self.fstype == 'none':
1070 self.rootfs_options = ''
1071
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001072 self.set('ROOTFS_OPTIONS', self.rootfs_options)
1073
1074 def guess_qb_system(self):
1075 """attempt to determine the appropriate qemu-system binary"""
1076 mach = self.get('MACHINE')
1077 if not mach:
1078 search = '.*(qemux86-64|qemux86|qemuarm64|qemuarm|qemumips64|qemumips64el|qemumipsel|qemumips|qemuppc).*'
1079 if self.rootfs:
1080 match = re.match(search, self.rootfs)
1081 if match:
1082 mach = match.group(1)
1083 elif self.kernel:
1084 match = re.match(search, self.kernel)
1085 if match:
1086 mach = match.group(1)
1087
1088 if not mach:
1089 return None
1090
1091 if mach == 'qemuarm':
1092 qbsys = 'arm'
1093 elif mach == 'qemuarm64':
1094 qbsys = 'aarch64'
1095 elif mach == 'qemux86':
1096 qbsys = 'i386'
1097 elif mach == 'qemux86-64':
1098 qbsys = 'x86_64'
1099 elif mach == 'qemuppc':
1100 qbsys = 'ppc'
1101 elif mach == 'qemumips':
1102 qbsys = 'mips'
1103 elif mach == 'qemumips64':
1104 qbsys = 'mips64'
1105 elif mach == 'qemumipsel':
1106 qbsys = 'mipsel'
1107 elif mach == 'qemumips64el':
1108 qbsys = 'mips64el'
Brad Bishop316dfdd2018-06-25 12:45:53 -04001109 elif mach == 'qemuriscv64':
1110 qbsys = 'riscv64'
1111 elif mach == 'qemuriscv32':
1112 qbsys = 'riscv32'
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001113
1114 return 'qemu-system-%s' % qbsys
1115
1116 def setup_final(self):
1117 qemu_system = self.get('QB_SYSTEM_NAME')
1118 if not qemu_system:
1119 qemu_system = self.guess_qb_system()
1120 if not qemu_system:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001121 raise RunQemuError("Failed to boot, QB_SYSTEM_NAME is NULL!")
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001122
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001123 qemu_bin = '%s/%s' % (self.bindir_native, qemu_system)
1124
1125 # It is possible to have qemu-native in ASSUME_PROVIDED, and it won't
1126 # find QEMU in sysroot, it needs to use host's qemu.
1127 if not os.path.exists(qemu_bin):
1128 logger.info("QEMU binary not found in %s, trying host's QEMU" % qemu_bin)
1129 for path in (os.environ['PATH'] or '').split(':'):
1130 qemu_bin_tmp = os.path.join(path, qemu_system)
1131 logger.info("Trying: %s" % qemu_bin_tmp)
1132 if os.path.exists(qemu_bin_tmp):
1133 qemu_bin = qemu_bin_tmp
1134 if not os.path.isabs(qemu_bin):
1135 qemu_bin = os.path.abspath(qemu_bin)
1136 logger.info("Using host's QEMU: %s" % qemu_bin)
1137 break
1138
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001139 if not os.access(qemu_bin, os.X_OK):
1140 raise OEPathError("No QEMU binary '%s' could be found" % qemu_bin)
1141
1142 check_libgl(qemu_bin)
1143
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001144 self.qemu_opt = "%s %s %s %s" % (qemu_bin, self.get('NETWORK_CMD'), self.get('ROOTFS_OPTIONS'), self.get('QB_OPT_APPEND'))
1145
1146 for ovmf in self.ovmf_bios:
1147 format = ovmf.rsplit('.', 1)[-1]
1148 self.qemu_opt += ' -drive if=pflash,format=%s,file=%s' % (format, ovmf)
1149 if self.ovmf_bios:
1150 # OVMF only supports normal VGA, i.e. we need to override a -vga vmware
1151 # that gets added for example for normal qemux86.
1152 self.qemu_opt += ' -vga std'
1153
1154 self.qemu_opt += ' ' + self.qemu_opt_script
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001155
1156 if self.snapshot:
1157 self.qemu_opt += " -snapshot"
1158
1159 if self.serialstdio:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001160 if sys.stdin.isatty():
1161 subprocess.check_call("stty intr ^]", shell=True)
1162 logger.info("Interrupt character is '^]'")
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001163
1164 first_serial = ""
1165 if not re.search("-nographic", self.qemu_opt):
1166 first_serial = "-serial mon:vc"
1167 # We always want a ttyS1. Since qemu by default adds a serial
1168 # port when nodefaults is not specified, it seems that all that
1169 # would be needed is to make sure a "-serial" is there. However,
1170 # it appears that when "-serial" is specified, it ignores the
1171 # default serial port that is normally added. So here we make
1172 # sure to add two -serial if there are none. And only one if
1173 # there is one -serial already.
1174 serial_num = len(re.findall("-serial", self.qemu_opt))
1175 if serial_num == 0:
1176 self.qemu_opt += " %s %s" % (first_serial, self.get("QB_SERIAL_OPT"))
1177 elif serial_num == 1:
1178 self.qemu_opt += " %s" % self.get("QB_SERIAL_OPT")
1179
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001180 # We always wants ttyS0 and ttyS1 in qemu machines (see SERIAL_CONSOLES),
1181 # if not serial or serialtcp options was specified only ttyS0 is created
1182 # and sysvinit shows an error trying to enable ttyS1:
1183 # INIT: Id "S1" respawning too fast: disabled for 5 minutes
1184 serial_num = len(re.findall("-serial", self.qemu_opt))
1185 if serial_num == 0:
1186 if re.search("-nographic", self.qemu_opt):
1187 self.qemu_opt += " -serial mon:stdio -serial null"
1188 else:
1189 self.qemu_opt += " -serial mon:vc -serial null"
1190
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001191 def start_qemu(self):
1192 if self.kernel:
Brad Bishop37a0e4d2017-12-04 01:01:44 -05001193 kernel_opts = "-kernel %s -append '%s %s %s %s'" % (self.kernel, self.kernel_cmdline,
1194 self.kernel_cmdline_script, self.get('QB_KERNEL_CMDLINE_APPEND'),
1195 self.bootparams)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001196 if self.dtb:
1197 kernel_opts += " -dtb %s" % self.dtb
1198 else:
1199 kernel_opts = ""
1200 cmd = "%s %s" % (self.qemu_opt, kernel_opts)
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001201 logger.info('Running %s\n' % cmd)
1202 process = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)
1203 if process.wait():
1204 logger.error("Failed to run qemu: %s", process.stderr.read().decode())
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001205
1206 def cleanup(self):
1207 if self.cleantap:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001208 cmd = 'sudo %s %s %s' % (self.qemuifdown, self.tap, self.bindir_native)
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001209 logger.debug('Running %s' % cmd)
1210 subprocess.check_call(cmd, shell=True)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001211 if self.lock_descriptor:
1212 logger.info("Releasing lockfile for tap device '%s'" % self.tap)
1213 self.release_lock()
1214
1215 if self.nfs_running:
1216 logger.info("Shutting down the userspace NFS server...")
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001217 cmd = "runqemu-export-rootfs stop %s" % self.rootfs
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001218 logger.debug('Running %s' % cmd)
1219 subprocess.check_call(cmd, shell=True)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001220
1221 if self.saved_stty:
1222 cmd = "stty %s" % self.saved_stty
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001223 subprocess.check_call(cmd, shell=True)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001224
1225 if self.clean_nfs_dir:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001226 logger.info('Removing %s' % self.rootfs)
1227 shutil.rmtree(self.rootfs)
1228 shutil.rmtree('%s.pseudo_state' % self.rootfs)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001229
1230 def load_bitbake_env(self, mach=None):
1231 if self.bitbake_e:
1232 return
1233
1234 bitbake = shutil.which('bitbake')
1235 if not bitbake:
1236 return
1237
1238 if not mach:
1239 mach = self.get('MACHINE')
1240
1241 if mach:
1242 cmd = 'MACHINE=%s bitbake -e' % mach
1243 else:
1244 cmd = 'bitbake -e'
1245
1246 logger.info('Running %s...' % cmd)
1247 try:
1248 self.bitbake_e = subprocess.check_output(cmd, shell=True).decode('utf-8')
1249 except subprocess.CalledProcessError as err:
1250 self.bitbake_e = ''
1251 logger.warn("Couldn't run 'bitbake -e' to gather environment information:\n%s" % err.output.decode('utf-8'))
1252
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001253 def validate_combos(self):
1254 if (self.fstype in self.vmtypes) and self.kernel:
1255 raise RunQemuError("%s doesn't need kernel %s!" % (self.fstype, self.kernel))
1256
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001257 @property
1258 def bindir_native(self):
1259 result = self.get('STAGING_BINDIR_NATIVE')
1260 if result and os.path.exists(result):
1261 return result
1262
1263 cmd = 'bitbake qemu-helper-native -e'
1264 logger.info('Running %s...' % cmd)
1265 out = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
1266 out = out.stdout.read().decode('utf-8')
1267
1268 match = re.search('^STAGING_BINDIR_NATIVE="(.*)"', out, re.M)
1269 if match:
1270 result = match.group(1)
1271 if os.path.exists(result):
1272 self.set('STAGING_BINDIR_NATIVE', result)
1273 return result
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001274 raise RunQemuError("Native sysroot directory %s doesn't exist" % result)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001275 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001276 raise RunQemuError("Can't find STAGING_BINDIR_NATIVE in '%s' output" % cmd)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001277
1278
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001279def main():
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001280 if "help" in sys.argv or '-h' in sys.argv or '--help' in sys.argv:
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001281 print_usage()
1282 return 0
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001283 try:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001284 config = BaseConfig()
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001285 config.check_args()
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001286 config.read_qemuboot()
1287 config.check_and_set()
1288 # Check whether the combos is valid or not
1289 config.validate_combos()
1290 config.print_config()
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001291 config.setup_network()
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001292 config.setup_rootfs()
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001293 config.setup_final()
1294 config.start_qemu()
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001295 except RunQemuError as err:
1296 logger.error(err)
1297 return 1
1298 except Exception as err:
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001299 import traceback
1300 traceback.print_exc()
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001301 return 1
1302 finally:
1303 print("Cleanup")
1304 config.cleanup()
1305
1306if __name__ == "__main__":
1307 sys.exit(main())