Speed up suspending when running under the loader lock.
[mono.git] / mono / mini / debugger-agent.c
1 /*
2  * debugger-agent.c: Soft Debugger back-end module
3  *
4  * Author:
5  *   Zoltan Varga (vargaz@gmail.com)
6  *
7  * Copyright 2009-2010 Novell, Inc.
8  */
9
10 #include <config.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #ifdef HAVE_SYS_TYPES_H
15 #include <sys/types.h>
16 #endif
17 #ifdef HAVE_SYS_SELECT_H
18 #include <sys/select.h>
19 #endif
20 #ifdef HAVE_SYS_SOCKET_H
21 #include <sys/socket.h>
22 #endif
23 #ifdef HAVE_NETINET_TCP_H
24 #include <netinet/tcp.h>
25 #endif
26 #ifdef HAVE_NETINET_IN_H
27 #include <netinet/in.h>
28 #endif
29 #ifdef HAVE_NETDB_H
30 #include <netdb.h>
31 #endif
32 #ifdef HAVE_UNISTD_H
33 #include <unistd.h>
34 #endif
35 #include <errno.h>
36 #include <glib.h>
37
38 #ifdef HAVE_PTHREAD_H
39 #include <pthread.h>
40 #endif
41
42 #ifdef HAVE_UCONTEXT_H
43 #include <ucontext.h>
44 #endif
45
46 #ifdef HOST_WIN32
47 #ifdef _MSC_VER
48 #include <winsock2.h>
49 #endif
50 #include <ws2tcpip.h>
51 #ifdef __GNUC__
52 /* cygwin's headers do not seem to define these */
53 void WSAAPI freeaddrinfo (struct addrinfo*);
54 int WSAAPI getaddrinfo (const char*,const char*,const struct addrinfo*,
55                         struct addrinfo**);
56 int WSAAPI getnameinfo(const struct sockaddr*,socklen_t,char*,DWORD,
57                        char*,DWORD,int);
58 #endif
59 #endif
60
61 #ifdef PLATFORM_ANDROID
62 #include <linux/in.h>
63 #include <linux/tcp.h>
64 #include <sys/endian.h>
65 #endif
66
67 #include <mono/metadata/mono-debug.h>
68 #include <mono/metadata/mono-debug-debugger.h>
69 #include <mono/metadata/debug-mono-symfile.h>
70 #include <mono/metadata/gc-internal.h>
71 #include <mono/metadata/threads-types.h>
72 #include <mono/metadata/socket-io.h>
73 #include <mono/metadata/assembly.h>
74 #include <mono/utils/mono-semaphore.h>
75 #include <mono/utils/mono-error-internals.h>
76 #include "debugger-agent.h"
77 #include "mini.h"
78
79 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
80 #define DISABLE_DEBUGGER_AGENT 1
81 #endif
82
83 #ifdef DISABLE_SOFT_DEBUG
84 #define DISABLE_DEBUGGER_AGENT 1
85 #endif
86
87 #ifndef DISABLE_DEBUGGER_AGENT
88
89 #include <mono/io-layer/mono-mutex.h>
90
91 /* Definitions to make backporting to 2.6 easier */
92 //#define MonoInternalThread MonoThread
93 //#define mono_thread_internal_current mono_thread_current
94 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
95
96 typedef struct {
97         gboolean enabled;
98         char *transport;
99         char *address;
100         int log_level;
101         char *log_file;
102         gboolean suspend;
103         gboolean server;
104         gboolean onuncaught;
105         GSList *onthrow;
106         int timeout;
107         char *launch;
108         gboolean embedding;
109         gboolean defer;
110 } AgentConfig;
111
112 typedef struct
113 {
114         int id;
115         guint32 il_offset, native_offset;
116         MonoDomain *domain;
117         MonoMethod *method;
118         /*
119          * If method is gshared, this is the actual instance, otherwise this is equal to
120          * method.
121          */
122         MonoMethod *actual_method;
123         MonoContext ctx;
124         MonoDebugMethodJitInfo *jit;
125         int flags;
126         /*
127          * Whenever ctx is set. This is FALSE for the last frame of running threads, since
128          * the frame can become invalid.
129          */
130         gboolean has_ctx;
131 } StackFrame;
132
133 typedef struct _InvokeData InvokeData;
134
135 struct _InvokeData
136 {
137         int id;
138         int flags;
139         guint8 *p;
140         guint8 *endp;
141         /* This is the context which needs to be restored after the invoke */
142         MonoContext ctx;
143         gboolean has_ctx;
144         /*
145          * If this is set, invoke this method with the arguments given by ARGS.
146          */
147         MonoMethod *method;
148         gpointer *args;
149         guint32 suspend_count;
150
151         InvokeData *last_invoke;
152 };
153
154 typedef struct {
155         MonoContext ctx;
156         MonoLMF *lmf;
157         MonoDomain *domain;
158         gboolean has_context;
159         gpointer resume_event;
160         /* This is computed on demand when it is requested using the wire protocol */
161         /* It is freed up when the thread is resumed */
162         int frame_count;
163         StackFrame **frames;
164         /* 
165          * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
166          * re-compute it.
167          */
168         gboolean frames_up_to_date;
169         /* 
170          * Points to data about a pending invoke which needs to be executed after the thread
171          * resumes.
172          */
173         InvokeData *pending_invoke;
174         /*
175          * Set to TRUE if this thread is suspended in suspend_current () or it is executing
176          * native code.
177          */
178         gboolean suspended;
179         /*
180          * Signals whenever the thread is in the process of suspending, i.e. it will suspend
181          * within a finite amount of time.
182          */
183         gboolean suspending;
184         /*
185          * Set to TRUE if this thread is suspended in suspend_current ().
186          */
187         gboolean really_suspended;
188         /* Used to pass the context to the breakpoint/single step handler */
189         MonoContext handler_ctx;
190         /* Whenever thread_stop () was called for this thread */
191         gboolean terminated;
192
193         /* Number of thread interruptions not yet processed */
194         gint32 interrupt_count;
195
196         /* Whenever to disable breakpoints (used during invokes) */
197         gboolean disable_breakpoints;
198
199         /*
200          * Number of times this thread has been resumed using resume_thread ().
201          */
202         guint32 resume_count;
203
204         MonoInternalThread *thread;
205
206         /*
207          * Information about the frame which transitioned to native code for running
208          * threads.
209          */
210         StackFrameInfo async_last_frame;
211
212         /*
213          * The context where the stack walk can be started for running threads.
214          */
215         MonoContext async_ctx;
216
217         gboolean has_async_ctx;
218
219         gboolean has_filter_ctx;
220         MonoContext filter_ctx;
221         MonoLMF *filter_lmf;
222
223         /*
224          * The lmf where the stack walk can be started for running threads.
225          */
226         gpointer async_lmf;
227
228         /*
229          * The callee address of the last mono_runtime_invoke call
230          */
231         gpointer invoke_addr;
232
233         gboolean abort_requested;
234
235         /*
236          * The current mono_runtime_invoke invocation.
237          */
238         InvokeData *invoke;
239
240         /*
241          * The context where single stepping should resume while the thread is suspended because
242          * of an EXCEPTION event.
243          */
244         MonoContext catch_ctx;
245
246         gboolean has_catch_ctx;
247 } DebuggerTlsData;
248
249 /* 
250  * Wire Protocol definitions
251  */
252
253 #define HEADER_LENGTH 11
254
255 #define MAJOR_VERSION 2
256 #define MINOR_VERSION 3
257
258 typedef enum {
259         CMD_SET_VM = 1,
260         CMD_SET_OBJECT_REF = 9,
261         CMD_SET_STRING_REF = 10,
262         CMD_SET_THREAD = 11,
263         CMD_SET_ARRAY_REF = 13,
264         CMD_SET_EVENT_REQUEST = 15,
265         CMD_SET_STACK_FRAME = 16,
266         CMD_SET_APPDOMAIN = 20,
267         CMD_SET_ASSEMBLY = 21,
268         CMD_SET_METHOD = 22,
269         CMD_SET_TYPE = 23,
270         CMD_SET_MODULE = 24,
271         CMD_SET_EVENT = 64
272 } CommandSet;
273
274 typedef enum {
275         EVENT_KIND_VM_START = 0,
276         EVENT_KIND_VM_DEATH = 1,
277         EVENT_KIND_THREAD_START = 2,
278         EVENT_KIND_THREAD_DEATH = 3,
279         EVENT_KIND_APPDOMAIN_CREATE = 4,
280         EVENT_KIND_APPDOMAIN_UNLOAD = 5,
281         EVENT_KIND_METHOD_ENTRY = 6,
282         EVENT_KIND_METHOD_EXIT = 7,
283         EVENT_KIND_ASSEMBLY_LOAD = 8,
284         EVENT_KIND_ASSEMBLY_UNLOAD = 9,
285         EVENT_KIND_BREAKPOINT = 10,
286         EVENT_KIND_STEP = 11,
287         EVENT_KIND_TYPE_LOAD = 12,
288         EVENT_KIND_EXCEPTION = 13
289 } EventKind;
290
291 typedef enum {
292         SUSPEND_POLICY_NONE = 0,
293         SUSPEND_POLICY_EVENT_THREAD = 1,
294         SUSPEND_POLICY_ALL = 2
295 } SuspendPolicy;
296
297 typedef enum {
298         ERR_NONE = 0,
299         ERR_INVALID_OBJECT = 20,
300         ERR_INVALID_FIELDID = 25,
301         ERR_INVALID_FRAMEID = 30,
302         ERR_NOT_IMPLEMENTED = 100,
303         ERR_NOT_SUSPENDED = 101,
304         ERR_INVALID_ARGUMENT = 102,
305         ERR_UNLOADED = 103,
306         ERR_NO_INVOCATION = 104,
307         ERR_ABSENT_INFORMATION = 105,
308         ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106
309 } ErrorCode;
310
311 typedef enum {
312         MOD_KIND_COUNT = 1,
313         MOD_KIND_THREAD_ONLY = 3,
314         MOD_KIND_LOCATION_ONLY = 7,
315         MOD_KIND_EXCEPTION_ONLY = 8,
316         MOD_KIND_STEP = 10,
317         MOD_KIND_ASSEMBLY_ONLY = 11
318 } ModifierKind;
319
320 typedef enum {
321         STEP_DEPTH_INTO = 0,
322         STEP_DEPTH_OVER = 1,
323         STEP_DEPTH_OUT = 2
324 } StepDepth;
325
326 typedef enum {
327         STEP_SIZE_MIN = 0,
328         STEP_SIZE_LINE = 1
329 } StepSize;
330
331 typedef enum {
332         TOKEN_TYPE_STRING = 0,
333         TOKEN_TYPE_TYPE = 1,
334         TOKEN_TYPE_FIELD = 2,
335         TOKEN_TYPE_METHOD = 3,
336         TOKEN_TYPE_UNKNOWN = 4
337 } DebuggerTokenType;
338
339 typedef enum {
340         VALUE_TYPE_ID_NULL = 0xf0,
341         VALUE_TYPE_ID_TYPE = 0xf1
342 } ValueTypeId;
343
344 typedef enum {
345         FRAME_FLAG_DEBUGGER_INVOKE = 1
346 } StackFrameFlags;
347
348 typedef enum {
349         INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
350         INVOKE_FLAG_SINGLE_THREADED = 2
351 } InvokeFlags;
352
353 typedef enum {
354         CMD_VM_VERSION = 1,
355         CMD_VM_ALL_THREADS = 2,
356         CMD_VM_SUSPEND = 3,
357         CMD_VM_RESUME = 4,
358         CMD_VM_EXIT = 5,
359         CMD_VM_DISPOSE = 6,
360         CMD_VM_INVOKE_METHOD = 7,
361         CMD_VM_SET_PROTOCOL_VERSION = 8,
362         CMD_VM_ABORT_INVOKE = 9
363 } CmdVM;
364
365 typedef enum {
366         CMD_THREAD_GET_FRAME_INFO = 1,
367         CMD_THREAD_GET_NAME = 2,
368         CMD_THREAD_GET_STATE = 3,
369         CMD_THREAD_GET_INFO = 4,
370         CMD_THREAD_GET_ID = 5,
371         CMD_THREAD_GET_TID = 6
372 } CmdThread;
373
374 typedef enum {
375         CMD_EVENT_REQUEST_SET = 1,
376         CMD_EVENT_REQUEST_CLEAR = 2,
377         CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
378 } CmdEvent;
379
380 typedef enum {
381         CMD_COMPOSITE = 100
382 } CmdComposite;
383
384 typedef enum {
385         CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
386         CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
387         CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
388         CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
389         CMD_APPDOMAIN_CREATE_STRING = 5,
390         CMD_APPDOMAIN_GET_CORLIB = 6,
391         CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7,
392 } CmdAppDomain;
393
394 typedef enum {
395         CMD_ASSEMBLY_GET_LOCATION = 1,
396         CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
397         CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
398         CMD_ASSEMBLY_GET_OBJECT = 4,
399         CMD_ASSEMBLY_GET_TYPE = 5,
400         CMD_ASSEMBLY_GET_NAME = 6
401 } CmdAssembly;
402
403 typedef enum {
404         CMD_MODULE_GET_INFO = 1,
405 } CmdModule;
406
407 typedef enum {
408         CMD_METHOD_GET_NAME = 1,
409         CMD_METHOD_GET_DECLARING_TYPE = 2,
410         CMD_METHOD_GET_DEBUG_INFO = 3,
411         CMD_METHOD_GET_PARAM_INFO = 4,
412         CMD_METHOD_GET_LOCALS_INFO = 5,
413         CMD_METHOD_GET_INFO = 6,
414         CMD_METHOD_GET_BODY = 7,
415         CMD_METHOD_RESOLVE_TOKEN = 8,
416 } CmdMethod;
417
418 typedef enum {
419         CMD_TYPE_GET_INFO = 1,
420         CMD_TYPE_GET_METHODS = 2,
421         CMD_TYPE_GET_FIELDS = 3,
422         CMD_TYPE_GET_VALUES = 4,
423         CMD_TYPE_GET_OBJECT = 5,
424         CMD_TYPE_GET_SOURCE_FILES = 6,
425         CMD_TYPE_SET_VALUES = 7,
426         CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
427         CMD_TYPE_GET_PROPERTIES = 9,
428         CMD_TYPE_GET_CATTRS = 10,
429         CMD_TYPE_GET_FIELD_CATTRS = 11,
430         CMD_TYPE_GET_PROPERTY_CATTRS = 12,
431         CMD_TYPE_GET_SOURCE_FILES_2 = 13,
432         CMD_TYPE_GET_VALUES_2 = 14
433 } CmdType;
434
435 typedef enum {
436         CMD_STACK_FRAME_GET_VALUES = 1,
437         CMD_STACK_FRAME_GET_THIS = 2,
438         CMD_STACK_FRAME_SET_VALUES = 3
439 } CmdStackFrame;
440
441 typedef enum {
442         CMD_ARRAY_REF_GET_LENGTH = 1,
443         CMD_ARRAY_REF_GET_VALUES = 2,
444         CMD_ARRAY_REF_SET_VALUES = 3,
445 } CmdArray;
446
447 typedef enum {
448         CMD_STRING_REF_GET_VALUE = 1,
449 } CmdString;
450
451 typedef enum {
452         CMD_OBJECT_REF_GET_TYPE = 1,
453         CMD_OBJECT_REF_GET_VALUES = 2,
454         CMD_OBJECT_REF_IS_COLLECTED = 3,
455         CMD_OBJECT_REF_GET_ADDRESS = 4,
456         CMD_OBJECT_REF_GET_DOMAIN = 5,
457         CMD_OBJECT_REF_SET_VALUES = 6
458 } CmdObject;
459
460 typedef struct {
461         ModifierKind kind;
462         union {
463                 int count; /* For kind == MOD_KIND_COUNT */
464                 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
465                 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
466                 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
467         } data;
468         gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
469 } Modifier;
470
471 typedef struct{
472         int id;
473         int event_kind;
474         int suspend_policy;
475         int nmodifiers;
476         gpointer info;
477         Modifier modifiers [MONO_ZERO_LEN_ARRAY];
478 } EventRequest;
479
480 /*
481  * Describes a single step request.
482  */
483 typedef struct {
484         EventRequest *req;
485         MonoInternalThread *thread;
486         StepDepth depth;
487         StepSize size;
488         gpointer last_sp;
489         gpointer start_sp;
490         MonoMethod *last_method;
491         int last_line;
492         /* Whenever single stepping is performed using start/stop_single_stepping () */
493         gboolean global;
494         /* The list of breakpoints used to implement step-over */
495         GSList *bps;
496 } SingleStepReq;
497
498 /*
499  * Contains additional information for an event
500  */
501 typedef struct {
502         /* For EVENT_KIND_EXCEPTION */
503         MonoObject *exc;
504         MonoContext catch_ctx;
505         gboolean caught;
506 } EventInfo;
507
508 /* Dummy structure used for the profiler callbacks */
509 typedef struct {
510         void* dummy;
511 } DebuggerProfiler;
512
513 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
514
515 /*
516  * Globals
517  */
518
519 static AgentConfig agent_config;
520
521 /* 
522  * Whenever the agent is fully initialized.
523  * When using the onuncaught or onthrow options, only some parts of the agent are
524  * initialized on startup, and the full initialization which includes connection
525  * establishment and the startup of the agent thread is only done in response to
526  * an event.
527  */
528 static gint32 inited;
529
530 static int conn_fd;
531 static int listen_fd;
532
533 static int packet_id = 0;
534
535 static int objref_id = 0;
536
537 static int event_request_id = 0;
538
539 static int frame_id = 0;
540
541 static GPtrArray *event_requests;
542
543 static guint32 debugger_tls_id;
544
545 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
546
547 /* Maps MonoInternalThread -> DebuggerTlsData */
548 static MonoGHashTable *thread_to_tls;
549
550 /* Maps tid -> MonoInternalThread */
551 static MonoGHashTable *tid_to_thread;
552
553 /* Maps tid -> MonoThread (not MonoInternalThread) */
554 static MonoGHashTable *tid_to_thread_obj;
555
556 static gsize debugger_thread_id;
557
558 static HANDLE debugger_thread_handle;
559
560 static int log_level;
561
562 static gboolean embedding;
563
564 static FILE *log_file;
565
566 /* Assemblies whose assembly load event has no been sent yet */
567 static GPtrArray *pending_assembly_loads;
568
569 /* Whenever the debugger thread has exited */
570 static gboolean debugger_thread_exited;
571
572 /* Cond variable used to wait for debugger_thread_exited becoming true */
573 static mono_cond_t debugger_thread_exited_cond;
574
575 /* Mutex for the cond var above */
576 static mono_mutex_t debugger_thread_exited_mutex;
577
578 static DebuggerProfiler debugger_profiler;
579
580 /* The single step request instance */
581 static SingleStepReq *ss_req = NULL;
582 static gpointer ss_invoke_addr = NULL;
583
584 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
585 /* Number of single stepping operations in progress */
586 static int ss_count;
587 #endif
588
589 /* The protocol version of the client */
590 static int major_version, minor_version;
591
592 /* Whenever the variables above are set by the client */
593 static gboolean protocol_version_set;
594
595 /* A hash table containing all active domains */
596 static GHashTable *domains;
597
598 static void transport_connect (const char *host, int port);
599
600 static guint32 WINAPI debugger_thread (void *arg);
601
602 static void runtime_initialized (MonoProfiler *prof);
603
604 static void runtime_shutdown (MonoProfiler *prof);
605
606 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
607
608 static void thread_end (MonoProfiler *prof, uintptr_t tid);
609
610 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
611
612 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
613
614 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
615
616 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
617
618 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
619
620 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
621
622 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
623
624 static void emit_assembly_load (gpointer assembly, gpointer user_data);
625
626 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
627
628 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
629
630 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
631
632 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
633
634 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
635
636 static void start_single_stepping (void);
637
638 static void stop_single_stepping (void);
639
640 static void suspend_current (void);
641
642 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
643
644 static void clear_types_for_assembly (MonoAssembly *assembly);
645
646 static void clear_breakpoints_for_domain (MonoDomain *domain);
647
648 static void process_profiler_event (EventKind event, gpointer arg);
649
650 /* Submodule init/cleanup */
651 static void breakpoints_init (void);
652 static void breakpoints_cleanup (void);
653
654 static void objrefs_init (void);
655 static void objrefs_cleanup (void);
656
657 static void ids_init (void);
658 static void ids_cleanup (void);
659
660 static void suspend_init (void);
661
662 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
663 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
664 static void ss_destroy (SingleStepReq *req);
665
666 static void start_debugger_thread (void);
667 static void stop_debugger_thread (void);
668
669 static void finish_agent_init (gboolean on_startup);
670
671 static int
672 parse_address (char *address, char **host, int *port)
673 {
674         char *pos = strchr (address, ':');
675
676         if (pos == NULL || pos == address)
677                 return 1;
678
679         *host = g_malloc (pos - address + 1);
680         strncpy (*host, address, pos - address);
681         (*host) [pos - address] = '\0';
682
683         *port = atoi (pos + 1);
684
685         return 0;
686 }
687
688 static void
689 print_usage (void)
690 {
691         fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
692         fprintf (stderr, "Available options:\n");
693         fprintf (stderr, "  transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
694         fprintf (stderr, "  address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
695         fprintf (stderr, "  loglevel=<n>\t\t\tLog level (defaults to 0)\n");
696         fprintf (stderr, "  logfile=<file>\t\tFile to log to (defaults to stdout)\n");
697         fprintf (stderr, "  suspend=y/n\t\t\tWhether to suspend after startup.\n");
698         fprintf (stderr, "  timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
699         fprintf (stderr, "  server=y/n\t\t\tWhether to listen for a client connection.\n");
700         fprintf (stderr, "  help\t\t\t\tPrint this help.\n");
701 }
702
703 static gboolean
704 parse_flag (const char *option, char *flag)
705 {
706         if (!strcmp (flag, "y"))
707                 return TRUE;
708         else if (!strcmp (flag, "n"))
709                 return FALSE;
710         else {
711                 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
712                 exit (1);
713                 return FALSE;
714         }
715 }
716
717 void
718 mono_debugger_agent_parse_options (char *options)
719 {
720         char **args, **ptr;
721         char *host;
722         int port;
723
724 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
725         fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
726         exit (1);
727 #endif
728
729         agent_config.enabled = TRUE;
730         agent_config.suspend = TRUE;
731         agent_config.server = FALSE;
732         agent_config.defer = FALSE;
733         agent_config.address = NULL;
734
735         args = g_strsplit (options, ",", -1);
736         for (ptr = args; ptr && *ptr; ptr ++) {
737                 char *arg = *ptr;
738
739                 if (strncmp (arg, "transport=", 10) == 0) {
740                         agent_config.transport = g_strdup (arg + 10);
741                 } else if (strncmp (arg, "address=", 8) == 0) {
742                         agent_config.address = g_strdup (arg + 8);
743                 } else if (strncmp (arg, "loglevel=", 9) == 0) {
744                         agent_config.log_level = atoi (arg + 9);
745                 } else if (strncmp (arg, "logfile=", 8) == 0) {
746                         agent_config.log_file = g_strdup (arg + 8);
747                 } else if (strncmp (arg, "suspend=", 8) == 0) {
748                         agent_config.suspend = parse_flag ("suspend", arg + 8);
749                 } else if (strncmp (arg, "server=", 7) == 0) {
750                         agent_config.server = parse_flag ("server", arg + 7);
751                 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
752                         agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
753                 } else if (strncmp (arg, "onthrow=", 8) == 0) {
754                         /* We support multiple onthrow= options */
755                         agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
756                 } else if (strncmp (arg, "onthrow", 7) == 0) {
757                         agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
758                 } else if (strncmp (arg, "help", 4) == 0) {
759                         print_usage ();
760                         exit (0);
761                 } else if (strncmp (arg, "timeout=", 8) == 0) {
762                         agent_config.timeout = atoi (arg + 8);
763                 } else if (strncmp (arg, "launch=", 7) == 0) {
764                         agent_config.launch = g_strdup (arg + 7);
765                 } else if (strncmp (arg, "embedding=", 10) == 0) {
766                         agent_config.embedding = atoi (arg + 10) == 1;
767                 } else {
768                         print_usage ();
769                         exit (1);
770                 }
771         }
772
773         if (agent_config.server && !agent_config.suspend) {
774                 /* Waiting for deferred attachment */
775                 agent_config.defer = TRUE;
776                 if (agent_config.address == NULL) {
777                         agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
778                 }
779         }
780
781         if (agent_config.transport == NULL) {
782                 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
783                 exit (1);
784         }
785         if (strcmp (agent_config.transport, "dt_socket") != 0) {
786                 fprintf (stderr, "debugger-agent: The only supported value for the 'transport' option is 'dt_socket'.\n");
787                 exit (1);
788         }
789
790         if (agent_config.address == NULL && !agent_config.server) {
791                 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
792                 exit (1);
793         }
794
795         if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
796                 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
797                 exit (1);
798         }
799 }
800
801 void
802 mono_debugger_agent_init (void)
803 {
804         if (!agent_config.enabled)
805                 return;
806
807         /* Need to know whenever a thread has acquired the loader mutex */
808         mono_loader_lock_track_ownership (TRUE);
809
810         event_requests = g_ptr_array_new ();
811
812         mono_mutex_init (&debugger_thread_exited_mutex, NULL);
813         mono_cond_init (&debugger_thread_exited_cond, NULL);
814
815         mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
816         mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
817         mono_profiler_install_runtime_initialized (runtime_initialized);
818         mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
819         mono_profiler_install_thread (thread_startup, thread_end);
820         mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
821         mono_profiler_install_jit_end (jit_end);
822         mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
823
824         debugger_tls_id = TlsAlloc ();
825
826         thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
827         MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
828
829         tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
830         MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
831
832         tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
833         MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
834
835         pending_assembly_loads = g_ptr_array_new ();
836         domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
837
838         log_level = agent_config.log_level;
839
840         embedding = agent_config.embedding;
841         disconnected = TRUE;
842
843         if (agent_config.log_file) {
844                 log_file = fopen (agent_config.log_file, "w+");
845                 if (!log_file) {
846                         fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
847                         exit (1);
848                 }
849         } else {
850                 log_file = stdout;
851         }
852
853         ids_init ();
854         objrefs_init ();
855         breakpoints_init ();
856         suspend_init ();
857
858         mini_get_debug_options ()->gen_seq_points = TRUE;
859         /* 
860          * This is needed because currently we don't handle liveness info.
861          */
862         mini_get_debug_options ()->mdb_optimizations = TRUE;
863
864         /* This is needed because we can't set local variables in registers yet */
865         mono_disable_optimizations (MONO_OPT_LINEARS);
866
867         if (!agent_config.onuncaught && !agent_config.onthrow)
868                 finish_agent_init (TRUE);
869 }
870
871 /*
872  * finish_agent_init:
873  *
874  *   Finish the initialization of the agent. This involves connecting the transport
875  * and starting the agent thread. This is either done at startup, or
876  * in response to some event like an unhandled exception.
877  */
878 static void
879 finish_agent_init (gboolean on_startup)
880 {
881         char *host;
882         int port;
883         int res;
884
885         if (InterlockedCompareExchange (&inited, 1, 0) == 1)
886                 return;
887
888         if (agent_config.launch) {
889                 char *argv [16];
890
891                 // FIXME: Generated address
892                 // FIXME: Races with transport_connect ()
893
894                 argv [0] = agent_config.launch;
895                 argv [1] = agent_config.transport;
896                 argv [2] = agent_config.address;
897                 argv [3] = NULL;
898
899                 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
900                 if (!res) {
901                         fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
902                         exit (1);
903                 }
904         }
905
906         if (agent_config.address) {
907                 res = parse_address (agent_config.address, &host, &port);
908                 g_assert (res == 0);
909         } else {
910                 host = NULL;
911                 port = 0;
912         }
913
914         transport_connect (host, port);
915
916         if (!on_startup) {
917                 /* Do some which is usually done after sending the VMStart () event */
918                 vm_start_event_sent = TRUE;
919                 start_debugger_thread ();
920         }
921 }
922
923 static void
924 mono_debugger_agent_cleanup (void)
925 {
926         if (!inited)
927                 return;
928
929         stop_debugger_thread ();
930
931         breakpoints_cleanup ();
932         objrefs_cleanup ();
933         ids_cleanup ();
934         
935         mono_mutex_destroy (&debugger_thread_exited_mutex);
936         mono_cond_destroy (&debugger_thread_exited_cond);
937 }
938
939 /*
940  * recv_length:
941  *
942  * recv() + handle incomplete reads and EINTR
943  */
944 static int
945 recv_length (int fd, void *buf, int len, int flags)
946 {
947         int res;
948         int total = 0;
949
950         do {
951                 res = recv (fd, (char *) buf + total, len - total, flags);
952                 if (res > 0)
953                         total += res;
954         } while ((res > 0 && total < len) || (res == -1 && errno == EINTR));
955         return total;
956 }
957
958 #ifndef TARGET_PS3
959 #define HAVE_GETADDRINFO 1
960 #endif
961  
962 static int
963 transport_accept (int socket_fd)
964 {
965         conn_fd = accept (socket_fd, NULL, NULL);
966         if (conn_fd == -1) {
967                 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
968         } else {
969                 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
970         }
971         
972         return conn_fd;
973 }
974
975 static gboolean
976 transport_handshake (void)
977 {
978         char handshake_msg [128];
979         guint8 buf [128];
980         int res;
981         
982         /* Write handshake message */
983         sprintf (handshake_msg, "DWP-Handshake");
984         do {
985                 res = send (conn_fd, handshake_msg, strlen (handshake_msg), 0);
986         } while (res == -1 && errno == EINTR);
987         g_assert (res != -1);
988
989         /* Read answer */
990         res = recv_length (conn_fd, buf, strlen (handshake_msg), 0);
991         if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
992                 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
993                 return FALSE;
994         }
995
996         /*
997          * To support older clients, the client sends its protocol version after connecting
998          * using a command. Until that is received, default to our protocol version.
999          */
1000         major_version = MAJOR_VERSION;
1001         minor_version = MINOR_VERSION;
1002         protocol_version_set = FALSE;
1003
1004         /* 
1005          * Set TCP_NODELAY on the socket so the client receives events/command
1006          * results immediately.
1007          */
1008         {
1009                 int flag = 1;
1010                 int result = setsockopt (conn_fd,
1011                                  IPPROTO_TCP,
1012                                  TCP_NODELAY,
1013                                  (char *) &flag,
1014                                  sizeof(int));
1015                 g_assert (result >= 0);
1016         }
1017         
1018         return TRUE;
1019 }
1020
1021 /*
1022  * transport_connect:
1023  *
1024  *   Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1025  */
1026 static void
1027 transport_connect (const char *host, int port)
1028 {
1029 #ifdef HAVE_GETADDRINFO
1030         struct addrinfo hints;
1031         struct addrinfo *result, *rp;
1032 #else
1033         struct hostent *result;
1034 #endif
1035         int sfd, s, res;
1036         char port_string [128];
1037
1038         conn_fd = -1;
1039         listen_fd = -1;
1040
1041         if (host) {
1042                 sprintf (port_string, "%d", port);
1043
1044                 mono_network_init ();
1045
1046                 /* Obtain address(es) matching host/port */
1047 #ifdef HAVE_GETADDRINFO
1048                 memset (&hints, 0, sizeof (struct addrinfo));
1049                 hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
1050                 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1051                 hints.ai_flags = 0;
1052                 hints.ai_protocol = 0;          /* Any protocol */
1053
1054                 s = getaddrinfo (host, port_string, &hints, &result);
1055                 if (s != 0) {
1056                         fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1057                         exit (1);
1058                 }
1059 #else
1060                 /* The PS3 doesn't even have _r or hstrerror () */
1061                 result = gethostbyname (host);
1062                 if (!result) {
1063                         fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1064                 }
1065 #endif
1066         }
1067
1068         if (agent_config.server) {
1069 #ifdef HAVE_GETADDRINFO
1070                 /* Wait for a connection */
1071                 if (!host) {
1072                         struct sockaddr_in addr;
1073                         socklen_t addrlen;
1074
1075                         /* No address, generate one */
1076                         sfd = socket (AF_INET, SOCK_STREAM, 0);
1077                         g_assert (sfd);
1078
1079                         /* This will bind the socket to a random port */
1080                         res = listen (sfd, 16);
1081                         if (res == -1) {
1082                                 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (errno));
1083                                 exit (1);
1084                         }
1085                         listen_fd = sfd;
1086
1087                         addrlen = sizeof (addr);
1088                         memset (&addr, 0, sizeof (addr));
1089                         res = getsockname (sfd, &addr, &addrlen);
1090                         g_assert (res == 0);
1091
1092                         host = "127.0.0.1";
1093                         port = ntohs (addr.sin_port);
1094
1095                         /* Emit the address to stdout */
1096                         /* FIXME: Should print another interface, not localhost */
1097                         printf ("%s:%d\n", host, port);
1098                 } else {
1099                         /* Listen on the provided address */
1100                         for (rp = result; rp != NULL; rp = rp->ai_next) {
1101                                 sfd = socket (rp->ai_family, rp->ai_socktype,
1102                                                           rp->ai_protocol);
1103                                 if (sfd == -1)
1104                                         continue;
1105
1106                                 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1107                                 if (res == -1)
1108                                         continue;
1109
1110                                 res = listen (sfd, 16);
1111                                 if (res == -1)
1112                                         continue;
1113                                 listen_fd = sfd;
1114                                 break;
1115                         }
1116
1117 #ifndef HOST_WIN32
1118                         /*
1119                          * this function is not present on win2000 which we still support, and the
1120                          * workaround described here:
1121                          * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1122                          * only works with MSVC.
1123                          */
1124 #ifdef HAVE_GETADDRINFO
1125                         freeaddrinfo (result);
1126 #endif
1127 #endif
1128                 }
1129
1130                 if (agent_config.defer)
1131                         return;
1132
1133                 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1134
1135                 if (agent_config.timeout) {
1136                         fd_set readfds;
1137                         struct timeval tv;
1138
1139                         tv.tv_sec = 0;
1140                         tv.tv_usec = agent_config.timeout * 1000;
1141                         FD_ZERO (&readfds);
1142                         FD_SET (sfd, &readfds);
1143                         res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1144                         if (res == 0) {
1145                                 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1146                                 exit (1);
1147                         }
1148                 }
1149
1150                 conn_fd = transport_accept (sfd);
1151                 if (conn_fd == -1)
1152                         exit (1);
1153
1154                 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1155 #else
1156                 NOT_IMPLEMENTED;
1157 #endif /* HAVE_GETADDRINFO */
1158         } else {
1159                 /* Connect to the specified address */
1160 #ifdef HAVE_GETADDRINFO
1161                 /* FIXME: Respect the timeout */
1162                 for (rp = result; rp != NULL; rp = rp->ai_next) {
1163                         sfd = socket (rp->ai_family, rp->ai_socktype,
1164                                                   rp->ai_protocol);
1165                         if (sfd == -1)
1166                                 continue;
1167
1168                         if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1169                                 break;       /* Success */
1170                         
1171                         close (sfd);
1172                 }
1173
1174                 if (rp == 0) {
1175                         fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1176                         exit (1);
1177                 }
1178 #else
1179                         sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1180                         if (sfd == -1)
1181                                 g_assert_not_reached ();
1182                         res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1183                         if (res == -1)
1184                                 g_assert_not_reached ();
1185 #endif
1186
1187                 conn_fd = sfd;
1188
1189 #ifndef HOST_WIN32
1190                 /* See the comment above */
1191 #ifdef HAVE_GETADDRINFO
1192                 freeaddrinfo (result);
1193 #endif
1194 #endif
1195         }
1196         
1197         disconnected = !transport_handshake ();
1198         if (disconnected)
1199                 exit (1);
1200 }
1201
1202 static gboolean
1203 transport_send (guint8 *data, int len)
1204 {
1205         int res;
1206
1207         do {
1208                 res = send (conn_fd, data, len, 0);
1209         } while (res == -1 && errno == EINTR);
1210         if (res != len)
1211                 return FALSE;
1212         else
1213                 return TRUE;
1214 }
1215
1216 static void
1217 stop_debugger_thread (void)
1218 {
1219         if (!inited)
1220                 return;
1221
1222         /* This will interrupt the agent thread */
1223         /* Close the read part only so it can still send back replies */
1224         /* Also shut down the connection listener so that we can exit normally */
1225 #ifdef HOST_WIN32
1226         /* SD_RECEIVE doesn't break the recv in the debugger thread */
1227         shutdown (conn_fd, SD_BOTH);
1228         shutdown (listen_fd, SD_BOTH);
1229         closesocket (listen_fd);
1230 #else
1231         shutdown (conn_fd, SHUT_RD);
1232         shutdown (listen_fd, SHUT_RDWR);
1233         close (listen_fd);
1234 #endif
1235
1236         /* 
1237          * Wait for the thread to exit.
1238          *
1239          * If we continue with the shutdown without waiting for it, then the client might
1240          * not receive an answer to its last command like a resume.
1241          * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1242          * use pthreads.
1243          */
1244         //WaitForSingleObject (debugger_thread_handle, INFINITE);
1245         if (GetCurrentThreadId () != debugger_thread_id) {
1246                 do {
1247                         mono_mutex_lock (&debugger_thread_exited_mutex);
1248                         if (!debugger_thread_exited) {
1249 #ifdef HOST_WIN32
1250                                 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1251                                         mono_mutex_unlock (&debugger_thread_exited_mutex);
1252                                         Sleep(1);
1253                                         mono_mutex_lock (&debugger_thread_exited_mutex);
1254                                 }
1255 #else
1256                                 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1257 #endif
1258                         }
1259                         mono_mutex_unlock (&debugger_thread_exited_mutex);
1260                 } while (!debugger_thread_exited);
1261         }
1262
1263 #ifdef HOST_WIN32
1264         shutdown (conn_fd, SD_BOTH);
1265 #else
1266         shutdown (conn_fd, SHUT_RDWR);
1267 #endif
1268 }
1269
1270 static void
1271 start_debugger_thread (void)
1272 {
1273         gsize tid;
1274
1275         debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1276         g_assert (debugger_thread_handle);
1277 }
1278
1279 /*
1280  * Functions to decode protocol data
1281  */
1282
1283 static inline int
1284 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1285 {
1286         *endbuf = buf + 1;
1287         g_assert (*endbuf <= limit);
1288         return buf [0];
1289 }
1290
1291 static inline int
1292 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1293 {
1294         *endbuf = buf + 4;
1295         g_assert (*endbuf <= limit);
1296
1297         return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1298 }
1299
1300 static inline gint64
1301 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1302 {
1303         guint32 high = decode_int (buf, &buf, limit);
1304         guint32 low = decode_int (buf, &buf, limit);
1305
1306         *endbuf = buf;
1307
1308         return ((((guint64)high) << 32) | ((guint64)low));
1309 }
1310
1311 static inline int
1312 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1313 {
1314         return decode_int (buf, endbuf, limit);
1315 }
1316
1317 static inline char*
1318 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1319 {
1320         int len = decode_int (buf, &buf, limit);
1321         char *s;
1322
1323         s = g_malloc (len + 1);
1324         g_assert (s);
1325
1326         memcpy (s, buf, len);
1327         s [len] = '\0';
1328         buf += len;
1329         *endbuf = buf;
1330
1331         return s;
1332 }
1333
1334 /*
1335  * Functions to encode protocol data
1336  */
1337
1338 typedef struct {
1339         guint8 *buf, *p, *end;
1340 } Buffer;
1341
1342 static inline void
1343 buffer_init (Buffer *buf, int size)
1344 {
1345         buf->buf = g_malloc (size);
1346         buf->p = buf->buf;
1347         buf->end = buf->buf + size;
1348 }
1349
1350 static inline void
1351 buffer_make_room (Buffer *buf, int size)
1352 {
1353         if (buf->end - buf->p < size) {
1354                 int new_size = buf->end - buf->buf + size + 32;
1355                 guint8 *p = g_realloc (buf->buf, new_size);
1356                 size = buf->p - buf->buf;
1357                 buf->buf = p;
1358                 buf->p = p + size;
1359                 buf->end = buf->buf + new_size;
1360         }
1361 }
1362
1363 static inline void
1364 buffer_add_byte (Buffer *buf, guint8 val)
1365 {
1366         buffer_make_room (buf, 1);
1367         buf->p [0] = val;
1368         buf->p++;
1369 }
1370
1371 static inline void
1372 buffer_add_int (Buffer *buf, guint32 val)
1373 {
1374         buffer_make_room (buf, 4);
1375         buf->p [0] = (val >> 24) & 0xff;
1376         buf->p [1] = (val >> 16) & 0xff;
1377         buf->p [2] = (val >> 8) & 0xff;
1378         buf->p [3] = (val >> 0) & 0xff;
1379         buf->p += 4;
1380 }
1381
1382 static inline void
1383 buffer_add_long (Buffer *buf, guint64 l)
1384 {
1385         buffer_add_int (buf, (l >> 32) & 0xffffffff);
1386         buffer_add_int (buf, (l >> 0) & 0xffffffff);
1387 }
1388
1389 static inline void
1390 buffer_add_id (Buffer *buf, int id)
1391 {
1392         buffer_add_int (buf, (guint64)id);
1393 }
1394
1395 static inline void
1396 buffer_add_data (Buffer *buf, guint8 *data, int len)
1397 {
1398         buffer_make_room (buf, len);
1399         memcpy (buf->p, data, len);
1400         buf->p += len;
1401 }
1402
1403 static inline void
1404 buffer_add_string (Buffer *buf, const char *str)
1405 {
1406         int len;
1407
1408         if (str == NULL) {
1409                 buffer_add_int (buf, 0);
1410         } else {
1411                 len = strlen (str);
1412                 buffer_add_int (buf, len);
1413                 buffer_add_data (buf, (guint8*)str, len);
1414         }
1415 }
1416
1417 static inline void
1418 buffer_free (Buffer *buf)
1419 {
1420         g_free (buf->buf);
1421 }
1422
1423 static gboolean
1424 send_packet (int command_set, int command, Buffer *data)
1425 {
1426         Buffer buf;
1427         int len, id;
1428         gboolean res;
1429
1430         id = InterlockedIncrement (&packet_id);
1431
1432         len = data->p - data->buf + 11;
1433         buffer_init (&buf, len);
1434         buffer_add_int (&buf, len);
1435         buffer_add_int (&buf, id);
1436         buffer_add_byte (&buf, 0); /* flags */
1437         buffer_add_byte (&buf, command_set);
1438         buffer_add_byte (&buf, command);
1439         memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1440
1441         res = transport_send (buf.buf, len);
1442
1443         buffer_free (&buf);
1444
1445         return res;
1446 }
1447
1448 static gboolean
1449 send_reply_packet (int id, int error, Buffer *data)
1450 {
1451         Buffer buf;
1452         int len;
1453         gboolean res;
1454         
1455         len = data->p - data->buf + 11;
1456         buffer_init (&buf, len);
1457         buffer_add_int (&buf, len);
1458         buffer_add_int (&buf, id);
1459         buffer_add_byte (&buf, 0x80); /* flags */
1460         buffer_add_byte (&buf, (error >> 8) & 0xff);
1461         buffer_add_byte (&buf, error);
1462         memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1463
1464         res = transport_send (buf.buf, len);
1465
1466         buffer_free (&buf);
1467
1468         return res;
1469 }
1470
1471 /*
1472  * OBJECT IDS
1473  */
1474
1475 /*
1476  * Represents an object accessible by the debugger client.
1477  */
1478 typedef struct {
1479         /* Unique id used in the wire protocol to refer to objects */
1480         int id;
1481         /*
1482          * A weakref gc handle pointing to the object. The gc handle is used to 
1483          * detect if the object was garbage collected.
1484          */
1485         guint32 handle;
1486 } ObjRef;
1487
1488 /* Maps objid -> ObjRef */
1489 static GHashTable *objrefs;
1490
1491 static void
1492 free_objref (gpointer value)
1493 {
1494         ObjRef *o = value;
1495
1496         mono_gchandle_free (o->handle);
1497
1498         g_free (o);
1499 }
1500
1501 static void
1502 objrefs_init (void)
1503 {
1504         objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1505 }
1506
1507 static void
1508 objrefs_cleanup (void)
1509 {
1510         g_hash_table_destroy (objrefs);
1511         objrefs = NULL;
1512 }
1513
1514 static GHashTable *obj_to_objref;
1515
1516 /*
1517  * Return an ObjRef for OBJ.
1518  */
1519 static ObjRef*
1520 get_objref (MonoObject *obj)
1521 {
1522         ObjRef *ref;
1523         GSList *reflist = NULL, *l;
1524         int hash = 0;
1525
1526         if (obj == NULL)
1527                 return 0;
1528
1529         mono_loader_lock ();
1530
1531         if (!obj_to_objref)
1532                 obj_to_objref = g_hash_table_new (NULL, NULL);
1533         
1534         /* FIXME: The tables can grow indefinitely */
1535
1536         if (mono_gc_is_moving ()) {
1537                 /*
1538                  * Objects can move, so use a hash table mapping hash codes to lists of
1539                  * ObjRef structures.
1540                  */
1541                 hash = mono_object_hash (obj);
1542
1543                 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1544                 for (l = reflist; l; l = l->next) {
1545                         ref = l->data;
1546                         if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1547                                 mono_loader_unlock ();
1548                                 return ref;
1549                         }
1550                 }
1551         } else {
1552                 /* Use a hash table with masked pointers to internalize object references */
1553                 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1554                 /* ref might refer to a different object with the same addr which was GCd */
1555                 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1556                         mono_loader_unlock ();
1557                         return ref;
1558                 }
1559         }
1560
1561         ref = g_new0 (ObjRef, 1);
1562         ref->id = InterlockedIncrement (&objref_id);
1563         ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1564
1565         g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1566
1567         if (mono_gc_is_moving ()) {
1568                 reflist = g_slist_append (reflist, ref);
1569                 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1570         } else {
1571                 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1572         }
1573
1574         mono_loader_unlock ();
1575
1576         return ref;
1577 }
1578
1579 static inline int
1580 get_objid (MonoObject *obj)
1581 {
1582         return get_objref (obj)->id;
1583 }
1584
1585 /*
1586  * Set OBJ to the object identified by OBJID.
1587  * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1588  * collected.
1589  */
1590 static ErrorCode
1591 get_object_allow_null (int objid, MonoObject **obj)
1592 {
1593         ObjRef *ref;
1594
1595         if (objid == 0) {
1596                 *obj = NULL;
1597                 return 0;
1598         }
1599
1600         if (!objrefs)
1601                 return ERR_INVALID_OBJECT;
1602
1603         mono_loader_lock ();
1604
1605         ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1606
1607         if (ref) {
1608                 *obj = mono_gchandle_get_target (ref->handle);
1609                 mono_loader_unlock ();
1610                 if (!(*obj))
1611                         return ERR_INVALID_OBJECT;
1612                 return 0;
1613         } else {
1614                 mono_loader_unlock ();
1615                 return ERR_INVALID_OBJECT;
1616         }
1617 }
1618
1619 static ErrorCode
1620 get_object (int objid, MonoObject **obj)
1621 {
1622         int err = get_object_allow_null (objid, obj);
1623
1624         if (err)
1625                 return err;
1626         if (!(*obj))
1627                 return ERR_INVALID_OBJECT;
1628         return 0;
1629 }
1630
1631 static inline int
1632 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1633 {
1634         return decode_id (buf, endbuf, limit);
1635 }
1636
1637 static inline void
1638 buffer_add_objid (Buffer *buf, MonoObject *o)
1639 {
1640         buffer_add_id (buf, get_objid (o));
1641 }
1642
1643 /*
1644  * IDS
1645  */
1646
1647 typedef enum {
1648         ID_ASSEMBLY = 0,
1649         ID_MODULE = 1,
1650         ID_TYPE = 2,
1651         ID_METHOD = 3,
1652         ID_FIELD = 4,
1653         ID_DOMAIN = 5,
1654         ID_PROPERTY = 6,
1655         ID_NUM
1656 } IdType;
1657
1658 /*
1659  * Represents a runtime structure accessible to the debugger client
1660  */
1661 typedef struct {
1662         /* Unique id used in the wire protocol */
1663         int id;
1664         /* Domain of the runtime structure, NULL if the domain was unloaded */
1665         MonoDomain *domain;
1666         union {
1667                 gpointer val;
1668                 MonoClass *klass;
1669                 MonoMethod *method;
1670                 MonoImage *image;
1671                 MonoAssembly *assembly;
1672                 MonoClassField *field;
1673                 MonoDomain *domain;
1674                 MonoProperty *property;
1675         } data;
1676 } Id;
1677
1678 typedef struct {
1679         /* Maps runtime structure -> Id */
1680         GHashTable *val_to_id [ID_NUM];
1681         /* Classes whose class load event has been sent */
1682         GHashTable *loaded_classes;
1683 } AgentDomainInfo;
1684
1685 /* Maps id -> Id */
1686 static GPtrArray *ids [ID_NUM];
1687
1688 static void
1689 ids_init (void)
1690 {
1691         int i;
1692
1693         for (i = 0; i < ID_NUM; ++i)
1694                 ids [i] = g_ptr_array_new ();
1695 }
1696
1697 static void
1698 ids_cleanup (void)
1699 {
1700         int i, j;
1701
1702         for (i = 0; i < ID_NUM; ++i) {
1703                 if (ids [i]) {
1704                         for (j = 0; j < ids [i]->len; ++j)
1705                                 g_free (g_ptr_array_index (ids [i], j));
1706                         g_ptr_array_free (ids [i], TRUE);
1707                 }
1708                 ids [i] = NULL;
1709         }
1710 }
1711
1712 void
1713 mono_debugger_agent_free_domain_info (MonoDomain *domain)
1714 {
1715         AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
1716         int i, j;
1717
1718         if (info) {
1719                 for (i = 0; i < ID_NUM; ++i)
1720                         if (info->val_to_id [i])
1721                                 g_hash_table_destroy (info->val_to_id [i]);
1722                 g_hash_table_destroy (info->loaded_classes);
1723                 g_free (info);
1724         }
1725
1726         domain_jit_info (domain)->agent_info = NULL;
1727
1728         /* Clear ids referencing structures in the domain */
1729         for (i = 0; i < ID_NUM; ++i) {
1730                 if (ids [i]) {
1731                         for (j = 0; j < ids [i]->len; ++j) {
1732                                 Id *id = g_ptr_array_index (ids [i], j);
1733                                 if (id->domain == domain)
1734                                         id->domain = NULL;
1735                         }
1736                 }
1737         }
1738
1739         mono_loader_lock ();
1740         g_hash_table_remove (domains, domain);
1741         mono_loader_unlock ();
1742 }
1743
1744 /*
1745  * Called when deferred debugger session is attached, 
1746  * after the VM start event has been sent successfully
1747  */
1748 static void
1749 mono_debugger_agent_on_attach (void)
1750 {
1751         /* Emit load events for currently loaded appdomains, assemblies, and types */
1752         mono_loader_lock ();
1753         g_hash_table_foreach (domains, emit_appdomain_load, NULL);
1754         mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
1755         mono_assembly_foreach (emit_assembly_load, NULL);
1756         mono_loader_unlock ();
1757 }
1758
1759 static AgentDomainInfo*
1760 get_agent_domain_info (MonoDomain *domain)
1761 {
1762         AgentDomainInfo *info = NULL;
1763
1764         mono_domain_lock (domain);
1765
1766         info = domain_jit_info (domain)->agent_info;
1767         if (!info) {
1768                 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
1769                 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
1770         }
1771
1772         mono_domain_unlock (domain);
1773
1774         return info;
1775 }
1776
1777 static int
1778 get_id (MonoDomain *domain, IdType type, gpointer val)
1779 {
1780         Id *id;
1781         AgentDomainInfo *info;
1782
1783         if (val == NULL)
1784                 return 0;
1785
1786         mono_loader_lock ();
1787
1788         mono_domain_lock (domain);
1789
1790         info = get_agent_domain_info (domain);
1791
1792         if (info->val_to_id [type] == NULL)
1793                 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
1794
1795         id = g_hash_table_lookup (info->val_to_id [type], val);
1796         if (id) {
1797                 mono_domain_unlock (domain);
1798                 mono_loader_unlock ();
1799                 return id->id;
1800         }
1801
1802         id = g_new0 (Id, 1);
1803         /* Reserve id 0 */
1804         id->id = ids [type]->len + 1;
1805         id->domain = domain;
1806         id->data.val = val;
1807
1808         g_hash_table_insert (info->val_to_id [type], val, id);
1809
1810         mono_domain_unlock (domain);
1811
1812         g_ptr_array_add (ids [type], id);
1813
1814         mono_loader_unlock ();
1815
1816         return id->id;
1817 }
1818
1819 static inline gpointer
1820 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
1821 {
1822         Id *res;
1823
1824         int id = decode_id (buf, endbuf, limit);
1825
1826         *err = 0;
1827         if (domain)
1828                 *domain = NULL;
1829
1830         if (id == 0)
1831                 return NULL;
1832
1833         // FIXME: error handling
1834         mono_loader_lock ();
1835         g_assert (id > 0 && id <= ids [type]->len);
1836
1837         res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
1838         mono_loader_unlock ();
1839
1840         if (res->domain == NULL) {
1841                 *err = ERR_UNLOADED;
1842                 return NULL;
1843         }
1844
1845         if (domain)
1846                 *domain = res->domain;
1847
1848         return res->data.val;
1849 }
1850
1851 static inline void
1852 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
1853 {
1854         buffer_add_id (buf, get_id (domain, type, val));
1855 }
1856
1857 static inline MonoClass*
1858 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1859 {
1860         return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
1861 }
1862
1863 static inline MonoAssembly*
1864 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1865 {
1866         return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
1867 }
1868
1869 static inline MonoImage*
1870 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1871 {
1872         return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
1873 }
1874
1875 static inline MonoMethod*
1876 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1877 {
1878         return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
1879 }
1880
1881 static inline MonoClassField*
1882 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1883 {
1884         return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
1885 }
1886
1887 static inline MonoDomain*
1888 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1889 {
1890         return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
1891 }
1892
1893 static inline MonoProperty*
1894 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1895 {
1896         return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
1897 }
1898
1899 static inline void
1900 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
1901 {
1902         buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
1903 }
1904
1905 static inline void
1906 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
1907 {
1908         buffer_add_ptr_id (buf, domain, ID_METHOD, method);
1909 }
1910
1911 static inline void
1912 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
1913 {
1914         buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
1915 }
1916
1917 static inline void
1918 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
1919 {
1920         buffer_add_ptr_id (buf, domain, ID_MODULE, image);
1921 }
1922
1923 static inline void
1924 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
1925 {
1926         buffer_add_ptr_id (buf, domain, ID_FIELD, field);
1927 }
1928
1929 static inline void
1930 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
1931 {
1932         buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
1933 }
1934
1935 static inline void
1936 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
1937 {
1938         buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
1939 }
1940
1941 static void invoke_method (void);
1942
1943 /*
1944  * SUSPEND/RESUME
1945  */
1946
1947 /*
1948  * save_thread_context:
1949  *
1950  *   Set CTX as the current threads context which is used for computing stack traces.
1951  * This function is signal-safe.
1952  */
1953 static void
1954 save_thread_context (MonoContext *ctx)
1955 {
1956         DebuggerTlsData *tls;
1957
1958         tls = TlsGetValue (debugger_tls_id);
1959         g_assert (tls);
1960
1961         if (ctx) {
1962                 memcpy (&tls->ctx, ctx, sizeof (MonoContext));
1963         } else {
1964 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
1965                 MONO_INIT_CONTEXT_FROM_CURRENT (&tls->ctx);
1966 #else
1967                 MONO_INIT_CONTEXT_FROM_FUNC (&tls->ctx, save_thread_context);
1968 #endif
1969         }
1970
1971         tls->lmf = mono_get_lmf ();
1972         tls->domain = mono_domain_get ();
1973         tls->has_context = TRUE;
1974 }
1975
1976 /* The number of times the runtime is suspended */
1977 static gint32 suspend_count;
1978
1979 /* Number of threads suspended */
1980 /* 
1981  * If this is equal to the size of thread_to_tls, the runtime is considered
1982  * suspended.
1983  */
1984 static gint32 threads_suspend_count;
1985
1986 static mono_mutex_t suspend_mutex;
1987
1988 /* Cond variable used to wait for suspend_count becoming 0 */
1989 static mono_cond_t suspend_cond;
1990
1991 /* Semaphore used to wait for a thread becoming suspended */
1992 static MonoSemType suspend_sem;
1993
1994 static void
1995 suspend_init (void)
1996 {
1997         mono_mutex_init (&suspend_mutex, NULL);
1998         mono_cond_init (&suspend_cond, NULL);   
1999         MONO_SEM_INIT (&suspend_sem, 0);
2000 }
2001
2002 typedef struct
2003 {
2004         StackFrameInfo last_frame;
2005         gboolean last_frame_set;
2006         MonoContext ctx;
2007         gpointer lmf;
2008 } GetLastFrameUserData;
2009
2010 static gboolean
2011 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2012 {
2013         GetLastFrameUserData *data = user_data;
2014
2015         if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2016                 return FALSE;
2017
2018         if (!data->last_frame_set) {
2019                 /* Store the last frame */
2020                 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2021                 data->last_frame_set = TRUE;
2022                 return FALSE;
2023         } else {
2024                 /* Store the context/lmf for the frame above the last frame */
2025                 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2026                 data->lmf = info->lmf;
2027
2028                 return TRUE;
2029         }
2030 }
2031
2032 /*
2033  * mono_debugger_agent_thread_interrupt:
2034  *
2035  *   Called by the abort signal handler.
2036  * Should be signal safe.
2037  */
2038 gboolean
2039 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2040 {
2041         DebuggerTlsData *tls;
2042
2043         if (!inited)
2044                 return FALSE;
2045
2046         tls = TlsGetValue (debugger_tls_id);
2047         if (!tls)
2048                 return FALSE;
2049
2050         /*
2051          * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2052          * guarantee the signal handler will be called that many times.  Instead of tracking
2053          * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2054          * has been requested that hasn't been handled yet, otherwise we can have threads
2055          * refuse to die when VM_EXIT is called
2056          */
2057 #if defined(__APPLE__)
2058         if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2059                 return FALSE;
2060 #else
2061         /*
2062          * We use interrupt_count to determine whenever this interrupt should be processed
2063          * by us or the normal interrupt processing code in the signal handler.
2064          * There is no race here with notify_thread (), since the signal is sent after
2065          * incrementing interrupt_count.
2066          */
2067         if (tls->interrupt_count == 0)
2068                 return FALSE;
2069
2070         InterlockedDecrement (&tls->interrupt_count);
2071 #endif
2072
2073         // FIXME: Races when the thread leaves managed code before hitting a single step
2074         // event.
2075
2076         if (ji) {
2077                 /* Running managed code, will be suspended by the single step code */
2078                 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)GetCurrentThreadId (), ji->method->name, mono_arch_ip_from_context (sigctx)));
2079                 return TRUE;
2080         } else {
2081                 /* 
2082                  * Running native code, will be suspended when it returns to/enters 
2083                  * managed code. Treat it as already suspended.
2084                  * This might interrupt the code in process_single_step_inner (), we use the
2085                  * tls->suspending flag to avoid races when that happens.
2086                  */
2087                 if (!tls->suspended && !tls->suspending) {
2088                         MonoContext ctx;
2089                         GetLastFrameUserData data;
2090
2091                         // FIXME: printf is not signal safe, but this is only used during
2092                         // debugger debugging
2093                         if (sigctx)
2094                                 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)GetCurrentThreadId (), mono_arch_ip_from_context (sigctx)));
2095                         //save_thread_context (&ctx);
2096
2097                         if (!tls->thread)
2098                                 /* Already terminated */
2099                                 return TRUE;
2100
2101                         /*
2102                          * We are in a difficult position: we want to be able to provide stack
2103                          * traces for this thread, but we can't use the current ctx+lmf, since
2104                          * the thread is still running, so it might return to managed code,
2105                          * making these invalid.
2106                          * So we start a stack walk and save the first frame, along with the
2107                          * parent frame's ctx+lmf. This (hopefully) works because the thread will be 
2108                          * suspended when it returns to managed code, so the parent's ctx should
2109                          * remain valid.
2110                          */
2111                         data.last_frame_set = FALSE;
2112                         if (sigctx) {
2113                                 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2114                                 mono_walk_stack (get_last_frame, mono_domain_get (), &ctx, MONO_UNWIND_DEFAULT, tls->thread, mono_get_lmf (), &data);
2115                         }
2116                         if (data.last_frame_set) {
2117                                 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2118                                 memcpy (&tls->async_ctx, &data.ctx, sizeof (MonoContext));
2119                                 tls->async_lmf = data.lmf;
2120                                 tls->has_async_ctx = TRUE;
2121                                 tls->domain = mono_domain_get ();
2122                                 memcpy (&tls->ctx, &ctx, sizeof (MonoContext));
2123                         } else {
2124                                 tls->has_async_ctx = FALSE;
2125                         }
2126
2127                         mono_memory_barrier ();
2128
2129                         tls->suspended = TRUE;
2130                         MONO_SEM_POST (&suspend_sem);
2131                 }
2132                 return TRUE;
2133         }
2134 }
2135
2136 #ifdef HOST_WIN32
2137 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2138 {
2139         //DebugBreak ();
2140         mono_debugger_agent_thread_interrupt (NULL, NULL);
2141 }
2142 #endif /* HOST_WIN32 */
2143
2144 /*
2145  * reset_native_thread_suspend_state:
2146  * 
2147  *   Reset the suspended flag on native threads
2148  */
2149 static void
2150 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2151 {
2152         DebuggerTlsData *tls = value;
2153
2154         if (!tls->really_suspended && tls->suspended)
2155                 tls->suspended = FALSE;
2156 }
2157
2158 /*
2159  * notify_thread:
2160  *
2161  *   Notify a thread that it needs to suspend.
2162  */
2163 static void
2164 notify_thread (gpointer key, gpointer value, gpointer user_data)
2165 {
2166         MonoInternalThread *thread = key;
2167         DebuggerTlsData *tls = value;
2168         gsize tid = thread->tid;
2169
2170         if (GetCurrentThreadId () == tid || tls->terminated)
2171                 return;
2172
2173         DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2174
2175         /*
2176          * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2177          * guarantee the signal handler will be called that many times.  Instead of tracking
2178          * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2179          * has been requested that hasn't been handled yet, otherwise we can have threads
2180          * refuse to die when VM_EXIT is called
2181          */
2182 #if defined(__APPLE__)
2183         if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2184                 return;
2185 #else
2186         /*
2187          * Maybe we could use the normal interrupt infrastructure, but that does a lot
2188          * of things like breaking waits etc. which we don't want.
2189          */
2190         InterlockedIncrement (&tls->interrupt_count);
2191 #endif
2192
2193         /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2194 #ifdef HOST_WIN32
2195         QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2196 #else
2197         mono_thread_kill (thread, mono_thread_get_abort_signal ());
2198 #endif
2199 }
2200
2201 static void
2202 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2203 {
2204         guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2205         MonoJitInfo *ji;
2206
2207         if (mono_loader_lock_is_owned_by_self ()) {
2208                 /*
2209                  * Shortcut for the check in suspend_current (). This speeds up processing
2210                  * when executing long running code inside the loader lock, i.e. assembly load
2211                  * hooks.
2212                  */
2213                 return;
2214         }
2215
2216         if (debugger_thread_id == GetCurrentThreadId ())
2217                 return;
2218
2219         /* Prevent races with mono_debugger_agent_thread_interrupt () */
2220         if (suspend_count - tls->resume_count > 0)
2221                 tls->suspending = TRUE;
2222
2223         DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2224
2225         if (suspend_count - tls->resume_count == 0) {
2226                 /* 
2227                  * We are executing a single threaded invoke but the single step for 
2228                  * suspending is still active.
2229                  * FIXME: This slows down single threaded invokes.
2230                  */
2231                 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2232                 return;
2233         }
2234
2235         ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2236
2237         /* Can't suspend in these methods */
2238         if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2239                 return;
2240
2241         save_thread_context (ctx);
2242
2243         suspend_current ();
2244 }
2245
2246 /*
2247  * suspend_vm:
2248  *
2249  * Increase the suspend count of the VM. While the suspend count is greater 
2250  * than 0, runtime threads are suspended at certain points during execution.
2251  */
2252 static void
2253 suspend_vm (void)
2254 {
2255         mono_loader_lock ();
2256
2257         mono_mutex_lock (&suspend_mutex);
2258
2259         suspend_count ++;
2260
2261         DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2262
2263         if (suspend_count == 1) {
2264                 // FIXME: Is it safe to call this inside the lock ?
2265                 start_single_stepping ();
2266                 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2267         }
2268
2269         mono_mutex_unlock (&suspend_mutex);
2270
2271         mono_loader_unlock ();
2272 }
2273
2274 /*
2275  * resume_vm:
2276  *
2277  * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2278  * are resumed.
2279  */
2280 static void
2281 resume_vm (void)
2282 {
2283         int err;
2284
2285         g_assert (debugger_thread_id == GetCurrentThreadId ());
2286
2287         mono_loader_lock ();
2288
2289         mono_mutex_lock (&suspend_mutex);
2290
2291         g_assert (suspend_count > 0);
2292         suspend_count --;
2293
2294         DEBUG(1, fprintf (log_file, "[%p] Resuming vm...\n", (gpointer)GetCurrentThreadId ()));
2295
2296         if (suspend_count == 0) {
2297                 // FIXME: Is it safe to call this inside the lock ?
2298                 stop_single_stepping ();
2299                 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2300         }
2301
2302         /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2303         err = mono_cond_broadcast (&suspend_cond);
2304         g_assert (err == 0);
2305
2306         mono_mutex_unlock (&suspend_mutex);
2307         //g_assert (err == 0);
2308
2309         mono_loader_unlock ();
2310 }
2311
2312 /*
2313  * resume_thread:
2314  *
2315  *   Resume just one thread.
2316  */
2317 static void
2318 resume_thread (MonoInternalThread *thread)
2319 {
2320         int err;
2321         DebuggerTlsData *tls;
2322
2323         g_assert (debugger_thread_id == GetCurrentThreadId ());
2324
2325         mono_loader_lock ();
2326
2327         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2328         g_assert (tls);
2329         
2330         mono_mutex_lock (&suspend_mutex);
2331
2332         g_assert (suspend_count > 0);
2333
2334         DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2335
2336         tls->resume_count += suspend_count;
2337
2338         /* 
2339          * Signal suspend_count without decreasing suspend_count, the threads will wake up
2340          * but only the one whose resume_count field is > 0 will be resumed.
2341          */
2342         err = mono_cond_broadcast (&suspend_cond);
2343         g_assert (err == 0);
2344
2345         mono_mutex_unlock (&suspend_mutex);
2346         //g_assert (err == 0);
2347
2348         mono_loader_unlock ();
2349 }
2350
2351 static void
2352 invalidate_frames (DebuggerTlsData *tls)
2353 {
2354         int i;
2355
2356         if (!tls)
2357                 tls = TlsGetValue (debugger_tls_id);
2358         g_assert (tls);
2359
2360         for (i = 0; i < tls->frame_count; ++i) {
2361                 if (tls->frames [i]->jit)
2362                         mono_debug_free_method_jit_info (tls->frames [i]->jit);
2363                 g_free (tls->frames [i]);
2364         }
2365         g_free (tls->frames);
2366         tls->frame_count = 0;
2367         tls->frames = NULL;
2368 }
2369
2370 /*
2371  * suspend_current:
2372  *
2373  *   Suspend the current thread until the runtime is resumed. If the thread has a 
2374  * pending invoke, then the invoke is executed before this function returns. 
2375  */
2376 static void
2377 suspend_current (void)
2378 {
2379         int err;
2380         DebuggerTlsData *tls;
2381
2382         g_assert (debugger_thread_id != GetCurrentThreadId ());
2383
2384         if (mono_loader_lock_is_owned_by_self ()) {
2385                 /*
2386                  * If we own the loader mutex, can't suspend until we release it, since the
2387                  * whole runtime can deadlock otherwise.
2388                  */
2389                 return;
2390         }
2391
2392         tls = TlsGetValue (debugger_tls_id);
2393         g_assert (tls);
2394
2395         mono_mutex_lock (&suspend_mutex);
2396
2397         tls->suspending = FALSE;
2398         tls->really_suspended = TRUE;
2399
2400         if (!tls->suspended) {
2401                 tls->suspended = TRUE;
2402                 MONO_SEM_POST (&suspend_sem);
2403         }
2404
2405         DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2406
2407         while (suspend_count - tls->resume_count > 0) {
2408 #ifdef HOST_WIN32
2409                 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2410                 {
2411                         mono_mutex_unlock (&suspend_mutex);
2412                         Sleep(1);
2413                         mono_mutex_lock (&suspend_mutex);
2414                 }
2415                 else
2416                 {
2417                 }
2418 #else
2419                 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2420                 g_assert (err == 0);
2421 #endif
2422         }
2423
2424         tls->suspended = FALSE;
2425         tls->really_suspended = FALSE;
2426
2427         threads_suspend_count --;
2428
2429         mono_mutex_unlock (&suspend_mutex);
2430
2431         DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2432
2433         if (tls->pending_invoke) {
2434                 /* Save the original context */
2435                 tls->pending_invoke->has_ctx = TRUE;
2436                 memcpy (&tls->pending_invoke->ctx, &tls->ctx, sizeof (MonoContext));
2437
2438                 invoke_method ();
2439         }
2440
2441         /* The frame info becomes invalid after a resume */
2442         tls->has_context = FALSE;
2443         tls->has_async_ctx = FALSE;
2444         invalidate_frames (NULL);
2445 }
2446
2447 static void
2448 count_thread (gpointer key, gpointer value, gpointer user_data)
2449 {
2450         DebuggerTlsData *tls = value;
2451
2452         if (!tls->suspended && !tls->terminated)
2453                 *(int*)user_data = *(int*)user_data + 1;
2454 }
2455
2456 static int
2457 count_threads_to_wait_for (void)
2458 {
2459         int count = 0;
2460
2461         mono_loader_lock ();
2462         mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2463         mono_loader_unlock ();
2464
2465         return count;
2466 }       
2467
2468 /*
2469  * wait_for_suspend:
2470  *
2471  *   Wait until the runtime is completely suspended.
2472  */
2473 static void
2474 wait_for_suspend (void)
2475 {
2476         int nthreads, nwait, err;
2477         gboolean waited = FALSE;
2478
2479         // FIXME: Threads starting/stopping ?
2480         mono_loader_lock ();
2481         nthreads = mono_g_hash_table_size (thread_to_tls);
2482         mono_loader_unlock ();
2483
2484         while (TRUE) {
2485                 nwait = count_threads_to_wait_for ();
2486                 if (nwait) {
2487                         DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2488                         err = MONO_SEM_WAIT (&suspend_sem);
2489                         g_assert (err == 0);
2490                         waited = TRUE;
2491                 } else {
2492                         break;
2493                 }
2494         }
2495
2496         if (waited)
2497                 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2498 }
2499
2500 /*
2501  * is_suspended:
2502  *
2503  *   Return whenever the runtime is suspended.
2504  */
2505 static gboolean
2506 is_suspended (void)
2507 {
2508         return count_threads_to_wait_for () == 0;
2509 }
2510
2511 /*
2512  * find_seq_point_for_native_offset:
2513  *
2514  *   Find the sequence point corresponding to the native offset NATIVE_OFFSET, which
2515  * should be the location of a sequence point.
2516  */
2517 static SeqPoint*
2518 find_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2519 {
2520         MonoSeqPointInfo *seq_points;
2521         int i;
2522
2523         mono_domain_lock (domain);
2524         seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2525         mono_domain_unlock (domain);
2526         g_assert (seq_points);
2527
2528         *info = seq_points;
2529
2530         for (i = 0; i < seq_points->len; ++i) {
2531                 if (seq_points->seq_points [i].native_offset == native_offset)
2532                         return &seq_points->seq_points [i];
2533         }
2534
2535         return NULL;
2536 }
2537
2538 /*
2539  * find_next_seq_point_for_native_offset:
2540  *
2541  *   Find the first sequence point after NATIVE_OFFSET.
2542  */
2543 static SeqPoint*
2544 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2545 {
2546         MonoSeqPointInfo *seq_points;
2547         int i;
2548
2549         mono_domain_lock (domain);
2550         seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2551         mono_domain_unlock (domain);
2552         g_assert (seq_points);
2553
2554         *info = seq_points;
2555
2556         for (i = 0; i < seq_points->len; ++i) {
2557                 if (seq_points->seq_points [i].native_offset >= native_offset)
2558                         return &seq_points->seq_points [i];
2559         }
2560
2561         return NULL;
2562 }
2563
2564 /*
2565  * find_prev_seq_point_for_native_offset:
2566  *
2567  *   Find the first sequence point before NATIVE_OFFSET.
2568  */
2569 static SeqPoint*
2570 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2571 {
2572         MonoSeqPointInfo *seq_points;
2573         int i;
2574
2575         mono_domain_lock (domain);
2576         seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2577         mono_domain_unlock (domain);
2578         g_assert (seq_points);
2579
2580         *info = seq_points;
2581
2582         for (i = seq_points->len - 1; i >= 0; --i) {
2583                 if (seq_points->seq_points [i].native_offset <= native_offset)
2584                         return &seq_points->seq_points [i];
2585         }
2586
2587         return NULL;
2588 }
2589
2590 /*
2591  * find_seq_point:
2592  *
2593  *   Find the sequence point corresponding to the IL offset IL_OFFSET, which
2594  * should be the location of a sequence point.
2595  */
2596 static SeqPoint*
2597 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
2598 {
2599         MonoSeqPointInfo *seq_points;
2600         int i;
2601
2602         mono_domain_lock (domain);
2603         seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2604         mono_domain_unlock (domain);
2605         g_assert (seq_points);
2606
2607         *info = seq_points;
2608
2609         for (i = 0; i < seq_points->len; ++i) {
2610                 if (seq_points->seq_points [i].il_offset == il_offset)
2611                         return &seq_points->seq_points [i];
2612         }
2613
2614         return NULL;
2615 }
2616
2617 /*
2618  * compute_il_offset:
2619  *
2620  *    Compute the IL offset corresponding to NATIVE_OFFSET, which should be
2621  * a location of a sequence point.
2622  * We use this function instead of mono_debug_il_offset_from_address () etc,
2623  * which doesn't seem to work in a lot of cases.
2624  */
2625 static gint32
2626 compute_il_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset)
2627 {
2628         MonoSeqPointInfo *seq_points;
2629         int i, last_il_offset, seq_il_offset, seq_native_offset;
2630
2631         mono_domain_lock (domain);
2632         seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2633         mono_domain_unlock (domain);
2634         g_assert (seq_points);
2635
2636         last_il_offset = -1;
2637
2638         /* Find the sequence point */
2639         for (i = 0; i < seq_points->len; ++i) {
2640                 seq_il_offset = seq_points->seq_points [i].il_offset;
2641                 seq_native_offset = seq_points->seq_points [i].native_offset;
2642
2643                 if (seq_native_offset > native_offset)
2644                         break;
2645                 last_il_offset = seq_il_offset;
2646         }
2647
2648         return last_il_offset;
2649 }
2650
2651 typedef struct {
2652         DebuggerTlsData *tls;
2653         GSList *frames;
2654 } ComputeFramesUserData;
2655
2656 static gboolean
2657 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2658 {
2659         ComputeFramesUserData *ud = user_data;
2660         StackFrame *frame;
2661         MonoMethod *method, *actual_method;
2662
2663         if (info->type != FRAME_TYPE_MANAGED) {
2664                 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
2665                         /* Mark the last frame as an invoke frame */
2666                         if (ud->frames)
2667                                 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
2668                 }
2669                 return FALSE;
2670         }
2671
2672         if (info->ji)
2673                 method = info->ji->method;
2674         else
2675                 method = info->method;
2676         actual_method = info->actual_method;
2677
2678         if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD))
2679                 return FALSE;
2680
2681         if (info->il_offset == -1) {
2682                 /* Can't use compute_il_offset () since ip doesn't point precisely at at a seq point */
2683                 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
2684         }
2685
2686         DEBUG (1, fprintf (log_file, "\tFrame: %s:%x(%x) %d\n", mono_method_full_name (method, TRUE), info->il_offset, info->native_offset, info->managed));
2687
2688         if (!info->managed && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD) {
2689                 /*
2690                  * mono_arch_find_jit_info () returns the context stored in the LMF for 
2691                  * native frames, but it should unwind once. This is why we have duplicate
2692                  * frames on the stack sometimes.
2693                  * !managed also seems to be set for dynamic methods.
2694                  */
2695                 return FALSE;
2696         }
2697
2698         frame = g_new0 (StackFrame, 1);
2699         frame->method = method;
2700         frame->actual_method = actual_method;
2701         frame->il_offset = info->il_offset;
2702         frame->native_offset = info->native_offset;
2703         if (ctx) {
2704                 frame->ctx = *ctx;
2705                 frame->has_ctx = TRUE;
2706         }
2707         frame->domain = info->domain;
2708
2709         ud->frames = g_slist_append (ud->frames, frame);
2710
2711         return FALSE;
2712 }
2713
2714 static gboolean
2715 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2716 {
2717         ComputeFramesUserData *ud = user_data;
2718
2719         /*
2720          * 'tls->filter_ctx' is the location of the throw site.
2721          *
2722          * mono_walk_stack() will never actually hit the throw site, but unwind
2723          * directly from the filter to the call site; we abort stack unwinding here
2724          * once this happens and resume from the throw site.
2725          */
2726
2727         if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_ctx))
2728                 return TRUE;
2729
2730         return process_frame (info, ctx, user_data);
2731 }
2732
2733 static void
2734 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
2735 {
2736         ComputeFramesUserData user_data;
2737         GSList *tmp;
2738         int i, findex, new_frame_count;
2739         StackFrame **new_frames, *f;
2740
2741         // FIXME: Locking on tls
2742         if (tls->frames && tls->frames_up_to_date)
2743                 return;
2744
2745         DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
2746
2747         user_data.tls = tls;
2748         user_data.frames = NULL;
2749         if (tls->terminated) {
2750                 tls->frame_count = 0;
2751                 return;
2752         } if (!tls->really_suspended && tls->has_async_ctx) {
2753                 /* Have to use the state saved by the signal handler */
2754                 process_frame (&tls->async_last_frame, NULL, &user_data);
2755                 mono_walk_stack (process_frame, tls->domain, &tls->async_ctx, MONO_UNWIND_DEFAULT, thread, tls->async_lmf, &user_data);
2756         } else if (tls->has_filter_ctx) {
2757                 /*
2758                  * We are inside an exception filter.
2759                  *
2760                  * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
2761                  */
2762                 if (tls->has_context)
2763                         mono_walk_stack (process_filter_frame, tls->domain, &tls->ctx, MONO_UNWIND_DEFAULT, thread, tls->lmf, &user_data);
2764                 /*
2765                  * After that, we resume unwinding from the location where the exception has been thrown.
2766                  */
2767                 mono_walk_stack (process_frame, tls->domain, &tls->filter_ctx, MONO_UNWIND_DEFAULT, thread, tls->filter_lmf, &user_data);
2768         } else if (tls->has_context) {
2769                 mono_walk_stack (process_frame, tls->domain, &tls->ctx, MONO_UNWIND_DEFAULT, thread, tls->lmf, &user_data);
2770         } else {
2771                 // FIXME:
2772                 tls->frame_count = 0;
2773                 return;
2774         }
2775
2776         new_frame_count = g_slist_length (user_data.frames);
2777         new_frames = g_new0 (StackFrame*, new_frame_count);
2778         findex = 0;
2779         for (tmp = user_data.frames; tmp; tmp = tmp->next) {
2780                 f = tmp->data;
2781
2782                 /* 
2783                  * Reuse the id for already existing stack frames, so invokes don't invalidate
2784                  * the still valid stack frames.
2785                  */
2786                 for (i = 0; i < tls->frame_count; ++i) {
2787                         if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
2788                                 f->id = tls->frames [i]->id;
2789                                 break;
2790                         }
2791                 }
2792
2793                 if (i >= tls->frame_count)
2794                         f->id = InterlockedIncrement (&frame_id);
2795
2796                 new_frames [findex ++] = f;
2797         }
2798
2799         g_slist_free (user_data.frames);
2800
2801         invalidate_frames (tls);
2802
2803         tls->frames = new_frames;
2804         tls->frame_count = new_frame_count;
2805         tls->frames_up_to_date = TRUE;
2806 }
2807
2808 /*
2809  * GHFunc to emit an appdomain creation event
2810  * @param key Don't care
2811  * @param value A loaded appdomain
2812  * @param user_data Don't care
2813  */
2814 static void
2815 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
2816 {
2817         process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
2818         g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
2819 }
2820
2821 /*
2822  * GHFunc to emit a thread start event
2823  * @param key A thread id
2824  * @param value A thread object
2825  * @param user_data Don't care
2826  */
2827 static void
2828 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
2829 {
2830         if (GPOINTER_TO_INT (key) != debugger_thread_id)
2831                 process_profiler_event (EVENT_KIND_THREAD_START, value);
2832 }
2833
2834 /*
2835  * GFunc to emit an assembly load event
2836  * @param value A loaded assembly
2837  * @param user_data Don't care
2838  */
2839 static void
2840 emit_assembly_load (gpointer value, gpointer user_data)
2841 {
2842         process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
2843 }
2844
2845 /*
2846  * GFunc to emit a type load event
2847  * @param value A loaded type
2848  * @param user_data Don't care
2849  */
2850 static void
2851 emit_type_load (gpointer key, gpointer value, gpointer user_data)
2852 {
2853         process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
2854 }
2855
2856
2857 /*
2858  * EVENT HANDLING
2859  */
2860
2861 /*
2862  * create_event_list:
2863  *
2864  *   Return a list of event request ids matching EVENT, starting from REQS, which
2865  * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
2866  * policy.
2867  * We return request ids, instead of requests, to simplify threading, since 
2868  * requests could be deleted anytime when the loader lock is not held.
2869  * LOCKING: Assumes the loader lock is held.
2870  */
2871 static GSList*
2872 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
2873 {
2874         int i, j;
2875         GSList *events = NULL;
2876
2877         *suspend_policy = SUSPEND_POLICY_NONE;
2878
2879         if (!reqs)
2880                 reqs = event_requests;
2881
2882         if (!reqs)
2883                 return NULL;
2884
2885         for (i = 0; i < reqs->len; ++i) {
2886                 EventRequest *req = g_ptr_array_index (reqs, i);
2887                 if (req->event_kind == event) {
2888                         gboolean filtered = FALSE;
2889
2890                         /* Apply filters */
2891                         for (j = 0; j < req->nmodifiers; ++j) {
2892                                 Modifier *mod = &req->modifiers [j];
2893
2894                                 if (mod->kind == MOD_KIND_COUNT) {
2895                                         filtered = TRUE;
2896                                         if (mod->data.count > 0) {
2897                                                 if (mod->data.count > 0) {
2898                                                         mod->data.count --;
2899                                                         if (mod->data.count == 0)
2900                                                                 filtered = FALSE;
2901                                                 }
2902                                         }
2903                                 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
2904                                         if (mod->data.thread != mono_thread_internal_current ())
2905                                                 filtered = TRUE;
2906                                 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
2907                                         if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
2908                                                 filtered = TRUE;
2909                                         if (ei->caught && !mod->caught)
2910                                                 filtered = TRUE;
2911                                         if (!ei->caught && !mod->uncaught)
2912                                                 filtered = TRUE;
2913                                 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
2914                                         int k;
2915                                         gboolean found = FALSE;
2916                                         MonoAssembly **assemblies = mod->data.assemblies;
2917
2918                                         if (assemblies) {
2919                                                 for (k = 0; assemblies [k]; ++k)
2920                                                         if (assemblies [k] == ji->method->klass->image->assembly)
2921                                                                 found = TRUE;
2922                                         }
2923                                         if (!found)
2924                                                 filtered = TRUE;
2925                                 }
2926                         }
2927
2928                         if (!filtered) {
2929                                 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
2930                                 events = g_slist_append (events, GINT_TO_POINTER (req->id));
2931                         }
2932                 }
2933         }
2934
2935         /* Send a VM START/DEATH event by default */
2936         if (event == EVENT_KIND_VM_START)
2937                 events = g_slist_append (events, GINT_TO_POINTER (0));
2938         if (event == EVENT_KIND_VM_DEATH)
2939                 events = g_slist_append (events, GINT_TO_POINTER (0));
2940
2941         return events;
2942 }
2943
2944 static G_GNUC_UNUSED const char*
2945 event_to_string (EventKind event)
2946 {
2947         switch (event) {
2948         case EVENT_KIND_VM_START: return "VM_START";
2949         case EVENT_KIND_VM_DEATH: return "VM_DEATH";
2950         case EVENT_KIND_THREAD_START: return "THREAD_START";
2951         case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
2952         case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
2953         case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
2954         case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
2955         case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
2956         case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
2957         case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
2958         case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
2959         case EVENT_KIND_STEP: return "STEP";
2960         case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
2961         case EVENT_KIND_EXCEPTION: return "EXCEPTION";
2962         default:
2963                 g_assert_not_reached ();
2964         }
2965 }
2966
2967 /*
2968  * process_event:
2969  *
2970  *   Send an event to the client, suspending the vm if needed.
2971  * LOCKING: Since this can suspend the calling thread, no locks should be held
2972  * by the caller.
2973  * The EVENTS list is freed by this function.
2974  */
2975 static void
2976 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
2977 {
2978         Buffer buf;
2979         GSList *l;
2980         MonoDomain *domain = mono_domain_get ();
2981         MonoThread *thread = NULL;
2982         gboolean send_success = FALSE;
2983
2984         if (!inited) {
2985                 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
2986                 return;
2987         }
2988
2989         if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
2990                 // FIXME: We miss those events
2991                 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
2992                 return;
2993         }
2994
2995         if (vm_death_event_sent) {
2996                 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
2997                 return;
2998         }
2999
3000         if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3001                 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3002                 return;
3003         }
3004
3005         if (disconnected) {
3006                 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3007                 return;
3008         }
3009
3010         if (events == NULL)
3011                 return;
3012         
3013         if (agent_config.defer) {
3014                 /* Make sure the thread id is always set when doing deferred debugging */
3015                 if (debugger_thread_id == GetCurrentThreadId ())
3016                         thread = mono_thread_get_main ();
3017                 else thread = mono_thread_current ();
3018         } else {
3019                 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3020                         // FIXME: Send these with a NULL thread, don't suspend the current thread
3021                         return;
3022         }
3023
3024         buffer_init (&buf, 128);
3025         buffer_add_byte (&buf, suspend_policy);
3026         buffer_add_int (&buf, g_slist_length (events)); // n of events
3027
3028         for (l = events; l; l = l->next) {
3029                 buffer_add_byte (&buf, event); // event kind
3030                 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3031
3032                 if (!thread)
3033                         thread = mono_thread_current ();
3034
3035                 if (event == EVENT_KIND_VM_START && arg != NULL)
3036                         thread = arg;
3037
3038                 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3039
3040                 switch (event) {
3041                 case EVENT_KIND_THREAD_START:
3042                 case EVENT_KIND_THREAD_DEATH:
3043                         break;
3044                 case EVENT_KIND_APPDOMAIN_CREATE:
3045                 case EVENT_KIND_APPDOMAIN_UNLOAD:
3046                         buffer_add_domainid (&buf, arg);
3047                         break;
3048                 case EVENT_KIND_METHOD_ENTRY:
3049                 case EVENT_KIND_METHOD_EXIT:
3050                         buffer_add_methodid (&buf, domain, arg);
3051                         break;
3052                 case EVENT_KIND_ASSEMBLY_LOAD:
3053                 case EVENT_KIND_ASSEMBLY_UNLOAD:
3054                         buffer_add_assemblyid (&buf, domain, arg);
3055                         break;
3056                 case EVENT_KIND_TYPE_LOAD:
3057                         buffer_add_typeid (&buf, domain, arg);
3058                         break;
3059                 case EVENT_KIND_BREAKPOINT:
3060                 case EVENT_KIND_STEP:
3061                         buffer_add_methodid (&buf, domain, arg);
3062                         buffer_add_long (&buf, il_offset);
3063                         break;
3064                 case EVENT_KIND_VM_START:
3065                         buffer_add_domainid (&buf, mono_get_root_domain ());
3066                         break;
3067                 case EVENT_KIND_VM_DEATH:
3068                         break;
3069                 case EVENT_KIND_EXCEPTION: {
3070                         EventInfo *ei = arg;
3071                         buffer_add_objid (&buf, ei->exc);
3072                         break;
3073                 }
3074                 default:
3075                         g_assert_not_reached ();
3076                 }
3077         }
3078
3079         if (event == EVENT_KIND_VM_START) {
3080                 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3081                 if (!agent_config.defer)
3082                         start_debugger_thread ();
3083         }
3084    
3085         if (event == EVENT_KIND_VM_DEATH) {
3086                 vm_death_event_sent = TRUE;
3087                 suspend_policy = SUSPEND_POLICY_NONE;
3088         }
3089
3090         if (mono_runtime_is_shutting_down ())
3091                 suspend_policy = SUSPEND_POLICY_NONE;
3092
3093         if (suspend_policy != SUSPEND_POLICY_NONE) {
3094                 /* 
3095                  * Save the thread context and start suspending before sending the packet,
3096                  * since we could be receiving the resume request before send_packet ()
3097                  * returns.
3098                  */
3099                 save_thread_context (ctx);
3100                 suspend_vm ();
3101         }
3102
3103         send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3104
3105         buffer_free (&buf);
3106
3107         g_slist_free (events);
3108         events = NULL;
3109
3110         if (!send_success) {
3111                 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3112                 return;
3113         }
3114         
3115         if (event == EVENT_KIND_VM_START) {
3116                 vm_start_event_sent = TRUE;
3117                 if (agent_config.defer)
3118                         mono_debugger_agent_on_attach ();
3119         }
3120         
3121         DEBUG (1, fprintf (log_file, "[%p] Sent event %s, suspend=%d.\n", (gpointer)GetCurrentThreadId (), event_to_string (event), suspend_policy));
3122
3123
3124         switch (suspend_policy) {
3125         case SUSPEND_POLICY_NONE:
3126                 break;
3127         case SUSPEND_POLICY_ALL:
3128                 suspend_current ();
3129                 break;
3130         case SUSPEND_POLICY_EVENT_THREAD:
3131                 NOT_IMPLEMENTED;
3132                 break;
3133         default:
3134                 g_assert_not_reached ();
3135         }
3136 }
3137
3138 static void
3139 process_profiler_event (EventKind event, gpointer arg)
3140 {
3141         int suspend_policy;
3142         GSList *events;
3143
3144         mono_loader_lock ();
3145         events = create_event_list (event, NULL, NULL, NULL, &suspend_policy);
3146         mono_loader_unlock ();
3147
3148         process_event (event, arg, 0, NULL, events, suspend_policy);
3149 }
3150
3151 static void
3152 runtime_initialized (MonoProfiler *prof)
3153 {
3154         process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3155         if (agent_config.defer)
3156                 start_debugger_thread ();
3157 }
3158
3159 static void
3160 runtime_shutdown (MonoProfiler *prof)
3161 {
3162         process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3163
3164         mono_debugger_agent_cleanup ();
3165 }
3166
3167 static void
3168 thread_startup (MonoProfiler *prof, uintptr_t tid)
3169 {
3170         MonoInternalThread *thread = mono_thread_internal_current ();
3171         MonoInternalThread *old_thread;
3172         DebuggerTlsData *tls;
3173
3174         if (tid == debugger_thread_id)
3175                 return;
3176
3177         g_assert (thread->tid == tid);
3178
3179         mono_loader_lock ();
3180         old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3181         mono_loader_unlock ();
3182         if (old_thread) {
3183                 if (thread == old_thread) {
3184                         /* 
3185                          * For some reason, thread_startup () might be called for the same thread
3186                          * multiple times (attach ?).
3187                          */
3188                         DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3189                         return;
3190                 } else {
3191                         /*
3192                          * thread_end () might not be called for some threads, and the tid could
3193                          * get reused.
3194                          */
3195                         DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3196                         mono_loader_lock ();
3197                         mono_g_hash_table_remove (thread_to_tls, old_thread);
3198                         mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3199                         mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3200                         mono_loader_unlock ();
3201                 }
3202         }
3203
3204         tls = TlsGetValue (debugger_tls_id);
3205         g_assert (!tls);
3206         // FIXME: Free this somewhere
3207         tls = g_new0 (DebuggerTlsData, 1);
3208         tls->resume_event = CreateEvent (NULL, FALSE, FALSE, NULL);
3209         MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3210         tls->thread = thread;
3211         TlsSetValue (debugger_tls_id, tls);
3212
3213         DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3214
3215         mono_loader_lock ();
3216         mono_g_hash_table_insert (thread_to_tls, thread, tls);
3217         mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3218         mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3219         mono_loader_unlock ();
3220
3221         process_profiler_event (EVENT_KIND_THREAD_START, thread);
3222
3223         /* 
3224          * suspend_vm () could have missed this thread, so wait for a resume.
3225          */
3226         suspend_current ();
3227 }
3228
3229 static void
3230 thread_end (MonoProfiler *prof, uintptr_t tid)
3231 {
3232         MonoInternalThread *thread;
3233         DebuggerTlsData *tls = NULL;
3234
3235         mono_loader_lock ();
3236         thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3237         if (thread) {
3238                 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3239                 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3240                 tls->terminated = TRUE;
3241                 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3242                 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3243                 MONO_GC_UNREGISTER_ROOT (tls->thread);
3244                 tls->thread = NULL;
3245         }
3246         mono_loader_unlock ();
3247
3248         /* We might be called for threads started before we registered the start callback */
3249         if (thread) {
3250                 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3251                 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3252         }
3253 }
3254
3255 static void
3256 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3257 {
3258         mono_loader_lock ();
3259         g_hash_table_insert (domains, domain, domain);
3260         mono_loader_unlock ();
3261
3262         process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3263 }
3264
3265 static void
3266 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3267 {
3268         clear_breakpoints_for_domain (domain);
3269         
3270         mono_loader_lock ();
3271         /* Invalidate each thread's frame stack */
3272         mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3273         mono_loader_unlock ();
3274         
3275         process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3276 }
3277
3278 /*
3279  * invalidate_each_thread:
3280  *
3281  *   A GHFunc to invalidate frames.
3282  *   value must be a DebuggerTlsData*
3283  */
3284 static void
3285 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3286 {
3287         invalidate_frames (value);
3288 }
3289
3290 static void
3291 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3292 {
3293         /* Sent later in jit_end () */
3294         mono_loader_lock ();
3295         g_ptr_array_add (pending_assembly_loads, assembly);
3296         mono_loader_unlock ();
3297 }
3298
3299 static void
3300 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3301 {
3302         process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3303
3304         clear_event_requests_for_assembly (assembly);
3305         clear_types_for_assembly (assembly);
3306 }
3307
3308 static void
3309 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3310 {
3311 #if defined(HOST_WIN32) && !defined(__GNUC__)
3312         gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3313 #else
3314         gpointer stackptr = __builtin_frame_address (1);
3315 #endif
3316         MonoInternalThread *thread = mono_thread_internal_current ();
3317         DebuggerTlsData *tls;
3318
3319         mono_loader_lock ();
3320         
3321         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3322         /* Could be the debugger thread with assembly/type load hooks */
3323         if (tls)
3324                 tls->invoke_addr = stackptr;
3325
3326         mono_loader_unlock ();
3327 }
3328
3329 static void
3330 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3331 {
3332         int i;
3333 #if defined(HOST_WIN32) && !defined(__GNUC__)
3334         gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3335 #else
3336         gpointer stackptr = __builtin_frame_address (1);
3337 #endif
3338
3339         if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3340                 return;
3341
3342         /*
3343          * We need to stop single stepping when exiting a runtime invoke, since if it is
3344          * a step out, it may return to native code, and thus never end.
3345          */
3346         mono_loader_lock ();
3347         ss_invoke_addr = NULL;
3348
3349         for (i = 0; i < event_requests->len; ++i) {
3350                 EventRequest *req = g_ptr_array_index (event_requests, i);
3351
3352                 if (req->event_kind == EVENT_KIND_STEP) {
3353                         ss_destroy (req->info);
3354                         g_ptr_array_remove_index_fast (event_requests, i);
3355                         g_free (req);
3356                         break;
3357                 }
3358         }
3359         mono_loader_unlock ();
3360 }
3361
3362 static void
3363 send_type_load (MonoClass *klass)
3364 {
3365         gboolean type_load = FALSE;
3366         MonoDomain *domain = mono_domain_get ();
3367         AgentDomainInfo *info = NULL;
3368
3369         mono_loader_lock ();
3370         mono_domain_lock (domain);
3371
3372         info = get_agent_domain_info (domain);
3373
3374         if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3375                 type_load = TRUE;
3376                 g_hash_table_insert (info->loaded_classes, klass, klass);
3377         }
3378
3379         mono_domain_unlock (domain);
3380         mono_loader_unlock ();
3381         if (type_load)
3382                 emit_type_load (klass, klass, NULL);
3383 }
3384
3385 static void
3386 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3387 {
3388         /*
3389          * We emit type load events when the first method of the type is JITted,
3390          * since the class load profiler callbacks might be called with the
3391          * loader lock held. They could also occur in the debugger thread.
3392          * Same for assembly load events.
3393          */
3394         while (TRUE) {
3395                 MonoAssembly *assembly = NULL;
3396
3397                 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3398                 mono_loader_lock ();
3399                 if (pending_assembly_loads->len > 0) {
3400                         assembly = g_ptr_array_index (pending_assembly_loads, 0);
3401                         g_ptr_array_remove_index (pending_assembly_loads, 0);
3402                 }
3403                 mono_loader_unlock ();
3404
3405                 if (assembly) {
3406                         process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3407                 } else {
3408                         break;
3409                 }
3410         }
3411
3412         send_type_load (method->klass);
3413
3414         if (!result)
3415                 add_pending_breakpoints (method, jinfo);
3416 }
3417
3418 /*
3419  * BREAKPOINTS/SINGLE STEPPING
3420  */
3421
3422 /* 
3423  * Contains information about an inserted breakpoint.
3424  */
3425 typedef struct {
3426         long il_offset, native_offset;
3427         guint8 *ip;
3428         MonoJitInfo *ji;
3429         MonoDomain *domain;
3430 } BreakpointInstance;
3431
3432 /*
3433  * Contains generic information about a breakpoint.
3434  */
3435 typedef struct {
3436         /* 
3437          * The method where the breakpoint is placed. Can be NULL in which case it 
3438          * is inserted into every method. This is used to implement method entry/
3439          * exit events. Can be a generic method definition, in which case the
3440          * breakpoint is inserted into every instance.
3441          */
3442         MonoMethod *method;
3443         long il_offset;
3444         EventRequest *req;
3445         /* 
3446          * A list of BreakpointInstance structures describing where the breakpoint
3447          * was inserted. There could be more than one because of 
3448          * generics/appdomains/method entry/exit.
3449          */
3450         GPtrArray *children;
3451 } MonoBreakpoint;
3452
3453 /* List of breakpoints */
3454 static GPtrArray *breakpoints;
3455 /* Maps breakpoint locations to the number of breakpoints at that location */
3456 static GHashTable *bp_locs;
3457
3458 static void
3459 breakpoints_init (void)
3460 {
3461         breakpoints = g_ptr_array_new ();
3462         bp_locs = g_hash_table_new (NULL, NULL);
3463 }       
3464
3465 /*
3466  * insert_breakpoint:
3467  *
3468  *   Insert the breakpoint described by BP into the method described by
3469  * JI.
3470  */
3471 static void
3472 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
3473 {
3474         int i, count;
3475         gint32 il_offset = -1, native_offset;
3476         BreakpointInstance *inst;
3477
3478         if (error)
3479                 mono_error_init (error);
3480
3481         native_offset = 0;
3482         for (i = 0; i < seq_points->len; ++i) {
3483                 il_offset = seq_points->seq_points [i].il_offset;
3484                 native_offset = seq_points->seq_points [i].native_offset;
3485
3486                 if (il_offset == bp->il_offset)
3487                         break;
3488         }
3489
3490         if (i == seq_points->len) {
3491                 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d, seq_points=%d\n", mono_method_full_name (ji->method, TRUE), bp->il_offset, seq_points->len);
3492                 if (error) {
3493                         mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
3494                         g_free (s);
3495                         return;
3496                 } else {
3497                         g_error ("%s", s);
3498                         g_free (s);
3499                 }
3500         }
3501
3502         inst = g_new0 (BreakpointInstance, 1);
3503         inst->native_offset = native_offset;
3504         inst->ip = (guint8*)ji->code_start + native_offset;
3505         inst->ji = ji;
3506         inst->domain = domain;
3507
3508         mono_loader_lock ();
3509
3510         g_ptr_array_add (bp->children, inst);
3511
3512         count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
3513         g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
3514         mono_loader_unlock ();
3515
3516         if (count == 0) {
3517 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3518                 mono_arch_set_breakpoint (ji, inst->ip);
3519 #else
3520                 NOT_IMPLEMENTED;
3521 #endif
3522         }
3523
3524         DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)il_offset));      
3525 }
3526
3527 static void
3528 remove_breakpoint (BreakpointInstance *inst)
3529 {
3530 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3531         int count;
3532         MonoJitInfo *ji = inst->ji;
3533         guint8 *ip = inst->ip;
3534
3535         mono_loader_lock ();
3536         count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
3537         g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
3538         mono_loader_unlock ();
3539
3540         g_assert (count > 0);
3541
3542         if (count == 1) {
3543                 mono_arch_clear_breakpoint (ji, ip);
3544         }
3545 #else
3546         NOT_IMPLEMENTED;
3547 #endif
3548 }       
3549
3550 static inline gboolean
3551 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
3552 {
3553         return (!bp->method || method == bp->method || (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method));
3554 }
3555
3556 /*
3557  * add_pending_breakpoints:
3558  *
3559  *   Insert pending breakpoints into the newly JITted method METHOD.
3560  */
3561 static void
3562 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
3563 {
3564         int i, j;
3565         MonoSeqPointInfo *seq_points;
3566         MonoDomain *domain;
3567
3568         if (!breakpoints)
3569                 return;
3570
3571         domain = mono_domain_get ();
3572
3573         mono_loader_lock ();
3574
3575         for (i = 0; i < breakpoints->len; ++i) {
3576                 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
3577                 gboolean found = FALSE;
3578
3579                 if (!bp_matches_method (bp, method))
3580                         continue;
3581
3582                 for (j = 0; j < bp->children->len; ++j) {
3583                         BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
3584
3585                         if (inst->ji == ji)
3586                                 found = TRUE;
3587                 }
3588
3589                 if (!found) {
3590                         mono_domain_lock (domain);
3591                         seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
3592                         mono_domain_unlock (domain);
3593                         if (!seq_points)
3594                                 /* Could be AOT code */
3595                                 continue;
3596                         g_assert (seq_points);
3597
3598                         insert_breakpoint (seq_points, domain, ji, bp, NULL);
3599                 }
3600         }
3601
3602         mono_loader_unlock ();
3603 }
3604
3605 static void
3606 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
3607 {
3608         gpointer code;
3609         MonoJitInfo *ji;
3610
3611         if (error)
3612                 mono_error_init (error);
3613
3614         code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
3615         if (!code) {
3616                 /* Might be AOTed code */
3617                 code = mono_aot_get_method (domain, method);
3618                 g_assert (code);
3619                 ji = mono_jit_info_table_find (domain, code);
3620                 g_assert (ji);
3621         }
3622         g_assert (code);
3623
3624         insert_breakpoint (seq_points, domain, ji, bp, error);
3625 }
3626
3627 static void
3628 clear_breakpoint (MonoBreakpoint *bp);
3629
3630 /*
3631  * set_breakpoint:
3632  *
3633  *   Set a breakpoint at IL_OFFSET in METHOD.
3634  * METHOD can be NULL, in which case a breakpoint is placed in all methods.
3635  * METHOD can also be a generic method definition, in which case a breakpoint
3636  * is placed in all instances of the method.
3637  * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
3638  * inserted.
3639  */
3640 static MonoBreakpoint*
3641 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
3642 {
3643         MonoBreakpoint *bp;
3644         GHashTableIter iter, iter2;
3645         MonoDomain *domain;
3646         MonoMethod *m;
3647         MonoSeqPointInfo *seq_points;
3648
3649         if (error)
3650                 mono_error_init (error);
3651
3652         // FIXME:
3653         // - suspend/resume the vm to prevent code patching problems
3654         // - multiple breakpoints on the same location
3655         // - dynamic methods
3656         // - races
3657
3658         bp = g_new0 (MonoBreakpoint, 1);
3659         bp->method = method;
3660         bp->il_offset = il_offset;
3661         bp->req = req;
3662         bp->children = g_ptr_array_new ();
3663
3664         DEBUG(1, fprintf (log_file, "[dbg] Setting %sbreakpoint at %s:0x%x.\n", (req->event_kind == EVENT_KIND_STEP) ? "single step " : "", method ? mono_method_full_name (method, TRUE) : "<all>", (int)il_offset));
3665
3666         mono_loader_lock ();
3667
3668         g_hash_table_iter_init (&iter, domains);
3669         while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
3670                 mono_domain_lock (domain);
3671
3672                 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
3673                 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
3674                         if (bp_matches_method (bp, m))
3675                                 set_bp_in_method (domain, m, seq_points, bp, error);
3676                 }
3677
3678                 mono_domain_unlock (domain);
3679         }
3680
3681         mono_loader_unlock ();
3682
3683         mono_loader_lock ();
3684         g_ptr_array_add (breakpoints, bp);
3685         mono_loader_unlock ();
3686
3687         if (error && !mono_error_ok (error)) {
3688                 clear_breakpoint (bp);
3689                 return NULL;
3690         }
3691
3692         return bp;
3693 }
3694
3695 static void
3696 clear_breakpoint (MonoBreakpoint *bp)
3697 {
3698         int i;
3699
3700         // FIXME: locking, races
3701         for (i = 0; i < bp->children->len; ++i) {
3702                 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
3703
3704                 remove_breakpoint (inst);
3705
3706                 g_free (inst);
3707         }
3708
3709         mono_loader_lock ();
3710         g_ptr_array_remove (breakpoints, bp);
3711         mono_loader_unlock ();
3712
3713         g_ptr_array_free (bp->children, TRUE);
3714         g_free (bp);
3715 }
3716
3717 static void
3718 breakpoints_cleanup (void)
3719 {
3720         int i;
3721
3722         mono_loader_lock ();
3723         i = 0;
3724         while (i < event_requests->len) {
3725                 EventRequest *req = g_ptr_array_index (event_requests, i);
3726
3727                 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
3728                         clear_breakpoint (req->info);
3729                         g_ptr_array_remove_index_fast (event_requests, i);
3730                         g_free (req);
3731                 } else {
3732                         i ++;
3733                 }
3734         }
3735
3736         for (i = 0; i < breakpoints->len; ++i)
3737                 g_free (g_ptr_array_index (breakpoints, i));
3738
3739         g_ptr_array_free (breakpoints, TRUE);
3740         g_hash_table_destroy (bp_locs);
3741
3742         breakpoints = NULL;
3743         bp_locs = NULL;
3744
3745         mono_loader_unlock ();
3746 }
3747
3748 /*
3749  * clear_breakpoints_for_domain:
3750  *
3751  *   Clear breakpoint instances which reference DOMAIN.
3752  */
3753 static void
3754 clear_breakpoints_for_domain (MonoDomain *domain)
3755 {
3756         int i, j;
3757
3758         /* This could be called after shutdown */
3759         if (!breakpoints)
3760                 return;
3761
3762         mono_loader_lock ();
3763         for (i = 0; i < breakpoints->len; ++i) {
3764                 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
3765
3766                 j = 0;
3767                 while (j < bp->children->len) {
3768                         BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
3769
3770                         if (inst->domain == domain) {
3771                                 remove_breakpoint (inst);
3772
3773                                 g_free (inst);
3774
3775                                 g_ptr_array_remove_index_fast (bp->children, j);
3776                         } else {
3777                                 j ++;
3778                         }
3779                 }
3780         }
3781         mono_loader_unlock ();
3782 }
3783
3784 static gboolean
3785 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
3786 {
3787         return bp->method && bp->method->klass->image->assembly == assembly;
3788 }
3789
3790 static void
3791 process_breakpoint_inner (DebuggerTlsData *tls, MonoContext *ctx)
3792 {
3793         MonoJitInfo *ji;
3794         guint8 *orig_ip, *ip;
3795         int i, j, suspend_policy;
3796         guint32 native_offset;
3797         MonoBreakpoint *bp;
3798         BreakpointInstance *inst;
3799         GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
3800         GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
3801         EventKind kind = EVENT_KIND_BREAKPOINT;
3802
3803         // FIXME: Speed this up
3804
3805         orig_ip = ip = MONO_CONTEXT_GET_IP (ctx);
3806         ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
3807         g_assert (ji);
3808         g_assert (ji->method);
3809
3810         /* Compute the native offset of the breakpoint from the ip */
3811 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3812         ip = mono_arch_get_ip_for_breakpoint (ji, ctx);
3813         native_offset = ip - (guint8*)ji->code_start;   
3814 #else
3815         NOT_IMPLEMENTED;
3816 #endif
3817
3818         /* 
3819          * Skip the instruction causing the breakpoint signal.
3820          */
3821         mono_arch_skip_breakpoint (ctx);
3822
3823         if (ji->method->wrapper_type || tls->disable_breakpoints)
3824                 return;
3825
3826         bp_reqs = g_ptr_array_new ();
3827         ss_reqs = g_ptr_array_new ();
3828         ss_reqs_orig = g_ptr_array_new ();
3829
3830         DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, offset=0x%x.\n", (gpointer)GetCurrentThreadId (), ji->method->name, native_offset));
3831
3832         mono_loader_lock ();
3833
3834         bp = NULL;
3835         for (i = 0; i < breakpoints->len; ++i) {
3836                 bp = g_ptr_array_index (breakpoints, i);
3837
3838                 if (!bp->method)
3839                         continue;
3840
3841                 for (j = 0; j < bp->children->len; ++j) {
3842                         inst = g_ptr_array_index (bp->children, j);
3843                         if (inst->ji == ji && inst->native_offset == native_offset) {
3844                                 if (bp->req->event_kind == EVENT_KIND_STEP) {
3845                                         g_ptr_array_add (ss_reqs_orig, bp->req);
3846                                 } else {
3847                                         g_ptr_array_add (bp_reqs, bp->req);
3848                                 }
3849                         }
3850                 }
3851         }
3852         if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
3853                 MonoSeqPointInfo *seq_points;
3854                 int seq_il_offset, seq_native_offset;
3855                 MonoDomain *domain = mono_domain_get ();
3856
3857                 /* Maybe a method entry/exit event */
3858                 mono_domain_lock (domain);
3859                 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
3860                 mono_domain_unlock (domain);
3861                 if (!seq_points) {
3862                         // FIXME: Generic sharing */
3863                         mono_loader_unlock ();
3864                         return;
3865                 }
3866                 g_assert (seq_points);
3867
3868                 for (i = 0; i < seq_points->len; ++i) {
3869                         seq_il_offset = seq_points->seq_points [i].il_offset;
3870                         seq_native_offset = seq_points->seq_points [i].native_offset;
3871
3872                         if (native_offset == seq_native_offset) {
3873                                 if (seq_il_offset == METHOD_ENTRY_IL_OFFSET)
3874                                         kind = EVENT_KIND_METHOD_ENTRY;
3875                                 else if (seq_il_offset == METHOD_EXIT_IL_OFFSET)
3876                                         kind = EVENT_KIND_METHOD_EXIT;
3877                                 break;
3878                         }
3879                 }
3880         }
3881
3882         /* Process single step requests */
3883         for (i = 0; i < ss_reqs_orig->len; ++i) {
3884                 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
3885                 SingleStepReq *ss_req = req->info;
3886                 gboolean hit = TRUE;
3887                 MonoSeqPointInfo *info;
3888                 SeqPoint *sp;
3889
3890                 sp = find_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
3891                 g_assert (sp);
3892
3893                 if (ss_req->size == STEP_SIZE_LINE) {
3894                         /* Have to check whenever a different source line was reached */
3895                         MonoDebugMethodInfo *minfo;
3896                         MonoDebugSourceLocation *loc = NULL;
3897
3898                         minfo = mono_debug_lookup_method (ji->method);
3899
3900                         if (minfo)
3901                                 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
3902
3903                         if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line))
3904                                 /* Have to continue single stepping */
3905                                 hit = FALSE;
3906                                 
3907                         if (loc) {
3908                                 ss_req->last_method = ji->method;
3909                                 ss_req->last_line = loc->row;
3910                                 mono_debug_free_source_location (loc);
3911                         }
3912                 }
3913
3914                 if (hit)
3915                         g_ptr_array_add (ss_reqs, req);
3916
3917                 /* Start single stepping again from the current sequence point */
3918                 ss_start (ss_req, ji->method, sp, info, ctx, NULL, FALSE);
3919         }
3920         
3921         if (ss_reqs->len > 0)
3922                 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
3923         if (bp_reqs->len > 0)
3924                 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
3925         if (kind != EVENT_KIND_BREAKPOINT)
3926                 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
3927
3928         mono_loader_unlock ();
3929
3930         g_ptr_array_free (bp_reqs, TRUE);
3931         g_ptr_array_free (ss_reqs, TRUE);
3932
3933         /* 
3934          * FIXME: The first event will suspend, so the second will only be sent after the
3935          * resume.
3936          */
3937         if (ss_events)
3938                 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
3939         if (bp_events)
3940                 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
3941         if (enter_leave_events)
3942                 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
3943 }
3944
3945 static void
3946 process_breakpoint (void)
3947 {
3948         DebuggerTlsData *tls;
3949         MonoContext ctx;
3950         static void (*restore_context) (void *);
3951
3952         if (!restore_context)
3953                 restore_context = mono_get_restore_context ();
3954
3955         tls = TlsGetValue (debugger_tls_id);
3956         memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
3957
3958         process_breakpoint_inner (tls, &ctx);
3959
3960         /* This is called when resuming from a signal handler, so it shouldn't return */
3961         restore_context (&ctx);
3962         g_assert_not_reached ();
3963 }
3964
3965 static void
3966 resume_from_signal_handler (void *sigctx, void *func)
3967 {
3968         DebuggerTlsData *tls;
3969         MonoContext ctx;
3970
3971         /* Save the original context in TLS */
3972         // FIXME: This might not work on an altstack ?
3973         tls = TlsGetValue (debugger_tls_id);
3974         g_assert (tls);
3975
3976         // FIXME: MonoContext usually doesn't include the fp registers, so these are 
3977         // clobbered by a single step/breakpoint event. If this turns out to be a problem,
3978         // clob:c could be added to op_seq_point.
3979
3980         mono_arch_sigctx_to_monoctx (sigctx, &ctx);
3981         memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
3982 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
3983         mono_arch_setup_resume_sighandler_ctx (&ctx, func);
3984 #else
3985         MONO_CONTEXT_SET_IP (&ctx, func);
3986 #endif
3987         mono_arch_monoctx_to_sigctx (&ctx, sigctx);
3988
3989 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3990         mono_ppc_set_func_into_sigctx (sigctx, func);
3991 #endif
3992 }
3993
3994 void
3995 mono_debugger_agent_breakpoint_hit (void *sigctx)
3996 {
3997         /*
3998          * We are called from a signal handler, and running code there causes all kinds of
3999          * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4000          * So set up the signal context to return to the real breakpoint handler function.
4001          */
4002
4003         resume_from_signal_handler (sigctx, process_breakpoint);
4004 }
4005
4006 static const char*
4007 ss_depth_to_string (StepDepth depth)
4008 {
4009         switch (depth) {
4010         case STEP_DEPTH_OVER:
4011                 return "over";
4012         case STEP_DEPTH_OUT:
4013                 return "out";
4014         case STEP_DEPTH_INTO:
4015                 return "into";
4016         default:
4017                 g_assert_not_reached ();
4018                 return NULL;
4019         }
4020 }
4021
4022 static void
4023 process_single_step_inner (DebuggerTlsData *tls, MonoContext *ctx)
4024 {
4025         MonoJitInfo *ji;
4026         guint8 *ip;
4027         GPtrArray *reqs;
4028         int il_offset, suspend_policy;
4029         MonoDomain *domain;
4030         GSList *events;
4031
4032         // FIXME: Speed this up
4033
4034         ip = MONO_CONTEXT_GET_IP (ctx);
4035
4036         /* Skip the instruction causing the single step */
4037         mono_arch_skip_single_step (ctx);
4038
4039         if (suspend_count > 0) {
4040                 process_suspend (tls, ctx);
4041                 return;
4042         }
4043
4044         if (!ss_req)
4045                 // FIXME: A suspend race
4046                 return;
4047
4048         if (mono_thread_internal_current () != ss_req->thread)
4049                 return;
4050
4051         if (log_level > 0) {
4052                 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4053
4054                 DEBUG (1, fprintf (log_file, "[%p] Single step event (depth=%s) at %s (%p), sp %p, last sp %p\n", (gpointer)GetCurrentThreadId (), ss_depth_to_string (ss_req->depth), mono_method_full_name (ji->method, TRUE), MONO_CONTEXT_GET_IP (ctx), MONO_CONTEXT_GET_SP (ctx), ss_req->last_sp));
4055         }
4056
4057         /*
4058          * We implement step over/out by single stepping until we reach the same 
4059          * frame/parent frame.
4060          * FIXME:
4061          * - this is slow
4062          * - stack growing upward
4063          * - localloc
4064          * - exceptions
4065          */
4066         if (ss_req->depth != STEP_DEPTH_INTO) {
4067                 if (ss_req->depth == STEP_DEPTH_OVER && MONO_CONTEXT_GET_SP (ctx) < ss_req->last_sp)
4068                         return;
4069                 if (ss_req->depth == STEP_DEPTH_OUT && MONO_CONTEXT_GET_SP (ctx) <= ss_req->last_sp)
4070                         return;
4071
4072                 ss_req->last_sp = MONO_CONTEXT_GET_SP (ctx);
4073         }
4074
4075         ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4076         g_assert (ji);
4077         g_assert (ji->method);
4078
4079         if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4080                 return;
4081
4082         /* 
4083          * FIXME: 
4084          * Stopping in memset makes half-initialized vtypes visible.
4085          * Stopping in memcpy makes half-copied vtypes visible.
4086          */
4087         if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4088                 return;
4089
4090         /* 
4091          * The ip points to the instruction causing the single step event, convert it
4092          * to the offset stored in seq_points.
4093          */
4094 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4095         ip = mono_arch_get_ip_for_single_step (ji, ctx);
4096 #else
4097         g_assert_not_reached ();
4098 #endif
4099
4100         /* 
4101          * mono_debug_lookup_source_location () doesn't work for IL offset 0 for 
4102          * example, so do things by hand.
4103          */
4104         il_offset = compute_il_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start);
4105
4106         if (il_offset == -1)
4107                 return;
4108
4109         if (ss_req->size == STEP_SIZE_LINE) {
4110                 /* Step until a different source line is reached */
4111                 MonoDebugMethodInfo *minfo;
4112
4113                 minfo = mono_debug_lookup_method (ji->method);
4114
4115                 if (minfo) {
4116                         MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4117
4118                         if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
4119                                 mono_debug_free_source_location (loc);
4120                                 return;
4121                         }
4122                         if (!loc)
4123                                 /*
4124                                  * Step until we reach a location with line number info, 
4125                                  * otherwise the client can't show a location.
4126                                  * This can happen for example with statics initialized inline
4127                                  * outside of a cctor.
4128                                  */
4129                                 return;
4130
4131                         if (loc) {
4132                                 ss_req->last_method = ji->method;
4133                                 ss_req->last_line = loc->row;
4134                                 mono_debug_free_source_location (loc);
4135                         }
4136                 }
4137         }
4138
4139         // FIXME: Has to lock earlier
4140
4141         reqs = g_ptr_array_new ();
4142
4143         mono_loader_lock ();
4144
4145         g_ptr_array_add (reqs, ss_req->req);
4146
4147         events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4148
4149         g_ptr_array_free (reqs, TRUE);
4150
4151         mono_loader_unlock ();
4152
4153         process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4154 }
4155
4156 static void
4157 process_single_step (void)
4158 {
4159         DebuggerTlsData *tls;
4160         MonoContext ctx;
4161         static void (*restore_context) (void *);
4162
4163         if (!restore_context)
4164                 restore_context = mono_get_restore_context ();
4165
4166         tls = TlsGetValue (debugger_tls_id);
4167         memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
4168
4169         process_single_step_inner (tls, &ctx);
4170
4171         /* This is called when resuming from a signal handler, so it shouldn't return */
4172         restore_context (&ctx);
4173         g_assert_not_reached ();
4174 }
4175
4176 /*
4177  * mono_debugger_agent_single_step_event:
4178  *
4179  *   Called from a signal handler to handle a single step event.
4180  */
4181 void
4182 mono_debugger_agent_single_step_event (void *sigctx)
4183 {
4184         /* Resume to process_single_step through the signal context */
4185
4186         // FIXME: Since step out/over is implemented using step in, the step in case should
4187         // be as fast as possible. Move the relevant code from process_single_step_inner ()
4188         // here
4189
4190         if (GetCurrentThreadId () == debugger_thread_id) {
4191                 /* 
4192                  * This could happen despite our best effors when the runtime calls 
4193                  * assembly/type resolve hooks.
4194                  * FIXME: Breakpoints too.
4195                  */
4196                 MonoContext ctx;
4197
4198                 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4199                 mono_arch_skip_single_step (&ctx);
4200                 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4201                 return;
4202         }
4203
4204         resume_from_signal_handler (sigctx, process_single_step);
4205 }
4206
4207 /*
4208  * start_single_stepping:
4209  *
4210  *   Turn on single stepping. Can be called multiple times, for example,
4211  * by a single step event request + a suspend.
4212  */
4213 static void
4214 start_single_stepping (void)
4215 {
4216 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4217         int val = InterlockedIncrement (&ss_count);
4218
4219         if (val == 1)
4220                 mono_arch_start_single_stepping ();
4221
4222         if (ss_req != NULL && ss_invoke_addr == NULL) {
4223                 DebuggerTlsData *tls;
4224         
4225                 mono_loader_lock ();
4226         
4227                 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4228                 ss_invoke_addr = tls->invoke_addr;
4229                 
4230                 mono_loader_unlock ();
4231         }
4232 #else
4233         g_assert_not_reached ();
4234 #endif
4235 }
4236
4237 static void
4238 stop_single_stepping (void)
4239 {
4240 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4241         int val = InterlockedDecrement (&ss_count);
4242
4243         if (val == 0)
4244                 mono_arch_stop_single_stepping ();
4245 #else
4246         g_assert_not_reached ();
4247 #endif
4248 }
4249
4250 /*
4251  * ss_stop:
4252  *
4253  *   Stop the single stepping operation given by SS_REQ.
4254  */
4255 static void
4256 ss_stop (SingleStepReq *ss_req)
4257 {
4258         gboolean use_bps = FALSE;
4259
4260         if (ss_req->bps) {
4261                 GSList *l;
4262
4263                 use_bps = TRUE;
4264
4265                 for (l = ss_req->bps; l; l = l->next) {
4266                         clear_breakpoint (l->data);
4267                 }
4268                 g_slist_free (ss_req->bps);
4269                 ss_req->bps = NULL;
4270         }
4271
4272         if (ss_req->global) {
4273                 stop_single_stepping ();
4274                 ss_req->global = FALSE;
4275         }
4276 }
4277
4278 /*
4279  * ss_start:
4280  *
4281  *   Start the single stepping operation given by SS_REQ from the sequence point SP.
4282  */
4283 static void
4284 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4285 {
4286         int i, frame_index;
4287         SeqPoint *next_sp;
4288         MonoBreakpoint *bp;
4289
4290         /* Stop the previous operation */
4291         ss_stop (ss_req);
4292
4293         /*
4294          * Implement single stepping using breakpoints if possible.
4295          */
4296         if (step_to_catch) {
4297                 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4298                 ss_req->bps = g_slist_append (ss_req->bps, bp);
4299         } else if (ss_req->depth == STEP_DEPTH_OVER) {
4300                 frame_index = 1;
4301                 /*
4302                  * Find the first sequence point in the current or in a previous frame which
4303                  * is not the last in its method.
4304                  */
4305                 while (sp && sp->next_len == 0) {
4306                         sp = NULL;
4307                         if (tls && frame_index < tls->frame_count) {
4308                                 StackFrame *frame = tls->frames [frame_index];
4309
4310                                 method = frame->method;
4311                                 if (frame->il_offset != -1) {
4312                                         sp = find_seq_point (frame->domain, frame->method, frame->il_offset, &info);
4313                                 }
4314                                 frame_index ++;
4315                         }
4316                 }
4317
4318                 if (sp && sp->next_len > 0) {
4319                         for (i = 0; i < sp->next_len; ++i) {
4320                                 next_sp = &info->seq_points [sp->next [i]];
4321
4322                                 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4323                                 ss_req->bps = g_slist_append (ss_req->bps, bp);
4324                         }
4325                 }
4326         }
4327
4328         if (!ss_req->bps) {
4329                 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4330                 ss_req->global = TRUE;
4331                 start_single_stepping ();
4332         } else {
4333                 ss_req->global = FALSE;
4334         }
4335 }
4336
4337 /*
4338  * Start single stepping of thread THREAD
4339  */
4340 static ErrorCode
4341 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
4342 {
4343         DebuggerTlsData *tls;
4344         MonoSeqPointInfo *info = NULL;
4345         SeqPoint *sp = NULL;
4346         MonoMethod *method = NULL;
4347         MonoDebugMethodInfo *minfo;
4348         gboolean step_to_catch = FALSE;
4349
4350         if (suspend_count == 0)
4351                 return ERR_NOT_SUSPENDED;
4352
4353         wait_for_suspend ();
4354
4355         // FIXME: Multiple requests
4356         if (ss_req) {
4357                 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
4358                 return ERR_NOT_IMPLEMENTED;
4359         }
4360
4361         DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
4362
4363         ss_req = g_new0 (SingleStepReq, 1);
4364         ss_req->req = req;
4365         ss_req->thread = thread;
4366         ss_req->size = size;
4367         ss_req->depth = depth;
4368         req->info = ss_req;
4369
4370         mono_loader_lock ();
4371         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4372         mono_loader_unlock ();
4373         g_assert (tls);
4374         g_assert (tls->has_context);
4375         ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->ctx);
4376
4377         if (tls->has_catch_ctx) {
4378                 gboolean res;
4379                 StackFrameInfo frame;
4380                 MonoContext new_ctx;
4381                 MonoLMF *lmf = NULL;
4382
4383                 /*
4384                  * We are stopped at a throw site. Stepping should go to the catch site.
4385                  */
4386
4387                 /* Find the the jit info for the catch context */
4388                 res = mono_find_jit_info_ext (mono_domain_get (), thread->jit_data, NULL, &tls->catch_ctx, &new_ctx, NULL, &lmf, NULL, &frame);
4389                 g_assert (res);
4390                 g_assert (frame.type == FRAME_TYPE_MANAGED);
4391
4392                 /*
4393                  * Find the seq point corresponding to the landing site ip, which is the first seq
4394                  * point after ip.
4395                  */
4396                 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
4397                 g_assert (sp);
4398
4399                 method = frame.method;
4400
4401                 step_to_catch = TRUE;
4402                 /* This make sure the seq point is not skipped by process_single_step () */
4403                 ss_req->last_sp = NULL;
4404         }
4405
4406         if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
4407                 StackFrame *frame;
4408
4409                 /* Compute the initial line info */
4410                 compute_frame_info (thread, tls);
4411
4412                 g_assert (tls->frame_count);
4413                 frame = tls->frames [0];
4414
4415                 ss_req->last_method = frame->method;
4416                 ss_req->last_line = -1;
4417
4418                 minfo = mono_debug_lookup_method (frame->method);
4419                 if (minfo && frame->il_offset != -1) {
4420                         MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
4421
4422                         if (loc) {
4423                                 ss_req->last_line = loc->row;
4424                                 g_free (loc);
4425                         }
4426                 }
4427         }
4428
4429         if (!step_to_catch && ss_req->depth == STEP_DEPTH_OVER) {
4430                 StackFrame *frame;
4431
4432                 compute_frame_info (thread, tls);
4433
4434                 g_assert (tls->frame_count);
4435                 frame = tls->frames [0];
4436
4437                 if (!method && frame->il_offset != -1) {
4438                         /* FIXME: Sort the table and use a binary search */
4439                         sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4440                         g_assert (sp);
4441                         method = frame->method;
4442                 }
4443         }
4444
4445         ss_start (ss_req, method, sp, info, NULL, tls, step_to_catch);
4446
4447         return 0;
4448 }
4449
4450 static void
4451 ss_destroy (SingleStepReq *req)
4452 {
4453         // FIXME: Locking
4454         g_assert (ss_req == req);
4455
4456         ss_stop (ss_req);
4457
4458         g_free (ss_req);
4459         ss_req = NULL;
4460 }
4461
4462 void
4463 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx, 
4464                                       MonoContext *catch_ctx)
4465 {
4466         int suspend_policy;
4467         GSList *events;
4468         MonoJitInfo *ji;
4469         EventInfo ei;
4470         DebuggerTlsData *tls = NULL;
4471
4472         if (thread_to_tls != NULL) {
4473                 MonoInternalThread *thread = mono_thread_internal_current ();
4474
4475                 mono_loader_lock ();
4476                 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4477                 mono_loader_unlock ();
4478
4479                 if (tls && tls->abort_requested)
4480                         return;
4481                 if (tls && tls->disable_breakpoints)
4482                         return;
4483         }
4484
4485         memset (&ei, 0, sizeof (EventInfo));
4486
4487         /* Just-In-Time debugging */
4488         if (!catch_ctx) {
4489                 if (agent_config.onuncaught && !inited) {
4490                         finish_agent_init (FALSE);
4491
4492                         /*
4493                          * Send an unsolicited EXCEPTION event with a dummy request id.
4494                          */
4495                         events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
4496                         ei.exc = (MonoObject*)exc;
4497                         process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
4498                         return;
4499                 }
4500         } else if (agent_config.onthrow && !inited) {
4501                 GSList *l;
4502                 gboolean found = FALSE;
4503
4504                 for (l = agent_config.onthrow; l; l = l->next) {
4505                         char *ex_type = l->data;
4506                         char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
4507
4508                         if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
4509                                 found = TRUE;
4510
4511                         g_free (f);
4512                 }
4513
4514                 if (found) {
4515                         finish_agent_init (FALSE);
4516
4517                         /*
4518                          * Send an unsolicited EXCEPTION event with a dummy request id.
4519                          */
4520                         events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
4521                         ei.exc = (MonoObject*)exc;
4522                         process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
4523                         return;
4524                 }
4525         }
4526
4527         if (!inited)
4528                 return;
4529
4530         ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
4531
4532         ei.exc = (MonoObject*)exc;
4533         ei.caught = catch_ctx != NULL;
4534
4535         mono_loader_lock ();
4536         events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
4537         mono_loader_unlock ();
4538
4539         if (tls && catch_ctx) {
4540                 tls->catch_ctx = *catch_ctx;
4541                 tls->has_catch_ctx = TRUE;
4542         }
4543
4544         process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
4545
4546         if (tls)
4547                 tls->has_catch_ctx = FALSE;
4548 }
4549
4550 void
4551 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
4552 {
4553         DebuggerTlsData *tls;
4554
4555         if (!inited)
4556                 return;
4557
4558         tls = TlsGetValue (debugger_tls_id);
4559         if (!tls)
4560                 return;
4561
4562         /*
4563          * We're about to invoke an exception filter during the first pass of exception handling.
4564          *
4565          * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
4566          * 'orig_ctx' is the context where the exception has been thrown.
4567          *
4568          *
4569          * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
4570          *
4571          * If we're stopped in Filter(), normal stack unwinding would first unwind to
4572          * the call site (line 37) and then continue to Main(), but it would never
4573          * include the throw site (line 32).
4574          *
4575          * Since exception filters are invoked during the first pass of exception handling,
4576          * the stack frames of the throw site are still intact, so we should include them
4577          * in a stack trace.
4578          *
4579          * We do this here by saving the context of the throw site in 'tls->filter_ctx'.
4580          *
4581          * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
4582          * but report the location of the 'throw' to the user.
4583          *
4584          */
4585
4586         memcpy (&tls->filter_ctx, orig_ctx, sizeof (MonoContext));
4587         tls->has_filter_ctx = TRUE;
4588
4589         tls->filter_lmf = mono_get_lmf ();
4590         tls->domain = mono_domain_get ();
4591 }
4592
4593 void
4594 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
4595 {
4596         DebuggerTlsData *tls;
4597
4598         if (!inited)
4599                 return;
4600
4601         tls = TlsGetValue (debugger_tls_id);
4602         if (!tls)
4603                 return;
4604
4605         tls->has_filter_ctx = FALSE;
4606 }
4607
4608 /*
4609  * buffer_add_value_full:
4610  *
4611  *   Add the encoding of the value at ADDR described by T to the buffer.
4612  * AS_VTYPE determines whenever to treat primitive types as primitive types or
4613  * vtypes.
4614  */
4615 static void
4616 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
4617                                            gboolean as_vtype)
4618 {
4619         MonoObject *obj;
4620
4621         if (t->byref) {
4622                 g_assert (*(void**)addr);
4623                 addr = *(void**)addr;
4624         }
4625
4626         if (as_vtype) {
4627                 switch (t->type) {
4628                 case MONO_TYPE_BOOLEAN:
4629                 case MONO_TYPE_I1:
4630                 case MONO_TYPE_U1:
4631                 case MONO_TYPE_CHAR:
4632                 case MONO_TYPE_I2:
4633                 case MONO_TYPE_U2:
4634                 case MONO_TYPE_I4:
4635                 case MONO_TYPE_U4:
4636                 case MONO_TYPE_R4:
4637                 case MONO_TYPE_I8:
4638                 case MONO_TYPE_U8:
4639                 case MONO_TYPE_R8:
4640                 case MONO_TYPE_I:
4641                 case MONO_TYPE_U:
4642                 case MONO_TYPE_PTR:
4643                         goto handle_vtype;
4644                         break;
4645                 default:
4646                         break;
4647                 }
4648         }
4649
4650         switch (t->type) {
4651         case MONO_TYPE_VOID:
4652                 buffer_add_byte (buf, t->type);
4653                 break;
4654         case MONO_TYPE_BOOLEAN:
4655         case MONO_TYPE_I1:
4656         case MONO_TYPE_U1:
4657                 buffer_add_byte (buf, t->type);
4658                 buffer_add_int (buf, *(gint8*)addr);
4659                 break;
4660         case MONO_TYPE_CHAR:
4661         case MONO_TYPE_I2:
4662         case MONO_TYPE_U2:
4663                 buffer_add_byte (buf, t->type);
4664                 buffer_add_int (buf, *(gint16*)addr);
4665                 break;
4666         case MONO_TYPE_I4:
4667         case MONO_TYPE_U4:
4668         case MONO_TYPE_R4:
4669                 buffer_add_byte (buf, t->type);
4670                 buffer_add_int (buf, *(gint32*)addr);
4671                 break;
4672         case MONO_TYPE_I8:
4673         case MONO_TYPE_U8:
4674         case MONO_TYPE_R8:
4675                 buffer_add_byte (buf, t->type);
4676                 buffer_add_long (buf, *(gint64*)addr);
4677                 break;
4678         case MONO_TYPE_I:
4679         case MONO_TYPE_U:
4680                 /* Treat it as a vtype */
4681                 goto handle_vtype;
4682         case MONO_TYPE_PTR: {
4683                 gssize val = *(gssize*)addr;
4684                 
4685                 buffer_add_byte (buf, t->type);
4686                 buffer_add_long (buf, val);
4687                 break;
4688         }
4689         handle_ref:
4690         case MONO_TYPE_STRING:
4691         case MONO_TYPE_SZARRAY:
4692         case MONO_TYPE_OBJECT:
4693         case MONO_TYPE_CLASS:
4694         case MONO_TYPE_ARRAY:
4695                 obj = *(MonoObject**)addr;
4696
4697                 if (!obj) {
4698                         buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
4699                 } else {
4700                         if (obj->vtable->klass->valuetype) {
4701                                 t = &obj->vtable->klass->byval_arg;
4702                                 addr = mono_object_unbox (obj);
4703                                 goto handle_vtype;
4704                         } else if (obj->vtable->klass->rank) {
4705                                 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
4706                         } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
4707                                 buffer_add_byte (buf, MONO_TYPE_CLASS);
4708                         } else {
4709                                 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
4710                         }
4711                         buffer_add_objid (buf, obj);
4712                 }
4713                 break;
4714         handle_vtype:
4715         case MONO_TYPE_VALUETYPE: {
4716                 int nfields;
4717                 gpointer iter;
4718                 MonoClassField *f;
4719                 MonoClass *klass = mono_class_from_mono_type (t);
4720
4721                 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
4722                 buffer_add_byte (buf, klass->enumtype);
4723                 buffer_add_typeid (buf, domain, klass);
4724
4725                 nfields = 0;
4726                 iter = NULL;
4727                 while ((f = mono_class_get_fields (klass, &iter))) {
4728                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4729                                 continue;
4730                         if (mono_field_is_deleted (f))
4731                                 continue;
4732                         nfields ++;
4733                 }
4734                 buffer_add_int (buf, nfields);
4735
4736                 iter = NULL;
4737                 while ((f = mono_class_get_fields (klass, &iter))) {
4738                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4739                                 continue;
4740                         if (mono_field_is_deleted (f))
4741                                 continue;
4742                         buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
4743                 }
4744                 break;
4745         }
4746         case MONO_TYPE_GENERICINST:
4747                 if (mono_type_generic_inst_is_valuetype (t)) {
4748                         goto handle_vtype;
4749                 } else {
4750                         goto handle_ref;
4751                 }
4752                 break;
4753         default:
4754                 NOT_IMPLEMENTED;
4755         }
4756 }
4757
4758 static void
4759 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
4760 {
4761         buffer_add_value_full (buf, t, addr, domain, FALSE);
4762 }
4763
4764 static ErrorCode
4765 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
4766 {
4767         int err;
4768         int type = decode_byte (buf, &buf, limit);
4769
4770         if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
4771                 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
4772                 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
4773                 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
4774                 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
4775                 char *name = mono_type_full_name (t);
4776                 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
4777                 g_free (name);
4778                 return ERR_INVALID_ARGUMENT;
4779         }
4780
4781         switch (t->type) {
4782         case MONO_TYPE_BOOLEAN:
4783                 *(guint8*)addr = decode_int (buf, &buf, limit);
4784                 break;
4785         case MONO_TYPE_CHAR:
4786                 *(gunichar2*)addr = decode_int (buf, &buf, limit);
4787                 break;
4788         case MONO_TYPE_I1:
4789                 *(gint8*)addr = decode_int (buf, &buf, limit);
4790                 break;
4791         case MONO_TYPE_U1:
4792                 *(guint8*)addr = decode_int (buf, &buf, limit);
4793                 break;
4794         case MONO_TYPE_I2:
4795                 *(gint16*)addr = decode_int (buf, &buf, limit);
4796                 break;
4797         case MONO_TYPE_U2:
4798                 *(guint16*)addr = decode_int (buf, &buf, limit);
4799                 break;
4800         case MONO_TYPE_I4:
4801                 *(gint32*)addr = decode_int (buf, &buf, limit);
4802                 break;
4803         case MONO_TYPE_U4:
4804                 *(guint32*)addr = decode_int (buf, &buf, limit);
4805                 break;
4806         case MONO_TYPE_I8:
4807                 *(gint64*)addr = decode_long (buf, &buf, limit);
4808                 break;
4809         case MONO_TYPE_U8:
4810                 *(guint64*)addr = decode_long (buf, &buf, limit);
4811                 break;
4812         case MONO_TYPE_R4:
4813                 *(guint32*)addr = decode_int (buf, &buf, limit);
4814                 break;
4815         case MONO_TYPE_R8:
4816                 *(guint64*)addr = decode_long (buf, &buf, limit);
4817                 break;
4818         case MONO_TYPE_PTR:
4819                 /* We send these as I8, so we get them back as such */
4820                 g_assert (type == MONO_TYPE_I8);
4821                 *(gssize*)addr = decode_long (buf, &buf, limit);
4822                 break;
4823         case MONO_TYPE_GENERICINST:
4824                 if (MONO_TYPE_ISSTRUCT (t)) {
4825                         /* The client sends these as a valuetype */
4826                         goto handle_vtype;
4827                 } else {
4828                         goto handle_ref;
4829                 }
4830                 break;
4831         case MONO_TYPE_I:
4832         case MONO_TYPE_U:
4833                 /* We send these as vtypes, so we get them back as such */
4834                 g_assert (type == MONO_TYPE_VALUETYPE);
4835                 /* Fall through */
4836                 handle_vtype:
4837         case MONO_TYPE_VALUETYPE: {
4838                 gboolean is_enum = decode_byte (buf, &buf, limit);
4839                 MonoClass *klass;
4840                 MonoClassField *f;
4841                 int nfields;
4842                 gpointer iter = NULL;
4843                 MonoDomain *d;
4844
4845                 /* Enums are sent as a normal vtype */
4846                 if (is_enum)
4847                         return ERR_NOT_IMPLEMENTED;
4848                 klass = decode_typeid (buf, &buf, limit, &d, &err);
4849                 if (err)
4850                         return err;
4851
4852                 if (klass != mono_class_from_mono_type (t))
4853                         return ERR_INVALID_ARGUMENT;
4854
4855                 nfields = decode_int (buf, &buf, limit);
4856                 while ((f = mono_class_get_fields (klass, &iter))) {
4857                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4858                                 continue;
4859                         if (mono_field_is_deleted (f))
4860                                 continue;
4861                         err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
4862                         if (err)
4863                                 return err;
4864                         nfields --;
4865                 }
4866                 g_assert (nfields == 0);
4867                 break;
4868         }
4869         handle_ref:
4870         default:
4871                 if (MONO_TYPE_IS_REFERENCE (t)) {
4872                         if (type == MONO_TYPE_OBJECT) {
4873                                 int objid = decode_objid (buf, &buf, limit);
4874                                 int err;
4875                                 MonoObject *obj;
4876
4877                                 err = get_object (objid, (MonoObject**)&obj);
4878                                 if (err)
4879                                         return err;
4880
4881                                 if (obj && !mono_class_is_assignable_from (mono_class_from_mono_type (t), obj->vtable->klass))
4882                                         return ERR_INVALID_ARGUMENT;
4883                                 if (obj && obj->vtable->domain != domain)
4884                                         return ERR_INVALID_ARGUMENT;
4885
4886                                 mono_gc_wbarrier_generic_store (addr, obj);
4887                         } else if (type == VALUE_TYPE_ID_NULL) {
4888                                 *(MonoObject**)addr = NULL;
4889                         } else {
4890                                 return ERR_INVALID_ARGUMENT;
4891                         }
4892                 } else {
4893                         NOT_IMPLEMENTED;
4894                 }
4895                 break;
4896         }
4897
4898         *endbuf = buf;
4899
4900         return 0;
4901 }
4902
4903 static void
4904 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
4905 {
4906         guint32 flags;
4907         int reg;
4908         guint8 *addr;
4909         gpointer reg_val;
4910
4911         flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4912         reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4913
4914         switch (flags) {
4915         case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
4916                 reg_val = mono_arch_context_get_int_reg (ctx, reg);
4917
4918                 buffer_add_value_full (buf, t, &reg_val, domain, as_vtype);
4919                 break;
4920         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
4921                 addr = mono_arch_context_get_int_reg (ctx, reg);
4922                 addr += (gint32)var->offset;
4923
4924                 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
4925
4926                 buffer_add_value_full (buf, t, addr, domain, as_vtype);
4927                 break;
4928         case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
4929                 NOT_IMPLEMENTED;
4930                 break;
4931         default:
4932                 g_assert_not_reached ();
4933         }
4934 }
4935
4936 static void
4937 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val)
4938 {
4939         guint32 flags;
4940         int reg, size;
4941         guint8 *addr;
4942
4943         flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4944         reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4945
4946         if (MONO_TYPE_IS_REFERENCE (t))
4947                 size = sizeof (gpointer);
4948         else
4949                 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
4950
4951         switch (flags) {
4952         case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
4953                 // FIXME: Can't set registers, so we disable linears
4954                 NOT_IMPLEMENTED;
4955                 break;
4956         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
4957                 addr = mono_arch_context_get_int_reg (ctx, reg);
4958                 addr += (gint32)var->offset;
4959
4960                 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
4961
4962                 // FIXME: Write barriers
4963                 memcpy (addr, val, size);
4964                 break;
4965         case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
4966                 NOT_IMPLEMENTED;
4967                 break;
4968         default:
4969                 g_assert_not_reached ();
4970         }
4971 }
4972
4973 static void
4974 clear_event_request (int req_id, int etype)
4975 {
4976         int i;
4977
4978         mono_loader_lock ();
4979         for (i = 0; i < event_requests->len; ++i) {
4980                 EventRequest *req = g_ptr_array_index (event_requests, i);
4981
4982                 if (req->id == req_id && req->event_kind == etype) {
4983                         if (req->event_kind == EVENT_KIND_BREAKPOINT)
4984                                 clear_breakpoint (req->info);
4985                         if (req->event_kind == EVENT_KIND_STEP)
4986                                 ss_destroy (req->info);
4987                         if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
4988                                 clear_breakpoint (req->info);
4989                         if (req->event_kind == EVENT_KIND_METHOD_EXIT)
4990                                 clear_breakpoint (req->info);
4991                         g_ptr_array_remove_index_fast (event_requests, i);
4992                         g_free (req);
4993                         break;
4994                 }
4995         }
4996         mono_loader_unlock ();
4997 }
4998
4999 static gboolean
5000 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
5001 {
5002         if (req->event_kind == EVENT_KIND_BREAKPOINT)
5003                 return breakpoint_matches_assembly (req->info, assembly);
5004         else {
5005                 int i, j;
5006
5007                 for (i = 0; i < req->nmodifiers; ++i) {
5008                         Modifier *m = &req->modifiers [i];
5009
5010                         if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
5011                                 return TRUE;
5012                         if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5013                                 for (j = 0; m->data.assemblies [j]; ++j)
5014                                         if (m->data.assemblies [j] == assembly)
5015                                                 return TRUE;
5016                         }
5017                 }
5018         }
5019
5020         return FALSE;
5021 }
5022
5023 /*
5024  * clear_event_requests_for_assembly:
5025  *
5026  *   Clear all events requests which reference ASSEMBLY.
5027  */
5028 static void
5029 clear_event_requests_for_assembly (MonoAssembly *assembly)
5030 {
5031         int i;
5032         gboolean found;
5033
5034         mono_loader_lock ();
5035         found = TRUE;
5036         while (found) {
5037                 found = FALSE;
5038                 for (i = 0; i < event_requests->len; ++i) {
5039                         EventRequest *req = g_ptr_array_index (event_requests, i);
5040
5041                         if (event_req_matches_assembly (req, assembly)) {
5042                                 clear_event_request (req->id, req->event_kind);
5043                                 found = TRUE;
5044                                 break;
5045                         }
5046                 }
5047         }
5048         mono_loader_unlock ();
5049 }
5050
5051 /*
5052  * type_comes_from_assembly:
5053  *
5054  *   GHRFunc that returns TRUE if klass comes from assembly
5055  */
5056 static gboolean
5057 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5058 {
5059         return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
5060 }
5061
5062 /*
5063  * clear_types_for_assembly:
5064  *
5065  *   Clears types from loaded_classes for a given assembly
5066  */
5067 static void
5068 clear_types_for_assembly (MonoAssembly *assembly)
5069 {
5070         MonoDomain *domain = mono_domain_get ();
5071         AgentDomainInfo *info = NULL;
5072
5073         mono_loader_lock ();
5074         info = get_agent_domain_info (domain);
5075         g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5076         mono_loader_unlock ();
5077 }
5078
5079 static void
5080 add_thread (gpointer key, gpointer value, gpointer user_data)
5081 {
5082         MonoInternalThread *thread = value;
5083         Buffer *buf = user_data;
5084
5085         buffer_add_objid (buf, (MonoObject*)thread);
5086 }
5087
5088 static ErrorCode
5089 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke)
5090 {
5091         guint8 *p = invoke->p;
5092         guint8 *end = invoke->endp;
5093         MonoMethod *m;
5094         int i, err, nargs;
5095         MonoMethodSignature *sig;
5096         guint8 **arg_buf;
5097         void **args;
5098         MonoObject *this, *res, *exc;
5099         MonoDomain *domain;
5100         guint8 *this_buf;
5101 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5102         MonoLMFExt ext;
5103 #endif
5104
5105         if (invoke->method) {
5106                 /* 
5107                  * Invoke this method directly, currently only Environment.Exit () is supported.
5108                  */
5109                 this = NULL;
5110                 DEBUG (1, fprintf (log_file, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)GetCurrentThreadId (), mono_method_full_name (invoke->method, TRUE), this ? this->vtable->klass->name : "<null>"));
5111                 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
5112                 g_assert_not_reached ();
5113         }
5114
5115         m = decode_methodid (p, &p, end, &domain, &err);
5116         if (err)
5117                 return err;
5118         sig = mono_method_signature (m);
5119
5120         if (m->klass->valuetype)
5121                 this_buf = g_alloca (mono_class_instance_size (m->klass));
5122         else
5123                 this_buf = g_alloca (sizeof (MonoObject*));
5124         if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
5125                 /* Should be null */
5126                 int type = decode_byte (p, &p, end);
5127                 if (type != VALUE_TYPE_ID_NULL)
5128                         return ERR_INVALID_ARGUMENT;
5129                 memset (this_buf, 0, mono_class_instance_size (m->klass));
5130         } else {
5131                 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
5132                 if (err)
5133                         return err;
5134         }
5135
5136         if (!m->klass->valuetype)
5137                 this = *(MonoObject**)this_buf;
5138         else
5139                 this = NULL;
5140
5141         DEBUG (1, fprintf (log_file, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)GetCurrentThreadId (), mono_method_full_name (m, TRUE), this ? this->vtable->klass->name : "<null>"));
5142
5143         if (this && this->vtable->domain != domain)
5144                 NOT_IMPLEMENTED;
5145
5146         if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
5147                 if (!strcmp (m->name, ".ctor")) {
5148                         if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
5149                                 return ERR_INVALID_ARGUMENT;
5150                         else
5151                                 this = mono_object_new (domain, m->klass);
5152                 } else {
5153                         return ERR_INVALID_ARGUMENT;
5154                 }
5155         }
5156
5157         if (this && !mono_class_is_assignable_from (m->klass, this->vtable->klass))
5158                 return ERR_INVALID_ARGUMENT;
5159
5160         nargs = decode_int (p, &p, end);
5161         if (nargs != sig->param_count)
5162                 return ERR_INVALID_ARGUMENT;
5163         /* Use alloca to get gc tracking */
5164         arg_buf = g_alloca (nargs * sizeof (gpointer));
5165         memset (arg_buf, 0, nargs * sizeof (gpointer));
5166         args = g_alloca (nargs * sizeof (gpointer));
5167         for (i = 0; i < nargs; ++i) {
5168                 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
5169                         err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
5170                         if (err)
5171                                 break;
5172
5173                         if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
5174                                 NOT_IMPLEMENTED;
5175                 } else {
5176                         arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
5177                         err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
5178                         if (err)
5179                                 break;
5180                         args [i] = arg_buf [i];
5181                 }
5182         }
5183
5184         if (i < nargs)
5185                 return err;
5186
5187         if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
5188                 tls->disable_breakpoints = TRUE;
5189         else
5190                 tls->disable_breakpoints = FALSE;
5191
5192         /* 
5193          * Add an LMF frame to link the stack frames on the invoke method with our caller.
5194          */
5195         /* FIXME: Move this to arch specific code */
5196 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5197         if (invoke->has_ctx) {
5198                 MonoLMF **lmf_addr;
5199
5200                 lmf_addr = mono_get_lmf_addr ();
5201
5202                 /* Setup our lmf */
5203                 memset (&ext, 0, sizeof (ext));
5204 #ifdef TARGET_AMD64
5205                 ext.lmf.previous_lmf = *(lmf_addr);
5206                 /* Mark that this is a MonoLMFExt */
5207                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5208                 ext.lmf.rsp = (gssize)&ext;
5209 #elif defined(TARGET_X86)
5210                 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
5211                 /* Mark that this is a MonoLMFExt */
5212                 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5213                 ext.lmf.ebp = (gssize)&ext;
5214 #elif defined(TARGET_ARM)
5215                 ext.lmf.previous_lmf = *(lmf_addr);
5216                 /* Mark that this is a MonoLMFExt */
5217                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5218 #elif defined(TARGET_POWERPC)
5219                 ext.lmf.previous_lmf = *(lmf_addr);
5220                 /* Mark that this is a MonoLMFExt */
5221                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5222                 ext.lmf.ebp = (gssize)&ext;
5223 #else
5224                 g_assert_not_reached ();
5225 #endif
5226
5227                 ext.debugger_invoke = TRUE;
5228                 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
5229
5230                 mono_set_lmf ((MonoLMF*)&ext);
5231         }
5232 #endif
5233
5234         if (m->klass->valuetype)
5235                 res = mono_runtime_invoke (m, this_buf, args, &exc);
5236         else
5237                 res = mono_runtime_invoke (m, this, args, &exc);
5238         if (exc) {
5239                 buffer_add_byte (buf, 0);
5240                 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
5241         } else {
5242                 buffer_add_byte (buf, 1);
5243                 if (sig->ret->type == MONO_TYPE_VOID) {
5244                         if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
5245                                 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
5246                         }
5247                         else
5248                                 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
5249                 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
5250                         buffer_add_value (buf, sig->ret, &res, domain);
5251                 } else if (mono_class_from_mono_type (sig->ret)->valuetype) {
5252                         g_assert (res);
5253                         buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
5254                 } else {
5255                         NOT_IMPLEMENTED;
5256                 }
5257         }
5258
5259         tls->disable_breakpoints = FALSE;
5260
5261 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5262         if (invoke->has_ctx)
5263                 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
5264 #endif
5265
5266         // FIXME: byref arguments
5267         // FIXME: varargs
5268         return ERR_NONE;
5269 }
5270
5271 /*
5272  * invoke_method:
5273  *
5274  *   Invoke the method given by tls->pending_invoke in the current thread.
5275  */
5276 static void
5277 invoke_method (void)
5278 {
5279         DebuggerTlsData *tls;
5280         InvokeData *invoke;
5281         int id;
5282         int err;
5283         Buffer buf;
5284         static void (*restore_context) (void *);
5285         MonoContext restore_ctx;
5286
5287         if (!restore_context)
5288                 restore_context = mono_get_restore_context ();
5289
5290         tls = TlsGetValue (debugger_tls_id);
5291         g_assert (tls);
5292
5293         /*
5294          * Store the `InvokeData *' in `tls->invoke' until we're done with
5295          * the invocation, so CMD_VM_ABORT_INVOKE can check it.
5296          */
5297
5298         mono_loader_lock ();
5299
5300         invoke = tls->pending_invoke;
5301         g_assert (invoke);
5302         tls->pending_invoke = NULL;
5303
5304         invoke->last_invoke = tls->invoke;
5305         tls->invoke = invoke;
5306
5307         mono_loader_unlock ();
5308
5309         tls->frames_up_to_date = FALSE;
5310
5311         id = invoke->id;
5312
5313         buffer_init (&buf, 128);
5314
5315         err = do_invoke_method (tls, &buf, invoke);
5316
5317         /* Start suspending before sending the reply */
5318         if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED))
5319                 suspend_vm ();
5320
5321         send_reply_packet (id, err, &buf);
5322         
5323         buffer_free (&buf);
5324
5325         memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
5326
5327         if (invoke->has_ctx)
5328                 save_thread_context (&restore_ctx);
5329
5330         if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
5331                 g_assert (tls->resume_count);
5332                 tls->resume_count -= invoke->suspend_count;
5333         }
5334
5335         DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
5336
5337         /*
5338          * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
5339          *
5340          * It is possible that ves_icall_System_Threading_Thread_Abort () was called
5341          * after the mono_runtime_invoke() already returned, but it doesn't matter
5342          * because we reset the abort here.
5343          */
5344
5345         mono_loader_lock ();
5346
5347         if (tls->abort_requested)
5348                 mono_thread_internal_reset_abort (tls->thread);
5349
5350         tls->invoke = tls->invoke->last_invoke;
5351         tls->abort_requested = FALSE;
5352
5353         mono_loader_unlock ();
5354
5355         g_free (invoke->p);
5356         g_free (invoke);
5357
5358         suspend_current ();
5359 }
5360
5361 static gboolean
5362 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
5363 {
5364         MonoThread *thread = value;
5365         DebuggerTlsData *tls;
5366         gboolean res;
5367
5368         mono_loader_lock ();
5369         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5370         g_assert (tls);
5371         res = tls->really_suspended;
5372         mono_loader_unlock ();
5373
5374         return res;
5375 }
5376
5377 static ErrorCode
5378 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
5379 {
5380         switch (command) {
5381         case CMD_VM_VERSION: {
5382                 char *build_info, *version;
5383
5384                 build_info = mono_get_runtime_build_info ();
5385                 version = g_strdup_printf ("mono %s", build_info);
5386
5387                 buffer_add_string (buf, version); /* vm version */
5388                 buffer_add_int (buf, MAJOR_VERSION);
5389                 buffer_add_int (buf, MINOR_VERSION);
5390                 g_free (build_info);
5391                 g_free (version);
5392                 break;
5393         }
5394         case CMD_VM_SET_PROTOCOL_VERSION: {
5395                 major_version = decode_int (p, &p, end);
5396                 minor_version = decode_int (p, &p, end);
5397                 protocol_version_set = TRUE;
5398                 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
5399                 break;
5400         }
5401         case CMD_VM_ALL_THREADS: {
5402                 // FIXME: Domains
5403                 mono_loader_lock ();
5404                 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
5405                 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
5406                 mono_loader_unlock ();
5407                 break;
5408         }
5409         case CMD_VM_SUSPEND:
5410                 suspend_vm ();
5411                 wait_for_suspend ();
5412                 break;
5413         case CMD_VM_RESUME:
5414                 if (suspend_count == 0)
5415                         return ERR_NOT_SUSPENDED;
5416                 resume_vm ();
5417                 break;
5418         case CMD_VM_DISPOSE:
5419                 /* Clear all event requests */
5420                 mono_loader_lock ();
5421                 while (event_requests->len > 0) {
5422                         EventRequest *req = g_ptr_array_index (event_requests, 0);
5423
5424                         clear_event_request (req->id, req->event_kind);
5425                 }
5426                 mono_loader_unlock ();
5427
5428                 while (suspend_count > 0)
5429                         resume_vm ();
5430                 disconnected = TRUE;
5431                 vm_start_event_sent = FALSE;
5432                 break;
5433         case CMD_VM_EXIT: {
5434                 MonoInternalThread *thread;
5435                 DebuggerTlsData *tls;
5436                 MonoClass *env_class;
5437                 MonoMethod *exit_method;
5438                 gpointer *args;
5439                 int exit_code;
5440
5441                 exit_code = decode_int (p, &p, end);
5442
5443                 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
5444
5445                 /* Have to send a reply before exiting */
5446                 send_reply_packet (id, 0, buf);
5447
5448                 /* Clear all event requests */
5449                 mono_loader_lock ();
5450                 while (event_requests->len > 0) {
5451                         EventRequest *req = g_ptr_array_index (event_requests, 0);
5452
5453                         clear_event_request (req->id, req->event_kind);
5454                 }
5455                 mono_loader_unlock ();
5456
5457                 /*
5458                  * The JDWP documentation says that the shutdown is not orderly. It doesn't
5459                  * specify whenever a VM_DEATH event is sent. We currently do an orderly
5460                  * shutdown by hijacking a thread to execute Environment.Exit (). This is
5461                  * better than doing the shutdown ourselves, since it avoids various races.
5462                  */
5463
5464                 suspend_vm ();
5465                 wait_for_suspend ();
5466
5467                 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
5468                 if (env_class)
5469                         exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
5470
5471                 mono_loader_lock ();
5472                 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
5473                 mono_loader_unlock ();
5474
5475                 if (thread && exit_method) {
5476                         mono_loader_lock ();
5477                         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5478                         mono_loader_unlock ();
5479
5480                         args = g_new0 (gpointer, 1);
5481                         args [0] = g_malloc (sizeof (int));
5482                         *(int*)(args [0]) = exit_code;
5483
5484                         tls->pending_invoke = g_new0 (InvokeData, 1);
5485                         tls->pending_invoke->method = exit_method;
5486                         tls->pending_invoke->args = args;
5487
5488                         while (suspend_count > 0)
5489                                 resume_vm ();
5490                 } else {
5491                         /* 
5492                          * No thread found, do it ourselves.
5493                          * FIXME: This can race with normal shutdown etc.
5494                          */
5495                         while (suspend_count > 0)
5496                                 resume_vm ();
5497
5498                         mono_runtime_set_shutting_down ();
5499
5500                         mono_threads_set_shutting_down ();
5501
5502                         /* Suspend all managed threads since the runtime is going away */
5503                         DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
5504                         mono_thread_suspend_all_other_threads ();
5505                         DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
5506                         mono_runtime_quit ();
5507 #ifdef HOST_WIN32
5508                         shutdown (conn_fd, SD_BOTH);
5509 #else
5510                         shutdown (conn_fd, SHUT_RDWR);
5511 #endif
5512                         DEBUG(1, fprintf (log_file, "Exiting...\n"));
5513
5514                         exit (exit_code);
5515                 }
5516                 break;
5517         }               
5518         case CMD_VM_INVOKE_METHOD: {
5519                 int objid = decode_objid (p, &p, end);
5520                 MonoThread *thread;
5521                 DebuggerTlsData *tls;
5522                 int err, flags;
5523
5524                 err = get_object (objid, (MonoObject**)&thread);
5525                 if (err)
5526                         return err;
5527
5528                 flags = decode_int (p, &p, end);
5529
5530                 // Wait for suspending if it already started
5531                 if (suspend_count)
5532                         wait_for_suspend ();
5533                 if (!is_suspended ())
5534                         return ERR_NOT_SUSPENDED;
5535
5536                 mono_loader_lock ();
5537                 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
5538                 mono_loader_unlock ();
5539                 g_assert (tls);
5540
5541                 if (!tls->really_suspended)
5542                         /* The thread is still running native code, can't do invokes */
5543                         return ERR_NOT_SUSPENDED;
5544
5545                 /* 
5546                  * Store the invoke data into tls, the thread will execute it after it is
5547                  * resumed.
5548                  */
5549                 if (tls->pending_invoke)
5550                         NOT_IMPLEMENTED;
5551                 tls->pending_invoke = g_new0 (InvokeData, 1);
5552                 tls->pending_invoke->id = id;
5553                 tls->pending_invoke->flags = flags;
5554                 tls->pending_invoke->p = g_malloc (end - p);
5555                 memcpy (tls->pending_invoke->p, p, end - p);
5556                 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
5557                 tls->pending_invoke->suspend_count = suspend_count;
5558
5559                 if (flags & INVOKE_FLAG_SINGLE_THREADED)
5560                         resume_thread (THREAD_TO_INTERNAL (thread));
5561                 else
5562                         resume_vm ();
5563                 break;
5564         }
5565         case CMD_VM_ABORT_INVOKE: {
5566                 int objid = decode_objid (p, &p, end);
5567                 MonoThread *thread;
5568                 DebuggerTlsData *tls;
5569                 int invoke_id, err;
5570
5571                 err = get_object (objid, (MonoObject**)&thread);
5572                 if (err)
5573                         return err;
5574
5575                 invoke_id = decode_int (p, &p, end);
5576
5577                 mono_loader_lock ();
5578                 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
5579                 g_assert (tls);
5580
5581                 if (tls->abort_requested) {
5582                         mono_loader_unlock ();
5583                         break;
5584                 }
5585
5586                 /*
5587                  * Check whether we're still inside the mono_runtime_invoke() and that it's
5588                  * actually the correct invocation.
5589                  *
5590                  * Careful, we do not stop the thread that's doing the invocation, so we can't
5591                  * inspect its stack.  However, invoke_method() also acquires the loader lock
5592                  * when it's done, so we're safe here.
5593                  *
5594                  */
5595
5596                 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
5597                         mono_loader_unlock ();
5598                         return ERR_NO_INVOCATION;
5599                 }
5600
5601                 tls->abort_requested = TRUE;
5602
5603                 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
5604                 mono_loader_unlock ();
5605                 break;
5606         }
5607
5608         default:
5609                 return ERR_NOT_IMPLEMENTED;
5610         }
5611
5612         return ERR_NONE;
5613 }
5614
5615 static ErrorCode
5616 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5617 {
5618         int err;
5619         MonoError error;
5620
5621         switch (command) {
5622         case CMD_EVENT_REQUEST_SET: {
5623                 EventRequest *req;
5624                 int i, event_kind, suspend_policy, nmodifiers, mod;
5625                 MonoMethod *method;
5626                 long location = 0;
5627                 MonoThread *step_thread;
5628                 int size = 0, depth = 0, step_thread_id = 0;
5629                 MonoDomain *domain;
5630
5631                 event_kind = decode_byte (p, &p, end);
5632                 suspend_policy = decode_byte (p, &p, end);
5633                 nmodifiers = decode_byte (p, &p, end);
5634
5635                 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
5636                 req->id = InterlockedIncrement (&event_request_id);
5637                 req->event_kind = event_kind;
5638                 req->suspend_policy = suspend_policy;
5639                 req->nmodifiers = nmodifiers;
5640
5641                 method = NULL;
5642                 for (i = 0; i < nmodifiers; ++i) {
5643                         mod = decode_byte (p, &p, end);
5644
5645                         req->modifiers [i].kind = mod;
5646                         if (mod == MOD_KIND_COUNT) {
5647                                 req->modifiers [i].data.count = decode_int (p, &p, end);
5648                         } else if (mod == MOD_KIND_LOCATION_ONLY) {
5649                                 method = decode_methodid (p, &p, end, &domain, &err);
5650                                 if (err)
5651                                         return err;
5652                                 location = decode_long (p, &p, end);
5653                         } else if (mod == MOD_KIND_STEP) {
5654                                 step_thread_id = decode_id (p, &p, end);
5655                                 size = decode_int (p, &p, end);
5656                                 depth = decode_int (p, &p, end);
5657                         } else if (mod == MOD_KIND_THREAD_ONLY) {
5658                                 int id = decode_id (p, &p, end);
5659
5660                                 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
5661                                 if (err) {
5662                                         g_free (req);
5663                                         return err;
5664                                 }
5665                         } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
5666                                 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
5667
5668                                 if (err)
5669                                         return err;
5670                                 req->modifiers [i].caught = decode_byte (p, &p, end);
5671                                 req->modifiers [i].uncaught = decode_byte (p, &p, end);
5672                                 DEBUG(1, fprintf (log_file, "[dbg] \tEXCEPTION_ONLY filter (%s%s%s).\n", exc_class ? exc_class->name : "all", req->modifiers [i].caught ? ", caught" : "", req->modifiers [i].uncaught ? ", uncaught" : ""));
5673                                 if (exc_class) {
5674                                         req->modifiers [i].data.exc_class = exc_class;
5675
5676                                         if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
5677                                                 g_free (req);
5678                                                 return ERR_INVALID_ARGUMENT;
5679                                         }
5680                                 }
5681                         } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
5682                                 int n = decode_int (p, &p, end);
5683                                 int j;
5684
5685                                 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
5686                                 for (j = 0; j < n; ++j) {
5687                                         req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
5688                                         if (err) {
5689                                                 g_free (req->modifiers [i].data.assemblies);
5690                                                 return err;
5691                                         }
5692                                 }
5693                         } else {
5694                                 g_free (req);
5695                                 return ERR_NOT_IMPLEMENTED;
5696                         }
5697                 }
5698
5699                 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
5700                         g_assert (method);
5701
5702                         req->info = set_breakpoint (method, location, req, &error);
5703                         if (!mono_error_ok (&error)) {
5704                                 g_free (req);
5705                                 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
5706                                 mono_error_cleanup (&error);
5707                                 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
5708                         }
5709                 } else if (req->event_kind == EVENT_KIND_STEP) {
5710                         g_assert (step_thread_id);
5711
5712                         err = get_object (step_thread_id, (MonoObject**)&step_thread);
5713                         if (err) {
5714                                 g_free (req);
5715                                 return err;
5716                         }
5717
5718                         err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
5719                         if (err) {
5720                                 g_free (req);
5721                                 return err;
5722                         }
5723                 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
5724                         req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
5725                 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
5726                         req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
5727                 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
5728                 } else {
5729                         if (req->nmodifiers) {
5730                                 g_free (req);
5731                                 return ERR_NOT_IMPLEMENTED;
5732                         }
5733                 }
5734
5735                 mono_loader_lock ();
5736                 g_ptr_array_add (event_requests, req);
5737                 mono_loader_unlock ();
5738
5739                 buffer_add_int (buf, req->id);
5740                 break;
5741         }
5742         case CMD_EVENT_REQUEST_CLEAR: {
5743                 int etype = decode_byte (p, &p, end);
5744                 int req_id = decode_int (p, &p, end);
5745
5746                 // FIXME: Make a faster mapping from req_id to request
5747                 mono_loader_lock ();
5748                 clear_event_request (req_id, etype);
5749                 mono_loader_unlock ();
5750                 break;
5751         }
5752         case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
5753                 int i;
5754
5755                 mono_loader_lock ();
5756                 i = 0;
5757                 while (i < event_requests->len) {
5758                         EventRequest *req = g_ptr_array_index (event_requests, i);
5759
5760                         if (req->event_kind == EVENT_KIND_BREAKPOINT) {
5761                                 clear_breakpoint (req->info);
5762
5763                                 g_ptr_array_remove_index_fast (event_requests, i);
5764                                 g_free (req);
5765                         } else {
5766                                 i ++;
5767                         }
5768                 }
5769                 mono_loader_unlock ();
5770                 break;
5771         }
5772         default:
5773                 return ERR_NOT_IMPLEMENTED;
5774         }
5775
5776         return ERR_NONE;
5777 }
5778
5779 static ErrorCode
5780 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5781 {
5782         int err;
5783         MonoDomain *domain;
5784
5785         switch (command) {
5786         case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
5787                 buffer_add_domainid (buf, mono_get_root_domain ());
5788                 break;
5789         }
5790         case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
5791                 domain = decode_domainid (p, &p, end, NULL, &err);
5792                 if (err)
5793                         return err;
5794                 buffer_add_string (buf, domain->friendly_name);
5795                 break;
5796         }
5797         case CMD_APPDOMAIN_GET_ASSEMBLIES: {
5798                 GSList *tmp;
5799                 MonoAssembly *ass;
5800                 int count;
5801
5802                 domain = decode_domainid (p, &p, end, NULL, &err);
5803                 if (err)
5804                         return err;
5805                 mono_loader_lock ();
5806                 count = 0;
5807                 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
5808                         count ++;
5809                 }
5810                 buffer_add_int (buf, count);
5811                 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
5812                         ass = tmp->data;
5813                         buffer_add_assemblyid (buf, domain, ass);
5814                 }
5815                 mono_loader_unlock ();
5816                 break;
5817         }
5818         case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
5819                 domain = decode_domainid (p, &p, end, NULL, &err);
5820                 if (err)
5821                         return err;
5822
5823                 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
5824                 break;
5825         }
5826         case CMD_APPDOMAIN_GET_CORLIB: {
5827                 domain = decode_domainid (p, &p, end, NULL, &err);
5828                 if (err)
5829                         return err;
5830
5831                 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
5832                 break;
5833         }
5834         case CMD_APPDOMAIN_CREATE_STRING: {
5835                 char *s;
5836                 MonoString *o;
5837
5838                 domain = decode_domainid (p, &p, end, NULL, &err);
5839                 if (err)
5840                         return err;
5841                 s = decode_string (p, &p, end);
5842
5843                 o = mono_string_new (domain, s);
5844                 buffer_add_objid (buf, (MonoObject*)o);
5845                 break;
5846         }
5847         case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
5848                 MonoClass *klass;
5849                 MonoDomain *domain2;
5850                 MonoObject *o;
5851
5852                 domain = decode_domainid (p, &p, end, NULL, &err);
5853                 if (err)
5854                         return err;
5855                 klass = decode_typeid (p, &p, end, &domain2, &err);
5856                 if (err)
5857                         return err;
5858
5859                 // FIXME:
5860                 g_assert (domain == domain2);
5861
5862                 o = mono_object_new (domain, klass);
5863
5864                 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
5865                 if (err)
5866                         return err;
5867
5868                 buffer_add_objid (buf, o);
5869                 break;
5870         }
5871         default:
5872                 return ERR_NOT_IMPLEMENTED;
5873         }
5874
5875         return ERR_NONE;
5876 }
5877
5878 static ErrorCode
5879 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5880 {
5881         int err;
5882         MonoAssembly *ass;
5883         MonoDomain *domain;
5884
5885         ass = decode_assemblyid (p, &p, end, &domain, &err);
5886         if (err)
5887                 return err;
5888
5889         switch (command) {
5890         case CMD_ASSEMBLY_GET_LOCATION: {
5891                 buffer_add_string (buf, mono_image_get_filename (ass->image));
5892                 break;                  
5893         }
5894         case CMD_ASSEMBLY_GET_ENTRY_POINT: {
5895                 guint32 token;
5896                 MonoMethod *m;
5897
5898                 if (ass->image->dynamic) {
5899                         buffer_add_id (buf, 0);
5900                 } else {
5901                         token = mono_image_get_entry_point (ass->image);
5902                         if (token == 0) {
5903                                 buffer_add_id (buf, 0);
5904                         } else {
5905                                 m = mono_get_method (ass->image, token, NULL);
5906                                 buffer_add_methodid (buf, domain, m);
5907                         }
5908                 }
5909                 break;                  
5910         }
5911         case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
5912                 buffer_add_moduleid (buf, domain, ass->image);
5913                 break;
5914         }
5915         case CMD_ASSEMBLY_GET_OBJECT: {
5916                 MonoObject *o = (MonoObject*)mono_assembly_get_object (mono_domain_get (), ass);
5917                 buffer_add_objid (buf, o);
5918                 break;
5919         }
5920         case CMD_ASSEMBLY_GET_TYPE: {
5921                 char *s = decode_string (p, &p, end);
5922                 gboolean ignorecase = decode_byte (p, &p, end);
5923                 MonoTypeNameParse info;
5924                 MonoType *t;
5925                 gboolean type_resolve;
5926
5927                 if (!mono_reflection_parse_type (s, &info)) {
5928                         t = NULL;
5929                 } else {
5930                         if (info.assembly.name)
5931                                 NOT_IMPLEMENTED;
5932                         t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
5933                 }
5934                 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
5935                 mono_reflection_free_type_info (&info);
5936                 g_free (s);
5937
5938                 break;
5939         }
5940         case CMD_ASSEMBLY_GET_NAME: {
5941                 gchar *name;
5942                 MonoAssembly *mass = ass;
5943
5944                 name = g_strdup_printf (
5945                   "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
5946                   mass->aname.name,
5947                   mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
5948                   mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
5949                   mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
5950                   (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
5951
5952                 buffer_add_string (buf, name);
5953                 g_free (name);
5954                 break;
5955         }
5956         default:
5957                 return ERR_NOT_IMPLEMENTED;
5958         }
5959
5960         return ERR_NONE;
5961 }
5962
5963 static ErrorCode
5964 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5965 {
5966         int err;
5967         MonoDomain *domain;
5968
5969         switch (command) {
5970         case CMD_MODULE_GET_INFO: {
5971                 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
5972                 char *basename;
5973
5974                 basename = g_path_get_basename (image->name);
5975                 buffer_add_string (buf, basename); // name
5976                 buffer_add_string (buf, image->module_name); // scopename
5977                 buffer_add_string (buf, image->name); // fqname
5978                 buffer_add_string (buf, mono_image_get_guid (image)); // guid
5979                 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
5980                 g_free (basename);
5981                 break;                  
5982         }
5983         default:
5984                 return ERR_NOT_IMPLEMENTED;
5985         }
5986
5987         return ERR_NONE;
5988 }
5989
5990 static void
5991 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
5992 {
5993         if (val && val->vtable->klass == mono_defaults.monotype_class) {
5994                 /* Special case these so the client doesn't have to handle Type objects */
5995                 
5996                 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
5997                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
5998         } else if (MONO_TYPE_IS_REFERENCE (t))
5999                 buffer_add_value (buf, t, &val, domain);
6000         else
6001                 buffer_add_value (buf, t, mono_object_unbox (val), domain);
6002 }
6003
6004 static void
6005 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
6006 {
6007         int i, j;
6008         int nattrs = 0;
6009
6010         if (!cinfo) {
6011                 buffer_add_int (buf, 0);
6012                 return;
6013         }
6014
6015         for (i = 0; i < cinfo->num_attrs; ++i) {
6016                 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
6017                         nattrs ++;
6018         }
6019         buffer_add_int (buf, nattrs);
6020
6021         for (i = 0; i < cinfo->num_attrs; ++i) {
6022                 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
6023                 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
6024                         MonoArray *typed_args, *named_args;
6025                         MonoType *t;
6026                         CattrNamedArg *arginfo;
6027
6028                         mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
6029
6030                         buffer_add_methodid (buf, domain, attr->ctor);
6031
6032                         /* Ctor args */
6033                         if (typed_args) {
6034                                 buffer_add_int (buf, mono_array_length (typed_args));
6035                                 for (j = 0; j < mono_array_length (typed_args); ++j) {
6036                                         MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
6037
6038                                         t = mono_method_signature (attr->ctor)->params [j];
6039
6040                                         buffer_add_cattr_arg (buf, t, domain, val);
6041                                 }
6042                         } else {
6043                                 buffer_add_int (buf, 0);
6044                         }
6045
6046                         /* Named args */
6047                         if (named_args) {
6048                                 buffer_add_int (buf, mono_array_length (named_args));
6049
6050                                 for (j = 0; j < mono_array_length (named_args); ++j) {
6051                                         MonoObject *val = mono_array_get (named_args, MonoObject*, j);
6052
6053                                         if (arginfo [j].prop) {
6054                                                 buffer_add_byte (buf, 0x54);
6055                                                 buffer_add_propertyid (buf, domain, arginfo [j].prop);
6056                                         } else if (arginfo [j].field) {
6057                                                 buffer_add_byte (buf, 0x53);
6058                                         } else {
6059                                                 g_assert_not_reached ();
6060                                         }
6061
6062                                         buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
6063                                 }
6064                         } else {
6065                                 buffer_add_int (buf, 0);
6066                         }
6067                 }
6068         }
6069 }
6070
6071 static ErrorCode
6072 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
6073 {
6074         MonoClass *nested;
6075         MonoType *type;
6076         gpointer iter;
6077         guint8 b;
6078         int err, nnested;
6079         char *name;
6080
6081         switch (command) {
6082         case CMD_TYPE_GET_INFO: {
6083                 buffer_add_string (buf, klass->name_space);
6084                 buffer_add_string (buf, klass->name);
6085                 // FIXME: byref
6086                 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
6087                 buffer_add_string (buf, name);
6088                 g_free (name);
6089                 buffer_add_assemblyid (buf, domain, klass->image->assembly);
6090                 buffer_add_moduleid (buf, domain, klass->image);
6091                 buffer_add_typeid (buf, domain, klass->parent);
6092                 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
6093                         buffer_add_typeid (buf, domain, klass->element_class);
6094                 else
6095                         buffer_add_id (buf, 0);
6096                 buffer_add_int (buf, klass->type_token);
6097                 buffer_add_byte (buf, klass->rank);
6098                 buffer_add_int (buf, klass->flags);
6099                 b = 0;
6100                 type = &klass->byval_arg;
6101                 // FIXME: Can't decide whenever a class represents a byref type
6102                 if (FALSE)
6103                         b |= (1 << 0);
6104                 if (type->type == MONO_TYPE_PTR)
6105                         b |= (1 << 1);
6106                 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
6107                         b |= (1 << 2);
6108                 if (type->type == MONO_TYPE_VALUETYPE)
6109                         b |= (1 << 3);
6110                 if (klass->enumtype)
6111                         b |= (1 << 4);
6112                 buffer_add_byte (buf, b);
6113                 nnested = 0;
6114                 iter = NULL;
6115                 while ((nested = mono_class_get_nested_types (klass, &iter)))
6116                         nnested ++;
6117                 buffer_add_int (buf, nnested);
6118                 iter = NULL;
6119                 while ((nested = mono_class_get_nested_types (klass, &iter)))
6120                         buffer_add_typeid (buf, domain, nested);
6121                 break;
6122         }
6123         case CMD_TYPE_GET_METHODS: {
6124                 int nmethods;
6125                 int i = 0;
6126                 gpointer iter = NULL;
6127                 MonoMethod *m;
6128
6129                 mono_class_setup_methods (klass);
6130
6131                 nmethods = mono_class_num_methods (klass);
6132
6133                 buffer_add_int (buf, nmethods);
6134
6135                 while ((m = mono_class_get_methods (klass, &iter))) {
6136                         buffer_add_methodid (buf, domain, m);
6137                         i ++;
6138                 }
6139                 g_assert (i == nmethods);
6140                 break;
6141         }
6142         case CMD_TYPE_GET_FIELDS: {
6143                 int nfields;
6144                 int i = 0;
6145                 gpointer iter = NULL;
6146                 MonoClassField *f;
6147
6148                 nfields = mono_class_num_fields (klass);
6149
6150                 buffer_add_int (buf, nfields);
6151
6152                 while ((f = mono_class_get_fields (klass, &iter))) {
6153                         buffer_add_fieldid (buf, domain, f);
6154                         buffer_add_string (buf, f->name);
6155                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
6156                         buffer_add_int (buf, f->type->attrs);
6157                         i ++;
6158                 }
6159                 g_assert (i == nfields);
6160                 break;
6161         }
6162         case CMD_TYPE_GET_PROPERTIES: {
6163                 int nprops;
6164                 int i = 0;
6165                 gpointer iter = NULL;
6166                 MonoProperty *p;
6167
6168                 nprops = mono_class_num_properties (klass);
6169
6170                 buffer_add_int (buf, nprops);
6171
6172                 while ((p = mono_class_get_properties (klass, &iter))) {
6173                         buffer_add_propertyid (buf, domain, p);
6174                         buffer_add_string (buf, p->name);
6175                         buffer_add_methodid (buf, domain, p->get);
6176                         buffer_add_methodid (buf, domain, p->set);
6177                         buffer_add_int (buf, p->attrs);
6178                         i ++;
6179                 }
6180                 g_assert (i == nprops);
6181                 break;
6182         }
6183         case CMD_TYPE_GET_CATTRS: {
6184                 MonoClass *attr_klass = decode_typeid (p, &p, end, NULL, &err);
6185                 MonoCustomAttrInfo *cinfo;
6186
6187                 cinfo = mono_custom_attrs_from_class (klass);
6188
6189                 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
6190                 break;
6191         }
6192         case CMD_TYPE_GET_FIELD_CATTRS: {
6193                 MonoClass *attr_klass;
6194                 MonoCustomAttrInfo *cinfo;
6195                 MonoClassField *field;
6196
6197                 field = decode_fieldid (p, &p, end, NULL, &err);
6198                 if (err)
6199                         return err;
6200                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
6201                 if (err)
6202                         return err;
6203
6204                 cinfo = mono_custom_attrs_from_field (klass, field);
6205
6206                 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
6207                 break;
6208         }
6209         case CMD_TYPE_GET_PROPERTY_CATTRS: {
6210                 MonoClass *attr_klass;
6211                 MonoCustomAttrInfo *cinfo;
6212                 MonoProperty *prop;
6213
6214                 prop = decode_propertyid (p, &p, end, NULL, &err);
6215                 if (err)
6216                         return err;
6217                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
6218                 if (err)
6219                         return err;
6220
6221                 cinfo = mono_custom_attrs_from_property (klass, prop);
6222
6223                 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
6224                 break;
6225         }
6226         case CMD_TYPE_GET_VALUES:
6227         case CMD_TYPE_GET_VALUES_2: {
6228                 guint8 *val;
6229                 MonoClassField *f;
6230                 MonoVTable *vtable;
6231                 MonoClass *k;
6232                 int len, i;
6233                 gboolean found;
6234                 MonoThread *thread_obj;
6235                 MonoInternalThread *thread = NULL;
6236                 guint32 special_static_type;
6237
6238                 if (command == CMD_TYPE_GET_VALUES_2) {
6239                         int objid = decode_objid (p, &p, end);
6240                         int err;
6241
6242                         err = get_object (objid, (MonoObject**)&thread_obj);
6243                         if (err)
6244                                 return err;
6245
6246                         thread = THREAD_TO_INTERNAL (thread_obj);
6247                 }
6248
6249                 len = decode_int (p, &p, end);
6250                 for (i = 0; i < len; ++i) {
6251                         f = decode_fieldid (p, &p, end, NULL, &err);
6252                         if (err)
6253                                 return err;
6254
6255                         if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
6256                                 return ERR_INVALID_FIELDID;
6257                         special_static_type = mono_class_field_get_special_static_type (f);
6258                         if (special_static_type != SPECIAL_STATIC_NONE) {
6259                                 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
6260                                         return ERR_INVALID_FIELDID;
6261                         }
6262
6263                         /* Check that the field belongs to the object */
6264                         found = FALSE;
6265                         for (k = klass; k; k = k->parent) {
6266                                 if (k == f->parent) {
6267                                         found = TRUE;
6268                                         break;
6269                                 }
6270                         }
6271                         if (!found)
6272                                 return ERR_INVALID_FIELDID;
6273
6274                         vtable = mono_class_vtable (domain, f->parent);
6275                         val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6276                         mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
6277                         buffer_add_value (buf, f->type, val, domain);
6278                         g_free (val);
6279                 }
6280                 break;
6281         }
6282         case CMD_TYPE_SET_VALUES: {
6283                 guint8 *val;
6284                 MonoClassField *f;
6285                 MonoVTable *vtable;
6286                 MonoClass *k;
6287                 int len, i;
6288                 gboolean found;
6289
6290                 len = decode_int (p, &p, end);
6291                 for (i = 0; i < len; ++i) {
6292                         f = decode_fieldid (p, &p, end, NULL, &err);
6293                         if (err)
6294                                 return err;
6295
6296                         if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
6297                                 return ERR_INVALID_FIELDID;
6298                         if (mono_class_field_is_special_static (f))
6299                                 return ERR_INVALID_FIELDID;
6300
6301                         /* Check that the field belongs to the object */
6302                         found = FALSE;
6303                         for (k = klass; k; k = k->parent) {
6304                                 if (k == f->parent) {
6305                                         found = TRUE;
6306                                         break;
6307                                 }
6308                         }
6309                         if (!found)
6310                                 return ERR_INVALID_FIELDID;
6311
6312                         // FIXME: Check for literal/const
6313
6314                         vtable = mono_class_vtable (domain, f->parent);
6315                         val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6316                         err = decode_value (f->type, domain, val, p, &p, end);
6317                         if (err) {
6318                                 g_free (val);
6319                                 return err;
6320                         }
6321                         if (MONO_TYPE_IS_REFERENCE (f->type))
6322                                 mono_field_static_set_value (vtable, f, *(gpointer*)val);
6323                         else
6324                                 mono_field_static_set_value (vtable, f, val);
6325                         g_free (val);
6326                 }
6327                 break;
6328         }
6329         case CMD_TYPE_GET_OBJECT: {
6330                 MonoObject *o = (MonoObject*)mono_type_get_object (mono_domain_get (), &klass->byval_arg);
6331                 buffer_add_objid (buf, o);
6332                 break;
6333         }
6334         case CMD_TYPE_GET_SOURCE_FILES:
6335         case CMD_TYPE_GET_SOURCE_FILES_2: {
6336                 gpointer iter = NULL;
6337                 MonoMethod *method;
6338                 char *source_file, *base;
6339                 GPtrArray *files;
6340                 int i;
6341
6342                 files = g_ptr_array_new ();
6343
6344                 while ((method = mono_class_get_methods (klass, &iter))) {
6345                         MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6346
6347                         if (minfo) {
6348                                 mono_debug_symfile_get_line_numbers (minfo, &source_file, NULL, NULL, NULL);
6349                                 if (!source_file)
6350                                         continue;
6351
6352                                 for (i = 0; i < files->len; ++i)
6353                                         if (!strcmp (g_ptr_array_index (files, i), source_file))
6354                                                 break;
6355                                 if (i == files->len)
6356                                         g_ptr_array_add (files, g_strdup (source_file));
6357                                 g_free (source_file);
6358                         }
6359                 }
6360
6361                 buffer_add_int (buf, files->len);
6362                 for (i = 0; i < files->len; ++i) {
6363                         source_file = g_ptr_array_index (files, i);
6364                         if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
6365                                 buffer_add_string (buf, source_file);
6366                         } else {
6367                                 base = g_path_get_basename (source_file);
6368                                 buffer_add_string (buf, base);
6369                                 g_free (base);
6370                         }
6371                         g_free (source_file);
6372                 }
6373                 g_ptr_array_free (files, TRUE);
6374                 break;
6375         }
6376         case CMD_TYPE_IS_ASSIGNABLE_FROM: {
6377                 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
6378
6379                 if (err)
6380                         return err;
6381                 if (mono_class_is_assignable_from (klass, oklass))
6382                         buffer_add_byte (buf, 1);
6383                 else
6384                         buffer_add_byte (buf, 0);
6385                 break;
6386         }
6387         default:
6388                 return ERR_NOT_IMPLEMENTED;
6389         }
6390
6391         return ERR_NONE;
6392 }
6393
6394 static ErrorCode
6395 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6396 {
6397         MonoClass *klass;
6398         MonoDomain *old_domain;
6399         MonoDomain *domain;
6400         int err;
6401
6402         klass = decode_typeid (p, &p, end, &domain, &err);
6403         if (err)
6404                 return err;
6405
6406         old_domain = mono_domain_get ();
6407
6408         mono_domain_set (domain, TRUE);
6409
6410         err = type_commands_internal (command, klass, domain, p, end, buf);
6411
6412         mono_domain_set (old_domain, TRUE);
6413
6414         return err;
6415 }
6416
6417 static ErrorCode
6418 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
6419 {
6420         MonoMethodHeader *header;
6421
6422         switch (command) {
6423         case CMD_METHOD_GET_NAME: {
6424                 buffer_add_string (buf, method->name);
6425                 break;                  
6426         }
6427         case CMD_METHOD_GET_DECLARING_TYPE: {
6428                 buffer_add_typeid (buf, domain, method->klass);
6429                 break;
6430         }
6431         case CMD_METHOD_GET_DEBUG_INFO: {
6432                 MonoDebugMethodInfo *minfo;
6433                 char *source_file;
6434                 int i, n_il_offsets;
6435                 int *il_offsets;
6436                 int *line_numbers;
6437
6438                 header = mono_method_get_header (method);
6439                 if (!header) {
6440                         buffer_add_int (buf, 0);
6441                         buffer_add_string (buf, "");
6442                         buffer_add_int (buf, 0);
6443                         break;
6444                 }
6445
6446                 minfo = mono_debug_lookup_method (method);
6447                 if (!minfo) {
6448                         buffer_add_int (buf, header->code_size);
6449                         buffer_add_string (buf, "");
6450                         buffer_add_int (buf, 0);
6451                         mono_metadata_free_mh (header);
6452                         break;
6453                 }
6454
6455                 mono_debug_symfile_get_line_numbers (minfo, &source_file, &n_il_offsets, &il_offsets, &line_numbers);
6456                 buffer_add_int (buf, header->code_size);
6457                 buffer_add_string (buf, source_file);
6458                 buffer_add_int (buf, n_il_offsets);
6459                 //printf ("Line number table for method %s:\n", mono_method_full_name (method,  TRUE));
6460                 for (i = 0; i < n_il_offsets; ++i) {
6461                         //printf ("IL%d -> %d\n", il_offsets [i], line_numbers [i]);
6462                         buffer_add_int (buf, il_offsets [i]);
6463                         buffer_add_int (buf, line_numbers [i]);
6464                 }
6465                 g_free (source_file);
6466                 g_free (il_offsets);
6467                 g_free (line_numbers);
6468                 mono_metadata_free_mh (header);
6469                 break;
6470         }
6471         case CMD_METHOD_GET_PARAM_INFO: {
6472                 MonoMethodSignature *sig = mono_method_signature (method);
6473                 guint32 i;
6474                 char **names;
6475
6476                 /* FIXME: mono_class_from_mono_type () and byrefs */
6477
6478                 /* FIXME: Use a smaller encoding */
6479                 buffer_add_int (buf, sig->call_convention);
6480                 buffer_add_int (buf, sig->param_count);
6481                 buffer_add_int (buf, sig->generic_param_count);
6482                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
6483                 for (i = 0; i < sig->param_count; ++i) {
6484                         /* FIXME: vararg */
6485                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
6486                 }
6487
6488                 /* Emit parameter names */
6489                 names = g_new (char *, sig->param_count);
6490                 mono_method_get_param_names (method, (const char **) names);
6491                 for (i = 0; i < sig->param_count; ++i)
6492                         buffer_add_string (buf, names [i]);
6493                 g_free (names);
6494
6495                 break;
6496         }
6497         case CMD_METHOD_GET_LOCALS_INFO: {
6498                 int i, j, num_locals;
6499                 MonoDebugLocalsInfo *locals;
6500
6501                 header = mono_method_get_header (method);
6502                 g_assert (header);
6503
6504                 buffer_add_int (buf, header->num_locals);
6505
6506                 /* Types */
6507                 for (i = 0; i < header->num_locals; ++i)
6508                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
6509
6510                 /* Names */
6511                 locals = mono_debug_lookup_locals (method);
6512                 if (locals)
6513                         num_locals = locals->num_locals;
6514                 else
6515                         num_locals = 0;
6516                 for (i = 0; i < header->num_locals; ++i) {
6517                         for (j = 0; j < num_locals; ++j)
6518                                 if (locals->locals [j].index == i)
6519                                         break;
6520                         if (j < num_locals)
6521                                 buffer_add_string (buf, locals->locals [j].name);
6522                         else
6523                                 buffer_add_string (buf, "");
6524                 }
6525
6526                 /* Scopes */
6527                 for (i = 0; i < header->num_locals; ++i) {
6528                         for (j = 0; j < num_locals; ++j)
6529                                 if (locals->locals [j].index == i)
6530                                         break;
6531                         if (j < num_locals && locals->locals [j].block) {
6532                                 buffer_add_int (buf, locals->locals [j].block->start_offset);
6533                                 buffer_add_int (buf, locals->locals [j].block->end_offset);
6534                         } else {
6535                                 buffer_add_int (buf, 0);
6536                                 buffer_add_int (buf, header->code_size);
6537                         }
6538                 }
6539                 mono_metadata_free_mh (header);
6540
6541                 if (locals)
6542                         mono_debug_symfile_free_locals (locals);
6543
6544                 break;
6545         }
6546         case CMD_METHOD_GET_INFO:
6547                 buffer_add_int (buf, method->flags);
6548                 buffer_add_int (buf, method->iflags);
6549                 buffer_add_int (buf, method->token);
6550                 break;
6551         case CMD_METHOD_GET_BODY: {
6552                 int i;
6553
6554                 header = mono_method_get_header (method);
6555                 if (!header) {
6556                         buffer_add_int (buf, 0);
6557                 } else {
6558                         buffer_add_int (buf, header->code_size);
6559                         for (i = 0; i < header->code_size; ++i)
6560                                 buffer_add_byte (buf, header->code [i]);
6561                 }
6562                 mono_metadata_free_mh (header);
6563                 break;
6564         }
6565         case CMD_METHOD_RESOLVE_TOKEN: {
6566                 guint32 token = decode_int (p, &p, end);
6567
6568                 // FIXME: Generics
6569                 switch (mono_metadata_token_code (token)) {
6570                 case MONO_TOKEN_STRING: {
6571                         MonoString *s;
6572                         char *s2;
6573
6574                         s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
6575                         g_assert (s);
6576
6577                         s2 = mono_string_to_utf8 (s);
6578
6579                         buffer_add_byte (buf, TOKEN_TYPE_STRING);
6580                         buffer_add_string (buf, s2);
6581                         g_free (s2);
6582                         break;
6583                 }
6584                 default: {
6585                         gpointer val;
6586                         MonoClass *handle_class;
6587
6588                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
6589                                 val = mono_method_get_wrapper_data (method, token);
6590                                 handle_class = mono_method_get_wrapper_data (method, token + 1);
6591
6592                                 if (handle_class == NULL) {
6593                                         // Can't figure out the token type
6594                                         buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
6595                                         break;
6596                                 }
6597                         } else {
6598                                 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
6599                                 g_assert (val);
6600                         }
6601
6602                         if (handle_class == mono_defaults.typehandle_class) {
6603                                 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
6604                                 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
6605                                         buffer_add_typeid (buf, domain, (MonoClass *) val);
6606                                 else
6607                                         buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
6608                         } else if (handle_class == mono_defaults.fieldhandle_class) {
6609                                 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
6610                                 buffer_add_fieldid (buf, domain, val);
6611                         } else if (handle_class == mono_defaults.methodhandle_class) {
6612                                 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
6613                                 buffer_add_methodid (buf, domain, val);
6614                         } else if (handle_class == mono_defaults.string_class) {
6615                                 char *s;
6616
6617                                 s = mono_string_to_utf8 (val);
6618                                 buffer_add_byte (buf, TOKEN_TYPE_STRING);
6619                                 buffer_add_string (buf, s);
6620                                 g_free (s);
6621                         } else {
6622                                 g_assert_not_reached ();
6623                         }
6624                         break;
6625                 }
6626                 }
6627                 break;
6628         }
6629         default:
6630                 return ERR_NOT_IMPLEMENTED;
6631         }
6632
6633         return ERR_NONE;
6634 }
6635
6636 static ErrorCode
6637 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6638 {
6639         int err;
6640         MonoDomain *old_domain;
6641         MonoDomain *domain;
6642         MonoMethod *method;
6643
6644         method = decode_methodid (p, &p, end, &domain, &err);
6645         if (err)
6646                 return err;
6647
6648         old_domain = mono_domain_get ();
6649
6650         mono_domain_set (domain, TRUE);
6651
6652         err = method_commands_internal (command, method, domain, p, end, buf);
6653
6654         mono_domain_set (old_domain, TRUE);
6655
6656         return err;
6657 }
6658
6659 static ErrorCode
6660 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6661 {
6662         int objid = decode_objid (p, &p, end);
6663         int err;
6664         MonoThread *thread_obj;
6665         MonoInternalThread *thread;
6666
6667         err = get_object (objid, (MonoObject**)&thread_obj);
6668         if (err)
6669                 return err;
6670
6671         thread = THREAD_TO_INTERNAL (thread_obj);
6672            
6673         switch (command) {
6674         case CMD_THREAD_GET_NAME: {
6675                 guint32 name_len;
6676                 gunichar2 *s = mono_thread_get_name (thread, &name_len);
6677
6678                 if (!s) {
6679                         buffer_add_int (buf, 0);
6680                 } else {
6681                         char *name;
6682                         glong len;
6683
6684                         name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
6685                         g_assert (name);
6686                         buffer_add_int (buf, len);
6687                         buffer_add_data (buf, (guint8*)name, len);
6688                         g_free (s);
6689                 }
6690                 break;
6691         }
6692         case CMD_THREAD_GET_FRAME_INFO: {
6693                 DebuggerTlsData *tls;
6694                 int i, start_frame, length;
6695
6696                 // Wait for suspending if it already started
6697                 if (suspend_count)
6698                         wait_for_suspend ();
6699                 if (!is_suspended ())
6700                         return ERR_NOT_SUSPENDED;
6701
6702                 start_frame = decode_int (p, &p, end);
6703                 length = decode_int (p, &p, end);
6704
6705                 if (start_frame != 0 || length != -1)
6706                         return ERR_NOT_IMPLEMENTED;
6707
6708                 mono_loader_lock ();
6709                 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6710                 mono_loader_unlock ();
6711                 g_assert (tls);
6712
6713                 compute_frame_info (thread, tls);
6714
6715                 buffer_add_int (buf, tls->frame_count);
6716                 for (i = 0; i < tls->frame_count; ++i) {
6717                         buffer_add_int (buf, tls->frames [i]->id);
6718                         buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
6719                         buffer_add_int (buf, tls->frames [i]->il_offset);
6720                         /*
6721                          * Instead of passing the frame type directly to the client, we associate
6722                          * it with the previous frame using a set of flags. This avoids lots of
6723                          * conditional code in the client, since a frame whose type isn't 
6724                          * FRAME_TYPE_MANAGED has no method, location, etc.
6725                          */
6726                         buffer_add_byte (buf, tls->frames [i]->flags);
6727                 }
6728
6729                 break;
6730         }
6731         case CMD_THREAD_GET_STATE:
6732                 buffer_add_int (buf, thread->state);
6733                 break;
6734         case CMD_THREAD_GET_INFO:
6735                 buffer_add_byte (buf, thread->threadpool_thread);
6736                 break;
6737         case CMD_THREAD_GET_ID:
6738                 buffer_add_long (buf, (guint64)(gsize)thread);
6739                 break;
6740         case CMD_THREAD_GET_TID:
6741                 buffer_add_long (buf, (guint64)thread->tid);
6742                 break;
6743         default:
6744                 return ERR_NOT_IMPLEMENTED;
6745         }
6746
6747         return ERR_NONE;
6748 }
6749
6750 static ErrorCode
6751 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6752 {
6753         int objid;
6754         int err;
6755         MonoThread *thread_obj;
6756         MonoInternalThread *thread;
6757         int pos, i, len;
6758         DebuggerTlsData *tls;
6759         StackFrame *frame;
6760         MonoDebugMethodJitInfo *jit;
6761         MonoDebugVarInfo *var;
6762         MonoMethodSignature *sig;
6763         gssize id;
6764         MonoMethodHeader *header;
6765
6766         objid = decode_objid (p, &p, end);
6767         err = get_object (objid, (MonoObject**)&thread_obj);
6768         if (err)
6769                 return err;
6770
6771         thread = THREAD_TO_INTERNAL (thread_obj);
6772
6773         id = decode_id (p, &p, end);
6774
6775         mono_loader_lock ();
6776         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6777         mono_loader_unlock ();
6778         g_assert (tls);
6779
6780         for (i = 0; i < tls->frame_count; ++i) {
6781                 if (tls->frames [i]->id == id)
6782                         break;
6783         }
6784         if (i == tls->frame_count)
6785                 return ERR_INVALID_FRAMEID;
6786
6787         frame = tls->frames [i];
6788
6789         if (!frame->has_ctx)
6790                 // FIXME:
6791                 return ERR_INVALID_FRAMEID;
6792
6793         if (!frame->jit) {
6794                 frame->jit = mono_debug_find_method (frame->method, frame->domain);
6795                 if (!frame->jit)
6796                         /* This could happen for aot images with no jit debug info */
6797                         return ERR_ABSENT_INFORMATION;
6798         }
6799         jit = frame->jit;
6800
6801         sig = mono_method_signature (frame->actual_method);
6802
6803         switch (command) {
6804         case CMD_STACK_FRAME_GET_VALUES: {
6805                 len = decode_int (p, &p, end);
6806                 header = mono_method_get_header (frame->actual_method);
6807
6808                 for (i = 0; i < len; ++i) {
6809                         pos = decode_int (p, &p, end);
6810
6811                         if (pos < 0) {
6812                                 pos = - pos - 1;
6813
6814                                 g_assert (pos >= 0 && pos < jit->num_params);
6815
6816                                 var = &jit->params [pos];
6817
6818                                 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
6819                         } else {
6820                                 g_assert (pos >= 0 && pos < jit->num_locals);
6821
6822                                 var = &jit->locals [pos];
6823                                 
6824                                 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
6825                         }
6826                 }
6827                 mono_metadata_free_mh (header);
6828                 break;
6829         }
6830         case CMD_STACK_FRAME_GET_THIS: {
6831                 if (frame->method->klass->valuetype) {
6832                         if (!sig->hasthis) {
6833                                 MonoObject *p = NULL;
6834                                 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
6835                         } else {
6836                                 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
6837                         }
6838                 } else {
6839                         if (!sig->hasthis) {
6840                                 MonoObject *p = NULL;
6841                                 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
6842                         } else {
6843                                 add_var (buf, &frame->method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
6844                         }
6845                 }
6846                 break;
6847         }
6848         case CMD_STACK_FRAME_SET_VALUES: {
6849                 guint8 *val_buf;
6850                 MonoType *t;
6851                 MonoDebugVarInfo *var;
6852
6853                 len = decode_int (p, &p, end);
6854                 header = mono_method_get_header (frame->actual_method);
6855
6856                 for (i = 0; i < len; ++i) {
6857                         pos = decode_int (p, &p, end);
6858
6859                         if (pos < 0) {
6860                                 pos = - pos - 1;
6861
6862                                 g_assert (pos >= 0 && pos < jit->num_params);
6863
6864                                 t = sig->params [pos];
6865                                 var = &jit->params [pos];
6866                         } else {
6867                                 g_assert (pos >= 0 && pos < jit->num_locals);
6868
6869                                 t = header->locals [pos];
6870                                 var = &jit->locals [pos];
6871                         }
6872
6873                         if (MONO_TYPE_IS_REFERENCE (t))
6874                                 val_buf = g_alloca (sizeof (MonoObject*));
6875                         else
6876                                 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
6877                         err = decode_value (t, frame->domain, val_buf, p, &p, end);
6878                         if (err)
6879                                 return err;
6880
6881                         set_var (t, var, &frame->ctx, frame->domain, val_buf);
6882                 }
6883                 mono_metadata_free_mh (header);
6884                 break;
6885         }
6886         default:
6887                 return ERR_NOT_IMPLEMENTED;
6888         }
6889
6890         return ERR_NONE;
6891 }
6892
6893 static ErrorCode
6894 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6895 {
6896         MonoArray *arr;
6897         int objid, err, index, len, i, esize;
6898         gpointer elem;
6899
6900         objid = decode_objid (p, &p, end);
6901         err = get_object (objid, (MonoObject**)&arr);
6902         if (err)
6903                 return err;
6904
6905         switch (command) {
6906         case CMD_ARRAY_REF_GET_LENGTH:
6907                 buffer_add_int (buf, arr->obj.vtable->klass->rank);
6908                 if (!arr->bounds) {
6909                         buffer_add_int (buf, arr->max_length);
6910                         buffer_add_int (buf, 0);
6911                 } else {
6912                         for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
6913                                 buffer_add_int (buf, arr->bounds [i].length);
6914                                 buffer_add_int (buf, arr->bounds [i].lower_bound);
6915                         }
6916                 }
6917                 break;
6918         case CMD_ARRAY_REF_GET_VALUES:
6919                 index = decode_int (p, &p, end);
6920                 len = decode_int (p, &p, end);
6921
6922                 g_assert (index >= 0 && len >= 0);
6923                 // Reordered to avoid integer overflow
6924                 g_assert (!(index > arr->max_length - len));
6925
6926                 esize = mono_array_element_size (arr->obj.vtable->klass);
6927                 for (i = index; i < index + len; ++i) {
6928                         elem = (gpointer*)((char*)arr->vector + (i * esize));
6929                         buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
6930                 }
6931                 break;
6932         case CMD_ARRAY_REF_SET_VALUES:
6933                 index = decode_int (p, &p, end);
6934                 len = decode_int (p, &p, end);
6935
6936                 g_assert (index >= 0 && len >= 0);
6937                 // Reordered to avoid integer overflow
6938                 g_assert (!(index > arr->max_length - len));
6939
6940                 esize = mono_array_element_size (arr->obj.vtable->klass);
6941                 for (i = index; i < index + len; ++i) {
6942                         elem = (gpointer*)((char*)arr->vector + (i * esize));
6943
6944                         decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
6945                 }
6946                 break;
6947         default:
6948                 return ERR_NOT_IMPLEMENTED;
6949         }
6950
6951         return ERR_NONE;
6952 }
6953
6954 static ErrorCode
6955 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6956 {
6957         int objid, err;
6958         MonoString *str;
6959         char *s;
6960
6961         objid = decode_objid (p, &p, end);
6962         err = get_object (objid, (MonoObject**)&str);
6963         if (err)
6964                 return err;
6965
6966         switch (command) {
6967         case CMD_STRING_REF_GET_VALUE:
6968                 s = mono_string_to_utf8 (str);
6969                 buffer_add_string (buf, s);
6970                 g_free (s);
6971                 break;
6972         default:
6973                 return ERR_NOT_IMPLEMENTED;
6974         }
6975
6976         return ERR_NONE;
6977 }
6978
6979 static ErrorCode
6980 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6981 {
6982         int objid, err;
6983         MonoObject *obj;
6984         int len, i;
6985         MonoClassField *f;
6986         MonoClass *k;
6987         gboolean found;
6988
6989         if (command == CMD_OBJECT_REF_IS_COLLECTED) {
6990                 objid = decode_objid (p, &p, end);
6991                 err = get_object (objid, &obj);
6992                 if (err)
6993                         buffer_add_int (buf, 1);
6994                 else
6995                         buffer_add_int (buf, 0);
6996                 return 0;
6997         }
6998
6999         objid = decode_objid (p, &p, end);
7000         err = get_object (objid, &obj);
7001         if (err)
7002                 return err;
7003
7004         switch (command) {
7005         case CMD_OBJECT_REF_GET_TYPE:
7006                 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
7007                 break;
7008         case CMD_OBJECT_REF_GET_VALUES:
7009                 len = decode_int (p, &p, end);
7010
7011                 for (i = 0; i < len; ++i) {
7012                         MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
7013                         if (err)
7014                                 return err;
7015
7016                         /* Check that the field belongs to the object */
7017                         found = FALSE;
7018                         for (k = obj->vtable->klass; k; k = k->parent) {
7019                                 if (k == f->parent) {
7020                                         found = TRUE;
7021                                         break;
7022                                 }
7023                         }
7024                         if (!found)
7025                                 return ERR_INVALID_FIELDID;
7026
7027                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
7028                                 guint8 *val;
7029                                 MonoVTable *vtable;
7030
7031                                 if (mono_class_field_is_special_static (f))
7032                                         return ERR_INVALID_FIELDID;
7033
7034                                 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
7035                                 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
7036                                 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7037                                 mono_field_static_get_value (vtable, f, val);
7038                                 buffer_add_value (buf, f->type, val, obj->vtable->domain);
7039                                 g_free (val);
7040                         } else {
7041                                 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
7042                         }
7043                 }
7044                 break;
7045         case CMD_OBJECT_REF_SET_VALUES:
7046                 len = decode_int (p, &p, end);
7047
7048                 for (i = 0; i < len; ++i) {
7049                         f = decode_fieldid (p, &p, end, NULL, &err);
7050                         if (err)
7051                                 return err;
7052
7053                         /* Check that the field belongs to the object */
7054                         found = FALSE;
7055                         for (k = obj->vtable->klass; k; k = k->parent) {
7056                                 if (k == f->parent) {
7057                                         found = TRUE;
7058                                         break;
7059                                 }
7060                         }
7061                         if (!found)
7062                                 return ERR_INVALID_FIELDID;
7063
7064                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
7065                                 guint8 *val;
7066                                 MonoVTable *vtable;
7067
7068                                 if (mono_class_field_is_special_static (f))
7069                                         return ERR_INVALID_FIELDID;
7070
7071                                 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
7072                                 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
7073
7074                                 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7075                                 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
7076                                 if (err) {
7077                                         g_free (val);
7078                                         return err;
7079                                 }
7080                                 mono_field_static_set_value (vtable, f, val);
7081                                 g_free (val);
7082                         } else {
7083                                 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
7084                                 if (err)
7085                                         return err;
7086                         }
7087                 }
7088                 break;
7089         case CMD_OBJECT_REF_GET_ADDRESS:
7090                 buffer_add_long (buf, (gssize)obj);
7091                 break;
7092         case CMD_OBJECT_REF_GET_DOMAIN:
7093                 buffer_add_domainid (buf, obj->vtable->domain);
7094                 break;
7095         default:
7096                 return ERR_NOT_IMPLEMENTED;
7097         }
7098
7099         return ERR_NONE;
7100 }
7101
7102 static const char*
7103 command_set_to_string (CommandSet command_set)
7104 {
7105         switch (command_set) {
7106         case CMD_SET_VM:
7107                 return "VM";
7108         case CMD_SET_OBJECT_REF:
7109                 return "OBJECT_REF";
7110         case CMD_SET_STRING_REF:
7111                 return "STRING_REF"; 
7112         case CMD_SET_THREAD:
7113                 return "THREAD"; 
7114         case CMD_SET_ARRAY_REF:
7115                 return "ARRAY_REF"; 
7116         case CMD_SET_EVENT_REQUEST:
7117                 return "EVENT_REQUEST"; 
7118         case CMD_SET_STACK_FRAME:
7119                 return "STACK_FRAME"; 
7120         case CMD_SET_APPDOMAIN:
7121                 return "APPDOMAIN"; 
7122         case CMD_SET_ASSEMBLY:
7123                 return "ASSEMBLY"; 
7124         case CMD_SET_METHOD:
7125                 return "METHOD"; 
7126         case CMD_SET_TYPE:
7127                 return "TYPE"; 
7128         case CMD_SET_MODULE:
7129                 return "MODULE"; 
7130         case CMD_SET_EVENT:
7131                 return "EVENT"; 
7132         default:
7133                 return "";
7134         }
7135 }
7136
7137 static const char*
7138 cmd_to_string (CommandSet set, int command)
7139 {
7140         switch (set) {
7141         case CMD_SET_VM: {
7142                 switch (command) {
7143                 case CMD_VM_VERSION:
7144                         return "VERSION";
7145                 case CMD_VM_ALL_THREADS:
7146                         return "ALL_THREADS";
7147                 case CMD_VM_SUSPEND:
7148                         return "SUSPEND";
7149                 case CMD_VM_RESUME:
7150                         return "RESUME";
7151                 case CMD_VM_EXIT:
7152                         return "EXIT";
7153                 case CMD_VM_DISPOSE:
7154                         return "DISPOSE";
7155                 case CMD_VM_INVOKE_METHOD:
7156                         return "INVOKE_METHOD";
7157                 case CMD_VM_SET_PROTOCOL_VERSION:
7158                         return "SET_PROTOCOL_VERSION";
7159                 case CMD_VM_ABORT_INVOKE:
7160                         return "ABORT_INVOKE";
7161                 default:
7162                         break;
7163                 }
7164                 break;
7165         }
7166         default:
7167                 break;
7168         }
7169         return NULL;
7170 }
7171
7172 static gboolean
7173 wait_for_attach (void)
7174 {
7175         if (listen_fd == -1) {
7176                 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
7177                 return FALSE;
7178         }
7179
7180         /* Block and wait for client connection */
7181         conn_fd = transport_accept (listen_fd);
7182         DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
7183         if (conn_fd == -1) {
7184                 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
7185                 return FALSE;
7186         }
7187         
7188         /* Handshake */
7189         disconnected = !transport_handshake ();
7190         if (disconnected) {
7191                 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
7192                 return FALSE;
7193         }
7194         
7195         return TRUE;
7196 }
7197
7198 /*
7199  * debugger_thread:
7200  *
7201  *   This thread handles communication with the debugger client using a JDWP
7202  * like protocol.
7203  */
7204 static guint32 WINAPI
7205 debugger_thread (void *arg)
7206 {
7207         int res, len, id, flags, command_set, command;
7208         guint8 header [HEADER_LENGTH];
7209         guint8 *data, *p, *end;
7210         Buffer buf;
7211         ErrorCode err;
7212         gboolean no_reply;
7213         gboolean attach_failed = FALSE;
7214
7215         DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
7216
7217         debugger_thread_id = GetCurrentThreadId ();
7218
7219         mono_jit_thread_attach (mono_get_root_domain ());
7220
7221         mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
7222
7223         mono_set_is_debugger_attached (TRUE);
7224         
7225         if (agent_config.defer) {
7226                 if (!wait_for_attach ()) {
7227                         DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
7228                         attach_failed = TRUE; // Don't abort process when we can't listen
7229                 } else {
7230                         /* Send start event to client */
7231                         process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
7232                 }
7233         }
7234         
7235         while (!attach_failed) {
7236                 res = recv_length (conn_fd, header, HEADER_LENGTH, 0);
7237
7238                 /* This will break if the socket is closed during shutdown too */
7239                 if (res != HEADER_LENGTH)
7240                         break;
7241
7242                 p = header;
7243                 end = header + HEADER_LENGTH;
7244
7245                 len = decode_int (p, &p, end);
7246                 id = decode_int (p, &p, end);
7247                 flags = decode_byte (p, &p, end);
7248                 command_set = decode_byte (p, &p, end);
7249                 command = decode_byte (p, &p, end);
7250
7251                 g_assert (flags == 0);
7252
7253                 if (log_level) {
7254                         const char *cmd_str;
7255                         char cmd_num [256];
7256
7257                         cmd_str = cmd_to_string (command_set, command);
7258                         if (!cmd_str) {
7259                                 sprintf (cmd_num, "%d", command);
7260                                 cmd_str = cmd_num;
7261                         }
7262                         
7263                         DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
7264                 }
7265
7266                 data = g_malloc (len - HEADER_LENGTH);
7267                 if (len - HEADER_LENGTH > 0)
7268                 {
7269                         res = recv_length (conn_fd, data, len - HEADER_LENGTH, 0);
7270                         if (res != len - HEADER_LENGTH)
7271                                 break;
7272                 }
7273
7274                 p = data;
7275                 end = data + (len - HEADER_LENGTH);
7276
7277                 buffer_init (&buf, 128);
7278
7279                 err = ERR_NONE;
7280                 no_reply = FALSE;
7281
7282                 /* Process the request */
7283                 switch (command_set) {
7284                 case CMD_SET_VM:
7285                         err = vm_commands (command, id, p, end, &buf);
7286                         if (!err && command == CMD_VM_INVOKE_METHOD)
7287                                 /* Sent after the invoke is complete */
7288                                 no_reply = TRUE;
7289                         break;
7290                 case CMD_SET_EVENT_REQUEST:
7291                         err = event_commands (command, p, end, &buf);
7292                         break;
7293                 case CMD_SET_APPDOMAIN:
7294                         err = domain_commands (command, p, end, &buf);
7295                         break;
7296                 case CMD_SET_ASSEMBLY:
7297                         err = assembly_commands (command, p, end, &buf);
7298                         break;
7299                 case CMD_SET_MODULE:
7300                         err = module_commands (command, p, end, &buf);
7301                         break;
7302                 case CMD_SET_TYPE:
7303                         err = type_commands (command, p, end, &buf);
7304                         break;
7305                 case CMD_SET_METHOD:
7306                         err = method_commands (command, p, end, &buf);
7307                         break;
7308                 case CMD_SET_THREAD:
7309                         err = thread_commands (command, p, end, &buf);
7310                         break;
7311                 case CMD_SET_STACK_FRAME:
7312                         err = frame_commands (command, p, end, &buf);
7313                         break;
7314                 case CMD_SET_ARRAY_REF:
7315                         err = array_commands (command, p, end, &buf);
7316                         break;
7317                 case CMD_SET_STRING_REF:
7318                         err = string_commands (command, p, end, &buf);
7319                         break;
7320                 case CMD_SET_OBJECT_REF:
7321                         err = object_commands (command, p, end, &buf);
7322                         break;
7323                 default:
7324                         err = ERR_NOT_IMPLEMENTED;
7325                 }               
7326
7327                 if (!no_reply)
7328                         send_reply_packet (id, err, &buf);
7329
7330                 g_free (data);
7331                 buffer_free (&buf);
7332
7333                 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
7334                         break;
7335         }
7336
7337         mono_set_is_debugger_attached (FALSE);
7338         
7339         mono_mutex_lock (&debugger_thread_exited_mutex);
7340         debugger_thread_exited = TRUE;
7341         mono_cond_signal (&debugger_thread_exited_cond);
7342         mono_mutex_unlock (&debugger_thread_exited_mutex);
7343
7344         DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
7345         
7346         if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
7347                 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
7348                 start_debugger_thread ();
7349         }
7350         
7351         return 0;
7352 }
7353
7354 #else /* DISABLE_DEBUGGER_AGENT */
7355
7356 void
7357 mono_debugger_agent_parse_options (char *options)
7358 {
7359         g_error ("This runtime is configured with the debugger agent disabled.");
7360 }
7361
7362 void
7363 mono_debugger_agent_init (void)
7364 {
7365 }
7366
7367 void
7368 mono_debugger_agent_breakpoint_hit (void *sigctx)
7369 {
7370 }
7371
7372 void
7373 mono_debugger_agent_single_step_event (void *sigctx)
7374 {
7375 }
7376
7377 void
7378 mono_debugger_agent_free_domain_info (MonoDomain *domain)
7379 {
7380 }
7381
7382 gboolean
7383 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
7384 {
7385         return FALSE;
7386 }
7387
7388 void
7389 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
7390                                                                           MonoContext *catch_ctx)
7391 {
7392 }
7393
7394 void
7395 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
7396 {
7397 }
7398
7399 void
7400 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
7401 {
7402 }
7403
7404 #endif
7405