g_main_context_unref() versus g_source_*() race
Submitted by Ognyan Tonchev (redstar_)
Link to original bug (#720186)
Description
Created attachment 263908 example program showing the problem
The sample program creates an idle source and attaches it to a main loop context. Then it unrefs the idle source while the main loop is quitting and unreffing its context which leads to the context being freed along with its mutex lock. At the very same time the source unref tries to lock the mutex (which no longer exists).
A normal execution of the program give the following log output:
main loop started
unreffing main loop 1
source unreffed 2
we are now done!
But when run for a long time either the program will hang, or it segfaults like this:
main loop started
unreffing main loop 1
Segmentation fault (core dumped)
or libc will detect that the mutex is invalid and glib will abort:
main loop started
unreffing main loop 1
GLib (gthread-posix.c): Unexpected error from C library during 'pthread_mutex_lock': Invalid argument. Aborting.
I think that one of the problems could be that GSource has a pointer to GMainContext, but it doesn't have a reference to it. Is adding a reference enough to fix this problem in your opinion? If so I can attach a proposed patch.
Attachment 263908, "example program showing the problem":
gmain_race.c
Version: 2.36.x