source: libcfa/src/exception.c @ 0f3d844

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

Fixed the disabled exceptions/resume test. Added more tests in exceptions/interact, one of which is disabled.

  • Property mode set to 100644
File size: 18.4 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 : Andrew Beach
12// Last Modified On : Thr Apr 02 14:47:00 2020
13// Update Count     : 13
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 __cfaehm_base_exception_t_vtable
44                ___cfaehm_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 __cfaehm_try_resume_node * top_resume;
56
57        exception_t * current_exception;
58        int current_handler_index;
59} static shared_stack = {NULL, NULL, 0};
60
61// Get the current exception context.
62// There can be a single global until multithreading occurs, then each stack
63// needs its own. It will have to be updated to handle that.
64struct exception_context_t * this_exception_context() {
65        return &shared_stack;
66}
67
68
69// RESUMPTION ================================================================
70
71void __cfaehm_throw_resume(exception_t * except) {
72        struct exception_context_t * context = this_exception_context();
73
74        __cfaabi_dbg_print_safe("Throwing resumption exception\n");
75
76        struct __cfaehm_try_resume_node * original_head = context->top_resume;
77        struct __cfaehm_try_resume_node * current = context->top_resume;
78
79        for ( ; current ; current = current->next) {
80                context->top_resume = current->next;
81                if (current->handler(except)) {
82                        context->top_resume = original_head;
83                        return;
84                }
85        }
86
87        __cfaabi_dbg_print_safe("Unhandled exception\n");
88        context->top_resume = original_head;
89
90        // Fall back to termination:
91        __cfaehm_throw_terminate(except);
92        // TODO: Default handler for resumption.
93}
94
95// Do we control where exceptions get thrown even with concurency?
96// If not these are not quite thread safe, the cleanup hook has to
97// be added after the node is built but before it is made the top node.
98
99void __cfaehm_try_resume_setup(struct __cfaehm_try_resume_node * node,
100                        _Bool (*handler)(exception_t * except)) {
101        struct exception_context_t * context = this_exception_context();
102        node->next = context->top_resume;
103        node->handler = handler;
104        context->top_resume = node;
105}
106
107void __cfaehm_try_resume_cleanup(struct __cfaehm_try_resume_node * node) {
108        struct exception_context_t * context = this_exception_context();
109        context->top_resume = node->next;
110}
111
112
113// TERMINATION ===============================================================
114
115// MEMORY MANAGEMENT (still for integers)
116// May have to move to cfa for constructors and destructors (references).
117
118struct __cfaehm_node {
119        struct __cfaehm_node * next;
120};
121
122#define NODE_TO_EXCEPT(node) ((exception_t *)(1 + (node)))
123#define EXCEPT_TO_NODE(except) ((struct __cfaehm_node *)(except) - 1)
124
125// Creates a copy of the indicated exception and sets current_exception to it.
126static void __cfaehm_allocate_exception( exception_t * except ) {
127        struct exception_context_t * context = this_exception_context();
128
129        // Allocate memory for the exception.
130        struct __cfaehm_node * store = malloc(
131                sizeof( struct __cfaehm_node ) + except->virtual_table->size );
132
133        if ( ! store ) {
134                // Failure: cannot allocate exception. Terminate thread.
135                abort(); // <- Although I think it might be the process.
136        }
137
138        // Add the node to the list:
139        store->next = EXCEPT_TO_NODE(context->current_exception);
140        context->current_exception = NODE_TO_EXCEPT(store);
141
142        // Copy the exception to storage.
143        except->virtual_table->copy( context->current_exception, except );
144}
145
146// Delete the provided exception, unsetting current_exception if relivant.
147static void __cfaehm_delete_exception( exception_t * except ) {
148        struct exception_context_t * context = this_exception_context();
149
150        __cfaabi_dbg_print_safe("Deleting Exception\n");
151
152        // Remove the exception from the list.
153        struct __cfaehm_node * to_free = EXCEPT_TO_NODE(except);
154        struct __cfaehm_node * node;
155
156        if ( context->current_exception == except ) {
157                node = to_free->next;
158                context->current_exception = (node) ? NODE_TO_EXCEPT(node) : 0;
159        } else {
160                node = EXCEPT_TO_NODE(context->current_exception);
161                // It may always be in the first or second position.
162                while ( to_free != node->next ) {
163                        node = node->next;
164                }
165                node->next = to_free->next;
166        }
167
168        // Free the old exception node.
169        except->virtual_table->free( except );
170        free( to_free );
171}
172
173// If this isn't a rethrow (*except==0), delete the provided exception.
174void __cfaehm_cleanup_terminate( void * except ) {
175        if ( *(void**)except ) __cfaehm_delete_exception( *(exception_t **)except );
176}
177
178
179// We need a piece of storage to raise the exception
180struct _Unwind_Exception this_exception_storage;
181
182// Function needed by force unwind
183// It basically says to unwind the whole stack and then exit when we reach the end of the stack
184static _Unwind_Reason_Code _Stop_Fn(
185                int version,
186                _Unwind_Action actions,
187                _Unwind_Exception_Class exception_class,
188                struct _Unwind_Exception * unwind_exception,
189                struct _Unwind_Context * unwind_context,
190                void * stop_param) {
191        if ( actions & _UA_END_OF_STACK  ) exit(1);
192        if ( actions & _UA_CLEANUP_PHASE ) return _URC_NO_REASON;
193
194        return _URC_FATAL_PHASE2_ERROR;
195}
196
197// The exception that is being thrown must already be stored.
198static __attribute__((noreturn)) void __cfaehm_begin_unwind(void) {
199        if ( ! this_exception_context()->current_exception ) {
200                printf("UNWIND ERROR missing exception in begin unwind\n");
201                abort();
202        }
203
204
205        // Call stdlibc to raise the exception
206        _Unwind_Reason_Code ret = _Unwind_RaiseException( &this_exception_storage );
207
208        // If we reach here it means something happened. For resumption to work we need to find a way
209        // to return back to here. Most of them will probably boil down to setting a global flag and
210        // making the phase 1 either stop or fail. Causing an error on purpose may help avoiding
211        // unnecessary work but it might have some weird side effects. If we just pretend no handler
212        // was found that would work but may be expensive for no reason since we will always search
213        // the whole stack.
214
215        if ( ret == _URC_END_OF_STACK ) {
216                // No proper handler was found. This can be handled in many ways, C++ calls std::terminate.
217                // Here we force unwind the stack, basically raising a cancellation.
218                printf("Uncaught exception %p\n", &this_exception_storage);
219
220                ret = _Unwind_ForcedUnwind( &this_exception_storage, _Stop_Fn, (void*)0x22 );
221                printf("UNWIND ERROR %d after force unwind\n", ret);
222                abort();
223        }
224
225        // We did not simply reach the end of the stack without finding a handler. This is an error.
226        printf("UNWIND ERROR %d after raise exception\n", ret);
227        abort();
228}
229
230void __cfaehm_throw_terminate( exception_t * val ) {
231        __cfaabi_dbg_print_safe("Throwing termination exception\n");
232
233        __cfaehm_allocate_exception( val );
234        __cfaehm_begin_unwind();
235}
236
237void __cfaehm_rethrow_terminate(void) {
238        __cfaabi_dbg_print_safe("Rethrowing termination exception\n");
239
240        __cfaehm_begin_unwind();
241}
242
243// This is our personality routine. For every stack frame annotated with
244// ".cfi_personality 0x3,__gcfa_personality_v0" this function will be called twice when unwinding.
245//  Once in the search phase and once in the cleanup phase.
246_Unwind_Reason_Code __gcfa_personality_v0(
247                int version,
248                _Unwind_Action actions,
249                unsigned long long exception_class,
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, exception_class, 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 = _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                // Check for what we must do:
323                if ( 0 == callsite_landing_pad ) {
324                        // Nothing to do, move along
325                        __cfaabi_dbg_print_safe(" no landing pad");
326                } else if (actions & _UA_SEARCH_PHASE) {
327                        // In search phase, these means we found a potential handler we must check.
328
329                        // We have arbitrarily decided that 0 means nothing to do and 1 means there is
330                        // a potential handler. This doesn't seem to conflict the gcc default behavior.
331                        if (callsite_action != 0) {
332                                // Now we want to run some code to see if the handler matches
333                                // This is the tricky part where we want to the power to run arbitrary code
334                                // However, generating a new exception table entry and try routine every time
335                                // is way more expansive than we might like
336                                // The information we have is :
337                                //  - The GR (Series of registers)
338                                //    GR1=GP Global Pointer of frame ref by context
339                                //  - The instruction pointer
340                                //  - The instruction pointer info (???)
341                                //  - The CFA (Canonical Frame Address)
342                                //  - The BSP (Probably the base stack pointer)
343
344                                // The current apprach uses one exception table entry per try block
345                                _uleb128_t imatcher;
346                                // Get the relative offset to the {...}?
347                                cur_ptr = read_uleb128(cur_ptr, &imatcher);
348
349#                               if defined( __x86_64 )
350                                _Unwind_Word match_pos = _Unwind_GetCFA(unwind_context) + 8;
351#                               elif defined( __i386 )
352                                _Unwind_Word match_pos = _Unwind_GetCFA(unwind_context) + 24;
353#                               endif
354                                int (*matcher)(exception_t *) = *(int(**)(exception_t *))match_pos;
355
356                                int index = matcher(context->current_exception);
357                                _Unwind_Reason_Code ret = (0 == index)
358                                        ? _URC_CONTINUE_UNWIND : _URC_HANDLER_FOUND;
359                                context->current_handler_index = index;
360
361                                // Based on the return value, check if we matched the exception
362                                if (ret == _URC_HANDLER_FOUND) {
363                                        __cfaabi_dbg_print_safe(" handler found\n");
364                                } else {
365                                        __cfaabi_dbg_print_safe(" no handler\n");
366                                }
367                                return ret;
368                        }
369
370                        // This is only a cleanup handler, ignore it
371                        __cfaabi_dbg_print_safe(" no action");
372                } else if (actions & _UA_CLEANUP_PHASE) {
373                        // In clean-up phase, no destructors here but this could be the handler.
374
375                        if ( (callsite_action != 0) && !(actions & _UA_HANDLER_FRAME) ){
376                                // If this is a potential exception handler
377                                // but not the one that matched the exception in the seach phase,
378                                // just ignore it
379                                goto UNWIND;
380                        }
381
382                        // We need to run some clean-up or a handler
383                        // These statment do the right thing but I don't know any specifics at all
384                        _Unwind_SetGR( unwind_context, __builtin_eh_return_data_regno(0),
385                                (_Unwind_Ptr)unwind_exception );
386                        _Unwind_SetGR( unwind_context, __builtin_eh_return_data_regno(1), 0 );
387
388                        // I assume this sets the instruction pointer to the adress of the landing pad
389                        // It doesn't actually set it, it only state the value that needs to be set once we
390                        // return _URC_INSTALL_CONTEXT
391                        _Unwind_SetIP( unwind_context, ((lsd_info.LPStart) + (callsite_landing_pad)) );
392
393                        __cfaabi_dbg_print_safe(" action\n");
394
395                        // Return have some action to run
396                        return _URC_INSTALL_CONTEXT;
397                }
398        }
399        // No handling found
400        __cfaabi_dbg_print_safe(" table end reached\n");
401
402        UNWIND:
403        __cfaabi_dbg_print_safe(" unwind\n");
404
405        // Keep unwinding the stack
406        return _URC_CONTINUE_UNWIND;
407}
408
409#pragma GCC push_options
410#pragma GCC optimize("O0")
411
412// Try statements are hoisted out see comments for details. While this could probably be unique
413// and simply linked from libcfa but there is one problem left, see the exception table for details
414__attribute__((noinline))
415void __cfaehm_try_terminate(void (*try_block)(),
416                void (*catch_block)(int index, exception_t * except),
417                __attribute__((unused)) int (*match_block)(exception_t * except)) {
418        //! volatile int xy = 0;
419        //! printf("%p %p %p %p\n", &try_block, &catch_block, &match_block, &xy);
420
421        // Setup the personality routine and exception table.
422        // Unforturnately these clobber gcc cancellation support which means we can't get access to
423        // the attribute cleanup tables at the same time. We would have to inspect the assembly to
424        // create a new set ourselves.
425#ifdef __PIC__
426        asm volatile (".cfi_personality 0x9b,CFA.ref.__gcfa_personality_v0");
427        asm volatile (".cfi_lsda 0x1b, .LLSDACFA2");
428#else
429        asm volatile (".cfi_personality 0x3,__gcfa_personality_v0");
430        asm volatile (".cfi_lsda 0x3, .LLSDACFA2");
431#endif
432
433        // Label which defines the start of the area for which the handler is setup.
434        asm volatile (".TRYSTART:");
435
436        // The actual statements of the try blocks
437        try_block();
438
439        // asm statement to prevent deadcode removal
440        asm volatile goto ("" : : : : CATCH );
441
442        // Normal return for when there is no throw.
443        return;
444
445        // Exceptionnal path
446        CATCH : __attribute__(( unused ));
447        // Label which defines the end of the area for which the handler is setup.
448        asm volatile (".TRYEND:");
449        // Label which defines the start of the exception landing pad. Basically what is called when
450        // the exception is caught. Note, if multiple handlers are given, the multiplexing should be
451        // done by the generated code, not the exception runtime.
452        asm volatile (".CATCH:");
453
454        // Exception handler
455        // Note: Saving the exception context on the stack breaks termination exceptions.
456        catch_block( this_exception_context()->current_handler_index,
457                     this_exception_context()->current_exception );
458}
459
460// Exception table data we need to generate. While this is almost generic, the custom data refers
461// to {*}try_terminate, which is no way generic. Some more works need to be done if we want to
462// have a single call to the try routine.
463
464#ifdef __PIC__
465asm (
466        // HEADER
467        ".LFECFA1:\n"
468        "       .globl  __gcfa_personality_v0\n"
469        "       .section        .gcc_except_table,\"a\",@progbits\n"
470        // TABLE HEADER (important field is the BODY length at the end)
471        ".LLSDACFA2:\n"
472        "       .byte   0xff\n"
473        "       .byte   0xff\n"
474        "       .byte   0x1\n"
475        "       .uleb128 .LLSDACSECFA2-.LLSDACSBCFA2\n"
476        // BODY (language specific data)
477        // This uses language specific data and can be modified arbitrarily
478        // We use handled area offset, handled area length,
479        // handler landing pad offset and 1 (action code, gcc seems to use 0).
480        ".LLSDACSBCFA2:\n"
481        "       .uleb128 .TRYSTART-__cfaehm_try_terminate\n"
482        "       .uleb128 .TRYEND-.TRYSTART\n"
483        "       .uleb128 .CATCH-__cfaehm_try_terminate\n"
484        "       .uleb128 1\n"
485        ".LLSDACSECFA2:\n"
486        // TABLE FOOTER
487        "       .text\n"
488        "       .size   __cfaehm_try_terminate, .-__cfaehm_try_terminate\n"
489);
490
491// Somehow this piece of helps with the resolution of debug symbols.
492__attribute__((unused)) static const int dummy = 0;
493
494asm (
495        // Add a hidden symbol which points at the function.
496        "       .hidden CFA.ref.__gcfa_personality_v0\n"
497        "       .weak   CFA.ref.__gcfa_personality_v0\n"
498        // No clue what this does specifically
499        "       .section        .data.rel.local.CFA.ref.__gcfa_personality_v0,\"awG\",@progbits,CFA.ref.__gcfa_personality_v0,comdat\n"
500        "       .align 8\n"
501        "       .type CFA.ref.__gcfa_personality_v0, @object\n"
502        "       .size CFA.ref.__gcfa_personality_v0, 8\n"
503        "CFA.ref.__gcfa_personality_v0:\n"
504#if defined( __x86_64 )
505        "       .quad __gcfa_personality_v0\n"
506#else // then __i386
507        "   .long __gcfa_personality_v0\n"
508#endif
509);
510#else // __PIC__
511asm (
512        // HEADER
513        ".LFECFA1:\n"
514        "       .globl  __gcfa_personality_v0\n"
515        "       .section        .gcc_except_table,\"a\",@progbits\n"
516        // TABLE HEADER (important field is the BODY length at the end)
517        ".LLSDACFA2:\n"
518        "       .byte   0xff\n"
519        "       .byte   0xff\n"
520        "       .byte   0x1\n"
521        "       .uleb128 .LLSDACSECFA2-.LLSDACSBCFA2\n"
522        // BODY (language specific data)
523        ".LLSDACSBCFA2:\n"
524        //      Handled area start (relative to start of function)
525        "       .uleb128 .TRYSTART-__cfaehm_try_terminate\n"
526        //      Handled area length
527        "       .uleb128 .TRYEND-.TRYSTART\n"
528        //      Handler landing pad address (relative to start of function)
529        "       .uleb128 .CATCH-__cfaehm_try_terminate\n"
530        //      Action code, gcc seems to always use 0.
531        "       .uleb128 1\n"
532        // TABLE FOOTER
533        ".LLSDACSECFA2:\n"
534        "       .text\n"
535        "       .size   __cfaehm_try_terminate, .-__cfaehm_try_terminate\n"
536        "       .ident  \"GCC: (Ubuntu 6.2.0-3ubuntu11~16.04) 6.2.0 20160901\"\n"
537        "       .section        .note.GNU-stack,\"x\",@progbits\n"
538);
539#endif // __PIC__
540
541#pragma GCC pop_options
Note: See TracBrowser for help on using the repository browser.