2010-01-20 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, appdomain_unload, NULL);
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                         tls->suspended = TRUE;
1856                         MONO_SEM_POST (&suspend_sem);
1857                 }
1858                 return TRUE;
1859         }
1860 }
1861
1862 #ifdef HOST_WIN32
1863 static void CALLBACK notify_thread_apc (ULONG_PTR param)
1864 {
1865         //DebugBreak ();
1866         mono_debugger_agent_thread_interrupt (NULL, NULL);
1867 }
1868 #endif /* HOST_WIN32 */
1869
1870 /*
1871  * reset_native_thread_suspend_state:
1872  * 
1873  *   Reset the suspended flag on native threads
1874  */
1875 static void
1876 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
1877 {
1878         DebuggerTlsData *tls = value;
1879
1880         if (!tls->really_suspended && tls->suspended)
1881                 tls->suspended = FALSE;
1882 }
1883
1884 /*
1885  * notify_thread:
1886  *
1887  *   Notify a thread that it needs to suspend.
1888  */
1889 static void
1890 notify_thread (gpointer key, gpointer value, gpointer user_data)
1891 {
1892         MonoInternalThread *thread = key;
1893         DebuggerTlsData *tls = value;
1894         gsize tid = thread->tid;
1895
1896         if (GetCurrentThreadId () != tid) {
1897                 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
1898
1899                 /*
1900                  * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
1901                  * guarantee the signal handler will be called that many times.  Instead of tracking
1902                  * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
1903                  * has been requested that hasn't been handled yet, otherwise we can have threads
1904                  * refuse to die when VM_EXIT is called
1905                  */
1906 #if defined(__APPLE__)
1907                 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
1908                         return;
1909 #else
1910                 /*
1911                  * Maybe we could use the normal interrupt infrastructure, but that does a lot
1912                  * of things like breaking waits etc. which we don't want.
1913                  */
1914                 InterlockedIncrement (&tls->interrupt_count);
1915 #endif
1916
1917                 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
1918 #ifdef HOST_WIN32
1919                 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
1920 #else
1921                 pthread_kill ((pthread_t) tid, mono_thread_get_abort_signal ());
1922 #endif
1923         }
1924 }
1925
1926 static void
1927 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
1928 {
1929         guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
1930         MonoJitInfo *ji;
1931
1932         if (debugger_thread_id == GetCurrentThreadId ())
1933                 return;
1934
1935         /* Prevent races with mono_debugger_agent_thread_interrupt () */
1936         if (suspend_count - tls->resume_count > 0)
1937                 tls->suspending = TRUE;
1938
1939         DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
1940
1941         if (suspend_count - tls->resume_count == 0) {
1942                 /* 
1943                  * We are executing a single threaded invoke but the single step for 
1944                  * suspending is still active.
1945                  * FIXME: This slows down single threaded invokes.
1946                  */
1947                 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
1948                 return;
1949         }
1950
1951         ji = mono_jit_info_table_find (mono_domain_get (), (char*)ip);
1952
1953         /* Can't suspend in these methods */
1954         if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
1955                 return;
1956
1957         save_thread_context (ctx);
1958
1959         suspend_current ();
1960 }
1961
1962 /*
1963  * suspend_vm:
1964  *
1965  * Increase the suspend count of the VM. While the suspend count is greater 
1966  * than 0, runtime threads are suspended at certain points during execution.
1967  */
1968 static void
1969 suspend_vm (void)
1970 {
1971         mono_loader_lock ();
1972
1973         mono_mutex_lock (&suspend_mutex);
1974
1975         suspend_count ++;
1976
1977         DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
1978
1979         if (suspend_count == 1) {
1980                 // FIXME: Is it safe to call this inside the lock ?
1981                 start_single_stepping ();
1982                 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
1983         }
1984
1985         mono_mutex_unlock (&suspend_mutex);
1986
1987         mono_loader_unlock ();
1988 }
1989
1990 /*
1991  * resume_vm:
1992  *
1993  * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
1994  * are resumed.
1995  */
1996 static void
1997 resume_vm (void)
1998 {
1999         int err;
2000
2001         g_assert (debugger_thread_id == GetCurrentThreadId ());
2002
2003         mono_loader_lock ();
2004
2005         mono_mutex_lock (&suspend_mutex);
2006
2007         g_assert (suspend_count > 0);
2008         suspend_count --;
2009
2010         DEBUG(1, fprintf (log_file, "[%p] Resuming vm...\n", (gpointer)GetCurrentThreadId ()));
2011
2012         if (suspend_count == 0) {
2013                 // FIXME: Is it safe to call this inside the lock ?
2014                 stop_single_stepping ();
2015                 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2016         }
2017
2018         /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2019         err = mono_cond_broadcast (&suspend_cond);
2020         g_assert (err == 0);
2021
2022         mono_mutex_unlock (&suspend_mutex);
2023         //g_assert (err == 0);
2024
2025         mono_loader_unlock ();
2026 }
2027
2028 /*
2029  * resume_thread:
2030  *
2031  *   Resume just one thread.
2032  */
2033 static void
2034 resume_thread (MonoInternalThread *thread)
2035 {
2036         int err;
2037         DebuggerTlsData *tls;
2038
2039         g_assert (debugger_thread_id == GetCurrentThreadId ());
2040
2041         mono_loader_lock ();
2042
2043         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2044         g_assert (tls);
2045         
2046         mono_mutex_lock (&suspend_mutex);
2047
2048         g_assert (suspend_count > 0);
2049
2050         DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2051
2052         tls->resume_count += suspend_count;
2053
2054         /* 
2055          * Signal suspend_count without decreasing suspend_count, the threads will wake up
2056          * but only the one whose resume_count field is > 0 will be resumed.
2057          */
2058         err = mono_cond_broadcast (&suspend_cond);
2059         g_assert (err == 0);
2060
2061         mono_mutex_unlock (&suspend_mutex);
2062         //g_assert (err == 0);
2063
2064         mono_loader_unlock ();
2065 }
2066
2067 static void
2068 invalidate_frames (DebuggerTlsData *tls)
2069 {
2070         int i;
2071
2072         if (!tls)
2073                 tls = TlsGetValue (debugger_tls_id);
2074         g_assert (tls);
2075
2076         for (i = 0; i < tls->frame_count; ++i) {
2077                 if (tls->frames [i]->jit)
2078                         mono_debug_free_method_jit_info (tls->frames [i]->jit);
2079                 g_free (tls->frames [i]);
2080         }
2081         g_free (tls->frames);
2082         tls->frame_count = 0;
2083         tls->frames = NULL;
2084 }
2085
2086 /*
2087  * suspend_current:
2088  *
2089  *   Suspend the current thread until the runtime is resumed. If the thread has a 
2090  * pending invoke, then the invoke is executed before this function returns. 
2091  */
2092 static void
2093 suspend_current (void)
2094 {
2095         int err;
2096         DebuggerTlsData *tls;
2097
2098         g_assert (debugger_thread_id != GetCurrentThreadId ());
2099
2100         if (mono_loader_lock_is_owned_by_self ()) {
2101                 /*
2102                  * If we own the loader mutex, can't suspend until we release it, since the
2103                  * whole runtime can deadlock otherwise.
2104                  */
2105                 return;
2106         }
2107
2108         tls = TlsGetValue (debugger_tls_id);
2109         g_assert (tls);
2110
2111         mono_mutex_lock (&suspend_mutex);
2112
2113         tls->suspending = FALSE;
2114         tls->really_suspended = TRUE;
2115
2116         if (!tls->suspended) {
2117                 tls->suspended = TRUE;
2118                 MONO_SEM_POST (&suspend_sem);
2119         }
2120
2121         DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2122
2123         while (suspend_count - tls->resume_count > 0) {
2124 #ifdef HOST_WIN32
2125                 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2126                 {
2127                         mono_mutex_unlock (&suspend_mutex);
2128                         Sleep(0);
2129                         mono_mutex_lock (&suspend_mutex);
2130                 }
2131                 else
2132                 {
2133                 }
2134 #else
2135                 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2136                 g_assert (err == 0);
2137 #endif
2138         }
2139
2140         tls->suspended = FALSE;
2141         tls->really_suspended = FALSE;
2142
2143         threads_suspend_count --;
2144
2145         mono_mutex_unlock (&suspend_mutex);
2146
2147         DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2148
2149         if (tls->invoke) {
2150                 /* Save the original context */
2151                 tls->invoke->has_ctx = TRUE;
2152                 memcpy (&tls->invoke->ctx, &tls->ctx, sizeof (MonoContext));
2153
2154                 invoke_method ();
2155         }
2156
2157         /* The frame info becomes invalid after a resume */
2158         tls->has_context = FALSE;
2159         tls->has_async_ctx = FALSE;
2160         invalidate_frames (NULL);
2161 }
2162
2163 static void
2164 count_thread (gpointer key, gpointer value, gpointer user_data)
2165 {
2166         DebuggerTlsData *tls = value;
2167
2168         if (!tls->suspended && !tls->terminated)
2169                 *(int*)user_data = *(int*)user_data + 1;
2170 }
2171
2172 static int
2173 count_threads_to_wait_for (void)
2174 {
2175         int count = 0;
2176
2177         mono_loader_lock ();
2178         mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2179         mono_loader_unlock ();
2180
2181         return count;
2182 }       
2183
2184 /*
2185  * wait_for_suspend:
2186  *
2187  *   Wait until the runtime is completely suspended.
2188  */
2189 static void
2190 wait_for_suspend (void)
2191 {
2192         int nthreads, nwait, err;
2193         gboolean waited = FALSE;
2194
2195         // FIXME: Threads starting/stopping ?
2196         mono_loader_lock ();
2197         nthreads = mono_g_hash_table_size (thread_to_tls);
2198         mono_loader_unlock ();
2199
2200         while (TRUE) {
2201                 nwait = count_threads_to_wait_for ();
2202                 if (nwait) {
2203                         DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2204                         err = MONO_SEM_WAIT (&suspend_sem);
2205                         g_assert (err == 0);
2206                         waited = TRUE;
2207                 } else {
2208                         break;
2209                 }
2210         }
2211
2212         if (waited)
2213                 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2214 }
2215
2216 /*
2217  * is_suspended:
2218  *
2219  *   Return whenever the runtime is suspended.
2220  */
2221 static gboolean
2222 is_suspended (void)
2223 {
2224         return count_threads_to_wait_for () == 0;
2225 }
2226
2227 /*
2228  * find_seq_point_for_native_offset:
2229  *
2230  *   Find the sequence point corresponding to the native offset NATIVE_OFFSET, which
2231  * should be the location of a sequence point.
2232  */
2233 static SeqPoint*
2234 find_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2235 {
2236         MonoSeqPointInfo *seq_points;
2237         int i;
2238
2239         mono_domain_lock (domain);
2240         seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2241         mono_domain_unlock (domain);
2242         g_assert (seq_points);
2243
2244         *info = seq_points;
2245
2246         for (i = 0; i < seq_points->len; ++i) {
2247                 if (seq_points->seq_points [i].native_offset == native_offset)
2248                         return &seq_points->seq_points [i];
2249         }
2250
2251         return NULL;
2252 }
2253
2254 /*
2255  * find_seq_point:
2256  *
2257  *   Find the sequence point corresponding to the IL offset IL_OFFSET, which
2258  * should be the location of a sequence point.
2259  */
2260 static SeqPoint*
2261 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
2262 {
2263         MonoSeqPointInfo *seq_points;
2264         int i;
2265
2266         mono_domain_lock (domain);
2267         seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2268         mono_domain_unlock (domain);
2269         g_assert (seq_points);
2270
2271         *info = seq_points;
2272
2273         for (i = 0; i < seq_points->len; ++i) {
2274                 if (seq_points->seq_points [i].il_offset == il_offset)
2275                         return &seq_points->seq_points [i];
2276         }
2277
2278         return NULL;
2279 }
2280
2281 /*
2282  * compute_il_offset:
2283  *
2284  *    Compute the IL offset corresponding to NATIVE_OFFSET, which should be
2285  * a location of a sequence point.
2286  * We use this function instead of mono_debug_il_offset_from_address () etc,
2287  * which doesn't seem to work in a lot of cases.
2288  */
2289 static gint32
2290 compute_il_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset)
2291 {
2292         MonoSeqPointInfo *seq_points;
2293         int i, last_il_offset, seq_il_offset, seq_native_offset;
2294
2295         mono_domain_lock (domain);
2296         seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2297         mono_domain_unlock (domain);
2298         g_assert (seq_points);
2299
2300         last_il_offset = -1;
2301
2302         /* Find the sequence point */
2303         for (i = 0; i < seq_points->len; ++i) {
2304                 seq_il_offset = seq_points->seq_points [i].il_offset;
2305                 seq_native_offset = seq_points->seq_points [i].native_offset;
2306
2307                 if (seq_native_offset > native_offset)
2308                         break;
2309                 last_il_offset = seq_il_offset;
2310         }
2311
2312         return last_il_offset;
2313 }
2314
2315 typedef struct {
2316         DebuggerTlsData *tls;
2317         GSList *frames;
2318 } ComputeFramesUserData;
2319
2320 static gboolean
2321 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2322 {
2323         ComputeFramesUserData *ud = user_data;
2324         StackFrame *frame;
2325         MonoMethod *method;
2326
2327         if (info->type != FRAME_TYPE_MANAGED) {
2328                 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
2329                         /* Mark the last frame as an invoke frame */
2330                         if (ud->frames)
2331                                 ((StackFrame*)ud->frames->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
2332                 }
2333                 return FALSE;
2334         }
2335
2336         if (info->ji)
2337                 method = info->ji->method;
2338         else
2339                 method = info->method;
2340
2341         if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD))
2342                 return FALSE;
2343
2344         if (info->il_offset == -1) {
2345                 /* Can't use compute_il_offset () since ip doesn't point precisely at at a seq point */
2346                 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
2347         }
2348
2349         DEBUG (1, fprintf (stderr, "\tFrame: %s %d %d %d\n", mono_method_full_name (method, TRUE), info->native_offset, info->il_offset, info->managed));
2350
2351         if (!info->managed && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD) {
2352                 /*
2353                  * mono_arch_find_jit_info () returns the context stored in the LMF for 
2354                  * native frames, but it should unwind once. This is why we have duplicate
2355                  * frames on the stack sometimes.
2356                  * !managed also seems to be set for dynamic methods.
2357                  */
2358                 return FALSE;
2359         }
2360
2361         frame = g_new0 (StackFrame, 1);
2362         frame->method = method;
2363         frame->il_offset = info->il_offset;
2364         if (ctx) {
2365                 frame->ctx = *ctx;
2366                 frame->has_ctx = TRUE;
2367         }
2368         frame->domain = info->domain;
2369
2370         ud->frames = g_slist_append (ud->frames, frame);
2371
2372         return FALSE;
2373 }
2374
2375 static void
2376 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
2377 {
2378         ComputeFramesUserData user_data;
2379         GSList *tmp;
2380         int i, findex, new_frame_count;
2381         StackFrame **new_frames, *f;
2382
2383         // FIXME: Locking on tls
2384         if (tls->frames && tls->frames_up_to_date)
2385                 return;
2386
2387         DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
2388
2389         user_data.tls = tls;
2390         user_data.frames = NULL;
2391         if (tls->terminated) {
2392                 tls->frame_count = 0;
2393                 return;
2394         } if (!tls->really_suspended && tls->has_async_ctx) {
2395                 /* Have to use the state saved by the signal handler */
2396                 process_frame (&tls->async_last_frame, NULL, &user_data);
2397                 mono_jit_walk_stack_from_ctx_in_thread (process_frame, tls->domain, &tls->async_ctx, FALSE, thread, tls->async_lmf, &user_data);
2398         } else if (tls->has_context) {
2399                 mono_jit_walk_stack_from_ctx_in_thread (process_frame, tls->domain, &tls->ctx, FALSE, thread, tls->lmf, &user_data);
2400         } else {
2401                 // FIXME:
2402                 tls->frame_count = 0;
2403                 return;
2404         }
2405
2406         new_frame_count = g_slist_length (user_data.frames);
2407         new_frames = g_new0 (StackFrame*, new_frame_count);
2408         findex = 0;
2409         for (tmp = user_data.frames; tmp; tmp = tmp->next) {
2410                 f = tmp->data;
2411
2412                 /* 
2413                  * Reuse the id for already existing stack frames, so invokes don't invalidate
2414                  * the still valid stack frames.
2415                  */
2416                 for (i = 0; i < tls->frame_count; ++i) {
2417                         if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
2418                                 f->id = tls->frames [i]->id;
2419                                 break;
2420                         }
2421                 }
2422
2423                 if (i >= tls->frame_count)
2424                         f->id = InterlockedIncrement (&frame_id);
2425
2426                 new_frames [findex ++] = f;
2427         }
2428
2429         g_slist_free (user_data.frames);
2430
2431         invalidate_frames (tls);
2432
2433         tls->frames = new_frames;
2434         tls->frame_count = new_frame_count;
2435         tls->frames_up_to_date = TRUE;
2436 }
2437
2438 /*
2439  * EVENT HANDLING
2440  */
2441
2442 /*
2443  * create_event_list:
2444  *
2445  *   Return a list of event request ids matching EVENT, starting from REQS, which
2446  * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
2447  * policy.
2448  * We return request ids, instead of requests, to simplify threading, since 
2449  * requests could be deleted anytime when the loader lock is not held.
2450  * LOCKING: Assumes the loader lock is held.
2451  */
2452 static GSList*
2453 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, MonoException *exc, int *suspend_policy)
2454 {
2455         int i, j;
2456         GSList *events = NULL;
2457
2458         *suspend_policy = SUSPEND_POLICY_NONE;
2459
2460         if (!reqs)
2461                 reqs = event_requests;
2462
2463         if (!reqs)
2464                 return NULL;
2465
2466         for (i = 0; i < reqs->len; ++i) {
2467                 EventRequest *req = g_ptr_array_index (reqs, i);
2468                 if (req->event_kind == event) {
2469                         gboolean filtered = FALSE;
2470
2471                         /* Apply filters */
2472                         for (j = 0; j < req->nmodifiers; ++j) {
2473                                 Modifier *mod = &req->modifiers [j];
2474
2475                                 if (mod->kind == MOD_KIND_COUNT) {
2476                                         filtered = TRUE;
2477                                         if (mod->data.count > 0) {
2478                                                 if (mod->data.count > 0) {
2479                                                         mod->data.count --;
2480                                                         if (mod->data.count == 0)
2481                                                                 filtered = FALSE;
2482                                                 }
2483                                         }
2484                                 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
2485                                         if (mod->data.thread != mono_thread_internal_current ())
2486                                                 filtered = TRUE;
2487                                 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && exc) {
2488                                         if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, exc->object.vtable->klass))
2489                                                 filtered = TRUE;
2490                                 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
2491                                         int k;
2492                                         gboolean found = FALSE;
2493                                         MonoAssembly **assemblies = mod->data.assemblies;
2494
2495                                         if (assemblies) {
2496                                                 for (k = 0; assemblies [k]; ++k)
2497                                                         if (assemblies [k] == ji->method->klass->image->assembly)
2498                                                                 found = TRUE;
2499                                         }
2500                                         if (!found)
2501                                                 filtered = TRUE;
2502                                 }
2503                         }
2504
2505                         if (!filtered) {
2506                                 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
2507                                 events = g_slist_append (events, GINT_TO_POINTER (req->id));
2508                         }
2509                 }
2510         }
2511
2512         /* Send a VM START/DEATH event by default */
2513         if (event == EVENT_KIND_VM_START)
2514                 events = g_slist_append (events, GINT_TO_POINTER (0));
2515         if (event == EVENT_KIND_VM_DEATH)
2516                 events = g_slist_append (events, GINT_TO_POINTER (0));
2517
2518         return events;
2519 }
2520
2521 static G_GNUC_UNUSED const char*
2522 event_to_string (EventKind event)
2523 {
2524         switch (event) {
2525         case EVENT_KIND_VM_START: return "VM_START";
2526         case EVENT_KIND_VM_DEATH: return "VM_DEATH";
2527         case EVENT_KIND_THREAD_START: return "THREAD_START";
2528         case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
2529         case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
2530         case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
2531         case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
2532         case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
2533         case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
2534         case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
2535         case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
2536         case EVENT_KIND_STEP: return "STEP";
2537         case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
2538         case EVENT_KIND_EXCEPTION: return "EXCEPTION";
2539         default:
2540                 g_assert_not_reached ();
2541         }
2542 }
2543
2544 /*
2545  * process_event:
2546  *
2547  *   Send an event to the client, suspending the vm if needed.
2548  * LOCKING: Since this can suspend the calling thread, no locks should be held
2549  * by the caller.
2550  * The EVENTS list is freed by this function.
2551  */
2552 static void
2553 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
2554 {
2555         Buffer buf;
2556         GSList *l;
2557         MonoDomain *domain = mono_domain_get ();
2558         MonoThread *thread;
2559
2560         if (!inited)
2561                 return;
2562
2563         if (!vm_start_event_sent && event != EVENT_KIND_VM_START)
2564                 // FIXME: We miss those events
2565                 return;
2566
2567         if (vm_death_event_sent)
2568                 return;
2569
2570         if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH)
2571                 return;
2572
2573         if (disconnected)
2574                 return;
2575
2576         if (events == NULL)
2577                 return;
2578
2579         if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
2580                 // FIXME: Send these with a NULL thread, don't suspend the current thread
2581                 return;
2582
2583         buffer_init (&buf, 128);
2584         buffer_add_byte (&buf, suspend_policy);
2585         buffer_add_int (&buf, g_slist_length (events)); // n of events
2586
2587         for (l = events; l; l = l->next) {
2588                 buffer_add_byte (&buf, event); // event kind
2589                 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
2590
2591                 thread = mono_thread_current ();
2592
2593                 if (event == EVENT_KIND_VM_START)
2594                         thread = arg;
2595                 else if (event == EVENT_KIND_THREAD_START)
2596                         g_assert (mono_thread_internal_current () == arg);
2597
2598                 buffer_add_objid (&buf, (MonoObject*)thread); // thread
2599
2600                 switch (event) {
2601                 case EVENT_KIND_THREAD_START:
2602                 case EVENT_KIND_THREAD_DEATH:
2603                         break;
2604                 case EVENT_KIND_APPDOMAIN_CREATE:
2605                 case EVENT_KIND_APPDOMAIN_UNLOAD:
2606                         buffer_add_domainid (&buf, arg);
2607                         break;
2608                 case EVENT_KIND_METHOD_ENTRY:
2609                 case EVENT_KIND_METHOD_EXIT:
2610                         buffer_add_methodid (&buf, domain, arg);
2611                         break;
2612                 case EVENT_KIND_ASSEMBLY_LOAD:
2613                 case EVENT_KIND_ASSEMBLY_UNLOAD:
2614                         buffer_add_assemblyid (&buf, domain, arg);
2615                         break;
2616                 case EVENT_KIND_TYPE_LOAD:
2617                         buffer_add_typeid (&buf, domain, arg);
2618                         break;
2619                 case EVENT_KIND_BREAKPOINT:
2620                 case EVENT_KIND_STEP:
2621                         buffer_add_methodid (&buf, domain, arg);
2622                         buffer_add_long (&buf, il_offset);
2623                         break;
2624                 case EVENT_KIND_VM_START:
2625                         buffer_add_domainid (&buf, mono_get_root_domain ());
2626                         break;
2627                 case EVENT_KIND_VM_DEATH:
2628                         break;
2629                 case EVENT_KIND_EXCEPTION:
2630                         buffer_add_objid (&buf, (MonoObject*)arg);
2631                         break;
2632                 default:
2633                         g_assert_not_reached ();
2634                 }
2635         }
2636
2637         if (event == EVENT_KIND_VM_START) {
2638                 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
2639                 start_debugger_thread ();
2640         }
2641    
2642         if (event == EVENT_KIND_VM_DEATH) {
2643                 vm_death_event_sent = TRUE;
2644
2645                 suspend_policy = SUSPEND_POLICY_NONE;
2646         }
2647
2648         if (mono_runtime_is_shutting_down ())
2649                 suspend_policy = SUSPEND_POLICY_NONE;
2650
2651         if (suspend_policy != SUSPEND_POLICY_NONE) {
2652                 /* 
2653                  * Save the thread context and start suspending before sending the packet,
2654                  * since we could be receiving the resume request before send_packet ()
2655                  * returns.
2656                  */
2657                 save_thread_context (ctx);
2658                 suspend_vm ();
2659         }
2660
2661         send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
2662
2663         g_slist_free (events);
2664         events = NULL;
2665
2666         if (event == EVENT_KIND_VM_START)
2667                 vm_start_event_sent = TRUE;
2668
2669         DEBUG (1, fprintf (log_file, "[%p] Sent event %s, suspend=%d.\n", (gpointer)GetCurrentThreadId (), event_to_string (event), suspend_policy));
2670
2671         buffer_free (&buf);
2672
2673         switch (suspend_policy) {
2674         case SUSPEND_POLICY_NONE:
2675                 break;
2676         case SUSPEND_POLICY_ALL:
2677                 suspend_current ();
2678                 break;
2679         case SUSPEND_POLICY_EVENT_THREAD:
2680                 NOT_IMPLEMENTED;
2681                 break;
2682         default:
2683                 g_assert_not_reached ();
2684         }
2685 }
2686
2687 static void
2688 process_profiler_event (EventKind event, gpointer arg)
2689 {
2690         int suspend_policy;
2691         GSList *events;
2692
2693         mono_loader_lock ();
2694         events = create_event_list (event, NULL, NULL, NULL, &suspend_policy);
2695         mono_loader_unlock ();
2696
2697         process_event (event, arg, 0, NULL, events, suspend_policy);
2698 }
2699
2700 static void
2701 runtime_initialized (MonoProfiler *prof)
2702 {
2703         process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
2704 }       
2705
2706 static void
2707 runtime_shutdown (MonoProfiler *prof)
2708 {
2709         process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
2710
2711         mono_debugger_agent_cleanup ();
2712 }
2713
2714 static void
2715 thread_startup (MonoProfiler *prof, gsize tid)
2716 {
2717         MonoInternalThread *thread = mono_thread_internal_current ();
2718         MonoInternalThread *old_thread;
2719         DebuggerTlsData *tls;
2720
2721         if (tid == debugger_thread_id)
2722                 return;
2723
2724         g_assert (thread->tid == tid);
2725
2726         mono_loader_lock ();
2727         old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
2728         mono_loader_unlock ();
2729         if (old_thread) {
2730                 if (thread == old_thread) {
2731                         /* 
2732                          * For some reason, thread_startup () might be called for the same thread
2733                          * multiple times (attach ?).
2734                          */
2735                         DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
2736                         return;
2737                 } else {
2738                         /*
2739                          * thread_end () might not be called for some threads, and the tid could
2740                          * get reused.
2741                          */
2742                         DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
2743                         mono_loader_lock ();
2744                         mono_g_hash_table_remove (thread_to_tls, old_thread);
2745                         mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
2746                         mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
2747                         mono_loader_unlock ();
2748                 }
2749         }
2750
2751         tls = TlsGetValue (debugger_tls_id);
2752         g_assert (!tls);
2753         // FIXME: Free this somewhere
2754         tls = g_new0 (DebuggerTlsData, 1);
2755         tls->resume_event = CreateEvent (NULL, FALSE, FALSE, NULL);
2756         MONO_GC_REGISTER_ROOT (tls->thread);
2757         tls->thread = thread;
2758         TlsSetValue (debugger_tls_id, tls);
2759
2760         DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
2761
2762         mono_loader_lock ();
2763         mono_g_hash_table_insert (thread_to_tls, thread, tls);
2764         mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
2765         mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
2766         mono_loader_unlock ();
2767
2768         process_profiler_event (EVENT_KIND_THREAD_START, thread);
2769
2770         /* 
2771          * suspend_vm () could have missed this thread, so wait for a resume.
2772          */
2773         suspend_current ();
2774 }
2775
2776 static void
2777 thread_end (MonoProfiler *prof, gsize tid)
2778 {
2779         MonoInternalThread *thread;
2780         DebuggerTlsData *tls = NULL;
2781
2782         mono_loader_lock ();
2783         thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
2784         if (thread) {
2785                 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2786                 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
2787                 tls->terminated = TRUE;
2788                 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
2789                 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
2790                 MONO_GC_UNREGISTER_ROOT (tls->thread);
2791                 tls->thread = NULL;
2792         }
2793         mono_loader_unlock ();
2794
2795         /* We might be called for threads started before we registered the start callback */
2796         if (thread) {
2797                 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
2798                 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
2799         }
2800 }
2801
2802 static void
2803 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
2804 {
2805         process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
2806 }
2807
2808 static void
2809 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
2810 {
2811         process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
2812 }
2813
2814 static void
2815 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
2816 {
2817         /* Sent later in jit_end () */
2818         mono_loader_lock ();
2819         g_ptr_array_add (pending_assembly_loads, assembly);
2820         mono_loader_unlock ();
2821 }
2822
2823 static void
2824 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
2825 {
2826         process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
2827 }
2828
2829 static void
2830 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
2831 {
2832 #if defined(HOST_WIN32) && !defined(__GNUC__)
2833         gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
2834 #else
2835         gpointer stackptr = __builtin_frame_address (1);
2836 #endif
2837         MonoInternalThread *thread = mono_thread_internal_current ();
2838         DebuggerTlsData *tls;
2839
2840         mono_loader_lock ();
2841         
2842         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2843         /* Could be the debugger thread with assembly/type load hooks */
2844         if (tls)
2845                 tls->invoke_addr = stackptr;
2846
2847         mono_loader_unlock ();
2848 }
2849
2850 static void
2851 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
2852 {
2853         int i;
2854 #if defined(HOST_WIN32) && !defined(__GNUC__)
2855         gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
2856 #else
2857         gpointer stackptr = __builtin_frame_address (1);
2858 #endif
2859
2860         if (ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
2861                 return;
2862
2863         /*
2864          * We need to stop single stepping when exiting a runtime invoke, since if it is
2865          * a step out, it may return to native code, and thus never end.
2866          */
2867         mono_loader_lock ();
2868         ss_invoke_addr = NULL;
2869
2870         for (i = 0; i < event_requests->len; ++i) {
2871                 EventRequest *req = g_ptr_array_index (event_requests, i);
2872
2873                 if (req->event_kind == EVENT_KIND_STEP) {
2874                         ss_destroy (req->info);
2875                         g_ptr_array_remove_index_fast (event_requests, i);
2876                         g_free (req);
2877                         break;
2878                 }
2879         }
2880         mono_loader_unlock ();
2881 }
2882
2883 static void
2884 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
2885 {
2886         /*
2887          * We emit type load events when the first method of the type is JITted,
2888          * since the class load profiler callbacks might be called with the
2889          * loader lock held. They could also occur in the debugger thread.
2890          * Same for assembly load events.
2891          */
2892         gboolean type_load = FALSE;
2893
2894         while (TRUE) {
2895                 MonoAssembly *assembly = NULL;
2896
2897                 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
2898                 mono_loader_lock ();
2899                 if (pending_assembly_loads->len > 0) {
2900                         assembly = g_ptr_array_index (pending_assembly_loads, 0);
2901                         g_ptr_array_remove_index (pending_assembly_loads, 0);
2902                 }
2903                 mono_loader_unlock ();
2904
2905                 if (assembly)
2906                         process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
2907                 else
2908                         break;
2909         }
2910
2911         mono_loader_lock ();
2912         if (!g_hash_table_lookup (loaded_classes, method->klass)) {
2913                 type_load = TRUE;
2914                 g_hash_table_insert (loaded_classes, method->klass, method->klass);
2915         }
2916         mono_loader_unlock ();
2917         if (type_load)
2918                 process_profiler_event (EVENT_KIND_TYPE_LOAD, method->klass);
2919
2920         if (!result)
2921                 add_pending_breakpoints (method, jinfo);
2922 }
2923
2924 /*
2925  * BREAKPOINTS/SINGLE STEPPING
2926  */
2927
2928 /* 
2929  * Contains information about an inserted breakpoint.
2930  */
2931 typedef struct {
2932         long il_offset, native_offset;
2933         guint8 *ip;
2934         gboolean pending, entry;
2935         MonoJitInfo *ji;
2936 } BreakpointInstance;
2937
2938 /*
2939  * Contains generic information about a breakpoint.
2940  */
2941 typedef struct {
2942         /* 
2943          * The method where the breakpoint is placed. Can be NULL in which case it 
2944          * is inserted into every method. This is used to implement method entry/
2945          * exit events. Can be a generic method definition, in which case the
2946          * breakpoint is inserted into every instance.
2947          */
2948         MonoMethod *method;
2949         long il_offset;
2950         gboolean pending, entry;
2951         EventRequest *req;
2952         /* 
2953          * A list of BreakpointInstance structures describing where the breakpoint
2954          * was inserted. There could be more than one because of 
2955          * generics/appdomains/method entry/exit.
2956          */
2957         GPtrArray *children;
2958 } MonoBreakpoint;
2959
2960 /* List of breakpoints */
2961 static GPtrArray *breakpoints;
2962 /* Maps breakpoint locations to the number of breakpoints at that location */
2963 static GHashTable *bp_locs;
2964
2965 static void
2966 breakpoints_init (void)
2967 {
2968         breakpoints = g_ptr_array_new ();
2969         bp_locs = g_hash_table_new (NULL, NULL);
2970 }       
2971
2972 static void
2973 breakpoints_cleanup (void)
2974 {
2975         int i;
2976
2977         mono_loader_lock ();
2978
2979         for (i = 0; i < breakpoints->len; ++i)
2980                 g_free (g_ptr_array_index (breakpoints, i));
2981
2982         g_ptr_array_free (breakpoints, TRUE);
2983         g_hash_table_destroy (bp_locs);
2984
2985         mono_loader_unlock ();
2986 }
2987
2988 /*
2989  * insert_breakpoint:
2990  *
2991  *   Insert the breakpoint described by BP into the method described by
2992  * JI.
2993  */
2994 static void
2995 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoJitInfo *ji, MonoBreakpoint *bp)
2996 {
2997         int i, count;
2998         gint32 il_offset, native_offset;
2999         BreakpointInstance *inst;
3000
3001         native_offset = 0;
3002         for (i = 0; i < seq_points->len; ++i) {
3003                 il_offset = seq_points->seq_points [i].il_offset;
3004                 native_offset = seq_points->seq_points [i].native_offset;
3005
3006                 if (il_offset == bp->il_offset)
3007                         break;
3008         }
3009
3010         if (i == seq_points->len)
3011                 /* Have to handle this somehow */
3012                 NOT_IMPLEMENTED;
3013
3014         inst = g_new0 (BreakpointInstance, 1);
3015         inst->native_offset = native_offset;
3016         inst->ip = (guint8*)ji->code_start + native_offset;
3017         inst->ji = ji;
3018
3019         mono_loader_lock ();
3020
3021         g_ptr_array_add (bp->children, inst);
3022
3023         count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
3024         g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
3025         mono_loader_unlock ();
3026
3027         if (count == 0) {
3028 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3029                 mono_arch_set_breakpoint (ji, inst->ip);
3030 #else
3031                 NOT_IMPLEMENTED;
3032 #endif
3033         }
3034 }
3035
3036 static void
3037 remove_breakpoint (BreakpointInstance *inst)
3038 {
3039 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3040         int count;
3041         MonoJitInfo *ji = inst->ji;
3042         guint8 *ip = inst->ip;
3043
3044         mono_loader_lock ();
3045         count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
3046         g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
3047         mono_loader_unlock ();
3048
3049         g_assert (count > 0);
3050
3051         if (count == 1) {
3052                 mono_arch_clear_breakpoint (ji, ip);
3053         }
3054 #else
3055         NOT_IMPLEMENTED;
3056 #endif
3057 }       
3058
3059 /*
3060  * add_pending_breakpoints:
3061  *
3062  *   Insert pending breakpoints into the newly JITted method METHOD.
3063  */
3064 static void
3065 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
3066 {
3067         int i;
3068         MonoSeqPointInfo *seq_points;
3069         MonoDomain *domain;
3070
3071         if (!breakpoints)
3072                 return;
3073
3074         domain = mono_domain_get ();
3075
3076         mono_loader_lock ();
3077
3078         for (i = 0; i < breakpoints->len; ++i) {
3079                 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
3080
3081                 if (bp->pending && (bp->method == method || !bp->method || (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method))) {
3082                         mono_domain_lock (domain);
3083                         seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
3084                         mono_domain_unlock (domain);
3085                         if (!seq_points)
3086                                 /* Could be AOT code */
3087                                 continue;
3088                         g_assert (seq_points);
3089
3090                         insert_breakpoint (seq_points, ji, bp);
3091                 }
3092         }
3093
3094         mono_loader_unlock ();
3095 }
3096
3097 static void
3098 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp)
3099 {
3100         gpointer code;
3101         MonoJitInfo *ji;
3102
3103         code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
3104         if (!code) {
3105                 /* Might be AOTed code */
3106                 code = mono_aot_get_method (domain, method);
3107                 g_assert (code);
3108                 ji = mono_jit_info_table_find (domain, code);
3109                 g_assert (ji);
3110         }
3111         g_assert (code);
3112
3113         insert_breakpoint (seq_points, ji, bp);
3114 }
3115
3116 static void
3117 set_bp_in_method_cb (gpointer key, gpointer value, gpointer user_data)
3118 {
3119         MonoMethod *method = key;
3120         MonoSeqPointInfo *seq_points = value;
3121         MonoBreakpoint *bp = user_data;
3122         MonoDomain *domain = mono_domain_get ();
3123
3124         if (bp->method) {
3125                 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method) {
3126                         /* Generic instance */
3127                         set_bp_in_method (domain, method, seq_points, bp);
3128                 }
3129         } else {
3130                 /* Method entry/exit */
3131                 set_bp_in_method (domain, method, seq_points, bp);
3132         }
3133 }
3134
3135 /*
3136  * set_breakpoint:
3137  *
3138  *   Set a breakpoint at IL_OFFSET in METHOD.
3139  * METHOD can be NULL, in which case a breakpoint is placed in all methods.
3140  * METHOD can also be a generic method definition, in which case a breakpoint
3141  * is placed in all instances of the method.
3142  */
3143 static MonoBreakpoint*
3144 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req)
3145 {
3146         MonoSeqPointInfo *seq_points;
3147         MonoDomain *domain;
3148         MonoBreakpoint *bp;
3149
3150         // FIXME: 
3151         // - suspend/resume the vm to prevent code patching problems
3152         // - appdomains
3153         // - multiple breakpoints on the same location
3154         // - dynamic methods
3155         // - races
3156
3157         bp = g_new0 (MonoBreakpoint, 1);
3158         bp->method = method;
3159         bp->il_offset = il_offset;
3160         bp->req = req;
3161         bp->children = g_ptr_array_new ();
3162
3163         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));
3164
3165         domain = mono_domain_get ();
3166         mono_domain_lock (domain);
3167         if (method) {
3168                 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
3169                 if (seq_points) {
3170                         set_bp_in_method (domain, method, seq_points, bp);
3171                 } else {
3172                         if (method->is_generic)
3173                                 /* There might be already JITted instances */
3174                                 g_hash_table_foreach (domain_jit_info (domain)->seq_points, set_bp_in_method_cb, bp);
3175
3176                         /* Not yet JITted */
3177                         bp->pending = TRUE;
3178                 }
3179         } else {
3180                 g_hash_table_foreach (domain_jit_info (domain)->seq_points, set_bp_in_method_cb, bp);
3181                 bp->pending = TRUE;
3182         }
3183         mono_domain_unlock (domain);
3184
3185         mono_loader_lock ();
3186         g_ptr_array_add (breakpoints, bp);
3187         mono_loader_unlock ();
3188
3189         return bp;
3190 }
3191
3192 static void
3193 clear_breakpoint (MonoBreakpoint *bp)
3194 {
3195         int i;
3196
3197         // FIXME: locking, races
3198         for (i = 0; i < bp->children->len; ++i) {
3199                 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
3200
3201                 remove_breakpoint (inst);
3202
3203                 g_free (inst);
3204         }
3205
3206         mono_loader_lock ();
3207         g_ptr_array_remove (breakpoints, bp);
3208         mono_loader_unlock ();
3209
3210         g_ptr_array_free (bp->children, TRUE);
3211         g_free (bp);
3212 }
3213
3214 static void
3215 process_breakpoint_inner (DebuggerTlsData *tls, MonoContext *ctx)
3216 {
3217         MonoJitInfo *ji;
3218         guint8 *orig_ip, *ip;
3219         int i, j, suspend_policy;
3220         guint32 native_offset;
3221         MonoBreakpoint *bp;
3222         BreakpointInstance *inst;
3223         GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
3224         GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
3225         EventKind kind = EVENT_KIND_BREAKPOINT;
3226
3227         // FIXME: Speed this up
3228
3229         orig_ip = ip = MONO_CONTEXT_GET_IP (ctx);
3230         ji = mono_jit_info_table_find (mono_domain_get (), (char*)ip);
3231         g_assert (ji);
3232         g_assert (ji->method);
3233
3234         /* Compute the native offset of the breakpoint from the ip */
3235 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3236         ip = mono_arch_get_ip_for_breakpoint (ji, ctx);
3237         native_offset = ip - (guint8*)ji->code_start;   
3238 #else
3239         NOT_IMPLEMENTED;
3240 #endif
3241
3242         /* 
3243          * Skip the instruction causing the breakpoint signal.
3244          */
3245         mono_arch_skip_breakpoint (ctx);
3246
3247         if (ji->method->wrapper_type || tls->disable_breakpoints)
3248                 return;
3249
3250         bp_reqs = g_ptr_array_new ();
3251         ss_reqs = g_ptr_array_new ();
3252         ss_reqs_orig = g_ptr_array_new ();
3253
3254         DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, offset=0x%x.\n", (gpointer)GetCurrentThreadId (), ji->method->name, native_offset));
3255
3256         mono_loader_lock ();
3257
3258         bp = NULL;
3259         for (i = 0; i < breakpoints->len; ++i) {
3260                 bp = g_ptr_array_index (breakpoints, i);
3261
3262                 if (!bp->method)
3263                         continue;
3264
3265                 for (j = 0; j < bp->children->len; ++j) {
3266                         inst = g_ptr_array_index (bp->children, j);
3267                         if (inst->ji == ji && inst->native_offset == native_offset) {
3268                                 if (bp->req->event_kind == EVENT_KIND_STEP) {
3269                                         g_ptr_array_add (ss_reqs_orig, bp->req);
3270                                 } else {
3271                                         g_ptr_array_add (bp_reqs, bp->req);
3272                                 }
3273                         }
3274                 }
3275         }
3276         if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
3277                 MonoSeqPointInfo *seq_points;
3278                 int seq_il_offset, seq_native_offset;
3279                 MonoDomain *domain = mono_domain_get ();
3280
3281                 /* Maybe a method entry/exit event */
3282                 mono_domain_lock (domain);
3283                 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
3284                 mono_domain_unlock (domain);
3285                 if (!seq_points) {
3286                         // FIXME: Generic sharing */
3287                         mono_loader_unlock ();
3288                         return;
3289                 }
3290                 g_assert (seq_points);
3291
3292                 for (i = 0; i < seq_points->len; ++i) {
3293                         seq_il_offset = seq_points->seq_points [i].il_offset;
3294                         seq_native_offset = seq_points->seq_points [i].native_offset;
3295
3296                         if (native_offset == seq_native_offset) {
3297                                 if (seq_il_offset == METHOD_ENTRY_IL_OFFSET)
3298                                         kind = EVENT_KIND_METHOD_ENTRY;
3299                                 else if (seq_il_offset == METHOD_EXIT_IL_OFFSET)
3300                                         kind = EVENT_KIND_METHOD_EXIT;
3301                                 break;
3302                         }
3303                 }
3304         }
3305
3306         /* Process single step requests */
3307         for (i = 0; i < ss_reqs_orig->len; ++i) {
3308                 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
3309                 SingleStepReq *ss_req = bp->req->info;
3310                 gboolean hit = TRUE;
3311                 MonoSeqPointInfo *info;
3312                 SeqPoint *sp;
3313
3314                 sp = find_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
3315                 g_assert (sp);
3316
3317                 if (ss_req->size == STEP_SIZE_LINE) {
3318                         /* Have to check whenever a different source line was reached */
3319                         MonoDebugMethodInfo *minfo;
3320                         MonoDebugSourceLocation *loc = NULL;
3321
3322                         minfo = mono_debug_lookup_method (ji->method);
3323
3324                         if (minfo)
3325                                 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
3326
3327                         if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line))
3328                                 /* Have to continue single stepping */
3329                                 hit = FALSE;
3330                                 
3331                         if (loc) {
3332                                 ss_req->last_method = ji->method;
3333                                 ss_req->last_line = loc->row;
3334                                 mono_debug_free_source_location (loc);
3335                         }
3336                 }
3337
3338                 if (hit)
3339                         g_ptr_array_add (ss_reqs, req);
3340
3341                 /* Start single stepping again from the current sequence point */
3342                 ss_start (ss_req, ji->method, sp, info, ctx, NULL);
3343         }
3344         
3345         if (ss_reqs->len > 0)
3346                 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
3347         if (bp_reqs->len > 0)
3348                 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
3349         if (kind != EVENT_KIND_BREAKPOINT)
3350                 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
3351
3352         mono_loader_unlock ();
3353
3354         g_ptr_array_free (bp_reqs, TRUE);
3355         g_ptr_array_free (ss_reqs, TRUE);
3356
3357         /* 
3358          * FIXME: The first event will suspend, so the second will only be sent after the
3359          * resume.
3360          */
3361         if (ss_events)
3362                 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
3363         if (bp_events)
3364                 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
3365         if (enter_leave_events)
3366                 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
3367 }
3368
3369 static void
3370 process_breakpoint (void)
3371 {
3372         DebuggerTlsData *tls;
3373         MonoContext ctx;
3374         static void (*restore_context) (void *);
3375
3376         if (!restore_context)
3377                 restore_context = mono_get_restore_context ();
3378
3379         tls = TlsGetValue (debugger_tls_id);
3380         memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
3381
3382         process_breakpoint_inner (tls, &ctx);
3383
3384         /* This is called when resuming from a signal handler, so it shouldn't return */
3385         restore_context (&ctx);
3386         g_assert_not_reached ();
3387 }
3388
3389 static void
3390 resume_from_signal_handler (void *sigctx, void *func)
3391 {
3392         DebuggerTlsData *tls;
3393         MonoContext ctx;
3394
3395         /* Save the original context in TLS */
3396         // FIXME: This might not work on an altstack ?
3397         tls = TlsGetValue (debugger_tls_id);
3398         g_assert (tls);
3399
3400         // FIXME: MonoContext usually doesn't include the fp registers, so these are 
3401         // clobbered by a single step/breakpoint event. If this turns out to be a problem,
3402         // clob:c could be added to op_seq_point.
3403
3404         mono_arch_sigctx_to_monoctx (sigctx, &ctx);
3405         memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
3406         MONO_CONTEXT_SET_IP (&ctx, func);
3407         mono_arch_monoctx_to_sigctx (&ctx, sigctx);
3408
3409 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3410         mono_ppc_set_func_into_sigctx (sigctx, func);
3411 #endif
3412 }
3413
3414 void
3415 mono_debugger_agent_breakpoint_hit (void *sigctx)
3416 {
3417         /*
3418          * We are called from a signal handler, and running code there causes all kinds of
3419          * problems, like the original signal is disabled, libgc can't handle altstack, etc.
3420          * So set up the signal context to return to the real breakpoint handler function.
3421          */
3422
3423         resume_from_signal_handler (sigctx, process_breakpoint);
3424 }
3425
3426 static void
3427 process_single_step_inner (DebuggerTlsData *tls, MonoContext *ctx)
3428 {
3429         MonoJitInfo *ji;
3430         guint8 *ip;
3431         GPtrArray *reqs;
3432         int il_offset, suspend_policy;
3433         MonoDomain *domain = mono_domain_get ();
3434         GSList *events;
3435
3436         // FIXME: Speed this up
3437
3438         ip = MONO_CONTEXT_GET_IP (ctx);
3439
3440         /* Skip the instruction causing the single step */
3441         mono_arch_skip_single_step (ctx);
3442
3443         if (suspend_count > 0) {
3444                 process_suspend (tls, ctx);
3445                 return;
3446         }
3447
3448         if (!ss_req)
3449                 // FIXME: A suspend race
3450                 return;
3451
3452         if (mono_thread_internal_current () != ss_req->thread)
3453                 return;
3454
3455         if (log_level > 0) {
3456                 const char *depth = NULL;
3457
3458                 ji = mono_jit_info_table_find (mono_domain_get (), (char*)ip);
3459
3460                 switch (ss_req->depth) {
3461                 case STEP_DEPTH_OVER:
3462                         depth = "over";
3463                         break;
3464                 case STEP_DEPTH_OUT:
3465                         depth = "out";
3466                         break;
3467                 case STEP_DEPTH_INTO:
3468                         depth = "into";
3469                         break;
3470                 default:
3471                         g_assert_not_reached ();
3472                 }
3473                         
3474                 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));
3475         }
3476
3477         /*
3478          * We implement step over/out by single stepping until we reach the same 
3479          * frame/parent frame.
3480          * FIXME:
3481          * - this is slow
3482          * - stack growing upward
3483          * - localloc
3484          * - exceptions
3485          */
3486         if (ss_req->depth != STEP_DEPTH_INTO) {
3487                 if (ss_req->depth == STEP_DEPTH_OVER && MONO_CONTEXT_GET_SP (ctx) < ss_req->last_sp)
3488                         return;
3489                 if (ss_req->depth == STEP_DEPTH_OUT && MONO_CONTEXT_GET_SP (ctx) <= ss_req->last_sp)
3490                         return;
3491
3492                 ss_req->last_sp = MONO_CONTEXT_GET_SP (ctx);
3493         }
3494
3495         ji = mono_jit_info_table_find (mono_domain_get (), (char*)ip);
3496         g_assert (ji);
3497         g_assert (ji->method);
3498
3499         if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
3500                 return;
3501
3502         /* 
3503          * FIXME: 
3504          * Stopping in memset makes half-initialized vtypes visible.
3505          * Stopping in memcpy makes half-copied vtypes visible.
3506          */
3507         if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
3508                 return;
3509
3510         /* 
3511          * The ip points to the instruction causing the single step event, convert it
3512          * to the offset stored in seq_points.
3513          */
3514 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3515         ip = mono_arch_get_ip_for_single_step (ji, ctx);
3516 #else
3517         g_assert_not_reached ();
3518 #endif
3519
3520         /* 
3521          * mono_debug_lookup_source_location () doesn't work for IL offset 0 for 
3522          * example, so do things by hand.
3523          */
3524         il_offset = compute_il_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start);
3525
3526         if (il_offset == -1)
3527                 return;
3528
3529         if (ss_req->size == STEP_SIZE_LINE) {
3530                 /* Step until a different source line is reached */
3531                 MonoDebugMethodInfo *minfo;
3532
3533                 minfo = mono_debug_lookup_method (ji->method);
3534
3535                 if (minfo) {
3536                         MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
3537
3538                         if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
3539                                 mono_debug_free_source_location (loc);
3540                                 return;
3541                         }
3542                         if (!loc)
3543                                 /*
3544                                  * Step until we reach a location with line number info, 
3545                                  * otherwise the client can't show a location.
3546                                  * This can happen for example with statics initialized inline
3547                                  * outside of a cctor.
3548                                  */
3549                                 return;
3550
3551                         if (loc) {
3552                                 ss_req->last_method = ji->method;
3553                                 ss_req->last_line = loc->row;
3554                                 mono_debug_free_source_location (loc);
3555                         }
3556                 }
3557         }
3558
3559         // FIXME: Has to lock earlier
3560
3561         reqs = g_ptr_array_new ();
3562
3563         mono_loader_lock ();
3564
3565         g_ptr_array_add (reqs, ss_req->req);
3566
3567         events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
3568
3569         g_ptr_array_free (reqs, TRUE);
3570
3571         mono_loader_unlock ();
3572
3573         process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
3574 }
3575
3576 static void
3577 process_single_step (void)
3578 {
3579         DebuggerTlsData *tls;
3580         MonoContext ctx;
3581         static void (*restore_context) (void *);
3582
3583         if (!restore_context)
3584                 restore_context = mono_get_restore_context ();
3585
3586         tls = TlsGetValue (debugger_tls_id);
3587         memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
3588
3589         process_single_step_inner (tls, &ctx);
3590
3591         /* This is called when resuming from a signal handler, so it shouldn't return */
3592         restore_context (&ctx);
3593         g_assert_not_reached ();
3594 }
3595
3596 /*
3597  * mono_debugger_agent_single_step_event:
3598  *
3599  *   Called from a signal handler to handle a single step event.
3600  */
3601 void
3602 mono_debugger_agent_single_step_event (void *sigctx)
3603 {
3604         /* Resume to process_single_step through the signal context */
3605
3606         // FIXME: Since step out/over is implemented using step in, the step in case should
3607         // be as fast as possible. Move the relevant code from process_single_step_inner ()
3608         // here
3609
3610         if (GetCurrentThreadId () == debugger_thread_id) {
3611                 /* 
3612                  * This could happen despite our best effors when the runtime calls 
3613                  * assembly/type resolve hooks.
3614                  * FIXME: Breakpoints too.
3615                  */
3616                 MonoContext ctx;
3617
3618                 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
3619                 mono_arch_skip_single_step (&ctx);
3620                 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
3621                 return;
3622         }
3623
3624         resume_from_signal_handler (sigctx, process_single_step);
3625 }
3626
3627 /*
3628  * start_single_stepping:
3629  *
3630  *   Turn on single stepping. Can be called multiple times, for example,
3631  * by a single step event request + a suspend.
3632  */
3633 static void
3634 start_single_stepping (void)
3635 {
3636 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3637         int val = InterlockedIncrement (&ss_count);
3638
3639         if (val == 1)
3640                 mono_arch_start_single_stepping ();
3641
3642         if (ss_req != NULL && ss_invoke_addr == NULL) {
3643                 DebuggerTlsData *tls;
3644         
3645                 mono_loader_lock ();
3646         
3647                 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
3648                 ss_invoke_addr = tls->invoke_addr;
3649                 
3650                 mono_loader_unlock ();
3651         }
3652 #else
3653         g_assert_not_reached ();
3654 #endif
3655 }
3656
3657 static void
3658 stop_single_stepping (void)
3659 {
3660 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3661         int val = InterlockedDecrement (&ss_count);
3662
3663         if (val == 0)
3664                 mono_arch_stop_single_stepping ();
3665 #else
3666         g_assert_not_reached ();
3667 #endif
3668 }
3669
3670 /*
3671  * ss_stop:
3672  *
3673  *   Stop the single stepping operation given by SS_REQ.
3674  */
3675 static void
3676 ss_stop (SingleStepReq *ss_req)
3677 {
3678         gboolean use_bps = FALSE;
3679
3680         if (ss_req->bps) {
3681                 GSList *l;
3682
3683                 use_bps = TRUE;
3684
3685                 for (l = ss_req->bps; l; l = l->next) {
3686                         clear_breakpoint (l->data);
3687                 }
3688                 g_slist_free (ss_req->bps);
3689                 ss_req->bps = NULL;
3690         }
3691
3692         if (ss_req->global) {
3693                 stop_single_stepping ();
3694                 ss_req->global = FALSE;
3695         }
3696 }
3697
3698 /*
3699  * ss_start:
3700  *
3701  *   Start the single stepping operation given by SS_REQ from the sequence point SP.
3702  */
3703 static void
3704 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls)
3705 {
3706         gboolean use_bp = FALSE;
3707         int i, frame_index;
3708         SeqPoint *next_sp;
3709         MonoBreakpoint *bp;
3710
3711         /* Stop the previous operation */
3712         ss_stop (ss_req);
3713
3714         /*
3715          * Implement single stepping using breakpoints if possible.
3716          */
3717         if (ss_req->depth == STEP_DEPTH_OVER) {
3718                 frame_index = 1;
3719                 /*
3720                  * Find the first sequence point in the current or in a previous frame which
3721                  * is not the last in its method.
3722                  */
3723                 while (sp && sp->next_len == 0) {
3724                         sp = NULL;
3725                         if (tls && frame_index < tls->frame_count) {
3726                                 StackFrame *frame = tls->frames [frame_index];
3727
3728                                 method = frame->method;
3729                                 if (frame->il_offset != -1) {
3730                                         sp = find_seq_point (frame->domain, frame->method, frame->il_offset, &info);
3731                                 }
3732                                 frame_index ++;
3733                         }
3734                 }
3735
3736                 if (sp && sp->next_len > 0) {
3737                         use_bp = TRUE;
3738                         for (i = 0; i < sp->next_len; ++i) {
3739                                 next_sp = &info->seq_points [sp->next [i]];
3740
3741                                 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req);
3742                                 ss_req->bps = g_slist_append (ss_req->bps, bp);
3743                         }
3744                 }
3745         }
3746
3747         if (!ss_req->bps) {
3748                 ss_req->global = TRUE;
3749                 start_single_stepping ();
3750         } else {
3751                 ss_req->global = FALSE;
3752         }
3753 }
3754
3755 /*
3756  * Start single stepping of thread THREAD
3757  */
3758 static ErrorCode
3759 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
3760 {
3761         DebuggerTlsData *tls;
3762         MonoSeqPointInfo *info;
3763         SeqPoint *sp = NULL;
3764         MonoMethod *method = NULL;
3765
3766         if (suspend_count == 0)
3767                 return ERR_NOT_SUSPENDED;
3768
3769         wait_for_suspend ();
3770
3771         // FIXME: Multiple requests
3772         if (ss_req) {
3773                 DEBUG (0, printf ("Received a single step request while the previous one was still active.\n"));
3774                 return ERR_NOT_IMPLEMENTED;
3775         }
3776
3777         ss_req = g_new0 (SingleStepReq, 1);
3778         ss_req->req = req;
3779         ss_req->thread = thread;
3780         ss_req->size = size;
3781         ss_req->depth = depth;
3782         req->info = ss_req;
3783
3784         mono_loader_lock ();
3785         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3786         mono_loader_unlock ();
3787         g_assert (tls);
3788         g_assert (tls->has_context);
3789         ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->ctx);
3790
3791         if (ss_req->size == STEP_SIZE_LINE) {
3792                 StackFrame *frame;
3793                 MonoDebugMethodInfo *minfo;
3794
3795                 /* Compute the initial line info */
3796                 compute_frame_info (thread, tls);
3797
3798                 g_assert (tls->frame_count);
3799                 frame = tls->frames [0];
3800
3801                 ss_req->last_method = frame->method;
3802                 ss_req->last_line = -1;
3803
3804                 minfo = mono_debug_lookup_method (frame->method);
3805                 if (minfo && frame->il_offset != -1) {
3806                         MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
3807
3808                         if (loc) {
3809                                 ss_req->last_line = loc->row;
3810                                 g_free (loc);
3811                         }
3812                 }
3813         }
3814
3815         if (ss_req->depth == STEP_DEPTH_OVER) {
3816                 StackFrame *frame;
3817
3818                 compute_frame_info (thread, tls);
3819
3820                 g_assert (tls->frame_count);
3821                 frame = tls->frames [0];
3822
3823                 if (frame->il_offset != -1) {
3824                         /* FIXME: Sort the table and use a binary search */
3825                         sp = find_seq_point (frame->domain, frame->method, frame->il_offset, &info);
3826                         g_assert (sp);
3827                         method = frame->method;
3828                 }
3829         }
3830
3831         ss_start (ss_req, method, sp, info, NULL, tls);
3832
3833         return 0;
3834 }
3835
3836 static void
3837 ss_destroy (SingleStepReq *req)
3838 {
3839         // FIXME: Locking
3840         g_assert (ss_req == req);
3841
3842         ss_stop (ss_req);
3843
3844         g_free (ss_req);
3845         ss_req = NULL;
3846 }
3847
3848 void
3849 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *ctx)
3850 {
3851         int suspend_policy;
3852         GSList *events;
3853         MonoJitInfo *ji;
3854
3855         /* Just-In-Time debugging */
3856         if (agent_config.onthrow && !inited) {
3857                 GSList *l;
3858                 gboolean found = FALSE;
3859
3860                 for (l = agent_config.onthrow; l; l = l->next) {
3861                         char *ex_type = l->data;
3862                         char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
3863
3864                         if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
3865                                 found = TRUE;
3866
3867                         g_free (f);
3868                 }
3869
3870                 if (found) {
3871                         finish_agent_init (FALSE);
3872
3873                         /*
3874                          * Send an unsolicited EXCEPTION event with a dummy request id.
3875                          */
3876                         events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
3877                         process_event (EVENT_KIND_EXCEPTION, exc, 0, ctx, events, SUSPEND_POLICY_ALL);
3878                         return;
3879                 }
3880         }
3881
3882         if (!inited)
3883                 return;
3884
3885         ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (ctx), NULL);
3886
3887         mono_loader_lock ();
3888         events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, exc, &suspend_policy);
3889         mono_loader_unlock ();
3890
3891         process_event (EVENT_KIND_EXCEPTION, exc, 0, ctx, events, suspend_policy);
3892 }
3893
3894 void
3895 mono_debugger_agent_handle_unhandled_exception (MonoException *exc, MonoContext *ctx)
3896 {
3897         GSList *events;
3898
3899         if (!agent_config.onuncaught)
3900                 return;
3901
3902         finish_agent_init (FALSE);
3903
3904         /*
3905          * Send an unsolicited EXCEPTION event with a dummy request id.
3906          */
3907         events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
3908         process_event (EVENT_KIND_EXCEPTION, exc, 0, ctx, events, SUSPEND_POLICY_ALL);
3909 }
3910
3911 /*
3912  * buffer_add_value_full:
3913  *
3914  *   Add the encoding of the value at ADDR described by T to the buffer.
3915  * AS_VTYPE determines whenever to treat primitive types as primitive types or
3916  * vtypes.
3917  */
3918 static void
3919 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
3920                                            gboolean as_vtype)
3921 {
3922         MonoObject *obj;
3923
3924         if (t->byref) {
3925                 g_assert (*(void**)addr);
3926                 addr = *(void**)addr;
3927         }
3928
3929         if (as_vtype) {
3930                 switch (t->type) {
3931                 case MONO_TYPE_BOOLEAN:
3932                 case MONO_TYPE_I1:
3933                 case MONO_TYPE_U1:
3934                 case MONO_TYPE_CHAR:
3935                 case MONO_TYPE_I2:
3936                 case MONO_TYPE_U2:
3937                 case MONO_TYPE_I4:
3938                 case MONO_TYPE_U4:
3939                 case MONO_TYPE_R4:
3940                 case MONO_TYPE_I8:
3941                 case MONO_TYPE_U8:
3942                 case MONO_TYPE_R8:
3943                 case MONO_TYPE_I:
3944                 case MONO_TYPE_U:
3945                 case MONO_TYPE_PTR:
3946                         goto handle_vtype;
3947                         break;
3948                 default:
3949                         break;
3950                 }
3951         }
3952
3953         switch (t->type) {
3954         case MONO_TYPE_VOID:
3955                 buffer_add_byte (buf, t->type);
3956                 break;
3957         case MONO_TYPE_BOOLEAN:
3958         case MONO_TYPE_I1:
3959         case MONO_TYPE_U1:
3960                 buffer_add_byte (buf, t->type);
3961                 buffer_add_int (buf, *(gint8*)addr);
3962                 break;
3963         case MONO_TYPE_CHAR:
3964         case MONO_TYPE_I2:
3965         case MONO_TYPE_U2:
3966                 buffer_add_byte (buf, t->type);
3967                 buffer_add_int (buf, *(gint16*)addr);
3968                 break;
3969         case MONO_TYPE_I4:
3970         case MONO_TYPE_U4:
3971         case MONO_TYPE_R4:
3972                 buffer_add_byte (buf, t->type);
3973                 buffer_add_int (buf, *(gint32*)addr);
3974                 break;
3975         case MONO_TYPE_I8:
3976         case MONO_TYPE_U8:
3977         case MONO_TYPE_R8:
3978                 buffer_add_byte (buf, t->type);
3979                 buffer_add_long (buf, *(gint64*)addr);
3980                 break;
3981         case MONO_TYPE_I:
3982         case MONO_TYPE_U:
3983                 /* Treat it as a vtype */
3984                 goto handle_vtype;
3985         case MONO_TYPE_PTR: {
3986                 gssize val = *(gssize*)addr;
3987                 
3988                 buffer_add_byte (buf, t->type);
3989                 buffer_add_long (buf, val);
3990                 break;
3991         }
3992         handle_ref:
3993         case MONO_TYPE_STRING:
3994         case MONO_TYPE_SZARRAY:
3995         case MONO_TYPE_OBJECT:
3996         case MONO_TYPE_CLASS:
3997         case MONO_TYPE_ARRAY:
3998                 obj = *(MonoObject**)addr;
3999
4000                 if (!obj) {
4001                         buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
4002                 } else {
4003                         if (obj->vtable->klass->valuetype) {
4004                                 t = &obj->vtable->klass->byval_arg;
4005                                 addr = mono_object_unbox (obj);
4006                                 goto handle_vtype;
4007                         } else if (obj->vtable->klass->rank) {
4008                                 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
4009                         } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
4010                                 buffer_add_byte (buf, MONO_TYPE_CLASS);
4011                         } else {
4012                                 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
4013                         }
4014                         buffer_add_objid (buf, obj);
4015                 }
4016                 break;
4017         handle_vtype:
4018         case MONO_TYPE_VALUETYPE: {
4019                 int nfields;
4020                 gpointer iter;
4021                 MonoClassField *f;
4022                 MonoClass *klass = mono_class_from_mono_type (t);
4023
4024                 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
4025                 buffer_add_byte (buf, klass->enumtype);
4026                 buffer_add_typeid (buf, domain, klass);
4027
4028                 nfields = 0;
4029                 iter = NULL;
4030                 while ((f = mono_class_get_fields (klass, &iter))) {
4031                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4032                                 continue;
4033                         if (mono_field_is_deleted (f))
4034                                 continue;
4035                         nfields ++;
4036                 }
4037                 buffer_add_int (buf, nfields);
4038
4039                 iter = NULL;
4040                 while ((f = mono_class_get_fields (klass, &iter))) {
4041                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4042                                 continue;
4043                         if (mono_field_is_deleted (f))
4044                                 continue;
4045                         buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
4046                 }
4047                 break;
4048         }
4049         case MONO_TYPE_GENERICINST:
4050                 if (mono_type_generic_inst_is_valuetype (t)) {
4051                         goto handle_vtype;
4052                 } else {
4053                         goto handle_ref;
4054                 }
4055                 break;
4056         default:
4057                 NOT_IMPLEMENTED;
4058         }
4059 }
4060
4061 static void
4062 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
4063 {
4064         buffer_add_value_full (buf, t, addr, domain, FALSE);
4065 }
4066
4067 static ErrorCode
4068 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
4069 {
4070         int err;
4071         int type = decode_byte (buf, &buf, limit);
4072
4073         if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
4074                 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
4075                 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
4076                 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8)) {
4077                 DEBUG(1, fprintf (log_file, "[%p] Expected value of type 0x%0x, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), t->type, type));
4078                 return ERR_INVALID_ARGUMENT;
4079         }
4080
4081         switch (t->type) {
4082         case MONO_TYPE_BOOLEAN:
4083                 *(guint8*)addr = decode_int (buf, &buf, limit);
4084                 break;
4085         case MONO_TYPE_CHAR:
4086                 *(gunichar2*)addr = decode_int (buf, &buf, limit);
4087                 break;
4088         case MONO_TYPE_I1:
4089                 *(gint8*)addr = decode_int (buf, &buf, limit);
4090                 break;
4091         case MONO_TYPE_U1:
4092                 *(guint8*)addr = decode_int (buf, &buf, limit);
4093                 break;
4094         case MONO_TYPE_I2:
4095                 *(gint16*)addr = decode_int (buf, &buf, limit);
4096                 break;
4097         case MONO_TYPE_U2:
4098                 *(guint16*)addr = decode_int (buf, &buf, limit);
4099                 break;
4100         case MONO_TYPE_I4:
4101                 *(gint32*)addr = decode_int (buf, &buf, limit);
4102                 break;
4103         case MONO_TYPE_U4:
4104                 *(guint32*)addr = decode_int (buf, &buf, limit);
4105                 break;
4106         case MONO_TYPE_I8:
4107                 *(gint64*)addr = decode_long (buf, &buf, limit);
4108                 break;
4109         case MONO_TYPE_U8:
4110                 *(guint64*)addr = decode_long (buf, &buf, limit);
4111                 break;
4112         case MONO_TYPE_R4:
4113                 *(guint32*)addr = decode_int (buf, &buf, limit);
4114                 break;
4115         case MONO_TYPE_R8:
4116                 *(guint64*)addr = decode_long (buf, &buf, limit);
4117                 break;
4118         case MONO_TYPE_PTR:
4119                 /* We send these as I8, so we get them back as such */
4120                 g_assert (type == MONO_TYPE_I8);
4121                 *(gssize*)addr = decode_long (buf, &buf, limit);
4122                 break;
4123         case MONO_TYPE_I:
4124         case MONO_TYPE_U:
4125                 /* We send these as vtypes, so we get them back as such */
4126                 g_assert (type == MONO_TYPE_VALUETYPE);
4127                 /* Fall through */
4128         case MONO_TYPE_VALUETYPE: {
4129                 gboolean is_enum = decode_byte (buf, &buf, limit);
4130                 MonoClass *klass;
4131                 MonoClassField *f;
4132                 int nfields;
4133                 gpointer iter = NULL;
4134                 MonoDomain *d;
4135
4136                 /* Enums are sent as a normal vtype */
4137                 if (is_enum)
4138                         return ERR_NOT_IMPLEMENTED;
4139                 klass = decode_typeid (buf, &buf, limit, &d, &err);
4140                 if (err)
4141                         return err;
4142
4143                 if (klass != mono_class_from_mono_type (t))
4144                         return ERR_INVALID_ARGUMENT;
4145
4146                 nfields = decode_int (buf, &buf, limit);
4147                 while ((f = mono_class_get_fields (klass, &iter))) {
4148                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4149                                 continue;
4150                         if (mono_field_is_deleted (f))
4151                                 continue;
4152                         err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
4153                         if (err)
4154                                 return err;
4155                         nfields --;
4156                 }
4157                 g_assert (nfields == 0);
4158                 break;
4159         }
4160         default:
4161                 if (MONO_TYPE_IS_REFERENCE (t)) {
4162                         if (type == MONO_TYPE_OBJECT) {
4163                                 int objid = decode_objid (buf, &buf, limit);
4164                                 int err;
4165                                 MonoObject *obj;
4166
4167                                 err = get_object (objid, (MonoObject**)&obj);
4168                                 if (err)
4169                                         return err;
4170
4171                                 if (obj && !mono_class_is_assignable_from (mono_class_from_mono_type (t), obj->vtable->klass))
4172                                         return ERR_INVALID_ARGUMENT;
4173                                 if (obj && obj->vtable->domain != domain)
4174                                         return ERR_INVALID_ARGUMENT;
4175
4176                                 mono_gc_wbarrier_generic_store (addr, obj);
4177                         } else if (type == VALUE_TYPE_ID_NULL) {
4178                                 *(MonoObject**)addr = NULL;
4179                         } else {
4180                                 return ERR_INVALID_ARGUMENT;
4181                         }
4182                 } else {
4183                         NOT_IMPLEMENTED;
4184                 }
4185                 break;
4186         }
4187
4188         *endbuf = buf;
4189
4190         return 0;
4191 }
4192
4193 static void
4194 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
4195 {
4196         guint32 flags;
4197         int reg;
4198         guint8 *addr;
4199         gpointer reg_val;
4200
4201         flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4202         reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4203
4204         switch (flags) {
4205         case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
4206                 reg_val = mono_arch_context_get_int_reg (ctx, reg);
4207
4208                 buffer_add_value_full (buf, t, &reg_val, domain, as_vtype);
4209                 break;
4210         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
4211                 addr = mono_arch_context_get_int_reg (ctx, reg);
4212                 addr += (gint32)var->offset;
4213
4214                 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
4215
4216                 buffer_add_value_full (buf, t, addr, domain, as_vtype);
4217                 break;
4218         case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
4219                 NOT_IMPLEMENTED;
4220                 break;
4221         default:
4222                 g_assert_not_reached ();
4223         }
4224 }
4225
4226 static void
4227 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val)
4228 {
4229         guint32 flags;
4230         int reg, size;
4231         guint8 *addr;
4232
4233         flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4234         reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4235
4236         if (MONO_TYPE_IS_REFERENCE (t))
4237                 size = sizeof (gpointer);
4238         else
4239                 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
4240
4241         switch (flags) {
4242         case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
4243                 // FIXME: Can't set registers, so we disable linears
4244                 NOT_IMPLEMENTED;
4245                 break;
4246         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
4247                 addr = mono_arch_context_get_int_reg (ctx, reg);
4248                 addr += (gint32)var->offset;
4249
4250                 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
4251
4252                 // FIXME: Write barriers
4253                 memcpy (addr, val, size);
4254                 break;
4255         case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
4256                 NOT_IMPLEMENTED;
4257                 break;
4258         default:
4259                 g_assert_not_reached ();
4260         }
4261 }
4262
4263 static void
4264 clear_event_request (int req_id, int etype)
4265 {
4266         int i;
4267
4268         mono_loader_lock ();
4269         for (i = 0; i < event_requests->len; ++i) {
4270                 EventRequest *req = g_ptr_array_index (event_requests, i);
4271
4272                 if (req->id == req_id && req->event_kind == etype) {
4273                         if (req->event_kind == EVENT_KIND_BREAKPOINT)
4274                                 clear_breakpoint (req->info);
4275                         if (req->event_kind == EVENT_KIND_STEP)
4276                                 ss_destroy (req->info);
4277                         if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
4278                                 clear_breakpoint (req->info);
4279                         if (req->event_kind == EVENT_KIND_METHOD_EXIT)
4280                                 clear_breakpoint (req->info);
4281                         g_ptr_array_remove_index_fast (event_requests, i);
4282                         g_free (req);
4283                         break;
4284                 }
4285         }
4286         mono_loader_unlock ();
4287 }
4288
4289 static void
4290 add_thread (gpointer key, gpointer value, gpointer user_data)
4291 {
4292         MonoInternalThread *thread = value;
4293         Buffer *buf = user_data;
4294
4295         buffer_add_objid (buf, (MonoObject*)thread);
4296 }
4297
4298 static ErrorCode
4299 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke)
4300 {
4301         guint8 *p = invoke->p;
4302         guint8 *end = invoke->endp;
4303         MonoMethod *m;
4304         int i, err, nargs;
4305         MonoMethodSignature *sig;
4306         guint8 **arg_buf;
4307         void **args;
4308         MonoObject *this, *res, *exc;
4309         MonoDomain *domain;
4310         guint8 *this_buf;
4311 #ifdef MONO_ARCH_HAVE_FIND_JIT_INFO_EXT
4312         MonoLMFExt ext;
4313 #endif
4314
4315         if (invoke->method) {
4316                 /* 
4317                  * Invoke this method directly, currently only Environment.Exit () is supported.
4318                  */
4319                 this = NULL;
4320                 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>"));
4321                 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
4322                 g_assert_not_reached ();
4323         }
4324
4325         m = decode_methodid (p, &p, end, &domain, &err);
4326         if (err)
4327                 return err;
4328         sig = mono_method_signature (m);
4329
4330         if (m->klass->valuetype)
4331                 this_buf = g_alloca (mono_class_instance_size (m->klass));
4332         else
4333                 this_buf = g_alloca (sizeof (MonoObject*));
4334         err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
4335         if (err)
4336                 return err;
4337
4338         if (!m->klass->valuetype)
4339                 this = *(MonoObject**)this_buf;
4340         else
4341                 this = NULL;
4342
4343         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>"));
4344
4345         if (this && this->vtable->domain != domain)
4346                 NOT_IMPLEMENTED;
4347
4348         if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
4349                 if (!strcmp (m->name, ".ctor")) {
4350                         if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
4351                                 return ERR_INVALID_ARGUMENT;
4352                         else
4353                                 this = mono_object_new (domain, m->klass);
4354                 } else {
4355                         return ERR_INVALID_ARGUMENT;
4356                 }
4357         }
4358
4359         if (this && !mono_class_is_assignable_from (m->klass, this->vtable->klass))
4360                 return ERR_INVALID_ARGUMENT;
4361
4362         nargs = decode_int (p, &p, end);
4363         if (nargs != sig->param_count)
4364                 return ERR_INVALID_ARGUMENT;
4365         /* Use alloca to get gc tracking */
4366         arg_buf = g_alloca (nargs * sizeof (gpointer));
4367         memset (arg_buf, 0, nargs * sizeof (gpointer));
4368         args = g_alloca (nargs * sizeof (gpointer));
4369         for (i = 0; i < nargs; ++i) {
4370                 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
4371                         err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
4372                         if (err)
4373                                 break;
4374
4375                         if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
4376                                 NOT_IMPLEMENTED;
4377                 } else {
4378                         arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
4379                         err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
4380                         if (err)
4381                                 break;
4382                         args [i] = arg_buf [i];
4383                 }
4384         }
4385
4386         if (i < nargs)
4387                 return err;
4388
4389         if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
4390                 tls->disable_breakpoints = TRUE;
4391         else
4392                 tls->disable_breakpoints = FALSE;
4393
4394         /* 
4395          * Add an LMF frame to link the stack frames on the invoke method with our caller.
4396          */
4397         /* FIXME: Move this to arch specific code */
4398 #ifdef MONO_ARCH_HAVE_FIND_JIT_INFO_EXT
4399         if (invoke->has_ctx) {
4400                 MonoLMF **lmf_addr;
4401
4402                 lmf_addr = mono_get_lmf_addr ();
4403
4404                 /* Setup our lmf */
4405                 memset (&ext, 0, sizeof (ext));
4406 #ifdef TARGET_AMD64
4407                 ext.lmf.previous_lmf = *(lmf_addr);
4408                 /* Mark that this is a MonoLMFExt */
4409                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
4410                 ext.lmf.rsp = (gssize)&ext;
4411 #elif defined(TARGET_X86)
4412                 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
4413                 /* Mark that this is a MonoLMFExt */
4414                 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
4415                 ext.lmf.ebp = (gssize)&ext;
4416 #elif defined(TARGET_ARM)
4417                 ext.lmf.previous_lmf = *(lmf_addr);
4418                 /* Mark that this is a MonoLMFExt */
4419                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
4420                 ext.lmf.ebp = (gssize)&ext;
4421 #elif defined(TARGET_POWERPC)
4422                 ext.lmf.previous_lmf = *(lmf_addr);
4423                 /* Mark that this is a MonoLMFExt */
4424                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
4425                 ext.lmf.ebp = (gssize)&ext;
4426 #else
4427                 g_assert_not_reached ();
4428 #endif
4429
4430                 ext.debugger_invoke = TRUE;
4431                 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
4432
4433                 mono_set_lmf ((MonoLMF*)&ext);
4434         }
4435 #endif
4436
4437         if (m->klass->valuetype)
4438                 res = mono_runtime_invoke (m, this_buf, args, &exc);
4439         else
4440                 res = mono_runtime_invoke (m, this, args, &exc);
4441         if (exc) {
4442                 buffer_add_byte (buf, 0);
4443                 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
4444         } else {
4445                 buffer_add_byte (buf, 1);
4446                 if (sig->ret->type == MONO_TYPE_VOID) {
4447                         if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
4448                                 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
4449                         }
4450                         else
4451                                 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
4452                 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
4453                         buffer_add_value (buf, sig->ret, &res, domain);
4454                 } else if (mono_class_from_mono_type (sig->ret)->valuetype) {
4455                         g_assert (res);
4456                         buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
4457                 } else {
4458                         NOT_IMPLEMENTED;
4459                 }
4460         }
4461
4462         tls->disable_breakpoints = FALSE;
4463
4464 #ifdef MONO_ARCH_HAVE_FIND_JIT_INFO_EXT
4465         if (invoke->has_ctx)
4466                 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
4467 #endif
4468
4469         // FIXME: byref arguments
4470         // FIXME: varargs
4471         return ERR_NONE;
4472 }
4473
4474 /*
4475  * invoke_method:
4476  *
4477  *   Invoke the method given by tls->invoke in the current thread.
4478  */
4479 static void
4480 invoke_method (void)
4481 {
4482         DebuggerTlsData *tls;
4483         InvokeData *invoke;
4484         int id;
4485         int err;
4486         Buffer buf;
4487         static void (*restore_context) (void *);
4488         MonoContext restore_ctx;
4489
4490         if (!restore_context)
4491                 restore_context = mono_get_restore_context ();
4492
4493         tls = TlsGetValue (debugger_tls_id);
4494         g_assert (tls);
4495
4496         invoke = tls->invoke;
4497         g_assert (invoke);
4498         tls->invoke = NULL;
4499
4500         tls->frames_up_to_date = FALSE;
4501
4502         id = invoke->id;
4503
4504         buffer_init (&buf, 128);
4505
4506         err = do_invoke_method (tls, &buf, invoke);
4507
4508         /* Start suspending before sending the reply */
4509         if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED))
4510                 suspend_vm ();
4511
4512         send_reply_packet (id, err, &buf);
4513         
4514         buffer_free (&buf);
4515
4516         memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
4517
4518         if (invoke->has_ctx)
4519                 save_thread_context (&restore_ctx);
4520
4521         if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
4522                 g_assert (tls->resume_count);
4523                 tls->resume_count -= invoke->suspend_count;
4524         }
4525
4526         DEBUG (1, printf ("[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
4527
4528         g_free (invoke->p);
4529         g_free (invoke);
4530
4531         suspend_current ();
4532 }
4533
4534 static gboolean
4535 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
4536 {
4537         MonoThread *thread = value;
4538         DebuggerTlsData *tls;
4539         gboolean res;
4540
4541         mono_loader_lock ();
4542         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4543         g_assert (tls);
4544         res = tls->really_suspended;
4545         mono_loader_unlock ();
4546
4547         return res;
4548 }
4549
4550 static ErrorCode
4551 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
4552 {
4553         switch (command) {
4554         case CMD_VM_VERSION: {
4555                 char *build_info, *version;
4556
4557                 build_info = mono_get_runtime_build_info ();
4558                 version = g_strdup_printf ("mono %s", build_info);
4559
4560                 buffer_add_string (buf, version); /* vm version */
4561                 buffer_add_int (buf, MAJOR_VERSION);
4562                 buffer_add_int (buf, MINOR_VERSION);
4563                 g_free (build_info);
4564                 g_free (version);
4565                 break;
4566         }
4567         case CMD_VM_ALL_THREADS: {
4568                 // FIXME: Domains
4569                 mono_loader_lock ();
4570                 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
4571                 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
4572                 mono_loader_unlock ();
4573                 break;
4574         }
4575         case CMD_VM_SUSPEND:
4576                 suspend_vm ();
4577                 wait_for_suspend ();
4578                 break;
4579         case CMD_VM_RESUME:
4580                 if (suspend_count == 0)
4581                         return ERR_NOT_SUSPENDED;
4582                 resume_vm ();
4583                 break;
4584         case CMD_VM_DISPOSE:
4585                 /* Clear all event requests */
4586                 mono_loader_lock ();
4587                 while (event_requests->len > 0) {
4588                         EventRequest *req = g_ptr_array_index (event_requests, 0);
4589
4590                         clear_event_request (req->id, req->event_kind);
4591                 }
4592                 mono_loader_unlock ();
4593
4594                 // FIXME: Count resumes
4595                 resume_vm ();
4596                 disconnected = TRUE;
4597                 break;
4598         case CMD_VM_EXIT: {
4599                 MonoInternalThread *thread;
4600                 DebuggerTlsData *tls;
4601                 MonoClass *env_class;
4602                 MonoMethod *exit_method;
4603                 gpointer *args;
4604                 int exit_code;
4605
4606                 exit_code = decode_int (p, &p, end);
4607
4608                 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
4609
4610                 /* Have to send a reply before exiting */
4611                 send_reply_packet (id, 0, buf);
4612
4613                 /* Clear all event requests */
4614                 mono_loader_lock ();
4615                 while (event_requests->len > 0) {
4616                         EventRequest *req = g_ptr_array_index (event_requests, 0);
4617
4618                         clear_event_request (req->id, req->event_kind);
4619                 }
4620                 mono_loader_unlock ();
4621
4622                 /*
4623                  * The JDWP documentation says that the shutdown is not orderly. It doesn't
4624                  * specify whenever a VM_DEATH event is sent. We currently do an orderly
4625                  * shutdown by hijacking a thread to execute Environment.Exit (). This is
4626                  * better than doing the shutdown ourselves, since it avoids various races.
4627                  */
4628
4629                 suspend_vm ();
4630                 wait_for_suspend ();
4631
4632                 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
4633                 g_assert (env_class);
4634                 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
4635                 g_assert (exit_method);
4636
4637                 mono_loader_lock ();
4638                 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
4639                 mono_loader_unlock ();
4640
4641                 if (thread) {
4642                         mono_loader_lock ();
4643                         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4644                         mono_loader_unlock ();
4645
4646                         args = g_new0 (gpointer, 1);
4647                         args [0] = g_malloc (sizeof (int));
4648                         *(int*)(args [0]) = exit_code;
4649
4650                         tls->invoke = g_new0 (InvokeData, 1);
4651                         tls->invoke->method = exit_method;
4652                         tls->invoke->args = args;
4653
4654                         while (suspend_count > 0)
4655                                 resume_vm ();
4656                 } else {
4657                         /* 
4658                          * No thread found, do it ourselves.
4659                          * FIXME: This can race with normal shutdown etc.
4660                          */
4661                         while (suspend_count > 0)
4662                                 resume_vm ();
4663
4664                         mono_runtime_set_shutting_down ();
4665
4666                         mono_threads_set_shutting_down ();
4667
4668                         /* Suspend all managed threads since the runtime is going away */
4669                         DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
4670                         mono_thread_suspend_all_other_threads ();
4671                         DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
4672                         mono_runtime_quit ();
4673 #ifdef HOST_WIN32
4674                         shutdown (conn_fd, SD_BOTH);
4675 #else
4676                         shutdown (conn_fd, SHUT_RDWR);
4677 #endif
4678                         DEBUG(1, fprintf (log_file, "Exiting...\n"));
4679
4680                         exit (exit_code);
4681                 }
4682                 break;
4683         }               
4684         case CMD_VM_INVOKE_METHOD: {
4685                 int objid = decode_objid (p, &p, end);
4686                 MonoThread *thread;
4687                 DebuggerTlsData *tls;
4688                 int err, flags;
4689
4690                 err = get_object (objid, (MonoObject**)&thread);
4691                 if (err)
4692                         return err;
4693
4694                 flags = decode_int (p, &p, end);
4695
4696                 // Wait for suspending if it already started
4697                 if (suspend_count)
4698                         wait_for_suspend ();
4699                 if (!is_suspended ())
4700                         return ERR_NOT_SUSPENDED;
4701
4702                 mono_loader_lock ();
4703                 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
4704                 mono_loader_unlock ();
4705                 g_assert (tls);
4706
4707                 if (!tls->really_suspended)
4708                         /* The thread is still running native code, can't do invokes */
4709                         return ERR_NOT_SUSPENDED;
4710
4711                 /* 
4712                  * Store the invoke data into tls, the thread will execute it after it is
4713                  * resumed.
4714                  */
4715                 if (tls->invoke)
4716                         NOT_IMPLEMENTED;
4717                 tls->invoke = g_new0 (InvokeData, 1);
4718                 tls->invoke->id = id;
4719                 tls->invoke->flags = flags;
4720                 tls->invoke->p = g_malloc (end - p);
4721                 memcpy (tls->invoke->p, p, end - p);
4722                 tls->invoke->endp = tls->invoke->p + (end - p);
4723                 tls->invoke->suspend_count = suspend_count;
4724
4725                 if (flags & INVOKE_FLAG_SINGLE_THREADED)
4726                         resume_thread (THREAD_TO_INTERNAL (thread));
4727                 else
4728                         resume_vm ();
4729                 break;
4730         }
4731         default:
4732                 return ERR_NOT_IMPLEMENTED;
4733         }
4734
4735         return ERR_NONE;
4736 }
4737
4738 static ErrorCode
4739 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4740 {
4741         int err;
4742
4743         switch (command) {
4744         case CMD_EVENT_REQUEST_SET: {
4745                 EventRequest *req;
4746                 int i, event_kind, suspend_policy, nmodifiers, mod;
4747                 MonoMethod *method;
4748                 long location = 0;
4749                 MonoThread *step_thread;
4750                 int size = 0, depth = 0, step_thread_id = 0;
4751                 MonoDomain *domain;
4752
4753                 event_kind = decode_byte (p, &p, end);
4754                 suspend_policy = decode_byte (p, &p, end);
4755                 nmodifiers = decode_byte (p, &p, end);
4756
4757                 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
4758                 req->id = InterlockedIncrement (&event_request_id);
4759                 req->event_kind = event_kind;
4760                 req->suspend_policy = suspend_policy;
4761                 req->nmodifiers = nmodifiers;
4762
4763                 method = NULL;
4764                 for (i = 0; i < nmodifiers; ++i) {
4765                         mod = decode_byte (p, &p, end);
4766
4767                         req->modifiers [i].kind = mod;
4768                         if (mod == MOD_KIND_COUNT) {
4769                                 req->modifiers [i].data.count = decode_int (p, &p, end);
4770                         } else if (mod == MOD_KIND_LOCATION_ONLY) {
4771                                 method = decode_methodid (p, &p, end, &domain, &err);
4772                                 if (err)
4773                                         return err;
4774                                 location = decode_long (p, &p, end);
4775                         } else if (mod == MOD_KIND_STEP) {
4776                                 step_thread_id = decode_id (p, &p, end);
4777                                 size = decode_int (p, &p, end);
4778                                 depth = decode_int (p, &p, end);
4779                         } else if (mod == MOD_KIND_THREAD_ONLY) {
4780                                 int id = decode_id (p, &p, end);
4781
4782                                 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
4783                                 if (err) {
4784                                         g_free (req);
4785                                         return err;
4786                                 }
4787                         } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
4788                                 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
4789
4790                                 if (err)
4791                                         return err;
4792                                 if (exc_class) {
4793                                         req->modifiers [i].data.exc_class = exc_class;
4794
4795                                         if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
4796                                                 g_free (req);
4797                                                 return ERR_INVALID_ARGUMENT;
4798                                         }
4799                                 }
4800                         } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
4801                                 int n = decode_int (p, &p, end);
4802                                 int j;
4803
4804                                 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
4805                                 for (j = 0; j < n; ++j) {
4806                                         req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
4807                                         if (err) {
4808                                                 g_free (req->modifiers [i].data.assemblies);
4809                                                 return err;
4810                                         }
4811                                 }
4812                         } else {
4813                                 g_free (req);
4814                                 return ERR_NOT_IMPLEMENTED;
4815                         }
4816                 }
4817
4818                 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4819                         g_assert (method);
4820
4821                         req->info = set_breakpoint (method, location, req);
4822                 } else if (req->event_kind == EVENT_KIND_STEP) {
4823                         g_assert (step_thread_id);
4824
4825                         err = get_object (step_thread_id, (MonoObject**)&step_thread);
4826                         if (err) {
4827                                 g_free (req);
4828                                 return err;
4829                         }
4830
4831                         err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
4832                         if (err) {
4833                                 g_free (req);
4834                                 return err;
4835                         }
4836                 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
4837                         req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req);
4838                 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
4839                         req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req);
4840                 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
4841                 } else {
4842                         if (req->nmodifiers) {
4843                                 g_free (req);
4844                                 return ERR_NOT_IMPLEMENTED;
4845                         }
4846                 }
4847
4848                 mono_loader_lock ();
4849                 g_ptr_array_add (event_requests, req);
4850                 mono_loader_unlock ();
4851
4852                 buffer_add_int (buf, req->id);
4853                 break;
4854         }
4855         case CMD_EVENT_REQUEST_CLEAR: {
4856                 int etype = decode_byte (p, &p, end);
4857                 int req_id = decode_int (p, &p, end);
4858
4859                 // FIXME: Make a faster mapping from req_id to request
4860                 mono_loader_lock ();
4861                 clear_event_request (req_id, etype);
4862                 mono_loader_unlock ();
4863                 break;
4864         }
4865         case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
4866                 int i;
4867
4868                 mono_loader_lock ();
4869                 i = 0;
4870                 while (i < event_requests->len) {
4871                         EventRequest *req = g_ptr_array_index (event_requests, i);
4872
4873                         if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4874                                 clear_breakpoint (req->info);
4875
4876                                 g_ptr_array_remove_index_fast (event_requests, i);
4877                                 g_free (req);
4878                         } else {
4879                                 i ++;
4880                         }
4881                 }
4882                 mono_loader_unlock ();
4883                 break;
4884         }
4885         default:
4886                 return ERR_NOT_IMPLEMENTED;
4887         }
4888
4889         return ERR_NONE;
4890 }
4891
4892 static ErrorCode
4893 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4894 {
4895         int err;
4896         MonoDomain *domain;
4897
4898         switch (command) {
4899         case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
4900                 buffer_add_domainid (buf, mono_get_root_domain ());
4901                 break;
4902         }
4903         case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
4904                 domain = decode_domainid (p, &p, end, NULL, &err);
4905                 if (err)
4906                         return err;
4907                 buffer_add_string (buf, domain->friendly_name);
4908                 break;
4909         }
4910         case CMD_APPDOMAIN_GET_ASSEMBLIES: {
4911                 GSList *tmp;
4912                 MonoAssembly *ass;
4913                 int count;
4914
4915                 domain = decode_domainid (p, &p, end, NULL, &err);
4916                 if (err)
4917                         return err;
4918                 mono_loader_lock ();
4919                 count = 0;
4920                 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4921                         count ++;
4922                 }
4923                 buffer_add_int (buf, count);
4924                 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4925                         ass = tmp->data;
4926                         buffer_add_assemblyid (buf, domain, ass);
4927                 }
4928                 mono_loader_unlock ();
4929                 break;
4930         }
4931         case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
4932                 domain = decode_domainid (p, &p, end, NULL, &err);
4933                 if (err)
4934                         return err;
4935
4936                 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
4937                 break;
4938         }
4939         case CMD_APPDOMAIN_GET_CORLIB: {
4940                 domain = decode_domainid (p, &p, end, NULL, &err);
4941                 if (err)
4942                         return err;
4943
4944                 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
4945                 break;
4946         }
4947         case CMD_APPDOMAIN_CREATE_STRING: {
4948                 char *s;
4949                 MonoString *o;
4950
4951                 domain = decode_domainid (p, &p, end, NULL, &err);
4952                 if (err)
4953                         return err;
4954                 s = decode_string (p, &p, end);
4955
4956                 o = mono_string_new (domain, s);
4957                 buffer_add_objid (buf, (MonoObject*)o);
4958                 break;
4959         }
4960         default:
4961                 return ERR_NOT_IMPLEMENTED;
4962         }
4963
4964         return ERR_NONE;
4965 }
4966
4967 static ErrorCode
4968 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4969 {
4970         int err;
4971         MonoAssembly *ass;
4972         MonoDomain *domain;
4973
4974         ass = decode_assemblyid (p, &p, end, &domain, &err);
4975         if (err)
4976                 return err;
4977
4978         switch (command) {
4979         case CMD_ASSEMBLY_GET_LOCATION: {
4980                 buffer_add_string (buf, mono_image_get_filename (ass->image));
4981                 break;                  
4982         }
4983         case CMD_ASSEMBLY_GET_ENTRY_POINT: {
4984                 guint32 token;
4985                 MonoMethod *m;
4986
4987                 if (ass->image->dynamic) {
4988                         buffer_add_id (buf, 0);
4989                 } else {
4990                         token = mono_image_get_entry_point (ass->image);
4991                         if (token == 0) {
4992                                 buffer_add_id (buf, 0);
4993                         } else {
4994                                 m = mono_get_method (ass->image, token, NULL);
4995                                 buffer_add_methodid (buf, domain, m);
4996                         }
4997                 }
4998                 break;                  
4999         }
5000         case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
5001                 buffer_add_moduleid (buf, domain, ass->image);
5002                 break;
5003         }
5004         case CMD_ASSEMBLY_GET_OBJECT: {
5005                 MonoObject *o = (MonoObject*)mono_assembly_get_object (mono_domain_get (), ass);
5006                 buffer_add_objid (buf, o);
5007                 break;
5008         }
5009         case CMD_ASSEMBLY_GET_TYPE: {
5010                 char *s = decode_string (p, &p, end);
5011                 gboolean ignorecase = decode_byte (p, &p, end);
5012                 MonoTypeNameParse info;
5013                 MonoType *t;
5014                 gboolean type_resolve;
5015
5016                 if (!mono_reflection_parse_type (s, &info)) {
5017                         t = NULL;
5018                 } else {
5019                         if (info.assembly.name)
5020                                 NOT_IMPLEMENTED;
5021                         t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
5022                 }
5023                 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
5024                 mono_reflection_free_type_info (&info);
5025                 g_free (s);
5026
5027                 break;
5028         }
5029         case CMD_ASSEMBLY_GET_NAME: {
5030                 gchar *name;
5031                 MonoAssembly *mass = ass;
5032
5033                 name = g_strdup_printf (
5034                   "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
5035                   mass->aname.name,
5036                   mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
5037                   mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
5038                   mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
5039                   (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
5040
5041                 buffer_add_string (buf, name);
5042                 g_free (name);
5043                 break;
5044         }
5045         default:
5046                 return ERR_NOT_IMPLEMENTED;
5047         }
5048
5049         return ERR_NONE;
5050 }
5051
5052 static ErrorCode
5053 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5054 {
5055         int err;
5056         MonoDomain *domain;
5057
5058         switch (command) {
5059         case CMD_MODULE_GET_INFO: {
5060                 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
5061                 char *basename;
5062
5063                 basename = g_path_get_basename (image->name);
5064                 buffer_add_string (buf, basename); // name
5065                 buffer_add_string (buf, image->module_name); // scopename
5066                 buffer_add_string (buf, image->name); // fqname
5067                 buffer_add_string (buf, mono_image_get_guid (image)); // guid
5068                 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
5069                 g_free (basename);
5070                 break;                  
5071         }
5072         default:
5073                 return ERR_NOT_IMPLEMENTED;
5074         }
5075
5076         return ERR_NONE;
5077 }
5078
5079 static void
5080 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
5081 {
5082         if (val && val->vtable->klass == mono_defaults.monotype_class) {
5083                 /* Special case these so the client doesn't have to handle Type objects */
5084                 
5085                 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
5086                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
5087         } else if (MONO_TYPE_IS_REFERENCE (t))
5088                 buffer_add_value (buf, t, &val, domain);
5089         else
5090                 buffer_add_value (buf, t, mono_object_unbox (val), domain);
5091 }
5092
5093 static void
5094 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
5095 {
5096         int i, j;
5097         int nattrs = 0;
5098
5099         if (!cinfo) {
5100                 buffer_add_int (buf, 0);
5101                 return;
5102         }
5103
5104         for (i = 0; i < cinfo->num_attrs; ++i) {
5105                 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
5106                         nattrs ++;
5107         }
5108         buffer_add_int (buf, nattrs);
5109
5110         for (i = 0; i < cinfo->num_attrs; ++i) {
5111                 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
5112                 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
5113                         MonoArray *typed_args, *named_args;
5114                         MonoType *t;
5115                         CattrNamedArg *arginfo;
5116
5117                         mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
5118
5119                         buffer_add_methodid (buf, domain, attr->ctor);
5120
5121                         /* Ctor args */
5122                         if (typed_args) {
5123                                 buffer_add_int (buf, mono_array_length (typed_args));
5124                                 for (j = 0; j < mono_array_length (typed_args); ++j) {
5125                                         MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
5126
5127                                         t = mono_method_signature (attr->ctor)->params [j];
5128
5129                                         buffer_add_cattr_arg (buf, t, domain, val);
5130                                 }
5131                         } else {
5132                                 buffer_add_int (buf, 0);
5133                         }
5134
5135                         /* Named args */
5136                         if (named_args) {
5137                                 buffer_add_int (buf, mono_array_length (named_args));
5138
5139                                 for (j = 0; j < mono_array_length (named_args); ++j) {
5140                                         MonoObject *val = mono_array_get (named_args, MonoObject*, j);
5141
5142                                         if (arginfo [j].prop) {
5143                                                 buffer_add_byte (buf, 0x54);
5144                                                 buffer_add_propertyid (buf, domain, arginfo [j].prop);
5145                                         } else if (arginfo [j].field) {
5146                                                 buffer_add_byte (buf, 0x53);
5147                                         } else {
5148                                                 g_assert_not_reached ();
5149                                         }
5150
5151                                         buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
5152                                 }
5153                         } else {
5154                                 buffer_add_int (buf, 0);
5155                         }
5156                 }
5157         }
5158 }
5159
5160 static ErrorCode
5161 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5162 {
5163         MonoClass *klass;
5164         MonoDomain *domain;
5165         MonoClass *nested;
5166         MonoType *type;
5167         gpointer iter;
5168         guint8 b;
5169         int err, nnested;
5170         char *name;
5171
5172         klass = decode_typeid (p, &p, end, &domain, &err);
5173         if (err)
5174                 return err;
5175
5176         switch (command) {
5177         case CMD_TYPE_GET_INFO: {
5178                 buffer_add_string (buf, klass->name_space);
5179                 buffer_add_string (buf, klass->name);
5180                 // FIXME: byref
5181                 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
5182                 buffer_add_string (buf, name);
5183                 g_free (name);
5184                 buffer_add_assemblyid (buf, domain, klass->image->assembly);
5185                 buffer_add_moduleid (buf, domain, klass->image);
5186                 buffer_add_typeid (buf, domain, klass->parent);
5187                 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
5188                         buffer_add_typeid (buf, domain, klass->element_class);
5189                 else
5190                         buffer_add_id (buf, 0);
5191                 buffer_add_int (buf, klass->type_token);
5192                 buffer_add_byte (buf, klass->rank);
5193                 buffer_add_int (buf, klass->flags);
5194                 b = 0;
5195                 type = &klass->byval_arg;
5196                 // FIXME: Can't decide whenever a class represents a byref type
5197                 if (FALSE)
5198                         b |= (1 << 0);
5199                 if (type->type == MONO_TYPE_PTR)
5200                         b |= (1 << 1);
5201                 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
5202                         b |= (1 << 2);
5203                 if (type->type == MONO_TYPE_VALUETYPE)
5204                         b |= (1 << 3);
5205                 buffer_add_byte (buf, b);
5206                 nnested = 0;
5207                 iter = NULL;
5208                 while ((nested = mono_class_get_nested_types (klass, &iter)))
5209                         nnested ++;
5210                 buffer_add_int (buf, nnested);
5211                 iter = NULL;
5212                 while ((nested = mono_class_get_nested_types (klass, &iter)))
5213                         buffer_add_typeid (buf, domain, nested);
5214                 break;
5215         }
5216         case CMD_TYPE_GET_METHODS: {
5217                 int nmethods;
5218                 int i = 0;
5219                 gpointer iter = NULL;
5220                 MonoMethod *m;
5221
5222                 nmethods = mono_class_num_methods (klass);
5223
5224                 buffer_add_int (buf, nmethods);
5225
5226                 while ((m = mono_class_get_methods (klass, &iter))) {
5227                         buffer_add_methodid (buf, domain, m);
5228                         i ++;
5229                 }
5230                 g_assert (i == nmethods);
5231                 break;
5232         }
5233         case CMD_TYPE_GET_FIELDS: {
5234                 int nfields;
5235                 int i = 0;
5236                 gpointer iter = NULL;
5237                 MonoClassField *f;
5238
5239                 nfields = mono_class_num_fields (klass);
5240
5241                 buffer_add_int (buf, nfields);
5242
5243                 while ((f = mono_class_get_fields (klass, &iter))) {
5244                         buffer_add_fieldid (buf, domain, f);
5245                         buffer_add_string (buf, f->name);
5246                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
5247                         buffer_add_int (buf, f->type->attrs);
5248                         i ++;
5249                 }
5250                 g_assert (i == nfields);
5251                 break;
5252         }
5253         case CMD_TYPE_GET_PROPERTIES: {
5254                 int nprops;
5255                 int i = 0;
5256                 gpointer iter = NULL;
5257                 MonoProperty *p;
5258
5259                 nprops = mono_class_num_properties (klass);
5260
5261                 buffer_add_int (buf, nprops);
5262
5263                 while ((p = mono_class_get_properties (klass, &iter))) {
5264                         buffer_add_propertyid (buf, domain, p);
5265                         buffer_add_string (buf, p->name);
5266                         buffer_add_methodid (buf, domain, p->get);
5267                         buffer_add_methodid (buf, domain, p->set);
5268                         buffer_add_int (buf, p->attrs);
5269                         i ++;
5270                 }
5271                 g_assert (i == nprops);
5272                 break;
5273         }
5274         case CMD_TYPE_GET_CATTRS: {
5275                 MonoClass *attr_klass = decode_typeid (p, &p, end, NULL, &err);
5276                 MonoCustomAttrInfo *cinfo;
5277
5278                 cinfo = mono_custom_attrs_from_class (klass);
5279
5280                 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
5281                 break;
5282         }
5283         case CMD_TYPE_GET_FIELD_CATTRS: {
5284                 MonoClass *attr_klass;
5285                 MonoCustomAttrInfo *cinfo;
5286                 MonoClassField *field;
5287
5288                 field = decode_fieldid (p, &p, end, NULL, &err);
5289                 if (err)
5290                         return err;
5291                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
5292                 if (err)
5293                         return err;
5294
5295                 cinfo = mono_custom_attrs_from_field (klass, field);
5296
5297                 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
5298                 break;
5299         }
5300         case CMD_TYPE_GET_PROPERTY_CATTRS: {
5301                 MonoClass *attr_klass;
5302                 MonoCustomAttrInfo *cinfo;
5303                 MonoProperty *prop;
5304
5305                 prop = decode_propertyid (p, &p, end, NULL, &err);
5306                 if (err)
5307                         return err;
5308                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
5309                 if (err)
5310                         return err;
5311
5312                 cinfo = mono_custom_attrs_from_property (klass, prop);
5313
5314                 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
5315                 break;
5316         }
5317         case CMD_TYPE_GET_VALUES: {
5318                 guint8 *val;
5319                 MonoClassField *f;
5320                 MonoVTable *vtable;
5321                 MonoClass *k;
5322                 int len, i;
5323                 gboolean found;
5324
5325                 len = decode_int (p, &p, end);
5326                 for (i = 0; i < len; ++i) {
5327                         f = decode_fieldid (p, &p, end, NULL, &err);
5328                         if (err)
5329                                 return err;
5330
5331                         if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
5332                                 return ERR_INVALID_FIELDID;
5333                         if (mono_class_field_is_special_static (f))
5334                                 return ERR_INVALID_FIELDID;
5335
5336                         /* Check that the field belongs to the object */
5337                         found = FALSE;
5338                         for (k = klass; k; k = k->parent) {
5339                                 if (k == f->parent) {
5340                                         found = TRUE;
5341                                         break;
5342                                 }
5343                         }
5344                         if (!found)
5345                                 return ERR_INVALID_FIELDID;
5346
5347                         vtable = mono_class_vtable (domain, f->parent);
5348                         val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
5349                         mono_field_static_get_value (vtable, f, val);
5350                         buffer_add_value (buf, f->type, val, domain);
5351                         g_free (val);
5352                 }
5353                 break;
5354         }
5355         case CMD_TYPE_SET_VALUES: {
5356                 guint8 *val;
5357                 MonoClassField *f;
5358                 MonoVTable *vtable;
5359                 MonoClass *k;
5360                 int len, i;
5361                 gboolean found;
5362
5363                 len = decode_int (p, &p, end);
5364                 for (i = 0; i < len; ++i) {
5365                         f = decode_fieldid (p, &p, end, NULL, &err);
5366                         if (err)
5367                                 return err;
5368
5369                         if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
5370                                 return ERR_INVALID_FIELDID;
5371                         if (mono_class_field_is_special_static (f))
5372                                 return ERR_INVALID_FIELDID;
5373
5374                         /* Check that the field belongs to the object */
5375                         found = FALSE;
5376                         for (k = klass; k; k = k->parent) {
5377                                 if (k == f->parent) {
5378                                         found = TRUE;
5379                                         break;
5380                                 }
5381                         }
5382                         if (!found)
5383                                 return ERR_INVALID_FIELDID;
5384
5385                         // FIXME: Check for literal/const
5386
5387                         vtable = mono_class_vtable (domain, f->parent);
5388                         val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
5389                         err = decode_value (f->type, domain, val, p, &p, end);
5390                         if (err) {
5391                                 g_free (val);
5392                                 return err;
5393                         }
5394                         mono_field_static_set_value (vtable, f, val);
5395                         g_free (val);
5396                 }
5397                 break;
5398         }
5399         case CMD_TYPE_GET_OBJECT: {
5400                 MonoObject *o = (MonoObject*)mono_type_get_object (mono_domain_get (), &klass->byval_arg);
5401                 buffer_add_objid (buf, o);
5402                 break;
5403         }
5404         case CMD_TYPE_GET_SOURCE_FILES: {
5405                 gpointer iter = NULL;
5406                 MonoMethod *method;
5407                 char *source_file, *base;
5408                 GPtrArray *files;
5409                 int i;
5410
5411                 files = g_ptr_array_new ();
5412
5413                 while ((method = mono_class_get_methods (klass, &iter))) {
5414                         MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
5415
5416                         if (minfo) {
5417                                 mono_debug_symfile_get_line_numbers (minfo, &source_file, NULL, NULL, NULL);
5418
5419                                 for (i = 0; i < files->len; ++i)
5420                                         if (!strcmp (g_ptr_array_index (files, i), source_file))
5421                                                 break;
5422                                 if (i == files->len)
5423                                         g_ptr_array_add (files, g_strdup (source_file));
5424                                 g_free (source_file);
5425                         }
5426                 }
5427
5428                 buffer_add_int (buf, files->len);
5429                 for (i = 0; i < files->len; ++i) {
5430                         source_file = g_ptr_array_index (files, i);
5431                         base = g_path_get_basename (source_file);
5432                         buffer_add_string (buf, base);
5433                         g_free (base);
5434                         g_free (source_file);
5435                 }
5436                 g_ptr_array_free (files, TRUE);
5437                 break;
5438         }
5439         case CMD_TYPE_IS_ASSIGNABLE_FROM: {
5440                 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
5441
5442                 if (err)
5443                         return err;
5444                 if (mono_class_is_assignable_from (klass, oklass))
5445                         buffer_add_byte (buf, 1);
5446                 else
5447                         buffer_add_byte (buf, 0);
5448                 break;
5449         }
5450         default:
5451                 return ERR_NOT_IMPLEMENTED;
5452         }
5453
5454         return ERR_NONE;
5455 }
5456
5457 static ErrorCode
5458 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5459 {
5460         int err;
5461         MonoDomain *domain;
5462         MonoMethod *method;
5463         MonoMethodHeader *header;
5464
5465         method = decode_methodid (p, &p, end, &domain, &err);
5466         if (err)
5467                 return err;
5468
5469         switch (command) {
5470         case CMD_METHOD_GET_NAME: {
5471                 buffer_add_string (buf, method->name);
5472                 break;                  
5473         }
5474         case CMD_METHOD_GET_DECLARING_TYPE: {
5475                 buffer_add_typeid (buf, domain, method->klass);
5476                 break;
5477         }
5478         case CMD_METHOD_GET_DEBUG_INFO: {
5479                 MonoDebugMethodInfo *minfo;
5480                 char *source_file;
5481                 int i, n_il_offsets;
5482                 int *il_offsets;
5483                 int *line_numbers;
5484
5485                 header = mono_method_get_header (method);
5486                 if (!header) {
5487                         buffer_add_int (buf, 0);
5488                         buffer_add_string (buf, "");
5489                         buffer_add_int (buf, 0);
5490                         break;
5491                 }
5492
5493                 minfo = mono_debug_lookup_method (method);
5494                 if (!minfo) {
5495                         buffer_add_int (buf, header->code_size);
5496                         buffer_add_string (buf, "");
5497                         buffer_add_int (buf, 0);
5498                         break;
5499                 }
5500
5501                 mono_debug_symfile_get_line_numbers (minfo, &source_file, &n_il_offsets, &il_offsets, &line_numbers);
5502                 buffer_add_int (buf, header->code_size);
5503                 buffer_add_string (buf, source_file);
5504                 buffer_add_int (buf, n_il_offsets);
5505                 //printf ("Line number table for method %s:\n", mono_method_full_name (method,  TRUE));
5506                 for (i = 0; i < n_il_offsets; ++i) {
5507                         //printf ("IL%d -> %d\n", il_offsets [i], line_numbers [i]);
5508                         buffer_add_int (buf, il_offsets [i]);
5509                         buffer_add_int (buf, line_numbers [i]);
5510                 }
5511                 g_free (source_file);
5512                 g_free (il_offsets);
5513                 g_free (line_numbers);
5514                 break;
5515         }
5516         case CMD_METHOD_GET_PARAM_INFO: {
5517                 MonoMethodSignature *sig = mono_method_signature (method);
5518                 guint32 i;
5519                 char **names;
5520
5521                 /* FIXME: mono_class_from_mono_type () and byrefs */
5522
5523                 /* FIXME: Use a smaller encoding */
5524                 buffer_add_int (buf, sig->call_convention);
5525                 buffer_add_int (buf, sig->param_count);
5526                 buffer_add_int (buf, sig->generic_param_count);
5527                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
5528                 for (i = 0; i < sig->param_count; ++i) {
5529                         /* FIXME: vararg */
5530                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
5531                 }
5532
5533                 /* Emit parameter names */
5534                 names = g_new (char *, sig->param_count);
5535                 mono_method_get_param_names (method, (const char **) names);
5536                 for (i = 0; i < sig->param_count; ++i)
5537                         buffer_add_string (buf, names [i]);
5538                 g_free (names);
5539
5540                 break;
5541         }
5542         case CMD_METHOD_GET_LOCALS_INFO: {
5543                 int i, j, num_locals;
5544                 char **local_names;
5545                 int *local_indexes;
5546
5547                 header = mono_method_get_header (method);
5548                 g_assert (header);
5549
5550                 buffer_add_int (buf, header->num_locals);
5551
5552                 /* Types */
5553                 for (i = 0; i < header->num_locals; ++i)
5554                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
5555
5556                 /* Names */
5557                 num_locals = mono_debug_lookup_locals (method, &local_names, &local_indexes);
5558                 for (i = 0; i < header->num_locals; ++i) {
5559                         for (j = 0; j < num_locals; ++j)
5560                                 if (local_indexes [j] == i)
5561                                         break;
5562                         if (j < num_locals)
5563                                 buffer_add_string (buf, local_names [j]);
5564                         else
5565                                 buffer_add_string (buf, "");
5566                 }
5567                 g_free (local_names);
5568                 g_free (local_indexes);
5569
5570                 /* Live ranges */
5571                 /* FIXME: This works because we set debug_options.mdb_optimizations */
5572                 for (i = 0; i < header->num_locals; ++i) {
5573                         buffer_add_int (buf, 0);
5574                         buffer_add_int (buf, header->code_size);
5575                 }
5576
5577                 break;
5578         }
5579         case CMD_METHOD_GET_INFO:
5580                 buffer_add_int (buf, method->flags);
5581                 buffer_add_int (buf, method->iflags);
5582                 buffer_add_int (buf, method->token);
5583                 break;
5584         case CMD_METHOD_GET_BODY: {
5585                 int i;
5586
5587                 header = mono_method_get_header (method);
5588                 if (!header) {
5589                         buffer_add_int (buf, 0);
5590                 } else {
5591                         buffer_add_int (buf, header->code_size);
5592                         for (i = 0; i < header->code_size; ++i)
5593                                 buffer_add_byte (buf, header->code [i]);
5594                 }
5595                 break;
5596         }
5597         case CMD_METHOD_RESOLVE_TOKEN: {
5598                 guint32 token = decode_int (p, &p, end);
5599
5600                 // FIXME: Generics
5601                 switch (mono_metadata_token_code (token)) {
5602                 case MONO_TOKEN_STRING: {
5603                         MonoString *s;
5604                         char *s2;
5605
5606                         s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
5607                         g_assert (s);
5608
5609                         s2 = mono_string_to_utf8 (s);
5610
5611                         buffer_add_byte (buf, TOKEN_TYPE_STRING);
5612                         buffer_add_string (buf, s2);
5613                         g_free (s2);
5614                         break;
5615                 }
5616                 default: {
5617                         gpointer val;
5618                         MonoClass *handle_class;
5619
5620                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
5621                                 val = mono_method_get_wrapper_data (method, token);
5622                                 handle_class = mono_method_get_wrapper_data (method, token + 1);
5623
5624                                 if (handle_class == NULL) {
5625                                         // Can't figure out the token type
5626                                         buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
5627                                         break;
5628                                 }
5629                         } else {
5630                                 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
5631                                 g_assert (val);
5632                         }
5633
5634                         if (handle_class == mono_defaults.typehandle_class) {
5635                                 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
5636                                 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
5637                         } else if (handle_class == mono_defaults.fieldhandle_class) {
5638                                 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
5639                                 buffer_add_fieldid (buf, domain, val);
5640                         } else if (handle_class == mono_defaults.methodhandle_class) {
5641                                 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
5642                                 buffer_add_methodid (buf, domain, val);
5643                         } else if (handle_class == mono_defaults.string_class) {
5644                                 char *s;
5645
5646                                 s = mono_string_to_utf8 (val);
5647                                 buffer_add_byte (buf, TOKEN_TYPE_STRING);
5648                                 buffer_add_string (buf, s);
5649                                 g_free (s);
5650                         } else {
5651                                 g_assert_not_reached ();
5652                         }
5653                         break;
5654                 }
5655                 }
5656                 break;
5657         }
5658         default:
5659                 return ERR_NOT_IMPLEMENTED;
5660         }
5661
5662         return ERR_NONE;
5663 }
5664
5665 static ErrorCode
5666 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5667 {
5668         int objid = decode_objid (p, &p, end);
5669         int err;
5670         MonoThread *thread_obj;
5671         MonoInternalThread *thread;
5672
5673         err = get_object (objid, (MonoObject**)&thread_obj);
5674         if (err)
5675                 return err;
5676
5677         thread = THREAD_TO_INTERNAL (thread_obj);
5678            
5679         switch (command) {
5680         case CMD_THREAD_GET_NAME: {
5681                 guint32 name_len;
5682                 gunichar2 *s = mono_thread_get_name (thread, &name_len);
5683
5684                 if (!s) {
5685                         buffer_add_int (buf, 0);
5686                 } else {
5687                         char *name;
5688                         glong len;
5689
5690                         name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
5691                         g_assert (name);
5692                         buffer_add_int (buf, len);
5693                         buffer_add_data (buf, (guint8*)name, len);
5694                         g_free (s);
5695                 }
5696                 break;
5697         }
5698         case CMD_THREAD_GET_FRAME_INFO: {
5699                 DebuggerTlsData *tls;
5700                 int i, start_frame, length;
5701
5702                 // Wait for suspending if it already started
5703                 if (suspend_count)
5704                         wait_for_suspend ();
5705                 if (!is_suspended ())
5706                         return ERR_NOT_SUSPENDED;
5707
5708                 start_frame = decode_int (p, &p, end);
5709                 length = decode_int (p, &p, end);
5710
5711                 if (start_frame != 0 || length != -1)
5712                         return ERR_NOT_IMPLEMENTED;
5713
5714                 mono_loader_lock ();
5715                 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5716                 mono_loader_unlock ();
5717                 g_assert (tls);
5718
5719                 compute_frame_info (thread, tls);
5720
5721                 buffer_add_int (buf, tls->frame_count);
5722                 for (i = 0; i < tls->frame_count; ++i) {
5723                         buffer_add_int (buf, tls->frames [i]->id);
5724                         buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->method);
5725                         buffer_add_int (buf, tls->frames [i]->il_offset);
5726                         /*
5727                          * Instead of passing the frame type directly to the client, we associate
5728                          * it with the previous frame using a set of flags. This avoids lots of
5729                          * conditional code in the client, since a frame whose type isn't 
5730                          * FRAME_TYPE_MANAGED has no method, location, etc.
5731                          */
5732                         buffer_add_byte (buf, tls->frames [i]->flags);
5733                 }
5734
5735                 break;
5736         }
5737         case CMD_THREAD_GET_STATE:
5738                 buffer_add_int (buf, thread->state);
5739                 break;
5740         case CMD_THREAD_GET_INFO:
5741                 buffer_add_byte (buf, thread->threadpool_thread);
5742                 break;
5743         default:
5744                 return ERR_NOT_IMPLEMENTED;
5745         }
5746
5747         return ERR_NONE;
5748 }
5749
5750 static ErrorCode
5751 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5752 {
5753         int objid;
5754         int err;
5755         MonoThread *thread_obj;
5756         MonoInternalThread *thread;
5757         int pos, i, len;
5758         DebuggerTlsData *tls;
5759         StackFrame *frame;
5760         MonoDebugMethodJitInfo *jit;
5761         MonoDebugVarInfo *var;
5762         MonoMethodSignature *sig;
5763         gssize id;
5764         MonoMethodHeader *header;
5765
5766         objid = decode_objid (p, &p, end);
5767         err = get_object (objid, (MonoObject**)&thread_obj);
5768         if (err)
5769                 return err;
5770
5771         thread = THREAD_TO_INTERNAL (thread_obj);
5772
5773         id = decode_id (p, &p, end);
5774
5775         mono_loader_lock ();
5776         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5777         mono_loader_unlock ();
5778         g_assert (tls);
5779
5780         for (i = 0; i < tls->frame_count; ++i) {
5781                 if (tls->frames [i]->id == id)
5782                         break;
5783         }
5784         if (i == tls->frame_count)
5785                 return ERR_INVALID_FRAMEID;
5786
5787         frame = tls->frames [i];
5788
5789         if (!frame->has_ctx)
5790                 // FIXME:
5791                 return ERR_INVALID_FRAMEID;
5792
5793         if (!frame->jit) {
5794                 frame->jit = mono_debug_find_method (frame->method, frame->domain);
5795                 g_assert (frame->jit);
5796         }
5797         jit = frame->jit;
5798
5799         sig = mono_method_signature (frame->method);
5800
5801         switch (command) {
5802         case CMD_STACK_FRAME_GET_VALUES: {
5803                 len = decode_int (p, &p, end);
5804                 header = mono_method_get_header (frame->method);
5805
5806                 for (i = 0; i < len; ++i) {
5807                         pos = decode_int (p, &p, end);
5808
5809                         if (pos < 0) {
5810                                 pos = - pos - 1;
5811
5812                                 g_assert (pos >= 0 && pos < jit->num_params);
5813
5814                                 var = &jit->params [pos];
5815
5816                                 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
5817                         } else {
5818                                 g_assert (pos >= 0 && pos < jit->num_locals);
5819
5820                                 var = &jit->locals [pos];
5821                                 
5822                                 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
5823                         }
5824                 }
5825                 break;
5826         }
5827         case CMD_STACK_FRAME_GET_THIS: {
5828                 if (frame->method->klass->valuetype) {
5829                         if (!sig->hasthis) {
5830                                 MonoObject *p = NULL;
5831                                 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
5832                         } else {
5833                                 add_var (buf, &frame->method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
5834                         }
5835                 } else {
5836                         if (!sig->hasthis) {
5837                                 MonoObject *p = NULL;
5838                                 buffer_add_value (buf, &frame->method->klass->byval_arg, &p, frame->domain);
5839                         } else {
5840                                 add_var (buf, &frame->method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
5841                         }
5842                 }
5843                 break;
5844         }
5845         case CMD_STACK_FRAME_SET_VALUES: {
5846                 guint8 *val_buf;
5847                 MonoType *t;
5848                 MonoDebugVarInfo *var;
5849
5850                 len = decode_int (p, &p, end);
5851                 header = mono_method_get_header (frame->method);
5852
5853                 for (i = 0; i < len; ++i) {
5854                         pos = decode_int (p, &p, end);
5855
5856                         if (pos < 0) {
5857                                 pos = - pos - 1;
5858
5859                                 g_assert (pos >= 0 && pos < jit->num_params);
5860
5861                                 t = sig->params [pos];
5862                                 var = &jit->params [pos];
5863                         } else {
5864                                 g_assert (pos >= 0 && pos < jit->num_locals);
5865
5866                                 t = header->locals [pos];
5867                                 var = &jit->locals [pos];
5868                         }
5869
5870                         if (MONO_TYPE_IS_REFERENCE (t))
5871                                 val_buf = g_alloca (sizeof (MonoObject*));
5872                         else
5873                                 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
5874                         err = decode_value (t, frame->domain, val_buf, p, &p, end);
5875                         if (err)
5876                                 return err;
5877
5878                         set_var (t, var, &frame->ctx, frame->domain, val_buf);
5879                 }
5880                 break;
5881         }
5882         default:
5883                 return ERR_NOT_IMPLEMENTED;
5884         }
5885
5886         return ERR_NONE;
5887 }
5888
5889 static ErrorCode
5890 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5891 {
5892         MonoArray *arr;
5893         int objid, err, index, len, i, esize;
5894         gpointer elem;
5895
5896         objid = decode_objid (p, &p, end);
5897         err = get_object (objid, (MonoObject**)&arr);
5898         if (err)
5899                 return err;
5900
5901         switch (command) {
5902         case CMD_ARRAY_REF_GET_LENGTH:
5903                 buffer_add_int (buf, arr->obj.vtable->klass->rank);
5904                 if (!arr->bounds) {
5905                         buffer_add_int (buf, arr->max_length);
5906                         buffer_add_int (buf, 0);
5907                 } else {
5908                         for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
5909                                 buffer_add_int (buf, arr->bounds [i].length);
5910                                 buffer_add_int (buf, arr->bounds [i].lower_bound);
5911                         }
5912                 }
5913                 break;
5914         case CMD_ARRAY_REF_GET_VALUES:
5915                 index = decode_int (p, &p, end);
5916                 len = decode_int (p, &p, end);
5917
5918                 g_assert (index >= 0 && len >= 0);
5919                 // Reordered to avoid integer overflow
5920                 g_assert (!(index > arr->max_length - len));
5921
5922                 esize = mono_array_element_size (arr->obj.vtable->klass);
5923                 for (i = index; i < index + len; ++i) {
5924                         elem = (gpointer*)((char*)arr->vector + (i * esize));
5925                         buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
5926                 }
5927                 break;
5928         case CMD_ARRAY_REF_SET_VALUES:
5929                 index = decode_int (p, &p, end);
5930                 len = decode_int (p, &p, end);
5931
5932                 g_assert (index >= 0 && len >= 0);
5933                 // Reordered to avoid integer overflow
5934                 g_assert (!(index > arr->max_length - len));
5935
5936                 esize = mono_array_element_size (arr->obj.vtable->klass);
5937                 for (i = index; i < index + len; ++i) {
5938                         elem = (gpointer*)((char*)arr->vector + (i * esize));
5939
5940                         decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
5941                 }
5942                 break;
5943         default:
5944                 return ERR_NOT_IMPLEMENTED;
5945         }
5946
5947         return ERR_NONE;
5948 }
5949
5950 static ErrorCode
5951 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5952 {
5953         int objid, err;
5954         MonoString *str;
5955         char *s;
5956
5957         objid = decode_objid (p, &p, end);
5958         err = get_object (objid, (MonoObject**)&str);
5959         if (err)
5960                 return err;
5961
5962         switch (command) {
5963         case CMD_STRING_REF_GET_VALUE:
5964                 s = mono_string_to_utf8 (str);
5965                 buffer_add_string (buf, s);
5966                 g_free (s);
5967                 break;
5968         default:
5969                 return ERR_NOT_IMPLEMENTED;
5970         }
5971
5972         return ERR_NONE;
5973 }
5974
5975 static ErrorCode
5976 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5977 {
5978         int objid, err;
5979         MonoObject *obj;
5980         int len, i;
5981         MonoClassField *f;
5982         MonoClass *k;
5983         gboolean found;
5984
5985         if (command == CMD_OBJECT_REF_IS_COLLECTED) {
5986                 objid = decode_objid (p, &p, end);
5987                 err = get_object (objid, &obj);
5988                 if (err)
5989                         buffer_add_int (buf, 1);
5990                 else
5991                         buffer_add_int (buf, 0);
5992                 return 0;
5993         }
5994
5995         objid = decode_objid (p, &p, end);
5996         err = get_object (objid, &obj);
5997         if (err)
5998                 return err;
5999
6000         switch (command) {
6001         case CMD_OBJECT_REF_GET_TYPE:
6002                 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
6003                 break;
6004         case CMD_OBJECT_REF_GET_VALUES:
6005                 len = decode_int (p, &p, end);
6006
6007                 for (i = 0; i < len; ++i) {
6008                         MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
6009                         if (err)
6010                                 return err;
6011
6012                         /* Check that the field belongs to the object */
6013                         found = FALSE;
6014                         for (k = obj->vtable->klass; k; k = k->parent) {
6015                                 if (k == f->parent) {
6016                                         found = TRUE;
6017                                         break;
6018                                 }
6019                         }
6020                         if (!found)
6021                                 return ERR_INVALID_FIELDID;
6022
6023                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
6024                                 guint8 *val;
6025                                 MonoVTable *vtable;
6026
6027                                 if (mono_class_field_is_special_static (f))
6028                                         return ERR_INVALID_FIELDID;
6029
6030                                 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
6031                                 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
6032                                 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6033                                 mono_field_static_get_value (vtable, f, val);
6034                                 buffer_add_value (buf, f->type, val, obj->vtable->domain);
6035                                 g_free (val);
6036                         } else {
6037                                 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
6038                         }
6039                 }
6040                 break;
6041         case CMD_OBJECT_REF_SET_VALUES:
6042                 len = decode_int (p, &p, end);
6043
6044                 for (i = 0; i < len; ++i) {
6045                         f = decode_fieldid (p, &p, end, NULL, &err);
6046                         if (err)
6047                                 return err;
6048
6049                         /* Check that the field belongs to the object */
6050                         found = FALSE;
6051                         for (k = obj->vtable->klass; k; k = k->parent) {
6052                                 if (k == f->parent) {
6053                                         found = TRUE;
6054                                         break;
6055                                 }
6056                         }
6057                         if (!found)
6058                                 return ERR_INVALID_FIELDID;
6059
6060                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
6061                                 guint8 *val;
6062                                 MonoVTable *vtable;
6063
6064                                 if (mono_class_field_is_special_static (f))
6065                                         return ERR_INVALID_FIELDID;
6066
6067                                 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
6068                                 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
6069
6070                                 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6071                                 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
6072                                 if (err) {
6073                                         g_free (val);
6074                                         return err;
6075                                 }
6076                                 mono_field_static_set_value (vtable, f, val);
6077                                 g_free (val);
6078                         } else {
6079                                 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
6080                                 if (err)
6081                                         return err;
6082                         }
6083                 }
6084                 break;
6085         case CMD_OBJECT_REF_GET_ADDRESS:
6086                 buffer_add_long (buf, (gssize)obj);
6087                 break;
6088         case CMD_OBJECT_REF_GET_DOMAIN:
6089                 buffer_add_domainid (buf, obj->vtable->domain);
6090                 break;
6091         default:
6092                 return ERR_NOT_IMPLEMENTED;
6093         }
6094
6095         return ERR_NONE;
6096 }
6097
6098 static const char*
6099 command_set_to_string (CommandSet command_set)
6100 {
6101         switch (command_set) {
6102         case CMD_SET_VM:
6103                 return "VM";
6104         case CMD_SET_OBJECT_REF:
6105                 return "OBJECT_REF";
6106         case CMD_SET_STRING_REF:
6107                 return "STRING_REF"; 
6108         case CMD_SET_THREAD:
6109                 return "THREAD"; 
6110         case CMD_SET_ARRAY_REF:
6111                 return "ARRAY_REF"; 
6112         case CMD_SET_EVENT_REQUEST:
6113                 return "EVENT_REQUEST"; 
6114         case CMD_SET_STACK_FRAME:
6115                 return "STACK_FRAME"; 
6116         case CMD_SET_APPDOMAIN:
6117                 return "APPDOMAIN"; 
6118         case CMD_SET_ASSEMBLY:
6119                 return "ASSEMBLY"; 
6120         case CMD_SET_METHOD:
6121                 return "METHOD"; 
6122         case CMD_SET_TYPE:
6123                 return "TYPE"; 
6124         case CMD_SET_MODULE:
6125                 return "MODULE"; 
6126         case CMD_SET_EVENT:
6127                 return "EVENT"; 
6128         default:
6129                 return "";
6130         }
6131 }
6132
6133 /*
6134  * debugger_thread:
6135  *
6136  *   This thread handles communication with the debugger client using a JDWP
6137  * like protocol.
6138  */
6139 static guint32 WINAPI
6140 debugger_thread (void *arg)
6141 {
6142         int res, len, id, flags, command_set, command;
6143         guint8 header [HEADER_LENGTH];
6144         guint8 *data, *p, *end;
6145         Buffer buf;
6146         ErrorCode err;
6147         gboolean no_reply;
6148
6149         DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
6150
6151         debugger_thread_id = GetCurrentThreadId ();
6152
6153         mono_jit_thread_attach (mono_get_root_domain ());
6154
6155         mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
6156
6157         mono_set_is_debugger_attached (TRUE);
6158
6159         while (TRUE) {
6160                 res = recv (conn_fd, header, HEADER_LENGTH, 0);
6161
6162                 /* This will break if the socket is closed during shutdown too */
6163                 if (res != HEADER_LENGTH)
6164                         break;
6165
6166                 p = header;
6167                 end = header + HEADER_LENGTH;
6168
6169                 len = decode_int (p, &p, end);
6170                 id = decode_int (p, &p, end);
6171                 flags = decode_byte (p, &p, end);
6172                 command_set = decode_byte (p, &p, end);
6173                 command = decode_byte (p, &p, end);
6174
6175                 g_assert (flags == 0);
6176
6177                 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%d), id=%d.\n", command_set_to_string (command_set), command, id));
6178
6179                 data = g_malloc (len - HEADER_LENGTH);
6180                 if (len - HEADER_LENGTH > 0)
6181                 {
6182                         res = recv (conn_fd, data, len - HEADER_LENGTH, 0);
6183                         if (res != len - HEADER_LENGTH)
6184                                 break;
6185                 }
6186
6187                 p = data;
6188                 end = data + (len - HEADER_LENGTH);
6189
6190                 buffer_init (&buf, 128);
6191
6192                 err = ERR_NONE;
6193                 no_reply = FALSE;
6194
6195                 /* Process the request */
6196                 switch (command_set) {
6197                 case CMD_SET_VM:
6198                         err = vm_commands (command, id, p, end, &buf);
6199                         if (!err && command == CMD_VM_INVOKE_METHOD)
6200                                 /* Sent after the invoke is complete */
6201                                 no_reply = TRUE;
6202                         break;
6203                 case CMD_SET_EVENT_REQUEST:
6204                         err = event_commands (command, p, end, &buf);
6205                         break;
6206                 case CMD_SET_APPDOMAIN:
6207                         err = domain_commands (command, p, end, &buf);
6208                         break;
6209                 case CMD_SET_ASSEMBLY:
6210                         err = assembly_commands (command, p, end, &buf);
6211                         break;
6212                 case CMD_SET_MODULE:
6213                         err = module_commands (command, p, end, &buf);
6214                         break;
6215                 case CMD_SET_TYPE:
6216                         err = type_commands (command, p, end, &buf);
6217                         break;
6218                 case CMD_SET_METHOD:
6219                         err = method_commands (command, p, end, &buf);
6220                         break;
6221                 case CMD_SET_THREAD:
6222                         err = thread_commands (command, p, end, &buf);
6223                         break;
6224                 case CMD_SET_STACK_FRAME:
6225                         err = frame_commands (command, p, end, &buf);
6226                         break;
6227                 case CMD_SET_ARRAY_REF:
6228                         err = array_commands (command, p, end, &buf);
6229                         break;
6230                 case CMD_SET_STRING_REF:
6231                         err = string_commands (command, p, end, &buf);
6232                         break;
6233                 case CMD_SET_OBJECT_REF:
6234                         err = object_commands (command, p, end, &buf);
6235                         break;
6236                 default:
6237                         err = ERR_NOT_IMPLEMENTED;
6238                 }               
6239
6240                 if (!no_reply)
6241                         send_reply_packet (id, err, &buf);
6242
6243                 g_free (data);
6244                 buffer_free (&buf);
6245
6246                 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
6247                         break;
6248         }
6249
6250         mono_set_is_debugger_attached (FALSE);
6251
6252         mono_mutex_lock (&debugger_thread_exited_mutex);
6253         debugger_thread_exited = TRUE;
6254         mono_cond_signal (&debugger_thread_exited_cond);
6255         mono_mutex_unlock (&debugger_thread_exited_mutex);
6256
6257         DEBUG (1, printf ("[dbg] Debugger thread exited.\n"));
6258
6259         return 0;
6260 }
6261
6262 #else /* DISABLE_DEBUGGER_AGENT */
6263
6264 void
6265 mono_debugger_agent_parse_options (char *options)
6266 {
6267         g_error ("This runtime is configure with the debugger agent disabled.");
6268 }
6269
6270 void
6271 mono_debugger_agent_init (void)
6272 {
6273 }
6274
6275 void
6276 mono_debugger_agent_breakpoint_hit (void *sigctx)
6277 {
6278 }
6279
6280 void
6281 mono_debugger_agent_single_step_event (void *sigctx)
6282 {
6283 }
6284
6285 void
6286 mono_debugger_agent_free_domain_info (MonoDomain *domain)
6287 {
6288 }
6289
6290 gboolean
6291 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
6292 {
6293         return FALSE;
6294 }
6295
6296 void
6297 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *ctx)
6298 {
6299 }
6300
6301 void
6302 mono_debugger_agent_handle_unhandled_exception (MonoException *exc, MonoContext *ctx)
6303 {
6304         
6305 }
6306 #endif
6307