2004-01-09 Zoltan Varga <vargaz@freemail.hu>
[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
16 #include <mono/arch/ppc/ppc-codegen.h>
17 #include <mono/metadata/appdomain.h>
18 #include <mono/metadata/tabledefs.h>
19 #include <mono/metadata/threads.h>
20 #include <mono/metadata/debug-helpers.h>
21 #include <mono/metadata/exception.h>
22 #include <mono/metadata/mono-debug.h>
23
24 #include "mini.h"
25 #include "mini-ppc.h"
26
27 typedef struct sigcontext MonoContext;
28
29 /*
30
31 struct sigcontext {
32     int      sc_onstack;     // sigstack state to restore 
33     int      sc_mask;        // signal mask to restore 
34     int      sc_ir;          // pc 
35     int      sc_psw;         // processor status word 
36     int      sc_sp;          // stack pointer if sc_regs == NULL 
37     void    *sc_regs;        // (kernel private) saved state 
38 };
39
40 struct ucontext {
41         int             uc_onstack;
42         sigset_t        uc_sigmask;     // signal mask used by this context 
43         stack_t         uc_stack;       // stack used by this context 
44         struct ucontext *uc_link;       // pointer to resuming context 
45         size_t          uc_mcsize;      // size of the machine context passed in 
46         mcontext_t      uc_mcontext;    // machine specific context 
47 };
48
49 typedef struct ppc_exception_state {
50         unsigned long dar;      // Fault registers for coredump 
51         unsigned long dsisr;
52         unsigned long exception;// number of powerpc exception taken 
53         unsigned long pad0;     // align to 16 bytes 
54
55         unsigned long pad1[4];  // space in PCB "just in case" 
56 } ppc_exception_state_t;
57
58 typedef struct ppc_vector_state {
59         unsigned long   save_vr[32][4];
60         unsigned long   save_vscr[4];
61         unsigned int    save_pad5[4];
62         unsigned int    save_vrvalid;                   // VRs that have been saved 
63         unsigned int    save_pad6[7];
64 } ppc_vector_state_t;
65
66 typedef struct ppc_float_state {
67         double  fpregs[32];
68
69         unsigned int fpscr_pad; // fpscr is 64 bits, 32 bits of rubbish 
70         unsigned int fpscr;     // floating point status register 
71 } ppc_float_state_t;
72
73 typedef struct ppc_thread_state {
74         unsigned int srr0;      // Instruction address register (PC) 
75         unsigned int srr1;      // Machine state register (supervisor) 
76         unsigned int r0;
77         unsigned int r1;
78         unsigned int r2;
79         ... 
80         unsigned int r31;
81         unsigned int cr;        // Condition register 
82         unsigned int xer;       // User's integer exception register 
83         unsigned int lr;        // Link register 
84         unsigned int ctr;       // Count register 
85         unsigned int mq;        // MQ register (601 only) 
86
87         unsigned int vrsave;    // Vector Save Register 
88 } ppc_thread_state_t;
89
90 struct mcontext {
91         ppc_exception_state_t   es;
92         ppc_thread_state_t      ss;
93         ppc_float_state_t       fs;
94         ppc_vector_state_t      vs;
95 };
96
97 typedef struct mcontext  * mcontext_t;
98
99 */
100
101 #ifdef __APPLE__
102
103 /* we have the stack pointer, not the base pointer in sigcontext */
104 #define MONO_CONTEXT_SET_IP(ctx,ip) do { (ctx)->sc_ir = (int)ip; } while (0); 
105 #define MONO_CONTEXT_SET_BP(ctx,bp) do { (ctx)->sc_sp = (int)bp; } while (0); 
106
107 #define MONO_CONTEXT_GET_IP(ctx) ((gpointer)((ctx)->sc_ir))
108 #define MONO_CONTEXT_GET_BP(ctx) ((gpointer)((ctx)->sc_sp))
109
110 typedef struct {
111         unsigned long sp;
112         unsigned long unused1;
113         unsigned long lr;
114 } MonoPPCStackFrame;
115
116 #else /* sigcontext is different on linux/ppc. See /usr/include/asm/ptrace.h. */
117
118 #define MONO_CONTEXT_SET_IP(ctx,ip) do { (ctx)->regs->nip = (unsigned long)ip; } while (0); 
119 #define MONO_CONTEXT_SET_BP(ctx,bp) do { (ctx)->regs->gpr[1] = (unsigned long)bp; } while (0); 
120
121 #define MONO_CONTEXT_GET_IP(ctx) ((gpointer)((ctx)->regs->nip))
122 #define MONO_CONTEXT_GET_BP(ctx) ((gpointer)((ctx)->regs->gpr[1]))
123
124 typedef struct {
125         unsigned long sp;
126         unsigned long lr;
127 } MonoPPCStackFrame;
128
129 #endif
130
131 /* disbale this for now */
132 #undef MONO_USE_EXC_TABLES
133
134 #ifdef MONO_USE_EXC_TABLES
135
136 /*************************************/
137 /*    STACK UNWINDING STUFF          */
138 /*************************************/
139
140 /* These definitions are from unwind-dw2.c in glibc 2.2.5 */
141
142 /* For x86 */
143 #define DWARF_FRAME_REGISTERS 17
144
145 typedef struct frame_state
146 {
147   void *cfa;
148   void *eh_ptr;
149   long cfa_offset;
150   long args_size;
151   long reg_or_offset[DWARF_FRAME_REGISTERS+1];
152   unsigned short cfa_reg;
153   unsigned short retaddr_column;
154   char saved[DWARF_FRAME_REGISTERS+1];
155 } frame_state;
156
157 #if 0
158
159 static long
160 get_sigcontext_reg (struct sigcontext *ctx, int dwarf_regnum)
161 {
162         switch (dwarf_regnum) {
163         case X86_EAX:
164                 return ctx->SC_EAX;
165         case X86_EBX:
166                 return ctx->SC_EBX;
167         case X86_ECX:
168                 return ctx->SC_ECX;
169         case X86_EDX:
170                 return ctx->SC_EDX;
171         case X86_ESI:
172                 return ctx->SC_ESI;
173         case X86_EDI:
174                 return ctx->SC_EDI;
175         case X86_EBP:
176                 return ctx->SC_EBP;
177         case X86_ESP:
178                 return ctx->SC_ESP;
179         default:
180                 g_assert_not_reached ();
181         }
182
183         return 0;
184 }
185
186 static void
187 set_sigcontext_reg (struct sigcontext *ctx, int dwarf_regnum, long value)
188 {
189         switch (dwarf_regnum) {
190         case X86_EAX:
191                 ctx->SC_EAX = value;
192                 break;
193         case X86_EBX:
194                 ctx->SC_EBX = value;
195                 break;
196         case X86_ECX:
197                 ctx->SC_ECX = value;
198                 break;
199         case X86_EDX:
200                 ctx->SC_EDX = value;
201                 break;
202         case X86_ESI:
203                 ctx->SC_ESI = value;
204                 break;
205         case X86_EDI:
206                 ctx->SC_EDI = value;
207                 break;
208         case X86_EBP:
209                 ctx->SC_EBP = value;
210                 break;
211         case X86_ESP:
212                 ctx->SC_ESP = value;
213                 break;
214         case 8:
215                 ctx->SC_EIP = value;
216                 break;
217         default:
218                 g_assert_not_reached ();
219         }
220 }
221
222 typedef struct frame_state * (*framesf) (void *, struct frame_state *);
223
224 static framesf frame_state_for = NULL;
225
226 static gboolean inited = FALSE;
227
228 typedef char ** (*get_backtrace_symbols_type) (void *__const *__array, int __size);
229
230 static get_backtrace_symbols_type get_backtrace_symbols = NULL;
231
232 static void
233 init_frame_state_for (void)
234 {
235         GModule *module;
236
237         /*
238          * There are two versions of __frame_state_for: one in libgcc.a and the
239          * other in glibc.so. We need the version from glibc.
240          * For more info, see this:
241          * http://gcc.gnu.org/ml/gcc/2002-08/msg00192.html
242          */
243         if ((module = g_module_open ("libc.so.6", G_MODULE_BIND_LAZY))) {
244         
245                 if (!g_module_symbol (module, "__frame_state_for", (gpointer*)&frame_state_for))
246                         frame_state_for = NULL;
247
248                 if (!g_module_symbol (module, "backtrace_symbols", (gpointer*)&get_backtrace_symbols)) {
249                         get_backtrace_symbols = NULL;
250                         frame_state_for = NULL;
251                 }
252
253                 g_module_close (module);
254         }
255
256         inited = TRUE;
257 }
258
259 #endif
260
261 gboolean  mono_arch_handle_exception (struct sigcontext *ctx, gpointer obj, gboolean test_only);
262
263 /* mono_arch_has_unwind_info:
264  *
265  * Tests if a function has an DWARF exception table able to restore
266  * all caller saved registers. 
267  */
268 gboolean
269 mono_arch_has_unwind_info (MonoMethod *method)
270 {
271 #if 0
272         struct frame_state state_in;
273         struct frame_state *res;
274
275         if (!inited) 
276                 init_frame_state_for ();
277         
278         if (!frame_state_for)
279                 return FALSE;
280
281         g_assert (method->addr);
282
283         memset (&state_in, 0, sizeof (state_in));
284
285         /* offset 10 is just a guess, but it works for all methods tested */
286         if ((res = frame_state_for ((char *)method->addr + 10, &state_in))) {
287
288                 if (res->saved [X86_EBX] != 1 ||
289                     res->saved [X86_EDI] != 1 ||
290                     res->saved [X86_EBP] != 1 ||
291                     res->saved [X86_ESI] != 1) {
292                         return FALSE;
293                 }
294                 return TRUE;
295         } else {
296                 return FALSE;
297         }
298 #else
299         return FALSE;
300 #endif
301 }
302
303 struct stack_frame
304 {
305   void *next;
306   void *return_address;
307 };
308
309 static MonoJitInfo *
310 ppc_unwind_native_frame (MonoDomain *domain, MonoJitTlsData *jit_tls, struct sigcontext *ctx, 
311                          struct sigcontext *new_ctx, MonoLMF *lmf, char **trace)
312 {
313 #if 0
314         struct stack_frame *frame;
315         gpointer max_stack;
316         MonoJitInfo *ji;
317         struct frame_state state_in;
318         struct frame_state *res;
319
320         if (trace)
321                 *trace = NULL;
322
323         if (!inited) 
324                 init_frame_state_for ();
325
326         if (!frame_state_for)
327                 return FALSE;
328
329         frame = MONO_CONTEXT_GET_BP (ctx);
330
331         max_stack = lmf && lmf->method ? lmf : jit_tls->end_of_stack;
332
333         *new_ctx = *ctx;
334
335         memset (&state_in, 0, sizeof (state_in));
336
337         while ((gpointer)frame->next < (gpointer)max_stack) {
338                 gpointer ip, addr = frame->return_address;
339                 void *cfa;
340                 char *tmp, **symbols;
341
342                 if (trace) {
343                         ip = MONO_CONTEXT_GET_IP (new_ctx);
344                         symbols = get_backtrace_symbols (&ip, 1);
345                         if (*trace)
346                                 tmp = g_strdup_printf ("%s\nin (unmanaged) %s", *trace, symbols [0]);
347                         else
348                                 tmp = g_strdup_printf ("in (unmanaged) %s", symbols [0]);
349
350                         free (symbols);
351                         g_free (*trace);
352                         *trace = tmp;
353                 }
354
355                 if ((res = frame_state_for (addr, &state_in))) {        
356                         int i;
357
358                         cfa = (gint8*) (get_sigcontext_reg (new_ctx, res->cfa_reg) + res->cfa_offset);
359                         frame = (struct stack_frame *)((gint8*)cfa - 8);
360                         for (i = 0; i < DWARF_FRAME_REGISTERS + 1; i++) {
361                                 int how = res->saved[i];
362                                 long val;
363                                 g_assert ((how == 0) || (how == 1));
364                         
365                                 if (how == 1) {
366                                         val = * (long*) ((gint8*)cfa + res->reg_or_offset[i]);
367                                         set_sigcontext_reg (new_ctx, i, val);
368                                 }
369                         }
370                         new_ctx->SC_ESP = (long)cfa;
371
372                         if (res->saved [X86_EBX] == 1 &&
373                             res->saved [X86_EDI] == 1 &&
374                             res->saved [X86_EBP] == 1 &&
375                             res->saved [X86_ESI] == 1 &&
376                             (ji = mono_jit_info_table_find (domain, frame->return_address))) {
377                                 //printf ("FRAME CFA %s\n", mono_method_full_name (ji->method, TRUE));
378                                 return ji;
379                         }
380
381                 } else {
382                         //printf ("FRAME %p %p %p\n", frame, MONO_CONTEXT_GET_IP (new_ctx), mono_jit_info_table_find (domain, MONO_CONTEXT_GET_IP (new_ctx)));
383
384                         MONO_CONTEXT_SET_IP (new_ctx, frame->return_address);
385                         frame = frame->next;
386                         MONO_CONTEXT_SET_BP (new_ctx, frame);
387
388                         /* stop if !frame or when we detect an unexpected managed frame */
389                         if (!frame || mono_jit_info_table_find (domain, frame->return_address)) {
390                                 if (trace) {
391                                         g_free (*trace);
392                                         *trace = NULL;
393                                 }
394                                 return NULL;
395                         }
396                 }
397         }
398
399         //if (!lmf)
400         //g_assert_not_reached ();
401
402         if (trace) {
403                 g_free (*trace);
404                 *trace = NULL;
405         }
406 #endif
407         return NULL;
408 }
409
410 #endif
411
412 /*
413  * arch_get_restore_context:
414  *
415  * Returns a pointer to a method which restores a previously saved sigcontext.
416  */
417 static gpointer
418 arch_get_restore_context (void)
419 {
420         static guint8 *start = NULL;
421         guint8 *code;
422
423         if (start)
424                 return start;
425
426 #if 0
427         /* restore_contect (struct sigcontext *ctx) */
428         /* we do not restore X86_EAX, X86_EDX */
429
430         start = code = g_malloc (1024);
431         
432         /* load ctx */
433         x86_mov_reg_membase (code, X86_EAX, X86_ESP, 4, 4);
434
435         /* get return address, stored in EDX */
436         x86_mov_reg_membase (code, X86_EDX, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, SC_EIP), 4);
437         /* restore EBX */
438         x86_mov_reg_membase (code, X86_EBX, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, SC_EBX), 4);
439         /* restore EDI */
440         x86_mov_reg_membase (code, X86_EDI, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, SC_EDI), 4);
441         /* restore ESI */
442         x86_mov_reg_membase (code, X86_ESI, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, SC_ESI), 4);
443         /* restore ESP */
444         x86_mov_reg_membase (code, X86_ESP, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, SC_ESP), 4);
445         /* restore EBP */
446         x86_mov_reg_membase (code, X86_EBP, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, SC_EBP), 4);
447
448         /* jump to the saved IP */
449         x86_jump_reg (code, X86_EDX);
450
451 #endif
452         return start;
453 }
454
455 /*
456  * arch_get_call_filter:
457  *
458  * Returns a pointer to a method which calls an exception filter. We
459  * also use this function to call finally handlers (we pass NULL as 
460  * @exc object in this case).
461  */
462 static gpointer
463 arch_get_call_filter (void)
464 {
465         static guint8 start [196];
466         static int inited = 0;
467         guint8 *code;
468         int alloc_size, pos, i;
469
470         if (inited)
471                 return start;
472
473         inited = 1;
474         /* call_filter (struct sigcontext *ctx, unsigned long eip, gpointer exc) */
475         code = start;
476
477         ppc_mflr (code, ppc_r0);
478         ppc_stw (code, ppc_r0, PPC_RET_ADDR_OFFSET, ppc_sp);
479         alloc_size = PPC_MINIMAL_STACK_SIZE + (sizeof (gulong) * 14 + sizeof (gdouble) * 14);
480         // align to PPC_STACK_ALIGNMENT bytes
481         if (alloc_size & (PPC_STACK_ALIGNMENT - 1))
482                 alloc_size += PPC_STACK_ALIGNMENT - (alloc_size & (PPC_STACK_ALIGNMENT - 1));
483         ppc_stwu (code, ppc_sp, -alloc_size, ppc_sp);
484         /* save all the regs on the stack */
485         pos = PPC_MINIMAL_STACK_SIZE;
486         ppc_stmw (code, ppc_r13, ppc_sp, pos);
487         pos += sizeof (gulong) * 19;
488         for (i = 14; i < 32; ++i) {
489                 ppc_stfd (code, i, pos, ppc_sp);
490                 pos += sizeof (gdouble);
491         }
492         /* FIXME: restore all the regs from ctx (in r3) */
493         /* call handler at eip (r4) and set the first arg with the exception (r5) */
494         ppc_mtctr (code, ppc_r4);
495         ppc_mr (code, ppc_r3, ppc_r5);
496         ppc_bcctrl (code, PPC_BR_ALWAYS, 0);
497         /* restore all the regs from the stack */
498         pos = PPC_MINIMAL_STACK_SIZE;
499         ppc_lmw (code, ppc_r13, ppc_sp, pos);
500         pos += sizeof (gulong) * 19;
501         for (i = 14; i < 32; ++i) {
502                 ppc_lfd (code, i, pos, ppc_sp);
503                 pos += sizeof (gdouble);
504         }
505         ppc_lwz (code, ppc_r0, alloc_size + PPC_RET_ADDR_OFFSET, ppc_sp);
506         ppc_mtlr (code, ppc_r0);
507         ppc_addic (code, ppc_sp, ppc_sp, alloc_size);
508
509         g_assert ((code - start) < sizeof(start));
510         return start;
511 }
512
513 static void
514 throw_exception (MonoObject *exc, unsigned long eip, unsigned long esp, gulong *int_regs, gdouble *fp_regs)
515 {
516         static void (*restore_context) (struct sigcontext *);
517         struct sigcontext ctx;
518
519         if (!restore_context)
520                 restore_context = arch_get_restore_context ();
521
522         /* adjust eip so that it point into the call instruction */
523         eip -= 4;
524
525         MONO_CONTEXT_SET_BP (&ctx, esp);
526         MONO_CONTEXT_SET_IP (&ctx, eip);
527 #if 0
528         ctx.SC_ESP = esp;
529         ctx.SC_EIP = eip;
530         ctx.SC_EBP = ebp;
531         ctx.SC_EDI = edi;
532         ctx.SC_ESI = esi;
533         ctx.SC_EBX = ebx;
534         ctx.SC_EDX = edx;
535         ctx.SC_ECX = ecx;
536         ctx.SC_EAX = eax;
537 #endif  
538         mono_arch_handle_exception (&ctx, exc, FALSE);
539         restore_context (&ctx);
540
541         g_assert_not_reached ();
542 }
543
544 /**
545  * arch_get_throw_exception_generic:
546  *
547  * Returns a function pointer which can be used to raise 
548  * exceptions. The returned function has the following 
549  * signature: void (*func) (MonoException *exc); or
550  * void (*func) (char *exc_name);
551  *
552  */
553 static gpointer 
554 mono_arch_get_throw_exception_generic (guint8 *start, int size, int by_name)
555 {
556         guint8 *code;
557         int alloc_size, pos, i;
558
559         code = start;
560
561         ppc_mflr (code, ppc_r0);
562         ppc_stw (code, ppc_r0, PPC_RET_ADDR_OFFSET, ppc_sp);
563         alloc_size = PPC_MINIMAL_STACK_SIZE + (sizeof (gulong) * 14 + sizeof (gdouble) * 14);
564         // align to PPC_STACK_ALIGNMENT bytes
565         if (alloc_size & (PPC_STACK_ALIGNMENT - 1))
566                 alloc_size += PPC_STACK_ALIGNMENT - (alloc_size & (PPC_STACK_ALIGNMENT - 1));
567         ppc_stwu (code, ppc_sp, -alloc_size, ppc_sp);
568         //ppc_break (code);
569         if (by_name) {
570                 ppc_mr (code, ppc_r5, ppc_r3);
571                 ppc_load (code, ppc_r3, mono_defaults.corlib);
572                 ppc_load (code, ppc_r4, "System");
573                 ppc_bl (code, 0);
574                 ppc_patch (code - 4, mono_exception_from_name);
575         }
576         /* save all the regs on the stack */
577         pos = PPC_MINIMAL_STACK_SIZE;
578         ppc_stmw (code, ppc_r13, ppc_sp, pos);
579         pos += sizeof (gulong) * 19;
580         for (i = 14; i < 32; ++i) {
581                 ppc_stfd (code, i, pos, ppc_sp);
582                 pos += sizeof (gdouble);
583         }
584         /* call throw_exception (exc, ip, sp, int_regs, fp_regs) */
585         /* exc is already in place in r3 */
586         if (by_name)
587                 ppc_mflr (code, ppc_r4);
588         else
589                 ppc_mr (code, ppc_r4, ppc_r0); /* caller ip */
590         ppc_lwz (code, ppc_r5, 0, ppc_sp); /* caller sp */
591         /* pointer to the saved int regs */
592         pos = PPC_MINIMAL_STACK_SIZE;
593         ppc_addi (code, ppc_r6, ppc_sp, pos);
594         /* pointer to the saved fp regs */
595         pos += sizeof (gulong) * 19;
596         ppc_addi (code, ppc_r7, ppc_sp, pos);
597         ppc_bl (code, 0);
598         ppc_patch (code - 4, throw_exception);
599         /* we should never reach this breakpoint */
600         ppc_break (code);
601         g_assert ((code - start) < size);
602         return start;
603 }
604
605 /**
606  * arch_get_throw_exception:
607  *
608  * Returns a function pointer which can be used to raise 
609  * exceptions. The returned function has the following 
610  * signature: void (*func) (MonoException *exc); 
611  * For example to raise an arithmetic exception you can use:
612  *
613  * x86_push_imm (code, mono_get_exception_arithmetic ()); 
614  * x86_call_code (code, arch_get_throw_exception ()); 
615  *
616  */
617 gpointer 
618 mono_arch_get_throw_exception (void)
619 {
620         static guint8 start [128];
621         static int inited = 0;
622
623         if (inited)
624                 return start;
625         mono_arch_get_throw_exception_generic (start, sizeof (start), FALSE);
626         inited = 1;
627         return start;
628 }
629
630 /**
631  * arch_get_throw_exception_by_name:
632  *
633  * Returns a function pointer which can be used to raise 
634  * corlib exceptions. The returned function has the following 
635  * signature: void (*func) (char *exc_name); 
636  * For example to raise an arithmetic exception you can use:
637  *
638  * x86_push_imm (code, "ArithmeticException"); 
639  * x86_call_code (code, arch_get_throw_exception_by_name ()); 
640  *
641  */
642 gpointer 
643 mono_arch_get_throw_exception_by_name (void)
644 {
645         static guint8 start [160];
646         static int inited = 0;
647
648         if (inited)
649                 return start;
650         mono_arch_get_throw_exception_generic (start, sizeof (start), TRUE);
651         inited = 1;
652         return start;
653 }       
654
655 static MonoArray *
656 glist_to_array (GList *list) 
657 {
658         MonoDomain *domain = mono_domain_get ();
659         MonoArray *res;
660         int len, i;
661
662         if (!list)
663                 return NULL;
664
665         len = g_list_length (list);
666         res = mono_array_new (domain, mono_defaults.int_class, len);
667
668         for (i = 0; list; list = list->next, i++)
669                 mono_array_set (res, gpointer, i, list->data);
670
671         return res;
672 }
673
674 /* mono_arch_find_jit_info:
675  *
676  * This function is used to gather information from @ctx. It return the 
677  * MonoJitInfo of the corresponding function, unwinds one stack frame and
678  * stores the resulting context into @new_ctx. It also stores a string 
679  * describing the stack location into @trace (if not NULL), and modifies
680  * the @lmf if necessary. @native_offset return the IP offset from the 
681  * start of the function or -1 if that info is not available.
682  */
683 static MonoJitInfo *
684 mono_arch_find_jit_info (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoJitInfo *res, MonoContext *ctx, 
685                          MonoContext *new_ctx, char **trace, MonoLMF **lmf, int *native_offset,
686                          gboolean *managed)
687 {
688         MonoJitInfo *ji;
689         gpointer ip = MONO_CONTEXT_GET_IP (ctx);
690         unsigned long *ptr;
691         char *p;
692         MonoPPCStackFrame *sframe;
693
694         ji = mono_jit_info_table_find (domain, ip);
695
696         if (trace)
697                 *trace = NULL;
698
699         if (native_offset)
700                 *native_offset = -1;
701
702         if (managed)
703                 *managed = FALSE;
704
705         if (ji != NULL) {
706                 char *source_location, *tmpaddr, *fname;
707                 gint32 address, iloffset;
708                 int offset;
709
710                 *new_ctx = *ctx;
711
712                 if (*lmf && (MONO_CONTEXT_GET_BP (ctx) >= (gpointer)(*lmf)->ebp)) {
713                         /* remove any unused lmf */
714                         *lmf = (*lmf)->previous_lmf;
715                 }
716
717                 address = (char *)ip - (char *)ji->code_start;
718
719                 if (native_offset)
720                         *native_offset = address;
721
722                 if (managed)
723                         if (!ji->method->wrapper_type)
724                                 *managed = TRUE;
725
726                 if (trace) {
727                         source_location = mono_debug_source_location_from_address (ji->method, address, NULL, domain);
728                         iloffset = mono_debug_il_offset_from_address (ji->method, address, domain);
729
730                         if (iloffset < 0)
731                                 tmpaddr = g_strdup_printf ("<0x%05x>", address);
732                         else
733                                 tmpaddr = g_strdup_printf ("[0x%05x]", iloffset);
734                 
735                         fname = mono_method_full_name (ji->method, TRUE);
736
737                         if (source_location)
738                                 *trace = g_strdup_printf ("in %s (at %s) %s", tmpaddr, source_location, fname);
739                         else
740                                 *trace = g_strdup_printf ("in %s %s", tmpaddr, fname);
741
742                         g_free (fname);
743                         g_free (source_location);
744                         g_free (tmpaddr);
745                 }
746 #if 0                           
747                 offset = -1;
748                 /* restore caller saved registers */
749                 if (ji->used_regs & X86_EBX_MASK) {
750                         new_ctx->SC_EBX = *((int *)ctx->SC_EBP + offset);
751                         offset--;
752                 }
753                 if (ji->used_regs & X86_EDI_MASK) {
754                         new_ctx->SC_EDI = *((int *)ctx->SC_EBP + offset);
755                         offset--;
756                 }
757                 if (ji->used_regs & X86_ESI_MASK) {
758                         new_ctx->SC_ESI = *((int *)ctx->SC_EBP + offset);
759                 }
760
761                 new_ctx->SC_ESP = ctx->SC_EBP;
762                 /* we substract 1, so that the IP points into the call instruction */
763                 new_ctx->SC_EIP = *((int *)ctx->SC_EBP + 1) - 1;
764                 new_ctx->SC_EBP = *((int *)ctx->SC_EBP);
765 #endif
766                 sframe = (MonoPPCStackFrame*)MONO_CONTEXT_GET_BP (ctx);
767                 MONO_CONTEXT_SET_BP (new_ctx, sframe->sp);
768                 MONO_CONTEXT_SET_IP (new_ctx, sframe->lr);
769                 *res = *ji;
770                 return res;
771 #ifdef MONO_USE_EXC_TABLES
772         } else if ((ji = ppc_unwind_native_frame (domain, jit_tls, ctx, new_ctx, *lmf, trace))) {
773                 *res = *ji;
774                 return res;
775 #endif
776         } else if (*lmf) {
777                 
778                 *new_ctx = *ctx;
779
780                 if (!(*lmf)->method)
781                         return (gpointer)-1;
782
783                 if (trace)
784                         *trace = g_strdup_printf ("in (unmanaged) %s", mono_method_full_name ((*lmf)->method, TRUE));
785                 
786                 if ((ji = mono_jit_info_table_find (domain, (gpointer)(*lmf)->eip))) {
787                         *res = *ji;
788                 } else {
789                         memset (res, 0, sizeof (MonoJitInfo));
790                         res->method = (*lmf)->method;
791                 }
792
793 #if 0
794                 new_ctx->SC_ESI = (*lmf)->esi;
795                 new_ctx->SC_EDI = (*lmf)->edi;
796                 new_ctx->SC_EBX = (*lmf)->ebx;
797                 new_ctx->SC_EBP = (*lmf)->ebp;
798                 new_ctx->SC_EIP = (*lmf)->eip;
799                 /* the lmf is always stored on the stack, so the following
800                  * expression points to a stack location which can be used as ESP */
801                 new_ctx->SC_ESP = (unsigned long)&((*lmf)->eip);
802 #endif
803                 sframe = (MonoPPCStackFrame*)MONO_CONTEXT_GET_BP (ctx);
804                 MONO_CONTEXT_SET_BP (new_ctx, sframe->sp);
805                 MONO_CONTEXT_SET_IP (new_ctx, sframe->lr);
806                 *lmf = (*lmf)->previous_lmf;
807
808                 return res;
809                 
810         }
811
812         return NULL;
813 }
814
815 MonoArray *
816 ves_icall_get_trace (MonoException *exc, gint32 skip, MonoBoolean need_file_info)
817 {
818         MonoDomain *domain = mono_domain_get ();
819         MonoArray *res;
820         MonoArray *ta = exc->trace_ips;
821         int i, len;
822         
823         len = mono_array_length (ta);
824
825         res = mono_array_new (domain, mono_defaults.stack_frame_class, len > skip ? len - skip : 0);
826
827         for (i = skip; i < len; i++) {
828                 MonoJitInfo *ji;
829                 MonoStackFrame *sf = (MonoStackFrame *)mono_object_new (domain, mono_defaults.stack_frame_class);
830                 gpointer ip = mono_array_get (ta, gpointer, i);
831
832                 ji = mono_jit_info_table_find (domain, ip);
833                 g_assert (ji != NULL);
834
835                 sf->method = mono_method_get_object (domain, ji->method, NULL);
836                 sf->native_offset = (char *)ip - (char *)ji->code_start;
837
838                 sf->il_offset = mono_debug_il_offset_from_address (ji->method, sf->native_offset, domain);
839
840                 if (need_file_info) {
841                         gchar *filename;
842                         
843                         filename = mono_debug_source_location_from_address (ji->method, sf->native_offset, &sf->line, domain);
844
845                         sf->filename = filename? mono_string_new (domain, filename): NULL;
846                         sf->column = 0;
847
848                         g_free (filename);
849                 }
850
851                 mono_array_set (res, gpointer, i, sf);
852         }
853
854         return res;
855 }
856
857 void
858 mono_jit_walk_stack (MonoStackWalk func, gpointer user_data) {
859         MonoDomain *domain = mono_domain_get ();
860         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
861         MonoLMF *lmf = jit_tls->lmf;
862         MonoJitInfo *ji, rji;
863         gint native_offset, il_offset;
864         gboolean managed;
865         MonoPPCStackFrame *sframe;
866
867         MonoContext ctx, new_ctx;
868
869         __asm__ volatile("lwz   %0,0(r1)" : "=r" (sframe));
870         MONO_CONTEXT_SET_IP (&ctx, sframe->lr);
871         MONO_CONTEXT_SET_BP (&ctx, sframe->sp);
872
873         while (MONO_CONTEXT_GET_BP (&ctx) < jit_tls->end_of_stack) {
874                 
875                 ji = mono_arch_find_jit_info (domain, jit_tls, &rji, &ctx, &new_ctx, NULL, &lmf, &native_offset, &managed);
876                 g_assert (ji);
877
878                 if (ji == (gpointer)-1)
879                         return;
880
881                 il_offset = mono_debug_il_offset_from_address (ji->method, native_offset, domain);
882
883                 if (func (ji->method, native_offset, il_offset, managed, user_data))
884                         return;
885                 
886                 ctx = new_ctx;
887         }
888 }
889
890 MonoBoolean
891 ves_icall_get_frame_info (gint32 skip, MonoBoolean need_file_info, 
892                           MonoReflectionMethod **method, 
893                           gint32 *iloffset, gint32 *native_offset,
894                           MonoString **file, gint32 *line, gint32 *column)
895 {
896         MonoDomain *domain = mono_domain_get ();
897         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
898         MonoLMF *lmf = jit_tls->lmf;
899         MonoJitInfo *ji, rji;
900         MonoContext ctx, new_ctx;
901
902         MONO_CONTEXT_SET_IP (&ctx, ves_icall_get_frame_info);
903         MONO_CONTEXT_SET_BP (&ctx, __builtin_frame_address (0));
904
905         skip++;
906
907         do {
908                 ji = mono_arch_find_jit_info (domain, jit_tls, &rji, &ctx, &new_ctx, NULL, &lmf, native_offset, NULL);
909
910                 ctx = new_ctx;
911                 
912                 if (!ji || ji == (gpointer)-1 || MONO_CONTEXT_GET_BP (&ctx) >= jit_tls->end_of_stack)
913                         return FALSE;
914
915                 /* skip all wrappers ??*/
916                 if (ji->method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE ||
917                     ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK ||
918                     ji->method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE)
919                         continue;
920
921                 skip--;
922
923         } while (skip >= 0);
924
925         *method = mono_method_get_object (domain, ji->method, NULL);
926         *iloffset = mono_debug_il_offset_from_address (ji->method, *native_offset, domain);
927
928         if (need_file_info) {
929                 gchar *filename;
930
931                 filename = mono_debug_source_location_from_address (ji->method, *native_offset, line, domain);
932
933                 *file = filename? mono_string_new (domain, filename): NULL;
934                 *column = 0;
935
936                 g_free (filename);
937         }
938
939         return TRUE;
940 }
941
942 /**
943  * arch_handle_exception:
944  * @ctx: saved processor state
945  * @obj: the exception object
946  * @test_only: only test if the exception is caught, but dont call handlers
947  *
948  *
949  */
950 gboolean
951 mono_arch_handle_exception (MonoContext *ctx, gpointer obj, gboolean test_only)
952 {
953         MonoDomain *domain = mono_domain_get ();
954         MonoJitInfo *ji, rji;
955         static int (*call_filter) (MonoContext *, gpointer, gpointer) = NULL;
956         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
957         MonoLMF *lmf = jit_tls->lmf;            
958         GList *trace_ips = NULL;
959         MonoException *mono_ex;
960
961         g_assert (ctx != NULL);
962         if (!obj) {
963                 MonoException *ex = mono_get_exception_null_reference ();
964                 ex->message = mono_string_new (domain, 
965                         "Object reference not set to an instance of an object");
966                 obj = (MonoObject *)ex;
967         } 
968
969         if (mono_object_isinst (obj, mono_defaults.exception_class)) {
970                 mono_ex = (MonoException*)obj;
971                 mono_ex->stack_trace = NULL;
972         } else {
973                 mono_ex = NULL;
974         }
975
976
977         if (!call_filter)
978                 call_filter = arch_get_call_filter ();
979
980         g_assert (jit_tls->end_of_stack);
981         g_assert (jit_tls->abort_func);
982
983         if (!test_only) {
984                 MonoContext ctx_cp = *ctx;
985                 if (mono_jit_trace_calls != NULL)
986                         g_print ("EXCEPTION handling: %s\n", mono_object_class (obj)->name);
987                 if (!mono_arch_handle_exception (&ctx_cp, obj, TRUE)) {
988                         if (mono_break_on_exc)
989                                 G_BREAKPOINT ();
990                         mono_unhandled_exception (obj);
991                 }
992         }
993
994         while (1) {
995                 MonoContext new_ctx;
996                 char *trace = NULL;
997                 
998                 ji = mono_arch_find_jit_info (domain, jit_tls, &rji, ctx, &new_ctx, 
999                                               test_only ? &trace : NULL, &lmf, NULL, NULL);
1000                 if (!ji) {
1001                         g_warning ("Exception inside function without unwind info");
1002                         g_assert_not_reached ();
1003                 }
1004
1005                 if (ji != (gpointer)-1) {
1006                         
1007                         if (test_only && ji->method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE && mono_ex) {
1008                                 char *tmp, *strace;
1009
1010                                 trace_ips = g_list_append (trace_ips, MONO_CONTEXT_GET_IP (ctx));
1011
1012                                 if (!mono_ex->stack_trace)
1013                                         strace = g_strdup ("");
1014                                 else
1015                                         strace = mono_string_to_utf8 (mono_ex->stack_trace);
1016                         
1017                                 tmp = g_strdup_printf ("%s%s\n", strace, trace);
1018                                 g_free (strace);
1019
1020                                 mono_ex->stack_trace = mono_string_new (domain, tmp);
1021
1022                                 g_free (tmp);
1023                         }
1024
1025                         if (ji->num_clauses) {
1026                                 int i;
1027                                 
1028                                 g_assert (ji->clauses);
1029                         
1030                                 for (i = 0; i < ji->num_clauses; i++) {
1031                                         MonoJitExceptionInfo *ei = &ji->clauses [i];
1032
1033                                         if (ei->try_start <= MONO_CONTEXT_GET_IP (ctx) && 
1034                                             MONO_CONTEXT_GET_IP (ctx) <= ei->try_end) { 
1035                                                 /* catch block */
1036                                                 if ((ei->flags == MONO_EXCEPTION_CLAUSE_NONE && 
1037                                                      mono_object_isinst (obj, mono_class_get (ji->method->klass->image, ei->data.token))) ||
1038                                                     ((ei->flags == MONO_EXCEPTION_CLAUSE_FILTER &&
1039                                                       call_filter (ctx, ei->data.filter, obj)))) {
1040                                                         if (test_only) {
1041                                                                 if (mono_ex)
1042                                                                         mono_ex->trace_ips = glist_to_array (trace_ips);
1043                                                                 g_list_free (trace_ips);
1044                                                                 g_free (trace);
1045                                                                 return TRUE;
1046                                                         }
1047                                                         if (mono_jit_trace_calls != NULL)
1048                                                                 g_print ("EXCEPTION: catch found at clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
1049                                                         MONO_CONTEXT_SET_IP (ctx, ei->handler_start);
1050                                                         *((gpointer *)((char *)MONO_CONTEXT_GET_BP (ctx) + ji->exvar_offset)) = obj;
1051                                                         jit_tls->lmf = lmf;
1052                                                         g_free (trace);
1053                                                         return 0;
1054                                                 }
1055                                                 if (!test_only && ei->try_start <= MONO_CONTEXT_GET_IP (ctx) && 
1056                                                     MONO_CONTEXT_GET_IP (ctx) < ei->try_end &&
1057                                                     (ei->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
1058                                                         if (mono_jit_trace_calls != NULL)
1059                                                                 g_print ("EXCEPTION: finally clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
1060                                                         call_filter (ctx, ei->handler_start, NULL);
1061                                                 }
1062                                                 
1063                                         }
1064                                 }
1065                         }
1066                 }
1067
1068                 g_free (trace);
1069                         
1070                 *ctx = new_ctx;
1071
1072                 if ((ji == (gpointer)-1) || MONO_CONTEXT_GET_BP (ctx) >= jit_tls->end_of_stack) {
1073                         if (!test_only) {
1074                                 jit_tls->lmf = lmf;
1075                                 jit_tls->abort_func (obj);
1076                                 g_assert_not_reached ();
1077                         } else {
1078                                 if (mono_ex)
1079                                         mono_ex->trace_ips = glist_to_array (trace_ips);
1080                                 g_list_free (trace_ips);
1081                                 return FALSE;
1082                         }
1083                 }
1084         }
1085
1086         g_assert_not_reached ();
1087 }
1088
1089 gboolean
1090 mono_arch_has_unwind_info (gconstpointer addr)
1091 {
1092         return FALSE;
1093 }
1094