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, see <http://www.gnu.org/licenses/>.
19 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
20 * file for a list of people on the GLib Team. See the ChangeLog
21 * files for a list of changes. These files are distributed with
22 * GLib at ftp://ftp.gtk.org/pub/gtk/.
36 #include <sys/types.h>
43 #include <io.h> /* For open() and close() prototypes. */
46 #include "gmoduleconf.h"
51 * @title: Dynamic Loading of Modules
52 * @short_description: portable method for dynamically loading 'plug-ins'
54 * These functions provide a portable way to dynamically load object files
55 * (commonly known as 'plug-ins'). The current implementation supports all
56 * systems that provide an implementation of dlopen() (e.g. Linux/Sun), as
57 * well as Windows platforms via DLLs.
59 * A program which wants to use these functions must be linked to the
60 * libraries output by the command
61 * <command>pkg-config --libs gmodule-2.0</command>.
63 * To use them you must first determine whether dynamic loading
64 * is supported on the platform by calling g_module_supported().
65 * If it is, you can open a module with g_module_open(),
66 * find the module's symbols (e.g. function names) with g_module_symbol(),
67 * and later close the module with g_module_close().
68 * g_module_name() will return the file name of a currently opened module.
70 * If any of the above functions fail, the error status can be found with
73 * The #GModule implementation features reference counting for opened modules,
74 * and supports hook functions within a module which are called when the
75 * module is loaded and unloaded (see #GModuleCheckInit and #GModuleUnload).
77 * If your module introduces static data to common subsystems in the running
78 * program, e.g. through calling
79 * <literal>g_quark_from_static_string ("my-module-stuff")</literal>,
80 * it must ensure that it is never unloaded, by calling g_module_make_resident().
82 * Example: Calling a function defined in a GModule
83 * |[<!-- language="C" -->
84 * /* the function signature for 'say_hello' */
85 * typedef void (* SayHelloFunc) (const char *message);
88 * just_say_hello (const char *filename, GError **error)
90 * SayHelloFunc say_hello;
93 * module = g_module_open (filename, G_MODULE_BIND_LAZY);
96 * g_set_error (error, FOO_ERROR, FOO_ERROR_BLAH,
97 * "%s", g_module_error ());
101 * if (!g_module_symbol (module, "say_hello", (gpointer *)&say_hello))
103 * g_set_error (error, SAY_ERROR, SAY_ERROR_OPEN,
104 * "%s: %s", filename, g_module_error ());
105 * if (!g_module_close (module))
106 * g_warning ("%s: %s", filename, g_module_error ());
110 * if (say_hello == NULL)
112 * g_set_error (error, SAY_ERROR, SAY_ERROR_OPEN,
113 * "symbol say_hello is NULL");
114 * if (!g_module_close (module))
115 * g_warning ("%s: %s", filename, g_module_error ());
119 * /* call our function in the module */
120 * say_hello ("Hello world!");
122 * if (!g_module_close (module))
123 * g_warning ("%s: %s", filename, g_module_error ());
132 * The #GModule struct is an opaque data structure to represent a
133 * <link linkend="glib-Dynamic-Loading-of-Modules">Dynamically-Loaded
134 * Module</link>. It should only be accessed via the following functions.
139 * @module: the #GModule corresponding to the module which has just been loaded
141 * Specifies the type of the module initialization function.
142 * If a module contains a function named g_module_check_init() it is called
143 * automatically when the module is loaded. It is passed the #GModule structure
144 * and should return %NULL on success or a string describing the initialization
147 * Returns: %NULL on success, or a string describing the initialization error
152 * @module: the #GModule about to be unloaded
154 * Specifies the type of the module function called when it is unloaded.
155 * If a module contains a function named g_module_unload() it is called
156 * automatically when the module is unloaded.
157 * It is passed the #GModule structure.
163 * Expands to the proper shared library suffix for the current platform
164 * without the leading dot. For most Unices and Linux this is "so", and
165 * for Windows this is "dll".
171 * Used to declare functions exported by modules. This is a no-op on Linux
172 * and Unices, but when compiling for Windows, it marks a symbol to be
173 * exported from the library or executable being built.
179 * Used to declare functions imported from modules.
182 /* We maintain a list of modules, so we can reference count them.
183 * That's needed because some platforms don't support references counts on
184 * modules. Also, the module for the program itself is kept seperately for
185 * faster access and because it has special semantics.
189 /* --- structures --- */
193 #if defined (G_OS_WIN32) && !defined(_WIN64)
197 guint ref_count : 31;
198 guint is_resident : 1;
199 GModuleUnload unload;
204 /* --- prototypes --- */
205 static gpointer _g_module_open (const gchar *file_name,
207 gboolean bind_local);
208 static void _g_module_close (gpointer handle,
210 static gpointer _g_module_self (void);
211 static gpointer _g_module_symbol (gpointer handle,
212 const gchar *symbol_name);
213 static gchar* _g_module_build_path (const gchar *directory,
214 const gchar *module_name);
215 static inline void g_module_set_error (const gchar *error);
216 static inline GModule* g_module_find_by_handle (gpointer handle);
217 static inline GModule* g_module_find_by_name (const gchar *name);
220 /* --- variables --- */
221 static GModule *modules = NULL;
222 static GModule *main_module = NULL;
223 static GPrivate module_error_private = G_PRIVATE_INIT (g_free);
224 static gboolean module_debug_initialized = FALSE;
225 static guint module_debug_flags = 0;
228 /* --- inline functions --- */
229 static inline GModule*
230 g_module_find_by_handle (gpointer handle)
233 GModule *retval = NULL;
235 if (main_module && main_module->handle == handle)
236 retval = main_module;
238 for (module = modules; module; module = module->next)
239 if (handle == module->handle)
248 static inline GModule*
249 g_module_find_by_name (const gchar *name)
252 GModule *retval = NULL;
254 for (module = modules; module; module = module->next)
255 if (strcmp (name, module->file_name) == 0)
265 g_module_set_error_unduped (gchar *error)
267 g_private_replace (&module_error_private, error);
272 g_module_set_error (const gchar *error)
274 g_module_set_error_unduped (g_strdup (error));
278 /* --- include platform specifc code --- */
279 #define SUPPORT_OR_RETURN(rv) { g_module_set_error (NULL); }
280 #if (G_MODULE_IMPL == G_MODULE_IMPL_DL)
281 #include "gmodule-dl.c"
282 #elif (G_MODULE_IMPL == G_MODULE_IMPL_WIN32)
283 #include "gmodule-win32.c"
284 #elif (G_MODULE_IMPL == G_MODULE_IMPL_DYLD)
285 #include "gmodule-dyld.c"
286 #elif (G_MODULE_IMPL == G_MODULE_IMPL_AR)
287 #include "gmodule-ar.c"
289 #undef SUPPORT_OR_RETURN
290 #define SUPPORT_OR_RETURN(rv) { g_module_set_error ("dynamic modules are " \
291 "not supported by this system"); return rv; }
293 _g_module_open (const gchar *file_name,
300 _g_module_close (gpointer handle,
305 _g_module_self (void)
310 _g_module_symbol (gpointer handle,
311 const gchar *symbol_name)
316 _g_module_build_path (const gchar *directory,
317 const gchar *module_name)
321 #endif /* no implementation */
323 /* --- functions --- */
326 * g_module_supported:
328 * Checks if modules are supported on the current platform.
330 * Returns: %TRUE if modules are supported
333 g_module_supported (void)
335 SUPPORT_OR_RETURN (FALSE);
341 parse_libtool_archive (const gchar* libtool_name)
343 const guint TOKEN_DLNAME = G_TOKEN_LAST + 1;
344 const guint TOKEN_INSTALLED = G_TOKEN_LAST + 2;
345 const guint TOKEN_LIBDIR = G_TOKEN_LAST + 3;
346 gchar *lt_dlname = NULL;
347 gboolean lt_installed = TRUE;
348 gchar *lt_libdir = NULL;
353 int fd = g_open (libtool_name, O_RDONLY, 0);
356 gchar *display_libtool_name = g_filename_display_name (libtool_name);
357 g_module_set_error_unduped (g_strdup_printf ("failed to open libtool archive \"%s\"", display_libtool_name));
358 g_free (display_libtool_name);
361 /* search libtool's dlname specification */
362 scanner = g_scanner_new (NULL);
363 g_scanner_input_file (scanner, fd);
364 scanner->config->symbol_2_token = TRUE;
365 g_scanner_scope_add_symbol (scanner, 0, "dlname",
366 GUINT_TO_POINTER (TOKEN_DLNAME));
367 g_scanner_scope_add_symbol (scanner, 0, "installed",
368 GUINT_TO_POINTER (TOKEN_INSTALLED));
369 g_scanner_scope_add_symbol (scanner, 0, "libdir",
370 GUINT_TO_POINTER (TOKEN_LIBDIR));
371 while (!g_scanner_eof (scanner))
373 token = g_scanner_get_next_token (scanner);
374 if (token == TOKEN_DLNAME || token == TOKEN_INSTALLED ||
375 token == TOKEN_LIBDIR)
377 if (g_scanner_get_next_token (scanner) != '=' ||
378 g_scanner_get_next_token (scanner) !=
379 (token == TOKEN_INSTALLED ?
380 G_TOKEN_IDENTIFIER : G_TOKEN_STRING))
382 gchar *display_libtool_name = g_filename_display_name (libtool_name);
383 g_module_set_error_unduped (g_strdup_printf ("unable to parse libtool archive \"%s\"", display_libtool_name));
384 g_free (display_libtool_name);
388 g_scanner_destroy (scanner);
395 if (token == TOKEN_DLNAME)
398 lt_dlname = g_strdup (scanner->value.v_string);
400 else if (token == TOKEN_INSTALLED)
402 strcmp (scanner->value.v_identifier, "yes") == 0;
403 else /* token == TOKEN_LIBDIR */
406 lt_libdir = g_strdup (scanner->value.v_string);
414 gchar *dir = g_path_get_dirname (libtool_name);
416 lt_libdir = g_strconcat (dir, G_DIR_SEPARATOR_S ".libs", NULL);
420 name = g_strconcat (lt_libdir, G_DIR_SEPARATOR_S, lt_dlname, NULL);
424 g_scanner_destroy (scanner);
430 static inline gboolean
431 str_check_suffix (const gchar* string,
434 gsize string_len = strlen (string);
435 gsize suffix_len = strlen (suffix);
437 return string_len >= suffix_len &&
438 strcmp (string + string_len - suffix_len, suffix) == 0;
443 G_MODULE_DEBUG_RESIDENT_MODULES = 1 << 0,
444 G_MODULE_DEBUG_BIND_NOW_MODULES = 1 << 1
448 _g_module_debug_init (void)
450 const GDebugKey keys[] = {
451 { "resident-modules", G_MODULE_DEBUG_RESIDENT_MODULES },
452 { "bind-now-modules", G_MODULE_DEBUG_BIND_NOW_MODULES }
456 env = g_getenv ("G_DEBUG");
459 !env ? 0 : g_parse_debug_string (env, keys, G_N_ELEMENTS (keys));
461 module_debug_initialized = TRUE;
464 static GRecMutex g_module_global_lock;
467 g_module_open (const gchar *file_name,
471 gpointer handle = NULL;
474 SUPPORT_OR_RETURN (NULL);
476 g_rec_mutex_lock (&g_module_global_lock);
478 if (G_UNLIKELY (!module_debug_initialized))
479 _g_module_debug_init ();
481 if (module_debug_flags & G_MODULE_DEBUG_BIND_NOW_MODULES)
482 flags &= ~G_MODULE_BIND_LAZY;
488 handle = _g_module_self ();
491 main_module = g_new (GModule, 1);
492 main_module->file_name = NULL;
493 #if defined (G_OS_WIN32) && !defined(_WIN64)
494 main_module->cp_file_name = NULL;
496 main_module->handle = handle;
497 main_module->ref_count = 1;
498 main_module->is_resident = TRUE;
499 main_module->unload = NULL;
500 main_module->next = NULL;
504 main_module->ref_count++;
506 g_rec_mutex_unlock (&g_module_global_lock);
510 /* we first search the module list by name */
511 module = g_module_find_by_name (file_name);
516 g_rec_mutex_unlock (&g_module_global_lock);
520 /* check whether we have a readable file right away */
521 if (g_file_test (file_name, G_FILE_TEST_IS_REGULAR))
522 name = g_strdup (file_name);
523 /* try completing file name with standard library suffix */
526 name = g_strconcat (file_name, "." G_MODULE_SUFFIX, NULL);
527 if (!g_file_test (name, G_FILE_TEST_IS_REGULAR))
533 /* try completing by appending libtool suffix */
536 name = g_strconcat (file_name, ".la", NULL);
537 if (!g_file_test (name, G_FILE_TEST_IS_REGULAR))
543 /* we can't access() the file, lets hope the platform backends finds
544 * it via library paths
548 gchar *dot = strrchr (file_name, '.');
549 gchar *slash = strrchr (file_name, G_DIR_SEPARATOR);
551 /* make sure the name has a suffix */
552 if (!dot || dot < slash)
553 name = g_strconcat (file_name, "." G_MODULE_SUFFIX, NULL);
555 name = g_strdup (file_name);
558 /* ok, try loading the module */
561 /* if it's a libtool archive, figure library file to load */
562 if (str_check_suffix (name, ".la")) /* libtool archive? */
564 gchar *real_name = parse_libtool_archive (name);
566 /* real_name might be NULL, but then module error is already set */
574 handle = _g_module_open (name, (flags & G_MODULE_BIND_LAZY) != 0,
575 (flags & G_MODULE_BIND_LOCAL) != 0);
579 gchar *display_file_name = g_filename_display_name (file_name);
580 g_module_set_error_unduped (g_strdup_printf ("unable to access file \"%s\"", display_file_name));
581 g_free (display_file_name);
588 GModuleCheckInit check_init;
589 const gchar *check_failed = NULL;
591 /* search the module list by handle, since file names are not unique */
592 module = g_module_find_by_handle (handle);
595 _g_module_close (module->handle, TRUE);
597 g_module_set_error (NULL);
599 g_rec_mutex_unlock (&g_module_global_lock);
603 saved_error = g_strdup (g_module_error ());
604 g_module_set_error (NULL);
606 module = g_new (GModule, 1);
607 module->file_name = g_strdup (file_name);
608 #if defined (G_OS_WIN32) && !defined(_WIN64)
609 module->cp_file_name = g_locale_from_utf8 (file_name, -1,
612 module->handle = handle;
613 module->ref_count = 1;
614 module->is_resident = FALSE;
615 module->unload = NULL;
616 module->next = modules;
619 /* check initialization */
620 if (g_module_symbol (module, "g_module_check_init", (gpointer) &check_init) && check_init != NULL)
621 check_failed = check_init (module);
623 /* we don't call unload() if the initialization check failed. */
625 g_module_symbol (module, "g_module_unload", (gpointer) &module->unload);
631 error = g_strconcat ("GModule (", file_name, ") ",
632 "initialization check failed: ",
634 g_module_close (module);
636 g_module_set_error (error);
640 g_module_set_error (saved_error);
642 g_free (saved_error);
645 if (module != NULL &&
646 (module_debug_flags & G_MODULE_DEBUG_RESIDENT_MODULES))
647 g_module_make_resident (module);
649 g_rec_mutex_unlock (&g_module_global_lock);
653 #if defined (G_OS_WIN32) && !defined(_WIN64)
659 * @G_MODULE_BIND_LAZY: specifies that symbols are only resolved when
660 * needed. The default action is to bind all symbols when the module
662 * @G_MODULE_BIND_LOCAL: specifies that symbols in the module should
663 * not be added to the global name space. The default action on most
664 * platforms is to place symbols in the module in the global name space,
665 * which may cause conflicts with existing symbols.
666 * @G_MODULE_BIND_MASK: mask for all flags.
668 * Flags passed to g_module_open().
669 * Note that these flags are not supported on all platforms.
674 * @file_name: (allow-none): the name of the file containing the module, or %NULL
675 * to obtain a #GModule representing the main program itself
676 * @flags: the flags used for opening the module. This can be the
677 * logical OR of any of the #GModuleFlags
679 * Opens a module. If the module has already been opened,
680 * its reference count is incremented.
682 * First of all g_module_open() tries to open @file_name as a module.
683 * If that fails and @file_name has the ".la"-suffix (and is a libtool
684 * archive) it tries to open the corresponding module. If that fails
685 * and it doesn't have the proper module suffix for the platform
686 * (#G_MODULE_SUFFIX), this suffix will be appended and the corresponding
687 * module will be opended. If that fails and @file_name doesn't have the
688 * ".la"-suffix, this suffix is appended and g_module_open() tries to open
689 * the corresponding module. If eventually that fails as well, %NULL is
692 * Returns: a #GModule on success, or %NULL on failure
695 g_module_open (const gchar *file_name,
698 gchar *utf8_file_name = g_locale_to_utf8 (file_name, -1, NULL, NULL, NULL);
699 GModule *retval = g_module_open_utf8 (utf8_file_name, flags);
701 g_free (utf8_file_name);
710 * @module: a #GModule to close
714 * Returns: %TRUE on success
717 g_module_close (GModule *module)
719 SUPPORT_OR_RETURN (FALSE);
721 g_return_val_if_fail (module != NULL, FALSE);
722 g_return_val_if_fail (module->ref_count > 0, FALSE);
724 g_rec_mutex_lock (&g_module_global_lock);
728 if (!module->ref_count && !module->is_resident && module->unload)
730 GModuleUnload unload;
732 unload = module->unload;
733 module->unload = NULL;
737 if (!module->ref_count && !module->is_resident)
750 last->next = node->next;
752 modules = node->next;
760 _g_module_close (module->handle, FALSE);
761 g_free (module->file_name);
762 #if defined (G_OS_WIN32) && !defined(_WIN64)
763 g_free (module->cp_file_name);
768 g_rec_mutex_unlock (&g_module_global_lock);
769 return g_module_error() == NULL;
773 * g_module_make_resident:
774 * @module: a #GModule to make permanently resident
776 * Ensures that a module will never be unloaded.
777 * Any future g_module_close() calls on the module will be ignored.
780 g_module_make_resident (GModule *module)
782 g_return_if_fail (module != NULL);
784 module->is_resident = TRUE;
790 * Gets a string describing the last module error.
792 * Returns: a string describing the last module error
795 g_module_error (void)
797 return g_private_get (&module_error_private);
802 * @module: a #GModule
803 * @symbol_name: the name of the symbol to find
804 * @symbol: (out): returns the pointer to the symbol value
806 * Gets a symbol pointer from a module, such as one exported
807 * by #G_MODULE_EXPORT. Note that a valid symbol can be %NULL.
809 * Returns: %TRUE on success
812 g_module_symbol (GModule *module,
813 const gchar *symbol_name,
816 const gchar *module_error;
820 SUPPORT_OR_RETURN (FALSE);
822 g_return_val_if_fail (module != NULL, FALSE);
823 g_return_val_if_fail (symbol_name != NULL, FALSE);
824 g_return_val_if_fail (symbol != NULL, FALSE);
826 g_rec_mutex_lock (&g_module_global_lock);
828 #ifdef G_MODULE_NEED_USCORE
832 name = g_strconcat ("_", symbol_name, NULL);
833 *symbol = _g_module_symbol (module->handle, name);
836 #else /* !G_MODULE_NEED_USCORE */
837 *symbol = _g_module_symbol (module->handle, symbol_name);
838 #endif /* !G_MODULE_NEED_USCORE */
840 module_error = g_module_error ();
845 error = g_strconcat ("'", symbol_name, "': ", module_error, NULL);
846 g_module_set_error (error);
851 g_rec_mutex_unlock (&g_module_global_lock);
852 return !module_error;
857 * @module: a #GModule
859 * Returns the filename that the module was opened with.
861 * If @module refers to the application itself, "main" is returned.
863 * Returns: (transfer none): the filename of the module
866 g_module_name (GModule *module)
868 g_return_val_if_fail (module != NULL, NULL);
870 if (module == main_module)
873 return module->file_name;
876 #if defined (G_OS_WIN32) && !defined(_WIN64)
881 g_module_name (GModule *module)
883 g_return_val_if_fail (module != NULL, NULL);
885 if (module == main_module)
888 return module->cp_file_name;
894 * g_module_build_path:
895 * @directory: (allow-none): the directory where the module is. This can be %NULL
896 * or the empty string to indicate that the standard platform-specific
897 * directories will be used, though that is not recommended
898 * @module_name: the name of the module
900 * A portable way to build the filename of a module. The platform-specific
901 * prefix and suffix are added to the filename, if needed, and the result
902 * is added to the directory, using the correct separator character.
904 * The directory should specify the directory where the module can be found.
905 * It can be %NULL or an empty string to indicate that the module is in a
906 * standard platform-specific directory, though this is not recommended
907 * since the wrong module may be found.
909 * For example, calling g_module_build_path() on a Linux system with a
910 * @directory of <filename>/lib</filename> and a @module_name of "mylibrary"
911 * will return <filename>/lib/libmylibrary.so</filename>. On a Windows system,
912 * using <filename>\Windows</filename> as the directory it will return
913 * <filename>\Windows\mylibrary.dll</filename>.
915 * Returns: the complete path of the module, including the standard library
916 * prefix and suffix. This should be freed when no longer needed
919 g_module_build_path (const gchar *directory,
920 const gchar *module_name)
922 g_return_val_if_fail (module_name != NULL, NULL);
924 return _g_module_build_path (directory, module_name);