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