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