-
Notifications
You must be signed in to change notification settings - Fork 7
/
boot-qemu.py
executable file
·937 lines (741 loc) · 30.8 KB
/
boot-qemu.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
#!/usr/bin/env python3
# pylint: disable=invalid-name
from argparse import ArgumentParser
import contextlib
import os
from pathlib import Path
import platform
import re
import shlex
import shutil
import subprocess
import sys
import utils
SUPPORTED_ARCHES = [
'arm',
'arm32_v5',
'arm32_v6',
'arm32_v7',
'arm64',
'arm64be',
'loongarch',
'm68k',
'mips',
'mipsel',
'ppc32',
'ppc32_mac',
'ppc64',
'ppc64le',
'riscv',
's390',
'sparc64',
'x86',
'x86_64',
]
class QEMURunner:
def __init__(self):
# Properties that can be adjusted by the user or class
self.cmdline = []
self.efi = False
self.gdb = False
self.gdb_bin = ''
self.gh_json_file = None
self.interactive = False
self.kernel = None
self.kernel_dir = None
self.memory = '512m'
self.supports_efi = False
# It may be tempting to use self.use_kvm during initialization of
# subclasses to set certain properties but the user can explicitly opt
# out of KVM after instantiation, so any decisions based on it should
# be confined to run().
self.use_kvm = False
self.smp = 0
self.timeout = ''
self._default_kernel_path = None
self._dtbs = []
self._efi_img = None
self._efi_vars = None
self._initrd_arch = None
self._kvm_cpu = ['host']
self._qemu_arch = None
self._qemu_args = [
'-display', 'none',
'-nodefaults',
] # yapf: disable
self._qemu_path = None
def _find_dtb(self):
if not self._dtbs:
raise RuntimeError('No dtbs set?')
if not self.kernel:
raise RuntimeError('Cannot locate dtb without kernel')
# If we are in a boot folder, look for them in the dts folder in it.
# Otherwise, assume there is a 'dtbs' folder in the same folder as the
# kernel image (tuxmake)
dtb_dir = 'dts' if self.kernel.parent.name == 'boot' else 'dtbs'
for dtb_loc in self._dtbs:
if (dtb := Path(self.kernel.parent, dtb_dir, dtb_loc)).exists():
return dtb
raise FileNotFoundError(
f"dtb is required for booting but it could not be found at expected locations ('{self._dtbs}')"
)
def _get_default_smp_value(self):
if not self.kernel_dir:
raise RuntimeError('No kernel build folder specified?')
# If kernel_dir is the kernel source, the configuration will be at
# <kernel_dir>/.config
#
# If kernel_dir is the direct parent to the full kernel image, the
# configuration could either be:
# * <kernel_dir>/.config (if the image is vmlinux)
# * <kernel_dir>/../../../.config (if the image is in arch/*/boot/)
# * <kernel_dir>/config (if the image is in a TuxMake folder)
possible_locations = ['.config', '../../../.config', 'config']
configuration = utils.find_first_file(self.kernel_dir,
possible_locations,
required=False)
config_nr_cpus = 8 # sensible default based on treewide defaults,
if configuration:
conf_txt = configuration.read_text(encoding='utf-8')
if (match := re.search(r'CONFIG_NR_CPUS=(\d+)', conf_txt)):
config_nr_cpus = int(match.groups()[0])
# Use the minimum of the number of usable processers for the script or
# CONFIG_NR_CPUS.
usable_cpus = os.cpu_count()
return min(usable_cpus, config_nr_cpus)
def _get_kernel_ver_tuple(self, decomp_prog):
if not self.kernel:
raise RuntimeError('No kernel set?')
utils.check_cmd(decomp_prog)
if decomp_prog in ('gzip', ):
decomp_cmd = [decomp_prog, '-c', '-d', self.kernel]
else:
raise RuntimeError(
f"Unsupported decompression program ('{decomp_prog}')?")
decomp = subprocess.run(decomp_cmd, capture_output=True, check=True)
utils.check_cmd('strings')
strings = subprocess.run('strings',
capture_output=True,
check=True,
input=decomp.stdout)
strings_stdout = strings.stdout.decode(encoding='utf-8',
errors='ignore')
if not (match := re.search(r'^Linux version (\d+\.\d+\.\d+)',
strings_stdout,
flags=re.M)):
raise RuntimeError(
f"Could not find Linux version in {self.kernel}?")
return tuple(int(x) for x in match.groups()[0].split('.'))
def _get_qemu_ver_string(self):
if not self._qemu_path:
raise RuntimeError('No path to QEMU set?')
qemu_ver = subprocess.run([self._qemu_path, '--version'],
capture_output=True,
check=True,
text=True)
return qemu_ver.stdout.splitlines()[0]
def _get_qemu_ver_tuple(self):
qemu_ver_string = self._get_qemu_ver_string()
if not (match := re.search(r'version (\d+\.\d+.\d+)',
qemu_ver_string)):
raise RuntimeError('Could not find QEMU version?')
return tuple(int(x) for x in match.groups()[0].split('.'))
def _have_dev_kvm_access(self):
return os.access('/dev/kvm', os.R_OK | os.W_OK)
def _prepare_initrd(self):
if not self._initrd_arch:
raise RuntimeError('No initrd architecture specified?')
return utils.prepare_initrd(self._initrd_arch,
gh_json_file=self.gh_json_file)
def _run_fg(self):
# Pretty print and run QEMU command
qemu_cmd = []
if not self.interactive:
utils.check_cmd('timeout')
qemu_cmd += ['timeout', '--foreground', self.timeout]
utils.check_cmd('stdbuf')
qemu_cmd += ['stdbuf', '-eL', '-oL']
qemu_cmd += [self._qemu_path, *self._qemu_args]
print(f"$ {' '.join(shlex.quote(str(elem)) for elem in qemu_cmd)}")
try:
subprocess.run(qemu_cmd, check=True)
except subprocess.CalledProcessError as err:
if err.returncode == 124:
utils.red("ERROR: QEMU timed out!")
else:
utils.red("ERROR: QEMU did not exit cleanly!")
sys.exit(err.returncode)
def _run_gdb(self):
qemu_cmd = [self._qemu_path, *self._qemu_args]
utils.check_cmd(self.gdb_bin)
utils.check_cmd('lsof')
gdb_cmd = [
self.gdb_bin,
Path(self.kernel_dir, 'vmlinux'),
'-ex',
'target remote :1234',
]
while True:
lsof = subprocess.run(['lsof', '-i:1234'],
capture_output=True,
check=False)
if lsof.returncode == 0:
utils.die('Port 1234 is already in use, is QEMU running?')
utils.green('Starting QEMU with gdb connection on port 1234...')
# setpgrp() is equivalent to setpgid(0, 0). The 'process_group'
# keyword argument is equivalent to calling setpgid(0, arg) but it
# is only available in Python 3.11 and newer.
if sys.version_info >= (3, 11, 0):
popen_kwargs = {'process_group': 0}
else:
popen_kwargs = {'preexec_fn': os.setpgrp}
# pylint seems to think process_group will be used with Python 3.10
# and earlier?
# pylint: disable-next=unexpected-keyword-arg
with subprocess.Popen(qemu_cmd, **popen_kwargs) as qemu_proc:
utils.green(f"Starting {self.gdb_bin}...")
with subprocess.Popen(gdb_cmd) as gdb_proc, \
contextlib.suppress(KeyboardInterrupt):
gdb_proc.wait()
utils.red('Killing QEMU...')
qemu_proc.kill()
answer = input('Re-run QEMU + gdb [y/n] ')
if answer.lower() == 'n':
break
def _set_kernel_vars(self):
if self.kernel:
if not self.kernel_dir:
self.kernel_dir = self.kernel.parent
# Nothing else to do, kernel image and build folder located and set
return
if not self.kernel_dir:
raise RuntimeError(
'No kernel image or kernel build folder specified?')
if not self._default_kernel_path:
raise RuntimeError('No default kernel path specified?')
possible_kernel_locations = {
Path(self._default_kernel_path), # default (kbuild)
Path(self._default_kernel_path.name), # tuxmake
}
self.kernel = utils.find_first_file(self.kernel_dir,
possible_kernel_locations)
def _set_qemu_path(self):
if self._qemu_path:
return # already found and set
if not self._qemu_arch:
raise RuntimeError('No QEMU architecture set?')
qemu_bin = f"qemu-system-{self._qemu_arch}"
if not (qemu_path := shutil.which(qemu_bin)):
raise RuntimeError(
f'{qemu_bin} could not be found on your system?')
self._qemu_path = Path(qemu_path)
def run(self):
# Make sure QEMU binary is configured and available
self._set_qemu_path()
# Locate kernel (may be done earlier in subclasses)
self._set_kernel_vars()
# EFI:
if self.efi:
self._qemu_args += [
'-drive', f"if=pflash,format=raw,file={self._efi_img},readonly=on",
'-drive', f"if=pflash,format=raw,file={self._efi_vars}",
'-object', 'rng-random,filename=/dev/urandom,id=rng0',
'-device', 'virtio-rng-pci',
] # yapf: disable
# Kernel options
if self.interactive or self.gdb:
self.cmdline.append('rdinit=/bin/sh')
if self.gdb:
self.cmdline.append('nokaslr')
if self.cmdline:
self._qemu_args += ['-append', ' '.join(self.cmdline)]
if self._dtbs:
self._qemu_args += ['-dtb', self._find_dtb()]
self._qemu_args += ['-kernel', self.kernel]
self._qemu_args += ['-initrd', self._prepare_initrd()]
# KVM
if self.use_kvm:
if not self.smp:
self.smp = self._get_default_smp_value()
self._qemu_args += ['-cpu', ','.join(self._kvm_cpu), '-enable-kvm']
# Machine specs
self._qemu_args += ['-m', self.memory]
if self.smp:
self._qemu_args += ['-smp', str(self.smp)]
# Show information about QEMU
utils.green(f"QEMU location: \033[0m{self._qemu_path.parent}")
utils.green(f"QEMU version: \033[0m{self._get_qemu_ver_string()}")
if self.gdb:
self._qemu_args += ['-s', '-S']
self._run_gdb()
else:
self._qemu_args += ['-serial', 'mon:stdio']
self._run_fg()
class ARMEFIQEMURunner(QEMURunner):
def _setup_efi(self, possible_locations):
# Sizing the images to 64M is recommended by "Prepare the firmware" section at
# https://mirrors.edge.kernel.org/pub/linux/kernel/people/will/docs/qemu/qemu-arm64-howto.html
efi_img_size = 64 * 1024 * 1024 # 64M
usr_share = Path('/usr/share')
aavmf = utils.find_first_file(usr_share, possible_locations)
self._efi_img = Path(utils.BOOT_UTILS, 'images', self._initrd_arch,
'efi.img')
# This file is in /usr/share, so it must be copied in order to be
# modified.
shutil.copyfile(aavmf, self._efi_img)
with self._efi_img.open(mode='r+b') as file:
file.truncate(efi_img_size)
self._efi_vars = self._efi_img.with_name('efivars.img')
self._efi_vars.unlink(missing_ok=True)
with self._efi_vars.open(mode='xb') as file:
file.truncate(efi_img_size)
class ARMQEMURunner(QEMURunner):
def __init__(self):
super().__init__()
self._default_kernel_path = Path('arch/arm/boot/zImage')
self._initrd_arch = self._qemu_arch = 'arm'
self._machine = 'virt'
self._qemu_args.append('-no-reboot')
def run(self):
self._qemu_args += ['-machine', self._machine]
super().run()
class ARMV5QEMURunner(ARMQEMURunner):
def __init__(self):
super().__init__()
self.cmdline.append('earlycon')
self._dtbs = [
'aspeed/aspeed-bmc-opp-palmetto.dtb', 'aspeed-bmc-opp-palmetto.dtb'
]
self._machine = 'palmetto-bmc'
class ARMV6QEMURunner(ARMQEMURunner):
def __init__(self):
super().__init__()
self._dtbs = [
'aspeed/aspeed-bmc-opp-romulus.dtb', 'aspeed-bmc-opp-romulus.dtb'
]
self._machine = 'romulus-bmc'
class ARMV7QEMURunner(ARMQEMURunner, ARMEFIQEMURunner):
def __init__(self):
super().__init__()
self.supports_efi = True
self.use_kvm = self._can_use_kvm()
self.cmdline += ['console=ttyAMA0', 'earlycon']
def _can_use_kvm(self):
# 32-bit ARM KVM was ripped out in 5.7, so we do not bother checking
# for it here.
if platform.machine() != 'aarch64':
return False
# 32-bit EL1 is not supported on all cores so support for it must be
# explicitly queried via the KVM_CHECK_EXTENSION ioctl().
try:
subprocess.run(Path(utils.BOOT_UTILS, 'utils',
'aarch64_32_bit_el1_supported'),
check=True)
except subprocess.CalledProcessError:
return False
return self._have_dev_kvm_access()
def run(self):
if self.efi:
aavmf_locations = [
Path('edk2/arm/QEMU_EFI.fd'), # Arch Linux, Fedora
]
self._setup_efi(aavmf_locations)
if self.use_kvm:
self._kvm_cpu.append('aarch64=off')
self._qemu_arch = 'aarch64'
super().run()
class ARM64QEMURunner(ARMEFIQEMURunner):
def __init__(self):
super().__init__()
self.cmdline += ['console=ttyAMA0', 'earlycon']
self.supports_efi = True
self.use_kvm = platform.machine() == 'aarch64' and \
self._have_dev_kvm_access()
self._default_kernel_path = Path('arch/arm64/boot/Image.gz')
self._initrd_arch = 'arm64'
self._qemu_arch = 'aarch64'
def _get_cpu_val(self):
cpu = ['max']
self._set_qemu_path()
# See the two gitlab links below for more details
if (qemu_ver := self._get_qemu_ver_tuple()) >= (6, 2, 50):
self._set_kernel_vars()
kernel_ver = self._get_kernel_ver_tuple('gzip')
# https://gitlab.com/qemu-project/qemu/-/issues/964
if kernel_ver < (4, 16, 0):
cpu = ['cortex-a72']
# https://gitlab.com/qemu-project/qemu/-/commit/69b2265d5fe8e0f401d75e175e0a243a7d505e53
elif kernel_ver < (5, 12, 0):
cpu.append('lpa2=off')
# https://lore.kernel.org/YlgVa+AP0g4IYvzN@lakrids/
if 'max' in cpu and qemu_ver >= (6, 0, 0):
cpu.append('pauth-impdef=true')
return cpu
def run(self):
machine = ['virt', 'gic-version=max']
if not self.use_kvm:
cpu_val = self._get_cpu_val()
self._qemu_args += ['-cpu', ','.join(cpu_val)]
# Boot with VHE emulation, which allows the kernel to run at EL2.
# KVM does not emulate VHE, so this cannot be unconditional.
machine.append('virtualization=true')
self._qemu_args += ['-machine', ','.join(machine)]
if self.efi:
aavmf_locations = [
Path('edk2/aarch64/QEMU_EFI.silent.fd'), # Fedora
Path('edk2/aarch64/QEMU_EFI.fd'), # Arch Linux (current)
Path('edk2-armvirt/aarch64/QEMU_EFI.fd'), # Arch Linux (old)
Path('qemu-efi-aarch64/QEMU_EFI.fd'), # Debian and Ubuntu
]
self._setup_efi(aavmf_locations)
super().run()
class ARM64BEQEMURunner(ARM64QEMURunner):
def __init__(self):
super().__init__()
self.supports_efi = False
self._initrd_arch = 'arm64be'
class LoongArchQEMURunner(QEMURunner):
def __init__(self):
super().__init__()
self.cmdline.append('console=ttyS0,115200')
self._default_kernel_path = Path('arch/loongarch/boot/vmlinuz.efi')
self._initrd_arch = 'loongarch'
bios = Path(utils.BOOT_UTILS, 'images', self._initrd_arch,
'edk2-loongarch64-code.fd')
if not bios.exists():
# Loongson renamed this in https://github.com/loongson/Firmware/commit/638906de6143283d86c70d80f4e9a30b50731c24
# so download it to the new location if it does not exist already.
bios = bios.with_name('QEMU_EFI.fd')
bios.parent.mkdir(exist_ok=True, parents=True)
firmware_url = f"https://github.com/loongson/Firmware/raw/main/LoongArchVirtMachine/{bios.name}"
utils.green(
f"Downloading LoongArch firmware from {firmware_url}...")
curl_cmd = ['curl', '-LSs', '-o', bios, firmware_url]
subprocess.run(curl_cmd, check=True)
self._qemu_arch = 'loongarch64'
self._qemu_args += [
'-M', 'virt',
'-cpu', 'la464',
'-bios', bios,
'-no-reboot',
] # yapf: disable
self.memory = '2G'
self.smp = 2
class M68KQEMURunner(QEMURunner):
def __init__(self):
super().__init__()
self.cmdline.append('console=ttyS0,115200')
self._default_kernel_path = Path('vmlinux')
self._initrd_arch = self._qemu_arch = 'm68k'
self._qemu_args += [
'-cpu', 'm68040',
'-M', 'q800',
'-no-reboot',
] # yapf: disable
class MIPSQEMURunner(QEMURunner):
def __init__(self):
super().__init__()
self._default_kernel_path = Path('vmlinux')
self._initrd_arch = self._qemu_arch = 'mips'
self._qemu_args += ['-cpu', '24Kf', '-machine', 'malta']
class MIPSELQEMURunner(MIPSQEMURunner):
def __init__(self):
super().__init__()
self._initrd_arch = self._qemu_arch = 'mipsel'
class PowerPC32QEMURunner(QEMURunner):
def __init__(self):
super().__init__()
self.cmdline.append('console=ttyS0')
self.memory = '128m'
self._default_kernel_path = Path('arch/powerpc/boot/uImage')
self._initrd_arch = 'ppc32'
self._machine = 'bamboo'
self._qemu_arch = 'ppc'
self._qemu_args.append('-no-reboot')
def run(self):
self._qemu_args += ['-machine', self._machine]
super().run()
class PowerPC32MacQEMURunner(PowerPC32QEMURunner):
def __init__(self):
super().__init__()
self._default_kernel_path = Path('vmlinux')
self._machine = 'mac99'
class PowerPC64QEMURunner(QEMURunner):
def __init__(self):
super().__init__()
self.memory = '1G'
self._default_kernel_path = Path('vmlinux')
self._initrd_arch = self._qemu_arch = 'ppc64'
self._qemu_args += [
'-cpu', 'power8',
'-machine', 'pseries',
'-vga', 'none',
] # yapf: disable
class PowerPC64LEQEMURunner(QEMURunner):
def __init__(self):
super().__init__()
self.memory = '2G'
self._default_kernel_path = Path('arch/powerpc/boot/zImage.epapr')
self._initrd_arch = 'ppc64le'
self._qemu_arch = 'ppc64'
self._qemu_args += [
'-device', 'ipmi-bmc-sim,id=bmc0',
'-device', 'isa-ipmi-bt,bmc=bmc0,irq=10',
'-machine', 'powernv',
] # yapf: disable
class RISCVQEMURunner(QEMURunner):
def __init__(self):
super().__init__()
self.cmdline.append('earlycon')
self._default_kernel_path = Path('arch/riscv/boot/Image')
self._initrd_arch = 'riscv'
self._qemu_arch = 'riscv64'
deb_bios = '/usr/lib/riscv64-linux-gnu/opensbi/qemu/virt/fw_jump.elf'
if 'BIOS' in os.environ:
bios = os.environ['BIOS']
elif Path(deb_bios).exists():
bios = deb_bios
else:
bios = 'default'
self._qemu_args += ['-bios', bios, '-M', 'virt']
class S390QEMURunner(QEMURunner):
def __init__(self):
super().__init__()
self._default_kernel_path = Path('arch/s390/boot/bzImage')
self._initrd_arch = 's390'
self._qemu_arch = 's390x'
self._qemu_args += ['-M', 's390-ccw-virtio']
class Sparc64QEMURunner(QEMURunner):
def __init__(self):
super().__init__()
self.cmdline.append('console=ttyS0')
self._default_kernel_path = Path('arch/sparc/boot/image')
self._initrd_arch = self._qemu_arch = 'sparc64'
self._qemu_args += ['-M', 'sun4u', '-cpu', 'TI UltraSparc IIi']
class X86QEMURunner(QEMURunner):
def __init__(self):
super().__init__()
self.cmdline += ['console=ttyS0', 'earlycon=uart8250,io,0x3f8']
self.use_kvm = platform.machine() == 'x86_64' and \
self._have_dev_kvm_access()
self._default_kernel_path = Path('arch/x86/boot/bzImage')
self._initrd_arch = 'x86'
self._qemu_arch = 'i386'
self._qemu_args += ['-M', 'q35']
def run(self):
if self.use_kvm and not self.efi:
# There are a lot of messages along the line of
# "Invalid read at addr 0xFED40000, size 1, region '(null)', reason: rejected"
# with EFI, so do not bother.
self._qemu_args += ['-d', 'unimp,guest_errors']
super().run()
class X8664QEMURunner(X86QEMURunner):
def __init__(self):
super().__init__()
self.supports_efi = True
self._initrd_arch = self._qemu_arch = 'x86_64'
def run(self):
if not self.use_kvm:
self._qemu_args += ['-cpu', 'Nehalem']
if self.efi:
usr_share = Path('/usr/share')
ovmf_locations = [
Path('edk2/x64/OVMF_CODE.fd'), # Arch Linux (current), Fedora
Path('edk2-ovmf/x64/OVMF_CODE.fd'), # Arch Linux (old)
Path('OVMF/OVMF_CODE.fd'), # Debian and Ubuntu
]
self._efi_img = utils.find_first_file(usr_share, ovmf_locations)
ovmf_vars_locations = [
Path('edk2/x64/OVMF_VARS.fd'), # Arch Linux and Fedora
Path('OVMF/OVMF_VARS.fd'), # Debian and Ubuntu
]
ovmf_vars = utils.find_first_file(usr_share, ovmf_vars_locations)
self._efi_vars = Path(utils.BOOT_UTILS, 'images',
self._initrd_arch, ovmf_vars.name)
# This file is in /usr/share, so it must be copied in order to be
# modified.
shutil.copyfile(ovmf_vars, self._efi_vars)
super().run()
def guess_arch(kernel_arg):
# kernel_arg is either a path to the kernel build folder or a full kernel
# location. If it is a file, we need to strip off the basename so that we
# can easily navigate around with '..'.
if (kernel_dir := kernel_arg).is_file():
kernel_dir = kernel_dir.parent
# If kernel_location is the kernel build folder, vmlinux will be at
# <kernel_dir>/vmlinux
#
# If kernel_location is a full kernel location, it could either be:
# * <kernel_dir>/vmlinux (if the image is vmlinux)
# * <kernel_dir>/../../../vmlinux (if the image is in arch/*/boot/)
#
# Note: 'required=False' just to provide our own exception.
vmlinux_locations = ['vmlinux', '../../../vmlinux']
if not (vmlinux := utils.find_first_file(
kernel_dir, vmlinux_locations, required=False)):
raise RuntimeError(
'Architecture was not provided and vmlinux could not be found!')
if not (file := shutil.which('file')):
raise RuntimeError(
"Architecture was not provided and 'file' is not installed!")
# Get output of file
file_out = subprocess.run([file, vmlinux],
capture_output=True,
check=True,
text=True).stdout.strip()
# Unfortunately, 'file' is not terribly precise when it comes to
# microarchitecture or architecture revisions. As such, there are certain
# strings that are just ambiguous so we bail out and let the user tell us
# exactly what architecture they were hoping to boot.
file_rosetta = {
'ELF 32-bit LSB executable, ARM, EABI5': 'ambiguous', # could be any arm32
'ELF 64-bit LSB executable, ARM aarch64': 'arm64',
'ELF 64-bit MSB executable, ARM aarch64': 'arm64be',
'ELF 64-bit LSB pie executable, ARM aarch64': 'arm64',
'ELF 64-bit MSB pie executable, ARM aarch64': 'arm64be',
'ELF 64-bit LSB executable, LoongArch': 'loongarch',
'ELF 32-bit MSB executable, Motorola m68k, 68020': 'm68k',
'ELF 32-bit MSB executable, MIPS, MIPS32': 'mips',
'ELF 32-bit LSB executable, MIPS, MIPS32': 'mipsel',
'ELF 32-bit MSB executable, PowerPC': 'ambiguous', # could be ppc32 or ppc32_mac
'ELF 64-bit MSB executable, 64-bit PowerPC or cisco 7500, Power ELF V1 ABI': 'ppc64',
'ELF 64-bit MSB executable, 64-bit PowerPC or cisco 7500, OpenPOWER ELF V2 ABI': 'ppc64',
'ELF 64-bit MSB pie executable, 64-bit PowerPC or cisco 7500, OpenPOWER ELF V2 ABI': 'ppc64',
'ELF 64-bit LSB executable, 64-bit PowerPC or cisco 7500, OpenPOWER ELF V2 ABI': 'ppc64le',
'ELF 64-bit LSB executable, UCB RISC-V': 'riscv',
'ELF 64-bit MSB executable, IBM S/390': 's390',
'ELF 64-bit MSB executable, SPARC V9': 'sparc64',
'ELF 32-bit LSB executable, Intel 80386': 'x86',
'ELF 64-bit LSB executable, x86-64': 'x86_64',
} # yapf: disable
for string, value in file_rosetta.items():
if string in file_out:
if value == 'ambiguous':
raise RuntimeError(
f"'{string}' found in '{file_out}' but the architecture is ambiguous, please explicitly specify it via '-a'!"
)
return value
raise RuntimeError(
f"Architecture could not be deduced from '{file_out}', please explicitly specify it via '-a' or add support for it to guess_arch()!"
)
def parse_arguments():
parser = ArgumentParser(description='Boot a Linux kernel in QEMU')
parser.add_argument(
'-a',
'--architecture',
choices=SUPPORTED_ARCHES,
help=
"The architecture to boot. If omitted, value will be guessed based on 'vmlinux' if available. Possible values are: %(choices)s",
metavar='ARCH')
parser.add_argument('--efi',
action='store_true',
help='Boot kernel via UEFI (x86_64 only)')
parser.add_argument(
'-g',
'--gdb',
action='store_true',
help="Start QEMU with '-s -S' then launch gdb on 'vmlinux'")
parser.add_argument(
'--gdb-bin',
default='gdb-multiarch',
help='gdb binary to use for debugging (default: gdb-multiarch)')
parser.add_argument(
'--gh-json-file',
help=
'Use file for downloading rootfs images, instead of querying GitHub API directly'
)
parser.add_argument(
'-k',
'--kernel-location',
required=True,
help='Absolute or relative path to kernel image or build folder.')
parser.add_argument('--append',
help='Append items to kernel cmdline',
nargs='+')
parser.add_argument(
'--no-kvm',
action='store_true',
help='Do not use KVM for accelration even when supported.')
parser.add_argument(
'-i',
'--interactive',
'--shell',
action='store_true',
help='Instead of immediately shutting down machine, spawn a shell.')
parser.add_argument(
'-m',
'--memory',
help=
"Value for '-m' QEMU option (default: generally '512m', depends on machine)",
)
parser.add_argument(
'-s',
'--smp',
type=int,
help=
'Number of processors for virtual machine (default: only KVM machines will use multiple vCPUs.)',
)
parser.add_argument('-t',
'--timeout',
default='3m',
help="Value to pass to 'timeout' (default: '3m')")
return parser.parse_args()
if __name__ == '__main__':
args = parse_arguments()
if not (kernel_location := Path(args.kernel_location).resolve()).exists():
raise FileNotFoundError(
f"Supplied kernel location ('{kernel_location}') does not exist!")
if not (arch := args.architecture):
arch = guess_arch(kernel_location)
arch_to_runner = {
'arm': ARMV7QEMURunner,
'arm32_v5': ARMV5QEMURunner,
'arm32_v6': ARMV6QEMURunner,
'arm32_v7': ARMV7QEMURunner,
'arm64': ARM64QEMURunner,
'arm64be': ARM64BEQEMURunner,
'loongarch': LoongArchQEMURunner,
'm68k': M68KQEMURunner,
'mips': MIPSQEMURunner,
'mipsel': MIPSELQEMURunner,
'ppc32': PowerPC32QEMURunner,
'ppc32_mac': PowerPC32MacQEMURunner,
'ppc64': PowerPC64QEMURunner,
'ppc64le': PowerPC64LEQEMURunner,
'riscv': RISCVQEMURunner,
's390': S390QEMURunner,
'sparc64': Sparc64QEMURunner,
'x86': X86QEMURunner,
'x86_64': X8664QEMURunner,
}
runner = arch_to_runner[arch]()
if kernel_location.is_file():
if args.gdb and kernel_location.name != 'vmlinux':
raise RuntimeError(
'Debugging with gdb requires a kernel build folder to locate vmlinux',
)
runner.kernel = kernel_location
else:
runner.kernel_dir = kernel_location
if args.append:
runner.cmdline += args.append
if args.efi:
runner.efi = runner.supports_efi
if not runner.efi:
utils.yellow(
f"EFI boot requested on unsupported architecture ('{arch}'), ignoring..."
)
if args.gdb:
runner.gdb = True
runner.gdb_bin = args.gdb_bin
if args.gh_json_file:
runner.gh_json_file = Path(args.gh_json_file).resolve()
if args.memory:
runner.memory = args.memory
if args.no_kvm:
runner.use_kvm = False
if args.smp:
runner.smp = args.smp
runner.interactive = args.interactive
runner.timeout = args.timeout
runner.run()