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