kunit_kernel.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. # SPDX-License-Identifier: GPL-2.0
  2. #
  3. # Runs UML kernel, collects output, and handles errors.
  4. #
  5. # Copyright (C) 2019, Google LLC.
  6. # Author: Felix Guo <felixguoxiuping@gmail.com>
  7. # Author: Brendan Higgins <brendanhiggins@google.com>
  8. import importlib.abc
  9. import importlib.util
  10. import logging
  11. import subprocess
  12. import os
  13. import shlex
  14. import shutil
  15. import signal
  16. import sys
  17. import threading
  18. from typing import Iterator, List, Optional, Tuple
  19. from types import FrameType
  20. import kunit_config
  21. import qemu_config
  22. KCONFIG_PATH = '.config'
  23. KUNITCONFIG_PATH = '.kunitconfig'
  24. OLD_KUNITCONFIG_PATH = 'last_used_kunitconfig'
  25. DEFAULT_KUNITCONFIG_PATH = 'tools/testing/kunit/configs/default.config'
  26. ALL_TESTS_CONFIG_PATH = 'tools/testing/kunit/configs/all_tests.config'
  27. UML_KCONFIG_PATH = 'tools/testing/kunit/configs/arch_uml.config'
  28. OUTFILE_PATH = 'test.log'
  29. ABS_TOOL_PATH = os.path.abspath(os.path.dirname(__file__))
  30. QEMU_CONFIGS_DIR = os.path.join(ABS_TOOL_PATH, 'qemu_configs')
  31. class ConfigError(Exception):
  32. """Represents an error trying to configure the Linux kernel."""
  33. class BuildError(Exception):
  34. """Represents an error trying to build the Linux kernel."""
  35. class LinuxSourceTreeOperations:
  36. """An abstraction over command line operations performed on a source tree."""
  37. def __init__(self, linux_arch: str, cross_compile: Optional[str]):
  38. self._linux_arch = linux_arch
  39. self._cross_compile = cross_compile
  40. def make_mrproper(self) -> None:
  41. try:
  42. subprocess.check_output(['make', 'mrproper'], stderr=subprocess.STDOUT)
  43. except OSError as e:
  44. raise ConfigError('Could not call make command: ' + str(e))
  45. except subprocess.CalledProcessError as e:
  46. raise ConfigError(e.output.decode())
  47. def make_arch_config(self, base_kunitconfig: kunit_config.Kconfig) -> kunit_config.Kconfig:
  48. return base_kunitconfig
  49. def make_olddefconfig(self, build_dir: str, make_options: Optional[List[str]]) -> None:
  50. command = ['make', 'ARCH=' + self._linux_arch, 'O=' + build_dir, 'olddefconfig']
  51. if self._cross_compile:
  52. command += ['CROSS_COMPILE=' + self._cross_compile]
  53. if make_options:
  54. command.extend(make_options)
  55. print('Populating config with:\n$', ' '.join(command))
  56. try:
  57. subprocess.check_output(command, stderr=subprocess.STDOUT)
  58. except OSError as e:
  59. raise ConfigError('Could not call make command: ' + str(e))
  60. except subprocess.CalledProcessError as e:
  61. raise ConfigError(e.output.decode())
  62. def make(self, jobs: int, build_dir: str, make_options: Optional[List[str]]) -> None:
  63. command = ['make', 'all', 'compile_commands.json', 'scripts_gdb',
  64. 'ARCH=' + self._linux_arch, 'O=' + build_dir, '--jobs=' + str(jobs)]
  65. if make_options:
  66. command.extend(make_options)
  67. if self._cross_compile:
  68. command += ['CROSS_COMPILE=' + self._cross_compile]
  69. print('Building with:\n$', ' '.join(command))
  70. try:
  71. proc = subprocess.Popen(command,
  72. stderr=subprocess.PIPE,
  73. stdout=subprocess.DEVNULL)
  74. except OSError as e:
  75. raise BuildError('Could not call execute make: ' + str(e))
  76. except subprocess.CalledProcessError as e:
  77. raise BuildError(e.output)
  78. _, stderr = proc.communicate()
  79. if proc.returncode != 0:
  80. raise BuildError(stderr.decode())
  81. if stderr: # likely only due to build warnings
  82. print(stderr.decode())
  83. def start(self, params: List[str], build_dir: str) -> subprocess.Popen:
  84. raise RuntimeError('not implemented!')
  85. class LinuxSourceTreeOperationsQemu(LinuxSourceTreeOperations):
  86. def __init__(self, qemu_arch_params: qemu_config.QemuArchParams, cross_compile: Optional[str]):
  87. super().__init__(linux_arch=qemu_arch_params.linux_arch,
  88. cross_compile=cross_compile)
  89. self._kconfig = qemu_arch_params.kconfig
  90. self._qemu_arch = qemu_arch_params.qemu_arch
  91. self._kernel_path = qemu_arch_params.kernel_path
  92. self._kernel_command_line = qemu_arch_params.kernel_command_line
  93. if 'kunit_shutdown=' not in self._kernel_command_line:
  94. self._kernel_command_line += ' kunit_shutdown=reboot'
  95. self._extra_qemu_params = qemu_arch_params.extra_qemu_params
  96. self._serial = qemu_arch_params.serial
  97. def make_arch_config(self, base_kunitconfig: kunit_config.Kconfig) -> kunit_config.Kconfig:
  98. kconfig = kunit_config.parse_from_string(self._kconfig)
  99. kconfig.merge_in_entries(base_kunitconfig)
  100. return kconfig
  101. def start(self, params: List[str], build_dir: str) -> subprocess.Popen:
  102. kernel_path = os.path.join(build_dir, self._kernel_path)
  103. qemu_command = ['qemu-system-' + self._qemu_arch,
  104. '-nodefaults',
  105. '-m', '1024',
  106. '-kernel', kernel_path,
  107. '-append', ' '.join(params + [self._kernel_command_line]),
  108. '-no-reboot',
  109. '-nographic',
  110. '-accel', 'kvm',
  111. '-accel', 'hvf',
  112. '-accel', 'tcg',
  113. '-serial', self._serial] + self._extra_qemu_params
  114. # Note: shlex.join() does what we want, but requires python 3.8+.
  115. print('Running tests with:\n$', ' '.join(shlex.quote(arg) for arg in qemu_command))
  116. return subprocess.Popen(qemu_command,
  117. stdin=subprocess.PIPE,
  118. stdout=subprocess.PIPE,
  119. stderr=subprocess.STDOUT,
  120. text=True, errors='backslashreplace')
  121. class LinuxSourceTreeOperationsUml(LinuxSourceTreeOperations):
  122. """An abstraction over command line operations performed on a source tree."""
  123. def __init__(self, cross_compile: Optional[str]=None):
  124. super().__init__(linux_arch='um', cross_compile=cross_compile)
  125. def make_arch_config(self, base_kunitconfig: kunit_config.Kconfig) -> kunit_config.Kconfig:
  126. kconfig = kunit_config.parse_file(UML_KCONFIG_PATH)
  127. kconfig.merge_in_entries(base_kunitconfig)
  128. return kconfig
  129. def start(self, params: List[str], build_dir: str) -> subprocess.Popen:
  130. """Runs the Linux UML binary. Must be named 'linux'."""
  131. linux_bin = os.path.join(build_dir, 'linux')
  132. params.extend(['mem=1G', 'console=tty', 'kunit_shutdown=halt'])
  133. print('Running tests with:\n$', linux_bin, ' '.join(shlex.quote(arg) for arg in params))
  134. return subprocess.Popen([linux_bin] + params,
  135. stdin=subprocess.PIPE,
  136. stdout=subprocess.PIPE,
  137. stderr=subprocess.STDOUT,
  138. text=True, errors='backslashreplace')
  139. def get_kconfig_path(build_dir: str) -> str:
  140. return os.path.join(build_dir, KCONFIG_PATH)
  141. def get_kunitconfig_path(build_dir: str) -> str:
  142. return os.path.join(build_dir, KUNITCONFIG_PATH)
  143. def get_old_kunitconfig_path(build_dir: str) -> str:
  144. return os.path.join(build_dir, OLD_KUNITCONFIG_PATH)
  145. def get_parsed_kunitconfig(build_dir: str,
  146. kunitconfig_paths: Optional[List[str]]=None) -> kunit_config.Kconfig:
  147. if not kunitconfig_paths:
  148. path = get_kunitconfig_path(build_dir)
  149. if not os.path.exists(path):
  150. shutil.copyfile(DEFAULT_KUNITCONFIG_PATH, path)
  151. return kunit_config.parse_file(path)
  152. merged = kunit_config.Kconfig()
  153. for path in kunitconfig_paths:
  154. if os.path.isdir(path):
  155. path = os.path.join(path, KUNITCONFIG_PATH)
  156. if not os.path.exists(path):
  157. raise ConfigError(f'Specified kunitconfig ({path}) does not exist')
  158. partial = kunit_config.parse_file(path)
  159. diff = merged.conflicting_options(partial)
  160. if diff:
  161. diff_str = '\n\n'.join(f'{a}\n vs from {path}\n{b}' for a, b in diff)
  162. raise ConfigError(f'Multiple values specified for {len(diff)} options in kunitconfig:\n{diff_str}')
  163. merged.merge_in_entries(partial)
  164. return merged
  165. def get_outfile_path(build_dir: str) -> str:
  166. return os.path.join(build_dir, OUTFILE_PATH)
  167. def _default_qemu_config_path(arch: str) -> str:
  168. config_path = os.path.join(QEMU_CONFIGS_DIR, arch + '.py')
  169. if os.path.isfile(config_path):
  170. return config_path
  171. options = [f[:-3] for f in os.listdir(QEMU_CONFIGS_DIR) if f.endswith('.py')]
  172. if arch == 'help':
  173. print('um')
  174. for option in options:
  175. print(option)
  176. sys.exit()
  177. raise ConfigError(arch + ' is not a valid arch, options are ' + str(sorted(options)))
  178. def _get_qemu_ops(config_path: str,
  179. extra_qemu_args: Optional[List[str]],
  180. cross_compile: Optional[str]) -> Tuple[str, LinuxSourceTreeOperations]:
  181. # The module name/path has very little to do with where the actual file
  182. # exists (I learned this through experimentation and could not find it
  183. # anywhere in the Python documentation).
  184. #
  185. # Bascially, we completely ignore the actual file location of the config
  186. # we are loading and just tell Python that the module lives in the
  187. # QEMU_CONFIGS_DIR for import purposes regardless of where it actually
  188. # exists as a file.
  189. module_path = '.' + os.path.join(os.path.basename(QEMU_CONFIGS_DIR), os.path.basename(config_path))
  190. spec = importlib.util.spec_from_file_location(module_path, config_path)
  191. assert spec is not None
  192. config = importlib.util.module_from_spec(spec)
  193. # See https://github.com/python/typeshed/pull/2626 for context.
  194. assert isinstance(spec.loader, importlib.abc.Loader)
  195. spec.loader.exec_module(config)
  196. if not hasattr(config, 'QEMU_ARCH'):
  197. raise ValueError('qemu_config module missing "QEMU_ARCH": ' + config_path)
  198. params: qemu_config.QemuArchParams = config.QEMU_ARCH
  199. if extra_qemu_args:
  200. params.extra_qemu_params.extend(extra_qemu_args)
  201. return params.linux_arch, LinuxSourceTreeOperationsQemu(
  202. params, cross_compile=cross_compile)
  203. class LinuxSourceTree:
  204. """Represents a Linux kernel source tree with KUnit tests."""
  205. def __init__(
  206. self,
  207. build_dir: str,
  208. kunitconfig_paths: Optional[List[str]]=None,
  209. kconfig_add: Optional[List[str]]=None,
  210. arch: Optional[str]=None,
  211. cross_compile: Optional[str]=None,
  212. qemu_config_path: Optional[str]=None,
  213. extra_qemu_args: Optional[List[str]]=None) -> None:
  214. signal.signal(signal.SIGINT, self.signal_handler)
  215. if qemu_config_path:
  216. self._arch, self._ops = _get_qemu_ops(qemu_config_path, extra_qemu_args, cross_compile)
  217. else:
  218. self._arch = 'um' if arch is None else arch
  219. if self._arch == 'um':
  220. self._ops = LinuxSourceTreeOperationsUml(cross_compile=cross_compile)
  221. else:
  222. qemu_config_path = _default_qemu_config_path(self._arch)
  223. _, self._ops = _get_qemu_ops(qemu_config_path, extra_qemu_args, cross_compile)
  224. self._kconfig = get_parsed_kunitconfig(build_dir, kunitconfig_paths)
  225. if kconfig_add:
  226. kconfig = kunit_config.parse_from_string('\n'.join(kconfig_add))
  227. self._kconfig.merge_in_entries(kconfig)
  228. def arch(self) -> str:
  229. return self._arch
  230. def clean(self) -> bool:
  231. try:
  232. self._ops.make_mrproper()
  233. except ConfigError as e:
  234. logging.error(e)
  235. return False
  236. return True
  237. def validate_config(self, build_dir: str) -> bool:
  238. kconfig_path = get_kconfig_path(build_dir)
  239. validated_kconfig = kunit_config.parse_file(kconfig_path)
  240. if self._kconfig.is_subset_of(validated_kconfig):
  241. return True
  242. missing = set(self._kconfig.as_entries()) - set(validated_kconfig.as_entries())
  243. message = 'Not all Kconfig options selected in kunitconfig were in the generated .config.\n' \
  244. 'This is probably due to unsatisfied dependencies.\n' \
  245. 'Missing: ' + ', '.join(str(e) for e in missing)
  246. if self._arch == 'um':
  247. message += '\nNote: many Kconfig options aren\'t available on UML. You can try running ' \
  248. 'on a different architecture with something like "--arch=x86_64".'
  249. logging.error(message)
  250. return False
  251. def build_config(self, build_dir: str, make_options: Optional[List[str]]) -> bool:
  252. kconfig_path = get_kconfig_path(build_dir)
  253. if build_dir and not os.path.exists(build_dir):
  254. os.mkdir(build_dir)
  255. try:
  256. self._kconfig = self._ops.make_arch_config(self._kconfig)
  257. self._kconfig.write_to_file(kconfig_path)
  258. self._ops.make_olddefconfig(build_dir, make_options)
  259. except ConfigError as e:
  260. logging.error(e)
  261. return False
  262. if not self.validate_config(build_dir):
  263. return False
  264. old_path = get_old_kunitconfig_path(build_dir)
  265. if os.path.exists(old_path):
  266. os.remove(old_path) # write_to_file appends to the file
  267. self._kconfig.write_to_file(old_path)
  268. return True
  269. def _kunitconfig_changed(self, build_dir: str) -> bool:
  270. old_path = get_old_kunitconfig_path(build_dir)
  271. if not os.path.exists(old_path):
  272. return True
  273. old_kconfig = kunit_config.parse_file(old_path)
  274. return old_kconfig != self._kconfig
  275. def build_reconfig(self, build_dir: str, make_options: Optional[List[str]]) -> bool:
  276. """Creates a new .config if it is not a subset of the .kunitconfig."""
  277. kconfig_path = get_kconfig_path(build_dir)
  278. if not os.path.exists(kconfig_path):
  279. print('Generating .config ...')
  280. return self.build_config(build_dir, make_options)
  281. existing_kconfig = kunit_config.parse_file(kconfig_path)
  282. self._kconfig = self._ops.make_arch_config(self._kconfig)
  283. if self._kconfig.is_subset_of(existing_kconfig) and not self._kunitconfig_changed(build_dir):
  284. return True
  285. print('Regenerating .config ...')
  286. os.remove(kconfig_path)
  287. return self.build_config(build_dir, make_options)
  288. def build_kernel(self, jobs: int, build_dir: str, make_options: Optional[List[str]]) -> bool:
  289. try:
  290. self._ops.make_olddefconfig(build_dir, make_options)
  291. self._ops.make(jobs, build_dir, make_options)
  292. except (ConfigError, BuildError) as e:
  293. logging.error(e)
  294. return False
  295. return self.validate_config(build_dir)
  296. def run_kernel(self, args: Optional[List[str]]=None, build_dir: str='', filter_glob: str='', filter: str='', filter_action: Optional[str]=None, timeout: Optional[int]=None) -> Iterator[str]:
  297. # Copy to avoid mutating the caller-supplied list. exec_tests() reuses
  298. # the same args across repeated run_kernel() calls (e.g. --run_isolated),
  299. # so appending to the original would accumulate stale flags on each call.
  300. args = list(args) if args else []
  301. if filter_glob:
  302. args.append('kunit.filter_glob=' + filter_glob)
  303. if filter:
  304. args.append('kunit.filter="' + filter + '"')
  305. if filter_action:
  306. args.append('kunit.filter_action=' + filter_action)
  307. args.append('kunit.enable=1')
  308. process = self._ops.start(args, build_dir)
  309. assert process.stdout is not None # tell mypy it's set
  310. # Enforce the timeout in a background thread.
  311. def _wait_proc() -> None:
  312. try:
  313. process.wait(timeout=timeout)
  314. except Exception as e:
  315. print(e)
  316. process.terminate()
  317. process.wait()
  318. waiter = threading.Thread(target=_wait_proc)
  319. waiter.start()
  320. output = open(get_outfile_path(build_dir), 'w')
  321. try:
  322. # Tee the output to the file and to our caller in real time.
  323. for line in process.stdout:
  324. output.write(line)
  325. yield line
  326. # This runs even if our caller doesn't consume every line.
  327. finally:
  328. # Flush any leftover output to the file
  329. output.write(process.stdout.read())
  330. output.close()
  331. process.stdout.close()
  332. waiter.join()
  333. subprocess.call(['stty', 'sane'])
  334. def signal_handler(self, unused_sig: int, unused_frame: Optional[FrameType]) -> None:
  335. logging.error('Build interruption occurred. Cleaning console.')
  336. subprocess.call(['stty', 'sane'])