]> git.sesse.net Git - vlc/blob - src/modules/bank.c
Qt4: use MTA apartment for COM (fixes #6880)
[vlc] / src / modules / bank.c
1 /*****************************************************************************
2  * bank.c : Modules list
3  *****************************************************************************
4  * Copyright (C) 2001-2011 VLC authors and VideoLAN
5  *
6  * Authors: Sam Hocevar <sam@zoy.org>
7  *          Ethan C. Baldridge <BaldridgeE@cadmus.com>
8  *          Hans-Peter Jansen <hpj@urpla.net>
9  *          Gildas Bazin <gbazin@videolan.org>
10  *          RĂ©mi Denis-Courmont
11  *
12  * This program is free software; you can redistribute it and/or modify it
13  * under the terms of the GNU Lesser General Public License as published by
14  * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public License
23  * along with this program; if not, write to the Free Software Foundation,
24  * 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 <stdlib.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <assert.h>
35
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #ifdef HAVE_UNISTD_H
39 #   include <unistd.h>
40 #endif
41
42 #include <vlc_common.h>
43 #include <vlc_plugin.h>
44 #include <vlc_modules.h>
45 #include <vlc_fs.h>
46 #include "libvlc.h"
47 #include "config/configuration.h"
48 #include "modules/modules.h"
49
50 static struct
51 {
52     vlc_mutex_t lock;
53     module_t *head;
54     unsigned usage;
55 } modules = { VLC_STATIC_MUTEX, NULL, 0 };
56
57 /*****************************************************************************
58  * Local prototypes
59  *****************************************************************************/
60 #ifdef HAVE_DYNAMIC_PLUGINS
61 static void AllocateAllPlugins (vlc_object_t *);
62 #endif
63 static module_t *module_InitStatic (vlc_plugin_cb);
64
65 static void module_StoreBank (module_t *module)
66 {
67     /*vlc_assert_locked (&modules.lock);*/
68     module->next = modules.head;
69     modules.head = module;
70 }
71
72 #if defined(__ELF__) || !HAVE_DYNAMIC_PLUGINS
73 # ifdef __GNUC__
74 __attribute__((weak))
75 # else
76 #  pragma weak vlc_static_modules
77 # endif
78 extern vlc_plugin_cb vlc_static_modules[];
79
80 static void module_InitStaticModules(void)
81 {
82     if (!vlc_static_modules)
83         return;
84
85     for (unsigned i = 0; vlc_static_modules[i]; i++) {
86         module_t *module = module_InitStatic (vlc_static_modules[i]);
87         if (likely(module != NULL))
88             module_StoreBank (module);
89     }
90 }
91 #else
92 static void module_InitStaticModules(void) { }
93 #endif
94
95 /**
96  * Init bank
97  *
98  * Creates a module bank structure which will be filled later
99  * on with all the modules found.
100  */
101 void module_InitBank (void)
102 {
103     vlc_mutex_lock (&modules.lock);
104
105     if (modules.usage == 0)
106     {
107         /* Fills the module bank structure with the main module infos.
108          * This is very useful as it will allow us to consider the main
109          * library just as another module, and for instance the configuration
110          * options of main will be available in the module bank structure just
111          * as for every other module. */
112         module_t *module = module_InitStatic (vlc_entry__main);
113         if (likely(module != NULL))
114             module_StoreBank (module);
115         config_SortConfig ();
116     }
117     modules.usage++;
118
119     /* We do retain the module bank lock until the plugins are loaded as well.
120      * This is ugly, this staged loading approach is needed: LibVLC gets
121      * some configuration parameters relevant to loading the plugins from
122      * the main (builtin) module. The module bank becomes shared read-only data
123      * once it is ready, so we need to fully serialize initialization.
124      * DO NOT UNCOMMENT the following line unless you managed to squeeze
125      * module_LoadPlugins() before you unlock the mutex. */
126     /*vlc_mutex_unlock (&modules.lock);*/
127 }
128
129 /**
130  * Unloads all unused plugin modules and empties the module
131  * bank in case of success.
132  */
133 void module_EndBank (bool b_plugins)
134 {
135     module_t *head = NULL;
136
137     /* If plugins were _not_ loaded, then the caller still has the bank lock
138      * from module_InitBank(). */
139     if( b_plugins )
140         vlc_mutex_lock (&modules.lock);
141     /*else
142         vlc_assert_locked (&modules.lock); not for static mutexes :( */
143
144     assert (modules.usage > 0);
145     if (--modules.usage == 0)
146     {
147         config_UnsortConfig ();
148         head = modules.head;
149         modules.head = NULL;
150     }
151     vlc_mutex_unlock (&modules.lock);
152
153     while (head != NULL)
154     {
155         module_t *module = head;
156
157         head = module->next;
158 #ifdef HAVE_DYNAMIC_PLUGINS
159         if (module->b_loaded && module->b_unloadable)
160         {
161             module_Unload (module->handle);
162             module->b_loaded = false;
163         }
164 #endif
165         vlc_module_destroy (module);
166     }
167 }
168
169 #undef module_LoadPlugins
170 /**
171  * Loads module descriptions for all available plugins.
172  * Fills the module bank structure with the plugin modules.
173  *
174  * \param p_this vlc object structure
175  * \return total number of modules in bank after loading all plug-ins
176  */
177 size_t module_LoadPlugins (vlc_object_t *obj)
178 {
179     /*vlc_assert_locked (&modules.lock); not for static mutexes :( */
180
181     if (modules.usage == 1)
182     {
183         module_InitStaticModules ();
184 #ifdef HAVE_DYNAMIC_PLUGINS
185         msg_Dbg (obj, "searching plug-in modules");
186         AllocateAllPlugins (obj);
187 #endif
188         config_UnsortConfig ();
189         config_SortConfig ();
190     }
191     vlc_mutex_unlock (&modules.lock);
192
193     size_t count;
194     module_t **list = module_list_get (&count);
195     module_list_free (list);
196     msg_Dbg (obj, "plug-ins loaded: %zu modules", count);
197     return count;
198 }
199
200 /**
201  * Frees the flat list of VLC modules.
202  * @param list list obtained by module_list_get()
203  * @param length number of items on the list
204  * @return nothing.
205  */
206 void module_list_free (module_t **list)
207 {
208     free (list);
209 }
210
211 /**
212  * Gets the flat list of VLC modules.
213  * @param n [OUT] pointer to the number of modules
214  * @return table of module pointers (release with module_list_free()),
215  *         or NULL in case of error (in that case, *n is zeroed).
216  */
217 module_t **module_list_get (size_t *n)
218 {
219     /* TODO: this whole module lookup is quite inefficient */
220     /* Remove this and improve module_need */
221     module_t **tab = NULL;
222     size_t i = 0;
223
224     assert (n != NULL);
225
226     for (module_t *mod = modules.head; mod; mod = mod->next)
227     {
228          module_t **nt;
229          nt  = realloc (tab, (i + 1 + mod->submodule_count) * sizeof (*tab));
230          if (unlikely(nt == NULL))
231          {
232              free (tab);
233              *n = 0;
234              return NULL;
235          }
236
237          tab = nt;
238          tab[i++] = mod;
239          for (module_t *subm = mod->submodule; subm; subm = subm->next)
240              tab[i++] = subm;
241     }
242     *n = i;
243     return tab;
244 }
245
246 #ifdef HAVE_DYNAMIC_PLUGINS
247 typedef enum { CACHE_USE, CACHE_RESET, CACHE_IGNORE } cache_mode_t;
248
249 static void AllocatePluginPath (vlc_object_t *, const char *, cache_mode_t);
250
251 /**
252  * Enumerates all dynamic plug-ins that can be found.
253  *
254  * This function will recursively browse the default plug-ins directory and any
255  * directory listed in the VLC_PLUGIN_PATH environment variable.
256  * For performance reasons, a cache is normally used so that plug-in shared
257  * objects do not need to loaded and linked into the process.
258  */
259 static void AllocateAllPlugins (vlc_object_t *p_this)
260 {
261     char *paths;
262     cache_mode_t mode;
263
264     if( !var_InheritBool( p_this, "plugins-cache" ) )
265         mode = CACHE_IGNORE;
266     else if( var_InheritBool( p_this, "reset-plugins-cache" ) )
267         mode = CACHE_RESET;
268     else
269         mode = CACHE_USE;
270
271     /* Contruct the special search path for system that have a relocatable
272      * executable. Set it to <vlc path>/plugins. */
273     char *vlcpath = config_GetLibDir ();
274     if (likely(vlcpath != NULL)
275      && likely(asprintf (&paths, "%s" DIR_SEP "plugins", vlcpath) != -1))
276     {
277         AllocatePluginPath (p_this, paths, mode);
278         free( paths );
279     }
280     free (vlcpath);
281
282     /* If the user provided a plugin path, we add it to the list */
283     paths = getenv( "VLC_PLUGIN_PATH" );
284     if( paths == NULL )
285         return;
286
287     paths = strdup( paths ); /* don't harm the environment ! :) */
288     if( unlikely(paths == NULL) )
289         return;
290
291     for( char *buf, *path = strtok_r( paths, PATH_SEP, &buf );
292          path != NULL;
293          path = strtok_r( NULL, PATH_SEP, &buf ) )
294         AllocatePluginPath (p_this, path, mode);
295
296     free( paths );
297 }
298
299 typedef struct module_bank
300 {
301     vlc_object_t *obj;
302     const char   *base;
303     cache_mode_t  mode;
304
305     size_t         i_cache;
306     module_cache_t *cache;
307
308     int            i_loaded_cache;
309     module_cache_t *loaded_cache;
310 } module_bank_t;
311
312 static void AllocatePluginDir (module_bank_t *, unsigned,
313                                const char *, const char *);
314
315 /**
316  * Scans for plug-ins within a file system hierarchy.
317  * \param path base directory to browse
318  */
319 static void AllocatePluginPath (vlc_object_t *p_this, const char *path,
320                                 cache_mode_t mode)
321 {
322     module_bank_t bank;
323     module_cache_t *cache = NULL;
324     size_t count = 0;
325
326     switch( mode )
327     {
328         case CACHE_USE:
329             count = CacheLoad( p_this, path, &cache );
330             break;
331         case CACHE_RESET:
332             CacheDelete( p_this, path );
333             break;
334         case CACHE_IGNORE:
335             msg_Dbg( p_this, "ignoring plugins cache file" );
336     }
337
338     msg_Dbg( p_this, "recursively browsing `%s'", path );
339
340     bank.obj = p_this;
341     bank.base = path;
342     bank.mode = mode;
343     bank.cache = NULL;
344     bank.i_cache = 0;
345     bank.loaded_cache = cache;
346     bank.i_loaded_cache = count;
347
348     /* Don't go deeper than 5 subdirectories */
349     AllocatePluginDir (&bank, 5, path, NULL);
350
351     switch( mode )
352     {
353         case CACHE_USE:
354             /* Discard unmatched cache entries */
355             for( size_t i = 0; i < count; i++ )
356             {
357                 if (cache[i].p_module != NULL)
358                    vlc_module_destroy (cache[i].p_module);
359                 free (cache[i].path);
360             }
361             free( cache );
362         case CACHE_RESET:
363             CacheSave (p_this, path, bank.cache, bank.i_cache);
364         case CACHE_IGNORE:
365             break;
366     }
367 }
368
369 static int AllocatePluginFile (module_bank_t *, const char *,
370                                const char *, const struct stat *);
371
372 /**
373  * Recursively browses a directory to look for plug-ins.
374  */
375 static void AllocatePluginDir (module_bank_t *bank, unsigned maxdepth,
376                                const char *absdir, const char *reldir)
377 {
378     if (maxdepth == 0)
379         return;
380     maxdepth--;
381
382     DIR *dh = vlc_opendir (absdir);
383     if (dh == NULL)
384         return;
385
386     /* Parse the directory and try to load all files it contains. */
387     for (;;)
388     {
389         char *file = vlc_readdir (dh), *relpath = NULL, *abspath = NULL;
390         if (file == NULL)
391             break;
392
393         /* Skip ".", ".." */
394         if (!strcmp (file, ".") || !strcmp (file, ".."))
395             goto skip;
396
397         /* Compute path relative to plug-in base directory */
398         if (reldir != NULL)
399         {
400             if (asprintf (&relpath, "%s"DIR_SEP"%s", reldir, file) == -1)
401                 relpath = NULL;
402         }
403         else
404             relpath = strdup (file);
405         if (unlikely(relpath == NULL))
406             goto skip;
407
408         /* Compute absolute path */
409         if (asprintf (&abspath, "%s"DIR_SEP"%s", bank->base, relpath) == -1)
410         {
411             abspath = NULL;
412             goto skip;
413         }
414
415         struct stat st;
416         if (vlc_stat (abspath, &st) == -1)
417             goto skip;
418
419         if (S_ISREG (st.st_mode))
420         {
421             static const char prefix[] = "lib";
422             static const char suffix[] = "_plugin"LIBEXT;
423             size_t len = strlen (file);
424
425 #ifndef __OS2__
426             /* Check that file matches the "lib*_plugin"LIBEXT pattern */
427             if (len > strlen (suffix)
428              && !strncmp (file, prefix, strlen (prefix))
429              && !strcmp (file + len - strlen (suffix), suffix))
430 #else
431             /* We load all the files ending with LIBEXT on OS/2,
432              * because OS/2 has a 8.3 length limitation for DLL name */
433             if (len > strlen (LIBEXT)
434              && !strcasecmp (file + len - strlen (LIBEXT), LIBEXT))
435 #endif
436                 AllocatePluginFile (bank, abspath, relpath, &st);
437         }
438         else if (S_ISDIR (st.st_mode))
439             /* Recurse into another directory */
440             AllocatePluginDir (bank, maxdepth, abspath, relpath);
441     skip:
442         free (relpath);
443         free (abspath);
444         free (file);
445     }
446     closedir (dh);
447 }
448
449 static module_t *module_InitDynamic (vlc_object_t *, const char *, bool);
450
451 /**
452  * Scans a plug-in from a file.
453  */
454 static int AllocatePluginFile (module_bank_t *bank, const char *abspath,
455                                const char *relpath, const struct stat *st)
456 {
457     module_t *module = NULL;
458
459     /* Check our plugins cache first then load plugin if needed */
460     if (bank->mode == CACHE_USE)
461     {
462         module = CacheFind (bank->loaded_cache, bank->i_loaded_cache,
463                             relpath, st);
464         if (module != NULL)
465         {
466             module->psz_filename = strdup (abspath);
467             if (unlikely(module->psz_filename == NULL))
468             {
469                 vlc_module_destroy (module);
470                 module = NULL;
471             }
472         }
473     }
474     if (module == NULL)
475         module = module_InitDynamic (bank->obj, abspath, true);
476     if (module == NULL)
477         return -1;
478
479     /* We have not already scanned and inserted this module */
480     assert (module->next == NULL);
481
482     /* Unload plugin until we really need it */
483     if (module->b_loaded && module->b_unloadable)
484     {
485         module_Unload (module->handle);
486         module->b_loaded = false;
487     }
488
489     /* For now we force loading if the module's config contains callbacks.
490      * Could be optimized by adding an API call.*/
491     for (size_t n = module->confsize, i = 0; i < n; i++)
492          if (module->p_config[i].list_count == 0
493           && (module->p_config[i].list.psz_cb != NULL || module->p_config[i].list.i_cb != NULL))
494          {
495              /* !unloadable not allowed for plugins with callbacks */
496              vlc_module_destroy (module);
497              module = module_InitDynamic (bank->obj, abspath, false);
498              if (unlikely(module == NULL))
499                  return -1;
500              break;
501          }
502
503     module_StoreBank (module);
504
505     if (bank->mode != CACHE_IGNORE) /* Add entry to cache */
506         CacheAdd (&bank->cache, &bank->i_cache, relpath, st, module);
507     /* TODO: deal with errors */
508     return  0;
509 }
510
511 #ifdef __OS2__
512 #   define EXTERN_PREFIX "_"
513 #else
514 #   define EXTERN_PREFIX
515 #endif
516
517
518 /**
519  * Loads a dynamically-linked plug-in into memory and initialize it.
520  *
521  * The module can then be handled by module_need() and module_unneed().
522  *
523  * \param path file path of the shared object
524  * \param fast whether to optimize loading for speed or safety
525  *             (fast is used when the plug-in is registered but not used)
526  */
527 static module_t *module_InitDynamic (vlc_object_t *obj, const char *path,
528                                      bool fast)
529 {
530     module_handle_t handle;
531
532     if (module_Load (obj, path, &handle, fast))
533         return NULL;
534
535     /* Try to resolve the symbol */
536     static const char entry_name[] = EXTERN_PREFIX "vlc_entry" MODULE_SUFFIX;
537     vlc_plugin_cb entry =
538         (vlc_plugin_cb) module_Lookup (handle, entry_name);
539     if (entry == NULL)
540     {
541         msg_Warn (obj, "cannot find plug-in entry point in %s", path);
542         goto error;
543     }
544
545     /* We can now try to call the symbol */
546     module_t *module = vlc_plugin_describe (entry);
547     if (unlikely(module == NULL))
548     {
549         /* With a well-written module we shouldn't have to print an
550          * additional error message here, but just make sure. */
551         msg_Err (obj, "cannot initialize plug-in %s", path);
552         goto error;
553     }
554
555     module->psz_filename = strdup (path);
556     if (unlikely(module->psz_filename == NULL))
557     {
558         vlc_module_destroy (module);
559         goto error;
560     }
561     module->handle = handle;
562     module->b_loaded = true;
563     return module;
564 error:
565     module_Unload( handle );
566     return NULL;
567 }
568 #endif /* HAVE_DYNAMIC_PLUGINS */
569
570 /**
571  * Registers a statically-linked plug-in.
572  */
573 static module_t *module_InitStatic (vlc_plugin_cb entry)
574 {
575     /* Initializes the module */
576     module_t *module = vlc_plugin_describe (entry);
577     if (unlikely(module == NULL))
578         return NULL;
579
580     module->b_loaded = true;
581     module->b_unloadable = false;
582     return module;
583 }
584
585 /**
586  * Makes sure the module is loaded in memory.
587  * \return 0 on success, -1 on failure
588  */
589 int module_Map (vlc_object_t *obj, module_t *module)
590 {
591     if (module->parent != NULL)
592         module = module->parent;
593
594 #warning FIXME: race condition!
595     if (module->b_loaded)
596         return 0;
597     assert (module->psz_filename != NULL);
598
599 #ifdef HAVE_DYNAMIC_PLUGINS
600     module_t *uncache = module_InitDynamic (obj, module->psz_filename, false);
601     if (uncache != NULL)
602     {
603         CacheMerge (obj, module, uncache);
604         vlc_module_destroy (uncache);
605         return 0;
606     }
607 #endif
608     msg_Err (obj, "corrupt module: %s", module->psz_filename);
609     return -1;
610 }