Coverage Report

Created: 2025-07-01 06:50

/src/openvswitch/lib/fatal-signal.c
Line
Count
Source (jump to first uncovered line)
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 "backtrace.h"
18
#include "fatal-signal.h"
19
#include <errno.h>
20
#include <signal.h>
21
#include <stdbool.h>
22
#include <stdio.h>
23
#include <stdint.h>
24
#include <stdlib.h>
25
#include <string.h>
26
#include <unistd.h>
27
#include "ovs-thread.h"
28
#include "openvswitch/poll-loop.h"
29
#include "openvswitch/shash.h"
30
#include "sset.h"
31
#include "signals.h"
32
#include "socket-util.h"
33
#include "util.h"
34
#include "openvswitch/vlog.h"
35
36
#include "openvswitch/type-props.h"
37
38
#if defined(HAVE_UNWIND) || defined(HAVE_BACKTRACE)
39
#include "daemon-private.h"
40
#endif
41
42
#ifdef HAVE_BACKTRACE
43
#include <execinfo.h>
44
#endif
45
46
#ifndef SIG_ATOMIC_MAX
47
#define SIG_ATOMIC_MAX TYPE_MAXIMUM(sig_atomic_t)
48
#endif
49
50
VLOG_DEFINE_THIS_MODULE(fatal_signal);
51
52
/* Signals to catch. */
53
#ifndef _WIN32
54
static const int fatal_signals[] = { SIGTERM, SIGINT, SIGHUP, SIGALRM,
55
                                     SIGSEGV };
56
#else
57
static const int fatal_signals[] = { SIGTERM };
58
#endif
59
60
/* Hooks to call upon catching a signal */
61
struct hook {
62
    void (*hook_cb)(void *aux);
63
    void (*cancel_cb)(void *aux);
64
    void *aux;
65
    bool run_at_exit;
66
};
67
#define MAX_HOOKS 32
68
static struct hook hooks[MAX_HOOKS];
69
static size_t n_hooks;
70
71
static int signal_fds[2];
72
static volatile sig_atomic_t stored_sig_nr = SIG_ATOMIC_MAX;
73
74
#ifdef _WIN32
75
static HANDLE wevent;
76
#endif
77
78
static struct ovs_mutex mutex;
79
80
static void call_hooks(int sig_nr);
81
#ifdef _WIN32
82
static BOOL WINAPI ConsoleHandlerRoutine(DWORD dwCtrlType);
83
#endif
84
85
/* Sets up a pipe or event handle that will be used to wake up the current
86
 * process after signal is received, so it can be processed outside of the
87
 * signal handler context in fatal_signal_run(). */
88
static void
89
fatal_signal_create_wakeup_events(void)
90
0
{
91
0
#ifndef _WIN32
92
0
    xpipe_nonblocking(signal_fds);
93
#else
94
    wevent = CreateEvent(NULL, TRUE, FALSE, NULL);
95
    if (!wevent) {
96
        char *msg_buf = ovs_lasterror_to_string();
97
        VLOG_FATAL("Failed to create a event (%s).", msg_buf);
98
    }
99
#endif
100
0
}
101
102
static void
103
fatal_signal_destroy_wakeup_events(void)
104
0
{
105
0
#ifndef _WIN32
106
0
    close(signal_fds[0]);
107
0
    signal_fds[0] = -1;
108
0
    close(signal_fds[1]);
109
0
    signal_fds[1] = -1;
110
#else
111
    ResetEvent(wevent);
112
    CloseHandle(wevent);
113
    wevent = NULL;
114
#endif
115
0
}
116
117
118
/* Initializes the fatal signal handling module.  Calling this function is
119
 * optional, because calling any other function in the module will also
120
 * initialize it.  However, in a multithreaded program, the module must be
121
 * initialized while the process is still single-threaded. */
