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