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