2009-04-11 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / mini / debug-mini.c
1 /*
2  * debug-mini.c: Mini-specific debugging stuff.
3  *
4  * Author:
5  *   Martin Baulig (martin@ximian.com)
6  *
7  * (C) 2003 Ximian, Inc.
8  */
9
10 #include "mini.h"
11 #include "jit.h"
12 #include "config.h"
13 #include <mono/metadata/verify.h>
14 #include <mono/metadata/mono-config.h>
15 #include <mono/metadata/mono-debug.h>
16 #include <mono/metadata/appdomain.h>
17 #include <mono/metadata/threads-types.h>
18
19 #define _IN_THE_MONO_DEBUGGER
20 #include <mono/metadata/mono-debug-debugger.h>
21 #include "debug-mini.h"
22
23 #ifdef HAVE_VALGRIND_H
24 #include <valgrind/valgrind.h>
25 #endif
26
27 #ifdef MONO_DEBUGGER_SUPPORTED
28 #include <libgc/include/libgc-mono-debugger.h>
29 #endif
30
31 typedef struct {
32         guint32 index;
33         MonoMethodDesc *desc;
34 } MiniDebugBreakpointInfo;
35
36 typedef struct
37 {
38         MonoDebugMethodJitInfo *jit;
39         GArray *line_numbers;
40         guint32 has_line_numbers;
41         guint32 breakpoint_id;
42 } MiniDebugMethodInfo;
43
44 typedef struct {
45         MonoObject *last_exception;
46         guint32 stopped_on_exception : 1;
47         guint32 stopped_on_unhandled : 1;
48 } MonoDebuggerExceptionState;
49
50 struct _MonoDebuggerThreadInfo {
51         guint64 tid;
52         guint64 lmf_addr;
53         guint64 end_stack;
54
55         guint64 extended_notifications;
56
57         /* Next pointer. */
58         MonoDebuggerThreadInfo *next;
59
60         /*
61          * The stack bounds are only used when reading a core file.
62          */
63         guint64 stack_start;
64         guint64 signal_stack_start;
65         guint32 stack_size;
66         guint32 signal_stack_size;
67
68         MonoDebuggerExceptionState exception_state;
69
70         /*
71          * The debugger doesn't access anything beyond this point.
72          */
73         MonoJitTlsData *jit_tls;
74         MonoThread *thread;
75 };
76
77 typedef struct {
78         gpointer stack_pointer;
79         MonoObject *exception_obj;
80         guint32 stop;
81         guint32 stop_unhandled;
82 } MonoDebuggerExceptionInfo;
83
84 typedef enum {
85         MONO_DEBUGGER_EXCEPTION_ACTION_NONE             = 0,
86         MONO_DEBUGGER_EXCEPTION_ACTION_STOP             = 1,
87         MONO_DEBUGGER_EXCEPTION_ACTION_STOP_UNHANDLED   = 2
88 } MonoDebuggerExceptionAction;
89
90 MonoDebuggerThreadInfo *mono_debugger_thread_table = NULL;
91
92 static inline void
93 record_line_number (MiniDebugMethodInfo *info, guint32 address, guint32 offset)
94 {
95         MonoDebugLineNumberEntry lne;
96
97         lne.native_offset = address;
98         lne.il_offset = offset;
99
100         g_array_append_val (info->line_numbers, lne);
101 }
102
103
104 void
105 mono_debug_init_method (MonoCompile *cfg, MonoBasicBlock *start_block, guint32 breakpoint_id)
106 {
107         MiniDebugMethodInfo *info;
108
109         if (mono_debug_format == MONO_DEBUG_FORMAT_NONE)
110                 return;
111
112         info = g_new0 (MiniDebugMethodInfo, 1);
113         info->breakpoint_id = breakpoint_id;
114
115         cfg->debug_info = info;
116 }
117
118 void
119 mono_debug_open_method (MonoCompile *cfg)
120 {
121         MiniDebugMethodInfo *info;
122         MonoDebugMethodJitInfo *jit;
123         MonoMethodHeader *header;
124
125         info = (MiniDebugMethodInfo *) cfg->debug_info;
126         if (!info)
127                 return;
128
129         mono_class_init (cfg->method->klass);
130
131         header = mono_method_get_header (cfg->method);
132         g_assert (header);
133         
134         info->jit = jit = g_new0 (MonoDebugMethodJitInfo, 1);
135         info->line_numbers = g_array_new (FALSE, TRUE, sizeof (MonoDebugLineNumberEntry));
136         jit->num_locals = header->num_locals;
137         jit->locals = g_new0 (MonoDebugVarInfo, jit->num_locals);
138 }
139
140 static void
141 write_variable (MonoInst *inst, MonoDebugVarInfo *var)
142 {
143         var->type = inst->inst_vtype;
144
145         if (inst->opcode == OP_REGVAR)
146                 var->index = inst->dreg | MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER;
147         else if (inst->flags & MONO_INST_IS_DEAD)
148                 var->index = MONO_DEBUG_VAR_ADDRESS_MODE_DEAD;
149         else {
150                 /* the debug interface needs fixing to allow 0(%base) address */
151                 var->index = inst->inst_basereg | MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET;
152                 var->offset = inst->inst_offset;
153         }
154 }
155
156 /*
157  * mono_debug_add_vg_method:
158  *
159  *  Register symbol information for the method with valgrind
160  */
161 static void 
162 mono_debug_add_vg_method (MonoMethod *method, MonoDebugMethodJitInfo *jit)
163 {
164 #ifdef VALGRIND_ADD_LINE_INFO
165         MonoMethodHeader *header;
166         MonoDebugMethodInfo *minfo;
167         int i;
168         char *filename = NULL;
169         guint32 address, line_number;
170         const char *full_name;
171         guint32 *addresses;
172         guint32 *lines;
173
174         if (!RUNNING_ON_VALGRIND)
175                 return;
176
177         header = mono_method_get_header (method);
178
179         full_name = mono_method_full_name (method, TRUE);
180
181         addresses = g_new0 (guint32, header->code_size + 1);
182         lines = g_new0 (guint32, header->code_size + 1);
183
184         /* 
185          * Very simple code to convert the addr->offset mappings that mono has
186          * into [addr-addr] ->line number mappings.
187          */
188
189         minfo = mono_debug_lookup_method (method);
190         if (minfo) {
191                 /* Create offset->line number mapping */
192                 for (i = 0; i < header->code_size; ++i) {
193                         MonoDebugSourceLocation *location;
194
195                         location = mono_debug_symfile_lookup_location (minfo, i);
196                         if (!location)
197                                 continue;
198
199                         lines [i] = location.row;
200                         if (!filename)
201                                 filename = location.source_file;
202
203                         mono_debug_free_source_location (location);
204                 }
205         }
206
207         /* Create address->offset mapping */
208         for (i = 0; i < jit->num_line_numbers; ++i) {
209                 MonoDebugLineNumberEntry *lne = jit->line_numbers [i];
210
211                 g_assert (lne->offset <= header->code_size);
212
213                 if ((addresses [lne->offset] == 0) || (lne->address < addresses [lne->offset]))
214                         addresses [lne->offset] = lne->address;
215         }
216         /* Fill out missing addresses */
217         address = 0;
218         for (i = 0; i < header->code_size; ++i) {
219                 if (addresses [i] == 0)
220                         addresses [i] = address;
221                 else
222                         address = addresses [i];
223         }
224         
225         address = 0;
226         line_number = 0;
227         i = 0;
228         while (i < header->code_size) {
229                 if (lines [i] == line_number)
230                         i ++;
231                 else {
232                         if (line_number > 0) {
233                                 //g_assert (addresses [i] - 1 >= address);
234                                 
235                                 if (addresses [i] - 1 >= address) {
236                                         VALGRIND_ADD_LINE_INFO (jit->code_start + address, jit->code_start + addresses [i] - 1, filename, line_number);
237                                         //printf ("[%d-%d] -> %d.\n", address, addresses [i] - 1, line_number);
238                                 }
239                         }
240                         address = addresses [i];
241                         line_number = lines [i];
242                 }
243         }
244
245         if (line_number > 0) {
246                 VALGRIND_ADD_LINE_INFO (jit->code_start + address, jit->code_start + jit->code_size - 1, filename, line_number);
247                 //printf ("[%d-%d] -> %d.\n", address, jit->code_size - 1, line_number);
248         }
249
250         VALGRIND_ADD_SYMBOL (jit->code_start, jit->code_size, full_name);
251
252         g_free (addresses);
253         g_free (lines);
254 #endif /* VALGRIND_ADD_LINE_INFO */
255 }
256
257 void
258 mono_debug_close_method (MonoCompile *cfg)
259 {
260         MiniDebugMethodInfo *info;
261         MonoDebugMethodJitInfo *jit;
262         MonoMethodHeader *header;
263         MonoMethodSignature *sig;
264         MonoDebugMethodAddress *debug_info;
265         MonoMethod *method;
266         int i;
267
268         info = (MiniDebugMethodInfo *) cfg->debug_info;
269         if (!info || !info->jit) {
270                 if (info)
271                         g_free (info);
272                 return;
273         }
274
275         method = cfg->method;
276         header = mono_method_get_header (method);
277         sig = mono_method_signature (method);
278
279         jit = info->jit;
280         jit->code_start = cfg->native_code;
281         jit->epilogue_begin = cfg->epilog_begin;
282         jit->code_size = cfg->code_len;
283
284         if (jit->epilogue_begin)
285                    record_line_number (info, jit->epilogue_begin, header->code_size);
286
287         jit->num_params = sig->param_count;
288         jit->params = g_new0 (MonoDebugVarInfo, jit->num_params);
289
290         for (i = 0; i < jit->num_locals; i++)
291                 write_variable (cfg->locals [i], &jit->locals [i]);
292
293         if (sig->hasthis) {
294                 jit->this_var = g_new0 (MonoDebugVarInfo, 1);
295                 write_variable (cfg->args [0], jit->this_var);
296         }
297
298         for (i = 0; i < jit->num_params; i++)
299                 write_variable (cfg->args [i + sig->hasthis], &jit->params [i]);
300
301         jit->num_line_numbers = info->line_numbers->len;
302         jit->line_numbers = g_new0 (MonoDebugLineNumberEntry, jit->num_line_numbers);
303
304         for (i = 0; i < jit->num_line_numbers; i++)
305                 jit->line_numbers [i] = g_array_index (info->line_numbers, MonoDebugLineNumberEntry, i);
306
307         debug_info = mono_debug_add_method (method, jit, cfg->domain);
308
309         mono_debug_add_vg_method (method, jit);
310
311         if (info->breakpoint_id)
312                 mono_debugger_breakpoint_callback (method, info->breakpoint_id);
313
314         mono_debugger_check_breakpoints (method, debug_info);
315
316         mono_debug_free_method_jit_info (jit);
317         g_array_free (info->line_numbers, TRUE);
318         g_free (info);
319 }
320
321 void
322 mono_debug_record_line_number (MonoCompile *cfg, MonoInst *ins, guint32 address)
323 {
324         MiniDebugMethodInfo *info;
325         MonoMethodHeader *header;
326         guint32 offset;
327
328         info = (MiniDebugMethodInfo *) cfg->debug_info;
329         if (!info || !info->jit || !ins->cil_code)
330                 return;
331
332         header = mono_method_get_header (cfg->method);
333         g_assert (header);
334
335         if ((ins->cil_code < header->code) ||
336             (ins->cil_code > header->code + header->code_size))
337                 return;
338
339         offset = ins->cil_code - header->code;
340         if (!info->has_line_numbers) {
341                 info->jit->prologue_end = address;
342                 info->has_line_numbers = TRUE;
343         }
344
345         record_line_number (info, address, offset);
346 }
347
348 void
349 mono_debug_open_block (MonoCompile *cfg, MonoBasicBlock *bb, guint32 address)
350 {
351         MiniDebugMethodInfo *info;
352         MonoMethodHeader *header;
353         guint32 offset;
354
355         info = (MiniDebugMethodInfo *) cfg->debug_info;
356         if (!info || !info->jit || !bb->cil_code)
357                 return;
358
359         header = mono_method_get_header (cfg->method);
360         g_assert (header);
361
362         if ((bb->cil_code < header->code) ||
363             (bb->cil_code > header->code + header->code_size))
364                 return;
365
366         offset = bb->cil_code - header->code;
367         if (!info->has_line_numbers) {
368                 info->jit->prologue_end = address;
369                 info->has_line_numbers = TRUE;
370         }
371
372         record_line_number (info, address, offset);
373 }
374
375 static inline void
376 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
377 {
378         guint8 *p = buf;
379
380         //printf ("ENCODE: %d 0x%x.\n", value, value);
381
382         /* 
383          * Same encoding as the one used in the metadata, extended to handle values
384          * greater than 0x1fffffff.
385          */
386         if ((value >= 0) && (value <= 127))
387                 *p++ = value;
388         else if ((value >= 0) && (value <= 16383)) {
389                 p [0] = 0x80 | (value >> 8);
390                 p [1] = value & 0xff;
391                 p += 2;
392         } else if ((value >= 0) && (value <= 0x1fffffff)) {
393                 p [0] = (value >> 24) | 0xc0;
394                 p [1] = (value >> 16) & 0xff;
395                 p [2] = (value >> 8) & 0xff;
396                 p [3] = value & 0xff;
397                 p += 4;
398         }
399         else {
400                 p [0] = 0xff;
401                 p [1] = (value >> 24) & 0xff;
402                 p [2] = (value >> 16) & 0xff;
403                 p [3] = (value >> 8) & 0xff;
404                 p [4] = value & 0xff;
405                 p += 5;
406         }
407         if (endbuf)
408                 *endbuf = p;
409 }
410
411 static inline gint32
412 decode_value (guint8 *ptr, guint8 **rptr)
413 {
414         guint8 b = *ptr;
415         gint32 len;
416         
417         if ((b & 0x80) == 0){
418                 len = b;
419                 ++ptr;
420         } else if ((b & 0x40) == 0){
421                 len = ((b & 0x3f) << 8 | ptr [1]);
422                 ptr += 2;
423         } else if (b != 0xff) {
424                 len = ((b & 0x1f) << 24) |
425                         (ptr [1] << 16) |
426                         (ptr [2] << 8) |
427                         ptr [3];
428                 ptr += 4;
429         }
430         else {
431                 len = (ptr [1] << 24) | (ptr [2] << 16) | (ptr [3] << 8) | ptr [4];
432                 ptr += 5;
433         }
434         if (rptr)
435                 *rptr = ptr;
436
437         //printf ("DECODE: %d.\n", len);
438         return len;
439 }
440
441 static void
442 serialize_variable (MonoDebugVarInfo *var, guint8 *p, guint8 **endbuf)
443 {
444         guint32 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
445
446         encode_value (var->index, p, &p);
447
448         switch (flags) {
449         case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
450                 break;
451         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
452                 encode_value (var->offset, p, &p);
453                 break;
454         case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
455                 break;
456         default:
457                 g_assert_not_reached ();
458         }
459         *endbuf = p;
460 }
461
462 void
463 mono_debug_serialize_debug_info (MonoCompile *cfg, guint8 **out_buf, guint32 *buf_len)
464 {
465         MonoDebugMethodJitInfo *jit;
466         guint32 size, prev_offset, prev_native_offset;
467         guint8 *buf, *p;
468         int i;
469
470         /* Can't use cfg->debug_info as it is freed by close_method () */
471         jit = mono_debug_find_method (cfg->method, mono_domain_get ());
472         if (!jit) {
473                 *buf_len = 0;
474                 return;
475         }
476
477         size = ((jit->num_params + jit->num_locals + 1) * 10) + (jit->num_line_numbers * 10) + 64;
478         p = buf = g_malloc (size);
479         encode_value (jit->epilogue_begin, p, &p);
480         encode_value (jit->prologue_end, p, &p);
481         encode_value (jit->code_size, p, &p);
482
483         for (i = 0; i < jit->num_params; ++i)
484                 serialize_variable (&jit->params [i], p, &p);
485
486         if (mono_method_signature (cfg->method)->hasthis)
487                 serialize_variable (jit->this_var, p, &p);
488
489         for (i = 0; i < jit->num_locals; i++)
490                 serialize_variable (&jit->locals [i], p, &p);
491
492         encode_value (jit->num_line_numbers, p, &p);
493
494         prev_offset = 0;
495         prev_native_offset = 0;
496         for (i = 0; i < jit->num_line_numbers; ++i) {
497                 /* Sometimes, the offset values are not in increasing order */
498                 MonoDebugLineNumberEntry *lne = &jit->line_numbers [i];
499                 encode_value (lne->il_offset - prev_offset, p, &p);
500                 encode_value (lne->native_offset - prev_native_offset, p, &p);
501                 prev_offset = lne->il_offset;
502                 prev_native_offset = lne->native_offset;
503         }
504
505         g_assert (p - buf < size);
506
507         *out_buf = buf;
508         *buf_len = p - buf;
509 }
510
511 static void
512 deserialize_variable (MonoDebugVarInfo *var, guint8 *p, guint8 **endbuf)
513 {
514         guint32 flags;
515
516         var->index = decode_value (p, &p);
517
518         flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
519
520         switch (flags) {
521         case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
522                 break;
523         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
524                 var->offset = decode_value (p, &p);
525                 break;
526         case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
527                 break;
528         default:
529                 g_assert_not_reached ();
530         }
531         *endbuf = p;
532 }
533
534 static MonoDebugMethodJitInfo *
535 deserialize_debug_info (MonoMethod *method, guint8 *code_start, guint8 *buf, guint32 buf_len)
536 {
537         MonoMethodHeader *header;
538         gint32 offset, native_offset, prev_offset, prev_native_offset;
539         MonoDebugMethodJitInfo *jit;
540         guint8 *p;
541         int i;
542
543         header = mono_method_get_header (method);
544         g_assert (header);
545
546         jit = g_new0 (MonoDebugMethodJitInfo, 1);
547         jit->code_start = code_start;
548         jit->num_locals = header->num_locals;
549         jit->locals = g_new0 (MonoDebugVarInfo, jit->num_locals);
550         jit->num_params = mono_method_signature (method)->param_count;
551         jit->params = g_new0 (MonoDebugVarInfo, jit->num_params);
552
553         p = buf;
554         jit->epilogue_begin = decode_value (p, &p);
555         jit->prologue_end = decode_value (p, &p);
556         jit->code_size = decode_value (p, &p);
557
558         for (i = 0; i < jit->num_params; ++i)
559                 deserialize_variable (&jit->params [i], p, &p);
560
561         if (mono_method_signature (method)->hasthis) {
562                 jit->this_var = g_new0 (MonoDebugVarInfo, 1);
563                 deserialize_variable (jit->this_var, p, &p);
564         }
565
566         for (i = 0; i < jit->num_locals; i++)
567                 deserialize_variable (&jit->locals [i], p, &p);
568
569         jit->num_line_numbers = decode_value (p, &p);
570         jit->line_numbers = g_new0 (MonoDebugLineNumberEntry, jit->num_line_numbers);
571
572         prev_offset = 0;
573         prev_native_offset = 0;
574         for (i = 0; i < jit->num_line_numbers; ++i) {
575                 MonoDebugLineNumberEntry *lne = &jit->line_numbers [i];
576
577                 offset = prev_offset + decode_value (p, &p);
578                 native_offset = prev_native_offset + decode_value (p, &p);
579
580                 lne->native_offset = native_offset;
581                 lne->il_offset = offset;
582
583                 prev_offset = offset;
584                 prev_native_offset = native_offset;
585         }
586
587         return jit;
588 }
589
590 void
591 mono_debug_add_aot_method (MonoDomain *domain, MonoMethod *method, guint8 *code_start, 
592                            guint8 *debug_info, guint32 debug_info_len)
593 {
594         MonoDebugMethodJitInfo *jit;
595
596         if (mono_debug_format == MONO_DEBUG_FORMAT_NONE)
597                 return;
598
599         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
600             (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
601             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
602             (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
603             (method->wrapper_type != MONO_WRAPPER_NONE))
604                 return;
605
606         if (debug_info_len == 0)
607                 return;
608
609         jit = deserialize_debug_info (method, code_start, debug_info, debug_info_len);
610
611         mono_debug_add_method (method, jit, domain);
612
613         mono_debug_add_vg_method (method, jit);
614
615         mono_debug_free_method_jit_info (jit);
616 }
617
618 void
619 mono_debug_add_icall_wrapper (MonoMethod *method, MonoJitICallInfo* callinfo)
620 {
621         if (mono_debug_format == MONO_DEBUG_FORMAT_NONE)
622                 return;
623
624         // mono_debug_add_wrapper (method, callinfo->wrapper, callinfo->func);
625 }
626
627 static void
628 print_var_info (MonoDebugVarInfo *info, int idx, const char *name, const char *type)
629 {
630         switch (info->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS) {
631         case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
632                 g_print ("%s %s (%d) in register %s\n", type, name, idx, mono_arch_regname (info->index & (~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS)));
633                 break;
634         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
635                 g_print ("%s %s (%d) in memory: base register %s + %d\n", type, name, idx, mono_arch_regname (info->index & (~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS)), info->offset);
636                 break;
637         case MONO_DEBUG_VAR_ADDRESS_MODE_TWO_REGISTERS:
638         default:
639                 g_assert_not_reached ();
640         }
641 }
642
643 /**
644  * mono_debug_print_locals:
645  *
646  * Prints to stdout the information about the local variables in
647  * a method (if @only_arguments is false) or about the arguments.
648  * The information includes the storage info (where the variable 
649  * lives, in a register or in memory).
650  * The method is found by looking up what method has been emitted at
651  * the instruction address @ip.
652  * This is for use inside a debugger.
653  */
654 void
655 mono_debug_print_vars (gpointer ip, gboolean only_arguments)
656 {
657         MonoDomain *domain = mono_domain_get ();
658         MonoJitInfo *ji = mono_jit_info_table_find (domain, ip);
659         MonoDebugMethodJitInfo *jit;
660         int i;
661
662         if (!ji)
663                 return;
664
665         jit = mono_debug_find_method (mono_jit_info_get_method (ji), domain);
666         if (!jit)
667                 return;
668
669         if (only_arguments) {
670                 char **names;
671                 names = g_new (char *, jit->num_params);
672                 mono_method_get_param_names (mono_jit_info_get_method (ji), (const char **) names);
673                 if (jit->this_var)
674                         print_var_info (jit->this_var, 0, "this", "Arg");
675                 for (i = 0; i < jit->num_params; ++i) {
676                         print_var_info (&jit->params [i], i, names [i]? names [i]: "unknown name", "Arg");
677                 }
678                 g_free (names);
679         } else {
680                 for (i = 0; i < jit->num_locals; ++i) {
681                         print_var_info (&jit->locals [i], i, "", "Local");
682                 }
683         }
684         mono_debug_free_method_jit_info (jit);
685 }
686
687 /*
688  * The old Debugger breakpoint interface.
689  *
690  * This interface is used to insert breakpoints on methods which are not yet JITed.
691  * The debugging code keeps a list of all such breakpoints and automatically inserts the
692  * breakpoint when the method is JITed.
693  */
694
695 static GPtrArray *breakpoints = NULL;
696
697 int
698 mono_debugger_insert_breakpoint_full (MonoMethodDesc *desc)
699 {
700         static int last_breakpoint_id = 0;
701         MiniDebugBreakpointInfo *info;
702
703         info = g_new0 (MiniDebugBreakpointInfo, 1);
704         info->desc = desc;
705         info->index = ++last_breakpoint_id;
706
707         if (!breakpoints)
708                 breakpoints = g_ptr_array_new ();
709
710         g_ptr_array_add (breakpoints, info);
711
712         return info->index;
713 }
714
715 int
716 mono_debugger_remove_breakpoint (int breakpoint_id)
717 {
718         int i;
719
720         if (!breakpoints)
721                 return 0;
722
723         for (i = 0; i < breakpoints->len; i++) {
724                 MiniDebugBreakpointInfo *info = g_ptr_array_index (breakpoints, i);
725
726                 if (info->index != breakpoint_id)
727                         continue;
728
729                 mono_method_desc_free (info->desc);
730                 g_ptr_array_remove (breakpoints, info);
731                 g_free (info);
732                 return 1;
733         }
734
735         return 0;
736 }
737
738 int
739 mono_debugger_insert_breakpoint (const gchar *method_name, gboolean include_namespace)
740 {
741         MonoMethodDesc *desc;
742
743         desc = mono_method_desc_new (method_name, include_namespace);
744         if (!desc)
745                 return 0;
746
747         return mono_debugger_insert_breakpoint_full (desc);
748 }
749
750 int
751 mono_debugger_method_has_breakpoint (MonoMethod *method)
752 {
753         int i;
754
755         if (!breakpoints || (method->wrapper_type != MONO_WRAPPER_NONE))
756                 return 0;
757
758         for (i = 0; i < breakpoints->len; i++) {
759                 MiniDebugBreakpointInfo *info = g_ptr_array_index (breakpoints, i);
760
761                 if (!mono_method_desc_full_match (info->desc, method))
762                         continue;
763
764                 return info->index;
765         }
766
767         return 0;
768 }
769
770 void
771 mono_debugger_breakpoint_callback (MonoMethod *method, guint32 index)
772 {
773         mono_debugger_event (MONO_DEBUGGER_EVENT_JIT_BREAKPOINT, (guint64) (gsize) method, index);
774 }
775
776 void
777 mono_debugger_thread_created (gsize tid, MonoThread *thread, MonoJitTlsData *jit_tls)
778 {
779 #ifdef MONO_DEBUGGER_SUPPORTED
780         size_t stsize = 0;
781         guint8 *staddr = NULL;
782         MonoDebuggerThreadInfo *info;
783
784         if (mono_debug_format == MONO_DEBUG_FORMAT_NONE)
785                 return;
786
787         mono_debugger_lock ();
788
789         mono_thread_get_stack_bounds (&staddr, &stsize);
790
791         info = g_new0 (MonoDebuggerThreadInfo, 1);
792         info->tid = tid;
793         info->thread = thread;
794         info->stack_start = (guint64) (gsize) staddr;
795         info->signal_stack_start = (guint64) (gsize) jit_tls->signal_stack;
796         info->stack_size = stsize;
797         info->signal_stack_size = jit_tls->signal_stack_size;
798         info->end_stack = (guint64) (gsize) GC_mono_debugger_get_stack_ptr ();
799         info->lmf_addr = (guint64) (gsize) mono_get_lmf_addr ();
800         info->jit_tls = jit_tls;
801
802         info->next = mono_debugger_thread_table;
803         mono_debugger_thread_table = info;
804
805         mono_debugger_event (MONO_DEBUGGER_EVENT_THREAD_CREATED,
806                              tid, (guint64) (gsize) info);
807
808         mono_debugger_unlock ();
809 #endif /* MONO_DEBUGGER_SUPPORTED */
810 }
811
812 void
813 mono_debugger_thread_cleanup (MonoJitTlsData *jit_tls)
814 {
815 #ifdef MONO_DEBUGGER_SUPPORTED
816         MonoDebuggerThreadInfo **ptr;
817
818         if (mono_debug_format == MONO_DEBUG_FORMAT_NONE)
819                 return;
820
821         mono_debugger_lock ();
822
823         for (ptr = &mono_debugger_thread_table; *ptr; ptr = &(*ptr)->next) {
824                 MonoDebuggerThreadInfo *info = *ptr;
825
826                 if (info->jit_tls != jit_tls)
827                         continue;
828
829                 mono_debugger_event (MONO_DEBUGGER_EVENT_THREAD_CLEANUP,
830                                      info->tid, (guint64) (gsize) info);
831
832                 *ptr = info->next;
833                 g_free (info);
834                 break;
835         }
836
837         mono_debugger_unlock ();
838 #endif
839 }
840
841 void
842 mono_debugger_extended_notification (MonoDebuggerEvent event, guint64 data, guint64 arg)
843 {
844 #ifdef MONO_DEBUGGER_SUPPORTED
845         MonoDebuggerThreadInfo **ptr;
846         MonoThread *thread = mono_thread_current ();
847
848         if (!mono_debug_using_mono_debugger ())
849                 return;
850
851         mono_debugger_lock ();
852
853         for (ptr = &mono_debugger_thread_table; *ptr; ptr = &(*ptr)->next) {
854                 MonoDebuggerThreadInfo *info = *ptr;
855
856                 if (info->thread != thread)
857                         continue;
858
859                 if ((info->extended_notifications & (int) event) == 0)
860                         continue;
861
862                 mono_debugger_event (event, data, arg);
863         }
864
865         mono_debugger_unlock ();
866 #endif
867 }
868
869 void
870 mono_debugger_trampoline_compiled (MonoMethod *method, const guint8 *code)
871 {
872         mono_debugger_extended_notification (MONO_DEBUGGER_EVENT_TRAMPOLINE,
873                                              (guint64) (gsize) method, (guint64) (gsize) code);
874 }
875
876 #if MONO_DEBUGGER_SUPPORTED
877 static MonoDebuggerThreadInfo *
878 find_debugger_thread_info (MonoThread *thread)
879 {
880         MonoDebuggerThreadInfo **ptr;
881
882         for (ptr = &mono_debugger_thread_table; *ptr; ptr = &(*ptr)->next) {
883                 MonoDebuggerThreadInfo *info = *ptr;
884
885                 if (info->thread == thread)
886                         return info;
887         }
888
889         return NULL;
890 }
891 #endif
892
893 static MonoDebuggerExceptionAction
894 _mono_debugger_throw_exception (gpointer addr, gpointer stack, MonoObject *exc)
895 {
896 #ifdef MONO_DEBUGGER_SUPPORTED
897         MonoDebuggerExceptionInfo exc_info;
898         MonoDebuggerThreadInfo *thread_info;
899
900         if (!mono_debug_using_mono_debugger ())
901                 return MONO_DEBUGGER_EXCEPTION_ACTION_NONE;
902
903         mono_debugger_lock ();
904
905         thread_info = find_debugger_thread_info (mono_thread_current ());
906         if (!thread_info) {
907                 mono_debugger_unlock ();
908                 return MONO_DEBUGGER_EXCEPTION_ACTION_NONE;
909         }
910
911         if (thread_info->exception_state.stopped_on_exception ||
912             thread_info->exception_state.stopped_on_unhandled) {
913                 thread_info->exception_state.stopped_on_exception = 0;
914                 mono_debugger_unlock ();
915                 return MONO_DEBUGGER_EXCEPTION_ACTION_NONE;
916         }
917
918         /* Protect the exception object from being garbage collected. */
919
920         thread_info->exception_state.stopped_on_unhandled = 0;
921         thread_info->exception_state.stopped_on_exception = 1;
922         thread_info->exception_state.last_exception = exc;
923
924         /*
925          * Backwards compatibility:
926          *
927          * Older debugger versions only know `exc_info.stop' and older runtime versions check
928          * `exc_info.stop != 0'.
929          *
930          * The debugger must check for `mono_debug_debugger_version >= 5' before accessing the
931          * `stop_unhandled' field.
932          */
933
934         exc_info.stack_pointer = stack;
935         exc_info.exception_obj = exc;
936         exc_info.stop = 0;
937         exc_info.stop_unhandled = 0;
938
939         mono_debugger_event (MONO_DEBUGGER_EVENT_THROW_EXCEPTION, (guint64) (gsize) &exc_info,
940                              (guint64) (gsize) addr);
941
942         if (!exc_info.stop) {
943                 thread_info->exception_state.stopped_on_exception = 0;
944                 thread_info->exception_state.last_exception = NULL;
945         } 
946
947         mono_debugger_unlock ();
948
949         if (exc_info.stop)
950                 return MONO_DEBUGGER_EXCEPTION_ACTION_STOP;
951         else if (exc_info.stop_unhandled)
952                 return MONO_DEBUGGER_EXCEPTION_ACTION_STOP_UNHANDLED;
953 #endif
954
955         return MONO_DEBUGGER_EXCEPTION_ACTION_NONE;
956 }
957
958 static gboolean
959 _mono_debugger_unhandled_exception (gpointer addr, gpointer stack, MonoObject *exc)
960 {
961 #ifdef MONO_DEBUGGER_SUPPORTED
962         MonoDebuggerThreadInfo *thread_info;
963
964         if (!mono_debug_using_mono_debugger ())
965                 return FALSE;
966
967         if (exc) {
968                 const gchar *name = mono_class_get_name (mono_object_get_class (exc));
969                 if (!strcmp (name, "ThreadAbortException"))
970                         return FALSE;
971         }
972
973         mono_debugger_lock ();
974
975         thread_info = find_debugger_thread_info (mono_thread_current ());
976         if (!thread_info) {
977                 mono_debugger_unlock ();
978                 return FALSE;
979         }
980
981         if (thread_info->exception_state.stopped_on_unhandled) {
982                 thread_info->exception_state.stopped_on_unhandled = 0;
983                 mono_debugger_unlock ();
984                 return FALSE;
985         }
986
987         thread_info->exception_state.stopped_on_unhandled = 1;
988         thread_info->exception_state.last_exception = exc;
989
990         mono_debugger_event (MONO_DEBUGGER_EVENT_UNHANDLED_EXCEPTION,
991                              (guint64) (gsize) exc, (guint64) (gsize) addr);
992
993         return TRUE;
994 #else
995         return FALSE;
996 #endif
997 }
998
999 /*
1000  * mono_debugger_call_exception_handler:
1001  *
1002  * Called from mono_handle_exception_internal() to tell the debugger that we're about
1003  * to invoke an exception handler.
1004  *
1005  * The debugger may choose to set a breakpoint at @addr.  This is used if the user is
1006  * single-stepping from a `try' into a `catch' block, for instance.
1007  */
1008
1009 void
1010 mono_debugger_call_exception_handler (gpointer addr, gpointer stack, MonoObject *exc)
1011 {
1012 #ifdef MONO_DEBUGGER_SUPPORTED
1013         MonoDebuggerThreadInfo *thread_info;
1014         MonoDebuggerExceptionInfo exc_info;
1015
1016         if (!mono_debug_using_mono_debugger ())
1017                 return;
1018
1019         mono_debugger_lock ();
1020
1021         thread_info = find_debugger_thread_info (mono_thread_current ());
1022         if (!thread_info) {
1023                 mono_debugger_unlock ();
1024                 return;
1025         }
1026
1027         // Prevent the object from being finalized.
1028         thread_info->exception_state.last_exception = exc;
1029
1030         exc_info.stack_pointer = stack;
1031         exc_info.exception_obj = exc;
1032         exc_info.stop = 0;
1033         exc_info.stop_unhandled = 0;
1034
1035         mono_debugger_event (MONO_DEBUGGER_EVENT_HANDLE_EXCEPTION, (guint64) (gsize) &exc_info,
1036                              (guint64) (gsize) addr);
1037
1038         mono_debugger_unlock ();
1039 #endif
1040 }
1041
1042 /*
1043  * mono_debugger_handle_exception:
1044  *
1045  *  Notify the debugger about exceptions.  Returns TRUE if the debugger wants us to stop
1046  *  at the exception and FALSE to resume with the normal exception handling.
1047  *
1048  *  The arch code is responsible to setup @ctx in a way that MONO_CONTEXT_GET_IP () and
1049  *  MONO_CONTEXT_GET_SP () point to the throw instruction; ie. before executing the
1050  *  `callq throw' instruction.
1051  */
1052 gboolean
1053 mono_debugger_handle_exception (MonoContext *ctx, MonoObject *obj)
1054 {
1055         MonoDebuggerExceptionAction action;
1056
1057         if (!mono_debug_using_mono_debugger ())
1058                 return FALSE;
1059
1060         if (!obj) {
1061                 MonoException *ex = mono_get_exception_null_reference ();
1062                 MONO_OBJECT_SETREF (ex, message, mono_string_new (mono_domain_get (), "Object reference not set to an instance of an object"));
1063                 obj = (MonoObject *)ex;
1064         } 
1065
1066         action = _mono_debugger_throw_exception (MONO_CONTEXT_GET_IP (ctx), MONO_CONTEXT_GET_SP (ctx), obj);
1067
1068         if (action == MONO_DEBUGGER_EXCEPTION_ACTION_STOP) {
1069                 /*
1070                  * The debugger wants us to stop on the `throw' instruction.
1071                  * By the time we get here, it already inserted a breakpoint there.
1072                  */
1073                 return TRUE;
1074         } else if (action == MONO_DEBUGGER_EXCEPTION_ACTION_STOP_UNHANDLED) {
1075                 MonoContext ctx_cp = *ctx;
1076
1077                 /*
1078                  * The debugger wants us to stop only if this exception is user-unhandled.
1079                  */
1080
1081                 if (!mono_handle_exception (&ctx_cp, obj, MONO_CONTEXT_GET_IP (ctx), TRUE)) {
1082                         /*
1083                          * The exception is user-unhandled - tell the debugger to stop.
1084                          */
1085                         return _mono_debugger_unhandled_exception (MONO_CONTEXT_GET_IP (ctx), MONO_CONTEXT_GET_SP (ctx), obj);
1086                 }
1087
1088                 /*
1089                  * The exception is catched somewhere - resume with the normal exception handling and don't
1090                  * stop in the debugger.
1091                  */
1092         }
1093
1094         return FALSE;
1095 }
1096
1097 #ifdef MONO_DEBUGGER_SUPPORTED
1098
1099 static gchar *
1100 get_exception_message (MonoObject *exc)
1101 {
1102         char *message = NULL;
1103         MonoString *str; 
1104         MonoMethod *method;
1105         MonoClass *klass;
1106         gint i;
1107
1108         if (mono_object_isinst (exc, mono_defaults.exception_class)) {
1109                 klass = exc->vtable->klass;
1110                 method = NULL;
1111                 while (klass && method == NULL) {
1112                         for (i = 0; i < klass->method.count; ++i) {
1113                                 method = klass->methods [i];
1114                                 if (!strcmp ("ToString", method->name) &&
1115                                     mono_method_signature (method)->param_count == 0 &&
1116                                     method->flags & METHOD_ATTRIBUTE_VIRTUAL &&
1117                                     method->flags & METHOD_ATTRIBUTE_PUBLIC) {
1118                                         break;
1119                                 }
1120                                 method = NULL;
1121                         }
1122                         
1123                         if (method == NULL)
1124                                 klass = klass->parent;
1125                 }
1126
1127                 g_assert (method);
1128
1129                 str = (MonoString *) mono_runtime_invoke (method, exc, NULL, NULL);
1130                 if (str)
1131                         message = mono_string_to_utf8 (str);
1132         }
1133
1134         return message;
1135 }
1136
1137 MonoObject *
1138 mono_debugger_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
1139 {
1140         MonoDebuggerThreadInfo *thread_info;
1141         MonoDebuggerExceptionState saved_exception_state;
1142         MonoObject *retval;
1143         gchar *message;
1144
1145         mono_debugger_lock ();
1146
1147         thread_info = find_debugger_thread_info (mono_thread_current ());
1148         if (!thread_info) {
1149                 mono_debugger_unlock ();
1150                 return NULL;
1151         }
1152
1153         saved_exception_state = thread_info->exception_state;
1154
1155         thread_info->exception_state.last_exception = NULL;
1156         thread_info->exception_state.stopped_on_unhandled = 0;
1157         thread_info->exception_state.stopped_on_exception = 0;
1158
1159         mono_debugger_unlock ();
1160
1161         if (!strcmp (method->name, ".ctor")) {
1162                 retval = obj = mono_object_new (mono_domain_get (), method->klass);
1163
1164                 mono_runtime_invoke (method, obj, params, exc);
1165         } else
1166                 retval = mono_runtime_invoke (method, obj, params, exc);
1167
1168         mono_debugger_lock ();
1169
1170         thread_info = find_debugger_thread_info (mono_thread_current ());
1171         if (thread_info)
1172                 thread_info->exception_state = saved_exception_state;
1173
1174         mono_debugger_unlock ();
1175
1176         if (!exc || (*exc == NULL))
1177                 return retval;
1178
1179         retval = *exc;
1180         message = get_exception_message (*exc);
1181         if (message) {
1182                 *exc = (MonoObject *) mono_string_new_wrapper (message);
1183                 g_free (message);
1184         }
1185
1186         return retval;
1187 }
1188
1189 #endif