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