Update primary code license to Apache 2.0.
[cascardo/ovs.git] / lib / fault.c
1 /*
2  * Copyright (c) 2008, 2009 Nicira Networks.
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
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 }