2009-04-10 Zoltan Varga <vargaz@gmail.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 #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->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                 default:
982                         tdie = ".LDIE_I4";
983                         break;
984                 }
985         }
986
987         return tdie;
988 }
989
990 static void
991 emit_var_type (MonoDwarfWriter *w, MonoType *t)
992 {
993         const char *tdie;
994
995         tdie = emit_type (w, t);
996
997         emit_symbol_diff (w, tdie, ".Ldebug_info_start", 0);
998 }
999
1000 static void
1001 encode_var_location (MonoDwarfWriter *w, MonoInst *ins, guint8 *p, guint8 **endp)
1002 {
1003         /* location */
1004         /* FIXME: This needs a location list, since the args can go from reg->stack */
1005         if (!ins || ins->flags & MONO_INST_IS_DEAD) {
1006                 /* gdb treats this as optimized out */
1007         } else if (ins->opcode == OP_REGVAR) {
1008                 *p = DW_OP_reg0 + mono_hw_reg_to_dwarf_reg (ins->dreg);
1009                 p ++;
1010         } else if (ins->opcode == OP_REGOFFSET) {
1011                 *p ++= DW_OP_breg0 + mono_hw_reg_to_dwarf_reg (ins->inst_basereg);
1012                 encode_sleb128 (ins->inst_offset, p, &p);
1013         } else {
1014                 // FIXME:
1015                 *p ++ = DW_OP_reg0;
1016         }
1017
1018         *endp = p;
1019 }
1020
1021 static void
1022 emit_loclist (MonoDwarfWriter *w, MonoInst *ins,
1023                           guint8 *loclist_begin_addr, guint8 *loclist_end_addr,
1024                           guint8 *expr, guint32 expr_len)
1025 {
1026         char label [128];
1027
1028         emit_push_section (w, ".debug_loc", 0);
1029         sprintf (label, ".Lloclist_%d", w->loclist_index ++ );
1030         emit_label (w, label);
1031
1032         emit_pointer_value (w, loclist_begin_addr);
1033         emit_pointer_value (w, loclist_end_addr);
1034         emit_byte (w, expr_len % 256);
1035         emit_byte (w, expr_len / 256);
1036         emit_bytes (w, expr, expr_len);
1037
1038         emit_pointer_value (w, NULL);
1039         emit_pointer_value (w, NULL);
1040
1041         emit_pop_section (w);
1042         emit_symbol_diff (w, label, ".Ldebug_loc_start", 0);
1043 }
1044
1045 /* 
1046  * MonoDisHelper->tokener doesn't take an IP argument, and we can't add one since 
1047  * it is a public header.
1048  */
1049 static const guint8 *token_handler_ip;
1050
1051 static char*
1052 token_handler (MonoDisHelper *dh, MonoMethod *method, guint32 token)
1053 {
1054         char *res, *desc;
1055         MonoMethod *cmethod;
1056         MonoClass *klass;
1057         MonoClassField *field;
1058         gpointer data = NULL;
1059
1060         if (method->wrapper_type)
1061                 data = mono_method_get_wrapper_data (method, token);
1062
1063         switch (*token_handler_ip) {
1064         case CEE_ISINST:
1065         case CEE_CASTCLASS:
1066         case CEE_LDELEMA:
1067                 if (method->wrapper_type)
1068                         klass = data;
1069                 else
1070                         klass = mono_class_get_full (method->klass->image, token, NULL);
1071                 res = g_strdup_printf ("<%s>", klass->name);
1072                 break;
1073         case CEE_NEWOBJ:
1074         case CEE_CALL:
1075         case CEE_CALLVIRT:
1076                 if (method->wrapper_type)
1077                         cmethod = data;
1078                 else
1079                         cmethod = mono_get_method_full (method->klass->image, token, NULL, NULL);
1080                 desc = mono_method_full_name (cmethod, TRUE);
1081                 res = g_strdup_printf ("<%s>", desc);
1082                 g_free (desc);
1083                 break;
1084         case CEE_CALLI:
1085                 if (method->wrapper_type) {
1086                         desc = mono_signature_get_desc (data, FALSE);
1087                         res = g_strdup_printf ("<%s>", desc);
1088                         g_free (desc);
1089                 } else {
1090                         res = g_strdup_printf ("<0x%08x>", token);
1091                 }
1092                 break;
1093         case CEE_LDFLD:
1094         case CEE_LDSFLD:
1095         case CEE_STFLD:
1096         case CEE_STSFLD:
1097                 if (method->wrapper_type)
1098                         field = data;
1099                 else
1100                         field = mono_field_from_token (method->klass->image, token, &klass, NULL);
1101                 desc = mono_field_full_name (field);
1102                 res = g_strdup_printf ("<%s>", desc);
1103                 g_free (desc);
1104                 break;
1105         default:
1106                 res = g_strdup_printf ("<0x%08x>", token);
1107                 break;
1108         }
1109
1110         return res;
1111 }
1112
1113 /*
1114  * disasm_ins:
1115  *
1116  *   Produce a disassembled form of the IL instruction at IP. This is an extension
1117  * of mono_disasm_code_one () which can disasm tokens, handle wrapper methods, and
1118  * CEE_MONO_ opcodes.
1119  */
1120 static char*
1121 disasm_ins (MonoMethod *method, const guchar *ip, const guint8 **endip)
1122 {
1123         char *dis;
1124         MonoDisHelper dh;
1125         MonoMethodHeader *header = mono_method_get_header (method);
1126
1127         memset (&dh, 0, sizeof (dh));
1128         dh.newline = "";
1129         dh.label_format = "IL_%04x: ";
1130         dh.label_target = "IL_%04x";
1131         dh.tokener = token_handler;
1132
1133         token_handler_ip = ip;
1134         if (*ip == MONO_CUSTOM_PREFIX) {
1135                 guint32 token;
1136                 gpointer data;
1137
1138                 switch (ip [1]) {
1139                 case CEE_MONO_ICALL: {
1140                         MonoJitICallInfo *info;
1141
1142                         token = read32 (ip + 2);
1143                         data = mono_method_get_wrapper_data (method, token);
1144                         info = mono_find_jit_icall_by_addr (data);
1145                         g_assert (info);
1146
1147                         dis = g_strdup_printf ("IL_%04x: mono_icall <%s>", (int)(ip - header->code), info->name);
1148                         ip += 6;
1149                         break;
1150                 }
1151                 case CEE_MONO_CLASSCONST: {
1152                         token = read32 (ip + 2);
1153                         data = mono_method_get_wrapper_data (method, token);
1154
1155                         dis = g_strdup_printf ("IL_%04x: mono_classconst <%s>", (int)(ip - header->code), ((MonoClass*)data)->name);
1156                         ip += 6;
1157                         break;
1158                 }
1159                 default:
1160                         dis = mono_disasm_code_one (&dh, method, ip, &ip);
1161                 }
1162         } else {
1163                 dis = mono_disasm_code_one (&dh, method, ip, &ip);
1164         }
1165         token_handler_ip = NULL;
1166
1167         *endip = ip;
1168         return dis;
1169 }
1170
1171 static gint32
1172 il_offset_from_address (MonoMethod *method, MonoDebugMethodJitInfo *jit, 
1173                                                 guint32 native_offset)
1174 {
1175         int i;
1176
1177         if (!jit->line_numbers)
1178                 return -1;
1179
1180         for (i = jit->num_line_numbers - 1; i >= 0; i--) {
1181                 MonoDebugLineNumberEntry lne = jit->line_numbers [i];
1182
1183                 if (lne.native_offset <= native_offset)
1184                         return lne.il_offset;
1185         }
1186
1187         return -1;
1188 }
1189
1190 static int max_special_addr_diff = 0;
1191
1192 static inline void
1193 emit_advance_op (MonoDwarfWriter *w, int line_diff, int addr_diff)
1194 {
1195         gint64 opcode = 0;
1196
1197         /* Use a special opcode if possible */
1198         if (line_diff - LINE_BASE >= 0 && line_diff - LINE_BASE < LINE_RANGE) {
1199                 if (max_special_addr_diff == 0)
1200                         max_special_addr_diff = (255 - OPCODE_BASE) / LINE_RANGE;
1201
1202                 if (addr_diff > max_special_addr_diff && (addr_diff < 2 * max_special_addr_diff)) {
1203                         emit_byte (w, DW_LNS_const_add_pc);
1204                         addr_diff -= max_special_addr_diff;
1205                 }
1206
1207                 opcode = (line_diff - LINE_BASE) + (LINE_RANGE * addr_diff) + OPCODE_BASE;
1208                 if (opcode > 255)
1209                         opcode = 0;
1210         }
1211
1212         if (opcode != 0) {
1213                 emit_byte (w, opcode);
1214         } else {
1215                 emit_byte (w, DW_LNS_advance_line);
1216                 emit_sleb128 (w, line_diff);
1217                 emit_byte (w, DW_LNS_advance_pc);
1218                 emit_sleb128 (w, addr_diff);
1219                 emit_byte (w, DW_LNS_copy);
1220         }
1221 }
1222
1223 static gint
1224 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
1225 {
1226         if (a->native_offset == b->native_offset)
1227                 return a->il_offset - b->il_offset;
1228         else
1229                 return a->native_offset - b->native_offset;
1230 }
1231
1232 static void
1233 emit_line_number_info (MonoDwarfWriter *w, MonoMethod *method, guint8 *code,
1234                                            guint32 code_size, MonoDebugMethodJitInfo *debug_info)
1235 {
1236         guint32 prev_line = 0;
1237         guint32 prev_native_offset = 0;
1238         int i, file_index, il_offset, prev_il_offset;
1239         gboolean first = TRUE;
1240         MonoDebugSourceLocation *loc;
1241         char *prev_file_name = NULL;
1242         MonoMethodHeader *header = mono_method_get_header (method);
1243         MonoDebugMethodInfo *minfo;
1244         GArray *ln_array;
1245         int *native_to_il_offset = NULL;
1246
1247         if (!code)
1248                 // FIXME: The set_address op below only works with xdebug
1249                 return;
1250
1251         minfo = mono_debug_lookup_method (method);
1252
1253         /* Compute the native->IL offset mapping */
1254
1255 #ifndef _EGLIB_MAJOR
1256         ln_array = g_array_sized_new (FALSE, FALSE, sizeof (MonoDebugLineNumberEntry), 
1257                                                                   debug_info->num_line_numbers);
1258         g_array_append_vals (ln_array, debug_info->line_numbers, debug_info->num_line_numbers);
1259         g_array_sort (ln_array, (GCompareFunc)compare_lne);
1260         native_to_il_offset = g_new0 (int, code_size + 1);
1261
1262         for (i = 0; i < debug_info->num_line_numbers; ++i) {
1263                 int j;
1264                 MonoDebugLineNumberEntry lne = g_array_index (ln_array, MonoDebugLineNumberEntry, i);
1265
1266                 if (i == 0) {
1267                         for (j = 0; j < lne.native_offset; ++j)
1268                                 native_to_il_offset [j] = -1;
1269                 }
1270
1271                 if (i < debug_info->num_line_numbers - 1) {
1272                         MonoDebugLineNumberEntry lne_next = g_array_index (ln_array, MonoDebugLineNumberEntry, i + 1);
1273
1274                         for (j = lne.native_offset; j < lne_next.native_offset; ++j)
1275                                 native_to_il_offset [j] = lne.il_offset;
1276                 } else {
1277                         for (j = lne.native_offset; j < code_size; ++j)
1278                                 native_to_il_offset [j] = lne.il_offset;
1279                 }
1280         }
1281         g_array_free (ln_array, TRUE);
1282 #endif
1283
1284         prev_line = 1;
1285         prev_il_offset = -1;
1286
1287         for (i = 0; i < code_size; ++i) {
1288                 if (!minfo)
1289                         continue;
1290
1291                 if (!debug_info->line_numbers)
1292                         continue;
1293
1294                 if (native_to_il_offset)
1295                         il_offset = native_to_il_offset [i];
1296                 else
1297                         il_offset = il_offset_from_address (method, debug_info, i);
1298                 /*
1299                 il_offset = il_offset_from_address (method, debug_info, i);
1300
1301                 g_assert (il_offset == native_to_il_offset [i]);
1302                 */
1303
1304                 il_offset = native_to_il_offset [i];
1305                 if (il_offset < 0)
1306                         continue;
1307
1308                 if (il_offset == prev_il_offset)
1309                         continue;
1310
1311                 prev_il_offset = il_offset;
1312
1313                 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
1314
1315                 if (loc) {
1316                         int line_diff = (gint32)loc->row - (gint32)prev_line;
1317                         int addr_diff = i - prev_native_offset;
1318
1319                         if (first) {    
1320                                 emit_section_change (w, ".debug_line", LINE_SUBSECTION_DATA);
1321
1322                                 emit_byte (w, 0);
1323                                 emit_byte (w, sizeof (gpointer) + 1);
1324                                 emit_byte (w, DW_LNE_set_address);
1325                                 emit_pointer_value (w, code);
1326
1327                                 /* 
1328                                  * The prolog+initlocals region does not have a line number, this
1329                                  * makes them belong to the first line of the method.
1330                                  */
1331                                 emit_byte (w, DW_LNS_advance_line);
1332                                 emit_sleb128 (w, (gint32)loc->row - (gint32)prev_line);
1333                                 prev_line = loc->row;
1334                         }
1335
1336                         if (loc->row != prev_line) {
1337                                 if (!prev_file_name || strcmp (loc->source_file, prev_file_name) != 0) {
1338                                         /* Add an entry to the file table */
1339                                         /* FIXME: Avoid duplicates */
1340                                         file_index = emit_line_number_file_name (w, loc->source_file, 0, 0);
1341                                         g_free (prev_file_name);
1342                                         prev_file_name = g_strdup (loc->source_file);
1343
1344                                         emit_byte (w, DW_LNS_set_file);
1345                                         emit_uleb128 (w, file_index);
1346                                         emit_byte (w, DW_LNS_copy);
1347                                 }
1348
1349                                 //printf ("X: %p(+0x%x) %d %s:%d(+%d)\n", code + i, addr_diff, loc->il_offset, loc->source_file, loc->row, line_diff);
1350
1351                                 emit_advance_op (w, line_diff, addr_diff);
1352
1353                                 prev_line = loc->row;
1354                                 prev_native_offset = i;
1355                         }
1356
1357                         first = FALSE;
1358                         g_free (loc);
1359                 }
1360         }
1361
1362         g_free (prev_file_name);
1363
1364         if (!first) {
1365                 emit_byte (w, DW_LNS_advance_pc);
1366                 emit_sleb128 (w, code_size - prev_native_offset);
1367                 emit_byte (w, DW_LNS_copy);
1368
1369                 emit_byte (w, 0);
1370                 emit_byte (w, 1);
1371                 emit_byte (w, DW_LNE_end_sequence);
1372         } else if (code) {
1373                 /* No debug info, XDEBUG mode */
1374                 char *name, *dis;
1375                 const guint8 *ip = header->code;
1376                 int prev_line, prev_native_offset;
1377                 int *il_to_line;
1378
1379                 /*
1380                  * Emit the IL code into a temporary file and emit line number info
1381                  * referencing that file.
1382                  */
1383
1384                 name = mono_method_full_name (method, TRUE);
1385                 fprintf (w->il_file, "// %s\n", name);
1386                 w->il_file_line_index ++;
1387                 g_free (name);
1388
1389                 il_to_line = g_new0 (int, header->code_size);
1390
1391                 emit_section_change (w, ".debug_line", LINE_SUBSECTION_DATA);
1392                 emit_byte (w, 0);
1393                 emit_byte (w, sizeof (gpointer) + 1);
1394                 emit_byte (w, DW_LNE_set_address);
1395                 emit_pointer_value (w, code);
1396
1397                 // FIXME: Optimize this
1398                 while (ip < header->code + header->code_size) {
1399                         int il_offset = ip - header->code;
1400
1401                         /* Emit IL */
1402                         w->il_file_line_index ++;
1403
1404                         dis = disasm_ins (method, ip, &ip);
1405                         fprintf (w->il_file, "%s\n", dis);
1406                         g_free (dis);
1407
1408                         il_to_line [il_offset] = w->il_file_line_index;
1409                 }
1410
1411                 /* Emit line number info */
1412                 prev_line = 1;
1413                 prev_native_offset = 0;
1414                 for (i = 0; i < debug_info->num_line_numbers; ++i) {
1415                         MonoDebugLineNumberEntry *lne = &debug_info->line_numbers [i];
1416                         int line;
1417
1418                         if (lne->il_offset >= header->code_size)
1419                                 continue;
1420                         line = il_to_line [lne->il_offset];
1421                         if (!line) {
1422                                 /* 
1423                                  * This seems to happen randomly, it looks like il_offset points
1424                                  * into the middle of an instruction.
1425                                  */
1426                                 continue;
1427                                 /*
1428                                 printf ("%s\n", mono_method_full_name (method, TRUE));
1429                                 printf ("%d %d\n", lne->il_offset, header->code_size);
1430                                 g_assert (line);
1431                                 */
1432                         }
1433
1434                         if (line - prev_line != 0) {
1435                                 emit_advance_op (w, line - prev_line, (gint32)lne->native_offset - prev_native_offset);
1436
1437                                 prev_line = line;
1438                                 prev_native_offset = lne->native_offset;
1439                         }
1440                 }
1441
1442                 emit_byte (w, DW_LNS_advance_pc);
1443                 emit_sleb128 (w, code_size - prev_native_offset);
1444                 emit_byte (w, DW_LNS_copy);
1445
1446                 emit_byte (w, 0);
1447                 emit_byte (w, 1);
1448                 emit_byte (w, DW_LNE_end_sequence);
1449
1450                 fflush (w->il_file);
1451                 g_free (il_to_line);
1452         }
1453 }
1454
1455 static MonoMethodVar*
1456 find_vmv (MonoCompile *cfg, MonoInst *ins)
1457 {
1458         int j;
1459
1460         if (cfg->varinfo) {
1461                 for (j = 0; j < cfg->num_varinfo; ++j) {
1462                         if (cfg->varinfo [j] == ins)
1463                                 break;
1464                 }
1465
1466                 if (j < cfg->num_varinfo) {
1467                         return MONO_VARINFO (cfg, j);
1468                 }
1469         }
1470
1471         return NULL;
1472 }
1473
1474 void
1475 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)
1476 {
1477         char *name;
1478         MonoMethodSignature *sig;
1479         MonoMethodHeader *header;
1480         char **names, **tdies, **local_tdies;
1481         char **local_names;
1482         int *local_indexes;
1483         int i, num_locals;
1484         guint8 buf [128];
1485         guint8 *p;
1486
1487         emit_section_change (w, ".debug_info", 0);
1488
1489         sig = mono_method_signature (method);
1490         header = mono_method_get_header (method);
1491
1492         /* Parameter types */
1493         tdies = g_new0 (char *, sig->param_count + sig->hasthis);
1494         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
1495                 MonoType *t;
1496
1497                 if (i == 0 && sig->hasthis) {
1498                         if (method->klass->valuetype)
1499                                 t = &method->klass->this_arg;
1500                         else
1501                                 t = &method->klass->byval_arg;
1502                 } else {
1503                         t = sig->params [i - sig->hasthis];
1504                 }
1505
1506                 emit_type (w, t);
1507         }
1508
1509         /* Local types */
1510         local_tdies = g_new0 (char *, header->num_locals);
1511         for (i = 0; i < header->num_locals; ++i) {
1512                 emit_type (w, header->locals [i]);
1513         }
1514
1515         /* Subprogram */
1516         names = g_new0 (char *, sig->param_count);
1517         mono_method_get_param_names (method, (const char **) names);
1518
1519         emit_uleb128 (w, ABBREV_SUBPROGRAM);
1520         name = mono_method_full_name (method, FALSE);
1521         emit_string (w, name);
1522         g_free (name);
1523         if (start_symbol) {
1524                 emit_pointer_unaligned (w, start_symbol);
1525                 emit_pointer_unaligned (w, end_symbol);
1526         } else {
1527                 emit_pointer_value (w, code);
1528                 emit_pointer_value (w, code + code_size);
1529         }
1530         /* frame_base */
1531         emit_byte (w, 2);
1532         emit_byte (w, DW_OP_breg6);
1533         emit_byte (w, 16);
1534
1535         /* Parameters */
1536         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
1537                 MonoInst *arg = args ? args [i] : NULL;
1538                 MonoType *t;
1539                 const char *pname;
1540                 char pname_buf [128];
1541                 MonoMethodVar *vmv = NULL;
1542                 gboolean need_loclist = FALSE;
1543
1544                 vmv = find_vmv (cfg, arg);
1545                 if (code && vmv && (vmv->live_range_start || vmv->live_range_end))
1546                         need_loclist = TRUE;
1547
1548                 if (i == 0 && sig->hasthis) {
1549                         if (method->klass->valuetype)
1550                                 t = &method->klass->this_arg;
1551                         else
1552                                 t = &method->klass->byval_arg;
1553                         pname = "this";
1554                 } else {
1555                         t = sig->params [i - sig->hasthis];
1556                         pname = names [i - sig->hasthis];
1557                 }
1558
1559                 emit_uleb128 (w, need_loclist ? ABBREV_PARAM_LOCLIST : ABBREV_PARAM);
1560                 /* name */
1561                 if (pname[0] == '\0') {
1562                         sprintf (pname_buf, "param%d", i - sig->hasthis);
1563                         pname = pname_buf;
1564                 }
1565                 emit_string (w, pname);
1566                 /* type */
1567                 if (!arg || arg->flags & MONO_INST_IS_DEAD)
1568                         emit_var_type (w, &mono_defaults.int32_class->byval_arg);
1569                 else
1570                         emit_var_type (w, t);
1571
1572                 p = buf;
1573                 encode_var_location (w, arg, p, &p);
1574                 if (need_loclist) {
1575                         vmv->live_range_start = 0;
1576                         if (vmv->live_range_end == 0)
1577                                 /* FIXME: Uses made in calls are not recorded */
1578                                 vmv->live_range_end = code_size;
1579                         emit_loclist (w, arg, code + vmv->live_range_start, code + vmv->live_range_end, buf, p - buf);
1580                 } else {
1581                         emit_byte (w, p - buf);
1582                         emit_bytes (w, buf, p - buf);
1583                 }
1584         }               
1585         g_free (names);
1586
1587         /* Locals */
1588         num_locals = mono_debug_lookup_locals (method, &local_names, &local_indexes);
1589
1590         for (i = 0; i < header->num_locals; ++i) {
1591                 MonoInst *ins = locals [i];
1592                 char name_buf [128];
1593                 int j;
1594                 MonoMethodVar *vmv = NULL;
1595                 gboolean need_loclist = FALSE;
1596
1597                 /* ins->dreg no longer contains the original vreg */
1598                 vmv = find_vmv (cfg, ins);
1599                 if (code && vmv) {
1600                         if (vmv->live_range_start) {
1601                                 /* This variable has a precise live range */
1602                                 need_loclist = TRUE;
1603                         }
1604                 }
1605
1606                 emit_uleb128 (w, need_loclist ? ABBREV_VARIABLE_LOCLIST : ABBREV_VARIABLE);
1607                 /* name */
1608                 for (j = 0; j < num_locals; ++j)
1609                         if (local_indexes [j] == i)
1610                                 break;
1611                 if (j < num_locals) {
1612                         emit_string (w, local_names [j]);
1613                 } else {
1614                         sprintf (name_buf, "V_%d", i);
1615                         emit_string (w, name_buf);
1616                 }
1617                 /* type */
1618                 if (!ins || ins->flags & MONO_INST_IS_DEAD)
1619                         emit_var_type (w, &mono_defaults.int32_class->byval_arg);
1620                 else
1621                         emit_var_type (w, header->locals [i]);
1622
1623                 p = buf;
1624                 encode_var_location (w, ins, p, &p);
1625
1626                 if (need_loclist) {
1627                         if (vmv->live_range_end == 0)
1628                                 /* FIXME: Uses made in calls are not recorded */
1629                                 vmv->live_range_end = code_size;
1630                         emit_loclist (w, ins, code + vmv->live_range_start, code + vmv->live_range_end, buf, p - buf);
1631                 } else {
1632                         emit_byte (w, p - buf);
1633                         emit_bytes (w, buf, p - buf);
1634                 }
1635         }
1636
1637         g_free (local_names);
1638         g_free (local_indexes);
1639
1640         /* Subprogram end */
1641         emit_uleb128 (w, 0x0);
1642
1643         emit_line (w);
1644
1645         /* Emit unwind info */
1646         if (unwind_info) {
1647                 emit_fde (w, w->fde_index, start_symbol, end_symbol, code, code_size, unwind_info, TRUE);
1648                 w->fde_index ++;
1649         }
1650
1651         /* Emit line number info */
1652         if (code && debug_info)
1653                 emit_line_number_info (w, method, code, code_size, debug_info);
1654
1655         emit_line (w);
1656 }
1657
1658 void
1659 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)
1660 {
1661         emit_section_change (w, ".debug_info", 0);
1662
1663         /* Subprogram */
1664         emit_uleb128 (w, ABBREV_SUBPROGRAM);
1665         emit_string (w, tramp_name);
1666         emit_pointer_value (w, code);
1667         emit_pointer_value (w, code + code_size);
1668         /* frame_base */
1669         emit_byte (w, 2);
1670         emit_byte (w, DW_OP_breg6);
1671         emit_byte (w, 16);
1672
1673         /* Subprogram end */
1674         emit_uleb128 (w, 0x0);
1675
1676         /* Emit unwind info */
1677         emit_fde (w, w->fde_index, start_symbol, end_symbol, code, code_size, unwind_info, FALSE);
1678         w->fde_index ++;
1679 }