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