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