Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 /* Copyright (c) 2021 Facebook */
0003 
0004 #include <linux/bpf.h>
0005 #define BPF_NO_GLOBAL_DATA
0006 #include <bpf/bpf_helpers.h>
0007 
0008 char LICENSE[] SEC("license") = "GPL";
0009 
0010 struct {
0011     __uint(type, BPF_MAP_TYPE_ARRAY);
0012     __type(key, int);
0013     __type(value, int);
0014     __uint(max_entries, 1);
0015 } my_pid_map SEC(".maps");
0016 
0017 struct {
0018     __uint(type, BPF_MAP_TYPE_ARRAY);
0019     __type(key, int);
0020     __type(value, int);
0021     __uint(max_entries, 1);
0022 } res_map SEC(".maps");
0023 
0024 volatile int my_pid_var = 0;
0025 volatile int res_var = 0;
0026 
0027 SEC("tp/raw_syscalls/sys_enter")
0028 int handle_legacy(void *ctx)
0029 {
0030     int zero = 0, *my_pid, cur_pid, *my_res;
0031 
0032     my_pid = bpf_map_lookup_elem(&my_pid_map, &zero);
0033     if (!my_pid)
0034         return 1;
0035 
0036     cur_pid = bpf_get_current_pid_tgid() >> 32;
0037     if (cur_pid != *my_pid)
0038         return 1;
0039 
0040     my_res = bpf_map_lookup_elem(&res_map, &zero);
0041     if (!my_res)
0042         return 1;
0043 
0044     if (*my_res == 0)
0045         /* use bpf_printk() in combination with BPF_NO_GLOBAL_DATA to
0046          * force .rodata.str1.1 section that previously caused
0047          * problems on old kernels due to libbpf always tried to
0048          * create a global data map for it
0049          */
0050         bpf_printk("Legacy-case bpf_printk test, pid %d\n", cur_pid);
0051     *my_res = 1;
0052 
0053     return *my_res;
0054 }
0055 
0056 SEC("tp/raw_syscalls/sys_enter")
0057 int handle_modern(void *ctx)
0058 {
0059     int zero = 0, cur_pid;
0060 
0061     cur_pid = bpf_get_current_pid_tgid() >> 32;
0062     if (cur_pid != my_pid_var)
0063         return 1;
0064 
0065     if (res_var == 0)
0066         /* we need bpf_printk() to validate libbpf logic around unused
0067          * global maps and legacy kernels; see comment in handle_legacy()
0068          */
0069         bpf_printk("Modern-case bpf_printk test, pid %d\n", cur_pid);
0070     res_var = 1;
0071 
0072     return res_var;
0073 }