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