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