source: libcfa/src/exception.c@ 70ac8d0

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 70ac8d0 was 2922871, checked in by Andrew Beach <ajbeach@…>, 5 years ago

Divided termination code in the exception library so it has memory management and cancellation sections.

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