xref: /linux/tools/testing/selftests/bpf/progs/test_d_path.c (revision b61104e7a6349bd2c2b3e2fb3260d87f15eda8f4)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include "vmlinux.h"
4 #include <bpf/bpf_helpers.h>
5 #include <bpf/bpf_tracing.h>
6 
7 #define MAX_PATH_LEN		128
8 #define MAX_FILES		7
9 
10 pid_t my_pid = 0;
11 __u32 cnt_stat = 0;
12 __u32 cnt_close = 0;
13 char paths_stat[MAX_FILES][MAX_PATH_LEN] = {};
14 char paths_close[MAX_FILES][MAX_PATH_LEN] = {};
15 int rets_stat[MAX_FILES] = {};
16 int rets_close[MAX_FILES] = {};
17 
18 int called_stat = 0;
19 int called_close = 0;
20 int path_match_fallocate = 0;
21 
22 SEC("fentry/security_inode_getattr")
23 int BPF_PROG(prog_stat, struct path *path, struct kstat *stat,
24 	     __u32 request_mask, unsigned int query_flags)
25 {
26 	pid_t pid = bpf_get_current_pid_tgid() >> 32;
27 	__u32 cnt = cnt_stat;
28 	int ret;
29 
30 	called_stat = 1;
31 
32 	if (pid != my_pid)
33 		return 0;
34 
35 	if (cnt >= MAX_FILES)
36 		return 0;
37 	ret = bpf_d_path(path, paths_stat[cnt], MAX_PATH_LEN);
38 
39 	rets_stat[cnt] = ret;
40 	cnt_stat++;
41 	return 0;
42 }
43 
44 SEC("fentry/filp_close")
45 int BPF_PROG(prog_close, struct file *file, void *id)
46 {
47 	pid_t pid = bpf_get_current_pid_tgid() >> 32;
48 	__u32 cnt = cnt_close;
49 	int ret;
50 
51 	called_close = 1;
52 
53 	if (pid != my_pid)
54 		return 0;
55 
56 	if (cnt >= MAX_FILES)
57 		return 0;
58 	ret = bpf_d_path(&file->f_path,
59 			 paths_close[cnt], MAX_PATH_LEN);
60 
61 	rets_close[cnt] = ret;
62 	cnt_close++;
63 	return 0;
64 }
65 
66 SEC("fentry/vfs_fallocate")
67 int BPF_PROG(prog_fallocate, struct file *file, int mode, loff_t offset, loff_t len)
68 {
69 	pid_t pid = bpf_get_current_pid_tgid() >> 32;
70 	int ret = 0;
71 	char path_fallocate[MAX_PATH_LEN] = {};
72 
73 	if (pid != my_pid)
74 		return 0;
75 
76 	ret = bpf_d_path(&file->f_path,
77 			 path_fallocate, MAX_PATH_LEN);
78 	if (ret < 0)
79 		return 0;
80 
81 	if (!path_fallocate[0])
82 		return 0;
83 
84 	path_match_fallocate = 1;
85 	return 0;
86 }
87 
88 char _license[] SEC("license") = "GPL";
89