]> git.sesse.net Git - vlc/blob - src/modules/modules.c
Hide module_bank
[vlc] / src / modules / modules.c
1 /*****************************************************************************
2  * modules.c : Builtin and plugin modules management functions
3  *****************************************************************************
4  * Copyright (C) 2001-2011 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Sam Hocevar <sam@zoy.org>
8  *          Ethan C. Baldridge <BaldridgeE@cadmus.com>
9  *          Hans-Peter Jansen <hpj@urpla.net>
10  *          Gildas Bazin <gbazin@videolan.org>
11  *          RĂ©mi Denis-Courmont
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
26  *****************************************************************************/
27
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc_common.h>
33 #include <vlc_plugin.h>
34 #include <vlc_memory.h>
35 #include <vlc_modules.h>
36 #include "libvlc.h"
37
38 #include <stdlib.h>                                      /* free(), strtol() */
39 #include <stdio.h>                                              /* sprintf() */
40 #include <string.h>                                              /* strdup() */
41 #include <assert.h>
42
43 #include <sys/types.h>
44 #ifdef HAVE_SYS_STAT_H
45 #   include <sys/stat.h>
46 #endif
47 #ifdef HAVE_UNISTD_H
48 #   include <unistd.h>
49 #endif
50 #ifdef ENABLE_NLS
51 # include <libintl.h>
52 #endif
53
54 #include "config/configuration.h"
55
56 #include <vlc_fs.h>
57 #include "vlc_arrays.h"
58
59 #include "modules/modules.h"
60
61 typedef struct
62 {
63     unsigned         i_usage;
64
65     /* Plugins cache */
66     int            i_cache;
67     module_cache_t **pp_cache;
68
69     int            i_loaded_cache;
70     module_cache_t **pp_loaded_cache;
71
72     module_t       *head;
73 } module_bank_t;
74
75 static module_bank_t *p_module_bank = NULL;
76 static vlc_mutex_t module_lock = VLC_STATIC_MUTEX;
77
78 int vlc_entry__main( module_t * );
79
80 /*****************************************************************************
81  * Local prototypes
82  *****************************************************************************/
83 #ifdef HAVE_DYNAMIC_PLUGINS
84 typedef enum { CACHE_USE, CACHE_RESET, CACHE_IGNORE } cache_mode_t;
85 static void AllocateAllPlugins( vlc_object_t *, module_bank_t * );
86 static void AllocatePluginPath( vlc_object_t *, module_bank_t *, const char *,
87                                 cache_mode_t );
88 static void AllocatePluginDir( vlc_object_t *, module_bank_t *, const char *,
89                                unsigned, cache_mode_t );
90 static int  AllocatePluginFile( vlc_object_t *, module_bank_t *, const char *,
91                                 const struct stat *, cache_mode_t );
92 static module_t * AllocatePlugin( vlc_object_t *, const char *, bool );
93 #endif
94 static int  AllocateBuiltinModule( vlc_object_t *, int ( * ) ( module_t * ) );
95 static void DeleteModule ( module_bank_t *, module_t * );
96 #ifdef HAVE_DYNAMIC_PLUGINS
97 static void   DupModule        ( module_t * );
98 static void   UndupModule      ( module_t * );
99 #endif
100
101 #undef module_InitBank
102 /**
103  * Init bank
104  *
105  * Creates a module bank structure which will be filled later
106  * on with all the modules found.
107  * \param p_this vlc object structure
108  * \return nothing
109  */
110 void module_InitBank( vlc_object_t *p_this )
111 {
112     module_bank_t *p_bank = NULL;
113
114     vlc_mutex_lock( &module_lock );
115
116     if( p_module_bank == NULL )
117     {
118         p_bank = calloc (1, sizeof(*p_bank));
119         p_bank->i_usage = 1;
120         p_bank->i_cache = 0;
121         p_bank->pp_cache = NULL;
122         p_bank->head = NULL;
123
124         /* Everything worked, attach the object */
125         p_module_bank = p_bank;
126
127         /* Fills the module bank structure with the main module infos.
128          * This is very useful as it will allow us to consider the main
129          * library just as another module, and for instance the configuration
130          * options of main will be available in the module bank structure just
131          * as for every other module. */
132         AllocateBuiltinModule( p_this, vlc_entry__main );
133         vlc_rwlock_init (&config_lock);
134         config_SortConfig ();
135     }
136     else
137         p_module_bank->i_usage++;
138
139     /* We do retain the module bank lock until the plugins are loaded as well.
140      * This is ugly, this staged loading approach is needed: LibVLC gets
141      * some configuration parameters relevant to loading the plugins from
142      * the main (builtin) module. The module bank becomes shared read-only data
143      * once it is ready, so we need to fully serialize initialization.
144      * DO NOT UNCOMMENT the following line unless you managed to squeeze
145      * module_LoadPlugins() before you unlock the mutex. */
146     /*vlc_mutex_unlock( &module_lock );*/
147 }
148
149 #undef module_EndBank
150 /**
151  * Unloads all unused plugin modules and empties the module
152  * bank in case of success.
153  * \param p_this vlc object structure
154  * \return nothing
155  */
156 void module_EndBank( vlc_object_t *p_this, bool b_plugins )
157 {
158     module_bank_t *p_bank = p_module_bank;
159
160     assert (p_bank != NULL);
161
162     /* If plugins were _not_ loaded, then the caller still has the bank lock
163      * from module_InitBank(). */
164     if( b_plugins )
165         vlc_mutex_lock( &module_lock );
166     /*else
167         vlc_assert_locked( &module_lock ); not for static mutexes :( */
168
169     if( --p_bank->i_usage > 0 )
170     {
171         vlc_mutex_unlock( &module_lock );
172         return;
173     }
174
175     config_UnsortConfig ();
176     vlc_rwlock_destroy (&config_lock);
177     p_module_bank = NULL;
178     vlc_mutex_unlock( &module_lock );
179
180 #ifdef HAVE_DYNAMIC_PLUGINS
181     while( p_bank->i_cache-- )
182     {
183         free( p_bank->pp_cache[p_bank->i_cache]->path );
184         free( p_bank->pp_cache[p_bank->i_cache] );
185     }
186     free( p_bank->pp_cache );
187 #endif
188
189     while( p_bank->head != NULL )
190         DeleteModule( p_bank, p_bank->head );
191
192     free( p_bank );
193 }
194
195 #undef module_LoadPlugins
196 /**
197  * Loads module descriptions for all available plugins.
198  * Fills the module bank structure with the plugin modules.
199  *
200  * \param p_this vlc object structure
201  * \return nothing
202  */
203 void module_LoadPlugins( vlc_object_t * p_this )
204 {
205     module_bank_t *p_bank = p_module_bank;
206
207     assert( p_bank );
208     /*vlc_assert_locked( &module_lock ); not for static mutexes :( */
209
210 #ifdef HAVE_DYNAMIC_PLUGINS
211     if( p_bank->i_usage == 1 )
212     {
213         msg_Dbg( p_this, "checking plugin modules" );
214         AllocateAllPlugins( p_this, p_module_bank );
215         config_UnsortConfig ();
216         config_SortConfig ();
217     }
218 #endif
219     vlc_mutex_unlock( &module_lock );
220 }
221
222 /**
223  * Checks whether a module implements a capability.
224  *
225  * \param m the module
226  * \param cap the capability to check
227  * \return TRUE if the module have the capability
228  */
229 bool module_provides( const module_t *m, const char *cap )
230 {
231     return !strcmp( m->psz_capability, cap );
232 }
233
234 /**
235  * Get the internal name of a module
236  *
237  * \param m the module
238  * \return the module name
239  */
240 const char *module_get_object( const module_t *m )
241 {
242     return m->psz_object_name;
243 }
244
245 /**
246  * Get the human-friendly name of a module.
247  *
248  * \param m the module
249  * \param long_name TRUE to have the long name of the module
250  * \return the short or long name of the module
251  */
252 const char *module_get_name( const module_t *m, bool long_name )
253 {
254     if( long_name && ( m->psz_longname != NULL) )
255         return m->psz_longname;
256
257     return m->psz_shortname ? m->psz_shortname : m->psz_object_name;
258 }
259
260 /**
261  * Get the help for a module
262  *
263  * \param m the module
264  * \return the help
265  */
266 const char *module_get_help( const module_t *m )
267 {
268     return m->psz_help;
269 }
270
271 /**
272  * Get the capability for a module
273  *
274  * \param m the module
275  * return the capability
276  */
277 const char *module_get_capability( const module_t *m )
278 {
279     return m->psz_capability;
280 }
281
282 /**
283  * Get the score for a module
284  *
285  * \param m the module
286  * return the score for the capability
287  */
288 int module_get_score( const module_t *m )
289 {
290     return m->i_score;
291 }
292
293 /**
294  * Translate a string using the module's text domain
295  *
296  * \param m the module
297  * \param str the American English ASCII string to localize
298  * \return the gettext-translated string
299  */
300 const char *module_gettext (const module_t *m, const char *str)
301 {
302 #ifdef ENABLE_NLS
303     const char *domain = m->domain ? m->domain : PACKAGE_NAME;
304     if (unlikely(str == NULL || *str == '\0'))
305         return "";
306     return dgettext (domain, str);
307 #else
308     (void)m;
309     return str;
310 #endif
311 }
312
313 module_t *module_hold (module_t *m)
314 {
315     vlc_hold (&m->vlc_gc_data);
316     return m;
317 }
318
319 void module_release (module_t *m)
320 {
321     vlc_release (&m->vlc_gc_data);
322 }
323
324 #undef module_start
325 int module_start (vlc_object_t *obj, module_t *m)
326 {
327    int (*activate) (vlc_object_t *) = m->pf_activate;
328
329    return (activate != NULL) ? activate (obj) : VLC_SUCCESS;
330 }
331
332 #undef module_stop
333 void module_stop (vlc_object_t *obj, module_t *m)
334 {
335    void (*deactivate) (vlc_object_t *) = m->pf_deactivate;
336
337     if (deactivate != NULL)
338         deactivate (obj);
339 }
340
341 /**
342  * Frees the flat list of VLC modules.
343  * @param list list obtained by module_list_get()
344  * @param length number of items on the list
345  * @return nothing.
346  */
347 void module_list_free (module_t **list)
348 {
349     if (list == NULL)
350         return;
351
352     for (size_t i = 0; list[i] != NULL; i++)
353          module_release (list[i]);
354     free (list);
355 }
356
357 /**
358  * Gets the flat list of VLC modules.
359  * @param n [OUT] pointer to the number of modules or NULL
360  * @return NULL-terminated table of module pointers
361  *         (release with module_list_free()), or NULL in case of error.
362  */
363 module_t **module_list_get (size_t *n)
364 {
365     /* TODO: this whole module lookup is quite inefficient */
366     /* Remove this and improve module_need */
367     module_t **tab = NULL;
368     size_t i = 0;
369
370     assert (p_module_bank);
371     for (module_t *mod = p_module_bank->head; mod; mod = mod->next)
372     {
373          module_t **nt;
374          nt  = realloc (tab, (i + 2 + mod->submodule_count) * sizeof (*tab));
375          if (nt == NULL)
376          {
377              module_list_free (tab);
378              return NULL;
379          }
380
381          tab = nt;
382          tab[i++] = module_hold (mod);
383          for (module_t *subm = mod->submodule; subm; subm = subm->next)
384              tab[i++] = module_hold (subm);
385          tab[i] = NULL;
386     }
387     if (n != NULL)
388         *n = i;
389     return tab;
390 }
391
392 typedef struct module_list_t
393 {
394     module_t *p_module;
395     int16_t  i_score;
396     bool     b_force;
397 } module_list_t;
398
399 static int modulecmp (const void *a, const void *b)
400 {
401     const module_list_t *la = a, *lb = b;
402     /* Note that qsort() uses _ascending_ order,
403      * so the smallest module is the one with the biggest score. */
404     return lb->i_score - la->i_score;
405 }
406
407 #undef vlc_module_load
408 /**
409  * Finds and instantiates the best module of a certain type.
410  * All candidates modules having the specified capability and name will be
411  * sorted in decreasing order of priority. Then the probe callback will be
412  * invoked for each module, until it succeeds (returns 0), or all candidate
413  * module failed to initialize.
414  *
415  * The probe callback first parameter is the address of the module entry point.
416  * Further parameters are passed as an argument list; it corresponds to the
417  * variable arguments passed to this function. This scheme is meant to
418  * support arbitrary prototypes for the module entry point.
419  *
420  * \param p_this VLC object
421  * \param psz_capability capability, i.e. class of module
422  * \param psz_name name name of the module asked, if any
423  * \param b_strict if true, do not fallback to plugin with a different name
424  *                 but the same capability
425  * \param probe module probe callback
426  * \return the module or NULL in case of a failure
427  */
428 module_t *vlc_module_load(vlc_object_t *p_this, const char *psz_capability,
429                           const char *psz_name, bool b_strict,
430                           vlc_activate_t probe, ...)
431 {
432     stats_TimerStart( p_this, "module_need()", STATS_TIMER_MODULE_NEED );
433
434     module_list_t *p_list;
435     module_t *p_module;
436     int i_shortcuts = 0;
437     char *psz_shortcuts = NULL, *psz_var = NULL, *psz_alias = NULL;
438     bool b_force_backup = p_this->b_force;
439
440     /* Deal with variables */
441     if( psz_name && psz_name[0] == '$' )
442     {
443         psz_name = psz_var = var_CreateGetString( p_this, psz_name + 1 );
444     }
445
446     /* Count how many different shortcuts were asked for */
447     if( psz_name && *psz_name )
448     {
449         char *psz_parser, *psz_last_shortcut;
450
451         /* If the user wants none, give him none. */
452         if( !strcmp( psz_name, "none" ) )
453         {
454             free( psz_var );
455             stats_TimerStop( p_this, STATS_TIMER_MODULE_NEED );
456             stats_TimerDump( p_this, STATS_TIMER_MODULE_NEED );
457             stats_TimerClean( p_this, STATS_TIMER_MODULE_NEED );
458             return NULL;
459         }
460
461         i_shortcuts++;
462         psz_parser = psz_shortcuts = psz_last_shortcut = strdup( psz_name );
463
464         while( ( psz_parser = strchr( psz_parser, ',' ) ) )
465         {
466              *psz_parser = '\0';
467              i_shortcuts++;
468              psz_last_shortcut = ++psz_parser;
469         }
470
471         /* Check if the user wants to override the "strict" mode */
472         if( psz_last_shortcut )
473         {
474             if( !strcmp(psz_last_shortcut, "none") )
475             {
476                 b_strict = true;
477                 i_shortcuts--;
478             }
479             else if( !strcmp(psz_last_shortcut, "any") )
480             {
481                 b_strict = false;
482                 i_shortcuts--;
483             }
484         }
485     }
486
487     /* Sort the modules and test them */
488     size_t count;
489     module_t **p_all = module_list_get (&count);
490     p_list = malloc( count * sizeof( module_list_t ) );
491
492     /* Parse the module list for capabilities and probe each of them */
493     count = 0;
494     for (size_t i = 0; (p_module = p_all[i]) != NULL; i++)
495     {
496         int i_shortcut_bonus = 0;
497
498         /* Test that this module can do what we need */
499         if( !module_provides( p_module, psz_capability ) )
500             continue;
501
502         /* If we required a shortcut, check this plugin provides it. */
503         if( i_shortcuts > 0 )
504         {
505             const char *name = psz_shortcuts;
506
507             for( unsigned i_short = i_shortcuts; i_short > 0; i_short-- )
508             {
509                 for( unsigned i = 0; i < p_module->i_shortcuts; i++ )
510                 {
511                     char *c;
512                     if( ( c = strchr( name, '@' ) )
513                         ? !strncasecmp( name, p_module->pp_shortcuts[i],
514                                         c-name )
515                         : !strcasecmp( name, p_module->pp_shortcuts[i] ) )
516                     {
517                         /* Found it */
518                         if( c && c[1] )
519                             psz_alias = c+1;
520                         i_shortcut_bonus = i_short * 10000;
521                         goto found_shortcut;
522                     }
523                 }
524
525                 /* Go to the next shortcut... This is so lame! */
526                 name += strlen( name ) + 1;
527             }
528
529             /* If we are in "strict" mode and we couldn't
530              * find the module in the list of provided shortcuts,
531              * then kick the bastard out of here!!! */
532             if( b_strict )
533                 continue;
534         }
535
536         /* Trash <= 0 scored plugins (they can only be selected by shortcut) */
537         if( p_module->i_score <= 0 )
538             continue;
539
540 found_shortcut:
541         /* Store this new module */
542         p_list[count].p_module = module_hold (p_module);
543         p_list[count].i_score = p_module->i_score + i_shortcut_bonus;
544         p_list[count].b_force = i_shortcut_bonus && b_strict;
545         count++;
546     }
547
548     /* We can release the list, interesting modules are held */
549     module_list_free (p_all);
550
551     /* Sort candidates by descending score */
552     qsort (p_list, count, sizeof (p_list[0]), modulecmp);
553     msg_Dbg( p_this, "looking for %s module: %zu candidate%s", psz_capability,
554              count, count == 1 ? "" : "s" );
555
556     /* Parse the linked list and use the first successful module */
557     va_list args;
558
559     va_start(args, probe);
560     p_module = NULL;
561
562     for (size_t i = 0; (i < count) && (p_module == NULL); i++)
563     {
564         module_t *p_cand = p_list[i].p_module;
565 #ifdef HAVE_DYNAMIC_PLUGINS
566         /* Make sure the module is loaded in mem */
567         module_t *p_real = p_cand->parent ? p_cand->parent : p_cand;
568
569         if( !p_real->b_builtin && !p_real->b_loaded )
570         {
571             module_t *p_new_module =
572                 AllocatePlugin( p_this, p_real->psz_filename, false );
573             if( p_new_module == NULL )
574             {   /* Corrupted module */
575                 msg_Err( p_this, "possibly corrupt module cache" );
576                 module_release( p_cand );
577                 continue;
578             }
579             CacheMerge( p_this, p_real, p_new_module );
580             DeleteModule( p_module_bank, p_new_module );
581         }
582 #endif
583         p_this->b_force = p_list[i].b_force;
584
585         int ret;
586
587         if (likely(p_cand->pf_activate != NULL))
588         {
589             va_list ap;
590
591             va_copy(ap, args);
592             ret = probe(p_cand->pf_activate, ap);
593             va_end(ap);
594         }
595         else
596             ret = VLC_SUCCESS;
597
598         switch (ret)
599         {
600         case VLC_SUCCESS:
601             /* good module! */
602             p_module = p_cand;
603             break;
604
605         case VLC_ETIMEOUT:
606             /* good module, but aborted */
607             module_release( p_cand );
608             break;
609
610         default: /* bad module */
611             module_release( p_cand );
612             continue;
613         }
614
615         /* Release the remaining modules */
616         while (++i < count)
617             module_release (p_list[i].p_module);
618     }
619
620     va_end (args);
621     free( p_list );
622     p_this->b_force = b_force_backup;
623
624     if( p_module != NULL )
625     {
626         msg_Dbg( p_this, "using %s module \"%s\"",
627                  psz_capability, p_module->psz_object_name );
628         vlc_object_set_name( p_this, psz_alias ? psz_alias
629                                                : p_module->psz_object_name );
630     }
631     else if( count == 0 )
632         msg_Dbg( p_this, "no %s module matched \"%s\"",
633                  psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
634     else
635         msg_Dbg( p_this, "no %s module matching \"%s\" could be loaded",
636                   psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
637
638     free( psz_shortcuts );
639     free( psz_var );
640
641     stats_TimerStop( p_this, STATS_TIMER_MODULE_NEED );
642     stats_TimerDump( p_this, STATS_TIMER_MODULE_NEED );
643     stats_TimerClean( p_this, STATS_TIMER_MODULE_NEED );
644
645     /* Don't forget that the module is still locked */
646     return p_module;
647 }
648
649
650 /**
651  * Deinstantiates a module.
652  * \param module the module pointer as returned by vlc_module_load()
653  * \param deinit deactivation callback
654  */
655 void vlc_module_unload(module_t *module, vlc_deactivate_t deinit, ...)
656 {
657     if (module->pf_deactivate != NULL)
658     {
659         va_list ap;
660
661         va_start(ap, deinit);
662         deinit(module->pf_deactivate, ap);
663         va_end(ap);
664     }
665     module_release(module);
666 }
667
668
669 static int generic_start(void *func, va_list ap)
670 {
671     vlc_object_t *obj = va_arg(ap, vlc_object_t *);
672     int (*activate)(vlc_object_t *) = func;
673
674     return activate(obj);
675 }
676
677 static void generic_stop(void *func, va_list ap)
678 {
679     vlc_object_t *obj = va_arg(ap, vlc_object_t *);
680     void (*deactivate)(vlc_object_t *) = func;
681
682     deactivate(obj);
683 }
684
685 #undef module_need
686 module_t *module_need(vlc_object_t *obj, const char *cap, const char *name,
687                       bool strict)
688 {
689     return vlc_module_load(obj, cap, name, strict, generic_start, obj);
690 }
691
692 #undef module_unneed
693 void module_unneed(vlc_object_t *obj, module_t *module)
694 {
695     msg_Dbg(obj, "removing module \"%s\"", module->psz_object_name);
696     vlc_module_unload(module, generic_stop, obj);
697 }
698
699 /**
700  * Get a pointer to a module_t given it's name.
701  *
702  * \param psz_name the name of the module
703  * \return a pointer to the module or NULL in case of a failure
704  */
705 module_t *module_find( const char * psz_name )
706 {
707     module_t **list, *module;
708
709     list = module_list_get (NULL);
710     if (!list)
711         return NULL;
712
713     for (size_t i = 0; (module = list[i]) != NULL; i++)
714     {
715         const char *psz_module_name = module->psz_object_name;
716
717         if( psz_module_name && !strcmp( psz_module_name, psz_name ) )
718         {
719             module_hold (module);
720             break;
721         }
722     }
723     module_list_free (list);
724     return module;
725 }
726
727 /**
728  * Tell if a module exists and release it in thic case
729  *
730  * \param psz_name th name of the module
731  * \return TRUE if the module exists
732  */
733 bool module_exists (const char * psz_name)
734 {
735     module_t *p_module = module_find (psz_name);
736     if( p_module )
737         module_release (p_module);
738     return p_module != NULL;
739 }
740
741 /**
742  * Get a pointer to a module_t that matches a shortcut.
743  * This is a temporary hack for SD. Do not re-use (generally multiple modules
744  * can have the same shortcut, so this is *broken* - use module_need()!).
745  *
746  * \param psz_shortcut shortcut of the module
747  * \param psz_cap capability of the module
748  * \return a pointer to the module or NULL in case of a failure
749  */
750 module_t *module_find_by_shortcut (const char *psz_shortcut)
751 {
752     module_t **list, *module;
753
754     list = module_list_get (NULL);
755     if (!list)
756         return NULL;
757
758     for (size_t i = 0; (module = list[i]) != NULL; i++)
759     {
760         for (size_t j = 0; j < module->i_shortcuts; j++)
761         {
762             if (!strcmp (module->pp_shortcuts[j], psz_shortcut))
763             {
764                 module_hold (module);
765                 goto out;
766              }
767         }
768     }
769 out:
770     module_list_free (list);
771     return module;
772 }
773
774 /**
775  * Get the configuration of a module
776  *
777  * \param module the module
778  * \param psize the size of the configuration returned
779  * \return the configuration as an array
780  */
781 module_config_t *module_config_get( const module_t *module, unsigned *restrict psize )
782 {
783     unsigned i,j;
784     unsigned size = module->confsize;
785     module_config_t *config = malloc( size * sizeof( *config ) );
786
787     assert( psize != NULL );
788     *psize = 0;
789
790     if( !config )
791         return NULL;
792
793     for( i = 0, j = 0; i < size; i++ )
794     {
795         const module_config_t *item = module->p_config + i;
796         if( item->b_internal /* internal option */
797          || item->b_removed /* removed option */ )
798             continue;
799
800         memcpy( config + j, item, sizeof( *config ) );
801         j++;
802     }
803     *psize = j;
804
805     return config;
806 }
807
808 /**
809  * Release the configuration
810  *
811  * \param the configuration
812  * \return nothing
813  */
814 void module_config_free( module_config_t *config )
815 {
816     free( config );
817 }
818
819 /*****************************************************************************
820  * Following functions are local.
821  *****************************************************************************/
822
823 char *psz_vlcpath = NULL;
824
825 #ifdef HAVE_DYNAMIC_PLUGINS
826
827 /*****************************************************************************
828  * AllocateAllPlugins: load all plugin modules we can find.
829  *****************************************************************************/
830 static void AllocateAllPlugins( vlc_object_t *p_this, module_bank_t *p_bank )
831 {
832     const char *vlcpath = psz_vlcpath;
833     char *paths;
834     cache_mode_t mode;
835
836     if( !var_InheritBool( p_this, "plugins-cache" ) )
837         mode = CACHE_IGNORE;
838     else if( var_InheritBool( p_this, "reset-plugins-cache" ) )
839         mode = CACHE_RESET;
840     else
841         mode = CACHE_USE;
842
843     /* Contruct the special search path for system that have a relocatable
844      * executable. Set it to <vlc path>/plugins. */
845     assert( vlcpath );
846
847     if( asprintf( &paths, "%s" DIR_SEP "plugins", vlcpath ) != -1 )
848     {
849         AllocatePluginPath( p_this, p_bank, paths, mode );
850         free( paths );
851     }
852
853     /* If the user provided a plugin path, we add it to the list */
854     paths = getenv( "VLC_PLUGIN_PATH" );
855     if( paths == NULL )
856         return;
857
858     paths = strdup( paths ); /* don't harm the environment ! :) */
859     if( unlikely(paths == NULL) )
860         return;
861
862     for( char *buf, *path = strtok_r( paths, PATH_SEP, &buf );
863          path != NULL;
864          path = strtok_r( NULL, PATH_SEP, &buf ) )
865         AllocatePluginPath( p_this, p_bank, path, mode );
866
867     free( paths );
868 }
869
870 static void AllocatePluginPath( vlc_object_t *p_this, module_bank_t *p_bank,
871                                 const char *path, cache_mode_t mode )
872 {
873     module_cache_t **cache;
874     size_t count = 0;
875     size_t offset = p_module_bank->i_cache;
876
877     switch( mode )
878     {
879         case CACHE_USE:
880             count = CacheLoad( p_this, path, &cache );
881             break;
882         case CACHE_RESET:
883             CacheDelete( p_this, path );
884             break;
885         case CACHE_IGNORE:
886             msg_Dbg( p_this, "ignoring plugins cache file" );
887     }
888
889     msg_Dbg( p_this, "recursively browsing `%s'", path );
890
891     /* TODO: pass as argument, remove this hack */
892     p_bank->pp_loaded_cache = cache;
893     p_bank->i_loaded_cache = count;
894     /* Don't go deeper than 5 subdirectories */
895     AllocatePluginDir( p_this, p_bank, path, 5, mode );
896
897     switch( mode )
898     {
899         case CACHE_USE:
900             for( size_t i = 0; i < count; i++ )
901                 if( likely(cache[i] != NULL) )
902                 {
903                     if( cache[i]->p_module != NULL )
904                        DeleteModule( p_bank, cache[i]->p_module );
905                     free( cache[i]->path );
906                     free( cache[i] );
907                 }
908             free( cache );
909         case CACHE_RESET:
910             CacheSave( p_this, path, p_bank->pp_cache + offset,
911                        p_bank->i_cache - offset );
912         case CACHE_IGNORE:
913             break;
914     }
915 }
916
917 /*****************************************************************************
918  * AllocatePluginDir: recursively parse a directory to look for plugins
919  *****************************************************************************/
920 static void AllocatePluginDir( vlc_object_t *p_this, module_bank_t *p_bank,
921                                const char *psz_dir, unsigned i_maxdepth,
922                                cache_mode_t mode )
923 {
924     if( i_maxdepth == 0 )
925         return;
926
927     DIR *dh = vlc_opendir (psz_dir);
928     if (dh == NULL)
929         return;
930
931     /* Parse the directory and try to load all files it contains. */
932     for (;;)
933     {
934         char *file = vlc_readdir (dh), *path;
935         struct stat st;
936
937         if (file == NULL)
938             break;
939
940         /* Skip ".", ".." */
941         if (!strcmp (file, ".") || !strcmp (file, ".."))
942         {
943             free (file);
944             continue;
945         }
946
947         const int pathlen = asprintf (&path, "%s"DIR_SEP"%s", psz_dir, file);
948         free (file);
949         if (pathlen == -1 || vlc_stat (path, &st))
950             continue;
951
952         if (S_ISDIR (st.st_mode))
953             /* Recurse into another directory */
954             AllocatePluginDir (p_this, p_bank, path, i_maxdepth - 1, mode);
955         else
956         if (S_ISREG (st.st_mode)
957          && strncmp (path, "lib", 3)
958          && ((size_t)pathlen >= sizeof ("_plugin"LIBEXT))
959          && !strncasecmp (path + pathlen - strlen ("_plugin"LIBEXT),
960                           "_plugin"LIBEXT, strlen ("_plugni"LIBEXT)))
961             /* ^^ We only load files matching "lib*_plugin"LIBEXT */
962             AllocatePluginFile (p_this, p_bank, path, &st, mode);
963
964         free (path);
965     }
966     closedir (dh);
967 }
968
969 /*****************************************************************************
970  * AllocatePluginFile: load a module into memory and initialize it.
971  *****************************************************************************
972  * This function loads a dynamically loadable module and allocates a structure
973  * for its information data. The module can then be handled by module_need
974  * and module_unneed. It can be removed by DeleteModule.
975  *****************************************************************************/
976 static int AllocatePluginFile( vlc_object_t * p_this, module_bank_t *p_bank,
977                                const char *path, const struct stat *st,
978                                cache_mode_t mode )
979 {
980     module_t * p_module = NULL;
981
982     /* msg_Dbg( p_this, "plugin \"%s\", %s",
983                 p_module->psz_object_name, p_module->psz_longname ); */
984     /* Check our plugins cache first then load plugin if needed */
985     if( mode == CACHE_USE )
986         p_module = CacheFind (p_bank->pp_loaded_cache, p_bank->i_loaded_cache,
987                               path, st);
988     if( p_module == NULL )
989         p_module = AllocatePlugin( p_this, path, true );
990     if( p_module == NULL )
991         return -1;
992
993     /* We have not already scanned and inserted this module */
994     assert( p_module->next == NULL );
995
996     /* Unload plugin until we really need it */
997     assert( !p_module->b_builtin );
998     if( p_module->b_loaded && p_module->b_unloadable )
999     {
1000         module_Unload( p_module->handle );
1001         p_module->b_loaded = false;
1002     }
1003
1004     /* For now we force loading if the module's config contains
1005      * callbacks or actions.
1006      * Could be optimized by adding an API call.*/
1007     for( size_t n = p_module->confsize, i = 0; i < n; i++ )
1008          if( p_module->p_config[i].i_action )
1009          {
1010              /* !unloadable not allowed for plugins with callbacks */
1011              assert( !p_module->b_loaded );
1012              DeleteModule( p_bank, p_module );
1013              p_module = AllocatePlugin( p_this, path, false );
1014              break;
1015          }
1016
1017     p_module->next = p_bank->head;
1018     p_bank->head = p_module;
1019
1020     if( mode == CACHE_IGNORE )
1021         return 0;
1022
1023     /* Add entry to cache */
1024     module_cache_t **pp_cache = p_bank->pp_cache;
1025
1026     pp_cache = realloc_or_free( pp_cache, (p_bank->i_cache + 1) * sizeof(void *) );
1027     if( pp_cache == NULL )
1028         return -1;
1029     pp_cache[p_bank->i_cache] = malloc( sizeof(module_cache_t) );
1030     if( pp_cache[p_bank->i_cache] == NULL )
1031         return -1;
1032     pp_cache[p_bank->i_cache]->path = strdup( path );
1033     pp_cache[p_bank->i_cache]->mtime = st->st_mtime;
1034     pp_cache[p_bank->i_cache]->size = st->st_size;
1035     pp_cache[p_bank->i_cache]->p_module = p_module;
1036     p_bank->pp_cache = pp_cache;
1037     p_bank->i_cache++;
1038     return  0;
1039 }
1040
1041 /*****************************************************************************
1042  * AllocatePlugin: load a module into memory and initialize it.
1043  *****************************************************************************
1044  * This function loads a dynamically loadable module and allocates a structure
1045  * for its information data. The module can then be handled by module_need
1046  * and module_unneed. It can be removed by DeleteModule.
1047  *****************************************************************************/
1048 static module_t *AllocatePlugin( vlc_object_t * p_this, const char *psz_file,
1049                                  bool fast )
1050 {
1051     module_t * p_module = NULL;
1052     module_handle_t handle;
1053
1054     if( module_Load( p_this, psz_file, &handle, fast ) )
1055         return NULL;
1056
1057     /* Now that we have successfully loaded the module, we can
1058      * allocate a structure for it */
1059     p_module = vlc_module_create();
1060     if( p_module == NULL )
1061     {
1062         module_Unload( handle );
1063         return NULL;
1064     }
1065
1066     p_module->psz_filename = strdup( psz_file );
1067     p_module->handle = handle;
1068     p_module->b_loaded = true;
1069
1070     /* Initialize the module: fill p_module, default config */
1071     static const char entry[] = "vlc_entry" MODULE_SUFFIX;
1072
1073     /* Try to resolve the symbol */
1074     int (*pf_symbol)(module_t * p_module)
1075         = (int (*)(module_t *)) module_Lookup( p_module->handle,entry );
1076     if( pf_symbol == NULL )
1077     {
1078         msg_Warn( p_this, "cannot find symbol \"%s\" in plugin `%s'",
1079                   entry, psz_file );
1080         goto error;
1081     }
1082     else
1083     /* We can now try to call the symbol */
1084     if( pf_symbol( p_module ) != 0 )
1085     {
1086         /* With a well-written module we shouldn't have to print an
1087          * additional error message here, but just make sure. */
1088         msg_Err( p_this, "cannot initialize plugin `%s'", psz_file );
1089         goto error;
1090     }
1091
1092     DupModule( p_module );
1093     assert( !p_module->b_builtin );
1094     return p_module;
1095 error:
1096     free( p_module->psz_filename );
1097     module_release( p_module );
1098     module_Unload( handle );
1099     return NULL;
1100 }
1101
1102 /*****************************************************************************
1103  * DupModule: make a plugin module standalone.
1104  *****************************************************************************
1105  * This function duplicates all strings in the module, so that the dynamic
1106  * object can be unloaded. It acts recursively on submodules.
1107  *****************************************************************************/
1108 static void DupModule( module_t *p_module )
1109 {
1110     char **pp_shortcuts = p_module->pp_shortcuts;
1111     for( unsigned i = 0; i < p_module->i_shortcuts; i++ )
1112         pp_shortcuts[i] = strdup( p_module->pp_shortcuts[i] );
1113
1114     /* We strdup() these entries so that they are still valid when the
1115      * module is unloaded. */
1116     p_module->psz_capability = strdup( p_module->psz_capability );
1117     p_module->psz_shortname = p_module->psz_shortname ?
1118                                  strdup( p_module->psz_shortname ) : NULL;
1119     p_module->psz_longname = strdup( p_module->psz_longname );
1120     p_module->psz_help = p_module->psz_help ? strdup( p_module->psz_help )
1121                                             : NULL;
1122     p_module->domain = p_module->domain ? strdup( p_module->domain ) : NULL;
1123
1124     for (module_t *subm = p_module->submodule; subm; subm = subm->next)
1125         DupModule (subm);
1126 }
1127
1128 /*****************************************************************************
1129  * UndupModule: free a duplicated module.
1130  *****************************************************************************
1131  * This function frees the allocations done in DupModule().
1132  *****************************************************************************/
1133 static void UndupModule( module_t *p_module )
1134 {
1135     char **pp_shortcuts = p_module->pp_shortcuts;
1136
1137     for (module_t *subm = p_module->submodule; subm; subm = subm->next)
1138         UndupModule (subm);
1139
1140     for( unsigned i = 0; i < p_module->i_shortcuts; i++ )
1141         free( pp_shortcuts[i] );
1142
1143     free( p_module->psz_capability );
1144     FREENULL( p_module->psz_shortname );
1145     free( p_module->psz_longname );
1146     FREENULL( p_module->psz_help );
1147     free( p_module->domain );
1148 }
1149
1150 #endif /* HAVE_DYNAMIC_PLUGINS */
1151
1152 /*****************************************************************************
1153  * AllocateBuiltinModule: initialize a builtin module.
1154  *****************************************************************************
1155  * This function registers a builtin module and allocates a structure
1156  * for its information data. The module can then be handled by module_need
1157  * and module_unneed. It can be removed by DeleteModule.
1158  *****************************************************************************/
1159 static int AllocateBuiltinModule( vlc_object_t * p_this,
1160                                   int ( *pf_entry ) ( module_t * ) )
1161 {
1162     module_t * p_module;
1163
1164     /* Now that we have successfully loaded the module, we can
1165      * allocate a structure for it */
1166     p_module = vlc_module_create();
1167     if( p_module == NULL )
1168         return -1;
1169
1170     /* Initialize the module : fill p_module->psz_object_name, etc. */
1171     if( pf_entry( p_module ) != 0 )
1172     {
1173         /* With a well-written module we shouldn't have to print an
1174          * additional error message here, but just make sure. */
1175         msg_Err( p_this, "failed calling entry point in builtin module" );
1176         module_release( p_module );
1177         return -1;
1178     }
1179
1180     /* Everything worked fine ! The module is ready to be added to the list. */
1181     p_module->b_builtin = true;
1182     /* LOCK */
1183     p_module->next = p_module_bank->head;
1184     p_module_bank->head = p_module;
1185     /* UNLOCK */
1186
1187     /* msg_Dbg( p_this, "builtin \"%s\", %s",
1188                 p_module->psz_object_name, p_module->psz_longname ); */
1189
1190     return 0;
1191 }
1192
1193 /*****************************************************************************
1194  * DeleteModule: delete a module and its structure.
1195  *****************************************************************************
1196  * This function can only be called if the module isn't being used.
1197  *****************************************************************************/
1198 static void DeleteModule( module_bank_t *p_bank, module_t * p_module )
1199 {
1200     assert( p_module );
1201
1202     /* Unlist the module (if it is in the list) */
1203     module_t **pp_self = &p_bank->head;
1204     while (*pp_self != NULL && *pp_self != p_module)
1205         pp_self = &((*pp_self)->next);
1206     if (*pp_self)
1207         *pp_self = p_module->next;
1208
1209     /* We free the structures that we strdup()ed in Allocate*Module(). */
1210 #ifdef HAVE_DYNAMIC_PLUGINS
1211     if( !p_module->b_builtin )
1212     {
1213         if( p_module->b_loaded && p_module->b_unloadable )
1214         {
1215             module_Unload( p_module->handle );
1216         }
1217         UndupModule( p_module );
1218         free( p_module->psz_filename );
1219     }
1220 #endif
1221
1222     /* Free and detach the object's children */
1223     while (p_module->submodule)
1224     {
1225         module_t *submodule = p_module->submodule;
1226         p_module->submodule = submodule->next;
1227         module_release (submodule);
1228     }
1229
1230     config_Free( p_module );
1231     module_release( p_module );
1232 }