forked from cirosantilli/linux-kernel-module-cheat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.py
2280 lines (2145 loc) · 90.6 KB
/
common.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
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import argparse
import bisect
import collections
import copy
import datetime
import enum
import functools
import glob
import inspect
import itertools
import json
import math
import os
import platform
import pathlib
import queue
import re
import shutil
import signal
import subprocess
import sys
import threading
from typing import Union
import time
import urllib
import urllib.request
from shell_helpers import LF
# https://cirosantilli.com/china-dictatorship/#mirrors
import china_dictatorship
assert "Tiananmen Square protests" in china_dictatorship.get_data()
import cli_function
import path_properties
import shell_helpers
import thread_pool
common = sys.modules[__name__]
# Fixed parameters that don't depend on CLI arguments.
consts = {}
consts['repo_short_id'] = 'lkmc'
consts['linux_kernel_version'] = '5.9.2'
# https://stackoverflow.com/questions/20010199/how-to-determine-if-a-process-runs-inside-lxc-docker
consts['in_docker'] = os.path.exists('/.dockerenv')
consts['root_dir'] = os.path.dirname(os.path.abspath(__file__))
consts['data_dir'] = os.path.join(consts['root_dir'], 'data')
consts['p9_dir'] = os.path.join(consts['data_dir'], '9p')
consts['gem5_non_default_source_root_dir'] = os.path.join(consts['data_dir'], 'gem5')
if consts['in_docker']:
# fatal: unsafe repository ('/root/lkmc' is owned by someone else)
# Fuck these error checks, let me shoot my feet in peace.
# The best solution would be to actually get Docker to mount
# the current diretory as root. But I've never been able to do that:
# * https://stackoverflow.com/questions/51973179/docker-mount-volumes-as-root
# * https://unix.stackexchange.com/questions/523492/how-to-mount-files-as-specific-user-when-using-docker-namespace-remapping
# * https://stackoverflow.com/questions/35291520/docker-and-userns-remap-how-to-manage-volume-permissions-to-share-data-betwee
# So for now we see as owner e.g. 1000:1000 on the volume, and root:root on /.
# '*' to ignore all was added on Git 2.36... Without that we would need to add every single submodule to the list.
# * https://stackoverflow.com/questions/71901632/fatal-unsafe-repository-home-repon-is-owned-by-someone-else
# * https://stackoverflow.com/questions/71849415/i-cannot-add-the-parent-directory-to-safe-directory-in-git/71904131#71904131
# * https://www.reddit.com/r/docker/comments/o8bnft/is_it_possible_to_mount_files_with_readwrite/
subprocess.check_output(['git', 'config', '--global', '--add', 'safe.directory', '*'])
consts['out_dir'] = os.path.join(consts['root_dir'], 'out.docker')
else:
consts['out_dir'] = os.path.join(consts['root_dir'], 'out')
consts['readme'] = os.path.join(consts['root_dir'], 'README.adoc')
consts['out_doc_dir'] = os.path.join(consts['out_dir'], 'doc')
consts['readme_out'] = os.path.join(consts['out_dir'], 'README.html')
consts['build_doc_log'] = os.path.join(consts['out_dir'], 'build-doc.log')
consts['build_doc_multipage_log'] = os.path.join(consts['out_dir'], 'build-doc-multipage.log')
consts['gem5_out_dir'] = os.path.join(consts['out_dir'], 'gem5')
consts['kernel_modules_build_base_dir'] = os.path.join(consts['out_dir'], 'kernel_modules')
consts['buildroot_out_dir'] = os.path.join(consts['out_dir'], 'buildroot')
consts['gem5_m5_build_dir'] = os.path.join(consts['out_dir'], 'util', 'm5')
consts['run_dir_base'] = os.path.join(consts['out_dir'], 'run')
consts['crosstool_ng_out_dir'] = os.path.join(consts['out_dir'], 'crosstool-ng')
consts['test_boot_benchmark_file'] = os.path.join(consts['out_dir'], 'test-boot.txt')
consts['packages_dir'] = os.path.join(consts['root_dir'], 'buildroot_packages')
consts['kernel_modules_subdir'] = 'kernel_modules'
consts['kernel_modules_source_dir'] = os.path.join(consts['root_dir'], consts['kernel_modules_subdir'])
consts['userland_subdir'] = 'userland'
consts['userland_source_dir'] = os.path.join(consts['root_dir'], consts['userland_subdir'])
consts['userland_libs_basename'] = 'libs'
consts['userland_source_libs_dir'] = os.path.join(consts['userland_source_dir'], consts['userland_libs_basename'])
consts['userland_source_arch_dir'] = os.path.join(consts['userland_source_dir'], 'arch')
consts['userland_executable_ext'] = '.out'
consts['baremetal_executable_ext'] = '.elf'
consts['baremetal_max_text_size'] = 0x1000000
consts['baremetal_memory_size'] = 0x2000000
consts['include_subdir'] = consts['repo_short_id']
consts['include_source_dir'] = os.path.join(consts['root_dir'], consts['include_subdir'])
consts['submodules_dir'] = os.path.join(consts['root_dir'], 'submodules')
consts['buildroot_source_dir'] = os.path.join(consts['submodules_dir'], 'buildroot')
consts['crosstool_ng_source_dir'] = os.path.join(consts['submodules_dir'], 'crosstool-ng')
consts['crosstool_ng_supported_archs'] = set(['arm', 'aarch64'])
consts['linux_source_dir'] = os.path.join(consts['submodules_dir'], 'linux')
consts['linux_config_dir'] = os.path.join(consts['root_dir'], 'linux_config')
consts['gem5_default_source_dir'] = os.path.join(consts['submodules_dir'], 'gem5')
consts['googletest_source_dir'] = os.path.join(consts['submodules_dir'], 'googletest')
consts['rootfs_overlay_dir'] = os.path.join(consts['root_dir'], 'rootfs_overlay')
consts['extract_vmlinux'] = os.path.join(consts['linux_source_dir'], 'scripts', 'extract-vmlinux')
consts['qemu_source_dir'] = os.path.join(consts['submodules_dir'], 'qemu')
consts['parsec_benchmark_source_dir'] = os.path.join(consts['submodules_dir'], 'parsec-benchmark')
consts['ccache_dir'] = os.path.join('/usr', 'lib', 'ccache')
consts['default_build_id'] = 'default'
consts['arch_short_to_long_dict'] = collections.OrderedDict([
('x', 'x86_64'),
('a', 'arm'),
('A', 'aarch64'),
])
# All long arch names.
consts['all_long_archs'] = [consts['arch_short_to_long_dict'][k] for k in consts['arch_short_to_long_dict']]
# All long and short arch names.
consts['arch_choices'] = set()
for key in consts['arch_short_to_long_dict']:
consts['arch_choices'].add(key)
consts['arch_choices'].add(consts['arch_short_to_long_dict'][key])
consts['default_arch'] = 'x86_64'
consts['gem5_cpt_prefix'] = '^cpt\.'
def git_sha(repo_path):
return subprocess.check_output(['git', '-C', repo_path, 'log', '-1', '--format=%H']).decode().rstrip()
consts['sha'] = common.git_sha(consts['root_dir'])
consts['release_dir'] = os.path.join(consts['out_dir'], 'release')
consts['release_zip_file'] = os.path.join(consts['release_dir'], 'lkmc-{}.zip'.format(consts['sha']))
consts['github_repo_id'] = 'cirosantilli/linux-kernel-module-cheat'
consts['github_repo_url'] = 'https://github.com/' + consts['github_repo_id']
consts['homepage_url'] = 'https://cirosantilli.com/linux-kernel-module-cheat'
consts['asm_ext'] = '.S'
consts['c_ext'] = '.c'
consts['cxx_ext'] = '.cpp'
consts['header_ext'] = '.h'
consts['kernel_module_ext'] = '.ko'
consts['obj_ext'] = '.o'
# https://cirosantilli.com/linux-kernel-module-cheat#baremetal-cpp
consts['baremetal_build_in_exts'] = [
consts['asm_ext'],
consts['c_ext'],
]
consts['build_in_exts'] = consts['baremetal_build_in_exts'] + [
consts['cxx_ext']
]
consts['userland_out_exts'] = [
consts['userland_executable_ext'],
consts['obj_ext'],
]
consts['default_config_file'] = os.path.join(consts['data_dir'], 'config.py')
consts['serial_magic_exit_status_regexp_string'] = b'lkmc_exit_status_(\d+)'
consts['baremetal_lib_basename'] = 'lib'
consts['emulator_userland_only_short_to_long_dict'] = collections.OrderedDict([
('n', 'native'),
])
consts['all_userland_only_emulators'] = set()
for key in consts['emulator_userland_only_short_to_long_dict']:
consts['all_userland_only_emulators'].add(key)
consts['all_userland_only_emulators'].add(consts['emulator_userland_only_short_to_long_dict'][key])
consts['emulator_short_to_long_dict'] = collections.OrderedDict([
('q', 'qemu'),
('g', 'gem5'),
])
consts['emulator_short_to_long_dict'].update(consts['emulator_userland_only_short_to_long_dict'])
consts['all_long_emulators'] = [consts['emulator_short_to_long_dict'][k] for k in consts['emulator_short_to_long_dict']]
consts['emulator_choices'] = set()
for key in consts['emulator_short_to_long_dict']:
consts['emulator_choices'].add(key)
consts['emulator_choices'].add(consts['emulator_short_to_long_dict'][key])
consts['host_arch'] = platform.processor()
consts['guest_lkmc_home'] = os.sep + consts['repo_short_id']
consts['build_type_choices'] = [
# -O2 -g
'opt',
# -O0 -g
'debug'
]
consts['gem5_build_type_choices'] = consts['build_type_choices'] + [
'fast', 'prof', 'perf',
]
consts['build_type_default'] = 'opt'
# Files whose basename start with this are gitignored.
consts['tmp_prefix'] = 'tmp.'
class ExitLoop(Exception):
pass
class LkmcCliFunction(cli_function.CliFunction):
'''
Common functionality shared across our CLI functions:
* command timing
* a lot some common flags, e.g.: --arch, --dry-run, --quiet, --verbose
* a lot of helpers that depend on self.env
+
self.env contains the command line arguments + a ton of values derived from those.
+
It would be beautiful to do this evaluation in a lazy way, e.g. with functions +
cache decorators:
https://stackoverflow.com/questions/815110/is-there-a-decorator-to-simply-cache-function-return-values
'''
def __init__(
self,
*args,
defaults=None,
**kwargs
):
'''
:ptype defaults: Dict[str,Any]
:param defaults: override the default value of an argument
'''
kwargs['default_config_file'] = consts['default_config_file']
kwargs['extra_config_params'] = os.path.basename(inspect.getfile(self.__class__))
if defaults is None:
defaults = {}
self._defaults = defaults
self._is_common = True
self._common_args = set()
super().__init__(*args, **kwargs)
self.print_lock = threading.Lock()
# Args for all scripts.
arches = consts['arch_short_to_long_dict']
arches_string = []
for arch_short in arches:
arch_long = arches[arch_short]
arches_string.append('{} ({})'.format(arch_long, arch_short))
arches_string = ', '.join(arches_string)
self.add_argument(
'-A',
'--all-archs',
default=False,
help='''\
Run action for all supported --archs archs. Ignore --archs.
'''.format(arches_string)
)
self.add_argument(
'-a',
'--arch',
action='append',
choices=consts['arch_choices'],
default=[consts['default_arch']],
dest='archs',
help='''\
CPU architecture to use. If given multiple times, run the action
for each arch sequentially in that order. If one of them fails, stop running.
Valid archs: {}
'''.format(arches_string)
)
self.add_argument(
'--ccache',
default=True,
help='''\
Enable or disable ccache: https://cirosantilli.com/linux-kernel-module-cheat#ccache
'''
)
self.add_argument(
'--china',
default=False,
help='''\
https://cirosantilli.com/linux-kernel-module-cheat#china
'''
)
self.add_argument(
'--disk-image',
)
self.add_argument(
'--dry-run',
default=False,
help='''\
Print the commands that would be run, but don't run them.
We aim display every command that modifies the filesystem state, and generate
Bash equivalents even for actions taken directly in Python without shelling out.
mkdir are generally omitted since those are obvious
See also: https://cirosantilli.com/linux-kernel-module-cheat#dry-run
'''
)
self.add_argument(
'--gcc-which',
choices=[
'buildroot',
'crosstool-ng',
'host',
'host-baremetal'
],
default='buildroot',
help='''\
Which toolchain binaries to use:
- buildroot: the ones we built with ./build-buildroot. For userland, links to glibc.
- crosstool-ng: the ones we built with ./build-crosstool-ng. For baremetal, links to newlib.
- host: the host distro pre-packaged userland ones. For userland, links to glibc.
- host-baremetal: the host distro pre-packaged bare one. For baremetal, links to newlib.
'''
)
self.add_argument(
'--march',
help='''\
GCC -march option to use. Currently only used for the more LKMC-specific builds such as
./build-userland and ./build-baremetal. Maybe we will use it for more things some day.
'''
)
self.add_argument(
'--mode',
choices=('userland', 'baremetal'),
default=None,
help='''Differentiate between userland and baremetal for scripts that can do both.
./run differentiates between them based on the --userland and --baremetal options,
however those options take arguments, Certain scripts can be run on either user or baremetal mode.
If given, this differentiates between them.
'''
)
self.add_argument(
'-j',
'--nproc',
default=len(os.sched_getaffinity(0)),
type=int,
help='''Number of processors (Jobs) to use for the action.''',
)
self.add_argument(
'-q',
'--quiet',
default=False,
help='''\
Don't print anything to stdout, except if it is part of an interactive terminal.
TODO: implement fully, some stuff is escaping it currently.
'''
)
self.add_argument(
'--quit-on-fail',
default=True,
help='''\
Stop running at the first failed test.
'''
)
self.add_argument(
'--show-cmds',
default=True,
help='''\
Print the exact Bash command equivalents being run by this script.
Implied by --quiet.
'''
)
self.add_argument(
'--show-time',
default=True,
help='''\
Print how long it took to run the command at the end.
Implied by --quiet.
'''
)
self.add_argument(
'-v',
'--verbose',
default=False,
help='Show full compilation commands when they are not shown by default.'
)
# Gem5 args.
self.add_argument(
'--dp650', default=False,
help='Use the ARM DP650 display processor instead of the default HDLCD on gem5.'
)
self.add_argument(
'--gem5-build-dir',
help='''\
Use the given directory as the gem5 build directory.
Ignore --gem5-build-id and --gem5-build-type.
'''
)
self.add_argument(
'-M',
'--gem5-build-id',
help='''\
gem5 build ID. Allows you to keep multiple separate gem5 builds.
Default: {}
'''.format(consts['default_build_id'])
)
self.add_argument(
'--gem5-build-type',
choices=consts['gem5_build_type_choices'],
default=consts['build_type_default'],
help='gem5 build type, most often used for "debug" builds.'
)
self.add_argument(
'--gem5-clang',
default=False,
help='''\
Build gem5 with clang and set the --gem5-build-id to 'clang' by default.
'''
)
self.add_argument(
'--gem5-source-dir',
help='''\
Use the given directory as the gem5 source tree. Ignore `--gem5-worktree`.
'''
)
self.add_argument(
'-N',
'--gem5-worktree',
help='''\
Create and use a git worktree of the gem5 submodule.
See: https://cirosantilli.com/linux-kernel-module-cheat#gem5-worktree
'''
)
# Linux kernel.
self.add_argument(
'--linux-build-dir',
help='''\
Use the given directory as the Linux build directory. Ignore --linux-build-id.
'''
)
self.add_argument(
'-L',
'--linux-build-id',
default=consts['default_build_id'],
help='''\
Linux build ID. Allows you to keep multiple separate Linux builds.
'''
)
self.add_argument(
'--linux-exec',
help='''\
Use the given executable Linux kernel image. Ignored in userland and baremetal modes,
Remember that different emulators may take different types of image, see:
https://cirosantilli.com/linux-kernel-module-cheat#vmlinux-vs-bzimage-vs-zimage-vs-image
''',
)
self.add_argument(
'--linux-source-dir',
help='''\
Use the given directory as the Linux source tree.
'''
)
self.add_argument(
'--initramfs',
default=False,
help='''\
See: https://cirosantilli.com/linux-kernel-module-cheat#initramfs
'''
)
self.add_argument(
'--initrd',
default=False,
help='''\
For Buildroot: create a CPIO root filessytem.
For QEMU use that CPUI root filesystem initrd instead of the default ext2.
See: https://cirosantilli.com/linux-kernel-module-cheat#initrd
'''
)
# Baremetal.
self.add_argument(
'-b',
'--baremetal',
action='append',
help='''\
Use the given baremetal executable instead of the Linux kernel.
If the path points to a source code inside baremetal/, then the
corresponding executable is automatically found.
'''
)
# Buildroot.
self.add_argument(
'--buildroot-build-id',
default=consts['default_build_id'],
help='Buildroot build ID. Allows you to keep multiple separate gem5 builds.'
)
self.add_argument(
'--buildroot-linux',
default=False,
help='Boot with the Buildroot Linux kernel instead of our custom built one. Mostly for sanity checks.'
)
# Android.
self.add_argument(
'--rootfs-type',
default='buildroot',
choices=('buildroot', 'android'),
help='Which rootfs to use.'
)
self.add_argument(
'--android-version', default='8.1.0_r60',
help='Which android version to use. implies --rootfs-type android'
)
self.add_argument(
'--android-base-dir',
help='''\
If given, place all android sources and build files into the given directory.
One application of this is to put those large directories in your HD instead
of SSD.
'''
)
# crosstool-ng
self.add_argument(
'--crosstool-ng-build-id',
default=consts['default_build_id'],
help='Crosstool-NG build ID. Allows you to keep multiple separate crosstool-NG builds.'
)
self.add_argument(
'--docker',
default=False,
help='''\
Use the docker download Ubuntu root filesystem instead of the default Buildroot one.
'''
)
# QEMU.
self.add_argument(
'--qemu-build-id',
default=consts['default_build_id'],
help='QEMU build ID. Allows you to keep multiple separate QEMU builds.'
)
self.add_argument(
'--qemu-build-type',
choices=consts['build_type_choices'],
default=consts['build_type_default'],
help='QEMU build type, most often used for "debug" vs optimized builds.'
)
self.add_argument(
'--qemu-which',
choices=[consts['repo_short_id'], 'host'],
default=consts['repo_short_id'],
help='''\
Which qemu binaries to use: qemu-system-, qemu-, qemu-img, etc.:
- lkmc: the ones we built with ./build-qemu
- host: the host distro pre-packaged provided ones
'''
)
self.add_argument(
'--machine',
help='''\
Machine type:
* QEMU default: -machine virt
* gem5 default: --machine-type VExpress_GEM5_V1
More infor on platforms at:
https://cirosantilli.com/linux-kernel-module-cheat#gem5-arm-platforms
'''
)
# Userland.
self.add_argument(
'--copy-overlay',
default=True,
help='''\
Copy userland build outputs to the overlay directory which will be put inside
the disk image. If not given explicitly, this is disabled automatically when certain
options are given, for example --static, since users don't usually want
static executables to be placed in the final image, but rather only for
user mode simulations in simulators that don't support dynamic linking like gem5.
'''
)
self.add_argument(
'--host',
default=False,
help='''\
Use the host toolchain and other dependencies to build exectuables for host execution.
Automatically place the build output on a separate directory from non --host builds,
e.g. by defaulting --userland-build-id host if that option has effect for the package.
Make --copy-overlay default to False as the generated executables can't in general
be run in the guest.
''',
)
self.add_argument(
'--out-rootfs-overlay-dir-prefix',
default='',
help='''\
Place the output files of userland build outputs inside the image within this
additional prefix. This is mostly useful to place different versions of binaries
with different build parameters inside image to compare them. See:
* https://cirosantilli.com/linux-kernel-module-cheat#update-the-buildroot-toolchain
* https://cirosantilli.com/linux-kernel-module-cheat#out-rootfs-overlay-dir
'''
)
self.add_argument(
'--package',
action='append',
help='''\
Request to install a package in the target root filesystem, or indicate that it is present
when building examples that rely on it or running tests for those examples.
''',
)
self.add_argument(
'--package-all',
action='store_true',
help='''\
Indicate that all packages used by our userland/ examples with --package
are available.
''',
)
self.add_argument(
'--print-cmd-oneline',
action='store_true',
help='''\
Print generated commands in a single line:
https://cirosantilli.com/linux-kernel-module-cheat#dry-run
'''
)
self.add_argument(
'--static',
default=False,
help='''\
Build userland executables statically. Set --userland-build-id to 'static'
if one was not given explicitly. See also:
https://cirosantilli.com/linux-kernel-module-cheat#user-mode-static-executables
''',
)
self.add_argument(
'-u',
'--userland',
action='append',
help='''\
Run the given userland executable in user mode instead of booting the Linux kernel
in full system mode. In gem5, user mode is called Syscall Emulation (SE) mode and
uses se.py. Path resolution is similar to --baremetal.
* https://cirosantilli.com/linux-kernel-module-cheat#userland-setup-getting-started
* https://cirosantilli.com/linux-kernel-module-cheat#gem5-syscall-emulation-mode
This option may be given multiple times only in gem5 syscall emulation:
https://cirosantilli.com/linux-kernel-module-cheat#gem5-syscall-emulation-multiple-executables
'''
)
self.add_argument(
'--cli-args',
help='''\
CLI arguments used in both --userland mode simulation, and in --baremetal. See also:
https://cirosantilli.com/linux-kernel-module-cheat#baremetal-command-line-arguments
'''
)
self.add_argument(
'--userland-build-id'
)
# Run.
self.add_argument(
'--background',
default=False,
help='''\
Make programs that would take over the terminal such as QEMU full system run on the
background instead.
Currently only implemented for ./run.
Interactive input cannot be given.
Send QEMU serial output to a file instead of the host terminal.
TODO: use a port instead. If only there was a way to redirect a serial to multiple
places, both to a port and a file? We use the file currently to be able to have
any output at all.
https://superuser.com/questions/1373226/how-to-redirect-qemu-serial-output-to-both-a-file-and-the-terminal-or-a-port
'''
)
self.add_argument(
'--in-tree',
default=False,
help='''\
Place build output inside source tree to conveniently run it, especially when
building with the host native toolchain.
When running, use in-tree executables instead of out-of-tree ones,
userland/c/hello resolves userland/c/hello.out instead of the out-of-tree one.
Currently only supported by userland scripts such as ./build-userland and
./run --userland.
''',
)
self.add_argument(
'--port-offset',
type=int,
help='''\
Increase the ports to be used such as for GDB by an offset to run multiple
instances in parallel. Default: the run ID (-n) if that is an integer, otherwise 0.
'''
)
self.add_argument(
'--prebuilt',
default=False,
help='''\
Use prebuilt packaged host utilities as much as possible instead
of the ones we built ourselves. Saves build time, but decreases
the likelihood of incompatibilities.
'''
)
self.add_argument(
'--run-id',
default='0',
help='''\
ID for run outputs such as gem5's m5out. Allows you to do multiple runs,
and then inspect separate outputs later in different output directories.
'''
)
# Misc.
emulators = consts['emulator_short_to_long_dict']
emulators_string = []
for emulator_short in emulators:
emulator_long = emulators[emulator_short]
emulators_string.append('{} ({})'.format(emulator_long, emulator_short))
emulators_string = ', '.join(emulators_string)
self.add_argument(
'--all-emulators', default=False,
help='''\
Run action for all supported emulators. Ignore --emulator.
'''.format(emulators_string)
)
self.add_argument(
'-e',
'--emulator',
action='append',
choices=consts['emulator_choices'],
default=['qemu'],
dest='emulators',
help='''\
Emulator to use. If given multiple times, semantics are similar to --arch.
Valid emulators: {}
"native" means running natively on host. It is only supported for userland,
and you must have built the program for native running, see:
https://cirosantilli.com/linux-kernel-module-cheat#userland-setup-getting-started-natively
Incompatible archs are skipped.
'''.format(emulators_string)
)
self._is_common = False
def __call__(self, *args, **kwargs):
'''
For Python code calls, in addition to base class behaviour:
* print the CLI equivalent of the call
* automatically forward common arguments
'''
print_cmd = ['./' + self.extra_config_params, LF]
if 'print_cmd_oneline' in kwargs:
force_oneline = kwargs['print_cmd_oneline']
del kwargs['print_cmd_oneline']
else:
force_oneline=False
for line in self.get_cli(**kwargs):
print_cmd.extend(line)
print_cmd.append(LF)
if not ('quiet' in kwargs and kwargs['quiet']):
shell_helpers.ShellHelpers().print_cmd(
print_cmd,
force_oneline=force_oneline
)
return super().__call__(**kwargs)
def _handle_thread_pool_errors(self, my_thread_pool):
handle_output_result = my_thread_pool.get_handle_output_result()
if handle_output_result is not None:
work_function_input, work_function_return, exception = handle_output_result
if not type(exception) is thread_pool.ThreadPoolExitException:
print('work_function or handle_output raised unexpectedly:')
print(thread_pool.ThreadPool.exception_traceback_string(exception), end='')
print('work_function_input: {}'.format(work_function_input))
print('work_function_return: {}'.format(work_function_return))
return 1
else:
return 0
def _init_env(self, env):
'''
Update the kwargs from the command line with values derived from them.
'''
def join(*paths):
return os.path.join(*paths)
if env['emulator'] in env['emulator_short_to_long_dict']:
env['emulator'] = env['emulator_short_to_long_dict'][env['emulator']]
if not env['_args_given']['userland_build_id']:
if env['static']:
env['userland_build_id'] = 'static'
elif env['host']:
env['userland_build_id'] = 'host'
else:
env['userland_build_id'] = env['default_build_id']
if not env['_args_given']['gem5_build_id']:
if env['_args_given']['gem5_clang']:
env['gem5_build_id'] = 'clang'
elif env['_args_given']['gem5_worktree']:
env['gem5_build_id'] = env['gem5_worktree']
else:
env['gem5_build_id'] = consts['default_build_id']
env['is_arm'] = False
# Our approach is as follows:
#
# * compilers: control maximum arch version emitted explicitly -mcpu
# +
# This helps to prevent blowing up simulation unnecessarily.
# +
# It does not matter if we miss any perf features for QEMU which is functional,
# but it could matter for gem5 perf simulations.
# * assemblers: enable as many features as possible.
# +
# Well, if I'm explicitly writing down the instructions, I want
# my emulator to blow up in peace!
# * emulators: enable as many features as possible
# +
# This is the gem5 default behavior, for QEMU TODO not sure if default,
# but we select it explicitly with -cpu max.
# https://habkost.net/posts/2017/03/qemu-cpu-model-probing-story.html
# +
# We doe this because QEMU does not add all possible Cortex Axx, there are
# just too many, and gem5 does not allow selecting lower feature in general.
env['int_size'] = 4
if env['arch'] == 'arm':
# TODO this shoud be 4. But that blows up running all gem5 arm 32-bit examples.
# https://cirosantilli.com/linux-kernel-module-cheat#gem5-baremetal-arm-cli-args
env['address_size'] = 8
env['armv'] = 7
env['buildroot_toolchain_prefix'] = 'arm-buildroot-linux-gnueabihf'
env['crosstool_ng_toolchain_prefix'] = 'arm-unknown-eabi'
env['ubuntu_toolchain_prefix'] = 'arm-linux-gnueabihf'
env['is_arm'] = True
if not env['_args_given']['march']:
env['march'] = 'armv8-a'
elif env['arch'] == 'aarch64':
env['address_size'] = 8
env['armv'] = 8
env['buildroot_toolchain_prefix'] = 'aarch64-buildroot-linux-gnu'
env['crosstool_ng_toolchain_prefix'] = 'aarch64-unknown-elf'
env['ubuntu_toolchain_prefix'] = 'aarch64-linux-gnu'
env['is_arm'] = True
if not env['_args_given']['march']:
env['march'] = 'armv8-a+lse'
elif env['arch'] == 'x86_64':
env['address_size'] = 8
env['crosstool_ng_toolchain_prefix'] = 'x86_64-unknown-elf'
env['gem5_arch'] = 'X86'
env['buildroot_toolchain_prefix'] = 'x86_64-buildroot-linux-gnu'
env['ubuntu_toolchain_prefix'] = 'x86_64-linux-gnu'
if env['emulator'] == 'gem5':
if not env['_args_given']['machine']:
env['machine'] = 'TODO'
else:
if not env['_args_given']['machine']:
env['machine'] = 'pc'
if env['is_arm']:
env['gem5_arch'] = 'ARM'
if env['emulator'] == 'gem5':
if not env['_args_given']['machine']:
if env['dp650']:
env['machine'] = 'VExpress_GEM5_V1_DPU'
else:
env['machine'] = 'VExpress_GEM5_V1'
else:
if not env['_args_given']['machine']:
env['machine'] = 'virt'
# Buildroot
env['buildroot_build_dir'] = join(env['buildroot_out_dir'], 'build', env['buildroot_build_id'], env['arch'])
env['buildroot_download_dir'] = join(env['buildroot_out_dir'], 'download')
env['buildroot_config_file'] = join(env['buildroot_build_dir'], '.config')
env['buildroot_build_build_dir'] = join(env['buildroot_build_dir'], 'build')
env['buildroot_linux_build_dir'] = join(env['buildroot_build_build_dir'], 'linux-custom')
env['buildroot_vmlinux'] = join(env['buildroot_linux_build_dir'], 'vmlinux')
env['buildroot_host_dir'] = join(env['buildroot_build_dir'], 'host')
env['buildroot_host_usr_dir'] = join(env['buildroot_host_dir'], 'usr')
env['buildroot_host_bin_dir'] = join(env['buildroot_host_usr_dir'], 'bin')
env['buildroot_pkg_config'] = join(env['buildroot_host_bin_dir'], 'pkg-config')
env['buildroot_images_dir'] = join(env['buildroot_build_dir'], 'images')
env['buildroot_rootfs_raw_file'] = join(env['buildroot_images_dir'], 'rootfs.ext2')
env['buildroot_qcow2_file'] = env['buildroot_rootfs_raw_file'] + '.qcow2'
env['buildroot_cpio'] = join(env['buildroot_images_dir'], 'rootfs.cpio')
env['staging_dir'] = join(env['out_dir'], 'staging', env['arch'])
env['buildroot_staging_dir'] = join(env['buildroot_build_dir'], 'staging')
env['buildroot_target_dir'] = join(env['buildroot_build_dir'], 'target')
if not env['_args_given']['linux_source_dir']:
env['linux_source_dir'] = os.path.join(consts['submodules_dir'], 'linux')
common.extract_vmlinux = os.path.join(env['linux_source_dir'], 'scripts', 'extract-vmlinux')
env['linux_buildroot_build_dir'] = join(env['buildroot_build_build_dir'], 'linux-custom')
# QEMU
env['qemu_build_dir'] = join(
env['out_dir'],
'qemu',
env['qemu_build_id'],
env['qemu_build_type']
)
env['qemu_img_basename'] = 'qemu-img'
env['qemu_img_executable'] = join(env['qemu_build_dir'], env['qemu_img_basename'])
if not env['userland']:
env['qemu_executable_basename'] = 'qemu-system-{}'.format(env['arch'])
else:
env['qemu_executable_basename'] = 'qemu-{}'.format(env['arch'])
if env['qemu_which'] == 'host':
env['qemu_executable'] = env['qemu_executable_basename']
else:
if not env['userland']:
env['qemu_executable'] = join(
env['qemu_build_dir'],
'{}-softmmu'.format(env['arch']),
env['qemu_executable_basename']
)
else:
env['qemu_executable'] = join(
self.env['qemu_build_dir'],
'{}-linux-user'.format(self.env['arch']),
env['qemu_executable_basename']
)
# gem5
if not env['_args_given']['gem5_build_dir']:
env['gem5_build_dir'] = join(env['gem5_out_dir'], env['gem5_build_id'])
env['gem5_test_binaries_dir'] = join(env['gem5_out_dir'], 'test_binaries')
env['gem5_m5term'] = join(env['gem5_build_dir'], 'm5term')
env['gem5_build_build_dir'] = join(env['gem5_build_dir'], 'build')
# https://cirosantilli.com/linux-kernel-module-cheat#gem5-eclipse-configuration
env['gem5_eclipse_cproject_basename'] = '.cproject'
env['gem5_eclipse_project_basename'] = '.project'
env['gem5_eclipse_cproject_path'] = join(env['gem5_build_build_dir'], env['gem5_eclipse_cproject_basename'])
env['gem5_eclipse_project_path'] = join(env['gem5_build_build_dir'], env['gem5_eclipse_project_basename'])
env['gem5_executable_dir'] = join(env['gem5_build_build_dir'], env['gem5_arch'])
env['gem5_executable_suffix'] = '.{}'.format(env['gem5_build_type'])
env['gem5_executable'] = self.get_gem5_target_path(env, 'gem5')
env['gem5_unit_test_target'] = self.get_gem5_target_path(env, 'unittests')
env['gem5_system_dir'] = join(env['gem5_build_dir'], 'system')
env['gem5_system_binaries_dir'] = join(env['gem5_system_dir'], 'binaries')
if self.env['is_arm']:
if env['arch'] == 'arm':
gem5_bootloader_basename = 'boot.arm'
elif env['arch'] == 'aarch64':
gem5_bootloader_basename = 'boot.arm64'
env['gem5_bootloader'] = join(env['gem5_system_binaries_dir'], gem5_bootloader_basename)
else:
env['gem5_bootloader'] = None
# gem5 source
if env['_args_given']['gem5_source_dir']:
assert os.path.exists(env['gem5_source_dir'])
else:
if env['_args_given']['gem5_worktree']:
env['gem5_source_dir'] = join(env['gem5_non_default_source_root_dir'], env['gem5_worktree'])
else:
env['gem5_source_dir'] = env['gem5_default_source_dir']
env['gem5_m5_source_dir'] = join(env['gem5_source_dir'], 'util', 'm5')
if self.env['arch'] == 'x86_64':
env['gem5_m5_source_dir_build_arch'] = 'x86'
elif self.env['arch'] == 'aarch64':
env['gem5_m5_source_dir_build_arch'] = 'arm64'
else:
env['gem5_m5_source_dir_build_arch'] = env['arch']
env['gem5_m5_source_dir_build'] = join(env['gem5_m5_source_dir'], 'build', env['gem5_m5_source_dir_build_arch'], 'out', 'm5')
env['gem5_config_dir'] = join(env['gem5_source_dir'], 'configs')
env['gem5_se_file'] = join(env['gem5_config_dir'], 'example', 'se.py')
env['gem5_fs_file'] = join(env['gem5_config_dir'], 'example', 'fs.py')
# crosstool-ng
env['crosstool_ng_buildid_dir'] = join(env['crosstool_ng_out_dir'], 'build', env['crosstool_ng_build_id'])
env['crosstool_ng_install_dir'] = join(env['crosstool_ng_buildid_dir'], 'install', env['arch'])
env['crosstool_ng_bin_dir'] = join(env['crosstool_ng_install_dir'], 'bin')
env['crosstool_ng_source_copy_dir'] = join(env['crosstool_ng_buildid_dir'], 'source')
env['crosstool_ng_config'] = join(env['crosstool_ng_source_copy_dir'], '.config')
env['crosstool_ng_defconfig'] = join(env['crosstool_ng_source_copy_dir'], 'defconfig')
env['crosstool_ng_executable'] = join(env['crosstool_ng_source_copy_dir'], 'ct-ng')
env['crosstool_ng_build_dir'] = join(env['crosstool_ng_buildid_dir'], 'build')
env['crosstool_ng_download_dir'] = join(env['crosstool_ng_out_dir'], 'download')
# run
env['gem5_run_dir'] = join(env['run_dir_base'], 'gem5', env['arch'], str(env['run_id']))
env['m5out_dir'] = join(env['gem5_run_dir'], 'm5out')
env['stats_file'] = join(env['m5out_dir'], 'stats.txt')
env['gem5_trace_txt_file'] = join(env['m5out_dir'], 'trace.txt')
env['gem5_guest_terminal_file'] = join(env['m5out_dir'], 'system.terminal')
env['gem5_readfile_file'] = join(env['gem5_run_dir'], 'readfile')
env['gem5_termout_file'] = join(env['gem5_run_dir'], 'termout.txt')
env['qemu_run_dir'] = join(env['run_dir_base'], 'qemu', env['arch'], str(env['run_id']))
env['qemu_termout_file'] = join(env['qemu_run_dir'], 'termout.txt')
env['qemu_trace_basename'] = 'trace.bin'
env['qemu_trace_file'] = join(env['qemu_run_dir'], 'trace.bin')
env['qemu_trace_txt_file'] = join(env['qemu_run_dir'], 'trace.txt')
env['qemu_rrfile'] = join(env['qemu_run_dir'], 'rrfile')
env['gem5_out_dir'] = join(env['out_dir'], 'gem5')
# Ports
if not env['_args_given']['port_offset']:
try:
env['port_offset'] = int(env['run_id'])
except ValueError:
env['port_offset'] = 0
if env['emulator'] == 'gem5':
# Tims 4 because gem5 now has 3 UARTs tha take up the previous ports:
# https://github.com/cirosantilli/linux-kernel-module-cheat/issues/131
env['gem5_telnet_port'] = 3456 + env['port_offset'] * 4
env['gdb_port'] = 7000 + env['port_offset']
else:
env['qemu_base_port'] = 45454 + 10 * env['port_offset']
env['qemu_monitor_port'] = env['qemu_base_port'] + 0
env['qemu_hostfwd_generic_port'] = env['qemu_base_port'] + 1
env['qemu_hostfwd_ssh_port'] = env['qemu_base_port'] + 2
env['qemu_gdb_port'] = env['qemu_base_port'] + 3
env['extra_serial_port'] = env['qemu_base_port'] + 4
env['gdb_port'] = env['qemu_gdb_port']