runqemu 53 KB

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