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