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