[PATCH liburing v1 1/2] recv-msgall: Fix undefined behavior in `recv_prep()`

From: Ammar Faizi
Date: Wed May 10 2023 - 10:40:27 EST


The lifetime of `struct msghdr msg;` must be long enough until the CQE
is generated because the recvmsg operation will write to that storage. I
found this test segfault when compiling with -O0 optimization. This is
undefined behavior and may behave randomly.

Fix this by making the lifetime of `struct msghdr msg;` long enough.

Fixes: https://github.com/axboe/liburing/issues/855
Signed-off-by: Ammar Faizi <ammarfaizi2@xxxxxxxxxxx>
---
test/recv-msgall.c | 28 +++++++++++++++-------------
1 file changed, 15 insertions(+), 13 deletions(-)

diff --git a/test/recv-msgall.c b/test/recv-msgall.c
index ae123e4c381b2b1a..f809834b2e427fc5 100644
--- a/test/recv-msgall.c
+++ b/test/recv-msgall.c
@@ -18,14 +18,18 @@
#define MAX_MSG 128
#define HOST "127.0.0.1"
static __be16 bind_port;
+struct recv_data {
+ pthread_mutex_t mutex;
+ int use_recvmsg;
+ struct msghdr msg;
+};

static int recv_prep(struct io_uring *ring, struct iovec *iov, int *sock,
- int use_recvmsg)
+ struct recv_data *rd)
{
struct sockaddr_in saddr;
struct io_uring_sqe *sqe;
int sockfd, ret, val;
- struct msghdr msg = { };

memset(&saddr, 0, sizeof(saddr));
saddr.sin_family = AF_INET;
@@ -47,14 +51,17 @@ static int recv_prep(struct io_uring *ring, struct iovec *iov, int *sock,
bind_port = saddr.sin_port;

sqe = io_uring_get_sqe(ring);
- if (!use_recvmsg) {
+ if (!rd->use_recvmsg) {
io_uring_prep_recv(sqe, sockfd, iov->iov_base, iov->iov_len,
MSG_WAITALL);
} else {
- msg.msg_namelen = sizeof(struct sockaddr_in);
- msg.msg_iov = iov;
- msg.msg_iovlen = 1;
- io_uring_prep_recvmsg(sqe, sockfd, &msg, MSG_WAITALL);
+ struct msghdr *msg = &rd->msg;
+
+ memset(msg, 0, sizeof(*msg));
+ msg->msg_namelen = sizeof(struct sockaddr_in);
+ msg->msg_iov = iov;
+ msg->msg_iovlen = 1;
+ io_uring_prep_recvmsg(sqe, sockfd, msg, MSG_WAITALL);
}

sqe->user_data = 2;
@@ -101,11 +108,6 @@ err:
return 1;
}

-struct recv_data {
- pthread_mutex_t mutex;
- int use_recvmsg;
-};
-
static void *recv_fn(void *data)
{
struct recv_data *rd = data;
@@ -128,7 +130,7 @@ static void *recv_fn(void *data)
goto err;
}

- ret = recv_prep(&ring, &iov, &sock, rd->use_recvmsg);
+ ret = recv_prep(&ring, &iov, &sock, rd);
if (ret) {
fprintf(stderr, "recv_prep failed: %d\n", ret);
goto err;
--
Ammar Faizi