]> git.sesse.net Git - vlc/blob - src/modules/modules.c
Support different prototype for plugin open/close callbacks
[vlc] / src / modules / modules.c
1 /*****************************************************************************
2  * modules.c : Builtin and plugin modules management functions
3  *****************************************************************************
4  * Copyright (C) 2001-2011 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  *          RĂ©mi Denis-Courmont
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
26  *****************************************************************************/
27
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc_common.h>
33 #include <vlc_plugin.h>
34 #include <vlc_memory.h>
35 #include <vlc_modules.h>
36 #include "libvlc.h"
37
38 #include <stdlib.h>                                      /* free(), strtol() */
39 #include <stdio.h>                                              /* sprintf() */
40 #include <string.h>                                              /* strdup() */
41 #include <assert.h>
42
43 #include <sys/types.h>
44 #ifdef HAVE_SYS_STAT_H
45 #   include <sys/stat.h>
46 #endif
47 #ifdef HAVE_UNISTD_H
48 #   include <unistd.h>
49 #endif
50 #ifdef ENABLE_NLS
51 # include <libintl.h>
52 #endif
53
54 #include "config/configuration.h"
55
56 #include <vlc_fs.h>
57 #include "vlc_arrays.h"
58
59 #include "modules/modules.h"
60
61 static module_bank_t *p_module_bank = NULL;
62 static vlc_mutex_t module_lock = VLC_STATIC_MUTEX;
63
64 int vlc_entry__main( module_t * );
65
66 /*****************************************************************************
67  * Local prototypes
68  *****************************************************************************/
69 #ifdef HAVE_DYNAMIC_PLUGINS
70 static void AllocateAllPlugins( vlc_object_t *, module_bank_t * );
71 static void AllocatePluginDir( vlc_object_t *, module_bank_t *, const char *,
72                                unsigned );
73 static int  AllocatePluginFile( vlc_object_t *, module_bank_t *, const char *,
74                                 int64_t, int64_t );
75 static module_t * AllocatePlugin( vlc_object_t *, const char * );
76 #endif
77 static int  AllocateBuiltinModule( vlc_object_t *, int ( * ) ( module_t * ) );
78 static void DeleteModule ( module_bank_t *, module_t * );
79 #ifdef HAVE_DYNAMIC_PLUGINS
80 static void   DupModule        ( module_t * );
81 static void   UndupModule      ( module_t * );
82 #endif
83
84 #undef module_InitBank
85 /**
86  * Init bank
87  *
88  * Creates a module bank structure which will be filled later
89  * on with all the modules found.
90  * \param p_this vlc object structure
91  * \return nothing
92  */
93 void module_InitBank( vlc_object_t *p_this )
94 {
95     module_bank_t *p_bank = NULL;
96
97     vlc_mutex_lock( &module_lock );
98
99     if( p_module_bank == NULL )
100     {
101         p_bank = calloc (1, sizeof(*p_bank));
102         p_bank->i_usage = 1;
103         p_bank->i_cache = p_bank->i_loaded_cache = 0;
104         p_bank->pp_cache = p_bank->pp_loaded_cache = NULL;
105         p_bank->b_cache = p_bank->b_cache_dirty = false;
106         p_bank->head = NULL;
107
108         /* Everything worked, attach the object */
109         p_module_bank = p_bank;
110
111         /* Fills the module bank structure with the main module infos.
112          * This is very useful as it will allow us to consider the main
113          * library just as another module, and for instance the configuration
114          * options of main will be available in the module bank structure just
115          * as for every other module. */
116         AllocateBuiltinModule( p_this, vlc_entry__main );
117         vlc_rwlock_init (&config_lock);
118         config_SortConfig ();
119     }
120     else
121         p_module_bank->i_usage++;
122
123     /* We do retain the module bank lock until the plugins are loaded as well.
124      * This is ugly, this staged loading approach is needed: LibVLC gets
125      * some configuration parameters relevant to loading the plugins from
126      * the main (builtin) module. The module bank becomes shared read-only data
127      * once it is ready, so we need to fully serialize initialization.
128      * DO NOT UNCOMMENT the following line unless you managed to squeeze
129      * module_LoadPlugins() before you unlock the mutex. */
130     /*vlc_mutex_unlock( &module_lock );*/
131 }
132
133 #undef module_EndBank
134 /**
135  * Unloads all unused plugin modules and empties the module
136  * bank in case of success.
137  * \param p_this vlc object structure
138  * \return nothing
139  */
140 void module_EndBank( vlc_object_t *p_this, bool b_plugins )
141 {
142     module_bank_t *p_bank = p_module_bank;
143
144     assert (p_bank != NULL);
145
146     /* Save the configuration */
147     if( !var_InheritBool( p_this, "ignore-config" ) )
148         config_AutoSaveConfigFile( p_this );
149
150     /* If plugins were _not_ loaded, then the caller still has the bank lock
151      * from module_InitBank(). */
152     if( b_plugins )
153         vlc_mutex_lock( &module_lock );
154     /*else
155         vlc_assert_locked( &module_lock ); not for static mutexes :( */
156
157     if( --p_bank->i_usage > 0 )
158     {
159         vlc_mutex_unlock( &module_lock );
160         return;
161     }
162
163     config_UnsortConfig ();
164     vlc_rwlock_destroy (&config_lock);
165     p_module_bank = NULL;
166     vlc_mutex_unlock( &module_lock );
167
168 #ifdef HAVE_DYNAMIC_PLUGINS
169     while( p_bank->i_loaded_cache-- )
170     {
171         if( p_bank->pp_loaded_cache[p_bank->i_loaded_cache] )
172         {
173             DeleteModule( p_bank,
174                     p_bank->pp_loaded_cache[p_bank->i_loaded_cache]->p_module );
175             free( p_bank->pp_loaded_cache[p_bank->i_loaded_cache]->psz_file );
176             free( p_bank->pp_loaded_cache[p_bank->i_loaded_cache] );
177         }
178     }
179     free( p_bank->pp_loaded_cache );
180     while( p_bank->i_cache-- )
181     {
182         free( p_bank->pp_cache[p_bank->i_cache]->psz_file );
183         free( p_bank->pp_cache[p_bank->i_cache] );
184     }
185     free( p_bank->pp_cache );
186 #endif
187
188     while( p_bank->head != NULL )
189         DeleteModule( p_bank, p_bank->head );
190
191     free( p_bank );
192 }
193
194 #undef module_LoadPlugins
195 /**
196  * Loads module descriptions for all available plugins.
197  * Fills the module bank structure with the plugin modules.
198  *
199  * \param p_this vlc object structure
200  * \return nothing
201  */
202 void module_LoadPlugins( vlc_object_t * p_this, const void **builtins )
203 {
204     module_bank_t *p_bank = p_module_bank;
205
206     assert( p_bank );
207     /*vlc_assert_locked( &module_lock ); not for static mutexes :( */
208
209     if (builtins)
210     {
211         for (int i = 0; builtins[i]; i++)
212             AllocateBuiltinModule( p_this, builtins[i] );
213     }
214
215 #ifdef HAVE_DYNAMIC_PLUGINS
216     if( p_bank->i_usage == 1 )
217     {
218         msg_Dbg( p_this, "checking plugin modules" );
219         p_module_bank->b_cache = var_InheritBool( p_this, "plugins-cache" );
220
221         AllocateAllPlugins( p_this, p_module_bank );
222         config_UnsortConfig ();
223         config_SortConfig ();
224     }
225 #endif
226     vlc_mutex_unlock( &module_lock );
227 }
228
229 /**
230  * Checks whether a module implements a capability.
231  *
232  * \param m the module
233  * \param cap the capability to check
234  * \return TRUE if the module have the capability
235  */
236 bool module_provides( const module_t *m, const char *cap )
237 {
238     return !strcmp( m->psz_capability, cap );
239 }
240
241 /**
242  * Get the internal name of a module
243  *
244  * \param m the module
245  * \return the module name
246  */
247 const char *module_get_object( const module_t *m )
248 {
249     return m->psz_object_name;
250 }
251
252 /**
253  * Get the human-friendly name of a module.
254  *
255  * \param m the module
256  * \param long_name TRUE to have the long name of the module
257  * \return the short or long name of the module
258  */
259 const char *module_get_name( const module_t *m, bool long_name )
260 {
261     if( long_name && ( m->psz_longname != NULL) )
262         return m->psz_longname;
263
264     return m->psz_shortname ? m->psz_shortname : m->psz_object_name;
265 }
266
267 /**
268  * Get the help for a module
269  *
270  * \param m the module
271  * \return the help
272  */
273 const char *module_get_help( const module_t *m )
274 {
275     return m->psz_help;
276 }
277
278 /**
279  * Get the capability for a module
280  *
281  * \param m the module
282  * return the capability
283  */
284 const char *module_get_capability( const module_t *m )
285 {
286     return m->psz_capability;
287 }
288
289 /**
290  * Get the score for a module
291  *
292  * \param m the module
293  * return the score for the capability
294  */
295 int module_get_score( const module_t *m )
296 {
297     return m->i_score;
298 }
299
300 /**
301  * Translate a string using the module's text domain
302  *
303  * \param m the module
304  * \param str the American English ASCII string to localize
305  * \return the gettext-translated string
306  */
307 const char *module_gettext (const module_t *m, const char *str)
308 {
309 #ifdef ENABLE_NLS
310     const char *domain = m->domain ? m->domain : PACKAGE_NAME;
311     if (unlikely(str == NULL || *str == '\0'))
312         return "";
313     return dgettext (domain, str);
314 #else
315     (void)m;
316     return str;
317 #endif
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 #undef module_start
332 int module_start (vlc_object_t *obj, module_t *m)
333 {
334    int (*activate) (vlc_object_t *) = m->pf_activate;
335
336    return (activate != NULL) ? activate (obj) : VLC_SUCCESS;
337 }
338
339 #undef module_stop
340 void module_stop (vlc_object_t *obj, module_t *m)
341 {
342    void (*deactivate) (vlc_object_t *) = m->pf_deactivate;
343
344     if (deactivate != NULL)
345         deactivate (obj);
346 }
347
348 /**
349  * Frees the flat list of VLC modules.
350  * @param list list obtained by module_list_get()
351  * @param length number of items on the list
352  * @return nothing.
353  */
354 void module_list_free (module_t **list)
355 {
356     if (list == NULL)
357         return;
358
359     for (size_t i = 0; list[i] != NULL; i++)
360          module_release (list[i]);
361     free (list);
362 }
363
364 /**
365  * Gets the flat list of VLC modules.
366  * @param n [OUT] pointer to the number of modules or NULL
367  * @return NULL-terminated table of module pointers
368  *         (release with module_list_free()), or NULL in case of error.
369  */
370 module_t **module_list_get (size_t *n)
371 {
372     /* TODO: this whole module lookup is quite inefficient */
373     /* Remove this and improve module_need */
374     module_t **tab = NULL;
375     size_t i = 0;
376
377     assert (p_module_bank);
378     for (module_t *mod = p_module_bank->head; mod; mod = mod->next)
379     {
380          module_t **nt;
381          nt  = realloc (tab, (i + 2 + mod->submodule_count) * sizeof (*tab));
382          if (nt == NULL)
383          {
384              module_list_free (tab);
385              return NULL;
386          }
387
388          tab = nt;
389          tab[i++] = module_hold (mod);
390          for (module_t *subm = mod->submodule; subm; subm = subm->next)
391              tab[i++] = module_hold (subm);
392          tab[i] = NULL;
393     }
394     if (n != NULL)
395         *n = i;
396     return tab;
397 }
398
399 typedef struct module_list_t
400 {
401     module_t *p_module;
402     int16_t  i_score;
403     bool     b_force;
404 } module_list_t;
405
406 static int modulecmp (const void *a, const void *b)
407 {
408     const module_list_t *la = a, *lb = b;
409     /* Note that qsort() uses _ascending_ order,
410      * so the smallest module is the one with the biggest score. */
411     return lb->i_score - la->i_score;
412 }
413
414 #undef vlc_module_load
415 /**
416  * Finds and instantiates the best module of a certain type.
417  * All candidates modules having the specified capability and name will be
418  * sorted in decreasing order of priority. Then the probe callback will be
419  * invoked for each module, until it succeeds (returns 0), or all candidate
420  * module failed to initialize.
421  *
422  * The probe callback first parameter is the address of the module entry point.
423  * Further parameters are passed as an argument list; it corresponds to the
424  * variable arguments passed to this function. This scheme is meant to
425  * support arbitrary prototypes for the module entry point.
426  *
427  * \param p_this VLC object
428  * \param psz_capability capability, i.e. class of module
429  * \param psz_name name name of the module asked, if any
430  * \param b_strict if true, do not fallback to plugin with a different name
431  *                 but the same capability
432  * \param probe module probe callback
433  * \return the module or NULL in case of a failure
434  */
435 module_t *vlc_module_load(vlc_object_t *p_this, const char *psz_capability,
436                           const char *psz_name, bool b_strict,
437                           vlc_activate_t probe, ...)
438 {
439     stats_TimerStart( p_this, "module_need()", STATS_TIMER_MODULE_NEED );
440
441     module_list_t *p_list;
442     module_t *p_module;
443     int i_shortcuts = 0;
444     char *psz_shortcuts = NULL, *psz_var = NULL, *psz_alias = NULL;
445     bool b_force_backup = p_this->b_force;
446
447     /* Deal with variables */
448     if( psz_name && psz_name[0] == '$' )
449     {
450         psz_name = psz_var = var_CreateGetString( p_this, psz_name + 1 );
451     }
452
453     /* Count how many different shortcuts were asked for */
454     if( psz_name && *psz_name )
455     {
456         char *psz_parser, *psz_last_shortcut;
457
458         /* If the user wants none, give him none. */
459         if( !strcmp( psz_name, "none" ) )
460         {
461             free( psz_var );
462             stats_TimerStop( p_this, STATS_TIMER_MODULE_NEED );
463             stats_TimerDump( p_this, STATS_TIMER_MODULE_NEED );
464             stats_TimerClean( p_this, STATS_TIMER_MODULE_NEED );
465             return NULL;
466         }
467
468         i_shortcuts++;
469         psz_parser = psz_shortcuts = psz_last_shortcut = strdup( psz_name );
470
471         while( ( psz_parser = strchr( psz_parser, ',' ) ) )
472         {
473              *psz_parser = '\0';
474              i_shortcuts++;
475              psz_last_shortcut = ++psz_parser;
476         }
477
478         /* Check if the user wants to override the "strict" mode */
479         if( psz_last_shortcut )
480         {
481             if( !strcmp(psz_last_shortcut, "none") )
482             {
483                 b_strict = true;
484                 i_shortcuts--;
485             }
486             else if( !strcmp(psz_last_shortcut, "any") )
487             {
488                 b_strict = false;
489                 i_shortcuts--;
490             }
491         }
492     }
493
494     /* Sort the modules and test them */
495     size_t count;
496     module_t **p_all = module_list_get (&count);
497     p_list = malloc( count * sizeof( module_list_t ) );
498
499     /* Parse the module list for capabilities and probe each of them */
500     count = 0;
501     for (size_t i = 0; (p_module = p_all[i]) != NULL; i++)
502     {
503         int i_shortcut_bonus = 0;
504
505         /* Test that this module can do what we need */
506         if( !module_provides( p_module, psz_capability ) )
507             continue;
508
509         /* If we required a shortcut, check this plugin provides it. */
510         if( i_shortcuts > 0 )
511         {
512             const char *name = psz_shortcuts;
513
514             for( unsigned i_short = i_shortcuts; i_short > 0; i_short-- )
515             {
516                 for( unsigned i = 0; i < p_module->i_shortcuts; i++ )
517                 {
518                     char *c;
519                     if( ( c = strchr( name, '@' ) )
520                         ? !strncasecmp( name, p_module->pp_shortcuts[i],
521                                         c-name )
522                         : !strcasecmp( name, p_module->pp_shortcuts[i] ) )
523                     {
524                         /* Found it */
525                         if( c && c[1] )
526                             psz_alias = c+1;
527                         i_shortcut_bonus = i_short * 10000;
528                         goto found_shortcut;
529                     }
530                 }
531
532                 /* Go to the next shortcut... This is so lame! */
533                 name += strlen( name ) + 1;
534             }
535
536             /* If we are in "strict" mode and we couldn't
537              * find the module in the list of provided shortcuts,
538              * then kick the bastard out of here!!! */
539             if( b_strict )
540                 continue;
541         }
542
543         /* Trash <= 0 scored plugins (they can only be selected by shortcut) */
544         if( p_module->i_score <= 0 )
545             continue;
546
547 found_shortcut:
548         /* Store this new module */
549         p_list[count].p_module = module_hold (p_module);
550         p_list[count].i_score = p_module->i_score + i_shortcut_bonus;
551         p_list[count].b_force = i_shortcut_bonus && b_strict;
552         count++;
553     }
554
555     /* We can release the list, interesting modules are held */
556     module_list_free (p_all);
557
558     /* Sort candidates by descending score */
559     qsort (p_list, count, sizeof (p_list[0]), modulecmp);
560     msg_Dbg( p_this, "looking for %s module: %zu candidate%s", psz_capability,
561              count, count == 1 ? "" : "s" );
562
563     /* Parse the linked list and use the first successful module */
564     va_list args;
565
566     va_start(args, probe);
567     p_module = NULL;
568
569     for (size_t i = 0; (i < count) && (p_module == NULL); i++)
570     {
571         module_t *p_cand = p_list[i].p_module;
572 #ifdef HAVE_DYNAMIC_PLUGINS
573         /* Make sure the module is loaded in mem */
574         module_t *p_real = p_cand->b_submodule ? p_cand->parent : p_cand;
575
576         if( !p_real->b_builtin && !p_real->b_loaded )
577         {
578             module_t *p_new_module =
579                 AllocatePlugin( p_this, p_real->psz_filename );
580             if( p_new_module == NULL )
581             {   /* Corrupted module */
582                 msg_Err( p_this, "possibly corrupt module cache" );
583                 module_release( p_cand );
584                 continue;
585             }
586             CacheMerge( p_this, p_real, p_new_module );
587             DeleteModule( p_module_bank, p_new_module );
588         }
589 #endif
590         p_this->b_force = p_list[i].b_force;
591
592         int ret;
593
594         if (likely(p_cand->pf_activate != NULL))
595         {
596             va_list ap;
597
598             va_copy(ap, args);
599             ret = probe(p_cand->pf_activate, ap);
600             va_end(ap);
601         }
602         else
603             ret = VLC_SUCCESS;
604
605         switch (ret)
606         {
607         case VLC_SUCCESS:
608             /* good module! */
609             p_module = p_cand;
610             break;
611
612         case VLC_ETIMEOUT:
613             /* good module, but aborted */
614             module_release( p_cand );
615             break;
616
617         default: /* bad module */
618             module_release( p_cand );
619             continue;
620         }
621
622         /* Release the remaining modules */
623         while (++i < count)
624             module_release (p_list[i].p_module);
625     }
626
627     va_end (args);
628     free( p_list );
629     p_this->b_force = b_force_backup;
630
631     if( p_module != NULL )
632     {
633         msg_Dbg( p_this, "using %s module \"%s\"",
634                  psz_capability, p_module->psz_object_name );
635         vlc_object_set_name( p_this, psz_alias ? psz_alias
636                                                : p_module->psz_object_name );
637     }
638     else if( count == 0 )
639         msg_Dbg( p_this, "no %s module matched \"%s\"",
640                  psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
641     else
642         msg_Dbg( p_this, "no %s module matching \"%s\" could be loaded",
643                   psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
644
645     free( psz_shortcuts );
646     free( psz_var );
647
648     stats_TimerStop( p_this, STATS_TIMER_MODULE_NEED );
649     stats_TimerDump( p_this, STATS_TIMER_MODULE_NEED );
650     stats_TimerClean( p_this, STATS_TIMER_MODULE_NEED );
651
652     /* Don't forget that the module is still locked */
653     return p_module;
654 }
655
656
657 /**
658  * Deinstantiates a module.
659  * \param module the module pointer as returned by vlc_module_load()
660  * \param deinit deactivation callback
661  */
662 void vlc_module_unload(module_t *module, vlc_deactivate_t deinit, ...)
663 {
664     if (module->pf_deactivate != NULL)
665     {
666         va_list ap;
667
668         va_start(ap, deinit);
669         deinit(module->pf_deactivate, ap);
670         va_end(ap);
671     }
672     module_release(module);
673 }
674
675
676 static int generic_start(void *func, va_list ap)
677 {
678     vlc_object_t *obj = va_arg(ap, vlc_object_t *);
679     int (*activate)(vlc_object_t *) = func;
680
681     return activate(obj);
682 }
683
684 static void generic_stop(void *func, va_list ap)
685 {
686     vlc_object_t *obj = va_arg(ap, vlc_object_t *);
687     void (*deactivate)(vlc_object_t *) = func;
688
689     deactivate(obj);
690 }
691
692 #undef module_need
693 module_t *module_need(vlc_object_t *obj, const char *cap, const char *name,
694                       bool strict)
695 {
696     return vlc_module_load(obj, cap, name, strict, generic_start, obj);
697 }
698
699 #undef module_unneed
700 void module_unneed(vlc_object_t *obj, module_t *module)
701 {
702     msg_Dbg(obj, "removing module \"%s\"", module->psz_object_name);
703     vlc_module_unload(module, generic_stop, obj);
704 }
705
706 /**
707  * Get a pointer to a module_t given it's name.
708  *
709  * \param psz_name the name of the module
710  * \return a pointer to the module or NULL in case of a failure
711  */
712 module_t *module_find( const char * psz_name )
713 {
714     module_t **list, *module;
715
716     list = module_list_get (NULL);
717     if (!list)
718         return NULL;
719
720     for (size_t i = 0; (module = list[i]) != NULL; i++)
721     {
722         const char *psz_module_name = module->psz_object_name;
723
724         if( psz_module_name && !strcmp( psz_module_name, psz_name ) )
725         {
726             module_hold (module);
727             break;
728         }
729     }
730     module_list_free (list);
731     return module;
732 }
733
734 /**
735  * Tell if a module exists and release it in thic case
736  *
737  * \param psz_name th name of the module
738  * \return TRUE if the module exists
739  */
740 bool module_exists (const char * psz_name)
741 {
742     module_t *p_module = module_find (psz_name);
743     if( p_module )
744         module_release (p_module);
745     return p_module != NULL;
746 }
747
748 /**
749  * Get a pointer to a module_t that matches a shortcut.
750  * This is a temporary hack for SD. Do not re-use (generally multiple modules
751  * can have the same shortcut, so this is *broken* - use module_need()!).
752  *
753  * \param psz_shortcut shortcut of the module
754  * \param psz_cap capability of the module
755  * \return a pointer to the module or NULL in case of a failure
756  */
757 module_t *module_find_by_shortcut (const char *psz_shortcut)
758 {
759     module_t **list, *module;
760
761     list = module_list_get (NULL);
762     if (!list)
763         return NULL;
764
765     for (size_t i = 0; (module = list[i]) != NULL; i++)
766     {
767         for (size_t j = 0; j < module->i_shortcuts; j++)
768         {
769             if (!strcmp (module->pp_shortcuts[j], psz_shortcut))
770             {
771                 module_hold (module);
772                 goto out;
773              }
774         }
775     }
776 out:
777     module_list_free (list);
778     return module;
779 }
780
781 /**
782  * Get the configuration of a module
783  *
784  * \param module the module
785  * \param psize the size of the configuration returned
786  * \return the configuration as an array
787  */
788 module_config_t *module_config_get( const module_t *module, unsigned *restrict psize )
789 {
790     unsigned i,j;
791     unsigned size = module->confsize;
792     module_config_t *config = malloc( size * sizeof( *config ) );
793
794     assert( psize != NULL );
795     *psize = 0;
796
797     if( !config )
798         return NULL;
799
800     for( i = 0, j = 0; i < size; i++ )
801     {
802         const module_config_t *item = module->p_config + i;
803         if( item->b_internal /* internal option */
804          || item->b_removed /* removed option */ )
805             continue;
806
807         memcpy( config + j, item, sizeof( *config ) );
808         j++;
809     }
810     *psize = j;
811
812     return config;
813 }
814
815 /**
816  * Release the configuration
817  *
818  * \param the configuration
819  * \return nothing
820  */
821 void module_config_free( module_config_t *config )
822 {
823     free( config );
824 }
825
826 /*****************************************************************************
827  * Following functions are local.
828  *****************************************************************************/
829
830  /*****************************************************************************
831  * copy_next_paths_token: from a PATH_SEP_CHAR (a ':' or a ';') separated paths
832  * return first path.
833  *****************************************************************************/
834 static char * copy_next_paths_token( char * paths, char ** remaining_paths )
835 {
836     char * path;
837     int i, done;
838     bool escaped = false;
839
840     assert( paths );
841
842     /* Alloc a buffer to store the path */
843     path = malloc( strlen( paths ) + 1 );
844     if( !path ) return NULL;
845
846     /* Look for PATH_SEP_CHAR (a ':' or a ';') */
847     for( i = 0, done = 0 ; paths[i]; i++ )
848     {
849         /* Take care of \\ and \: or \; escapement */
850         if( escaped )
851         {
852             escaped = false;
853             path[done++] = paths[i];
854         }
855 #ifdef WIN32
856         else if( paths[i] == '/' )
857             escaped = true;
858 #else
859         else if( paths[i] == '\\' )
860             escaped = true;
861 #endif
862         else if( paths[i] == PATH_SEP_CHAR )
863             break;
864         else
865             path[done++] = paths[i];
866     }
867     path[done] = 0;
868
869     /* Return the remaining paths */
870     if( remaining_paths ) {
871         *remaining_paths = paths[i] ? &paths[i]+1 : NULL;
872     }
873
874     return path;
875 }
876
877 char *psz_vlcpath = NULL;
878
879 /*****************************************************************************
880  * AllocateAllPlugins: load all plugin modules we can find.
881  *****************************************************************************/
882 #ifdef HAVE_DYNAMIC_PLUGINS
883 static void AllocateAllPlugins( vlc_object_t *p_this, module_bank_t *p_bank )
884 {
885     const char *vlcpath = psz_vlcpath;
886     int count,i;
887     char * path;
888     vlc_array_t *arraypaths = vlc_array_new();
889     const bool b_reset = var_InheritBool( p_this, "reset-plugins-cache" );
890
891     /* Contruct the special search path for system that have a relocatable
892      * executable. Set it to <vlc path>/plugins. */
893     assert( vlcpath );
894
895     if( asprintf( &path, "%s" DIR_SEP "plugins", vlcpath ) != -1 )
896         vlc_array_append( arraypaths, path );
897
898     /* If the user provided a plugin path, we add it to the list */
899     char *userpaths = var_InheritString( p_this, "plugin-path" );
900     char *paths_iter;
901
902     for( paths_iter = userpaths; paths_iter; )
903     {
904         path = copy_next_paths_token( paths_iter, &paths_iter );
905         if( path )
906             vlc_array_append( arraypaths, path );
907     }
908
909     count = vlc_array_count( arraypaths );
910     for( i = 0 ; i < count ; i++ )
911     {
912         path = vlc_array_item_at_index( arraypaths, i );
913         if( !path )
914             continue;
915
916         size_t offset = p_module_bank->i_cache;
917         if( b_reset )
918             CacheDelete( p_this, path );
919         else
920             CacheLoad( p_this, p_module_bank, path );
921
922         msg_Dbg( p_this, "recursively browsing `%s'", path );
923
924         /* Don't go deeper than 5 subdirectories */
925         AllocatePluginDir( p_this, p_bank, path, 5 );
926
927
928         CacheSave( p_this, path, p_module_bank->pp_cache + offset,
929                    p_module_bank->i_cache - offset );
930         free( path );
931     }
932
933     vlc_array_destroy( arraypaths );
934     free( userpaths );
935 }
936
937 /*****************************************************************************
938  * AllocatePluginDir: recursively parse a directory to look for plugins
939  *****************************************************************************/
940 static void AllocatePluginDir( vlc_object_t *p_this, module_bank_t *p_bank,
941                                const char *psz_dir, unsigned i_maxdepth )
942 {
943     if( i_maxdepth == 0 )
944         return;
945
946     DIR *dh = vlc_opendir (psz_dir);
947     if (dh == NULL)
948         return;
949
950     /* Parse the directory and try to load all files it contains. */
951     for (;;)
952     {
953         char *file = vlc_readdir (dh), *path;
954         struct stat st;
955
956         if (file == NULL)
957             break;
958
959         /* Skip ".", ".." */
960         if (!strcmp (file, ".") || !strcmp (file, "..")
961         /* Skip directories for unsupported optimizations */
962          || !vlc_CPU_CheckPluginDir (file))
963         {
964             free (file);
965             continue;
966         }
967
968         const int pathlen = asprintf (&path, "%s"DIR_SEP"%s", psz_dir, file);
969         free (file);
970         if (pathlen == -1 || vlc_stat (path, &st))
971             continue;
972
973         if (S_ISDIR (st.st_mode))
974             /* Recurse into another directory */
975             AllocatePluginDir (p_this, p_bank, path, i_maxdepth - 1);
976         else
977         if (S_ISREG (st.st_mode)
978          && strncmp (path, "lib", 3)
979          && ((size_t)pathlen >= sizeof ("_plugin"LIBEXT))
980          && !strncasecmp (path + pathlen - strlen ("_plugin"LIBEXT),
981                           "_plugin"LIBEXT, strlen ("_plugni"LIBEXT)))
982             /* ^^ We only load files matching "lib*_plugin"LIBEXT */
983             AllocatePluginFile (p_this, p_bank, path, st.st_mtime, st.st_size);
984
985         free (path);
986     }
987     closedir (dh);
988 }
989
990 /*****************************************************************************
991  * AllocatePluginFile: load a module into memory and initialize it.
992  *****************************************************************************
993  * This function loads a dynamically loadable module and allocates a structure
994  * for its information data. The module can then be handled by module_need
995  * and module_unneed. It can be removed by DeleteModule.
996  *****************************************************************************/
997 static int AllocatePluginFile( vlc_object_t * p_this, module_bank_t *p_bank,
998                                const char *psz_file,
999                                int64_t i_file_time, int64_t i_file_size )
1000 {
1001     module_t * p_module = NULL;
1002     module_cache_t *p_cache_entry = NULL;
1003
1004     /*
1005      * Check our plugins cache first then load plugin if needed
1006      */
1007     p_cache_entry = CacheFind( p_bank, psz_file, i_file_time, i_file_size );
1008     if( !p_cache_entry )
1009     {
1010         p_module = AllocatePlugin( p_this, psz_file );
1011     }
1012     else
1013     {
1014         module_config_t *p_item = NULL, *p_end = NULL;
1015
1016         p_module = p_cache_entry->p_module;
1017         p_module->b_loaded = false;
1018
1019         /* If plugin-path contains duplicate entries... */
1020         if( p_module->next != NULL )
1021             return 0; /* already taken care of that one */
1022
1023         /* For now we force loading if the module's config contains
1024          * callbacks or actions.
1025          * Could be optimized by adding an API call.*/
1026         for( p_item = p_module->p_config, p_end = p_item + p_module->confsize;
1027              p_item < p_end; p_item++ )
1028         {
1029             if( p_item->i_action )
1030             {
1031                 p_module = AllocatePlugin( p_this, psz_file );
1032                 break;
1033             }
1034         }
1035     }
1036
1037     if( p_module == NULL )
1038         return -1;
1039
1040     /* We have not already scanned and inserted this module */
1041     assert( p_module->next == NULL );
1042
1043     /* Everything worked fine !
1044      * The module is ready to be added to the list. */
1045     p_module->b_builtin = false;
1046
1047     /* msg_Dbg( p_this, "plugin \"%s\", %s",
1048                 p_module->psz_object_name, p_module->psz_longname ); */
1049     p_module->next = p_bank->head;
1050     p_bank->head = p_module;
1051     assert( p_module->next != NULL ); /* Insertion done */
1052
1053     if( !p_module_bank->b_cache )
1054         return 0;
1055
1056     /* Add entry to cache */
1057     module_cache_t **pp_cache = p_bank->pp_cache;
1058
1059     pp_cache = realloc_or_free( pp_cache, (p_bank->i_cache + 1) * sizeof(void *) );
1060     if( pp_cache == NULL )
1061         return -1;
1062     pp_cache[p_bank->i_cache] = malloc( sizeof(module_cache_t) );
1063     if( pp_cache[p_bank->i_cache] == NULL )
1064         return -1;
1065     pp_cache[p_bank->i_cache]->psz_file = strdup( psz_file );
1066     pp_cache[p_bank->i_cache]->i_time = i_file_time;
1067     pp_cache[p_bank->i_cache]->i_size = i_file_size;
1068     pp_cache[p_bank->i_cache]->p_module = p_module;
1069     p_bank->pp_cache = pp_cache;
1070     p_bank->i_cache++;
1071     return  0;
1072 }
1073
1074 /*****************************************************************************
1075  * AllocatePlugin: load a module into memory and initialize it.
1076  *****************************************************************************
1077  * This function loads a dynamically loadable module and allocates a structure
1078  * for its information data. The module can then be handled by module_need
1079  * and module_unneed. It can be removed by DeleteModule.
1080  *****************************************************************************/
1081 static module_t * AllocatePlugin( vlc_object_t * p_this, const char *psz_file )
1082 {
1083     module_t * p_module = NULL;
1084     module_handle_t handle;
1085
1086     if( module_Load( p_this, psz_file, &handle ) )
1087         return NULL;
1088
1089     /* Now that we have successfully loaded the module, we can
1090      * allocate a structure for it */
1091     p_module = vlc_module_create( p_this );
1092     if( p_module == NULL )
1093     {
1094         module_Unload( handle );
1095         return NULL;
1096     }
1097
1098     p_module->psz_filename = strdup( psz_file );
1099     p_module->handle = handle;
1100     p_module->b_loaded = true;
1101
1102     /* Initialize the module: fill p_module, default config */
1103     if( module_Call( p_this, p_module ) != 0 )
1104     {
1105         /* We couldn't call module_init() */
1106         free( p_module->psz_filename );
1107         module_release( p_module );
1108         module_Unload( handle );
1109         return NULL;
1110     }
1111
1112     DupModule( p_module );
1113
1114     /* Everything worked fine ! The module is ready to be added to the list. */
1115     p_module->b_builtin = false;
1116
1117     return p_module;
1118 }
1119
1120 /*****************************************************************************
1121  * DupModule: make a plugin module standalone.
1122  *****************************************************************************
1123  * This function duplicates all strings in the module, so that the dynamic
1124  * object can be unloaded. It acts recursively on submodules.
1125  *****************************************************************************/
1126 static void DupModule( module_t *p_module )
1127 {
1128     char **pp_shortcuts = p_module->pp_shortcuts;
1129     for( unsigned i = 0; i < p_module->i_shortcuts; i++ )
1130         pp_shortcuts[i] = strdup( p_module->pp_shortcuts[i] );
1131
1132     /* We strdup() these entries so that they are still valid when the
1133      * module is unloaded. */
1134     p_module->psz_capability = strdup( p_module->psz_capability );
1135     p_module->psz_shortname = p_module->psz_shortname ?
1136                                  strdup( p_module->psz_shortname ) : NULL;
1137     p_module->psz_longname = strdup( p_module->psz_longname );
1138     p_module->psz_help = p_module->psz_help ? strdup( p_module->psz_help )
1139                                             : NULL;
1140     p_module->domain = p_module->domain ? strdup( p_module->domain ) : NULL;
1141
1142     for (module_t *subm = p_module->submodule; subm; subm = subm->next)
1143         DupModule (subm);
1144 }
1145
1146 /*****************************************************************************
1147  * UndupModule: free a duplicated module.
1148  *****************************************************************************
1149  * This function frees the allocations done in DupModule().
1150  *****************************************************************************/
1151 static void UndupModule( module_t *p_module )
1152 {
1153     char **pp_shortcuts = p_module->pp_shortcuts;
1154
1155     for (module_t *subm = p_module->submodule; subm; subm = subm->next)
1156         UndupModule (subm);
1157
1158     for( unsigned i = 0; i < p_module->i_shortcuts; i++ )
1159         free( pp_shortcuts[i] );
1160
1161     free( p_module->psz_capability );
1162     FREENULL( p_module->psz_shortname );
1163     free( p_module->psz_longname );
1164     FREENULL( p_module->psz_help );
1165     free( p_module->domain );
1166 }
1167
1168 #endif /* HAVE_DYNAMIC_PLUGINS */
1169
1170 /*****************************************************************************
1171  * AllocateBuiltinModule: initialize a builtin module.
1172  *****************************************************************************
1173  * This function registers a builtin module and allocates a structure
1174  * for its information data. The module can then be handled by module_need
1175  * and module_unneed. It can be removed by DeleteModule.
1176  *****************************************************************************/
1177 static int AllocateBuiltinModule( vlc_object_t * p_this,
1178                                   int ( *pf_entry ) ( module_t * ) )
1179 {
1180     module_t * p_module;
1181
1182     /* Now that we have successfully loaded the module, we can
1183      * allocate a structure for it */
1184     p_module = vlc_module_create( p_this );
1185     if( p_module == NULL )
1186         return -1;
1187
1188     /* Initialize the module : fill p_module->psz_object_name, etc. */
1189     if( pf_entry( p_module ) != 0 )
1190     {
1191         /* With a well-written module we shouldn't have to print an
1192          * additional error message here, but just make sure. */
1193         msg_Err( p_this, "failed calling entry point in builtin module" );
1194         module_release( p_module );
1195         return -1;
1196     }
1197
1198     /* Everything worked fine ! The module is ready to be added to the list. */
1199     p_module->b_builtin = true;
1200     /* LOCK */
1201     p_module->next = p_module_bank->head;
1202     p_module_bank->head = p_module;
1203     /* UNLOCK */
1204
1205     /* msg_Dbg( p_this, "builtin \"%s\", %s",
1206                 p_module->psz_object_name, p_module->psz_longname ); */
1207
1208     return 0;
1209 }
1210
1211 /*****************************************************************************
1212  * DeleteModule: delete a module and its structure.
1213  *****************************************************************************
1214  * This function can only be called if the module isn't being used.
1215  *****************************************************************************/
1216 static void DeleteModule( module_bank_t *p_bank, module_t * p_module )
1217 {
1218     assert( p_module );
1219
1220     /* Unlist the module (if it is in the list) */
1221     module_t **pp_self = &p_bank->head;
1222     while (*pp_self != NULL && *pp_self != p_module)
1223         pp_self = &((*pp_self)->next);
1224     if (*pp_self)
1225         *pp_self = p_module->next;
1226
1227     /* We free the structures that we strdup()ed in Allocate*Module(). */
1228 #ifdef HAVE_DYNAMIC_PLUGINS
1229     if( !p_module->b_builtin )
1230     {
1231         if( p_module->b_loaded && p_module->b_unloadable )
1232         {
1233             module_Unload( p_module->handle );
1234         }
1235         UndupModule( p_module );
1236         free( p_module->psz_filename );
1237     }
1238 #endif
1239
1240     /* Free and detach the object's children */
1241     while (p_module->submodule)
1242     {
1243         module_t *submodule = p_module->submodule;
1244         p_module->submodule = submodule->next;
1245         module_release (submodule);
1246     }
1247
1248     config_Free( p_module );
1249     module_release( p_module );
1250 }