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