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