2008-08-14 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / mini / exceptions-ppc.c
1 /*
2  * exceptions-ppc.c: exception support for PowerPC
3  *
4  * Authors:
5  *   Dietmar Maurer (dietmar@ximian.com)
6  *   Paolo Molaro (lupus@ximian.com)
7  *
8  * (C) 2001 Ximian, Inc.
9  */
10
11 #include <config.h>
12 #include <glib.h>
13 #include <signal.h>
14 #include <string.h>
15 #include <stddef.h>
16 #include <ucontext.h>
17
18 #include <mono/arch/ppc/ppc-codegen.h>
19 #include <mono/metadata/appdomain.h>
20 #include <mono/metadata/tabledefs.h>
21 #include <mono/metadata/threads.h>
22 #include <mono/metadata/debug-helpers.h>
23 #include <mono/metadata/exception.h>
24 #include <mono/metadata/mono-debug.h>
25
26 #include "mini.h"
27 #include "mini-ppc.h"
28
29 static gboolean arch_handle_exception (MonoContext *ctx, gpointer obj, gboolean test_only);
30
31 /*
32
33 struct sigcontext {
34     int      sc_onstack;     // sigstack state to restore 
35     int      sc_mask;        // signal mask to restore 
36     int      sc_ir;          // pc 
37     int      sc_psw;         // processor status word 
38     int      sc_sp;          // stack pointer if sc_regs == NULL 
39     void    *sc_regs;        // (kernel private) saved state 
40 };
41
42 struct ucontext {
43         int             uc_onstack;
44         sigset_t        uc_sigmask;     // signal mask used by this context 
45         stack_t         uc_stack;       // stack used by this context 
46         struct ucontext *uc_link;       // pointer to resuming context 
47         size_t          uc_mcsize;      // size of the machine context passed in 
48         mcontext_t      uc_mcontext;    // machine specific context 
49 };
50
51 typedef struct ppc_exception_state {
52         unsigned long dar;      // Fault registers for coredump 
53         unsigned long dsisr;
54         unsigned long exception;// number of powerpc exception taken 
55         unsigned long pad0;     // align to 16 bytes 
56
57         unsigned long pad1[4];  // space in PCB "just in case" 
58 } ppc_exception_state_t;
59
60 typedef struct ppc_vector_state {
61         unsigned long   save_vr[32][4];
62         unsigned long   save_vscr[4];
63         unsigned int    save_pad5[4];
64         unsigned int    save_vrvalid;                   // VRs that have been saved 
65         unsigned int    save_pad6[7];
66 } ppc_vector_state_t;
67
68 typedef struct ppc_float_state {
69         double  fpregs[32];
70
71         unsigned int fpscr_pad; // fpscr is 64 bits, 32 bits of rubbish 
72         unsigned int fpscr;     // floating point status register 
73 } ppc_float_state_t;
74
75 typedef struct ppc_thread_state {
76         unsigned int srr0;      // Instruction address register (PC) 
77         unsigned int srr1;      // Machine state register (supervisor) 
78         unsigned int r0;
79         unsigned int r1;
80         unsigned int r2;
81         ... 
82         unsigned int r31;
83         unsigned int cr;        // Condition register 
84         unsigned int xer;       // User's integer exception register 
85         unsigned int lr;        // Link register 
86         unsigned int ctr;       // Count register 
87         unsigned int mq;        // MQ register (601 only) 
88
89         unsigned int vrsave;    // Vector Save Register 
90 } ppc_thread_state_t;
91
92 struct mcontext {
93         ppc_exception_state_t   es;
94         ppc_thread_state_t      ss;
95         ppc_float_state_t       fs;
96         ppc_vector_state_t      vs;
97 };
98
99 typedef struct mcontext  * mcontext_t;
100
101 Linux/PPC instead has:
102 struct sigcontext {
103         unsigned long   _unused[4];
104         int             signal;
105         unsigned long   handler;
106         unsigned long   oldmask;
107         struct pt_regs  *regs;
108 };
109 struct pt_regs {
110         unsigned long gpr[32];
111         unsigned long nip;
112         unsigned long msr;
113         unsigned long orig_gpr3;        // Used for restarting system calls 
114         unsigned long ctr;
115         unsigned long link;
116         unsigned long xer;
117         unsigned long ccr;
118         unsigned long mq;               // 601 only (not used at present) 
119                                         // Used on APUS to hold IPL value. 
120         unsigned long trap;             // Reason for being here 
121         // N.B. for critical exceptions on 4xx, the dar and dsisr
122         // fields are overloaded to hold srr0 and srr1. 
123         unsigned long dar;              // Fault registers 
124         unsigned long dsisr;            // on 4xx/Book-E used for ESR 
125         unsigned long result;           // Result of a system call 
126 };
127 struct mcontext {
128         elf_gregset_t   mc_gregs;
129         elf_fpregset_t  mc_fregs;
130         unsigned long   mc_pad[2];
131         elf_vrregset_t  mc_vregs __attribute__((__aligned__(16)));
132 };
133
134 struct ucontext {
135         unsigned long    uc_flags;
136         struct ucontext *uc_link;
137         stack_t          uc_stack;
138         int              uc_pad[7];
139         struct mcontext *uc_regs;       // points to uc_mcontext field 
140         sigset_t         uc_sigmask;
141         // glibc has 1024-bit signal masks, ours are 64-bit 
142         int              uc_maskext[30];
143         int              uc_pad2[3];
144         struct mcontext  uc_mcontext;
145 };
146
147 #define ELF_NGREG       48      // includes nip, msr, lr, etc. 
148 #define ELF_NFPREG      33      // includes fpscr 
149
150 // General registers 
151 typedef unsigned long elf_greg_t;
152 typedef elf_greg_t elf_gregset_t[ELF_NGREG];
153
154 // Floating point registers 
155 typedef double elf_fpreg_t;
156 typedef elf_fpreg_t elf_fpregset_t[ELF_NFPREG];
157
158
159 */
160
161
162 #define restore_regs_from_context(ctx_reg,ip_reg,tmp_reg) do {  \
163                 int reg;        \
164                 ppc_lwz (code, ip_reg, G_STRUCT_OFFSET (MonoContext, sc_ir), ctx_reg);  \
165                 ppc_lmw (code, ppc_r13, ctx_reg, G_STRUCT_OFFSET (MonoContext, regs));  \
166                 for (reg = 0; reg < MONO_SAVED_FREGS; ++reg) {  \
167                         ppc_lfd (code, (14 + reg), G_STRUCT_OFFSET(MonoLMF, fregs) + reg * sizeof (gdouble), ctx_reg);  \
168                 }       \
169         } while (0)
170
171 /* nothing to do */
172 #define setup_context(ctx)
173
174 /*
175  * arch_get_restore_context:
176  *
177  * Returns a pointer to a method which restores a previously saved sigcontext.
178  * The first argument in r3 is the pointer to the context.
179  */
180 gpointer
181 mono_arch_get_restore_context (void)
182 {
183         guint8 *code;
184         static guint8 *start = NULL;
185
186         if (start)
187                 return start;
188
189         code = start = mono_global_codeman_reserve (128);
190         restore_regs_from_context (ppc_r3, ppc_r4, ppc_r5);
191         /* restore also the stack pointer */
192         ppc_lwz (code, ppc_sp, G_STRUCT_OFFSET (MonoContext, sc_sp), ppc_r3);
193         //ppc_break (code);
194         /* jump to the saved IP */
195         ppc_mtctr (code, ppc_r4);
196         ppc_bcctr (code, PPC_BR_ALWAYS, 0);
197         /* never reached */
198         ppc_break (code);
199
200         g_assert ((code - start) < 128);
201         mono_arch_flush_icache (start, code - start);
202         return start;
203 }
204
205 /*
206  * mono_arch_get_call_filter:
207  *
208  * Returns a pointer to a method which calls an exception filter. We
209  * also use this function to call finally handlers (we pass NULL as 
210  * @exc object in this case).
211  */
212 gpointer
213 mono_arch_get_call_filter (void)
214 {
215         static guint8 *start = NULL;
216         guint8 *code;
217         int alloc_size, pos, i;
218
219         if (start)
220                 return start;
221
222         /* call_filter (MonoContext *ctx, unsigned long eip, gpointer exc) */
223         code = start = mono_global_codeman_reserve (320);
224
225         /* save all the regs on the stack */
226         pos = 0;
227         for (i = 31; i >= 14; --i) {
228                 pos += sizeof (gdouble);
229                 ppc_stfd (code, i, -pos, ppc_sp);
230         }
231         pos += sizeof (gulong) * MONO_SAVED_GREGS;
232         ppc_stmw (code, ppc_r13, ppc_sp, -pos);
233
234         ppc_mflr (code, ppc_r0);
235         ppc_stw (code, ppc_r0, PPC_RET_ADDR_OFFSET, ppc_sp);
236
237         alloc_size = PPC_MINIMAL_STACK_SIZE + pos + 64;
238         // align to PPC_STACK_ALIGNMENT bytes
239         alloc_size += PPC_STACK_ALIGNMENT - 1;
240         alloc_size &= ~(PPC_STACK_ALIGNMENT - 1);
241
242         g_assert ((alloc_size & (PPC_STACK_ALIGNMENT-1)) == 0);
243         ppc_stwu (code, ppc_sp, -alloc_size, ppc_sp);
244
245         /* restore all the regs from ctx (in r3), but not r1, the stack pointer */
246         restore_regs_from_context (ppc_r3, ppc_r6, ppc_r7);
247         /* call handler at eip (r4) and set the first arg with the exception (r5) */
248         ppc_mtctr (code, ppc_r4);
249         ppc_mr (code, ppc_r3, ppc_r5);
250         ppc_bcctrl (code, PPC_BR_ALWAYS, 0);
251
252         /* epilog */
253         ppc_lwz (code, ppc_r0, alloc_size + PPC_RET_ADDR_OFFSET, ppc_sp);
254         ppc_mtlr (code, ppc_r0);
255         ppc_addic (code, ppc_sp, ppc_sp, alloc_size);
256         
257         /* restore all the regs from the stack */
258         pos = 0;
259         for (i = 31; i >= 14; --i) {
260                 pos += sizeof (double);
261                 ppc_lfd (code, i, -pos, ppc_sp);
262         }
263         pos += sizeof (gulong) * MONO_SAVED_GREGS;
264         ppc_lmw (code, ppc_r13, ppc_sp, -pos);
265
266         ppc_blr (code);
267
268         g_assert ((code - start) < 320);
269         mono_arch_flush_icache (start, code - start);
270         return start;
271 }
272
273 static void
274 throw_exception (MonoObject *exc, unsigned long eip, unsigned long esp, gulong *int_regs, gdouble *fp_regs, gboolean rethrow)
275 {
276         static void (*restore_context) (MonoContext *);
277         MonoContext ctx;
278
279         if (!restore_context)
280                 restore_context = mono_arch_get_restore_context ();
281
282         /* adjust eip so that it point into the call instruction */
283         eip -= 4;
284
285         setup_context (&ctx);
286
287         /*printf ("stack in throw: %p\n", esp);*/
288         MONO_CONTEXT_SET_BP (&ctx, esp);
289         MONO_CONTEXT_SET_IP (&ctx, eip);
290         memcpy (&ctx.regs, int_regs, sizeof (gulong) * MONO_SAVED_GREGS);
291         memcpy (&ctx.fregs, fp_regs, sizeof (double) * MONO_SAVED_FREGS);
292
293         if (mono_object_isinst (exc, mono_defaults.exception_class)) {
294                 MonoException *mono_ex = (MonoException*)exc;
295                 if (!rethrow)
296                         mono_ex->stack_trace = NULL;
297         }
298         arch_handle_exception (&ctx, exc, FALSE);
299         restore_context (&ctx);
300
301         g_assert_not_reached ();
302 }
303
304 /**
305  * arch_get_throw_exception_generic:
306  *
307  * Returns a function pointer which can be used to raise 
308  * exceptions. The returned function has the following 
309  * signature: void (*func) (MonoException *exc); or
310  * void (*func) (char *exc_name);
311  *
312  */
313 static gpointer 
314 mono_arch_get_throw_exception_generic (guint8 *start, int size, int by_name, gboolean rethrow)
315 {
316         guint8 *code;
317         int alloc_size, pos, i;
318
319         code = start;
320
321         /* save all the regs on the stack */
322         pos = 0;
323         for (i = 31; i >= 14; --i) {
324                 pos += sizeof (gdouble);
325                 ppc_stfd (code, i, -pos, ppc_sp);
326         }
327         pos += sizeof (gulong) * MONO_SAVED_GREGS;
328         ppc_stmw (code, ppc_r13, ppc_sp, -pos);
329
330         ppc_mflr (code, ppc_r0);
331         ppc_stw (code, ppc_r0, PPC_RET_ADDR_OFFSET, ppc_sp);
332
333         alloc_size = PPC_MINIMAL_STACK_SIZE + pos + 64;
334         // align to PPC_STACK_ALIGNMENT bytes
335         alloc_size += PPC_STACK_ALIGNMENT - 1;
336         alloc_size &= ~(PPC_STACK_ALIGNMENT - 1);
337
338         g_assert ((alloc_size & (PPC_STACK_ALIGNMENT-1)) == 0);
339         ppc_stwu (code, ppc_sp, -alloc_size, ppc_sp);
340
341         //ppc_break (code);
342         if (by_name) {
343                 ppc_mr (code, ppc_r5, ppc_r3);
344                 ppc_load (code, ppc_r3, mono_defaults.corlib);
345                 ppc_load (code, ppc_r4, "System");
346                 ppc_load (code, ppc_r0, mono_exception_from_name);
347                 ppc_mtctr (code, ppc_r0);
348                 ppc_bcctrl (code, PPC_BR_ALWAYS, 0);
349         }
350
351         /* call throw_exception (exc, ip, sp, int_regs, fp_regs) */
352         /* caller sp */
353         ppc_lwz (code, ppc_r5, 0, ppc_sp); 
354         /* exc is already in place in r3 */
355         if (by_name)
356                 ppc_lwz (code, ppc_r4, PPC_RET_ADDR_OFFSET, ppc_r5); 
357         else
358                 ppc_mr (code, ppc_r4, ppc_r0); /* caller ip */
359         /* pointer to the saved fp regs */
360         pos = alloc_size - sizeof (double) * MONO_SAVED_FREGS;
361         ppc_addi (code, ppc_r7, ppc_sp, pos);
362         /* pointer to the saved int regs */
363         pos -= sizeof (gulong) * MONO_SAVED_GREGS;
364         ppc_addi (code, ppc_r6, ppc_sp, pos);
365         ppc_li (code, ppc_r8, rethrow);
366
367         ppc_load (code, ppc_r0, throw_exception);
368         ppc_mtctr (code, ppc_r0);
369         ppc_bcctrl (code, PPC_BR_ALWAYS, 0);
370         /* we should never reach this breakpoint */
371         ppc_break (code);
372         g_assert ((code - start) < size);
373         mono_arch_flush_icache (start, code - start);
374         return start;
375 }
376
377 /**
378  * mono_arch_get_rethrow_exception:
379  *
380  * Returns a function pointer which can be used to rethrow 
381  * exceptions. The returned function has the following 
382  * signature: void (*func) (MonoException *exc); 
383  *
384  */
385 gpointer
386 mono_arch_get_rethrow_exception (void)
387 {
388         static guint8 *start = NULL;
389         static int inited = 0;
390
391         if (inited)
392                 return start;
393         start = mono_global_codeman_reserve (132);
394         mono_arch_get_throw_exception_generic (start, 132, FALSE, TRUE);
395         inited = 1;
396         return start;
397 }
398 /**
399  * arch_get_throw_exception:
400  *
401  * Returns a function pointer which can be used to raise 
402  * exceptions. The returned function has the following 
403  * signature: void (*func) (MonoException *exc); 
404  * For example to raise an arithmetic exception you can use:
405  *
406  * x86_push_imm (code, mono_get_exception_arithmetic ()); 
407  * x86_call_code (code, arch_get_throw_exception ()); 
408  *
409  */
410 gpointer 
411 mono_arch_get_throw_exception (void)
412 {
413         static guint8 *start = NULL;
414         static int inited = 0;
415
416         if (inited)
417                 return start;
418         start = mono_global_codeman_reserve (132);
419         mono_arch_get_throw_exception_generic (start, 132, FALSE, FALSE);
420         inited = 1;
421         return start;
422 }
423
424 /**
425  * arch_get_throw_exception_by_name:
426  *
427  * Returns a function pointer which can be used to raise 
428  * corlib exceptions. The returned function has the following 
429  * signature: void (*func) (char *exc_name); 
430  * For example to raise an arithmetic exception you can use:
431  *
432  * x86_push_imm (code, "ArithmeticException"); 
433  * x86_call_code (code, arch_get_throw_exception_by_name ()); 
434  *
435  */
436 gpointer 
437 mono_arch_get_throw_exception_by_name (void)
438 {
439         static guint8 *start = NULL;
440         static int inited = 0;
441
442         if (inited)
443                 return start;
444         start = mono_global_codeman_reserve (168);
445         mono_arch_get_throw_exception_generic (start, 168, TRUE, FALSE);
446         inited = 1;
447         return start;
448 }       
449
450 static MonoArray *
451 glist_to_array (GList *list, MonoClass *eclass) 
452 {
453         MonoDomain *domain = mono_domain_get ();
454         MonoArray *res;
455         int len, i;
456
457         if (!list)
458                 return NULL;
459
460         len = g_list_length (list);
461         res = mono_array_new (domain, eclass, len);
462
463         for (i = 0; list; list = list->next, i++)
464                 mono_array_set (res, gpointer, i, list->data);
465
466         return res;
467 }
468
469 /* mono_arch_find_jit_info:
470  *
471  * This function is used to gather information from @ctx. It return the 
472  * MonoJitInfo of the corresponding function, unwinds one stack frame and
473  * stores the resulting context into @new_ctx. It also stores a string 
474  * describing the stack location into @trace (if not NULL), and modifies
475  * the @lmf if necessary. @native_offset return the IP offset from the 
476  * start of the function or -1 if that info is not available.
477  */
478 MonoJitInfo *
479 mono_arch_find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoJitInfo *res, MonoJitInfo *prev_ji, MonoContext *ctx,
480                                                  MonoContext *new_ctx, MonoLMF **lmf, gboolean *managed)
481 {
482         MonoJitInfo *ji;
483         gpointer ip = MONO_CONTEXT_GET_IP (ctx);
484         MonoPPCStackFrame *sframe;
485
486         /* Avoid costly table lookup during stack overflow */
487         if (prev_ji && (ip > prev_ji->code_start && ((guint8*)ip < ((guint8*)prev_ji->code_start) + prev_ji->code_size)))
488                 ji = prev_ji;
489         else
490                 ji = mono_jit_info_table_find (domain, ip);
491
492         if (managed)
493                 *managed = FALSE;
494
495         if (ji != NULL) {
496                 gint32 address;
497                 int offset, i;
498
499                 *new_ctx = *ctx;
500                 setup_context (new_ctx);
501
502                 if (*lmf && (MONO_CONTEXT_GET_BP (ctx) >= (gpointer)(*lmf)->ebp)) {
503                         /* remove any unused lmf */
504                         *lmf = (*lmf)->previous_lmf;
505                 }
506
507                 address = (char *)ip - (char *)ji->code_start;
508
509                 if (managed)
510                         if (!ji->method->wrapper_type)
511                                 *managed = TRUE;
512
513                 sframe = (MonoPPCStackFrame*)MONO_CONTEXT_GET_BP (ctx);
514                 MONO_CONTEXT_SET_BP (new_ctx, sframe->sp);
515                 if (ji->method->save_lmf) {
516                         memcpy (&new_ctx->fregs, (char*)sframe->sp - sizeof (double) * MONO_SAVED_FREGS, sizeof (double) * MONO_SAVED_FREGS);
517                         memcpy (&new_ctx->regs, (char*)sframe->sp - sizeof (double) * MONO_SAVED_FREGS - sizeof (gulong) * MONO_SAVED_GREGS, sizeof (gulong) * MONO_SAVED_GREGS);
518                 } else if (ji->used_regs) {
519                         /* keep updated with emit_prolog in mini-ppc.c */
520                         offset = 0;
521                         /* FIXME handle floating point args 
522                         for (i = 31; i >= 14; --i) {
523                                 if (ji->used_fregs & (1 << i)) {
524                                         offset += sizeof (double);
525                                         new_ctx->fregs [i - 14] = *(gulong*)((char*)sframe->sp - offset);
526                                 }
527                         }*/
528                         for (i = 31; i >= 13; --i) {
529                                 if (ji->used_regs & (1 << i)) {
530                                         offset += sizeof (gulong);
531                                         new_ctx->regs [i - 13] = *(gulong*)((char*)sframe->sp - offset);
532                                 }
533                         }
534                 }
535                 /* the calling IP is in the parent frame */
536                 sframe = (MonoPPCStackFrame*)sframe->sp;
537                 /* we substract 4, so that the IP points into the call instruction */
538                 MONO_CONTEXT_SET_IP (new_ctx, sframe->lr - 4);
539
540                 return ji;
541         } else if (*lmf) {
542                 
543                 *new_ctx = *ctx;
544                 setup_context (new_ctx);
545
546                 if (!(*lmf)->method)
547                         return (gpointer)-1;
548
549                 if ((ji = mono_jit_info_table_find (domain, (gpointer)(*lmf)->eip))) {
550                 } else {
551                         memset (res, 0, sizeof (MonoJitInfo));
552                         res->method = (*lmf)->method;
553                 }
554
555                 /*sframe = (MonoPPCStackFrame*)MONO_CONTEXT_GET_BP (ctx);
556                 MONO_CONTEXT_SET_BP (new_ctx, sframe->sp);
557                 MONO_CONTEXT_SET_IP (new_ctx, sframe->lr);*/
558                 MONO_CONTEXT_SET_BP (new_ctx, (*lmf)->ebp);
559                 MONO_CONTEXT_SET_IP (new_ctx, (*lmf)->eip);
560                 memcpy (&new_ctx->regs, (*lmf)->iregs, sizeof (gulong) * MONO_SAVED_GREGS);
561                 memcpy (&new_ctx->fregs, (*lmf)->fregs, sizeof (double) * MONO_SAVED_FREGS);
562                 *lmf = (*lmf)->previous_lmf;
563
564                 return ji ? ji : res;
565         }
566
567         return NULL;
568 }
569
570 /*
571  * This is the function called from the signal handler
572  */
573 void
574 mono_arch_sigctx_to_monoctx (void *ctx, MonoContext *mctx)
575 {
576         os_ucontext *uc = ctx;
577
578         mctx->sc_ir = UCONTEXT_REG_NIP(uc);
579         mctx->sc_sp = UCONTEXT_REG_Rn(uc, 1);
580         memcpy (&mctx->regs, &UCONTEXT_REG_Rn(uc, 13), sizeof (gulong) * MONO_SAVED_GREGS);
581         memcpy (&mctx->fregs, &UCONTEXT_REG_FPRn(uc, 14), sizeof (double) * MONO_SAVED_FREGS);
582 }
583
584 void
585 mono_arch_monoctx_to_sigctx (MonoContext *mctx, void *ctx)
586 {
587         os_ucontext *uc = ctx;
588
589         UCONTEXT_REG_NIP(uc) = mctx->sc_ir;
590         UCONTEXT_REG_Rn(uc, 1) = mctx->sc_sp;
591         memcpy (&UCONTEXT_REG_Rn(uc, 13), &mctx->regs, sizeof (gulong) * MONO_SAVED_GREGS);
592         memcpy (&UCONTEXT_REG_FPRn(uc, 14), &mctx->fregs, sizeof (double) * MONO_SAVED_FREGS);
593 }
594
595 gpointer
596 mono_arch_ip_from_context (void *sigctx)
597 {
598         os_ucontext *uc = sigctx;
599         return (gpointer)UCONTEXT_REG_NIP(uc);
600 }
601
602 #ifndef __APPLE__
603 static void
604 altstack_handle_and_restore (void *sigctx, gpointer obj, gboolean test_only)
605 {
606         void (*restore_context) (MonoContext *);
607         MonoContext mctx;
608
609         restore_context = mono_arch_get_restore_context ();
610         mono_arch_sigctx_to_monoctx (sigctx, &mctx);
611         arch_handle_exception (&mctx, obj, test_only);
612         restore_context (&mctx);
613 }
614
615 void
616 mono_arch_handle_altstack_exception (void *sigctx, gpointer fault_addr, gboolean stack_ovf)
617 {
618 #ifdef MONO_ARCH_USE_SIGACTION
619         ucontext_t *uc = (ucontext_t*)sigctx;
620         ucontext_t *uc_copy;
621         MonoJitInfo *ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context (sigctx));
622         gpointer *sp;
623         int frame_size;
624
625         if (stack_ovf) {
626                 const char *method;
627                 /* we don't do much now, but we can warn the user with a useful message */
628                 fprintf (stderr, "Stack overflow: IP: %p, SP: %p\n", mono_arch_ip_from_context (sigctx), (gpointer)UCONTEXT_REG_Rn(uc, 1));
629                 if (ji && ji->method)
630                         method = mono_method_full_name (ji->method, TRUE);
631                 else
632                         method = "Unmanaged";
633                 fprintf (stderr, "At %s\n", method);
634                 abort ();
635         }
636         if (!ji)
637                 mono_handle_native_sigsegv (SIGSEGV, sigctx);
638         /* setup a call frame on the real stack so that control is returned there
639          * and exception handling can continue.
640          * The frame looks like:
641          *   ucontext struct
642          *   ...
643          * 224 is the size of the red zone
644          */
645         frame_size = sizeof (ucontext_t) + sizeof (gpointer) * 16 + 224;
646         frame_size += 15;
647         frame_size &= ~15;
648         sp = (gpointer)(UCONTEXT_REG_Rn(uc, 1) & ~15);
649         sp = (gpointer)((char*)sp - frame_size);
650         /* may need to adjust pointers in the new struct copy, depending on the OS */
651         uc_copy = (ucontext_t*)(sp + 16);
652         memcpy (uc_copy, uc, sizeof (os_ucontext));
653 #ifdef __linux__
654         uc_copy->uc_mcontext.uc_regs = (char*)uc_copy + offsetof(ucontext_t, uc_mcontext.uc_regs);
655 #endif
656         /* at the return form the signal handler execution starts in altstack_handle_and_restore() */
657         UCONTEXT_REG_LNK(uc) = UCONTEXT_REG_NIP(uc);
658         UCONTEXT_REG_NIP(uc) = (unsigned long)altstack_handle_and_restore;
659         UCONTEXT_REG_Rn(uc, 1) = (unsigned long)sp;
660         UCONTEXT_REG_Rn(uc, PPC_FIRST_ARG_REG) = (unsigned long)(sp + 16);
661         UCONTEXT_REG_Rn(uc, PPC_FIRST_ARG_REG + 1) = 0;
662         UCONTEXT_REG_Rn(uc, PPC_FIRST_ARG_REG + 2) = 0;
663 #endif
664 }
665
666 #endif
667
668 gboolean
669 mono_arch_handle_exception (void *ctx, gpointer obj, gboolean test_only)
670 {
671         MonoContext mctx;
672         gboolean result;
673
674         mono_arch_sigctx_to_monoctx (ctx, &mctx);
675
676         result = arch_handle_exception (&mctx, obj, test_only);
677         /* restore the context so that returning from the signal handler will invoke
678          * the catch clause 
679          */
680         mono_arch_monoctx_to_sigctx (&mctx, ctx);
681         return result;
682 }
683
684 /**
685  * arch_handle_exception:
686  * @ctx: saved processor state
687  * @obj: the exception object
688  * @test_only: only test if the exception is caught, but dont call handlers
689  *
690  *
691  */
692 static gboolean
693 arch_handle_exception (MonoContext *ctx, gpointer obj, gboolean test_only)
694 {
695         MonoDomain *domain = mono_domain_get ();
696         MonoJitInfo *ji, rji;
697         static int (*call_filter) (MonoContext *, gpointer, gpointer) = NULL;
698         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
699         MonoLMF *lmf = jit_tls->lmf;            
700         GList *trace_ips = NULL;
701         MonoException *mono_ex;
702         MonoArray *initial_trace_ips = NULL;
703         int frame_count = 0;
704         gboolean has_dynamic_methods = FALSE;
705
706         g_assert (ctx != NULL);
707         if (!obj) {
708                 MonoException *ex = mono_get_exception_null_reference ();
709                 ex->message = mono_string_new (domain, 
710                         "Object reference not set to an instance of an object");
711                 obj = (MonoObject *)ex;
712         } 
713
714         if (mono_object_isinst (obj, mono_defaults.exception_class)) {
715                 mono_ex = (MonoException*)obj;
716                 initial_trace_ips = mono_ex->trace_ips;
717         } else {
718                 mono_ex = NULL;
719         }
720
721
722         if (!call_filter)
723                 call_filter = mono_arch_get_call_filter ();
724
725         g_assert (jit_tls->end_of_stack);
726         g_assert (jit_tls->abort_func);
727
728         if (!test_only) {
729                 MonoContext ctx_cp = *ctx;
730                 setup_context (&ctx_cp);
731                 if (mono_jit_trace_calls != NULL)
732                         g_print ("EXCEPTION handling: %s\n", mono_object_class (obj)->name);
733                 if (!arch_handle_exception (&ctx_cp, obj, TRUE)) {
734                         if (mono_break_on_exc)
735                                 G_BREAKPOINT ();
736                         mono_unhandled_exception (obj);
737                 }
738         }
739
740         memset (&rji, 0, sizeof (rji));
741
742         while (1) {
743                 MonoContext new_ctx;
744
745                 setup_context (&new_ctx);
746                 ji = mono_find_jit_info (domain, jit_tls, &rji, &rji, ctx, &new_ctx, 
747                                               NULL, &lmf, NULL, NULL);
748                 if (!ji) {
749                         g_warning ("Exception inside function without unwind info");
750                         g_assert_not_reached ();
751                 }
752
753                 if (ji != (gpointer)-1) {
754                         frame_count ++;
755                         
756                         if (test_only && ji->method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE && mono_ex) {
757                                 /* 
758                                  * Avoid overwriting the stack trace if the exception is
759                                  * rethrown. Also avoid giant stack traces during a stack
760                                  * overflow.
761                                  */
762                                 if (!initial_trace_ips && (frame_count < 1000)) {
763                                         trace_ips = g_list_prepend (trace_ips, MONO_CONTEXT_GET_IP (ctx));
764
765                                 }
766                         }
767
768                         if (ji->method->dynamic)
769                                 has_dynamic_methods = TRUE;
770
771                         if (ji->num_clauses) {
772                                 int i;
773                                 
774                                 g_assert (ji->clauses);
775                         
776                                 for (i = 0; i < ji->num_clauses; i++) {
777                                         MonoJitExceptionInfo *ei = &ji->clauses [i];
778                                         gboolean filtered = FALSE;
779
780                                         if (ei->try_start <= MONO_CONTEXT_GET_IP (ctx) && 
781                                             MONO_CONTEXT_GET_IP (ctx) <= ei->try_end) { 
782                                                 /* catch block */
783
784                                                 if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE) || (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)) {
785                                                         /* store the exception object int cfg->excvar */
786                                                         g_assert (ei->exvar_offset);
787                                                         /* need to use the frame pointer (ppc_r31), not r1 (regs start from register r13): methods with clauses always have r31 */
788                                                         *((gpointer *)((char *)(ctx->regs [ppc_r31-13]) + ei->exvar_offset)) = obj;
789                                                 }
790
791                                                 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
792                                                         filtered = call_filter (ctx, ei->data.filter, mono_ex);
793
794                                                 if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE && 
795                                                      mono_object_isinst (obj, ei->data.catch_class)) || filtered) {
796                                                         if (test_only) {
797                                                                 if (mono_ex && !initial_trace_ips) {
798                                                                         trace_ips = g_list_reverse (trace_ips);
799                                                                         mono_ex->trace_ips = glist_to_array (trace_ips, mono_defaults.int_class);
800                                                                         if (has_dynamic_methods)
801                                                                                 /* These methods could go away anytime, so compute the stack trace now */
802                                                                                 mono_ex->stack_trace = ves_icall_System_Exception_get_trace (mono_ex);
803                                                                 }
804                                                                 g_list_free (trace_ips);
805                                                                 return TRUE;
806                                                         }
807                                                         if (mono_jit_trace_calls != NULL)
808                                                                 g_print ("EXCEPTION: catch found at clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
809                                                         /*printf ("stack for catch: %p\n", MONO_CONTEXT_GET_BP (ctx));*/
810                                                         MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
811                                                         jit_tls->lmf = lmf;
812                                                         return 0;
813                                                 }
814                                                 if (!test_only && ei->try_start <= MONO_CONTEXT_GET_IP (ctx) && 
815                                                     MONO_CONTEXT_GET_IP (ctx) < ei->try_end &&
816                                                     (ei->flags == MONO_EXCEPTION_CLAUSE_FAULT)) {
817                                                         if (mono_jit_trace_calls != NULL)
818                                                                 g_print ("EXCEPTION: fault clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
819                                                         call_filter (ctx, ei->handler_start, NULL);
820                                                 }
821                                                 if (!test_only && ei->try_start <= MONO_CONTEXT_GET_IP (ctx) && 
822                                                     MONO_CONTEXT_GET_IP (ctx) < ei->try_end &&
823                                                     (ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)) {
824                                                         if (mono_jit_trace_calls != NULL)
825                                                                 g_print ("EXCEPTION: finally clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
826                                                         call_filter (ctx, ei->handler_start, NULL);
827                                                 }
828                                                 
829                                         }
830                                 }
831                         }
832                 }
833
834                 *ctx = new_ctx;
835                 setup_context (ctx);
836
837                 if ((ji == (gpointer)-1) || MONO_CONTEXT_GET_BP (ctx) >= jit_tls->end_of_stack) {
838                         if (!test_only) {
839                                 jit_tls->lmf = lmf;
840                                 jit_tls->abort_func (obj);
841                                 g_assert_not_reached ();
842                         } else {
843                                 if (mono_ex && !initial_trace_ips) {
844                                         trace_ips = g_list_reverse (trace_ips);
845                                         mono_ex->trace_ips = glist_to_array (trace_ips, mono_defaults.int_class);
846                                         if (has_dynamic_methods)
847                                                 /* These methods could go away anytime, so compute the stack trace now */
848                                                 mono_ex->stack_trace = ves_icall_System_Exception_get_trace (mono_ex);
849                                 }
850                                 g_list_free (trace_ips);
851                                 return FALSE;
852                         }
853                 }
854         }
855
856         g_assert_not_reached ();
857 }
858
859 gboolean
860 mono_arch_has_unwind_info (gconstpointer addr)
861 {
862         return FALSE;
863 }
864