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