]> git.sesse.net Git - vlc/blob - src/misc/modules.c
* modules.c: fixed module_Need. (but I'm not sure of what to do with
[vlc] / src / misc / modules.c
1 /*****************************************************************************
2  * modules.c : Builtin and plugin modules management functions
3  *****************************************************************************
4  * Copyright (C) 2001-2004 VideoLAN
5  * $Id: modules.c,v 1.147 2004/03/04 23:59:16 fenrir Exp $
6  *
7  * Authors: Sam Hocevar <sam@zoy.org>
8  *          Ethan C. Baldridge <BaldridgeE@cadmus.com>
9  *          Hans-Peter Jansen <hpj@urpla.net>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
24  *****************************************************************************/
25
26 /* Some faulty libcs have a broken struct dirent when _FILE_OFFSET_BITS
27  * is set to 64. Don't try to be cleverer. */
28 #ifdef _FILE_OFFSET_BITS
29 #undef _FILE_OFFSET_BITS
30 #endif
31
32 #include <stdlib.h>                                      /* free(), strtol() */
33 #include <stdio.h>                                              /* sprintf() */
34 #include <string.h>                                              /* strdup() */
35
36 #include <vlc/vlc.h>
37
38 #ifdef HAVE_DIRENT_H
39 #   include <dirent.h>
40 #elif defined( UNDER_CE )
41 #   include <windows.h>                               /* GetFileAttributes() */
42 #else
43 #   include "../extras/dirent.h"
44 #endif
45
46 #ifdef HAVE_SYS_TYPES_H
47 #   include <sys/types.h>
48 #endif
49 #ifdef HAVE_SYS_STAT_H
50 #   include <sys/stat.h>
51 #endif
52 #ifdef HAVE_UNISTD_H
53 #   include <unistd.h>
54 #endif
55
56 #define HAVE_DYNAMIC_PLUGINS
57 #if defined(HAVE_DL_DYLD)
58 #   if defined(HAVE_MACH_O_DYLD_H)
59 #       include <mach-o/dyld.h>
60 #   endif
61 #elif defined(HAVE_DL_BEOS)
62 #   if defined(HAVE_IMAGE_H)
63 #       include <image.h>
64 #   endif
65 #elif defined(HAVE_DL_WINDOWS)
66 #   include <windows.h>
67 #elif defined(HAVE_DL_DLOPEN)
68 #   if defined(HAVE_DLFCN_H) /* Linux, BSD, Hurd */
69 #       include <dlfcn.h>
70 #   endif
71 #   if defined(HAVE_SYS_DL_H)
72 #       include <sys/dl.h>
73 #   endif
74 #elif defined(HAVE_DL_SHL_LOAD)
75 #   if defined(HAVE_DL_H)
76 #       include <dl.h>
77 #   endif
78 #else
79 #   undef HAVE_DYNAMIC_PLUGINS
80 #endif
81
82 #include "vlc_error.h"
83
84 #include "vlc_interface.h"
85 #include "vlc_playlist.h"
86 #include "intf_eject.h"
87
88 #include "stream_control.h"
89 #include "input_ext-intf.h"
90 #include "input_ext-dec.h"
91 #include "input_ext-plugins.h"
92 #include "ninput.h"
93
94 #include "vlc_video.h"
95 #include "video_output.h"
96 #include "vout_synchro.h"
97
98 #include "audio_output.h"
99 #include "aout_internal.h"
100
101 #include "stream_output.h"
102 #include "osd.h"
103 #include "vlc_httpd.h"
104
105 #include "iso_lang.h"
106 #include "charset.h"
107
108 #include "vlc_block.h"
109
110 #if defined( UNDER_CE )
111 #   define MYCHAR wchar_t
112 #else
113 #   define MYCHAR char
114 #endif
115
116 #ifdef HAVE_DYNAMIC_PLUGINS
117 #   include "modules_plugin.h"
118 #endif
119
120 #if defined( UNDER_CE )
121 #    include "modules_builtin_evc.h"
122 #elif defined( _MSC_VER )
123 #    include "modules_builtin_msvc.h"
124 #else
125 #    include "modules_builtin.h"
126 #endif
127 #include "network.h"
128
129 /*****************************************************************************
130  * Local prototypes
131  *****************************************************************************/
132 #ifdef HAVE_DYNAMIC_PLUGINS
133 static void AllocateAllPlugins   ( vlc_object_t * );
134 static void AllocatePluginDir    ( vlc_object_t *, const MYCHAR *, int );
135 static int  AllocatePluginFile   ( vlc_object_t *, MYCHAR * );
136 #endif
137 static int  AllocateBuiltinModule( vlc_object_t *, int ( * ) ( module_t * ) );
138 static int  DeleteModule ( module_t * );
139 #ifdef HAVE_DYNAMIC_PLUGINS
140 static void   DupModule        ( module_t * );
141 static void   UndupModule      ( module_t * );
142 static int    CallEntry        ( module_t * );
143 static void   CloseModule      ( module_handle_t );
144 static void * GetSymbol        ( module_handle_t, const char * );
145 #if defined(HAVE_DL_WINDOWS)
146 static char * GetWindowsError  ( void );
147 #endif
148 #endif
149
150 /*****************************************************************************
151  * module_InitBank: create the module bank.
152  *****************************************************************************
153  * This function creates a module bank structure which will be filled later
154  * on with all the modules found.
155  *****************************************************************************/
156 void __module_InitBank( vlc_object_t *p_this )
157 {
158     module_bank_t *p_bank;
159
160     p_bank = vlc_object_create( p_this, sizeof(module_bank_t) );
161     p_bank->psz_object_name = "module bank";
162
163     /*
164      * Store the symbols to be exported
165      */
166 #ifdef HAVE_DYNAMIC_PLUGINS
167     STORE_SYMBOLS( &p_bank->symbols );
168 #endif
169
170     /* Everything worked, attach the object */
171     p_this->p_libvlc->p_module_bank = p_bank;
172     vlc_object_attach( p_bank, p_this->p_libvlc );
173
174     return;
175 }
176
177 /*****************************************************************************
178  * module_ResetBank: reset the module bank.
179  *****************************************************************************
180  * This function resets the module bank by unloading all unused plugin
181  * modules.
182  *****************************************************************************/
183 void __module_ResetBank( vlc_object_t *p_this )
184 {
185     msg_Err( p_this, "FIXME: module_ResetBank unimplemented" );
186     return;
187 }
188
189 /*****************************************************************************
190  * module_EndBank: empty the module bank.
191  *****************************************************************************
192  * This function unloads all unused plugin modules and empties the module
193  * bank in case of success.
194  *****************************************************************************/
195 void __module_EndBank( vlc_object_t *p_this )
196 {
197     module_t * p_next;
198
199     vlc_object_detach( p_this->p_libvlc->p_module_bank );
200
201     while( p_this->p_libvlc->p_module_bank->i_children )
202     {
203         p_next = (module_t *)p_this->p_libvlc->p_module_bank->pp_children[0];
204
205         if( DeleteModule( p_next ) )
206         {
207             /* Module deletion failed */
208             msg_Err( p_this, "module \"%s\" can't be removed, trying harder",
209                      p_next->psz_object_name );
210
211             /* We just free the module by hand. Niahahahahaha. */
212             vlc_object_detach( p_next );
213             vlc_object_destroy( p_next );
214         }
215     }
216
217     vlc_object_destroy( p_this->p_libvlc->p_module_bank );
218
219     return;
220 }
221
222 /*****************************************************************************
223  * module_LoadMain: load the main program info into the module bank.
224  *****************************************************************************
225  * This function fills the module bank structure with the main module infos.
226  * This is very useful as it will allow us to consider the main program just
227  * as another module, and for instance the configuration options of main will
228  * be available in the module bank structure just as for every other module.
229  *****************************************************************************/
230 void __module_LoadMain( vlc_object_t *p_this )
231 {
232     AllocateBuiltinModule( p_this, vlc_entry__main );
233 }
234
235 /*****************************************************************************
236  * module_LoadBuiltins: load all modules which we built with.
237  *****************************************************************************
238  * This function fills the module bank structure with the builtin modules.
239  *****************************************************************************/
240 void __module_LoadBuiltins( vlc_object_t * p_this )
241 {
242     msg_Dbg( p_this, "checking builtin modules" );
243     ALLOCATE_ALL_BUILTINS();
244 }
245
246 /*****************************************************************************
247  * module_LoadPlugins: load all plugin modules we can find.
248  *****************************************************************************
249  * This function fills the module bank structure with the plugin modules.
250  *****************************************************************************/
251 void __module_LoadPlugins( vlc_object_t * p_this )
252 {
253 #ifdef HAVE_DYNAMIC_PLUGINS
254     msg_Dbg( p_this, "checking plugin modules" );
255     AllocateAllPlugins( p_this );
256 #endif
257 }
258
259 /*****************************************************************************
260  * module_Need: return the best module function, given a capability list.
261  *****************************************************************************
262  * This function returns the module that best fits the asked capabilities.
263  *****************************************************************************/
264 module_t * __module_Need( vlc_object_t *p_this, const char *psz_capability,
265                           const char *psz_name, vlc_bool_t b_strict )
266 {
267     typedef struct module_list_t module_list_t;
268
269     struct module_list_t
270     {
271         module_t *p_module;
272         int i_score;
273         module_list_t *p_next;
274     };
275
276     module_list_t *p_list, *p_first, *p_tmp;
277     vlc_list_t *p_all;
278
279     int i_which_module, i_index = 0;
280     vlc_bool_t b_intf = VLC_FALSE;
281
282     module_t *p_module;
283
284     int   i_shortcuts = 0;
285     char *psz_shortcuts = NULL, *psz_var = NULL;
286
287     msg_Dbg( p_this, "looking for %s module", psz_capability );
288
289     /* Deal with variables */
290     if( psz_name && psz_name[0] == '$' )
291     {
292         vlc_value_t val;
293         var_Create( p_this, psz_name + 1, VLC_VAR_MODULE | VLC_VAR_DOINHERIT );
294         var_Get( p_this, psz_name + 1, &val );
295         psz_var = val.psz_string;
296         psz_name = psz_var;
297     }
298
299     /* Count how many different shortcuts were asked for */
300     if( psz_name && *psz_name )
301     {
302         char *psz_parser, *psz_last_shortcut;
303
304         /* If the user wants none, give him none. */
305         if( !strcmp( psz_name, "none" ) )
306         {
307             if( psz_var ) free( psz_var );
308             return NULL;
309         }
310
311         i_shortcuts++;
312         psz_shortcuts = psz_last_shortcut = strdup( psz_name );
313
314         for( psz_parser = psz_shortcuts; *psz_parser; psz_parser++ )
315         {
316             if( *psz_parser == ',' )
317             {
318                  *psz_parser = '\0';
319                  i_shortcuts++;
320                  psz_last_shortcut = psz_parser + 1;
321             }
322         }
323
324         /* Check if the user wants to override the "strict" mode */
325         if( psz_last_shortcut )
326         {
327             if( !strcmp(psz_last_shortcut, "none") )
328             {
329                 b_strict = VLC_TRUE;
330                 i_shortcuts--;
331             }
332             else if( !strcmp(psz_last_shortcut, "any") )
333             {
334                 b_strict = VLC_FALSE;
335                 i_shortcuts--;
336             }
337         }
338     }
339
340     /* Sort the modules and test them */
341     p_all = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
342     p_list = malloc( p_all->i_count * sizeof( module_list_t ) );
343     p_first = NULL;
344
345     /* Parse the module list for capabilities and probe each of them */
346     for( i_which_module = 0; i_which_module < p_all->i_count; i_which_module++ )
347     {
348         module_t * p_submodule = NULL;
349         int i_shortcut_bonus = 0, i_submodule;
350
351         p_module = (module_t *)p_all->p_values[i_which_module].p_object;
352
353         /* Test that this module can do what we need */
354         if( strcmp( p_module->psz_capability, psz_capability ) )
355         {
356             for( i_submodule = 0;
357                  i_submodule < p_module->i_children;
358                  i_submodule++ )
359             {
360                 if( !strcmp( ((module_t*)p_module->pp_children[ i_submodule ])
361                                            ->psz_capability, psz_capability ) )
362                 {
363                     p_submodule =
364                             (module_t*)p_module->pp_children[ i_submodule ];
365                     break;
366                 }
367             }
368
369             if( p_submodule == NULL )
370             {
371                 continue;
372             }
373
374             p_module = p_submodule;
375         }
376
377         /* Test if we have the required CPU */
378         if( (p_module->i_cpu & p_this->p_libvlc->i_cpu) != p_module->i_cpu )
379         {
380             continue;
381         }
382
383         /* If we required a shortcut, check this plugin provides it. */
384         if( i_shortcuts > 0 )
385         {
386             vlc_bool_t b_trash;
387             int i_dummy, i_short = i_shortcuts;
388             char *psz_name = psz_shortcuts;
389
390             /* Let's drop modules with a 0 score (unless they are
391              * explicitly requested) */
392             b_trash = !p_module->i_score;
393
394             while( i_short > 0 )
395             {
396                 for( i_dummy = 0; p_module->pp_shortcuts[i_dummy]; i_dummy++ )
397                 {
398                     if( !strcasecmp( psz_name,
399                                      p_module->pp_shortcuts[i_dummy] ) )
400                     {
401                         /* Found it */
402                         b_trash = VLC_FALSE;
403                         i_shortcut_bonus = i_short * 10000;
404                         break;
405                     }
406                 }
407
408                 if( i_shortcut_bonus )
409                 {
410                     /* We found it... remember ? */
411                     break;
412                 }
413
414                 /* Go to the next shortcut... This is so lame! */
415                 while( *psz_name )
416                 {
417                     psz_name++;
418                 }
419                 psz_name++;
420                 i_short--;
421             }
422
423             /* If we are in "strict" mode and we couldn't
424              * find the module in the list of provided shortcuts,
425              * then kick the bastard out of here!!! */
426             if( i_short == 0 && b_strict )
427             {
428                 b_trash = VLC_TRUE;
429             }
430
431             if( b_trash )
432             {
433                 continue;
434             }
435         }
436         /* If we didn't require a shortcut, trash zero-scored plugins */
437         else if( !p_module->i_score )
438         {
439             continue;
440         }
441
442         /* Special case: test if we requested a particular intf plugin */
443         if( !i_shortcuts && p_module->psz_program
444              && !strcmp( p_module->psz_program,
445                          p_this->p_vlc->psz_object_name ) )
446         {
447             if( !b_intf )
448             {
449                 /* Remove previous non-matching plugins */
450                 i_index = 0;
451                 b_intf = VLC_TRUE;
452             }
453         }
454         else if( b_intf )
455         {
456             /* This one doesn't match */
457             continue;
458         }
459
460         /* Store this new module */
461         p_list[ i_index ].p_module = p_module;
462         p_list[ i_index ].i_score = p_module->i_score + i_shortcut_bonus;
463
464         /* Add it to the modules-to-probe list */
465         if( i_index == 0 )
466         {
467             p_list[ 0 ].p_next = NULL;
468             p_first = p_list;
469         }
470         else
471         {
472             /* Ok, so at school you learned that quicksort is quick, and
473              * bubble sort sucks raw eggs. But that's when dealing with
474              * thousands of items. Here we have barely 50. */
475             module_list_t *p_newlist = p_first;
476
477             if( p_first->i_score < p_list[ i_index ].i_score )
478             {
479                 p_list[ i_index ].p_next = p_first;
480                 p_first = &p_list[ i_index ];
481             }
482             else
483             {
484                 while( p_newlist->p_next != NULL &&
485                     p_newlist->p_next->i_score >= p_list[ i_index ].i_score )
486                 {
487                     p_newlist = p_newlist->p_next;
488                 }
489
490                 p_list[ i_index ].p_next = p_newlist->p_next;
491                 p_newlist->p_next = &p_list[ i_index ];
492             }
493         }
494
495         i_index++;
496     }
497
498     msg_Dbg( p_this, "probing %i candidate%s",
499                      i_index, i_index == 1 ? "" : "s" );
500
501     /* Lock all candidate modules */
502     p_tmp = p_first;
503     while( p_tmp != NULL )
504     {
505         vlc_object_yield( p_tmp->p_module );
506         p_tmp = p_tmp->p_next;
507     }
508
509     /* We can release the list, interesting modules were yielded */
510     vlc_list_release( p_all );
511
512     /* Parse the linked list and use the first successful module */
513     p_tmp = p_first;
514     while( p_tmp != NULL )
515     {
516         if( p_tmp->p_module->pf_activate
517              && p_tmp->p_module->pf_activate( p_this ) == VLC_SUCCESS )
518         {
519             break;
520         }
521
522         vlc_object_release( p_tmp->p_module );
523         p_tmp = p_tmp->p_next;
524     }
525
526     /* Store the locked module value */
527     if( p_tmp != NULL )
528     {
529         p_module = p_tmp->p_module;
530         p_tmp = p_tmp->p_next;
531     }
532     else
533     {
534         p_module = NULL;
535     }
536
537     /* Unlock the remaining modules */
538     while( p_tmp != NULL )
539     {
540         vlc_object_release( p_tmp->p_module );
541         p_tmp = p_tmp->p_next;
542     }
543
544     free( p_list );
545
546     if( p_module != NULL )
547     {
548         msg_Dbg( p_module, "using %s module \"%s\"",
549                  psz_capability, p_module->psz_object_name );
550     }
551     else if( p_first == NULL )
552     {
553         msg_Err( p_this, "no %s module matched \"%s\"",
554                  psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
555     }
556     else if( psz_name != NULL && *psz_name )
557     {
558         msg_Warn( p_this, "no %s module matching \"%s\" could be loaded",
559                   psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
560     }
561
562     if( psz_shortcuts )
563     {
564         free( psz_shortcuts );
565     }
566
567     if( psz_var )
568     {
569         free( psz_var );
570     }
571
572     /* Don't forget that the module is still locked */
573     return p_module;
574 }
575
576 /*****************************************************************************
577  * module_Unneed: decrease the usage count of a module.
578  *****************************************************************************
579  * This function must be called by the thread that called module_Need, to
580  * decrease the reference count and allow for hiding of modules.
581  *****************************************************************************/
582 void __module_Unneed( vlc_object_t * p_this, module_t * p_module )
583 {
584     /* Use the close method */
585     if( p_module->pf_deactivate )
586     {
587         p_module->pf_deactivate( p_this );
588     }
589
590     msg_Dbg( p_module, "unlocking module \"%s\"", p_module->psz_object_name );
591
592     vlc_object_release( p_module );
593
594     return;
595 }
596
597 /*****************************************************************************
598  * Following functions are local.
599  *****************************************************************************/
600
601 /*****************************************************************************
602  * AllocateAllPlugins: load all plugin modules we can find.
603  *****************************************************************************/
604 #ifdef HAVE_DYNAMIC_PLUGINS
605 static void AllocateAllPlugins( vlc_object_t *p_this )
606 {
607     /* Yes, there are two NULLs because we replace one with "plugin-path". */
608     char *          path[] = { "modules", PLUGIN_PATH, "plugins", NULL,
609                                NULL };
610
611     char **         ppsz_path = path;
612     char *          psz_fullpath;
613
614 #if defined( UNDER_CE )
615     wchar_t         psz_dir[MAX_PATH];
616 #endif
617
618     /* If the user provided a plugin path, we add it to the list */
619     path[ sizeof(path)/sizeof(char*) - 2 ] = config_GetPsz( p_this,
620                                                             "plugin-path" );
621
622     for( ; *ppsz_path != NULL ; ppsz_path++ )
623     {
624 #if defined( SYS_BEOS ) || defined( SYS_DARWIN ) \
625      || ( defined( WIN32 ) && !defined( UNDER_CE ) )
626
627         /* Handle relative as well as absolute paths */
628 #ifdef WIN32
629         if( !(*ppsz_path)[0] || (*ppsz_path)[1] != ':' )
630 #else
631         if( (*ppsz_path)[0] != '/' )
632 #endif
633         {
634             int i_dirlen = strlen( *ppsz_path );
635             i_dirlen += strlen( p_this->p_libvlc->psz_vlcpath ) + 2;
636
637             psz_fullpath = malloc( i_dirlen );
638             if( psz_fullpath == NULL )
639             {
640                 continue;
641             }
642 #ifdef WIN32
643             sprintf( psz_fullpath, "%s\\%s",
644                      p_this->p_libvlc->psz_vlcpath, *ppsz_path );
645 #else
646             sprintf( psz_fullpath, "%s/%s",
647                      p_this->p_libvlc->psz_vlcpath, *ppsz_path );
648 #endif
649         }
650         else
651 #endif
652         {
653             psz_fullpath = strdup( *ppsz_path );
654         }
655
656         msg_Dbg( p_this, "recursively browsing `%s'", psz_fullpath );
657
658         /* Don't go deeper than 5 subdirectories */
659 #if defined( UNDER_CE )
660         MultiByteToWideChar( CP_ACP, 0, psz_fullpath, -1, psz_dir, MAX_PATH );
661         AllocatePluginDir( p_this, psz_dir, 5 );
662 #else
663         AllocatePluginDir( p_this, psz_fullpath, 5 );
664 #endif
665
666         free( psz_fullpath );
667     }
668
669     /* Free plugin-path */
670     if( path[ sizeof(path)/sizeof(char*) - 2 ] )
671         free( path[ sizeof(path)/sizeof(char*) - 2 ] );
672     path[ sizeof(path)/sizeof(char*) - 2 ] = NULL;
673 }
674
675 /*****************************************************************************
676  * AllocatePluginDir: recursively parse a directory to look for plugins
677  *****************************************************************************/
678 static void AllocatePluginDir( vlc_object_t *p_this, const MYCHAR *psz_dir,
679                                int i_maxdepth )
680 {
681 #if defined( UNDER_CE ) || defined( _MSC_VER )
682 #ifdef UNDER_CE
683     MYCHAR psz_path[MAX_PATH + 256];
684 #else
685     char psz_path[MAX_PATH + 256];
686 #endif
687     WIN32_FIND_DATA finddata;
688     HANDLE handle;
689     unsigned int rc;
690 #else
691     int    i_dirlen;
692     DIR *  dir;
693     char * psz_file;
694     struct dirent * file;
695 #endif
696
697     if( p_this->p_vlc->b_die || i_maxdepth < 0 )
698     {
699         return;
700     }
701
702 #if defined( UNDER_CE ) || defined( _MSC_VER )
703     rc = GetFileAttributes( psz_dir );
704     if( !(rc & FILE_ATTRIBUTE_DIRECTORY) )
705     {
706         /* Not a directory */
707         return;
708     }
709
710     /* Parse all files in the directory */
711 #ifdef UNDER_CE
712     swprintf( psz_path, L"%s\\*.*", psz_dir );
713 #else
714     sprintf( psz_path, "%s\\*.*", psz_dir );
715 #endif
716     handle = FindFirstFile( psz_path, &finddata );
717     if( handle == INVALID_HANDLE_VALUE )
718     {
719         /* Empty directory */
720         return;
721     }
722
723     /* Parse the directory and try to load all files it contains. */
724     do
725     {
726 #ifdef UNDER_CE
727         unsigned int i_len = wcslen( finddata.cFileName );
728         swprintf( psz_path, L"%s\\%s", psz_dir, finddata.cFileName );
729 #else
730         unsigned int i_len = strlen( finddata.cFileName );
731         /* Skip ".", ".." and anything starting with "." */
732         if( !*finddata.cFileName || *finddata.cFileName == '.' )
733         {
734             if( !FindNextFile( handle, &finddata ) ) break;
735             continue;
736         }
737         sprintf( psz_path, "%s\\%s", psz_dir, finddata.cFileName );
738 #endif
739
740         if( GetFileAttributes( psz_path ) & FILE_ATTRIBUTE_DIRECTORY )
741         {
742             AllocatePluginDir( p_this, psz_path, i_maxdepth - 1 );
743         }
744         else if( i_len > strlen( LIBEXT )
745 #ifdef UNDER_CE
746                 )
747 #else
748                   /* We only load files ending with LIBEXT */
749                   && !strncasecmp( psz_path + strlen( psz_path)
750                                    - strlen( LIBEXT ),
751                                    LIBEXT, strlen( LIBEXT ) ) )
752 #endif
753         {
754             AllocatePluginFile( p_this, psz_path );
755         }
756     }
757     while( !p_this->p_vlc->b_die && FindNextFile( handle, &finddata ) );
758
759     /* Close the directory */
760     FindClose( handle );
761
762 #else
763     dir = opendir( psz_dir );
764     if( !dir )
765     {
766         return;
767     }
768
769     i_dirlen = strlen( psz_dir );
770
771     /* Parse the directory and try to load all files it contains. */
772     while( !p_this->p_vlc->b_die && (file = readdir( dir )) )
773     {
774         struct stat statbuf;
775         unsigned int i_len;
776
777         /* Skip ".", ".." and anything starting with "." */
778         if( !*file->d_name || *file->d_name == '.' )
779         {
780             continue;
781         }
782
783         i_len = strlen( file->d_name );
784         psz_file = malloc( i_dirlen + 1 + i_len + 1 );
785 #ifdef WIN32
786         sprintf( psz_file, "%s\\%s", psz_dir, file->d_name );
787 #else
788         sprintf( psz_file, "%s/%s", psz_dir, file->d_name );
789 #endif
790
791         if( !stat( psz_file, &statbuf ) && statbuf.st_mode & S_IFDIR )
792         {
793             AllocatePluginDir( p_this, psz_file, i_maxdepth - 1 );
794         }
795         else if( i_len > strlen( LIBEXT )
796                   /* We only load files ending with LIBEXT */
797                   && !strncasecmp( file->d_name + i_len - strlen( LIBEXT ),
798                                    LIBEXT, strlen( LIBEXT ) ) )
799         {
800             AllocatePluginFile( p_this, psz_file );
801         }
802
803         free( psz_file );
804     }
805
806     /* Close the directory */
807     closedir( dir );
808
809 #endif
810 }
811
812 /*****************************************************************************
813  * AllocatePluginFile: load a module into memory and initialize it.
814  *****************************************************************************
815  * This function loads a dynamically loadable module and allocates a structure
816  * for its information data. The module can then be handled by module_Need
817  * and module_Unneed. It can be removed by DeleteModule.
818  *****************************************************************************/
819 static int AllocatePluginFile( vlc_object_t * p_this, MYCHAR * psz_file )
820 {
821     module_t * p_module;
822     module_handle_t handle;
823
824     /*
825      * Try to dynamically load the module. This part is very platform-
826      * specific, and error messages should be as verbose as possible.
827      */
828
829 #if defined(HAVE_DL_DYLD)
830     NSObjectFileImage image;
831     NSObjectFileImageReturnCode ret;
832
833     ret = NSCreateObjectFileImageFromFile( psz_file, &image );
834
835     if( ret != NSObjectFileImageSuccess )
836     {
837         msg_Warn( p_this, "cannot create image from `%s'", psz_file );
838         return -1;
839     }
840
841     /* Open the dynamic module */
842     handle = NSLinkModule( image, psz_file,
843                            NSLINKMODULE_OPTION_RETURN_ON_ERROR );
844
845     if( !handle )
846     {
847         NSLinkEditErrors errors;
848         const char *psz_file, *psz_err;
849         int i_errnum;
850         NSLinkEditError( &errors, &i_errnum, &psz_file, &psz_err );
851         msg_Warn( p_this, "cannot link module `%s' (%s)", psz_file, psz_err );
852         NSDestroyObjectFileImage( image );
853         return -1;
854     }
855
856     /* Destroy our image, we won't need it */
857     NSDestroyObjectFileImage( image );
858
859 #elif defined(HAVE_DL_BEOS)
860     handle = load_add_on( psz_file );
861     if( handle < 0 )
862     {
863         msg_Warn( p_this, "cannot load module `%s'", psz_file );
864         return -1;
865     }
866
867 #elif defined(HAVE_DL_WINDOWS) && defined(UNDER_CE)
868     char psz_filename[MAX_PATH];
869     WideCharToMultiByte( CP_ACP, WC_DEFAULTCHAR, psz_file, -1,
870                          psz_filename, MAX_PATH, NULL, NULL );
871     handle = LoadLibrary( psz_filename );
872     if( handle == NULL )
873     {
874         char *psz_error = GetWindowsError();
875         msg_Warn( p_this, "cannot load module `%s' (%s)",
876                           psz_filename, psz_error );
877         free( psz_error );
878     }
879
880 #elif defined(HAVE_DL_WINDOWS) && defined(WIN32)
881     handle = LoadLibrary( psz_file );
882     if( handle == NULL )
883     {
884         char *psz_error = GetWindowsError();
885         msg_Warn( p_this, "cannot load module `%s' (%s)",
886                           psz_file, psz_error );
887         free( psz_error );
888     }
889
890 #elif defined(HAVE_DL_DLOPEN) && defined(RTLD_NOW)
891     /* static is OK, we are called atomically */
892     static vlc_bool_t b_kde = VLC_FALSE;
893
894 #   if defined(SYS_LINUX)
895     /* XXX HACK #1 - we should NOT open modules with RTLD_GLOBAL, or we
896      * are going to get namespace collisions when two modules have common
897      * public symbols, but ALSA is being a pest here. */
898     if( strstr( psz_file, "alsa_plugin" ) )
899     {
900         handle = dlopen( psz_file, RTLD_NOW | RTLD_GLOBAL );
901         if( handle == NULL )
902         {
903             msg_Warn( p_this, "cannot load module `%s' (%s)",
904                               psz_file, dlerror() );
905             return -1;
906         }
907     }
908 #   endif
909     /* XXX HACK #2 - the ugly KDE workaround. It seems that libkdewhatever
910      * causes dlopen() to segfault if libstdc++ is not loaded in the caller,
911      * so we just load libstdc++. Bwahahaha! ph34r! -- Sam. */
912     /* Update: FYI, this is Debian bug #180505, and seems to be fixed. */
913     if( !b_kde && !strstr( psz_file, "kde" ) )
914     {
915         dlopen( "libstdc++.so.6", RTLD_NOW )
916          || dlopen( "libstdc++.so.5", RTLD_NOW )
917          || dlopen( "libstdc++.so.4", RTLD_NOW )
918          || dlopen( "libstdc++.so.3", RTLD_NOW );
919         b_kde = VLC_TRUE;
920     }
921
922     handle = dlopen( psz_file, RTLD_NOW );
923     if( handle == NULL )
924     {
925         msg_Warn( p_this, "cannot load module `%s' (%s)",
926                           psz_file, dlerror() );
927         return -1;
928     }
929
930 #elif defined(HAVE_DL_DLOPEN)
931 #   if defined(DL_LAZY)
932     handle = dlopen( psz_file, DL_LAZY );
933 #   else
934     handle = dlopen( psz_file, 0 );
935 #   endif
936     if( handle == NULL )
937     {
938         msg_Warn( p_this, "cannot load module `%s' (%s)",
939                           psz_file, dlerror() );
940         return -1;
941     }
942
943 #elif defined(HAVE_DL_SHL_LOAD)
944     handle = shl_load( psz_file, BIND_IMMEDIATE | BIND_NONFATAL, NULL );
945     if( handle == NULL )
946     {
947         msg_Warn( p_this, "cannot load module `%s' (%s)",
948                           psz_file, strerror(errno) );
949         return -1;
950     }
951
952 #else
953 #   error "Something is wrong in modules.c"
954
955 #endif
956
957     /* Now that we have successfully loaded the module, we can
958      * allocate a structure for it */
959     p_module = vlc_object_create( p_this, VLC_OBJECT_MODULE );
960     if( p_module == NULL )
961     {
962         msg_Err( p_this, "out of memory" );
963         CloseModule( handle );
964         return -1;
965     }
966
967     /* We need to fill these since they may be needed by CallEntry() */
968 #ifdef UNDER_CE
969     p_module->psz_filename = psz_filename;
970 #else
971     p_module->psz_filename = psz_file;
972 #endif
973     p_module->handle = handle;
974     p_module->p_symbols = &p_this->p_libvlc->p_module_bank->symbols;
975
976     /* Initialize the module: fill p_module->psz_object_name, default config */
977     if( CallEntry( p_module ) != 0 )
978     {
979         /* We couldn't call module_init() */
980         vlc_object_destroy( p_module );
981         CloseModule( handle );
982         return -1;
983     }
984
985     DupModule( p_module );
986     p_module->psz_filename = strdup( p_module->psz_filename );
987     p_module->psz_longname = strdup( p_module->psz_longname );
988
989     /* Everything worked fine ! The module is ready to be added to the list. */
990     p_module->b_builtin = VLC_FALSE;
991
992     /* msg_Dbg( p_this, "plugin \"%s\", %s",
993                 p_module->psz_object_name, p_module->psz_longname ); */
994
995     vlc_object_attach( p_module, p_this->p_libvlc->p_module_bank );
996
997     return 0;
998 }
999
1000 /*****************************************************************************
1001  * DupModule: make a plugin module standalone.
1002  *****************************************************************************
1003  * This function duplicates all strings in the module, so that the dynamic
1004  * object can be unloaded. It acts recursively on submodules.
1005  *****************************************************************************/
1006 static void DupModule( module_t *p_module )
1007 {
1008     char **pp_shortcut;
1009     int i_submodule;
1010
1011     for( pp_shortcut = p_module->pp_shortcuts ; *pp_shortcut ; pp_shortcut++ )
1012     {
1013         *pp_shortcut = strdup( *pp_shortcut );
1014     }
1015
1016     /* We strdup() these entries so that they are still valid when the
1017      * module is unloaded. */
1018     p_module->psz_object_name = strdup( p_module->psz_object_name );
1019     p_module->psz_capability = strdup( p_module->psz_capability );
1020
1021     if( p_module->psz_program != NULL )
1022     {
1023         p_module->psz_program = strdup( p_module->psz_program );
1024     }
1025
1026     for( i_submodule = 0; i_submodule < p_module->i_children; i_submodule++ )
1027     {
1028         DupModule( (module_t*)p_module->pp_children[ i_submodule ] );
1029     }
1030 }
1031
1032 /*****************************************************************************
1033  * UndupModule: free a duplicated module.
1034  *****************************************************************************
1035  * This function frees the allocations done in DupModule().
1036  *****************************************************************************/
1037 static void UndupModule( module_t *p_module )
1038 {
1039     char **pp_shortcut;
1040     int i_submodule;
1041
1042     for( i_submodule = 0; i_submodule < p_module->i_children; i_submodule++ )
1043     {
1044         UndupModule( (module_t*)p_module->pp_children[ i_submodule ] );
1045     }
1046
1047     for( pp_shortcut = p_module->pp_shortcuts ; *pp_shortcut ; pp_shortcut++ )
1048     {
1049         free( *pp_shortcut );
1050     }
1051
1052     free( p_module->psz_object_name );
1053     free( p_module->psz_capability );
1054
1055     if( p_module->psz_program != NULL )
1056     {
1057         free( p_module->psz_program );
1058     }
1059 }
1060
1061 #endif /* HAVE_DYNAMIC_PLUGINS */
1062
1063 /*****************************************************************************
1064  * AllocateBuiltinModule: initialize a builtin module.
1065  *****************************************************************************
1066  * This function registers a builtin module and allocates a structure
1067  * for its information data. The module can then be handled by module_Need
1068  * and module_Unneed. It can be removed by DeleteModule.
1069  *****************************************************************************/
1070 static int AllocateBuiltinModule( vlc_object_t * p_this,
1071                                   int ( *pf_entry ) ( module_t * ) )
1072 {
1073     module_t * p_module;
1074
1075     /* Now that we have successfully loaded the module, we can
1076      * allocate a structure for it */
1077     p_module = vlc_object_create( p_this, VLC_OBJECT_MODULE );
1078     if( p_module == NULL )
1079     {
1080         msg_Err( p_this, "out of memory" );
1081         return -1;
1082     }
1083
1084     /* Initialize the module : fill p_module->psz_object_name, etc. */
1085     if( pf_entry( p_module ) != 0 )
1086     {
1087         /* With a well-written module we shouldn't have to print an
1088          * additional error message here, but just make sure. */
1089         msg_Err( p_this, "failed calling entry point in builtin module" );
1090         vlc_object_destroy( p_module );
1091         return -1;
1092     }
1093
1094     /* Everything worked fine ! The module is ready to be added to the list. */
1095     p_module->b_builtin = VLC_TRUE;
1096
1097     /* msg_Dbg( p_this, "builtin \"%s\", %s",
1098                 p_module->psz_object_name, p_module->psz_longname ); */
1099
1100     vlc_object_attach( p_module, p_this->p_libvlc->p_module_bank );
1101
1102     return 0;
1103 }
1104
1105 /*****************************************************************************
1106  * DeleteModule: delete a module and its structure.
1107  *****************************************************************************
1108  * This function can only be called if the module isn't being used.
1109  *****************************************************************************/
1110 static int DeleteModule( module_t * p_module )
1111 {
1112     vlc_object_detach( p_module );
1113
1114     /* We free the structures that we strdup()ed in Allocate*Module(). */
1115 #ifdef HAVE_DYNAMIC_PLUGINS
1116     if( !p_module->b_builtin )
1117     {
1118         if( p_module->b_unloadable )
1119         {
1120             CloseModule( p_module->handle );
1121         }
1122         UndupModule( p_module );
1123         free( p_module->psz_filename );
1124         free( p_module->psz_longname );
1125     }
1126 #endif
1127
1128     /* Free and detach the object's children */
1129     while( p_module->i_children )
1130     {
1131         vlc_object_t *p_this = p_module->pp_children[0];
1132         vlc_object_detach( p_this );
1133         vlc_object_destroy( p_this );
1134     }
1135
1136     config_Free( p_module );
1137     vlc_object_destroy( p_module );
1138
1139     return 0;
1140 }
1141
1142 #ifdef HAVE_DYNAMIC_PLUGINS
1143 /*****************************************************************************
1144  * CallEntry: call an entry point.
1145  *****************************************************************************
1146  * This function calls a symbol given its name and a module structure. The
1147  * symbol MUST refer to a function returning int and taking a module_t* as
1148  * an argument.
1149  *****************************************************************************/
1150 static int CallEntry( module_t * p_module )
1151 {
1152     static char *psz_name = "vlc_entry" MODULE_SUFFIX;
1153     int (* pf_symbol) ( module_t * p_module );
1154
1155     /* Try to resolve the symbol */
1156     pf_symbol = (int (*)(module_t *)) GetSymbol( p_module->handle, psz_name );
1157
1158     if( pf_symbol == NULL )
1159     {
1160 #if defined(HAVE_DL_DYLD) || defined(HAVE_DL_BEOS)
1161         msg_Warn( p_module, "cannot find symbol \"%s\" in file `%s'",
1162                             psz_name, p_module->psz_filename );
1163 #elif defined(HAVE_DL_WINDOWS)
1164         char *psz_error = GetWindowsError();
1165         msg_Warn( p_module, "cannot find symbol \"%s\" in file `%s' (%s)",
1166                             psz_name, p_module->psz_filename, psz_error );
1167         free( psz_error );
1168 #elif defined(HAVE_DL_DLOPEN)
1169         msg_Warn( p_module, "cannot find symbol \"%s\" in file `%s' (%s)",
1170                             psz_name, p_module->psz_filename, dlerror() );
1171 #elif defined(HAVE_DL_SHL_LOAD)
1172         msg_Warn( p_module, "cannot find symbol \"%s\" in file `%s' (%s)",
1173                             psz_name, p_module->psz_filename, strerror(errno) );
1174 #else
1175 #   error "Something is wrong in modules.c"
1176 #endif
1177         return -1;
1178     }
1179
1180     /* We can now try to call the symbol */
1181     if( pf_symbol( p_module ) != 0 )
1182     {
1183         /* With a well-written module we shouldn't have to print an
1184          * additional error message here, but just make sure. */
1185         msg_Err( p_module, "failed calling symbol \"%s\" in file `%s'",
1186                            psz_name, p_module->psz_filename );
1187         return -1;
1188     }
1189
1190     /* Everything worked fine, we can return */
1191     return 0;
1192 }
1193
1194 /*****************************************************************************
1195  * CloseModule: unload a dynamic library
1196  *****************************************************************************
1197  * This function unloads a previously opened dynamically linked library
1198  * using a system dependant method. No return value is taken in consideration,
1199  * since some libraries sometimes refuse to close properly.
1200  *****************************************************************************/
1201 static void CloseModule( module_handle_t handle )
1202 {
1203 #if defined(HAVE_DL_DYLD)
1204     NSUnLinkModule( handle, FALSE );
1205
1206 #elif defined(HAVE_DL_BEOS)
1207     unload_add_on( handle );
1208
1209 #elif defined(HAVE_DL_WINDOWS)
1210     FreeLibrary( handle );
1211
1212 #elif defined(HAVE_DL_DLOPEN)
1213     dlclose( handle );
1214
1215 #elif defined(HAVE_DL_SHL_LOAD)
1216     shl_unload( handle );
1217
1218 #endif
1219     return;
1220 }
1221
1222 /*****************************************************************************
1223  * GetSymbol: get a symbol from a dynamic library
1224  *****************************************************************************
1225  * This function queries a loaded library for a symbol specified in a
1226  * string, and returns a pointer to it. We don't check for dlerror() or
1227  * similar functions, since we want a non-NULL symbol anyway.
1228  *****************************************************************************/
1229 static void * _module_getsymbol( module_handle_t, const char * );
1230
1231 static void * GetSymbol( module_handle_t handle, const char * psz_function )
1232 {
1233     void * p_symbol = _module_getsymbol( handle, psz_function );
1234
1235     /* MacOS X dl library expects symbols to begin with "_". So do
1236      * some other operating systems. That's really lame, but hey, what
1237      * can we do ? */
1238     if( p_symbol == NULL )
1239     {
1240         char *psz_call = malloc( strlen( psz_function ) + 2 );
1241
1242         strcpy( psz_call + 1, psz_function );
1243         psz_call[ 0 ] = '_';
1244         p_symbol = _module_getsymbol( handle, psz_call );
1245         free( psz_call );
1246     }
1247
1248     return p_symbol;
1249 }
1250
1251 static void * _module_getsymbol( module_handle_t handle,
1252                                  const char * psz_function )
1253 {
1254 #if defined(HAVE_DL_DYLD)
1255     NSSymbol sym = NSLookupSymbolInModule( handle, psz_function );
1256     return NSAddressOfSymbol( sym );
1257
1258 #elif defined(HAVE_DL_BEOS)
1259     void * p_symbol;
1260     if( B_OK == get_image_symbol( handle, psz_function,
1261                                   B_SYMBOL_TYPE_TEXT, &p_symbol ) )
1262     {
1263         return p_symbol;
1264     }
1265     else
1266     {
1267         return NULL;
1268     }
1269
1270 #elif defined(HAVE_DL_WINDOWS) && defined(UNDER_CE)
1271     wchar_t psz_real[256];
1272     MultiByteToWideChar( CP_ACP, 0, psz_function, -1, psz_real, 256 );
1273
1274     return (void *)GetProcAddress( handle, psz_real );
1275
1276 #elif defined(HAVE_DL_WINDOWS) && defined(WIN32)
1277     return (void *)GetProcAddress( handle, (MYCHAR*)psz_function );
1278
1279 #elif defined(HAVE_DL_DLOPEN)
1280     return dlsym( handle, psz_function );
1281
1282 #elif defined(HAVE_DL_SHL_LOAD)
1283     void *p_sym;
1284     shl_findsym( &handle, psz_function, TYPE_UNDEFINED, &p_sym );
1285     return p_sym;
1286
1287 #endif
1288 }
1289
1290 #if defined(HAVE_DL_WINDOWS)
1291 static char * GetWindowsError( void )
1292 {
1293 #if defined(UNDER_CE)
1294     wchar_t psz_tmp[256];
1295     char * psz_buffer = malloc( 256 );
1296 #else
1297     char * psz_tmp = malloc( 256 );
1298 #endif
1299     int i = 0, i_error = GetLastError();
1300
1301     FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1302                    NULL, i_error, MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
1303                    (LPTSTR) psz_tmp, 256, NULL );
1304
1305     /* Go to the end of the string */
1306 #if defined(UNDER_CE)
1307     while( psz_tmp[i] && psz_tmp[i] != L'\r' && psz_tmp[i] != L'\n' )
1308 #else
1309     while( psz_tmp[i] && psz_tmp[i] != '\r' && psz_tmp[i] != '\n' )
1310 #endif
1311     {
1312         i++;
1313     }
1314
1315     if( psz_tmp[i] )
1316     {
1317 #if defined(UNDER_CE)
1318         swprintf( psz_tmp + i, L" (error %i)", i_error );
1319         psz_tmp[ 255 ] = L'\0';
1320 #else
1321         snprintf( psz_tmp + i, 256 - i, " (error %i)", i_error );
1322         psz_tmp[ 255 ] = '\0';
1323 #endif
1324     }
1325
1326 #if defined(UNDER_CE)
1327     WideCharToMultiByte( CP_ACP, WC_DEFAULTCHAR, psz_tmp, -1,
1328                          psz_buffer, 256, NULL, NULL );
1329     return psz_buffer;
1330 #else
1331     return psz_tmp;
1332 #endif
1333 }
1334 #endif /* HAVE_DL_WINDOWS */
1335
1336 #endif /* HAVE_DYNAMIC_PLUGINS */