From 61066408712d7d0a8cbde84712b49fef449bb181 Mon Sep 17 00:00:00 2001
From: fvogel <fvogelnew1@free.fr>
Date: Wed, 10 Jan 2018 20:45:24 +0000
Subject: [PATCH 105/693] Fix [382712ade6]: X11: 'event generate . <KeyPress>'
 segfaults. Patch from Christian Werner.

---
 unix/tkUnixKey.c | 28 +++++++++++++++++++++++++++-
 1 file changed, 27 insertions(+), 1 deletion(-)

diff --git a/unix/tkUnixKey.c b/unix/tkUnixKey.c
index 23c4aa48d..dcdc85f05 100644
--- a/unix/tkUnixKey.c
+++ b/unix/tkUnixKey.c
@@ -110,7 +110,7 @@ TkpGetString(
     XEvent *eventPtr,		/* X keyboard event. */
     Tcl_DString *dsPtr)		/* Initialized, empty string to hold result. */
 {
-    int len;
+    int len, mincode, maxcode;
     Tcl_DString buf;
     TkKeyEvent *kePtr = (TkKeyEvent *) eventPtr;
 
@@ -125,6 +125,32 @@ TkpGetString(
 	return Tcl_DStringValue(dsPtr);
     }
 
+    /*
+     * Only do this for KeyPress events, otherwise
+     * further Xlib function behavior might be undefined.
+     */
+
+    if (eventPtr->type != KeyPress) {
+	len = 0;
+	Tcl_DStringSetLength(dsPtr, len);
+	goto done;
+    }
+
+    /*
+     * Filter keycodes out of range, otherwise
+     * further Xlib function behavior might be undefined.
+     */
+
+    mincode = 0;
+    maxcode = -1;
+    XDisplayKeycodes(winPtr->dispPtr->display, &mincode, &maxcode);
+    if ((eventPtr->xkey.keycode < mincode) ||
+	(eventPtr->xkey.keycode > maxcode)) {
+	len = 0;
+	Tcl_DStringSetLength(dsPtr, len);
+	goto done;
+    }
+
 #ifdef TK_USE_INPUT_METHODS
     if ((winPtr->dispPtr->flags & TK_DISPLAY_USE_IM)
 	    && (winPtr->inputContext != NULL)
-- 
2.19.1

