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