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