Crafter.Graphics/tests/KeyboardKeymap/main.cpp
Jorijn van der Graaf 148ed01952
fix(wayland): keys come without text while no keymap has loaded, and a keymap that loads frees the one before
Device::keyboard_keymap made no state for a keymap of another format than
xkb_v1 or one it could not map: after such a first keymap the state
stayed null, and keyboard_modifiers and keyboard_key passed it unchecked
to libxkbcommon. For a keymap that did not compile, first or later,
keyboard_keymap called xkb_state_new on the null keymap, which crashed
(SIGSEGV) in the handler itself. Each keymap that loaded also made a
context, a keymap and a state of its own, and released none of the
earlier ones (#167).

Device, keyboard_keymap: a keymap that does not load is ignored, which
leaves the keymap and state there were. #167 has the earlier ones go
once new ones exist, and the handler already left them for a keymap of
another format or one it could not map; a context or a state that
libxkbcommon fails to make is ignored the same way. A keymap that loads
replaces the keymap and state and releases the earlier ones. Every
keymap is compiled in one context, made with the first that is mapped:
Device::xkb_context no longer gets one from a static initializer, and
is null before that.

Device, keyboard_key and keyboard_modifiers: without a state the key
brings no text and the modifiers are only kept, so a key still fires
onRawKeyDown and onRawKeyUp with the kernel's code, and only its
onTextInput is lost.

Device, the modifiers: a new state is set from the modifiers and group
the compositor last sent. wayland.xml (1.26) keeps them in wl_keyboard's
logical state, which the keymap is no part of: the modifiers event sets
them and a leave resets them to zero. A state made for a keymap that
came without a modifiers event started from none, so a Caps Lock that
was on stopped typing capitals until the next modifiers event.
keyboard_modifiers now keeps the values it was sent, keyboard_keymap sets
a new state from them, and keyboard_leave zeroes them and sets the state
from those zeros.

Device, the statics: Device::xkb_keymap and xkb_state are freed when the
next keymap loads, where the earlier ones leaked, so an application that
reads them reads them at each use. Their comment and AGENTS.consumer.md
say so, and when they are null.

Tests: KeyboardKeymap (new) drives the wl_keyboard callbacks directly,
with keymaps in memfds, on a default-constructed Window, each case in a
child process. A first keymap of the no_keymap format, one whose fd
cannot be mapped (a pipe's) and one that does not compile each have
their fd closed and make no state, and a key after modifiers then fires
onRawKeyDown and onRawKeyUp without text. After a keymap that loaded,
each of the three leaves it in place, until one loads. A second keymap
replaces the first in the same context, and on glibc 100 more leave less
than 16 KiB more on the heap. Caps Lock carries into the state of a
keymap that comes without modifiers, a leave clears it from the state
and a state made after the leave has none, and modifiers sent before the
first keymap apply to it. Run against the handlers before this change,
with libxkbcommon 1.13.2, all seven cases fail: five die of signal 11
(SIGSEGV), the 100 keymaps leave 769056 bytes more on the heap and are
not compiled in the first one's context, and the Caps Lock is kept
through the leave and lost to the next keymap.

Docs: the consumer notes say what a key brings without a keymap, that a
keymap that does not load is ignored, and when Device::xkb_keymap and
xkb_state are null and when they are freed. AGENTS.template.md names
KeyboardKeymap among the tests that drive the Wayland listeners
directly.
2026-11-26 10:55:26 +01:00

317 lines
13 KiB
C++

//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Issue #167: the wl_keyboard handlers with a keymap that does not load, and
// with keymaps that come one after another. keyboard_keymap left
// Device::xkb_state null after a first keymap of another format than xkb_v1
// or one it could not map, and keyboard_modifiers and keyboard_key then
// passed the null state to libxkbcommon, which crashes on it, at the
// modifiers a compositor sends after a keyboard enter, before any key. For a
// keymap that did not compile, first or later, keyboard_keymap called
// xkb_state_new on the null keymap, which crashed in the handler itself. And
// every keymap that loaded made a context, a keymap and a state, and freed
// none of the ones before.
//
// What the handlers do now: a keymap that does not load is ignored, so keys
// without a keymap fire onRawKeyDown and onRawKeyUp without text, and keys
// after one that loaded keep its text; a keymap that loads frees the one
// before it; every keymap is compiled in one context; and the state is set
// from the modifiers the compositor last sent, also when they came before its
// keymap, and drops them at a leave, as wl_keyboard's logical state has them.
//
// Drives the callbacks directly, with keymaps in memfds, on a
// default-constructed Window (inert without a compositor): no compositor, no
// GPU. Each case runs in a child process, so that a crash fails that case
// alone and each starts with no keymap, as a process does.
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <fcntl.h>
#include <linux/input-event-codes.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <unistd.h>
#include <wayland-client.h>
#include <xkbcommon/xkbcommon.h>
#if defined(__GLIBC__)
#include <malloc.h>
#endif
import Crafter.Graphics;
import Crafter.Event;
import std;
using namespace Crafter;
namespace {
int failures = 0;
// Flushed at once: a case that crashes keeps what it printed before.
void Check(bool ok, std::string_view what) {
std::println("{} {}", ok ? "PASS" : "FAIL", what);
std::fflush(stdout);
if (!ok) ++failures;
}
// A whole keymap in the xkb_v1 text, as a compositor serialises one: every
// section written out, nothing included. KEY_A (<AC01>, 30 + 8) types
// `lower`, and `upper` with Shift or Caps Lock.
std::string Keymap(std::string_view lower, std::string_view upper) {
return std::format(R"(xkb_keymap {{
xkb_keycodes "test" {{
minimum = 8;
maximum = 255;
<AC01> = 38;
}};
xkb_types "test" {{
type "ALPHABETIC" {{
modifiers = Shift + Lock;
map[Shift] = Level2;
map[Lock] = Level2;
level_name[Level1] = "Base";
level_name[Level2] = "Caps";
}};
}};
xkb_compatibility "test" {{
}};
xkb_symbols "test" {{
key <AC01> {{ type = "ALPHABETIC", [ {}, {} ] }};
}};
}};
)", lower, upper);
}
constexpr std::string_view kNoKeymap = "xkb_keymap { this is no keymap };";
bool Closed(int fd) {
return fcntl(fd, F_GETFD) == -1 && errno == EBADF;
}
// wl_keyboard.keymap of the xkb_v1 format, `text` in a memfd with the NUL the
// format ends it with. True when the handler closed the fd, as it must on
// every path.
bool SendKeymap(std::string_view text) {
const int fd = memfd_create("crafter-keymap", MFD_CLOEXEC);
if (fd < 0 || write(fd, text.data(), text.size()) != static_cast<ssize_t>(text.size()) || write(fd, "", 1) != 1) {
std::println("FAIL could not write a keymap to a memfd: {}", std::strerror(errno));
std::exit(EXIT_FAILURE);
}
Device::keyboard_keymap(nullptr, nullptr, WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1, fd, static_cast<std::uint32_t>(text.size() + 1));
return Closed(fd);
}
// One of the no_keymap format: /dev/null, size 0.
bool SendNoKeymap() {
const int fd = open("/dev/null", O_RDONLY | O_CLOEXEC);
Device::keyboard_keymap(nullptr, nullptr, WL_KEYBOARD_KEYMAP_FORMAT_NO_KEYMAP, fd, 0);
return Closed(fd);
}
// One of the xkb_v1 format whose fd cannot be mapped: a pipe's.
bool SendUnmappableKeymap() {
int ends[2];
if (pipe(ends) != 0) {
std::println("FAIL could not make a pipe: {}", std::strerror(errno));
std::exit(EXIT_FAILURE);
}
close(ends[1]);
Device::keyboard_keymap(nullptr, nullptr, WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1, ends[0], 4096);
return Closed(ends[0]);
}
void SendModifiers(std::uint32_t depressed, std::uint32_t locked) {
Device::keyboard_modifiers(nullptr, nullptr, 0, depressed, 0, locked, 0);
}
// The mask of the modifier `name` as a compositor with the test's keymap sends
// it, from that keymap compiled in a context of the test's own.
std::uint32_t Mask(const char* name) {
xkb_context* context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
const std::string text = Keymap("a", "A");
xkb_keymap* keymap = xkb_keymap_new_from_string(context, text.c_str(), XKB_KEYMAP_FORMAT_TEXT_V1, XKB_KEYMAP_COMPILE_NO_FLAGS);
const xkb_mod_index_t index = xkb_keymap_mod_get_index(keymap, name);
xkb_keymap_unref(keymap);
xkb_context_unref(context);
return 1u << index;
}
bool CapsLockActive() {
return xkb_state_mod_name_is_active(Device::xkb_state, XKB_MOD_NAME_CAPS, XKB_STATE_MODS_EFFECTIVE) > 0;
}
#if defined(__GLIBC__)
// The bytes the heap has handed out and not had back, mmapped chunks too.
std::size_t HeapInUse() {
const struct mallinfo2 info = mallinfo2();
return info.uordblks + info.hblkhd;
}
#endif
// A window with the keyboard focus, and what its key events brought.
struct Keyboard {
Window window; // default ctor creates no surface — safe without a compositor
int downs = 0;
int ups = 0;
std::string text;
EventListener<KeyCode> down { &window.onRawKeyDown, [this](KeyCode) { ++downs; } };
EventListener<KeyCode> up { &window.onRawKeyUp, [this](KeyCode) { ++ups; } };
EventListener<const std::string_view> typed { &window.onTextInput, [this](const std::string_view utf8) { text += utf8; } };
Keyboard() { Device::keyboardWindow = &window; }
// KEY_A pressed and released: the text it brought.
std::string TypeA() {
text.clear();
Device::keyboard_key(nullptr, nullptr, 0, 0, KEY_A, WL_KEYBOARD_KEY_STATE_PRESSED);
Device::keyboard_key(nullptr, nullptr, 0, 0, KEY_A, WL_KEYBOARD_KEY_STATE_RELEASED);
return text;
}
};
// Without a keymap: the modifiers a compositor sends after an enter, then a
// key, which still fires its raw events, without text.
void CheckKeysWithoutText(Keyboard& keyboard) {
SendModifiers(Mask(XKB_MOD_NAME_SHIFT), 0);
const std::string text = keyboard.TypeA();
Check(keyboard.downs == 1 && keyboard.ups == 1,
std::format("a key with modifiers still fires onRawKeyDown and onRawKeyUp ({} and {})", keyboard.downs, keyboard.ups));
Check(text.empty(), std::format("without text ('{}')", text));
}
void FirstKeymapOfAnotherFormat() {
Keyboard keyboard;
Check(SendNoKeymap(), "the fd of a keymap of the no_keymap format is closed");
Check(Device::xkb_state == nullptr, "and it makes no state");
CheckKeysWithoutText(keyboard);
}
void FirstKeymapUnmappable() {
Keyboard keyboard;
Check(SendUnmappableKeymap(), "the fd of a keymap that cannot be mapped is closed");
Check(Device::xkb_state == nullptr, "and it makes no state");
CheckKeysWithoutText(keyboard);
}
void FirstKeymapDoesNotCompile() {
Keyboard keyboard;
Check(SendKeymap(kNoKeymap), "the fd of a keymap that does not compile is closed");
Check(Device::xkb_keymap == nullptr && Device::xkb_state == nullptr, "and it makes no keymap and no state");
CheckKeysWithoutText(keyboard);
}
void KeymapsOneAfterAnother() {
Keyboard keyboard;
const std::string qwerty = Keymap("a", "A");
const std::string azerty = Keymap("q", "Q");
Check(SendKeymap(qwerty), "the fd of a keymap that loads is closed");
Check(keyboard.TypeA() == "a", "and KEY_A types its a");
SendModifiers(Mask(XKB_MOD_NAME_SHIFT), 0);
Check(keyboard.TypeA() == "A", "with Shift, A");
SendModifiers(0, 0);
const auto context = Device::xkb_context;
SendKeymap(azerty);
Check(keyboard.TypeA() == "q", "the next keymap replaces it: q");
Check(Device::xkb_context == context, "and is compiled in the first one's context");
#if defined(__GLIBC__)
// Both compiled in that context once more first, so that what it keeps of
// a keymap (the names it interns) is there before the count.
SendKeymap(qwerty);
SendKeymap(azerty);
const std::size_t before = HeapInUse();
for (int i = 0; i < 100; ++i) SendKeymap(i % 2 == 0 ? qwerty : azerty);
const std::ptrdiff_t grown = static_cast<std::ptrdiff_t>(HeapInUse()) - static_cast<std::ptrdiff_t>(before);
Check(grown < 16 * 1024, std::format("100 keymaps more leave {} more bytes on the heap: each frees the one before", grown));
#else
std::println("SKIP the heap count reads glibc's mallinfo2");
#endif
Check(Device::xkb_context == context, "every keymap is compiled in that one context");
Check(keyboard.TypeA() == "q", "and the last one's text is the one typed");
}
void KeymapThatDoesNotLoadAfterOne() {
Keyboard keyboard;
SendKeymap(Keymap("a", "A"));
const auto state = Device::xkb_state;
Check(SendKeymap(kNoKeymap), "the fd of a keymap that does not compile is closed");
Check(Device::xkb_state == state && keyboard.TypeA() == "a", "and it leaves the keymap there was: a");
Check(SendUnmappableKeymap(), "the fd of one that cannot be mapped is closed");
Check(Device::xkb_state == state && keyboard.TypeA() == "a", "and it leaves it too");
Check(SendNoKeymap(), "the fd of one of the no_keymap format is closed");
Check(Device::xkb_state == state && keyboard.TypeA() == "a", "and so does it");
SendKeymap(Keymap("q", "Q"));
Check(keyboard.TypeA() == "q", "until one loads: q");
}
void ModifiersApartFromTheKeymap() {
Keyboard keyboard;
const std::uint32_t capsLock = Mask(XKB_MOD_NAME_CAPS);
SendKeymap(Keymap("a", "A"));
SendModifiers(0, capsLock);
Check(keyboard.TypeA() == "A", "with Caps Lock, A");
Device::keyboard_leave(nullptr, nullptr, 0, nullptr);
Check(!CapsLockActive(), "a leave drops the modifiers from the state");
// An enter, and the modifiers the compositor sends after it.
Device::keyboardWindow = &keyboard.window;
SendModifiers(0, capsLock);
SendKeymap(Keymap("q", "Q"));
Check(keyboard.TypeA() == "Q", "the state of a keymap that comes with no modifiers takes the ones last sent: Q");
Device::keyboard_leave(nullptr, nullptr, 0, nullptr);
SendKeymap(Keymap("a", "A"));
Check(!CapsLockActive(), "and a state made after a leave, none");
}
void ModifiersBeforeTheFirstKeymap() {
Keyboard keyboard;
SendModifiers(Mask(XKB_MOD_NAME_SHIFT), 0);
SendKeymap(Keymap("a", "A"));
Check(keyboard.TypeA() == "A", "modifiers sent before the first keymap are its state's: A");
}
// Runs `body` in a child: its checks print there, and its death by a signal,
// which is how these handlers failed, is one more failure.
bool RunCase(std::string_view name, void (*body)()) {
std::println("{}:", name);
std::fflush(stdout);
const pid_t child = fork();
if (child < 0) {
std::println("FAIL could not fork: {}", std::strerror(errno));
return false;
}
if (child == 0) {
body();
std::fflush(stdout);
_exit(failures == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
}
int status = 0;
waitpid(child, &status, 0);
if (WIFSIGNALED(status)) {
std::println("FAIL the case died of signal {}", WTERMSIG(status));
return false;
}
return WIFEXITED(status) && WEXITSTATUS(status) == EXIT_SUCCESS;
}
} // namespace
int main() {
const std::pair<std::string_view, void (*)()> cases[] = {
{ "a first keymap of the no_keymap format", FirstKeymapOfAnotherFormat },
{ "a first keymap that cannot be mapped", FirstKeymapUnmappable },
{ "a first keymap that does not compile", FirstKeymapDoesNotCompile },
{ "keymaps one after another", KeymapsOneAfterAnother },
{ "keymaps that do not load, after one that did", KeymapThatDoesNotLoadAfterOne },
{ "the modifiers, apart from the keymap", ModifiersApartFromTheKeymap },
{ "modifiers before the first keymap", ModifiersBeforeTheFirstKeymap },
};
std::size_t failed = 0;
for (const auto& [name, body] : cases) {
if (!RunCase(name, body)) ++failed;
}
if (failed == 0) {
std::println("all checks passed");
} else {
std::println("{} of {} cases failed", failed, std::size(cases));
}
return failed == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}