f882c2e0d5a14a2d5e110634d9456e87eb3c4daf
[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 #include <libubox/uloop.h>
28 #include <libubox/blobmsg.h>
29 #include <libubox/blobmsg_json.h>
30
31 #include "../syscall-names.h"
32
33 #define _offsetof(a, b) __builtin_offsetof(a,b)
34 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
35
36 #ifdef __amd64__
37 #define reg_syscall_nr  _offsetof(struct user, regs.orig_rax)
38 #elif defined(__i386__)
39 #define reg_syscall_nr  _offsetof(struct user, regs.orig_eax)
40 #elif defined(__mips)
41 # ifndef EF_REG2
42 # define EF_REG2        8
43 # endif
44 #define reg_syscall_nr  (EF_REG2 / 4)
45 #elif defined(__arm__)
46 #define reg_syscall_nr  _offsetof(struct user, regs.uregs[7])
47 #else
48 #error tracing is not supported on this architecture
49 #endif
50
51 #define INFO(fmt, ...) do { \
52         fprintf(stderr, "utrace: "fmt, ## __VA_ARGS__); \
53 } while (0)
54
55 #define ERROR(fmt, ...) do { \
56         syslog(LOG_ERR, "utrace: "fmt, ## __VA_ARGS__); \
57         fprintf(stderr, "utrace: "fmt, ## __VA_ARGS__); \
58 } while (0)
59
60 struct tracee {
61         struct uloop_process proc;
62         int in_syscall;
63 };
64
65 static struct tracee tracer;
66 static int *syscall_count;
67 static struct blob_buf b;
68 static int syscall_max;
69 static int debug;
70
71 static int max_syscall = ARRAY_SIZE(syscall_names);
72
73 static void set_syscall(const char *name, int val)
74 {
75         int i;
76
77         for (i = 0; i < max_syscall; i++)
78                 if (syscall_names[i] && !strcmp(syscall_names[i], name)) {
79                         syscall_count[i] = val;
80                         return;
81                 }
82 }
83
84 struct syscall {
85         int syscall;
86         int count;
87 };
88
89 static int cmp_count(const void *a, const void *b)
90 {
91         return ((struct syscall*)b)->count - ((struct syscall*)a)->count;
92 }
93
94 static void print_syscalls(int policy, const char *json)
95 {
96         void *c;
97         int i;
98
99         set_syscall("rt_sigaction", 1);
100         set_syscall("sigreturn", 1);
101         set_syscall("rt_sigreturn", 1);
102         set_syscall("exit_group", 1);
103         set_syscall("exit", 1);
104
105         struct syscall sorted[ARRAY_SIZE(syscall_names)];
106
107         for (i = 0; i < ARRAY_SIZE(syscall_names); i++) {
108                 sorted[i].syscall = i;
109                 sorted[i].count = syscall_count[i];
110         }
111
112         qsort(sorted, ARRAY_SIZE(syscall_names), sizeof(sorted[0]), cmp_count);
113
114         blob_buf_init(&b, 0);
115         c = blobmsg_open_array(&b, "whitelist");
116
117         for (i = 0; i < ARRAY_SIZE(syscall_names); i++) {
118                 int sc = sorted[i].syscall;
119                 if (!sorted[i].count)
120                         break;
121                 if (syscall_names[sc]) {
122                         if (debug)
123                                 printf("syscall %d (%s) was called %d times\n",
124                                         sc, syscall_names[sc], sorted[i].count);
125                         blobmsg_add_string(&b, NULL, syscall_names[sc]);
126                 } else {
127                         ERROR("no name found for syscall(%d)\n", sc);
128                 }
129         }
130         blobmsg_close_array(&b, c);
131         blobmsg_add_u32(&b, "policy", policy);
132         if (json) {
133                 FILE *fp = fopen(json, "w");
134                 if (fp) {
135                         fprintf(fp, "%s", blobmsg_format_json_indent(b.head, true, 0));
136                         fclose(fp);
137                         INFO("saving syscall trace to %s\n", json);
138                 } else {
139                         ERROR("failed to open %s\n", json);
140                 }
141         } else {
142                 printf("%s\n",
143                         blobmsg_format_json_indent(b.head, true, 0));
144         }
145
146 }
147
148 static void tracer_cb(struct uloop_process *c, int ret)
149 {
150         struct tracee *tracee = container_of(c, struct tracee, proc);
151
152         if (WIFSTOPPED(ret)) {
153                 if (WSTOPSIG(ret) & 0x80) {
154                         if (!tracee->in_syscall) {
155                                 int syscall = ptrace(PTRACE_PEEKUSER, c->pid, reg_syscall_nr);
156
157                                 if (syscall < syscall_max) {
158                                         syscall_count[syscall]++;
159                                         if (debug)
160                                                 fprintf(stderr, "%s()\n", syscall_names[syscall]);
161                                 } else if (debug) {
162                                         fprintf(stderr, "syscal(%d)\n", syscall);
163                                 }
164                         }
165                         tracee->in_syscall = !tracee->in_syscall;
166                 } else if ((ret >> 8) == (SIGTRAP | (PTRACE_EVENT_FORK << 8))) {
167                         struct tracee *child = calloc(1, sizeof(struct tracee));
168
169                         ptrace(PTRACE_GETEVENTMSG, c->pid, 0, &child->proc.pid);
170                         child->proc.cb = tracer_cb;
171                         ptrace(PTRACE_SYSCALL, child->proc.pid, 0, 0);
172                         uloop_process_add(&child->proc);
173                         if (debug)
174                                 fprintf(stderr, "Tracing new child %d\n", child->proc.pid);
175                 }
176         } else if (WIFEXITED(ret)) {
177                 if (tracee == &tracer) {
178                         uloop_end(); /* Main process exit */
179                 } else {
180                         if (debug)
181                                 fprintf(stderr, "Child %d exited\n", tracee->proc.pid);
182                         free(tracee);
183                 }
184                 return;
185         }
186
187         ptrace(PTRACE_SYSCALL, c->pid, 0, 0);
188         uloop_process_add(c);
189 }
190
191 int main(int argc, char **argv, char **envp)
192 {
193         char *json = NULL;
194         int status, ch, policy = EPERM;
195         pid_t child;
196
197         while ((ch = getopt(argc, argv, "f:p:")) != -1) {
198                 switch (ch) {
199                 case 'f':
200                         json = optarg;
201                         break;
202                 case 'p':
203                         policy = atoi(optarg);
204                         break;
205                 }
206         }
207
208         argc -= optind;
209         argv += optind;
210
211         if (!argc)
212                 return -1;
213
214         if (getenv("TRACE_DEBUG"))
215                 debug = 1;
216         unsetenv("TRACE_DEBUG");
217
218         child = fork();
219
220         if (child == 0) {
221                 char **_argv = calloc(argc + 1, sizeof(char *));
222                 char **_envp;
223                 char *preload = "LD_PRELOAD=/lib/libpreload-trace.so";
224                 int envc = 0;
225                 int ret;
226
227                 memcpy(_argv, argv, argc * sizeof(char *));
228
229                 while (envp[envc++])
230                         ;
231
232                 _envp = calloc(envc + 1, sizeof(char *));
233                 memcpy(&_envp[1], envp, envc * sizeof(char *));
234                 *_envp = preload;
235
236                 ret = execve(_argv[0], _argv, _envp);
237                 ERROR("failed to exec %s: %s\n", _argv[0], strerror(errno));
238
239                 free(_argv);
240                 free(_envp);
241                 return ret;
242         }
243
244         if (child < 0)
245                 return -1;
246
247         syscall_max = ARRAY_SIZE(syscall_names);
248         syscall_count = calloc(syscall_max, sizeof(int));
249         waitpid(child, &status, 0);
250         if (!WIFSTOPPED(status)) {
251                 ERROR("failed to start %s\n", *argv);
252                 return -1;
253         }
254
255         ptrace(PTRACE_SETOPTIONS, child, 0,
256                PTRACE_O_TRACESYSGOOD |
257                PTRACE_O_TRACEFORK);
258         ptrace(PTRACE_SYSCALL, child, 0, 0);
259
260         uloop_init();
261         tracer.proc.pid = child;
262         tracer.proc.cb = tracer_cb;
263         uloop_process_add(&tracer.proc);
264         uloop_run();
265         uloop_done();
266
267         if (!json)
268                 if (asprintf(&json, "/tmp/%s.%u.json", basename(*argv), child) < 0)
269                         ERROR("failed to allocate output path: %s\n", strerror(errno));
270
271         print_syscalls(policy, json);
272
273         return 0;
274 }