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