-
Notifications
You must be signed in to change notification settings - Fork 25
/
main.bpf.c
67 lines (55 loc) · 1.83 KB
/
main.bpf.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#include <bpf/bpf_core_read.h>
#include "main.h"
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 10240);
__type(key, pid_t);
__type(value, struct event_t);
} entries SEC(".maps");
struct {
__uint(type, BPF_MAP_TYPE_PERF_EVENT_ARRAY);
__uint(key_size, sizeof(u32));
__uint(value_size, sizeof(u32));
} events SEC(".maps");
static void get_file_path(const struct path *path, char *buf, size_t size)
{
struct qstr dname;
dname = BPF_CORE_READ(path, dentry, d_name);
bpf_probe_read_kernel(buf, size, dname.name);
}
SEC("kprobe/vfs_open")
int BPF_KPROBE(kprobe_vfs_open, const struct path *path, struct file *file) {
pid_t tid;
struct event_t event = {};
tid = (pid_t)bpf_get_current_pid_tgid();
event.pid = bpf_get_current_pid_tgid() >> 32;
bpf_get_current_comm(&event.comm, sizeof(event.comm));
// 获取打开模式
event.fmode = BPF_CORE_READ(file, f_mode);
// 获取文件名称
get_file_path(path, event.filename, sizeof(event.filename));
// 保存获取到的 event 信息
bpf_map_update_elem(&entries, &tid, &event, BPF_NOEXIST);
return 0;
}
SEC("kretprobe/vfs_open")
int BPF_KRETPROBE(kretprobe_vfs_open, long ret) {
pid_t tid;
struct event_t *event;
// 获取 kprobe_vfs_open 中保存的 event 信息
tid = (pid_t)bpf_get_current_pid_tgid();
event = bpf_map_lookup_elem(&entries, &tid);
if (!event)
return 0;
// 保存执行结果
event->ret = (int)ret;
// 将事件提交到 events 中供用户态程序消费
bpf_perf_event_output(ctx, &events, BPF_F_CURRENT_CPU, event, sizeof(*event));
// 删除保存的 event 信息
bpf_map_delete_elem(&entries, &tid);
return 0;
}
char _license[] SEC("license") = "GPL";