sig-monitor: Handle signals in exit
[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 /* internal signal lists */
44 static int sigerr[] = { SIG_FOR_TIMER, SIGSEGV, SIGFPE, SIGILL, SIGBUS, 0 };
45 static int sigterm[] = { SIGINT, SIGABRT, SIGTERM, 0 };
46 static int exiting = 0;
47
48 /*
49  * Dumps the current stack
50  */
51 static void dumpstack(int crop, int signum)
52 {
53         int idx, count, rc;
54         void *addresses[100];
55         char **locations;
56         char buffer[8000];
57         size_t pos, length;
58
59         count = backtrace(addresses, sizeof addresses / sizeof *addresses);
60         if (count <= crop)
61                 crop = 0;
62         count -= crop;
63         locations = backtrace_symbols(&addresses[crop], count);
64         if (locations == NULL)
65                 ERROR("can't get the backtrace (returned %d addresses)", count);
66         else {
67                 length = sizeof buffer - 1;
68                 pos = 0;
69                 idx = 0;
70                 while (pos < length && idx < count) {
71                         rc = snprintf(&buffer[pos], length - pos, " [%d/%d] %s\n", idx + 1, count, locations[idx]);
72                         pos += rc >= 0 ? rc : 0;
73                         idx++;
74                 }
75                 buffer[length] = 0;
76                 if (signum)
77                         ERROR("BACKTRACE due to signal %s/%d:\n%s", strsignal(signum), signum, buffer);
78                 else
79                         ERROR("BACKTRACE:\n%s", buffer);
80                 free(locations);
81         }
82 }
83
84 static void safe_dumpstack_cb(int signum, void *closure)
85 {
86         int *args = closure;
87         if (signum)
88                 ERROR("Can't provide backtrace: raised signal %s", strsignal(signum));
89         else
90                 dumpstack(args[0], args[1]);
91 }
92
93 static void safe_dumpstack(int crop, int signum)
94 {
95         int args[2] = { crop + 3, signum };
96
97         in_safe_dumpstack = 1;
98         sig_monitor(0, safe_dumpstack_cb, args);
99         in_safe_dumpstack = 0;
100 }
101
102 /*
103  * Creates a timer for the current thread
104  *
105  * Returns 0 in case of success
106  */
107 static inline int timeout_create()
108 {
109         int rc;
110         struct sigevent sevp;
111
112         if (thread_timer_set)
113                 rc = 0;
114         else {
115                 sevp.sigev_notify = SIGEV_THREAD_ID;
116                 sevp.sigev_signo = SIG_FOR_TIMER;
117                 sevp.sigev_value.sival_ptr = NULL;
118 #if defined(sigev_notify_thread_id)
119                 sevp.sigev_notify_thread_id = (pid_t)syscall(SYS_gettid);
120 #else
121                 sevp._sigev_un._tid = (pid_t)syscall(SYS_gettid);
122 #endif
123                 rc = timer_create(CLOCK_THREAD_CPUTIME_ID, &sevp, &thread_timerid);
124                 thread_timer_set = !rc;
125         }
126         return 0;
127 }
128
129 /*
130  * Arms the alarm in timeout seconds for the current thread
131  */
132 static inline int timeout_arm(int timeout)
133 {
134         int rc;
135         struct itimerspec its;
136
137         rc = timeout_create();
138         if (rc == 0) {
139                 its.it_interval.tv_sec = 0;
140                 its.it_interval.tv_nsec = 0;
141                 its.it_value.tv_sec = timeout;
142                 its.it_value.tv_nsec = 0;
143                 rc = timer_settime(thread_timerid, 0, &its, NULL);
144         }
145
146         return rc;
147 }
148
149 /*
150  * Disarms the current alarm
151  */
152 static inline void timeout_disarm()
153 {
154         if (thread_timer_set)
155                 timeout_arm(0);
156 }
157
158 /*
159  * Destroy any alarm resource for the current thread
160  */
161 static inline void timeout_delete()
162 {
163         if (thread_timer_set) {
164                 timer_delete(thread_timerid);
165                 thread_timer_set = 0;
166         }
167 }
168
169 /* install the handlers */
170 static int install(void (*handler)(int), int *signals)
171 {
172         int result = 1;
173         struct sigaction sa;
174
175         sa.sa_handler = handler;
176         sigemptyset(&sa.sa_mask);
177         sa.sa_flags = SA_NODEFER;
178         while(*signals > 0) {
179                 if (sigaction(*signals, &sa, NULL) < 0) {
180                         ERROR("failed to install signal handler for signal %s: %m", strsignal(*signals));
181                         result = 0;
182                 }
183                 signals++;
184         }
185         return result;
186 }
187
188 /*
189  * rescue exit
190  */
191 static void on_rescue_exit(int signum)
192 {
193         ERROR("Rescue exit for signal %d: %s", signum, strsignal(signum));
194         _exit(exiting);
195 }
196
197 /*
198  * Do a safe exit
199  */
200 static void safe_exit(int code)
201 {
202         install(on_rescue_exit, sigerr);
203         install(on_rescue_exit, sigterm);
204         exiting = code;
205         exit(code);
206 }
207
208 /* Handles signals that terminate the process */
209 static void on_signal_terminate (int signum)
210 {
211         if (!in_safe_dumpstack) {
212                 ERROR("Terminating signal %d received: %s", signum, strsignal(signum));
213                 if (signum == SIGABRT)
214                         safe_dumpstack(3, signum);
215         }
216         safe_exit(1);
217 }
218
219 /* Handles monitored signals that can be continued */
220 static void on_signal_error(int signum)
221 {
222         if (in_safe_dumpstack)
223                 longjmp(*error_handler, signum);
224
225         ERROR("ALERT! signal %d received: %s", signum, strsignal(signum));
226         if (error_handler == NULL && signum == SIG_FOR_TIMER)
227                 return;
228
229         safe_dumpstack(3, signum);
230
231         // unlock signal to allow a new signal to come
232         if (error_handler != NULL)
233                 longjmp(*error_handler, signum);
234
235         ERROR("Unmonitored signal %d received: %s", signum, strsignal(signum));
236         safe_exit(2);
237 }
238
239 int sig_monitor_init()
240 {
241         return (install(on_signal_error, sigerr) & install(on_signal_terminate, sigterm)) - 1;
242 }
243
244 int sig_monitor_init_timeouts()
245 {
246         return timeout_create();
247 }
248
249 void sig_monitor_clean_timeouts()
250 {
251         timeout_delete();
252 }
253
254 void sig_monitor(int timeout, void (*function)(int sig, void*), void *arg)
255 {
256         volatile int signum, signum2;
257         sigjmp_buf jmpbuf, *older;
258
259         older = error_handler;
260         signum = setjmp(jmpbuf);
261         if (signum == 0) {
262                 error_handler = &jmpbuf;
263                 if (timeout)
264                         timeout_arm(timeout);
265                 function(0, arg);
266         } else {
267                 signum2 = setjmp(jmpbuf);
268                 if (signum2 == 0)
269                         function(signum, arg);
270         }
271         error_handler = older;
272         if (timeout)
273                 timeout_disarm();
274 }
275
276