source: libcfa/src/exception.c @ 2a3b019

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 2a3b019 was 2a3b019, checked in by Andrew Beach <ajbeach@…>, 4 years ago

Cleaning exception code: no direct access to shared_stack anymore, small reorganization that fixes debug print.

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