From b163045fa982e88c53d2d5236c3b8164d7a1d9bf Mon Sep 17 00:00:00 2001 From: John Lindgren Date: Wed, 2 Nov 2022 16:26:33 -0400 Subject: [PATCH] key-state: Prevent array overflow - Prevent adding the same keycode more than once - Prevent adding more keycodes than MAX_PRESSED_KEYS --- src/key-state.c | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/src/key-state.c b/src/key-state.c index 775b2e9b..2175e46d 100644 --- a/src/key-state.c +++ b/src/key-state.c @@ -12,6 +12,17 @@ struct key_array { static struct key_array pressed, bound, pressed_sent; +static bool +key_present(struct key_array *array, uint32_t keycode) +{ + for (int i = 0; i < array->nr_keys; ++i) { + if (array->keys[i] == keycode) { + return true; + } + } + return false; +} + static void remove_key(struct key_array *array, uint32_t keycode) { @@ -32,7 +43,9 @@ remove_key(struct key_array *array, uint32_t keycode) static void add_key(struct key_array *array, uint32_t keycode) { - array->keys[array->nr_keys++] = keycode; + if (!key_present(array, keycode) && array->nr_keys < MAX_PRESSED_KEYS) { + array->keys[array->nr_keys++] = keycode; + } } uint32_t * @@ -74,12 +87,7 @@ key_state_store_pressed_keys_as_bound(void) bool key_state_corresponding_press_event_was_bound(uint32_t keycode) { - for (int i = 0; i < bound.nr_keys; ++i) { - if (bound.keys[i] == keycode) { - return true; - } - } - return false; + return key_present(&bound, keycode); } void