From ae34b68e3ae476c26afb17a6dad577d4b87ff672 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Barnab=C3=A1s=20P=C5=91cze?= Date: Thu, 16 Jun 2022 19:59:30 +0200 Subject: [PATCH] pulse-server: message: improve resizing logic As Coverity points out, `ensure_size()` is not fully correct. Let us assume that the message already has some allocated storage, and the `realloc()` call in the next `ensure_size()` invocation fails. In that case `message::data` is freed, but the pointer is left behind. If another `ensure_size()` call is made, then `realloc()` will be called (since the previous call left `message::allocated` as zero), but the first argument of the `realloc()` call will be a dangling pointer. In order to avoid the above, first of all, clear `message::data` after a failed `realloc()` call, and immediately return `-ENOMEM` if `message::length` is greater than `message::allocated` since that signals if the message has even run into an out-of-memory situation. --- src/modules/module-protocol-pulse/message.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/modules/module-protocol-pulse/message.c b/src/modules/module-protocol-pulse/message.c index a362f28f5..e70b03a2b 100644 --- a/src/modules/module-protocol-pulse/message.c +++ b/src/modules/module-protocol-pulse/message.c @@ -390,6 +390,9 @@ static int ensure_size(struct message *m, uint32_t size) uint32_t alloc, diff; void *data; + if (m->length > m->allocated) + return -ENOMEM; + if (m->length + size <= m->allocated) return size; @@ -397,6 +400,7 @@ static int ensure_size(struct message *m, uint32_t size) diff = alloc - m->allocated; if ((data = realloc(m->data, alloc)) == NULL) { free(m->data); + m->data = NULL; m->impl->stat.allocated -= m->allocated; m->allocated = 0; return -errno;