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 HP-UX via its shl_load() mechanism, and 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 <structname>GModule</structname></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 the most Unices and Linux this is "so",
171 * for some HP-UX versions this is "sl" and 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 e.g. the shl_* implementation of HP-UX
191 * (http://www.stat.umn.edu/~luke/xls/projects/dlbasics/dlbasics.html).
192 * Also, the module for the program itself is kept seperatedly for
193 * faster access and because it has special semantics.
197 /* --- structures --- */
201 #if defined (G_OS_WIN32) && !defined(_WIN64)
205 guint ref_count : 31;
206 guint is_resident : 1;
207 GModuleUnload unload;
212 /* --- prototypes --- */
213 static gpointer _g_module_open (const gchar *file_name,
215 gboolean bind_local);
216 static void _g_module_close (gpointer handle,
218 static gpointer _g_module_self (void);
219 static gpointer _g_module_symbol (gpointer handle,
220 const gchar *symbol_name);
221 static gchar* _g_module_build_path (const gchar *directory,
222 const gchar *module_name);
223 static inline void g_module_set_error (const gchar *error);
224 static inline GModule* g_module_find_by_handle (gpointer handle);
225 static inline GModule* g_module_find_by_name (const gchar *name);
228 /* --- variables --- */
229 static GModule *modules = NULL;
230 static GModule *main_module = NULL;
231 static GPrivate module_error_private = G_PRIVATE_INIT (g_free);
232 static gboolean module_debug_initialized = FALSE;
233 static guint module_debug_flags = 0;
236 /* --- inline functions --- */
237 static inline GModule*
238 g_module_find_by_handle (gpointer handle)
241 GModule *retval = NULL;
243 if (main_module && main_module->handle == handle)
244 retval = main_module;
246 for (module = modules; module; module = module->next)
247 if (handle == module->handle)
256 static inline GModule*
257 g_module_find_by_name (const gchar *name)
260 GModule *retval = NULL;
262 for (module = modules; module; module = module->next)
263 if (strcmp (name, module->file_name) == 0)
273 g_module_set_error_unduped (gchar *error)
275 g_private_replace (&module_error_private, error);
280 g_module_set_error (const gchar *error)
282 g_module_set_error_unduped (g_strdup (error));
286 /* --- include platform specifc code --- */
287 #define SUPPORT_OR_RETURN(rv) { g_module_set_error (NULL); }
288 #if (G_MODULE_IMPL == G_MODULE_IMPL_DL)
289 #include "gmodule-dl.c"
290 #elif (G_MODULE_IMPL == G_MODULE_IMPL_DLD)
291 #include "gmodule-dld.c"
292 #elif (G_MODULE_IMPL == G_MODULE_IMPL_WIN32)
293 #include "gmodule-win32.c"
294 #elif (G_MODULE_IMPL == G_MODULE_IMPL_DYLD)
295 #include "gmodule-dyld.c"
296 #elif (G_MODULE_IMPL == G_MODULE_IMPL_AR)
297 #include "gmodule-ar.c"
299 #undef SUPPORT_OR_RETURN
300 #define SUPPORT_OR_RETURN(rv) { g_module_set_error ("dynamic modules are " \
301 "not supported by this system"); return rv; }
303 _g_module_open (const gchar *file_name,
310 _g_module_close (gpointer handle,
315 _g_module_self (void)
320 _g_module_symbol (gpointer handle,
321 const gchar *symbol_name)
326 _g_module_build_path (const gchar *directory,
327 const gchar *module_name)
331 #endif /* no implementation */
333 /* --- functions --- */
336 * g_module_supported:
338 * Checks if modules are supported on the current platform.
340 * Returns: %TRUE if modules are supported
343 g_module_supported (void)
345 SUPPORT_OR_RETURN (FALSE);
351 parse_libtool_archive (const gchar* libtool_name)
353 const guint TOKEN_DLNAME = G_TOKEN_LAST + 1;
354 const guint TOKEN_INSTALLED = G_TOKEN_LAST + 2;
355 const guint TOKEN_LIBDIR = G_TOKEN_LAST + 3;
356 gchar *lt_dlname = NULL;
357 gboolean lt_installed = TRUE;
358 gchar *lt_libdir = NULL;
363 int fd = g_open (libtool_name, O_RDONLY, 0);
366 gchar *display_libtool_name = g_filename_display_name (libtool_name);
367 g_module_set_error_unduped (g_strdup_printf ("failed to open libtool archive \"%s\"", display_libtool_name));
368 g_free (display_libtool_name);
371 /* search libtool's dlname specification */
372 scanner = g_scanner_new (NULL);
373 g_scanner_input_file (scanner, fd);
374 scanner->config->symbol_2_token = TRUE;
375 g_scanner_scope_add_symbol (scanner, 0, "dlname",
376 GUINT_TO_POINTER (TOKEN_DLNAME));
377 g_scanner_scope_add_symbol (scanner, 0, "installed",
378 GUINT_TO_POINTER (TOKEN_INSTALLED));
379 g_scanner_scope_add_symbol (scanner, 0, "libdir",
380 GUINT_TO_POINTER (TOKEN_LIBDIR));
381 while (!g_scanner_eof (scanner))
383 token = g_scanner_get_next_token (scanner);
384 if (token == TOKEN_DLNAME || token == TOKEN_INSTALLED ||
385 token == TOKEN_LIBDIR)
387 if (g_scanner_get_next_token (scanner) != '=' ||
388 g_scanner_get_next_token (scanner) !=
389 (token == TOKEN_INSTALLED ?
390 G_TOKEN_IDENTIFIER : G_TOKEN_STRING))
392 gchar *display_libtool_name = g_filename_display_name (libtool_name);
393 g_module_set_error_unduped (g_strdup_printf ("unable to parse libtool archive \"%s\"", display_libtool_name));
394 g_free (display_libtool_name);
398 g_scanner_destroy (scanner);
405 if (token == TOKEN_DLNAME)
408 lt_dlname = g_strdup (scanner->value.v_string);
410 else if (token == TOKEN_INSTALLED)
412 strcmp (scanner->value.v_identifier, "yes") == 0;
413 else /* token == TOKEN_LIBDIR */
416 lt_libdir = g_strdup (scanner->value.v_string);
424 gchar *dir = g_path_get_dirname (libtool_name);
426 lt_libdir = g_strconcat (dir, G_DIR_SEPARATOR_S ".libs", NULL);
430 name = g_strconcat (lt_libdir, G_DIR_SEPARATOR_S, lt_dlname, NULL);
434 g_scanner_destroy (scanner);
440 static inline gboolean
441 str_check_suffix (const gchar* string,
444 gsize string_len = strlen (string);
445 gsize suffix_len = strlen (suffix);
447 return string_len >= suffix_len &&
448 strcmp (string + string_len - suffix_len, suffix) == 0;
453 G_MODULE_DEBUG_RESIDENT_MODULES = 1 << 0,
454 G_MODULE_DEBUG_BIND_NOW_MODULES = 1 << 1
458 _g_module_debug_init (void)
460 const GDebugKey keys[] = {
461 { "resident-modules", G_MODULE_DEBUG_RESIDENT_MODULES },
462 { "bind-now-modules", G_MODULE_DEBUG_BIND_NOW_MODULES }
466 env = g_getenv ("G_DEBUG");
469 !env ? 0 : g_parse_debug_string (env, keys, G_N_ELEMENTS (keys));
471 module_debug_initialized = TRUE;
474 static GRecMutex g_module_global_lock;
477 g_module_open (const gchar *file_name,
481 gpointer handle = NULL;
484 SUPPORT_OR_RETURN (NULL);
486 g_rec_mutex_lock (&g_module_global_lock);
488 if (G_UNLIKELY (!module_debug_initialized))
489 _g_module_debug_init ();
491 if (module_debug_flags & G_MODULE_DEBUG_BIND_NOW_MODULES)
492 flags &= ~G_MODULE_BIND_LAZY;
498 handle = _g_module_self ();
501 main_module = g_new (GModule, 1);
502 main_module->file_name = NULL;
503 #if defined (G_OS_WIN32) && !defined(_WIN64)
504 main_module->cp_file_name = NULL;
506 main_module->handle = handle;
507 main_module->ref_count = 1;
508 main_module->is_resident = TRUE;
509 main_module->unload = NULL;
510 main_module->next = NULL;
514 main_module->ref_count++;
516 g_rec_mutex_unlock (&g_module_global_lock);
520 /* we first search the module list by name */
521 module = g_module_find_by_name (file_name);
526 g_rec_mutex_unlock (&g_module_global_lock);
530 /* check whether we have a readable file right away */
531 if (g_file_test (file_name, G_FILE_TEST_IS_REGULAR))
532 name = g_strdup (file_name);
533 /* try completing file name with standard library suffix */
536 name = g_strconcat (file_name, "." G_MODULE_SUFFIX, NULL);
537 if (!g_file_test (name, G_FILE_TEST_IS_REGULAR))
543 /* try completing by appending libtool suffix */
546 name = g_strconcat (file_name, ".la", NULL);
547 if (!g_file_test (name, G_FILE_TEST_IS_REGULAR))
553 /* we can't access() the file, lets hope the platform backends finds
554 * it via library paths
558 gchar *dot = strrchr (file_name, '.');
559 gchar *slash = strrchr (file_name, G_DIR_SEPARATOR);
561 /* make sure the name has a suffix */
562 if (!dot || dot < slash)
563 name = g_strconcat (file_name, "." G_MODULE_SUFFIX, NULL);
565 name = g_strdup (file_name);
568 /* ok, try loading the module */
571 /* if it's a libtool archive, figure library file to load */
572 if (str_check_suffix (name, ".la")) /* libtool archive? */
574 gchar *real_name = parse_libtool_archive (name);
576 /* real_name might be NULL, but then module error is already set */
584 handle = _g_module_open (name, (flags & G_MODULE_BIND_LAZY) != 0,
585 (flags & G_MODULE_BIND_LOCAL) != 0);
589 gchar *display_file_name = g_filename_display_name (file_name);
590 g_module_set_error_unduped (g_strdup_printf ("unable to access file \"%s\"", display_file_name));
591 g_free (display_file_name);
598 GModuleCheckInit check_init;
599 const gchar *check_failed = NULL;
601 /* search the module list by handle, since file names are not unique */
602 module = g_module_find_by_handle (handle);
605 _g_module_close (module->handle, TRUE);
607 g_module_set_error (NULL);
609 g_rec_mutex_unlock (&g_module_global_lock);
613 saved_error = g_strdup (g_module_error ());
614 g_module_set_error (NULL);
616 module = g_new (GModule, 1);
617 module->file_name = g_strdup (file_name);
618 #if defined (G_OS_WIN32) && !defined(_WIN64)
619 module->cp_file_name = g_locale_from_utf8 (file_name, -1,
622 module->handle = handle;
623 module->ref_count = 1;
624 module->is_resident = FALSE;
625 module->unload = NULL;
626 module->next = modules;
629 /* check initialization */
630 if (g_module_symbol (module, "g_module_check_init", (gpointer) &check_init) && check_init != NULL)
631 check_failed = check_init (module);
633 /* we don't call unload() if the initialization check failed. */
635 g_module_symbol (module, "g_module_unload", (gpointer) &module->unload);
641 error = g_strconcat ("GModule (", file_name, ") ",
642 "initialization check failed: ",
644 g_module_close (module);
646 g_module_set_error (error);
650 g_module_set_error (saved_error);
652 g_free (saved_error);
655 if (module != NULL &&
656 (module_debug_flags & G_MODULE_DEBUG_RESIDENT_MODULES))
657 g_module_make_resident (module);
659 g_rec_mutex_unlock (&g_module_global_lock);
663 #if defined (G_OS_WIN32) && !defined(_WIN64)
669 * @G_MODULE_BIND_LAZY: specifies that symbols are only resolved when
670 * needed. The default action is to bind all symbols when the module
672 * @G_MODULE_BIND_LOCAL: specifies that symbols in the module should
673 * not be added to the global name space. The default action on most
674 * platforms is to place symbols in the module in the global name space,
675 * which may cause conflicts with existing symbols.
676 * @G_MODULE_BIND_MASK: mask for all flags.
678 * Flags passed to g_module_open().
679 * Note that these flags are not supported on all platforms.
684 * @file_name: (allow-none): the name of the file containing the module, or %NULL
685 * to obtain a #GModule representing the main program itself
686 * @flags: the flags used for opening the module. This can be the
687 * logical OR of any of the #GModuleFlags
689 * Opens a module. If the module has already been opened,
690 * its reference count is incremented.
692 * First of all g_module_open() tries to open @file_name as a module.
693 * If that fails and @file_name has the ".la"-suffix (and is a libtool
694 * archive) it tries to open the corresponding module. If that fails
695 * and it doesn't have the proper module suffix for the platform
696 * (#G_MODULE_SUFFIX), this suffix will be appended and the corresponding
697 * module will be opended. If that fails and @file_name doesn't have the
698 * ".la"-suffix, this suffix is appended and g_module_open() tries to open
699 * the corresponding module. If eventually that fails as well, %NULL is
702 * Returns: a #GModule on success, or %NULL on failure
705 g_module_open (const gchar *file_name,
708 gchar *utf8_file_name = g_locale_to_utf8 (file_name, -1, NULL, NULL, NULL);
709 GModule *retval = g_module_open_utf8 (utf8_file_name, flags);
711 g_free (utf8_file_name);
720 * @module: a #GModule to close
724 * Returns: %TRUE on success
727 g_module_close (GModule *module)
729 SUPPORT_OR_RETURN (FALSE);
731 g_return_val_if_fail (module != NULL, FALSE);
732 g_return_val_if_fail (module->ref_count > 0, FALSE);
734 g_rec_mutex_lock (&g_module_global_lock);
738 if (!module->ref_count && !module->is_resident && module->unload)
740 GModuleUnload unload;
742 unload = module->unload;
743 module->unload = NULL;
747 if (!module->ref_count && !module->is_resident)
760 last->next = node->next;
762 modules = node->next;
770 _g_module_close (module->handle, FALSE);
771 g_free (module->file_name);
772 #if defined (G_OS_WIN32) && !defined(_WIN64)
773 g_free (module->cp_file_name);
778 g_rec_mutex_unlock (&g_module_global_lock);
779 return g_module_error() == NULL;
783 * g_module_make_resident:
784 * @module: a #GModule to make permanently resident
786 * Ensures that a module will never be unloaded.
787 * Any future g_module_close() calls on the module will be ignored.
790 g_module_make_resident (GModule *module)
792 g_return_if_fail (module != NULL);
794 module->is_resident = TRUE;
800 * Gets a string describing the last module error.
802 * Returns: a string describing the last module error
805 g_module_error (void)
807 return g_private_get (&module_error_private);
812 * @module: a #GModule
813 * @symbol_name: the name of the symbol to find
814 * @symbol: returns the pointer to the symbol value
816 * Gets a symbol pointer from a module, such as one exported
817 * by #G_MODULE_EXPORT. Note that a valid symbol can be %NULL.
819 * Returns: %TRUE on success
822 g_module_symbol (GModule *module,
823 const gchar *symbol_name,
826 const gchar *module_error;
830 SUPPORT_OR_RETURN (FALSE);
832 g_return_val_if_fail (module != NULL, FALSE);
833 g_return_val_if_fail (symbol_name != NULL, FALSE);
834 g_return_val_if_fail (symbol != NULL, FALSE);
836 g_rec_mutex_lock (&g_module_global_lock);
838 #ifdef G_MODULE_NEED_USCORE
842 name = g_strconcat ("_", symbol_name, NULL);
843 *symbol = _g_module_symbol (module->handle, name);
846 #else /* !G_MODULE_NEED_USCORE */
847 *symbol = _g_module_symbol (module->handle, symbol_name);
848 #endif /* !G_MODULE_NEED_USCORE */
850 module_error = g_module_error ();
855 error = g_strconcat ("'", symbol_name, "': ", module_error, NULL);
856 g_module_set_error (error);
861 g_rec_mutex_unlock (&g_module_global_lock);
862 return !module_error;
867 * @module: a #GModule
869 * Returns the filename that the module was opened with.
871 * If @module refers to the application itself, "main" is returned.
873 * Returns: (transfer none): the filename of the module
876 g_module_name (GModule *module)
878 g_return_val_if_fail (module != NULL, NULL);
880 if (module == main_module)
883 return module->file_name;
886 #if defined (G_OS_WIN32) && !defined(_WIN64)
891 g_module_name (GModule *module)
893 g_return_val_if_fail (module != NULL, NULL);
895 if (module == main_module)
898 return module->cp_file_name;
904 * g_module_build_path:
905 * @directory: the directory where the module is. This can be %NULL
906 * or the empty string to indicate that the standard platform-specific
907 * directories will be used, though that is not recommended
908 * @module_name: the name of the module
910 * A portable way to build the filename of a module. The platform-specific
911 * prefix and suffix are added to the filename, if needed, and the result
912 * is added to the directory, using the correct separator character.
914 * The directory should specify the directory where the module can be found.
915 * It can be %NULL or an empty string to indicate that the module is in a
916 * standard platform-specific directory, though this is not recommended
917 * since the wrong module may be found.
919 * For example, calling g_module_build_path() on a Linux system with a
920 * @directory of <filename>/lib</filename> and a @module_name of "mylibrary"
921 * will return <filename>/lib/libmylibrary.so</filename>. On a Windows system,
922 * using <filename>\Windows</filename> as the directory it will return
923 * <filename>\Windows\mylibrary.dll</filename>.
925 * Returns: the complete path of the module, including the standard library
926 * prefix and suffix. This should be freed when no longer needed
929 g_module_build_path (const gchar *directory,
930 const gchar *module_name)
932 g_return_val_if_fail (module_name != NULL, NULL);
934 return _g_module_build_path (directory, module_name);