1 /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
2
3 /*
4 * exitsnoop Trace process termination.
5 *
6 * Copyright (c) 2021 Hengqi Chen
7 *
8 * Based on exitsnoop(8) from BCC by Arturo Martin-de-Nicolas & Jeroen Soeters.
9 * 05-Aug-2021 Hengqi Chen Created this.
10 */
11 #include <argp.h>
12 #include <errno.h>
13 #include <signal.h>
14 #include <string.h>
15 #include <time.h>
16 #include <fcntl.h>
17 #include <unistd.h>
18
19 #include <bpf/libbpf.h>
20 #include <bpf/bpf.h>
21 #include "exitsnoop.h"
22 #include "exitsnoop.skel.h"
23 #include "btf_helpers.h"
24 #include "trace_helpers.h"
25
26 #define PERF_BUFFER_PAGES 16
27 #define PERF_POLL_TIMEOUT_MS 100
28 #define warn(...) fprintf(stderr, __VA_ARGS__)
29
30 static volatile sig_atomic_t exiting = 0;
31
32 static bool emit_timestamp = false;
33 static pid_t target_pid = 0;
34 static bool trace_failed_only = false;
35 static bool trace_by_process = true;
36 static bool verbose = false;
37
38 static struct env {
39 char *cgroupspath;
40 bool cg;
41 } env;
42
43 const char *argp_program_version = "exitsnoop 0.1";
44 const char *argp_program_bug_address =
45 "https://github.com/iovisor/bcc/tree/master/libbpf-tools";
46 const char argp_program_doc[] =
47 "Trace process termination.\n"
48 "\n"
49 "USAGE: exitsnoop [-h] [-t] [-x] [-p PID] [-T] [-c CG]\n"
50 "\n"
51 "EXAMPLES:\n"
52 " exitsnoop # trace process exit events\n"
53 " exitsnoop -t # include timestamps\n"
54 " exitsnoop -x # trace error exits only\n"
55 " exitsnoop -p 1216 # only trace PID 1216\n"
56 " exitsnoop -T # trace by thread\n"
57 " exitsnoop -c CG # Trace process under cgroupsPath CG\n";
58
59 static const struct argp_option opts[] = {
60 { "timestamp", 't', NULL, 0, "Include timestamp on output" },
61 { "failed", 'x', NULL, 0, "Trace error exits only." },
62 { "pid", 'p', "PID", 0, "Process ID to trace" },
63 { "threaded", 'T', NULL, 0, "Trace by thread." },
64 { "verbose", 'v', NULL, 0, "Verbose debug output" },
65 { NULL, 'h', NULL, OPTION_HIDDEN, "Show the full help" },
66 { "cgroup", 'c', "/sys/fs/cgroup/unified", 0, "Trace process in cgroup path"},
67 {},
68 };
69
parse_arg(int key,char * arg,struct argp_state * state)70 static error_t parse_arg(int key, char *arg, struct argp_state *state)
71 {
72 long pid;
73
74 switch (key) {
75 case 'p':
76 errno = 0;
77 pid = strtol(arg, NULL, 10);
78 if (errno || pid <= 0) {
79 warn("Invalid PID: %s\n", arg);
80 argp_usage(state);
81 }
82 target_pid = pid;
83 break;
84 case 't':
85 emit_timestamp = true;
86 break;
87 case 'x':
88 trace_failed_only = true;
89 break;
90 case 'T':
91 trace_by_process = false;
92 break;
93 case 'v':
94 verbose = true;
95 break;
96 case 'c':
97 env.cgroupspath = arg;
98 env.cg = true;
99 break;
100 case 'h':
101 argp_state_help(state, stderr, ARGP_HELP_STD_HELP);
102 break;
103 default:
104 return ARGP_ERR_UNKNOWN;
105 }
106 return 0;
107 }
108
libbpf_print_fn(enum libbpf_print_level level,const char * format,va_list args)109 static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args)
110 {
111 if (level == LIBBPF_DEBUG && !verbose)
112 return 0;
113 return vfprintf(stderr, format, args);
114 }
115
sig_int(int signo)116 static void sig_int(int signo)
117 {
118 exiting = 1;
119 }
120
handle_event(void * ctx,int cpu,void * data,__u32 data_sz)121 static void handle_event(void *ctx, int cpu, void *data, __u32 data_sz)
122 {
123 struct event *e = data;
124 time_t t;
125 struct tm *tm;
126 char ts[32];
127 double age;
128 int sig, coredump;
129
130 if (emit_timestamp) {
131 time(&t);
132 tm = localtime(&t);
133 strftime(ts, sizeof(ts), "%H:%M:%S", tm);
134 printf("%8s ", ts);
135 }
136
137 age = (e->exit_time - e->start_time) / 1e9;
138 printf("%-16s %-7d %-7d %-7d %-7.2f ",
139 e->comm, e->pid, e->ppid, e->tid, age);
140
141 if (!e->sig) {
142 if (!e->exit_code)
143 printf("0\n");
144 else
145 printf("code %d\n", e->exit_code);
146 } else {
147 sig = e->sig & 0x7f;
148 coredump = e->sig & 0x80;
149 if (sig)
150 printf("signal %d (%s)", sig, strsignal(sig));
151 if (coredump)
152 printf(", core dumped");
153 printf("\n");
154 }
155 }
156
handle_lost_events(void * ctx,int cpu,__u64 lost_cnt)157 static void handle_lost_events(void *ctx, int cpu, __u64 lost_cnt)
158 {
159 warn("lost %llu events on CPU #%d\n", lost_cnt, cpu);
160 }
161
main(int argc,char ** argv)162 int main(int argc, char **argv)
163 {
164 LIBBPF_OPTS(bpf_object_open_opts, open_opts);
165 static const struct argp argp = {
166 .options = opts,
167 .parser = parse_arg,
168 .doc = argp_program_doc,
169 };
170 struct perf_buffer *pb = NULL;
171 struct exitsnoop_bpf *obj;
172 int err;
173 int idx, cg_map_fd;
174 int cgfd = -1;
175
176 err = argp_parse(&argp, argc, argv, 0, NULL, NULL);
177 if (err)
178 return err;
179
180 libbpf_set_print(libbpf_print_fn);
181
182 err = ensure_core_btf(&open_opts);
183 if (err) {
184 fprintf(stderr, "failed to fetch necessary BTF for CO-RE: %s\n", strerror(-err));
185 return 1;
186 }
187
188 obj = exitsnoop_bpf__open_opts(&open_opts);
189 if (!obj) {
190 warn("failed to open BPF object\n");
191 return 1;
192 }
193
194 obj->rodata->target_pid = target_pid;
195 obj->rodata->trace_failed_only = trace_failed_only;
196 obj->rodata->trace_by_process = trace_by_process;
197 obj->rodata->filter_cg = env.cg;
198
199 err = exitsnoop_bpf__load(obj);
200 if (err) {
201 warn("failed to load BPF object: %d\n", err);
202 goto cleanup;
203 }
204
205 /* update cgroup path fd to map */
206 if (env.cg) {
207 idx = 0;
208 cg_map_fd = bpf_map__fd(obj->maps.cgroup_map);
209 cgfd = open(env.cgroupspath, O_RDONLY);
210 if (cgfd < 0) {
211 fprintf(stderr, "Failed opening Cgroup path: %s", env.cgroupspath);
212 goto cleanup;
213 }
214 if (bpf_map_update_elem(cg_map_fd, &idx, &cgfd, BPF_ANY)) {
215 fprintf(stderr, "Failed adding target cgroup to map");
216 goto cleanup;
217 }
218 }
219
220 err = exitsnoop_bpf__attach(obj);
221 if (err) {
222 warn("failed to attach BPF programs: %d\n", err);
223 goto cleanup;
224 }
225
226 pb = perf_buffer__new(bpf_map__fd(obj->maps.events), PERF_BUFFER_PAGES,
227 handle_event, handle_lost_events, NULL, NULL);
228 if (!pb) {
229 err = -errno;
230 warn("failed to open perf buffer: %d\n", err);
231 goto cleanup;
232 }
233
234 if (signal(SIGINT, sig_int) == SIG_ERR) {
235 warn("can't set signal handler: %s\n", strerror(errno));
236 err = 1;
237 goto cleanup;
238 }
239
240 if (emit_timestamp)
241 printf("%-8s ", "TIME(s)");
242 printf("%-16s %-7s %-7s %-7s %-7s %-s\n",
243 "PCOMM", "PID", "PPID", "TID", "AGE(s)", "EXIT_CODE");
244
245 while (!exiting) {
246 err = perf_buffer__poll(pb, PERF_POLL_TIMEOUT_MS);
247 if (err < 0 && err != -EINTR) {
248 warn("error polling perf buffer: %s\n", strerror(-err));
249 goto cleanup;
250 }
251 /* reset err to return 0 if exiting */
252 err = 0;
253 }
254
255 cleanup:
256 perf_buffer__free(pb);
257 exitsnoop_bpf__destroy(obj);
258 cleanup_core_btf(&open_opts);
259 if (cgfd > 0)
260 close(cgfd);
261
262 return err != 0;
263 }
264