ce087bbc36bb4e5d7b9d5e12f1885d7a0a5dcd27
[mono.git] / mono / utils / mono-threads-posix.c
1 /*
2  * mono-threads-posix.c: Low-level threading, posix version
3  *
4  * Author:
5  *      Rodrigo Kumpera (kumpera@gmail.com)
6  *
7  * (C) 2011 Novell, Inc
8  */
9
10 #include <config.h>
11
12 #include <mono/utils/mono-compiler.h>
13 #include <mono/utils/mono-semaphore.h>
14 #include <mono/utils/mono-threads.h>
15 #include <mono/utils/mono-tls.h>
16 #include <mono/utils/mono-mmap.h>
17 #include <mono/metadata/threads-types.h>
18 #include <limits.h>
19
20 #include <errno.h>
21
22 #if defined(PLATFORM_ANDROID)
23 extern int tkill (pid_t tid, int signal);
24 #endif
25
26 #if defined(_POSIX_VERSION) || defined(__native_client__)
27 #include <sys/resource.h>
28 #include <signal.h>
29
30 #if defined(__native_client__)
31 void nacl_shutdown_gc_thread(void);
32 #endif
33
34 typedef struct {
35         void *(*start_routine)(void*);
36         void *arg;
37         int flags;
38         MonoSemType registered;
39         HANDLE handle;
40 } StartInfo;
41
42 static void*
43 inner_start_thread (void *arg)
44 {
45         StartInfo *start_info = arg;
46         void *t_arg = start_info->arg;
47         int res;
48         void *(*start_func)(void*) = start_info->start_routine;
49         guint32 flags = start_info->flags;
50         void *result;
51         HANDLE handle;
52         MonoThreadInfo *info;
53
54         /* Register the thread with the io-layer */
55         handle = wapi_create_thread_handle ();
56         if (!handle) {
57                 res = MONO_SEM_POST (&(start_info->registered));
58                 g_assert (!res);
59                 return NULL;
60         }
61         start_info->handle = handle;
62
63         info = mono_thread_info_attach (&result);
64         info->runtime_thread = TRUE;
65         info->handle = handle;
66
67         if (flags & CREATE_SUSPENDED) {
68                 info->create_suspended = TRUE;
69                 MONO_SEM_INIT (&info->create_suspended_sem, 0);
70         }
71
72         /* start_info is not valid after this */
73         res = MONO_SEM_POST (&(start_info->registered));
74         g_assert (!res);
75         start_info = NULL;
76
77         if (flags & CREATE_SUSPENDED) {
78                 while (MONO_SEM_WAIT (&info->create_suspended_sem) != 0 &&
79                            errno == EINTR);
80                 MONO_SEM_DESTROY (&info->create_suspended_sem);
81         }
82
83         /* Run the actual main function of the thread */
84         result = start_func (t_arg);
85
86         /*
87         mono_thread_info_detach ();
88         */
89
90 #if defined(__native_client__)
91         nacl_shutdown_gc_thread();
92 #endif
93
94         wapi_thread_handle_set_exited (handle, GPOINTER_TO_UINT (result));
95         /* This is needed by mono_threads_core_unregister () which is called later */
96         info->handle = NULL;
97
98         g_assert (mono_threads_get_callbacks ()->thread_exit);
99         mono_threads_get_callbacks ()->thread_exit (NULL);
100         g_assert_not_reached ();
101         return result;
102 }
103
104 HANDLE
105 mono_threads_core_create_thread (LPTHREAD_START_ROUTINE start_routine, gpointer arg, guint32 stack_size, guint32 creation_flags, MonoNativeThreadId *out_tid)
106 {
107         pthread_attr_t attr;
108         int res;
109         pthread_t thread;
110         StartInfo start_info;
111
112         res = pthread_attr_init (&attr);
113         g_assert (!res);
114
115         if (stack_size == 0) {
116 #if HAVE_VALGRIND_MEMCHECK_H
117                 if (RUNNING_ON_VALGRIND)
118                         stack_size = 1 << 20;
119                 else
120                         stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
121 #else
122                 stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
123 #endif
124         }
125
126 #ifdef PTHREAD_STACK_MIN
127         if (stack_size < PTHREAD_STACK_MIN)
128                 stack_size = PTHREAD_STACK_MIN;
129 #endif
130
131 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
132         res = pthread_attr_setstacksize (&attr, stack_size);
133         g_assert (!res);
134 #endif
135
136         memset (&start_info, 0, sizeof (StartInfo));
137         start_info.start_routine = (gpointer)start_routine;
138         start_info.arg = arg;
139         start_info.flags = creation_flags;
140         MONO_SEM_INIT (&(start_info.registered), 0);
141
142         /* Actually start the thread */
143         res = mono_threads_get_callbacks ()->mono_gc_pthread_create (&thread, &attr, inner_start_thread, &start_info);
144         if (res) {
145                 MONO_SEM_DESTROY (&(start_info.registered));
146                 return NULL;
147         }
148
149         /* Wait until the thread register itself in various places */
150         while (MONO_SEM_WAIT (&(start_info.registered)) != 0) {
151                 /*if (EINTR != errno) ABORT("sem_wait failed"); */
152         }
153         MONO_SEM_DESTROY (&(start_info.registered));
154
155         if (out_tid)
156                 *out_tid = thread;
157
158         return start_info.handle;
159 }
160
161 /*
162  * mono_threads_core_resume_created:
163  *
164  *   Resume a newly created thread created using CREATE_SUSPENDED.
165  */
166 void
167 mono_threads_core_resume_created (MonoThreadInfo *info, MonoNativeThreadId tid)
168 {
169         MONO_SEM_POST (&info->create_suspended_sem);
170 }
171
172 gboolean
173 mono_threads_core_yield (void)
174 {
175         return sched_yield () == 0;
176 }
177
178 void
179 mono_threads_core_exit (int exit_code)
180 {
181         MonoThreadInfo *current = mono_thread_info_current ();
182
183 #if defined(__native_client__)
184         nacl_shutdown_gc_thread();
185 #endif
186
187         wapi_thread_handle_set_exited (current->handle, exit_code);
188
189         g_assert (mono_threads_get_callbacks ()->thread_exit);
190         mono_threads_get_callbacks ()->thread_exit (NULL);
191 }
192
193 void
194 mono_threads_core_unregister (MonoThreadInfo *info)
195 {
196         if (info->handle) {
197                 wapi_thread_handle_set_exited (info->handle, 0);
198                 info->handle = NULL;
199         }
200 }
201
202 HANDLE
203 mono_threads_core_open_handle (void)
204 {
205         MonoThreadInfo *info;
206
207         info = mono_thread_info_current ();
208         g_assert (info);
209
210         if (!info->handle)
211                 info->handle = wapi_create_thread_handle ();
212         else
213                 wapi_ref_thread_handle (info->handle);
214         return info->handle;
215 }
216
217 int
218 mono_threads_get_max_stack_size (void)
219 {
220         struct rlimit lim;
221
222         /* If getrlimit fails, we don't enforce any limits. */
223         if (getrlimit (RLIMIT_STACK, &lim))
224                 return INT_MAX;
225         /* rlim_t is an unsigned long long on 64bits OSX but we want an int response. */
226         if (lim.rlim_max > (rlim_t)INT_MAX)
227                 return INT_MAX;
228         return (int)lim.rlim_max;
229 }
230
231 HANDLE
232 mono_threads_core_open_thread_handle (HANDLE handle, MonoNativeThreadId tid)
233 {
234         wapi_ref_thread_handle (handle);
235
236         return handle;
237 }
238
239 #if !defined (__MACH__)
240
241 #if !defined(__native_client__)
242 static void
243 suspend_signal_handler (int _dummy, siginfo_t *info, void *context)
244 {
245         MonoThreadInfo *current = mono_thread_info_current ();
246         gboolean ret;
247         
248         if (current->syscall_break_signal) {
249                 current->syscall_break_signal = FALSE;
250                 return;
251         }
252
253         ret = mono_threads_get_runtime_callbacks ()->thread_state_init_from_sigctx (&current->suspend_state, context);
254
255         /* thread_state_init_from_sigctx return FALSE if the current thread is detaching and suspend can't continue. */
256         current->suspend_can_continue = ret;
257
258         MONO_SEM_POST (&current->begin_suspend_semaphore);
259
260         /* This thread is doomed, all we can do is give up and let the suspender recover. */
261         if (!ret)
262                 return;
263
264         while (MONO_SEM_WAIT (&current->resume_semaphore) != 0) {
265                 /*if (EINTR != errno) ABORT("sem_wait failed"); */
266         }
267
268         if (current->async_target) {
269 #if MONO_ARCH_HAS_MONO_CONTEXT
270                 MonoContext tmp = current->suspend_state.ctx;
271                 mono_threads_get_runtime_callbacks ()->setup_async_callback (&tmp, current->async_target, current->user_data);
272                 current->async_target = current->user_data = NULL;
273                 mono_monoctx_to_sigctx (&tmp, context);
274 #else
275                 g_error ("The new interruption machinery requires a working mono-context");
276 #endif
277         }
278
279         MONO_SEM_POST (&current->finish_resume_semaphore);
280 }
281 #endif
282
283 static void
284 mono_posix_add_signal_handler (int signo, gpointer handler)
285 {
286 #if !defined(__native_client__)
287         /*FIXME, move the code from mini to utils and do the right thing!*/
288         struct sigaction sa;
289         struct sigaction previous_sa;
290         int ret;
291
292         sa.sa_sigaction = handler;
293         sigemptyset (&sa.sa_mask);
294         sa.sa_flags = SA_SIGINFO;
295         ret = sigaction (signo, &sa, &previous_sa);
296
297         g_assert (ret != -1);
298 #endif
299 }
300
301 void
302 mono_threads_init_platform (void)
303 {
304 #if !defined(__native_client__)
305         /*
306         FIXME we should use all macros from mini to make this more portable
307         FIXME it would be very sweet if sgen could end up using this too.
308         */
309         if (mono_thread_info_new_interrupt_enabled ())
310                 mono_posix_add_signal_handler (mono_thread_get_abort_signal (), suspend_signal_handler);
311 #endif
312 }
313
314 /*nothing to be done here since suspend always abort syscalls due using signals*/
315 void
316 mono_threads_core_interrupt (MonoThreadInfo *info)
317 {
318 }
319
320 int
321 mono_threads_pthread_kill (MonoThreadInfo *info, int signum)
322 {
323 #if defined (PLATFORM_ANDROID)
324         int result, old_errno = errno;
325         result = tkill (info->native_handle, signum);
326         if (result < 0) {
327                 result = errno;
328                 errno = old_errno;
329         }
330         return result;
331 #elif defined(__native_client__)
332         /* Workaround pthread_kill abort() in NaCl glibc. */
333         return 0;
334 #else
335         return pthread_kill (mono_thread_info_get_tid (info), signum);
336 #endif
337
338 }
339
340 void
341 mono_threads_core_abort_syscall (MonoThreadInfo *info)
342 {
343         /*
344         We signal a thread to break it from the urrent syscall.
345         This signal should not be interpreted as a suspend request.
346         */
347         info->syscall_break_signal = TRUE;
348         mono_threads_pthread_kill (info, mono_thread_get_abort_signal ());
349 }
350
351 gboolean
352 mono_threads_core_needs_abort_syscall (void)
353 {
354         return TRUE;
355 }
356
357 gboolean
358 mono_threads_core_suspend (MonoThreadInfo *info)
359 {
360         /*FIXME, check return value*/
361         mono_threads_pthread_kill (info, mono_thread_get_abort_signal ());
362         while (MONO_SEM_WAIT (&info->begin_suspend_semaphore) != 0) {
363                 /* g_assert (errno == EINTR); */
364         }
365         return info->suspend_can_continue;
366 }
367
368 gboolean
369 mono_threads_core_resume (MonoThreadInfo *info)
370 {
371         MONO_SEM_POST (&info->resume_semaphore);
372         while (MONO_SEM_WAIT (&info->finish_resume_semaphore) != 0) {
373                 /* g_assert (errno == EINTR); */
374         }
375
376         return TRUE;
377 }
378
379 void
380 mono_threads_platform_register (MonoThreadInfo *info)
381 {
382         MONO_SEM_INIT (&info->begin_suspend_semaphore, 0);
383
384 #if defined (PLATFORM_ANDROID)
385         info->native_handle = (gpointer) gettid ();
386 #endif
387 }
388
389 void
390 mono_threads_platform_free (MonoThreadInfo *info)
391 {
392         MONO_SEM_DESTROY (&info->begin_suspend_semaphore);
393 }
394
395 MonoNativeThreadId
396 mono_native_thread_id_get (void)
397 {
398         return pthread_self ();
399 }
400
401 gboolean
402 mono_native_thread_id_equals (MonoNativeThreadId id1, MonoNativeThreadId id2)
403 {
404         return pthread_equal (id1, id2);
405 }
406
407 /*
408  * mono_native_thread_create:
409  *
410  *   Low level thread creation function without any GC wrappers.
411  */
412 gboolean
413 mono_native_thread_create (MonoNativeThreadId *tid, gpointer func, gpointer arg)
414 {
415         return pthread_create (tid, NULL, func, arg) == 0;
416 }
417
418 void
419 mono_threads_core_set_name (MonoNativeThreadId tid, const char *name)
420 {
421 #ifdef HAVE_PTHREAD_SETNAME_NP
422         if (!name) {
423                 pthread_setname_np (tid, "");
424         } else {
425                 char n [16];
426
427                 strncpy (n, name, 16);
428                 n [15] = '\0';
429                 pthread_setname_np (tid, n);
430         }
431 #endif
432 }
433
434 #endif /*!defined (__MACH__)*/
435
436 #endif