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