Re: [PATCH] libbpf hashmap: Avoid undefined behavior in hash_bits

From: Andrii Nakryiko
Date: Thu Oct 29 2020 - 18:25:05 EST


On Thu, Oct 29, 2020 at 3:10 PM Ian Rogers <irogers@xxxxxxxxxx> wrote:
>
> If bits is 0, the case when the map is empty, then the >> is the size of
> the register which is undefined behavior - on x86 it is the same as a
> shift by 0.
> Avoid calling hash_bits with bits == 0 by adding additional empty
> hashmap tests.
>
> Suggested-by: Andrii Nakryiko <andriin@xxxxxx>,
> Suggested-by: Song Liu <songliubraving@xxxxxx>
> Signed-off-by: Ian Rogers <irogers@xxxxxxxxxx>
> ---

I didn't realize you'd need to add three extra checks. If that's the
case, let's just add `if (!bits) return 0;` to hash_bits() and be done
with it. Please keep
hashmap__for_each_key_entry_safe/hashmap__for_each_key_entry changes,
they are ok regardless.

> tools/lib/bpf/hashmap.c | 12 ++++++++++--
> tools/lib/bpf/hashmap.h | 12 ++++++------
> 2 files changed, 16 insertions(+), 8 deletions(-)
>

[...]