• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
17 #include <bpf/libbpf.h>
18 #include <bpf/bpf.h>
19 #include "exitsnoop.h"
20 #include "exitsnoop.skel.h"
21 #include "trace_helpers.h"
22 
23 #define PERF_BUFFER_PAGES	16
24 #define PERF_POLL_TIMEOUT_MS	100
25 #define warn(...) fprintf(stderr, __VA_ARGS__)
26 
27 static volatile sig_atomic_t exiting = 0;
28 
29 static bool emit_timestamp = false;
30 static pid_t target_pid = 0;
31 static bool trace_failed_only = false;
32 static bool trace_by_process = true;
33 static bool verbose = false;
34 
35 const char *argp_program_version = "exitsnoop 0.1";
36 const char *argp_program_bug_address =
37 	"https://github.com/iovisor/bcc/tree/master/libbpf-tools";
38 const char argp_program_doc[] =
39 "Trace process termination.\n"
40 "\n"
41 "USAGE: exitsnoop [-h] [-t] [-x] [-p PID] [-T]\n"
42 "\n"
43 "EXAMPLES:\n"
44 "    exitsnoop             # trace process exit events\n"
45 "    exitsnoop -t          # include timestamps\n"
46 "    exitsnoop -x          # trace error exits only\n"
47 "    exitsnoop -p 1216     # only trace PID 1216\n"
48 "    exitsnoop -T          # trace by thread\n";
49 
50 static const struct argp_option opts[] = {
51 	{ "timestamp", 't', NULL, 0, "Include timestamp on output" },
52 	{ "failed", 'x', NULL, 0, "Trace error exits only." },
53 	{ "pid", 'p', "PID", 0, "Process ID to trace" },
54 	{ "threaded", 'T', NULL, 0, "Trace by thread." },
55 	{ "verbose", 'v', NULL, 0, "Verbose debug output" },
56 	{ NULL, 'h', NULL, OPTION_HIDDEN, "Show the full help" },
57 	{},
58 };
59 
parse_arg(int key,char * arg,struct argp_state * state)60 static error_t parse_arg(int key, char *arg, struct argp_state *state)
61 {
62 	long pid;
63 
64 	switch (key) {
65 	case 'p':
66 		errno = 0;
67 		pid = strtol(arg, NULL, 10);
68 		if (errno || pid <= 0) {
69 			warn("Invalid PID: %s\n", arg);
70 			argp_usage(state);
71 		}
72 		target_pid = pid;
73 		break;
74 	case 't':
75 		emit_timestamp = true;
76 		break;
77 	case 'x':
78 		trace_failed_only = true;
79 		break;
80 	case 'T':
81 		trace_by_process = false;
82 		break;
83 	case 'v':
84 		verbose = true;
85 		break;
86 	case 'h':
87 		argp_state_help(state, stderr, ARGP_HELP_STD_HELP);
88 		break;
89 	default:
90 		return ARGP_ERR_UNKNOWN;
91 	}
92 	return 0;
93 }
94 
libbpf_print_fn(enum libbpf_print_level level,const char * format,va_list args)95 static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args)
96 {
97 	if (level == LIBBPF_DEBUG && !verbose)
98 		return 0;
99 	return vfprintf(stderr, format, args);
100 }
101 
sig_int(int signo)102 static void sig_int(int signo)
103 {
104 	exiting = 1;
105 }
106 
handle_event(void * ctx,int cpu,void * data,__u32 data_sz)107 static void handle_event(void *ctx, int cpu, void *data, __u32 data_sz)
108 {
109 	struct event *e = data;
110 	time_t t;
111 	struct tm *tm;
112 	char ts[32];
113 	double age;
114 	int sig, coredump;
115 
116 	if (emit_timestamp) {
117 		time(&t);
118 		tm = localtime(&t);
119 		strftime(ts, sizeof(ts), "%H:%M:%S", tm);
120 		printf("%8s ", ts);
121 	}
122 
123 	age = (e->exit_time - e->start_time) / 1e9;
124 	printf("%-16s %-7d %-7d %-7d %-7.2f ",
125 	       e->comm, e->pid, e->ppid, e->tid, age);
126 
127 	if (!e->sig) {
128 		if (!e->exit_code)
129 			printf("0\n");
130 		else
131 			printf("code %d\n", e->exit_code);
132 	} else {
133 		sig = e->sig & 0x7f;
134 		coredump = e->sig & 0x80;
135 		if (sig)
136 			printf("signal %d (%s)", sig, strsignal(sig));
137 		if (coredump)
138 			printf(", core dumped");
139 		printf("\n");
140 	}
141 }
142 
handle_lost_events(void * ctx,int cpu,__u64 lost_cnt)143 static void handle_lost_events(void *ctx, int cpu, __u64 lost_cnt)
144 {
145 	warn("lost %llu events on CPU #%d\n", lost_cnt, cpu);
146 }
147 
main(int argc,char ** argv)148 int main(int argc, char **argv)
149 {
150 	static const struct argp argp = {
151 		.options = opts,
152 		.parser = parse_arg,
153 		.doc = argp_program_doc,
154 	};
155 	struct perf_buffer *pb = NULL;
156 	struct exitsnoop_bpf *obj;
157 	int err;
158 
159 	err = argp_parse(&argp, argc, argv, 0, NULL, NULL);
160 	if (err)
161 		return err;
162 
163 	libbpf_set_strict_mode(LIBBPF_STRICT_ALL);
164 	libbpf_set_print(libbpf_print_fn);
165 
166 	obj = exitsnoop_bpf__open();
167 	if (!obj) {
168 		warn("failed to open BPF object\n");
169 		return 1;
170 	}
171 
172 	obj->rodata->target_pid = target_pid;
173 	obj->rodata->trace_failed_only = trace_failed_only;
174 	obj->rodata->trace_by_process = trace_by_process;
175 
176 	err = exitsnoop_bpf__load(obj);
177 	if (err) {
178 		warn("failed to load BPF object: %d\n", err);
179 		goto cleanup;
180 	}
181 
182 	err = exitsnoop_bpf__attach(obj);
183 	if (err) {
184 		warn("failed to attach BPF programs: %d\n", err);
185 		goto cleanup;
186 	}
187 
188 	pb = perf_buffer__new(bpf_map__fd(obj->maps.events), PERF_BUFFER_PAGES,
189 			      handle_event, handle_lost_events, NULL, NULL);
190 	if (!pb) {
191 		err = -errno;
192 		warn("failed to open perf buffer: %d\n", err);
193 		goto cleanup;
194 	}
195 
196 	if (signal(SIGINT, sig_int) == SIG_ERR) {
197 		warn("can't set signal handler: %s\n", strerror(errno));
198 		err = 1;
199 		goto cleanup;
200 	}
201 
202 	if (emit_timestamp)
203 		printf("%-8s ", "TIME(s)");
204 	printf("%-16s %-7s %-7s %-7s %-7s %-s\n",
205 	       "PCOMM", "PID", "PPID", "TID", "AGE(s)", "EXIT_CODE");
206 
207 	while (!exiting) {
208 		err = perf_buffer__poll(pb, PERF_POLL_TIMEOUT_MS);
209 		if (err < 0 && err != -EINTR) {
210 			warn("error polling perf buffer: %s\n", strerror(-err));
211 			goto cleanup;
212 		}
213 		/* reset err to return 0 if exiting */
214 		err = 0;
215 	}
216 
217 cleanup:
218 	perf_buffer__free(pb);
219 	exitsnoop_bpf__destroy(obj);
220 
221 	return err != 0;
222 }
223