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