From: John Lindgren <john@jlindgren.net>
Date: Tue, 6 Aug 2019 01:58:03 -0400
Subject: Fix use-after-free due to unexpected unref of
 context->default_style.

Segfault occurred when displaying two windows on different X11 displays.

valgrind said:

Invalid read of size 8
  at 0x4A20962: _gtk_style_init_for_settings (gtkstyle.c:398)
  by 0x49ED785: gtk_rc_get_style (gtkrc.c:2036)
  by 0x4AC39C2: gtk_widget_reset_rc_style (gtkwidget.c:6601)
Address 0x70b8e80 is 560 bytes inside a block of size 1,024 free'd
  at 0x48399AB: free (vg_replace_malloc.c:530)
  by 0x51180D6: g_type_free_instance (in /usr/lib/libgobject-2.0.so.0.6000.6)
  by 0x49E98CE: gtk_rc_reset_styles (gtkrc.c:1702)
  by 0x49E9A0C: _gtk_rc_context_get_default_font_name (gtkrc.c:1740)
  by 0x4A20961: _gtk_style_init_for_settings (gtkstyle.c:396)
  by 0x49ED785: gtk_rc_get_style (gtkrc.c:2036)
  by 0x4AC39C2: gtk_widget_reset_rc_style (gtkwidget.c:6601)
Block was alloc'd at
  at 0x483877F: malloc (vg_replace_malloc.c:299)
  by 0x51BD289: g_malloc (in /usr/lib/libglib-2.0.so.0.6000.6)
  by 0x519F673: g_slice_alloc (in /usr/lib/libglib-2.0.so.0.6000.6)
  by 0x51A62BA: g_slice_alloc0 (in /usr/lib/libglib-2.0.so.0.6000.6)
  by 0x5119141: g_type_create_instance (in /usr/lib/libgobject-2.0.so.0.6000.6)
  by 0x513563D: ??? (in /usr/lib/libgobject-2.0.so.0.6000.6)
  by 0x5136A54: g_object_new_with_properties (in /usr/lib/libgobject-2.0.so.0.6000.6)
  by 0x5136B51: g_object_new (in /usr/lib/libgobject-2.0.so.0.6000.6)
  by 0x49ED774: gtk_rc_get_style (gtkrc.c:2035)
  by 0x4AC39C2: gtk_widget_reset_rc_style (gtkwidget.c:6601)

Origin: upstream, 2.24.33, commit:539a596e497a09f9a50172ecf49b1732e3e1f707
---
 gtk/gtkrc.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)

diff --git a/gtk/gtkrc.c b/gtk/gtkrc.c
index 952010e..cffaf65 100644
--- a/gtk/gtkrc.c
+++ b/gtk/gtkrc.c
@@ -2032,8 +2032,14 @@ gtk_rc_get_style (GtkWidget *widget)
     {
       if (!context->default_style)
 	{
-	  context->default_style = gtk_style_new ();
-	  _gtk_style_init_for_settings (context->default_style, context->settings);
+	  GtkStyle * style = gtk_style_new ();
+	  _gtk_style_init_for_settings (style, context->settings);
+
+	  /* Only after _gtk_style_init_for_settings() do we install the style
+	   * as the default, otherwise gtk_rc_reset_styles() can be called and
+	   * unref the style while initializing it, causing a segfault.
+	   */
+	  context->default_style = style;
 	}
 
       return context->default_style;
