]> git.sesse.net Git - vlc/blob - src/misc/objects.c
951c5f9896242db4b539934330c328fce87ad3d5
[vlc] / src / misc / objects.c
1 /*****************************************************************************
2  * objects.c: vlc_object_t handling
3  *****************************************************************************
4  * Copyright (C) 2004-2008 the VideoLAN team
5  *
6  * Authors: Samuel Hocevar <sam@zoy.org>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
21  *****************************************************************************/
22
23 /**
24  * \file
25  * This file contains the functions to handle the vlc_object_t type
26  *
27  * Unless otherwise stated, functions in this file are not cancellation point.
28  * All functions in this file are safe w.r.t. deferred cancellation.
29  */
30
31
32 /*****************************************************************************
33  * Preamble
34  *****************************************************************************/
35 #ifdef HAVE_CONFIG_H
36 # include "config.h"
37 #endif
38
39 #include <vlc_common.h>
40
41 #include "../libvlc.h"
42 #include <vlc_vout.h>
43 #include <vlc_aout.h>
44 #include "audio_output/aout_internal.h"
45
46 #include <vlc_access.h>
47 #include <vlc_demux.h>
48 #include <vlc_stream.h>
49
50 #include <vlc_sout.h>
51 #include "stream_output/stream_output.h"
52
53 #include "vlc_interface.h"
54 #include "vlc_codec.h"
55 #include "vlc_filter.h"
56
57 #include "variables.h"
58 #ifndef WIN32
59 # include <unistd.h>
60 #else
61 # include <io.h>
62 # include <fcntl.h>
63 # include <errno.h> /* ENOSYS */
64 #endif
65 #include <assert.h>
66
67 /*****************************************************************************
68  * Local prototypes
69  *****************************************************************************/
70 static int  DumpCommand( vlc_object_t *, char const *,
71                          vlc_value_t, vlc_value_t, void * );
72
73 static vlc_object_t * FindObject    ( vlc_object_t *, int, int );
74 static vlc_object_t * FindObjectName( vlc_object_t *, const char *, int );
75 static void           PrintObject   ( vlc_object_t *, const char * );
76 static void           DumpStructure ( vlc_object_t *, int, char * );
77
78 static vlc_list_t   * NewList       ( int );
79 static void           ListReplace   ( vlc_list_t *, vlc_object_t *, int );
80 /*static void           ListAppend    ( vlc_list_t *, vlc_object_t * );*/
81 static int            CountChildren ( vlc_object_t *, int );
82 static void           ListChildren  ( vlc_list_t *, vlc_object_t *, int );
83
84 static void vlc_object_destroy( vlc_object_t *p_this );
85 static void vlc_object_detach_unlocked (vlc_object_t *p_this);
86
87 #ifdef LIBVLC_REFCHECK
88 static vlc_threadvar_t held_objects;
89 typedef struct held_list_t
90 {
91     struct held_list_t *next;
92     vlc_object_t *obj;
93 } held_list_t;
94 static void held_objects_destroy (void *);
95 #endif
96
97 /*****************************************************************************
98  * Local structure lock
99  *****************************************************************************/
100 static vlc_mutex_t structure_lock;
101 static unsigned    object_counter = 0;
102
103 static void close_nocancel (int fd)
104 {
105     int canc = vlc_savecancel ();
106     close (fd);
107     vlc_restorecancel (canc);
108 }
109
110 void *__vlc_custom_create( vlc_object_t *p_this, size_t i_size,
111                            int i_type, const char *psz_type )
112 {
113     vlc_object_t *p_new;
114     vlc_object_internals_t *p_priv;
115
116     /* NOTE:
117      * VLC objects are laid out as follow:
118      * - first the LibVLC-private per-object data,
119      * - then VLC_COMMON members from vlc_object_t,
120      * - finally, the type-specific data (if any).
121      *
122      * This function initializes the LibVLC and common data,
123      * and zeroes the rest.
124      */
125     p_priv = calloc( 1, sizeof( *p_priv ) + i_size );
126     if( p_priv == NULL )
127         return NULL;
128
129     assert (i_size >= sizeof (vlc_object_t));
130     p_new = (vlc_object_t *)(p_priv + 1);
131
132     p_new->i_object_type = i_type;
133     p_new->psz_object_type = psz_type;
134     p_new->psz_object_name = NULL;
135
136     p_new->b_die = false;
137     p_new->b_error = false;
138     p_new->b_dead = false;
139     p_new->b_force = false;
140
141     p_new->psz_header = NULL;
142
143     if (p_this)
144         p_new->i_flags = p_this->i_flags
145             & (OBJECT_FLAGS_NODBG|OBJECT_FLAGS_QUIET|OBJECT_FLAGS_NOINTERACT);
146
147     p_priv->p_vars = calloc( sizeof( variable_t ), 16 );
148
149     if( !p_priv->p_vars )
150     {
151         free( p_priv );
152         return NULL;
153     }
154
155     libvlc_global_data_t *p_libvlc_global;
156     if( p_this == NULL )
157     {
158         /* Only the global root object is created out of the blue */
159         p_libvlc_global = (libvlc_global_data_t *)p_new;
160         p_new->p_libvlc = NULL;
161
162         object_counter = 0; /* reset */
163         p_priv->next = p_priv->prev = p_new;
164         vlc_mutex_init( &structure_lock );
165 #ifdef LIBVLC_REFCHECK
166         /* TODO: use the destruction callback to track ref leaks */
167         vlc_threadvar_create( &held_objects, held_objects_destroy );
168 #endif
169     }
170     else
171     {
172         p_libvlc_global = vlc_global();
173         if( i_type == VLC_OBJECT_LIBVLC )
174             p_new->p_libvlc = (libvlc_int_t*)p_new;
175         else
176             p_new->p_libvlc = p_this->p_libvlc;
177     }
178
179     vlc_spin_init( &p_priv->ref_spin );
180     p_priv->i_refcount = 1;
181     p_priv->pf_destructor = NULL;
182     p_priv->b_thread = false;
183     p_new->p_parent = NULL;
184     p_priv->pp_children = NULL;
185     p_priv->i_children = 0;
186
187     p_new->p_private = NULL;
188
189     /* Initialize mutexes and condvars */
190     vlc_mutex_init( &p_priv->lock );
191     vlc_cond_init( p_new, &p_priv->wait );
192     vlc_mutex_init( &p_priv->var_lock );
193     vlc_spin_init( &p_priv->spin );
194     p_priv->pipes[0] = p_priv->pipes[1] = -1;
195
196     p_priv->next = VLC_OBJECT (p_libvlc_global);
197 #if !defined (LIBVLC_REFCHECK)
198     /* ... */
199 #elif defined (LIBVLC_USE_PTHREAD)
200     p_priv->creator_id = pthread_self ();
201 #elif defined (WIN32)
202     p_priv->creator_id = GetCurrentThreadId ();
203 #endif
204     vlc_mutex_lock( &structure_lock );
205     p_priv->prev = vlc_internals (p_libvlc_global)->prev;
206     vlc_internals (p_libvlc_global)->prev = p_new;
207     vlc_internals (p_priv->prev)->next = p_new;
208     p_new->i_object_id = object_counter++; /* fetch THEN increment */
209     vlc_mutex_unlock( &structure_lock );
210
211     if( i_type == VLC_OBJECT_LIBVLC )
212     {
213         int canc = vlc_savecancel ();
214         var_Create( p_new, "list", VLC_VAR_STRING | VLC_VAR_ISCOMMAND );
215         var_AddCallback( p_new, "list", DumpCommand, NULL );
216         var_Create( p_new, "tree", VLC_VAR_STRING | VLC_VAR_ISCOMMAND );
217         var_AddCallback( p_new, "tree", DumpCommand, NULL );
218         var_Create( p_new, "vars", VLC_VAR_STRING | VLC_VAR_ISCOMMAND );
219         var_AddCallback( p_new, "vars", DumpCommand, NULL );
220         vlc_restorecancel (canc);
221     }
222
223     return p_new;
224 }
225
226
227 /**
228  * Allocates and initializes a vlc object.
229  *
230  * @param i_type known object type (all of them are negative integer values),
231  *               or object byte size (always positive).
232  *
233  * @return the new object, or NULL on error.
234  */
235 void * __vlc_object_create( vlc_object_t *p_this, int i_type )
236 {
237     const char   * psz_type;
238     size_t         i_size;
239
240     switch( i_type )
241     {
242         case VLC_OBJECT_INTF:
243             i_size = sizeof(intf_thread_t);
244             psz_type = "interface";
245             break;
246         case VLC_OBJECT_DECODER:
247             i_size = sizeof(decoder_t);
248             psz_type = "decoder";
249             break;
250         case VLC_OBJECT_PACKETIZER:
251             i_size = sizeof(decoder_t);
252             psz_type = "packetizer";
253             break;
254         case VLC_OBJECT_ENCODER:
255             i_size = sizeof(encoder_t);
256             psz_type = "encoder";
257             break;
258         case VLC_OBJECT_AOUT:
259             i_size = sizeof(aout_instance_t);
260             psz_type = "audio output";
261             break;
262         case VLC_OBJECT_OPENGL:
263             i_size = sizeof( vout_thread_t );
264             psz_type = "opengl";
265             break;
266         case VLC_OBJECT_ANNOUNCE:
267             i_size = sizeof( announce_handler_t );
268             psz_type = "announce";
269             break;
270         default:
271             assert( i_type > 0 ); /* unknown type?! */
272             i_size = i_type;
273             i_type = VLC_OBJECT_GENERIC;
274             psz_type = "generic";
275             break;
276     }
277
278     return vlc_custom_create( p_this, i_size, i_type, psz_type );
279 }
280
281
282 /**
283  ****************************************************************************
284  * Set the destructor of a vlc object
285  *
286  * This function sets the destructor of the vlc object. It will be called
287  * when the object is destroyed when the its refcount reaches 0.
288  * (It is called by the internal function vlc_object_destroy())
289  *****************************************************************************/
290 void __vlc_object_set_destructor( vlc_object_t *p_this,
291                                   vlc_destructor_t pf_destructor )
292 {
293     vlc_object_internals_t *p_priv = vlc_internals(p_this );
294     p_priv->pf_destructor = pf_destructor;
295 }
296
297 /**
298  ****************************************************************************
299  * Destroy a vlc object (Internal)
300  *
301  * This function destroys an object that has been previously allocated with
302  * vlc_object_create. The object's refcount must be zero and it must not be
303  * attached to other objects in any way.
304  *
305  * This function must be called with cancellation disabled (currently).
306  *****************************************************************************/
307 static void vlc_object_destroy( vlc_object_t *p_this )
308 {
309     vlc_object_internals_t *p_priv = vlc_internals( p_this );
310
311     /* Objects are always detached beforehand */
312     assert( !p_this->p_parent );
313
314     /* Send a kill to the object's thread if applicable */
315     vlc_object_kill( p_this );
316
317     /* Call the custom "subclass" destructor */
318     if( p_priv->pf_destructor )
319         p_priv->pf_destructor( p_this );
320
321     /* Any thread must have been cleaned up at this point. */
322     assert( !p_priv->b_thread );
323
324     /* Destroy the associated variables, starting from the end so that
325      * no memmove calls have to be done. */
326     while( p_priv->i_vars )
327     {
328         var_Destroy( p_this, p_priv->p_vars[p_priv->i_vars - 1].psz_name );
329     }
330
331     free( p_priv->p_vars );
332     vlc_mutex_destroy( &p_priv->var_lock );
333
334     free( p_this->psz_header );
335
336     if( p_this->p_libvlc == NULL )
337     {
338 #ifndef NDEBUG
339         libvlc_global_data_t *p_global = (libvlc_global_data_t *)p_this;
340
341         assert( p_global == vlc_global() );
342         /* Test for leaks */
343         if (p_priv->next != p_this)
344         {
345             vlc_object_t *leaked = p_priv->next, *first = leaked;
346             do
347             {
348                 /* We are leaking this object */
349                 fprintf( stderr,
350                          "ERROR: leaking object (id:%i, type:%s, name:%s)\n",
351                          leaked->i_object_id, leaked->psz_object_type,
352                          leaked->psz_object_name );
353                 /* Dump libvlc object to ease debugging */
354                 vlc_object_dump( leaked );
355                 fflush(stderr);
356                 leaked = vlc_internals (leaked)->next;
357             }
358             while (leaked != first);
359
360             /* Dump global object to ease debugging */
361             vlc_object_dump( p_this );
362             /* Strongly abort, cause we want these to be fixed */
363             abort();
364         }
365 #endif
366
367         /* We are the global object ... no need to lock. */
368         vlc_mutex_destroy( &structure_lock );
369 #ifdef LIBVLC_REFCHECK
370         held_objects_destroy( vlc_threadvar_get( &held_objects ) );
371         vlc_threadvar_delete( &held_objects );
372 #endif
373     }
374
375     FREENULL( p_this->psz_object_name );
376
377 #if defined(WIN32) || defined(UNDER_CE)
378     /* if object has an associated thread, close it now */
379     if( p_priv->thread_id )
380        CloseHandle(p_priv->thread_id);
381 #endif
382
383     vlc_spin_destroy( &p_priv->ref_spin );
384     vlc_mutex_destroy( &p_priv->lock );
385     vlc_cond_destroy( &p_priv->wait );
386     vlc_spin_destroy( &p_priv->spin );
387     if( p_priv->pipes[1] != -1 )
388         close( p_priv->pipes[1] );
389     if( p_priv->pipes[0] != -1 )
390         close( p_priv->pipes[0] );
391
392     free( p_priv );
393 }
394
395
396 /** Inter-object signaling */
397
398 void __vlc_object_lock( vlc_object_t *obj )
399 {
400     vlc_mutex_lock( &(vlc_internals(obj)->lock) );
401 }
402
403 void __vlc_object_unlock( vlc_object_t *obj )
404 {
405     vlc_assert_locked( &(vlc_internals(obj)->lock) );
406     vlc_mutex_unlock( &(vlc_internals(obj)->lock) );
407 }
408
409 #ifdef WIN32
410 # include <winsock2.h>
411 # include <ws2tcpip.h>
412
413 /**
414  * select()-able pipes emulated using Winsock
415  */
416 static int pipe (int fd[2])
417 {
418     SOCKADDR_IN addr;
419     int addrlen = sizeof (addr);
420
421     SOCKET l = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP), a,
422            c = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
423     if ((l == INVALID_SOCKET) || (c == INVALID_SOCKET))
424         goto error;
425
426     memset (&addr, 0, sizeof (addr));
427     addr.sin_family = AF_INET;
428     addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
429     if (bind (l, (PSOCKADDR)&addr, sizeof (addr))
430      || getsockname (l, (PSOCKADDR)&addr, &addrlen)
431      || listen (l, 1)
432      || connect (c, (PSOCKADDR)&addr, addrlen))
433         goto error;
434
435     a = accept (l, NULL, NULL);
436     if (a == INVALID_SOCKET)
437         goto error;
438
439     closesocket (l);
440     //shutdown (a, 0);
441     //shutdown (c, 1);
442     fd[0] = c;
443     fd[1] = a;
444     return 0;
445
446 error:
447     if (l != INVALID_SOCKET)
448         closesocket (l);
449     if (c != INVALID_SOCKET)
450         closesocket (c);
451     return -1;
452 }
453
454 #undef  read
455 #define read( a, b, c )  recv (a, b, c, 0)
456 #undef  write
457 #define write( a, b, c ) send (a, b, c, 0)
458 #undef  close
459 #define close( a )       closesocket (a)
460 #endif /* WIN32 */
461
462 /**
463  * Returns the readable end of a pipe that becomes readable once termination
464  * of the object is requested (vlc_object_kill()).
465  * This can be used to wake-up out of a select() or poll() event loop, such
466  * typically when doing network I/O.
467  *
468  * Note that the pipe will remain the same for the lifetime of the object.
469  * DO NOT read the pipe nor close it yourself. Ever.
470  *
471  * @param obj object that would be "killed"
472  * @return a readable pipe descriptor, or -1 on error.
473  */
474 int __vlc_object_waitpipe( vlc_object_t *obj )
475 {
476     int pfd[2] = { -1, -1 };
477     vlc_object_internals_t *internals = vlc_internals( obj );
478     bool killed = false;
479
480     vlc_spin_lock (&internals->spin);
481     if (internals->pipes[0] == -1)
482     {
483         /* This can only ever happen if someone killed us without locking: */
484         assert (internals->pipes[1] == -1);
485         vlc_spin_unlock (&internals->spin);
486
487         if (pipe (pfd))
488             return -1;
489
490         vlc_spin_lock (&internals->spin);
491         if (internals->pipes[0] == -1)
492         {
493             internals->pipes[0] = pfd[0];
494             internals->pipes[1] = pfd[1];
495             pfd[0] = pfd[1] = -1;
496         }
497         killed = obj->b_die;
498     }
499     vlc_spin_unlock (&internals->spin);
500
501     if (killed)
502     {
503         /* Race condition: vlc_object_kill() already invoked! */
504         int fd;
505
506         vlc_spin_lock (&internals->spin);
507         fd = internals->pipes[1];
508         internals->pipes[1] = -1;
509         vlc_spin_unlock (&internals->spin);
510
511         msg_Dbg (obj, "waitpipe: object already dying");
512         if (fd != -1)
513             close (fd);
514     }
515
516     /* Race condition: two threads call pipe() - unlikely */
517     if (pfd[0] != -1)
518         close (pfd[0]);
519     if (pfd[1] != -1)
520         close (pfd[1]);
521
522     return internals->pipes[0];
523 }
524
525
526 /**
527  * Waits for the object to be signaled (using vlc_object_signal()).
528  * It is assumed that the caller has locked the object. This function will
529  * unlock the object, and lock it again before returning.
530  * If the object was signaled before the caller locked the object, it is
531  * undefined whether the signal will be lost or will wake the process.
532  *
533  * This function is a cancellation point. In case of cancellation, the object
534  * will be in locked state.
535  *
536  * @return true if the object is dying and should terminate.
537  */
538 void __vlc_object_wait( vlc_object_t *obj )
539 {
540     vlc_object_internals_t *priv = vlc_internals( obj );
541     vlc_assert_locked( &priv->lock);
542     vlc_cond_wait( &priv->wait, &priv->lock );
543 }
544
545
546 /**
547  * Waits for the object to be signaled (using vlc_object_signal()), or for
548  * a timer to expire. It is asserted that the caller holds the object lock.
549  *
550  * This function is a cancellation point. In case of cancellation, the object
551  * will be in locked state.
552  *
553  * @return 0 if the object was signaled before the timer expiration, or
554  * ETIMEDOUT if the timer expired without any signal.
555  */
556 int __vlc_object_timedwait( vlc_object_t *obj, mtime_t deadline )
557 {
558     vlc_object_internals_t *priv = vlc_internals( obj );
559     vlc_assert_locked( &priv->lock);
560     return vlc_cond_timedwait( &priv->wait, &priv->lock, deadline );
561 }
562
563
564 /**
565  * Signals an object for which the lock is held.
566  * At least one thread currently sleeping in vlc_object_wait() or
567  * vlc_object_timedwait() will wake up, assuming that there is at least one
568  * such thread in the first place. Otherwise, it is undefined whether the
569  * signal will be lost or will wake up one or more thread later.
570  */
571 void __vlc_object_signal_unlocked( vlc_object_t *obj )
572 {
573     vlc_assert_locked (&(vlc_internals(obj)->lock));
574     vlc_cond_signal( &(vlc_internals(obj)->wait) );
575 }
576
577
578 /**
579  * Requests termination of an object.
580  * If the object is LibVLC, also request to terminate all its children.
581  */
582 void __vlc_object_kill( vlc_object_t *p_this )
583 {
584     vlc_object_internals_t *priv = vlc_internals( p_this );
585     int fd;
586
587     vlc_thread_cancel( p_this );
588     vlc_object_lock( p_this );
589     p_this->b_die = true;
590
591     vlc_spin_lock (&priv->spin);
592     fd = priv->pipes[1];
593     priv->pipes[1] = -1;
594     vlc_spin_unlock (&priv->spin);
595
596     if( fd != -1 )
597     {
598         msg_Dbg (p_this, "waitpipe: object killed");
599         close_nocancel (fd);
600     }
601
602     vlc_object_signal_unlocked( p_this );
603     /* This also serves as a memory barrier toward vlc_object_alive(): */
604     vlc_object_unlock( p_this );
605 }
606
607
608 /**
609  * Find an object given its ID.
610  *
611  * This function looks for the object whose i_object_id field is i_id.
612  * This function is slow, and often used to hide bugs. Do not use it.
613  * If you need to retain reference to an object, yield the object pointer with
614  * vlc_object_yield(), use the pointer as your reference, and call
615  * vlc_object_release() when you're done.
616  */
617 void * vlc_object_get( int i_id )
618 {
619     libvlc_global_data_t *p_libvlc_global = vlc_global();
620     vlc_object_t *obj = NULL;
621 #ifndef NDEBUG
622     vlc_object_t *caller = vlc_threadobj ();
623
624     if (caller)
625         msg_Dbg (caller, "uses deprecated vlc_object_get(%d)", i_id);
626     else
627     {
628         int canc = vlc_savecancel ();
629         fprintf (stderr, "main thread uses deprecated vlc_object_get(%d)\n",
630                  i_id);
631         vlc_restorecancel (canc);
632     }
633 #endif
634     vlc_mutex_lock( &structure_lock );
635
636     for( obj = vlc_internals (p_libvlc_global)->next;
637          obj != VLC_OBJECT (p_libvlc_global);
638          obj = vlc_internals (obj)->next )
639     {
640         if( obj->i_object_id == i_id )
641         {
642             vlc_object_yield( obj );
643             goto out;
644         }
645     }
646     obj = NULL;
647 #ifndef NDEBUG
648     if (caller)
649         msg_Warn (caller, "wants non-existing object %d", i_id);
650     else
651         fprintf (stderr, "main thread wants non-existing object %d\n", i_id);
652 #endif
653 out:
654     vlc_mutex_unlock( &structure_lock );
655     return obj;
656 }
657
658 /**
659  ****************************************************************************
660  * find a typed object and increment its refcount
661  *****************************************************************************
662  * This function recursively looks for a given object type. i_mode can be one
663  * of FIND_PARENT, FIND_CHILD or FIND_ANYWHERE.
664  *****************************************************************************/
665 void * __vlc_object_find( vlc_object_t *p_this, int i_type, int i_mode )
666 {
667     vlc_object_t *p_found;
668
669     /* If we are of the requested type ourselves, don't look further */
670     if( !(i_mode & FIND_STRICT) && p_this->i_object_type == i_type )
671     {
672         vlc_object_yield( p_this );
673         return p_this;
674     }
675
676     /* Otherwise, recursively look for the object */
677     if ((i_mode & 0x000f) == FIND_ANYWHERE)
678     {
679 #ifndef NDEBUG
680         if (i_type == VLC_OBJECT_PLAYLIST)
681             msg_Err (p_this, "using vlc_object_find(VLC_OBJECT_PLAYLIST) "
682                      "instead of pl_Yield()");
683 #endif
684         return vlc_object_find (p_this->p_libvlc, i_type,
685                                 (i_mode & ~0x000f)|FIND_CHILD);
686     }
687
688     vlc_mutex_lock( &structure_lock );
689     p_found = FindObject( p_this, i_type, i_mode );
690     vlc_mutex_unlock( &structure_lock );
691     return p_found;
692 }
693
694 /**
695  ****************************************************************************
696  * find a named object and increment its refcount
697  *****************************************************************************
698  * This function recursively looks for a given object name. i_mode can be one
699  * of FIND_PARENT, FIND_CHILD or FIND_ANYWHERE.
700  *****************************************************************************/
701 void * __vlc_object_find_name( vlc_object_t *p_this, const char *psz_name,
702                                int i_mode )
703 {
704     vlc_object_t *p_found;
705
706     /* If have the requested name ourselves, don't look further */
707     if( !(i_mode & FIND_STRICT)
708         && p_this->psz_object_name
709         && !strcmp( p_this->psz_object_name, psz_name ) )
710     {
711         vlc_object_yield( p_this );
712         return p_this;
713     }
714
715     vlc_mutex_lock( &structure_lock );
716
717     /* Otherwise, recursively look for the object */
718     if( (i_mode & 0x000f) == FIND_ANYWHERE )
719     {
720         vlc_object_t *p_root = p_this;
721
722         /* Find the root */
723         while( p_root->p_parent != NULL &&
724                p_root != VLC_OBJECT( p_this->p_libvlc ) )
725         {
726             p_root = p_root->p_parent;
727         }
728
729         p_found = FindObjectName( p_root, psz_name,
730                                  (i_mode & ~0x000f)|FIND_CHILD );
731         if( p_found == NULL && p_root != VLC_OBJECT( p_this->p_libvlc ) )
732         {
733             p_found = FindObjectName( VLC_OBJECT( p_this->p_libvlc ),
734                                       psz_name, (i_mode & ~0x000f)|FIND_CHILD );
735         }
736     }
737     else
738     {
739         p_found = FindObjectName( p_this, psz_name, i_mode );
740     }
741
742     vlc_mutex_unlock( &structure_lock );
743
744     return p_found;
745 }
746
747 /**
748  * Increment an object reference counter.
749  */
750 void __vlc_object_yield( vlc_object_t *p_this )
751 {
752     vlc_object_internals_t *internals = vlc_internals( p_this );
753
754     vlc_spin_lock( &internals->ref_spin );
755     /* Avoid obvious freed object uses */
756     assert( internals->i_refcount > 0 );
757     /* Increment the counter */
758     internals->i_refcount++;
759     vlc_spin_unlock( &internals->ref_spin );
760 #ifdef LIBVLC_REFCHECK
761     /* Update the list of referenced objects */
762     /* Using TLS, so no need to lock */
763     /* The following line may leak memory if a thread leaks objects. */
764     held_list_t *newhead = malloc (sizeof (*newhead));
765     held_list_t *oldhead = vlc_threadvar_get (&held_objects);
766     newhead->next = oldhead;
767     newhead->obj = p_this;
768     vlc_threadvar_set (&held_objects, newhead);
769 #endif
770 }
771
772 /*****************************************************************************
773  * Decrement an object refcount
774  * And destroy the object if its refcount reach zero.
775  *****************************************************************************/
776 void __vlc_object_release( vlc_object_t *p_this )
777 {
778     vlc_object_internals_t *internals = vlc_internals( p_this );
779     bool b_should_destroy;
780
781 #ifdef LIBVLC_REFCHECK
782     /* Update the list of referenced objects */
783     /* Using TLS, so no need to lock */
784     for (held_list_t *hlcur = vlc_threadvar_get (&held_objects),
785                      *hlprev = NULL;
786          hlcur != NULL;
787          hlprev = hlcur, hlcur = hlcur->next)
788     {
789         if (hlcur->obj == p_this)
790         {
791             if (hlprev == NULL)
792                 vlc_threadvar_set (&held_objects, hlcur->next);
793             else
794                 hlprev->next = hlcur->next;
795             free (hlcur);
796             break;
797         }
798     }
799     /* TODO: what if releasing without references? */
800 #endif
801
802     vlc_spin_lock( &internals->ref_spin );
803     assert( internals->i_refcount > 0 );
804
805     if( internals->i_refcount > 1 )
806     {
807         /* Fast path */
808         /* There are still other references to the object */
809         internals->i_refcount--;
810         vlc_spin_unlock( &internals->ref_spin );
811         return;
812     }
813     vlc_spin_unlock( &internals->ref_spin );
814
815     /* Slow path */
816     /* Remember that we cannot hold the spin while waiting on the mutex */
817     vlc_mutex_lock( &structure_lock );
818     /* Take the spin again. Note that another thread may have yielded the
819      * object in the (very short) mean time. */
820     vlc_spin_lock( &internals->ref_spin );
821     b_should_destroy = --internals->i_refcount == 0;
822     vlc_spin_unlock( &internals->ref_spin );
823
824     if( b_should_destroy )
825     {
826         /* Remove the object from object list
827          * so that it cannot be encountered by vlc_object_get() */
828         vlc_internals (internals->next)->prev = internals->prev;
829         vlc_internals (internals->prev)->next = internals->next;
830
831         /* Detach from parent to protect against FIND_CHILDREN */
832         vlc_object_detach_unlocked (p_this);
833         /* Detach from children to protect against FIND_PARENT */
834         for (int i = 0; i < internals->i_children; i++)
835             internals->pp_children[i]->p_parent = NULL;
836     }
837
838     vlc_mutex_unlock( &structure_lock );
839
840     if( b_should_destroy )
841     {
842         int canc;
843
844         free( internals->pp_children );
845         internals->pp_children = NULL;
846         internals->i_children = 0;
847         canc = vlc_savecancel ();
848         vlc_object_destroy( p_this );
849         vlc_restorecancel (canc);
850     }
851 }
852
853 /**
854  ****************************************************************************
855  * attach object to a parent object
856  *****************************************************************************
857  * This function sets p_this as a child of p_parent, and p_parent as a parent
858  * of p_this. This link can be undone using vlc_object_detach.
859  *****************************************************************************/
860 void __vlc_object_attach( vlc_object_t *p_this, vlc_object_t *p_parent )
861 {
862     if( !p_this ) return;
863
864     vlc_mutex_lock( &structure_lock );
865
866     /* Attach the parent to its child */
867     assert (!p_this->p_parent);
868     p_this->p_parent = p_parent;
869
870     /* Attach the child to its parent */
871     vlc_object_internals_t *priv = vlc_internals( p_parent );
872     INSERT_ELEM( priv->pp_children, priv->i_children, priv->i_children,
873                  p_this );
874
875     vlc_mutex_unlock( &structure_lock );
876 }
877
878
879 static void vlc_object_detach_unlocked (vlc_object_t *p_this)
880 {
881     vlc_assert_locked (&structure_lock);
882
883     if (p_this->p_parent == NULL)
884         return;
885
886     vlc_object_internals_t *priv = vlc_internals( p_this->p_parent );
887
888     int i_index, i;
889
890     /* Remove p_this's parent */
891     p_this->p_parent = NULL;
892
893     /* Remove all of p_parent's children which are p_this */
894     for( i_index = priv->i_children ; i_index-- ; )
895     {
896         if( priv->pp_children[i_index] == p_this )
897         {
898             priv->i_children--;
899             for( i = i_index ; i < priv->i_children ; i++ )
900                 priv->pp_children[i] = priv->pp_children[i+1];
901         }
902     }
903
904     if( priv->i_children )
905     {
906         priv->pp_children = (vlc_object_t **)realloc( priv->pp_children,
907                                priv->i_children * sizeof(vlc_object_t *) );
908     }
909     else
910     {
911         /* Special case - don't realloc() to zero to avoid leaking */
912         free( priv->pp_children );
913         priv->pp_children = NULL;
914     }
915 }
916
917
918 /**
919  ****************************************************************************
920  * detach object from its parent
921  *****************************************************************************
922  * This function removes all links between an object and its parent.
923  *****************************************************************************/
924 void __vlc_object_detach( vlc_object_t *p_this )
925 {
926     if( !p_this ) return;
927
928     vlc_mutex_lock( &structure_lock );
929     if( !p_this->p_parent )
930         msg_Err( p_this, "object is not attached" );
931     else
932         vlc_object_detach_unlocked( p_this );
933     vlc_mutex_unlock( &structure_lock );
934 }
935
936
937 /**
938  ****************************************************************************
939  * find a list typed objects and increment their refcount
940  *****************************************************************************
941  * This function recursively looks for a given object type. i_mode can be one
942  * of FIND_PARENT, FIND_CHILD or FIND_ANYWHERE.
943  *****************************************************************************/
944 vlc_list_t * __vlc_list_find( vlc_object_t *p_this, int i_type, int i_mode )
945 {
946     vlc_list_t *p_list;
947     int i_count = 0;
948
949     /* Look for the objects */
950     switch( i_mode & 0x000f )
951     {
952     case FIND_ANYWHERE:
953         /* Modules should probably not be object, and the module should perhaps
954          * not be shared across LibVLC instances. In the mean time, this ugly
955          * hack is brought to you by Courmisch. */
956         if (i_type == VLC_OBJECT_MODULE)
957             return vlc_list_find ((vlc_object_t *)vlc_global ()->p_module_bank,
958                                   i_type, FIND_CHILD);
959         return vlc_list_find (p_this->p_libvlc, i_type, FIND_CHILD);
960
961     case FIND_CHILD:
962         vlc_mutex_lock( &structure_lock );
963         i_count = CountChildren( p_this, i_type );
964         p_list = NewList( i_count );
965
966         /* Check allocation was successful */
967         if( p_list->i_count != i_count )
968         {
969             vlc_mutex_unlock( &structure_lock );
970             msg_Err( p_this, "list allocation failed!" );
971             p_list->i_count = 0;
972             break;
973         }
974
975         p_list->i_count = 0;
976         ListChildren( p_list, p_this, i_type );
977         vlc_mutex_unlock( &structure_lock );
978         break;
979
980     default:
981         msg_Err( p_this, "unimplemented!" );
982         p_list = NewList( 0 );
983         break;
984     }
985
986     return p_list;
987 }
988
989 /**
990  * Gets the list of children of an objects, and increment their reference
991  * count.
992  * @return a list (possibly empty) or NULL in case of error.
993  */
994 vlc_list_t *__vlc_list_children( vlc_object_t *obj )
995 {
996     vlc_list_t *l;
997     vlc_object_internals_t *priv = vlc_internals( obj );
998
999     vlc_mutex_lock( &structure_lock );
1000     l = NewList( priv->i_children );
1001     for (int i = 0; i < l->i_count; i++)
1002     {
1003         vlc_object_yield( priv->pp_children[i] );
1004         l->p_values[i].p_object = priv->pp_children[i];
1005     }
1006     vlc_mutex_unlock( &structure_lock );
1007     return l;
1008 }
1009
1010 /*****************************************************************************
1011  * DumpCommand: print the current vlc structure
1012  *****************************************************************************
1013  * This function prints either an ASCII tree showing the connections between
1014  * vlc objects, and additional information such as their refcount, thread ID,
1015  * etc. (command "tree"), or the same data as a simple list (command "list").
1016  *****************************************************************************/
1017 static int DumpCommand( vlc_object_t *p_this, char const *psz_cmd,
1018                         vlc_value_t oldval, vlc_value_t newval, void *p_data )
1019 {
1020     (void)oldval; (void)p_data;
1021     if( *psz_cmd == 'l' )
1022     {
1023         vlc_object_t *root = VLC_OBJECT (vlc_global ()), *cur = root;
1024
1025         vlc_mutex_lock( &structure_lock );
1026         do
1027         {
1028             PrintObject (cur, "");
1029             cur = vlc_internals (cur)->next;
1030         }
1031         while (cur != root);
1032         vlc_mutex_unlock( &structure_lock );
1033     }
1034     else
1035     {
1036         vlc_object_t *p_object = NULL;
1037
1038         if( *newval.psz_string )
1039         {
1040             char *end;
1041             int i_id = strtol( newval.psz_string, &end, 0 );
1042             if( end != newval.psz_string )
1043                 p_object = vlc_object_get( i_id );
1044             else
1045                 /* try using the object's name to find it */
1046                 p_object = vlc_object_find_name( p_this, newval.psz_string,
1047                                                  FIND_ANYWHERE );
1048
1049             if( !p_object )
1050             {
1051                 return VLC_ENOOBJ;
1052             }
1053         }
1054
1055         vlc_mutex_lock( &structure_lock );
1056
1057         if( *psz_cmd == 't' )
1058         {
1059             char psz_foo[2 * MAX_DUMPSTRUCTURE_DEPTH + 1];
1060
1061             if( !p_object )
1062                 p_object = p_this->p_libvlc ? VLC_OBJECT(p_this->p_libvlc) : p_this;
1063
1064             psz_foo[0] = '|';
1065             DumpStructure( p_object, 0, psz_foo );
1066         }
1067         else if( *psz_cmd == 'v' )
1068         {
1069             int i;
1070
1071             if( !p_object )
1072                 p_object = p_this->p_libvlc ? VLC_OBJECT(p_this->p_libvlc) : p_this;
1073
1074             PrintObject( p_object, "" );
1075
1076             if( !vlc_internals( p_object )->i_vars )
1077                 printf( " `-o No variables\n" );
1078             for( i = 0; i < vlc_internals( p_object )->i_vars; i++ )
1079             {
1080                 variable_t *p_var = vlc_internals( p_object )->p_vars + i;
1081
1082                 const char *psz_type = "unknown";
1083                 switch( p_var->i_type & VLC_VAR_TYPE )
1084                 {
1085 #define MYCASE( type, nice )                \
1086                     case VLC_VAR_ ## type:  \
1087                         psz_type = nice;    \
1088                         break;
1089                     MYCASE( VOID, "void" );
1090                     MYCASE( BOOL, "bool" );
1091                     MYCASE( INTEGER, "integer" );
1092                     MYCASE( HOTKEY, "hotkey" );
1093                     MYCASE( STRING, "string" );
1094                     MYCASE( MODULE, "module" );
1095                     MYCASE( FILE, "file" );
1096                     MYCASE( DIRECTORY, "directory" );
1097                     MYCASE( VARIABLE, "variable" );
1098                     MYCASE( FLOAT, "float" );
1099                     MYCASE( TIME, "time" );
1100                     MYCASE( ADDRESS, "address" );
1101                     MYCASE( MUTEX, "mutex" );
1102                     MYCASE( LIST, "list" );
1103 #undef MYCASE
1104                 }
1105                 printf( " %c-o \"%s\" (%s",
1106                         i + 1 == vlc_internals( p_object )->i_vars ? '`' : '|',
1107                         p_var->psz_name, psz_type );
1108                 if( p_var->psz_text )
1109                     printf( ", %s", p_var->psz_text );
1110                 printf( ")" );
1111                 if( p_var->i_type & VLC_VAR_HASCHOICE )
1112                     printf( ", has choices" );
1113                 if( p_var->i_type & VLC_VAR_ISCOMMAND )
1114                     printf( ", command" );
1115                 if( p_var->i_entries )
1116                     printf( ", %d callbacks", p_var->i_entries );
1117                 switch( p_var->i_type & 0x00f0 )
1118                 {
1119                     case VLC_VAR_VOID:
1120                     case VLC_VAR_MUTEX:
1121                         break;
1122                     case VLC_VAR_BOOL:
1123                         printf( ": %s", p_var->val.b_bool ? "true" : "false" );
1124                         break;
1125                     case VLC_VAR_INTEGER:
1126                         printf( ": %d", p_var->val.i_int );
1127                         break;
1128                     case VLC_VAR_STRING:
1129                         printf( ": \"%s\"", p_var->val.psz_string );
1130                         break;
1131                     case VLC_VAR_FLOAT:
1132                         printf( ": %f", p_var->val.f_float );
1133                         break;
1134                     case VLC_VAR_TIME:
1135                         printf( ": %"PRIi64, (int64_t)p_var->val.i_time );
1136                         break;
1137                     case VLC_VAR_ADDRESS:
1138                         printf( ": %p", p_var->val.p_address );
1139                         break;
1140                     case VLC_VAR_LIST:
1141                         printf( ": TODO" );
1142                         break;
1143                 }
1144                 printf( "\n" );
1145             }
1146         }
1147
1148         vlc_mutex_unlock( &structure_lock );
1149
1150         if( *newval.psz_string )
1151         {
1152             vlc_object_release( p_object );
1153         }
1154     }
1155
1156     return VLC_SUCCESS;
1157 }
1158
1159 /*****************************************************************************
1160  * vlc_list_release: free a list previously allocated by vlc_list_find
1161  *****************************************************************************
1162  * This function decreases the refcount of all objects in the list and
1163  * frees the list.
1164  *****************************************************************************/
1165 void vlc_list_release( vlc_list_t *p_list )
1166 {
1167     int i_index;
1168
1169     for( i_index = 0; i_index < p_list->i_count; i_index++ )
1170     {
1171         vlc_object_release( p_list->p_values[i_index].p_object );
1172     }
1173
1174     free( p_list->p_values );
1175     free( p_list );
1176 }
1177
1178 /*****************************************************************************
1179  * dump an object. (Debug function)
1180  *****************************************************************************/
1181 void __vlc_object_dump( vlc_object_t *p_this )
1182 {
1183     vlc_mutex_lock( &structure_lock );
1184     char psz_foo[2 * MAX_DUMPSTRUCTURE_DEPTH + 1];
1185     psz_foo[0] = '|';
1186     DumpStructure( p_this, 0, psz_foo );
1187     vlc_mutex_unlock( &structure_lock );
1188 }
1189
1190 /* Following functions are local */
1191
1192 static vlc_object_t * FindObject( vlc_object_t *p_this, int i_type, int i_mode )
1193 {
1194     int i;
1195     vlc_object_t *p_tmp;
1196
1197     switch( i_mode & 0x000f )
1198     {
1199     case FIND_PARENT:
1200         p_tmp = p_this->p_parent;
1201         if( p_tmp )
1202         {
1203             if( p_tmp->i_object_type == i_type )
1204             {
1205                 vlc_object_yield( p_tmp );
1206                 return p_tmp;
1207             }
1208             else
1209             {
1210                 return FindObject( p_tmp, i_type, i_mode );
1211             }
1212         }
1213         break;
1214
1215     case FIND_CHILD:
1216         for( i = vlc_internals( p_this )->i_children; i--; )
1217         {
1218             p_tmp = vlc_internals( p_this )->pp_children[i];
1219             if( p_tmp->i_object_type == i_type )
1220             {
1221                 vlc_object_yield( p_tmp );
1222                 return p_tmp;
1223             }
1224             else if( vlc_internals( p_tmp )->i_children )
1225             {
1226                 p_tmp = FindObject( p_tmp, i_type, i_mode );
1227                 if( p_tmp )
1228                 {
1229                     return p_tmp;
1230                 }
1231             }
1232         }
1233         break;
1234
1235     case FIND_ANYWHERE:
1236         /* Handled in vlc_object_find */
1237         break;
1238     }
1239
1240     return NULL;
1241 }
1242
1243 static vlc_object_t * FindObjectName( vlc_object_t *p_this,
1244                                       const char *psz_name,
1245                                       int i_mode )
1246 {
1247     int i;
1248     vlc_object_t *p_tmp;
1249
1250     switch( i_mode & 0x000f )
1251     {
1252     case FIND_PARENT:
1253         p_tmp = p_this->p_parent;
1254         if( p_tmp )
1255         {
1256             if( p_tmp->psz_object_name
1257                 && !strcmp( p_tmp->psz_object_name, psz_name ) )
1258             {
1259                 vlc_object_yield( p_tmp );
1260                 return p_tmp;
1261             }
1262             else
1263             {
1264                 return FindObjectName( p_tmp, psz_name, i_mode );
1265             }
1266         }
1267         break;
1268
1269     case FIND_CHILD:
1270         for( i = vlc_internals( p_this )->i_children; i--; )
1271         {
1272             p_tmp = vlc_internals( p_this )->pp_children[i];
1273             if( p_tmp->psz_object_name
1274                 && !strcmp( p_tmp->psz_object_name, psz_name ) )
1275             {
1276                 vlc_object_yield( p_tmp );
1277                 return p_tmp;
1278             }
1279             else if( vlc_internals( p_tmp )->i_children )
1280             {
1281                 p_tmp = FindObjectName( p_tmp, psz_name, i_mode );
1282                 if( p_tmp )
1283                 {
1284                     return p_tmp;
1285                 }
1286             }
1287         }
1288         break;
1289
1290     case FIND_ANYWHERE:
1291         /* Handled in vlc_object_find */
1292         break;
1293     }
1294
1295     return NULL;
1296 }
1297
1298
1299 static void PrintObject( vlc_object_t *p_this, const char *psz_prefix )
1300 {
1301     char psz_children[20], psz_refcount[20], psz_thread[30], psz_name[50],
1302          psz_parent[20];
1303
1304     int canc = vlc_savecancel ();
1305     memset( &psz_name, 0, sizeof(psz_name) );
1306     if( p_this->psz_object_name )
1307     {
1308         snprintf( psz_name, 49, " \"%s\"", p_this->psz_object_name );
1309         if( psz_name[48] )
1310             psz_name[48] = '\"';
1311     }
1312
1313     psz_children[0] = '\0';
1314     switch( vlc_internals( p_this )->i_children )
1315     {
1316         case 0:
1317             break;
1318         case 1:
1319             strcpy( psz_children, ", 1 child" );
1320             break;
1321         default:
1322             snprintf( psz_children, 19, ", %i children",
1323                       vlc_internals( p_this )->i_children );
1324             break;
1325     }
1326
1327     psz_refcount[0] = '\0';
1328     if( vlc_internals( p_this )->i_refcount > 0 )
1329         snprintf( psz_refcount, 19, ", refcount %u",
1330                   vlc_internals( p_this )->i_refcount );
1331
1332     psz_thread[0] = '\0';
1333     if( vlc_internals( p_this )->b_thread )
1334         snprintf( psz_thread, 29, " (thread %lu)",
1335                   (unsigned long)vlc_internals( p_this )->thread_id );
1336
1337     psz_parent[0] = '\0';
1338     if( p_this->p_parent )
1339         snprintf( psz_parent, 19, ", parent %i", p_this->p_parent->i_object_id );
1340
1341     printf( " %so %.8i %s%s%s%s%s%s\n", psz_prefix,
1342             p_this->i_object_id, p_this->psz_object_type,
1343             psz_name, psz_thread, psz_refcount, psz_children,
1344             psz_parent );
1345     vlc_restorecancel (canc);
1346 }
1347
1348 static void DumpStructure( vlc_object_t *p_this, int i_level, char *psz_foo )
1349 {
1350     int i;
1351     char i_back = psz_foo[i_level];
1352     psz_foo[i_level] = '\0';
1353
1354     PrintObject( p_this, psz_foo );
1355
1356     psz_foo[i_level] = i_back;
1357
1358     if( i_level / 2 >= MAX_DUMPSTRUCTURE_DEPTH )
1359     {
1360         msg_Warn( p_this, "structure tree is too deep" );
1361         return;
1362     }
1363
1364     for( i = 0 ; i < vlc_internals( p_this )->i_children ; i++ )
1365     {
1366         if( i_level )
1367         {
1368             psz_foo[i_level-1] = ' ';
1369
1370             if( psz_foo[i_level-2] == '`' )
1371             {
1372                 psz_foo[i_level-2] = ' ';
1373             }
1374         }
1375
1376         if( i == vlc_internals( p_this )->i_children - 1 )
1377         {
1378             psz_foo[i_level] = '`';
1379         }
1380         else
1381         {
1382             psz_foo[i_level] = '|';
1383         }
1384
1385         psz_foo[i_level+1] = '-';
1386         psz_foo[i_level+2] = '\0';
1387
1388         DumpStructure( vlc_internals( p_this )->pp_children[i], i_level + 2,
1389                        psz_foo );
1390     }
1391 }
1392
1393 static vlc_list_t * NewList( int i_count )
1394 {
1395     vlc_list_t * p_list = (vlc_list_t *)malloc( sizeof( vlc_list_t ) );
1396     if( p_list == NULL )
1397     {
1398         return NULL;
1399     }
1400
1401     p_list->i_count = i_count;
1402
1403     if( i_count == 0 )
1404     {
1405         p_list->p_values = NULL;
1406         return p_list;
1407     }
1408
1409     p_list->p_values = malloc( i_count * sizeof( vlc_value_t ) );
1410     if( p_list->p_values == NULL )
1411     {
1412         p_list->i_count = 0;
1413         return p_list;
1414     }
1415
1416     return p_list;
1417 }
1418
1419 static void ListReplace( vlc_list_t *p_list, vlc_object_t *p_object,
1420                          int i_index )
1421 {
1422     if( p_list == NULL || i_index >= p_list->i_count )
1423     {
1424         return;
1425     }
1426
1427     vlc_object_yield( p_object );
1428
1429     p_list->p_values[i_index].p_object = p_object;
1430
1431     return;
1432 }
1433
1434 /*static void ListAppend( vlc_list_t *p_list, vlc_object_t *p_object )
1435 {
1436     if( p_list == NULL )
1437     {
1438         return;
1439     }
1440
1441     p_list->p_values = realloc( p_list->p_values, (p_list->i_count + 1)
1442                                 * sizeof( vlc_value_t ) );
1443     if( p_list->p_values == NULL )
1444     {
1445         p_list->i_count = 0;
1446         return;
1447     }
1448
1449     vlc_object_yield( p_object );
1450
1451     p_list->p_values[p_list->i_count].p_object = p_object;
1452     p_list->i_count++;
1453
1454     return;
1455 }*/
1456
1457 static int CountChildren( vlc_object_t *p_this, int i_type )
1458 {
1459     vlc_object_t *p_tmp;
1460     int i, i_count = 0;
1461
1462     for( i = 0; i < vlc_internals( p_this )->i_children; i++ )
1463     {
1464         p_tmp = vlc_internals( p_this )->pp_children[i];
1465
1466         if( p_tmp->i_object_type == i_type )
1467         {
1468             i_count++;
1469         }
1470         i_count += CountChildren( p_tmp, i_type );
1471     }
1472
1473     return i_count;
1474 }
1475
1476 static void ListChildren( vlc_list_t *p_list, vlc_object_t *p_this, int i_type )
1477 {
1478     vlc_object_t *p_tmp;
1479     int i;
1480
1481     for( i = 0; i < vlc_internals( p_this )->i_children; i++ )
1482     {
1483         p_tmp = vlc_internals( p_this )->pp_children[i];
1484
1485         if( p_tmp->i_object_type == i_type )
1486             ListReplace( p_list, p_tmp, p_list->i_count++ );
1487
1488         ListChildren( p_list, p_tmp, i_type );
1489     }
1490 }
1491
1492 #ifdef LIBVLC_REFCHECK
1493 # if defined(HAVE_EXECINFO_H) && defined(HAVE_BACKTRACE)
1494 #  include <execinfo.h>
1495 # endif
1496
1497 void vlc_refcheck (vlc_object_t *obj)
1498 {
1499     static unsigned errors = 0;
1500     if (errors > 100)
1501         return;
1502
1503     /* Anyone can use the root object (though it should not exist) */
1504     if (obj == VLC_OBJECT (vlc_global ()))
1505         return;
1506
1507     /* Anyone can use its libvlc instance object */
1508     if (obj == VLC_OBJECT (obj->p_libvlc))
1509         return;
1510
1511     /* The thread that created the object holds the initial reference */
1512     vlc_object_internals_t *priv = vlc_internals (obj);
1513 #if defined (LIBVLC_USE_PTHREAD)
1514     if (pthread_equal (priv->creator_id, pthread_self ()))
1515 #elif defined WIN32
1516     if (priv->creator_id == GetCurrentThreadId ())
1517 #else
1518     if (0)
1519 #endif
1520         return;
1521
1522     /* A thread can use its own object without references! */
1523     vlc_object_t *caller = vlc_threadobj ();
1524     if (caller == obj)
1525         return;
1526 #if 0
1527     /* The calling thread is younger than the object.
1528      * Access could be valid through cross-thread synchronization;
1529      * we would need better accounting. */
1530     if (caller && (caller->i_object_id > obj->i_object_id))
1531         return;
1532 #endif
1533     int refs;
1534     vlc_spin_lock (&priv->ref_spin);
1535     refs = priv->i_refcount;
1536     vlc_spin_unlock (&priv->ref_spin);
1537
1538     for (held_list_t *hlcur = vlc_threadvar_get (&held_objects);
1539          hlcur != NULL; hlcur = hlcur->next)
1540         if (hlcur->obj == obj)
1541             return;
1542
1543     int canc = vlc_savecancel ();
1544
1545     fprintf (stderr, "The %s %s thread object is accessing...\n"
1546              "the %s %s object without references.\n",
1547              caller && caller->psz_object_name
1548                      ? caller->psz_object_name : "unnamed",
1549              caller ? caller->psz_object_type : "main",
1550              obj->psz_object_name ? obj->psz_object_name : "unnamed",
1551              obj->psz_object_type);
1552     fflush (stderr);
1553
1554 #ifdef HAVE_BACKTRACE
1555     void *stack[20];
1556     int stackdepth = backtrace (stack, sizeof (stack) / sizeof (stack[0]));
1557     backtrace_symbols_fd (stack, stackdepth, 2);
1558 #endif
1559
1560     if (++errors == 100)
1561         fprintf (stderr, "Too many reference errors!\n");
1562     vlc_restorecancel (canc);
1563 }
1564
1565 static void held_objects_destroy (void *data)
1566 {
1567     VLC_UNUSED( data );
1568     held_list_t *hl = vlc_threadvar_get (&held_objects);
1569     vlc_object_t *caller = vlc_threadobj ();
1570
1571     int canc = vlc_savecancel ();
1572
1573     while (hl != NULL)
1574     {
1575         held_list_t *buf = hl->next;
1576         vlc_object_t *obj = hl->obj;
1577
1578         fprintf (stderr, "The %s %s thread object leaked a reference to...\n"
1579                          "the %s %s object.\n",
1580                  caller && caller->psz_object_name
1581                      ? caller->psz_object_name : "unnamed",
1582                  caller ? caller->psz_object_type : "main",
1583                  obj->psz_object_name ? obj->psz_object_name : "unnamed",
1584                  obj->psz_object_type);
1585         free (hl);
1586         hl = buf;
1587     }
1588     vlc_restorecancel (canc);
1589 }
1590 #endif