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