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