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