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