Merge pull request #5714 from alexischr/update_bockbuild
[mono.git] / mono / mini / exceptions-ppc.c
1 /**
2  * \file
3  * exception support for PowerPC
4  *
5  * Authors:
6  *   Dietmar Maurer (dietmar@ximian.com)
7  *   Paolo Molaro (lupus@ximian.com)
8  *   Andreas Faerber <andreas.faerber@web.de>
9  *
10  * (C) 2001 Ximian, Inc.
11  * (C) 2007-2008 Andreas Faerber
12  */
13
14 #include <config.h>
15 #include <glib.h>
16 #include <signal.h>
17 #include <string.h>
18 #include <stddef.h>
19 #if HAVE_UCONTEXT_H
20 #include <ucontext.h>
21 #endif
22
23 #include <mono/arch/ppc/ppc-codegen.h>
24 #include <mono/metadata/appdomain.h>
25 #include <mono/metadata/tabledefs.h>
26 #include <mono/metadata/threads.h>
27 #include <mono/metadata/debug-helpers.h>
28 #include <mono/metadata/exception.h>
29 #include <mono/metadata/mono-debug.h>
30
31 #include "mini.h"
32 #include "mini-ppc.h"
33
34 /*
35
36 struct sigcontext {
37     int      sc_onstack;     // sigstack state to restore 
38     int      sc_mask;        // signal mask to restore 
39     int      sc_ir;          // pc 
40     int      sc_psw;         // processor status word 
41     int      sc_sp;          // stack pointer if sc_regs == NULL 
42     void    *sc_regs;        // (kernel private) saved state 
43 };
44
45 struct ucontext {
46         int             uc_onstack;
47         sigset_t        uc_sigmask;     // signal mask used by this context 
48         stack_t         uc_stack;       // stack used by this context 
49         struct ucontext *uc_link;       // pointer to resuming context 
50         size_t          uc_mcsize;      // size of the machine context passed in 
51         mcontext_t      uc_mcontext;    // machine specific context 
52 };
53
54 typedef struct ppc_exception_state {
55         unsigned long dar;      // Fault registers for coredump 
56         unsigned long dsisr;
57         unsigned long exception;// number of powerpc exception taken 
58         unsigned long pad0;     // align to 16 bytes 
59
60         unsigned long pad1[4];  // space in PCB "just in case" 
61 } ppc_exception_state_t;
62
63 typedef struct ppc_vector_state {
64         unsigned long   save_vr[32][4];
65         unsigned long   save_vscr[4];
66         unsigned int    save_pad5[4];
67         unsigned int    save_vrvalid;                   // VRs that have been saved 
68         unsigned int    save_pad6[7];
69 } ppc_vector_state_t;
70
71 typedef struct ppc_float_state {
72         double  fpregs[32];
73
74         unsigned int fpscr_pad; // fpscr is 64 bits, 32 bits of rubbish 
75         unsigned int fpscr;     // floating point status register 
76 } ppc_float_state_t;
77
78 typedef struct ppc_thread_state {
79         unsigned int srr0;      // Instruction address register (PC) 
80         unsigned int srr1;      // Machine state register (supervisor) 
81         unsigned int r0;
82         unsigned int r1;
83         unsigned int r2;
84         ... 
85         unsigned int r31;
86         unsigned int cr;        // Condition register 
87         unsigned int xer;       // User's integer exception register 
88         unsigned int lr;        // Link register 
89         unsigned int ctr;       // Count register 
90         unsigned int mq;        // MQ register (601 only) 
91
92         unsigned int vrsave;    // Vector Save Register 
93 } ppc_thread_state_t;
94
95 struct mcontext {
96         ppc_exception_state_t   es;
97         ppc_thread_state_t      ss;
98         ppc_float_state_t       fs;
99         ppc_vector_state_t      vs;
100 };
101
102 typedef struct mcontext  * mcontext_t;
103
104 Linux/PPC instead has:
105 struct sigcontext {
106         unsigned long   _unused[4];
107         int             signal;
108         unsigned long   handler;
109         unsigned long   oldmask;
110         struct pt_regs  *regs;
111 };
112 struct pt_regs {
113         unsigned long gpr[32];
114         unsigned long nip;
115         unsigned long msr;
116         unsigned long orig_gpr3;        // Used for restarting system calls 
117         unsigned long ctr;
118         unsigned long link;
119         unsigned long xer;
120         unsigned long ccr;
121         unsigned long mq;               // 601 only (not used at present) 
122                                         // Used on APUS to hold IPL value. 
123         unsigned long trap;             // Reason for being here 
124         // N.B. for critical exceptions on 4xx, the dar and dsisr
125         // fields are overloaded to hold srr0 and srr1. 
126         unsigned long dar;              // Fault registers 
127         unsigned long dsisr;            // on 4xx/Book-E used for ESR 
128         unsigned long result;           // Result of a system call 
129 };
130 struct mcontext {
131         elf_gregset_t   mc_gregs;
132         elf_fpregset_t  mc_fregs;
133         unsigned long   mc_pad[2];
134         elf_vrregset_t  mc_vregs __attribute__((__aligned__(16)));
135 };
136
137 struct ucontext {
138         unsigned long    uc_flags;
139         struct ucontext *uc_link;
140         stack_t          uc_stack;
141         int              uc_pad[7];
142         struct mcontext *uc_regs;       // points to uc_mcontext field 
143         sigset_t         uc_sigmask;
144         // glibc has 1024-bit signal masks, ours are 64-bit 
145         int              uc_maskext[30];
146         int              uc_pad2[3];
147         struct mcontext  uc_mcontext;
148 };
149
150 #define ELF_NGREG       48      // includes nip, msr, lr, etc. 
151 #define ELF_NFPREG      33      // includes fpscr 
152
153 // General registers 
154 typedef unsigned long elf_greg_t;
155 typedef elf_greg_t elf_gregset_t[ELF_NGREG];
156
157 // Floating point registers 
158 typedef double elf_fpreg_t;
159 typedef elf_fpreg_t elf_fpregset_t[ELF_NFPREG];
160
161
162 */
163
164
165 #define restore_regs_from_context(ctx_reg,ip_reg,tmp_reg) do {  \
166                 int reg;        \
167                 ppc_ldptr (code, ip_reg, G_STRUCT_OFFSET (MonoContext, sc_ir), ctx_reg);        \
168                 ppc_load_multiple_regs (code, MONO_PPC_FIRST_SAVED_GREG,        \
169                         G_STRUCT_OFFSET (MonoContext, regs) + MONO_PPC_FIRST_SAVED_GREG * sizeof (gpointer), ctx_reg);  \
170                 for (reg = MONO_PPC_FIRST_SAVED_FREG; reg < MONO_MAX_FREGS; ++reg) {    \
171                         ppc_lfd (code, reg,     \
172                                 G_STRUCT_OFFSET(MonoContext, fregs) + reg * sizeof (gdouble), ctx_reg); \
173                 }       \
174         } while (0)
175
176 /* nothing to do */
177 #define setup_context(ctx)
178
179 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
180 guint8*
181 mono_ppc_create_pre_code_ftnptr (guint8 *code)
182 {
183         MonoPPCFunctionDescriptor *ftnptr = (MonoPPCFunctionDescriptor*)code;
184
185         code += sizeof (MonoPPCFunctionDescriptor);
186         ftnptr->code = code;
187         ftnptr->toc = NULL;
188         ftnptr->env = NULL;
189
190         return code;
191 }
192 #endif
193
194 /*
195  * arch_get_restore_context:
196  *
197  * Returns a pointer to a method which restores a previously saved sigcontext.
198  * The first argument in r3 is the pointer to the context.
199  */
200 gpointer
201 mono_arch_get_restore_context (MonoTrampInfo **info, gboolean aot)
202 {
203         guint8 *start, *code;
204         int size = MONO_PPC_32_64_CASE (128, 172) + PPC_FTNPTR_SIZE;
205         MonoJumpInfo *ji = NULL;
206         GSList *unwind_ops = NULL;
207
208         code = start = mono_global_codeman_reserve (size);
209         if (!aot)
210                 code = mono_ppc_create_pre_code_ftnptr (code);
211         restore_regs_from_context (ppc_r3, ppc_r4, ppc_r5);
212         /* restore also the stack pointer */
213         ppc_ldptr (code, ppc_sp, G_STRUCT_OFFSET (MonoContext, sc_sp), ppc_r3);
214         //ppc_break (code);
215         /* jump to the saved IP */
216         ppc_mtctr (code, ppc_r4);
217         ppc_bcctr (code, PPC_BR_ALWAYS, 0);
218         /* never reached */
219         ppc_break (code);
220
221         g_assert ((code - start) <= size);
222         mono_arch_flush_icache (start, code - start);
223         MONO_PROFILER_RAISE (jit_code_buffer, (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL));
224
225         if (info)
226                 *info = mono_tramp_info_create ("restore_context", start, code - start, ji, unwind_ops);
227
228         return start;
229 }
230
231 #define SAVED_REGS_LENGTH               (sizeof (gdouble) * MONO_MAX_FREGS + sizeof (gpointer) * MONO_MAX_IREGS)
232 #define ALIGN_STACK_FRAME_SIZE(s)       (((s) + MONO_ARCH_FRAME_ALIGNMENT - 1) & ~(MONO_ARCH_FRAME_ALIGNMENT - 1))
233 /* The 64 bytes here are for outgoing arguments and a bit of spare.
234    We don't use it all, but it doesn't hurt. */
235 #define REG_SAVE_STACK_FRAME_SIZE       (ALIGN_STACK_FRAME_SIZE (SAVED_REGS_LENGTH + PPC_MINIMAL_STACK_SIZE + 64))
236
237 static guint8*
238 emit_save_saved_regs (guint8 *code, int pos)
239 {
240         int i;
241
242         for (i = MONO_MAX_FREGS - 1; i >= MONO_PPC_FIRST_SAVED_FREG; --i) {
243                 pos -= sizeof (gdouble);
244                 ppc_stfd (code, i, pos, ppc_sp);
245         }
246         pos -= (MONO_MAX_FREGS - MONO_SAVED_FREGS) * sizeof (gdouble);
247         pos -= sizeof (gpointer) * MONO_SAVED_GREGS;
248         ppc_store_multiple_regs (code, MONO_PPC_FIRST_SAVED_GREG, pos, ppc_sp);
249
250         return code;
251 }
252
253 /*
254  * mono_arch_get_call_filter:
255  *
256  * Returns a pointer to a method which calls an exception filter. We
257  * also use this function to call finally handlers (we pass NULL as 
258  * @exc object in this case).
259  */
260 gpointer
261 mono_arch_get_call_filter (MonoTrampInfo **info, gboolean aot)
262 {
263         guint8 *start, *code;
264         int alloc_size, pos, i;
265         int size = MONO_PPC_32_64_CASE (320, 500) + PPC_FTNPTR_SIZE;
266         MonoJumpInfo *ji = NULL;
267         GSList *unwind_ops = NULL;
268
269         /* call_filter (MonoContext *ctx, unsigned long eip, gpointer exc) */
270         code = start = mono_global_codeman_reserve (size);
271         if (!aot)
272                 code = mono_ppc_create_pre_code_ftnptr (code);
273
274         /* store ret addr */
275         ppc_mflr (code, ppc_r0);
276         ppc_stptr (code, ppc_r0, PPC_RET_ADDR_OFFSET, ppc_sp);
277
278         alloc_size = REG_SAVE_STACK_FRAME_SIZE;
279
280         /* allocate stack frame and set link from sp in ctx */
281         g_assert ((alloc_size & (MONO_ARCH_FRAME_ALIGNMENT-1)) == 0);
282         ppc_ldptr (code, ppc_r0, G_STRUCT_OFFSET (MonoContext, sc_sp), ppc_r3);
283         ppc_ldptr_indexed (code, ppc_r0, ppc_r0, ppc_r0);
284         ppc_stptr_update (code, ppc_r0, -alloc_size, ppc_sp);
285
286         code = emit_save_saved_regs (code, alloc_size);
287
288         /* restore all the regs from ctx (in r3), but not r1, the stack pointer */
289         restore_regs_from_context (ppc_r3, ppc_r6, ppc_r7);
290         /* call handler at eip (r4) and set the first arg with the exception (r5) */
291         ppc_mtctr (code, ppc_r4);
292         ppc_mr (code, ppc_r3, ppc_r5);
293         ppc_bcctrl (code, PPC_BR_ALWAYS, 0);
294
295         /* epilog */
296         ppc_ldptr (code, ppc_r0, alloc_size + PPC_RET_ADDR_OFFSET, ppc_sp);
297         ppc_mtlr (code, ppc_r0);
298
299         /* restore all the regs from the stack */
300         pos = alloc_size;
301         for (i = MONO_MAX_FREGS - 1; i >= MONO_PPC_FIRST_SAVED_FREG; --i) {
302                 pos -= sizeof (gdouble);
303                 ppc_lfd (code, i, pos, ppc_sp);
304         }
305         pos -= (MONO_MAX_FREGS - MONO_SAVED_FREGS) * sizeof (gdouble);
306         pos -= sizeof (gpointer) * MONO_SAVED_GREGS;
307         ppc_load_multiple_regs (code, MONO_PPC_FIRST_SAVED_GREG, pos, ppc_sp);
308
309         ppc_addic (code, ppc_sp, ppc_sp, alloc_size);
310         ppc_blr (code);
311
312         g_assert ((code - start) < size);
313         mono_arch_flush_icache (start, code - start);
314         MONO_PROFILER_RAISE (jit_code_buffer, (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL));
315
316         if (info)
317                 *info = mono_tramp_info_create ("call_filter", start, code - start, ji, unwind_ops);
318
319         return start;
320 }
321
322 void
323 mono_ppc_throw_exception (MonoObject *exc, unsigned long eip, unsigned long esp, mgreg_t *int_regs, gdouble *fp_regs, gboolean rethrow)
324 {
325         MonoError error;
326         MonoContext ctx;
327
328         /* adjust eip so that it point into the call instruction */
329         eip -= 4;
330
331         setup_context (&ctx);
332
333         /*printf ("stack in throw: %p\n", esp);*/
334         MONO_CONTEXT_SET_BP (&ctx, esp);
335         MONO_CONTEXT_SET_IP (&ctx, eip);
336         memcpy (&ctx.regs, int_regs, sizeof (mgreg_t) * MONO_MAX_IREGS);
337         memcpy (&ctx.fregs, fp_regs, sizeof (double) * MONO_MAX_FREGS);
338
339         if (mono_object_isinst_checked (exc, mono_defaults.exception_class, &error)) {
340                 MonoException *mono_ex = (MonoException*)exc;
341                 if (!rethrow) {
342                         mono_ex->stack_trace = NULL;
343                         mono_ex->trace_ips = NULL;
344                 }
345         }
346         mono_error_assert_ok (&error);
347         mono_handle_exception (&ctx, exc);
348         mono_restore_context (&ctx);
349
350         g_assert_not_reached ();
351 }
352
353 /**
354  * arch_get_throw_exception_generic:
355  *
356  * Returns a function pointer which can be used to raise 
357  * exceptions. The returned function has the following 
358  * signature: void (*func) (MonoException *exc); or
359  * void (*func) (guint32 ex_token, gpointer ip)
360  *
361  */
362 static gpointer
363 mono_arch_get_throw_exception_generic (int size, MonoTrampInfo **info, int corlib, gboolean rethrow, gboolean aot)
364 {
365         guint8 *start, *code;
366         int alloc_size, pos;
367         MonoJumpInfo *ji = NULL;
368         GSList *unwind_ops = NULL;
369
370         code = start = mono_global_codeman_reserve (size);
371         if (!aot)
372                 code = mono_ppc_create_pre_code_ftnptr (code);
373
374         /* store ret addr */
375         if (corlib)
376                 ppc_mr (code, ppc_r0, ppc_r4);
377         else
378                 ppc_mflr (code, ppc_r0);
379         ppc_stptr (code, ppc_r0, PPC_RET_ADDR_OFFSET, ppc_sp);
380
381         alloc_size = REG_SAVE_STACK_FRAME_SIZE;
382
383         g_assert ((alloc_size & (MONO_ARCH_FRAME_ALIGNMENT-1)) == 0);
384         ppc_stptr_update (code, ppc_sp, -alloc_size, ppc_sp);
385
386         code = emit_save_saved_regs (code, alloc_size);
387
388         //ppc_break (code);
389         if (corlib) {
390                 ppc_mr (code, ppc_r4, ppc_r3);
391
392                 if (aot) {
393                         code = mono_arch_emit_load_aotconst (start, code, &ji, MONO_PATCH_INFO_IMAGE, mono_defaults.corlib);
394                         ppc_mr (code, ppc_r3, ppc_r12);
395                         code = mono_arch_emit_load_aotconst (start, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_exception_from_token");
396 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
397                         ppc_ldptr (code, ppc_r2, sizeof (gpointer), ppc_r12);
398                         ppc_ldptr (code, ppc_r12, 0, ppc_r12);
399 #endif
400                         ppc_mtctr (code, ppc_r12);
401                         ppc_bcctrl (code, PPC_BR_ALWAYS, 0);
402                 } else {
403                         ppc_load (code, ppc_r3, (gulong)mono_defaults.corlib);
404                         ppc_load_func (code, PPC_CALL_REG, mono_exception_from_token);
405                         ppc_mtctr (code, PPC_CALL_REG);
406                         ppc_bcctrl (code, PPC_BR_ALWAYS, 0);
407                 }
408         }
409
410         /* call throw_exception (exc, ip, sp, int_regs, fp_regs) */
411         /* caller sp */
412         ppc_ldptr (code, ppc_r5, 0, ppc_sp);
413         /* exc is already in place in r3 */
414         if (corlib)
415                 ppc_ldptr (code, ppc_r4, PPC_RET_ADDR_OFFSET, ppc_r5);
416         else
417                 ppc_mr (code, ppc_r4, ppc_r0); /* caller ip */
418         /* pointer to the saved fp regs */
419         pos = alloc_size - sizeof (gdouble) * MONO_MAX_FREGS;
420         ppc_addi (code, ppc_r7, ppc_sp, pos);
421         /* pointer to the saved int regs */
422         pos -= sizeof (gpointer) * MONO_MAX_IREGS;
423         ppc_addi (code, ppc_r6, ppc_sp, pos);
424         ppc_li (code, ppc_r8, rethrow);
425
426         if (aot) {
427                 // This can be called from runtime code, which can't guarantee that
428                 // r30 contains the got address.
429                 // So emit the got address loading code too
430                 code = mono_arch_emit_load_got_addr (start, code, NULL, &ji);
431                 code = mono_arch_emit_load_aotconst (start, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_ppc_throw_exception");
432 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
433                 ppc_ldptr (code, ppc_r2, sizeof (gpointer), ppc_r12);
434                 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
435 #endif
436                 ppc_mtctr (code, ppc_r12);
437                 ppc_bcctrl (code, PPC_BR_ALWAYS, 0);
438         } else {
439                 ppc_load_func (code, PPC_CALL_REG, mono_ppc_throw_exception);
440                 ppc_mtctr (code, PPC_CALL_REG);
441                 ppc_bcctrl (code, PPC_BR_ALWAYS, 0);
442         }
443         /* we should never reach this breakpoint */
444         ppc_break (code);
445         g_assert ((code - start) <= size);
446         mono_arch_flush_icache (start, code - start);
447         MONO_PROFILER_RAISE (jit_code_buffer, (start, code - start, MONO_PROFILER_CODE_BUFFER_EXCEPTION_HANDLING, NULL));
448
449         if (info)
450                 *info = mono_tramp_info_create (corlib ? "throw_corlib_exception" : (rethrow ? "rethrow_exception" : "throw_exception"), start, code - start, ji, unwind_ops);
451
452         return start;
453 }
454
455 /**
456  * mono_arch_get_rethrow_exception:
457  * \returns a function pointer which can be used to rethrow 
458  * exceptions. The returned function has the following 
459  * signature: void (*func) (MonoException *exc); 
460  */
461 gpointer
462 mono_arch_get_rethrow_exception (MonoTrampInfo **info, gboolean aot)
463 {
464         int size = MONO_PPC_32_64_CASE (132, 224) + PPC_FTNPTR_SIZE;
465
466         if (aot)
467                 size += 64;
468         return mono_arch_get_throw_exception_generic (size, info, FALSE, TRUE, aot);
469 }
470
471 /**
472  * arch_get_throw_exception:
473  *
474  * Returns a function pointer which can be used to raise 
475  * exceptions. The returned function has the following 
476  * signature: void (*func) (MonoException *exc); 
477  * For example to raise an arithmetic exception you can use:
478  *
479  * x86_push_imm (code, mono_get_exception_arithmetic ()); 
480  * x86_call_code (code, arch_get_throw_exception ()); 
481  *
482  */
483 gpointer
484 mono_arch_get_throw_exception (MonoTrampInfo **info, gboolean aot)
485 {
486         int size = MONO_PPC_32_64_CASE (132, 224) + PPC_FTNPTR_SIZE;
487
488         if (aot)
489                 size += 64;
490         return mono_arch_get_throw_exception_generic (size, info, FALSE, FALSE, aot);
491 }
492
493 /**
494  * mono_arch_get_throw_corlib_exception:
495  * \returns a function pointer which can be used to raise 
496  * corlib exceptions. The returned function has the following 
497  * signature: void (*func) (guint32 ex_token, guint32 offset); 
498  * On PPC, we pass the ip instead of the offset
499  */
500 gpointer
501 mono_arch_get_throw_corlib_exception (MonoTrampInfo **info, gboolean aot)
502 {
503         int size = MONO_PPC_32_64_CASE (168, 304) + PPC_FTNPTR_SIZE;
504
505         if (aot)
506                 size += 64;
507         return mono_arch_get_throw_exception_generic (size, info, TRUE, FALSE, aot);
508 }
509
510 /*
511  * mono_arch_unwind_frame:
512  *
513  * See exceptions-amd64.c for docs.
514  */
515 gboolean
516 mono_arch_unwind_frame (MonoDomain *domain, MonoJitTlsData *jit_tls, 
517                                                          MonoJitInfo *ji, MonoContext *ctx, 
518                                                          MonoContext *new_ctx, MonoLMF **lmf,
519                                                          mgreg_t **save_locations,
520                                                          StackFrameInfo *frame)
521 {
522         gpointer ip = MONO_CONTEXT_GET_IP (ctx);
523         MonoPPCStackFrame *sframe;
524
525         memset (frame, 0, sizeof (StackFrameInfo));
526         frame->ji = ji;
527
528         *new_ctx = *ctx;
529         setup_context (new_ctx);
530
531         if (ji != NULL) {
532                 int i;
533                 mgreg_t regs [ppc_lr + 1];
534                 guint8 *cfa;
535                 guint32 unwind_info_len;
536                 guint8 *unwind_info;
537
538                 if (ji->is_trampoline)
539                         frame->type = FRAME_TYPE_TRAMPOLINE;
540                 else
541                         frame->type = FRAME_TYPE_MANAGED;
542
543                 unwind_info = mono_jinfo_get_unwind_info (ji, &unwind_info_len);
544
545                 sframe = (MonoPPCStackFrame*)MONO_CONTEXT_GET_SP (ctx);
546                 MONO_CONTEXT_SET_BP (new_ctx, sframe->sp);
547                 if (!ji->is_trampoline && jinfo_get_method (ji)->save_lmf) {
548                         /* sframe->sp points just past the end of the LMF */
549                         guint8 *lmf_addr = (guint8*)sframe->sp - sizeof (MonoLMF);
550                         memcpy (&new_ctx->fregs [MONO_PPC_FIRST_SAVED_FREG], lmf_addr + G_STRUCT_OFFSET (MonoLMF, fregs), sizeof (double) * MONO_SAVED_FREGS);
551                         memcpy (&new_ctx->regs [MONO_PPC_FIRST_SAVED_GREG], lmf_addr + G_STRUCT_OFFSET (MonoLMF, iregs), sizeof (mgreg_t) * MONO_SAVED_GREGS);
552                         /* the calling IP is in the parent frame */
553                         sframe = (MonoPPCStackFrame*)sframe->sp;
554                         /* we substract 4, so that the IP points into the call instruction */
555                         MONO_CONTEXT_SET_IP (new_ctx, sframe->lr - 4);
556                 } else {
557                         regs [ppc_lr] = ctx->sc_ir;
558                         regs [ppc_sp] = ctx->sc_sp;
559                         for (i = MONO_PPC_FIRST_SAVED_GREG; i < MONO_MAX_IREGS; ++i)
560                                 regs [i] = ctx->regs [i];
561
562                         mono_unwind_frame (unwind_info, unwind_info_len, ji->code_start, 
563                                                            (guint8*)ji->code_start + ji->code_size,
564                                                            ip, NULL, regs, ppc_lr + 1,
565                                                            save_locations, MONO_MAX_IREGS, &cfa);
566
567                         /* we substract 4, so that the IP points into the call instruction */
568                         MONO_CONTEXT_SET_IP (new_ctx, regs [ppc_lr] - 4);
569                         MONO_CONTEXT_SET_BP (new_ctx, cfa);
570
571                         for (i = MONO_PPC_FIRST_SAVED_GREG; i < MONO_MAX_IREGS; ++i)
572                                 new_ctx->regs [i] = regs [i];
573                 }
574
575                 return TRUE;
576         } else if (*lmf) {
577                 
578                 if ((ji = mini_jit_info_table_find (domain, (gpointer)(*lmf)->eip, NULL))) {
579                 } else {
580                         if (!(*lmf)->method)
581                                 return FALSE;
582
583                         /* Trampoline lmf frame */
584                         frame->method = (*lmf)->method;
585                 }
586
587                 /*sframe = (MonoPPCStackFrame*)MONO_CONTEXT_GET_SP (ctx);
588                 MONO_CONTEXT_SET_BP (new_ctx, sframe->sp);
589                 MONO_CONTEXT_SET_IP (new_ctx, sframe->lr);*/
590                 MONO_CONTEXT_SET_BP (new_ctx, (*lmf)->ebp);
591                 MONO_CONTEXT_SET_IP (new_ctx, (*lmf)->eip);
592                 memcpy (&new_ctx->regs [MONO_PPC_FIRST_SAVED_GREG], (*lmf)->iregs, sizeof (mgreg_t) * MONO_SAVED_GREGS);
593                 memcpy (&new_ctx->fregs [MONO_PPC_FIRST_SAVED_FREG], (*lmf)->fregs, sizeof (double) * MONO_SAVED_FREGS);
594
595                 frame->ji = ji;
596                 frame->type = FRAME_TYPE_MANAGED_TO_NATIVE;
597
598                 /* FIXME: what about trampoline LMF frames?  see exceptions-x86.c */
599
600                 *lmf = (*lmf)->previous_lmf;
601
602                 return TRUE;
603         }
604
605         return FALSE;
606 }
607
608 gpointer
609 mono_arch_ip_from_context (void *sigctx)
610 {
611 #ifdef MONO_CROSS_COMPILE
612         g_assert_not_reached ();
613 #else
614         os_ucontext *uc = sigctx;
615         return (gpointer)UCONTEXT_REG_NIP(uc);
616 #endif
617 }
618
619 void
620 mono_ppc_set_func_into_sigctx (void *sigctx, void *func)
621 {
622 #ifdef MONO_CROSS_COMPILE
623         g_assert_not_reached ();
624 #elif defined(PPC_USES_FUNCTION_DESCRIPTOR)
625         /* Have to set both the ip and the TOC reg */
626         os_ucontext *uc = sigctx;
627
628         UCONTEXT_REG_NIP(uc) = ((gsize*)func) [0];
629         UCONTEXT_REG_Rn (uc, 2) = ((gsize*)func)[1];
630 #else
631         g_assert_not_reached ();
632 #endif
633 }
634
635 static void
636 altstack_handle_and_restore (void *sigctx, gpointer obj)
637 {
638         MonoContext mctx;
639
640         mono_sigctx_to_monoctx (sigctx, &mctx);
641         mono_handle_exception (&mctx, obj);
642         mono_restore_context (&mctx);
643 }
644
645 void
646 mono_arch_handle_altstack_exception (void *sigctx, MONO_SIG_HANDLER_INFO_TYPE *siginfo, gpointer fault_addr, gboolean stack_ovf)
647 {
648 #ifdef MONO_CROSS_COMPILE
649         g_assert_not_reached ();
650 #else
651 #ifdef MONO_ARCH_USE_SIGACTION
652         os_ucontext *uc = (ucontext_t*)sigctx;
653         os_ucontext *uc_copy;
654         MonoJitInfo *ji = mini_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context (sigctx), NULL);
655         gpointer *sp;
656         int frame_size;
657
658         if (stack_ovf) {
659                 const char *method;
660                 /* we don't do much now, but we can warn the user with a useful message */
661                 fprintf (stderr, "Stack overflow: IP: %p, SP: %p\n", mono_arch_ip_from_context (sigctx), (gpointer)UCONTEXT_REG_Rn(uc, 1));
662                 if (ji && !ji->is_trampoline && jinfo_get_method (ji))
663                         method = mono_method_full_name (jinfo_get_method (ji), TRUE);
664                 else
665                         method = "Unmanaged";
666                 fprintf (stderr, "At %s\n", method);
667                 abort ();
668         }
669         if (!ji)
670                 mono_handle_native_crash ("SIGSEGV", sigctx, siginfo);
671         /* setup a call frame on the real stack so that control is returned there
672          * and exception handling can continue.
673          * The frame looks like:
674          *   ucontext struct
675          *   ...
676          * 224 is the size of the red zone
677          */
678         frame_size = sizeof (ucontext_t) + sizeof (gpointer) * 16 + 224;
679         frame_size += 15;
680         frame_size &= ~15;
681         sp = (gpointer)(UCONTEXT_REG_Rn(uc, 1) & ~15);
682         sp = (gpointer)((char*)sp - frame_size);
683         /* may need to adjust pointers in the new struct copy, depending on the OS */
684         uc_copy = (ucontext_t*)(sp + 16);
685         memcpy (uc_copy, uc, sizeof (os_ucontext));
686 #if defined(__linux__) && !defined(__mono_ppc64__)
687         uc_copy->uc_mcontext.uc_regs = (gpointer)((char*)uc_copy + ((char*)uc->uc_mcontext.uc_regs - (char*)uc));
688 #endif
689         g_assert (mono_arch_ip_from_context (uc) == mono_arch_ip_from_context (uc_copy));
690         /* at the return form the signal handler execution starts in altstack_handle_and_restore() */
691         UCONTEXT_REG_LNK(uc) = UCONTEXT_REG_NIP(uc);
692 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
693         {
694                 MonoPPCFunctionDescriptor *handler_ftnptr = (MonoPPCFunctionDescriptor*)altstack_handle_and_restore;
695
696                 UCONTEXT_REG_NIP(uc) = (gulong)handler_ftnptr->code;
697                 UCONTEXT_REG_Rn(uc, 2) = (gulong)handler_ftnptr->toc;
698         }
699 #else
700         UCONTEXT_REG_NIP(uc) = (unsigned long)altstack_handle_and_restore;
701 #if _CALL_ELF == 2
702         /* ELF v2 ABI calling convention requires to put the target address into
703         * r12 if we use the global entry point of a function. */
704         UCONTEXT_REG_Rn(uc, 12) = (unsigned long) altstack_handle_and_restore;
705 #endif
706 #endif
707         UCONTEXT_REG_Rn(uc, 1) = (unsigned long)sp;
708         UCONTEXT_REG_Rn(uc, PPC_FIRST_ARG_REG) = (unsigned long)(sp + 16);
709         UCONTEXT_REG_Rn(uc, PPC_FIRST_ARG_REG + 1) = 0;
710         UCONTEXT_REG_Rn(uc, PPC_FIRST_ARG_REG + 2) = 0;
711 #endif
712
713 #endif /* !MONO_CROSS_COMPILE */
714 }
715
716 /*
717  * handle_exception:
718  *
719  *   Called by resuming from a signal handler.
720  */
721 static void
722 handle_signal_exception (gpointer obj)
723 {
724         MonoJitTlsData *jit_tls = mono_tls_get_jit_tls ();
725         MonoContext ctx;
726
727         memcpy (&ctx, &jit_tls->ex_ctx, sizeof (MonoContext));
728
729         mono_handle_exception (&ctx, obj);
730
731         mono_restore_context (&ctx);
732 }
733
734 static void
735 setup_ucontext_return (void *uc, gpointer func)
736 {
737 #if !defined(MONO_CROSS_COMPILE)
738         UCONTEXT_REG_LNK(uc) = UCONTEXT_REG_NIP(uc);
739 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
740         {
741                 MonoPPCFunctionDescriptor *handler_ftnptr = (MonoPPCFunctionDescriptor*)func;
742
743                 UCONTEXT_REG_NIP(uc) = (gulong)handler_ftnptr->code;
744                 UCONTEXT_REG_Rn(uc, 2) = (gulong)handler_ftnptr->toc;
745         }
746 #else
747         UCONTEXT_REG_NIP(uc) = (unsigned long)func;
748 #if _CALL_ELF == 2
749         /* ELF v2 ABI calling convention requires to put the target address into
750         * r12 if we use the global entry point of a function. */
751         UCONTEXT_REG_Rn(uc, 12) = (unsigned long) func;
752 #endif
753 #endif
754 #endif
755 }
756
757 gboolean
758 mono_arch_handle_exception (void *ctx, gpointer obj)
759 {
760 #if defined(MONO_ARCH_USE_SIGACTION) && defined(UCONTEXT_REG_Rn)
761         /*
762          * Handling the exception in the signal handler is problematic, since the original
763          * signal is disabled, and we could run arbitrary code though the debugger. So
764          * resume into the normal stack and do most work there if possible.
765          */
766         MonoJitTlsData *jit_tls = mono_tls_get_jit_tls ();
767         mgreg_t sp;
768         void *sigctx = ctx;
769         int frame_size;
770         void *uc = sigctx;
771
772         /* Pass the ctx parameter in TLS */
773         mono_sigctx_to_monoctx (sigctx, &jit_tls->ex_ctx);
774         /* The others in registers */
775         UCONTEXT_REG_Rn (sigctx, PPC_FIRST_ARG_REG) = (gsize)obj;
776
777         /* Allocate a stack frame below the red zone */
778         /* Similar to mono_arch_handle_altstack_exception () */
779         frame_size = 224;
780         frame_size += 15;
781         frame_size &= ~15;
782         sp = (mgreg_t)(UCONTEXT_REG_Rn(uc, 1) & ~15);
783         sp = (mgreg_t)(sp - frame_size);
784         UCONTEXT_REG_Rn(uc, 1) = (mgreg_t)sp;
785         setup_ucontext_return (uc, handle_signal_exception);
786
787         return TRUE;
788 #else
789         MonoContext mctx;
790         gboolean result;
791
792         mono_sigctx_to_monoctx (ctx, &mctx);
793
794         result = mono_handle_exception (&mctx, obj);
795         /* restore the context so that returning from the signal handler will invoke
796          * the catch clause 
797          */
798         mono_monoctx_to_sigctx (&mctx, ctx);
799         return result;
800 #endif
801 }
802
803
804 // FIX ME: This is not complete
805 void
806 mono_arch_setup_async_callback (MonoContext *ctx, void (*async_cb)(void *fun), gpointer user_data)
807 {
808         uintptr_t sp = (uintptr_t) MONO_CONTEXT_GET_SP(ctx);
809         sp -= PPC_MINIMAL_STACK_SIZE;
810         *(unsigned long *)sp = MONO_CONTEXT_GET_SP(ctx);
811         MONO_CONTEXT_SET_BP(ctx, sp);
812         MONO_CONTEXT_SET_IP(ctx, (unsigned long) async_cb);
813 }
814