runqemu 54 KB

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