]> git.sesse.net Git - vlc/blob - src/misc/threads.c
Win32: use the destructor function for TLS (fixes #2398)
[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 #ifndef NDEBUG
98 /*****************************************************************************
99  * vlc_thread_fatal: Report an error from the threading layer
100  *****************************************************************************
101  * This is mostly meant for debugging.
102  *****************************************************************************/
103 static void
104 vlc_thread_fatal (const char *action, int error,
105                   const char *function, const char *file, unsigned line)
106 {
107     fprintf (stderr, "LibVLC fatal error %s (%d) in thread %lu ",
108              action, error, vlc_threadid ());
109     vlc_trace (function, file, line);
110
111     /* Sometimes strerror_r() crashes too, so make sure we print an error
112      * message before we invoke it */
113 #ifdef __GLIBC__
114     /* Avoid the strerror_r() prototype brain damage in glibc */
115     errno = error;
116     fprintf (stderr, " Error message: %m\n");
117 #elif !defined (WIN32)
118     char buf[1000];
119     const char *msg;
120
121     switch (strerror_r (error, buf, sizeof (buf)))
122     {
123         case 0:
124             msg = buf;
125             break;
126         case ERANGE: /* should never happen */
127             msg = "unknwon (too big to display)";
128             break;
129         default:
130             msg = "unknown (invalid error number)";
131             break;
132     }
133     fprintf (stderr, " Error message: %s\n", msg);
134 #endif
135     fflush (stderr);
136
137     abort ();
138 }
139
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, tls_mutex;
248 static struct vlc_threadvar *tls_list = NULL;
249
250 BOOL WINAPI DllMain (HINSTANCE hinstDll, DWORD fdwReason, LPVOID lpvReserved)
251 {
252     (void) hinstDll;
253     (void) lpvReserved;
254
255     switch (fdwReason)
256     {
257         case DLL_PROCESS_ATTACH:
258             vlc_mutex_init (&super_mutex);
259             vlc_mutex_init (&tls_mutex);
260             vlc_threadvar_create (&cancel_key, free);
261             break;
262
263         case DLL_PROCESS_DETACH:
264             vlc_threadvar_delete( &cancel_key );
265             assert (tls_list == NULL);
266             vlc_mutex_destroy (&tls_mutex);
267             vlc_mutex_destroy (&super_mutex);
268             break;
269     }
270     return TRUE;
271 }
272 #endif
273
274 #if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
275 /* This is not prototyped under glibc, though it exists. */
276 int pthread_mutexattr_setkind_np( pthread_mutexattr_t *attr, int kind );
277 #endif
278
279 /*****************************************************************************
280  * vlc_mutex_init: initialize a mutex
281  *****************************************************************************/
282 int vlc_mutex_init( vlc_mutex_t *p_mutex )
283 {
284 #if defined( LIBVLC_USE_PTHREAD )
285     pthread_mutexattr_t attr;
286     int                 i_result;
287
288     pthread_mutexattr_init( &attr );
289
290 # ifndef NDEBUG
291     /* Create error-checking mutex to detect problems more easily. */
292 #  if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
293     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_ERRORCHECK_NP );
294 #  else
295     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_ERRORCHECK );
296 #  endif
297 # endif
298     i_result = pthread_mutex_init( p_mutex, &attr );
299     pthread_mutexattr_destroy( &attr );
300     return i_result;
301
302 #elif defined( WIN32 )
303     /* This creates a recursive mutex. This is OK as fast mutexes have
304      * no defined behavior in case of recursive locking. */
305     InitializeCriticalSection (&p_mutex->mutex);
306     p_mutex->initialized = 1;
307     return 0;
308
309 #endif
310 }
311
312 /*****************************************************************************
313  * vlc_mutex_init: initialize a recursive mutex (Do not use)
314  *****************************************************************************/
315 int vlc_mutex_init_recursive( vlc_mutex_t *p_mutex )
316 {
317 #if defined( LIBVLC_USE_PTHREAD )
318     pthread_mutexattr_t attr;
319     int                 i_result;
320
321     pthread_mutexattr_init( &attr );
322 #  if defined (__GLIBC__) && (__GLIBC_MINOR__ < 6)
323     pthread_mutexattr_setkind_np( &attr, PTHREAD_MUTEX_RECURSIVE_NP );
324 #  else
325     pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
326 #  endif
327     i_result = pthread_mutex_init( p_mutex, &attr );
328     pthread_mutexattr_destroy( &attr );
329     return( i_result );
330
331 #elif defined( WIN32 )
332     InitializeCriticalSection( &p_mutex->mutex );
333     p_mutex->initialized = 1;
334     return 0;
335
336 #endif
337 }
338
339
340 /**
341  * Destroys a mutex. The mutex must not be locked.
342  *
343  * @param p_mutex mutex to destroy
344  * @return always succeeds
345  */
346 void vlc_mutex_destroy (vlc_mutex_t *p_mutex)
347 {
348 #if defined( LIBVLC_USE_PTHREAD )
349     int val = pthread_mutex_destroy( p_mutex );
350     VLC_THREAD_ASSERT ("destroying mutex");
351
352 #elif defined( WIN32 )
353     assert (InterlockedExchange (&p_mutex->initialized, -1) == 1);
354     DeleteCriticalSection (&p_mutex->mutex);
355
356 #endif
357 }
358
359 /**
360  * Acquires a mutex. If needed, waits for any other thread to release it.
361  * Beware of deadlocks when locking multiple mutexes at the same time,
362  * or when using mutexes from callbacks.
363  * This function is not a cancellation-point.
364  *
365  * @param p_mutex mutex initialized with vlc_mutex_init() or
366  *                vlc_mutex_init_recursive()
367  */
368 void vlc_mutex_lock (vlc_mutex_t *p_mutex)
369 {
370 #if defined(LIBVLC_USE_PTHREAD)
371     int val = pthread_mutex_lock( p_mutex );
372     VLC_THREAD_ASSERT ("locking mutex");
373
374 #elif defined( WIN32 )
375     if (InterlockedCompareExchange (&p_mutex->initialized, 0, 0) == 0)
376     { /* ^^ We could also lock super_mutex all the time... sluggish */
377         assert (p_mutex != &super_mutex); /* this one cannot be static */
378
379         vlc_mutex_lock (&super_mutex);
380         if (InterlockedCompareExchange (&p_mutex->initialized, 0, 0) == 0)
381             vlc_mutex_init (p_mutex);
382         /* FIXME: destroy the mutex some time... */
383         vlc_mutex_unlock (&super_mutex);
384     }
385     assert (InterlockedExchange (&p_mutex->initialized, 1) == 1);
386     EnterCriticalSection (&p_mutex->mutex);
387
388 #endif
389 }
390
391 /**
392  * Acquires a mutex if and only if it is not currently held by another thread.
393  * This function never sleeps and can be used in delay-critical code paths.
394  * This function is not a cancellation-point.
395  *
396  * <b>Beware</b>: If this function fails, then the mutex is held... by another
397  * thread. The calling thread must deal with the error appropriately. That
398  * typically implies postponing the operations that would have required the
399  * mutex. If the thread cannot defer those operations, then it must use
400  * vlc_mutex_lock(). If in doubt, use vlc_mutex_lock() instead.
401  *
402  * @param p_mutex mutex initialized with vlc_mutex_init() or
403  *                vlc_mutex_init_recursive()
404  * @return 0 if the mutex could be acquired, an error code otherwise.
405  */
406 int vlc_mutex_trylock (vlc_mutex_t *p_mutex)
407 {
408 #if defined(LIBVLC_USE_PTHREAD)
409     int val = pthread_mutex_trylock( p_mutex );
410
411     if (val != EBUSY)
412         VLC_THREAD_ASSERT ("locking mutex");
413     return val;
414
415 #elif defined( WIN32 )
416     if (InterlockedCompareExchange (&p_mutex->initialized, 0, 0) == 0)
417     { /* ^^ We could also lock super_mutex all the time... sluggish */
418         assert (p_mutex != &super_mutex); /* this one cannot be static */
419
420         vlc_mutex_lock (&super_mutex);
421         if (InterlockedCompareExchange (&p_mutex->initialized, 0, 0) == 0)
422             vlc_mutex_init (p_mutex);
423         /* FIXME: destroy the mutex some time... */
424         vlc_mutex_unlock (&super_mutex);
425     }
426     assert (InterlockedExchange (&p_mutex->initialized, 1) == 1);
427     return TryEnterCriticalSection (&p_mutex->mutex) ? 0 : EBUSY;
428
429 #endif
430 }
431
432 /**
433  * Releases a mutex (or crashes if the mutex is not locked by the caller).
434  * @param p_mutex mutex locked with vlc_mutex_lock().
435  */
436 void vlc_mutex_unlock (vlc_mutex_t *p_mutex)
437 {
438 #if defined(LIBVLC_USE_PTHREAD)
439     int val = pthread_mutex_unlock( p_mutex );
440     VLC_THREAD_ASSERT ("unlocking mutex");
441
442 #elif defined( WIN32 )
443     assert (InterlockedExchange (&p_mutex->initialized, 1) == 1);
444     LeaveCriticalSection (&p_mutex->mutex);
445
446 #endif
447 }
448
449 /*****************************************************************************
450  * vlc_cond_init: initialize a condition variable
451  *****************************************************************************/
452 int vlc_cond_init( vlc_cond_t *p_condvar )
453 {
454 #if defined( LIBVLC_USE_PTHREAD )
455     pthread_condattr_t attr;
456     int ret;
457
458     ret = pthread_condattr_init (&attr);
459     if (ret)
460         return ret;
461
462 # if !defined (_POSIX_CLOCK_SELECTION)
463    /* Fairly outdated POSIX support (that was defined in 2001) */
464 #  define _POSIX_CLOCK_SELECTION (-1)
465 # endif
466 # if (_POSIX_CLOCK_SELECTION >= 0)
467     /* NOTE: This must be the same clock as the one in mtime.c */
468     pthread_condattr_setclock (&attr, CLOCK_MONOTONIC);
469 # endif
470
471     ret = pthread_cond_init (p_condvar, &attr);
472     pthread_condattr_destroy (&attr);
473     return ret;
474
475 #elif defined( WIN32 )
476     /* Create a manual-reset event (manual reset is needed for broadcast). */
477     *p_condvar = CreateEvent( NULL, TRUE, FALSE, NULL );
478     return *p_condvar ? 0 : ENOMEM;
479
480 #endif
481 }
482
483 /**
484  * Destroys a condition variable. No threads shall be waiting or signaling the
485  * condition.
486  * @param p_condvar condition variable to destroy
487  */
488 void vlc_cond_destroy (vlc_cond_t *p_condvar)
489 {
490 #if defined( LIBVLC_USE_PTHREAD )
491     int val = pthread_cond_destroy( p_condvar );
492     VLC_THREAD_ASSERT ("destroying condition");
493
494 #elif defined( WIN32 )
495     CloseHandle( *p_condvar );
496
497 #endif
498 }
499
500 /**
501  * Wakes up one thread waiting on a condition variable, if any.
502  * @param p_condvar condition variable
503  */
504 void vlc_cond_signal (vlc_cond_t *p_condvar)
505 {
506 #if defined(LIBVLC_USE_PTHREAD)
507     int val = pthread_cond_signal( p_condvar );
508     VLC_THREAD_ASSERT ("signaling condition variable");
509
510 #elif defined( WIN32 )
511     /* NOTE: This will cause a broadcast, that is wrong.
512      * This will also wake up the next waiting thread if no thread are yet
513      * waiting, which is also wrong. However both of these issues are allowed
514      * by the provision for spurious wakeups. Better have too many wakeups
515      * than too few (= deadlocks). */
516     SetEvent (*p_condvar);
517
518 #endif
519 }
520
521 /**
522  * Wakes up all threads (if any) waiting on a condition variable.
523  * @param p_cond condition variable
524  */
525 void vlc_cond_broadcast (vlc_cond_t *p_condvar)
526 {
527 #if defined (LIBVLC_USE_PTHREAD)
528     pthread_cond_broadcast (p_condvar);
529
530 #elif defined (WIN32)
531     SetEvent (*p_condvar);
532
533 #endif
534 }
535
536 /**
537  * Waits for a condition variable. The calling thread will be suspended until
538  * another thread calls vlc_cond_signal() or vlc_cond_broadcast() on the same
539  * condition variable, the thread is cancelled with vlc_cancel(), or the
540  * system causes a "spurious" unsolicited wake-up.
541  *
542  * A mutex is needed to wait on a condition variable. It must <b>not</b> be
543  * a recursive mutex. Although it is possible to use the same mutex for
544  * multiple condition, it is not valid to use different mutexes for the same
545  * condition variable at the same time from different threads.
546  *
547  * In case of thread cancellation, the mutex is always locked before
548  * cancellation proceeds.
549  *
550  * The canonical way to use a condition variable to wait for event foobar is:
551  @code
552    vlc_mutex_lock (&lock);
553    mutex_cleanup_push (&lock); // release the mutex in case of cancellation
554
555    while (!foobar)
556        vlc_cond_wait (&wait, &lock);
557
558    --- foobar is now true, do something about it here --
559
560    vlc_cleanup_run (); // release the mutex
561   @endcode
562  *
563  * @param p_condvar condition variable to wait on
564  * @param p_mutex mutex which is unlocked while waiting,
565  *                then locked again when waking up.
566  * @param deadline <b>absolute</b> timeout
567  *
568  * @return 0 if the condition was signaled, an error code in case of timeout.
569  */
570 void vlc_cond_wait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex)
571 {
572 #if defined(LIBVLC_USE_PTHREAD)
573     int val = pthread_cond_wait( p_condvar, p_mutex );
574     VLC_THREAD_ASSERT ("waiting on condition");
575
576 #elif defined( WIN32 )
577     DWORD result;
578
579     do
580     {
581         vlc_testcancel ();
582         LeaveCriticalSection (&p_mutex->mutex);
583         result = WaitForSingleObjectEx (*p_condvar, INFINITE, TRUE);
584         EnterCriticalSection (&p_mutex->mutex);
585     }
586     while (result == WAIT_IO_COMPLETION);
587
588     ResetEvent (*p_condvar);
589
590 #endif
591 }
592
593 /**
594  * Waits for a condition variable up to a certain date.
595  * This works like vlc_cond_wait(), except for the additional timeout.
596  *
597  * @param p_condvar condition variable to wait on
598  * @param p_mutex mutex which is unlocked while waiting,
599  *                then locked again when waking up.
600  * @param deadline <b>absolute</b> timeout
601  *
602  * @return 0 if the condition was signaled, an error code in case of timeout.
603  */
604 int vlc_cond_timedwait (vlc_cond_t *p_condvar, vlc_mutex_t *p_mutex,
605                         mtime_t deadline)
606 {
607 #if defined(LIBVLC_USE_PTHREAD)
608 #ifdef __APPLE__
609     /* mdate() is mac_absolute_time on osx, which we must convert to do
610      * the same base than gettimeofday() on which pthread_cond_timedwait
611      * counts on. */
612     mtime_t oldbase = mdate();
613     struct timeval tv;
614     gettimeofday(&tv, NULL);
615     mtime_t newbase = (mtime_t)tv.tv_sec * 1000000 + (mtime_t) tv.tv_usec;
616     deadline = deadline - oldbase + newbase;
617 #endif
618     lldiv_t d = lldiv( deadline, CLOCK_FREQ );
619     struct timespec ts = { d.quot, d.rem * (1000000000 / CLOCK_FREQ) };
620
621     int val = pthread_cond_timedwait (p_condvar, p_mutex, &ts);
622     if (val != ETIMEDOUT)
623         VLC_THREAD_ASSERT ("timed-waiting on condition");
624     return val;
625
626 #elif defined( WIN32 )
627     DWORD result;
628
629     do
630     {
631         vlc_testcancel ();
632
633         mtime_t total = (deadline - mdate ())/1000;
634         if( total < 0 )
635             total = 0;
636
637         DWORD delay = (total > 0x7fffffff) ? 0x7fffffff : total;
638         LeaveCriticalSection (&p_mutex->mutex);
639         result = WaitForSingleObjectEx (*p_condvar, delay, TRUE);
640         EnterCriticalSection (&p_mutex->mutex);
641     }
642     while (result == WAIT_IO_COMPLETION);
643
644     ResetEvent (*p_condvar);
645
646     return (result == WAIT_OBJECT_0) ? 0 : ETIMEDOUT;
647
648 #endif
649 }
650
651
652 #if defined (LIBVLC_USE_PTHREAD)
653 #elif defined (WIN32)
654 struct vlc_threadvar
655 {
656     DWORD handle;
657     void (*cleanup) (void *);
658     struct vlc_threadvar *prev, *next;
659 };
660
661 static void vlc_threadvar_cleanup (void)
662 {
663     struct vlc_threadvar *p;
664
665     vlc_mutex_lock (&tls_mutex);
666     for (p = tls_list; p != NULL; p = p->next)
667     {
668         void *value = TlsGetValue (p->handle);
669         if (value)
670             p->cleanup (value);
671     }
672     vlc_mutex_unlock (&tls_mutex);
673 }
674 #endif
675
676 /*****************************************************************************
677  * vlc_tls_create: create a thread-local variable
678  *****************************************************************************/
679 int vlc_threadvar_create( vlc_threadvar_t *p_tls, void (*destr) (void *) )
680 {
681 #if defined( LIBVLC_USE_PTHREAD )
682     return pthread_key_create( p_tls, destr );
683
684 #elif defined( WIN32 )
685     struct vlc_threadvar *tls = malloc (sizeof (*tls));
686     if (tls == NULL)
687        return ENOMEM;
688
689     tls->handle = TlsAlloc();
690     if (tls->handle == TLS_OUT_OF_INDEXES)
691     {
692         free (tls);
693         return EAGAIN;
694     }
695     tls->cleanup = destr;
696     tls->prev = NULL;
697     vlc_mutex_lock (&tls_mutex);
698     tls->next = tls_list;
699     if (tls_list)
700         tls_list->prev = tls;
701     tls_list = tls;
702     vlc_mutex_unlock (&tls_mutex);
703     *p_tls = tls;
704     return 0;
705
706 #else
707 # error Unimplemented!
708 #endif
709 }
710
711 void vlc_threadvar_delete (vlc_threadvar_t *p_tls)
712 {
713 #if defined( LIBVLC_USE_PTHREAD )
714     pthread_key_delete (*p_tls);
715
716 #elif defined( WIN32 )
717     struct vlc_threadvar *tls = *p_tls;
718
719     TlsFree (tls->handle);
720     vlc_mutex_lock (&tls_mutex);
721     if (tls->prev)
722         tls->prev->next = tls->next;
723     if (tls->next)
724         tls->next->prev = tls->prev;
725     vlc_mutex_unlock (&tls_mutex);
726     free (tls);
727
728 #else
729 # error Unimplemented!
730 #endif
731 }
732
733 /**
734  * Sets a thread-local variable.
735  * @param key thread-local variable key (created with vlc_threadvar_create())
736  * @param value new value for the variable for the calling thread
737  * @return 0 on success, a system error code otherwise.
738  */
739 int vlc_threadvar_set (vlc_threadvar_t key, void *value)
740 {
741 #if defined(LIBVLC_USE_PTHREAD)
742     return pthread_setspecific (key, value);
743 #elif defined( UNDER_CE ) || defined( WIN32 )
744     return TlsSetValue (key->handle, value) ? ENOMEM : 0;
745 #else
746 # error Unimplemented!
747 #endif
748 }
749
750 /**
751  * Gets the value of a thread-local variable for the calling thread.
752  * This function cannot fail.
753  * @return the value associated with the given variable for the calling
754  * or NULL if there is no value.
755  */
756 void *vlc_threadvar_get (vlc_threadvar_t key)
757 {
758 #if defined(LIBVLC_USE_PTHREAD)
759     return pthread_getspecific (key);
760 #elif defined( UNDER_CE ) || defined( WIN32 )
761     return TlsGetValue (key->handle);
762 #else
763 # error Unimplemented!
764 #endif
765 }
766
767 #if defined (LIBVLC_USE_PTHREAD)
768 #elif defined (WIN32)
769 static unsigned __stdcall vlc_entry (void *data)
770 {
771     vlc_cancel_t cancel_data = VLC_CANCEL_INIT;
772     vlc_thread_t self = data;
773 #ifdef UNDER_CE
774     cancel_data.cancel_event = self->cancel_event;
775 #endif
776
777     vlc_threadvar_set (cancel_key, &cancel_data);
778     self->data = self->entry (self->data);
779     vlc_threadvar_cleanup ();
780     return 0;
781 }
782 #endif
783
784 /**
785  * Creates and starts new thread.
786  *
787  * @param p_handle [OUT] pointer to write the handle of the created thread to
788  * @param entry entry point for the thread
789  * @param data data parameter given to the entry point
790  * @param priority thread priority value
791  * @return 0 on success, a standard error code on error.
792  */
793 int vlc_clone (vlc_thread_t *p_handle, void * (*entry) (void *), void *data,
794                int priority)
795 {
796     int ret;
797
798 #if defined( LIBVLC_USE_PTHREAD )
799     pthread_attr_t attr;
800     pthread_attr_init (&attr);
801
802     /* Block the signals that signals interface plugin handles.
803      * If the LibVLC caller wants to handle some signals by itself, it should
804      * block these before whenever invoking LibVLC. And it must obviously not
805      * start the VLC signals interface plugin.
806      *
807      * LibVLC will normally ignore any interruption caused by an asynchronous
808      * signal during a system call. But there may well be some buggy cases
809      * where it fails to handle EINTR (bug reports welcome). Some underlying
810      * libraries might also not handle EINTR properly.
811      */
812     sigset_t oldset;
813     {
814         sigset_t set;
815         sigemptyset (&set);
816         sigdelset (&set, SIGHUP);
817         sigaddset (&set, SIGINT);
818         sigaddset (&set, SIGQUIT);
819         sigaddset (&set, SIGTERM);
820
821         sigaddset (&set, SIGPIPE); /* We don't want this one, really! */
822         pthread_sigmask (SIG_BLOCK, &set, &oldset);
823     }
824     {
825         struct sched_param sp = { .sched_priority = priority, };
826         int policy;
827
828         if (sp.sched_priority <= 0)
829             sp.sched_priority += sched_get_priority_max (policy = SCHED_OTHER);
830         else
831             sp.sched_priority += sched_get_priority_min (policy = SCHED_RR);
832
833         pthread_attr_setschedpolicy (&attr, policy);
834         pthread_attr_setschedparam (&attr, &sp);
835     }
836
837     /* The thread stack size.
838      * The lower the value, the less address space per thread, the highest
839      * maximum simultaneous threads per process. Too low values will cause
840      * stack overflows and weird crashes. Set with caution. Also keep in mind
841      * that 64-bits platforms consume more stack than 32-bits one.
842      *
843      * Thanks to on-demand paging, thread stack size only affects address space
844      * consumption. In terms of memory, threads only use what they need
845      * (rounded up to the page boundary).
846      *
847      * For example, on Linux i386, the default is 2 mega-bytes, which supports
848      * about 320 threads per processes. */
849 #define VLC_STACKSIZE (128 * sizeof (void *) * 1024)
850
851 #ifdef VLC_STACKSIZE
852     ret = pthread_attr_setstacksize (&attr, VLC_STACKSIZE);
853     assert (ret == 0); /* fails iif VLC_STACKSIZE is invalid */
854 #endif
855
856     ret = pthread_create (p_handle, &attr, entry, data);
857     pthread_sigmask (SIG_SETMASK, &oldset, NULL);
858     pthread_attr_destroy (&attr);
859
860 #elif defined( WIN32 ) || defined( UNDER_CE )
861     /* When using the MSVCRT C library you have to use the _beginthreadex
862      * function instead of CreateThread, otherwise you'll end up with
863      * memory leaks and the signal functions not working (see Microsoft
864      * Knowledge Base, article 104641) */
865     HANDLE hThread;
866     vlc_thread_t th = malloc (sizeof (*th));
867
868     if (th == NULL)
869         return ENOMEM;
870
871     th->data = data;
872     th->entry = entry;
873 #if defined( UNDER_CE )
874     th->cancel_event = CreateEvent (NULL, FALSE, FALSE, NULL);
875     if (th->cancel_event == NULL)
876     {
877         free(th);
878         return errno;
879     }
880     hThread = CreateThread (NULL, 128*1024, vlc_entry, th, CREATE_SUSPENDED, NULL);
881 #else
882     hThread = (HANDLE)(uintptr_t)
883         _beginthreadex (NULL, 0, vlc_entry, th, CREATE_SUSPENDED, NULL);
884 #endif
885
886     if (hThread)
887     {
888 #ifndef UNDER_CE
889         /* Thread closes the handle when exiting, duplicate it here
890          * to be on the safe side when joining. */
891         if (!DuplicateHandle (GetCurrentProcess (), hThread,
892                               GetCurrentProcess (), &th->handle, 0, FALSE,
893                               DUPLICATE_SAME_ACCESS))
894         {
895             CloseHandle (hThread);
896             free (th);
897             return ENOMEM;
898         }
899 #else
900         th->handle = hThread;
901 #endif
902
903         ResumeThread (hThread);
904         if (priority)
905             SetThreadPriority (hThread, priority);
906
907         ret = 0;
908         *p_handle = th;
909     }
910     else
911     {
912         ret = errno;
913         free (th);
914     }
915
916 #endif
917     return ret;
918 }
919
920 #if defined (WIN32)
921 /* APC procedure for thread cancellation */
922 static void CALLBACK vlc_cancel_self (ULONG_PTR dummy)
923 {
924     (void)dummy;
925     vlc_control_cancel (VLC_DO_CANCEL);
926 }
927 #endif
928
929 /**
930  * Marks a thread as cancelled. Next time the target thread reaches a
931  * cancellation point (while not having disabled cancellation), it will
932  * run its cancellation cleanup handler, the thread variable destructors, and
933  * terminate. vlc_join() must be used afterward regardless of a thread being
934  * cancelled or not.
935  */
936 void vlc_cancel (vlc_thread_t thread_id)
937 {
938 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
939     pthread_cancel (thread_id);
940 #elif defined (UNDER_CE)
941     SetEvent (thread_id->cancel_event);
942 #elif defined (WIN32)
943     QueueUserAPC (vlc_cancel_self, thread_id->handle, 0);
944 #else
945 #   warning vlc_cancel is not implemented!
946 #endif
947 }
948
949 /**
950  * Waits for a thread to complete (if needed), and destroys it.
951  * This is a cancellation point; in case of cancellation, the join does _not_
952  * occur.
953  *
954  * @param handle thread handle
955  * @param p_result [OUT] pointer to write the thread return value or NULL
956  * @return 0 on success, a standard error code otherwise.
957  */
958 void vlc_join (vlc_thread_t handle, void **result)
959 {
960 #if defined( LIBVLC_USE_PTHREAD )
961     int val = pthread_join (handle, result);
962     VLC_THREAD_ASSERT ("joining thread");
963
964 #elif defined( UNDER_CE ) || defined( WIN32 )
965     do
966         vlc_testcancel ();
967     while (WaitForSingleObjectEx (handle->handle, INFINITE, TRUE)
968                                                         == WAIT_IO_COMPLETION);
969
970     CloseHandle (handle->handle);
971     if (result)
972         *result = handle->data;
973 #if defined( UNDER_CE )
974     CloseHandle (handle->cancel_event);
975 #endif
976     free (handle);
977
978 #endif
979 }
980
981 /**
982  * Save the current cancellation state (enabled or disabled), then disable
983  * cancellation for the calling thread.
984  * This function must be called before entering a piece of code that is not
985  * cancellation-safe, unless it can be proven that the calling thread will not
986  * be cancelled.
987  * @return Previous cancellation state (opaque value for vlc_restorecancel()).
988  */
989 int vlc_savecancel (void)
990 {
991     int state;
992
993 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
994     int val = pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &state);
995     VLC_THREAD_ASSERT ("saving cancellation");
996
997 #else
998     vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
999     if (nfo == NULL)
1000         return false; /* Main thread - cannot be cancelled anyway */
1001
1002      state = nfo->killable;
1003      nfo->killable = false;
1004
1005 #endif
1006     return state;
1007 }
1008
1009 /**
1010  * Restore the cancellation state for the calling thread.
1011  * @param state previous state as returned by vlc_savecancel().
1012  * @return Nothing, always succeeds.
1013  */
1014 void vlc_restorecancel (int state)
1015 {
1016 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
1017 # ifndef NDEBUG
1018     int oldstate, val;
1019
1020     val = pthread_setcancelstate (state, &oldstate);
1021     /* This should fail if an invalid value for given for state */
1022     VLC_THREAD_ASSERT ("restoring cancellation");
1023
1024     if (oldstate != PTHREAD_CANCEL_DISABLE)
1025          vlc_thread_fatal ("restoring cancellation while not disabled", EINVAL,
1026                            __func__, __FILE__, __LINE__);
1027 # else
1028     pthread_setcancelstate (state, NULL);
1029 # endif
1030
1031 #else
1032     vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
1033     assert (state == false || state == true);
1034
1035     if (nfo == NULL)
1036         return; /* Main thread - cannot be cancelled anyway */
1037
1038     assert (!nfo->killable);
1039     nfo->killable = state != 0;
1040
1041 #endif
1042 }
1043
1044 /**
1045  * Issues an explicit deferred cancellation point.
1046  * This has no effect if thread cancellation is disabled.
1047  * This can be called when there is a rather slow non-sleeping operation.
1048  * This is also used to force a cancellation point in a function that would
1049  * otherwise "not always" be a one (block_FifoGet() is an example).
1050  */
1051 void vlc_testcancel (void)
1052 {
1053 #if defined (LIBVLC_USE_PTHREAD_CANCEL)
1054     pthread_testcancel ();
1055
1056 #else
1057     vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
1058     if (nfo == NULL)
1059         return; /* Main thread - cannot be cancelled anyway */
1060
1061     if (nfo->killable && nfo->killed)
1062     {
1063         for (vlc_cleanup_t *p = nfo->cleaners; p != NULL; p = p->next)
1064              p->proc (p->data);
1065 # if defined (LIBVLC_USE_PTHREAD)
1066         pthread_exit (PTHREAD_CANCELLED);
1067 # elif defined (UNDER_CE)
1068         vlc_threadvar_cleanup ();
1069         ExitThread(0);
1070 # elif defined (WIN32)
1071         vlc_threadvar_cleanup ();
1072         _endthread ();
1073 # else
1074 #  error Not implemented!
1075 # endif
1076     }
1077 #endif
1078 }
1079
1080
1081 struct vlc_thread_boot
1082 {
1083     void * (*entry) (vlc_object_t *);
1084     vlc_object_t *object;
1085 };
1086
1087 static void *thread_entry (void *data)
1088 {
1089     vlc_object_t *obj = ((struct vlc_thread_boot *)data)->object;
1090     void *(*func) (vlc_object_t *) = ((struct vlc_thread_boot *)data)->entry;
1091
1092     free (data);
1093     msg_Dbg (obj, "thread started");
1094     func (obj);
1095     msg_Dbg (obj, "thread ended");
1096
1097     return NULL;
1098 }
1099
1100 #undef vlc_thread_create
1101 /*****************************************************************************
1102  * vlc_thread_create: create a thread
1103  *****************************************************************************
1104  * Note that i_priority is only taken into account on platforms supporting
1105  * userland real-time priority threads.
1106  *****************************************************************************/
1107 int vlc_thread_create( vlc_object_t *p_this, const char * psz_file, int i_line,
1108                        const char *psz_name, void *(*func) ( vlc_object_t * ),
1109                        int i_priority )
1110 {
1111     int i_ret;
1112     vlc_object_internals_t *p_priv = vlc_internals( p_this );
1113
1114     struct vlc_thread_boot *boot = malloc (sizeof (*boot));
1115     if (boot == NULL)
1116         return errno;
1117     boot->entry = func;
1118     boot->object = p_this;
1119
1120     /* Make sure we don't re-create a thread if the object has already one */
1121     assert( !p_priv->b_thread );
1122
1123 #if defined( LIBVLC_USE_PTHREAD )
1124 #ifndef __APPLE__
1125     if( config_GetInt( p_this, "rt-priority" ) > 0 )
1126 #endif
1127     {
1128         /* Hack to avoid error msg */
1129         if( config_GetType( p_this, "rt-offset" ) )
1130             i_priority += config_GetInt( p_this, "rt-offset" );
1131     }
1132 #endif
1133
1134     p_priv->b_thread = true;
1135     i_ret = vlc_clone( &p_priv->thread_id, thread_entry, boot, i_priority );
1136     if( i_ret == 0 )
1137         msg_Dbg( p_this, "thread (%s) created at priority %d (%s:%d)",
1138                  psz_name, i_priority, psz_file, i_line );
1139     else
1140     {
1141         p_priv->b_thread = false;
1142         errno = i_ret;
1143         msg_Err( p_this, "%s thread could not be created at %s:%d (%m)",
1144                          psz_name, psz_file, i_line );
1145     }
1146
1147     return i_ret;
1148 }
1149
1150 /*****************************************************************************
1151  * vlc_thread_set_priority: set the priority of the current thread when we
1152  * couldn't set it in vlc_thread_create (for instance for the main thread)
1153  *****************************************************************************/
1154 int __vlc_thread_set_priority( vlc_object_t *p_this, const char * psz_file,
1155                                int i_line, int i_priority )
1156 {
1157     vlc_object_internals_t *p_priv = vlc_internals( p_this );
1158
1159     if( !p_priv->b_thread )
1160     {
1161         msg_Err( p_this, "couldn't set priority of non-existent thread" );
1162         return ESRCH;
1163     }
1164
1165 #if defined( LIBVLC_USE_PTHREAD )
1166 # ifndef __APPLE__
1167     if( config_GetInt( p_this, "rt-priority" ) > 0 )
1168 # endif
1169     {
1170         int i_error, i_policy;
1171         struct sched_param param;
1172
1173         memset( &param, 0, sizeof(struct sched_param) );
1174         if( config_GetType( p_this, "rt-offset" ) )
1175             i_priority += config_GetInt( p_this, "rt-offset" );
1176         if( i_priority <= 0 )
1177         {
1178             param.sched_priority = (-1) * i_priority;
1179             i_policy = SCHED_OTHER;
1180         }
1181         else
1182         {
1183             param.sched_priority = i_priority;
1184             i_policy = SCHED_RR;
1185         }
1186         if( (i_error = pthread_setschedparam( p_priv->thread_id,
1187                                               i_policy, &param )) )
1188         {
1189             errno = i_error;
1190             msg_Warn( p_this, "couldn't set thread priority (%s:%d): %m",
1191                       psz_file, i_line );
1192             i_priority = 0;
1193         }
1194     }
1195
1196 #elif defined( WIN32 ) || defined( UNDER_CE )
1197     VLC_UNUSED( psz_file); VLC_UNUSED( i_line );
1198
1199     if( !SetThreadPriority(p_priv->thread_id->handle, i_priority) )
1200     {
1201         msg_Warn( p_this, "couldn't set a faster priority" );
1202         return 1;
1203     }
1204
1205 #endif
1206
1207     return 0;
1208 }
1209
1210 /*****************************************************************************
1211  * vlc_thread_join: wait until a thread exits, inner version
1212  *****************************************************************************/
1213 void __vlc_thread_join( vlc_object_t *p_this )
1214 {
1215     vlc_object_internals_t *p_priv = vlc_internals( p_this );
1216
1217 #if defined( LIBVLC_USE_PTHREAD )
1218     vlc_join (p_priv->thread_id, NULL);
1219
1220 #elif defined( UNDER_CE ) || defined( WIN32 )
1221     HANDLE hThread;
1222     FILETIME create_ft, exit_ft, kernel_ft, user_ft;
1223     int64_t real_time, kernel_time, user_time;
1224
1225 #ifndef UNDER_CE
1226     if( ! DuplicateHandle(GetCurrentProcess(),
1227             p_priv->thread_id->handle,
1228             GetCurrentProcess(),
1229             &hThread,
1230             0,
1231             FALSE,
1232             DUPLICATE_SAME_ACCESS) )
1233     {
1234         p_priv->b_thread = false;
1235         return; /* We have a problem! */
1236     }
1237 #else
1238     hThread = p_priv->thread_id->handle;
1239 #endif
1240
1241     vlc_join( p_priv->thread_id, NULL );
1242
1243     if( GetThreadTimes( hThread, &create_ft, &exit_ft, &kernel_ft, &user_ft ) )
1244     {
1245         real_time =
1246           ((((int64_t)exit_ft.dwHighDateTime)<<32)| exit_ft.dwLowDateTime) -
1247           ((((int64_t)create_ft.dwHighDateTime)<<32)| create_ft.dwLowDateTime);
1248         real_time /= 10;
1249
1250         kernel_time =
1251           ((((int64_t)kernel_ft.dwHighDateTime)<<32)|
1252            kernel_ft.dwLowDateTime) / 10;
1253
1254         user_time =
1255           ((((int64_t)user_ft.dwHighDateTime)<<32)|
1256            user_ft.dwLowDateTime) / 10;
1257
1258         msg_Dbg( p_this, "thread times: "
1259                  "real %"PRId64"m%fs, kernel %"PRId64"m%fs, user %"PRId64"m%fs",
1260                  real_time/60/1000000,
1261                  (double)((real_time%(60*1000000))/1000000.0),
1262                  kernel_time/60/1000000,
1263                  (double)((kernel_time%(60*1000000))/1000000.0),
1264                  user_time/60/1000000,
1265                  (double)((user_time%(60*1000000))/1000000.0) );
1266     }
1267     CloseHandle( hThread );
1268
1269 #else
1270     vlc_join( p_priv->thread_id, NULL );
1271
1272 #endif
1273
1274     p_priv->b_thread = false;
1275 }
1276
1277 void vlc_thread_cancel (vlc_object_t *obj)
1278 {
1279     vlc_object_internals_t *priv = vlc_internals (obj);
1280
1281     if (priv->b_thread)
1282         vlc_cancel (priv->thread_id);
1283 }
1284
1285 void vlc_control_cancel (int cmd, ...)
1286 {
1287     /* NOTE: This function only modifies thread-specific data, so there is no
1288      * need to lock anything. */
1289 #ifdef LIBVLC_USE_PTHREAD_CANCEL
1290     (void) cmd;
1291     assert (0);
1292 #else
1293     va_list ap;
1294
1295     vlc_cancel_t *nfo = vlc_threadvar_get (cancel_key);
1296     if (nfo == NULL)
1297     {
1298 #ifdef WIN32
1299         /* Main thread - cannot be cancelled anyway */
1300         return;
1301 #else
1302         nfo = malloc (sizeof (*nfo));
1303         if (nfo == NULL)
1304             return; /* Uho! Expect problems! */
1305         *nfo = VLC_CANCEL_INIT;
1306         vlc_threadvar_set (cancel_key, nfo);
1307 #endif
1308     }
1309
1310     va_start (ap, cmd);
1311     switch (cmd)
1312     {
1313         case VLC_DO_CANCEL:
1314             nfo->killed = true;
1315             break;
1316
1317         case VLC_CLEANUP_PUSH:
1318         {
1319             /* cleaner is a pointer to the caller stack, no need to allocate
1320              * and copy anything. As a nice side effect, this cannot fail. */
1321             vlc_cleanup_t *cleaner = va_arg (ap, vlc_cleanup_t *);
1322             cleaner->next = nfo->cleaners;
1323             nfo->cleaners = cleaner;
1324             break;
1325         }
1326
1327         case VLC_CLEANUP_POP:
1328         {
1329             nfo->cleaners = nfo->cleaners->next;
1330             break;
1331         }
1332     }
1333     va_end (ap);
1334 #endif
1335 }