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