Re: [PATCH] selftests/user_events: Avoid taking address of packed member in perf_test

Andrew Morton
2025-11-01T03:19:27Z

On Wed, 29 Oct 2025 20:50:38 +0530 Ankit Khushwaha <ankitkhushwaha.linux@gmail.com> wrote:

> > > > > /* Ensure write shows up at correct offset */
> > > > > - ASSERT_NE(-1, write(self->data_fd, &reg.write_index,
> > > > > + memcpy(&write_index, &reg.write_index, sizeof(reg.write_index));
> > > > > + ASSERT_NE(-1, write(self->data_fd, &write_index,
> > > > > sizeof(reg.write_index)));
> > > >
> > > > Simply casting &write_index to void* would fix this?
> > >
> > > yes, this hides the type mismatch from the compiler. But i think
> > > casting to void * will not fix the alignment mismatch for packed struct.
> > > It works on x86, but might break on other platform.
> >
> > It's the second argument to write(2)! write(2) expects a const char *,
> > but void* will work.
>
> Hi Andrew,
> Indeed
> `ASSERT_NE(-1, write(self->data_fd, (void *)&reg.write_index,
> sizeof(reg.write_index)));`
>
> would work. However since `reg` is packed struct, directly taking the
> address of its member `&reg.write_index` may lead to unaligned access
> on some architectures. as indicated by the compiler warning
>
> perf_test.c:239:38: warning: taking address of packed member
> 'write_index' of class or structure 'user_reg' may result in
> an unaligned pointer value [-Waddress-of-packed-member]

Well sure, we might get an unaligned pointer value and it would be an
error to dereference that pointer.

But we don't dereference it! We pass that pointer to write(2), which
is happy with any alignment.

The warning is accurate. It "may" indeed "result in an unaligned
pointer value". But there is nothing at all wrong with this code. OK,
let's find some way to suppress the warning (preferably without adding
a pointless memcpy) and let's make the changelog and code comments be
clear about what's going on here.