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