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