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