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