Import from old repository commit 61ef2b42a9c4ba8e1600f15bb0236765edc2ad45.
[cascardo/ovs.git] / lib / fault.c
1 /*
2  * Copyright (c) 2008, 2009 Nicira Networks.
3  *
4  * Permission to use, copy, modify, and/or distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16
17 #include <config.h>
18 #include "fault.h"
19 #include <dlfcn.h>
20 #include <inttypes.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <signal.h>
25 #include "util.h"
26
27 #include "vlog.h"
28 #define THIS_MODULE VLM_fault
29
30 static void
31 fault_handler(int sig_nr)
32 {
33     VLOG_EMER("Caught signal %d.", sig_nr);
34     log_backtrace();
35     fflush(stdout);
36     fflush(stderr);
37
38     signal(sig_nr, SIG_DFL);
39     raise(sig_nr);
40 }
41
42 void
43 log_backtrace(void)
44 {
45     /* During the loop:
46
47        frame[0] points to the next frame.
48        frame[1] points to the return address. */
49     void **frame;
50     for (frame = __builtin_frame_address(0);
51          frame != NULL && frame[0] != NULL;
52          frame = frame[0]) {
53         Dl_info addrinfo;
54         if (!dladdr(frame[1], &addrinfo) || !addrinfo.dli_sname) {
55             fprintf(stderr, "  0x%08"PRIxPTR"\n", (uintptr_t) frame[1]);
56         } else {
57             fprintf(stderr, "  0x%08"PRIxPTR" (%s+0x%x)\n",
58                     (uintptr_t) frame[1], addrinfo.dli_sname,
59                     (char *) frame[1] - (char *) addrinfo.dli_saddr); 
60         }
61     }
62     fflush(stderr);
63 }
64
65 void
66 register_fault_handlers(void)
67 {
68     signal(SIGABRT, fault_handler);
69     signal(SIGBUS, fault_handler);
70     signal(SIGFPE, fault_handler);
71     signal(SIGILL, fault_handler);
72     signal(SIGSEGV, fault_handler);
73 }