source: mainline/tools/ew.py@ 06b8383

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 06b8383 was edb57bc6, checked in by Jakub Jermář <jakub@…>, 5 years ago

Request python3 explicitly in ew.py

  • Property mode set to 100755
File size: 14.6 KB
Line 
1#!/usr/bin/env python3
2#
3# Copyright (c) 2013 Jakub Jermar
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions
8# are met:
9#
10# - Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12# - Redistributions in binary form must reproduce the above copyright
13# notice, this list of conditions and the following disclaimer in the
14# documentation and/or other materials provided with the distribution.
15# - The name of the author may not be used to endorse or promote products
16# derived from this software without specific prior written permission.
17#
18# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28#
29
30
31"""
32Emulator wrapper for running HelenOS
33"""
34
35import inspect
36import os
37import platform
38import re
39import subprocess
40import sys
41import _thread
42import time
43
44overrides = {}
45
46CONFIG = 'Makefile.config'
47
48TOOLS_DIR = os.path.dirname(inspect.getabsfile(inspect.currentframe()))
49
50def read_config():
51 "Read HelenOS build configuration"
52
53 inf = open(CONFIG, 'r')
54 config = {}
55
56 for line in inf:
57 res = re.match(r'^(?:#!# )?([^#]\w*)\s*=\s*(.*?)\s*$', line)
58 if (res):
59 config[res.group(1)] = res.group(2)
60
61 inf.close()
62 return config
63
64def is_override(str):
65 if str in overrides.keys():
66 return overrides[str]
67 return False
68
69def cfg_get(platform, machine, processor):
70 if machine == "" or "run" in emulators[platform]:
71 return emulators[platform]
72 elif processor == "" or "run" in emulators[platform][machine]:
73 return emulators[platform][machine]
74 else:
75 return emulators[platform][machine][processor]
76
77def termemu_detect():
78 emus = ['gnome-terminal', 'xfce4-terminal', 'xterm']
79 for termemu in emus:
80 try:
81 subprocess.check_output('which ' + termemu, shell = True)
82 return termemu
83 except:
84 pass
85
86 print('Could not find any of the terminal emulators %s.'%(emus))
87 sys.exit(1)
88
89def run_in_console(cmd, title):
90 temu = termemu_detect()
91 if temu == 'gnome-terminal':
92 cmdline = temu + ' -- ' + cmd
93 else:
94 ecmd = cmd.replace('"', '\\"')
95 cmdline = temu + ' -T ' + '"' + title + '"' + ' -e "' + ecmd + '"'
96
97 print(cmdline)
98 if not is_override('dryrun'):
99 subprocess.call(cmdline, shell = True)
100
101def get_host_native_width():
102 return int(platform.architecture()[0].strip('bit'))
103
104def pc_options(guest_width):
105 opts = ''
106
107 # Do not enable KVM if running 64 bits HelenOS
108 # on 32 bits host
109 host_width = get_host_native_width()
110 if guest_width <= host_width and not is_override('nokvm'):
111 opts = opts + ' -enable-kvm'
112
113 # Remove the leading space
114 return opts[1:]
115
116def malta_options():
117 return '-cpu 4Kc -append "console=devices/\\hw\\pci0\\00:0a.0\\com1\\a"'
118
119def find_firmware(name, environ_var, default_paths, extra_info=None):
120 """Find firmware image(s)."""
121
122 if environ_var in os.environ:
123 return os.environ[environ_var]
124
125 for path in default_paths:
126 if os.path.exists(path):
127 return path
128
129 sys.stderr.write("Cannot find %s binary image(s)!\n" % name)
130 sys.stderr.write(
131 "Either set %s environment variable accordingly or place the image(s) in one of the default locations: %s.\n" %
132 (environ_var, ", ".join(default_paths)))
133 if extra_info is not None:
134 sys.stderr.write(extra_info)
135 return None
136
137def platform_to_qemu_options(platform, machine, processor):
138 if platform == 'amd64':
139 return 'system-x86_64', pc_options(64)
140 elif platform == 'arm32':
141 return 'system-arm', '-M integratorcp'
142 elif platform == 'arm64':
143 # Search for the EDK2 firmware image
144 default_paths = (
145 '/usr/local/qemu-efi-aarch64/QEMU_EFI.fd', # Custom
146 '/usr/share/edk2/aarch64/QEMU_EFI.fd', # Fedora
147 '/usr/share/qemu-efi-aarch64/QEMU_EFI.fd', # Ubuntu
148 )
149 extra_info = ("Pre-compiled binary can be obtained from "
150 "http://snapshots.linaro.org/components/kernel/leg-virt-tianocore-edk2-upstream/latest/QEMU-AARCH64/RELEASE_GCC5/QEMU_EFI.fd.\n")
151 efi_path = find_firmware(
152 "EDK2", 'EW_QEMU_EFI_AARCH64', default_paths, extra_info)
153 if efi_path is None:
154 raise Exception
155
156 return 'system-aarch64', \
157 '-M virt -cpu cortex-a57 -m 1024 -bios %s' % efi_path
158 elif platform == 'ia32':
159 return 'system-i386', pc_options(32)
160 elif platform == 'mips32':
161 if machine == 'lmalta':
162 return 'system-mipsel', malta_options()
163 elif machine == 'bmalta':
164 return 'system-mips', malta_options()
165 elif platform == 'ppc32':
166 return 'system-ppc', '-m 256'
167 elif platform == 'sparc64':
168 if machine != 'generic':
169 raise Exception
170 if processor == 'us':
171 return 'system-sparc64', '-M sun4u --prom-env boot-args="console=devices/\\hw\\pci0\\01:01.0\\com1\\a"'
172
173 # processor = 'sun4v'
174 opensparc_bins = find_firmware(
175 "OpenSPARC", 'OPENSPARC_BINARIES',
176 ('/usr/local/opensparc/image/', ))
177 if opensparc_bins is None:
178 raise Exception
179
180 return 'system-sparc64', '-M niagara -m 256 -L %s' % (opensparc_bins)
181
182
183def hdisk_mk():
184 if not os.path.exists('hdisk.img'):
185 subprocess.call(TOOLS_DIR + '/mkfat.py 1048576 dist/data hdisk.img', shell = True)
186
187def qemu_bd_options():
188 if is_override('nohdd'):
189 return ''
190
191 hdisk_mk()
192
193 hdd_options = ''
194 if 'hdd' in overrides.keys():
195 if 'ata' in overrides['hdd'].keys():
196 hdd_options += ''
197 elif 'virtio-blk' in overrides['hdd'].keys():
198 hdd_options += ',if=virtio'
199
200 return ' -drive file=hdisk.img,index=0,media=disk,format=raw' + hdd_options
201
202def qemu_nic_ne2k_options():
203 return ' -device ne2k_isa,irq=5,netdev=n1'
204
205def qemu_nic_e1k_options():
206 return ' -device e1000,netdev=n1'
207
208def qemu_nic_rtl8139_options():
209 return ' -device rtl8139,netdev=n1'
210
211def qemu_nic_virtio_options():
212 return ' -device virtio-net,netdev=n1'
213
214def qemu_net_options():
215 if is_override('nonet'):
216 return ''
217
218 nic_options = ''
219 if 'net' in overrides.keys():
220 if 'e1k' in overrides['net'].keys():
221 nic_options += qemu_nic_e1k_options()
222 if 'rtl8139' in overrides['net'].keys():
223 nic_options += qemu_nic_rtl8139_options()
224 if 'ne2k' in overrides['net'].keys():
225 nic_options += qemu_nic_ne2k_options()
226 if 'virtio-net' in overrides['net'].keys():
227 nic_options += qemu_nic_virtio_options()
228 else:
229 # Use the default NIC
230 nic_options += qemu_nic_e1k_options()
231
232 return nic_options + ' -netdev user,id=n1,hostfwd=udp::8080-:8080,hostfwd=udp::8081-:8081,hostfwd=tcp::8080-:8080,hostfwd=tcp::8081-:8081,hostfwd=tcp::2223-:2223'
233
234def qemu_usb_options():
235 if is_override('nousb'):
236 return ''
237 return ' -usb'
238
239def qemu_xhci_options():
240 if is_override('noxhci'):
241 return ''
242 return ' -device nec-usb-xhci,id=xhci'
243
244def qemu_tablet_options():
245 if is_override('notablet') or (is_override('nousb') and is_override('noxhci')):
246 return ''
247 return ' -device usb-tablet'
248
249def qemu_audio_options():
250 if is_override('nosnd'):
251 return ''
252 return ' -device intel-hda -device hda-duplex'
253
254def qemu_run(platform, machine, processor):
255 cfg = cfg_get(platform, machine, processor)
256 suffix, options = platform_to_qemu_options(platform, machine, processor)
257 cmd = 'qemu-' + suffix
258
259 cmdline = cmd
260 if 'qemu_path' in overrides.keys():
261 cmdline = overrides['qemu_path'] + cmd
262
263 if options != '':
264 cmdline += ' ' + options
265
266 if (not 'hdd' in cfg.keys() or cfg['hdd']):
267 cmdline += qemu_bd_options()
268 if (not 'net' in cfg.keys()) or cfg['net']:
269 cmdline += qemu_net_options()
270 if (not 'usb' in cfg.keys()) or cfg['usb']:
271 cmdline += qemu_usb_options()
272 if (not 'xhci' in cfg.keys()) or cfg['xhci']:
273 cmdline += qemu_xhci_options()
274 if (not 'tablet' in cfg.keys()) or cfg['tablet']:
275 cmdline += qemu_tablet_options()
276 if (not 'audio' in cfg.keys()) or cfg['audio']:
277 cmdline += qemu_audio_options()
278
279 console = ('console' in cfg.keys() and cfg['console'])
280
281 if (is_override('nographic')):
282 cmdline += ' -nographic'
283
284 if (not console and (not is_override('nographic')) and not is_override('noserial')):
285 cmdline += ' -serial stdio'
286
287 if (is_override('bigmem')):
288 cmdline += ' -m 4G'
289
290 if cfg['image'] == 'image.iso':
291 cmdline += ' -boot d -cdrom image.iso'
292 elif cfg['image'] == 'image.iso@arm64':
293 # Define image.iso cdrom backend.
294 cmdline += ' -drive if=none,file=image.iso,id=cdrom,media=cdrom'
295 # Define scsi bus.
296 cmdline += ' -device virtio-scsi-device'
297 # Define cdrom frontend connected to this scsi bus.
298 cmdline += ' -device scsi-cd,drive=cdrom'
299 elif cfg['image'] == 'image.boot':
300 cmdline += ' -kernel image.boot'
301 else:
302 cmdline += ' ' + cfg['image']
303
304 if console:
305 cmdline += ' -nographic'
306
307 title = 'HelenOS/' + platform
308 if machine != '':
309 title += ' on ' + machine
310 if 'expect' in cfg.keys():
311 cmdline = 'expect -c \'spawn %s; expect "%s" { send "%s" } timeout exp_continue; interact\'' % (cmdline, cfg['expect']['src'], cfg['expect']['dst'])
312 run_in_console(cmdline, title)
313 else:
314 print(cmdline)
315 if not is_override('dryrun'):
316 subprocess.call(cmdline, shell = True)
317
318def ski_run(platform, machine, processor):
319 run_in_console('ski -i ' + TOOLS_DIR + '/conf/ski.conf', 'HelenOS/ia64 on ski')
320
321def msim_run(platform, machine, processor):
322 hdisk_mk()
323 run_in_console('msim -c ' + TOOLS_DIR + '/conf/msim.conf', 'HelenOS/mips32 on msim')
324
325def spike_run(platform, machine, processor):
326 run_in_console('spike -m1073741824:1073741824 image.boot', 'HelenOS/risvc64 on Spike')
327
328emulators = {
329 'amd64' : {
330 'run' : qemu_run,
331 'image' : 'image.iso'
332 },
333 'arm32' : {
334 'integratorcp' : {
335 'run' : qemu_run,
336 'image' : 'image.boot',
337 'net' : False,
338 'audio' : False,
339 'xhci' : False,
340 'tablet' : False
341 }
342 },
343 'arm64' : {
344 'virt' : {
345 'run' : qemu_run,
346 'image' : 'image.iso@arm64',
347 'audio' : False,
348 'console' : True,
349 'hdd' : False,
350 'net' : False,
351 'tablet' : False,
352 'usb' : False,
353 'xhci' : False
354 }
355 },
356 'ia32' : {
357 'run' : qemu_run,
358 'image' : 'image.iso'
359 },
360 'ia64' : {
361 'ski' : {
362 'run' : ski_run
363 }
364 },
365 'mips32' : {
366 'msim' : {
367 'run' : msim_run
368 },
369 'lmalta' : {
370 'run' : qemu_run,
371 'image' : 'image.boot',
372 'console' : True
373 },
374 'bmalta' : {
375 'run' : qemu_run,
376 'image' : 'image.boot',
377 'console' : True
378 },
379 },
380 'ppc32' : {
381 'run' : qemu_run,
382 'image' : 'image.iso',
383 'audio' : False
384 },
385 'riscv64' : {
386 'run' : spike_run,
387 'image' : 'image.boot'
388 },
389 'sparc64' : {
390 'generic' : {
391 'us' : {
392 'run' : qemu_run,
393 'image' : 'image.iso',
394 'audio' : False,
395 'console' : True,
396 'net' : False,
397 'usb' : False,
398 'xhci' : False,
399 'tablet' : False
400 },
401 'sun4v' : {
402 'run' : qemu_run,
403 'image' : '-drive if=pflash,readonly=on,file=image.iso',
404 'audio' : False,
405 'console' : True,
406 'net' : False,
407 'usb' : False,
408 'xhci' : False,
409 'tablet' : False,
410 'expect' : {
411 'src' : 'ok ',
412 'dst' : 'boot\n'
413 },
414 }
415 }
416 },
417}
418
419def usage():
420 print("%s - emulator wrapper for running HelenOS\n" % os.path.basename(sys.argv[0]))
421 print("%s [-d] [-h] [-net e1k|rtl8139|ne2k|virtio-net] [-hdd ata|virtio-blk] [-nohdd] [-nokvm] [-nonet] [-nosnd] [-nousb] [-noxhci] [-notablet]\n" %
422 os.path.basename(sys.argv[0]))
423 print("-d\tDry run: do not run the emulation, just print the command line.")
424 print("-h\tPrint the usage information and exit.")
425 print("-nohdd\tDisable hard disk, if applicable.")
426 print("-nokvm\tDisable KVM, if applicable.")
427 print("-nonet\tDisable networking support, if applicable.")
428 print("-nosnd\tDisable sound, if applicable.")
429 print("-nousb\tDisable USB support, if applicable.")
430 print("-noxhci\tDisable XHCI support, if applicable.")
431 print("-notablet\tDisable USB tablet (use only relative-position PS/2 mouse instead), if applicable.")
432 print("-nographic\tDisable graphical output. Serial port output must be enabled for this to be useful.")
433 print("-noserial\tDisable serial port output in the terminal.")
434 print("-bigmem\tSets maximum RAM size to 4GB.")
435
436def fail(platform, machine):
437 print("Cannot start emulation for the chosen configuration. (%s/%s)" % (platform, machine))
438
439
440def run():
441 expect_nic = False
442 expect_hdd = False
443 expect_qemu = False
444
445 for i in range(1, len(sys.argv)):
446
447 if expect_nic:
448 expect_nic = False
449 if not 'net' in overrides.keys():
450 overrides['net'] = {}
451 if sys.argv[i] == 'e1k':
452 overrides['net']['e1k'] = True
453 elif sys.argv[i] == 'rtl8139':
454 overrides['net']['rtl8139'] = True
455 elif sys.argv[i] == 'ne2k':
456 overrides['net']['ne2k'] = True
457 elif sys.argv[i] == 'virtio-net':
458 overrides['net']['virtio-net'] = True
459 else:
460 usage()
461 exit()
462 continue
463
464 if expect_hdd:
465 expect_hdd = False
466 if not 'hdd' in overrides.keys():
467 overrides['hdd'] = {}
468 if sys.argv[i] == 'ata':
469 overrides['hdd']['ata'] = True
470 elif sys.argv[i] == 'virtio-blk':
471 overrides['hdd']['virtio-blk'] = True
472 else:
473 usage()
474 exit()
475 continue
476
477 if expect_qemu:
478 expect_qemu = False
479 overrides['qemu_path'] = sys.argv[i]
480
481 elif sys.argv[i] == '-h':
482 usage()
483 exit()
484 elif sys.argv[i] == '-d':
485 overrides['dryrun'] = True
486 elif sys.argv[i] == '-net' and i < len(sys.argv) - 1:
487 expect_nic = True
488 elif sys.argv[i] == '-hdd' and i < len(sys.argv) - 1:
489 expect_hdd = True
490 elif sys.argv[i] == '-nohdd':
491 overrides['nohdd'] = True
492 elif sys.argv[i] == '-nokvm':
493 overrides['nokvm'] = True
494 elif sys.argv[i] == '-nonet':
495 overrides['nonet'] = True
496 elif sys.argv[i] == '-nosnd':
497 overrides['nosnd'] = True
498 elif sys.argv[i] == '-nousb':
499 overrides['nousb'] = True
500 elif sys.argv[i] == '-noxhci':
501 overrides['noxhci'] = True
502 elif sys.argv[i] == '-notablet':
503 overrides['notablet'] = True
504 elif sys.argv[i] == '-nographic':
505 overrides['nographic'] = True
506 elif sys.argv[i] == '-bigmem':
507 overrides['bigmem'] = True
508 elif sys.argv[i] == '-noserial':
509 overrides['noserial'] = True
510 elif sys.argv[i] == '-qemu_path' and i < len(sys.argv) - 1:
511 expect_qemu = True
512 else:
513 usage()
514 exit()
515
516 config = read_config()
517
518 if 'PLATFORM' in config.keys():
519 platform = config['PLATFORM']
520 else:
521 platform = ''
522
523 if 'MACHINE' in config.keys():
524 mach = config['MACHINE']
525 else:
526 mach = ''
527
528 if 'PROCESSOR' in config.keys():
529 processor = config['PROCESSOR']
530 else:
531 processor = ''
532
533 try:
534 emu_run = cfg_get(platform, mach, processor)['run']
535 emu_run(platform, mach, processor)
536 except:
537 fail(platform, mach)
538 return
539
540run()
Note: See TracBrowser for help on using the repository browser.