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