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