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