util: Avoid undefined behaviour in for_each_helper
authorFergus Dall <sidereal@google.com>
Fri, 9 Jul 2021 07:52:01 +0000 (17:52 +1000)
committerDaniel Stone <daniels@collabora.com>
Wed, 21 Jul 2021 11:42:42 +0000 (11:42 +0000)
commit80164ef3005e8bb5f785082b97a75cab15444f82
tree27b27a8978fd941332eec986265277a33c261411
parentada25fbd526dec116026cb2567a912b47890ad05
util: Avoid undefined behaviour in for_each_helper

for_each_helper tries to calculate a one-past-the-end pointer for its
wl_array input. This is fine when the array has one or more entries, but we
initialize arrays by setting wl_array.data to NULL. Pointer arithmetic is
only defined when both the pointer operand and the result point to the same
allocation, or one-past-the-end of that allocation. As NULL points to no
allocation, no pointer arithmetic can be performed on it, not even adding 0,
even if the result is never dereferenced.

This is caught by clang's ubsan from version 10.

Many tests already hit this case, but I added an explicit test for iterating
over an empty wl_map.

Signed-off-by: Fergus Dall <sidereal@google.com>
src/wayland-util.c
tests/map-test.c