blob: dbe17abfc586da8ca1670d46c731dc6575f0c848 [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
Patrick Williamsc0f7c042017-02-23 20:41:17 -060031class OEPathError(Exception):
32 """Custom Exception to give better guidance on missing binaries"""
33 def __init__(self, message):
34 self.message = "In order for this script to dynamically infer paths\n \
35kernels or filesystem images, you either need bitbake in your PATH\n \
36or to source oe-init-build-env before running this script.\n\n \
37Dynamic path inference can be avoided by passing a *.qemuboot.conf to\n \
38runqemu, i.e. `runqemu /path/to/my-image-name.qemuboot.conf`\n\n %s" % message
39
40
41def create_logger():
42 logger = logging.getLogger('runqemu')
43 logger.setLevel(logging.INFO)
44
45 # create console handler and set level to debug
46 ch = logging.StreamHandler()
47 ch.setLevel(logging.INFO)
48
49 # create formatter
50 formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
51
52 # add formatter to ch
53 ch.setFormatter(formatter)
54
55 # add ch to logger
56 logger.addHandler(ch)
57
58 return logger
59
60logger = create_logger()
61
62def print_usage():
63 print("""
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050064Usage: you can run this script with any valid combination
65of the following environment variables (in any order):
66 KERNEL - the kernel image file to use
67 ROOTFS - the rootfs image file or nfsroot directory to use
68 MACHINE - the machine name (optional, autodetected from KERNEL filename if unspecified)
69 Simplified QEMU command-line options can be passed with:
Patrick Williamsc0f7c042017-02-23 20:41:17 -060070 nographic - disable video console
71 serial - enable a serial console on /dev/ttyS0
72 slirp - enable user networking, no root privileges is required
73 kvm - enable KVM when running x86/x86_64 (VT-capable CPU required)
74 kvm-vhost - enable KVM with vhost when running x86/x86_64 (VT-capable CPU required)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050075 publicvnc - enable a VNC server open to all hosts
Patrick Williamsc0f7c042017-02-23 20:41:17 -060076 audio - enable audio
77 tcpserial=<port> - specify tcp serial port number
78 biosdir=<dir> - specify custom bios dir
79 biosfilename=<filename> - specify bios filename
80 qemuparams=<xyz> - specify custom parameters to QEMU
81 bootparams=<xyz> - specify custom kernel parameters during boot
82 help: print this text
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050083
84Examples:
Patrick Williamsc0f7c042017-02-23 20:41:17 -060085 runqemu qemuarm
86 runqemu tmp/deploy/images/qemuarm
87 runqemu tmp/deploy/images/qemux86/.qemuboot.conf
88 runqemu qemux86-64 core-image-sato ext4
89 runqemu qemux86-64 wic-image-minimal wic
90 runqemu path/to/bzImage-qemux86.bin path/to/nfsrootdir/ serial
91 runqemu qemux86 iso/hddimg/vmdk/qcow2/vdi/ramfs/cpio.gz...
92 runqemu qemux86 qemuparams="-m 256"
93 runqemu qemux86 bootparams="psplash=false"
94 runqemu path/to/<image>-<machine>.vmdk
95 runqemu path/to/<image>-<machine>.wic
96""")
Patrick Williamsc124f4f2015-09-15 14:41:29 -050097
Patrick Williamsc0f7c042017-02-23 20:41:17 -060098def check_tun():
99 """Check /dev/net/run"""
100 dev_tun = '/dev/net/tun'
101 if not os.path.exists(dev_tun):
102 raise Exception("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 -0500103
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600104 if not os.access(dev_tun, os.W_OK):
105 raise Exception("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 -0500106
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600107def check_libgl(qemu_bin):
108 cmd = 'ldd %s' % qemu_bin
109 logger.info('Running %s...' % cmd)
110 need_gl = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
111 if re.search('libGLU', need_gl):
112 # We can't run without a libGL.so
113 libgl = False
114 check_files = (('/usr/lib/libGL.so', '/usr/lib/libGLU.so'), \
115 ('/usr/lib64/libGL.so', '/usr/lib64/libGLU.so'), \
116 ('/usr/lib/*-linux-gnu/libGL.so', '/usr/lib/*-linux-gnu/libGLU.so'))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500117
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600118 for (f1, f2) in check_files:
119 if re.search('\*', f1):
120 for g1 in glob.glob(f1):
121 if libgl:
122 break
123 if os.path.exists(g1):
124 for g2 in glob.glob(f2):
125 if os.path.exists(g2):
126 libgl = True
127 break
128 if libgl:
129 break
130 else:
131 if os.path.exists(f1) and os.path.exists(f2):
132 libgl = True
133 break
134 if not libgl:
135 logger.error("You need libGL.so and libGLU.so to exist in your library path to run the QEMU emulator.")
136 logger.error("Ubuntu package names are: libgl1-mesa-dev and libglu1-mesa-dev.")
137 logger.error("Fedora package names are: mesa-libGL-devel mesa-libGLU-devel.")
138 raise Exception('%s requires libGLU, but not found' % qemu_bin)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500139
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600140def get_first_file(cmds):
141 """Return first file found in wildcard cmds"""
142 for cmd in cmds:
143 all_files = glob.glob(cmd)
144 if all_files:
145 for f in all_files:
146 if not os.path.isdir(f):
147 return f
148 return ''
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500149
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600150class BaseConfig(object):
151 def __init__(self):
152 # Vars can be merged with .qemuboot.conf, use a dict to manage them.
153 self.d = {
154 'MACHINE': '',
155 'DEPLOY_DIR_IMAGE': '',
156 'QB_KERNEL_ROOT': '/dev/vda',
157 }
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500158
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600159 self.qemu_opt = ''
160 self.qemu_opt_script = ''
161 self.nfs_dir = ''
162 self.clean_nfs_dir = False
163 self.nfs_server = ''
164 self.rootfs = ''
165 self.qemuboot = ''
166 self.qbconfload = False
167 self.kernel = ''
168 self.kernel_cmdline = ''
169 self.kernel_cmdline_script = ''
170 self.dtb = ''
171 self.fstype = ''
172 self.kvm_enabled = False
173 self.vhost_enabled = False
174 self.slirp_enabled = False
175 self.nfs_instance = 0
176 self.nfs_running = False
177 self.serialstdio = False
178 self.cleantap = False
179 self.saved_stty = ''
180 self.audio_enabled = False
181 self.tcpserial_portnum = ''
182 self.custombiosdir = ''
183 self.lock = ''
184 self.lock_descriptor = ''
185 self.bitbake_e = ''
186 self.snapshot = False
187 self.fstypes = ('ext2', 'ext3', 'ext4', 'jffs2', 'nfs', 'btrfs', 'cpio.gz', 'cpio', 'ramfs')
188 self.vmtypes = ('hddimg', 'hdddirect', 'wic', 'vmdk', 'qcow2', 'vdi', 'iso')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500189
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600190 def acquire_lock(self):
191 logger.info("Acquiring lockfile %s..." % self.lock)
192 try:
193 self.lock_descriptor = open(self.lock, 'w')
194 fcntl.flock(self.lock_descriptor, fcntl.LOCK_EX|fcntl.LOCK_NB)
195 except Exception as e:
196 logger.info("Acquiring lockfile %s failed: %s" % (self.lock, e))
197 if self.lock_descriptor:
198 self.lock_descriptor.close()
199 return False
200 return True
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500201
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600202 def release_lock(self):
203 fcntl.flock(self.lock_descriptor, fcntl.LOCK_UN)
204 self.lock_descriptor.close()
205 os.remove(self.lock)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500206
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600207 def get(self, key):
208 if key in self.d:
209 return self.d.get(key)
210 else:
211 return ''
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500212
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600213 def set(self, key, value):
214 self.d[key] = value
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500215
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600216 def is_deploy_dir_image(self, p):
217 if os.path.isdir(p):
218 if not re.search('.qemuboot.conf$', '\n'.join(os.listdir(p)), re.M):
219 logger.info("Can't find required *.qemuboot.conf in %s" % p)
220 return False
221 if not re.search('-image-', '\n'.join(os.listdir(p))):
222 logger.info("Can't find *-image-* in %s" % p)
223 return False
224 return True
225 else:
226 return False
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500227
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600228 def check_arg_fstype(self, fst):
229 """Check and set FSTYPE"""
230 if fst not in self.fstypes + self.vmtypes:
231 logger.warn("Maybe unsupported FSTYPE: %s" % fst)
232 if not self.fstype or self.fstype == fst:
233 if fst == 'ramfs':
234 fst = 'cpio.gz'
235 self.fstype = fst
236 else:
237 raise Exception("Conflicting: FSTYPE %s and %s" % (self.fstype, fst))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500238
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600239 def set_machine_deploy_dir(self, machine, deploy_dir_image):
240 """Set MACHINE and DEPLOY_DIR_IMAGE"""
241 logger.info('MACHINE: %s' % machine)
242 self.set("MACHINE", machine)
243 logger.info('DEPLOY_DIR_IMAGE: %s' % deploy_dir_image)
244 self.set("DEPLOY_DIR_IMAGE", deploy_dir_image)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500245
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600246 def check_arg_nfs(self, p):
247 if os.path.isdir(p):
248 self.nfs_dir = p
249 else:
250 m = re.match('(.*):(.*)', p)
251 self.nfs_server = m.group(1)
252 self.nfs_dir = m.group(2)
253 self.rootfs = ""
254 self.check_arg_fstype('nfs')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500255
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600256 def check_arg_path(self, p):
257 """
258 - Check whether it is <image>.qemuboot.conf or contains <image>.qemuboot.conf
259 - Check whether is a kernel file
260 - Check whether is a image file
261 - Check whether it is a nfs dir
262 """
263 if p.endswith('.qemuboot.conf'):
264 self.qemuboot = p
265 self.qbconfload = True
266 elif re.search('\.bin$', p) or re.search('bzImage', p) or \
267 re.search('zImage', p) or re.search('vmlinux', p) or \
268 re.search('fitImage', p) or re.search('uImage', p):
269 self.kernel = p
270 elif os.path.exists(p) and (not os.path.isdir(p)) and re.search('-image-', os.path.basename(p)):
271 self.rootfs = p
272 dirpath = os.path.dirname(p)
273 m = re.search('(.*)\.(.*)$', p)
274 if m:
275 qb = '%s%s' % (re.sub('\.rootfs$', '', m.group(1)), '.qemuboot.conf')
276 if os.path.exists(qb):
277 self.qemuboot = qb
278 self.qbconfload = True
279 else:
280 logger.warn("%s doesn't exist" % qb)
281 fst = m.group(2)
282 self.check_arg_fstype(fst)
283 else:
284 raise Exception("Can't find FSTYPE from: %s" % p)
285 elif os.path.isdir(p) or re.search(':', arg) and re.search('/', arg):
286 if self.is_deploy_dir_image(p):
287 logger.info('DEPLOY_DIR_IMAGE: %s' % p)
288 self.set("DEPLOY_DIR_IMAGE", p)
289 else:
290 logger.info("Assuming %s is an nfs rootfs" % p)
291 self.check_arg_nfs(p)
292 else:
293 raise Exception("Unknown path arg %s" % p)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500294
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600295 def check_arg_machine(self, arg):
296 """Check whether it is a machine"""
297 if self.get('MACHINE') and self.get('MACHINE') != arg or re.search('/', arg):
298 raise Exception("Unknown arg: %s" % arg)
299 elif self.get('MACHINE') == arg:
300 return
301 logger.info('Assuming MACHINE = %s' % arg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500302
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600303 # if we're running under testimage, or similarly as a child
304 # of an existing bitbake invocation, we can't invoke bitbake
305 # to validate the MACHINE setting and must assume it's correct...
306 # FIXME: testimage.bbclass exports these two variables into env,
307 # are there other scenarios in which we need to support being
308 # invoked by bitbake?
309 deploy = os.environ.get('DEPLOY_DIR_IMAGE')
310 bbchild = deploy and os.environ.get('OE_TMPDIR')
311 if bbchild:
312 self.set_machine_deploy_dir(arg, deploy)
313 return
314 # also check whether we're running under a sourced toolchain
315 # environment file
316 if os.environ.get('OECORE_NATIVE_SYSROOT'):
317 self.set("MACHINE", arg)
318 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500319
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600320 cmd = 'MACHINE=%s bitbake -e' % arg
321 logger.info('Running %s...' % cmd)
322 self.bitbake_e = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
323 # bitbake -e doesn't report invalid MACHINE as an error, so
324 # let's check DEPLOY_DIR_IMAGE to make sure that it is a valid
325 # MACHINE.
326 s = re.search('^DEPLOY_DIR_IMAGE="(.*)"', self.bitbake_e, re.M)
327 if s:
328 deploy_dir_image = s.group(1)
329 else:
330 raise Exception("bitbake -e %s" % self.bitbake_e)
331 if self.is_deploy_dir_image(deploy_dir_image):
332 self.set_machine_deploy_dir(arg, deploy_dir_image)
333 else:
334 logger.error("%s not a directory valid DEPLOY_DIR_IMAGE" % deploy_dir_image)
335 self.set("MACHINE", arg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500336
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600337 def check_args(self):
338 unknown_arg = ""
339 for arg in sys.argv[1:]:
340 if arg in self.fstypes + self.vmtypes:
341 self.check_arg_fstype(arg)
342 elif arg == 'nographic':
343 self.qemu_opt_script += ' -nographic'
344 self.kernel_cmdline_script += ' console=ttyS0'
345 elif arg == 'serial':
346 self.kernel_cmdline_script += ' console=ttyS0'
347 self.serialstdio = True
348 elif arg == 'audio':
349 logger.info("Enabling audio in qemu")
350 logger.info("Please install sound drivers in linux host")
351 self.audio_enabled = True
352 elif arg == 'kvm':
353 self.kvm_enabled = True
354 elif arg == 'kvm-vhost':
355 self.vhost_enabled = True
356 elif arg == 'slirp':
357 self.slirp_enabled = True
358 elif arg == 'snapshot':
359 self.snapshot = True
360 elif arg == 'publicvnc':
361 self.qemu_opt_script += ' -vnc :0'
362 elif arg.startswith('tcpserial='):
363 self.tcpserial_portnum = arg[len('tcpserial='):]
364 elif arg.startswith('biosdir='):
365 self.custombiosdir = arg[len('biosdir='):]
366 elif arg.startswith('biosfilename='):
367 self.qemu_opt_script += ' -bios %s' % arg[len('biosfilename='):]
368 elif arg.startswith('qemuparams='):
369 self.qemu_opt_script += ' %s' % arg[len('qemuparams='):]
370 elif arg.startswith('bootparams='):
371 self.kernel_cmdline_script += ' %s' % arg[len('bootparams='):]
372 elif os.path.exists(arg) or (re.search(':', arg) and re.search('/', arg)):
373 self.check_arg_path(os.path.abspath(arg))
374 elif re.search('-image-', arg):
375 # Lazy rootfs
376 self.rootfs = arg
377 else:
378 # At last, assume is it the MACHINE
379 if (not unknown_arg) or unknown_arg == arg:
380 unknown_arg = arg
381 else:
382 raise Exception("Can't handle two unknown args: %s %s" % (unknown_arg, arg))
383 # Check to make sure it is a valid machine
384 if unknown_arg:
385 if self.get('MACHINE') == unknown_arg:
386 return
387 if not self.get('DEPLOY_DIR_IMAGE'):
388 # Trying to get DEPLOY_DIR_IMAGE from env.
389 p = os.getenv('DEPLOY_DIR_IMAGE')
390 if p and self.is_deploy_dir_image(p):
391 machine = os.path.basename(p)
392 if unknown_arg == machine:
393 self.set_machine_deploy_dir(machine, p)
394 return
395 else:
396 logger.info('DEPLOY_DIR_IMAGE: %s' % p)
397 self.set("DEPLOY_DIR_IMAGE", p)
398 self.check_arg_machine(unknown_arg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500399
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600400 def check_kvm(self):
401 """Check kvm and kvm-host"""
402 if not (self.kvm_enabled or self.vhost_enabled):
403 self.qemu_opt_script += ' %s %s' % (self.get('QB_MACHINE'), self.get('QB_CPU'))
404 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500405
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600406 if not self.get('QB_CPU_KVM'):
407 raise Exception("QB_CPU_KVM is NULL, this board doesn't support kvm")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500408
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600409 self.qemu_opt_script += ' %s %s' % (self.get('QB_MACHINE'), self.get('QB_CPU_KVM'))
410 yocto_kvm_wiki = "https://wiki.yoctoproject.org/wiki/How_to_enable_KVM_for_Poky_qemu"
411 yocto_paravirt_kvm_wiki = "https://wiki.yoctoproject.org/wiki/Running_an_x86_Yocto_Linux_image_under_QEMU_KVM"
412 dev_kvm = '/dev/kvm'
413 dev_vhost = '/dev/vhost-net'
414 with open('/proc/cpuinfo', 'r') as f:
415 kvm_cap = re.search('vmx|svm', "".join(f.readlines()))
416 if not kvm_cap:
417 logger.error("You are trying to enable KVM on a cpu without VT support.")
418 logger.error("Remove kvm from the command-line, or refer:")
419 raise Exception(yocto_kvm_wiki)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500420
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600421 if not os.path.exists(dev_kvm):
422 logger.error("Missing KVM device. Have you inserted kvm modules?")
423 logger.error("For further help see:")
424 raise Exception(yocto_kvm_wiki)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500425
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600426 if os.access(dev_kvm, os.W_OK|os.R_OK):
427 self.qemu_opt_script += ' -enable-kvm'
428 else:
429 logger.error("You have no read or write permission on /dev/kvm.")
430 logger.error("Please change the ownership of this file as described at:")
431 raise Exception(yocto_kvm_wiki)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500432
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600433 if self.vhost_enabled:
434 if not os.path.exists(dev_vhost):
435 logger.error("Missing virtio net device. Have you inserted vhost-net module?")
436 logger.error("For further help see:")
437 raise Exception(yocto_paravirt_kvm_wiki)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500438
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600439 if not os.access(dev_kvm, os.W_OK|os.R_OK):
440 logger.error("You have no read or write permission on /dev/vhost-net.")
441 logger.error("Please change the ownership of this file as described at:")
442 raise Exception(yocto_kvm_wiki)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500443
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600444 def check_fstype(self):
445 """Check and setup FSTYPE"""
446 if not self.fstype:
447 fstype = self.get('QB_DEFAULT_FSTYPE')
448 if fstype:
449 self.fstype = fstype
450 else:
451 raise Exception("FSTYPE is NULL!")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500452
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600453 def check_rootfs(self):
454 """Check and set rootfs"""
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500455
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600456 if self.fstype == 'nfs':
457 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500458
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600459 if self.rootfs and not os.path.exists(self.rootfs):
460 # Lazy rootfs
461 self.rootfs = "%s/%s-%s.%s" % (self.get('DEPLOY_DIR_IMAGE'),
462 self.rootfs, self.get('MACHINE'),
463 self.fstype)
464 elif not self.rootfs:
465 cmd_name = '%s/%s*.%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_NAME'), self.fstype)
466 cmd_link = '%s/%s*.%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_LINK_NAME'), self.fstype)
467 cmds = (cmd_name, cmd_link)
468 self.rootfs = get_first_file(cmds)
469 if not self.rootfs:
470 raise Exception("Failed to find rootfs: %s or %s" % cmds)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500471
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600472 if not os.path.exists(self.rootfs):
473 raise Exception("Can't find rootfs: %s" % self.rootfs)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500474
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600475 def check_kernel(self):
476 """Check and set kernel, dtb"""
477 # The vm image doesn't need a kernel
478 if self.fstype in self.vmtypes:
479 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500480
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600481 deploy_dir_image = self.get('DEPLOY_DIR_IMAGE')
482 if not self.kernel:
483 kernel_match_name = "%s/%s" % (deploy_dir_image, self.get('QB_DEFAULT_KERNEL'))
484 kernel_match_link = "%s/%s" % (deploy_dir_image, self.get('KERNEL_IMAGETYPE'))
485 kernel_startswith = "%s/%s*" % (deploy_dir_image, self.get('KERNEL_IMAGETYPE'))
486 cmds = (kernel_match_name, kernel_match_link, kernel_startswith)
487 self.kernel = get_first_file(cmds)
488 if not self.kernel:
489 raise Exception('KERNEL not found: %s, %s or %s' % cmds)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500490
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600491 if not os.path.exists(self.kernel):
492 raise Exception("KERNEL %s not found" % self.kernel)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500493
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600494 dtb = self.get('QB_DTB')
495 if dtb:
496 cmd_match = "%s/%s" % (deploy_dir_image, dtb)
497 cmd_startswith = "%s/%s*" % (deploy_dir_image, dtb)
498 cmd_wild = "%s/*.dtb" % deploy_dir_image
499 cmds = (cmd_match, cmd_startswith, cmd_wild)
500 self.dtb = get_first_file(cmds)
501 if not os.path.exists(self.dtb):
502 raise Exception('DTB not found: %s, %s or %s' % cmds)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500503
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600504 def check_biosdir(self):
505 """Check custombiosdir"""
506 if not self.custombiosdir:
507 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500508
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600509 biosdir = ""
510 biosdir_native = "%s/%s" % (self.get('STAGING_DIR_NATIVE'), self.custombiosdir)
511 biosdir_host = "%s/%s" % (self.get('STAGING_DIR_HOST'), self.custombiosdir)
512 for i in (self.custombiosdir, biosdir_native, biosdir_host):
513 if os.path.isdir(i):
514 biosdir = i
515 break
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500516
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600517 if biosdir:
518 logger.info("Assuming biosdir is: %s" % biosdir)
519 self.qemu_opt_script += ' -L %s' % biosdir
520 else:
521 logger.error("Custom BIOS directory not found. Tried: %s, %s, and %s" % (self.custombiosdir, biosdir_native, biosdir_host))
522 raise Exception("Invalid custombiosdir: %s" % self.custombiosdir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500523
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600524 def check_mem(self):
525 s = re.search('-m +([0-9]+)', self.qemu_opt_script)
526 if s:
527 self.set('QB_MEM', '-m %s' % s.group(1))
528 elif not self.get('QB_MEM'):
529 logger.info('QB_MEM is not set, use 512M by default')
530 self.set('QB_MEM', '-m 512')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500531
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600532 self.kernel_cmdline_script += ' mem=%s' % self.get('QB_MEM').replace('-m','').strip() + 'M'
533 self.qemu_opt_script += ' %s' % self.get('QB_MEM')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500534
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600535 def check_tcpserial(self):
536 if self.tcpserial_portnum:
537 if self.get('QB_TCPSERIAL_OPT'):
538 self.qemu_opt_script += ' ' + self.get('QB_TCPSERIAL_OPT').replace('@PORT@', self.tcpserial_portnum)
539 else:
540 self.qemu_opt_script += ' -serial tcp:127.0.0.1:%s' % self.tcpserial_portnum
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500541
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600542 def check_and_set(self):
543 """Check configs sanity and set when needed"""
544 self.validate_paths()
545 check_tun()
546 # Check audio
547 if self.audio_enabled:
548 if not self.get('QB_AUDIO_DRV'):
549 raise Exception("QB_AUDIO_DRV is NULL, this board doesn't support audio")
550 if not self.get('QB_AUDIO_OPT'):
551 logger.warn('QB_AUDIO_OPT is NULL, you may need define it to make audio work')
552 else:
553 self.qemu_opt_script += ' %s' % self.get('QB_AUDIO_OPT')
554 os.putenv('QEMU_AUDIO_DRV', self.get('QB_AUDIO_DRV'))
555 else:
556 os.putenv('QEMU_AUDIO_DRV', 'none')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500557
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600558 self.check_kvm()
559 self.check_fstype()
560 self.check_rootfs()
561 self.check_kernel()
562 self.check_biosdir()
563 self.check_mem()
564 self.check_tcpserial()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500565
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600566 def read_qemuboot(self):
567 if not self.qemuboot:
568 if self.get('DEPLOY_DIR_IMAGE'):
569 deploy_dir_image = self.get('DEPLOY_DIR_IMAGE')
570 elif os.getenv('DEPLOY_DIR_IMAGE'):
571 deploy_dir_image = os.getenv('DEPLOY_DIR_IMAGE')
572 else:
573 logger.info("Can't find qemuboot conf file, DEPLOY_DIR_IMAGE is NULL!")
574 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500575
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600576 if self.rootfs and not os.path.exists(self.rootfs):
577 # Lazy rootfs
578 machine = self.get('MACHINE')
579 if not machine:
580 machine = os.path.basename(deploy_dir_image)
581 self.qemuboot = "%s/%s-%s.qemuboot.conf" % (deploy_dir_image,
582 self.rootfs, machine)
583 else:
584 cmd = 'ls -t %s/*.qemuboot.conf' % deploy_dir_image
585 logger.info('Running %s...' % cmd)
586 qbs = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
587 if qbs:
588 self.qemuboot = qbs.split()[0]
589 self.qbconfload = True
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500590
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600591 if not self.qemuboot:
592 # If we haven't found a .qemuboot.conf at this point it probably
593 # doesn't exist, continue without
594 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500595
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600596 if not os.path.exists(self.qemuboot):
597 raise Exception("Failed to find <image>.qemuboot.conf!")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500598
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600599 logger.info('CONFFILE: %s' % self.qemuboot)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500600
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600601 cf = configparser.ConfigParser()
602 cf.read(self.qemuboot)
603 for k, v in cf.items('config_bsp'):
604 k_upper = k.upper()
605 self.set(k_upper, v)
606
607 def validate_paths(self):
608 """Ensure all relevant path variables are set"""
609 # When we're started with a *.qemuboot.conf arg assume that image
610 # artefacts are relative to that file, rather than in whatever
611 # directory DEPLOY_DIR_IMAGE in the conf file points to.
612 if self.qbconfload:
613 imgdir = os.path.dirname(self.qemuboot)
614 if imgdir != self.get('DEPLOY_DIR_IMAGE'):
615 logger.info('Setting DEPLOY_DIR_IMAGE to folder containing %s (%s)' % (self.qemuboot, imgdir))
616 self.set('DEPLOY_DIR_IMAGE', imgdir)
617
618 # If the STAGING_*_NATIVE directories from the config file don't exist
619 # and we're in a sourced OE build directory try to extract the paths
620 # from `bitbake -e`
621 havenative = os.path.exists(self.get('STAGING_DIR_NATIVE')) and \
622 os.path.exists(self.get('STAGING_BINDIR_NATIVE'))
623
624 if not havenative:
625 if not self.bitbake_e:
626 self.load_bitbake_env()
627
628 if self.bitbake_e:
629 native_vars = ['STAGING_DIR_NATIVE', 'STAGING_BINDIR_NATIVE']
630 for nv in native_vars:
631 s = re.search('^%s="(.*)"' % nv, self.bitbake_e, re.M)
632 if s and s.group(1) != self.get(nv):
633 logger.info('Overriding conf file setting of %s to %s from Bitbake environment' % (nv, s.group(1)))
634 self.set(nv, s.group(1))
635 else:
636 # when we're invoked from a running bitbake instance we won't
637 # be able to call `bitbake -e`, then try:
638 # - get OE_TMPDIR from environment and guess paths based on it
639 # - get OECORE_NATIVE_SYSROOT from environment (for sdk)
640 tmpdir = os.environ.get('OE_TMPDIR', None)
641 oecore_native_sysroot = os.environ.get('OECORE_NATIVE_SYSROOT', None)
642 if tmpdir:
643 logger.info('Setting STAGING_DIR_NATIVE and STAGING_BINDIR_NATIVE relative to OE_TMPDIR (%s)' % tmpdir)
644 hostos, _, _, _, machine = os.uname()
645 buildsys = '%s-%s' % (machine, hostos.lower())
646 staging_dir_native = '%s/sysroots/%s' % (tmpdir, buildsys)
647 self.set('STAGING_DIR_NATIVE', staging_dir_native)
648 elif oecore_native_sysroot:
649 logger.info('Setting STAGING_DIR_NATIVE to OECORE_NATIVE_SYSROOT (%s)' % oecore_native_sysroot)
650 self.set('STAGING_DIR_NATIVE', oecore_native_sysroot)
651 if self.get('STAGING_DIR_NATIVE'):
652 # we have to assume that STAGING_BINDIR_NATIVE is at usr/bin
653 staging_bindir_native = '%s/usr/bin' % self.get('STAGING_DIR_NATIVE')
654 logger.info('Setting STAGING_BINDIR_NATIVE to %s' % staging_bindir_native)
655 self.set('STAGING_BINDIR_NATIVE', '%s/usr/bin' % self.get('STAGING_DIR_NATIVE'))
656
657 def print_config(self):
658 logger.info('Continuing with the following parameters:\n')
659 if not self.fstype in self.vmtypes:
660 print('KERNEL: [%s]' % self.kernel)
661 if self.dtb:
662 print('DTB: [%s]' % self.dtb)
663 print('MACHINE: [%s]' % self.get('MACHINE'))
664 print('FSTYPE: [%s]' % self.fstype)
665 if self.fstype == 'nfs':
666 print('NFS_DIR: [%s]' % self.nfs_dir)
667 else:
668 print('ROOTFS: [%s]' % self.rootfs)
669 print('CONFFILE: [%s]' % self.qemuboot)
670 print('')
671
672 def setup_nfs(self):
673 if not self.nfs_server:
674 if self.slirp_enabled:
675 self.nfs_server = '10.0.2.2'
676 else:
677 self.nfs_server = '192.168.7.1'
678
679 nfs_instance = int(self.nfs_instance)
680
681 mountd_rpcport = 21111 + nfs_instance
682 nfsd_rpcport = 11111 + nfs_instance
683 nfsd_port = 3049 + 2 * nfs_instance
684 mountd_port = 3048 + 2 * nfs_instance
685 unfs_opts="nfsvers=3,port=%s,mountprog=%s,nfsprog=%s,udp,mountport=%s" % (nfsd_port, mountd_rpcport, nfsd_rpcport, mountd_port)
686 self.unfs_opts = unfs_opts
687
688 p = '%s/.runqemu-sdk/pseudo' % os.getenv('HOME')
689 os.putenv('PSEUDO_LOCALSTATEDIR', p)
690
691 # Extract .tar.bz2 or .tar.bz if no self.nfs_dir
692 if not self.nfs_dir:
693 src_prefix = '%s/%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_LINK_NAME'))
694 dest = "%s-nfsroot" % src_prefix
695 if os.path.exists('%s.pseudo_state' % dest):
696 logger.info('Use %s as NFS_DIR' % dest)
697 self.nfs_dir = dest
698 else:
699 src = ""
700 src1 = '%s.tar.bz2' % src_prefix
701 src2 = '%s.tar.gz' % src_prefix
702 if os.path.exists(src1):
703 src = src1
704 elif os.path.exists(src2):
705 src = src2
706 if not src:
707 raise Exception("No NFS_DIR is set, and can't find %s or %s to extract" % (src1, src2))
708 logger.info('NFS_DIR not found, extracting %s to %s' % (src, dest))
709 cmd = 'runqemu-extract-sdk %s %s' % (src, dest)
710 logger.info('Running %s...' % cmd)
711 if subprocess.call(cmd, shell=True) != 0:
712 raise Exception('Failed to run %s' % cmd)
713 self.clean_nfs_dir = True
714 self.nfs_dir = dest
715
716 # Start the userspace NFS server
717 cmd = 'runqemu-export-rootfs restart %s' % self.nfs_dir
718 logger.info('Running %s...' % cmd)
719 if subprocess.call(cmd, shell=True) != 0:
720 raise Exception('Failed to run %s' % cmd)
721
722 self.nfs_running = True
723
724
725 def setup_slirp(self):
726 if self.fstype == 'nfs':
727 self.setup_nfs()
728 self.kernel_cmdline_script += ' ip=dhcp'
729 self.set('NETWORK_CMD', self.get('QB_SLIRP_OPT'))
730
731 def setup_tap(self):
732 """Setup tap"""
733
734 # This file is created when runqemu-gen-tapdevs creates a bank of tap
735 # devices, indicating that the user should not bring up new ones using
736 # sudo.
737 nosudo_flag = '/etc/runqemu-nosudo'
738 self.qemuifup = shutil.which('runqemu-ifup')
739 self.qemuifdown = shutil.which('runqemu-ifdown')
740 ip = shutil.which('ip')
741 lockdir = "/tmp/qemu-tap-locks"
742
743 if not (self.qemuifup and self.qemuifdown and ip):
744 raise OEPathError("runqemu-ifup, runqemu-ifdown or ip not found")
745
746 if not os.path.exists(lockdir):
747 # There might be a race issue when multi runqemu processess are
748 # running at the same time.
749 try:
750 os.mkdir(lockdir)
751 except FileExistsError:
752 pass
753
754 cmd = '%s link' % ip
755 logger.info('Running %s...' % cmd)
756 ip_link = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
757 # Matches line like: 6: tap0: <foo>
758 possibles = re.findall('^[1-9]+: +(tap[0-9]+): <.*', ip_link, re.M)
759 tap = ""
760 for p in possibles:
761 lockfile = os.path.join(lockdir, p)
762 if os.path.exists('%s.skip' % lockfile):
763 logger.info('Found %s.skip, skipping %s' % (lockfile, p))
764 continue
765 self.lock = lockfile + '.lock'
766 if self.acquire_lock():
767 tap = p
768 logger.info("Using preconfigured tap device %s" % tap)
769 logger.info("If this is not intended, touch %s.skip to make runqemu skip %s." %(lockfile, tap))
770 break
771
772 if not tap:
773 if os.path.exists(nosudo_flag):
774 logger.error("Error: There are no available tap devices to use for networking,")
775 logger.error("and I see %s exists, so I am not going to try creating" % nosudo_flag)
776 raise Exception("a new one with sudo.")
777
778 gid = os.getgid()
779 uid = os.getuid()
780 logger.info("Setting up tap interface under sudo")
781 cmd = 'sudo %s %s %s %s' % (self.qemuifup, uid, gid, self.get('STAGING_DIR_NATIVE'))
782 tap = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8').rstrip('\n')
783 lockfile = os.path.join(lockdir, tap)
784 self.lock = lockfile + '.lock'
785 self.acquire_lock()
786 self.cleantap = True
787 logger.info('Created tap: %s' % tap)
788
789 if not tap:
790 logger.error("Failed to setup tap device. Run runqemu-gen-tapdevs to manually create.")
791 return 1
792 self.tap = tap
793 n0 = tap[3:]
794 n1 = int(n0) * 2 + 1
795 n2 = n1 + 1
796 self.nfs_instance = n0
797 if self.fstype == 'nfs':
798 self.setup_nfs()
799 self.kernel_cmdline_script += " ip=192.168.7.%s::192.168.7.%s:255.255.255.0" % (n2, n1)
800 mac = "52:54:00:12:34:%02x" % n2
801 qb_tap_opt = self.get('QB_TAP_OPT')
802 if qb_tap_opt:
803 qemu_tap_opt = qb_tap_opt.replace('@TAP@', tap).replace('@MAC@', mac)
804 else:
805 qemu_tap_opt = "-device virtio-net-pci,netdev=net0,mac=%s -netdev tap,id=net0,ifname=%s,script=no,downscript=no" % (mac, self.tap)
806
807 if self.vhost_enabled:
808 qemu_tap_opt += ',vhost=on'
809
810 self.set('NETWORK_CMD', qemu_tap_opt)
811
812 def setup_network(self):
813 cmd = "stty -g"
814 self.saved_stty = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
815 if self.slirp_enabled:
816 self.setup_slirp()
817 else:
818 self.setup_tap()
819
820 rootfs_format = self.fstype if self.fstype in ('vmdk', 'qcow2', 'vdi') else 'raw'
821
822 qb_rootfs_opt = self.get('QB_ROOTFS_OPT')
823 if qb_rootfs_opt:
824 self.rootfs_options = qb_rootfs_opt.replace('@ROOTFS@', self.rootfs)
825 else:
826 self.rootfs_options = '-drive file=%s,if=virtio,format=%s' % (self.rootfs, rootfs_format)
827
828 if self.fstype in ('cpio.gz', 'cpio'):
829 self.kernel_cmdline = 'root=/dev/ram0 rw debugshell'
830 self.rootfs_options = '-initrd %s' % self.rootfs
831 else:
832 if self.fstype in self.vmtypes:
833 if self.fstype == 'iso':
834 vm_drive = '-cdrom %s' % self.rootfs
835 else:
836 cmd1 = "grep -q 'root=/dev/sd' %s" % self.rootfs
837 cmd2 = "grep -q 'root=/dev/hd' %s" % self.rootfs
838 if subprocess.call(cmd1, shell=True) == 0:
839 logger.info('Using scsi drive')
840 vm_drive = '-drive if=none,id=hd,file=%s,format=%s -device virtio-scsi-pci,id=scsi -device scsi-hd,drive=hd' \
841 % (self.rootfs, rootfs_format)
842 elif subprocess.call(cmd2, shell=True) == 0:
843 logger.info('Using scsi drive')
844 vm_drive = "%s,format=%s" % (self.rootfs, rootfs_format)
845 else:
846 logger.warn("Can't detect drive type %s" % self.rootfs)
847 logger.warn('Tring to use virtio block drive')
848 vm_drive = '-drive if=virtio,file=%s,format=%s' % (self.rootfs, rootfs_format)
849 self.rootfs_options = '%s -no-reboot' % vm_drive
850 self.kernel_cmdline = 'root=%s rw highres=off' % (self.get('QB_KERNEL_ROOT'))
851
852 if self.fstype == 'nfs':
853 self.rootfs_options = ''
854 k_root = '/dev/nfs nfsroot=%s:%s,%s' % (self.nfs_server, self.nfs_dir, self.unfs_opts)
855 self.kernel_cmdline = 'root=%s rw highres=off' % k_root
856
857 self.set('ROOTFS_OPTIONS', self.rootfs_options)
858
859 def guess_qb_system(self):
860 """attempt to determine the appropriate qemu-system binary"""
861 mach = self.get('MACHINE')
862 if not mach:
863 search = '.*(qemux86-64|qemux86|qemuarm64|qemuarm|qemumips64|qemumips64el|qemumipsel|qemumips|qemuppc).*'
864 if self.rootfs:
865 match = re.match(search, self.rootfs)
866 if match:
867 mach = match.group(1)
868 elif self.kernel:
869 match = re.match(search, self.kernel)
870 if match:
871 mach = match.group(1)
872
873 if not mach:
874 return None
875
876 if mach == 'qemuarm':
877 qbsys = 'arm'
878 elif mach == 'qemuarm64':
879 qbsys = 'aarch64'
880 elif mach == 'qemux86':
881 qbsys = 'i386'
882 elif mach == 'qemux86-64':
883 qbsys = 'x86_64'
884 elif mach == 'qemuppc':
885 qbsys = 'ppc'
886 elif mach == 'qemumips':
887 qbsys = 'mips'
888 elif mach == 'qemumips64':
889 qbsys = 'mips64'
890 elif mach == 'qemumipsel':
891 qbsys = 'mipsel'
892 elif mach == 'qemumips64el':
893 qbsys = 'mips64el'
894
895 return 'qemu-system-%s' % qbsys
896
897 def setup_final(self):
898 qemu_system = self.get('QB_SYSTEM_NAME')
899 if not qemu_system:
900 qemu_system = self.guess_qb_system()
901 if not qemu_system:
902 raise Exception("Failed to boot, QB_SYSTEM_NAME is NULL!")
903
904 qemu_bin = '%s/%s' % (self.get('STAGING_BINDIR_NATIVE'), qemu_system)
905 if not os.access(qemu_bin, os.X_OK):
906 raise OEPathError("No QEMU binary '%s' could be found" % qemu_bin)
907
908 check_libgl(qemu_bin)
909
910 self.qemu_opt = "%s %s %s %s %s" % (qemu_bin, self.get('NETWORK_CMD'), self.qemu_opt_script, self.get('ROOTFS_OPTIONS'), self.get('QB_OPT_APPEND'))
911
912 if self.snapshot:
913 self.qemu_opt += " -snapshot"
914
915 if self.serialstdio:
916 logger.info("Interrupt character is '^]'")
917 cmd = "stty intr ^]"
918 subprocess.call(cmd, shell=True)
919
920 first_serial = ""
921 if not re.search("-nographic", self.qemu_opt):
922 first_serial = "-serial mon:vc"
923 # We always want a ttyS1. Since qemu by default adds a serial
924 # port when nodefaults is not specified, it seems that all that
925 # would be needed is to make sure a "-serial" is there. However,
926 # it appears that when "-serial" is specified, it ignores the
927 # default serial port that is normally added. So here we make
928 # sure to add two -serial if there are none. And only one if
929 # there is one -serial already.
930 serial_num = len(re.findall("-serial", self.qemu_opt))
931 if serial_num == 0:
932 self.qemu_opt += " %s %s" % (first_serial, self.get("QB_SERIAL_OPT"))
933 elif serial_num == 1:
934 self.qemu_opt += " %s" % self.get("QB_SERIAL_OPT")
935
936 def start_qemu(self):
937 if self.kernel:
938 kernel_opts = "-kernel %s -append '%s %s %s'" % (self.kernel, self.kernel_cmdline, self.kernel_cmdline_script, self.get('QB_KERNEL_CMDLINE_APPEND'))
939 if self.dtb:
940 kernel_opts += " -dtb %s" % self.dtb
941 else:
942 kernel_opts = ""
943 cmd = "%s %s" % (self.qemu_opt, kernel_opts)
944 logger.info('Running %s' % cmd)
945 if subprocess.call(cmd, shell=True) != 0:
946 raise Exception('Failed to run %s' % cmd)
947
948 def cleanup(self):
949 if self.cleantap:
950 cmd = 'sudo %s %s %s' % (self.qemuifdown, self.tap, self.get('STAGING_DIR_NATIVE'))
951 logger.info('Running %s' % cmd)
952 subprocess.call(cmd, shell=True)
953 if self.lock_descriptor:
954 logger.info("Releasing lockfile for tap device '%s'" % self.tap)
955 self.release_lock()
956
957 if self.nfs_running:
958 logger.info("Shutting down the userspace NFS server...")
959 cmd = "runqemu-export-rootfs stop %s" % self.nfs_dir
960 logger.info('Running %s' % cmd)
961 subprocess.call(cmd, shell=True)
962
963 if self.saved_stty:
964 cmd = "stty %s" % self.saved_stty
965 subprocess.call(cmd, shell=True)
966
967 if self.clean_nfs_dir:
968 logger.info('Removing %s' % self.nfs_dir)
969 shutil.rmtree(self.nfs_dir)
970 shutil.rmtree('%s.pseudo_state' % self.nfs_dir)
971
972 def load_bitbake_env(self, mach=None):
973 if self.bitbake_e:
974 return
975
976 bitbake = shutil.which('bitbake')
977 if not bitbake:
978 return
979
980 if not mach:
981 mach = self.get('MACHINE')
982
983 if mach:
984 cmd = 'MACHINE=%s bitbake -e' % mach
985 else:
986 cmd = 'bitbake -e'
987
988 logger.info('Running %s...' % cmd)
989 try:
990 self.bitbake_e = subprocess.check_output(cmd, shell=True).decode('utf-8')
991 except subprocess.CalledProcessError as err:
992 self.bitbake_e = ''
993 logger.warn("Couldn't run 'bitbake -e' to gather environment information:\n%s" % err.output.decode('utf-8'))
994
995def main():
996 if len(sys.argv) == 1 or "help" in sys.argv:
997 print_usage()
998 return 0
999 config = BaseConfig()
1000 try:
1001 config.check_args()
1002 except Exception as esc:
1003 logger.error(esc)
1004 logger.error("Try 'runqemu help' on how to use it")
1005 return 1
1006 config.read_qemuboot()
1007 config.check_and_set()
1008 config.print_config()
1009 try:
1010 config.setup_network()
1011 config.setup_final()
1012 config.start_qemu()
1013 finally:
1014 config.cleanup()
1015 return 0
1016
1017if __name__ == "__main__":
1018 try:
1019 ret = main()
1020 except OEPathError as err:
1021 ret = 1
1022 logger.error(err.message)
1023 except Exception as esc:
1024 ret = 1
1025 import traceback
1026 traceback.print_exc()
1027 sys.exit(ret)