runqemu 55 KB

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