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