source: mainline/tools/ew.py@ 77578e8

Last change on this file since 77578e8 was 27dd0e6, checked in by Jiří Zárevúcky <zarevucky.jiri@…>, 3 years ago

update files with python3 shebang

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