Merge pull request #201 from QuickJack/master
[mono.git] / mono / mini / mini-darwin.c
1 /*
2  * mini-darwin.c: Darwin/MacOS support for Mono.
3  *
4  * Authors:
5  *   Mono Team (mono-list@lists.ximian.com)
6  *
7  * Copyright 2001-2003 Ximian, Inc.
8  * Copyright 2003-2011 Novell, Inc (http://www.novell.com)
9  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
10  *
11  * See LICENSE for licensing information.
12  */
13 #include <config.h>
14 #include <signal.h>
15 #ifdef HAVE_ALLOCA_H
16 #include <alloca.h>
17 #endif
18 #ifdef HAVE_UNISTD_H
19 #include <unistd.h>
20 #endif
21 #include <math.h>
22 #ifdef HAVE_SYS_TIME_H
23 #include <sys/time.h>
24 #endif
25
26 #include <mono/metadata/assembly.h>
27 #include <mono/metadata/loader.h>
28 #include <mono/metadata/tabledefs.h>
29 #include <mono/metadata/class.h>
30 #include <mono/metadata/object.h>
31 #include <mono/metadata/tokentype.h>
32 #include <mono/metadata/tabledefs.h>
33 #include <mono/metadata/threads.h>
34 #include <mono/metadata/appdomain.h>
35 #include <mono/metadata/debug-helpers.h>
36 #include <mono/io-layer/io-layer.h>
37 #include "mono/metadata/profiler.h"
38 #include <mono/metadata/profiler-private.h>
39 #include <mono/metadata/mono-config.h>
40 #include <mono/metadata/environment.h>
41 #include <mono/metadata/mono-debug.h>
42 #include <mono/metadata/threads-types.h>
43 #include <mono/metadata/verify.h>
44 #include <mono/metadata/verify-internals.h>
45 #include <mono/metadata/mempool-internals.h>
46 #include <mono/metadata/attach.h>
47 #include <mono/metadata/gc-internal.h>
48 #include <mono/utils/mono-math.h>
49 #include <mono/utils/mono-compiler.h>
50 #include <mono/utils/mono-counters.h>
51 #include <mono/utils/mono-logger-internal.h>
52 #include <mono/utils/mono-mmap.h>
53 #include <mono/utils/dtrace.h>
54
55 #include "mini.h"
56 #include <string.h>
57 #include <ctype.h>
58 #include "trace.h"
59 #include "version.h"
60
61 #include "jit-icalls.h"
62
63 /* MacOS includes */
64 #include <mach/mach.h>
65 #include <mach/mach_error.h>
66 #include <mach/exception.h>
67 #include <mach/task.h>
68 #include <pthread.h>
69 #include <dlfcn.h>
70 #include <AvailabilityMacros.h>
71
72 #if (MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_5) && !defined (TARGET_ARM)
73 #define NEEDS_EXCEPTION_THREAD
74 #endif
75
76 #ifdef NEEDS_EXCEPTION_THREAD
77
78 /*
79  * This code disables the CrashReporter of MacOS X by installing
80  * a dummy Mach exception handler.
81  */
82
83 /*
84  * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/exc_server.html
85  */
86 extern boolean_t exc_server (mach_msg_header_t *request_msg, mach_msg_header_t *reply_msg);
87
88 /*
89  * The exception message
90  */
91 typedef struct {
92         mach_msg_base_t msg;  /* common mach message header */
93         char payload [1024];  /* opaque */
94 } mach_exception_msg_t;
95
96 /* The exception port */
97 static mach_port_t mach_exception_port = VM_MAP_NULL;
98
99 /*
100  * Implicitly called by exc_server. Must be public.
101  *
102  * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/catch_exception_raise.html
103  */
104 kern_return_t
105 catch_exception_raise (
106         mach_port_t exception_port,
107         mach_port_t thread,
108         mach_port_t task,
109         exception_type_t exception,
110         exception_data_t code,
111         mach_msg_type_number_t code_count)
112 {
113         /* consume the exception */
114         return KERN_FAILURE;
115 }
116
117 /*
118  * Exception thread handler.
119  */
120 static
121 void *
122 mach_exception_thread (void *arg)
123 {
124         for (;;) {
125                 mach_exception_msg_t request;
126                 mach_exception_msg_t reply;
127                 mach_msg_return_t result;
128
129                 /* receive from "mach_exception_port" */
130                 result = mach_msg (&request.msg.header,
131                                    MACH_RCV_MSG | MACH_RCV_LARGE,
132                                    0,
133                                    sizeof (request),
134                                    mach_exception_port,
135                                    MACH_MSG_TIMEOUT_NONE,
136                                    MACH_PORT_NULL);
137
138                 g_assert (result == MACH_MSG_SUCCESS);
139
140                 /* dispatch to catch_exception_raise () */
141                 exc_server (&request.msg.header, &reply.msg.header);
142
143                 /* send back to sender */
144                 result = mach_msg (&reply.msg.header,
145                                    MACH_SEND_MSG,
146                                    reply.msg.header.msgh_size,
147                                    0,
148                                    MACH_PORT_NULL,
149                                    MACH_MSG_TIMEOUT_NONE,
150                                    MACH_PORT_NULL);
151
152                 g_assert (result == MACH_MSG_SUCCESS);
153         }
154         return NULL;
155 }
156
157 static void
158 macosx_register_exception_handler ()
159 {
160         mach_port_t task;
161         pthread_attr_t attr;
162         pthread_t thread;
163
164         if (mach_exception_port != VM_MAP_NULL)
165                 return;
166
167         task = mach_task_self ();
168
169         /* create the "mach_exception_port" with send & receive rights */
170         g_assert (mach_port_allocate (task, MACH_PORT_RIGHT_RECEIVE,
171                                       &mach_exception_port) == KERN_SUCCESS);
172         g_assert (mach_port_insert_right (task, mach_exception_port, mach_exception_port,
173                                           MACH_MSG_TYPE_MAKE_SEND) == KERN_SUCCESS);
174
175         /* create the exception handler thread */
176         g_assert (!pthread_attr_init (&attr));
177         g_assert (!pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED));
178         g_assert (!pthread_create (&thread, &attr, mach_exception_thread, NULL));
179         pthread_attr_destroy (&attr);
180
181         /*
182          * register "mach_exception_port" as a receiver for the
183          * EXC_BAD_ACCESS exception
184          *
185          * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/task_set_exception_ports.html
186          */
187         g_assert (task_set_exception_ports (task, EXC_MASK_BAD_ACCESS,
188                                             mach_exception_port,
189                                             EXCEPTION_DEFAULT,
190                                             MACHINE_THREAD_STATE) == KERN_SUCCESS);
191
192         mono_gc_register_mach_exception_thread (thread);
193 }
194
195 #endif
196
197 /* This is #define'd by Boehm GC to _GC_dlopen. */
198 #undef dlopen
199
200 void
201 mono_runtime_install_handlers (void)
202 {
203 #ifdef NEEDS_EXCEPTION_THREAD
204         macosx_register_exception_handler ();
205 #endif
206         mono_runtime_posix_install_handlers ();
207
208         /* Snow Leopard has a horrible bug: http://openradar.appspot.com/7209349
209          * This causes obscure SIGTRAP's for any application that comes across this built on
210          * Snow Leopard.  This is a horrible hack to ensure that the private __CFInitialize
211          * is run on the main thread, so that we don't get SIGTRAPs later
212          */
213 #if defined (__APPLE__) && (defined (__i386__) || defined (__x86_64__))
214         {
215                 void *handle = dlopen ("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", RTLD_LAZY);
216                 if (handle == NULL)
217                         return;
218
219                 dlclose (handle);
220         }
221 #endif
222 }
223
224 pid_t
225 mono_runtime_syscall_fork ()
226 {
227         return (pid_t) fork ();
228 }
229
230 gboolean
231 mono_gdb_render_native_backtraces (pid_t crashed_pid)
232 {
233         const char *argv [5];
234         char gdb_template [] = "/tmp/mono-gdb-commands.XXXXXX";
235
236         argv [0] = g_find_program_in_path ("gdb");
237         if (argv [0] == NULL) {
238                 return FALSE;
239         }
240
241         if (mkstemp (gdb_template) != -1) {
242                 FILE *gdb_commands = fopen (gdb_template, "w");
243
244                 fprintf (gdb_commands, "attach %ld\n", (long) crashed_pid);
245                 fprintf (gdb_commands, "info threads\n");
246                 fprintf (gdb_commands, "thread apply all bt\n");
247
248                 fflush (gdb_commands);
249                 fclose (gdb_commands);
250
251                 argv [1] = "-batch";
252                 argv [2] = "-x";
253                 argv [3] = gdb_template;
254                 argv [4] = 0;
255
256                 execv (argv [0], (char**)argv);
257
258                 unlink (gdb_template);
259         }
260
261         return TRUE;
262 }
263
264 gboolean
265 mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoNativeThreadId thread_id, MonoNativeThreadHandle thread_handle)
266 {
267         kern_return_t ret;
268         mach_msg_type_number_t num_state;
269         thread_state_t state;
270         ucontext_t ctx;
271         mcontext_t mctx;
272         guint32 domain_key, jit_key;
273         MonoJitTlsData *jit_tls;
274         void *domain;
275
276         state = (thread_state_t) alloca (mono_mach_arch_get_thread_state_size ());
277         mctx = (mcontext_t) alloca (mono_mach_arch_get_mcontext_size ());
278
279         ret = mono_mach_arch_get_thread_state (thread_handle, state, &num_state);
280         if (ret != KERN_SUCCESS)
281                 return FALSE;
282
283         mono_mach_arch_thread_state_to_mcontext (state, mctx);
284         ctx.uc_mcontext = mctx;
285
286         mono_sigctx_to_monoctx (&ctx, &tctx->ctx);
287
288         domain_key = mono_domain_get_tls_offset ();
289         jit_key = mono_get_jit_tls_key ();
290         jit_tls = mono_mach_arch_get_tls_value_from_thread (thread_id, jit_key);
291         domain = mono_mach_arch_get_tls_value_from_thread (thread_id, domain_key);
292
293         /*Thread already started to cleanup, can no longer capture unwind state*/
294         if (!jit_tls)
295                 return FALSE;
296         g_assert (domain);
297
298         tctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = domain;
299         tctx->unwind_data [MONO_UNWIND_DATA_LMF] = jit_tls ? jit_tls->lmf : NULL;
300         tctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
301         tctx->valid = TRUE;
302
303         return TRUE;
304 }