xref: /linux/tools/testing/selftests/bpf/prog_tests/trampoline_count.c (revision 9f2c9170934eace462499ba0bfe042cc72900173)
1 // SPDX-License-Identifier: GPL-2.0-only
2 #define _GNU_SOURCE
3 #include <test_progs.h>
4 
5 #define MAX_TRAMP_PROGS 38
6 
7 struct inst {
8 	struct bpf_object *obj;
9 	struct bpf_link   *link;
10 };
11 
12 static struct bpf_program *load_prog(char *file, char *name, struct inst *inst)
13 {
14 	struct bpf_object *obj;
15 	struct bpf_program *prog;
16 	int err;
17 
18 	obj = bpf_object__open_file(file, NULL);
19 	if (!ASSERT_OK_PTR(obj, "obj_open_file"))
20 		return NULL;
21 
22 	inst->obj = obj;
23 
24 	err = bpf_object__load(obj);
25 	if (!ASSERT_OK(err, "obj_load"))
26 		return NULL;
27 
28 	prog = bpf_object__find_program_by_name(obj, name);
29 	if (!ASSERT_OK_PTR(prog, "obj_find_prog"))
30 		return NULL;
31 
32 	return prog;
33 }
34 
35 /* TODO: use different target function to run in concurrent mode */
36 void serial_test_trampoline_count(void)
37 {
38 	char *file = "test_trampoline_count.bpf.o";
39 	char *const progs[] = { "fentry_test", "fmod_ret_test", "fexit_test" };
40 	struct inst inst[MAX_TRAMP_PROGS + 1] = {};
41 	struct bpf_program *prog;
42 	struct bpf_link *link;
43 	int prog_fd, err, i;
44 	LIBBPF_OPTS(bpf_test_run_opts, opts);
45 
46 	/* attach 'allowed' trampoline programs */
47 	for (i = 0; i < MAX_TRAMP_PROGS; i++) {
48 		prog = load_prog(file, progs[i % ARRAY_SIZE(progs)], &inst[i]);
49 		if (!prog)
50 			goto cleanup;
51 
52 		link = bpf_program__attach(prog);
53 		if (!ASSERT_OK_PTR(link, "attach_prog"))
54 			goto cleanup;
55 
56 		inst[i].link = link;
57 	}
58 
59 	/* and try 1 extra.. */
60 	prog = load_prog(file, "fmod_ret_test", &inst[i]);
61 	if (!prog)
62 		goto cleanup;
63 
64 	/* ..that needs to fail */
65 	link = bpf_program__attach(prog);
66 	if (!ASSERT_ERR_PTR(link, "attach_prog")) {
67 		inst[i].link = link;
68 		goto cleanup;
69 	}
70 
71 	/* with E2BIG error */
72 	if (!ASSERT_EQ(libbpf_get_error(link), -E2BIG, "E2BIG"))
73 		goto cleanup;
74 	if (!ASSERT_EQ(link, NULL, "ptr_is_null"))
75 		goto cleanup;
76 
77 	/* and finaly execute the probe */
78 	prog_fd = bpf_program__fd(prog);
79 	if (!ASSERT_GE(prog_fd, 0, "bpf_program__fd"))
80 		goto cleanup;
81 
82 	err = bpf_prog_test_run_opts(prog_fd, &opts);
83 	if (!ASSERT_OK(err, "bpf_prog_test_run_opts"))
84 		goto cleanup;
85 
86 	ASSERT_EQ(opts.retval & 0xffff, 4, "bpf_modify_return_test.result");
87 	ASSERT_EQ(opts.retval >> 16, 1, "bpf_modify_return_test.side_effect");
88 
89 cleanup:
90 	for (; i >= 0; i--) {
91 		bpf_link__destroy(inst[i].link);
92 		bpf_object__close(inst[i].obj);
93 	}
94 }
95