kunit_kernel.py 14 KB

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