217e86fa0bc05a62310d2c08fda0c52de8013bed
[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 "unwind.h"
12
13 #include <mono/utils/mono-counters.h>
14 #include <mono/metadata/threads-types.h>
15
16 typedef enum {
17         LOC_SAME,
18         LOC_OFFSET
19 } LocType;
20
21 typedef struct {
22         LocType loc_type;
23         int offset;
24 } Loc;
25
26 typedef struct {
27         guint32 len;
28         guint8 info [MONO_ZERO_LEN_ARRAY];
29 } MonoUnwindInfo;
30
31 static CRITICAL_SECTION unwind_mutex;
32
33 static MonoUnwindInfo **cached_info;
34 static int cached_info_next, cached_info_size;
35 /* Statistics */
36 static int unwind_info_size;
37
38 #define unwind_lock() EnterCriticalSection (&unwind_mutex)
39 #define unwind_unlock() LeaveCriticalSection (&unwind_mutex)
40
41 #ifdef __x86_64__
42 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 };
43 #define NUM_REGS AMD64_NREG
44 #define DWARF_DATA_ALIGN (-8)
45 #define DWARF_PC_REG (mono_hw_reg_to_dwarf_reg (AMD64_RIP))
46 #elif defined(__arm__)
47 // http://infocenter.arm.com/help/topic/com.arm.doc.ihi0040a/IHI0040A_aadwarf.pdf
48 static int map_hw_reg_to_dwarf_reg [] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
49 #define NUM_REGS 16
50 #define DWARF_DATA_ALIGN (-4)
51 #define DWARF_PC_REG (mono_hw_reg_to_dwarf_reg (ARMREG_LR))
52 #elif defined (__i386__)
53 static int map_hw_reg_to_dwarf_reg [] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
54 /* + 1 is for IP */
55 #define NUM_REGS X86_NREG + 1
56 #define DWARF_DATA_ALIGN (-4)
57 #define DWARF_PC_REG (mono_hw_reg_to_dwarf_reg (X86_NREG))
58 #else
59 static int map_hw_reg_to_dwarf_reg [16];
60 #define NUM_REGS 16
61 #define DWARF_DATA_ALIGN 0
62 #define DWARF_PC_REG -1
63 #endif
64
65 static gboolean dwarf_reg_to_hw_reg_inited;
66
67 static int map_dwarf_reg_to_hw_reg [NUM_REGS];
68
69 /*
70  * mono_hw_reg_to_dwarf_reg:
71  *
72  *   Map the hardware register number REG to the register number used by DWARF.
73  */
74 int
75 mono_hw_reg_to_dwarf_reg (int reg)
76 {
77         if (NUM_REGS == 0) {
78                 g_assert_not_reached ();
79                 return -1;
80         } else {
81                 return map_hw_reg_to_dwarf_reg [reg];
82         }
83 }
84
85 static void
86 init_reg_map (void)
87 {
88         int i;
89
90         g_assert (NUM_REGS > 0);
91         g_assert (sizeof (map_hw_reg_to_dwarf_reg) / sizeof (int) == NUM_REGS);
92         for (i = 0; i < NUM_REGS; ++i) {
93                 map_dwarf_reg_to_hw_reg [mono_hw_reg_to_dwarf_reg (i)] = i;
94         }
95
96         mono_memory_barrier ();
97         dwarf_reg_to_hw_reg_inited = TRUE;
98 }
99
100 static inline int
101 mono_dwarf_reg_to_hw_reg (int reg)
102 {
103         if (!dwarf_reg_to_hw_reg_inited)
104                 init_reg_map ();
105
106         return map_dwarf_reg_to_hw_reg [reg];
107 }
108
109 static G_GNUC_UNUSED void
110 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
111 {
112         guint8 *p = buf;
113
114         do {
115                 guint8 b = value & 0x7f;
116                 value >>= 7;
117                 if (value != 0) /* more bytes to come */
118                         b |= 0x80;
119                 *p ++ = b;
120         } while (value);
121
122         *endbuf = p;
123 }
124
125 static inline guint32
126 decode_uleb128 (guint8 *buf, guint8 **endbuf)
127 {
128         guint8 *p = buf;
129         guint32 res = 0;
130         int shift = 0;
131
132         while (TRUE) {
133                 guint8 b = *p;
134                 p ++;
135
136                 res = res | (((int)(b & 0x7f)) << shift);
137                 if (!(b & 0x80))
138                         break;
139                 shift += 7;
140         }
141
142         *endbuf = p;
143
144         return res;
145 }
146
147 static inline gint32
148 decode_sleb128 (guint8 *buf, guint8 **endbuf)
149 {
150         guint8 *p = buf;
151         gint32 res = 0;
152         int shift = 0;
153
154         while (TRUE) {
155                 guint8 b = *p;
156                 p ++;
157
158                 res = res | (((int)(b & 0x7f)) << shift);
159                 shift += 7;
160                 if (!(b & 0x80)) {
161                         if (shift < 32 && (b & 0x40))
162                                 res |= - (1 << shift);
163                         break;
164                 }
165         }
166
167         *endbuf = p;
168
169         return res;
170 }
171
172 /*
173  * mono_unwind_ops_encode:
174  *
175  *   Encode the unwind ops in UNWIND_OPS into the compact DWARF encoding.
176  * Return a pointer to malloc'ed memory.
177  */
178 guint8*
179 mono_unwind_ops_encode (GSList *unwind_ops, guint32 *out_len)
180 {
181         GSList *l;
182         MonoUnwindOp *op;
183         int loc;
184         guint8 *buf, *p, *res;
185
186         p = buf = g_malloc0 (4096);
187
188         loc = 0;
189         l = unwind_ops;
190         for (; l; l = l->next) {
191                 int reg;
192
193                 op = l->data;
194
195                 /* Convert the register from the hw encoding to the dwarf encoding */
196                 reg = mono_hw_reg_to_dwarf_reg (op->reg);
197
198                 /* Emit an advance_loc if neccesary */
199                 while (op->when > loc) {
200                         if (op->when - loc < 32) {
201                                 *p ++ = DW_CFA_advance_loc | (op->when - loc);
202                                 loc = op->when;
203                         } else {
204                                 *p ++ = DW_CFA_advance_loc | (30);
205                                 loc += 30;
206                         }
207                 }                       
208
209                 switch (op->op) {
210                 case DW_CFA_def_cfa:
211                         *p ++ = op->op;
212                         encode_uleb128 (reg, p, &p);
213                         encode_uleb128 (op->val, p, &p);
214                         break;
215                 case DW_CFA_def_cfa_offset:
216                         *p ++ = op->op;
217                         encode_uleb128 (op->val, p, &p);
218                         break;
219                 case DW_CFA_def_cfa_register:
220                         *p ++ = op->op;
221                         encode_uleb128 (reg, p, &p);
222                         break;
223                 case DW_CFA_offset:
224                         *p ++ = DW_CFA_offset | reg;
225                         encode_uleb128 (op->val / DWARF_DATA_ALIGN, p, &p);
226                         break;
227                 default:
228                         g_assert_not_reached ();
229                         break;
230                 }
231         }
232         
233         g_assert (p - buf < 4096);
234         *out_len = p - buf;
235         res = g_malloc (p - buf);
236         memcpy (res, buf, p - buf);
237         g_free (buf);
238         return res;
239 }
240
241 #if 0
242 #define UNW_DEBUG(stmt) do { stmt; } while (0)
243 #else
244 #define UNW_DEBUG(stmt) do { } while (0)
245 #endif
246
247 static G_GNUC_UNUSED void
248 print_dwarf_state (int cfa_reg, int cfa_offset, int ip, int nregs, Loc *locations)
249 {
250         int i;
251
252         printf ("\t%x: cfa=r%d+%d ", ip, cfa_reg, cfa_offset);
253
254         for (i = 0; i < nregs; ++i)
255                 if (locations [i].loc_type == LOC_OFFSET)
256                         printf ("r%d@%d(cfa) ", i, locations [i].offset);
257         printf ("\n");
258 }
259
260 /*
261  * Given the state of the current frame as stored in REGS, execute the unwind 
262  * operations in unwind_info until the location counter reaches POS. The result is 
263  * stored back into REGS. OUT_CFA will receive the value of the CFA.
264  * This function is signal safe.
265  */
266 void
267 mono_unwind_frame (guint8 *unwind_info, guint32 unwind_info_len, 
268                                    guint8 *start_ip, guint8 *end_ip, guint8 *ip, gssize *regs, 
269                                    int nregs, guint8 **out_cfa) 
270 {
271         Loc locations [NUM_REGS];
272         int i, pos, reg, cfa_reg, cfa_offset;
273         guint8 *p;
274         guint8 *cfa_val;
275
276         g_assert (nregs <= NUM_REGS);
277
278         for (i = 0; i < nregs; ++i)
279                 locations [i].loc_type = LOC_SAME;
280
281         p = unwind_info;
282         pos = 0;
283         cfa_reg = -1;
284         cfa_offset = -1;
285         while (pos <= ip - start_ip && p < unwind_info + unwind_info_len) {
286                 int op = *p & 0xc0;
287
288                 switch (op) {
289                 case DW_CFA_advance_loc:
290                         UNW_DEBUG (print_dwarf_state (cfa_reg, cfa_offset, pos, nregs, locations));
291                         pos += *p & 0x3f;
292                         p ++;
293                         break;
294                 case DW_CFA_offset:
295                         reg = mono_dwarf_reg_to_hw_reg (*p & 0x3f);
296                         p ++;
297                         locations [reg].loc_type = LOC_OFFSET;
298                         locations [reg].offset = decode_uleb128 (p, &p) * DWARF_DATA_ALIGN;
299                         break;
300                 case 0: {
301                         int ext_op = *p;
302                         p ++;
303                         switch (ext_op) {
304                         case DW_CFA_def_cfa:
305                                 cfa_reg = mono_dwarf_reg_to_hw_reg (decode_uleb128 (p, &p));
306                                 cfa_offset = decode_uleb128 (p, &p);
307                                 break;
308                         case DW_CFA_def_cfa_offset:
309                                 cfa_offset = decode_uleb128 (p, &p);
310                                 break;
311                         case DW_CFA_def_cfa_register:
312                                 cfa_reg = mono_dwarf_reg_to_hw_reg (decode_uleb128 (p, &p));
313                                 break;
314                         case DW_CFA_advance_loc4:
315                                 pos += *(guint32*)p;
316                                 p += 4;
317                                 break;
318                         default:
319                                 g_assert_not_reached ();
320                         }
321                         break;
322                 }
323                 default:
324                         g_assert_not_reached ();
325                 }
326         }
327
328         cfa_val = (guint8*)regs [cfa_reg] + cfa_offset;
329         for (i = 0; i < nregs; ++i) {
330                 if (locations [i].loc_type == LOC_OFFSET)
331                         regs [i] = *(gssize*)(cfa_val + locations [i].offset);
332         }
333
334         *out_cfa = cfa_val;
335 }
336
337 void
338 mono_unwind_init (void)
339 {
340         InitializeCriticalSection (&unwind_mutex);
341
342         mono_counters_register ("Unwind info size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &unwind_info_size);
343 }
344
345 void
346 mono_unwind_cleanup (void)
347 {
348         int i;
349
350         DeleteCriticalSection (&unwind_mutex);
351
352         if (!cached_info)
353                 return;
354
355         for (i = 0; i < cached_info_next; ++i) {
356                 MonoUnwindInfo *cached = cached_info [i];
357
358                 g_free (cached);
359         }
360
361         g_free (cached_info);
362 }
363
364 /*
365  * mono_cache_unwind_info
366  *
367  *   Save UNWIND_INFO in the unwind info cache and return an id which can be passed
368  * to mono_get_cached_unwind_info to get a cached copy of the info.
369  * A copy is made of the unwind info.
370  * This function is useful for two reasons:
371  * - many methods have the same unwind info
372  * - MonoJitInfo->used_regs is an int so it can't store the pointer to the unwind info
373  */
374 guint32
375 mono_cache_unwind_info (guint8 *unwind_info, guint32 unwind_info_len)
376 {
377         int i;
378         MonoUnwindInfo *info;
379
380         unwind_lock ();
381
382         if (cached_info == NULL) {
383                 cached_info_size = 16;
384                 cached_info = g_new0 (MonoUnwindInfo*, cached_info_size);
385         }
386
387         for (i = 0; i < cached_info_next; ++i) {
388                 MonoUnwindInfo *cached = cached_info [i];
389
390                 if (cached->len == unwind_info_len && memcmp (cached->info, unwind_info, unwind_info_len) == 0) {
391                         unwind_unlock ();
392                         return i;
393                 }
394         }
395
396         info = g_malloc (sizeof (MonoUnwindInfo) + unwind_info_len);
397         info->len = unwind_info_len;
398         memcpy (&info->info, unwind_info, unwind_info_len);
399
400         i = cached_info_next;
401         
402         if (cached_info_next >= cached_info_size) {
403                 MonoUnwindInfo **old_table, **new_table;
404
405                 /*
406                  * Have to resize the table, while synchronizing with 
407                  * mono_get_cached_unwind_info () using hazard pointers.
408                  */
409
410                 old_table = cached_info;
411                 new_table = g_new0 (MonoUnwindInfo*, cached_info_size * 2);
412
413                 memcpy (new_table, cached_info, cached_info_size * sizeof (MonoUnwindInfo*));
414
415                 mono_memory_barrier ();
416
417                 cached_info = new_table;
418
419                 mono_memory_barrier ();
420
421                 mono_thread_hazardous_free_or_queue (old_table, g_free);
422
423                 cached_info_size *= 2;
424         }
425
426         cached_info [cached_info_next ++] = info;
427
428         unwind_info_size += sizeof (MonoUnwindInfo) + unwind_info_len;
429
430         unwind_unlock ();
431         return i;
432 }
433
434 static gpointer
435 get_hazardous_pointer (gpointer volatile *pp, MonoThreadHazardPointers *hp, int hazard_index)
436 {
437         gpointer p;
438
439         for (;;) {
440                 /* Get the pointer */
441                 p = *pp;
442                 /* If we don't have hazard pointers just return the
443                    pointer. */
444                 if (!hp)
445                         return p;
446                 /* Make it hazardous */
447                 mono_hazard_pointer_set (hp, hazard_index, p);
448                 /* Check that it's still the same.  If not, try
449                    again. */
450                 if (*pp != p) {
451                         mono_hazard_pointer_clear (hp, hazard_index);
452                         continue;
453                 }
454                 break;
455         }
456
457         return p;
458 }
459
460 /*
461  * This function is signal safe.
462  */
463 guint8*
464 mono_get_cached_unwind_info (guint32 index, guint32 *unwind_info_len)
465 {
466         MonoUnwindInfo **table;
467         MonoUnwindInfo *info;
468         guint8 *data;
469         MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
470
471         table = get_hazardous_pointer ((gpointer volatile*)&cached_info, hp, 0);
472
473         info = table [index];
474
475         *unwind_info_len = info->len;
476         data = info->info;
477
478         mono_hazard_pointer_clear (hp, 0);
479
480         return data;
481 }
482
483 /*
484  * mono_unwind_get_dwarf_data_align:
485  *
486  *   Return the data alignment used by the encoded unwind information.
487  */
488 int
489 mono_unwind_get_dwarf_data_align (void)
490 {
491         return DWARF_DATA_ALIGN;
492 }
493
494 /*
495  * mono_unwind_get_dwarf_pc_reg:
496  *
497  *   Return the dwarf register number of the register holding the ip of the
498  * previous frame.
499  */
500 int
501 mono_unwind_get_dwarf_pc_reg (void)
502 {
503         return DWARF_PC_REG;
504 }
505
506 static void
507 decode_cie_op (guint8 *p, guint8 **endp)
508 {
509         int op = *p & 0xc0;
510
511         switch (op) {
512         case DW_CFA_advance_loc:
513                 p ++;
514                 break;
515         case DW_CFA_offset:
516                 p ++;
517                 decode_uleb128 (p, &p);
518                 break;
519         case 0: {
520                 int ext_op = *p;
521                 p ++;
522                 switch (ext_op) {
523                 case DW_CFA_def_cfa:
524                         decode_uleb128 (p, &p);
525                         decode_uleb128 (p, &p);
526                         break;
527                 case DW_CFA_def_cfa_offset:
528                         decode_uleb128 (p, &p);
529                         break;
530                 case DW_CFA_def_cfa_register:
531                         decode_uleb128 (p, &p);
532                         break;
533                 case DW_CFA_advance_loc4:
534                         p += 4;
535                         break;
536                 default:
537                         g_assert_not_reached ();
538                 }
539                 break;
540         }
541         default:
542                 g_assert_not_reached ();
543         }
544
545         *endp = p;
546 }
547
548 /*
549  * mono_unwind_get_ops_from_fde:
550  *
551  *   Return the unwind opcodes encoded in a DWARF FDE entry.
552  */
553 guint8*
554 mono_unwind_get_ops_from_fde (guint8 *fde, guint32 *out_len)
555 {
556         guint8 *p, *cie, *code, *fde_cfi, *cie_cfi;
557         gint32 fde_len, cie_offset, pc_begin, pc_range, aug_len, fde_data_len;
558         gint32 cie_len, cie_id, cie_version, code_align, data_align, return_reg;
559         gint32 i, cie_aug_len, buf_len;
560         char *cie_aug_str;
561         guint8 *buf;
562
563         /* 
564          * http://refspecs.freestandards.org/LSB_3.0.0/LSB-Core-generic/LSB-Core-generic/ehframechpt.html
565          */
566
567         /* Decode FDE */
568
569         p = fde;
570         // FIXME: Endianess ?
571         fde_len = *(guint32*)p;
572         g_assert (fde_len != 0xffffffff && fde_len != 0);
573         p += 4;
574         cie_offset = *(guint32*)p;
575         cie = p - cie_offset;
576         p += 4;
577         pc_begin = *(gint32*)p;
578         code = p + pc_begin;
579         p += 4;
580         pc_range = *(guint32*)p;
581         p += 4;
582         aug_len = decode_uleb128 (p, &p);
583         g_assert (aug_len == 0);
584         fde_cfi = p;
585         fde_data_len = fde + 4 + fde_len - p;
586
587         /* Decode CIE */
588         p = cie;
589         cie_len = *(guint32*)p;
590         p += 4;
591         cie_id = *(guint32*)p;
592         g_assert (cie_id == 0);
593         p += 4;
594         cie_version = *p;
595         g_assert (cie_version == 1);
596         p += 1;
597         cie_aug_str = (char*)p;
598         p += strlen (cie_aug_str) + 1;
599         code_align = decode_uleb128 (p, &p);
600         data_align = decode_sleb128 (p, &p);
601         return_reg = decode_uleb128 (p, &p);
602         if (strstr (cie_aug_str, "z")) {
603                 cie_aug_len = decode_uleb128 (p, &p);
604                 p += cie_aug_len;
605         }
606         cie_cfi = p;
607
608         /* Make sure the FDE uses the same constants as we do */
609         g_assert (code_align == 1);
610         g_assert (data_align == DWARF_DATA_ALIGN);
611         g_assert (return_reg == DWARF_PC_REG);
612
613         buf_len = (cie + cie_len + 4 - cie_cfi) + (fde + fde_len + 4 - fde_cfi);
614         buf = g_malloc0 (buf_len);
615
616         i = 0;
617         p = cie_cfi;
618         while (p < cie + cie_len + 4) {
619                 if (*p == DW_CFA_nop)
620                         break;
621                 else
622                         decode_cie_op (p, &p);
623         }
624         memcpy (buf + i, cie_cfi, p - cie_cfi);
625         i += p - cie_cfi;
626
627         p = fde_cfi;
628         while (p < fde + fde_len + 4) {
629                 if (*p == DW_CFA_nop)
630                         break;
631                 else
632                         decode_cie_op (p, &p);
633         }
634         memcpy (buf + i, fde_cfi, p - fde_cfi);
635         i += p - fde_cfi;
636         g_assert (i <= buf_len);
637
638         *out_len = i;
639
640         return g_realloc (buf, i);
641 }