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