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