1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2022 Meta Platforms, Inc. and affiliates. */
3 
4 #include "bpf_iter.h"
5 #include <bpf/bpf_helpers.h>
6 #include <bpf/bpf_tracing.h>
7 #include "bpf_misc.h"
8 
9 char _license[] SEC("license") = "GPL";
10 
11 struct {
12 	__uint(type, BPF_MAP_TYPE_CGRP_STORAGE);
13 	__uint(map_flags, BPF_F_NO_PREALLOC);
14 	__type(key, int);
15 	__type(value, long);
16 } map_a SEC(".maps");
17 
18 __u32 target_pid;
19 __u64 cgroup_id;
20 
21 void bpf_rcu_read_lock(void) __ksym;
22 void bpf_rcu_read_unlock(void) __ksym;
23 
24 SEC("?iter.s/cgroup")
25 int cgroup_iter(struct bpf_iter__cgroup *ctx)
26 {
27 	struct seq_file *seq = ctx->meta->seq;
28 	struct cgroup *cgrp = ctx->cgroup;
29 	long *ptr;
30 
31 	if (cgrp == NULL)
32 		return 0;
33 
34 	ptr = bpf_cgrp_storage_get(&map_a, cgrp, 0,
35 				   BPF_LOCAL_STORAGE_GET_F_CREATE);
36 	if (ptr)
37 		cgroup_id = cgrp->kn->id;
38 	return 0;
39 }
40 
41 SEC("?fentry.s/" SYS_PREFIX "sys_getpgid")
42 int no_rcu_lock(void *ctx)
43 {
44 	struct task_struct *task;
45 	struct cgroup *cgrp;
46 	long *ptr;
47 
48 	task = bpf_get_current_task_btf();
49 	if (task->pid != target_pid)
50 		return 0;
51 
52 	/* ptr_to_btf_id semantics. should work. */
53 	cgrp = task->cgroups->dfl_cgrp;
54 	ptr = bpf_cgrp_storage_get(&map_a, cgrp, 0,
55 				   BPF_LOCAL_STORAGE_GET_F_CREATE);
56 	if (ptr)
57 		cgroup_id = cgrp->kn->id;
58 	return 0;
59 }
60 
61 SEC("?fentry.s/" SYS_PREFIX "sys_getpgid")
62 int yes_rcu_lock(void *ctx)
63 {
64 	struct task_struct *task;
65 	struct cgroup *cgrp;
66 	long *ptr;
67 
68 	task = bpf_get_current_task_btf();
69 	if (task->pid != target_pid)
70 		return 0;
71 
72 	bpf_rcu_read_lock();
73 	cgrp = task->cgroups->dfl_cgrp;
74 	/* cgrp is untrusted and cannot pass to bpf_cgrp_storage_get() helper. */
75 	ptr = bpf_cgrp_storage_get(&map_a, cgrp, 0, BPF_LOCAL_STORAGE_GET_F_CREATE);
76 	if (ptr)
77 		cgroup_id = cgrp->kn->id;
78 	bpf_rcu_read_unlock();
79 	return 0;
80 }
81