source: doc/working/exception/impl/exception.c@ 974bcdd

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new with_gc
Last change on this file since 974bcdd was 35ba584c, checked in by Andrew Beach <ajbeach@…>, 8 years ago

Added rethrow to translation.
Implemend and tested termination rethrowing.

  • Property mode set to 100644
File size: 12.3 KB
Line 
1#include "exception.h"
2
3// Implementation of the secret header.
4
5#include <stdlib.h>
6#include <stdio.h>
7#include <unwind.h>
8
9#include "lsda.h"
10
11struct shared_stack_t shared_stack;
12
13
14// This macro should be the only thing that needs to change across machines.
15// Used in the personality function, way down in termination.
16// struct _Unwind_Context * -> _Unwind_Reason_Code(*)()
17#define MATCHER_FROM_CONTEXT(ptr_to_context) \
18 (*(_Unwind_Reason_Code(**)())(_Unwind_GetCFA(ptr_to_context) + 8))
19
20
21// RESUMPTION ================================================================
22
23void __throw_resume(exception except) {
24
25 // DEBUG
26 printf("Throwing resumption exception %d\n", except);
27
28 struct __try_resume_node * original_head = shared_stack.current_resume;
29 struct __try_resume_node * current =
30 (original_head) ? original_head->next : shared_stack.top_resume;
31
32 for ( ; current ; current = current->next) {
33 shared_stack.current_resume = current;
34 if (current->try_to_handle(except)) {
35 shared_stack.current_resume = original_head;
36 return;
37 }
38 }
39
40 printf("Unhandled exception %d\n", except);
41 shared_stack.current_resume = original_head;
42
43 // Fall back to termination:
44 __throw_terminate(except);
45 // TODO: Default handler for resumption.
46}
47
48
49// TERMINATION ===============================================================
50
51// Requires -fexceptions to work.
52
53// Global which defines the current exception
54// Currently an int just to make matching easier
55//int this_exception; (became shared_stack.current_exception)
56
57// We need a piece of storage to raise the exception
58struct _Unwind_Exception this_exception_storage;
59
60// Function needed by force unwind
61// It basically says to unwind the whole stack and then exit when we reach the end of the stack
62static _Unwind_Reason_Code _Stop_Fn(
63 int version,
64 _Unwind_Action actions,
65 _Unwind_Exception_Class exceptionClass,
66 struct _Unwind_Exception * unwind_exception,
67 struct _Unwind_Context * context,
68 void * some_param) {
69 if( actions & _UA_END_OF_STACK ) exit(1);
70 if( actions & _UA_CLEANUP_PHASE ) return _URC_NO_REASON;
71
72 return _URC_FATAL_PHASE2_ERROR;
73}
74
75void __throw_terminate( int val ) {
76 // Store the current exception
77 shared_stack.current_exception = val;
78
79 // DEBUG
80 printf("Throwing termination exception %d\n", val);
81
82 // Call stdlibc to raise the exception
83 _Unwind_Reason_Code ret = _Unwind_RaiseException( &this_exception_storage );
84
85 // If we reach here it means something happened
86 // For resumption to work we need to find a way to return back to here
87 // Most of them will probably boil down to setting a global flag and making the phase 1 either stop or fail.
88 // Causing an error on purpose may help avoiding unnecessary work but it might have some weird side effects.
89 // If we just pretend no handler was found that would work but may be expensive for no reason since we will always
90 // search the whole stack
91
92 if( ret == _URC_END_OF_STACK ) {
93 // No proper handler was found
94 // This can be handled in several way
95 // C++ calls std::terminate
96 // Here we force unwind the stack, basically raising a cancellation
97 printf("Uncaught exception %p\n", &this_exception_storage);
98
99 ret = _Unwind_ForcedUnwind( &this_exception_storage, _Stop_Fn, (void*)0x22 );
100 printf("UNWIND ERROR %d after force unwind\n", ret);
101 abort();
102 }
103
104 // We did not simply reach the end of the stack without finding a handler,
105 // Something wen't wrong
106 printf("UNWIND ERROR %d after raise exception\n", ret);
107 abort();
108}
109
110// Nesting this the other way would probably be faster.
111void __rethrow_terminate(void) {
112 // DEBUG
113 printf("Rethrowing termination exception\n");
114
115 __throw_terminate(shared_stack.current_exception);
116}
117
118// This is our personality routine
119// For every stack frame anotated with ".cfi_personality 0x3,__gcfa_personality_v0"
120// This function will be called twice when unwinding
121// Once in the search phased and once in the cleanup phase
122_Unwind_Reason_Code __gcfa_personality_v0 (
123 int version, _Unwind_Action actions, unsigned long long exceptionClass,
124 struct _Unwind_Exception* unwind_exception,
125 struct _Unwind_Context* context)
126{
127
128 // DEBUG
129 //printf("CFA: 0x%lx\n", _Unwind_GetCFA(context));
130 printf("Personality function (%d, %x, %llu, %p, %p):", version, actions, exceptionClass, unwind_exception, context);
131
132 // If we've reached the end of the stack then there is nothing much we can do...
133 if( actions & _UA_END_OF_STACK ) return _URC_END_OF_STACK;
134
135 // DEBUG
136 if (actions & _UA_SEARCH_PHASE) {
137 printf(" lookup phase");
138 }
139 // DEBUG
140 else if (actions & _UA_CLEANUP_PHASE) {
141 printf(" cleanup phase");
142 }
143 // Just in case, probably can't actually happen
144 else {
145 printf(" error\n");
146 return _URC_FATAL_PHASE1_ERROR;
147 }
148
149 // Get a pointer to the language specific data from which we will read what we need
150 const unsigned char * lsd = (const unsigned char*) _Unwind_GetLanguageSpecificData( context );
151
152 if( !lsd ) { //Nothing to do, keep unwinding
153 printf(" no LSD");
154 goto UNWIND;
155 }
156
157 // Get the instuction pointer and a reading pointer into the exception table
158 lsda_header_info lsd_info;
159 const unsigned char * cur_ptr = parse_lsda_header( context, lsd, &lsd_info);
160 _Unwind_Ptr instruction_ptr = _Unwind_GetIP( context );
161
162 // Linearly search the table for stuff to do
163 while( cur_ptr < lsd_info.action_table ) {
164 _Unwind_Ptr callsite_start;
165 _Unwind_Ptr callsite_len;
166 _Unwind_Ptr callsite_landing_pad;
167 _uleb128_t callsite_action;
168
169 // Decode the common stuff we have in here
170 cur_ptr = read_encoded_value (0, lsd_info.call_site_encoding, cur_ptr, &callsite_start);
171 cur_ptr = read_encoded_value (0, lsd_info.call_site_encoding, cur_ptr, &callsite_len);
172 cur_ptr = read_encoded_value (0, lsd_info.call_site_encoding, cur_ptr, &callsite_landing_pad);
173 cur_ptr = read_uleb128 (cur_ptr, &callsite_action);
174
175 // Have we reach the correct frame info yet?
176 if( lsd_info.Start + callsite_start + callsite_len < instruction_ptr ) {
177 //DEBUG BEGIN
178 void * ls = (void*)lsd_info.Start;
179 void * cs = (void*)callsite_start;
180 void * cl = (void*)callsite_len;
181 void * bp = (void*)lsd_info.Start + callsite_start;
182 void * ep = (void*)lsd_info.Start + callsite_start + callsite_len;
183 void * ip = (void*)instruction_ptr;
184 printf("\nfound %p - %p (%p, %p, %p), looking for %p\n", bp, ep, ls, cs, cl, ip);
185 //DEBUG END
186 continue;
187 }
188
189 // Have we gone too far
190 if( lsd_info.Start + callsite_start > instruction_ptr ) {
191 printf(" gone too far");
192 break;
193 }
194
195 // Something to do?
196 if( callsite_landing_pad ) {
197 // Which phase are we in
198 if (actions & _UA_SEARCH_PHASE) {
199 // Search phase, this means we probably found a potential handler and must check if it is a match
200
201 // If we have arbitrarily decided that 0 means nothing to do and 1 means there is a potential handler
202 // This doesn't seem to conflict the gcc default behavior
203 if (callsite_action != 0) {
204 // Now we want to run some code to see if the handler matches
205 // This is the tricky part where we want to the power to run arbitrary code
206 // However, generating a new exception table entry and try routine every time
207 // is way more expansive than we might like
208 // The information we have is :
209 // - The GR (Series of registers)
210 // GR1=GP Global Pointer of frame ref by context
211 // - The instruction pointer
212 // - The instruction pointer info (???)
213 // - The CFA (Canonical Frame Address)
214 // - The BSP (Probably the base stack pointer)
215
216
217 // The current apprach uses one exception table entry per try block
218 _uleb128_t imatcher;
219 // Get the relative offset to the
220 cur_ptr = read_uleb128 (cur_ptr, &imatcher);
221
222 // Get a function pointer from the relative offset and call it
223 // _Unwind_Reason_Code (*matcher)() = (_Unwind_Reason_Code (*)())lsd_info.LPStart + imatcher;
224
225 _Unwind_Reason_Code (*matcher)() =
226 MATCHER_FROM_CONTEXT(context);
227 int index = matcher(shared_stack.current_exception);
228 _Unwind_Reason_Code ret = (0 == index)
229 ? _URC_CONTINUE_UNWIND : _URC_HANDLER_FOUND;
230 shared_stack.current_handler_index = index;
231
232 // Based on the return value, check if we matched the exception
233 if( ret == _URC_HANDLER_FOUND) printf(" handler found\n");
234 else printf(" no handler\n");
235 return ret;
236 }
237
238 // This is only a cleanup handler, ignore it
239 printf(" no action");
240 }
241 else if (actions & _UA_CLEANUP_PHASE) {
242
243 if( (callsite_action != 0) && !(actions & _UA_HANDLER_FRAME) ){
244 // If this is a potential exception handler
245 // but not the one that matched the exception in the seach phase,
246 // just ignore it
247 goto UNWIND;
248 }
249
250 // We need to run some clean-up or a handler
251 // These statment do the right thing but I don't know any specifics at all
252 _Unwind_SetGR( context, __builtin_eh_return_data_regno(0), (_Unwind_Ptr) unwind_exception );
253 _Unwind_SetGR( context, __builtin_eh_return_data_regno(1), 0 );
254
255 // I assume this sets the instruction pointer to the adress of the landing pad
256 // It doesn't actually set it, it only state the value that needs to be set once we return _URC_INSTALL_CONTEXT
257 _Unwind_SetIP( context, lsd_info.LPStart + callsite_landing_pad );
258
259 // DEBUG
260 printf(" action\n");
261
262 // Return have some action to run
263 return _URC_INSTALL_CONTEXT;
264 }
265 }
266
267 // Nothing to do, move along
268 printf(" no landing pad");
269 }
270 // No handling found
271 printf(" table end reached\n");
272
273 // DEBUG
274 UNWIND:
275 printf(" unwind\n");
276
277 // Keep unwinding the stack
278 return _URC_CONTINUE_UNWIND;
279}
280
281// Try statements are hoisted out see comments for details
282// With this could probably be unique and simply linked from
283// libcfa but there is one problem left, see the exception table
284// for details
285__attribute__((noinline))
286void __try_terminate(void (*try_block)(),
287 void (*catch_block)(int index, exception except),
288 __attribute__((unused)) int (*match_block)(exception except)) {
289 //! volatile int xy = 0;
290 //! printf("%p %p %p %p\n", &try_block, &catch_block, &match_block, &xy);
291
292 // Setup statments
293 // These 2 statments won't actually result in any code,
294 // they only setup global tables.
295 // However, they clobber gcc cancellation support from gcc.
296 // We can replace the personality routine but replacing the exception
297 // table gcc generates is not really doable, it generates labels based
298 // on how the assembly works.
299 // Setup the personality routine
300 asm volatile (".cfi_personality 0x3,__gcfa_personality_v0");
301 // Setup the exception table
302 asm volatile (".cfi_lsda 0x3, .LLSDACFA2");
303
304 // Label which defines the start of the area for which the handler is setup
305 asm volatile (".TRYSTART:");
306
307 // The actual statements of the try blocks
308 try_block();
309
310 // asm statement to prevent deadcode removal
311 asm volatile goto ("" : : : : CATCH );
312
313 // Normal return
314 return;
315
316 // Exceptionnal path
317 CATCH : __attribute__(( unused ));
318 // Label which defines the end of the area for which the handler is setup
319 asm volatile (".TRYEND:");
320 // Label which defines the start of the exception landing pad
321 // basically what will be called when the exception is caught
322 // Note, if multiple handlers are given, the multiplexing should be done
323 // by the generated code, not the exception runtime
324 asm volatile (".CATCH:");
325
326 // Exception handler
327 catch_block(shared_stack.current_handler_index,
328 shared_stack.current_exception);
329}
330
331// Exception table data we need to generate
332// While this is almost generic, the custom data refers to
333// foo_try_match try match, which is no way generic
334// Some more works need to be done if we want to have a single
335// call to the try routine
336asm (
337 //HEADER
338 ".LFECFA1:\n"
339 " .globl __gcfa_personality_v0\n"
340 " .section .gcc_except_table,\"a\",@progbits\n"
341 ".LLSDACFA2:\n" //TABLE header
342 " .byte 0xff\n"
343 " .byte 0xff\n"
344 " .byte 0x1\n"
345 " .uleb128 .LLSDACSECFA2-.LLSDACSBCFA2\n" // BODY length
346 // Body uses language specific data and therefore could be modified arbitrarily
347 ".LLSDACSBCFA2:\n" // BODY start
348 " .uleb128 .TRYSTART-__try_terminate\n" // Handled area start (relative to start of function)
349 " .uleb128 .TRYEND-.TRYSTART\n" // Handled area length
350 " .uleb128 .CATCH-__try_terminate\n" // Hanlder landing pad adress (relative to start of function)
351 " .uleb128 1\n" // Action code, gcc seems to use always 0
352 ".LLSDACSECFA2:\n" // BODY end
353 " .text\n" // TABLE footer
354 " .size __try_terminate, .-__try_terminate\n"
355 " .ident \"GCC: (Ubuntu 6.2.0-3ubuntu11~16.04) 6.2.0 20160901\"\n"
356// " .section .note.GNU-stack,\"x\",@progbits\n"
357);
Note: See TracBrowser for help on using the repository browser.