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