1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2017 Facebook
5 #include "test_progs.h"
6 #include "testing_helpers.h"
7 #include "cgroup_helpers.h"
13 #include <execinfo.h> /* backtrace */
14 #include <linux/membarrier.h>
15 #include <sys/sysinfo.h> /* get_nprocs */
16 #include <netinet/in.h>
17 #include <sys/select.h>
18 #include <sys/socket.h>
21 #include "json_writer.h"
23 static bool verbose(void)
25 return env.verbosity > VERBOSE_NONE;
28 static void stdio_hijack_init(char **log_buf, size_t *log_cnt)
31 if (verbose() && env.worker_id == -1) {
32 /* nothing to do, output to stdout by default */
39 stdout = open_memstream(log_buf, log_cnt);
42 perror("open_memstream");
46 if (env.subtest_state)
47 env.subtest_state->stdout = stdout;
49 env.test_state->stdout = stdout;
55 static void stdio_hijack(char **log_buf, size_t *log_cnt)
58 if (verbose() && env.worker_id == -1) {
59 /* nothing to do, output to stdout by default */
66 stdio_hijack_init(log_buf, log_cnt);
70 static void stdio_restore_cleanup(void)
73 if (verbose() && env.worker_id == -1) {
74 /* nothing to do, output to stdout by default */
80 if (env.subtest_state) {
81 fclose(env.subtest_state->stdout);
82 env.subtest_state->stdout = NULL;
83 stdout = env.test_state->stdout;
84 stderr = env.test_state->stdout;
86 fclose(env.test_state->stdout);
87 env.test_state->stdout = NULL;
92 static void stdio_restore(void)
95 if (verbose() && env.worker_id == -1) {
96 /* nothing to do, output to stdout by default */
100 if (stdout == env.stdout)
103 stdio_restore_cleanup();
110 /* Adapted from perf/util/string.c */
111 static bool glob_match(const char *str, const char *pat)
113 while (*str && *pat && *pat != '*') {
119 /* Check wild card */
123 if (!*pat) /* Tail wild card matches all */
126 if (glob_match(str++, pat))
129 return !*str && !*pat;
132 #define EXIT_NO_TEST 2
133 #define EXIT_ERR_SETUP_INFRA 3
135 /* defined in test_progs.h */
136 struct test_env env = {};
138 struct prog_test_def {
139 const char *test_name;
141 void (*run_test)(void);
142 void (*run_serial_test)(void);
144 bool need_cgroup_cleanup;
147 /* Override C runtime library's usleep() implementation to ensure nanosleep()
148 * is always called. Usleep is frequently used in selftests as a way to
149 * trigger kprobe and tracepoints.
151 int usleep(useconds_t usec)
153 struct timespec ts = {
154 .tv_sec = usec / 1000000,
155 .tv_nsec = (usec % 1000000) * 1000,
158 return syscall(__NR_nanosleep, &ts, NULL);
161 static bool should_run(struct test_selector *sel, int num, const char *name)
165 for (i = 0; i < sel->blacklist.cnt; i++) {
166 if (glob_match(name, sel->blacklist.tests[i].name) &&
167 !sel->blacklist.tests[i].subtest_cnt)
171 for (i = 0; i < sel->whitelist.cnt; i++) {
172 if (glob_match(name, sel->whitelist.tests[i].name))
176 if (!sel->whitelist.cnt && !sel->num_set)
179 return num < sel->num_set_len && sel->num_set[num];
182 static bool should_run_subtest(struct test_selector *sel,
183 struct test_selector *subtest_sel,
185 const char *test_name,
186 const char *subtest_name)
190 for (i = 0; i < sel->blacklist.cnt; i++) {
191 if (glob_match(test_name, sel->blacklist.tests[i].name)) {
192 if (!sel->blacklist.tests[i].subtest_cnt)
195 for (j = 0; j < sel->blacklist.tests[i].subtest_cnt; j++) {
196 if (glob_match(subtest_name,
197 sel->blacklist.tests[i].subtests[j]))
203 for (i = 0; i < sel->whitelist.cnt; i++) {
204 if (glob_match(test_name, sel->whitelist.tests[i].name)) {
205 if (!sel->whitelist.tests[i].subtest_cnt)
208 for (j = 0; j < sel->whitelist.tests[i].subtest_cnt; j++) {
209 if (glob_match(subtest_name,
210 sel->whitelist.tests[i].subtests[j]))
216 if (!sel->whitelist.cnt && !subtest_sel->num_set)
219 return subtest_num < subtest_sel->num_set_len && subtest_sel->num_set[subtest_num];
222 static char *test_result(bool failed, bool skipped)
224 return failed ? "FAIL" : (skipped ? "SKIP" : "OK");
227 #define TEST_NUM_WIDTH 7
229 static void print_test_result(const struct prog_test_def *test, const struct test_state *test_state)
231 int skipped_cnt = test_state->skip_cnt;
232 int subtests_cnt = test_state->subtest_num;
234 fprintf(env.stdout, "#%-*d %s:", TEST_NUM_WIDTH, test->test_num, test->test_name);
235 if (test_state->error_cnt)
236 fprintf(env.stdout, "FAIL");
237 else if (!skipped_cnt)
238 fprintf(env.stdout, "OK");
239 else if (skipped_cnt == subtests_cnt || !subtests_cnt)
240 fprintf(env.stdout, "SKIP");
242 fprintf(env.stdout, "OK (SKIP: %d/%d)", skipped_cnt, subtests_cnt);
244 fprintf(env.stdout, "\n");
247 static void print_test_log(char *log_buf, size_t log_cnt)
249 log_buf[log_cnt] = '\0';
250 fprintf(env.stdout, "%s", log_buf);
251 if (log_buf[log_cnt - 1] != '\n')
252 fprintf(env.stdout, "\n");
255 static void print_subtest_name(int test_num, int subtest_num,
256 const char *test_name, char *subtest_name,
259 char test_num_str[TEST_NUM_WIDTH + 1];
261 snprintf(test_num_str, sizeof(test_num_str), "%d/%d", test_num, subtest_num);
263 fprintf(env.stdout, "#%-*s %s/%s",
264 TEST_NUM_WIDTH, test_num_str,
265 test_name, subtest_name);
268 fprintf(env.stdout, ":%s", result);
270 fprintf(env.stdout, "\n");
273 static void jsonw_write_log_message(json_writer_t *w, char *log_buf, size_t log_cnt)
275 /* open_memstream (from stdio_hijack_init) ensures that log_bug is terminated by a
276 * null byte. Yet in parallel mode, log_buf will be NULL if there is no message.
279 jsonw_string_field(w, "message", log_buf);
281 jsonw_string_field(w, "message", "");
285 static void dump_test_log(const struct prog_test_def *test,
286 const struct test_state *test_state,
287 bool skip_ok_subtests,
288 bool par_exec_result,
291 bool test_failed = test_state->error_cnt > 0;
292 bool force_log = test_state->force_log;
293 bool print_test = verbose() || force_log || test_failed;
295 struct subtest_state *subtest_state;
297 bool subtest_filtered;
300 /* we do not print anything in the worker thread */
301 if (env.worker_id != -1)
304 /* there is nothing to print when verbose log is used and execution
305 * is not in parallel mode
307 if (verbose() && !par_exec_result)
310 if (test_state->log_cnt && print_test)
311 print_test_log(test_state->log_buf, test_state->log_cnt);
313 if (w && print_test) {
314 jsonw_start_object(w);
315 jsonw_string_field(w, "name", test->test_name);
316 jsonw_uint_field(w, "number", test->test_num);
317 jsonw_write_log_message(w, test_state->log_buf, test_state->log_cnt);
318 jsonw_bool_field(w, "failed", test_failed);
319 jsonw_name(w, "subtests");
320 jsonw_start_array(w);
323 for (i = 0; i < test_state->subtest_num; i++) {
324 subtest_state = &test_state->subtest_states[i];
325 subtest_failed = subtest_state->error_cnt;
326 subtest_filtered = subtest_state->filtered;
327 print_subtest = verbose() || force_log || subtest_failed;
329 if ((skip_ok_subtests && !subtest_failed) || subtest_filtered)
332 if (subtest_state->log_cnt && print_subtest) {
333 print_test_log(subtest_state->log_buf,
334 subtest_state->log_cnt);
337 print_subtest_name(test->test_num, i + 1,
338 test->test_name, subtest_state->name,
339 test_result(subtest_state->error_cnt,
340 subtest_state->skipped));
342 if (w && print_subtest) {
343 jsonw_start_object(w);
344 jsonw_string_field(w, "name", subtest_state->name);
345 jsonw_uint_field(w, "number", i+1);
346 jsonw_write_log_message(w, subtest_state->log_buf, subtest_state->log_cnt);
347 jsonw_bool_field(w, "failed", subtest_failed);
352 if (w && print_test) {
357 print_test_result(test, test_state);
360 static void stdio_restore(void);
362 /* A bunch of tests set custom affinity per-thread and/or per-process. Reset
363 * it after each test/sub-test.
365 static void reset_affinity(void)
371 for (i = 0; i < env.nr_cpus; i++)
374 err = sched_setaffinity(0, sizeof(cpuset), &cpuset);
377 fprintf(stderr, "Failed to reset process affinity: %d!\n", err);
378 exit(EXIT_ERR_SETUP_INFRA);
380 err = pthread_setaffinity_np(pthread_self(), sizeof(cpuset), &cpuset);
383 fprintf(stderr, "Failed to reset thread affinity: %d!\n", err);
384 exit(EXIT_ERR_SETUP_INFRA);
388 static void save_netns(void)
390 env.saved_netns_fd = open("/proc/self/ns/net", O_RDONLY);
391 if (env.saved_netns_fd == -1) {
392 perror("open(/proc/self/ns/net)");
393 exit(EXIT_ERR_SETUP_INFRA);
397 static void restore_netns(void)
399 if (setns(env.saved_netns_fd, CLONE_NEWNET) == -1) {
401 perror("setns(CLONE_NEWNS)");
402 exit(EXIT_ERR_SETUP_INFRA);
406 void test__end_subtest(void)
408 struct prog_test_def *test = env.test;
409 struct test_state *test_state = env.test_state;
410 struct subtest_state *subtest_state = env.subtest_state;
412 if (subtest_state->error_cnt) {
413 test_state->error_cnt++;
415 if (!subtest_state->skipped)
416 test_state->sub_succ_cnt++;
418 test_state->skip_cnt++;
421 if (verbose() && !env.workers)
422 print_subtest_name(test->test_num, test_state->subtest_num,
423 test->test_name, subtest_state->name,
424 test_result(subtest_state->error_cnt,
425 subtest_state->skipped));
427 stdio_restore_cleanup();
428 env.subtest_state = NULL;
431 bool test__start_subtest(const char *subtest_name)
433 struct prog_test_def *test = env.test;
434 struct test_state *state = env.test_state;
435 struct subtest_state *subtest_state;
436 size_t sub_state_size = sizeof(*subtest_state);
438 if (env.subtest_state)
441 state->subtest_num++;
442 state->subtest_states =
443 realloc(state->subtest_states,
444 state->subtest_num * sub_state_size);
445 if (!state->subtest_states) {
446 fprintf(stderr, "Not enough memory to allocate subtest result\n");
450 subtest_state = &state->subtest_states[state->subtest_num - 1];
452 memset(subtest_state, 0, sub_state_size);
454 if (!subtest_name || !subtest_name[0]) {
456 "Subtest #%d didn't provide sub-test name!\n",
461 subtest_state->name = strdup(subtest_name);
462 if (!subtest_state->name) {
464 "Subtest #%d: failed to copy subtest name!\n",
469 if (!should_run_subtest(&env.test_selector,
470 &env.subtest_selector,
474 subtest_state->filtered = true;
478 env.subtest_state = subtest_state;
479 stdio_hijack_init(&subtest_state->log_buf, &subtest_state->log_cnt);
484 void test__force_log(void)
486 env.test_state->force_log = true;
489 void test__skip(void)
491 if (env.subtest_state)
492 env.subtest_state->skipped = true;
494 env.test_state->skip_cnt++;
497 void test__fail(void)
499 if (env.subtest_state)
500 env.subtest_state->error_cnt++;
502 env.test_state->error_cnt++;
505 int test__join_cgroup(const char *path)
509 if (!env.test->need_cgroup_cleanup) {
510 if (setup_cgroup_environment()) {
512 "#%d %s: Failed to setup cgroup environment\n",
513 env.test->test_num, env.test->test_name);
517 env.test->need_cgroup_cleanup = true;
520 fd = create_and_get_cgroup(path);
523 "#%d %s: Failed to create cgroup '%s' (errno=%d)\n",
524 env.test->test_num, env.test->test_name, path, errno);
528 if (join_cgroup(path)) {
530 "#%d %s: Failed to join cgroup '%s' (errno=%d)\n",
531 env.test->test_num, env.test->test_name, path, errno);
538 int bpf_find_map(const char *test, struct bpf_object *obj, const char *name)
542 map = bpf_object__find_map_by_name(obj, name);
544 fprintf(stdout, "%s:FAIL:map '%s' not found\n", test, name);
548 return bpf_map__fd(map);
551 static bool is_jit_enabled(void)
553 const char *jit_sysctl = "/proc/sys/net/core/bpf_jit_enable";
554 bool enabled = false;
557 sysctl_fd = open(jit_sysctl, 0, O_RDONLY);
558 if (sysctl_fd != -1) {
561 if (read(sysctl_fd, &tmpc, sizeof(tmpc)) == 1)
562 enabled = (tmpc != '0');
569 int compare_map_keys(int map1_fd, int map2_fd)
572 char val_buf[PERF_MAX_STACK_DEPTH *
573 sizeof(struct bpf_stack_build_id)];
576 err = bpf_map_get_next_key(map1_fd, NULL, &key);
579 err = bpf_map_lookup_elem(map2_fd, &key, val_buf);
583 while (bpf_map_get_next_key(map1_fd, &key, &next_key) == 0) {
584 err = bpf_map_lookup_elem(map2_fd, &next_key, val_buf);
596 int compare_stack_ips(int smap_fd, int amap_fd, int stack_trace_len)
598 __u32 key, next_key, *cur_key_p, *next_key_p;
599 char *val_buf1, *val_buf2;
602 val_buf1 = malloc(stack_trace_len);
603 val_buf2 = malloc(stack_trace_len);
606 while (bpf_map_get_next_key(smap_fd, cur_key_p, next_key_p) == 0) {
607 err = bpf_map_lookup_elem(smap_fd, next_key_p, val_buf1);
610 err = bpf_map_lookup_elem(amap_fd, next_key_p, val_buf2);
613 for (i = 0; i < stack_trace_len; i++) {
614 if (val_buf1[i] != val_buf2[i]) {
621 next_key_p = &next_key;
632 static int finit_module(int fd, const char *param_values, int flags)
634 return syscall(__NR_finit_module, fd, param_values, flags);
637 static int delete_module(const char *name, int flags)
639 return syscall(__NR_delete_module, name, flags);
643 * Trigger synchronize_rcu() in kernel.
645 int kern_sync_rcu(void)
647 return syscall(__NR_membarrier, MEMBARRIER_CMD_SHARED, 0, 0);
650 static void unload_bpf_testmod(void)
653 fprintf(env.stderr, "Failed to trigger kernel-side RCU sync!\n");
654 if (delete_module("bpf_testmod", 0)) {
655 if (errno == ENOENT) {
657 fprintf(stdout, "bpf_testmod.ko is already unloaded.\n");
660 fprintf(env.stderr, "Failed to unload bpf_testmod.ko from kernel: %d\n", -errno);
664 fprintf(stdout, "Successfully unloaded bpf_testmod.ko.\n");
667 static int load_bpf_testmod(void)
671 /* ensure previous instance of the module is unloaded */
672 unload_bpf_testmod();
675 fprintf(stdout, "Loading bpf_testmod.ko...\n");
677 fd = open("bpf_testmod.ko", O_RDONLY);
679 fprintf(env.stderr, "Can't find bpf_testmod.ko kernel module: %d\n", -errno);
682 if (finit_module(fd, "", 0)) {
683 fprintf(env.stderr, "Failed to load bpf_testmod.ko into the kernel: %d\n", -errno);
690 fprintf(stdout, "Successfully loaded bpf_testmod.ko.\n");
694 /* extern declarations for test funcs */
695 #define DEFINE_TEST(name) \
696 extern void test_##name(void) __weak; \
697 extern void serial_test_##name(void) __weak;
698 #include <prog_tests/tests.h>
701 static struct prog_test_def prog_test_defs[] = {
702 #define DEFINE_TEST(name) { \
703 .test_name = #name, \
704 .run_test = &test_##name, \
705 .run_serial_test = &serial_test_##name, \
707 #include <prog_tests/tests.h>
711 static const int prog_test_cnt = ARRAY_SIZE(prog_test_defs);
713 static struct test_state test_states[ARRAY_SIZE(prog_test_defs)];
715 const char *argp_program_version = "test_progs 0.1";
716 const char *argp_program_bug_address = "<bpf@vger.kernel.org>";
717 static const char argp_program_doc[] = "BPF selftests test runner";
722 ARG_TEST_NAME_BLACKLIST = 'b',
723 ARG_VERIFIER_STATS = 's',
725 ARG_GET_TEST_CNT = 'c',
726 ARG_LIST_TEST_NAMES = 'l',
727 ARG_TEST_NAME_GLOB_ALLOWLIST = 'a',
728 ARG_TEST_NAME_GLOB_DENYLIST = 'd',
729 ARG_NUM_WORKERS = 'j',
731 ARG_JSON_SUMMARY = 'J'
734 static const struct argp_option opts[] = {
735 { "num", ARG_TEST_NUM, "NUM", 0,
736 "Run test number NUM only " },
737 { "name", ARG_TEST_NAME, "NAMES", 0,
738 "Run tests with names containing any string from NAMES list" },
739 { "name-blacklist", ARG_TEST_NAME_BLACKLIST, "NAMES", 0,
740 "Don't run tests with names containing any string from NAMES list" },
741 { "verifier-stats", ARG_VERIFIER_STATS, NULL, 0,
742 "Output verifier statistics", },
743 { "verbose", ARG_VERBOSE, "LEVEL", OPTION_ARG_OPTIONAL,
744 "Verbose output (use -vv or -vvv for progressively verbose output)" },
745 { "count", ARG_GET_TEST_CNT, NULL, 0,
746 "Get number of selected top-level tests " },
747 { "list", ARG_LIST_TEST_NAMES, NULL, 0,
748 "List test names that would run (without running them) " },
749 { "allow", ARG_TEST_NAME_GLOB_ALLOWLIST, "NAMES", 0,
750 "Run tests with name matching the pattern (supports '*' wildcard)." },
751 { "deny", ARG_TEST_NAME_GLOB_DENYLIST, "NAMES", 0,
752 "Don't run tests with name matching the pattern (supports '*' wildcard)." },
753 { "workers", ARG_NUM_WORKERS, "WORKERS", OPTION_ARG_OPTIONAL,
754 "Number of workers to run in parallel, default to number of cpus." },
755 { "debug", ARG_DEBUG, NULL, 0,
756 "print extra debug information for test_progs." },
757 { "json-summary", ARG_JSON_SUMMARY, "FILE", 0, "Write report in json format to this file."},
761 static int libbpf_print_fn(enum libbpf_print_level level,
762 const char *format, va_list args)
764 if (env.verbosity < VERBOSE_VERY && level == LIBBPF_DEBUG)
766 vfprintf(stdout, format, args);
770 static void free_test_filter_set(const struct test_filter_set *set)
777 for (i = 0; i < set->cnt; i++) {
778 free((void *)set->tests[i].name);
779 for (j = 0; j < set->tests[i].subtest_cnt; j++)
780 free((void *)set->tests[i].subtests[j]);
782 free((void *)set->tests[i].subtests);
785 free((void *)set->tests);
788 static void free_test_selector(struct test_selector *test_selector)
790 free_test_filter_set(&test_selector->blacklist);
791 free_test_filter_set(&test_selector->whitelist);
792 free(test_selector->num_set);
795 extern int extra_prog_load_log_flags;
797 static error_t parse_arg(int key, char *arg, struct argp_state *state)
799 struct test_env *env = state->input;
803 char *subtest_str = strchr(arg, '/');
807 if (parse_num_list(subtest_str + 1,
808 &env->subtest_selector.num_set,
809 &env->subtest_selector.num_set_len)) {
811 "Failed to parse subtest numbers.\n");
815 if (parse_num_list(arg, &env->test_selector.num_set,
816 &env->test_selector.num_set_len)) {
817 fprintf(stderr, "Failed to parse test numbers.\n");
822 case ARG_TEST_NAME_GLOB_ALLOWLIST:
823 case ARG_TEST_NAME: {
824 if (parse_test_list(arg,
825 &env->test_selector.whitelist,
826 key == ARG_TEST_NAME_GLOB_ALLOWLIST))
830 case ARG_TEST_NAME_GLOB_DENYLIST:
831 case ARG_TEST_NAME_BLACKLIST: {
832 if (parse_test_list(arg,
833 &env->test_selector.blacklist,
834 key == ARG_TEST_NAME_GLOB_DENYLIST))
838 case ARG_VERIFIER_STATS:
839 env->verifier_stats = true;
842 env->verbosity = VERBOSE_NORMAL;
844 if (strcmp(arg, "v") == 0) {
845 env->verbosity = VERBOSE_VERY;
846 extra_prog_load_log_flags = 1;
847 } else if (strcmp(arg, "vv") == 0) {
848 env->verbosity = VERBOSE_SUPER;
849 extra_prog_load_log_flags = 2;
852 "Unrecognized verbosity setting ('%s'), only -v and -vv are supported\n",
859 if (setenv("SELFTESTS_VERBOSE", "1", 1) == -1) {
861 "Unable to setenv SELFTESTS_VERBOSE=1 (errno=%d)",
868 case ARG_GET_TEST_CNT:
869 env->get_test_cnt = true;
871 case ARG_LIST_TEST_NAMES:
872 env->list_test_names = true;
874 case ARG_NUM_WORKERS:
876 env->workers = atoi(arg);
878 fprintf(stderr, "Invalid number of worker: %s.", arg);
882 env->workers = get_nprocs();
888 case ARG_JSON_SUMMARY:
889 env->json = fopen(arg, "w");
890 if (env->json == NULL) {
891 perror("Failed to open json summary file");
901 return ARGP_ERR_UNKNOWN;
907 * Determine if test_progs is running as a "flavored" test runner and switch
908 * into corresponding sub-directory to load correct BPF objects.
910 * This is done by looking at executable name. If it contains "-flavor"
911 * suffix, then we are running as a flavored test runner.
913 int cd_flavor_subdir(const char *exec_name)
915 /* General form of argv[0] passed here is:
916 * some/path/to/test_progs[-flavor], where -flavor part is optional.
917 * First cut out "test_progs[-flavor]" part, then extract "flavor"
918 * part, if it's there.
920 const char *flavor = strrchr(exec_name, '/');
927 flavor = strrchr(flavor, '-');
932 fprintf(stdout, "Switching to flavor '%s' subdirectory...\n", flavor);
934 return chdir(flavor);
937 int trigger_module_test_read(int read_sz)
941 fd = open(BPF_TESTMOD_TEST_FILE, O_RDONLY);
943 if (!ASSERT_GE(fd, 0, "testmod_file_open"))
946 read(fd, NULL, read_sz);
952 int trigger_module_test_write(int write_sz)
955 char *buf = malloc(write_sz);
960 memset(buf, 'a', write_sz);
961 buf[write_sz-1] = '\0';
963 fd = open(BPF_TESTMOD_TEST_FILE, O_WRONLY);
965 if (!ASSERT_GE(fd, 0, "testmod_file_open")) {
970 write(fd, buf, write_sz);
976 int write_sysctl(const char *sysctl, const char *value)
980 fd = open(sysctl, O_WRONLY);
981 if (!ASSERT_NEQ(fd, -1, "open sysctl"))
985 err = write(fd, value, len);
987 if (!ASSERT_EQ(err, len, "write sysctl"))
993 int get_bpf_max_tramp_links_from(struct btf *btf)
995 const struct btf_enum *e;
996 const struct btf_type *t;
1001 for (i = 1, type_cnt = btf__type_cnt(btf); i < type_cnt; i++) {
1002 t = btf__type_by_id(btf, i);
1003 if (!t || !btf_is_enum(t) || t->name_off)
1006 for (j = 0, vlen = btf_vlen(t); j < vlen; j++, e++) {
1007 name = btf__str_by_offset(btf, e->name_off);
1008 if (name && !strcmp(name, "BPF_MAX_TRAMP_LINKS"))
1016 int get_bpf_max_tramp_links(void)
1018 struct btf *vmlinux_btf;
1021 vmlinux_btf = btf__load_vmlinux_btf();
1022 if (!ASSERT_OK_PTR(vmlinux_btf, "vmlinux btf"))
1024 ret = get_bpf_max_tramp_links_from(vmlinux_btf);
1025 btf__free(vmlinux_btf);
1030 #define MAX_BACKTRACE_SZ 128
1031 void crash_handler(int signum)
1033 void *bt[MAX_BACKTRACE_SZ];
1036 sz = backtrace(bt, ARRAY_SIZE(bt));
1041 env.test_state->error_cnt++;
1042 dump_test_log(env.test, env.test_state, true, false, NULL);
1044 if (env.worker_id != -1)
1045 fprintf(stderr, "[%d]: ", env.worker_id);
1046 fprintf(stderr, "Caught signal #%d!\nStack trace:\n", signum);
1047 backtrace_symbols_fd(bt, sz, STDERR_FILENO);
1050 static void sigint_handler(int signum)
1054 for (i = 0; i < env.workers; i++)
1055 if (env.worker_socks[i] > 0)
1056 close(env.worker_socks[i]);
1059 static int current_test_idx;
1060 static pthread_mutex_t current_test_lock;
1061 static pthread_mutex_t stdout_output_lock;
1063 static inline const char *str_msg(const struct msg *msg, char *buf)
1065 switch (msg->type) {
1067 sprintf(buf, "MSG_DO_TEST %d", msg->do_test.num);
1070 sprintf(buf, "MSG_TEST_DONE %d (log: %d)",
1072 msg->test_done.have_log);
1074 case MSG_SUBTEST_DONE:
1075 sprintf(buf, "MSG_SUBTEST_DONE %d (log: %d)",
1076 msg->subtest_done.num,
1077 msg->subtest_done.have_log);
1080 sprintf(buf, "MSG_TEST_LOG (cnt: %zu, last: %d)",
1081 strlen(msg->test_log.log_buf),
1082 msg->test_log.is_last);
1085 sprintf(buf, "MSG_EXIT");
1088 sprintf(buf, "UNKNOWN");
1095 static int send_message(int sock, const struct msg *msg)
1100 fprintf(stderr, "Sending msg: %s\n", str_msg(msg, buf));
1101 return send(sock, msg, sizeof(*msg), 0);
1104 static int recv_message(int sock, struct msg *msg)
1109 memset(msg, 0, sizeof(*msg));
1110 ret = recv(sock, msg, sizeof(*msg), 0);
1113 fprintf(stderr, "Received msg: %s\n", str_msg(msg, buf));
1118 static void run_one_test(int test_num)
1120 struct prog_test_def *test = &prog_test_defs[test_num];
1121 struct test_state *state = &test_states[test_num];
1124 env.test_state = state;
1126 stdio_hijack(&state->log_buf, &state->log_cnt);
1130 else if (test->run_serial_test)
1131 test->run_serial_test();
1133 /* ensure last sub-test is finalized properly */
1134 if (env.subtest_state)
1135 test__end_subtest();
1137 state->tested = true;
1139 if (verbose() && env.worker_id == -1)
1140 print_test_result(test, state);
1144 if (test->need_cgroup_cleanup)
1145 cleanup_cgroup_environment();
1149 dump_test_log(test, state, false, false, NULL);
1152 struct dispatch_data {
1157 static int read_prog_test_msg(int sock_fd, struct msg *msg, enum msg_type type)
1159 if (recv_message(sock_fd, msg) < 0)
1162 if (msg->type != type) {
1163 printf("%s: unexpected message type %d. expected %d\n", __func__, msg->type, type);
1170 static int dispatch_thread_read_log(int sock_fd, char **log_buf, size_t *log_cnt)
1172 FILE *log_fp = NULL;
1175 log_fp = open_memstream(log_buf, log_cnt);
1182 if (read_prog_test_msg(sock_fd, &msg, MSG_TEST_LOG)) {
1187 fprintf(log_fp, "%s", msg.test_log.log_buf);
1188 if (msg.test_log.is_last)
1198 static int dispatch_thread_send_subtests(int sock_fd, struct test_state *state)
1201 struct subtest_state *subtest_state;
1202 int subtest_num = state->subtest_num;
1204 state->subtest_states = malloc(subtest_num * sizeof(*subtest_state));
1206 for (int i = 0; i < subtest_num; i++) {
1207 subtest_state = &state->subtest_states[i];
1209 memset(subtest_state, 0, sizeof(*subtest_state));
1211 if (read_prog_test_msg(sock_fd, &msg, MSG_SUBTEST_DONE))
1214 subtest_state->name = strdup(msg.subtest_done.name);
1215 subtest_state->error_cnt = msg.subtest_done.error_cnt;
1216 subtest_state->skipped = msg.subtest_done.skipped;
1217 subtest_state->filtered = msg.subtest_done.filtered;
1219 /* collect all logs */
1220 if (msg.subtest_done.have_log)
1221 if (dispatch_thread_read_log(sock_fd,
1222 &subtest_state->log_buf,
1223 &subtest_state->log_cnt))
1230 static void *dispatch_thread(void *ctx)
1232 struct dispatch_data *data = ctx;
1235 sock_fd = data->sock_fd;
1238 int test_to_run = -1;
1239 struct prog_test_def *test;
1240 struct test_state *state;
1244 pthread_mutex_lock(¤t_test_lock);
1246 if (current_test_idx >= prog_test_cnt) {
1247 pthread_mutex_unlock(¤t_test_lock);
1251 test = &prog_test_defs[current_test_idx];
1252 test_to_run = current_test_idx;
1255 pthread_mutex_unlock(¤t_test_lock);
1258 if (!test->should_run || test->run_serial_test)
1261 /* run test through worker */
1263 struct msg msg_do_test;
1265 memset(&msg_do_test, 0, sizeof(msg_do_test));
1266 msg_do_test.type = MSG_DO_TEST;
1267 msg_do_test.do_test.num = test_to_run;
1268 if (send_message(sock_fd, &msg_do_test) < 0) {
1269 perror("Fail to send command");
1272 env.worker_current_test[data->worker_id] = test_to_run;
1275 /* wait for test done */
1279 if (read_prog_test_msg(sock_fd, &msg, MSG_TEST_DONE))
1281 if (test_to_run != msg.test_done.num)
1284 state = &test_states[test_to_run];
1285 state->tested = true;
1286 state->error_cnt = msg.test_done.error_cnt;
1287 state->skip_cnt = msg.test_done.skip_cnt;
1288 state->sub_succ_cnt = msg.test_done.sub_succ_cnt;
1289 state->subtest_num = msg.test_done.subtest_num;
1291 /* collect all logs */
1292 if (msg.test_done.have_log) {
1293 if (dispatch_thread_read_log(sock_fd,
1299 /* collect all subtests and subtest logs */
1300 if (!state->subtest_num)
1303 if (dispatch_thread_send_subtests(sock_fd, state))
1307 pthread_mutex_lock(&stdout_output_lock);
1308 dump_test_log(test, state, false, true, NULL);
1309 pthread_mutex_unlock(&stdout_output_lock);
1310 } /* while (true) */
1313 fprintf(stderr, "[%d]: Protocol/IO error: %s.\n", data->worker_id, strerror(errno));
1317 struct msg msg_exit;
1319 msg_exit.type = MSG_EXIT;
1320 if (send_message(sock_fd, &msg_exit) < 0) {
1322 fprintf(stderr, "[%d]: send_message msg_exit: %s.\n",
1323 data->worker_id, strerror(errno));
1329 static void calculate_summary_and_print_errors(struct test_env *env)
1332 int succ_cnt = 0, fail_cnt = 0, sub_succ_cnt = 0, skip_cnt = 0;
1333 json_writer_t *w = NULL;
1335 for (i = 0; i < prog_test_cnt; i++) {
1336 struct test_state *state = &test_states[i];
1341 sub_succ_cnt += state->sub_succ_cnt;
1342 skip_cnt += state->skip_cnt;
1344 if (state->error_cnt)
1351 w = jsonw_new(env->json);
1353 fprintf(env->stderr, "Failed to create new JSON stream.");
1357 jsonw_start_object(w);
1358 jsonw_uint_field(w, "success", succ_cnt);
1359 jsonw_uint_field(w, "success_subtest", sub_succ_cnt);
1360 jsonw_uint_field(w, "skipped", skip_cnt);
1361 jsonw_uint_field(w, "failed", fail_cnt);
1362 jsonw_name(w, "results");
1363 jsonw_start_array(w);
1367 * We only print error logs summary when there are failed tests and
1368 * verbose mode is not enabled. Otherwise, results may be incosistent.
1371 if (!verbose() && fail_cnt) {
1372 printf("\nAll error logs:\n");
1374 /* print error logs again */
1375 for (i = 0; i < prog_test_cnt; i++) {
1376 struct prog_test_def *test = &prog_test_defs[i];
1377 struct test_state *state = &test_states[i];
1379 if (!state->tested || !state->error_cnt)
1382 dump_test_log(test, state, true, true, w);
1388 jsonw_end_object(w);
1395 printf("Summary: %d/%d PASSED, %d SKIPPED, %d FAILED\n",
1396 succ_cnt, sub_succ_cnt, skip_cnt, fail_cnt);
1398 env->succ_cnt = succ_cnt;
1399 env->sub_succ_cnt = sub_succ_cnt;
1400 env->fail_cnt = fail_cnt;
1401 env->skip_cnt = skip_cnt;
1404 static void server_main(void)
1406 pthread_t *dispatcher_threads;
1407 struct dispatch_data *data;
1408 struct sigaction sigact_int = {
1409 .sa_handler = sigint_handler,
1410 .sa_flags = SA_RESETHAND,
1414 sigaction(SIGINT, &sigact_int, NULL);
1416 dispatcher_threads = calloc(sizeof(pthread_t), env.workers);
1417 data = calloc(sizeof(struct dispatch_data), env.workers);
1419 env.worker_current_test = calloc(sizeof(int), env.workers);
1420 for (i = 0; i < env.workers; i++) {
1423 data[i].worker_id = i;
1424 data[i].sock_fd = env.worker_socks[i];
1425 rc = pthread_create(&dispatcher_threads[i], NULL, dispatch_thread, &data[i]);
1427 perror("Failed to launch dispatcher thread");
1428 exit(EXIT_ERR_SETUP_INFRA);
1432 /* wait for all dispatcher to finish */
1433 for (i = 0; i < env.workers; i++) {
1435 int ret = pthread_tryjoin_np(dispatcher_threads[i], NULL);
1439 } else if (ret == EBUSY) {
1441 fprintf(stderr, "Still waiting for thread %d (test %d).\n",
1442 i, env.worker_current_test[i] + 1);
1443 usleep(1000 * 1000);
1446 fprintf(stderr, "Unexpected error joining dispatcher thread: %d", ret);
1451 free(dispatcher_threads);
1452 free(env.worker_current_test);
1455 /* run serial tests */
1458 for (int i = 0; i < prog_test_cnt; i++) {
1459 struct prog_test_def *test = &prog_test_defs[i];
1461 if (!test->should_run || !test->run_serial_test)
1467 /* generate summary */
1471 calculate_summary_and_print_errors(&env);
1473 /* reap all workers */
1474 for (i = 0; i < env.workers; i++) {
1477 pid = waitpid(env.worker_pids[i], &wstatus, 0);
1478 if (pid != env.worker_pids[i])
1479 perror("Unable to reap worker");
1483 static void worker_main_send_log(int sock, char *log_buf, size_t log_cnt)
1495 memset(&msg_log, 0, sizeof(msg_log));
1496 msg_log.type = MSG_TEST_LOG;
1497 dest = msg_log.test_log.log_buf;
1498 len = slen >= MAX_LOG_TRUNK_SIZE ? MAX_LOG_TRUNK_SIZE : slen;
1499 memcpy(dest, src, len);
1504 msg_log.test_log.is_last = true;
1506 assert(send_message(sock, &msg_log) >= 0);
1510 static void free_subtest_state(struct subtest_state *state)
1512 if (state->log_buf) {
1513 free(state->log_buf);
1514 state->log_buf = NULL;
1521 static int worker_main_send_subtests(int sock, struct test_state *state)
1525 struct subtest_state *subtest_state;
1527 memset(&msg, 0, sizeof(msg));
1528 msg.type = MSG_SUBTEST_DONE;
1530 for (i = 0; i < state->subtest_num; i++) {
1531 subtest_state = &state->subtest_states[i];
1533 msg.subtest_done.num = i;
1535 strncpy(msg.subtest_done.name, subtest_state->name, MAX_SUBTEST_NAME);
1537 msg.subtest_done.error_cnt = subtest_state->error_cnt;
1538 msg.subtest_done.skipped = subtest_state->skipped;
1539 msg.subtest_done.filtered = subtest_state->filtered;
1540 msg.subtest_done.have_log = false;
1542 if (verbose() || state->force_log || subtest_state->error_cnt) {
1543 if (subtest_state->log_cnt)
1544 msg.subtest_done.have_log = true;
1547 if (send_message(sock, &msg) < 0) {
1548 perror("Fail to send message done");
1554 if (msg.subtest_done.have_log)
1555 worker_main_send_log(sock, subtest_state->log_buf, subtest_state->log_cnt);
1557 free_subtest_state(subtest_state);
1558 free(subtest_state->name);
1562 for (; i < state->subtest_num; i++)
1563 free_subtest_state(&state->subtest_states[i]);
1564 free(state->subtest_states);
1568 static int worker_main(int sock)
1573 /* receive command */
1576 if (recv_message(sock, &msg) < 0)
1582 fprintf(stderr, "[%d]: worker exit.\n",
1586 int test_to_run = msg.do_test.num;
1587 struct prog_test_def *test = &prog_test_defs[test_to_run];
1588 struct test_state *state = &test_states[test_to_run];
1592 fprintf(stderr, "[%d]: #%d:%s running.\n",
1597 run_one_test(test_to_run);
1599 memset(&msg, 0, sizeof(msg));
1600 msg.type = MSG_TEST_DONE;
1601 msg.test_done.num = test_to_run;
1602 msg.test_done.error_cnt = state->error_cnt;
1603 msg.test_done.skip_cnt = state->skip_cnt;
1604 msg.test_done.sub_succ_cnt = state->sub_succ_cnt;
1605 msg.test_done.subtest_num = state->subtest_num;
1606 msg.test_done.have_log = false;
1608 if (verbose() || state->force_log || state->error_cnt) {
1610 msg.test_done.have_log = true;
1612 if (send_message(sock, &msg) < 0) {
1613 perror("Fail to send message done");
1618 if (msg.test_done.have_log)
1619 worker_main_send_log(sock, state->log_buf, state->log_cnt);
1621 if (state->log_buf) {
1622 free(state->log_buf);
1623 state->log_buf = NULL;
1627 if (state->subtest_num)
1628 if (worker_main_send_subtests(sock, state))
1632 fprintf(stderr, "[%d]: #%d:%s done.\n",
1637 } /* case MSG_DO_TEST */
1640 fprintf(stderr, "[%d]: unknown message.\n", env.worker_id);
1648 static void free_test_states(void)
1652 for (i = 0; i < ARRAY_SIZE(prog_test_defs); i++) {
1653 struct test_state *test_state = &test_states[i];
1655 for (j = 0; j < test_state->subtest_num; j++)
1656 free_subtest_state(&test_state->subtest_states[j]);
1658 free(test_state->subtest_states);
1659 free(test_state->log_buf);
1660 test_state->subtest_states = NULL;
1661 test_state->log_buf = NULL;
1665 int main(int argc, char **argv)
1667 static const struct argp argp = {
1669 .parser = parse_arg,
1670 .doc = argp_program_doc,
1672 struct sigaction sigact = {
1673 .sa_handler = crash_handler,
1674 .sa_flags = SA_RESETHAND,
1678 sigaction(SIGSEGV, &sigact, NULL);
1680 err = argp_parse(&argp, argc, argv, 0, NULL, &env);
1684 err = cd_flavor_subdir(argv[0]);
1688 /* Use libbpf 1.0 API mode */
1689 libbpf_set_strict_mode(LIBBPF_STRICT_ALL);
1690 libbpf_set_print(libbpf_print_fn);
1694 env.jit_enabled = is_jit_enabled();
1695 env.nr_cpus = libbpf_num_possible_cpus();
1696 if (env.nr_cpus < 0) {
1697 fprintf(stderr, "Failed to get number of CPUs: %d!\n",
1702 env.stdout = stdout;
1703 env.stderr = stderr;
1705 env.has_testmod = true;
1706 if (!env.list_test_names && load_bpf_testmod()) {
1707 fprintf(env.stderr, "WARNING! Selftests relying on bpf_testmod.ko will be skipped.\n");
1708 env.has_testmod = false;
1711 /* initializing tests */
1712 for (i = 0; i < prog_test_cnt; i++) {
1713 struct prog_test_def *test = &prog_test_defs[i];
1715 test->test_num = i + 1;
1716 test->should_run = should_run(&env.test_selector,
1717 test->test_num, test->test_name);
1719 if ((test->run_test == NULL && test->run_serial_test == NULL) ||
1720 (test->run_test != NULL && test->run_serial_test != NULL)) {
1721 fprintf(stderr, "Test %d:%s must have either test_%s() or serial_test_%sl() defined.\n",
1722 test->test_num, test->test_name, test->test_name, test->test_name);
1723 exit(EXIT_ERR_SETUP_INFRA);
1727 /* ignore workers if we are just listing */
1728 if (env.get_test_cnt || env.list_test_names)
1731 /* launch workers if requested */
1732 env.worker_id = -1; /* main process */
1734 env.worker_pids = calloc(sizeof(__pid_t), env.workers);
1735 env.worker_socks = calloc(sizeof(int), env.workers);
1737 fprintf(stdout, "Launching %d workers.\n", env.workers);
1738 for (i = 0; i < env.workers; i++) {
1742 if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sv) < 0) {
1743 perror("Fail to create worker socket");
1748 perror("Failed to fork worker");
1750 } else if (pid != 0) { /* main process */
1752 env.worker_pids[i] = pid;
1753 env.worker_socks[i] = sv[0];
1754 } else { /* inside each worker process */
1757 return worker_main(sv[1]);
1761 if (env.worker_id == -1) {
1767 /* The rest of the main process */
1769 /* on single mode */
1772 for (i = 0; i < prog_test_cnt; i++) {
1773 struct prog_test_def *test = &prog_test_defs[i];
1775 if (!test->should_run)
1778 if (env.get_test_cnt) {
1783 if (env.list_test_names) {
1784 fprintf(env.stdout, "%s\n", test->test_name);
1792 if (env.get_test_cnt) {
1793 printf("%d\n", env.succ_cnt);
1797 if (env.list_test_names)
1800 calculate_summary_and_print_errors(&env);
1802 close(env.saved_netns_fd);
1804 if (!env.list_test_names && env.has_testmod)
1805 unload_bpf_testmod();
1807 free_test_selector(&env.test_selector);
1808 free_test_selector(&env.subtest_selector);
1811 if (env.succ_cnt + env.fail_cnt + env.skip_cnt == 0)
1812 return EXIT_NO_TEST;
1814 return env.fail_cnt ? EXIT_FAILURE : EXIT_SUCCESS;