1 // SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
2 /* Copyright (c) 2020 Facebook */
3 #include <vmlinux.h>
4 #include <bpf/bpf_helpers.h>
5 #include <bpf/bpf_core_read.h>
6 #include <bpf/bpf_tracing.h>
7 #include "pid_iter.h"
8
9 /* keep in sync with the definition in main.h */
10 enum bpf_obj_type {
11 BPF_OBJ_UNKNOWN,
12 BPF_OBJ_PROG,
13 BPF_OBJ_MAP,
14 BPF_OBJ_LINK,
15 BPF_OBJ_BTF,
16 };
17
18 extern const void bpf_link_fops __ksym;
19 extern const void bpf_map_fops __ksym;
20 extern const void bpf_prog_fops __ksym;
21 extern const void btf_fops __ksym;
22
23 const volatile enum bpf_obj_type obj_type = BPF_OBJ_UNKNOWN;
24
get_obj_id(void * ent,enum bpf_obj_type type)25 static __always_inline __u32 get_obj_id(void *ent, enum bpf_obj_type type)
26 {
27 switch (type) {
28 case BPF_OBJ_PROG:
29 return BPF_CORE_READ((struct bpf_prog *)ent, aux, id);
30 case BPF_OBJ_MAP:
31 return BPF_CORE_READ((struct bpf_map *)ent, id);
32 case BPF_OBJ_BTF:
33 return BPF_CORE_READ((struct btf *)ent, id);
34 case BPF_OBJ_LINK:
35 return BPF_CORE_READ((struct bpf_link *)ent, id);
36 default:
37 return 0;
38 }
39 }
40
41 SEC("iter/task_file")
iter(struct bpf_iter__task_file * ctx)42 int iter(struct bpf_iter__task_file *ctx)
43 {
44 struct file *file = ctx->file;
45 struct task_struct *task = ctx->task;
46 struct pid_iter_entry e;
47 const void *fops;
48
49 if (!file || !task)
50 return 0;
51
52 switch (obj_type) {
53 case BPF_OBJ_PROG:
54 fops = &bpf_prog_fops;
55 break;
56 case BPF_OBJ_MAP:
57 fops = &bpf_map_fops;
58 break;
59 case BPF_OBJ_BTF:
60 fops = &btf_fops;
61 break;
62 case BPF_OBJ_LINK:
63 fops = &bpf_link_fops;
64 break;
65 default:
66 return 0;
67 }
68
69 if (file->f_op != fops)
70 return 0;
71
72 e.pid = task->tgid;
73 e.id = get_obj_id(file->private_data, obj_type);
74 bpf_probe_read_kernel(&e.comm, sizeof(e.comm),
75 task->group_leader->comm);
76 bpf_seq_write(ctx->meta->seq, &e, sizeof(e));
77
78 return 0;
79 }
80
81 char LICENSE[] SEC("license") = "Dual BSD/GPL";
82