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