clang: Add annotations for thread safety check.
[sliver-openvswitch.git] / lib / fatal-signal.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include <config.h>
17 #include "fatal-signal.h"
18 #include <errno.h>
19 #include <signal.h>
20 #include <stdbool.h>
21 #include <stdio.h>
22 #include <stdint.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include "ovs-thread.h"
27 #include "poll-loop.h"
28 #include "shash.h"
29 #include "sset.h"
30 #include "signals.h"
31 #include "socket-util.h"
32 #include "util.h"
33 #include "vlog.h"
34
35 #include "type-props.h"
36
37 #ifndef SIG_ATOMIC_MAX
38 #define SIG_ATOMIC_MAX TYPE_MAXIMUM(sig_atomic_t)
39 #endif
40
41 VLOG_DEFINE_THIS_MODULE(fatal_signal);
42
43 /* Signals to catch. */
44 static const int fatal_signals[] = { SIGTERM, SIGINT, SIGHUP, SIGALRM };
45
46 /* Hooks to call upon catching a signal */
47 struct hook {
48     void (*hook_cb)(void *aux);
49     void (*cancel_cb)(void *aux);
50     void *aux;
51     bool run_at_exit;
52 };
53 #define MAX_HOOKS 32
54 static struct hook hooks[MAX_HOOKS];
55 static size_t n_hooks;
56
57 static int signal_fds[2];
58 static volatile sig_atomic_t stored_sig_nr = SIG_ATOMIC_MAX;
59
60 static struct ovs_mutex mutex;
61
62 static void atexit_handler(void);
63 static void call_hooks(int sig_nr);
64
65 /* Initializes the fatal signal handling module.  Calling this function is
66  * optional, because calling any other function in the module will also
67  * initialize it.  However, in a multithreaded program, the module must be
68  * initialized while the process is still single-threaded. */
69 void
70 fatal_signal_init(void)
71 {
72     static bool inited = false;
73
74     if (!inited) {
75         size_t i;
76
77         assert_single_threaded();
78         inited = true;
79
80         ovs_mutex_init(&mutex, PTHREAD_MUTEX_RECURSIVE);
81         xpipe_nonblocking(signal_fds);
82
83         for (i = 0; i < ARRAY_SIZE(fatal_signals); i++) {
84             int sig_nr = fatal_signals[i];
85             struct sigaction old_sa;
86
87             xsigaction(sig_nr, NULL, &old_sa);
88             if (old_sa.sa_handler == SIG_DFL
89                 && signal(sig_nr, fatal_signal_handler) == SIG_ERR) {
90                 VLOG_FATAL("signal failed (%s)", ovs_strerror(errno));
91             }
92         }
93         atexit(atexit_handler);
94     }
95 }
96
97 /* Registers 'hook_cb' to be called from inside poll_block() following a fatal
98  * signal.  'hook_cb' does not need to be async-signal-safe.  In a
99  * multithreaded program 'hook_cb' might be called from any thread, with
100  * threads other than the one running 'hook_cb' in unknown states.
101  *
102  * If 'run_at_exit' is true, 'hook_cb' is also called during normal process
103  * termination, e.g. when exit() is called or when main() returns.
104  *
105  * If the current process forks, fatal_signal_fork() may be called to clear the
106  * parent process's fatal signal hooks, so that 'hook_cb' is only called when
107  * the child terminates, not when the parent does.  When fatal_signal_fork() is
108  * called, it calls the 'cancel_cb' function if it is nonnull, passing 'aux',
109  * to notify that the hook has been canceled.  This allows the hook to free
110  * memory, etc. */
111 void
112 fatal_signal_add_hook(void (*hook_cb)(void *aux), void (*cancel_cb)(void *aux),
113                       void *aux, bool run_at_exit)
114 {
115     fatal_signal_init();
116
117     ovs_mutex_lock(&mutex);
118     ovs_assert(n_hooks < MAX_HOOKS);
119     hooks[n_hooks].hook_cb = hook_cb;
120     hooks[n_hooks].cancel_cb = cancel_cb;
121     hooks[n_hooks].aux = aux;
122     hooks[n_hooks].run_at_exit = run_at_exit;
123     n_hooks++;
124     ovs_mutex_unlock(&mutex);
125 }
126
127 /* Handles fatal signal number 'sig_nr'.
128  *
129  * Ordinarily this is the actual signal handler.  When other code needs to
130  * handle one of our signals, however, it can register for that signal and, if
131  * and when necessary, call this function to do fatal signal processing for it
132  * and terminate the process.  Currently only timeval.c does this, for SIGALRM.
133  * (It is not important whether the other code sets up its signal handler
134  * before or after this file, because this file will only set up a signal
135  * handler in the case where the signal has its default handling.)  */
136 void
137 fatal_signal_handler(int sig_nr)
138 {
139     ignore(write(signal_fds[1], "", 1));
140     stored_sig_nr = sig_nr;
141 }
142
143 /* Check whether a fatal signal has occurred and, if so, call the fatal signal
144  * hooks and exit.
145  *
146  * This function is called automatically by poll_block(), but specialized
147  * programs that may not always call poll_block() on a regular basis should
148  * also call it periodically.  (Therefore, any function with "block" in its
149  * name should call fatal_signal_run() each time it is called, either directly
150  * or through poll_block(), because such functions can only used by specialized
151  * programs that can afford to block outside their main loop around
152  * poll_block().)
153  */
154 void
155 fatal_signal_run(void)
156 {
157     sig_atomic_t sig_nr;
158
159     fatal_signal_init();
160
161     sig_nr = stored_sig_nr;
162     if (sig_nr != SIG_ATOMIC_MAX) {
163         char namebuf[SIGNAL_NAME_BUFSIZE];
164
165         ovs_mutex_lock(&mutex);
166
167         VLOG_WARN("terminating with signal %d (%s)",
168                   (int)sig_nr, signal_name(sig_nr, namebuf, sizeof namebuf));
169         call_hooks(sig_nr);
170
171         /* Re-raise the signal with the default handling so that the program
172          * termination status reflects that we were killed by this signal */
173         signal(sig_nr, SIG_DFL);
174         raise(sig_nr);
175
176         ovs_mutex_unlock(&mutex);
177         NOT_REACHED();
178     }
179 }
180
181 void
182 fatal_signal_wait(void)
183 {
184     fatal_signal_init();
185     poll_fd_wait(signal_fds[0], POLLIN);
186 }
187
188 static void
189 atexit_handler(void)
190 {
191     call_hooks(0);
192 }
193
194 static void
195 call_hooks(int sig_nr)
196 {
197     static volatile sig_atomic_t recurse = 0;
198     if (!recurse) {
199         size_t i;
200
201         recurse = 1;
202
203         for (i = 0; i < n_hooks; i++) {
204             struct hook *h = &hooks[i];
205             if (sig_nr || h->run_at_exit) {
206                 h->hook_cb(h->aux);
207             }
208         }
209     }
210 }
211 \f
212 /* Files to delete on exit. */
213 static struct sset files = SSET_INITIALIZER(&files);
214
215 /* Has a hook function been registered with fatal_signal_add_hook() (and not
216  * cleared by fatal_signal_fork())? */
217 static bool added_hook;
218
219 static void unlink_files(void *aux);
220 static void cancel_files(void *aux);
221 static void do_unlink_files(void);
222
223 /* Registers 'file' to be unlinked when the program terminates via exit() or a
224  * fatal signal. */
225 void
226 fatal_signal_add_file_to_unlink(const char *file)
227 {
228     fatal_signal_init();
229
230     ovs_mutex_lock(&mutex);
231     if (!added_hook) {
232         added_hook = true;
233         fatal_signal_add_hook(unlink_files, cancel_files, NULL, true);
234     }
235
236     sset_add(&files, file);
237     ovs_mutex_unlock(&mutex);
238 }
239
240 /* Unregisters 'file' from being unlinked when the program terminates via
241  * exit() or a fatal signal. */
242 void
243 fatal_signal_remove_file_to_unlink(const char *file)
244 {
245     fatal_signal_init();
246
247     ovs_mutex_lock(&mutex);
248     sset_find_and_delete(&files, file);
249     ovs_mutex_unlock(&mutex);
250 }
251
252 /* Like fatal_signal_remove_file_to_unlink(), but also unlinks 'file'.
253  * Returns 0 if successful, otherwise a positive errno value. */
254 int
255 fatal_signal_unlink_file_now(const char *file)
256 {
257     int error;
258
259     fatal_signal_init();
260
261     ovs_mutex_lock(&mutex);
262
263     error = unlink(file) ? errno : 0;
264     if (error) {
265         VLOG_WARN("could not unlink \"%s\" (%s)", file, ovs_strerror(error));
266     }
267
268     fatal_signal_remove_file_to_unlink(file);
269
270     ovs_mutex_unlock(&mutex);
271
272     return error;
273 }
274
275 static void
276 unlink_files(void *aux OVS_UNUSED)
277 {
278     do_unlink_files();
279 }
280
281 static void
282 cancel_files(void *aux OVS_UNUSED)
283 {
284     sset_clear(&files);
285     added_hook = false;
286 }
287
288 static void
289 do_unlink_files(void)
290 {
291     const char *file;
292
293     SSET_FOR_EACH (file, &files) {
294         unlink(file);
295     }
296 }
297 \f
298 /* Clears all of the fatal signal hooks without executing them.  If any of the
299  * hooks passed a 'cancel_cb' function to fatal_signal_add_hook(), then those
300  * functions will be called, allowing them to free resources, etc.
301  *
302  * Following a fork, one of the resulting processes can call this function to
303  * allow it to terminate without calling the hooks registered before calling
304  * this function.  New hooks registered after calling this function will take
305  * effect normally. */
306 void
307 fatal_signal_fork(void)
308 {
309     size_t i;
310
311     assert_single_threaded();
312
313     for (i = 0; i < n_hooks; i++) {
314         struct hook *h = &hooks[i];
315         if (h->cancel_cb) {
316             h->cancel_cb(h->aux);
317         }
318     }
319     n_hooks = 0;
320
321     /* Raise any signals that we have already received with the default
322      * handler. */
323     if (stored_sig_nr != SIG_ATOMIC_MAX) {
324         raise(stored_sig_nr);
325     }
326 }