kunit_kernel.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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 <[email protected]>
  7. # Author: Brendan Higgins <[email protected]>
  8. import importlib.abc
  9. import importlib.util
  10. import logging
  11. import subprocess
  12. import os
  13. import glob
  14. import shlex
  15. import shutil
  16. import signal
  17. import threading
  18. from typing import Iterator, List, Optional, Tuple
  19. import kunit_config
  20. from kunit_printer import stdout
  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. DEFAULT_SUBMODULE_KUNITCONFIG_PATH = 'kunitconfigs'
  32. PREFIX_SUBMODULE_FILE = 'kunitconfig.'
  33. class ConfigError(Exception):
  34. """Represents an error trying to configure the Linux kernel."""
  35. class BuildError(Exception):
  36. """Represents an error trying to build the Linux kernel."""
  37. class LinuxSourceTreeOperations:
  38. """An abstraction over command line operations performed on a source tree."""
  39. def __init__(self, linux_arch: str, cross_compile: Optional[str]):
  40. self._linux_arch = linux_arch
  41. self._cross_compile = cross_compile
  42. def make_mrproper(self) -> None:
  43. try:
  44. subprocess.check_output(['make', 'mrproper'], stderr=subprocess.STDOUT)
  45. except OSError as e:
  46. raise ConfigError('Could not call make command: ' + str(e))
  47. except subprocess.CalledProcessError as e:
  48. raise ConfigError(e.output.decode())
  49. def make_arch_config(self, base_kunitconfig: kunit_config.Kconfig) -> kunit_config.Kconfig:
  50. return base_kunitconfig
  51. def make_olddefconfig(self, build_dir: str, make_options) -> None:
  52. command = ['make', 'ARCH=' + self._linux_arch, 'O=' + build_dir, 'olddefconfig']
  53. if self._cross_compile:
  54. command += ['CROSS_COMPILE=' + self._cross_compile]
  55. if make_options:
  56. command.extend(make_options)
  57. print('Populating config with:\n$', ' '.join(command))
  58. try:
  59. subprocess.check_output(command, stderr=subprocess.STDOUT)
  60. except OSError as e:
  61. raise ConfigError('Could not call make command: ' + str(e))
  62. except subprocess.CalledProcessError as e:
  63. raise ConfigError(e.output.decode())
  64. def make(self, jobs, build_dir: str, make_options) -> None:
  65. command = ['make', 'ARCH=' + self._linux_arch, 'O=' + build_dir, '--jobs=' + str(jobs)]
  66. if make_options:
  67. command.extend(make_options)
  68. if self._cross_compile:
  69. command += ['CROSS_COMPILE=' + self._cross_compile]
  70. print('Building with:\n$', ' '.join(command))
  71. try:
  72. proc = subprocess.Popen(command,
  73. stderr=subprocess.PIPE,
  74. stdout=subprocess.DEVNULL)
  75. except OSError as e:
  76. raise BuildError('Could not call execute make: ' + str(e))
  77. except subprocess.CalledProcessError as e:
  78. raise BuildError(e.output)
  79. _, stderr = proc.communicate()
  80. if proc.returncode != 0:
  81. raise BuildError(stderr.decode())
  82. if stderr: # likely only due to build warnings
  83. print(stderr.decode())
  84. def start(self, params: List[str], build_dir: str) -> subprocess.Popen:
  85. raise RuntimeError('not implemented!')
  86. class LinuxSourceTreeOperationsQemu(LinuxSourceTreeOperations):
  87. def __init__(self, qemu_arch_params: qemu_config.QemuArchParams, cross_compile: Optional[str]):
  88. super().__init__(linux_arch=qemu_arch_params.linux_arch,
  89. cross_compile=cross_compile)
  90. self._kconfig = qemu_arch_params.kconfig
  91. self._qemu_arch = qemu_arch_params.qemu_arch
  92. self._kernel_path = qemu_arch_params.kernel_path
  93. self._kernel_command_line = qemu_arch_params.kernel_command_line + ' kunit_shutdown=reboot'
  94. self._extra_qemu_params = qemu_arch_params.extra_qemu_params
  95. def make_arch_config(self, base_kunitconfig: kunit_config.Kconfig) -> kunit_config.Kconfig:
  96. kconfig = kunit_config.parse_from_string(self._kconfig)
  97. kconfig.merge_in_entries(base_kunitconfig)
  98. return kconfig
  99. def start(self, params: List[str], build_dir: str) -> subprocess.Popen:
  100. kernel_path = os.path.join(build_dir, self._kernel_path)
  101. qemu_command = ['qemu-system-' + self._qemu_arch,
  102. '-nodefaults',
  103. '-m', '1024',
  104. '-kernel', kernel_path,
  105. '-append', ' '.join(params + [self._kernel_command_line]),
  106. '-no-reboot',
  107. '-nographic',
  108. '-serial', 'stdio'] + self._extra_qemu_params
  109. # Note: shlex.join() does what we want, but requires python 3.8+.
  110. print('Running tests with:\n$', ' '.join(shlex.quote(arg) for arg in qemu_command))
  111. return subprocess.Popen(qemu_command,
  112. stdin=subprocess.PIPE,
  113. stdout=subprocess.PIPE,
  114. stderr=subprocess.STDOUT,
  115. text=True, errors='backslashreplace')
  116. class LinuxSourceTreeOperationsUml(LinuxSourceTreeOperations):
  117. """An abstraction over command line operations performed on a source tree."""
  118. def __init__(self, cross_compile=None):
  119. super().__init__(linux_arch='um', cross_compile=cross_compile)
  120. def make_arch_config(self, base_kunitconfig: kunit_config.Kconfig) -> kunit_config.Kconfig:
  121. kconfig = kunit_config.parse_file(UML_KCONFIG_PATH)
  122. kconfig.merge_in_entries(base_kunitconfig)
  123. return kconfig
  124. def start(self, params: List[str], build_dir: str) -> subprocess.Popen:
  125. """Runs the Linux UML binary. Must be named 'linux'."""
  126. linux_bin = os.path.join(build_dir, 'linux')
  127. params.extend(['mem=1G', 'console=tty', 'kunit_shutdown=halt'])
  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 # type: ignore
  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. def get_submodule_kunitconfig_path(name):
  193. return os.path.join(DEFAULT_SUBMODULE_KUNITCONFIG_PATH, PREFIX_SUBMODULE_FILE + '%s' %name)
  194. def get_sub_config(name):
  195. submodule_kunitconfig = get_submodule_kunitconfig_path(name)
  196. group_submodule_kunitconfig = glob.glob(submodule_kunitconfig + '*')
  197. if not group_submodule_kunitconfig:
  198. return [os.path.join('.', name)]
  199. else:
  200. return group_submodule_kunitconfig
  201. class LinuxSourceTree:
  202. """Represents a Linux kernel source tree with KUnit tests."""
  203. def __init__(
  204. self,
  205. build_dir: str,
  206. kunitconfig_paths: Optional[List[str]]=None,
  207. kconfig_add: Optional[List[str]]=None,
  208. arch=None,
  209. cross_compile=None,
  210. qemu_config_path=None,
  211. extra_qemu_args=None) -> None:
  212. signal.signal(signal.SIGINT, self.signal_handler)
  213. if qemu_config_path:
  214. self._arch, self._ops = _get_qemu_ops(qemu_config_path, extra_qemu_args, cross_compile)
  215. else:
  216. self._arch = 'um' if arch is None else arch
  217. if self._arch == 'um':
  218. self._ops = LinuxSourceTreeOperationsUml(cross_compile=cross_compile)
  219. else:
  220. qemu_config_path = _default_qemu_config_path(self._arch)
  221. _, self._ops = _get_qemu_ops(qemu_config_path, extra_qemu_args, cross_compile)
  222. self._kconfig = get_parsed_kunitconfig(build_dir, kunitconfig_paths)
  223. if kconfig_add:
  224. kconfig = kunit_config.parse_from_string('\n'.join(kconfig_add))
  225. self._kconfig.merge_in_entries(kconfig)
  226. def arch(self) -> str:
  227. return self._arch
  228. def clean(self) -> bool:
  229. try:
  230. self._ops.make_mrproper()
  231. except ConfigError as e:
  232. logging.error(e)
  233. return False
  234. return True
  235. def validate_config(self, build_dir: str) -> bool:
  236. kconfig_path = get_kconfig_path(build_dir)
  237. validated_kconfig = kunit_config.parse_file(kconfig_path)
  238. if self._kconfig.is_subset_of(validated_kconfig):
  239. return True
  240. missing = set(self._kconfig.as_entries()) - set(validated_kconfig.as_entries())
  241. message = 'Not all Kconfig options selected in kunitconfig were in the generated .config.\n' \
  242. 'This is probably due to unsatisfied dependencies.\n' \
  243. 'Missing: ' + ', '.join(str(e) for e in missing)
  244. if self._arch == 'um':
  245. message += '\nNote: many Kconfig options aren\'t available on UML. You can try running ' \
  246. 'on a different architecture with something like "--arch=x86_64".'
  247. logging.error(message)
  248. return False
  249. def add_external_config(self, ex_config):
  250. print("-------- Add External configs ----------")
  251. if not ex_config:
  252. logging.warning("No external config!")
  253. return
  254. for module in ex_config:
  255. module_configs = get_sub_config(module)
  256. for config in module_configs:
  257. if not os.path.exists(config):
  258. logging.error("Couldn't find kunitconfigs/kunitconfig.%s file" %module)
  259. continue;
  260. additional_config = kunit_config.parse_file(config)
  261. print(additional_config)
  262. self._kconfig.merge_in_entries(additional_config)
  263. print("-------- External configs are added ----------")
  264. def update_config(self, build_dir, make_options):
  265. kconfig_path = get_kconfig_path(build_dir)
  266. if build_dir and not os.path.exists(build_dir):
  267. os.mkdir(build_dir)
  268. try:
  269. self._kconfig.write_to_file(kconfig_path)
  270. self._ops.make_olddefconfig(build_dir, make_options)
  271. except ConfigError as e:
  272. logging.error(e)
  273. return False
  274. validated_kconfig = kunit_config.parse_file(kconfig_path)
  275. if self._kconfig.is_subset_of(validated_kconfig):
  276. return True
  277. missing = set(self._kconfig.as_entries()) - set(validated_kconfig.as_entries())
  278. message = 'Not all Kconfig options selected in kunitconfig were in the generated .config.\n' \
  279. 'This is probably due to unsatisfied dependencies. Please double check dependencies of below configs.\n' \
  280. 'Missing: ' + ', '.join(str(e) for e in missing)
  281. logging.warning(message)
  282. self._kconfig.remove_entry(missing)
  283. return True
  284. def build_config(self, build_dir: str, make_options) -> bool:
  285. kconfig_path = get_kconfig_path(build_dir)
  286. if build_dir and not os.path.exists(build_dir):
  287. os.mkdir(build_dir)
  288. try:
  289. self._kconfig = self._ops.make_arch_config(self._kconfig)
  290. self._kconfig.write_to_file(kconfig_path)
  291. self._ops.make_olddefconfig(build_dir, make_options)
  292. except ConfigError as e:
  293. logging.error(e)
  294. return False
  295. if not self.validate_config(build_dir):
  296. return False
  297. old_path = get_old_kunitconfig_path(build_dir)
  298. if os.path.exists(old_path):
  299. os.remove(old_path) # write_to_file appends to the file
  300. self._kconfig.write_to_file(old_path)
  301. return True
  302. def _kunitconfig_changed(self, build_dir: str) -> bool:
  303. old_path = get_old_kunitconfig_path(build_dir)
  304. if not os.path.exists(old_path):
  305. return True
  306. old_kconfig = kunit_config.parse_file(old_path)
  307. return old_kconfig != self._kconfig
  308. def build_reconfig(self, build_dir: str, make_options) -> bool:
  309. """Creates a new .config if it is not a subset of the .kunitconfig."""
  310. kconfig_path = get_kconfig_path(build_dir)
  311. if not os.path.exists(kconfig_path):
  312. print('Generating .config ...')
  313. return self.build_config(build_dir, make_options)
  314. existing_kconfig = kunit_config.parse_file(kconfig_path)
  315. self._kconfig = self._ops.make_arch_config(self._kconfig)
  316. if self._kconfig.is_subset_of(existing_kconfig) and not self._kunitconfig_changed(build_dir):
  317. return True
  318. print('Regenerating .config ...')
  319. os.remove(kconfig_path)
  320. return self.build_config(build_dir, make_options)
  321. def build_kernel(self, jobs, build_dir: str, make_options) -> bool:
  322. try:
  323. self._ops.make_olddefconfig(build_dir, make_options)
  324. self._ops.make(jobs, build_dir, make_options)
  325. except (ConfigError, BuildError) as e:
  326. logging.error(e)
  327. return False
  328. return self.validate_config(build_dir)
  329. def run_kernel(self, args=None, build_dir='', filter_glob='', timeout=None) -> Iterator[str]:
  330. if not args:
  331. args = []
  332. if filter_glob:
  333. args.append('kunit.filter_glob='+filter_glob)
  334. args.append('kunit.enable=1')
  335. process = self._ops.start(args, build_dir)
  336. assert process.stdout is not None # tell mypy it's set
  337. # Enforce the timeout in a background thread.
  338. def _wait_proc():
  339. try:
  340. process.wait(timeout=timeout)
  341. except Exception as e:
  342. print(e)
  343. process.terminate()
  344. process.wait()
  345. waiter = threading.Thread(target=_wait_proc)
  346. waiter.start()
  347. output = open(get_outfile_path(build_dir), 'w')
  348. try:
  349. # Tee the output to the file and to our caller in real time.
  350. for line in process.stdout:
  351. output.write(line)
  352. yield line
  353. # This runs even if our caller doesn't consume every line.
  354. finally:
  355. # Flush any leftover output to the file
  356. output.write(process.stdout.read())
  357. output.close()
  358. process.stdout.close()
  359. waiter.join()
  360. subprocess.call(['stty', 'sane'])
  361. def signal_handler(self, unused_sig, unused_frame) -> None:
  362. logging.error('Build interruption occurred. Cleaning console.')
  363. subprocess.call(['stty', 'sane'])