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