utrace: Sort syscalls by number of invocations
[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 static struct uloop_process tracer;
61 static int *syscall_count;
62 static struct blob_buf b;
63 static int syscall_max;
64 static int in_syscall;
65 static int debug;
66
67 static int max_syscall = ARRAY_SIZE(syscall_names);
68
69 static void set_syscall(const char *name, int val)
70 {
71         int i;
72
73         for (i = 0; i < max_syscall; i++)
74                 if (syscall_names[i] && !strcmp(syscall_names[i], name)) {
75                         syscall_count[i] = val;
76                         return;
77                 }
78 }
79
80 struct syscall {
81         int syscall;
82         int count;
83 };
84
85 static int cmp_count(const void *a, const void *b)
86 {
87         return ((struct syscall*)b)->count - ((struct syscall*)a)->count;
88 }
89
90 static void print_syscalls(int policy, const char *json)
91 {
92         void *c;
93         int i;
94
95         set_syscall("rt_sigaction", 1);
96         set_syscall("sigreturn", 1);
97         set_syscall("rt_sigreturn", 1);
98         set_syscall("exit_group", 1);
99         set_syscall("exit", 1);
100
101         struct syscall sorted[ARRAY_SIZE(syscall_names)];
102
103         for (i = 0; i < ARRAY_SIZE(syscall_names); i++) {
104                 sorted[i].syscall = i;
105                 sorted[i].count = syscall_count[i];
106         }
107
108         qsort(sorted, ARRAY_SIZE(syscall_names), sizeof(sorted[0]), cmp_count);
109
110         blob_buf_init(&b, 0);
111         c = blobmsg_open_array(&b, "whitelist");
112
113         for (i = 0; i < ARRAY_SIZE(syscall_names); i++) {
114                 int sc = sorted[i].syscall;
115                 if (!sorted[i].count)
116                         break;
117                 if (syscall_names[sc]) {
118                         if (debug)
119                                 printf("syscall %d (%s) was called %d times\n",
120                                         sc, syscall_names[sc], sorted[i].count);
121                         blobmsg_add_string(&b, NULL, syscall_names[sc]);
122                 } else {
123                         ERROR("no name found for syscall(%d)\n", sc);
124                 }
125         }
126         blobmsg_close_array(&b, c);
127         blobmsg_add_u32(&b, "policy", policy);
128         if (json) {
129                 FILE *fp = fopen(json, "w");
130                 if (fp) {
131                         fprintf(fp, "%s", blobmsg_format_json_indent(b.head, true, 0));
132                         fclose(fp);
133                         INFO("saving syscall trace to %s\n", json);
134                 } else {
135                         ERROR("failed to open %s\n", json);
136                 }
137         } else {
138                 printf("%s\n",
139                         blobmsg_format_json_indent(b.head, true, 0));
140         }
141
142 }
143
144 static void tracer_cb(struct uloop_process *c, int ret)
145 {
146         if (WIFSTOPPED(ret) && WSTOPSIG(ret) & 0x80) {
147                 if (!in_syscall) {
148                         int syscall = ptrace(PTRACE_PEEKUSER, c->pid, reg_syscall_nr);
149
150                         if (syscall < syscall_max) {
151                                 syscall_count[syscall]++;
152                                 if (debug)
153                                         fprintf(stderr, "%s()\n", syscall_names[syscall]);
154                         } else if (debug) {
155                                 fprintf(stderr, "syscal(%d)\n", syscall);
156                         }
157                 }
158                 in_syscall = !in_syscall;
159         } else if (WIFEXITED(ret)) {
160                 uloop_end();
161                 return;
162         }
163         ptrace(PTRACE_SYSCALL, c->pid, 0, 0);
164         uloop_process_add(&tracer);
165 }
166
167 int main(int argc, char **argv, char **envp)
168 {
169         char *json = NULL;
170         int status, ch, policy = EPERM;
171         pid_t child;
172
173         while ((ch = getopt(argc, argv, "f:p:")) != -1) {
174                 switch (ch) {
175                 case 'f':
176                         json = optarg;
177                         break;
178                 case 'p':
179                         policy = atoi(optarg);
180                         break;
181                 }
182         }
183
184         argc -= optind;
185         argv += optind;
186
187         if (!argc)
188                 return -1;
189
190         if (getenv("TRACE_DEBUG"))
191                 debug = 1;
192         unsetenv("TRACE_DEBUG");
193
194         child = fork();
195
196         if (child == 0) {
197                 char **_argv = calloc(argc + 1, sizeof(char *));
198                 char **_envp;
199                 char *preload = "LD_PRELOAD=/lib/libpreload-trace.so";
200                 int envc = 0;
201                 int ret;
202
203                 memcpy(_argv, argv, argc * sizeof(char *));
204
205                 while (envp[envc++])
206                         ;
207
208                 _envp = calloc(envc + 1, sizeof(char *));
209                 memcpy(&_envp[1], envp, envc * sizeof(char *));
210                 *_envp = preload;
211
212                 ret = execve(_argv[0], _argv, _envp);
213                 ERROR("failed to exec %s: %s\n", _argv[0], strerror(errno));
214
215                 free(_argv);
216                 free(_envp);
217                 return ret;
218         }
219
220         if (child < 0)
221                 return -1;
222
223         syscall_max = ARRAY_SIZE(syscall_names);
224         syscall_count = calloc(syscall_max, sizeof(int));
225         waitpid(child, &status, 0);
226         if (!WIFSTOPPED(status)) {
227                 ERROR("failed to start %s\n", *argv);
228                 return -1;
229         }
230
231         ptrace(PTRACE_SETOPTIONS, child, 0, PTRACE_O_TRACESYSGOOD);
232         ptrace(PTRACE_SYSCALL, child, 0, 0);
233
234         uloop_init();
235         tracer.pid = child;
236         tracer.cb = tracer_cb;
237         uloop_process_add(&tracer);
238         uloop_run();
239         uloop_done();
240
241         if (!json)
242                 if (asprintf(&json, "/tmp/%s.%u.json", basename(*argv), child) < 0)
243                         ERROR("failed to allocate output path: %s\n", strerror(errno));
244
245         print_syscalls(policy, json);
246
247         return 0;
248 }