1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2021 Facebook */
3 
4 #include <linux/bpf.h>
5 #define BPF_NO_GLOBAL_DATA
6 #include <bpf/bpf_helpers.h>
7 
8 char LICENSE[] SEC("license") = "GPL";
9 
10 struct {
11 	__uint(type, BPF_MAP_TYPE_ARRAY);
12 	__type(key, int);
13 	__type(value, int);
14 	__uint(max_entries, 1);
15 } my_pid_map SEC(".maps");
16 
17 struct {
18 	__uint(type, BPF_MAP_TYPE_ARRAY);
19 	__type(key, int);
20 	__type(value, int);
21 	__uint(max_entries, 1);
22 } res_map SEC(".maps");
23 
24 volatile int my_pid_var = 0;
25 volatile int res_var = 0;
26 
27 SEC("tp/raw_syscalls/sys_enter")
28 int handle_legacy(void *ctx)
29 {
30 	int zero = 0, *my_pid, cur_pid, *my_res;
31 
32 	my_pid = bpf_map_lookup_elem(&my_pid_map, &zero);
33 	if (!my_pid)
34 		return 1;
35 
36 	cur_pid = bpf_get_current_pid_tgid() >> 32;
37 	if (cur_pid != *my_pid)
38 		return 1;
39 
40 	my_res = bpf_map_lookup_elem(&res_map, &zero);
41 	if (!my_res)
42 		return 1;
43 
44 	if (*my_res == 0)
45 		/* use bpf_printk() in combination with BPF_NO_GLOBAL_DATA to
46 		 * force .rodata.str1.1 section that previously caused
47 		 * problems on old kernels due to libbpf always tried to
48 		 * create a global data map for it
49 		 */
50 		bpf_printk("Legacy-case bpf_printk test, pid %d\n", cur_pid);
51 	*my_res = 1;
52 
53 	return *my_res;
54 }
55 
56 SEC("tp/raw_syscalls/sys_enter")
57 int handle_modern(void *ctx)
58 {
59 	int cur_pid;
60 
61 	cur_pid = bpf_get_current_pid_tgid() >> 32;
62 	if (cur_pid != my_pid_var)
63 		return 1;
64 
65 	if (res_var == 0)
66 		/* we need bpf_printk() to validate libbpf logic around unused
67 		 * global maps and legacy kernels; see comment in handle_legacy()
68 		 */
69 		bpf_printk("Modern-case bpf_printk test, pid %d\n", cur_pid);
70 	res_var = 1;
71 
72 	return res_var;
73 }
74