sig-monitor: handle SIGSEGV in backtrace
[src/app-framework-binder.git] / src / sig-monitor.c
1 /*
2  * Copyright (C) 2017 "IoT.bzh"
3  * Author José Bollo <jose.bollo@iot.bzh>
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #define _GNU_SOURCE
19
20 #include <stdlib.h>
21 #include <stdio.h>
22 #include <signal.h>
23 #include <string.h>
24 #include <setjmp.h>
25 #include <time.h>
26 #include <unistd.h>
27 #include <sys/syscall.h>
28 #include <execinfo.h>
29
30 #include "sig-monitor.h"
31 #include "verbose.h"
32
33 #define SIG_FOR_TIMER   SIGVTALRM
34
35 /* local handler */
36 static _Thread_local sigjmp_buf *error_handler;
37 static _Thread_local int in_safe_dumpstack;
38
39 /* local timers */
40 static _Thread_local int thread_timer_set;
41 static _Thread_local timer_t thread_timerid;
42
43 /*
44  * Dumps the current stack
45  */
46 static void dumpstack(int crop, int signum)
47 {
48         int idx, count, rc;
49         void *addresses[100];
50         char **locations;
51         char buffer[8000];
52         size_t pos, length;
53
54         count = backtrace(addresses, sizeof addresses / sizeof *addresses);
55         if (count <= crop)
56                 crop = 0;
57         count -= crop;
58         locations = backtrace_symbols(&addresses[crop], count);
59         if (locations == NULL)
60                 ERROR("can't get the backtrace (returned %d addresses)", count);
61         else {
62                 length = sizeof buffer - 1;
63                 pos = 0;
64                 idx = 0;
65                 while (pos < length && idx < count) {
66                         rc = snprintf(&buffer[pos], length - pos, " [%d/%d] %s\n", idx + 1, count, locations[idx]);
67                         pos += rc >= 0 ? rc : 0;
68                         idx++;
69                 }
70                 buffer[length] = 0;
71                 if (signum)
72                         ERROR("BACKTRACE due to signal %s/%d:\n%s", strsignal(signum), signum, buffer);
73                 else
74                         ERROR("BACKTRACE:\n%s", buffer);
75                 free(locations);
76         }
77 }
78
79 static void safe_dumpstack_cb(int signum, void *closure)
80 {
81         int *args = closure;
82         if (signum)
83                 ERROR("Can't provide backtrace: raised signal %s", strsignal(signum));
84         else
85                 dumpstack(args[0], args[1]);
86 }
87
88 static void safe_dumpstack(int crop, int signum)
89 {
90         int args[2] = { crop, signum };
91
92         in_safe_dumpstack = 1;
93         sig_monitor(0, safe_dumpstack_cb, args);
94         in_safe_dumpstack = 0;
95 }
96
97 /*
98  * Creates a timer for the current thread
99  *
100  * Returns 0 in case of success
101  */
102 static inline int timeout_create()
103 {
104         int rc;
105         struct sigevent sevp;
106
107         if (thread_timer_set)
108                 rc = 0;
109         else {
110                 sevp.sigev_notify = SIGEV_THREAD_ID;
111                 sevp.sigev_signo = SIG_FOR_TIMER;
112                 sevp.sigev_value.sival_ptr = NULL;
113 #if defined(sigev_notify_thread_id)
114                 sevp.sigev_notify_thread_id = (pid_t)syscall(SYS_gettid);
115 #else
116                 sevp._sigev_un._tid = (pid_t)syscall(SYS_gettid);
117 #endif
118                 rc = timer_create(CLOCK_THREAD_CPUTIME_ID, &sevp, &thread_timerid);
119                 thread_timer_set = !rc;
120         }
121         return 0;
122 }
123
124 /*
125  * Arms the alarm in timeout seconds for the current thread
126  */
127 static inline int timeout_arm(int timeout)
128 {
129         int rc;
130         struct itimerspec its;
131
132         rc = timeout_create();
133         if (rc == 0) {
134                 its.it_interval.tv_sec = 0;
135                 its.it_interval.tv_nsec = 0;
136                 its.it_value.tv_sec = timeout;
137                 its.it_value.tv_nsec = 0;
138                 rc = timer_settime(thread_timerid, 0, &its, NULL);
139         }
140
141         return rc;
142 }
143
144 /*
145  * Disarms the current alarm
146  */
147 static inline void timeout_disarm()
148 {
149         if (thread_timer_set)
150                 timeout_arm(0);
151 }
152
153 /*
154  * Destroy any alarm resource for the current thread
155  */
156 static inline void timeout_delete()
157 {
158         if (thread_timer_set) {
159                 timer_delete(thread_timerid);
160                 thread_timer_set = 0;
161         }
162 }
163
164
165 /* Handles signals that terminate the process */
166 static void on_signal_terminate (int signum)
167 {
168         if (!in_safe_dumpstack) {
169                 ERROR("Terminating signal %d received: %s", signum, strsignal(signum));
170                 if (signum == SIGABRT)
171                         safe_dumpstack(3, signum);
172         }
173         exit(1);
174 }
175
176 /* Handles monitored signals that can be continued */
177 static void on_signal_error(int signum)
178 {
179         sigset_t sigset;
180
181         if (in_safe_dumpstack)
182                 longjmp(*error_handler, signum);
183
184         ERROR("ALERT! signal %d received: %s", signum, strsignal(signum));
185         if (error_handler == NULL && signum == SIG_FOR_TIMER)
186                 return;
187
188         safe_dumpstack(3, signum);
189
190         // unlock signal to allow a new signal to come
191         if (error_handler != NULL)
192                 longjmp(*error_handler, signum);
193
194         ERROR("Unmonitored signal %d received: %s", signum, strsignal(signum));
195         exit(2);
196 }
197
198 /* install the handlers */
199 static int install(void (*handler)(int), int *signals)
200 {
201         int result = 1;
202         struct sigaction sa;
203
204         sa.sa_handler = handler;
205         sigemptyset(&sa.sa_mask);
206         sa.sa_flags = SA_NODEFER;
207         while(*signals > 0) {
208                 if (sigaction(*signals, &sa, NULL) < 0) {
209                         ERROR("failed to install signal handler for signal %s: %m", strsignal(*signals));
210                         result = 0;
211                 }
212                 signals++;
213         }
214         return result;
215 }
216
217 int sig_monitor_init()
218 {
219         static int sigerr[] = { SIG_FOR_TIMER, SIGSEGV, SIGFPE, SIGILL, SIGBUS, 0 };
220         static int sigterm[] = { SIGINT, SIGABRT, SIGTERM, 0 };
221
222         return (install(on_signal_error, sigerr) & install(on_signal_terminate, sigterm)) - 1;
223 }
224
225 int sig_monitor_init_timeouts()
226 {
227         return timeout_create();
228 }
229
230 void sig_monitor_clean_timeouts()
231 {
232         timeout_delete();
233 }
234
235 void sig_monitor(int timeout, void (*function)(int sig, void*), void *arg)
236 {
237         volatile int signum, signum2;
238         sigjmp_buf jmpbuf, *older;
239
240         older = error_handler;
241         signum = setjmp(jmpbuf);
242         if (signum == 0) {
243                 error_handler = &jmpbuf;
244                 if (timeout)
245                         timeout_arm(timeout);
246                 function(0, arg);
247         } else {
248                 signum2 = setjmp(jmpbuf);
249                 if (signum2 == 0)
250                         function(signum, arg);
251         }
252         error_handler = older;
253         if (timeout)
254                 timeout_disarm();
255 }
256
257