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