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