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