]> git.sesse.net Git - vlc/blob - src/modules/modules.c
Do not include vlc_modules.h in vlc_common.h
[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 <vlc_modules.h>
35 #include "libvlc.h"
36
37 #include <stdlib.h>                                      /* free(), strtol() */
38 #include <stdio.h>                                              /* sprintf() */
39 #include <string.h>                                              /* strdup() */
40 #include <assert.h>
41
42 #ifdef HAVE_DIRENT_H
43 #   include <dirent.h>
44 #endif
45
46 #include <sys/types.h>
47 #ifdef HAVE_SYS_STAT_H
48 #   include <sys/stat.h>
49 #endif
50 #ifdef HAVE_UNISTD_H
51 #   include <unistd.h>
52 #endif
53 #ifdef ENABLE_NLS
54 # include <libintl.h>
55 #endif
56
57 #include "config/configuration.h"
58
59 #include <vlc_fs.h>
60 #include "vlc_arrays.h"
61
62 #include "modules/modules.h"
63
64 static module_bank_t *p_module_bank = NULL;
65 static vlc_mutex_t module_lock = VLC_STATIC_MUTEX;
66
67 int vlc_entry__main( module_t * );
68
69 /*****************************************************************************
70  * Local prototypes
71  *****************************************************************************/
72 #ifdef HAVE_DYNAMIC_PLUGINS
73 static void AllocateAllPlugins( vlc_object_t *, module_bank_t * );
74 static void AllocatePluginDir( vlc_object_t *, module_bank_t *, const char *,
75                                unsigned );
76 static int  AllocatePluginFile( vlc_object_t *, module_bank_t *, const char *,
77                                 int64_t, int64_t );
78 static module_t * AllocatePlugin( vlc_object_t *, const char * );
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 = p_bank->i_loaded_cache = 0;
107         p_bank->pp_cache = p_bank->pp_loaded_cache = NULL;
108         p_bank->b_cache = p_bank->b_cache_dirty = false;
109         p_bank->head = NULL;
110
111         /* Everything worked, attach the object */
112         p_module_bank = p_bank;
113
114         /* Fills the module bank structure with the main module infos.
115          * This is very useful as it will allow us to consider the main
116          * library just as another module, and for instance the configuration
117          * options of main will be available in the module bank structure just
118          * as for every other module. */
119         AllocateBuiltinModule( p_this, vlc_entry__main );
120         vlc_rwlock_init (&config_lock);
121         config_SortConfig ();
122     }
123     else
124         p_module_bank->i_usage++;
125
126     /* We do retain the module bank lock until the plugins are loaded as well.
127      * This is ugly, this staged loading approach is needed: LibVLC gets
128      * some configuration parameters relevant to loading the plugins from
129      * the main (builtin) module. The module bank becomes shared read-only data
130      * once it is ready, so we need to fully serialize initialization.
131      * DO NOT UNCOMMENT the following line unless you managed to squeeze
132      * module_LoadPlugins() before you unlock the mutex. */
133     /*vlc_mutex_unlock( &module_lock );*/
134 }
135
136 #undef module_EndBank
137 /**
138  * Unloads all unused plugin modules and empties the module
139  * bank in case of success.
140  * \param p_this vlc object structure
141  * \return nothing
142  */
143 void module_EndBank( vlc_object_t *p_this, bool b_plugins )
144 {
145     module_bank_t *p_bank = p_module_bank;
146
147     assert (p_bank != NULL);
148
149     /* Save the configuration */
150     if( !var_InheritBool( p_this, "ignore-config" ) )
151         config_AutoSaveConfigFile( p_this );
152
153     /* If plugins were _not_ loaded, then the caller still has the bank lock
154      * from module_InitBank(). */
155     if( b_plugins )
156         vlc_mutex_lock( &module_lock );
157     /*else
158         vlc_assert_locked( &module_lock ); not for static mutexes :( */
159
160     if( --p_bank->i_usage > 0 )
161     {
162         vlc_mutex_unlock( &module_lock );
163         return;
164     }
165
166     config_UnsortConfig ();
167     vlc_rwlock_destroy (&config_lock);
168     p_module_bank = NULL;
169     vlc_mutex_unlock( &module_lock );
170
171 #ifdef HAVE_DYNAMIC_PLUGINS
172     while( p_bank->i_loaded_cache-- )
173     {
174         if( p_bank->pp_loaded_cache[p_bank->i_loaded_cache] )
175         {
176             DeleteModule( p_bank,
177                     p_bank->pp_loaded_cache[p_bank->i_loaded_cache]->p_module );
178             free( p_bank->pp_loaded_cache[p_bank->i_loaded_cache]->psz_file );
179             free( p_bank->pp_loaded_cache[p_bank->i_loaded_cache] );
180         }
181     }
182     free( p_bank->pp_loaded_cache );
183     while( p_bank->i_cache-- )
184     {
185         free( p_bank->pp_cache[p_bank->i_cache]->psz_file );
186         free( p_bank->pp_cache[p_bank->i_cache] );
187     }
188     free( p_bank->pp_cache );
189 #endif
190
191     while( p_bank->head != NULL )
192         DeleteModule( p_bank, p_bank->head );
193
194     free( p_bank );
195 }
196
197 #undef module_LoadPlugins
198 /**
199  * Loads module descriptions for all available plugins.
200  * Fills the module bank structure with the plugin modules.
201  *
202  * \param p_this vlc object structure
203  * \return nothing
204  */
205 void module_LoadPlugins( vlc_object_t * p_this )
206 {
207     module_bank_t *p_bank = p_module_bank;
208
209     assert( p_bank );
210     /*vlc_assert_locked( &module_lock ); not for static mutexes :( */
211
212 #ifdef HAVE_DYNAMIC_PLUGINS
213     if( p_bank->i_usage == 1 )
214     {
215         msg_Dbg( p_this, "checking plugin modules" );
216         p_module_bank->b_cache = var_InheritBool( p_this, "plugins-cache" );
217
218         AllocateAllPlugins( p_this, p_module_bank );
219         config_UnsortConfig ();
220         config_SortConfig ();
221     }
222 #endif
223     vlc_mutex_unlock( &module_lock );
224 }
225
226 /**
227  * Checks whether a module implements a capability.
228  *
229  * \param m the module
230  * \param cap the capability to check
231  * \return TRUE if the module have the capability
232  */
233 bool module_provides( const module_t *m, const char *cap )
234 {
235     return !strcmp( m->psz_capability, cap );
236 }
237
238 /**
239  * Get the internal name of a module
240  *
241  * \param m the module
242  * \return the module name
243  */
244 const char *module_get_object( const module_t *m )
245 {
246     return m->psz_object_name;
247 }
248
249 /**
250  * Get the human-friendly name of a module.
251  *
252  * \param m the module
253  * \param long_name TRUE to have the long name of the module
254  * \return the short or long name of the module
255  */
256 const char *module_get_name( const module_t *m, bool long_name )
257 {
258     if( long_name && ( m->psz_longname != NULL) )
259         return m->psz_longname;
260
261     return m->psz_shortname ? m->psz_shortname : m->psz_object_name;
262 }
263
264 /**
265  * Get the help for a module
266  *
267  * \param m the module
268  * \return the help
269  */
270 const char *module_get_help( const module_t *m )
271 {
272     return m->psz_help;
273 }
274
275 /**
276  * Get the capability for a module
277  *
278  * \param m the module
279  * return the capability
280  */
281 const char *module_get_capability( const module_t *m )
282 {
283     return m->psz_capability;
284 }
285
286 /**
287  * Get the score for a module
288  *
289  * \param m the module
290  * return the score for the capability
291  */
292 int module_get_score( const module_t *m )
293 {
294     return m->i_score;
295 }
296
297 /**
298  * Translate a string using the module's text domain
299  *
300  * \param m the module
301  * \param str the American English ASCII string to localize
302  * \return the gettext-translated string
303  */
304 const char *module_gettext (const module_t *m, const char *str)
305 {
306 #ifdef ENABLE_NLS
307     const char *domain = m->domain ? m->domain : PACKAGE_NAME;
308     return dgettext (domain, str);
309 #else
310     (void)m;
311     return str;
312 #endif
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 #undef module_need
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; i < p_module->i_shortcuts; 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         msg_Dbg( p_this, "no %s module matched \"%s\"",
595                  psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
596     else
597         msg_Dbg( p_this, "no %s module matching \"%s\" could be loaded",
598                   psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
599
600     free( psz_shortcuts );
601     free( psz_var );
602
603     stats_TimerStop( p_this, STATS_TIMER_MODULE_NEED );
604     stats_TimerDump( p_this, STATS_TIMER_MODULE_NEED );
605     stats_TimerClean( p_this, STATS_TIMER_MODULE_NEED );
606
607     /* Don't forget that the module is still locked */
608     return p_module;
609 }
610
611 #undef module_unneed
612 /**
613  * Module unneed
614  *
615  * This function must be called by the thread that called module_need, to
616  * decrease the reference count and allow for hiding of modules.
617  * \param p_this vlc object structure
618  * \param p_module the module structure
619  * \return nothing
620  */
621 void module_unneed( vlc_object_t * p_this, module_t * p_module )
622 {
623     /* Use the close method */
624     if( p_module->pf_deactivate )
625     {
626         p_module->pf_deactivate( p_this );
627     }
628
629     msg_Dbg( p_this, "removing module \"%s\"", p_module->psz_object_name );
630
631     module_release( p_module );
632 }
633
634 /**
635  * Get a pointer to a module_t given it's name.
636  *
637  * \param psz_name the name of the module
638  * \return a pointer to the module or NULL in case of a failure
639  */
640 module_t *module_find( const char * psz_name )
641 {
642     module_t **list, *module;
643
644     list = module_list_get (NULL);
645     if (!list)
646         return NULL;
647
648     for (size_t i = 0; (module = list[i]) != NULL; i++)
649     {
650         const char *psz_module_name = module->psz_object_name;
651
652         if( psz_module_name && !strcmp( psz_module_name, psz_name ) )
653         {
654             module_hold (module);
655             break;
656         }
657     }
658     module_list_free (list);
659     return module;
660 }
661
662 /**
663  * Tell if a module exists and release it in thic case
664  *
665  * \param psz_name th name of the module
666  * \return TRUE if the module exists
667  */
668 bool module_exists (const char * psz_name)
669 {
670     module_t *p_module = module_find (psz_name);
671     if( p_module )
672         module_release (p_module);
673     return p_module != NULL;
674 }
675
676 /**
677  * Get a pointer to a module_t that matches a shortcut.
678  * This is a temporary hack for SD. Do not re-use (generally multiple modules
679  * can have the same shortcut, so this is *broken* - use module_need()!).
680  *
681  * \param psz_shortcut shortcut of the module
682  * \param psz_cap capability of the module
683  * \return a pointer to the module or NULL in case of a failure
684  */
685 module_t *module_find_by_shortcut (const char *psz_shortcut)
686 {
687     module_t **list, *module;
688
689     list = module_list_get (NULL);
690     if (!list)
691         return NULL;
692
693     for (size_t i = 0; (module = list[i]) != NULL; i++)
694     {
695         for (size_t j = 0; j < module->i_shortcuts; j++)
696         {
697             if (!strcmp (module->pp_shortcuts[j], psz_shortcut))
698             {
699                 module_hold (module);
700                 goto out;
701              }
702         }
703     }
704 out:
705     module_list_free (list);
706     return module;
707 }
708
709 /**
710  * Get the configuration of a module
711  *
712  * \param module the module
713  * \param psize the size of the configuration returned
714  * \return the configuration as an array
715  */
716 module_config_t *module_config_get( const module_t *module, unsigned *restrict psize )
717 {
718     unsigned i,j;
719     unsigned size = module->confsize;
720     module_config_t *config = malloc( size * sizeof( *config ) );
721
722     assert( psize != NULL );
723     *psize = 0;
724
725     if( !config )
726         return NULL;
727
728     for( i = 0, j = 0; i < size; i++ )
729     {
730         const module_config_t *item = module->p_config + i;
731         if( item->b_internal /* internal option */
732          || item->b_removed /* removed option */ )
733             continue;
734
735         memcpy( config + j, item, sizeof( *config ) );
736         j++;
737     }
738     *psize = j;
739
740     return config;
741 }
742
743 /**
744  * Release the configuration
745  *
746  * \param the configuration
747  * \return nothing
748  */
749 void module_config_free( module_config_t *config )
750 {
751     free( config );
752 }
753
754 /*****************************************************************************
755  * Following functions are local.
756  *****************************************************************************/
757
758  /*****************************************************************************
759  * copy_next_paths_token: from a PATH_SEP_CHAR (a ':' or a ';') separated paths
760  * return first path.
761  *****************************************************************************/
762 static char * copy_next_paths_token( char * paths, char ** remaining_paths )
763 {
764     char * path;
765     int i, done;
766     bool escaped = false;
767
768     assert( paths );
769
770     /* Alloc a buffer to store the path */
771     path = malloc( strlen( paths ) + 1 );
772     if( !path ) return NULL;
773
774     /* Look for PATH_SEP_CHAR (a ':' or a ';') */
775     for( i = 0, done = 0 ; paths[i]; i++ )
776     {
777         /* Take care of \\ and \: or \; escapement */
778         if( escaped )
779         {
780             escaped = false;
781             path[done++] = paths[i];
782         }
783 #ifdef WIN32
784         else if( paths[i] == '/' )
785             escaped = true;
786 #else
787         else if( paths[i] == '\\' )
788             escaped = true;
789 #endif
790         else if( paths[i] == PATH_SEP_CHAR )
791             break;
792         else
793             path[done++] = paths[i];
794     }
795     path[done] = 0;
796
797     /* Return the remaining paths */
798     if( remaining_paths ) {
799         *remaining_paths = paths[i] ? &paths[i]+1 : NULL;
800     }
801
802     return path;
803 }
804
805 char *psz_vlcpath = NULL;
806
807 /*****************************************************************************
808  * AllocateAllPlugins: load all plugin modules we can find.
809  *****************************************************************************/
810 #ifdef HAVE_DYNAMIC_PLUGINS
811 static void AllocateAllPlugins( vlc_object_t *p_this, module_bank_t *p_bank )
812 {
813     const char *vlcpath = psz_vlcpath;
814     int count,i;
815     char * path;
816     vlc_array_t *arraypaths = vlc_array_new();
817     const bool b_reset = var_InheritBool( p_this, "reset-plugins-cache" );
818
819     /* Contruct the special search path for system that have a relocatable
820      * executable. Set it to <vlc path>/plugins. */
821     assert( vlcpath );
822
823     if( asprintf( &path, "%s" DIR_SEP "plugins", vlcpath ) != -1 )
824         vlc_array_append( arraypaths, path );
825
826     /* If the user provided a plugin path, we add it to the list */
827     char *userpaths = var_InheritString( p_this, "plugin-path" );
828     char *paths_iter;
829
830     for( paths_iter = userpaths; paths_iter; )
831     {
832         path = copy_next_paths_token( paths_iter, &paths_iter );
833         if( path )
834             vlc_array_append( arraypaths, path );
835     }
836
837     count = vlc_array_count( arraypaths );
838     for( i = 0 ; i < count ; i++ )
839     {
840         path = vlc_array_item_at_index( arraypaths, i );
841         if( !path )
842             continue;
843
844         size_t offset = p_module_bank->i_cache;
845         if( b_reset )
846             CacheDelete( p_this, path );
847         else
848             CacheLoad( p_this, p_module_bank, path );
849
850         msg_Dbg( p_this, "recursively browsing `%s'", path );
851
852         /* Don't go deeper than 5 subdirectories */
853         AllocatePluginDir( p_this, p_bank, path, 5 );
854
855
856         CacheSave( p_this, path, p_module_bank->pp_cache + offset,
857                    p_module_bank->i_cache - offset );
858         free( path );
859     }
860
861     vlc_array_destroy( arraypaths );
862     free( userpaths );
863 }
864
865 /*****************************************************************************
866  * AllocatePluginDir: recursively parse a directory to look for plugins
867  *****************************************************************************/
868 static void AllocatePluginDir( vlc_object_t *p_this, module_bank_t *p_bank,
869                                const char *psz_dir, unsigned i_maxdepth )
870 {
871     if( i_maxdepth == 0 )
872         return;
873
874     DIR *dh = vlc_opendir (psz_dir);
875     if (dh == NULL)
876         return;
877
878     /* Parse the directory and try to load all files it contains. */
879     for (;;)
880     {
881         char *file = vlc_readdir (dh), *path;
882         struct stat st;
883
884         if (file == NULL)
885             break;
886
887         /* Skip ".", ".." */
888         if (!strcmp (file, ".") || !strcmp (file, "..")
889         /* Skip directories for unsupported optimizations */
890          || !vlc_CPU_CheckPluginDir (file))
891         {
892             free (file);
893             continue;
894         }
895
896         const int pathlen = asprintf (&path, "%s"DIR_SEP"%s", psz_dir, file);
897         free (file);
898         if (pathlen == -1 || vlc_stat (path, &st))
899             continue;
900
901         if (S_ISDIR (st.st_mode))
902             /* Recurse into another directory */
903             AllocatePluginDir (p_this, p_bank, path, i_maxdepth - 1);
904         else
905         if (S_ISREG (st.st_mode)
906          && strncmp (path, "lib", 3)
907          && ((size_t)pathlen >= sizeof ("_plugin"LIBEXT))
908          && !strncasecmp (path + pathlen - strlen ("_plugin"LIBEXT),
909                           "_plugin"LIBEXT, strlen ("_plugni"LIBEXT)))
910             /* ^^ We only load files matching "lib*_plugin"LIBEXT */
911             AllocatePluginFile (p_this, p_bank, path, st.st_mtime, st.st_size);
912
913         free (path);
914     }
915     closedir (dh);
916 }
917
918 /*****************************************************************************
919  * AllocatePluginFile: load a module into memory and initialize it.
920  *****************************************************************************
921  * This function loads a dynamically loadable module and allocates a structure
922  * for its information data. The module can then be handled by module_need
923  * and module_unneed. It can be removed by DeleteModule.
924  *****************************************************************************/
925 static int AllocatePluginFile( vlc_object_t * p_this, module_bank_t *p_bank,
926                                const char *psz_file,
927                                int64_t i_file_time, int64_t i_file_size )
928 {
929     module_t * p_module = NULL;
930     module_cache_t *p_cache_entry = NULL;
931
932     /*
933      * Check our plugins cache first then load plugin if needed
934      */
935     p_cache_entry = CacheFind( p_bank, psz_file, i_file_time, i_file_size );
936     if( !p_cache_entry )
937     {
938         p_module = AllocatePlugin( p_this, psz_file );
939     }
940     else
941     {
942         module_config_t *p_item = NULL, *p_end = NULL;
943
944         p_module = p_cache_entry->p_module;
945         p_module->b_loaded = false;
946
947         /* If plugin-path contains duplicate entries... */
948         if( p_module->next != NULL )
949             return 0; /* already taken care of that one */
950
951         /* For now we force loading if the module's config contains
952          * callbacks or actions.
953          * Could be optimized by adding an API call.*/
954         for( p_item = p_module->p_config, p_end = p_item + p_module->confsize;
955              p_item < p_end; p_item++ )
956         {
957             if( p_item->pf_callback || p_item->i_action )
958             {
959                 p_module = AllocatePlugin( p_this, psz_file );
960                 break;
961             }
962         }
963     }
964
965     if( p_module == NULL )
966         return -1;
967
968     /* We have not already scanned and inserted this module */
969     assert( p_module->next == NULL );
970
971     /* Everything worked fine !
972      * The module is ready to be added to the list. */
973     p_module->b_builtin = false;
974
975     /* msg_Dbg( p_this, "plugin \"%s\", %s",
976                 p_module->psz_object_name, p_module->psz_longname ); */
977     p_module->next = p_bank->head;
978     p_bank->head = p_module;
979     assert( p_module->next != NULL ); /* Insertion done */
980
981     if( !p_module_bank->b_cache )
982         return 0;
983
984     /* Add entry to cache */
985     module_cache_t **pp_cache = p_bank->pp_cache;
986
987     pp_cache = realloc_or_free( pp_cache, (p_bank->i_cache + 1) * sizeof(void *) );
988     if( pp_cache == NULL )
989         return -1;
990     pp_cache[p_bank->i_cache] = malloc( sizeof(module_cache_t) );
991     if( pp_cache[p_bank->i_cache] == NULL )
992         return -1;
993     pp_cache[p_bank->i_cache]->psz_file = strdup( psz_file );
994     pp_cache[p_bank->i_cache]->i_time = i_file_time;
995     pp_cache[p_bank->i_cache]->i_size = i_file_size;
996     pp_cache[p_bank->i_cache]->p_module = p_module;
997     p_bank->pp_cache = pp_cache;
998     p_bank->i_cache++;
999     return  0;
1000 }
1001
1002 /*****************************************************************************
1003  * AllocatePlugin: load a module into memory and initialize it.
1004  *****************************************************************************
1005  * This function loads a dynamically loadable module and allocates a structure
1006  * for its information data. The module can then be handled by module_need
1007  * and module_unneed. It can be removed by DeleteModule.
1008  *****************************************************************************/
1009 static module_t * AllocatePlugin( vlc_object_t * p_this, const char *psz_file )
1010 {
1011     module_t * p_module = NULL;
1012     module_handle_t handle;
1013
1014     if( module_Load( p_this, psz_file, &handle ) )
1015         return NULL;
1016
1017     /* Now that we have successfully loaded the module, we can
1018      * allocate a structure for it */
1019     p_module = vlc_module_create( p_this );
1020     if( p_module == NULL )
1021     {
1022         module_Unload( handle );
1023         return NULL;
1024     }
1025
1026     p_module->psz_filename = strdup( psz_file );
1027     p_module->handle = handle;
1028     p_module->b_loaded = true;
1029
1030     /* Initialize the module: fill p_module, default config */
1031     if( module_Call( p_this, p_module ) != 0 )
1032     {
1033         /* We couldn't call module_init() */
1034         free( p_module->psz_filename );
1035         module_release( p_module );
1036         module_Unload( handle );
1037         return NULL;
1038     }
1039
1040     DupModule( p_module );
1041
1042     /* Everything worked fine ! The module is ready to be added to the list. */
1043     p_module->b_builtin = false;
1044
1045     return p_module;
1046 }
1047
1048 /*****************************************************************************
1049  * DupModule: make a plugin module standalone.
1050  *****************************************************************************
1051  * This function duplicates all strings in the module, so that the dynamic
1052  * object can be unloaded. It acts recursively on submodules.
1053  *****************************************************************************/
1054 static void DupModule( module_t *p_module )
1055 {
1056     char **pp_shortcuts = p_module->pp_shortcuts;
1057     for( unsigned i = 0; i < p_module->i_shortcuts; i++ )
1058         pp_shortcuts[i] = strdup( p_module->pp_shortcuts[i] );
1059
1060     /* We strdup() these entries so that they are still valid when the
1061      * module is unloaded. */
1062     p_module->psz_capability = strdup( p_module->psz_capability );
1063     p_module->psz_shortname = p_module->psz_shortname ?
1064                                  strdup( p_module->psz_shortname ) : NULL;
1065     p_module->psz_longname = strdup( p_module->psz_longname );
1066     p_module->psz_help = p_module->psz_help ? strdup( p_module->psz_help )
1067                                             : NULL;
1068     p_module->domain = p_module->domain ? strdup( p_module->domain ) : NULL;
1069
1070     for (module_t *subm = p_module->submodule; subm; subm = subm->next)
1071         DupModule (subm);
1072 }
1073
1074 /*****************************************************************************
1075  * UndupModule: free a duplicated module.
1076  *****************************************************************************
1077  * This function frees the allocations done in DupModule().
1078  *****************************************************************************/
1079 static void UndupModule( module_t *p_module )
1080 {
1081     char **pp_shortcuts = p_module->pp_shortcuts;
1082
1083     for (module_t *subm = p_module->submodule; subm; subm = subm->next)
1084         UndupModule (subm);
1085
1086     for( unsigned i = 0; i < p_module->i_shortcuts; i++ )
1087         free( pp_shortcuts[i] );
1088
1089     free( p_module->psz_capability );
1090     FREENULL( p_module->psz_shortname );
1091     free( p_module->psz_longname );
1092     FREENULL( p_module->psz_help );
1093     free( p_module->domain );
1094 }
1095
1096 #endif /* HAVE_DYNAMIC_PLUGINS */
1097
1098 /*****************************************************************************
1099  * AllocateBuiltinModule: initialize a builtin module.
1100  *****************************************************************************
1101  * This function registers a builtin module and allocates a structure
1102  * for its information data. The module can then be handled by module_need
1103  * and module_unneed. It can be removed by DeleteModule.
1104  *****************************************************************************/
1105 static int AllocateBuiltinModule( vlc_object_t * p_this,
1106                                   int ( *pf_entry ) ( module_t * ) )
1107 {
1108     module_t * p_module;
1109
1110     /* Now that we have successfully loaded the module, we can
1111      * allocate a structure for it */
1112     p_module = vlc_module_create( p_this );
1113     if( p_module == NULL )
1114         return -1;
1115
1116     /* Initialize the module : fill p_module->psz_object_name, etc. */
1117     if( pf_entry( p_module ) != 0 )
1118     {
1119         /* With a well-written module we shouldn't have to print an
1120          * additional error message here, but just make sure. */
1121         msg_Err( p_this, "failed calling entry point in builtin module" );
1122         module_release( p_module );
1123         return -1;
1124     }
1125
1126     /* Everything worked fine ! The module is ready to be added to the list. */
1127     p_module->b_builtin = true;
1128     /* LOCK */
1129     p_module->next = p_module_bank->head;
1130     p_module_bank->head = p_module;
1131     /* UNLOCK */
1132
1133     /* msg_Dbg( p_this, "builtin \"%s\", %s",
1134                 p_module->psz_object_name, p_module->psz_longname ); */
1135
1136     return 0;
1137 }
1138
1139 /*****************************************************************************
1140  * DeleteModule: delete a module and its structure.
1141  *****************************************************************************
1142  * This function can only be called if the module isn't being used.
1143  *****************************************************************************/
1144 static void DeleteModule( module_bank_t *p_bank, module_t * p_module )
1145 {
1146     assert( p_module );
1147
1148     /* Unlist the module (if it is in the list) */
1149     module_t **pp_self = &p_bank->head;
1150     while (*pp_self != NULL && *pp_self != p_module)
1151         pp_self = &((*pp_self)->next);
1152     if (*pp_self)
1153         *pp_self = p_module->next;
1154
1155     /* We free the structures that we strdup()ed in Allocate*Module(). */
1156 #ifdef HAVE_DYNAMIC_PLUGINS
1157     if( !p_module->b_builtin )
1158     {
1159         if( p_module->b_loaded && p_module->b_unloadable )
1160         {
1161             module_Unload( p_module->handle );
1162         }
1163         UndupModule( p_module );
1164         free( p_module->psz_filename );
1165     }
1166 #endif
1167
1168     /* Free and detach the object's children */
1169     while (p_module->submodule)
1170     {
1171         module_t *submodule = p_module->submodule;
1172         p_module->submodule = submodule->next;
1173         module_release (submodule);
1174     }
1175
1176     config_Free( p_module );
1177     module_release( p_module );
1178 }