source: libcfa/src/interpose.cfa@ feb999f

Last change on this file since feb999f was 45d1ab9, checked in by Peter A. Buhr <pabuhr@…>, 20 months ago

revert interpose experiment for build failure, not the cause

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