//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 #include #include #include #include #include #include #include #include #include #if defined(__GLIBC__) #include #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 (, 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; = 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 {{ 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(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(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 down { &window.onRawKeyDown, [this](KeyCode) { ++downs; } }; EventListener up { &window.onRawKeyUp, [this](KeyCode) { ++ups; } }; EventListener 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(HeapInUse()) - static_cast(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 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; }