1// SPDX-License-Identifier: GPL-2.0
2/*
3 * builtin-test.c
4 *
5 * Builtin regression testing command: ever growing number of sanity tests
6 */
7#include <fcntl.h>
8#include <errno.h>
9#include <unistd.h>
10#include <string.h>
11#include <stdlib.h>
12#include <sys/types.h>
13#include <dirent.h>
14#include <sys/wait.h>
15#include <sys/stat.h>
16#include "builtin.h"
17#include "hist.h"
18#include "intlist.h"
19#include "tests.h"
20#include "debug.h"
21#include "color.h"
22#include <subcmd/parse-options.h>
23#include "string2.h"
24#include "symbol.h"
25#include "util/rlimit.h"
26#include <linux/kernel.h>
27#include <linux/string.h>
28#include <subcmd/exec-cmd.h>
29#include <linux/zalloc.h>
30
31#include "builtin-test-list.h"
32
33static bool dont_fork;
34const char *dso_to_test;
35
36/*
37 * List of architecture specific tests. Not a weak symbol as the array length is
38 * dependent on the initialization, as such GCC with LTO complains of
39 * conflicting definitions with a weak symbol.
40 */
41#if defined(__i386__) || defined(__x86_64__) || defined(__aarch64__) || defined(__powerpc64__)
42extern struct test_suite *arch_tests[];
43#else
44static struct test_suite *arch_tests[] = {
45	NULL,
46};
47#endif
48
49static struct test_suite *generic_tests[] = {
50	&suite__vmlinux_matches_kallsyms,
51#ifdef HAVE_LIBTRACEEVENT
52	&suite__openat_syscall_event,
53	&suite__openat_syscall_event_on_all_cpus,
54	&suite__basic_mmap,
55#endif
56	&suite__mem,
57	&suite__parse_events,
58	&suite__expr,
59	&suite__PERF_RECORD,
60	&suite__pmu,
61	&suite__pmu_events,
62	&suite__dso_data,
63	&suite__dso_data_cache,
64	&suite__dso_data_reopen,
65	&suite__perf_evsel__roundtrip_name_test,
66#ifdef HAVE_LIBTRACEEVENT
67	&suite__perf_evsel__tp_sched_test,
68	&suite__syscall_openat_tp_fields,
69#endif
70	&suite__attr,
71	&suite__hists_link,
72	&suite__python_use,
73	&suite__bp_signal,
74	&suite__bp_signal_overflow,
75	&suite__bp_accounting,
76	&suite__wp,
77	&suite__task_exit,
78	&suite__sw_clock_freq,
79	&suite__code_reading,
80	&suite__sample_parsing,
81	&suite__keep_tracking,
82	&suite__parse_no_sample_id_all,
83	&suite__hists_filter,
84	&suite__mmap_thread_lookup,
85	&suite__thread_maps_share,
86	&suite__hists_output,
87	&suite__hists_cumulate,
88#ifdef HAVE_LIBTRACEEVENT
89	&suite__switch_tracking,
90#endif
91	&suite__fdarray__filter,
92	&suite__fdarray__add,
93	&suite__kmod_path__parse,
94	&suite__thread_map,
95	&suite__session_topology,
96	&suite__thread_map_synthesize,
97	&suite__thread_map_remove,
98	&suite__cpu_map,
99	&suite__synthesize_stat_config,
100	&suite__synthesize_stat,
101	&suite__synthesize_stat_round,
102	&suite__event_update,
103	&suite__event_times,
104	&suite__backward_ring_buffer,
105	&suite__sdt_event,
106	&suite__is_printable_array,
107	&suite__bitmap_print,
108	&suite__perf_hooks,
109	&suite__unit_number__scnprint,
110	&suite__mem2node,
111	&suite__time_utils,
112	&suite__jit_write_elf,
113	&suite__pfm,
114	&suite__api_io,
115	&suite__maps__merge_in,
116	&suite__demangle_java,
117	&suite__demangle_ocaml,
118	&suite__parse_metric,
119	&suite__pe_file_parsing,
120	&suite__expand_cgroup_events,
121	&suite__perf_time_to_tsc,
122	&suite__dlfilter,
123	&suite__sigtrap,
124	&suite__event_groups,
125	&suite__symbols,
126	NULL,
127};
128
129static struct test_suite **tests[] = {
130	generic_tests,
131	arch_tests,
132};
133
134static struct test_workload *workloads[] = {
135	&workload__noploop,
136	&workload__thloop,
137	&workload__leafloop,
138	&workload__sqrtloop,
139	&workload__brstack,
140	&workload__datasym,
141};
142
143static int num_subtests(const struct test_suite *t)
144{
145	int num;
146
147	if (!t->test_cases)
148		return 0;
149
150	num = 0;
151	while (t->test_cases[num].name)
152		num++;
153
154	return num;
155}
156
157static bool has_subtests(const struct test_suite *t)
158{
159	return num_subtests(t) > 1;
160}
161
162static const char *skip_reason(const struct test_suite *t, int subtest)
163{
164	if (!t->test_cases)
165		return NULL;
166
167	return t->test_cases[subtest >= 0 ? subtest : 0].skip_reason;
168}
169
170static const char *test_description(const struct test_suite *t, int subtest)
171{
172	if (t->test_cases && subtest >= 0)
173		return t->test_cases[subtest].desc;
174
175	return t->desc;
176}
177
178static test_fnptr test_function(const struct test_suite *t, int subtest)
179{
180	if (subtest <= 0)
181		return t->test_cases[0].run_case;
182
183	return t->test_cases[subtest].run_case;
184}
185
186static bool perf_test__matches(const char *desc, int curr, int argc, const char *argv[])
187{
188	int i;
189
190	if (argc == 0)
191		return true;
192
193	for (i = 0; i < argc; ++i) {
194		char *end;
195		long nr = strtoul(argv[i], &end, 10);
196
197		if (*end == '\0') {
198			if (nr == curr + 1)
199				return true;
200			continue;
201		}
202
203		if (strcasestr(desc, argv[i]))
204			return true;
205	}
206
207	return false;
208}
209
210static int run_test(struct test_suite *test, int subtest)
211{
212	int status, err = -1, child = dont_fork ? 0 : fork();
213	char sbuf[STRERR_BUFSIZE];
214
215	if (child < 0) {
216		pr_err("failed to fork test: %s\n",
217			str_error_r(errno, sbuf, sizeof(sbuf)));
218		return -1;
219	}
220
221	if (!child) {
222		if (!dont_fork) {
223			pr_debug("test child forked, pid %d\n", getpid());
224
225			if (verbose <= 0) {
226				int nullfd = open("/dev/null", O_WRONLY);
227
228				if (nullfd >= 0) {
229					close(STDERR_FILENO);
230					close(STDOUT_FILENO);
231
232					dup2(nullfd, STDOUT_FILENO);
233					dup2(STDOUT_FILENO, STDERR_FILENO);
234					close(nullfd);
235				}
236			} else {
237				signal(SIGSEGV, sighandler_dump_stack);
238				signal(SIGFPE, sighandler_dump_stack);
239			}
240		}
241
242		err = test_function(test, subtest)(test, subtest);
243		if (!dont_fork)
244			exit(err);
245	}
246
247	if (!dont_fork) {
248		wait(&status);
249
250		if (WIFEXITED(status)) {
251			err = (signed char)WEXITSTATUS(status);
252			pr_debug("test child finished with %d\n", err);
253		} else if (WIFSIGNALED(status)) {
254			err = -1;
255			pr_debug("test child interrupted\n");
256		}
257	}
258
259	return err;
260}
261
262#define for_each_test(j, k, t)			\
263	for (j = 0, k = 0; j < ARRAY_SIZE(tests); j++, k = 0)	\
264		while ((t = tests[j][k++]) != NULL)
265
266static int test_and_print(struct test_suite *t, int subtest)
267{
268	int err;
269
270	pr_debug("\n--- start ---\n");
271	err = run_test(t, subtest);
272	pr_debug("---- end ----\n");
273
274	if (!has_subtests(t))
275		pr_debug("%s:", t->desc);
276	else
277		pr_debug("%s subtest %d:", t->desc, subtest + 1);
278
279	switch (err) {
280	case TEST_OK:
281		pr_info(" Ok\n");
282		break;
283	case TEST_SKIP: {
284		const char *reason = skip_reason(t, subtest);
285
286		if (reason)
287			color_fprintf(stderr, PERF_COLOR_YELLOW, " Skip (%s)\n", reason);
288		else
289			color_fprintf(stderr, PERF_COLOR_YELLOW, " Skip\n");
290	}
291		break;
292	case TEST_FAIL:
293	default:
294		color_fprintf(stderr, PERF_COLOR_RED, " FAILED!\n");
295		break;
296	}
297
298	return err;
299}
300
301struct shell_test {
302	const char *dir;
303	const char *file;
304};
305
306static int shell_test__run(struct test_suite *test, int subdir __maybe_unused)
307{
308	int err;
309	char script[PATH_MAX];
310	struct shell_test *st = test->priv;
311
312	path__join(script, sizeof(script) - 3, st->dir, st->file);
313
314	if (verbose > 0)
315		strncat(script, " -v", sizeof(script) - strlen(script) - 1);
316
317	err = system(script);
318	if (!err)
319		return TEST_OK;
320
321	return WEXITSTATUS(err) == 2 ? TEST_SKIP : TEST_FAIL;
322}
323
324static int run_shell_tests(int argc, const char *argv[], int i, int width,
325				struct intlist *skiplist)
326{
327	struct shell_test st;
328	const struct script_file *files, *file;
329
330	files = list_script_files();
331	if (!files)
332		return 0;
333	for (file = files; file->dir; file++) {
334		int curr = i++;
335		struct test_case test_cases[] = {
336			{
337				.desc = file->desc,
338				.run_case = shell_test__run,
339			},
340			{ .name = NULL, }
341		};
342		struct test_suite test_suite = {
343			.desc = test_cases[0].desc,
344			.test_cases = test_cases,
345			.priv = &st,
346		};
347		st.dir = file->dir;
348
349		if (test_suite.desc == NULL ||
350		    !perf_test__matches(test_suite.desc, curr, argc, argv))
351			continue;
352
353		st.file = file->file;
354		pr_info("%3d: %-*s:", i, width, test_suite.desc);
355
356		if (intlist__find(skiplist, i)) {
357			color_fprintf(stderr, PERF_COLOR_YELLOW, " Skip (user override)\n");
358			continue;
359		}
360
361		test_and_print(&test_suite, 0);
362	}
363	return 0;
364}
365
366static int __cmd_test(int argc, const char *argv[], struct intlist *skiplist)
367{
368	struct test_suite *t;
369	unsigned int j, k;
370	int i = 0;
371	int width = list_script_max_width();
372
373	for_each_test(j, k, t) {
374		int len = strlen(test_description(t, -1));
375
376		if (width < len)
377			width = len;
378	}
379
380	for_each_test(j, k, t) {
381		int curr = i++;
382		int subi;
383
384		if (!perf_test__matches(test_description(t, -1), curr, argc, argv)) {
385			bool skip = true;
386			int subn;
387
388			subn = num_subtests(t);
389
390			for (subi = 0; subi < subn; subi++) {
391				if (perf_test__matches(test_description(t, subi),
392							curr, argc, argv))
393					skip = false;
394			}
395
396			if (skip)
397				continue;
398		}
399
400		pr_info("%3d: %-*s:", i, width, test_description(t, -1));
401
402		if (intlist__find(skiplist, i)) {
403			color_fprintf(stderr, PERF_COLOR_YELLOW, " Skip (user override)\n");
404			continue;
405		}
406
407		if (!has_subtests(t)) {
408			test_and_print(t, -1);
409		} else {
410			int subn = num_subtests(t);
411			/*
412			 * minus 2 to align with normal testcases.
413			 * For subtest we print additional '.x' in number.
414			 * for example:
415			 *
416			 * 35: Test LLVM searching and compiling                        :
417			 * 35.1: Basic BPF llvm compiling test                          : Ok
418			 */
419			int subw = width > 2 ? width - 2 : width;
420
421			if (subn <= 0) {
422				color_fprintf(stderr, PERF_COLOR_YELLOW,
423					      " Skip (not compiled in)\n");
424				continue;
425			}
426			pr_info("\n");
427
428			for (subi = 0; subi < subn; subi++) {
429				int len = strlen(test_description(t, subi));
430
431				if (subw < len)
432					subw = len;
433			}
434
435			for (subi = 0; subi < subn; subi++) {
436				if (!perf_test__matches(test_description(t, subi),
437							curr, argc, argv))
438					continue;
439
440				pr_info("%3d.%1d: %-*s:", i, subi + 1, subw,
441					test_description(t, subi));
442				test_and_print(t, subi);
443			}
444		}
445	}
446
447	return run_shell_tests(argc, argv, i, width, skiplist);
448}
449
450static int perf_test__list_shell(int argc, const char **argv, int i)
451{
452	const struct script_file *files, *file;
453
454	files = list_script_files();
455	if (!files)
456		return 0;
457	for (file = files; file->dir; file++) {
458		int curr = i++;
459		struct test_suite t = {
460			.desc = file->desc
461		};
462
463		if (!perf_test__matches(t.desc, curr, argc, argv))
464			continue;
465
466		pr_info("%3d: %s\n", i, t.desc);
467	}
468	return 0;
469}
470
471static int perf_test__list(int argc, const char **argv)
472{
473	unsigned int j, k;
474	struct test_suite *t;
475	int i = 0;
476
477	for_each_test(j, k, t) {
478		int curr = i++;
479
480		if (!perf_test__matches(test_description(t, -1), curr, argc, argv))
481			continue;
482
483		pr_info("%3d: %s\n", i, test_description(t, -1));
484
485		if (has_subtests(t)) {
486			int subn = num_subtests(t);
487			int subi;
488
489			for (subi = 0; subi < subn; subi++)
490				pr_info("%3d:%1d: %s\n", i, subi + 1,
491					test_description(t, subi));
492		}
493	}
494
495	perf_test__list_shell(argc, argv, i);
496
497	return 0;
498}
499
500static int run_workload(const char *work, int argc, const char **argv)
501{
502	unsigned int i = 0;
503	struct test_workload *twl;
504
505	for (i = 0; i < ARRAY_SIZE(workloads); i++) {
506		twl = workloads[i];
507		if (!strcmp(twl->name, work))
508			return twl->func(argc, argv);
509	}
510
511	pr_info("No workload found: %s\n", work);
512	return -1;
513}
514
515int cmd_test(int argc, const char **argv)
516{
517	const char *test_usage[] = {
518	"perf test [<options>] [{list <test-name-fragment>|[<test-name-fragments>|<test-numbers>]}]",
519	NULL,
520	};
521	const char *skip = NULL;
522	const char *workload = NULL;
523	const struct option test_options[] = {
524	OPT_STRING('s', "skip", &skip, "tests", "tests to skip"),
525	OPT_INCR('v', "verbose", &verbose,
526		    "be more verbose (show symbol address, etc)"),
527	OPT_BOOLEAN('F', "dont-fork", &dont_fork,
528		    "Do not fork for testcase"),
529	OPT_STRING('w', "workload", &workload, "work", "workload to run for testing"),
530	OPT_STRING(0, "dso", &dso_to_test, "dso", "dso to test"),
531	OPT_END()
532	};
533	const char * const test_subcommands[] = { "list", NULL };
534	struct intlist *skiplist = NULL;
535        int ret = hists__init();
536
537        if (ret < 0)
538                return ret;
539
540	/* Unbuffered output */
541	setvbuf(stdout, NULL, _IONBF, 0);
542
543	argc = parse_options_subcommand(argc, argv, test_options, test_subcommands, test_usage, 0);
544	if (argc >= 1 && !strcmp(argv[0], "list"))
545		return perf_test__list(argc - 1, argv + 1);
546
547	if (workload)
548		return run_workload(workload, argc, argv);
549
550	symbol_conf.priv_size = sizeof(int);
551	symbol_conf.try_vmlinux_path = true;
552
553	if (symbol__init(NULL) < 0)
554		return -1;
555
556	if (skip != NULL)
557		skiplist = intlist__new(skip);
558	/*
559	 * Tests that create BPF maps, for instance, need more than the 64K
560	 * default:
561	 */
562	rlimit__bump_memlock();
563
564	return __cmd_test(argc, argv, skiplist);
565}
566