1 /* GLib testing framework examples and tests
2 * Copyright (C) 2008 Imendio AB
5 * SPDX-License-Identifier: LicenseRef-old-glib-tests
7 * This work is provided "as is"; redistribution and modification
8 * in whole or in part, in any medium, physical or electronic is
9 * permitted without restriction.
11 * This work is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15 * In no event shall the authors or contributors be liable for any
16 * direct, indirect, incidental, special, exemplary, or consequential
17 * damages (including, but not limited to, procurement of substitute
18 * goods or services; loss of use, data, or profits; or business
19 * interruption) however caused and on any theory of liability, whether
20 * in contract, strict liability, or tort (including negligence or
21 * otherwise) arising in any way out of the use of this software, even
22 * if advised of the possibility of such damage.
25 #ifndef GLIB_DISABLE_DEPRECATION_WARNINGS
26 #define GLIB_DISABLE_DEPRECATION_WARNINGS
30 #include <glib-object.h>
32 static int mtsafe_call_counter = 0; /* multi thread safe call counter, must be accessed atomically */
33 static int unsafe_call_counter = 0; /* single-threaded call counter */
34 static GCond sync_cond;
35 static GMutex sync_mutex;
37 #define NUM_COUNTER_INCREMENTS 100000
40 call_counter_init (gpointer tclass)
43 for (i = 0; i < NUM_COUNTER_INCREMENTS; i++)
45 int saved_unsafe_call_counter = unsafe_call_counter;
46 g_atomic_int_add (&mtsafe_call_counter, 1); /* real call count update */
47 g_thread_yield(); /* let concurrent threads corrupt the unsafe_call_counter state */
48 unsafe_call_counter = 1 + saved_unsafe_call_counter; /* non-atomic counter update */
52 static void interface_per_class_init (void) { call_counter_init (NULL); }
54 /* define 3 test interfaces */
55 typedef GTypeInterface MyFace0Interface;
56 static GType my_face0_get_type (void);
57 G_DEFINE_INTERFACE (MyFace0, my_face0, G_TYPE_OBJECT)
58 static void my_face0_default_init (MyFace0Interface *iface) { call_counter_init (iface); }
59 typedef GTypeInterface MyFace1Interface;
60 static GType my_face1_get_type (void);
61 G_DEFINE_INTERFACE (MyFace1, my_face1, G_TYPE_OBJECT)
62 static void my_face1_default_init (MyFace1Interface *iface) { call_counter_init (iface); }
64 /* define 3 test objects, adding interfaces 0 & 1, and adding interface 2 after class initialization */
65 typedef GObject MyTester0;
66 typedef GObjectClass MyTester0Class;
67 static GType my_tester0_get_type (void);
68 G_DEFINE_TYPE_WITH_CODE (MyTester0, my_tester0, G_TYPE_OBJECT,
69 G_IMPLEMENT_INTERFACE (my_face0_get_type(), interface_per_class_init)
70 G_IMPLEMENT_INTERFACE (my_face1_get_type(), interface_per_class_init))
71 static void my_tester0_init (MyTester0*t) {}
72 static void my_tester0_class_init (MyTester0Class*c) { call_counter_init (c); }
73 typedef GObject MyTester1;
74 typedef GObjectClass MyTester1Class;
76 /* Disabled for now (see https://bugzilla.gnome.org/show_bug.cgi?id=687659) */
78 typedef GTypeInterface MyFace2Interface;
79 static GType my_face2_get_type (void);
80 G_DEFINE_INTERFACE (MyFace2, my_face2, G_TYPE_OBJECT)
81 static void my_face2_default_init (MyFace2Interface *iface) { call_counter_init (iface); }
83 static GType my_tester1_get_type (void);
84 G_DEFINE_TYPE_WITH_CODE (MyTester1, my_tester1, G_TYPE_OBJECT,
85 G_IMPLEMENT_INTERFACE (my_face0_get_type(), interface_per_class_init)
86 G_IMPLEMENT_INTERFACE (my_face1_get_type(), interface_per_class_init))
87 static void my_tester1_init (MyTester1*t) {}
88 static void my_tester1_class_init (MyTester1Class*c) { call_counter_init (c); }
89 typedef GObject MyTester2;
90 typedef GObjectClass MyTester2Class;
91 static GType my_tester2_get_type (void);
92 G_DEFINE_TYPE_WITH_CODE (MyTester2, my_tester2, G_TYPE_OBJECT,
93 G_IMPLEMENT_INTERFACE (my_face0_get_type(), interface_per_class_init)
94 G_IMPLEMENT_INTERFACE (my_face1_get_type(), interface_per_class_init))
95 static void my_tester2_init (MyTester2*t) {}
96 static void my_tester2_class_init (MyTester2Class*c) { call_counter_init (c); }
99 tester_init_thread (gpointer data)
101 const GInterfaceInfo face2_interface_info = { (GInterfaceInitFunc) interface_per_class_init, NULL, NULL };
103 /* first, synchronize with other threads,
104 * then run interface and class initializers,
105 * using unsafe_call_counter concurrently
107 g_mutex_lock (&sync_mutex);
108 g_mutex_unlock (&sync_mutex);
109 /* test default interface initialization for face0 */
110 g_type_default_interface_unref (g_type_default_interface_ref (my_face0_get_type()));
111 /* test class initialization, face0 per-class initializer, face1 default and per-class initializer */
112 klass = g_type_class_ref ((GType) data);
113 /* test face2 default and per-class initializer, after class_init */
114 g_type_add_interface_static (G_TYPE_FROM_CLASS (klass), my_face2_get_type(), &face2_interface_info);
116 g_type_class_unref (klass);
121 test_threaded_class_init (void)
123 GThread *t1, *t2, *t3;
125 /* pause newly created threads */
126 g_mutex_lock (&sync_mutex);
129 t1 = g_thread_create (tester_init_thread, (gpointer) my_tester0_get_type(), TRUE, NULL);
130 t2 = g_thread_create (tester_init_thread, (gpointer) my_tester1_get_type(), TRUE, NULL);
131 t3 = g_thread_create (tester_init_thread, (gpointer) my_tester2_get_type(), TRUE, NULL);
133 /* execute threads */
134 g_mutex_unlock (&sync_mutex);
135 while (g_atomic_int_get (&mtsafe_call_counter) < (3 + 3 + 3 * 3) * NUM_COUNTER_INCREMENTS)
137 if (g_test_verbose())
138 g_printerr ("Initializers counted: %u\n", g_atomic_int_get (&mtsafe_call_counter));
139 g_usleep (50 * 1000); /* wait for threads to complete */
141 if (g_test_verbose())
142 g_printerr ("Total initializers: %u\n", g_atomic_int_get (&mtsafe_call_counter));
143 /* ensure non-corrupted counter updates */
144 g_assert_cmpint (g_atomic_int_get (&mtsafe_call_counter), ==, unsafe_call_counter);
156 typedef GObjectClass PropTesterClass;
157 static GType prop_tester_get_type (void);
158 G_DEFINE_TYPE (PropTester, prop_tester, G_TYPE_OBJECT)
161 prop_tester_init (PropTester* t)
164 { } /* needs unit test framework initialization: g_test_bug ("race initializing properties"); */
167 prop_tester_set_property (GObject *object,
173 prop_tester_class_init (PropTesterClass *c)
177 GObjectClass *gobject_class = G_OBJECT_CLASS (c);
179 gobject_class->set_property = prop_tester_set_property; /* silence GObject checks */
181 g_mutex_lock (&sync_mutex);
182 g_cond_signal (&sync_cond);
183 g_mutex_unlock (&sync_mutex);
185 for (i = 0; i < 100; i++) /* wait a bit. */
188 call_counter_init (c);
189 param = g_param_spec_string ("name", "name_i18n",
190 "yet-more-wasteful-i18n",
192 G_PARAM_CONSTRUCT_ONLY | G_PARAM_WRITABLE |
193 G_PARAM_STATIC_NAME | G_PARAM_STATIC_BLURB |
194 G_PARAM_STATIC_NICK);
195 g_object_class_install_property (gobject_class, PROP_NAME, param);
199 object_create (gpointer data)
201 GObject *obj = g_object_new (prop_tester_get_type(), "name", "fish", NULL);
202 g_object_unref (obj);
207 test_threaded_object_init (void)
210 g_mutex_lock (&sync_mutex);
212 creator = g_thread_create (object_create, NULL, TRUE, NULL);
213 /* really provoke the race */
214 g_cond_wait (&sync_cond, &sync_mutex);
216 object_create (NULL);
217 g_mutex_unlock (&sync_mutex);
219 g_thread_join (creator);
228 unref_in_thread (gpointer p)
230 UnrefInThreadData *data = p;
232 g_usleep (data->unref_delay);
233 g_object_unref (data->strong);
238 /* undefine to see this test fail without GWeakRef */
239 #define HAVE_G_WEAK_REF
241 #define SLEEP_MIN_USEC 1
242 #define SLEEP_MAX_USEC 10
245 test_threaded_weak_ref (void)
248 guint get_wins = 0, unref_wins = 0;
251 if (g_test_thorough ())
252 n = NUM_COUNTER_INCREMENTS;
254 n = NUM_COUNTER_INCREMENTS / 20;
257 /* On Windows usleep has millisecond resolution and gets rounded up
258 * leading to the test running for a long time. */
262 for (i = 0; i < n; i++)
264 UnrefInThreadData data;
265 #ifdef HAVE_G_WEAK_REF
266 /* GWeakRef<MyTester0> in C++ terms */
271 MyTester0 *strengthened;
274 GError *error = NULL;
276 if (g_test_verbose () && (i % (n/20)) == 0)
277 g_printerr ("%u%%\n", ((i * 100) / n));
279 /* Have an object and a weak ref to it */
280 data.strong = g_object_new (my_tester0_get_type (), NULL);
282 #ifdef HAVE_G_WEAK_REF
283 g_weak_ref_init (&weak, data.strong);
286 g_object_add_weak_pointer ((GObject *) weak, &weak);
289 /* Delay for a random time on each side of the race, to perturb the
290 * timing. Ideally, we want each side to win half the races; on
291 * smcv's laptop, these timings are about right.
293 data.unref_delay = g_random_int_range (SLEEP_MIN_USEC / 2, SLEEP_MAX_USEC / 2);
294 get_delay = g_random_int_range (SLEEP_MIN_USEC, SLEEP_MAX_USEC);
296 /* One half of the race is to unref the shared object */
297 thread = g_thread_create (unref_in_thread, &data, TRUE, &error);
298 g_assert_no_error (error);
300 /* The other half of the race is to get the object from the "global
303 g_usleep (get_delay);
305 #ifdef HAVE_G_WEAK_REF
306 strengthened = g_weak_ref_get (&weak);
308 /* Spot the unsafe pointer access! In GDBusConnection this is rather
309 * better-hidden, but ends up with essentially the same thing, albeit
310 * cleared in dispose() rather than by a traditional weak pointer
314 if (strengthened != NULL)
315 g_object_ref (strengthened);
318 if (strengthened != NULL)
319 g_assert (G_IS_OBJECT (strengthened));
321 /* Wait for the thread to run */
322 g_thread_join (thread);
324 if (strengthened != NULL)
327 g_assert (G_IS_OBJECT (strengthened));
328 g_object_unref (strengthened);
335 #ifdef HAVE_G_WEAK_REF
336 g_weak_ref_clear (&weak);
339 g_object_remove_weak_pointer (weak, &weak);
343 if (g_test_verbose ())
344 g_printerr ("Race won by get %u times, unref %u times\n",
345 get_wins, unref_wins);
352 gint started; /* (atomic) */
353 gint finished; /* (atomic) */
354 gint disposing; /* (atomic) */
355 } ThreadedWeakRefData;
358 on_weak_ref_disposed (gpointer data,
361 ThreadedWeakRefData *thread_data = data;
363 /* Wait until the thread has started */
364 while (!g_atomic_int_get (&thread_data->started))
367 g_atomic_int_set (&thread_data->disposing, 1);
369 /* Wait for the thread to act, so that the object is still valid */
370 while (!g_atomic_int_get (&thread_data->finished))
373 g_atomic_int_set (&thread_data->disposing, 0);
377 on_other_thread_weak_ref (gpointer user_data)
379 ThreadedWeakRefData *thread_data = user_data;
380 GObject *object = thread_data->object;
382 g_atomic_int_set (&thread_data->started, 1);
384 /* Ensure we've started disposal */
385 while (!g_atomic_int_get (&thread_data->disposing))
388 g_object_ref (object);
389 g_weak_ref_set (thread_data->weak, object);
390 g_object_unref (object);
392 g_assert_cmpint (thread_data->disposing, ==, 1);
393 g_atomic_int_set (&thread_data->finished, 1);
399 test_threaded_weak_ref_finalization (void)
401 GObject *obj = g_object_new (G_TYPE_OBJECT, NULL);
402 GWeakRef weak = { { GUINT_TO_POINTER (0xDEADBEEFU) } };
403 ThreadedWeakRefData thread_data = {
404 .object = obj, .weak = &weak, .started = 0, .finished = 0
407 g_test_bug ("https://gitlab.gnome.org/GNOME/glib/-/issues/2390");
408 g_test_summary ("Test that a weak ref added by another thread during dispose "
409 "of a GObject is cleared during finalisation. "
410 "Use on_weak_ref_disposed() to synchronize the other thread "
411 "with the dispose vfunc.");
413 g_weak_ref_init (&weak, NULL);
414 g_object_weak_ref (obj, on_weak_ref_disposed, &thread_data);
416 g_assert_cmpint (obj->ref_count, ==, 1);
417 g_thread_unref (g_thread_new ("on_other_thread",
418 on_other_thread_weak_ref,
420 g_object_unref (obj);
422 /* This is what this test is about: at this point the weak reference
423 * should have been unset (and not point to a dead object either). */
424 g_assert_null (g_weak_ref_get (&weak));
430 int done; /* (atomic) */
431 int toggles; /* (atomic) */
432 } ToggleNotifyThreadData;
435 on_reffer_thread (gpointer user_data)
437 ToggleNotifyThreadData *thread_data = user_data;
439 while (!g_atomic_int_get (&thread_data->done))
441 g_object_ref (thread_data->object);
442 g_object_unref (thread_data->object);
449 on_toggle_notify (gpointer data,
451 gboolean is_last_ref)
453 /* Anything could be put here, but we don't care for this test.
454 * Actually having this empty made the bug to happen more frequently (being
460 on_toggler_thread (gpointer user_data)
462 ToggleNotifyThreadData *thread_data = user_data;
464 while (!g_atomic_int_get (&thread_data->done))
466 g_object_ref (thread_data->object);
467 g_object_remove_toggle_ref (thread_data->object, on_toggle_notify, thread_data);
468 g_object_add_toggle_ref (thread_data->object, on_toggle_notify, thread_data);
469 g_object_unref (thread_data->object);
470 g_atomic_int_add (&thread_data->toggles, 1);
477 test_threaded_toggle_notify (void)
479 GObject *object = g_object_new (G_TYPE_OBJECT, NULL);
480 ToggleNotifyThreadData data = { object, FALSE, 0 };
483 const int n_iterations = g_test_thorough () ? 1000000 : 100000;
485 g_test_bug ("https://gitlab.gnome.org/GNOME/glib/issues/2394");
486 g_test_summary ("Test that toggle reference notifications can be changed "
487 "safely from another (the main) thread without causing the "
488 "notifying thread to abort");
490 g_object_add_toggle_ref (object, on_toggle_notify, &data);
491 g_object_unref (object);
493 g_assert_cmpint (object->ref_count, ==, 1);
494 threads[0] = g_thread_new ("on_reffer_thread", on_reffer_thread, &data);
495 threads[1] = g_thread_new ("on_another_reffer_thread", on_reffer_thread, &data);
496 threads[2] = g_thread_new ("on_main_toggler_thread", on_toggler_thread, &data);
498 /* We need to wait here for the threads to run for a bit in order to make the
499 * race to happen, so we wait for an high number of toggle changes to be met
500 * so that we can be consistent on each platform.
502 while (g_atomic_int_get (&data.toggles) < n_iterations)
504 g_atomic_int_set (&data.done, TRUE);
506 for (i = 0; i < G_N_ELEMENTS (threads); i++)
507 g_thread_join (threads[i]);
509 g_assert_cmpint (object->ref_count, ==, 1);
510 g_clear_object (&object);
514 test_threaded_g_pointer_bit_unlock_and_set (void)
520 gpointer mangled_obj;
522 #if defined(__GNUC__)
523 /* We should have at least one bit we can use safely for bit-locking */
524 G_STATIC_ASSERT (__alignof (GObject) > 1);
527 obj = g_object_new (G_TYPE_OBJECT, NULL);
529 g_assert_true (g_pointer_bit_lock_mask_ptr (obj, 0, 0, 0, NULL) == obj);
530 g_assert_true (g_pointer_bit_lock_mask_ptr (obj, 0, 0, 0x2, obj) == obj);
531 g_assert_true (g_pointer_bit_lock_mask_ptr (obj, 0, 1, 0, NULL) != obj);
534 g_assert_true (g_pointer_bit_lock_mask_ptr (obj, 0, 0, 0x2, mangled_obj) == obj);
535 g_assert_true (g_pointer_bit_lock_mask_ptr (obj, 0, 0, 0x3, mangled_obj) == obj);
536 g_atomic_pointer_and (&mangled_obj, ~((gsize) 0x7));
537 g_atomic_pointer_or (&mangled_obj, 0x2);
538 g_assert_true (g_pointer_bit_lock_mask_ptr (obj, 0, 0, 0x2, mangled_obj) != obj);
539 g_assert_true (g_pointer_bit_lock_mask_ptr (obj, 0, 0, 0x2, mangled_obj) == (gpointer) (((guintptr) obj) | ((guintptr) mangled_obj)));
540 g_assert_true (g_pointer_bit_lock_mask_ptr (obj, 0, 0, 0x3, mangled_obj) == (gpointer) (((guintptr) obj) | ((guintptr) mangled_obj)));
541 g_assert_true (g_pointer_bit_lock_mask_ptr (obj, 0, TRUE, 0x3, mangled_obj) == (gpointer) (((guintptr) obj) | ((guintptr) mangled_obj) | ((guintptr) 1)));
542 g_atomic_pointer_and (&mangled_obj, ~((gsize) 0x2));
543 g_assert_true (g_pointer_bit_lock_mask_ptr (obj, 0, 0, 0x2, mangled_obj) == obj);
544 g_atomic_pointer_or (&mangled_obj, 0x2);
547 g_pointer_bit_lock (&plock, 0);
548 g_assert_true (plock != obj);
549 g_pointer_bit_unlock_and_set (&plock, 0, obj, 0);
550 g_assert_true (plock == obj);
553 g_pointer_bit_lock_and_get (&plock, 0, &ptr2);
554 g_assert_true ((gpointer) ptr2 == plock);
555 g_assert_true (plock != obj);
556 g_atomic_pointer_set (&plock, mangled_obj);
557 g_pointer_bit_unlock_and_set (&plock, 0, obj, 0);
558 g_assert_true (plock == obj);
561 g_pointer_bit_lock_and_get (&plock, 0, NULL);
562 g_assert_true (plock != obj);
563 g_atomic_pointer_set (&plock, mangled_obj);
564 g_pointer_bit_unlock_and_set (&plock, 0, obj, 0x7);
565 g_assert_true (plock != obj);
566 g_assert_true (plock == (gpointer) (((guintptr) obj) | ((guintptr) mangled_obj)));
569 g_pointer_bit_lock (&plock, 0);
570 g_assert_true (plock != NULL);
571 g_pointer_bit_unlock_and_set (&plock, 0, NULL, 0);
572 g_assert_true (plock == NULL);
574 ptr = ((char *) obj) + 1;
576 g_pointer_bit_lock (&plock, 0);
577 g_assert_true (plock == ptr);
578 g_test_expect_message ("GLib", G_LOG_LEVEL_CRITICAL,
579 "*assertion 'ptr == pointer_bit_lock_mask_ptr (ptr, lock_bit, FALSE, 0, NULL)' failed*");
580 g_pointer_bit_unlock_and_set (&plock, 0, ptr, 0);
581 g_test_assert_expected_messages ();
582 g_assert_true (plock != ptr);
583 g_assert_true (plock == obj);
585 g_object_unref (obj);
592 g_test_init (&argc, &argv, NULL);
594 /* g_test_add_func ("/GObject/threaded-class-init", test_threaded_class_init); */
595 g_test_add_func ("/GObject/threaded-object-init", test_threaded_object_init);
596 g_test_add_func ("/GObject/threaded-weak-ref", test_threaded_weak_ref);
597 g_test_add_func ("/GObject/threaded-weak-ref/on-finalization",
598 test_threaded_weak_ref_finalization);
599 g_test_add_func ("/GObject/threaded-toggle-notify",
600 test_threaded_toggle_notify);
601 g_test_add_func ("/GObject/threaded-g-pointer-bit-unlock-and-set",
602 test_threaded_g_pointer_bit_unlock_and_set);