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