2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
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:
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include "backtrace.h"
18 #include "fatal-signal.h"
27 #include "ovs-thread.h"
28 #include "openvswitch/poll-loop.h"
29 #include "openvswitch/shash.h"
32 #include "socket-util.h"
34 #include "openvswitch/vlog.h"
36 #include "openvswitch/type-props.h"
39 #include "daemon-private.h"
42 #ifndef SIG_ATOMIC_MAX
43 #define SIG_ATOMIC_MAX TYPE_MAXIMUM(sig_atomic_t)
46 VLOG_DEFINE_THIS_MODULE(fatal_signal
);
48 /* Signals to catch. */
50 static const int fatal_signals
[] = { SIGTERM
, SIGINT
, SIGHUP
, SIGALRM
,
53 static const int fatal_signals
[] = { SIGTERM
};
56 /* Hooks to call upon catching a signal */
58 void (*hook_cb
)(void *aux
);
59 void (*cancel_cb
)(void *aux
);
64 static struct hook hooks
[MAX_HOOKS
];
65 static size_t n_hooks
;
67 static int signal_fds
[2];
68 static volatile sig_atomic_t stored_sig_nr
= SIG_ATOMIC_MAX
;
74 static struct ovs_mutex mutex
;
76 static void call_hooks(int sig_nr
);
78 static BOOL WINAPI
ConsoleHandlerRoutine(DWORD dwCtrlType
);
81 /* Initializes the fatal signal handling module. Calling this function is
82 * optional, because calling any other function in the module will also
83 * initialize it. However, in a multithreaded program, the module must be
84 * initialized while the process is still single-threaded. */
86 fatal_signal_init(void)
88 static bool inited
= false;
93 assert_single_threaded();
96 ovs_mutex_init_recursive(&mutex
);
98 xpipe_nonblocking(signal_fds
);
100 wevent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
102 char *msg_buf
= ovs_lasterror_to_string();
103 VLOG_FATAL("Failed to create a event (%s).", msg_buf
);
106 /* Register a function to handle Ctrl+C. */
107 SetConsoleCtrlHandler(ConsoleHandlerRoutine
, true);
110 for (i
= 0; i
< ARRAY_SIZE(fatal_signals
); i
++) {
111 int sig_nr
= fatal_signals
[i
];
113 struct sigaction old_sa
;
115 xsigaction(sig_nr
, NULL
, &old_sa
);
116 if (old_sa
.sa_handler
== SIG_DFL
117 && signal(sig_nr
, fatal_signal_handler
) == SIG_ERR
) {
118 VLOG_FATAL("signal failed (%s)", ovs_strerror(errno
));
121 if (signal(sig_nr
, fatal_signal_handler
) == SIG_ERR
) {
122 VLOG_FATAL("signal failed (%s)", ovs_strerror(errno
));
126 atexit(fatal_signal_atexit_handler
);
130 /* Registers 'hook_cb' to be called from inside poll_block() following a fatal
131 * signal. 'hook_cb' does not need to be async-signal-safe. In a
132 * multithreaded program 'hook_cb' might be called from any thread, with
133 * threads other than the one running 'hook_cb' in unknown states.
135 * If 'run_at_exit' is true, 'hook_cb' is also called during normal process
136 * termination, e.g. when exit() is called or when main() returns.
138 * If the current process forks, fatal_signal_fork() may be called to clear the
139 * parent process's fatal signal hooks, so that 'hook_cb' is only called when
140 * the child terminates, not when the parent does. When fatal_signal_fork() is
141 * called, it calls the 'cancel_cb' function if it is nonnull, passing 'aux',
142 * to notify that the hook has been canceled. This allows the hook to free
145 fatal_signal_add_hook(void (*hook_cb
)(void *aux
), void (*cancel_cb
)(void *aux
),
146 void *aux
, bool run_at_exit
)
150 ovs_mutex_lock(&mutex
);
151 ovs_assert(n_hooks
< MAX_HOOKS
);
152 hooks
[n_hooks
].hook_cb
= hook_cb
;
153 hooks
[n_hooks
].cancel_cb
= cancel_cb
;
154 hooks
[n_hooks
].aux
= aux
;
155 hooks
[n_hooks
].run_at_exit
= run_at_exit
;
157 ovs_mutex_unlock(&mutex
);
161 /* Convert unsigned long long to string. This is needed because
162 * using snprintf() is not async signal safe. */
164 llong_to_hex_str(unsigned long long value
, char *str
)
168 if (value
/ 16 > 0) {
169 i
= llong_to_hex_str(value
/ 16, str
);
173 str
[i
] = "0123456789abcdef"[res
];
178 /* Send the backtrace buffer to monitor thread.
180 * Note that this runs in the signal handling context, any system
181 * library functions used here must be async-signal-safe.
184 send_backtrace_to_monitor(void) {
185 /* volatile added to prevent a "clobbered" error on ppc64le with gcc */
187 struct unw_backtrace unw_bt
[UNW_MAX_DEPTH
];
191 if (daemonize_fd
== -1) {
197 unw_init_local(&cursor
, &uc
);
199 while (dep
< UNW_MAX_DEPTH
&& unw_step(&cursor
)) {
200 memset(unw_bt
[dep
].func
, 0, UNW_MAX_FUNCN
);
201 unw_get_reg(&cursor
, UNW_REG_IP
, &unw_bt
[dep
].ip
);
202 unw_get_proc_name(&cursor
, unw_bt
[dep
].func
, UNW_MAX_FUNCN
,
203 &unw_bt
[dep
].offset
);
208 ignore(write(daemonize_fd
, unw_bt
,
209 dep
* sizeof(struct unw_backtrace
)));
211 /* Since there is no monitor daemon running, write backtrace
212 * in current process.
214 char str
[] = "SIGSEGV detected, backtrace:\n";
215 char ip_str
[16], offset_str
[6];
216 char line
[64], fn_name
[UNW_MAX_FUNCN
];
218 vlog_direct_write_to_log_file_unsafe(str
);
220 for (int i
= 0; i
< dep
; i
++) {
221 memset(line
, 0, sizeof line
);
222 memset(fn_name
, 0, sizeof fn_name
);
223 memset(offset_str
, 0, sizeof offset_str
);
224 memset(ip_str
, ' ', sizeof ip_str
);
225 ip_str
[sizeof(ip_str
) - 1] = 0;
227 llong_to_hex_str(unw_bt
[i
].ip
, ip_str
);
228 llong_to_hex_str(unw_bt
[i
].offset
, offset_str
);
231 strcat(line
, ip_str
);
233 memcpy(fn_name
, unw_bt
[i
].func
, UNW_MAX_FUNCN
- 1);
234 strcat(line
, fn_name
);
236 strcat(line
, offset_str
);
238 vlog_direct_write_to_log_file_unsafe(line
);
244 send_backtrace_to_monitor(void) {
249 /* Handles fatal signal number 'sig_nr'.
251 * Ordinarily this is the actual signal handler. When other code needs to
252 * handle one of our signals, however, it can register for that signal and, if
253 * and when necessary, call this function to do fatal signal processing for it
254 * and terminate the process. Currently only timeval.c does this, for SIGALRM.
255 * (It is not important whether the other code sets up its signal handler
256 * before or after this file, because this file will only set up a signal
257 * handler in the case where the signal has its default handling.) */
259 fatal_signal_handler(int sig_nr
)
262 if (sig_nr
== SIGSEGV
) {
263 signal(sig_nr
, SIG_DFL
); /* Set it back immediately. */
264 send_backtrace_to_monitor();
267 ignore(write(signal_fds
[1], "", 1));
271 stored_sig_nr
= sig_nr
;
274 /* Check whether a fatal signal has occurred and, if so, call the fatal signal
277 * This function is called automatically by poll_block(), but specialized
278 * programs that may not always call poll_block() on a regular basis should
279 * also call it periodically. (Therefore, any function with "block" in its
280 * name should call fatal_signal_run() each time it is called, either directly
281 * or through poll_block(), because such functions can only used by specialized
282 * programs that can afford to block outside their main loop around
286 fatal_signal_run(void)
292 sig_nr
= stored_sig_nr
;
293 if (sig_nr
!= SIG_ATOMIC_MAX
) {
294 char namebuf
[SIGNAL_NAME_BUFSIZE
];
296 ovs_mutex_lock(&mutex
);
299 VLOG_WARN("terminating with signal %d (%s)",
300 (int)sig_nr
, signal_name(sig_nr
, namebuf
, sizeof namebuf
));
302 VLOG_WARN("terminating with signal %d", (int)sig_nr
);
307 /* Re-raise the signal with the default handling so that the program
308 * termination status reflects that we were killed by this signal */
309 signal(sig_nr
, SIG_DFL
);
312 ovs_mutex_unlock(&mutex
);
318 fatal_signal_wait(void)
322 poll_wevent_wait(wevent
);
324 poll_fd_wait(signal_fds
[0], POLLIN
);
329 fatal_ignore_sigpipe(void)
332 signal(SIGPIPE
, SIG_IGN
);
337 fatal_signal_atexit_handler(void)
343 call_hooks(int sig_nr
)
345 static volatile sig_atomic_t recurse
= 0;
351 for (i
= 0; i
< n_hooks
; i
++) {
352 struct hook
*h
= &hooks
[i
];
353 if (sig_nr
|| h
->run_at_exit
) {
361 BOOL WINAPI
ConsoleHandlerRoutine(DWORD dwCtrlType
)
363 stored_sig_nr
= SIGINT
;
369 /* Files to delete on exit. */
370 static struct sset files
= SSET_INITIALIZER(&files
);
372 /* Has a hook function been registered with fatal_signal_add_hook() (and not
373 * cleared by fatal_signal_fork())? */
374 static bool added_hook
;
376 static void unlink_files(void *aux
);
377 static void cancel_files(void *aux
);
378 static void do_unlink_files(void);
380 /* Registers 'file' to be unlinked when the program terminates via exit() or a
383 fatal_signal_add_file_to_unlink(const char *file
)
387 ovs_mutex_lock(&mutex
);
390 fatal_signal_add_hook(unlink_files
, cancel_files
, NULL
, true);
393 sset_add(&files
, file
);
394 ovs_mutex_unlock(&mutex
);
397 /* Unregisters 'file' from being unlinked when the program terminates via
398 * exit() or a fatal signal. */
400 fatal_signal_remove_file_to_unlink(const char *file
)
404 ovs_mutex_lock(&mutex
);
405 sset_find_and_delete(&files
, file
);
406 ovs_mutex_unlock(&mutex
);
409 /* Like fatal_signal_remove_file_to_unlink(), but also unlinks 'file'.
410 * Returns 0 if successful, otherwise a positive errno value. */
412 fatal_signal_unlink_file_now(const char *file
)
418 ovs_mutex_lock(&mutex
);
420 error
= unlink(file
) ? errno
: 0;
422 VLOG_WARN("could not unlink \"%s\" (%s)", file
, ovs_strerror(error
));
425 fatal_signal_remove_file_to_unlink(file
);
427 ovs_mutex_unlock(&mutex
);
433 unlink_files(void *aux OVS_UNUSED
)
439 cancel_files(void *aux OVS_UNUSED
)
446 do_unlink_files(void)
450 SSET_FOR_EACH (file
, &files
) {
455 /* Clears all of the fatal signal hooks without executing them. If any of the
456 * hooks passed a 'cancel_cb' function to fatal_signal_add_hook(), then those
457 * functions will be called, allowing them to free resources, etc.
459 * Following a fork, one of the resulting processes can call this function to
460 * allow it to terminate without calling the hooks registered before calling
461 * this function. New hooks registered after calling this function will take
462 * effect normally. */
464 fatal_signal_fork(void)
468 assert_single_threaded();
470 for (i
= 0; i
< n_hooks
; i
++) {
471 struct hook
*h
= &hooks
[i
];
473 h
->cancel_cb(h
->aux
);
478 /* Raise any signals that we have already received with the default
480 if (stored_sig_nr
!= SIG_ATOMIC_MAX
) {
481 raise(stored_sig_nr
);
486 /* Blocks all fatal signals and returns previous signal mask into
489 fatal_signal_block(sigset_t
*prev_mask
)
494 sigemptyset(&block_mask
);
495 for (i
= 0; i
< ARRAY_SIZE(fatal_signals
); i
++) {
496 int sig_nr
= fatal_signals
[i
];
497 sigaddset(&block_mask
, sig_nr
);
499 xpthread_sigmask(SIG_BLOCK
, &block_mask
, prev_mask
);