4b9f5d393f5e79fb7ee9dc489f7fe8b00a0e7f69
[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 /* For pthread_main_np, pthread_get_stackaddr_np and pthread_get_stacksize_np */
13 #if defined (__MACH__)
14 #define _DARWIN_C_SOURCE 1
15 #endif
16
17 #include <mono/utils/mono-threads.h>
18 #include <mono/utils/mono-threads-posix-signals.h>
19 #include <mono/utils/mono-coop-semaphore.h>
20 #include <mono/metadata/gc-internals.h>
21 #include <mono/metadata/w32mutex-utils.h>
22 #include <mono/utils/w32handle.h>
23
24 #include <errno.h>
25
26 #if defined(PLATFORM_ANDROID) && !defined(TARGET_ARM64) && !defined(TARGET_AMD64)
27 #define USE_TKILL_ON_ANDROID 1
28 #endif
29
30 #ifdef USE_TKILL_ON_ANDROID
31 extern int tkill (pid_t tid, int signal);
32 #endif
33
34 #if defined(_POSIX_VERSION) || defined(__native_client__)
35
36 #include <pthread.h>
37
38 #include <sys/resource.h>
39
40 #if defined(__native_client__)
41 void nacl_shutdown_gc_thread(void);
42 #endif
43
44 void
45 mono_threads_platform_register (MonoThreadInfo *info)
46 {
47         gpointer thread_handle;
48
49         info->owned_mutexes = g_ptr_array_new ();
50
51         thread_handle = mono_w32handle_new (MONO_W32HANDLE_THREAD, NULL);
52         if (thread_handle == INVALID_HANDLE_VALUE)
53                 g_error ("%s: failed to create handle", __func__);
54
55         g_assert (!info->handle);
56         info->handle = thread_handle;
57 }
58
59 int
60 mono_threads_platform_create_thread (MonoThreadStart thread_fn, gpointer thread_data, gsize stack_size, MonoNativeThreadId *out_tid)
61 {
62         pthread_attr_t attr;
63         pthread_t thread;
64         int policy;
65         struct sched_param param;
66         gint res;
67
68         res = pthread_attr_init (&attr);
69         g_assert (!res);
70
71 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
72         if (stack_size == 0) {
73 #if HAVE_VALGRIND_MEMCHECK_H
74                 if (RUNNING_ON_VALGRIND)
75                         stack_size = 1 << 20;
76                 else
77                         stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
78 #else
79                 stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
80 #endif
81         }
82
83 #ifdef PTHREAD_STACK_MIN
84         if (stack_size < PTHREAD_STACK_MIN)
85                 stack_size = PTHREAD_STACK_MIN;
86 #endif
87
88         res = pthread_attr_setstacksize (&attr, stack_size);
89         g_assert (!res);
90 #endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */
91
92         memset (&param, 0, sizeof (param));
93
94         res = pthread_attr_getschedpolicy (&attr, &policy);
95         if (res != 0)
96                 g_error ("%s: pthread_attr_getschedpolicy failed, error: \"%s\" (%d)", g_strerror (res), res);
97
98 #ifdef _POSIX_PRIORITY_SCHEDULING
99         int max, min;
100
101         /* Necessary to get valid priority range */
102
103         min = sched_get_priority_min (policy);
104         max = sched_get_priority_max (policy);
105
106         if (max > 0 && min >= 0 && max > min)
107                 param.sched_priority = (max - min) / 2 + min;
108         else
109 #endif
110         {
111                 switch (policy) {
112                 case SCHED_FIFO:
113                 case SCHED_RR:
114                         param.sched_priority = 50;
115                         break;
116 #ifdef SCHED_BATCH
117                 case SCHED_BATCH:
118 #endif
119                 case SCHED_OTHER:
120                         param.sched_priority = 0;
121                         break;
122                 default:
123                         g_error ("%s: unknown policy %d", __func__, policy);
124                 }
125         }
126
127         res = pthread_attr_setschedparam (&attr, &param);
128         if (res != 0)
129                 g_error ("%s: pthread_attr_setschedparam failed, error: \"%s\" (%d)", g_strerror (res), res);
130
131         /* Actually start the thread */
132         res = mono_gc_pthread_create (&thread, &attr, (gpointer (*)(gpointer)) thread_fn, thread_data);
133         if (res)
134                 return -1;
135
136         if (out_tid)
137                 *out_tid = thread;
138
139         return 0;
140 }
141
142 gboolean
143 mono_threads_platform_yield (void)
144 {
145         return sched_yield () == 0;
146 }
147
148 void
149 mono_threads_platform_exit (int exit_code)
150 {
151 #if defined(__native_client__)
152         nacl_shutdown_gc_thread();
153 #endif
154
155         mono_thread_info_detach ();
156
157         pthread_exit (NULL);
158 }
159
160 void
161 mono_threads_platform_unregister (MonoThreadInfo *info)
162 {
163         mono_threads_platform_set_exited (info);
164 }
165
166 int
167 mono_threads_get_max_stack_size (void)
168 {
169         struct rlimit lim;
170
171         /* If getrlimit fails, we don't enforce any limits. */
172         if (getrlimit (RLIMIT_STACK, &lim))
173                 return INT_MAX;
174         /* rlim_t is an unsigned long long on 64bits OSX but we want an int response. */
175         if (lim.rlim_max > (rlim_t)INT_MAX)
176                 return INT_MAX;
177         return (int)lim.rlim_max;
178 }
179
180 gpointer
181 mono_threads_platform_duplicate_handle (MonoThreadInfo *info)
182 {
183         g_assert (info->handle);
184         mono_w32handle_ref (info->handle);
185         return info->handle;
186 }
187
188 HANDLE
189 mono_threads_platform_open_thread_handle (HANDLE handle, MonoNativeThreadId tid)
190 {
191         mono_w32handle_ref (handle);
192
193         return handle;
194 }
195
196 void
197 mono_threads_platform_close_thread_handle (HANDLE handle)
198 {
199         mono_w32handle_unref (handle);
200 }
201
202 int
203 mono_threads_pthread_kill (MonoThreadInfo *info, int signum)
204 {
205         THREADS_SUSPEND_DEBUG ("sending signal %d to %p[%p]\n", signum, info, mono_thread_info_get_tid (info));
206 #ifdef USE_TKILL_ON_ANDROID
207         int result, old_errno = errno;
208         result = tkill (info->native_handle, signum);
209         if (result < 0) {
210                 result = errno;
211                 errno = old_errno;
212         }
213         return result;
214 #elif defined(__native_client__)
215         /* Workaround pthread_kill abort() in NaCl glibc. */
216         return 0;
217 #elif !defined(HAVE_PTHREAD_KILL)
218         g_error ("pthread_kill() is not supported by this platform");
219 #else
220         return pthread_kill (mono_thread_info_get_tid (info), signum);
221 #endif
222 }
223
224 MonoNativeThreadId
225 mono_native_thread_id_get (void)
226 {
227         return pthread_self ();
228 }
229
230 gboolean
231 mono_native_thread_id_equals (MonoNativeThreadId id1, MonoNativeThreadId id2)
232 {
233         return pthread_equal (id1, id2);
234 }
235
236 /*
237  * mono_native_thread_create:
238  *
239  *   Low level thread creation function without any GC wrappers.
240  */
241 gboolean
242 mono_native_thread_create (MonoNativeThreadId *tid, gpointer func, gpointer arg)
243 {
244         return pthread_create (tid, NULL, (void *(*)(void *)) func, arg) == 0;
245 }
246
247 void
248 mono_native_thread_set_name (MonoNativeThreadId tid, const char *name)
249 {
250 #ifdef __MACH__
251         /*
252          * We can't set the thread name for other threads, but we can at least make
253          * it work for threads that try to change their own name.
254          */
255         if (tid != mono_native_thread_id_get ())
256                 return;
257
258         if (!name) {
259                 pthread_setname_np ("");
260         } else {
261                 char n [63];
262
263                 strncpy (n, name, 63);
264                 n [62] = '\0';
265                 pthread_setname_np (n);
266         }
267 #elif defined (__NetBSD__)
268         if (!name) {
269                 pthread_setname_np (tid, "%s", (void*)"");
270         } else {
271                 char n [PTHREAD_MAX_NAMELEN_NP];
272
273                 strncpy (n, name, PTHREAD_MAX_NAMELEN_NP);
274                 n [PTHREAD_MAX_NAMELEN_NP - 1] = '\0';
275                 pthread_setname_np (tid, "%s", (void*)n);
276         }
277 #elif defined (HAVE_PTHREAD_SETNAME_NP)
278         if (!name) {
279                 pthread_setname_np (tid, "");
280         } else {
281                 char n [16];
282
283                 strncpy (n, name, 16);
284                 n [15] = '\0';
285                 pthread_setname_np (tid, n);
286         }
287 #endif
288 }
289
290 void
291 mono_threads_platform_set_exited (MonoThreadInfo *info)
292 {
293         gpointer mutex_handle;
294         int i, thr_ret;
295         pthread_t tid;
296
297         g_assert (info->handle);
298
299         if (mono_w32handle_issignalled (info->handle))
300                 g_error ("%s: handle %p thread %p has already exited, it's handle is signalled", __func__, info->handle, mono_thread_info_get_tid (info));
301         if (mono_w32handle_get_type (info->handle) == MONO_W32HANDLE_UNUSED)
302                 g_error ("%s: handle %p thread %p has already exited, it's handle type is 'unused'", __func__, info->handle, mono_thread_info_get_tid (info));
303
304         tid = pthread_self ();
305
306         for (i = 0; i < info->owned_mutexes->len; i++) {
307                 mutex_handle = g_ptr_array_index (info->owned_mutexes, i);
308                 mono_w32mutex_abandon (mutex_handle, tid);
309                 mono_thread_info_disown_mutex (info, mutex_handle);
310         }
311
312         g_ptr_array_free (info->owned_mutexes, TRUE);
313
314         thr_ret = mono_w32handle_lock_handle (info->handle);
315         g_assert (thr_ret == 0);
316
317         mono_w32handle_set_signal_state (info->handle, TRUE, TRUE);
318
319         thr_ret = mono_w32handle_unlock_handle (info->handle);
320         g_assert (thr_ret == 0);
321
322         /* The thread is no longer active, so unref it */
323         mono_w32handle_unref (info->handle);
324
325         info->handle = NULL;
326 }
327
328 void
329 mono_threads_platform_describe (MonoThreadInfo *info, GString *text)
330 {
331         int i;
332
333         g_string_append_printf (text, "thread handle %p state : ", info->handle);
334
335         mono_thread_info_describe_interrupt_token (info, text);
336
337         g_string_append_printf (text, ", owns (");
338         for (i = 0; i < info->owned_mutexes->len; i++)
339                 g_string_append_printf (text, i > 0 ? ", %p" : "%p", g_ptr_array_index (info->owned_mutexes, i));
340         g_string_append_printf (text, ")");
341 }
342
343 void
344 mono_threads_platform_own_mutex (MonoThreadInfo *info, gpointer mutex_handle)
345 {
346         mono_w32handle_ref (mutex_handle);
347
348         g_ptr_array_add (info->owned_mutexes, mutex_handle);
349 }
350
351 void
352 mono_threads_platform_disown_mutex (MonoThreadInfo *info, gpointer mutex_handle)
353 {
354         mono_w32handle_unref (mutex_handle);
355
356         g_ptr_array_remove (info->owned_mutexes, mutex_handle);
357 }
358
359 static const gchar* thread_typename (void)
360 {
361         return "Thread";
362 }
363
364 static gsize thread_typesize (void)
365 {
366         return 0;
367 }
368
369 static MonoW32HandleOps thread_ops = {
370         NULL,                           /* close */
371         NULL,                           /* signal */
372         NULL,                           /* own */
373         NULL,                           /* is_owned */
374         NULL,                           /* special_wait */
375         NULL,                           /* prewait */
376         NULL,                           /* details */
377         thread_typename,        /* typename */
378         thread_typesize,        /* typesize */
379 };
380
381 void
382 mono_threads_platform_init (void)
383 {
384         mono_w32handle_register_ops (MONO_W32HANDLE_THREAD, &thread_ops);
385
386         mono_w32handle_register_capabilities (MONO_W32HANDLE_THREAD, MONO_W32HANDLE_CAP_WAIT);
387 }
388
389 #endif /* defined(_POSIX_VERSION) || defined(__native_client__) */
390
391 #if defined(USE_POSIX_BACKEND)
392
393 gboolean
394 mono_threads_suspend_begin_async_suspend (MonoThreadInfo *info, gboolean interrupt_kernel)
395 {
396         int sig = interrupt_kernel ? mono_threads_posix_get_abort_signal () :  mono_threads_posix_get_suspend_signal ();
397
398         if (!mono_threads_pthread_kill (info, sig)) {
399                 mono_threads_add_to_pending_operation_set (info);
400                 return TRUE;
401         }
402         return FALSE;
403 }
404
405 gboolean
406 mono_threads_suspend_check_suspend_result (MonoThreadInfo *info)
407 {
408         return info->suspend_can_continue;
409 }
410
411 /*
412 This begins async resume. This function must do the following:
413
414 - Install an async target if one was requested.
415 - Notify the target to resume.
416 */
417 gboolean
418 mono_threads_suspend_begin_async_resume (MonoThreadInfo *info)
419 {
420         mono_threads_add_to_pending_operation_set (info);
421         return mono_threads_pthread_kill (info, mono_threads_posix_get_restart_signal ()) == 0;
422 }
423
424 void
425 mono_threads_suspend_register (MonoThreadInfo *info)
426 {
427 #if defined (PLATFORM_ANDROID)
428         info->native_handle = gettid ();
429 #endif
430 }
431
432 void
433 mono_threads_suspend_free (MonoThreadInfo *info)
434 {
435 }
436
437 void
438 mono_threads_suspend_init (void)
439 {
440         mono_threads_posix_init_signals (MONO_THREADS_POSIX_INIT_SIGNALS_SUSPEND_RESTART);
441 }
442
443 #endif /* defined(USE_POSIX_BACKEND) */