Skip to content

Fix use of freed binding in key rebinding - #1739

Open
NoahBPeterson wants to merge 1 commit into
NetHack:NetHack-5.0from
NoahBPeterson:fix-rebind-keys-use-after-free
Open

NoahBPeterson wants to merge 1 commit into
NetHack:NetHack-5.0from
NoahBPeterson:fix-rebind-keys-use-after-free

Conversation

@NoahBPeterson

@NoahBPeterson NoahBPeterson commented Nov 9, 2026 •

Copy link
Copy Markdown

Follow-up to my report #1650 (fixed by c3ce341 and 411c8be). With cmdstr initialized, the same function has two more problems.

1. Unbinding a key reads freed memory. Choosing "nothing" for a bound key:

  1. prevcmd = cmdbind_get(key) points to the key's struct Cmd_bind
  2. bind_key(key, "nothing", TRUE) calls cmdbind_remove(key), which free()s that struct
  3. if (prevcmd && prevcmd->cmd != ec) and prevcmd->cmd->ef_txt then read the freed struct

What is printed depends on the allocator. With the 5.0.0 release plus the #1650 fix, on macOS arm64, the freed cmd field read back as NULL, so no message appeared. A recording of the same keystrokes made on another machine printed Changed key 'K' from "runnorth" to "nothing".

2. Rebinding a bound key never reports the change. Rebinding K (runnorth) to apply makes cmdbind_add() update the same struct in place, so afterwards prevcmd->cmd == ec and nothing is printed.

The fix notes the previous command before calling bind_key() and uses that. Both cases now print the message the code intends:

  • unbind: Changed key 'K' from "runnorth" to "nothing".
  • rebind: Changed key 'K' from "runnorth" to "apply".

A binding is removed rather than kept with a NULL cmd, so testing prevec instead of prevcmd changes nothing else. The PR also adds an entry to doc/fixes5-0-1.txt.

To reproduce: #optionsfull, select "bind keys", a (bind key to a command), K, then a (nothing) to unbind, or :apply Enter to rebind.

Tested with the same change applied to the 5.0.0 release source (16ff591, where this function is identical) on macOS arm64 with clang. The unbind and rebind sessions print the messages above, and 106 other recorded sessions are unchanged. I have not built the current NetHack-5.0 branch.

🤖 Generated with Claude Code

handler_rebind_keys_add() saves prevcmd = cmdbind_get(key) and then
calls bind_key(). Binding "nothing" makes bind_key() call
cmdbind_remove(), which frees that binding, and the message code then
reads prevcmd->cmd and prevcmd->cmd->ef_txt from freed memory.

Rebinding an already-bound key to another command updates the binding
in place, so prevcmd->cmd already equals the new command afterwards
and "Changed key" is never printed.

Note the previous command before calling bind_key() and use that.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant