1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2017 Facebook
3  */
4 #define _GNU_SOURCE
5 #include "test_progs.h"
6 #include "cgroup_helpers.h"
7 #include "bpf_rlimit.h"
8 #include <argp.h>
9 #include <pthread.h>
10 #include <sched.h>
11 #include <signal.h>
12 #include <string.h>
13 #include <execinfo.h> /* backtrace */
14 
15 /* defined in test_progs.h */
16 struct test_env env = {};
17 
18 struct prog_test_def {
19 	const char *test_name;
20 	int test_num;
21 	void (*run_test)(void);
22 	bool force_log;
23 	int error_cnt;
24 	int skip_cnt;
25 	bool tested;
26 	bool need_cgroup_cleanup;
27 
28 	char *subtest_name;
29 	int subtest_num;
30 
31 	/* store counts before subtest started */
32 	int old_error_cnt;
33 };
34 
35 /* Override C runtime library's usleep() implementation to ensure nanosleep()
36  * is always called. Usleep is frequently used in selftests as a way to
37  * trigger kprobe and tracepoints.
38  */
39 int usleep(useconds_t usec)
40 {
41 	struct timespec ts = {
42 		.tv_sec = usec / 1000000,
43 		.tv_nsec = (usec % 1000000) * 1000,
44 	};
45 
46 	return syscall(__NR_nanosleep, &ts, NULL);
47 }
48 
49 static bool should_run(struct test_selector *sel, int num, const char *name)
50 {
51 	int i;
52 
53 	for (i = 0; i < sel->blacklist.cnt; i++) {
54 		if (strstr(name, sel->blacklist.strs[i]))
55 			return false;
56 	}
57 
58 	for (i = 0; i < sel->whitelist.cnt; i++) {
59 		if (strstr(name, sel->whitelist.strs[i]))
60 			return true;
61 	}
62 
63 	if (!sel->whitelist.cnt && !sel->num_set)
64 		return true;
65 
66 	return num < sel->num_set_len && sel->num_set[num];
67 }
68 
69 static void dump_test_log(const struct prog_test_def *test, bool failed)
70 {
71 	if (stdout == env.stdout)
72 		return;
73 
74 	fflush(stdout); /* exports env.log_buf & env.log_cnt */
75 
76 	if (env.verbosity > VERBOSE_NONE || test->force_log || failed) {
77 		if (env.log_cnt) {
78 			env.log_buf[env.log_cnt] = '\0';
79 			fprintf(env.stdout, "%s", env.log_buf);
80 			if (env.log_buf[env.log_cnt - 1] != '\n')
81 				fprintf(env.stdout, "\n");
82 		}
83 	}
84 
85 	fseeko(stdout, 0, SEEK_SET); /* rewind */
86 }
87 
88 static void skip_account(void)
89 {
90 	if (env.test->skip_cnt) {
91 		env.skip_cnt++;
92 		env.test->skip_cnt = 0;
93 	}
94 }
95 
96 static void stdio_restore(void);
97 
98 /* A bunch of tests set custom affinity per-thread and/or per-process. Reset
99  * it after each test/sub-test.
100  */
101 static void reset_affinity() {
102 
103 	cpu_set_t cpuset;
104 	int i, err;
105 
106 	CPU_ZERO(&cpuset);
107 	for (i = 0; i < env.nr_cpus; i++)
108 		CPU_SET(i, &cpuset);
109 
110 	err = sched_setaffinity(0, sizeof(cpuset), &cpuset);
111 	if (err < 0) {
112 		stdio_restore();
113 		fprintf(stderr, "Failed to reset process affinity: %d!\n", err);
114 		exit(-1);
115 	}
116 	err = pthread_setaffinity_np(pthread_self(), sizeof(cpuset), &cpuset);
117 	if (err < 0) {
118 		stdio_restore();
119 		fprintf(stderr, "Failed to reset thread affinity: %d!\n", err);
120 		exit(-1);
121 	}
122 }
123 
124 void test__end_subtest()
125 {
126 	struct prog_test_def *test = env.test;
127 	int sub_error_cnt = test->error_cnt - test->old_error_cnt;
128 
129 	if (sub_error_cnt)
130 		env.fail_cnt++;
131 	else
132 		env.sub_succ_cnt++;
133 	skip_account();
134 
135 	dump_test_log(test, sub_error_cnt);
136 
137 	fprintf(env.stdout, "#%d/%d %s:%s\n",
138 	       test->test_num, test->subtest_num,
139 	       test->subtest_name, sub_error_cnt ? "FAIL" : "OK");
140 
141 	reset_affinity();
142 
143 	free(test->subtest_name);
144 	test->subtest_name = NULL;
145 }
146 
147 bool test__start_subtest(const char *name)
148 {
149 	struct prog_test_def *test = env.test;
150 
151 	if (test->subtest_name)
152 		test__end_subtest();
153 
154 	test->subtest_num++;
155 
156 	if (!name || !name[0]) {
157 		fprintf(env.stderr,
158 			"Subtest #%d didn't provide sub-test name!\n",
159 			test->subtest_num);
160 		return false;
161 	}
162 
163 	if (!should_run(&env.subtest_selector, test->subtest_num, name))
164 		return false;
165 
166 	test->subtest_name = strdup(name);
167 	if (!test->subtest_name) {
168 		fprintf(env.stderr,
169 			"Subtest #%d: failed to copy subtest name!\n",
170 			test->subtest_num);
171 		return false;
172 	}
173 	env.test->old_error_cnt = env.test->error_cnt;
174 
175 	return true;
176 }
177 
178 void test__force_log() {
179 	env.test->force_log = true;
180 }
181 
182 void test__skip(void)
183 {
184 	env.test->skip_cnt++;
185 }
186 
187 void test__fail(void)
188 {
189 	env.test->error_cnt++;
190 }
191 
192 int test__join_cgroup(const char *path)
193 {
194 	int fd;
195 
196 	if (!env.test->need_cgroup_cleanup) {
197 		if (setup_cgroup_environment()) {
198 			fprintf(stderr,
199 				"#%d %s: Failed to setup cgroup environment\n",
200 				env.test->test_num, env.test->test_name);
201 			return -1;
202 		}
203 
204 		env.test->need_cgroup_cleanup = true;
205 	}
206 
207 	fd = create_and_get_cgroup(path);
208 	if (fd < 0) {
209 		fprintf(stderr,
210 			"#%d %s: Failed to create cgroup '%s' (errno=%d)\n",
211 			env.test->test_num, env.test->test_name, path, errno);
212 		return fd;
213 	}
214 
215 	if (join_cgroup(path)) {
216 		fprintf(stderr,
217 			"#%d %s: Failed to join cgroup '%s' (errno=%d)\n",
218 			env.test->test_num, env.test->test_name, path, errno);
219 		return -1;
220 	}
221 
222 	return fd;
223 }
224 
225 struct ipv4_packet pkt_v4 = {
226 	.eth.h_proto = __bpf_constant_htons(ETH_P_IP),
227 	.iph.ihl = 5,
228 	.iph.protocol = IPPROTO_TCP,
229 	.iph.tot_len = __bpf_constant_htons(MAGIC_BYTES),
230 	.tcp.urg_ptr = 123,
231 	.tcp.doff = 5,
232 };
233 
234 struct ipv6_packet pkt_v6 = {
235 	.eth.h_proto = __bpf_constant_htons(ETH_P_IPV6),
236 	.iph.nexthdr = IPPROTO_TCP,
237 	.iph.payload_len = __bpf_constant_htons(MAGIC_BYTES),
238 	.tcp.urg_ptr = 123,
239 	.tcp.doff = 5,
240 };
241 
242 int bpf_find_map(const char *test, struct bpf_object *obj, const char *name)
243 {
244 	struct bpf_map *map;
245 
246 	map = bpf_object__find_map_by_name(obj, name);
247 	if (!map) {
248 		fprintf(stdout, "%s:FAIL:map '%s' not found\n", test, name);
249 		test__fail();
250 		return -1;
251 	}
252 	return bpf_map__fd(map);
253 }
254 
255 static bool is_jit_enabled(void)
256 {
257 	const char *jit_sysctl = "/proc/sys/net/core/bpf_jit_enable";
258 	bool enabled = false;
259 	int sysctl_fd;
260 
261 	sysctl_fd = open(jit_sysctl, 0, O_RDONLY);
262 	if (sysctl_fd != -1) {
263 		char tmpc;
264 
265 		if (read(sysctl_fd, &tmpc, sizeof(tmpc)) == 1)
266 			enabled = (tmpc != '0');
267 		close(sysctl_fd);
268 	}
269 
270 	return enabled;
271 }
272 
273 int compare_map_keys(int map1_fd, int map2_fd)
274 {
275 	__u32 key, next_key;
276 	char val_buf[PERF_MAX_STACK_DEPTH *
277 		     sizeof(struct bpf_stack_build_id)];
278 	int err;
279 
280 	err = bpf_map_get_next_key(map1_fd, NULL, &key);
281 	if (err)
282 		return err;
283 	err = bpf_map_lookup_elem(map2_fd, &key, val_buf);
284 	if (err)
285 		return err;
286 
287 	while (bpf_map_get_next_key(map1_fd, &key, &next_key) == 0) {
288 		err = bpf_map_lookup_elem(map2_fd, &next_key, val_buf);
289 		if (err)
290 			return err;
291 
292 		key = next_key;
293 	}
294 	if (errno != ENOENT)
295 		return -1;
296 
297 	return 0;
298 }
299 
300 int compare_stack_ips(int smap_fd, int amap_fd, int stack_trace_len)
301 {
302 	__u32 key, next_key, *cur_key_p, *next_key_p;
303 	char *val_buf1, *val_buf2;
304 	int i, err = 0;
305 
306 	val_buf1 = malloc(stack_trace_len);
307 	val_buf2 = malloc(stack_trace_len);
308 	cur_key_p = NULL;
309 	next_key_p = &key;
310 	while (bpf_map_get_next_key(smap_fd, cur_key_p, next_key_p) == 0) {
311 		err = bpf_map_lookup_elem(smap_fd, next_key_p, val_buf1);
312 		if (err)
313 			goto out;
314 		err = bpf_map_lookup_elem(amap_fd, next_key_p, val_buf2);
315 		if (err)
316 			goto out;
317 		for (i = 0; i < stack_trace_len; i++) {
318 			if (val_buf1[i] != val_buf2[i]) {
319 				err = -1;
320 				goto out;
321 			}
322 		}
323 		key = *next_key_p;
324 		cur_key_p = &key;
325 		next_key_p = &next_key;
326 	}
327 	if (errno != ENOENT)
328 		err = -1;
329 
330 out:
331 	free(val_buf1);
332 	free(val_buf2);
333 	return err;
334 }
335 
336 int extract_build_id(char *build_id, size_t size)
337 {
338 	FILE *fp;
339 	char *line = NULL;
340 	size_t len = 0;
341 
342 	fp = popen("readelf -n ./urandom_read | grep 'Build ID'", "r");
343 	if (fp == NULL)
344 		return -1;
345 
346 	if (getline(&line, &len, fp) == -1)
347 		goto err;
348 	fclose(fp);
349 
350 	if (len > size)
351 		len = size;
352 	memcpy(build_id, line, len);
353 	build_id[len] = '\0';
354 	return 0;
355 err:
356 	fclose(fp);
357 	return -1;
358 }
359 
360 void *spin_lock_thread(void *arg)
361 {
362 	__u32 duration, retval;
363 	int err, prog_fd = *(u32 *) arg;
364 
365 	err = bpf_prog_test_run(prog_fd, 10000, &pkt_v4, sizeof(pkt_v4),
366 				NULL, NULL, &retval, &duration);
367 	CHECK(err || retval, "",
368 	      "err %d errno %d retval %d duration %d\n",
369 	      err, errno, retval, duration);
370 	pthread_exit(arg);
371 }
372 
373 /* extern declarations for test funcs */
374 #define DEFINE_TEST(name) extern void test_##name(void);
375 #include <prog_tests/tests.h>
376 #undef DEFINE_TEST
377 
378 static struct prog_test_def prog_test_defs[] = {
379 #define DEFINE_TEST(name) {		\
380 	.test_name = #name,		\
381 	.run_test = &test_##name,	\
382 },
383 #include <prog_tests/tests.h>
384 #undef DEFINE_TEST
385 };
386 const int prog_test_cnt = ARRAY_SIZE(prog_test_defs);
387 
388 const char *argp_program_version = "test_progs 0.1";
389 const char *argp_program_bug_address = "<bpf@vger.kernel.org>";
390 const char argp_program_doc[] = "BPF selftests test runner";
391 
392 enum ARG_KEYS {
393 	ARG_TEST_NUM = 'n',
394 	ARG_TEST_NAME = 't',
395 	ARG_TEST_NAME_BLACKLIST = 'b',
396 	ARG_VERIFIER_STATS = 's',
397 	ARG_VERBOSE = 'v',
398 };
399 
400 static const struct argp_option opts[] = {
401 	{ "num", ARG_TEST_NUM, "NUM", 0,
402 	  "Run test number NUM only " },
403 	{ "name", ARG_TEST_NAME, "NAMES", 0,
404 	  "Run tests with names containing any string from NAMES list" },
405 	{ "name-blacklist", ARG_TEST_NAME_BLACKLIST, "NAMES", 0,
406 	  "Don't run tests with names containing any string from NAMES list" },
407 	{ "verifier-stats", ARG_VERIFIER_STATS, NULL, 0,
408 	  "Output verifier statistics", },
409 	{ "verbose", ARG_VERBOSE, "LEVEL", OPTION_ARG_OPTIONAL,
410 	  "Verbose output (use -vv or -vvv for progressively verbose output)" },
411 	{},
412 };
413 
414 static int libbpf_print_fn(enum libbpf_print_level level,
415 			   const char *format, va_list args)
416 {
417 	if (env.verbosity < VERBOSE_VERY && level == LIBBPF_DEBUG)
418 		return 0;
419 	vfprintf(stdout, format, args);
420 	return 0;
421 }
422 
423 static int parse_str_list(const char *s, struct str_set *set)
424 {
425 	char *input, *state = NULL, *next, **tmp, **strs = NULL;
426 	int cnt = 0;
427 
428 	input = strdup(s);
429 	if (!input)
430 		return -ENOMEM;
431 
432 	set->cnt = 0;
433 	set->strs = NULL;
434 
435 	while ((next = strtok_r(state ? NULL : input, ",", &state))) {
436 		tmp = realloc(strs, sizeof(*strs) * (cnt + 1));
437 		if (!tmp)
438 			goto err;
439 		strs = tmp;
440 
441 		strs[cnt] = strdup(next);
442 		if (!strs[cnt])
443 			goto err;
444 
445 		cnt++;
446 	}
447 
448 	set->cnt = cnt;
449 	set->strs = (const char **)strs;
450 	free(input);
451 	return 0;
452 err:
453 	free(strs);
454 	free(input);
455 	return -ENOMEM;
456 }
457 
458 int parse_num_list(const char *s, struct test_selector *sel)
459 {
460 	int i, set_len = 0, new_len, num, start = 0, end = -1;
461 	bool *set = NULL, *tmp, parsing_end = false;
462 	char *next;
463 
464 	while (s[0]) {
465 		errno = 0;
466 		num = strtol(s, &next, 10);
467 		if (errno)
468 			return -errno;
469 
470 		if (parsing_end)
471 			end = num;
472 		else
473 			start = num;
474 
475 		if (!parsing_end && *next == '-') {
476 			s = next + 1;
477 			parsing_end = true;
478 			continue;
479 		} else if (*next == ',') {
480 			parsing_end = false;
481 			s = next + 1;
482 			end = num;
483 		} else if (*next == '\0') {
484 			parsing_end = false;
485 			s = next;
486 			end = num;
487 		} else {
488 			return -EINVAL;
489 		}
490 
491 		if (start > end)
492 			return -EINVAL;
493 
494 		if (end + 1 > set_len) {
495 			new_len = end + 1;
496 			tmp = realloc(set, new_len);
497 			if (!tmp) {
498 				free(set);
499 				return -ENOMEM;
500 			}
501 			for (i = set_len; i < start; i++)
502 				tmp[i] = false;
503 			set = tmp;
504 			set_len = new_len;
505 		}
506 		for (i = start; i <= end; i++)
507 			set[i] = true;
508 	}
509 
510 	if (!set)
511 		return -EINVAL;
512 
513 	sel->num_set = set;
514 	sel->num_set_len = set_len;
515 
516 	return 0;
517 }
518 
519 extern int extra_prog_load_log_flags;
520 
521 static error_t parse_arg(int key, char *arg, struct argp_state *state)
522 {
523 	struct test_env *env = state->input;
524 
525 	switch (key) {
526 	case ARG_TEST_NUM: {
527 		char *subtest_str = strchr(arg, '/');
528 
529 		if (subtest_str) {
530 			*subtest_str = '\0';
531 			if (parse_num_list(subtest_str + 1,
532 					   &env->subtest_selector)) {
533 				fprintf(stderr,
534 					"Failed to parse subtest numbers.\n");
535 				return -EINVAL;
536 			}
537 		}
538 		if (parse_num_list(arg, &env->test_selector)) {
539 			fprintf(stderr, "Failed to parse test numbers.\n");
540 			return -EINVAL;
541 		}
542 		break;
543 	}
544 	case ARG_TEST_NAME: {
545 		char *subtest_str = strchr(arg, '/');
546 
547 		if (subtest_str) {
548 			*subtest_str = '\0';
549 			if (parse_str_list(subtest_str + 1,
550 					   &env->subtest_selector.whitelist))
551 				return -ENOMEM;
552 		}
553 		if (parse_str_list(arg, &env->test_selector.whitelist))
554 			return -ENOMEM;
555 		break;
556 	}
557 	case ARG_TEST_NAME_BLACKLIST: {
558 		char *subtest_str = strchr(arg, '/');
559 
560 		if (subtest_str) {
561 			*subtest_str = '\0';
562 			if (parse_str_list(subtest_str + 1,
563 					   &env->subtest_selector.blacklist))
564 				return -ENOMEM;
565 		}
566 		if (parse_str_list(arg, &env->test_selector.blacklist))
567 			return -ENOMEM;
568 		break;
569 	}
570 	case ARG_VERIFIER_STATS:
571 		env->verifier_stats = true;
572 		break;
573 	case ARG_VERBOSE:
574 		env->verbosity = VERBOSE_NORMAL;
575 		if (arg) {
576 			if (strcmp(arg, "v") == 0) {
577 				env->verbosity = VERBOSE_VERY;
578 				extra_prog_load_log_flags = 1;
579 			} else if (strcmp(arg, "vv") == 0) {
580 				env->verbosity = VERBOSE_SUPER;
581 				extra_prog_load_log_flags = 2;
582 			} else {
583 				fprintf(stderr,
584 					"Unrecognized verbosity setting ('%s'), only -v and -vv are supported\n",
585 					arg);
586 				return -EINVAL;
587 			}
588 		}
589 		break;
590 	case ARGP_KEY_ARG:
591 		argp_usage(state);
592 		break;
593 	case ARGP_KEY_END:
594 		break;
595 	default:
596 		return ARGP_ERR_UNKNOWN;
597 	}
598 	return 0;
599 }
600 
601 static void stdio_hijack(void)
602 {
603 #ifdef __GLIBC__
604 	env.stdout = stdout;
605 	env.stderr = stderr;
606 
607 	if (env.verbosity > VERBOSE_NONE) {
608 		/* nothing to do, output to stdout by default */
609 		return;
610 	}
611 
612 	/* stdout and stderr -> buffer */
613 	fflush(stdout);
614 
615 	stdout = open_memstream(&env.log_buf, &env.log_cnt);
616 	if (!stdout) {
617 		stdout = env.stdout;
618 		perror("open_memstream");
619 		return;
620 	}
621 
622 	stderr = stdout;
623 #endif
624 }
625 
626 static void stdio_restore(void)
627 {
628 #ifdef __GLIBC__
629 	if (stdout == env.stdout)
630 		return;
631 
632 	fclose(stdout);
633 	free(env.log_buf);
634 
635 	env.log_buf = NULL;
636 	env.log_cnt = 0;
637 
638 	stdout = env.stdout;
639 	stderr = env.stderr;
640 #endif
641 }
642 
643 /*
644  * Determine if test_progs is running as a "flavored" test runner and switch
645  * into corresponding sub-directory to load correct BPF objects.
646  *
647  * This is done by looking at executable name. If it contains "-flavor"
648  * suffix, then we are running as a flavored test runner.
649  */
650 int cd_flavor_subdir(const char *exec_name)
651 {
652 	/* General form of argv[0] passed here is:
653 	 * some/path/to/test_progs[-flavor], where -flavor part is optional.
654 	 * First cut out "test_progs[-flavor]" part, then extract "flavor"
655 	 * part, if it's there.
656 	 */
657 	const char *flavor = strrchr(exec_name, '/');
658 
659 	if (!flavor)
660 		return 0;
661 	flavor++;
662 	flavor = strrchr(flavor, '-');
663 	if (!flavor)
664 		return 0;
665 	flavor++;
666 	fprintf(stdout, "Switching to flavor '%s' subdirectory...\n", flavor);
667 	return chdir(flavor);
668 }
669 
670 #define MAX_BACKTRACE_SZ 128
671 void crash_handler(int signum)
672 {
673 	void *bt[MAX_BACKTRACE_SZ];
674 	size_t sz;
675 
676 	sz = backtrace(bt, ARRAY_SIZE(bt));
677 
678 	if (env.test)
679 		dump_test_log(env.test, true);
680 	if (env.stdout)
681 		stdio_restore();
682 
683 	fprintf(stderr, "Caught signal #%d!\nStack trace:\n", signum);
684 	backtrace_symbols_fd(bt, sz, STDERR_FILENO);
685 }
686 
687 int main(int argc, char **argv)
688 {
689 	static const struct argp argp = {
690 		.options = opts,
691 		.parser = parse_arg,
692 		.doc = argp_program_doc,
693 	};
694 	struct sigaction sigact = {
695 		.sa_handler = crash_handler,
696 		.sa_flags = SA_RESETHAND,
697 	};
698 	int err, i;
699 
700 	sigaction(SIGSEGV, &sigact, NULL);
701 
702 	err = argp_parse(&argp, argc, argv, 0, NULL, &env);
703 	if (err)
704 		return err;
705 
706 	err = cd_flavor_subdir(argv[0]);
707 	if (err)
708 		return err;
709 
710 	libbpf_set_print(libbpf_print_fn);
711 
712 	srand(time(NULL));
713 
714 	env.jit_enabled = is_jit_enabled();
715 	env.nr_cpus = libbpf_num_possible_cpus();
716 	if (env.nr_cpus < 0) {
717 		fprintf(stderr, "Failed to get number of CPUs: %d!\n",
718 			env.nr_cpus);
719 		return -1;
720 	}
721 
722 	stdio_hijack();
723 	for (i = 0; i < prog_test_cnt; i++) {
724 		struct prog_test_def *test = &prog_test_defs[i];
725 
726 		env.test = test;
727 		test->test_num = i + 1;
728 
729 		if (!should_run(&env.test_selector,
730 				test->test_num, test->test_name))
731 			continue;
732 
733 		test->run_test();
734 		/* ensure last sub-test is finalized properly */
735 		if (test->subtest_name)
736 			test__end_subtest();
737 
738 		test->tested = true;
739 		if (test->error_cnt)
740 			env.fail_cnt++;
741 		else
742 			env.succ_cnt++;
743 		skip_account();
744 
745 		dump_test_log(test, test->error_cnt);
746 
747 		fprintf(env.stdout, "#%d %s:%s\n",
748 			test->test_num, test->test_name,
749 			test->error_cnt ? "FAIL" : "OK");
750 
751 		reset_affinity();
752 		if (test->need_cgroup_cleanup)
753 			cleanup_cgroup_environment();
754 	}
755 	stdio_restore();
756 	fprintf(stdout, "Summary: %d/%d PASSED, %d SKIPPED, %d FAILED\n",
757 		env.succ_cnt, env.sub_succ_cnt, env.skip_cnt, env.fail_cnt);
758 
759 	free(env.test_selector.blacklist.strs);
760 	free(env.test_selector.whitelist.strs);
761 	free(env.test_selector.num_set);
762 	free(env.subtest_selector.blacklist.strs);
763 	free(env.subtest_selector.whitelist.strs);
764 	free(env.subtest_selector.num_set);
765 
766 	return env.fail_cnt ? EXIT_FAILURE : EXIT_SUCCESS;
767 }
768