[PATCH 1/1] samples/seccomp: eliminate two boring compile warnings in user-trap.c

From: Zhen Lei
Date: Fri Aug 28 2020 - 23:09:16 EST


samples/seccomp/user-trap.c is compiled with $(userccflags), and the
latter does not contain -fno-strict-aliasing, so the warnings reported as
below. Due to add "userccflags += -fno-strict-aliasin" will impact other
files, so use __attribute__((__may_alias__)) to suppress it exactly.

My gcc version is 5.5.0 20171010.

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

Signed-off-by: Zhen Lei <thunder.leizhen@xxxxxxxxxx>
---
samples/seccomp/user-trap.c | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/samples/seccomp/user-trap.c b/samples/seccomp/user-trap.c
index 20291ec6489f31e..e36696b7f41517f 100644
--- a/samples/seccomp/user-trap.c
+++ b/samples/seccomp/user-trap.c
@@ -23,6 +23,8 @@

#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))

+typedef int __attribute__((__may_alias__)) __int_alias_t;
+
static int seccomp(unsigned int op, unsigned int flags, void *args)
{
errno = 0;
@@ -47,7 +49,7 @@ static int send_fd(int sock, int fd)
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof(int));
- *((int *)CMSG_DATA(cmsg)) = fd;
+ *(__int_alias_t *)CMSG_DATA(cmsg) = fd;
msg.msg_controllen = cmsg->cmsg_len;

if (sendmsg(sock, &msg, 0) < 0) {
@@ -80,7 +82,7 @@ static int recv_fd(int sock)

cmsg = CMSG_FIRSTHDR(&msg);

- return *((int *)CMSG_DATA(cmsg));
+ return *(__int_alias_t *)CMSG_DATA(cmsg);
}

static int user_trap_syscall(int nr, unsigned int flags)
--
1.8.3