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