source: libcfa/src/interpose.cfa @ bbe3719

ADTast-experimentalenumforall-pointer-decaypthread-emulationqualifiedEnum
Last change on this file since bbe3719 was 96f002c1, checked in by Thierry Delisle <tdelisle@…>, 3 years ago

Added new device folder and cpu file to libcfa

  • Property mode set to 100644
File size: 11.5 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2016 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// interpose.c --
8//
9// Author           : Thierry Delisle
10// Created On       : Wed Mar 29 16:10:31 2017
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Fri Mar 13 17:35:37 2020
13// Update Count     : 178
14//
15
16#include <stdarg.h>                                                                             // va_start, va_end
17#include <stdio.h>
18#include <string.h>                                                                             // strlen
19#include <unistd.h>                                                                             // _exit, getpid
20#define __USE_GNU
21#include <signal.h>
22#undef __USE_GNU
23extern "C" {
24#include <dlfcn.h>                                                                              // dlopen, dlsym
25#include <execinfo.h>                                                                   // backtrace, messages
26}
27
28#include "bits/debug.hfa"
29#include "bits/defs.hfa"
30#include "bits/signal.hfa"                                                              // sigHandler_?
31#include "startup.hfa"                                                                  // STARTUP_PRIORITY_CORE
32#include <assert.h>
33
34//=============================================================================================
35// Interposing helpers
36//=============================================================================================
37
38void preload_libgcc(void) {
39        dlopen( "libgcc_s.so.1", RTLD_NOW );
40        if ( const char * error = dlerror() ) abort( "interpose_symbol : internal error pre-loading libgcc, %s\n", error );
41}
42
43typedef void (* generic_fptr_t)(void);
44generic_fptr_t interpose_symbol( const char symbol[], const char version[] ) {
45        const char * error;
46
47        static void * library;
48        if ( ! library ) {
49                #if defined( RTLD_NEXT )
50                        library = RTLD_NEXT;
51                #else
52                        // missing RTLD_NEXT => must hard-code library name, assuming libstdc++
53                        library = dlopen( "libc.so.6", RTLD_LAZY );
54                        error = dlerror();
55                        if ( error ) {
56                                abort( "interpose_symbol : failed to open libc, %s\n", error );
57                        }
58                #endif
59        } // if
60
61        union { generic_fptr_t fptr; void * ptr; } originalFunc;
62
63        #if defined( _GNU_SOURCE )
64                if ( version ) {
65                        originalFunc.ptr = dlvsym( library, symbol, version );
66                } else {
67                        originalFunc.ptr = dlsym( library, symbol );
68                }
69        #else
70                originalFunc.ptr = dlsym( library, symbol );
71        #endif // _GNU_SOURCE
72
73        error = dlerror();
74        if ( error ) abort( "interpose_symbol : internal error, %s\n", error );
75
76        return originalFunc.fptr;
77}
78
79#define INTERPOSE_LIBC( x, ver ) __cabi_libc.x = (typeof(__cabi_libc.x))interpose_symbol( #x, ver )
80
81//=============================================================================================
82// Interposition Startup logic
83//=============================================================================================
84
85void sigHandler_segv( __CFA_SIGPARMS__ );
86void sigHandler_ill ( __CFA_SIGPARMS__ );
87void sigHandler_fpe ( __CFA_SIGPARMS__ );
88void sigHandler_abrt( __CFA_SIGPARMS__ );
89void sigHandler_term( __CFA_SIGPARMS__ );
90
91struct {
92        void (* exit)( int ) __attribute__(( __noreturn__ ));
93        void (* abort)( void ) __attribute__(( __noreturn__ ));
94} __cabi_libc;
95
96extern "C" {
97        void __cfaabi_interpose_startup( void ) {
98                const char *version = 0p;
99
100                preload_libgcc();
101
102#pragma GCC diagnostic push
103#pragma GCC diagnostic ignored "-Wdiscarded-qualifiers"
104                INTERPOSE_LIBC( abort, version );
105                INTERPOSE_LIBC( exit , version );
106#pragma GCC diagnostic pop
107
108                // As a precaution (and necessity), errors that result in termination are delivered on a separate stack because
109                // task stacks might be very small (4K) and the signal delivery corrupts memory to the point that a clean
110                // shutdown is impossible. Also, when a stack overflow encounters the non-accessible sentinel page (debug only)
111                // and generates a segment fault, the signal cannot be delivered on the sentinel page. Finally, calls to abort
112                // print a stack trace that uses substantial stack space.
113
114                #define MINSTKSZ SIGSTKSZ * 8
115                static char stack[MINSTKSZ] __attribute__(( aligned (16) ));
116                static stack_t ss;
117
118                ss.ss_sp = stack;
119                ss.ss_size = MINSTKSZ;
120                ss.ss_flags = 0;
121                if ( sigaltstack( &ss, 0p ) == -1 ) {
122                        abort( "__cfaabi_interpose_startup : internal error, sigaltstack error(%d) %s.", errno, strerror( errno ) );
123                } // if
124
125                // Failure handler
126                 // internal errors
127                __cfaabi_sigaction( SIGSEGV, sigHandler_segv, SA_SIGINFO | SA_ONSTACK ); // Invalid memory reference (default: Core)
128                __cfaabi_sigaction( SIGBUS , sigHandler_segv, SA_SIGINFO | SA_ONSTACK ); // Bus error, bad memory access (default: Core)
129                __cfaabi_sigaction( SIGILL , sigHandler_ill , SA_SIGINFO | SA_ONSTACK ); // Illegal Instruction (default: Core)
130                __cfaabi_sigaction( SIGFPE , sigHandler_fpe , SA_SIGINFO | SA_ONSTACK ); // Floating-point exception (default: Core)
131
132                // handlers to outside errors
133                // reset in-case they insist and send it over and over
134                __cfaabi_sigaction( SIGTERM, sigHandler_term, SA_SIGINFO | SA_ONSTACK | SA_RESETHAND ); // Termination signal (default: Term)
135                __cfaabi_sigaction( SIGINT , sigHandler_term, SA_SIGINFO | SA_ONSTACK | SA_RESETHAND ); // Interrupt from keyboard (default: Term)
136                __cfaabi_sigaction( SIGHUP , sigHandler_term, SA_SIGINFO | SA_ONSTACK | SA_RESETHAND ); // Hangup detected on controlling terminal or death of controlling process (default: Term)
137                __cfaabi_sigaction( SIGQUIT, sigHandler_term, SA_SIGINFO | SA_ONSTACK | SA_RESETHAND ); // Quit from keyboard (default: Core)
138                __cfaabi_sigaction( SIGABRT, sigHandler_term, SA_SIGINFO | SA_ONSTACK | SA_RESETHAND ); // Abort signal from abort(3) (default: Core)
139        }
140}
141
142//=============================================================================================
143// Terminating Signals logic
144//=============================================================================================
145
146// Forward declare abort after the __typeof__ call to avoid ambiguities
147void exit( int status, const char fmt[], ... ) __attribute__(( format(printf, 2, 3), __nothrow__, __leaf__, __noreturn__ ));
148void abort( const char fmt[], ... ) __attribute__(( format(printf, 1, 2), __nothrow__, __leaf__, __noreturn__ ));
149void abort( bool signalAbort, const char fmt[], ... ) __attribute__(( format(printf, 2, 3), __nothrow__, __leaf__, __noreturn__ ));
150void __abort( bool signalAbort, const char fmt[], va_list args ) __attribute__(( __nothrow__, __leaf__, __noreturn__ ));
151
152extern "C" {
153        void abort( void ) __attribute__(( __nothrow__, __leaf__, __noreturn__ )) {
154                abort( false, "%s", "" );
155        }
156
157        void __cabi_abort( const char fmt[], ... ) __attribute__(( format(printf, 1, 2), __nothrow__, __leaf__, __noreturn__ )) {
158                va_list argp;
159                va_start( argp, fmt );
160                __abort( false, fmt, argp );
161                va_end( argp );
162        }
163
164        void exit( int status ) __attribute__(( __nothrow__, __leaf__, __noreturn__ )) {
165                __cabi_libc.exit( status );
166        }
167}
168
169// See concurrency/kernel.cfa and concurrency/preemption.cfa for strong definition used in multi-processor mode.
170void __kernel_abort_lock( void ) __attribute__(( __nothrow__, __leaf__, __weak__ )) {}
171void __kernel_abort_msg( char buffer[], int size ) __attribute__(( __nothrow__, __leaf__, __weak__ )) {}
172int __kernel_abort_lastframe( void ) __attribute__(( __nothrow__, __leaf__, __weak__ )) { return 4; }
173
174enum { abort_text_size = 1024 };
175static char abort_text[ abort_text_size ];
176
177static void __cfaabi_backtrace( int start ) {
178        enum { Frames = 50, };                                                          // maximum number of stack frames
179        int last = __kernel_abort_lastframe();                          // skip last N stack frames
180
181        void * array[Frames];
182        size_t size = backtrace( array, Frames );
183        char ** messages = backtrace_symbols( array, size ); // does not demangle names
184
185        *index( messages[0], '(' ) = '\0';                                      // find executable name
186        __cfaabi_bits_print_nolock( STDERR_FILENO, "Stack back trace for: %s\n", messages[0]);
187
188        for ( unsigned int i = start; i < size - last && messages != 0p; i += 1 ) {
189                char * name = 0p, * offset_begin = 0p, * offset_end = 0p;
190
191                for ( char * p = messages[i]; *p; p += 1 ) {    // find parantheses and +offset
192                        //__cfaabi_bits_print_nolock( "X %s\n", p);
193                        if ( *p == '(' ) {
194                                name = p;
195                        } else if ( *p == '+' ) {
196                                offset_begin = p;
197                        } else if ( *p == ')' ) {
198                                offset_end = p;
199                                break;
200                        }
201                }
202
203                // if line contains symbol, print it
204                int frameNo = i - start;
205                if ( name && offset_begin && offset_end && name < offset_begin ) {
206                        *name++ = '\0';                                                         // delimit strings
207                        *offset_begin++ = '\0';
208                        *offset_end++ = '\0';
209
210                        __cfaabi_bits_print_nolock( STDERR_FILENO, "(%i) %s : %s + %s %s\n", frameNo, messages[i], name, offset_begin, offset_end);
211                } else {                                                                                // otherwise, print the whole line
212                        __cfaabi_bits_print_nolock( STDERR_FILENO, "(%i) %s\n", frameNo, messages[i] );
213                }
214        }
215        free( messages );
216}
217
218void exit( int status, const char fmt[], ... ) {
219        va_list args;
220        va_start( args, fmt );
221        vfprintf( stderr, fmt, args );
222        va_end( args );
223        __cabi_libc.exit( status );
224}
225
226static volatile bool __abort_first = 0;
227
228// Cannot forward va_list.
229void __abort( bool signalAbort, const char fmt[], va_list args ) {
230        // Multiple threads can come here from multiple paths
231        // To make sure this is safe any concurrent/subsequent call to abort is redirected to libc-abort
232        bool first = ! __atomic_test_and_set( &__abort_first, __ATOMIC_SEQ_CST);
233
234        // Prevent preemption from kicking-in and messing with the abort
235        __kernel_abort_lock();
236
237        // first to abort ?
238        if ( !first ) {
239                // We aren't the first to abort just let C handle it
240                signal( SIGABRT, SIG_DFL );     // restore default in case we came here through the function.
241                __cabi_libc.abort();
242        }
243
244        int len = snprintf( abort_text, abort_text_size, "Cforall Runtime error (UNIX pid:%ld) ", (long int)getpid() ); // use UNIX pid (versus getPid)
245        __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
246
247        // print the cause of the error
248        assert( fmt );
249        len = vsnprintf( abort_text, abort_text_size, fmt, args );
250        __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
251
252        // add optional newline if missing at the end of the format text
253        if ( fmt[strlen( fmt ) - 1] != '\n' ) {
254                __cfaabi_bits_write( STDERR_FILENO, "\n", 1 );
255        } // if
256
257        // Give the kernel the chance to add some data in here
258        __kernel_abort_msg( abort_text, abort_text_size );
259
260        // print stack trace in handler
261        __cfaabi_backtrace( signalAbort ? 4 : 2 );
262
263        // Finally call abort
264        __cabi_libc.abort();
265
266}
267
268void abort( const char fmt[], ... ) {
269        va_list args;
270        va_start( args, fmt );
271        __abort( false, fmt, args );
272    // CONTROL NEVER REACHES HERE!
273        va_end( args );
274}
275
276void abort( bool signalAbort, const char fmt[], ... ) {
277    va_list args;
278    va_start( args, fmt );
279    __abort( signalAbort, fmt, args );
280    // CONTROL NEVER REACHES HERE!
281    va_end( args );
282}
283
284void sigHandler_segv( __CFA_SIGPARMS__ ) {
285                if ( sfp->si_addr == 0p ) {
286                        abort( true, "Null pointer (0p) dereference.\n" );
287                } else {
288                        abort( true, "%s at memory location %p.\n"
289                                   "Possible cause is reading outside the address space or writing to a protected area within the address space with an invalid pointer or subscript.\n",
290                                   (sig == SIGSEGV ? "Segment fault" : "Bus error"), sfp->si_addr );
291                }
292}
293
294void sigHandler_ill( __CFA_SIGPARMS__ ) {
295        abort( true, "Executing illegal instruction at location %p.\n"
296                        "Possible cause is stack corruption.\n",
297                        sfp->si_addr );
298}
299
300void sigHandler_fpe( __CFA_SIGPARMS__ ) {
301        const char * msg;
302
303        choose( sfp->si_code ) {
304          case FPE_INTDIV, FPE_FLTDIV: msg = "divide by zero";
305          case FPE_FLTOVF: msg = "overflow";
306          case FPE_FLTUND: msg = "underflow";
307          case FPE_FLTRES: msg = "inexact result";
308          case FPE_FLTINV: msg = "invalid operation";
309          default: msg = "unknown";
310        } // choose
311        abort( true, "Computation error %s at location %p.\n", msg, sfp->si_addr );
312}
313
314void sigHandler_term( __CFA_SIGPARMS__ ) {
315        abort( true, "Application interrupted by signal: %s.\n", strsignal( sig ) );
316}
317
318// Local Variables: //
319// mode: c //
320// tab-width: 4 //
321// End: //
Note: See TracBrowser for help on using the repository browser.