source: libcfa/src/interpose.cfa@ 692c1cc

ADT ast-experimental
Last change on this file since 692c1cc was fbdfcd8, checked in by Peter A. Buhr <pabuhr@…>, 3 years ago

isolate error variable declaration

  • Property mode set to 100644
File size: 12.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 : Mon Jan 9 08:44:03 2023
13// Update Count : 182
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#include <signal.h>
21extern "C" {
22#include <dlfcn.h> // dlopen, dlsym
23#include <execinfo.h> // backtrace, messages
24}
25
26#include "bits/debug.hfa"
27#include "bits/defs.hfa"
28#include "bits/signal.hfa" // sigHandler_?
29#include "startup.hfa" // STARTUP_PRIORITY_CORE
30#include <assert.h>
31
32//=============================================================================================
33// Interposing helpers
34//=============================================================================================
35
36static void preload_libgcc(void) {
37 dlopen( "libgcc_s.so.1", RTLD_NOW );
38 if ( const char * error = dlerror() ) abort( "interpose_symbol : internal error pre-loading libgcc, %s\n", error );
39}
40
41typedef void (* generic_fptr_t)(void);
42static generic_fptr_t do_interpose_symbol( void * library, const char symbol[], const char version[] ) {
43 const char * error;
44
45 union { generic_fptr_t fptr; void * ptr; } originalFunc;
46
47 #if defined( _GNU_SOURCE )
48 if ( version ) {
49 originalFunc.ptr = dlvsym( library, symbol, version );
50 } else {
51 originalFunc.ptr = dlsym( library, symbol );
52 }
53 #else
54 originalFunc.ptr = dlsym( library, symbol );
55 #endif // _GNU_SOURCE
56
57 error = dlerror();
58 if ( error ) abort( "interpose_symbol : internal error, %s\n", error );
59
60 return originalFunc.fptr;
61}
62
63static generic_fptr_t interpose_symbol( const char symbol[], const char version[] ) {
64 static void * library;
65 static void * pthread_library;
66
67 if ( ! library ) {
68 #if defined( RTLD_NEXT )
69 library = RTLD_NEXT;
70 #else
71 // missing RTLD_NEXT => must hard-code library name, assuming libstdc++
72 library = dlopen( "libc.so.6", RTLD_LAZY );
73 const char * error = dlerror();
74 if ( error ) {
75 abort( "interpose_symbol : failed to open libc, %s\n", error );
76 }
77 #endif
78 } // if
79 if ( ! pthread_library ) {
80 #if defined( RTLD_NEXT )
81 pthread_library = RTLD_NEXT;
82 #else
83 // missing RTLD_NEXT => must hard-code library name, assuming libstdc++
84 pthread_library = dlopen( "libpthread.so", RTLD_LAZY );
85 const char * error = dlerror();
86 if ( error ) {
87 abort( "interpose_symbol : failed to open libpthread, %s\n", error );
88 }
89 #endif
90 } // if
91
92 return do_interpose_symbol(library, symbol, version);
93}
94
95#define INTERPOSE_LIBC( x, ver ) __cabi_libc.x = (typeof(__cabi_libc.x))interpose_symbol( #x, ver )
96
97//=============================================================================================
98// Interposition Startup logic
99//=============================================================================================
100
101static void sigHandler_segv( __CFA_SIGPARMS__ );
102static void sigHandler_ill ( __CFA_SIGPARMS__ );
103static void sigHandler_fpe ( __CFA_SIGPARMS__ );
104static void sigHandler_abrt( __CFA_SIGPARMS__ );
105static void sigHandler_term( __CFA_SIGPARMS__ );
106
107static struct {
108 void (* exit)( int ) __attribute__(( __noreturn__ ));
109 void (* abort)( void ) __attribute__(( __noreturn__ ));
110} __cabi_libc;
111
112libcfa_public int cfa_main_returned;
113
114extern "C" {
115 void __cfathreadabi_interpose_startup( generic_fptr_t (*do_interpose_symbol)( void * library, const char symbol[], const char version[] ) ) __attribute__((weak));
116 void __cfaabi_interpose_startup( void ) {
117 const char *version = 0p;
118 cfa_main_returned = 0;
119
120 preload_libgcc();
121
122#pragma GCC diagnostic push
123#pragma GCC diagnostic ignored "-Wdiscarded-qualifiers"
124 INTERPOSE_LIBC( abort, version );
125 INTERPOSE_LIBC( exit , version );
126#pragma GCC diagnostic pop
127
128 if(__cfathreadabi_interpose_startup) __cfathreadabi_interpose_startup( do_interpose_symbol );
129
130 // As a precaution (and necessity), errors that result in termination are delivered on a separate stack because
131 // task stacks might be very small (4K) and the signal delivery corrupts memory to the point that a clean
132 // shutdown is impossible. Also, when a stack overflow encounters the non-accessible sentinel page (debug only)
133 // and generates a segment fault, the signal cannot be delivered on the sentinel page. Finally, calls to abort
134 // print a stack trace that uses substantial stack space.
135
136 #define MINSTKSZ SIGSTKSZ * 8
137 static char stack[MINSTKSZ] __attribute__(( aligned (16) ));
138 static stack_t ss;
139
140 ss.ss_sp = stack;
141 ss.ss_size = MINSTKSZ;
142 ss.ss_flags = 0;
143 if ( sigaltstack( &ss, 0p ) == -1 ) {
144 abort( "__cfaabi_interpose_startup : internal error, sigaltstack error(%d) %s.", errno, strerror( errno ) );
145 } // if
146
147 // Failure handler
148 // internal errors
149 __cfaabi_sigaction( SIGSEGV, sigHandler_segv, SA_SIGINFO | SA_ONSTACK ); // Invalid memory reference (default: Core)
150 __cfaabi_sigaction( SIGBUS , sigHandler_segv, SA_SIGINFO | SA_ONSTACK ); // Bus error, bad memory access (default: Core)
151 __cfaabi_sigaction( SIGILL , sigHandler_ill , SA_SIGINFO | SA_ONSTACK ); // Illegal Instruction (default: Core)
152 __cfaabi_sigaction( SIGFPE , sigHandler_fpe , SA_SIGINFO | SA_ONSTACK ); // Floating-point exception (default: Core)
153
154 // handlers to outside errors
155 // reset in-case they insist and send it over and over
156 __cfaabi_sigaction( SIGTERM, sigHandler_term, SA_SIGINFO | SA_ONSTACK | SA_RESETHAND ); // Termination signal (default: Term)
157 __cfaabi_sigaction( SIGINT , sigHandler_term, SA_SIGINFO | SA_ONSTACK | SA_RESETHAND ); // Interrupt from keyboard (default: Term)
158 __cfaabi_sigaction( SIGHUP , sigHandler_term, SA_SIGINFO | SA_ONSTACK | SA_RESETHAND ); // Hangup detected on controlling terminal or death of controlling process (default: Term)
159 __cfaabi_sigaction( SIGQUIT, sigHandler_term, SA_SIGINFO | SA_ONSTACK | SA_RESETHAND ); // Quit from keyboard (default: Core)
160 __cfaabi_sigaction( SIGABRT, sigHandler_term, SA_SIGINFO | SA_ONSTACK | SA_RESETHAND ); // Abort signal from abort(3) (default: Core)
161 }
162}
163
164//=============================================================================================
165// Terminating Signals logic
166//=============================================================================================
167
168// Forward declare abort after the __typeof__ call to avoid ambiguities
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__ ));
173
174extern "C" {
175 libcfa_public void abort( void ) __attribute__(( __nothrow__, __leaf__, __noreturn__ )) {
176 abort( false, "%s", "" );
177 }
178
179 libcfa_public void __cabi_abort( const char fmt[], ... ) __attribute__(( format(printf, 1, 2), __nothrow__, __leaf__, __noreturn__ )) {
180 va_list argp;
181 va_start( argp, fmt );
182 __abort( false, fmt, argp );
183 va_end( argp );
184 }
185
186 libcfa_public void exit( int status ) __attribute__(( __nothrow__, __leaf__, __noreturn__ )) {
187 __cabi_libc.exit( status );
188 }
189}
190
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; }
195
196enum { abort_text_size = 1024 };
197static char abort_text[ abort_text_size ];
198
199static void __cfaabi_backtrace( int start ) {
200 enum { Frames = 50, }; // maximum number of stack frames
201 int last = __kernel_abort_lastframe(); // skip last N stack frames
202
203 void * array[Frames];
204 size_t size = backtrace( array, Frames );
205 char ** messages = backtrace_symbols( array, size ); // does not demangle names
206
207 *index( messages[0], '(' ) = '\0'; // find executable name
208 __cfaabi_bits_print_nolock( STDERR_FILENO, "Stack back trace for: %s\n", messages[0]);
209
210 for ( unsigned int i = start; i < size - last && messages != 0p; i += 1 ) {
211 char * name = 0p, * offset_begin = 0p, * offset_end = 0p;
212
213 for ( char * p = messages[i]; *p; p += 1 ) { // find parantheses and +offset
214 //__cfaabi_bits_print_nolock( "X %s\n", p);
215 if ( *p == '(' ) {
216 name = p;
217 } else if ( *p == '+' ) {
218 offset_begin = p;
219 } else if ( *p == ')' ) {
220 offset_end = p;
221 break;
222 }
223 }
224
225 // if line contains symbol, print it
226 int frameNo = i - start;
227 if ( name && offset_begin && offset_end && name < offset_begin ) {
228 *name++ = '\0'; // delimit strings
229 *offset_begin++ = '\0';
230 *offset_end++ = '\0';
231
232 __cfaabi_bits_print_nolock( STDERR_FILENO, "(%i) %s : %s + %s %s\n", frameNo, messages[i], name, offset_begin, offset_end);
233 } else { // otherwise, print the whole line
234 __cfaabi_bits_print_nolock( STDERR_FILENO, "(%i) %s\n", frameNo, messages[i] );
235 }
236 }
237 free( messages );
238}
239
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
248static volatile bool __abort_first = 0;
249
250// Cannot forward va_list.
251void __abort( bool signalAbort, const char fmt[], va_list args ) {
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);
255
256 // Prevent preemption from kicking-in and messing with the abort
257 __kernel_abort_lock();
258
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 }
265
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 );
268
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 );
273
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
278
279 // Give the kernel the chance to add some data in here
280 __kernel_abort_msg( abort_text, abort_text_size );
281
282 // print stack trace in handler
283 __cfaabi_backtrace( signalAbort ? 4 : 2 );
284
285 // Finally call abort
286 __cabi_libc.abort();
287
288}
289
290void abort( const char fmt[], ... ) {
291 va_list args;
292 va_start( args, fmt );
293 __abort( false, fmt, args );
294 // CONTROL NEVER REACHES HERE!
295 va_end( args );
296}
297
298void abort( bool signalAbort, const char fmt[], ... ) {
299 va_list args;
300 va_start( args, fmt );
301 __abort( signalAbort, fmt, args );
302 // CONTROL NEVER REACHES HERE!
303 va_end( args );
304}
305
306void sigHandler_segv( __CFA_SIGPARMS__ ) {
307 if ( sfp->si_addr == 0p ) {
308 abort( true, "Null pointer (0p) dereference.\n" );
309 } else {
310 abort( true, "%s at memory location %p.\n"
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 }
314}
315
316void sigHandler_ill( __CFA_SIGPARMS__ ) {
317 abort( true, "Executing illegal instruction at location %p.\n"
318 "Possible cause is stack corruption.\n",
319 sfp->si_addr );
320}
321
322void sigHandler_fpe( __CFA_SIGPARMS__ ) {
323 const char * msg;
324
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";
331 default: msg = "unknown";
332 } // choose
333 abort( true, "Computation error %s at location %p.\n", msg, sfp->si_addr );
334}
335
336void sigHandler_term( __CFA_SIGPARMS__ ) {
337 abort( true, "Application interrupted by signal: %s.\n", strsignal( sig ) );
338}
339
340// Local Variables: //
341// mode: c //
342// tab-width: 4 //
343// End: //
Note: See TracBrowser for help on using the repository browser.