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