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 Jul 28 12:41:00 2017 |
---|
13 | // Update Count : 3 |
---|
14 | // |
---|
15 | |
---|
16 | #include "exception.h" |
---|
17 | |
---|
18 | // Implementation of the secret header. |
---|
19 | |
---|
20 | #include <stdlib.h> |
---|
21 | #include <stdio.h> |
---|
22 | #include <unwind.h> |
---|
23 | |
---|
24 | // FIX ME: temporary hack to keep ARM build working |
---|
25 | #ifndef _URC_FATAL_PHASE1_ERROR |
---|
26 | #define _URC_FATAL_PHASE1_ERROR 2 |
---|
27 | #endif // ! _URC_FATAL_PHASE1_ERROR |
---|
28 | #ifndef _URC_FATAL_PHASE2_ERROR |
---|
29 | #define _URC_FATAL_PHASE2_ERROR 2 |
---|
30 | #endif // ! _URC_FATAL_PHASE2_ERROR |
---|
31 | |
---|
32 | #include "lsda.h" |
---|
33 | |
---|
34 | // Temperary global exception context. Does not work with concurency. |
---|
35 | struct exception_context_t { |
---|
36 | struct __cfaehm__try_resume_node * top_resume; |
---|
37 | struct __cfaehm__try_resume_node * current_resume; |
---|
38 | |
---|
39 | exception * current_exception; |
---|
40 | int current_handler_index; |
---|
41 | |
---|
42 | // Storage to avoid using the heap for exceptions. |
---|
43 | exception built_in_storage; |
---|
44 | } shared_stack = {NULL, NULL, 0, 0, 0}; |
---|
45 | |
---|
46 | // Get the current exception context. |
---|
47 | // There can be a single global until multithreading occurs, then each stack |
---|
48 | // needs its own. It will have to be updated to handle that. |
---|
49 | struct exception_context_t * this_exception_context() { |
---|
50 | return &shared_stack; |
---|
51 | } |
---|
52 | //#define SAVE_EXCEPTION_CONTEXT(to_name) |
---|
53 | //struct exception_context_t * to_name = this_exception_context(); |
---|
54 | //exception * this_exception() { |
---|
55 | // return this_exception_context()->current_exception; |
---|
56 | //} |
---|
57 | |
---|
58 | |
---|
59 | // This macro should be the only thing that needs to change across machines. Used in the personality function, way down |
---|
60 | // in termination. |
---|
61 | // struct _Unwind_Context * -> _Unwind_Reason_Code(*)(exception *) |
---|
62 | #define MATCHER_FROM_CONTEXT(ptr_to_context) \ |
---|
63 | (*(_Unwind_Reason_Code(**)(exception*))(_Unwind_GetCFA(ptr_to_context) + 8)) |
---|
64 | |
---|
65 | |
---|
66 | // RESUMPTION ================================================================ |
---|
67 | |
---|
68 | void __cfaehm__throw_resume(exception * except) { |
---|
69 | |
---|
70 | // DEBUG |
---|
71 | printf("Throwing resumption exception %d\n", *except); |
---|
72 | |
---|
73 | struct __cfaehm__try_resume_node * original_head = shared_stack.current_resume; |
---|
74 | struct __cfaehm__try_resume_node * current = |
---|
75 | (original_head) ? original_head->next : shared_stack.top_resume; |
---|
76 | |
---|
77 | for ( ; current ; current = current->next) { |
---|
78 | shared_stack.current_resume = current; |
---|
79 | if (current->handler(except)) { |
---|
80 | shared_stack.current_resume = original_head; |
---|
81 | return; |
---|
82 | } |
---|
83 | } |
---|
84 | |
---|
85 | printf("Unhandled exception %d\n", *except); |
---|
86 | shared_stack.current_resume = original_head; |
---|
87 | |
---|
88 | // Fall back to termination: |
---|
89 | __cfaehm__throw_terminate(except); |
---|
90 | // TODO: Default handler for resumption. |
---|
91 | } |
---|
92 | |
---|
93 | // Do we control where exceptions get thrown even with concurency? If not these are not quite thread safe, the cleanup |
---|
94 | // hook has to be added after the node is built but before it is made the top node. |
---|
95 | |
---|
96 | void __cfaehm__try_resume_setup(struct __cfaehm__try_resume_node * node, |
---|
97 | int (*handler)(exception * except)) { |
---|
98 | node->next = shared_stack.top_resume; |
---|
99 | node->handler = handler; |
---|
100 | shared_stack.top_resume = node; |
---|
101 | } |
---|
102 | |
---|
103 | void __cfaehm__try_resume_cleanup(struct __cfaehm__try_resume_node * node) { |
---|
104 | shared_stack.top_resume = node->next; |
---|
105 | } |
---|
106 | |
---|
107 | |
---|
108 | // TERMINATION =============================================================== |
---|
109 | |
---|
110 | // MEMORY MANAGEMENT (still for integers) |
---|
111 | // May have to move to cfa for constructors and destructors. |
---|
112 | |
---|
113 | // Creates a copy of the indicated exception and sets current_exception to it. |
---|
114 | static void __cfaehm__allocate_exception( exception * except ) { |
---|
115 | struct exception_context_t * context = this_exception_context(); |
---|
116 | |
---|
117 | // Try to use the context's store, otherwise use the heap. |
---|
118 | if ( 0 == context->built_in_storage ) { |
---|
119 | context->current_exception = &context->built_in_storage; |
---|
120 | } else { |
---|
121 | exception * new_copy = malloc( sizeof( exception/*int*/ ) ); |
---|
122 | if ( ! new_copy ) { |
---|
123 | // Failure: cannot allocate exception. Terminate thread. |
---|
124 | exit(1); // <- thread or program? |
---|
125 | } |
---|
126 | context->current_exception = new_copy; |
---|
127 | } |
---|
128 | |
---|
129 | // Copy the exception to storage. |
---|
130 | *context->current_exception = *except; |
---|
131 | } |
---|
132 | |
---|
133 | // Delete the provided exception, unsetting current_exception if relivant. |
---|
134 | static void __cfaehm__delete_exception( exception * except ) { |
---|
135 | struct exception_context_t * context = this_exception_context(); |
---|
136 | |
---|
137 | // DEBUG |
---|
138 | printf( "Deleting Exception %d (%s)\n", *except, |
---|
139 | (&context->built_in_storage == except) ? "builtin" : "dynamic" ); |
---|
140 | |
---|
141 | if ( context->current_exception == except ) { |
---|
142 | // TODO: This should restore it to the last exception. |
---|
143 | context->current_exception = NULL; |
---|
144 | } |
---|
145 | if ( &context->built_in_storage == except ) { |
---|
146 | // You can't throw the exception '0'. |
---|
147 | context->built_in_storage = 0; |
---|
148 | } else { |
---|
149 | // Only secondary or too large exceptions are thrown. |
---|
150 | free( except ); |
---|
151 | } |
---|
152 | } |
---|
153 | |
---|
154 | // If this isn't a rethrow (*except==0), delete the provided exception. |
---|
155 | void __cfaehm__cleanup_terminate( exception ** except ) { |
---|
156 | if ( *except ) __cfaehm__delete_exception( *except ); |
---|
157 | } |
---|
158 | |
---|
159 | |
---|
160 | // We need a piece of storage to raise the exception |
---|
161 | struct _Unwind_Exception this_exception_storage; |
---|
162 | |
---|
163 | // Function needed by force unwind |
---|
164 | // It basically says to unwind the whole stack and then exit when we reach the end of the stack |
---|
165 | static _Unwind_Reason_Code _Stop_Fn( |
---|
166 | int version, |
---|
167 | _Unwind_Action actions, |
---|
168 | _Unwind_Exception_Class exceptionClass, |
---|
169 | struct _Unwind_Exception * unwind_exception, |
---|
170 | struct _Unwind_Context * context, |
---|
171 | void * some_param) { |
---|
172 | if( actions & _UA_END_OF_STACK ) exit(1); |
---|
173 | if( actions & _UA_CLEANUP_PHASE ) return _URC_NO_REASON; |
---|
174 | |
---|
175 | return _URC_FATAL_PHASE2_ERROR; |
---|
176 | } |
---|
177 | |
---|
178 | // The exception that is being thrown must already be stored. |
---|
179 | __attribute__((noreturn)) void __cfaehm__begin_unwind(void) { |
---|
180 | if ( ! this_exception_context()->current_exception ) { |
---|
181 | printf("UNWIND ERROR missing exception in begin unwind\n"); |
---|
182 | abort(); |
---|
183 | } |
---|
184 | |
---|
185 | |
---|
186 | // Call stdlibc to raise the exception |
---|
187 | _Unwind_Reason_Code ret = _Unwind_RaiseException( &this_exception_storage ); |
---|
188 | |
---|
189 | // If we reach here it means something happened. For resumption to work we need to find a way to return back to |
---|
190 | // here. Most of them will probably boil down to setting a global flag and making the phase 1 either stop or |
---|
191 | // fail. Causing an error on purpose may help avoiding unnecessary work but it might have some weird side |
---|
192 | // effects. If we just pretend no handler was found that would work but may be expensive for no reason since we |
---|
193 | // will always search the whole stack. |
---|
194 | |
---|
195 | if( ret == _URC_END_OF_STACK ) { |
---|
196 | // No proper handler was found. This can be handled in several way. C++ calls std::terminate Here we |
---|
197 | // force unwind the stack, basically raising a cancellation. |
---|
198 | printf("Uncaught exception %p\n", &this_exception_storage); |
---|
199 | |
---|
200 | ret = _Unwind_ForcedUnwind( &this_exception_storage, _Stop_Fn, (void*)0x22 ); |
---|
201 | printf("UNWIND ERROR %d after force unwind\n", ret); |
---|
202 | abort(); |
---|
203 | } |
---|
204 | |
---|
205 | // We did not simply reach the end of the stack without finding a handler. Something wen't wrong |
---|
206 | printf("UNWIND ERROR %d after raise exception\n", ret); |
---|
207 | abort(); |
---|
208 | } |
---|
209 | |
---|
210 | void __cfaehm__throw_terminate( exception * val ) { |
---|
211 | // DEBUG |
---|
212 | printf("Throwing termination exception\n"); |
---|
213 | |
---|
214 | __cfaehm__allocate_exception( val ); |
---|
215 | __cfaehm__begin_unwind(); |
---|
216 | } |
---|
217 | |
---|
218 | void __cfaehm__rethrow_terminate(void) { |
---|
219 | // DEBUG |
---|
220 | printf("Rethrowing termination exception\n"); |
---|
221 | |
---|
222 | __cfaehm__begin_unwind(); |
---|
223 | } |
---|
224 | |
---|
225 | // This is our personality routine. For every stack frame anotated with ".cfi_personality 0x3,__gcfa_personality_v0". |
---|
226 | // This function will be called twice when unwinding. Once in the search phased and once in the cleanup phase. |
---|
227 | _Unwind_Reason_Code __gcfa_personality_v0 ( |
---|
228 | int version, _Unwind_Action actions, unsigned long long exceptionClass, |
---|
229 | struct _Unwind_Exception* unwind_exception, |
---|
230 | struct _Unwind_Context* context) |
---|
231 | { |
---|
232 | |
---|
233 | // DEBUG |
---|
234 | //printf("CFA: 0x%lx\n", _Unwind_GetCFA(context)); |
---|
235 | printf("Personality function (%d, %x, %llu, %p, %p):", version, actions, exceptionClass, unwind_exception, context); |
---|
236 | |
---|
237 | // If we've reached the end of the stack then there is nothing much we can do... |
---|
238 | if( actions & _UA_END_OF_STACK ) return _URC_END_OF_STACK; |
---|
239 | |
---|
240 | // DEBUG |
---|
241 | if (actions & _UA_SEARCH_PHASE) { |
---|
242 | printf(" lookup phase"); |
---|
243 | } |
---|
244 | // DEBUG |
---|
245 | else if (actions & _UA_CLEANUP_PHASE) { |
---|
246 | printf(" cleanup phase"); |
---|
247 | } |
---|
248 | // Just in case, probably can't actually happen |
---|
249 | else { |
---|
250 | printf(" error\n"); |
---|
251 | return _URC_FATAL_PHASE1_ERROR; |
---|
252 | } |
---|
253 | |
---|
254 | // Get a pointer to the language specific data from which we will read what we need |
---|
255 | const unsigned char * lsd = (const unsigned char*) _Unwind_GetLanguageSpecificData( context ); |
---|
256 | |
---|
257 | if( !lsd ) { //Nothing to do, keep unwinding |
---|
258 | printf(" no LSD"); |
---|
259 | goto UNWIND; |
---|
260 | } |
---|
261 | |
---|
262 | // Get the instuction pointer and a reading pointer into the exception table |
---|
263 | lsda_header_info lsd_info; |
---|
264 | const unsigned char * cur_ptr = parse_lsda_header( context, lsd, &lsd_info); |
---|
265 | _Unwind_Ptr instruction_ptr = _Unwind_GetIP( context ); |
---|
266 | |
---|
267 | // Linearly search the table for stuff to do |
---|
268 | while( cur_ptr < lsd_info.action_table ) { |
---|
269 | _Unwind_Ptr callsite_start; |
---|
270 | _Unwind_Ptr callsite_len; |
---|
271 | _Unwind_Ptr callsite_landing_pad; |
---|
272 | _uleb128_t callsite_action; |
---|
273 | |
---|
274 | // Decode the common stuff we have in here |
---|
275 | cur_ptr = read_encoded_value (0, lsd_info.call_site_encoding, cur_ptr, &callsite_start); |
---|
276 | cur_ptr = read_encoded_value (0, lsd_info.call_site_encoding, cur_ptr, &callsite_len); |
---|
277 | cur_ptr = read_encoded_value (0, lsd_info.call_site_encoding, cur_ptr, &callsite_landing_pad); |
---|
278 | cur_ptr = read_uleb128 (cur_ptr, &callsite_action); |
---|
279 | |
---|
280 | // Have we reach the correct frame info yet? |
---|
281 | if( lsd_info.Start + callsite_start + callsite_len < instruction_ptr ) { |
---|
282 | //DEBUG BEGIN |
---|
283 | void * ls = (void*)lsd_info.Start; |
---|
284 | void * cs = (void*)callsite_start; |
---|
285 | void * cl = (void*)callsite_len; |
---|
286 | void * bp = (void*)lsd_info.Start + callsite_start; |
---|
287 | void * ep = (void*)lsd_info.Start + callsite_start + callsite_len; |
---|
288 | void * ip = (void*)instruction_ptr; |
---|
289 | printf("\nfound %p - %p (%p, %p, %p), looking for %p\n", bp, ep, ls, cs, cl, ip); |
---|
290 | //DEBUG END |
---|
291 | continue; |
---|
292 | } |
---|
293 | |
---|
294 | // Have we gone too far |
---|
295 | if( lsd_info.Start + callsite_start > instruction_ptr ) { |
---|
296 | printf(" gone too far"); |
---|
297 | break; |
---|
298 | } |
---|
299 | |
---|
300 | // Something to do? |
---|
301 | if( callsite_landing_pad ) { |
---|
302 | // Which phase are we in |
---|
303 | if (actions & _UA_SEARCH_PHASE) { |
---|
304 | // Search phase, this means we probably found a potential handler and must check if it is a match |
---|
305 | |
---|
306 | // If we have arbitrarily decided that 0 means nothing to do and 1 means there is a potential handler |
---|
307 | // This doesn't seem to conflict the gcc default behavior |
---|
308 | if (callsite_action != 0) { |
---|
309 | // Now we want to run some code to see if the handler matches |
---|
310 | // This is the tricky part where we want to the power to run arbitrary code |
---|
311 | // However, generating a new exception table entry and try routine every time |
---|
312 | // is way more expansive than we might like |
---|
313 | // The information we have is : |
---|
314 | // - The GR (Series of registers) |
---|
315 | // GR1=GP Global Pointer of frame ref by context |
---|
316 | // - The instruction pointer |
---|
317 | // - The instruction pointer info (???) |
---|
318 | // - The CFA (Canonical Frame Address) |
---|
319 | // - The BSP (Probably the base stack pointer) |
---|
320 | |
---|
321 | |
---|
322 | // The current apprach uses one exception table entry per try block |
---|
323 | _uleb128_t imatcher; |
---|
324 | // Get the relative offset to the |
---|
325 | cur_ptr = read_uleb128 (cur_ptr, &imatcher); |
---|
326 | |
---|
327 | // Get a function pointer from the relative offset and call it |
---|
328 | // _Unwind_Reason_Code (*matcher)() = (_Unwind_Reason_Code (*)())lsd_info.LPStart + imatcher; |
---|
329 | |
---|
330 | _Unwind_Reason_Code (*matcher)(exception *) = |
---|
331 | MATCHER_FROM_CONTEXT(context); |
---|
332 | int index = matcher(shared_stack.current_exception); |
---|
333 | _Unwind_Reason_Code ret = (0 == index) |
---|
334 | ? _URC_CONTINUE_UNWIND : _URC_HANDLER_FOUND; |
---|
335 | shared_stack.current_handler_index = index; |
---|
336 | |
---|
337 | // Based on the return value, check if we matched the exception |
---|
338 | if( ret == _URC_HANDLER_FOUND) printf(" handler found\n"); |
---|
339 | else printf(" no handler\n"); |
---|
340 | return ret; |
---|
341 | } |
---|
342 | |
---|
343 | // This is only a cleanup handler, ignore it |
---|
344 | printf(" no action"); |
---|
345 | } |
---|
346 | else if (actions & _UA_CLEANUP_PHASE) { |
---|
347 | |
---|
348 | if( (callsite_action != 0) && !(actions & _UA_HANDLER_FRAME) ){ |
---|
349 | // If this is a potential exception handler |
---|
350 | // but not the one that matched the exception in the seach phase, |
---|
351 | // just ignore it |
---|
352 | goto UNWIND; |
---|
353 | } |
---|
354 | |
---|
355 | // We need to run some clean-up or a handler |
---|
356 | // These statment do the right thing but I don't know any specifics at all |
---|
357 | _Unwind_SetGR( context, __builtin_eh_return_data_regno(0), (_Unwind_Ptr) unwind_exception ); |
---|
358 | _Unwind_SetGR( context, __builtin_eh_return_data_regno(1), 0 ); |
---|
359 | |
---|
360 | // I assume this sets the instruction pointer to the adress of the landing pad |
---|
361 | // It doesn't actually set it, it only state the value that needs to be set once we return _URC_INSTALL_CONTEXT |
---|
362 | _Unwind_SetIP( context, ((lsd_info.LPStart) + (callsite_landing_pad)) ); |
---|
363 | |
---|
364 | // DEBUG |
---|
365 | printf(" action\n"); |
---|
366 | |
---|
367 | // Return have some action to run |
---|
368 | return _URC_INSTALL_CONTEXT; |
---|
369 | } |
---|
370 | } |
---|
371 | |
---|
372 | // Nothing to do, move along |
---|
373 | printf(" no landing pad"); |
---|
374 | } |
---|
375 | // No handling found |
---|
376 | printf(" table end reached\n"); |
---|
377 | |
---|
378 | // DEBUG |
---|
379 | UNWIND: |
---|
380 | printf(" unwind\n"); |
---|
381 | |
---|
382 | // Keep unwinding the stack |
---|
383 | return _URC_CONTINUE_UNWIND; |
---|
384 | } |
---|
385 | |
---|
386 | // Try statements are hoisted out see comments for details. With this could probably be unique and simply linked from |
---|
387 | // libcfa but there is one problem left, see the exception table for details |
---|
388 | __attribute__((noinline)) |
---|
389 | void __cfaehm__try_terminate(void (*try_block)(), |
---|
390 | void (*catch_block)(int index, exception * except), |
---|
391 | __attribute__((unused)) int (*match_block)(exception * except)) { |
---|
392 | //! volatile int xy = 0; |
---|
393 | //! printf("%p %p %p %p\n", &try_block, &catch_block, &match_block, &xy); |
---|
394 | |
---|
395 | // Setup statments: These 2 statments won't actually result in any code, they only setup global tables. |
---|
396 | // However, they clobber gcc cancellation support from gcc. We can replace the personality routine but |
---|
397 | // replacing the exception table gcc generates is not really doable, it generates labels based on how the |
---|
398 | // assembly works. |
---|
399 | |
---|
400 | // Setup the personality routine |
---|
401 | asm volatile (".cfi_personality 0x3,__gcfa_personality_v0"); |
---|
402 | // Setup the exception table |
---|
403 | asm volatile (".cfi_lsda 0x3, .LLSDACFA2"); |
---|
404 | |
---|
405 | // Label which defines the start of the area for which the handler is setup. |
---|
406 | asm volatile (".TRYSTART:"); |
---|
407 | |
---|
408 | // The actual statements of the try blocks |
---|
409 | try_block(); |
---|
410 | |
---|
411 | // asm statement to prevent deadcode removal |
---|
412 | asm volatile goto ("" : : : : CATCH ); |
---|
413 | |
---|
414 | // Normal return |
---|
415 | return; |
---|
416 | |
---|
417 | // Exceptionnal path |
---|
418 | CATCH : __attribute__(( unused )); |
---|
419 | // Label which defines the end of the area for which the handler is setup. |
---|
420 | asm volatile (".TRYEND:"); |
---|
421 | // Label which defines the start of the exception landing pad. Basically what is called when the exception is |
---|
422 | // caught. Note, if multiple handlers are given, the multiplexing should be done by the generated code, not the |
---|
423 | // exception runtime. |
---|
424 | asm volatile (".CATCH:"); |
---|
425 | |
---|
426 | // Exception handler |
---|
427 | catch_block( shared_stack.current_handler_index, |
---|
428 | shared_stack.current_exception ); |
---|
429 | } |
---|
430 | |
---|
431 | // Exception table data we need to generate. While this is almost generic, the custom data refers to foo_try_match try |
---|
432 | // match, which is no way generic. Some more works need to be done if we want to have a single call to the try routine. |
---|
433 | |
---|
434 | #if defined( __x86_64__ ) || defined( __i386__ ) |
---|
435 | asm ( |
---|
436 | //HEADER |
---|
437 | ".LFECFA1:\n" |
---|
438 | " .globl __gcfa_personality_v0\n" |
---|
439 | " .section .gcc_except_table,\"a\",@progbits\n" |
---|
440 | ".LLSDACFA2:\n" //TABLE header |
---|
441 | " .byte 0xff\n" |
---|
442 | " .byte 0xff\n" |
---|
443 | " .byte 0x1\n" |
---|
444 | " .uleb128 .LLSDACSECFA2-.LLSDACSBCFA2\n" // BODY length |
---|
445 | // Body uses language specific data and therefore could be modified arbitrarily |
---|
446 | ".LLSDACSBCFA2:\n" // BODY start |
---|
447 | " .uleb128 .TRYSTART-__cfaehm__try_terminate\n" // Handled area start (relative to start of function) |
---|
448 | " .uleb128 .TRYEND-.TRYSTART\n" // Handled area length |
---|
449 | " .uleb128 .CATCH-__cfaehm__try_terminate\n" // Hanlder landing pad adress (relative to start of function) |
---|
450 | " .uleb128 1\n" // Action code, gcc seems to use always 0 |
---|
451 | ".LLSDACSECFA2:\n" // BODY end |
---|
452 | " .text\n" // TABLE footer |
---|
453 | " .size __cfaehm__try_terminate, .-__cfaehm__try_terminate\n" |
---|
454 | " .ident \"GCC: (Ubuntu 6.2.0-3ubuntu11~16.04) 6.2.0 20160901\"\n" |
---|
455 | // " .section .note.GNU-stack,\"x\",@progbits\n" |
---|
456 | ); |
---|
457 | #endif // __x86_64__ || __i386__ |
---|