runqemu 51 KB

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