122
void
123
fatal_signal_init(void)
124
0
{
125
0
    static bool inited = false;
126
127
0
    if (!inited) {
128
0
        size_t i;
129
130
0
        assert_single_threaded();
131
0
        inited = true;
132
133
0
        ovs_mutex_init_recursive(&mutex);
134
135
        /* The dummy backtrace is needed.
136
         * See comment for send_backtrace_to_monitor(). */
137
0
        struct backtrace dummy_bt;
138
139
0
        backtrace_capture(&dummy_bt);
140
141
0
        fatal_signal_create_wakeup_events();
142
143
#ifdef _WIN32
144
        /* Register a function to handle Ctrl+C. */
145
        SetConsoleCtrlHandler(ConsoleHandlerRoutine, true);
146
#endif
147
148
0
        for (i = 0; i < ARRAY_SIZE(fatal_signals); i++) {
149
0
            int sig_nr = fatal_signals[i];
150
0
#ifndef _WIN32
151
0
            struct sigaction old_sa;
152
153
0
            xsigaction(sig_nr, NULL, &old_sa);
154
0
            if (old_sa.sa_handler == SIG_DFL
155
0
                && signal(sig_nr, fatal_signal_handler) == SIG_ERR) {
156
0
                VLOG_FATAL("signal failed (%s)", ovs_strerror(errno));
157
0
            }
158
#else
159
            if (signal(sig_nr, fatal_signal_handler) == SIG_ERR) {
160
                VLOG_FATAL("signal failed (%s)", ovs_strerror(errno));
161
            }
162
#endif
163
0
        }
164
0
        atexit(fatal_signal_atexit_handler);
165
0
    }
166
0
}
167
168
/* Registers 'hook_cb' to be called from inside poll_block() following a fatal
169
 * signal.  'hook_cb' does not need to be async-signal-safe.  In a
170
 * multithreaded program 'hook_cb' might be called from any thread, with
171
 * threads other than the one running 'hook_cb' in unknown states.
172
 *
173
 * If 'run_at_exit' is true, 'hook_cb' is also called during normal process
174
 * termination, e.g. when exit() is called or when main() returns.
175
 *
176
 * If the current process forks, fatal_signal_fork() may be called to clear the
177
 * parent process's fatal signal hooks, so that 'hook_cb' is only called when
178
 * the child terminates, not when the parent does.  When fatal_signal_fork() is
179
 * called, it calls the 'cancel_cb' function if it is nonnull, passing 'aux',
180
 * to notify that the hook has been canceled.  This allows the hook to free
181
 * memory, etc. */
182
void
183
fatal_signal_add_hook(void (*hook_cb)(void *aux), void (*cancel_cb)(void *aux),
184
                      void *aux, bool run_at_exit)
185
0
{
186
0
    fatal_signal_init();
187
188
0
    ovs_mutex_lock(&mutex);
189
0
    ovs_assert(n_hooks < MAX_HOOKS);
190
0
    hooks[n_hooks].hook_cb = hook_cb;
191
0
    hooks[n_hooks].cancel_cb = cancel_cb;
192
0
    hooks[n_hooks].aux = aux;
193
0
    hooks[n_hooks].run_at_exit = run_at_exit;
194
0
    n_hooks++;
195
0
    ovs_mutex_unlock(&mutex);
196
0
}
197
198
#ifdef HAVE_UNWIND
199
/* Convert unsigned long long to string.  This is needed because
200
 * using snprintf() is not async signal safe. */
201
static inline int
202
llong_to_hex_str(unsigned long long value, char *str)
203
{
204
    int i = 0, res;
205
206
    if (value / 16 > 0) {
207
        i = llong_to_hex_str(value / 16, str);
208
    }
209
210
    res = value % 16;
211
    str[i] = "0123456789abcdef"[res];
212
213
    return i + 1;
214
}
215
216
/* Send the backtrace buffer to monitor thread.
217
 *
218
 * Note that this runs in the signal handling context, any system
219
 * library functions used here must be async-signal-safe.
220
 */
