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 "testing_helpers.h" 7 #include "cgroup_helpers.h" 8 #include <argp.h> 9 #include <pthread.h> 10 #include <sched.h> 11 #include <signal.h> 12 #include <string.h> 13 #include <sys/sysinfo.h> /* get_nprocs */ 14 #include <netinet/in.h> 15 #include <sys/select.h> 16 #include <sys/socket.h> 17 #include <linux/keyctl.h> 18 #include <sys/un.h> 19 #include <bpf/btf.h> 20 #include <time.h> 21 #include "json_writer.h" 22 23 #include "network_helpers.h" 24 #include "verification_cert.h" 25 26 /* backtrace() and backtrace_symbols_fd() are glibc specific, 27 * use header file when glibc is available and provide stub 28 * implementations when another libc implementation is used. 29 */ 30 #ifdef __GLIBC__ 31 #include <execinfo.h> /* backtrace */ 32 #else 33 __weak int backtrace(void **buffer, int size) 34 { 35 return 0; 36 } 37 38 __weak void backtrace_symbols_fd(void *const *buffer, int size, int fd) 39 { 40 dprintf(fd, "<backtrace not supported>\n"); 41 } 42 #endif /*__GLIBC__ */ 43 44 int env_verbosity = 0; 45 46 static bool verbose(void) 47 { 48 return env.verbosity > VERBOSE_NONE; 49 } 50 51 static void stdio_hijack_init(char **log_buf, size_t *log_cnt) 52 { 53 #ifdef __GLIBC__ 54 if (verbose() && env.worker_id == -1) { 55 /* nothing to do, output to stdout by default */ 56 return; 57 } 58 59 fflush(stdout); 60 fflush(stderr); 61 62 stdout = open_memstream(log_buf, log_cnt); 63 if (!stdout) { 64 stdout = env.stdout_saved; 65 perror("open_memstream"); 66 return; 67 } 68 69 if (env.subtest_state) 70 env.subtest_state->stdout_saved = stdout; 71 else 72 env.test_state->stdout_saved = stdout; 73 74 stderr = stdout; 75 #endif 76 } 77 78 static void stdio_hijack(char **log_buf, size_t *log_cnt) 79 { 80 #ifdef __GLIBC__ 81 if (verbose() && env.worker_id == -1) { 82 /* nothing to do, output to stdout by default */ 83 return; 84 } 85 86 env.stdout_saved = stdout; 87 env.stderr_saved = stderr; 88 89 stdio_hijack_init(log_buf, log_cnt); 90 #endif 91 } 92 93 static pthread_mutex_t stdout_lock = PTHREAD_MUTEX_INITIALIZER; 94 95 static void stdio_restore(void) 96 { 97 #ifdef __GLIBC__ 98 if (verbose() && env.worker_id == -1) { 99 /* nothing to do, output to stdout by default */ 100 return; 101 } 102 103 fflush(stdout); 104 105 pthread_mutex_lock(&stdout_lock); 106 107 if (env.subtest_state) { 108 if (env.subtest_state->stdout_saved) 109 fclose(env.subtest_state->stdout_saved); 110 env.subtest_state->stdout_saved = NULL; 111 stdout = env.test_state->stdout_saved; 112 stderr = env.test_state->stdout_saved; 113 } else { 114 if (env.test_state->stdout_saved) 115 fclose(env.test_state->stdout_saved); 116 env.test_state->stdout_saved = NULL; 117 stdout = env.stdout_saved; 118 stderr = env.stderr_saved; 119 } 120 121 pthread_mutex_unlock(&stdout_lock); 122 #endif 123 } 124 125 static int traffic_monitor_print_fn(const char *format, va_list args) 126 { 127 pthread_mutex_lock(&stdout_lock); 128 vfprintf(stdout, format, args); 129 pthread_mutex_unlock(&stdout_lock); 130 131 return 0; 132 } 133 134 /* Adapted from perf/util/string.c */ 135 static bool glob_match(const char *str, const char *pat) 136 { 137 while (*str && *pat && *pat != '*') { 138 if (*str != *pat) 139 return false; 140 str++; 141 pat++; 142 } 143 /* Check wild card */ 144 if (*pat == '*') { 145 while (*pat == '*') 146 pat++; 147 if (!*pat) /* Tail wild card matches all */ 148 return true; 149 while (*str) 150 if (glob_match(str++, pat)) 151 return true; 152 } 153 return !*str && !*pat; 154 } 155 156 #define EXIT_NO_TEST 2 157 #define EXIT_ERR_SETUP_INFRA 3 158 159 /* defined in test_progs.h */ 160 struct test_env env = {}; 161 162 struct prog_test_def { 163 const char *test_name; 164 int test_num; 165 void (*run_test)(void); 166 void (*run_serial_test)(void); 167 bool should_run; 168 bool not_built; 169 bool selected; 170 bool need_cgroup_cleanup; 171 bool should_tmon; 172 }; 173 174 /* Override C runtime library's usleep() implementation to ensure nanosleep() 175 * is always called. Usleep is frequently used in selftests as a way to 176 * trigger kprobe and tracepoints. 177 */ 178 int usleep(useconds_t usec) 179 { 180 struct timespec ts = { 181 .tv_sec = usec / 1000000, 182 .tv_nsec = (usec % 1000000) * 1000, 183 }; 184 185 return syscall(__NR_nanosleep, &ts, NULL); 186 } 187 188 /* Watchdog timer is started by watchdog_start() and stopped by watchdog_stop(). 189 * If timer is active for longer than env.secs_till_notify, 190 * it prints the name of the current test to the stderr. 191 * If timer is active for longer than env.secs_till_kill, 192 * it kills the thread executing the test by sending a SIGSEGV signal to it. 193 */ 194 static void watchdog_timer_func(union sigval sigval) 195 { 196 struct itimerspec timeout = {}; 197 char test_name[256]; 198 int err; 199 200 if (env.subtest_state) 201 snprintf(test_name, sizeof(test_name), "%s/%s", 202 env.test->test_name, env.subtest_state->name); 203 else 204 snprintf(test_name, sizeof(test_name), "%s", 205 env.test->test_name); 206 207 switch (env.watchdog_state) { 208 case WD_NOTIFY: 209 fprintf(env.stderr_saved, "WATCHDOG: test case %s executes for %d seconds...\n", 210 test_name, env.secs_till_notify); 211 timeout.it_value.tv_sec = env.secs_till_kill - env.secs_till_notify; 212 env.watchdog_state = WD_KILL; 213 err = timer_settime(env.watchdog, 0, &timeout, NULL); 214 if (err) 215 fprintf(env.stderr_saved, "Failed to arm watchdog timer\n"); 216 break; 217 case WD_KILL: 218 fprintf(env.stderr_saved, 219 "WATCHDOG: test case %s executes for %d seconds, terminating with SIGSEGV\n", 220 test_name, env.secs_till_kill); 221 pthread_kill(env.main_thread, SIGSEGV); 222 break; 223 } 224 } 225 226 static void watchdog_start(void) 227 { 228 struct itimerspec timeout = {}; 229 int err; 230 231 if (env.secs_till_kill == 0) 232 return; 233 if (env.secs_till_notify > 0) { 234 env.watchdog_state = WD_NOTIFY; 235 timeout.it_value.tv_sec = env.secs_till_notify; 236 } else { 237 env.watchdog_state = WD_KILL; 238 timeout.it_value.tv_sec = env.secs_till_kill; 239 } 240 err = timer_settime(env.watchdog, 0, &timeout, NULL); 241 if (err) 242 fprintf(env.stderr_saved, "Failed to start watchdog timer\n"); 243 } 244 245 static void watchdog_stop(void) 246 { 247 struct itimerspec timeout = {}; 248 int err; 249 250 env.watchdog_state = WD_NOTIFY; 251 err = timer_settime(env.watchdog, 0, &timeout, NULL); 252 if (err) 253 fprintf(env.stderr_saved, "Failed to stop watchdog timer\n"); 254 } 255 256 static void watchdog_init(void) 257 { 258 struct sigevent watchdog_sev = { 259 .sigev_notify = SIGEV_THREAD, 260 .sigev_notify_function = watchdog_timer_func, 261 }; 262 int err; 263 264 env.main_thread = pthread_self(); 265 err = timer_create(CLOCK_MONOTONIC, &watchdog_sev, &env.watchdog); 266 if (err) 267 fprintf(stderr, "Failed to initialize watchdog timer\n"); 268 } 269 270 static bool should_run(struct test_selector *sel, int num, const char *name) 271 { 272 int i; 273 274 for (i = 0; i < sel->blacklist.cnt; i++) { 275 if (glob_match(name, sel->blacklist.tests[i].name) && 276 !sel->blacklist.tests[i].subtest_cnt) 277 return false; 278 } 279 280 for (i = 0; i < sel->whitelist.cnt; i++) { 281 if (glob_match(name, sel->whitelist.tests[i].name)) 282 return true; 283 } 284 285 if (!sel->whitelist.cnt && !sel->num_set) 286 return true; 287 288 return num < sel->num_set_len && sel->num_set[num]; 289 } 290 291 static bool match_subtest(struct test_filter_set *filter, 292 const char *test_name, 293 const char *subtest_name) 294 { 295 int i, j; 296 297 for (i = 0; i < filter->cnt; i++) { 298 if (glob_match(test_name, filter->tests[i].name)) { 299 if (!filter->tests[i].subtest_cnt) 300 return true; 301 302 for (j = 0; j < filter->tests[i].subtest_cnt; j++) { 303 if (glob_match(subtest_name, 304 filter->tests[i].subtests[j])) 305 return true; 306 } 307 } 308 } 309 310 return false; 311 } 312 313 static bool match_subtest_desc(struct test_filter_set *filter, 314 const char *test_name, 315 const char *subtest_name, 316 const char *subtest_desc) 317 { 318 if (match_subtest(filter, test_name, subtest_name)) 319 return true; 320 321 if (!subtest_desc || !subtest_desc[0] || 322 strcmp(subtest_name, subtest_desc) == 0) 323 return false; 324 325 return match_subtest(filter, test_name, subtest_desc); 326 } 327 328 static bool should_run_subtest(struct test_selector *sel, 329 struct test_selector *subtest_sel, 330 int subtest_num, 331 const char *test_name, 332 const char *subtest_name, 333 const char *subtest_desc) 334 { 335 if (match_subtest_desc(&sel->blacklist, test_name, 336 subtest_name, subtest_desc)) 337 return false; 338 339 if (match_subtest_desc(&sel->whitelist, test_name, 340 subtest_name, subtest_desc)) 341 return true; 342 343 if (!sel->whitelist.cnt && !subtest_sel->num_set) 344 return true; 345 346 return subtest_num < subtest_sel->num_set_len && subtest_sel->num_set[subtest_num]; 347 } 348 349 static bool should_tmon(struct test_selector *sel, const char *name) 350 { 351 int i; 352 353 for (i = 0; i < sel->whitelist.cnt; i++) { 354 if (glob_match(name, sel->whitelist.tests[i].name) && 355 !sel->whitelist.tests[i].subtest_cnt) 356 return true; 357 } 358 359 return false; 360 } 361 362 static char *test_result(bool failed, bool skipped) 363 { 364 return failed ? "FAIL" : (skipped ? "SKIP" : "OK"); 365 } 366 367 #define TEST_NUM_WIDTH 7 368 369 static void print_test_result(const struct prog_test_def *test, const struct test_state *test_state) 370 { 371 int skipped_cnt = test_state->skip_cnt; 372 int subtests_cnt = test_state->subtest_num; 373 374 fprintf(env.stdout_saved, "#%-*d %s:", TEST_NUM_WIDTH, test->test_num, test->test_name); 375 if (test_state->error_cnt) 376 fprintf(env.stdout_saved, "FAIL"); 377 else if (test->not_built) 378 fprintf(env.stdout_saved, "SKIP (not built)"); 379 else if (!skipped_cnt) 380 fprintf(env.stdout_saved, "OK"); 381 else if (skipped_cnt == subtests_cnt || !subtests_cnt) 382 fprintf(env.stdout_saved, "SKIP"); 383 else 384 fprintf(env.stdout_saved, "OK (SKIP: %d/%d)", skipped_cnt, subtests_cnt); 385 386 fprintf(env.stdout_saved, "\n"); 387 } 388 389 static void print_test_log(char *log_buf, size_t log_cnt) 390 { 391 log_buf[log_cnt] = '\0'; 392 fprintf(env.stdout_saved, "%s", log_buf); 393 if (log_buf[log_cnt - 1] != '\n') 394 fprintf(env.stdout_saved, "\n"); 395 } 396 397 static void print_subtest_name(int test_num, int subtest_num, 398 const char *test_name, char *subtest_name, 399 char *result) 400 { 401 char test_num_str[32]; 402 403 snprintf(test_num_str, sizeof(test_num_str), "%d/%d", test_num, subtest_num); 404 405 fprintf(env.stdout_saved, "#%-*s %s/%s", 406 TEST_NUM_WIDTH, test_num_str, 407 test_name, subtest_name); 408 409 if (result) 410 fprintf(env.stdout_saved, ":%s", result); 411 412 fprintf(env.stdout_saved, "\n"); 413 } 414 415 static void jsonw_write_log_message(json_writer_t *w, char *log_buf, size_t log_cnt) 416 { 417 /* open_memstream (from stdio_hijack_init) ensures that log_bug is terminated by a 418 * null byte. Yet in parallel mode, log_buf will be NULL if there is no message. 419 */ 420 if (log_cnt) { 421 jsonw_string_field(w, "message", log_buf); 422 } else { 423 jsonw_string_field(w, "message", ""); 424 } 425 } 426 427 /* @quiet elides the human readable output, the JSON report is unaffected */ 428 static void dump_test_log(const struct prog_test_def *test, 429 const struct test_state *test_state, 430 bool skip_ok_subtests, 431 bool par_exec_result, 432 bool quiet, 433 json_writer_t *w) 434 { 435 bool test_failed = test_state->error_cnt > 0; 436 bool force_log = test_state->force_log; 437 bool print_test = verbose() || force_log || test_failed; 438 int i; 439 struct subtest_state *subtest_state; 440 bool subtest_failed; 441 bool subtest_filtered; 442 bool print_subtest; 443 444 /* we do not print anything in the worker thread */ 445 if (env.worker_id != -1) 446 return; 447 448 /* there is nothing to print when verbose log is used and execution 449 * is not in parallel mode 450 */ 451 if (verbose() && !par_exec_result) 452 return; 453 454 if (test_state->log_cnt && print_test && !quiet) 455 print_test_log(test_state->log_buf, test_state->log_cnt); 456 457 if (w && print_test) { 458 jsonw_start_object(w); 459 jsonw_string_field(w, "name", test->test_name); 460 jsonw_uint_field(w, "number", test->test_num); 461 jsonw_write_log_message(w, test_state->log_buf, test_state->log_cnt); 462 jsonw_bool_field(w, "failed", test_failed); 463 jsonw_name(w, "subtests"); 464 jsonw_start_array(w); 465 } 466 467 for (i = 0; i < test_state->subtest_num; i++) { 468 subtest_state = &test_state->subtest_states[i]; 469 subtest_failed = subtest_state->error_cnt; 470 subtest_filtered = subtest_state->filtered; 471 print_subtest = verbose() || force_log || subtest_failed; 472 473 if ((skip_ok_subtests && !subtest_failed) || subtest_filtered) 474 continue; 475 476 if (subtest_state->log_cnt && print_subtest && !quiet) { 477 print_test_log(subtest_state->log_buf, 478 subtest_state->log_cnt); 479 } 480 481 if (!quiet) 482 print_subtest_name(test->test_num, i + 1, 483 test->test_name, subtest_state->name, 484 test_result(subtest_state->error_cnt, 485 subtest_state->skipped)); 486 487 if (w && print_subtest) { 488 jsonw_start_object(w); 489 jsonw_string_field(w, "name", subtest_state->name); 490 jsonw_uint_field(w, "number", i+1); 491 jsonw_write_log_message(w, subtest_state->log_buf, subtest_state->log_cnt); 492 jsonw_bool_field(w, "failed", subtest_failed); 493 jsonw_end_object(w); 494 } 495 } 496 497 if (w && print_test) { 498 jsonw_end_array(w); 499 jsonw_end_object(w); 500 } 501 502 if (!quiet) 503 print_test_result(test, test_state); 504 } 505 506 /* A bunch of tests set custom affinity per-thread and/or per-process. Reset 507 * it after each test/sub-test. 508 */ 509 static void reset_affinity(void) 510 { 511 cpu_set_t cpuset; 512 int i, err; 513 514 CPU_ZERO(&cpuset); 515 for (i = 0; i < env.nr_cpus; i++) 516 CPU_SET(i, &cpuset); 517 518 err = sched_setaffinity(0, sizeof(cpuset), &cpuset); 519 if (err < 0) { 520 fprintf(stderr, "Failed to reset process affinity: %d!\n", err); 521 exit(EXIT_ERR_SETUP_INFRA); 522 } 523 err = pthread_setaffinity_np(pthread_self(), sizeof(cpuset), &cpuset); 524 if (err < 0) { 525 fprintf(stderr, "Failed to reset thread affinity: %d!\n", err); 526 exit(EXIT_ERR_SETUP_INFRA); 527 } 528 } 529 530 static void save_netns(void) 531 { 532 env.saved_netns_fd = open("/proc/self/ns/net", O_RDONLY); 533 if (env.saved_netns_fd == -1) { 534 perror("open(/proc/self/ns/net)"); 535 exit(EXIT_ERR_SETUP_INFRA); 536 } 537 } 538 539 static void restore_netns(void) 540 { 541 if (setns(env.saved_netns_fd, CLONE_NEWNET) == -1) { 542 perror("setns(CLONE_NEWNS)"); 543 exit(EXIT_ERR_SETUP_INFRA); 544 } 545 } 546 547 void test__end_subtest(void) 548 { 549 struct prog_test_def *test = env.test; 550 struct test_state *test_state = env.test_state; 551 struct subtest_state *subtest_state = env.subtest_state; 552 553 if (subtest_state->error_cnt) { 554 test_state->error_cnt++; 555 } else { 556 if (!subtest_state->skipped) 557 test_state->sub_succ_cnt++; 558 else 559 test_state->skip_cnt++; 560 } 561 562 if (verbose() && !env.workers) 563 print_subtest_name(test->test_num, test_state->subtest_num, 564 test->test_name, subtest_state->name, 565 test_result(subtest_state->error_cnt, 566 subtest_state->skipped)); 567 568 stdio_restore(); 569 570 env.subtest_state = NULL; 571 } 572 573 bool test__start_subtest_with_desc(const char *subtest_name, const char *subtest_desc) 574 { 575 struct prog_test_def *test = env.test; 576 struct test_state *state = env.test_state; 577 struct subtest_state *subtest_state; 578 const char *subtest_display_name; 579 size_t sub_state_size = sizeof(*subtest_state); 580 void *tmp; 581 582 if (env.subtest_state) 583 test__end_subtest(); 584 585 state->subtest_num++; 586 tmp = realloc(state->subtest_states, state->subtest_num * sub_state_size); 587 if (!tmp) { 588 state->subtest_num--; 589 fprintf(stderr, "Not enough memory to allocate subtest result\n"); 590 return false; 591 } 592 state->subtest_states = tmp; 593 594 subtest_state = &state->subtest_states[state->subtest_num - 1]; 595 596 memset(subtest_state, 0, sub_state_size); 597 598 if (!subtest_name || !subtest_name[0]) { 599 fprintf(env.stderr_saved, 600 "Subtest #%d didn't provide sub-test name!\n", 601 state->subtest_num); 602 return false; 603 } 604 605 subtest_display_name = subtest_desc ? subtest_desc : subtest_name; 606 607 subtest_state->name = strdup(subtest_display_name); 608 if (!subtest_state->name) { 609 fprintf(env.stderr_saved, 610 "Subtest #%d: failed to copy subtest name!\n", 611 state->subtest_num); 612 return false; 613 } 614 615 if (!should_run_subtest(&env.test_selector, 616 &env.subtest_selector, 617 state->subtest_num, 618 test->test_name, 619 subtest_name, 620 subtest_desc)) { 621 subtest_state->filtered = true; 622 return false; 623 } 624 625 subtest_state->should_tmon = match_subtest_desc(&env.tmon_selector.whitelist, 626 test->test_name, subtest_name, 627 subtest_desc); 628 629 env.subtest_state = subtest_state; 630 stdio_hijack_init(&subtest_state->log_buf, &subtest_state->log_cnt); 631 watchdog_start(); 632 633 return true; 634 } 635 636 bool test__start_subtest(const char *subtest_name) 637 { 638 return test__start_subtest_with_desc(subtest_name, NULL); 639 } 640 641 void test__force_log(void) 642 { 643 env.test_state->force_log = true; 644 } 645 646 void test__skip(void) 647 { 648 if (env.subtest_state) 649 env.subtest_state->skipped = true; 650 else 651 env.test_state->skip_cnt++; 652 } 653 654 void test__fail(void) 655 { 656 if (env.subtest_state) 657 env.subtest_state->error_cnt++; 658 else 659 env.test_state->error_cnt++; 660 } 661 662 int test__join_cgroup(const char *path) 663 { 664 int fd; 665 666 if (!env.test->need_cgroup_cleanup) { 667 if (setup_cgroup_environment()) { 668 fprintf(stderr, 669 "#%d %s: Failed to setup cgroup environment\n", 670 env.test->test_num, env.test->test_name); 671 return -1; 672 } 673 674 env.test->need_cgroup_cleanup = true; 675 } 676 677 fd = create_and_get_cgroup(path); 678 if (fd < 0) { 679 fprintf(stderr, 680 "#%d %s: Failed to create cgroup '%s' (errno=%d)\n", 681 env.test->test_num, env.test->test_name, path, errno); 682 return fd; 683 } 684 685 if (join_cgroup(path)) { 686 fprintf(stderr, 687 "#%d %s: Failed to join cgroup '%s' (errno=%d)\n", 688 env.test->test_num, env.test->test_name, path, errno); 689 return -1; 690 } 691 692 return fd; 693 } 694 695 int bpf_find_map(const char *test, struct bpf_object *obj, const char *name) 696 { 697 struct bpf_map *map; 698 699 map = bpf_object__find_map_by_name(obj, name); 700 if (!map) { 701 fprintf(stdout, "%s:FAIL:map '%s' not found\n", test, name); 702 test__fail(); 703 return -1; 704 } 705 return bpf_map__fd(map); 706 } 707 708 int compare_map_keys(int map1_fd, int map2_fd) 709 { 710 __u32 key, next_key; 711 char val_buf[PERF_MAX_STACK_DEPTH * 712 sizeof(struct bpf_stack_build_id)]; 713 int err; 714 715 err = bpf_map_get_next_key(map1_fd, NULL, &key); 716 if (err) 717 return err; 718 err = bpf_map_lookup_elem(map2_fd, &key, val_buf); 719 if (err) 720 return err; 721 722 while (bpf_map_get_next_key(map1_fd, &key, &next_key) == 0) { 723 err = bpf_map_lookup_elem(map2_fd, &next_key, val_buf); 724 if (err) 725 return err; 726 727 key = next_key; 728 } 729 if (errno != ENOENT) 730 return -1; 731 732 return 0; 733 } 734 735 int compare_stack_ips(int smap_fd, int amap_fd, int stack_trace_len) 736 { 737 __u32 key, next_key, *cur_key_p, *next_key_p; 738 char *val_buf1 = NULL, *val_buf2 = NULL; 739 int i, err = -ENOMEM; 740 741 val_buf1 = malloc(stack_trace_len); 742 val_buf2 = malloc(stack_trace_len); 743 if (!val_buf1 || !val_buf2) 744 goto out; 745 err = 0; 746 cur_key_p = NULL; 747 next_key_p = &key; 748 while (bpf_map_get_next_key(smap_fd, cur_key_p, next_key_p) == 0) { 749 err = bpf_map_lookup_elem(smap_fd, next_key_p, val_buf1); 750 if (err) 751 goto out; 752 err = bpf_map_lookup_elem(amap_fd, next_key_p, val_buf2); 753 if (err) 754 goto out; 755 for (i = 0; i < stack_trace_len; i++) { 756 if (val_buf1[i] != val_buf2[i]) { 757 err = -1; 758 goto out; 759 } 760 } 761 key = *next_key_p; 762 cur_key_p = &key; 763 next_key_p = &next_key; 764 } 765 if (errno != ENOENT) 766 err = -1; 767 768 out: 769 free(val_buf1); 770 free(val_buf2); 771 return err; 772 } 773 774 struct netns_obj { 775 char *nsname; 776 struct tmonitor_ctx *tmon; 777 struct nstoken *nstoken; 778 }; 779 780 /* Create a new network namespace with the given name. 781 * 782 * Create a new network namespace and set the network namespace of the 783 * current process to the new network namespace if the argument "open" is 784 * true. This function should be paired with netns_free() to release the 785 * resource and delete the network namespace. 786 * 787 * It also implements the functionality of the option "-m" by starting 788 * traffic monitor on the background to capture the packets in this network 789 * namespace if the current test or subtest matching the pattern. 790 * 791 * nsname: the name of the network namespace to create. 792 * open: open the network namespace if true. 793 * 794 * Return: the network namespace object on success, NULL on failure. 795 */ 796 struct netns_obj *netns_new(const char *nsname, bool open) 797 { 798 struct netns_obj *netns_obj = malloc(sizeof(*netns_obj)); 799 const char *test_name, *subtest_name; 800 int r; 801 802 if (!netns_obj) 803 return NULL; 804 memset(netns_obj, 0, sizeof(*netns_obj)); 805 806 netns_obj->nsname = strdup(nsname); 807 if (!netns_obj->nsname) 808 goto fail; 809 810 /* Create the network namespace */ 811 r = make_netns(nsname); 812 if (r) 813 goto fail; 814 815 /* Start traffic monitor */ 816 if (env.test->should_tmon || 817 (env.subtest_state && env.subtest_state->should_tmon)) { 818 test_name = env.test->test_name; 819 subtest_name = env.subtest_state ? env.subtest_state->name : NULL; 820 netns_obj->tmon = traffic_monitor_start(nsname, test_name, subtest_name); 821 if (!netns_obj->tmon) { 822 fprintf(stderr, "Failed to start traffic monitor for %s\n", nsname); 823 goto fail; 824 } 825 } else { 826 netns_obj->tmon = NULL; 827 } 828 829 if (open) { 830 netns_obj->nstoken = open_netns(nsname); 831 if (!netns_obj->nstoken) 832 goto fail; 833 } 834 835 return netns_obj; 836 fail: 837 traffic_monitor_stop(netns_obj->tmon); 838 remove_netns(nsname); 839 free(netns_obj->nsname); 840 free(netns_obj); 841 return NULL; 842 } 843 844 /* Delete the network namespace. 845 * 846 * This function should be paired with netns_new() to delete the namespace 847 * created by netns_new(). 848 */ 849 void netns_free(struct netns_obj *netns_obj) 850 { 851 if (!netns_obj) 852 return; 853 traffic_monitor_stop(netns_obj->tmon); 854 close_netns(netns_obj->nstoken); 855 remove_netns(netns_obj->nsname); 856 free(netns_obj->nsname); 857 free(netns_obj); 858 } 859 860 /* extern declarations for test funcs */ 861 #define DEFINE_TEST(name) \ 862 extern void test_##name(void) __weak; \ 863 extern void serial_test_##name(void) __weak; 864 #include <prog_tests/tests.h> 865 #undef DEFINE_TEST 866 867 static struct prog_test_def prog_test_defs[] = { 868 #define DEFINE_TEST(name) { \ 869 .test_name = #name, \ 870 .run_test = &test_##name, \ 871 .run_serial_test = &serial_test_##name, \ 872 }, 873 #include <prog_tests/tests.h> 874 #undef DEFINE_TEST 875 }; 876 877 static const int prog_test_cnt = ARRAY_SIZE(prog_test_defs); 878 879 static struct test_state test_states[ARRAY_SIZE(prog_test_defs)]; 880 881 const char *argp_program_version = "test_progs 0.1"; 882 const char *argp_program_bug_address = "<bpf@vger.kernel.org>"; 883 static const char argp_program_doc[] = 884 "BPF selftests test runner\v" 885 "Options accepting the NAMES parameter take either a comma-separated list\n" 886 "of test names, or a filename prefixed with @. The file contains one name\n" 887 "(or wildcard pattern) per line, and comments beginning with # are ignored.\n" 888 "\n" 889 "These options can be passed repeatedly to read multiple files.\n"; 890 891 enum ARG_KEYS { 892 ARG_TEST_NUM = 'n', 893 ARG_TEST_NAME = 't', 894 ARG_TEST_NAME_BLACKLIST = 'b', 895 ARG_VERIFIER_STATS = 's', 896 ARG_VERBOSE = 'v', 897 ARG_GET_TEST_CNT = 'c', 898 ARG_LIST_TEST_NAMES = 'l', 899 ARG_TEST_NAME_GLOB_ALLOWLIST = 'a', 900 ARG_TEST_NAME_GLOB_DENYLIST = 'd', 901 ARG_NUM_WORKERS = 'j', 902 ARG_DEBUG = -1, 903 ARG_JSON_SUMMARY = 'J', 904 ARG_TRAFFIC_MONITOR = 'm', 905 ARG_WATCHDOG_TIMEOUT = 'w', 906 ARG_NO_ERROR_SUMMARY = -2, 907 }; 908 909 static const struct argp_option opts[] = { 910 { "num", ARG_TEST_NUM, "NUM", 0, 911 "Run test number NUM only " }, 912 { "name", ARG_TEST_NAME, "NAMES", 0, 913 "Run tests with names containing any string from NAMES list" }, 914 { "name-blacklist", ARG_TEST_NAME_BLACKLIST, "NAMES", 0, 915 "Don't run tests with names containing any string from NAMES list" }, 916 { "verifier-stats", ARG_VERIFIER_STATS, NULL, 0, 917 "Output verifier statistics", }, 918 { "verbose", ARG_VERBOSE, "LEVEL", OPTION_ARG_OPTIONAL, 919 "Verbose output (use -vv or -vvv for progressively verbose output)" }, 920 { "count", ARG_GET_TEST_CNT, NULL, 0, 921 "Get number of selected top-level tests " }, 922 { "list", ARG_LIST_TEST_NAMES, NULL, 0, 923 "List test names that would run (without running them) " }, 924 { "allow", ARG_TEST_NAME_GLOB_ALLOWLIST, "NAMES", 0, 925 "Run tests with name matching the pattern (supports '*' wildcard)." }, 926 { "deny", ARG_TEST_NAME_GLOB_DENYLIST, "NAMES", 0, 927 "Don't run tests with name matching the pattern (supports '*' wildcard)." }, 928 { "workers", ARG_NUM_WORKERS, "WORKERS", OPTION_ARG_OPTIONAL, 929 "Number of workers to run in parallel, default to number of cpus." }, 930 { "debug", ARG_DEBUG, NULL, 0, 931 "print extra debug information for test_progs." }, 932 { "json-summary", ARG_JSON_SUMMARY, "FILE", 0, "Write report in json format to this file."}, 933 #ifdef TRAFFIC_MONITOR 934 { "traffic-monitor", ARG_TRAFFIC_MONITOR, "NAMES", 0, 935 "Monitor network traffic of tests with name matching the pattern (supports '*' wildcard)." }, 936 #endif 937 { "watchdog-timeout", ARG_WATCHDOG_TIMEOUT, "SECONDS", 0, 938 "Kill the process if tests are not making progress for specified number of seconds." }, 939 { "no-error-summary", ARG_NO_ERROR_SUMMARY, NULL, 0, 940 "Do not re-print the aggregated error logs of failed tests at the end of the run." }, 941 {}, 942 }; 943 944 static FILE *libbpf_capture_stream; 945 946 static struct { 947 char *buf; 948 size_t buf_sz; 949 } libbpf_output_capture; 950 951 /* Creates a global memstream capturing INFO and WARN level output 952 * passed to libbpf_print_fn. 953 * Returns 0 on success, negative value on failure. 954 * On failure the description is printed using PRINT_FAIL and 955 * current test case is marked as fail. 956 */ 957 int start_libbpf_log_capture(void) 958 { 959 if (libbpf_capture_stream) { 960 PRINT_FAIL("%s: libbpf_capture_stream != NULL\n", __func__); 961 return -EINVAL; 962 } 963 964 libbpf_capture_stream = open_memstream(&libbpf_output_capture.buf, 965 &libbpf_output_capture.buf_sz); 966 if (!libbpf_capture_stream) { 967 PRINT_FAIL("%s: open_memstream failed errno=%d\n", __func__, errno); 968 return -EINVAL; 969 } 970 971 return 0; 972 } 973 974 /* Destroys global memstream created by start_libbpf_log_capture(). 975 * Returns a pointer to captured data which has to be freed. 976 * Returned buffer is null terminated. 977 */ 978 char *stop_libbpf_log_capture(void) 979 { 980 char *buf; 981 982 if (!libbpf_capture_stream) 983 return NULL; 984 985 fputc(0, libbpf_capture_stream); 986 fclose(libbpf_capture_stream); 987 libbpf_capture_stream = NULL; 988 /* get 'buf' after fclose(), see open_memstream() documentation */ 989 buf = libbpf_output_capture.buf; 990 memset(&libbpf_output_capture, 0, sizeof(libbpf_output_capture)); 991 return buf; 992 } 993 994 static int libbpf_print_fn(enum libbpf_print_level level, 995 const char *format, va_list args) 996 { 997 if (libbpf_capture_stream && level != LIBBPF_DEBUG) { 998 va_list args2; 999 1000 va_copy(args2, args); 1001 vfprintf(libbpf_capture_stream, format, args2); 1002 va_end(args2); 1003 } 1004 1005 if (env.verbosity < VERBOSE_VERY && level == LIBBPF_DEBUG) 1006 return 0; 1007 1008 vfprintf(stdout, format, args); 1009 return 0; 1010 } 1011 1012 static void free_test_filter_set(const struct test_filter_set *set) 1013 { 1014 int i, j; 1015 1016 if (!set) 1017 return; 1018 1019 for (i = 0; i < set->cnt; i++) { 1020 free((void *)set->tests[i].name); 1021 for (j = 0; j < set->tests[i].subtest_cnt; j++) 1022 free((void *)set->tests[i].subtests[j]); 1023 1024 free((void *)set->tests[i].subtests); 1025 } 1026 1027 free((void *)set->tests); 1028 } 1029 1030 static void free_test_selector(struct test_selector *test_selector) 1031 { 1032 free_test_filter_set(&test_selector->blacklist); 1033 free_test_filter_set(&test_selector->whitelist); 1034 free(test_selector->num_set); 1035 } 1036 1037 extern int extra_prog_load_log_flags; 1038 1039 static error_t parse_arg(int key, char *arg, struct argp_state *state) 1040 { 1041 struct test_env *env = state->input; 1042 int err = 0; 1043 1044 switch (key) { 1045 case ARG_TEST_NUM: { 1046 char *subtest_str = strchr(arg, '/'); 1047 1048 if (subtest_str) { 1049 *subtest_str = '\0'; 1050 if (parse_num_list(subtest_str + 1, 1051 &env->subtest_selector.num_set, 1052 &env->subtest_selector.num_set_len)) { 1053 fprintf(stderr, 1054 "Failed to parse subtest numbers.\n"); 1055 return -EINVAL; 1056 } 1057 } 1058 if (parse_num_list(arg, &env->test_selector.num_set, 1059 &env->test_selector.num_set_len)) { 1060 fprintf(stderr, "Failed to parse test numbers.\n"); 1061 return -EINVAL; 1062 } 1063 break; 1064 } 1065 case ARG_TEST_NAME_GLOB_ALLOWLIST: 1066 case ARG_TEST_NAME: { 1067 if (arg[0] == '@') 1068 err = parse_test_list_file(arg + 1, 1069 &env->test_selector.whitelist, 1070 key == ARG_TEST_NAME_GLOB_ALLOWLIST); 1071 else 1072 err = parse_test_list(arg, 1073 &env->test_selector.whitelist, 1074 key == ARG_TEST_NAME_GLOB_ALLOWLIST); 1075 1076 break; 1077 } 1078 case ARG_TEST_NAME_GLOB_DENYLIST: 1079 case ARG_TEST_NAME_BLACKLIST: { 1080 if (arg[0] == '@') 1081 err = parse_test_list_file(arg + 1, 1082 &env->test_selector.blacklist, 1083 key == ARG_TEST_NAME_GLOB_DENYLIST); 1084 else 1085 err = parse_test_list(arg, 1086 &env->test_selector.blacklist, 1087 key == ARG_TEST_NAME_GLOB_DENYLIST); 1088 1089 break; 1090 } 1091 case ARG_VERIFIER_STATS: 1092 env->verifier_stats = true; 1093 break; 1094 case ARG_VERBOSE: 1095 env->verbosity = VERBOSE_NORMAL; 1096 if (arg) { 1097 if (strcmp(arg, "v") == 0) { 1098 env->verbosity = VERBOSE_VERY; 1099 extra_prog_load_log_flags = 1; 1100 } else if (strcmp(arg, "vv") == 0) { 1101 env->verbosity = VERBOSE_SUPER; 1102 extra_prog_load_log_flags = 2; 1103 } else { 1104 fprintf(stderr, 1105 "Unrecognized verbosity setting ('%s'), only -v and -vv are supported\n", 1106 arg); 1107 return -EINVAL; 1108 } 1109 } 1110 env_verbosity = env->verbosity; 1111 1112 if (verbose()) { 1113 if (setenv("SELFTESTS_VERBOSE", "1", 1) == -1) { 1114 fprintf(stderr, 1115 "Unable to setenv SELFTESTS_VERBOSE=1 (errno=%d)", 1116 errno); 1117 return -EINVAL; 1118 } 1119 } 1120 1121 break; 1122 case ARG_GET_TEST_CNT: 1123 env->get_test_cnt = true; 1124 break; 1125 case ARG_LIST_TEST_NAMES: 1126 env->list_test_names = true; 1127 break; 1128 case ARG_NUM_WORKERS: 1129 if (arg) { 1130 env->workers = atoi(arg); 1131 if (!env->workers) { 1132 fprintf(stderr, "Invalid number of worker: %s.", arg); 1133 return -EINVAL; 1134 } 1135 } else { 1136 env->workers = get_nprocs(); 1137 } 1138 break; 1139 case ARG_DEBUG: 1140 env->debug = true; 1141 break; 1142 case ARG_NO_ERROR_SUMMARY: 1143 env->error_summary = false; 1144 break; 1145 case ARG_JSON_SUMMARY: 1146 env->json = fopen(arg, "w"); 1147 if (env->json == NULL) { 1148 perror("Failed to open json summary file"); 1149 return -errno; 1150 } 1151 break; 1152 case ARGP_KEY_ARG: 1153 argp_usage(state); 1154 break; 1155 case ARGP_KEY_END: 1156 break; 1157 #ifdef TRAFFIC_MONITOR 1158 case ARG_TRAFFIC_MONITOR: 1159 if (arg[0] == '@') 1160 err = parse_test_list_file(arg + 1, 1161 &env->tmon_selector.whitelist, 1162 true); 1163 else 1164 err = parse_test_list(arg, 1165 &env->tmon_selector.whitelist, 1166 true); 1167 break; 1168 #endif 1169 case ARG_WATCHDOG_TIMEOUT: 1170 env->secs_till_kill = atoi(arg); 1171 if (env->secs_till_kill < 0) { 1172 fprintf(stderr, "Invalid watchdog timeout: %s.\n", arg); 1173 return -EINVAL; 1174 } 1175 if (env->secs_till_kill < env->secs_till_notify) { 1176 env->secs_till_notify = 0; 1177 } 1178 break; 1179 default: 1180 return ARGP_ERR_UNKNOWN; 1181 } 1182 return err; 1183 } 1184 1185 /* 1186 * Determine if test_progs is running as a "flavored" test runner and switch 1187 * into corresponding sub-directory to load correct BPF objects. 1188 * 1189 * This is done by looking at executable name. If it contains "-flavor" 1190 * suffix, then we are running as a flavored test runner. 1191 */ 1192 int cd_flavor_subdir(const char *exec_name) 1193 { 1194 /* General form of argv[0] passed here is: 1195 * some/path/to/test_progs[-flavor], where -flavor part is optional. 1196 * First cut out "test_progs[-flavor]" part, then extract "flavor" 1197 * part, if it's there. 1198 */ 1199 const char *flavor = strrchr(exec_name, '/'); 1200 1201 if (!flavor) 1202 flavor = exec_name; 1203 else 1204 flavor++; 1205 1206 flavor = strrchr(flavor, '-'); 1207 if (!flavor) 1208 return 0; 1209 flavor++; 1210 if (verbose()) 1211 fprintf(stdout, "Switching to flavor '%s' subdirectory...\n", flavor); 1212 1213 return chdir(flavor); 1214 } 1215 1216 int trigger_module_test_read(int read_sz) 1217 { 1218 int fd, err; 1219 1220 fd = open(BPF_TESTMOD_TEST_FILE, O_RDONLY); 1221 err = -errno; 1222 if (!ASSERT_GE(fd, 0, "testmod_file_open")) 1223 return err; 1224 1225 read(fd, NULL, read_sz); 1226 close(fd); 1227 1228 return 0; 1229 } 1230 1231 int trigger_module_test_write(int write_sz) 1232 { 1233 int fd, err; 1234 char *buf = malloc(write_sz); 1235 1236 if (!buf) 1237 return -ENOMEM; 1238 1239 memset(buf, 'a', write_sz); 1240 buf[write_sz-1] = '\0'; 1241 1242 fd = open(BPF_TESTMOD_TEST_FILE, O_WRONLY); 1243 err = -errno; 1244 if (!ASSERT_GE(fd, 0, "testmod_file_open")) { 1245 free(buf); 1246 return err; 1247 } 1248 1249 write(fd, buf, write_sz); 1250 close(fd); 1251 free(buf); 1252 return 0; 1253 } 1254 1255 int write_sysctl(const char *sysctl, const char *value) 1256 { 1257 int fd, err, len; 1258 1259 fd = open(sysctl, O_WRONLY); 1260 if (!ASSERT_NEQ(fd, -1, "open sysctl")) 1261 return -1; 1262 1263 len = strlen(value); 1264 err = write(fd, value, len); 1265 close(fd); 1266 if (!ASSERT_EQ(err, len, "write sysctl")) 1267 return -1; 1268 1269 return 0; 1270 } 1271 1272 int get_bpf_max_tramp_links_from(struct btf *btf) 1273 { 1274 const struct btf_enum *e; 1275 const struct btf_type *t; 1276 __u32 i, type_cnt; 1277 const char *name; 1278 __u32 j, vlen; 1279 1280 for (i = 1, type_cnt = btf__type_cnt(btf); i < type_cnt; i++) { 1281 t = btf__type_by_id(btf, i); 1282 if (!t || !btf_is_enum(t) || t->name_off) 1283 continue; 1284 e = btf_enum(t); 1285 for (j = 0, vlen = btf_vlen(t); j < vlen; j++, e++) { 1286 name = btf__str_by_offset(btf, e->name_off); 1287 if (name && !strcmp(name, "BPF_MAX_TRAMP_LINKS")) 1288 return e->val; 1289 } 1290 } 1291 1292 return -1; 1293 } 1294 1295 int get_bpf_max_tramp_links(void) 1296 { 1297 struct btf *vmlinux_btf; 1298 int ret; 1299 1300 vmlinux_btf = btf__load_vmlinux_btf(); 1301 if (!ASSERT_OK_PTR(vmlinux_btf, "vmlinux btf")) 1302 return -1; 1303 ret = get_bpf_max_tramp_links_from(vmlinux_btf); 1304 btf__free(vmlinux_btf); 1305 1306 return ret; 1307 } 1308 1309 static void dump_crash_log(void) 1310 { 1311 fflush(stdout); 1312 stdout = env.stdout_saved; 1313 stderr = env.stderr_saved; 1314 1315 if (env.test) { 1316 env.test_state->error_cnt++; 1317 dump_test_log(env.test, env.test_state, true, false, false, NULL); 1318 } 1319 } 1320 1321 #define MAX_BACKTRACE_SZ 128 1322 1323 void crash_handler(int signum) 1324 { 1325 void *bt[MAX_BACKTRACE_SZ]; 1326 size_t sz; 1327 1328 sz = backtrace(bt, ARRAY_SIZE(bt)); 1329 1330 dump_crash_log(); 1331 1332 if (env.worker_id != -1) 1333 fprintf(stderr, "[%d]: ", env.worker_id); 1334 fprintf(stderr, "Caught signal #%d!\nStack trace:\n", signum); 1335 backtrace_symbols_fd(bt, sz, STDERR_FILENO); 1336 } 1337 1338 #ifdef __SANITIZE_ADDRESS__ 1339 void __asan_on_error(void) 1340 { 1341 dump_crash_log(); 1342 } 1343 #endif 1344 1345 void hexdump(const char *prefix, const void *buf, size_t len) 1346 { 1347 for (int i = 0; i < len; i++) { 1348 if (!(i % 16)) { 1349 if (i) 1350 fprintf(stdout, "\n"); 1351 fprintf(stdout, "%s", prefix); 1352 } 1353 if (i && !(i % 8) && (i % 16)) 1354 fprintf(stdout, "\t"); 1355 fprintf(stdout, "%02X ", ((uint8_t *)(buf))[i]); 1356 } 1357 fprintf(stdout, "\n"); 1358 } 1359 1360 static void sigint_handler(int signum) 1361 { 1362 int i; 1363 1364 for (i = 0; i < env.workers; i++) 1365 if (env.worker_socks[i] > 0) 1366 close(env.worker_socks[i]); 1367 } 1368 1369 static int current_test_idx; 1370 static pthread_mutex_t current_test_lock; 1371 static pthread_mutex_t stdout_output_lock; 1372 1373 static inline const char *str_msg(const struct msg *msg, char *buf) 1374 { 1375 switch (msg->type) { 1376 case MSG_DO_TEST: 1377 sprintf(buf, "MSG_DO_TEST %d", msg->do_test.num); 1378 break; 1379 case MSG_TEST_DONE: 1380 sprintf(buf, "MSG_TEST_DONE %d (log: %d)", 1381 msg->test_done.num, 1382 msg->test_done.have_log); 1383 break; 1384 case MSG_SUBTEST_DONE: 1385 sprintf(buf, "MSG_SUBTEST_DONE %d (log: %d)", 1386 msg->subtest_done.num, 1387 msg->subtest_done.have_log); 1388 break; 1389 case MSG_TEST_LOG: 1390 sprintf(buf, "MSG_TEST_LOG (cnt: %zu, last: %d)", 1391 strlen(msg->test_log.log_buf), 1392 msg->test_log.is_last); 1393 break; 1394 case MSG_EXIT: 1395 sprintf(buf, "MSG_EXIT"); 1396 break; 1397 default: 1398 sprintf(buf, "UNKNOWN"); 1399 break; 1400 } 1401 1402 return buf; 1403 } 1404 1405 static int send_message(int sock, const struct msg *msg) 1406 { 1407 char buf[256]; 1408 1409 if (env.debug) 1410 fprintf(stderr, "Sending msg: %s\n", str_msg(msg, buf)); 1411 return send(sock, msg, sizeof(*msg), 0); 1412 } 1413 1414 static int recv_message(int sock, struct msg *msg) 1415 { 1416 int ret; 1417 char buf[256]; 1418 1419 memset(msg, 0, sizeof(*msg)); 1420 ret = recv(sock, msg, sizeof(*msg), 0); 1421 if (ret >= 0) { 1422 if (env.debug) 1423 fprintf(stderr, "Received msg: %s\n", str_msg(msg, buf)); 1424 } 1425 return ret; 1426 } 1427 1428 static bool ns_is_needed(const char *test_name) 1429 { 1430 if (strlen(test_name) < 3) 1431 return false; 1432 1433 return !strncmp(test_name, "ns_", 3); 1434 } 1435 1436 static void run_one_test(int test_num) 1437 { 1438 struct prog_test_def *test = &prog_test_defs[test_num]; 1439 struct test_state *state = &test_states[test_num]; 1440 struct netns_obj *ns = NULL; 1441 1442 env.test = test; 1443 env.test_state = state; 1444 1445 stdio_hijack(&state->log_buf, &state->log_cnt); 1446 1447 watchdog_start(); 1448 if (ns_is_needed(test->test_name)) 1449 ns = netns_new(test->test_name, true); 1450 if (test->run_test) 1451 test->run_test(); 1452 else if (test->run_serial_test) 1453 test->run_serial_test(); 1454 netns_free(ns); 1455 watchdog_stop(); 1456 1457 /* ensure last sub-test is finalized properly */ 1458 if (env.subtest_state) 1459 test__end_subtest(); 1460 1461 state->tested = true; 1462 1463 stdio_restore(); 1464 1465 if (verbose() && env.worker_id == -1) 1466 print_test_result(test, state); 1467 1468 reset_affinity(); 1469 restore_netns(); 1470 if (test->need_cgroup_cleanup) 1471 cleanup_cgroup_environment(); 1472 1473 free(stop_libbpf_log_capture()); 1474 1475 dump_test_log(test, state, false, false, false, NULL); 1476 } 1477 1478 struct dispatch_data { 1479 int worker_id; 1480 int sock_fd; 1481 }; 1482 1483 static int read_prog_test_msg(int sock_fd, struct msg *msg, enum msg_type type) 1484 { 1485 if (recv_message(sock_fd, msg) < 0) 1486 return 1; 1487 1488 if (msg->type != type) { 1489 printf("%s: unexpected message type %d. expected %d\n", __func__, msg->type, type); 1490 return 1; 1491 } 1492 1493 return 0; 1494 } 1495 1496 static int dispatch_thread_read_log(int sock_fd, char **log_buf, size_t *log_cnt) 1497 { 1498 FILE *log_fp = NULL; 1499 int result = 0; 1500 1501 log_fp = open_memstream(log_buf, log_cnt); 1502 if (!log_fp) 1503 return 1; 1504 1505 while (true) { 1506 struct msg msg; 1507 1508 if (read_prog_test_msg(sock_fd, &msg, MSG_TEST_LOG)) { 1509 result = 1; 1510 goto out; 1511 } 1512 1513 fprintf(log_fp, "%s", msg.test_log.log_buf); 1514 if (msg.test_log.is_last) 1515 break; 1516 } 1517 1518 out: 1519 fclose(log_fp); 1520 log_fp = NULL; 1521 return result; 1522 } 1523 1524 static int dispatch_thread_send_subtests(int sock_fd, struct test_state *state) 1525 { 1526 struct msg msg; 1527 struct subtest_state *subtest_state; 1528 int subtest_num = state->subtest_num; 1529 1530 state->subtest_states = calloc(subtest_num, sizeof(*subtest_state)); 1531 if (!state->subtest_states) { 1532 state->subtest_num = 0; 1533 return -ENOMEM; 1534 } 1535 1536 for (int i = 0; i < subtest_num; i++) { 1537 subtest_state = &state->subtest_states[i]; 1538 1539 if (read_prog_test_msg(sock_fd, &msg, MSG_SUBTEST_DONE)) 1540 return 1; 1541 1542 subtest_state->name = strdup(msg.subtest_done.name); 1543 subtest_state->error_cnt = msg.subtest_done.error_cnt; 1544 subtest_state->skipped = msg.subtest_done.skipped; 1545 subtest_state->filtered = msg.subtest_done.filtered; 1546 1547 /* collect all logs */ 1548 if (msg.subtest_done.have_log) 1549 if (dispatch_thread_read_log(sock_fd, 1550 &subtest_state->log_buf, 1551 &subtest_state->log_cnt)) 1552 return 1; 1553 } 1554 1555 return 0; 1556 } 1557 1558 static void *dispatch_thread(void *ctx) 1559 { 1560 struct dispatch_data *data = ctx; 1561 int sock_fd; 1562 1563 sock_fd = data->sock_fd; 1564 1565 while (true) { 1566 int test_to_run = -1; 1567 struct prog_test_def *test; 1568 struct test_state *state; 1569 1570 /* grab a test */ 1571 { 1572 pthread_mutex_lock(¤t_test_lock); 1573 1574 if (current_test_idx >= prog_test_cnt) { 1575 pthread_mutex_unlock(¤t_test_lock); 1576 goto done; 1577 } 1578 1579 test = &prog_test_defs[current_test_idx]; 1580 test_to_run = current_test_idx; 1581 current_test_idx++; 1582 1583 pthread_mutex_unlock(¤t_test_lock); 1584 } 1585 1586 if (!test->should_run || test->run_serial_test) 1587 continue; 1588 1589 /* run test through worker */ 1590 { 1591 struct msg msg_do_test; 1592 1593 memset(&msg_do_test, 0, sizeof(msg_do_test)); 1594 msg_do_test.type = MSG_DO_TEST; 1595 msg_do_test.do_test.num = test_to_run; 1596 if (send_message(sock_fd, &msg_do_test) < 0) { 1597 perror("Fail to send command"); 1598 goto done; 1599 } 1600 env.worker_current_test[data->worker_id] = test_to_run; 1601 } 1602 1603 /* wait for test done */ 1604 do { 1605 struct msg msg; 1606 1607 if (read_prog_test_msg(sock_fd, &msg, MSG_TEST_DONE)) 1608 goto error; 1609 if (test_to_run != msg.test_done.num) 1610 goto error; 1611 1612 state = &test_states[test_to_run]; 1613 state->tested = true; 1614 state->error_cnt = msg.test_done.error_cnt; 1615 state->skip_cnt = msg.test_done.skip_cnt; 1616 state->sub_succ_cnt = msg.test_done.sub_succ_cnt; 1617 state->subtest_num = msg.test_done.subtest_num; 1618 1619 /* collect all logs */ 1620 if (msg.test_done.have_log) { 1621 if (dispatch_thread_read_log(sock_fd, 1622 &state->log_buf, 1623 &state->log_cnt)) 1624 goto error; 1625 } 1626 1627 /* collect all subtests and subtest logs */ 1628 if (!state->subtest_num) 1629 break; 1630 1631 if (dispatch_thread_send_subtests(sock_fd, state)) 1632 goto error; 1633 } while (false); 1634 1635 pthread_mutex_lock(&stdout_output_lock); 1636 dump_test_log(test, state, false, true, false, NULL); 1637 pthread_mutex_unlock(&stdout_output_lock); 1638 } /* while (true) */ 1639 error: 1640 if (env.debug) 1641 fprintf(stderr, "[%d]: Protocol/IO error: %s.\n", data->worker_id, strerror(errno)); 1642 1643 done: 1644 { 1645 struct msg msg_exit; 1646 1647 msg_exit.type = MSG_EXIT; 1648 if (send_message(sock_fd, &msg_exit) < 0) { 1649 if (env.debug) 1650 fprintf(stderr, "[%d]: send_message msg_exit: %s.\n", 1651 data->worker_id, strerror(errno)); 1652 } 1653 } 1654 return NULL; 1655 } 1656 1657 static void calculate_summary_and_print_errors(struct test_env *env) 1658 { 1659 int i, j; 1660 int succ_cnt = 0, fail_cnt = 0, sub_succ_cnt = 0, sub_fail_cnt = 0, skip_cnt = 0; 1661 json_writer_t *w = NULL; 1662 1663 for (i = 0; i < prog_test_cnt; i++) { 1664 struct prog_test_def *test = &prog_test_defs[i]; 1665 struct test_state *state = &test_states[i]; 1666 1667 if (!state->tested) 1668 continue; 1669 1670 sub_succ_cnt += state->sub_succ_cnt; 1671 skip_cnt += state->skip_cnt; 1672 1673 if (state->error_cnt) { 1674 fail_cnt++; 1675 for (j = 0; j < state->subtest_num; j++) 1676 if (state->subtest_states[j].error_cnt) 1677 sub_fail_cnt++; 1678 } else if (!test->not_built) { 1679 succ_cnt++; 1680 } 1681 } 1682 1683 if (env->json) { 1684 w = jsonw_new(env->json); 1685 if (!w) 1686 fprintf(env->stderr_saved, "Failed to create new JSON stream."); 1687 } 1688 1689 if (w) { 1690 jsonw_start_object(w); 1691 jsonw_uint_field(w, "success", succ_cnt); 1692 jsonw_uint_field(w, "success_subtest", sub_succ_cnt); 1693 jsonw_uint_field(w, "skipped", skip_cnt); 1694 jsonw_uint_field(w, "failed", fail_cnt); 1695 jsonw_uint_field(w, "failed_subtest", sub_fail_cnt); 1696 jsonw_name(w, "results"); 1697 jsonw_start_array(w); 1698 } 1699 1700 /* 1701 * We only print error logs summary when there are failed tests and 1702 * verbose mode is not enabled. Otherwise, results may be inconsistent. 1703 * 1704 * --no-error-summary elides the human readable dump. The walk still 1705 * happens when a JSON report was requested, so the JSON output keeps 1706 * its per-test results; with no JSON report there is nothing left to 1707 * do and the whole loop is skipped. 1708 */ 1709 if (!verbose() && fail_cnt && (env->error_summary || w)) { 1710 if (env->error_summary) 1711 printf("\nAll error logs:\n"); 1712 1713 /* print error logs again */ 1714 for (i = 0; i < prog_test_cnt; i++) { 1715 struct prog_test_def *test = &prog_test_defs[i]; 1716 struct test_state *state = &test_states[i]; 1717 1718 if (!state->tested || !state->error_cnt) 1719 continue; 1720 1721 dump_test_log(test, state, true, true, 1722 !env->error_summary, w); 1723 } 1724 } 1725 1726 if (w) { 1727 jsonw_end_array(w); 1728 jsonw_end_object(w); 1729 jsonw_destroy(&w); 1730 } 1731 1732 if (env->json) 1733 fclose(env->json); 1734 1735 if (env->not_built_cnt) 1736 printf("Summary: %d/%d PASSED, %d SKIPPED (%d not built), %d/%d FAILED\n", 1737 succ_cnt, sub_succ_cnt, skip_cnt, env->not_built_cnt, 1738 fail_cnt, sub_fail_cnt); 1739 else 1740 printf("Summary: %d/%d PASSED, %d SKIPPED, %d/%d FAILED\n", 1741 succ_cnt, sub_succ_cnt, skip_cnt, fail_cnt, sub_fail_cnt); 1742 1743 env->succ_cnt = succ_cnt; 1744 env->sub_succ_cnt = sub_succ_cnt; 1745 env->fail_cnt = fail_cnt; 1746 env->skip_cnt = skip_cnt; 1747 } 1748 1749 static void server_main(void) 1750 { 1751 pthread_t *dispatcher_threads; 1752 struct dispatch_data *data; 1753 struct sigaction sigact_int = { 1754 .sa_handler = sigint_handler, 1755 .sa_flags = SA_RESETHAND, 1756 }; 1757 int i; 1758 1759 sigaction(SIGINT, &sigact_int, NULL); 1760 1761 dispatcher_threads = calloc(sizeof(pthread_t), env.workers); 1762 data = calloc(sizeof(struct dispatch_data), env.workers); 1763 1764 env.worker_current_test = calloc(sizeof(int), env.workers); 1765 for (i = 0; i < env.workers; i++) { 1766 int rc; 1767 1768 data[i].worker_id = i; 1769 data[i].sock_fd = env.worker_socks[i]; 1770 rc = pthread_create(&dispatcher_threads[i], NULL, dispatch_thread, &data[i]); 1771 if (rc) { 1772 perror("Failed to launch dispatcher thread"); 1773 exit(EXIT_ERR_SETUP_INFRA); 1774 } 1775 } 1776 1777 /* wait for all dispatcher to finish */ 1778 for (i = 0; i < env.workers; i++) { 1779 while (true) { 1780 int ret = pthread_tryjoin_np(dispatcher_threads[i], NULL); 1781 1782 if (!ret) { 1783 break; 1784 } else if (ret == EBUSY) { 1785 if (env.debug) 1786 fprintf(stderr, "Still waiting for thread %d (test %d).\n", 1787 i, env.worker_current_test[i] + 1); 1788 usleep(1000 * 1000); 1789 continue; 1790 } else { 1791 fprintf(stderr, "Unexpected error joining dispatcher thread: %d", ret); 1792 break; 1793 } 1794 } 1795 } 1796 free(dispatcher_threads); 1797 free(env.worker_current_test); 1798 free(data); 1799 1800 /* run serial tests */ 1801 save_netns(); 1802 1803 for (int i = 0; i < prog_test_cnt; i++) { 1804 struct prog_test_def *test = &prog_test_defs[i]; 1805 1806 if (!test->should_run || !test->run_serial_test) 1807 continue; 1808 1809 run_one_test(i); 1810 } 1811 1812 /* mark not-built tests as skipped */ 1813 for (int i = 0; i < prog_test_cnt; i++) { 1814 struct prog_test_def *test = &prog_test_defs[i]; 1815 struct test_state *state = &test_states[i]; 1816 1817 if (test->not_built && test->selected) { 1818 state->tested = true; 1819 state->skip_cnt = 1; 1820 env.not_built_cnt++; 1821 print_test_result(test, state); 1822 } 1823 } 1824 1825 /* generate summary */ 1826 fflush(stderr); 1827 fflush(stdout); 1828 1829 calculate_summary_and_print_errors(&env); 1830 1831 /* reap all workers */ 1832 for (i = 0; i < env.workers; i++) { 1833 int wstatus, pid; 1834 1835 pid = waitpid(env.worker_pids[i], &wstatus, 0); 1836 if (pid != env.worker_pids[i]) 1837 perror("Unable to reap worker"); 1838 } 1839 } 1840 1841 static void worker_main_send_log(int sock, char *log_buf, size_t log_cnt) 1842 { 1843 char *src; 1844 size_t slen; 1845 1846 src = log_buf; 1847 slen = log_cnt; 1848 while (slen) { 1849 struct msg msg_log; 1850 char *dest; 1851 size_t len; 1852 1853 memset(&msg_log, 0, sizeof(msg_log)); 1854 msg_log.type = MSG_TEST_LOG; 1855 dest = msg_log.test_log.log_buf; 1856 len = slen >= MAX_LOG_TRUNK_SIZE ? MAX_LOG_TRUNK_SIZE : slen; 1857 memcpy(dest, src, len); 1858 1859 src += len; 1860 slen -= len; 1861 if (!slen) 1862 msg_log.test_log.is_last = true; 1863 1864 assert(send_message(sock, &msg_log) >= 0); 1865 } 1866 } 1867 1868 static void free_subtest_state(struct subtest_state *state) 1869 { 1870 if (state->log_buf) { 1871 free(state->log_buf); 1872 state->log_buf = NULL; 1873 state->log_cnt = 0; 1874 } 1875 free(state->name); 1876 state->name = NULL; 1877 } 1878 1879 static int worker_main_send_subtests(int sock, struct test_state *state) 1880 { 1881 int i, result = 0; 1882 struct msg msg; 1883 struct subtest_state *subtest_state; 1884 1885 memset(&msg, 0, sizeof(msg)); 1886 msg.type = MSG_SUBTEST_DONE; 1887 1888 for (i = 0; i < state->subtest_num; i++) { 1889 subtest_state = &state->subtest_states[i]; 1890 1891 msg.subtest_done.num = i; 1892 1893 strscpy(msg.subtest_done.name, subtest_state->name, MAX_SUBTEST_NAME); 1894 1895 msg.subtest_done.error_cnt = subtest_state->error_cnt; 1896 msg.subtest_done.skipped = subtest_state->skipped; 1897 msg.subtest_done.filtered = subtest_state->filtered; 1898 msg.subtest_done.have_log = false; 1899 1900 if (verbose() || state->force_log || subtest_state->error_cnt) { 1901 if (subtest_state->log_cnt) 1902 msg.subtest_done.have_log = true; 1903 } 1904 1905 if (send_message(sock, &msg) < 0) { 1906 perror("Fail to send message done"); 1907 result = 1; 1908 goto out; 1909 } 1910 1911 /* send logs */ 1912 if (msg.subtest_done.have_log) 1913 worker_main_send_log(sock, subtest_state->log_buf, subtest_state->log_cnt); 1914 1915 free_subtest_state(subtest_state); 1916 } 1917 1918 out: 1919 for (; i < state->subtest_num; i++) 1920 free_subtest_state(&state->subtest_states[i]); 1921 free(state->subtest_states); 1922 return result; 1923 } 1924 1925 static int worker_main(int sock) 1926 { 1927 save_netns(); 1928 watchdog_init(); 1929 1930 while (true) { 1931 /* receive command */ 1932 struct msg msg; 1933 1934 if (recv_message(sock, &msg) < 0) 1935 goto out; 1936 1937 switch (msg.type) { 1938 case MSG_EXIT: 1939 if (env.debug) 1940 fprintf(stderr, "[%d]: worker exit.\n", 1941 env.worker_id); 1942 goto out; 1943 case MSG_DO_TEST: { 1944 int test_to_run = msg.do_test.num; 1945 struct prog_test_def *test = &prog_test_defs[test_to_run]; 1946 struct test_state *state = &test_states[test_to_run]; 1947 struct msg msg; 1948 1949 if (env.debug) 1950 fprintf(stderr, "[%d]: #%d:%s running.\n", 1951 env.worker_id, 1952 test_to_run + 1, 1953 test->test_name); 1954 1955 run_one_test(test_to_run); 1956 1957 memset(&msg, 0, sizeof(msg)); 1958 msg.type = MSG_TEST_DONE; 1959 msg.test_done.num = test_to_run; 1960 msg.test_done.error_cnt = state->error_cnt; 1961 msg.test_done.skip_cnt = state->skip_cnt; 1962 msg.test_done.sub_succ_cnt = state->sub_succ_cnt; 1963 msg.test_done.subtest_num = state->subtest_num; 1964 msg.test_done.have_log = false; 1965 1966 if (verbose() || state->force_log || state->error_cnt) { 1967 if (state->log_cnt) 1968 msg.test_done.have_log = true; 1969 } 1970 if (send_message(sock, &msg) < 0) { 1971 perror("Fail to send message done"); 1972 goto out; 1973 } 1974 1975 /* send logs */ 1976 if (msg.test_done.have_log) 1977 worker_main_send_log(sock, state->log_buf, state->log_cnt); 1978 1979 if (state->log_buf) { 1980 free(state->log_buf); 1981 state->log_buf = NULL; 1982 state->log_cnt = 0; 1983 } 1984 1985 if (state->subtest_num) 1986 if (worker_main_send_subtests(sock, state)) 1987 goto out; 1988 1989 if (env.debug) 1990 fprintf(stderr, "[%d]: #%d:%s done.\n", 1991 env.worker_id, 1992 test_to_run + 1, 1993 test->test_name); 1994 break; 1995 } /* case MSG_DO_TEST */ 1996 default: 1997 if (env.debug) 1998 fprintf(stderr, "[%d]: unknown message.\n", env.worker_id); 1999 return -1; 2000 } 2001 } 2002 out: 2003 return 0; 2004 } 2005 2006 static void free_test_states(void) 2007 { 2008 int i, j; 2009 2010 for (i = 0; i < ARRAY_SIZE(prog_test_defs); i++) { 2011 struct test_state *test_state = &test_states[i]; 2012 2013 for (j = 0; j < test_state->subtest_num; j++) 2014 free_subtest_state(&test_state->subtest_states[j]); 2015 2016 free(test_state->subtest_states); 2017 free(test_state->log_buf); 2018 test_state->subtest_states = NULL; 2019 test_state->log_buf = NULL; 2020 } 2021 } 2022 2023 static __u32 register_session_key(const char *key_data, size_t key_data_size) 2024 { 2025 return syscall(__NR_add_key, "asymmetric", "libbpf_session_key", 2026 (const void *)key_data, key_data_size, 2027 KEY_SPEC_SESSION_KEYRING); 2028 } 2029 2030 int main(int argc, char **argv) 2031 { 2032 static const struct argp argp = { 2033 .options = opts, 2034 .parser = parse_arg, 2035 .doc = argp_program_doc, 2036 }; 2037 int err, i; 2038 2039 #ifndef __SANITIZE_ADDRESS__ 2040 struct sigaction sigact = { 2041 .sa_handler = crash_handler, 2042 .sa_flags = SA_RESETHAND, 2043 }; 2044 sigaction(SIGSEGV, &sigact, NULL); 2045 #endif 2046 2047 env.stdout_saved = stdout; 2048 env.stderr_saved = stderr; 2049 2050 env.secs_till_notify = 10; 2051 env.secs_till_kill = 120; 2052 env.error_summary = true; 2053 err = argp_parse(&argp, argc, argv, 0, NULL, &env); 2054 if (err) 2055 return err; 2056 2057 err = cd_flavor_subdir(argv[0]); 2058 if (err) 2059 return err; 2060 2061 watchdog_init(); 2062 2063 /* Use libbpf 1.0 API mode */ 2064 libbpf_set_strict_mode(LIBBPF_STRICT_ALL); 2065 libbpf_set_print(libbpf_print_fn); 2066 err = register_session_key((const char *)test_progs_verification_cert, 2067 test_progs_verification_cert_len); 2068 if (err < 0) 2069 return err; 2070 2071 traffic_monitor_set_print(traffic_monitor_print_fn); 2072 2073 srand(time(NULL)); 2074 2075 env.jit_enabled = is_jit_enabled(); 2076 env.nr_cpus = libbpf_num_possible_cpus(); 2077 if (env.nr_cpus < 0) { 2078 fprintf(stderr, "Failed to get number of CPUs: %d!\n", 2079 env.nr_cpus); 2080 return -1; 2081 } 2082 2083 env.has_testmod = true; 2084 if (!env.list_test_names) { 2085 /* ensure previous instance of the module is unloaded */ 2086 unload_bpf_testmod(verbose()); 2087 2088 if (load_bpf_testmod(verbose())) { 2089 fprintf(env.stderr_saved, "WARNING! Selftests relying on bpf_testmod.ko will be skipped.\n"); 2090 env.has_testmod = false; 2091 } 2092 } 2093 2094 /* initializing tests */ 2095 for (i = 0; i < prog_test_cnt; i++) { 2096 struct prog_test_def *test = &prog_test_defs[i]; 2097 2098 test->test_num = i + 1; 2099 test->selected = should_run(&env.test_selector, 2100 test->test_num, test->test_name); 2101 test->should_run = test->selected; 2102 2103 if (test->run_test && test->run_serial_test) { 2104 fprintf(stderr, "Test %d:%s must have either test_%s() or serial_test_%sl() defined.\n", 2105 test->test_num, test->test_name, test->test_name, test->test_name); 2106 exit(EXIT_ERR_SETUP_INFRA); 2107 } 2108 if (!test->run_test && !test->run_serial_test) { 2109 test->not_built = true; 2110 test->should_run = false; 2111 continue; 2112 } 2113 if (test->should_run) 2114 test->should_tmon = should_tmon(&env.tmon_selector, test->test_name); 2115 } 2116 2117 /* ignore workers if we are just listing */ 2118 if (env.get_test_cnt || env.list_test_names) 2119 env.workers = 0; 2120 2121 /* launch workers if requested */ 2122 env.worker_id = -1; /* main process */ 2123 if (env.workers) { 2124 env.worker_pids = calloc(sizeof(pid_t), env.workers); 2125 env.worker_socks = calloc(sizeof(int), env.workers); 2126 if (env.debug) 2127 fprintf(stdout, "Launching %d workers.\n", env.workers); 2128 for (i = 0; i < env.workers; i++) { 2129 int sv[2]; 2130 pid_t pid; 2131 2132 if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sv) < 0) { 2133 perror("Fail to create worker socket"); 2134 return -1; 2135 } 2136 pid = fork(); 2137 if (pid < 0) { 2138 perror("Failed to fork worker"); 2139 return -1; 2140 } else if (pid != 0) { /* main process */ 2141 close(sv[1]); 2142 env.worker_pids[i] = pid; 2143 env.worker_socks[i] = sv[0]; 2144 } else { /* inside each worker process */ 2145 close(sv[0]); 2146 env.worker_id = i; 2147 return worker_main(sv[1]); 2148 } 2149 } 2150 2151 if (env.worker_id == -1) { 2152 server_main(); 2153 goto out; 2154 } 2155 } 2156 2157 /* The rest of the main process */ 2158 2159 /* on single mode */ 2160 save_netns(); 2161 2162 for (i = 0; i < prog_test_cnt; i++) { 2163 struct prog_test_def *test = &prog_test_defs[i]; 2164 struct test_state *state = &test_states[i]; 2165 2166 if (!test->should_run) { 2167 if (test->not_built && test->selected && 2168 !env.get_test_cnt && !env.list_test_names) { 2169 state->tested = true; 2170 state->skip_cnt = 1; 2171 env.not_built_cnt++; 2172 print_test_result(test, state); 2173 } 2174 continue; 2175 } 2176 2177 if (env.get_test_cnt) { 2178 env.succ_cnt++; 2179 continue; 2180 } 2181 2182 if (env.list_test_names) { 2183 fprintf(env.stdout_saved, "%s\n", test->test_name); 2184 env.succ_cnt++; 2185 continue; 2186 } 2187 2188 run_one_test(i); 2189 } 2190 2191 if (env.get_test_cnt) { 2192 printf("%d\n", env.succ_cnt); 2193 goto out; 2194 } 2195 2196 if (env.list_test_names) 2197 goto out; 2198 2199 calculate_summary_and_print_errors(&env); 2200 2201 close(env.saved_netns_fd); 2202 out: 2203 if (!env.list_test_names && env.has_testmod) 2204 unload_bpf_testmod(verbose()); 2205 2206 free_test_selector(&env.test_selector); 2207 free_test_selector(&env.subtest_selector); 2208 free_test_selector(&env.tmon_selector); 2209 free_test_states(); 2210 2211 if (env.succ_cnt + env.fail_cnt + env.skip_cnt == 0) 2212 return EXIT_NO_TEST; 2213 2214 return env.fail_cnt ? EXIT_FAILURE : EXIT_SUCCESS; 2215 } 2216