common.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  1. #!/usr/bin/env python3
  2. import argparse
  3. import base64
  4. import collections
  5. import copy
  6. import datetime
  7. import enum
  8. import glob
  9. import imp
  10. import inspect
  11. import json
  12. import math
  13. import multiprocessing
  14. import os
  15. import platform
  16. import re
  17. import shutil
  18. import signal
  19. import subprocess
  20. import sys
  21. import time
  22. import urllib
  23. import urllib.request
  24. import cli_function
  25. import shell_helpers
  26. from shell_helpers import LF
  27. common = sys.modules[__name__]
  28. # Fixed parameters that don't depend on CLI arguments.
  29. consts = {}
  30. consts['repo_short_id'] = 'lkmc'
  31. # https://stackoverflow.com/questions/20010199/how-to-determine-if-a-process-runs-inside-lxc-docker
  32. consts['in_docker'] = os.path.exists('/.dockerenv')
  33. consts['root_dir'] = os.path.dirname(os.path.abspath(__file__))
  34. consts['data_dir'] = os.path.join(consts['root_dir'], 'data')
  35. consts['p9_dir'] = os.path.join(consts['data_dir'], '9p')
  36. consts['gem5_non_default_source_root_dir'] = os.path.join(consts['data_dir'], 'gem5')
  37. if consts['in_docker']:
  38. consts['out_dir'] = os.path.join(consts['root_dir'], 'out.docker')
  39. else:
  40. consts['out_dir'] = os.path.join(consts['root_dir'], 'out')
  41. consts['readme'] = os.path.join(consts['root_dir'], 'README.adoc')
  42. consts['readme_out'] = os.path.join(consts['out_dir'], 'README.html')
  43. consts['build_doc_log'] = os.path.join(consts['out_dir'], 'build-doc.log')
  44. consts['gem5_out_dir'] = os.path.join(consts['out_dir'], 'gem5')
  45. consts['kernel_modules_build_base_dir'] = os.path.join(consts['out_dir'], 'kernel_modules')
  46. consts['buildroot_out_dir'] = os.path.join(consts['out_dir'], 'buildroot')
  47. consts['gem5_m5_build_dir'] = os.path.join(consts['out_dir'], 'util', 'm5')
  48. consts['run_dir_base'] = os.path.join(consts['out_dir'], 'run')
  49. consts['crosstool_ng_out_dir'] = os.path.join(consts['out_dir'], 'crosstool-ng')
  50. consts['test_boot_benchmark_file'] = os.path.join(consts['out_dir'], 'test-boot.txt')
  51. consts['packages_dir'] = os.path.join(consts['root_dir'], 'buildroot_packages')
  52. consts['kernel_modules_subdir'] = 'kernel_modules'
  53. consts['kernel_modules_source_dir'] = os.path.join(consts['root_dir'], consts['kernel_modules_subdir'])
  54. consts['userland_subdir'] = 'userland'
  55. consts['userland_source_dir'] = os.path.join(consts['root_dir'], consts['userland_subdir'])
  56. consts['userland_build_ext'] = '.out'
  57. consts['include_subdir'] = 'include'
  58. consts['include_source_dir'] = os.path.join(consts['root_dir'], consts['include_subdir'])
  59. consts['submodules_dir'] = os.path.join(consts['root_dir'], 'submodules')
  60. consts['buildroot_source_dir'] = os.path.join(consts['submodules_dir'], 'buildroot')
  61. consts['crosstool_ng_source_dir'] = os.path.join(consts['submodules_dir'], 'crosstool-ng')
  62. consts['crosstool_ng_supported_archs'] = set(['arm', 'aarch64'])
  63. consts['linux_source_dir'] = os.path.join(consts['submodules_dir'], 'linux')
  64. consts['linux_config_dir'] = os.path.join(consts['root_dir'], 'linux_config')
  65. consts['gem5_default_source_dir'] = os.path.join(consts['submodules_dir'], 'gem5')
  66. consts['rootfs_overlay_dir'] = os.path.join(consts['root_dir'], 'rootfs_overlay')
  67. consts['extract_vmlinux'] = os.path.join(consts['linux_source_dir'], 'scripts', 'extract-vmlinux')
  68. consts['qemu_source_dir'] = os.path.join(consts['submodules_dir'], 'qemu')
  69. consts['parsec_benchmark_source_dir'] = os.path.join(consts['submodules_dir'], 'parsec-benchmark')
  70. consts['ccache_dir'] = os.path.join('/usr', 'lib', 'ccache')
  71. consts['default_build_id'] = 'default'
  72. consts['arch_short_to_long_dict'] = collections.OrderedDict([
  73. ('x', 'x86_64'),
  74. ('a', 'arm'),
  75. ('A', 'aarch64'),
  76. ])
  77. # All long arch names.
  78. consts['all_long_archs'] = [consts['arch_short_to_long_dict'][k] for k in consts['arch_short_to_long_dict']]
  79. # All long and short arch names.
  80. consts['arch_choices'] = set()
  81. for key in consts['arch_short_to_long_dict']:
  82. consts['arch_choices'].add(key)
  83. consts['arch_choices'].add(consts['arch_short_to_long_dict'][key])
  84. consts['default_arch'] = 'x86_64'
  85. consts['gem5_cpt_prefix'] = '^cpt\.'
  86. def git_sha(repo_path):
  87. return subprocess.check_output(['git', '-C', repo_path, 'log', '-1', '--format=%H']).decode().rstrip()
  88. consts['sha'] = common.git_sha(consts['root_dir'])
  89. consts['release_dir'] = os.path.join(consts['out_dir'], 'release')
  90. consts['release_zip_file'] = os.path.join(consts['release_dir'], 'lkmc-{}.zip'.format(consts['sha']))
  91. consts['github_repo_id'] = 'cirosantilli/linux-kernel-module-cheat'
  92. consts['asm_ext'] = '.S'
  93. consts['c_ext'] = '.c'
  94. consts['header_ext'] = '.h'
  95. consts['kernel_module_ext'] = '.ko'
  96. consts['obj_ext'] = '.o'
  97. consts['config_file'] = os.path.join(consts['data_dir'], 'config.py')
  98. consts['magic_fail_string'] = b'lkmc_test_fail'
  99. consts['baremetal_lib_basename'] = 'lib'
  100. consts['emulator_short_to_long_dict'] = collections.OrderedDict([
  101. ('q', 'qemu'),
  102. ('g', 'gem5'),
  103. ])
  104. consts['all_long_emulators'] = [consts['emulator_short_to_long_dict'][k] for k in consts['emulator_short_to_long_dict']]
  105. consts['emulator_choices'] = set()
  106. for key in consts['emulator_short_to_long_dict']:
  107. consts['emulator_choices'].add(key)
  108. consts['emulator_choices'].add(consts['emulator_short_to_long_dict'][key])
  109. consts['host_arch'] = platform.processor()
  110. class LkmcCliFunction(cli_function.CliFunction):
  111. '''
  112. Common functionality shared across our CLI functions:
  113. * command timing
  114. * some common flags, e.g.: --arch, --dry-run, --quiet, --verbose
  115. '''
  116. def __init__(self, *args, defaults=None, supported_archs=None, **kwargs):
  117. '''
  118. :ptype defaults: Dict[str,Any]
  119. :param defaults: override the default value of an argument
  120. '''
  121. kwargs['config_file'] = consts['config_file']
  122. kwargs['extra_config_params'] = os.path.basename(inspect.getfile(self.__class__))
  123. if defaults is None:
  124. defaults = {}
  125. self._defaults = defaults
  126. self._is_common = True
  127. self._common_args = set()
  128. super().__init__(*args, **kwargs)
  129. self.supported_archs = supported_archs
  130. # Args for all scripts.
  131. arches = consts['arch_short_to_long_dict']
  132. arches_string = []
  133. for arch_short in arches:
  134. arch_long = arches[arch_short]
  135. arches_string.append('{} ({})'.format(arch_long, arch_short))
  136. arches_string = ', '.join(arches_string)
  137. self.add_argument(
  138. '-A', '--all-archs', default=False,
  139. help='''\
  140. Run action for all supported --archs archs. Ignore --archs.
  141. '''.format(arches_string)
  142. )
  143. self.add_argument(
  144. '-a',
  145. '--arch',
  146. action='append',
  147. choices=consts['arch_choices'],
  148. default=[consts['default_arch']],
  149. dest='archs',
  150. help='''\
  151. CPU architecture to use. If given multiple times, run the action
  152. for each arch sequentially in that order. If one of them fails, stop running.
  153. Valid archs: {}
  154. '''.format(arches_string)
  155. )
  156. self.add_argument(
  157. '--dry-run',
  158. default=False,
  159. help='''\
  160. Print the commands that would be run, but don't run them.
  161. We aim display every command that modifies the filesystem state, and generate
  162. Bash equivalents even for actions taken directly in Python without shelling out.
  163. mkdir are generally omitted since those are obvious
  164. '''
  165. )
  166. self.add_argument(
  167. '--print-time', default=True,
  168. help='''\
  169. Print how long it took to run the command at the end.
  170. Implied by --quiet.
  171. '''
  172. )
  173. self.add_argument(
  174. '-q', '--quiet', default=False,
  175. help='''\
  176. Don't print anything to stdout, except if it is part of an interactive terminal.
  177. TODO: implement fully, some stuff is escaping it currently.
  178. '''
  179. )
  180. self.add_argument(
  181. '--quit-on-fail',
  182. default=True,
  183. help='''\
  184. Stop running at the first failed test.
  185. '''
  186. )
  187. self.add_argument(
  188. '-v', '--verbose', default=False,
  189. help='Show full compilation commands when they are not shown by default.'
  190. )
  191. # Gem5 args.
  192. self.add_argument(
  193. '--dp650', default=False,
  194. help='Use the ARM DP650 display processor instead of the default HDLCD on gem5.'
  195. )
  196. self.add_argument(
  197. '--gem5-build-dir',
  198. help='''\
  199. Use the given directory as the gem5 build directory.
  200. Ignore --gem5-build-id and --gem5-build-type.
  201. '''
  202. )
  203. self.add_argument(
  204. '-M', '--gem5-build-id',
  205. help='''\
  206. gem5 build ID. Allows you to keep multiple separate gem5 builds.
  207. Default: {}
  208. '''.format(consts['default_build_id'])
  209. )
  210. self.add_argument(
  211. '--gem5-build-type', default='opt',
  212. help='gem5 build type, most often used for "debug" builds.'
  213. )
  214. self.add_argument(
  215. '--gem5-source-dir',
  216. help='''\
  217. Use the given directory as the gem5 source tree. Ignore `--gem5-worktree`.
  218. '''
  219. )
  220. self.add_argument(
  221. '-N', '--gem5-worktree',
  222. help='''\
  223. Create and use a git worktree of the gem5 submodule.
  224. See: https://github.com/cirosantilli/linux-kernel-module-cheat#gem5-worktree
  225. '''
  226. )
  227. # Linux kernel.
  228. self.add_argument(
  229. '--linux-build-dir',
  230. help='''\
  231. Use the given directory as the Linux build directory. Ignore --linux-build-id.
  232. '''
  233. )
  234. self.add_argument(
  235. '-L', '--linux-build-id', default=consts['default_build_id'],
  236. help='''\
  237. Linux build ID. Allows you to keep multiple separate Linux builds.
  238. '''
  239. )
  240. self.add_argument(
  241. '--linux-source-dir',
  242. help='''\
  243. Use the given directory as the Linux source tree.
  244. '''
  245. )
  246. self.add_argument(
  247. '--initramfs',
  248. default=False,
  249. help='''\
  250. See: https://github.com/cirosantilli/linux-kernel-module-cheat#initramfs
  251. '''
  252. )
  253. self.add_argument(
  254. '--initrd',
  255. default=False,
  256. help='''\
  257. For Buildroot: create a CPIO root filessytem.
  258. For QEMU use that CPUI root filesystem initrd instead of the default ext2.
  259. See: https://github.com/cirosantilli/linux-kernel-module-cheat#initrd
  260. '''
  261. )
  262. # Baremetal.
  263. self.add_argument(
  264. '-b', '--baremetal',
  265. help='''\
  266. Use the given baremetal executable instead of the Linux kernel.
  267. If the path is absolute, it is used as is.
  268. If the path is relative, we assume that it points to a source code
  269. inside baremetal/ and then try to use corresponding executable.
  270. '''
  271. )
  272. # Buildroot.
  273. self.add_argument(
  274. '--buildroot-build-id',
  275. default=consts['default_build_id'],
  276. help='Buildroot build ID. Allows you to keep multiple separate gem5 builds.'
  277. )
  278. self.add_argument(
  279. '--buildroot-linux', default=False,
  280. help='Boot with the Buildroot Linux kernel instead of our custom built one. Mostly for sanity checks.'
  281. )
  282. # crosstool-ng
  283. self.add_argument(
  284. '--crosstool-ng-build-id', default=consts['default_build_id'],
  285. help='Crosstool-NG build ID. Allows you to keep multiple separate crosstool-NG builds.'
  286. )
  287. self.add_argument(
  288. '--docker', default=False,
  289. help='''\
  290. Use the docker download Ubuntu root filesystem instead of the default Buildroot one.
  291. '''
  292. )
  293. self.add_argument(
  294. '--machine',
  295. help='''Machine type.
  296. QEMU default: virt
  297. gem5 default: VExpress_GEM5_V1
  298. See the documentation for other values known to work.
  299. '''
  300. )
  301. # QEMU.
  302. self.add_argument(
  303. '-Q', '--qemu-build-id', default=consts['default_build_id'],
  304. help='QEMU build ID. Allows you to keep multiple separate QEMU builds.'
  305. )
  306. # Userland.
  307. self.add_argument(
  308. '-u', '--userland',
  309. help='''\
  310. Run the given userland executable in user mode instead of booting the Linux kernel
  311. in full system mode. In gem5, user mode is called Syscall Emulation (SE) mode and
  312. uses se.py.
  313. Path resolution is similar to --baremetal.
  314. '''
  315. )
  316. self.add_argument(
  317. '--userland-args',
  318. help='''\
  319. CLI arguments to pass to the userland executable.
  320. '''
  321. )
  322. self.add_argument(
  323. '--userland-build-id'
  324. )
  325. # Run.
  326. self.add_argument(
  327. '-n', '--run-id', default='0',
  328. help='''\
  329. ID for run outputs such as gem5's m5out. Allows you to do multiple runs,
  330. and then inspect separate outputs later in different output directories.
  331. '''
  332. )
  333. self.add_argument(
  334. '-P', '--prebuilt', default=False,
  335. help='''\
  336. Use prebuilt packaged host utilities as much as possible instead
  337. of the ones we built ourselves. Saves build time, but decreases
  338. the likelihood of incompatibilities.
  339. '''
  340. )
  341. self.add_argument(
  342. '--port-offset', type=int,
  343. help='''\
  344. Increase the ports to be used such as for GDB by an offset to run multiple
  345. instances in parallel. Default: the run ID (-n) if that is an integer, otherwise 0.
  346. '''
  347. )
  348. # Misc.
  349. emulators = consts['emulator_short_to_long_dict']
  350. emulators_string = []
  351. for emulator_short in emulators:
  352. emulator_long = emulators[emulator_short]
  353. emulators_string.append('{} ({})'.format(emulator_long, emulator_short))
  354. emulators_string = ', '.join(emulators_string)
  355. self.add_argument(
  356. '--all-emulators', default=False,
  357. help='''\
  358. Run action for all supported --emulators emulators. Ignore --emulators.
  359. '''.format(emulators_string)
  360. )
  361. self.add_argument(
  362. '-e',
  363. '--emulator',
  364. action='append',
  365. choices=consts['emulator_choices'],
  366. default=['qemu'],
  367. dest='emulators',
  368. help='''\
  369. Emulator to use. If given multiple times, semantics are similar to --arch.
  370. Valid emulators: {}
  371. '''.format(emulators_string)
  372. )
  373. self._is_common = False
  374. def __call__(self, *args, **kwargs):
  375. '''
  376. For Python code calls, in addition to base:
  377. - print the CLI equivalent of the call
  378. - automatically forward common arguments
  379. '''
  380. print_cmd = ['./' + self.extra_config_params, LF]
  381. for line in self.get_cli(**kwargs):
  382. print_cmd.extend(line)
  383. print_cmd.append(LF)
  384. if not ('quiet' in kwargs and kwargs['quiet']):
  385. shell_helpers.ShellHelpers().print_cmd(print_cmd)
  386. return super().__call__(**kwargs)
  387. def _init_env(self, env):
  388. '''
  389. Update the kwargs from the command line with values derived from them.
  390. '''
  391. def join(*paths):
  392. return os.path.join(*paths)
  393. if env['emulator'] in env['emulator_short_to_long_dict']:
  394. env['emulator'] = env['emulator_short_to_long_dict'][env['emulator']]
  395. if not env['_args_given']['userland_build_id']:
  396. env['userland_build_id'] = env['default_build_id']
  397. if not env['_args_given']['gem5_build_id']:
  398. if env['_args_given']['gem5_worktree']:
  399. env['gem5_build_id'] = env['gem5_worktree']
  400. else:
  401. env['gem5_build_id'] = consts['default_build_id']
  402. env['is_arm'] = False
  403. if env['arch'] == 'arm':
  404. env['armv'] = 7
  405. env['mcpu'] = 'cortex-a15'
  406. env['buildroot_toolchain_prefix'] = 'arm-buildroot-linux-uclibcgnueabihf'
  407. env['crosstool_ng_toolchain_prefix'] = 'arm-unknown-eabi'
  408. env['ubuntu_toolchain_prefix'] = 'arm-linux-gnueabihf'
  409. env['is_arm'] = True
  410. elif env['arch'] == 'aarch64':
  411. env['armv'] = 8
  412. env['mcpu'] = 'cortex-a57'
  413. env['buildroot_toolchain_prefix'] = 'aarch64-buildroot-linux-uclibc'
  414. env['crosstool_ng_toolchain_prefix'] = 'aarch64-unknown-elf'
  415. env['ubuntu_toolchain_prefix'] = 'aarch64-linux-gnu'
  416. env['is_arm'] = True
  417. elif env['arch'] == 'x86_64':
  418. env['crosstool_ng_toolchain_prefix'] = 'x86_64-unknown-elf'
  419. env['gem5_arch'] = 'X86'
  420. env['buildroot_toolchain_prefix'] = 'x86_64-buildroot-linux-uclibc'
  421. env['ubuntu_toolchain_prefix'] = 'x86_64-linux-gnu'
  422. if env['emulator'] == 'gem5':
  423. if not env['_args_given']['machine']:
  424. env['machine'] = 'TODO'
  425. else:
  426. if not env['_args_given']['machine']:
  427. env['machine'] = 'pc'
  428. if env['is_arm']:
  429. env['gem5_arch'] = 'ARM'
  430. if env['emulator'] == 'gem5':
  431. if not env['_args_given']['machine']:
  432. if env['dp650']:
  433. env['machine'] = 'VExpress_GEM5_V1_DPU'
  434. else:
  435. env['machine'] = 'VExpress_GEM5_V1'
  436. else:
  437. if not env['_args_given']['machine']:
  438. env['machine'] = 'virt'
  439. if env['arch'] == 'arm':
  440. # highmem=off needed since v3.0.0 due to:
  441. # http://lists.nongnu.org/archive/html/qemu-discuss/2018-08/msg00034.html
  442. env['machine2'] = 'highmem=off'
  443. elif env['arch'] == 'aarch64':
  444. env['machine2'] = 'gic_version=3'
  445. else:
  446. env['machine2'] = None
  447. # Buildroot
  448. env['buildroot_build_dir'] = join(env['buildroot_out_dir'], 'build', env['buildroot_build_id'], env['arch'])
  449. env['buildroot_download_dir'] = join(env['buildroot_out_dir'], 'download')
  450. env['buildroot_config_file'] = join(env['buildroot_build_dir'], '.config')
  451. env['buildroot_build_build_dir'] = join(env['buildroot_build_dir'], 'build')
  452. env['buildroot_linux_build_dir'] = join(env['buildroot_build_build_dir'], 'linux-custom')
  453. env['buildroot_vmlinux'] = join(env['buildroot_linux_build_dir'], 'vmlinux')
  454. env['host_dir'] = join(env['buildroot_build_dir'], 'host')
  455. env['host_bin_dir'] = join(env['host_dir'], 'usr', 'bin')
  456. env['buildroot_pkg_config'] = join(env['host_bin_dir'], 'pkg-config')
  457. env['buildroot_images_dir'] = join(env['buildroot_build_dir'], 'images')
  458. env['buildroot_rootfs_raw_file'] = join(env['buildroot_images_dir'], 'rootfs.ext2')
  459. env['buildroot_qcow2_file'] = env['buildroot_rootfs_raw_file'] + '.qcow2'
  460. env['buildroot_cpio'] = join(env['buildroot_images_dir'], 'rootfs.cpio')
  461. env['staging_dir'] = join(env['out_dir'], 'staging', env['arch'])
  462. env['buildroot_staging_dir'] = join(env['buildroot_build_dir'], 'staging')
  463. env['target_dir'] = join(env['buildroot_build_dir'], 'target')
  464. if not env['_args_given']['linux_source_dir']:
  465. env['linux_source_dir'] = os.path.join(consts['submodules_dir'], 'linux')
  466. common.extract_vmlinux = os.path.join(env['linux_source_dir'], 'scripts', 'extract-vmlinux')
  467. env['linux_buildroot_build_dir'] = join(env['buildroot_build_build_dir'], 'linux-custom')
  468. # QEMU
  469. env['qemu_build_dir'] = join(env['out_dir'], 'qemu', env['qemu_build_id'])
  470. env['qemu_executable_basename'] = 'qemu-system-{}'.format(env['arch'])
  471. env['qemu_executable'] = join(env['qemu_build_dir'], '{}-softmmu'.format(env['arch']), env['qemu_executable_basename'])
  472. env['qemu_img_basename'] = 'qemu-img'
  473. env['qemu_img_executable'] = join(env['qemu_build_dir'], env['qemu_img_basename'])
  474. # gem5
  475. if not env['_args_given']['gem5_build_dir']:
  476. env['gem5_build_dir'] = join(env['gem5_out_dir'], env['gem5_build_id'], env['gem5_build_type'])
  477. env['gem5_fake_iso'] = join(env['gem5_out_dir'], 'fake.iso')
  478. env['gem5_m5term'] = join(env['gem5_build_dir'], 'm5term')
  479. env['gem5_build_build_dir'] = join(env['gem5_build_dir'], 'build')
  480. env['gem5_executable'] = join(env['gem5_build_build_dir'], env['gem5_arch'], 'gem5.{}'.format(env['gem5_build_type']))
  481. env['gem5_system_dir'] = join(env['gem5_build_dir'], 'system')
  482. # gem5 source
  483. if env['gem5_source_dir'] is not None:
  484. assert os.path.exists(env['gem5_source_dir'])
  485. else:
  486. if env['gem5_worktree'] is not None:
  487. env['gem5_source_dir'] = join(env['gem5_non_default_source_root_dir'], env['gem5_worktree'])
  488. else:
  489. env['gem5_source_dir'] = env['gem5_default_source_dir']
  490. env['gem5_m5_source_dir'] = join(env['gem5_source_dir'], 'util', 'm5')
  491. env['gem5_config_dir'] = join(env['gem5_source_dir'], 'configs')
  492. env['gem5_se_file'] = join(env['gem5_config_dir'], 'example', 'se.py')
  493. env['gem5_fs_file'] = join(env['gem5_config_dir'], 'example', 'fs.py')
  494. # crosstool-ng
  495. env['crosstool_ng_buildid_dir'] = join(env['crosstool_ng_out_dir'], 'build', env['crosstool_ng_build_id'])
  496. env['crosstool_ng_install_dir'] = join(env['crosstool_ng_buildid_dir'], 'install', env['arch'])
  497. env['crosstool_ng_bin_dir'] = join(env['crosstool_ng_install_dir'], 'bin')
  498. env['crosstool_ng_util_dir'] = join(env['crosstool_ng_buildid_dir'], 'util')
  499. env['crosstool_ng_config'] = join(env['crosstool_ng_util_dir'], '.config')
  500. env['crosstool_ng_defconfig'] = join(env['crosstool_ng_util_dir'], 'defconfig')
  501. env['crosstool_ng_executable'] = join(env['crosstool_ng_util_dir'], 'ct-ng')
  502. env['crosstool_ng_build_dir'] = join(env['crosstool_ng_buildid_dir'], 'build')
  503. env['crosstool_ng_download_dir'] = join(env['crosstool_ng_out_dir'], 'download')
  504. # run
  505. env['gem5_run_dir'] = join(env['run_dir_base'], 'gem5', env['arch'], str(env['run_id']))
  506. env['m5out_dir'] = join(env['gem5_run_dir'], 'm5out')
  507. env['stats_file'] = join(env['m5out_dir'], 'stats.txt')
  508. env['gem5_trace_txt_file'] = join(env['m5out_dir'], 'trace.txt')
  509. env['gem5_guest_terminal_file'] = join(env['m5out_dir'], 'system.terminal')
  510. env['gem5_readfile'] = join(env['gem5_run_dir'], 'readfile')
  511. env['gem5_termout_file'] = join(env['gem5_run_dir'], 'termout.txt')
  512. env['qemu_run_dir'] = join(env['run_dir_base'], 'qemu', env['arch'], str(env['run_id']))
  513. env['qemu_termout_file'] = join(env['qemu_run_dir'], 'termout.txt')
  514. env['qemu_trace_basename'] = 'trace.bin'
  515. env['qemu_trace_file'] = join(env['qemu_run_dir'], 'trace.bin')
  516. env['qemu_trace_txt_file'] = join(env['qemu_run_dir'], 'trace.txt')
  517. env['qemu_rrfile'] = join(env['qemu_run_dir'], 'rrfile')
  518. env['gem5_out_dir'] = join(env['out_dir'], 'gem5')
  519. # Ports
  520. if not env['_args_given']['port_offset']:
  521. try:
  522. env['port_offset'] = int(env['run_id'])
  523. except ValueError:
  524. env['port_offset'] = 0
  525. if env['emulator'] == 'gem5':
  526. env['gem5_telnet_port'] = 3456 + env['port_offset']
  527. env['gdb_port'] = 7000 + env['port_offset']
  528. else:
  529. env['qemu_base_port'] = 45454 + 10 * env['port_offset']
  530. env['qemu_monitor_port'] = env['qemu_base_port'] + 0
  531. env['qemu_hostfwd_generic_port'] = env['qemu_base_port'] + 1
  532. env['qemu_hostfwd_ssh_port'] = env['qemu_base_port'] + 2
  533. env['qemu_gdb_port'] = env['qemu_base_port'] + 3
  534. env['extra_serial_port'] = env['qemu_base_port'] + 4
  535. env['gdb_port'] = env['qemu_gdb_port']
  536. env['qemu_background_serial_file'] = join(env['qemu_run_dir'], 'background.log')
  537. # gem5 QEMU polymorphism.
  538. if env['emulator'] == 'gem5':
  539. env['executable'] = env['gem5_executable']
  540. env['run_dir'] = env['gem5_run_dir']
  541. env['termout_file'] = env['gem5_termout_file']
  542. env['guest_terminal_file'] = env['gem5_guest_terminal_file']
  543. env['trace_txt_file'] = env['gem5_trace_txt_file']
  544. else:
  545. env['executable'] = env['qemu_executable']
  546. env['run_dir'] = env['qemu_run_dir']
  547. env['termout_file'] = env['qemu_termout_file']
  548. env['guest_terminal_file'] = env['qemu_termout_file']
  549. env['trace_txt_file'] = env['qemu_trace_txt_file']
  550. env['run_cmd_file'] = join(env['run_dir'], 'run.sh')
  551. # Linux kernel.
  552. if not env['_args_given']['linux_build_dir']:
  553. env['linux_build_dir'] = join(env['out_dir'], 'linux', env['linux_build_id'], env['arch'])
  554. env['lkmc_vmlinux'] = join(env['linux_build_dir'], 'vmlinux')
  555. if env['arch'] == 'arm':
  556. env['linux_arch'] = 'arm'
  557. env['linux_image_prefix'] = join('arch', env['linux_arch'], 'boot', 'zImage')
  558. elif env['arch'] == 'aarch64':
  559. env['linux_arch'] = 'arm64'
  560. env['linux_image_prefix'] = join('arch', env['linux_arch'], 'boot', 'Image')
  561. elif env['arch'] == 'x86_64':
  562. env['linux_arch'] = 'x86'
  563. env['linux_image_prefix'] = join('arch', env['linux_arch'], 'boot', 'bzImage')
  564. env['lkmc_linux_image'] = join(env['linux_build_dir'], env['linux_image_prefix'])
  565. env['buildroot_linux_image'] = join(env['buildroot_linux_build_dir'], env['linux_image_prefix'])
  566. if env['buildroot_linux']:
  567. env['vmlinux'] = env['buildroot_vmlinux']
  568. env['linux_image'] = env['buildroot_linux_image']
  569. else:
  570. env['vmlinux'] = env['lkmc_vmlinux']
  571. env['linux_image'] = env['lkmc_linux_image']
  572. if env['emulator']== 'gem5':
  573. env['userland_quit_cmd'] = '/gem5_exit.sh'
  574. else:
  575. env['userland_quit_cmd'] = '/poweroff.out'
  576. env['ramfs'] = env['initrd'] or env['initramfs']
  577. if env['ramfs']:
  578. env['initarg'] = 'rdinit'
  579. else:
  580. env['initarg'] = 'init'
  581. env['quit_init'] = '{}={}'.format(env['initarg'], env['userland_quit_cmd'])
  582. # Kernel modules.
  583. env['kernel_modules_build_dir'] = join(env['kernel_modules_build_base_dir'], env['arch'])
  584. env['kernel_modules_build_subdir'] = join(env['kernel_modules_build_dir'], env['kernel_modules_subdir'])
  585. env['kernel_modules_build_host_dir'] = join(env['kernel_modules_build_base_dir'], 'host')
  586. env['kernel_modules_build_host_subdir'] = join(env['kernel_modules_build_host_dir'], env['kernel_modules_subdir'])
  587. env['userland_build_dir'] = join(env['out_dir'], 'userland', env['userland_build_id'], env['arch'])
  588. env['out_rootfs_overlay_dir'] = join(env['out_dir'], 'rootfs_overlay', env['arch'])
  589. env['out_rootfs_overlay_bin_dir'] = join(env['out_rootfs_overlay_dir'], 'bin')
  590. # Baremetal.
  591. env['baremetal_source_dir'] = join(env['root_dir'], 'baremetal')
  592. env['baremetal_source_arch_subpath'] = join('arch', env['arch'])
  593. env['baremetal_source_arch_dir'] = join(env['baremetal_source_dir'], env['baremetal_source_arch_subpath'])
  594. env['baremetal_source_lib_dir'] = join(env['baremetal_source_dir'], env['baremetal_lib_basename'])
  595. if env['emulator'] == 'gem5':
  596. env['simulator_name'] = 'gem5'
  597. else:
  598. env['simulator_name'] = 'qemu'
  599. env['baremetal_build_dir'] = join(env['out_dir'], 'baremetal', env['arch'], env['simulator_name'], env['machine'])
  600. env['baremetal_build_lib_dir'] = join(env['baremetal_build_dir'], env['baremetal_lib_basename'])
  601. env['baremetal_build_ext'] = '.elf'
  602. # Docker
  603. env['docker_build_dir'] = join(env['out_dir'], 'docker', env['arch'])
  604. env['docker_tar_dir'] = join(env['docker_build_dir'], 'export')
  605. env['docker_tar_file'] = join(env['docker_build_dir'], 'export.tar')
  606. env['docker_rootfs_raw_file'] = join(env['docker_build_dir'], 'export.ext2')
  607. env['docker_qcow2_file'] = join(env['docker_rootfs_raw_file'] + '.qcow2')
  608. if env['docker']:
  609. env['rootfs_raw_file'] = env['docker_rootfs_raw_file']
  610. env['qcow2_file'] = env['docker_qcow2_file']
  611. else:
  612. env['rootfs_raw_file'] = env['buildroot_rootfs_raw_file']
  613. env['qcow2_file'] = env['buildroot_qcow2_file']
  614. # Image
  615. if env['_args_given']['baremetal']:
  616. env['disk_image'] = env['gem5_fake_iso']
  617. if env['baremetal'] == 'all':
  618. path = env['baremetal']
  619. else:
  620. path = self.resolve_executable(
  621. env['baremetal'],
  622. env['baremetal_source_dir'],
  623. env['baremetal_build_dir'],
  624. env['baremetal_build_ext'],
  625. )
  626. source_path_noext = os.path.splitext(join(
  627. env['baremetal_source_dir'],
  628. os.path.relpath(path, env['baremetal_build_dir'])
  629. ))[0]
  630. for ext in [env['c_ext'], env['asm_ext']]:
  631. source_path = source_path_noext + ext
  632. if os.path.exists(source_path):
  633. env['source_path'] = source_path
  634. break
  635. env['image'] = path
  636. else:
  637. if env['emulator'] == 'gem5':
  638. env['image'] = env['vmlinux']
  639. if env['ramfs']:
  640. env['disk_image'] = env['gem5_fake_iso']
  641. else:
  642. env['disk_image'] = env['rootfs_raw_file']
  643. else:
  644. env['image'] = env['linux_image']
  645. env['disk_image'] = env['qcow2_file']
  646. def add_argument(self, *args, **kwargs):
  647. '''
  648. Also handle:
  649. - modified defaults from child classes.
  650. - common arguments to forward on Python calls
  651. '''
  652. shortname, longname, key, is_option = self.get_key(*args, **kwargs)
  653. if key in self._defaults:
  654. kwargs['default'] = self._defaults[key]
  655. if self._is_common:
  656. self._common_args.add(key)
  657. super().add_argument(*args, **kwargs)
  658. @staticmethod
  659. def base64_encode(string):
  660. return base64.b64encode(string.encode()).decode()
  661. def get_elf_entry(self, elf_file_path):
  662. readelf_header = subprocess.check_output([
  663. self.get_toolchain_tool('readelf'),
  664. '-h',
  665. elf_file_path
  666. ])
  667. for line in readelf_header.decode().split('\n'):
  668. split = line.split()
  669. if line.startswith(' Entry point address:'):
  670. addr = line.split()[-1]
  671. break
  672. return int(addr, 0)
  673. def gem5_list_checkpoint_dirs(self):
  674. '''
  675. List checkpoint directory, oldest first.
  676. '''
  677. prefix_re = re.compile(self.env['gem5_cpt_prefix'])
  678. files = list(filter(lambda x: os.path.isdir(os.path.join(self.env['m5out_dir'], x)) and prefix_re.search(x), os.listdir(self.env['m5out_dir'])))
  679. files.sort(key=lambda x: os.path.getmtime(os.path.join(self.env['m5out_dir'], x)))
  680. return files
  681. def get_common_args(self):
  682. '''
  683. These are arguments that might be used by more than one script,
  684. and are all defined in this class instead of in the derived class
  685. of the script.
  686. '''
  687. return {
  688. key:self.env[key] for key in self._common_args if self.env['_args_given'][key]
  689. }
  690. def get_stats(self, stat_re=None, stats_file=None):
  691. if stat_re is None:
  692. stat_re = '^system.cpu[0-9]*.numCycles$'
  693. if stats_file is None:
  694. stats_file = self.env['stats_file']
  695. stat_re = re.compile(stat_re)
  696. ret = []
  697. with open(stats_file, 'r') as statfile:
  698. for line in statfile:
  699. if line[0] != '-':
  700. cols = line.split()
  701. if len(cols) > 1 and stat_re.search(cols[0]):
  702. ret.append(cols[1])
  703. return ret
  704. def get_toolchain_prefix(self, tool, allowed_toolchains=None):
  705. buildroot_full_prefix = os.path.join(self.env['host_bin_dir'], self.env['buildroot_toolchain_prefix'])
  706. buildroot_exists = os.path.exists('{}-{}'.format(buildroot_full_prefix, tool))
  707. crosstool_ng_full_prefix = os.path.join(self.env['crosstool_ng_bin_dir'], self.env['crosstool_ng_toolchain_prefix'])
  708. crosstool_ng_exists = os.path.exists('{}-{}'.format(crosstool_ng_full_prefix, tool))
  709. host_tool = '{}-{}'.format(self.env['ubuntu_toolchain_prefix'], tool)
  710. host_path = shutil.which(host_tool)
  711. if host_path is not None:
  712. host_exists = True
  713. host_full_prefix = host_path[:-(len(tool)+1)]
  714. else:
  715. host_exists = False
  716. host_full_prefix = None
  717. known_toolchains = {
  718. 'crosstool-ng': (crosstool_ng_exists, crosstool_ng_full_prefix),
  719. 'buildroot': (buildroot_exists, buildroot_full_prefix),
  720. 'host': (host_exists, host_full_prefix),
  721. }
  722. if allowed_toolchains is None:
  723. if self.env['baremetal'] is None:
  724. allowed_toolchains = ['buildroot', 'crosstool-ng', 'host']
  725. else:
  726. allowed_toolchains = ['crosstool-ng', 'buildroot', 'host']
  727. tried = []
  728. for toolchain in allowed_toolchains:
  729. exists, prefix = known_toolchains[toolchain]
  730. tried.append('{}-{}'.format(prefix, tool))
  731. if exists:
  732. return prefix
  733. error_message = 'Tool not found. Tried:\n' + '\n'.join(tried)
  734. if self.env['dry_run']:
  735. self.log_error(error_message)
  736. return ''
  737. else:
  738. raise Exception(error_message)
  739. def get_toolchain_tool(self, tool, allowed_toolchains=None):
  740. return '{}-{}'.format(self.get_toolchain_prefix(tool, allowed_toolchains), tool)
  741. def github_make_request(
  742. self,
  743. authenticate=False,
  744. data=None,
  745. extra_headers=None,
  746. path='',
  747. subdomain='api',
  748. url_params=None,
  749. **extra_request_args
  750. ):
  751. if extra_headers is None:
  752. extra_headers = {}
  753. headers = {'Accept': 'application/vnd.github.v3+json'}
  754. headers.update(extra_headers)
  755. if authenticate:
  756. headers['Authorization'] = 'token ' + os.environ['LKMC_GITHUB_TOKEN']
  757. if url_params is not None:
  758. path += '?' + urllib.parse.urlencode(url_params)
  759. request = urllib.request.Request(
  760. 'https://' + subdomain + '.github.com/repos/' + self.env['github_repo_id'] + path,
  761. headers=headers,
  762. data=data,
  763. **extra_request_args
  764. )
  765. response_body = urllib.request.urlopen(request).read().decode()
  766. if response_body:
  767. _json = json.loads(response_body)
  768. else:
  769. _json = {}
  770. return _json
  771. def import_path(self, basename):
  772. '''
  773. https://stackoverflow.com/questions/2601047/import-a-python-module-without-the-py-extension
  774. https://stackoverflow.com/questions/31773310/what-does-the-first-argument-of-the-imp-load-source-method-do
  775. '''
  776. return imp.load_source(basename.replace('-', '_'), os.path.join(self.env['root_dir'], basename))
  777. def import_path_main(self, path):
  778. '''
  779. Import an object of the Main class of a given file.
  780. By convention, we call the main object of all our CLI scripts as Main.
  781. '''
  782. return self.import_path(path).Main()
  783. def is_arch_supported(self, arch):
  784. return self.supported_archs is None or arch in self.supported_archs
  785. def log_error(self, msg):
  786. print('error: {}'.format(msg), file=sys.stdout)
  787. def log_info(self, msg='', flush=False, **kwargs):
  788. if not self.env['quiet']:
  789. print('{}'.format(msg), **kwargs)
  790. if flush:
  791. sys.stdout.flush()
  792. def main(self, *args, **kwargs):
  793. '''
  794. Run timed_main across all selected archs and emulators.
  795. :return: if any of the timed_mains exits non-zero and non-null,
  796. return that. Otherwise, return 0.
  797. '''
  798. env = kwargs.copy()
  799. self.input_args = env.copy()
  800. env.update(consts)
  801. real_all_archs = env['all_archs']
  802. if real_all_archs:
  803. real_archs = consts['all_long_archs']
  804. else:
  805. real_archs = env['archs']
  806. if env['all_emulators']:
  807. real_emulators = consts['all_long_emulators']
  808. else:
  809. real_emulators = env['emulators']
  810. return_value = 0
  811. class GetOutOfLoop(Exception): pass
  812. try:
  813. ret = self.setup()
  814. if ret is not None and ret != 0:
  815. return_value = ret
  816. raise GetOutOfLoop()
  817. for emulator in real_emulators:
  818. for arch in real_archs:
  819. if arch in env['arch_short_to_long_dict']:
  820. arch = env['arch_short_to_long_dict'][arch]
  821. if self.is_arch_supported(arch):
  822. if not env['dry_run']:
  823. start_time = time.time()
  824. env['arch'] = arch
  825. env['archs'] = [arch]
  826. env['_args_given']['archs'] = True
  827. env['all_archs'] = False
  828. env['emulator'] = emulator
  829. env['emulators'] = [emulator]
  830. env['_args_given']['emulators'] = True
  831. env['all_emulators'] = False
  832. self.env = env.copy()
  833. self._init_env(self.env)
  834. self.sh = shell_helpers.ShellHelpers(
  835. dry_run=self.env['dry_run'],
  836. quiet=self.env['quiet'],
  837. )
  838. ret = self.timed_main()
  839. if not env['dry_run']:
  840. end_time = time.time()
  841. self.ellapsed_seconds = end_time - start_time
  842. self.print_time(self.ellapsed_seconds)
  843. if ret is not None and ret != 0:
  844. return_value = ret
  845. if self.env['quit_on_fail']:
  846. raise GetOutOfLoop()
  847. elif not real_all_archs:
  848. raise Exception('Unsupported arch for this action: ' + arch)
  849. except GetOutOfLoop:
  850. pass
  851. ret = self.teardown()
  852. if ret is not None and ret != 0:
  853. return_value = ret
  854. return return_value
  855. def make_build_dirs(self):
  856. os.makedirs(self.env['buildroot_build_build_dir'], exist_ok=True)
  857. os.makedirs(self.env['gem5_build_dir'], exist_ok=True)
  858. os.makedirs(self.env['out_rootfs_overlay_dir'], exist_ok=True)
  859. def make_run_dirs(self):
  860. '''
  861. Make directories required for the run.
  862. The user could nuke those anytime between runs to try and clean things up.
  863. '''
  864. os.makedirs(self.env['gem5_run_dir'], exist_ok=True)
  865. os.makedirs(self.env['p9_dir'], exist_ok=True)
  866. os.makedirs(self.env['qemu_run_dir'], exist_ok=True)
  867. @staticmethod
  868. def need_rebuild(srcs, dst):
  869. if not os.path.exists(dst):
  870. return True
  871. for src in srcs:
  872. if os.path.getmtime(src) > os.path.getmtime(dst):
  873. return True
  874. return False
  875. @staticmethod
  876. def seconds_to_hms(seconds):
  877. '''
  878. Seconds to hour:minute:seconds
  879. :ptype seconds: float
  880. :rtype: str
  881. https://stackoverflow.com/questions/775049/how-do-i-convert-seconds-to-hours-minutes-and-seconds
  882. '''
  883. frac, whole = math.modf(seconds)
  884. hours, rem = divmod(whole, 3600)
  885. minutes, seconds = divmod(rem, 60)
  886. return '{:02}:{:02}:{:02}'.format(int(hours), int(minutes), int(seconds))
  887. def print_time(self, ellapsed_seconds):
  888. if self.env['print_time'] and not self.env['quiet']:
  889. print('time {}'.format(self.seconds_to_hms(ellapsed_seconds)))
  890. def raw_to_qcow2(self, prebuilt=False, reverse=False):
  891. if prebuilt or not os.path.exists(self.env['qemu_img_executable']):
  892. disable_trace = []
  893. qemu_img_executable = self.env['qemu_img_basename']
  894. else:
  895. # Prevent qemu-img from generating trace files like QEMU. Disgusting.
  896. disable_trace = ['-T', 'pr_manager_run,file=/dev/null', LF]
  897. qemu_img_executable = self.env['qemu_img_executable']
  898. infmt = 'raw'
  899. outfmt = 'qcow2'
  900. infile = self.env['rootfs_raw_file']
  901. outfile = self.env['qcow2_file']
  902. if reverse:
  903. tmp = infmt
  904. infmt = outfmt
  905. outfmt = tmp
  906. tmp = infile
  907. infile = outfile
  908. outfile = tmp
  909. self.sh.run_cmd(
  910. [
  911. qemu_img_executable, LF,
  912. ] +
  913. disable_trace +
  914. [
  915. 'convert', LF,
  916. '-f', infmt, LF,
  917. '-O', outfmt, LF,
  918. infile, LF,
  919. outfile, LF,
  920. ]
  921. )
  922. @staticmethod
  923. def resolve_args(defaults, args, extra_args):
  924. if extra_args is None:
  925. extra_args = {}
  926. argcopy = copy.copy(args)
  927. argcopy.__dict__ = dict(list(defaults.items()) + list(argcopy.__dict__.items()) + list(extra_args.items()))
  928. return argcopy
  929. def resolve_executable(self, in_path, magic_in_dir, magic_out_dir, out_ext):
  930. if os.path.isabs(in_path):
  931. return in_path
  932. else:
  933. paths = [
  934. os.path.join(magic_out_dir, in_path),
  935. os.path.join(
  936. magic_out_dir,
  937. os.path.relpath(in_path, magic_in_dir),
  938. )
  939. ]
  940. paths[:] = [os.path.splitext(path)[0] + out_ext for path in paths]
  941. for path in paths:
  942. if os.path.exists(path):
  943. return path
  944. if not self.env['dry_run']:
  945. raise Exception('Executable file not found. Tried:\n' + '\n'.join(paths))
  946. def resolve_userland(self, path):
  947. return self.resolve_executable(
  948. path,
  949. self.env['userland_source_dir'],
  950. self.env['userland_build_dir'],
  951. self.env['userland_build_ext'],
  952. )
  953. def setup(self):
  954. '''
  955. Similar to timed_main, but gets run only once for all --arch and --emulator,
  956. before timed_main.
  957. Different from __init__, since at this point env has already been calculated,
  958. so variables that don't depend on --arch or --emulator can be used.
  959. '''
  960. pass
  961. def timed_main(self):
  962. '''
  963. Main action of the derived class.
  964. Gets run once for every --arch and every --emulator.
  965. '''
  966. pass
  967. def teardown(self):
  968. '''
  969. Similar to setup, but run after timed_main.
  970. '''
  971. pass
  972. class BuildCliFunction(LkmcCliFunction):
  973. '''
  974. A CLI function with common facilities to build stuff, e.g.:
  975. * `--clean` to clean the build directory
  976. * `--nproc` to set he number of build threads
  977. '''
  978. def __init__(self, *args, **kwargs):
  979. super().__init__(*args, **kwargs)
  980. self.add_argument(
  981. '--clean',
  982. default=False,
  983. help='Clean the build instead of building.',
  984. ),
  985. self.add_argument(
  986. '-j',
  987. '--nproc',
  988. default=multiprocessing.cpu_count(),
  989. type=int,
  990. help='Number of processors to use for the build.',
  991. )
  992. self.test_results = []
  993. def clean(self):
  994. build_dir = self.get_build_dir()
  995. if build_dir is not None:
  996. self.sh.rmrf(build_dir)
  997. def build(self):
  998. '''
  999. Do the actual main build work.
  1000. '''
  1001. raise NotImplementedError()
  1002. def get_build_dir(self):
  1003. return None
  1004. def timed_main(self):
  1005. '''
  1006. Parse CLI, and to the build based on it.
  1007. The actual build work is done by do_build in implementing classes.
  1008. '''
  1009. if self.env['clean']:
  1010. return self.clean()
  1011. else:
  1012. return self.build()
  1013. # from aenum import Enum # for the aenum version
  1014. TestResult = enum.Enum('TestResult', ['PASS', 'FAIL'])
  1015. class Test:
  1016. def __init__(
  1017. self,
  1018. test_id: str,
  1019. result : TestResult =None,
  1020. ellapsed_seconds : float =None
  1021. ):
  1022. self.test_id = test_id
  1023. self.result = result
  1024. self.ellapsed_seconds = ellapsed_seconds
  1025. def __str__(self):
  1026. out = []
  1027. if self.result is not None:
  1028. out.append(self.result.name)
  1029. if self.ellapsed_seconds is not None:
  1030. out.append(LkmcCliFunction.seconds_to_hms(self.ellapsed_seconds))
  1031. out.append(self.test_id)
  1032. return ' '.join(out)
  1033. class TestCliFunction(LkmcCliFunction):
  1034. '''
  1035. Represents a CLI command that runs tests.
  1036. Automates test reporting boilerplate for those commands.
  1037. '''
  1038. def __init__(self, *args, **kwargs):
  1039. defaults = {
  1040. 'print_time': False,
  1041. }
  1042. if 'defaults' in kwargs:
  1043. defaults.update(kwargs['defaults'])
  1044. kwargs['defaults'] = defaults
  1045. super().__init__(*args, **kwargs)
  1046. self.tests = []
  1047. def run_test(self, run_obj, run_args=None, test_id=None):
  1048. '''
  1049. This is a setup / run / teardown setup for simple tests that just do a single run.
  1050. More complex tests might need to run the steps separately, e.g. gdb tests
  1051. must run multiple commands: one for the run and one GDB.
  1052. :param run_obj: callable object
  1053. :param run_args: arguments to be passed to the runnable object
  1054. :param test_id: test identifier, to be added in addition to of arch and emulator ids
  1055. '''
  1056. if run_obj.is_arch_supported(self.env['arch']):
  1057. if run_args is None:
  1058. run_args = {}
  1059. test_id_string = self.test_setup(test_id)
  1060. exit_status = run_obj(**run_args)
  1061. self.test_teardown(run_obj, exit_status, test_id_string)
  1062. def test_setup(self, test_id):
  1063. test_id_string = '{} {}'.format(self.env['emulator'], self.env['arch'])
  1064. if test_id is not None:
  1065. test_id_string += ' {}'.format(test_id)
  1066. self.log_info('test_id {}'.format(test_id_string), flush=True)
  1067. return test_id_string
  1068. def test_teardown(self, run_obj, exit_status, test_id_string):
  1069. if not self.env['dry_run']:
  1070. if exit_status == 0:
  1071. test_result = TestResult.PASS
  1072. else:
  1073. test_result = TestResult.FAIL
  1074. if self.env['quit_on_fail']:
  1075. self.log_error('Test failed')
  1076. sys.exit(1)
  1077. self.log_info('test_result {}'.format(test_result.name))
  1078. ellapsed_seconds = run_obj.ellapsed_seconds
  1079. else:
  1080. test_result = None
  1081. ellapsed_seconds = None
  1082. self.log_info()
  1083. self.tests.append(Test(test_id_string, test_result, ellapsed_seconds))
  1084. def teardown(self):
  1085. '''
  1086. :return: 1 if any test failed, 0 otherwise
  1087. '''
  1088. self.log_info('Test result summary')
  1089. passes = []
  1090. fails = []
  1091. for test in self.tests:
  1092. if test.result in (TestResult.PASS, None):
  1093. passes.append(test)
  1094. else:
  1095. fails.append(test)
  1096. if passes:
  1097. for test in passes:
  1098. self.log_info(test)
  1099. if fails:
  1100. for test in fails:
  1101. self.log_info(test)
  1102. self.log_error('A test failed')
  1103. return 1
  1104. return 0