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