Wed Feb 24 15:47:16 CET 2010 Paolo Molaro <lupus@ximian.com>
[mono.git] / mono / mini / dwarfwriter.c
1 /*
2  * dwarfwriter.c: Creation of DWARF debug information
3  *
4  * Author:
5  *   Zoltan Varga (vargaz@gmail.com)
6  *
7  * (C) 2008-2009 Novell, Inc.
8  */
9
10 #include "config.h"
11
12 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
13 #include "dwarfwriter.h"
14
15 #include <sys/types.h>
16 #include <ctype.h>
17 #include <string.h>
18 #ifdef HAVE_STDINT_H
19 #include <stdint.h>
20 #endif
21
22 #include <mono/metadata/mono-endian.h>
23 #include <mono/metadata/debug-mono-symfile.h>
24 #include <mono/utils/mono-compiler.h>
25
26 #ifndef HOST_WIN32
27 #include <mono/utils/freebsd-elf32.h>
28 #include <mono/utils/freebsd-elf64.h>
29 #endif
30
31 #include <mono/utils/freebsd-dwarf.h>
32
33 struct _MonoDwarfWriter
34 {
35         MonoImageWriter *w;
36         GHashTable *class_to_die, *class_to_vtype_die, *class_to_pointer_die;
37         GHashTable *class_to_reference_die;
38         int fde_index, tdie_index, line_number_file_index, line_number_dir_index;
39         GHashTable *file_to_index, *dir_to_index;
40         FILE *il_file;
41         int il_file_line_index, loclist_index;
42         GSList *cie_program;
43         FILE *fp;
44         const char *temp_prefix;
45         gboolean emit_line, appending;
46 };
47
48 /*
49  * mono_dwarf_writer_create:
50  *
51  *   Create a DWARF writer object. WRITER is the underlying image writer this 
52  * writer will emit to. IL_FILE is the file where IL code will be dumped to for
53  * methods which have no line number info. It can be NULL.
54  * If APPENDING is TRUE, the output file will be in assembleable state after each
55  * call to the _emit_ functions. This is used for XDEBUG. If APPENDING is FALSE,
56  * a separate mono_dwarf_writer_close () call is needed to finish the emission of
57  * debug information.
58  */
59 MonoDwarfWriter*
60 mono_dwarf_writer_create (MonoImageWriter *writer, FILE *il_file, int il_file_start_line, gboolean appending)
61 {
62         MonoDwarfWriter *w = g_new0 (MonoDwarfWriter, 1);
63         
64         /*
65          * The appending flag is needed because we use subsections to order things in 
66          * the debug info, and:
67          * - apple's assembler doesn't support them
68          * - the binary writer has problems with subsections+alignment
69          * So instead of subsections, we use the _close () function in AOT mode,
70          * which writes out things in order.
71          */
72
73         w->w = writer;
74         w->il_file = il_file;
75         w->il_file_line_index = il_file_start_line;
76         w->appending = appending;
77
78         if (appending)
79                 g_assert (img_writer_subsections_supported (w->w));
80
81         w->fp = img_writer_get_fp (w->w);
82         w->temp_prefix = img_writer_get_temp_label_prefix (w->w);
83
84         return w;
85 }
86
87 void
88 mono_dwarf_writer_destroy (MonoDwarfWriter *w)
89 {
90         g_free (w);
91 }
92
93 int
94 mono_dwarf_writer_get_il_file_line_index (MonoDwarfWriter *w)
95 {
96         return w->il_file_line_index;
97 }
98
99 /* Wrappers around the image writer functions */
100
101 static inline void
102 emit_section_change (MonoDwarfWriter *w, const char *section_name, int subsection_index)
103 {
104         img_writer_emit_section_change (w->w, section_name, subsection_index);
105 }
106
107 static inline void
108 emit_push_section (MonoDwarfWriter *w, const char *section_name, int subsection)
109 {
110         img_writer_emit_push_section (w->w, section_name, subsection);
111 }
112
113 static inline void
114 emit_pop_section (MonoDwarfWriter *w)
115 {
116         img_writer_emit_pop_section (w->w);
117 }
118
119 static inline void
120 emit_local_symbol (MonoDwarfWriter *w, const char *name, const char *end_label, gboolean func) 
121
122         img_writer_emit_local_symbol (w->w, name, end_label, func); 
123 }
124
125 static inline void
126 emit_label (MonoDwarfWriter *w, const char *name) 
127
128         img_writer_emit_label (w->w, name); 
129 }
130
131 static inline void
132 emit_bytes (MonoDwarfWriter *w, const guint8* buf, int size) 
133
134         img_writer_emit_bytes (w->w, buf, size); 
135 }
136
137 static inline void
138 emit_string (MonoDwarfWriter *w, const char *value) 
139
140         img_writer_emit_string (w->w, value); 
141 }
142
143 static inline void
144 emit_line (MonoDwarfWriter *w) 
145
146         img_writer_emit_line (w->w); 
147 }
148
149 static inline void
150 emit_alignment (MonoDwarfWriter *w, int size) 
151
152         img_writer_emit_alignment (w->w, size); 
153 }
154
155 static inline void
156 emit_pointer_unaligned (MonoDwarfWriter *w, const char *target) 
157
158         img_writer_emit_pointer_unaligned (w->w, target); 
159 }
160
161 static inline void
162 emit_pointer (MonoDwarfWriter *w, const char *target) 
163
164         img_writer_emit_pointer (w->w, target); 
165 }
166
167 static inline void
168 emit_int16 (MonoDwarfWriter *w, int value) 
169
170         img_writer_emit_int16 (w->w, value); 
171 }
172
173 static inline void
174 emit_int32 (MonoDwarfWriter *w, int value) 
175
176         img_writer_emit_int32 (w->w, value); 
177 }
178
179 static inline void
180 emit_symbol_diff (MonoDwarfWriter *w, const char *end, const char* start, int offset) 
181
182         img_writer_emit_symbol_diff (w->w, end, start, offset); 
183 }
184
185 static inline void
186 emit_zero_bytes (MonoDwarfWriter *w, int num) 
187
188         img_writer_emit_zero_bytes (w->w, num); 
189 }
190
191 static inline void
192 emit_byte (MonoDwarfWriter *w, guint8 val) 
193
194         img_writer_emit_byte (w->w, val); 
195 }
196
197 static G_GNUC_UNUSED void
198 emit_uleb128 (MonoDwarfWriter *w, guint32 value)
199 {
200         do {
201                 guint8 b = value & 0x7f;
202                 value >>= 7;
203                 if (value != 0) /* more bytes to come */
204                         b |= 0x80;
205                 emit_byte (w, b);
206         } while (value);
207 }
208
209 static G_GNUC_UNUSED void
210 emit_sleb128 (MonoDwarfWriter *w, gint64 value)
211 {
212         gboolean more = 1;
213         gboolean negative = (value < 0);
214         guint32 size = 64;
215         guint8 byte;
216
217         while (more) {
218                 byte = value & 0x7f;
219                 value >>= 7;
220                 /* the following is unnecessary if the
221                  * implementation of >>= uses an arithmetic rather
222                  * than logical shift for a signed left operand
223                  */
224                 if (negative)
225                         /* sign extend */
226                         value |= - ((gint64)1 <<(size - 7));
227                 /* sign bit of byte is second high order bit (0x40) */
228                 if ((value == 0 && !(byte & 0x40)) ||
229                         (value == -1 && (byte & 0x40)))
230                         more = 0;
231                 else
232                         byte |= 0x80;
233                 emit_byte (w, byte);
234         }
235 }
236
237 static G_GNUC_UNUSED void
238 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
239 {
240         guint8 *p = buf;
241
242         do {
243                 guint8 b = value & 0x7f;
244                 value >>= 7;
245                 if (value != 0) /* more bytes to come */
246                         b |= 0x80;
247                 *p ++ = b;
248         } while (value);
249
250         *endbuf = p;
251 }
252
253 static G_GNUC_UNUSED void
254 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
255 {
256         gboolean more = 1;
257         gboolean negative = (value < 0);
258         guint32 size = 32;
259         guint8 byte;
260         guint8 *p = buf;
261
262         while (more) {
263                 byte = value & 0x7f;
264                 value >>= 7;
265                 /* the following is unnecessary if the
266                  * implementation of >>= uses an arithmetic rather
267                  * than logical shift for a signed left operand
268                  */
269                 if (negative)
270                         /* sign extend */
271                         value |= - (1 <<(size - 7));
272                 /* sign bit of byte is second high order bit (0x40) */
273                 if ((value == 0 && !(byte & 0x40)) ||
274                         (value == -1 && (byte & 0x40)))
275                         more = 0;
276                 else
277                         byte |= 0x80;
278                 *p ++= byte;
279         }
280
281         *endbuf = p;
282 }
283
284 static void
285 emit_dwarf_abbrev (MonoDwarfWriter *w, int code, int tag, gboolean has_child,
286                                    int *attrs, int attrs_len)
287 {
288         int i;
289
290         emit_uleb128 (w, code);
291         emit_uleb128 (w, tag);
292         emit_byte (w, has_child);
293
294         for (i = 0; i < attrs_len; i++)
295                 emit_uleb128 (w, attrs [i]);
296         emit_uleb128 (w, 0);
297         emit_uleb128 (w, 0);
298 }
299
300 static void
301 emit_cie (MonoDwarfWriter *w)
302 {
303         emit_section_change (w, ".debug_frame", 0);
304
305         emit_alignment (w, 8);
306
307         /* Emit a CIE */
308         emit_symbol_diff (w, ".Lcie0_end", ".Lcie0_start", 0); /* length */
309         emit_label (w, ".Lcie0_start");
310         emit_int32 (w, 0xffffffff); /* CIE id */
311         emit_byte (w, 3); /* version */
312         emit_string (w, ""); /* augmention */
313         emit_sleb128 (w, 1); /* code alignment factor */
314         emit_sleb128 (w, mono_unwind_get_dwarf_data_align ()); /* data alignment factor */
315         emit_uleb128 (w, mono_unwind_get_dwarf_pc_reg ());
316
317         w->cie_program = w->cie_program;
318         if (w->cie_program) {
319                 guint32 uw_info_len;
320                 guint8 *uw_info = mono_unwind_ops_encode (w->cie_program, &uw_info_len);
321                 emit_bytes (w, uw_info, uw_info_len);
322                 g_free (uw_info);
323         }
324
325         emit_alignment (w, sizeof (gpointer));
326         emit_label (w, ".Lcie0_end");
327 }
328
329 static void
330 emit_pointer_value (MonoDwarfWriter *w, gpointer ptr)
331 {
332         gssize val = (gssize)ptr;
333         emit_bytes (w, (guint8*)&val, sizeof (gpointer));
334 }
335
336 static void
337 emit_fde (MonoDwarfWriter *w, int fde_index, char *start_symbol, char *end_symbol,
338                   guint8 *code, guint32 code_size, GSList *unwind_ops, gboolean use_cie)
339 {
340         char symbol1 [128];
341         char symbol2 [128];
342         GSList *l;
343         guint8 *uw_info;
344         guint32 uw_info_len;
345
346         emit_section_change (w, ".debug_frame", 0);
347
348         sprintf (symbol1, ".Lfde%d_start", fde_index);
349         sprintf (symbol2, ".Lfde%d_end", fde_index);
350         emit_symbol_diff (w, symbol2, symbol1, 0); /* length */
351         emit_label (w, symbol1);
352         emit_int32 (w, 0); /* CIE_pointer */
353         if (start_symbol) {
354                 emit_pointer (w, start_symbol); /* initial_location */
355                 if (end_symbol)
356                         emit_symbol_diff (w, end_symbol, start_symbol, 0); /* address_range */
357                 else {
358                         g_assert (code_size);
359                         emit_int32 (w, code_size);
360                 }
361         } else {
362                 emit_pointer_value (w, code);
363                 emit_int32 (w, code_size);
364         }
365 #if SIZEOF_VOID_P == 8
366         /* Upper 32 bits of code size */
367         emit_int32 (w, 0);
368 #endif
369
370         l = unwind_ops;
371         if (w->cie_program) {
372                 // FIXME: Check that the ops really begin with the CIE program */
373                 int i;
374
375                 for (i = 0; i < g_slist_length (w->cie_program); ++i)
376                         l = l->next;
377         }
378
379         /* Convert the list of MonoUnwindOps to the format used by DWARF */     
380         uw_info = mono_unwind_ops_encode (l, &uw_info_len);
381         emit_bytes (w, uw_info, uw_info_len);
382         g_free (uw_info);
383
384         emit_alignment (w, sizeof (mgreg_t));
385         emit_label (w, symbol2);
386 }
387
388 /* Abbrevations */
389 #define ABBREV_COMPILE_UNIT 1
390 #define ABBREV_SUBPROGRAM 2
391 #define ABBREV_PARAM 3
392 #define ABBREV_BASE_TYPE 4
393 #define ABBREV_STRUCT_TYPE 5
394 #define ABBREV_DATA_MEMBER 6
395 #define ABBREV_TYPEDEF 7
396 #define ABBREV_ENUM_TYPE 8
397 #define ABBREV_ENUMERATOR 9
398 #define ABBREV_NAMESPACE 10
399 #define ABBREV_VARIABLE 11
400 #define ABBREV_VARIABLE_LOCLIST 12
401 #define ABBREV_POINTER_TYPE 13
402 #define ABBREV_REFERENCE_TYPE 14
403 #define ABBREV_PARAM_LOCLIST 15
404 #define ABBREV_INHERITANCE 16
405 #define ABBREV_STRUCT_TYPE_NOCHILDREN 17
406
407 static int compile_unit_attr [] = {
408         DW_AT_producer     ,DW_FORM_string,
409     DW_AT_name         ,DW_FORM_string,
410     DW_AT_comp_dir     ,DW_FORM_string,
411         DW_AT_language     ,DW_FORM_data1,
412     DW_AT_low_pc       ,DW_FORM_addr,
413     DW_AT_high_pc      ,DW_FORM_addr,
414         DW_AT_stmt_list    ,DW_FORM_data4
415 };
416
417 static int subprogram_attr [] = {
418         DW_AT_name         , DW_FORM_string,
419     DW_AT_low_pc       , DW_FORM_addr,
420     DW_AT_high_pc      , DW_FORM_addr,
421         DW_AT_frame_base   , DW_FORM_block1
422 };
423
424 static int param_attr [] = {
425         DW_AT_name,     DW_FORM_string,
426         DW_AT_type,     DW_FORM_ref4,
427         DW_AT_location, DW_FORM_block1
428 };
429
430 static int param_loclist_attr [] = {
431         DW_AT_name,     DW_FORM_string,
432         DW_AT_type,     DW_FORM_ref4,
433         DW_AT_location, DW_FORM_data4
434 };
435
436 static int base_type_attr [] = {
437         DW_AT_byte_size,   DW_FORM_data1,
438         DW_AT_encoding,    DW_FORM_data1,
439         DW_AT_name,        DW_FORM_string
440 };
441
442 static int struct_type_attr [] = {
443         DW_AT_name,        DW_FORM_string,
444         DW_AT_byte_size,   DW_FORM_udata,
445 };
446
447 static int data_member_attr [] = {
448         DW_AT_name,        DW_FORM_string,
449         DW_AT_type,        DW_FORM_ref4,
450         DW_AT_data_member_location, DW_FORM_block1
451 };
452
453 static int typedef_attr [] = {
454         DW_AT_name,        DW_FORM_string,
455         DW_AT_type,        DW_FORM_ref4
456 };
457
458 static int pointer_type_attr [] = {
459         DW_AT_type,        DW_FORM_ref4,
460 };
461
462 static int reference_type_attr [] = {
463         DW_AT_type,        DW_FORM_ref4,
464 };
465
466 static int enum_type_attr [] = {
467         DW_AT_name,        DW_FORM_string,
468         DW_AT_byte_size,   DW_FORM_udata,
469         DW_AT_type,        DW_FORM_ref4,
470 };
471
472 static int enumerator_attr [] = {
473         DW_AT_name,        DW_FORM_string,
474         DW_AT_const_value, DW_FORM_sdata,
475 };
476
477 static int namespace_attr [] = {
478         DW_AT_name,        DW_FORM_string,
479 };
480
481 static int variable_attr [] = {
482         DW_AT_name,     DW_FORM_string,
483         DW_AT_type,     DW_FORM_ref4,
484         DW_AT_location, DW_FORM_block1
485 };
486
487 static int variable_loclist_attr [] = {
488         DW_AT_name,     DW_FORM_string,
489         DW_AT_type,     DW_FORM_ref4,
490         DW_AT_location, DW_FORM_data4
491 };
492  
493 static int inheritance_attr [] = {
494         DW_AT_type,        DW_FORM_ref4,
495         DW_AT_data_member_location, DW_FORM_block1
496 };
497
498 typedef struct DwarfBasicType {
499         const char *die_name, *name;
500         int type;
501         int size;
502         int encoding;
503 } DwarfBasicType;
504
505 static DwarfBasicType basic_types [] = {
506         { ".LDIE_I1", "sbyte", MONO_TYPE_I1, 1, DW_ATE_signed },
507         { ".LDIE_U1", "byte", MONO_TYPE_U1, 1, DW_ATE_unsigned },
508         { ".LDIE_I2", "short", MONO_TYPE_I2, 2, DW_ATE_signed },
509         { ".LDIE_U2", "ushort", MONO_TYPE_U2, 2, DW_ATE_unsigned },
510         { ".LDIE_I4", "int", MONO_TYPE_I4, 4, DW_ATE_signed },
511         { ".LDIE_U4", "uint", MONO_TYPE_U4, 4, DW_ATE_unsigned },
512         { ".LDIE_I8", "long", MONO_TYPE_I8, 8, DW_ATE_signed },
513         { ".LDIE_U8", "ulong", MONO_TYPE_U8, 8, DW_ATE_unsigned },
514         { ".LDIE_I", "intptr", MONO_TYPE_I, SIZEOF_VOID_P, DW_ATE_signed },
515         { ".LDIE_U", "uintptr", MONO_TYPE_U, SIZEOF_VOID_P, DW_ATE_unsigned },
516         { ".LDIE_R4", "float", MONO_TYPE_R4, 4, DW_ATE_float },
517         { ".LDIE_R8", "double", MONO_TYPE_R8, 8, DW_ATE_float },
518         { ".LDIE_BOOLEAN", "boolean", MONO_TYPE_BOOLEAN, 1, DW_ATE_boolean },
519         { ".LDIE_CHAR", "char", MONO_TYPE_CHAR, 2, DW_ATE_unsigned_char },
520         { ".LDIE_STRING", "string", MONO_TYPE_STRING, sizeof (gpointer), DW_ATE_address },
521         { ".LDIE_OBJECT", "object", MONO_TYPE_OBJECT, sizeof (gpointer), DW_ATE_address },
522         { ".LDIE_SZARRAY", "object", MONO_TYPE_SZARRAY, sizeof (gpointer), DW_ATE_address },
523 };
524
525 /* Constants for encoding line number special opcodes */
526 #define OPCODE_BASE 13
527 #define LINE_BASE -5
528 #define LINE_RANGE 14
529
530 /* Subsections of the .debug_line section */
531 #define LINE_SUBSECTION_HEADER 1
532 #define LINE_SUBSECTION_INCLUDES 2
533 #define LINE_SUBSECTION_FILES 3
534 #define LINE_SUBSECTION_DATA 4
535 #define LINE_SUBSECTION_END 5
536
537 static int
538 emit_line_number_file_name (MonoDwarfWriter *w, const char *name,
539                                                         gint64 last_mod_time, gint64 file_size)
540 {
541         int index;
542         int dir_index;
543         char *basename = NULL;
544
545         if (!w->file_to_index)
546                 w->file_to_index = g_hash_table_new (g_str_hash, g_str_equal);
547
548         index = GPOINTER_TO_UINT (g_hash_table_lookup (w->file_to_index, name));
549         if (index > 0)
550                 return index;
551
552         if (g_path_is_absolute (name)) {
553                 char *dir = g_path_get_dirname (name);
554
555                 if (!w->dir_to_index)
556                         w->dir_to_index = g_hash_table_new (g_str_hash, g_str_equal);
557
558                 dir_index = GPOINTER_TO_UINT (g_hash_table_lookup (w->dir_to_index, dir));
559                 if (dir_index == 0) {
560                         emit_section_change (w, ".debug_line", LINE_SUBSECTION_INCLUDES);
561                         emit_string (w, dir);
562
563                         dir_index = ++ w->line_number_dir_index;
564                         g_hash_table_insert (w->dir_to_index, g_strdup (dir), GUINT_TO_POINTER (dir_index));
565                 }
566
567                 g_free (dir);
568
569                 basename = g_path_get_basename (name);
570         } else {
571                 dir_index = 0;
572         }
573
574         emit_section_change (w, ".debug_line", LINE_SUBSECTION_FILES);
575
576         if (basename)
577                 emit_string (w, basename);
578         else
579                 emit_string (w, name);
580         emit_uleb128 (w, dir_index);
581         emit_byte (w, 0);
582         emit_byte (w, 0);
583
584         emit_section_change (w, ".debug_line", LINE_SUBSECTION_DATA);
585
586         if (basename)
587                 g_free (basename);
588
589         index = ++ w->line_number_file_index;
590         g_hash_table_insert (w->file_to_index, g_strdup (name), GUINT_TO_POINTER (index));
591
592         return index;
593 }
594
595 static void
596 emit_line_number_info_begin (MonoDwarfWriter *w)
597 {
598         /* Line number info header */
599         /* 
600          * GAS seems to emit its own data to the end of the first subsection, so we use
601          * subsections 1, 2 etc:
602          * 1 - contains the header
603          * 2 - contains the file names
604          * 3 - contains the end of the header + the data
605          * 4 - the end symbol
606          */
607         emit_section_change (w, ".debug_line", 0);
608         emit_label (w, ".Ldebug_line_section_start");
609         emit_section_change (w, ".debug_line", LINE_SUBSECTION_HEADER);
610         emit_label (w, ".Ldebug_line_start");
611         emit_symbol_diff (w, ".Ldebug_line_end", ".", -4); /* length */
612         emit_int16 (w, 0x2); /* version */
613         emit_symbol_diff (w, ".Ldebug_line_header_end", ".", -4); /* header_length */
614         emit_byte (w, 1); /* minimum_instruction_length */
615         emit_byte (w, 1); /* default_is_stmt */
616         emit_byte (w, LINE_BASE); /* line_base */
617         emit_byte (w, LINE_RANGE); /* line_range */
618         emit_byte (w, OPCODE_BASE); /* opcode_base */
619         emit_byte (w, 0); /* standard_opcode_lengths */
620         emit_byte (w, 1);
621         emit_byte (w, 1);
622         emit_byte (w, 1);
623         emit_byte (w, 1);
624         emit_byte (w, 0);
625         emit_byte (w, 0);
626         emit_byte (w, 0);
627         emit_byte (w, 1);
628         emit_byte (w, 0);
629         emit_byte (w, 0);
630         emit_byte (w, 1);
631
632         /* Includes */
633         emit_section_change (w, ".debug_line", LINE_SUBSECTION_INCLUDES);
634
635         /* End of Includes */
636         emit_section_change (w, ".debug_line", LINE_SUBSECTION_FILES);
637         emit_byte (w, 0);
638
639         /* Files */
640         emit_line_number_file_name (w, "xdb.il", 0, 0);
641
642         /* End of Files */
643         emit_section_change (w, ".debug_line", LINE_SUBSECTION_DATA);
644         emit_byte (w, 0);
645
646         emit_label (w, ".Ldebug_line_header_end");
647
648         /* Emit this into a separate subsection so it gets placed at the end */ 
649         emit_section_change (w, ".debug_line", LINE_SUBSECTION_END);
650
651         emit_byte (w, 0);
652         emit_byte (w, 1);
653         emit_byte (w, DW_LNE_end_sequence);
654
655         emit_label (w, ".Ldebug_line_end");
656 }
657
658 /*
659  * Some assemblers like apple's do not support subsections, so we can't place
660  * .Ldebug_info_end at the end of the section using subsections. Instead, we 
661  * define it every time something gets added to the .debug_info section.
662  * The apple assember seems to use the last definition.
663  */
664 static void
665 emit_debug_info_end (MonoDwarfWriter *w)
666 {
667         /* This doesn't seem to work/required with recent iphone sdk versions */
668 #if 0
669         if (!img_writer_subsections_supported (w->w))
670                 fprintf (w->fp, "\n.set %sdebug_info_end,.\n", w->temp_prefix);
671 #endif
672 }
673
674 void
675 mono_dwarf_writer_emit_base_info (MonoDwarfWriter *w, GSList *base_unwind_program)
676 {
677         char *s, *build_info;
678         int i;
679
680         if (!img_writer_subsections_supported (w->w))
681                 /* Can't emit line number info without subsections */
682                 w->emit_line = FALSE;
683         else
684                 w->emit_line = TRUE;
685
686         w->cie_program = base_unwind_program;
687
688         emit_section_change (w, ".debug_abbrev", 0);
689         emit_dwarf_abbrev (w, ABBREV_COMPILE_UNIT, DW_TAG_compile_unit, TRUE, 
690                                            compile_unit_attr, G_N_ELEMENTS (compile_unit_attr));
691         emit_dwarf_abbrev (w, ABBREV_SUBPROGRAM, DW_TAG_subprogram, TRUE, 
692                                            subprogram_attr, G_N_ELEMENTS (subprogram_attr));
693         emit_dwarf_abbrev (w, ABBREV_PARAM, DW_TAG_formal_parameter, FALSE, 
694                                            param_attr, G_N_ELEMENTS (param_attr));
695         emit_dwarf_abbrev (w, ABBREV_PARAM_LOCLIST, DW_TAG_formal_parameter, FALSE, 
696                                            param_loclist_attr, G_N_ELEMENTS (param_loclist_attr));
697         emit_dwarf_abbrev (w, ABBREV_BASE_TYPE, DW_TAG_base_type, FALSE, 
698                                            base_type_attr, G_N_ELEMENTS (base_type_attr));
699         emit_dwarf_abbrev (w, ABBREV_STRUCT_TYPE, DW_TAG_class_type, TRUE, 
700                                            struct_type_attr, G_N_ELEMENTS (struct_type_attr));
701         emit_dwarf_abbrev (w, ABBREV_STRUCT_TYPE_NOCHILDREN, DW_TAG_class_type, FALSE, 
702                                            struct_type_attr, G_N_ELEMENTS (struct_type_attr));
703         emit_dwarf_abbrev (w, ABBREV_DATA_MEMBER, DW_TAG_member, FALSE, 
704                                            data_member_attr, G_N_ELEMENTS (data_member_attr));
705         emit_dwarf_abbrev (w, ABBREV_TYPEDEF, DW_TAG_typedef, FALSE, 
706                                            typedef_attr, G_N_ELEMENTS (typedef_attr));
707         emit_dwarf_abbrev (w, ABBREV_ENUM_TYPE, DW_TAG_enumeration_type, TRUE,
708                                            enum_type_attr, G_N_ELEMENTS (enum_type_attr));
709         emit_dwarf_abbrev (w, ABBREV_ENUMERATOR, DW_TAG_enumerator, FALSE,
710                                            enumerator_attr, G_N_ELEMENTS (enumerator_attr));
711         emit_dwarf_abbrev (w, ABBREV_NAMESPACE, DW_TAG_namespace, TRUE,
712                                            namespace_attr, G_N_ELEMENTS (namespace_attr));
713         emit_dwarf_abbrev (w, ABBREV_VARIABLE, DW_TAG_variable, FALSE,
714                                            variable_attr, G_N_ELEMENTS (variable_attr));
715         emit_dwarf_abbrev (w, ABBREV_VARIABLE_LOCLIST, DW_TAG_variable, FALSE,
716                                            variable_loclist_attr, G_N_ELEMENTS (variable_loclist_attr));
717         emit_dwarf_abbrev (w, ABBREV_POINTER_TYPE, DW_TAG_pointer_type, FALSE,
718                                            pointer_type_attr, G_N_ELEMENTS (pointer_type_attr));
719         emit_dwarf_abbrev (w, ABBREV_REFERENCE_TYPE, DW_TAG_reference_type, FALSE,
720                                            reference_type_attr, G_N_ELEMENTS (reference_type_attr));
721         emit_dwarf_abbrev (w, ABBREV_INHERITANCE, DW_TAG_inheritance, FALSE,
722                                            inheritance_attr, G_N_ELEMENTS (inheritance_attr));
723         emit_byte (w, 0);
724
725         emit_section_change (w, ".debug_info", 0);
726         emit_label (w, ".Ldebug_info_start");
727         emit_symbol_diff (w, ".Ldebug_info_end", ".Ldebug_info_begin", 0); /* length */
728         emit_label (w, ".Ldebug_info_begin");
729         emit_int16 (w, 0x2); /* DWARF version 2 */
730         emit_int32 (w, 0); /* .debug_abbrev offset */
731         emit_byte (w, sizeof (gpointer)); /* address size */
732
733         if (img_writer_subsections_supported (w->w) && w->appending) {
734                 /* Emit this into a separate section so it gets placed at the end */
735                 emit_section_change (w, ".debug_info", 1);
736                 emit_byte (w, 0); /* close COMPILE_UNIT */
737                 emit_label (w, ".Ldebug_info_end");
738                 emit_section_change (w, ".debug_info", 0);
739         }
740
741         /* Compilation unit */
742         emit_uleb128 (w, ABBREV_COMPILE_UNIT);
743         build_info = mono_get_runtime_build_info ();
744         s = g_strdup_printf ("Mono AOT Compiler %s", build_info);
745         emit_string (w, s);
746         g_free (build_info);
747         g_free (s);
748         emit_string (w, "JITted code");
749         emit_string (w, "");
750         emit_byte (w, DW_LANG_C);
751         emit_pointer_value (w, 0);
752         emit_pointer_value (w, 0);
753         /* offset into .debug_line section */
754         emit_symbol_diff (w, ".Ldebug_line_start", ".Ldebug_line_section_start", 0);
755
756         /* Base types */
757         for (i = 0; i < G_N_ELEMENTS (basic_types); ++i) {
758                 emit_label (w, basic_types [i].die_name);
759                 emit_uleb128 (w, ABBREV_BASE_TYPE);
760                 emit_byte (w, basic_types [i].size);
761                 emit_byte (w, basic_types [i].encoding);
762                 emit_string (w, basic_types [i].name);
763         }
764
765         emit_debug_info_end (w);
766
767         /* debug_loc section */
768         emit_section_change (w, ".debug_loc", 0);
769         emit_label (w, ".Ldebug_loc_start");
770
771         /* debug_line section */
772         /*
773          * We emit some info even if emit_line is FALSE, as the
774          * apple linker seems to require a .debug_line section.
775          */
776         emit_line_number_info_begin (w);
777
778         emit_cie (w);
779 }
780
781 /*
782  * mono_dwarf_writer_close:
783  *
784  *   Finalize the emitted debugging info.
785  */
786 void
787 mono_dwarf_writer_close (MonoDwarfWriter *w)
788 {
789         if (!w->appending) {
790                 emit_section_change (w, ".debug_info", 0);
791                 emit_byte (w, 0); /* close COMPILE_UNIT */
792                 emit_label (w, ".Ldebug_info_end");
793         }
794 }
795
796 static const char* emit_type (MonoDwarfWriter *w, MonoType *t);
797
798 /* Returns the local symbol pointing to the emitted debug info */
799 static char*
800 emit_class_dwarf_info (MonoDwarfWriter *w, MonoClass *klass, gboolean vtype)
801 {
802         char *die, *pointer_die, *reference_die;
803         char *full_name, *p;
804         gpointer iter;
805         MonoClassField *field;
806         const char *fdie;
807         int k;
808         gboolean emit_namespace = FALSE, has_children;
809         GHashTable *cache;
810
811         // FIXME: Appdomains
812         if (!w->class_to_die)
813                 w->class_to_die = g_hash_table_new (NULL, NULL);
814         if (!w->class_to_vtype_die)
815                 w->class_to_vtype_die = g_hash_table_new (NULL, NULL);
816         if (!w->class_to_pointer_die)
817                 w->class_to_pointer_die = g_hash_table_new (NULL, NULL);
818         if (!w->class_to_reference_die)
819                 w->class_to_reference_die = g_hash_table_new (NULL, NULL);
820
821         if (vtype)
822                 cache = w->class_to_vtype_die;
823         else
824                 cache = w->class_to_die;
825
826         die = g_hash_table_lookup (cache, klass);
827         if (die)
828                 return die;
829
830         if (!((klass->byval_arg.type == MONO_TYPE_CLASS) || (klass->byval_arg.type == MONO_TYPE_OBJECT) || klass->byval_arg.type == MONO_TYPE_GENERICINST || klass->enumtype || (klass->byval_arg.type == MONO_TYPE_VALUETYPE && vtype)))
831                 return NULL;
832
833         /*
834          * FIXME: gdb can't handle namespaces in languages it doesn't know about.
835          */
836         /*
837         if (klass->name_space && klass->name_space [0] != '\0')
838                 emit_namespace = TRUE;
839         */
840         if (emit_namespace) {
841                 emit_uleb128 (w, ABBREV_NAMESPACE);
842                 emit_string (w, klass->name_space);
843         }
844
845         full_name = g_strdup_printf ("%s%s%s", klass->name_space, klass->name_space ? "." : "", klass->name);
846         /* 
847          * gdb doesn't support namespaces for non-C++ dwarf objects, so use _
848          * to separate components.
849          */
850         for (p = full_name; *p; p ++)
851                 if (*p == '.')
852                         *p = '_';
853
854         die = g_strdup_printf (".LTDIE_%d", w->tdie_index);
855         pointer_die = g_strdup_printf (".LTDIE_%d_POINTER", w->tdie_index);
856         reference_die = g_strdup_printf (".LTDIE_%d_REFERENCE", w->tdie_index);
857         w->tdie_index ++;
858
859         g_hash_table_insert (w->class_to_pointer_die, klass, pointer_die);
860         g_hash_table_insert (w->class_to_reference_die, klass, reference_die);
861         g_hash_table_insert (cache, klass, die);
862
863         if (klass->enumtype) {
864                 int size = mono_class_value_size (mono_class_from_mono_type (mono_class_enum_basetype (klass)), NULL);
865
866                 emit_label (w, die);
867
868                 emit_uleb128 (w, ABBREV_ENUM_TYPE);
869                 emit_string (w, full_name);
870                 emit_uleb128 (w, size);
871                 for (k = 0; k < G_N_ELEMENTS (basic_types); ++k)
872                         if (basic_types [k].type == mono_class_enum_basetype (klass)->type)
873                                 break;
874                 g_assert (k < G_N_ELEMENTS (basic_types));
875                 emit_symbol_diff (w, basic_types [k].die_name, ".Ldebug_info_start", 0);
876
877                 /* Emit enum values */
878                 iter = NULL;
879                 while ((field = mono_class_get_fields (klass, &iter))) {
880                         const char *p;
881                         int len;
882                         MonoTypeEnum def_type;
883
884                         if (strcmp ("value__", mono_field_get_name (field)) == 0)
885                                 continue;
886                         if (mono_field_is_deleted (field))
887                                 continue;
888
889                         emit_uleb128 (w, ABBREV_ENUMERATOR);
890                         emit_string (w, mono_field_get_name (field));
891
892                         p = mono_class_get_field_default_value (field, &def_type);
893                         len = mono_metadata_decode_blob_size (p, &p);
894                         switch (mono_class_enum_basetype (klass)->type) {
895                         case MONO_TYPE_U1:
896                         case MONO_TYPE_I1:
897                         case MONO_TYPE_BOOLEAN:
898                                 emit_sleb128 (w, *p);
899                                 break;
900                         case MONO_TYPE_U2:
901                         case MONO_TYPE_I2:
902                         case MONO_TYPE_CHAR:
903                                 emit_sleb128 (w, read16 (p));
904                                 break;
905                         case MONO_TYPE_U4:
906                         case MONO_TYPE_I4:
907                                 emit_sleb128 (w, read32 (p));
908                                 break;
909                         case MONO_TYPE_U8:
910                         case MONO_TYPE_I8:
911                                 emit_sleb128 (w, read64 (p));
912                                 break;
913                         case MONO_TYPE_I:
914                         case MONO_TYPE_U:
915 #if SIZEOF_VOID_P == 8
916                                 emit_sleb128 (w, read64 (p));
917 #else
918                                 emit_sleb128 (w, read32 (p));
919 #endif
920                                 break;
921                         default:
922                                 g_assert_not_reached ();
923                         }
924                 }
925
926                 has_children = TRUE;
927         } else {
928                 guint8 buf [128];
929                 guint8 *p;
930                 char *parent_die;
931
932                 if (klass->parent)
933                         parent_die = emit_class_dwarf_info (w, klass->parent, FALSE);
934                 else
935                         parent_die = NULL;
936
937                 /* Emit field types */
938                 iter = NULL;
939                 while ((field = mono_class_get_fields (klass, &iter))) {
940                         if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
941                                 continue;
942
943                         emit_type (w, field->type);
944                 }
945
946                 iter = NULL;
947                 has_children = parent_die || mono_class_get_fields (klass, &iter);
948
949                 emit_label (w, die);
950
951                 emit_uleb128 (w, has_children ? ABBREV_STRUCT_TYPE : ABBREV_STRUCT_TYPE_NOCHILDREN);
952                 emit_string (w, full_name);
953                 emit_uleb128 (w, klass->instance_size);
954
955                 if (parent_die) {
956                         emit_uleb128 (w, ABBREV_INHERITANCE);
957                         emit_symbol_diff (w, parent_die, ".Ldebug_info_start", 0);
958
959                         p = buf;
960                         *p ++= DW_OP_plus_uconst;
961                         encode_uleb128 (0, p, &p);
962                         emit_byte (w, p - buf);
963                         emit_bytes (w, buf, p - buf);
964                 }
965
966                 /* Emit fields */
967                 iter = NULL;
968                 while ((field = mono_class_get_fields (klass, &iter))) {
969                         if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
970                                 continue;
971
972                         fdie = emit_type (w, field->type);
973                         if (fdie) {
974                                 emit_uleb128 (w, ABBREV_DATA_MEMBER);
975                                 emit_string (w, field->name);
976                                 emit_symbol_diff (w, fdie, ".Ldebug_info_start", 0);
977                                 /* location */
978                                 p = buf;
979                                 *p ++= DW_OP_plus_uconst;
980                                 if (klass->valuetype && vtype)
981                                         encode_uleb128 (field->offset - sizeof (MonoObject), p, &p);
982                                 else
983                                         encode_uleb128 (field->offset, p, &p);
984
985                                 emit_byte (w, p - buf);
986                                 emit_bytes (w, buf, p - buf);
987                         }
988                 }
989         }
990
991         /* Type end */
992         if (has_children)
993                 emit_uleb128 (w, 0x0);
994
995         /* Add a typedef, so we can reference the type without a 'struct' in gdb */
996         emit_uleb128 (w, ABBREV_TYPEDEF);
997         emit_string (w, full_name);
998         emit_symbol_diff (w, die, ".Ldebug_info_start", 0);
999
1000         /* Add a pointer type */
1001         emit_label (w, pointer_die);
1002
1003         emit_uleb128 (w, ABBREV_POINTER_TYPE);
1004         emit_symbol_diff (w, die, ".Ldebug_info_start", 0);
1005
1006         /* Add a reference type */
1007         emit_label (w, reference_die);
1008
1009         emit_uleb128 (w, ABBREV_REFERENCE_TYPE);
1010         emit_symbol_diff (w, die, ".Ldebug_info_start", 0);
1011
1012         g_free (full_name);
1013
1014         if (emit_namespace) {
1015                 /* Namespace end */
1016                 emit_uleb128 (w, 0x0);
1017         }
1018
1019         return die;
1020 }
1021
1022 static const char*
1023 emit_type (MonoDwarfWriter *w, MonoType *t)
1024 {
1025         MonoClass *klass = mono_class_from_mono_type (t);
1026         int j;
1027         const char *tdie;
1028
1029         if (t->byref) {
1030                 if (t->type == MONO_TYPE_VALUETYPE) {
1031                         tdie = emit_class_dwarf_info (w, klass, TRUE);
1032                         if (tdie)
1033                                 return g_hash_table_lookup (w->class_to_pointer_die, klass);
1034                 }
1035                 else {
1036                         tdie = emit_class_dwarf_info (w, klass, FALSE);
1037                         /* Should return a pointer type to a reference */
1038                 }
1039                 // FIXME:
1040                 t = &mono_defaults.int_class->byval_arg;
1041         }
1042         for (j = 0; j < G_N_ELEMENTS (basic_types); ++j)
1043                 if (basic_types [j].type == t->type)
1044                         break;
1045         if (j < G_N_ELEMENTS (basic_types))
1046                 tdie = basic_types [j].die_name;
1047         else {
1048                 switch (t->type) {
1049                 case MONO_TYPE_CLASS:
1050                         emit_class_dwarf_info (w, klass, FALSE);
1051                         tdie = g_hash_table_lookup (w->class_to_reference_die, klass);
1052                         //tdie = ".LDIE_OBJECT";
1053                         break;
1054                 case MONO_TYPE_ARRAY:
1055                         tdie = ".LDIE_OBJECT";
1056                         break;
1057                 case MONO_TYPE_VALUETYPE:
1058                         if (klass->enumtype)
1059                                 tdie = emit_class_dwarf_info (w, klass, FALSE);
1060                         else
1061                                 tdie = ".LDIE_I4";
1062                         break;
1063                 case MONO_TYPE_GENERICINST:
1064                         if (!MONO_TYPE_ISSTRUCT (t)) {
1065                                 emit_class_dwarf_info (w, klass, FALSE);
1066                                 tdie = g_hash_table_lookup (w->class_to_reference_die, klass);
1067                         } else {
1068                                 tdie = ".LDIE_I4";
1069                         }
1070                         break;
1071                 case MONO_TYPE_PTR:
1072                         tdie = ".LDIE_I";
1073                         break;
1074                 default:
1075                         tdie = ".LDIE_I4";
1076                         break;
1077                 }
1078         }
1079
1080         return tdie;
1081 }
1082
1083 static void
1084 emit_var_type (MonoDwarfWriter *w, MonoType *t)
1085 {
1086         const char *tdie;
1087
1088         tdie = emit_type (w, t);
1089
1090         emit_symbol_diff (w, tdie, ".Ldebug_info_start", 0);
1091 }
1092
1093 static void
1094 encode_var_location (MonoDwarfWriter *w, MonoInst *ins, guint8 *p, guint8 **endp)
1095 {
1096         /* location */
1097         /* FIXME: This needs a location list, since the args can go from reg->stack */
1098         if (!ins || ins->flags & MONO_INST_IS_DEAD) {
1099                 /* gdb treats this as optimized out */
1100         } else if (ins->opcode == OP_REGVAR) {
1101                 *p = DW_OP_reg0 + mono_hw_reg_to_dwarf_reg (ins->dreg);
1102                 p ++;
1103         } else if (ins->opcode == OP_REGOFFSET) {
1104                 *p ++= DW_OP_breg0 + mono_hw_reg_to_dwarf_reg (ins->inst_basereg);
1105                 encode_sleb128 (ins->inst_offset, p, &p);
1106         } else {
1107                 // FIXME:
1108                 *p ++ = DW_OP_reg0;
1109         }
1110
1111         *endp = p;
1112 }
1113
1114 static void
1115 emit_loclist (MonoDwarfWriter *w, MonoInst *ins,
1116                           guint8 *loclist_begin_addr, guint8 *loclist_end_addr,
1117                           guint8 *expr, guint32 expr_len)
1118 {
1119         char label [128];
1120
1121         emit_push_section (w, ".debug_loc", 0);
1122         sprintf (label, ".Lloclist_%d", w->loclist_index ++ );
1123         emit_label (w, label);
1124
1125         emit_pointer_value (w, loclist_begin_addr);
1126         emit_pointer_value (w, loclist_end_addr);
1127         emit_byte (w, expr_len % 256);
1128         emit_byte (w, expr_len / 256);
1129         emit_bytes (w, expr, expr_len);
1130
1131         emit_pointer_value (w, NULL);
1132         emit_pointer_value (w, NULL);
1133
1134         emit_pop_section (w);
1135         emit_symbol_diff (w, label, ".Ldebug_loc_start", 0);
1136 }
1137
1138 /* 
1139  * MonoDisHelper->tokener doesn't take an IP argument, and we can't add one since 
1140  * it is a public header.
1141  */
1142 static const guint8 *token_handler_ip;
1143
1144 static char*
1145 token_handler (MonoDisHelper *dh, MonoMethod *method, guint32 token)
1146 {
1147         char *res, *desc;
1148         MonoMethod *cmethod;
1149         MonoClass *klass;
1150         MonoClassField *field;
1151         gpointer data = NULL;
1152
1153         if (method->wrapper_type)
1154                 data = mono_method_get_wrapper_data (method, token);
1155
1156         switch (*token_handler_ip) {
1157         case CEE_ISINST:
1158         case CEE_CASTCLASS:
1159         case CEE_LDELEMA:
1160                 if (method->wrapper_type)
1161                         klass = data;
1162                 else
1163                         klass = mono_class_get_full (method->klass->image, token, NULL);
1164                 res = g_strdup_printf ("<%s>", klass->name);
1165                 break;
1166         case CEE_NEWOBJ:
1167         case CEE_CALL:
1168         case CEE_CALLVIRT:
1169                 if (method->wrapper_type)
1170                         cmethod = data;
1171                 else
1172                         cmethod = mono_get_method_full (method->klass->image, token, NULL, NULL);
1173                 desc = mono_method_full_name (cmethod, TRUE);
1174                 res = g_strdup_printf ("<%s>", desc);
1175                 g_free (desc);
1176                 break;
1177         case CEE_CALLI:
1178                 if (method->wrapper_type) {
1179                         desc = mono_signature_get_desc (data, FALSE);
1180                         res = g_strdup_printf ("<%s>", desc);
1181                         g_free (desc);
1182                 } else {
1183                         res = g_strdup_printf ("<0x%08x>", token);
1184                 }
1185                 break;
1186         case CEE_LDFLD:
1187         case CEE_LDSFLD:
1188         case CEE_STFLD:
1189         case CEE_STSFLD:
1190                 if (method->wrapper_type)
1191                         field = data;
1192                 else
1193                         field = mono_field_from_token (method->klass->image, token, &klass, NULL);
1194                 desc = mono_field_full_name (field);
1195                 res = g_strdup_printf ("<%s>", desc);
1196                 g_free (desc);
1197                 break;
1198         default:
1199                 res = g_strdup_printf ("<0x%08x>", token);
1200                 break;
1201         }
1202
1203         return res;
1204 }
1205
1206 /*
1207  * disasm_ins:
1208  *
1209  *   Produce a disassembled form of the IL instruction at IP. This is an extension
1210  * of mono_disasm_code_one () which can disasm tokens, handle wrapper methods, and
1211  * CEE_MONO_ opcodes.
1212  */
1213 static char*
1214 disasm_ins (MonoMethod *method, const guchar *ip, const guint8 **endip)
1215 {
1216         char *dis;
1217         MonoDisHelper dh;
1218         MonoMethodHeader *header = mono_method_get_header (method);
1219
1220         memset (&dh, 0, sizeof (dh));
1221         dh.newline = "";
1222         dh.label_format = "IL_%04x: ";
1223         dh.label_target = "IL_%04x";
1224         dh.tokener = token_handler;
1225
1226         token_handler_ip = ip;
1227         if (*ip == MONO_CUSTOM_PREFIX) {
1228                 guint32 token;
1229                 gpointer data;
1230
1231                 switch (ip [1]) {
1232                 case CEE_MONO_ICALL: {
1233                         MonoJitICallInfo *info;
1234
1235                         token = read32 (ip + 2);
1236                         data = mono_method_get_wrapper_data (method, token);
1237                         info = mono_find_jit_icall_by_addr (data);
1238                         g_assert (info);
1239
1240                         dis = g_strdup_printf ("IL_%04x: mono_icall <%s>", (int)(ip - header->code), info->name);
1241                         ip += 6;
1242                         break;
1243                 }
1244                 case CEE_MONO_CLASSCONST: {
1245                         token = read32 (ip + 2);
1246                         data = mono_method_get_wrapper_data (method, token);
1247
1248                         dis = g_strdup_printf ("IL_%04x: mono_classconst <%s>", (int)(ip - header->code), ((MonoClass*)data)->name);
1249                         ip += 6;
1250                         break;
1251                 }
1252                 default:
1253                         dis = mono_disasm_code_one (&dh, method, ip, &ip);
1254                 }
1255         } else {
1256                 dis = mono_disasm_code_one (&dh, method, ip, &ip);
1257         }
1258         token_handler_ip = NULL;
1259
1260         *endip = ip;
1261         return dis;
1262 }
1263
1264 static gint32
1265 il_offset_from_address (MonoMethod *method, MonoDebugMethodJitInfo *jit, 
1266                                                 guint32 native_offset)
1267 {
1268         int i;
1269
1270         if (!jit->line_numbers)
1271                 return -1;
1272
1273         for (i = jit->num_line_numbers - 1; i >= 0; i--) {
1274                 MonoDebugLineNumberEntry lne = jit->line_numbers [i];
1275
1276                 if (lne.native_offset <= native_offset)
1277                         return lne.il_offset;
1278         }
1279
1280         return -1;
1281 }
1282
1283 static int max_special_addr_diff = 0;
1284
1285 static inline void
1286 emit_advance_op (MonoDwarfWriter *w, int line_diff, int addr_diff)
1287 {
1288         gint64 opcode = 0;
1289
1290         /* Use a special opcode if possible */
1291         if (line_diff - LINE_BASE >= 0 && line_diff - LINE_BASE < LINE_RANGE) {
1292                 if (max_special_addr_diff == 0)
1293                         max_special_addr_diff = (255 - OPCODE_BASE) / LINE_RANGE;
1294
1295                 if (addr_diff > max_special_addr_diff && (addr_diff < 2 * max_special_addr_diff)) {
1296                         emit_byte (w, DW_LNS_const_add_pc);
1297                         addr_diff -= max_special_addr_diff;
1298                 }
1299
1300                 opcode = (line_diff - LINE_BASE) + (LINE_RANGE * addr_diff) + OPCODE_BASE;
1301                 if (opcode > 255)
1302                         opcode = 0;
1303         }
1304
1305         if (opcode != 0) {
1306                 emit_byte (w, opcode);
1307         } else {
1308                 emit_byte (w, DW_LNS_advance_line);
1309                 emit_sleb128 (w, line_diff);
1310                 emit_byte (w, DW_LNS_advance_pc);
1311                 emit_sleb128 (w, addr_diff);
1312                 emit_byte (w, DW_LNS_copy);
1313         }
1314 }
1315
1316 static gint
1317 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
1318 {
1319         if (a->native_offset == b->native_offset)
1320                 return a->il_offset - b->il_offset;
1321         else
1322                 return a->native_offset - b->native_offset;
1323 }
1324
1325 static void
1326 emit_line_number_info (MonoDwarfWriter *w, MonoMethod *method, 
1327                                            char *start_symbol, char *end_symbol,
1328                                            guint8 *code, guint32 code_size,
1329                                            MonoDebugMethodJitInfo *debug_info)
1330 {
1331         guint32 prev_line = 0;
1332         guint32 prev_native_offset = 0;
1333         int i, file_index, il_offset, prev_il_offset;
1334         gboolean first = TRUE;
1335         MonoDebugSourceLocation *loc;
1336         char *prev_file_name = NULL;
1337         MonoMethodHeader *header = mono_method_get_header (method);
1338         MonoDebugMethodInfo *minfo;
1339         GArray *ln_array;
1340         int *native_to_il_offset = NULL;
1341
1342         if (!w->emit_line)
1343                 return;
1344
1345         minfo = mono_debug_lookup_method (method);
1346
1347         /* Compute the native->IL offset mapping */
1348
1349         g_assert (code_size);
1350
1351 #ifdef _EGLIB_MAJOR
1352         /* g_array is not implemented in eglib */
1353         return;
1354 #else
1355         ln_array = g_array_sized_new (FALSE, FALSE, sizeof (MonoDebugLineNumberEntry), 
1356                                                                   debug_info->num_line_numbers);
1357         g_array_append_vals (ln_array, debug_info->line_numbers, debug_info->num_line_numbers);
1358         g_array_sort (ln_array, (GCompareFunc)compare_lne);
1359         native_to_il_offset = g_new0 (int, code_size + 1);
1360
1361         for (i = 0; i < debug_info->num_line_numbers; ++i) {
1362                 int j;
1363                 MonoDebugLineNumberEntry lne = g_array_index (ln_array, MonoDebugLineNumberEntry, i);
1364
1365                 if (i == 0) {
1366                         for (j = 0; j < lne.native_offset; ++j)
1367                                 native_to_il_offset [j] = -1;
1368                 }
1369
1370                 if (i < debug_info->num_line_numbers - 1) {
1371                         MonoDebugLineNumberEntry lne_next = g_array_index (ln_array, MonoDebugLineNumberEntry, i + 1);
1372
1373                         for (j = lne.native_offset; j < lne_next.native_offset; ++j)
1374                                 native_to_il_offset [j] = lne.il_offset;
1375                 } else {
1376                         for (j = lne.native_offset; j < code_size; ++j)
1377                                 native_to_il_offset [j] = lne.il_offset;
1378                 }
1379         }
1380         g_array_free (ln_array, TRUE);
1381 #endif
1382
1383         prev_line = 1;
1384         prev_il_offset = -1;
1385
1386         for (i = 0; i < code_size; ++i) {
1387                 if (!minfo)
1388                         continue;
1389
1390                 if (!debug_info->line_numbers)
1391                         continue;
1392
1393                 if (native_to_il_offset)
1394                         il_offset = native_to_il_offset [i];
1395                 else
1396                         il_offset = il_offset_from_address (method, debug_info, i);
1397                 /*
1398                 il_offset = il_offset_from_address (method, debug_info, i);
1399
1400                 g_assert (il_offset == native_to_il_offset [i]);
1401                 */
1402
1403                 il_offset = native_to_il_offset [i];
1404                 if (il_offset < 0)
1405                         continue;
1406
1407                 if (il_offset == prev_il_offset)
1408                         continue;
1409
1410                 prev_il_offset = il_offset;
1411
1412                 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
1413
1414                 // Added the loc->source_file check as otherwise we can
1415                 // crash, see the sample in bug 553191 that makes this code
1416                 // crash when we call strcmp on loc->source_file below
1417                 if (loc && loc->source_file) {
1418                         int line_diff = (gint32)loc->row - (gint32)prev_line;
1419                         int addr_diff = i - prev_native_offset;
1420
1421                         if (first) {    
1422                                 emit_section_change (w, ".debug_line", LINE_SUBSECTION_DATA);
1423
1424                                 emit_byte (w, 0);
1425                                 emit_byte (w, sizeof (gpointer) + 1);
1426                                 emit_byte (w, DW_LNE_set_address);
1427                                 if (start_symbol)
1428                                         emit_pointer_unaligned (w, start_symbol);
1429                                 else
1430                                         emit_pointer_value (w, code);
1431
1432                                 /* 
1433                                  * The prolog+initlocals region does not have a line number, this
1434                                  * makes them belong to the first line of the method.
1435                                  */
1436                                 emit_byte (w, DW_LNS_advance_line);
1437                                 emit_sleb128 (w, (gint32)loc->row - (gint32)prev_line);
1438                                 prev_line = loc->row;
1439                         }
1440
1441                         if (loc->row != prev_line) {
1442                                 if (!prev_file_name || strcmp (loc->source_file, prev_file_name) != 0) {
1443                                         /* Add an entry to the file table */
1444                                         /* FIXME: Avoid duplicates */
1445                                         file_index = emit_line_number_file_name (w, loc->source_file, 0, 0);
1446                                         g_free (prev_file_name);
1447                                         prev_file_name = g_strdup (loc->source_file);
1448
1449                                         emit_byte (w, DW_LNS_set_file);
1450                                         emit_uleb128 (w, file_index);
1451                                         emit_byte (w, DW_LNS_copy);
1452                                 }
1453
1454                                 //printf ("X: %p(+0x%x) %d %s:%d(+%d)\n", code + i, addr_diff, loc->il_offset, loc->source_file, loc->row, line_diff);
1455
1456                                 emit_advance_op (w, line_diff, addr_diff);
1457
1458                                 prev_line = loc->row;
1459                                 prev_native_offset = i;
1460                         }
1461
1462                         first = FALSE;
1463                         g_free (loc);
1464                 }
1465         }
1466
1467         g_free (prev_file_name);
1468
1469         if (!first) {
1470                 emit_byte (w, DW_LNS_advance_pc);
1471                 emit_sleb128 (w, code_size - prev_native_offset);
1472                 emit_byte (w, DW_LNS_copy);
1473
1474                 emit_byte (w, 0);
1475                 emit_byte (w, 1);
1476                 emit_byte (w, DW_LNE_end_sequence);
1477         } else if (!start_symbol) {
1478                 /* No debug info, XDEBUG mode */
1479                 char *name, *dis;
1480                 const guint8 *ip = header->code;
1481                 int prev_line, prev_native_offset;
1482                 int *il_to_line;
1483
1484                 /*
1485                  * Emit the IL code into a temporary file and emit line number info
1486                  * referencing that file.
1487                  */
1488
1489                 name = mono_method_full_name (method, TRUE);
1490                 fprintf (w->il_file, "// %s\n", name);
1491                 w->il_file_line_index ++;
1492                 g_free (name);
1493
1494                 il_to_line = g_new0 (int, header->code_size);
1495
1496                 emit_section_change (w, ".debug_line", LINE_SUBSECTION_DATA);
1497                 emit_byte (w, 0);
1498                 emit_byte (w, sizeof (gpointer) + 1);
1499                 emit_byte (w, DW_LNE_set_address);
1500                 emit_pointer_value (w, code);
1501
1502                 // FIXME: Optimize this
1503                 while (ip < header->code + header->code_size) {
1504                         int il_offset = ip - header->code;
1505
1506                         /* Emit IL */
1507                         w->il_file_line_index ++;
1508
1509                         dis = disasm_ins (method, ip, &ip);
1510                         fprintf (w->il_file, "%s\n", dis);
1511                         g_free (dis);
1512
1513                         il_to_line [il_offset] = w->il_file_line_index;
1514                 }
1515
1516                 /* Emit line number info */
1517                 prev_line = 1;
1518                 prev_native_offset = 0;
1519                 for (i = 0; i < debug_info->num_line_numbers; ++i) {
1520                         MonoDebugLineNumberEntry *lne = &debug_info->line_numbers [i];
1521                         int line;
1522
1523                         if (lne->il_offset >= header->code_size)
1524                                 continue;
1525                         line = il_to_line [lne->il_offset];
1526                         if (!line) {
1527                                 /* 
1528                                  * This seems to happen randomly, it looks like il_offset points
1529                                  * into the middle of an instruction.
1530                                  */
1531                                 continue;
1532                                 /*
1533                                 printf ("%s\n", mono_method_full_name (method, TRUE));
1534                                 printf ("%d %d\n", lne->il_offset, header->code_size);
1535                                 g_assert (line);
1536                                 */
1537                         }
1538
1539                         if (line - prev_line != 0) {
1540                                 emit_advance_op (w, line - prev_line, (gint32)lne->native_offset - prev_native_offset);
1541
1542                                 prev_line = line;
1543                                 prev_native_offset = lne->native_offset;
1544                         }
1545                 }
1546
1547                 emit_byte (w, DW_LNS_advance_pc);
1548                 emit_sleb128 (w, code_size - prev_native_offset);
1549                 emit_byte (w, DW_LNS_copy);
1550
1551                 emit_byte (w, 0);
1552                 emit_byte (w, 1);
1553                 emit_byte (w, DW_LNE_end_sequence);
1554
1555                 fflush (w->il_file);
1556                 g_free (il_to_line);
1557         }
1558 }
1559
1560 static MonoMethodVar*
1561 find_vmv (MonoCompile *cfg, MonoInst *ins)
1562 {
1563         int j;
1564
1565         if (cfg->varinfo) {
1566                 for (j = 0; j < cfg->num_varinfo; ++j) {
1567                         if (cfg->varinfo [j] == ins)
1568                                 break;
1569                 }
1570
1571                 if (j < cfg->num_varinfo) {
1572                         return MONO_VARINFO (cfg, j);
1573                 }
1574         }
1575
1576         return NULL;
1577 }
1578
1579 void
1580 mono_dwarf_writer_emit_method (MonoDwarfWriter *w, MonoCompile *cfg, MonoMethod *method, char *start_symbol, char *end_symbol, guint8 *code, guint32 code_size, MonoInst **args, MonoInst **locals, GSList *unwind_info, MonoDebugMethodJitInfo *debug_info)
1581 {
1582         char *name;
1583         MonoMethodSignature *sig;
1584         MonoMethodHeader *header;
1585         char **names, **tdies, **local_tdies;
1586         char **local_names;
1587         int *local_indexes;
1588         int i, num_locals;
1589         guint8 buf [128];
1590         guint8 *p;
1591
1592         emit_section_change (w, ".debug_info", 0);
1593
1594         sig = mono_method_signature (method);
1595         header = mono_method_get_header (method);
1596
1597         /* Parameter types */
1598         tdies = g_new0 (char *, sig->param_count + sig->hasthis);
1599         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
1600                 MonoType *t;
1601
1602                 if (i == 0 && sig->hasthis) {
1603                         if (method->klass->valuetype)
1604                                 t = &method->klass->this_arg;
1605                         else
1606                                 t = &method->klass->byval_arg;
1607                 } else {
1608                         t = sig->params [i - sig->hasthis];
1609                 }
1610
1611                 emit_type (w, t);
1612         }
1613
1614         /* Local types */
1615         local_tdies = g_new0 (char *, header->num_locals);
1616         for (i = 0; i < header->num_locals; ++i) {
1617                 emit_type (w, header->locals [i]);
1618         }
1619
1620         /* Subprogram */
1621         names = g_new0 (char *, sig->param_count);
1622         mono_method_get_param_names (method, (const char **) names);
1623
1624         emit_uleb128 (w, ABBREV_SUBPROGRAM);
1625         name = mono_method_full_name (method, FALSE);
1626         emit_string (w, name);
1627         g_free (name);
1628         if (start_symbol) {
1629                 emit_pointer_unaligned (w, start_symbol);
1630                 emit_pointer_unaligned (w, end_symbol);
1631         } else {
1632                 emit_pointer_value (w, code);
1633                 emit_pointer_value (w, code + code_size);
1634         }
1635         /* frame_base */
1636         emit_byte (w, 2);
1637         emit_byte (w, DW_OP_breg6);
1638         emit_byte (w, 16);
1639
1640         /* Parameters */
1641         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
1642                 MonoInst *arg = args ? args [i] : NULL;
1643                 MonoType *t;
1644                 const char *pname;
1645                 char pname_buf [128];
1646                 MonoMethodVar *vmv = NULL;
1647                 gboolean need_loclist = FALSE;
1648
1649                 vmv = find_vmv (cfg, arg);
1650                 if (code && vmv && (vmv->live_range_start || vmv->live_range_end))
1651                         need_loclist = TRUE;
1652
1653                 if (i == 0 && sig->hasthis) {
1654                         if (method->klass->valuetype)
1655                                 t = &method->klass->this_arg;
1656                         else
1657                                 t = &method->klass->byval_arg;
1658                         pname = "this";
1659                 } else {
1660                         t = sig->params [i - sig->hasthis];
1661                         pname = names [i - sig->hasthis];
1662                 }
1663
1664                 emit_uleb128 (w, need_loclist ? ABBREV_PARAM_LOCLIST : ABBREV_PARAM);
1665                 /* name */
1666                 if (pname[0] == '\0') {
1667                         sprintf (pname_buf, "param%d", i - sig->hasthis);
1668                         pname = pname_buf;
1669                 }
1670                 emit_string (w, pname);
1671                 /* type */
1672                 if (!arg || arg->flags & MONO_INST_IS_DEAD)
1673                         emit_var_type (w, &mono_defaults.int32_class->byval_arg);
1674                 else
1675                         emit_var_type (w, t);
1676
1677                 p = buf;
1678                 encode_var_location (w, arg, p, &p);
1679                 if (need_loclist) {
1680                         vmv->live_range_start = 0;
1681                         if (vmv->live_range_end == 0)
1682                                 /* FIXME: Uses made in calls are not recorded */
1683                                 vmv->live_range_end = code_size;
1684                         emit_loclist (w, arg, code + vmv->live_range_start, code + vmv->live_range_end, buf, p - buf);
1685                 } else {
1686                         emit_byte (w, p - buf);
1687                         emit_bytes (w, buf, p - buf);
1688                 }
1689         }               
1690         g_free (names);
1691
1692         /* Locals */
1693         num_locals = mono_debug_lookup_locals (method, &local_names, &local_indexes);
1694
1695         for (i = 0; i < header->num_locals; ++i) {
1696                 MonoInst *ins = locals [i];
1697                 char name_buf [128];
1698                 int j;
1699                 MonoMethodVar *vmv = NULL;
1700                 gboolean need_loclist = FALSE;
1701
1702                 /* ins->dreg no longer contains the original vreg */
1703                 vmv = find_vmv (cfg, ins);
1704                 if (code && vmv) {
1705                         if (vmv->live_range_start) {
1706                                 /* This variable has a precise live range */
1707                                 need_loclist = TRUE;
1708                         }
1709                 }
1710
1711                 emit_uleb128 (w, need_loclist ? ABBREV_VARIABLE_LOCLIST : ABBREV_VARIABLE);
1712                 /* name */
1713                 for (j = 0; j < num_locals; ++j)
1714                         if (local_indexes [j] == i)
1715                                 break;
1716                 if (j < num_locals) {
1717                         emit_string (w, local_names [j]);
1718                 } else {
1719                         sprintf (name_buf, "V_%d", i);
1720                         emit_string (w, name_buf);
1721                 }
1722                 /* type */
1723                 if (!ins || ins->flags & MONO_INST_IS_DEAD)
1724                         emit_var_type (w, &mono_defaults.int32_class->byval_arg);
1725                 else
1726                         emit_var_type (w, header->locals [i]);
1727
1728                 p = buf;
1729                 encode_var_location (w, ins, p, &p);
1730
1731                 if (need_loclist) {
1732                         if (vmv->live_range_end == 0)
1733                                 /* FIXME: Uses made in calls are not recorded */
1734                                 vmv->live_range_end = code_size;
1735                         emit_loclist (w, ins, code + vmv->live_range_start, code + vmv->live_range_end, buf, p - buf);
1736                 } else {
1737                         emit_byte (w, p - buf);
1738                         emit_bytes (w, buf, p - buf);
1739                 }
1740         }
1741
1742         g_free (local_names);
1743         g_free (local_indexes);
1744
1745         /* Subprogram end */
1746         emit_uleb128 (w, 0x0);
1747
1748         emit_line (w);
1749
1750         emit_debug_info_end (w);
1751
1752         /* Emit unwind info */
1753         if (unwind_info) {
1754                 emit_fde (w, w->fde_index, start_symbol, end_symbol, code, code_size, unwind_info, TRUE);
1755                 w->fde_index ++;
1756         }
1757
1758         /* Emit line number info */
1759         /* != could happen when using --regression */
1760         if (debug_info && (debug_info->code_start == code))
1761                 emit_line_number_info (w, method, start_symbol, end_symbol, code, code_size, debug_info);
1762
1763         emit_line (w);
1764 }
1765
1766 void
1767 mono_dwarf_writer_emit_trampoline (MonoDwarfWriter *w, const char *tramp_name, char *start_symbol, char *end_symbol, guint8 *code, guint32 code_size, GSList *unwind_info)
1768 {
1769         emit_section_change (w, ".debug_info", 0);
1770
1771         /* Subprogram */
1772         emit_uleb128 (w, ABBREV_SUBPROGRAM);
1773         emit_string (w, tramp_name);
1774         emit_pointer_value (w, code);
1775         emit_pointer_value (w, code + code_size);
1776         /* frame_base */
1777         emit_byte (w, 2);
1778         emit_byte (w, DW_OP_breg6);
1779         emit_byte (w, 16);
1780
1781         /* Subprogram end */
1782         emit_uleb128 (w, 0x0);
1783
1784         emit_debug_info_end (w);
1785
1786         /* Emit unwind info */
1787         emit_fde (w, w->fde_index, start_symbol, end_symbol, code, code_size, unwind_info, FALSE);
1788         w->fde_index ++;
1789 }
1790 #endif /* End of: !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */