xref: /linux/tools/testing/selftests/bpf/progs/modify_return.c (revision 0fc8f6200d2313278fbf4539bbab74677c685531)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 /*
4  * Copyright 2020 Google LLC.
5  */
6 
7 #include <linux/bpf.h>
8 #include <bpf/bpf_helpers.h>
9 #include <bpf/bpf_tracing.h>
10 
11 char _license[] SEC("license") = "GPL";
12 
13 static int sequence = 0;
14 __s32 input_retval = 0;
15 __u32 test_pid = 0;
16 
17 __u64 fentry_result = 0;
18 SEC("fentry/bpf_modify_return_test")
19 int BPF_PROG(fentry_test, int a, __u64 b)
20 {
21 	if (bpf_get_current_pid_tgid() >> 32 != test_pid)
22 		return 0;
23 	sequence++;
24 	fentry_result = (sequence == 1);
25 	return 0;
26 }
27 
28 __u64 fmod_ret_result = 0;
29 SEC("fmod_ret/bpf_modify_return_test")
30 int BPF_PROG(fmod_ret_test, int a, int *b, int ret)
31 {
32 	if (bpf_get_current_pid_tgid() >> 32 != test_pid)
33 		return ret;
34 	sequence++;
35 	/* This is the first fmod_ret program, the ret passed should be 0 */
36 	fmod_ret_result = (sequence == 2 && ret == 0);
37 	return input_retval;
38 }
39 
40 __u64 fexit_result = 0;
41 SEC("fexit/bpf_modify_return_test")
42 int BPF_PROG(fexit_test, int a, __u64 b, int ret)
43 {
44 	if (bpf_get_current_pid_tgid() >> 32 != test_pid)
45 		return 0;
46 	sequence++;
47 	/* If the input_reval is non-zero a successful modification should have
48 	 * occurred.
49 	 */
50 	if (input_retval)
51 		fexit_result = (sequence == 3 && ret == input_retval);
52 	else
53 		fexit_result = (sequence == 3 && ret == 4);
54 
55 	return 0;
56 }
57 
58 static int sequence2;
59 
60 __u64 fentry_result2 = 0;
61 SEC("fentry/bpf_modify_return_test2")
62 int BPF_PROG(fentry_test2, int a, int *b, short c, int d, void *e, char f,
63 	     int g)
64 {
65 	if (bpf_get_current_pid_tgid() >> 32 != test_pid)
66 		return 0;
67 	sequence2++;
68 	fentry_result2 = (sequence2 == 1);
69 	return 0;
70 }
71 
72 __u64 fmod_ret_result2 = 0;
73 SEC("fmod_ret/bpf_modify_return_test2")
74 int BPF_PROG(fmod_ret_test2, int a, int *b, short c, int d, void *e, char f,
75 	     int g, int ret)
76 {
77 	if (bpf_get_current_pid_tgid() >> 32 != test_pid)
78 		return ret;
79 	sequence2++;
80 	/* This is the first fmod_ret program, the ret passed should be 0 */
81 	fmod_ret_result2 = (sequence2 == 2 && ret == 0);
82 	return input_retval;
83 }
84 
85 __u64 fexit_result2 = 0;
86 SEC("fexit/bpf_modify_return_test2")
87 int BPF_PROG(fexit_test2, int a, int *b, short c, int d, void *e, char f,
88 	     int g, int ret)
89 {
90 	if (bpf_get_current_pid_tgid() >> 32 != test_pid)
91 		return 0;
92 	sequence2++;
93 	/* If the input_reval is non-zero a successful modification should have
94 	 * occurred.
95 	 */
96 	if (input_retval)
97 		fexit_result2 = (sequence2 == 3 && ret == input_retval);
98 	else
99 		fexit_result2 = (sequence2 == 3 && ret == 29);
100 
101 	return 0;
102 }
103