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