]> git.sesse.net Git - vlc/blob - src/misc/objects.c
Don't try to close a handle already closed
[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 static void vlc_object_dump( vlc_object_t *p_this );
87
88 /*****************************************************************************
89  * Local structure lock
90  *****************************************************************************/
91 static vlc_mutex_t structure_lock;
92 static unsigned    object_counter = 0;
93
94 static void close_nocancel (int fd)
95 {
96     int canc = vlc_savecancel ();
97     close (fd);
98     vlc_restorecancel (canc);
99 }
100
101 void *__vlc_custom_create( vlc_object_t *p_this, size_t i_size,
102                            int i_type, const char *psz_type )
103 {
104     vlc_object_t *p_new;
105     vlc_object_internals_t *p_priv;
106
107     /* NOTE:
108      * VLC objects are laid out as follow:
109      * - first the LibVLC-private per-object data,
110      * - then VLC_COMMON members from vlc_object_t,
111      * - finally, the type-specific data (if any).
112      *
113      * This function initializes the LibVLC and common data,
114      * and zeroes the rest.
115      */
116     p_priv = calloc( 1, sizeof( *p_priv ) + i_size );
117     if( p_priv == NULL )
118         return NULL;
119
120     assert (i_size >= sizeof (vlc_object_t));
121     p_new = (vlc_object_t *)(p_priv + 1);
122
123     p_new->i_object_type = i_type;
124     p_new->psz_object_type = psz_type;
125     p_new->psz_object_name = NULL;
126
127     p_new->b_die = false;
128     p_new->b_error = false;
129     p_new->b_dead = false;
130     p_new->b_force = false;
131
132     p_new->psz_header = NULL;
133
134     if (p_this)
135         p_new->i_flags = p_this->i_flags
136             & (OBJECT_FLAGS_NODBG|OBJECT_FLAGS_QUIET|OBJECT_FLAGS_NOINTERACT);
137
138     p_priv->p_vars = calloc( sizeof( variable_t ), 16 );
139
140     if( !p_priv->p_vars )
141     {
142         free( p_priv );
143         return NULL;
144     }
145
146     if( p_this == NULL )
147     {
148         if( i_type == VLC_OBJECT_LIBVLC )
149             p_new->p_libvlc = (libvlc_int_t*)p_new;
150         else
151         {
152             p_new->p_libvlc = NULL;
153             vlc_mutex_init( &structure_lock );
154         }
155
156         p_this = p_priv->next = p_priv->prev = p_new;
157     }
158     else
159         p_new->p_libvlc = p_this->p_libvlc;
160
161     vlc_spin_init( &p_priv->ref_spin );
162     p_priv->i_refcount = 1;
163     p_priv->pf_destructor = NULL;
164     p_priv->b_thread = false;
165     p_new->p_parent = NULL;
166     p_priv->pp_children = NULL;
167     p_priv->i_children = 0;
168
169     p_new->p_private = NULL;
170
171     /* Initialize mutexes and condvars */
172     vlc_mutex_init( &p_priv->lock );
173     vlc_cond_init( &p_priv->wait );
174     vlc_mutex_init( &p_priv->var_lock );
175     vlc_spin_init( &p_priv->spin );
176     p_priv->pipes[0] = p_priv->pipes[1] = -1;
177
178     p_priv->next = p_this;
179     vlc_mutex_lock( &structure_lock );
180     p_priv->prev = vlc_internals (p_this)->prev;
181     vlc_internals (p_this)->prev = p_new;
182     vlc_internals (p_priv->prev)->next = p_new;
183     p_new->i_object_id = object_counter++; /* fetch THEN increment */
184     vlc_mutex_unlock( &structure_lock );
185
186     if( i_type == VLC_OBJECT_LIBVLC )
187     {
188         int canc = vlc_savecancel ();
189         var_Create( p_new, "list", VLC_VAR_STRING | VLC_VAR_ISCOMMAND );
190         var_AddCallback( p_new, "list", DumpCommand, NULL );
191         var_Create( p_new, "tree", VLC_VAR_STRING | VLC_VAR_ISCOMMAND );
192         var_AddCallback( p_new, "tree", DumpCommand, NULL );
193         var_Create( p_new, "vars", VLC_VAR_STRING | VLC_VAR_ISCOMMAND );
194         var_AddCallback( p_new, "vars", DumpCommand, NULL );
195         vlc_restorecancel (canc);
196     }
197
198     return p_new;
199 }
200
201
202 /**
203  * Allocates and initializes a vlc object.
204  *
205  * @param i_type known object type (all of them are negative integer values),
206  *               or object byte size (always positive).
207  *
208  * @return the new object, or NULL on error.
209  */
210 void * __vlc_object_create( vlc_object_t *p_this, int i_type )
211 {
212     const char   * psz_type;
213     size_t         i_size;
214
215     switch( i_type )
216     {
217         case VLC_OBJECT_INTF:
218             i_size = sizeof(intf_thread_t);
219             psz_type = "interface";
220             break;
221         case VLC_OBJECT_DECODER:
222             i_size = sizeof(decoder_t);
223             psz_type = "decoder";
224             break;
225         case VLC_OBJECT_PACKETIZER:
226             i_size = sizeof(decoder_t);
227             psz_type = "packetizer";
228             break;
229         case VLC_OBJECT_ENCODER:
230             i_size = sizeof(encoder_t);
231             psz_type = "encoder";
232             break;
233         case VLC_OBJECT_AOUT:
234             i_size = sizeof(aout_instance_t);
235             psz_type = "audio output";
236             break;
237         case VLC_OBJECT_OPENGL:
238             i_size = sizeof( vout_thread_t );
239             psz_type = "opengl";
240             break;
241         case VLC_OBJECT_ANNOUNCE:
242             i_size = sizeof( announce_handler_t );
243             psz_type = "announce";
244             break;
245         default:
246             assert( i_type > 0 ); /* unknown type?! */
247             i_size = i_type;
248             i_type = VLC_OBJECT_GENERIC;
249             psz_type = "generic";
250             break;
251     }
252
253     return vlc_custom_create( p_this, i_size, i_type, psz_type );
254 }
255
256
257 /**
258  ****************************************************************************
259  * Set the destructor of a vlc object
260  *
261  * This function sets the destructor of the vlc object. It will be called
262  * when the object is destroyed when the its refcount reaches 0.
263  * (It is called by the internal function vlc_object_destroy())
264  *****************************************************************************/
265 void __vlc_object_set_destructor( vlc_object_t *p_this,
266                                   vlc_destructor_t pf_destructor )
267 {
268     vlc_object_internals_t *p_priv = vlc_internals(p_this );
269     p_priv->pf_destructor = pf_destructor;
270 }
271
272 /**
273  ****************************************************************************
274  * Destroy a vlc object (Internal)
275  *
276  * This function destroys an object that has been previously allocated with
277  * vlc_object_create. The object's refcount must be zero and it must not be
278  * attached to other objects in any way.
279  *
280  * This function must be called with cancellation disabled (currently).
281  *****************************************************************************/
282 static void vlc_object_destroy( vlc_object_t *p_this )
283 {
284     vlc_object_internals_t *p_priv = vlc_internals( p_this );
285
286     /* Objects are always detached beforehand */
287     assert( !p_this->p_parent );
288
289     /* Send a kill to the object's thread if applicable */
290     vlc_object_kill( p_this );
291
292     /* Call the custom "subclass" destructor */
293     if( p_priv->pf_destructor )
294         p_priv->pf_destructor( p_this );
295
296     /* Any thread must have been cleaned up at this point. */
297     assert( !p_priv->b_thread );
298
299     /* Destroy the associated variables, starting from the end so that
300      * no memmove calls have to be done. */
301     while( p_priv->i_vars )
302     {
303         var_Destroy( p_this, p_priv->p_vars[p_priv->i_vars - 1].psz_name );
304     }
305
306     free( p_priv->p_vars );
307     vlc_mutex_destroy( &p_priv->var_lock );
308
309     free( p_this->psz_header );
310
311     if( p_this->p_libvlc == NULL )
312         /* We are the global object ... no need to lock. */
313         vlc_mutex_destroy( &structure_lock );
314
315     FREENULL( p_this->psz_object_name );
316
317     vlc_spin_destroy( &p_priv->ref_spin );
318     vlc_mutex_destroy( &p_priv->lock );
319     vlc_cond_destroy( &p_priv->wait );
320     vlc_spin_destroy( &p_priv->spin );
321     if( p_priv->pipes[1] != -1 )
322         close( p_priv->pipes[1] );
323     if( p_priv->pipes[0] != -1 )
324         close( p_priv->pipes[0] );
325
326     free( p_priv );
327 }
328
329
330 /** Inter-object signaling */
331
332 void __vlc_object_lock( vlc_object_t *obj )
333 {
334     vlc_mutex_lock( &(vlc_internals(obj)->lock) );
335 }
336
337 void __vlc_object_unlock( vlc_object_t *obj )
338 {
339     vlc_assert_locked( &(vlc_internals(obj)->lock) );
340     vlc_mutex_unlock( &(vlc_internals(obj)->lock) );
341 }
342
343 #ifdef WIN32
344 # include <winsock2.h>
345 # include <ws2tcpip.h>
346
347 /**
348  * select()-able pipes emulated using Winsock
349  */
350 static int pipe (int fd[2])
351 {
352     SOCKADDR_IN addr;
353     int addrlen = sizeof (addr);
354
355     SOCKET l = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP), a,
356            c = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
357     if ((l == INVALID_SOCKET) || (c == INVALID_SOCKET))
358         goto error;
359
360     memset (&addr, 0, sizeof (addr));
361     addr.sin_family = AF_INET;
362     addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
363     if (bind (l, (PSOCKADDR)&addr, sizeof (addr))
364      || getsockname (l, (PSOCKADDR)&addr, &addrlen)
365      || listen (l, 1)
366      || connect (c, (PSOCKADDR)&addr, addrlen))
367         goto error;
368
369     a = accept (l, NULL, NULL);
370     if (a == INVALID_SOCKET)
371         goto error;
372
373     closesocket (l);
374     //shutdown (a, 0);
375     //shutdown (c, 1);
376     fd[0] = c;
377     fd[1] = a;
378     return 0;
379
380 error:
381     if (l != INVALID_SOCKET)
382         closesocket (l);
383     if (c != INVALID_SOCKET)
384         closesocket (c);
385     return -1;
386 }
387
388 #undef  read
389 #define read( a, b, c )  recv (a, b, c, 0)
390 #undef  write
391 #define write( a, b, c ) send (a, b, c, 0)
392 #undef  close
393 #define close( a )       closesocket (a)
394 #endif /* WIN32 */
395
396 /**
397  * Returns the readable end of a pipe that becomes readable once termination
398  * of the object is requested (vlc_object_kill()).
399  * This can be used to wake-up out of a select() or poll() event loop, such
400  * typically when doing network I/O.
401  *
402  * Note that the pipe will remain the same for the lifetime of the object.
403  * DO NOT read the pipe nor close it yourself. Ever.
404  *
405  * @param obj object that would be "killed"
406  * @return a readable pipe descriptor, or -1 on error.
407  */
408 int __vlc_object_waitpipe( vlc_object_t *obj )
409 {
410     int pfd[2] = { -1, -1 };
411     vlc_object_internals_t *internals = vlc_internals( obj );
412     bool killed = false;
413
414     vlc_spin_lock (&internals->spin);
415     if (internals->pipes[0] == -1)
416     {
417         /* This can only ever happen if someone killed us without locking: */
418         assert (internals->pipes[1] == -1);
419         vlc_spin_unlock (&internals->spin);
420
421         if (pipe (pfd))
422             return -1;
423
424         vlc_spin_lock (&internals->spin);
425         if (internals->pipes[0] == -1)
426         {
427             internals->pipes[0] = pfd[0];
428             internals->pipes[1] = pfd[1];
429             pfd[0] = pfd[1] = -1;
430         }
431         killed = obj->b_die;
432     }
433     vlc_spin_unlock (&internals->spin);
434
435     if (killed)
436     {
437         /* Race condition: vlc_object_kill() already invoked! */
438         int fd;
439
440         vlc_spin_lock (&internals->spin);
441         fd = internals->pipes[1];
442         internals->pipes[1] = -1;
443         vlc_spin_unlock (&internals->spin);
444
445         msg_Dbg (obj, "waitpipe: object already dying");
446         if (fd != -1)
447             close (fd);
448     }
449
450     /* Race condition: two threads call pipe() - unlikely */
451     if (pfd[0] != -1)
452         close (pfd[0]);
453     if (pfd[1] != -1)
454         close (pfd[1]);
455
456     return internals->pipes[0];
457 }
458
459
460 /**
461  * Suspends until another thread calls vlc_object_signal_unlocked().
462  * The thread may be woken up earlier due to limitations of the underlying
463  * implementation.
464  *
465  * In new code, please use vlc_cond_wait() instead.
466  *
467  * This function is a cancellation point. In case of cancellation, the object
468  * will be in locked state.
469  */
470 void __vlc_object_wait( vlc_object_t *obj )
471 {
472     vlc_object_internals_t *priv = vlc_internals( obj );
473     vlc_assert_locked( &priv->lock);
474     vlc_cond_wait( &priv->wait, &priv->lock );
475 }
476
477
478 /**
479  * Wakes up one thread waiting on the object. If no thread are (yet) waiting,
480  * nothing happens.
481  *
482  * Please do not use this function in new code as we are trying to untangle
483  * objects and threads. Use vlc_cond_wait() instead.
484  */
485 void __vlc_object_signal_unlocked( vlc_object_t *obj )
486 {
487     vlc_assert_locked (&(vlc_internals(obj)->lock));
488     vlc_cond_signal( &(vlc_internals(obj)->wait) );
489 }
490
491
492 /**
493  * Requests termination of an object.
494  * If the object is LibVLC, also request to terminate all its children.
495  */
496 void __vlc_object_kill( vlc_object_t *p_this )
497 {
498     vlc_object_internals_t *priv = vlc_internals( p_this );
499     int fd;
500
501     vlc_thread_cancel( p_this );
502     vlc_object_lock( p_this );
503     p_this->b_die = true;
504
505     vlc_spin_lock (&priv->spin);
506     fd = priv->pipes[1];
507     priv->pipes[1] = -1;
508     vlc_spin_unlock (&priv->spin);
509
510     if( fd != -1 )
511     {
512         msg_Dbg (p_this, "waitpipe: object killed");
513         close_nocancel (fd);
514     }
515
516     vlc_cond_broadcast (&priv->wait);
517     /* This also serves as a memory barrier toward vlc_object_alive(): */
518     vlc_object_unlock( p_this );
519 }
520
521
522 /**
523  * Find an object given its ID.
524  *
525  * This function looks for the object whose i_object_id field is i_id.
526  * This function is slow, and often used to hide bugs. Do not use it.
527  * If you need to retain reference to an object, yield the object pointer with
528  * vlc_object_yield(), use the pointer as your reference, and call
529  * vlc_object_release() when you're done.
530  */
531 void * vlc_object_get( libvlc_int_t *p_anchor, int i_id )
532 {
533     vlc_object_t *obj = NULL;
534 #ifndef NDEBUG
535     int canc = vlc_savecancel ();
536     fprintf (stderr, "Use of deprecated vlc_object_get(%d) ", i_id);
537     vlc_backtrace ();
538     vlc_restorecancel (canc);
539 #endif
540     vlc_mutex_lock( &structure_lock );
541
542     for( obj = vlc_internals (p_anchor)->next;
543          obj != VLC_OBJECT (p_anchor);
544          obj = vlc_internals (obj)->next )
545     {
546         if( obj->i_object_id == i_id )
547         {
548             vlc_object_yield( obj );
549             goto out;
550         }
551     }
552     obj = NULL;
553 #ifndef NDEBUG
554     fprintf (stderr, "Object %d does not exist\n", i_id);
555 #endif
556 out:
557     vlc_mutex_unlock( &structure_lock );
558     return obj;
559 }
560
561 /**
562  ****************************************************************************
563  * find a typed object and increment its refcount
564  *****************************************************************************
565  * This function recursively looks for a given object type. i_mode can be one
566  * of FIND_PARENT, FIND_CHILD or FIND_ANYWHERE.
567  *****************************************************************************/
568 void * __vlc_object_find( vlc_object_t *p_this, int i_type, int i_mode )
569 {
570     vlc_object_t *p_found;
571
572     /* If we are of the requested type ourselves, don't look further */
573     if( !(i_mode & FIND_STRICT) && p_this->i_object_type == i_type )
574     {
575         vlc_object_yield( p_this );
576         return p_this;
577     }
578
579     /* Otherwise, recursively look for the object */
580     if ((i_mode & 0x000f) == FIND_ANYWHERE)
581     {
582 #ifndef NDEBUG
583         if (i_type == VLC_OBJECT_PLAYLIST)
584             msg_Err (p_this, "using vlc_object_find(VLC_OBJECT_PLAYLIST) "
585                      "instead of pl_Yield()");
586 #endif
587         return vlc_object_find (p_this->p_libvlc, i_type,
588                                 (i_mode & ~0x000f)|FIND_CHILD);
589     }
590
591     vlc_mutex_lock( &structure_lock );
592     p_found = FindObject( p_this, i_type, i_mode );
593     vlc_mutex_unlock( &structure_lock );
594     return p_found;
595 }
596
597 #undef vlc_object_find_name
598 /**
599  * Finds a named object and increment its reference count.
600  * Beware that objects found in this manner can be "owned" by another thread,
601  * be of _any_ type, and be attached to any module (if any). With such an
602  * object reference, you can set or get object variables, emit log messages,
603  * and read write-once object parameters (i_object_id, psz_object_type, etc).
604  * You CANNOT cast the object to a more specific object type, and you
605  * definitely cannot invoke object type-specific callbacks with this.
606  *
607  * @param p_this object to search from
608  * @param psz_name name of the object to search for
609  * @param i_mode search direction: FIND_PARENT, FIND_CHILD or FIND_ANYWHERE.
610  *
611  * @return a matching object (must be released by the caller),
612  * or NULL on error.
613  */
614 vlc_object_t *vlc_object_find_name( vlc_object_t *p_this,
615                                     const char *psz_name, int i_mode )
616 {
617     vlc_object_t *p_found;
618
619     /* If have the requested name ourselves, don't look further */
620     if( !(i_mode & FIND_STRICT)
621         && p_this->psz_object_name
622         && !strcmp( p_this->psz_object_name, psz_name ) )
623     {
624         vlc_object_yield( p_this );
625         return p_this;
626     }
627
628     vlc_mutex_lock( &structure_lock );
629
630     /* Otherwise, recursively look for the object */
631     if( (i_mode & 0x000f) == FIND_ANYWHERE )
632     {
633         vlc_object_t *p_root = p_this;
634
635         /* Find the root */
636         while( p_root->p_parent != NULL &&
637                p_root != VLC_OBJECT( p_this->p_libvlc ) )
638         {
639             p_root = p_root->p_parent;
640         }
641
642         p_found = FindObjectName( p_root, psz_name,
643                                  (i_mode & ~0x000f)|FIND_CHILD );
644         if( p_found == NULL && p_root != VLC_OBJECT( p_this->p_libvlc ) )
645         {
646             p_found = FindObjectName( VLC_OBJECT( p_this->p_libvlc ),
647                                       psz_name, (i_mode & ~0x000f)|FIND_CHILD );
648         }
649     }
650     else
651     {
652         p_found = FindObjectName( p_this, psz_name, i_mode );
653     }
654
655     vlc_mutex_unlock( &structure_lock );
656
657     return p_found;
658 }
659
660 /**
661  * Increment an object reference counter.
662  */
663 void __vlc_object_yield( vlc_object_t *p_this )
664 {
665     vlc_object_internals_t *internals = vlc_internals( p_this );
666
667     vlc_spin_lock( &internals->ref_spin );
668     /* Avoid obvious freed object uses */
669     assert( internals->i_refcount > 0 );
670     /* Increment the counter */
671     internals->i_refcount++;
672     vlc_spin_unlock( &internals->ref_spin );
673 }
674
675 /*****************************************************************************
676  * Decrement an object refcount
677  * And destroy the object if its refcount reach zero.
678  *****************************************************************************/
679 void __vlc_object_release( vlc_object_t *p_this )
680 {
681     vlc_object_internals_t *internals = vlc_internals( p_this );
682     bool b_should_destroy;
683
684     vlc_spin_lock( &internals->ref_spin );
685     assert( internals->i_refcount > 0 );
686
687     if( internals->i_refcount > 1 )
688     {
689         /* Fast path */
690         /* There are still other references to the object */
691         internals->i_refcount--;
692         vlc_spin_unlock( &internals->ref_spin );
693         return;
694     }
695     vlc_spin_unlock( &internals->ref_spin );
696
697     /* Slow path */
698     /* Remember that we cannot hold the spin while waiting on the mutex */
699     vlc_mutex_lock( &structure_lock );
700     /* Take the spin again. Note that another thread may have yielded the
701      * object in the (very short) mean time. */
702     vlc_spin_lock( &internals->ref_spin );
703     b_should_destroy = --internals->i_refcount == 0;
704     vlc_spin_unlock( &internals->ref_spin );
705
706     if( b_should_destroy )
707     {
708 #ifndef NDEBUG
709         if( VLC_OBJECT(p_this->p_libvlc) == p_this )
710         {
711             /* Test for leaks */
712             vlc_object_t *leaked = internals->next;
713             while( leaked != p_this )
714             {
715                 /* We are leaking this object */
716                 fprintf( stderr,
717                          "ERROR: leaking object (id:%i, type:%s, name:%s)\n",
718                          leaked->i_object_id, leaked->psz_object_type,
719                          leaked->psz_object_name );
720                 /* Dump object to ease debugging */
721                 vlc_object_dump( leaked );
722                 fflush(stderr);
723                 leaked = vlc_internals (leaked)->next;
724             }
725
726             if( internals->next != p_this )
727                 /* Dump libvlc object to ease debugging */
728                 vlc_object_dump( p_this );
729         }
730 #endif
731         /* Remove the object from object list
732          * so that it cannot be encountered by vlc_object_get() */
733         vlc_internals (internals->next)->prev = internals->prev;
734         vlc_internals (internals->prev)->next = internals->next;
735
736         /* Detach from parent to protect against FIND_CHILDREN */
737         vlc_object_detach_unlocked (p_this);
738         /* Detach from children to protect against FIND_PARENT */
739         for (int i = 0; i < internals->i_children; i++)
740             internals->pp_children[i]->p_parent = NULL;
741     }
742
743     vlc_mutex_unlock( &structure_lock );
744
745     if( b_should_destroy )
746     {
747         int canc;
748
749         free( internals->pp_children );
750         internals->pp_children = NULL;
751         internals->i_children = 0;
752         canc = vlc_savecancel ();
753         vlc_object_destroy( p_this );
754         vlc_restorecancel (canc);
755     }
756 }
757
758 /**
759  ****************************************************************************
760  * attach object to a parent object
761  *****************************************************************************
762  * This function sets p_this as a child of p_parent, and p_parent as a parent
763  * of p_this. This link can be undone using vlc_object_detach.
764  *****************************************************************************/
765 void __vlc_object_attach( vlc_object_t *p_this, vlc_object_t *p_parent )
766 {
767     if( !p_this ) return;
768
769     vlc_mutex_lock( &structure_lock );
770
771     /* Attach the parent to its child */
772     assert (!p_this->p_parent);
773     p_this->p_parent = p_parent;
774
775     /* Attach the child to its parent */
776     vlc_object_internals_t *priv = vlc_internals( p_parent );
777     INSERT_ELEM( priv->pp_children, priv->i_children, priv->i_children,
778                  p_this );
779
780     vlc_mutex_unlock( &structure_lock );
781 }
782
783
784 static void vlc_object_detach_unlocked (vlc_object_t *p_this)
785 {
786     vlc_assert_locked (&structure_lock);
787
788     if (p_this->p_parent == NULL)
789         return;
790
791     vlc_object_internals_t *priv = vlc_internals( p_this->p_parent );
792
793     int i_index, i;
794
795     /* Remove p_this's parent */
796     p_this->p_parent = NULL;
797
798     /* Remove all of p_parent's children which are p_this */
799     for( i_index = priv->i_children ; i_index-- ; )
800     {
801         if( priv->pp_children[i_index] == p_this )
802         {
803             priv->i_children--;
804             for( i = i_index ; i < priv->i_children ; i++ )
805                 priv->pp_children[i] = priv->pp_children[i+1];
806         }
807     }
808
809     if( priv->i_children )
810     {
811         priv->pp_children = (vlc_object_t **)realloc( priv->pp_children,
812                                priv->i_children * sizeof(vlc_object_t *) );
813     }
814     else
815     {
816         /* Special case - don't realloc() to zero to avoid leaking */
817         free( priv->pp_children );
818         priv->pp_children = NULL;
819     }
820 }
821
822
823 /**
824  ****************************************************************************
825  * detach object from its parent
826  *****************************************************************************
827  * This function removes all links between an object and its parent.
828  *****************************************************************************/
829 void __vlc_object_detach( vlc_object_t *p_this )
830 {
831     if( !p_this ) return;
832
833     vlc_mutex_lock( &structure_lock );
834     if( !p_this->p_parent )
835         msg_Err( p_this, "object is not attached" );
836     else
837         vlc_object_detach_unlocked( p_this );
838     vlc_mutex_unlock( &structure_lock );
839 }
840
841
842 /**
843  ****************************************************************************
844  * find a list typed objects and increment their refcount
845  *****************************************************************************
846  * This function recursively looks for a given object type. i_mode can be one
847  * of FIND_PARENT, FIND_CHILD or FIND_ANYWHERE.
848  *****************************************************************************/
849 vlc_list_t * __vlc_list_find( vlc_object_t *p_this, int i_type, int i_mode )
850 {
851     vlc_list_t *p_list;
852     int i_count = 0;
853
854     /* Look for the objects */
855     switch( i_mode & 0x000f )
856     {
857     case FIND_ANYWHERE:
858         /* Modules should probably not be object, and the module should perhaps
859          * not be shared across LibVLC instances. In the mean time, this ugly
860          * hack is brought to you by Courmisch. */
861         if (i_type == VLC_OBJECT_MODULE)
862             return vlc_list_find ((vlc_object_t *)p_module_bank,
863                                   i_type, FIND_CHILD);
864         return vlc_list_find (p_this->p_libvlc, i_type, FIND_CHILD);
865
866     case FIND_CHILD:
867         vlc_mutex_lock( &structure_lock );
868         i_count = CountChildren( p_this, i_type );
869         p_list = NewList( i_count );
870
871         /* Check allocation was successful */
872         if( p_list->i_count != i_count )
873         {
874             vlc_mutex_unlock( &structure_lock );
875             msg_Err( p_this, "list allocation failed!" );
876             p_list->i_count = 0;
877             break;
878         }
879
880         p_list->i_count = 0;
881         ListChildren( p_list, p_this, i_type );
882         vlc_mutex_unlock( &structure_lock );
883         break;
884
885     default:
886         msg_Err( p_this, "unimplemented!" );
887         p_list = NewList( 0 );
888         break;
889     }
890
891     return p_list;
892 }
893
894 /**
895  * Gets the list of children of an objects, and increment their reference
896  * count.
897  * @return a list (possibly empty) or NULL in case of error.
898  */
899 vlc_list_t *__vlc_list_children( vlc_object_t *obj )
900 {
901     vlc_list_t *l;
902     vlc_object_internals_t *priv = vlc_internals( obj );
903
904     vlc_mutex_lock( &structure_lock );
905     l = NewList( priv->i_children );
906     for (int i = 0; i < l->i_count; i++)
907     {
908         vlc_object_yield( priv->pp_children[i] );
909         l->p_values[i].p_object = priv->pp_children[i];
910     }
911     vlc_mutex_unlock( &structure_lock );
912     return l;
913 }
914
915 /*****************************************************************************
916  * DumpCommand: print the current vlc structure
917  *****************************************************************************
918  * This function prints either an ASCII tree showing the connections between
919  * vlc objects, and additional information such as their refcount, thread ID,
920  * etc. (command "tree"), or the same data as a simple list (command "list").
921  *****************************************************************************/
922 static int DumpCommand( vlc_object_t *p_this, char const *psz_cmd,
923                         vlc_value_t oldval, vlc_value_t newval, void *p_data )
924 {
925     libvlc_int_t *p_libvlc = p_this->p_libvlc;
926
927     (void)oldval; (void)p_data;
928     if( *psz_cmd == 'l' )
929     {
930         vlc_object_t *cur = VLC_OBJECT (p_libvlc);
931
932         vlc_mutex_lock( &structure_lock );
933         do
934         {
935             PrintObject (cur, "");
936             cur = vlc_internals (cur)->next;
937         }
938         while (cur != VLC_OBJECT(p_libvlc));
939         vlc_mutex_unlock( &structure_lock );
940     }
941     else
942     {
943         vlc_object_t *p_object = NULL;
944
945         if( *newval.psz_string )
946         {
947             char *end;
948             int i_id = strtol( newval.psz_string, &end, 0 );
949             if( !*end )
950                 p_object = vlc_object_get( p_libvlc, i_id );
951             else
952                 /* try using the object's name to find it */
953                 p_object = vlc_object_find_name( p_this, newval.psz_string,
954                                                  FIND_ANYWHERE );
955
956             if( !p_object )
957             {
958                 return VLC_ENOOBJ;
959             }
960         }
961
962         vlc_mutex_lock( &structure_lock );
963
964         if( *psz_cmd == 't' )
965         {
966             char psz_foo[2 * MAX_DUMPSTRUCTURE_DEPTH + 1];
967
968             if( !p_object )
969                 p_object = VLC_OBJECT(p_this->p_libvlc);
970
971             psz_foo[0] = '|';
972             DumpStructure( p_object, 0, psz_foo );
973         }
974         else if( *psz_cmd == 'v' )
975         {
976             int i;
977
978             if( !p_object )
979                 p_object = p_this->p_libvlc ? VLC_OBJECT(p_this->p_libvlc) : p_this;
980
981             PrintObject( p_object, "" );
982
983             if( !vlc_internals( p_object )->i_vars )
984                 printf( " `-o No variables\n" );
985             for( i = 0; i < vlc_internals( p_object )->i_vars; i++ )
986             {
987                 variable_t *p_var = vlc_internals( p_object )->p_vars + i;
988
989                 const char *psz_type = "unknown";
990                 switch( p_var->i_type & VLC_VAR_TYPE )
991                 {
992 #define MYCASE( type, nice )                \
993                     case VLC_VAR_ ## type:  \
994                         psz_type = nice;    \
995                         break;
996                     MYCASE( VOID, "void" );
997                     MYCASE( BOOL, "bool" );
998                     MYCASE( INTEGER, "integer" );
999                     MYCASE( HOTKEY, "hotkey" );
1000                     MYCASE( STRING, "string" );
1001                     MYCASE( MODULE, "module" );
1002                     MYCASE( FILE, "file" );
1003                     MYCASE( DIRECTORY, "directory" );
1004                     MYCASE( VARIABLE, "variable" );
1005                     MYCASE( FLOAT, "float" );
1006                     MYCASE( TIME, "time" );
1007                     MYCASE( ADDRESS, "address" );
1008                     MYCASE( MUTEX, "mutex" );
1009                     MYCASE( LIST, "list" );
1010 #undef MYCASE
1011                 }
1012                 printf( " %c-o \"%s\" (%s",
1013                         i + 1 == vlc_internals( p_object )->i_vars ? '`' : '|',
1014                         p_var->psz_name, psz_type );
1015                 if( p_var->psz_text )
1016                     printf( ", %s", p_var->psz_text );
1017                 printf( ")" );
1018                 if( p_var->i_type & VLC_VAR_HASCHOICE )
1019                     printf( ", has choices" );
1020                 if( p_var->i_type & VLC_VAR_ISCOMMAND )
1021                     printf( ", command" );
1022                 if( p_var->i_entries )
1023                     printf( ", %d callbacks", p_var->i_entries );
1024                 switch( p_var->i_type & 0x00f0 )
1025                 {
1026                     case VLC_VAR_VOID:
1027                     case VLC_VAR_MUTEX:
1028                         break;
1029                     case VLC_VAR_BOOL:
1030                         printf( ": %s", p_var->val.b_bool ? "true" : "false" );
1031                         break;
1032                     case VLC_VAR_INTEGER:
1033                         printf( ": %d", p_var->val.i_int );
1034                         break;
1035                     case VLC_VAR_STRING:
1036                         printf( ": \"%s\"", p_var->val.psz_string );
1037                         break;
1038                     case VLC_VAR_FLOAT:
1039                         printf( ": %f", p_var->val.f_float );
1040                         break;
1041                     case VLC_VAR_TIME:
1042                         printf( ": %"PRIi64, (int64_t)p_var->val.i_time );
1043                         break;
1044                     case VLC_VAR_ADDRESS:
1045                         printf( ": %p", p_var->val.p_address );
1046                         break;
1047                     case VLC_VAR_LIST:
1048                         printf( ": TODO" );
1049                         break;
1050                 }
1051                 printf( "\n" );
1052             }
1053         }
1054
1055         vlc_mutex_unlock( &structure_lock );
1056
1057         if( *newval.psz_string )
1058         {
1059             vlc_object_release( p_object );
1060         }
1061     }
1062
1063     return VLC_SUCCESS;
1064 }
1065
1066 /*****************************************************************************
1067  * vlc_list_release: free a list previously allocated by vlc_list_find
1068  *****************************************************************************
1069  * This function decreases the refcount of all objects in the list and
1070  * frees the list.
1071  *****************************************************************************/
1072 void vlc_list_release( vlc_list_t *p_list )
1073 {
1074     int i_index;
1075
1076     for( i_index = 0; i_index < p_list->i_count; i_index++ )
1077     {
1078         vlc_object_release( p_list->p_values[i_index].p_object );
1079     }
1080
1081     free( p_list->p_values );
1082     free( p_list );
1083 }
1084
1085 /*****************************************************************************
1086  * dump an object. (Debug function)
1087  *****************************************************************************/
1088 static void vlc_object_dump( vlc_object_t *p_this )
1089 {
1090     char psz_foo[2 * MAX_DUMPSTRUCTURE_DEPTH + 1];
1091     psz_foo[0] = '|';
1092
1093     vlc_assert_locked( &structure_lock );
1094     DumpStructure( p_this, 0, psz_foo );
1095 }
1096
1097 /* Following functions are local */
1098
1099 static vlc_object_t * FindObject( vlc_object_t *p_this, int i_type, int i_mode )
1100 {
1101     int i;
1102     vlc_object_t *p_tmp;
1103
1104     switch( i_mode & 0x000f )
1105     {
1106     case FIND_PARENT:
1107         p_tmp = p_this->p_parent;
1108         if( p_tmp )
1109         {
1110             if( p_tmp->i_object_type == i_type )
1111             {
1112                 vlc_object_yield( p_tmp );
1113                 return p_tmp;
1114             }
1115             else
1116             {
1117                 return FindObject( p_tmp, i_type, i_mode );
1118             }
1119         }
1120         break;
1121
1122     case FIND_CHILD:
1123         for( i = vlc_internals( p_this )->i_children; i--; )
1124         {
1125             p_tmp = vlc_internals( p_this )->pp_children[i];
1126             if( p_tmp->i_object_type == i_type )
1127             {
1128                 vlc_object_yield( p_tmp );
1129                 return p_tmp;
1130             }
1131             else if( vlc_internals( p_tmp )->i_children )
1132             {
1133                 p_tmp = FindObject( p_tmp, i_type, i_mode );
1134                 if( p_tmp )
1135                 {
1136                     return p_tmp;
1137                 }
1138             }
1139         }
1140         break;
1141
1142     case FIND_ANYWHERE:
1143         /* Handled in vlc_object_find */
1144         break;
1145     }
1146
1147     return NULL;
1148 }
1149
1150 static vlc_object_t * FindObjectName( vlc_object_t *p_this,
1151                                       const char *psz_name,
1152                                       int i_mode )
1153 {
1154     int i;
1155     vlc_object_t *p_tmp;
1156
1157     switch( i_mode & 0x000f )
1158     {
1159     case FIND_PARENT:
1160         p_tmp = p_this->p_parent;
1161         if( p_tmp )
1162         {
1163             if( p_tmp->psz_object_name
1164                 && !strcmp( p_tmp->psz_object_name, psz_name ) )
1165             {
1166                 vlc_object_yield( p_tmp );
1167                 return p_tmp;
1168             }
1169             else
1170             {
1171                 return FindObjectName( p_tmp, psz_name, i_mode );
1172             }
1173         }
1174         break;
1175
1176     case FIND_CHILD:
1177         for( i = vlc_internals( p_this )->i_children; i--; )
1178         {
1179             p_tmp = vlc_internals( p_this )->pp_children[i];
1180             if( p_tmp->psz_object_name
1181                 && !strcmp( p_tmp->psz_object_name, psz_name ) )
1182             {
1183                 vlc_object_yield( p_tmp );
1184                 return p_tmp;
1185             }
1186             else if( vlc_internals( p_tmp )->i_children )
1187             {
1188                 p_tmp = FindObjectName( p_tmp, psz_name, i_mode );
1189                 if( p_tmp )
1190                 {
1191                     return p_tmp;
1192                 }
1193             }
1194         }
1195         break;
1196
1197     case FIND_ANYWHERE:
1198         /* Handled in vlc_object_find */
1199         break;
1200     }
1201
1202     return NULL;
1203 }
1204
1205
1206 static void PrintObject( vlc_object_t *p_this, const char *psz_prefix )
1207 {
1208     char psz_children[20], psz_refcount[20], psz_thread[30], psz_name[50],
1209          psz_parent[20];
1210
1211     int canc = vlc_savecancel ();
1212     memset( &psz_name, 0, sizeof(psz_name) );
1213     if( p_this->psz_object_name )
1214     {
1215         snprintf( psz_name, 49, " \"%s\"", p_this->psz_object_name );
1216         if( psz_name[48] )
1217             psz_name[48] = '\"';
1218     }
1219
1220     psz_children[0] = '\0';
1221     switch( vlc_internals( p_this )->i_children )
1222     {
1223         case 0:
1224             break;
1225         case 1:
1226             strcpy( psz_children, ", 1 child" );
1227             break;
1228         default:
1229             snprintf( psz_children, 19, ", %i children",
1230                       vlc_internals( p_this )->i_children );
1231             break;
1232     }
1233
1234     psz_refcount[0] = '\0';
1235     if( vlc_internals( p_this )->i_refcount > 0 )
1236         snprintf( psz_refcount, 19, ", refcount %u",
1237                   vlc_internals( p_this )->i_refcount );
1238
1239     psz_thread[0] = '\0';
1240     if( vlc_internals( p_this )->b_thread )
1241         snprintf( psz_thread, 29, " (thread %lu)",
1242                   (unsigned long)vlc_internals( p_this )->thread_id );
1243
1244     psz_parent[0] = '\0';
1245     if( p_this->p_parent )
1246         snprintf( psz_parent, 19, ", parent %i", p_this->p_parent->i_object_id );
1247
1248     printf( " %so %.8i %s%s%s%s%s%s\n", psz_prefix,
1249             p_this->i_object_id, p_this->psz_object_type,
1250             psz_name, psz_thread, psz_refcount, psz_children,
1251             psz_parent );
1252     vlc_restorecancel (canc);
1253 }
1254
1255 static void DumpStructure( vlc_object_t *p_this, int i_level, char *psz_foo )
1256 {
1257     int i;
1258     char i_back = psz_foo[i_level];
1259     psz_foo[i_level] = '\0';
1260
1261     PrintObject( p_this, psz_foo );
1262
1263     psz_foo[i_level] = i_back;
1264
1265     if( i_level / 2 >= MAX_DUMPSTRUCTURE_DEPTH )
1266     {
1267         msg_Warn( p_this, "structure tree is too deep" );
1268         return;
1269     }
1270
1271     for( i = 0 ; i < vlc_internals( p_this )->i_children ; i++ )
1272     {
1273         if( i_level )
1274         {
1275             psz_foo[i_level-1] = ' ';
1276
1277             if( psz_foo[i_level-2] == '`' )
1278             {
1279                 psz_foo[i_level-2] = ' ';
1280             }
1281         }
1282
1283         if( i == vlc_internals( p_this )->i_children - 1 )
1284         {
1285             psz_foo[i_level] = '`';
1286         }
1287         else
1288         {
1289             psz_foo[i_level] = '|';
1290         }
1291
1292         psz_foo[i_level+1] = '-';
1293         psz_foo[i_level+2] = '\0';
1294
1295         DumpStructure( vlc_internals( p_this )->pp_children[i], i_level + 2,
1296                        psz_foo );
1297     }
1298 }
1299
1300 static vlc_list_t * NewList( int i_count )
1301 {
1302     vlc_list_t * p_list = (vlc_list_t *)malloc( sizeof( vlc_list_t ) );
1303     if( p_list == NULL )
1304     {
1305         return NULL;
1306     }
1307
1308     p_list->i_count = i_count;
1309
1310     if( i_count == 0 )
1311     {
1312         p_list->p_values = NULL;
1313         return p_list;
1314     }
1315
1316     p_list->p_values = malloc( i_count * sizeof( vlc_value_t ) );
1317     if( p_list->p_values == NULL )
1318     {
1319         p_list->i_count = 0;
1320         return p_list;
1321     }
1322
1323     return p_list;
1324 }
1325
1326 static void ListReplace( vlc_list_t *p_list, vlc_object_t *p_object,
1327                          int i_index )
1328 {
1329     if( p_list == NULL || i_index >= p_list->i_count )
1330     {
1331         return;
1332     }
1333
1334     vlc_object_yield( p_object );
1335
1336     p_list->p_values[i_index].p_object = p_object;
1337
1338     return;
1339 }
1340
1341 /*static void ListAppend( vlc_list_t *p_list, vlc_object_t *p_object )
1342 {
1343     if( p_list == NULL )
1344     {
1345         return;
1346     }
1347
1348     p_list->p_values = realloc( p_list->p_values, (p_list->i_count + 1)
1349                                 * sizeof( vlc_value_t ) );
1350     if( p_list->p_values == NULL )
1351     {
1352         p_list->i_count = 0;
1353         return;
1354     }
1355
1356     vlc_object_yield( p_object );
1357
1358     p_list->p_values[p_list->i_count].p_object = p_object;
1359     p_list->i_count++;
1360
1361     return;
1362 }*/
1363
1364 static int CountChildren( vlc_object_t *p_this, int i_type )
1365 {
1366     vlc_object_t *p_tmp;
1367     int i, i_count = 0;
1368
1369     for( i = 0; i < vlc_internals( p_this )->i_children; i++ )
1370     {
1371         p_tmp = vlc_internals( p_this )->pp_children[i];
1372
1373         if( p_tmp->i_object_type == i_type )
1374         {
1375             i_count++;
1376         }
1377         i_count += CountChildren( p_tmp, i_type );
1378     }
1379
1380     return i_count;
1381 }
1382
1383 static void ListChildren( vlc_list_t *p_list, vlc_object_t *p_this, int i_type )
1384 {
1385     vlc_object_t *p_tmp;
1386     int i;
1387
1388     for( i = 0; i < vlc_internals( p_this )->i_children; i++ )
1389     {
1390         p_tmp = vlc_internals( p_this )->pp_children[i];
1391
1392         if( p_tmp->i_object_type == i_type )
1393             ListReplace( p_list, p_tmp, p_list->i_count++ );
1394
1395         ListChildren( p_list, p_tmp, i_type );
1396     }
1397 }