source: libcfa/src/interpose.cfa @ a3a76ea

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since a3a76ea was 6011658, checked in by Thierry Delisle <tdelisle@…>, 3 years ago

Fixed abort to no longer deadlock when calling itself recursively.
abort now disable interrupts indefinitely.

  • Property mode set to 100644
File size: 11.0 KB
RevLine 
[9d944b2]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
[6b0b624]11// Last Modified By : Peter A. Buhr
[6791213]12// Last Modified On : Fri Mar 13 17:35:37 2020
13// Update Count     : 178
[9d944b2]14//
15
[7867eb9]16#include <stdarg.h>                                                                             // va_start, va_end
[851fd92]17#include <stdio.h>
[7867eb9]18#include <string.h>                                                                             // strlen
19#include <unistd.h>                                                                             // _exit, getpid
[dbe9b08]20#define __USE_GNU
[58b6d1b]21#include <signal.h>
[dbe9b08]22#undef __USE_GNU
[67db067]23extern "C" {
[7867eb9]24#include <dlfcn.h>                                                                              // dlopen, dlsym
25#include <execinfo.h>                                                                   // backtrace, messages
[9d944b2]26}
27
[73abe95]28#include "bits/debug.hfa"
29#include "bits/defs.hfa"
30#include "bits/signal.hfa"                                                              // sigHandler_?
31#include "startup.hfa"                                                                  // STARTUP_PRIORITY_CORE
[1d94116]32#include <assert.h>
[9d944b2]33
[3d5f2ef1]34//=============================================================================================
35// Interposing helpers
36//=============================================================================================
37
[ad64520]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
[67db067]43typedef void (* generic_fptr_t)(void);
[1d94116]44generic_fptr_t interpose_symbol( const char symbol[], const char version[] ) {
[9d944b2]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 ) {
[169d944]56                                abort( "interpose_symbol : failed to open libc, %s\n", error );
[9d944b2]57                        }
58                #endif
59        } // if
60
[67db067]61        union { generic_fptr_t fptr; void * ptr; } originalFunc;
[aca65621]62
[9d944b2]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
[aca65621]72
[9d944b2]73        error = dlerror();
[169d944]74        if ( error ) abort( "interpose_symbol : internal error, %s\n", error );
[9d944b2]75
76        return originalFunc.fptr;
77}
78
[67db067]79#define INTERPOSE_LIBC( x, ver ) __cabi_libc.x = (typeof(__cabi_libc.x))interpose_symbol( #x, ver )
[3d5f2ef1]80
81//=============================================================================================
[67db067]82// Interposition Startup logic
[3d5f2ef1]83//=============================================================================================
[9d944b2]84
[4f37255]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__ );
[dbe9b08]90
[3d5f2ef1]91struct {
[d7312ac]92        void (* exit)( int ) __attribute__(( __noreturn__ ));
93        void (* abort)( void ) __attribute__(( __noreturn__ ));
[3d5f2ef1]94} __cabi_libc;
95
[6bfe5cc]96extern "C" {
97        void __cfaabi_interpose_startup(void)  __attribute__(( constructor( STARTUP_PRIORITY_CORE ) ));
98        void __cfaabi_interpose_startup( void ) {
[8a13c47]99                const char *version = 0p;
[9d944b2]100
[ad64520]101                preload_libgcc();
102
[d7312ac]103#pragma GCC diagnostic push
104#pragma GCC diagnostic ignored "-Wdiscarded-qualifiers"
[3d5f2ef1]105                INTERPOSE_LIBC( abort, version );
106                INTERPOSE_LIBC( exit , version );
[d7312ac]107#pragma GCC diagnostic pop
[dbe9b08]108
[8a13c47]109                // As a precaution (and necessity), errors that result in termination are delivered on a separate stack because
110                // task stacks might be very small (4K) and the signal delivery corrupts memory to the point that a clean
111                // shutdown is impossible. Also, when a stack overflow encounters the non-accessible sentinel page (debug only)
112                // and generates a segment fault, the signal cannot be delivered on the sentinel page. Finally, calls to abort
113                // print a stack trace that uses substantial stack space.
114
115                #define MINSTKSZ SIGSTKSZ * 8
116                static char stack[MINSTKSZ] __attribute__(( aligned (16) ));
117                static stack_t ss;
118
119                ss.ss_sp = stack;
120                ss.ss_size = MINSTKSZ;
121                ss.ss_flags = 0;
122                if ( sigaltstack( &ss, 0p ) == -1 ) {
123                        abort( "__cfaabi_interpose_startup : internal error, sigaltstack error(%d) %s.", errno, strerror( errno ) );
124                } // if
125
[de94a60]126                // Failure handler
[8a13c47]127                __cfaabi_sigaction( SIGSEGV, sigHandler_segv, SA_SIGINFO | SA_ONSTACK );
128                __cfaabi_sigaction( SIGBUS , sigHandler_segv, SA_SIGINFO | SA_ONSTACK );
129                __cfaabi_sigaction( SIGILL , sigHandler_ill , SA_SIGINFO | SA_ONSTACK );
130                __cfaabi_sigaction( SIGFPE , sigHandler_fpe , SA_SIGINFO | SA_ONSTACK );
131                __cfaabi_sigaction( SIGTERM, sigHandler_term, SA_SIGINFO | SA_ONSTACK | SA_RESETHAND ); // one shot handler, return to default
132                __cfaabi_sigaction( SIGINT , sigHandler_term, SA_SIGINFO | SA_ONSTACK | SA_RESETHAND );
133                __cfaabi_sigaction( SIGABRT, sigHandler_term, SA_SIGINFO | SA_ONSTACK | SA_RESETHAND );
134                __cfaabi_sigaction( SIGHUP , sigHandler_term, SA_SIGINFO | SA_ONSTACK | SA_RESETHAND ); // terminal hangup
[6bfe5cc]135        }
[9d944b2]136}
137
[dbe9b08]138//=============================================================================================
139// Terminating Signals logic
140//=============================================================================================
141
[3d5f2ef1]142// Forward declare abort after the __typeof__ call to avoid ambiguities
[d7312ac]143void exit( int status, const char fmt[], ... ) __attribute__(( format(printf, 2, 3), __nothrow__, __leaf__, __noreturn__ ));
144void abort( const char fmt[], ... ) __attribute__(( format(printf, 1, 2), __nothrow__, __leaf__, __noreturn__ ));
[8a13c47]145void abort( bool signalAbort, const char fmt[], ... ) __attribute__(( format(printf, 2, 3), __nothrow__, __leaf__, __noreturn__ ));
[d870df3]146void __abort( bool signalAbort, const char fmt[], va_list args ) __attribute__(( __nothrow__, __leaf__, __noreturn__ ));
[3d5f2ef1]147
[9d944b2]148extern "C" {
[d7312ac]149        void abort( void ) __attribute__(( __nothrow__, __leaf__, __noreturn__ )) {
[1d94116]150                abort( false, "%s", "" );
[9d944b2]151        }
152
[d7312ac]153        void __cabi_abort( const char fmt[], ... ) __attribute__(( format(printf, 1, 2), __nothrow__, __leaf__, __noreturn__ )) {
[3d5f2ef1]154                va_list argp;
155                va_start( argp, fmt );
[d870df3]156                __abort( false, fmt, argp );
[3d5f2ef1]157                va_end( argp );
[9d944b2]158        }
159
[d7312ac]160        void exit( int status ) __attribute__(( __nothrow__, __leaf__, __noreturn__ )) {
[169d944]161                __cabi_libc.exit( status );
[3d5f2ef1]162        }
[9d944b2]163}
164
[8a13c47]165void * kernel_abort( void ) __attribute__(( __nothrow__, __leaf__, __weak__ )) { return 0p; }
[1d94116]166void kernel_abort_msg( void * data, char buffer[], int size ) __attribute__(( __nothrow__, __leaf__, __weak__ )) {}
[8a13c47]167// See concurrency/kernel.cfa for strong definition used in multi-processor mode.
[d7312ac]168int kernel_abort_lastframe( void ) __attribute__(( __nothrow__, __leaf__, __weak__ )) { return 4; }
[9d944b2]169
170enum { abort_text_size = 1024 };
171static char abort_text[ abort_text_size ];
172
[8a13c47]173static void __cfaabi_backtrace( int start ) {
[74330e7]174        enum { Frames = 50, };                                                          // maximum number of stack frames
[8a13c47]175        int last = kernel_abort_lastframe();                            // skip last N stack frames
[dbe9b08]176
177        void * array[Frames];
[6bfe5cc]178        size_t size = backtrace( array, Frames );
[74330e7]179        char ** messages = backtrace_symbols( array, size ); // does not demangle names
[dbe9b08]180
[8a13c47]181        *index( messages[0], '(' ) = '\0';                                      // find executable name
[1c40091]182        __cfaabi_bits_print_nolock( STDERR_FILENO, "Stack back trace for: %s\n", messages[0]);
[dbe9b08]183
[8a13c47]184        for ( unsigned int i = start; i < size - last && messages != 0p; i += 1 ) {
[524627e]185                char * name = 0p, * offset_begin = 0p, * offset_end = 0p;
[dbe9b08]186
[74330e7]187                for ( char * p = messages[i]; *p; p += 1 ) {    // find parantheses and +offset
[1c40091]188                        //__cfaabi_bits_print_nolock( "X %s\n", p);
[dbe9b08]189                        if ( *p == '(' ) {
190                                name = p;
[4f37255]191                        } else if ( *p == '+' ) {
[dbe9b08]192                                offset_begin = p;
[4f37255]193                        } else if ( *p == ')' ) {
[dbe9b08]194                                offset_end = p;
195                                break;
196                        }
197                }
198
[8a13c47]199                // if line contains symbol, print it
200                int frameNo = i - start;
[dbe9b08]201                if ( name && offset_begin && offset_end && name < offset_begin ) {
[8a13c47]202                        *name++ = '\0';                                                         // delimit strings
[dbe9b08]203                        *offset_begin++ = '\0';
204                        *offset_end++ = '\0';
205
[1c40091]206                        __cfaabi_bits_print_nolock( STDERR_FILENO, "(%i) %s : %s + %s %s\n", frameNo, messages[i], name, offset_begin, offset_end);
[4f37255]207                } else {                                                                                // otherwise, print the whole line
[1c40091]208                        __cfaabi_bits_print_nolock( STDERR_FILENO, "(%i) %s\n", frameNo, messages[i] );
[dbe9b08]209                }
210        }
211        free( messages );
212}
213
[8a13c47]214void exit( int status, const char fmt[], ... ) {
215        va_list args;
216        va_start( args, fmt );
217        vfprintf( stderr, fmt, args );
218        va_end( args );
219        __cabi_libc.exit( status );
220}
221
[6011658]222static volatile int __abort_stage = 0;
223
[d870df3]224// Cannot forward va_list.
225void __abort( bool signalAbort, const char fmt[], va_list args ) {
[6011658]226        int stage = __atomic_add_fetch( &__abort_stage, 1, __ATOMIC_SEQ_CST );
[8a13c47]227
[6011658]228        // First stage: stop the cforall kernel and print
229        if(stage == 1) {
230                // increment stage
231                stage = __atomic_add_fetch( &__abort_stage, 1, __ATOMIC_SEQ_CST );
[8a13c47]232
[6011658]233                // must be done here to lock down kernel
234                void * kernel_data = kernel_abort();
235                int len;
[8a13c47]236
[6011658]237                signal( SIGABRT, SIG_DFL );                                                     // prevent final "real" abort from recursing to handler
[8a13c47]238
[6011658]239                len = snprintf( abort_text, abort_text_size, "Cforall Runtime error (UNIX pid:%ld) ", (long int)getpid() ); // use UNIX pid (versus getPid)
240                __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
241
242                assert( fmt );
243                len = vsnprintf( abort_text, abort_text_size, fmt, args );
244                __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
245
246                // add optional newline if missing at the end of the format text
247                if ( fmt[strlen( fmt ) - 1] != '\n' ) {
248                        __cfaabi_bits_write( STDERR_FILENO, "\n", 1 );
249                } // if
250                kernel_abort_msg( kernel_data, abort_text, abort_text_size );
251        }
252
253        // Second stage: print the backtrace
254        if(stage == 2) {
255                // increment stage
256                stage = __atomic_add_fetch( &__abort_stage, 1, __ATOMIC_SEQ_CST );
257
258                // print stack trace in handler
259                __cfaabi_backtrace( signalAbort ? 4 : 2 );
260        }
[5ccee64]261
[6011658]262        do {
263                // Finally call abort
264                __cabi_libc.abort();
[8a13c47]265
[6011658]266                // Loop so that we never return
267        } while(true);
[8a13c47]268}
269
270void abort( const char fmt[], ... ) {
271        va_list args;
272        va_start( args, fmt );
[d870df3]273        __abort( false, fmt, args );
274    // CONTROL NEVER REACHES HERE!
[8a13c47]275        va_end( args );
276}
277
[d870df3]278void abort( bool signalAbort, const char fmt[], ... ) {
279    va_list args;
280    va_start( args, fmt );
281    __abort( signalAbort, fmt, args );
282    // CONTROL NEVER REACHES HERE!
283    va_end( args );
284}
285
[dbe9b08]286void sigHandler_segv( __CFA_SIGPARMS__ ) {
[8a13c47]287                if ( sfp->si_addr == 0p ) {
288                        abort( true, "Null pointer (0p) dereference.\n" );
[1469a8a]289                } else {
[8a13c47]290                        abort( true, "%s at memory location %p.\n"
[1469a8a]291                                   "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",
292                                   (sig == SIGSEGV ? "Segment fault" : "Bus error"), sfp->si_addr );
293                }
[2b8bc41]294}
295
296void sigHandler_ill( __CFA_SIGPARMS__ ) {
[8a13c47]297        abort( true, "Executing illegal instruction at location %p.\n"
[2b8bc41]298                        "Possible cause is stack corruption.\n",
299                        sfp->si_addr );
300}
301
302void sigHandler_fpe( __CFA_SIGPARMS__ ) {
303        const char * msg;
304
[a424315d]305        choose( sfp->si_code ) {
306          case FPE_INTDIV, FPE_FLTDIV: msg = "divide by zero";
307          case FPE_FLTOVF: msg = "overflow";
308          case FPE_FLTUND: msg = "underflow";
309          case FPE_FLTRES: msg = "inexact result";
310          case FPE_FLTINV: msg = "invalid operation";
[2b8bc41]311          default: msg = "unknown";
[a424315d]312        } // choose
[8a13c47]313        abort( true, "Computation error %s at location %p.\n", msg, sfp->si_addr );
[dbe9b08]314}
315
[94dea96]316void sigHandler_term( __CFA_SIGPARMS__ ) {
[8a13c47]317        abort( true, "Application interrupted by signal: %s.\n", strsignal( sig ) );
[94dea96]318}
319
[6b0b624]320// Local Variables: //
321// mode: c //
322// tab-width: 4 //
323// End: //
Note: See TracBrowser for help on using the repository browser.