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