Subject: bug#10631: Infinite loop in emacs 23 on terminal (-nw option) on xgselect.c:58-59 when compiled with gtk+ or gconf support

From: Maciej Marcin Piechotka <[email-masked]>
Date: Sat, 28 Jan 2012 16:24:48 +0000

I hit an infinite loop on gselect.c:58-59. After quick debugging I found
that the problem is in loop xgselect.c:58-59:

while(n_gfds > gfds_size)
  gfds_size *= 2;

Problem is that:

(gdb) p n_gfds
$3 = 1
(gdb) p gfds_size
$4 = 0

1. It seems that xgselect_initialize was not called as X system is
initialized.

2. Is there a reason why the code is not using (much more efficient but
equivalent) such code in the first place:

if (ngfds > gfds_size)
  {
    gfds_size = 1 << g_bit_storage (ngfds);
    xfree (gfds);
    gfds = xmalloc (sizeof (*gfds) * gfds_size);
  }

3. The attached file get rids of initialization at all initializing at
the cost of conditional freeing of gfds (and starting mallocing from 1
instead of 128).

Best regards

>From 3facfd8d8fe1482b41015b7aaf22bcde7c49d517 Mon Sep 17 00:00:00 2001
From: Maciej Piechotka <[email-masked]>
Date: Sat, 28 Jan 2012 16:12:45 +0000
Subject: [PATCH] Fix infinit loop when emacs is compiled with GTK+ support
 and used in no-window mode

---
 src/xgselect.c |   17 +++++------------
 src/xgselect.h |    2 --
 2 files changed, 5 insertions(+), 14 deletions(-)

diff --git a/src/xgselect.c b/src/xgselect.c
index 333f7b1..4301eee 100644
--- a/src/xgselect.c
+++ b/src/xgselect.c
@@ -55,9 +55,11 @@ xg_select (max_fds, rfds, wfds, efds, timeout)
   do {
     if (n_gfds > gfds_size) 
       {
-        while (n_gfds > gfds_size) 
-          gfds_size *= 2;
-        xfree (gfds);
+        gfds_size = 1 << g_bit_storage (n_gfds);
+        if (gfds)
+          {
+            xfree (gfds);
+          }
         gfds = xmalloc (sizeof (*gfds) * gfds_size);
       }
 
@@ -152,14 +154,5 @@ xg_select (max_fds, rfds, wfds, efds, timeout)
 }
 #endif /* defined (USE_GTK) || defined (HAVE_GCONF) */
 
-void
-xgselect_initialize ()
-{
-#if defined (USE_GTK) || defined (HAVE_GCONF)
-  gfds_size = 128;
-  gfds = xmalloc (sizeof (*gfds)*gfds_size);
-#endif /* defined (USE_GTK) || defined (HAVE_GCONF) */
-}
-
 /* arch-tag: c5873ee3-d1f6-44f9-9f3b-b14f70fd0e6a
    (do not change this comment) */
diff --git a/src/xgselect.h b/src/xgselect.h
index 14488d6..3bb5428 100644
--- a/src/xgselect.h
+++ b/src/xgselect.h
@@ -30,8 +30,6 @@ extern int xg_select P_ ((int max_fds,
                           SELECT_TYPE *efds,
                           EMACS_TIME *timeout));
 
-extern void xgselect_initialize P_ ((void));
-
 #endif /* XGSELECT_H */
 
 /* arch-tag: 0c5392a8-3a41-41eb-839c-58e6595926f0
-- 
1.7.8.4