runqemu 42 KB

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