source: src/libcfa/exception.c @ e195093

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since e195093 was ff7ff14a, checked in by Andrew Beach <ajbeach@…>, 7 years ago

Discovered a case where the memory management didn't work, stricter tracking of the current exception fixes the issue.

  • Property mode set to 100644
File size: 16.5 KB
RevLine 
[fa4805f]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// exception.c --
8//
9// Author           : Andrew Beach
10// Created On       : Mon Jun 26 15:13:00 2017
[86d5ba7c]11// Last Modified By : Andrew Beach
[ff7ff14a]12// Last Modified On : Mon Jul 31 13:51:00 2017
13// Update Count     : 4
[fa4805f]14//
15
16#include "exception.h"
17
18// Implementation of the secret header.
19
20#include <stdlib.h>
21#include <stdio.h>
22#include <unwind.h>
23
[b947fb2]24// FIX ME: temporary hack to keep ARM build working
25#ifndef _URC_FATAL_PHASE1_ERROR
26#define _URC_FATAL_PHASE1_ERROR 2
27#endif // ! _URC_FATAL_PHASE1_ERROR
28#ifndef _URC_FATAL_PHASE2_ERROR
29#define _URC_FATAL_PHASE2_ERROR 2
30#endif // ! _URC_FATAL_PHASE2_ERROR
31
[fa4805f]32#include "lsda.h"
33
34// Temperary global exception context. Does not work with concurency.
[86d5ba7c]35struct exception_context_t {
[fa4805f]36    struct __cfaehm__try_resume_node * top_resume;
37    struct __cfaehm__try_resume_node * current_resume;
38
[86d5ba7c]39    exception * current_exception;
[fa4805f]40    int current_handler_index;
41
[86d5ba7c]42        // Storage to avoid using the heap for exceptions.
43        exception built_in_storage;
44} shared_stack = {NULL, NULL, 0, 0, 0};
45
46// Get the current exception context.
47// There can be a single global until multithreading occurs, then each stack
48// needs its own. It will have to be updated to handle that.
49struct exception_context_t * this_exception_context() {
50        return &shared_stack;
51}
52//#define SAVE_EXCEPTION_CONTEXT(to_name)
53//struct exception_context_t * to_name = this_exception_context();
54//exception * this_exception() {
55//    return this_exception_context()->current_exception;
56//}
[fa4805f]57
58
[b947fb2]59// This macro should be the only thing that needs to change across machines.  Used in the personality function, way down
60// in termination.
[ad0be81]61// struct _Unwind_Context * -> _Unwind_Reason_Code(*)(exception *)
[fa4805f]62#define MATCHER_FROM_CONTEXT(ptr_to_context) \
[ad0be81]63        (*(_Unwind_Reason_Code(**)(exception*))(_Unwind_GetCFA(ptr_to_context) + 8))
[fa4805f]64
65
66// RESUMPTION ================================================================
67
[38ac6ec]68void __cfaehm__throw_resume(exception * except) {
[fa4805f]69
70        // DEBUG
[307a732]71        printf("Throwing resumption exception %d\n", *except);
[fa4805f]72
[307a732]73        struct __cfaehm__try_resume_node * original_head = shared_stack.current_resume;
74        struct __cfaehm__try_resume_node * current =
[fa4805f]75                (original_head) ? original_head->next : shared_stack.top_resume;
76
77        for ( ; current ; current = current->next) {
78                shared_stack.current_resume = current;
[307a732]79                if (current->handler(except)) {
[fa4805f]80                        shared_stack.current_resume = original_head;
81                        return;
82                }
83        }
84
[307a732]85        printf("Unhandled exception %d\n", *except);
[fa4805f]86        shared_stack.current_resume = original_head;
87
88        // Fall back to termination:
[38ac6ec]89        __cfaehm__throw_terminate(except);
[fa4805f]90        // TODO: Default handler for resumption.
91}
92
[b947fb2]93// Do we control where exceptions get thrown even with concurency?  If not these are not quite thread safe, the cleanup
94// hook has to be added after the node is built but before it is made the top node.
95
[307a732]96void __cfaehm__try_resume_setup(struct __cfaehm__try_resume_node * node,
97                        int (*handler)(exception * except)) {
[fa4805f]98        node->next = shared_stack.top_resume;
[307a732]99        node->handler = handler;
[fa4805f]100        shared_stack.top_resume = node;
101}
102
[307a732]103void __cfaehm__try_resume_cleanup(struct __cfaehm__try_resume_node * node) {
[fa4805f]104        shared_stack.top_resume = node->next;
105}
106
107
108// TERMINATION ===============================================================
109
[86d5ba7c]110// MEMORY MANAGEMENT (still for integers)
[ff7ff14a]111// May have to move to cfa for constructors and destructors (references).
112
113struct __cfaehm__node {
114        struct __cfaehm__node * next;
115};
116
117#define NODE_TO_EXCEPT(node) ((exception *)(1 + (node)))
118#define EXCEPT_TO_NODE(except) ((struct __cfaehm__node *)(except) - 1)
[86d5ba7c]119
120// Creates a copy of the indicated exception and sets current_exception to it.
121static void __cfaehm__allocate_exception( exception * except ) {
122        struct exception_context_t * context = this_exception_context();
123
[ff7ff14a]124        // Allocate memory for the exception.
125        struct __cfaehm__node * store = malloc(
126                sizeof( except ) + sizeof( struct __cfaehm__node ) );
127
128        if ( ! store ) {
129                // Failure: cannot allocate exception. Terminate thread.
130                abort(); // <- Although I think it might be the process.
[86d5ba7c]131        }
132
[ff7ff14a]133        // Add the node to the list:
134        store->next = EXCEPT_TO_NODE(context->current_exception);
135        context->current_exception = NODE_TO_EXCEPT(store);
136
[86d5ba7c]137        // Copy the exception to storage.
138        *context->current_exception = *except;
139}
140
141// Delete the provided exception, unsetting current_exception if relivant.
142static void __cfaehm__delete_exception( exception * except ) {
143        struct exception_context_t * context = this_exception_context();
144
145        // DEBUG
[ff7ff14a]146        printf( "Deleting Exception %d\n", *except);
147
148        // Remove the exception from the list.
149        struct __cfaehm__node * to_free = EXCEPT_TO_NODE(except);
150        struct __cfaehm__node * node;
[86d5ba7c]151
152        if ( context->current_exception == except ) {
[ff7ff14a]153                node = to_free->next;
154                context->current_exception = (node) ? NODE_TO_EXCEPT(node) : 0;
[86d5ba7c]155        } else {
[ff7ff14a]156                node = EXCEPT_TO_NODE(context->current_exception);
157                // It may always be in the first or second position.
158                while( to_free != node->next ) {
159                        node = node->next;
160                }
161                node->next = to_free->next;
[86d5ba7c]162        }
[ff7ff14a]163
164        // Free the old exception node.
165        free( to_free );
[86d5ba7c]166}
167
168// If this isn't a rethrow (*except==0), delete the provided exception.
169void __cfaehm__cleanup_terminate( exception ** except ) {
170        if ( *except ) __cfaehm__delete_exception( *except );
171}
[fa4805f]172
173
174// We need a piece of storage to raise the exception
175struct _Unwind_Exception this_exception_storage;
176
177// Function needed by force unwind
178// It basically says to unwind the whole stack and then exit when we reach the end of the stack
179static _Unwind_Reason_Code _Stop_Fn(
180                int version,
181                _Unwind_Action actions,
182                _Unwind_Exception_Class exceptionClass,
183                struct _Unwind_Exception * unwind_exception,
184                struct _Unwind_Context * context,
185                void * some_param) {
186        if( actions & _UA_END_OF_STACK  ) exit(1);
187        if( actions & _UA_CLEANUP_PHASE ) return _URC_NO_REASON;
188
189        return _URC_FATAL_PHASE2_ERROR;
190}
191
[86d5ba7c]192// The exception that is being thrown must already be stored.
193__attribute__((noreturn)) void __cfaehm__begin_unwind(void) {
194        if ( ! this_exception_context()->current_exception ) {
195                printf("UNWIND ERROR missing exception in begin unwind\n");
196                abort();
197        }
[fa4805f]198
199
200        // Call stdlibc to raise the exception
201        _Unwind_Reason_Code ret = _Unwind_RaiseException( &this_exception_storage );
202
[b947fb2]203        // If we reach here it means something happened.  For resumption to work we need to find a way to return back to
204        // here.  Most of them will probably boil down to setting a global flag and making the phase 1 either stop or
205        // fail.  Causing an error on purpose may help avoiding unnecessary work but it might have some weird side
206        // effects.  If we just pretend no handler was found that would work but may be expensive for no reason since we
207        // will always search the whole stack.
[fa4805f]208
209        if( ret == _URC_END_OF_STACK ) {
[b947fb2]210                // No proper handler was found.  This can be handled in several way.  C++ calls std::terminate Here we
211                // force unwind the stack, basically raising a cancellation.
[fa4805f]212                printf("Uncaught exception %p\n", &this_exception_storage);
213
214                ret = _Unwind_ForcedUnwind( &this_exception_storage, _Stop_Fn, (void*)0x22 );
215                printf("UNWIND ERROR %d after force unwind\n", ret);
216                abort();
217        }
218
[b947fb2]219        // We did not simply reach the end of the stack without finding a handler.  Something wen't wrong
[fa4805f]220        printf("UNWIND ERROR %d after raise exception\n", ret);
221        abort();
222}
223
[86d5ba7c]224void __cfaehm__throw_terminate( exception * val ) {
225        // DEBUG
226        printf("Throwing termination exception\n");
227
228        __cfaehm__allocate_exception( val );
229        __cfaehm__begin_unwind();
230}
231
[38ac6ec]232void __cfaehm__rethrow_terminate(void) {
[fa4805f]233        // DEBUG
234        printf("Rethrowing termination exception\n");
235
[86d5ba7c]236        __cfaehm__begin_unwind();
[fa4805f]237}
238
[b947fb2]239// This is our personality routine.  For every stack frame anotated with ".cfi_personality 0x3,__gcfa_personality_v0".
240// This function will be called twice when unwinding.  Once in the search phased and once in the cleanup phase.
[fa4805f]241_Unwind_Reason_Code __gcfa_personality_v0 (
242                int version, _Unwind_Action actions, unsigned long long exceptionClass,
243                struct _Unwind_Exception* unwind_exception,
244                struct _Unwind_Context* context)
245{
246
247        // DEBUG
248        //printf("CFA: 0x%lx\n", _Unwind_GetCFA(context));
249        printf("Personality function (%d, %x, %llu, %p, %p):", version, actions, exceptionClass, unwind_exception, context);
250
251        // If we've reached the end of the stack then there is nothing much we can do...
252        if( actions & _UA_END_OF_STACK ) return _URC_END_OF_STACK;
253
254        // DEBUG
255        if (actions & _UA_SEARCH_PHASE) {
256                printf(" lookup phase");
257        }
258        // DEBUG
259        else if (actions & _UA_CLEANUP_PHASE) {
260                printf(" cleanup phase");
261        }
262        // Just in case, probably can't actually happen
263        else {
264                printf(" error\n");
265                return _URC_FATAL_PHASE1_ERROR;
266        }
267
268        // Get a pointer to the language specific data from which we will read what we need
269        const unsigned char * lsd = (const unsigned char*) _Unwind_GetLanguageSpecificData( context );
270
271        if( !lsd ) {    //Nothing to do, keep unwinding
272                printf(" no LSD");
273                goto UNWIND;
274        }
275
276        // Get the instuction pointer and a reading pointer into the exception table
277        lsda_header_info lsd_info;
278        const unsigned char * cur_ptr = parse_lsda_header( context, lsd, &lsd_info);
279        _Unwind_Ptr instruction_ptr = _Unwind_GetIP( context );
280
281        // Linearly search the table for stuff to do
282        while( cur_ptr < lsd_info.action_table ) {
283                _Unwind_Ptr callsite_start;
284                _Unwind_Ptr callsite_len;
285                _Unwind_Ptr callsite_landing_pad;
286                _uleb128_t  callsite_action;
287
288                // Decode the common stuff we have in here
289                cur_ptr = read_encoded_value (0, lsd_info.call_site_encoding, cur_ptr, &callsite_start);
290                cur_ptr = read_encoded_value (0, lsd_info.call_site_encoding, cur_ptr, &callsite_len);
291                cur_ptr = read_encoded_value (0, lsd_info.call_site_encoding, cur_ptr, &callsite_landing_pad);
292                cur_ptr = read_uleb128 (cur_ptr, &callsite_action);
293
294                // Have we reach the correct frame info yet?
295                if( lsd_info.Start + callsite_start + callsite_len < instruction_ptr ) {
296                        //DEBUG BEGIN
297                        void * ls = (void*)lsd_info.Start;
298                        void * cs = (void*)callsite_start;
299                        void * cl = (void*)callsite_len;
300                        void * bp = (void*)lsd_info.Start + callsite_start;
301                        void * ep = (void*)lsd_info.Start + callsite_start + callsite_len;
302                        void * ip = (void*)instruction_ptr;
303                        printf("\nfound %p - %p (%p, %p, %p), looking for %p\n", bp, ep, ls, cs, cl, ip);
304                        //DEBUG END
305                        continue;
306                }
307
308                // Have we gone too far
309                if( lsd_info.Start + callsite_start > instruction_ptr ) {
310                        printf(" gone too far");
311                        break;
312                }
313
314                // Something to do?
315                if( callsite_landing_pad ) {
316                        // Which phase are we in
317                        if (actions & _UA_SEARCH_PHASE) {
318                                // Search phase, this means we probably found a potential handler and must check if it is a match
319
320                                // If we have arbitrarily decided that 0 means nothing to do and 1 means there is a potential handler
321                                // This doesn't seem to conflict the gcc default behavior
322                                if (callsite_action != 0) {
323                                        // Now we want to run some code to see if the handler matches
324                                        // This is the tricky part where we want to the power to run arbitrary code
325                                        // However, generating a new exception table entry and try routine every time
326                                        // is way more expansive than we might like
327                                        // The information we have is :
328                                        //  - The GR (Series of registers)
329                                        //    GR1=GP Global Pointer of frame ref by context
330                                        //  - The instruction pointer
331                                        //  - The instruction pointer info (???)
332                                        //  - The CFA (Canonical Frame Address)
333                                        //  - The BSP (Probably the base stack pointer)
334
335
336                                        // The current apprach uses one exception table entry per try block
337                                        _uleb128_t imatcher;
338                                        // Get the relative offset to the
339                                        cur_ptr = read_uleb128 (cur_ptr, &imatcher);
340
341                                        // Get a function pointer from the relative offset and call it
342                                        // _Unwind_Reason_Code (*matcher)() = (_Unwind_Reason_Code (*)())lsd_info.LPStart + imatcher;                                   
343
[ad0be81]344                                        _Unwind_Reason_Code (*matcher)(exception *) =
[fa4805f]345                                                MATCHER_FROM_CONTEXT(context);
[86d5ba7c]346                                        int index = matcher(shared_stack.current_exception);
[fa4805f]347                                        _Unwind_Reason_Code ret = (0 == index)
348                                                ? _URC_CONTINUE_UNWIND : _URC_HANDLER_FOUND;
349                                        shared_stack.current_handler_index = index;
350
351                                        // Based on the return value, check if we matched the exception
352                                        if( ret == _URC_HANDLER_FOUND) printf(" handler found\n");
353                                        else printf(" no handler\n");
354                                        return ret;
355                                }
356
357                                // This is only a cleanup handler, ignore it
358                                printf(" no action");
359                        }
360                        else if (actions & _UA_CLEANUP_PHASE) {
361
362                                if( (callsite_action != 0) && !(actions & _UA_HANDLER_FRAME) ){
363                                        // If this is a potential exception handler
364                                        // but not the one that matched the exception in the seach phase,
365                                        // just ignore it
366                                        goto UNWIND;
367                                }
368
369                                // We need to run some clean-up or a handler
370                                // These statment do the right thing but I don't know any specifics at all
371                                _Unwind_SetGR( context, __builtin_eh_return_data_regno(0), (_Unwind_Ptr) unwind_exception );
372                                _Unwind_SetGR( context, __builtin_eh_return_data_regno(1), 0 );
373
374                                // I assume this sets the instruction pointer to the adress of the landing pad
375                                // It doesn't actually set it, it only state the value that needs to be set once we return _URC_INSTALL_CONTEXT
[b947fb2]376                                _Unwind_SetIP( context, ((lsd_info.LPStart) + (callsite_landing_pad)) );
[fa4805f]377
378                                // DEBUG
379                                printf(" action\n");
380
381                                // Return have some action to run
382                                return _URC_INSTALL_CONTEXT;
383                        }
384                }
385
386                // Nothing to do, move along
387                printf(" no landing pad");
388        }
389        // No handling found
390        printf(" table end reached\n");
391
392        // DEBUG
393        UNWIND:
394        printf(" unwind\n");
395
396        // Keep unwinding the stack
397        return _URC_CONTINUE_UNWIND;
398}
399
[b947fb2]400// Try statements are hoisted out see comments for details.  With this could probably be unique and simply linked from
401// libcfa but there is one problem left, see the exception table for details
[fa4805f]402__attribute__((noinline))
[307a732]403void __cfaehm__try_terminate(void (*try_block)(),
404                void (*catch_block)(int index, exception * except),
405                __attribute__((unused)) int (*match_block)(exception * except)) {
[fa4805f]406        //! volatile int xy = 0;
407        //! printf("%p %p %p %p\n", &try_block, &catch_block, &match_block, &xy);
408
[b947fb2]409        // Setup statments: These 2 statments won't actually result in any code, they only setup global tables.
410        // However, they clobber gcc cancellation support from gcc.  We can replace the personality routine but
411        // replacing the exception table gcc generates is not really doable, it generates labels based on how the
412        // assembly works.
413
[fa4805f]414        // Setup the personality routine
415        asm volatile (".cfi_personality 0x3,__gcfa_personality_v0");
416        // Setup the exception table
417        asm volatile (".cfi_lsda 0x3, .LLSDACFA2");
418
[b947fb2]419        // Label which defines the start of the area for which the handler is setup.
[fa4805f]420        asm volatile (".TRYSTART:");
421
422        // The actual statements of the try blocks
423        try_block();
424
425        // asm statement to prevent deadcode removal
426        asm volatile goto ("" : : : : CATCH );
427
428        // Normal return
429        return;
430
431        // Exceptionnal path
432        CATCH : __attribute__(( unused ));
[b947fb2]433        // Label which defines the end of the area for which the handler is setup.
[fa4805f]434        asm volatile (".TRYEND:");
[b947fb2]435        // Label which defines the start of the exception landing pad.  Basically what is called when the exception is
436        // caught.  Note, if multiple handlers are given, the multiplexing should be done by the generated code, not the
437        // exception runtime.
[fa4805f]438        asm volatile (".CATCH:");
439
440        // Exception handler
[b947fb2]441        catch_block( shared_stack.current_handler_index,
[86d5ba7c]442                     shared_stack.current_exception );
[fa4805f]443}
444
[b947fb2]445// Exception table data we need to generate.  While this is almost generic, the custom data refers to foo_try_match try
446// match, which is no way generic.  Some more works need to be done if we want to have a single call to the try routine.
447
448#if defined( __x86_64__ ) || defined( __i386__ )
[fa4805f]449asm (
450        //HEADER
451        ".LFECFA1:\n"
452        "       .globl  __gcfa_personality_v0\n"
453        "       .section        .gcc_except_table,\"a\",@progbits\n"
454        ".LLSDACFA2:\n"                                                 //TABLE header
455        "       .byte   0xff\n"
456        "       .byte   0xff\n"
457        "       .byte   0x1\n"
458        "       .uleb128 .LLSDACSECFA2-.LLSDACSBCFA2\n"         // BODY length
459        // Body uses language specific data and therefore could be modified arbitrarily
460        ".LLSDACSBCFA2:\n"                                              // BODY start
[307a732]461        "       .uleb128 .TRYSTART-__cfaehm__try_terminate\n"           // Handled area start  (relative to start of function)
[fa4805f]462        "       .uleb128 .TRYEND-.TRYSTART\n"                           // Handled area length
[307a732]463        "       .uleb128 .CATCH-__cfaehm__try_terminate\n"                              // Hanlder landing pad adress  (relative to start of function)
[fa4805f]464        "       .uleb128 1\n"                                           // Action code, gcc seems to use always 0
465        ".LLSDACSECFA2:\n"                                              // BODY end
466        "       .text\n"                                                        // TABLE footer
[307a732]467        "       .size   __cfaehm__try_terminate, .-__cfaehm__try_terminate\n"
[fa4805f]468        "       .ident  \"GCC: (Ubuntu 6.2.0-3ubuntu11~16.04) 6.2.0 20160901\"\n"
469//      "       .section        .note.GNU-stack,\"x\",@progbits\n"
470);
[b947fb2]471#endif // __x86_64__ || __i386__
Note: See TracBrowser for help on using the repository browser.