source: libcfa/src/exception.c @ 73530d9

arm-ehjacob/cs343-translationnew-astnew-ast-unique-expr
Last change on this file since 73530d9 was 73530d9, checked in by Andrew Beach <ajbeach@…>, 19 months ago

Set up the public fields in _Unwind_Exception. Helps with cross language compatability.

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