common.py 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281
  1. #!/usr/bin/env python3
  2. import argparse
  3. import bisect
  4. import collections
  5. import copy
  6. import datetime
  7. import enum
  8. import functools
  9. import glob
  10. import inspect
  11. import itertools
  12. import json
  13. import math
  14. import os
  15. import platform
  16. import pathlib
  17. import queue
  18. import re
  19. import shutil
  20. import signal
  21. import subprocess
  22. import sys
  23. import threading
  24. from typing import Union
  25. import time
  26. import urllib
  27. import urllib.request
  28. from shell_helpers import LF
  29. # https://cirosantilli.com/china-dictatorship/#mirrors
  30. import china_dictatorship
  31. assert "Tiananmen Square protests" in china_dictatorship.get_data()
  32. import cli_function
  33. import path_properties
  34. import shell_helpers
  35. import thread_pool
  36. common = sys.modules[__name__]
  37. # Fixed parameters that don't depend on CLI arguments.
  38. consts = {}
  39. consts['repo_short_id'] = 'lkmc'
  40. consts['linux_kernel_version'] = '5.9.2'
  41. # https://stackoverflow.com/questions/20010199/how-to-determine-if-a-process-runs-inside-lxc-docker
  42. consts['in_docker'] = os.path.exists('/.dockerenv')
  43. consts['root_dir'] = os.path.dirname(os.path.abspath(__file__))
  44. consts['data_dir'] = os.path.join(consts['root_dir'], 'data')
  45. consts['p9_dir'] = os.path.join(consts['data_dir'], '9p')
  46. consts['gem5_non_default_source_root_dir'] = os.path.join(consts['data_dir'], 'gem5')
  47. if consts['in_docker']:
  48. # fatal: unsafe repository ('/root/lkmc' is owned by someone else)
  49. # Fuck these error checks, let me shoot my feet in peace.
  50. # The best solution would be to actually get Docker to mount
  51. # the current diretory as root. But I've never been able to do that:
  52. # * https://stackoverflow.com/questions/51973179/docker-mount-volumes-as-root
  53. # * https://unix.stackexchange.com/questions/523492/how-to-mount-files-as-specific-user-when-using-docker-namespace-remapping
  54. # * https://stackoverflow.com/questions/35291520/docker-and-userns-remap-how-to-manage-volume-permissions-to-share-data-betwee
  55. # So for now we see as owner e.g. 1000:1000 on the volume, and root:root on /.
  56. # '*' to ignore all was added on Git 2.36... Without that we would need to add every single submodule to the list.
  57. # * https://stackoverflow.com/questions/71901632/fatal-unsafe-repository-home-repon-is-owned-by-someone-else
  58. # * https://stackoverflow.com/questions/71849415/i-cannot-add-the-parent-directory-to-safe-directory-in-git/71904131#71904131
  59. # * https://www.reddit.com/r/docker/comments/o8bnft/is_it_possible_to_mount_files_with_readwrite/
  60. subprocess.check_output(['git', 'config', '--global', '--add', 'safe.directory', '*'])
  61. consts['out_dir'] = os.path.join(consts['root_dir'], 'out.docker')
  62. else:
  63. consts['out_dir'] = os.path.join(consts['root_dir'], 'out')
  64. consts['readme'] = os.path.join(consts['root_dir'], 'README.adoc')
  65. consts['out_doc_dir'] = os.path.join(consts['out_dir'], 'doc')
  66. consts['readme_out'] = os.path.join(consts['out_dir'], 'README.html')
  67. consts['build_doc_log'] = os.path.join(consts['out_dir'], 'build-doc.log')
  68. consts['build_doc_multipage_log'] = os.path.join(consts['out_dir'], 'build-doc-multipage.log')
  69. consts['gem5_out_dir'] = os.path.join(consts['out_dir'], 'gem5')
  70. consts['kernel_modules_build_base_dir'] = os.path.join(consts['out_dir'], 'kernel_modules')
  71. consts['buildroot_out_dir'] = os.path.join(consts['out_dir'], 'buildroot')
  72. consts['gem5_m5_build_dir'] = os.path.join(consts['out_dir'], 'util', 'm5')
  73. consts['run_dir_base'] = os.path.join(consts['out_dir'], 'run')
  74. consts['crosstool_ng_out_dir'] = os.path.join(consts['out_dir'], 'crosstool-ng')
  75. consts['test_boot_benchmark_file'] = os.path.join(consts['out_dir'], 'test-boot.txt')
  76. consts['packages_dir'] = os.path.join(consts['root_dir'], 'buildroot_packages')
  77. consts['kernel_modules_subdir'] = 'kernel_modules'
  78. consts['kernel_modules_source_dir'] = os.path.join(consts['root_dir'], consts['kernel_modules_subdir'])
  79. consts['userland_subdir'] = 'userland'
  80. consts['userland_source_dir'] = os.path.join(consts['root_dir'], consts['userland_subdir'])
  81. consts['userland_libs_basename'] = 'libs'
  82. consts['userland_source_libs_dir'] = os.path.join(consts['userland_source_dir'], consts['userland_libs_basename'])
  83. consts['userland_source_arch_dir'] = os.path.join(consts['userland_source_dir'], 'arch')
  84. consts['userland_executable_ext'] = '.out'
  85. consts['baremetal_executable_ext'] = '.elf'
  86. consts['baremetal_max_text_size'] = 0x1000000
  87. consts['baremetal_memory_size'] = 0x2000000
  88. consts['include_subdir'] = consts['repo_short_id']
  89. consts['include_source_dir'] = os.path.join(consts['root_dir'], consts['include_subdir'])
  90. consts['submodules_dir'] = os.path.join(consts['root_dir'], 'submodules')
  91. consts['buildroot_source_dir'] = os.path.join(consts['submodules_dir'], 'buildroot')
  92. consts['crosstool_ng_source_dir'] = os.path.join(consts['submodules_dir'], 'crosstool-ng')
  93. consts['crosstool_ng_supported_archs'] = set(['arm', 'aarch64'])
  94. consts['linux_source_dir'] = os.path.join(consts['submodules_dir'], 'linux')
  95. consts['linux_config_dir'] = os.path.join(consts['root_dir'], 'linux_config')
  96. consts['gem5_default_source_dir'] = os.path.join(consts['submodules_dir'], 'gem5')
  97. consts['googletest_source_dir'] = os.path.join(consts['submodules_dir'], 'googletest')
  98. consts['rootfs_overlay_dir'] = os.path.join(consts['root_dir'], 'rootfs_overlay')
  99. consts['extract_vmlinux'] = os.path.join(consts['linux_source_dir'], 'scripts', 'extract-vmlinux')
  100. consts['qemu_source_dir'] = os.path.join(consts['submodules_dir'], 'qemu')
  101. consts['parsec_benchmark_source_dir'] = os.path.join(consts['submodules_dir'], 'parsec-benchmark')
  102. consts['ccache_dir'] = os.path.join('/usr', 'lib', 'ccache')
  103. consts['default_build_id'] = 'default'
  104. consts['arch_short_to_long_dict'] = collections.OrderedDict([
  105. ('x', 'x86_64'),
  106. ('a', 'arm'),
  107. ('A', 'aarch64'),
  108. ])
  109. # All long arch names.
  110. consts['all_long_archs'] = [consts['arch_short_to_long_dict'][k] for k in consts['arch_short_to_long_dict']]
  111. # All long and short arch names.
  112. consts['arch_choices'] = set()
  113. for key in consts['arch_short_to_long_dict']:
  114. consts['arch_choices'].add(key)
  115. consts['arch_choices'].add(consts['arch_short_to_long_dict'][key])
  116. consts['default_arch'] = 'x86_64'
  117. consts['gem5_cpt_prefix'] = '^cpt\.'
  118. def git_sha(repo_path):
  119. return subprocess.check_output(['git', '-C', repo_path, 'log', '-1', '--format=%H']).decode().rstrip()
  120. consts['sha'] = common.git_sha(consts['root_dir'])
  121. consts['release_dir'] = os.path.join(consts['out_dir'], 'release')
  122. consts['release_zip_file'] = os.path.join(consts['release_dir'], 'lkmc-{}.zip'.format(consts['sha']))
  123. consts['github_repo_id'] = 'cirosantilli/linux-kernel-module-cheat'
  124. consts['github_repo_url'] = 'https://github.com/' + consts['github_repo_id']
  125. consts['homepage_url'] = 'https://cirosantilli.com/linux-kernel-module-cheat'
  126. consts['asm_ext'] = '.S'
  127. consts['c_ext'] = '.c'
  128. consts['cxx_ext'] = '.cpp'
  129. consts['header_ext'] = '.h'
  130. consts['kernel_module_ext'] = '.ko'
  131. consts['obj_ext'] = '.o'
  132. # https://cirosantilli.com/linux-kernel-module-cheat#baremetal-cpp
  133. consts['baremetal_build_in_exts'] = [
  134. consts['asm_ext'],
  135. consts['c_ext'],
  136. ]
  137. consts['build_in_exts'] = consts['baremetal_build_in_exts'] + [
  138. consts['cxx_ext']
  139. ]
  140. consts['userland_out_exts'] = [
  141. consts['userland_executable_ext'],
  142. consts['obj_ext'],
  143. ]
  144. consts['default_config_file'] = os.path.join(consts['data_dir'], 'config.py')
  145. consts['serial_magic_exit_status_regexp_string'] = b'lkmc_exit_status_(\d+)'
  146. consts['baremetal_lib_basename'] = 'lib'
  147. consts['emulator_userland_only_short_to_long_dict'] = collections.OrderedDict([
  148. ('n', 'native'),
  149. ])
  150. consts['all_userland_only_emulators'] = set()
  151. for key in consts['emulator_userland_only_short_to_long_dict']:
  152. consts['all_userland_only_emulators'].add(key)
  153. consts['all_userland_only_emulators'].add(consts['emulator_userland_only_short_to_long_dict'][key])
  154. consts['emulator_short_to_long_dict'] = collections.OrderedDict([
  155. ('q', 'qemu'),
  156. ('g', 'gem5'),
  157. ])
  158. consts['emulator_short_to_long_dict'].update(consts['emulator_userland_only_short_to_long_dict'])
  159. consts['all_long_emulators'] = [consts['emulator_short_to_long_dict'][k] for k in consts['emulator_short_to_long_dict']]
  160. consts['emulator_choices'] = set()
  161. for key in consts['emulator_short_to_long_dict']:
  162. consts['emulator_choices'].add(key)
  163. consts['emulator_choices'].add(consts['emulator_short_to_long_dict'][key])
  164. consts['host_arch'] = platform.processor()
  165. consts['guest_lkmc_home'] = os.sep + consts['repo_short_id']
  166. consts['build_type_choices'] = [
  167. # -O2 -g
  168. 'opt',
  169. # -O0 -g
  170. 'debug'
  171. ]
  172. consts['gem5_build_type_choices'] = consts['build_type_choices'] + [
  173. 'fast', 'prof', 'perf',
  174. ]
  175. consts['build_type_default'] = 'opt'
  176. # Files whose basename start with this are gitignored.
  177. consts['tmp_prefix'] = 'tmp.'
  178. class ExitLoop(Exception):
  179. pass
  180. class LkmcCliFunction(cli_function.CliFunction):
  181. '''
  182. Common functionality shared across our CLI functions:
  183. * command timing
  184. * a lot some common flags, e.g.: --arch, --dry-run, --quiet, --verbose
  185. * a lot of helpers that depend on self.env
  186. +
  187. self.env contains the command line arguments + a ton of values derived from those.
  188. +
  189. It would be beautiful to do this evaluation in a lazy way, e.g. with functions +
  190. cache decorators:
  191. https://stackoverflow.com/questions/815110/is-there-a-decorator-to-simply-cache-function-return-values
  192. '''
  193. def __init__(
  194. self,
  195. *args,
  196. defaults=None,
  197. **kwargs
  198. ):
  199. '''
  200. :ptype defaults: Dict[str,Any]
  201. :param defaults: override the default value of an argument
  202. '''
  203. kwargs['default_config_file'] = consts['default_config_file']
  204. kwargs['extra_config_params'] = os.path.basename(inspect.getfile(self.__class__))
  205. if defaults is None:
  206. defaults = {}
  207. self._defaults = defaults
  208. self._is_common = True
  209. self._common_args = set()
  210. super().__init__(*args, **kwargs)
  211. self.print_lock = threading.Lock()
  212. # Args for all scripts.
  213. arches = consts['arch_short_to_long_dict']
  214. arches_string = []
  215. for arch_short in arches:
  216. arch_long = arches[arch_short]
  217. arches_string.append('{} ({})'.format(arch_long, arch_short))
  218. arches_string = ', '.join(arches_string)
  219. self.add_argument(
  220. '-A',
  221. '--all-archs',
  222. default=False,
  223. help='''\
  224. Run action for all supported --archs archs. Ignore --archs.
  225. '''.format(arches_string)
  226. )
  227. self.add_argument(
  228. '-a',
  229. '--arch',
  230. action='append',
  231. choices=consts['arch_choices'],
  232. default=[consts['default_arch']],
  233. dest='archs',
  234. help='''\
  235. CPU architecture to use. If given multiple times, run the action
  236. for each arch sequentially in that order. If one of them fails, stop running.
  237. Valid archs: {}
  238. '''.format(arches_string)
  239. )
  240. self.add_argument(
  241. '--ccache',
  242. default=True,
  243. help='''\
  244. Enable or disable ccache: https://cirosantilli.com/linux-kernel-module-cheat#ccache
  245. '''
  246. )
  247. self.add_argument(
  248. '--china',
  249. default=False,
  250. help='''\
  251. https://cirosantilli.com/linux-kernel-module-cheat#china
  252. '''
  253. )
  254. self.add_argument(
  255. '--disk-image',
  256. )
  257. self.add_argument(
  258. '--dry-run',
  259. default=False,
  260. help='''\
  261. Print the commands that would be run, but don't run them.
  262. We aim display every command that modifies the filesystem state, and generate
  263. Bash equivalents even for actions taken directly in Python without shelling out.
  264. mkdir are generally omitted since those are obvious
  265. See also: https://cirosantilli.com/linux-kernel-module-cheat#dry-run
  266. '''
  267. )
  268. self.add_argument(
  269. '--gcc-which',
  270. choices=[
  271. 'buildroot',
  272. 'crosstool-ng',
  273. 'host',
  274. 'host-baremetal'
  275. ],
  276. default='buildroot',
  277. help='''\
  278. Which toolchain binaries to use:
  279. - buildroot: the ones we built with ./build-buildroot. For userland, links to glibc.
  280. - crosstool-ng: the ones we built with ./build-crosstool-ng. For baremetal, links to newlib.
  281. - host: the host distro pre-packaged userland ones. For userland, links to glibc.
  282. - host-baremetal: the host distro pre-packaged bare one. For baremetal, links to newlib.
  283. '''
  284. )
  285. self.add_argument(
  286. '--march',
  287. help='''\
  288. GCC -march option to use. Currently only used for the more LKMC-specific builds such as
  289. ./build-userland and ./build-baremetal. Maybe we will use it for more things some day.
  290. '''
  291. )
  292. self.add_argument(
  293. '--mode',
  294. choices=('userland', 'baremetal'),
  295. default=None,
  296. help='''Differentiate between userland and baremetal for scripts that can do both.
  297. ./run differentiates between them based on the --userland and --baremetal options,
  298. however those options take arguments, Certain scripts can be run on either user or baremetal mode.
  299. If given, this differentiates between them.
  300. '''
  301. )
  302. self.add_argument(
  303. '-j',
  304. '--nproc',
  305. default=len(os.sched_getaffinity(0)),
  306. type=int,
  307. help='''Number of processors (Jobs) to use for the action.''',
  308. )
  309. self.add_argument(
  310. '-q',
  311. '--quiet',
  312. default=False,
  313. help='''\
  314. Don't print anything to stdout, except if it is part of an interactive terminal.
  315. TODO: implement fully, some stuff is escaping it currently.
  316. '''
  317. )
  318. self.add_argument(
  319. '--quit-on-fail',
  320. default=True,
  321. help='''\
  322. Stop running at the first failed test.
  323. '''
  324. )
  325. self.add_argument(
  326. '--show-cmds',
  327. default=True,
  328. help='''\
  329. Print the exact Bash command equivalents being run by this script.
  330. Implied by --quiet.
  331. '''
  332. )
  333. self.add_argument(
  334. '--show-time',
  335. default=True,
  336. help='''\
  337. Print how long it took to run the command at the end.
  338. Implied by --quiet.
  339. '''
  340. )
  341. self.add_argument(
  342. '-v',
  343. '--verbose',
  344. default=False,
  345. help='Show full compilation commands when they are not shown by default.'
  346. )
  347. # Gem5 args.
  348. self.add_argument(
  349. '--dp650', default=False,
  350. help='Use the ARM DP650 display processor instead of the default HDLCD on gem5.'
  351. )
  352. self.add_argument(
  353. '--gem5-build-dir',
  354. help='''\
  355. Use the given directory as the gem5 build directory.
  356. Ignore --gem5-build-id and --gem5-build-type.
  357. '''
  358. )
  359. self.add_argument(
  360. '-M',
  361. '--gem5-build-id',
  362. help='''\
  363. gem5 build ID. Allows you to keep multiple separate gem5 builds.
  364. Default: {}
  365. '''.format(consts['default_build_id'])
  366. )
  367. self.add_argument(
  368. '--gem5-build-type',
  369. choices=consts['gem5_build_type_choices'],
  370. default=consts['build_type_default'],
  371. help='gem5 build type, most often used for "debug" builds.'
  372. )
  373. self.add_argument(
  374. '--gem5-clang',
  375. default=False,
  376. help='''\
  377. Build gem5 with clang and set the --gem5-build-id to 'clang' by default.
  378. '''
  379. )
  380. self.add_argument(
  381. '--gem5-source-dir',
  382. help='''\
  383. Use the given directory as the gem5 source tree. Ignore `--gem5-worktree`.
  384. '''
  385. )
  386. self.add_argument(
  387. '-N',
  388. '--gem5-worktree',
  389. help='''\
  390. Create and use a git worktree of the gem5 submodule.
  391. See: https://cirosantilli.com/linux-kernel-module-cheat#gem5-worktree
  392. '''
  393. )
  394. # Linux kernel.
  395. self.add_argument(
  396. '--linux-build-dir',
  397. help='''\
  398. Use the given directory as the Linux build directory. Ignore --linux-build-id.
  399. '''
  400. )
  401. self.add_argument(
  402. '-L',
  403. '--linux-build-id',
  404. default=consts['default_build_id'],
  405. help='''\
  406. Linux build ID. Allows you to keep multiple separate Linux builds.
  407. '''
  408. )
  409. self.add_argument(
  410. '--linux-exec',
  411. help='''\
  412. Use the given executable Linux kernel image. Ignored in userland and baremetal modes,
  413. Remember that different emulators may take different types of image, see:
  414. https://cirosantilli.com/linux-kernel-module-cheat#vmlinux-vs-bzimage-vs-zimage-vs-image
  415. ''',
  416. )
  417. self.add_argument(
  418. '--linux-source-dir',
  419. help='''\
  420. Use the given directory as the Linux source tree.
  421. '''
  422. )
  423. self.add_argument(
  424. '--initramfs',
  425. default=False,
  426. help='''\
  427. See: https://cirosantilli.com/linux-kernel-module-cheat#initramfs
  428. '''
  429. )
  430. self.add_argument(
  431. '--initrd',
  432. default=False,
  433. help='''\
  434. For Buildroot: create a CPIO root filessytem.
  435. For QEMU use that CPUI root filesystem initrd instead of the default ext2.
  436. See: https://cirosantilli.com/linux-kernel-module-cheat#initrd
  437. '''
  438. )
  439. # Baremetal.
  440. self.add_argument(
  441. '-b',
  442. '--baremetal',
  443. action='append',
  444. help='''\
  445. Use the given baremetal executable instead of the Linux kernel.
  446. If the path points to a source code inside baremetal/, then the
  447. corresponding executable is automatically found.
  448. '''
  449. )
  450. # Buildroot.
  451. self.add_argument(
  452. '--buildroot-build-id',
  453. default=consts['default_build_id'],
  454. help='Buildroot build ID. Allows you to keep multiple separate gem5 builds.'
  455. )
  456. self.add_argument(
  457. '--buildroot-linux',
  458. default=False,
  459. help='Boot with the Buildroot Linux kernel instead of our custom built one. Mostly for sanity checks.'
  460. )
  461. # Android.
  462. self.add_argument(
  463. '--rootfs-type',
  464. default='buildroot',
  465. choices=('buildroot', 'android'),
  466. help='Which rootfs to use.'
  467. )
  468. self.add_argument(
  469. '--android-version', default='8.1.0_r60',
  470. help='Which android version to use. implies --rootfs-type android'
  471. )
  472. self.add_argument(
  473. '--android-base-dir',
  474. help='''\
  475. If given, place all android sources and build files into the given directory.
  476. One application of this is to put those large directories in your HD instead
  477. of SSD.
  478. '''
  479. )
  480. # crosstool-ng
  481. self.add_argument(
  482. '--crosstool-ng-build-id',
  483. default=consts['default_build_id'],
  484. help='Crosstool-NG build ID. Allows you to keep multiple separate crosstool-NG builds.'
  485. )
  486. self.add_argument(
  487. '--docker',
  488. default=False,
  489. help='''\
  490. Use the docker download Ubuntu root filesystem instead of the default Buildroot one.
  491. '''
  492. )
  493. # QEMU.
  494. self.add_argument(
  495. '--qemu-build-id',
  496. default=consts['default_build_id'],
  497. help='QEMU build ID. Allows you to keep multiple separate QEMU builds.'
  498. )
  499. self.add_argument(
  500. '--qemu-build-type',
  501. choices=consts['build_type_choices'],
  502. default=consts['build_type_default'],
  503. help='QEMU build type, most often used for "debug" vs optimized builds.'
  504. )
  505. self.add_argument(
  506. '--qemu-which',
  507. choices=[consts['repo_short_id'], 'host'],
  508. default=consts['repo_short_id'],
  509. help='''\
  510. Which qemu binaries to use: qemu-system-, qemu-, qemu-img, etc.:
  511. - lkmc: the ones we built with ./build-qemu
  512. - host: the host distro pre-packaged provided ones
  513. '''
  514. )
  515. self.add_argument(
  516. '--machine',
  517. help='''\
  518. Machine type:
  519. * QEMU default: -machine virt
  520. * gem5 default: --machine-type VExpress_GEM5_V1
  521. More infor on platforms at:
  522. https://cirosantilli.com/linux-kernel-module-cheat#gem5-arm-platforms
  523. '''
  524. )
  525. # Userland.
  526. self.add_argument(
  527. '--copy-overlay',
  528. default=True,
  529. help='''\
  530. Copy userland build outputs to the overlay directory which will be put inside
  531. the disk image. If not given explicitly, this is disabled automatically when certain
  532. options are given, for example --static, since users don't usually want
  533. static executables to be placed in the final image, but rather only for
  534. user mode simulations in simulators that don't support dynamic linking like gem5.
  535. '''
  536. )
  537. self.add_argument(
  538. '--host',
  539. default=False,
  540. help='''\
  541. Use the host toolchain and other dependencies to build exectuables for host execution.
  542. Automatically place the build output on a separate directory from non --host builds,
  543. e.g. by defaulting --userland-build-id host if that option has effect for the package.
  544. Make --copy-overlay default to False as the generated executables can't in general
  545. be run in the guest.
  546. ''',
  547. )
  548. self.add_argument(
  549. '--out-rootfs-overlay-dir-prefix',
  550. default='',
  551. help='''\
  552. Place the output files of userland build outputs inside the image within this
  553. additional prefix. This is mostly useful to place different versions of binaries
  554. with different build parameters inside image to compare them. See:
  555. * https://cirosantilli.com/linux-kernel-module-cheat#update-the-buildroot-toolchain
  556. * https://cirosantilli.com/linux-kernel-module-cheat#out-rootfs-overlay-dir
  557. '''
  558. )
  559. self.add_argument(
  560. '--package',
  561. action='append',
  562. help='''\
  563. Request to install a package in the target root filesystem, or indicate that it is present
  564. when building examples that rely on it or running tests for those examples.
  565. ''',
  566. )
  567. self.add_argument(
  568. '--package-all',
  569. action='store_true',
  570. help='''\
  571. Indicate that all packages used by our userland/ examples with --package
  572. are available.
  573. ''',
  574. )
  575. self.add_argument(
  576. '--print-cmd-oneline',
  577. action='store_true',
  578. help='''\
  579. Print generated commands in a single line:
  580. https://cirosantilli.com/linux-kernel-module-cheat#dry-run
  581. '''
  582. )
  583. self.add_argument(
  584. '--static',
  585. default=False,
  586. help='''\
  587. Build userland executables statically. Set --userland-build-id to 'static'
  588. if one was not given explicitly. See also:
  589. https://cirosantilli.com/linux-kernel-module-cheat#user-mode-static-executables
  590. ''',
  591. )
  592. self.add_argument(
  593. '-u',
  594. '--userland',
  595. action='append',
  596. help='''\
  597. Run the given userland executable in user mode instead of booting the Linux kernel
  598. in full system mode. In gem5, user mode is called Syscall Emulation (SE) mode and
  599. uses se.py. Path resolution is similar to --baremetal.
  600. * https://cirosantilli.com/linux-kernel-module-cheat#userland-setup-getting-started
  601. * https://cirosantilli.com/linux-kernel-module-cheat#gem5-syscall-emulation-mode
  602. This option may be given multiple times only in gem5 syscall emulation:
  603. https://cirosantilli.com/linux-kernel-module-cheat#gem5-syscall-emulation-multiple-executables
  604. '''
  605. )
  606. self.add_argument(
  607. '--cli-args',
  608. help='''\
  609. CLI arguments used in both --userland mode simulation, and in --baremetal. See also:
  610. https://cirosantilli.com/linux-kernel-module-cheat#baremetal-command-line-arguments
  611. '''
  612. )
  613. self.add_argument(
  614. '--userland-build-id'
  615. )
  616. # Run.
  617. self.add_argument(
  618. '--background',
  619. default=False,
  620. help='''\
  621. Make programs that would take over the terminal such as QEMU full system run on the
  622. background instead.
  623. Currently only implemented for ./run.
  624. Interactive input cannot be given.
  625. Send QEMU serial output to a file instead of the host terminal.
  626. TODO: use a port instead. If only there was a way to redirect a serial to multiple
  627. places, both to a port and a file? We use the file currently to be able to have
  628. any output at all.
  629. https://superuser.com/questions/1373226/how-to-redirect-qemu-serial-output-to-both-a-file-and-the-terminal-or-a-port
  630. '''
  631. )
  632. self.add_argument(
  633. '--in-tree',
  634. default=False,
  635. help='''\
  636. Place build output inside source tree to conveniently run it, especially when
  637. building with the host native toolchain.
  638. When running, use in-tree executables instead of out-of-tree ones,
  639. userland/c/hello resolves userland/c/hello.out instead of the out-of-tree one.
  640. Currently only supported by userland scripts such as ./build-userland and
  641. ./run --userland.
  642. ''',
  643. )
  644. self.add_argument(
  645. '--port-offset',
  646. type=int,
  647. help='''\
  648. Increase the ports to be used such as for GDB by an offset to run multiple
  649. instances in parallel. Default: the run ID (-n) if that is an integer, otherwise 0.
  650. '''
  651. )
  652. self.add_argument(
  653. '--prebuilt',
  654. default=False,
  655. help='''\
  656. Use prebuilt packaged host utilities as much as possible instead
  657. of the ones we built ourselves. Saves build time, but decreases
  658. the likelihood of incompatibilities.
  659. '''
  660. )
  661. self.add_argument(
  662. '--run-id',
  663. default='0',
  664. help='''\
  665. ID for run outputs such as gem5's m5out. Allows you to do multiple runs,
  666. and then inspect separate outputs later in different output directories.
  667. '''
  668. )
  669. # Misc.
  670. emulators = consts['emulator_short_to_long_dict']
  671. emulators_string = []
  672. for emulator_short in emulators:
  673. emulator_long = emulators[emulator_short]
  674. emulators_string.append('{} ({})'.format(emulator_long, emulator_short))
  675. emulators_string = ', '.join(emulators_string)
  676. self.add_argument(
  677. '--all-emulators', default=False,
  678. help='''\
  679. Run action for all supported emulators. Ignore --emulator.
  680. '''.format(emulators_string)
  681. )
  682. self.add_argument(
  683. '-e',
  684. '--emulator',
  685. action='append',
  686. choices=consts['emulator_choices'],
  687. default=['qemu'],
  688. dest='emulators',
  689. help='''\
  690. Emulator to use. If given multiple times, semantics are similar to --arch.
  691. Valid emulators: {}
  692. "native" means running natively on host. It is only supported for userland,
  693. and you must have built the program for native running, see:
  694. https://cirosantilli.com/linux-kernel-module-cheat#userland-setup-getting-started-natively
  695. Incompatible archs are skipped.
  696. '''.format(emulators_string)
  697. )
  698. self._is_common = False
  699. def __call__(self, *args, **kwargs):
  700. '''
  701. For Python code calls, in addition to base class behaviour:
  702. * print the CLI equivalent of the call
  703. * automatically forward common arguments
  704. '''
  705. print_cmd = ['./' + self.extra_config_params, LF]
  706. if 'print_cmd_oneline' in kwargs:
  707. force_oneline = kwargs['print_cmd_oneline']
  708. del kwargs['print_cmd_oneline']
  709. else:
  710. force_oneline=False
  711. for line in self.get_cli(**kwargs):
  712. print_cmd.extend(line)
  713. print_cmd.append(LF)
  714. if not ('quiet' in kwargs and kwargs['quiet']):
  715. shell_helpers.ShellHelpers().print_cmd(
  716. print_cmd,
  717. force_oneline=force_oneline
  718. )
  719. return super().__call__(**kwargs)
  720. def _handle_thread_pool_errors(self, my_thread_pool):
  721. handle_output_result = my_thread_pool.get_handle_output_result()
  722. if handle_output_result is not None:
  723. work_function_input, work_function_return, exception = handle_output_result
  724. if not type(exception) is thread_pool.ThreadPoolExitException:
  725. print('work_function or handle_output raised unexpectedly:')
  726. print(thread_pool.ThreadPool.exception_traceback_string(exception), end='')
  727. print('work_function_input: {}'.format(work_function_input))
  728. print('work_function_return: {}'.format(work_function_return))
  729. return 1
  730. else:
  731. return 0
  732. def _init_env(self, env):
  733. '''
  734. Update the kwargs from the command line with values derived from them.
  735. '''
  736. def join(*paths):
  737. return os.path.join(*paths)
  738. if env['emulator'] in env['emulator_short_to_long_dict']:
  739. env['emulator'] = env['emulator_short_to_long_dict'][env['emulator']]
  740. if not env['_args_given']['userland_build_id']:
  741. if env['static']:
  742. env['userland_build_id'] = 'static'
  743. elif env['host']:
  744. env['userland_build_id'] = 'host'
  745. else:
  746. env['userland_build_id'] = env['default_build_id']
  747. if not env['_args_given']['gem5_build_id']:
  748. if env['_args_given']['gem5_clang']:
  749. env['gem5_build_id'] = 'clang'
  750. elif env['_args_given']['gem5_worktree']:
  751. env['gem5_build_id'] = env['gem5_worktree']
  752. else:
  753. env['gem5_build_id'] = consts['default_build_id']
  754. env['is_arm'] = False
  755. # Our approach is as follows:
  756. #
  757. # * compilers: control maximum arch version emitted explicitly -mcpu
  758. # +
  759. # This helps to prevent blowing up simulation unnecessarily.
  760. # +
  761. # It does not matter if we miss any perf features for QEMU which is functional,
  762. # but it could matter for gem5 perf simulations.
  763. # * assemblers: enable as many features as possible.
  764. # +
  765. # Well, if I'm explicitly writing down the instructions, I want
  766. # my emulator to blow up in peace!
  767. # * emulators: enable as many features as possible
  768. # +
  769. # This is the gem5 default behavior, for QEMU TODO not sure if default,
  770. # but we select it explicitly with -cpu max.
  771. # https://habkost.net/posts/2017/03/qemu-cpu-model-probing-story.html
  772. # +
  773. # We doe this because QEMU does not add all possible Cortex Axx, there are
  774. # just too many, and gem5 does not allow selecting lower feature in general.
  775. env['int_size'] = 4
  776. if env['arch'] == 'arm':
  777. # TODO this shoud be 4. But that blows up running all gem5 arm 32-bit examples.
  778. # https://cirosantilli.com/linux-kernel-module-cheat#gem5-baremetal-arm-cli-args
  779. env['address_size'] = 8
  780. env['armv'] = 7
  781. env['buildroot_toolchain_prefix'] = 'arm-buildroot-linux-gnueabihf'
  782. env['crosstool_ng_toolchain_prefix'] = 'arm-unknown-eabi'
  783. env['ubuntu_toolchain_prefix'] = 'arm-linux-gnueabihf'
  784. env['is_arm'] = True
  785. if not env['_args_given']['march']:
  786. env['march'] = 'armv8-a'
  787. elif env['arch'] == 'aarch64':
  788. env['address_size'] = 8
  789. env['armv'] = 8
  790. env['buildroot_toolchain_prefix'] = 'aarch64-buildroot-linux-gnu'
  791. env['crosstool_ng_toolchain_prefix'] = 'aarch64-unknown-elf'
  792. env['ubuntu_toolchain_prefix'] = 'aarch64-linux-gnu'
  793. env['is_arm'] = True
  794. if not env['_args_given']['march']:
  795. env['march'] = 'armv8-a+lse'
  796. elif env['arch'] == 'x86_64':
  797. env['address_size'] = 8
  798. env['crosstool_ng_toolchain_prefix'] = 'x86_64-unknown-elf'
  799. env['gem5_arch'] = 'X86'
  800. env['buildroot_toolchain_prefix'] = 'x86_64-buildroot-linux-gnu'
  801. env['ubuntu_toolchain_prefix'] = 'x86_64-linux-gnu'
  802. if env['emulator'] == 'gem5':
  803. if not env['_args_given']['machine']:
  804. env['machine'] = 'TODO'
  805. else:
  806. if not env['_args_given']['machine']:
  807. env['machine'] = 'pc'
  808. if env['is_arm']:
  809. env['gem5_arch'] = 'ARM'
  810. if env['emulator'] == 'gem5':
  811. if not env['_args_given']['machine']:
  812. if env['dp650']:
  813. env['machine'] = 'VExpress_GEM5_V1_DPU'
  814. else:
  815. env['machine'] = 'VExpress_GEM5_V1'
  816. else:
  817. if not env['_args_given']['machine']:
  818. env['machine'] = 'virt'
  819. # Buildroot
  820. env['buildroot_build_dir'] = join(env['buildroot_out_dir'], 'build', env['buildroot_build_id'], env['arch'])
  821. env['buildroot_download_dir'] = join(env['buildroot_out_dir'], 'download')
  822. env['buildroot_config_file'] = join(env['buildroot_build_dir'], '.config')
  823. env['buildroot_build_build_dir'] = join(env['buildroot_build_dir'], 'build')
  824. env['buildroot_linux_build_dir'] = join(env['buildroot_build_build_dir'], 'linux-custom')
  825. env['buildroot_vmlinux'] = join(env['buildroot_linux_build_dir'], 'vmlinux')
  826. env['buildroot_host_dir'] = join(env['buildroot_build_dir'], 'host')
  827. env['buildroot_host_usr_dir'] = join(env['buildroot_host_dir'], 'usr')
  828. env['buildroot_host_bin_dir'] = join(env['buildroot_host_usr_dir'], 'bin')
  829. env['buildroot_pkg_config'] = join(env['buildroot_host_bin_dir'], 'pkg-config')
  830. env['buildroot_images_dir'] = join(env['buildroot_build_dir'], 'images')
  831. env['buildroot_rootfs_raw_file'] = join(env['buildroot_images_dir'], 'rootfs.ext2')
  832. env['buildroot_qcow2_file'] = env['buildroot_rootfs_raw_file'] + '.qcow2'
  833. env['buildroot_cpio'] = join(env['buildroot_images_dir'], 'rootfs.cpio')
  834. env['staging_dir'] = join(env['out_dir'], 'staging', env['arch'])
  835. env['buildroot_staging_dir'] = join(env['buildroot_build_dir'], 'staging')
  836. env['buildroot_target_dir'] = join(env['buildroot_build_dir'], 'target')
  837. if not env['_args_given']['linux_source_dir']:
  838. env['linux_source_dir'] = os.path.join(consts['submodules_dir'], 'linux')
  839. common.extract_vmlinux = os.path.join(env['linux_source_dir'], 'scripts', 'extract-vmlinux')
  840. env['linux_buildroot_build_dir'] = join(env['buildroot_build_build_dir'], 'linux-custom')
  841. # QEMU
  842. env['qemu_build_dir'] = join(
  843. env['out_dir'],
  844. 'qemu',
  845. env['qemu_build_id'],
  846. env['qemu_build_type']
  847. )
  848. env['qemu_img_basename'] = 'qemu-img'
  849. env['qemu_img_executable'] = join(env['qemu_build_dir'], env['qemu_img_basename'])
  850. if not env['userland']:
  851. env['qemu_executable_basename'] = 'qemu-system-{}'.format(env['arch'])
  852. else:
  853. env['qemu_executable_basename'] = 'qemu-{}'.format(env['arch'])
  854. if env['qemu_which'] == 'host':
  855. env['qemu_executable'] = env['qemu_executable_basename']
  856. else:
  857. if not env['userland']:
  858. env['qemu_executable'] = join(
  859. env['qemu_build_dir'],
  860. '{}-softmmu'.format(env['arch']),
  861. env['qemu_executable_basename']
  862. )
  863. else:
  864. env['qemu_executable'] = join(
  865. self.env['qemu_build_dir'],
  866. '{}-linux-user'.format(self.env['arch']),
  867. env['qemu_executable_basename']
  868. )
  869. # gem5
  870. if not env['_args_given']['gem5_build_dir']:
  871. env['gem5_build_dir'] = join(env['gem5_out_dir'], env['gem5_build_id'])
  872. env['gem5_test_binaries_dir'] = join(env['gem5_out_dir'], 'test_binaries')
  873. env['gem5_m5term'] = join(env['gem5_build_dir'], 'm5term')
  874. env['gem5_build_build_dir'] = join(env['gem5_build_dir'], 'build')
  875. # https://cirosantilli.com/linux-kernel-module-cheat#gem5-eclipse-configuration
  876. env['gem5_eclipse_cproject_basename'] = '.cproject'
  877. env['gem5_eclipse_project_basename'] = '.project'
  878. env['gem5_eclipse_cproject_path'] = join(env['gem5_build_build_dir'], env['gem5_eclipse_cproject_basename'])
  879. env['gem5_eclipse_project_path'] = join(env['gem5_build_build_dir'], env['gem5_eclipse_project_basename'])
  880. env['gem5_executable_dir'] = join(env['gem5_build_build_dir'], env['gem5_arch'])
  881. env['gem5_executable_suffix'] = '.{}'.format(env['gem5_build_type'])
  882. env['gem5_executable'] = self.get_gem5_target_path(env, 'gem5')
  883. env['gem5_unit_test_target'] = self.get_gem5_target_path(env, 'unittests')
  884. env['gem5_system_dir'] = join(env['gem5_build_dir'], 'system')
  885. env['gem5_system_binaries_dir'] = join(env['gem5_system_dir'], 'binaries')
  886. if self.env['is_arm']:
  887. if env['arch'] == 'arm':
  888. gem5_bootloader_basename = 'boot.arm'
  889. elif env['arch'] == 'aarch64':
  890. gem5_bootloader_basename = 'boot.arm64'
  891. env['gem5_bootloader'] = join(env['gem5_system_binaries_dir'], gem5_bootloader_basename)
  892. else:
  893. env['gem5_bootloader'] = None
  894. # gem5 source
  895. if env['_args_given']['gem5_source_dir']:
  896. assert os.path.exists(env['gem5_source_dir'])
  897. else:
  898. if env['_args_given']['gem5_worktree']:
  899. env['gem5_source_dir'] = join(env['gem5_non_default_source_root_dir'], env['gem5_worktree'])
  900. else:
  901. env['gem5_source_dir'] = env['gem5_default_source_dir']
  902. env['gem5_m5_source_dir'] = join(env['gem5_source_dir'], 'util', 'm5')
  903. if self.env['arch'] == 'x86_64':
  904. env['gem5_m5_source_dir_build_arch'] = 'x86'
  905. elif self.env['arch'] == 'aarch64':
  906. env['gem5_m5_source_dir_build_arch'] = 'arm64'
  907. else:
  908. env['gem5_m5_source_dir_build_arch'] = env['arch']
  909. env['gem5_m5_source_dir_build'] = join(env['gem5_m5_source_dir'], 'build', env['gem5_m5_source_dir_build_arch'], 'out', 'm5')
  910. env['gem5_config_dir'] = join(env['gem5_source_dir'], 'configs')
  911. env['gem5_se_file'] = join(env['gem5_config_dir'], 'example', 'se.py')
  912. env['gem5_fs_file'] = join(env['gem5_config_dir'], 'example', 'fs.py')
  913. # crosstool-ng
  914. env['crosstool_ng_buildid_dir'] = join(env['crosstool_ng_out_dir'], 'build', env['crosstool_ng_build_id'])
  915. env['crosstool_ng_install_dir'] = join(env['crosstool_ng_buildid_dir'], 'install', env['arch'])
  916. env['crosstool_ng_bin_dir'] = join(env['crosstool_ng_install_dir'], 'bin')
  917. env['crosstool_ng_source_copy_dir'] = join(env['crosstool_ng_buildid_dir'], 'source')
  918. env['crosstool_ng_config'] = join(env['crosstool_ng_source_copy_dir'], '.config')
  919. env['crosstool_ng_defconfig'] = join(env['crosstool_ng_source_copy_dir'], 'defconfig')
  920. env['crosstool_ng_executable'] = join(env['crosstool_ng_source_copy_dir'], 'ct-ng')
  921. env['crosstool_ng_build_dir'] = join(env['crosstool_ng_buildid_dir'], 'build')
  922. env['crosstool_ng_download_dir'] = join(env['crosstool_ng_out_dir'], 'download')
  923. # run
  924. env['gem5_run_dir'] = join(env['run_dir_base'], 'gem5', env['arch'], str(env['run_id']))
  925. env['m5out_dir'] = join(env['gem5_run_dir'], 'm5out')
  926. env['stats_file'] = join(env['m5out_dir'], 'stats.txt')
  927. env['gem5_trace_txt_file'] = join(env['m5out_dir'], 'trace.txt')
  928. env['gem5_guest_terminal_file'] = join(env['m5out_dir'], 'system.terminal')
  929. env['gem5_readfile_file'] = join(env['gem5_run_dir'], 'readfile')
  930. env['gem5_termout_file'] = join(env['gem5_run_dir'], 'termout.txt')
  931. env['qemu_run_dir'] = join(env['run_dir_base'], 'qemu', env['arch'], str(env['run_id']))
  932. env['qemu_termout_file'] = join(env['qemu_run_dir'], 'termout.txt')
  933. env['qemu_trace_basename'] = 'trace.bin'
  934. env['qemu_trace_file'] = join(env['qemu_run_dir'], 'trace.bin')
  935. env['qemu_trace_txt_file'] = join(env['qemu_run_dir'], 'trace.txt')
  936. env['qemu_rrfile'] = join(env['qemu_run_dir'], 'rrfile')
  937. env['gem5_out_dir'] = join(env['out_dir'], 'gem5')
  938. # Ports
  939. if not env['_args_given']['port_offset']:
  940. try:
  941. env['port_offset'] = int(env['run_id'])
  942. except ValueError:
  943. env['port_offset'] = 0
  944. if env['emulator'] == 'gem5':
  945. # Tims 4 because gem5 now has 3 UARTs tha take up the previous ports:
  946. # https://github.com/cirosantilli/linux-kernel-module-cheat/issues/131
  947. env['gem5_telnet_port'] = 3456 + env['port_offset'] * 4
  948. env['gdb_port'] = 7000 + env['port_offset']
  949. else:
  950. env['qemu_base_port'] = 45454 + 10 * env['port_offset']
  951. env['qemu_monitor_port'] = env['qemu_base_port'] + 0
  952. env['qemu_hostfwd_generic_port'] = env['qemu_base_port'] + 1
  953. env['qemu_hostfwd_ssh_port'] = env['qemu_base_port'] + 2
  954. env['qemu_gdb_port'] = env['qemu_base_port'] + 3
  955. env['extra_serial_port'] = env['qemu_base_port'] + 4
  956. env['gdb_port'] = env['qemu_gdb_port']
  957. env['qemu_background_serial_file'] = join(env['qemu_run_dir'], 'background.log')
  958. # gem5 QEMU polymorphism.
  959. if env['emulator'] == 'gem5':
  960. env['executable'] = env['gem5_executable']
  961. env['run_dir'] = env['gem5_run_dir']
  962. env['termout_file'] = env['gem5_termout_file']
  963. env['guest_terminal_file'] = env['gem5_guest_terminal_file']
  964. env['trace_txt_file'] = env['gem5_trace_txt_file']
  965. else:
  966. env['executable'] = env['qemu_executable']
  967. env['run_dir'] = env['qemu_run_dir']
  968. env['termout_file'] = env['qemu_termout_file']
  969. if env['background']:
  970. env['guest_terminal_file'] = env['qemu_background_serial_file']
  971. else:
  972. env['guest_terminal_file'] = env['qemu_termout_file']
  973. env['trace_txt_file'] = env['qemu_trace_txt_file']
  974. env['run_cmd_file_basename'] = 'run.sh'
  975. env['run_cmd_file'] = join(env['run_dir'], env['run_cmd_file_basename'])
  976. # Linux kernel.
  977. if not env['_args_given']['linux_build_dir']:
  978. env['linux_build_dir'] = join(env['out_dir'], 'linux', env['linux_build_id'], env['arch'])
  979. env['lkmc_vmlinux'] = join(env['linux_build_dir'], 'vmlinux')
  980. if env['arch'] == 'arm':
  981. env['android_arch'] = 'arm'
  982. env['linux_arch'] = 'arm'
  983. env['linux_image_prefix'] = join('arch', env['linux_arch'], 'boot', 'zImage')
  984. elif env['arch'] == 'aarch64':
  985. env['android_arch'] = 'arm64'
  986. env['linux_arch'] = 'arm64'
  987. env['linux_image_prefix'] = join('arch', env['linux_arch'], 'boot', 'Image')
  988. elif env['arch'] == 'x86_64':
  989. env['android_arch'] = 'x86_64'
  990. env['linux_arch'] = 'x86'
  991. env['linux_image_prefix'] = join('arch', env['linux_arch'], 'boot', 'bzImage')
  992. env['lkmc_linux_image'] = join(env['linux_build_dir'], env['linux_image_prefix'])
  993. env['buildroot_linux_image'] = join(env['buildroot_linux_build_dir'], env['linux_image_prefix'])
  994. if env['buildroot_linux']:
  995. env['vmlinux'] = env['buildroot_vmlinux']
  996. env['linux_image'] = env['buildroot_linux_image']
  997. else:
  998. env['vmlinux'] = env['lkmc_vmlinux']
  999. env['linux_image'] = env['lkmc_linux_image']
  1000. env['linux_config'] = join(env['linux_build_dir'], '.config')
  1001. if env['emulator']== 'gem5':
  1002. env['userland_quit_cmd'] = join(
  1003. env['guest_lkmc_home'],
  1004. 'gem5_exit.sh'
  1005. )
  1006. else:
  1007. env['userland_quit_cmd'] = join(
  1008. env['guest_lkmc_home'],
  1009. 'linux',
  1010. 'poweroff' + env['userland_executable_ext']
  1011. )
  1012. env['ramfs'] = env['initrd'] or env['initramfs']
  1013. if env['ramfs']:
  1014. env['initarg'] = 'rdinit'
  1015. else:
  1016. env['initarg'] = 'init'
  1017. env['quit_init'] = '{}={}'.format(env['initarg'], env['userland_quit_cmd'])
  1018. # Userland
  1019. env['userland_source_arch_arch_dir'] = join(env['userland_source_arch_dir'], env['arch'])
  1020. if env['in_tree']:
  1021. env['userland_build_dir'] = env['userland_source_dir']
  1022. else:
  1023. env['userland_build_dir'] = join(env['out_dir'], 'userland', env['userland_build_id'], env['arch'])
  1024. env['package'] = set(env['package'])
  1025. if not env['_args_given']['copy_overlay']:
  1026. if (
  1027. env['in_tree'] or
  1028. env['static'] or
  1029. env['host'] or
  1030. env['mode'] == 'baremetal'
  1031. ):
  1032. env['copy_overlay'] = False
  1033. # Kernel modules.
  1034. env['kernel_modules_build_dir'] = join(env['kernel_modules_build_base_dir'], env['arch'])
  1035. env['kernel_modules_build_subdir'] = join(env['kernel_modules_build_dir'], env['kernel_modules_subdir'])
  1036. env['kernel_modules_build_host_dir'] = join(env['kernel_modules_build_base_dir'], 'host')
  1037. env['kernel_modules_build_host_subdir'] = join(env['kernel_modules_build_host_dir'], env['kernel_modules_subdir'])
  1038. # Overlay.
  1039. # https://cirosantilli.com/linux-kernel-module-cheat#buildroot-packages-directory
  1040. env['out_rootfs_overlay_dir'] = join(env['out_dir'], 'rootfs_overlay', env['arch'])
  1041. env['out_rootfs_overlay_lkmc_dir'] = join(env['out_rootfs_overlay_dir'], env['repo_short_id'])
  1042. env['out_rootfs_overlay_bin_dir'] = join(env['out_rootfs_overlay_dir'], 'bin')
  1043. # Baremetal.
  1044. env['baremetal_source_dir'] = join(env['root_dir'], 'baremetal')
  1045. env['baremetal_source_arch_subpath'] = join('arch', env['arch'])
  1046. env['baremetal_source_arch_dir'] = join(env['baremetal_source_dir'], env['baremetal_source_arch_subpath'])
  1047. env['baremetal_source_lib_dir'] = join(env['baremetal_source_dir'], env['baremetal_lib_basename'])
  1048. env['baremetal_link_script'] = os.path.join(env['baremetal_source_dir'], 'link.ld')
  1049. if env['emulator'] == 'gem5':
  1050. env['simulator_name'] = 'gem5'
  1051. else:
  1052. env['simulator_name'] = 'qemu'
  1053. env['baremetal_build_dir'] = join(env['out_dir'], 'baremetal', env['arch'], env['simulator_name'], env['machine'])
  1054. env['baremetal_build_lib_dir'] = join(env['baremetal_build_dir'], env['baremetal_lib_basename'])
  1055. env['baremetal_syscalls_basename_noext'] = 'syscalls'
  1056. env['baremetal_syscalls_src'] = os.path.join(
  1057. env['baremetal_source_lib_dir'],
  1058. env['baremetal_syscalls_basename_noext'] + env['c_ext']
  1059. )
  1060. env['baremetal_syscalls_obj'] = os.path.join(
  1061. env['baremetal_build_lib_dir'],
  1062. env['baremetal_syscalls_basename_noext'] + env['obj_ext']
  1063. )
  1064. env['baremetal_syscalls_asm_src'] = os.path.join(
  1065. env['baremetal_source_lib_dir'],
  1066. env['baremetal_syscalls_basename_noext'] + '_asm' + env['asm_ext']
  1067. )
  1068. env['baremetal_syscalls_asm_obj'] = os.path.join(
  1069. env['baremetal_build_lib_dir'],
  1070. env['baremetal_syscalls_basename_noext'] + '_asm' + env['obj_ext']
  1071. )
  1072. if env['emulator'] == 'gem5':
  1073. if self.env['is_arm']:
  1074. if env['machine'] == 'VExpress_GEM5_V1':
  1075. env['entry_address'] = 0x80000000
  1076. env['uart_address'] = 0x1c090000
  1077. elif env['machine'] == 'RealViewPBX':
  1078. env['entry_address'] = 0x10000
  1079. env['uart_address'] = 0x10009000
  1080. else:
  1081. raise Exception('unknown machine: ' + env['machine'])
  1082. else:
  1083. env['entry_address'] = 0x40000000
  1084. env['uart_address'] = 0x09000000
  1085. env['common_basename_noext'] = env['repo_short_id']
  1086. env['baremetal_extra_obj_bootloader'] = join(
  1087. env['baremetal_build_lib_dir'],
  1088. 'bootloader{}'.format(env['obj_ext'])
  1089. )
  1090. env['baremetal_extra_obj_lkmc_common'] = join(
  1091. env['baremetal_build_lib_dir'],
  1092. env['common_basename_noext'] + env['obj_ext']
  1093. )
  1094. # Userland / baremetal common source.
  1095. env['common_c'] = os.path.join(
  1096. env['root_dir'],
  1097. env['common_basename_noext'] + env['c_ext']
  1098. )
  1099. env['common_h'] = os.path.join(
  1100. env['root_dir'],
  1101. env['common_basename_noext'] + env['header_ext']
  1102. )
  1103. if env['mode'] == 'baremetal':
  1104. env['build_dir'] = env['baremetal_build_dir']
  1105. env['extra_objs'] = [
  1106. env['baremetal_extra_obj_bootloader'],
  1107. env['baremetal_extra_obj_lkmc_common'],
  1108. env['baremetal_syscalls_asm_obj'],
  1109. env['baremetal_syscalls_obj'],
  1110. ]
  1111. env['ccflags_default'] = [
  1112. '-nostartfiles', LF,
  1113. ]
  1114. if env['arch'] == 'arm':
  1115. env['ccflags_default'].extend([
  1116. '-mhard-float', LF,
  1117. # This uses the soft float ABI for calling functions from objets in Newlib which
  1118. # our crosstool-NG config compiles with soft floats, while emiting hard float
  1119. # from C and allowing us to use it from assembly, e.g. for the VMRS instruction:
  1120. # which would otherwise fail "with selected processor does not support XXX in ARM mode"
  1121. # Bibliography:
  1122. # - https://stackoverflow.com/questions/9753749/arm-compilation-error-vfp-registered-used-by-executable-not-object-file
  1123. # - https://stackoverflow.com/questions/41131432/cross-compiling-error-selected-processor-does-not-support-fmrx-r3-fpexc-in/41131782#41131782
  1124. # - https://embeddedartistry.com/blog/2017/10/9/r1q7pksku2q3gww9rpqef0dnskphtc
  1125. '-mfloat-abi=softfp', LF,
  1126. '-mfpu=crypto-neon-fp-armv8', LF,
  1127. ])
  1128. env['ldflags'] = [
  1129. '-Wl,--section-start=.text={:#x}'.format(env['entry_address']), LF,
  1130. '-T', env['baremetal_link_script'], LF,
  1131. ]
  1132. else:
  1133. env['build_dir'] = env['userland_build_dir']
  1134. env['ccflags_default'] = []
  1135. env['extra_objs'] = []
  1136. env['ldflags'] = []
  1137. # Docker
  1138. env['docker_build_dir'] = join(env['out_dir'], 'docker', env['arch'])
  1139. env['docker_tar_dir'] = join(env['docker_build_dir'], 'export')
  1140. env['docker_tar_file'] = join(env['docker_build_dir'], 'export.tar')
  1141. env['docker_rootfs_raw_file'] = join(env['docker_build_dir'], 'export.ext2')
  1142. env['docker_qcow2_file'] = join(env['docker_rootfs_raw_file'] + '.qcow2')
  1143. if env['docker']:
  1144. env['rootfs_raw_file'] = env['docker_rootfs_raw_file']
  1145. env['qcow2_file'] = env['docker_qcow2_file']
  1146. else:
  1147. env['rootfs_raw_file'] = env['buildroot_rootfs_raw_file']
  1148. env['qcow2_file'] = env['buildroot_qcow2_file']
  1149. # Image
  1150. if env['baremetal']:
  1151. env['image'] = self.resolve_baremetal_executable(env['baremetal'][0])
  1152. # This is needed because the Linux kerne limage for certain emulators like QEMU
  1153. # might not be in plain ELF format, but rather some crazy compressed kernel format.
  1154. # https://cirosantilli.com/linux-kernel-module-cheat#vmlinux-vs-bzimage-vs-zimage-vs-image
  1155. env['image_elf'] = env['image']
  1156. source_path_noext = os.path.splitext(join(
  1157. env['root_dir'],
  1158. env['image'][len(env['baremetal_build_dir']) + 1:]
  1159. ))[0]
  1160. env['source_path'] = None
  1161. for ext in env['baremetal_build_in_exts']:
  1162. source_path = source_path_noext + ext
  1163. if os.path.exists(source_path):
  1164. env['source_path'] = source_path
  1165. break
  1166. elif env['userland']:
  1167. env['image'] = self.resolve_userland_executable(env['userland'][0])
  1168. env['image_elf'] = env['image']
  1169. source_path_noext = os.path.splitext(join(
  1170. env['userland_source_dir'],
  1171. env['image'][len(env['userland_build_dir']) + 1:]
  1172. ))[0]
  1173. env['source_path'] = None
  1174. for ext in env['build_in_exts']:
  1175. source_path = source_path_noext + ext
  1176. if os.path.exists(source_path):
  1177. env['source_path'] = source_path
  1178. break
  1179. else:
  1180. if env['emulator'] == 'gem5':
  1181. if not env['_args_given']['linux_exec']:
  1182. env['image'] = env['vmlinux']
  1183. else:
  1184. if not env['_args_given']['linux_exec']:
  1185. env['image'] = env['linux_image']
  1186. env['image_elf'] = env['vmlinux']
  1187. if env['_args_given']['linux_exec']:
  1188. env['image'] = env['linux_exec']
  1189. if not env['_args_given']['disk_image']:
  1190. if env['emulator'] == 'gem5':
  1191. if env['ramfs']:
  1192. env['disk_image'] = None
  1193. else:
  1194. env['disk_image'] = env['rootfs_raw_file']
  1195. else:
  1196. env['disk_image'] = env['qcow2_file']
  1197. # A squahfs of 'out_rootfs_overlay_dir'.
  1198. env['disk_image_2'] = env['out_rootfs_overlay_dir'] + '.squashfs'
  1199. # Android
  1200. if not env['_args_given']['android_base_dir']:
  1201. env['android_base_dir'] = join(env['out_dir'], 'android')
  1202. env['android_dir'] = join(env['android_base_dir'], env['android_version'])
  1203. env['android_build_dir'] = join(env['android_dir'], 'out')
  1204. env['repo_path'] = join(env['android_base_dir'], 'repo')
  1205. env['repo_path_base64'] = env['repo_path'] + '.base64'
  1206. env['android_shell_setup'] = '''\
  1207. . build/envsetup.sh
  1208. lunch aosp_{}-eng
  1209. '''.format(self.env['android_arch'])
  1210. # Toolchain.
  1211. if not env['_args_given']['mode']:
  1212. if env['baremetal']:
  1213. env['mode'] = 'baremetal'
  1214. if env['userland']:
  1215. env['mode'] = 'userland'
  1216. if not env['_args_given']['gcc_which']:
  1217. if env['mode'] == 'baremetal':
  1218. env['gcc_which'] = 'crosstool-ng'
  1219. elif env['host']:
  1220. env['gcc_which'] = 'host'
  1221. if env['gcc_which'] == 'buildroot':
  1222. env['toolchain_prefix'] = os.path.join(
  1223. env['buildroot_host_bin_dir'],
  1224. env['buildroot_toolchain_prefix']
  1225. )
  1226. env['userland_library_dir'] = env['buildroot_target_dir']
  1227. env['userland_library_redirects'] = [
  1228. 'lib',
  1229. 'lib64',
  1230. os.path.join('usr', 'lib'),
  1231. os.path.join('usr', 'lib64')
  1232. ]
  1233. env['pkg_config'] = env['buildroot_pkg_config']
  1234. elif env['gcc_which'] == 'crosstool-ng':
  1235. env['toolchain_prefix'] = os.path.join(
  1236. env['crosstool_ng_bin_dir'],
  1237. env['crosstool_ng_toolchain_prefix']
  1238. )
  1239. elif env['gcc_which'] == 'host':
  1240. if env['arch'] == env['host_arch']:
  1241. env['toolchain_prefix'] = ''
  1242. else:
  1243. env['toolchain_prefix'] = env['ubuntu_toolchain_prefix']
  1244. if env['arch'] == env['host_arch']:
  1245. env['userland_library_dir'] = '/'
  1246. elif env['arch'] == 'x86_64':
  1247. env['userland_library_dir'] = '/usr/x86_64-linux-gnu/'
  1248. elif env['arch'] == 'arm':
  1249. env['userland_library_dir'] = '/usr/arm-linux-gnueabihf'
  1250. elif env['arch'] == 'aarch64':
  1251. env['userland_library_dir'] = '/usr/aarch64-linux-gnu/'
  1252. env['pkg_config'] = 'pkg-config'
  1253. env['userland_library_redirects'] = ['lib']
  1254. elif env['gcc_which'] == 'host-baremetal':
  1255. if env['arch'] == 'arm':
  1256. env['toolchain_prefix'] = 'arm-none-eabi'
  1257. else:
  1258. raise Exception('There is no host baremetal chain for arch: ' + env['arch'])
  1259. else:
  1260. raise Exception('Unknown toolchain: ' + env['gcc_which'])
  1261. if env['toolchain_prefix'] == '':
  1262. env['toolchain_prefix_dash'] = ''
  1263. else:
  1264. env['toolchain_prefix_dash'] = '{}-'.format(env['toolchain_prefix'])
  1265. env['gfortran_path'] = self.get_toolchain_tool('gfortran')
  1266. env['gcc_path'] = self.get_toolchain_tool('gcc')
  1267. env['gxx_path'] = self.get_toolchain_tool('g++')
  1268. env['ld_path'] = self.get_toolchain_tool('ld')
  1269. if env['gcc_which'] == 'host':
  1270. if env['arch'] == 'x86_64':
  1271. env['gdb_path'] = 'gdb'
  1272. else:
  1273. env['gdb_path'] = 'gdb-multiarch'
  1274. else:
  1275. env['gdb_path'] = self.get_toolchain_tool('gdb')
  1276. def add_argument(self, *args, **kwargs):
  1277. '''
  1278. Also handle:
  1279. - modified defaults from child classes.
  1280. - common arguments to forward on Python calls
  1281. '''
  1282. shortname, longname, key, is_option = self.get_key(*args, **kwargs)
  1283. if key in self._defaults:
  1284. kwargs['default'] = self._defaults[key]
  1285. if self._is_common:
  1286. self._common_args.add(key)
  1287. super().add_argument(*args, **kwargs)
  1288. def assert_is_subpath(self, subpath, parents):
  1289. is_subpath = False
  1290. for parent in parents:
  1291. if self.is_subpath(subpath, parent):
  1292. is_subpath = True
  1293. if not is_subpath:
  1294. raise Exception(
  1295. 'Can only accept targets inside:\n{}\nGiven: {}'.format(
  1296. '\n'.join(parents),
  1297. subpath
  1298. )
  1299. )
  1300. def get_elf_entry(self, elf_file_path):
  1301. readelf_header = self.sh.check_output([
  1302. self.get_toolchain_tool('readelf'),
  1303. '-h',
  1304. elf_file_path
  1305. ]).decode()
  1306. for line in readelf_header.decode().split('\n'):
  1307. split = line.split()
  1308. if line.startswith(' Entry point address:'):
  1309. addr = line.split()[-1]
  1310. break
  1311. return int(addr, 0)
  1312. @staticmethod
  1313. def get_gem5_target_path(env, name):
  1314. '''
  1315. Get the magic gem5 target path form the meaningful component name.
  1316. '''
  1317. return os.path.join(env['gem5_executable_dir'], name + env['gem5_executable_suffix'])
  1318. @staticmethod
  1319. def cwd_in_lib():
  1320. return pathlib.Path(common.consts['userland_source_libs_dir']) in pathlib.Path(os.getcwd()).parents
  1321. def gem5_list_checkpoint_dirs(self):
  1322. '''
  1323. List checkpoint directory, oldest first.
  1324. '''
  1325. prefix_re = re.compile(self.env['gem5_cpt_prefix'])
  1326. files = list(filter(
  1327. lambda x: os.path.isdir(os.path.join(self.env['m5out_dir'], x))
  1328. and prefix_re.search(x), os.listdir(self.env['m5out_dir'])
  1329. ))
  1330. files.sort(key=lambda x: os.path.getmtime(os.path.join(self.env['m5out_dir'], x)))
  1331. return files
  1332. def get_common_args(self):
  1333. '''
  1334. These are arguments that might be used by more than one script,
  1335. and are all defined in this class instead of in the derived class
  1336. of the script.
  1337. This can be used to forward common arguments to a call of another CLI function.
  1338. '''
  1339. return {
  1340. key:self.env[key] for key in self._common_args if
  1341. (
  1342. # Args given on command line.
  1343. self.env['_args_given'][key] or
  1344. # Ineritance changed defaults.
  1345. key in self._defaults
  1346. )
  1347. }
  1348. def get_stats(self, stat_re=None, stats_file=None):
  1349. if stat_re is None:
  1350. stat_re = '^system.cpu[0-9]*.numCycles$'
  1351. if stats_file is None:
  1352. stats_file = self.env['stats_file']
  1353. stat_re = re.compile(stat_re)
  1354. ret = []
  1355. with open(stats_file, 'r') as statfile:
  1356. for line in statfile:
  1357. if line[0] != '-':
  1358. cols = line.split()
  1359. if len(cols) > 1 and stat_re.search(cols[0]):
  1360. ret.append(cols[1])
  1361. return ret
  1362. def get_toolchain_tool(self, tool):
  1363. return '{}{}'.format(self.env['toolchain_prefix_dash'], tool)
  1364. def github_make_request(
  1365. self,
  1366. authenticate=False,
  1367. data=None,
  1368. extra_headers=None,
  1369. path='',
  1370. subdomain='api',
  1371. url_params=None,
  1372. **extra_request_args
  1373. ):
  1374. if extra_headers is None:
  1375. extra_headers = {}
  1376. headers = {'Accept': 'application/vnd.github.v3+json'}
  1377. headers.update(extra_headers)
  1378. if authenticate:
  1379. headers['Authorization'] = 'token ' + os.environ['LKMC_GITHUB_TOKEN']
  1380. if url_params is not None:
  1381. path += '?' + urllib.parse.urlencode(url_params)
  1382. request = urllib.request.Request(
  1383. 'https://' + subdomain + '.github.com/repos/' + self.env['github_repo_id'] + path,
  1384. headers=headers,
  1385. data=data,
  1386. **extra_request_args
  1387. )
  1388. response_body = urllib.request.urlopen(request).read().decode()
  1389. if response_body:
  1390. _json = json.loads(response_body)
  1391. else:
  1392. _json = {}
  1393. return _json
  1394. def is_arch_supported(self, arch, mode):
  1395. return not (
  1396. mode == 'baremetal' and
  1397. not arch in consts['crosstool_ng_supported_archs']
  1398. )
  1399. def log_error(self, msg):
  1400. with self.print_lock:
  1401. print('error: {}'.format(msg), file=sys.stdout)
  1402. def log_info(self, msg='', flush=False, **kwargs):
  1403. with self.print_lock:
  1404. if not self.env['quiet']:
  1405. print('{}'.format(msg), **kwargs)
  1406. if flush:
  1407. sys.stdout.flush()
  1408. def log_warn(self, msg):
  1409. with self.print_lock:
  1410. print('warning: {}'.format(msg), file=sys.stdout)
  1411. def is_subpath(self, subpath, parent):
  1412. '''
  1413. https://stackoverflow.com/questions/3812849/how-to-check-whether-a-directory-is-a-sub-directory-of-another-directory
  1414. '''
  1415. return os.path.abspath(subpath).startswith(os.path.abspath(parent))
  1416. def main(self, *args, **kwargs):
  1417. '''
  1418. Run timed_main across all selected archs and emulators.
  1419. :return: if any of the timed_mains exits non-zero and non-None,
  1420. return that. Otherwise, return 0.
  1421. '''
  1422. env = kwargs.copy()
  1423. if env['china']:
  1424. print(china_dictatorship.get_data())
  1425. sys.exit(0)
  1426. self.input_args = env.copy()
  1427. env.update(consts)
  1428. real_all_archs = env['all_archs']
  1429. if real_all_archs:
  1430. real_archs = consts['all_long_archs']
  1431. else:
  1432. real_archs = env['archs']
  1433. real_all_emulators = env['all_emulators']
  1434. if real_all_emulators:
  1435. real_emulators = consts['all_long_emulators']
  1436. else:
  1437. real_emulators = env['emulators']
  1438. return_value = 0
  1439. if env['_args_given']['show_cmds']:
  1440. show_cmds = env['show_cmds']
  1441. else:
  1442. show_cmds = not env['quiet']
  1443. self.setup(env)
  1444. try:
  1445. for emulator in real_emulators:
  1446. for arch in real_archs:
  1447. if arch in env['arch_short_to_long_dict']:
  1448. arch = env['arch_short_to_long_dict'][arch]
  1449. if emulator in env['emulator_short_to_long_dict']:
  1450. emulator = env['emulator_short_to_long_dict'][emulator]
  1451. if self.is_arch_supported(arch, env['mode']):
  1452. if not env['dry_run']:
  1453. start_time = time.time()
  1454. env['arch'] = arch
  1455. env['archs'] = [arch]
  1456. env['_args_given']['archs'] = True
  1457. env['all_archs'] = False
  1458. env['emulator'] = emulator
  1459. env['emulators'] = [emulator]
  1460. env['_args_given']['emulators'] = True
  1461. env['all_emulators'] = False
  1462. self.env = env.copy()
  1463. self.sh = shell_helpers.ShellHelpers(
  1464. dry_run=self.env['dry_run'],
  1465. force_oneline=self.env['print_cmd_oneline'],
  1466. quiet=(not show_cmds),
  1467. )
  1468. self._init_env(self.env)
  1469. if emulator == 'native':
  1470. if arch != self.env['host_arch']:
  1471. if real_all_archs:
  1472. continue
  1473. else:
  1474. raise Exception('native emulator only supported in if target arch ({}) == host arch ({})'.format(arch, self.env['host_arch']))
  1475. if self.env['userland'] and not self.env['mode'] == 'userland':
  1476. if real_all_emulators:
  1477. continue
  1478. else:
  1479. raise Exception('native emulator only supported in user mode')
  1480. self.setup_one()
  1481. ret = self.timed_main()
  1482. if not env['dry_run']:
  1483. end_time = time.time()
  1484. self.ellapsed_seconds = end_time - start_time
  1485. self.print_time(self.ellapsed_seconds)
  1486. if ret is not None and ret != 0:
  1487. return_value = ret
  1488. if self.env['quit_on_fail']:
  1489. raise ExitLoop()
  1490. elif not real_all_archs:
  1491. raise Exception('Unsupported arch for this action: ' + arch)
  1492. except ExitLoop:
  1493. pass
  1494. ret = self.teardown()
  1495. if ret is not None and ret != 0:
  1496. return_value = ret
  1497. return return_value
  1498. def make_build_dirs(self):
  1499. os.makedirs(self.env['buildroot_build_build_dir'], exist_ok=True)
  1500. os.makedirs(self.env['gem5_build_dir'], exist_ok=True)
  1501. os.makedirs(self.env['out_rootfs_overlay_dir'], exist_ok=True)
  1502. def make_run_dirs(self):
  1503. '''
  1504. Make directories required for the run.
  1505. The user could nuke those anytime between runs to try and clean things up.
  1506. '''
  1507. os.makedirs(self.env['gem5_run_dir'], exist_ok=True)
  1508. os.makedirs(self.env['p9_dir'], exist_ok=True)
  1509. os.makedirs(self.env['qemu_run_dir'], exist_ok=True)
  1510. @staticmethod
  1511. def python_escape_double_quotes(s):
  1512. s2 = []
  1513. for c in s:
  1514. if c == '"':
  1515. s2.append('\\"')
  1516. else:
  1517. s2.append(c)
  1518. return ''.join(s2)
  1519. @staticmethod
  1520. def python_struct_int_format(size):
  1521. if size == 4:
  1522. return 'i'
  1523. elif size == 8:
  1524. return 'Q'
  1525. else:
  1526. raise 'unknown size {}'.format(size)
  1527. @staticmethod
  1528. def seconds_to_hms(seconds):
  1529. '''
  1530. Seconds to hour:minute:seconds
  1531. :ptype seconds: float
  1532. :rtype: str
  1533. https://stackoverflow.com/questions/775049/how-do-i-convert-seconds-to-hours-minutes-and-seconds
  1534. '''
  1535. frac, whole = math.modf(seconds)
  1536. hours, rem = divmod(whole, 3600)
  1537. minutes, seconds = divmod(rem, 60)
  1538. return '{:02}:{:02}:{:02}'.format(int(hours), int(minutes), int(seconds))
  1539. def print_time(self, ellapsed_seconds):
  1540. if self.env['show_time'] and not self.env['quiet']:
  1541. print('time {}'.format(self.seconds_to_hms(ellapsed_seconds)))
  1542. def raw_to_qcow2(self, qemu_which=False, reverse=False):
  1543. if qemu_which == 'host' or not os.path.exists(self.env['qemu_img_executable']):
  1544. disable_trace = []
  1545. qemu_img_executable = self.env['qemu_img_basename']
  1546. else:
  1547. # Prevent qemu-img from generating trace files like QEMU. Disgusting.
  1548. disable_trace = ['-T', 'pr_manager_run,file=/dev/null', LF]
  1549. qemu_img_executable = self.env['qemu_img_executable']
  1550. infmt = 'raw'
  1551. outfmt = 'qcow2'
  1552. infile = self.env['rootfs_raw_file']
  1553. outfile = self.env['qcow2_file']
  1554. if reverse:
  1555. tmp = infmt
  1556. infmt = outfmt
  1557. outfmt = tmp
  1558. tmp = infile
  1559. infile = outfile
  1560. outfile = tmp
  1561. self.sh.run_cmd(
  1562. [
  1563. qemu_img_executable, LF,
  1564. ] +
  1565. disable_trace +
  1566. [
  1567. 'convert', LF,
  1568. '-f', infmt, LF,
  1569. '-O', outfmt, LF,
  1570. infile, LF,
  1571. outfile, LF,
  1572. ]
  1573. )
  1574. def resolve_executable(
  1575. self,
  1576. in_path,
  1577. magic_in_dirs,
  1578. magic_out_dir,
  1579. executable_ext
  1580. ):
  1581. '''
  1582. Resolve the path of an userland or baremetal executable.
  1583. If it is in tree, resolve source paths to their corresponding executables.
  1584. If it is out of tree, return the same exact path as input.
  1585. If the input path is a file, add the executable extension automatically.
  1586. Directories map to the directories that would contain executable in that directory.
  1587. '''
  1588. if not self.env['dry_run'] and not os.path.exists(in_path):
  1589. raise Exception('Input path does not exist: ' + in_path)
  1590. if len(magic_in_dirs) > 1:
  1591. relative_subpath = self.env['root_dir']
  1592. else:
  1593. relative_subpath = magic_in_dirs[0]
  1594. for magic_in_dir in magic_in_dirs:
  1595. if self.is_subpath(in_path, magic_in_dir):
  1596. # Abspath needed to remove the trailing `/.` which makes e.g. rmrf fail.
  1597. out = os.path.abspath(os.path.join(
  1598. magic_out_dir,
  1599. os.path.relpath(
  1600. os.path.splitext(in_path)[0],
  1601. relative_subpath
  1602. )
  1603. ))
  1604. if os.path.isfile(in_path):
  1605. out += executable_ext
  1606. return out
  1607. return in_path
  1608. def resolve_targets(self, source_dirs, targets):
  1609. '''
  1610. Resolve userland or baremetal CLI provided targets to final paths.
  1611. Notably converts the toplevel directory into all source directories needed.
  1612. '''
  1613. if not targets:
  1614. targets = source_dirs.copy()
  1615. new_targets = []
  1616. for target in targets:
  1617. for resolved_target in self.toplevel_to_source_dirs(target, source_dirs):
  1618. self.assert_is_subpath(resolved_target, source_dirs)
  1619. new_targets.append(resolved_target)
  1620. return new_targets
  1621. def resolve_baremetal_executable(self, path):
  1622. return self.resolve_executable(
  1623. path,
  1624. [
  1625. self.env['baremetal_source_dir'],
  1626. self.env['userland_source_dir']
  1627. ],
  1628. self.env['baremetal_build_dir'],
  1629. self.env['baremetal_executable_ext'],
  1630. )
  1631. def resolve_userland_executable(self, path):
  1632. return self.resolve_executable(
  1633. path,
  1634. [self.env['userland_source_dir']],
  1635. self.env['userland_build_dir'],
  1636. self.env['userland_executable_ext'],
  1637. )
  1638. def setup(self, env):
  1639. '''
  1640. Similar to setup run before all timed_main are called.
  1641. _init_env has not yet been called, so only primary CLI arguments may be used.
  1642. '''
  1643. pass
  1644. def setup_one(self):
  1645. '''
  1646. Run just before timed_main, after _init_env.
  1647. '''
  1648. pass
  1649. def toplevel_to_source_dirs(self, path, source_dirs):
  1650. path = os.path.abspath(path)
  1651. if path == self.env['root_dir']:
  1652. return source_dirs
  1653. else:
  1654. return [path]
  1655. def timed_main(self):
  1656. '''
  1657. Main action of the derived class.
  1658. Gets run once for every --arch and every --emulator.
  1659. '''
  1660. pass
  1661. def teardown(self) -> Union[None,int]:
  1662. '''
  1663. Similar to setup, but run once after all timed_main are called.
  1664. :return: if not None, the return integer gets used as the exit status of the program.
  1665. '''
  1666. pass
  1667. class BuildCliFunction(LkmcCliFunction):
  1668. '''
  1669. A CLI function with common facilities to build stuff, e.g.:
  1670. * `--clean` to clean the build directory
  1671. * `--nproc` to set he number of build threads
  1672. '''
  1673. def __init__(self, *args, **kwargs):
  1674. super().__init__(*args, **kwargs)
  1675. self.add_argument(
  1676. '--clean',
  1677. default=False,
  1678. help='Clean the build instead of building.',
  1679. ),
  1680. self._build_arguments = {
  1681. '--ccflags': {
  1682. 'default': '',
  1683. 'help': '''\
  1684. Pass the given compiler flags to all languages (C, C++, Fortran, etc.)
  1685. ''',
  1686. },
  1687. '--ldflags': {
  1688. 'default': '',
  1689. 'help': '''\
  1690. Extra linker flags.
  1691. ''',
  1692. },
  1693. '--configure': {
  1694. 'default': True,
  1695. 'help': '''\
  1696. Also run the configuration step during build.
  1697. ''',
  1698. },
  1699. '--force-rebuild': {
  1700. 'default': False,
  1701. "help": '''\
  1702. Force rebuild even if sources didn't change.
  1703. ''',
  1704. },
  1705. '--optimization-level': {
  1706. 'default': '0',
  1707. 'help': '''\
  1708. https://cirosantilli.com/linux-kernel-module-cheat#optimization-level-of-a-build
  1709. ''',
  1710. },
  1711. 'extra_make_args': {
  1712. 'default': [],
  1713. 'help': '''\
  1714. Extra arguments to pass to the Make command or analogous final build command,
  1715. after configure, e.g. SCons. Usually contains specific targets or other build flags.
  1716. ''',
  1717. 'metavar': 'extra-make-args',
  1718. 'nargs': '*',
  1719. },
  1720. }
  1721. def _add_argument(self, argument_name):
  1722. '''
  1723. Enable build argument with a fixed name to provide an uniform CLI API
  1724. across different builds.
  1725. '''
  1726. self.add_argument(
  1727. argument_name,
  1728. **self._build_arguments[argument_name]
  1729. )
  1730. def _build_one(
  1731. self,
  1732. in_path,
  1733. out_path,
  1734. build_exts=None,
  1735. cc_flags=None,
  1736. cc_flags_after=None,
  1737. extra_objs=None,
  1738. extra_objs_userland_asm=None,
  1739. extra_objs_lkmc_common=None,
  1740. extra_objs_baremetal_bootloader=None,
  1741. extra_deps=None,
  1742. link=True,
  1743. ):
  1744. '''
  1745. Build one userland or baremetal executable.
  1746. '''
  1747. if cc_flags is None:
  1748. cc_flags = []
  1749. else:
  1750. cc_flags = cc_flags.copy()
  1751. if cc_flags_after is None:
  1752. cc_flags_after = []
  1753. else:
  1754. cc_flags_after = cc_flags_after.copy()
  1755. if extra_deps is None:
  1756. extra_deps = []
  1757. ret = 0
  1758. in_dir, in_basename = os.path.split(in_path)
  1759. in_dir_abs = os.path.abspath(in_dir)
  1760. dirpath_relative_root = in_dir_abs[len(self.env['root_dir']) + 1:]
  1761. dirpath_relative_root_components = dirpath_relative_root.split(os.sep)
  1762. dirpath_relative_root_components_len = len(dirpath_relative_root_components)
  1763. my_path_properties = path_properties.get(os.path.join(
  1764. dirpath_relative_root,
  1765. in_basename
  1766. ))
  1767. if my_path_properties.should_be_built(
  1768. self.env,
  1769. link,
  1770. ):
  1771. if extra_objs is None:
  1772. extra_objs= []
  1773. if link:
  1774. # Baremetal builds cannot add their usual syscall objects, as those
  1775. # rely on standard library symbols.
  1776. if my_path_properties['freestanding']:
  1777. extra_objs = []
  1778. if (self.env['mode'] == 'baremetal' and not my_path_properties['freestanding']) \
  1779. or my_path_properties['extra_objs_lkmc_common']:
  1780. extra_objs.extend(extra_objs_lkmc_common)
  1781. if (
  1782. self.env['mode'] == 'baremetal' and
  1783. not my_path_properties['freestanding'] and
  1784. not my_path_properties['extra_objs_disable_baremetal_bootloader']
  1785. ):
  1786. extra_objs.extend(extra_objs_baremetal_bootloader)
  1787. if self.env['mode'] == 'userland':
  1788. cc_flags_after.extend(['-pthread', LF])
  1789. if self.need_rebuild([in_path] + extra_objs + extra_deps, out_path):
  1790. cc_flags.extend(my_path_properties['cc_flags'])
  1791. if self.env['verbose']:
  1792. cc_flags.extend([
  1793. '-v', LF,
  1794. ])
  1795. cc_flags_after.extend(my_path_properties['cc_flags_after'])
  1796. if my_path_properties['cc_pedantic']:
  1797. cc_flags.extend(['-pedantic', LF])
  1798. if not link:
  1799. cc_flags.extend(['-c', LF])
  1800. in_ext = os.path.splitext(in_path)[1]
  1801. if in_ext in (self.env['c_ext'], self.env['asm_ext']):
  1802. cc = self.env['gcc_path']
  1803. std = my_path_properties['c_std']
  1804. elif in_ext == self.env['cxx_ext']:
  1805. cc = self.env['gxx_path']
  1806. std = my_path_properties['cxx_std']
  1807. if self.env['is_arm']:
  1808. if in_ext == self.env['asm_ext']:
  1809. cc_flags.extend([
  1810. '-Xassembler', '-march=all', LF,
  1811. ])
  1812. else:
  1813. cc_flags.extend([
  1814. '-march={}'.format(self.env['march']), LF,
  1815. ])
  1816. if dirpath_relative_root_components_len > 0:
  1817. if dirpath_relative_root_components[0] == consts['userland_subdir']:
  1818. if dirpath_relative_root_components_len > 1:
  1819. if dirpath_relative_root_components[1] == self.env['userland_libs_basename']:
  1820. if dirpath_relative_root_components_len > 1:
  1821. if self.env['gcc_which'] == 'host':
  1822. eigen_root = '/'
  1823. else:
  1824. eigen_root = self.env['buildroot_staging_dir']
  1825. # TODO move to path_properties.py somehow.
  1826. packages = {
  1827. 'boost': {
  1828. # Header only, no pkg-config package.
  1829. 'cc_flags': [],
  1830. 'cc_flags_after': [],
  1831. },
  1832. 'eigen': {
  1833. # TODO: was failing with:
  1834. # fatal error: Eigen/Dense: No such file or directory as of
  1835. # 975ce0723ee3fa1fea1766e6683e2f3acb8558d6
  1836. # http://lists.busybox.net/pipermail/buildroot/2018-June/222914.html
  1837. 'cc_flags': [
  1838. '-I',
  1839. os.path.join(
  1840. eigen_root,
  1841. 'usr',
  1842. 'include',
  1843. 'eigen3'
  1844. ),
  1845. LF
  1846. ],
  1847. # Header only.
  1848. 'cc_flags_after': [],
  1849. },
  1850. 'hdf5': {
  1851. 'pkg_config_id': 'hdf5-serial',
  1852. },
  1853. 'googletest': {
  1854. 'cc_flags': [
  1855. '-I', os.path.join(self.env['googletest_source_dir'], 'googletest', 'include'), LF,
  1856. '-I', os.path.join(self.env['googletest_source_dir'], 'googlemock', 'include'), LF,
  1857. ],
  1858. 'cc_flags_after': [
  1859. os.path.join(self.env['googletest_source_dir'], 'build', 'lib', 'libgtest.a'), LF,
  1860. os.path.join(self.env['googletest_source_dir'], 'build', 'lib', 'libgtest_main.a'), LF,
  1861. os.path.join(self.env['googletest_source_dir'], 'build', 'lib', 'libgmock.a'), LF,
  1862. ],
  1863. },
  1864. }
  1865. package_key = dirpath_relative_root_components[2]
  1866. if package_key in packages:
  1867. package = packages[package_key]
  1868. else:
  1869. package = {}
  1870. if 'pkg_config_id' in package:
  1871. pkg_config_id = package['pkg_config_id']
  1872. else:
  1873. pkg_config_id = package_key
  1874. if 'cc_flags' in package:
  1875. cc_flags.extend(package['cc_flags'])
  1876. else:
  1877. pkg_config_output = self.sh.check_output([
  1878. self.env['pkg_config'],
  1879. '--cflags',
  1880. pkg_config_id
  1881. ]).decode()
  1882. cc_flags.extend(self.sh.shlex_split(pkg_config_output))
  1883. if 'cc_flags_after' in package:
  1884. cc_flags_after.extend(package['cc_flags_after'])
  1885. else:
  1886. pkg_config_output = subprocess.check_output([
  1887. self.env['pkg_config'],
  1888. '--libs',
  1889. pkg_config_id
  1890. ]).decode()
  1891. cc_flags_after.extend(self.sh.shlex_split(pkg_config_output))
  1892. os.makedirs(os.path.dirname(out_path), exist_ok=True)
  1893. ret = self.sh.run_cmd(
  1894. (
  1895. [
  1896. cc, LF,
  1897. ] +
  1898. cc_flags +
  1899. [
  1900. '-std={}'.format(std), LF,
  1901. '-o', out_path, LF,
  1902. in_path, LF,
  1903. ] +
  1904. self.sh.add_newlines(extra_objs) +
  1905. cc_flags_after
  1906. ),
  1907. extra_paths=[self.env['ccache_dir']],
  1908. )
  1909. return ret
  1910. def clean_pre(self, build_dir):
  1911. pass
  1912. def clean(self):
  1913. build_dir = self.get_build_dir()
  1914. self.clean_pre(build_dir)
  1915. if build_dir is not None:
  1916. self.sh.rmrf(build_dir)
  1917. self.clean_post(build_dir)
  1918. def clean_post(self, build_dir):
  1919. pass
  1920. def build(self):
  1921. '''
  1922. Do the actual main build work.
  1923. '''
  1924. raise NotImplementedError()
  1925. def get_build_dir(self):
  1926. return None
  1927. def need_rebuild(self, srcs, dst):
  1928. if self.env['force_rebuild']:
  1929. return True
  1930. if not os.path.exists(dst):
  1931. return True
  1932. for src in srcs:
  1933. if os.path.getmtime(src) > os.path.getmtime(dst):
  1934. return True
  1935. return False
  1936. def setup_one(self):
  1937. ccflags = []
  1938. ccflags.extend(self.env['ccflags_default'])
  1939. if 'optimization_level' in self.env:
  1940. ccflags.extend(['-O{}'.format(self.env['optimization_level']), LF])
  1941. if self.env['static']:
  1942. ccflags.extend(['-static', LF])
  1943. if 'ccflags' in self.env:
  1944. ccflags.extend(self.sh.shlex_split(self.env['ccflags']))
  1945. self.env['ccflags'] = ccflags
  1946. self.setup_one_build()
  1947. def setup_one_build(self):
  1948. '''
  1949. Called once before every build type, after BuildCliFunction::setup_one
  1950. '''
  1951. pass
  1952. def timed_main(self):
  1953. '''
  1954. Parse CLI, and to the build based on it.
  1955. The actual build work is done by do_build in implementing classes.
  1956. '''
  1957. if self.env['clean']:
  1958. return self.clean()
  1959. else:
  1960. return self.build()
  1961. TestStatus = enum.Enum('TestStatus', ['PASS', 'FAIL'])
  1962. @functools.total_ordering
  1963. class TestResult:
  1964. def __init__(
  1965. self,
  1966. test_id: str ='',
  1967. status : TestStatus =TestStatus.PASS,
  1968. ellapsed_seconds : float =0,
  1969. reason : str =''
  1970. ):
  1971. self.test_id = test_id
  1972. self.status = status
  1973. self.ellapsed_seconds = ellapsed_seconds
  1974. self.reason = reason
  1975. def __eq__(self, other):
  1976. return self.test_id == other.test_id
  1977. def __lt__(self, other):
  1978. return self.test_id < other.test_id
  1979. def __str__(self):
  1980. out = [
  1981. self.status.name,
  1982. LkmcCliFunction.seconds_to_hms(self.ellapsed_seconds),
  1983. repr(self.test_id),
  1984. ]
  1985. if self.status is TestStatus.FAIL:
  1986. out.append(repr(self.reason))
  1987. return ' '.join(out)
  1988. class TestCliFunction(LkmcCliFunction):
  1989. '''
  1990. Represents a CLI command that runs tests.
  1991. Automates test reporting boilerplate for those commands.
  1992. '''
  1993. base_run_args = {
  1994. 'background': True,
  1995. 'ctrl_c_host': True,
  1996. 'print_cmd_oneline': True,
  1997. 'show_cmds': False,
  1998. 'show_stdout': False,
  1999. 'show_time': False,
  2000. }
  2001. def __init__(self, *args, **kwargs):
  2002. defaults = {
  2003. 'quit_on_fail': False,
  2004. 'show_time': False,
  2005. }
  2006. if 'defaults' in kwargs:
  2007. defaults.update(kwargs['defaults'])
  2008. kwargs['defaults'] = defaults
  2009. super().__init__(*args, **kwargs)
  2010. self.test_results = queue.Queue()
  2011. def handle_output_function(
  2012. self,
  2013. work_function_input,
  2014. work_function_return,
  2015. work_function_exception
  2016. ):
  2017. if work_function_exception is not None:
  2018. return work_function_exception
  2019. if work_function_return.status != TestStatus.PASS:
  2020. return thread_pool.ThreadPoolExitException()
  2021. def run_test(
  2022. self,
  2023. run_obj,
  2024. run_args=None,
  2025. test_id=None,
  2026. expected_exit_status=None,
  2027. thread_id=0,
  2028. ):
  2029. '''
  2030. This is a setup / run / teardown setup for simple tests that just do a single run.
  2031. More complex tests might need to run the steps separately, e.g. gdb tests
  2032. must run multiple commands: one for the run and one GDB.
  2033. This function is meant to be called from threads. In particular,
  2034. those threads have to cross over archs: the original motivation is to parallelize
  2035. super slow gem5 boot tests. Therefore, we cannot use self.env['arch'] and selv.env['emulator']
  2036. in this function or callees!
  2037. Ideally, we should make this static and pass all arguments to the call... but lazy to refactor.
  2038. I have the feeling I will regret this one day down the line.
  2039. :param run_obj: callable object
  2040. :param run_args: arguments to be passed to the runnable object
  2041. :param test_id: test identifier, to be added in addition to of arch and emulator ids
  2042. :param thread_id: which thread the test is running under
  2043. '''
  2044. if run_obj.is_arch_supported(run_args['archs'][0], run_args.get('mode', None)):
  2045. cur_run_args = {
  2046. 'run_id': thread_id,
  2047. }
  2048. cur_run_args.update(self.base_run_args)
  2049. if run_args is not None:
  2050. cur_run_args.update(run_args)
  2051. test_id_string = self.test_setup(run_args, test_id)
  2052. exit_status = run_obj(**cur_run_args)
  2053. return self.test_teardown(
  2054. run_obj,
  2055. exit_status,
  2056. test_id_string,
  2057. expected_exit_status=expected_exit_status
  2058. )
  2059. def test_setup(self, run_args, test_id):
  2060. test_id_string = '{} {}'.format(run_args['emulators'][0], run_args['archs'][0])
  2061. if test_id is not None and str(test_id) != '':
  2062. test_id_string += ' {}'.format(test_id)
  2063. self.log_info('Starting: {}'.format(repr(test_id_string)), flush=True)
  2064. return test_id_string
  2065. def test_teardown(
  2066. self,
  2067. run_obj,
  2068. exit_status,
  2069. test_id_string,
  2070. expected_exit_status=None
  2071. ):
  2072. if expected_exit_status is None:
  2073. expected_exit_status = 0
  2074. reason = ''
  2075. if not self.env['dry_run']:
  2076. if exit_status == expected_exit_status:
  2077. test_status = TestStatus.PASS
  2078. else:
  2079. test_status = TestStatus.FAIL
  2080. reason = 'wrong exit status, got {} expected {}'.format(
  2081. exit_status,
  2082. expected_exit_status
  2083. )
  2084. ellapsed_seconds = run_obj.ellapsed_seconds
  2085. else:
  2086. test_status = TestStatus.PASS
  2087. ellapsed_seconds = 0
  2088. test_result = TestResult(
  2089. test_id_string,
  2090. test_status,
  2091. ellapsed_seconds,
  2092. reason
  2093. )
  2094. self.log_info('Result: ' + str(test_result))
  2095. self.test_results.put(test_result)
  2096. return test_result
  2097. def teardown(self):
  2098. '''
  2099. :return: 1 if any test failed, 0 otherwise
  2100. '''
  2101. self.log_info('\nTest result summary:')
  2102. passes = []
  2103. fails = []
  2104. while not self.test_results.empty():
  2105. test = self.test_results.get()
  2106. if test.status in (TestStatus.PASS, None):
  2107. bisect.insort(passes, test)
  2108. else:
  2109. bisect.insort(fails, test)
  2110. for test in itertools.chain(passes, fails):
  2111. self.log_info(test)
  2112. if fails:
  2113. self.log_error('A test failed')
  2114. return 1
  2115. return 0
  2116. # IO format.
  2117. class LkmcList(list):
  2118. '''
  2119. list with a lightweight serialization format for algorithm IO.
  2120. '''
  2121. def __init__(self, *args, **kwargs):
  2122. if 'oneline' in kwargs:
  2123. self.oneline = kwargs['oneline']
  2124. del kwargs['oneline']
  2125. else:
  2126. self.oneline = False
  2127. super().__init__(*args, **kwargs)
  2128. def __str__(self):
  2129. if self.oneline:
  2130. sep = ' '
  2131. else:
  2132. sep = '\n'
  2133. return sep.join([str(item) for item in self])
  2134. class LkmcOrderedDict(collections.OrderedDict):
  2135. '''
  2136. dict with a lightweight serialization format for algorithm IO.
  2137. '''
  2138. def __str__(self):
  2139. out = []
  2140. for key in self:
  2141. out.extend([
  2142. str(key),
  2143. str(self[key]) + '\n',
  2144. ])
  2145. return '\n'.join(out)