]> git.sesse.net Git - vlc/blob - src/modules/modules.c
8301933064113eacf4249e81c545d239675bcdd9
[vlc] / src / modules / modules.c
1 /*****************************************************************************
2  * modules.c : Builtin and plugin modules management functions
3  *****************************************************************************
4  * Copyright (C) 2001-2007 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Sam Hocevar <sam@zoy.org>
8  *          Ethan C. Baldridge <BaldridgeE@cadmus.com>
9  *          Hans-Peter Jansen <hpj@urpla.net>
10  *          Gildas Bazin <gbazin@videolan.org>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <vlc_common.h>
32 #include <vlc_plugin.h>
33 #include "libvlc.h"
34
35 /* Some faulty libcs have a broken struct dirent when _FILE_OFFSET_BITS
36  * is set to 64. Don't try to be cleverer. */
37 #ifdef _FILE_OFFSET_BITS
38 #undef _FILE_OFFSET_BITS
39 #endif
40
41 #include <stdlib.h>                                      /* free(), strtol() */
42 #include <stdio.h>                                              /* sprintf() */
43 #include <string.h>                                              /* strdup() */
44 #include <assert.h>
45
46 #ifdef HAVE_DIRENT_H
47 #   include <dirent.h>
48 #endif
49
50 #ifdef HAVE_SYS_TYPES_H
51 #   include <sys/types.h>
52 #endif
53 #ifdef HAVE_SYS_STAT_H
54 #   include <sys/stat.h>
55 #endif
56 #ifdef HAVE_UNISTD_H
57 #   include <unistd.h>
58 #endif
59
60 #if !defined(HAVE_DYNAMIC_PLUGINS)
61     /* no support for plugins */
62 #elif defined(HAVE_DL_DYLD)
63 #   if defined(HAVE_MACH_O_DYLD_H)
64 #       include <mach-o/dyld.h>
65 #   endif
66 #elif defined(HAVE_DL_BEOS)
67 #   if defined(HAVE_IMAGE_H)
68 #       include <image.h>
69 #   endif
70 #elif defined(HAVE_DL_WINDOWS)
71 #   include <windows.h>
72 #elif defined(HAVE_DL_DLOPEN)
73 #   if defined(HAVE_DLFCN_H) /* Linux, BSD, Hurd */
74 #       include <dlfcn.h>
75 #   endif
76 #   if defined(HAVE_SYS_DL_H)
77 #       include <sys/dl.h>
78 #   endif
79 #elif defined(HAVE_DL_SHL_LOAD)
80 #   if defined(HAVE_DL_H)
81 #       include <dl.h>
82 #   endif
83 #endif
84
85 #include "config/configuration.h"
86
87 #include "vlc_charset.h"
88 #include "vlc_arrays.h"
89
90 #include "modules/modules.h"
91 #include "modules/builtin.h"
92
93 /*****************************************************************************
94  * Local prototypes
95  *****************************************************************************/
96 #ifdef HAVE_DYNAMIC_PLUGINS
97 static void AllocateAllPlugins  ( vlc_object_t * );
98 static void AllocatePluginDir   ( vlc_object_t *, const char *, int );
99 static int  AllocatePluginFile  ( vlc_object_t *, char *, int64_t, int64_t );
100 static module_t * AllocatePlugin( vlc_object_t *, char * );
101 #endif
102 static int  AllocateBuiltinModule( vlc_object_t *, int ( * ) ( module_t * ) );
103 static void DeleteModule ( module_t *, bool );
104 #ifdef HAVE_DYNAMIC_PLUGINS
105 static void   DupModule        ( module_t * );
106 static void   UndupModule      ( module_t * );
107 #endif
108
109 /**
110  * Init bank
111  *
112  * Creates a module bank structure which will be filled later
113  * on with all the modules found.
114  * \param p_this vlc object structure
115  * \return nothing
116  */
117 void __module_InitBank( vlc_object_t *p_this )
118 {
119     module_bank_t *p_bank = NULL;
120     libvlc_global_data_t *p_libvlc_global = vlc_global();
121
122     vlc_mutex_t *lock = var_AcquireMutex( "libvlc" );
123
124     if( p_libvlc_global->p_module_bank == NULL )
125     {
126         p_bank = vlc_custom_create( p_this, sizeof(module_bank_t),
127                                     VLC_OBJECT_GENERIC, "module bank");
128         p_bank->i_usage = 1;
129         p_bank->i_cache = p_bank->i_loaded_cache = 0;
130         p_bank->pp_cache = p_bank->pp_loaded_cache = NULL;
131         p_bank->b_cache = p_bank->b_cache_dirty =
132         p_bank->b_cache_delete = false;
133
134         /* Everything worked, attach the object */
135         p_libvlc_global->p_module_bank = p_bank;
136         vlc_object_attach( p_bank, p_libvlc_global );
137
138         /* Fills the module bank structure with the main module infos.
139          * This is very useful as it will allow us to consider the main
140          * library just as another module, and for instance the configuration
141          * options of main will be available in the module bank structure just
142          * as for every other module. */
143         AllocateBuiltinModule( p_this, vlc_entry__main );
144     }
145     else
146         p_libvlc_global->p_module_bank->i_usage++;
147
148     vlc_mutex_unlock( lock );
149 }
150
151
152 /**
153  * End bank
154  *
155  * Unloads all unused plugin modules and empties the module
156  * bank in case of success.
157  * \param p_this vlc object structure
158  * \return nothing
159  */
160 void __module_EndBank( vlc_object_t *p_this )
161 {
162     module_t * p_next = NULL;
163     libvlc_global_data_t *p_libvlc_global = vlc_global();
164
165     vlc_mutex_t *lock = var_AcquireMutex( "libvlc" );
166     if( !p_libvlc_global->p_module_bank )
167     {
168         vlc_mutex_unlock( lock );
169         return;
170     }
171     if( --p_libvlc_global->p_module_bank->i_usage )
172     {
173         vlc_mutex_unlock( lock );
174         return;
175     }
176     vlc_mutex_unlock( lock );
177
178     /* Save the configuration */
179     config_AutoSaveConfigFile( p_this );
180
181 #ifdef HAVE_DYNAMIC_PLUGINS
182 # define p_bank p_libvlc_global->p_module_bank
183     if( p_bank->b_cache ) CacheSave( p_this );
184     while( p_bank->i_loaded_cache-- )
185     {
186         if( p_bank->pp_loaded_cache[p_bank->i_loaded_cache] )
187         {
188             DeleteModule(
189                     p_bank->pp_loaded_cache[p_bank->i_loaded_cache]->p_module,
190                     p_bank->pp_loaded_cache[p_bank->i_loaded_cache]->b_used );
191             free( p_bank->pp_loaded_cache[p_bank->i_loaded_cache]->psz_file );
192             free( p_bank->pp_loaded_cache[p_bank->i_loaded_cache] );
193             p_bank->pp_loaded_cache[p_bank->i_loaded_cache] = NULL;
194         }
195     }
196     if( p_bank->pp_loaded_cache )
197     {
198         free( p_bank->pp_loaded_cache );
199         p_bank->pp_loaded_cache = NULL;
200     }
201     while( p_bank->i_cache-- )
202     {
203         free( p_bank->pp_cache[p_bank->i_cache]->psz_file );
204         free( p_bank->pp_cache[p_bank->i_cache] );
205         p_bank->pp_cache[p_bank->i_cache] = NULL;
206     }
207     if( p_bank->pp_cache )
208     {
209         free( p_bank->pp_cache );
210         p_bank->pp_cache = NULL;
211     }
212 # undef p_bank
213 #endif
214
215     vlc_object_detach( p_libvlc_global->p_module_bank );
216
217     while( vlc_internals( p_libvlc_global->p_module_bank )->i_children )
218     {
219         p_next = (module_t *)vlc_internals( p_libvlc_global->p_module_bank )->pp_children[0];
220         DeleteModule( p_next, true );
221     }
222
223     vlc_object_release( p_libvlc_global->p_module_bank );
224     p_libvlc_global->p_module_bank = NULL;
225 }
226
227 /**
228  * Load all modules which we built with.
229  *
230  * Fills the module bank structure with the builtin modules.
231  * \param p_this vlc object structure
232  * \return nothing
233  */
234 void __module_LoadBuiltins( vlc_object_t * p_this )
235 {
236     libvlc_global_data_t *p_libvlc_global = vlc_global();
237
238     vlc_mutex_t *lock = var_AcquireMutex( "libvlc" );
239     if( p_libvlc_global->p_module_bank->b_builtins )
240     {
241         vlc_mutex_unlock( lock );
242         return;
243     }
244     p_libvlc_global->p_module_bank->b_builtins = true;
245     vlc_mutex_unlock( lock );
246
247     msg_Dbg( p_this, "checking builtin modules" );
248     ALLOCATE_ALL_BUILTINS();
249 }
250
251 /**
252  * Load all plugins
253  *
254  * Load all plugin modules we can find.
255  * Fills the module bank structure with the plugin modules.
256  * \param p_this vlc object structure
257  * \return nothing
258  */
259 void __module_LoadPlugins( vlc_object_t * p_this )
260 {
261 #ifdef HAVE_DYNAMIC_PLUGINS
262     libvlc_global_data_t *p_libvlc_global = vlc_global();
263
264     vlc_mutex_t *lock = var_AcquireMutex( "libvlc" );
265     if( p_libvlc_global->p_module_bank->b_plugins )
266     {
267         vlc_mutex_unlock( lock );
268         return;
269     }
270     p_libvlc_global->p_module_bank->b_plugins = true;
271     vlc_mutex_unlock( lock );
272
273     msg_Dbg( p_this, "checking plugin modules" );
274
275     if( config_GetInt( p_this, "plugins-cache" ) )
276         p_libvlc_global->p_module_bank->b_cache = true;
277
278     if( p_libvlc_global->p_module_bank->b_cache ||
279         p_libvlc_global->p_module_bank->b_cache_delete ) CacheLoad( p_this );
280
281     AllocateAllPlugins( p_this );
282 #endif
283 }
284
285 /**
286  * Checks whether a module implements a capability.
287  *
288  * \param m the module
289  * \param cap the capability to check
290  * \return TRUE if the module have the capability
291  */
292 bool module_IsCapable( const module_t *m, const char *cap )
293 {
294     return !strcmp( m->psz_capability, cap );
295 }
296
297 /**
298  * Get the internal name of a module
299  *
300  * \param m the module
301  * \return the module name
302  */
303 const char *module_GetObjName( const module_t *m )
304 {
305     return m->psz_object_name;
306 }
307
308 /**
309  * Get the human-friendly name of a module.
310  *
311  * \param m the module
312  * \param long_name TRUE to have the long name of the module
313  * \return the short or long name of the module
314  */
315 const char *module_GetName( const module_t *m, bool long_name )
316 {
317     if( long_name && ( m->psz_longname != NULL) )
318         return m->psz_longname;
319
320     return m->psz_shortname ?: m->psz_object_name;
321 }
322
323 /**
324  * Get the help for a module
325  *
326  * \param m the module
327  * \return the help
328  */
329 const char *module_GetHelp( const module_t *m )
330 {
331     return m->psz_help;
332 }
333
334 /**
335  * module Need
336  *
337  * Return the best module function, given a capability list.
338  * \param p_this the vlc object
339  * \param psz_capability list of capabilities needed
340  * \param psz_name name of the module asked
341  * \param b_strict TRUE yto use the strict mode
342  * \return the module or NULL in case of a failure
343  */
344 module_t * __module_Need( vlc_object_t *p_this, const char *psz_capability,
345                           const char *psz_name, bool b_strict )
346 {
347     typedef struct module_list_t module_list_t;
348
349     stats_TimerStart( p_this, "module_Need()", STATS_TIMER_MODULE_NEED );
350
351     struct module_list_t
352     {
353         module_t *p_module;
354         int i_score;
355         bool b_force;
356         module_list_t *p_next;
357     };
358
359     module_list_t *p_list, *p_first, *p_tmp;
360     vlc_list_t *p_all;
361
362     int i_which_module, i_index = 0;
363
364     module_t *p_module;
365
366     int   i_shortcuts = 0;
367     char *psz_shortcuts = NULL, *psz_var = NULL, *psz_alias = NULL;
368     bool b_force_backup = p_this->b_force;
369
370
371     /* Deal with variables */
372     if( psz_name && psz_name[0] == '$' )
373     {
374         vlc_value_t val;
375         var_Create( p_this, psz_name + 1, VLC_VAR_MODULE | VLC_VAR_DOINHERIT );
376         var_Get( p_this, psz_name + 1, &val );
377         psz_var = val.psz_string;
378         psz_name = psz_var;
379     }
380
381     /* Count how many different shortcuts were asked for */
382     if( psz_name && *psz_name )
383     {
384         char *psz_parser, *psz_last_shortcut;
385
386         /* If the user wants none, give him none. */
387         if( !strcmp( psz_name, "none" ) )
388         {
389             free( psz_var );
390             stats_TimerStop( p_this, STATS_TIMER_MODULE_NEED );
391             stats_TimerDump( p_this, STATS_TIMER_MODULE_NEED );
392             stats_TimerClean( p_this, STATS_TIMER_MODULE_NEED );
393             return NULL;
394         }
395
396         i_shortcuts++;
397         psz_shortcuts = psz_last_shortcut = strdup( psz_name );
398
399         for( psz_parser = psz_shortcuts; *psz_parser; psz_parser++ )
400         {
401             if( *psz_parser == ',' )
402             {
403                  *psz_parser = '\0';
404                  i_shortcuts++;
405                  psz_last_shortcut = psz_parser + 1;
406             }
407         }
408
409         /* Check if the user wants to override the "strict" mode */
410         if( psz_last_shortcut )
411         {
412             if( !strcmp(psz_last_shortcut, "none") )
413             {
414                 b_strict = true;
415                 i_shortcuts--;
416             }
417             else if( !strcmp(psz_last_shortcut, "any") )
418             {
419                 b_strict = false;
420                 i_shortcuts--;
421             }
422         }
423     }
424
425     /* Sort the modules and test them */
426     p_all = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
427     p_list = malloc( p_all->i_count * sizeof( module_list_t ) );
428     p_first = NULL;
429     unsigned i_cpu = vlc_CPU();
430
431     /* Parse the module list for capabilities and probe each of them */
432     for( i_which_module = 0; i_which_module < p_all->i_count; i_which_module++ )
433     {
434         int i_shortcut_bonus = 0;
435
436         p_module = (module_t *)p_all->p_values[i_which_module].p_object;
437
438         /* Test that this module can do what we need */
439         if( !module_IsCapable( p_module, psz_capability ) )
440         {
441             /* Don't recurse through the sub-modules because vlc_list_find()
442              * will list them anyway. */
443             continue;
444         }
445
446         /* Test if we have the required CPU */
447         if( (p_module->i_cpu & i_cpu) != p_module->i_cpu )
448         {
449             continue;
450         }
451
452         /* If we required a shortcut, check this plugin provides it. */
453         if( i_shortcuts > 0 )
454         {
455             bool b_trash;
456             const char *psz_name = psz_shortcuts;
457
458             /* Let's drop modules with a <= 0 score (unless they are
459              * explicitly requested) */
460             b_trash = p_module->i_score <= 0;
461
462             for( unsigned i_short = i_shortcuts; i_short > 0; i_short-- )
463             {
464                 for( unsigned i = 0; p_module->pp_shortcuts[i]; i++ )
465                 {
466                     char *c;
467                     if( ( c = strchr( psz_name, '@' ) )
468                         ? !strncasecmp( psz_name, p_module->pp_shortcuts[i],
469                                         c-psz_name )
470                         : !strcasecmp( psz_name, p_module->pp_shortcuts[i] ) )
471                     {
472                         /* Found it */
473                         if( c && c[1] )
474                             psz_alias = c+1;
475                         i_shortcut_bonus = i_short * 10000;
476                         goto found_shortcut;
477                     }
478                 }
479
480                 /* Go to the next shortcut... This is so lame! */
481                 psz_name += strlen( psz_name ) + 1;
482             }
483
484             /* If we are in "strict" mode and we couldn't
485              * find the module in the list of provided shortcuts,
486              * then kick the bastard out of here!!! */
487             if( b_strict )
488                 continue;
489         }
490         /* If we didn't require a shortcut, trash <= 0 scored plugins */
491         else if( p_module->i_score <= 0 )
492         {
493             continue;
494         }
495
496 found_shortcut:
497
498         /* Store this new module */
499         p_list[ i_index ].p_module = p_module;
500         p_list[ i_index ].i_score = p_module->i_score + i_shortcut_bonus;
501         p_list[ i_index ].b_force = i_shortcut_bonus && b_strict;
502
503         /* Add it to the modules-to-probe list */
504         if( i_index == 0 )
505         {
506             p_list[ 0 ].p_next = NULL;
507             p_first = p_list;
508         }
509         else
510         {
511             /* Ok, so at school you learned that quicksort is quick, and
512              * bubble sort sucks raw eggs. But that's when dealing with
513              * thousands of items. Here we have barely 50. */
514             module_list_t *p_newlist = p_first;
515
516             if( p_first->i_score < p_list[ i_index ].i_score )
517             {
518                 p_list[ i_index ].p_next = p_first;
519                 p_first = &p_list[ i_index ];
520             }
521             else
522             {
523                 while( p_newlist->p_next != NULL &&
524                     p_newlist->p_next->i_score >= p_list[ i_index ].i_score )
525                 {
526                     p_newlist = p_newlist->p_next;
527                 }
528
529                 p_list[ i_index ].p_next = p_newlist->p_next;
530                 p_newlist->p_next = &p_list[ i_index ];
531             }
532         }
533
534         i_index++;
535     }
536
537     msg_Dbg( p_this, "looking for %s module: %i candidate%s", psz_capability,
538                                             i_index, i_index == 1 ? "" : "s" );
539
540     /* Lock all candidate modules */
541     p_tmp = p_first;
542     while( p_tmp != NULL )
543     {
544         vlc_object_yield( p_tmp->p_module );
545         p_tmp = p_tmp->p_next;
546     }
547
548     /* We can release the list, interesting modules were yielded */
549     vlc_list_release( p_all );
550
551     /* Parse the linked list and use the first successful module */
552     p_tmp = p_first;
553     while( p_tmp != NULL )
554     {
555 #ifdef HAVE_DYNAMIC_PLUGINS
556         /* Make sure the module is loaded in mem */
557         module_t *p_module = p_tmp->p_module;
558         if( p_module->b_submodule )
559             p_module = (module_t *)p_module->p_parent;
560
561         if( !p_module->b_builtin && !p_module->b_loaded )
562         {
563             module_t *p_new_module =
564                 AllocatePlugin( p_this, p_module->psz_filename );
565             if( p_new_module )
566             {
567                 CacheMerge( p_this, p_module, p_new_module );
568                 vlc_object_attach( p_new_module, p_module );
569                 DeleteModule( p_new_module, true );
570             }
571         }
572 #endif
573
574         p_this->b_force = p_tmp->b_force;
575         if( p_tmp->p_module->pf_activate
576              && p_tmp->p_module->pf_activate( p_this ) == VLC_SUCCESS )
577         {
578             break;
579         }
580
581         vlc_object_release( p_tmp->p_module );
582         p_tmp = p_tmp->p_next;
583     }
584
585     /* Store the locked module value */
586     if( p_tmp != NULL )
587     {
588         p_module = p_tmp->p_module;
589         p_tmp = p_tmp->p_next;
590     }
591     else
592     {
593         p_module = NULL;
594     }
595
596     /* Unlock the remaining modules */
597     while( p_tmp != NULL )
598     {
599         vlc_object_release( p_tmp->p_module );
600         p_tmp = p_tmp->p_next;
601     }
602
603     free( p_list );
604     p_this->b_force = b_force_backup;
605
606     if( p_module != NULL )
607     {
608         msg_Dbg( p_this, "using %s module \"%s\"",
609                  psz_capability, p_module->psz_object_name );
610     }
611     else if( p_first == NULL )
612     {
613         if( !strcmp( psz_capability, "access_demux" ) )
614         {
615             msg_Warn( p_this, "no %s module matched \"%s\"",
616                  psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
617         }
618         else
619         {
620             msg_Err( p_this, "no %s module matched \"%s\"",
621                  psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
622
623             msg_StackSet( VLC_EGENERIC, "no %s module matched \"%s\"",
624                  psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
625         }
626     }
627     else if( psz_name != NULL && *psz_name )
628     {
629         msg_Warn( p_this, "no %s module matching \"%s\" could be loaded",
630                   psz_capability, (psz_name && *psz_name) ? psz_name : "any" );
631     }
632     else
633         msg_StackSet( VLC_EGENERIC, "no suitable %s module", psz_capability );
634
635     if( p_module && !p_this->psz_object_name )
636     {
637         /* This assumes that p_this is the object which will be using the
638          * module. That's not always the case ... but it is in most cases.
639          */
640         if( psz_alias )
641             p_this->psz_object_name = strdup( psz_alias );
642         else
643             p_this->psz_object_name = strdup( p_module->psz_object_name );
644     }
645
646     free( psz_shortcuts );
647     free( psz_var );
648
649     stats_TimerStop( p_this, STATS_TIMER_MODULE_NEED );
650     stats_TimerDump( p_this, STATS_TIMER_MODULE_NEED );
651     stats_TimerClean( p_this, STATS_TIMER_MODULE_NEED );
652
653     /* Don't forget that the module is still locked */
654     return p_module;
655 }
656
657 /**
658  * Module unneed
659  *
660  * This function must be called by the thread that called module_Need, to
661  * decrease the reference count and allow for hiding of modules.
662  * \param p_this vlc object structure
663  * \param p_module the module structure
664  * \return nothing
665  */
666 void __module_Unneed( vlc_object_t * p_this, module_t * p_module )
667 {
668     /* Use the close method */
669     if( p_module->pf_deactivate )
670     {
671         p_module->pf_deactivate( p_this );
672     }
673
674     msg_Dbg( p_this, "removing module \"%s\"", p_module->psz_object_name );
675
676     vlc_object_release( p_module );
677 }
678
679 /**
680  * Get a pointer to a module_t given it's name.
681  *
682  * \param p_this vlc object structure
683  * \param psz_name the name of the module
684  * \return a pointer to the module or NULL in case of a failure
685  */
686 module_t *__module_Find( vlc_object_t *p_this, const char * psz_name )
687 {
688     vlc_list_t *p_list;
689     int i;
690     p_list = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
691     for( i = 0 ; i < p_list->i_count; i++)
692     {
693         module_t *p_module = ((module_t *) p_list->p_values[i].p_object);
694         const char *psz_module_name = p_module->psz_object_name;
695         if( psz_module_name && !strcmp( psz_module_name, psz_name ) )
696         {
697             /* We can release the list, and return yes */
698             vlc_object_yield( p_module );
699             vlc_list_release( p_list );
700             return p_module;
701         }
702     }
703     vlc_list_release( p_list );
704     return NULL;
705 }
706
707
708 /**
709  * Release a module_t pointer from module_Find().
710  *
711  * \param module the module to release
712  * \return nothing
713  */
714 void module_Put( module_t *module )
715 {
716     vlc_object_release( module );
717 }
718
719
720 /**
721  * Tell if a module exists and release it in thic case
722  *
723  * \param p_this vlc object structure
724  * \param psz_name th name of the module
725  * \return TRUE if the module exists
726  */
727 bool __module_Exists( vlc_object_t *p_this, const char * psz_name )
728 {
729     module_t *p_module = __module_Find( p_this, psz_name );
730     if( p_module )
731     {
732         module_Put( p_module );
733         return true;
734     }
735     else
736     {
737         return false;
738     }
739 }
740
741 /**
742  * GetModuleNamesForCapability
743  *
744  * Return a NULL terminated array with the names of the modules
745  * that have a certain capability.
746  * Free after uses both the string and the table.
747  * \param p_this vlc object structure
748  * \param psz_capability the capability asked
749  * \param pppsz_longname an pointer to an array of string to contain
750     the long names of the modules. If set to NULL the function don't use it.
751  * \return the NULL terminated array
752  */
753 char ** __module_GetModulesNamesForCapability( vlc_object_t *p_this,
754                                                const char *psz_capability,
755                                                char ***pppsz_longname )
756 {
757     vlc_list_t *p_list;
758     int i, j, count = 0;
759     char **psz_ret;
760
761     /* Do it in two passes : count the number of modules before */
762     p_list = vlc_list_find( p_this, VLC_OBJECT_MODULE, FIND_ANYWHERE );
763     for( i = 0 ; i < p_list->i_count; i++)
764     {
765         module_t *p_module = ((module_t *) p_list->p_values[i].p_object);
766         const char *psz_module_capability = p_module->psz_capability;
767         if( psz_module_capability && !strcmp( psz_module_capability, psz_capability ) )
768             count++;
769     }
770
771     psz_ret = malloc( sizeof(char*) * (count+1) );
772     if( pppsz_longname )
773         *pppsz_longname = malloc( sizeof(char*) * (count+1) );
774     if( !psz_ret || ( pppsz_longname && *pppsz_longname == NULL ) )
775     {
776         free( psz_ret );
777         free( *pppsz_longname );
778         *pppsz_longname = NULL;
779         vlc_list_release( p_list );
780         return NULL;
781     }
782
783     j = 0;
784     for( i = 0 ; i < p_list->i_count; i++)
785     {
786         module_t *p_module = ((module_t *) p_list->p_values[i].p_object);
787         const char *psz_module_capability = p_module->psz_capability;
788         if( psz_module_capability && !strcmp( psz_module_capability, psz_capability ) )
789         {
790             int k = -1; /* hack to handle submodules properly */
791             if( p_module->b_submodule )
792             {
793                 while( p_module->pp_shortcuts[++k] != NULL );
794                 k--;
795             }
796             psz_ret[j] = strdup( k>=0?p_module->pp_shortcuts[k]
797                                      :p_module->psz_object_name );
798             if( pppsz_longname )
799                 (*pppsz_longname)[j] = strdup( module_GetName( p_module, true ) );
800             j++;
801         }
802     }
803     psz_ret[count] = NULL;
804
805     vlc_list_release( p_list );
806
807     return psz_ret;
808 }
809
810 /**
811  * Get the configuration of a module
812  *
813  * \param module the module
814  * \param psize the size of the configuration returned
815  * \return the configuration as an array
816  */
817 module_config_t *module_GetConfig( const module_t *module, unsigned *restrict psize )
818 {
819     unsigned i,j;
820     unsigned size = module->confsize;
821     module_config_t *config = malloc( size * sizeof( *config ) );
822
823     assert( psize != NULL );
824     *psize = 0;
825
826     if( !config )
827         return NULL;
828
829     for( i = 0, j = 0; i < size; i++ )
830     {
831         const module_config_t *item = module->p_config + i;
832         if( item->b_internal /* internal option */
833          || item->b_unsaveable /* non-modifiable option */
834          || item->b_removed /* removed option */ )
835             continue;
836
837         memcpy( config + j, item, sizeof( *config ) );
838         j++;
839     }
840     *psize = j;
841
842     return config;
843 }
844
845 /**
846  * Release the configuration
847  *
848  * \param the configuration
849  * \return nothing
850  */
851 void module_PutConfig( module_config_t *config )
852 {
853     free( config );
854 }
855
856 /*****************************************************************************
857  * Following functions are local.
858  *****************************************************************************/
859
860  /*****************************************************************************
861  * copy_next_paths_token: from a PATH_SEP_CHAR (a ':' or a ';') separated paths
862  * return first path.
863  *****************************************************************************/
864 static char * copy_next_paths_token( char * paths, char ** remaining_paths )
865 {
866     char * path;
867     int i, done;
868     bool escaped = false;
869
870     assert( paths );
871
872     /* Alloc a buffer to store the path */
873     path = malloc( strlen( paths ) + 1 );
874     if( !path ) return NULL;
875
876     /* Look for PATH_SEP_CHAR (a ':' or a ';') */
877     for( i = 0, done = 0 ; paths[i]; i++ )
878     {
879         /* Take care of \\ and \: or \; escapement */
880         if( escaped )
881         {
882             escaped = false;
883             path[done++] = paths[i];
884         }
885 #ifdef WIN32
886         else if( paths[i] == '/' )
887             escaped = true;
888 #else
889         else if( paths[i] == '\\' )
890             escaped = true;
891 #endif
892         else if( paths[i] == PATH_SEP_CHAR )
893             break;
894         else
895             path[done++] = paths[i];
896     }
897     path[done++] = 0;
898
899     /* Return the remaining paths */
900     if( remaining_paths ) {
901         *remaining_paths = paths[i] ? &paths[i]+1 : NULL;
902     }
903
904     return path;
905 }
906
907 /*****************************************************************************
908  * AllocateAllPlugins: load all plugin modules we can find.
909  *****************************************************************************/
910 #ifdef HAVE_DYNAMIC_PLUGINS
911 static void AllocateAllPlugins( vlc_object_t *p_this )
912 {
913     const char *vlcpath = vlc_global()->psz_vlcpath;
914     int count,i;
915     char * path;
916     vlc_array_t *arraypaths = vlc_array_new();
917
918     /* Contruct the special search path for system that have a relocatable
919      * executable. Set it to <vlc path>/modules and <vlc path>/plugins. */
920
921     if( vlcpath && asprintf( &path, "%s" DIR_SEP "modules", vlcpath ) != -1 )
922         vlc_array_append( arraypaths, path );
923     if( vlcpath && asprintf( &path, "%s" DIR_SEP "plugins", vlcpath ) != -1 )
924         vlc_array_append( arraypaths, path );
925 #ifndef WIN32
926     vlc_array_append( arraypaths, strdup( PLUGIN_PATH ) );
927 #endif
928
929     /* If the user provided a plugin path, we add it to the list */
930     char *userpaths = config_GetPsz( p_this, "plugin-path" );
931     char *paths_iter;
932
933     for( paths_iter = userpaths; paths_iter; )
934     {
935         path = copy_next_paths_token( paths_iter, &paths_iter );
936         if( path )
937             vlc_array_append( arraypaths, path );
938     }
939
940     count = vlc_array_count( arraypaths );
941     for( i = 0 ; i < count ; i++ )
942     {
943         path = vlc_array_item_at_index( arraypaths, i );
944         if( !path )
945             continue;
946
947         msg_Dbg( p_this, "recursively browsing `%s'", path );
948
949         /* Don't go deeper than 5 subdirectories */
950         AllocatePluginDir( p_this, path, 5 );
951
952         free( path );
953     }
954
955     vlc_array_destroy( arraypaths );
956     free( userpaths );
957 }
958
959 /*****************************************************************************
960  * AllocatePluginDir: recursively parse a directory to look for plugins
961  *****************************************************************************/
962 static void AllocatePluginDir( vlc_object_t *p_this, const char *psz_dir,
963                                int i_maxdepth )
964 {
965 /* FIXME: Needs to be ported to wide char on ALL Windows builds */
966 #ifdef WIN32
967 # undef opendir
968 # undef closedir
969 # undef readdir
970 #endif
971 #if defined( UNDER_CE ) || defined( _MSC_VER )
972 #ifdef UNDER_CE
973     wchar_t psz_wpath[MAX_PATH + 256];
974     wchar_t psz_wdir[MAX_PATH];
975 #endif
976     char psz_path[MAX_PATH + 256];
977     WIN32_FIND_DATA finddata;
978     HANDLE handle;
979     int rc;
980 #else
981     int    i_dirlen;
982     DIR *  dir;
983     struct dirent * file;
984 #endif
985     char * psz_file;
986
987     if( p_this->p_libvlc->b_die || i_maxdepth < 0 )
988     {
989         return;
990     }
991
992 #if defined( UNDER_CE ) || defined( _MSC_VER )
993 #ifdef UNDER_CE
994     MultiByteToWideChar( CP_ACP, 0, psz_dir, -1, psz_wdir, MAX_PATH );
995
996     rc = GetFileAttributes( psz_wdir );
997     if( rc<0 || !(rc&FILE_ATTRIBUTE_DIRECTORY) ) return; /* Not a directory */
998
999     /* Parse all files in the directory */
1000     swprintf( psz_wpath, L"%ls\\*", psz_wdir );
1001 #else
1002     rc = GetFileAttributes( psz_dir );
1003     if( rc<0 || !(rc&FILE_ATTRIBUTE_DIRECTORY) ) return; /* Not a directory */
1004 #endif
1005
1006     /* Parse all files in the directory */
1007     sprintf( psz_path, "%s\\*", psz_dir );
1008
1009 #ifdef UNDER_CE
1010     handle = FindFirstFile( psz_wpath, &finddata );
1011 #else
1012     handle = FindFirstFile( psz_path, &finddata );
1013 #endif
1014     if( handle == INVALID_HANDLE_VALUE )
1015     {
1016         /* Empty directory */
1017         return;
1018     }
1019
1020     /* Parse the directory and try to load all files it contains. */
1021     do
1022     {
1023 #ifdef UNDER_CE
1024         unsigned int i_len = wcslen( finddata.cFileName );
1025         swprintf( psz_wpath, L"%ls\\%ls", psz_wdir, finddata.cFileName );
1026         sprintf( psz_path, "%s\\%ls", psz_dir, finddata.cFileName );
1027 #else
1028         unsigned int i_len = strlen( finddata.cFileName );
1029         sprintf( psz_path, "%s\\%s", psz_dir, finddata.cFileName );
1030 #endif
1031
1032         /* Skip ".", ".." */
1033         if( !*finddata.cFileName || !strcmp( finddata.cFileName, "." )
1034          || !strcmp( finddata.cFileName, ".." ) )
1035         {
1036             if( !FindNextFile( handle, &finddata ) ) break;
1037             continue;
1038         }
1039
1040 #ifdef UNDER_CE
1041         if( GetFileAttributes( psz_wpath ) & FILE_ATTRIBUTE_DIRECTORY )
1042 #else
1043         if( GetFileAttributes( psz_path ) & FILE_ATTRIBUTE_DIRECTORY )
1044 #endif
1045         {
1046             AllocatePluginDir( p_this, psz_path, i_maxdepth - 1 );
1047         }
1048         else if( i_len > strlen( LIBEXT )
1049                   /* We only load files ending with LIBEXT */
1050                   && !strncasecmp( psz_path + strlen( psz_path)
1051                                    - strlen( LIBEXT ),
1052                                    LIBEXT, strlen( LIBEXT ) ) )
1053         {
1054             WIN32_FILE_ATTRIBUTE_DATA attrbuf;
1055             int64_t i_time = 0, i_size = 0;
1056
1057 #ifdef UNDER_CE
1058             if( GetFileAttributesEx( psz_wpath, GetFileExInfoStandard,
1059                                      &attrbuf ) )
1060 #else
1061             if( GetFileAttributesEx( psz_path, GetFileExInfoStandard,
1062                                      &attrbuf ) )
1063 #endif
1064             {
1065                 i_time = attrbuf.ftLastWriteTime.dwHighDateTime;
1066                 i_time <<= 32;
1067                 i_time |= attrbuf.ftLastWriteTime.dwLowDateTime;
1068                 i_size = attrbuf.nFileSizeHigh;
1069                 i_size <<= 32;
1070                 i_size |= attrbuf.nFileSizeLow;
1071             }
1072             psz_file = psz_path;
1073
1074             AllocatePluginFile( p_this, psz_file, i_time, i_size );
1075         }
1076     }
1077     while( !p_this->p_libvlc->b_die && FindNextFile( handle, &finddata ) );
1078
1079     /* Close the directory */
1080     FindClose( handle );
1081
1082 #else
1083     dir = opendir( psz_dir );
1084     if( !dir )
1085     {
1086         return;
1087     }
1088
1089     i_dirlen = strlen( psz_dir );
1090
1091     /* Parse the directory and try to load all files it contains. */
1092     while( !p_this->p_libvlc->b_die && ( file = readdir( dir ) ) )
1093     {
1094         struct stat statbuf;
1095         unsigned int i_len;
1096         int i_stat;
1097
1098         /* Skip ".", ".." */
1099         if( !*file->d_name || !strcmp( file->d_name, "." )
1100          || !strcmp( file->d_name, ".." ) )
1101         {
1102             continue;
1103         }
1104
1105         i_len = strlen( file->d_name );
1106         psz_file = malloc( i_dirlen + 1 + i_len + 1 );
1107         sprintf( psz_file, "%s"DIR_SEP"%s", psz_dir, file->d_name );
1108
1109         i_stat = stat( psz_file, &statbuf );
1110         if( !i_stat && statbuf.st_mode & S_IFDIR )
1111         {
1112             AllocatePluginDir( p_this, psz_file, i_maxdepth - 1 );
1113         }
1114         else if( i_len > strlen( LIBEXT )
1115                   /* We only load files ending with LIBEXT */
1116                   && !strncasecmp( file->d_name + i_len - strlen( LIBEXT ),
1117                                    LIBEXT, strlen( LIBEXT ) ) )
1118         {
1119             int64_t i_time = 0, i_size = 0;
1120
1121             if( !i_stat )
1122             {
1123                 i_time = statbuf.st_mtime;
1124                 i_size = statbuf.st_size;
1125             }
1126
1127             AllocatePluginFile( p_this, psz_file, i_time, i_size );
1128         }
1129
1130         free( psz_file );
1131     }
1132
1133     /* Close the directory */
1134     closedir( dir );
1135
1136 #endif
1137 }
1138
1139 /*****************************************************************************
1140  * AllocatePluginFile: load a module into memory and initialize it.
1141  *****************************************************************************
1142  * This function loads a dynamically loadable module and allocates a structure
1143  * for its information data. The module can then be handled by module_Need
1144  * and module_Unneed. It can be removed by DeleteModule.
1145  *****************************************************************************/
1146 static int AllocatePluginFile( vlc_object_t * p_this, char * psz_file,
1147                                int64_t i_file_time, int64_t i_file_size )
1148 {
1149     module_t * p_module = NULL;
1150     module_cache_t *p_cache_entry = NULL;
1151
1152     /*
1153      * Check our plugins cache first then load plugin if needed
1154      */
1155     p_cache_entry =
1156         CacheFind( psz_file, i_file_time, i_file_size );
1157
1158     if( !p_cache_entry )
1159     {
1160         p_module = AllocatePlugin( p_this, psz_file );
1161     }
1162     else
1163     {
1164         /* If junk dll, don't try to load it */
1165         if( p_cache_entry->b_junk )
1166         {
1167             p_module = NULL;
1168         }
1169         else
1170         {
1171             module_config_t *p_item = NULL, *p_end = NULL;
1172
1173             p_module = p_cache_entry->p_module;
1174             p_module->b_loaded = false;
1175
1176             /* For now we force loading if the module's config contains
1177              * callbacks or actions.
1178              * Could be optimized by adding an API call.*/
1179             for( p_item = p_module->p_config, p_end = p_item + p_module->confsize;
1180                  p_item < p_end; p_item++ )
1181             {
1182                 if( p_item->pf_callback || p_item->i_action )
1183                 {
1184                     p_module = AllocatePlugin( p_this, psz_file );
1185                     break;
1186                 }
1187             }
1188             if( p_module == p_cache_entry->p_module )
1189                 p_cache_entry->b_used = true;
1190         }
1191     }
1192
1193     if( p_module )
1194     {
1195         libvlc_global_data_t *p_libvlc_global = vlc_global();
1196
1197         /* Everything worked fine !
1198          * The module is ready to be added to the list. */
1199         p_module->b_builtin = false;
1200
1201         /* msg_Dbg( p_this, "plugin \"%s\", %s",
1202                     p_module->psz_object_name, p_module->psz_longname ); */
1203
1204         vlc_object_attach( p_module, p_libvlc_global->p_module_bank );
1205
1206         if( !p_libvlc_global->p_module_bank->b_cache )
1207             return 0;
1208
1209 #define p_bank p_libvlc_global->p_module_bank
1210         /* Add entry to cache */
1211         p_bank->pp_cache =
1212             realloc( p_bank->pp_cache, (p_bank->i_cache + 1) * sizeof(void *) );
1213         p_bank->pp_cache[p_bank->i_cache] = malloc( sizeof(module_cache_t) );
1214         if( !p_bank->pp_cache[p_bank->i_cache] )
1215             return -1;
1216         p_bank->pp_cache[p_bank->i_cache]->psz_file = strdup( psz_file );
1217         p_bank->pp_cache[p_bank->i_cache]->i_time = i_file_time;
1218         p_bank->pp_cache[p_bank->i_cache]->i_size = i_file_size;
1219         p_bank->pp_cache[p_bank->i_cache]->b_junk = p_module ? 0 : 1;
1220         p_bank->pp_cache[p_bank->i_cache]->b_used = true;
1221         p_bank->pp_cache[p_bank->i_cache]->p_module = p_module;
1222         p_bank->i_cache++;
1223     }
1224
1225     return p_module ? 0 : -1;
1226 }
1227
1228 /*****************************************************************************
1229  * AllocatePlugin: load a module into memory and initialize it.
1230  *****************************************************************************
1231  * This function loads a dynamically loadable module and allocates a structure
1232  * for its information data. The module can then be handled by module_Need
1233  * and module_Unneed. It can be removed by DeleteModule.
1234  *****************************************************************************/
1235 static module_t * AllocatePlugin( vlc_object_t * p_this, char * psz_file )
1236 {
1237     module_t * p_module = NULL;
1238     module_handle_t handle;
1239
1240     if( module_Load( p_this, psz_file, &handle ) )
1241         return NULL;
1242
1243     /* Now that we have successfully loaded the module, we can
1244      * allocate a structure for it */
1245     p_module = vlc_module_create( p_this );
1246     if( p_module == NULL )
1247     {
1248         module_Unload( handle );
1249         return NULL;
1250     }
1251
1252     /* We need to fill these since they may be needed by module_Call() */
1253     p_module->psz_filename = psz_file;
1254     p_module->handle = handle;
1255     p_module->b_loaded = true;
1256
1257     /* Initialize the module: fill p_module, default config */
1258     if( module_Call( p_module ) != 0 )
1259     {
1260         /* We couldn't call module_init() */
1261         vlc_object_release( p_module );
1262         module_Unload( handle );
1263         return NULL;
1264     }
1265
1266     DupModule( p_module );
1267     p_module->psz_filename = strdup( p_module->psz_filename );
1268
1269     /* Everything worked fine ! The module is ready to be added to the list. */
1270     p_module->b_builtin = false;
1271
1272     return p_module;
1273 }
1274
1275 /*****************************************************************************
1276  * DupModule: make a plugin module standalone.
1277  *****************************************************************************
1278  * This function duplicates all strings in the module, so that the dynamic
1279  * object can be unloaded. It acts recursively on submodules.
1280  *****************************************************************************/
1281 static void DupModule( module_t *p_module )
1282 {
1283     char **pp_shortcut;
1284     int i_submodule;
1285
1286     for( pp_shortcut = p_module->pp_shortcuts ; *pp_shortcut ; pp_shortcut++ )
1287     {
1288         *pp_shortcut = strdup( *pp_shortcut );
1289     }
1290
1291     /* We strdup() these entries so that they are still valid when the
1292      * module is unloaded. */
1293     p_module->psz_capability = strdup( p_module->psz_capability );
1294     p_module->psz_shortname = p_module->psz_shortname ?
1295                                  strdup( p_module->psz_shortname ) : NULL;
1296     p_module->psz_longname = strdup( p_module->psz_longname );
1297     p_module->psz_help = p_module->psz_help ? strdup( p_module->psz_help )
1298                                             : NULL;
1299
1300     for( i_submodule = 0; i_submodule < vlc_internals( p_module )->i_children; i_submodule++ )
1301     {
1302         DupModule( (module_t*)vlc_internals( p_module )->pp_children[ i_submodule ] );
1303     }
1304 }
1305
1306 /*****************************************************************************
1307  * UndupModule: free a duplicated module.
1308  *****************************************************************************
1309  * This function frees the allocations done in DupModule().
1310  *****************************************************************************/
1311 static void UndupModule( module_t *p_module )
1312 {
1313     char **pp_shortcut;
1314     int i_submodule;
1315
1316     for( i_submodule = 0; i_submodule < vlc_internals( p_module )->i_children; i_submodule++ )
1317     {
1318         UndupModule( (module_t*)vlc_internals( p_module )->pp_children[ i_submodule ] );
1319     }
1320
1321     for( pp_shortcut = p_module->pp_shortcuts ; *pp_shortcut ; pp_shortcut++ )
1322     {
1323         free( *pp_shortcut );
1324     }
1325
1326     FREENULL( p_module->psz_object_name );
1327     free( p_module->psz_capability );
1328     free( p_module->psz_shortname );
1329     free( p_module->psz_longname );
1330     free( p_module->psz_help );
1331 }
1332
1333 #endif /* HAVE_DYNAMIC_PLUGINS */
1334
1335 /*****************************************************************************
1336  * AllocateBuiltinModule: initialize a builtin module.
1337  *****************************************************************************
1338  * This function registers a builtin module and allocates a structure
1339  * for its information data. The module can then be handled by module_Need
1340  * and module_Unneed. It can be removed by DeleteModule.
1341  *****************************************************************************/
1342 static int AllocateBuiltinModule( vlc_object_t * p_this,
1343                                   int ( *pf_entry ) ( module_t * ) )
1344 {
1345     module_t * p_module;
1346
1347     /* Now that we have successfully loaded the module, we can
1348      * allocate a structure for it */
1349     p_module = vlc_module_create( p_this );
1350     if( p_module == NULL )
1351         return -1;
1352
1353     /* Initialize the module : fill p_module->psz_object_name, etc. */
1354     if( pf_entry( p_module ) != 0 )
1355     {
1356         /* With a well-written module we shouldn't have to print an
1357          * additional error message here, but just make sure. */
1358         msg_Err( p_this, "failed calling entry point in builtin module" );
1359         vlc_object_release( p_module );
1360         return -1;
1361     }
1362
1363     /* Everything worked fine ! The module is ready to be added to the list. */
1364     p_module->b_builtin = true;
1365
1366     /* msg_Dbg( p_this, "builtin \"%s\", %s",
1367                 p_module->psz_object_name, p_module->psz_longname ); */
1368
1369     vlc_object_attach( p_module, vlc_global()->p_module_bank );
1370
1371     return 0;
1372 }
1373
1374 /*****************************************************************************
1375  * DeleteModule: delete a module and its structure.
1376  *****************************************************************************
1377  * This function can only be called if the module isn't being used.
1378  *****************************************************************************/
1379 static void DeleteModule( module_t * p_module, bool b_detach )
1380 {
1381     assert( p_module );
1382
1383     if( b_detach )
1384         vlc_object_detach( p_module );
1385
1386     /* We free the structures that we strdup()ed in Allocate*Module(). */
1387 #ifdef HAVE_DYNAMIC_PLUGINS
1388     if( !p_module->b_builtin )
1389     {
1390         if( p_module->b_loaded && p_module->b_unloadable )
1391         {
1392             module_Unload( p_module->handle );
1393         }
1394         UndupModule( p_module );
1395         free( p_module->psz_filename );
1396     }
1397 #endif
1398
1399     /* Free and detach the object's children */
1400     while( vlc_internals( p_module )->i_children )
1401     {
1402         vlc_object_t *p_this = vlc_internals( p_module )->pp_children[0];
1403         vlc_object_detach( p_this );
1404         vlc_object_release( p_this );
1405     }
1406
1407     config_Free( p_module );
1408     vlc_object_release( p_module );
1409 }