source: libcfa/src/interpose.cfa @ 4eebbcc

ADTast-experimental
Last change on this file since 4eebbcc was 089a0d7, checked in by Peter A. Buhr <pabuhr@…>, 16 months ago

formatting, rework interpose code (again), remove unnecessary #include files, temporary patch to fix 32-bit build problem using _GNU_SOURCE

  • Property mode set to 100644
File size: 12.4 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
[089a0d7]12// Last Modified On : Mon Mar 13 22:39:12 2023
13// Update Count     : 193
[9d944b2]14//
15
[851fd92]16#include <stdio.h>
[7867eb9]17#include <unistd.h>                                                                             // _exit, getpid
[67db067]18extern "C" {
[7867eb9]19#include <dlfcn.h>                                                                              // dlopen, dlsym
20#include <execinfo.h>                                                                   // backtrace, messages
[9d944b2]21}
22
[73abe95]23#include "bits/defs.hfa"
24#include "bits/signal.hfa"                                                              // sigHandler_?
25#include "startup.hfa"                                                                  // STARTUP_PRIORITY_CORE
[1d94116]26#include <assert.h>
[9d944b2]27
[3d5f2ef1]28//=============================================================================================
29// Interposing helpers
30//=============================================================================================
31
[032234bd]32static void preload_libgcc(void) {
[ad64520]33        dlopen( "libgcc_s.so.1", RTLD_NOW );
34        if ( const char * error = dlerror() ) abort( "interpose_symbol : internal error pre-loading libgcc, %s\n", error );
35}
36
[67db067]37typedef void (* generic_fptr_t)(void);
[95dab9e]38
[089a0d7]39static generic_fptr_t do_interpose_symbol( void * library, const char symbol[], const char version[] ) {
[95dab9e]40        union { generic_fptr_t fptr; void * ptr; } originalFunc;
41
[c910709]42        originalFunc.ptr = dlsym( library, symbol );
[089a0d7]43        if ( ! originalFunc.ptr ) {                                                             // == nullptr
44                abort( "interpose_symbol : internal error, %s\n", dlerror() );
45        } // if
[95dab9e]46        return originalFunc.fptr;
47}
48
[032234bd]49static generic_fptr_t interpose_symbol( const char symbol[], const char version[] ) {
[8bb46d2]50        void * library;
51        #if defined( RTLD_NEXT )
52        library = RTLD_NEXT;
53        #else
[089a0d7]54        // missing RTLD_NEXT => must hard-code library name, assuming libstdc++
[8bb46d2]55        library = dlopen( "libc.so.6", RTLD_LAZY );
[089a0d7]56        if ( ! library ) {                                                                      // == nullptr
57                abort( "interpose_symbol : failed to open libc, %s\n", dlerror() );
[9d944b2]58        } // if
[089a0d7]59        #endif // RTLD_NEXT
[9d944b2]60
[089a0d7]61        return do_interpose_symbol( library, symbol, version );
[9d944b2]62}
63
[67db067]64#define INTERPOSE_LIBC( x, ver ) __cabi_libc.x = (typeof(__cabi_libc.x))interpose_symbol( #x, ver )
[3d5f2ef1]65
66//=============================================================================================
[67db067]67// Interposition Startup logic
[3d5f2ef1]68//=============================================================================================
[9d944b2]69
[032234bd]70static void sigHandler_segv( __CFA_SIGPARMS__ );
71static void sigHandler_ill ( __CFA_SIGPARMS__ );
72static void sigHandler_fpe ( __CFA_SIGPARMS__ );
73static void sigHandler_abrt( __CFA_SIGPARMS__ );
74static void sigHandler_term( __CFA_SIGPARMS__ );
[dbe9b08]75
[032234bd]76static struct {
[d7312ac]77        void (* exit)( int ) __attribute__(( __noreturn__ ));
78        void (* abort)( void ) __attribute__(( __noreturn__ ));
[3d5f2ef1]79} __cabi_libc;
80
[032234bd]81libcfa_public int cfa_main_returned;
[7dd98b6]82
[6bfe5cc]83extern "C" {
[95dab9e]84        void __cfathreadabi_interpose_startup( generic_fptr_t (*do_interpose_symbol)( void * library, const char symbol[], const char version[] ) ) __attribute__((weak));
[6bfe5cc]85        void __cfaabi_interpose_startup( void ) {
[8a13c47]86                const char *version = 0p;
[7dd98b6]87                cfa_main_returned = 0;
[9d944b2]88
[ad64520]89                preload_libgcc();
90
[43f29f6]91                #pragma GCC diagnostic push
92                #pragma GCC diagnostic ignored "-Wdiscarded-qualifiers"
[3d5f2ef1]93                INTERPOSE_LIBC( abort, version );
94                INTERPOSE_LIBC( exit , version );
[43f29f6]95                #pragma GCC diagnostic pop
[dbe9b08]96
[95dab9e]97                if(__cfathreadabi_interpose_startup) __cfathreadabi_interpose_startup( do_interpose_symbol );
98
[8bb46d2]99                // SKULLDUGGERY: In Ubuntu 22.04, someone augmented signal.h to allow SIGSTKSZ to be "sysconf(_SC_SIGSTKSZ)" in
100                // sigstksz.h, as well as 8192 in sigstack.h. HOWEVER, they forgot to provide a mechanism to tell signal.h to
101                // use sigstack.h rather than sigstksz.h. (I'm not happy.) By undefining _GNU_SOURCE before signal.h and
102                // redefining it afterwards, you can get 8192, but then nothing works correctly inside of signal.h without
103                // _GNU_SOURCE defined.  So what is needed is a way to get signal.h to use sigstack.h WITH _GNU_SOURCE defined.
104                // Basically something is wrong with features.h and its use in signal.h.
105
106                #undef SIGSTKSZ
107                #define SIGSTKSZ 8192
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
[92bfda0]127                 // internal errors
128                __cfaabi_sigaction( SIGSEGV, sigHandler_segv, SA_SIGINFO | SA_ONSTACK ); // Invalid memory reference (default: Core)
129                __cfaabi_sigaction( SIGBUS , sigHandler_segv, SA_SIGINFO | SA_ONSTACK ); // Bus error, bad memory access (default: Core)
130                __cfaabi_sigaction( SIGILL , sigHandler_ill , SA_SIGINFO | SA_ONSTACK ); // Illegal Instruction (default: Core)
131                __cfaabi_sigaction( SIGFPE , sigHandler_fpe , SA_SIGINFO | SA_ONSTACK ); // Floating-point exception (default: Core)
132
133                // handlers to outside errors
134                // reset in-case they insist and send it over and over
135                __cfaabi_sigaction( SIGTERM, sigHandler_term, SA_SIGINFO | SA_ONSTACK | SA_RESETHAND ); // Termination signal (default: Term)
136                __cfaabi_sigaction( SIGINT , sigHandler_term, SA_SIGINFO | SA_ONSTACK | SA_RESETHAND ); // Interrupt from keyboard (default: Term)
137                __cfaabi_sigaction( SIGHUP , sigHandler_term, SA_SIGINFO | SA_ONSTACK | SA_RESETHAND ); // Hangup detected on controlling terminal or death of controlling process (default: Term)
138                __cfaabi_sigaction( SIGQUIT, sigHandler_term, SA_SIGINFO | SA_ONSTACK | SA_RESETHAND ); // Quit from keyboard (default: Core)
139                __cfaabi_sigaction( SIGABRT, sigHandler_term, SA_SIGINFO | SA_ONSTACK | SA_RESETHAND ); // Abort signal from abort(3) (default: Core)
[6bfe5cc]140        }
[9d944b2]141}
142
[dbe9b08]143//=============================================================================================
144// Terminating Signals logic
145//=============================================================================================
146
[3d5f2ef1]147// Forward declare abort after the __typeof__ call to avoid ambiguities
[032234bd]148libcfa_public void exit( int status, const char fmt[], ... ) __attribute__(( format(printf, 2, 3), __nothrow__, __leaf__, __noreturn__ ));
149libcfa_public void abort( const char fmt[], ... ) __attribute__(( format(printf, 1, 2), __nothrow__, __leaf__, __noreturn__ ));
150libcfa_public void abort( bool signalAbort, const char fmt[], ... ) __attribute__(( format(printf, 2, 3), __nothrow__, __leaf__, __noreturn__ ));
151libcfa_public void __abort( bool signalAbort, const char fmt[], va_list args ) __attribute__(( __nothrow__, __leaf__, __noreturn__ ));
[3d5f2ef1]152
[9d944b2]153extern "C" {
[032234bd]154        libcfa_public void abort( void ) __attribute__(( __nothrow__, __leaf__, __noreturn__ )) {
[1d94116]155                abort( false, "%s", "" );
[9d944b2]156        }
157
[032234bd]158        libcfa_public void __cabi_abort( const char fmt[], ... ) __attribute__(( format(printf, 1, 2), __nothrow__, __leaf__, __noreturn__ )) {
[3d5f2ef1]159                va_list argp;
160                va_start( argp, fmt );
[d870df3]161                __abort( false, fmt, argp );
[3d5f2ef1]162                va_end( argp );
[9d944b2]163        }
164
[032234bd]165        libcfa_public void exit( int status ) __attribute__(( __nothrow__, __leaf__, __noreturn__ )) {
[169d944]166                __cabi_libc.exit( status );
[3d5f2ef1]167        }
[9d944b2]168}
169
[92bfda0]170// See concurrency/kernel.cfa and concurrency/preemption.cfa for strong definition used in multi-processor mode.
171void __kernel_abort_lock( void ) __attribute__(( __nothrow__, __leaf__, __weak__ )) {}
172void __kernel_abort_msg( char buffer[], int size ) __attribute__(( __nothrow__, __leaf__, __weak__ )) {}
173int __kernel_abort_lastframe( void ) __attribute__(( __nothrow__, __leaf__, __weak__ )) { return 4; }
[9d944b2]174
175enum { abort_text_size = 1024 };
176static char abort_text[ abort_text_size ];
177
[8a13c47]178static void __cfaabi_backtrace( int start ) {
[74330e7]179        enum { Frames = 50, };                                                          // maximum number of stack frames
[92bfda0]180        int last = __kernel_abort_lastframe();                          // skip last N stack frames
[dbe9b08]181
182        void * array[Frames];
[6bfe5cc]183        size_t size = backtrace( array, Frames );
[74330e7]184        char ** messages = backtrace_symbols( array, size ); // does not demangle names
[dbe9b08]185
[8a13c47]186        *index( messages[0], '(' ) = '\0';                                      // find executable name
[1c40091]187        __cfaabi_bits_print_nolock( STDERR_FILENO, "Stack back trace for: %s\n", messages[0]);
[dbe9b08]188
[8a13c47]189        for ( unsigned int i = start; i < size - last && messages != 0p; i += 1 ) {
[524627e]190                char * name = 0p, * offset_begin = 0p, * offset_end = 0p;
[dbe9b08]191
[74330e7]192                for ( char * p = messages[i]; *p; p += 1 ) {    // find parantheses and +offset
[1c40091]193                        //__cfaabi_bits_print_nolock( "X %s\n", p);
[dbe9b08]194                        if ( *p == '(' ) {
195                                name = p;
[4f37255]196                        } else if ( *p == '+' ) {
[dbe9b08]197                                offset_begin = p;
[4f37255]198                        } else if ( *p == ')' ) {
[dbe9b08]199                                offset_end = p;
200                                break;
201                        }
202                }
203
[8a13c47]204                // if line contains symbol, print it
205                int frameNo = i - start;
[dbe9b08]206                if ( name && offset_begin && offset_end && name < offset_begin ) {
[8a13c47]207                        *name++ = '\0';                                                         // delimit strings
[dbe9b08]208                        *offset_begin++ = '\0';
209                        *offset_end++ = '\0';
210
[1c40091]211                        __cfaabi_bits_print_nolock( STDERR_FILENO, "(%i) %s : %s + %s %s\n", frameNo, messages[i], name, offset_begin, offset_end);
[4f37255]212                } else {                                                                                // otherwise, print the whole line
[1c40091]213                        __cfaabi_bits_print_nolock( STDERR_FILENO, "(%i) %s\n", frameNo, messages[i] );
[dbe9b08]214                }
215        }
216        free( messages );
217}
218
[8a13c47]219void exit( int status, const char fmt[], ... ) {
220        va_list args;
221        va_start( args, fmt );
222        vfprintf( stderr, fmt, args );
223        va_end( args );
224        __cabi_libc.exit( status );
225}
226
[92bfda0]227static volatile bool __abort_first = 0;
[6011658]228
[d870df3]229// Cannot forward va_list.
230void __abort( bool signalAbort, const char fmt[], va_list args ) {
[92bfda0]231        // Multiple threads can come here from multiple paths
232        // To make sure this is safe any concurrent/subsequent call to abort is redirected to libc-abort
233        bool first = ! __atomic_test_and_set( &__abort_first, __ATOMIC_SEQ_CST);
[8a13c47]234
[92bfda0]235        // Prevent preemption from kicking-in and messing with the abort
236        __kernel_abort_lock();
[8a13c47]237
[92bfda0]238        // first to abort ?
239        if ( !first ) {
240                // We aren't the first to abort just let C handle it
241                signal( SIGABRT, SIG_DFL );     // restore default in case we came here through the function.
242                __cabi_libc.abort();
243        }
[8a13c47]244
[92bfda0]245        int len = snprintf( abort_text, abort_text_size, "Cforall Runtime error (UNIX pid:%ld) ", (long int)getpid() ); // use UNIX pid (versus getPid)
246        __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
[8a13c47]247
[92bfda0]248        // print the cause of the error
249        assert( fmt );
250        len = vsnprintf( abort_text, abort_text_size, fmt, args );
251        __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
[6011658]252
[92bfda0]253        // add optional newline if missing at the end of the format text
254        if ( fmt[strlen( fmt ) - 1] != '\n' ) {
255                __cfaabi_bits_write( STDERR_FILENO, "\n", 1 );
256        } // if
[6011658]257
[92bfda0]258        // Give the kernel the chance to add some data in here
259        __kernel_abort_msg( abort_text, abort_text_size );
[6011658]260
[92bfda0]261        // print stack trace in handler
262        __cfaabi_backtrace( signalAbort ? 4 : 2 );
[6011658]263
[92bfda0]264        // Finally call abort
265        __cabi_libc.abort();
[5ccee64]266
[8a13c47]267}
268
269void abort( const char fmt[], ... ) {
270        va_list args;
271        va_start( args, fmt );
[d870df3]272        __abort( false, fmt, args );
[f883ef1]273        // CONTROL NEVER REACHES HERE!
[8a13c47]274        va_end( args );
275}
276
[d870df3]277void abort( bool signalAbort, const char fmt[], ... ) {
[f883ef1]278        va_list args;
279        va_start( args, fmt );
280        __abort( signalAbort, fmt, args );
281        // CONTROL NEVER REACHES HERE!
282        va_end( args );
[d870df3]283}
284
[dbe9b08]285void sigHandler_segv( __CFA_SIGPARMS__ ) {
[8a13c47]286                if ( sfp->si_addr == 0p ) {
287                        abort( true, "Null pointer (0p) dereference.\n" );
[1469a8a]288                } else {
[8a13c47]289                        abort( true, "%s at memory location %p.\n"
[1469a8a]290                                   "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",
291                                   (sig == SIGSEGV ? "Segment fault" : "Bus error"), sfp->si_addr );
292                }
[2b8bc41]293}
294
295void sigHandler_ill( __CFA_SIGPARMS__ ) {
[8a13c47]296        abort( true, "Executing illegal instruction at location %p.\n"
[2b8bc41]297                        "Possible cause is stack corruption.\n",
298                        sfp->si_addr );
299}
300
301void sigHandler_fpe( __CFA_SIGPARMS__ ) {
302        const char * msg;
303
[a424315d]304        choose( sfp->si_code ) {
305          case FPE_INTDIV, FPE_FLTDIV: msg = "divide by zero";
306          case FPE_FLTOVF: msg = "overflow";
307          case FPE_FLTUND: msg = "underflow";
308          case FPE_FLTRES: msg = "inexact result";
309          case FPE_FLTINV: msg = "invalid operation";
[2b8bc41]310          default: msg = "unknown";
[a424315d]311        } // choose
[8a13c47]312        abort( true, "Computation error %s at location %p.\n", msg, sfp->si_addr );
[dbe9b08]313}
314
[94dea96]315void sigHandler_term( __CFA_SIGPARMS__ ) {
[8a13c47]316        abort( true, "Application interrupted by signal: %s.\n", strsignal( sig ) );
[94dea96]317}
318
[6b0b624]319// Local Variables: //
320// mode: c //
321// tab-width: 4 //
322// End: //
Note: See TracBrowser for help on using the repository browser.