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