Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

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 fec7b6690541 ("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>

authored by

Arnd Bergmann and committed by
Kees Cook
56af94aa 55e68669

+6 -2
+6 -2
samples/seccomp/user-trap.c
··· 33 33 { 34 34 struct msghdr msg = {}; 35 35 struct cmsghdr *cmsg; 36 + int *fd_ptr; 36 37 char buf[CMSG_SPACE(sizeof(int))] = {0}, c = 'c'; 37 38 struct iovec io = { 38 39 .iov_base = &c, ··· 48 47 cmsg->cmsg_level = SOL_SOCKET; 49 48 cmsg->cmsg_type = SCM_RIGHTS; 50 49 cmsg->cmsg_len = CMSG_LEN(sizeof(int)); 51 - *((int *)CMSG_DATA(cmsg)) = fd; 50 + fd_ptr = (int *)CMSG_DATA(cmsg); 51 + *fd_ptr = fd; 52 52 msg.msg_controllen = cmsg->cmsg_len; 53 53 54 54 if (sendmsg(sock, &msg, 0) < 0) { ··· 64 62 { 65 63 struct msghdr msg = {}; 66 64 struct cmsghdr *cmsg; 65 + int *fd_ptr; 67 66 char buf[CMSG_SPACE(sizeof(int))] = {0}, c = 'c'; 68 67 struct iovec io = { 69 68 .iov_base = &c, ··· 82 79 } 83 80 84 81 cmsg = CMSG_FIRSTHDR(&msg); 82 + fd_ptr = (int *)CMSG_DATA(cmsg); 85 83 86 - return *((int *)CMSG_DATA(cmsg)); 84 + return *fd_ptr; 87 85 } 88 86 89 87 static int user_trap_syscall(int nr, unsigned int flags)