221
static inline void
222
send_backtrace_to_monitor(void)
223
{
224
    /* volatile added to prevent a "clobbered" error on ppc64le with gcc */
225
    volatile int dep;
226
    struct unw_backtrace unw_bt[UNW_MAX_DEPTH];
227
    unw_cursor_t cursor;
228
    unw_context_t uc;
229
230
    if (daemonize_fd == -1) {
231
        return;
232
    }
233
234
    dep = 0;
235
    unw_getcontext(&uc);
236
    unw_init_local(&cursor, &uc);
237
238
    while (dep < UNW_MAX_DEPTH && unw_step(&cursor)) {
239
        memset(unw_bt[dep].func, 0, UNW_MAX_FUNCN);
240
        unw_get_reg(&cursor, UNW_REG_IP, &unw_bt[dep].ip);
241
        unw_get_proc_name(&cursor, unw_bt[dep].func, UNW_MAX_FUNCN,
242
                          &unw_bt[dep].offset);
243
        dep++;
244
    }
245
246
    if (monitor) {
247
        ignore(write(daemonize_fd, unw_bt,
248
                     dep * sizeof(struct unw_backtrace)));
249
    } else {
250
        /* Since there is no monitor daemon running, write backtrace
251
         * in current process.
252
         */
253
        char ip_str[16], offset_str[6];
254
        char line[64], fn_name[UNW_MAX_FUNCN];
255
256
        vlog_direct_write_to_log_file_unsafe(BACKTRACE_DUMP_MSG);
257
258
        for (int i = 0; i < dep; i++) {
259
            memset(line, 0, sizeof line);
260
            memset(fn_name, 0, sizeof fn_name);
261
            memset(offset_str, 0, sizeof offset_str);
262
            memset(ip_str, ' ', sizeof ip_str);
263
            ip_str[sizeof(ip_str) - 1] = 0;
264
265
            llong_to_hex_str(unw_bt[i].ip, ip_str);
266
            llong_to_hex_str(unw_bt[i].offset, offset_str);
267
268
            strcat(line, "0x");
269
            strcat(line, ip_str);
270
            strcat(line, "<");
271
            memcpy(fn_name, unw_bt[i].func, UNW_MAX_FUNCN - 1);
272
            strcat(line, fn_name);
273
            strcat(line, "+0x");
274
            strcat(line, offset_str);
275
            strcat(line, ">\n");
276
            vlog_direct_write_to_log_file_unsafe(line);
277
        }
278
    }
279
}
280
#elif HAVE_BACKTRACE
281
/* Send the backtrace to monitor thread.
282
 *
283
 * Note that this runs in the signal handling context, any system
284
 * library functions used here must be async-signal-safe.
285
 * backtrace() is only signal safe if the "libgcc" or equivalent was loaded
286
 * before the signal handler. In order to keep it safe the fatal_signal_init()
287
 * should always call backtrace_capture which will ensure that "libgcc" or
288
 * equivlent is loaded.
289
 */
290
static inline void
291
send_backtrace_to_monitor(void)
292
0
{
293
0
    struct backtrace bt;
294
295
0
    backtrace_capture(&bt);
296
297
0
    if (monitor && daemonize_fd > -1) {
298
0
        ignore(write(daemonize_fd, &bt, sizeof bt));
299
0
    } else {
300
0
        int log_fd = vlog_get_log_file_fd_unsafe();
301
302
0
        if (log_fd < 0) {
303
0
            return;
304
0
        }
305
306
0
        vlog_direct_write_to_log_file_unsafe(BACKTRACE_DUMP_MSG);
307
0
        backtrace_symbols_fd(bt.frames, bt.n_frames, log_fd);
308
0
    }
309
0
}
310
#else
311
static inline void
312
send_backtrace_to_monitor(void) {
313
    /* Nothing. */
314
}
315
#endif
316
317
/* Handles fatal signal number 'sig_nr'.
318
 *
319
 * Ordinarily this is the actual signal handler.  When other code needs to
320
 * handle one of our signals, however, it can register for that signal and, if
321
 * and when necessary, call this function to do fatal signal processing for it
322
 * and terminate the process.  Currently only timeval.c does this, for SIGALRM.
323
 * (It is not important whether the other code sets up its signal handler
324
 * before or after this file, because this file will only set up a signal
325
 * handler in the case where the signal has its default handling.)  */
