#include <glib.h>
#include <dlfcn.h>

int main(int argc, char * argv[])
{
	void * handle, * handle_aux;
	GQuark quark;
	
	/* not defined */
	quark = g_quark_try_string("-g-type-private--GTypeFlags");
	g_print("quark %" G_GUINT32_FORMAT "=%s\n", quark, g_quark_to_string(quark));

	g_print("First load\n");
	/* gobject_init_ctor() will create the quark... */
	handle = dlopen("libgobject-2.0.so", RTLD_NOW);
	g_assert(handle != NULL);
	quark = g_quark_try_string("-g-type-private--GTypeFlags");
	g_print("Handle=%p\n", handle);
	/* ... which can be printed. */
	g_print("quark %" G_GUINT32_FORMAT "=%s\n", quark, g_quark_to_string(quark));
	dlclose(handle);
	
	g_print("Second load\n");
	/* gobject_init_ctor() will reuse the quark... */
	handle = dlopen("libgobject-2.0.so", RTLD_NOW);
	g_assert(handle != NULL);
	g_print("Handle=%p\n", handle);
	/* ... which can be printed. */
	g_print("new quark is %" G_GUINT32_FORMAT "\n", g_quark_try_string("-g-type-private--GTypeFlags"));
	g_print("original quark is %" G_GUINT32_FORMAT "=%s\n", quark, g_quark_to_string(quark));
	dlclose(handle);
	
	
	g_print("Load another library\n");
	handle_aux = dlopen("libm.so", RTLD_NOW);
	g_assert(handle_aux != NULL);
	g_print("Handle=%p\n", handle_aux);
	
	
	g_print("Last load\n");
	/* gobject_init_ctor() will not find the quark because the key string
	 * pointer is dangling, This may cause segmentation fault. */
	handle = dlopen("libgobject-2.0.so", RTLD_NOW);
	g_assert(handle != NULL);
	g_print("Handle=%p\n", handle);
	/* New quark was created */
	g_print("new quark is %" G_GUINT32_FORMAT "\n", g_quark_try_string("-g-type-private--GTypeFlags"));
	/* The quark will not be correctly printed. */
	g_print("original quark is %" G_GUINT32_FORMAT "=%s\n", quark, g_quark_to_string(quark));
	dlclose(handle);
	
	/* The quark will not be correctly printed. The key string pointer may
	 * point to some data in the other library. */
	g_print("quark %" G_GUINT32_FORMAT "=%s\n", quark, g_quark_to_string(quark));
	dlclose(handle_aux);
	/* Should segfault. */
	g_print("quark %" G_GUINT32_FORMAT "=%s\n", quark, g_quark_to_string(quark));
	
	return 0;
}
