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