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