utrace: Use PTHREAD_SEIZE instead of PTHREAD_TRACEME
[project/procd.git] / trace / trace.c
1 /*
2 * Copyright (C) 2015 John Crispin <blogic@openwrt.org>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU Lesser General Public License version 2.1
6 * as published by the Free Software Foundation
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 */
13
14 #define _GNU_SOURCE
15 #include <stddef.h>
16 #include <sys/ptrace.h>
17 #include <sys/types.h>
18 #include <sys/user.h>
19 #include <sys/wait.h>
20 #include <unistd.h>
21 #include <stdlib.h>
22 #include <stdio.h>
23 #include <errno.h>
24 #include <string.h>
25 #include <syslog.h>
26
27 #ifndef PTRACE_EVENT_STOP
28 /* PTRACE_EVENT_STOP is defined in linux/ptrace.h, but this header
29 * collides with musl's sys/ptrace.h */
30 #define PTRACE_EVENT_STOP 128
31 #endif
32
33 #include <libubox/uloop.h>
34 #include <libubox/blobmsg.h>
35 #include <libubox/blobmsg_json.h>
36
37 #include "../syscall-names.h"
38
39 #define _offsetof(a, b) __builtin_offsetof(a,b)
40 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
41
42 #ifdef __amd64__
43 #define reg_syscall_nr _offsetof(struct user, regs.orig_rax)
44 #elif defined(__i386__)
45 #define reg_syscall_nr _offsetof(struct user, regs.orig_eax)
46 #elif defined(__mips)
47 # ifndef EF_REG2
48 # define EF_REG2 8
49 # endif
50 #define reg_syscall_nr (EF_REG2 / 4)
51 #elif defined(__arm__)
52 #define reg_syscall_nr _offsetof(struct user, regs.uregs[7])
53 #else
54 #error tracing is not supported on this architecture
55 #endif
56
57 #define INFO(fmt, ...) do { \
58 fprintf(stderr, "utrace: "fmt, ## __VA_ARGS__); \
59 } while (0)
60
61 #define ERROR(fmt, ...) do { \
62 syslog(LOG_ERR, "utrace: "fmt, ## __VA_ARGS__); \
63 fprintf(stderr, "utrace: "fmt, ## __VA_ARGS__); \
64 } while (0)
65
66 struct tracee {
67 struct uloop_process proc;
68 int in_syscall;
69 };
70
71 static struct tracee tracer;
72 static int *syscall_count;
73 static struct blob_buf b;
74 static int syscall_max;
75 static int debug;
76
77 static int max_syscall = ARRAY_SIZE(syscall_names);
78
79 static void set_syscall(const char *name, int val)
80 {
81 int i;
82
83 for (i = 0; i < max_syscall; i++)
84 if (syscall_names[i] && !strcmp(syscall_names[i], name)) {
85 syscall_count[i] = val;
86 return;
87 }
88 }
89
90 struct syscall {
91 int syscall;
92 int count;
93 };
94
95 static int cmp_count(const void *a, const void *b)
96 {
97 return ((struct syscall*)b)->count - ((struct syscall*)a)->count;
98 }
99
100 static void print_syscalls(int policy, const char *json)
101 {
102 void *c;
103 int i;
104
105 set_syscall("rt_sigaction", 1);
106 set_syscall("sigreturn", 1);
107 set_syscall("rt_sigreturn", 1);
108 set_syscall("exit_group", 1);
109 set_syscall("exit", 1);
110
111 struct syscall sorted[ARRAY_SIZE(syscall_names)];
112
113 for (i = 0; i < ARRAY_SIZE(syscall_names); i++) {
114 sorted[i].syscall = i;
115 sorted[i].count = syscall_count[i];
116 }
117
118 qsort(sorted, ARRAY_SIZE(syscall_names), sizeof(sorted[0]), cmp_count);
119
120 blob_buf_init(&b, 0);
121 c = blobmsg_open_array(&b, "whitelist");
122
123 for (i = 0; i < ARRAY_SIZE(syscall_names); i++) {
124 int sc = sorted[i].syscall;
125 if (!sorted[i].count)
126 break;
127 if (syscall_names[sc]) {
128 if (debug)
129 printf("syscall %d (%s) was called %d times\n",
130 sc, syscall_names[sc], sorted[i].count);
131 blobmsg_add_string(&b, NULL, syscall_names[sc]);
132 } else {
133 ERROR("no name found for syscall(%d)\n", sc);
134 }
135 }
136 blobmsg_close_array(&b, c);
137 blobmsg_add_u32(&b, "policy", policy);
138 if (json) {
139 FILE *fp = fopen(json, "w");
140 if (fp) {
141 fprintf(fp, "%s", blobmsg_format_json_indent(b.head, true, 0));
142 fclose(fp);
143 INFO("saving syscall trace to %s\n", json);
144 } else {
145 ERROR("failed to open %s\n", json);
146 }
147 } else {
148 printf("%s\n",
149 blobmsg_format_json_indent(b.head, true, 0));
150 }
151
152 }
153
154 static void tracer_cb(struct uloop_process *c, int ret)
155 {
156 struct tracee *tracee = container_of(c, struct tracee, proc);
157 int inject_signal = 0;
158
159 /* We explicitely check for events in upper 16 bits, because
160 * musl (as opposed to glibc) does not report
161 * PTRACE_EVENT_STOP as WIFSTOPPED */
162 if (WIFSTOPPED(ret) || (ret >> 16)) {
163 if (WSTOPSIG(ret) & 0x80) {
164 if (!tracee->in_syscall) {
165 int syscall = ptrace(PTRACE_PEEKUSER, c->pid, reg_syscall_nr);
166
167 if (syscall < syscall_max) {
168 syscall_count[syscall]++;
169 if (debug)
170 fprintf(stderr, "%s()\n", syscall_names[syscall]);
171 } else if (debug) {
172 fprintf(stderr, "syscal(%d)\n", syscall);
173 }
174 }
175 tracee->in_syscall = !tracee->in_syscall;
176 } else if ((ret >> 8) == (SIGTRAP | (PTRACE_EVENT_FORK << 8)) ||
177 (ret >> 8) == (SIGTRAP | (PTRACE_EVENT_VFORK << 8)) ||
178 (ret >> 8) == (SIGTRAP | (PTRACE_EVENT_CLONE << 8))) {
179 struct tracee *child = calloc(1, sizeof(struct tracee));
180
181 ptrace(PTRACE_GETEVENTMSG, c->pid, 0, &child->proc.pid);
182 child->proc.cb = tracer_cb;
183 ptrace(PTRACE_SYSCALL, child->proc.pid, 0, 0);
184 uloop_process_add(&child->proc);
185 if (debug)
186 fprintf(stderr, "Tracing new child %d\n", child->proc.pid);
187 } else if ((ret >> 16) == PTRACE_EVENT_STOP) {
188 /* Nothing special to do here */
189 } else {
190 inject_signal = WSTOPSIG(ret);
191 if (debug)
192 fprintf(stderr, "Injecting signal %d into pid %d\n",
193 inject_signal, tracee->proc.pid);
194 }
195 } else if (WIFEXITED(ret) || (WIFSIGNALED(ret) && WTERMSIG(ret))) {
196 if (tracee == &tracer) {
197 uloop_end(); /* Main process exit */
198 } else {
199 if (debug)
200 fprintf(stderr, "Child %d exited\n", tracee->proc.pid);
201 free(tracee);
202 }
203 return;
204 }
205
206 ptrace(PTRACE_SYSCALL, c->pid, 0, inject_signal);
207 uloop_process_add(c);
208 }
209
210 int main(int argc, char **argv, char **envp)
211 {
212 char *json = NULL;
213 int status, ch, policy = EPERM;
214 pid_t child;
215
216 while ((ch = getopt(argc, argv, "f:p:")) != -1) {
217 switch (ch) {
218 case 'f':
219 json = optarg;
220 break;
221 case 'p':
222 policy = atoi(optarg);
223 break;
224 }
225 }
226
227 argc -= optind;
228 argv += optind;
229
230 if (!argc)
231 return -1;
232
233 if (getenv("TRACE_DEBUG"))
234 debug = 1;
235 unsetenv("TRACE_DEBUG");
236
237 child = fork();
238
239 if (child == 0) {
240 char **_argv = calloc(argc + 1, sizeof(char *));
241 char **_envp;
242 char *preload = "LD_PRELOAD=/lib/libpreload-trace.so";
243 int envc = 0;
244 int ret;
245
246 memcpy(_argv, argv, argc * sizeof(char *));
247
248 while (envp[envc++])
249 ;
250
251 _envp = calloc(envc + 1, sizeof(char *));
252 memcpy(&_envp[1], envp, envc * sizeof(char *));
253 *_envp = preload;
254
255 ret = execve(_argv[0], _argv, _envp);
256 ERROR("failed to exec %s: %s\n", _argv[0], strerror(errno));
257
258 free(_argv);
259 free(_envp);
260 return ret;
261 }
262
263 if (child < 0)
264 return -1;
265
266 syscall_max = ARRAY_SIZE(syscall_names);
267 syscall_count = calloc(syscall_max, sizeof(int));
268 waitpid(child, &status, WUNTRACED);
269 if (!WIFSTOPPED(status)) {
270 ERROR("failed to start %s\n", *argv);
271 return -1;
272 }
273
274 ptrace(PTRACE_SEIZE, child, 0,
275 PTRACE_O_TRACESYSGOOD |
276 PTRACE_O_TRACEFORK |
277 PTRACE_O_TRACEVFORK |
278 PTRACE_O_TRACECLONE);
279 ptrace(PTRACE_SYSCALL, child, 0, SIGCONT);
280
281 uloop_init();
282 tracer.proc.pid = child;
283 tracer.proc.cb = tracer_cb;
284 uloop_process_add(&tracer.proc);
285 uloop_run();
286 uloop_done();
287
288 if (!json)
289 if (asprintf(&json, "/tmp/%s.%u.json", basename(*argv), child) < 0)
290 ERROR("failed to allocate output path: %s\n", strerror(errno));
291
292 print_syscalls(policy, json);
293
294 return 0;
295 }