Merge branch 'master' of github.com:mono/mono
[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, NULL, &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         nacl_global_codeman_validate(&start, 128, &code);
312
313         if (info)
314                 *info = mono_tramp_info_create (g_strdup_printf ("restore_context"), start, code - start, ji, unwind_ops);
315         else {
316                 GSList *l;
317
318                 for (l = unwind_ops; l; l = l->next)
319                         g_free (l->data);
320                 g_slist_free (unwind_ops);
321         }
322
323         return start;
324 }
325
326 /*
327  * mono_arch_get_call_filter:
328  *
329  * Returns a pointer to a method which calls an exception filter. We
330  * also use this function to call finally handlers (we pass NULL as 
331  * @exc object in this case).
332  */
333 gpointer
334 mono_arch_get_call_filter (MonoTrampInfo **info, gboolean aot)
335 {
336         guint8* start;
337         guint8 *code;
338         MonoJumpInfo *ji = NULL;
339         GSList *unwind_ops = NULL;
340         guint kMaxCodeSize = NACL_SIZE (64, 128);
341
342         /* call_filter (MonoContext *ctx, unsigned long eip) */
343         start = code = mono_global_codeman_reserve (kMaxCodeSize);
344
345         x86_push_reg (code, X86_EBP);
346         x86_mov_reg_reg (code, X86_EBP, X86_ESP, 4);
347         x86_push_reg (code, X86_EBX);
348         x86_push_reg (code, X86_EDI);
349         x86_push_reg (code, X86_ESI);
350
351         /* load ctx */
352         x86_mov_reg_membase (code, X86_EAX, X86_EBP, 8, 4);
353         /* load eip */
354         x86_mov_reg_membase (code, X86_ECX, X86_EBP, 12, 4);
355         /* save EBP */
356         x86_push_reg (code, X86_EBP);
357
358         /* set new EBP */
359         x86_mov_reg_membase (code, X86_EBP, X86_EAX,  G_STRUCT_OFFSET (MonoContext, ebp), 4);
360         /* restore registers used by global register allocation (EBX & ESI) */
361         x86_mov_reg_membase (code, X86_EBX, X86_EAX,  G_STRUCT_OFFSET (MonoContext, ebx), 4);
362         x86_mov_reg_membase (code, X86_ESI, X86_EAX,  G_STRUCT_OFFSET (MonoContext, esi), 4);
363         x86_mov_reg_membase (code, X86_EDI, X86_EAX,  G_STRUCT_OFFSET (MonoContext, edi), 4);
364
365         /* align stack and save ESP */
366         x86_mov_reg_reg (code, X86_EDX, X86_ESP, 4);
367         x86_alu_reg_imm (code, X86_AND, X86_ESP, -MONO_ARCH_FRAME_ALIGNMENT);
368         g_assert (MONO_ARCH_FRAME_ALIGNMENT >= 8);
369         x86_alu_reg_imm (code, X86_SUB, X86_ESP, MONO_ARCH_FRAME_ALIGNMENT - 8);
370         x86_push_reg (code, X86_EDX);
371
372         /* call the handler */
373         x86_call_reg (code, X86_ECX);
374
375         /* restore ESP */
376         x86_pop_reg (code, X86_ESP);
377
378         /* restore EBP */
379         x86_pop_reg (code, X86_EBP);
380
381         /* restore saved regs */
382         x86_pop_reg (code, X86_ESI);
383         x86_pop_reg (code, X86_EDI);
384         x86_pop_reg (code, X86_EBX);
385         x86_leave (code);
386         x86_ret (code);
387
388         nacl_global_codeman_validate(&start, kMaxCodeSize, &code);
389
390         if (info)
391                 *info = mono_tramp_info_create (g_strdup_printf ("call_filter"), start, code - start, ji, unwind_ops);
392         else {
393                 GSList *l;
394
395                 for (l = unwind_ops; l; l = l->next)
396                         g_free (l->data);
397                 g_slist_free (unwind_ops);
398         }
399
400         g_assert ((code - start) < kMaxCodeSize);
401         return start;
402 }
403
404 /*
405  * mono_x86_throw_exception:
406  *
407  *   C function called from the throw trampolines.
408  */
409 void
410 mono_x86_throw_exception (mgreg_t *regs, MonoObject *exc, 
411                                                   mgreg_t eip, gboolean rethrow)
412 {
413         static void (*restore_context) (MonoContext *);
414         MonoContext ctx;
415
416         if (!restore_context)
417                 restore_context = mono_get_restore_context ();
418
419         ctx.esp = regs [X86_ESP];
420         ctx.eip = eip;
421         ctx.ebp = regs [X86_EBP];
422         ctx.edi = regs [X86_EDI];
423         ctx.esi = regs [X86_ESI];
424         ctx.ebx = regs [X86_EBX];
425         ctx.edx = regs [X86_EDX];
426         ctx.ecx = regs [X86_ECX];
427         ctx.eax = regs [X86_EAX];
428
429 #ifdef __APPLE__
430         /* The OSX ABI specifies 16 byte alignment at call sites */
431         g_assert ((ctx.esp % MONO_ARCH_FRAME_ALIGNMENT) == 0);
432 #endif
433
434         if (mono_object_isinst (exc, mono_defaults.exception_class)) {
435                 MonoException *mono_ex = (MonoException*)exc;
436                 if (!rethrow)
437                         mono_ex->stack_trace = NULL;
438         }
439
440         if (mono_debug_using_mono_debugger ()) {
441                 guint8 buf [16], *code;
442
443                 mono_breakpoint_clean_code (NULL, (gpointer)eip, 8, buf, sizeof (buf));
444                 code = buf + 8;
445
446                 if (buf [3] == 0xe8) {
447                         MonoContext ctx_cp = ctx;
448                         ctx_cp.eip = eip - 5;
449
450                         if (mono_debugger_handle_exception (&ctx_cp, exc)) {
451                                 restore_context (&ctx_cp);
452                                 g_assert_not_reached ();
453                         }
454                 }
455         }
456
457         /* adjust eip so that it point into the call instruction */
458         ctx.eip -= 1;
459
460         mono_handle_exception (&ctx, exc, (gpointer)eip, FALSE);
461
462         restore_context (&ctx);
463
464         g_assert_not_reached ();
465 }
466
467 void
468 mono_x86_throw_corlib_exception (mgreg_t *regs, guint32 ex_token_index, 
469                                                                  mgreg_t eip, gint32 pc_offset)
470 {
471         guint32 ex_token = MONO_TOKEN_TYPE_DEF | ex_token_index;
472         MonoException *ex;
473
474         ex = mono_exception_from_token (mono_defaults.exception_class->image, ex_token);
475
476         eip -= pc_offset;
477
478         /* Negate the ip adjustment done in mono_x86_throw_exception () */
479         eip += 1;
480
481         mono_x86_throw_exception (regs, (MonoObject*)ex, eip, FALSE);
482 }
483
484 static void
485 mono_x86_resume_unwind (mgreg_t *regs, MonoObject *exc, 
486                                                 mgreg_t eip, gboolean rethrow)
487 {
488         MonoContext ctx;
489
490         ctx.esp = regs [X86_ESP];
491         ctx.eip = eip;
492         ctx.ebp = regs [X86_EBP];
493         ctx.edi = regs [X86_EDI];
494         ctx.esi = regs [X86_ESI];
495         ctx.ebx = regs [X86_EBX];
496         ctx.edx = regs [X86_EDX];
497         ctx.ecx = regs [X86_ECX];
498         ctx.eax = regs [X86_EAX];
499
500         mono_resume_unwind (&ctx);
501 }
502
503 /*
504  * get_throw_trampoline:
505  *
506  *  Generate a call to mono_x86_throw_exception/
507  * mono_x86_throw_corlib_exception.
508  * If LLVM is true, generate code which assumes the caller is LLVM generated code, 
509  * which doesn't push the arguments.
510  */
511 static guint8*
512 get_throw_trampoline (const char *name, gboolean rethrow, gboolean llvm, gboolean corlib, gboolean llvm_abs, gboolean resume_unwind, MonoTrampInfo **info, gboolean aot)
513 {
514         guint8 *start, *code;
515         int i, stack_size, stack_offset, arg_offsets [5], regs_offset;
516         MonoJumpInfo *ji = NULL;
517         GSList *unwind_ops = NULL;
518         guint kMaxCodeSize = NACL_SIZE (128, 256);
519
520         start = code = mono_global_codeman_reserve (kMaxCodeSize);
521
522         stack_size = 128;
523
524         /* 
525          * On apple, the stack is misaligned by the pushing of the return address.
526          */
527         if (!llvm && corlib)
528                 /* On OSX, we don't generate alignment code to save space */
529                 stack_size += 4;
530         else
531                 stack_size += MONO_ARCH_FRAME_ALIGNMENT - 4;
532
533         /*
534          * The stack looks like this:
535          * <pc offset> (only if corlib is TRUE)
536          * <exception object>/<type token>
537          * <return addr> <- esp (unaligned on apple)
538          */
539
540         mono_add_unwind_op_def_cfa (unwind_ops, (guint8*)NULL, (guint8*)NULL, X86_ESP, 4);
541         mono_add_unwind_op_offset (unwind_ops, (guint8*)NULL, (guint8*)NULL, X86_NREG, -4);
542
543         /* Alloc frame */
544         x86_alu_reg_imm (code, X86_SUB, X86_ESP, stack_size);
545         mono_add_unwind_op_def_cfa_offset (unwind_ops, code, start, stack_size + 4);
546
547         arg_offsets [0] = 0;
548         arg_offsets [1] = 4;
549         arg_offsets [2] = 8;
550         arg_offsets [3] = 12;
551         regs_offset = 16;
552
553         /* Save registers */
554         for (i = 0; i < X86_NREG; ++i)
555                 if (i != X86_ESP)
556                         x86_mov_membase_reg (code, X86_ESP, regs_offset + (i * 4), i, 4);
557         /* Calculate the offset between the current sp and the sp of the caller */
558         if (llvm) {
559                 /* LLVM doesn't push the arguments */
560                 stack_offset = stack_size + 4;
561         } else {
562                 if (corlib) {
563                         /* Two arguments */
564                         stack_offset = stack_size + 4 + 8;
565 #ifdef __APPLE__
566                         /* We don't generate stack alignment code on osx to save space */
567 #endif
568                 } else {
569                         /* One argument + stack alignment */
570                         stack_offset = stack_size + 4 + 4;
571 #ifdef __APPLE__
572                         /* Pop the alignment added by OP_THROW too */
573                         stack_offset += MONO_ARCH_FRAME_ALIGNMENT - 4;
574 #else
575                         if (mono_do_x86_stack_align)
576                                 stack_offset += MONO_ARCH_FRAME_ALIGNMENT - 4;
577 #endif
578                 }
579         }
580         /* Save ESP */
581         x86_lea_membase (code, X86_EAX, X86_ESP, stack_offset);
582         x86_mov_membase_reg (code, X86_ESP, regs_offset + (X86_ESP * 4), X86_EAX, 4);
583
584         /* Set arg1 == regs */
585         x86_lea_membase (code, X86_EAX, X86_ESP, regs_offset);
586         x86_mov_membase_reg (code, X86_ESP, arg_offsets [0], X86_EAX, 4);
587         /* Set arg2 == exc/ex_token_index */
588         if (resume_unwind)
589                 x86_mov_reg_imm (code, X86_EAX, 0);
590         else
591                 x86_mov_reg_membase (code, X86_EAX, X86_ESP, stack_size + 4, 4);
592         x86_mov_membase_reg (code, X86_ESP, arg_offsets [1], X86_EAX, 4);
593         /* Set arg3 == eip */
594         if (llvm_abs)
595                 x86_alu_reg_reg (code, X86_XOR, X86_EAX, X86_EAX);
596         else
597                 x86_mov_reg_membase (code, X86_EAX, X86_ESP, stack_size, 4);
598         x86_mov_membase_reg (code, X86_ESP, arg_offsets [2], X86_EAX, 4);
599         /* Set arg4 == rethrow/pc_offset */
600         if (resume_unwind) {
601                 x86_mov_membase_imm (code, X86_ESP, arg_offsets [3], 0, 4);
602         } else if (corlib) {
603                 x86_mov_reg_membase (code, X86_EAX, X86_ESP, stack_size + 8, 4);
604                 if (llvm_abs) {
605                         /* 
606                          * The caller is LLVM code which passes the absolute address not a pc offset,
607                          * so compensate by passing 0 as 'ip' and passing the negated abs address as
608                          * the pc offset.
609                          */
610                         x86_neg_reg (code, X86_EAX);
611                 }
612                 x86_mov_membase_reg (code, X86_ESP, arg_offsets [3], X86_EAX, 4);
613         } else {
614                 x86_mov_membase_imm (code, X86_ESP, arg_offsets [3], rethrow, 4);
615         }
616         /* Make the call */
617         if (aot) {
618                 // This can be called from runtime code, which can't guarantee that
619                 // ebx contains the got address.
620                 // So emit the got address loading code too
621                 code = mono_arch_emit_load_got_addr (start, code, NULL, &ji);
622                 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");
623                 x86_call_reg (code, X86_EAX);
624         } else {
625                 x86_call_code (code, resume_unwind ? (mono_x86_resume_unwind) : (corlib ? (gpointer)mono_x86_throw_corlib_exception : (gpointer)mono_x86_throw_exception));
626         }
627         x86_breakpoint (code);
628
629         nacl_global_codeman_validate(&start, kMaxCodeSize, &code);
630
631         g_assert ((code - start) < kMaxCodeSize);
632
633         if (info)
634                 *info = mono_tramp_info_create (g_strdup (name), start, code - start, ji, unwind_ops);
635         else {
636                 GSList *l;
637
638                 for (l = unwind_ops; l; l = l->next)
639                         g_free (l->data);
640                 g_slist_free (unwind_ops);
641         }
642
643         return start;
644 }
645
646 /**
647  * mono_arch_get_throw_exception:
648  *
649  * Returns a function pointer which can be used to raise 
650  * exceptions. The returned function has the following 
651  * signature: void (*func) (MonoException *exc); 
652  * For example to raise an arithmetic exception you can use:
653  *
654  * x86_push_imm (code, mono_get_exception_arithmetic ()); 
655  * x86_call_code (code, arch_get_throw_exception ()); 
656  *
657  */
658 gpointer 
659 mono_arch_get_throw_exception (MonoTrampInfo **info, gboolean aot)
660 {
661         return get_throw_trampoline ("throw_exception", FALSE, FALSE, FALSE, FALSE, FALSE, info, aot);
662 }
663
664 gpointer 
665 mono_arch_get_rethrow_exception (MonoTrampInfo **info, gboolean aot)
666 {
667         return get_throw_trampoline ("rethrow_exception", TRUE, FALSE, FALSE, FALSE, FALSE, info, aot);
668 }
669
670 /**
671  * mono_arch_get_throw_corlib_exception:
672  *
673  * Returns a function pointer which can be used to raise 
674  * corlib exceptions. The returned function has the following 
675  * signature: void (*func) (guint32 ex_token, guint32 offset); 
676  * Here, offset is the offset which needs to be substracted from the caller IP 
677  * to get the IP of the throw. Passing the offset has the advantage that it 
678  * needs no relocations in the caller.
679  */
680 gpointer 
681 mono_arch_get_throw_corlib_exception (MonoTrampInfo **info, gboolean aot)
682 {
683         return get_throw_trampoline ("throw_corlib_exception", FALSE, FALSE, TRUE, FALSE, FALSE, info, aot);
684 }
685
686 void
687 mono_arch_exceptions_init (void)
688 {
689         guint8 *tramp;
690
691 /* 
692  * If we're running WoW64, we need to set the usermode exception policy 
693  * for SEHs to behave. This requires hotfix http://support.microsoft.com/kb/976038
694  * or (eventually) Windows 7 SP1.
695  */
696 #ifdef HOST_WIN32
697         DWORD flags;
698         FARPROC getter;
699         FARPROC setter;
700         HMODULE kernel32 = LoadLibraryW (L"kernel32.dll");
701
702         if (kernel32) {
703                 getter = GetProcAddress (kernel32, "GetProcessUserModeExceptionPolicy");
704                 setter = GetProcAddress (kernel32, "SetProcessUserModeExceptionPolicy");
705                 if (getter && setter) {
706                         if (getter (&flags))
707                                 setter (flags & ~PROCESS_CALLBACK_FILTER_ENABLED);
708                 }
709         }
710 #endif
711
712         if (mono_aot_only) {
713                 signal_exception_trampoline = mono_aot_get_trampoline ("x86_signal_exception_trampoline");
714                 return;
715         }
716
717         /* LLVM needs different throw trampolines */
718         tramp = get_throw_trampoline ("llvm_throw_exception_trampoline", FALSE, TRUE, FALSE, FALSE, FALSE, NULL, FALSE);
719         mono_register_jit_icall (tramp, "llvm_throw_exception_trampoline", NULL, TRUE);
720
721         tramp = get_throw_trampoline ("llvm_rethrow_exception_trampoline", FALSE, TRUE, FALSE, FALSE, FALSE, NULL, FALSE);
722         mono_register_jit_icall (tramp, "llvm_rethrow_exception_trampoline", NULL, TRUE);
723
724         tramp = get_throw_trampoline ("llvm_throw_corlib_exception_trampoline", FALSE, TRUE, TRUE, FALSE, FALSE, NULL, FALSE);
725         mono_register_jit_icall (tramp, "llvm_throw_corlib_exception_trampoline", NULL, TRUE);
726
727         tramp = get_throw_trampoline ("llvm_throw_corlib_exception_abs_trampoline", FALSE, TRUE, TRUE, TRUE, FALSE, NULL, FALSE);
728         mono_register_jit_icall (tramp, "llvm_throw_corlib_exception_abs_trampoline", NULL, TRUE);
729
730         tramp = get_throw_trampoline ("llvm_resume_unwind_trampoline", FALSE, FALSE, FALSE, FALSE, TRUE, NULL, FALSE);
731         mono_register_jit_icall (tramp, "llvm_resume_unwind_trampoline", NULL, TRUE);
732
733         signal_exception_trampoline = mono_x86_get_signal_exception_trampoline (NULL, FALSE);
734 }
735
736 /*
737  * mono_arch_find_jit_info:
738  *
739  * See exceptions-amd64.c for docs.
740  */
741 gboolean
742 mono_arch_find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls, 
743                                                          MonoJitInfo *ji, MonoContext *ctx, 
744                                                          MonoContext *new_ctx, MonoLMF **lmf,
745                                                          mgreg_t **save_locations,
746                                                          StackFrameInfo *frame)
747 {
748         gpointer ip = MONO_CONTEXT_GET_IP (ctx);
749
750         memset (frame, 0, sizeof (StackFrameInfo));
751         frame->ji = ji;
752
753         *new_ctx = *ctx;
754
755         if (ji != NULL) {
756                 gssize regs [MONO_MAX_IREGS + 1];
757                 guint8 *cfa;
758                 guint32 unwind_info_len;
759                 guint8 *unwind_info;
760
761                 frame->type = FRAME_TYPE_MANAGED;
762
763                 if (ji->from_aot)
764                         unwind_info = mono_aot_get_unwind_info (ji, &unwind_info_len);
765                 else
766                         unwind_info = mono_get_cached_unwind_info (ji->used_regs, &unwind_info_len);
767
768                 regs [X86_EAX] = new_ctx->eax;
769                 regs [X86_EBX] = new_ctx->ebx;
770                 regs [X86_ECX] = new_ctx->ecx;
771                 regs [X86_EDX] = new_ctx->edx;
772                 regs [X86_ESP] = new_ctx->esp;
773                 regs [X86_EBP] = new_ctx->ebp;
774                 regs [X86_ESI] = new_ctx->esi;
775                 regs [X86_EDI] = new_ctx->edi;
776                 regs [X86_NREG] = new_ctx->eip;
777
778                 mono_unwind_frame (unwind_info, unwind_info_len, ji->code_start, 
779                                                    (guint8*)ji->code_start + ji->code_size,
780                                                    ip, regs, MONO_MAX_IREGS + 1,
781                                                    save_locations, MONO_MAX_IREGS, &cfa);
782
783                 new_ctx->eax = regs [X86_EAX];
784                 new_ctx->ebx = regs [X86_EBX];
785                 new_ctx->ecx = regs [X86_ECX];
786                 new_ctx->edx = regs [X86_EDX];
787                 new_ctx->esp = regs [X86_ESP];
788                 new_ctx->ebp = regs [X86_EBP];
789                 new_ctx->esi = regs [X86_ESI];
790                 new_ctx->edi = regs [X86_EDI];
791                 new_ctx->eip = regs [X86_NREG];
792
793                 /* The CFA becomes the new SP value */
794                 new_ctx->esp = (gssize)cfa;
795
796                 /* Adjust IP */
797                 new_ctx->eip --;
798
799                 if (*lmf && (MONO_CONTEXT_GET_BP (ctx) >= (gpointer)(*lmf)->ebp)) {
800                         /* remove any unused lmf */
801                         *lmf = (gpointer)(((gsize)(*lmf)->previous_lmf) & ~3);
802                 }
803
804                 /* Pop arguments off the stack */
805                 /* 
806                  * FIXME: LLVM doesn't push these, we can't use ji->from_llvm as it describes
807                  * the caller.
808                  */
809 #ifndef ENABLE_LLVM
810                 {
811                         MonoJitArgumentInfo *arg_info = g_newa (MonoJitArgumentInfo, mono_method_signature (ji->method)->param_count + 1);
812
813                         guint32 stack_to_pop = mono_arch_get_argument_info (mono_method_signature (ji->method), mono_method_signature (ji->method)->param_count, arg_info);
814                         new_ctx->esp += stack_to_pop;
815                 }
816 #endif
817
818                 return TRUE;
819         } else if (*lmf) {
820
821                 if (((guint64)(*lmf)->previous_lmf) & 2) {
822                         /* 
823                          * This LMF entry is created by the soft debug code to mark transitions to
824                          * managed code done during invokes.
825                          */
826                         MonoLMFExt *ext = (MonoLMFExt*)(*lmf);
827
828                         g_assert (ext->debugger_invoke);
829
830                         memcpy (new_ctx, &ext->ctx, sizeof (MonoContext));
831
832                         *lmf = (gpointer)(((gsize)(*lmf)->previous_lmf) & ~3);
833
834                         frame->type = FRAME_TYPE_DEBUGGER_INVOKE;
835
836                         return TRUE;
837                 }
838                 
839                 if ((ji = mini_jit_info_table_find (domain, (gpointer)(*lmf)->eip, NULL))) {
840                 } else {
841                         if (!((guint32)((*lmf)->previous_lmf) & 1))
842                                 /* Top LMF entry */
843                                 return FALSE;
844                         g_assert_not_reached ();
845                         /* Trampoline lmf frame */
846                         frame->method = (*lmf)->method;
847                 }
848
849                 new_ctx->esi = (*lmf)->esi;
850                 new_ctx->edi = (*lmf)->edi;
851                 new_ctx->ebx = (*lmf)->ebx;
852                 new_ctx->ebp = (*lmf)->ebp;
853                 new_ctx->eip = (*lmf)->eip;
854
855                 /* Adjust IP */
856                 new_ctx->eip --;
857
858                 frame->ji = ji;
859                 frame->type = FRAME_TYPE_MANAGED_TO_NATIVE;
860
861                 /* Check if we are in a trampoline LMF frame */
862                 if ((guint32)((*lmf)->previous_lmf) & 1) {
863                         /* lmf->esp is set by the trampoline code */
864                         new_ctx->esp = (*lmf)->esp;
865
866                         /* Pop arguments off the stack */
867                         /* FIXME: Handle the delegate case too ((*lmf)->method == NULL) */
868                         /* FIXME: Handle the IMT/vtable case too */
869 #ifndef ENABLE_LLVM
870                         if ((*lmf)->method) {
871                                 MonoMethod *method = (*lmf)->method;
872                                 MonoJitArgumentInfo *arg_info = g_newa (MonoJitArgumentInfo, mono_method_signature (method)->param_count + 1);
873
874                                 guint32 stack_to_pop = mono_arch_get_argument_info (mono_method_signature (method), mono_method_signature (method)->param_count, arg_info);
875                                 new_ctx->esp += stack_to_pop;
876                         }
877 #endif
878                 }
879                 else
880                         /* the lmf is always stored on the stack, so the following
881                          * expression points to a stack location which can be used as ESP */
882                         new_ctx->esp = (unsigned long)&((*lmf)->eip);
883
884                 *lmf = (gpointer)(((gsize)(*lmf)->previous_lmf) & ~3);
885
886                 return TRUE;
887         }
888
889         return FALSE;
890 }
891
892 #ifdef __sun
893 #define REG_EAX EAX
894 #define REG_EBX EBX
895 #define REG_ECX ECX
896 #define REG_EDX EDX
897 #define REG_EBP EBP
898 #define REG_ESP ESP
899 #define REG_ESI ESI
900 #define REG_EDI EDI
901 #define REG_EIP EIP
902 #endif
903
904 void
905 mono_arch_sigctx_to_monoctx (void *sigctx, MonoContext *mctx)
906 {
907 #if defined (__native_client__)
908         printf("WARNING: mono_arch_sigctx_to_monoctx() called!\n");
909         mctx->eax = 0xDEADBEEF;
910         mctx->ebx = 0xDEADBEEF;
911         mctx->ecx = 0xDEADBEEF;
912         mctx->edx = 0xDEADBEEF;
913         mctx->ebp = 0xDEADBEEF;
914         mctx->esp = 0xDEADBEEF;
915         mctx->esi = 0xDEADBEEF;
916         mctx->edi = 0xDEADBEEF;
917         mctx->eip = 0xDEADBEEF;
918 #else
919 #ifdef MONO_ARCH_USE_SIGACTION
920         ucontext_t *ctx = (ucontext_t*)sigctx;
921         
922         mctx->eax = UCONTEXT_REG_EAX (ctx);
923         mctx->ebx = UCONTEXT_REG_EBX (ctx);
924         mctx->ecx = UCONTEXT_REG_ECX (ctx);
925         mctx->edx = UCONTEXT_REG_EDX (ctx);
926         mctx->ebp = UCONTEXT_REG_EBP (ctx);
927         mctx->esp = UCONTEXT_REG_ESP (ctx);
928         mctx->esi = UCONTEXT_REG_ESI (ctx);
929         mctx->edi = UCONTEXT_REG_EDI (ctx);
930         mctx->eip = UCONTEXT_REG_EIP (ctx);
931 #else   
932         struct sigcontext *ctx = (struct sigcontext *)sigctx;
933
934         mctx->eax = ctx->SC_EAX;
935         mctx->ebx = ctx->SC_EBX;
936         mctx->ecx = ctx->SC_ECX;
937         mctx->edx = ctx->SC_EDX;
938         mctx->ebp = ctx->SC_EBP;
939         mctx->esp = ctx->SC_ESP;
940         mctx->esi = ctx->SC_ESI;
941         mctx->edi = ctx->SC_EDI;
942         mctx->eip = ctx->SC_EIP;
943 #endif
944 #endif /* if defined(__native_client__) */
945 }
946
947 void
948 mono_arch_monoctx_to_sigctx (MonoContext *mctx, void *sigctx)
949 {
950 #if defined(__native_client__)
951         printf("WARNING: mono_arch_monoctx_to_sigctx() called!\n");
952 #else
953 #ifdef MONO_ARCH_USE_SIGACTION
954         ucontext_t *ctx = (ucontext_t*)sigctx;
955
956         UCONTEXT_REG_EAX (ctx) = mctx->eax;
957         UCONTEXT_REG_EBX (ctx) = mctx->ebx;
958         UCONTEXT_REG_ECX (ctx) = mctx->ecx;
959         UCONTEXT_REG_EDX (ctx) = mctx->edx;
960         UCONTEXT_REG_EBP (ctx) = mctx->ebp;
961         UCONTEXT_REG_ESP (ctx) = mctx->esp;
962         UCONTEXT_REG_ESI (ctx) = mctx->esi;
963         UCONTEXT_REG_EDI (ctx) = mctx->edi;
964         UCONTEXT_REG_EIP (ctx) = mctx->eip;
965 #else
966         struct sigcontext *ctx = (struct sigcontext *)sigctx;
967
968         ctx->SC_EAX = mctx->eax;
969         ctx->SC_EBX = mctx->ebx;
970         ctx->SC_ECX = mctx->ecx;
971         ctx->SC_EDX = mctx->edx;
972         ctx->SC_EBP = mctx->ebp;
973         ctx->SC_ESP = mctx->esp;
974         ctx->SC_ESI = mctx->esi;
975         ctx->SC_EDI = mctx->edi;
976         ctx->SC_EIP = mctx->eip;
977 #endif
978 #endif /* __native_client__ */
979 }       
980
981 gpointer
982 mono_arch_ip_from_context (void *sigctx)
983 {
984 #if defined(__native_client__)
985         printf("WARNING: mono_arch_ip_from_context() called!\n");
986         return (NULL);
987 #else
988 #ifdef MONO_ARCH_USE_SIGACTION
989         ucontext_t *ctx = (ucontext_t*)sigctx;
990         return (gpointer)UCONTEXT_REG_EIP (ctx);
991 #else
992         struct sigcontext *ctx = sigctx;
993         return (gpointer)ctx->SC_EIP;
994 #endif
995 #endif  /* __native_client__ */
996 }
997
998 /*
999  * handle_exception:
1000  *
1001  *   Called by resuming from a signal handler.
1002  */
1003 static void
1004 handle_signal_exception (gpointer obj)
1005 {
1006         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
1007         MonoContext ctx;
1008         static void (*restore_context) (MonoContext *);
1009
1010         if (!restore_context)
1011                 restore_context = mono_get_restore_context ();
1012
1013         memcpy (&ctx, &jit_tls->ex_ctx, sizeof (MonoContext));
1014
1015         if (mono_debugger_handle_exception (&ctx, (MonoObject *)obj))
1016                 return;
1017
1018         mono_handle_exception (&ctx, obj, MONO_CONTEXT_GET_IP (&ctx), FALSE);
1019
1020         restore_context (&ctx);
1021 }
1022
1023 /*
1024  * mono_x86_get_signal_exception_trampoline:
1025  *
1026  *   This x86 specific trampoline is used to call handle_signal_exception.
1027  */
1028 gpointer
1029 mono_x86_get_signal_exception_trampoline (MonoTrampInfo **info, gboolean aot)
1030 {
1031         guint8 *start, *code;
1032         MonoJumpInfo *ji = NULL;
1033         GSList *unwind_ops = NULL;
1034         int stack_size;
1035
1036         start = code = mono_global_codeman_reserve (128);
1037
1038         /* Caller ip */
1039         x86_push_reg (code, X86_ECX);
1040
1041         mono_add_unwind_op_def_cfa (unwind_ops, (guint8*)NULL, (guint8*)NULL, X86_ESP, 4);
1042         mono_add_unwind_op_offset (unwind_ops, (guint8*)NULL, (guint8*)NULL, X86_NREG, -4);
1043
1044         /* Fix the alignment to be what apple expects */
1045         stack_size = 12;
1046
1047         x86_alu_reg_imm (code, X86_SUB, X86_ESP, stack_size);
1048         mono_add_unwind_op_def_cfa_offset (unwind_ops, code, start, stack_size + 4);
1049
1050         /* Arg1 */
1051         x86_mov_membase_reg (code, X86_ESP, 0, X86_EAX, 4);
1052         /* Branch to target */
1053         x86_call_reg (code, X86_EDX);
1054
1055         g_assert ((code - start) < 128);
1056
1057         if (info)
1058                 *info = mono_tramp_info_create (g_strdup ("x86_signal_exception_trampoline"), start, code - start, ji, unwind_ops);
1059         else {
1060                 GSList *l;
1061
1062                 for (l = unwind_ops; l; l = l->next)
1063                         g_free (l->data);
1064                 g_slist_free (unwind_ops);
1065         }
1066
1067         return start;
1068 }
1069
1070 gboolean
1071 mono_arch_handle_exception (void *sigctx, gpointer obj, gboolean test_only)
1072 {
1073 #if defined(MONO_ARCH_USE_SIGACTION)
1074         ucontext_t *ctx = (ucontext_t*)sigctx;
1075
1076         /*
1077          * Handling the exception in the signal handler is problematic, since the original
1078          * signal is disabled, and we could run arbitrary code though the debugger. So
1079          * resume into the normal stack and do most work there if possible.
1080          */
1081         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
1082         guint64 sp = UCONTEXT_REG_ESP (ctx);
1083
1084         /* Pass the ctx parameter in TLS */
1085         mono_arch_sigctx_to_monoctx (ctx, &jit_tls->ex_ctx);
1086         /*
1087          * Can't pass the obj on the stack, since we are executing on the
1088          * same stack. Can't save it into MonoJitTlsData, since it needs GC tracking.
1089          * So put it into a register, and branch to a trampoline which
1090          * pushes it.
1091          */
1092         g_assert (!test_only);
1093         UCONTEXT_REG_EAX (ctx) = (gsize)obj;
1094         UCONTEXT_REG_ECX (ctx) = UCONTEXT_REG_EIP (ctx);
1095         UCONTEXT_REG_EDX (ctx) = (gsize)handle_signal_exception;
1096
1097         /* Allocate a stack frame, align it to 16 bytes which is needed on apple */
1098         sp -= 16;
1099         sp &= ~15;
1100         UCONTEXT_REG_ESP (ctx) = sp;
1101
1102         UCONTEXT_REG_EIP (ctx) = (gsize)signal_exception_trampoline;
1103
1104         return TRUE;
1105 #elif defined (TARGET_WIN32)
1106         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
1107         struct sigcontext *ctx = (struct sigcontext *)sigctx;
1108         guint64 sp = ctx->SC_ESP;
1109
1110         mono_arch_sigctx_to_monoctx (sigctx, &jit_tls->ex_ctx);
1111
1112         /*
1113          * Can't pass the obj on the stack, since we are executing on the
1114          * same stack. Can't save it into MonoJitTlsData, since it needs GC tracking.
1115          * So put it into a register, and branch to a trampoline which
1116          * pushes it.
1117          */
1118         g_assert (!test_only);
1119         ctx->SC_EAX = (gsize)obj;
1120         ctx->SC_ECX = ctx->SC_EIP;
1121         ctx->SC_EDX = (gsize)handle_signal_exception;
1122
1123         /* Allocate a stack frame, align it to 16 bytes which is needed on apple */
1124         sp -= 16;
1125         sp &= ~15;
1126         ctx->SC_ESP = sp;
1127
1128         ctx->SC_EIP = (gsize)signal_exception_trampoline;
1129
1130         return TRUE;
1131 #else
1132         MonoContext mctx;
1133
1134         mono_arch_sigctx_to_monoctx (sigctx, &mctx);
1135
1136         if (mono_debugger_handle_exception (&mctx, (MonoObject *)obj))
1137                 return TRUE;
1138
1139         mono_handle_exception (&mctx, obj, (gpointer)mctx.eip, test_only);
1140
1141         mono_arch_monoctx_to_sigctx (&mctx, sigctx);
1142
1143         return TRUE;
1144 #endif
1145 }
1146
1147 static void
1148 restore_soft_guard_pages (void)
1149 {
1150         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
1151         if (jit_tls->stack_ovf_guard_base)
1152                 mono_mprotect (jit_tls->stack_ovf_guard_base, jit_tls->stack_ovf_guard_size, MONO_MMAP_NONE);
1153 }
1154
1155 /* 
1156  * this function modifies mctx so that when it is restored, it
1157  * won't execcute starting at mctx.eip, but in a function that
1158  * will restore the protection on the soft-guard pages and return back to
1159  * continue at mctx.eip.
1160  */
1161 static void
1162 prepare_for_guard_pages (MonoContext *mctx)
1163 {
1164         gpointer *sp;
1165         sp = (gpointer)(mctx->esp);
1166         sp -= 1;
1167         /* the resturn addr */
1168         sp [0] = (gpointer)(mctx->eip);
1169         mctx->eip = (unsigned long)restore_soft_guard_pages;
1170         mctx->esp = (unsigned long)sp;
1171 }
1172
1173 static void
1174 altstack_handle_and_restore (void *sigctx, gpointer obj, gboolean stack_ovf)
1175 {
1176         void (*restore_context) (MonoContext *);
1177         MonoContext mctx;
1178
1179         restore_context = mono_get_restore_context ();
1180         mono_arch_sigctx_to_monoctx (sigctx, &mctx);
1181
1182         if (mono_debugger_handle_exception (&mctx, (MonoObject *)obj)) {
1183                 if (stack_ovf)
1184                         prepare_for_guard_pages (&mctx);
1185                 restore_context (&mctx);
1186         }
1187
1188         mono_handle_exception (&mctx, obj, (gpointer)mctx.eip, FALSE);
1189         if (stack_ovf)
1190                 prepare_for_guard_pages (&mctx);
1191         restore_context (&mctx);
1192 }
1193
1194 void
1195 mono_arch_handle_altstack_exception (void *sigctx, gpointer fault_addr, gboolean stack_ovf)
1196 {
1197 #ifdef MONO_ARCH_USE_SIGACTION
1198         MonoException *exc = NULL;
1199         ucontext_t *ctx = (ucontext_t*)sigctx;
1200         MonoJitInfo *ji = mini_jit_info_table_find (mono_domain_get (), (gpointer)UCONTEXT_REG_EIP (ctx), NULL);
1201         gpointer *sp;
1202         int frame_size;
1203
1204         /* if we didn't find a managed method for the ip address and it matches the fault
1205          * address, we assume we followed a broken pointer during an indirect call, so
1206          * we try the lookup again with the return address pushed on the stack
1207          */
1208         if (!ji && fault_addr == (gpointer)UCONTEXT_REG_EIP (ctx)) {
1209                 glong *sp = (gpointer)UCONTEXT_REG_ESP (ctx);
1210                 ji = mini_jit_info_table_find (mono_domain_get (), (gpointer)sp [0], NULL);
1211                 if (ji)
1212                         UCONTEXT_REG_EIP (ctx) = sp [0];
1213         }
1214         if (stack_ovf)
1215                 exc = mono_domain_get ()->stack_overflow_ex;
1216         if (!ji)
1217                 mono_handle_native_sigsegv (SIGSEGV, sigctx);
1218         /* setup a call frame on the real stack so that control is returned there
1219          * and exception handling can continue.
1220          * If this was a stack overflow the caller already ensured the stack pages
1221          * needed have been unprotected.
1222          * The frame looks like:
1223          *   ucontext struct
1224          *   test_only arg
1225          *   exception arg
1226          *   ctx arg
1227          *   return ip
1228          */
1229         frame_size = sizeof (ucontext_t) + sizeof (gpointer) * 4;
1230         frame_size += 15;
1231         frame_size &= ~15;
1232         sp = (gpointer)(UCONTEXT_REG_ESP (ctx) & ~15);
1233         sp = (gpointer)((char*)sp - frame_size);
1234         /* the incoming arguments are aligned to 16 bytes boundaries, so the return address IP
1235          * goes at sp [-1]
1236          */
1237         sp [-1] = (gpointer)UCONTEXT_REG_EIP (ctx);
1238         sp [0] = sp + 4;
1239         sp [1] = exc;
1240         sp [2] = (gpointer)stack_ovf;
1241         /* may need to adjust pointers in the new struct copy, depending on the OS */
1242         memcpy (sp + 4, ctx, sizeof (ucontext_t));
1243         /* at the return form the signal handler execution starts in altstack_handle_and_restore() */
1244         UCONTEXT_REG_EIP (ctx) = (unsigned long)altstack_handle_and_restore;
1245         UCONTEXT_REG_ESP (ctx) = (unsigned long)(sp - 1);
1246 #endif
1247 }
1248
1249 #if MONO_SUPPORT_TASKLETS
1250 MonoContinuationRestore
1251 mono_tasklets_arch_restore (void)
1252 {
1253         static guint8* saved = NULL;
1254         guint8 *code, *start;
1255
1256 #ifdef __native_client_codegen__
1257         g_print("mono_tasklets_arch_restore needs to be aligned for Native Client\n");
1258 #endif
1259         if (saved)
1260                 return (MonoContinuationRestore)saved;
1261         code = start = mono_global_codeman_reserve (48);
1262         /* the signature is: restore (MonoContinuation *cont, int state, MonoLMF **lmf_addr) */
1263         /* put cont in edx */
1264         x86_mov_reg_membase (code, X86_EDX, X86_ESP, 4, 4);
1265         /* setup the copy of the stack */
1266         x86_mov_reg_membase (code, X86_ECX, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, stack_used_size), 4);
1267         x86_shift_reg_imm (code, X86_SHR, X86_ECX, 2);
1268         x86_cld (code);
1269         x86_mov_reg_membase (code, X86_ESI, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, saved_stack), 4);
1270         x86_mov_reg_membase (code, X86_EDI, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, return_sp), 4);
1271         x86_prefix (code, X86_REP_PREFIX);
1272         x86_movsl (code);
1273
1274         /* now restore the registers from the LMF */
1275         x86_mov_reg_membase (code, X86_ECX, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, lmf), 4);
1276         x86_mov_reg_membase (code, X86_EBX, X86_ECX, G_STRUCT_OFFSET (MonoLMF, ebx), 4);
1277         x86_mov_reg_membase (code, X86_EBP, X86_ECX, G_STRUCT_OFFSET (MonoLMF, ebp), 4);
1278         x86_mov_reg_membase (code, X86_ESI, X86_ECX, G_STRUCT_OFFSET (MonoLMF, esi), 4);
1279         x86_mov_reg_membase (code, X86_EDI, X86_ECX, G_STRUCT_OFFSET (MonoLMF, edi), 4);
1280
1281         /* restore the lmf chain */
1282         /*x86_mov_reg_membase (code, X86_ECX, X86_ESP, 12, 4);
1283         x86_mov_membase_reg (code, X86_ECX, 0, X86_EDX, 4);*/
1284
1285         /* state in eax, so it's setup as the return value */
1286         x86_mov_reg_membase (code, X86_EAX, X86_ESP, 8, 4);
1287         x86_jump_membase (code, X86_EDX, G_STRUCT_OFFSET (MonoContinuation, return_ip));
1288         g_assert ((code - start) <= 48);
1289         saved = start;
1290         return (MonoContinuationRestore)saved;
1291 }
1292 #endif
1293
1294 /*
1295  * mono_arch_setup_resume_sighandler_ctx:
1296  *
1297  *   Setup CTX so execution continues at FUNC.
1298  */
1299 void
1300 mono_arch_setup_resume_sighandler_ctx (MonoContext *ctx, gpointer func)
1301 {
1302         int align = (((gint32)MONO_CONTEXT_GET_SP (ctx)) % MONO_ARCH_FRAME_ALIGNMENT + 4);
1303
1304         if (align != 0)
1305                 MONO_CONTEXT_SET_SP (ctx, (gsize)MONO_CONTEXT_GET_SP (ctx) - align);
1306
1307         MONO_CONTEXT_SET_IP (ctx, func);
1308 }