Merged in rest of Native Client changes, untested
[mono.git] / mono / mini / exceptions-x86.c
1 /*
2  * exceptions-x86.c: exception support for x86
3  *
4  * Authors:
5  *   Dietmar Maurer (dietmar@ximian.com)
6  *
7  * (C) 2001 Ximian, Inc.
8  */
9
10 #include <config.h>
11 #include <glib.h>
12 #include <signal.h>
13 #include <string.h>
14
15 #include <mono/arch/x86/x86-codegen.h>
16 #include <mono/metadata/appdomain.h>
17 #include <mono/metadata/tabledefs.h>
18 #include <mono/metadata/threads.h>
19 #include <mono/metadata/debug-helpers.h>
20 #include <mono/metadata/exception.h>
21 #include <mono/metadata/gc-internal.h>
22 #include <mono/metadata/mono-debug.h>
23 #include <mono/utils/mono-mmap.h>
24
25 #include "mini.h"
26 #include "mini-x86.h"
27 #include "tasklets.h"
28 #include "debug-mini.h"
29
30 static gpointer signal_exception_trampoline;
31
32 gpointer
33 mono_x86_get_signal_exception_trampoline (MonoTrampInfo **info, gboolean aot) MONO_INTERNAL;
34
35 #ifdef TARGET_WIN32
36 static void (*restore_stack) (void *);
37
38 static MonoW32ExceptionHandler fpe_handler;
39 static MonoW32ExceptionHandler ill_handler;
40 static MonoW32ExceptionHandler segv_handler;
41
42 static LPTOP_LEVEL_EXCEPTION_FILTER old_handler;
43
44 #ifndef PROCESS_CALLBACK_FILTER_ENABLED
45 #       define PROCESS_CALLBACK_FILTER_ENABLED 1
46 #endif
47
48 #define W32_SEH_HANDLE_EX(_ex) \
49         if (_ex##_handler) _ex##_handler(0, er, sctx)
50
51 /*
52  * mono_win32_get_handle_stackoverflow (void):
53  *
54  * Returns a pointer to a method which restores the current context stack
55  * and calls handle_exceptions, when done restores the original stack.
56  */
57 static gpointer
58 mono_win32_get_handle_stackoverflow (void)
59 {
60         static guint8 *start = NULL;
61         guint8 *code;
62
63         if (start)
64                 return start;
65
66         /* restore_contect (void *sigctx) */
67         start = code = mono_global_codeman_reserve (128);
68
69         /* load context into ebx */
70         x86_mov_reg_membase (code, X86_EBX, X86_ESP, 4, 4);
71
72         /* move current stack into edi for later restore */
73         x86_mov_reg_reg (code, X86_EDI, X86_ESP, 4);
74
75         /* use the new freed stack from sigcontext */
76         x86_mov_reg_membase (code, X86_ESP, X86_EBX,  G_STRUCT_OFFSET (struct sigcontext, esp), 4);
77
78         /* get the current domain */
79         x86_call_code (code, mono_domain_get);
80
81         /* get stack overflow exception from domain object */
82         x86_mov_reg_membase (code, X86_EAX, X86_EAX, G_STRUCT_OFFSET (MonoDomain, stack_overflow_ex), 4);
83
84         /* call mono_arch_handle_exception (sctx, stack_overflow_exception_obj, FALSE) */
85         x86_push_imm (code, 0);
86         x86_push_reg (code, X86_EAX);
87         x86_push_reg (code, X86_EBX);
88         x86_call_code (code, mono_arch_handle_exception);
89
90         /* restore the SEH handler stack */
91         x86_mov_reg_reg (code, X86_ESP, X86_EDI, 4);
92
93         /* return */
94         x86_ret (code);
95
96         return start;
97 }
98
99 /* Special hack to workaround the fact that the
100  * when the SEH handler is called the stack is
101  * to small to recover.
102  *
103  * Stack walking part of this method is from mono_handle_exception
104  *
105  * The idea is simple; 
106  *  - walk the stack to free some space (64k)
107  *  - set esp to new stack location
108  *  - call mono_arch_handle_exception with stack overflow exception
109  *  - set esp to SEH handlers stack
110  *  - done
111  */
112 static void 
113 win32_handle_stack_overflow (EXCEPTION_POINTERS* ep, struct sigcontext *sctx) 
114 {
115         SYSTEM_INFO si;
116         DWORD page_size;
117         MonoDomain *domain = mono_domain_get ();
118         MonoJitInfo rji;
119         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
120         MonoLMF *lmf = jit_tls->lmf;            
121         MonoContext initial_ctx;
122         MonoContext ctx;
123         guint32 free_stack = 0;
124         StackFrameInfo frame;
125
126         /* convert sigcontext to MonoContext (due to reuse of stack walking helpers */
127         mono_arch_sigctx_to_monoctx (sctx, &ctx);
128         
129         /* get our os page size */
130         GetSystemInfo(&si);
131         page_size = si.dwPageSize;
132
133         /* Let's walk the stack to recover
134          * the needed stack space (if possible)
135          */
136         memset (&rji, 0, sizeof (rji));
137
138         initial_ctx = ctx;
139         free_stack = (guint8*)(MONO_CONTEXT_GET_BP (&ctx)) - (guint8*)(MONO_CONTEXT_GET_BP (&initial_ctx));
140
141         /* try to free 64kb from our stack */
142         do {
143                 MonoContext new_ctx;
144
145                 mono_arch_find_jit_info (domain, jit_tls, &rji, &ctx, &new_ctx, &lmf, &frame);
146                 if (!frame.ji) {
147                         g_warning ("Exception inside function without unwind info");
148                         g_assert_not_reached ();
149                 }
150
151                 if (frame.ji != (gpointer)-1) {
152                         free_stack = (guint8*)(MONO_CONTEXT_GET_BP (&ctx)) - (guint8*)(MONO_CONTEXT_GET_BP (&initial_ctx));
153                 }
154
155                 /* todo: we should call abort if ji is -1 */
156                 ctx = new_ctx;
157         } while (free_stack < 64 * 1024 && frame.ji != (gpointer) -1);
158
159         /* convert into sigcontext to be used in mono_arch_handle_exception */
160         mono_arch_monoctx_to_sigctx (&ctx, sctx);
161
162         /* todo: install new stack-guard page */
163
164         /* use the new stack and call mono_arch_handle_exception () */
165         restore_stack (sctx);
166 }
167
168 /*
169  * Unhandled Exception Filter
170  * Top-level per-process exception handler.
171  */
172 LONG CALLBACK seh_handler(EXCEPTION_POINTERS* ep)
173 {
174         EXCEPTION_RECORD* er;
175         CONTEXT* ctx;
176         struct sigcontext* sctx;
177         LONG res;
178
179         res = EXCEPTION_CONTINUE_EXECUTION;
180
181         er = ep->ExceptionRecord;
182         ctx = ep->ContextRecord;
183         sctx = g_malloc(sizeof(struct sigcontext));
184
185         /* Copy Win32 context to UNIX style context */
186         sctx->eax = ctx->Eax;
187         sctx->ebx = ctx->Ebx;
188         sctx->ecx = ctx->Ecx;
189         sctx->edx = ctx->Edx;
190         sctx->ebp = ctx->Ebp;
191         sctx->esp = ctx->Esp;
192         sctx->esi = ctx->Esi;
193         sctx->edi = ctx->Edi;
194         sctx->eip = ctx->Eip;
195
196         switch (er->ExceptionCode) {
197         case EXCEPTION_STACK_OVERFLOW:
198                 win32_handle_stack_overflow (ep, sctx);
199                 break;
200         case EXCEPTION_ACCESS_VIOLATION:
201                 W32_SEH_HANDLE_EX(segv);
202                 break;
203         case EXCEPTION_ILLEGAL_INSTRUCTION:
204                 W32_SEH_HANDLE_EX(ill);
205                 break;
206         case EXCEPTION_INT_DIVIDE_BY_ZERO:
207         case EXCEPTION_INT_OVERFLOW:
208         case EXCEPTION_FLT_DIVIDE_BY_ZERO:
209         case EXCEPTION_FLT_OVERFLOW:
210         case EXCEPTION_FLT_UNDERFLOW:
211         case EXCEPTION_FLT_INEXACT_RESULT:
212                 W32_SEH_HANDLE_EX(fpe);
213                 break;
214         default:
215                 break;
216         }
217
218         /* Copy context back */
219         ctx->Eax = sctx->eax;
220         ctx->Ebx = sctx->ebx;
221         ctx->Ecx = sctx->ecx;
222         ctx->Edx = sctx->edx;
223         ctx->Ebp = sctx->ebp;
224         ctx->Esp = sctx->esp;
225         ctx->Esi = sctx->esi;
226         ctx->Edi = sctx->edi;
227         ctx->Eip = sctx->eip;
228
229         g_free (sctx);
230
231         return res;
232 }
233
234 void win32_seh_init()
235 {
236         /* install restore stack helper */
237         if (!restore_stack)
238                 restore_stack = mono_win32_get_handle_stackoverflow ();
239
240         old_handler = SetUnhandledExceptionFilter(seh_handler);
241 }
242
243 void win32_seh_cleanup()
244 {
245         if (old_handler) SetUnhandledExceptionFilter(old_handler);
246 }
247
248 void win32_seh_set_handler(int type, MonoW32ExceptionHandler handler)
249 {
250         switch (type) {
251         case SIGFPE:
252                 fpe_handler = handler;
253                 break;
254         case SIGILL:
255                 ill_handler = handler;
256                 break;
257         case SIGSEGV:
258                 segv_handler = handler;
259                 break;
260         default:
261                 break;
262         }
263 }
264
265 #endif /* TARGET_WIN32 */
266
267 /*
268  * mono_arch_get_restore_context:
269  *
270  * Returns a pointer to a method which restores a previously saved sigcontext.
271  */
272 gpointer
273 mono_arch_get_restore_context (MonoTrampInfo **info, gboolean aot)
274 {
275         guint8 *start = NULL;
276         guint8 *code;
277         MonoJumpInfo *ji = NULL;
278         GSList *unwind_ops = NULL;
279
280         /* restore_contect (MonoContext *ctx) */
281
282         start = code = mono_global_codeman_reserve (128);
283         
284         /* load ctx */
285         x86_mov_reg_membase (code, X86_EAX, X86_ESP, 4, 4);
286
287         /* get return address, stored in ECX */
288         x86_mov_reg_membase (code, X86_ECX, X86_EAX,  G_STRUCT_OFFSET (MonoContext, eip), 4);
289         /* restore EBX */
290         x86_mov_reg_membase (code, X86_EBX, X86_EAX,  G_STRUCT_OFFSET (MonoContext, ebx), 4);
291         /* restore EDI */
292         x86_mov_reg_membase (code, X86_EDI, X86_EAX,  G_STRUCT_OFFSET (MonoContext, edi), 4);
293         /* restore ESI */
294         x86_mov_reg_membase (code, X86_ESI, X86_EAX,  G_STRUCT_OFFSET (MonoContext, esi), 4);
295         /* restore ESP */
296         x86_mov_reg_membase (code, X86_ESP, X86_EAX,  G_STRUCT_OFFSET (MonoContext, esp), 4);
297         /* save the return addr to the restored stack */
298         x86_push_reg (code, X86_ECX);
299         /* restore EBP */
300         x86_mov_reg_membase (code, X86_EBP, X86_EAX,  G_STRUCT_OFFSET (MonoContext, ebp), 4);
301         /* restore ECX */
302         x86_mov_reg_membase (code, X86_ECX, X86_EAX,  G_STRUCT_OFFSET (MonoContext, ecx), 4);
303         /* restore EDX */
304         x86_mov_reg_membase (code, X86_EDX, X86_EAX,  G_STRUCT_OFFSET (MonoContext, edx), 4);
305         /* restore EAX */
306         x86_mov_reg_membase (code, X86_EAX, X86_EAX,  G_STRUCT_OFFSET (MonoContext, eax), 4);
307
308         /* jump to the saved IP */
309         x86_ret (code);
310
311 #if defined(__native_client_codegen__) && defined(__native_client__)
312         nacl_global_codeman_validate(&start, 128, &code);
313 #endif
314
315         if (info)
316                 *info = mono_tramp_info_create (g_strdup_printf ("restore_context"), start, code - start, ji, unwind_ops);
317         else {
318                 GSList *l;
319
320                 for (l = unwind_ops; l; l = l->next)
321                         g_free (l->data);
322                 g_slist_free (unwind_ops);
323         }
324
325         return start;
326 }
327
328 /*
329  * mono_arch_get_call_filter:
330  *
331  * Returns a pointer to a method which calls an exception filter. We
332  * also use this function to call finally handlers (we pass NULL as 
333  * @exc object in this case).
334  */
335 gpointer
336 mono_arch_get_call_filter (MonoTrampInfo **info, gboolean aot)
337 {
338         guint8* start;
339         guint8 *code;
340         MonoJumpInfo *ji = NULL;
341         GSList *unwind_ops = NULL;
342         guint kMaxCodeSize = NACL_SIZE (64, 128);
343
344         /* call_filter (MonoContext *ctx, unsigned long eip) */
345         start = code = mono_global_codeman_reserve (kMaxCodeSize);
346
347         x86_push_reg (code, X86_EBP);
348         x86_mov_reg_reg (code, X86_EBP, X86_ESP, 4);
349         x86_push_reg (code, X86_EBX);
350         x86_push_reg (code, X86_EDI);
351         x86_push_reg (code, X86_ESI);
352
353         /* load ctx */
354         x86_mov_reg_membase (code, X86_EAX, X86_EBP, 8, 4);
355         /* load eip */
356         x86_mov_reg_membase (code, X86_ECX, X86_EBP, 12, 4);
357         /* save EBP */
358         x86_push_reg (code, X86_EBP);
359
360         /* set new EBP */
361         x86_mov_reg_membase (code, X86_EBP, X86_EAX,  G_STRUCT_OFFSET (MonoContext, ebp), 4);
362         /* restore registers used by global register allocation (EBX & ESI) */
363         x86_mov_reg_membase (code, X86_EBX, X86_EAX,  G_STRUCT_OFFSET (MonoContext, ebx), 4);
364         x86_mov_reg_membase (code, X86_ESI, X86_EAX,  G_STRUCT_OFFSET (MonoContext, esi), 4);
365         x86_mov_reg_membase (code, X86_EDI, X86_EAX,  G_STRUCT_OFFSET (MonoContext, edi), 4);
366
367         /* align stack and save ESP */
368         x86_mov_reg_reg (code, X86_EDX, X86_ESP, 4);
369         x86_alu_reg_imm (code, X86_AND, X86_ESP, -MONO_ARCH_FRAME_ALIGNMENT);
370         g_assert (MONO_ARCH_FRAME_ALIGNMENT >= 8);
371         x86_alu_reg_imm (code, X86_SUB, X86_ESP, MONO_ARCH_FRAME_ALIGNMENT - 8);
372         x86_push_reg (code, X86_EDX);
373
374         /* call the handler */
375         x86_call_reg (code, X86_ECX);
376
377         /* restore ESP */
378         x86_pop_reg (code, X86_ESP);
379
380         /* restore EBP */
381         x86_pop_reg (code, X86_EBP);
382
383         /* restore saved regs */
384         x86_pop_reg (code, X86_ESI);
385         x86_pop_reg (code, X86_EDI);
386         x86_pop_reg (code, X86_EBX);
387         x86_leave (code);
388         x86_ret (code);
389
390 #if defined(__native_client_codegen__) && defined(__native_client__)
391         nacl_global_codeman_validate(&start, kMaxCodeSize, &code);
392 #endif
393
394         if (info)
395                 *info = mono_tramp_info_create (g_strdup_printf ("call_filter"), start, code - start, ji, unwind_ops);
396         else {
397                 GSList *l;
398
399                 for (l = unwind_ops; l; l = l->next)
400                         g_free (l->data);
401                 g_slist_free (unwind_ops);
402         }
403
404         g_assert ((code - start) < kMaxCodeSize);
405         return start;
406 }
407
408 /*
409  * mono_x86_throw_exception:
410  *
411  *   C function called from the throw trampolines.
412  */
413 void
414 mono_x86_throw_exception (mgreg_t *regs, MonoObject *exc, 
415                                                   mgreg_t eip, gboolean rethrow)
416 {
417         static void (*restore_context) (MonoContext *);
418         MonoContext ctx;
419
420         if (!restore_context)
421                 restore_context = mono_get_restore_context ();
422
423         ctx.esp = regs [X86_ESP];
424         ctx.eip = eip;
425         ctx.ebp = regs [X86_EBP];
426         ctx.edi = regs [X86_EDI];
427         ctx.esi = regs [X86_ESI];
428         ctx.ebx = regs [X86_EBX];
429         ctx.edx = regs [X86_EDX];
430         ctx.ecx = regs [X86_ECX];
431         ctx.eax = regs [X86_EAX];
432
433 #ifdef __APPLE__
434         /* The OSX ABI specifies 16 byte alignment at call sites */
435         g_assert ((ctx.esp % MONO_ARCH_FRAME_ALIGNMENT) == 0);
436 #endif
437
438         if (mono_object_isinst (exc, mono_defaults.exception_class)) {
439                 MonoException *mono_ex = (MonoException*)exc;
440                 if (!rethrow)
441                         mono_ex->stack_trace = NULL;
442         }
443
444         if (mono_debug_using_mono_debugger ()) {
445                 guint8 buf [16], *code;
446
447                 mono_breakpoint_clean_code (NULL, (gpointer)eip, 8, buf, sizeof (buf));
448                 code = buf + 8;
449
450                 if (buf [3] == 0xe8) {
451                         MonoContext ctx_cp = ctx;
452                         ctx_cp.eip = eip - 5;
453
454                         if (mono_debugger_handle_exception (&ctx_cp, exc)) {
455                                 restore_context (&ctx_cp);
456                                 g_assert_not_reached ();
457                         }
458                 }
459         }
460
461         /* adjust eip so that it point into the call instruction */
462         ctx.eip -= 1;
463
464         mono_handle_exception (&ctx, exc, (gpointer)eip, FALSE);
465
466         restore_context (&ctx);
467
468         g_assert_not_reached ();
469 }
470
471 void
472 mono_x86_throw_corlib_exception (mgreg_t *regs, guint32 ex_token_index, 
473                                                                  mgreg_t eip, gint32 pc_offset)
474 {
475         guint32 ex_token = MONO_TOKEN_TYPE_DEF | ex_token_index;
476         MonoException *ex;
477
478         ex = mono_exception_from_token (mono_defaults.exception_class->image, ex_token);
479
480         eip -= pc_offset;
481
482         /* Negate the ip adjustment done in mono_x86_throw_exception () */
483         eip += 1;
484
485         mono_x86_throw_exception (regs, (MonoObject*)ex, eip, FALSE);
486 }
487
488 static void
489 mono_x86_resume_unwind (mgreg_t *regs, MonoObject *exc, 
490                                                 mgreg_t eip, gboolean rethrow)
491 {
492         MonoContext ctx;
493
494         ctx.esp = regs [X86_ESP];
495         ctx.eip = eip;
496         ctx.ebp = regs [X86_EBP];
497         ctx.edi = regs [X86_EDI];
498         ctx.esi = regs [X86_ESI];
499         ctx.ebx = regs [X86_EBX];
500         ctx.edx = regs [X86_EDX];
501         ctx.ecx = regs [X86_ECX];
502         ctx.eax = regs [X86_EAX];
503
504         mono_resume_unwind (&ctx);
505 }
506
507 /*
508  * get_throw_trampoline:
509  *
510  *  Generate a call to mono_x86_throw_exception/
511  * mono_x86_throw_corlib_exception.
512  * If LLVM is true, generate code which assumes the caller is LLVM generated code, 
513  * which doesn't push the arguments.
514  */
515 static guint8*
516 get_throw_trampoline (const char *name, gboolean rethrow, gboolean llvm, gboolean corlib, gboolean llvm_abs, gboolean resume_unwind, MonoTrampInfo **info, gboolean aot)
517 {
518         guint8 *start, *code;
519         int i, stack_size, stack_offset, arg_offsets [5], regs_offset;
520         MonoJumpInfo *ji = NULL;
521         GSList *unwind_ops = NULL;
522         guint kMaxCodeSize = NACL_SIZE (128, 256);
523
524         start = code = mono_global_codeman_reserve (kMaxCodeSize);
525
526         stack_size = 128;
527
528         /* 
529          * On apple, the stack is misaligned by the pushing of the return address.
530          */
531         if (!llvm && corlib)
532                 /* On OSX, we don't generate alignment code to save space */
533                 stack_size += 4;
534         else
535                 stack_size += MONO_ARCH_FRAME_ALIGNMENT - 4;
536
537         /*
538          * The stack looks like this:
539          * <pc offset> (only if corlib is TRUE)
540          * <exception object>/<type token>
541          * <return addr> <- esp (unaligned on apple)
542          */
543
544         mono_add_unwind_op_def_cfa (unwind_ops, (guint8*)NULL, (guint8*)NULL, X86_ESP, 4);
545         mono_add_unwind_op_offset (unwind_ops, (guint8*)NULL, (guint8*)NULL, X86_NREG, -4);
546
547         /* Alloc frame */
548         x86_alu_reg_imm (code, X86_SUB, X86_ESP, stack_size);
549         mono_add_unwind_op_def_cfa_offset (unwind_ops, code, start, stack_size + 4);
550
551         arg_offsets [0] = 0;
552         arg_offsets [1] = 4;
553         arg_offsets [2] = 8;
554         arg_offsets [3] = 12;
555         regs_offset = 16;
556
557         /* Save registers */
558         for (i = 0; i < X86_NREG; ++i)
559                 if (i != X86_ESP)
560                         x86_mov_membase_reg (code, X86_ESP, regs_offset + (i * 4), i, 4);
561         /* Calculate the offset between the current sp and the sp of the caller */
562         if (llvm) {
563                 /* LLVM doesn't push the arguments */
564                 stack_offset = stack_size + 4;
565         } else {
566                 if (corlib) {
567                         /* Two arguments */
568                         stack_offset = stack_size + 4 + 8;
569 #ifdef __APPLE__
570                         /* We don't generate stack alignment code on osx to save space */
571 #endif
572                 } else {
573                         /* One argument + stack alignment */
574                         stack_offset = stack_size + 4 + 4;
575 #ifdef __APPLE__
576                         /* Pop the alignment added by OP_THROW too */
577                         stack_offset += MONO_ARCH_FRAME_ALIGNMENT - 4;
578 #else
579                         if (mono_do_x86_stack_align)
580                                 stack_offset += MONO_ARCH_FRAME_ALIGNMENT - 4;
581 #endif
582                 }
583         }
584         /* Save ESP */
585         x86_lea_membase (code, X86_EAX, X86_ESP, stack_offset);
586         x86_mov_membase_reg (code, X86_ESP, regs_offset + (X86_ESP * 4), X86_EAX, 4);
587
588         /* Set arg1 == regs */
589         x86_lea_membase (code, X86_EAX, X86_ESP, regs_offset);
590         x86_mov_membase_reg (code, X86_ESP, arg_offsets [0], X86_EAX, 4);
591         /* Set arg2 == exc/ex_token_index */
592         if (resume_unwind)
593                 x86_mov_reg_imm (code, X86_EAX, 0);
594         else
595                 x86_mov_reg_membase (code, X86_EAX, X86_ESP, stack_size + 4, 4);
596         x86_mov_membase_reg (code, X86_ESP, arg_offsets [1], X86_EAX, 4);
597         /* Set arg3 == eip */
598         if (llvm_abs)
599                 x86_alu_reg_reg (code, X86_XOR, X86_EAX, X86_EAX);
600         else
601                 x86_mov_reg_membase (code, X86_EAX, X86_ESP, stack_size, 4);
602         x86_mov_membase_reg (code, X86_ESP, arg_offsets [2], X86_EAX, 4);
603         /* Set arg4 == rethrow/pc_offset */
604         if (resume_unwind) {
605                 x86_mov_membase_imm (code, X86_ESP, arg_offsets [3], 0, 4);
606         } else if (corlib) {
607                 x86_mov_reg_membase (code, X86_EAX, X86_ESP, stack_size + 8, 4);
608                 if (llvm_abs) {
609                         /* 
610                          * The caller is LLVM code which passes the absolute address not a pc offset,
611                          * so compensate by passing 0 as 'ip' and passing the negated abs address as
612                          * the pc offset.
613                          */
614                         x86_neg_reg (code, X86_EAX);
615                 }
616                 x86_mov_membase_reg (code, X86_ESP, arg_offsets [3], X86_EAX, 4);
617         } else {
618                 x86_mov_membase_imm (code, X86_ESP, arg_offsets [3], rethrow, 4);
619         }
620         /* Make the call */
621         if (aot) {
622                 // This can be called from runtime code, which can't guarantee that
623                 // ebx contains the got address.
624                 // So emit the got address loading code too
625                 code = mono_arch_emit_load_got_addr (start, code, NULL, &ji);
626                 code = mono_arch_emit_load_aotconst (start, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, corlib ? "mono_x86_throw_corlib_exception" : "mono_x86_throw_exception");
627                 x86_call_reg (code, X86_EAX);
628         } else {
629                 x86_call_code (code, resume_unwind ? (mono_x86_resume_unwind) : (corlib ? (gpointer)mono_x86_throw_corlib_exception : (gpointer)mono_x86_throw_exception));
630         }
631         x86_breakpoint (code);
632
633 #if defined(__native_client_codegen__) && defined(__native_client__)
634         nacl_global_codeman_validate(&start, kMaxCodeSize, &code);
635 #endif
636
637         g_assert ((code - start) < kMaxCodeSize);
638
639         if (info)
640                 *info = mono_tramp_info_create (g_strdup (name), start, code - start, ji, unwind_ops);
641         else {
642                 GSList *l;
643
644                 for (l = unwind_ops; l; l = l->next)
645                         g_free (l->data);
646                 g_slist_free (unwind_ops);
647         }
648
649         return start;
650 }
651
652 /**
653  * mono_arch_get_throw_exception:
654  *
655  * Returns a function pointer which can be used to raise 
656  * exceptions. The returned function has the following 
657  * signature: void (*func) (MonoException *exc); 
658  * For example to raise an arithmetic exception you can use:
659  *
660  * x86_push_imm (code, mono_get_exception_arithmetic ()); 
661  * x86_call_code (code, arch_get_throw_exception ()); 
662  *
663  */
664 gpointer 
665 mono_arch_get_throw_exception (MonoTrampInfo **info, gboolean aot)
666 {
667         return get_throw_trampoline ("throw_exception", FALSE, FALSE, FALSE, FALSE, FALSE, info, aot);
668 }
669
670 gpointer 
671 mono_arch_get_rethrow_exception (MonoTrampInfo **info, gboolean aot)
672 {
673         return get_throw_trampoline ("rethrow_exception", TRUE, FALSE, FALSE, FALSE, FALSE, info, aot);
674 }
675
676 /**
677  * mono_arch_get_throw_corlib_exception:
678  *
679  * Returns a function pointer which can be used to raise 
680  * corlib exceptions. The returned function has the following 
681  * signature: void (*func) (guint32 ex_token, guint32 offset); 
682  * Here, offset is the offset which needs to be substracted from the caller IP 
683  * to get the IP of the throw. Passing the offset has the advantage that it 
684  * needs no relocations in the caller.
685  */
686 gpointer 
687 mono_arch_get_throw_corlib_exception (MonoTrampInfo **info, gboolean aot)
688 {
689         return get_throw_trampoline ("throw_corlib_exception", FALSE, FALSE, TRUE, FALSE, FALSE, info, aot);
690 }
691
692 void
693 mono_arch_exceptions_init (void)
694 {
695         guint8 *tramp;
696
697 /* 
698  * If we're running WoW64, we need to set the usermode exception policy 
699  * for SEHs to behave. This requires hotfix http://support.microsoft.com/kb/976038
700  * or (eventually) Windows 7 SP1.
701  */
702 #ifdef HOST_WIN32
703         DWORD flags;
704         FARPROC getter;
705         FARPROC setter;
706         HMODULE kernel32 = LoadLibraryW (L"kernel32.dll");
707
708         if (kernel32) {
709                 getter = GetProcAddress (kernel32, "GetProcessUserModeExceptionPolicy");
710                 setter = GetProcAddress (kernel32, "SetProcessUserModeExceptionPolicy");
711                 if (getter && setter) {
712                         if (getter (&flags))
713                                 setter (flags & ~PROCESS_CALLBACK_FILTER_ENABLED);
714                 }
715         }
716 #endif
717
718         if (mono_aot_only) {
719                 signal_exception_trampoline = mono_aot_get_trampoline ("x86_signal_exception_trampoline");
720                 return;
721         }
722
723         /* LLVM needs different throw trampolines */
724         tramp = get_throw_trampoline ("llvm_throw_exception_trampoline", FALSE, TRUE, FALSE, FALSE, FALSE, NULL, FALSE);
725         mono_register_jit_icall (tramp, "llvm_throw_exception_trampoline", NULL, TRUE);
726
727         tramp = get_throw_trampoline ("llvm_rethrow_exception_trampoline", FALSE, TRUE, FALSE, FALSE, FALSE, NULL, FALSE);
728         mono_register_jit_icall (tramp, "llvm_rethrow_exception_trampoline", NULL, TRUE);
729
730         tramp = get_throw_trampoline ("llvm_throw_corlib_exception_trampoline", FALSE, TRUE, TRUE, FALSE, FALSE, NULL, FALSE);
731         mono_register_jit_icall (tramp, "llvm_throw_corlib_exception_trampoline", NULL, TRUE);
732
733         tramp = get_throw_trampoline ("llvm_throw_corlib_exception_abs_trampoline", FALSE, TRUE, TRUE, TRUE, FALSE, NULL, FALSE);
734         mono_register_jit_icall (tramp, "llvm_throw_corlib_exception_abs_trampoline", NULL, TRUE);
735
736         tramp = get_throw_trampoline ("llvm_resume_unwind_trampoline", FALSE, FALSE, FALSE, FALSE, TRUE, NULL, FALSE);
737         mono_register_jit_icall (tramp, "llvm_resume_unwind_trampoline", NULL, TRUE);
738
739         signal_exception_trampoline = mono_x86_get_signal_exception_trampoline (NULL, FALSE);
740 }
741
742 /*
743  * mono_arch_find_jit_info:
744  *
745  * See exceptions-amd64.c for docs.
746  */
747 gboolean
748 mono_arch_find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls, 
749                                                          MonoJitInfo *ji, MonoContext *ctx, 
750                                                          MonoContext *new_ctx, MonoLMF **lmf, 
751                                                          StackFrameInfo *frame)
752 {
753         gpointer ip = MONO_CONTEXT_GET_IP (ctx);
754
755         memset (frame, 0, sizeof (StackFrameInfo));
756         frame->ji = ji;
757         frame->managed = FALSE;
758
759         *new_ctx = *ctx;
760
761         if (ji != NULL) {
762                 gssize regs [MONO_MAX_IREGS + 1];
763                 guint8 *cfa;
764                 guint32 unwind_info_len;
765                 guint8 *unwind_info;
766
767                 frame->type = FRAME_TYPE_MANAGED;
768
769                 if (!ji->method->wrapper_type || ji->method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
770                         frame->managed = TRUE;
771
772                 if (ji->from_aot)
773                         unwind_info = mono_aot_get_unwind_info (ji, &unwind_info_len);
774                 else
775                         unwind_info = mono_get_cached_unwind_info (ji->used_regs, &unwind_info_len);
776
777                 regs [X86_EAX] = new_ctx->eax;
778                 regs [X86_EBX] = new_ctx->ebx;
779                 regs [X86_ECX] = new_ctx->ecx;
780                 regs [X86_EDX] = new_ctx->edx;
781                 regs [X86_ESP] = new_ctx->esp;
782                 regs [X86_EBP] = new_ctx->ebp;
783                 regs [X86_ESI] = new_ctx->esi;
784                 regs [X86_EDI] = new_ctx->edi;
785                 regs [X86_NREG] = new_ctx->eip;
786
787                 mono_unwind_frame (unwind_info, unwind_info_len, ji->code_start, 
788                                                    (guint8*)ji->code_start + ji->code_size,
789                                                    ip, regs, MONO_MAX_IREGS + 1, &cfa);
790
791                 new_ctx->eax = regs [X86_EAX];
792                 new_ctx->ebx = regs [X86_EBX];
793                 new_ctx->ecx = regs [X86_ECX];
794                 new_ctx->edx = regs [X86_EDX];
795                 new_ctx->esp = regs [X86_ESP];
796                 new_ctx->ebp = regs [X86_EBP];
797                 new_ctx->esi = regs [X86_ESI];
798                 new_ctx->edi = regs [X86_EDI];
799                 new_ctx->eip = regs [X86_NREG];
800
801                 /* The CFA becomes the new SP value */
802                 new_ctx->esp = (gssize)cfa;
803
804                 /* Adjust IP */
805                 new_ctx->eip --;
806
807                 if (*lmf && (MONO_CONTEXT_GET_BP (ctx) >= (gpointer)(*lmf)->ebp)) {
808                         /* remove any unused lmf */
809                         *lmf = (gpointer)(((gsize)(*lmf)->previous_lmf) & ~3);
810                 }
811
812                 /* Pop arguments off the stack */
813                 /* 
814                  * FIXME: LLVM doesn't push these, we can't use ji->from_llvm as it describes
815                  * the caller.
816                  */
817 #ifndef ENABLE_LLVM
818                 {
819                         MonoJitArgumentInfo *arg_info = g_newa (MonoJitArgumentInfo, mono_method_signature (ji->method)->param_count + 1);
820
821                         guint32 stack_to_pop = mono_arch_get_argument_info (mono_method_signature (ji->method), mono_method_signature (ji->method)->param_count, arg_info);
822                         new_ctx->esp += stack_to_pop;
823                 }
824 #endif
825
826                 return TRUE;
827         } else if (*lmf) {
828
829                 if (((guint64)(*lmf)->previous_lmf) & 2) {
830                         /* 
831                          * This LMF entry is created by the soft debug code to mark transitions to
832                          * managed code done during invokes.
833                          */
834                         MonoLMFExt *ext = (MonoLMFExt*)(*lmf);
835
836                         g_assert (ext->debugger_invoke);
837
838                         memcpy (new_ctx, &ext->ctx, sizeof (MonoContext));
839
840                         *lmf = (gpointer)(((gsize)(*lmf)->previous_lmf) & ~3);
841
842                         frame->type = FRAME_TYPE_DEBUGGER_INVOKE;
843
844                         return TRUE;
845                 }
846                 
847                 if ((ji = mini_jit_info_table_find (domain, (gpointer)(*lmf)->eip, NULL))) {
848                 } else {
849                         if (!((guint32)((*lmf)->previous_lmf) & 1))
850                                 /* Top LMF entry */
851                                 return FALSE;
852                         g_assert_not_reached ();
853                         /* Trampoline lmf frame */
854                         frame->method = (*lmf)->method;
855                 }
856
857                 new_ctx->esi = (*lmf)->esi;
858                 new_ctx->edi = (*lmf)->edi;
859                 new_ctx->ebx = (*lmf)->ebx;
860                 new_ctx->ebp = (*lmf)->ebp;
861                 new_ctx->eip = (*lmf)->eip;
862
863                 /* Adjust IP */
864                 new_ctx->eip --;
865
866                 frame->ji = ji;
867                 frame->type = FRAME_TYPE_MANAGED_TO_NATIVE;
868
869                 /* Check if we are in a trampoline LMF frame */
870                 if ((guint32)((*lmf)->previous_lmf) & 1) {
871                         /* lmf->esp is set by the trampoline code */
872                         new_ctx->esp = (*lmf)->esp;
873
874                         /* Pop arguments off the stack */
875                         /* FIXME: Handle the delegate case too ((*lmf)->method == NULL) */
876                         /* FIXME: Handle the IMT/vtable case too */
877 #ifndef ENABLE_LLVM
878                         if ((*lmf)->method) {
879                                 MonoMethod *method = (*lmf)->method;
880                                 MonoJitArgumentInfo *arg_info = g_newa (MonoJitArgumentInfo, mono_method_signature (method)->param_count + 1);
881
882                                 guint32 stack_to_pop = mono_arch_get_argument_info (mono_method_signature (method), mono_method_signature (method)->param_count, arg_info);
883                                 new_ctx->esp += stack_to_pop;
884                         }
885 #endif
886                 }
887                 else
888                         /* the lmf is always stored on the stack, so the following
889                          * expression points to a stack location which can be used as ESP */
890                         new_ctx->esp = (unsigned long)&((*lmf)->eip);
891
892                 *lmf = (gpointer)(((gsize)(*lmf)->previous_lmf) & ~3);
893
894                 return TRUE;
895         }
896
897         return FALSE;
898 }
899
900 #ifdef __sun
901 #define REG_EAX EAX
902 #define REG_EBX EBX
903 #define REG_ECX ECX
904 #define REG_EDX EDX
905 #define REG_EBP EBP
906 #define REG_ESP ESP
907 #define REG_ESI ESI
908 #define REG_EDI EDI
909 #define REG_EIP EIP
910 #endif
911
912 void
913 mono_arch_sigctx_to_monoctx (void *sigctx, MonoContext *mctx)
914 {
915 #if defined (__native_client__)
916         printf("WARNING: mono_arch_sigctx_to_monoctx() called!\n");
917         mctx->eax = 0xDEADBEEF;
918         mctx->ebx = 0xDEADBEEF;
919         mctx->ecx = 0xDEADBEEF;
920         mctx->edx = 0xDEADBEEF;
921         mctx->ebp = 0xDEADBEEF;
922         mctx->esp = 0xDEADBEEF;
923         mctx->esi = 0xDEADBEEF;
924         mctx->edi = 0xDEADBEEF;
925         mctx->eip = 0xDEADBEEF;
926 #else
927 #ifdef MONO_ARCH_USE_SIGACTION
928         ucontext_t *ctx = (ucontext_t*)sigctx;
929         
930         mctx->eax = UCONTEXT_REG_EAX (ctx);
931         mctx->ebx = UCONTEXT_REG_EBX (ctx);
932         mctx->ecx = UCONTEXT_REG_ECX (ctx);
933         mctx->edx = UCONTEXT_REG_EDX (ctx);
934         mctx->ebp = UCONTEXT_REG_EBP (ctx);
935         mctx->esp = UCONTEXT_REG_ESP (ctx);
936         mctx->esi = UCONTEXT_REG_ESI (ctx);
937         mctx->edi = UCONTEXT_REG_EDI (ctx);
938         mctx->eip = UCONTEXT_REG_EIP (ctx);
939 #else   
940         struct sigcontext *ctx = (struct sigcontext *)sigctx;
941
942         mctx->eax = ctx->SC_EAX;
943         mctx->ebx = ctx->SC_EBX;
944         mctx->ecx = ctx->SC_ECX;
945         mctx->edx = ctx->SC_EDX;
946         mctx->ebp = ctx->SC_EBP;
947         mctx->esp = ctx->SC_ESP;
948         mctx->esi = ctx->SC_ESI;
949         mctx->edi = ctx->SC_EDI;
950         mctx->eip = ctx->SC_EIP;
951 #endif
952 #endif /* if defined(__native_client__) */
953 }
954
955 void
956 mono_arch_monoctx_to_sigctx (MonoContext *mctx, void *sigctx)
957 {
958 #if defined(__native_client__)
959         printf("WARNING: mono_arch_monoctx_to_sigctx() called!\n");
960 #else
961 #ifdef MONO_ARCH_USE_SIGACTION
962         ucontext_t *ctx = (ucontext_t*)sigctx;
963
964         UCONTEXT_REG_EAX (ctx) = mctx->eax;
965         UCONTEXT_REG_EBX (ctx) = mctx->ebx;
966         UCONTEXT_REG_ECX (ctx) = mctx->ecx;
967         UCONTEXT_REG_EDX (ctx) = mctx->edx;
968         UCONTEXT_REG_EBP (ctx) = mctx->ebp;
969         UCONTEXT_REG_ESP (ctx) = mctx->esp;
970         UCONTEXT_REG_ESI (ctx) = mctx->esi;
971         UCONTEXT_REG_EDI (ctx) = mctx->edi;
972         UCONTEXT_REG_EIP (ctx) = mctx->eip;
973 #else
974         struct sigcontext *ctx = (struct sigcontext *)sigctx;
975
976         ctx->SC_EAX = mctx->eax;
977         ctx->SC_EBX = mctx->ebx;
978         ctx->SC_ECX = mctx->ecx;
979         ctx->SC_EDX = mctx->edx;
980         ctx->SC_EBP = mctx->ebp;
981         ctx->SC_ESP = mctx->esp;
982         ctx->SC_ESI = mctx->esi;
983         ctx->SC_EDI = mctx->edi;
984         ctx->SC_EIP = mctx->eip;
985 #endif
986 #endif /* __native_client__ */
987 }       
988
989 gpointer
990 mono_arch_ip_from_context (void *sigctx)
991 {
992 #if defined(__native_client__)
993         printf("WARNING: mono_arch_ip_from_context() called!\n");
994         return (NULL);
995 #else
996 #ifdef MONO_ARCH_USE_SIGACTION
997         ucontext_t *ctx = (ucontext_t*)sigctx;
998         return (gpointer)UCONTEXT_REG_EIP (ctx);
999 #else
1000         struct sigcontext *ctx = sigctx;
1001         return (gpointer)ctx->SC_EIP;
1002 #endif
1003 #endif  /* __native_client__ */
1004 }
1005
1006 /*
1007  * handle_exception:
1008  *
1009  *   Called by resuming from a signal handler.
1010  */
1011 static void
1012 handle_signal_exception (gpointer obj)
1013 {
1014         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
1015         MonoContext ctx;
1016         static void (*restore_context) (MonoContext *);
1017
1018         if (!restore_context)
1019                 restore_context = mono_get_restore_context ();
1020
1021         memcpy (&ctx, &jit_tls->ex_ctx, sizeof (MonoContext));
1022
1023         if (mono_debugger_handle_exception (&ctx, (MonoObject *)obj))
1024                 return;
1025
1026         mono_handle_exception (&ctx, obj, MONO_CONTEXT_GET_IP (&ctx), FALSE);
1027
1028         restore_context (&ctx);
1029 }
1030
1031 /*
1032  * mono_x86_get_signal_exception_trampoline:
1033  *
1034  *   This x86 specific trampoline is used to call handle_signal_exception.
1035  */
1036 gpointer
1037 mono_x86_get_signal_exception_trampoline (MonoTrampInfo **info, gboolean aot)
1038 {
1039         guint8 *start, *code;
1040         MonoJumpInfo *ji = NULL;
1041         GSList *unwind_ops = NULL;
1042         int stack_size;
1043
1044         start = code = mono_global_codeman_reserve (128);
1045
1046         /* Caller ip */
1047         x86_push_reg (code, X86_ECX);
1048
1049         mono_add_unwind_op_def_cfa (unwind_ops, (guint8*)NULL, (guint8*)NULL, X86_ESP, 4);
1050         mono_add_unwind_op_offset (unwind_ops, (guint8*)NULL, (guint8*)NULL, X86_NREG, -4);
1051
1052         /* Fix the alignment to be what apple expects */
1053         stack_size = 12;
1054
1055         x86_alu_reg_imm (code, X86_SUB, X86_ESP, stack_size);
1056         mono_add_unwind_op_def_cfa_offset (unwind_ops, code, start, stack_size + 4);
1057
1058         /* Arg1 */
1059         x86_mov_membase_reg (code, X86_ESP, 0, X86_EAX, 4);
1060         /* Branch to target */
1061         x86_call_reg (code, X86_EDX);
1062
1063         g_assert ((code - start) < 128);
1064
1065         if (info)
1066                 *info = mono_tramp_info_create (g_strdup ("x86_signal_exception_trampoline"), start, code - start, ji, unwind_ops);
1067         else {
1068                 GSList *l;
1069
1070                 for (l = unwind_ops; l; l = l->next)
1071                         g_free (l->data);
1072                 g_slist_free (unwind_ops);
1073         }
1074
1075         return start;
1076 }
1077
1078 gboolean
1079 mono_arch_handle_exception (void *sigctx, gpointer obj, gboolean test_only)
1080 {
1081 #if defined(MONO_ARCH_USE_SIGACTION)
1082         ucontext_t *ctx = (ucontext_t*)sigctx;
1083
1084         /*
1085          * Handling the exception in the signal handler is problematic, since the original
1086          * signal is disabled, and we could run arbitrary code though the debugger. So
1087          * resume into the normal stack and do most work there if possible.
1088          */
1089         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
1090         guint64 sp = UCONTEXT_REG_ESP (ctx);
1091
1092         /* Pass the ctx parameter in TLS */
1093         mono_arch_sigctx_to_monoctx (ctx, &jit_tls->ex_ctx);
1094         /*
1095          * Can't pass the obj on the stack, since we are executing on the
1096          * same stack. Can't save it into MonoJitTlsData, since it needs GC tracking.
1097          * So put it into a register, and branch to a trampoline which
1098          * pushes it.
1099          */
1100         g_assert (!test_only);
1101         UCONTEXT_REG_EAX (ctx) = (gsize)obj;
1102         UCONTEXT_REG_ECX (ctx) = UCONTEXT_REG_EIP (ctx);
1103         UCONTEXT_REG_EDX (ctx) = (gsize)handle_signal_exception;
1104
1105         /* Allocate a stack frame, align it to 16 bytes which is needed on apple */
1106         sp -= 16;
1107         sp &= ~15;
1108         UCONTEXT_REG_ESP (ctx) = sp;
1109
1110         UCONTEXT_REG_EIP (ctx) = (gsize)signal_exception_trampoline;
1111
1112         return TRUE;
1113 #elif defined (TARGET_WIN32)
1114         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
1115         struct sigcontext *ctx = (struct sigcontext *)sigctx;
1116         guint64 sp = ctx->SC_ESP;
1117
1118         mono_arch_sigctx_to_monoctx (sigctx, &jit_tls->ex_ctx);
1119
1120         /*
1121          * Can't pass the obj on the stack, since we are executing on the
1122          * same stack. Can't save it into MonoJitTlsData, since it needs GC tracking.
1123          * So put it into a register, and branch to a trampoline which
1124          * pushes it.
1125          */
1126         g_assert (!test_only);
1127         ctx->SC_EAX = (gsize)obj;
1128         ctx->SC_ECX = ctx->SC_EIP;
1129         ctx->SC_EDX = (gsize)handle_signal_exception;
1130
1131         /* Allocate a stack frame, align it to 16 bytes which is needed on apple */
1132         sp -= 16;
1133         sp &= ~15;
1134         ctx->SC_ESP = sp;
1135
1136         ctx->SC_EIP = (gsize)signal_exception_trampoline;
1137
1138         return TRUE;
1139 #else
1140         MonoContext mctx;
1141
1142         mono_arch_sigctx_to_monoctx (sigctx, &mctx);
1143
1144         if (mono_debugger_handle_exception (&mctx, (MonoObject *)obj))
1145                 return TRUE;
1146
1147         mono_handle_exception (&mctx, obj, (gpointer)mctx.eip, test_only);
1148
1149         mono_arch_monoctx_to_sigctx (&mctx, sigctx);
1150
1151         return TRUE;
1152 #endif
1153 }
1154
1155 static void
1156 restore_soft_guard_pages (void)
1157 {
1158         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
1159         if (jit_tls->stack_ovf_guard_base)
1160                 mono_mprotect (jit_tls->stack_ovf_guard_base, jit_tls->stack_ovf_guard_size, MONO_MMAP_NONE);
1161 }
1162
1163 /* 
1164  * this function modifies mctx so that when it is restored, it
1165  * won't execcute starting at mctx.eip, but in a function that
1166  * will restore the protection on the soft-guard pages and return back to
1167  * continue at mctx.eip.
1168  */
1169 static void
1170 prepare_for_guard_pages (MonoContext *mctx)
1171 {
1172         gpointer *sp;
1173         sp = (gpointer)(mctx->esp);
1174         sp -= 1;
1175         /* the resturn addr */
1176         sp [0] = (gpointer)(mctx->eip);
1177         mctx->eip = (unsigned long)restore_soft_guard_pages;
1178         mctx->esp = (unsigned long)sp;
1179 }
1180
1181 static void
1182 altstack_handle_and_restore (void *sigctx, gpointer obj, gboolean stack_ovf)
1183 {
1184         void (*restore_context) (MonoContext *);
1185         MonoContext mctx;
1186
1187         restore_context = mono_get_restore_context ();
1188         mono_arch_sigctx_to_monoctx (sigctx, &mctx);
1189
1190         if (mono_debugger_handle_exception (&mctx, (MonoObject *)obj)) {
1191                 if (stack_ovf)
1192                         prepare_for_guard_pages (&mctx);
1193                 restore_context (&mctx);
1194         }
1195
1196         mono_handle_exception (&mctx, obj, (gpointer)mctx.eip, FALSE);
1197         if (stack_ovf)
1198                 prepare_for_guard_pages (&mctx);
1199         restore_context (&mctx);
1200 }
1201
1202 void
1203 mono_arch_handle_altstack_exception (void *sigctx, gpointer fault_addr, gboolean stack_ovf)
1204 {
1205 #ifdef MONO_ARCH_USE_SIGACTION
1206         MonoException *exc = NULL;
1207         ucontext_t *ctx = (ucontext_t*)sigctx;
1208         MonoJitInfo *ji = mini_jit_info_table_find (mono_domain_get (), (gpointer)UCONTEXT_REG_EIP (ctx), NULL);
1209         gpointer *sp;
1210         int frame_size;
1211
1212         /* if we didn't find a managed method for the ip address and it matches the fault
1213          * address, we assume we followed a broken pointer during an indirect call, so
1214          * we try the lookup again with the return address pushed on the stack
1215          */
1216         if (!ji && fault_addr == (gpointer)UCONTEXT_REG_EIP (ctx)) {
1217                 glong *sp = (gpointer)UCONTEXT_REG_ESP (ctx);
1218                 ji = mini_jit_info_table_find (mono_domain_get (), (gpointer)sp [0], NULL);
1219                 if (ji)
1220                         UCONTEXT_REG_EIP (ctx) = sp [0];
1221         }
1222         if (stack_ovf)
1223                 exc = mono_domain_get ()->stack_overflow_ex;
1224         if (!ji)
1225                 mono_handle_native_sigsegv (SIGSEGV, sigctx);
1226         /* setup a call frame on the real stack so that control is returned there
1227          * and exception handling can continue.
1228          * If this was a stack overflow the caller already ensured the stack pages
1229          * needed have been unprotected.
1230          * The frame looks like:
1231          *   ucontext struct
1232          *   test_only arg
1233          *   exception arg
1234          *   ctx arg
1235          *   return ip
1236          */
1237         frame_size = sizeof (ucontext_t) + sizeof (gpointer) * 4;
1238         frame_size += 15;
1239         frame_size &= ~15;
1240         sp = (gpointer)(UCONTEXT_REG_ESP (ctx) & ~15);
1241         sp = (gpointer)((char*)sp - frame_size);
1242         /* the incoming arguments are aligned to 16 bytes boundaries, so the return address IP
1243          * goes at sp [-1]
1244          */
1245         sp [-1] = (gpointer)UCONTEXT_REG_EIP (ctx);
1246         sp [0] = sp + 4;
1247         sp [1] = exc;
1248         sp [2] = (gpointer)stack_ovf;
1249         /* may need to adjust pointers in the new struct copy, depending on the OS */
1250         memcpy (sp + 4, ctx, sizeof (ucontext_t));
1251         /* at the return form the signal handler execution starts in altstack_handle_and_restore() */
1252         UCONTEXT_REG_EIP (ctx) = (unsigned long)altstack_handle_and_restore;
1253         UCONTEXT_REG_ESP (ctx) = (unsigned long)(sp - 1);
1254 #endif
1255 }
1256
1257 #if MONO_SUPPORT_TASKLETS
1258 MonoContinuationRestore
1259 mono_tasklets_arch_restore (void)
1260 {
1261         static guint8* saved = NULL;
1262         guint8 *code, *start;
1263
1264 #ifdef __native_client_codegen__
1265         g_print("mono_tasklets_arch_restore needs to be aligned for Native Client\n");
1266 #endif
1267         if (saved)
1268                 return (MonoContinuationRestore)saved;
1269         code = start = mono_global_codeman_reserve (48);
1270         /* the signature is: restore (MonoContinuation *cont, int state, MonoLMF **lmf_addr) */
1271         /* put cont in edx */
1272         x86_mov_reg_membase (code, X86_EDX, X86_ESP, 4, 4);
1273         /* setup the copy of the stack */
1274         x86_mov_reg_membase (code, X86_ECX, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, stack_used_size), 4);
1275         x86_shift_reg_imm (code, X86_SHR, X86_ECX, 2);
1276         x86_cld (code);
1277         x86_mov_reg_membase (code, X86_ESI, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, saved_stack), 4);
1278         x86_mov_reg_membase (code, X86_EDI, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, return_sp), 4);
1279         x86_prefix (code, X86_REP_PREFIX);
1280         x86_movsl (code);
1281
1282         /* now restore the registers from the LMF */
1283         x86_mov_reg_membase (code, X86_ECX, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, lmf), 4);
1284         x86_mov_reg_membase (code, X86_EBX, X86_ECX, G_STRUCT_OFFSET (MonoLMF, ebx), 4);
1285         x86_mov_reg_membase (code, X86_EBP, X86_ECX, G_STRUCT_OFFSET (MonoLMF, ebp), 4);
1286         x86_mov_reg_membase (code, X86_ESI, X86_ECX, G_STRUCT_OFFSET (MonoLMF, esi), 4);
1287         x86_mov_reg_membase (code, X86_EDI, X86_ECX, G_STRUCT_OFFSET (MonoLMF, edi), 4);
1288
1289         /* restore the lmf chain */
1290         /*x86_mov_reg_membase (code, X86_ECX, X86_ESP, 12, 4);
1291         x86_mov_membase_reg (code, X86_ECX, 0, X86_EDX, 4);*/
1292
1293         /* state in eax, so it's setup as the return value */
1294         x86_mov_reg_membase (code, X86_EAX, X86_ESP, 8, 4);
1295         x86_jump_membase (code, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, return_ip));
1296         g_assert ((code - start) <= 48);
1297         saved = start;
1298         return (MonoContinuationRestore)saved;
1299 }
1300 #endif
1301