samples: user-trap: fix strict-aliasing warning

I started getting warnings for this one file, though I can't see what changed
since it was originally introduced in commit fec7b66905 ("samples: add an
example of seccomp user trap").

samples/seccomp/user-trap.c: In function 'send_fd':
samples/seccomp/user-trap.c:50:11: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
   50 |         *((int *)CMSG_DATA(cmsg)) = fd;
      |          ~^~~~~~~~~~~~~~~~~~~~~~~
samples/seccomp/user-trap.c: In function 'recv_fd':
samples/seccomp/user-trap.c:83:18: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
   83 |         return *((int *)CMSG_DATA(cmsg));
      |                 ~^~~~~~~~~~~~~~~~~~~~~~~

Using a temporary pointer variable avoids the warning.

Signed-off-by: Arnd Bergmann <arnd@arndb.de>
Link: https://lore.kernel.org/r/20240212111737.917428-1-arnd@kernel.org
Acked-by: Tycho Andersen <tandersen@netflix.com>
Signed-off-by: Kees Cook <keescook@chromium.org>
This commit is contained in:
Arnd Bergmann 2024-02-12 12:17:31 +01:00 committed by Kees Cook
parent 55e68669b1
commit 56af94aace

View File

@ -33,6 +33,7 @@ static int send_fd(int sock, int fd)
{ {
struct msghdr msg = {}; struct msghdr msg = {};
struct cmsghdr *cmsg; struct cmsghdr *cmsg;
int *fd_ptr;
char buf[CMSG_SPACE(sizeof(int))] = {0}, c = 'c'; char buf[CMSG_SPACE(sizeof(int))] = {0}, c = 'c';
struct iovec io = { struct iovec io = {
.iov_base = &c, .iov_base = &c,
@ -47,7 +48,8 @@ static int send_fd(int sock, int fd)
cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS; cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof(int)); cmsg->cmsg_len = CMSG_LEN(sizeof(int));
*((int *)CMSG_DATA(cmsg)) = fd; fd_ptr = (int *)CMSG_DATA(cmsg);
*fd_ptr = fd;
msg.msg_controllen = cmsg->cmsg_len; msg.msg_controllen = cmsg->cmsg_len;
if (sendmsg(sock, &msg, 0) < 0) { if (sendmsg(sock, &msg, 0) < 0) {
@ -62,6 +64,7 @@ static int recv_fd(int sock)
{ {
struct msghdr msg = {}; struct msghdr msg = {};
struct cmsghdr *cmsg; struct cmsghdr *cmsg;
int *fd_ptr;
char buf[CMSG_SPACE(sizeof(int))] = {0}, c = 'c'; char buf[CMSG_SPACE(sizeof(int))] = {0}, c = 'c';
struct iovec io = { struct iovec io = {
.iov_base = &c, .iov_base = &c,
@ -79,8 +82,9 @@ static int recv_fd(int sock)
} }
cmsg = CMSG_FIRSTHDR(&msg); cmsg = CMSG_FIRSTHDR(&msg);
fd_ptr = (int *)CMSG_DATA(cmsg);
return *((int *)CMSG_DATA(cmsg)); return *fd_ptr;
} }
static int user_trap_syscall(int nr, unsigned int flags) static int user_trap_syscall(int nr, unsigned int flags)