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