326
void
327
fatal_signal_handler(int sig_nr)
328
0
{
329
0
#ifndef _WIN32
330
0
    if (sig_nr == SIGSEGV) {
331
0
        signal(sig_nr, SIG_DFL); /* Set it back immediately. */
332
0
        send_backtrace_to_monitor();
333
0
        raise(sig_nr);
334
0
    }
335
0
    ignore(write(signal_fds[1], "", 1));
336
#else
337
    SetEvent(wevent);
338
#endif
339
0
    stored_sig_nr = sig_nr;
340
0
}
341
342
/* Check whether a fatal signal has occurred and, if so, call the fatal signal
343
 * hooks and exit.
344
 *
345
 * This function is called automatically by poll_block(), but specialized
346
 * programs that may not always call poll_block() on a regular basis should
347
 * also call it periodically.  (Therefore, any function with "block" in its
348
 * name should call fatal_signal_run() each time it is called, either directly
349
 * or through poll_block(), because such functions can only used by specialized
350
 * programs that can afford to block outside their main loop around
351
 * poll_block().)
352
 */
353
void
354
fatal_signal_run(void)
355
0
{
356
0
    sig_atomic_t sig_nr;
357
358
0
    fatal_signal_init();
359
360
0
    sig_nr = stored_sig_nr;
361
0
    if (sig_nr != SIG_ATOMIC_MAX) {
362
0
        char namebuf[SIGNAL_NAME_BUFSIZE];
363
364
0
        ovs_mutex_lock(&mutex);
365
366
0
#ifndef _WIN32
367
0
        VLOG_WARN("terminating with signal %d (%s)",
368
0
                  (int)sig_nr, signal_name(sig_nr, namebuf, sizeof namebuf));
369
#else
370
        VLOG_WARN("terminating with signal %d", (int)sig_nr);
371
#endif
372
0
        call_hooks(sig_nr);
373
0
        fflush(stderr);
374
375
        /* Re-raise the signal with the default handling so that the program
376
         * termination status reflects that we were killed by this signal */
377
0
        signal(sig_nr, SIG_DFL);
378
0
        raise(sig_nr);
379
380
0
        ovs_mutex_unlock(&mutex);
381
0
        OVS_NOT_REACHED();
382
0
    }
383
0
}
384
385
void
386
fatal_signal_wait(void)
387
0
{
388
0
    fatal_signal_init();
389
#ifdef _WIN32
390
    poll_wevent_wait(wevent);
391
#else
392
0
    poll_fd_wait(signal_fds[0], POLLIN);
393
0
#endif
394
0
}
395
396
void
397
fatal_ignore_sigpipe(void)
398
0
{
399
0
#ifndef _WIN32
400
0
    signal(SIGPIPE, SIG_IGN);
401
0
#endif
402
0
}
403
404
void
405
fatal_signal_atexit_handler(void)
406
0
{
407
0
    call_hooks(0);
408
0
}
409
410
static void
411
call_hooks(int sig_nr)
412
0
{
413
0
    static volatile sig_atomic_t recurse = 0;
414
0
    if (!recurse) {
415
0
        size_t i;
416
417
0
        recurse = 1;
418
419
0
        for (i = 0; i < n_hooks; i++) {
420
0
            struct hook *h = &hooks[i];
421
0
            if (sig_nr || h->run_at_exit) {
422
0
                h->hook_cb(h->aux);
423
0
            }
424
0
        }
425
0
    }
426
0
}
427
428
#ifdef _WIN32
429
BOOL WINAPI ConsoleHandlerRoutine(DWORD dwCtrlType)
430
{
431
    stored_sig_nr = SIGINT;
432
    SetEvent(wevent);
433
    return true;
434
}
435
#endif
436

437
/* Files to delete on exit. */
438
static struct sset files = SSET_INITIALIZER(&files);
439
440
/* Has a hook function been registered with fatal_signal_add_hook() (and not
441
 * cleared by fatal_signal_fork())? */
442
static bool added_hook;
443
444
static void unlink_files(void *aux);
445
static void cancel_files(void *aux);
446
static void do_unlink_files(void);
447
448
/* Registers 'file' to be unlinked when the program terminates via exit() or a
449
 * fatal signal. */
