xref: /linux/tools/testing/selftests/bpf/prog_tests/vmlinux.c (revision a0fa68d8ce759dbf6aaf19a043ddd77a2128c26c)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2020 Facebook */
3 
4 #include <test_progs.h>
5 #include <time.h>
6 #include "test_vmlinux.skel.h"
7 
8 #define MY_TV_NSEC 1337
9 
10 static void nsleep()
11 {
12 	struct timespec ts = { .tv_nsec = MY_TV_NSEC };
13 
14 	(void)syscall(__NR_nanosleep, &ts, NULL);
15 }
16 
17 static const char *hrtimer_func = "hrtimer_start_range_ns";
18 
19 static int setup_hrtimer_progs(struct test_vmlinux *skel)
20 {
21 	int err;
22 
23 	if (libbpf_find_vmlinux_btf_id("hrtimer_start_range_ns_user", BPF_TRACE_FENTRY) > 0)
24 		hrtimer_func = "hrtimer_start_range_ns_user";
25 
26 	err = bpf_program__set_attach_target(skel->progs.handle__fentry, 0, hrtimer_func);
27 	if (err)
28 		return err;
29 
30 	/*
31 	 * Bare SEC("kprobe") has no target function, so attach it manually
32 	 * later after selecting the hrtimer function to probe.
33 	 */
34 	bpf_program__set_autoattach(skel->progs.handle__kprobe, false);
35 
36 	return 0;
37 }
38 
39 void test_vmlinux(void)
40 {
41 	int err;
42 	struct test_vmlinux* skel;
43 	struct test_vmlinux__bss *bss;
44 	struct bpf_link *kprobe_link = NULL;
45 
46 	skel = test_vmlinux__open();
47 	if (!ASSERT_OK_PTR(skel, "test_vmlinux__open"))
48 		return;
49 
50 	err = setup_hrtimer_progs(skel);
51 	if (!ASSERT_OK(err, "setup_hrtimer_progs"))
52 		goto cleanup;
53 
54 	err = test_vmlinux__load(skel);
55 	if (!ASSERT_OK(err, "test_vmlinux__load"))
56 		goto cleanup;
57 
58 	bss = skel->bss;
59 
60 	err = test_vmlinux__attach(skel);
61 	if (!ASSERT_OK(err, "test_vmlinux__attach"))
62 		goto cleanup;
63 
64 	/* manually attach kprobe with the selected function */
65 	if (hrtimer_func) {
66 		kprobe_link = bpf_program__attach_kprobe(skel->progs.handle__kprobe,
67 							 false /* retprobe */, hrtimer_func);
68 		if (!ASSERT_OK_PTR(kprobe_link, "bpf_program__attach_kprobe"))
69 			goto cleanup;
70 	}
71 
72 	/* trigger everything */
73 	nsleep();
74 
75 	ASSERT_TRUE(bss->tp_called, "tp");
76 	ASSERT_TRUE(bss->raw_tp_called, "raw_tp");
77 	ASSERT_TRUE(bss->tp_btf_called, "tp_btf");
78 	ASSERT_TRUE(bss->kprobe_called, "kprobe");
79 	ASSERT_TRUE(bss->fentry_called, "fentry");
80 
81 cleanup:
82 	bpf_link__destroy(kprobe_link);
83 	test_vmlinux__destroy(skel);
84 }
85