source: libcfa/src/exception.c@ 8f6ea08

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 8f6ea08 was f1b6671, checked in by Andrew Beach <ajbeach@…>, 5 years ago

Unwinding is now handled in exception handling code. That is used to fix one bug, other exception tests added. Noise from the change altered one other test.

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