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