1 // SPDX-License-Identifier: GPL-2.0 2 /* Copyright (c) 2025 Meta Platforms, Inc. and affiliates. */ 3 4 #include <test_progs.h> 5 #include <network_helpers.h> 6 #include "file_reader.skel.h" 7 #include "file_reader_fail.skel.h" 8 #include <dlfcn.h> 9 #include <sys/mman.h> 10 11 const char *user_ptr = "hello world"; 12 char file_contents[256000]; 13 void *addr; 14 15 void *get_executable_base_addr(void) 16 { 17 Dl_info info; 18 19 if (!dladdr((void *)&get_executable_base_addr, &info)) { 20 fprintf(stderr, "dladdr failed\n"); 21 return NULL; 22 } 23 24 return info.dli_fbase; 25 } 26 27 static int initialize_file_contents(void) 28 { 29 int fd, page_sz = sysconf(_SC_PAGESIZE); 30 ssize_t n = 0, cur; 31 32 fd = open("/proc/self/exe", O_RDONLY); 33 if (!ASSERT_OK_FD(fd, "Open /proc/self/exe\n")) 34 return 1; 35 36 do { 37 cur = read(fd, file_contents + n, sizeof(file_contents) - n); 38 if (!ASSERT_GT(cur, 0, "read success")) 39 break; 40 n += cur; 41 } while (n < sizeof(file_contents)); 42 43 close(fd); 44 45 if (!ASSERT_EQ(n, sizeof(file_contents), "Read /proc/self/exe\n")) 46 return 1; 47 48 addr = get_executable_base_addr(); 49 if (!ASSERT_NEQ(addr, NULL, "get executable address")) 50 return 1; 51 52 /* page-align base file address */ 53 addr = (void *)((unsigned long)addr & ~(page_sz - 1)); 54 55 return 0; 56 } 57 58 static void run_test(const char *prog_name) 59 { 60 struct file_reader *skel; 61 struct bpf_program *prog; 62 int err, fd; 63 64 err = initialize_file_contents(); 65 if (!ASSERT_OK(err, "initialize file contents")) 66 return; 67 68 skel = file_reader__open(); 69 if (!ASSERT_OK_PTR(skel, "file_reader__open")) 70 return; 71 72 bpf_object__for_each_program(prog, skel->obj) { 73 bpf_program__set_autoload(prog, strcmp(bpf_program__name(prog), prog_name) == 0); 74 } 75 76 memcpy(skel->bss->user_buf, file_contents, sizeof(file_contents)); 77 skel->bss->pid = getpid(); 78 79 err = file_reader__load(skel); 80 if (!ASSERT_OK(err, "file_reader__load")) 81 goto cleanup; 82 83 /* 84 * Page out range 0..512K, use 0..256K for positive tests and 85 * 256K..512K for negative tests expecting page faults 86 */ 87 if (!ASSERT_OK(madvise(addr, sizeof(file_contents) * 2, MADV_PAGEOUT), 88 "madvise pageout")) 89 goto cleanup; 90 91 err = file_reader__attach(skel); 92 if (!ASSERT_OK(err, "file_reader__attach")) 93 goto cleanup; 94 95 fd = open("/proc/self/exe", O_RDONLY); 96 if (fd >= 0) 97 close(fd); 98 99 ASSERT_EQ(skel->bss->err, 0, "err"); 100 ASSERT_EQ(skel->bss->run_success, 1, "run_success"); 101 cleanup: 102 file_reader__destroy(skel); 103 } 104 105 void test_file_reader(void) 106 { 107 if (test__start_subtest("on_open_expect_fault")) 108 run_test("on_open_expect_fault"); 109 110 if (test__start_subtest("on_open_validate_file_read")) 111 run_test("on_open_validate_file_read"); 112 113 if (test__start_subtest("negative")) 114 RUN_TESTS(file_reader_fail); 115 } 116