]> git.sesse.net Git - vlc/blob - src/modules/modules.c
fdf123683371be952f0d51c70fcf6461585e64c9
[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 #include <vlc/vlc.h>
28 #include "../libvlc.h"
29
30 /* Some faulty libcs have a broken struct dirent when _FILE_OFFSET_BITS
31  * is set to 64. Don't try to be cleverer. */
32 #ifdef _FILE_OFFSET_BITS
33 #undef _FILE_OFFSET_BITS
34 #endif
35
36 #include <stdlib.h>                                      /* free(), strtol() */
37 #include <stdio.h>                                              /* sprintf() */
38 #include <string.h>                                              /* strdup() */
39
40 #ifdef HAVE_DIRENT_H
41 #   include <dirent.h>
42 #endif
43
44 #ifdef HAVE_SYS_TYPES_H
45 #   include <sys/types.h>
46 #endif
47 #ifdef HAVE_SYS_STAT_H
48 #   include <sys/stat.h>
49 #endif
50 #ifdef HAVE_UNISTD_H
51 #   include <unistd.h>
52 #endif
53
54 #if !defined(HAVE_DYNAMIC_PLUGINS)
55     /* no support for plugins */
56 #elif defined(HAVE_DL_DYLD)
57 #   if defined(HAVE_MACH_O_DYLD_H)
58 #       include <mach-o/dyld.h>
59 #   endif
60 #elif defined(HAVE_DL_BEOS)
61 #   if defined(HAVE_IMAGE_H)
62 #       include <image.h>
63 #   endif
64 #elif defined(HAVE_DL_WINDOWS)
65 #   include <windows.h>
66 #elif defined(HAVE_DL_DLOPEN)
67 #   if defined(HAVE_DLFCN_H) /* Linux, BSD, Hurd */
68 #       include <dlfcn.h>
69 #   endif
70 #   if defined(HAVE_SYS_DL_H)
71 #       include <sys/dl.h>
72 #   endif
73 #elif defined(HAVE_DL_SHL_LOAD)
74 #   if defined(HAVE_DL_H)
75 #       include <dl.h>
76 #   endif
77 #endif
78
79 #include "modules/configuration.h"
80 #include "libvlc.h"
81
82 #include "vlc_interface.h"
83 #include "vlc_playlist.h"
84
85 #include "vlc_stream.h"
86 #include "vlc_access.h"
87 #include "vlc_demux.h"
88 #include "vlc_codec.h"
89
90 #include "vlc_vout.h"
91 #include "vlc_vout_synchro.h"
92
93 #include "vlc_aout.h"
94
95 #include "vlc_sout.h"
96 #include "vlc_httpd.h"
97 #include "vlc_acl.h"
98 #include "vlc_tls.h"
99 #include "vlc_md5.h"
100 #include "vlc_xml.h"
101 #include "vlc_url.h"
102
103 #include "iso_lang.h"
104 #include "vlc_charset.h"
105
106 #include "vlc_block.h"
107
108 #include "vlc_vlm.h"
109
110 #include "vlc_image.h"
111 #include "vlc_osd.h"
112
113 #include "vlc_update.h"
114 #include "vlc_strings.h"
115 #include "vlc_streaming.h"
116
117 #include "modules/modules.h"
118 #include "modules/builtin.h"
119
120 #include "vlc_network.h"
121
122 #if defined( WIN32 ) || defined( UNDER_CE )
123     /* Avoid name collisions */
124 #   define LoadModule(a,b,c) LoadVlcModule(a,b,c)
125 #endif
126
127 /*****************************************************************************
128  * Local prototypes
129  *****************************************************************************/
130 #ifdef HAVE_DYNAMIC_PLUGINS
131 static void AllocateAllPlugins  ( vlc_object_t * );
132 static void AllocatePluginDir   ( vlc_object_t *, const char *, int );
133 static int  AllocatePluginFile  ( vlc_object_t *, char *, int64_t, int64_t );
134 static module_t * AllocatePlugin( vlc_object_t *, char * );
135 #endif
136 static int  AllocateBuiltinModule( vlc_object_t *, int ( * ) ( module_t * ) );
137 static int  DeleteModule ( module_t *, vlc_bool_t );
138 #ifdef HAVE_DYNAMIC_PLUGINS
139 static void   DupModule        ( module_t * );
140 static void   UndupModule      ( module_t * );
141 static int    CallEntry        ( module_t * );
142 static int    LoadModule       ( vlc_object_t *, char *, module_handle_t * );
143 static void   CloseModule      ( module_handle_t );
144 static void * GetSymbol        ( module_handle_t, const char * );
145 static void   CacheLoad        ( vlc_object_t * );
146 static int    CacheLoadConfig  ( module_t *, FILE * );
147 static void   CacheSave        ( vlc_object_t * );
148 static void   CacheSaveConfig  ( module_t *, FILE * );
149 static char * CacheName        ( void );
150 static void   CacheMerge       ( vlc_object_t *, module_t *, module_t * );
151 static module_cache_t * CacheFind( vlc_object_t *, char *, int64_t, int64_t );
152
153 #if defined(HAVE_DL_WINDOWS)
154 static char * GetWindowsError  ( void );
155 #endif
156 #endif
157
158 static void module_LoadMain( vlc_object_t *p_this );
159
160 /* Sub-version number
161  * (only used to avoid breakage in dev version when cache structure changes) */
162 #define CACHE_SUBVERSION_NUM 3
163
164 /*****************************************************************************
165  * module_InitBank: create the module bank.
166  *****************************************************************************
167  * This function creates a module bank structure which will be filled later
168  * on with all the modules found.
169  *****************************************************************************/
170 void __module_InitBank( vlc_object_t *p_this )
171 {
172     module_bank_t *p_bank = NULL;
173     vlc_value_t  lockval;
174     libvlc_global_data_t *p_libvlc_global = vlc_global( p_this );
175
176     var_Create( p_libvlc_global, "libvlc", VLC_VAR_MUTEX );
177     var_Get( p_libvlc_global, "libvlc", &lockval );
178     vlc_mutex_lock( lockval.p_address );
179     if( p_libvlc_global->p_module_bank )
180     {
181         p_libvlc_global->p_module_bank->i_usage++;
182         vlc_mutex_unlock( lockval.p_address );
183         var_Destroy( p_libvlc_global, "libvlc" );
184         return;
185     }
186     vlc_mutex_unlock( lockval.p_address );
187     var_Destroy( p_libvlc_global, "libvlc" );
188
189     p_bank = vlc_object_create( p_this, sizeof(module_bank_t) );
190     if( !p_bank )
191         return;
192     p_bank->psz_object_name = "module bank";
193     p_bank->i_usage = 1;
194     p_bank->i_cache = p_bank->i_loaded_cache = 0;
195     p_bank->pp_cache = p_bank->pp_loaded_cache = NULL;
196     p_bank->b_cache = p_bank->b_cache_dirty =
197         p_bank->b_cache_delete = VLC_FALSE;
198
199     /* Everything worked, attach the object */
200     p_libvlc_global->p_module_bank = p_bank;
201     vlc_object_attach( p_bank, p_libvlc_global );
202
203     module_LoadMain( p_this );
204 }
205
206
207 /*****************************************************************************
208  * module_EndBank: empty the module bank.
209  *****************************************************************************
210  * This function unloads all unused plugin modules and empties the module
211  * bank in case of success.
212  *****************************************************************************/
213 void __module_EndBank( vlc_object_t *p_this )
214 {
215     module_t * p_next = NULL;
216     vlc_value_t lockval;
217     libvlc_global_data_t *p_libvlc_global = vlc_global( p_this );
218
219     var_Create( p_libvlc_global, "libvlc", VLC_VAR_MUTEX );
220     var_Get( p_libvlc_global, "libvlc", &lockval );
221     vlc_mutex_lock( lockval.p_address );
222     if( !p_libvlc_global->p_module_bank )
223     {
224         vlc_mutex_unlock( lockval.p_address );
225         var_Destroy( p_libvlc_global, "libvlc" );
226         return;
227     }
228     if( --p_libvlc_global->p_module_bank->i_usage )
229     {
230         vlc_mutex_unlock( lockval.p_address );
231         var_Destroy( p_libvlc_global, "libvlc" );
232         return;
233     }
234     vlc_mutex_unlock( lockval.p_address );
235     var_Destroy( p_libvlc_global, "libvlc" );
236
237     config_AutoSaveConfigFile( p_this );
238
239 #ifdef HAVE_DYNAMIC_PLUGINS
240 # define p_bank p_libvlc_global->p_module_bank
241     if( p_bank->b_cache ) CacheSave( p_this );
242     while( p_bank->i_loaded_cache-- )
243     {
244         if( p_bank->pp_loaded_cache[p_bank->i_loaded_cache] )
245         {
246             DeleteModule( p_bank->pp_loaded_cache[p_bank->i_loaded_cache]->p_module,
247                           p_bank->pp_loaded_cache[p_bank->i_loaded_cache]->b_used );
248             free( p_bank->pp_loaded_cache[p_bank->i_loaded_cache]->psz_file );
249             free( p_bank->pp_loaded_cache[p_bank->i_loaded_cache] );
250             p_bank->pp_loaded_cache[p_bank->i_loaded_cache] = NULL;
251         }
252     }
253     if( p_bank->pp_loaded_cache )
254     {
255         free( p_bank->pp_loaded_cache );
256         p_bank->pp_loaded_cache = NULL;
257     }
258     while( p_bank->i_cache-- )
259     {
260         free( p_bank->pp_cache[p_bank->i_cache]->psz_file );
261         free( p_bank->pp_cache[p_bank->i_cache] );
262         p_bank->pp_cache[p_bank->i_cache] = NULL;
263     }
264     if( p_bank->pp_cache )
265     {
266         free( p_bank->pp_cache );
267         p_bank->pp_cache = NULL;
268     }
269 # undef p_bank
270 #endif
271
272     vlc_object_detach( p_libvlc_global->p_module_bank );
273
274     while( p_libvlc_global->p_module_bank->i_children )
275     {
276         p_next = (module_t *)p_libvlc_global->p_module_bank->pp_children[0];
277
278         if( DeleteModule( p_next, VLC_TRUE ) )
279         {
280             /* Module deletion failed */
281             msg_Err( p_this, "module \"%s\" can't be removed, trying harder",
282                      p_next->psz_object_name );
283
284             /* We just free the module by hand. Niahahahahaha. */
285             vlc_object_detach( p_next );
286             vlc_object_destroy( p_next );
287         }
288     }
289
290     vlc_object_destroy( p_libvlc_global->p_module_bank );
291     p_libvlc_global->p_module_bank = NULL;
292 }
293
294 /*****************************************************************************
295  * module_LoadMain: load the main program info into the module bank.
296  *****************************************************************************
297  * This function fills the module bank structure with the main module infos.
298  * This is very useful as it will allow us to consider the main program just
299  * as another module, and for instance the configuration options of main will
300  * be available in the module bank structure just as for every other module.
301  *****************************************************************************/
302 static void module_LoadMain( vlc_object_t *p_this )
303 {
304     vlc_value_t lockval;
305     libvlc_global_data_t *p_libvlc_global = vlc_global( p_this );
306
307     var_Create( p_libvlc_global, "libvlc", VLC_VAR_MUTEX );
308     var_Get( p_libvlc_global, "libvlc", &lockval );
309     vlc_mutex_lock( lockval.p_address );
310     if( p_libvlc_global->p_module_bank->b_main )
311     {
312         vlc_mutex_unlock( lockval.p_address );
313         var_Destroy( p_libvlc_global, "libvlc" );
314         return;
315     }
316     p_libvlc_global->p_module_bank->b_main = VLC_TRUE;
317     vlc_mutex_unlock( lockval.p_address );
318     var_Destroy( p_libvlc_global, "libvlc" );
319
320     AllocateBuiltinModule( p_this, vlc_entry__main );
321 }
322
323 /*****************************************************************************
324  * module_LoadBuiltins: load all modules which we built with.
325  *****************************************************************************
326  * This function fills the module bank structure with the builtin modules.
327  *****************************************************************************/
328 void __module_LoadBuiltins( vlc_object_t * p_this )
329 {
330     vlc_value_t lockval;
331     libvlc_global_data_t *p_libvlc_global = vlc_global( p_this );
332
333     var_Create( p_libvlc_global, "libvlc", VLC_VAR_MUTEX );
334     var_Get( p_libvlc_global, "libvlc", &lockval );
335     vlc_mutex_lock( lockval.p_address );
336     if( p_libvlc_global->p_module_bank->b_builtins )
337     {
338         vlc_mutex_unlock( lockval.p_address );
339         var_Destroy( p_libvlc_global, "libvlc" );
340         return;
341     }
342     p_libvlc_global->p_module_bank->b_builtins = VLC_TRUE;
343     vlc_mutex_unlock( lockval.p_address );
344     var_Destroy( p_libvlc_global, "libvlc" );
345
346     msg_Dbg( p_this, "checking builtin modules" );
347     ALLOCATE_ALL_BUILTINS();
348 }
349
350 /*****************************************************************************
351  * module_LoadPlugins: load all plugin modules we can find.
352  *****************************************************************************
353  * This function fills the module bank structure with the plugin modules.
354  *****************************************************************************/
355 void __module_LoadPlugins( vlc_object_t * p_this )
356 {
357 #ifdef HAVE_DYNAMIC_PLUGINS
358     vlc_value_t lockval;
359     libvlc_global_data_t *p_libvlc_global = vlc_global( p_this );
360
361     var_Create( p_libvlc_global, "libvlc", VLC_VAR_MUTEX );
362     var_Get( p_libvlc_global, "libvlc", &lockval );
363     vlc_mutex_lock( lockval.p_address );
364     if( p_libvlc_global->p_module_bank->b_plugins )
365     {
366         vlc_mutex_unlock( lockval.p_address );
367         var_Destroy( p_libvlc_global, "libvlc" );
368         return;
369     }
370     p_libvlc_global->p_module_bank->b_plugins = VLC_TRUE;
371     vlc_mutex_unlock( lockval.p_address );
372     var_Destroy( p_libvlc_global, "libvlc" );
373
374     msg_Dbg( p_this, "checking plugin modules" );
375
376     if( config_GetInt( p_this, "plugins-cache" ) )
377         p_libvlc_global->p_module_bank->b_cache = VLC_TRUE;
378
379     if( p_libvlc_global->p_module_bank->b_cache ||
380         p_libvlc_global->p_module_bank->b_cache_delete ) CacheLoad( p_this );
381
382     AllocateAllPlugins( p_this );
383 #endif
384 }
385
386 /*****************************************************************************
387  * module_IsCapable: checks whether a module implements a capability.
388  *****************************************************************************/
389 vlc_bool_t module_IsCapable( const module_t *m, const char *cap )
390 {
391     return !strcmp( m->psz_capability, cap );
392 }
393
394 /*****************************************************************************
395  * module_Need: return the best module function, given a capability list.
396  *****************************************************************************
397  * This function returns the module that best fits the asked capabilities.
398  *****************************************************************************/
399 module_t * __module_Need( vlc_object_t *p_this, const char *psz_capability,
400                           const char *psz_name, vlc_bool_t b_strict )
401 {
402     typedef struct module_list_t module_list_t;
403
404     struct module_list_t
405     {
406         module_t *p_module;
407         int i_score;
408         vlc_bool_t b_force;
409         module_list_t *p_next;
410     };
411
412     module_list_t *p_list, *p_first, *p_tmp;
413     vlc_list_t *p_all;
414
415     int i_which_module, i_index = 0;
416     vlc_bool_t b_intf = VLC_FALSE;
417
418     module_t *p_module;
419
420     int   i_shortcuts = 0;
421     char *psz_shortcuts = NULL, *psz_var = NULL, *psz_alias = NULL;
422     vlc_bool_t b_force_backup = p_this->b_force;
423
424
425     /* Deal with variables */
426     if( psz_name && psz_name[0] == '$' )
427     {
428         vlc_value_t val;
429         var_Create( p_this, psz_name + 1, VLC_VAR_MODULE | VLC_VAR_DOINHERIT );
430         var_Get( p_this, psz_name + 1, &val );
431         psz_var = val.psz_string;
432         psz_name = psz_var;
433     }
434
435     /* Count how many different shortcuts were asked for */
436     if( psz_name && *psz_name )
437     {
438         char *psz_parser, *psz_last_shortcut;
439
440         /* If the user wants none, give him none. */
441         if( !strcmp( psz_name, "none" ) )
442         {
443             free( psz_var );
444             return NULL;
445         }
446
447         i_shortcuts++;
448         psz_shortcuts = psz_last_shortcut = strdup( psz_name );
449
450         for( psz_parser = psz_shortcuts; *psz_parser; psz_parser++ )
451         {
452             if( *psz_parser == ',' )
453             {
454                  *psz_parser = '\0';
455                  i_shortcuts++;
456                  psz_last_shortcut = psz_parser + 1;
457             }
458         }
459
460         /* Check if the user wants to override the "strict" mode */
461         if( psz_last_shortcut )
462         {
463             if( !strcmp(psz_last_shortcut, "none") )
464             {
465                 b_strict = VLC_TRUE;
466                 i_shortcuts--;
467             }
468             else if( !strcmp(psz_last_shortcut, "any") )
469             {
470                 b_strict = VLC_FALSE;
471                 i_shortcuts--;
472             }
473         }
474     }
475
476     /* Sort the modules and test them */
477     p_all = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
478     p_list = malloc( p_all->i_count * sizeof( module_list_t ) );
479     p_first = NULL;
480     unsigned i_cpu = vlc_CPU();
481
482     /* Parse the module list for capabilities and probe each of them */
483     for( i_which_module = 0; i_which_module < p_all->i_count; i_which_module++ )
484     {
485         int i_shortcut_bonus = 0;
486
487         p_module = (module_t *)p_all->p_values[i_which_module].p_object;
488
489         /* Test that this module can do what we need */
490         if( !module_IsCapable( p_module, psz_capability ) )
491         {
492             /* Don't recurse through the sub-modules because vlc_list_find()
493              * will list them anyway. */
494             continue;
495         }
496
497         /* Test if we have the required CPU */
498         if( (p_module->i_cpu & i_cpu) != p_module->i_cpu )
499         {
500             continue;
501         }
502
503         /* If we required a shortcut, check this plugin provides it. */
504         if( i_shortcuts > 0 )
505         {
506             vlc_bool_t b_trash;
507             const char *psz_name = psz_shortcuts;
508
509             /* Let's drop modules with a <= 0 score (unless they are
510              * explicitly requested) */
511             b_trash = p_module->i_score <= 0;
512
513             for( unsigned i_short = i_shortcuts; i_short > 0; i_short-- )
514             {
515                 for( unsigned i = 0; p_module->pp_shortcuts[i]; i++ )
516                 {
517                     char *c;
518                     if( ( c = strchr( psz_name, '@' ) )
519                         ? !strncasecmp( psz_name, p_module->pp_shortcuts[i],
520                                         c-psz_name )
521                         : !strcasecmp( psz_name, p_module->pp_shortcuts[i] ) )
522                     {
523                         /* Found it */
524                         if( c && c[1] )
525                             psz_alias = c+1;
526                         i_shortcut_bonus = i_short * 10000;
527                         goto found_shortcut;
528                     }
529                 }
530
531                 /* Go to the next shortcut... This is so lame! */
532                 psz_name += strlen( psz_name ) + 1;
533             }
534
535             /* If we are in "strict" mode and we couldn't
536              * find the module in the list of provided shortcuts,
537              * then kick the bastard out of here!!! */
538             if( b_strict )
539                 continue;
540         }
541         /* If we didn't require a shortcut, trash <= 0 scored plugins */
542         else if( p_module->i_score <= 0 )
543         {
544             continue;
545         }
546
547 found_shortcut:
548
549         /* Special case: test if we requested a particular intf plugin */
550         if( !i_shortcuts && p_module->psz_program
551              && !strcmp( psz_capability, "interface" )
552              && !strcmp( p_module->psz_program,
553                          p_this->p_libvlc->psz_object_name ) )
554         {
555             if( !b_intf )
556             {
557                 /* Remove previous non-matching plugins */
558                 i_index = 0;
559                 b_intf = VLC_TRUE;
560             }
561         }
562         else if( b_intf )
563         {
564             /* This one doesn't match */
565             continue;
566         }
567
568         /* Store this new module */
569         p_list[ i_index ].p_module = p_module;
570         p_list[ i_index ].i_score = p_module->i_score + i_shortcut_bonus;
571         p_list[ i_index ].b_force = i_shortcut_bonus && b_strict;
572
573         /* Add it to the modules-to-probe list */
574         if( i_index == 0 )
575         {
576             p_list[ 0 ].p_next = NULL;
577             p_first = p_list;
578         }
579         else
580         {
581             /* Ok, so at school you learned that quicksort is quick, and
582              * bubble sort sucks raw eggs. But that's when dealing with
583              * thousands of items. Here we have barely 50. */
584             module_list_t *p_newlist = p_first;
585
586             if( p_first->i_score < p_list[ i_index ].i_score )
587             {
588                 p_list[ i_index ].p_next = p_first;
589                 p_first = &p_list[ i_index ];
590             }
591             else
592             {
593                 while( p_newlist->p_next != NULL &&
594                     p_newlist->p_next->i_score >= p_list[ i_index ].i_score )
595                 {
596                     p_newlist = p_newlist->p_next;
597                 }
598
599                 p_list[ i_index ].p_next = p_newlist->p_next;
600                 p_newlist->p_next = &p_list[ i_index ];
601             }
602         }
603
604         i_index++;
605     }
606
607     msg_Dbg( p_this, "looking for %s module: %i candidate%s", psz_capability,
608                                             i_index, i_index == 1 ? "" : "s" );
609
610     /* Lock all candidate modules */
611     p_tmp = p_first;
612     while( p_tmp != NULL )
613     {
614         vlc_object_yield( p_tmp->p_module );
615         p_tmp = p_tmp->p_next;
616     }
617
618     /* We can release the list, interesting modules were yielded */
619     vlc_list_release( p_all );
620
621     /* Parse the linked list and use the first successful module */
622     p_tmp = p_first;
623     while( p_tmp != NULL )
624     {
625 #ifdef HAVE_DYNAMIC_PLUGINS
626         /* Make sure the module is loaded in mem */
627         module_t *p_module = p_tmp->p_module;
628         if( p_module->b_submodule )
629             p_module = (module_t *)p_module->p_parent;
630
631         if( !p_module->b_builtin && !p_module->b_loaded )
632         {
633             module_t *p_new_module =
634                 AllocatePlugin( p_this, p_module->psz_filename );
635             if( p_new_module )
636             {
637                 CacheMerge( p_this, p_module, p_new_module );
638                 vlc_object_attach( p_new_module, p_module );
639                 DeleteModule( p_new_module, VLC_TRUE );
640             }
641         }
642 #endif
643
644         p_this->b_force = p_tmp->b_force;
645         if( p_tmp->p_module->pf_activate
646              && p_tmp->p_module->pf_activate( p_this ) == VLC_SUCCESS )
647         {
648             break;
649         }
650
651         vlc_object_release( p_tmp->p_module );
652         p_tmp = p_tmp->p_next;
653     }
654
655     /* Store the locked module value */
656     if( p_tmp != NULL )
657     {
658         p_module = p_tmp->p_module;
659         p_tmp = p_tmp->p_next;
660     }
661     else
662     {
663         p_module = NULL;
664     }
665
666     /* Unlock the remaining modules */
667     while( p_tmp != NULL )
668     {
669         vlc_object_release( p_tmp->p_module );
670         p_tmp = p_tmp->p_next;
671     }
672
673     free( p_list );
674     p_this->b_force = b_force_backup;
675
676     if( p_module != NULL )
677     {
678         msg_Dbg( p_this, "using %s module \"%s\"",
679                  psz_capability, p_module->psz_object_name );
680     }
681     else if( p_first == NULL )
682     {
683         if( !strcmp( psz_capability, "access_demux" ) )
684         {
685             msg_Warn( p_this, "no %s module matched \"%s\"",
686                  psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
687         }
688         else
689         {
690             msg_Err( p_this, "no %s module matched \"%s\"",
691                  psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
692
693             msg_StackSet( VLC_EGENERIC, "no %s module matched \"%s\"",
694                  psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
695         }
696     }
697     else if( psz_name != NULL && *psz_name )
698     {
699         msg_Warn( p_this, "no %s module matching \"%s\" could be loaded",
700                   psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
701     }
702     else
703         msg_StackSet( VLC_EGENERIC, "no suitable %s module", psz_capability );
704
705     if( p_module && !p_this->psz_object_name )
706     {
707         /* This assumes that p_this is the object which will be using the
708          * module. That's not always the case ... but it is in most cases.
709          */
710         if( psz_alias )
711             p_this->psz_object_name = strdup( psz_alias );
712         else
713             p_this->psz_object_name = strdup( p_module->psz_object_name );
714     }
715
716     free( psz_shortcuts );
717     free( psz_var );
718
719     /* Don't forget that the module is still locked */
720     return p_module;
721 }
722
723 /*****************************************************************************
724  * module_Unneed: decrease the usage count of a module.
725  *****************************************************************************
726  * This function must be called by the thread that called module_Need, to
727  * decrease the reference count and allow for hiding of modules.
728  *****************************************************************************/
729 void __module_Unneed( vlc_object_t * p_this, module_t * p_module )
730 {
731     /* Use the close method */
732     if( p_module->pf_deactivate )
733     {
734         p_module->pf_deactivate( p_this );
735     }
736
737     msg_Dbg( p_this, "removing module \"%s\"", p_module->psz_object_name );
738
739     vlc_object_release( p_module );
740
741     return;
742 }
743
744 /*****************************************************************************
745  * module_Exists: tell if a module exists.
746  *****************************************************************************
747  * This function is a boolean function that tells if a module exist or not.
748  *****************************************************************************/
749
750 vlc_bool_t __module_Exists(  vlc_object_t *p_this, const char * psz_name )
751 {
752     vlc_list_t *p_list;
753     int i;
754     p_list = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
755     for( i = 0 ; i < p_list->i_count; i++)
756     {
757         const char *psz_module_name =
758             ((module_t *) p_list->p_values[i].p_object)->psz_shortname;
759         if( psz_module_name && !strcmp( psz_module_name, psz_name ) )
760         {
761             /* We can release the list, and return yes */
762             vlc_list_release( p_list ); return VLC_TRUE;
763         }
764     }
765     vlc_list_release( p_list ); return VLC_FALSE;
766 }
767
768
769 /*****************************************************************************
770  * Following functions are local.
771  *****************************************************************************/
772
773 /*****************************************************************************
774  * AllocateAllPlugins: load all plugin modules we can find.
775  *****************************************************************************/
776 #ifdef HAVE_DYNAMIC_PLUGINS
777 static void AllocateAllPlugins( vlc_object_t *p_this )
778 {
779     /* Yes, there are two NULLs because we replace one with "plugin-path". */
780 #if defined( WIN32 ) || defined( UNDER_CE )
781     const char *path[] = { "modules", "", "plugins", NULL, NULL };
782 #else
783     const char *path[] = { "modules", PLUGIN_PATH, "plugins", NULL, NULL };
784 #endif
785
786     const char *const *ppsz_path;
787
788     /* If the user provided a plugin path, we add it to the list */
789     char *userpath = config_GetPsz( p_this, "plugin-path" );
790     path[sizeof(path)/sizeof(path[0]) - 2] = userpath;
791
792     for (ppsz_path = path; *ppsz_path != NULL; ppsz_path++)
793     {
794         char *psz_fullpath;
795
796         if (!**ppsz_path) continue;
797
798 #if defined( SYS_BEOS ) || defined( __APPLE__ ) || defined( WIN32 )
799
800         /* Handle relative as well as absolute paths */
801 #ifdef WIN32
802         if( (*ppsz_path)[0] != '\\' && (*ppsz_path)[0] != '/' &&
803             (*ppsz_path)[1] != ':' )
804 #else
805         if( (*ppsz_path)[0] != '/' )
806 #endif
807         {
808             if( 0>= asprintf( &psz_fullpath, "%s"DIR_SEP"%s",
809                               vlc_global( p_this )->psz_vlcpath, *ppsz_path) )
810                 psz_fullpath = NULL;
811         }
812         else
813 #endif
814             psz_fullpath = strdup( *ppsz_path );
815
816         if( psz_fullpath == NULL )
817             continue;
818
819         msg_Dbg( p_this, "recursively browsing `%s'", psz_fullpath );
820
821         /* Don't go deeper than 5 subdirectories */
822         AllocatePluginDir( p_this, psz_fullpath, 5 );
823
824         free( psz_fullpath );
825     }
826
827     /* Free plugin-path */
828     free( userpath );
829 }
830
831 /*****************************************************************************
832  * AllocatePluginDir: recursively parse a directory to look for plugins
833  *****************************************************************************/
834 static void AllocatePluginDir( vlc_object_t *p_this, const char *psz_dir,
835                                int i_maxdepth )
836 {
837 /* FIXME: Needs to be ported to wide char on ALL Windows builds */
838 #ifdef WIN32
839 # undef opendir
840 # undef closedir
841 # undef readdir
842 #endif
843 #if defined( UNDER_CE ) || defined( _MSC_VER )
844 #ifdef UNDER_CE
845     wchar_t psz_wpath[MAX_PATH + 256];
846     wchar_t psz_wdir[MAX_PATH];
847 #endif
848     char psz_path[MAX_PATH + 256];
849     WIN32_FIND_DATA finddata;
850     HANDLE handle;
851     int rc;
852 #else
853     int    i_dirlen;
854     DIR *  dir;
855     struct dirent * file;
856 #endif
857     char * psz_file;
858
859     if( p_this->p_libvlc->b_die || i_maxdepth < 0 )
860     {
861         return;
862     }
863
864 #if defined( UNDER_CE ) || defined( _MSC_VER )
865 #ifdef UNDER_CE
866     MultiByteToWideChar( CP_ACP, 0, psz_dir, -1, psz_wdir, MAX_PATH );
867
868     rc = GetFileAttributes( psz_wdir );
869     if( rc<0 || !(rc&FILE_ATTRIBUTE_DIRECTORY) ) return; /* Not a directory */
870
871     /* Parse all files in the directory */
872     swprintf( psz_wpath, L"%ls\\*", psz_wdir );
873 #else
874     rc = GetFileAttributes( psz_dir );
875     if( rc<0 || !(rc&FILE_ATTRIBUTE_DIRECTORY) ) return; /* Not a directory */
876 #endif
877
878     /* Parse all files in the directory */
879     sprintf( psz_path, "%s\\*", psz_dir );
880
881 #ifdef UNDER_CE
882     handle = FindFirstFile( psz_wpath, &finddata );
883 #else
884     handle = FindFirstFile( psz_path, &finddata );
885 #endif
886     if( handle == INVALID_HANDLE_VALUE )
887     {
888         /* Empty directory */
889         return;
890     }
891
892     /* Parse the directory and try to load all files it contains. */
893     do
894     {
895 #ifdef UNDER_CE
896         unsigned int i_len = wcslen( finddata.cFileName );
897         swprintf( psz_wpath, L"%ls\\%ls", psz_wdir, finddata.cFileName );
898         sprintf( psz_path, "%s\\%ls", psz_dir, finddata.cFileName );
899 #else
900         unsigned int i_len = strlen( finddata.cFileName );
901         sprintf( psz_path, "%s\\%s", psz_dir, finddata.cFileName );
902 #endif
903
904         /* Skip ".", ".." */
905         if( !*finddata.cFileName || !strcmp( finddata.cFileName, "." )
906          || !strcmp( finddata.cFileName, ".." ) )
907         {
908             if( !FindNextFile( handle, &finddata ) ) break;
909             continue;
910         }
911
912 #ifdef UNDER_CE
913         if( GetFileAttributes( psz_wpath ) & FILE_ATTRIBUTE_DIRECTORY )
914 #else
915         if( GetFileAttributes( psz_path ) & FILE_ATTRIBUTE_DIRECTORY )
916 #endif
917         {
918             AllocatePluginDir( p_this, psz_path, i_maxdepth - 1 );
919         }
920         else if( i_len > strlen( LIBEXT )
921                   /* We only load files ending with LIBEXT */
922                   && !strncasecmp( psz_path + strlen( psz_path)
923                                    - strlen( LIBEXT ),
924                                    LIBEXT, strlen( LIBEXT ) ) )
925         {
926             WIN32_FILE_ATTRIBUTE_DATA attrbuf;
927             int64_t i_time = 0, i_size = 0;
928
929 #ifdef UNDER_CE
930             if( GetFileAttributesEx( psz_wpath, GetFileExInfoStandard,
931                                      &attrbuf ) )
932 #else
933             if( GetFileAttributesEx( psz_path, GetFileExInfoStandard,
934                                      &attrbuf ) )
935 #endif
936             {
937                 i_time = attrbuf.ftLastWriteTime.dwHighDateTime;
938                 i_time <<= 32;
939                 i_time |= attrbuf.ftLastWriteTime.dwLowDateTime;
940                 i_size = attrbuf.nFileSizeHigh;
941                 i_size <<= 32;
942                 i_size |= attrbuf.nFileSizeLow;
943             }
944             psz_file = psz_path;
945
946             AllocatePluginFile( p_this, psz_file, i_time, i_size );
947         }
948     }
949     while( !p_this->p_libvlc->b_die && FindNextFile( handle, &finddata ) );
950
951     /* Close the directory */
952     FindClose( handle );
953
954 #else
955     dir = opendir( psz_dir );
956     if( !dir )
957     {
958         return;
959     }
960
961     i_dirlen = strlen( psz_dir );
962
963     /* Parse the directory and try to load all files it contains. */
964     while( !p_this->p_libvlc->b_die && (file = readdir( dir )) )
965     {
966         struct stat statbuf;
967         unsigned int i_len;
968         int i_stat;
969
970         /* Skip ".", ".." */
971         if( !*file->d_name || !strcmp( file->d_name, "." )
972          || !strcmp( file->d_name, ".." ) )
973         {
974             continue;
975         }
976
977         i_len = strlen( file->d_name );
978         psz_file = malloc( i_dirlen + 1 + i_len + 1 );
979 #ifdef WIN32
980         sprintf( psz_file, "%s\\%s", psz_dir, file->d_name );
981 #else
982         sprintf( psz_file, "%s/%s", psz_dir, file->d_name );
983 #endif
984
985         i_stat = stat( psz_file, &statbuf );
986         if( !i_stat && statbuf.st_mode & S_IFDIR )
987         {
988             AllocatePluginDir( p_this, psz_file, i_maxdepth - 1 );
989         }
990         else if( i_len > strlen( LIBEXT )
991                   /* We only load files ending with LIBEXT */
992                   && !strncasecmp( file->d_name + i_len - strlen( LIBEXT ),
993                                    LIBEXT, strlen( LIBEXT ) ) )
994         {
995             int64_t i_time = 0, i_size = 0;
996
997             if( !i_stat )
998             {
999                 i_time = statbuf.st_mtime;
1000                 i_size = statbuf.st_size;
1001             }
1002
1003             AllocatePluginFile( p_this, psz_file, i_time, i_size );
1004         }
1005
1006         free( psz_file );
1007     }
1008
1009     /* Close the directory */
1010     closedir( dir );
1011
1012 #endif
1013 }
1014
1015 /*****************************************************************************
1016  * AllocatePluginFile: load a module into memory and initialize it.
1017  *****************************************************************************
1018  * This function loads a dynamically loadable module and allocates a structure
1019  * for its information data. The module can then be handled by module_Need
1020  * and module_Unneed. It can be removed by DeleteModule.
1021  *****************************************************************************/
1022 static int AllocatePluginFile( vlc_object_t * p_this, char * psz_file,
1023                                int64_t i_file_time, int64_t i_file_size )
1024 {
1025     module_t * p_module = NULL;
1026     module_cache_t *p_cache_entry = NULL;
1027
1028     /*
1029      * Check our plugins cache first then load plugin if needed
1030      */
1031     p_cache_entry =
1032         CacheFind( p_this, psz_file, i_file_time, i_file_size );
1033
1034     if( !p_cache_entry )
1035     {
1036         p_module = AllocatePlugin( p_this, psz_file );
1037     }
1038     else
1039     {
1040         /* If junk dll, don't try to load it */
1041         if( p_cache_entry->b_junk )
1042         {
1043             p_module = NULL;
1044         }
1045         else
1046         {
1047             module_config_t *p_item = NULL, *p_end = NULL;
1048
1049             p_module = p_cache_entry->p_module;
1050             p_module->b_loaded = VLC_FALSE;
1051
1052             /* For now we force loading if the module's config contains
1053              * callbacks or actions.
1054              * Could be optimized by adding an API call.*/
1055             for( p_item = p_module->p_config, p_end = p_item + p_module->confsize;
1056                  p_item < p_end; p_item++ )
1057             {
1058                 if( p_item->pf_callback || p_item->i_action )
1059                 {
1060                     p_module = AllocatePlugin( p_this, psz_file );
1061                     break;
1062                 }
1063             }
1064             if( p_module == p_cache_entry->p_module )
1065                 p_cache_entry->b_used = VLC_TRUE;
1066         }
1067     }
1068
1069     if( p_module )
1070     {
1071         libvlc_global_data_t *p_libvlc_global = vlc_global( p_this );
1072
1073         /* Everything worked fine !
1074          * The module is ready to be added to the list. */
1075         p_module->b_builtin = VLC_FALSE;
1076
1077         /* msg_Dbg( p_this, "plugin \"%s\", %s",
1078                     p_module->psz_object_name, p_module->psz_longname ); */
1079
1080         vlc_object_attach( p_module, p_libvlc_global->p_module_bank );
1081
1082         if( !p_libvlc_global->p_module_bank->b_cache )
1083             return 0;
1084
1085 #define p_bank p_libvlc_global->p_module_bank
1086         /* Add entry to cache */
1087         p_bank->pp_cache =
1088             realloc( p_bank->pp_cache, (p_bank->i_cache + 1) * sizeof(void *) );
1089         p_bank->pp_cache[p_bank->i_cache] = malloc( sizeof(module_cache_t) );
1090         if( !p_bank->pp_cache[p_bank->i_cache] )
1091             return -1;
1092         p_bank->pp_cache[p_bank->i_cache]->psz_file = strdup( psz_file );
1093         p_bank->pp_cache[p_bank->i_cache]->i_time = i_file_time;
1094         p_bank->pp_cache[p_bank->i_cache]->i_size = i_file_size;
1095         p_bank->pp_cache[p_bank->i_cache]->b_junk = p_module ? 0 : 1;
1096         p_bank->pp_cache[p_bank->i_cache]->b_used = VLC_TRUE;
1097         p_bank->pp_cache[p_bank->i_cache]->p_module = p_module;
1098         p_bank->i_cache++;
1099     }
1100
1101     return p_module ? 0 : -1;
1102 }
1103
1104 /*****************************************************************************
1105  * AllocatePlugin: load a module into memory and initialize it.
1106  *****************************************************************************
1107  * This function loads a dynamically loadable module and allocates a structure
1108  * for its information data. The module can then be handled by module_Need
1109  * and module_Unneed. It can be removed by DeleteModule.
1110  *****************************************************************************/
1111 static module_t * AllocatePlugin( vlc_object_t * p_this, char * psz_file )
1112 {
1113     module_t * p_module = NULL;
1114     module_handle_t handle;
1115
1116     if( LoadModule( p_this, psz_file, &handle ) )
1117         return NULL;
1118
1119     /* Now that we have successfully loaded the module, we can
1120      * allocate a structure for it */
1121     p_module = vlc_module_create( p_this );
1122     if( p_module == NULL )
1123     {
1124         msg_Err( p_this, "out of memory" );
1125         CloseModule( handle );
1126         return NULL;
1127     }
1128
1129     /* We need to fill these since they may be needed by CallEntry() */
1130     p_module->psz_filename = psz_file;
1131     p_module->handle = handle;
1132     p_module->b_loaded = VLC_TRUE;
1133
1134     /* Initialize the module: fill p_module, default config */
1135     if( CallEntry( p_module ) != 0 )
1136     {
1137         /* We couldn't call module_init() */
1138         vlc_object_destroy( p_module );
1139         CloseModule( handle );
1140         return NULL;
1141     }
1142
1143     DupModule( p_module );
1144     p_module->psz_filename = strdup( p_module->psz_filename );
1145
1146     /* Everything worked fine ! The module is ready to be added to the list. */
1147     p_module->b_builtin = VLC_FALSE;
1148
1149     return p_module;
1150 }
1151
1152 /*****************************************************************************
1153  * DupModule: make a plugin module standalone.
1154  *****************************************************************************
1155  * This function duplicates all strings in the module, so that the dynamic
1156  * object can be unloaded. It acts recursively on submodules.
1157  *****************************************************************************/
1158 static void DupModule( module_t *p_module )
1159 {
1160     const char **pp_shortcut;
1161     int i_submodule;
1162
1163     for( pp_shortcut = p_module->pp_shortcuts ; *pp_shortcut ; pp_shortcut++ )
1164     {
1165         *pp_shortcut = strdup( *pp_shortcut );
1166     }
1167
1168     /* We strdup() these entries so that they are still valid when the
1169      * module is unloaded. */
1170     p_module->psz_object_name = strdup( p_module->psz_object_name );
1171     p_module->psz_capability = strdup( p_module->psz_capability );
1172     p_module->psz_shortname = p_module->psz_shortname ?
1173                                  strdup( p_module->psz_shortname ) : NULL;
1174     p_module->psz_longname = strdup( p_module->psz_longname );
1175     p_module->psz_help = p_module->psz_help ? strdup( p_module->psz_help )
1176                                             : NULL;
1177
1178     if( p_module->psz_program != NULL )
1179     {
1180         p_module->psz_program = strdup( p_module->psz_program );
1181     }
1182
1183     for( i_submodule = 0; i_submodule < p_module->i_children; i_submodule++ )
1184     {
1185         DupModule( (module_t*)p_module->pp_children[ i_submodule ] );
1186     }
1187 }
1188
1189 /*****************************************************************************
1190  * UndupModule: free a duplicated module.
1191  *****************************************************************************
1192  * This function frees the allocations done in DupModule().
1193  *****************************************************************************/
1194 static void UndupModule( module_t *p_module )
1195 {
1196     const char **pp_shortcut;
1197     int i_submodule;
1198
1199     for( i_submodule = 0; i_submodule < p_module->i_children; i_submodule++ )
1200     {
1201         UndupModule( (module_t*)p_module->pp_children[ i_submodule ] );
1202     }
1203
1204     for( pp_shortcut = p_module->pp_shortcuts ; *pp_shortcut ; pp_shortcut++ )
1205     {
1206         free( (void*)*pp_shortcut );
1207     }
1208
1209     free( (void*)p_module->psz_object_name );
1210     free( p_module->psz_capability );
1211     free( (void*)p_module->psz_shortname );
1212     free( (void*)p_module->psz_longname );
1213     free( (void*)p_module->psz_help );
1214     free( (void*)p_module->psz_program );
1215 }
1216
1217 #endif /* HAVE_DYNAMIC_PLUGINS */
1218
1219 /*****************************************************************************
1220  * AllocateBuiltinModule: initialize a builtin module.
1221  *****************************************************************************
1222  * This function registers a builtin module and allocates a structure
1223  * for its information data. The module can then be handled by module_Need
1224  * and module_Unneed. It can be removed by DeleteModule.
1225  *****************************************************************************/
1226 static int AllocateBuiltinModule( vlc_object_t * p_this,
1227                                   int ( *pf_entry ) ( module_t * ) )
1228 {
1229     module_t * p_module;
1230
1231     /* Now that we have successfully loaded the module, we can
1232      * allocate a structure for it */
1233     p_module = vlc_module_create( p_this );
1234     if( p_module == NULL )
1235     {
1236         msg_Err( p_this, "out of memory" );
1237         return -1;
1238     }
1239
1240     /* Initialize the module : fill p_module->psz_object_name, etc. */
1241     if( pf_entry( p_module ) != 0 )
1242     {
1243         /* With a well-written module we shouldn't have to print an
1244          * additional error message here, but just make sure. */
1245         msg_Err( p_this, "failed calling entry point in builtin module" );
1246         vlc_object_destroy( p_module );
1247         return -1;
1248     }
1249
1250     /* Everything worked fine ! The module is ready to be added to the list. */
1251     p_module->b_builtin = VLC_TRUE;
1252
1253     /* msg_Dbg( p_this, "builtin \"%s\", %s",
1254                 p_module->psz_object_name, p_module->psz_longname ); */
1255
1256     vlc_object_attach( p_module, vlc_global( p_this )->p_module_bank );
1257
1258     return 0;
1259 }
1260
1261 /*****************************************************************************
1262  * DeleteModule: delete a module and its structure.
1263  *****************************************************************************
1264  * This function can only be called if the module isn't being used.
1265  *****************************************************************************/
1266 static int DeleteModule( module_t * p_module, vlc_bool_t b_detach )
1267 {
1268     if( !p_module ) return VLC_EGENERIC;
1269     if( b_detach )
1270         vlc_object_detach( p_module );
1271
1272     /* We free the structures that we strdup()ed in Allocate*Module(). */
1273 #ifdef HAVE_DYNAMIC_PLUGINS
1274     if( !p_module->b_builtin )
1275     {
1276         if( p_module->b_loaded && p_module->b_unloadable )
1277         {
1278             CloseModule( p_module->handle );
1279         }
1280         UndupModule( p_module );
1281         free( p_module->psz_filename );
1282     }
1283 #endif
1284
1285     /* Free and detach the object's children */
1286     while( p_module->i_children )
1287     {
1288         vlc_object_t *p_this = p_module->pp_children[0];
1289         vlc_object_detach( p_this );
1290         vlc_object_destroy( p_this );
1291     }
1292
1293     config_Free( p_module );
1294     vlc_object_destroy( p_module );
1295     p_module = NULL;
1296     return 0;
1297 }
1298
1299 #ifdef HAVE_DYNAMIC_PLUGINS
1300 /*****************************************************************************
1301  * CallEntry: call an entry point.
1302  *****************************************************************************
1303  * This function calls a symbol given its name and a module structure. The
1304  * symbol MUST refer to a function returning int and taking a module_t* as
1305  * an argument.
1306  *****************************************************************************/
1307 static int CallEntry( module_t * p_module )
1308 {
1309     static const char psz_name[] = "vlc_entry" MODULE_SUFFIX;
1310     int (* pf_symbol) ( module_t * p_module );
1311
1312     /* Try to resolve the symbol */
1313     pf_symbol = (int (*)(module_t *)) GetSymbol( p_module->handle, psz_name );
1314
1315     if( pf_symbol == NULL )
1316     {
1317 #if defined(HAVE_DL_DYLD) || defined(HAVE_DL_BEOS)
1318         msg_Warn( p_module, "cannot find symbol \"%s\" in file `%s'",
1319                             psz_name, p_module->psz_filename );
1320 #elif defined(HAVE_DL_WINDOWS)
1321         char *psz_error = GetWindowsError();
1322         msg_Warn( p_module, "cannot find symbol \"%s\" in file `%s' (%s)",
1323                             psz_name, p_module->psz_filename, psz_error );
1324         free( psz_error );
1325 #elif defined(HAVE_DL_DLOPEN)
1326         msg_Warn( p_module, "cannot find symbol \"%s\" in file `%s' (%s)",
1327                             psz_name, p_module->psz_filename, dlerror() );
1328 #elif defined(HAVE_DL_SHL_LOAD)
1329         msg_Warn( p_module, "cannot find symbol \"%s\" in file `%s' (%s)",
1330                             psz_name, p_module->psz_filename, strerror(errno) );
1331 #else
1332 #   error "Something is wrong in modules.c"
1333 #endif
1334         return -1;
1335     }
1336
1337     /* We can now try to call the symbol */
1338     if( pf_symbol( p_module ) != 0 )
1339     {
1340         /* With a well-written module we shouldn't have to print an
1341          * additional error message here, but just make sure. */
1342         msg_Err( p_module, "Failed to call symbol \"%s\" in file `%s'",
1343                            psz_name, p_module->psz_filename );
1344         return -1;
1345     }
1346
1347     /* Everything worked fine, we can return */
1348     return 0;
1349 }
1350
1351 /*****************************************************************************
1352  * LoadModule: loads a dynamic library
1353  *****************************************************************************
1354  * This function loads a dynamically linked library using a system dependant
1355  * method. Will return 0 on success as well as the module handle.
1356  *****************************************************************************/
1357 static int LoadModule( vlc_object_t *p_this, char *psz_file,
1358                        module_handle_t *p_handle )
1359 {
1360     module_handle_t handle;
1361
1362 #if defined(HAVE_DL_DYLD)
1363     NSObjectFileImage image;
1364     NSObjectFileImageReturnCode ret;
1365
1366     ret = NSCreateObjectFileImageFromFile( psz_file, &image );
1367
1368     if( ret != NSObjectFileImageSuccess )
1369     {
1370         msg_Warn( p_this, "cannot create image from `%s'", psz_file );
1371         return -1;
1372     }
1373
1374     /* Open the dynamic module */
1375     handle = NSLinkModule( image, psz_file,
1376                            NSLINKMODULE_OPTION_RETURN_ON_ERROR );
1377
1378     if( !handle )
1379     {
1380         NSLinkEditErrors errors;
1381         const char *psz_file, *psz_err;
1382         int i_errnum;
1383         NSLinkEditError( &errors, &i_errnum, &psz_file, &psz_err );
1384         msg_Warn( p_this, "cannot link module `%s' (%s)", psz_file, psz_err );
1385         NSDestroyObjectFileImage( image );
1386         return -1;
1387     }
1388
1389     /* Destroy our image, we won't need it */
1390     NSDestroyObjectFileImage( image );
1391
1392 #elif defined(HAVE_DL_BEOS)
1393     handle = load_add_on( psz_file );
1394     if( handle < 0 )
1395     {
1396         msg_Warn( p_this, "cannot load module `%s'", psz_file );
1397         return -1;
1398     }
1399
1400 #elif defined(HAVE_DL_WINDOWS)
1401 #ifdef UNDER_CE
1402     {
1403         wchar_t psz_wfile[MAX_PATH];
1404         MultiByteToWideChar( CP_ACP, 0, psz_file, -1, psz_wfile, MAX_PATH );
1405         handle = LoadLibrary( psz_wfile );
1406     }
1407 #else
1408     handle = LoadLibrary( psz_file );
1409 #endif
1410     if( handle == NULL )
1411     {
1412         char *psz_err = GetWindowsError();
1413         msg_Warn( p_this, "cannot load module `%s' (%s)", psz_file, psz_err );
1414         free( psz_err );
1415         return -1;
1416     }
1417
1418 #elif defined(HAVE_DL_DLOPEN) && defined(RTLD_NOW)
1419     /* static is OK, we are called atomically */
1420
1421 #   if defined(SYS_LINUX)
1422     /* XXX HACK #1 - we should NOT open modules with RTLD_GLOBAL, or we
1423      * are going to get namespace collisions when two modules have common
1424      * public symbols, but ALSA is being a pest here. */
1425     if( strstr( psz_file, "alsa_plugin" ) )
1426     {
1427         handle = dlopen( psz_file, RTLD_NOW | RTLD_GLOBAL );
1428         if( handle == NULL )
1429         {
1430             msg_Warn( p_this, "cannot load module `%s' (%s)",
1431                               psz_file, dlerror() );
1432             return -1;
1433         }
1434     }
1435 #   endif
1436
1437     handle = dlopen( psz_file, RTLD_NOW );
1438     if( handle == NULL )
1439     {
1440         msg_Warn( p_this, "cannot load module `%s' (%s)",
1441                           psz_file, dlerror() );
1442         return -1;
1443     }
1444
1445 #elif defined(HAVE_DL_DLOPEN)
1446 #   if defined(DL_LAZY)
1447     handle = dlopen( psz_file, DL_LAZY );
1448 #   else
1449     handle = dlopen( psz_file, 0 );
1450 #   endif
1451     if( handle == NULL )
1452     {
1453         msg_Warn( p_this, "cannot load module `%s' (%s)",
1454                           psz_file, dlerror() );
1455         return -1;
1456     }
1457
1458 #elif defined(HAVE_DL_SHL_LOAD)
1459     handle = shl_load( psz_file, BIND_IMMEDIATE | BIND_NONFATAL, NULL );
1460     if( handle == NULL )
1461     {
1462         msg_Warn( p_this, "cannot load module `%s' (%s)",
1463                           psz_file, strerror(errno) );
1464         return -1;
1465     }
1466
1467 #else
1468 #   error "Something is wrong in modules.c"
1469
1470 #endif
1471
1472     *p_handle = handle;
1473     return 0;
1474 }
1475
1476 /*****************************************************************************
1477  * CloseModule: unload a dynamic library
1478  *****************************************************************************
1479  * This function unloads a previously opened dynamically linked library
1480  * using a system dependant method. No return value is taken in consideration,
1481  * since some libraries sometimes refuse to close properly.
1482  *****************************************************************************/
1483 static void CloseModule( module_handle_t handle )
1484 {
1485 #if defined(HAVE_DL_DYLD)
1486     NSUnLinkModule( handle, FALSE );
1487
1488 #elif defined(HAVE_DL_BEOS)
1489     unload_add_on( handle );
1490
1491 #elif defined(HAVE_DL_WINDOWS)
1492     FreeLibrary( handle );
1493
1494 #elif defined(HAVE_DL_DLOPEN)
1495 # ifndef NDEBUG
1496     dlclose( handle );
1497 # endif
1498
1499 #elif defined(HAVE_DL_SHL_LOAD)
1500     shl_unload( handle );
1501
1502 #endif
1503     return;
1504 }
1505
1506 /*****************************************************************************
1507  * GetSymbol: get a symbol from a dynamic library
1508  *****************************************************************************
1509  * This function queries a loaded library for a symbol specified in a
1510  * string, and returns a pointer to it. We don't check for dlerror() or
1511  * similar functions, since we want a non-NULL symbol anyway.
1512  *****************************************************************************/
1513 static void * _module_getsymbol( module_handle_t, const char * );
1514
1515 static void * GetSymbol( module_handle_t handle, const char * psz_function )
1516 {
1517     void * p_symbol = _module_getsymbol( handle, psz_function );
1518
1519     /* MacOS X dl library expects symbols to begin with "_". So do
1520      * some other operating systems. That's really lame, but hey, what
1521      * can we do ? */
1522     if( p_symbol == NULL )
1523     {
1524         char psz_call[strlen( psz_function ) + 2];
1525
1526         psz_call[ 0 ] = '_';
1527         memcpy( psz_call + 1, psz_function, sizeof (psz_call) - 1 );
1528         p_symbol = _module_getsymbol( handle, psz_call );
1529     }
1530
1531     return p_symbol;
1532 }
1533
1534 static void * _module_getsymbol( module_handle_t handle,
1535                                  const char * psz_function )
1536 {
1537 #if defined(HAVE_DL_DYLD)
1538     NSSymbol sym = NSLookupSymbolInModule( handle, psz_function );
1539     return NSAddressOfSymbol( sym );
1540
1541 #elif defined(HAVE_DL_BEOS)
1542     void * p_symbol;
1543     if( B_OK == get_image_symbol( handle, psz_function,
1544                                   B_SYMBOL_TYPE_TEXT, &p_symbol ) )
1545     {
1546         return p_symbol;
1547     }
1548     else
1549     {
1550         return NULL;
1551     }
1552
1553 #elif defined(HAVE_DL_WINDOWS) && defined(UNDER_CE)
1554     wchar_t psz_real[256];
1555     MultiByteToWideChar( CP_ACP, 0, psz_function, -1, psz_real, 256 );
1556
1557     return (void *)GetProcAddress( handle, psz_real );
1558
1559 #elif defined(HAVE_DL_WINDOWS) && defined(WIN32)
1560     return (void *)GetProcAddress( handle, (char *)psz_function );
1561
1562 #elif defined(HAVE_DL_DLOPEN)
1563     return dlsym( handle, psz_function );
1564
1565 #elif defined(HAVE_DL_SHL_LOAD)
1566     void *p_sym;
1567     shl_findsym( &handle, psz_function, TYPE_UNDEFINED, &p_sym );
1568     return p_sym;
1569
1570 #endif
1571 }
1572
1573 #if defined(HAVE_DL_WINDOWS)
1574 static char * GetWindowsError( void )
1575 {
1576 #if defined(UNDER_CE)
1577     wchar_t psz_tmp[MAX_PATH];
1578     char * psz_buffer = malloc( MAX_PATH );
1579 #else
1580     char * psz_tmp = malloc( MAX_PATH );
1581 #endif
1582     int i = 0, i_error = GetLastError();
1583
1584     FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1585                    NULL, i_error, MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
1586                    (LPTSTR)psz_tmp, MAX_PATH, NULL );
1587
1588     /* Go to the end of the string */
1589     while( psz_tmp[i] && psz_tmp[i] != _T('\r') && psz_tmp[i] != _T('\n') )
1590     {
1591         i++;
1592     }
1593
1594     if( psz_tmp[i] )
1595     {
1596 #if defined(UNDER_CE)
1597         swprintf( psz_tmp + i, L" (error %i)", i_error );
1598         psz_tmp[ 255 ] = L'\0';
1599 #else
1600         snprintf( psz_tmp + i, 256 - i, " (error %i)", i_error );
1601         psz_tmp[ 255 ] = '\0';
1602 #endif
1603     }
1604
1605 #if defined(UNDER_CE)
1606     wcstombs( psz_buffer, psz_tmp, MAX_PATH );
1607     return psz_buffer;
1608 #else
1609     return psz_tmp;
1610 #endif
1611 }
1612 #endif /* HAVE_DL_WINDOWS */
1613
1614 /*****************************************************************************
1615  * LoadPluginsCache: loads the plugins cache file
1616  *****************************************************************************
1617  * This function will load the plugin cache if present and valid. This cache
1618  * will in turn be queried by AllocateAllPlugins() to see if it needs to
1619  * actually load the dynamically loadable module.
1620  * This allows us to only fully load plugins when they are actually used.
1621  *****************************************************************************/
1622 static void CacheLoad( vlc_object_t *p_this )
1623 {
1624     char *psz_filename, *psz_homedir;
1625     FILE *file;
1626     int i, j, i_size, i_read;
1627     char p_cachestring[sizeof(PLUGINSCACHE_DIR COPYRIGHT_MESSAGE)];
1628     char p_cachelang[6], p_lang[6];
1629     int i_cache;
1630     module_cache_t **pp_cache = 0;
1631     int32_t i_file_size, i_marker;
1632     libvlc_global_data_t *p_libvlc_global = vlc_global( p_this );
1633
1634     psz_homedir = p_this->p_libvlc->psz_homedir;
1635     if( !psz_homedir )
1636     {
1637         msg_Err( p_this, "psz_homedir is null" );
1638         return;
1639     }
1640
1641     i_size = asprintf( &psz_filename, "%s/%s/%s/%s", psz_homedir, CONFIG_DIR,
1642                        PLUGINSCACHE_DIR, CacheName() );
1643     if( i_size <= 0 )
1644     {
1645         msg_Err( p_this, "out of memory" );
1646         return;
1647     }
1648
1649     if( p_libvlc_global->p_module_bank->b_cache_delete )
1650     {
1651 #if !defined( UNDER_CE )
1652         unlink( psz_filename );
1653 #else
1654         wchar_t psz_wf[MAX_PATH];
1655         MultiByteToWideChar( CP_ACP, 0, psz_filename, -1, psz_wf, MAX_PATH );
1656         DeleteFile( psz_wf );
1657 #endif
1658         msg_Dbg( p_this, "removing plugins cache file %s", psz_filename );
1659         free( psz_filename );
1660         return;
1661     }
1662
1663     msg_Dbg( p_this, "loading plugins cache file %s", psz_filename );
1664
1665     file = utf8_fopen( psz_filename, "rb" );
1666     if( !file )
1667     {
1668         msg_Warn( p_this, "could not open plugins cache file %s for reading",
1669                   psz_filename );
1670         free( psz_filename );
1671         return;
1672     }
1673     free( psz_filename );
1674
1675     /* Check the file size */
1676     i_read = fread( &i_file_size, 1, sizeof(i_file_size), file );
1677     if( i_read != sizeof(i_file_size) )
1678     {
1679         msg_Warn( p_this, "This doesn't look like a valid plugins cache "
1680                   "(too short)" );
1681         fclose( file );
1682         return;
1683     }
1684
1685     fseek( file, 0, SEEK_END );
1686     if( ftell( file ) != i_file_size )
1687     {
1688         msg_Warn( p_this, "This doesn't look like a valid plugins cache "
1689                   "(corrupted size)" );
1690         fclose( file );
1691         return;
1692     }
1693     fseek( file, sizeof(i_file_size), SEEK_SET );
1694
1695     /* Check the file is a plugins cache */
1696     i_size = sizeof(PLUGINSCACHE_DIR COPYRIGHT_MESSAGE) - 1;
1697     i_read = fread( p_cachestring, 1, i_size, file );
1698     if( i_read != i_size ||
1699         memcmp( p_cachestring, PLUGINSCACHE_DIR COPYRIGHT_MESSAGE, i_size ) )
1700     {
1701         msg_Warn( p_this, "This doesn't look like a valid plugins cache" );
1702         fclose( file );
1703         return;
1704     }
1705
1706     /* Check Sub-version number */
1707     i_read = fread( &i_marker, 1, sizeof(i_marker), file );
1708     if( i_read != sizeof(i_marker) || i_marker != CACHE_SUBVERSION_NUM )
1709     {
1710         msg_Warn( p_this, "This doesn't look like a valid plugins cache "
1711                   "(corrupted header)" );
1712         fclose( file );
1713         return;
1714     }
1715
1716     /* Check the language hasn't changed */
1717     sprintf( p_lang, "%5.5s", _("C") ); i_size = 5;
1718     i_read = fread( p_cachelang, 1, i_size, file );
1719     if( i_read != i_size || memcmp( p_cachelang, p_lang, i_size ) )
1720     {
1721         msg_Warn( p_this, "This doesn't look like a valid plugins cache "
1722                   "(language changed)" );
1723         fclose( file );
1724         return;
1725     }
1726
1727     /* Check header marker */
1728     i_read = fread( &i_marker, 1, sizeof(i_marker), file );
1729     if( i_read != sizeof(i_marker) ||
1730         i_marker != ftell( file ) - (int)sizeof(i_marker) )
1731     {
1732         msg_Warn( p_this, "This doesn't look like a valid plugins cache "
1733                   "(corrupted header)" );
1734         fclose( file );
1735         return;
1736     }
1737
1738     p_libvlc_global->p_module_bank->i_loaded_cache = 0;
1739     if (fread( &i_cache, 1, sizeof(i_cache), file ) != sizeof(i_cache) )
1740     {
1741         msg_Warn( p_this, "This doesn't look like a valid plugins cache "
1742                   "(file too short)" );
1743         fclose( file );
1744         return;
1745     }
1746
1747     if( i_cache )
1748         pp_cache = p_libvlc_global->p_module_bank->pp_loaded_cache =
1749                    malloc( i_cache * sizeof(void *) );
1750
1751 #define LOAD_IMMEDIATE(a) \
1752     if( fread( (void *)&a, sizeof(char), sizeof(a), file ) != sizeof(a) ) goto error
1753 #define LOAD_STRING(a) \
1754 { \
1755     a = NULL; \
1756     if( ( fread( &i_size, sizeof(i_size), 1, file ) != 1 ) \
1757      || ( i_size > 16384 ) ) \
1758         goto error; \
1759     if( i_size ) { \
1760         char *psz = malloc( i_size ); \
1761         if( fread( psz, i_size, 1, file ) != 1 ) { \
1762             free( psz ); \
1763             goto error; \
1764         } \
1765         if( psz[i_size-1] ) { \
1766             free( psz ); \
1767             goto error; \
1768         } \
1769         a = psz; \
1770     } \
1771 }
1772
1773     for( i = 0; i < i_cache; i++ )
1774     {
1775         uint16_t i_size;
1776         int i_submodules;
1777
1778         pp_cache[i] = malloc( sizeof(module_cache_t) );
1779         p_libvlc_global->p_module_bank->i_loaded_cache++;
1780
1781         /* Load common info */
1782         LOAD_STRING( pp_cache[i]->psz_file );
1783         LOAD_IMMEDIATE( pp_cache[i]->i_time );
1784         LOAD_IMMEDIATE( pp_cache[i]->i_size );
1785         LOAD_IMMEDIATE( pp_cache[i]->b_junk );
1786         pp_cache[i]->b_used = VLC_FALSE;
1787
1788         if( pp_cache[i]->b_junk ) continue;
1789
1790         pp_cache[i]->p_module = vlc_module_create( p_this );
1791
1792         /* Load additional infos */
1793         LOAD_STRING( pp_cache[i]->p_module->psz_object_name );
1794         LOAD_STRING( pp_cache[i]->p_module->psz_shortname );
1795         LOAD_STRING( pp_cache[i]->p_module->psz_longname );
1796         LOAD_STRING( pp_cache[i]->p_module->psz_help );
1797         LOAD_STRING( pp_cache[i]->p_module->psz_program );
1798         for( j = 0; j < MODULE_SHORTCUT_MAX; j++ )
1799         {
1800             LOAD_STRING( pp_cache[i]->p_module->pp_shortcuts[j] ); // FIX
1801         }
1802         LOAD_STRING( pp_cache[i]->p_module->psz_capability );
1803         LOAD_IMMEDIATE( pp_cache[i]->p_module->i_score );
1804         LOAD_IMMEDIATE( pp_cache[i]->p_module->i_cpu );
1805         LOAD_IMMEDIATE( pp_cache[i]->p_module->b_unloadable );
1806         LOAD_IMMEDIATE( pp_cache[i]->p_module->b_reentrant );
1807         LOAD_IMMEDIATE( pp_cache[i]->p_module->b_submodule );
1808
1809         /* Config stuff */
1810         if( CacheLoadConfig( pp_cache[i]->p_module, file ) != VLC_SUCCESS )
1811             goto error;
1812
1813         LOAD_STRING( pp_cache[i]->p_module->psz_filename );
1814
1815         LOAD_IMMEDIATE( i_submodules );
1816
1817         while( i_submodules-- )
1818         {
1819             module_t *p_module = vlc_submodule_create( pp_cache[i]->p_module );
1820             LOAD_STRING( p_module->psz_object_name );
1821             LOAD_STRING( p_module->psz_shortname );
1822             LOAD_STRING( p_module->psz_longname );
1823             LOAD_STRING( p_module->psz_help );
1824             LOAD_STRING( p_module->psz_program );
1825             for( j = 0; j < MODULE_SHORTCUT_MAX; j++ )
1826             {
1827                 LOAD_STRING( p_module->pp_shortcuts[j] ); // FIX
1828             }
1829             LOAD_STRING( p_module->psz_capability );
1830             LOAD_IMMEDIATE( p_module->i_score );
1831             LOAD_IMMEDIATE( p_module->i_cpu );
1832             LOAD_IMMEDIATE( p_module->b_unloadable );
1833             LOAD_IMMEDIATE( p_module->b_reentrant );
1834         }
1835     }
1836
1837     fclose( file );
1838     return;
1839
1840  error:
1841
1842     msg_Warn( p_this, "plugins cache not loaded (corrupted)" );
1843
1844     /* TODO: cleanup */
1845     p_libvlc_global->p_module_bank->i_loaded_cache = 0;
1846
1847     fclose( file );
1848     return;
1849 }
1850
1851
1852 int CacheLoadConfig( module_t *p_module, FILE *file )
1853 {
1854     uint32_t i_lines;
1855     uint16_t i_size;
1856
1857     /* Calculate the structure length */
1858     LOAD_IMMEDIATE( p_module->i_config_items );
1859     LOAD_IMMEDIATE( p_module->i_bool_items );
1860
1861     LOAD_IMMEDIATE( i_lines );
1862
1863     /* Allocate memory */
1864     if (i_lines)
1865     {
1866         p_module->p_config =
1867             (module_config_t *)calloc( i_lines, sizeof(module_config_t) );
1868         if( p_module->p_config == NULL )
1869         {
1870             p_module->confsize = 0;
1871             msg_Err( p_module, "config error: can't duplicate p_config" );
1872             return VLC_ENOMEM;
1873         }
1874     }
1875     p_module->confsize = i_lines;
1876
1877     /* Do the duplication job */
1878     for (size_t i = 0; i < i_lines; i++ )
1879     {
1880         LOAD_IMMEDIATE( p_module->p_config[i] );
1881
1882         LOAD_STRING( p_module->p_config[i].psz_type );
1883         LOAD_STRING( p_module->p_config[i].psz_name );
1884         LOAD_STRING( p_module->p_config[i].psz_text );
1885         LOAD_STRING( p_module->p_config[i].psz_longtext );
1886         LOAD_STRING( p_module->p_config[i].psz_current );
1887
1888         if (IsConfigStringType (p_module->p_config[i].i_type))
1889         {
1890             LOAD_STRING (p_module->p_config[i].orig.psz);
1891             p_module->p_config[i].value.psz =
1892                     (p_module->p_config[i].orig.psz != NULL)
1893                         ? strdup (p_module->p_config[i].orig.psz) : NULL;
1894             p_module->p_config[i].saved.psz = NULL;
1895         }
1896         else
1897         {
1898             memcpy (&p_module->p_config[i].value, &p_module->p_config[i].orig,
1899                     sizeof (p_module->p_config[i].value));
1900             memcpy (&p_module->p_config[i].saved, &p_module->p_config[i].orig,
1901                     sizeof (p_module->p_config[i].saved));
1902         }
1903
1904         p_module->p_config[i].b_dirty = VLC_FALSE;
1905
1906         p_module->p_config[i].p_lock = &p_module->object_lock;
1907
1908         if( p_module->p_config[i].i_list )
1909         {
1910             if( p_module->p_config[i].ppsz_list )
1911             {
1912                 int j;
1913                 p_module->p_config[i].ppsz_list =
1914                     malloc( (p_module->p_config[i].i_list+1) * sizeof(char *));
1915                 if( p_module->p_config[i].ppsz_list )
1916                 {
1917                     for( j = 0; j < p_module->p_config[i].i_list; j++ )
1918                         LOAD_STRING( p_module->p_config[i].ppsz_list[j] );
1919                     p_module->p_config[i].ppsz_list[j] = NULL;
1920                 }
1921             }
1922             if( p_module->p_config[i].ppsz_list_text )
1923             {
1924                 int j;
1925                 p_module->p_config[i].ppsz_list_text =
1926                     malloc( (p_module->p_config[i].i_list+1) * sizeof(char *));
1927                 if( p_module->p_config[i].ppsz_list_text )
1928                 {
1929                   for( j = 0; j < p_module->p_config[i].i_list; j++ )
1930                       LOAD_STRING( p_module->p_config[i].ppsz_list_text[j] );
1931                   p_module->p_config[i].ppsz_list_text[j] = NULL;
1932                 }
1933             }
1934             if( p_module->p_config[i].pi_list )
1935             {
1936                 p_module->p_config[i].pi_list =
1937                     malloc( (p_module->p_config[i].i_list + 1) * sizeof(int) );
1938                 if( p_module->p_config[i].pi_list )
1939                 {
1940                     for (int j = 0; j < p_module->p_config[i].i_list; j++)
1941                         LOAD_IMMEDIATE( p_module->p_config[i].pi_list[j] );
1942                 }
1943             }
1944         }
1945
1946         if( p_module->p_config[i].i_action )
1947         {
1948             p_module->p_config[i].ppf_action =
1949                 malloc( p_module->p_config[i].i_action * sizeof(void *) );
1950             p_module->p_config[i].ppsz_action_text =
1951                 malloc( p_module->p_config[i].i_action * sizeof(char *) );
1952
1953             for (int j = 0; j < p_module->p_config[i].i_action; j++)
1954             {
1955                 p_module->p_config[i].ppf_action[j] = 0;
1956                 LOAD_STRING( p_module->p_config[i].ppsz_action_text[j] );
1957             }
1958         }
1959
1960         LOAD_IMMEDIATE( p_module->p_config[i].pf_callback );
1961     }
1962
1963     return VLC_SUCCESS;
1964
1965  error:
1966
1967     return VLC_EGENERIC;
1968 }
1969
1970 /*****************************************************************************
1971  * SavePluginsCache: saves the plugins cache to a file
1972  *****************************************************************************/
1973 static void CacheSave( vlc_object_t *p_this )
1974 {
1975     static char const psz_tag[] =
1976         "Signature: 8a477f597d28d172789f06886806bc55\r\n"
1977         "# This file is a cache directory tag created by VLC.\r\n"
1978         "# For information about cache directory tags, see:\r\n"
1979         "#   http://www.brynosaurus.com/cachedir/\r\n";
1980
1981     char *psz_filename, *psz_homedir;
1982     FILE *file;
1983     int i, j, i_cache;
1984     module_cache_t **pp_cache;
1985     int32_t i_file_size = 0;
1986     libvlc_global_data_t *p_libvlc_global = vlc_global( p_this );
1987
1988     psz_homedir = p_this->p_libvlc->psz_homedir;
1989     if( !psz_homedir )
1990     {
1991         msg_Err( p_this, "psz_homedir is null" );
1992         return;
1993     }
1994     psz_filename =
1995        (char *)malloc( sizeof("/" CONFIG_DIR "/" PLUGINSCACHE_DIR "/" ) +
1996                        strlen(psz_homedir) + strlen(CacheName()) );
1997
1998     if( !psz_filename )
1999     {
2000         msg_Err( p_this, "out of memory" );
2001         return;
2002     }
2003
2004     sprintf( psz_filename, "%s/%s", psz_homedir, CONFIG_DIR );
2005
2006     config_CreateDir( p_this, psz_filename );
2007
2008     strcat( psz_filename, "/" PLUGINSCACHE_DIR );
2009
2010     config_CreateDir( p_this, psz_filename );
2011
2012     strcat( psz_filename, "/CACHEDIR.TAG" );
2013
2014     file = utf8_fopen( psz_filename, "wb" );
2015     if( file )
2016     {
2017         fwrite( psz_tag, 1, strlen(psz_tag), file );
2018         fclose( file );
2019     }
2020
2021     sprintf( psz_filename, "%s/%s/%s/%s", psz_homedir, CONFIG_DIR,
2022              PLUGINSCACHE_DIR, CacheName() );
2023
2024     msg_Dbg( p_this, "saving plugins cache file %s", psz_filename );
2025
2026     file = utf8_fopen( psz_filename, "wb" );
2027     if( !file )
2028     {
2029         msg_Warn( p_this, "could not open plugins cache file %s for writing",
2030                   psz_filename );
2031         free( psz_filename );
2032         return;
2033     }
2034     free( psz_filename );
2035
2036     /* Empty space for file size */
2037     fwrite( &i_file_size, sizeof(char), sizeof(i_file_size), file );
2038
2039     /* Contains version number */
2040     fprintf( file, "%s", PLUGINSCACHE_DIR COPYRIGHT_MESSAGE );
2041
2042     /* Sub-version number (to avoid breakage in the dev version when cache
2043      * structure changes) */
2044     i_file_size = CACHE_SUBVERSION_NUM;
2045     fwrite( &i_file_size, sizeof(char), sizeof(i_file_size), file );
2046
2047     /* Language */
2048     fprintf( file, "%5.5s", _("C") );
2049
2050     /* Header marker */
2051     i_file_size = ftell( file );
2052     fwrite( &i_file_size, sizeof(char), sizeof(i_file_size), file );
2053
2054     i_cache = p_libvlc_global->p_module_bank->i_cache;
2055     pp_cache = p_libvlc_global->p_module_bank->pp_cache;
2056
2057     fwrite( &i_cache, sizeof(char), sizeof(i_cache), file );
2058
2059 #define SAVE_IMMEDIATE(a) \
2060     fwrite( &a, sizeof(char), sizeof(a), file )
2061 #define SAVE_STRING(a) \
2062     { i_size = a ? strlen( a ) + 1 : 0; \
2063       fwrite( &i_size, sizeof(char), sizeof(i_size), file ); \
2064       if( a ) fwrite( a, sizeof(char), i_size, file ); \
2065     } while(0)
2066
2067     for( i = 0; i < i_cache; i++ )
2068     {
2069         uint16_t i_size;
2070         uint32_t i_submodule;
2071
2072         /* Save common info */
2073         SAVE_STRING( pp_cache[i]->psz_file );
2074         SAVE_IMMEDIATE( pp_cache[i]->i_time );
2075         SAVE_IMMEDIATE( pp_cache[i]->i_size );
2076         SAVE_IMMEDIATE( pp_cache[i]->b_junk );
2077
2078         if( pp_cache[i]->b_junk ) continue;
2079
2080         /* Save additional infos */
2081         SAVE_STRING( pp_cache[i]->p_module->psz_object_name );
2082         SAVE_STRING( pp_cache[i]->p_module->psz_shortname );
2083         SAVE_STRING( pp_cache[i]->p_module->psz_longname );
2084         SAVE_STRING( pp_cache[i]->p_module->psz_help );
2085         SAVE_STRING( pp_cache[i]->p_module->psz_program );
2086         for( j = 0; j < MODULE_SHORTCUT_MAX; j++ )
2087         {
2088             SAVE_STRING( pp_cache[i]->p_module->pp_shortcuts[j] ); // FIX
2089         }
2090         SAVE_STRING( pp_cache[i]->p_module->psz_capability );
2091         SAVE_IMMEDIATE( pp_cache[i]->p_module->i_score );
2092         SAVE_IMMEDIATE( pp_cache[i]->p_module->i_cpu );
2093         SAVE_IMMEDIATE( pp_cache[i]->p_module->b_unloadable );
2094         SAVE_IMMEDIATE( pp_cache[i]->p_module->b_reentrant );
2095         SAVE_IMMEDIATE( pp_cache[i]->p_module->b_submodule );
2096
2097         /* Config stuff */
2098         CacheSaveConfig( pp_cache[i]->p_module, file );
2099
2100         SAVE_STRING( pp_cache[i]->p_module->psz_filename );
2101
2102         i_submodule = pp_cache[i]->p_module->i_children;
2103         SAVE_IMMEDIATE( i_submodule );
2104         for( i_submodule = 0;
2105              i_submodule < (unsigned)pp_cache[i]->p_module->i_children;
2106              i_submodule++ )
2107         {
2108             module_t *p_module =
2109                 (module_t *)pp_cache[i]->p_module->pp_children[i_submodule];
2110
2111             SAVE_STRING( p_module->psz_object_name );
2112             SAVE_STRING( p_module->psz_shortname );
2113             SAVE_STRING( p_module->psz_longname );
2114             SAVE_STRING( p_module->psz_help );
2115             SAVE_STRING( p_module->psz_program );
2116             for( j = 0; j < MODULE_SHORTCUT_MAX; j++ )
2117             {
2118                 SAVE_STRING( p_module->pp_shortcuts[j] ); // FIX
2119             }
2120             SAVE_STRING( p_module->psz_capability );
2121             SAVE_IMMEDIATE( p_module->i_score );
2122             SAVE_IMMEDIATE( p_module->i_cpu );
2123             SAVE_IMMEDIATE( p_module->b_unloadable );
2124             SAVE_IMMEDIATE( p_module->b_reentrant );
2125         }
2126     }
2127
2128     /* Fill-up file size */
2129     i_file_size = ftell( file );
2130     fseek( file, 0, SEEK_SET );
2131     fwrite( &i_file_size, sizeof(char), sizeof(i_file_size), file );
2132
2133     fclose( file );
2134
2135     return;
2136 }
2137
2138 void CacheSaveConfig( module_t *p_module, FILE *file )
2139 {
2140     uint32_t i_lines = p_module->confsize;
2141     uint16_t i_size;
2142
2143     SAVE_IMMEDIATE( p_module->i_config_items );
2144     SAVE_IMMEDIATE( p_module->i_bool_items );
2145     SAVE_IMMEDIATE( i_lines );
2146
2147     for (size_t i = 0; i < i_lines ; i++)
2148     {
2149         SAVE_IMMEDIATE( p_module->p_config[i] );
2150
2151         SAVE_STRING( p_module->p_config[i].psz_type );
2152         SAVE_STRING( p_module->p_config[i].psz_name );
2153         SAVE_STRING( p_module->p_config[i].psz_text );
2154         SAVE_STRING( p_module->p_config[i].psz_longtext );
2155         SAVE_STRING( p_module->p_config[i].psz_current );
2156         if (IsConfigStringType (p_module->p_config[i].i_type))
2157             SAVE_STRING( p_module->p_config[i].orig.psz );
2158
2159         if( p_module->p_config[i].i_list )
2160         {
2161             if( p_module->p_config[i].ppsz_list )
2162             {
2163                 for (int j = 0; j < p_module->p_config[i].i_list; j++)
2164                     SAVE_STRING( p_module->p_config[i].ppsz_list[j] );
2165             }
2166
2167             if( p_module->p_config[i].ppsz_list_text )
2168             {
2169                 for (int j = 0; j < p_module->p_config[i].i_list; j++)
2170                     SAVE_STRING( p_module->p_config[i].ppsz_list_text[j] );
2171             }
2172             if( p_module->p_config[i].pi_list )
2173             {
2174                 for (int j = 0; j < p_module->p_config[i].i_list; j++)
2175                     SAVE_IMMEDIATE( p_module->p_config[i].pi_list[j] );
2176             }
2177         }
2178
2179         for (int j = 0; j < p_module->p_config[i].i_action; j++)
2180             SAVE_STRING( p_module->p_config[i].ppsz_action_text[j] );
2181
2182         SAVE_IMMEDIATE( p_module->p_config[i].pf_callback );
2183     }
2184 }
2185
2186 /*****************************************************************************
2187  * CacheName: Return the cache file name for this platform.
2188  *****************************************************************************/
2189 static char *CacheName( void )
2190 {
2191     static char psz_cachename[32];
2192
2193     /* Code int size, pointer size and endianness in the filename */
2194     int32_t x = 0xbe00001e;
2195     sprintf( psz_cachename, "plugins-%.2x%.2x%.2x.dat", (int)sizeof(int),
2196              (int)sizeof(void *), (unsigned int)((unsigned char *)&x)[0] );
2197     return psz_cachename;
2198 }
2199
2200 /*****************************************************************************
2201  * CacheMerge: Merge a cache module descriptor with a full module descriptor.
2202  *****************************************************************************/
2203 static void CacheMerge( vlc_object_t *p_this, module_t *p_cache,
2204                         module_t *p_module )
2205 {
2206     int i_submodule;
2207     (void)p_this;
2208
2209     p_cache->pf_activate = p_module->pf_activate;
2210     p_cache->pf_deactivate = p_module->pf_deactivate;
2211     p_cache->handle = p_module->handle;
2212
2213     for( i_submodule = 0; i_submodule < p_module->i_children; i_submodule++ )
2214     {
2215         module_t *p_child = (module_t*)p_module->pp_children[i_submodule];
2216         module_t *p_cchild = (module_t*)p_cache->pp_children[i_submodule];
2217         p_cchild->pf_activate = p_child->pf_activate;
2218         p_cchild->pf_deactivate = p_child->pf_deactivate;
2219     }
2220
2221     p_cache->b_loaded = VLC_TRUE;
2222     p_module->b_loaded = VLC_FALSE;
2223 }
2224
2225 /*****************************************************************************
2226  * CacheFind: finds the cache entry corresponding to a file
2227  *****************************************************************************/
2228 static module_cache_t *CacheFind( vlc_object_t *p_this, char *psz_file,
2229                                   int64_t i_time, int64_t i_size )
2230 {
2231     module_cache_t **pp_cache;
2232     int i_cache, i;
2233     libvlc_global_data_t *p_libvlc_global = vlc_global( p_this );
2234
2235     pp_cache = p_libvlc_global->p_module_bank->pp_loaded_cache;
2236     i_cache = p_libvlc_global->p_module_bank->i_loaded_cache;
2237
2238     for( i = 0; i < i_cache; i++ )
2239     {
2240         if( !strcmp( pp_cache[i]->psz_file, psz_file ) &&
2241             pp_cache[i]->i_time == i_time &&
2242             pp_cache[i]->i_size == i_size ) return pp_cache[i];
2243     }
2244
2245     return NULL;
2246 }
2247
2248 #endif /* HAVE_DYNAMIC_PLUGINS */