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