1 /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
2
3 /*
4 * mountsnoop Trace mount and umount[2] syscalls
5 *
6 * Copyright (c) 2021 Hengqi Chen
7 * 30-May-2021 Hengqi Chen Created this.
8 */
9 #ifndef _GNU_SOURCE
10 #define _GNU_SOURCE
11 #endif
12 #include <argp.h>
13 #include <errno.h>
14 #include <signal.h>
15 #include <string.h>
16 #include <time.h>
17 #include <unistd.h>
18
19 #include <bpf/libbpf.h>
20 #include <bpf/bpf.h>
21 #include "mountsnoop.h"
22 #include "mountsnoop.skel.h"
23 #include "compat.h"
24 #include "btf_helpers.h"
25 #include "trace_helpers.h"
26
27 #define warn(...) fprintf(stderr, __VA_ARGS__)
28
29 /* https://www.gnu.org/software/gnulib/manual/html_node/strerrorname_005fnp.html */
30 #if !defined(__GLIBC__) || __GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 32)
strerrorname_np(int errnum)31 const char *strerrorname_np(int errnum)
32 {
33 return NULL;
34 }
35 #endif
36
37 static volatile sig_atomic_t exiting = 0;
38
39 static pid_t target_pid = 0;
40 static bool emit_timestamp = false;
41 static bool output_vertically = false;
42 static bool verbose = false;
43 static const char *flag_names[] = {
44 [0] = "MS_RDONLY",
45 [1] = "MS_NOSUID",
46 [2] = "MS_NODEV",
47 [3] = "MS_NOEXEC",
48 [4] = "MS_SYNCHRONOUS",
49 [5] = "MS_REMOUNT",
50 [6] = "MS_MANDLOCK",
51 [7] = "MS_DIRSYNC",
52 [8] = "MS_NOSYMFOLLOW",
53 [9] = "MS_NOATIME",
54 [10] = "MS_NODIRATIME",
55 [11] = "MS_BIND",
56 [12] = "MS_MOVE",
57 [13] = "MS_REC",
58 [14] = "MS_VERBOSE",
59 [15] = "MS_SILENT",
60 [16] = "MS_POSIXACL",
61 [17] = "MS_UNBINDABLE",
62 [18] = "MS_PRIVATE",
63 [19] = "MS_SLAVE",
64 [20] = "MS_SHARED",
65 [21] = "MS_RELATIME",
66 [22] = "MS_KERNMOUNT",
67 [23] = "MS_I_VERSION",
68 [24] = "MS_STRICTATIME",
69 [25] = "MS_LAZYTIME",
70 [26] = "MS_SUBMOUNT",
71 [27] = "MS_NOREMOTELOCK",
72 [28] = "MS_NOSEC",
73 [29] = "MS_BORN",
74 [30] = "MS_ACTIVE",
75 [31] = "MS_NOUSER",
76 };
77 static const int flag_count = sizeof(flag_names) / sizeof(flag_names[0]);
78
79 const char *argp_program_version = "mountsnoop 0.1";
80 const char *argp_program_bug_address =
81 "https://github.com/iovisor/bcc/tree/master/libbpf-tools";
82 const char argp_program_doc[] =
83 "Trace mount and umount syscalls.\n"
84 "\n"
85 "USAGE: mountsnoop [-h] [-t] [-p PID] [-v]\n"
86 "\n"
87 "EXAMPLES:\n"
88 " mountsnoop # trace mount and umount syscalls\n"
89 " mountsnoop -d # detailed output (one line per column value)\n"
90 " mountsnoop -p 1216 # only trace PID 1216\n";
91
92 static const struct argp_option opts[] = {
93 { "pid", 'p', "PID", 0, "Process ID to trace" },
94 { "timestamp", 't', NULL, 0, "Include timestamp on output" },
95 { "detailed", 'd', NULL, 0, "Output result in detail mode" },
96 { "verbose", 'v', NULL, 0, "Verbose debug output" },
97 { NULL, 'h', NULL, OPTION_HIDDEN, "Show the full help" },
98 {},
99 };
100
parse_arg(int key,char * arg,struct argp_state * state)101 static error_t parse_arg(int key, char *arg, struct argp_state *state)
102 {
103 long pid;
104
105 switch (key) {
106 case 'p':
107 errno = 0;
108 pid = strtol(arg, NULL, 10);
109 if (errno || pid <= 0) {
110 warn("Invalid PID: %s\n", arg);
111 argp_usage(state);
112 }
113 target_pid = pid;
114 break;
115 case 't':
116 emit_timestamp = true;
117 break;
118 case 'd':
119 output_vertically = true;
120 break;
121 case 'v':
122 verbose = true;
123 break;
124 case 'h':
125 argp_state_help(state, stderr, ARGP_HELP_STD_HELP);
126 break;
127 default:
128 return ARGP_ERR_UNKNOWN;
129 }
130 return 0;
131 }
132
libbpf_print_fn(enum libbpf_print_level level,const char * format,va_list args)133 static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args)
134 {
135 if (level == LIBBPF_DEBUG && !verbose)
136 return 0;
137 return vfprintf(stderr, format, args);
138 }
139
sig_int(int signo)140 static void sig_int(int signo)
141 {
142 exiting = 1;
143 }
144
strflags(__u64 flags)145 static const char *strflags(__u64 flags)
146 {
147 static char str[512];
148 int i;
149
150 if (!flags)
151 return "0x0";
152
153 str[0] = '\0';
154 for (i = 0; i < flag_count; i++) {
155 if (!((1 << i) & flags))
156 continue;
157 if (str[0])
158 strcat(str, " | ");
159 strcat(str, flag_names[i]);
160 }
161 return str;
162 }
163
strerrno(int errnum)164 static const char *strerrno(int errnum)
165 {
166 const char *errstr;
167 static char ret[32] = {};
168
169 if (!errnum)
170 return "0";
171
172 ret[0] = '\0';
173 errstr = strerrorname_np(-errnum);
174 if (!errstr) {
175 snprintf(ret, sizeof(ret), "%d", errnum);
176 return ret;
177 }
178
179 snprintf(ret, sizeof(ret), "-%s", errstr);
180 return ret;
181 }
182
gen_call(const struct event * e)183 static const char *gen_call(const struct event *e)
184 {
185 static char call[10240];
186
187 memset(call, 0, sizeof(call));
188 if (e->op == UMOUNT) {
189 snprintf(call, sizeof(call), "umount(\"%s\", %s) = %s",
190 e->dest, strflags(e->flags), strerrno(e->ret));
191 } else {
192 snprintf(call, sizeof(call), "mount(\"%s\", \"%s\", \"%s\", %s, \"%s\") = %s",
193 e->src, e->dest, e->fs, strflags(e->flags), e->data, strerrno(e->ret));
194 }
195 return call;
196 }
197
handle_event(void * ctx,void * data,size_t len)198 static int handle_event(void *ctx, void *data, size_t len)
199 {
200 const struct event *e = data;
201 struct tm *tm;
202 char ts[32];
203 time_t t;
204 const char *indent;
205 static const char *op_name[] = {
206 [MOUNT] = "MOUNT",
207 [UMOUNT] = "UMOUNT",
208 };
209
210 if (emit_timestamp) {
211 time(&t);
212 tm = localtime(&t);
213 strftime(ts, sizeof(ts), "%H:%M:%S ", tm);
214 printf("%s", ts);
215 indent = " ";
216 } else {
217 indent = "";
218 }
219 if (!output_vertically) {
220 printf("%-16s %-7d %-7d %-11u %s\n",
221 e->comm, e->pid, e->tid, e->mnt_ns, gen_call(e));
222 return 0;
223 }
224 if (emit_timestamp)
225 printf("\n");
226 printf("%sPID: %d\n", indent, e->pid);
227 printf("%sTID: %d\n", indent, e->tid);
228 printf("%sCOMM: %s\n", indent, e->comm);
229 printf("%sOP: %s\n", indent, op_name[e->op]);
230 printf("%sRET: %s\n", indent, strerrno(e->ret));
231 printf("%sLAT: %lldus\n", indent, e->delta / 1000);
232 printf("%sMNT_NS: %u\n", indent, e->mnt_ns);
233 printf("%sFS: %s\n", indent, e->fs);
234 printf("%sSOURCE: %s\n", indent, e->src);
235 printf("%sTARGET: %s\n", indent, e->dest);
236 printf("%sDATA: %s\n", indent, e->data);
237 printf("%sFLAGS: %s\n", indent, strflags(e->flags));
238 printf("\n");
239
240 return 0;
241 }
242
handle_lost_events(void * ctx,int cpu,__u64 lost_cnt)243 static void handle_lost_events(void *ctx, int cpu, __u64 lost_cnt)
244 {
245 warn("lost %llu events on CPU #%d\n", lost_cnt, cpu);
246 }
247
main(int argc,char ** argv)248 int main(int argc, char **argv)
249 {
250 LIBBPF_OPTS(bpf_object_open_opts, open_opts);
251 static const struct argp argp = {
252 .options = opts,
253 .parser = parse_arg,
254 .doc = argp_program_doc,
255 };
256 struct bpf_buffer *buf = NULL;
257 struct mountsnoop_bpf *obj;
258 int err;
259
260 err = argp_parse(&argp, argc, argv, 0, NULL, NULL);
261 if (err)
262 return err;
263
264 libbpf_set_print(libbpf_print_fn);
265
266 err = ensure_core_btf(&open_opts);
267 if (err) {
268 fprintf(stderr, "failed to fetch necessary BTF for CO-RE: %s\n", strerror(-err));
269 return 1;
270 }
271
272 obj = mountsnoop_bpf__open_opts(&open_opts);
273 if (!obj) {
274 warn("failed to open BPF object\n");
275 return 1;
276 }
277
278 obj->rodata->target_pid = target_pid;
279
280 buf = bpf_buffer__new(obj->maps.events, obj->maps.heap);
281 if (!buf) {
282 err = -errno;
283 warn("failed to create ring/perf buffer: %d\n", err);
284 goto cleanup;
285 }
286
287 err = mountsnoop_bpf__load(obj);
288 if (err) {
289 warn("failed to load BPF object: %d\n", err);
290 goto cleanup;
291 }
292
293 err = mountsnoop_bpf__attach(obj);
294 if (err) {
295 warn("failed to attach BPF programs: %d\n", err);
296 goto cleanup;
297 }
298
299 err = bpf_buffer__open(buf, handle_event, handle_lost_events, NULL);
300 if (err) {
301 warn("failed to open ring/perf buffer: %d\n", err);
302 goto cleanup;
303 }
304
305 if (signal(SIGINT, sig_int) == SIG_ERR) {
306 warn("can't set signal handler: %s\n", strerror(errno));
307 err = 1;
308 goto cleanup;
309 }
310
311 if (!output_vertically) {
312 if (emit_timestamp)
313 printf("%-8s ", "TIME");
314 printf("%-16s %-7s %-7s %-11s %s\n", "COMM", "PID", "TID", "MNT_NS", "CALL");
315 }
316
317 while (!exiting) {
318 err = bpf_buffer__poll(buf, POLL_TIMEOUT_MS);
319 if (err < 0 && err != -EINTR) {
320 fprintf(stderr, "error polling ring/perf buffer: %s\n", strerror(-err));
321 goto cleanup;
322 }
323 /* reset err to return 0 if exiting */
324 err = 0;
325 }
326
327 cleanup:
328 bpf_buffer__free(buf);
329 mountsnoop_bpf__destroy(obj);
330 cleanup_core_btf(&open_opts);
331
332 return err != 0;
333 }
334