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