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