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