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