source: libcfa/src/exception.c@ 9246ec6

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 9246ec6 was 8ad5752, checked in by Andrew Beach <ajbeach@…>, 5 years ago

Added tests for default exception handlers. Fixed a memory leak they revealed.

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