1 /* GMODULE - GLIB wrapper code for dynamic module loading
2 * Copyright (C) 1998 Tim Janik
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
21 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
22 * file for a list of people on the GLib Team. See the ChangeLog
23 * files for a list of changes. These files are distributed with
24 * GLib at ftp://ftp.gtk.org/pub/gtk/.
38 #include <sys/types.h>
45 #include <io.h> /* For open() and close() prototypes. */
48 #include "gmoduleconf.h"
53 * @title: Dynamic Loading of Modules
54 * @short_description: portable method for dynamically loading 'plug-ins'
56 * These functions provide a portable way to dynamically load object files
57 * (commonly known as 'plug-ins'). The current implementation supports all
58 * systems that provide an implementation of dlopen() (e.g. Linux/Sun), as
59 * well as Windows platforms via DLLs.
61 * A program which wants to use these functions must be linked to the
62 * libraries output by the command
63 * <command>pkg-config --libs gmodule-2.0</command>.
65 * To use them you must first determine whether dynamic loading
66 * is supported on the platform by calling g_module_supported().
67 * If it is, you can open a module with g_module_open(),
68 * find the module's symbols (e.g. function names) with g_module_symbol(),
69 * and later close the module with g_module_close().
70 * g_module_name() will return the file name of a currently opened module.
72 * If any of the above functions fail, the error status can be found with
75 * The #GModule implementation features reference counting for opened modules,
76 * and supports hook functions within a module which are called when the
77 * module is loaded and unloaded (see #GModuleCheckInit and #GModuleUnload).
79 * If your module introduces static data to common subsystems in the running
80 * program, e.g. through calling
81 * <literal>g_quark_from_static_string ("my-module-stuff")</literal>,
82 * it must ensure that it is never unloaded, by calling g_module_make_resident().
85 * <title>Calling a function defined in a GModule</title>
87 * /* the function signature for 'say_hello' */
88 * typedef void (* SayHelloFunc) (const char *message);
91 * just_say_hello (const char *filename, GError **error)
93 * SayHelloFunc say_hello;
96 * module = g_module_open (filename, G_MODULE_BIND_LAZY);
99 * g_set_error (error, FOO_ERROR, FOO_ERROR_BLAH,
100 * "%s", g_module_error ());
104 * if (!g_module_symbol (module, "say_hello", (gpointer *)&say_hello))
106 * g_set_error (error, SAY_ERROR, SAY_ERROR_OPEN,
107 * "%s: %s", filename, g_module_error ());
108 * if (!g_module_close (module))
109 * g_warning ("%s: %s", filename, g_module_error ());
113 * if (say_hello == NULL)
115 * g_set_error (error, SAY_ERROR, SAY_ERROR_OPEN,
116 * "symbol say_hello is NULL");
117 * if (!g_module_close (module))
118 * g_warning ("%s: %s", filename, g_module_error ());
122 * /* call our function in the module */
123 * say_hello ("Hello world!");
125 * if (!g_module_close (module))
126 * g_warning ("%s: %s", filename, g_module_error ());
136 * The #GModule struct is an opaque data structure to represent a
137 * <link linkend="glib-Dynamic-Loading-of-Modules">Dynamically-Loaded
138 * Module</link>. It should only be accessed via the following functions.
143 * @module: the #GModule corresponding to the module which has just been loaded
145 * Specifies the type of the module initialization function.
146 * <indexterm zone="g-module-check-init"><primary>g_module_check_init</primary></indexterm>
147 * If a module contains a function named g_module_check_init() it is called
148 * automatically when the module is loaded. It is passed the #GModule structure
149 * and should return %NULL on success or a string describing the initialization
152 * Returns: %NULL on success, or a string describing the initialization error
157 * @module: the #GModule about to be unloaded
159 * <indexterm zone="g-module-unload"><primary>g_module_unload</primary></indexterm>
160 * Specifies the type of the module function called when it is unloaded.
161 * If a module contains a function named g_module_unload() it is called
162 * automatically when the module is unloaded.
163 * It is passed the #GModule structure.
169 * Expands to the proper shared library suffix for the current platform
170 * without the leading dot. For most Unices and Linux this is "so", and
171 * for Windows this is "dll".
177 * Used to declare functions exported by modules. This is a no-op on Linux
178 * and Unices, but when compiling for Windows, it marks a symbol to be
179 * exported from the library or executable being built.
185 * Used to declare functions imported from modules.
188 /* We maintain a list of modules, so we can reference count them.
189 * That's needed because some platforms don't support references counts on
190 * modules. Also, the module for the program itself is kept seperately for
191 * faster access and because it has special semantics.
195 /* --- structures --- */
199 #if defined (G_OS_WIN32) && !defined(_WIN64)
203 guint ref_count : 31;
204 guint is_resident : 1;
205 GModuleUnload unload;
210 /* --- prototypes --- */
211 static gpointer _g_module_open (const gchar *file_name,
213 gboolean bind_local);
214 static void _g_module_close (gpointer handle,
216 static gpointer _g_module_self (void);
217 static gpointer _g_module_symbol (gpointer handle,
218 const gchar *symbol_name);
219 static gchar* _g_module_build_path (const gchar *directory,
220 const gchar *module_name);
221 static inline void g_module_set_error (const gchar *error);
222 static inline GModule* g_module_find_by_handle (gpointer handle);
223 static inline GModule* g_module_find_by_name (const gchar *name);
226 /* --- variables --- */
227 static GModule *modules = NULL;
228 static GModule *main_module = NULL;
229 static GPrivate module_error_private = G_PRIVATE_INIT (g_free);
230 static gboolean module_debug_initialized = FALSE;
231 static guint module_debug_flags = 0;
234 /* --- inline functions --- */
235 static inline GModule*
236 g_module_find_by_handle (gpointer handle)
239 GModule *retval = NULL;
241 if (main_module && main_module->handle == handle)
242 retval = main_module;
244 for (module = modules; module; module = module->next)
245 if (handle == module->handle)
254 static inline GModule*
255 g_module_find_by_name (const gchar *name)
258 GModule *retval = NULL;
260 for (module = modules; module; module = module->next)
261 if (strcmp (name, module->file_name) == 0)
271 g_module_set_error_unduped (gchar *error)
273 g_private_replace (&module_error_private, error);
278 g_module_set_error (const gchar *error)
280 g_module_set_error_unduped (g_strdup (error));
284 /* --- include platform specifc code --- */
285 #define SUPPORT_OR_RETURN(rv) { g_module_set_error (NULL); }
286 #if (G_MODULE_IMPL == G_MODULE_IMPL_DL)
287 #include "gmodule-dl.c"
288 #elif (G_MODULE_IMPL == G_MODULE_IMPL_WIN32)
289 #include "gmodule-win32.c"
290 #elif (G_MODULE_IMPL == G_MODULE_IMPL_DYLD)
291 #include "gmodule-dyld.c"
292 #elif (G_MODULE_IMPL == G_MODULE_IMPL_AR)
293 #include "gmodule-ar.c"
295 #undef SUPPORT_OR_RETURN
296 #define SUPPORT_OR_RETURN(rv) { g_module_set_error ("dynamic modules are " \
297 "not supported by this system"); return rv; }
299 _g_module_open (const gchar *file_name,
306 _g_module_close (gpointer handle,
311 _g_module_self (void)
316 _g_module_symbol (gpointer handle,
317 const gchar *symbol_name)
322 _g_module_build_path (const gchar *directory,
323 const gchar *module_name)
327 #endif /* no implementation */
329 /* --- functions --- */
332 * g_module_supported:
334 * Checks if modules are supported on the current platform.
336 * Returns: %TRUE if modules are supported
339 g_module_supported (void)
341 SUPPORT_OR_RETURN (FALSE);
347 parse_libtool_archive (const gchar* libtool_name)
349 const guint TOKEN_DLNAME = G_TOKEN_LAST + 1;
350 const guint TOKEN_INSTALLED = G_TOKEN_LAST + 2;
351 const guint TOKEN_LIBDIR = G_TOKEN_LAST + 3;
352 gchar *lt_dlname = NULL;
353 gboolean lt_installed = TRUE;
354 gchar *lt_libdir = NULL;
359 int fd = g_open (libtool_name, O_RDONLY, 0);
362 gchar *display_libtool_name = g_filename_display_name (libtool_name);
363 g_module_set_error_unduped (g_strdup_printf ("failed to open libtool archive \"%s\"", display_libtool_name));
364 g_free (display_libtool_name);
367 /* search libtool's dlname specification */
368 scanner = g_scanner_new (NULL);
369 g_scanner_input_file (scanner, fd);
370 scanner->config->symbol_2_token = TRUE;
371 g_scanner_scope_add_symbol (scanner, 0, "dlname",
372 GUINT_TO_POINTER (TOKEN_DLNAME));
373 g_scanner_scope_add_symbol (scanner, 0, "installed",
374 GUINT_TO_POINTER (TOKEN_INSTALLED));
375 g_scanner_scope_add_symbol (scanner, 0, "libdir",
376 GUINT_TO_POINTER (TOKEN_LIBDIR));
377 while (!g_scanner_eof (scanner))
379 token = g_scanner_get_next_token (scanner);
380 if (token == TOKEN_DLNAME || token == TOKEN_INSTALLED ||
381 token == TOKEN_LIBDIR)
383 if (g_scanner_get_next_token (scanner) != '=' ||
384 g_scanner_get_next_token (scanner) !=
385 (token == TOKEN_INSTALLED ?
386 G_TOKEN_IDENTIFIER : G_TOKEN_STRING))
388 gchar *display_libtool_name = g_filename_display_name (libtool_name);
389 g_module_set_error_unduped (g_strdup_printf ("unable to parse libtool archive \"%s\"", display_libtool_name));
390 g_free (display_libtool_name);
394 g_scanner_destroy (scanner);
401 if (token == TOKEN_DLNAME)
404 lt_dlname = g_strdup (scanner->value.v_string);
406 else if (token == TOKEN_INSTALLED)
408 strcmp (scanner->value.v_identifier, "yes") == 0;
409 else /* token == TOKEN_LIBDIR */
412 lt_libdir = g_strdup (scanner->value.v_string);
420 gchar *dir = g_path_get_dirname (libtool_name);
422 lt_libdir = g_strconcat (dir, G_DIR_SEPARATOR_S ".libs", NULL);
426 name = g_strconcat (lt_libdir, G_DIR_SEPARATOR_S, lt_dlname, NULL);
430 g_scanner_destroy (scanner);
436 static inline gboolean
437 str_check_suffix (const gchar* string,
440 gsize string_len = strlen (string);
441 gsize suffix_len = strlen (suffix);
443 return string_len >= suffix_len &&
444 strcmp (string + string_len - suffix_len, suffix) == 0;
449 G_MODULE_DEBUG_RESIDENT_MODULES = 1 << 0,
450 G_MODULE_DEBUG_BIND_NOW_MODULES = 1 << 1
454 _g_module_debug_init (void)
456 const GDebugKey keys[] = {
457 { "resident-modules", G_MODULE_DEBUG_RESIDENT_MODULES },
458 { "bind-now-modules", G_MODULE_DEBUG_BIND_NOW_MODULES }
462 env = g_getenv ("G_DEBUG");
465 !env ? 0 : g_parse_debug_string (env, keys, G_N_ELEMENTS (keys));
467 module_debug_initialized = TRUE;
470 static GRecMutex g_module_global_lock;
473 g_module_open (const gchar *file_name,
477 gpointer handle = NULL;
480 SUPPORT_OR_RETURN (NULL);
482 g_rec_mutex_lock (&g_module_global_lock);
484 if (G_UNLIKELY (!module_debug_initialized))
485 _g_module_debug_init ();
487 if (module_debug_flags & G_MODULE_DEBUG_BIND_NOW_MODULES)
488 flags &= ~G_MODULE_BIND_LAZY;
494 handle = _g_module_self ();
497 main_module = g_new (GModule, 1);
498 main_module->file_name = NULL;
499 #if defined (G_OS_WIN32) && !defined(_WIN64)
500 main_module->cp_file_name = NULL;
502 main_module->handle = handle;
503 main_module->ref_count = 1;
504 main_module->is_resident = TRUE;
505 main_module->unload = NULL;
506 main_module->next = NULL;
510 main_module->ref_count++;
512 g_rec_mutex_unlock (&g_module_global_lock);
516 /* we first search the module list by name */
517 module = g_module_find_by_name (file_name);
522 g_rec_mutex_unlock (&g_module_global_lock);
526 /* check whether we have a readable file right away */
527 if (g_file_test (file_name, G_FILE_TEST_IS_REGULAR))
528 name = g_strdup (file_name);
529 /* try completing file name with standard library suffix */
532 name = g_strconcat (file_name, "." G_MODULE_SUFFIX, NULL);
533 if (!g_file_test (name, G_FILE_TEST_IS_REGULAR))
539 /* try completing by appending libtool suffix */
542 name = g_strconcat (file_name, ".la", NULL);
543 if (!g_file_test (name, G_FILE_TEST_IS_REGULAR))
549 /* we can't access() the file, lets hope the platform backends finds
550 * it via library paths
554 gchar *dot = strrchr (file_name, '.');
555 gchar *slash = strrchr (file_name, G_DIR_SEPARATOR);
557 /* make sure the name has a suffix */
558 if (!dot || dot < slash)
559 name = g_strconcat (file_name, "." G_MODULE_SUFFIX, NULL);
561 name = g_strdup (file_name);
564 /* ok, try loading the module */
567 /* if it's a libtool archive, figure library file to load */
568 if (str_check_suffix (name, ".la")) /* libtool archive? */
570 gchar *real_name = parse_libtool_archive (name);
572 /* real_name might be NULL, but then module error is already set */
580 handle = _g_module_open (name, (flags & G_MODULE_BIND_LAZY) != 0,
581 (flags & G_MODULE_BIND_LOCAL) != 0);
585 gchar *display_file_name = g_filename_display_name (file_name);
586 g_module_set_error_unduped (g_strdup_printf ("unable to access file \"%s\"", display_file_name));
587 g_free (display_file_name);
594 GModuleCheckInit check_init;
595 const gchar *check_failed = NULL;
597 /* search the module list by handle, since file names are not unique */
598 module = g_module_find_by_handle (handle);
601 _g_module_close (module->handle, TRUE);
603 g_module_set_error (NULL);
605 g_rec_mutex_unlock (&g_module_global_lock);
609 saved_error = g_strdup (g_module_error ());
610 g_module_set_error (NULL);
612 module = g_new (GModule, 1);
613 module->file_name = g_strdup (file_name);
614 #if defined (G_OS_WIN32) && !defined(_WIN64)
615 module->cp_file_name = g_locale_from_utf8 (file_name, -1,
618 module->handle = handle;
619 module->ref_count = 1;
620 module->is_resident = FALSE;
621 module->unload = NULL;
622 module->next = modules;
625 /* check initialization */
626 if (g_module_symbol (module, "g_module_check_init", (gpointer) &check_init) && check_init != NULL)
627 check_failed = check_init (module);
629 /* we don't call unload() if the initialization check failed. */
631 g_module_symbol (module, "g_module_unload", (gpointer) &module->unload);
637 error = g_strconcat ("GModule (", file_name, ") ",
638 "initialization check failed: ",
640 g_module_close (module);
642 g_module_set_error (error);
646 g_module_set_error (saved_error);
648 g_free (saved_error);
651 if (module != NULL &&
652 (module_debug_flags & G_MODULE_DEBUG_RESIDENT_MODULES))
653 g_module_make_resident (module);
655 g_rec_mutex_unlock (&g_module_global_lock);
659 #if defined (G_OS_WIN32) && !defined(_WIN64)
665 * @G_MODULE_BIND_LAZY: specifies that symbols are only resolved when
666 * needed. The default action is to bind all symbols when the module
668 * @G_MODULE_BIND_LOCAL: specifies that symbols in the module should
669 * not be added to the global name space. The default action on most
670 * platforms is to place symbols in the module in the global name space,
671 * which may cause conflicts with existing symbols.
672 * @G_MODULE_BIND_MASK: mask for all flags.
674 * Flags passed to g_module_open().
675 * Note that these flags are not supported on all platforms.
680 * @file_name: (allow-none): the name of the file containing the module, or %NULL
681 * to obtain a #GModule representing the main program itself
682 * @flags: the flags used for opening the module. This can be the
683 * logical OR of any of the #GModuleFlags
685 * Opens a module. If the module has already been opened,
686 * its reference count is incremented.
688 * First of all g_module_open() tries to open @file_name as a module.
689 * If that fails and @file_name has the ".la"-suffix (and is a libtool
690 * archive) it tries to open the corresponding module. If that fails
691 * and it doesn't have the proper module suffix for the platform
692 * (#G_MODULE_SUFFIX), this suffix will be appended and the corresponding
693 * module will be opended. If that fails and @file_name doesn't have the
694 * ".la"-suffix, this suffix is appended and g_module_open() tries to open
695 * the corresponding module. If eventually that fails as well, %NULL is
698 * Returns: a #GModule on success, or %NULL on failure
701 g_module_open (const gchar *file_name,
704 gchar *utf8_file_name = g_locale_to_utf8 (file_name, -1, NULL, NULL, NULL);
705 GModule *retval = g_module_open_utf8 (utf8_file_name, flags);
707 g_free (utf8_file_name);
716 * @module: a #GModule to close
720 * Returns: %TRUE on success
723 g_module_close (GModule *module)
725 SUPPORT_OR_RETURN (FALSE);
727 g_return_val_if_fail (module != NULL, FALSE);
728 g_return_val_if_fail (module->ref_count > 0, FALSE);
730 g_rec_mutex_lock (&g_module_global_lock);
734 if (!module->ref_count && !module->is_resident && module->unload)
736 GModuleUnload unload;
738 unload = module->unload;
739 module->unload = NULL;
743 if (!module->ref_count && !module->is_resident)
756 last->next = node->next;
758 modules = node->next;
766 _g_module_close (module->handle, FALSE);
767 g_free (module->file_name);
768 #if defined (G_OS_WIN32) && !defined(_WIN64)
769 g_free (module->cp_file_name);
774 g_rec_mutex_unlock (&g_module_global_lock);
775 return g_module_error() == NULL;
779 * g_module_make_resident:
780 * @module: a #GModule to make permanently resident
782 * Ensures that a module will never be unloaded.
783 * Any future g_module_close() calls on the module will be ignored.
786 g_module_make_resident (GModule *module)
788 g_return_if_fail (module != NULL);
790 module->is_resident = TRUE;
796 * Gets a string describing the last module error.
798 * Returns: a string describing the last module error
801 g_module_error (void)
803 return g_private_get (&module_error_private);
808 * @module: a #GModule
809 * @symbol_name: the name of the symbol to find
810 * @symbol: (out): returns the pointer to the symbol value
812 * Gets a symbol pointer from a module, such as one exported
813 * by #G_MODULE_EXPORT. Note that a valid symbol can be %NULL.
815 * Returns: %TRUE on success
818 g_module_symbol (GModule *module,
819 const gchar *symbol_name,
822 const gchar *module_error;
826 SUPPORT_OR_RETURN (FALSE);
828 g_return_val_if_fail (module != NULL, FALSE);
829 g_return_val_if_fail (symbol_name != NULL, FALSE);
830 g_return_val_if_fail (symbol != NULL, FALSE);
832 g_rec_mutex_lock (&g_module_global_lock);
834 #ifdef G_MODULE_NEED_USCORE
838 name = g_strconcat ("_", symbol_name, NULL);
839 *symbol = _g_module_symbol (module->handle, name);
842 #else /* !G_MODULE_NEED_USCORE */
843 *symbol = _g_module_symbol (module->handle, symbol_name);
844 #endif /* !G_MODULE_NEED_USCORE */
846 module_error = g_module_error ();
851 error = g_strconcat ("'", symbol_name, "': ", module_error, NULL);
852 g_module_set_error (error);
857 g_rec_mutex_unlock (&g_module_global_lock);
858 return !module_error;
863 * @module: a #GModule
865 * Returns the filename that the module was opened with.
867 * If @module refers to the application itself, "main" is returned.
869 * Returns: (transfer none): the filename of the module
872 g_module_name (GModule *module)
874 g_return_val_if_fail (module != NULL, NULL);
876 if (module == main_module)
879 return module->file_name;
882 #if defined (G_OS_WIN32) && !defined(_WIN64)
887 g_module_name (GModule *module)
889 g_return_val_if_fail (module != NULL, NULL);
891 if (module == main_module)
894 return module->cp_file_name;
900 * g_module_build_path:
901 * @directory: (allow-none): the directory where the module is. This can be %NULL
902 * or the empty string to indicate that the standard platform-specific
903 * directories will be used, though that is not recommended
904 * @module_name: the name of the module
906 * A portable way to build the filename of a module. The platform-specific
907 * prefix and suffix are added to the filename, if needed, and the result
908 * is added to the directory, using the correct separator character.
910 * The directory should specify the directory where the module can be found.
911 * It can be %NULL or an empty string to indicate that the module is in a
912 * standard platform-specific directory, though this is not recommended
913 * since the wrong module may be found.
915 * For example, calling g_module_build_path() on a Linux system with a
916 * @directory of <filename>/lib</filename> and a @module_name of "mylibrary"
917 * will return <filename>/lib/libmylibrary.so</filename>. On a Windows system,
918 * using <filename>\Windows</filename> as the directory it will return
919 * <filename>\Windows\mylibrary.dll</filename>.
921 * Returns: the complete path of the module, including the standard library
922 * prefix and suffix. This should be freed when no longer needed
925 g_module_build_path (const gchar *directory,
926 const gchar *module_name)
928 g_return_val_if_fail (module_name != NULL, NULL);
930 return _g_module_build_path (directory, module_name);