Subject: Re: bug#42943: 28.0.50; Emacsclient crashes in ftcrfont_glyph_extents

From: Eli Zaretskii <[email-masked]>
Date: Sat, 24 Oct 2020 17:48:26 +0300

> Date: Sat, 24 Oct 2020 17:12:04 +0300
> From: Eli Zaretskii <[email-masked]>
> Cc: [email-masked], [email-masked], [email-masked]
> 
> >   s->font = XFONT_OBJECT (LGSTRING_FONT (lgstring)); <----
> > 
> > so itʼs the caching in the Lisp_Object for the composition thatʼs
> > causing the problem.
> 
> OK, so when we are about to release a font, we need to go over all the
> LGSTRING objects in gstring_hash_table, and remove from that cache
> every LGSTRING whose LGSTRING_FONT object holds the font we are about
> to release.

Here, does the below give good results?

diff --git a/src/composite.c b/src/composite.c
index 984e0d9..f1b4b97 100644
--- a/src/composite.c
+++ b/src/composite.c
@@ -679,6 +679,27 @@ composition_gstring_from_id (ptrdiff_t id)
   return HASH_VALUE (h, id);
 }
 
+/* Remove from the composition hash table every lgstring that
+   references the given FONT_OBJECT.  */
+void
+composition_gstring_cache_clear_font (Lisp_Object font_object)
+{
+  struct Lisp_Hash_Table *h = XHASH_TABLE (gstring_hash_table);
+
+  for (ptrdiff_t i = 0; i < HASH_TABLE_SIZE (h); ++i)
+    {
+      Lisp_Object k = HASH_KEY (h, i);
+
+      if (!EQ (k, Qunbound))
+	{
+	  Lisp_Object gstring = HASH_VALUE (h, i);
+
+	  if (EQ (LGSTRING_FONT (gstring), font_object))
+	    hash_remove_from_table (h, k);
+	}
+    }
+}
+
 DEFUN ("clear-composition-cache", Fclear_composition_cache,
        Sclear_composition_cache, 0, 0, 0,
        doc: /* Internal use only.
diff --git a/src/composite.h b/src/composite.h
index 239f1e5..0d7d1c7 100644
--- a/src/composite.h
+++ b/src/composite.h
@@ -331,6 +331,8 @@ #define LGLYPH_WADJUST(g) (VECTORP (LGLYPH_ADJUSTMENT (g)) \
 
 extern ptrdiff_t composition_adjust_point (ptrdiff_t, ptrdiff_t);
 
+extern void composition_gstring_cache_clear_font (Lisp_Object);
+
 INLINE_HEADER_END
 
 #endif /* not EMACS_COMPOSITE_H */
diff --git a/src/font.c b/src/font.c
index fe257f4..d74938e 100644
--- a/src/font.c
+++ b/src/font.c
@@ -2645,6 +2645,11 @@ font_clear_cache (struct frame *f, Lisp_Object cache,
 		      if (! NILP (AREF (val, FONT_TYPE_INDEX)))
 			{
 			  eassert (font && driver == font->driver);
+			  /* We are going to close the font, so make
+			     sure we don't have any lgstrings lying
+			     around in lgstring cache that reference
+			     the font.  */
+			  composition_gstring_cache_clear_font (val);
 			  driver->close_font (font);
 			}
 		    }