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