]> git.sesse.net Git - vlc/blob - src/modules/modules.c
cc9570faa3cb02b2e5b1f28db6f38d4ea0e6327b
[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/vlc.h>
32 #include "libvlc.h"
33
34 /* Some faulty libcs have a broken struct dirent when _FILE_OFFSET_BITS
35  * is set to 64. Don't try to be cleverer. */
36 #ifdef _FILE_OFFSET_BITS
37 #undef _FILE_OFFSET_BITS
38 #endif
39
40 #include <stdlib.h>                                      /* free(), strtol() */
41 #include <stdio.h>                                              /* sprintf() */
42 #include <string.h>                                              /* strdup() */
43 #include <assert.h>
44
45 #ifdef HAVE_DIRENT_H
46 #   include <dirent.h>
47 #endif
48
49 #ifdef HAVE_SYS_TYPES_H
50 #   include <sys/types.h>
51 #endif
52 #ifdef HAVE_SYS_STAT_H
53 #   include <sys/stat.h>
54 #endif
55 #ifdef HAVE_UNISTD_H
56 #   include <unistd.h>
57 #endif
58
59 #if !defined(HAVE_DYNAMIC_PLUGINS)
60     /* no support for plugins */
61 #elif defined(HAVE_DL_DYLD)
62 #   if defined(HAVE_MACH_O_DYLD_H)
63 #       include <mach-o/dyld.h>
64 #   endif
65 #elif defined(HAVE_DL_BEOS)
66 #   if defined(HAVE_IMAGE_H)
67 #       include <image.h>
68 #   endif
69 #elif defined(HAVE_DL_WINDOWS)
70 #   include <windows.h>
71 #elif defined(HAVE_DL_DLOPEN)
72 #   if defined(HAVE_DLFCN_H) /* Linux, BSD, Hurd */
73 #       include <dlfcn.h>
74 #   endif
75 #   if defined(HAVE_SYS_DL_H)
76 #       include <sys/dl.h>
77 #   endif
78 #elif defined(HAVE_DL_SHL_LOAD)
79 #   if defined(HAVE_DL_H)
80 #       include <dl.h>
81 #   endif
82 #endif
83
84 #include "config/configuration.h"
85
86 #include "vlc_charset.h"
87
88 #include "modules/modules.h"
89 #include "modules/builtin.h"
90
91 /*****************************************************************************
92  * Local prototypes
93  *****************************************************************************/
94 #ifdef HAVE_DYNAMIC_PLUGINS
95 static void AllocateAllPlugins  ( vlc_object_t * );
96 static void AllocatePluginDir   ( vlc_object_t *, const char *, int );
97 static int  AllocatePluginFile  ( vlc_object_t *, char *, int64_t, int64_t );
98 static module_t * AllocatePlugin( vlc_object_t *, char * );
99 #endif
100 static int  AllocateBuiltinModule( vlc_object_t *, int ( * ) ( module_t * ) );
101 static int  DeleteModule ( module_t *, vlc_bool_t );
102 #ifdef HAVE_DYNAMIC_PLUGINS
103 static void   DupModule        ( module_t * );
104 static void   UndupModule      ( module_t * );
105 #endif
106
107 static void module_LoadMain( vlc_object_t *p_this );
108
109 /*****************************************************************************
110  * module_InitBank: create the module bank.
111  *****************************************************************************
112  * This function creates a module bank structure which will be filled later
113  * on with all the modules found.
114  *****************************************************************************/
115 void __module_InitBank( vlc_object_t *p_this )
116 {
117     module_bank_t *p_bank = NULL;
118     vlc_value_t  lockval;
119     libvlc_global_data_t *p_libvlc_global = vlc_global();
120
121     var_Create( p_libvlc_global, "libvlc", VLC_VAR_MUTEX );
122     var_Get( p_libvlc_global, "libvlc", &lockval );
123     vlc_mutex_lock( lockval.p_address );
124     if( p_libvlc_global->p_module_bank )
125     {
126         p_libvlc_global->p_module_bank->i_usage++;
127         vlc_mutex_unlock( lockval.p_address );
128         var_Destroy( p_libvlc_global, "libvlc" );
129         return;
130     }
131     vlc_mutex_unlock( lockval.p_address );
132     var_Destroy( p_libvlc_global, "libvlc" );
133
134     p_bank = vlc_object_create( p_this, sizeof(module_bank_t) );
135     if( !p_bank )
136         return;
137     p_bank->psz_object_name = "module bank";
138     p_bank->i_usage = 1;
139     p_bank->i_cache = p_bank->i_loaded_cache = 0;
140     p_bank->pp_cache = p_bank->pp_loaded_cache = NULL;
141     p_bank->b_cache = p_bank->b_cache_dirty =
142         p_bank->b_cache_delete = VLC_FALSE;
143
144     /* Everything worked, attach the object */
145     p_libvlc_global->p_module_bank = p_bank;
146     vlc_object_attach( p_bank, p_libvlc_global );
147
148     module_LoadMain( p_this );
149 }
150
151
152 /*****************************************************************************
153  * module_EndBank: empty the module bank.
154  *****************************************************************************
155  * This function unloads all unused plugin modules and empties the module
156  * bank in case of success.
157  *****************************************************************************/
158 void __module_EndBank( vlc_object_t *p_this )
159 {
160     module_t * p_next = NULL;
161     vlc_value_t lockval;
162     libvlc_global_data_t *p_libvlc_global = vlc_global();
163
164     var_Create( p_libvlc_global, "libvlc", VLC_VAR_MUTEX );
165     var_Get( p_libvlc_global, "libvlc", &lockval );
166     vlc_mutex_lock( lockval.p_address );
167     if( !p_libvlc_global->p_module_bank )
168     {
169         vlc_mutex_unlock( lockval.p_address );
170         var_Destroy( p_libvlc_global, "libvlc" );
171         return;
172     }
173     if( --p_libvlc_global->p_module_bank->i_usage )
174     {
175         vlc_mutex_unlock( lockval.p_address );
176         var_Destroy( p_libvlc_global, "libvlc" );
177         return;
178     }
179     vlc_mutex_unlock( lockval.p_address );
180     var_Destroy( p_libvlc_global, "libvlc" );
181
182     config_AutoSaveConfigFile( p_this );
183
184 #ifdef HAVE_DYNAMIC_PLUGINS
185 # define p_bank p_libvlc_global->p_module_bank
186     if( p_bank->b_cache ) CacheSave( p_this );
187     while( p_bank->i_loaded_cache-- )
188     {
189         if( p_bank->pp_loaded_cache[p_bank->i_loaded_cache] )
190         {
191             DeleteModule( p_bank->pp_loaded_cache[p_bank->i_loaded_cache]->p_module,
192                           p_bank->pp_loaded_cache[p_bank->i_loaded_cache]->b_used );
193             free( p_bank->pp_loaded_cache[p_bank->i_loaded_cache]->psz_file );
194             free( p_bank->pp_loaded_cache[p_bank->i_loaded_cache] );
195             p_bank->pp_loaded_cache[p_bank->i_loaded_cache] = NULL;
196         }
197     }
198     if( p_bank->pp_loaded_cache )
199     {
200         free( p_bank->pp_loaded_cache );
201         p_bank->pp_loaded_cache = NULL;
202     }
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         p_bank->pp_cache[p_bank->i_cache] = NULL;
208     }
209     if( p_bank->pp_cache )
210     {
211         free( p_bank->pp_cache );
212         p_bank->pp_cache = NULL;
213     }
214 # undef p_bank
215 #endif
216
217     vlc_object_detach( p_libvlc_global->p_module_bank );
218
219     while( p_libvlc_global->p_module_bank->i_children )
220     {
221         p_next = (module_t *)p_libvlc_global->p_module_bank->pp_children[0];
222
223         if( DeleteModule( p_next, VLC_TRUE ) )
224         {
225             /* Module deletion failed */
226             msg_Err( p_this, "module \"%s\" can't be removed, trying harder",
227                      p_next->psz_object_name );
228
229             /* We just free the module by hand. Niahahahahaha. */
230             vlc_object_detach( p_next );
231             vlc_object_destroy( p_next );
232         }
233     }
234
235     vlc_object_destroy( p_libvlc_global->p_module_bank );
236     p_libvlc_global->p_module_bank = NULL;
237 }
238
239 /*****************************************************************************
240  * module_LoadMain: load the main program info into the module bank.
241  *****************************************************************************
242  * This function fills the module bank structure with the main module infos.
243  * This is very useful as it will allow us to consider the main program just
244  * as another module, and for instance the configuration options of main will
245  * be available in the module bank structure just as for every other module.
246  *****************************************************************************/
247 static void module_LoadMain( vlc_object_t *p_this )
248 {
249     vlc_value_t lockval;
250     libvlc_global_data_t *p_libvlc_global = vlc_global();
251
252     var_Create( p_libvlc_global, "libvlc", VLC_VAR_MUTEX );
253     var_Get( p_libvlc_global, "libvlc", &lockval );
254     vlc_mutex_lock( lockval.p_address );
255     if( p_libvlc_global->p_module_bank->b_main )
256     {
257         vlc_mutex_unlock( lockval.p_address );
258         var_Destroy( p_libvlc_global, "libvlc" );
259         return;
260     }
261     p_libvlc_global->p_module_bank->b_main = VLC_TRUE;
262     vlc_mutex_unlock( lockval.p_address );
263     var_Destroy( p_libvlc_global, "libvlc" );
264
265     AllocateBuiltinModule( p_this, vlc_entry__main );
266 }
267
268 /*****************************************************************************
269  * module_LoadBuiltins: load all modules which we built with.
270  *****************************************************************************
271  * This function fills the module bank structure with the builtin modules.
272  *****************************************************************************/
273 void __module_LoadBuiltins( vlc_object_t * p_this )
274 {
275     vlc_value_t lockval;
276     libvlc_global_data_t *p_libvlc_global = vlc_global();
277
278     var_Create( p_libvlc_global, "libvlc", VLC_VAR_MUTEX );
279     var_Get( p_libvlc_global, "libvlc", &lockval );
280     vlc_mutex_lock( lockval.p_address );
281     if( p_libvlc_global->p_module_bank->b_builtins )
282     {
283         vlc_mutex_unlock( lockval.p_address );
284         var_Destroy( p_libvlc_global, "libvlc" );
285         return;
286     }
287     p_libvlc_global->p_module_bank->b_builtins = VLC_TRUE;
288     vlc_mutex_unlock( lockval.p_address );
289     var_Destroy( p_libvlc_global, "libvlc" );
290
291     msg_Dbg( p_this, "checking builtin modules" );
292     ALLOCATE_ALL_BUILTINS();
293 }
294
295 /*****************************************************************************
296  * module_LoadPlugins: load all plugin modules we can find.
297  *****************************************************************************
298  * This function fills the module bank structure with the plugin modules.
299  *****************************************************************************/
300 void __module_LoadPlugins( vlc_object_t * p_this )
301 {
302 #ifdef HAVE_DYNAMIC_PLUGINS
303     vlc_value_t lockval;
304     libvlc_global_data_t *p_libvlc_global = vlc_global();
305
306     var_Create( p_libvlc_global, "libvlc", VLC_VAR_MUTEX );
307     var_Get( p_libvlc_global, "libvlc", &lockval );
308     vlc_mutex_lock( lockval.p_address );
309     if( p_libvlc_global->p_module_bank->b_plugins )
310     {
311         vlc_mutex_unlock( lockval.p_address );
312         var_Destroy( p_libvlc_global, "libvlc" );
313         return;
314     }
315     p_libvlc_global->p_module_bank->b_plugins = VLC_TRUE;
316     vlc_mutex_unlock( lockval.p_address );
317     var_Destroy( p_libvlc_global, "libvlc" );
318
319     msg_Dbg( p_this, "checking plugin modules" );
320
321     if( config_GetInt( p_this, "plugins-cache" ) )
322         p_libvlc_global->p_module_bank->b_cache = VLC_TRUE;
323
324     if( p_libvlc_global->p_module_bank->b_cache ||
325         p_libvlc_global->p_module_bank->b_cache_delete ) CacheLoad( p_this );
326
327     AllocateAllPlugins( p_this );
328 #endif
329 }
330
331 /*****************************************************************************
332  * module_IsCapable: checks whether a module implements a capability.
333  *****************************************************************************/
334 vlc_bool_t module_IsCapable( const module_t *m, const char *cap )
335 {
336     return !strcmp( m->psz_capability, cap );
337 }
338
339 /*****************************************************************************
340  * module_GetObjName: internal name of a module.
341  *****************************************************************************/
342 const char *module_GetObjName( const module_t *m )
343 {
344     return m->psz_object_name;
345 }
346
347 /*****************************************************************************
348  * module_GetName: human-friendly name of a module.
349  *****************************************************************************/
350 const char *module_GetName( const module_t *m, vlc_bool_t long_name )
351 {
352     if( long_name && ( m->psz_longname != NULL) )
353         return m->psz_longname;
354  
355     return m->psz_shortname ?: m->psz_object_name;
356 }
357
358 const char *module_GetHelp( const module_t *m )
359 {
360     return m->psz_help;
361 }
362
363 /*****************************************************************************
364  * module_Need: return the best module function, given a capability list.
365  *****************************************************************************
366  * This function returns the module that best fits the asked capabilities.
367  *****************************************************************************/
368 module_t * __module_Need( vlc_object_t *p_this, const char *psz_capability,
369                           const char *psz_name, vlc_bool_t b_strict )
370 {
371     typedef struct module_list_t module_list_t;
372
373     struct module_list_t
374     {
375         module_t *p_module;
376         int i_score;
377         vlc_bool_t b_force;
378         module_list_t *p_next;
379     };
380
381     module_list_t *p_list, *p_first, *p_tmp;
382     vlc_list_t *p_all;
383
384     int i_which_module, i_index = 0;
385
386     module_t *p_module;
387
388     int   i_shortcuts = 0;
389     char *psz_shortcuts = NULL, *psz_var = NULL, *psz_alias = NULL;
390     vlc_bool_t b_force_backup = p_this->b_force;
391
392
393     /* Deal with variables */
394     if( psz_name && psz_name[0] == '$' )
395     {
396         vlc_value_t val;
397         var_Create( p_this, psz_name + 1, VLC_VAR_MODULE | VLC_VAR_DOINHERIT );
398         var_Get( p_this, psz_name + 1, &val );
399         psz_var = val.psz_string;
400         psz_name = psz_var;
401     }
402
403     /* Count how many different shortcuts were asked for */
404     if( psz_name && *psz_name )
405     {
406         char *psz_parser, *psz_last_shortcut;
407
408         /* If the user wants none, give him none. */
409         if( !strcmp( psz_name, "none" ) )
410         {
411             free( psz_var );
412             return NULL;
413         }
414
415         i_shortcuts++;
416         psz_shortcuts = psz_last_shortcut = strdup( psz_name );
417
418         for( psz_parser = psz_shortcuts; *psz_parser; psz_parser++ )
419         {
420             if( *psz_parser == ',' )
421             {
422                  *psz_parser = '\0';
423                  i_shortcuts++;
424                  psz_last_shortcut = psz_parser + 1;
425             }
426         }
427
428         /* Check if the user wants to override the "strict" mode */
429         if( psz_last_shortcut )
430         {
431             if( !strcmp(psz_last_shortcut, "none") )
432             {
433                 b_strict = VLC_TRUE;
434                 i_shortcuts--;
435             }
436             else if( !strcmp(psz_last_shortcut, "any") )
437             {
438                 b_strict = VLC_FALSE;
439                 i_shortcuts--;
440             }
441         }
442     }
443
444     /* Sort the modules and test them */
445     p_all = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
446     p_list = malloc( p_all->i_count * sizeof( module_list_t ) );
447     p_first = NULL;
448     unsigned i_cpu = vlc_CPU();
449
450     /* Parse the module list for capabilities and probe each of them */
451     for( i_which_module = 0; i_which_module < p_all->i_count; i_which_module++ )
452     {
453         int i_shortcut_bonus = 0;
454
455         p_module = (module_t *)p_all->p_values[i_which_module].p_object;
456
457         /* Test that this module can do what we need */
458         if( !module_IsCapable( p_module, psz_capability ) )
459         {
460             /* Don't recurse through the sub-modules because vlc_list_find()
461              * will list them anyway. */
462             continue;
463         }
464
465         /* Test if we have the required CPU */
466         if( (p_module->i_cpu & i_cpu) != p_module->i_cpu )
467         {
468             continue;
469         }
470
471         /* If we required a shortcut, check this plugin provides it. */
472         if( i_shortcuts > 0 )
473         {
474             vlc_bool_t b_trash;
475             const char *psz_name = psz_shortcuts;
476
477             /* Let's drop modules with a <= 0 score (unless they are
478              * explicitly requested) */
479             b_trash = p_module->i_score <= 0;
480
481             for( unsigned i_short = i_shortcuts; i_short > 0; i_short-- )
482             {
483                 for( unsigned i = 0; p_module->pp_shortcuts[i]; i++ )
484                 {
485                     char *c;
486                     if( ( c = strchr( psz_name, '@' ) )
487                         ? !strncasecmp( psz_name, p_module->pp_shortcuts[i],
488                                         c-psz_name )
489                         : !strcasecmp( psz_name, p_module->pp_shortcuts[i] ) )
490                     {
491                         /* Found it */
492                         if( c && c[1] )
493                             psz_alias = c+1;
494                         i_shortcut_bonus = i_short * 10000;
495                         goto found_shortcut;
496                     }
497                 }
498
499                 /* Go to the next shortcut... This is so lame! */
500                 psz_name += strlen( psz_name ) + 1;
501             }
502
503             /* If we are in "strict" mode and we couldn't
504              * find the module in the list of provided shortcuts,
505              * then kick the bastard out of here!!! */
506             if( b_strict )
507                 continue;
508         }
509         /* If we didn't require a shortcut, trash <= 0 scored plugins */
510         else if( p_module->i_score <= 0 )
511         {
512             continue;
513         }
514
515 found_shortcut:
516
517         /* Store this new module */
518         p_list[ i_index ].p_module = p_module;
519         p_list[ i_index ].i_score = p_module->i_score + i_shortcut_bonus;
520         p_list[ i_index ].b_force = i_shortcut_bonus && b_strict;
521
522         /* Add it to the modules-to-probe list */
523         if( i_index == 0 )
524         {
525             p_list[ 0 ].p_next = NULL;
526             p_first = p_list;
527         }
528         else
529         {
530             /* Ok, so at school you learned that quicksort is quick, and
531              * bubble sort sucks raw eggs. But that's when dealing with
532              * thousands of items. Here we have barely 50. */
533             module_list_t *p_newlist = p_first;
534
535             if( p_first->i_score < p_list[ i_index ].i_score )
536             {
537                 p_list[ i_index ].p_next = p_first;
538                 p_first = &p_list[ i_index ];
539             }
540             else
541             {
542                 while( p_newlist->p_next != NULL &&
543                     p_newlist->p_next->i_score >= p_list[ i_index ].i_score )
544                 {
545                     p_newlist = p_newlist->p_next;
546                 }
547
548                 p_list[ i_index ].p_next = p_newlist->p_next;
549                 p_newlist->p_next = &p_list[ i_index ];
550             }
551         }
552
553         i_index++;
554     }
555
556     msg_Dbg( p_this, "looking for %s module: %i candidate%s", psz_capability,
557                                             i_index, i_index == 1 ? "" : "s" );
558
559     /* Lock all candidate modules */
560     p_tmp = p_first;
561     while( p_tmp != NULL )
562     {
563         vlc_object_yield( p_tmp->p_module );
564         p_tmp = p_tmp->p_next;
565     }
566
567     /* We can release the list, interesting modules were yielded */
568     vlc_list_release( p_all );
569
570     /* Parse the linked list and use the first successful module */
571     p_tmp = p_first;
572     while( p_tmp != NULL )
573     {
574 #ifdef HAVE_DYNAMIC_PLUGINS
575         /* Make sure the module is loaded in mem */
576         module_t *p_module = p_tmp->p_module;
577         if( p_module->b_submodule )
578             p_module = (module_t *)p_module->p_parent;
579
580         if( !p_module->b_builtin && !p_module->b_loaded )
581         {
582             module_t *p_new_module =
583                 AllocatePlugin( p_this, p_module->psz_filename );
584             if( p_new_module )
585             {
586                 CacheMerge( p_this, p_module, p_new_module );
587                 vlc_object_attach( p_new_module, p_module );
588                 DeleteModule( p_new_module, VLC_TRUE );
589             }
590         }
591 #endif
592
593         p_this->b_force = p_tmp->b_force;
594         if( p_tmp->p_module->pf_activate
595              && p_tmp->p_module->pf_activate( p_this ) == VLC_SUCCESS )
596         {
597             break;
598         }
599
600         vlc_object_release( p_tmp->p_module );
601         p_tmp = p_tmp->p_next;
602     }
603
604     /* Store the locked module value */
605     if( p_tmp != NULL )
606     {
607         p_module = p_tmp->p_module;
608         p_tmp = p_tmp->p_next;
609     }
610     else
611     {
612         p_module = NULL;
613     }
614
615     /* Unlock the remaining modules */
616     while( p_tmp != NULL )
617     {
618         vlc_object_release( p_tmp->p_module );
619         p_tmp = p_tmp->p_next;
620     }
621
622     free( p_list );
623     p_this->b_force = b_force_backup;
624
625     if( p_module != NULL )
626     {
627         msg_Dbg( p_this, "using %s module \"%s\"",
628                  psz_capability, p_module->psz_object_name );
629     }
630     else if( p_first == NULL )
631     {
632         if( !strcmp( psz_capability, "access_demux" ) )
633         {
634             msg_Warn( p_this, "no %s module matched \"%s\"",
635                  psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
636         }
637         else
638         {
639             msg_Err( p_this, "no %s module matched \"%s\"",
640                  psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
641
642             msg_StackSet( VLC_EGENERIC, "no %s module matched \"%s\"",
643                  psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
644         }
645     }
646     else if( psz_name != NULL && *psz_name )
647     {
648         msg_Warn( p_this, "no %s module matching \"%s\" could be loaded",
649                   psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
650     }
651     else
652         msg_StackSet( VLC_EGENERIC, "no suitable %s module", psz_capability );
653
654     if( p_module && !p_this->psz_object_name )
655     {
656         /* This assumes that p_this is the object which will be using the
657          * module. That's not always the case ... but it is in most cases.
658          */
659         if( psz_alias )
660             p_this->psz_object_name = strdup( psz_alias );
661         else
662             p_this->psz_object_name = strdup( p_module->psz_object_name );
663     }
664
665     free( psz_shortcuts );
666     free( psz_var );
667
668     /* Don't forget that the module is still locked */
669     return p_module;
670 }
671
672 /*****************************************************************************
673  * module_Unneed: decrease the usage count of a module.
674  *****************************************************************************
675  * This function must be called by the thread that called module_Need, to
676  * decrease the reference count and allow for hiding of modules.
677  *****************************************************************************/
678 void __module_Unneed( vlc_object_t * p_this, module_t * p_module )
679 {
680     /* Use the close method */
681     if( p_module->pf_deactivate )
682     {
683         p_module->pf_deactivate( p_this );
684     }
685
686     msg_Dbg( p_this, "removing module \"%s\"", p_module->psz_object_name );
687
688     vlc_object_release( p_module );
689
690     return;
691 }
692
693 /*****************************************************************************
694  * module_Find: get a pointer to a module_t given it's name.
695  *****************************************************************************/
696 module_t *__module_Find( vlc_object_t *p_this, const char * psz_name )
697 {
698     vlc_list_t *p_list;
699     int i;
700     p_list = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
701     for( i = 0 ; i < p_list->i_count; i++)
702     {
703         module_t *p_module = ((module_t *) p_list->p_values[i].p_object);
704         const char *psz_module_name = p_module->psz_object_name;
705         if( psz_module_name && !strcmp( psz_module_name, psz_name ) )
706         {
707             /* We can release the list, and return yes */
708             vlc_object_yield( p_module );
709             vlc_list_release( p_list );
710             return p_module;
711         }
712     }
713     vlc_list_release( p_list );
714     return NULL;
715 }
716
717
718 /*****************************************************************************
719  * module_Put: release a module_t pointer from module_Find().
720  *****************************************************************************/
721 void module_Put ( module_t *module )
722 {
723     vlc_object_release ( module );
724 }
725
726
727 /*****************************************************************************
728  * module_Exists: tell if a module exists.
729  *****************************************************************************
730  * This function is a boolean function that tells if a module exist or not.
731  *****************************************************************************/
732 vlc_bool_t __module_Exists(  vlc_object_t *p_this, const char * psz_name )
733 {
734     module_t *p_module = __module_Find( p_this, psz_name );
735     if( p_module )
736     {
737         module_Put( p_module );
738         return VLC_TRUE;
739     }
740     else
741     {
742         return VLC_FALSE;
743     }
744 }
745
746 /*****************************************************************************
747  * module_GetModuleNamesForCapability: Return a NULL terminated array with the
748  * names of the modules that have a certain capability.
749  * Free after uses both the string and the table.
750  *****************************************************************************/
751 char ** __module_GetModulesNamesForCapability( vlc_object_t *p_this,
752                                                const char * psz_capability,
753                                                char ***pppsz_longname )
754 {
755     vlc_list_t *p_list;
756     int i, j, count = 0;
757     char ** psz_ret;
758
759     /* Do it in two passes */
760     p_list = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
761     for( i = 0 ; i < p_list->i_count; i++)
762     {
763         module_t *p_module = ((module_t *) p_list->p_values[i].p_object);
764         const char *psz_module_capability = p_module->psz_capability;
765         if( psz_module_capability && !strcmp( psz_module_capability, psz_capability ) )
766             count++;
767     }
768     psz_ret = malloc( sizeof(char*) * (count+1) );
769     if( pppsz_longname )
770         *pppsz_longname = malloc( sizeof(char*) * (count+1) );
771     j = 0;
772     for( i = 0 ; i < p_list->i_count; i++)
773     {
774         module_t *p_module = ((module_t *) p_list->p_values[i].p_object);
775         const char *psz_module_capability = p_module->psz_capability;
776         if( psz_module_capability && !strcmp( psz_module_capability, psz_capability ) )
777         {
778             int k = -1; /* hack to handle submodules properly */
779             if( p_module->b_submodule )
780             {
781                 while( p_module->pp_shortcuts[++k] != NULL );
782                 k--;
783             }
784             psz_ret[j] = strdup( k>=0?p_module->pp_shortcuts[k]
785                                      :p_module->psz_object_name );
786             if( pppsz_longname )
787                 (*pppsz_longname)[j] = strdup( module_GetName( p_module, VLC_TRUE ) );
788             j++;
789         }
790     }
791     psz_ret[count] = NULL;
792
793     vlc_list_release( p_list );
794
795     return psz_ret;
796 }
797
798
799 module_config_t *module_GetConfig (const module_t *module, unsigned *restrict psize)
800 {
801     unsigned size = module->confsize;
802     module_config_t *config = malloc (size * sizeof (*config));
803
804     assert (psize != NULL);
805     *psize = 0;
806
807     for (unsigned i = 0, j = 0; i < size; i++)
808     {
809         const module_config_t *item = module->p_config + i;
810         if (item->b_internal /* internal option */
811          || item->b_unsaveable /* non-modifiable option */
812          || item->b_removed /* removed option */)
813             continue;
814
815         if (config != NULL)
816             memcpy (config + j, item, sizeof (*config));
817         *psize = ++j;
818     }
819
820     return config;
821 }
822
823 void module_PutConfig (module_config_t *config)
824 {
825     free (config);
826 }
827
828 /*****************************************************************************
829  * Following functions are local.
830  *****************************************************************************/
831
832 /*****************************************************************************
833  * AllocateAllPlugins: load all plugin modules we can find.
834  *****************************************************************************/
835 #ifdef HAVE_DYNAMIC_PLUGINS
836 static void AllocateAllPlugins( vlc_object_t *p_this )
837 {
838     /* Yes, there are two NULLs because we replace one with "plugin-path". */
839 #if defined( WIN32 ) || defined( UNDER_CE )
840     const char *path[] = { "modules", "", "plugins", NULL, NULL };
841 #else
842     const char *path[] = { "modules", PLUGIN_PATH, "plugins", NULL, NULL };
843 #endif
844
845     const char *const *ppsz_path;
846
847     /* If the user provided a plugin path, we add it to the list */
848     char *userpath = config_GetPsz( p_this, "plugin-path" );
849     path[sizeof(path)/sizeof(path[0]) - 2] = userpath;
850
851     for (ppsz_path = path; *ppsz_path != NULL; ppsz_path++)
852     {
853         char *psz_fullpath;
854
855         if (!**ppsz_path) continue;
856
857 #if defined( SYS_BEOS ) || defined( __APPLE__ ) || defined( WIN32 )
858
859         /* Handle relative as well as absolute paths */
860 #ifdef WIN32
861         if( (*ppsz_path)[0] != '\\' && (*ppsz_path)[0] != '/' &&
862             (*ppsz_path)[1] != ':' )
863 #else
864         if( (*ppsz_path)[0] != '/' )
865 #endif
866         {
867             if( 0>= asprintf( &psz_fullpath, "%s"DIR_SEP"%s",
868                               vlc_global()->psz_vlcpath, *ppsz_path) )
869                 psz_fullpath = NULL;
870         }
871         else
872 #endif
873             psz_fullpath = strdup( *ppsz_path );
874
875         if( psz_fullpath == NULL )
876             continue;
877
878         msg_Dbg( p_this, "recursively browsing `%s'", psz_fullpath );
879
880         /* Don't go deeper than 5 subdirectories */
881         AllocatePluginDir( p_this, psz_fullpath, 5 );
882
883         free( psz_fullpath );
884     }
885
886     /* Free plugin-path */
887     free( userpath );
888 }
889
890 /*****************************************************************************
891  * AllocatePluginDir: recursively parse a directory to look for plugins
892  *****************************************************************************/
893 static void AllocatePluginDir( vlc_object_t *p_this, const char *psz_dir,
894                                int i_maxdepth )
895 {
896 /* FIXME: Needs to be ported to wide char on ALL Windows builds */
897 #ifdef WIN32
898 # undef opendir
899 # undef closedir
900 # undef readdir
901 #endif
902 #if defined( UNDER_CE ) || defined( _MSC_VER )
903 #ifdef UNDER_CE
904     wchar_t psz_wpath[MAX_PATH + 256];
905     wchar_t psz_wdir[MAX_PATH];
906 #endif
907     char psz_path[MAX_PATH + 256];
908     WIN32_FIND_DATA finddata;
909     HANDLE handle;
910     int rc;
911 #else
912     int    i_dirlen;
913     DIR *  dir;
914     struct dirent * file;
915 #endif
916     char * psz_file;
917
918     if( p_this->p_libvlc->b_die || i_maxdepth < 0 )
919     {
920         return;
921     }
922
923 #if defined( UNDER_CE ) || defined( _MSC_VER )
924 #ifdef UNDER_CE
925     MultiByteToWideChar( CP_ACP, 0, psz_dir, -1, psz_wdir, MAX_PATH );
926
927     rc = GetFileAttributes( psz_wdir );
928     if( rc<0 || !(rc&FILE_ATTRIBUTE_DIRECTORY) ) return; /* Not a directory */
929
930     /* Parse all files in the directory */
931     swprintf( psz_wpath, L"%ls\\*", psz_wdir );
932 #else
933     rc = GetFileAttributes( psz_dir );
934     if( rc<0 || !(rc&FILE_ATTRIBUTE_DIRECTORY) ) return; /* Not a directory */
935 #endif
936
937     /* Parse all files in the directory */
938     sprintf( psz_path, "%s\\*", psz_dir );
939
940 #ifdef UNDER_CE
941     handle = FindFirstFile( psz_wpath, &finddata );
942 #else
943     handle = FindFirstFile( psz_path, &finddata );
944 #endif
945     if( handle == INVALID_HANDLE_VALUE )
946     {
947         /* Empty directory */
948         return;
949     }
950
951     /* Parse the directory and try to load all files it contains. */
952     do
953     {
954 #ifdef UNDER_CE
955         unsigned int i_len = wcslen( finddata.cFileName );
956         swprintf( psz_wpath, L"%ls\\%ls", psz_wdir, finddata.cFileName );
957         sprintf( psz_path, "%s\\%ls", psz_dir, finddata.cFileName );
958 #else
959         unsigned int i_len = strlen( finddata.cFileName );
960         sprintf( psz_path, "%s\\%s", psz_dir, finddata.cFileName );
961 #endif
962
963         /* Skip ".", ".." */
964         if( !*finddata.cFileName || !strcmp( finddata.cFileName, "." )
965          || !strcmp( finddata.cFileName, ".." ) )
966         {
967             if( !FindNextFile( handle, &finddata ) ) break;
968             continue;
969         }
970
971 #ifdef UNDER_CE
972         if( GetFileAttributes( psz_wpath ) & FILE_ATTRIBUTE_DIRECTORY )
973 #else
974         if( GetFileAttributes( psz_path ) & FILE_ATTRIBUTE_DIRECTORY )
975 #endif
976         {
977             AllocatePluginDir( p_this, psz_path, i_maxdepth - 1 );
978         }
979         else if( i_len > strlen( LIBEXT )
980                   /* We only load files ending with LIBEXT */
981                   && !strncasecmp( psz_path + strlen( psz_path)
982                                    - strlen( LIBEXT ),
983                                    LIBEXT, strlen( LIBEXT ) ) )
984         {
985             WIN32_FILE_ATTRIBUTE_DATA attrbuf;
986             int64_t i_time = 0, i_size = 0;
987
988 #ifdef UNDER_CE
989             if( GetFileAttributesEx( psz_wpath, GetFileExInfoStandard,
990                                      &attrbuf ) )
991 #else
992             if( GetFileAttributesEx( psz_path, GetFileExInfoStandard,
993                                      &attrbuf ) )
994 #endif
995             {
996                 i_time = attrbuf.ftLastWriteTime.dwHighDateTime;
997                 i_time <<= 32;
998                 i_time |= attrbuf.ftLastWriteTime.dwLowDateTime;
999                 i_size = attrbuf.nFileSizeHigh;
1000                 i_size <<= 32;
1001                 i_size |= attrbuf.nFileSizeLow;
1002             }
1003             psz_file = psz_path;
1004
1005             AllocatePluginFile( p_this, psz_file, i_time, i_size );
1006         }
1007     }
1008     while( !p_this->p_libvlc->b_die && FindNextFile( handle, &finddata ) );
1009
1010     /* Close the directory */
1011     FindClose( handle );
1012
1013 #else
1014     dir = opendir( psz_dir );
1015     if( !dir )
1016     {
1017         return;
1018     }
1019
1020     i_dirlen = strlen( psz_dir );
1021
1022     /* Parse the directory and try to load all files it contains. */
1023     while( !p_this->p_libvlc->b_die && (file = readdir( dir )) )
1024     {
1025         struct stat statbuf;
1026         unsigned int i_len;
1027         int i_stat;
1028
1029         /* Skip ".", ".." */
1030         if( !*file->d_name || !strcmp( file->d_name, "." )
1031          || !strcmp( file->d_name, ".." ) )
1032         {
1033             continue;
1034         }
1035
1036         i_len = strlen( file->d_name );
1037         psz_file = malloc( i_dirlen + 1 + i_len + 1 );
1038         sprintf( psz_file, "%s"DIR_SEP"%s", psz_dir, file->d_name );
1039
1040         i_stat = stat( psz_file, &statbuf );
1041         if( !i_stat && statbuf.st_mode & S_IFDIR )
1042         {
1043             AllocatePluginDir( p_this, psz_file, i_maxdepth - 1 );
1044         }
1045         else if( i_len > strlen( LIBEXT )
1046                   /* We only load files ending with LIBEXT */
1047                   && !strncasecmp( file->d_name + i_len - strlen( LIBEXT ),
1048                                    LIBEXT, strlen( LIBEXT ) ) )
1049         {
1050             int64_t i_time = 0, i_size = 0;
1051
1052             if( !i_stat )
1053             {
1054                 i_time = statbuf.st_mtime;
1055                 i_size = statbuf.st_size;
1056             }
1057
1058             AllocatePluginFile( p_this, psz_file, i_time, i_size );
1059         }
1060
1061         free( psz_file );
1062     }
1063
1064     /* Close the directory */
1065     closedir( dir );
1066
1067 #endif
1068 }
1069
1070 /*****************************************************************************
1071  * AllocatePluginFile: load a module into memory and initialize it.
1072  *****************************************************************************
1073  * This function loads a dynamically loadable module and allocates a structure
1074  * for its information data. The module can then be handled by module_Need
1075  * and module_Unneed. It can be removed by DeleteModule.
1076  *****************************************************************************/
1077 static int AllocatePluginFile( vlc_object_t * p_this, char * psz_file,
1078                                int64_t i_file_time, int64_t i_file_size )
1079 {
1080     module_t * p_module = NULL;
1081     module_cache_t *p_cache_entry = NULL;
1082
1083     /*
1084      * Check our plugins cache first then load plugin if needed
1085      */
1086     p_cache_entry =
1087         CacheFind( psz_file, i_file_time, i_file_size );
1088
1089     if( !p_cache_entry )
1090     {
1091         p_module = AllocatePlugin( p_this, psz_file );
1092     }
1093     else
1094     {
1095         /* If junk dll, don't try to load it */
1096         if( p_cache_entry->b_junk )
1097         {
1098             p_module = NULL;
1099         }
1100         else
1101         {
1102             module_config_t *p_item = NULL, *p_end = NULL;
1103
1104             p_module = p_cache_entry->p_module;
1105             p_module->b_loaded = VLC_FALSE;
1106
1107             /* For now we force loading if the module's config contains
1108              * callbacks or actions.
1109              * Could be optimized by adding an API call.*/
1110             for( p_item = p_module->p_config, p_end = p_item + p_module->confsize;
1111                  p_item < p_end; p_item++ )
1112             {
1113                 if( p_item->pf_callback || p_item->i_action )
1114                 {
1115                     p_module = AllocatePlugin( p_this, psz_file );
1116                     break;
1117                 }
1118             }
1119             if( p_module == p_cache_entry->p_module )
1120                 p_cache_entry->b_used = VLC_TRUE;
1121         }
1122     }
1123
1124     if( p_module )
1125     {
1126         libvlc_global_data_t *p_libvlc_global = vlc_global();
1127
1128         /* Everything worked fine !
1129          * The module is ready to be added to the list. */
1130         p_module->b_builtin = VLC_FALSE;
1131
1132         /* msg_Dbg( p_this, "plugin \"%s\", %s",
1133                     p_module->psz_object_name, p_module->psz_longname ); */
1134
1135         vlc_object_attach( p_module, p_libvlc_global->p_module_bank );
1136
1137         if( !p_libvlc_global->p_module_bank->b_cache )
1138             return 0;
1139
1140 #define p_bank p_libvlc_global->p_module_bank
1141         /* Add entry to cache */
1142         p_bank->pp_cache =
1143             realloc( p_bank->pp_cache, (p_bank->i_cache + 1) * sizeof(void *) );
1144         p_bank->pp_cache[p_bank->i_cache] = malloc( sizeof(module_cache_t) );
1145         if( !p_bank->pp_cache[p_bank->i_cache] )
1146             return -1;
1147         p_bank->pp_cache[p_bank->i_cache]->psz_file = strdup( psz_file );
1148         p_bank->pp_cache[p_bank->i_cache]->i_time = i_file_time;
1149         p_bank->pp_cache[p_bank->i_cache]->i_size = i_file_size;
1150         p_bank->pp_cache[p_bank->i_cache]->b_junk = p_module ? 0 : 1;
1151         p_bank->pp_cache[p_bank->i_cache]->b_used = VLC_TRUE;
1152         p_bank->pp_cache[p_bank->i_cache]->p_module = p_module;
1153         p_bank->i_cache++;
1154     }
1155
1156     return p_module ? 0 : -1;
1157 }
1158
1159 /*****************************************************************************
1160  * AllocatePlugin: load a module into memory and initialize it.
1161  *****************************************************************************
1162  * This function loads a dynamically loadable module and allocates a structure
1163  * for its information data. The module can then be handled by module_Need
1164  * and module_Unneed. It can be removed by DeleteModule.
1165  *****************************************************************************/
1166 static module_t * AllocatePlugin( vlc_object_t * p_this, char * psz_file )
1167 {
1168     module_t * p_module = NULL;
1169     module_handle_t handle;
1170
1171     if( module_Load( p_this, psz_file, &handle ) )
1172         return NULL;
1173
1174     /* Now that we have successfully loaded the module, we can
1175      * allocate a structure for it */
1176     p_module = vlc_module_create( p_this );
1177     if( p_module == NULL )
1178     {
1179         msg_Err( p_this, "out of memory" );
1180         module_Unload( handle );
1181         return NULL;
1182     }
1183
1184     /* We need to fill these since they may be needed by module_Call() */
1185     p_module->psz_filename = psz_file;
1186     p_module->handle = handle;
1187     p_module->b_loaded = VLC_TRUE;
1188
1189     /* Initialize the module: fill p_module, default config */
1190     if( module_Call( p_module ) != 0 )
1191     {
1192         /* We couldn't call module_init() */
1193         vlc_object_destroy( p_module );
1194         module_Unload( handle );
1195         return NULL;
1196     }
1197
1198     DupModule( p_module );
1199     p_module->psz_filename = strdup( p_module->psz_filename );
1200
1201     /* Everything worked fine ! The module is ready to be added to the list. */
1202     p_module->b_builtin = VLC_FALSE;
1203
1204     return p_module;
1205 }
1206
1207 /*****************************************************************************
1208  * DupModule: make a plugin module standalone.
1209  *****************************************************************************
1210  * This function duplicates all strings in the module, so that the dynamic
1211  * object can be unloaded. It acts recursively on submodules.
1212  *****************************************************************************/
1213 static void DupModule( module_t *p_module )
1214 {
1215     const char **pp_shortcut;
1216     int i_submodule;
1217
1218     for( pp_shortcut = p_module->pp_shortcuts ; *pp_shortcut ; pp_shortcut++ )
1219     {
1220         *pp_shortcut = strdup( *pp_shortcut );
1221     }
1222
1223     /* We strdup() these entries so that they are still valid when the
1224      * module is unloaded. */
1225     p_module->psz_object_name = strdup( p_module->psz_object_name );
1226     p_module->psz_capability = strdup( p_module->psz_capability );
1227     p_module->psz_shortname = p_module->psz_shortname ?
1228                                  strdup( p_module->psz_shortname ) : NULL;
1229     p_module->psz_longname = strdup( p_module->psz_longname );
1230     p_module->psz_help = p_module->psz_help ? strdup( p_module->psz_help )
1231                                             : NULL;
1232
1233     for( i_submodule = 0; i_submodule < p_module->i_children; i_submodule++ )
1234     {
1235         DupModule( (module_t*)p_module->pp_children[ i_submodule ] );
1236     }
1237 }
1238
1239 /*****************************************************************************
1240  * UndupModule: free a duplicated module.
1241  *****************************************************************************
1242  * This function frees the allocations done in DupModule().
1243  *****************************************************************************/
1244 static void UndupModule( module_t *p_module )
1245 {
1246     const char **pp_shortcut;
1247     int i_submodule;
1248
1249     for( i_submodule = 0; i_submodule < p_module->i_children; i_submodule++ )
1250     {
1251         UndupModule( (module_t*)p_module->pp_children[ i_submodule ] );
1252     }
1253
1254     for( pp_shortcut = p_module->pp_shortcuts ; *pp_shortcut ; pp_shortcut++ )
1255     {
1256         free( (void*)*pp_shortcut );
1257     }
1258
1259     free( (void*)p_module->psz_object_name );
1260     free( p_module->psz_capability );
1261     free( (void*)p_module->psz_shortname );
1262     free( (void*)p_module->psz_longname );
1263     free( (void*)p_module->psz_help );
1264 }
1265
1266 #endif /* HAVE_DYNAMIC_PLUGINS */
1267
1268 /*****************************************************************************
1269  * AllocateBuiltinModule: initialize a builtin module.
1270  *****************************************************************************
1271  * This function registers a builtin module and allocates a structure
1272  * for its information data. The module can then be handled by module_Need
1273  * and module_Unneed. It can be removed by DeleteModule.
1274  *****************************************************************************/
1275 static int AllocateBuiltinModule( vlc_object_t * p_this,
1276                                   int ( *pf_entry ) ( module_t * ) )
1277 {
1278     module_t * p_module;
1279
1280     /* Now that we have successfully loaded the module, we can
1281      * allocate a structure for it */
1282     p_module = vlc_module_create( p_this );
1283     if( p_module == NULL )
1284     {
1285         msg_Err( p_this, "out of memory" );
1286         return -1;
1287     }
1288
1289     /* Initialize the module : fill p_module->psz_object_name, etc. */
1290     if( pf_entry( p_module ) != 0 )
1291     {
1292         /* With a well-written module we shouldn't have to print an
1293          * additional error message here, but just make sure. */
1294         msg_Err( p_this, "failed calling entry point in builtin module" );
1295         vlc_object_destroy( p_module );
1296         return -1;
1297     }
1298
1299     /* Everything worked fine ! The module is ready to be added to the list. */
1300     p_module->b_builtin = VLC_TRUE;
1301
1302     /* msg_Dbg( p_this, "builtin \"%s\", %s",
1303                 p_module->psz_object_name, p_module->psz_longname ); */
1304
1305     vlc_object_attach( p_module, vlc_global()->p_module_bank );
1306
1307     return 0;
1308 }
1309
1310 /*****************************************************************************
1311  * DeleteModule: delete a module and its structure.
1312  *****************************************************************************
1313  * This function can only be called if the module isn't being used.
1314  *****************************************************************************/
1315 static int DeleteModule( module_t * p_module, vlc_bool_t b_detach )
1316 {
1317     if( !p_module ) return VLC_EGENERIC;
1318     if( b_detach )
1319         vlc_object_detach( p_module );
1320
1321     /* We free the structures that we strdup()ed in Allocate*Module(). */
1322 #ifdef HAVE_DYNAMIC_PLUGINS
1323     if( !p_module->b_builtin )
1324     {
1325         if( p_module->b_loaded && p_module->b_unloadable )
1326         {
1327             module_Unload( p_module->handle );
1328         }
1329         UndupModule( p_module );
1330         free( p_module->psz_filename );
1331     }
1332 #endif
1333
1334     /* Free and detach the object's children */
1335     while( p_module->i_children )
1336     {
1337         vlc_object_t *p_this = p_module->pp_children[0];
1338         vlc_object_detach( p_this );
1339         vlc_object_destroy( p_this );
1340     }
1341
1342     config_Free( p_module );
1343     vlc_object_destroy( p_module );
1344     p_module = NULL;
1345     return 0;
1346 }