runqemu 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  1. #!/usr/bin/env python3
  2. # Handle running OE images standalone with QEMU
  3. #
  4. # Copyright (C) 2006-2011 Linux Foundation
  5. # Copyright (c) 2016 Wind River Systems, Inc.
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License version 2 as
  9. # published by the Free Software Foundation.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License along
  17. # with this program; if not, write to the Free Software Foundation, Inc.,
  18. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  19. import os
  20. import sys
  21. import logging
  22. import subprocess
  23. import re
  24. import fcntl
  25. import shutil
  26. import glob
  27. import configparser
  28. class OEPathError(Exception):
  29. """Custom Exception to give better guidance on missing binaries"""
  30. def __init__(self, message):
  31. self.message = "In order for this script to dynamically infer paths\n \
  32. kernels or filesystem images, you either need bitbake in your PATH\n \
  33. or to source oe-init-build-env before running this script.\n\n \
  34. Dynamic path inference can be avoided by passing a *.qemuboot.conf to\n \
  35. runqemu, i.e. `runqemu /path/to/my-image-name.qemuboot.conf`\n\n %s" % message
  36. def create_logger():
  37. logger = logging.getLogger('runqemu')
  38. logger.setLevel(logging.INFO)
  39. # create console handler and set level to debug
  40. ch = logging.StreamHandler()
  41. ch.setLevel(logging.INFO)
  42. # create formatter
  43. formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
  44. # add formatter to ch
  45. ch.setFormatter(formatter)
  46. # add ch to logger
  47. logger.addHandler(ch)
  48. return logger
  49. logger = create_logger()
  50. def print_usage():
  51. print("""
  52. Usage: you can run this script with any valid combination
  53. of the following environment variables (in any order):
  54. KERNEL - the kernel image file to use
  55. ROOTFS - the rootfs image file or nfsroot directory to use
  56. MACHINE - the machine name (optional, autodetected from KERNEL filename if unspecified)
  57. Simplified QEMU command-line options can be passed with:
  58. nographic - disable video console
  59. serial - enable a serial console on /dev/ttyS0
  60. slirp - enable user networking, no root privileges is required
  61. kvm - enable KVM when running x86/x86_64 (VT-capable CPU required)
  62. kvm-vhost - enable KVM with vhost when running x86/x86_64 (VT-capable CPU required)
  63. publicvnc - enable a VNC server open to all hosts
  64. audio - enable audio
  65. [*/]ovmf* - OVMF firmware file or base name for booting with UEFI
  66. tcpserial=<port> - specify tcp serial port number
  67. biosdir=<dir> - specify custom bios dir
  68. biosfilename=<filename> - specify bios filename
  69. qemuparams=<xyz> - specify custom parameters to QEMU
  70. bootparams=<xyz> - specify custom kernel parameters during boot
  71. help, -h, --help: print this text
  72. Examples:
  73. runqemu
  74. runqemu qemuarm
  75. runqemu tmp/deploy/images/qemuarm
  76. runqemu tmp/deploy/images/qemux86/<qemuboot.conf>
  77. runqemu qemux86-64 core-image-sato ext4
  78. runqemu qemux86-64 wic-image-minimal wic
  79. runqemu path/to/bzImage-qemux86.bin path/to/nfsrootdir/ serial
  80. runqemu qemux86 iso/hddimg/vmdk/qcow2/vdi/ramfs/cpio.gz...
  81. runqemu qemux86 qemuparams="-m 256"
  82. runqemu qemux86 bootparams="psplash=false"
  83. runqemu path/to/<image>-<machine>.vmdk
  84. runqemu path/to/<image>-<machine>.wic
  85. """)
  86. def check_tun():
  87. """Check /dev/net/tun"""
  88. dev_tun = '/dev/net/tun'
  89. if not os.path.exists(dev_tun):
  90. raise Exception("TUN control device %s is unavailable; you may need to enable TUN (e.g. sudo modprobe tun)" % dev_tun)
  91. if not os.access(dev_tun, os.W_OK):
  92. raise Exception("TUN control device %s is not writable, please fix (e.g. sudo chmod 666 %s)" % (dev_tun, dev_tun))
  93. def check_libgl(qemu_bin):
  94. cmd = 'ldd %s' % qemu_bin
  95. logger.info('Running %s...' % cmd)
  96. need_gl = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
  97. if re.search('libGLU', need_gl):
  98. # We can't run without a libGL.so
  99. libgl = False
  100. check_files = (('/usr/lib/libGL.so', '/usr/lib/libGLU.so'), \
  101. ('/usr/lib64/libGL.so', '/usr/lib64/libGLU.so'), \
  102. ('/usr/lib/*-linux-gnu/libGL.so', '/usr/lib/*-linux-gnu/libGLU.so'))
  103. for (f1, f2) in check_files:
  104. if re.search('\*', f1):
  105. for g1 in glob.glob(f1):
  106. if libgl:
  107. break
  108. if os.path.exists(g1):
  109. for g2 in glob.glob(f2):
  110. if os.path.exists(g2):
  111. libgl = True
  112. break
  113. if libgl:
  114. break
  115. else:
  116. if os.path.exists(f1) and os.path.exists(f2):
  117. libgl = True
  118. break
  119. if not libgl:
  120. logger.error("You need libGL.so and libGLU.so to exist in your library path to run the QEMU emulator.")
  121. logger.error("Ubuntu package names are: libgl1-mesa-dev and libglu1-mesa-dev.")
  122. logger.error("Fedora package names are: mesa-libGL-devel mesa-libGLU-devel.")
  123. raise Exception('%s requires libGLU, but not found' % qemu_bin)
  124. def get_first_file(cmds):
  125. """Return first file found in wildcard cmds"""
  126. for cmd in cmds:
  127. all_files = glob.glob(cmd)
  128. if all_files:
  129. for f in all_files:
  130. if not os.path.isdir(f):
  131. return f
  132. return ''
  133. def check_free_port(host, port):
  134. """ Check whether the port is free or not """
  135. import socket
  136. from contextlib import closing
  137. with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
  138. if sock.connect_ex((host, port)) == 0:
  139. # Port is open, so not free
  140. return False
  141. else:
  142. # Port is not open, so free
  143. return True
  144. class BaseConfig(object):
  145. def __init__(self):
  146. # The self.d saved vars from self.set(), part of them are from qemuboot.conf
  147. self.d = {'QB_KERNEL_ROOT': '/dev/vda'}
  148. # Supported env vars, add it here if a var can be got from env,
  149. # and don't use os.getenv in the code.
  150. self.env_vars = ('MACHINE',
  151. 'ROOTFS',
  152. 'KERNEL',
  153. 'DEPLOY_DIR_IMAGE',
  154. 'OE_TMPDIR',
  155. 'OECORE_NATIVE_SYSROOT',
  156. )
  157. self.qemu_opt = ''
  158. self.qemu_opt_script = ''
  159. self.clean_nfs_dir = False
  160. self.nfs_server = ''
  161. self.rootfs = ''
  162. # File name(s) of a OVMF firmware file or variable store,
  163. # to be added with -drive if=pflash.
  164. # Found in the same places as the rootfs, with or without one of
  165. # these suffices: qcow2, bin.
  166. # Setting one also adds "-vga std" because that is all that
  167. # OVMF supports.
  168. self.ovmf_bios = []
  169. self.qemuboot = ''
  170. self.qbconfload = False
  171. self.kernel = ''
  172. self.kernel_cmdline = ''
  173. self.kernel_cmdline_script = ''
  174. self.bootparams = ''
  175. self.dtb = ''
  176. self.fstype = ''
  177. self.kvm_enabled = False
  178. self.vhost_enabled = False
  179. self.slirp_enabled = False
  180. self.nfs_instance = 0
  181. self.nfs_running = False
  182. self.serialstdio = False
  183. self.cleantap = False
  184. self.saved_stty = ''
  185. self.audio_enabled = False
  186. self.tcpserial_portnum = ''
  187. self.custombiosdir = ''
  188. self.lock = ''
  189. self.lock_descriptor = ''
  190. self.bitbake_e = ''
  191. self.snapshot = False
  192. self.fstypes = ('ext2', 'ext3', 'ext4', 'jffs2', 'nfs', 'btrfs', 'cpio.gz', 'cpio', 'ramfs')
  193. self.vmtypes = ('hddimg', 'hdddirect', 'wic', 'vmdk', 'qcow2', 'vdi', 'iso')
  194. self.network_device = "-device e1000,netdev=net0,mac=@MAC@"
  195. # Use different mac section for tap and slirp to avoid
  196. # conflicts, e.g., when one is running with tap, the other is
  197. # running with slirp.
  198. # The last section is dynamic, which is for avoiding conflicts,
  199. # when multiple qemus are running, e.g., when multiple tap or
  200. # slirp qemus are running.
  201. self.mac_tap = "52:54:00:12:34:"
  202. self.mac_slirp = "52:54:00:12:35:"
  203. def acquire_lock(self):
  204. logger.info("Acquiring lockfile %s..." % self.lock)
  205. try:
  206. self.lock_descriptor = open(self.lock, 'w')
  207. fcntl.flock(self.lock_descriptor, fcntl.LOCK_EX|fcntl.LOCK_NB)
  208. except Exception as e:
  209. logger.info("Acquiring lockfile %s failed: %s" % (self.lock, e))
  210. if self.lock_descriptor:
  211. self.lock_descriptor.close()
  212. return False
  213. return True
  214. def release_lock(self):
  215. fcntl.flock(self.lock_descriptor, fcntl.LOCK_UN)
  216. self.lock_descriptor.close()
  217. os.remove(self.lock)
  218. def get(self, key):
  219. if key in self.d:
  220. return self.d.get(key)
  221. elif os.getenv(key):
  222. return os.getenv(key)
  223. else:
  224. return ''
  225. def set(self, key, value):
  226. self.d[key] = value
  227. def is_deploy_dir_image(self, p):
  228. if os.path.isdir(p):
  229. if not re.search('.qemuboot.conf$', '\n'.join(os.listdir(p)), re.M):
  230. logger.info("Can't find required *.qemuboot.conf in %s" % p)
  231. return False
  232. if not any(map(lambda name: '-image-' in name, os.listdir(p))):
  233. logger.info("Can't find *-image-* in %s" % p)
  234. return False
  235. return True
  236. else:
  237. return False
  238. def check_arg_fstype(self, fst):
  239. """Check and set FSTYPE"""
  240. if fst not in self.fstypes + self.vmtypes:
  241. logger.warn("Maybe unsupported FSTYPE: %s" % fst)
  242. if not self.fstype or self.fstype == fst:
  243. if fst == 'ramfs':
  244. fst = 'cpio.gz'
  245. self.fstype = fst
  246. else:
  247. raise Exception("Conflicting: FSTYPE %s and %s" % (self.fstype, fst))
  248. def set_machine_deploy_dir(self, machine, deploy_dir_image):
  249. """Set MACHINE and DEPLOY_DIR_IMAGE"""
  250. logger.info('MACHINE: %s' % machine)
  251. self.set("MACHINE", machine)
  252. logger.info('DEPLOY_DIR_IMAGE: %s' % deploy_dir_image)
  253. self.set("DEPLOY_DIR_IMAGE", deploy_dir_image)
  254. def check_arg_nfs(self, p):
  255. if os.path.isdir(p):
  256. self.rootfs = p
  257. else:
  258. m = re.match('(.*):(.*)', p)
  259. self.nfs_server = m.group(1)
  260. self.rootfs = m.group(2)
  261. self.check_arg_fstype('nfs')
  262. def check_arg_path(self, p):
  263. """
  264. - Check whether it is <image>.qemuboot.conf or contains <image>.qemuboot.conf
  265. - Check whether is a kernel file
  266. - Check whether is a image file
  267. - Check whether it is a nfs dir
  268. - Check whether it is a OVMF flash file
  269. """
  270. if p.endswith('.qemuboot.conf'):
  271. self.qemuboot = p
  272. self.qbconfload = True
  273. elif re.search('\.bin$', p) or re.search('bzImage', p) or \
  274. re.search('zImage', p) or re.search('vmlinux', p) or \
  275. re.search('fitImage', p) or re.search('uImage', p):
  276. self.kernel = p
  277. elif os.path.exists(p) and (not os.path.isdir(p)) and '-image-' in os.path.basename(p):
  278. self.rootfs = p
  279. # Check filename against self.fstypes can hanlde <file>.cpio.gz,
  280. # otherwise, its type would be "gz", which is incorrect.
  281. fst = ""
  282. for t in self.fstypes:
  283. if p.endswith(t):
  284. fst = t
  285. break
  286. if not fst:
  287. m = re.search('.*\.(.*)$', self.rootfs)
  288. if m:
  289. fst = m.group(1)
  290. if fst:
  291. self.check_arg_fstype(fst)
  292. qb = re.sub('\.' + fst + "$", '', self.rootfs)
  293. qb = '%s%s' % (re.sub('\.rootfs$', '', qb), '.qemuboot.conf')
  294. if os.path.exists(qb):
  295. self.qemuboot = qb
  296. self.qbconfload = True
  297. else:
  298. logger.warn("%s doesn't exist" % qb)
  299. else:
  300. raise Exception("Can't find FSTYPE from: %s" % p)
  301. elif os.path.isdir(p) or re.search(':', p) and re.search('/', p):
  302. if self.is_deploy_dir_image(p):
  303. logger.info('DEPLOY_DIR_IMAGE: %s' % p)
  304. self.set("DEPLOY_DIR_IMAGE", p)
  305. else:
  306. logger.info("Assuming %s is an nfs rootfs" % p)
  307. self.check_arg_nfs(p)
  308. elif os.path.basename(p).startswith('ovmf'):
  309. self.ovmf_bios.append(p)
  310. else:
  311. raise Exception("Unknown path arg %s" % p)
  312. def check_arg_machine(self, arg):
  313. """Check whether it is a machine"""
  314. if self.get('MACHINE') == arg:
  315. return
  316. elif self.get('MACHINE') and self.get('MACHINE') != arg:
  317. raise Exception("Maybe conflicted MACHINE: %s vs %s" % (self.get('MACHINE'), arg))
  318. elif re.search('/', arg):
  319. raise Exception("Unknown arg: %s" % arg)
  320. logger.info('Assuming MACHINE = %s' % arg)
  321. # if we're running under testimage, or similarly as a child
  322. # of an existing bitbake invocation, we can't invoke bitbake
  323. # to validate the MACHINE setting and must assume it's correct...
  324. # FIXME: testimage.bbclass exports these two variables into env,
  325. # are there other scenarios in which we need to support being
  326. # invoked by bitbake?
  327. deploy = self.get('DEPLOY_DIR_IMAGE')
  328. bbchild = deploy and self.get('OE_TMPDIR')
  329. if bbchild:
  330. self.set_machine_deploy_dir(arg, deploy)
  331. return
  332. # also check whether we're running under a sourced toolchain
  333. # environment file
  334. if self.get('OECORE_NATIVE_SYSROOT'):
  335. self.set("MACHINE", arg)
  336. return
  337. cmd = 'MACHINE=%s bitbake -e' % arg
  338. logger.info('Running %s...' % cmd)
  339. self.bitbake_e = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
  340. # bitbake -e doesn't report invalid MACHINE as an error, so
  341. # let's check DEPLOY_DIR_IMAGE to make sure that it is a valid
  342. # MACHINE.
  343. s = re.search('^DEPLOY_DIR_IMAGE="(.*)"', self.bitbake_e, re.M)
  344. if s:
  345. deploy_dir_image = s.group(1)
  346. else:
  347. raise Exception("bitbake -e %s" % self.bitbake_e)
  348. if self.is_deploy_dir_image(deploy_dir_image):
  349. self.set_machine_deploy_dir(arg, deploy_dir_image)
  350. else:
  351. logger.error("%s not a directory valid DEPLOY_DIR_IMAGE" % deploy_dir_image)
  352. self.set("MACHINE", arg)
  353. def check_args(self):
  354. unknown_arg = ""
  355. for arg in sys.argv[1:]:
  356. if arg in self.fstypes + self.vmtypes:
  357. self.check_arg_fstype(arg)
  358. elif arg == 'nographic':
  359. self.qemu_opt_script += ' -nographic'
  360. self.kernel_cmdline_script += ' console=ttyS0'
  361. elif arg == 'serial':
  362. self.kernel_cmdline_script += ' console=ttyS0'
  363. self.serialstdio = True
  364. elif arg == 'audio':
  365. logger.info("Enabling audio in qemu")
  366. logger.info("Please install sound drivers in linux host")
  367. self.audio_enabled = True
  368. elif arg == 'kvm':
  369. self.kvm_enabled = True
  370. elif arg == 'kvm-vhost':
  371. self.vhost_enabled = True
  372. elif arg == 'slirp':
  373. self.slirp_enabled = True
  374. elif arg == 'snapshot':
  375. self.snapshot = True
  376. elif arg == 'publicvnc':
  377. self.qemu_opt_script += ' -vnc :0'
  378. elif arg.startswith('tcpserial='):
  379. self.tcpserial_portnum = arg[len('tcpserial='):]
  380. elif arg.startswith('biosdir='):
  381. self.custombiosdir = arg[len('biosdir='):]
  382. elif arg.startswith('biosfilename='):
  383. self.qemu_opt_script += ' -bios %s' % arg[len('biosfilename='):]
  384. elif arg.startswith('qemuparams='):
  385. self.qemu_opt_script += ' %s' % arg[len('qemuparams='):]
  386. elif arg.startswith('bootparams='):
  387. self.bootparams = arg[len('bootparams='):]
  388. elif os.path.exists(arg) or (re.search(':', arg) and re.search('/', arg)):
  389. self.check_arg_path(os.path.abspath(arg))
  390. elif re.search(r'-image-|-image$', arg):
  391. # Lazy rootfs
  392. self.rootfs = arg
  393. elif arg.startswith('ovmf'):
  394. self.ovmf_bios.append(arg)
  395. else:
  396. # At last, assume it is the MACHINE
  397. if (not unknown_arg) or unknown_arg == arg:
  398. unknown_arg = arg
  399. else:
  400. raise Exception("Can't handle two unknown args: %s %s" % (unknown_arg, arg))
  401. # Check to make sure it is a valid machine
  402. if unknown_arg:
  403. if self.get('MACHINE') == unknown_arg:
  404. return
  405. if self.get('DEPLOY_DIR_IMAGE'):
  406. machine = os.path.basename(self.get('DEPLOY_DIR_IMAGE'))
  407. if unknown_arg == machine:
  408. self.set("MACHINE", machine)
  409. return
  410. self.check_arg_machine(unknown_arg)
  411. if not self.get('DEPLOY_DIR_IMAGE'):
  412. self.load_bitbake_env()
  413. s = re.search('^DEPLOY_DIR_IMAGE="(.*)"', self.bitbake_e, re.M)
  414. if s:
  415. self.set("DEPLOY_DIR_IMAGE", s.group(1))
  416. def check_kvm(self):
  417. """Check kvm and kvm-host"""
  418. if not (self.kvm_enabled or self.vhost_enabled):
  419. self.qemu_opt_script += ' %s %s' % (self.get('QB_MACHINE'), self.get('QB_CPU'))
  420. return
  421. if not self.get('QB_CPU_KVM'):
  422. raise Exception("QB_CPU_KVM is NULL, this board doesn't support kvm")
  423. self.qemu_opt_script += ' %s %s' % (self.get('QB_MACHINE'), self.get('QB_CPU_KVM'))
  424. yocto_kvm_wiki = "https://wiki.yoctoproject.org/wiki/How_to_enable_KVM_for_Poky_qemu"
  425. yocto_paravirt_kvm_wiki = "https://wiki.yoctoproject.org/wiki/Running_an_x86_Yocto_Linux_image_under_QEMU_KVM"
  426. dev_kvm = '/dev/kvm'
  427. dev_vhost = '/dev/vhost-net'
  428. with open('/proc/cpuinfo', 'r') as f:
  429. kvm_cap = re.search('vmx|svm', "".join(f.readlines()))
  430. if not kvm_cap:
  431. logger.error("You are trying to enable KVM on a cpu without VT support.")
  432. logger.error("Remove kvm from the command-line, or refer:")
  433. raise Exception(yocto_kvm_wiki)
  434. if not os.path.exists(dev_kvm):
  435. logger.error("Missing KVM device. Have you inserted kvm modules?")
  436. logger.error("For further help see:")
  437. raise Exception(yocto_kvm_wiki)
  438. if os.access(dev_kvm, os.W_OK|os.R_OK):
  439. self.qemu_opt_script += ' -enable-kvm'
  440. else:
  441. logger.error("You have no read or write permission on /dev/kvm.")
  442. logger.error("Please change the ownership of this file as described at:")
  443. raise Exception(yocto_kvm_wiki)
  444. if self.vhost_enabled:
  445. if not os.path.exists(dev_vhost):
  446. logger.error("Missing virtio net device. Have you inserted vhost-net module?")
  447. logger.error("For further help see:")
  448. raise Exception(yocto_paravirt_kvm_wiki)
  449. if not os.access(dev_kvm, os.W_OK|os.R_OK):
  450. logger.error("You have no read or write permission on /dev/vhost-net.")
  451. logger.error("Please change the ownership of this file as described at:")
  452. raise Exception(yocto_kvm_wiki)
  453. def check_fstype(self):
  454. """Check and setup FSTYPE"""
  455. if not self.fstype:
  456. fstype = self.get('QB_DEFAULT_FSTYPE')
  457. if fstype:
  458. self.fstype = fstype
  459. else:
  460. raise Exception("FSTYPE is NULL!")
  461. def check_rootfs(self):
  462. """Check and set rootfs"""
  463. if self.fstype == "none":
  464. return
  465. if self.get('ROOTFS'):
  466. if not self.rootfs:
  467. self.rootfs = self.get('ROOTFS')
  468. elif self.get('ROOTFS') != self.rootfs:
  469. raise Exception("Maybe conflicted ROOTFS: %s vs %s" % (self.get('ROOTFS'), self.rootfs))
  470. if self.fstype == 'nfs':
  471. return
  472. if self.rootfs and not os.path.exists(self.rootfs):
  473. # Lazy rootfs
  474. self.rootfs = "%s/%s-%s.%s" % (self.get('DEPLOY_DIR_IMAGE'),
  475. self.rootfs, self.get('MACHINE'),
  476. self.fstype)
  477. elif not self.rootfs:
  478. cmd_name = '%s/%s*.%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_NAME'), self.fstype)
  479. cmd_link = '%s/%s*.%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_LINK_NAME'), self.fstype)
  480. cmds = (cmd_name, cmd_link)
  481. self.rootfs = get_first_file(cmds)
  482. if not self.rootfs:
  483. raise Exception("Failed to find rootfs: %s or %s" % cmds)
  484. if not os.path.exists(self.rootfs):
  485. raise Exception("Can't find rootfs: %s" % self.rootfs)
  486. def check_ovmf(self):
  487. """Check and set full path for OVMF firmware and variable file(s)."""
  488. for index, ovmf in enumerate(self.ovmf_bios):
  489. if os.path.exists(ovmf):
  490. continue
  491. for suffix in ('qcow2', 'bin'):
  492. path = '%s/%s.%s' % (self.get('DEPLOY_DIR_IMAGE'), ovmf, suffix)
  493. if os.path.exists(path):
  494. self.ovmf_bios[index] = path
  495. break
  496. else:
  497. raise Exception("Can't find OVMF firmware: %s" % ovmf)
  498. def check_kernel(self):
  499. """Check and set kernel, dtb"""
  500. # The vm image doesn't need a kernel
  501. if self.fstype in self.vmtypes:
  502. return
  503. # QB_DEFAULT_KERNEL is always a full file path
  504. kernel_name = os.path.basename(self.get('QB_DEFAULT_KERNEL'))
  505. # The user didn't want a kernel to be loaded
  506. if kernel_name == "none":
  507. return
  508. deploy_dir_image = self.get('DEPLOY_DIR_IMAGE')
  509. if not self.kernel:
  510. kernel_match_name = "%s/%s" % (deploy_dir_image, kernel_name)
  511. kernel_match_link = "%s/%s" % (deploy_dir_image, self.get('KERNEL_IMAGETYPE'))
  512. kernel_startswith = "%s/%s*" % (deploy_dir_image, self.get('KERNEL_IMAGETYPE'))
  513. cmds = (kernel_match_name, kernel_match_link, kernel_startswith)
  514. self.kernel = get_first_file(cmds)
  515. if not self.kernel:
  516. raise Exception('KERNEL not found: %s, %s or %s' % cmds)
  517. if not os.path.exists(self.kernel):
  518. raise Exception("KERNEL %s not found" % self.kernel)
  519. dtb = self.get('QB_DTB')
  520. if dtb:
  521. cmd_match = "%s/%s" % (deploy_dir_image, dtb)
  522. cmd_startswith = "%s/%s*" % (deploy_dir_image, dtb)
  523. cmd_wild = "%s/*.dtb" % deploy_dir_image
  524. cmds = (cmd_match, cmd_startswith, cmd_wild)
  525. self.dtb = get_first_file(cmds)
  526. if not os.path.exists(self.dtb):
  527. raise Exception('DTB not found: %s, %s or %s' % cmds)
  528. def check_biosdir(self):
  529. """Check custombiosdir"""
  530. if not self.custombiosdir:
  531. return
  532. biosdir = ""
  533. biosdir_native = "%s/%s" % (self.get('STAGING_DIR_NATIVE'), self.custombiosdir)
  534. biosdir_host = "%s/%s" % (self.get('STAGING_DIR_HOST'), self.custombiosdir)
  535. for i in (self.custombiosdir, biosdir_native, biosdir_host):
  536. if os.path.isdir(i):
  537. biosdir = i
  538. break
  539. if biosdir:
  540. logger.info("Assuming biosdir is: %s" % biosdir)
  541. self.qemu_opt_script += ' -L %s' % biosdir
  542. else:
  543. logger.error("Custom BIOS directory not found. Tried: %s, %s, and %s" % (self.custombiosdir, biosdir_native, biosdir_host))
  544. raise Exception("Invalid custombiosdir: %s" % self.custombiosdir)
  545. def check_mem(self):
  546. s = re.search('-m +([0-9]+)', self.qemu_opt_script)
  547. if s:
  548. self.set('QB_MEM', '-m %s' % s.group(1))
  549. elif not self.get('QB_MEM'):
  550. logger.info('QB_MEM is not set, use 512M by default')
  551. self.set('QB_MEM', '-m 512')
  552. self.kernel_cmdline_script += ' mem=%s' % self.get('QB_MEM').replace('-m','').strip() + 'M'
  553. self.qemu_opt_script += ' %s' % self.get('QB_MEM')
  554. def check_tcpserial(self):
  555. if self.tcpserial_portnum:
  556. if self.get('QB_TCPSERIAL_OPT'):
  557. self.qemu_opt_script += ' ' + self.get('QB_TCPSERIAL_OPT').replace('@PORT@', self.tcpserial_portnum)
  558. else:
  559. self.qemu_opt_script += ' -serial tcp:127.0.0.1:%s' % self.tcpserial_portnum
  560. def check_and_set(self):
  561. """Check configs sanity and set when needed"""
  562. self.validate_paths()
  563. if not self.slirp_enabled:
  564. check_tun()
  565. # Check audio
  566. if self.audio_enabled:
  567. if not self.get('QB_AUDIO_DRV'):
  568. raise Exception("QB_AUDIO_DRV is NULL, this board doesn't support audio")
  569. if not self.get('QB_AUDIO_OPT'):
  570. logger.warn('QB_AUDIO_OPT is NULL, you may need define it to make audio work')
  571. else:
  572. self.qemu_opt_script += ' %s' % self.get('QB_AUDIO_OPT')
  573. os.putenv('QEMU_AUDIO_DRV', self.get('QB_AUDIO_DRV'))
  574. else:
  575. os.putenv('QEMU_AUDIO_DRV', 'none')
  576. self.check_kvm()
  577. self.check_fstype()
  578. self.check_rootfs()
  579. self.check_ovmf()
  580. self.check_kernel()
  581. self.check_biosdir()
  582. self.check_mem()
  583. self.check_tcpserial()
  584. def read_qemuboot(self):
  585. if not self.qemuboot:
  586. if self.get('DEPLOY_DIR_IMAGE'):
  587. deploy_dir_image = self.get('DEPLOY_DIR_IMAGE')
  588. else:
  589. logger.info("Can't find qemuboot conf file, DEPLOY_DIR_IMAGE is NULL!")
  590. return
  591. if self.rootfs and not os.path.exists(self.rootfs):
  592. # Lazy rootfs
  593. machine = self.get('MACHINE')
  594. if not machine:
  595. machine = os.path.basename(deploy_dir_image)
  596. self.qemuboot = "%s/%s-%s.qemuboot.conf" % (deploy_dir_image,
  597. self.rootfs, machine)
  598. else:
  599. cmd = 'ls -t %s/*.qemuboot.conf' % deploy_dir_image
  600. logger.info('Running %s...' % cmd)
  601. qbs = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
  602. if qbs:
  603. for qb in qbs.split():
  604. # Don't use initramfs when other choices unless fstype is ramfs
  605. if '-initramfs-' in os.path.basename(qb) and self.fstype != 'cpio.gz':
  606. continue
  607. self.qemuboot = qb
  608. break
  609. if not self.qemuboot:
  610. # Use the first one when no choice
  611. self.qemuboot = qbs.split()[0]
  612. self.qbconfload = True
  613. if not self.qemuboot:
  614. # If we haven't found a .qemuboot.conf at this point it probably
  615. # doesn't exist, continue without
  616. return
  617. if not os.path.exists(self.qemuboot):
  618. raise Exception("Failed to find %s (wrong image name or BSP does not support running under qemu?)." % self.qemuboot)
  619. logger.info('CONFFILE: %s' % self.qemuboot)
  620. cf = configparser.ConfigParser()
  621. cf.read(self.qemuboot)
  622. for k, v in cf.items('config_bsp'):
  623. k_upper = k.upper()
  624. self.set(k_upper, v)
  625. def validate_paths(self):
  626. """Ensure all relevant path variables are set"""
  627. # When we're started with a *.qemuboot.conf arg assume that image
  628. # artefacts are relative to that file, rather than in whatever
  629. # directory DEPLOY_DIR_IMAGE in the conf file points to.
  630. if self.qbconfload:
  631. imgdir = os.path.realpath(os.path.dirname(self.qemuboot))
  632. if imgdir != os.path.realpath(self.get('DEPLOY_DIR_IMAGE')):
  633. logger.info('Setting DEPLOY_DIR_IMAGE to folder containing %s (%s)' % (self.qemuboot, imgdir))
  634. self.set('DEPLOY_DIR_IMAGE', imgdir)
  635. # If the STAGING_*_NATIVE directories from the config file don't exist
  636. # and we're in a sourced OE build directory try to extract the paths
  637. # from `bitbake -e`
  638. havenative = os.path.exists(self.get('STAGING_DIR_NATIVE')) and \
  639. os.path.exists(self.get('STAGING_BINDIR_NATIVE'))
  640. if not havenative:
  641. if not self.bitbake_e:
  642. self.load_bitbake_env()
  643. if self.bitbake_e:
  644. native_vars = ['STAGING_DIR_NATIVE']
  645. for nv in native_vars:
  646. s = re.search('^%s="(.*)"' % nv, self.bitbake_e, re.M)
  647. if s and s.group(1) != self.get(nv):
  648. logger.info('Overriding conf file setting of %s to %s from Bitbake environment' % (nv, s.group(1)))
  649. self.set(nv, s.group(1))
  650. else:
  651. # when we're invoked from a running bitbake instance we won't
  652. # be able to call `bitbake -e`, then try:
  653. # - get OE_TMPDIR from environment and guess paths based on it
  654. # - get OECORE_NATIVE_SYSROOT from environment (for sdk)
  655. tmpdir = self.get('OE_TMPDIR', None)
  656. oecore_native_sysroot = self.get('OECORE_NATIVE_SYSROOT', None)
  657. if tmpdir:
  658. logger.info('Setting STAGING_DIR_NATIVE and STAGING_BINDIR_NATIVE relative to OE_TMPDIR (%s)' % tmpdir)
  659. hostos, _, _, _, machine = os.uname()
  660. buildsys = '%s-%s' % (machine, hostos.lower())
  661. staging_dir_native = '%s/sysroots/%s' % (tmpdir, buildsys)
  662. self.set('STAGING_DIR_NATIVE', staging_dir_native)
  663. elif oecore_native_sysroot:
  664. logger.info('Setting STAGING_DIR_NATIVE to OECORE_NATIVE_SYSROOT (%s)' % oecore_native_sysroot)
  665. self.set('STAGING_DIR_NATIVE', oecore_native_sysroot)
  666. if self.get('STAGING_DIR_NATIVE'):
  667. # we have to assume that STAGING_BINDIR_NATIVE is at usr/bin
  668. staging_bindir_native = '%s/usr/bin' % self.get('STAGING_DIR_NATIVE')
  669. logger.info('Setting STAGING_BINDIR_NATIVE to %s' % staging_bindir_native)
  670. self.set('STAGING_BINDIR_NATIVE', '%s/usr/bin' % self.get('STAGING_DIR_NATIVE'))
  671. def print_config(self):
  672. logger.info('Continuing with the following parameters:\n')
  673. if not self.fstype in self.vmtypes:
  674. print('KERNEL: [%s]' % self.kernel)
  675. if self.dtb:
  676. print('DTB: [%s]' % self.dtb)
  677. print('MACHINE: [%s]' % self.get('MACHINE'))
  678. print('FSTYPE: [%s]' % self.fstype)
  679. if self.fstype == 'nfs':
  680. print('NFS_DIR: [%s]' % self.rootfs)
  681. else:
  682. print('ROOTFS: [%s]' % self.rootfs)
  683. if self.ovmf_bios:
  684. print('OVMF: %s' % self.ovmf_bios)
  685. print('CONFFILE: [%s]' % self.qemuboot)
  686. print('')
  687. def setup_nfs(self):
  688. if not self.nfs_server:
  689. if self.slirp_enabled:
  690. self.nfs_server = '10.0.2.2'
  691. else:
  692. self.nfs_server = '192.168.7.1'
  693. # Figure out a new nfs_instance to allow multiple qemus running.
  694. # CentOS 7.1's ps doesn't print full command line without "ww"
  695. # when invoke by subprocess.Popen().
  696. cmd = "ps auxww"
  697. ps = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
  698. pattern = '/bin/unfsd .* -i .*\.pid -e .*/exports([0-9]+) '
  699. all_instances = re.findall(pattern, ps, re.M)
  700. if all_instances:
  701. all_instances.sort(key=int)
  702. self.nfs_instance = int(all_instances.pop()) + 1
  703. mountd_rpcport = 21111 + self.nfs_instance
  704. nfsd_rpcport = 11111 + self.nfs_instance
  705. nfsd_port = 3049 + 2 * self.nfs_instance
  706. mountd_port = 3048 + 2 * self.nfs_instance
  707. # Export vars for runqemu-export-rootfs
  708. export_dict = {
  709. 'NFS_INSTANCE': self.nfs_instance,
  710. 'MOUNTD_RPCPORT': mountd_rpcport,
  711. 'NFSD_RPCPORT': nfsd_rpcport,
  712. 'NFSD_PORT': nfsd_port,
  713. 'MOUNTD_PORT': mountd_port,
  714. }
  715. for k, v in export_dict.items():
  716. # Use '%s' since they are integers
  717. os.putenv(k, '%s' % v)
  718. self.unfs_opts="nfsvers=3,port=%s,mountprog=%s,nfsprog=%s,udp,mountport=%s" % (nfsd_port, mountd_rpcport, nfsd_rpcport, mountd_port)
  719. # Extract .tar.bz2 or .tar.bz if no nfs dir
  720. if not (self.rootfs and os.path.isdir(self.rootfs)):
  721. src_prefix = '%s/%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_LINK_NAME'))
  722. dest = "%s-nfsroot" % src_prefix
  723. if os.path.exists('%s.pseudo_state' % dest):
  724. logger.info('Use %s as NFS_DIR' % dest)
  725. self.rootfs = dest
  726. else:
  727. src = ""
  728. src1 = '%s.tar.bz2' % src_prefix
  729. src2 = '%s.tar.gz' % src_prefix
  730. if os.path.exists(src1):
  731. src = src1
  732. elif os.path.exists(src2):
  733. src = src2
  734. if not src:
  735. raise Exception("No NFS_DIR is set, and can't find %s or %s to extract" % (src1, src2))
  736. logger.info('NFS_DIR not found, extracting %s to %s' % (src, dest))
  737. cmd = 'runqemu-extract-sdk %s %s' % (src, dest)
  738. logger.info('Running %s...' % cmd)
  739. if subprocess.call(cmd, shell=True) != 0:
  740. raise Exception('Failed to run %s' % cmd)
  741. self.clean_nfs_dir = True
  742. self.rootfs = dest
  743. # Start the userspace NFS server
  744. cmd = 'runqemu-export-rootfs start %s' % self.rootfs
  745. logger.info('Running %s...' % cmd)
  746. if subprocess.call(cmd, shell=True) != 0:
  747. raise Exception('Failed to run %s' % cmd)
  748. self.nfs_running = True
  749. def setup_slirp(self):
  750. """Setup user networking"""
  751. if self.fstype == 'nfs':
  752. self.setup_nfs()
  753. self.kernel_cmdline_script += ' ip=dhcp'
  754. # Port mapping
  755. hostfwd = ",hostfwd=tcp::2222-:22,hostfwd=tcp::2323-:23"
  756. qb_slirp_opt_default = "-netdev user,id=net0%s" % hostfwd
  757. qb_slirp_opt = self.get('QB_SLIRP_OPT') or qb_slirp_opt_default
  758. # Figure out the port
  759. ports = re.findall('hostfwd=[^-]*:([0-9]+)-[^,-]*', qb_slirp_opt)
  760. ports = [int(i) for i in ports]
  761. mac = 2
  762. # Find a free port to avoid conflicts
  763. for p in ports[:]:
  764. p_new = p
  765. while not check_free_port('localhost', p_new):
  766. p_new += 1
  767. mac += 1
  768. while p_new in ports:
  769. p_new += 1
  770. mac += 1
  771. if p != p_new:
  772. ports.append(p_new)
  773. qb_slirp_opt = re.sub(':%s-' % p, ':%s-' % p_new, qb_slirp_opt)
  774. logger.info("Port forward changed: %s -> %s" % (p, p_new))
  775. mac = "%s%02x" % (self.mac_slirp, mac)
  776. self.set('NETWORK_CMD', '%s %s' % (self.network_device.replace('@MAC@', mac), qb_slirp_opt))
  777. # Print out port foward
  778. hostfwd = re.findall('(hostfwd=[^,]*)', qb_slirp_opt)
  779. if hostfwd:
  780. logger.info('Port forward: %s' % ' '.join(hostfwd))
  781. def setup_tap(self):
  782. """Setup tap"""
  783. # This file is created when runqemu-gen-tapdevs creates a bank of tap
  784. # devices, indicating that the user should not bring up new ones using
  785. # sudo.
  786. nosudo_flag = '/etc/runqemu-nosudo'
  787. self.qemuifup = shutil.which('runqemu-ifup')
  788. self.qemuifdown = shutil.which('runqemu-ifdown')
  789. ip = shutil.which('ip')
  790. lockdir = "/tmp/qemu-tap-locks"
  791. if not (self.qemuifup and self.qemuifdown and ip):
  792. raise OEPathError("runqemu-ifup, runqemu-ifdown or ip not found")
  793. if not os.path.exists(lockdir):
  794. # There might be a race issue when multi runqemu processess are
  795. # running at the same time.
  796. try:
  797. os.mkdir(lockdir)
  798. except FileExistsError:
  799. pass
  800. cmd = '%s link' % ip
  801. logger.info('Running %s...' % cmd)
  802. ip_link = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
  803. # Matches line like: 6: tap0: <foo>
  804. possibles = re.findall('^[1-9]+: +(tap[0-9]+): <.*', ip_link, re.M)
  805. tap = ""
  806. for p in possibles:
  807. lockfile = os.path.join(lockdir, p)
  808. if os.path.exists('%s.skip' % lockfile):
  809. logger.info('Found %s.skip, skipping %s' % (lockfile, p))
  810. continue
  811. self.lock = lockfile + '.lock'
  812. if self.acquire_lock():
  813. tap = p
  814. logger.info("Using preconfigured tap device %s" % tap)
  815. logger.info("If this is not intended, touch %s.skip to make runqemu skip %s." %(lockfile, tap))
  816. break
  817. if not tap:
  818. if os.path.exists(nosudo_flag):
  819. logger.error("Error: There are no available tap devices to use for networking,")
  820. logger.error("and I see %s exists, so I am not going to try creating" % nosudo_flag)
  821. raise Exception("a new one with sudo.")
  822. gid = os.getgid()
  823. uid = os.getuid()
  824. logger.info("Setting up tap interface under sudo")
  825. cmd = 'sudo %s %s %s %s' % (self.qemuifup, uid, gid, self.bindir_native)
  826. tap = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8').rstrip('\n')
  827. lockfile = os.path.join(lockdir, tap)
  828. self.lock = lockfile + '.lock'
  829. self.acquire_lock()
  830. self.cleantap = True
  831. logger.info('Created tap: %s' % tap)
  832. if not tap:
  833. logger.error("Failed to setup tap device. Run runqemu-gen-tapdevs to manually create.")
  834. return 1
  835. self.tap = tap
  836. tapnum = int(tap[3:])
  837. gateway = tapnum * 2 + 1
  838. client = gateway + 1
  839. if self.fstype == 'nfs':
  840. self.setup_nfs()
  841. netconf = "192.168.7.%s::192.168.7.%s:255.255.255.0" % (client, gateway)
  842. logger.info("Network configuration: %s", netconf)
  843. self.kernel_cmdline_script += " ip=%s" % netconf
  844. mac = "%s%02x" % (self.mac_tap, client)
  845. qb_tap_opt = self.get('QB_TAP_OPT')
  846. if qb_tap_opt:
  847. qemu_tap_opt = qb_tap_opt.replace('@TAP@', tap)
  848. else:
  849. qemu_tap_opt = "-netdev tap,id=net0,ifname=%s,script=no,downscript=no" % (self.tap)
  850. if self.vhost_enabled:
  851. qemu_tap_opt += ',vhost=on'
  852. self.set('NETWORK_CMD', '%s %s' % (self.network_device.replace('@MAC@', mac), qemu_tap_opt))
  853. def setup_network(self):
  854. if self.get('QB_NET') == 'none':
  855. return
  856. cmd = "stty -g"
  857. self.saved_stty = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
  858. self.network_device = self.get('QB_NETWORK_DEVICE') or self.network_device
  859. if self.slirp_enabled:
  860. self.setup_slirp()
  861. else:
  862. self.setup_tap()
  863. def setup_rootfs(self):
  864. if self.get('QB_ROOTFS') == 'none':
  865. return
  866. rootfs_format = self.fstype if self.fstype in ('vmdk', 'qcow2', 'vdi') else 'raw'
  867. qb_rootfs_opt = self.get('QB_ROOTFS_OPT')
  868. if qb_rootfs_opt:
  869. self.rootfs_options = qb_rootfs_opt.replace('@ROOTFS@', self.rootfs)
  870. else:
  871. self.rootfs_options = '-drive file=%s,if=virtio,format=%s' % (self.rootfs, rootfs_format)
  872. if self.fstype in ('cpio.gz', 'cpio'):
  873. self.kernel_cmdline = 'root=/dev/ram0 rw debugshell'
  874. self.rootfs_options = '-initrd %s' % self.rootfs
  875. else:
  876. vm_drive = ''
  877. if self.fstype in self.vmtypes:
  878. if self.fstype == 'iso':
  879. vm_drive = '-cdrom %s' % self.rootfs
  880. elif self.get('QB_DRIVE_TYPE'):
  881. drive_type = self.get('QB_DRIVE_TYPE')
  882. if drive_type.startswith("/dev/sd"):
  883. logger.info('Using scsi drive')
  884. vm_drive = '-drive if=none,id=hd,file=%s,format=%s -device virtio-scsi-pci,id=scsi -device scsi-hd,drive=hd' \
  885. % (self.rootfs, rootfs_format)
  886. elif drive_type.startswith("/dev/hd"):
  887. logger.info('Using ide drive')
  888. vm_drive = "%s,format=%s" % (self.rootfs, rootfs_format)
  889. else:
  890. logger.warn("Unknown QB_DRIVE_TYPE: %s" % drive_type)
  891. if not vm_drive:
  892. logger.warn("Failed to figure out drive type, consider define or fix QB_DRIVE_TYPE")
  893. logger.warn('Trying to use virtio block drive')
  894. vm_drive = '-drive if=virtio,file=%s,format=%s' % (self.rootfs, rootfs_format)
  895. self.rootfs_options = '%s -no-reboot' % vm_drive
  896. self.kernel_cmdline = 'root=%s rw highres=off' % (self.get('QB_KERNEL_ROOT'))
  897. if self.fstype == 'nfs':
  898. self.rootfs_options = ''
  899. k_root = '/dev/nfs nfsroot=%s:%s,%s' % (self.nfs_server, self.rootfs, self.unfs_opts)
  900. self.kernel_cmdline = 'root=%s rw highres=off' % k_root
  901. if self.fstype == 'none':
  902. self.rootfs_options = ''
  903. self.set('ROOTFS_OPTIONS', self.rootfs_options)
  904. def guess_qb_system(self):
  905. """attempt to determine the appropriate qemu-system binary"""
  906. mach = self.get('MACHINE')
  907. if not mach:
  908. search = '.*(qemux86-64|qemux86|qemuarm64|qemuarm|qemumips64|qemumips64el|qemumipsel|qemumips|qemuppc).*'
  909. if self.rootfs:
  910. match = re.match(search, self.rootfs)
  911. if match:
  912. mach = match.group(1)
  913. elif self.kernel:
  914. match = re.match(search, self.kernel)
  915. if match:
  916. mach = match.group(1)
  917. if not mach:
  918. return None
  919. if mach == 'qemuarm':
  920. qbsys = 'arm'
  921. elif mach == 'qemuarm64':
  922. qbsys = 'aarch64'
  923. elif mach == 'qemux86':
  924. qbsys = 'i386'
  925. elif mach == 'qemux86-64':
  926. qbsys = 'x86_64'
  927. elif mach == 'qemuppc':
  928. qbsys = 'ppc'
  929. elif mach == 'qemumips':
  930. qbsys = 'mips'
  931. elif mach == 'qemumips64':
  932. qbsys = 'mips64'
  933. elif mach == 'qemumipsel':
  934. qbsys = 'mipsel'
  935. elif mach == 'qemumips64el':
  936. qbsys = 'mips64el'
  937. return 'qemu-system-%s' % qbsys
  938. def setup_final(self):
  939. qemu_system = self.get('QB_SYSTEM_NAME')
  940. if not qemu_system:
  941. qemu_system = self.guess_qb_system()
  942. if not qemu_system:
  943. raise Exception("Failed to boot, QB_SYSTEM_NAME is NULL!")
  944. qemu_bin = '%s/%s' % (self.bindir_native, qemu_system)
  945. # It is possible to have qemu-native in ASSUME_PROVIDED, and it won't
  946. # find QEMU in sysroot, it needs to use host's qemu.
  947. if not os.path.exists(qemu_bin):
  948. logger.info("QEMU binary not found in %s, trying host's QEMU" % qemu_bin)
  949. for path in (os.environ['PATH'] or '').split(':'):
  950. qemu_bin_tmp = os.path.join(path, qemu_system)
  951. logger.info("Trying: %s" % qemu_bin_tmp)
  952. if os.path.exists(qemu_bin_tmp):
  953. qemu_bin = qemu_bin_tmp
  954. if not os.path.isabs(qemu_bin):
  955. qemu_bin = os.path.abspath(qemu_bin)
  956. logger.info("Using host's QEMU: %s" % qemu_bin)
  957. break
  958. if not os.access(qemu_bin, os.X_OK):
  959. raise OEPathError("No QEMU binary '%s' could be found" % qemu_bin)
  960. check_libgl(qemu_bin)
  961. self.qemu_opt = "%s %s %s %s" % (qemu_bin, self.get('NETWORK_CMD'), self.get('ROOTFS_OPTIONS'), self.get('QB_OPT_APPEND'))
  962. for ovmf in self.ovmf_bios:
  963. format = ovmf.rsplit('.', 1)[-1]
  964. self.qemu_opt += ' -drive if=pflash,format=%s,file=%s' % (format, ovmf)
  965. if self.ovmf_bios:
  966. # OVMF only supports normal VGA, i.e. we need to override a -vga vmware
  967. # that gets added for example for normal qemux86.
  968. self.qemu_opt += ' -vga std'
  969. self.qemu_opt += ' ' + self.qemu_opt_script
  970. if self.snapshot:
  971. self.qemu_opt += " -snapshot"
  972. if self.serialstdio:
  973. logger.info("Interrupt character is '^]'")
  974. cmd = "stty intr ^]"
  975. subprocess.call(cmd, shell=True)
  976. first_serial = ""
  977. if not re.search("-nographic", self.qemu_opt):
  978. first_serial = "-serial mon:vc"
  979. # We always want a ttyS1. Since qemu by default adds a serial
  980. # port when nodefaults is not specified, it seems that all that
  981. # would be needed is to make sure a "-serial" is there. However,
  982. # it appears that when "-serial" is specified, it ignores the
  983. # default serial port that is normally added. So here we make
  984. # sure to add two -serial if there are none. And only one if
  985. # there is one -serial already.
  986. serial_num = len(re.findall("-serial", self.qemu_opt))
  987. if serial_num == 0:
  988. self.qemu_opt += " %s %s" % (first_serial, self.get("QB_SERIAL_OPT"))
  989. elif serial_num == 1:
  990. self.qemu_opt += " %s" % self.get("QB_SERIAL_OPT")
  991. # We always wants ttyS0 and ttyS1 in qemu machines (see SERIAL_CONSOLES),
  992. # if not serial or serialtcp options was specified only ttyS0 is created
  993. # and sysvinit shows an error trying to enable ttyS1:
  994. # INIT: Id "S1" respawning too fast: disabled for 5 minutes
  995. serial_num = len(re.findall("-serial", self.qemu_opt))
  996. if serial_num == 0:
  997. if re.search("-nographic", self.qemu_opt):
  998. self.qemu_opt += " -serial mon:stdio -serial null"
  999. else:
  1000. self.qemu_opt += " -serial mon:vc -serial null"
  1001. def start_qemu(self):
  1002. if self.kernel:
  1003. kernel_opts = "-kernel %s -append '%s %s %s %s'" % (self.kernel, self.kernel_cmdline,
  1004. self.kernel_cmdline_script, self.get('QB_KERNEL_CMDLINE_APPEND'),
  1005. self.bootparams)
  1006. if self.dtb:
  1007. kernel_opts += " -dtb %s" % self.dtb
  1008. else:
  1009. kernel_opts = ""
  1010. cmd = "%s %s" % (self.qemu_opt, kernel_opts)
  1011. logger.info('Running %s' % cmd)
  1012. if subprocess.call(cmd, shell=True) != 0:
  1013. raise Exception('Failed to run %s' % cmd)
  1014. def cleanup(self):
  1015. if self.cleantap:
  1016. cmd = 'sudo %s %s %s' % (self.qemuifdown, self.tap, self.bindir_native)
  1017. logger.info('Running %s' % cmd)
  1018. subprocess.call(cmd, shell=True)
  1019. if self.lock_descriptor:
  1020. logger.info("Releasing lockfile for tap device '%s'" % self.tap)
  1021. self.release_lock()
  1022. if self.nfs_running:
  1023. logger.info("Shutting down the userspace NFS server...")
  1024. cmd = "runqemu-export-rootfs stop %s" % self.rootfs
  1025. logger.info('Running %s' % cmd)
  1026. subprocess.call(cmd, shell=True)
  1027. if self.saved_stty:
  1028. cmd = "stty %s" % self.saved_stty
  1029. subprocess.call(cmd, shell=True)
  1030. if self.clean_nfs_dir:
  1031. logger.info('Removing %s' % self.rootfs)
  1032. shutil.rmtree(self.rootfs)
  1033. shutil.rmtree('%s.pseudo_state' % self.rootfs)
  1034. def load_bitbake_env(self, mach=None):
  1035. if self.bitbake_e:
  1036. return
  1037. bitbake = shutil.which('bitbake')
  1038. if not bitbake:
  1039. return
  1040. if not mach:
  1041. mach = self.get('MACHINE')
  1042. if mach:
  1043. cmd = 'MACHINE=%s bitbake -e' % mach
  1044. else:
  1045. cmd = 'bitbake -e'
  1046. logger.info('Running %s...' % cmd)
  1047. try:
  1048. self.bitbake_e = subprocess.check_output(cmd, shell=True).decode('utf-8')
  1049. except subprocess.CalledProcessError as err:
  1050. self.bitbake_e = ''
  1051. logger.warn("Couldn't run 'bitbake -e' to gather environment information:\n%s" % err.output.decode('utf-8'))
  1052. @property
  1053. def bindir_native(self):
  1054. result = self.get('STAGING_BINDIR_NATIVE')
  1055. if result and os.path.exists(result):
  1056. return result
  1057. cmd = 'bitbake qemu-helper-native -e'
  1058. logger.info('Running %s...' % cmd)
  1059. out = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
  1060. out = out.stdout.read().decode('utf-8')
  1061. match = re.search('^STAGING_BINDIR_NATIVE="(.*)"', out, re.M)
  1062. if match:
  1063. result = match.group(1)
  1064. if os.path.exists(result):
  1065. self.set('STAGING_BINDIR_NATIVE', result)
  1066. return result
  1067. raise Exception("Native sysroot directory %s doesn't exist" % result)
  1068. else:
  1069. raise Exception("Can't find STAGING_BINDIR_NATIVE in '%s' output" % cmd)
  1070. def main():
  1071. if "help" in sys.argv or '-h' in sys.argv or '--help' in sys.argv:
  1072. print_usage()
  1073. return 0
  1074. config = BaseConfig()
  1075. try:
  1076. config.check_args()
  1077. except Exception as esc:
  1078. logger.error(esc)
  1079. logger.error("Try 'runqemu help' on how to use it")
  1080. return 1
  1081. config.read_qemuboot()
  1082. config.check_and_set()
  1083. config.print_config()
  1084. try:
  1085. config.setup_network()
  1086. config.setup_rootfs()
  1087. config.setup_final()
  1088. config.start_qemu()
  1089. finally:
  1090. config.cleanup()
  1091. return 0
  1092. if __name__ == "__main__":
  1093. try:
  1094. ret = main()
  1095. except OEPathError as err:
  1096. ret = 1
  1097. logger.error(err.message)
  1098. except Exception as esc:
  1099. ret = 1
  1100. import traceback
  1101. traceback.print_exc()
  1102. sys.exit(ret)