xref: /openbmc/linux/tools/perf/tests/builtin-test.c (revision c76ec1cf25d5240ded2e17384101890ff46b8797)
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 static bool dont_fork;
32 
33 struct test_suite *__weak arch_tests[] = {
34 	NULL,
35 };
36 
37 static struct test_suite *generic_tests[] = {
38 	&suite__vmlinux_matches_kallsyms,
39 	&suite__openat_syscall_event,
40 	&suite__openat_syscall_event_on_all_cpus,
41 	&suite__basic_mmap,
42 	&suite__mem,
43 	&suite__parse_events,
44 	&suite__expr,
45 	&suite__PERF_RECORD,
46 	&suite__pmu,
47 	&suite__pmu_events,
48 	&suite__dso_data,
49 	&suite__dso_data_cache,
50 	&suite__dso_data_reopen,
51 	&suite__perf_evsel__roundtrip_name_test,
52 	&suite__perf_evsel__tp_sched_test,
53 	&suite__syscall_openat_tp_fields,
54 	&suite__attr,
55 	&suite__hists_link,
56 	&suite__python_use,
57 	&suite__bp_signal,
58 	&suite__bp_signal_overflow,
59 	&suite__bp_accounting,
60 	&suite__wp,
61 	&suite__task_exit,
62 	&suite__sw_clock_freq,
63 	&suite__code_reading,
64 	&suite__sample_parsing,
65 	&suite__keep_tracking,
66 	&suite__parse_no_sample_id_all,
67 	&suite__hists_filter,
68 	&suite__mmap_thread_lookup,
69 	&suite__thread_maps_share,
70 	&suite__hists_output,
71 	&suite__hists_cumulate,
72 	&suite__switch_tracking,
73 	&suite__fdarray__filter,
74 	&suite__fdarray__add,
75 	&suite__kmod_path__parse,
76 	&suite__thread_map,
77 	&suite__llvm,
78 	&suite__session_topology,
79 	&suite__bpf,
80 	&suite__thread_map_synthesize,
81 	&suite__thread_map_remove,
82 	&suite__cpu_map_synthesize,
83 	&suite__synthesize_stat_config,
84 	&suite__synthesize_stat,
85 	&suite__synthesize_stat_round,
86 	&suite__event_update,
87 	&suite__event_times,
88 	&suite__backward_ring_buffer,
89 	&suite__cpu_map_print,
90 	&suite__cpu_map_merge,
91 	&suite__sdt_event,
92 	&suite__is_printable_array,
93 	&suite__bitmap_print,
94 	&suite__perf_hooks,
95 	&suite__clang,
96 	&suite__unit_number__scnprint,
97 	&suite__mem2node,
98 	&suite__time_utils,
99 	&suite__jit_write_elf,
100 	&suite__pfm,
101 	&suite__api_io,
102 	&suite__maps__merge_in,
103 	&suite__demangle_java,
104 	&suite__demangle_ocaml,
105 	&suite__parse_metric,
106 	&suite__pe_file_parsing,
107 	&suite__expand_cgroup_events,
108 	&suite__perf_time_to_tsc,
109 	&suite__dlfilter,
110 	NULL,
111 };
112 
113 static struct test_suite **tests[] = {
114 	generic_tests,
115 	arch_tests,
116 };
117 
118 static int num_subtests(const struct test_suite *t)
119 {
120 	int num;
121 
122 	if (!t->test_cases)
123 		return 0;
124 
125 	num = 0;
126 	while (t->test_cases[num].name)
127 		num++;
128 
129 	return num;
130 }
131 
132 static bool has_subtests(const struct test_suite *t)
133 {
134 	return num_subtests(t) > 1;
135 }
136 
137 static const char *skip_reason(const struct test_suite *t, int subtest)
138 {
139 	if (t->test_cases && subtest >= 0)
140 		return t->test_cases[subtest].skip_reason;
141 
142 	return NULL;
143 }
144 
145 static const char *test_description(const struct test_suite *t, int subtest)
146 {
147 	if (t->test_cases && subtest >= 0)
148 		return t->test_cases[subtest].desc;
149 
150 	return t->desc;
151 }
152 
153 static bool is_supported(const struct test_suite *t)
154 {
155 	return !t->is_supported || t->is_supported();
156 }
157 
158 static test_fnptr test_function(const struct test_suite *t, int subtest)
159 {
160 	if (subtest <= 0)
161 		return t->test_cases[0].run_case;
162 
163 	return t->test_cases[subtest].run_case;
164 }
165 
166 static bool perf_test__matches(const char *desc, int curr, int argc, const char *argv[])
167 {
168 	int i;
169 
170 	if (argc == 0)
171 		return true;
172 
173 	for (i = 0; i < argc; ++i) {
174 		char *end;
175 		long nr = strtoul(argv[i], &end, 10);
176 
177 		if (*end == '\0') {
178 			if (nr == curr + 1)
179 				return true;
180 			continue;
181 		}
182 
183 		if (strcasestr(desc, argv[i]))
184 			return true;
185 	}
186 
187 	return false;
188 }
189 
190 static int run_test(struct test_suite *test, int subtest)
191 {
192 	int status, err = -1, child = dont_fork ? 0 : fork();
193 	char sbuf[STRERR_BUFSIZE];
194 
195 	if (child < 0) {
196 		pr_err("failed to fork test: %s\n",
197 			str_error_r(errno, sbuf, sizeof(sbuf)));
198 		return -1;
199 	}
200 
201 	if (!child) {
202 		if (!dont_fork) {
203 			pr_debug("test child forked, pid %d\n", getpid());
204 
205 			if (verbose <= 0) {
206 				int nullfd = open("/dev/null", O_WRONLY);
207 
208 				if (nullfd >= 0) {
209 					close(STDERR_FILENO);
210 					close(STDOUT_FILENO);
211 
212 					dup2(nullfd, STDOUT_FILENO);
213 					dup2(STDOUT_FILENO, STDERR_FILENO);
214 					close(nullfd);
215 				}
216 			} else {
217 				signal(SIGSEGV, sighandler_dump_stack);
218 				signal(SIGFPE, sighandler_dump_stack);
219 			}
220 		}
221 
222 		err = test_function(test, subtest)(test, subtest);
223 		if (!dont_fork)
224 			exit(err);
225 	}
226 
227 	if (!dont_fork) {
228 		wait(&status);
229 
230 		if (WIFEXITED(status)) {
231 			err = (signed char)WEXITSTATUS(status);
232 			pr_debug("test child finished with %d\n", err);
233 		} else if (WIFSIGNALED(status)) {
234 			err = -1;
235 			pr_debug("test child interrupted\n");
236 		}
237 	}
238 
239 	return err;
240 }
241 
242 #define for_each_test(j, k, t)			\
243 	for (j = 0; j < ARRAY_SIZE(tests); j++)	\
244 		for (k = 0, t = tests[j][k]; tests[j][k]; k++, t = tests[j][k])
245 
246 static int test_and_print(struct test_suite *t, bool force_skip, int subtest)
247 {
248 	int err;
249 
250 	if (!force_skip) {
251 		pr_debug("\n--- start ---\n");
252 		err = run_test(t, subtest);
253 		pr_debug("---- end ----\n");
254 	} else {
255 		pr_debug("\n--- force skipped ---\n");
256 		err = TEST_SKIP;
257 	}
258 
259 	if (!has_subtests(t))
260 		pr_debug("%s:", t->desc);
261 	else
262 		pr_debug("%s subtest %d:", t->desc, subtest + 1);
263 
264 	switch (err) {
265 	case TEST_OK:
266 		pr_info(" Ok\n");
267 		break;
268 	case TEST_SKIP: {
269 		const char *reason = skip_reason(t, subtest);
270 
271 		if (reason)
272 			color_fprintf(stderr, PERF_COLOR_YELLOW, " Skip (%s)\n", reason);
273 		else
274 			color_fprintf(stderr, PERF_COLOR_YELLOW, " Skip\n");
275 	}
276 		break;
277 	case TEST_FAIL:
278 	default:
279 		color_fprintf(stderr, PERF_COLOR_RED, " FAILED!\n");
280 		break;
281 	}
282 
283 	return err;
284 }
285 
286 static const char *shell_test__description(char *description, size_t size,
287 					   const char *path, const char *name)
288 {
289 	FILE *fp;
290 	char filename[PATH_MAX];
291 
292 	path__join(filename, sizeof(filename), path, name);
293 	fp = fopen(filename, "r");
294 	if (!fp)
295 		return NULL;
296 
297 	/* Skip shebang */
298 	while (fgetc(fp) != '\n');
299 
300 	description = fgets(description, size, fp);
301 	fclose(fp);
302 
303 	return description ? strim(description + 1) : NULL;
304 }
305 
306 #define for_each_shell_test(entlist, nr, base, ent)	                \
307 	for (int __i = 0; __i < nr && (ent = entlist[__i]); __i++)	\
308 		if (!is_directory(base, ent) && ent->d_name[0] != '.')
309 
310 static const char *shell_tests__dir(char *path, size_t size)
311 {
312 	const char *devel_dirs[] = { "./tools/perf/tests", "./tests", };
313         char *exec_path;
314 	unsigned int i;
315 
316 	for (i = 0; i < ARRAY_SIZE(devel_dirs); ++i) {
317 		struct stat st;
318 		if (!lstat(devel_dirs[i], &st)) {
319 			scnprintf(path, size, "%s/shell", devel_dirs[i]);
320 			if (!lstat(devel_dirs[i], &st))
321 				return path;
322 		}
323 	}
324 
325         /* Then installed path. */
326         exec_path = get_argv_exec_path();
327         scnprintf(path, size, "%s/tests/shell", exec_path);
328 	free(exec_path);
329 	return path;
330 }
331 
332 static int shell_tests__max_desc_width(void)
333 {
334 	struct dirent **entlist;
335 	struct dirent *ent;
336 	int n_dirs, e;
337 	char path_dir[PATH_MAX];
338 	const char *path = shell_tests__dir(path_dir, sizeof(path_dir));
339 	int width = 0;
340 
341 	if (path == NULL)
342 		return -1;
343 
344 	n_dirs = scandir(path, &entlist, NULL, alphasort);
345 	if (n_dirs == -1)
346 		return -1;
347 
348 	for_each_shell_test(entlist, n_dirs, path, ent) {
349 		char bf[256];
350 		const char *desc = shell_test__description(bf, sizeof(bf), path, ent->d_name);
351 
352 		if (desc) {
353 			int len = strlen(desc);
354 
355 			if (width < len)
356 				width = len;
357 		}
358 	}
359 
360 	for (e = 0; e < n_dirs; e++)
361 		zfree(&entlist[e]);
362 	free(entlist);
363 	return width;
364 }
365 
366 struct shell_test {
367 	const char *dir;
368 	const char *file;
369 };
370 
371 static int shell_test__run(struct test_suite *test, int subdir __maybe_unused)
372 {
373 	int err;
374 	char script[PATH_MAX];
375 	struct shell_test *st = test->priv;
376 
377 	path__join(script, sizeof(script) - 3, st->dir, st->file);
378 
379 	if (verbose)
380 		strncat(script, " -v", sizeof(script) - strlen(script) - 1);
381 
382 	err = system(script);
383 	if (!err)
384 		return TEST_OK;
385 
386 	return WEXITSTATUS(err) == 2 ? TEST_SKIP : TEST_FAIL;
387 }
388 
389 static int run_shell_tests(int argc, const char *argv[], int i, int width,
390 				struct intlist *skiplist)
391 {
392 	struct dirent **entlist;
393 	struct dirent *ent;
394 	int n_dirs, e;
395 	char path_dir[PATH_MAX];
396 	struct shell_test st = {
397 		.dir = shell_tests__dir(path_dir, sizeof(path_dir)),
398 	};
399 
400 	if (st.dir == NULL)
401 		return -1;
402 
403 	n_dirs = scandir(st.dir, &entlist, NULL, alphasort);
404 	if (n_dirs == -1) {
405 		pr_err("failed to open shell test directory: %s\n",
406 			st.dir);
407 		return -1;
408 	}
409 
410 	for_each_shell_test(entlist, n_dirs, st.dir, ent) {
411 		int curr = i++;
412 		char desc[256];
413 		struct test_case test_cases[] = {
414 			{
415 				.desc = shell_test__description(desc,
416 								sizeof(desc),
417 								st.dir,
418 								ent->d_name),
419 				.run_case = shell_test__run,
420 			},
421 			{ .name = NULL, }
422 		};
423 		struct test_suite test_suite = {
424 			.desc = test_cases[0].desc,
425 			.test_cases = test_cases,
426 			.priv = &st,
427 		};
428 
429 		if (!perf_test__matches(test_suite.desc, curr, argc, argv))
430 			continue;
431 
432 		st.file = ent->d_name;
433 		pr_info("%2d: %-*s:", i, width, test_suite.desc);
434 
435 		if (intlist__find(skiplist, i)) {
436 			color_fprintf(stderr, PERF_COLOR_YELLOW, " Skip (user override)\n");
437 			continue;
438 		}
439 
440 		test_and_print(&test_suite, false, 0);
441 	}
442 
443 	for (e = 0; e < n_dirs; e++)
444 		zfree(&entlist[e]);
445 	free(entlist);
446 	return 0;
447 }
448 
449 static int __cmd_test(int argc, const char *argv[], struct intlist *skiplist)
450 {
451 	struct test_suite *t;
452 	unsigned int j, k;
453 	int i = 0;
454 	int width = shell_tests__max_desc_width();
455 
456 	for_each_test(j, k, t) {
457 		int len = strlen(test_description(t, -1));
458 
459 		if (width < len)
460 			width = len;
461 	}
462 
463 	for_each_test(j, k, t) {
464 		int curr = i++, err;
465 		int subi;
466 
467 		if (!perf_test__matches(test_description(t, -1), curr, argc, argv)) {
468 			bool skip = true;
469 			int subn;
470 
471 			subn = num_subtests(t);
472 
473 			for (subi = 0; subi < subn; subi++) {
474 				if (perf_test__matches(test_description(t, subi),
475 							curr, argc, argv))
476 					skip = false;
477 			}
478 
479 			if (skip)
480 				continue;
481 		}
482 
483 		if (!is_supported(t)) {
484 			pr_debug("%2d: %-*s: Disabled\n", i, width,
485 				 test_description(t, -1));
486 			continue;
487 		}
488 
489 		pr_info("%2d: %-*s:", i, width, test_description(t, -1));
490 
491 		if (intlist__find(skiplist, i)) {
492 			color_fprintf(stderr, PERF_COLOR_YELLOW, " Skip (user override)\n");
493 			continue;
494 		}
495 
496 		if (!has_subtests(t)) {
497 			test_and_print(t, false, -1);
498 		} else {
499 			int subn = num_subtests(t);
500 			/*
501 			 * minus 2 to align with normal testcases.
502 			 * For subtest we print additional '.x' in number.
503 			 * for example:
504 			 *
505 			 * 35: Test LLVM searching and compiling                        :
506 			 * 35.1: Basic BPF llvm compiling test                          : Ok
507 			 */
508 			int subw = width > 2 ? width - 2 : width;
509 			bool skip = false;
510 
511 			if (subn <= 0) {
512 				color_fprintf(stderr, PERF_COLOR_YELLOW,
513 					      " Skip (not compiled in)\n");
514 				continue;
515 			}
516 			pr_info("\n");
517 
518 			for (subi = 0; subi < subn; subi++) {
519 				int len = strlen(test_description(t, subi));
520 
521 				if (subw < len)
522 					subw = len;
523 			}
524 
525 			for (subi = 0; subi < subn; subi++) {
526 				if (!perf_test__matches(test_description(t, subi),
527 							curr, argc, argv))
528 					continue;
529 
530 				pr_info("%2d.%1d: %-*s:", i, subi + 1, subw,
531 					test_description(t, subi));
532 				err = test_and_print(t, skip, subi);
533 				if (err != TEST_OK && t->subtest.skip_if_fail)
534 					skip = true;
535 			}
536 		}
537 	}
538 
539 	return run_shell_tests(argc, argv, i, width, skiplist);
540 }
541 
542 static int perf_test__list_shell(int argc, const char **argv, int i)
543 {
544 	struct dirent **entlist;
545 	struct dirent *ent;
546 	int n_dirs, e;
547 	char path_dir[PATH_MAX];
548 	const char *path = shell_tests__dir(path_dir, sizeof(path_dir));
549 
550 	if (path == NULL)
551 		return -1;
552 
553 	n_dirs = scandir(path, &entlist, NULL, alphasort);
554 	if (n_dirs == -1)
555 		return -1;
556 
557 	for_each_shell_test(entlist, n_dirs, path, ent) {
558 		int curr = i++;
559 		char bf[256];
560 		struct test_suite t = {
561 			.desc = shell_test__description(bf, sizeof(bf), path, ent->d_name),
562 		};
563 
564 		if (!perf_test__matches(t.desc, curr, argc, argv))
565 			continue;
566 
567 		pr_info("%2d: %s\n", i, t.desc);
568 
569 	}
570 
571 	for (e = 0; e < n_dirs; e++)
572 		zfree(&entlist[e]);
573 	free(entlist);
574 	return 0;
575 }
576 
577 static int perf_test__list(int argc, const char **argv)
578 {
579 	unsigned int j, k;
580 	struct test_suite *t;
581 	int i = 0;
582 
583 	for_each_test(j, k, t) {
584 		int curr = i++;
585 
586 		if (!perf_test__matches(test_description(t, -1), curr, argc, argv) ||
587 		    !is_supported(t))
588 			continue;
589 
590 		pr_info("%2d: %s\n", i, test_description(t, -1));
591 
592 		if (has_subtests(t)) {
593 			int subn = num_subtests(t);
594 			int subi;
595 
596 			for (subi = 0; subi < subn; subi++)
597 				pr_info("%2d:%1d: %s\n", i, subi + 1,
598 					test_description(t, subi));
599 		}
600 	}
601 
602 	perf_test__list_shell(argc, argv, i);
603 
604 	return 0;
605 }
606 
607 int cmd_test(int argc, const char **argv)
608 {
609 	const char *test_usage[] = {
610 	"perf test [<options>] [{list <test-name-fragment>|[<test-name-fragments>|<test-numbers>]}]",
611 	NULL,
612 	};
613 	const char *skip = NULL;
614 	const struct option test_options[] = {
615 	OPT_STRING('s', "skip", &skip, "tests", "tests to skip"),
616 	OPT_INCR('v', "verbose", &verbose,
617 		    "be more verbose (show symbol address, etc)"),
618 	OPT_BOOLEAN('F', "dont-fork", &dont_fork,
619 		    "Do not fork for testcase"),
620 	OPT_END()
621 	};
622 	const char * const test_subcommands[] = { "list", NULL };
623 	struct intlist *skiplist = NULL;
624         int ret = hists__init();
625 
626         if (ret < 0)
627                 return ret;
628 
629 	argc = parse_options_subcommand(argc, argv, test_options, test_subcommands, test_usage, 0);
630 	if (argc >= 1 && !strcmp(argv[0], "list"))
631 		return perf_test__list(argc - 1, argv + 1);
632 
633 	symbol_conf.priv_size = sizeof(int);
634 	symbol_conf.sort_by_name = true;
635 	symbol_conf.try_vmlinux_path = true;
636 
637 	if (symbol__init(NULL) < 0)
638 		return -1;
639 
640 	if (skip != NULL)
641 		skiplist = intlist__new(skip);
642 	/*
643 	 * Tests that create BPF maps, for instance, need more than the 64K
644 	 * default:
645 	 */
646 	rlimit__bump_memlock();
647 
648 	return __cmd_test(argc, argv, skiplist);
649 }
650