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