Merge pull request #3505 from ntherning/fix-resource-lookup-in-ResourceReaderTest...
[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/utils/w32handle.h>
22
23 #include <errno.h>
24
25 #if defined(PLATFORM_ANDROID) && !defined(TARGET_ARM64) && !defined(TARGET_AMD64)
26 #define USE_TKILL_ON_ANDROID 1
27 #endif
28
29 #ifdef USE_TKILL_ON_ANDROID
30 extern int tkill (pid_t tid, int signal);
31 #endif
32
33 #if defined(_POSIX_VERSION) || defined(__native_client__)
34
35 #include <pthread.h>
36
37 #include <sys/resource.h>
38
39 #if defined(__native_client__)
40 void nacl_shutdown_gc_thread(void);
41 #endif
42
43 typedef struct {
44         pthread_t id;
45         GPtrArray *owned_mutexes;
46         gint32 priority;
47 } MonoW32HandleThread;
48
49 static gpointer
50 thread_handle_create (void)
51 {
52         MonoW32HandleThread thread_data;
53         gpointer thread_handle;
54
55         thread_data.id = pthread_self ();
56         thread_data.owned_mutexes = g_ptr_array_new ();
57         thread_data.priority = MONO_THREAD_PRIORITY_NORMAL;
58
59         thread_handle = mono_w32handle_new (MONO_W32HANDLE_THREAD, (gpointer) &thread_data);
60         if (thread_handle == INVALID_HANDLE_VALUE)
61                 return NULL;
62
63         /* We need to keep the handle alive, as long as the corresponding managed
64          * thread object is alive. The handle is going to be unref when calling
65          * the finalizer on the MonoThreadInternal object */
66         mono_w32handle_ref (thread_handle);
67
68         return thread_handle;
69 }
70
71 static int
72 win32_priority_to_posix_priority (MonoThreadPriority priority, int policy)
73 {
74         g_assert (priority >= MONO_THREAD_PRIORITY_LOWEST);
75         g_assert (priority <= MONO_THREAD_PRIORITY_HIGHEST);
76
77 /* Necessary to get valid priority range */
78 #ifdef _POSIX_PRIORITY_SCHEDULING
79         int max, min;
80
81         min = sched_get_priority_min (policy);
82         max = sched_get_priority_max (policy);
83
84         /* Partition priority range linearly (cross-multiply) */
85         if (max > 0 && min >= 0 && max > min)
86                 return (int)((double) priority * (max - min) / (MONO_THREAD_PRIORITY_HIGHEST - MONO_THREAD_PRIORITY_LOWEST));
87 #endif
88
89         switch (policy) {
90         case SCHED_FIFO:
91         case SCHED_RR:
92                 return 50;
93 #ifdef SCHED_BATCH
94         case SCHED_BATCH:
95 #endif
96         case SCHED_OTHER:
97                 return 0;
98         default:
99                 return -1;
100         }
101 }
102
103 void
104 mono_threads_platform_register (MonoThreadInfo *info)
105 {
106         g_assert (!info->handle);
107         info->handle = thread_handle_create ();
108 }
109
110 int
111 mono_threads_platform_create_thread (MonoThreadStart thread_fn, gpointer thread_data, gsize stack_size, MonoNativeThreadId *out_tid)
112 {
113         pthread_attr_t attr;
114         pthread_t thread;
115         gint res;
116
117         res = pthread_attr_init (&attr);
118         g_assert (!res);
119
120 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
121         if (stack_size == 0) {
122 #if HAVE_VALGRIND_MEMCHECK_H
123                 if (RUNNING_ON_VALGRIND)
124                         stack_size = 1 << 20;
125                 else
126                         stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
127 #else
128                 stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
129 #endif
130         }
131
132 #ifdef PTHREAD_STACK_MIN
133         if (stack_size < PTHREAD_STACK_MIN)
134                 stack_size = PTHREAD_STACK_MIN;
135 #endif
136
137         res = pthread_attr_setstacksize (&attr, stack_size);
138         g_assert (!res);
139 #endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */
140
141         /* Actually start the thread */
142         res = mono_gc_pthread_create (&thread, &attr, (gpointer (*)(gpointer)) thread_fn, thread_data);
143         if (res)
144                 return -1;
145
146         if (out_tid)
147                 *out_tid = thread;
148
149         return 0;
150 }
151
152 gboolean
153 mono_threads_platform_yield (void)
154 {
155         return sched_yield () == 0;
156 }
157
158 void
159 mono_threads_platform_exit (int exit_code)
160 {
161 #if defined(__native_client__)
162         nacl_shutdown_gc_thread();
163 #endif
164
165         mono_thread_info_detach ();
166
167         pthread_exit (NULL);
168 }
169
170 void
171 mono_threads_platform_unregister (MonoThreadInfo *info)
172 {
173         mono_threads_platform_set_exited (info);
174 }
175
176 int
177 mono_threads_get_max_stack_size (void)
178 {
179         struct rlimit lim;
180
181         /* If getrlimit fails, we don't enforce any limits. */
182         if (getrlimit (RLIMIT_STACK, &lim))
183                 return INT_MAX;
184         /* rlim_t is an unsigned long long on 64bits OSX but we want an int response. */
185         if (lim.rlim_max > (rlim_t)INT_MAX)
186                 return INT_MAX;
187         return (int)lim.rlim_max;
188 }
189
190 HANDLE
191 mono_threads_platform_open_thread_handle (HANDLE handle, MonoNativeThreadId tid)
192 {
193         mono_w32handle_ref (handle);
194
195         return handle;
196 }
197
198 void
199 mono_threads_platform_close_thread_handle (HANDLE handle)
200 {
201         mono_w32handle_unref (handle);
202 }
203
204 int
205 mono_threads_pthread_kill (MonoThreadInfo *info, int signum)
206 {
207         THREADS_SUSPEND_DEBUG ("sending signal %d to %p[%p]\n", signum, info, mono_thread_info_get_tid (info));
208 #ifdef USE_TKILL_ON_ANDROID
209         int result, old_errno = errno;
210         result = tkill (info->native_handle, signum);
211         if (result < 0) {
212                 result = errno;
213                 errno = old_errno;
214         }
215         return result;
216 #elif defined(__native_client__)
217         /* Workaround pthread_kill abort() in NaCl glibc. */
218         return 0;
219 #elif !defined(HAVE_PTHREAD_KILL)
220         g_error ("pthread_kill() is not supported by this platform");
221 #else
222         return pthread_kill (mono_thread_info_get_tid (info), signum);
223 #endif
224 }
225
226 MonoNativeThreadId
227 mono_native_thread_id_get (void)
228 {
229         return pthread_self ();
230 }
231
232 gboolean
233 mono_native_thread_id_equals (MonoNativeThreadId id1, MonoNativeThreadId id2)
234 {
235         return pthread_equal (id1, id2);
236 }
237
238 /*
239  * mono_native_thread_create:
240  *
241  *   Low level thread creation function without any GC wrappers.
242  */
243 gboolean
244 mono_native_thread_create (MonoNativeThreadId *tid, gpointer func, gpointer arg)
245 {
246         return pthread_create (tid, NULL, (void *(*)(void *)) func, arg) == 0;
247 }
248
249 void
250 mono_native_thread_set_name (MonoNativeThreadId tid, const char *name)
251 {
252 #ifdef __MACH__
253         /*
254          * We can't set the thread name for other threads, but we can at least make
255          * it work for threads that try to change their own name.
256          */
257         if (tid != mono_native_thread_id_get ())
258                 return;
259
260         if (!name) {
261                 pthread_setname_np ("");
262         } else {
263                 char n [63];
264
265                 strncpy (n, name, 63);
266                 n [62] = '\0';
267                 pthread_setname_np (n);
268         }
269 #elif defined (__NetBSD__)
270         if (!name) {
271                 pthread_setname_np (tid, "%s", (void*)"");
272         } else {
273                 char n [PTHREAD_MAX_NAMELEN_NP];
274
275                 strncpy (n, name, PTHREAD_MAX_NAMELEN_NP);
276                 n [PTHREAD_MAX_NAMELEN_NP - 1] = '\0';
277                 pthread_setname_np (tid, "%s", (void*)n);
278         }
279 #elif defined (HAVE_PTHREAD_SETNAME_NP)
280         if (!name) {
281                 pthread_setname_np (tid, "");
282         } else {
283                 char n [16];
284
285                 strncpy (n, name, 16);
286                 n [15] = '\0';
287                 pthread_setname_np (tid, n);
288         }
289 #endif
290 }
291
292 void
293 mono_threads_platform_set_exited (MonoThreadInfo *info)
294 {
295         MonoW32HandleThread *thread_data;
296         gpointer mutex_handle;
297         int i, thr_ret;
298         pid_t pid;
299         pthread_t tid;
300
301         g_assert (info->handle);
302
303         if (mono_w32handle_issignalled (info->handle) || mono_w32handle_get_type (info->handle) == MONO_W32HANDLE_UNUSED) {
304                 /* We must have already deliberately finished
305                  * with this thread, so don't do any more now */
306                 return;
307         }
308
309         if (!mono_w32handle_lookup (info->handle, MONO_W32HANDLE_THREAD, (gpointer*) &thread_data))
310                 g_error ("unknown thread handle %p", info->handle);
311
312         pid = wapi_getpid ();
313         tid = pthread_self ();
314
315         for (i = 0; i < thread_data->owned_mutexes->len; i++) {
316                 mutex_handle = g_ptr_array_index (thread_data->owned_mutexes, i);
317                 wapi_mutex_abandon (mutex_handle, pid, tid);
318                 mono_thread_info_disown_mutex (info, mutex_handle);
319         }
320
321         g_ptr_array_free (thread_data->owned_mutexes, TRUE);
322
323         thr_ret = mono_w32handle_lock_handle (info->handle);
324         g_assert (thr_ret == 0);
325
326         mono_w32handle_set_signal_state (info->handle, TRUE, TRUE);
327
328         thr_ret = mono_w32handle_unlock_handle (info->handle);
329         g_assert (thr_ret == 0);
330
331         /* The thread is no longer active, so unref it */
332         mono_w32handle_unref (info->handle);
333
334         info->handle = NULL;
335 }
336
337 void
338 mono_threads_platform_describe (MonoThreadInfo *info, GString *text)
339 {
340         MonoW32HandleThread *thread_data;
341         int i;
342
343         g_assert (info->handle);
344
345         if (!mono_w32handle_lookup (info->handle, MONO_W32HANDLE_THREAD, (gpointer*) &thread_data))
346                 g_error ("unknown thread handle %p", info->handle);
347
348         g_string_append_printf (text, "thread handle %p state : ", info->handle);
349
350         mono_thread_info_describe_interrupt_token (info, text);
351
352         g_string_append_printf (text, ", owns (");
353         for (i = 0; i < thread_data->owned_mutexes->len; i++)
354                 g_string_append_printf (text, i > 0 ? ", %p" : "%p", g_ptr_array_index (thread_data->owned_mutexes, i));
355         g_string_append_printf (text, ")");
356 }
357
358 void
359 mono_threads_platform_own_mutex (MonoThreadInfo *info, gpointer mutex_handle)
360 {
361         MonoW32HandleThread *thread_data;
362
363         g_assert (info->handle);
364
365         if (!mono_w32handle_lookup (info->handle, MONO_W32HANDLE_THREAD, (gpointer*) &thread_data))
366                 g_error ("unknown thread handle %p", info->handle);
367
368         mono_w32handle_ref (mutex_handle);
369
370         g_ptr_array_add (thread_data->owned_mutexes, mutex_handle);
371 }
372
373 void
374 mono_threads_platform_disown_mutex (MonoThreadInfo *info, gpointer mutex_handle)
375 {
376         MonoW32HandleThread *thread_data;
377
378         g_assert (info->handle);
379
380         if (!mono_w32handle_lookup (info->handle, MONO_W32HANDLE_THREAD, (gpointer*) &thread_data))
381                 g_error ("unknown thread handle %p", info->handle);
382
383         mono_w32handle_unref (mutex_handle);
384
385         g_ptr_array_remove (thread_data->owned_mutexes, mutex_handle);
386 }
387
388 MonoThreadPriority
389 mono_threads_platform_get_priority (MonoThreadInfo *info)
390 {
391         MonoW32HandleThread *thread_data;
392
393         g_assert (info->handle);
394
395         if (!mono_w32handle_lookup (info->handle, MONO_W32HANDLE_THREAD, (gpointer *)&thread_data))
396                 return MONO_THREAD_PRIORITY_NORMAL;
397
398         return thread_data->priority;
399 }
400
401 gboolean
402 mono_threads_platform_set_priority (MonoThreadInfo *info, MonoThreadPriority priority)
403 {
404         MonoW32HandleThread *thread_data;
405         int policy, posix_priority;
406         struct sched_param param;
407
408         g_assert (info->handle);
409
410         if (!mono_w32handle_lookup (info->handle, MONO_W32HANDLE_THREAD, (gpointer*) &thread_data))
411                 return FALSE;
412
413         switch (pthread_getschedparam (thread_data->id, &policy, &param)) {
414         case 0:
415                 break;
416         case ESRCH:
417                 g_warning ("pthread_getschedparam: error looking up thread id %x", (gsize)thread_data->id);
418                 return FALSE;
419         default:
420                 return FALSE;
421         }
422
423         posix_priority =  win32_priority_to_posix_priority (priority, policy);
424         if (posix_priority < 0)
425                 return FALSE;
426
427         param.sched_priority = posix_priority;
428         switch (pthread_setschedparam (thread_data->id, policy, &param)) {
429         case 0:
430                 break;
431         case ESRCH:
432                 g_warning ("%s: pthread_setschedprio: error looking up thread id %x", __func__, (gsize)thread_data->id);
433                 return FALSE;
434         case ENOTSUP:
435                 g_warning ("%s: priority %d not supported", __func__, priority);
436                 return FALSE;
437         case EPERM:
438                 g_warning ("%s: permission denied", __func__);
439                 return FALSE;
440         default:
441                 return FALSE;
442         }
443
444         thread_data->priority = priority;
445         return TRUE;
446
447 }
448
449 static void thread_details (gpointer data)
450 {
451         MonoW32HandleThread *thread = (MonoW32HandleThread*) data;
452         g_print ("id: %p, owned_mutexes: %d, priority: %d",
453                 thread->id, thread->owned_mutexes->len, thread->priority);
454 }
455
456 static const gchar* thread_typename (void)
457 {
458         return "Thread";
459 }
460
461 static gsize thread_typesize (void)
462 {
463         return sizeof (MonoW32HandleThread);
464 }
465
466 static MonoW32HandleOps thread_ops = {
467         NULL,                           /* close */
468         NULL,                           /* signal */
469         NULL,                           /* own */
470         NULL,                           /* is_owned */
471         NULL,                           /* special_wait */
472         NULL,                           /* prewait */
473         thread_details,         /* details */
474         thread_typename,        /* typename */
475         thread_typesize,        /* typesize */
476 };
477
478 void
479 mono_threads_platform_init (void)
480 {
481         mono_w32handle_register_ops (MONO_W32HANDLE_THREAD, &thread_ops);
482
483         mono_w32handle_register_capabilities (MONO_W32HANDLE_THREAD, MONO_W32HANDLE_CAP_WAIT);
484 }
485
486 #endif /* defined(_POSIX_VERSION) || defined(__native_client__) */
487
488 #if defined(USE_POSIX_BACKEND)
489
490 gboolean
491 mono_threads_suspend_begin_async_suspend (MonoThreadInfo *info, gboolean interrupt_kernel)
492 {
493         int sig = interrupt_kernel ? mono_threads_posix_get_abort_signal () :  mono_threads_posix_get_suspend_signal ();
494
495         if (!mono_threads_pthread_kill (info, sig)) {
496                 mono_threads_add_to_pending_operation_set (info);
497                 return TRUE;
498         }
499         return FALSE;
500 }
501
502 gboolean
503 mono_threads_suspend_check_suspend_result (MonoThreadInfo *info)
504 {
505         return info->suspend_can_continue;
506 }
507
508 /*
509 This begins async resume. This function must do the following:
510
511 - Install an async target if one was requested.
512 - Notify the target to resume.
513 */
514 gboolean
515 mono_threads_suspend_begin_async_resume (MonoThreadInfo *info)
516 {
517         mono_threads_add_to_pending_operation_set (info);
518         return mono_threads_pthread_kill (info, mono_threads_posix_get_restart_signal ()) == 0;
519 }
520
521 void
522 mono_threads_suspend_register (MonoThreadInfo *info)
523 {
524 #if defined (PLATFORM_ANDROID)
525         info->native_handle = gettid ();
526 #endif
527 }
528
529 void
530 mono_threads_suspend_free (MonoThreadInfo *info)
531 {
532 }
533
534 void
535 mono_threads_suspend_init (void)
536 {
537         mono_threads_posix_init_signals (MONO_THREADS_POSIX_INIT_SIGNALS_SUSPEND_RESTART);
538 }
539
540 #endif /* defined(USE_POSIX_BACKEND) */