Subject: bug#20223: 25.0.50; key-chord.el crashes Emacs

From: Eli Zaretskii <[email-masked]>
Date: Mon, 30 Mar 2015 18:04:26 +0300

> From: Jan Tatarik <[email-masked]>
> Date: Sun, 29 Mar 2015 12:01:42 +0200
> 
> This can be reproduced from emacs -Q, with just key-chord.el
> loaded. Happens with the latest key-chord available from MELPA
> (key-chord-20140929.2246.el). Tried with current emacs master.
> 
> (package-install-file "/PATH/TO/key-chord.el")
> (key-chord-define-global "vv" ctl-x-r-map)
> (key-chord-mode 1)
> 
> Pressing [vv b] will execute bookmark-jump, as expected.
> 
> But pressing the key-chord with a key that is not defined in the target
> map will crash Emacs immediately. Try [vv q], for instance.
> 
> Only the fact that matters is the key not defined in the map. The actual
> key-chord (tried vv, pf, others) nor the map affect the outcome.

This happens because key-chord triggers a situation where the value of
't' in the snippet below (from read_key_sequence) is not in sync with
the value of 'this_command_key_count':

      /* Record what part of this_command_keys is the current key sequence.  */
      this_single_command_key_start = this_command_key_count - t;

If 't' is greater than this_command_key_count, then
this_single_command_key_start will be assigned a negative value.  In
this scenario, the result is -2 (t is 4, while this_command_key_count
is 2).  Then this-single-command-keys will produce a vector with bogus
elements.  And when a key sequence is undefined, we invoke
'undefined', which does this:

  (message "%s is undefined" (key-description (this-single-command-keys)))

So we are trying to display bogus data, with predictable results.

The same problem happens if you type "v v b", but we escape narrowly
because this key sequence is bound to a command, so we don't try to
access the result of this-single-command-keys.

I can fix this with the simple patch shown below.  It looks like
papering over the problem, and perhaps it is.  But I couldn't find any
obvious place where this_command_key_count should have been
incremented, but wasn't.  We avoid incrementing it in this scenario
because the value of 'reread' variable is 'true', since we have events
in unread-post-input-method-events after invoking the "input-method"
provided by key-chord.

HTH

--- src/keyboard.c~	2015-03-08 08:16:29 +0200
+++ src/keyboard.c	2015-03-29 15:45:46 +0300
@@ -9591,6 +9591,8 @@ read_key_sequence (Lisp_Object *keybuf,
 
       /* Record what part of this_command_keys is the current key sequence.  */
       this_single_command_key_start = this_command_key_count - t;
+      if (this_single_command_key_start < 0)
+	this_single_command_key_start = 0;
 
       /* Look for this sequence in input-decode-map.
 	 Scan from indec.end until we find a bound suffix.  */