]> git.sesse.net Git - vlc/blob - src/modules/modules.c
Delete unneeded instruction from a loop
[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 i,j;
802     unsigned size = module->confsize;
803     module_config_t *config = malloc (size * sizeof (*config));
804
805     assert (psize != NULL);
806     *psize = 0;
807
808     for (i = 0, j = 0; i < size; i++)
809     {
810         const module_config_t *item = module->p_config + i;
811         if (item->b_internal /* internal option */
812          || item->b_unsaveable /* non-modifiable option */
813          || item->b_removed /* removed option */)
814             continue;
815
816         if (config != NULL)
817             memcpy (config + j, item, sizeof (*config));
818         j++;
819     }
820     *psize = j;
821
822     return config;
823 }
824
825 void module_PutConfig (module_config_t *config)
826 {
827     free (config);
828 }
829
830 /*****************************************************************************
831  * Following functions are local.
832  *****************************************************************************/
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 )
839 {
840     /* Yes, there are two NULLs because we replace one with "plugin-path". */
841 #if defined( WIN32 ) || defined( UNDER_CE )
842     const char *path[] = { "modules", "", "plugins", NULL, NULL };
843 #else
844     const char *path[] = { "modules", PLUGIN_PATH, "plugins", NULL, NULL };
845 #endif
846
847     const char *const *ppsz_path;
848
849     /* If the user provided a plugin path, we add it to the list */
850     char *userpath = config_GetPsz( p_this, "plugin-path" );
851     path[sizeof(path)/sizeof(path[0]) - 2] = userpath;
852
853     for (ppsz_path = path; *ppsz_path != NULL; ppsz_path++)
854     {
855         char *psz_fullpath;
856
857         if (!**ppsz_path) continue;
858
859 #if defined( SYS_BEOS ) || defined( __APPLE__ ) || defined( WIN32 )
860
861         /* Handle relative as well as absolute paths */
862 #ifdef WIN32
863         if( (*ppsz_path)[0] != '\\' && (*ppsz_path)[0] != '/' &&
864             (*ppsz_path)[1] != ':' )
865 #else
866         if( (*ppsz_path)[0] != '/' )
867 #endif
868         {
869             if( 0>= asprintf( &psz_fullpath, "%s"DIR_SEP"%s",
870                               vlc_global()->psz_vlcpath, *ppsz_path) )
871                 psz_fullpath = NULL;
872         }
873         else
874 #endif
875             psz_fullpath = strdup( *ppsz_path );
876
877         if( psz_fullpath == NULL )
878             continue;
879
880         msg_Dbg( p_this, "recursively browsing `%s'", psz_fullpath );
881
882         /* Don't go deeper than 5 subdirectories */
883         AllocatePluginDir( p_this, psz_fullpath, 5 );
884
885         free( psz_fullpath );
886     }
887
888     /* Free plugin-path */
889     free( userpath );
890 }
891
892 /*****************************************************************************
893  * AllocatePluginDir: recursively parse a directory to look for plugins
894  *****************************************************************************/
895 static void AllocatePluginDir( vlc_object_t *p_this, const char *psz_dir,
896                                int i_maxdepth )
897 {
898 /* FIXME: Needs to be ported to wide char on ALL Windows builds */
899 #ifdef WIN32
900 # undef opendir
901 # undef closedir
902 # undef readdir
903 #endif
904 #if defined( UNDER_CE ) || defined( _MSC_VER )
905 #ifdef UNDER_CE
906     wchar_t psz_wpath[MAX_PATH + 256];
907     wchar_t psz_wdir[MAX_PATH];
908 #endif
909     char psz_path[MAX_PATH + 256];
910     WIN32_FIND_DATA finddata;
911     HANDLE handle;
912     int rc;
913 #else
914     int    i_dirlen;
915     DIR *  dir;
916     struct dirent * file;
917 #endif
918     char * psz_file;
919
920     if( p_this->p_libvlc->b_die || i_maxdepth < 0 )
921     {
922         return;
923     }
924
925 #if defined( UNDER_CE ) || defined( _MSC_VER )
926 #ifdef UNDER_CE
927     MultiByteToWideChar( CP_ACP, 0, psz_dir, -1, psz_wdir, MAX_PATH );
928
929     rc = GetFileAttributes( psz_wdir );
930     if( rc<0 || !(rc&FILE_ATTRIBUTE_DIRECTORY) ) return; /* Not a directory */
931
932     /* Parse all files in the directory */
933     swprintf( psz_wpath, L"%ls\\*", psz_wdir );
934 #else
935     rc = GetFileAttributes( psz_dir );
936     if( rc<0 || !(rc&FILE_ATTRIBUTE_DIRECTORY) ) return; /* Not a directory */
937 #endif
938
939     /* Parse all files in the directory */
940     sprintf( psz_path, "%s\\*", psz_dir );
941
942 #ifdef UNDER_CE
943     handle = FindFirstFile( psz_wpath, &finddata );
944 #else
945     handle = FindFirstFile( psz_path, &finddata );
946 #endif
947     if( handle == INVALID_HANDLE_VALUE )
948     {
949         /* Empty directory */
950         return;
951     }
952
953     /* Parse the directory and try to load all files it contains. */
954     do
955     {
956 #ifdef UNDER_CE
957         unsigned int i_len = wcslen( finddata.cFileName );
958         swprintf( psz_wpath, L"%ls\\%ls", psz_wdir, finddata.cFileName );
959         sprintf( psz_path, "%s\\%ls", psz_dir, finddata.cFileName );
960 #else
961         unsigned int i_len = strlen( finddata.cFileName );
962         sprintf( psz_path, "%s\\%s", psz_dir, finddata.cFileName );
963 #endif
964
965         /* Skip ".", ".." */
966         if( !*finddata.cFileName || !strcmp( finddata.cFileName, "." )
967          || !strcmp( finddata.cFileName, ".." ) )
968         {
969             if( !FindNextFile( handle, &finddata ) ) break;
970             continue;
971         }
972
973 #ifdef UNDER_CE
974         if( GetFileAttributes( psz_wpath ) & FILE_ATTRIBUTE_DIRECTORY )
975 #else
976         if( GetFileAttributes( psz_path ) & FILE_ATTRIBUTE_DIRECTORY )
977 #endif
978         {
979             AllocatePluginDir( p_this, psz_path, i_maxdepth - 1 );
980         }
981         else if( i_len > strlen( LIBEXT )
982                   /* We only load files ending with LIBEXT */
983                   && !strncasecmp( psz_path + strlen( psz_path)
984                                    - strlen( LIBEXT ),
985                                    LIBEXT, strlen( LIBEXT ) ) )
986         {
987             WIN32_FILE_ATTRIBUTE_DATA attrbuf;
988             int64_t i_time = 0, i_size = 0;
989
990 #ifdef UNDER_CE
991             if( GetFileAttributesEx( psz_wpath, GetFileExInfoStandard,
992                                      &attrbuf ) )
993 #else
994             if( GetFileAttributesEx( psz_path, GetFileExInfoStandard,
995                                      &attrbuf ) )
996 #endif
997             {
998                 i_time = attrbuf.ftLastWriteTime.dwHighDateTime;
999                 i_time <<= 32;
1000                 i_time |= attrbuf.ftLastWriteTime.dwLowDateTime;
1001                 i_size = attrbuf.nFileSizeHigh;
1002                 i_size <<= 32;
1003                 i_size |= attrbuf.nFileSizeLow;
1004             }
1005             psz_file = psz_path;
1006
1007             AllocatePluginFile( p_this, psz_file, i_time, i_size );
1008         }
1009     }
1010     while( !p_this->p_libvlc->b_die && FindNextFile( handle, &finddata ) );
1011
1012     /* Close the directory */
1013     FindClose( handle );
1014
1015 #else
1016     dir = opendir( psz_dir );
1017     if( !dir )
1018     {
1019         return;
1020     }
1021
1022     i_dirlen = strlen( psz_dir );
1023
1024     /* Parse the directory and try to load all files it contains. */
1025     while( !p_this->p_libvlc->b_die && (file = readdir( dir )) )
1026     {
1027         struct stat statbuf;
1028         unsigned int i_len;
1029         int i_stat;
1030
1031         /* Skip ".", ".." */
1032         if( !*file->d_name || !strcmp( file->d_name, "." )
1033          || !strcmp( file->d_name, ".." ) )
1034         {
1035             continue;
1036         }
1037
1038         i_len = strlen( file->d_name );
1039         psz_file = malloc( i_dirlen + 1 + i_len + 1 );
1040         sprintf( psz_file, "%s"DIR_SEP"%s", psz_dir, file->d_name );
1041
1042         i_stat = stat( psz_file, &statbuf );
1043         if( !i_stat && statbuf.st_mode & S_IFDIR )
1044         {
1045             AllocatePluginDir( p_this, psz_file, i_maxdepth - 1 );
1046         }
1047         else if( i_len > strlen( LIBEXT )
1048                   /* We only load files ending with LIBEXT */
1049                   && !strncasecmp( file->d_name + i_len - strlen( LIBEXT ),
1050                                    LIBEXT, strlen( LIBEXT ) ) )
1051         {
1052             int64_t i_time = 0, i_size = 0;
1053
1054             if( !i_stat )
1055             {
1056                 i_time = statbuf.st_mtime;
1057                 i_size = statbuf.st_size;
1058             }
1059
1060             AllocatePluginFile( p_this, psz_file, i_time, i_size );
1061         }
1062
1063         free( psz_file );
1064     }
1065
1066     /* Close the directory */
1067     closedir( dir );
1068
1069 #endif
1070 }
1071
1072 /*****************************************************************************
1073  * AllocatePluginFile: load a module into memory and initialize it.
1074  *****************************************************************************
1075  * This function loads a dynamically loadable module and allocates a structure
1076  * for its information data. The module can then be handled by module_Need
1077  * and module_Unneed. It can be removed by DeleteModule.
1078  *****************************************************************************/
1079 static int AllocatePluginFile( vlc_object_t * p_this, char * psz_file,
1080                                int64_t i_file_time, int64_t i_file_size )
1081 {
1082     module_t * p_module = NULL;
1083     module_cache_t *p_cache_entry = NULL;
1084
1085     /*
1086      * Check our plugins cache first then load plugin if needed
1087      */
1088     p_cache_entry =
1089         CacheFind( psz_file, i_file_time, i_file_size );
1090
1091     if( !p_cache_entry )
1092     {
1093         p_module = AllocatePlugin( p_this, psz_file );
1094     }
1095     else
1096     {
1097         /* If junk dll, don't try to load it */
1098         if( p_cache_entry->b_junk )
1099         {
1100             p_module = NULL;
1101         }
1102         else
1103         {
1104             module_config_t *p_item = NULL, *p_end = NULL;
1105
1106             p_module = p_cache_entry->p_module;
1107             p_module->b_loaded = VLC_FALSE;
1108
1109             /* For now we force loading if the module's config contains
1110              * callbacks or actions.
1111              * Could be optimized by adding an API call.*/
1112             for( p_item = p_module->p_config, p_end = p_item + p_module->confsize;
1113                  p_item < p_end; p_item++ )
1114             {
1115                 if( p_item->pf_callback || p_item->i_action )
1116                 {
1117                     p_module = AllocatePlugin( p_this, psz_file );
1118                     break;
1119                 }
1120             }
1121             if( p_module == p_cache_entry->p_module )
1122                 p_cache_entry->b_used = VLC_TRUE;
1123         }
1124     }
1125
1126     if( p_module )
1127     {
1128         libvlc_global_data_t *p_libvlc_global = vlc_global();
1129
1130         /* Everything worked fine !
1131          * The module is ready to be added to the list. */
1132         p_module->b_builtin = VLC_FALSE;
1133
1134         /* msg_Dbg( p_this, "plugin \"%s\", %s",
1135                     p_module->psz_object_name, p_module->psz_longname ); */
1136
1137         vlc_object_attach( p_module, p_libvlc_global->p_module_bank );
1138
1139         if( !p_libvlc_global->p_module_bank->b_cache )
1140             return 0;
1141
1142 #define p_bank p_libvlc_global->p_module_bank
1143         /* Add entry to cache */
1144         p_bank->pp_cache =
1145             realloc( p_bank->pp_cache, (p_bank->i_cache + 1) * sizeof(void *) );
1146         p_bank->pp_cache[p_bank->i_cache] = malloc( sizeof(module_cache_t) );
1147         if( !p_bank->pp_cache[p_bank->i_cache] )
1148             return -1;
1149         p_bank->pp_cache[p_bank->i_cache]->psz_file = strdup( psz_file );
1150         p_bank->pp_cache[p_bank->i_cache]->i_time = i_file_time;
1151         p_bank->pp_cache[p_bank->i_cache]->i_size = i_file_size;
1152         p_bank->pp_cache[p_bank->i_cache]->b_junk = p_module ? 0 : 1;
1153         p_bank->pp_cache[p_bank->i_cache]->b_used = VLC_TRUE;
1154         p_bank->pp_cache[p_bank->i_cache]->p_module = p_module;
1155         p_bank->i_cache++;
1156     }
1157
1158     return p_module ? 0 : -1;
1159 }
1160
1161 /*****************************************************************************
1162  * AllocatePlugin: load a module into memory and initialize it.
1163  *****************************************************************************
1164  * This function loads a dynamically loadable module and allocates a structure
1165  * for its information data. The module can then be handled by module_Need
1166  * and module_Unneed. It can be removed by DeleteModule.
1167  *****************************************************************************/
1168 static module_t * AllocatePlugin( vlc_object_t * p_this, char * psz_file )
1169 {
1170     module_t * p_module = NULL;
1171     module_handle_t handle;
1172
1173     if( module_Load( p_this, psz_file, &handle ) )
1174         return NULL;
1175
1176     /* Now that we have successfully loaded the module, we can
1177      * allocate a structure for it */
1178     p_module = vlc_module_create( p_this );
1179     if( p_module == NULL )
1180     {
1181         msg_Err( p_this, "out of memory" );
1182         module_Unload( handle );
1183         return NULL;
1184     }
1185
1186     /* We need to fill these since they may be needed by module_Call() */
1187     p_module->psz_filename = psz_file;
1188     p_module->handle = handle;
1189     p_module->b_loaded = VLC_TRUE;
1190
1191     /* Initialize the module: fill p_module, default config */
1192     if( module_Call( p_module ) != 0 )
1193     {
1194         /* We couldn't call module_init() */
1195         vlc_object_destroy( p_module );
1196         module_Unload( handle );
1197         return NULL;
1198     }
1199
1200     DupModule( p_module );
1201     p_module->psz_filename = strdup( p_module->psz_filename );
1202
1203     /* Everything worked fine ! The module is ready to be added to the list. */
1204     p_module->b_builtin = VLC_FALSE;
1205
1206     return p_module;
1207 }
1208
1209 /*****************************************************************************
1210  * DupModule: make a plugin module standalone.
1211  *****************************************************************************
1212  * This function duplicates all strings in the module, so that the dynamic
1213  * object can be unloaded. It acts recursively on submodules.
1214  *****************************************************************************/
1215 static void DupModule( module_t *p_module )
1216 {
1217     const char **pp_shortcut;
1218     int i_submodule;
1219
1220     for( pp_shortcut = p_module->pp_shortcuts ; *pp_shortcut ; pp_shortcut++ )
1221     {
1222         *pp_shortcut = strdup( *pp_shortcut );
1223     }
1224
1225     /* We strdup() these entries so that they are still valid when the
1226      * module is unloaded. */
1227     p_module->psz_object_name = strdup( p_module->psz_object_name );
1228     p_module->psz_capability = strdup( p_module->psz_capability );
1229     p_module->psz_shortname = p_module->psz_shortname ?
1230                                  strdup( p_module->psz_shortname ) : NULL;
1231     p_module->psz_longname = strdup( p_module->psz_longname );
1232     p_module->psz_help = p_module->psz_help ? strdup( p_module->psz_help )
1233                                             : NULL;
1234
1235     for( i_submodule = 0; i_submodule < p_module->i_children; i_submodule++ )
1236     {
1237         DupModule( (module_t*)p_module->pp_children[ i_submodule ] );
1238     }
1239 }
1240
1241 /*****************************************************************************
1242  * UndupModule: free a duplicated module.
1243  *****************************************************************************
1244  * This function frees the allocations done in DupModule().
1245  *****************************************************************************/
1246 static void UndupModule( module_t *p_module )
1247 {
1248     const char **pp_shortcut;
1249     int i_submodule;
1250
1251     for( i_submodule = 0; i_submodule < p_module->i_children; i_submodule++ )
1252     {
1253         UndupModule( (module_t*)p_module->pp_children[ i_submodule ] );
1254     }
1255
1256     for( pp_shortcut = p_module->pp_shortcuts ; *pp_shortcut ; pp_shortcut++ )
1257     {
1258         free( (void*)*pp_shortcut );
1259     }
1260
1261     free( (void*)p_module->psz_object_name );
1262     free( p_module->psz_capability );
1263     free( (void*)p_module->psz_shortname );
1264     free( (void*)p_module->psz_longname );
1265     free( (void*)p_module->psz_help );
1266 }
1267
1268 #endif /* HAVE_DYNAMIC_PLUGINS */
1269
1270 /*****************************************************************************
1271  * AllocateBuiltinModule: initialize a builtin module.
1272  *****************************************************************************
1273  * This function registers a builtin module and allocates a structure
1274  * for its information data. The module can then be handled by module_Need
1275  * and module_Unneed. It can be removed by DeleteModule.
1276  *****************************************************************************/
1277 static int AllocateBuiltinModule( vlc_object_t * p_this,
1278                                   int ( *pf_entry ) ( module_t * ) )
1279 {
1280     module_t * p_module;
1281
1282     /* Now that we have successfully loaded the module, we can
1283      * allocate a structure for it */
1284     p_module = vlc_module_create( p_this );
1285     if( p_module == NULL )
1286     {
1287         msg_Err( p_this, "out of memory" );
1288         return -1;
1289     }
1290
1291     /* Initialize the module : fill p_module->psz_object_name, etc. */
1292     if( pf_entry( p_module ) != 0 )
1293     {
1294         /* With a well-written module we shouldn't have to print an
1295          * additional error message here, but just make sure. */
1296         msg_Err( p_this, "failed calling entry point in builtin module" );
1297         vlc_object_destroy( p_module );
1298         return -1;
1299     }
1300
1301     /* Everything worked fine ! The module is ready to be added to the list. */
1302     p_module->b_builtin = VLC_TRUE;
1303
1304     /* msg_Dbg( p_this, "builtin \"%s\", %s",
1305                 p_module->psz_object_name, p_module->psz_longname ); */
1306
1307     vlc_object_attach( p_module, vlc_global()->p_module_bank );
1308
1309     return 0;
1310 }
1311
1312 /*****************************************************************************
1313  * DeleteModule: delete a module and its structure.
1314  *****************************************************************************
1315  * This function can only be called if the module isn't being used.
1316  *****************************************************************************/
1317 static int DeleteModule( module_t * p_module, vlc_bool_t b_detach )
1318 {
1319     if( !p_module ) return VLC_EGENERIC;
1320     if( b_detach )
1321         vlc_object_detach( p_module );
1322
1323     /* We free the structures that we strdup()ed in Allocate*Module(). */
1324 #ifdef HAVE_DYNAMIC_PLUGINS
1325     if( !p_module->b_builtin )
1326     {
1327         if( p_module->b_loaded && p_module->b_unloadable )
1328         {
1329             module_Unload( p_module->handle );
1330         }
1331         UndupModule( p_module );
1332         free( p_module->psz_filename );
1333     }
1334 #endif
1335
1336     /* Free and detach the object's children */
1337     while( p_module->i_children )
1338     {
1339         vlc_object_t *p_this = p_module->pp_children[0];
1340         vlc_object_detach( p_this );
1341         vlc_object_destroy( p_this );
1342     }
1343
1344     config_Free( p_module );
1345     vlc_object_destroy( p_module );
1346     p_module = NULL;
1347     return 0;
1348 }