450
void
451
fatal_signal_add_file_to_unlink(const char *file)
452
0
{
453
0
    fatal_signal_init();
454
455
0
    ovs_mutex_lock(&mutex);
456
0
    if (!added_hook) {
457
0
        added_hook = true;
458
0
        fatal_signal_add_hook(unlink_files, cancel_files, NULL, true);
459
0
    }
460
461
0
    sset_add(&files, file);
462
0
    ovs_mutex_unlock(&mutex);
463
0
}
464
465
/* Unregisters 'file' from being unlinked when the program terminates via
466
 * exit() or a fatal signal. */
467
void
468
fatal_signal_remove_file_to_unlink(const char *file)
469
0
{
470
0
    fatal_signal_init();
471
472
0
    ovs_mutex_lock(&mutex);
473
0
    sset_find_and_delete(&files, file);
474
0
    ovs_mutex_unlock(&mutex);
475
0
}
476
477
/* Like fatal_signal_remove_file_to_unlink(), but also unlinks 'file'.
478
 * Returns 0 if successful, otherwise a positive errno value. */
479
int
480
fatal_signal_unlink_file_now(const char *file)
481
0
{
482
0
    int error;
483
484
0
    fatal_signal_init();
485
486
0
    ovs_mutex_lock(&mutex);
487
488
0
    error = unlink(file) ? errno : 0;
489
0
    if (error) {
490
0
        VLOG_WARN("could not unlink \"%s\" (%s)", file, ovs_strerror(error));
491
0
    }
492
493
0
    fatal_signal_remove_file_to_unlink(file);
494
495
0
    ovs_mutex_unlock(&mutex);
496
497
0
    return error;
498
0
}
499
500
static void
501
unlink_files(void *aux OVS_UNUSED)
502
0
{
503
0
    do_unlink_files();
504
0
}
505
506
static void
507
cancel_files(void *aux OVS_UNUSED)
508
0
{
509
0
    sset_clear(&files);
510
0
    added_hook = false;
511
0
}
512
513
static void
514
do_unlink_files(void)
515
0
{
516
0
    const char *file;
517
518
0
    SSET_FOR_EACH (file, &files) {
519
0
        unlink(file);
520
0
    }
521
0
}
522

523
/* Clears all of the fatal signal hooks without executing them.  If any of the
524
 * hooks passed a 'cancel_cb' function to fatal_signal_add_hook(), then those
525
 * functions will be called, allowing them to free resources, etc.
526
 *
527
 * Also re-creates wake-up events, so signals in one of the processes do not
528
 * wake up the other one.
529
 *
530
 * Following a fork, one of the resulting processes can call this function to
531
 * allow it to terminate without calling the hooks registered before calling
532
 * this function.  New hooks registered after calling this function will take
533
 * effect normally. */
534
void
535
fatal_signal_fork(void)
536
0
{
537
0
    size_t i;
538
539
0
    assert_single_threaded();
540
541
0
    fatal_signal_destroy_wakeup_events();
542
0
    fatal_signal_create_wakeup_events();
543
544
0
    for (i = 0; i < n_hooks; i++) {
545
0
        struct hook *h = &hooks[i];
546
0
        if (h->cancel_cb) {
547
0
            h->cancel_cb(h->aux);
548
0
        }
549
0
    }
550
0
    n_hooks = 0;
551
552
    /* Raise any signals that we have already received with the default
553
     * handler. */
554
0
    if (stored_sig_nr != SIG_ATOMIC_MAX) {
555
0
        raise(stored_sig_nr);
556
0
    }
557
0
}
558
559
#ifndef _WIN32
560
/* Blocks all fatal signals and returns previous signal mask into
561
 * 'prev_mask'. */
562
void
563
fatal_signal_block(sigset_t *prev_mask)
564
0
{
565
0
    int i;
566
0
    sigset_t block_mask;
567
568
0
    sigemptyset(&block_mask);
569
0
    for (i = 0; i < ARRAY_SIZE(fatal_signals); i++) {
570
0
        int sig_nr = fatal_signals[i];
571
0
        sigaddset(&block_mask, sig_nr);
572
0
    }
573
0
    xpthread_sigmask(SIG_BLOCK, &block_mask, prev_mask);
574
0
}
575
#endif