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