Subject: 25.0.50; X11 error: BadPixmap when creating first emacsclient frame; and memory leak

From: Dima Kogan <[email-masked]>
Date: Thu, 17 Sep 2015 21:41:00 -0700

Hi. I'm continuing the hunt for memory leaks:

  http://lists.gnu.org/archive/html/emacs-devel/2015-09/msg00619.html

As noted in that post, even after fixing the winner-mode problem, memory
still leaks, albeit slowly. Chasing down that leak led me to this bug.
The issue is an X11 BadPixmap error thrown maybe 20% of the time when
the FIRST client frame is opened. I have only tested with the lucid
widgets. Steps:

  1. emacs -Q --daemon
  2. In bash:   while true; do timeout 1 emacsclient -a '' -c; sleep 1; done;

So I spawn a new frame kill it after 1 second, then wait 1 more second
and repeat. Most of the time this looks like what you'd expect. About
20% of the time, however, the new X window pops up momentarily, and
instantly goes away. What's happening internally is apparently an X11
error that blows up the window. This isn't printed anywhere, but I use
perf to see it:

   # perf probe -x /usr/bin/emacs --add 'x_connection_closed error_message:string'
   ...

   # perf record -p `pidof emacs` -eprobe_emacs:x_connection_closed
   ... Ctrl-c when done

   # perf script
       emacs-tst 24692 [000] 443392.814048: probe_emacs:x_connection_closed: (4c0000) error_message_string="X protocol error: BadPixmap (invalid Pixmap parameter) on protocol request 55"

This clearly shouldn't happen. I've been running my emacs as a daemon
for years, however and I've never seen this. It turns out that this
happens ONLY if we creates/destroy the only frame. If instead, we

  1. create one frame by keeping an instance of the client open
  2. Run the above bash snippet to repeatedly create/destroy the second
  frame, then this X error does not happen, and everything works.

Another part of this is that when an X frame dies in this way, we leak
memory. The biggest offender is the font system. Normally, when a frame
is created, we open some fonts with xftfont_open(). Then when the frame
is destroyed x_delete_terminal() is called, which among other things
does

  if (dpyinfo->display)
      XtCloseDisplay();

which frees the fonts. If we get an X error, however, then
x_connection_closed() runs first. This sets dpyinfo->display=0, so the
above doesn't run, and the fonts leak.

I'm attaching a plot where I sampled the memory usage every second. At
the start I had an extra client window open, and we leak memory. Then I
closed that client window, and we started leaking memory much faster.
Then I created an extra client window again, and the leak slowed down
once again.

If we can fix the X error, the leak maybe doesn't matter.