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().
83 * <title>Calling a function defined in a GModule</title>
85 * /* the function signature for 'say_hello' */
86 * typedef void (* SayHelloFunc) (const char *message);
89 * just_say_hello (const char *filename, GError **error)
91 * SayHelloFunc say_hello;
94 * module = g_module_open (filename, G_MODULE_BIND_LAZY);
97 * g_set_error (error, FOO_ERROR, FOO_ERROR_BLAH,
98 * "%s", g_module_error ());
102 * if (!g_module_symbol (module, "say_hello", (gpointer *)&say_hello))
104 * g_set_error (error, SAY_ERROR, SAY_ERROR_OPEN,
105 * "%s: %s", filename, g_module_error ());
106 * if (!g_module_close (module))
107 * g_warning ("%s: %s", filename, g_module_error ());
111 * if (say_hello == NULL)
113 * g_set_error (error, SAY_ERROR, SAY_ERROR_OPEN,
114 * "symbol say_hello is NULL");
115 * if (!g_module_close (module))
116 * g_warning ("%s: %s", filename, g_module_error ());
120 * /* call our function in the module */
121 * say_hello ("Hello world!");
123 * if (!g_module_close (module))
124 * g_warning ("%s: %s", filename, g_module_error ());
134 * The #GModule struct is an opaque data structure to represent a
135 * <link linkend="glib-Dynamic-Loading-of-Modules">Dynamically-Loaded
136 * Module</link>. It should only be accessed via the following functions.
141 * @module: the #GModule corresponding to the module which has just been loaded
143 * Specifies the type of the module initialization function.
144 * <indexterm zone="g-module-check-init"><primary>g_module_check_init</primary></indexterm>
145 * If a module contains a function named g_module_check_init() it is called
146 * automatically when the module is loaded. It is passed the #GModule structure
147 * and should return %NULL on success or a string describing the initialization
150 * Returns: %NULL on success, or a string describing the initialization error
155 * @module: the #GModule about to be unloaded
157 * <indexterm zone="g-module-unload"><primary>g_module_unload</primary></indexterm>
158 * Specifies the type of the module function called when it is unloaded.
159 * If a module contains a function named g_module_unload() it is called
160 * automatically when the module is unloaded.
161 * It is passed the #GModule structure.
167 * Expands to the proper shared library suffix for the current platform
168 * without the leading dot. For most Unices and Linux this is "so", and
169 * for Windows this is "dll".
175 * Used to declare functions exported by modules. This is a no-op on Linux
176 * and Unices, but when compiling for Windows, it marks a symbol to be
177 * exported from the library or executable being built.
183 * Used to declare functions imported from modules.
186 /* We maintain a list of modules, so we can reference count them.
187 * That's needed because some platforms don't support references counts on
188 * modules. Also, the module for the program itself is kept seperately for
189 * faster access and because it has special semantics.
193 /* --- structures --- */
197 #if defined (G_OS_WIN32) && !defined(_WIN64)
201 guint ref_count : 31;
202 guint is_resident : 1;
203 GModuleUnload unload;
208 /* --- prototypes --- */
209 static gpointer _g_module_open (const gchar *file_name,
211 gboolean bind_local);
212 static void _g_module_close (gpointer handle,
214 static gpointer _g_module_self (void);
215 static gpointer _g_module_symbol (gpointer handle,
216 const gchar *symbol_name);
217 static gchar* _g_module_build_path (const gchar *directory,
218 const gchar *module_name);
219 static inline void g_module_set_error (const gchar *error);
220 static inline GModule* g_module_find_by_handle (gpointer handle);
221 static inline GModule* g_module_find_by_name (const gchar *name);
224 /* --- variables --- */
225 static GModule *modules = NULL;
226 static GModule *main_module = NULL;
227 static GPrivate module_error_private = G_PRIVATE_INIT (g_free);
228 static gboolean module_debug_initialized = FALSE;
229 static guint module_debug_flags = 0;
232 /* --- inline functions --- */
233 static inline GModule*
234 g_module_find_by_handle (gpointer handle)
237 GModule *retval = NULL;
239 if (main_module && main_module->handle == handle)
240 retval = main_module;
242 for (module = modules; module; module = module->next)
243 if (handle == module->handle)
252 static inline GModule*
253 g_module_find_by_name (const gchar *name)
256 GModule *retval = NULL;
258 for (module = modules; module; module = module->next)
259 if (strcmp (name, module->file_name) == 0)
269 g_module_set_error_unduped (gchar *error)
271 g_private_replace (&module_error_private, error);
276 g_module_set_error (const gchar *error)
278 g_module_set_error_unduped (g_strdup (error));
282 /* --- include platform specifc code --- */
283 #define SUPPORT_OR_RETURN(rv) { g_module_set_error (NULL); }
284 #if (G_MODULE_IMPL == G_MODULE_IMPL_DL)
285 #include "gmodule-dl.c"
286 #elif (G_MODULE_IMPL == G_MODULE_IMPL_WIN32)
287 #include "gmodule-win32.c"
288 #elif (G_MODULE_IMPL == G_MODULE_IMPL_DYLD)
289 #include "gmodule-dyld.c"
290 #elif (G_MODULE_IMPL == G_MODULE_IMPL_AR)
291 #include "gmodule-ar.c"
293 #undef SUPPORT_OR_RETURN
294 #define SUPPORT_OR_RETURN(rv) { g_module_set_error ("dynamic modules are " \
295 "not supported by this system"); return rv; }
297 _g_module_open (const gchar *file_name,
304 _g_module_close (gpointer handle,
309 _g_module_self (void)
314 _g_module_symbol (gpointer handle,
315 const gchar *symbol_name)
320 _g_module_build_path (const gchar *directory,
321 const gchar *module_name)
325 #endif /* no implementation */
327 /* --- functions --- */
330 * g_module_supported:
332 * Checks if modules are supported on the current platform.
334 * Returns: %TRUE if modules are supported
337 g_module_supported (void)
339 SUPPORT_OR_RETURN (FALSE);
345 parse_libtool_archive (const gchar* libtool_name)
347 const guint TOKEN_DLNAME = G_TOKEN_LAST + 1;
348 const guint TOKEN_INSTALLED = G_TOKEN_LAST + 2;
349 const guint TOKEN_LIBDIR = G_TOKEN_LAST + 3;
350 gchar *lt_dlname = NULL;
351 gboolean lt_installed = TRUE;
352 gchar *lt_libdir = NULL;
357 int fd = g_open (libtool_name, O_RDONLY, 0);
360 gchar *display_libtool_name = g_filename_display_name (libtool_name);
361 g_module_set_error_unduped (g_strdup_printf ("failed to open libtool archive \"%s\"", display_libtool_name));
362 g_free (display_libtool_name);
365 /* search libtool's dlname specification */
366 scanner = g_scanner_new (NULL);
367 g_scanner_input_file (scanner, fd);
368 scanner->config->symbol_2_token = TRUE;
369 g_scanner_scope_add_symbol (scanner, 0, "dlname",
370 GUINT_TO_POINTER (TOKEN_DLNAME));
371 g_scanner_scope_add_symbol (scanner, 0, "installed",
372 GUINT_TO_POINTER (TOKEN_INSTALLED));
373 g_scanner_scope_add_symbol (scanner, 0, "libdir",
374 GUINT_TO_POINTER (TOKEN_LIBDIR));
375 while (!g_scanner_eof (scanner))
377 token = g_scanner_get_next_token (scanner);
378 if (token == TOKEN_DLNAME || token == TOKEN_INSTALLED ||
379 token == TOKEN_LIBDIR)
381 if (g_scanner_get_next_token (scanner) != '=' ||
382 g_scanner_get_next_token (scanner) !=
383 (token == TOKEN_INSTALLED ?
384 G_TOKEN_IDENTIFIER : G_TOKEN_STRING))
386 gchar *display_libtool_name = g_filename_display_name (libtool_name);
387 g_module_set_error_unduped (g_strdup_printf ("unable to parse libtool archive \"%s\"", display_libtool_name));
388 g_free (display_libtool_name);
392 g_scanner_destroy (scanner);
399 if (token == TOKEN_DLNAME)
402 lt_dlname = g_strdup (scanner->value.v_string);
404 else if (token == TOKEN_INSTALLED)
406 strcmp (scanner->value.v_identifier, "yes") == 0;
407 else /* token == TOKEN_LIBDIR */
410 lt_libdir = g_strdup (scanner->value.v_string);
418 gchar *dir = g_path_get_dirname (libtool_name);
420 lt_libdir = g_strconcat (dir, G_DIR_SEPARATOR_S ".libs", NULL);
424 name = g_strconcat (lt_libdir, G_DIR_SEPARATOR_S, lt_dlname, NULL);
428 g_scanner_destroy (scanner);
434 static inline gboolean
435 str_check_suffix (const gchar* string,
438 gsize string_len = strlen (string);
439 gsize suffix_len = strlen (suffix);
441 return string_len >= suffix_len &&
442 strcmp (string + string_len - suffix_len, suffix) == 0;
447 G_MODULE_DEBUG_RESIDENT_MODULES = 1 << 0,
448 G_MODULE_DEBUG_BIND_NOW_MODULES = 1 << 1
452 _g_module_debug_init (void)
454 const GDebugKey keys[] = {
455 { "resident-modules", G_MODULE_DEBUG_RESIDENT_MODULES },
456 { "bind-now-modules", G_MODULE_DEBUG_BIND_NOW_MODULES }
460 env = g_getenv ("G_DEBUG");
463 !env ? 0 : g_parse_debug_string (env, keys, G_N_ELEMENTS (keys));
465 module_debug_initialized = TRUE;
468 static GRecMutex g_module_global_lock;
471 g_module_open (const gchar *file_name,
475 gpointer handle = NULL;
478 SUPPORT_OR_RETURN (NULL);
480 g_rec_mutex_lock (&g_module_global_lock);
482 if (G_UNLIKELY (!module_debug_initialized))
483 _g_module_debug_init ();
485 if (module_debug_flags & G_MODULE_DEBUG_BIND_NOW_MODULES)
486 flags &= ~G_MODULE_BIND_LAZY;
492 handle = _g_module_self ();
495 main_module = g_new (GModule, 1);
496 main_module->file_name = NULL;
497 #if defined (G_OS_WIN32) && !defined(_WIN64)
498 main_module->cp_file_name = NULL;
500 main_module->handle = handle;
501 main_module->ref_count = 1;
502 main_module->is_resident = TRUE;
503 main_module->unload = NULL;
504 main_module->next = NULL;
508 main_module->ref_count++;
510 g_rec_mutex_unlock (&g_module_global_lock);
514 /* we first search the module list by name */
515 module = g_module_find_by_name (file_name);
520 g_rec_mutex_unlock (&g_module_global_lock);
524 /* check whether we have a readable file right away */
525 if (g_file_test (file_name, G_FILE_TEST_IS_REGULAR))
526 name = g_strdup (file_name);
527 /* try completing file name with standard library suffix */
530 name = g_strconcat (file_name, "." G_MODULE_SUFFIX, NULL);
531 if (!g_file_test (name, G_FILE_TEST_IS_REGULAR))
537 /* try completing by appending libtool suffix */
540 name = g_strconcat (file_name, ".la", NULL);
541 if (!g_file_test (name, G_FILE_TEST_IS_REGULAR))
547 /* we can't access() the file, lets hope the platform backends finds
548 * it via library paths
552 gchar *dot = strrchr (file_name, '.');
553 gchar *slash = strrchr (file_name, G_DIR_SEPARATOR);
555 /* make sure the name has a suffix */
556 if (!dot || dot < slash)
557 name = g_strconcat (file_name, "." G_MODULE_SUFFIX, NULL);
559 name = g_strdup (file_name);
562 /* ok, try loading the module */
565 /* if it's a libtool archive, figure library file to load */
566 if (str_check_suffix (name, ".la")) /* libtool archive? */
568 gchar *real_name = parse_libtool_archive (name);
570 /* real_name might be NULL, but then module error is already set */
578 handle = _g_module_open (name, (flags & G_MODULE_BIND_LAZY) != 0,
579 (flags & G_MODULE_BIND_LOCAL) != 0);
583 gchar *display_file_name = g_filename_display_name (file_name);
584 g_module_set_error_unduped (g_strdup_printf ("unable to access file \"%s\"", display_file_name));
585 g_free (display_file_name);
592 GModuleCheckInit check_init;
593 const gchar *check_failed = NULL;
595 /* search the module list by handle, since file names are not unique */
596 module = g_module_find_by_handle (handle);
599 _g_module_close (module->handle, TRUE);
601 g_module_set_error (NULL);
603 g_rec_mutex_unlock (&g_module_global_lock);
607 saved_error = g_strdup (g_module_error ());
608 g_module_set_error (NULL);
610 module = g_new (GModule, 1);
611 module->file_name = g_strdup (file_name);
612 #if defined (G_OS_WIN32) && !defined(_WIN64)
613 module->cp_file_name = g_locale_from_utf8 (file_name, -1,
616 module->handle = handle;
617 module->ref_count = 1;
618 module->is_resident = FALSE;
619 module->unload = NULL;
620 module->next = modules;
623 /* check initialization */
624 if (g_module_symbol (module, "g_module_check_init", (gpointer) &check_init) && check_init != NULL)
625 check_failed = check_init (module);
627 /* we don't call unload() if the initialization check failed. */
629 g_module_symbol (module, "g_module_unload", (gpointer) &module->unload);
635 error = g_strconcat ("GModule (", file_name, ") ",
636 "initialization check failed: ",
638 g_module_close (module);
640 g_module_set_error (error);
644 g_module_set_error (saved_error);
646 g_free (saved_error);
649 if (module != NULL &&
650 (module_debug_flags & G_MODULE_DEBUG_RESIDENT_MODULES))
651 g_module_make_resident (module);
653 g_rec_mutex_unlock (&g_module_global_lock);
657 #if defined (G_OS_WIN32) && !defined(_WIN64)
663 * @G_MODULE_BIND_LAZY: specifies that symbols are only resolved when
664 * needed. The default action is to bind all symbols when the module
666 * @G_MODULE_BIND_LOCAL: specifies that symbols in the module should
667 * not be added to the global name space. The default action on most
668 * platforms is to place symbols in the module in the global name space,
669 * which may cause conflicts with existing symbols.
670 * @G_MODULE_BIND_MASK: mask for all flags.
672 * Flags passed to g_module_open().
673 * Note that these flags are not supported on all platforms.
678 * @file_name: (allow-none): the name of the file containing the module, or %NULL
679 * to obtain a #GModule representing the main program itself
680 * @flags: the flags used for opening the module. This can be the
681 * logical OR of any of the #GModuleFlags
683 * Opens a module. If the module has already been opened,
684 * its reference count is incremented.
686 * First of all g_module_open() tries to open @file_name as a module.
687 * If that fails and @file_name has the ".la"-suffix (and is a libtool
688 * archive) it tries to open the corresponding module. If that fails
689 * and it doesn't have the proper module suffix for the platform
690 * (#G_MODULE_SUFFIX), this suffix will be appended and the corresponding
691 * module will be opended. If that fails and @file_name doesn't have the
692 * ".la"-suffix, this suffix is appended and g_module_open() tries to open
693 * the corresponding module. If eventually that fails as well, %NULL is
696 * Returns: a #GModule on success, or %NULL on failure
699 g_module_open (const gchar *file_name,
702 gchar *utf8_file_name = g_locale_to_utf8 (file_name, -1, NULL, NULL, NULL);
703 GModule *retval = g_module_open_utf8 (utf8_file_name, flags);
705 g_free (utf8_file_name);
714 * @module: a #GModule to close
718 * Returns: %TRUE on success
721 g_module_close (GModule *module)
723 SUPPORT_OR_RETURN (FALSE);
725 g_return_val_if_fail (module != NULL, FALSE);
726 g_return_val_if_fail (module->ref_count > 0, FALSE);
728 g_rec_mutex_lock (&g_module_global_lock);
732 if (!module->ref_count && !module->is_resident && module->unload)
734 GModuleUnload unload;
736 unload = module->unload;
737 module->unload = NULL;
741 if (!module->ref_count && !module->is_resident)
754 last->next = node->next;
756 modules = node->next;
764 _g_module_close (module->handle, FALSE);
765 g_free (module->file_name);
766 #if defined (G_OS_WIN32) && !defined(_WIN64)
767 g_free (module->cp_file_name);
772 g_rec_mutex_unlock (&g_module_global_lock);
773 return g_module_error() == NULL;
777 * g_module_make_resident:
778 * @module: a #GModule to make permanently resident
780 * Ensures that a module will never be unloaded.
781 * Any future g_module_close() calls on the module will be ignored.
784 g_module_make_resident (GModule *module)
786 g_return_if_fail (module != NULL);
788 module->is_resident = TRUE;
794 * Gets a string describing the last module error.
796 * Returns: a string describing the last module error
799 g_module_error (void)
801 return g_private_get (&module_error_private);
806 * @module: a #GModule
807 * @symbol_name: the name of the symbol to find
808 * @symbol: (out): returns the pointer to the symbol value
810 * Gets a symbol pointer from a module, such as one exported
811 * by #G_MODULE_EXPORT. Note that a valid symbol can be %NULL.
813 * Returns: %TRUE on success
816 g_module_symbol (GModule *module,
817 const gchar *symbol_name,
820 const gchar *module_error;
824 SUPPORT_OR_RETURN (FALSE);
826 g_return_val_if_fail (module != NULL, FALSE);
827 g_return_val_if_fail (symbol_name != NULL, FALSE);
828 g_return_val_if_fail (symbol != NULL, FALSE);
830 g_rec_mutex_lock (&g_module_global_lock);
832 #ifdef G_MODULE_NEED_USCORE
836 name = g_strconcat ("_", symbol_name, NULL);
837 *symbol = _g_module_symbol (module->handle, name);
840 #else /* !G_MODULE_NEED_USCORE */
841 *symbol = _g_module_symbol (module->handle, symbol_name);
842 #endif /* !G_MODULE_NEED_USCORE */
844 module_error = g_module_error ();
849 error = g_strconcat ("'", symbol_name, "': ", module_error, NULL);
850 g_module_set_error (error);
855 g_rec_mutex_unlock (&g_module_global_lock);
856 return !module_error;
861 * @module: a #GModule
863 * Returns the filename that the module was opened with.
865 * If @module refers to the application itself, "main" is returned.
867 * Returns: (transfer none): the filename of the module
870 g_module_name (GModule *module)
872 g_return_val_if_fail (module != NULL, NULL);
874 if (module == main_module)
877 return module->file_name;
880 #if defined (G_OS_WIN32) && !defined(_WIN64)
885 g_module_name (GModule *module)
887 g_return_val_if_fail (module != NULL, NULL);
889 if (module == main_module)
892 return module->cp_file_name;
898 * g_module_build_path:
899 * @directory: (allow-none): the directory where the module is. This can be %NULL
900 * or the empty string to indicate that the standard platform-specific
901 * directories will be used, though that is not recommended
902 * @module_name: the name of the module
904 * A portable way to build the filename of a module. The platform-specific
905 * prefix and suffix are added to the filename, if needed, and the result
906 * is added to the directory, using the correct separator character.
908 * The directory should specify the directory where the module can be found.
909 * It can be %NULL or an empty string to indicate that the module is in a
910 * standard platform-specific directory, though this is not recommended
911 * since the wrong module may be found.
913 * For example, calling g_module_build_path() on a Linux system with a
914 * @directory of <filename>/lib</filename> and a @module_name of "mylibrary"
915 * will return <filename>/lib/libmylibrary.so</filename>. On a Windows system,
916 * using <filename>\Windows</filename> as the directory it will return
917 * <filename>\Windows\mylibrary.dll</filename>.
919 * Returns: the complete path of the module, including the standard library
920 * prefix and suffix. This should be freed when no longer needed
923 g_module_build_path (const gchar *directory,
924 const gchar *module_name)
926 g_return_val_if_fail (module_name != NULL, NULL);
928 return _g_module_build_path (directory, module_name);