Merge pull request #225 from mistoll/master
[mono.git] / mono / mini / unwind.c
1 /*
2  * unwind.c: Stack Unwinding Interface
3  *
4  * Authors:
5  *   Zoltan Varga (vargaz@gmail.com)
6  *
7  * (C) 2008 Novell, Inc.
8  */
9
10 #include "mini.h"
11 #include "mini-unwind.h"
12
13 #include <mono/utils/mono-counters.h>
14 #include <mono/utils/freebsd-dwarf.h>
15 #include <mono/utils/hazard-pointer.h>
16 #include <mono/metadata/threads-types.h>
17 #include <mono/metadata/mono-endian.h>
18
19 typedef enum {
20         LOC_SAME,
21         LOC_OFFSET
22 } LocType;
23
24 typedef struct {
25         LocType loc_type;
26         int offset;
27 } Loc;
28
29 typedef struct {
30         guint32 len;
31         guint8 info [MONO_ZERO_LEN_ARRAY];
32 } MonoUnwindInfo;
33
34 static CRITICAL_SECTION unwind_mutex;
35
36 static MonoUnwindInfo **cached_info;
37 static int cached_info_next, cached_info_size;
38 static GSList *cached_info_list;
39 /* Statistics */
40 static int unwind_info_size;
41
42 #define unwind_lock() EnterCriticalSection (&unwind_mutex)
43 #define unwind_unlock() LeaveCriticalSection (&unwind_mutex)
44
45 #ifdef TARGET_AMD64
46 static int map_hw_reg_to_dwarf_reg [] = { 0, 2, 1, 3, 7, 6, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
47 #define NUM_REGS AMD64_NREG
48 #define DWARF_DATA_ALIGN (-8)
49 #define DWARF_PC_REG (mono_hw_reg_to_dwarf_reg (AMD64_RIP))
50 #elif defined(TARGET_ARM)
51 // http://infocenter.arm.com/help/topic/com.arm.doc.ihi0040a/IHI0040A_aadwarf.pdf
52 static int map_hw_reg_to_dwarf_reg [] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
53 #define NUM_REGS 16
54 #define DWARF_DATA_ALIGN (-4)
55 #define DWARF_PC_REG (mono_hw_reg_to_dwarf_reg (ARMREG_LR))
56 #elif defined (TARGET_X86)
57 static int map_hw_reg_to_dwarf_reg [] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
58 /* + 1 is for IP */
59 #define NUM_REGS X86_NREG + 1
60 #define DWARF_DATA_ALIGN (-4)
61 #define DWARF_PC_REG (mono_hw_reg_to_dwarf_reg (X86_NREG))
62 #elif defined (TARGET_POWERPC)
63 // http://refspecs.linuxfoundation.org/ELF/ppc64/PPC-elf64abi-1.9.html
64 static int map_hw_reg_to_dwarf_reg [] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 
65                                                                                   9, 10, 11, 12, 13, 14, 15, 16,
66                                                                                   17, 18, 19, 20, 21, 22, 23, 24,
67                                                                                   25, 26, 27, 28, 29, 30, 31 };
68 #define NUM_REGS 110
69 #define DWARF_DATA_ALIGN (-(gint32)sizeof (mgreg_t))
70 #define DWARF_PC_REG 108
71 #elif defined (TARGET_S390X)
72 static int map_hw_reg_to_dwarf_reg [] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
73 #define NUM_REGS 16
74 #define DWARF_DATA_ALIGN (-8)
75 #define DWARF_PC_REG (mono_hw_reg_to_dwarf_reg (14))
76 #elif defined (TARGET_MIPS)
77 /* FIXME: */
78 static int map_hw_reg_to_dwarf_reg [32] = {
79         0, 1, 2, 3, 4, 5, 6, 7,
80         8, 9, 10, 11, 12, 13, 14, 15,
81         16, 17, 18, 19, 20, 21, 22, 23,
82         24, 25, 26, 27, 28, 29, 30, 31
83 };
84 #define NUM_REGS 32
85 #define DWARF_DATA_ALIGN (-(gint32)sizeof (mgreg_t))
86 #define DWARF_PC_REG (mono_hw_reg_to_dwarf_reg (mips_ra))
87 #else
88 static int map_hw_reg_to_dwarf_reg [16];
89 #define NUM_REGS 16
90 #define DWARF_DATA_ALIGN 0
91 #define DWARF_PC_REG -1
92 #endif
93
94 static gboolean dwarf_reg_to_hw_reg_inited;
95
96 static int map_dwarf_reg_to_hw_reg [NUM_REGS];
97
98 /*
99  * mono_hw_reg_to_dwarf_reg:
100  *
101  *   Map the hardware register number REG to the register number used by DWARF.
102  */
103 int
104 mono_hw_reg_to_dwarf_reg (int reg)
105 {
106 #ifdef TARGET_POWERPC
107         if (reg == ppc_lr)
108                 return 108;
109         else
110                 g_assert (reg < NUM_REGS);
111 #endif
112
113         if (NUM_REGS == 0) {
114                 g_assert_not_reached ();
115                 return -1;
116         } else {
117                 return map_hw_reg_to_dwarf_reg [reg];
118         }
119 }
120
121 static void
122 init_reg_map (void)
123 {
124         int i;
125
126         g_assert (NUM_REGS > 0);
127         for (i = 0; i < sizeof (map_hw_reg_to_dwarf_reg) / sizeof (int); ++i) {
128                 map_dwarf_reg_to_hw_reg [mono_hw_reg_to_dwarf_reg (i)] = i;
129         }
130
131 #ifdef TARGET_POWERPC
132         map_dwarf_reg_to_hw_reg [DWARF_PC_REG] = ppc_lr;
133 #endif
134
135         mono_memory_barrier ();
136         dwarf_reg_to_hw_reg_inited = TRUE;
137 }
138
139 int
140 mono_dwarf_reg_to_hw_reg (int reg)
141 {
142         if (!dwarf_reg_to_hw_reg_inited)
143                 init_reg_map ();
144
145         return map_dwarf_reg_to_hw_reg [reg];
146 }
147
148 static G_GNUC_UNUSED void
149 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
150 {
151         guint8 *p = buf;
152
153         do {
154                 guint8 b = value & 0x7f;
155                 value >>= 7;
156                 if (value != 0) /* more bytes to come */
157                         b |= 0x80;
158                 *p ++ = b;
159         } while (value);
160
161         *endbuf = p;
162 }
163
164 static G_GNUC_UNUSED void
165 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
166 {
167         gboolean more = 1;
168         gboolean negative = (value < 0);
169         guint32 size = 32;
170         guint8 byte;
171         guint8 *p = buf;
172
173         while (more) {
174                 byte = value & 0x7f;
175                 value >>= 7;
176                 /* the following is unnecessary if the
177                  * implementation of >>= uses an arithmetic rather
178                  * than logical shift for a signed left operand
179                  */
180                 if (negative)
181                         /* sign extend */
182                         value |= - (1 <<(size - 7));
183                 /* sign bit of byte is second high order bit (0x40) */
184                 if ((value == 0 && !(byte & 0x40)) ||
185                         (value == -1 && (byte & 0x40)))
186                         more = 0;
187                 else
188                         byte |= 0x80;
189                 *p ++= byte;
190         }
191
192         *endbuf = p;
193 }
194
195 static inline guint32
196 decode_uleb128 (guint8 *buf, guint8 **endbuf)
197 {
198         guint8 *p = buf;
199         guint32 res = 0;
200         int shift = 0;
201
202         while (TRUE) {
203                 guint8 b = *p;
204                 p ++;
205
206                 res = res | (((int)(b & 0x7f)) << shift);
207                 if (!(b & 0x80))
208                         break;
209                 shift += 7;
210         }
211
212         *endbuf = p;
213
214         return res;
215 }
216
217 static inline gint32
218 decode_sleb128 (guint8 *buf, guint8 **endbuf)
219 {
220         guint8 *p = buf;
221         gint32 res = 0;
222         int shift = 0;
223
224         while (TRUE) {
225                 guint8 b = *p;
226                 p ++;
227
228                 res = res | (((int)(b & 0x7f)) << shift);
229                 shift += 7;
230                 if (!(b & 0x80)) {
231                         if (shift < 32 && (b & 0x40))
232                                 res |= - (1 << shift);
233                         break;
234                 }
235         }
236
237         *endbuf = p;
238
239         return res;
240 }
241
242 /*
243  * mono_unwind_ops_encode:
244  *
245  *   Encode the unwind ops in UNWIND_OPS into the compact DWARF encoding.
246  * Return a pointer to malloc'ed memory.
247  */
248 guint8*
249 mono_unwind_ops_encode (GSList *unwind_ops, guint32 *out_len)
250 {
251         GSList *l;
252         MonoUnwindOp *op;
253         int loc;
254         guint8 *buf, *p, *res;
255
256         p = buf = g_malloc0 (4096);
257
258         loc = 0;
259         l = unwind_ops;
260         for (; l; l = l->next) {
261                 int reg;
262
263                 op = l->data;
264
265                 /* Convert the register from the hw encoding to the dwarf encoding */
266                 reg = mono_hw_reg_to_dwarf_reg (op->reg);
267
268                 /* Emit an advance_loc if neccesary */
269                 while (op->when > loc) {
270                         if (op->when - loc < 32) {
271                                 *p ++ = DW_CFA_advance_loc | (op->when - loc);
272                                 loc = op->when;
273                         } else {
274                                 *p ++ = DW_CFA_advance_loc | (30);
275                                 loc += 30;
276                         }
277                 }                       
278
279                 switch (op->op) {
280                 case DW_CFA_def_cfa:
281                         *p ++ = op->op;
282                         encode_uleb128 (reg, p, &p);
283                         encode_uleb128 (op->val, p, &p);
284                         break;
285                 case DW_CFA_def_cfa_offset:
286                         *p ++ = op->op;
287                         encode_uleb128 (op->val, p, &p);
288                         break;
289                 case DW_CFA_def_cfa_register:
290                         *p ++ = op->op;
291                         encode_uleb128 (reg, p, &p);
292                         break;
293                 case DW_CFA_offset:
294                         if (reg > 63) {
295                                 *p ++ = DW_CFA_offset_extended_sf;
296                                 encode_uleb128 (reg, p, &p);
297                                 encode_sleb128 (op->val / DWARF_DATA_ALIGN, p, &p);
298                         } else {
299                                 *p ++ = DW_CFA_offset | reg;
300                                 encode_uleb128 (op->val / DWARF_DATA_ALIGN, p, &p);
301                         }
302                         break;
303                 default:
304                         g_assert_not_reached ();
305                         break;
306                 }
307         }
308         
309         g_assert (p - buf < 4096);
310         *out_len = p - buf;
311         res = g_malloc (p - buf);
312         memcpy (res, buf, p - buf);
313         g_free (buf);
314         return res;
315 }
316
317 #if 0
318 #define UNW_DEBUG(stmt) do { stmt; } while (0)
319 #else
320 #define UNW_DEBUG(stmt) do { } while (0)
321 #endif
322
323 static G_GNUC_UNUSED void
324 print_dwarf_state (int cfa_reg, int cfa_offset, int ip, int nregs, Loc *locations)
325 {
326         int i;
327
328         printf ("\t%x: cfa=r%d+%d ", ip, cfa_reg, cfa_offset);
329
330         for (i = 0; i < nregs; ++i)
331                 if (locations [i].loc_type == LOC_OFFSET)
332                         printf ("r%d@%d(cfa) ", i, locations [i].offset);
333         printf ("\n");
334 }
335
336 /*
337  * Given the state of the current frame as stored in REGS, execute the unwind 
338  * operations in unwind_info until the location counter reaches POS. The result is 
339  * stored back into REGS. OUT_CFA will receive the value of the CFA.
340  * If SAVE_LOCATIONS is non-NULL, it should point to an array of size SAVE_LOCATIONS_LEN.
341  * On return, the nth entry will point to the address of the stack slot where register
342  * N was saved, or NULL, if it was not saved by this frame.
343  * This function is signal safe.
344  */
345 void
346 mono_unwind_frame (guint8 *unwind_info, guint32 unwind_info_len, 
347                                    guint8 *start_ip, guint8 *end_ip, guint8 *ip, mgreg_t *regs, int nregs,
348                                    mgreg_t **save_locations, int save_locations_len,
349                                    guint8 **out_cfa)
350 {
351         Loc locations [NUM_REGS];
352         int i, pos, reg, cfa_reg, cfa_offset;
353         guint8 *p;
354         guint8 *cfa_val;
355
356         for (i = 0; i < NUM_REGS; ++i)
357                 locations [i].loc_type = LOC_SAME;
358
359         p = unwind_info;
360         pos = 0;
361         cfa_reg = -1;
362         cfa_offset = -1;
363         while (pos <= ip - start_ip && p < unwind_info + unwind_info_len) {
364                 int op = *p & 0xc0;
365
366                 switch (op) {
367                 case DW_CFA_advance_loc:
368                         UNW_DEBUG (print_dwarf_state (cfa_reg, cfa_offset, pos, nregs, locations));
369                         pos += *p & 0x3f;
370                         p ++;
371                         break;
372                 case DW_CFA_offset:
373                         reg = *p & 0x3f;
374                         p ++;
375                         locations [reg].loc_type = LOC_OFFSET;
376                         locations [reg].offset = decode_uleb128 (p, &p) * DWARF_DATA_ALIGN;
377                         break;
378                 case 0: {
379                         int ext_op = *p;
380                         p ++;
381                         switch (ext_op) {
382                         case DW_CFA_def_cfa:
383                                 cfa_reg = decode_uleb128 (p, &p);
384                                 cfa_offset = decode_uleb128 (p, &p);
385                                 break;
386                         case DW_CFA_def_cfa_offset:
387                                 cfa_offset = decode_uleb128 (p, &p);
388                                 break;
389                         case DW_CFA_def_cfa_register:
390                                 cfa_reg = decode_uleb128 (p, &p);
391                                 break;
392                         case DW_CFA_offset_extended_sf:
393                                 reg = decode_uleb128 (p, &p);
394                                 locations [reg].loc_type = LOC_OFFSET;
395                                 locations [reg].offset = decode_sleb128 (p, &p) * DWARF_DATA_ALIGN;
396                                 break;
397                         case DW_CFA_advance_loc4:
398                                 pos += read32 (p);
399                                 p += 4;
400                                 break;
401                         default:
402                                 g_assert_not_reached ();
403                         }
404                         break;
405                 }
406                 default:
407                         g_assert_not_reached ();
408                 }
409         }
410
411         if (save_locations)
412                 memset (save_locations, 0, save_locations_len * sizeof (mgreg_t*));
413
414         cfa_val = (guint8*)regs [mono_dwarf_reg_to_hw_reg (cfa_reg)] + cfa_offset;
415         for (i = 0; i < NUM_REGS; ++i) {
416                 if (locations [i].loc_type == LOC_OFFSET) {
417                         int hreg = mono_dwarf_reg_to_hw_reg (i);
418                         g_assert (hreg < nregs);
419                         regs [hreg] = *(mgreg_t*)(cfa_val + locations [i].offset);
420                         if (save_locations && hreg < save_locations_len)
421                                 save_locations [hreg] = (mgreg_t*)(cfa_val + locations [i].offset);
422                 }
423         }
424
425         *out_cfa = cfa_val;
426 }
427
428 void
429 mono_unwind_init (void)
430 {
431         InitializeCriticalSection (&unwind_mutex);
432
433         mono_counters_register ("Unwind info size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &unwind_info_size);
434 }
435
436 void
437 mono_unwind_cleanup (void)
438 {
439         int i;
440
441         DeleteCriticalSection (&unwind_mutex);
442
443         if (!cached_info)
444                 return;
445
446         for (i = 0; i < cached_info_next; ++i) {
447                 MonoUnwindInfo *cached = cached_info [i];
448
449                 g_free (cached);
450         }
451
452         g_free (cached_info);
453 }
454
455 /*
456  * mono_cache_unwind_info
457  *
458  *   Save UNWIND_INFO in the unwind info cache and return an id which can be passed
459  * to mono_get_cached_unwind_info to get a cached copy of the info.
460  * A copy is made of the unwind info.
461  * This function is useful for two reasons:
462  * - many methods have the same unwind info
463  * - MonoJitInfo->used_regs is an int so it can't store the pointer to the unwind info
464  */
465 guint32
466 mono_cache_unwind_info (guint8 *unwind_info, guint32 unwind_info_len)
467 {
468         int i;
469         MonoUnwindInfo *info;
470
471         unwind_lock ();
472
473         if (cached_info == NULL) {
474                 cached_info_size = 16;
475                 cached_info = g_new0 (MonoUnwindInfo*, cached_info_size);
476         }
477
478         for (i = 0; i < cached_info_next; ++i) {
479                 MonoUnwindInfo *cached = cached_info [i];
480
481                 if (cached->len == unwind_info_len && memcmp (cached->info, unwind_info, unwind_info_len) == 0) {
482                         unwind_unlock ();
483                         return i;
484                 }
485         }
486
487         info = g_malloc (sizeof (MonoUnwindInfo) + unwind_info_len);
488         info->len = unwind_info_len;
489         memcpy (&info->info, unwind_info, unwind_info_len);
490
491         i = cached_info_next;
492         
493         if (cached_info_next >= cached_info_size) {
494                 MonoUnwindInfo **old_table, **new_table;
495
496                 /*
497                  * Avoid freeing the old table so mono_get_cached_unwind_info ()
498                  * doesn't need locks/hazard pointers.
499                  */
500
501                 old_table = cached_info;
502                 new_table = g_new0 (MonoUnwindInfo*, cached_info_size * 2);
503
504                 memcpy (new_table, cached_info, cached_info_size * sizeof (MonoUnwindInfo*));
505
506                 mono_memory_barrier ();
507
508                 cached_info = new_table;
509
510                 cached_info_list = g_slist_prepend (cached_info_list, cached_info);
511
512                 cached_info_size *= 2;
513         }
514
515         cached_info [cached_info_next ++] = info;
516
517         unwind_info_size += sizeof (MonoUnwindInfo) + unwind_info_len;
518
519         unwind_unlock ();
520         return i;
521 }
522
523 /*
524  * This function is signal safe.
525  */
526 guint8*
527 mono_get_cached_unwind_info (guint32 index, guint32 *unwind_info_len)
528 {
529         MonoUnwindInfo **table;
530         MonoUnwindInfo *info;
531         guint8 *data;
532
533         /*
534          * This doesn't need any locks/hazard pointers,
535          * since new tables are copies of the old ones.
536          */
537         table = cached_info;
538
539         info = table [index];
540
541         *unwind_info_len = info->len;
542         data = info->info;
543
544         return data;
545 }
546
547 /*
548  * mono_unwind_get_dwarf_data_align:
549  *
550  *   Return the data alignment used by the encoded unwind information.
551  */
552 int
553 mono_unwind_get_dwarf_data_align (void)
554 {
555         return DWARF_DATA_ALIGN;
556 }
557
558 /*
559  * mono_unwind_get_dwarf_pc_reg:
560  *
561  *   Return the dwarf register number of the register holding the ip of the
562  * previous frame.
563  */
564 int
565 mono_unwind_get_dwarf_pc_reg (void)
566 {
567         return DWARF_PC_REG;
568 }
569
570 static void
571 decode_cie_op (guint8 *p, guint8 **endp)
572 {
573         int op = *p & 0xc0;
574
575         switch (op) {
576         case DW_CFA_advance_loc:
577                 p ++;
578                 break;
579         case DW_CFA_offset:
580                 p ++;
581                 decode_uleb128 (p, &p);
582                 break;
583         case 0: {
584                 int ext_op = *p;
585                 p ++;
586                 switch (ext_op) {
587                 case DW_CFA_def_cfa:
588                         decode_uleb128 (p, &p);
589                         decode_uleb128 (p, &p);
590                         break;
591                 case DW_CFA_def_cfa_offset:
592                         decode_uleb128 (p, &p);
593                         break;
594                 case DW_CFA_def_cfa_register:
595                         decode_uleb128 (p, &p);
596                         break;
597                 case DW_CFA_advance_loc4:
598                         p += 4;
599                         break;
600                 case DW_CFA_offset_extended_sf:
601                         decode_uleb128 (p, &p);
602                         decode_uleb128 (p, &p);
603                         break;
604                 default:
605                         g_assert_not_reached ();
606                 }
607                 break;
608         }
609         default:
610                 g_assert_not_reached ();
611         }
612
613         *endp = p;
614 }
615
616 /* Pointer Encoding in the .eh_frame */
617 enum {
618         DW_EH_PE_absptr = 0x00,
619         DW_EH_PE_omit = 0xff,
620
621         DW_EH_PE_udata4 = 0x03,
622         DW_EH_PE_sdata4 = 0x0b,
623         DW_EH_PE_sdata8 = 0x0c,
624
625         DW_EH_PE_pcrel = 0x10,
626         DW_EH_PE_textrel = 0x20,
627         DW_EH_PE_datarel = 0x30,
628         DW_EH_PE_funcrel = 0x40,
629         DW_EH_PE_aligned = 0x50,
630
631         DW_EH_PE_indirect = 0x80
632 };
633
634 static gint64
635 read_encoded_val (guint32 encoding, guint8 *p, guint8 **endp)
636 {
637         gint64 res;
638
639         switch (encoding & 0xf) {
640         case DW_EH_PE_sdata8:
641                 res = *(gint64*)p;
642                 p += 8;
643                 break;
644         case DW_EH_PE_sdata4:
645                 res = *(gint32*)p;
646                 p += 4;
647                 break;
648         default:
649                 g_assert_not_reached ();
650         }
651
652         *endp = p;
653         return res;
654 }
655
656 /*
657  * decode_lsda:
658  *
659  *   Decode the Language Specific Data Area generated by LLVM.
660  */
661 static void
662 decode_lsda (guint8 *lsda, guint8 *code, MonoJitExceptionInfo **ex_info, guint32 *ex_info_len, gpointer **type_info, int *this_reg, int *this_offset)
663 {
664         gint32 ttype_offset, call_site_length;
665         gint32 ttype_encoding, call_site_encoding;
666         guint8 *ttype, *action_table, *call_site, *p;
667         int i, ncall_sites;
668
669         /*
670          * LLVM generates a c++ style LSDA, which can be decoded by looking at
671          * eh_personality.cc in gcc.
672          */
673         p = lsda;
674
675         if (*p == DW_EH_PE_udata4) {
676                 /* This is the modified LSDA generated by the LLVM mono branch */
677                 guint32 mono_magic, version;
678                 gint32 op, reg, offset;
679
680                 p ++;
681                 mono_magic = decode_uleb128 (p, &p);
682                 g_assert (mono_magic == 0x4d4fef4f);
683                 version = decode_uleb128 (p, &p);
684                 g_assert (version == 1);
685
686                 /* 'this' location */
687                 op = *p;
688                 g_assert (op == DW_OP_bregx);
689                 p ++;
690                 reg = decode_uleb128 (p, &p);
691                 offset = decode_sleb128 (p, &p);
692
693                 *this_reg = mono_dwarf_reg_to_hw_reg (reg);
694                 *this_offset = offset;
695         } else {
696                 /* Read @LPStart */
697                 g_assert (*p == DW_EH_PE_omit);
698                 p ++;
699
700                 *this_reg = -1;
701                 *this_offset = -1;
702         }
703
704         /* Read @TType */
705         ttype_encoding = *p;
706         p ++;
707         ttype_offset = decode_uleb128 (p, &p);
708         ttype = p + ttype_offset;
709
710         /* Read call-site table */
711         call_site_encoding = *p;
712         g_assert (call_site_encoding == DW_EH_PE_udata4);
713         p ++;
714         call_site_length = decode_uleb128 (p, &p);
715         call_site = p;
716         p += call_site_length;
717         action_table = p;
718
719         /* Calculate the size of our table */
720         ncall_sites = 0;
721         p = call_site;
722         while (p < action_table) {
723                 int block_start_offset, block_size, landing_pad, action_offset;
724
725                 block_start_offset = read32 (p);
726                 p += sizeof (gint32);
727                 block_size = read32 (p);
728                 p += sizeof (gint32);
729                 landing_pad = read32 (p);
730                 p += sizeof (gint32);
731                 action_offset = decode_uleb128 (p, &p);
732
733                 /* landing_pad == 0 means the region has no landing pad */
734                 if (landing_pad)
735                         ncall_sites ++;
736         }
737
738         if (ex_info) {
739                 *ex_info = g_malloc0 (ncall_sites * sizeof (MonoJitExceptionInfo));
740                 *ex_info_len = ncall_sites;
741         }
742
743         if (type_info)
744                 *type_info = g_malloc0 (ncall_sites * sizeof (gpointer));
745
746         p = call_site;
747         i = 0;
748         while (p < action_table) {
749                 int block_start_offset, block_size, landing_pad, action_offset, type_offset;
750                 guint8 *action, *tinfo;
751
752                 block_start_offset = read32 (p);
753                 p += sizeof (gint32);
754                 block_size = read32 (p);
755                 p += sizeof (gint32);
756                 landing_pad = read32 (p);
757                 p += sizeof (gint32);
758                 action_offset = decode_uleb128 (p, &p);
759
760                 if (!action_offset)
761                         continue;
762
763                 action = action_table + action_offset - 1;
764
765                 type_offset = decode_sleb128 (action, &action);
766
767                 if (landing_pad) {
768                         //printf ("BLOCK: %p-%p %p, %d\n", code + block_start_offset, code + block_start_offset + block_size, code + landing_pad, action_offset);
769
770                         g_assert (ttype_offset);
771
772                         if (ttype_encoding == DW_EH_PE_absptr) {
773                                 guint8 *ttype_entry = (ttype - (type_offset * sizeof (gpointer)));
774                                 tinfo = *(gpointer*)ttype_entry;
775                         } else if (ttype_encoding == (DW_EH_PE_indirect | DW_EH_PE_pcrel | DW_EH_PE_sdata4)) {
776                                 guint8 *ttype_entry = (ttype - (type_offset * 4));
777                                 gint32 offset = *(gint32*)ttype_entry;
778                                 guint8 *stub = ttype_entry + offset;
779                                 tinfo = *(gpointer*)stub;
780                         } else if (ttype_encoding == (DW_EH_PE_pcrel | DW_EH_PE_sdata4)) {
781                                 guint8 *ttype_entry = (ttype - (type_offset * 4));
782                                 gint32 offset = *(gint32*)ttype_entry;
783                                 tinfo = ttype_entry + offset;
784                         } else if (ttype_encoding == DW_EH_PE_udata4) {
785                                 /* Embedded directly */
786                                 guint8 *ttype_entry = (ttype - (type_offset * 4));
787                                 tinfo = ttype_entry;
788                         } else {
789                                 g_assert_not_reached ();
790                         }
791
792                         if (ex_info) {
793                                 if (*type_info)
794                                         (*type_info) [i] = tinfo;
795                                 (*ex_info)[i].try_start = code + block_start_offset;
796                                 (*ex_info)[i].try_end = code + block_start_offset + block_size;
797                                 (*ex_info)[i].handler_start = code + landing_pad;
798
799                         }
800                         i ++;
801                 }
802         }
803 }
804
805 /*
806  * mono_unwind_decode_fde:
807  *
808  *   Decode a DWARF FDE entry, returning the unwind opcodes.
809  * If not NULL, EX_INFO is set to a malloc-ed array of MonoJitExceptionInfo structures,
810  * only try_start, try_end and handler_start is set.
811  * If not NULL, TYPE_INFO is set to a malloc-ed array containing the ttype table from the
812  * LSDA.
813  */
814 guint8*
815 mono_unwind_decode_fde (guint8 *fde, guint32 *out_len, guint32 *code_len, MonoJitExceptionInfo **ex_info, guint32 *ex_info_len, gpointer **type_info, int *this_reg, int *this_offset)
816 {
817         guint8 *p, *cie, *fde_current, *fde_aug = NULL, *code, *fde_cfi, *cie_cfi;
818         gint32 fde_len, cie_offset, pc_begin, pc_range, aug_len, fde_data_len;
819         gint32 cie_len, cie_id, cie_version, code_align, data_align, return_reg;
820         gint32 i, cie_aug_len, buf_len;
821         char *cie_aug_str;
822         guint8 *buf;
823         gboolean has_fde_augmentation = FALSE;
824
825         /* 
826          * http://refspecs.freestandards.org/LSB_3.0.0/LSB-Core-generic/LSB-Core-generic/ehframechpt.html
827          */
828
829         *type_info = NULL;
830         *this_reg = -1;
831         *this_offset = -1;
832
833         /* Decode FDE */
834
835         p = fde;
836         // FIXME: Endianess ?
837         fde_len = *(guint32*)p;
838         g_assert (fde_len != 0xffffffff && fde_len != 0);
839         p += 4;
840         cie_offset = *(guint32*)p;
841         cie = p - cie_offset;
842         p += 4;
843         fde_current = p;
844
845         /* Decode CIE */
846         p = cie;
847         cie_len = *(guint32*)p;
848         p += 4;
849         cie_id = *(guint32*)p;
850         g_assert (cie_id == 0);
851         p += 4;
852         cie_version = *p;
853         g_assert (cie_version == 1);
854         p += 1;
855         cie_aug_str = (char*)p;
856         p += strlen (cie_aug_str) + 1;
857         code_align = decode_uleb128 (p, &p);
858         data_align = decode_sleb128 (p, &p);
859         return_reg = decode_uleb128 (p, &p);
860         if (strstr (cie_aug_str, "z")) {
861                 guint8 *cie_aug;
862                 guint32 p_encoding;
863
864                 cie_aug_len = decode_uleb128 (p, &p);
865
866                 has_fde_augmentation = TRUE;
867
868                 cie_aug = p;
869                 for (i = 0; cie_aug_str [i] != '\0'; ++i) {
870                         switch (cie_aug_str [i]) {
871                         case 'z':
872                                 break;
873                         case 'P':
874                                 p_encoding = *p;
875                                 p ++;
876                                 read_encoded_val (p_encoding, p, &p);
877                                 break;
878                         case 'L':
879                                 g_assert ((*p == (DW_EH_PE_sdata4|DW_EH_PE_pcrel)) || (*p == (DW_EH_PE_sdata8|DW_EH_PE_pcrel)));
880                                 p ++;
881                                 break;
882                         case 'R':
883                                 g_assert (*p == (DW_EH_PE_sdata4|DW_EH_PE_pcrel));
884                                 p ++;
885                                 break;
886                         default:
887                                 g_assert_not_reached ();
888                                 break;
889                         }
890                 }
891                         
892                 p = cie_aug;
893                 p += cie_aug_len;
894         }
895         cie_cfi = p;
896
897         /* Continue decoding FDE */
898         p = fde_current;
899         /* DW_EH_PE_sdata4|DW_EH_PE_pcrel encoding */
900         pc_begin = *(gint32*)p;
901         code = p + pc_begin;
902         p += 4;
903         pc_range = *(guint32*)p;
904         p += 4;
905         if (has_fde_augmentation) {
906                 aug_len = decode_uleb128 (p, &p);
907                 fde_aug = p;
908                 p += aug_len;
909         } else {
910                 aug_len = 0;
911         }
912         fde_cfi = p;
913         fde_data_len = fde + 4 + fde_len - p;
914
915         if (code_len)
916                 *code_len = pc_range;
917
918         if (ex_info) {
919                 *ex_info = NULL;
920                 *ex_info_len = 0;
921         }
922
923         /* Decode FDE augmention */
924         if (aug_len) {
925                 gint32 lsda_offset;
926                 guint8 *lsda;
927
928                 /* sdata|pcrel encoding */
929                 if (aug_len == 4)
930                         lsda_offset = read32 (fde_aug);
931                 else if (aug_len == 8)
932                         lsda_offset = *(gint64*)fde_aug;
933                 else
934                         g_assert_not_reached ();
935                 if (lsda_offset != 0) {
936                         lsda = fde_aug + lsda_offset;
937
938                         decode_lsda (lsda, code, ex_info, ex_info_len, type_info, this_reg, this_offset);
939                 }
940         }
941
942         /* Make sure the FDE uses the same constants as we do */
943         g_assert (code_align == 1);
944         g_assert (data_align == DWARF_DATA_ALIGN);
945         g_assert (return_reg == DWARF_PC_REG);
946
947         buf_len = (cie + cie_len + 4 - cie_cfi) + (fde + fde_len + 4 - fde_cfi);
948         buf = g_malloc0 (buf_len);
949
950         i = 0;
951         p = cie_cfi;
952         while (p < cie + cie_len + 4) {
953                 if (*p == DW_CFA_nop)
954                         break;
955                 else
956                         decode_cie_op (p, &p);
957         }
958         memcpy (buf + i, cie_cfi, p - cie_cfi);
959         i += p - cie_cfi;
960
961         p = fde_cfi;
962         while (p < fde + fde_len + 4) {
963                 if (*p == DW_CFA_nop)
964                         break;
965                 else
966                         decode_cie_op (p, &p);
967         }
968         memcpy (buf + i, fde_cfi, p - fde_cfi);
969         i += p - fde_cfi;
970         g_assert (i <= buf_len);
971
972         *out_len = i;
973
974         return g_realloc (buf, i);
975 }
976
977 /*
978  * mono_unwind_decode_mono_fde:
979  *
980  *   Decode an FDE entry in the LLVM emitted mono EH frame.
981  * info->ex_info is set to a malloc-ed array of MonoJitExceptionInfo structures,
982  * only try_start, try_end and handler_start is set.
983  * info->type_info is set to a malloc-ed array containing the ttype table from the
984  * LSDA.
985  */
986 void
987 mono_unwind_decode_llvm_mono_fde (guint8 *fde, int fde_len, guint8 *cie, guint8 *code, MonoLLVMFDEInfo *res)
988 {
989         guint8 *p, *fde_aug, *cie_cfi, *fde_cfi, *buf;
990         int has_aug, aug_len, cie_cfi_len, fde_cfi_len;
991         gint32 code_align, data_align, return_reg, pers_encoding;
992
993         memset (res, 0, sizeof (*res));
994         res->this_reg = -1;
995         res->this_offset = -1;
996
997         /* fde points to data emitted by LLVM in DwarfException::EmitMonoEHFrame () */
998         p = fde;
999         has_aug = *p;
1000         p ++;
1001         if (has_aug) {
1002                 aug_len = read32 (p);
1003                 p += 4;
1004         } else {
1005                 aug_len = 0;
1006         }
1007         fde_aug = p;
1008         p += aug_len;
1009         fde_cfi = p;
1010
1011         if (has_aug) {
1012                 guint8 *lsda;
1013
1014                 /* The LSDA is embedded directly into the FDE */
1015                 lsda = fde_aug;
1016
1017                 decode_lsda (lsda, code, &res->ex_info, &res->ex_info_len, &res->type_info, &res->this_reg, &res->this_offset);
1018         }
1019
1020         /* Decode CIE */
1021         p = cie;
1022         code_align = decode_uleb128 (p, &p);
1023         data_align = decode_sleb128 (p, &p);
1024         return_reg = decode_uleb128 (p, &p);
1025         pers_encoding = *p;
1026         p ++;
1027         if (pers_encoding != DW_EH_PE_omit)
1028                 read_encoded_val (pers_encoding, p, &p);
1029
1030         cie_cfi = p;
1031
1032         /* Make sure the FDE uses the same constants as we do */
1033         g_assert (code_align == 1);
1034         g_assert (data_align == DWARF_DATA_ALIGN);
1035         g_assert (return_reg == DWARF_PC_REG);
1036
1037         /* Compute size of CIE unwind info it is DW_CFA_nop terminated */
1038         p = cie_cfi;
1039         while (TRUE) {
1040                 if (*p == DW_CFA_nop)
1041                         break;
1042                 else
1043                         decode_cie_op (p, &p);
1044         }
1045         cie_cfi_len = p - cie_cfi;
1046         fde_cfi_len = (fde + fde_len - fde_cfi);
1047
1048         buf = g_malloc0 (cie_cfi_len + fde_cfi_len);
1049         memcpy (buf, cie_cfi, cie_cfi_len);
1050         memcpy (buf + cie_cfi_len, fde_cfi, fde_cfi_len);
1051
1052         res->unw_info_len = cie_cfi_len + fde_cfi_len;
1053         res->unw_info = buf;
1054 }
1055
1056 /*
1057  * mono_unwind_get_cie_program:
1058  *
1059  *   Get the unwind bytecode for the DWARF CIE.
1060  */
1061 GSList*
1062 mono_unwind_get_cie_program (void)
1063 {
1064 #if defined(TARGET_AMD64) || defined(TARGET_X86) || defined(TARGET_POWERPC)
1065         return mono_arch_get_cie_program ();
1066 #else
1067         return NULL;
1068 #endif
1069 }