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