From a6386eda9c4de125e58985b19b6028c3f868de36 Mon Sep 17 00:00:00 2001 From: Sergey Bugaev Date: Tue, 9 May 2023 00:31:05 +0300 Subject: libpipe: Fix use-after-realloc We cannot use old_buf after we realloc it, even just for subtracting it from another pointer. Instead, compute the offsets in advance. Message-Id: <20230508213136.608575-11-bugaevc@gmail.com> --- libpipe/pq.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'libpipe') diff --git a/libpipe/pq.c b/libpipe/pq.c index af380274..fff03e67 100644 --- a/libpipe/pq.c +++ b/libpipe/pq.c @@ -193,20 +193,21 @@ packet_extend (struct packet *packet, size_t new_len) /* A malloc'd packet. */ { char *new_buf; - char *old_buf = packet->buf; + ptrdiff_t start_offset = packet->buf_start - packet->buf; + ptrdiff_t end_offset = packet->buf_end - packet->buf; if (new_len >= PACKET_SIZE_LARGE) /* The old packet length is malloc'd, but we want to vm_allocate the new length, so we'd have to copy the old contents. */ return 0; - new_buf = realloc (old_buf, new_len); + new_buf = realloc (packet->buf, new_len); if (! new_buf) return 0; packet->buf = new_buf; - packet->buf_start = new_buf + (packet->buf_start - old_buf); - packet->buf_end = new_buf + (packet->buf_end - old_buf); + packet->buf_start = new_buf + start_offset; + packet->buf_end = new_buf + end_offset; } packet->buf_len = new_len; -- cgit v1.2.3