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