blob: 0ed1eec2d3c03432a93e684a6bfb9b5cc05578e0 [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
72 MACHINE - the machine name (optional, autodetected from KERNEL filename if unspecified)
73 Simplified QEMU command-line options can be passed with:
Patrick Williamsc0f7c042017-02-23 20:41:17 -060074 nographic - disable video console
75 serial - enable a serial console on /dev/ttyS0
76 slirp - enable user networking, no root privileges is required
77 kvm - enable KVM when running x86/x86_64 (VT-capable CPU required)
78 kvm-vhost - enable KVM with vhost when running x86/x86_64 (VT-capable CPU required)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050079 publicvnc - enable a VNC server open to all hosts
Patrick Williamsc0f7c042017-02-23 20:41:17 -060080 audio - enable audio
Brad Bishop6e60e8b2018-02-01 10:27:11 -050081 [*/]ovmf* - OVMF firmware file or base name for booting with UEFI
Patrick Williamsc0f7c042017-02-23 20:41:17 -060082 tcpserial=<port> - specify tcp serial port number
83 biosdir=<dir> - specify custom bios dir
84 biosfilename=<filename> - specify bios filename
85 qemuparams=<xyz> - specify custom parameters to QEMU
86 bootparams=<xyz> - specify custom kernel parameters during boot
Brad Bishop6e60e8b2018-02-01 10:27:11 -050087 help, -h, --help: print this text
Brad Bishopd7bf8c12018-02-25 22:55:05 -050088 -d, --debug: Enable debug output
89 -q, --quite: Hide most output except error messages
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050090
91Examples:
Brad Bishop6e60e8b2018-02-01 10:27:11 -050092 runqemu
Patrick Williamsc0f7c042017-02-23 20:41:17 -060093 runqemu qemuarm
94 runqemu tmp/deploy/images/qemuarm
Brad Bishop6e60e8b2018-02-01 10:27:11 -050095 runqemu tmp/deploy/images/qemux86/<qemuboot.conf>
Patrick Williamsc0f7c042017-02-23 20:41:17 -060096 runqemu qemux86-64 core-image-sato ext4
97 runqemu qemux86-64 wic-image-minimal wic
98 runqemu path/to/bzImage-qemux86.bin path/to/nfsrootdir/ serial
Brad Bishopd7bf8c12018-02-25 22:55:05 -050099 runqemu qemux86 iso/hddimg/wic.vmdk/wic.qcow2/wic.vdi/ramfs/cpio.gz...
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600100 runqemu qemux86 qemuparams="-m 256"
101 runqemu qemux86 bootparams="psplash=false"
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600102 runqemu path/to/<image>-<machine>.wic
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500103 runqemu path/to/<image>-<machine>.wic.vmdk
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600104""")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500105
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600106def check_tun():
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500107 """Check /dev/net/tun"""
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600108 dev_tun = '/dev/net/tun'
109 if not os.path.exists(dev_tun):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500110 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 -0500111
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600112 if not os.access(dev_tun, os.W_OK):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500113 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 -0500114
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600115def check_libgl(qemu_bin):
116 cmd = 'ldd %s' % qemu_bin
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500117 logger.debug('Running %s...' % cmd)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600118 need_gl = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
119 if re.search('libGLU', need_gl):
120 # We can't run without a libGL.so
121 libgl = False
122 check_files = (('/usr/lib/libGL.so', '/usr/lib/libGLU.so'), \
123 ('/usr/lib64/libGL.so', '/usr/lib64/libGLU.so'), \
124 ('/usr/lib/*-linux-gnu/libGL.so', '/usr/lib/*-linux-gnu/libGLU.so'))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500125
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600126 for (f1, f2) in check_files:
127 if re.search('\*', f1):
128 for g1 in glob.glob(f1):
129 if libgl:
130 break
131 if os.path.exists(g1):
132 for g2 in glob.glob(f2):
133 if os.path.exists(g2):
134 libgl = True
135 break
136 if libgl:
137 break
138 else:
139 if os.path.exists(f1) and os.path.exists(f2):
140 libgl = True
141 break
142 if not libgl:
143 logger.error("You need libGL.so and libGLU.so to exist in your library path to run the QEMU emulator.")
144 logger.error("Ubuntu package names are: libgl1-mesa-dev and libglu1-mesa-dev.")
145 logger.error("Fedora package names are: mesa-libGL-devel mesa-libGLU-devel.")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500146 raise RunQemuError('%s requires libGLU, but not found' % qemu_bin)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500147
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600148def get_first_file(cmds):
149 """Return first file found in wildcard cmds"""
150 for cmd in cmds:
151 all_files = glob.glob(cmd)
152 if all_files:
153 for f in all_files:
154 if not os.path.isdir(f):
155 return f
156 return ''
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500157
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500158def check_free_port(host, port):
159 """ Check whether the port is free or not """
160 import socket
161 from contextlib import closing
162
163 with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
164 if sock.connect_ex((host, port)) == 0:
165 # Port is open, so not free
166 return False
167 else:
168 # Port is not open, so free
169 return True
170
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600171class BaseConfig(object):
172 def __init__(self):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500173 # The self.d saved vars from self.set(), part of them are from qemuboot.conf
174 self.d = {'QB_KERNEL_ROOT': '/dev/vda'}
175
176 # Supported env vars, add it here if a var can be got from env,
177 # and don't use os.getenv in the code.
178 self.env_vars = ('MACHINE',
179 'ROOTFS',
180 'KERNEL',
181 'DEPLOY_DIR_IMAGE',
182 'OE_TMPDIR',
183 'OECORE_NATIVE_SYSROOT',
184 )
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500185
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600186 self.qemu_opt = ''
187 self.qemu_opt_script = ''
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600188 self.clean_nfs_dir = False
189 self.nfs_server = ''
190 self.rootfs = ''
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500191 # File name(s) of a OVMF firmware file or variable store,
192 # to be added with -drive if=pflash.
193 # Found in the same places as the rootfs, with or without one of
194 # these suffices: qcow2, bin.
195 # Setting one also adds "-vga std" because that is all that
196 # OVMF supports.
197 self.ovmf_bios = []
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600198 self.qemuboot = ''
199 self.qbconfload = False
200 self.kernel = ''
201 self.kernel_cmdline = ''
202 self.kernel_cmdline_script = ''
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500203 self.bootparams = ''
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600204 self.dtb = ''
205 self.fstype = ''
206 self.kvm_enabled = False
207 self.vhost_enabled = False
208 self.slirp_enabled = False
209 self.nfs_instance = 0
210 self.nfs_running = False
211 self.serialstdio = False
212 self.cleantap = False
213 self.saved_stty = ''
214 self.audio_enabled = False
215 self.tcpserial_portnum = ''
216 self.custombiosdir = ''
217 self.lock = ''
218 self.lock_descriptor = ''
219 self.bitbake_e = ''
220 self.snapshot = False
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500221 self.fstypes = ('ext2', 'ext3', 'ext4', 'jffs2', 'nfs', 'btrfs',
222 'cpio.gz', 'cpio', 'ramfs', 'tar.bz2', 'tar.gz')
223 self.vmtypes = ('hddimg', 'hdddirect', 'wic', 'wic.vmdk',
224 'wic.qcow2', 'wic.vdi', 'iso')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500225 self.network_device = "-device e1000,netdev=net0,mac=@MAC@"
226 # Use different mac section for tap and slirp to avoid
227 # conflicts, e.g., when one is running with tap, the other is
228 # running with slirp.
229 # The last section is dynamic, which is for avoiding conflicts,
230 # when multiple qemus are running, e.g., when multiple tap or
231 # slirp qemus are running.
232 self.mac_tap = "52:54:00:12:34:"
233 self.mac_slirp = "52:54:00:12:35:"
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500234
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500235 def acquire_lock(self, error=True):
236 logger.debug("Acquiring lockfile %s..." % self.lock)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600237 try:
238 self.lock_descriptor = open(self.lock, 'w')
239 fcntl.flock(self.lock_descriptor, fcntl.LOCK_EX|fcntl.LOCK_NB)
240 except Exception as e:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500241 msg = "Acquiring lockfile %s failed: %s" % (self.lock, e)
242 if error:
243 logger.error(msg)
244 else:
245 logger.info(msg)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600246 if self.lock_descriptor:
247 self.lock_descriptor.close()
248 return False
249 return True
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500250
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600251 def release_lock(self):
252 fcntl.flock(self.lock_descriptor, fcntl.LOCK_UN)
253 self.lock_descriptor.close()
254 os.remove(self.lock)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500255
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600256 def get(self, key):
257 if key in self.d:
258 return self.d.get(key)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500259 elif os.getenv(key):
260 return os.getenv(key)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600261 else:
262 return ''
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500263
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600264 def set(self, key, value):
265 self.d[key] = value
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500266
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600267 def is_deploy_dir_image(self, p):
268 if os.path.isdir(p):
269 if not re.search('.qemuboot.conf$', '\n'.join(os.listdir(p)), re.M):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500270 logger.debug("Can't find required *.qemuboot.conf in %s" % p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600271 return False
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500272 if not any(map(lambda name: '-image-' in name, os.listdir(p))):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500273 logger.debug("Can't find *-image-* in %s" % p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600274 return False
275 return True
276 else:
277 return False
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500278
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600279 def check_arg_fstype(self, fst):
280 """Check and set FSTYPE"""
281 if fst not in self.fstypes + self.vmtypes:
282 logger.warn("Maybe unsupported FSTYPE: %s" % fst)
283 if not self.fstype or self.fstype == fst:
284 if fst == 'ramfs':
285 fst = 'cpio.gz'
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500286 if fst in ('tar.bz2', 'tar.gz'):
287 fst = 'nfs'
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600288 self.fstype = fst
289 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500290 raise RunQemuError("Conflicting: FSTYPE %s and %s" % (self.fstype, fst))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500291
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600292 def set_machine_deploy_dir(self, machine, deploy_dir_image):
293 """Set MACHINE and DEPLOY_DIR_IMAGE"""
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500294 logger.debug('MACHINE: %s' % machine)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600295 self.set("MACHINE", machine)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500296 logger.debug('DEPLOY_DIR_IMAGE: %s' % deploy_dir_image)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600297 self.set("DEPLOY_DIR_IMAGE", deploy_dir_image)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500298
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600299 def check_arg_nfs(self, p):
300 if os.path.isdir(p):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500301 self.rootfs = p
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600302 else:
303 m = re.match('(.*):(.*)', p)
304 self.nfs_server = m.group(1)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500305 self.rootfs = m.group(2)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600306 self.check_arg_fstype('nfs')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500307
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600308 def check_arg_path(self, p):
309 """
310 - Check whether it is <image>.qemuboot.conf or contains <image>.qemuboot.conf
311 - Check whether is a kernel file
312 - Check whether is a image file
313 - Check whether it is a nfs dir
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500314 - Check whether it is a OVMF flash file
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600315 """
316 if p.endswith('.qemuboot.conf'):
317 self.qemuboot = p
318 self.qbconfload = True
319 elif re.search('\.bin$', p) or re.search('bzImage', p) or \
320 re.search('zImage', p) or re.search('vmlinux', p) or \
321 re.search('fitImage', p) or re.search('uImage', p):
322 self.kernel = p
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500323 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 -0600324 self.rootfs = p
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500325 # Check filename against self.fstypes can hanlde <file>.cpio.gz,
326 # otherwise, its type would be "gz", which is incorrect.
327 fst = ""
328 for t in self.fstypes:
329 if p.endswith(t):
330 fst = t
331 break
332 if not fst:
333 m = re.search('.*\.(.*)$', self.rootfs)
334 if m:
335 fst = m.group(1)
336 if fst:
337 self.check_arg_fstype(fst)
338 qb = re.sub('\.' + fst + "$", '', self.rootfs)
339 qb = '%s%s' % (re.sub('\.rootfs$', '', qb), '.qemuboot.conf')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600340 if os.path.exists(qb):
341 self.qemuboot = qb
342 self.qbconfload = True
343 else:
344 logger.warn("%s doesn't exist" % qb)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600345 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500346 raise RunQemuError("Can't find FSTYPE from: %s" % p)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500347
348 elif os.path.isdir(p) or re.search(':', p) and re.search('/', p):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600349 if self.is_deploy_dir_image(p):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500350 logger.debug('DEPLOY_DIR_IMAGE: %s' % p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600351 self.set("DEPLOY_DIR_IMAGE", p)
352 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500353 logger.debug("Assuming %s is an nfs rootfs" % p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600354 self.check_arg_nfs(p)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500355 elif os.path.basename(p).startswith('ovmf'):
356 self.ovmf_bios.append(p)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600357 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500358 raise RunQemuError("Unknown path arg %s" % p)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500359
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600360 def check_arg_machine(self, arg):
361 """Check whether it is a machine"""
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500362 if self.get('MACHINE') == arg:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600363 return
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500364 elif self.get('MACHINE') and self.get('MACHINE') != arg:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500365 raise RunQemuError("Maybe conflicted MACHINE: %s vs %s" % (self.get('MACHINE'), arg))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500366 elif re.search('/', arg):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500367 raise RunQemuError("Unknown arg: %s" % arg)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500368
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500369 logger.debug('Assuming MACHINE = %s' % arg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500370
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600371 # if we're running under testimage, or similarly as a child
372 # of an existing bitbake invocation, we can't invoke bitbake
373 # to validate the MACHINE setting and must assume it's correct...
374 # FIXME: testimage.bbclass exports these two variables into env,
375 # are there other scenarios in which we need to support being
376 # invoked by bitbake?
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500377 deploy = self.get('DEPLOY_DIR_IMAGE')
378 bbchild = deploy and self.get('OE_TMPDIR')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600379 if bbchild:
380 self.set_machine_deploy_dir(arg, deploy)
381 return
382 # also check whether we're running under a sourced toolchain
383 # environment file
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500384 if self.get('OECORE_NATIVE_SYSROOT'):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600385 self.set("MACHINE", arg)
386 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500387
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600388 cmd = 'MACHINE=%s bitbake -e' % arg
389 logger.info('Running %s...' % cmd)
390 self.bitbake_e = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
391 # bitbake -e doesn't report invalid MACHINE as an error, so
392 # let's check DEPLOY_DIR_IMAGE to make sure that it is a valid
393 # MACHINE.
394 s = re.search('^DEPLOY_DIR_IMAGE="(.*)"', self.bitbake_e, re.M)
395 if s:
396 deploy_dir_image = s.group(1)
397 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500398 raise RunQemuError("bitbake -e %s" % self.bitbake_e)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600399 if self.is_deploy_dir_image(deploy_dir_image):
400 self.set_machine_deploy_dir(arg, deploy_dir_image)
401 else:
402 logger.error("%s not a directory valid DEPLOY_DIR_IMAGE" % deploy_dir_image)
403 self.set("MACHINE", arg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500404
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600405 def check_args(self):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500406 for debug in ("-d", "--debug"):
407 if debug in sys.argv:
408 logger.setLevel(logging.DEBUG)
409 sys.argv.remove(debug)
410
411 for quiet in ("-q", "--quiet"):
412 if quiet in sys.argv:
413 logger.setLevel(logging.ERROR)
414 sys.argv.remove(quiet)
415
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600416 unknown_arg = ""
417 for arg in sys.argv[1:]:
418 if arg in self.fstypes + self.vmtypes:
419 self.check_arg_fstype(arg)
420 elif arg == 'nographic':
421 self.qemu_opt_script += ' -nographic'
422 self.kernel_cmdline_script += ' console=ttyS0'
423 elif arg == 'serial':
424 self.kernel_cmdline_script += ' console=ttyS0'
425 self.serialstdio = True
426 elif arg == 'audio':
427 logger.info("Enabling audio in qemu")
428 logger.info("Please install sound drivers in linux host")
429 self.audio_enabled = True
430 elif arg == 'kvm':
431 self.kvm_enabled = True
432 elif arg == 'kvm-vhost':
433 self.vhost_enabled = True
434 elif arg == 'slirp':
435 self.slirp_enabled = True
436 elif arg == 'snapshot':
437 self.snapshot = True
438 elif arg == 'publicvnc':
439 self.qemu_opt_script += ' -vnc :0'
440 elif arg.startswith('tcpserial='):
441 self.tcpserial_portnum = arg[len('tcpserial='):]
442 elif arg.startswith('biosdir='):
443 self.custombiosdir = arg[len('biosdir='):]
444 elif arg.startswith('biosfilename='):
445 self.qemu_opt_script += ' -bios %s' % arg[len('biosfilename='):]
446 elif arg.startswith('qemuparams='):
447 self.qemu_opt_script += ' %s' % arg[len('qemuparams='):]
448 elif arg.startswith('bootparams='):
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500449 self.bootparams = arg[len('bootparams='):]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600450 elif os.path.exists(arg) or (re.search(':', arg) and re.search('/', arg)):
451 self.check_arg_path(os.path.abspath(arg))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500452 elif re.search(r'-image-|-image$', arg):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600453 # Lazy rootfs
454 self.rootfs = arg
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500455 elif arg.startswith('ovmf'):
456 self.ovmf_bios.append(arg)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600457 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500458 # At last, assume it is the MACHINE
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600459 if (not unknown_arg) or unknown_arg == arg:
460 unknown_arg = arg
461 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500462 raise RunQemuError("Can't handle two unknown args: %s %s\n"
463 "Try 'runqemu help' on how to use it" % \
464 (unknown_arg, arg))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600465 # Check to make sure it is a valid machine
466 if unknown_arg:
467 if self.get('MACHINE') == unknown_arg:
468 return
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500469 if self.get('DEPLOY_DIR_IMAGE'):
470 machine = os.path.basename(self.get('DEPLOY_DIR_IMAGE'))
471 if unknown_arg == machine:
472 self.set("MACHINE", machine)
473 return
474
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600475 self.check_arg_machine(unknown_arg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500476
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500477 if not (self.get('DEPLOY_DIR_IMAGE') or self.qbconfload):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500478 self.load_bitbake_env()
479 s = re.search('^DEPLOY_DIR_IMAGE="(.*)"', self.bitbake_e, re.M)
480 if s:
481 self.set("DEPLOY_DIR_IMAGE", s.group(1))
482
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600483 def check_kvm(self):
484 """Check kvm and kvm-host"""
485 if not (self.kvm_enabled or self.vhost_enabled):
486 self.qemu_opt_script += ' %s %s' % (self.get('QB_MACHINE'), self.get('QB_CPU'))
487 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500488
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600489 if not self.get('QB_CPU_KVM'):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500490 raise RunQemuError("QB_CPU_KVM is NULL, this board doesn't support kvm")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500491
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600492 self.qemu_opt_script += ' %s %s' % (self.get('QB_MACHINE'), self.get('QB_CPU_KVM'))
493 yocto_kvm_wiki = "https://wiki.yoctoproject.org/wiki/How_to_enable_KVM_for_Poky_qemu"
494 yocto_paravirt_kvm_wiki = "https://wiki.yoctoproject.org/wiki/Running_an_x86_Yocto_Linux_image_under_QEMU_KVM"
495 dev_kvm = '/dev/kvm'
496 dev_vhost = '/dev/vhost-net'
497 with open('/proc/cpuinfo', 'r') as f:
498 kvm_cap = re.search('vmx|svm', "".join(f.readlines()))
499 if not kvm_cap:
500 logger.error("You are trying to enable KVM on a cpu without VT support.")
501 logger.error("Remove kvm from the command-line, or refer:")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500502 raise RunQemuError(yocto_kvm_wiki)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500503
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600504 if not os.path.exists(dev_kvm):
505 logger.error("Missing KVM device. Have you inserted kvm modules?")
506 logger.error("For further help see:")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500507 raise RunQemuError(yocto_kvm_wiki)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500508
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600509 if os.access(dev_kvm, os.W_OK|os.R_OK):
510 self.qemu_opt_script += ' -enable-kvm'
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500511 if self.get('MACHINE') == "qemux86":
512 # Workaround for broken APIC window on pre 4.15 host kernels which causes boot hangs
513 # See YOCTO #12301
514 # On 64 bit we use x2apic
515 self.kernel_cmdline_script += " clocksource=kvm-clock hpet=disable noapic nolapic"
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600516 else:
517 logger.error("You have no read or write permission on /dev/kvm.")
518 logger.error("Please change the ownership of this file as described at:")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500519 raise RunQemuError(yocto_kvm_wiki)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500520
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600521 if self.vhost_enabled:
522 if not os.path.exists(dev_vhost):
523 logger.error("Missing virtio net device. Have you inserted vhost-net module?")
524 logger.error("For further help see:")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500525 raise RunQemuError(yocto_paravirt_kvm_wiki)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500526
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600527 if not os.access(dev_kvm, os.W_OK|os.R_OK):
528 logger.error("You have no read or write permission on /dev/vhost-net.")
529 logger.error("Please change the ownership of this file as described at:")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500530 raise RunQemuError(yocto_kvm_wiki)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500531
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600532 def check_fstype(self):
533 """Check and setup FSTYPE"""
534 if not self.fstype:
535 fstype = self.get('QB_DEFAULT_FSTYPE')
536 if fstype:
537 self.fstype = fstype
538 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500539 raise RunQemuError("FSTYPE is NULL!")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500540
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600541 def check_rootfs(self):
542 """Check and set rootfs"""
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500543
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500544 if self.fstype == "none":
545 return
546
547 if self.get('ROOTFS'):
548 if not self.rootfs:
549 self.rootfs = self.get('ROOTFS')
550 elif self.get('ROOTFS') != self.rootfs:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500551 raise RunQemuError("Maybe conflicted ROOTFS: %s vs %s" % (self.get('ROOTFS'), self.rootfs))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500552
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600553 if self.fstype == 'nfs':
554 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500555
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600556 if self.rootfs and not os.path.exists(self.rootfs):
557 # Lazy rootfs
558 self.rootfs = "%s/%s-%s.%s" % (self.get('DEPLOY_DIR_IMAGE'),
559 self.rootfs, self.get('MACHINE'),
560 self.fstype)
561 elif not self.rootfs:
562 cmd_name = '%s/%s*.%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_NAME'), self.fstype)
563 cmd_link = '%s/%s*.%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_LINK_NAME'), self.fstype)
564 cmds = (cmd_name, cmd_link)
565 self.rootfs = get_first_file(cmds)
566 if not self.rootfs:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500567 raise RunQemuError("Failed to find rootfs: %s or %s" % cmds)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500568
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600569 if not os.path.exists(self.rootfs):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500570 raise RunQemuError("Can't find rootfs: %s" % self.rootfs)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500571
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500572 def check_ovmf(self):
573 """Check and set full path for OVMF firmware and variable file(s)."""
574
575 for index, ovmf in enumerate(self.ovmf_bios):
576 if os.path.exists(ovmf):
577 continue
578 for suffix in ('qcow2', 'bin'):
579 path = '%s/%s.%s' % (self.get('DEPLOY_DIR_IMAGE'), ovmf, suffix)
580 if os.path.exists(path):
581 self.ovmf_bios[index] = path
582 break
583 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500584 raise RunQemuError("Can't find OVMF firmware: %s" % ovmf)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500585
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600586 def check_kernel(self):
587 """Check and set kernel, dtb"""
588 # The vm image doesn't need a kernel
589 if self.fstype in self.vmtypes:
590 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500591
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500592 # QB_DEFAULT_KERNEL is always a full file path
593 kernel_name = os.path.basename(self.get('QB_DEFAULT_KERNEL'))
594
595 # The user didn't want a kernel to be loaded
596 if kernel_name == "none":
597 return
598
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600599 deploy_dir_image = self.get('DEPLOY_DIR_IMAGE')
600 if not self.kernel:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500601 kernel_match_name = "%s/%s" % (deploy_dir_image, kernel_name)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600602 kernel_match_link = "%s/%s" % (deploy_dir_image, self.get('KERNEL_IMAGETYPE'))
603 kernel_startswith = "%s/%s*" % (deploy_dir_image, self.get('KERNEL_IMAGETYPE'))
604 cmds = (kernel_match_name, kernel_match_link, kernel_startswith)
605 self.kernel = get_first_file(cmds)
606 if not self.kernel:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500607 raise RunQemuError('KERNEL not found: %s, %s or %s' % cmds)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500608
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600609 if not os.path.exists(self.kernel):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500610 raise RunQemuError("KERNEL %s not found" % self.kernel)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500611
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600612 dtb = self.get('QB_DTB')
613 if dtb:
614 cmd_match = "%s/%s" % (deploy_dir_image, dtb)
615 cmd_startswith = "%s/%s*" % (deploy_dir_image, dtb)
616 cmd_wild = "%s/*.dtb" % deploy_dir_image
617 cmds = (cmd_match, cmd_startswith, cmd_wild)
618 self.dtb = get_first_file(cmds)
619 if not os.path.exists(self.dtb):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500620 raise RunQemuError('DTB not found: %s, %s or %s' % cmds)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500621
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600622 def check_biosdir(self):
623 """Check custombiosdir"""
624 if not self.custombiosdir:
625 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500626
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600627 biosdir = ""
628 biosdir_native = "%s/%s" % (self.get('STAGING_DIR_NATIVE'), self.custombiosdir)
629 biosdir_host = "%s/%s" % (self.get('STAGING_DIR_HOST'), self.custombiosdir)
630 for i in (self.custombiosdir, biosdir_native, biosdir_host):
631 if os.path.isdir(i):
632 biosdir = i
633 break
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500634
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600635 if biosdir:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500636 logger.debug("Assuming biosdir is: %s" % biosdir)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600637 self.qemu_opt_script += ' -L %s' % biosdir
638 else:
639 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 -0500640 raise RunQemuError("Invalid custombiosdir: %s" % self.custombiosdir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500641
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600642 def check_mem(self):
643 s = re.search('-m +([0-9]+)', self.qemu_opt_script)
644 if s:
645 self.set('QB_MEM', '-m %s' % s.group(1))
646 elif not self.get('QB_MEM'):
647 logger.info('QB_MEM is not set, use 512M by default')
648 self.set('QB_MEM', '-m 512')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500649
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600650 self.kernel_cmdline_script += ' mem=%s' % self.get('QB_MEM').replace('-m','').strip() + 'M'
651 self.qemu_opt_script += ' %s' % self.get('QB_MEM')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500652
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600653 def check_tcpserial(self):
654 if self.tcpserial_portnum:
655 if self.get('QB_TCPSERIAL_OPT'):
656 self.qemu_opt_script += ' ' + self.get('QB_TCPSERIAL_OPT').replace('@PORT@', self.tcpserial_portnum)
657 else:
658 self.qemu_opt_script += ' -serial tcp:127.0.0.1:%s' % self.tcpserial_portnum
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500659
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600660 def check_and_set(self):
661 """Check configs sanity and set when needed"""
662 self.validate_paths()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500663 if not self.slirp_enabled:
664 check_tun()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600665 # Check audio
666 if self.audio_enabled:
667 if not self.get('QB_AUDIO_DRV'):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500668 raise RunQemuError("QB_AUDIO_DRV is NULL, this board doesn't support audio")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600669 if not self.get('QB_AUDIO_OPT'):
670 logger.warn('QB_AUDIO_OPT is NULL, you may need define it to make audio work')
671 else:
672 self.qemu_opt_script += ' %s' % self.get('QB_AUDIO_OPT')
673 os.putenv('QEMU_AUDIO_DRV', self.get('QB_AUDIO_DRV'))
674 else:
675 os.putenv('QEMU_AUDIO_DRV', 'none')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500676
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600677 self.check_kvm()
678 self.check_fstype()
679 self.check_rootfs()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500680 self.check_ovmf()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600681 self.check_kernel()
682 self.check_biosdir()
683 self.check_mem()
684 self.check_tcpserial()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500685
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600686 def read_qemuboot(self):
687 if not self.qemuboot:
688 if self.get('DEPLOY_DIR_IMAGE'):
689 deploy_dir_image = self.get('DEPLOY_DIR_IMAGE')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600690 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500691 logger.warn("Can't find qemuboot conf file, DEPLOY_DIR_IMAGE is NULL!")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600692 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500693
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600694 if self.rootfs and not os.path.exists(self.rootfs):
695 # Lazy rootfs
696 machine = self.get('MACHINE')
697 if not machine:
698 machine = os.path.basename(deploy_dir_image)
699 self.qemuboot = "%s/%s-%s.qemuboot.conf" % (deploy_dir_image,
700 self.rootfs, machine)
701 else:
702 cmd = 'ls -t %s/*.qemuboot.conf' % deploy_dir_image
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500703 logger.debug('Running %s...' % cmd)
704 try:
705 qbs = subprocess.check_output(cmd, shell=True).decode('utf-8')
706 except subprocess.CalledProcessError as err:
707 raise RunQemuError(err)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600708 if qbs:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500709 for qb in qbs.split():
710 # Don't use initramfs when other choices unless fstype is ramfs
711 if '-initramfs-' in os.path.basename(qb) and self.fstype != 'cpio.gz':
712 continue
713 self.qemuboot = qb
714 break
715 if not self.qemuboot:
716 # Use the first one when no choice
717 self.qemuboot = qbs.split()[0]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600718 self.qbconfload = True
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500719
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600720 if not self.qemuboot:
721 # If we haven't found a .qemuboot.conf at this point it probably
722 # doesn't exist, continue without
723 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500724
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600725 if not os.path.exists(self.qemuboot):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500726 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 -0500727
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500728 logger.debug('CONFFILE: %s' % self.qemuboot)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500729
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600730 cf = configparser.ConfigParser()
731 cf.read(self.qemuboot)
732 for k, v in cf.items('config_bsp'):
733 k_upper = k.upper()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500734 if v.startswith("../"):
735 v = os.path.abspath(os.path.dirname(self.qemuboot) + "/" + v)
736 elif v == ".":
737 v = os.path.dirname(self.qemuboot)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600738 self.set(k_upper, v)
739
740 def validate_paths(self):
741 """Ensure all relevant path variables are set"""
742 # When we're started with a *.qemuboot.conf arg assume that image
743 # artefacts are relative to that file, rather than in whatever
744 # directory DEPLOY_DIR_IMAGE in the conf file points to.
745 if self.qbconfload:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500746 imgdir = os.path.realpath(os.path.dirname(self.qemuboot))
747 if imgdir != os.path.realpath(self.get('DEPLOY_DIR_IMAGE')):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600748 logger.info('Setting DEPLOY_DIR_IMAGE to folder containing %s (%s)' % (self.qemuboot, imgdir))
749 self.set('DEPLOY_DIR_IMAGE', imgdir)
750
751 # If the STAGING_*_NATIVE directories from the config file don't exist
752 # and we're in a sourced OE build directory try to extract the paths
753 # from `bitbake -e`
754 havenative = os.path.exists(self.get('STAGING_DIR_NATIVE')) and \
755 os.path.exists(self.get('STAGING_BINDIR_NATIVE'))
756
757 if not havenative:
758 if not self.bitbake_e:
759 self.load_bitbake_env()
760
761 if self.bitbake_e:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500762 native_vars = ['STAGING_DIR_NATIVE']
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600763 for nv in native_vars:
764 s = re.search('^%s="(.*)"' % nv, self.bitbake_e, re.M)
765 if s and s.group(1) != self.get(nv):
766 logger.info('Overriding conf file setting of %s to %s from Bitbake environment' % (nv, s.group(1)))
767 self.set(nv, s.group(1))
768 else:
769 # when we're invoked from a running bitbake instance we won't
770 # be able to call `bitbake -e`, then try:
771 # - get OE_TMPDIR from environment and guess paths based on it
772 # - get OECORE_NATIVE_SYSROOT from environment (for sdk)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500773 tmpdir = self.get('OE_TMPDIR')
774 oecore_native_sysroot = self.get('OECORE_NATIVE_SYSROOT')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600775 if tmpdir:
776 logger.info('Setting STAGING_DIR_NATIVE and STAGING_BINDIR_NATIVE relative to OE_TMPDIR (%s)' % tmpdir)
777 hostos, _, _, _, machine = os.uname()
778 buildsys = '%s-%s' % (machine, hostos.lower())
779 staging_dir_native = '%s/sysroots/%s' % (tmpdir, buildsys)
780 self.set('STAGING_DIR_NATIVE', staging_dir_native)
781 elif oecore_native_sysroot:
782 logger.info('Setting STAGING_DIR_NATIVE to OECORE_NATIVE_SYSROOT (%s)' % oecore_native_sysroot)
783 self.set('STAGING_DIR_NATIVE', oecore_native_sysroot)
784 if self.get('STAGING_DIR_NATIVE'):
785 # we have to assume that STAGING_BINDIR_NATIVE is at usr/bin
786 staging_bindir_native = '%s/usr/bin' % self.get('STAGING_DIR_NATIVE')
787 logger.info('Setting STAGING_BINDIR_NATIVE to %s' % staging_bindir_native)
788 self.set('STAGING_BINDIR_NATIVE', '%s/usr/bin' % self.get('STAGING_DIR_NATIVE'))
789
790 def print_config(self):
791 logger.info('Continuing with the following parameters:\n')
792 if not self.fstype in self.vmtypes:
793 print('KERNEL: [%s]' % self.kernel)
794 if self.dtb:
795 print('DTB: [%s]' % self.dtb)
796 print('MACHINE: [%s]' % self.get('MACHINE'))
797 print('FSTYPE: [%s]' % self.fstype)
798 if self.fstype == 'nfs':
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500799 print('NFS_DIR: [%s]' % self.rootfs)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600800 else:
801 print('ROOTFS: [%s]' % self.rootfs)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500802 if self.ovmf_bios:
803 print('OVMF: %s' % self.ovmf_bios)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600804 print('CONFFILE: [%s]' % self.qemuboot)
805 print('')
806
807 def setup_nfs(self):
808 if not self.nfs_server:
809 if self.slirp_enabled:
810 self.nfs_server = '10.0.2.2'
811 else:
812 self.nfs_server = '192.168.7.1'
813
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500814 # Figure out a new nfs_instance to allow multiple qemus running.
815 # CentOS 7.1's ps doesn't print full command line without "ww"
816 # when invoke by subprocess.Popen().
817 cmd = "ps auxww"
818 ps = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
819 pattern = '/bin/unfsd .* -i .*\.pid -e .*/exports([0-9]+) '
820 all_instances = re.findall(pattern, ps, re.M)
821 if all_instances:
822 all_instances.sort(key=int)
823 self.nfs_instance = int(all_instances.pop()) + 1
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600824
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500825 nfsd_port = 3049 + 2 * self.nfs_instance
826 mountd_port = 3048 + 2 * self.nfs_instance
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600827
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500828 # Export vars for runqemu-export-rootfs
829 export_dict = {
830 'NFS_INSTANCE': self.nfs_instance,
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500831 'NFSD_PORT': nfsd_port,
832 'MOUNTD_PORT': mountd_port,
833 }
834 for k, v in export_dict.items():
835 # Use '%s' since they are integers
836 os.putenv(k, '%s' % v)
837
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500838 self.unfs_opts="nfsvers=3,port=%s,udp,mountport=%s" % (nfsd_port, mountd_port)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600839
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500840 # Extract .tar.bz2 or .tar.bz if no nfs dir
841 if not (self.rootfs and os.path.isdir(self.rootfs)):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600842 src_prefix = '%s/%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_LINK_NAME'))
843 dest = "%s-nfsroot" % src_prefix
844 if os.path.exists('%s.pseudo_state' % dest):
845 logger.info('Use %s as NFS_DIR' % dest)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500846 self.rootfs = dest
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600847 else:
848 src = ""
849 src1 = '%s.tar.bz2' % src_prefix
850 src2 = '%s.tar.gz' % src_prefix
851 if os.path.exists(src1):
852 src = src1
853 elif os.path.exists(src2):
854 src = src2
855 if not src:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500856 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 -0600857 logger.info('NFS_DIR not found, extracting %s to %s' % (src, dest))
858 cmd = 'runqemu-extract-sdk %s %s' % (src, dest)
859 logger.info('Running %s...' % cmd)
860 if subprocess.call(cmd, shell=True) != 0:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500861 raise RunQemuError('Failed to run %s' % cmd)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600862 self.clean_nfs_dir = True
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500863 self.rootfs = dest
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600864
865 # Start the userspace NFS server
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500866 cmd = 'runqemu-export-rootfs start %s' % self.rootfs
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600867 logger.info('Running %s...' % cmd)
868 if subprocess.call(cmd, shell=True) != 0:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500869 raise RunQemuError('Failed to run %s' % cmd)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600870
871 self.nfs_running = True
872
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600873 def setup_slirp(self):
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500874 """Setup user networking"""
875
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600876 if self.fstype == 'nfs':
877 self.setup_nfs()
878 self.kernel_cmdline_script += ' ip=dhcp'
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500879 # Port mapping
880 hostfwd = ",hostfwd=tcp::2222-:22,hostfwd=tcp::2323-:23"
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500881 qb_slirp_opt_default = "-netdev user,id=net0%s,tftp=%s" % (hostfwd, self.get('DEPLOY_DIR_IMAGE'))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500882 qb_slirp_opt = self.get('QB_SLIRP_OPT') or qb_slirp_opt_default
883 # Figure out the port
884 ports = re.findall('hostfwd=[^-]*:([0-9]+)-[^,-]*', qb_slirp_opt)
885 ports = [int(i) for i in ports]
886 mac = 2
887 # Find a free port to avoid conflicts
888 for p in ports[:]:
889 p_new = p
890 while not check_free_port('localhost', p_new):
891 p_new += 1
892 mac += 1
893 while p_new in ports:
894 p_new += 1
895 mac += 1
896 if p != p_new:
897 ports.append(p_new)
898 qb_slirp_opt = re.sub(':%s-' % p, ':%s-' % p_new, qb_slirp_opt)
899 logger.info("Port forward changed: %s -> %s" % (p, p_new))
900 mac = "%s%02x" % (self.mac_slirp, mac)
901 self.set('NETWORK_CMD', '%s %s' % (self.network_device.replace('@MAC@', mac), qb_slirp_opt))
902 # Print out port foward
903 hostfwd = re.findall('(hostfwd=[^,]*)', qb_slirp_opt)
904 if hostfwd:
905 logger.info('Port forward: %s' % ' '.join(hostfwd))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600906
907 def setup_tap(self):
908 """Setup tap"""
909
910 # This file is created when runqemu-gen-tapdevs creates a bank of tap
911 # devices, indicating that the user should not bring up new ones using
912 # sudo.
913 nosudo_flag = '/etc/runqemu-nosudo'
914 self.qemuifup = shutil.which('runqemu-ifup')
915 self.qemuifdown = shutil.which('runqemu-ifdown')
916 ip = shutil.which('ip')
917 lockdir = "/tmp/qemu-tap-locks"
918
919 if not (self.qemuifup and self.qemuifdown and ip):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500920 logger.error("runqemu-ifup: %s" % self.qemuifup)
921 logger.error("runqemu-ifdown: %s" % self.qemuifdown)
922 logger.error("ip: %s" % ip)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600923 raise OEPathError("runqemu-ifup, runqemu-ifdown or ip not found")
924
925 if not os.path.exists(lockdir):
926 # There might be a race issue when multi runqemu processess are
927 # running at the same time.
928 try:
929 os.mkdir(lockdir)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500930 os.chmod(lockdir, 0o777)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600931 except FileExistsError:
932 pass
933
934 cmd = '%s link' % ip
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500935 logger.debug('Running %s...' % cmd)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600936 ip_link = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
937 # Matches line like: 6: tap0: <foo>
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500938 possibles = re.findall('^[0-9]+: +(tap[0-9]+): <.*', ip_link, re.M)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600939 tap = ""
940 for p in possibles:
941 lockfile = os.path.join(lockdir, p)
942 if os.path.exists('%s.skip' % lockfile):
943 logger.info('Found %s.skip, skipping %s' % (lockfile, p))
944 continue
945 self.lock = lockfile + '.lock'
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500946 if self.acquire_lock(error=False):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600947 tap = p
948 logger.info("Using preconfigured tap device %s" % tap)
949 logger.info("If this is not intended, touch %s.skip to make runqemu skip %s." %(lockfile, tap))
950 break
951
952 if not tap:
953 if os.path.exists(nosudo_flag):
954 logger.error("Error: There are no available tap devices to use for networking,")
955 logger.error("and I see %s exists, so I am not going to try creating" % nosudo_flag)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500956 raise RunQemuError("a new one with sudo.")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600957
958 gid = os.getgid()
959 uid = os.getuid()
960 logger.info("Setting up tap interface under sudo")
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500961 cmd = 'sudo %s %s %s %s' % (self.qemuifup, uid, gid, self.bindir_native)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600962 tap = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8').rstrip('\n')
963 lockfile = os.path.join(lockdir, tap)
964 self.lock = lockfile + '.lock'
965 self.acquire_lock()
966 self.cleantap = True
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500967 logger.debug('Created tap: %s' % tap)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600968
969 if not tap:
970 logger.error("Failed to setup tap device. Run runqemu-gen-tapdevs to manually create.")
971 return 1
972 self.tap = tap
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500973 tapnum = int(tap[3:])
974 gateway = tapnum * 2 + 1
975 client = gateway + 1
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600976 if self.fstype == 'nfs':
977 self.setup_nfs()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500978 netconf = "192.168.7.%s::192.168.7.%s:255.255.255.0" % (client, gateway)
979 logger.info("Network configuration: %s", netconf)
980 self.kernel_cmdline_script += " ip=%s" % netconf
981 mac = "%s%02x" % (self.mac_tap, client)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600982 qb_tap_opt = self.get('QB_TAP_OPT')
983 if qb_tap_opt:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500984 qemu_tap_opt = qb_tap_opt.replace('@TAP@', tap)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600985 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500986 qemu_tap_opt = "-netdev tap,id=net0,ifname=%s,script=no,downscript=no" % (self.tap)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600987
988 if self.vhost_enabled:
989 qemu_tap_opt += ',vhost=on'
990
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500991 self.set('NETWORK_CMD', '%s %s' % (self.network_device.replace('@MAC@', mac), qemu_tap_opt))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600992
993 def setup_network(self):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500994 if self.get('QB_NET') == 'none':
995 return
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500996 if sys.stdin.isatty():
997 self.saved_stty = subprocess.check_output("stty -g", shell=True).decode('utf-8')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500998 self.network_device = self.get('QB_NETWORK_DEVICE') or self.network_device
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600999 if self.slirp_enabled:
1000 self.setup_slirp()
1001 else:
1002 self.setup_tap()
1003
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001004 def setup_rootfs(self):
1005 if self.get('QB_ROOTFS') == 'none':
1006 return
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001007 if 'wic.' in self.fstype:
1008 self.fstype = self.fstype[4:]
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001009 rootfs_format = self.fstype if self.fstype in ('vmdk', 'qcow2', 'vdi') else 'raw'
1010
1011 qb_rootfs_opt = self.get('QB_ROOTFS_OPT')
1012 if qb_rootfs_opt:
1013 self.rootfs_options = qb_rootfs_opt.replace('@ROOTFS@', self.rootfs)
1014 else:
1015 self.rootfs_options = '-drive file=%s,if=virtio,format=%s' % (self.rootfs, rootfs_format)
1016
1017 if self.fstype in ('cpio.gz', 'cpio'):
1018 self.kernel_cmdline = 'root=/dev/ram0 rw debugshell'
1019 self.rootfs_options = '-initrd %s' % self.rootfs
1020 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001021 vm_drive = ''
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001022 if self.fstype in self.vmtypes:
1023 if self.fstype == 'iso':
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001024 vm_drive = '-drive file=%s,if=virtio,media=cdrom' % self.rootfs
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001025 elif self.get('QB_DRIVE_TYPE'):
1026 drive_type = self.get('QB_DRIVE_TYPE')
1027 if drive_type.startswith("/dev/sd"):
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001028 logger.info('Using scsi drive')
1029 vm_drive = '-drive if=none,id=hd,file=%s,format=%s -device virtio-scsi-pci,id=scsi -device scsi-hd,drive=hd' \
1030 % (self.rootfs, rootfs_format)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001031 elif drive_type.startswith("/dev/hd"):
Brad Bishop37a0e4d2017-12-04 01:01:44 -05001032 logger.info('Using ide drive')
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001033 vm_drive = "-drive file=%s,format=%s" % (self.rootfs, rootfs_format)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001034 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001035 # virtio might have been selected explicitly (just use it), or
1036 # is used as fallback (then warn about that).
1037 if not drive_type.startswith("/dev/vd"):
1038 logger.warn("Unknown QB_DRIVE_TYPE: %s" % drive_type)
1039 logger.warn("Failed to figure out drive type, consider define or fix QB_DRIVE_TYPE")
1040 logger.warn('Trying to use virtio block drive')
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001041 vm_drive = '-drive if=virtio,file=%s,format=%s' % (self.rootfs, rootfs_format)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001042
1043 # All branches above set vm_drive.
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001044 self.rootfs_options = '%s -no-reboot' % vm_drive
1045 self.kernel_cmdline = 'root=%s rw highres=off' % (self.get('QB_KERNEL_ROOT'))
1046
1047 if self.fstype == 'nfs':
1048 self.rootfs_options = ''
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001049 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 -06001050 self.kernel_cmdline = 'root=%s rw highres=off' % k_root
1051
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001052 if self.fstype == 'none':
1053 self.rootfs_options = ''
1054
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001055 self.set('ROOTFS_OPTIONS', self.rootfs_options)
1056
1057 def guess_qb_system(self):
1058 """attempt to determine the appropriate qemu-system binary"""
1059 mach = self.get('MACHINE')
1060 if not mach:
1061 search = '.*(qemux86-64|qemux86|qemuarm64|qemuarm|qemumips64|qemumips64el|qemumipsel|qemumips|qemuppc).*'
1062 if self.rootfs:
1063 match = re.match(search, self.rootfs)
1064 if match:
1065 mach = match.group(1)
1066 elif self.kernel:
1067 match = re.match(search, self.kernel)
1068 if match:
1069 mach = match.group(1)
1070
1071 if not mach:
1072 return None
1073
1074 if mach == 'qemuarm':
1075 qbsys = 'arm'
1076 elif mach == 'qemuarm64':
1077 qbsys = 'aarch64'
1078 elif mach == 'qemux86':
1079 qbsys = 'i386'
1080 elif mach == 'qemux86-64':
1081 qbsys = 'x86_64'
1082 elif mach == 'qemuppc':
1083 qbsys = 'ppc'
1084 elif mach == 'qemumips':
1085 qbsys = 'mips'
1086 elif mach == 'qemumips64':
1087 qbsys = 'mips64'
1088 elif mach == 'qemumipsel':
1089 qbsys = 'mipsel'
1090 elif mach == 'qemumips64el':
1091 qbsys = 'mips64el'
1092
1093 return 'qemu-system-%s' % qbsys
1094
1095 def setup_final(self):
1096 qemu_system = self.get('QB_SYSTEM_NAME')
1097 if not qemu_system:
1098 qemu_system = self.guess_qb_system()
1099 if not qemu_system:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001100 raise RunQemuError("Failed to boot, QB_SYSTEM_NAME is NULL!")
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001101
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001102 qemu_bin = '%s/%s' % (self.bindir_native, qemu_system)
1103
1104 # It is possible to have qemu-native in ASSUME_PROVIDED, and it won't
1105 # find QEMU in sysroot, it needs to use host's qemu.
1106 if not os.path.exists(qemu_bin):
1107 logger.info("QEMU binary not found in %s, trying host's QEMU" % qemu_bin)
1108 for path in (os.environ['PATH'] or '').split(':'):
1109 qemu_bin_tmp = os.path.join(path, qemu_system)
1110 logger.info("Trying: %s" % qemu_bin_tmp)
1111 if os.path.exists(qemu_bin_tmp):
1112 qemu_bin = qemu_bin_tmp
1113 if not os.path.isabs(qemu_bin):
1114 qemu_bin = os.path.abspath(qemu_bin)
1115 logger.info("Using host's QEMU: %s" % qemu_bin)
1116 break
1117
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001118 if not os.access(qemu_bin, os.X_OK):
1119 raise OEPathError("No QEMU binary '%s' could be found" % qemu_bin)
1120
1121 check_libgl(qemu_bin)
1122
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001123 self.qemu_opt = "%s %s %s %s" % (qemu_bin, self.get('NETWORK_CMD'), self.get('ROOTFS_OPTIONS'), self.get('QB_OPT_APPEND'))
1124
1125 for ovmf in self.ovmf_bios:
1126 format = ovmf.rsplit('.', 1)[-1]
1127 self.qemu_opt += ' -drive if=pflash,format=%s,file=%s' % (format, ovmf)
1128 if self.ovmf_bios:
1129 # OVMF only supports normal VGA, i.e. we need to override a -vga vmware
1130 # that gets added for example for normal qemux86.
1131 self.qemu_opt += ' -vga std'
1132
1133 self.qemu_opt += ' ' + self.qemu_opt_script
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001134
1135 if self.snapshot:
1136 self.qemu_opt += " -snapshot"
1137
1138 if self.serialstdio:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001139 if sys.stdin.isatty():
1140 subprocess.check_call("stty intr ^]", shell=True)
1141 logger.info("Interrupt character is '^]'")
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001142
1143 first_serial = ""
1144 if not re.search("-nographic", self.qemu_opt):
1145 first_serial = "-serial mon:vc"
1146 # We always want a ttyS1. Since qemu by default adds a serial
1147 # port when nodefaults is not specified, it seems that all that
1148 # would be needed is to make sure a "-serial" is there. However,
1149 # it appears that when "-serial" is specified, it ignores the
1150 # default serial port that is normally added. So here we make
1151 # sure to add two -serial if there are none. And only one if
1152 # there is one -serial already.
1153 serial_num = len(re.findall("-serial", self.qemu_opt))
1154 if serial_num == 0:
1155 self.qemu_opt += " %s %s" % (first_serial, self.get("QB_SERIAL_OPT"))
1156 elif serial_num == 1:
1157 self.qemu_opt += " %s" % self.get("QB_SERIAL_OPT")
1158
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001159 # We always wants ttyS0 and ttyS1 in qemu machines (see SERIAL_CONSOLES),
1160 # if not serial or serialtcp options was specified only ttyS0 is created
1161 # and sysvinit shows an error trying to enable ttyS1:
1162 # INIT: Id "S1" respawning too fast: disabled for 5 minutes
1163 serial_num = len(re.findall("-serial", self.qemu_opt))
1164 if serial_num == 0:
1165 if re.search("-nographic", self.qemu_opt):
1166 self.qemu_opt += " -serial mon:stdio -serial null"
1167 else:
1168 self.qemu_opt += " -serial mon:vc -serial null"
1169
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001170 def start_qemu(self):
1171 if self.kernel:
Brad Bishop37a0e4d2017-12-04 01:01:44 -05001172 kernel_opts = "-kernel %s -append '%s %s %s %s'" % (self.kernel, self.kernel_cmdline,
1173 self.kernel_cmdline_script, self.get('QB_KERNEL_CMDLINE_APPEND'),
1174 self.bootparams)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001175 if self.dtb:
1176 kernel_opts += " -dtb %s" % self.dtb
1177 else:
1178 kernel_opts = ""
1179 cmd = "%s %s" % (self.qemu_opt, kernel_opts)
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001180 logger.info('Running %s\n' % cmd)
1181 process = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)
1182 if process.wait():
1183 logger.error("Failed to run qemu: %s", process.stderr.read().decode())
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001184
1185 def cleanup(self):
1186 if self.cleantap:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001187 cmd = 'sudo %s %s %s' % (self.qemuifdown, self.tap, self.bindir_native)
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001188 logger.debug('Running %s' % cmd)
1189 subprocess.check_call(cmd, shell=True)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001190 if self.lock_descriptor:
1191 logger.info("Releasing lockfile for tap device '%s'" % self.tap)
1192 self.release_lock()
1193
1194 if self.nfs_running:
1195 logger.info("Shutting down the userspace NFS server...")
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001196 cmd = "runqemu-export-rootfs stop %s" % self.rootfs
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001197 logger.debug('Running %s' % cmd)
1198 subprocess.check_call(cmd, shell=True)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001199
1200 if self.saved_stty:
1201 cmd = "stty %s" % self.saved_stty
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001202 subprocess.check_call(cmd, shell=True)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001203
1204 if self.clean_nfs_dir:
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001205 logger.info('Removing %s' % self.rootfs)
1206 shutil.rmtree(self.rootfs)
1207 shutil.rmtree('%s.pseudo_state' % self.rootfs)
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001208
1209 def load_bitbake_env(self, mach=None):
1210 if self.bitbake_e:
1211 return
1212
1213 bitbake = shutil.which('bitbake')
1214 if not bitbake:
1215 return
1216
1217 if not mach:
1218 mach = self.get('MACHINE')
1219
1220 if mach:
1221 cmd = 'MACHINE=%s bitbake -e' % mach
1222 else:
1223 cmd = 'bitbake -e'
1224
1225 logger.info('Running %s...' % cmd)
1226 try:
1227 self.bitbake_e = subprocess.check_output(cmd, shell=True).decode('utf-8')
1228 except subprocess.CalledProcessError as err:
1229 self.bitbake_e = ''
1230 logger.warn("Couldn't run 'bitbake -e' to gather environment information:\n%s" % err.output.decode('utf-8'))
1231
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001232 def validate_combos(self):
1233 if (self.fstype in self.vmtypes) and self.kernel:
1234 raise RunQemuError("%s doesn't need kernel %s!" % (self.fstype, self.kernel))
1235
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001236 @property
1237 def bindir_native(self):
1238 result = self.get('STAGING_BINDIR_NATIVE')
1239 if result and os.path.exists(result):
1240 return result
1241
1242 cmd = 'bitbake qemu-helper-native -e'
1243 logger.info('Running %s...' % cmd)
1244 out = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
1245 out = out.stdout.read().decode('utf-8')
1246
1247 match = re.search('^STAGING_BINDIR_NATIVE="(.*)"', out, re.M)
1248 if match:
1249 result = match.group(1)
1250 if os.path.exists(result):
1251 self.set('STAGING_BINDIR_NATIVE', result)
1252 return result
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001253 raise RunQemuError("Native sysroot directory %s doesn't exist" % result)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001254 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001255 raise RunQemuError("Can't find STAGING_BINDIR_NATIVE in '%s' output" % cmd)
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001256
1257
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001258def main():
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001259 if "help" in sys.argv or '-h' in sys.argv or '--help' in sys.argv:
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001260 print_usage()
1261 return 0
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001262 try:
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001263 config = BaseConfig()
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001264 config.check_args()
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001265 config.read_qemuboot()
1266 config.check_and_set()
1267 # Check whether the combos is valid or not
1268 config.validate_combos()
1269 config.print_config()
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001270 config.setup_network()
Brad Bishop6e60e8b2018-02-01 10:27:11 -05001271 config.setup_rootfs()
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001272 config.setup_final()
1273 config.start_qemu()
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001274 except RunQemuError as err:
1275 logger.error(err)
1276 return 1
1277 except Exception as err:
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001278 import traceback
1279 traceback.print_exc()
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001280 return 1
1281 finally:
1282 print("Cleanup")
1283 config.cleanup()
1284
1285if __name__ == "__main__":
1286 sys.exit(main())