Re: [PATCH v1 1/2] libbpf: Fix strict aliasing violations in hashmap

From: Kumar Kartikeya Dwivedi

Date: Sat Mar 21 2026 - 13:37:15 EST


On Sat, 21 Mar 2026 at 16:42, Yonghong Song <yonghong.song@xxxxxxxxx> wrote:
>
>
>
> On 3/20/26 7:44 PM, Ian Rogers wrote:
> > The hashmap implementation contained strict aliasing violations.
> > Specifically, the hashmap_cast_ptr(p) macro was casting pointers (such
> > as void **) to long *, and these were subsequently dereferenced in
> > functions like hashmap_insert(), hashmap_find(), and hashmap_delete().
> >
> > C's strict aliasing rules (C11 6.5/7) prohibit accessing an object
> > through an lvalue of an incompatible type. Dereferencing a long * to
> > write to a void * object is a violation, even if they share the same
> > size, as they are not compatible types. This can lead to undefined
> > behavior, especially with aggressive compiler optimizations.
>
> Potentially this could be a concern. Did you actually find an issue
> with it?
>
> The linux kernel build has
> KBUILD_CFLAGS += -fno-strict-aliasing
>
> The libbpf does not have this flag. Maybe we should add '-fno-strict-aliasing'
> for libbpf as well? This way, we can avoid any future potential
> 'strict aliasing' issues.
>
> Note that bpf program (tools/testing/selftests/bpf/Makefile)
> also has '-fno-strict-alaising' flag.
>

The change itself looks correct to me, fwiw, but as Yonghong said, we
can add -fno-strict-aliasing to CFLAGS and move on. I also doubt the
compiler can cause issues here, since the usage happens in hashmap.c
which wouldn't be visible in other CUs where the call is made and
pointers are passed in (unless compilers also do aliasing-based opts
during LTO). I guess libbpf maintainers can decide what they prefer.

> [...]