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