]> git.sesse.net Git - vlc/blob - src/misc/threads.c
8875d15932857e1ad757d9e5cb02ab22822aef17
[vlc] / src / misc / threads.c
1 /*****************************************************************************
2  * threads.c : threads implementation for the VideoLAN client
3  *****************************************************************************
4  * Copyright (C) 1999-2008 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Jean-Marc Dressler <polux@via.ecp.fr>
8  *          Samuel Hocevar <sam@zoy.org>
9  *          Gildas Bazin <gbazin@netcourrier.com>
10  *          Clément Sténac
11  *          Rémi Denis-Courmont
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
26  *****************************************************************************/
27
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc_common.h>
33
34 #include "libvlc.h"
35 #include <stdarg.h>
36 #include <assert.h>
37 #ifdef HAVE_UNISTD_H
38 # include <unistd.h>
39 #endif
40 #include <signal.h>
41
42 #if defined( LIBVLC_USE_PTHREAD )
43 # include <sched.h>
44 # ifdef __linux__
45 #  include <sys/syscall.h> /* SYS_gettid */
46 # endif
47 #else
48 static vlc_threadvar_t cancel_key;
49 #endif
50
51 #ifdef HAVE_EXECINFO_H
52 # include <execinfo.h>
53 #endif
54
55 #ifdef __APPLE__
56 # include <sys/time.h> /* gettimeofday in vlc_cond_timedwait */
57 #endif
58
59 /**
60  * Print a backtrace to the standard error for debugging purpose.
61  */
62 void vlc_trace (const char *fn, const char *file, unsigned line)
63 {
64      fprintf (stderr, "at %s:%u in %s\n", file, line, fn);
65      fflush (stderr); /* needed before switch to low-level I/O */
66 #ifdef HAVE_BACKTRACE
67      void *stack[20];
68      int len = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
69      backtrace_symbols_fd (stack, len, 2);
70 #endif
71 #ifndef WIN32
72      fsync (2);
73 #endif
74 }
75
76 static inline unsigned long vlc_threadid (void)
77 {
78 #if defined (LIBVLC_USE_PTHREAD)
79 # if defined (__linux__)
80      return syscall (SYS_gettid);
81
82 # else
83      union { pthread_t th; unsigned long int i; } v = { };
84      v.th = pthread_self ();
85      return v.i;
86
87 #endif
88 #elif defined (WIN32)
89      return GetCurrentThreadId ();
90
91 #else
92      return 0;
93
94 #endif
95 }
96
97 /*****************************************************************************
98  * vlc_thread_fatal: Report an error from the threading layer
99  *****************************************************************************
100  * This is mostly meant for debugging.
101  *****************************************************************************/
102 static void
103 vlc_thread_fatal (const char *action, int error,
104                   const char *function, const char *file, unsigned line)
105 {
106     fprintf (stderr, "LibVLC fatal error %s (%d) in thread %lu ",
107              action, error, vlc_threadid ());
108     vlc_trace (function, file, line);
109
110     /* Sometimes strerror_r() crashes too, so make sure we print an error
111      * message before we invoke it */
112 #ifdef __GLIBC__
113     /* Avoid the strerror_r() prototype brain damage in glibc */
114     errno = error;
115     fprintf (stderr, " Error message: %m\n");
116 #elif !defined (WIN32)
117     char buf[1000];
118     const char *msg;
119
120     switch (strerror_r (error, buf, sizeof (buf)))
121     {
122         case 0:
123             msg = buf;
124             break;
125         case ERANGE: /* should never happen */
126             msg = "unknwon (too big to display)";
127             break;
128         default:
129             msg = "unknown (invalid error number)";
130             break;
131     }
132     fprintf (stderr, " Error message: %s\n", msg);
133 #endif
134     fflush (stderr);
135
136     abort ();
137 }
138
139 #ifndef NDEBUG
140 # define VLC_THREAD_ASSERT( action ) \
141     if (val) vlc_thread_fatal (action, val, __func__, __FILE__, __LINE__)
142 #else
143 # define VLC_THREAD_ASSERT( action ) ((void)val)
144 #endif
145
146 /**
147  * Per-thread cancellation data
148  */
149 #ifndef LIBVLC_USE_PTHREAD_CANCEL
150 typedef struct vlc_cancel_t
151 {
152     vlc_cleanup_t *cleaners;
153     bool           killable;
154     bool           killed;
155 # ifdef UNDER_CE
156     HANDLE         cancel_event;
157 # endif
158 } vlc_cancel_t;
159
160 # ifndef UNDER_CE
161 #  define VLC_CANCEL_INIT { NULL, true, false }
162 # else
163 #  define VLC_CANCEL_INIT { NULL, true, false, NULL }
164 # endif
165 #endif
166
167 #ifdef UNDER_CE
168 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy);
169
170 static DWORD vlc_cancelable_wait (DWORD count, const HANDLE *handles,
171                                   DWORD delay)
172 {
173     vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
174     if (nfo == NULL)
175     {
176         /* Main thread - cannot be cancelled anyway */
177         return WaitForMultipleObjects (count, handles, FALSE, delay);
178     }
179     HANDLE new_handles[count + 1];
180     memcpy(new_handles, handles, count * sizeof(HANDLE));
181     new_handles[count] = nfo->cancel_event;
182     DWORD result = WaitForMultipleObjects (count + 1, new_handles, FALSE,
183                                            delay);
184     if (result == WAIT_OBJECT_0 + count)
185     {
186         vlc_cancel_self (NULL);
187         return WAIT_IO_COMPLETION;
188     }
189     else
190     {
191         return result;
192     }
193 }
194
195 DWORD SleepEx (DWORD dwMilliseconds, BOOL bAlertable)
196 {
197     if (bAlertable)
198     {
199         DWORD result = vlc_cancelable_wait (0, NULL, dwMilliseconds);
200         return (result == WAIT_TIMEOUT) ? 0 : WAIT_IO_COMPLETION;
201     }
202     else
203     {
204         Sleep(dwMilliseconds);
205         return 0;
206     }
207 }
208
209 DWORD WaitForSingleObjectEx (HANDLE hHandle, DWORD dwMilliseconds,
210                              BOOL bAlertable)
211 {
212     if (bAlertable)
213     {
214         /* The MSDN documentation specifies different return codes,
215          * but in practice they are the same. We just check that it
216          * remains so. */
217 #if WAIT_ABANDONED != WAIT_ABANDONED_0
218 # error Windows headers changed, code needs to be rewritten!
219 #endif
220         return vlc_cancelable_wait (1, &hHandle, dwMilliseconds);
221     }
222     else
223     {
224         return WaitForSingleObject (hHandle, dwMilliseconds);
225     }
226 }
227
228 DWORD WaitForMultipleObjectsEx (DWORD nCount, const HANDLE *lpHandles,
229                                 BOOL bWaitAll, DWORD dwMilliseconds,
230                                 BOOL bAlertable)
231 {
232     if (bAlertable)
233     {
234         /* We do not support the bWaitAll case */
235         assert (! bWaitAll);
236         return vlc_cancelable_wait (nCount, lpHandles, dwMilliseconds);
237     }
238     else
239     {
240         return WaitForMultipleObjects (nCount, lpHandles, bWaitAll,
241                                        dwMilliseconds);
242     }
243 }
244 #endif
245
246 #ifdef WIN32
247 static vlc_mutex_t super_mutex;
248
249 BOOL WINAPI DllMain (HINSTANCE hinstDll, DWORD fdwReason, LPVOID lpvReserved)
250 {
251     (void) hinstDll;
252     (void) lpvReserved;
253
254     switch (fdwReason)
255     {
256         case DLL_PROCESS_ATTACH:
257             vlc_mutex_init (&super_mutex);
258             vlc_threadvar_create (&cancel_key, free);
259             break;
260
261         case DLL_PROCESS_DETACH:
262             vlc_threadvar_delete( &cancel_key );
263             vlc_mutex_destroy (&super_mutex);
264             break;
265     }
266     return TRUE;
267 }
268 #endif
269
270 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
271 /* This is not prototyped under glibc, though it exists. */
272 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
273 #endif
274
275 /*****************************************************************************
276  * vlc_mutex_init: initialize a mutex
277  *****************************************************************************/
278 int vlc_mutex_init( vlc_mutex_t *p_mutex )
279 {
280 #if defined( LIBVLC_USE_PTHREAD )
281     pthread_mutexattr_t attr;
282     int                 i_result;
283
284     pthread_mutexattr_init( &attr );
285
286 # ifndef NDEBUG
287     /* Create error-checking mutex to detect problems more easily. */
288 #  if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
289     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
290 #  else
291     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
292 #  endif
293 # endif
294     i_result = pthread_mutex_init( p_mutex, &attr );
295     pthread_mutexattr_destroy( &attr );
296     return i_result;
297
298 #elif defined( WIN32 )
299     /* This creates a recursive mutex. This is OK as fast mutexes have
300      * no defined behavior in case of recursive locking. */
301     InitializeCriticalSection (&p_mutex->mutex);
302     p_mutex->initialized = 1;
303     return 0;
304
305 #endif
306 }
307
308 /*****************************************************************************
309  * vlc_mutex_init: initialize a recursive mutex (Do not use)
310  *****************************************************************************/
311 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
312 {
313 #if defined( LIBVLC_USE_PTHREAD )
314     pthread_mutexattr_t attr;
315     int                 i_result;
316
317     pthread_mutexattr_init( &attr );
318 #  if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
319     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
320 #  else
321     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
322 #  endif
323     i_result = pthread_mutex_init( p_mutex, &attr );
324     pthread_mutexattr_destroy( &attr );
325     return( i_result );
326
327 #elif defined( WIN32 )
328     InitializeCriticalSection( &p_mutex->mutex );
329     p_mutex->initialized = 1;
330     return 0;
331
332 #endif
333 }
334
335
336 /**
337  * Destroys a mutex. The mutex must not be locked.
338  *
339  * @param p_mutex mutex to destroy
340  * @return always succeeds
341  */
342 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
343 {
344 #if defined( LIBVLC_USE_PTHREAD )
345     int val = pthread_mutex_destroy( p_mutex );
346     VLC_THREAD_ASSERT ("destroying mutex");
347
348 #elif defined( WIN32 )
349     assert (InterlockedExchange (&p_mutex->initialized, -1) == 1);
350     DeleteCriticalSection (&p_mutex->mutex);
351
352 #endif
353 }
354
355 /**
356  * Acquires a mutex. If needed, waits for any other thread to release it.
357  * Beware of deadlocks when locking multiple mutexes at the same time,
358  * or when using mutexes from callbacks.
359  *
360  * @param p_mutex mutex initialized with vlc_mutex_init() or
361  *                vlc_mutex_init_recursive()
362  */
363 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
364 {
365 #if defined(LIBVLC_USE_PTHREAD)
366     int val = pthread_mutex_lock( p_mutex );
367     VLC_THREAD_ASSERT ("locking mutex");
368
369 #elif defined( WIN32 )
370     if (InterlockedCompareExchange (&p_mutex->initialized, 0, 0) == 0)
371     { /* ^^ We could also lock super_mutex all the time... sluggish */
372         assert (p_mutex != &super_mutex); /* this one cannot be static */
373
374         vlc_mutex_lock (&super_mutex);
375         if (InterlockedCompareExchange (&p_mutex->initialized, 0, 0) == 0)
376             vlc_mutex_init (p_mutex);
377         /* FIXME: destroy the mutex some time... */
378         vlc_mutex_unlock (&super_mutex);
379     }
380     assert (InterlockedExchange (&p_mutex->initialized, 1) == 1);
381     EnterCriticalSection (&p_mutex->mutex);
382
383 #endif
384 }
385
386
387 /**
388  * Releases a mutex (or crashes if the mutex is not locked by the caller).
389  * @param p_mutex mutex locked with vlc_mutex_lock().
390  */
391 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
392 {
393 #if defined(LIBVLC_USE_PTHREAD)
394     int val = pthread_mutex_unlock( p_mutex );
395     VLC_THREAD_ASSERT ("unlocking mutex");
396
397 #elif defined( WIN32 )
398     assert (InterlockedExchange (&p_mutex->initialized, 1) == 1);
399     LeaveCriticalSection (&p_mutex->mutex);
400
401 #endif
402 }
403
404 /*****************************************************************************
405  * vlc_cond_init: initialize a condition variable
406  *****************************************************************************/
407 int vlc_cond_init( vlc_cond_t *p_condvar )
408 {
409 #if defined( LIBVLC_USE_PTHREAD )
410     pthread_condattr_t attr;
411     int ret;
412
413     ret = pthread_condattr_init (&attr);
414     if (ret)
415         return ret;
416
417 # if !defined (_POSIX_CLOCK_SELECTION)
418    /* Fairly outdated POSIX support (that was defined in 2001) */
419 #  define _POSIX_CLOCK_SELECTION (-1)
420 # endif
421 # if (_POSIX_CLOCK_SELECTION >= 0)
422     /* NOTE: This must be the same clock as the one in mtime.c */
423     pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
424 # endif
425
426     ret = pthread_cond_init (p_condvar, &attr);
427     pthread_condattr_destroy (&attr);
428     return ret;
429
430 #elif defined( WIN32 )
431     /* Create a manual-reset event (manual reset is needed for broadcast). */
432     *p_condvar = CreateEvent( NULL, TRUE, FALSE, NULL );
433     return *p_condvar ? 0 : ENOMEM;
434
435 #endif
436 }
437
438 /**
439  * Destroys a condition variable. No threads shall be waiting or signaling the
440  * condition.
441  * @param p_condvar condition variable to destroy
442  */
443 void vlc_cond_destroy (vlc_cond_t *p_condvar)
444 {
445 #if defined( LIBVLC_USE_PTHREAD )
446     int val = pthread_cond_destroy( p_condvar );
447     VLC_THREAD_ASSERT ("destroying condition");
448
449 #elif defined( WIN32 )
450     CloseHandle( *p_condvar );
451
452 #endif
453 }
454
455 /**
456  * Wakes up one thread waiting on a condition variable, if any.
457  * @param p_condvar condition variable
458  */
459 void vlc_cond_signal (vlc_cond_t *p_condvar)
460 {
461 #if defined(LIBVLC_USE_PTHREAD)
462     int val = pthread_cond_signal( p_condvar );
463     VLC_THREAD_ASSERT ("signaling condition variable");
464
465 #elif defined( WIN32 )
466     /* NOTE: This will cause a broadcast, that is wrong.
467      * This will also wake up the next waiting thread if no thread are yet
468      * waiting, which is also wrong. However both of these issues are allowed
469      * by the provision for spurious wakeups. Better have too many wakeups
470      * than too few (= deadlocks). */
471     SetEvent (*p_condvar);
472
473 #endif
474 }
475
476 /**
477  * Wakes up all threads (if any) waiting on a condition variable.
478  * @param p_cond condition variable
479  */
480 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
481 {
482 #if defined (LIBVLC_USE_PTHREAD)
483     pthread_cond_broadcast (p_condvar);
484
485 #elif defined (WIN32)
486     SetEvent (*p_condvar);
487
488 #endif
489 }
490
491 /**
492  * Waits for a condition variable. The calling thread will be suspended until
493  * another thread calls vlc_cond_signal() or vlc_cond_broadcast() on the same
494  * condition variable, the thread is cancelled with vlc_cancel(), or the
495  * system causes a "spurious" unsolicited wake-up.
496  *
497  * A mutex is needed to wait on a condition variable. It must <b>not</b> be
498  * a recursive mutex. Although it is possible to use the same mutex for
499  * multiple condition, it is not valid to use different mutexes for the same
500  * condition variable at the same time from different threads.
501  *
502  * In case of thread cancellation, the mutex is always locked before
503  * cancellation proceeds.
504  *
505  * The canonical way to use a condition variable to wait for event foobar is:
506  @code
507    vlc_mutex_lock (&lock);
508    mutex_cleanup_push (&lock); // release the mutex in case of cancellation
509
510    while (!foobar)
511        vlc_cond_wait (&wait, &lock);
512
513    --- foobar is now true, do something about it here --
514
515    vlc_cleanup_run (); // release the mutex
516   @endcode
517  *
518  * @param p_condvar condition variable to wait on
519  * @param p_mutex mutex which is unlocked while waiting,
520  *                then locked again when waking up.
521  * @param deadline <b>absolute</b> timeout
522  *
523  * @return 0 if the condition was signaled, an error code in case of timeout.
524  */
525 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
526 {
527 #if defined(LIBVLC_USE_PTHREAD)
528     int val = pthread_cond_wait( p_condvar, p_mutex );
529     VLC_THREAD_ASSERT ("waiting on condition");
530
531 #elif defined( WIN32 )
532     DWORD result;
533
534     do
535     {
536         vlc_testcancel ();
537         LeaveCriticalSection (&p_mutex->mutex);
538         result = WaitForSingleObjectEx (*p_condvar, INFINITE, TRUE);
539         EnterCriticalSection (&p_mutex->mutex);
540     }
541     while (result == WAIT_IO_COMPLETION);
542
543     ResetEvent (*p_condvar);
544
545 #endif
546 }
547
548 /**
549  * Waits for a condition variable up to a certain date.
550  * This works like vlc_cond_wait(), except for the additional timeout.
551  *
552  * @param p_condvar condition variable to wait on
553  * @param p_mutex mutex which is unlocked while waiting,
554  *                then locked again when waking up.
555  * @param deadline <b>absolute</b> timeout
556  *
557  * @return 0 if the condition was signaled, an error code in case of timeout.
558  */
559 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
560                         mtime_t deadline)
561 {
562 #if defined(LIBVLC_USE_PTHREAD)
563 #ifdef __APPLE__
564     /* mdate() is mac_absolute_time on osx, which we must convert to do
565      * the same base than gettimeofday() on which pthread_cond_timedwait
566      * counts on. */
567     mtime_t oldbase = mdate();
568     struct timeval tv;
569     gettimeofday(&tv, NULL);
570     mtime_t newbase = (mtime_t)tv.tv_sec * 1000000 + (mtime_t) tv.tv_usec;
571     deadline = deadline - oldbase + newbase;
572 #endif
573     lldiv_t d = lldiv( deadline, CLOCK_FREQ );
574     struct timespec ts = { d.quot, d.rem * (1000000000 / CLOCK_FREQ) };
575
576     int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
577     if (val != ETIMEDOUT)
578         VLC_THREAD_ASSERT ("timed-waiting on condition");
579     return val;
580
581 #elif defined( WIN32 )
582     DWORD result;
583
584     do
585     {
586         vlc_testcancel ();
587
588         mtime_t total = (deadline - mdate ())/1000;
589         if( total < 0 )
590             total = 0;
591
592         DWORD delay = (total > 0x7fffffff) ? 0x7fffffff : total;
593         LeaveCriticalSection (&p_mutex->mutex);
594         result = WaitForSingleObjectEx (*p_condvar, delay, TRUE);
595         EnterCriticalSection (&p_mutex->mutex);
596     }
597     while (result == WAIT_IO_COMPLETION);
598
599     ResetEvent (*p_condvar);
600
601     return (result == WAIT_OBJECT_0) ? 0 : ETIMEDOUT;
602
603 #endif
604 }
605
606 /*****************************************************************************
607  * vlc_tls_create: create a thread-local variable
608  *****************************************************************************/
609 int vlc_threadvar_create( vlc_threadvar_t *p_tls, void (*destr) (void *) )
610 {
611     int i_ret;
612
613 #if defined( LIBVLC_USE_PTHREAD )
614     i_ret =  pthread_key_create( p_tls, destr );
615 #elif defined( WIN32 )
616     /* FIXME: remember/use the destr() callback and stop leaking whatever */
617     *p_tls = TlsAlloc();
618     i_ret = (*p_tls == TLS_OUT_OF_INDEXES) ? EAGAIN : 0;
619 #else
620 # error Unimplemented!
621 #endif
622     return i_ret;
623 }
624
625 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
626 {
627 #if defined( LIBVLC_USE_PTHREAD )
628     pthread_key_delete (*p_tls);
629 #elif defined( WIN32 )
630     TlsFree (*p_tls);
631 #else
632 # error Unimplemented!
633 #endif
634 }
635
636 #if defined (LIBVLC_USE_PTHREAD)
637 #elif defined (WIN32)
638 static unsigned __stdcall vlc_entry (void *data)
639 {
640     vlc_cancel_t cancel_data = VLC_CANCEL_INIT;
641     vlc_thread_t self = data;
642 #ifdef UNDER_CE
643     cancel_data.cancel_event = self->cancel_event;
644 #endif
645
646     vlc_threadvar_set (&cancel_key, &cancel_data);
647     self->data = self->entry (self->data);
648     return 0;
649 }
650 #endif
651
652 /**
653  * Creates and starts new thread.
654  *
655  * @param p_handle [OUT] pointer to write the handle of the created thread to
656  * @param entry entry point for the thread
657  * @param data data parameter given to the entry point
658  * @param priority thread priority value
659  * @return 0 on success, a standard error code on error.
660  */
661 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
662                int priority)
663 {
664     int ret;
665
666 #if defined( LIBVLC_USE_PTHREAD )
667     pthread_attr_t attr;
668     pthread_attr_init (&attr);
669
670     /* Block the signals that signals interface plugin handles.
671      * If the LibVLC caller wants to handle some signals by itself, it should
672      * block these before whenever invoking LibVLC. And it must obviously not
673      * start the VLC signals interface plugin.
674      *
675      * LibVLC will normally ignore any interruption caused by an asynchronous
676      * signal during a system call. But there may well be some buggy cases
677      * where it fails to handle EINTR (bug reports welcome). Some underlying
678      * libraries might also not handle EINTR properly.
679      */
680     sigset_t oldset;
681     {
682         sigset_t set;
683         sigemptyset (&set);
684         sigdelset (&set, SIGHUP);
685         sigaddset (&set, SIGINT);
686         sigaddset (&set, SIGQUIT);
687         sigaddset (&set, SIGTERM);
688
689         sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
690         pthread_sigmask (SIG_BLOCK, &set, &oldset);
691     }
692     {
693         struct sched_param sp = { .sched_priority = priority, };
694         int policy;
695
696         if (sp.sched_priority <= 0)
697             sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
698         else
699             sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
700
701         pthread_attr_setschedpolicy (&attr, policy);
702         pthread_attr_setschedparam (&attr, &sp);
703     }
704
705     /* The thread stack size.
706      * The lower the value, the less address space per thread, the highest
707      * maximum simultaneous threads per process. Too low values will cause
708      * stack overflows and weird crashes. Set with caution. Also keep in mind
709      * that 64-bits platforms consume more stack than 32-bits one.
710      *
711      * Thanks to on-demand paging, thread stack size only affects address space
712      * consumption. In terms of memory, threads only use what they need
713      * (rounded up to the page boundary).
714      *
715      * For example, on Linux i386, the default is 2 mega-bytes, which supports
716      * about 320 threads per processes. */
717 #define VLC_STACKSIZE (128 * sizeof (void *) * 1024)
718
719 #ifdef VLC_STACKSIZE
720     ret = pthread_attr_setstacksize (&attr, VLC_STACKSIZE);
721     assert (ret == 0); /* fails iif VLC_STACKSIZE is invalid */
722 #endif
723
724     ret = pthread_create (p_handle, &attr, entry, data);
725     pthread_sigmask (SIG_SETMASK, &oldset, NULL);
726     pthread_attr_destroy (&attr);
727
728 #elif defined( WIN32 ) || defined( UNDER_CE )
729     /* When using the MSVCRT C library you have to use the _beginthreadex
730      * function instead of CreateThread, otherwise you'll end up with
731      * memory leaks and the signal functions not working (see Microsoft
732      * Knowledge Base, article 104641) */
733     HANDLE hThread;
734     vlc_thread_t th = malloc (sizeof (*th));
735
736     if (th == NULL)
737         return ENOMEM;
738
739     th->data = data;
740     th->entry = entry;
741 #if defined( UNDER_CE )
742     th->cancel_event = CreateEvent (NULL, FALSE, FALSE, NULL);
743     if (th->cancel_event == NULL)
744     {
745         free(th);
746         return errno;
747     }
748     hThread = CreateThread (NULL, 128*1024, vlc_entry, th, CREATE_SUSPENDED, NULL);
749 #else
750     hThread = (HANDLE)(uintptr_t)
751         _beginthreadex (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
752 #endif
753
754     if (hThread)
755     {
756 #ifndef UNDER_CE
757         /* Thread closes the handle when exiting, duplicate it here
758          * to be on the safe side when joining. */
759         if (!DuplicateHandle (GetCurrentProcess (), hThread,
760                               GetCurrentProcess (), &th->handle, 0, FALSE,
761                               DUPLICATE_SAME_ACCESS))
762         {
763             CloseHandle (hThread);
764             free (th);
765             return ENOMEM;
766         }
767 #else
768         th->handle = hThread;
769 #endif
770
771         ResumeThread (hThread);
772         if (priority)
773             SetThreadPriority (hThread, priority);
774
775         ret = 0;
776         *p_handle = th;
777     }
778     else
779     {
780         ret = errno;
781         free (th);
782     }
783
784 #endif
785     return ret;
786 }
787
788 #if defined (WIN32)
789 /* APC procedure for thread cancellation */
790 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy)
791 {
792     (void)dummy;
793     vlc_control_cancel (VLC_DO_CANCEL);
794 }
795 #endif
796
797 /**
798  * Marks a thread as cancelled. Next time the target thread reaches a
799  * cancellation point (while not having disabled cancellation), it will
800  * run its cancellation cleanup handler, the thread variable destructors, and
801  * terminate. vlc_join() must be used afterward regardless of a thread being
802  * cancelled or not.
803  */
804 void vlc_cancel (vlc_thread_t thread_id)
805 {
806 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
807     pthread_cancel (thread_id);
808 #elif defined (UNDER_CE)
809     SetEvent (thread_id->cancel_event);
810 #elif defined (WIN32)
811     QueueUserAPC (vlc_cancel_self, thread_id->handle, 0);
812 #else
813 #   warning vlc_cancel is not implemented!
814 #endif
815 }
816
817 /**
818  * Waits for a thread to complete (if needed), and destroys it.
819  * This is a cancellation point; in case of cancellation, the join does _not_
820  * occur.
821  *
822  * @param handle thread handle
823  * @param p_result [OUT] pointer to write the thread return value or NULL
824  * @return 0 on success, a standard error code otherwise.
825  */
826 void vlc_join (vlc_thread_t handle, void **result)
827 {
828 #if defined( LIBVLC_USE_PTHREAD )
829     int val = pthread_join (handle, result);
830     VLC_THREAD_ASSERT ("joining thread");
831
832 #elif defined( UNDER_CE ) || defined( WIN32 )
833     do
834         vlc_testcancel ();
835     while (WaitForSingleObjectEx (handle->handle, INFINITE, TRUE)
836                                                         == WAIT_IO_COMPLETION);
837
838     CloseHandle (handle->handle);
839     if (result)
840         *result = handle->data;
841 #if defined( UNDER_CE )
842     CloseHandle (handle->cancel_event);
843 #endif
844     free (handle);
845
846 #endif
847 }
848
849 /**
850  * Save the current cancellation state (enabled or disabled), then disable
851  * cancellation for the calling thread.
852  * This function must be called before entering a piece of code that is not
853  * cancellation-safe, unless it can be proven that the calling thread will not
854  * be cancelled.
855  * @return Previous cancellation state (opaque value for vlc_restorecancel()).
856  */
857 int vlc_savecancel (void)
858 {
859     int state;
860
861 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
862     int val = pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &state);
863     VLC_THREAD_ASSERT ("saving cancellation");
864
865 #else
866     vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
867     if (nfo == NULL)
868         return false; /* Main thread - cannot be cancelled anyway */
869
870      state = nfo->killable;
871      nfo->killable = false;
872
873 #endif
874     return state;
875 }
876
877 /**
878  * Restore the cancellation state for the calling thread.
879  * @param state previous state as returned by vlc_savecancel().
880  * @return Nothing, always succeeds.
881  */
882 void vlc_restorecancel (int state)
883 {
884 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
885 # ifndef NDEBUG
886     int oldstate, val;
887
888     val = pthread_setcancelstate (state, &oldstate);
889     /* This should fail if an invalid value for given for state */
890     VLC_THREAD_ASSERT ("restoring cancellation");
891
892     if (oldstate != PTHREAD_CANCEL_DISABLE)
893          vlc_thread_fatal ("restoring cancellation while not disabled", EINVAL,
894                            __func__, __FILE__, __LINE__);
895 # else
896     pthread_setcancelstate (state, NULL);
897 # endif
898
899 #else
900     vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
901     assert (state == false || state == true);
902
903     if (nfo == NULL)
904         return; /* Main thread - cannot be cancelled anyway */
905
906     assert (!nfo->killable);
907     nfo->killable = state != 0;
908
909 #endif
910 }
911
912 /**
913  * Issues an explicit deferred cancellation point.
914  * This has no effect if thread cancellation is disabled.
915  * This can be called when there is a rather slow non-sleeping operation.
916  * This is also used to force a cancellation point in a function that would
917  * otherwise "not always" be a one (block_FifoGet() is an example).
918  */
919 void vlc_testcancel (void)
920 {
921 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
922     pthread_testcancel ();
923
924 #else
925     vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
926     if (nfo == NULL)
927         return; /* Main thread - cannot be cancelled anyway */
928
929     if (nfo->killable && nfo->killed)
930     {
931         for (vlc_cleanup_t *p = nfo->cleaners; p != NULL; p = p->next)
932              p->proc (p->data);
933 # if defined (LIBVLC_USE_PTHREAD)
934         pthread_exit (PTHREAD_CANCELLED);
935 # elif defined (UNDER_CE)
936         ExitThread(0);
937 # elif defined (WIN32)
938         _endthread ();
939 # else
940 #  error Not implemented!
941 # endif
942     }
943 #endif
944 }
945
946
947 struct vlc_thread_boot
948 {
949     void * (*entry) (vlc_object_t *);
950     vlc_object_t *object;
951 };
952
953 static void *thread_entry (void *data)
954 {
955     vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
956     void *(*func) (vlc_object_t *) = ((struct vlc_thread_boot *)data)->entry;
957
958     free (data);
959     msg_Dbg (obj, "thread started");
960     func (obj);
961     msg_Dbg (obj, "thread ended");
962
963     return NULL;
964 }
965
966 #undef vlc_thread_create
967 /*****************************************************************************
968  * vlc_thread_create: create a thread
969  *****************************************************************************
970  * Note that i_priority is only taken into account on platforms supporting
971  * userland real-time priority threads.
972  *****************************************************************************/
973 int vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
974                        const char *psz_name, void *(*func) ( vlc_object_t * ),
975                        int i_priority )
976 {
977     int i_ret;
978     vlc_object_internals_t *p_priv = vlc_internals( p_this );
979
980     struct vlc_thread_boot *boot = malloc (sizeof (*boot));
981     if (boot == NULL)
982         return errno;
983     boot->entry = func;
984     boot->object = p_this;
985
986     /* Make sure we don't re-create a thread if the object has already one */
987     assert( !p_priv->b_thread );
988
989 #if defined( LIBVLC_USE_PTHREAD )
990 #ifndef __APPLE__
991     if( config_GetInt( p_this, "rt-priority" ) > 0 )
992 #endif
993     {
994         /* Hack to avoid error msg */
995         if( config_GetType( p_this, "rt-offset" ) )
996             i_priority += config_GetInt( p_this, "rt-offset" );
997     }
998 #endif
999
1000     p_priv->b_thread = true;
1001     i_ret = vlc_clone( &p_priv->thread_id, thread_entry, boot, i_priority );
1002     if( i_ret == 0 )
1003         msg_Dbg( p_this, "thread (%s) created at priority %d (%s:%d)",
1004                  psz_name, i_priority, psz_file, i_line );
1005     else
1006     {
1007         p_priv->b_thread = false;
1008         errno = i_ret;
1009         msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
1010                          psz_name, psz_file, i_line );
1011     }
1012
1013     return i_ret;
1014 }
1015
1016 /*****************************************************************************
1017  * vlc_thread_set_priority: set the priority of the current thread when we
1018  * couldn't set it in vlc_thread_create (for instance for the main thread)
1019  *****************************************************************************/
1020 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
1021                                int i_line, int i_priority )
1022 {
1023     vlc_object_internals_t *p_priv = vlc_internals( p_this );
1024
1025     if( !p_priv->b_thread )
1026     {
1027         msg_Err( p_this, "couldn't set priority of non-existent thread" );
1028         return ESRCH;
1029     }
1030
1031 #if defined( LIBVLC_USE_PTHREAD )
1032 # ifndef __APPLE__
1033     if( config_GetInt( p_this, "rt-priority" ) > 0 )
1034 # endif
1035     {
1036         int i_error, i_policy;
1037         struct sched_param param;
1038
1039         memset( &param, 0, sizeof(struct sched_param) );
1040         if( config_GetType( p_this, "rt-offset" ) )
1041             i_priority += config_GetInt( p_this, "rt-offset" );
1042         if( i_priority <= 0 )
1043         {
1044             param.sched_priority = (-1) * i_priority;
1045             i_policy = SCHED_OTHER;
1046         }
1047         else
1048         {
1049             param.sched_priority = i_priority;
1050             i_policy = SCHED_RR;
1051         }
1052         if( (i_error = pthread_setschedparam( p_priv->thread_id,
1053                                               i_policy, &param )) )
1054         {
1055             errno = i_error;
1056             msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
1057                       psz_file, i_line );
1058             i_priority = 0;
1059         }
1060     }
1061
1062 #elif defined( WIN32 ) || defined( UNDER_CE )
1063     VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
1064
1065     if( !SetThreadPriority(p_priv->thread_id->handle, i_priority) )
1066     {
1067         msg_Warn( p_this, "couldn't set a faster priority" );
1068         return 1;
1069     }
1070
1071 #endif
1072
1073     return 0;
1074 }
1075
1076 /*****************************************************************************
1077  * vlc_thread_join: wait until a thread exits, inner version
1078  *****************************************************************************/
1079 void __vlc_thread_join( vlc_object_t *p_this )
1080 {
1081     vlc_object_internals_t *p_priv = vlc_internals( p_this );
1082
1083 #if defined( LIBVLC_USE_PTHREAD )
1084     vlc_join (p_priv->thread_id, NULL);
1085
1086 #elif defined( UNDER_CE ) || defined( WIN32 )
1087     HANDLE hThread;
1088     FILETIME create_ft, exit_ft, kernel_ft, user_ft;
1089     int64_t real_time, kernel_time, user_time;
1090
1091 #ifndef UNDER_CE
1092     if( ! DuplicateHandle(GetCurrentProcess(),
1093             p_priv->thread_id->handle,
1094             GetCurrentProcess(),
1095             &hThread,
1096             0,
1097             FALSE,
1098             DUPLICATE_SAME_ACCESS) )
1099     {
1100         p_priv->b_thread = false;
1101         return; /* We have a problem! */
1102     }
1103 #else
1104     hThread = p_priv->thread_id->handle;
1105 #endif
1106
1107     vlc_join( p_priv->thread_id, NULL );
1108
1109     if( GetThreadTimes( hThread, &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
1110     {
1111         real_time =
1112           ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
1113           ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
1114         real_time /= 10;
1115
1116         kernel_time =
1117           ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
1118            kernel_ft.dwLowDateTime) / 10;
1119
1120         user_time =
1121           ((((int64_t)user_ft.dwHighDateTime)<<32)|
1122            user_ft.dwLowDateTime) / 10;
1123
1124         msg_Dbg( p_this, "thread times: "
1125                  "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
1126                  real_time/60/1000000,
1127                  (double)((real_time%(60*1000000))/1000000.0),
1128                  kernel_time/60/1000000,
1129                  (double)((kernel_time%(60*1000000))/1000000.0),
1130                  user_time/60/1000000,
1131                  (double)((user_time%(60*1000000))/1000000.0) );
1132     }
1133     CloseHandle( hThread );
1134
1135 #else
1136     vlc_join( p_priv->thread_id, NULL );
1137
1138 #endif
1139
1140     p_priv->b_thread = false;
1141 }
1142
1143 void vlc_thread_cancel (vlc_object_t *obj)
1144 {
1145     vlc_object_internals_t *priv = vlc_internals (obj);
1146
1147     if (priv->b_thread)
1148         vlc_cancel (priv->thread_id);
1149 }
1150
1151 void vlc_control_cancel (int cmd, ...)
1152 {
1153     /* NOTE: This function only modifies thread-specific data, so there is no
1154      * need to lock anything. */
1155 #ifdef LIBVLC_USE_PTHREAD_CANCEL
1156     (void) cmd;
1157     assert (0);
1158 #else
1159     va_list ap;
1160
1161     vlc_cancel_t *nfo = vlc_threadvar_get (&cancel_key);
1162     if (nfo == NULL)
1163     {
1164 #ifdef WIN32
1165         /* Main thread - cannot be cancelled anyway */
1166         return;
1167 #else
1168         nfo = malloc (sizeof (*nfo));
1169         if (nfo == NULL)
1170             return; /* Uho! Expect problems! */
1171         *nfo = VLC_CANCEL_INIT;
1172         vlc_threadvar_set (&cancel_key, nfo);
1173 #endif
1174     }
1175
1176     va_start (ap, cmd);
1177     switch (cmd)
1178     {
1179         case VLC_DO_CANCEL:
1180             nfo->killed = true;
1181             break;
1182
1183         case VLC_CLEANUP_PUSH:
1184         {
1185             /* cleaner is a pointer to the caller stack, no need to allocate
1186              * and copy anything. As a nice side effect, this cannot fail. */
1187             vlc_cleanup_t *cleaner = va_arg (ap, vlc_cleanup_t *);
1188             cleaner->next = nfo->cleaners;
1189             nfo->cleaners = cleaner;
1190             break;
1191         }
1192
1193         case VLC_CLEANUP_POP:
1194         {
1195             nfo->cleaners = nfo->cleaners->next;
1196             break;
1197         }
1198     }
1199     va_end (ap);
1200 #endif
1201 }